content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:2.0.50727.3603
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace ClearCanvas.Common {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "9.0.0.0")]
internal sealed partial class ProductSettings : global::System.Configuration.ApplicationSettingsBase {
private static ProductSettings defaultInstance = ((ProductSettings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new ProductSettings())));
public static ProductSettings Default {
get {
return defaultInstance;
}
}
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("jL55pMp+3yM7A6LSOywdX1oRfRZd9RvJ")]
public string Name {
get {
return ((string)(this["Name"]));
}
}
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("")]
public string Version {
get {
return ((string)(this["Version"]));
}
}
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("vKfTr+ue1fm9jaIYbfkY5g==")]
public string VersionSuffix {
get {
return ((string)(this["VersionSuffix"]));
}
}
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("SQpazixeCBBvq0bzF3/Un/1Jj+VVYb1ASJnvtW5wOq0MkD6q0e5fsBbTSf/1f3YmOupFw9rtXbA=")]
public string Copyright {
get {
return ((string)(this["Copyright"]));
}
}
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("SQpazixeCBD4G1zRA+eXWoOkhHpv4j+3ZFb8u6nTqdHUCrHs03TmjVNqz3nFBQnQrGTwhxAjmuQ2KUyxV" +
"mBfbg/hLi3m8r0bYKXa9a6foVJlnsKNIF+G9nRcvoS/pdxl06SqZSVpXXPoo8P+nHoZtOSwu/rZQ+O7g" +
"ZBp2NfiRVvUu+/Sf+jfe+s2Gey9zZNv28ef2/DfG5P7MtZOrs0YUn6l6ypji7hM6Uobeh0b83fWi1VF0" +
"SiuUqtxmlJXlwaCKXLY+hzItghHh8w/D/nOvL1fMtuTc3nqAcPurWNpJ49wp6gRMZulCfiJaT7/6QR0G" +
"imZhkIGUYDioGYgg/125UkflJ1URvkAIrGBmEDABT0nMocYNfVQwi9Uk+BCwPiYInCmHtb9g8RG8Y9Ey" +
"g+vhvtPgggiy0/oIFeaAv1IILMYheeXkT3+cIRiggptUm1W4Sb9OHfEWm4AlaQWc5usJzxBsF6gNAYgP" +
"xw0xyx+Wayiu+NEPT63XEsMQfhUS1cviALvlPp0qi1Ly9aArwtL3VoHaHXvAdU7b3Tf992f3NA+gDZZT" +
"ft74DqLZLD0HfP6n4b0uX/hbIBCIn9jzEIS9Nuo03LIUEBC/U/HjiU05Iyx2k+vXZp7NBfI4Wb1aI857" +
"tLb5oO4Fefmz+G5z+m9XPWgFtWLKosLnt3FrKWizjTVOqkqeadjHGy+8kjlzVHkaBOz2xYqglb3kMO4i" +
"bmrbEnowwB/87OPySVktJ5+Tud14Lw+WdpL0AFFKB7CdEHE5gfo7xQfhtfHTtHYVZoe1fgsOZnVe5f4f" +
"p8G9ZoY/D0AEdMMQ06w1A1fTeuuAbjZHmlr9pleeKWlh4us+RMDfy43WC3AX5osQ8mKCEosNj1oJL+uw" +
"qxp9aXY2x3hGGu53LzyNb8vcJpxAiVfiOrSkjTYVKOtqAkq7B/P5UiNhv9+57hf4m1ZNJjcrfTiXfvrv" +
"NKipUG2YZABiqRGS4rDczxLKs9u9XUKRG4TmQCdYMqZSqr9TXeT4LSocf76ehOmXaJ294NZqQIULqpQM" +
"x5/06CEpGU4mrASjd+Fyb/E8ClK8z1pGeXN0M83zfhYNSTF7O6eYJ7gPGuZCQO++HrfgUF1gqrqe9seS" +
"YDAKaaPeu+UKJe/MCv9833ptWsNqrVSqdQBEfcAJNCFguHftmwctrBVKu/x9g6XLAzOHq9yTB3cxZUGN" +
"293TX3pzvOf+5xogCZxflYNRD88odHbHNawlVuRyo2Q0WVK4x9qubg6v6Ao3FW+aOPCK6EN19igUwVQ0" +
"F9FIw0T8pEZgKQ2E0RwDcSXJz6m1IPv/H0/eH2FkNkhy3MUYGZ5kot8QmpKP+zJESsyc9alUVG1evwwG" +
"9M1JD/p3v3/kbgKihVPumOI2z+X5YqHSFpqbQWhTaX8pLFK9G1v4Tm7H+7vX5696IH9QEV1jXWY5qQBA" +
"fcI9EMZkt/K6km4IqqA2Hq9KucIJG9Gha65UG97Q1QCoN9hSKJifYdcgxIuQRXvDb+ua+sqVWxlJQxrt" +
"o41eaNblaSqjnRorNTzlDGg3Pn+ioMrjdThXlSizH7URFNrTylppNvEWvn/pTfoP5LC3JF0A1tKEw/KD" +
"RubJ2uhhnpj8Hg3+8MF+YMoCCIPW5qAZbzaZIBYI16E9FNKagDHa+6kAY4x55ZNxCKAZBDDqNqI08A6v" +
"ASS9RACxmyoBaDIzu0YJPf26d5LyrMqxU05/w3Y4pcAMvtTlbqaiofy335PaO3eohGjwd91AUcdlPnYZ" +
"GSHvv8xEjuhhRKOb9P6B9ZCDg5CE5AGpdhhhazgFRI+hMEMVBPPkcti4rZNS1zpe85toks1rinv2uTQW" +
"GYJgk8ebBxM4WskpAf18KJarFre6/PpFBxUvIqWkCwysQ5OU3oQrrW7zBfHp6rVVFB54cL/UILt8vn78" +
"WRIHFBlGmSPaJlQ0H2ua/l2o1gpjw6uKEVO3s8ZXroTKbcD89KkaT5HtIqPL3AB3oDaszvbzw2L22mXv" +
"L05QhXudrzPEC20yZ7/NcIuQroam+MKWUoL5QeqCwwmk3fV4d4qchFygq9Fj921QRoe4Q==")]
public string License {
get {
return ((string)(this["License"]));
}
}
}
}
| 57.525773 | 168 | 0.683513 | [
"Apache-2.0"
] | econmed/ImageServer20 | Common/ProductSettings.Designer.cs | 5,582 | C# |
using System;
using System.Collections.Generic;
namespace FoundationStandard.ObjectHydrator.Tests.POCOs
{
public enum CustomerType
{
Lead,
Prospect,
Active,
Inactive
}
public class ComplexCustomer
{
public ComplexCustomer()
{
}
public int Id { get; private set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Company { get; set; }
public string Description { get; set; }
public int Locations { get; set; }
public DateTime IncorporatedOn { get; set; }
public Double Revenue { get; set; }
public Address WorkAddress { get; set; }
public Address HomeAddress { get; set; }
public IList<Address> Addresses { get; set; }
public string HomePhone { get; set; }
public string WorkPhone { get; set; }
public string[] PhoneNumbers { get; set; }
public CustomerType Type { get; set; }
}
}
| 23.636364 | 55 | 0.581731 | [
"Apache-2.0"
] | PrintsCharming/FoundationStandard.ObjectHydrator | FoundationStandard.ObjectHydrator.Tests/POCOs/ComplexCustomer.cs | 1,042 | C# |
using System;
namespace MovieEntities
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
| 11.153846 | 37 | 0.655172 | [
"MIT"
] | TaleLearnCode/CL-MovesEF | Program.cs | 147 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.Network.Latest
{
/// <summary>
/// VpnConnection Resource.
/// Latest API Version: 2020-08-01.
/// </summary>
[Obsolete(@"The 'latest' version is deprecated. Please migrate to the resource in the top-level module: 'azure-native:network:VpnConnection'.")]
[AzureNativeResourceType("azure-native:network/latest:VpnConnection")]
public partial class VpnConnection : Pulumi.CustomResource
{
/// <summary>
/// Expected bandwidth in MBPS.
/// </summary>
[Output("connectionBandwidth")]
public Output<int?> ConnectionBandwidth { get; private set; } = null!;
/// <summary>
/// The connection status.
/// </summary>
[Output("connectionStatus")]
public Output<string> ConnectionStatus { get; private set; } = null!;
/// <summary>
/// DPD timeout in seconds for vpn connection.
/// </summary>
[Output("dpdTimeoutSeconds")]
public Output<int?> DpdTimeoutSeconds { get; private set; } = null!;
/// <summary>
/// Egress bytes transferred.
/// </summary>
[Output("egressBytesTransferred")]
public Output<double> EgressBytesTransferred { get; private set; } = null!;
/// <summary>
/// EnableBgp flag.
/// </summary>
[Output("enableBgp")]
public Output<bool?> EnableBgp { get; private set; } = null!;
/// <summary>
/// Enable internet security.
/// </summary>
[Output("enableInternetSecurity")]
public Output<bool?> EnableInternetSecurity { get; private set; } = null!;
/// <summary>
/// EnableBgp flag.
/// </summary>
[Output("enableRateLimiting")]
public Output<bool?> EnableRateLimiting { get; private set; } = null!;
/// <summary>
/// A unique read-only string that changes whenever the resource is updated.
/// </summary>
[Output("etag")]
public Output<string> Etag { get; private set; } = null!;
/// <summary>
/// Ingress bytes transferred.
/// </summary>
[Output("ingressBytesTransferred")]
public Output<double> IngressBytesTransferred { get; private set; } = null!;
/// <summary>
/// The IPSec Policies to be considered by this connection.
/// </summary>
[Output("ipsecPolicies")]
public Output<ImmutableArray<Outputs.IpsecPolicyResponse>> IpsecPolicies { get; private set; } = null!;
/// <summary>
/// The name of the resource that is unique within a resource group. This name can be used to access the resource.
/// </summary>
[Output("name")]
public Output<string?> Name { get; private set; } = null!;
/// <summary>
/// The provisioning state of the VPN connection resource.
/// </summary>
[Output("provisioningState")]
public Output<string> ProvisioningState { get; private set; } = null!;
/// <summary>
/// Id of the connected vpn site.
/// </summary>
[Output("remoteVpnSite")]
public Output<Outputs.SubResourceResponse?> RemoteVpnSite { get; private set; } = null!;
/// <summary>
/// The Routing Configuration indicating the associated and propagated route tables on this connection.
/// </summary>
[Output("routingConfiguration")]
public Output<Outputs.RoutingConfigurationResponse?> RoutingConfiguration { get; private set; } = null!;
/// <summary>
/// Routing weight for vpn connection.
/// </summary>
[Output("routingWeight")]
public Output<int?> RoutingWeight { get; private set; } = null!;
/// <summary>
/// SharedKey for the vpn connection.
/// </summary>
[Output("sharedKey")]
public Output<string?> SharedKey { get; private set; } = null!;
/// <summary>
/// Use local azure ip to initiate connection.
/// </summary>
[Output("useLocalAzureIpAddress")]
public Output<bool?> UseLocalAzureIpAddress { get; private set; } = null!;
/// <summary>
/// Enable policy-based traffic selectors.
/// </summary>
[Output("usePolicyBasedTrafficSelectors")]
public Output<bool?> UsePolicyBasedTrafficSelectors { get; private set; } = null!;
/// <summary>
/// Connection protocol used for this connection.
/// </summary>
[Output("vpnConnectionProtocolType")]
public Output<string?> VpnConnectionProtocolType { get; private set; } = null!;
/// <summary>
/// List of all vpn site link connections to the gateway.
/// </summary>
[Output("vpnLinkConnections")]
public Output<ImmutableArray<Outputs.VpnSiteLinkConnectionResponse>> VpnLinkConnections { get; private set; } = null!;
/// <summary>
/// Create a VpnConnection resource with the given unique name, arguments, and options.
/// </summary>
///
/// <param name="name">The unique name of the resource</param>
/// <param name="args">The arguments used to populate this resource's properties</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public VpnConnection(string name, VpnConnectionArgs args, CustomResourceOptions? options = null)
: base("azure-native:network/latest:VpnConnection", name, args ?? new VpnConnectionArgs(), MakeResourceOptions(options, ""))
{
}
private VpnConnection(string name, Input<string> id, CustomResourceOptions? options = null)
: base("azure-native:network/latest:VpnConnection", name, null, MakeResourceOptions(options, id))
{
}
private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id)
{
var defaultOptions = new CustomResourceOptions
{
Version = Utilities.Version,
Aliases =
{
new Pulumi.Alias { Type = "azure-nextgen:network/latest:VpnConnection"},
new Pulumi.Alias { Type = "azure-native:network:VpnConnection"},
new Pulumi.Alias { Type = "azure-nextgen:network:VpnConnection"},
new Pulumi.Alias { Type = "azure-native:network/v20180401:VpnConnection"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20180401:VpnConnection"},
new Pulumi.Alias { Type = "azure-native:network/v20180601:VpnConnection"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20180601:VpnConnection"},
new Pulumi.Alias { Type = "azure-native:network/v20180701:VpnConnection"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20180701:VpnConnection"},
new Pulumi.Alias { Type = "azure-native:network/v20180801:VpnConnection"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20180801:VpnConnection"},
new Pulumi.Alias { Type = "azure-native:network/v20181001:VpnConnection"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20181001:VpnConnection"},
new Pulumi.Alias { Type = "azure-native:network/v20181101:VpnConnection"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20181101:VpnConnection"},
new Pulumi.Alias { Type = "azure-native:network/v20181201:VpnConnection"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20181201:VpnConnection"},
new Pulumi.Alias { Type = "azure-native:network/v20190201:VpnConnection"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190201:VpnConnection"},
new Pulumi.Alias { Type = "azure-native:network/v20190401:VpnConnection"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190401:VpnConnection"},
new Pulumi.Alias { Type = "azure-native:network/v20190601:VpnConnection"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190601:VpnConnection"},
new Pulumi.Alias { Type = "azure-native:network/v20190701:VpnConnection"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190701:VpnConnection"},
new Pulumi.Alias { Type = "azure-native:network/v20190801:VpnConnection"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190801:VpnConnection"},
new Pulumi.Alias { Type = "azure-native:network/v20190901:VpnConnection"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190901:VpnConnection"},
new Pulumi.Alias { Type = "azure-native:network/v20191101:VpnConnection"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20191101:VpnConnection"},
new Pulumi.Alias { Type = "azure-native:network/v20191201:VpnConnection"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20191201:VpnConnection"},
new Pulumi.Alias { Type = "azure-native:network/v20200301:VpnConnection"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200301:VpnConnection"},
new Pulumi.Alias { Type = "azure-native:network/v20200401:VpnConnection"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200401:VpnConnection"},
new Pulumi.Alias { Type = "azure-native:network/v20200501:VpnConnection"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200501:VpnConnection"},
new Pulumi.Alias { Type = "azure-native:network/v20200601:VpnConnection"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200601:VpnConnection"},
new Pulumi.Alias { Type = "azure-native:network/v20200701:VpnConnection"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200701:VpnConnection"},
new Pulumi.Alias { Type = "azure-native:network/v20200801:VpnConnection"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200801:VpnConnection"},
},
};
var merged = CustomResourceOptions.Merge(defaultOptions, options);
// Override the ID if one was specified for consistency with other language SDKs.
merged.Id = id ?? merged.Id;
return merged;
}
/// <summary>
/// Get an existing VpnConnection resource's state with the given name, ID, and optional extra
/// properties used to qualify the lookup.
/// </summary>
///
/// <param name="name">The unique name of the resulting resource.</param>
/// <param name="id">The unique provider ID of the resource to lookup.</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public static VpnConnection Get(string name, Input<string> id, CustomResourceOptions? options = null)
{
return new VpnConnection(name, id, options);
}
}
public sealed class VpnConnectionArgs : Pulumi.ResourceArgs
{
/// <summary>
/// Expected bandwidth in MBPS.
/// </summary>
[Input("connectionBandwidth")]
public Input<int>? ConnectionBandwidth { get; set; }
/// <summary>
/// The name of the connection.
/// </summary>
[Input("connectionName")]
public Input<string>? ConnectionName { get; set; }
/// <summary>
/// DPD timeout in seconds for vpn connection.
/// </summary>
[Input("dpdTimeoutSeconds")]
public Input<int>? DpdTimeoutSeconds { get; set; }
/// <summary>
/// EnableBgp flag.
/// </summary>
[Input("enableBgp")]
public Input<bool>? EnableBgp { get; set; }
/// <summary>
/// Enable internet security.
/// </summary>
[Input("enableInternetSecurity")]
public Input<bool>? EnableInternetSecurity { get; set; }
/// <summary>
/// EnableBgp flag.
/// </summary>
[Input("enableRateLimiting")]
public Input<bool>? EnableRateLimiting { get; set; }
/// <summary>
/// The name of the gateway.
/// </summary>
[Input("gatewayName", required: true)]
public Input<string> GatewayName { get; set; } = null!;
/// <summary>
/// Resource ID.
/// </summary>
[Input("id")]
public Input<string>? Id { get; set; }
[Input("ipsecPolicies")]
private InputList<Inputs.IpsecPolicyArgs>? _ipsecPolicies;
/// <summary>
/// The IPSec Policies to be considered by this connection.
/// </summary>
public InputList<Inputs.IpsecPolicyArgs> IpsecPolicies
{
get => _ipsecPolicies ?? (_ipsecPolicies = new InputList<Inputs.IpsecPolicyArgs>());
set => _ipsecPolicies = value;
}
/// <summary>
/// The name of the resource that is unique within a resource group. This name can be used to access the resource.
/// </summary>
[Input("name")]
public Input<string>? Name { get; set; }
/// <summary>
/// Id of the connected vpn site.
/// </summary>
[Input("remoteVpnSite")]
public Input<Inputs.SubResourceArgs>? RemoteVpnSite { get; set; }
/// <summary>
/// The resource group name of the VpnGateway.
/// </summary>
[Input("resourceGroupName", required: true)]
public Input<string> ResourceGroupName { get; set; } = null!;
/// <summary>
/// The Routing Configuration indicating the associated and propagated route tables on this connection.
/// </summary>
[Input("routingConfiguration")]
public Input<Inputs.RoutingConfigurationArgs>? RoutingConfiguration { get; set; }
/// <summary>
/// Routing weight for vpn connection.
/// </summary>
[Input("routingWeight")]
public Input<int>? RoutingWeight { get; set; }
/// <summary>
/// SharedKey for the vpn connection.
/// </summary>
[Input("sharedKey")]
public Input<string>? SharedKey { get; set; }
/// <summary>
/// Use local azure ip to initiate connection.
/// </summary>
[Input("useLocalAzureIpAddress")]
public Input<bool>? UseLocalAzureIpAddress { get; set; }
/// <summary>
/// Enable policy-based traffic selectors.
/// </summary>
[Input("usePolicyBasedTrafficSelectors")]
public Input<bool>? UsePolicyBasedTrafficSelectors { get; set; }
/// <summary>
/// Connection protocol used for this connection.
/// </summary>
[Input("vpnConnectionProtocolType")]
public InputUnion<string, Pulumi.AzureNative.Network.Latest.VirtualNetworkGatewayConnectionProtocol>? VpnConnectionProtocolType { get; set; }
[Input("vpnLinkConnections")]
private InputList<Inputs.VpnSiteLinkConnectionArgs>? _vpnLinkConnections;
/// <summary>
/// List of all vpn site link connections to the gateway.
/// </summary>
public InputList<Inputs.VpnSiteLinkConnectionArgs> VpnLinkConnections
{
get => _vpnLinkConnections ?? (_vpnLinkConnections = new InputList<Inputs.VpnSiteLinkConnectionArgs>());
set => _vpnLinkConnections = value;
}
public VpnConnectionArgs()
{
}
}
}
| 44.480769 | 149 | 0.59669 | [
"Apache-2.0"
] | pulumi-bot/pulumi-azure-native | sdk/dotnet/Network/Latest/VpnConnection.cs | 16,191 | C# |
#nullable disable
using System;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using HtmlAgilityPack;
using VocaDb.Model.Helpers;
namespace VocaDb.Model.Service.VideoServices
{
public class CreofugaParser : IVideoServiceParser
{
private int? ParseLength(string lengthStr)
{
if (string.IsNullOrEmpty(lengthStr))
return null;
return TimeSpan.TryParseExact(lengthStr, "mm\\:ss", CultureInfo.InvariantCulture, out TimeSpan timespan) ? (int)timespan.TotalSeconds : null;
}
private DateTime? ParseDate(string dateStr)
{
if (string.IsNullOrEmpty(dateStr))
return null;
return DateTime.TryParseExact(dateStr, "yy/MM/dd mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, out DateTime date) ? (DateTime?)date : null; // 15/10/15 21:20
}
private VideoTitleParseResult ParseDocument(HtmlDocument doc, string url)
{
var title = doc.DocumentNode.SelectSingleNode("//meta[@name = 'twitter:title']")?.Attributes["content"]?.Value;
title = !string.IsNullOrEmpty(title) ? title.Substring(0, title.Length - 1) : title;
var thumb = doc.DocumentNode.SelectSingleNode("//meta[@name = 'twitter:image']")?.Attributes["content"]?.Value;
var length = ParseLength(doc.DocumentNode.SelectSingleNode("//p[contains(@class, 'dummy_current_time_label')]")?.InnerText.Trim());
var date = ParseDate(doc.DocumentNode.SelectSingleNode("//div[@class = 'audio-main-content-info-heading']")?.InnerText);
var author = doc.DocumentNode.SelectSingleNode("//a[@class = 'user-info-icon']")?.Attributes["title"]?.Value; // <a class="user-info-icon" title="ERIGON" href="/erigon">
return VideoTitleParseResult.CreateSuccess(title, author, null, thumb, length, uploadDate: date);
}
private VideoTitleParseResult ParseByHtmlStream(Stream htmlStream, Encoding encoding, string url)
{
var doc = new HtmlDocument();
doc.Load(htmlStream, encoding);
return ParseDocument(doc, url);
}
public Task<VideoTitleParseResult> GetTitleAsync(string id)
{
var url = $"https://creofuga.net/audios/{id}";
return HtmlRequestHelper.GetStreamAsync(url, stream => ParseByHtmlStream(stream, Encoding.UTF8, url));
}
}
}
| 39.465517 | 186 | 0.721276 | [
"MIT"
] | AgFlore/vocadb | VocaDbModel/Service/VideoServices/CreofugaParser.cs | 2,289 | C# |
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Vega.Data;
namespace Vega.Migrations
{
[DbContext(typeof(VegaDbContext))]
[Migration("20170408044330_ApplyConstraints")]
partial class ApplyConstraints
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
modelBuilder
.HasAnnotation("ProductVersion", "1.1.1")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("Vega.Data.Models.Feature", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Name");
b.HasKey("Id");
b.ToTable("Features");
});
modelBuilder.Entity("Vega.Data.Models.Make", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(255);
b.HasKey("Id");
b.ToTable("Makes");
});
modelBuilder.Entity("Vega.Data.Models.Model", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int>("MakeId");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(255);
b.HasKey("Id");
b.HasIndex("MakeId");
b.ToTable("Models");
});
modelBuilder.Entity("Vega.Data.Models.Model", b =>
{
b.HasOne("Vega.Data.Models.Make", "Make")
.WithMany("Models")
.HasForeignKey("MakeId")
.OnDelete(DeleteBehavior.Cascade);
});
}
}
}
| 30.864865 | 118 | 0.461471 | [
"MIT"
] | ulnagar/Vega | Migrations/20170408044330_ApplyConstraints.Designer.cs | 2,286 | C# |
using ECS;
namespace ECSExample.GameObjectExample {
public class Main : ECSController<UnityStandardSystemRoot, UnityEntityManager> {
// Use this for initialization
protected override void Initialize() {
AddSystem<RotateObjectSystem>();
}
}
}
| 27.090909 | 85 | 0.654362 | [
"MIT"
] | Spy-Shifty/BrokenBricksECS | Example/GameObjectExample/Main.cs | 300 | C# |
using GitObjectDb;
using GitObjectDb.Git.Hooks;
using GitObjectDb.IO;
using GitObjectDb.Models;
using GitObjectDb.Models.Compare;
using GitObjectDb.Serialization;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace LibGit2Sharp
{
/// <summary>
/// A set of methods for instances of <see cref="IRepository"/>.
/// </summary>
internal static partial class IRepositoryExtensions
{
/// <summary>
/// Creates the Blob from a <see cref="StringBuilder"/>.
/// </summary>
/// <param name="repository">The repository.</param>
/// <param name="content">The content.</param>
/// <returns>New newly created Blob.</returns>
internal static Blob CreateBlob(this IRepository repository, StringBuilder content)
{
using (var stream = new StringBuilderStream(content))
{
return repository.ObjectDatabase.CreateBlob(stream);
}
}
/// <summary>
/// Creates the Blob from a <see cref="StringBuilder"/>.
/// </summary>
/// <param name="repository">The repository.</param>
/// <param name="content">The content.</param>
/// <returns>New newly created Blob.</returns>
internal static Blob CreateBlob(this IRepository repository, string content)
{
using (var stream = new MemoryStream(Encoding.Default.GetBytes(content)))
{
return repository.ObjectDatabase.CreateBlob(stream);
}
}
internal static Commit CommitChanges(this IRepository repository, ObjectRepositoryChangeCollection changes, IObjectRepositorySerializer serializer, string message, Signature author, Signature committer, GitHooks hooks, CommitOptions options = null, Commit mergeParent = null)
{
TreeDefinition definition;
Commit startCommit;
if (changes.OldRepository?.CommitId != null)
{
if (repository.Head.Tip.Id != changes.OldRepository.CommitId)
{
throw new GitObjectDbException("Changes are not based on the HEAD commit.");
}
startCommit = repository.Lookup<Commit>(changes.OldRepository.CommitId);
definition = TreeDefinition.From(startCommit);
}
else if (repository.Info.IsHeadUnborn)
{
startCommit = null;
definition = new TreeDefinition();
}
else
{
throw new GitObjectDbException("Changes are not based on the HEAD commit.");
}
if (!hooks.OnCommitStarted(changes, message))
{
return null;
}
repository.UpdateTreeDefinition(changes, definition, serializer, startCommit);
var result = Commit(repository, definition, message, author, committer, options, mergeParent);
hooks.OnCommitCompleted(changes, message, result.Id);
return result;
}
internal static void UpdateTreeDefinition(this IRepository repository, ObjectRepositoryChangeCollection changes, TreeDefinition definition, IObjectRepositorySerializer serializer, Commit oldCommit = null)
{
if (repository == null)
{
throw new ArgumentNullException(nameof(repository));
}
if (definition == null)
{
throw new ArgumentNullException(nameof(definition));
}
UpdateChangeTreeDefinitions(repository, changes.Modified, definition, serializer);
UpdateChangeTreeDefinitions(repository, changes.Added, definition, serializer);
UpdateDeletionTreeDefinitions(changes.Deleted, definition, oldCommit);
UpdateIndexTreeDefinitions(repository, changes, definition, serializer);
}
private static void UpdateChangeTreeDefinitions(IRepository repository, IEnumerable<ObjectRepositoryEntryChanges> changes, TreeDefinition definition, IObjectRepositorySerializer serializer)
{
var buffer = new StringBuilder();
foreach (var change in changes)
{
if (change.New is IObjectRepositoryIndex index)
{
// Index are managed separately
continue;
}
buffer.Clear();
var nested = serializer.Serialize(change.New, buffer);
definition.Add(change.Path, repository.CreateBlob(buffer), Mode.NonExecutableFile);
foreach (var info in nested)
{
var nestedPath = change.New.GetDataPath(info.FileName);
definition.Add(nestedPath, repository.CreateBlob(info.Data), Mode.NonExecutableFile);
}
}
}
private static void UpdateDeletionTreeDefinitions(IEnumerable<ObjectRepositoryEntryChanges> deletions, TreeDefinition definition, Commit oldCommit = null)
{
foreach (var deleted in deletions)
{
if (oldCommit == null)
{
throw new GitObjectDbException("Unexpected state: no deletion should be detected on blank commit.");
}
var folderEntry = oldCommit[deleted.Path.GetParentPath()];
if (folderEntry != null)
{
definition.Remove(folderEntry.Path);
}
}
}
private static void UpdateIndexTreeDefinitions(IRepository repository, ObjectRepositoryChangeCollection changes, TreeDefinition definition, IObjectRepositorySerializer serializer)
{
var buffer = new StringBuilder();
foreach (var index in changes.NewRepository.Indexes)
{
var fullScan = changes.Added.Any(c => c.New.Id == index.Id);
if (UpdateAndSerializerIndex(index, changes, serializer, buffer, fullScan))
{
definition.Add(index.GetDataPath(), repository.CreateBlob(buffer), Mode.NonExecutableFile);
}
}
}
private static bool UpdateAndSerializerIndex(IObjectRepositoryIndex index, ObjectRepositoryChangeCollection changes, IObjectRepositorySerializer serializer, StringBuilder buffer, bool fullScan)
{
buffer.Clear();
var binding = index.DataAccessor.ConstructorParameterBinding;
var updatedIndex = fullScan ? index.FullScan() : index.Update(changes);
if (updatedIndex == null)
{
return false;
}
var cloned = (IObjectRepositoryIndex)binding.Cloner(index,
(instance, propertyName, type, fallback) =>
propertyName == nameof(IObjectRepositoryIndex.Values) ? updatedIndex : fallback,
(childProperty, children, @new, dataAccessor) =>
throw new NotSupportedException("Index should not contain child properties."));
serializer.Serialize(cloned, buffer);
return true;
}
/// <summary>
/// Inserts a <see cref="LibGit2Sharp.Commit" /> into the object database by applying a <see cref="TreeDefinition"/>.
/// </summary>
/// <param name="repository">The repository.</param>
/// <param name="definition">The tree definition.</param>
/// <param name="message">The message.</param>
/// <param name="author">The author.</param>
/// <param name="committer">The committer.</param>
/// <param name="options">The options.</param>
/// <param name="mergeParent">The parent commit for a merge.</param>
/// <returns>The created <see cref="LibGit2Sharp.Commit" />.</returns>
internal static Commit Commit(this IRepository repository, TreeDefinition definition, string message, Signature author, Signature committer, CommitOptions options = null, Commit mergeParent = null)
{
if (options == null)
{
options = new CommitOptions();
}
var parents = RetrieveParentsOfTheCommitBeingCreated(repository, options.AmendPreviousCommit, mergeParent).ToList();
var tree = repository.ObjectDatabase.CreateTree(definition);
var commit = repository.ObjectDatabase.CreateCommit(author, committer, message, tree, parents, false);
var logMessage = commit.BuildCommitLogMessage(options.AmendPreviousCommit, repository.Info.IsHeadUnborn, parents.Count > 1);
UpdateHeadAndTerminalReference(repository, commit, logMessage);
return commit;
}
private static IEnumerable<Commit> RetrieveParentsOfTheCommitBeingCreated(IRepository repository, bool amendPreviousCommit, Commit mergeParent = null)
{
if (amendPreviousCommit)
{
return repository.Head.Tip.Parents;
}
if (repository.Info.IsHeadUnborn)
{
return Enumerable.Empty<Commit>();
}
var parents = new List<Commit> { repository.Head.Tip };
if (mergeParent != null)
{
parents.Add(mergeParent);
}
if (repository.Info.CurrentOperation == CurrentOperation.Merge)
{
throw new NotImplementedException();
}
return parents;
}
/// <summary>
/// Builds the commit log message.
/// </summary>
/// <param name="commit">The commit.</param>
/// <param name="amendPreviousCommit">if set to <c>true</c> [amend previous commit].</param>
/// <param name="isHeadOrphaned">if set to <c>true</c> [is head orphaned].</param>
/// <param name="isMergeCommit">if set to <c>true</c> [is merge commit].</param>
/// <returns>The commit log message.</returns>
internal static string BuildCommitLogMessage(this Commit commit, bool amendPreviousCommit, bool isHeadOrphaned, bool isMergeCommit)
{
var kind = string.Empty;
if (isHeadOrphaned)
{
kind = " (initial)";
}
else if (amendPreviousCommit)
{
kind = " (amend)";
}
else if (isMergeCommit)
{
kind = " (merge)";
}
return $"commit{kind}: {commit.MessageShort}";
}
/// <summary>
/// Updates the head and terminal reference.
/// </summary>
/// <param name="repository">The repository.</param>
/// <param name="commit">The commit.</param>
/// <param name="reflogMessage">The reflog message.</param>
internal static void UpdateHeadAndTerminalReference(this IRepository repository, Commit commit, string reflogMessage)
{
var reference = repository.Refs.Head;
while (true)
{
switch (reference)
{
case DirectReference direct:
repository.Refs.UpdateTarget(direct, commit.Id, reflogMessage);
return;
case SymbolicReference symRef:
reference = symRef.Target;
if (reference == null)
{
repository.Refs.Add(symRef.TargetIdentifier, commit.Id, reflogMessage);
return;
}
break;
default:
throw new NotSupportedException($"The reference type {reference?.GetType().ToString() ?? "null"} is not supported.");
}
}
}
}
} | 42.637011 | 283 | 0.583173 | [
"MIT"
] | frblondin/GitObjectDb | src/GitObjectDb/Extensions/IRepositoryExtensions.cs | 11,981 | C# |
using System;
using g3;
namespace f3
{
public class SpatialDeviceGrabBehavior : StandardInputBehavior
{
FContext context;
Func<SceneObject, bool> ObjectFilterF;
public float RotationSpeed = 1.0f;
public float TranslationSpeed = 1.0f;
public float StickMoveSpeed = 0.1f;
public delegate void GrabEventHandler(object sender, SceneObject target);
public event GrabEventHandler OnBeginGrab;
public event GrabEventHandler OnEndGrab;
public SpatialDeviceGrabBehavior(Cockpit cockpit) {
this.context = cockpit.Context;
}
public SpatialDeviceGrabBehavior(FContext context, Func<SceneObject, bool> filterF) {
this.context = context;
ObjectFilterF = filterF;
}
public override InputDevice SupportedDevices
{
get { return InputDevice.AnySpatialDevice; }
}
class GrabInfo
{
public SceneObject so;
public Frame3f startObjFW;
public Frame3f startObjRelF;
public Frame3f startHandF;
public Vector2f stickDelta;
public float RotationSpeed = 1.0f;
public float TranslationSpeed = 1.0f;
public float StickSpeed = 0.1f;
public TransformGizmoChange change; // [TODO] shouldn't be using gizmo change for this?
public GrabInfo(SceneObject so, Frame3f handF)
{
this.so = so;
this.startHandF = handF;
this.startObjFW = so.GetLocalFrame(CoordSpace.WorldCoords);
this.startObjRelF = this.startHandF.ToFrame(this.startObjFW);
this.stickDelta = Vector2f.Zero;
change = new TransformGizmoChange() {
parentSO = new WeakReference(so),
parentBefore = so.GetLocalFrame(CoordSpace.SceneCoords),
parentScaleBefore = so.GetLocalScale()
};
}
public Frame3f curHandF;
public Frame3f curHandTargetF;
public Frame3f curUseTargetF;
public void update(Frame3f handF)
{
curHandF = handF;
// [RMS] this function updates the position of object based on hand frame
// Not clear how this should work, there are lots of options...
// [1] scaled relative motion of hand inherited by object (lags ray though)
//Vector3f dt = startHandF.ToFrameP(handF.Origin);
//dt *= 10.0f;
//Frame3f fNew = new Frame3f(startObjFW);
//fNew.Origin += dt;
// [2] object stays on ray, inherits a bit of xform
// - resulting orientation is weird. works well for rotate in-place around ray,
// but up/down/left/right tilts are impossible w/o moving object
Frame3f fNew = handF.FromFrame(this.startObjRelF);
if (RotationSpeed != 1.0f) {
fNew.Rotation = Quaternionf.Slerp(startObjFW.Rotation, fNew.Rotation, RotationSpeed);
}
if (TranslationSpeed != 1.0f) {
fNew.Origin = Vector3f.Lerp(startObjFW.Origin, fNew.Origin, TranslationSpeed);
}
// [3] object stays on ray but no rotation
// - weird if you rotate left/right, because distance stays same but it
// keeps pointing in same direction
// - we have gizmo for this kind of translation.
//Frame3 fNew = handF.FromFrame(this.startObjRelF);
//fNew.Rotation = startObjFW.Rotation;
// [4] object stays in place, rotate by hand rotation
// - pretty hard to control, but would be good for approx orienting...
// - definitely needs damping!!
//Frame3 fNew = startObjFW;
//Quaternion relative = handF.Rotation * Quaternion.Inverse(startHandF.Rotation);
//fNew.Rotation = relative * fNew.Rotation;
// apply stick rotation DOESN"T WORK
//Quaternion stickY = Quaternion.AngleAxis(stickDelta[1], startHandF.X);
//fNew.Rotation = fNew.Rotation * stickY;
// shift in/out along hand-ray by Z
fNew.Origin += StickSpeed * stickDelta[1] * handF.Z * so.GetScene().GetSceneScale();
curHandTargetF = fNew;
curUseTargetF = new Frame3f(curHandTargetF);
// update so
so.SetLocalFrame(curUseTargetF, CoordSpace.WorldCoords);
}
public void complete()
{
}
}
public override CaptureRequest WantsCapture(InputState input)
{
if ((input.bLeftTriggerDown && input.bLeftShoulderPressed)
|| (input.bLeftTriggerPressed && input.bLeftShoulderDown)) {
return CaptureRequest.Begin(this, CaptureSide.Left);
} else if ((input.bRightTriggerDown && input.bRightShoulderPressed)
|| (input.bRightTriggerPressed && input.bRightShoulderDown)) {
return CaptureRequest.Begin(this, CaptureSide.Right);
} else
return CaptureRequest.Ignore;
}
public override Capture BeginCapture(InputState input, CaptureSide eSide)
{
Ray3f useRay = (eSide == CaptureSide.Left) ? input.vLeftSpatialWorldRay : input.vRightSpatialWorldRay;
SORayHit rayHit;
if (context.Scene.FindSORayIntersection(useRay, out rayHit, ObjectFilterF)) {
var tso = rayHit.hitSO;
if (tso != null) {
Frame3f handF = (eSide == CaptureSide.Left) ? input.LeftHandFrame : input.RightHandFrame;
if ( OnBeginGrab != null )
OnBeginGrab(this, tso);
return Capture.Begin(this, eSide,
new GrabInfo(tso, handF) {
RotationSpeed = this.RotationSpeed, TranslationSpeed = this.TranslationSpeed, StickSpeed = this.StickMoveSpeed } );
}
}
return Capture.Ignore;
}
Capture end_transform(CaptureData data)
{
GrabInfo gi = data.custom_data as GrabInfo;
gi.change.parentAfter = gi.so.GetLocalFrame(CoordSpace.SceneCoords);
gi.change.parentScaleAfter = gi.so.GetLocalScale();
context.Scene.History.PushChange(gi.change, true);
context.Scene.History.PushInteractionCheckpoint();
return Capture.End;
}
public override Capture UpdateCapture(InputState input, CaptureData data)
{
GrabInfo gi = data.custom_data as GrabInfo;
bool bFinished = false;
if (data.which == CaptureSide.Left && (input.bLeftShoulderReleased || input.bLeftTriggerReleased)) {
bFinished = true;
} else if (data.which == CaptureSide.Right && (input.bRightShoulderReleased || input.bRightTriggerReleased)) {
bFinished = true;
}
if ( bFinished ) {
gi.complete();
Capture result = end_transform(data);
if ( OnEndGrab != null )
OnEndGrab(this, gi.so);
return result;
}
Frame3f handF = (data.which == CaptureSide.Left) ? input.LeftHandFrame : input.RightHandFrame;
gi.stickDelta += (data.which == CaptureSide.Left) ? input.vLeftStickDelta2D : input.vRightStickDelta2D;
gi.update(handF);
// drop-a-copy on X/A button release
if ( (data.which == CaptureSide.Left && input.bXButtonReleased) ||
(data.which == CaptureSide.Right && input.bAButtonReleased ) ) {
SceneObject copy = gi.so.Duplicate();
// save an undo-point for the current xform, and start a new one. That way we can
// step between drop-a-copy stages
end_transform(data);
gi.change = new TransformGizmoChange() {
parentSO = new WeakReference(gi.so),
parentBefore = gi.so.GetLocalFrame(CoordSpace.SceneCoords),
parentScaleBefore = gi.so.GetLocalScale()
};
// if we do this afterwards, and don't push an interaction state, then when
// we undo/redo we don't end up sitting on top of a duplicate.
context.Scene.History.PushChange(
new AddSOChange() { scene = context.Scene, so = copy, bKeepWorldPosition = false });
}
return Capture.Continue;
}
public override Capture ForceEndCapture(InputState input, CaptureData data)
{
GrabInfo gi = data.custom_data as GrabInfo;
gi.complete();
return end_transform(data);
}
}
}
| 40.50885 | 143 | 0.565265 | [
"MIT"
] | Elevator89/frame3Sharp | behaviors/SpatialDeviceGrabBehavior.cs | 9,157 | C# |
namespace Amazon.Kms
{
public sealed class CreateAliasRequest : KmsRequest
{
public CreateAliasRequest(string targetKeyId, string aliasName)
{
TargetKeyId = targetKeyId;
AliasName = aliasName;
}
public string TargetKeyId { get; }
public string AliasName { get; }
}
} | 24.333333 | 72 | 0.572603 | [
"MIT"
] | JTOne123/Amazon | src/Amazon.Kms/Actions/CreateAliasRequest.cs | 367 | C# |
using System;
using System.Collections.Concurrent;
using System.Reflection;
namespace KidsToyHive.Domain.Common
{
public static class DotNetTypeMapper
{
private static readonly ConcurrentDictionary<string, string> _types = new ConcurrentDictionary<string, string>();
static DotNetTypeMapper()
{
foreach (var type in typeof(DotNetTypeMapper).GetTypeInfo().Assembly.GetTypes())
{
if (type.AssemblyQualifiedName.Contains("+Request"))
_types.TryAdd(type.DeclaringType.Name, type.AssemblyQualifiedName);
}
}
public static string Map(string key)
{
_types.TryGetValue(key, out string value);
return value;
}
}
}
| 27.928571 | 121 | 0.620205 | [
"MIT"
] | QuinntyneBrown/KidsToyHive | src/KidsToyHive.Domain/Common/DotNetTypeMapper.cs | 784 | C# |
//using SendGrid.Helpers.Mail;
//using System;
//using System.Collections.Generic;
//using System.Linq;
//using System.Web;
//namespace GymApplication.Models.GymTracking
//{
// public class AppointmentConfirmEmail
// {
// //overload with what you want to show in the email.
// public void SendConfirmation(string Email, string FullName, DateTime Date,DateTime Time, string Slot, string Teacher)
// {
// try
// {
// var myMessage = new SendGridMessage
// {
// From = new EmailAddress("Appointments@InnovtechAcademy.co.za", "Innovtech Academy")
// };
// myMessage.AddTo(Email);
// string subject = "Appointment outcome";
// string body = (
// "Dear " + FullName + "" + "<br/>"
// + "<br/>"
// + "Your appointment has been successfully scheduled, your appointment details are as follows: "
// + "<br/>" + "" + "" + "Appointment with"+"" + Teacher + ""
// + "<br/>" + "Date:" + "" + Date.ToString("dd-MM-yyyy-dddd") + ""
// + "<br/>" + "" + "" + " Session:" + "" + Slot + ""
// + "<br/>" + "" + "" + " Which starts at:" + "" + Time.ToString("HH:mm") + ""
// + "<br/>" + "Please note the duration of meetings is 15 minutes." +""
// + "<br/>" + "Ensure to keep this information as your proof of appointment" +
// "<br/>" +
// "Sincerely Yours, " +
// "<br/>" +
// "Innovtech Academy");
// myMessage.Subject = subject;
// myMessage.HtmlContent = body;
// var transportWeb = new
// SendGrid.SendGridClient("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");
// transportWeb.SendEmailAsync(myMessage);
// }
// catch (Exception x)
// {
// Console.WriteLine(x);
// }
// }
// }
//} | 43.673469 | 128 | 0.470561 | [
"Apache-2.0"
] | SphamandlaK/Gym-Application | Controllers/GymTracking/AppointmentConfirmEmail.cs | 2,142 | C# |
using SpiceSharp.Algebra;
using SpiceSharp.ParameterSets;
using System;
using System.Collections.Generic;
namespace SpiceSharp.Components.ParallelComponents
{
/// <summary>
/// An <see cref="ISparseSolver{T}"/> that only allows direct access to an element once. All subsequent calls will be
/// through a local element.
/// </summary>
/// <typeparam name="T">The value type.</typeparam>
/// <seealso cref="ISparseSolver{T}" />
public partial class ParallelSolver<T> : ISparsePivotingSolver<T>
{
private readonly ISparsePivotingSolver<T> _parent;
private readonly HashSet<MatrixLocation> _sharedMatrixElements = new HashSet<MatrixLocation>();
private readonly HashSet<int> _sharedVectorElements = new HashSet<int>();
private readonly List<BridgeElement> _bridgeElements = new List<BridgeElement>();
/// <inheritdoc/>
P IParameterSetCollection.GetParameterSet<P>() => _parent.GetParameterSet<P>();
/// <inheritdoc/>
bool IParameterSetCollection.TryGetParameterSet<P>(out P value) => _parent.TryGetParameterSet(out value);
/// <inheritdoc/>
IEnumerable<IParameterSet> IParameterSetCollection.ParameterSets => _parent.ParameterSets;
/// <inheritdoc/>
/// <exception cref="ArgumentException">Thrown when trying to write in a parallel solver.</exception>
public int Degeneracy { get => _parent.Degeneracy; set => throw new ArgumentException(Properties.Resources.Parallel_AccessNotSupported.FormatString(nameof(Degeneracy))); }
/// <inheritdoc/>
/// <exception cref="ArgumentException">Thrown when trying to write in a parallel solver.</exception>
public int PivotSearchReduction { get => _parent.PivotSearchReduction; set => throw new ArgumentException(Properties.Resources.Parallel_AccessNotSupported.FormatString(nameof(PivotSearchReduction))); }
/// <inheritdoc/>
/// <exception cref="ArgumentException">Thrown when trying to write in a parallel solver.</exception>
public bool NeedsReordering { get => _parent.NeedsReordering; set => throw new ArgumentException(Properties.Resources.Parallel_AccessNotSupported.FormatString(nameof(NeedsReordering))); }
/// <inheritdoc/>
public bool IsFactored => _parent.IsFactored;
/// <inheritdoc/>
T ISolver<T>.this[int row, int column]
{
get => _parent[row, column];
set => throw new ArgumentException(Properties.Resources.Parallel_AccessNotSupported.FormatString("this[row, column]"));
}
/// <inheritdoc/>
T ISolver<T>.this[MatrixLocation location]
{
get => _parent[location];
set => throw new ArgumentException(Properties.Resources.Parallel_AccessNotSupported.FormatString("this[location]"));
}
/// <inheritdoc/>
T ISolver<T>.this[int row]
{
get => _parent[row];
set => throw new ArgumentException(Properties.Resources.Parallel_AccessNotSupported.FormatString("this[row]"));
}
/// <inheritdoc/>
public int Size => _parent.Size;
/// <summary>
/// Initializes a new instance of the <see cref="ParallelSolver{T}"/> class.
/// </summary>
/// <param name="parent">The parent.</param>
public ParallelSolver(ISparsePivotingSolver<T> parent)
{
_parent = parent.ThrowIfNull(nameof(parent));
}
/// <inheritdoc/>
void IPivotingSolver<ISparseMatrix<T>, ISparseVector<T>, T>.Precondition(PreconditioningMethod<ISparseMatrix<T>, ISparseVector<T>, T> method)
=> throw new ArgumentException(Properties.Resources.Parallel_AccessNotSupported.FormatString(nameof(IPivotingSolver<ISparseMatrix<T>, ISparseVector<T>, T>.Precondition)));
/// <inheritdoc/>
void ISolver<T>.Clear()
{
_sharedMatrixElements.Clear();
_bridgeElements.Clear();
}
/// <inheritdoc/>
bool ISolver<T>.Factor()
=> throw new SpiceSharpException(Properties.Resources.Parallel_AccessNotSupported.FormatString(nameof(ISolver<T>.Factor)));
/// <inheritdoc/>
int IPivotingSolver<ISparseMatrix<T>, ISparseVector<T>, T>.OrderAndFactor()
=> throw new SpiceSharpException(Properties.Resources.Parallel_AccessNotSupported.FormatString(nameof(IPivotingSolver<ISparseMatrix<T>, ISparseVector<T>, T>.OrderAndFactor)));
/// <inheritdoc/>
public Element<T> FindElement(MatrixLocation location)
{
var elt = _parent.FindElement(location);
if (elt == null)
return null;
if (_sharedMatrixElements.Contains(location))
{
// We only allow one reference to an element
var bridge = new BridgeElement(elt);
_bridgeElements.Add(bridge);
return bridge;
}
else
_sharedMatrixElements.Add(location);
return elt;
}
/// <inheritdoc/>
public Element<T> FindElement(int row)
{
var elt = _parent.FindElement(row);
if (elt == null)
return null;
if (_sharedVectorElements.Contains(row))
{
var bridge = new BridgeElement(elt);
_bridgeElements.Add(bridge);
return bridge;
}
else
_sharedVectorElements.Add(row);
return elt;
}
/// <inheritdoc/>
public Element<T> GetElement(MatrixLocation location)
{
var elt = _parent.GetElement(location);
if (_sharedMatrixElements.Contains(location))
{
var bridge = new BridgeElement(elt);
_bridgeElements.Add(bridge);
return bridge;
}
else
_sharedMatrixElements.Add(location);
return elt;
}
/// <inheritdoc/>
public bool RemoveElement(MatrixLocation location) =>
throw new SpiceSharpException(Properties.Resources.Parallel_AccessNotSupported.FormatString(nameof(IPivotingSolver<ISparseMatrix<T>, ISparseVector<T>, T>.OrderAndFactor)));
/// <inheritdoc/>
public Element<T> GetElement(int row)
{
var elt = _parent.GetElement(row);
if (_sharedVectorElements.Contains(row))
{
var bridge = new BridgeElement(elt);
_bridgeElements.Add(bridge);
return bridge;
}
else
_sharedVectorElements.Add(row);
return elt;
}
/// <inheritdoc/>
public bool RemoveElement(int index)
=> throw new SpiceSharpException(Properties.Resources.Parallel_AccessNotSupported.FormatString(nameof(IPivotingSolver<ISparseMatrix<T>, ISparseVector<T>, T>.OrderAndFactor)));
/// <summary>
/// Clears all matrix and vector elements.
/// </summary>
public void Reset()
{
foreach (var bridge in _bridgeElements)
bridge.Value = default;
}
/// <inheritdoc/>
void ISolver<T>.Solve(IVector<T> solution)
=> throw new SpiceSharpException(Properties.Resources.Parallel_AccessNotSupported.FormatString(nameof(ISolver<T>.Solve)));
/// <inheritdoc/>
void ISolver<T>.SolveTransposed(IVector<T> solution)
=> throw new SpiceSharpException(Properties.Resources.Parallel_AccessNotSupported.FormatString(nameof(ISolver<T>.SolveTransposed)));
/// <inheritdoc/>
MatrixLocation IPivotingSolver<ISparseMatrix<T>, ISparseVector<T>, T>.InternalToExternal(MatrixLocation location)
=> _parent.InternalToExternal(location);
/// <inheritdoc/>
MatrixLocation IPivotingSolver<ISparseMatrix<T>, ISparseVector<T>, T>.ExternalToInternal(MatrixLocation location)
=> _parent.ExternalToInternal(location);
/// <summary>
/// Applies all bridge elements.
/// </summary>
public void Apply()
{
foreach (var bridge in _bridgeElements)
bridge.Apply();
}
/// <inheritdoc/>
public void SetParameter<P>(string name, P value) => _parent.SetParameter(name, value);
/// <inheritdoc/>
public bool TrySetParameter<P>(string name, P value) => _parent.TrySetParameter(name, value);
/// <inheritdoc/>
public P GetProperty<P>(string name) => _parent.GetProperty<P>(name);
/// <inheritdoc/>
public bool TryGetProperty<P>(string name, out P value) => _parent.TryGetProperty(name, out value);
/// <inheritdoc/>
public Action<P> CreateParameterSetter<P>(string name) => _parent.CreateParameterSetter<P>(name);
/// <inheritdoc/>
public Func<P> CreatePropertyGetter<P>(string name) => _parent.CreatePropertyGetter<P>(name);
}
} | 41.004505 | 209 | 0.622652 | [
"MIT"
] | Neos-Metaverse/SpiceSharp | SpiceSharp/Components/ParallelComponents/ParallelSolver.cs | 9,105 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Devx;
using Devx.DbProvider;
using WXB.Bussiness.Utils;
using WXB.Bussiness.Common;
using WXB.Bussiness.ViewModels;
namespace WXB.Bussiness.Service
{
public class ResponseStatusService
{
#region 获取最新响应状态
/// <summary>
/// 获取最新响应状态
/// </summary>
/// <returns></returns>
public ResponseStatusView GetResponseStatus()
{
string sql = @" select * from responsestatus ORDER BY ID DESC LIMIT 0,1 ";
using (var dbContext = new DbContext().ConnectionStringName(ConnectionUtil.connWXB, DbProviderTypes.MySql))
{
ResponseStatusView resVM = dbContext.Sql(sql).QuerySingle<ResponseStatusView>(reader =>
{
ResponseStatusView temp = new ResponseStatusView();
if (!string.IsNullOrEmpty(reader["ID"].ToString()))
temp.ID = reader.AsInt("ID");
if (!string.IsNullOrEmpty(reader["Status"].ToString()))
temp.Status = reader.AsInt("Status");
if (!string.IsNullOrEmpty(reader["StartTime"].ToString()))
temp.StartTime = Convert.ToDateTime(reader["StartTime"]);
if (!string.IsNullOrEmpty(reader["EndTime"].ToString()))
temp.EndTime = Convert.ToDateTime(reader["EndTime"]);
if (!string.IsNullOrEmpty(reader["InputerID"].ToString()))
temp.InputerID = reader.AsInt("InputerID");
if (!string.IsNullOrEmpty(reader["Inputer"].ToString()))
temp.Inputer = reader.AsString("InputerID");
return temp;
});
return resVM;
}
}
#endregion
#region 通过Id获取响应状态详情
/// <summary>
/// 通过Id获取响应状态详情
/// </summary>
/// <param name="responseStatusId"></param>
/// <returns></returns>
public ResponseStatusView GetResponseStatusByID(int ID)
{
string sql = string.Format(@" select * from responsestatus where ID = {0} ", ID);
using (var dbContext = new DbContext().ConnectionStringName(ConnectionUtil.connWXB, DbProviderTypes.MySql))
{
ResponseStatusView resVM = dbContext.Sql(sql).QuerySingle<ResponseStatusView>(reader =>
{
ResponseStatusView temp = new ResponseStatusView();
if (!string.IsNullOrEmpty(reader["ID"].ToString()))
temp.ID = reader.AsInt("ID");
if (!string.IsNullOrEmpty(reader["Status"].ToString()))
temp.Status = reader.AsInt("Status");
if (!string.IsNullOrEmpty(reader["StartTime"].ToString()))
temp.StartTime = Convert.ToDateTime(reader["StartTime"]);
if (!string.IsNullOrEmpty(reader["EndTime"].ToString()))
temp.EndTime = Convert.ToDateTime(reader["EndTime"]);
if (!string.IsNullOrEmpty(reader["InputerID"].ToString()))
temp.InputerID = reader.AsInt("InputerID");
if (!string.IsNullOrEmpty(reader["Inputer"].ToString()))
temp.Inputer = reader.AsString("InputerID");
return temp;
});
return resVM;
}
}
#endregion
#region 保存
/// <summary>
/// 保存
/// </summary>
/// <param name="vm"></param>
/// <returns></returns>
public ResponseStatusView SaveResponse(ResponseStatusView vm)
{
if (vm == null) return null;
using (var dbContext = new DbContext().ConnectionStringName(ConnectionUtil.connWXB, DbProviderTypes.MySql))
{
if (vm.ID.HasValue)
{
dbContext.Update("responsestatus").Column("Status", vm.Status)
.Column("StartTime", vm.StartTime)
.Column("EndTime", vm.EndTime)
.Column("Inputer", vm.Inputer)
.Column("InputerID", vm.InputerID)
.Where("ID", vm.ID.Value)
.Execute();
}
else
{
vm.ID = dbContext.Insert("responsestatus").Column("Status", vm.Status)
.Column("StartTime", vm.StartTime)
.Column("EndTime", vm.EndTime)
.Column("Inputer", vm.Inputer)
.Column("InputerID", vm.InputerID)
.ExecuteReturnLastId<int>();
}
return vm;
}
}
#endregion
}
}
| 37.859155 | 119 | 0.475074 | [
"MIT"
] | shuaiagain/mvc-wxb | Wxb2018/WXB.Bussiness/Bussiness/service/ResponseStatusService.cs | 5,458 | C# |
using CCXT.NET.Coin.Private;
using Newtonsoft.Json;
namespace CCXT.NET.Bitfinex.Private
{
/// <summary>
/// 거래소 회원 지갑 정보
/// </summary>
public class BBalanceItem : CCXT.NET.Coin.Private.BalanceItem, IBalanceItem
{
/// <summary>
///
/// </summary>
[JsonProperty(PropertyName = "currency")]
public override string currency
{
get;
set;
}
/// <summary>
///
/// </summary>
[JsonProperty(PropertyName = "available")]
public override decimal free
{
get;
set;
}
/// <summary>
///
/// </summary>
[JsonProperty(PropertyName = "amount")]
public override decimal total
{
get;
set;
}
/// <summary>
///
/// </summary>
[JsonProperty(PropertyName = "type")]
public string exchangeType
{
get;
set;
}
}
} | 20.294118 | 79 | 0.450242 | [
"MIT"
] | Lkskwlkr1/ccxt.net | src/exchanges/gbr/bitfinex/private/balance.cs | 1,055 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Moq;
using Newtonsoft.Json.Linq;
using NuGet.Configuration;
using NuGet.Protocol.Core.Types;
using NuGet.Versioning;
using Test.Utility;
using Xunit;
namespace NuGet.Protocol.Providers.Tests
{
public class RepositorySignatureResourceProviderTests
{
private const string _resourceType470 = "RepositorySignatures/4.7.0";
private const string _resourceType490 = "RepositorySignatures/4.9.0";
private const string _resourceType500 = "RepositorySignatures/5.0.0";
private const string _resourceUri470 = "https://unit.test/4.7.0";
private const string _resourceUri490 = "https://unit.test/4.9.0";
private const string _resourceUri500 = "https://unit.test/5.0.0";
private static readonly SemanticVersion _defaultVersion = new SemanticVersion(0, 0, 0);
private readonly PackageSource _packageSource;
private readonly RepositorySignatureResourceProvider _repositorySignatureResourceProvider;
public RepositorySignatureResourceProviderTests()
{
_packageSource = new PackageSource("https://unit.test");
_repositorySignatureResourceProvider = new RepositorySignatureResourceProvider();
}
[Fact]
public async Task TryCreate_WhenResourceDoesNotExist_ReturnsNoResource()
{
var resourceProviders = new ResourceProvider[]
{
CreateServiceIndexResourceV3Provider(),
_repositorySignatureResourceProvider
};
var sourceRepository = new SourceRepository(_packageSource, resourceProviders);
var result = await _repositorySignatureResourceProvider.TryCreate(sourceRepository, CancellationToken.None);
Assert.False(result.Item1);
Assert.Null(result.Item2);
}
[Theory]
[InlineData("http://unit.test/4.9.0", _resourceType490)]
[InlineData(@"\\localhost\unit\test\4.9.0", _resourceType490)]
public async Task TryCreate_WhenUrlIsInvalid_Throws(string resourceUrl, string resourceType)
{
var serviceEntry = new ServiceIndexEntry(new Uri(resourceUrl), resourceType, _defaultVersion);
var resourceProviders = new ResourceProvider[]
{
CreateServiceIndexResourceV3Provider(serviceEntry),
StaticHttpSource.CreateHttpSource(
new Dictionary<string, string>()
{
{ serviceEntry.Uri.AbsoluteUri, GetRepositorySignaturesResourceJson(resourceUrl) }
}),
_repositorySignatureResourceProvider
};
var sourceRepository = new SourceRepository(_packageSource, resourceProviders);
var exception = await Assert.ThrowsAsync<FatalProtocolException>(
() => _repositorySignatureResourceProvider.TryCreate(sourceRepository, CancellationToken.None));
Assert.Equal($"Repository Signatures resouce must be served over HTTPS. Source: {_packageSource.Source}", exception.Message);
}
[Theory]
[InlineData(_resourceUri500, _resourceType500)]
[InlineData(_resourceUri490, _resourceType490)]
[InlineData(_resourceUri470, _resourceType470)]
public async Task TryCreate_WhenOnlyOneResourceIsPresent_ReturnsThatResource(string resourceUrl, string resourceType)
{
var serviceEntry = new ServiceIndexEntry(new Uri(resourceUrl), resourceType, _defaultVersion);
var resourceProviders = new ResourceProvider[]
{
CreateServiceIndexResourceV3Provider(serviceEntry),
StaticHttpSource.CreateHttpSource(
new Dictionary<string, string>()
{
{ serviceEntry.Uri.AbsoluteUri, GetRepositorySignaturesResourceJson(resourceUrl) }
}),
_repositorySignatureResourceProvider
};
var sourceRepository = new SourceRepository(_packageSource, resourceProviders);
var result = await _repositorySignatureResourceProvider.TryCreate(sourceRepository, CancellationToken.None);
Assert.True(result.Item1);
var resource = result.Item2 as RepositorySignatureResource;
Assert.NotNull(resource);
Assert.Equal(_packageSource.Source, resource.Source);
Assert.Single(resource.RepositoryCertificateInfos);
}
[Fact]
public async Task TryCreate_WhenMultipleResourcesArePresent_Returns500Resource()
{
var serviceEntry470 = new ServiceIndexEntry(new Uri(_resourceUri470), _resourceType470, _defaultVersion);
var serviceEntry490 = new ServiceIndexEntry(new Uri(_resourceUri490), _resourceType490, _defaultVersion);
var serviceEntry500 = new ServiceIndexEntry(new Uri(_resourceUri500), _resourceType500, _defaultVersion);
var resourceProviders = new ResourceProvider[]
{
CreateServiceIndexResourceV3Provider(serviceEntry470, serviceEntry490, serviceEntry500),
StaticHttpSource.CreateHttpSource(
new Dictionary<string, string>()
{
{ serviceEntry470.Uri.AbsoluteUri, GetRepositorySignaturesResourceJson(serviceEntry470.Uri.AbsoluteUri) },
{ serviceEntry490.Uri.AbsoluteUri, GetRepositorySignaturesResourceJson(serviceEntry490.Uri.AbsoluteUri) },
{ serviceEntry500.Uri.AbsoluteUri, GetRepositorySignaturesResourceJson(serviceEntry500.Uri.AbsoluteUri) }
}),
_repositorySignatureResourceProvider
};
var sourceRepository = new SourceRepository(_packageSource, resourceProviders);
var result = await _repositorySignatureResourceProvider.TryCreate(sourceRepository, CancellationToken.None);
Assert.True(result.Item1);
var resource = result.Item2 as RepositorySignatureResource;
Assert.NotNull(resource);
Assert.Equal(_packageSource.Source, resource.Source);
Assert.Single(resource.RepositoryCertificateInfos);
Assert.StartsWith(serviceEntry500.Uri.AbsoluteUri, resource.RepositoryCertificateInfos.Single().ContentUrl);
}
[Theory]
[InlineData(_resourceUri500, _resourceType500, "repository_signatures_5.0.0")]
[InlineData(_resourceUri490, _resourceType490, "repository_signatures_4.9.0")]
[InlineData(_resourceUri470, _resourceType470, "repository_signatures_4.7.0")]
public async Task TryCreate_WhenResourceIsPresent_CreatesVersionedHttpCacheEntry(string resourceUrl, string resourceType, string expectedCacheKey)
{
var serviceEntry = new ServiceIndexEntry(new Uri(resourceUrl), resourceType, _defaultVersion);
var responses = new Dictionary<string, string>()
{
{ serviceEntry.Uri.AbsoluteUri, GetRepositorySignaturesResourceJson(resourceUrl) }
};
var httpSource = new TestHttpSource(_packageSource, responses);
var resourceProviders = new ResourceProvider[]
{
CreateServiceIndexResourceV3Provider(serviceEntry),
StaticHttpSource.CreateHttpSource(responses, httpSource: httpSource),
_repositorySignatureResourceProvider
};
var sourceRepository = new SourceRepository(_packageSource, resourceProviders);
string actualCacheKey = null;
httpSource.HttpSourceCachedRequestInspector = request =>
{
actualCacheKey = request.CacheKey;
};
var result = await _repositorySignatureResourceProvider.TryCreate(sourceRepository, CancellationToken.None);
Assert.True(result.Item1);
Assert.Equal(expectedCacheKey, actualCacheKey);
}
private static ServiceIndexResourceV3Provider CreateServiceIndexResourceV3Provider(params ServiceIndexEntry[] entries)
{
var provider = new Mock<ServiceIndexResourceV3Provider>();
provider.Setup(x => x.Name)
.Returns(nameof(ServiceIndexResourceV3Provider));
provider.Setup(x => x.ResourceType)
.Returns(typeof(ServiceIndexResourceV3));
var resources = new JArray();
foreach (var entry in entries)
{
resources.Add(
new JObject(
new JProperty("@id", entry.Uri.AbsoluteUri),
new JProperty("@type", entry.Type)));
}
var index = new JObject();
index.Add("version", "3.0.0");
index.Add("resources", resources);
index.Add("@context",
new JObject(
new JProperty("@vocab", "http://schema.nuget.org/schema#"),
new JProperty("comment", "http://www.w3.org/2000/01/rdf-schema#comment")));
var serviceIndexResource = new ServiceIndexResourceV3(index, DateTime.UtcNow);
var tryCreateResult = new Tuple<bool, INuGetResource>(true, serviceIndexResource);
provider.Setup(x => x.TryCreate(It.IsAny<SourceRepository>(), It.IsAny<CancellationToken>()))
.Returns(Task.FromResult(tryCreateResult));
return provider.Object;
}
private static string GetRepositorySignaturesResourceJson(string resourceBaseUri)
{
var jObject = new JObject(
new JProperty("allRepositorySigned", false),
new JProperty("signingCertificates",
new JArray(
new JObject(
new JProperty("fingerprints",
new JObject(
new JProperty("2.16.840.1.101.3.4.2.1", "0e5f38f57dc1bcc806d8494f4f90fbcedd988b46760709cbeec6f4219aa6157d"))),
new JProperty("subject", "CN=NuGet.org Repository by Microsoft, O=NuGet.org Repository by Microsoft, L=Redmond, S=Washington, C=US"),
new JProperty("issuer", "CN=DigiCert SHA2 Assured ID Code Signing CA, OU=www.digicert.com, O=DigiCert Inc, C=US"),
new JProperty("notBefore", "2018-04-10T00:00:00.0000000Z"),
new JProperty("notAfter", "2021-04-14T12:00:00.0000000Z"),
new JProperty("contentUrl", $"{resourceBaseUri}/certificates/0e5f38f57dc1bcc806d8494f4f90fbcedd988b46760709cbeec6f4219aa6157d.crt")))));
return jObject.ToString();
}
}
}
| 47.939394 | 164 | 0.648998 | [
"Apache-2.0"
] | ChrisMaddock/NuGet.Client | test/NuGet.Core.Tests/NuGet.Protocol.Tests/Providers/RepositorySignatureResourceProviderTests.cs | 11,074 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNextGen.Insights.V20140401.Outputs
{
[OutputType]
public sealed class ThresholdRuleConditionResponse
{
/// <summary>
/// the resource from which the rule collects its data. For this type dataSource will always be of type RuleMetricDataSource.
/// </summary>
public readonly Union<Outputs.RuleManagementEventDataSourceResponse, Outputs.RuleMetricDataSourceResponse>? DataSource;
/// <summary>
/// specifies the type of condition. This can be one of three types: ManagementEventRuleCondition (occurrences of management events), LocationThresholdRuleCondition (based on the number of failures of a web test), and ThresholdRuleCondition (based on the threshold of a metric).
/// Expected value is 'Microsoft.Azure.Management.Insights.Models.ThresholdRuleCondition'.
/// </summary>
public readonly string OdataType;
/// <summary>
/// the operator used to compare the data and the threshold.
/// </summary>
public readonly string Operator;
/// <summary>
/// the threshold value that activates the alert.
/// </summary>
public readonly double Threshold;
/// <summary>
/// the time aggregation operator. How the data that are collected should be combined over time. The default value is the PrimaryAggregationType of the Metric.
/// </summary>
public readonly string? TimeAggregation;
/// <summary>
/// the period of time (in ISO 8601 duration format) that is used to monitor alert activity based on the threshold. If specified then it must be between 5 minutes and 1 day.
/// </summary>
public readonly string? WindowSize;
[OutputConstructor]
private ThresholdRuleConditionResponse(
Union<Outputs.RuleManagementEventDataSourceResponse, Outputs.RuleMetricDataSourceResponse>? dataSource,
string odataType,
string @operator,
double threshold,
string? timeAggregation,
string? windowSize)
{
DataSource = dataSource;
OdataType = odataType;
Operator = @operator;
Threshold = threshold;
TimeAggregation = timeAggregation;
WindowSize = windowSize;
}
}
}
| 40.923077 | 286 | 0.668045 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/Insights/V20140401/Outputs/ThresholdRuleConditionResponse.cs | 2,660 | C# |
using System;
using System.Data;
using System.Linq;
using CMS.Base.Web.UI;
using CMS.ContactManagement;
using CMS.Core;
using CMS.DataEngine;
using CMS.EventLog;
using CMS.Helpers;
using CMS.Membership;
using CMS.Newsletters;
using CMS.SiteProvider;
using CMS.UIControls;
public partial class CMSModules_Newsletters_Controls_MySubscriptions : CMSAdminControl
{
#region "Variables"
private SubscriberInfo subscriber;
private string selectorValue = string.Empty;
private string currentValues = string.Empty;
private bool mSendConfirmationEmail = true;
private UserInfo userInfo;
private int siteID;
private readonly ISubscriptionService mSubscriptionService = Service.Resolve<ISubscriptionService>();
private readonly IUnsubscriptionProvider mUnsubscriptionProvider = Service.Resolve<IUnsubscriptionProvider>();
private readonly IContactProvider mContactProvider = Service.Resolve<IContactProvider>();
#endregion
#region "Properties"
/// <summary>
/// Messages placeholder
/// </summary>
public override MessagesPlaceHolder MessagesPlaceHolder
{
get
{
return plcMess;
}
}
/// <summary>
/// Gets or sets the value that indicates whether send confirmation emails.
/// </summary>
public bool SendConfirmationEmail
{
get
{
return mSendConfirmationEmail;
}
set
{
mSendConfirmationEmail = value;
}
}
/// <summary>
/// Gets or sets the value that indicates whether this control is visible.
/// </summary>
public bool ForcedVisible
{
get
{
return plcMain.Visible;
}
set
{
plcMain.Visible = value;
}
}
/// <summary>
/// Gets or sets the value that indicates whether this control is used in other control.
/// </summary>
public bool ExternalUse
{
get;
set;
}
/// <summary>
/// Gets or sets the WebPart cache minutes.
/// </summary>
public int CacheMinutes
{
get;
set;
}
/// <summary>
/// Gets or sets current site ID.
/// </summary>
public int SiteID
{
get
{
if (siteID <= 0)
{
siteID = SiteContext.CurrentSiteID;
}
return siteID;
}
set
{
siteID = value;
}
}
/// <summary>
/// Gets or sets current user ID.
/// </summary>
public int UserID
{
get;
set;
}
/// <summary>
/// Indicates if selector control is on live site.
/// </summary>
public override bool IsLiveSite
{
get
{
return ValidationHelper.GetBoolean(GetValue("IsLiveSite"), false);
}
set
{
SetValue("IsLiveSite", value);
plcMess.IsLiveSite = value;
}
}
/// <summary>
/// Last selector value.
/// </summary>
private string SelectorValue
{
get
{
if (string.IsNullOrEmpty(selectorValue))
{
// Try to get value from hidden field
selectorValue = ValidationHelper.GetString(hdnValue.Value, string.Empty);
}
return selectorValue;
}
set
{
selectorValue = value;
}
}
#endregion
#region "Methods"
/// <summary>
/// Load data.
/// </summary>
public void LoadData()
{
if (StopProcessing)
{
// Hide control
Visible = false;
}
else
{
SetContext();
InitializeUser();
usNewsletters.WhereCondition = new WhereCondition().WhereEquals("NewsletterSiteID", SiteID).WhereEquals("NewsletterType", (int)EmailCommunicationTypeEnum.Newsletter).ToString(true);
if (IsUserIdentified())
{
usNewsletters.Visible = true;
InitializeSubscriber(userInfo, SiteID);
LoadNewslettersForSubscriber();
}
else
{
usNewsletters.Visible = false;
if ((UserID > 0) && (MembershipContext.AuthenticatedUser.UserID == UserID))
{
ShowInformation(GetString("MySubscriptions.CannotIdentify"));
}
else
{
if (!IsLiveSite)
{
// It's located in Admin/Users/Subscriptions
lblText.ResourceString = "MySubscriptions.EmailCommunicationDisabled";
}
else
{
ShowInformation(GetString("MySubscriptions.CannotIdentifyUser"));
}
}
}
ReleaseContext();
}
}
/// <summary>
/// Overridden SetValue - because of MyAccount webpart.
/// </summary>
/// <param name="propertyName">Name of the property to set</param>
/// <param name="value">Value to set</param>
public override bool SetValue(string propertyName, object value)
{
base.SetValue(propertyName, value);
switch (propertyName.ToLowerInvariant())
{
case "forcedvisible":
ForcedVisible = ValidationHelper.GetBoolean(value, false);
break;
case "externaluse":
ExternalUse = ValidationHelper.GetBoolean(value, false);
break;
case "cacheminutes":
CacheMinutes = ValidationHelper.GetInteger(value, 0);
break;
case "reloaddata":
// Special property which enables to call LoadData from MyAccount webpart
LoadData();
break;
case "userid":
UserID = ValidationHelper.GetInteger(value, 0);
break;
case "siteid":
SiteID = ValidationHelper.GetInteger(value, 0);
break;
case "sendconfirmationemail":
mSendConfirmationEmail = ValidationHelper.GetBoolean(value, true);
break;
}
return true;
}
/// <summary>
/// PageLoad.
/// </summary>
protected void Page_Load(object sender, EventArgs e)
{
usNewsletters.OnSelectionChanged += usNewsletters_OnSelectionChanged;
usNewsletters.IsLiveSite = IsLiveSite;
if (ExternalUse)
{
LoadData();
}
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
if (!IsLiveSite)
{
// It's located in Admin/Users/Subscriptions
headNewsletters.Visible = false;
lblUnsubscribeFromAll.Visible = false;
btnUsubscribeFromAll.Visible = false;
}
if (IsUserIdentified())
{
if (!IsLiveSite)
{
lblText.ResourceString = "mysubscriptions.selectorheading.thirdperson";
}
else
{
string email = GetVisitorEmail();
bool isUnsubscribedFromAll = mUnsubscriptionProvider.IsUnsubscribedFromAllNewsletters(email);
if (isUnsubscribedFromAll)
{
lblUnsubscribeFromAll.Text = GetString("mysubscriptions.unsubscribed.description");
btnUsubscribeFromAll.Text = GetString("mysubscriptions.unsubscribed.buttontext");
}
else
{
lblUnsubscribeFromAll.Text = string.Format(GetString("mysubscriptions.notunsubscribed.description"), email);
btnUsubscribeFromAll.Text = GetString("mysubscriptions.notunsubscribed.buttontext");
}
}
}
// Preserve selected values
hdnValue.Value = ValidationHelper.GetString(usNewsletters.Value, string.Empty);
}
protected void btnUnsubscribeFromAll_Click(object sender, EventArgs e)
{
if (IsUserIdentified() && IsLiveSite)
{
string email = GetVisitorEmail();
var isUnsubscribed = mUnsubscriptionProvider.IsUnsubscribedFromAllNewsletters(email);
if (!isUnsubscribed)
{
mSubscriptionService.UnsubscribeFromAllNewsletters(email);
}
else
{
mUnsubscriptionProvider.RemoveUnsubscriptionsFromAllNewsletters(email);
}
}
}
private void usNewsletters_OnSelectionChanged(object sender, EventArgs e)
{
if (RaiseOnCheckPermissions("ManageSubscribers", this))
{
if (StopProcessing)
{
return;
}
}
// Remove old items
string newValues = ValidationHelper.GetString(usNewsletters.Value, null);
string items = DataHelper.GetNewItemsInList(newValues, currentValues);
if (subscriber != null)
{
if (!String.IsNullOrEmpty(items))
{
string[] newItems = items.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
var newsletterIds = newItems.Select(item => ValidationHelper.GetInteger(item, 0)).ToArray();
foreach (var newsletterId in newsletterIds)
{
mSubscriptionService.RemoveSubscription(subscriber.SubscriberID, newsletterId, SendConfirmationEmail);
LogUnsubscriptionActivity(newsletterId);
}
}
}
// Add new items
items = DataHelper.GetNewItemsInList(currentValues, newValues);
if (!String.IsNullOrEmpty(items))
{
string[] newItems = items.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string item in newItems)
{
var newsletterId = ValidationHelper.GetInteger(item, 0);
try
{
var contact = mContactProvider.GetContactForSubscribing(userInfo);
var newsletter = NewsletterInfoProvider.GetNewsletterInfo(newsletterId);
mSubscriptionService.Subscribe(contact, newsletter, new SubscribeSettings()
{
SendConfirmationEmail = SendConfirmationEmail,
AllowOptIn = true,
RemoveAlsoUnsubscriptionFromAllNewsletters = true,
});
}
catch (Exception ex)
{
EventLogProvider.LogException(ex.Source, "SUBSCRIBE", ex, SiteID);
// Can occur e.g. when newsletter is deleted while the user is selecting it for subscription.
// This is rare scenario, the main purpose of this catch is to avoid YSOD on the live site.
}
}
}
// Display information about successful (un)subscription
ShowChangesSaved();
}
private void LoadNewslettersForSubscriber()
{
if (subscriber == null)
{
return;
}
// Get selected newsletters
DataSet ds = SubscriberNewsletterInfoProvider.GetSubscriberNewsletters().WhereEquals("SubscriberID", subscriber.SubscriberID).Column("NewsletterID");
if (!DataHelper.DataSourceIsEmpty(ds))
{
currentValues = TextHelper.Join(";", DataHelper.GetStringValues(ds.Tables[0], "NewsletterID"));
}
// Load selected newsletters
if (!RequestHelper.IsPostBack() || !string.IsNullOrEmpty(DataHelper.GetNewItemsInList(SelectorValue, currentValues)))
{
usNewsletters.Value = currentValues;
}
}
private void InitializeUser()
{
// Get specified user if used instead of current user
if (UserID > 0)
{
userInfo = UserInfoProvider.GetUserInfo(UserID);
}
else
{
userInfo = MembershipContext.AuthenticatedUser;
}
}
/// <summary>
/// Logs unsubscription activity if newsletter exists
/// </summary>
private void LogUnsubscriptionActivity(int newsletterId)
{
var newsletter = NewsletterInfoProvider.GetNewsletterInfo(newsletterId);
if (newsletter == null)
{
return;
}
var activityLogger = Service.Resolve<INewslettersActivityLogger>();
activityLogger.LogUnsubscribeFromSingleNewsletterActivity(newsletter);
}
private void InitializeSubscriber(UserInfo user, int siteId)
{
var contact = mContactProvider.GetContactForSubscribing(user);
subscriber = SubscriberInfoProvider.GetSubscriberInfo(ContactInfo.OBJECT_TYPE, contact.ContactID, siteId);
}
private bool IsUserIdentified()
{
return (userInfo != null) && !userInfo.IsPublic() && ValidationHelper.IsEmail(userInfo.Email);
}
private string GetVisitorEmail()
{
return mContactProvider.GetContactForSubscribing(userInfo).ContactEmail;
}
#endregion
} | 27.460905 | 193 | 0.563165 | [
"MIT"
] | BryanSoltis/KenticoMVCWidgetShowcase | CMS/CMSModules/Newsletters/Controls/MySubscriptions.ascx.cs | 13,348 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public enum GameState
{
Menu,
Play,
Pause
}
| 12.454545 | 33 | 0.722628 | [
"MIT"
] | mdduran/Colossal-Ascent | Assets/Scripts/Game/GameState.cs | 139 | C# |
using System;
using Android.App;
using Android.Content.PM;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using Xamarin.Material.Forms.Android.Renderers;
namespace Shrine.Droid
{
[Activity(Label = "Shrine", Icon = "@mipmap/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
protected override void OnCreate(Bundle savedInstanceState)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
LoadApplication(new App());
}
}
} | 33.346154 | 181 | 0.709343 | [
"MIT"
] | XenoltSoftware/Xamarin.Material.Forms | Xamarin.Material.Forms/Shrine.Android/MainActivity.cs | 869 | C# |
using RefactoringEssentials.CSharp.Diagnostics;
using Xunit;
namespace RefactoringEssentials.Tests.CSharp.Diagnostics
{
public class EqualExpressionComparisonTests : CSharpDiagnosticTestBase
{
[Fact]
public void TestEquality()
{
Analyze<EqualExpressionComparisonAnalyzer>(@"class Foo
{
static int Bar (object o)
{
if ($o == o$) {
}
return 5;
}
}", @"class Foo
{
static int Bar (object o)
{
if (true) {
}
return 5;
}
}");
}
[Fact]
public void TestInequality()
{
Analyze<EqualExpressionComparisonAnalyzer>(@"class Foo
{
static int Bar (object o)
{
if ($o != o$) {
}
return 5;
}
}", @"class Foo
{
static int Bar (object o)
{
if (false) {
}
return 5;
}
}");
}
[Fact]
public void TestEquals()
{
Analyze<EqualExpressionComparisonAnalyzer>(@"class Foo
{
static int Bar (object o)
{
if ($(1 + 2).Equals(1 + 2)$) {
}
return 5;
}
}", @"class Foo
{
static int Bar (object o)
{
if (true) {
}
return 5;
}
}");
}
[Fact]
public void TestNotEquals()
{
Analyze<EqualExpressionComparisonAnalyzer>(@"class Foo
{
static int Bar (object o)
{
if ($!(1 + 2).Equals(1 + 2)$) {
}
return 5;
}
}", @"class Foo
{
static int Bar (object o)
{
if (false) {
}
return 5;
}
}");
}
[Fact]
public void TestStaticEquals()
{
Analyze<EqualExpressionComparisonAnalyzer>(@"class Foo
{
static int Bar (object o)
{
if ($Equals(o, o)$) {
}
return 5;
}
}", @"class Foo
{
static int Bar (object o)
{
if (true) {
}
return 5;
}
}");
}
[Fact]
public void TestNotStaticEquals()
{
Analyze<EqualExpressionComparisonAnalyzer>(@"class Foo
{
static int Bar (object o)
{
if ($!Equals(o, o)$) {
}
return 5;
}
}", @"class Foo
{
static int Bar (object o)
{
if (false) {
}
return 5;
}
}");
}
[Fact]
public void TestDisable()
{
Analyze<EqualExpressionComparisonAnalyzer>(@"class Foo
{
static int Bar (object o)
{
#pragma warning disable " + CSharpDiagnosticIDs.EqualExpressionComparisonAnalyzerID + @"
if (o == o) {
}
return 5;
}
}");
}
[Fact]
public void TestStaticQualifiedEquals()
{
Analyze<EqualExpressionComparisonAnalyzer>(@"class Foo
{
static int Bar (object o)
{
if ($object.Equals(o, o)$) {
}
return 5;
}
}", @"class Foo
{
static int Bar (object o)
{
if (true) {
}
return 5;
}
}");
}
}
}
| 16.856354 | 88 | 0.466404 | [
"MIT"
] | GrahamTheCoder/RefactoringEssentials | Tests/CSharp/Diagnostics/EqualExpressionComparisonTests.cs | 3,051 | C# |
// Licensed to Elasticsearch B.V under one or more agreements.
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
using Elastic.Clients.Elasticsearch.Cluster;
using Tests.Core.ManagedElasticsearch.Clusters;
using Tests.Framework.EndpointTests;
using Tests.Framework.EndpointTests.TestState;
namespace Tests.Cluster.ClusterPendingTasks
{
public class ClusterPendingTasksApiTests
: ApiIntegrationTestBase<ReadOnlyCluster, ClusterPendingTasksResponse, ClusterPendingTasksRequestDescriptor,
ClusterPendingTasksRequest>
{
public ClusterPendingTasksApiTests(ReadOnlyCluster cluster, EndpointUsage usage) : base(cluster, usage) { }
protected override bool ExpectIsValid => true;
protected override int ExpectStatusCode => 200;
protected override HttpMethod HttpMethod => HttpMethod.GET;
protected override string ExpectedUrlPathAndQuery => "/_cluster/pending_tasks";
protected override LazyResponses ClientUsage() => Calls(
(client, f) => client.Cluster.PendingTasks(),
(client, f) => client.Cluster.PendingTasksAsync(),
(client, r) => client.Cluster.PendingTasks(r),
(client, r) => client.Cluster.PendingTasksAsync(r)
);
protected override void ExpectResponse(ClusterPendingTasksResponse response) => response.Tasks.Should().NotBeNull();
}
}
| 41.484848 | 118 | 0.791819 | [
"Apache-2.0"
] | SimonCropp/elasticsearch-net | tests/Tests/Cluster/ClusterPendingTasks/ClusterPendingTasksApiTests.cs | 1,369 | C# |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
namespace PassingParameters
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
var bootstrapper = new Bootstrapper();
bootstrapper.Run();
}
}
}
| 21.12 | 61 | 0.645833 | [
"MIT"
] | Arc3D/Prism-Samples-Wpf | 21-PassingParameters/PassingParameters/App.xaml.cs | 530 | C# |
//
// ThreadSafe attribute
//
// Copyright 2012, 2015, Xamarin Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//
using System;
namespace XamCore.ObjCRuntime {
#if XAMCORE_2_0
sealed
#endif
public class ThreadSafeAttribute : Attribute {
public ThreadSafeAttribute ()
{
Safe = true;
}
public ThreadSafeAttribute (bool safe)
{
Safe = safe;
}
public bool Safe { get; private set; }
}
} | 30.25 | 73 | 0.739669 | [
"BSD-3-Clause"
] | Acidburn0zzz/xamarin-macios | src/ObjCRuntime/ThreadSafeAttribute.cs | 1,452 | C# |
using System.Reflection;
using System.Runtime.InteropServices;
// Les informations générales relatives à un assembly dépendent de
// l'ensemble d'attributs suivant. Changez les valeurs de ces attributs pour modifier les informations
// associées à un assembly.
[assembly: AssemblyTitle("Wexflow.Tasks.FilesRenamer")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("EL ASSAS")]
[assembly: AssemblyProduct("Wexflow.Tasks.FilesRenamer")]
[assembly: AssemblyCopyright("Copyright © EL ASSAS 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// L'affectation de la valeur false à ComVisible rend les types invisibles dans cet assembly
// aux composants COM. Si vous devez accéder à un type dans cet assembly à partir de
// COM, affectez la valeur true à l'attribut ComVisible sur ce type.
[assembly: ComVisible(false)]
// Le GUID suivant est pour l'ID de la typelib si ce projet est exposé à COM
[assembly: Guid("795b2411-606f-4ec9-8009-5885cbd37671")]
// Les informations de version pour un assembly se composent des quatre valeurs suivantes :
//
// Version principale
// Version secondaire
// Numéro de build
// Révision
//
// Vous pouvez spécifier toutes les valeurs ou indiquer les numéros de build et de révision par défaut
// en utilisant '*', comme indiqué ci-dessous :
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 41.694444 | 103 | 0.750833 | [
"MIT"
] | BrianLakstins/Wexflow | src/dotnet/Wexflow.Tasks.FilesRenamer/Properties/AssemblyInfo.cs | 1,526 | C# |
using System;
namespace Neko.Utility.Core.Configurations
{
[Serializable]
public class GenerateCodeConfiguration
{
/// <summary>
/// 二维码/条形码的边距
/// </summary>
public int CodeMargin { get; set; }
/// <summary>
/// 二维码/条形码的长
/// </summary>
public int CodeWidth { get; set; }
/// <summary>
/// 二维码/条形码的宽
/// </summary>
public int CodeHeight { get; set; }
/// <summary>
/// 二维码logo的长
/// <para>仅在生成二维码时有效</para>
/// </summary>
public int LogoWidth { get; set; }
/// <summary>
/// 二维码logo的宽
/// <para>仅在生成二维码时有效</para>
/// </summary>
public int LogoHeight { get; set; }
/// <summary>
/// 二维码/条形码的内容编码
/// </summary>
public string CodeCharset { get; set; }
/// <summary>
/// 生成二维码的默认配置
/// </summary>
public static GenerateCodeConfiguration QrCodeDefault { get; }
/// <summary>
/// 生成条形码的默认配置
/// </summary>
public static GenerateCodeConfiguration BarCodeDefault { get; }
static GenerateCodeConfiguration()
{
QrCodeDefault = InitQrCodeDefault();
BarCodeDefault = InitBarCodeDefault();
}
/// <summary>
/// 初始化条形码默认配置
/// </summary>
/// <returns></returns>
private static GenerateCodeConfiguration InitBarCodeDefault()
{
return new GenerateCodeConfiguration()
{
CodeMargin = 1,
CodeWidth = 100,
CodeHeight = 40,
CodeCharset = "UTF-8"
};
}
/// <summary>
/// 初始化二维码默认配置
/// </summary>
/// <returns></returns>
private static GenerateCodeConfiguration InitQrCodeDefault()
{
return new GenerateCodeConfiguration()
{
CodeMargin = 1,
CodeWidth = 250,
CodeHeight = 250,
LogoWidth = 83,
LogoHeight = 83,
CodeCharset = "UTF-8"
};
}
}
}
| 24.831461 | 71 | 0.475113 | [
"Apache-2.0"
] | SKYC829/Neko.Utility.Core | src/Neko.Utility.Core/Neko.Utility.Core/Configurations/GenerateCodeConfiguration.cs | 2,424 | C# |
using System;
using UnityEngine;
namespace HouraiTeahouse.Attributes {
/// <summary>
/// A propperty attribute that provides a Tag selector for strings.
/// </summary>
[AttributeUsage(AttributeTargets.Field)]
public class TagAttribute : PropertyAttribute {
}
}
| 18.857143 | 67 | 0.765152 | [
"MIT"
] | HouraiTeahouse/HouraiCore | Runtime/Attributes/TagAttribute.cs | 264 | C# |
using System.Web;
using System.Web.Mvc;
namespace MVC.RBAC
{
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
}
}
| 19.571429 | 81 | 0.616788 | [
"Apache-2.0"
] | HuZeHua/MVC.RBAC | MVC.RBAC/App_Start/FilterConfig.cs | 276 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Gcp.Container.Outputs
{
[OutputType]
public sealed class GetClusterNodeConfigGuestAcceleratorResult
{
public readonly int Count;
public readonly string Type;
[OutputConstructor]
private GetClusterNodeConfigGuestAcceleratorResult(
int count,
string type)
{
Count = count;
Type = type;
}
}
}
| 24.566667 | 88 | 0.662144 | [
"ECL-2.0",
"Apache-2.0"
] | dimpu47/pulumi-gcp | sdk/dotnet/Container/Outputs/GetClusterNodeConfigGuestAcceleratorResult.cs | 737 | C# |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// Template Source: Templates\CSharp\Requests\EntityCollectionRequestBuilder.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
/// <summary>
/// The type OutlookUserMasterCategoriesCollectionRequestBuilder.
/// </summary>
public partial class OutlookUserMasterCategoriesCollectionRequestBuilder : BaseRequestBuilder, IOutlookUserMasterCategoriesCollectionRequestBuilder
{
/// <summary>
/// Constructs a new OutlookUserMasterCategoriesCollectionRequestBuilder.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
public OutlookUserMasterCategoriesCollectionRequestBuilder(
string requestUrl,
IBaseClient client)
: base(requestUrl, client)
{
}
/// <summary>
/// Builds the request.
/// </summary>
/// <returns>The built request.</returns>
public IOutlookUserMasterCategoriesCollectionRequest Request()
{
return this.Request(null);
}
/// <summary>
/// Builds the request.
/// </summary>
/// <param name="options">The query and header options for the request.</param>
/// <returns>The built request.</returns>
public IOutlookUserMasterCategoriesCollectionRequest Request(IEnumerable<Option> options)
{
return new OutlookUserMasterCategoriesCollectionRequest(this.RequestUrl, this.Client, options);
}
/// <summary>
/// Gets an <see cref="IOutlookCategoryRequestBuilder"/> for the specified OutlookUserOutlookCategory.
/// </summary>
/// <param name="id">The ID for the OutlookUserOutlookCategory.</param>
/// <returns>The <see cref="IOutlookCategoryRequestBuilder"/>.</returns>
public IOutlookCategoryRequestBuilder this[string id]
{
get
{
return new OutlookCategoryRequestBuilder(this.AppendSegmentToRequestUrl(id), this.Client);
}
}
}
}
| 39.876923 | 153 | 0.609182 | [
"MIT"
] | AzureMentor/msgraph-sdk-dotnet | src/Microsoft.Graph/Requests/Generated/OutlookUserMasterCategoriesCollectionRequestBuilder.cs | 2,592 | C# |
using System;
using Newtonsoft.Json;
namespace Essensoft.AspNetCore.Payment.Alipay.Domain
{
/// <summary>
/// PrizeLiteInfo Data Structure.
/// </summary>
[Serializable]
public class PrizeLiteInfo : AlipayObject
{
/// <summary>
/// 外部奖品ID
/// </summary>
[JsonProperty("out_prize_id")]
public string OutPrizeId { get; set; }
/// <summary>
/// 奖品状态,可枚举,分别为“可用”(ENABLED)、“不可用”(DISABLED)、“不满足使用规则”(NOT_MATCH_USE_CONDITION)
/// </summary>
[JsonProperty("status")]
public string Status { get; set; }
}
}
| 24.36 | 88 | 0.579639 | [
"MIT"
] | gebiWangshushu/payment | src/Essensoft.AspNetCore.Payment.Alipay/Domain/PrizeLiteInfo.cs | 683 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.OleDb; // Veri tabanı bağlantısı için gerekli kütüphaneyi ekledik.
using System.Data; // Veri tabanı bağlantısı için gerekli kütüphaneyi ekledik.
using Entity; // Entity katmanını kullandık.
namespace DAL
{
public class KitapIadeDAL
{
//Kitabin iade edilip edilmediği kontrol edilerek istenilen formattıki veriler veritabanından çekildi
public static List<KitapOgrenciVeri> KayitKitapOgrenciListe(KitapOgrenciVeri kitap)
{
OleDbCommand command = new OleDbCommand("Select k.KitapId,k.KitapAd,o.OgrenciAd,o.OgrenciSoyad,kk.KitapAlinma,kk.KitapTeslim,kk.KitapKontrol from ((Kitap k inner join KitapKayit kk on k.KitapId=kk.KitapId) inner join Ogrenci o on o.OgrenciId=kk.OgrenciId) where kk.KitapKontrol = @Kotrol", Baglanti.baglanti);
Baglanti.Connection(command);
command.Parameters.AddWithValue("@Kontrol", kitap.KitapKontrol);
OleDbDataReader read = command.ExecuteReader();
List<KitapOgrenciVeri> kitapOgrenci = new List<KitapOgrenciVeri>();
while (read.Read())
{
kitapOgrenci.Add(new KitapOgrenciVeri
{
KitapId = int.Parse(read["KitapId"].ToString()),
KitapAd = read["KitapAd"].ToString(),
OgrenciAd = read["OgrenciAd"].ToString(),
OgrenciSoyad = read["OgrenciSoyad"].ToString(),
KitapAlinma = DateTime.Parse(read["KitapAlinma"].ToString()),
KitapTeslim = read["KitapTeslim"].ToString(),
KitapKontrol = bool.Parse(read["KitapKontrol"].ToString())
});
}
return kitapOgrenci;
}
//Kitabı alanların detaylı listesini inner join yöntemi ile 3 tablodan verilerini çekerek aldık
public static List<KitapOgrenciVeri> kitapOgrenciListe(KitapOgrenciVeri kitap)
{
OleDbCommand command = new OleDbCommand("Select k.KitapId,o.OgrenciAd,o.OgrenciSoyad,k.KitapAd,kk.KitapAlinma,kk.KitapTeslim,kk.KitapKontrol from ((Kitap k inner join KitapKayit kk on k.KitapId=kk.KitapId) inner join Ogrenci o on o.OgrenciId=kk.OgrenciId) where k.KitapId = @KitapId", Baglanti.baglanti);
Baglanti.Connection(command);
command.Parameters.AddWithValue("@KitapId", kitap.KitapId);
OleDbDataReader read = command.ExecuteReader();
List<KitapOgrenciVeri> kitapOgrenci = new List<KitapOgrenciVeri>();
while (read.Read())
{
kitapOgrenci.Add(new KitapOgrenciVeri
{
KitapId = int.Parse(read["KitapId"].ToString()),
OgrenciAd = read["OgrenciAd"].ToString(),
OgrenciSoyad = read["OgrenciSoyad"].ToString(),
KitapAd = read["KitapAd"].ToString(),
KitapAlinma = DateTime.Parse(read["KitapAlinma"].ToString()),
KitapTeslim = read["KitapTeslim"].ToString(),
KitapKontrol = bool.Parse(read["KitapKontrol"].ToString())
});
}
return kitapOgrenci;
}
//Ogrencinin almış olduğu kitaplar tarihsel olarak listelendi. Yine inner join yöntemi ile veriler çekildi
public static List<AlinanKitapVeri> ogrenciIdListe(AlinanKitapVeri kitap)
{
OleDbCommand command = new OleDbCommand("Select o.OgrenciId,k.KitapAd,kk.KitapAlinma,kk.KitapTeslim,kk.KitapKontrol from ((Kitap k inner join KitapKayit kk on k.KitapId=kk.KitapId) inner join Ogrenci o on o.OgrenciId=kk.OgrenciId) where o.OgrenciId = @OgrenciId", Baglanti.baglanti);
Baglanti.Connection(command);
command.Parameters.AddWithValue("@OgrenciId", kitap.OgrenciId);
OleDbDataReader read = command.ExecuteReader();
List<AlinanKitapVeri> kitapOgrenci = new List<AlinanKitapVeri>();
while (read.Read())
{
kitapOgrenci.Add(new AlinanKitapVeri
{
OgrenciId = int.Parse(read["OgrenciId"].ToString()),
KitapAd = read["KitapAd"].ToString(),
KitapAlinma = DateTime.Parse(read["KitapAlinma"].ToString()),
KitapTeslim = read["KitapTeslim"].ToString(),
KitapKontrol = bool.Parse(read["KitapKontrol"].ToString())
});
}
return kitapOgrenci;
}
//Alinabilir durumdaki kitapların teslim edilme durumlarına göre listeleme işlemi gerçekleştirildi
public static List<string> kitapAlinanListe(KitapIadeVeri kitap)
{
OleDbCommand command = new OleDbCommand("Select KitapAd from Kitap where KitapId not in(select KitapId from KitapKayit where OgrenciId=@OgrenciId and KitapKontrol=false)", Baglanti.baglanti);
Baglanti.Connection(command);
command.Parameters.AddWithValue("@OgrenciId", kitap.OgrenciId);
OleDbDataReader read = command.ExecuteReader();
List<string> liste = new List<string>();
while (read.Read())
{
liste.Add(read["KitapAd"].ToString());
}
return liste;
}
//Teslim edilmesi gereken kitaplar teslim edilmeme durumuna göre listeye aktarıldı
public static List<string> kitapTeslimListe(KitapIadeVeri kitap)
{
OleDbCommand command = new OleDbCommand("Select KitapAd from Kitap where KitapId in(select KitapId from KitapKayit where OgrenciId=@OgrenciId and KitapKontrol=false)", Baglanti.baglanti);
Baglanti.Connection(command);
command.Parameters.AddWithValue("@OgrenciId", kitap.OgrenciId);
OleDbDataReader read = command.ExecuteReader();
List<string> liste = new List<string>();
while (read.Read())
{
liste.Add(read["KitapAd"].ToString());
}
return liste;
}
//Öğrenciye verilmiş kitapların sayısı int olarak döndürüldü
public static int grafikVerilmis(KitapIadeVeri kitap)
{
OleDbCommand command = new OleDbCommand("Select KitapAd from Kitap where KitapId in(select KitapId from KitapKayit where OgrenciId=@OgrenciId and KitapKontrol=false)", Baglanti.baglanti);
Baglanti.Connection(command);
command.Parameters.AddWithValue("@OgrenciId", kitap.OgrenciId);
OleDbDataReader read = command.ExecuteReader();
int sayac = 0;
while (read.Read())
{
sayac++;
}
return sayac;
}
//Tüm kitapların sayısı int olarak döndürüldü
public static int grafikHepsi()
{
OleDbCommand command = new OleDbCommand("Select * from Kitap", Baglanti.baglanti);
Baglanti.Connection(command);
OleDbDataReader read = command.ExecuteReader();
int sayac = 0;
while (read.Read())
{
sayac++;
}
return sayac;
}
//Alınabilir kitapların sayısı int olarak döndürüldü
public static int grafikAlinabilir(KitapIadeVeri kitap)
{
OleDbCommand command = new OleDbCommand("Select KitapAd from Kitap where KitapId not in(select KitapId from KitapKayit where OgrenciId=@OgrenciId and KitapKontrol=false)", Baglanti.baglanti);
Baglanti.Connection(command);
command.Parameters.AddWithValue("@OgrenciId", kitap.OgrenciId);
OleDbDataReader read = command.ExecuteReader();
int sayac = 0;
while (read.Read())
{
sayac++;
}
return sayac;
}
// Alınma tarihini kitapkayıt tablosundan çekip listeye aktardık
public static List<string> kitapTarih(KitapIadeVeri kitap)
{
OleDbCommand command = new OleDbCommand("Select KitapAlinma from KitapKayit where KitapId=@KitapId and OgrenciId=@OgrenciId", Baglanti.baglanti);
Baglanti.Connection(command);
command.Parameters.AddWithValue("@KitapId", kitap.KitapId);
command.Parameters.AddWithValue("@OgrenciId", kitap.OgrenciId);
OleDbDataReader read = command.ExecuteReader();
List<string> liste = new List<string>();
while (read.Read())
{
kitap.KitapAlinma = DateTime.Parse(read["KitapAlinma"].ToString());
}
return liste;
}
//Veritabanından öğrenciye ait ceza bilgisi listeye aktarıldı
public static List<string> OgrenciCeza(KitapIadeVeri kitap)
{
OleDbCommand command = new OleDbCommand("Select o.OgrenciCeza from ((Kitap k inner join KitapKayit kk on k.KitapId=kk.KitapId) inner join Ogrenci o on o.OgrenciId=kk.OgrenciId) where o.OgrenciId = @OgrenciId", Baglanti.baglanti);
Baglanti.Connection(command);
command.Parameters.AddWithValue("@OgrenciId", kitap.OgrenciId);
OleDbDataReader read = command.ExecuteReader();
List<string> liste = new List<string>();
while (read.Read())
{
kitap.OgrenciCeza = float.Parse(read["OgrenciCeza"].ToString());
}
return liste;
}
//Ceza işlemi gerçekleştirildikten sonra ogrenciye ait ceza verisinde guncelleme yapıldı
public static int ogrenciCezaIslemi(KitapIadeVeri ogrenci)
{
OleDbCommand command = new OleDbCommand("Update Ogrenci set OgrenciCeza=@OgrenciCeza where OgrenciId=@OgrenciId", Baglanti.baglanti);
Baglanti.Connection(command);
command.Parameters.AddWithValue("@OgrenciCeza", ogrenci.OgrenciCeza);
command.Parameters.AddWithValue("@OgrenciId", ogrenci.OgrenciId);
return command.ExecuteNonQuery();
}
//Kitap alındğında veri tabanına veriler eklendi
public static int kitapAlimIslemi(KitapIadeVeri kitap)
{
OleDbCommand command = new OleDbCommand("insert into KitapKayit(KitapId,OgrenciId,KitapAlinma) values(@KitapId,OgrenciId,@KitapAlinma)", Baglanti.baglanti);
Baglanti.Connection(command);
command.Parameters.AddWithValue("@KitapId", kitap.KitapId);
command.Parameters.AddWithValue("@OgrenciId", kitap.OgrenciId);
command.Parameters.AddWithValue("@KitapAlinma", kitap.KitapAlinma);
return command.ExecuteNonQuery();
}
//Kitap teslim edildiğinde veriler güncellendi
public static int kitapTeslimIslemi(KitapIadeVeri kitap)
{
OleDbCommand command = new OleDbCommand("Update KitapKayit set KitapTeslim=@KitapTeslim,KitapKontrol=@KitapKontrol where KitapId=@KitapId and OgrenciId=@Ogrenci", Baglanti.baglanti);
Baglanti.Connection(command);
command.Parameters.AddWithValue("@KitapTeslim", kitap.KitapTeslim);
command.Parameters.AddWithValue("@KitapKontrol", kitap.KitapKontrol);
command.Parameters.AddWithValue("@KitapId", kitap.KitapId);
command.Parameters.AddWithValue("@OgrenciId", kitap.OgrenciId);
return command.ExecuteNonQuery();
}
//Kitap adı sorgusu ile ada ait kitapId verisi int döndürüldü
public static int kitapId(KitapOgrenciVeri kitap)
{
OleDbCommand command = new OleDbCommand("Select KitapId from Kitap where KitapAd=@KitapAd", Baglanti.baglanti);
Baglanti.Connection(command);
command.Parameters.AddWithValue("@KitapAd", kitap.KitapAd);
OleDbDataReader read = command.ExecuteReader();
int id = 0;
while (read.Read())
{
id = int.Parse(read["KitapId"].ToString());
}
return id;
}
}
}
| 45.666667 | 321 | 0.62339 | [
"MIT"
] | Huseyinarkin/KutuphaneOtomasyonu | DAL/KitapIadeDAL.cs | 12,287 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml;
using Microsoft.Build.BackEnd.SdkResolution;
using Microsoft.Build.Construction;
using Microsoft.Build.Definition;
using Microsoft.Build.Evaluation;
using Microsoft.Build.Evaluation.Context;
using Microsoft.Build.Execution;
using Microsoft.Build.Framework;
using Microsoft.Build.Unittest;
using Shouldly;
using Xunit;
using SdkResult = Microsoft.Build.BackEnd.SdkResolution.SdkResult;
namespace Microsoft.Build.UnitTests.Definition
{
/// <summary>
/// Tests some manipulations of Project and ProjectCollection that require dealing with internal data.
/// </summary>
public class ProjectEvaluationContext_Tests : IDisposable
{
public ProjectEvaluationContext_Tests()
{
_env = TestEnvironment.Create();
_resolver = new SdkUtilities.ConfigurableMockSdkResolver(
new Dictionary<string, SdkResult>
{
{"foo", new SdkResult(new SdkReference("foo", "1.0.0", null), "path", "1.0.0", null)},
{"bar", new SdkResult(new SdkReference("bar", "1.0.0", null), "path", "1.0.0", null)}
});
}
public void Dispose()
{
_env.Dispose();
}
private readonly SdkUtilities.ConfigurableMockSdkResolver _resolver;
private readonly TestEnvironment _env;
private static void SetResolverForContext(EvaluationContext context, SdkResolver resolver)
{
var sdkService = (SdkResolverService) context.SdkResolverService;
sdkService.InitializeForTests(null, new List<SdkResolver> {resolver});
}
[Theory]
[InlineData(EvaluationContext.SharingPolicy.Shared)]
[InlineData(EvaluationContext.SharingPolicy.Isolated)]
public void SharedContextShouldGetReusedWhereasIsolatedContextShouldNot(EvaluationContext.SharingPolicy policy)
{
var previousContext = EvaluationContext.Create(policy);
for (var i = 0; i < 10; i++)
{
var currentContext = previousContext.ContextForNewProject();
if (i == 0)
{
currentContext.ShouldBeSameAs(previousContext, "first usage context was not the same as the initial context");
}
else
{
switch (policy)
{
case EvaluationContext.SharingPolicy.Shared:
currentContext.ShouldBeSameAs(previousContext, $"Shared policy: usage {i} was not the same as usage {i - 1}");
break;
case EvaluationContext.SharingPolicy.Isolated:
currentContext.ShouldNotBeSameAs(previousContext, $"Isolated policy: usage {i} was the same as usage {i - 1}");
break;
default:
throw new ArgumentOutOfRangeException(nameof(policy), policy, null);
}
}
previousContext = currentContext;
}
}
[Fact]
public void PassedInFileSystemShouldBeReusedInSharedContext()
{
var projectFiles = new[]
{
_env.CreateFile("1.proj", @"<Project> <PropertyGroup Condition=`Exists('1.file')`></PropertyGroup> </Project>".Cleanup()).Path,
_env.CreateFile("2.proj", @"<Project> <PropertyGroup Condition=`Exists('2.file')`></PropertyGroup> </Project>".Cleanup()).Path
};
var projectCollection = _env.CreateProjectCollection().Collection;
var fileSystem = new Helpers.LoggingFileSystem();
var evaluationContext = EvaluationContext.Create(EvaluationContext.SharingPolicy.Shared, fileSystem);
foreach (var projectFile in projectFiles)
{
Project.FromFile(
projectFile,
new ProjectOptions
{
ProjectCollection = projectCollection,
EvaluationContext = evaluationContext
}
);
}
fileSystem.ExistenceChecks.OrderBy(kvp => kvp.Key)
.ShouldBe(
new Dictionary<string, int>
{
{Path.Combine(_env.DefaultTestDirectory.Path, "1.file"), 1},
{Path.Combine(_env.DefaultTestDirectory.Path, "2.file"), 1}
}.OrderBy(kvp => kvp.Key));
fileSystem.FileOrDirectoryExistsCalls.ShouldBe(2);
}
[Fact]
public void IsolatedContextShouldNotSupportBeingPassedAFileSystem()
{
var fileSystem = new Helpers.LoggingFileSystem();
Should.Throw<ArgumentException>(() => EvaluationContext.Create(EvaluationContext.SharingPolicy.Isolated, fileSystem));
}
[Fact]
public void EvaluationShouldUseDirectoryCache()
{
var projectFile = _env.CreateFile("1.proj", @"<Project> <ItemGroup Condition=`Exists('1.file')`> <Compile Include='*.cs'/> </ItemGroup> </Project>".Cleanup()).Path;
var projectCollection = _env.CreateProjectCollection().Collection;
var directoryCacheFactory = new Helpers.LoggingDirectoryCacheFactory();
var project = Project.FromFile(
projectFile,
new ProjectOptions
{
ProjectCollection = projectCollection,
DirectoryCacheFactory = directoryCacheFactory,
}
);
directoryCacheFactory.DirectoryCaches.Count.ShouldBe(1);
var directoryCache = directoryCacheFactory.DirectoryCaches[0];
directoryCache.EvaluationId.ShouldBe(project.LastEvaluationId);
directoryCache.ExistenceChecks.OrderBy(kvp => kvp.Key).ShouldBe(
new Dictionary<string, int>
{
{ _env.DefaultTestDirectory.Path, 1},
{ Path.Combine(_env.DefaultTestDirectory.Path, "1.file"), 2 }
}.OrderBy(kvp => kvp.Key));
directoryCache.Enumerations.ShouldBe(
new Dictionary<string, int>
{
{ _env.DefaultTestDirectory.Path, 1 }
});
}
[Theory]
[InlineData(EvaluationContext.SharingPolicy.Shared)]
[InlineData(EvaluationContext.SharingPolicy.Isolated)]
public void ReevaluationShouldNotReuseInitialContext(EvaluationContext.SharingPolicy policy)
{
try
{
EvaluationContext.TestOnlyHookOnCreate = c => SetResolverForContext(c, _resolver);
var collection = _env.CreateProjectCollection().Collection;
var context = EvaluationContext.Create(policy);
var project = Project.FromXmlReader(
XmlReader.Create(new StringReader("<Project Sdk=\"foo\"></Project>")),
new ProjectOptions
{
ProjectCollection = collection,
EvaluationContext = context,
LoadSettings = ProjectLoadSettings.IgnoreMissingImports
});
_resolver.ResolvedCalls["foo"].ShouldBe(1);
project.AddItem("a", "b");
project.ReevaluateIfNecessary();
_resolver.ResolvedCalls["foo"].ShouldBe(2);
}
finally
{
EvaluationContext.TestOnlyHookOnCreate = null;
}
}
[Theory]
[InlineData(EvaluationContext.SharingPolicy.Shared)]
[InlineData(EvaluationContext.SharingPolicy.Isolated)]
public void ProjectInstanceShouldRespectSharingPolicy(EvaluationContext.SharingPolicy policy)
{
try
{
var seenContexts = new HashSet<EvaluationContext>();
EvaluationContext.TestOnlyHookOnCreate = c => seenContexts.Add(c);
var collection = _env.CreateProjectCollection().Collection;
var context = EvaluationContext.Create(policy);
const int numIterations = 10;
for (int i = 0; i < numIterations; i++)
{
ProjectInstance.FromProjectRootElement(
ProjectRootElement.Create(),
new ProjectOptions
{
ProjectCollection = collection,
EvaluationContext = context,
LoadSettings = ProjectLoadSettings.IgnoreMissingImports
});
}
int expectedNumContexts = policy == EvaluationContext.SharingPolicy.Shared ? 1 : numIterations;
seenContexts.Count.ShouldBe(expectedNumContexts);
seenContexts.ShouldAllBe(c => c.Policy == policy);
}
finally
{
EvaluationContext.TestOnlyHookOnCreate = null;
}
}
private static string[] _sdkResolutionProjects =
{
"<Project Sdk=\"foo\"></Project>",
"<Project Sdk=\"bar\"></Project>",
"<Project Sdk=\"foo\"></Project>",
"<Project Sdk=\"bar\"></Project>"
};
[Theory]
[InlineData(EvaluationContext.SharingPolicy.Shared, 1, 1)]
[InlineData(EvaluationContext.SharingPolicy.Isolated, 4, 4)]
public void ContextPinsSdkResolverCache(EvaluationContext.SharingPolicy policy, int sdkLookupsForFoo, int sdkLookupsForBar)
{
try
{
EvaluationContext.TestOnlyHookOnCreate = c => SetResolverForContext(c, _resolver);
var context = EvaluationContext.Create(policy);
EvaluateProjects(_sdkResolutionProjects, context, null);
_resolver.ResolvedCalls.Count.ShouldBe(2);
_resolver.ResolvedCalls["foo"].ShouldBe(sdkLookupsForFoo);
_resolver.ResolvedCalls["bar"].ShouldBe(sdkLookupsForBar);
}
finally
{
EvaluationContext.TestOnlyHookOnCreate = null;
}
}
[Fact]
public void DefaultContextIsIsolatedContext()
{
try
{
var seenContexts = new HashSet<EvaluationContext>();
EvaluationContext.TestOnlyHookOnCreate = c => seenContexts.Add(c);
EvaluateProjects(_sdkResolutionProjects, null, null);
seenContexts.Count.ShouldBe(8); // 4 evaluations and 4 reevaluations
seenContexts.ShouldAllBe(c => c.Policy == EvaluationContext.SharingPolicy.Isolated);
}
finally
{
EvaluationContext.TestOnlyHookOnCreate = null;
}
}
public static IEnumerable<object[]> ContextPinsGlobExpansionCacheData
{
get
{
yield return new object[]
{
EvaluationContext.SharingPolicy.Shared,
new[]
{
new[] {"0.cs"},
new[] {"0.cs"},
new[] {"0.cs"},
new[] {"0.cs"}
}
};
yield return new object[]
{
EvaluationContext.SharingPolicy.Isolated,
new[]
{
new[] {"0.cs"},
new[] {"0.cs", "1.cs"},
new[] {"0.cs", "1.cs", "2.cs"},
new[] {"0.cs", "1.cs", "2.cs", "3.cs"},
}
};
}
}
private static string[] _projectsWithGlobs =
{
@"<Project>
<ItemGroup>
<i Include=`**/*.cs` />
</ItemGroup>
</Project>",
@"<Project>
<ItemGroup>
<i Include=`**/*.cs` />
</ItemGroup>
</Project>",
};
[Theory]
[MemberData(nameof(ContextPinsGlobExpansionCacheData))]
public void ContextCachesItemElementGlobExpansions(EvaluationContext.SharingPolicy policy, string[][] expectedGlobExpansions)
{
var projectDirectory = _env.DefaultTestDirectory.Path;
var context = EvaluationContext.Create(policy);
var evaluationCount = 0;
File.WriteAllText(Path.Combine(projectDirectory, $"{evaluationCount}.cs"), "");
EvaluateProjects(
_projectsWithGlobs,
context,
project =>
{
var expectedGlobExpansion = expectedGlobExpansions[evaluationCount];
evaluationCount++;
File.WriteAllText(Path.Combine(projectDirectory, $"{evaluationCount}.cs"), "");
ObjectModelHelpers.AssertItems(expectedGlobExpansion, project.GetItems("i"));
}
);
}
public static IEnumerable<object[]> ContextDisambiguatesRelativeGlobsData
{
get
{
yield return new object[]
{
EvaluationContext.SharingPolicy.Shared,
new[]
{
new[] {"0.cs"}, // first project
new[] {"0.cs", "1.cs"}, // second project
new[] {"0.cs"}, // first project reevaluation
new[] {"0.cs", "1.cs"}, // second project reevaluation
}
};
yield return new object[]
{
EvaluationContext.SharingPolicy.Isolated,
new[]
{
new[] {"0.cs"},
new[] {"0.cs", "1.cs"},
new[] {"0.cs", "1.cs", "2.cs"},
new[] {"0.cs", "1.cs", "2.cs", "3.cs"},
}
};
}
}
[Theory]
[MemberData(nameof(ContextDisambiguatesRelativeGlobsData))]
public void ContextDisambiguatesSameRelativeGlobsPointingInsideDifferentProjectCones(EvaluationContext.SharingPolicy policy, string[][] expectedGlobExpansions)
{
var projectDirectory1 = _env.DefaultTestDirectory.CreateDirectory("1").Path;
var projectDirectory2 = _env.DefaultTestDirectory.CreateDirectory("2").Path;
var context = EvaluationContext.Create(policy);
var evaluationCount = 0;
File.WriteAllText(Path.Combine(projectDirectory1, $"1.{evaluationCount}.cs"), "");
File.WriteAllText(Path.Combine(projectDirectory2, $"2.{evaluationCount}.cs"), "");
EvaluateProjects(
new []
{
new ProjectSpecification(
Path.Combine(projectDirectory1, "1"),
$@"<Project>
<ItemGroup>
<i Include=`{Path.Combine("**", "*.cs")}` />
</ItemGroup>
</Project>"),
new ProjectSpecification(
Path.Combine(projectDirectory2, "2"),
$@"<Project>
<ItemGroup>
<i Include=`{Path.Combine("**", "*.cs")}` />
</ItemGroup>
</Project>"),
},
context,
project =>
{
var projectName = Path.GetFileNameWithoutExtension(project.FullPath);
var expectedGlobExpansion = expectedGlobExpansions[evaluationCount]
.Select(i => $"{projectName}.{i}")
.ToArray();
ObjectModelHelpers.AssertItems(expectedGlobExpansion, project.GetItems("i"));
evaluationCount++;
File.WriteAllText(Path.Combine(projectDirectory1, $"1.{evaluationCount}.cs"), "");
File.WriteAllText(Path.Combine(projectDirectory2, $"2.{evaluationCount}.cs"), "");
}
);
}
[Theory]
[MemberData(nameof(ContextDisambiguatesRelativeGlobsData))]
public void ContextDisambiguatesSameRelativeGlobsPointingOutsideDifferentProjectCones(EvaluationContext.SharingPolicy policy, string[][] expectedGlobExpansions)
{
var project1Root = _env.DefaultTestDirectory.CreateDirectory("Project1");
var project1Directory = project1Root.CreateDirectory("1").Path;
var project1GlobDirectory = project1Root.CreateDirectory("Glob").CreateDirectory("1").Path;
var project2Root = _env.DefaultTestDirectory.CreateDirectory("Project2");
var project2Directory = project2Root.CreateDirectory("2").Path;
var project2GlobDirectory = project2Root.CreateDirectory("Glob").CreateDirectory("2").Path;
var context = EvaluationContext.Create(policy);
var evaluationCount = 0;
File.WriteAllText(Path.Combine(project1GlobDirectory, $"1.{evaluationCount}.cs"), "");
File.WriteAllText(Path.Combine(project2GlobDirectory, $"2.{evaluationCount}.cs"), "");
EvaluateProjects(
new []
{
new ProjectSpecification(
Path.Combine(project1Directory, "1"),
$@"<Project>
<ItemGroup>
<i Include=`{Path.Combine("..", "Glob", "**", "*.cs")}`/>
</ItemGroup>
</Project>"),
new ProjectSpecification(
Path.Combine(project2Directory, "2"),
$@"<Project>
<ItemGroup>
<i Include=`{Path.Combine("..", "Glob", "**", "*.cs")}`/>
</ItemGroup>
</Project>")
},
context,
project =>
{
var projectName = Path.GetFileNameWithoutExtension(project.FullPath);
// globs have the fixed directory part prepended, so add it to the expected results
var expectedGlobExpansion = expectedGlobExpansions[evaluationCount]
.Select(i => Path.Combine("..", "Glob", projectName, $"{projectName}.{i}"))
.ToArray();
var actualGlobExpansion = project.GetItems("i");
ObjectModelHelpers.AssertItems(expectedGlobExpansion, actualGlobExpansion);
evaluationCount++;
File.WriteAllText(Path.Combine(project1GlobDirectory, $"1.{evaluationCount}.cs"), "");
File.WriteAllText(Path.Combine(project2GlobDirectory, $"2.{evaluationCount}.cs"), "");
}
);
}
[Theory]
[MemberData(nameof(ContextDisambiguatesRelativeGlobsData))]
public void ContextDisambiguatesAFullyQualifiedGlobPointingInAnotherRelativeGlobsCone(EvaluationContext.SharingPolicy policy, string[][] expectedGlobExpansions)
{
if (policy == EvaluationContext.SharingPolicy.Shared)
{
// This test case has a dependency on our glob expansion caching policy. If the evaluation context is reused
// between evaluations and files are added to the filesystem between evaluations, the cache may be returning
// stale results. Run only the Isolated variant.
return;
}
var project1Directory = _env.DefaultTestDirectory.CreateDirectory("Project1");
var project1GlobDirectory = project1Directory.CreateDirectory("Glob").CreateDirectory("1").Path;
var project2Directory = _env.DefaultTestDirectory.CreateDirectory("Project2");
var context = EvaluationContext.Create(policy);
var evaluationCount = 0;
File.WriteAllText(Path.Combine(project1GlobDirectory, $"{evaluationCount}.cs"), "");
EvaluateProjects(
new []
{
// first project uses a relative path
new ProjectSpecification(
Path.Combine(project1Directory.Path, "1"),
$@"<Project>
<ItemGroup>
<i Include=`{Path.Combine("Glob", "**", "*.cs")}` />
</ItemGroup>
</Project>"),
// second project reaches out into first project's cone via a fully qualified path
new ProjectSpecification(
Path.Combine(project2Directory.Path, "2"),
$@"<Project>
<ItemGroup>
<i Include=`{Path.Combine(project1Directory.Path, "Glob", "**", "*.cs")}` />
</ItemGroup>
</Project>")
},
context,
project =>
{
var projectName = Path.GetFileNameWithoutExtension(project.FullPath);
// globs have the fixed directory part prepended, so add it to the expected results
var expectedGlobExpansion = expectedGlobExpansions[evaluationCount]
.Select(i => Path.Combine("Glob", "1", i))
.ToArray();
// project 2 has fully qualified directory parts, so make the results for 2 fully qualified
if (projectName.Equals("2"))
{
expectedGlobExpansion = expectedGlobExpansion
.Select(i => Path.Combine(project1Directory.Path, i))
.ToArray();
}
var actualGlobExpansion = project.GetItems("i");
ObjectModelHelpers.AssertItems(expectedGlobExpansion, actualGlobExpansion);
evaluationCount++;
File.WriteAllText(Path.Combine(project1GlobDirectory, $"{evaluationCount}.cs"), "");
}
);
}
[Theory]
[MemberData(nameof(ContextDisambiguatesRelativeGlobsData))]
public void ContextDisambiguatesDistinctRelativeGlobsPointingOutsideOfSameProjectCone(EvaluationContext.SharingPolicy policy, string[][] expectedGlobExpansions)
{
var globDirectory = _env.DefaultTestDirectory.CreateDirectory("glob");
var projectRoot = _env.DefaultTestDirectory.CreateDirectory("proj");
var project1Directory = projectRoot.CreateDirectory("Project1");
var project2SubDir = projectRoot.CreateDirectory("subdirectory");
var project2Directory = project2SubDir.CreateDirectory("Project2");
var context = EvaluationContext.Create(policy);
var evaluationCount = 0;
File.WriteAllText(Path.Combine(globDirectory.Path, $"{evaluationCount}.cs"), "");
EvaluateProjects(
new []
{
new ProjectSpecification(
Path.Combine(project1Directory.Path, "1"),
@"<Project>
<ItemGroup>
<i Include=`../../glob/*.cs` />
</ItemGroup>
</Project>"),
new ProjectSpecification(
Path.Combine(project2Directory.Path, "2"),
@"<Project>
<ItemGroup>
<i Include=`../../../glob/*.cs` />
</ItemGroup>
</Project>")
},
context,
project =>
{
var projectName = Path.GetFileNameWithoutExtension(project.FullPath);
var globFixedDirectoryPart = projectName.EndsWith("1")
? Path.Combine("..", "..", "glob")
: Path.Combine("..", "..", "..", "glob");
// globs have the fixed directory part prepended, so add it to the expected results
var expectedGlobExpansion = expectedGlobExpansions[evaluationCount]
.Select(i => Path.Combine(globFixedDirectoryPart, i))
.ToArray();
var actualGlobExpansion = project.GetItems("i");
ObjectModelHelpers.AssertItems(expectedGlobExpansion, actualGlobExpansion);
evaluationCount++;
File.WriteAllText(Path.Combine(globDirectory.Path, $"{evaluationCount}.cs"), "");
}
);
}
[Theory]
[MemberData(nameof(ContextPinsGlobExpansionCacheData))]
// projects should cache glob expansions when the __fully qualified__ glob is shared between projects and points outside of project cone
public void ContextCachesCommonOutOfProjectConeFullyQualifiedGlob(EvaluationContext.SharingPolicy policy, string[][] expectedGlobExpansions)
{
ContextCachesCommonOutOfProjectCone(itemSpecPathIsRelative: false, policy: policy, expectedGlobExpansions: expectedGlobExpansions);
}
[Theory (Skip="https://github.com/Microsoft/msbuild/issues/3889")]
[MemberData(nameof(ContextPinsGlobExpansionCacheData))]
// projects should cache glob expansions when the __relative__ glob is shared between projects and points outside of project cone
public void ContextCachesCommonOutOfProjectConeRelativeGlob(EvaluationContext.SharingPolicy policy, string[][] expectedGlobExpansions)
{
ContextCachesCommonOutOfProjectCone(itemSpecPathIsRelative: true, policy: policy, expectedGlobExpansions: expectedGlobExpansions);
}
private void ContextCachesCommonOutOfProjectCone(bool itemSpecPathIsRelative, EvaluationContext.SharingPolicy policy, string[][] expectedGlobExpansions)
{
var testDirectory = _env.DefaultTestDirectory;
var globDirectory = testDirectory.CreateDirectory("GlobDirectory");
var itemSpecDirectoryPart = itemSpecPathIsRelative
? Path.Combine("..", "GlobDirectory")
: globDirectory.Path;
Directory.CreateDirectory(globDirectory.Path);
// Globs with a directory part will produce items prepended with that directory part
foreach (var globExpansion in expectedGlobExpansions)
{
for (var i = 0; i < globExpansion.Length; i++)
{
globExpansion[i] = Path.Combine(itemSpecDirectoryPart, globExpansion[i]);
}
}
var projectSpecs = new[]
{
$@"<Project>
<ItemGroup>
<i Include=`{Path.Combine("{0}", "**", "*.cs")}`/>
</ItemGroup>
</Project>",
$@"<Project>
<ItemGroup>
<i Include=`{Path.Combine("{0}", "**", "*.cs")}`/>
</ItemGroup>
</Project>"
}
.Select(p => string.Format(p, itemSpecDirectoryPart))
.Select((p, i) => new ProjectSpecification(Path.Combine(testDirectory.Path, $"ProjectDirectory{i}", $"Project{i}.proj"), p));
var context = EvaluationContext.Create(policy);
var evaluationCount = 0;
File.WriteAllText(Path.Combine(globDirectory.Path, $"{evaluationCount}.cs"), "");
EvaluateProjects(
projectSpecs,
context,
project =>
{
var expectedGlobExpansion = expectedGlobExpansions[evaluationCount];
evaluationCount++;
File.WriteAllText(Path.Combine(globDirectory.Path, $"{evaluationCount}.cs"), "");
ObjectModelHelpers.AssertItems(expectedGlobExpansion, project.GetItems("i"));
}
);
}
private static string[] _projectsWithGlobImports =
{
@"<Project>
<Import Project=`*.props` />
</Project>",
@"<Project>
<Import Project=`*.props` />
</Project>",
};
[Theory]
[MemberData(nameof(ContextPinsGlobExpansionCacheData))]
public void ContextCachesImportGlobExpansions(EvaluationContext.SharingPolicy policy, string[][] expectedGlobExpansions)
{
var projectDirectory = _env.DefaultTestDirectory.Path;
var context = EvaluationContext.Create(policy);
var evaluationCount = 0;
File.WriteAllText(Path.Combine(projectDirectory, $"{evaluationCount}.props"), $"<Project><ItemGroup><i Include=`{evaluationCount}.cs`/></ItemGroup></Project>".Cleanup());
EvaluateProjects(
_projectsWithGlobImports,
context,
project =>
{
var expectedGlobExpansion = expectedGlobExpansions[evaluationCount];
evaluationCount++;
File.WriteAllText(Path.Combine(projectDirectory, $"{evaluationCount}.props"), $"<Project><ItemGroup><i Include=`{evaluationCount}.cs`/></ItemGroup></Project>".Cleanup());
ObjectModelHelpers.AssertItems(expectedGlobExpansion, project.GetItems("i"));
}
);
}
private static string[] _projectsWithConditions =
{
@"<Project>
<PropertyGroup Condition=`Exists('0.cs')`>
<p>val</p>
</PropertyGroup>
</Project>",
@"<Project>
<PropertyGroup Condition=`Exists('0.cs')`>
<p>val</p>
</PropertyGroup>
</Project>",
};
[Theory]
[InlineData(EvaluationContext.SharingPolicy.Isolated)]
[InlineData(EvaluationContext.SharingPolicy.Shared)]
public void ContextCachesExistenceChecksInConditions(EvaluationContext.SharingPolicy policy)
{
var projectDirectory = _env.DefaultTestDirectory.Path;
var context = EvaluationContext.Create(policy);
var theFile = Path.Combine(projectDirectory, "0.cs");
File.WriteAllText(theFile, "");
var evaluationCount = 0;
EvaluateProjects(
_projectsWithConditions,
context,
project =>
{
evaluationCount++;
if (File.Exists(theFile))
{
File.Delete(theFile);
}
if (evaluationCount == 1)
{
project.GetPropertyValue("p").ShouldBe("val");
}
else
switch (policy)
{
case EvaluationContext.SharingPolicy.Shared:
project.GetPropertyValue("p").ShouldBe("val");
break;
case EvaluationContext.SharingPolicy.Isolated:
project.GetPropertyValue("p").ShouldBeEmpty();
break;
default:
throw new ArgumentOutOfRangeException(nameof(policy), policy, null);
}
}
);
}
[Theory]
[InlineData(EvaluationContext.SharingPolicy.Isolated)]
[InlineData(EvaluationContext.SharingPolicy.Shared)]
public void ContextCachesExistenceChecksInGetDirectoryNameOfFileAbove(EvaluationContext.SharingPolicy policy)
{
var context = EvaluationContext.Create(policy);
var subdirectory = _env.DefaultTestDirectory.CreateDirectory("subDirectory");
var subdirectoryFile = subdirectory.CreateFile("a");
_env.DefaultTestDirectory.CreateFile("a");
int evaluationCount = 0;
EvaluateProjects(
new []
{
$@"<Project>
<PropertyGroup>
<SearchedPath>$([MSBuild]::GetDirectoryNameOfFileAbove('{subdirectory.Path}', 'a'))</SearchedPath>
</PropertyGroup>
</Project>"
},
context,
project =>
{
evaluationCount++;
var searchedPath = project.GetProperty("SearchedPath");
switch (policy)
{
case EvaluationContext.SharingPolicy.Shared:
searchedPath.EvaluatedValue.ShouldBe(subdirectory.Path);
break;
case EvaluationContext.SharingPolicy.Isolated:
searchedPath.EvaluatedValue.ShouldBe(
evaluationCount == 1
? subdirectory.Path
: _env.DefaultTestDirectory.Path);
break;
default:
throw new ArgumentOutOfRangeException(nameof(policy), policy, null);
}
if (evaluationCount == 1)
{
// this will cause the upper file to get picked up in the Isolated policy
subdirectoryFile.Delete();
}
});
evaluationCount.ShouldBe(2);
}
[Theory]
[InlineData(EvaluationContext.SharingPolicy.Isolated)]
[InlineData(EvaluationContext.SharingPolicy.Shared)]
public void ContextCachesExistenceChecksInGetPathOfFileAbove(EvaluationContext.SharingPolicy policy)
{
var context = EvaluationContext.Create(policy);
var subdirectory = _env.DefaultTestDirectory.CreateDirectory("subDirectory");
var subdirectoryFile = subdirectory.CreateFile("a");
var rootFile = _env.DefaultTestDirectory.CreateFile("a");
int evaluationCount = 0;
EvaluateProjects(
new []
{
$@"<Project>
<PropertyGroup>
<SearchedPath>$([MSBuild]::GetPathOfFileAbove('a', '{subdirectory.Path}'))</SearchedPath>
</PropertyGroup>
</Project>"
},
context,
project =>
{
evaluationCount++;
var searchedPath = project.GetProperty("SearchedPath");
switch (policy)
{
case EvaluationContext.SharingPolicy.Shared:
searchedPath.EvaluatedValue.ShouldBe(subdirectoryFile.Path);
break;
case EvaluationContext.SharingPolicy.Isolated:
searchedPath.EvaluatedValue.ShouldBe(
evaluationCount == 1
? subdirectoryFile.Path
: rootFile.Path);
break;
default:
throw new ArgumentOutOfRangeException(nameof(policy), policy, null);
}
if (evaluationCount == 1)
{
// this will cause the upper file to get picked up in the Isolated policy
subdirectoryFile.Delete();
}
});
evaluationCount.ShouldBe(2);
}
private void EvaluateProjects(IEnumerable<string> projectContents, EvaluationContext context, Action<Project> afterEvaluationAction)
{
EvaluateProjects(
projectContents.Select((p, i) => new ProjectSpecification(Path.Combine(_env.DefaultTestDirectory.Path, $"Project{i}.proj"), p)),
context,
afterEvaluationAction);
}
private struct ProjectSpecification
{
public string ProjectFilePath { get; }
public string ProjectContents { get; }
public ProjectSpecification(string projectFilePath, string projectContents)
{
ProjectFilePath = projectFilePath;
ProjectContents = projectContents;
}
public void Deconstruct(out string projectPath, out string projectContents)
{
projectPath = this.ProjectFilePath;
projectContents = this.ProjectContents;
}
}
/// <summary>
/// Should be at least two test projects to test cache visibility between projects
/// </summary>
private void EvaluateProjects(IEnumerable<ProjectSpecification> projectSpecs, EvaluationContext context, Action<Project> afterEvaluationAction)
{
var collection = _env.CreateProjectCollection().Collection;
var projects = new List<Project>();
foreach (var (projectFilePath, projectContents) in projectSpecs)
{
Directory.CreateDirectory(Path.GetDirectoryName(projectFilePath));
File.WriteAllText(projectFilePath, projectContents.Cleanup());
var project = Project.FromFile(
projectFilePath,
new ProjectOptions
{
ProjectCollection = collection,
EvaluationContext = context,
LoadSettings = ProjectLoadSettings.IgnoreMissingImports
});
afterEvaluationAction?.Invoke(project);
projects.Add(project);
}
foreach (var project in projects)
{
project.AddItem("a", "b");
project.ReevaluateIfNecessary(context);
afterEvaluationAction?.Invoke(project);
}
}
}
}
| 40.3381 | 190 | 0.524752 | [
"MIT"
] | BenVillalobos/msbuild | src/Build.UnitTests/Definition/ProjectEvaluationContext_Tests.cs | 39,491 | C# |
using AConfig;
using NeoCortexApi.Entities;
using NeoCortexApi;
using NeoCortexApi.Network;
using NeoCortexApi.Utility;
using Daenet.ImageBinarizerLib;
using Daenet.ImageBinarizerLib.Entities;
namespace ConsoleApp
{
internal class Experiment
{
HtmConfig htmConfig;
ArgsConfig expConfig;
public Experiment(ArgsConfig config)
{
expConfig = config;
htmConfig = config.htmConfig;
}
public void run()
{
int height = htmConfig.InputDimensions[0];
int width = htmConfig.InputDimensions[1];
// By default it only returns subdirectories one level deep.
var directories = Directory.GetDirectories(expConfig.inputFolder).ToList();
(Dictionary<string, int[]> binaries, // List of Binarized images
Dictionary<string, List<string>> inputsPath // Path of the list of images found in the given folder
) = imageBinarization(directories, width, height);
// The key of the dictionary helps to keep track of which class the SDR belongs to
(Dictionary<string, int[]> sdrs, var cortexLayer) = SPTrain(htmConfig, binaries);
//(Dictionary<string, int[]> sdrs2, var cortexLayer2) = SPTrain(htmConfig, binaries, colorThreshold );
HelpersTemp helperFunc = new HelpersTemp();
Dictionary<string, double> listCorrelation = new();
Dictionary<string, double> listInputCorrelation = new();
foreach (KeyValuePair<string, List<string>> entry in inputsPath) // loop of the folder (classes) eg: Apple, banana, etc
{
var classLabel = entry.Key;
var filePathList = entry.Value;
var numberOfImages = filePathList.Count;
for (int i = 0; i < numberOfImages; i++) // loop of the images inside the folder
{
if (!sdrs.TryGetValue(filePathList[i], out int[] sdr1)) continue;
foreach (KeyValuePair<string, List<string>> secondEntry in inputsPath)
{ // loop of the folder (again)
var classLabel2 = secondEntry.Key;
var filePathList2 = secondEntry.Value;
var numberOfImages2 = filePathList2.Count;
for (int j = 0; j < numberOfImages2; j++) // loop of the images inside the folder
{
if (!sdrs.TryGetValue(filePathList2[j], out int[] sdr2)) continue;
string fileNameofFirstImage = Path.GetFileNameWithoutExtension(filePathList[i]);
string fileNameOfSecondImage = Path.GetFileNameWithoutExtension(filePathList2[j]);
string temp = $"{classLabel + fileNameofFirstImage}__{classLabel2 + fileNameOfSecondImage}";
listCorrelation.Add(temp, MathHelpers.CalcArraySimilarity(sdr1, sdr2));
listInputCorrelation.Add(temp, MathHelpers.CalcArraySimilarity(binaries[filePathList[i]].IndexWhere((el) => el == 1), binaries[filePathList2[j]].IndexWhere((el) => el == 1)));
}
}
}
}
var classes = inputsPath.Keys.ToList();
//helperFunc.printSimilarityMatrix(listCorrelation, "micro", classes);
//helperFunc.printSimilarityMatrix(listCorrelation, "macro", classes);
helperFunc.printSimilarityMatrix(listCorrelation, "both", classes);
//--------------------------PredictionCode--------------------------//
// Extracting the prediction images from the project directory
// Fetch the filepath and images from the PredictInputFolder
var currentDirList = Directory.GetDirectories(Directory.GetCurrentDirectory()).ToList();
var predictImageFilePath = currentDirList.Find(x => x.Contains("PredictInputFolder"));
var predictInputImages = Directory.GetFiles(predictImageFilePath).Where(name => !name.EndsWith(".txt")).ToList();
//Predict the similarity between the train model object to the predictInputImages
PredictionSimilarity(height, width, inputsPath, sdrs, cortexLayer, predictInputImages);
//--------------------------End of PredictionCode--------------------------//
}
private Tuple<Dictionary<string, int[]>, Dictionary<string, List<string>>> imageBinarization(List<string> directories, int width, int height)
{
Dictionary<string, List<string>> inputsPath = new Dictionary<string, List<string>>();
Dictionary<string, int[]> binaries = new Dictionary<string, int[]>();
foreach (var fullPath in directories)
{
string folderName = Path.GetFileName(fullPath);
if (!inputsPath.ContainsKey(folderName))
{
inputsPath[folderName] = new List<string>();
}
var filePathList = Directory.GetFiles(fullPath).Where(name => !name.EndsWith(".txt")).ToList();
foreach (var filePath in filePathList)
{
inputsPath[folderName].Add(filePath);
// Image binarization
int[] inputVector = ReadImageData(filePath, height, width);
string[] savedVector = ConvertToString(inputVector, height, width);
// Write binarized data to a file
var baseDir = Path.GetDirectoryName(filePath);
var fileNameWithoutExt = Path.GetFileNameWithoutExtension(filePath);
var ext = "txt";
var fullFileName = $"{fileNameWithoutExt}.{ext}";
binaries.Add(filePath, inputVector);
System.IO.File.WriteAllLines(Path.Combine(baseDir, fullFileName), savedVector);
}
}
return Tuple.Create(binaries, inputsPath);
}
private string[] ConvertToString(int[] inputVector, int height, int width)
{
string[] vs = new string[width];
for (int j = 0; j < height; j++)
{
for (int i = 0; i < width; i++)
{
vs[i] += inputVector[j * width + i].ToString() + ',';
}
}
return vs;
}
/// <summary>
/// Returns Binarized Image in integer array
/// </summary>
/// <param name="imagePath">Name of Image to be binarized</param>
/// <param name="height">Height of Binarized Image</param>
/// <param name="width">Width of Binarized Image</param>
/// <returns></returns>
public int[] ReadImageData(string imagePath, int height, int width)
{
var parameters = new BinarizerParams
{
InputImagePath = imagePath,
ImageHeight = height,
ImageWidth = width,
//BlueThreshold = 200,
//RedThreshold = 200,
//GreenThreshold = 200
};
ImageBinarizer bizer = new ImageBinarizer(parameters);
var doubleArray = bizer.GetArrayBinary();
var hg = doubleArray.GetLength(1);
var wd = doubleArray.GetLength(0);
var intArray = new int[hg * wd];
for (int j = 0; j < hg; j++)
{
for (int i = 0; i < wd; i++)
{
intArray[j * wd + i] = (int)doubleArray[i, j, 0];
}
}
return intArray;
}
/// <summary> Modified by Long Nguyen
/// Pulling out SDRs after HPC fires a STABLE event when training the SP with list of patterns
/// </summary>
/// <param name="cfg"></param> Spatial Pooler configuration by HtmConfig style
/// <param name="inputValues"></param> Binary input vector (pattern) list
private static (Dictionary<string, int[]>, CortexLayer<object, object> cortexLayer) SPTrain(HtmConfig cfg, Dictionary<string, int[]> inputValues)
{
// Creates the htm memory.
var mem = new Connections(cfg);
bool isInStableState = false;
// HPC extends the default Spatial Pooler algorithm.
// The purpose of HPC is to set the SP in the new-born stage at the begining of the learning process.
// In this stage the boosting is very active, but the SP behaves instable. After this stage is over
// (defined by the second argument) the HPC is controlling the learning process of the SP.
// Once the SDR generated for every input gets stable, the HPC will fire event that notifies your code
// that SP is stable now.
HomeostaticPlasticityController hpa = new HomeostaticPlasticityController(mem, inputValues.Count * 40,
(isStable, numPatterns, actColAvg, seenInputs) =>
{
// Event should only be fired when entering the stable state.
// Ideal SP should never enter unstable state after stable state.
if (isStable == false)
{
Console.WriteLine($"INSTABLE STATE");
// This should usually not happen.
isInStableState = false;
}
else
{
Console.WriteLine($"STABLE STATE");
// Here you can perform any action if required.
isInStableState = true;
}
});
// It creates the instance of Spatial Pooler Multithreaded version.
SpatialPooler sp = new SpatialPoolerMT(hpa);
// Initializes the Spatial Pooler
sp.Init(mem, new DistributedMemory() { ColumnDictionary = new InMemoryDistributedDictionary<int, NeoCortexApi.Entities.Column>(1) });
// mem.TraceProximalDendritePotential(true);
// It creates the instance of the neo-cortex layer.
// Algorithm will be performed inside of that layer.
CortexLayer<object, object> cortexLayer = new CortexLayer<object, object>("L1");
// Add encoder as the very first module. This model is connected to the sensory input cells
// that receive the input. Encoder will receive the input and forward the encoded signal
// to the next module.
//cortexLayer.HtmModules.Add("encoder", encoder);
// The next module in the layer is Spatial Pooler. This module will receive the output of the
// encoder.
cortexLayer.HtmModules.Add("sp", sp);
// Learning process will take 1000 iterations (cycles)
int maxSPLearningCycles = 1000;
// Save the result SDR into a list of array
Dictionary<string, int[]> outputValues = new Dictionary<string, int[]>();
for (int cycle = 0; cycle < maxSPLearningCycles; cycle++)
{
Console.WriteLine($"Cycle ** {cycle} ** Stability: {isInStableState}");
int iteration = 0;
outputValues.Clear(); // Remove all elements in output SDR list
// This trains the layer on input pattern.
foreach (var input in inputValues)
{
iteration++;
// Learn the input pattern.
// Output lyrOut is the output of the last module in the layer.
var lyrOut = cortexLayer.Compute(input.Value, true) as ComputeCycle;
// This is a general way to get the SpatialPooler result from the layer.
var activeColumns = cortexLayer.GetResult("sp") as int[];
var actCols = activeColumns.OrderBy(c => c).ToArray();
outputValues[input.Key] = actCols;
}
if (isInStableState)
break;
}
return (outputValues, cortexLayer);
}
//--------------------------Prediction Methods--------------------------//
/// <summary>
/// This method loops between all the images that need to be predicted by the
/// trained model and displays the similarity between the trained objects and input images
/// </summary>
/// <param name="height">input image height</param>
/// <param name="width">input image width</param>
/// <param name="inputsPath">path of the trained model images</param>
/// <param name="sdrs">sdrs of the rained model images</param>
/// <param name="cortexLayer"></param>
/// <param name="predictInputImages">Input images that are to be predicted by trained model</param>
private void PredictionSimilarity(int height, int width, Dictionary<string, List<string>> inputsPath, Dictionary<string, int[]> sdrs, CortexLayer<object, object>? cortexLayer, List<string> predictInputImages)
{
// loop for the images that needs to be predicted by the trained model
foreach (var predictfilePath in predictInputImages)
{
// Fetching the predict input image file name
var predictImageNameWithoutExt = Path.GetFileNameWithoutExtension(predictfilePath);
// input image encoding and learn the input pattern
int[] encodedInputImage = ReadImageData(predictfilePath, width, height);
cortexLayer.Compute(encodedInputImage, false);
var activeColumns = cortexLayer.GetResult("sp") as int[];
var sdrOfInputImage = activeColumns.OrderBy(c => c).ToArray();
// Comparing the trained model sdrs to the input image sdr
Dictionary<string, string> predictedSimilarityList = PredictLabel(inputsPath, sdrs, sdrOfInputImage);
// Displaying the prediction result
Console.WriteLine($"\nThe predicted results for the input image \"{predictImageNameWithoutExt}\" is");
predictedSimilarityList.Select(i => $"{i.Key}: {i.Value}").ToList().ForEach(Console.WriteLine);
}
}
/// <summary>
/// This method compares the sdrs from the trained model to the input image sdr
/// By Team CrustyCrab
/// </summary>
/// <param name="objectPath">trained model images inputpath</param>
/// <param name="sdrs">trained image sdrs</param>
/// <param name="sdrOfInputImage">sdr of the input images that needs to be predicted</param>
/// <returns>dictionary with key as object class and value as the correlation between input image and trained object class</returns>
public Dictionary<string, string> PredictLabel(Dictionary<string, List<string>> objectPath, Dictionary<string, int[]> sdrs, int[] sdrOfInputImage)
{
// Dictionary to store the result of the corelation values of different trained model objects
Dictionary<string, string> objectSimilarityList = new();
// loop of trained object images
foreach (KeyValuePair<string, List<string>> entry in objectPath)
{
// Extracting the trained object class and file paths from the objectpath dictionary
var classLabel = entry.Key;
var filePathList = entry.Value;
var numberOfImages = filePathList.Count;
// list to store the similarity values between the predict input image to trained images of an object
List<double> similarityList = new();
// Result string to format all the similartity values
String resultString = "";
// loop for comparing the given input image sdr to trained image sdr
for (int i = 0; i < numberOfImages; i++)
{
if (!sdrs.TryGetValue(filePathList[i], out int[] sdr)) continue;
// calculating and storing the similarity between the given input image sdr to trained image sdr
double inputSimilarity = MathHelpers.CalcArraySimilarity(sdrOfInputImage, sdr);
// adding the inputSimilarity values to the similarityList of an object class
similarityList.Add(inputSimilarity);
}
// Storing the maximum, average and minimum value from the similarityList and adding it to result dictionary
resultString = "\tMax:" + Math.Round(similarityList.Max(), 2) + "%\tAvg:" + Math.Round(similarityList.Average(), 2) + "%\tMin:" + Math.Round(similarityList.Min(), 2) + "%";
objectSimilarityList.Add(classLabel, resultString);
}
return objectSimilarityList;
}
//--------------------------End of Prediction Methods--------------------------//
}
} | 49.83526 | 216 | 0.5749 | [
"Apache-2.0"
] | GurunagSai/neocortexapi-classification | ImageClassification/ImageClassification/Experiment.cs | 17,245 | C# |
using System;
using System.Net;
using OC.DiscordBotServer.Models;
using Discord.Commands;
using Transfer;
using System.Net.Sockets;
using OCUnion;
using Util;
using OC.DiscordBotServer.Common;
using OC.DiscordBotServer.Helpers;
namespace OC.DiscordBotServer.Commands
{
public class RegCommand : ICommand
{
private readonly ApplicationContext _appContext;
public RegCommand(ApplicationContext appContext)
{
_appContext = appContext;
}
protected string CanExecute(SocketCommandContext context, string ip, string token, out IPEndPoint serverAdr)
{
// RU: Проверка на дурака: такой сервер не зарегистрирован, и сервер живой
// RU: Регистрируем сервер и сохраняем параметры: в виде таблицы: IDканала, IPserver
serverAdr = Helper.TryParseStringToIp(ip);
if (serverAdr == null)
{
return Languages.Translator.ErrInvalidIP;
}
if (_appContext.DiscrordToOCServer.TryGetValue(context.Channel.Id, out SessionClientWrapper server2Chanel))
{
if (!ip.Equals(server2Chanel.Chanel2Server.IP))
{
return Languages.Translator.ErrTryAddToExistChannel + $"{server2Chanel.Chanel2Server.IP}, Register on new discrord channel pls ";
}
else
{
// TO DO: if ip is eqauls,
return Languages.Translator.ErrTryAddToExistChannel + $"{server2Chanel.Chanel2Server.IP}, Register on new discrord channel pls ";
}
}
if (context.IsPrivate)
{
return Languages.Translator.InfResctrictInPrivate;
}
if (!Guid.TryParse(token, out Guid guidToken))
{
return Languages.Translator.ErrInvalidToken;
}
return string.Empty;
}
public string Execute(SocketCommandContext context, string ip, string token)
{
try
{
IPEndPoint serverAdr;
var message = CanExecute(context, ip, token, out serverAdr);
if (!string.IsNullOrEmpty(message))
{
return message;
}
try
{
new TcpClient(serverAdr.Address.ToString(), serverAdr.Port);
}
catch
(Exception ex)
{
return Languages.Translator.ErrServerNotAvailable + "\n" + ex.Message;
}
var client = new SessionClient();
if (!client.Connect(serverAdr.Address.ToString(), serverAdr.Port))
{
return Languages.Translator.ErrServerNotAvailable;
}
var pass = new CryptoProvider().GetHash(token);
if (!client.Login(SessionClientWrapper.DiscrodLogin, pass, null))
{
return Languages.Translator.ErrInvalidToken;
}
var channelToServer = new Chanel2Server()
{
Id = context.Channel.Id,
IP = serverAdr.Address.ToString(),
Port = serverAdr.Port,
LinkCreator = context.Message.Author.Id,
LastOnlineTime = DateTime.UtcNow.AddDays(-1),
Token = token,
LastRecivedPostIndex = -1,
};
//
_appContext.RegisterNewServer(channelToServer, new SessionClientWrapper(channelToServer, client));
context.Message.DeleteAsync();
return string.Format(Languages.Translator.InfServerReg, serverAdr.ToString(), "#" + context.Channel.Name);
}
catch (Exception ex)
{
Loger.Log(ex.ToString());
return "Internal error";
}
}
}
}
| 34.159664 | 149 | 0.536777 | [
"Apache-2.0"
] | AantCoder/OnlineCity | Source/DiscordChatBotServer/Commands/RegCommand.cs | 4,178 | C# |
using Dock.Model;
using System;
namespace Stride.Editor.Presentation.VirtualDom.Controls.Dock
{
public class DockControl : ViewBuilder<global::Dock.Avalonia.Controls.DockControl>
{
public IDock Layout
{
set { Property(global::Dock.Avalonia.Controls.DockControl.LayoutProperty, value); }
}
}
}
| 24.5 | 95 | 0.682216 | [
"MIT"
] | manio143/StrideComponentsEditorAvalonia | Stride.Editor.Presentation.VirtualDom/Controls/Dock/DockControl.cs | 345 | C# |
using Hive.SeedWorks.Characteristics;
namespace Hive.SeedWorks.TacticalPatterns
{
/// <summary>
/// Агрегат.
/// </summary>
/// <typeparam name="TBoundedContext">Ограниченный контест.</typeparam>
public interface IAggregate<TBoundedContext> :
IComplexKey,
ICommandSubject,
IAnemicModel<TBoundedContext>,
IBoundedContextScope<TBoundedContext>
where TBoundedContext : IBoundedContext
{
}
}
| 24.157895 | 75 | 0.67756 | [
"MIT"
] | Ekstrem/Hive | Source/TacticalPatterns/IAggregate.cs | 487 | C# |
#region Auto-generated classes for PicParamDb database on 2010-03-30 10:11:04Z
//
// ____ _ __ __ _ _
// | _ \| |__ | \/ | ___| |_ __ _| |
// | | | | '_ \| |\/| |/ _ \ __/ _` | |
// | |_| | |_) | | | | __/ || (_| | |
// |____/|_.__/|_| |_|\___|\__\__,_|_|
//
// Auto-generated from PicParamDb on 2010-03-30 10:11:04Z
// Please visit http://linq.to/db for more information
#endregion
using System;
using System.Data;
using System.Data.Linq.Mapping;
using System.Diagnostics;
using System.Reflection;
#if MONO_STRICT
using System.Data.Linq;
#else // MONO_STRICT
using DbLinq.Data.Linq;
using DbLinq.Vendor;
#endif // MONO_STRICT
using System.ComponentModel;
namespace Pic.DAL
{
public partial class PicParamDbDataContext : DataContext
{
#region Extensibility Method Definitions
partial void OnCreated();
#endregion
public PicParamDbDataContext(string connectionString)
: base(connectionString)
{
OnCreated();
}
public PicParamDbDataContext(IDbConnection connection)
#if MONO_STRICT
: base(connection)
#else // MONO_STRICT
: base(connection, new DbLinq.SqlServer.SqlServerVendor())
#endif // MONO_STRICT
{
OnCreated();
}
public PicParamDbDataContext(string connection, MappingSource mappingSource)
: base(connection, mappingSource)
{
OnCreated();
}
public PicParamDbDataContext(IDbConnection connection, MappingSource mappingSource)
: base(connection, mappingSource)
{
OnCreated();
}
#if !MONO_STRICT
public PicParamDbDataContext(IDbConnection connection, IVendor vendor)
: base(connection, vendor)
{
OnCreated();
}
#endif // !MONO_STRICT
#if !MONO_STRICT
public PicParamDbDataContext(IDbConnection connection, MappingSource mappingSource, IVendor vendor)
: base(connection, mappingSource, vendor)
{
OnCreated();
}
#endif // !MONO_STRICT
public Table<CardboardProfile> CardboardProfiles { get { return GetTable<CardboardProfile>(); } }
public Table<CardboardQuality> CardboardQualities { get { return GetTable<CardboardQuality>(); } }
public Table<Component> Components { get { return GetTable<Component>(); } }
public Table<ComponentDependancy> ComponentDependancies { get { return GetTable<ComponentDependancy>(); } }
public Table<DataVersion> DataVersions { get { return GetTable<DataVersion>(); } }
public Table<Document> Documents { get { return GetTable<Document>(); } }
public Table<DocumentType> DocumentTypes { get { return GetTable<DocumentType>(); } }
public Table<File> Files { get { return GetTable<File>(); } }
public Table<Majoration> Majorations { get { return GetTable<Majoration>(); } }
public Table<MajorationSet> MajorationSets { get { return GetTable<MajorationSet>(); } }
public Table<MajorationSet1> MajorationSet1s { get { return GetTable<MajorationSet1>(); } }
public Table<Thumbnail> Thumbnails { get { return GetTable<Thumbnail>(); } }
public Table<TreeNode> TreeNodes { get { return GetTable<TreeNode>(); } }
public Table<TreeNodeDocument> TreeNodeDocuments { get { return GetTable<TreeNodeDocument>(); } }
}
[Table(Name = "dbo.CardboardProfile")]
public partial class CardboardProfile : INotifyPropertyChanging, INotifyPropertyChanged
{
#region INotifyPropertyChanging handling
public event PropertyChangingEventHandler PropertyChanging;
private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs("");
protected virtual void SendPropertyChanging()
{
if (PropertyChanging != null)
{
PropertyChanging(this, emptyChangingEventArgs);
}
}
#endregion
#region INotifyPropertyChanged handling
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void SendPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
#region Extensibility Method Definitions
partial void OnCreated();
partial void OnChanged();
partial void OnChanging(int value);
partial void OnChanged();
partial void OnChanging(string value);
partial void OnChanged();
partial void OnChanging(string value);
partial void OnChanged();
partial void OnChanging(float value);
#endregion
#region int
[DebuggerNonUserCode]
[Column(Storage = null, Name = "ID", DbType = "Int NOT NULL IDENTITY", IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.Never, CanBeNull = false)]
public int
{
get; set;
}
#endregion
#region string
[DebuggerNonUserCode]
[Column(Storage = null, Name = "Name", DbType = "NVarChar(50) NOT NULL", AutoSync = AutoSync.Never, CanBeNull = false)]
public string
{
get; set;
}
#endregion
#region string
[DebuggerNonUserCode]
[Column(Storage = null, Name = "Code", DbType = "NChar(10) NOT NULL", AutoSync = AutoSync.Never, CanBeNull = false)]
public string
{
get; set;
}
#endregion
#region float
[DebuggerNonUserCode]
[Column(Storage = null, Name = "Thickness", DbType = "Real NOT NULL", AutoSync = AutoSync.Never, CanBeNull = false)]
public float
{
get; set;
}
#endregion
#region Children
[Association(Storage = null, OtherKey = "CardboardProfileID", ThisKey = "ID", Name = "CardboardProfile_CardboardQuality")]
[DebuggerNonUserCode]
public EntitySet<CardboardQuality> CardboardQualities
{
get; set;
}
[Association(Storage = null, OtherKey = "CardboardProfileID", ThisKey = "ID", Name = "CardboardProfile_MajorationSet")]
[DebuggerNonUserCode]
public EntitySet<MajorationSet> MajorationSets
{
get; set;
}
[Association(Storage = null, OtherKey = "CardboardProfileID", ThisKey = "ID", Name = "CardboardProfile_MajorationSet1")]
[DebuggerNonUserCode]
public EntitySet<MajorationSet1> MajorationSet1s
{
get; set;
}
#endregion
#region Attachement handlers
private void CardboardQualities_Attach(CardboardQuality entity)
{
entity.CardboardProfile = this;
}
private void CardboardQualities_Detach(CardboardQuality entity)
{
entity.CardboardProfile = null;
}
private void MajorationSets_Attach(MajorationSet entity)
{
entity.CardboardProfile = this;
}
private void MajorationSets_Detach(MajorationSet entity)
{
entity.CardboardProfile = null;
}
private void MajorationSet1s_Attach(MajorationSet1 entity)
{
entity.CardboardProfile = this;
}
private void MajorationSet1s_Detach(MajorationSet1 entity)
{
entity.CardboardProfile = null;
}
#endregion
#region ctor
public CardboardProfile()
{
CardboardQualities = new EntitySet<CardboardQuality>(CardboardQualities_Attach, CardboardQualities_Detach);
MajorationSets = new EntitySet<MajorationSet>(MajorationSets_Attach, MajorationSets_Detach);
MajorationSet1s = new EntitySet<MajorationSet1>(MajorationSet1s_Attach, MajorationSet1s_Detach);
OnCreated();
}
#endregion
}
[Table(Name = "dbo.CardboardQuality")]
public partial class CardboardQuality : INotifyPropertyChanging, INotifyPropertyChanged
{
#region INotifyPropertyChanging handling
public event PropertyChangingEventHandler PropertyChanging;
private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs("");
protected virtual void SendPropertyChanging()
{
if (PropertyChanging != null)
{
PropertyChanging(this, emptyChangingEventArgs);
}
}
#endregion
#region INotifyPropertyChanged handling
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void SendPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
#region Extensibility Method Definitions
partial void OnCreated();
partial void OnChanged();
partial void OnChanging(int value);
partial void OnChanged();
partial void OnChanging(int value);
partial void OnChanged();
partial void OnChanging(string value);
partial void OnChanged();
partial void OnChanging(string value);
partial void OnChanged();
partial void OnChanging(float value);
partial void OnChanged();
partial void OnChanging(float value);
partial void OnChanged();
partial void OnChanging(float value);
partial void OnChanged();
partial void OnChanging(float value);
partial void OnChanged();
partial void OnChanging(float value);
#endregion
#region int
[DebuggerNonUserCode]
[Column(Storage = null, Name = "ID", DbType = "Int NOT NULL IDENTITY", IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.Never, CanBeNull = false)]
public int
{
get; set;
}
#endregion
#region int
[DebuggerNonUserCode]
[Column(Storage = null, Name = "CardboardProfileID", DbType = "Int NOT NULL", AutoSync = AutoSync.Never, CanBeNull = false)]
public int
{
get; set;
}
#endregion
#region string
[DebuggerNonUserCode]
[Column(Storage = null, Name = "Name", DbType = "NVarChar(50) NOT NULL", AutoSync = AutoSync.Never, CanBeNull = false)]
public string
{
get; set;
}
#endregion
#region string
[DebuggerNonUserCode]
[Column(Storage = null, Name = "Description", DbType = "NVarChar(MAX) NOT NULL", AutoSync = AutoSync.Never, CanBeNull = false)]
public string
{
get; set;
}
#endregion
#region float
[DebuggerNonUserCode]
[Column(Storage = null, Name = "SurfacicMass", DbType = "Real NOT NULL", AutoSync = AutoSync.Never, CanBeNull = false)]
public float
{
get; set;
}
#endregion
#region float
[DebuggerNonUserCode]
[Column(Storage = null, Name = "RigidityX", DbType = "Real NOT NULL", AutoSync = AutoSync.Never, CanBeNull = false)]
public float
{
get; set;
}
#endregion
#region float
[DebuggerNonUserCode]
[Column(Storage = null, Name = "RigidityY", DbType = "Real NOT NULL", AutoSync = AutoSync.Never, CanBeNull = false)]
public float
{
get; set;
}
#endregion
#region float
[DebuggerNonUserCode]
[Column(Storage = null, Name = "YoungModulus", DbType = "Real NOT NULL", AutoSync = AutoSync.Never, CanBeNull = false)]
public float
{
get; set;
}
#endregion
#region float
[DebuggerNonUserCode]
[Column(Storage = null, Name = "ECT", DbType = "Real NOT NULL", AutoSync = AutoSync.Never, CanBeNull = false)]
public float
{
get; set;
}
#endregion
#region Parents
private EntityRef<CardboardProfile> ;
[Association(Storage = null, OtherKey = "ID", ThisKey = "CardboardProfileID", Name = "CardboardProfile_CardboardQuality", IsForeignKey = true)]
[DebuggerNonUserCode]
public CardboardProfile CardboardProfile
{
get
{
return .Entity;
}
set
{
if (value != .Entity)
{
if (.Entity != null)
{
var previousCardboardProfile = .Entity;
.Entity = null;
previousCardboardProfile.CardboardQualities.Remove(this);
}
.Entity = value;
if (value != null)
{
value.CardboardQualities.Add(this);
}
}
}
#endregion
}
}
| 24.524336 | 162 | 0.71069 | [
"MIT",
"Unlicense"
] | frozenflame83/PLMPackLib | Pic.DAL/Pic.DAL.DataContext.designer.sqlserver.cs | 11,085 | C# |
// ==========================================================================
// PartitioningTests.cs
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex Group
// All rights reserved.
// ==========================================================================
using Xunit;
namespace Squidex.Domain.Apps.Core.Model
{
public sealed class PartitioningTests
{
[Fact]
public void Should_consider_null_as_valid_partitioning()
{
string partitioning = null;
Assert.True(partitioning.IsValidPartitioning());
}
[Fact]
public void Should_consider_invariant_as_valid_partitioning()
{
var partitioning = "invariant";
Assert.True(partitioning.IsValidPartitioning());
}
[Fact]
public void Should_consider_language_as_valid_partitioning()
{
var partitioning = "language";
Assert.True(partitioning.IsValidPartitioning());
}
[Fact]
public void Should_not_consider_empty_as_valid_partitioning()
{
var partitioning = string.Empty;
Assert.False(partitioning.IsValidPartitioning());
}
[Fact]
public void Should_not_consider_other_string_as_valid_partitioning()
{
var partitioning = "invalid";
Assert.False(partitioning.IsValidPartitioning());
}
[Fact]
public void Should_provide_invariant_instance()
{
Assert.Equal("invariant", Partitioning.Invariant.Key);
Assert.Equal("invariant", Partitioning.Invariant.ToString());
}
[Fact]
public void Should_provide_language_instance()
{
Assert.Equal("language", Partitioning.Language.Key);
Assert.Equal("language", Partitioning.Language.ToString());
}
[Fact]
public void Should_make_correct_equal_comparisons()
{
var partitioning1a = new Partitioning("partitioning1");
var partitioning1b = new Partitioning("partitioning1");
var partitioning2a = new Partitioning("partitioning2");
Assert.True(partitioning1a.Equals(partitioning1b));
Assert.False(partitioning1a.Equals(partitioning2a));
}
[Fact]
public void Should_make_correct_object_equal_comparisons()
{
object partitioning1a = new Partitioning("partitioning1");
object partitioning1b = new Partitioning("partitioning1");
object partitioning2a = new Partitioning("partitioning2");
Assert.True(partitioning1a.Equals(partitioning1b));
Assert.False(partitioning1a.Equals(partitioning2a));
}
[Fact]
public void Should_provide_correct_hash_codes()
{
var partitioning1a = new Partitioning("partitioning1");
var partitioning1b = new Partitioning("partitioning1");
var partitioning2a = new Partitioning("partitioning2");
Assert.Equal(partitioning1a.GetHashCode(), partitioning1b.GetHashCode());
Assert.NotEqual(partitioning1a.GetHashCode(), partitioning2a.GetHashCode());
}
}
}
| 31.358491 | 88 | 0.581528 | [
"MIT"
] | maooson/squidex | tests/Squidex.Domain.Apps.Core.Tests/Model/PartitioningTests.cs | 3,326 | C# |
using System;
using System.Collections.Specialized;
using System.Net;
using System.Text;
namespace QuantoAgent.Models {
[Serializable]
public class RestRequest {
readonly string[] acceptTypes;
readonly Encoding contentEncoding;
readonly long contentLength;
readonly string contentType;
readonly CookieCollection cookies;
readonly string httpMethod;
readonly bool isAuthenticated;
readonly bool isLocal;
readonly bool isSecureConnection;
readonly bool isWebSocketRequest;
readonly bool keepAlive;
readonly NameValueCollection queryString;
readonly string rawUrl;
readonly string userAgent;
readonly string userHostAddress;
readonly string userHostName;
readonly string[] userLanguages;
readonly string bodyData;
readonly Uri url;
readonly Uri urlReferrer;
readonly NameValueCollection headers;
//
// Summary:
// Gets the MIME types accepted by the client.
//
// Returns:
// A System.String array that contains the type names specified in the request's
// Accept header or null if the client request did not include an Accept header.
public string[] AcceptTypes { get { return acceptTypes; } }
//
// Summary:
// Gets the content encoding that can be used with data sent with the request
//
// Returns:
// An System.Text.Encoding object suitable for use with the data in the System.Net.HttpListenerRequest.InputStream
// property.
public Encoding ContentEncoding { get { return contentEncoding; } }
//
// Summary:
// Gets the length of the body data included in the request.
//
// Returns:
// The value from the request's Content-Length header. This value is -1 if the content
// length is not known.
public long ContentLength { get { return contentLength; } }
//
// Summary:
// Gets the MIME type of the body data included in the request.
//
// Returns:
// A System.String that contains the text of the request's Content-Type header.
public string ContentType { get { return contentType; } }
//
// Summary:
// Gets the cookies sent with the request.
//
// Returns:
// A System.Net.CookieCollection that contains cookies that accompany the request.
// This property returns an empty collection if the request does not contain cookies.
public CookieCollection Cookies { get { return cookies; } }
//
// Summary:
// Gets the HTTP method specified by the client.
//
// Returns:
// A System.String that contains the method used in the request.
public string HttpMethod { get { return httpMethod; } }
//
// Summary:
// Gets a System.Boolean value that indicates whether the client sending this request
// is authenticated.
//
// Returns:
// true if the client was authenticated; otherwise, false.
public bool IsAuthenticated { get { return isAuthenticated; } }
//
// Summary:
// Gets a System.Boolean value that indicates whether the request is sent from the
// local computer.
//
// Returns:
// true if the request originated on the same computer as the System.Net.HttpListener
// object that provided the request; otherwise, false.
public bool IsLocal { get { return isLocal; } }
//
// Summary:
// Gets a System.Boolean value that indicates whether the TCP connection used to
// send the request is using the Secure Sockets Layer (SSL) protocol.
//
// Returns:
// true if the TCP connection is using SSL; otherwise, false.
public bool IsSecureConnection { get { return isSecureConnection; } }
//
// Summary:
// Gets a System.Boolean value that indicates whether the TCP connection was a WebSocket
// request.
//
// Returns:
// Returns System.Boolean.true if the TCP connection is a WebSocket request; otherwise,
// false.
public bool IsWebSocketRequest { get { return isWebSocketRequest; } }
//
// Summary:
// Gets a System.Boolean value that indicates whether the client requests a persistent
// connection.
//
// Returns:
// true if the connection should be kept open; otherwise, false.
public bool KeepAlive { get { return keepAlive; } }
//
// Summary:
// Gets the query string included in the request.
//
// Returns:
// A System.Collections.Specialized.NameValueCollection object that contains the
// query data included in the request System.Net.HttpListenerRequest.Url.
public NameValueCollection QueryString { get { return queryString; } }
//
// Summary:
// Gets the URL information (without the host and port) requested by the client.
//
// Returns:
// A System.String that contains the raw URL for this request.
public string RawUrl { get { return rawUrl; } }
//
// Summary:
// Gets the user agent presented by the client.
//
// Returns:
// A System.String object that contains the text of the request's User-Agent header.
public string UserAgent { get { return userAgent; } }
//
// Summary:
// Gets the server IP address and port number to which the request is directed.
//
// Returns:
// A System.String that contains the host address information.
public string UserHostAddress { get { return userHostAddress; } }
//
// Summary:
// Gets the DNS name and, if provided, the port number specified by the client.
//
// Returns:
// A System.String value that contains the text of the request's Host header.
public string UserHostName { get { return userHostName; } }
//
// Summary:
// Gets the natural languages that are preferred for the response.
//
// Returns:
// A System.String array that contains the languages specified in the request's
// System.Net.HttpRequestHeader.AcceptLanguage header or null if the client request
// did not include an System.Net.HttpRequestHeader.AcceptLanguage header.
public string[] UserLanguages { get { return userLanguages; } }
//
// Summary:
// Gets the System.Uri object requested by the client.
//
// Returns:
// A System.Uri object that identifies the resource requested by the client.
public Uri Url { get { return url; } }
//
// Summary:
// Gets the Uniform Resource Identifier (URI) of the resource that referred the
// client to the server.
//
// Returns:
// A System.Uri object that contains the text of the request's System.Net.HttpRequestHeader.Referer
// header, or null if the header was not included in the request.
public Uri UrlReferrer { get { return urlReferrer; } }
public string BodyData { get { return bodyData; } }
public NameValueCollection Headers { get { return headers; } }
public RestRequest(HttpListenerRequest request) {
userAgent = request.UserAgent;
userHostAddress = request.UserHostAddress;
userHostName = request.UserHostName;
userLanguages = request.UserLanguages;
url = request.Url;
urlReferrer = request.UrlReferrer;
acceptTypes = request.AcceptTypes;
contentEncoding = request.ContentEncoding;
contentLength = request.ContentLength64;
contentType = request.ContentType;
cookies = request.Cookies;
httpMethod = request.HttpMethod;
isAuthenticated = request.IsAuthenticated;
isLocal = request.IsLocal;
isSecureConnection = request.IsSecureConnection;
isWebSocketRequest = request.IsWebSocketRequest;
keepAlive = request.KeepAlive;
queryString = request.QueryString;
rawUrl = request.RawUrl;
headers = request.Headers;
if (request.HasEntityBody) {
using (System.IO.Stream body = request.InputStream) {
using (System.IO.StreamReader reader = new System.IO.StreamReader(body, request.ContentEncoding)) {
bodyData = reader.ReadToEnd();
}
}
}
}
}
}
| 41.953917 | 126 | 0.594684 | [
"MIT"
] | quan-to/quanto-agent | QuantoAgent/Models/RestRequest.cs | 9,106 | C# |
using CDCavell.ClassLibrary.Web.Identity.Models;
using dis5_cdcavell.Models.AppSettings;
using dis5_cdcavell.Models.TwoFactor;
using Duende.IdentityServer;
using Duende.IdentityServer.Events;
using Duende.IdentityServer.Services;
using Duende.IdentityServer.Stores;
using IdentityModel;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Claims;
using System.Threading.Tasks;
namespace dis5_cdcavell.Controllers
{
/// <summary>
/// External Controller
/// <br /><br />
/// Copyright (c) Duende Software. All rights reserved.
/// See https://duendesoftware.com/license/identityserver.pdf for license information.
/// </summary>
/// <revision>
/// __Revisions:__~~
/// | Contributor | Build | Revison Date | Description |~
/// |-------------|-------|--------------|-------------|~
/// | Christopher D. Cavell | 1.0.2.0 | 01/16/2021 | Initial build |~
/// | Christopher D. Cavell | 1.0.4.3 | 03/21/2021 | 2FA using TOTP |~
/// | Christopher D. Cavell | 1.1.0.0 | 03/28/2021 | Integrate ASP.NET Core Identity |~
/// | Christopher D. Cavell | 1.1.1.0 | 04/06/2021 | Permission-Based Authorization |~
/// </revision>
[AllowAnonymous]
public class ExternalController : ApplicationBaseController<ExternalController>
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly IIdentityServerInteractionService _interaction;
private readonly IClientStore _clientStore;
private readonly IEventService _events;
/// <summary>
/// Constructor method
/// </summary>
/// <param name="logger">ILogger<ExternalController></param>
/// <param name="webHostEnvironment">IWebHostEnvironment</param>
/// <param name="httpContextAccessor">IHttpContextAccessor</param>
/// <param name="interaction">IIdentityServerInteractionService</param>
/// <param name="clientStore">IClientStore</param>
/// <param name="events">IEventService</param>
/// <param name="signInManager">SignInManager<ApplicationUser></param>
/// <param name="userManager">UserManager<ApplicationUser></param>
/// <param name="appSettings">AppSettings</param>
/// <method>
/// AccountController(
/// ILogger<ExternalController> logger,
/// IWebHostEnvironment webHostEnvironment,
/// IHttpContextAccessor httpContextAccessor
/// IIdentityServerInteractionService interaction,
/// IClientStore clientStore,
/// IEventService events,
/// SignInManager<ApplicationUser> signInManager,
/// UserManager<ApplicationUser> userManager,
/// AppSettings appSettings
/// ) : base(logger, webHostEnvironment, httpContextAccessor, appSettings)
/// </method>
public ExternalController(
ILogger<ExternalController> logger,
IWebHostEnvironment webHostEnvironment,
IHttpContextAccessor httpContextAccessor,
IIdentityServerInteractionService interaction,
IClientStore clientStore,
IEventService events,
SignInManager<ApplicationUser> signInManager,
UserManager<ApplicationUser> userManager,
AppSettings appSettings
) : base(logger, webHostEnvironment, httpContextAccessor, appSettings)
{
_userManager = userManager;
_signInManager = signInManager;
_interaction = interaction;
_clientStore = clientStore;
_events = events;
}
/// <summary>
/// initiate roundtrip to external authentication provider
/// </summary>
/// <returns>IActionResult</returns>
/// <method>Challenge(string scheme, string returnUrl)</method>
/// <exception cref="Exception">invalid return URL</exception>
[HttpGet]
public IActionResult Challenge(string scheme, string returnUrl)
{
if (string.IsNullOrEmpty(returnUrl)) returnUrl = _appSettings.Application.MainSiteUrlTrim;
// validate returnUrl - either it is a valid OIDC URL or back to a local page
if (Url.IsLocalUrl(returnUrl) == false && _interaction.IsValidReturnUrl(returnUrl) == false)
{
// user might have clicked on a malicious link - should be logged
throw new Exception("invalid return URL");
}
// start challenge and roundtrip the return URL and scheme
var props = new AuthenticationProperties
{
RedirectUri = Url.Action(nameof(Callback)),
Items =
{
{ "returnUrl", returnUrl },
{ "scheme", scheme },
}
};
return Challenge(props, scheme);
}
/// <summary>
/// Post processing of external authentication
/// </summary>
/// <returns>Task<IActionResult></returns>
/// <method>Callback()</method>
/// <exception cref="Exception">External authentication error</exception>
[HttpGet]
public async Task<IActionResult> Callback()
{
// read external identity from the temporary cookie
var result = await HttpContext.AuthenticateAsync(IdentityServerConstants.ExternalCookieAuthenticationScheme);
if (result?.Succeeded != true)
{
_logger.Exception(result.Failure);
string errMsg = "External authentication error - " + result.Failure.Message;
errMsg += (result.Failure.InnerException != null) ? (" - " + result.Failure.InnerException.Message) : string.Empty;
throw new HttpRequestException(
CDCavell.ClassLibrary.Web.Html.StatusCodes.ToString(401),
new Exception(errMsg),
HttpStatusCode.Unauthorized
);
}
if (_logger.IsEnabled(LogLevel.Debug))
{
var externalClaims = result.Principal.Claims.Select(c => $"{c.Type}: {c.Value}");
_logger.Debug($"External claims: {externalClaims}");
}
// lookup our user and external provider info
var (user, provider, providerUserId, claims) = await FindUserFromExternalProviderAsync(result);
if (user == null)
{
// this might be where you might initiate a custom workflow for user registration
// in this sample we don't show how that would be done, as our sample implementation
// simply auto-provisions new external user
user = await AutoProvisionUserAsync(provider, providerUserId, claims);
}
// validate email address
if (!user.EmailConfirmed)
{
// delete temporary cookie used during external authentication
await HttpContext.SignOutAsync(IdentityServerConstants.ExternalCookieAuthenticationScheme);
TempData["Email"] = user.Email;
return RedirectToAction("Index", "Registration");
}
if (user.TwoFactorEnabled)
{
TwoFactorValidateModel model = new TwoFactorValidateModel();
model.Email = user.Email;
model.Provider = provider;
model.ProviderUserId = providerUserId;
model.ReturnUrl = result.Properties.Items["returnUrl"];
// if the external system sent a session id claim, copy it over
// so we can use it for single sign-out
var sid = result.Principal.Claims.FirstOrDefault(x => x.Type == JwtClaimTypes.SessionId);
if (sid != null)
{
model.SessionId = sid.Value;
}
// if the external provider issued an id_token, we'll keep it for signout
var idToken = result.Properties.GetTokenValue("id_token");
if (idToken != null)
{
model.AuthenticationToken = idToken;
}
TempData["TwoFactorValidateModel"] = JsonConvert.SerializeObject(model);
return RedirectToAction("Validate", "TwoFactor");
}
// this allows us to collect any additional claims or properties
// for the specific protocols used and store them in the local auth cookie.
// this is typically used to store data needed for signout from those protocols.
var additionalLocalClaims = new List<Claim>();
var localSignInProps = new AuthenticationProperties();
ProcessLoginCallback(result, additionalLocalClaims, localSignInProps);
// issue authentication cookie for user
// we must issue the cookie maually, and can't use the SignInManager because
// it doesn't expose an API to issue additional claims from the login workflow
var principal = await _signInManager.CreateUserPrincipalAsync(user);
additionalLocalClaims.AddRange(principal.Claims);
var name = user.FullName; //principal.FindFirst(JwtClaimTypes.Name)?.Value ?? user.Id;
var isuser = new IdentityServerUser(user.Id)
{
DisplayName = name,
IdentityProvider = provider,
AdditionalClaims = additionalLocalClaims
};
await HttpContext.SignInAsync(isuser, localSignInProps);
// delete temporary cookie used during external authentication
await HttpContext.SignOutAsync(IdentityServerConstants.ExternalCookieAuthenticationScheme);
// retrieve return URL
var returnUrl = result.Properties.Items["returnUrl"] ?? "~/";
// check if external login is in the context of an OIDC request
var context = await _interaction.GetAuthorizationContextAsync(returnUrl);
await _events.RaiseAsync(new UserLoginSuccessEvent(provider, providerUserId, user.Id, name, true, context?.Client.ClientId));
if (context != null)
{
if (context.IsNativeClient())
{
// The client is native, so this change in how to
// return the response is for better UX for the end user.
return this.LoadingPage("Redirect", returnUrl);
}
}
return Redirect(returnUrl);
}
private async Task<(ApplicationUser user, string provider, string providerUserId, IEnumerable<Claim> claims)>
FindUserFromExternalProviderAsync(AuthenticateResult result)
{
var externalUser = result.Principal;
// try to determine the unique id of the external user (issued by the provider)
// the most common claim type for that are the sub claim and the NameIdentifier
// depending on the external provider, some other claim type might be used
var userIdClaim = externalUser.FindFirst(JwtClaimTypes.Subject) ??
externalUser.FindFirst(ClaimTypes.NameIdentifier) ??
throw new Exception("Unknown userid");
// remove the user id claim so we don't include it as an extra claim if/when we provision the user
var claims = externalUser.Claims.ToList();
claims.Remove(userIdClaim);
var provider = result.Properties.Items["scheme"];
var providerUserId = userIdClaim.Value;
// find external user
var user = await _userManager.FindByLoginAsync(provider, providerUserId);
return (user, provider, providerUserId, claims);
}
private async Task<ApplicationUser> AutoProvisionUserAsync(string provider, string providerUserId, IEnumerable<Claim> claims)
{
// create a list of claims that we want to transfer into our store
var filtered = new List<Claim>();
// user's display name
var name = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.Name)?.Value ??
claims.FirstOrDefault(x => x.Type == ClaimTypes.Name)?.Value;
if (name != null)
{
filtered.Add(new Claim(JwtClaimTypes.Name, name));
}
else
{
var first = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.GivenName)?.Value ??
claims.FirstOrDefault(x => x.Type == ClaimTypes.GivenName)?.Value;
var last = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.FamilyName)?.Value ??
claims.FirstOrDefault(x => x.Type == ClaimTypes.Surname)?.Value;
if (first != null && last != null)
{
filtered.Add(new Claim(JwtClaimTypes.Name, first + " " + last));
}
else if (first != null)
{
filtered.Add(new Claim(JwtClaimTypes.Name, first));
}
else if (last != null)
{
filtered.Add(new Claim(JwtClaimTypes.Name, last));
}
}
// email
var email = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.Email)?.Value ??
claims.FirstOrDefault(x => x.Type == ClaimTypes.Email)?.Value;
if (email != null)
{
filtered.Add(new Claim(JwtClaimTypes.Email, email));
}
else
{
throw new Exception("Missing required email claim");
}
// setup results
var identityResult = new IdentityResult();
// check to make sure user dose not exist under diffrent external login
var user = await _userManager.FindByNameAsync(email);
if (user == null)
{
// no, so create user
user = new ApplicationUser
{
Email = email,
UserName = email,
NormalizedEmail = email.Trim().ToUpper(),
NormalizedUserName = email.Trim().ToUpper()
};
identityResult = await _userManager.CreateAsync(user);
if (!identityResult.Succeeded) throw new Exception(identityResult.Errors.First().Description);
// get created user
user = await _userManager.FindByEmailAsync(email);
if (user == null) throw new Exception($"User not found for {email}");
if (filtered.Any())
{
identityResult = await _userManager.AddClaimsAsync(user, filtered);
if (!identityResult.Succeeded) throw new Exception(identityResult.Errors.First().Description);
}
identityResult = await _userManager.AddLoginAsync(user, new UserLoginInfo(provider, providerUserId, provider));
if (!identityResult.Succeeded) throw new Exception(identityResult.Errors.First().Description);
}
else
{
// yes, so update existing user claims
if (filtered.Any())
{
foreach (Claim claim in filtered)
{
var foundClaim = user.Claims.Where(x => x.ClaimType == claim.Type && x.ClaimValue == claim.Value).FirstOrDefault();
if (foundClaim == null)
{
IdentityUserClaim<string> identityUserClaim = new IdentityUserClaim<string>();
identityUserClaim.UserId = user.Id;
identityUserClaim.ClaimType = claim.Type;
identityUserClaim.ClaimValue = claim.Value;
user.Claims.Add(identityUserClaim);
}
}
var userLogin = ((List<UserLoginInfo>)await _userManager.GetLoginsAsync(user))
.Where(x => x.LoginProvider == provider && x.ProviderKey == providerUserId)
.FirstOrDefault();
if (userLogin == null)
{
identityResult = await _userManager.AddLoginAsync(user, new UserLoginInfo(provider, providerUserId, provider));
if (!identityResult.Succeeded) throw new Exception(identityResult.Errors.First().Description);
}
identityResult = await _userManager.UpdateAsync(user);
if (!identityResult.Succeeded) throw new Exception(identityResult.Errors.First().Description);
}
}
return user;
}
// if the external login is OIDC-based, there are certain things we need to preserve to make logout work
// this will be different for WS-Fed, SAML2p or other protocols
private void ProcessLoginCallback(AuthenticateResult externalResult, List<Claim> localClaims, AuthenticationProperties localSignInProps)
{
// if the external system sent a session id claim, copy it over
// so we can use it for single sign-out
var sid = externalResult.Principal.Claims.FirstOrDefault(x => x.Type == JwtClaimTypes.SessionId);
if (sid != null)
{
localClaims.Add(new Claim(JwtClaimTypes.SessionId, sid.Value));
}
// if the external provider issued an id_token, we'll keep it for signout
var idToken = externalResult.Properties.GetTokenValue("id_token");
if (idToken != null)
{
localSignInProps.StoreTokens(new[] { new AuthenticationToken { Name = "id_token", Value = idToken } });
}
}
}
}
| 46.676471 | 145 | 0.573882 | [
"MIT"
] | cdcavell/cdcavell.name | Source/Web/dis5-cdcavell/Controllers/ExternalController.cs | 19,046 | C# |
//====================================================================
//
// COPYRIGHT (C) 2003 - 2008 OPINIONATEDGEEK LTD.
//
// The contents of this file are subject to License from OpinionatedGeek;
// you may not use this file except in compliance with the License.
// You may obtain a License from OpinionatedGeek Ltd. Software distributed
// under the License is distributed "as is" and without any warranty
// as to merchantability or fitness for a particular purpose or any
// other warranties either expressed or implied. The author will
// not be liable for data loss, damages, loss of profits or any
// other kind of loss while using or misusing this software.
//
// For more information visit http://www.opinionatedgeek.com/
//
//====================================================================
//
// ID: $Id$
//
// URL: $URL$
//
// Last Modified: $Date$
//
// Author: $Author$
//
// Revision: $Revision$
//
//====================================================================
using System.Collections;
using System.Collections.Specialized;
namespace OpinionatedGeek.Web.PowerPack
{
///
/// <summary>
/// Represents a collection of configuration file string keys and string values.
/// <p class="i1" style="color: #0206A6">
/// <b>Browser Requirements:</b> Not applicable.
/// </p>
/// </summary>
/// <remarks>
/// Represents a collection of configuration file string keys and string values. In addition to the normal
/// key-value pairing, compound values can be retrieved through the <see cref="GetCompoundValue"/> method.
/// <p class="i1">
/// This class is never normally instantiated in user code. Instead it is more usually created and returned
/// by the <see cref="ConfigurationSectionHandler"/> class as part of the configuration file processing.
/// </p>
/// <p class="i1" style="color: #0206A6; background-color: #FFFFCC; padding: 0.5em 1em 0.5em 1em; border-width: 1px; border-style: solid; border-color: #999999;">
/// <b>Browser Notes:</b>
/// Not applicable.
/// </p>
/// <seealso cref="ConfigurationSectionHandler"/>
/// </remarks>
///
public class PowerPackConfigurationSection
{
//============================================================
// Private Data
//============================================================
private readonly Hashtable _compoundValues = new Hashtable ();
private readonly NameValueCollection _nameValues = new NameValueCollection ();
//============================================================
// Constructors
//============================================================
///
/// <summary>
/// Initializes a new instance of the <see cref="PowerPackConfigurationSection"/> class that is empty, has
/// the default initial capacity and uses the default case-insensitive hash code provider and the default
/// case-insensitive comparer.
/// </summary>
/// <remarks>
/// The capacity is the number of key-and-value pairs that the <see cref="PowerPackConfigurationSection"/>
/// can contain. The default initial capacity is zero. The capacity is automatically increased as required.
/// </remarks>
///
public PowerPackConfigurationSection ()
{
return;
}
///
/// <summary>
/// Copies the entries from the specified <see cref="NameValueCollection"/> to a new
/// <see cref="PowerPackConfigurationSection"/> with the same initial capacity as the number of entries
/// copied and using the same hash code provider and the same comparer as the source collection.
/// </summary>
/// <remarks>
/// The capacity is the number of key-and-value pairs that the <see cref="PowerPackConfigurationSection"/>
/// can contain. The default initial capacity is zero. The capacity is automatically increased as required.
/// <p class="i1">
/// The elements of the new <see cref="PowerPackConfigurationSection"/> are sorted in the same order as the
/// source <see cref="NameValueCollection"/>.
/// </p>
/// </remarks>
/// <param name="collection">The <see cref="NameValueCollection"/> to copy to the new
/// <see cref="PowerPackConfigurationSection"/> instance.</param>
///
public PowerPackConfigurationSection (NameValueCollection collection)
{
_nameValues.Add (collection);
return;
}
//============================================================
// Properties
//============================================================
///
/// <summary>
/// Gets the entry with the specified key in the <see cref="PowerPackConfigurationSection"/>.
/// </summary>
/// <remarks>
/// This property provides the ability to access a specific element in the
/// <see cref="PowerPackConfigurationSection"/> by using the following syntax: myCollection [name].
/// </remarks>
/// <param name="name">The <see cref="System.String"/> key of the entry to locate. The key can be a null reference (Nothing in Visual Basic).</param>
/// <returns>A <see cref="System.String"/> value associated with the specified key.</returns>
///
public string this [string name]
{
get
{
return _nameValues [name];
}
}
//============================================================
// Methods
//============================================================
///
/// <summary>
/// Adds entries to the current <see cref="PowerPackConfigurationSection"/>.
/// </summary>
/// <remarks>
/// If the specified key already exists in the target <see cref="PowerPackConfigurationSection"/> instance,
/// the specified value is added to the existing comma-separated list of values associated with the same key
/// in the target <see cref="PowerPackConfigurationSection"/> instance.
/// <p class="i1">
/// If the same value already exists under the same key in the collection, the new value overwrites the old
/// value.
/// </p>
/// </remarks>
/// <param name="name">The key of the entry to add. The key can be a null reference.</param>
/// <param name="value">The value of the entry to add. The value can be a null reference.</param>
///
public void Add (string name, string value)
{
_nameValues[name] = value;
if (name != null)
{
if (value != null)
{
AddCompound (name, value);
}
}
return;
}
///
/// <summary>
/// Removes the entries with the specified key from the <see cref="PowerPackConfigurationSection"/> instance.
/// </summary>
/// <remarks>
/// In collections of contiguous elements, such as lists, fthe elements that follow the removed element
/// move up to occupy the vacated spot. If the collection is indexed, the indexes of the elements that
/// are moved are also updated. This behavior does not apply to collections where elements are conceptually
/// grouped into buckets, such as a hashtable.
/// </remarks>
/// <param name="name">The key of the entry to remove. The key can be a null reference.</param>
///
public void Remove (string name)
{
if (name != null)
{
_compoundValues.Remove (name);
}
return;
}
///
/// <summary>
/// Invalidates the cached arrays and removes all entries from the <see cref="PowerPackConfigurationSection"/>.
/// </summary>
/// <remarks>
/// Invalidates the cached arrays and removes all entries from the <see cref="PowerPackConfigurationSection"/>.
/// </remarks>
///
public void Clear ()
{
_compoundValues.Clear ();
return;
}
///
/// <summary>
/// Retrieves all the values that have been specified for that key, as an array of strings.
/// </summary>
/// <remarks>
/// When keys have been specified more than once in a configuration file, this method will return
/// all values in an array of strings.
/// </remarks>
/// <example>
/// When configuration items have been specified more than once as follows:
/// <code>
/// <add name="License" value="Value1"/>
/// <add name="License" value="Value2"/>
/// <add name="License" value="Value3"/>
/// </code>
/// A call to GetCompoundValue will return an array of strings equivalent to:
/// <code>
/// {"Value1", "Value2", "Value3"}
/// </code>
/// </example>
/// <param name="name">The key of the entry to retrieve. The key can be a null reference.</param>
/// <returns>All set values of the key, each as its own element in an array of strings.</returns>
///
public string[] GetCompoundValue (string name)
{
string[] valueStrings = null;
var values = (ArrayList) _compoundValues [name];
if (values == null)
{
string ordinaryValue = this [name];
if (ordinaryValue != null)
{
valueStrings = new [] {ordinaryValue};
}
}
else
{
valueStrings = new string[values.Count];
values.CopyTo (valueStrings);
}
return valueStrings;
}
///
/// <summary>
/// Determines whether a compound value has been specified for a given key.
/// </summary>
/// <remarks>
/// This method allows you to check if keys have been specified more than once in
/// a configuration file.
/// </remarks>
/// <example>
/// When configuration items have been specified more than once as follows:
/// <code>
/// <add name="License" value="Value1"/>
/// <add name="License" value="Value2"/>
/// <add name="License" value="Value3"/>
/// </code>
/// A call to HasCompoundValue will return true:
/// </example>
/// <param name="name">The key of the entry to check.</param>
/// <returns>True if the key has a compound value, false if the key has zero or one values.</returns>
///
public bool HasCompoundValue (string name)
{
return _compoundValues [name] != null;
}
private void AddCompound (string name, string value)
{
if (_compoundValues [name] == null)
{
var values = new ArrayList {value};
_compoundValues [name] = values;
}
else
{
var values = (ArrayList) _compoundValues [name];
values.Add (value);
}
return;
}
}
} | 39.896194 | 166 | 0.53634 | [
"Unlicense"
] | OpinionatedGeek/PowerPack | Source/Configuration/PowerPackConfigurationSection.cs | 11,530 | C# |
namespace Microsoft.eShopOnContainers.Services.Catalog.API.Infrastructure.Services
{
public interface IIdentityService
{
string GetUserIdentity();
}
}
| 21.5 | 83 | 0.738372 | [
"MIT"
] | amroSaad78/eShopOnContainers | src/Services/Catalog/Catalog.API/Infrastructure/Services/IIdentityService.cs | 174 | C# |
// Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using Roslyn.Utilities;
namespace Microsoft.Cci
{
internal sealed class MemberRefComparer : IEqualityComparer<ITypeMemberReference>
{
private readonly MetadataWriter metadataWriter;
internal MemberRefComparer(MetadataWriter metadataWriter)
{
this.metadataWriter = metadataWriter;
}
public bool Equals(ITypeMemberReference x, ITypeMemberReference y)
{
if (x == y)
{
return true;
}
if (x.GetContainingType(metadataWriter.Context) != y.GetContainingType(metadataWriter.Context))
{
if (this.metadataWriter.GetMemberRefParentCodedIndex(x) != this.metadataWriter.GetMemberRefParentCodedIndex(y))
{
return false;
}
}
if (x.Name != y.Name)
{
return false;
}
IFieldReference/*?*/ xf = x as IFieldReference;
IFieldReference/*?*/ yf = y as IFieldReference;
if (xf != null && yf != null)
{
return this.metadataWriter.GetFieldSignatureIndex(xf) == this.metadataWriter.GetFieldSignatureIndex(yf);
}
IMethodReference/*?*/ xm = x as IMethodReference;
IMethodReference/*?*/ ym = y as IMethodReference;
if (xm != null && ym != null)
{
return this.metadataWriter.GetMethodSignatureIndex(xm) == this.metadataWriter.GetMethodSignatureIndex(ym);
}
return false;
}
public int GetHashCode(ITypeMemberReference memberRef)
{
int hash = Hash.Combine(memberRef.Name, (int)this.metadataWriter.GetMemberRefParentCodedIndex(memberRef) << 4);
IFieldReference/*?*/ fieldRef = memberRef as IFieldReference;
if (fieldRef != null)
{
hash = Hash.Combine(hash, (int)this.metadataWriter.GetFieldSignatureIndex(fieldRef));
}
else
{
IMethodReference/*?*/ methodRef = memberRef as IMethodReference;
if (methodRef != null)
{
hash = Hash.Combine(hash, (int)this.metadataWriter.GetMethodSignatureIndex(methodRef));
}
}
return hash;
}
}
} | 34.76 | 184 | 0.570004 | [
"Apache-2.0"
] | enginekit/copy_of_roslyn | Src/Compilers/Core/Portable/PEWriter/MemberRefComparer.cs | 2,609 | C# |
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Copyright (c) 2008 - 2015 Jb Evain
// Copyright (c) 2008 - 2011 Novell, Inc.
//
// Licensed under the MIT/X11 license.
//
using Mono.Collections.Generic;
namespace Cecilia
{
public abstract class PropertyReference : MemberReference
{
TypeReference property_type;
public TypeReference PropertyType
{
get { return property_type; }
set { property_type = value; }
}
public abstract Collection<ParameterDefinition> Parameters
{
get;
}
internal PropertyReference(string name, TypeReference propertyType)
: base(name)
{
Mixin.CheckNotNull(propertyType);
property_type = propertyType;
}
protected override IMemberDefinition ResolveDefinition()
{
return this.Resolve();
}
public new abstract PropertyDefinition Resolve();
}
}
| 21.456522 | 75 | 0.598784 | [
"MIT"
] | teo-tsirpanis/Cecilia | src/Cecilia/PropertyReference.cs | 987 | C# |
// Copyright © 2007 by Initial Force AS. All rights reserved.
// https://github.com/InitialForce/UnitsNet
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using JetBrains.Annotations;
using UnitsNet.I18n;
// ReSharper disable once CheckNamespace
namespace UnitsNet
{
[PublicAPI]
public partial class UnitSystem
{
private static readonly Dictionary<CultureInfo, UnitSystem> CultureToInstance;
private static readonly CultureInfo DefaultCulture = new CultureInfo("en-US");
/// <summary>
/// The culture of which this unit system is based on. Either passed in to constructor or the default culture.
/// </summary>
[NotNull] [PublicAPI] public readonly CultureInfo Culture;
/// <summary>
/// Per-unit-type dictionary of enum values by abbreviation. This is the inverse of
/// <see cref="_unitTypeToUnitValueToAbbrevs" />.
/// </summary>
private readonly Dictionary<Type, Dictionary<string, int>> _unitTypeToAbbrevToUnitValue;
/// <summary>
/// Per-unit-type dictionary of abbreviations by enum value. This is the inverse of
/// <see cref="_unitTypeToAbbrevToUnitValue" />.
/// </summary>
private readonly Dictionary<Type, Dictionary<int, List<string>>> _unitTypeToUnitValueToAbbrevs;
static UnitSystem()
{
CultureToInstance = new Dictionary<CultureInfo, UnitSystem>();
}
/// <summary>
/// Create unit system for parsing and generating strings of the specified culture.
/// If null is specified, the default English US culture will be used.
/// </summary>
/// <param name="cultureInfo"></param>
public UnitSystem([CanBeNull] CultureInfo cultureInfo = null)
{
if (cultureInfo == null)
cultureInfo = new CultureInfo(DefaultCulture.Name);
Culture = cultureInfo;
_unitTypeToUnitValueToAbbrevs = new Dictionary<Type, Dictionary<int, List<string>>>();
_unitTypeToAbbrevToUnitValue = new Dictionary<Type, Dictionary<string, int>>();
LoadDefaultAbbreviatons(cultureInfo);
}
public bool IsDefaultCulture
{
get { return Culture.Equals(DefaultCulture); }
}
[PublicAPI]
public static void ClearCache()
{
CultureToInstance.Clear();
}
/// <summary>
/// Get or create a unit system for parsing and presenting numbers, units and abbreviations.
/// Creating can be a little expensive, so it will use a static cache.
/// To always create, use the constructor.
/// </summary>
/// <param name="cultureInfo">Culture to use. If null then <see cref="CultureInfo.CurrentUICulture" /> will be used.</param>
/// <returns></returns>
[PublicAPI]
public static UnitSystem GetCached(CultureInfo cultureInfo = null)
{
if (cultureInfo == null)
cultureInfo = CultureInfo.CurrentUICulture;
if (!CultureToInstance.ContainsKey(cultureInfo))
CultureToInstance[cultureInfo] = new UnitSystem(cultureInfo);
return CultureToInstance[cultureInfo];
}
[PublicAPI]
public static TUnit Parse<TUnit>(string unitAbbreviation, CultureInfo culture)
where TUnit : /*Enum constraint hack*/ struct, IComparable, IFormattable
{
return GetCached(culture).Parse<TUnit>(unitAbbreviation);
}
[PublicAPI]
public TUnit Parse<TUnit>(string unitAbbreviation)
where TUnit : /*Enum constraint hack*/ struct, IComparable, IFormattable
{
Type unitType = typeof (TUnit);
Dictionary<string, int> abbrevToUnitValue;
if (!_unitTypeToAbbrevToUnitValue.TryGetValue(unitType, out abbrevToUnitValue))
throw new NotImplementedException(
string.Format("No abbreviations defined for unit type [{0}] for culture [{1}].", unitType,
Culture.EnglishName));
int unitValue;
TUnit result = abbrevToUnitValue.TryGetValue(unitAbbreviation, out unitValue)
? (TUnit) (object) unitValue
: default(TUnit);
return result;
}
[PublicAPI]
public static string GetDefaultAbbreviation<TUnit>(TUnit unit, CultureInfo culture)
where TUnit : /*Enum constraint hack*/ struct, IComparable, IFormattable
{
return GetCached(culture).GetDefaultAbbreviation(unit);
}
[PublicAPI]
public string GetDefaultAbbreviation<TUnit>(TUnit unit)
where TUnit : /*Enum constraint hack*/ struct, IComparable, IFormattable
{
return GetAllAbbreviations(unit).First();
}
[PublicAPI]
public void MapUnitToAbbreviation<TUnit>(TUnit unit, params string[] abbreviations)
where TUnit : /*Enum constraint hack*/ struct, IComparable, IFormattable
{
// Assuming TUnit is an enum, this conversion is safe. Seems not possible to enforce this today.
// Src: http://stackoverflow.com/questions/908543/how-to-convert-from-system-enum-to-base-integer
// http://stackoverflow.com/questions/79126/create-generic-method-constraining-t-to-an-enum
int unitValue = Convert.ToInt32(unit);
Type unitType = typeof (TUnit);
MapUnitToAbbreviation(unitType, unitValue, abbreviations);
}
[PublicAPI]
public void MapUnitToAbbreviation(Type unitType, int unitValue, [NotNull] params string[] abbreviations)
{
#if PORTABLE45
if (!unitType.GetTypeInfo().IsEnum)
throw new ArgumentException("Must be an enum type.", "unitType");
#else
if (!unitType.IsEnum)
throw new ArgumentException("Must be an enum type.", "unitType");
#endif
if (abbreviations == null)
throw new ArgumentNullException("abbreviations");
Dictionary<int, List<string>> unitValueToAbbrev;
if (!_unitTypeToUnitValueToAbbrevs.TryGetValue(unitType, out unitValueToAbbrev))
{
unitValueToAbbrev = _unitTypeToUnitValueToAbbrevs[unitType] = new Dictionary<int, List<string>>();
}
List<string> existingAbbreviations;
if (!unitValueToAbbrev.TryGetValue(unitValue, out existingAbbreviations))
{
existingAbbreviations = unitValueToAbbrev[unitValue] = new List<string>();
}
// Update any existing abbreviations so that the latest abbreviations
// take precedence in GetDefaultAbbreviation().
unitValueToAbbrev[unitValue] = abbreviations.Concat(existingAbbreviations).Distinct().ToList();
foreach (string abbreviation in abbreviations)
{
Dictionary<string, int> abbrevToUnitValue;
if (!_unitTypeToAbbrevToUnitValue.TryGetValue(unitType, out abbrevToUnitValue))
{
abbrevToUnitValue = _unitTypeToAbbrevToUnitValue[unitType] =
new Dictionary<string, int>();
}
if (!abbrevToUnitValue.ContainsKey(abbreviation))
abbrevToUnitValue[abbreviation] = unitValue;
}
}
[PublicAPI]
public bool TryParse<TUnit>(string unitAbbreviation, out TUnit unit)
where TUnit : /*Enum constraint hack*/ struct, IComparable, IFormattable
{
Type unitType = typeof (TUnit);
Dictionary<string, int> abbrevToUnitValue;
int unitValue;
if (!_unitTypeToAbbrevToUnitValue.TryGetValue(unitType, out abbrevToUnitValue) ||
!abbrevToUnitValue.TryGetValue(unitAbbreviation, out unitValue))
{
if (IsDefaultCulture)
{
unit = default(TUnit);
return false;
}
// Fall back to default culture
return GetCached(DefaultCulture).TryParse(unitAbbreviation, out unit);
}
unit = (TUnit) (object) unitValue;
return true;
}
/// <summary>
/// Get all abbreviations for unit.
/// </summary>
/// <typeparam name="TUnit">Enum type for units.</typeparam>
/// <param name="unit">Enum value for unit.</param>
/// <returns>Unit abbreviations associated with unit.</returns>
[PublicAPI]
public string[] GetAllAbbreviations<TUnit>(TUnit unit)
where TUnit : /*Enum constraint hack*/ struct, IComparable, IFormattable
{
Type unitType = typeof (TUnit);
int unitValue = Convert.ToInt32(unit);
Dictionary<int, List<string>> unitValueToAbbrevs;
List<string> abbrevs;
if (!_unitTypeToUnitValueToAbbrevs.TryGetValue(unitType, out unitValueToAbbrevs) ||
!unitValueToAbbrevs.TryGetValue(unitValue, out abbrevs))
{
if (IsDefaultCulture)
{
return new[] {string.Format("(no abbreviation for {0}.{1})", unitType.Name, unit)};
}
// Fall back to default culture
return GetCached(DefaultCulture).GetAllAbbreviations(unit);
}
return abbrevs.ToArray();
}
private void LoadDefaultAbbreviatons([NotNull] CultureInfo culture)
{
foreach (UnitLocalization localization in DefaultLocalizations)
{
Type unitEnumType = localization.UnitEnumType;
foreach (CulturesForEnumValue ev in localization.EnumValues)
{
int unitEnumValue = ev.Value;
var usCulture = new CultureInfo("en-US");
// Fall back to US English if localization not found
AbbreviationsForCulture matchingCulture =
ev.Cultures.FirstOrDefault(a => a.Cult.Equals(culture)) ??
ev.Cultures.FirstOrDefault(a => a.Cult.Equals(usCulture));
if (matchingCulture == null)
continue;
MapUnitToAbbreviation(unitEnumType, unitEnumValue, matchingCulture.Abbreviations.ToArray());
}
}
}
}
} | 41.195804 | 132 | 0.616109 | [
"MIT"
] | bretthysuik/UnitsNet | Src/UnitsNet/CustomCode/UnitSystem.cs | 11,785 | C# |
using Microsoft.Extensions.DependencyInjection;
using MyBrokenPage.Bll.Contracts;
using MyBrokenPage.Bll.Logic;
namespace MyBrokenPage.Bll
{
public static class ServiceCollectionExtensions
{
public static IServiceCollection AddMyBrokenPageBll(this IServiceCollection services)
{
services.AddScoped<IUserBll, UserBll>();
services.AddScoped<ISecurityQuestionBll, SecurityQuestionBll>();
services.AddScoped<IPostsBll, PostsBll>();
services.AddScoped<IFileManagementHelper, FileManagementHelper>();
return services;
}
}
}
| 31.8 | 94 | 0.687107 | [
"Unlicense"
] | saw-your-packet/my-broken-page | src/MyBrokenPage.Bll/ServiceCollectionExtensions.cs | 638 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Gcp.Storage.Outputs
{
[OutputType]
public sealed class TransferJobTransferSpec
{
/// <summary>
/// An AWS S3 data source. Structure documented below.
/// </summary>
public readonly Outputs.TransferJobTransferSpecAwsS3DataSource? AwsS3DataSource;
/// <summary>
/// A Google Cloud Storage data sink. Structure documented below.
/// </summary>
public readonly Outputs.TransferJobTransferSpecGcsDataSink? GcsDataSink;
/// <summary>
/// A Google Cloud Storage data source. Structure documented below.
/// </summary>
public readonly Outputs.TransferJobTransferSpecGcsDataSource? GcsDataSource;
/// <summary>
/// An HTTP URL data source. Structure documented below.
/// </summary>
public readonly Outputs.TransferJobTransferSpecHttpDataSource? HttpDataSource;
/// <summary>
/// Only objects that satisfy these object conditions are included in the set of data source and data sink objects. Object conditions based on objects' `last_modification_time` do not exclude objects in a data sink. Structure documented below.
/// </summary>
public readonly Outputs.TransferJobTransferSpecObjectConditions? ObjectConditions;
/// <summary>
/// Characteristics of how to treat files from datasource and sink during job. If the option `delete_objects_unique_in_sink` is true, object conditions based on objects' `last_modification_time` are ignored and do not exclude objects in a data source or a data sink. Structure documented below.
/// </summary>
public readonly Outputs.TransferJobTransferSpecTransferOptions? TransferOptions;
[OutputConstructor]
private TransferJobTransferSpec(
Outputs.TransferJobTransferSpecAwsS3DataSource? awsS3DataSource,
Outputs.TransferJobTransferSpecGcsDataSink? gcsDataSink,
Outputs.TransferJobTransferSpecGcsDataSource? gcsDataSource,
Outputs.TransferJobTransferSpecHttpDataSource? httpDataSource,
Outputs.TransferJobTransferSpecObjectConditions? objectConditions,
Outputs.TransferJobTransferSpecTransferOptions? transferOptions)
{
AwsS3DataSource = awsS3DataSource;
GcsDataSink = gcsDataSink;
GcsDataSource = gcsDataSource;
HttpDataSource = httpDataSource;
ObjectConditions = objectConditions;
TransferOptions = transferOptions;
}
}
}
| 44.90625 | 302 | 0.704245 | [
"ECL-2.0",
"Apache-2.0"
] | dimpu47/pulumi-gcp | sdk/dotnet/Storage/Outputs/TransferJobTransferSpec.cs | 2,874 | C# |
/*
* These tests are for the netcoreapp2.1 version of the client (there are separate tests for netstandard that don't actually connect to a server).
*/
using k8s.Models;
using k8s.Autorest;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net.Http;
using System.Net.WebSockets;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace k8s.Tests
{
/// <summary>
/// Tests for <see cref="KubeApiClient"/>'s exec-in-pod functionality.
/// </summary>
public class PodExecTests
: WebSocketTestBase
{
private readonly ITestOutputHelper testOutput;
/// <summary>
/// Initializes a new instance of the <see cref="PodExecTests"/> class.
/// Create a new <see cref="KubeApiClient"/> exec-in-pod test suite.
/// </summary>
/// <param name="testOutput">
/// Output for the current test.
/// </param>
public PodExecTests(ITestOutputHelper testOutput)
: base(testOutput)
{
this.testOutput = testOutput;
}
/// <summary>
/// Verify that the client can request execution of a command in a pod's default container, with only the STDOUT stream enabled.
/// </summary>
/// <returns><placeholder>A <see cref="Task"/> representing the asynchronous unit test.</placeholder></returns>
/// <returns><placeholder>A <see cref="Task"/> representing the asynchronous unit test.</placeholder></returns>
[Fact(DisplayName = "Can exec in pod's default container, STDOUT only")]
public async Task ExecDefaultContainerStdOut()
{
if (!Debugger.IsAttached)
{
CancellationSource.CancelAfter(
TimeSpan.FromSeconds(5));
}
await Host.StartAsync(TestCancellation).ConfigureAwait(false);
using (Kubernetes client = CreateTestClient())
{
testOutput.WriteLine("Invoking exec operation...");
WebSocket clientSocket = await client.WebSocketNamespacedPodExecAsync(
"mypod",
"mynamespace",
new string[] { "/bin/bash" },
"mycontainer",
false,
false,
true,
webSocketSubProtol: WebSocketProtocol.ChannelWebSocketProtocol,
cancellationToken: TestCancellation).ConfigureAwait(false);
Assert.Equal(
WebSocketProtocol.ChannelWebSocketProtocol,
clientSocket.SubProtocol); // For WebSockets, the Kubernetes API defaults to the binary channel (v1) protocol.
testOutput.WriteLine(
$"Client socket connected (socket state is {clientSocket.State}). Waiting for server-side socket to become available...");
WebSocket serverSocket = await WebSocketTestAdapter.AcceptedPodExecV1Connection;
testOutput.WriteLine(
$"Server-side socket is now available (socket state is {serverSocket.State}). Sending data to server socket...");
const int STDOUT = 1;
const string expectedOutput = "This is text send to STDOUT.";
int bytesSent = await SendMultiplexed(serverSocket, STDOUT, expectedOutput).ConfigureAwait(false);
testOutput.WriteLine($"Sent {bytesSent} bytes to server socket; receiving from client socket...");
(string receivedText, byte streamIndex, int bytesReceived) = await ReceiveTextMultiplexed(clientSocket).ConfigureAwait(false);
testOutput.WriteLine(
$"Received {bytesReceived} bytes from client socket ('{receivedText}', stream {streamIndex}).");
Assert.Equal(STDOUT, streamIndex);
Assert.Equal(expectedOutput, receivedText);
await Disconnect(clientSocket, serverSocket,
WebSocketCloseStatus.NormalClosure,
"Normal Closure").ConfigureAwait(false);
WebSocketTestAdapter.CompleteTest();
}
}
[Fact]
public void GetExitCodeOrThrowSuccess()
{
var status = new V1Status() { Metadata = null, Status = "Success", };
Assert.Equal(0, Kubernetes.GetExitCodeOrThrow(status));
}
[Fact]
public void GetExitCodeOrThrowNonZeroExitCode()
{
var status = new V1Status()
{
Metadata = null,
Status = "Failure",
Message = "command terminated with non-zero exit code: Error executing in Docker Container: 1",
Reason = "NonZeroExitCode",
Details = new V1StatusDetails()
{
Causes = new List<V1StatusCause>()
{
new V1StatusCause() { Reason = "ExitCode", Message = "1" },
},
},
};
Assert.Equal(1, Kubernetes.GetExitCodeOrThrow(status));
}
[Fact]
public void GetExitCodeOrThrowInvalidExitCode()
{
var status = new V1Status()
{
Metadata = null,
Status = "Failure",
Message = "command terminated with non-zero exit code: Error executing in Docker Container: 1",
Reason = "NonZeroExitCode",
Details = new V1StatusDetails()
{
Causes = new List<V1StatusCause>()
{
new V1StatusCause() { Reason = "ExitCode", Message = "abc" },
},
},
};
var ex = Assert.Throws<KubernetesException>(() => Kubernetes.GetExitCodeOrThrow(status));
Assert.Equal(status, ex.Status);
}
[Fact]
public void GetExitCodeOrThrowNoExitCode()
{
var status = new V1Status()
{
Metadata = null,
Status = "Failure",
Message = "command terminated with non-zero exit code: Error executing in Docker Container: 1",
Reason = "NonZeroExitCode",
Details = new V1StatusDetails() { Causes = new List<V1StatusCause>() { } },
};
var ex = Assert.Throws<KubernetesException>(() => Kubernetes.GetExitCodeOrThrow(status));
Assert.Equal(status, ex.Status);
}
[Fact]
public void GetExitCodeOrThrowOtherError()
{
var status = new V1Status() { Metadata = null, Status = "Failure", Reason = "SomethingElse" };
var ex = Assert.Throws<KubernetesException>(() => Kubernetes.GetExitCodeOrThrow(status));
Assert.Equal(status, ex.Status);
}
[Fact]
public async Task NamespacedPodExecAsyncActionNull()
{
using (MemoryStream stdIn = new MemoryStream())
using (MemoryStream stdOut = new MemoryStream())
using (MemoryStream stdErr = new MemoryStream())
using (MemoryStream errorStream = new MemoryStream())
{
var muxedStream = new Moq.Mock<IStreamDemuxer>();
muxedStream.Setup(m => m.GetStream(null, ChannelIndex.StdIn)).Returns(stdIn);
muxedStream.Setup(m => m.GetStream(ChannelIndex.StdOut, null)).Returns(stdOut);
muxedStream.Setup(m => m.GetStream(ChannelIndex.StdErr, null)).Returns(stdErr);
muxedStream.Setup(m => m.GetStream(ChannelIndex.Error, null)).Returns(errorStream);
var kubernetesMock = new Moq.Mock<Kubernetes>(
new object[] { new KubernetesClientConfiguration() { Host = "http://localhost" }, new DelegatingHandler[] { } })
{ CallBase = true };
var command = new string[] { "/bin/bash", "-c", "echo Hello, World!" };
kubernetesMock.Setup(m => m.MuxedStreamNamespacedPodExecAsync("pod-name", "pod-namespace", command,
"my-container", true, true, true, false, WebSocketProtocol.V4BinaryWebsocketProtocol, null,
CancellationToken.None))
.Returns(Task.FromResult(muxedStream.Object));
using (Kubernetes client = kubernetesMock.Object)
{
await Assert.ThrowsAsync<ArgumentNullException>(() => client.NamespacedPodExecAsync(
"pod-name",
"pod-namespace", "my-container", command, false, null, CancellationToken.None))
.ConfigureAwait(false);
}
}
}
[Fact]
public async Task NamespacedPodExecAsyncHttpExceptionWithStatus()
{
var kubernetesMock = new Moq.Mock<Kubernetes>(
new object[] { new KubernetesClientConfiguration() { Host = "http://localhost" }, new DelegatingHandler[] { } })
{ CallBase = true };
var command = new string[] { "/bin/bash", "-c", "echo Hello, World!" };
var handler = new ExecAsyncCallback((stdIn, stdOut, stdError) => Task.CompletedTask);
var status = new V1Status();
kubernetesMock.Setup(m => m.MuxedStreamNamespacedPodExecAsync("pod-name", "pod-namespace", command,
"my-container", true, true, true, false, WebSocketProtocol.V4BinaryWebsocketProtocol, null,
CancellationToken.None))
.Throws(new HttpOperationException() { Body = status });
using (Kubernetes client = kubernetesMock.Object)
{
var ex = await Assert.ThrowsAsync<KubernetesException>(() => client.NamespacedPodExecAsync(
"pod-name",
"pod-namespace", "my-container", command, false, handler, CancellationToken.None))
.ConfigureAwait(false);
Assert.Same(status, ex.Status);
}
}
[Fact]
public async Task NamespacedPodExecAsyncHttpExceptionNoStatus()
{
var kubernetesMock = new Moq.Mock<Kubernetes>(
new object[] { new KubernetesClientConfiguration() { Host = "http://localhost" }, new DelegatingHandler[] { } })
{ CallBase = true };
var command = new string[] { "/bin/bash", "-c", "echo Hello, World!" };
var handler = new ExecAsyncCallback((stdIn, stdOut, stdError) => Task.CompletedTask);
var exception = new HttpOperationException();
kubernetesMock.Setup(m => m.MuxedStreamNamespacedPodExecAsync("pod-name", "pod-namespace", command,
"my-container", true, true, true, false, WebSocketProtocol.V4BinaryWebsocketProtocol, null,
CancellationToken.None))
.Throws(exception);
using (Kubernetes client = kubernetesMock.Object)
{
var ex = await Assert.ThrowsAsync<HttpOperationException>(() =>
client.NamespacedPodExecAsync("pod-name", "pod-namespace", "my-container", command, false, handler,
CancellationToken.None)).ConfigureAwait(false);
Assert.Same(exception, ex);
}
}
[Fact]
public async Task NamespacedPodExecAsyncGenericException()
{
var kubernetesMock = new Moq.Mock<Kubernetes>(
new object[] { new KubernetesClientConfiguration() { Host = "http://localhost" }, new DelegatingHandler[] { } })
{ CallBase = true };
var command = new string[] { "/bin/bash", "-c", "echo Hello, World!" };
var handler = new ExecAsyncCallback((stdIn, stdOut, stdError) => Task.CompletedTask);
var exception = new Exception();
kubernetesMock.Setup(m => m.MuxedStreamNamespacedPodExecAsync("pod-name", "pod-namespace", command,
"my-container", true, true, true, false, WebSocketProtocol.V4BinaryWebsocketProtocol, null,
CancellationToken.None))
.Throws(exception);
using (Kubernetes client = kubernetesMock.Object)
{
var ex = await Assert.ThrowsAsync<Exception>(() => client.NamespacedPodExecAsync(
"pod-name",
"pod-namespace", "my-container", command, false, handler, CancellationToken.None))
.ConfigureAwait(false);
Assert.Same(exception, ex);
}
}
[Fact]
public async Task NamespacedPodExecAsyncExitCodeNonZero()
{
var processStatus = new V1Status()
{
Metadata = null,
Status = "Failure",
Message = "command terminated with non-zero exit code: Error executing in Docker Container: 1",
Reason = "NonZeroExitCode",
Details = new V1StatusDetails()
{
Causes = new List<V1StatusCause>()
{
new V1StatusCause() { Reason = "ExitCode", Message = "1" },
},
},
};
var processStatusJson = JsonSerializer.SerializeToUtf8Bytes(processStatus);
var handler = new ExecAsyncCallback((stdIn, stdOut, stdError) => Task.CompletedTask);
using (MemoryStream stdIn = new MemoryStream())
using (MemoryStream stdOut = new MemoryStream())
using (MemoryStream stdErr = new MemoryStream())
using (MemoryStream errorStream = new MemoryStream(processStatusJson))
{
var muxedStream = new Moq.Mock<IStreamDemuxer>();
muxedStream.Setup(m => m.GetStream(null, ChannelIndex.StdIn)).Returns(stdIn);
muxedStream.Setup(m => m.GetStream(ChannelIndex.StdOut, null)).Returns(stdOut);
muxedStream.Setup(m => m.GetStream(ChannelIndex.StdErr, null)).Returns(stdErr);
muxedStream.Setup(m => m.GetStream(ChannelIndex.Error, null)).Returns(errorStream);
var kubernetesMock = new Moq.Mock<Kubernetes>(
new object[] { new KubernetesClientConfiguration() { Host = "http://localhost" }, new DelegatingHandler[] { } })
{ CallBase = true };
var command = new string[] { "/bin/bash", "-c", "echo Hello, World!" };
var exception = new Exception();
kubernetesMock.Setup(m => m.MuxedStreamNamespacedPodExecAsync("pod-name", "pod-namespace", command,
"my-container", true, true, true, false, WebSocketProtocol.V4BinaryWebsocketProtocol, null,
CancellationToken.None))
.Returns(Task.FromResult(muxedStream.Object));
using (Kubernetes client = kubernetesMock.Object)
{
var exitCode = await client.NamespacedPodExecAsync("pod-name", "pod-namespace", "my-container",
command, false, handler, CancellationToken.None).ConfigureAwait(false);
Assert.Equal(1, exitCode);
}
}
}
}
}
| 45.41349 | 146 | 0.566512 | [
"Apache-2.0"
] | BearerPipelineTest/csharp | tests/KubernetesClient.Tests/PodExecTests.cs | 15,486 | C# |
//
// XMouseScrollArgs.cs
//
// Author:
// Anna-Sophia Schröck <annasophia.schroeck@gmail.com>
//
// Copyright (c) 2014 Anna-Sophia Schröck
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
using System;
namespace System.API.Platform.Linux.Widgets
{
public enum MouseScrollDirection : int
{
Up = 1,
Down = -1
}
public class XMouseScrollArgs : XEventArgs
{
private MouseScrollDirection m_eScrollDirection;
public MouseScrollDirection ScrollDirection
{
get { return m_eScrollDirection; }
}
public XMouseScrollArgs(int direction)
{
m_eScrollDirection = (MouseScrollDirection)direction;
}
}
}
| 27.456522 | 79 | 0.7308 | [
"MIT"
] | RoseLeBlood/libral | liboRg/System/API/Platform/Linux/Widgets/Event/XMouseScrollArgs.cs | 1,267 | C# |
using System;
using System.Linq;
namespace Okuma.PanelMode.Common
{
/// <summary>Extension methods</summary>
public static class ExtensionMethods
{
/// <summary>Translates one enum to another by attempting to match names.</summary>
/// <typeparam name="TIn">The input enum type</typeparam>
/// <typeparam name="TOut">The output enum type</typeparam>
/// <param name="in">The input enum value</param>
/// <returns>The input enum value, converted to the output enum type based on name.</returns>
public static TOut Translate<TIn, TOut>(this TIn @in)
where TIn: System.Enum
where TOut : System.Enum
{
var inName = @in.ToString();
try
{
return (TOut)System.Enum.Parse(typeof(TOut), inName);
}
catch
{
throw new ArgumentException($"Enum type {typeof(TOut).FullName} does not contain a definition for {inName}");
}
}
}
}
| 34.6 | 125 | 0.578035 | [
"Apache-2.0"
] | Machining-Code/Okuma.PanelMode | Okuma.PanelMode/Common/ExtensionMethods.cs | 1,040 | C# |
// Instance generated by TankLibHelper.InstanceBuilder
using TankLib.STU.Types.Enums;
// ReSharper disable All
namespace TankLib.STU.Types {
[STUAttribute(0xB66C7F70)]
public class STU_B66C7F70 : STU_DBB143CB {
[STUFieldAttribute(0x07DD813E, "m_value")]
public Enum_7888DAF2 m_value;
}
}
| 26.416667 | 54 | 0.731861 | [
"MIT"
] | Mike111177/OWLib | TankLib/STU/Types/STU_B66C7F70.cs | 317 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Runtime.Serialization;
using System.Data;
namespace Livestock_Auction.DB
{
public class clsPayments : clsAuctionDataCollection<IDAuctionDataKey, clsPayment, DB.Setup.Payments>
{
Dictionary<int, Dictionary<int, clsPayment>> dictPayments;
public clsPayments(IDbConnection Connection)
: base(Connection)
{
}
public override void Load()
{
dictPayments = new Dictionary<int, Dictionary<int, clsPayment>>();
m_Setup = new DB.Setup.Payments();
IDbCommand dbLoad = m_Setup.SQLLoadDataQuery(m_dbConn);
//IDbCommand dbLoad = m_dbConn.CreateCommand();
//dbLoad.CommandText = "SELECT LastUpdated, BuyerID, PaymentIndex, PaymentMethod, Amount, CheckNumber, Comments FROM vPayments_Current ORDER BY BuyerID ASC, PaymentIndex ASC";
IDataReader PaymentReader = dbLoad.ExecuteReader();
while (PaymentReader.Read())
{
clsPayment Payment = new clsPayment((int)PaymentReader["BuyerID"], (int)PaymentReader["PaymentIndex"], (clsPayment.PaymentMethod)PaymentReader["PaymentMethod"], (int)PaymentReader["CheckNumber"], double.Parse(PaymentReader["Amount"].ToString()), PaymentReader["Comments"].ToString());
if (!dictPayments.ContainsKey(Payment.BuyerNumber))
{
dictPayments.Add(Payment.BuyerNumber, new Dictionary<int, clsPayment>());
}
dictPayments[Payment.BuyerNumber].Add(Payment.Index, Payment);
if (PaymentReader["LastUpdated"] is DateTime)
{
m_dtLastUpdate = (DateTime)PaymentReader["LastUpdated"];
}
else
{
m_dtLastUpdate = DateTime.Parse(PaymentReader["LastUpdated"].ToString());
}
}
PaymentReader.Close();
}
public override void Update(IDbConnection Connection)
{
try
{
DatabaseUpdatedEventArgs UpdateArgs = new DatabaseUpdatedEventArgs();
//IDbCommand dbUpdate = Connection.CreateCommand();
//dbUpdate.CommandText = "SELECT CommitDate, CommitAction, BuyerID, PaymentIndex, PaymentMethod, Amount, CheckNumber, Comments FROM vPayments_Journal WHERE CommitDate > '" + m_dtLastUpdate.ToString("yyyy-MM-dd HH:mm:ss.fffffff") + "' ORDER BY BuyerID ASC, PaymentIndex ASC";
//dbUpdate.CommandText = "SELECT CommitDate, CommitAction, BuyerID, PaymentIndex, PaymentMethod, Amount, CheckNumber, Comments FROM vPayments_Journal WHERE CommitDate > @LastUpdate ORDER BY BuyerID ASC, PaymentIndex ASC";
IDbCommand dbUpdate = m_Setup.SQLUpdateDataQuery(Connection);
IDbDataParameter param = dbUpdate.CreateParameter();
param.ParameterName = "@LastUpdate";
if (param is System.Data.SqlServerCe.SqlCeParameter)
{
param.Value = m_dtLastUpdate;
}
else
{
param.DbType = DbType.DateTime2;
param.Value = m_dtLastUpdate;
}
dbUpdate.Parameters.Add(param);
IDataReader PaymentReader = dbUpdate.ExecuteReader();
try
{
while (PaymentReader.Read())
{
Int32 iBuyerNumber = -1;
Int32 iPaymentIndex = -1;
try
{
iBuyerNumber = (Int32)PaymentReader["BuyerID"];
iPaymentIndex = (Int32)PaymentReader["PaymentIndex"];
//Apply the changes to the dictionary
clsPayment Payment = new clsPayment(iBuyerNumber, iPaymentIndex, (clsPayment.PaymentMethod)PaymentReader["PaymentMethod"], (int)PaymentReader["CheckNumber"], double.Parse(PaymentReader["Amount"].ToString()), PaymentReader["Comments"].ToString());
if ((DB.CommitAction)int.Parse(PaymentReader["CommitAction"].ToString()) == DB.CommitAction.Modify)
{
//Modifications and addtions....
if (!dictPayments.ContainsKey(Payment.BuyerNumber))
{
dictPayments.Add(Payment.BuyerNumber, new Dictionary<int, clsPayment>());
}
if (!dictPayments[Payment.BuyerNumber].ContainsKey(Payment.Index))
{
dictPayments[Payment.BuyerNumber].Add(Payment.Index, Payment);
}
else
{
dictPayments[Payment.BuyerNumber][Payment.Index] = Payment;
}
}
else
{
//Deletes.....
if (dictPayments.ContainsKey(Payment.BuyerNumber))
{
dictPayments[Payment.BuyerNumber].Remove(Payment.Index);
if (dictPayments[Payment.BuyerNumber].Count <= 0)
{
dictPayments.Remove(Payment.BuyerNumber);
}
}
}
//Keep Track up what was changed for the updated event
UpdateArgs.UpdatedItems.Add(Payment, (DB.CommitAction)int.Parse(PaymentReader["CommitAction"].ToString()));
//Keep track of the last update time
DateTime dtLastUpdate;
if (PaymentReader["CommitDate"] is DateTime)
{
dtLastUpdate = (DateTime)PaymentReader["CommitDate"];
}
else
{
dtLastUpdate = DateTime.Parse(PaymentReader["CommitDate"].ToString());
}
if (dtLastUpdate > m_dtLastUpdate)
{
m_dtLastUpdate = dtLastUpdate;
}
}
catch (Exception ex)
{
clsLogger.WriteLog(string.Format("An error occured processing update for payment buyer number {0}, payment index {1}:\r\nMessage:{2}\r\nStack Trace:\r\n{3}\r\n", iBuyerNumber, iPaymentIndex, ex.Message, ex.StackTrace));
}
}
}
catch (Exception ex)
{
clsLogger.WriteLog(string.Format("An error occured updating payments while the reader was open:\r\nMessage:{0}\r\nStack Trace:\r\n{1}\r\n", ex.Message, ex.StackTrace));
}
PaymentReader.Close();
//Call the updated event if nessesary
if (UpdateArgs.UpdatedItems.Count > 0)
{
onUpdated(UpdateArgs);
}
}
catch (Exception ex)
{
clsLogger.WriteLog(string.Format("An error occured updating Payments:\r\nMessage:{0}\r\nStack Trace:\r\n{1}\r\n", ex.Message, ex.StackTrace));
}
}
public clsPayment this[int BuyerNumber, int PaymentIndex]
{
get
{
if (dictPayments.ContainsKey(BuyerNumber) && dictPayments[BuyerNumber].ContainsKey(PaymentIndex))
{
return dictPayments[BuyerNumber][PaymentIndex];
}
else
{
return null;
}
}
}
public Dictionary<int, clsPayment> this[int BuyerNumber]
{
get
{
if (dictPayments.ContainsKey(BuyerNumber))
{
return dictPayments[BuyerNumber];
}
else
{
return null;
}
}
}
public Dictionary<int, clsPayment> this[clsBuyer Buyer]
{
get
{
if (dictPayments.ContainsKey(Buyer.BuyerNumber))
{
return dictPayments[Buyer.BuyerNumber];
}
else
{
return null;
}
}
}
}
public class clsPayment : AuctionData, IComparable<clsPayment>
{
//Square gets 2.75% of the total purchase. The surcharge is
// calculated such that the total amount owed by the buyer
// gets the fair the full purchase price and the square
// their 2.75%.
//public double CREDIT_CARD_FEE = Math.Round((1 / (1 - 0.0275)) - 1, 5);
public double CREDIT_CARD_FEE = Math.Round((1 / (1 - clsDB.Settings.CreditCardFee)) - 1, 5);
public enum PaymentMethod
{
NotSet = 0,
Cash = 1,
Check = 2,
Credit = 3
}
int iBuyerNum = 0;
clsBuyer cBuyer = null;
int iPaymentIndex = -1;
PaymentMethod eMethod = PaymentMethod.NotSet;
int iCheckNumber = 0;
double fAmount = 0.0;
string sComments = "";
public clsPayment()
{
}
public clsPayment(int BuyerNumber, PaymentMethod Method, int CheckNumber, double Amount, string Comments)
{
iBuyerNum = BuyerNumber;
cBuyer = clsDB.Buyers[iBuyerNum];
iPaymentIndex = 0;
if (clsDB.Payments[BuyerNumber] != null)
{
foreach (clsPayment Payment in clsDB.Payments[BuyerNumber].Values)
{
if (Payment.Index >= iPaymentIndex)
{
iPaymentIndex = Payment.Index + 1;
}
}
}
eMethod = Method;
iCheckNumber = CheckNumber;
fAmount = Amount;
sComments = Comments;
}
public clsPayment(int BuyerNumber, int PaymentIndex, PaymentMethod Method, int CheckNumber, double Amount, string Comments)
{
iBuyerNum = BuyerNumber;
iPaymentIndex = PaymentIndex;
eMethod = Method;
iCheckNumber = CheckNumber;
fAmount = Amount;
sComments = Comments;
}
public override void Load(IDataReader dbReader)
{
base.Load(dbReader);
}
protected override void DBCommit(DB.CommitAction Action, IDbConnection DatabaseConnection, IDbTransaction Transaction)
{
IDbCommand dbCommit = DatabaseConnection.CreateCommand();
dbCommit.Transaction = Transaction;
dbCommit.CommandText = "INSERT INTO Payments (CommitAction, BuyerID, PaymentIndex, PaymentMethod, CheckNumber, Amount, Comments) VALUES (@CommitAction, @BuyerID, @PaymentIndex, @PaymentMethod, @CheckNumber, @Amount, @Comments)";
IDbDataParameter param = dbCommit.CreateParameter();
param.ParameterName = "@CommitAction";
param.Value = (int)Action;
dbCommit.Parameters.Add(param);
param = dbCommit.CreateParameter();
param.ParameterName = "@BuyerID";
param.Value = this.BuyerNumber;
dbCommit.Parameters.Add(param);
param = dbCommit.CreateParameter();
param.ParameterName = "@PaymentIndex";
param.Value = this.Index;
dbCommit.Parameters.Add(param);
param = dbCommit.CreateParameter();
param.ParameterName = "@PaymentMethod";
param.Value = this.Method;
dbCommit.Parameters.Add(param);
param = dbCommit.CreateParameter();
param.ParameterName = "@CheckNumber";
param.Value = this.CheckNumber;
dbCommit.Parameters.Add(param);
param = dbCommit.CreateParameter();
param.ParameterName = "@Amount";
param.Value = this.Amount;
dbCommit.Parameters.Add(param);
param = dbCommit.CreateParameter();
param.ParameterName = "@Comments";
param.Value = this.Comments;
dbCommit.Parameters.Add(param);
dbCommit.ExecuteNonQuery();
}
public static bool operator ==(clsPayment Payment1, clsPayment Payment2)
{
if ((object)Payment1 == null && (object)Payment2 == null)
{
return true;
}
else if ((object)Payment1 == null || (object)Payment2 == null)
{
return false;
}
else
{
return (Payment1.CompareTo(Payment2) == 0);
}
}
public static bool operator !=(clsPayment Payment1, clsPayment Payment2)
{
return !(Payment1 == Payment2);
}
#region IComparable<clsExhibitor> Members
public int CompareTo(clsPayment other)
{
return this.BuyerNumber.CompareTo(other.BuyerNumber);
}
#endregion
#region ISerializable Members
protected clsPayment(SerializationInfo info, StreamingContext context)
{
if (info == null)
{
throw new System.ArgumentNullException("info");
}
iBuyerNum = (int)info.GetValue("iBuyerNum", typeof(int));
cBuyer = (clsBuyer)info.GetValue("cBuyer", typeof(clsBuyer));
iPaymentIndex = (int)info.GetValue("iPaymentIndex", typeof(int));
eMethod = (PaymentMethod)info.GetValue("eMethod", typeof(PaymentMethod));
iCheckNumber = (int)info.GetValue("iCheckNumber", typeof(int));
fAmount = (double)info.GetValue("fAmount", typeof(double));
sComments = (string)info.GetValue("sComments", typeof(string));
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
{
throw new System.ArgumentNullException("info");
}
info.AddValue("iBuyerNum", iBuyerNum);
info.AddValue("cBuyer", cBuyer);
info.AddValue("iPaymentIndex", iPaymentIndex);
info.AddValue("eMethod", eMethod);
info.AddValue("iCheckNumber", iCheckNumber);
info.AddValue("fAmount", fAmount);
info.AddValue("sComments", sComments);
}
#endregion
public int BuyerNumber
{
get
{
return iBuyerNum;
}
}
public clsBuyer Buyer
{
get
{
if (clsDB.Buyers != null)
{
return clsDB.Buyers[iBuyerNum];
}
else
{
return cBuyer;
}
}
}
public int Index
{
get
{
return iPaymentIndex;
}
}
public PaymentMethod Method
{
get
{
return eMethod;
}
set
{
eMethod = value;
}
}
public string Method_String
{
get
{
if (eMethod == PaymentMethod.Cash)
{
return "Cash";
}
else if (eMethod == PaymentMethod.Check)
{
return string.Format("Check (#{0})", iCheckNumber);
}
else if (eMethod == PaymentMethod.Credit)
{
//return string.Format("Credit (${0:0.00} + ${1:0.00})", fAmount, this.Surcharge);
return "Credit Card";
}
else
{
return "";
}
}
}
public string Fee_String
{
get
{
if (eMethod == PaymentMethod.Credit)
{
return String.Format("Credit Card Fee ({0:0.00}% of ${1:#,##0.00})", CREDIT_CARD_FEE * 100, fAmount);
}
else
{
return "";
}
}
}
public int CheckNumber
{
get
{
return iCheckNumber;
}
set
{
iCheckNumber = value;
}
}
public double Amount
{
get
{
return fAmount;
}
set
{
fAmount = value;
}
}
public double Surcharge
{
get
{
if (eMethod == PaymentMethod.Credit)
{
return Math.Round(fAmount * CREDIT_CARD_FEE, 2);// Math.Round((fAmount * (1 / (1 - 0.0275))) - fAmount, 2);
}
else
{
return 0;
}
}
}
public string Comments
{
get
{
return sComments;
}
set
{
sComments = value;
}
}
}
namespace Setup
{
public class Payments : AuctionDBSetup
{
public Payments()
{
TABLE_NAME = "Payments";
TABLE_COLUMNS = new List<SQLColumn>() {
new SQLColumn("BuyerID", "int", "0", true),
new SQLColumn("PaymentIndex", "int", "0", true),
new SQLColumn("PaymentMethod", "int", "0", false), /*Pay now (cash or check) or Mail bill*/
new SQLColumn("CheckNumber", "int", "0", false),
new SQLColumn("Amount", "Money", "0", false),
new SQLColumn("Comments", "nvarchar(1000)", "0", false)
};
}
}
}
}
| 35.368715 | 300 | 0.479861 | [
"MIT"
] | The-Missing-Semicolon/Livestock-Auction | Livestock Auction/DB/clsPayments.cs | 18,995 | C# |
using System.Collections.Generic;
using System.IO;
using System.Linq;
using DataAPI.Service.Helpers;
using DataAPI.Service.Search;
using NUnit.Framework;
namespace DataAPI.Service.Test.Search
{
[TestFixture]
public class SearchResultStreamTest
{
[Test]
public void StreamWithoutItemsDoesntThrowExceptions()
{
var asyncEnumerable = AsyncEnumerableBuilder.FromArray(new string[0]);
using var sut = new SearchResultStream(asyncEnumerable);
using var streamReader = new StreamReader(sut);
var actual = ReadAllLines(streamReader).ToList();
CollectionAssert.IsEmpty(actual);
}
[Test]
public void StreamReturnsInputItems()
{
var expected = new[] {"Item1", "Item2", "Item3"};
var asyncEnumerable = AsyncEnumerableBuilder.FromArray(expected);
using var sut = new SearchResultStream(asyncEnumerable);
using var streamReader = new StreamReader(sut);
var actual = ReadAllLines(streamReader).ToList();
CollectionAssert.AreEqual(expected, actual);
}
private static IEnumerable<string> ReadAllLines(TextReader streamReader)
{
string line;
while ((line = streamReader.ReadLine()) != null)
{
yield return line;
}
}
}
}
| 32.931818 | 83 | 0.604555 | [
"MIT"
] | mindleaving/dataapi | DataAPI.Service.Test/Search/SearchResultStreamTest.cs | 1,451 | C# |
using EventSourcingCQRS.Domain.Core;
using System;
using EventSourcingCQRS.Domain.CustomerModule;
using EventSourcingCQRS.Domain.ProductModule;
using System.Collections.Generic;
using System.Linq;
using EventSourcingCQRS.Domain.Validation;
namespace EventSourcingCQRS.Domain.CartModule
{
public class Cart : AggregateBase<CartId>
{
public const int ProductQuantityThreshold = 50;
//Needed for persistence purposes
private Cart()
{
Items = new List<CartItem>();
}
private CustomerId CustomerId { get; set; }
private List<CartItem> Items { get; set; }
public Cart(CartId cartId, CustomerId customerId) : this()
{
if (cartId == null)
{
throw new ArgumentNullException(nameof(cartId));
}
if (customerId == null)
{
throw new ArgumentNullException(nameof(customerId));
}
RaiseEvent(new CartCreatedEvent(cartId, customerId));
}
public void AddProduct(CartItem cartItem)
{
var validator = new ProductInInventoryValidator().And(new CartItemNotInCartValidator(Items));
var result = validator.Validate(cartItem);
if (!result.IsValid)
{
throw new CartException( result.Errors.First().ErrorMessage);
}
RaiseEvent(new ProductAddedEvent(cartItem.ProductId, cartItem.Quantity));
}
public void ChangeProductQuantity(ProductId productId, int quantity)
{
var validator = new ProductInInventoryValidator().And(new CartItemInCartValidator(Items));
var result = validator.Validate(new CartItem(productId, quantity));
if (!result.IsValid)
{
throw new CartException(result.Errors.First().ErrorMessage);
}
RaiseEvent(new ProductQuantityChangedEvent(productId, GetCartItemByProduct(productId).Quantity, quantity));
}
public override string ToString()
{
return $"{{ Id: \"{Id}\", CustomerId: \"{CustomerId.IdAsString()}\", Items: [{string.Join(", ", Items.Select(x => x.ToString()))}] }}";
}
internal void Apply(CartCreatedEvent ev)
{
Id = ev.AggregateId;
CustomerId = ev.CustomerId;
}
internal void Apply(ProductAddedEvent ev)
{
Items.Add(new CartItem(ev.ProductId, ev.Quantity));
}
internal void Apply(ProductQuantityChangedEvent ev)
{
var existingItem = Items.Single(x => x.ProductId == ev.ProductId);
Items.Remove(existingItem);
Items.Add(existingItem.WithQuantity(ev.NewQuantity));
}
private CartItem GetCartItemByProduct(ProductId productId)
{
return Items.Single(x => x.ProductId == productId);
}
}
}
| 31.478723 | 147 | 0.601893 | [
"MIT"
] | kmiltiadous/EventSourcingCQRS | EventSourcingCQRS.Domain/CartModule/Cart.cs | 2,961 | C# |
using ScottPlot.Drawing;
using ScottPlot.MinMaxSearchStrategies;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Linq.Expressions;
using System.Runtime.InteropServices;
namespace ScottPlot.Plottable
{
public abstract class SignalPlotBase<T> : IPlottable, IHasPointsGenericX<double, T> where T : struct, IComparable
{
protected IMinMaxSearchStrategy<T> Strategy = new SegmentedTreeMinMaxSearchStrategy<T>();
protected bool MaxRenderIndexLowerYSPromise = false;
protected bool MaxRenderIndexHigherMinRenderIndexPromise = false;
protected bool FillColor1MustBeSetPromise = false;
protected bool FillColor2MustBeSetPromise = false;
public int XAxisIndex { get; set; } = 0;
public int YAxisIndex { get; set; } = 0;
public bool IsVisible { get; set; } = true;
public bool StepDisplay { get; set; } = false;
public float MarkerSize { get; set; } = 5;
public double OffsetX { get; set; } = 0;
public T OffsetY { get; set; } = default;
public double LineWidth { get; set; } = 1;
public string Label { get; set; } = null;
public Color Color { get; set; } = Color.Green;
public LineStyle LineStyle { get; set; } = LineStyle.Solid;
/// <summary>
/// If enabled, parallel processing will be used to calculate pixel positions for high density datasets.
/// </summary>
public bool UseParallel { get; set; } = true;
/// <summary>
/// If fill above and/or below is enabled, this defines the baseline level.
/// </summary>
public double BaselineY { get; set; } = 0;
/// <summary>
/// If fill is enabled, a baseline will be drawn using this color.
/// </summary>
public Color BaselineColor { get; set; } = Color.Black;
/// <summary>
/// If fill is enabled, a baseline will be drawn using this width.
/// </summary>
public float BaselineWidth { get; set; } = 1;
/// <summary>
/// If fill is enabled, this color will be used to fill the area below the curve above BaselineY.
/// </summary>
public Color? GradientFillColor1 { get; set; } = null;
/// <summary>
/// If fill is enabled, this color will be used to fill the area above the curve below BaselineY.
/// </summary>
public Color? GradientFillColor2 { get; set; } = null;
/// <summary>
/// When markers are visible on the line (low density mode) this is True
/// </summary>
private bool ShowMarkersInLegend { get; set; } = false;
protected T[] _Ys;
public virtual T[] Ys
{
get => _Ys;
set
{
if (value == null)
throw new Exception("Y data cannot be null");
MaxRenderIndexLowerYSPromise = MaxRenderIndex > value.Length - 1;
_Ys = value;
Strategy.SourceArray = _Ys;
}
}
private double _SampleRate = 1;
public double SampleRate
{
get => _SampleRate;
set
{
if (value <= 0)
throw new Exception("SampleRate must be greater then zero");
_SampleRate = value;
_SamplePeriod = 1.0 / value;
}
}
private double _SamplePeriod = 1;
public double SamplePeriod
{
get => _SamplePeriod;
set
{
if (_SamplePeriod <= 0)
throw new Exception("SamplePeriod must be greater then zero");
_SamplePeriod = value;
_SampleRate = 1.0 / value;
}
}
protected int _MinRenderIndex = 0;
public int MinRenderIndex
{
get => _MinRenderIndex;
set
{
if (value < 0)
throw new ArgumentException("MinRenderIndex must be positive");
MaxRenderIndexHigherMinRenderIndexPromise = value > MaxRenderIndex;
_MinRenderIndex = value;
}
}
protected int _maxRenderIndex = 0;
public int MaxRenderIndex
{
get => _maxRenderIndex;
set
{
if (value < 0)
throw new ArgumentException("MaxRenderIndex must be positive");
MaxRenderIndexHigherMinRenderIndexPromise = MinRenderIndex > value;
MaxRenderIndexLowerYSPromise = value > _Ys.Length - 1;
_maxRenderIndex = value;
}
}
private int DensityLevelCount = 0;
private Color[] PenColorsByDensity;
public Color[] DensityColors
{
set
{
if (value != null)
{
// turn the ramp into a pen triangle
DensityLevelCount = value.Length * 2 - 1;
PenColorsByDensity = new Color[DensityLevelCount];
for (int i = 0; i < value.Length; i++)
{
PenColorsByDensity[i] = value[i];
PenColorsByDensity[DensityLevelCount - 1 - i] = value[i];
}
}
}
}
private FillType _FillType = FillType.NoFill;
public FillType FillType
{
get => _FillType;
set
{
FillColor1MustBeSetPromise = (_FillColor1 == null && value != FillType.NoFill);
FillColor2MustBeSetPromise = (_FillColor2 == null && value == FillType.FillAboveAndBelow);
_FillType = value;
}
}
private Color? _FillColor1 = null;
public Color? FillColor1
{
get => _FillColor1;
set
{
FillColor1MustBeSetPromise = (value == null && FillType != FillType.NoFill);
_FillColor1 = value;
}
}
private Color? _FillColor2 = null;
public Color? FillColor2
{
get => _FillColor2;
set
{
FillColor2MustBeSetPromise = (value == null && FillType == FillType.FillAboveAndBelow);
_FillColor2 = value;
}
}
/// <summary>
/// This expression adds two parameters of the generic type used by this signal plot.
/// </summary>
private readonly Func<T, T, T> AddYsGenericExpression;
/// <summary>
/// Add two Y values (of the generic type used by this signal plot) and return the result as a double
/// </summary>
private double AddYs(T y1, T y2) => Convert.ToDouble(AddYsGenericExpression(y1, y2));
/// <summary>
/// Add two Y values (of the generic type used by this signal plot) and return the result as a the same type
/// </summary>
private T AddYsGeneric(T y1, T y2) => AddYsGenericExpression(y1, y2);
public SignalPlotBase()
{
ParameterExpression paramA = Expression.Parameter(typeof(T), "a");
ParameterExpression paramB = Expression.Parameter(typeof(T), "b");
BinaryExpression bodyAdd = Expression.Add(paramA, paramB);
AddYsGenericExpression = Expression.Lambda<Func<T, T, T>>(bodyAdd, paramA, paramB).Compile();
}
/// <summary>
/// Replace a single Y value
/// </summary>
/// <param name="index">array index to replace</param>
/// <param name="newValue">new value</param>
public void Update(int index, T newValue) => Strategy.updateElement(index, newValue);
/// <summary>
/// Replace a range of Y values
/// </summary>
/// <param name="firstIndex">index to begin replacing</param>
/// <param name="lastIndex">last index to replace</param>
/// <param name="newData">source for new data</param>
/// <param name="fromData">source data offset</param>
public void Update(int firstIndex, int lastIndex, T[] newData, int fromData = 0) =>
Strategy.updateRange(firstIndex, lastIndex, newData, fromData);
/// <summary>
/// Replace all Y values from the given index through the end of the array
/// </summary>
/// <param name="firstIndex">first index to begin replacing</param>
/// <param name="newData">new values</param>
public void Update(int firstIndex, T[] newData) => Update(firstIndex, newData.Length, newData);
/// <summary>
/// Replace all Y values with new ones
/// </summary>
/// <param name="newData">new Y values</param>
public void Update(T[] newData) => Update(0, newData.Length, newData);
public virtual AxisLimits GetAxisLimits()
{
double xMin = _SamplePeriod * MinRenderIndex;
double xMax = _SamplePeriod * MaxRenderIndex;
Strategy.MinMaxRangeQuery(MinRenderIndex, MaxRenderIndex, out double yMin, out double yMax);
if (double.IsNaN(yMin) || double.IsNaN(yMax))
throw new InvalidOperationException("Signal data must not contain NaN");
if (double.IsInfinity(yMin) || double.IsInfinity(yMax))
throw new InvalidOperationException("Signal data must not contain Infinity");
double offsetY = Convert.ToDouble(OffsetY);
return new AxisLimits(
xMin: xMin + OffsetX,
xMax: xMax + OffsetX,
yMin: yMin + offsetY,
yMax: yMax + offsetY);
}
/// <summary>
/// Render when the data is zoomed out so much that it just looks like a vertical line.
/// </summary>
private void RenderSingleLine(PlotDimensions dims, Graphics gfx, Pen penHD)
{
// this function is for when the graph is zoomed so far out its entire display is a single vertical pixel column
Strategy.MinMaxRangeQuery(MinRenderIndex, MaxRenderIndex, out double yMin, out double yMax);
double offsetY = Convert.ToDouble(OffsetY);
PointF point1 = new(dims.GetPixelX(OffsetX), dims.GetPixelY(yMin + offsetY));
PointF point2 = new(dims.GetPixelX(OffsetX), dims.GetPixelY(yMax + offsetY));
gfx.DrawLine(penHD, point1, point2);
}
/// <summary>
/// Render when the data is zoomed in such that there is more than 1 column per data point.
/// Rendering is accomplished by drawing a straight line from point to point.
/// </summary>
private void RenderLowDensity(PlotDimensions dims, Graphics gfx, int visibleIndex1, int visibleIndex2, Brush brush, Pen penLD, Pen penHD)
{
int capacity = visibleIndex2 - visibleIndex1 + 2;
List<PointF> linePoints = new(capacity);
if (visibleIndex2 > _Ys.Length - 2)
visibleIndex2 = _Ys.Length - 2;
if (visibleIndex2 > MaxRenderIndex - 1)
visibleIndex2 = MaxRenderIndex - 1;
if (visibleIndex1 < 0)
visibleIndex1 = 0;
if (visibleIndex1 < MinRenderIndex)
visibleIndex1 = MinRenderIndex;
for (int i = visibleIndex1; i <= visibleIndex2 + 1; i++)
{
double yCoordinateWithOffset = AddYs(Ys[i], OffsetY);
float yPixel = dims.GetPixelY(yCoordinateWithOffset);
float xPixel = dims.GetPixelX(_SamplePeriod * i + OffsetX);
PointF linePoint = new(xPixel, yPixel);
linePoints.Add(linePoint);
}
if (linePoints.Count > 1)
{
PointF[] pointsArray = linePoints.ToArray();
ValidatePoints(pointsArray);
if (StepDisplay)
pointsArray = GetStepPoints(pointsArray);
if (penLD.Width > 0)
gfx.DrawLines(penLD, pointsArray);
switch (FillType)
{
case FillType.NoFill:
break;
case FillType.FillAbove:
FillToInfinity(dims, gfx, linePoints[0].X, linePoints[linePoints.Count - 1].X, pointsArray, true);
break;
case FillType.FillBelow:
FillToInfinity(dims, gfx, linePoints[0].X, linePoints[linePoints.Count - 1].X, pointsArray, false);
break;
case FillType.FillAboveAndBelow:
FillToBaseline(dims, gfx, linePoints[0].X, linePoints[linePoints.Count - 1].X, pointsArray, BaselineY);
break;
default:
throw new InvalidOperationException("unsupported fill type");
}
if (MarkerSize > 0)
{
// make markers transition away smoothly by making them smaller as the user zooms out
float pixelsBetweenPoints = (float)(_SamplePeriod * dims.DataWidth / dims.XSpan);
float zoomTransitionScale = Math.Min(1, pixelsBetweenPoints / 10);
float markerPxDiameter = MarkerSize * zoomTransitionScale;
float markerPxRadius = markerPxDiameter / 2;
if (markerPxRadius > .25)
{
ShowMarkersInLegend = true;
// adjust marker offset to improve rendering on Linux and MacOS
float markerOffsetX = (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) ? 0 : 1;
foreach (PointF point in linePoints)
gfx.FillEllipse(brush: brush,
x: point.X - markerPxRadius + markerOffsetX, y: point.Y - markerPxRadius,
width: markerPxDiameter, height: markerPxDiameter);
}
else
{
ShowMarkersInLegend = false;
}
}
}
}
/// <summary>
/// Convert scatter plot points (connected by diagnal lines) to step plot points (connected by right angles)
/// by inserting an extra point between each of the original data points.
/// </summary>
private PointF[] GetStepPoints(PointF[] pointsArray)
{
PointF[] pointsStep = new PointF[pointsArray.Length * 2 - 1];
for (int i = 0; i < pointsArray.Length - 1; i++)
{
pointsStep[i * 2] = pointsArray[i];
pointsStep[i * 2 + 1] = new PointF(pointsArray[i + 1].X, pointsArray[i].Y);
}
pointsStep[pointsStep.Length - 1] = pointsArray[pointsArray.Length - 1];
return pointsStep;
}
private class IntervalMinMax
{
public float x;
public float Min;
public float Max;
public IntervalMinMax(float x, float Min, float Max)
{
this.x = x;
this.Min = Min;
this.Max = Max;
}
public IEnumerable<PointF> GetPoints()
{
yield return new PointF(x, Min);
yield return new PointF(x, Max);
}
}
private IntervalMinMax CalcInterval(int xPx, double offsetPoints, double columnPointCount, PlotDimensions dims)
{
int index1 = (int)(offsetPoints + columnPointCount * xPx);
int index2 = (int)(offsetPoints + columnPointCount * (xPx + 1));
if (index1 < 0)
index1 = 0;
if (index1 < MinRenderIndex)
index1 = MinRenderIndex;
if (index2 > _Ys.Length - 1)
index2 = _Ys.Length - 1;
if (index2 > MaxRenderIndex)
index2 = MaxRenderIndex;
// get the min and max value for this column
Strategy.MinMaxRangeQuery(index1, index2, out double lowestValue, out double highestValue);
float yPxHigh = dims.GetPixelY(lowestValue + Convert.ToDouble(OffsetY));
float yPxLow = dims.GetPixelY(highestValue + Convert.ToDouble(OffsetY));
return new IntervalMinMax(xPx, yPxLow, yPxHigh);
}
/// <summary>
/// Render the data when there is more than one data point per pixel column.
/// Each pixel column therefore represents multiple data points.
/// Rendering is optimized by determining the min/max for each pixel column, then a single line is drawn connecting those values.
/// </summary>
private void RenderHighDensity(PlotDimensions dims, Graphics gfx, double offsetPoints, double columnPointCount, Pen penHD)
{
int dataColumnFirst = (int)Math.Ceiling((-1 - offsetPoints + MinRenderIndex) / columnPointCount - 1);
int dataColumnLast = (int)Math.Ceiling((MaxRenderIndex - offsetPoints) / columnPointCount);
dataColumnFirst = Math.Max(0, dataColumnFirst);
dataColumnLast = Math.Min((int)dims.DataWidth, dataColumnLast);
if (dataColumnFirst >= dataColumnLast)
return;
var columns = Enumerable.Range(dataColumnFirst, dataColumnLast - dataColumnFirst);
float xPixelStart = dataColumnFirst + dims.DataOffsetX;
float xPixelEnd = dataColumnLast + dims.DataOffsetX;
IEnumerable<IntervalMinMax> intervals;
if (UseParallel)
{
intervals = columns
.AsParallel()
.AsOrdered()
.Select(xPx => CalcInterval(xPx, offsetPoints, columnPointCount, dims))
.AsSequential();
}
else
{
intervals = columns
.Select(xPx => CalcInterval(xPx, offsetPoints, columnPointCount, dims));
}
PointF[] linePoints = intervals
.SelectMany(c => c.GetPoints())
.ToArray();
// adjust order of points to enhance anti-aliasing
PointF buf;
for (int i = 1; i < linePoints.Length / 2; i++)
{
if (linePoints[i * 2].Y >= linePoints[i * 2 - 1].Y)
{
buf = linePoints[i * 2];
linePoints[i * 2] = linePoints[i * 2 + 1];
linePoints[i * 2 + 1] = buf;
}
}
for (int i = 0; i < linePoints.Length; i++)
linePoints[i].X += dims.DataOffsetX;
if (linePoints.Length > 0)
{
ValidatePoints(linePoints);
gfx.DrawLines(penHD, linePoints);
}
switch (FillType)
{
case FillType.NoFill:
break;
case FillType.FillAbove:
FillToInfinity(dims, gfx, xPixelStart, xPixelEnd, linePoints, true);
break;
case FillType.FillBelow:
FillToInfinity(dims, gfx, xPixelStart, xPixelEnd, linePoints, false);
break;
case FillType.FillAboveAndBelow:
FillToBaseline(dims, gfx, xPixelStart, xPixelEnd, linePoints, BaselineY);
break;
default:
throw new InvalidOperationException("unsupported fill type");
}
}
/// <summary>
/// Shade the region abvove or below the curve (to infinity) by drawing a polygon to the edge of the visible plot area.
/// </summary>
internal void FillToInfinity(PlotDimensions dims, Graphics gfx, float xPxStart, float xPxEnd, PointF[] linePoints, bool fillToPositiveInfinity)
{
float minVal = 0;
float maxVal = (dims.DataHeight * (fillToPositiveInfinity ? -1 : 1)) + dims.DataOffsetY;
PointF first = new(xPxStart, maxVal);
PointF last = new(xPxEnd, maxVal);
PointF[] points = new PointF[] { first }
.Concat(linePoints)
.Concat(new PointF[] { last })
.ToArray();
Rectangle gradientRectangle = new(
x: (int)first.X,
y: (int)minVal - (fillToPositiveInfinity ? 2 : 0),
width: (int)(last.X - first.X),
height: (int)dims.Height);
using var brush = new LinearGradientBrush(gradientRectangle, _FillColor1.Value, GradientFillColor1 ?? _FillColor1.Value, LinearGradientMode.Vertical);
gfx.FillPolygon(brush, points);
}
private PointF? GetIntersection(PointF point1, PointF point2, PointF baselineStart, PointF baselineEnd)
{
double a1 = point2.Y - point1.Y;
double b1 = point1.X - point2.X;
double c1 = a1 * (point1.X) + b1 * (point1.Y);
double a2 = baselineEnd.Y - baselineStart.Y;
double b2 = baselineStart.X - baselineEnd.X;
double c2 = a2 * (baselineStart.X) + b2 * (baselineStart.Y);
double d = a1 * b2 - a2 * b1;
if (d == 0)
{
// Lines do not intersect. This could also be the case if the plot is zoomed out too much.
return null;
}
else
{
double x = (b2 * c1 - b1 * c2) / d;
double y = (a1 * c2 - a2 * c1) / d;
return new PointF((float)x, (float)y);
}
}
/// <summary>
/// Shade the region abvove and below the curve (to the baseline level) by drawing two polygons
/// </summary>
internal void FillToBaseline(PlotDimensions dims, Graphics gfx, float xPxStart, float xPxEnd, PointF[] linePoints, double baselineY)
{
int baseline = (int)dims.GetPixelY(baselineY);
PointF first = new(xPxStart, baseline);
PointF last = new(xPxEnd, baseline);
PointF[] points = new PointF[] { first }
.Concat(linePoints)
.Concat(new PointF[] { last })
.ToArray();
PointF baselinePointStart = new(linePoints[0].X, baseline);
PointF baselinePointEnd = new(linePoints[linePoints.Length - 1].X, baseline);
var pointList = points.ToList();
int newlyAddedItems = 0;
for (int i = 1; i < points.Length + newlyAddedItems; ++i)
{
if ((pointList[i - 1].Y > baseline && pointList[i].Y < baseline) ||
(pointList[i - 1].Y < baseline && pointList[i].Y > baseline))
{
var intersection = GetIntersection(pointList[i], pointList[i - 1], baselinePointStart, baselinePointEnd);
if (intersection != null)
{
pointList.Insert(i, intersection.Value);
newlyAddedItems++;
i++;
}
}
}
// Above graph
var aboveRect = GetFillRectangle(dims, xPxStart, xPxEnd, FillType.FillAbove);
if (aboveRect.Height != 0 && aboveRect.Width != 0)
{
using var brush = new LinearGradientBrush(aboveRect, _FillColor1.Value, GradientFillColor1 ?? _FillColor1.Value, LinearGradientMode.Vertical);
gfx.FillPolygon(brush,
new PointF[] { first }
.Concat(pointList.Where(p => p.Y <= baseline).ToArray())
.Concat(new PointF[] { last })
.ToArray());
}
// Below graph
var belowRect = GetFillRectangle(dims, xPxStart, xPxEnd, FillType.FillBelow);
if (belowRect.Height != 0 && belowRect.Width != 0)
{
using var brush = new LinearGradientBrush(belowRect, _FillColor2.Value, GradientFillColor2 ?? _FillColor2.Value, LinearGradientMode.Vertical);
gfx.FillPolygon(brush,
new PointF[] { first }
.Concat(pointList.Where(p => p.Y >= baseline).ToArray())
.Concat(new PointF[] { last })
.ToArray());
}
// Draw baseline
using var baselinePen = GDI.Pen(BaselineColor, BaselineWidth);
gfx.DrawLine(baselinePen, baselinePointStart, baselinePointEnd);
}
private Rectangle GetFillRectangle(PlotDimensions dims, float startX, float xPxEnd, FillType fillType)
{
float maxVal = (dims.DataHeight * (fillType == FillType.FillAbove ? -1 : 1));
Rectangle rectangle = new(
x: (int)startX,
y: 0,
width: (int)(xPxEnd - startX),
height: (int)maxVal);
return rectangle;
}
/// <summary>
/// Render similar to high density mode except use multiple colors to represent density distributions.
/// </summary>
private void RenderHighDensityDistributionParallel(PlotDimensions dims, Graphics gfx, double offsetPoints, double columnPointCount)
{
int xPxStart = (int)Math.Ceiling((-1 - offsetPoints) / columnPointCount - 1);
int xPxEnd = (int)Math.Ceiling((_Ys.Length - offsetPoints) / columnPointCount);
xPxStart = Math.Max(0, xPxStart);
xPxEnd = Math.Min((int)dims.DataWidth, xPxEnd);
if (xPxStart >= xPxEnd)
return;
int capacity = (xPxEnd - xPxStart) * 2 + 1;
List<PointF> linePoints = new(capacity);
var levelValues = Enumerable.Range(xPxStart, xPxEnd - xPxStart)
.AsParallel()
.AsOrdered()
.Select(xPx =>
{
// determine data indexes for this pixel column
int index1 = (int)(offsetPoints + columnPointCount * xPx);
int index2 = (int)(offsetPoints + columnPointCount * (xPx + 1));
if (index1 < 0)
index1 = 0;
if (index1 > _Ys.Length - 1)
index1 = _Ys.Length - 1;
if (index2 > _Ys.Length - 1)
index2 = _Ys.Length - 1;
var indexes = Enumerable.Range(0, DensityLevelCount + 1).Select(x => x * (index2 - index1 - 1) / (DensityLevelCount));
var levelsValues = new ArraySegment<T>(_Ys, index1, index2 - index1)
.OrderBy(x => x)
.Where((y, i) => indexes.Contains(i)).ToArray();
return (xPx, levelsValues);
})
.ToArray();
List<PointF[]> linePointsLevels = levelValues
.Select(x => x.levelsValues
.Select(y => new PointF(
x: x.xPx + dims.DataOffsetX,
y: dims.GetPixelY(AddYs(y, OffsetY))))
.ToArray())
.ToList();
for (int i = 0; i < DensityLevelCount; i++)
{
linePoints.Clear();
for (int j = 0; j < linePointsLevels.Count; j++)
{
if (i + 1 < linePointsLevels[j].Length)
{
linePoints.Add(linePointsLevels[j][i]);
linePoints.Add(linePointsLevels[j][i + 1]);
}
}
PointF[] pointsArray = linePoints.ToArray();
ValidatePoints(pointsArray);
using (Pen densityPen = GDI.Pen(PenColorsByDensity[i]))
{
gfx.DrawLines(densityPen, pointsArray);
}
switch (FillType)
{
case FillType.NoFill:
break;
case FillType.FillAbove:
FillToInfinity(dims, gfx, xPxStart, xPxEnd, pointsArray, true);
break;
case FillType.FillBelow:
FillToInfinity(dims, gfx, xPxStart, xPxEnd, pointsArray, false);
break;
case FillType.FillAboveAndBelow:
FillToBaseline(dims, gfx, xPxStart, xPxEnd, pointsArray, BaselineY);
break;
default:
throw new InvalidOperationException("unsupported fill type");
}
}
}
public override string ToString()
{
string label = string.IsNullOrWhiteSpace(this.Label) ? "" : $" ({this.Label})";
return $"PlottableSignalBase{label} with {PointCount} points ({typeof(T).Name})";
}
public int PointCount { get => _Ys.Length; }
public LegendItem[] GetLegendItems()
{
var singleLegendItem = new LegendItem()
{
label = Label,
color = Color,
lineStyle = LineStyle,
lineWidth = LineWidth,
markerShape = ShowMarkersInLegend ? MarkerShape.filledCircle : MarkerShape.none,
markerSize = ShowMarkersInLegend ? MarkerSize : 0
};
return new LegendItem[] { singleLegendItem };
}
public virtual void Render(PlotDimensions dims, Bitmap bmp, bool lowQuality = false)
{
using var gfx = GDI.Graphics(bmp, dims, lowQuality);
using var brush = GDI.Brush(Color);
using var penLD = GDI.Pen(Color, (float)LineWidth, LineStyle, true);
using var penHD = GDI.Pen(Color, (float)LineWidth, LineStyle.Solid, true);
double dataSpanUnits = _Ys.Length * _SamplePeriod;
double columnSpanUnits = dims.XSpan / dims.DataWidth;
double columnPointCount = (columnSpanUnits / dataSpanUnits) * _Ys.Length;
double offsetUnits = dims.XMin - OffsetX;
double offsetPoints = offsetUnits / _SamplePeriod;
int visibleIndex1 = (int)(offsetPoints);
int visibleIndex2 = (int)(offsetPoints + columnPointCount * (dims.DataWidth + 1));
int visiblePointCount = visibleIndex2 - visibleIndex1;
double pointsPerPixelColumn = visiblePointCount / dims.DataWidth;
double dataWidthPx2 = visibleIndex2 - visibleIndex1 + 2;
bool densityLevelsAvailable = DensityLevelCount > 0 && pointsPerPixelColumn > DensityLevelCount;
double firstPointX = dims.GetPixelX(OffsetX);
double lastPointX = dims.GetPixelX(_SamplePeriod * (_Ys.Length - 1) + OffsetX);
double dataWidthPx = lastPointX - firstPointX;
double columnsWithData = Math.Min(dataWidthPx, dataWidthPx2);
if (columnsWithData < 1)
{
RenderSingleLine(dims, gfx, penHD);
}
else if (pointsPerPixelColumn > 1)
{
if (densityLevelsAvailable)
RenderHighDensityDistributionParallel(dims, gfx, offsetPoints, columnPointCount);
else
RenderHighDensity(dims, gfx, offsetPoints, columnPointCount, penHD);
}
else
{
RenderLowDensity(dims, gfx, visibleIndex1, visibleIndex2, brush, penLD, penHD);
}
}
private void ValidatePoints(PointF[] points)
{
foreach (PointF pt in points)
if (float.IsNaN(pt.Y))
throw new InvalidOperationException("Data must not contain NaN");
}
public void ValidateData(bool deep = false)
{
// check Y values
if (Ys is null)
throw new InvalidOperationException("ys cannot be null");
if (deep)
Validate.AssertAllReal("ys", Ys);
// check render indexes
if (MinRenderIndex < 0 || MinRenderIndex > MaxRenderIndex)
throw new IndexOutOfRangeException("minRenderIndex must be between 0 and maxRenderIndex");
if ((MaxRenderIndex > Ys.Length - 1) || MaxRenderIndex < 0)
throw new IndexOutOfRangeException("maxRenderIndex must be a valid index for ys[]");
if (MaxRenderIndexLowerYSPromise)
throw new IndexOutOfRangeException("maxRenderIndex must be a valid index for ys[]");
if (MaxRenderIndexHigherMinRenderIndexPromise)
throw new IndexOutOfRangeException("minRenderIndex must be lower maxRenderIndex");
// check misc styling options
if (FillColor1MustBeSetPromise)
throw new InvalidOperationException($"A Color must be assigned to FillColor1 to use fill type '{FillType}'");
if (FillColor2MustBeSetPromise)
throw new InvalidOperationException($"A Color must be assigned to FillColor2 to use fill type '{FillType}'");
}
/// <summary>
/// Return the X/Y coordinates of the point nearest the X position
/// </summary>
/// <param name="x">X position in plot space</param>
/// <returns></returns>
public (double x, T y, int index) GetPointNearestX(double x)
{
int index = (int)((x - OffsetX) / SamplePeriod);
index = Math.Max(index, MinRenderIndex);
index = Math.Min(index, MaxRenderIndex);
return (OffsetX + index * SamplePeriod, AddYsGeneric(Ys[index], OffsetY), index);
}
}
}
| 41.617254 | 162 | 0.536948 | [
"MIT"
] | KanishkKhurana/ScottPlot | src/ScottPlot/Plottable/SignalPlotBase.cs | 34,253 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using System.Xml.Linq;
using System.Xml.XPath;
using Gov.Lclb.Cllb.Interfaces;
using Gov.Lclb.Cllb.Interfaces.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Configuration;
namespace Watchdog.Pages
{
public static class AppTypeCheckerExtensions
{
public static void AddConfigItem(this Dictionary<string, string> obj, string name, string prefix, IConfigurationRoot input)
{
string sourceKey = $"{prefix}_{name}";
string value = input[sourceKey];
if (!string.IsNullOrEmpty(value))
{
obj.Add(name, value);
}
}
public static Boolean DynamicsAttributeToBoolean(this XAttribute attribute)
{
Boolean result = false;
if (attribute != null)
{
string value = attribute.Value;
if (!string.IsNullOrEmpty(value))
{
result = (value.Equals("1") || value.ToLower().Equals("true"));
}
}
return result;
}
}
public class ApplicationTypesCheckModel : PageModel
{
private readonly IConfigurationRoot Configuration;
public ApplicationTypesCheckModel(IConfiguration configuration)
{
Configuration = (ConfigurationRoot)configuration;
allKeys = new List<string>();
allRowSizes = new Dictionary<string, int>();
allFieldNames = new Dictionary<string, List<string>>();
devFieldNames = new Dictionary<string, List<string>>();
tstFieldNames = new Dictionary<string, List<string>>();
prdFieldNames = new Dictionary<string, List<string>>();
allFieldClasses = new Dictionary<string, Dictionary<string, string>>();
devAppTypes = new Dictionary<string, MicrosoftDynamicsCRMadoxioApplicationtype>();
tstAppTypes = new Dictionary<string, MicrosoftDynamicsCRMadoxioApplicationtype>();
prdAppTypes = new Dictionary<string, MicrosoftDynamicsCRMadoxioApplicationtype>();
Parallel.Invoke(
delegate() { GetAppTypes("DEV", Configuration, devAppTypes, devFieldNames, allKeys); },
delegate() { GetAppTypes("TST", Configuration, tstAppTypes, tstFieldNames, allKeys); },
delegate() { GetAppTypes("PRD", Configuration, prdAppTypes, prdFieldNames, allKeys); }
);
foreach (var item in allFieldNames.Keys)
{
var d = new Dictionary<string, string>();
foreach (var field in allFieldNames[item])
{
d.Add(field, GetRowClass(devFieldNames[item].Contains(field).ToString(), tstFieldNames[item].Contains(field).ToString(), prdFieldNames[item].Contains(field).ToString()));
}
allFieldClasses.Add(item, d);
}
}
public List<string> allKeys;
public Dictionary<string, MicrosoftDynamicsCRMadoxioApplicationtype> devAppTypes;
public Dictionary<string, MicrosoftDynamicsCRMadoxioApplicationtype> tstAppTypes;
public Dictionary<string, MicrosoftDynamicsCRMadoxioApplicationtype> prdAppTypes;
public Dictionary<string, int> allRowSizes;
public Dictionary<string, List<string>> allFieldNames;
public Dictionary<string, List<string>> devFieldNames;
public Dictionary<string, List<string>> tstFieldNames;
public Dictionary<string, List<string>> prdFieldNames;
public Dictionary<string, Dictionary<string, string>> allFieldClasses;
// true if there is a difference
public bool IsDifferent (string dev, string test, string prod)
{
bool result = true;
if (dev == test && test == prod)
{
result = false;
}
return result;
}
public string GetRowClass (string dev, string test, string prod)
{
string result;
if (IsDifferent(dev, test, prod))
{
result = "different";
}
else
{
result = "same";
}
return result;
}
private void GetAppTypes (string prefix, IConfigurationRoot configuration, Dictionary<string, MicrosoftDynamicsCRMadoxioApplicationtype> appTypesDict, Dictionary<string, List<string>> envFields, List<string> allKeys)
{
IConfigurationRoot config = CreateConfig(prefix, configuration);
IDynamicsClient client = DynamicsSetupUtil.SetupDynamics(config);
// get all of the app types.
var appTypes = client.Applicationtypes.Get().Value;
foreach (var item in appTypes)
{
appTypesDict.Add(item.AdoxioName, item);
if (! allKeys.Contains (item.AdoxioName))
{
allKeys.Add(item.AdoxioName);
}
if (! string.IsNullOrEmpty (item.AdoxioFormreference))
{
List<string> fields = new List<string>();
// add the form fields.
try
{
var systemForm = client.Systemforms.GetByKey(item.AdoxioFormreference);
string formXml = systemForm.Formxml;
var tabs = XDocument.Parse(formXml).XPathSelectElements("form/tabs/tab");
if (tabs != null)
{
foreach (var tab in tabs)
{
// get the sections
var sections = tab.XPathSelectElements("columns/column/sections/section");
foreach (var section in sections)
{
var sectionLabels = section.XPathSelectElements("labels/label");
string sectionName = "";
foreach (var sectionLabel in sectionLabels)
{
sectionName = sectionLabel.Attribute("description").Value;
}
// get the cells.
var cells = section.XPathSelectElements("rows/row/cell");
foreach (var cell in cells)
{
bool cellShowLabel = cell.Attribute("showlabel").DynamicsAttributeToBoolean();
var control = cell.XPathSelectElement("control");
string fieldName = "";
if (cellShowLabel)
{
var cellLabels = cell.XPathSelectElements("labels/label");
foreach (var cellLabel in cellLabels)
{
fieldName = cellLabel.Attribute("description").Value;
}
}
else // use section name
{
fieldName = sectionName;
}
if (!string.IsNullOrEmpty(fieldName) && control != null && control.Attribute("datafieldname") != null)
{
string datafieldname = control.Attribute("datafieldname").Value;
}
if (! allFieldNames.ContainsKey(item.AdoxioName))
{
allFieldNames.Add(item.AdoxioName, new List<string>());
}
if (! allFieldNames[item.AdoxioName].Contains (fieldName))
{
allFieldNames[item.AdoxioName].Add(fieldName);
}
// add for this environment.
if (!envFields.ContainsKey(item.AdoxioName))
{
envFields.Add(item.AdoxioName, new List<string>());
}
if (!envFields[item.AdoxioName].Contains(fieldName))
{
envFields[item.AdoxioName].Add(fieldName);
}
}
}
}
}
}
catch (Exception)
{
}
}
// now calculate the row height.
int rowSize = 31;
if (allFieldNames.ContainsKey(item.AdoxioName))
{
rowSize += allFieldNames[item.AdoxioName].Count + 1;
}
if (!allRowSizes.ContainsKey(item.AdoxioName))
{
allRowSizes.Add(item.AdoxioName, rowSize);
}
else
{
if (allRowSizes[item.AdoxioName] < rowSize)
{
allRowSizes[item.AdoxioName] = rowSize;
}
}
}
}
private IConfigurationRoot CreateConfig (string prefix, IConfigurationRoot input)
{
var strings = new Dictionary<string, string>();
strings.AddConfigItem("ADFS_OAUTH2_URI", prefix, input);
strings.AddConfigItem("DYNAMICS_APP_GROUP_RESOURCE", prefix, input);
strings.AddConfigItem("DYNAMICS_APP_GROUP_CLIENT_ID", prefix, input);
strings.AddConfigItem("DYNAMICS_APP_GROUP_SECRET", prefix, input);
strings.AddConfigItem("DYNAMICS_USERNAME", prefix, input);
strings.AddConfigItem("DYNAMICS_PASSWORD", prefix, input);
strings.AddConfigItem("DYNAMICS_ODATA_URI", prefix, input);
strings.AddConfigItem("DYNAMICS_NATIVE_ODATA_URI", prefix, input);
ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
// Add defaultConfigurationStrings
configurationBuilder.AddInMemoryCollection(strings);
return (IConfigurationRoot) configurationBuilder.Build();
}
public void OnGet()
{
}
}
}
| 39.575862 | 224 | 0.48253 | [
"Apache-2.0"
] | BrendanBeachBC/jag-lcrb-carla-public | watchdog/Pages/ApplicationTypesCheck.cshtml.cs | 11,477 | C# |
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using mphdict.Models.morph;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using uSofTrod.generalTypes.Models;
namespace mphdict.Models.morph
{
public partial class mphContext
{
private static object o = new object();
static private alphadigit[] _talpha=null;
public alphadigit[] talpha
{
get
{
if (_talpha == null)
{
lock (o)
{
_talpha = (from c in this.alphadigits orderby c.digit, c.ls select c).ToArray();
}
}
return _talpha;
}
}
static private short[] _pclass = null;
public short[] pclass
{
get
{
if (_pclass == null)
{
lock (o)
{
_pclass = (from c in this.indents orderby c.type select c.type).ToArray();
}
}
return _pclass;
}
}
static private List<ps[]> _pofs = null;
public List<ps[]> pofs
{
get
{
if (_pofs == null)
{
lock (o)
{
_pofs = new List<ps[]>();
var gc_gr = (from c in this.grs where !string.IsNullOrEmpty(c.part_of_speech) orderby c.part_of_speech select c).ToArray();
var gc_parts = (from c in this.parts where ((!string.IsNullOrEmpty(c.com)) && (c.id > 70)) orderby c.com select c).ToArray();
_pofs.Add((from c in gc_gr select new ps() { id = c.id, name = c.part_of_speech, category = "Змінні" }).ToArray());
_pofs.Add(gc_parts.Select(c => new ps() { id = c.id, name = c.com, category = "Незмінні" }).ToArray());
}
}
return _pofs;
}
}
static private indents_base[] _indents = null;
public indents_base[] indent
{
get
{
if (_indents == null)
{
lock (o)
{
//_indents = (from c in this.words_list.AsNoTracking()
// group c by c.type into pg
// join ind in this.indents.Include(t => t.gr).AsNoTracking()
// on pg.FirstOrDefault().type equals ind.type
// orderby ind.type
// select new indents_base()
// {
// CountOfWords = pg.Count(),
// comment = ind.comment,
// type = ind.type,
// field3 = ind.field3,
// field4 = ind.field4,
// gr_id = ind.gr_id,
// grName = ind.gr.part_of_speech,
// indent = ind.indent
// }).ToArray();
//This query do not work in vs2017 (EF CORE 1.1)
_indents = (from c in this.indents.Include(t => t.gr).Include(t => t.words_list).AsNoTracking()
orderby c.type
select new indents_base()
{
CountOfWords = c.words_list.Count(),
comment = c.comment,
type = c.type,
field3 = c.field3,
field4 = c.field4,
gr_id = c.gr_id,
grName = c.gr.part_of_speech,
indent = c.indent
}).ToArray();
}
}
return _indents;
}
}
private static langid _lid;
public langid lid
{
get
{
if (_lid == null)
{
lock (o)
{
_lid = (from c in this.lang select c).FirstOrDefault();
}
}
return _lid;
}
}
// перетворення рядка в код (якщо не потрібно враховувати \', то askip=true)
private IQueryable<word_param> setWordListQueryFilter(filter f, IQueryable<word_param> q)
{
if ((f.isStrFiltering) && (!string.IsNullOrEmpty(f.str)))
{
string s = sharedTypes.atod(f.str, talpha);
//switch (f.fetchType)
//{
// case FetchType.StartsWith:
// q = q.Where(c => c.digit.StartsWith(s));
// //q = q.Where(c => c.reestr.Replace("\"","").StartsWith(f.str));
// break;
// case FetchType.EndsWith:
// q = q.Where(c => c.digit.EndsWith(s));
// //q = q.Where(c => c.reestr.Replace("\"", "").EndsWith(f.str));
// break;
// case FetchType.Contains:
// q = q.Where(c => c.digit.Contains(s));
// //q = q.Where(c => c.reestr.Replace("\"", "").Contains(f.str));
// break;
//}
q = q.Where(c => EF.Functions.Like(c.digit, s));
}
if (f.ispclass) {
q = q.Where(c => c.type == f.pclass);
}
if (f.ispofs) {
if (f.pofs > 70)
{
q = q.Where(c => c.part == f.pofs);
}
else {
q = q.Where(c => ((c.parts.gr_id == f.pofs)&&(c.part<70)));
}
}
return q;
}
public async Task<int> CountWords(filter f)
{
var q = (from c in this.words_list select c);
q = setWordListQueryFilter(f, q);
return await q.CountAsync();
}
public async Task<word_param[]> getPage(filter f, int start, int pageSize)
{
var q = (from c in this.words_list.AsNoTracking() select c);
q = setWordListQueryFilter(f, q);
if (f.isInverse)
q = q.OrderBy(c => c.reverse).ThenBy(c => c.field2).Skip(start * pageSize).Take(pageSize);
else
q = q.OrderBy(c=>c.digit).ThenBy(c=>c.field2).Skip(start * pageSize).Take(pageSize);
//var sql = q.ToSql();
return await q.ToArrayAsync();
}
public async Task<word_param_base> searchWord(filter f, string word)
{
string w = f.isInverse == true ? sharedTypes.atod(new string(word.Reverse().ToArray()), talpha) : sharedTypes.atod(word, talpha);
int start = 0;
var q = (from c in this.words_list select c);
q = setWordListQueryFilter(f, q);
if (f.isInverse)
{
q = q.OrderBy(c => c.reverse).ThenBy(c => c.field2);
start = await (from c in q where w.CompareTo(c.reverse) > 0 select c).CountAsync();
}
else
{
q = q.OrderBy(c => c.digit).ThenBy(c => c.field2);
start = await (from c in q where w.CompareTo(c.digit) > 0 select c).CountAsync();
}
int pagenumber = start / 100;
int count = q.Count();
if (count <= start)
{
q = q.Skip((start - 1)).Take(1);
}
else
{
q = q.Skip(start).Take(1);
}
word_param wp = await q.FirstOrDefaultAsync();
word_param_base r = null;
if (wp != null)
{
r = (new word_param_base() { CountOfWords = count, wordsPageNumber = pagenumber, accent = wp.accent, digit = wp.digit, field2 = wp.field2, field5 = wp.field5, field6 = wp.field6, field7 = wp.field7, isdel = wp.isdel, isproblem = wp.isproblem, nom_old = wp.nom_old, own = wp.own, part = wp.part, reestr = wp.reestr, reverse = wp.reverse, suppl_accent = wp.suppl_accent, type = wp.type });
}
return r;
}
public async Task<word_param> getEntry(int id)
{
var word_param = await (from c in this.words_list.AsNoTracking() where c.nom_old == id select c).FirstOrDefaultAsync();
indents indent = await (from c in this.indents.AsNoTracking() where c.type == word_param.type select c).FirstOrDefaultAsync();
List<flexes> flex = await (from c in this.flexes.AsNoTracking() where (c.type == word_param.type && (c.field2 > 0)) orderby c.field2, c.id select c).ToListAsync();
accents_class aclass = await (from c in this.accents_class.AsNoTracking() select c).FirstOrDefaultAsync();
accent[] acnt = await (from c in this.accent.AsNoTracking() where c.accent_type == word_param.accent select c).ToArrayAsync();
//minor_acc macc = await (from c in this.minor_acc.AsNoTracking() where c.nom_old == id select c).FirstOrDefaultAsync();
parts part = await (from c in this.parts.AsNoTracking() where c.id == word_param.part select c).FirstOrDefaultAsync();
word_param.parts = part;
word_param.indents = indent;
word_param.indents.flexes = flex;
word_param.accents_class = aclass;
word_param.accents_class.accents = acnt;
//word_param.minor_acc = macc;
return word_param;
}
public async Task<pclass_info> getPClass(short id)
{
return new pclass_info()
{
cls = (from c in indents where (c.type == id) select c).FirstOrDefault(),
flexes = await (from c in this.flexes.AsNoTracking() where (c.type == id) orderby c.field2, c.id select c).ToArrayAsync()
};
}
}
public class pclass_info {
public indents_base cls { get; set; }
public flexes_base[] flexes { get; set; }
}
public class filter
{
//public FetchType fetchType { get; set; }
//pattern="[A-za-zА-Яа-я\sЇїЁёЄєІі]+"
//[RegularExpression(@"^([A-za-zА-Яа-я\sЇїЁёЄєІі]+)$", ErrorMessage = "Invalid characters")]
public string str { get; set; }
public bool isStrFiltering { get; set; }
public bool isInverse { get; set; }
public bool ispclass { get; set; }
public short pclass { get; set; }
public bool ispofs { get; set; }
public byte pofs { get; set; }
}
public class pclsfilter
{
public bool ispofsPcls { get; set; }
public byte pofsPcls { get; set; }
public short pclassPcls { get; set; }
}
}
| 41.883636 | 403 | 0.454419 | [
"MIT"
] | LinguisticAndInformationSystems/mphdict | src/mphdict/mphObj.cs | 11,606 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNextGen.VMwareCloudSimple.Latest.Inputs
{
/// <summary>
/// Virtual disk model
/// </summary>
public sealed class VirtualDiskArgs : Pulumi.ResourceArgs
{
/// <summary>
/// Disk's Controller id
/// </summary>
[Input("controllerId", required: true)]
public Input<string> ControllerId { get; set; } = null!;
/// <summary>
/// Disk's independence mode type
/// </summary>
[Input("independenceMode", required: true)]
public Input<Pulumi.AzureNextGen.VMwareCloudSimple.Latest.DiskIndependenceMode> IndependenceMode { get; set; } = null!;
/// <summary>
/// Disk's total size
/// </summary>
[Input("totalSize", required: true)]
public Input<int> TotalSize { get; set; } = null!;
/// <summary>
/// Disk's id
/// </summary>
[Input("virtualDiskId")]
public Input<string>? VirtualDiskId { get; set; }
public VirtualDiskArgs()
{
}
}
}
| 28.851064 | 127 | 0.599558 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/VMwareCloudSimple/Latest/Inputs/VirtualDiskArgs.cs | 1,356 | C# |
namespace Antrv.FFMpeg.Interop;
public enum AVPictureStructure
{
/// <summary>
/// unknown
/// </summary>
AV_PICTURE_STRUCTURE_UNKNOWN,
/// <summary>
/// coded as top field
/// </summary>
AV_PICTURE_STRUCTURE_TOP_FIELD,
/// <summary>
/// coded as bottom field
/// </summary>
AV_PICTURE_STRUCTURE_BOTTOM_FIELD,
/// <summary>
/// coded as frame
/// </summary>
AV_PICTURE_STRUCTURE_FRAME,
}
| 18.28 | 38 | 0.612691 | [
"MIT"
] | antrv/ffmpeg-net | Antrv.FFMpeg/Interop/libavcodec/avcodec.h/AVPictureStructure.cs | 459 | C# |
using TARGET = UnityEngine.RectTransform;
namespace Lean.Transition.Method
{
/// <summary>This component allows you to transition the RectTransform's anchorMin value.</summary>
[UnityEngine.HelpURL(LeanTransition.HelpUrlPrefix + "LeanRectTransformAnchorMin")]
[UnityEngine.AddComponentMenu(LeanTransition.MethodsMenuPrefix + "RectTransform/RectTransform.anchorMin" + LeanTransition.MethodsMenuSuffix + "(LeanRectTransformAnchorMin)")]
public class LeanRectTransformAnchorMin : LeanMethodWithStateAndTarget
{
public override System.Type GetTargetType()
{
return typeof(TARGET);
}
public override void Register()
{
PreviousState = Register(GetAliasedTarget(Data.Target), Data.Value, Data.Duration, Data.Ease);
}
public static LeanState Register(TARGET target, UnityEngine.Vector2 value, float duration, LeanEase ease = LeanEase.Smooth)
{
var state = LeanTransition.SpawnWithTarget(State.Pool, target);
state.Value = value;
state.Ease = ease;
return LeanTransition.Register(state, duration);
}
[System.Serializable]
public class State : LeanStateWithTarget<TARGET>
{
[UnityEngine.Tooltip("The anchorMin value will transition to this.")]
[UnityEngine.Serialization.FormerlySerializedAs("AnchorMin")]public UnityEngine.Vector2 Value;
[UnityEngine.Tooltip("This allows you to control how the transition will look.")]
public LeanEase Ease = LeanEase.Smooth;
[System.NonSerialized] private UnityEngine.Vector2 oldValue;
public override int CanFill
{
get
{
return Target != null && Target.anchorMin != Value ? 1 : 0;
}
}
public override void FillWithTarget()
{
Value = Target.anchorMin;
}
public override void BeginWithTarget()
{
oldValue = Target.anchorMin;
}
public override void UpdateWithTarget(float progress)
{
Target.anchorMin = UnityEngine.Vector2.LerpUnclamped(oldValue, Value, Smooth(Ease, progress));
}
public static System.Collections.Generic.Stack<State> Pool = new System.Collections.Generic.Stack<State>(); public override void Despawn() { Pool.Push(this); }
}
public State Data;
}
}
namespace Lean.Transition
{
public static partial class LeanExtensions
{
public static TARGET anchorMinTransition(this TARGET target, UnityEngine.Vector2 value, float duration, LeanEase ease = LeanEase.Smooth)
{
Method.LeanRectTransformAnchorMin.Register(target, value, duration, ease); return target;
}
}
} | 30.407407 | 175 | 0.747462 | [
"MIT"
] | AbhishekPardhi/GameDev-Project-1 | Monkey KickOff/Assets/Lean/Transition/Methods/RectTransform/LeanRectTransformAnchorMin.cs | 2,463 | C# |
using System.Collections.Generic;
namespace GG.Portafolio.Shared
{
public class ErrorApi
{
public string Type { get; set; }
public string Title { get; set; }
public int Status { get; set; }
public string Detail { get; set; }
public string Instance { get; set; }
public string AdditionalProp1 { get; set; }
public string AdditionalProp2 { get; set; }
public string AdditionalProp3 { get; set; }
public Dictionary<string,string[]> Errors { get; set; }
}
}
| 21.076923 | 63 | 0.60219 | [
"MIT"
] | guillermo-galvan/portafolio | src/GG.Portafolio.Share/ErrorApi.cs | 550 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace coderush.Models
{
public class CashBank
{
public int CashBankId { get; set; }
[Display(Name = "Cash / Bank Name")]
public string CashBankName { get; set; }
public string Description { get; set; }
}
}
| 23.411765 | 48 | 0.675879 | [
"MIT"
] | 2644783865/Asp.Net-Core-Inventory-Order-Management-System | coderush/Models/CashBank.cs | 400 | C# |
#pragma warning disable 1591
using System;
namespace Braintree
{
public class KeyValueNode<T> : SearchNode<T> where T : SearchRequest
{
public KeyValueNode(string name, T parent) : base(name, parent)
{
}
public T Is(object value) {
Parent.AddCriteria(Name, value.ToString());
return Parent;
}
}
}
| 18.85 | 72 | 0.588859 | [
"MIT"
] | chrisjdiver/braintree_dotnet | Braintree/KeyValueNode.cs | 377 | C# |
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("FixedChannel.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("FixedChannel.Tests")]
[assembly: AssemblyCopyright("Copyright © 2021")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("1DC7DC48-8518-4CDA-A771-4691C049C605")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.055556 | 84 | 0.742336 | [
"Apache-2.0"
] | REDNIGHT/FixedChannel | RNKitSolution/FixedChannel.Tests/Properties/AssemblyInfo.cs | 1,373 | C# |
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Host;
namespace Microsoft.CodeAnalysis.CodeFixes
{
/// <summary>
/// An <see cref="IWorkspaceService"/> that can be retrieved from
/// <see cref="Workspace.Services"/> for retrieving and applying
/// code fixes.
/// </summary>
public interface ICodeFixService : IWorkspaceService
{
/// <summary>
/// Retrieves the <see cref="CodeFixProvider"/>, if any, of the given
/// name for given language.
/// </summary>
/// <param name="language">The language supported by the code fix provider. See <see cref="LanguageNames"/>.</param>
/// <param name="codeFixName">The name of the provider, such as the ones listed in <see cref="CodeFixNames"/>.</param>
/// <returns>The provider, or <see langword="null"/>.</returns>
CodeFixProvider GetCodeFixProvider(string language, string codeFixName);
/// <summary>
/// Gets all the available code fixes from all registered providers for the
/// specified document.
/// </summary>
/// <param name="document">The <see cref="Document"/> to retrieve code fixes for.</param>
/// <param name="analyzers">Optional <see cref="DiagnosticAnalyzer"/>s to run during the code fix population.</param>
/// <param name="cancellationToken">Optional <see cref="CancellationToken"/> for the operation.</param>
/// <returns>Available code fixes, if any.</returns>
Task<ImmutableArray<ICodeFix>> GetCodeFixes(Document document, ImmutableArray<DiagnosticAnalyzer> analyzers = default(ImmutableArray<DiagnosticAnalyzer>), CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the available code fixes from the given provider for the
/// specified document.
/// </summary>
/// <param name="document">The <see cref="Document"/> to retrieve code fixes for.</param>
/// <param name="codeFixName">The name of a code fix provider, such as one listed in <see cref="CodeFixNames"/>.</param>
/// <param name="analyzers">Optional <see cref="DiagnosticAnalyzer"/>s to run during the code fix population.</param>
/// <param name="cancellationToken">Optional <see cref="CancellationToken"/> for the operation.</param>
/// <returns>Available code fixes, if any.</returns>
Task<ImmutableArray<ICodeFix>> GetCodeFixes(Document document, string codeFixName, ImmutableArray<DiagnosticAnalyzer> analyzers = default(ImmutableArray<DiagnosticAnalyzer>), CancellationToken cancellationToken = default(CancellationToken));
}
} | 60.152174 | 249 | 0.68558 | [
"MIT"
] | kzu/roslynator | src/Roslynator.Interfaces/ICodeFixService.cs | 2,769 | C# |
//********************************************************************************************************************************
// Filename: InterfaceType.cs
// Owner: Richard Dunkley
//********************************************************************************************************************************
// Copyright © Richard Dunkley 2020
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the
// License. You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable
// law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and
// limitations under the License.
//********************************************************************************************************************************
namespace VHDLCodeGen.ARM.AXI
{
/// <summary>
/// Enumerates the various types of AXI bus interfaces.
/// </summary>
public enum InterfaceType
{
/// <summary>
/// The interface is a master.
/// </summary>
/// <remarks>This interface will direct the read and write transactions on the bus.</remarks>
Master,
/// <summary>
/// The interface is a slave.
/// </summary>
/// <remarks>This interface will receive the read and write transactions on the bus directed towards it.</remarks>
Slave,
/// <summary>
/// The interface is a monitor.
/// </summary>
/// <remarks>This interface will monitor a AXI bus without performing any transaction upon it.</remarks>
Monitor,
}
}
| 43.6 | 131 | 0.549312 | [
"Apache-2.0"
] | RDunkley/VHDLCodeGen | VHDLCodeGen/ARM/AXI/InterfaceType.cs | 1,747 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System.Collections.Generic;
using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Http;
using Aliyun.Acs.Core.Transform;
using Aliyun.Acs.Core.Utils;
using Aliyun.Acs.Cms.Transform;
using Aliyun.Acs.Cms.Transform.V20180308;
namespace Aliyun.Acs.Cms.Model.V20180308
{
public class NodeUninstallRequest : RpcAcsRequest<NodeUninstallResponse>
{
public NodeUninstallRequest()
: base("Cms", "2018-03-08", "NodeUninstall", "cms", "openAPI")
{
}
private string instanceId;
public string InstanceId
{
get
{
return instanceId;
}
set
{
instanceId = value;
DictionaryUtil.Add(QueryParameters, "InstanceId", value);
}
}
public override NodeUninstallResponse GetResponse(UnmarshallerContext unmarshallerContext)
{
return NodeUninstallResponseUnmarshaller.Unmarshall(unmarshallerContext);
}
}
}
| 29.844828 | 98 | 0.711727 | [
"Apache-2.0"
] | AxiosCros/aliyun-openapi-net-sdk | aliyun-net-sdk-cms/Cms/Model/V20180308/NodeUninstallRequest.cs | 1,731 | C# |
namespace SampleLiveCoin
{
using System;
using System.ComponentModel;
using System.Windows;
using Ecng.Common;
using Ecng.Xaml;
using StockSharp.BusinessEntities;
using StockSharp.LiveCoin;
using StockSharp.Logging;
using StockSharp.Localization;
public partial class MainWindow
{
private bool _isConnected;
public LiveCoinTrader Trader;
private readonly SecuritiesWindow _securitiesWindow = new SecuritiesWindow();
private readonly TradesWindow _tradesWindow = new TradesWindow();
private readonly MyTradesWindow _myTradesWindow = new MyTradesWindow();
private readonly OrdersWindow _ordersWindow = new OrdersWindow();
private readonly PortfoliosWindow _portfoliosWindow = new PortfoliosWindow();
private readonly LogManager _logManager = new LogManager();
public MainWindow()
{
InitializeComponent();
Title = Title.Put("LiveCoin");
_ordersWindow.MakeHideable();
_myTradesWindow.MakeHideable();
_tradesWindow.MakeHideable();
_securitiesWindow.MakeHideable();
_portfoliosWindow.MakeHideable();
Instance = this;
_logManager.Sources.Add(MemoryStatistics.Instance);
_logManager.Listeners.Add(new FileLogListener { LogDirectory = "StockSharp_LiveCoin" });
}
protected override void OnClosing(CancelEventArgs e)
{
_ordersWindow.DeleteHideable();
_myTradesWindow.DeleteHideable();
_tradesWindow.DeleteHideable();
_securitiesWindow.DeleteHideable();
_portfoliosWindow.DeleteHideable();
_securitiesWindow.Close();
_tradesWindow.Close();
_myTradesWindow.Close();
_ordersWindow.Close();
_portfoliosWindow.Close();
if (Trader != null)
Trader.Dispose();
base.OnClosing(e);
}
public static MainWindow Instance { get; private set; }
private void ConnectClick(object sender, RoutedEventArgs e)
{
if (!_isConnected)
{
if (Key.Text.IsEmpty())
{
MessageBox.Show(this, LocalizedStrings.Str3689);
return;
}
else if (Secret.Password.IsEmpty())
{
MessageBox.Show(this, LocalizedStrings.Str3690);
return;
}
if (Trader == null)
{
// create connector
Trader = new LiveCoinTrader();// { LogLevel = LogLevels.Debug };
_logManager.Sources.Add(Trader);
Trader.Restored += () => this.GuiAsync(() =>
{
// update gui labels
ChangeConnectStatus(true);
MessageBox.Show(this, LocalizedStrings.Str2958);
});
// subscribe on connection successfully event
Trader.Connected += () =>
{
// set flag (connection is established)
_isConnected = true;
// update gui labels
this.GuiAsync(() => ChangeConnectStatus(true));
};
Trader.Disconnected += () => this.GuiAsync(() => ChangeConnectStatus(false));
// subscribe on connection error event
Trader.ConnectionError += error => this.GuiAsync(() =>
{
// update gui labels
ChangeConnectStatus(false);
MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2959);
});
// subscribe on error event
Trader.Error += error =>
this.GuiAsync(() => MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2955));
// subscribe on error of market data subscription event
Trader.MarketDataSubscriptionFailed += (security, msg, error) =>
this.GuiAsync(() => MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2956Params.Put(msg.DataType, security)));
Trader.NewSecurity += _securitiesWindow.SecurityPicker.Securities.Add;
Trader.NewMyTrade += _myTradesWindow.TradeGrid.Trades.Add;
Trader.NewTrade += _tradesWindow.TradeGrid.Trades.Add;
Trader.NewOrder += _ordersWindow.OrderGrid.Orders.Add;
Trader.NewPortfolio += _portfoliosWindow.PortfolioGrid.Portfolios.Add;
Trader.NewPosition += _portfoliosWindow.PortfolioGrid.Positions.Add;
// subscribe on error of order registration event
Trader.OrderRegisterFailed += _ordersWindow.OrderGrid.AddRegistrationFail;
// subscribe on error of order cancelling event
Trader.OrderCancelFailed += OrderFailed;
Trader.MassOrderCancelFailed += (transId, error) =>
this.GuiAsync(() => MessageBox.Show(this, error.ToString(), LocalizedStrings.Str716));
// set market data provider
_securitiesWindow.SecurityPicker.MarketDataProvider = Trader;
ShowSecurities.IsEnabled = ShowTrades.IsEnabled =
ShowMyTrades.IsEnabled = ShowOrders.IsEnabled =
ShowPortfolios.IsEnabled = true;
}
Trader.Key = Key.Text;
Trader.Secret = Secret.Password;
// clear password box for security reason
//Secret.Clear();
Trader.Connect();
}
else
{
Trader.Disconnect();
}
}
private void OrderFailed(OrderFail fail)
{
this.GuiAsync(() =>
{
MessageBox.Show(this, fail.Error.ToString(), LocalizedStrings.Str153);
});
}
private void ChangeConnectStatus(bool isConnected)
{
_isConnected = isConnected;
ConnectBtn.Content = isConnected ? LocalizedStrings.Disconnect : LocalizedStrings.Connect;
}
private void ShowSecuritiesClick(object sender, RoutedEventArgs e)
{
ShowOrHide(_securitiesWindow);
}
private void ShowTradesClick(object sender, RoutedEventArgs e)
{
ShowOrHide(_tradesWindow);
}
private void ShowMyTradesClick(object sender, RoutedEventArgs e)
{
ShowOrHide(_myTradesWindow);
}
private void ShowOrdersClick(object sender, RoutedEventArgs e)
{
ShowOrHide(_ordersWindow);
}
private void ShowPortfoliosClick(object sender, RoutedEventArgs e)
{
ShowOrHide(_portfoliosWindow);
}
private static void ShowOrHide(Window window)
{
if (window == null)
throw new ArgumentNullException(nameof(window));
if (window.Visibility == Visibility.Visible)
window.Hide();
else
window.Show();
}
}
}
| 27.023256 | 127 | 0.706713 | [
"Apache-2.0"
] | DimTrdr/StockSharp | Samples/LiveCoin/SampleLiveCoin/MainWindow.xaml.cs | 5,810 | C# |
using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("AWSSDK.GuardDuty")]
#if BCL35
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - Amazon GuardDuty. Enable Amazon GuardDuty to continuously monitor and process AWS data sources to identify threats to your AWS accounts and workloads. You can add customization by uploading additional threat intelligence lists and IP safe lists. You can list security findings, suspend, and disable the service.")]
#elif BCL45
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (4.5) - Amazon GuardDuty. Enable Amazon GuardDuty to continuously monitor and process AWS data sources to identify threats to your AWS accounts and workloads. You can add customization by uploading additional threat intelligence lists and IP safe lists. You can list security findings, suspend, and disable the service.")]
#elif PCL
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (PCL) - Amazon GuardDuty. Enable Amazon GuardDuty to continuously monitor and process AWS data sources to identify threats to your AWS accounts and workloads. You can add customization by uploading additional threat intelligence lists and IP safe lists. You can list security findings, suspend, and disable the service.")]
#elif UNITY
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (Unity) - Amazon GuardDuty. Enable Amazon GuardDuty to continuously monitor and process AWS data sources to identify threats to your AWS accounts and workloads. You can add customization by uploading additional threat intelligence lists and IP safe lists. You can list security findings, suspend, and disable the service.")]
#elif NETSTANDARD13
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 1.3)- Amazon GuardDuty. Enable Amazon GuardDuty to continuously monitor and process AWS data sources to identify threats to your AWS accounts and workloads. You can add customization by uploading additional threat intelligence lists and IP safe lists. You can list security findings, suspend, and disable the service.")]
#elif NETSTANDARD20
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 2.0)- Amazon GuardDuty. Enable Amazon GuardDuty to continuously monitor and process AWS data sources to identify threats to your AWS accounts and workloads. You can add customization by uploading additional threat intelligence lists and IP safe lists. You can list security findings, suspend, and disable the service.")]
#else
#error Unknown platform constant - unable to set correct AssemblyDescription
#endif
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("Amazon Web Services SDK for .NET")]
[assembly: AssemblyCompany("Amazon.com, Inc")]
[assembly: AssemblyCopyright("Copyright 2009-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("3.3")]
[assembly: AssemblyFileVersion("3.3.100.20")]
#if WINDOWS_PHONE || UNITY
[assembly: System.CLSCompliant(false)]
# else
[assembly: System.CLSCompliant(true)]
#endif
#if BCL
[assembly: System.Security.AllowPartiallyTrustedCallers]
#endif | 69 | 402 | 0.790469 | [
"Apache-2.0"
] | k0lpak/aws-sdk-net | sdk/src/Services/GuardDuty/Properties/AssemblyInfo.cs | 4,071 | C# |
namespace Stripe
{
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using Stripe.Infrastructure;
public class CreditNote : StripeEntity, IHasId, IHasMetadata, IHasObject
{
/// <summary>
/// Unique identifier for the object.
/// </summary>
[JsonProperty("id")]
public string Id { get; set; }
/// <summary>
/// String representing the object’s type. Objects of the same type share the same value.
/// </summary>
[JsonProperty("object")]
public string Object { get; set; }
/// <summary>
/// Credit note amount.
/// </summary>
[JsonProperty("amount")]
public long Amount { get; set; }
/// <summary>
/// Time at which the object was created. Measured in seconds since the Unix epoch.
/// </summary>
[JsonProperty("created")]
[JsonConverter(typeof(DateTimeConverter))]
public DateTime Created { get; set; }
/// <summary>
/// Three-letter ISO currency code, in lowercase. Must be a supported currency.
/// </summary>
[JsonProperty("currency")]
public string Currency { get; set; }
#region Expandable Customer
/// <summary>
/// ID of the customer associated with that credit note.
/// </summary>
[JsonIgnore]
public string CustomerId
{
get => this.InternalCustomer?.Id;
set => this.InternalCustomer = SetExpandableFieldId(value, this.InternalCustomer);
}
[JsonIgnore]
public Customer Customer
{
get => this.InternalCustomer?.ExpandedObject;
set => this.InternalCustomer = SetExpandableFieldObject(value, this.InternalCustomer);
}
[JsonProperty("customer")]
[JsonConverter(typeof(ExpandableFieldConverter<Customer>))]
internal ExpandableField<Customer> InternalCustomer { get; set; }
#endregion
#region Expandable CustomerBalanceTransaction
/// <summary>
/// ID of the customer balance transaction related to this credit note.
/// </summary>
[JsonIgnore]
public string CustomerBalanceTransactionId
{
get => this.InternalCustomerBalanceTransaction?.Id;
set => this.InternalCustomerBalanceTransaction = SetExpandableFieldId(value, this.InternalCustomerBalanceTransaction);
}
[JsonIgnore]
public CustomerBalanceTransaction CustomerBalanceTransaction
{
get => this.InternalCustomerBalanceTransaction?.ExpandedObject;
set => this.InternalCustomerBalanceTransaction = SetExpandableFieldObject(value, this.InternalCustomerBalanceTransaction);
}
[JsonProperty("customer_balance_transaction")]
[JsonConverter(typeof(ExpandableFieldConverter<CustomerBalanceTransaction>))]
internal ExpandableField<CustomerBalanceTransaction> InternalCustomerBalanceTransaction { get; set; }
#endregion
#region Expandable Invoice
/// <summary>
/// ID of the invoice associated with that credit note.
/// </summary>
[JsonIgnore]
public string InvoiceId
{
get => this.InternalInvoice?.Id;
set => this.InternalInvoice = SetExpandableFieldId(value, this.InternalInvoice);
}
[JsonIgnore]
public Invoice Invoice
{
get => this.InternalInvoice?.ExpandedObject;
set => this.InternalInvoice = SetExpandableFieldObject(value, this.InternalInvoice);
}
[JsonProperty("invoice")]
[JsonConverter(typeof(ExpandableFieldConverter<Invoice>))]
internal ExpandableField<Invoice> InternalInvoice { get; set; }
#endregion
/// <summary>
/// Has the value <c>true</c> if the object exists in live mode or the value <c>false</c>
/// if the object exists in test mode.
/// </summary>
[JsonProperty("livemode")]
public bool Livemode { get; set; }
/// <summary>
/// Credit note memo.
/// </summary>
[JsonProperty("memo")]
public string Memo { get; set; }
/// <summary>
/// A set of key/value pairs that you can attach to an order object. It can be useful for
/// storing additional information about the order in a structured format.
/// </summary>
[JsonProperty("metadata")]
public Dictionary<string, string> Metadata { get; set; }
/// <summary>
/// Credit note number.
/// </summary>
[JsonProperty("number")]
public string Number { get; set; }
/// <summary>
/// The link to download the PDF of the credit note.
/// </summary>
[JsonProperty("pdf")]
public string Pdf { get; set; }
/// <summary>
/// Reason for issuing this credit note, one of <c>duplicate</c>, <c>fraudulent</c>,
/// <c>order_change</c>, or <c>product_unsatisfactory</c>.
/// </summary>
[JsonProperty("reason")]
public string Reason { get; set; }
#region Expandable Refund
/// <summary>
/// ID of the refund associated with that credit note.
/// </summary>
[JsonIgnore]
public string RefundId
{
get => this.InternalRefund?.Id;
set => this.InternalRefund = SetExpandableFieldId(value, this.InternalRefund);
}
[JsonIgnore]
public Refund Refund
{
get => this.InternalRefund?.ExpandedObject;
set => this.InternalRefund = SetExpandableFieldObject(value, this.InternalRefund);
}
[JsonProperty("refund")]
[JsonConverter(typeof(ExpandableFieldConverter<Refund>))]
internal ExpandableField<Refund> InternalRefund { get; set; }
#endregion
/// <summary>
/// Status of this credit note, one of <c>issued</c> or <c>void</c>.
/// </summary>
[JsonProperty("status")]
public string Status { get; set; }
/// <summary>
/// Type of this credit note, one of <c>post_payment</c> or <c>pre_payment</c>.
/// </summary>
[JsonProperty("type")]
public string Type { get; set; }
}
}
| 33.835979 | 134 | 0.592181 | [
"Apache-2.0"
] | richardlawley/stripe.net | src/Stripe.net/Entities/CreditNote.cs | 6,397 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
namespace Microsoft.Bot.Schema.Teams
{
using System.Linq;
using Newtonsoft.Json;
/// <summary>
/// Specifies if a notification is to be sent for the mentions.
/// </summary>
public partial class NotificationInfo
{
/// <summary>
/// Initializes a new instance of the <see cref="NotificationInfo"/> class.
/// </summary>
public NotificationInfo()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the <see cref="NotificationInfo"/> class.
/// </summary>
/// <param name="alert">true if notification is to be sent to the user,
/// false otherwise.</param>
public NotificationInfo(bool? alert = default(bool?))
{
Alert = alert;
CustomInit();
}
/// <summary>
/// Gets or sets true if notification is to be sent to the user, false
/// otherwise.
/// </summary>
/// <value>Boolean indicating if notification is sent to the user.</value>
[JsonProperty(PropertyName = "alert")]
public bool? Alert { get; set; }
/// <summary>
/// Gets or sets the value indicating if a notification is to be shown to the user while in a meeting,
/// false otherwise.
/// </summary>
/// <value>Boolean indicating if a notification is to be shown to the user while in a meeting.</value>
[JsonProperty(PropertyName = "alertInMeeting")]
public bool? AlertInMeeting { get; set; }
/// <summary>
/// Gets or sets the value of the notification's external resource URL.
/// </summary>
/// <value>The value of the notification's external resource URL.</value>
[JsonProperty(PropertyName = "externalResourceUrl")]
#pragma warning disable CA1056 // Uri properties should not be strings
public string ExternalResourceUrl { get; set; }
#pragma warning restore CA1056 // Uri properties should not be strings
/// <summary>
/// An initialization method that performs custom operations like setting defaults.
/// </summary>
partial void CustomInit();
}
}
| 35.96875 | 110 | 0.605126 | [
"MIT"
] | HiltonGiesenow/botbuilder-dotnet | libraries/Microsoft.Bot.Schema/Teams/NotificationInfo.cs | 2,304 | C# |
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.Contracts;
using System.Linq;
using Contractor.Core.Model;
using Microsoft.Cci;
using Microsoft.Cci.MutableCodeModel;
using Microsoft.Cci.MutableContracts;
using IAssembly = Contractor.Core.Model.IAssembly;
using ITypeDefinition = Contractor.Core.Model.ITypeDefinition;
namespace Analysis.Cci
{
public class CciAssembly : IAssembly
{
protected Module module;
protected ContractProvider contractProvider;
public CciAssembly(Module module, ContractProvider contractProvider)
{
Contract.Requires(module != null);
Contract.Requires(contractProvider != null);
this.module = module;
this.contractProvider = contractProvider;
}
public Module Module
{
get { return module; }
}
public ContractProvider ContractProvider
{
get { return contractProvider; }
}
public IReadOnlyCollection<NamespaceDefinition> Namespaces()
{
var namespaces = new Dictionary<string, List<ITypeDefinition>>();
var analyzableTypes = GetAnalyzableTypes(module);
foreach (var type in analyzableTypes)
{
var typeNamespace = TypeHelper.GetDefiningNamespace(type).Name.Value;
if (!namespaces.ContainsKey(typeNamespace))
{
namespaces.Add(typeNamespace, new List<ITypeDefinition>());
}
namespaces[typeNamespace].Add(new CciTypeDefinition(type, contractProvider));
}
return new ReadOnlyCollection<NamespaceDefinition>(namespaces.Select(kvp => new NamespaceDefinition(kvp.Key, kvp.Value)).ToList());
}
public IReadOnlyCollection<ITypeDefinition> Types()
{
return
new ReadOnlyCollection<ITypeDefinition>(Namespaces()
.Aggregate(new List<ITypeDefinition>(), (l, n) => new List<ITypeDefinition>(l.Union(n.Types()))));
}
protected IReadOnlyCollection<INamedTypeDefinition> GetAnalyzableTypes(IModule module)
{
var types = from t in module.GetAllTypes()
where (t.IsClass || t.IsStruct) &&
!t.IsStatic &&
!t.IsEnum &&
!t.IsInterface
select t;
return new List<INamedTypeDefinition>(types);
}
}
} | 33.853333 | 143 | 0.614021 | [
"MIT"
] | lleraromero/contractor-net | Analysis.Cci/CciAssembly.cs | 2,541 | C# |
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading;
using Interrogator.Http.TestApi;
using Interrogator.xUnit;
using Microsoft.AspNetCore.Mvc.Testing;
namespace Interrogator.Http.Tests
{
public class RestClientAttribute : FromAttribute
{
public RestClientAttribute()
: base(typeof(RestClientAttribute), nameof(GetHttpClient))
{
}
private static readonly WebApplicationFactory<Startup> _clientFactory = new WebApplicationFactory<Startup>();
private static readonly Lazy<HttpClient> _httpClient = new Lazy<HttpClient>(CreateHttpClient, LazyThreadSafetyMode.ExecutionAndPublication);
private static HttpClient GetHttpClient()
=> _httpClient.Value;
private static HttpClient CreateHttpClient()
=> _clientFactory.CreateClient();
}
}
| 27.4 | 142 | 0.798054 | [
"MIT"
] | JohannesMoersch/Interrogator | Interrogator.Http.Tests/RestClientAttribute.cs | 824 | C# |
using MongoDB.Bson.Serialization.Attributes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Catalog.API.Entities
{
public class Product
{
[BsonId]
[BsonRepresentation(MongoDB.Bson.BsonType.ObjectId)]
public string Id { get; set; }
[BsonElement("Name")]
public string Name { get; set; }
public string Category { get; set; }
public string Summary { get; set; }
public string Description { get; set; }
public string ImageFile { get; set; }
public decimal Price { get; set; }
}
}
| 22.206897 | 60 | 0.625776 | [
"MIT"
] | lev1atan/AspnetMicroServices | src/Services/Catalog/Catalog.API/Entities/Product.cs | 646 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace NaiveBayes
{
public class NaiveBayes
{
private List<string> spamMails;
private List<string> notSpamMails;
private int countSpamMails;
private int countNotSpamMails;
public NaiveBayes()
{
EmailReader emailReader = new EmailReader();
spamMails = emailReader.Read(@"\Mails\Spam\");
notSpamMails = emailReader.Read(@"\Mails\NotSpam\");
countSpamMails = spamMails.Count();
countNotSpamMails = notSpamMails.Count();
}
public bool CheckEmail(string text)
{
Parser parser = new Parser();
foreach(var spamMail in spamMails)
{
parser.Parse(spamMail);
}
var spamWords = parser.WordCounter;
parser = new Parser();
foreach (var notSpamMail in notSpamMails)
{
parser.Parse(notSpamMail);
}
var notSpamWords = parser.WordCounter;
return CheckIfSpam(text, countSpamMails, spamWords, countNotSpamMails, notSpamWords);
}
private bool CheckIfSpam(string text,
int countSpamMails, Dictionary<string,int> spamWordList,
int countNotSpamMails, Dictionary<string,int> notSpamWordList)
{
var stringArray = text.Split(' ');
var sumQ = 0.0;
var wordCounter = 0;
foreach (var item in stringArray)
{
var q = CalculateQ(item.ToLower(),
countSpamMails, spamWordList,
countNotSpamMails, notSpamWordList);
sumQ += q;
wordCounter++;
}
if (sumQ / wordCounter > 1)
{
return true;
}
else
{
return false;
}
}
private double CalculateQ(string word,
int countSpamMails, Dictionary<string,int> spamWordList,
int countNotSpamMails, Dictionary<string,int> notSpamWordList)
{
double wordCountSpam = 1;
if (spamWordList.ContainsKey(word))
{
wordCountSpam = spamWordList[word];
}
double Ph1e = 0.5 * wordCountSpam / countSpamMails;
double wordCountNotSpam = 1;
if (notSpamWordList.ContainsKey(word))
{
wordCountNotSpam = notSpamWordList[word];
}
double Ph2e = 0.5 * wordCountNotSpam / countNotSpamMails;
double q = Ph1e / Ph2e;
return q;
}
}
}
| 31.804598 | 97 | 0.529816 | [
"MIT"
] | netmatze/NaiveBayes | NaiveBayes/NaiveBayes.cs | 2,769 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.ResourceManager;
using Azure.ResourceManager.Core;
using Azure.ResourceManager.Network.Models;
using Azure.ResourceManager.Resources;
namespace Azure.ResourceManager.Network
{
/// <summary> A class representing collection of ExpressRouteCircuit and their operations over its parent. </summary>
public partial class ExpressRouteCircuitCollection : ArmCollection, IEnumerable<ExpressRouteCircuit>, IAsyncEnumerable<ExpressRouteCircuit>
{
private readonly ClientDiagnostics _clientDiagnostics;
private readonly ExpressRouteCircuitsRestOperations _expressRouteCircuitsRestClient;
/// <summary> Initializes a new instance of the <see cref="ExpressRouteCircuitCollection"/> class for mocking. </summary>
protected ExpressRouteCircuitCollection()
{
}
/// <summary> Initializes a new instance of ExpressRouteCircuitCollection class. </summary>
/// <param name="parent"> The resource representing the parent resource. </param>
internal ExpressRouteCircuitCollection(ArmResource parent) : base(parent)
{
_clientDiagnostics = new ClientDiagnostics(ClientOptions);
_expressRouteCircuitsRestClient = new ExpressRouteCircuitsRestOperations(_clientDiagnostics, Pipeline, ClientOptions, Id.SubscriptionId, BaseUri);
}
/// <summary> Gets the valid resource type for this object. </summary>
protected override ResourceType ValidResourceType => ResourceGroup.ResourceType;
// Collection level operations.
/// <summary> Creates or updates an express route circuit. </summary>
/// <param name="circuitName"> The name of the circuit. </param>
/// <param name="parameters"> Parameters supplied to the create or update express route circuit operation. </param>
/// <param name="waitForCompletion"> Waits for the completion of the long running operations. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="circuitName"/> or <paramref name="parameters"/> is null. </exception>
public virtual ExpressRouteCircuitCreateOrUpdateOperation CreateOrUpdate(string circuitName, ExpressRouteCircuitData parameters, bool waitForCompletion = true, CancellationToken cancellationToken = default)
{
if (circuitName == null)
{
throw new ArgumentNullException(nameof(circuitName));
}
if (parameters == null)
{
throw new ArgumentNullException(nameof(parameters));
}
using var scope = _clientDiagnostics.CreateScope("ExpressRouteCircuitCollection.CreateOrUpdate");
scope.Start();
try
{
var response = _expressRouteCircuitsRestClient.CreateOrUpdate(Id.ResourceGroupName, circuitName, parameters, cancellationToken);
var operation = new ExpressRouteCircuitCreateOrUpdateOperation(Parent, _clientDiagnostics, Pipeline, _expressRouteCircuitsRestClient.CreateCreateOrUpdateRequest(Id.ResourceGroupName, circuitName, parameters).Request, response);
if (waitForCompletion)
operation.WaitForCompletion(cancellationToken);
return operation;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Creates or updates an express route circuit. </summary>
/// <param name="circuitName"> The name of the circuit. </param>
/// <param name="parameters"> Parameters supplied to the create or update express route circuit operation. </param>
/// <param name="waitForCompletion"> Waits for the completion of the long running operations. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="circuitName"/> or <paramref name="parameters"/> is null. </exception>
public async virtual Task<ExpressRouteCircuitCreateOrUpdateOperation> CreateOrUpdateAsync(string circuitName, ExpressRouteCircuitData parameters, bool waitForCompletion = true, CancellationToken cancellationToken = default)
{
if (circuitName == null)
{
throw new ArgumentNullException(nameof(circuitName));
}
if (parameters == null)
{
throw new ArgumentNullException(nameof(parameters));
}
using var scope = _clientDiagnostics.CreateScope("ExpressRouteCircuitCollection.CreateOrUpdate");
scope.Start();
try
{
var response = await _expressRouteCircuitsRestClient.CreateOrUpdateAsync(Id.ResourceGroupName, circuitName, parameters, cancellationToken).ConfigureAwait(false);
var operation = new ExpressRouteCircuitCreateOrUpdateOperation(Parent, _clientDiagnostics, Pipeline, _expressRouteCircuitsRestClient.CreateCreateOrUpdateRequest(Id.ResourceGroupName, circuitName, parameters).Request, response);
if (waitForCompletion)
await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false);
return operation;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Gets information about the specified express route circuit. </summary>
/// <param name="circuitName"> The name of express route circuit. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="circuitName"/> is null. </exception>
public virtual Response<ExpressRouteCircuit> Get(string circuitName, CancellationToken cancellationToken = default)
{
if (circuitName == null)
{
throw new ArgumentNullException(nameof(circuitName));
}
using var scope = _clientDiagnostics.CreateScope("ExpressRouteCircuitCollection.Get");
scope.Start();
try
{
var response = _expressRouteCircuitsRestClient.Get(Id.ResourceGroupName, circuitName, cancellationToken);
if (response.Value == null)
throw _clientDiagnostics.CreateRequestFailedException(response.GetRawResponse());
return Response.FromValue(new ExpressRouteCircuit(Parent, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Gets information about the specified express route circuit. </summary>
/// <param name="circuitName"> The name of express route circuit. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="circuitName"/> is null. </exception>
public async virtual Task<Response<ExpressRouteCircuit>> GetAsync(string circuitName, CancellationToken cancellationToken = default)
{
if (circuitName == null)
{
throw new ArgumentNullException(nameof(circuitName));
}
using var scope = _clientDiagnostics.CreateScope("ExpressRouteCircuitCollection.Get");
scope.Start();
try
{
var response = await _expressRouteCircuitsRestClient.GetAsync(Id.ResourceGroupName, circuitName, cancellationToken).ConfigureAwait(false);
if (response.Value == null)
throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(response.GetRawResponse()).ConfigureAwait(false);
return Response.FromValue(new ExpressRouteCircuit(Parent, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Tries to get details for this resource from the service. </summary>
/// <param name="circuitName"> The name of express route circuit. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="circuitName"/> is null. </exception>
public virtual Response<ExpressRouteCircuit> GetIfExists(string circuitName, CancellationToken cancellationToken = default)
{
if (circuitName == null)
{
throw new ArgumentNullException(nameof(circuitName));
}
using var scope = _clientDiagnostics.CreateScope("ExpressRouteCircuitCollection.GetIfExists");
scope.Start();
try
{
var response = _expressRouteCircuitsRestClient.Get(Id.ResourceGroupName, circuitName, cancellationToken: cancellationToken);
return response.Value == null
? Response.FromValue<ExpressRouteCircuit>(null, response.GetRawResponse())
: Response.FromValue(new ExpressRouteCircuit(this, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Tries to get details for this resource from the service. </summary>
/// <param name="circuitName"> The name of express route circuit. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="circuitName"/> is null. </exception>
public async virtual Task<Response<ExpressRouteCircuit>> GetIfExistsAsync(string circuitName, CancellationToken cancellationToken = default)
{
if (circuitName == null)
{
throw new ArgumentNullException(nameof(circuitName));
}
using var scope = _clientDiagnostics.CreateScope("ExpressRouteCircuitCollection.GetIfExistsAsync");
scope.Start();
try
{
var response = await _expressRouteCircuitsRestClient.GetAsync(Id.ResourceGroupName, circuitName, cancellationToken: cancellationToken).ConfigureAwait(false);
return response.Value == null
? Response.FromValue<ExpressRouteCircuit>(null, response.GetRawResponse())
: Response.FromValue(new ExpressRouteCircuit(this, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Tries to get details for this resource from the service. </summary>
/// <param name="circuitName"> The name of express route circuit. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="circuitName"/> is null. </exception>
public virtual Response<bool> CheckIfExists(string circuitName, CancellationToken cancellationToken = default)
{
if (circuitName == null)
{
throw new ArgumentNullException(nameof(circuitName));
}
using var scope = _clientDiagnostics.CreateScope("ExpressRouteCircuitCollection.CheckIfExists");
scope.Start();
try
{
var response = GetIfExists(circuitName, cancellationToken: cancellationToken);
return Response.FromValue(response.Value != null, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Tries to get details for this resource from the service. </summary>
/// <param name="circuitName"> The name of express route circuit. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="circuitName"/> is null. </exception>
public async virtual Task<Response<bool>> CheckIfExistsAsync(string circuitName, CancellationToken cancellationToken = default)
{
if (circuitName == null)
{
throw new ArgumentNullException(nameof(circuitName));
}
using var scope = _clientDiagnostics.CreateScope("ExpressRouteCircuitCollection.CheckIfExistsAsync");
scope.Start();
try
{
var response = await GetIfExistsAsync(circuitName, cancellationToken: cancellationToken).ConfigureAwait(false);
return Response.FromValue(response.Value != null, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Gets all the express route circuits in a resource group. </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <returns> A collection of <see cref="ExpressRouteCircuit" /> that may take multiple service requests to iterate over. </returns>
public virtual Pageable<ExpressRouteCircuit> GetAll(CancellationToken cancellationToken = default)
{
Page<ExpressRouteCircuit> FirstPageFunc(int? pageSizeHint)
{
using var scope = _clientDiagnostics.CreateScope("ExpressRouteCircuitCollection.GetAll");
scope.Start();
try
{
var response = _expressRouteCircuitsRestClient.List(Id.ResourceGroupName, cancellationToken: cancellationToken);
return Page.FromValues(response.Value.Value.Select(value => new ExpressRouteCircuit(Parent, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
Page<ExpressRouteCircuit> NextPageFunc(string nextLink, int? pageSizeHint)
{
using var scope = _clientDiagnostics.CreateScope("ExpressRouteCircuitCollection.GetAll");
scope.Start();
try
{
var response = _expressRouteCircuitsRestClient.ListNextPage(nextLink, Id.ResourceGroupName, cancellationToken: cancellationToken);
return Page.FromValues(response.Value.Value.Select(value => new ExpressRouteCircuit(Parent, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateEnumerable(FirstPageFunc, NextPageFunc);
}
/// <summary> Gets all the express route circuits in a resource group. </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <returns> An async collection of <see cref="ExpressRouteCircuit" /> that may take multiple service requests to iterate over. </returns>
public virtual AsyncPageable<ExpressRouteCircuit> GetAllAsync(CancellationToken cancellationToken = default)
{
async Task<Page<ExpressRouteCircuit>> FirstPageFunc(int? pageSizeHint)
{
using var scope = _clientDiagnostics.CreateScope("ExpressRouteCircuitCollection.GetAll");
scope.Start();
try
{
var response = await _expressRouteCircuitsRestClient.ListAsync(Id.ResourceGroupName, cancellationToken: cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value.Select(value => new ExpressRouteCircuit(Parent, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
async Task<Page<ExpressRouteCircuit>> NextPageFunc(string nextLink, int? pageSizeHint)
{
using var scope = _clientDiagnostics.CreateScope("ExpressRouteCircuitCollection.GetAll");
scope.Start();
try
{
var response = await _expressRouteCircuitsRestClient.ListNextPageAsync(nextLink, Id.ResourceGroupName, cancellationToken: cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value.Select(value => new ExpressRouteCircuit(Parent, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, NextPageFunc);
}
/// <summary> Filters the list of <see cref="ExpressRouteCircuit" /> for this resource group represented as generic resources. </summary>
/// <param name="nameFilter"> The filter used in this operation. </param>
/// <param name="expand"> Comma-separated list of additional properties to be included in the response. Valid values include `createdTime`, `changedTime` and `provisioningState`. </param>
/// <param name="top"> The number of results to return. </param>
/// <param name="cancellationToken"> A token to allow the caller to cancel the call to the service. The default value is <see cref="CancellationToken.None" />. </param>
/// <returns> A collection of resource that may take multiple service requests to iterate over. </returns>
public virtual Pageable<GenericResource> GetAllAsGenericResources(string nameFilter, string expand = null, int? top = null, CancellationToken cancellationToken = default)
{
using var scope = _clientDiagnostics.CreateScope("ExpressRouteCircuitCollection.GetAllAsGenericResources");
scope.Start();
try
{
var filters = new ResourceFilterCollection(ExpressRouteCircuit.ResourceType);
filters.SubstringFilter = nameFilter;
return ResourceListOperations.GetAtContext(Parent as ResourceGroup, filters, expand, top, cancellationToken);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Filters the list of <see cref="ExpressRouteCircuit" /> for this resource group represented as generic resources. </summary>
/// <param name="nameFilter"> The filter used in this operation. </param>
/// <param name="expand"> Comma-separated list of additional properties to be included in the response. Valid values include `createdTime`, `changedTime` and `provisioningState`. </param>
/// <param name="top"> The number of results to return. </param>
/// <param name="cancellationToken"> A token to allow the caller to cancel the call to the service. The default value is <see cref="CancellationToken.None" />. </param>
/// <returns> An async collection of resource that may take multiple service requests to iterate over. </returns>
public virtual AsyncPageable<GenericResource> GetAllAsGenericResourcesAsync(string nameFilter, string expand = null, int? top = null, CancellationToken cancellationToken = default)
{
using var scope = _clientDiagnostics.CreateScope("ExpressRouteCircuitCollection.GetAllAsGenericResources");
scope.Start();
try
{
var filters = new ResourceFilterCollection(ExpressRouteCircuit.ResourceType);
filters.SubstringFilter = nameFilter;
return ResourceListOperations.GetAtContextAsync(Parent as ResourceGroup, filters, expand, top, cancellationToken);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
IEnumerator<ExpressRouteCircuit> IEnumerable<ExpressRouteCircuit>.GetEnumerator()
{
return GetAll().GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetAll().GetEnumerator();
}
IAsyncEnumerator<ExpressRouteCircuit> IAsyncEnumerable<ExpressRouteCircuit>.GetAsyncEnumerator(CancellationToken cancellationToken)
{
return GetAllAsync(cancellationToken: cancellationToken).GetAsyncEnumerator(cancellationToken);
}
// Builders.
// public ArmBuilder<Azure.ResourceManager.ResourceIdentifier, ExpressRouteCircuit, ExpressRouteCircuitData> Construct() { }
}
}
| 52.098558 | 243 | 0.633738 | [
"MIT"
] | DiskRP-Swagger/azure-sdk-for-net | sdk/network/Azure.ResourceManager.Network/src/Generated/ExpressRouteCircuitCollection.cs | 21,673 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
namespace System.Security.Cryptography
{
public interface ICryptoTransform : IDisposable
{
int InputBlockSize { get; }
int OutputBlockSize { get; }
// CanTransformMultipleBlocks == true implies that TransformBlock() can accept any number
// of whole blocks, not just a single block. If CanTransformMultipleBlocks is false, you have
// to feed blocks one at a time.
bool CanTransformMultipleBlocks { get; }
// If CanReuseTransform is true, then after a call to TransformFinalBlock() the transform
// resets its internal state to its initial configuration (with Key and IV loaded) and can
// be used to perform another encryption/decryption.
bool CanReuseTransform { get; }
// The return value of TransformBlock is the number of bytes returned to outputBuffer and is
// always <= OutputBlockSize. If CanTransformMultipleBlocks is true, then inputCount may be
// any positive multiple of InputBlockSize
int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset);
// Special function for transforming the last block or partial block in the stream. The
// return value is an array containing the remaining transformed bytes.
// We return a new array here because the amount of information we send back at the end could
// be larger than a single block once padding is accounted for.
byte[] TransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount);
}
}
| 48.210526 | 119 | 0.713428 | [
"MIT"
] | 06needhamt/runtime | src/libraries/System.Security.Cryptography.Primitives/src/System/Security/Cryptography/ICryptoTransform.cs | 1,832 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Aurora.Profiles.Voron
{
/// <summary>
/// Interaction logic for VoronControl.xaml
/// </summary>
public partial class VoronControl : UserControl
{
public VoronControl()
{
InitializeComponent();
}
}
}
| 21 | 48 | 0.773399 | [
"MIT"
] | VoronFX/Aurora | Project-Aurora/Profiles/Voron/VoronControl.xaml.cs | 611 | C# |
/*
* ******************************************************************************
* Copyright 2014-2017 Spectra Logic Corporation. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file.
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
* ****************************************************************************
*/
// This code is auto-generated, do not modify
namespace Ds3.Models
{
public enum VersioningLevel
{
NONE,
KEEP_LATEST,
KEEP_MULTIPLE_VERSIONS
}
}
| 34.851852 | 89 | 0.582359 | [
"Apache-2.0"
] | RachelTucker/ds3_net_sdk | Ds3/Models/VersioningLevel.cs | 941 | C# |
using NUnit.Framework;
using Osaru;
using Osaru.Json;
using Osaru.Serialization.Serializers;
using System;
using System.Collections.Generic;
using System.Linq;
namespace OsaruTest.Json
{
public static class TypeRegistryExtensions
{
public static void TypeTest<T>(this Osaru.Serialization.TypeRegistry typeRegistry
, T value, string expected)
{
var serializer = (SerializerBase<T>)typeRegistry.GetSerializer<T>();
var serialized = serializer.SerializeToJson(value);
Assert.AreEqual(expected, serialized);
var deserializer = typeRegistry.GetDeserializer<T>();
var deserialized = default(T);
try
{
deserialized = Activator.CreateInstance<T>();
}
catch (Exception)
{
}
var json = JsonParser.Parse(serialized);
deserializer.Deserialize(json, ref deserialized);
Assert.AreEqual(value, deserialized);
}
}
public class SerializerTest
{
[Test]
public void NumberTest()
{
var typeRegistry = new Osaru.Serialization.TypeRegistry();
typeRegistry.TypeTest(1, "1");
}
[Test]
public void ArrayTest()
{
var typeRegistry = new Osaru.Serialization.TypeRegistry();
var array = new[] { 1, 2, 3 };
typeRegistry.TypeTest(array, "[1,2,3]");
}
[Test]
public void ListTest()
{
var typeRegistry = new Osaru.Serialization.TypeRegistry();
var list = new List<int> { 1, 2, 3 };
typeRegistry.TypeTest(list, "[1,2,3]");
}
[Test]
public void Vector3Test()
{
var typeRegistry = new Osaru.Serialization.TypeRegistry();
var v = new UnityEngine.Vector3(1, 2, 3);
typeRegistry.TypeTest(v, "[1,2,3]");
}
[Serializable]
struct Base64Struct
{
public byte[] Bytes;
public List<Byte> ListBytes;
public override bool Equals(System.Object obj)
{
// If parameter is null return false.
if (obj == null)
{
return false;
}
// If parameter cannot be cast to Point return false.
var p = (Base64Struct)obj;
// Return true if the fields match:
return Equals(p);
}
public bool Equals(Base64Struct p)
{
// Return true if the fields match:
return Bytes.SequenceEqual(p.Bytes)
&& ListBytes.SequenceEqual(p.ListBytes)
;
}
}
[Test]
public void Base64Test()
{
var typeRegistry = new Osaru.Serialization.TypeRegistry();
var v = new Base64Struct
{
Bytes=new Byte[] { (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G' },
ListBytes = new List<Byte> { (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G' },
};
typeRegistry.TypeTest(v, "{\"Bytes\":\"QUJDREVGRw==\",\"ListBytes\":\"QUJDREVGRw==\"}");
}
}
}
| 30.417391 | 124 | 0.494568 | [
"MIT"
] | ousttrue/JsonSan | UnityProject/Assets/Osaru/Scripts/Formats/Json/Editor/JsonSerializerTest.cs | 3,500 | C# |
// c:\program files (x86)\windows kits\10\include\10.0.22000.0\um\d3dumddi.h(3949,9)
using System;
using System.Runtime.InteropServices;
namespace DirectN
{
[StructLayout(LayoutKind.Sequential)]
public partial struct _D3DDDICB_FREEGPUVIRTUALADDRESS
{
public ulong BaseAddress;
public ulong Size;
}
}
| 24.785714 | 86 | 0.691643 | [
"MIT"
] | Steph55/DirectN | DirectN/DirectN/Generated/_D3DDDICB_FREEGPUVIRTUALADDRESS.cs | 349 | C# |
using System;
using System.Diagnostics;
namespace MyGeneration
{
public class ThreadData
{
public ThreadData(ZeusProcessStatusDelegate cbk, Process p, Guid id)
{
CallbackHandlers += cbk;
SysProcess = p;
ID = id;
}
protected event ZeusProcessStatusDelegate CallbackHandlers;
public void Callback(ZeusProcessStatusEventArgs args)
{
if (CallbackHandlers != null) CallbackHandlers(args);
}
public Process SysProcess;
public Guid ID;
}
} | 26.681818 | 77 | 0.591141 | [
"BSD-3-Clause"
] | cafephin/mygeneration | src/mygeneration/MyGenUtility/ZeusProcess/ThreadData.cs | 589 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace QK.Framework.Core.Model
{
/// <summary>
/// 数据查询条件
/// </summary>
public class DataFilter
{
/// <summary>
/// 数据库字段名
/// </summary>
public string field { get; set; }
/// <summary>
/// 运算符
/// l 模糊查询
/// g 时间大于
/// e 时间小于
/// d 数字等于
/// b 数字大于
/// s 数字小于
/// n 不等于
/// od or等于查询
/// o or模糊查询
/// </summary>
public string comparison { get; set; }
/// <summary>
/// 值
/// </summary>
public string value { get; set; }
}
}
| 19.189189 | 46 | 0.422535 | [
"Apache-2.0"
] | hywb/QK.Framework | QK.Framework/Core/Model/DataFilter.cs | 814 | C# |
using UnityEngine;
public class HiddenPlatform : MonoBehaviour
{
private SpriteRenderer spRenderer;
private void Start()
{
spRenderer = GetComponent<SpriteRenderer>();
}
private void OnCollisionEnter2D(Collision2D other)
{
spRenderer.enabled = true;
}
}
| 19.933333 | 54 | 0.67893 | [
"MIT"
] | muyangye/Games | An Easy Game/Assets/Scripts/HiddenPlatform.cs | 299 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.GoogleNative.Compute.V1.Outputs
{
/// <summary>
/// Informational metadata about Partner attachments from Partners to display to customers. These fields are propagated from PARTNER_PROVIDER attachments to their corresponding PARTNER attachments.
/// </summary>
[OutputType]
public sealed class InterconnectAttachmentPartnerMetadataResponse
{
/// <summary>
/// Plain text name of the Interconnect this attachment is connected to, as displayed in the Partner's portal. For instance "Chicago 1". This value may be validated to match approved Partner values.
/// </summary>
public readonly string InterconnectName;
/// <summary>
/// Plain text name of the Partner providing this attachment. This value may be validated to match approved Partner values.
/// </summary>
public readonly string PartnerName;
/// <summary>
/// URL of the Partner's portal for this Attachment. Partners may customise this to be a deep link to the specific resource on the Partner portal. This value may be validated to match approved Partner values.
/// </summary>
public readonly string PortalUrl;
[OutputConstructor]
private InterconnectAttachmentPartnerMetadataResponse(
string interconnectName,
string partnerName,
string portalUrl)
{
InterconnectName = interconnectName;
PartnerName = partnerName;
PortalUrl = portalUrl;
}
}
}
| 40.282609 | 216 | 0.689692 | [
"Apache-2.0"
] | AaronFriel/pulumi-google-native | sdk/dotnet/Compute/V1/Outputs/InterconnectAttachmentPartnerMetadataResponse.cs | 1,853 | C# |
namespace AnimalFarm.Animals
{
using Contracts;
using Foods;
public abstract class Animal : IAnimal
{
protected Animal(string name, double weight)
{
this.Name = name;
this.Weight = weight;
}
public string Name { get; private set; }
public double Weight { get; set; }
public int FoodEaten { get; set; }
public abstract void ProduceSound();
public abstract void Eat(Food food);
public override string ToString()
{
return $"{this.GetType().Name} [{this.Name}, ";
}
}
} | 21.275862 | 59 | 0.551053 | [
"MIT"
] | TihomirIvanovIvanov/SoftUni | C#Fundamentals/C#OOP-Basics/06Polymorphism/PolymorphismExercise/AnimalFarm/Animals/Animal.cs | 619 | C# |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading;
/// <summary>
/// The type WorkbookFunctionsNpvRequest.
/// </summary>
public partial class WorkbookFunctionsNpvRequest : BaseRequest, IWorkbookFunctionsNpvRequest
{
/// <summary>
/// Constructs a new WorkbookFunctionsNpvRequest.
/// </summary>
public WorkbookFunctionsNpvRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
this.ContentType = "application/json";
this.RequestBody = new WorkbookFunctionsNpvRequestBody();
}
/// <summary>
/// Gets the request body.
/// </summary>
public WorkbookFunctionsNpvRequestBody RequestBody { get; private set; }
/// <summary>
/// Issues the POST request.
/// </summary>
public System.Threading.Tasks.Task<WorkbookFunctionResult> PostAsync()
{
return this.PostAsync(CancellationToken.None);
}
/// <summary>
/// Issues the POST request.
/// </summary>
/// <param name=""cancellationToken"">The <see cref=""CancellationToken""/> for the request.</param>
/// <returns>The task to await for async call.</returns>
public System.Threading.Tasks.Task<WorkbookFunctionResult> PostAsync(
CancellationToken cancellationToken)
{
this.Method = "POST";
return this.SendAsync<WorkbookFunctionResult>(this.RequestBody, cancellationToken);
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookFunctionsNpvRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookFunctionsNpvRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
}
}
| 34.647059 | 153 | 0.572835 | [
"MIT"
] | twsouthwick/msgraph-sdk-dotnet | src/Microsoft.Graph/Requests/Generated/WorkbookFunctionsNpvRequest.cs | 2,945 | C# |
#region License
/*
* Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
using System;
using System.Runtime.Serialization;
namespace Spring.Transaction
{
/// <summary>
/// Exception thrown when a general transaction system error is encountered,
/// for instance on commit or rollback.
/// </summary>
/// <author>Juergen Hoeller</author>
/// <author>Griffin Caprio (.NET)</author>
[Serializable]
public class TransactionSystemException : TransactionException
{
/// <summary>
/// Creates a new instance of the
/// <see cref="Spring.Transaction.TransactionSystemException"/> class.
/// </summary>
public TransactionSystemException( ) {}
/// <summary>
/// Creates a new instance of the
/// <see cref="Spring.Transaction.TransactionSystemException"/> class.
/// </summary>
/// <param name="message">
/// A message about the exception.
/// </param>
public TransactionSystemException( String message ) : base(message) {}
/// <summary>
/// Creates a new instance of the
/// <see cref="Spring.Transaction.TransactionSystemException"/> class.
/// </summary>
/// <param name="message">
/// A message about the exception.
/// </param>
/// <param name="rootCause">
/// The root exception that is being wrapped.
/// </param>
public TransactionSystemException(string message, Exception rootCause)
: base(message, rootCause) {}
/// <summary>
/// Creates a new instance of the
/// <see cref="Spring.Transaction.TransactionSystemException"/> class.
/// </summary>
/// <param name="info">
/// The <see cref="System.Runtime.Serialization.SerializationInfo"/>
/// that holds the serialized object data about the exception being thrown.
/// </param>
/// <param name="context">
/// The <see cref="System.Runtime.Serialization.StreamingContext"/>
/// that contains contextual information about the source or destination.
/// </param>
protected TransactionSystemException(
SerializationInfo info, StreamingContext context ) : base( info, context ) {}
}
} | 33.346154 | 80 | 0.702422 | [
"Apache-2.0"
] | MaferYangPointJun/Spring.net | src/Spring/Spring.Data/Transaction/TransactionSystemException.cs | 2,601 | C# |
/**
* $File: JCS_Vector.cs $
* $Date: $
* $Revision: $
* $Creator: Jen-Chieh Shen $
* $Notice: See LICENSE.txt for modification and distribution information
* Copyright (c) 2016 by Shen, Jen-Chieh $
*/
using UnityEngine;
namespace JCSUnity
{
/// <summary>
/// Vector data structure implementation.
/// </summary>
public class JCS_Vector<T>
{
private T[] m_array = null;
public T[] array { get { return m_array; } }
public int length { get { return m_array.Length; } }
public bool empty { get { return (length == 0); } }
public JCS_Vector(int length = 0)
{
m_array = new T[length];
}
/// <summary>
/// add one element at the end of the m_array
/// </summary>
/// <param name="target">new element.</param>
public T[] push(T target)
{
T[] newm_array = new T[length + 1];
for (int i = 0; i < length; i++)
{
newm_array[i] = m_array[i];
}
newm_array[length] = target;
m_array = newm_array;
return m_array;
}
/// <summary>
/// remove first element and return it
/// </summary>
public T shift()
{
if (length == 0) return default(T);
T[] newm_array = new T[length - 1];
T element = m_array[0];
for (int i = 0; i < length - 1; i++)
{
newm_array[i] = m_array[i + 1];
}
m_array = newm_array;
return element;
}
/// <summary>
/// remove the element of index, and return the element
/// </summary>
/// <param name="index">Target index.</param>
public T slice(int index)
{
if (index >= 0 && index <= m_array.Length - 1)
{
T[] newarray = new T[length - 1];
T result = m_array[index];
for (int i = 0; i < index; i++)
{
newarray[i] = m_array[i];
}
for (int j = index; j < length - 1; j++)
{
newarray[j] = m_array[j + 1];
}
m_array = newarray;
return result;
}
else
{
Debug.Log("JCS_Vector slice: index out of range, failed to slice.");
return default(T);
}
}
/// <summary>
/// remove the element of index, and return the element
/// </summary>
/// <param name="target">Target object.</param>
public T slice(T target)
{
bool isFound = false;
int index = 0;
for (int i = 0; i < length; i++)
{
if (m_array[i].Equals(target))
{
//found elements
index = i;
isFound = true;
}
}
if (isFound)
{
return slice(index);
}
else
{
Debug.Log("JCS_Vector slice: target object not found in vector.");
return default(T);
}
}
/// <summary>
/// Return GameObject with index
/// </summary>
public T at(int index)
{
if (index >= 0 && index <= m_array.Length - 1)
return m_array[index];
else
Debug.Log("JCS_Vector::(129)::Out of Range!");
return default(T);
}
/// <summary>
/// Set the object by index.
/// </summary>
/// <param name="index">Target index.</param>
/// <param name="val">Object value.</param>
public void set(int index, T val)
{
if (index >= 0 && index <= m_array.Length - 1)
this.m_array[index] = val;
else
Debug.Log("JCS_Vector::(139)::Out of Range!");
}
/// <summary>
/// Clear the array.
/// </summary>
public void clear()
{
// Call init directly clear the vector.
// TODO(JenChieh): not sure this will cause memory leak.
m_array = null;
m_array = new T[0];
}
}
}
| 26.704819 | 84 | 0.428378 | [
"BSD-3-Clause"
] | MapleStoryUnity/MapleStoryUnity | Assets/JCSUnity/Scripts/Lib/JCS_Vector.cs | 4,435 | C# |
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Web;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using Microsoft.Owin.Security;
using EventHub.Models;
namespace EventHub
{
public class EmailService : IIdentityMessageService
{
public Task SendAsync(IdentityMessage message)
{
// Plug in your email service here to send an email.
return Task.FromResult(0);
}
}
public class SmsService : IIdentityMessageService
{
public Task SendAsync(IdentityMessage message)
{
// Plug in your SMS service here to send a text message.
return Task.FromResult(0);
}
}
// Configure the application user manager used in this application. UserManager is defined in ASP.NET Identity and is used by the application.
public class ApplicationUserManager : UserManager<ApplicationUser>
{
public ApplicationUserManager(IUserStore<ApplicationUser> store)
: base(store)
{
}
public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
{
var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()));
// Configure validation logic for usernames
manager.UserValidator = new UserValidator<ApplicationUser>(manager)
{
AllowOnlyAlphanumericUserNames = false,
RequireUniqueEmail = true
};
// Configure validation logic for passwords
manager.PasswordValidator = new PasswordValidator
{
RequiredLength = 3,
RequireNonLetterOrDigit = false,
RequireDigit = false,
RequireLowercase = false,
RequireUppercase = false,
};
// Configure user lockout defaults
manager.UserLockoutEnabledByDefault = true;
manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
manager.MaxFailedAccessAttemptsBeforeLockout = 5;
// Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
// You can write your own provider and plug it in here.
manager.RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider<ApplicationUser>
{
MessageFormat = "Your security code is {0}"
});
manager.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider<ApplicationUser>
{
Subject = "Security Code",
BodyFormat = "Your security code is {0}"
});
manager.EmailService = new EmailService();
manager.SmsService = new SmsService();
var dataProtectionProvider = options.DataProtectionProvider;
if (dataProtectionProvider != null)
{
manager.UserTokenProvider =
new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
}
return manager;
}
}
// Configure the application sign-in manager which is used in this application.
public class ApplicationSignInManager : SignInManager<ApplicationUser, string>
{
public ApplicationSignInManager(ApplicationUserManager userManager, IAuthenticationManager authenticationManager)
: base(userManager, authenticationManager)
{
}
public override Task<ClaimsIdentity> CreateUserIdentityAsync(ApplicationUser user)
{
return user.GenerateUserIdentityAsync((ApplicationUserManager)UserManager);
}
public static ApplicationSignInManager Create(IdentityFactoryOptions<ApplicationSignInManager> options, IOwinContext context)
{
return new ApplicationSignInManager(context.GetUserManager<ApplicationUserManager>(), context.Authentication);
}
}
}
| 39.327273 | 152 | 0.659732 | [
"MIT"
] | kmrul/EventHub | EventHub/App_Start/IdentityConfig.cs | 4,328 | C# |
using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Comformation
{
/// <summary>
/// Used to serialize strings that represents json
/// </summary>
public class RawJsonConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var str = value.ToString();
// TODO: verify that value is JSON
if (str.StartsWith("[") && str.EndsWith("]") || str.StartsWith("{") && str.EndsWith("}"))
writer.WriteRawValue(str);
else
writer.WriteValue(value);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override bool CanConvert(Type objectType)
{
return typeof(string).IsAssignableFrom(objectType);
}
public override bool CanRead => false;
}
} | 30.647059 | 124 | 0.609405 | [
"MIT"
] | stanb/Comformation | src/Comformation/Serialization/RawJsonConverter.cs | 1,044 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Lamar.Microsoft.DependencyInjection;
namespace Portal
{
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseLamar()
.UseStartup<Startup>()
;
}
}
| 24.5 | 76 | 0.673469 | [
"MIT"
] | akash-yadav-tech/dddwithlamardapperandautomapper | Portal/Program.cs | 688 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using Portal2.DataTypes;
using Portal2.Items;
namespace Portal2
{
/// <summary>
/// A field of voxels that makes up a level.
/// </summary>
public class VoxelField
{
#region Fields
Puzzle owner;
int width = 0;
int depth = 0;
int height = 0;
/// <summary>
/// The voxels, stored in x y z order
/// </summary>
private Voxel[] voxels;
#endregion
#region Properties
/// <summary>
/// Whether or not the field will automatically grow to fit any queried or set values
/// </summary>
public bool AutoGrow { get; set; }
/// <summary>
/// The width of the voxel field (in the X/Right direction)
/// </summary>
public int Width
{
get { return width; }
set { Resize(value, depth, height); }
}
/// <summary>
/// The depth of the voxel field (in the Y/Forward direction)
/// </summary>
public int Depth
{
get { return depth; }
set { Resize(width, value, height); }
}
/// <summary>
/// The height of the voxel field (in the Z/Up direction)
/// </summary>
public int Height
{
get { return height; }
set { Resize(width, depth, value); }
}
#endregion
#region Construction
public VoxelField(Puzzle owner)
{
this.owner = owner;
AutoGrow = false;
Point3 size = owner.ChamberSize;
Resize(size.X, size.Y, size.Z);
}
internal VoxelField(Puzzle owner, P2CNode voxelsNode)
{
this.owner = owner;
AutoGrow = false;
Point3 size = owner.ChamberSize;
Resize(size.X + 1, size.Y + 1, size.Z + 1);
if (voxelsNode == null)
return;
List<P2CNode> voxelNodes = voxelsNode.GetNodes("Voxel");
foreach (P2CNode voxelNode in voxelNodes)
{
Voxel voxel = new Voxel(this, voxelNode);
SetVoxel(voxel.Position, voxel);
}
}
#endregion
#region Methods
/// <summary>
/// Gets the voxel at the specified position.
/// </summary>
public Voxel GetVoxel(Point3 position)
{
int x = position.X;
int y = position.Y;
int z = position.Z;
if (x < 0 || y < 0 || z < 0)
return Voxel.Empty;
if (x >= width || y >= depth || z >= height)
{
if (!AutoGrow)
return Voxel.Empty;
Resize(Math.Max(x + 1, width), Math.Max(y + 1, depth), Math.Max(z + 1, height));
}
return voxels[(x * depth * height) + (y * height) + z];
}
/// <summary>
/// Copies the voxel data to the voxel at the specified position.
/// </summary>
internal void SetVoxel(Point3 position, Voxel voxel)
{
int x = position.X;
int y = position.Y;
int z = position.Z;
if (x < 0 || y < 0 || z < 0)
return;
if (x >= width || y >= depth || z >= height)
{
if (!AutoGrow)
return;
Resize(Math.Max(x + 1, width), Math.Max(y + 1, depth), Math.Max(z + 1, height));
}
voxels[(x * depth * height) + (y * height) + z].SetData(voxel);
}
internal void SetPortalable(Point3 position, Direction direction, bool portalable)
{
voxels[(position.X * depth * height) + (position.Y * height) + position.Z].SetPortalable(direction, portalable);
}
/// <summary>
/// Sets the specified voxel data on the voxel at the specified position.
/// </summary>
public void SetVoxelData(Point3 position, VoxelData mask, VoxelData data)
{
int x = position.X;
int y = position.Y;
int z = position.Z;
if (x < 0 || y < 0 || z < 0)
return;
if (x >= width || y >= depth || z >= height)
{
if (!AutoGrow)
return;
Resize(Math.Max(x + 1, width), Math.Max(y + 1, depth), Math.Max(z + 1, height));
}
voxels[(x * depth * height) + (y * height) + z].SetData(mask, data);
}
/// <summary>
/// Resizes the voxel field.
/// </summary>
internal void Resize(int sx, int sy, int sz)
{
if (sx <= 1 || sy <= 1 || sz <= 1)
return;
if (sx == width && sy == depth && sz == height)
return;
int planewidth = sy * sz;
int rowwidth = sz;
Voxel[] newArray = new Voxel[sx * sy * sz];
// Fill out new array
for (int x = 0; x < sx; x++)
{
for (int y = 0; y < sy; y++)
{
int rowOffset = x * (sy * sz) + y * (sz);
// Copy values that will fit in new array
// Fill out rest
if (voxels != null && x < width && y < depth)
{
Array.Copy(voxels, x * (depth * height) + y * (height),
newArray, rowOffset, height);
}
// Fill out rest of values
int minz = (x < width && y < depth) ? height : 0;
for (int z = minz; z < sz; z++)
{
newArray[rowOffset + z] = new Voxel(this, new Point3(x, y, z));
}
if (x == sx - 1 || y == sy - 1)
{
// Set all data on last row to solid
for (int z = 0; z < sz; z++)
{
newArray[rowOffset + z].SetData(VoxelData.IsSolid, VoxelData.IsSolid);
}
}
else
{
// Set last voxel on row to solid
newArray[rowOffset + sz - 1].SetData(VoxelData.IsSolid, VoxelData.IsSolid);
}
}
}
// Set array
voxels = newArray;
width = sx;
depth = sy;
height = sz;
}
/// <summary>
/// Sets a range of data.
/// </summary>
public void SetRange(Point3 position, Point3 size, VoxelData mask, VoxelData values)
{
// Grow size if necessary
Point3 max = position + size + Point3.One;
if (AutoGrow && (max.X > width || max.Y > depth || max.Z > height))
{
Resize(Math.Max(max.X, width), Math.Max(max.Y, depth), Math.Max(max.Z, height));
}
// TODO: If setting positive portalable values on a range, try to overlap the data to reduce property access.
// Set values
for (int dx = 0; dx < size.X; dx++)
{
int x = dx + position.X;
if (x >= width)
break;
int ox = x * (depth * height);
for (int dy = 0; dy < size.Y; dy++)
{
int y = dy + position.Y;
if (y >= depth)
break;
int oy = y * (height);
for (int dz = 0; dz < size.Z; dz++)
{
int z = dz + position.Z;
if (z >= height)
break;
int i = ox + oy + z;
voxels[i].SetData(mask, values);
}
}
}
}
#endregion
#region Utility Methods
/// <summary>
/// Gets the position of the last non-solid voxel directly above the specified position.
/// </summary>
public Point3 GetCeilingVoxel(Point3 location)
{
Point3 pos = location;
while (!GetVoxel(pos + Point3.UnitZ).IsSolid)
{
pos.Z += 1;
}
return pos;
}
/// <summary>
/// Gets the position of the last non-solid voxel directly below the specified position.
/// </summary>
public Point3 GetFloorVoxel(Point3 location)
{
Point3 pos = location;
while (!GetVoxel(pos - Point3.UnitZ).IsSolid)
{
pos.Z -= 1;
}
return pos;
}
#endregion
#region I/O Operations
/// <summary>
/// Gets a P2CNode representing the voxel field.
/// </summary>
internal P2CNode GetNode()
{
P2CNode voxelsNode = new P2CNode("Voxels");
for (int x = 0; x < width; x++)
{
int ox = x * depth * height;
for (int y = 0; y < depth; y++)
{
int oy = y * height;
for (int z = 0; z < height; z++)
{
int i = ox + oy + z;
int ni1 = (x <= 0) ? -1 : ((x - 1) * depth * height) + oy + z;
int ni2 = (y <= 0) ? -1 : ox + ((y - 1) * height) + z;
int ni3 = (z <= 0) ? -1 : ox + oy + (z - 1);
// Skip any empty voxels that have all empty negative neighbors
if (!voxels[i].IsSolid &&
x != width - 1 && y != depth - 1 && z != height - 1 &&
ni1 != -1 && ni2 != -1 && ni3 != -1 &&
!voxels[ni1].IsSolid &&
!voxels[ni2].IsSolid &&
!voxels[ni3].IsSolid)
continue;
voxelsNode.Nodes.Add(voxels[i].GetNode());
}
}
}
return voxelsNode;
}
#endregion
}
}
| 30.968481 | 125 | 0.400167 | [
"MIT"
] | Kyle0654/Portal2.Puzzle | Portal2Puzzle/VoxelField.cs | 10,810 | C# |
using System;
namespace Project
{
public interface IFlyweight
{
string IntrinsicState { get; }
void Operation(string extrinsicState);
}
} | 15.181818 | 46 | 0.646707 | [
"MIT"
] | danieldeveloper001/csharp_design_patterns | src/structural/flyweight/001_abstract/Flyweight/IFlyweight.cs | 167 | C# |
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Linq;
using System.Security.Claims;
namespace Oldmansoft.Identity
{
/// <summary>
/// 提供帐号认证
/// </summary>
[Microsoft.AspNetCore.Authorization.Authorize]
public abstract class AuthController : Controller, Mvc.IAuthController
{
private const string AccountCacheKey = "IdentityAccount";
/// <summary>
/// 操作资源
/// </summary>
public abstract Guid OperateResource { get; }
/// <summary>
/// 身份系统仓储工厂
/// </summary>
protected abstract Infrastructure.IRepositoryFactory Factory { get; }
private Guid? _AccountId;
/// <summary>
/// 帐号序号
/// </summary>
protected Guid AccountId
{
get
{
if (_AccountId.HasValue) return _AccountId.Value;
_AccountId = Guid.Empty;
if (User.Identity == null) return _AccountId.Value;
var userId = GetUserId(User.Identity);
if (string.IsNullOrEmpty(userId)) return _AccountId.Value;
_AccountId = Guid.Parse(userId);
return _AccountId.Value;
}
}
/// <summary>
/// 获取用户序号
/// </summary>
/// <param name="identity"></param>
/// <returns></returns>
private static string GetUserId(System.Security.Principal.IIdentity identity)
{
if (identity == null)
{
throw new ArgumentNullException("identity");
}
if (identity is ClaimsIdentity identity2)
{
return FindFirstValue(identity2, ClaimTypes.NameIdentifier);
}
return null;
}
/// <summary>
/// 查找第一个值
/// </summary>
/// <param name="identity"></param>
/// <param name="claimType"></param>
/// <returns></returns>
private static string FindFirstValue(ClaimsIdentity identity, string claimType)
{
if (identity == null)
{
throw new ArgumentNullException("identity");
}
var claim = identity.FindFirst(claimType);
if (claim == null)
{
return null;
}
return claim.Value;
}
/// <summary>
/// 在调用操作方法前调用
/// </summary>
/// <param name="context"></param>
public override void OnActionExecuting(ActionExecutingContext context)
{
var action = context.ActionDescriptor;
if (action.EndpointMetadata.FirstOrDefault(o => o.GetType() == typeof(HttpPostAttribute)) != null && action.EndpointMetadata.FirstOrDefault(o => o.GetType() == typeof(CrossSiteRequestAttribute)) == null)
{
new CsrfDefendAttribute().OnActionExecuting(context);
}
base.OnActionExecuting(context);
}
/// <summary>
/// 帐号
/// </summary>
public Data.AccountData Account
{
get
{
if (HttpContext.Items.ContainsKey(AccountCacheKey))
{
return HttpContext.Items[AccountCacheKey] as Data.AccountData;
}
var result = new IdentityManager(Factory).GetAccount(AccountId);
HttpContext.Items.Add(AccountCacheKey, result);
return result;
}
}
/// <summary>
/// 是否有权限
/// </summary>
/// <param name="operation"></param>
/// <returns></returns>
protected bool HasPower(Operation operation)
{
return Account.HasPower(OperateResource, operation);
}
}
}
| 30.015504 | 215 | 0.52531 | [
"Apache-2.0"
] | Oldmansoft/Identity | src/Oldmansoft.Identity.MvcCore/AuthController.cs | 3,976 | C# |
/* ------------------------------------------------------------------------- */
//
// Copyright (c) 2010 CubeSoft, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
/* ------------------------------------------------------------------------- */
using System;
using Cube.Mixin.Time;
using NUnit.Framework;
namespace Cube.Tests.Mixin
{
/* --------------------------------------------------------------------- */
///
/// TimeTest
///
/// <summary>
/// Tests extended methods of the DateTime and related classes.
/// </summary>
///
/* --------------------------------------------------------------------- */
[TestFixture]
class TimeTest
{
#region Tests
/* ----------------------------------------------------------------- */
///
/// ToUniversalTime
///
/// <summary>
/// Tests the ToUniversalTime extended method.
/// </summary>
///
/* ----------------------------------------------------------------- */
[TestCase(0x7fffffffu, 2038, 1, 19, 3, 14, 7)]
[TestCase(0x80000000u, 2038, 1, 19, 3, 14, 8)]
[TestCase(0xffffffffu, 2106, 2, 7, 6, 28, 15)]
public void ToUniversalTime(uint unix, int y, int m, int d, int hh, int mm, int ss)
{
var src = (int)unix;
var expected = new DateTime(y, m, d, hh, mm, ss, 0, DateTimeKind.Utc);
Assert.That(src.ToUniversalTime(), Is.EqualTo(expected));
}
/* ----------------------------------------------------------------- */
///
/// ToLocalTime
///
/// <summary>
/// Tests the ToLocalTime extended method.
/// </summary>
///
/* ----------------------------------------------------------------- */
[TestCase(0x7fffffffu, 2038, 1, 19, 3, 14, 7)]
[TestCase(0x80000000u, 2038, 1, 19, 3, 14, 8)]
[TestCase(0xffffffffu, 2106, 2, 7, 6, 28, 15)]
public void ToLocalTime(uint unix, int y, int m, int d, int hh, int mm, int ss)
{
var src = (int)unix;
var expected = new DateTime(y, m, d, hh, mm, ss, 0, DateTimeKind.Utc).ToLocalTime();
Assert.That(src.ToLocalTime(), Is.EqualTo(expected));
}
/* ----------------------------------------------------------------- */
///
/// Convert_Unix_Utc
///
/// <summary>
/// Confirms the result when converting the DateTime object to the
/// UNIX time and reconverting to the DateTime object.
/// </summary>
///
/* ----------------------------------------------------------------- */
[TestCase(1970, 1, 1, 0, 0, 0)]
[TestCase(2000, 1, 1, 0, 0, 0)]
[TestCase(2038, 1, 19, 3, 14, 7)]
[TestCase(2104, 1, 1, 0, 0, 0)]
[TestCase(2999, 12, 31, 23, 59, 59)]
public void Convert_Unix_Utc(int y, int m, int d, int hh, int mm, int ss)
{
var src = new DateTime(y, m, d, hh, mm, ss, 0, DateTimeKind.Utc);
var dest = src.ToUnixTime().ToUniversalTime();
Assert.That(dest, Is.EqualTo(src));
}
/* ----------------------------------------------------------------- */
///
/// Convert_Unix_Local
///
/// <summary>
/// Confirms the result when converting the DateTime object to the
/// UNIX time and reconverting to the DateTime object.
/// </summary>
///
/* ----------------------------------------------------------------- */
[TestCase(1970, 1, 1, 0, 0, 0)]
[TestCase(2000, 1, 1, 0, 0, 0)]
[TestCase(2038, 1, 19, 3, 14, 7)]
[TestCase(2104, 1, 1, 0, 0, 0)]
[TestCase(2999, 12, 31, 23, 59, 59)]
public void Convert_Unix_Local(int y, int m, int d, int hh, int mm, int ss)
{
var src = new DateTime(y, m, d, hh, mm, ss, 0, DateTimeKind.Local);
var dest = src.ToUnixTime().ToLocalTime();
Assert.That(dest, Is.EqualTo(src));
}
/* ----------------------------------------------------------------- */
///
/// Parse_UniversalTime
///
/// <summary>
/// Tests the extended method of parsing the specified date-time
/// string.
/// </summary>
///
/* ----------------------------------------------------------------- */
[TestCase("2017/02/03 12:34:55", "yyyy/MM/dd HH:mm:ss", 2017, 2, 3, 12, 34, 55)]
public void Parse_UniversalTime(string src, string fmt, int y, int m, int d, int hh, int mm, int ss)
{
var expected = new DateTime(y, m, d, hh, mm, ss, 0, DateTimeKind.Utc);
var dest = src.ToUniversalTime(fmt);
Assert.That(dest.Kind, Is.EqualTo(DateTimeKind.Utc));
Assert.That(dest, Is.EqualTo(expected));
}
/* ----------------------------------------------------------------- */
///
/// Parse_LocalTime
///
/// <summary>
/// Tests the extended method of parsing the specified date-time
/// string.
/// </summary>
///
/* ----------------------------------------------------------------- */
[TestCase("2017/02/03 12:34:55", "yyyy/MM/dd HH:mm:ss", 2017, 2, 3, 12, 34, 55)]
public void Parse_LocalTime(string src, string fmt, int y, int m, int d, int hh, int mm, int ss)
{
var expected = new DateTime(y, m, d, hh, mm, ss, 0, DateTimeKind.Local);
var dest = src.ToLocalTime(fmt);
Assert.That(dest.Kind, Is.EqualTo(DateTimeKind.Local));
Assert.That(dest, Is.EqualTo(expected));
}
/* ----------------------------------------------------------------- */
///
/// Parse_FormatException
///
/// <summary>
/// Tests the ToUniversalTime and ToLocalTime methods with the
/// empty string.
/// </summary>
///
/* ----------------------------------------------------------------- */
[TestCase("2017/02/03 12:34:55", "")]
[TestCase("", "yyyy/MM/dd HH:mm:ss")]
public void Parse_FormatException(string src, string fmt)
{
Assert.That(() => src.ToUniversalTime(fmt), Throws.TypeOf<FormatException>());
Assert.That(() => src.ToLocalTime(fmt), Throws.TypeOf<FormatException>());
}
/* ----------------------------------------------------------------- */
///
/// Parse_ArgumentNullException
///
/// <summary>
/// Tests the ToUniversalTime and ToLocalTime methods with the
/// null string.
/// </summary>
///
/* ----------------------------------------------------------------- */
[TestCase("2017/02/03 12:34:55", default(string))]
[TestCase(default(string), "yyyy/MM/dd HH:mm:ss")]
public void Parse_ArgumentNullException(string src, string fmt)
{
Assert.That(() => src.ToUniversalTime(fmt), Throws.ArgumentNullException);
Assert.That(() => src.ToLocalTime(fmt), Throws.ArgumentNullException);
}
#endregion
}
}
| 39.462312 | 108 | 0.428626 | [
"Apache-2.0"
] | bubdm/Cube.Core | Tests/Core/Sources/Mixin/TimeTest.cs | 7,855 | C# |
using System;
using NetRuntimeSystem = System;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.ComponentModel;
using System.Reflection;
using System.Collections.Generic;
using NetOffice;
namespace NetOffice.AccessApi
{
///<summary>
/// DispatchInterface _AutoCorrect
/// SupportByVersion Access, 11,12,14,15,16
///</summary>
[SupportByVersionAttribute("Access", 11,12,14,15,16)]
[EntityTypeAttribute(EntityType.IsDispatchInterface)]
public class _AutoCorrect : COMObject
{
#pragma warning disable
#region Type Information
private static Type _type;
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public static Type LateBindingApiWrapperType
{
get
{
if (null == _type)
_type = typeof(_AutoCorrect);
return _type;
}
}
#endregion
#region Construction
///<param name="factory">current used factory core</param>
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
public _AutoCorrect(Core factory, ICOMObject parentObject, object comProxy) : base(factory, parentObject, comProxy)
{
}
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public _AutoCorrect(ICOMObject parentObject, object comProxy) : base(parentObject, comProxy)
{
}
///<param name="factory">current used factory core</param>
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
///<param name="comProxyType">Type of inner wrapped COM proxy"</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public _AutoCorrect(Core factory, ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(factory, parentObject, comProxy, comProxyType)
{
}
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
///<param name="comProxyType">Type of inner wrapped COM proxy"</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public _AutoCorrect(ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(parentObject, comProxy, comProxyType)
{
}
///<param name="replacedObject">object to replaced. replacedObject are not usable after this action</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public _AutoCorrect(ICOMObject replacedObject) : base(replacedObject)
{
}
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public _AutoCorrect() : base()
{
}
/// <param name="progId">registered ProgID</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public _AutoCorrect(string progId) : base(progId)
{
}
#endregion
#region Properties
/// <summary>
/// SupportByVersion Access 11, 12, 14, 15, 16
/// Get/Set
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff193224.aspx
/// </summary>
[SupportByVersionAttribute("Access", 11,12,14,15,16)]
public bool DisplayAutoCorrectOptions
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "DisplayAutoCorrectOptions", paramsArray);
return NetRuntimeSystem.Convert.ToBoolean(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "DisplayAutoCorrectOptions", paramsArray);
}
}
#endregion
#region Methods
/// <summary>
/// SupportByVersion Access 11, 12, 14, 15, 16
///
/// </summary>
/// <param name="dispid">Int32 dispid</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
[SupportByVersionAttribute("Access", 11,12,14,15,16)]
public bool IsMemberSafe(Int32 dispid)
{
object[] paramsArray = Invoker.ValidateParamsArray(dispid);
object returnItem = Invoker.MethodReturn(this, "IsMemberSafe", paramsArray);
return NetRuntimeSystem.Convert.ToBoolean(returnItem);
}
#endregion
#pragma warning restore
}
} | 32.772059 | 167 | 0.702266 | [
"MIT"
] | brunobola/NetOffice | Source/Access/DispatchInterfaces/_AutoCorrect.cs | 4,459 | C# |
using Volo.Abp.Http.Client.IdentityModel;
using Volo.Abp.Modularity;
namespace ModuleA
{
[DependsOn(
typeof(ModuleAHttpApiClientModule),
typeof(AbpHttpClientIdentityModelModule)
)]
public class ModuleAConsoleApiClientModule : AbpModule
{
}
}
| 19.533333 | 58 | 0.686007 | [
"MIT"
] | antosubash/NewModuleWithTieredAbpApp | modules/ModuleA/test/ModuleA.HttpApi.Client.ConsoleTestApp/ModuleAConsoleApiClientModule.cs | 295 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Artifactory
{
/// <summary>
/// This resource can be used to manage Artifactory's LDAP Group settings for user authentication.
///
/// LDAP Groups Add-on allows you to synchronize your LDAP groups with the system and leverage your existing organizational
/// structure for managing group-based permissions.
///
/// ## Import
///
/// LDAP Group setting can be imported using the key, e.g.
///
/// ```sh
/// $ pulumi import artifactory:index/ldapGroupSetting:LdapGroupSetting ldap_group_name ldap_group_name
/// ```
/// </summary>
[ArtifactoryResourceType("artifactory:index/ldapGroupSetting:LdapGroupSetting")]
public partial class LdapGroupSetting : Pulumi.CustomResource
{
/// <summary>
/// An attribute on the group entry which denoting the group description. Used when importing groups.
/// </summary>
[Output("descriptionAttribute")]
public Output<string> DescriptionAttribute { get; private set; } = null!;
/// <summary>
/// The LDAP filter used to search for group entries. Used for importing groups.
/// </summary>
[Output("filter")]
public Output<string> Filter { get; private set; } = null!;
/// <summary>
/// A search base for group entry DNs, relative to the DN on the LDAP server’s URL (and not relative to the LDAP Setting’s “Search Base”). Used when importing groups.
/// </summary>
[Output("groupBaseDn")]
public Output<string?> GroupBaseDn { get; private set; } = null!;
/// <summary>
/// A multi-value attribute on the group entry containing user DNs or IDs of the group members (e.g., uniqueMember,member).
/// </summary>
[Output("groupMemberAttribute")]
public Output<string> GroupMemberAttribute { get; private set; } = null!;
/// <summary>
/// Attribute on the group entry denoting the group name. Used when importing groups.
/// </summary>
[Output("groupNameAttribute")]
public Output<string> GroupNameAttribute { get; private set; } = null!;
/// <summary>
/// The LDAP setting key you want to use for group retrieval. The value for this field corresponds to 'enabledLdap' field of
/// the ldap group setting XML block of system configuration.
/// </summary>
[Output("ldapSettingKey")]
public Output<string> LdapSettingKey { get; private set; } = null!;
/// <summary>
/// Ldap group setting name.
/// </summary>
[Output("name")]
public Output<string> Name { get; private set; } = null!;
/// <summary>
/// The JFrog Platform Deployment (JPD) supports three ways of mapping groups to LDAP schemas:
/// - STATIC: Group objects are aware of their members, however, the users are not aware of the groups they belong to. Each group object such as groupOfNames or groupOfUniqueNames holds its respective member attributes, typically member or uniqueMember, which is a user DN.
/// - DYNAMIC: User objects are aware of what groups they belong to, but the group objects are not aware of their members. Each user object contains a custom attribute, such as group, that holds the group DNs or group names of which the user is a member.
/// - HIERARCHICAL: The user's DN is indicative of the groups the user belongs to by using group names as part of user DN hierarchy. Each user DN contains a list of ou's or custom attributes that make up the group association. For example, uid=user1,ou=developers,ou=uk,dc=jfrog,dc=org indicates that user1 belongs to two groups: uk and developers.
/// </summary>
[Output("strategy")]
public Output<string> Strategy { get; private set; } = null!;
/// <summary>
/// When set, enables deep search through the sub-tree of the LDAP URL + Search Base. True by default.
/// </summary>
[Output("subTree")]
public Output<bool?> SubTree { get; private set; } = null!;
/// <summary>
/// Create a LdapGroupSetting resource with the given unique name, arguments, and options.
/// </summary>
///
/// <param name="name">The unique name of the resource</param>
/// <param name="args">The arguments used to populate this resource's properties</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public LdapGroupSetting(string name, LdapGroupSettingArgs args, CustomResourceOptions? options = null)
: base("artifactory:index/ldapGroupSetting:LdapGroupSetting", name, args ?? new LdapGroupSettingArgs(), MakeResourceOptions(options, ""))
{
}
private LdapGroupSetting(string name, Input<string> id, LdapGroupSettingState? state = null, CustomResourceOptions? options = null)
: base("artifactory:index/ldapGroupSetting:LdapGroupSetting", name, state, MakeResourceOptions(options, id))
{
}
private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id)
{
var defaultOptions = new CustomResourceOptions
{
Version = Utilities.Version,
};
var merged = CustomResourceOptions.Merge(defaultOptions, options);
// Override the ID if one was specified for consistency with other language SDKs.
merged.Id = id ?? merged.Id;
return merged;
}
/// <summary>
/// Get an existing LdapGroupSetting resource's state with the given name, ID, and optional extra
/// properties used to qualify the lookup.
/// </summary>
///
/// <param name="name">The unique name of the resulting resource.</param>
/// <param name="id">The unique provider ID of the resource to lookup.</param>
/// <param name="state">Any extra arguments used during the lookup.</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public static LdapGroupSetting Get(string name, Input<string> id, LdapGroupSettingState? state = null, CustomResourceOptions? options = null)
{
return new LdapGroupSetting(name, id, state, options);
}
}
public sealed class LdapGroupSettingArgs : Pulumi.ResourceArgs
{
/// <summary>
/// An attribute on the group entry which denoting the group description. Used when importing groups.
/// </summary>
[Input("descriptionAttribute", required: true)]
public Input<string> DescriptionAttribute { get; set; } = null!;
/// <summary>
/// The LDAP filter used to search for group entries. Used for importing groups.
/// </summary>
[Input("filter", required: true)]
public Input<string> Filter { get; set; } = null!;
/// <summary>
/// A search base for group entry DNs, relative to the DN on the LDAP server’s URL (and not relative to the LDAP Setting’s “Search Base”). Used when importing groups.
/// </summary>
[Input("groupBaseDn")]
public Input<string>? GroupBaseDn { get; set; }
/// <summary>
/// A multi-value attribute on the group entry containing user DNs or IDs of the group members (e.g., uniqueMember,member).
/// </summary>
[Input("groupMemberAttribute", required: true)]
public Input<string> GroupMemberAttribute { get; set; } = null!;
/// <summary>
/// Attribute on the group entry denoting the group name. Used when importing groups.
/// </summary>
[Input("groupNameAttribute", required: true)]
public Input<string> GroupNameAttribute { get; set; } = null!;
/// <summary>
/// The LDAP setting key you want to use for group retrieval. The value for this field corresponds to 'enabledLdap' field of
/// the ldap group setting XML block of system configuration.
/// </summary>
[Input("ldapSettingKey", required: true)]
public Input<string> LdapSettingKey { get; set; } = null!;
/// <summary>
/// Ldap group setting name.
/// </summary>
[Input("name")]
public Input<string>? Name { get; set; }
/// <summary>
/// The JFrog Platform Deployment (JPD) supports three ways of mapping groups to LDAP schemas:
/// - STATIC: Group objects are aware of their members, however, the users are not aware of the groups they belong to. Each group object such as groupOfNames or groupOfUniqueNames holds its respective member attributes, typically member or uniqueMember, which is a user DN.
/// - DYNAMIC: User objects are aware of what groups they belong to, but the group objects are not aware of their members. Each user object contains a custom attribute, such as group, that holds the group DNs or group names of which the user is a member.
/// - HIERARCHICAL: The user's DN is indicative of the groups the user belongs to by using group names as part of user DN hierarchy. Each user DN contains a list of ou's or custom attributes that make up the group association. For example, uid=user1,ou=developers,ou=uk,dc=jfrog,dc=org indicates that user1 belongs to two groups: uk and developers.
/// </summary>
[Input("strategy", required: true)]
public Input<string> Strategy { get; set; } = null!;
/// <summary>
/// When set, enables deep search through the sub-tree of the LDAP URL + Search Base. True by default.
/// </summary>
[Input("subTree")]
public Input<bool>? SubTree { get; set; }
public LdapGroupSettingArgs()
{
}
}
public sealed class LdapGroupSettingState : Pulumi.ResourceArgs
{
/// <summary>
/// An attribute on the group entry which denoting the group description. Used when importing groups.
/// </summary>
[Input("descriptionAttribute")]
public Input<string>? DescriptionAttribute { get; set; }
/// <summary>
/// The LDAP filter used to search for group entries. Used for importing groups.
/// </summary>
[Input("filter")]
public Input<string>? Filter { get; set; }
/// <summary>
/// A search base for group entry DNs, relative to the DN on the LDAP server’s URL (and not relative to the LDAP Setting’s “Search Base”). Used when importing groups.
/// </summary>
[Input("groupBaseDn")]
public Input<string>? GroupBaseDn { get; set; }
/// <summary>
/// A multi-value attribute on the group entry containing user DNs or IDs of the group members (e.g., uniqueMember,member).
/// </summary>
[Input("groupMemberAttribute")]
public Input<string>? GroupMemberAttribute { get; set; }
/// <summary>
/// Attribute on the group entry denoting the group name. Used when importing groups.
/// </summary>
[Input("groupNameAttribute")]
public Input<string>? GroupNameAttribute { get; set; }
/// <summary>
/// The LDAP setting key you want to use for group retrieval. The value for this field corresponds to 'enabledLdap' field of
/// the ldap group setting XML block of system configuration.
/// </summary>
[Input("ldapSettingKey")]
public Input<string>? LdapSettingKey { get; set; }
/// <summary>
/// Ldap group setting name.
/// </summary>
[Input("name")]
public Input<string>? Name { get; set; }
/// <summary>
/// The JFrog Platform Deployment (JPD) supports three ways of mapping groups to LDAP schemas:
/// - STATIC: Group objects are aware of their members, however, the users are not aware of the groups they belong to. Each group object such as groupOfNames or groupOfUniqueNames holds its respective member attributes, typically member or uniqueMember, which is a user DN.
/// - DYNAMIC: User objects are aware of what groups they belong to, but the group objects are not aware of their members. Each user object contains a custom attribute, such as group, that holds the group DNs or group names of which the user is a member.
/// - HIERARCHICAL: The user's DN is indicative of the groups the user belongs to by using group names as part of user DN hierarchy. Each user DN contains a list of ou's or custom attributes that make up the group association. For example, uid=user1,ou=developers,ou=uk,dc=jfrog,dc=org indicates that user1 belongs to two groups: uk and developers.
/// </summary>
[Input("strategy")]
public Input<string>? Strategy { get; set; }
/// <summary>
/// When set, enables deep search through the sub-tree of the LDAP URL + Search Base. True by default.
/// </summary>
[Input("subTree")]
public Input<bool>? SubTree { get; set; }
public LdapGroupSettingState()
{
}
}
}
| 51.636015 | 356 | 0.645025 | [
"ECL-2.0",
"Apache-2.0"
] | pulumi/pulumi-artifactory | sdk/dotnet/LdapGroupSetting.cs | 13,501 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.