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
namespace Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210 { using Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.PowerShell; /// <summary>Recovery plan details.</summary> [System.ComponentModel.TypeConverter(typeof(RecoveryPlanTypeConverter))] public partial class RecoveryPlan { /// <summary> /// <c>AfterDeserializeDictionary</c> will be called after the deserialization has finished, allowing customization of the /// object before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); /// <summary> /// <c>AfterDeserializePSObject</c> will be called after the deserialization has finished, allowing customization of the object /// before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); /// <summary> /// <c>BeforeDeserializeDictionary</c> will be called before the deserialization has commenced, allowing complete customization /// of the object before it is deserialized. /// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> /// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return /// instantly.</param> partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); /// <summary> /// <c>BeforeDeserializePSObject</c> will be called before the deserialization has commenced, allowing complete customization /// of the object before it is deserialized. /// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> /// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return /// instantly.</param> partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); /// <summary> /// Deserializes a <see cref="global::System.Collections.IDictionary" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.RecoveryPlan" /// />. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> /// <returns> /// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlan" />. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlan DeserializeFromDictionary(global::System.Collections.IDictionary content) { return new RecoveryPlan(content); } /// <summary> /// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.RecoveryPlan" /// />. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> /// <returns> /// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlan" />. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlan DeserializeFromPSObject(global::System.Management.Automation.PSObject content) { return new RecoveryPlan(content); } /// <summary> /// Creates a new instance of <see cref="RecoveryPlan" />, deserializing the content from a json string. /// </summary> /// <param name="jsonText">a string containing a JSON serialized instance of this model.</param> /// <returns>an instance of the <see cref="className" /> model class.</returns> public static Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlan FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode.Parse(jsonText)); /// <summary> /// Deserializes a <see cref="global::System.Collections.IDictionary" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.RecoveryPlan" /// />. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> internal RecoveryPlan(global::System.Collections.IDictionary content) { bool returnNow = false; BeforeDeserializeDictionary(content, ref returnNow); if (returnNow) { return; } // actually deserialize ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.RecoveryPlanPropertiesTypeConverter.ConvertFrom); ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IResourceInternal)this).Id, global::System.Convert.ToString); ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IResourceInternal)this).Name, global::System.Convert.ToString); ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IResourceInternal)this).Type, global::System.Convert.ToString); ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IResourceInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IResourceInternal)this).Location, global::System.Convert.ToString); ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanInternal)this).CurrentScenario = (Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.ICurrentScenarioDetails) content.GetValueForProperty("CurrentScenario",((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanInternal)this).CurrentScenario, Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.CurrentScenarioDetailsTypeConverter.ConvertFrom); ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanInternal)this).FriendlyName = (string) content.GetValueForProperty("FriendlyName",((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanInternal)this).FriendlyName, global::System.Convert.ToString); ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanInternal)this).PrimaryFabricId = (string) content.GetValueForProperty("PrimaryFabricId",((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanInternal)this).PrimaryFabricId, global::System.Convert.ToString); ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanInternal)this).PrimaryFabricFriendlyName = (string) content.GetValueForProperty("PrimaryFabricFriendlyName",((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanInternal)this).PrimaryFabricFriendlyName, global::System.Convert.ToString); ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanInternal)this).RecoveryFabricId = (string) content.GetValueForProperty("RecoveryFabricId",((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanInternal)this).RecoveryFabricId, global::System.Convert.ToString); ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanInternal)this).RecoveryFabricFriendlyName = (string) content.GetValueForProperty("RecoveryFabricFriendlyName",((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanInternal)this).RecoveryFabricFriendlyName, global::System.Convert.ToString); ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanInternal)this).FailoverDeploymentModel = (string) content.GetValueForProperty("FailoverDeploymentModel",((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanInternal)this).FailoverDeploymentModel, global::System.Convert.ToString); ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanInternal)this).ReplicationProvider = (string[]) content.GetValueForProperty("ReplicationProvider",((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanInternal)this).ReplicationProvider, __y => TypeConverterExtensions.SelectToArray<string>(__y, global::System.Convert.ToString)); ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanInternal)this).AllowedOperation = (string[]) content.GetValueForProperty("AllowedOperation",((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanInternal)this).AllowedOperation, __y => TypeConverterExtensions.SelectToArray<string>(__y, global::System.Convert.ToString)); ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanInternal)this).LastPlannedFailoverTime = (global::System.DateTime?) content.GetValueForProperty("LastPlannedFailoverTime",((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanInternal)this).LastPlannedFailoverTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanInternal)this).LastUnplannedFailoverTime = (global::System.DateTime?) content.GetValueForProperty("LastUnplannedFailoverTime",((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanInternal)this).LastUnplannedFailoverTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanInternal)this).LastTestFailoverTime = (global::System.DateTime?) content.GetValueForProperty("LastTestFailoverTime",((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanInternal)this).LastTestFailoverTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanInternal)this).CurrentScenarioStatus = (string) content.GetValueForProperty("CurrentScenarioStatus",((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanInternal)this).CurrentScenarioStatus, global::System.Convert.ToString); ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanInternal)this).CurrentScenarioStatusDescription = (string) content.GetValueForProperty("CurrentScenarioStatusDescription",((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanInternal)this).CurrentScenarioStatusDescription, global::System.Convert.ToString); ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanInternal)this).Group = (Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanGroup[]) content.GetValueForProperty("Group",((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanInternal)this).Group, __y => TypeConverterExtensions.SelectToArray<Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanGroup>(__y, Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.RecoveryPlanGroupTypeConverter.ConvertFrom)); ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanInternal)this).ProviderSpecificDetail = (Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanProviderSpecificDetails[]) content.GetValueForProperty("ProviderSpecificDetail",((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanInternal)this).ProviderSpecificDetail, __y => TypeConverterExtensions.SelectToArray<Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanProviderSpecificDetails>(__y, Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.RecoveryPlanProviderSpecificDetailsTypeConverter.ConvertFrom)); ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanInternal)this).CurrentScenarioName = (string) content.GetValueForProperty("CurrentScenarioName",((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanInternal)this).CurrentScenarioName, global::System.Convert.ToString); ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanInternal)this).CurrentScenarioJobId = (string) content.GetValueForProperty("CurrentScenarioJobId",((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanInternal)this).CurrentScenarioJobId, global::System.Convert.ToString); ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanInternal)this).CurrentScenarioStartTime = (global::System.DateTime?) content.GetValueForProperty("CurrentScenarioStartTime",((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanInternal)this).CurrentScenarioStartTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); AfterDeserializeDictionary(content); } /// <summary> /// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.RecoveryPlan" /// />. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> internal RecoveryPlan(global::System.Management.Automation.PSObject content) { bool returnNow = false; BeforeDeserializePSObject(content, ref returnNow); if (returnNow) { return; } // actually deserialize ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.RecoveryPlanPropertiesTypeConverter.ConvertFrom); ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IResourceInternal)this).Id, global::System.Convert.ToString); ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IResourceInternal)this).Name, global::System.Convert.ToString); ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IResourceInternal)this).Type, global::System.Convert.ToString); ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IResourceInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IResourceInternal)this).Location, global::System.Convert.ToString); ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanInternal)this).CurrentScenario = (Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.ICurrentScenarioDetails) content.GetValueForProperty("CurrentScenario",((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanInternal)this).CurrentScenario, Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.CurrentScenarioDetailsTypeConverter.ConvertFrom); ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanInternal)this).FriendlyName = (string) content.GetValueForProperty("FriendlyName",((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanInternal)this).FriendlyName, global::System.Convert.ToString); ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanInternal)this).PrimaryFabricId = (string) content.GetValueForProperty("PrimaryFabricId",((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanInternal)this).PrimaryFabricId, global::System.Convert.ToString); ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanInternal)this).PrimaryFabricFriendlyName = (string) content.GetValueForProperty("PrimaryFabricFriendlyName",((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanInternal)this).PrimaryFabricFriendlyName, global::System.Convert.ToString); ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanInternal)this).RecoveryFabricId = (string) content.GetValueForProperty("RecoveryFabricId",((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanInternal)this).RecoveryFabricId, global::System.Convert.ToString); ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanInternal)this).RecoveryFabricFriendlyName = (string) content.GetValueForProperty("RecoveryFabricFriendlyName",((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanInternal)this).RecoveryFabricFriendlyName, global::System.Convert.ToString); ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanInternal)this).FailoverDeploymentModel = (string) content.GetValueForProperty("FailoverDeploymentModel",((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanInternal)this).FailoverDeploymentModel, global::System.Convert.ToString); ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanInternal)this).ReplicationProvider = (string[]) content.GetValueForProperty("ReplicationProvider",((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanInternal)this).ReplicationProvider, __y => TypeConverterExtensions.SelectToArray<string>(__y, global::System.Convert.ToString)); ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanInternal)this).AllowedOperation = (string[]) content.GetValueForProperty("AllowedOperation",((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanInternal)this).AllowedOperation, __y => TypeConverterExtensions.SelectToArray<string>(__y, global::System.Convert.ToString)); ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanInternal)this).LastPlannedFailoverTime = (global::System.DateTime?) content.GetValueForProperty("LastPlannedFailoverTime",((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanInternal)this).LastPlannedFailoverTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanInternal)this).LastUnplannedFailoverTime = (global::System.DateTime?) content.GetValueForProperty("LastUnplannedFailoverTime",((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanInternal)this).LastUnplannedFailoverTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanInternal)this).LastTestFailoverTime = (global::System.DateTime?) content.GetValueForProperty("LastTestFailoverTime",((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanInternal)this).LastTestFailoverTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanInternal)this).CurrentScenarioStatus = (string) content.GetValueForProperty("CurrentScenarioStatus",((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanInternal)this).CurrentScenarioStatus, global::System.Convert.ToString); ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanInternal)this).CurrentScenarioStatusDescription = (string) content.GetValueForProperty("CurrentScenarioStatusDescription",((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanInternal)this).CurrentScenarioStatusDescription, global::System.Convert.ToString); ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanInternal)this).Group = (Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanGroup[]) content.GetValueForProperty("Group",((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanInternal)this).Group, __y => TypeConverterExtensions.SelectToArray<Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanGroup>(__y, Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.RecoveryPlanGroupTypeConverter.ConvertFrom)); ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanInternal)this).ProviderSpecificDetail = (Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanProviderSpecificDetails[]) content.GetValueForProperty("ProviderSpecificDetail",((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanInternal)this).ProviderSpecificDetail, __y => TypeConverterExtensions.SelectToArray<Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanProviderSpecificDetails>(__y, Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.RecoveryPlanProviderSpecificDetailsTypeConverter.ConvertFrom)); ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanInternal)this).CurrentScenarioName = (string) content.GetValueForProperty("CurrentScenarioName",((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanInternal)this).CurrentScenarioName, global::System.Convert.ToString); ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanInternal)this).CurrentScenarioJobId = (string) content.GetValueForProperty("CurrentScenarioJobId",((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanInternal)this).CurrentScenarioJobId, global::System.Convert.ToString); ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanInternal)this).CurrentScenarioStartTime = (global::System.DateTime?) content.GetValueForProperty("CurrentScenarioStartTime",((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanInternal)this).CurrentScenarioStartTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); AfterDeserializePSObject(content); } /// <summary>Serializes this instance to a json string.</summary> /// <returns>a <see cref="System.String" /> containing this model serialized to JSON text.</returns> public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.SerializationMode.IncludeAll)?.ToString(); } /// Recovery plan details. [System.ComponentModel.TypeConverter(typeof(RecoveryPlanTypeConverter))] public partial interface IRecoveryPlan { } }
147.887006
677
0.783122
[ "MIT" ]
AverageDesigner/azure-powershell
src/Migrate/generated/api/Models/Api20210210/RecoveryPlan.PowerShell.cs
26,000
C#
namespace ImpossibleOdds.Xml { using System; using ImpossibleOdds.Serialization; [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Struct, AllowMultiple = true)] public class XmlTypeAttribute : Attribute, ILookupTypeResolveParameter { private Type target = null; private object value = null; private string keyOverride = null; private bool setAsElement = false; /// <inheritdoc /> public Type Target { get { return target; } } /// <inheritdoc /> public object Value { get { return value; } set { this.value = value; } } /// <inheritdoc /> object ILookupTypeResolveParameter.KeyOverride { get { return keyOverride; } } /// <inheritdoc /> public string KeyOverride { get { return keyOverride; } set { keyOverride = value; } } /// <summary> /// By default, type information is saved in an XML Attribute. /// Setting this to true will save the type information in an XML Element instead. /// </summary> public bool SetAsElement { get { return setAsElement; } set { setAsElement = value; } } public XmlTypeAttribute(Type target) { target.ThrowIfNull(nameof(target)); this.target = target; } } }
21.596491
118
0.682372
[ "MIT" ]
juniordiscart/ImpossibleOdds-Toolkit
Assets/Impossible Odds/Toolkit/Runtime/Xml/Attributes/XmlTypeAttribute.cs
1,233
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 BuildXL.Utilities.Instrumentation.Common; using BuildXL.Utilities.Tracing; #pragma warning disable 1591 namespace BuildXL.Native.Tracing { /// <summary> /// Logging for Native /// </summary> public class Logger { /// <summary> /// Returns the logger instance /// </summary> public static Logger Log { get; } = new Logger(); public void FileUtilitiesDiagnostic(LoggingContext context, string path, string description) { context.SpecifyVerboseWasLogged((int)EventId.FileUtilitiesDiagnostic); if (LogEventLevel.Verbose <= context.MaximumLevelToLog) { Console.WriteLine("FileUtilities: '{0}'. {1}", path, description); } } public void RetryOnFailureException(LoggingContext context, string exception) { context.SpecifyVerboseWasLogged((int)EventId.RetryOnFailureException); if (LogEventLevel.Verbose <= context.MaximumLevelToLog) { Console.WriteLine("Retry attempt failed with exception. {0}", exception); } } public void SettingOwnershipAndAcl(LoggingContext context, string path) { context.SpecifyVerboseWasLogged((int)EventId.SettingOwnershipAndAcl); if (LogEventLevel.Verbose <= context.MaximumLevelToLog) { Console.WriteLine("Attempting to set ownership and ACL to path '{0}'.", path); } } public void SettingOwnershipAndAclFailed(LoggingContext context, string path, string filename, string arguments, string reason) { context.SpecifyVerboseWasLogged((int)EventId.SettingOwnershipAndAclFailed); if (LogEventLevel.Verbose <= context.MaximumLevelToLog) { Console.WriteLine("Failed to set ownership and ACL to path '{0}'. Command {1} {2} {3}", path, filename, arguments, reason); } } public void StorageReadUsn(LoggingContext context, ulong idHigh, ulong idLow, ulong usn) { context.SpecifyVerboseWasLogged((int)EventId.StorageReadUsn); if (LogEventLevel.Verbose <= context.MaximumLevelToLog) { Console.WriteLine("Read USN: (id {0:X16}-{1:X16}) @ {2:X16}", idHigh, idLow, usn); } } public void StorageCheckpointUsn(LoggingContext context, ulong newUsn) { context.SpecifyVerboseWasLogged((int)EventId.StorageCheckpointUsn); if (LogEventLevel.Verbose <= context.MaximumLevelToLog) { Console.WriteLine("Checkpoint (new USN): {0:X16}", newUsn); } } public void StorageTryOpenOrCreateFileFailure(LoggingContext context, string path, int creationDisposition, int hresult) { context.SpecifyVerboseWasLogged((int)EventId.StorageTryOpenOrCreateFileFailure); if (LogEventLevel.Verbose <= context.MaximumLevelToLog) { Console.WriteLine( "Creating a file handle for path {0} (disposition 0x{1:X8}) failed with HRESULT 0x{2:X8}", path, creationDisposition, hresult); } } public void StorageTryOpenDirectoryFailure(LoggingContext context, string path, int hresult) { context.SpecifyVerboseWasLogged((int)EventId.StorageTryOpenDirectoryFailure); if (LogEventLevel.Verbose <= context.MaximumLevelToLog) { Console.WriteLine("Opening a directory handle for path {0} failed with HRESULT 0x{1:X8}", path, hresult); } } public void StorageFoundVolume(LoggingContext context, string volumeGuidPath, ulong serial) { context.SpecifyVerboseWasLogged((int)EventId.StorageFoundVolume); if (LogEventLevel.Verbose <= context.MaximumLevelToLog) { Console.WriteLine("Found volume {0} (serial: {1:X16})", volumeGuidPath, serial); } } public void StorageTryOpenFileByIdFailure(LoggingContext context, ulong idHigh, ulong idLow, ulong volumeSerial, int hresult) { context.SpecifyVerboseWasLogged((int)EventId.StorageTryOpenFileByIdFailure); if (LogEventLevel.Verbose <= context.MaximumLevelToLog) { Console.WriteLine( "Opening the file with file ID {0:X16}-{1:X16} on {2:X16} failed with HRESULT 0x{3:X8}", idHigh, idLow, volumeSerial, hresult); } } } }
41.377049
140
0.5937
[ "MIT" ]
blufugen/BuildXL
Public/src/Utilities/Native/Tracing/Log.cs
5,048
C#
using System; using System.Collections.Generic; using System.Text; namespace Shove.Gateways.Weixin.Gongzhong { /// <summary> /// 图片,图文类消息 /// </summary> public class ImageTextMessage : Message { private string _ArticleCount; /// <summary> /// 图文消息个数,限制为10条以内 /// </summary> public string ArticleCount { get { return _ArticleCount; } } private string _Title; /// <summary> /// 图文标题 /// </summary> public string Title { get { return _Title; } } private string _Description; /// <summary> /// 图文描述 /// </summary> public string Description { get { return _Description; } } private string _PicUrl; /// <summary> /// 图片链接,支持JPG、PNG格式,较好的效果为大图640*320,小图80*80。 /// </summary> public string PicUrl { get { return _PicUrl; } } private string _Url; /// <summary> /// 点击图片跳转页面 /// </summary> public string Url { get { return _Url; } } /// <summary> /// 构造函数,初始化属性 /// </summary> /// <param name="articleCount">图文消息个数,限制为10条以内</param> /// <param name="title">图文消息标题</param> /// <param name="description">图文描述</param> /// <param name="picUrl">图片链接</param> /// <param name="url">点击图片跳转页面</param> public ImageTextMessage(string articleCount, string title, string description, string picUrl, string url) : base("news") { this._ArticleCount = articleCount; this._Description = description; this._PicUrl = picUrl; this._Title = title; this._Url = url; } } }
25.592105
114
0.480206
[ "MIT" ]
EIMSKobe/Shove.NetCore
Shove.NetCore/Gateways/Weixin/Gongzhong/Message/ReplyMessage/ImageTextMessage.cs
2,157
C#
namespace Msg.Core.Transport.Frames.Constants { public static class Performatives { public const string Begin = "Begin"; public const string Attach = "Attach"; public const string Open = "Open"; public const string Flow = "Flow"; public const string Transfer = "Transfer"; public const string Disposition = "Disposition"; public const string End = "End"; public const string Detach = "Detach"; public const string Close = "Close"; } }
21.16
56
0.618147
[ "Apache-2.0" ]
jagrem/msg
Core/Msg.Core/Transport/Frames/Constants/Performatives.cs
531
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.NetApp.V20190801 { /// <summary> /// NetApp account resource /// </summary> [AzureNativeResourceType("azure-native:netapp/v20190801:Account")] public partial class Account : Pulumi.CustomResource { /// <summary> /// Active Directories /// </summary> [Output("activeDirectories")] public Output<ImmutableArray<Outputs.ActiveDirectoryResponse>> ActiveDirectories { get; private set; } = null!; /// <summary> /// Resource location /// </summary> [Output("location")] public Output<string> Location { get; private set; } = null!; /// <summary> /// Resource name /// </summary> [Output("name")] public Output<string> Name { get; private set; } = null!; /// <summary> /// Azure lifecycle management /// </summary> [Output("provisioningState")] public Output<string> ProvisioningState { get; private set; } = null!; /// <summary> /// Resource tags /// </summary> [Output("tags")] public Output<ImmutableDictionary<string, string>?> Tags { get; private set; } = null!; /// <summary> /// Resource type /// </summary> [Output("type")] public Output<string> Type { get; private set; } = null!; /// <summary> /// Create a Account 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 Account(string name, AccountArgs args, CustomResourceOptions? options = null) : base("azure-native:netapp/v20190801:Account", name, args ?? new AccountArgs(), MakeResourceOptions(options, "")) { } private Account(string name, Input<string> id, CustomResourceOptions? options = null) : base("azure-native:netapp/v20190801:Account", 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:netapp/v20190801:Account"}, new Pulumi.Alias { Type = "azure-native:netapp:Account"}, new Pulumi.Alias { Type = "azure-nextgen:netapp:Account"}, new Pulumi.Alias { Type = "azure-native:netapp/latest:Account"}, new Pulumi.Alias { Type = "azure-nextgen:netapp/latest:Account"}, new Pulumi.Alias { Type = "azure-native:netapp/v20170815:Account"}, new Pulumi.Alias { Type = "azure-nextgen:netapp/v20170815:Account"}, new Pulumi.Alias { Type = "azure-native:netapp/v20190501:Account"}, new Pulumi.Alias { Type = "azure-nextgen:netapp/v20190501:Account"}, new Pulumi.Alias { Type = "azure-native:netapp/v20190601:Account"}, new Pulumi.Alias { Type = "azure-nextgen:netapp/v20190601:Account"}, new Pulumi.Alias { Type = "azure-native:netapp/v20190701:Account"}, new Pulumi.Alias { Type = "azure-nextgen:netapp/v20190701:Account"}, new Pulumi.Alias { Type = "azure-native:netapp/v20191001:Account"}, new Pulumi.Alias { Type = "azure-nextgen:netapp/v20191001:Account"}, new Pulumi.Alias { Type = "azure-native:netapp/v20191101:Account"}, new Pulumi.Alias { Type = "azure-nextgen:netapp/v20191101:Account"}, new Pulumi.Alias { Type = "azure-native:netapp/v20200201:Account"}, new Pulumi.Alias { Type = "azure-nextgen:netapp/v20200201:Account"}, new Pulumi.Alias { Type = "azure-native:netapp/v20200301:Account"}, new Pulumi.Alias { Type = "azure-nextgen:netapp/v20200301:Account"}, new Pulumi.Alias { Type = "azure-native:netapp/v20200501:Account"}, new Pulumi.Alias { Type = "azure-nextgen:netapp/v20200501:Account"}, new Pulumi.Alias { Type = "azure-native:netapp/v20200601:Account"}, new Pulumi.Alias { Type = "azure-nextgen:netapp/v20200601:Account"}, new Pulumi.Alias { Type = "azure-native:netapp/v20200701:Account"}, new Pulumi.Alias { Type = "azure-nextgen:netapp/v20200701:Account"}, new Pulumi.Alias { Type = "azure-native:netapp/v20200801:Account"}, new Pulumi.Alias { Type = "azure-nextgen:netapp/v20200801:Account"}, new Pulumi.Alias { Type = "azure-native:netapp/v20200901:Account"}, new Pulumi.Alias { Type = "azure-nextgen:netapp/v20200901:Account"}, new Pulumi.Alias { Type = "azure-native:netapp/v20201101:Account"}, new Pulumi.Alias { Type = "azure-nextgen:netapp/v20201101:Account"}, }, }; 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 Account 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 Account Get(string name, Input<string> id, CustomResourceOptions? options = null) { return new Account(name, id, options); } } public sealed class AccountArgs : Pulumi.ResourceArgs { /// <summary> /// The name of the NetApp account /// </summary> [Input("accountName")] public Input<string>? AccountName { get; set; } [Input("activeDirectories")] private InputList<Inputs.ActiveDirectoryArgs>? _activeDirectories; /// <summary> /// Active Directories /// </summary> public InputList<Inputs.ActiveDirectoryArgs> ActiveDirectories { get => _activeDirectories ?? (_activeDirectories = new InputList<Inputs.ActiveDirectoryArgs>()); set => _activeDirectories = value; } /// <summary> /// Resource location /// </summary> [Input("location")] public Input<string>? Location { get; set; } /// <summary> /// The name of the resource group. /// </summary> [Input("resourceGroupName", required: true)] public Input<string> ResourceGroupName { get; set; } = null!; [Input("tags")] private InputMap<string>? _tags; /// <summary> /// Resource tags /// </summary> public InputMap<string> Tags { get => _tags ?? (_tags = new InputMap<string>()); set => _tags = value; } public AccountArgs() { } } }
44.351648
126
0.579286
[ "Apache-2.0" ]
pulumi-bot/pulumi-azure-native
sdk/dotnet/NetApp/V20190801/Account.cs
8,072
C#
using System; using System.Collections.Generic; namespace Day_13 { class Program { static void Main() { string input = System.IO.File.ReadAllText("../../../input.txt"); Console.WriteLine(Part1(input)); Console.WriteLine(Part2(input)); } static int Part1(string input) { string[] inputSplit = input.Split("\r\n"); int desiredTime = int.Parse(inputSplit[0]); string[] busesStr = inputSplit[1].Split(","); List<int> buses = new List<int>(); foreach (string b in busesStr) { if (b != "x") { buses.Add(int.Parse(b)); } } int n = desiredTime; while (true) { foreach (int x in buses) { if (n % x == 0) { return x * (n - desiredTime); } } n++; } } static long Part2(string input) { // didnt work string[] inputSplit = input.Split("\r\n"); string[] busesStr = inputSplit[1].Split(","); Dictionary<long, long> buses = new Dictionary<long, long>(); long nn = 0; foreach (string b in busesStr) { if (b != "x") { buses[nn] = long.Parse(b); } nn++; } long n = 0; while (true) { if (n % buses[0] == 0) { int counter = 0; foreach (KeyValuePair<long, long> b in buses) { if (b.Key != 0) { if ((n + b.Key) % b.Value != 0) { break; } } if (counter == buses.Count - 1) { return n; } counter++; } n += buses[0] - 1; } n++; } } } }
27.356322
76
0.317647
[ "MIT" ]
fourjr/advent-of-code
2020/Day 13/Program.cs
2,382
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Simple.Data.Ado { using System.Data; class ConnectionScope : IDisposable { private readonly IDbConnection _connection; public IDbConnection Connection { get { return _connection; } } private readonly bool _dispose; private ConnectionScope(IDbConnection connection, bool dispose) { _connection = connection; _dispose = dispose; } public static ConnectionScope Create(IDbTransaction transaction, Func<IDbConnection> creator) { if (transaction != null) { return new ConnectionScope(transaction.Connection, false); } var connection = creator(); connection.OpenIfClosed(); return new ConnectionScope(connection, true); } public void Dispose() { if (!_dispose) return; _connection.Dispose(); } } }
24.8
102
0.560036
[ "MIT" ]
SimonH/Simple.Data
Simple.Data.Ado/ConnectionScope.cs
1,118
C#
using System.Reflection; using System.Runtime.CompilerServices; 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("PersonalPlanung.Persistence.xml")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("PersonalPlanung.Persistence.xml")] [assembly: AssemblyCopyright("Copyright © 2019")] [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("856578ed-8976-42a9-91dd-b27babb2fa13")] // 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.648649
84
0.751748
[ "MIT" ]
Slesa/Godot
src/PersonalPlanung/PersonalPlanung.Persistence.xml/Properties/AssemblyInfo.cs
1,433
C#
// Copyright (c) 2021, Phoenix Contact GmbH & Co. KG // Licensed under the Apache License, Version 2.0 using System.Runtime.Serialization; using Moryx.Serialization; namespace Moryx.ControlSystem.VisualInstructions { /// <summary> /// Type of instruction /// </summary> public enum InstructionContentType { /// <summary> /// Default value. Should only be used in clients /// </summary> Unknown, /// <summary> /// Simple text instruction /// </summary> Text, /// <summary> /// Media instruction /// </summary> Media } /// <summary> /// Interface of a single instruction /// </summary> [DataContract] public class VisualInstruction { /// <summary> /// Type of instruction /// </summary> [EntrySerialize, DataMember] public InstructionContentType Type { get; set; } /// <summary> /// Content of the instruction /// </summary> [EntrySerialize, DataMember] public string Content { get; set; } /// <summary> /// Smaller/shorter preview for the instruction /// </summary> [DataMember, EntrySerialize] public string Preview { get; set; } } /// <summary> /// Interface for classes that define instructions /// </summary> public interface IVisualInstructions { /// <summary> /// All instructions for this activity /// </summary> VisualInstruction[] Instructions { get; } } }
24.921875
57
0.561755
[ "Apache-2.0" ]
1nf0rmagician/MORYX-Factory
src/Moryx.ControlSystem/VisualInstructions/VisualInstruction.cs
1,595
C#
using System; using cryptography.Services; using NUnit.Framework; namespace cryptography.tests.ServiceTests { public class StringOperationsServiceTests { [Test] [TestCase("abcadaa", 'a', new[] {0,3,5,6})] [TestCase("Test String", 's', new[] {2})] [TestCase("Test String", 't', new[] {3,6})] public void charIndexInStringTestExpectedPasses(String fullText, char val, int[] expected) { var trueCount = 0; var results = StringOperationsService.getCharIndexInString(fullText, val); foreach (var r in results) { if (Array.Exists(expected, e => e == r)){ trueCount++; } } if (trueCount == results.Count){ Assert.Pass(); } else { Assert.Fail(); } } } }
29.258065
98
0.507166
[ "MIT" ]
SimAin/Cryptography
cryptography.tests/ServiceTests/StringOperationsServiceTests.cs
907
C#
using MediaManager.Notifications; using MediaPlayer; namespace MediaManager.Platforms.Apple.Notifications { public class NotificationManager : NotificationManagerBase { public NotificationManager() { Enabled = true; } protected MediaManagerImplementation MediaManager = CrossMediaManager.Apple; protected MPRemoteCommandCenter CommandCenter = MPRemoteCommandCenter.Shared; public override bool Enabled { get => base.Enabled; set { base.Enabled = value; ShowPlayPauseControls = value; ShowNavigationControls = value; } } public override bool ShowPlayPauseControls { get => base.ShowPlayPauseControls; set { base.ShowPlayPauseControls = value; if (ShowPlayPauseControls) { CommandCenter.TogglePlayPauseCommand.Enabled = true; CommandCenter.TogglePlayPauseCommand.AddTarget(PlayPauseCommand); CommandCenter.PlayCommand.Enabled = true; CommandCenter.PlayCommand.AddTarget(PlayCommand); CommandCenter.PauseCommand.Enabled = true; CommandCenter.PauseCommand.AddTarget(PauseCommand); CommandCenter.StopCommand.Enabled = true; CommandCenter.StopCommand.AddTarget(StopCommand); } else { CommandCenter.TogglePlayPauseCommand.Enabled = false; CommandCenter.PlayCommand.Enabled = false; CommandCenter.PauseCommand.Enabled = false; CommandCenter.StopCommand.Enabled = false; } } } public override bool ShowNavigationControls { get => base.ShowNavigationControls; set { base.ShowNavigationControls = value; if (ShowNavigationControls) { CommandCenter.NextTrackCommand.Enabled = true; CommandCenter.NextTrackCommand.AddTarget(NextCommand); CommandCenter.PreviousTrackCommand.Enabled = true; CommandCenter.PreviousTrackCommand.AddTarget(PreviousCommand); CommandCenter.SeekBackwardCommand.Enabled = true; CommandCenter.SeekBackwardCommand.AddTarget(SeekBackwardCommand); CommandCenter.SeekForwardCommand.Enabled = true; CommandCenter.SeekForwardCommand.AddTarget(SeekForwardCommand); CommandCenter.SkipBackwardCommand.Enabled = true; CommandCenter.SkipBackwardCommand.PreferredIntervals = new double[] { MediaManager.StepSizeBackward.TotalSeconds }; CommandCenter.SkipBackwardCommand.AddTarget(SkipBackwardCommand); CommandCenter.SkipForwardCommand.Enabled = true; CommandCenter.SkipForwardCommand.PreferredIntervals = new double[] { MediaManager.StepSizeForward.TotalSeconds }; CommandCenter.SkipForwardCommand.AddTarget(SkipForwardCommand); CommandCenter.ChangeRepeatModeCommand.Enabled = true; CommandCenter.ChangeRepeatModeCommand.AddTarget(RepeatCommand); CommandCenter.ChangeShuffleModeCommand.Enabled = true; CommandCenter.ChangeShuffleModeCommand.AddTarget(ShuffleCommand); CommandCenter.ChangePlaybackPositionCommand.Enabled = true; CommandCenter.ChangePlaybackPositionCommand.AddTarget(PlaybackPositionCommand); } else { CommandCenter.NextTrackCommand.Enabled = false; CommandCenter.PreviousTrackCommand.Enabled = false; CommandCenter.SeekBackwardCommand.Enabled = false; CommandCenter.SeekForwardCommand.Enabled = false; CommandCenter.SkipBackwardCommand.Enabled = false; CommandCenter.SkipForwardCommand.Enabled = false; CommandCenter.ChangeRepeatModeCommand.Enabled = false; CommandCenter.ChangeShuffleModeCommand.Enabled = false; CommandCenter.ChangePlaybackPositionCommand.Enabled = false; } } } public override void UpdateNotification() { var mediaItem = MediaManager.Queue.Current; if (mediaItem == null || !Enabled) { MPNowPlayingInfoCenter.DefaultCenter.NowPlaying = null; return; } var nowPlayingInfo = new MPNowPlayingInfo { Title = mediaItem.DisplayTitle, AlbumTitle = mediaItem.Album, AlbumTrackNumber = mediaItem.TrackNumber, AlbumTrackCount = mediaItem.NumTracks, Artist = mediaItem.DisplaySubtitle, Composer = mediaItem.Composer, DiscNumber = mediaItem.DiscNumber, Genre = mediaItem.Genre, ElapsedPlaybackTime = MediaManager.Position.TotalSeconds, PlaybackDuration = MediaManager.Duration.TotalSeconds, PlaybackQueueIndex = MediaManager.Queue.CurrentIndex, PlaybackQueueCount = MediaManager.Queue.Count, IsLiveStream = mediaItem.IsLive }; if (MediaManager.IsPlaying()) { nowPlayingInfo.PlaybackRate = 1f; // MediaManager.Player.Rate? } else { nowPlayingInfo.PlaybackRate = 0f; } #if __IOS__ || __TVOS__ var cover = mediaItem.DisplayImage as UIKit.UIImage; if (cover != null) { //TODO: Why is this deprecated? nowPlayingInfo.Artwork = new MPMediaItemArtwork(cover); } #endif MPNowPlayingInfoCenter.DefaultCenter.NowPlaying = nowPlayingInfo; } protected virtual MPRemoteCommandHandlerStatus SkipBackwardCommand(MPRemoteCommandEvent arg) { MediaManager.StepBackward(); return MPRemoteCommandHandlerStatus.Success; } protected virtual MPRemoteCommandHandlerStatus SkipForwardCommand(MPRemoteCommandEvent arg) { MediaManager.StepForward(); return MPRemoteCommandHandlerStatus.Success; } protected virtual MPRemoteCommandHandlerStatus StopCommand(MPRemoteCommandEvent arg) { MediaManager.Stop(); return MPRemoteCommandHandlerStatus.Success; } protected virtual MPRemoteCommandHandlerStatus SeekForwardCommand(MPRemoteCommandEvent arg) { MediaManager.StepForward(); UpdateNotification(); return MPRemoteCommandHandlerStatus.Success; } protected virtual MPRemoteCommandHandlerStatus SeekBackwardCommand(MPRemoteCommandEvent arg) { MediaManager.StepBackward(); UpdateNotification(); return MPRemoteCommandHandlerStatus.Success; } protected virtual MPRemoteCommandHandlerStatus PreviousCommand(MPRemoteCommandEvent arg) { MediaManager.PlayPrevious(); return MPRemoteCommandHandlerStatus.Success; } protected virtual MPRemoteCommandHandlerStatus PauseCommand(MPRemoteCommandEvent arg) { MediaManager.Pause(); return MPRemoteCommandHandlerStatus.Success; } protected virtual MPRemoteCommandHandlerStatus NextCommand(MPRemoteCommandEvent arg) { MediaManager.PlayNext(); return MPRemoteCommandHandlerStatus.Success; } protected virtual MPRemoteCommandHandlerStatus ShuffleCommand(MPRemoteCommandEvent arg) { MediaManager.ToggleShuffle(); return MPRemoteCommandHandlerStatus.Success; } protected virtual MPRemoteCommandHandlerStatus PlaybackPositionCommand(MPRemoteCommandEvent arg) { if (!(arg is MPChangePlaybackPositionCommandEvent e)) { return MPRemoteCommandHandlerStatus.CommandFailed; } MediaManager.SeekTo(TimeSpan.FromSeconds(e.PositionTime)); UpdateNotification(); return MPRemoteCommandHandlerStatus.Success; } protected virtual MPRemoteCommandHandlerStatus RepeatCommand(MPRemoteCommandEvent arg) { MediaManager.ToggleRepeat(); return MPRemoteCommandHandlerStatus.Success; } protected virtual MPRemoteCommandHandlerStatus PlayCommand(MPRemoteCommandEvent arg) { MediaManager.Play(); return MPRemoteCommandHandlerStatus.Success; } protected virtual MPRemoteCommandHandlerStatus PlayPauseCommand(MPRemoteCommandEvent arg) { MediaManager.PlayPause(); return MPRemoteCommandHandlerStatus.Success; } } }
36.652344
135
0.609826
[ "MIT" ]
BaseflowIT/XamarinMediaManager
MediaManager/Platforms/Apple/Notifications/NotificationManager.cs
9,385
C#
using Lucene.Net.Analysis.Util; using NUnit.Framework; using System.IO; using Reader = System.IO.TextReader; namespace Lucene.Net.Analysis.Miscellaneous { /* * 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. */ public class TestCapitalizationFilterFactory : BaseTokenStreamFactoryTestCase { [Test] public virtual void TestCapitalization() { Reader reader = new StringReader("kiTTEN"); TokenStream stream = new MockTokenizer(reader, MockTokenizer.WHITESPACE, false); stream = TokenFilterFactory("Capitalization", "keep", "and the it BIG", "onlyFirstWord", "true").Create(stream); AssertTokenStreamContents(stream, new string[] { "Kitten" }); } [Test] public virtual void TestCapitalization2() { Reader reader = new StringReader("and"); TokenStream stream = new MockTokenizer(reader, MockTokenizer.WHITESPACE, false); stream = TokenFilterFactory("Capitalization", "keep", "and the it BIG", "onlyFirstWord", "true", "forceFirstLetter", "true").Create(stream); AssertTokenStreamContents(stream, new string[] { "And" }); } /// <summary> /// first is forced, but it's not a keep word, either </summary> [Test] public virtual void TestCapitalization3() { Reader reader = new StringReader("AnD"); TokenStream stream = new MockTokenizer(reader, MockTokenizer.WHITESPACE, false); stream = TokenFilterFactory("Capitalization", "keep", "and the it BIG", "onlyFirstWord", "true", "forceFirstLetter", "true").Create(stream); AssertTokenStreamContents(stream, new string[] { "And" }); } [Test] public virtual void TestCapitalization4() { Reader reader = new StringReader("AnD"); TokenStream stream = new MockTokenizer(reader, MockTokenizer.WHITESPACE, false); stream = TokenFilterFactory("Capitalization", "keep", "and the it BIG", "onlyFirstWord", "true", "forceFirstLetter", "false").Create(stream); AssertTokenStreamContents(stream, new string[] { "And" }); } [Test] public virtual void TestCapitalization5() { Reader reader = new StringReader("big"); TokenStream stream = new MockTokenizer(reader, MockTokenizer.WHITESPACE, false); stream = TokenFilterFactory("Capitalization", "keep", "and the it BIG", "onlyFirstWord", "true", "forceFirstLetter", "true").Create(stream); AssertTokenStreamContents(stream, new string[] { "Big" }); } [Test] public virtual void TestCapitalization6() { Reader reader = new StringReader("BIG"); TokenStream stream = new MockTokenizer(reader, MockTokenizer.WHITESPACE, false); stream = TokenFilterFactory("Capitalization", "keep", "and the it BIG", "onlyFirstWord", "true", "forceFirstLetter", "true").Create(stream); AssertTokenStreamContents(stream, new string[] { "BIG" }); } [Test] public virtual void TestCapitalization7() { Reader reader = new StringReader("Hello thEre my Name is Ryan"); TokenStream stream = new MockTokenizer(reader, MockTokenizer.KEYWORD, false); stream = TokenFilterFactory("Capitalization", "keep", "and the it BIG", "onlyFirstWord", "true", "forceFirstLetter", "true").Create(stream); AssertTokenStreamContents(stream, new string[] { "Hello there my name is ryan" }); } [Test] public virtual void TestCapitalization8() { Reader reader = new StringReader("Hello thEre my Name is Ryan"); TokenStream stream = new MockTokenizer(reader, MockTokenizer.WHITESPACE, false); stream = TokenFilterFactory("Capitalization", "keep", "and the it BIG", "onlyFirstWord", "false", "forceFirstLetter", "true").Create(stream); AssertTokenStreamContents(stream, new string[] { "Hello", "There", "My", "Name", "Is", "Ryan" }); } [Test] public virtual void TestCapitalization9() { Reader reader = new StringReader("Hello thEre my Name is Ryan"); TokenStream stream = new MockTokenizer(reader, MockTokenizer.WHITESPACE, false); stream = TokenFilterFactory("Capitalization", "keep", "and the it BIG", "onlyFirstWord", "false", "minWordLength", "3", "forceFirstLetter", "true").Create(stream); AssertTokenStreamContents(stream, new string[] { "Hello", "There", "my", "Name", "is", "Ryan" }); } [Test] public virtual void TestCapitalization10() { Reader reader = new StringReader("McKinley"); TokenStream stream = new MockTokenizer(reader, MockTokenizer.WHITESPACE, false); stream = TokenFilterFactory("Capitalization", "keep", "and the it BIG", "onlyFirstWord", "false", "minWordLength", "3", "forceFirstLetter", "true").Create(stream); AssertTokenStreamContents(stream, new string[] { "Mckinley" }); } /// <summary> /// using "McK" as okPrefix </summary> [Test] public virtual void TestCapitalization11() { Reader reader = new StringReader("McKinley"); TokenStream stream = new MockTokenizer(reader, MockTokenizer.WHITESPACE, false); stream = TokenFilterFactory("Capitalization", "keep", "and the it BIG", "onlyFirstWord", "false", "minWordLength", "3", "okPrefix", "McK", "forceFirstLetter", "true").Create(stream); AssertTokenStreamContents(stream, new string[] { "McKinley" }); } /// <summary> /// test with numbers </summary> [Test] public virtual void TestCapitalization12() { Reader reader = new StringReader("1st 2nd third"); TokenStream stream = new MockTokenizer(reader, MockTokenizer.WHITESPACE, false); stream = TokenFilterFactory("Capitalization", "keep", "and the it BIG", "onlyFirstWord", "false", "minWordLength", "3", "okPrefix", "McK", "forceFirstLetter", "false").Create(stream); AssertTokenStreamContents(stream, new string[] { "1st", "2nd", "Third" }); } [Test] public virtual void TestCapitalization13() { Reader reader = new StringReader("the The the"); TokenStream stream = new MockTokenizer(reader, MockTokenizer.KEYWORD, false); stream = TokenFilterFactory("Capitalization", "keep", "and the it BIG", "onlyFirstWord", "false", "minWordLength", "3", "okPrefix", "McK", "forceFirstLetter", "true").Create(stream); AssertTokenStreamContents(stream, new string[] { "The The the" }); } [Test] public virtual void TestKeepIgnoreCase() { Reader reader = new StringReader("kiTTEN"); TokenStream stream = new MockTokenizer(reader, MockTokenizer.KEYWORD, false); stream = TokenFilterFactory("Capitalization", "keep", "kitten", "keepIgnoreCase", "true", "onlyFirstWord", "true", "forceFirstLetter", "true").Create(stream); AssertTokenStreamContents(stream, new string[] { "KiTTEN" }); } [Test] public virtual void TestKeepIgnoreCase2() { Reader reader = new StringReader("kiTTEN"); TokenStream stream = new MockTokenizer(reader, MockTokenizer.KEYWORD, false); stream = TokenFilterFactory("Capitalization", "keep", "kitten", "keepIgnoreCase", "true", "onlyFirstWord", "true", "forceFirstLetter", "false").Create(stream); AssertTokenStreamContents(stream, new string[] { "kiTTEN" }); } [Test] public virtual void TestKeepIgnoreCase3() { Reader reader = new StringReader("kiTTEN"); TokenStream stream = new MockTokenizer(reader, MockTokenizer.KEYWORD, false); stream = TokenFilterFactory("Capitalization", "keepIgnoreCase", "true", "onlyFirstWord", "true", "forceFirstLetter", "false").Create(stream); AssertTokenStreamContents(stream, new string[] { "Kitten" }); } /// <summary> /// Test CapitalizationFilterFactory's minWordLength option. /// /// This is very weird when combined with ONLY_FIRST_WORD!!! /// </summary> [Test] public virtual void TestMinWordLength() { Reader reader = new StringReader("helo testing"); TokenStream stream = new MockTokenizer(reader, MockTokenizer.WHITESPACE, false); stream = TokenFilterFactory("Capitalization", "onlyFirstWord", "true", "minWordLength", "5").Create(stream); AssertTokenStreamContents(stream, new string[] { "helo", "Testing" }); } /// <summary> /// Test CapitalizationFilterFactory's maxWordCount option with only words of 1 /// in each token (it should do nothing) /// </summary> [Test] public virtual void TestMaxWordCount() { Reader reader = new StringReader("one two three four"); TokenStream stream = new MockTokenizer(reader, MockTokenizer.WHITESPACE, false); stream = TokenFilterFactory("Capitalization", "maxWordCount", "2").Create(stream); AssertTokenStreamContents(stream, new string[] { "One", "Two", "Three", "Four" }); } /// <summary> /// Test CapitalizationFilterFactory's maxWordCount option when exceeded /// </summary> [Test] public virtual void TestMaxWordCount2() { Reader reader = new StringReader("one two three four"); TokenStream stream = new MockTokenizer(reader, MockTokenizer.KEYWORD, false); stream = TokenFilterFactory("Capitalization", "maxWordCount", "2").Create(stream); AssertTokenStreamContents(stream, new string[] { "one two three four" }); } /// <summary> /// Test CapitalizationFilterFactory's maxTokenLength option when exceeded /// /// This is weird, it is not really a max, but inclusive (look at 'is') /// </summary> [Test] public virtual void TestMaxTokenLength() { Reader reader = new StringReader("this is a test"); TokenStream stream = new MockTokenizer(reader, MockTokenizer.WHITESPACE, false); stream = TokenFilterFactory("Capitalization", "maxTokenLength", "2").Create(stream); AssertTokenStreamContents(stream, new string[] { "this", "is", "A", "test" }); } /// <summary> /// Test CapitalizationFilterFactory's forceFirstLetter option /// </summary> [Test] public virtual void TestForceFirstLetterWithKeep() { Reader reader = new StringReader("kitten"); TokenStream stream = new MockTokenizer(reader, MockTokenizer.WHITESPACE, false); stream = TokenFilterFactory("Capitalization", "keep", "kitten", "forceFirstLetter", "true").Create(stream); AssertTokenStreamContents(stream, new string[] { "Kitten" }); } /// <summary> /// Test that bogus arguments result in exception </summary> [Test] public virtual void TestBogusArguments() { try { TokenFilterFactory("Capitalization", "bogusArg", "bogusValue"); fail(); } catch (System.ArgumentException expected) { assertTrue(expected.Message.Contains("Unknown parameters")); } } /// <summary> /// Test that invalid arguments result in exception /// </summary> [Test] public virtual void TestInvalidArguments() { foreach (string arg in new string[] { "minWordLength", "maxTokenLength", "maxWordCount" }) { try { Reader reader = new StringReader("foo foobar super-duper-trooper"); TokenStream stream = new MockTokenizer(reader, MockTokenizer.WHITESPACE, false); TokenFilterFactory("Capitalization", "keep", "and the it BIG", "onlyFirstWord", "false", arg, "-3", "okPrefix", "McK", "forceFirstLetter", "true").Create(stream); fail(); } catch (System.ArgumentException expected) { assertTrue(expected.Message.Contains(arg + " must be greater than or equal to zero") || expected.Message.Contains(arg + " must be greater than zero")); } } } } }
47.614035
195
0.614149
[ "Apache-2.0" ]
BlueCurve-Team/lucenenet
src/Lucene.Net.Tests.Analysis.Common/Analysis/Miscellaneous/TestCapitalizationFilterFactory.cs
13,572
C#
/* * Swagger Petstore * * This is a sample Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using SwaggerDateConverter = IO.Swagger.Client.SwaggerDateConverter; namespace IO.Swagger.Model { /// <summary> /// Macaw /// </summary> [DataContract] public partial class Macaw : IEquatable<Macaw>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="Macaw" /> class. /// </summary> /// <param name="color">color.</param> /// <param name="singer">singer.</param> public Macaw(string color = default(string), bool? singer = default(bool?)) { this.Color = color; this.Singer = singer; } /// <summary> /// Gets or Sets Color /// </summary> [DataMember(Name="color", EmitDefaultValue=false)] public string Color { get; set; } /// <summary> /// Gets or Sets Singer /// </summary> [DataMember(Name="singer", EmitDefaultValue=false)] public bool? Singer { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class Macaw {\n"); sb.Append(" Color: ").Append(Color).Append("\n"); sb.Append(" Singer: ").Append(Singer).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as Macaw); } /// <summary> /// Returns true if Macaw instances are equal /// </summary> /// <param name="input">Instance of Macaw to be compared</param> /// <returns>Boolean</returns> public bool Equals(Macaw input) { if (input == null) return false; return ( this.Color == input.Color || (this.Color != null && this.Color.Equals(input.Color)) ) && ( this.Singer == input.Singer || (this.Singer != null && this.Singer.Equals(input.Singer)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.Color != null) hashCode = hashCode * 59 + this.Color.GetHashCode(); if (this.Singer != null) hashCode = hashCode * 59 + this.Singer.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
32.482014
176
0.546844
[ "Apache-2.0" ]
Cadcorp/swagger-codegen
samples/composed/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Macaw.cs
4,515
C#
using FreeSql.Internal.Model; using System; using System.Collections.Generic; using System.Data; using System.Linq.Expressions; using System.Threading.Tasks; namespace FreeSql.Internal.CommonProvider { abstract class Select6Provider<T1, T2, T3, T4, T5, T6> : Select0Provider<ISelect<T1, T2, T3, T4, T5, T6>, T1>, ISelect<T1, T2, T3, T4, T5, T6> where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class { public Select6Provider(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { if (_orm.CodeFirst.IsAutoSyncStructure) _orm.CodeFirst.SyncStructure(typeof(T2), typeof(T3), typeof(T4), typeof(T5), typeof(T6)); _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T2)), Alias = $"SP10b", On = null, Type = SelectTableInfoType.From }); _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T3)), Alias = $"SP10c", On = null, Type = SelectTableInfoType.From }); _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T4)), Alias = $"SP10d", On = null, Type = SelectTableInfoType.From }); _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T5)), Alias = $"SP10e", On = null, Type = SelectTableInfoType.From }); _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T6)), Alias = $"SP10f", On = null, Type = SelectTableInfoType.From }); } TMember ISelect<T1, T2, T3, T4, T5, T6>.Avg<TMember>(Expression<Func<T1, T2, T3, T4, T5, T6, TMember>> column) { if (column == null) return default(TMember); for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; return this.InternalAvg<TMember>(column?.Body); } Task<TMember> ISelect<T1, T2, T3, T4, T5, T6>.AvgAsync<TMember>(Expression<Func<T1, T2, T3, T4, T5, T6, TMember>> column) { if (column == null) return Task.FromResult(default(TMember)); for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; return this.InternalAvgAsync<TMember>(column?.Body); } ISelectGrouping<TKey, (T1, T2, T3, T4, T5, T6)> ISelect<T1, T2, T3, T4, T5, T6>.GroupBy<TKey>(Expression<Func<T1, T2, T3, T4, T5, T6, TKey>> exp) { if (exp == null) return this.InternalGroupBy<TKey, (T1, T2, T3, T4, T5, T6)>(exp?.Body); for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; return this.InternalGroupBy<TKey, (T1, T2, T3, T4, T5, T6)>(exp?.Body); } TMember ISelect<T1, T2, T3, T4, T5, T6>.Max<TMember>(Expression<Func<T1, T2, T3, T4, T5, T6, TMember>> column) { if (column == null) return default(TMember); for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; return this.InternalMax<TMember>(column?.Body); } Task<TMember> ISelect<T1, T2, T3, T4, T5, T6>.MaxAsync<TMember>(Expression<Func<T1, T2, T3, T4, T5, T6, TMember>> column) { if (column == null) return Task.FromResult(default(TMember)); for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; return this.InternalMaxAsync<TMember>(column?.Body); } TMember ISelect<T1, T2, T3, T4, T5, T6>.Min<TMember>(Expression<Func<T1, T2, T3, T4, T5, T6, TMember>> column) { if (column == null) return default(TMember); for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; return this.InternalMin<TMember>(column?.Body); } Task<TMember> ISelect<T1, T2, T3, T4, T5, T6>.MinAsync<TMember>(Expression<Func<T1, T2, T3, T4, T5, T6, TMember>> column) { if (column == null) return Task.FromResult(default(TMember)); for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; return this.InternalMinAsync<TMember>(column?.Body); } ISelect<T1, T2, T3, T4, T5, T6> ISelect<T1, T2, T3, T4, T5, T6>.OrderBy<TMember>(Expression<Func<T1, T2, T3, T4, T5, T6, TMember>> column) { if (column == null) this.InternalOrderBy(column?.Body); for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; return this.InternalOrderBy(column?.Body); } ISelect<T1, T2, T3, T4, T5, T6> ISelect<T1, T2, T3, T4, T5, T6>.OrderByDescending<TMember>(Expression<Func<T1, T2, T3, T4, T5, T6, TMember>> column) { if (column == null) this.InternalOrderBy(column?.Body); for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; return this.InternalOrderByDescending(column?.Body); } TMember ISelect<T1, T2, T3, T4, T5, T6>.Sum<TMember>(Expression<Func<T1, T2, T3, T4, T5, T6, TMember>> column) { if (column == null) this.InternalOrderBy(column?.Body); for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; return this.InternalSum<TMember>(column?.Body); } Task<TMember> ISelect<T1, T2, T3, T4, T5, T6>.SumAsync<TMember>(Expression<Func<T1, T2, T3, T4, T5, T6, TMember>> column) { if (column == null) this.InternalOrderBy(column?.Body); for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; return this.InternalSumAsync<TMember>(column?.Body); } TReturn ISelect<T1, T2, T3, T4, T5, T6>.ToAggregate<TReturn>(Expression<Func<ISelectGroupingAggregate<T1>, ISelectGroupingAggregate<T2>, ISelectGroupingAggregate<T3>, ISelectGroupingAggregate<T4>, ISelectGroupingAggregate<T5>, ISelectGroupingAggregate<T6>, TReturn>> select) { if (select == null) return default(TReturn); for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; return this.InternalToAggregate<TReturn>(select?.Body); } Task<TReturn> ISelect<T1, T2, T3, T4, T5, T6>.ToAggregateAsync<TReturn>(Expression<Func<ISelectGroupingAggregate<T1>, ISelectGroupingAggregate<T2>, ISelectGroupingAggregate<T3>, ISelectGroupingAggregate<T4>, ISelectGroupingAggregate<T5>, ISelectGroupingAggregate<T6>, TReturn>> select) { if (select == null) return Task.FromResult(default(TReturn)); for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; return this.InternalToAggregateAsync<TReturn>(select?.Body); } List<TReturn> ISelect<T1, T2, T3, T4, T5, T6>.ToList<TReturn>(Expression<Func<T1, T2, T3, T4, T5, T6, TReturn>> select) { if (select == null) return this.InternalToList<TReturn>(select?.Body); for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; return this.InternalToList<TReturn>(select?.Body); } Task<List<TReturn>> ISelect<T1, T2, T3, T4, T5, T6>.ToListAsync<TReturn>(Expression<Func<T1, T2, T3, T4, T5, T6, TReturn>> select) { if (select == null) return this.InternalToListAsync<TReturn>(select?.Body); for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; return this.InternalToListAsync<TReturn>(select?.Body); } DataTable ISelect<T1, T2, T3, T4, T5, T6>.ToDataTable<TReturn>(Expression<Func<T1, T2, T3, T4, T5, T6, TReturn>> select) { if (select == null) return this.InternalToDataTable(select?.Body); for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; return this.InternalToDataTable(select?.Body); } Task<DataTable> ISelect<T1, T2, T3, T4, T5, T6>.ToDataTableAsync<TReturn>(Expression<Func<T1, T2, T3, T4, T5, T6, TReturn>> select) { if (select == null) return this.InternalToDataTableAsync(select?.Body); for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; return this.InternalToDataTableAsync(select?.Body); } string ISelect<T1, T2, T3, T4, T5, T6>.ToSql<TReturn>(Expression<Func<T1, T2, T3, T4, T5, T6, TReturn>> select) { if (select == null) return this.InternalToSql<TReturn>(select?.Body); for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; return this.InternalToSql<TReturn>(select?.Body); } ISelect<T1, T2, T3, T4, T5, T6> ISelect<T1, T2, T3, T4, T5, T6>.Where(Expression<Func<T1, T2, T3, T4, T5, T6, bool>> exp) { if (exp == null) return this.Where(null); for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; return this.Where(_commonExpression.ExpressionWhereLambda(_tables, exp?.Body, null)); } ISelect<T1, T2, T3, T4, T5, T6> ISelect<T1, T2, T3, T4, T5, T6>.WhereIf(bool condition, Expression<Func<T1, T2, T3, T4, T5, T6, bool>> exp) { if (condition == false || exp == null) return this; for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; return this.Where(_commonExpression.ExpressionWhereLambda(_tables, exp?.Body, null)); } bool ISelect<T1, T2, T3, T4, T5, T6>.Any(Expression<Func<T1, T2, T3, T4, T5, T6, bool>> exp) { if (exp == null) return this.Any(); for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; return this.Where(_commonExpression.ExpressionWhereLambda(_tables, exp?.Body, null)).Any(); } Task<bool> ISelect<T1, T2, T3, T4, T5, T6>.AnyAsync(Expression<Func<T1, T2, T3, T4, T5, T6, bool>> exp) { if (exp == null) return this.AnyAsync(); for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; return this.Where(_commonExpression.ExpressionWhereLambda(_tables, exp?.Body, null)).AnyAsync(); } } }
60.245283
289
0.690051
[ "MIT" ]
orm-core-group/FreeSql
FreeSql/Internal/CommonProvider/SelectProvider/Select6Provider.cs
9,581
C#
using FeatureFlags.APIs.Services; namespace FeatureFlags.APIs.Models { public abstract class UserVariation { public VariationOption Variation { get; } public abstract bool SendToExperiment { get; } protected UserVariation(VariationOption variation) { Variation = variation; } } public class CachedUserVariation : UserVariation { public override bool SendToExperiment { get; } public CachedUserVariation(VariationOption variation, bool? sendToExperiment) : base(variation) { SendToExperiment = // if sendToExperiment is null, that means send all data to experiment !sendToExperiment.HasValue || sendToExperiment.Value; } } public class FeatureFlagDisabledUserVariation : UserVariation { public override bool SendToExperiment => false; public FeatureFlagDisabledUserVariation(VariationOption variation) : base(variation) { } } public class TargetedUserVariation : UserVariation { public override bool SendToExperiment { get; } public TargetedUserVariation( VariationOption variation, bool? experimentIncludeAllRules) : base(variation) { SendToExperiment = // if experimentIncludeAllRules is null, that means send all data to experiment !experimentIncludeAllRules.HasValue || experimentIncludeAllRules.Value; } } public class ConditionedUserVariation : UserVariation { public override bool SendToExperiment { get; } public ConditionedUserVariation( VariationOptionPercentageRollout percentageRollout, string userKey, bool? thisRuleIncludedInExperiment) : base(percentageRollout.ValueOption) { // if thisRuleIncludedInExperiment or this rule's experiment rollout is null // that means send all data to experiment if (!thisRuleIncludedInExperiment.HasValue || !percentageRollout.ExptRollout.HasValue) { SendToExperiment = true; return; } // this rule does not participate in experiment if (!thisRuleIncludedInExperiment.Value) { SendToExperiment = false; return; } // send to experiment by percentage var sendToExperimentPercentage = percentageRollout.ExptRollout.Value; var splittingPercentage = percentageRollout.RolloutPercentage[1] - percentageRollout.RolloutPercentage[0]; if (sendToExperimentPercentage == 0.0 || splittingPercentage == 0.0) { SendToExperiment = false; return; } var upperBound = sendToExperimentPercentage / splittingPercentage; if (upperBound > 1.0) { upperBound = 1.0; } SendToExperiment = VariationSplittingAlgorithm.IfKeyBelongsPercentage(userKey, new[] { 0.0, upperBound }); } } public class DefaultUserVariation : UserVariation { public override bool SendToExperiment { get; } public DefaultUserVariation( VariationOptionPercentageRollout percentageRollout, string userKey, bool? defaultRuleIncludedInExperiment) : base(percentageRollout.ValueOption) { // if defaultRuleIncludedInExperiment is null or the default rule's experiment rollout is null, // that means send all data to experiment if (!defaultRuleIncludedInExperiment.HasValue || !percentageRollout.ExptRollout.HasValue) { SendToExperiment = true; return; } // default rule does not participate in experiment if (!defaultRuleIncludedInExperiment.Value) { SendToExperiment = false; return; } // send to experiment by percentage var sendToExperimentPercentage = percentageRollout.ExptRollout.Value; var splittingPercentage = percentageRollout.RolloutPercentage[1] - percentageRollout.RolloutPercentage[0]; if (sendToExperimentPercentage == 0.0 || splittingPercentage == 0.0) { SendToExperiment = false; return; } var upperBound = sendToExperimentPercentage / splittingPercentage; if (upperBound > 1.0) { upperBound = 1.0; } SendToExperiment = VariationSplittingAlgorithm.IfKeyBelongsPercentage(userKey, new[] { 0.0, upperBound }); } } }
35.605839
118
0.604551
[ "Apache-2.0" ]
ZhenhangTung/feature-flags-co
FeatureFlagsCo.APIs/FeatureFlags.APIs/Models/UserVariation.cs
4,880
C#
using System; using System.Collections.Generic; using System.Text; namespace TStack.RedisExchange.Tool { public interface ISerializer { SerializerType SerializerType { get; set; } object SerializeObject<T>(T value); T DeserializeObject<T>(object value); object DeserializeObject(object value, Type type); object DeserializeObject(object value); } public enum SerializerType { String, ByteArray } }
22.857143
58
0.666667
[ "MIT" ]
ferhatcandas/TStack.RedisExchange
src/TStack.RedisExchange/Tool/ISerializer.cs
482
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.CodeDom; using System.Collections.Generic; using System.ComponentModel.Design.Serialization; using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using Moq; using Xunit; namespace System.Windows.Forms.Design.Serialization.Tests { public class CodeDomSerializerExceptionTests { public static IEnumerable<object[]> Ctor_String_CodeLinePragma_TestData() { yield return new object[] { "message", new CodeLinePragma() }; yield return new object[] { null, null }; } [Theory] [MemberData(nameof(Ctor_String_CodeLinePragma_TestData))] public void CodeDomSerializerException_Ctor_String_CodeLinePragma(string message, CodeLinePragma linePragma) { var exception = new CodeDomSerializerException(message, linePragma); Assert.NotEmpty(exception.Message); Assert.Null(exception.InnerException); Assert.Same(linePragma, exception.LinePragma); } public static IEnumerable<object[]> Ctor_Exception_CodeLinePragma_TestData() { yield return new object[] { new Exception(), new CodeLinePragma() }; yield return new object[] { null, null }; } [Theory] [MemberData(nameof(Ctor_Exception_CodeLinePragma_TestData))] public void CodeDomSerializerException_Ctor_Exception_CodeLinePragma(Exception innerException, CodeLinePragma linePragma) { var exception = new CodeDomSerializerException(innerException, linePragma); Assert.NotEmpty(exception.Message); Assert.Same(innerException, exception.InnerException); Assert.Same(linePragma, exception.LinePragma); } public static IEnumerable<object[]> Ctor_String_IDesignerSerializationManager_TestData() { var mockDesignerSerializationManager = new Mock<IDesignerSerializationManager>(MockBehavior.Strict); yield return new object[] { "message", mockDesignerSerializationManager.Object }; yield return new object[] { null, mockDesignerSerializationManager.Object }; } [Theory] [MemberData(nameof(Ctor_String_IDesignerSerializationManager_TestData))] public void CodeDomSerializerException_Ctor_String_IDesignerSerializationManager(string message, IDesignerSerializationManager manager) { var exception = new CodeDomSerializerException(message, manager); Assert.NotEmpty(exception.Message); Assert.Null(exception.InnerException); Assert.Null(exception.LinePragma); } public static IEnumerable<object[]> Ctor_Exception_IDesignerSerializationManager_TestData() { var mockDesignerSerializationManager = new Mock<IDesignerSerializationManager>(MockBehavior.Strict); yield return new object[] { new Exception(), mockDesignerSerializationManager.Object }; yield return new object[] { null, mockDesignerSerializationManager.Object }; } [Theory] [MemberData(nameof(Ctor_Exception_IDesignerSerializationManager_TestData))] public void CodeDomSerializerException_Ctor_Exception_IDesignerSerializationManager(Exception innerException, IDesignerSerializationManager manager) { var exception = new CodeDomSerializerException(innerException, manager); Assert.NotEmpty(exception.Message); Assert.Same(innerException, exception.InnerException); Assert.Null(exception.LinePragma); } [Fact] public void CodeDomSerializerException_NullManager_ThrowsArgumentNullException() { Assert.Throws<ArgumentNullException>("manager", () => new CodeDomSerializerException("message", (IDesignerSerializationManager)null)); Assert.Throws<ArgumentNullException>("manager", () => new CodeDomSerializerException(new Exception(), (IDesignerSerializationManager)null)); } [Fact] public void CodeDomSerializerException_Serialize_ThrowsSerializationException() { using (var stream = new MemoryStream()) { var formatter = new BinaryFormatter(); var exception = new CodeDomSerializerException("message", new CodeLinePragma("fileName.cs", 11)); Assert.Throws<SerializationException>(() => formatter.Serialize(stream, exception)); } } [Fact] public void CodeDomSerializerException_GetObjectData_ThrowsPlatformNotSupportedException() { var exception = new CodeDomSerializerException("message", new CodeLinePragma("fileName.cs", 11)); Assert.Throws<PlatformNotSupportedException>(() => exception.GetObjectData(null, new StreamingContext())); } } }
46.454545
156
0.697652
[ "MIT" ]
15835229565/winforms-1
src/System.Windows.Forms.Design/tests/UnitTests/System/ComponentModel/Design/Serialization/CodeDomSerializerExceptionTests.cs
5,112
C#
// This file was automatically generated and may be regenerated at any // time. To ensure any changes are retained, modify the tool with any segment/component/group/field name // or type changes. namespace Machete.HL7Schema.V26.Maps { using V26; /// <summary> /// SPM (SegmentMap) - Specimen /// </summary> public class SPMMap : HL7V26SegmentMap<SPM> { public SPMMap() { Id = "SPM"; Name = "Specimen"; Value(x => x.SetId, 1); Entity(x => x.SpecimenId, 2); Entity(x => x.SpecimenParentIds, 3); Entity(x => x.SpecimenType, 4, x => x.IsRequired()); Entity(x => x.SpecimenTypeModifier, 5); Entity(x => x.SpecimenAdditives, 6); Entity(x => x.SpecimenCollectionMethod, 7); Entity(x => x.SpecimenSourceSite, 8); Entity(x => x.SpecimenSourceSiteModifier, 9); Entity(x => x.SpecimenCollectionSite, 10); Entity(x => x.SpecimenRole, 11); Entity(x => x.SpecimenCollectionAmount, 12); Value(x => x.GroupedSpecimenCount, 13); Value(x => x.SpecimenDescription, 14); Entity(x => x.SpecimenHandlingCode, 15); Entity(x => x.SpecimenRiskCode, 16); Entity(x => x.SpecimenCollectionDateTime, 17); Value(x => x.SpecimenReceivedDateTime, 18, x => x.Converter = HL7.HL7ValueConverters.VariableLongDateTime); Value(x => x.SpecimenExpirationDateTime, 19, x => x.Converter = HL7.HL7ValueConverters.VariableLongDateTime); Value(x => x.SpecimenAvailability, 20); Entity(x => x.SpecimenRejectReason, 21); Entity(x => x.SpecimenQuality, 22); Entity(x => x.SpecimenAppropriateness, 23); Entity(x => x.SpecimenCondition, 24); Entity(x => x.SpecimenCurrentQuantity, 25); Value(x => x.NumberOfSpecimenContainers, 26); Entity(x => x.ContainerType, 27); Entity(x => x.ContainerCondition, 28); Entity(x => x.SpecimenChildRole, 29); } } }
41.843137
121
0.577788
[ "Apache-2.0" ]
AreebaAroosh/Machete
src/Machete.HL7Schema/Generated/V26/Segments/Maps/SPMMap.cs
2,134
C#
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.Management.Batch.Models { using Newtonsoft.Json; using System.Linq; /// <summary> /// Defines headers for DisableAutoScale operation. /// </summary> public partial class PoolDisableAutoScaleHeaders { /// <summary> /// Initializes a new instance of the PoolDisableAutoScaleHeaders /// class. /// </summary> public PoolDisableAutoScaleHeaders() { CustomInit(); } /// <summary> /// Initializes a new instance of the PoolDisableAutoScaleHeaders /// class. /// </summary> /// <param name="eTag">The ETag HTTP response header. This is an opaque /// string. You can use it to detect whether the resource has changed /// between requests. In particular, you can pass the ETag to one of /// the If-Match or If-None-Match headers.</param> public PoolDisableAutoScaleHeaders(string eTag = default(string)) { ETag = eTag; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets the ETag HTTP response header. This is an opaque /// string. You can use it to detect whether the resource has changed /// between requests. In particular, you can pass the ETag to one of /// the If-Match or If-None-Match headers. /// </summary> [JsonProperty(PropertyName = "ETag")] public string ETag { get; set; } } }
33.483333
90
0.621205
[ "MIT" ]
0rland0Wats0n/azure-sdk-for-net
sdk/batch/Microsoft.Azure.Management.Batch/src/Generated/Models/PoolDisableAutoScaleHeaders.cs
2,009
C#
using System; using System.Globalization; using System.Windows.Data; using System.Windows.Media; using System.Windows.Media.Imaging; namespace DeveImageOptimizerWPF.Converters { [ValueConversion(typeof(string), typeof(ImageSource))] public class StringToImageSourceConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (!(value is string valueString)) { return null; } try { //BitmapImage image = new BitmapImage(); //image.BeginInit(); //image.CacheOption = BitmapCacheOption.OnLoad; //image.UriSource = new Uri(valueString); //image.EndInit(); //return image; //imgThumbnail.Source = image; ImageSource image = BitmapFrame.Create(new Uri(valueString), BitmapCreateOptions.IgnoreImageCache, BitmapCacheOption.OnLoad); return image; } catch { return null; } } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } }
33.25641
141
0.593678
[ "MIT" ]
devedse/DeveImageOptimizerWPF
DeveImageOptimizerWPF/Converters/StringToImageSourceConverter.cs
1,299
C#
using System.Reflection; using System.Runtime.CompilerServices; 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("CSLA .NET Validation")] [assembly: AssemblyDescription("CSLA .NET Validation from 3.5.x and newer")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Marimer LLC")] [assembly: AssemblyProduct("CSLA .NET")] [assembly: AssemblyCopyright("Copyright © 2010-18 Marimer LLC")] [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("e945bbbc-7703-4fdb-bf2c-c18959f1930e")] // 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("5.0.0.0")] [assembly: AssemblyFileVersion("5.0.0.0")]
39.675676
84
0.745913
[ "MIT" ]
Crown0815/csla
Source/Csla.Validation.Net4.5/Properties/AssemblyInfo.cs
1,471
C#
using System; using NpcService.Ai.NpcType; namespace NpcService.Ai.NpcCitizen { public class SymbolMakerMarsden : Citizen { } }
14.1
45
0.723404
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
dr3dd/L2Interlude
NpcService/Ai/NpcCitizen/SymbolMakerMarsden.cs
141
C#
using System.Collections.Generic; using System.Xml.Serialization; using Newtonsoft.Json; namespace Essensoft.AspNetCore.Payment.Alipay.Response { /// <summary> /// AlipayOfflineMarketShopPublicUnbindResponse. /// </summary> public class AlipayOfflineMarketShopPublicUnbindResponse : AlipayResponse { /// <summary> /// 绑定失败的店铺ID列表,绑定失败原因可能是:a)检测到shop_id不存在;b)检测到shop_id不属于当前商户;c)该门店ID已经绑定服务窗 /// </summary> [JsonProperty("error_un_binding_shop_ids")] [XmlArray("error_un_binding_shop_ids")] [XmlArrayItem("string")] public List<string> ErrorUnBindingShopIds { get; set; } /// <summary> /// 总的基础绑定错误数 /// </summary> [JsonProperty("total_error")] [XmlElement("total_error")] public long TotalError { get; set; } /// <summary> /// 总的解除绑定成功数 /// </summary> [JsonProperty("total_success")] [XmlElement("total_success")] public long TotalSuccess { get; set; } } }
29.6
84
0.628378
[ "MIT" ]
AkonCoder/Payment
src/Essensoft.AspNetCore.Payment.Alipay/Response/AlipayOfflineMarketShopPublicUnbindResponse.cs
1,166
C#
using Anno.EventBus; using SamplesEventBus.Events; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SamplesEventBus.EventHandlers { public class MailSend : IEventHandler<Notice> { public void Handler(Notice entity) { Console.WriteLine($"Mail:你好{entity.Name},{entity.Msg}"); } } }
21.368421
68
0.697044
[ "Apache-2.0" ]
duyanming/Anno.Samples
SamplesEventBus/SamplesEventBus/EventHandlers/MailSend.cs
412
C#
using System; namespace UnityEngine.Rendering.PostProcessing { public enum GradingMode { LowDefinitionRange, HighDefinitionRange, External } public enum Tonemapper { None, // Neutral tonemapper (based off John Hable's & Jim Hejl's work) Neutral, // ACES Filmic reference tonemapper (custom approximation) ACES, // Custom artist-friendly curve Custom } [Serializable] public sealed class GradingModeParameter : ParameterOverride<GradingMode> {} [Serializable] public sealed class TonemapperParameter : ParameterOverride<Tonemapper> {} // TODO: Could use some refactoring, too much duplicated code here [Serializable] [PostProcess(typeof(ColorGradingRenderer), "Unity/Color Grading")] public sealed class ColorGrading : PostProcessEffectSettings { [DisplayName("Mode"), Tooltip("Select a color grading mode that fits your dynamic range and workflow. Use HDR if your camera is set to render in HDR and your target platform supports it. Use LDR for low-end mobiles or devices that don't support HDR. Use External if you prefer authoring a Log LUT in external softwares.")] public GradingModeParameter gradingMode = new GradingModeParameter { value = GradingMode.HighDefinitionRange }; [DisplayName("Lookup Texture"), Tooltip("")] public TextureParameter externalLut = new TextureParameter { value = null }; [DisplayName("Mode"), Tooltip("Select a tonemapping algorithm to use at the end of the color grading process.")] public TonemapperParameter tonemapper = new TonemapperParameter { value = Tonemapper.None }; [DisplayName("Toe Strength"), Range(0f, 1f), Tooltip("Affects the transition between the toe and the mid section of the curve. A value of 0 means no toe, a value of 1 means a very hard transition.")] public FloatParameter toneCurveToeStrength = new FloatParameter { value = 0f }; [DisplayName("Toe Length"), Range(0f, 1f), Tooltip("Affects how much of the dynamic range is in the toe. With a small value, the toe will be very short and quickly transition into the linear section, and with a longer value having a longer toe.")] public FloatParameter toneCurveToeLength = new FloatParameter { value = 0.5f }; [DisplayName("Shoulder Strength"), Range(0f, 1f), Tooltip("Affects the transition between the mid section and the shoulder of the curve. A value of 0 means no shoulder, a value of 1 means a very hard transition.")] public FloatParameter toneCurveShoulderStrength = new FloatParameter { value = 0f }; [DisplayName("Shoulder Length"), Min(0f), Tooltip("Affects how many F-stops (EV) to add to the dynamic range of the curve.")] public FloatParameter toneCurveShoulderLength = new FloatParameter { value = 0.5f }; [DisplayName("Shoulder Angle"), Range(0f, 1f), Tooltip("Affects how much overshoot to add to the shoulder.")] public FloatParameter toneCurveShoulderAngle = new FloatParameter { value = 0f }; [DisplayName("Gamma"), Min(0.001f), Tooltip("")] public FloatParameter toneCurveGamma = new FloatParameter { value = 1f }; [DisplayName("Lookup Texture"), Tooltip("Custom log-space lookup texture (strip format, e.g. 1024x32). EXR format is highly recommended or precision will be heavily degraded. Refer to the documentation for more information about how to create such a Lut.")] public TextureParameter logLut = new TextureParameter { value = null }; [DisplayName("Lookup Texture"), Tooltip("Custom lookup texture (strip format, e.g. 256x16) to apply before the rest of the color grading operators. If none is provided, a neutral one will be generated internally.")] public TextureParameter ldrLut = new TextureParameter { value = null }; // LDR only [DisplayName("Temperature"), Range(-100f, 100f), Tooltip("Sets the white balance to a custom color temperature.")] public FloatParameter temperature = new FloatParameter { value = 0f }; [DisplayName("Tint"), Range(-100f, 100f), Tooltip("Sets the white balance to compensate for a green or magenta tint.")] public FloatParameter tint = new FloatParameter { value = 0f }; #if UNITY_2018_1_OR_NEWER [DisplayName("Color Filter"), ColorUsage(false, true), Tooltip("Tint the render by multiplying a color.")] #else [DisplayName("Color Filter"), ColorUsage(false, true, 0f, 8f, 0.125f, 3f), Tooltip("Tint the render by multiplying a color.")] #endif public ColorParameter colorFilter = new ColorParameter { value = Color.white }; [DisplayName("Hue Shift"), Range(-180f, 180f), Tooltip("Shift the hue of all colors.")] public FloatParameter hueShift = new FloatParameter { value = 0f }; [DisplayName("Saturation"), Range(-100f, 100f), Tooltip("Pushes the intensity of all colors.")] public FloatParameter saturation = new FloatParameter { value = 0f }; [DisplayName("Brightness"), Range(-100f, 100f), Tooltip("Makes the image brighter or darker.")] public FloatParameter brightness = new FloatParameter { value = 0f }; // LDR only [DisplayName("Post-exposure (EV)"), Tooltip("Adjusts the overall exposure of the scene in EV units. This is applied after HDR effect and right before tonemapping so it won't affect previous effects in the chain.")] public FloatParameter postExposure = new FloatParameter { value = 0f }; // HDR only [DisplayName("Contrast"), Range(-100f, 100f), Tooltip("Expands or shrinks the overall range of tonal values.")] public FloatParameter contrast = new FloatParameter { value = 0f }; [DisplayName("Red"), Range(-200f, 200f), Tooltip("Modify influence of the red channel in the overall mix.")] public FloatParameter mixerRedOutRedIn = new FloatParameter { value = 100f }; [DisplayName("Green"), Range(-200f, 200f), Tooltip("Modify influence of the green channel in the overall mix.")] public FloatParameter mixerRedOutGreenIn = new FloatParameter { value = 0f }; [DisplayName("Blue"), Range(-200f, 200f), Tooltip("Modify influence of the blue channel in the overall mix.")] public FloatParameter mixerRedOutBlueIn = new FloatParameter { value = 0f }; [DisplayName("Red"), Range(-200f, 200f), Tooltip("Modify influence of the red channel in the overall mix.")] public FloatParameter mixerGreenOutRedIn = new FloatParameter { value = 0f }; [DisplayName("Green"), Range(-200f, 200f), Tooltip("Modify influence of the green channel in the overall mix.")] public FloatParameter mixerGreenOutGreenIn = new FloatParameter { value = 100f }; [DisplayName("Blue"), Range(-200f, 200f), Tooltip("Modify influence of the blue channel in the overall mix.")] public FloatParameter mixerGreenOutBlueIn = new FloatParameter { value = 0f }; [DisplayName("Red"), Range(-200f, 200f), Tooltip("Modify influence of the red channel in the overall mix.")] public FloatParameter mixerBlueOutRedIn = new FloatParameter { value = 0f }; [DisplayName("Green"), Range(-200f, 200f), Tooltip("Modify influence of the green channel in the overall mix.")] public FloatParameter mixerBlueOutGreenIn = new FloatParameter { value = 0f }; [DisplayName("Blue"), Range(-200f, 200f), Tooltip("Modify influence of the blue channel in the overall mix.")] public FloatParameter mixerBlueOutBlueIn = new FloatParameter { value = 100f }; [DisplayName("Lift"), Tooltip("Controls the darkest portions of the render."), Trackball(TrackballAttribute.Mode.Lift)] public Vector4Parameter lift = new Vector4Parameter { value = new Vector4(1f, 1f, 1f, 0f) }; [DisplayName("Gamma"), Tooltip("Power function that controls midrange tones."), Trackball(TrackballAttribute.Mode.Gamma)] public Vector4Parameter gamma = new Vector4Parameter { value = new Vector4(1f, 1f, 1f, 0f) }; [DisplayName("Gain"), Tooltip("Controls the lightest portions of the render."), Trackball(TrackballAttribute.Mode.Gain)] public Vector4Parameter gain = new Vector4Parameter { value = new Vector4(1f, 1f, 1f, 0f) }; public SplineParameter masterCurve = new SplineParameter { value = new Spline(new AnimationCurve(new Keyframe(0f, 0f, 1f, 1f), new Keyframe(1f, 1f, 1f, 1f)), 0f, false, new Vector2(0f, 1f)) }; public SplineParameter redCurve = new SplineParameter { value = new Spline(new AnimationCurve(new Keyframe(0f, 0f, 1f, 1f), new Keyframe(1f, 1f, 1f, 1f)), 0f, false, new Vector2(0f, 1f)) }; public SplineParameter greenCurve = new SplineParameter { value = new Spline(new AnimationCurve(new Keyframe(0f, 0f, 1f, 1f), new Keyframe(1f, 1f, 1f, 1f)), 0f, false, new Vector2(0f, 1f)) }; public SplineParameter blueCurve = new SplineParameter { value = new Spline(new AnimationCurve(new Keyframe(0f, 0f, 1f, 1f), new Keyframe(1f, 1f, 1f, 1f)), 0f, false, new Vector2(0f, 1f)) }; public SplineParameter hueVsHueCurve = new SplineParameter { value = new Spline(new AnimationCurve(), 0.5f, true, new Vector2(0f, 1f)) }; public SplineParameter hueVsSatCurve = new SplineParameter { value = new Spline(new AnimationCurve(), 0.5f, true, new Vector2(0f, 1f)) }; public SplineParameter satVsSatCurve = new SplineParameter { value = new Spline(new AnimationCurve(), 0.5f, false, new Vector2(0f, 1f)) }; public SplineParameter lumVsSatCurve = new SplineParameter { value = new Spline(new AnimationCurve(), 0.5f, false, new Vector2(0f, 1f)) }; public override bool IsEnabledAndSupported(PostProcessRenderContext context) { if (gradingMode.value == GradingMode.External) { if (!SystemInfo.supports3DRenderTextures || !SystemInfo.supportsComputeShaders) return false; } return enabled.value; } } public sealed class ColorGradingRenderer : PostProcessEffectRenderer<ColorGrading> { enum Pass { LutGenLDRFromScratch, LutGenLDR, LutGenHDR2D } Texture2D m_GradingCurves; readonly Color[] m_Pixels = new Color[Spline.k_Precision * 2]; // Avoids GC stress RenderTexture m_InternalLdrLut; RenderTexture m_InternalLogLut; const int k_Lut2DSize = 32; const int k_Lut3DSize = 33; readonly HableCurve m_HableCurve = new HableCurve(); public override void Render(PostProcessRenderContext context) { var gradingMode = settings.gradingMode.value; var supportComputeTex3D = SystemInfo.supports3DRenderTextures && SystemInfo.supportsComputeShaders && SystemInfo.graphicsDeviceType != GraphicsDeviceType.OpenGLCore && SystemInfo.graphicsDeviceType != GraphicsDeviceType.OpenGLES3; if (gradingMode == GradingMode.External) RenderExternalPipeline3D(context); else if (gradingMode == GradingMode.HighDefinitionRange && supportComputeTex3D) RenderHDRPipeline3D(context); else if (gradingMode == GradingMode.HighDefinitionRange) RenderHDRPipeline2D(context); else RenderLDRPipeline2D(context); } // Do color grading using an externally authored 3D lut; it requires Texture3D support and // compute shaders in case blending is required - Desktop / Consoles / Some high-end mobiles void RenderExternalPipeline3D(PostProcessRenderContext context) { var lut = settings.externalLut.value; if (lut == null) return; var uberSheet = context.uberSheet; uberSheet.EnableKeyword("COLOR_GRADING_HDR_3D"); uberSheet.properties.SetTexture(ShaderIDs.Lut3D, lut); uberSheet.properties.SetVector(ShaderIDs.Lut3D_Params, new Vector2(1f / lut.width, lut.width - 1f)); uberSheet.properties.SetFloat(ShaderIDs.PostExposure, RuntimeUtilities.Exp2(settings.postExposure.value)); context.logLut = lut; } // HDR color pipeline is rendered to a 3D lut; it requires Texture3D & compute shaders // support - Desktop / Consoles / Some high-end mobiles // TODO: Use ShaderIDs for compute once the compatible APIs go in void RenderHDRPipeline3D(PostProcessRenderContext context) { // Unfortunately because AnimationCurve doesn't implement GetHashCode and we don't have // any reliable way to figure out if a curve data is different from another one we can't // skip regenerating the Lut if nothing has changed. So it has to be done on every // frame... // It's not a very expensive operation anyway (we're talking about filling a 33x33x33 // Lut on the GPU) but every little thing helps, especially on mobile. { CheckInternalLogLut(); // Lut setup var compute = context.resources.computeShaders.lut3DBaker; int kernel = 0; switch (settings.tonemapper.value) { case Tonemapper.None: kernel = compute.FindKernel("KGenLut3D_NoTonemap"); break; case Tonemapper.Neutral: kernel = compute.FindKernel("KGenLut3D_NeutralTonemap"); break; case Tonemapper.ACES: kernel = compute.FindKernel("KGenLut3D_AcesTonemap"); break; case Tonemapper.Custom: kernel = compute.FindKernel("KGenLut3D_CustomTonemap"); break; } int groupSizeXY = Mathf.CeilToInt(k_Lut3DSize / 8f); int groupSizeZ = Mathf.CeilToInt(k_Lut3DSize / (RuntimeUtilities.isAndroidOpenGL ? 2f : 8f)); var cmd = context.command; cmd.SetComputeTextureParam(compute, kernel, "_Output", m_InternalLogLut); cmd.SetComputeVectorParam(compute, "_Size", new Vector4(k_Lut3DSize, 1f / (k_Lut3DSize - 1f), 0f, 0f)); var colorBalance = ColorUtilities.ComputeColorBalance(settings.temperature.value, settings.tint.value); cmd.SetComputeVectorParam(compute, "_ColorBalance", colorBalance); cmd.SetComputeVectorParam(compute, "_ColorFilter", settings.colorFilter.value); float hue = settings.hueShift.value / 360f; // Remap to [-0.5;0.5] float sat = settings.saturation.value / 100f + 1f; // Remap to [0;2] float con = settings.contrast.value / 100f + 1f; // Remap to [0;2] cmd.SetComputeVectorParam(compute, "_HueSatCon", new Vector4(hue, sat, con, 0f)); var channelMixerR = new Vector4(settings.mixerRedOutRedIn, settings.mixerRedOutGreenIn, settings.mixerRedOutBlueIn, 0f); var channelMixerG = new Vector4(settings.mixerGreenOutRedIn, settings.mixerGreenOutGreenIn, settings.mixerGreenOutBlueIn, 0f); var channelMixerB = new Vector4(settings.mixerBlueOutRedIn, settings.mixerBlueOutGreenIn, settings.mixerBlueOutBlueIn, 0f); cmd.SetComputeVectorParam(compute, "_ChannelMixerRed", channelMixerR / 100f); // Remap to [-2;2] cmd.SetComputeVectorParam(compute, "_ChannelMixerGreen", channelMixerG / 100f); cmd.SetComputeVectorParam(compute, "_ChannelMixerBlue", channelMixerB / 100f); var lift = ColorUtilities.ColorToLift(settings.lift.value * 0.2f); var gain = ColorUtilities.ColorToGain(settings.gain.value * 0.8f); var invgamma = ColorUtilities.ColorToInverseGamma(settings.gamma.value * 0.8f); cmd.SetComputeVectorParam(compute, "_Lift", new Vector4(lift.x, lift.y, lift.z, 0f)); cmd.SetComputeVectorParam(compute, "_InvGamma", new Vector4(invgamma.x, invgamma.y, invgamma.z, 0f)); cmd.SetComputeVectorParam(compute, "_Gain", new Vector4(gain.x, gain.y, gain.z, 0f)); cmd.SetComputeTextureParam(compute, kernel, "_Curves", GetCurveTexture(true)); if (settings.tonemapper.value == Tonemapper.Custom) { m_HableCurve.Init( settings.toneCurveToeStrength.value, settings.toneCurveToeLength.value, settings.toneCurveShoulderStrength.value, settings.toneCurveShoulderLength.value, settings.toneCurveShoulderAngle.value, settings.toneCurveGamma.value ); cmd.SetComputeVectorParam(compute, "_CustomToneCurve", m_HableCurve.uniforms.curve); cmd.SetComputeVectorParam(compute, "_ToeSegmentA", m_HableCurve.uniforms.toeSegmentA); cmd.SetComputeVectorParam(compute, "_ToeSegmentB", m_HableCurve.uniforms.toeSegmentB); cmd.SetComputeVectorParam(compute, "_MidSegmentA", m_HableCurve.uniforms.midSegmentA); cmd.SetComputeVectorParam(compute, "_MidSegmentB", m_HableCurve.uniforms.midSegmentB); cmd.SetComputeVectorParam(compute, "_ShoSegmentA", m_HableCurve.uniforms.shoSegmentA); cmd.SetComputeVectorParam(compute, "_ShoSegmentB", m_HableCurve.uniforms.shoSegmentB); } // Generate the lut context.command.BeginSample("HdrColorGradingLut3D"); cmd.DispatchCompute(compute, kernel, groupSizeXY, groupSizeXY, groupSizeZ); context.command.EndSample("HdrColorGradingLut3D"); } var lut = m_InternalLogLut; var uberSheet = context.uberSheet; uberSheet.EnableKeyword("COLOR_GRADING_HDR_3D"); uberSheet.properties.SetTexture(ShaderIDs.Lut3D, lut); uberSheet.properties.SetVector(ShaderIDs.Lut3D_Params, new Vector2(1f / lut.width, lut.width - 1f)); uberSheet.properties.SetFloat(ShaderIDs.PostExposure, RuntimeUtilities.Exp2(settings.postExposure.value)); context.logLut = lut; } // HDR color pipeline is rendered to a 2D strip lut (works on HDR platforms without compute // and 3D texture support). Precision is sliiiiiiightly lower than when using a 3D texture // LUT (33^3 -> 32^3) but most of the time it's imperceptible. void RenderHDRPipeline2D(PostProcessRenderContext context) { // For the same reasons as in RenderHDRPipeline3D, regen LUT on evey frame { CheckInternalStripLut(); // Lut setup var lutSheet = context.propertySheets.Get(context.resources.shaders.lut2DBaker); lutSheet.ClearKeywords(); lutSheet.properties.SetVector(ShaderIDs.Lut2D_Params, new Vector4(k_Lut2DSize, 0.5f / (k_Lut2DSize * k_Lut2DSize), 0.5f / k_Lut2DSize, k_Lut2DSize / (k_Lut2DSize - 1f))); var colorBalance = ColorUtilities.ComputeColorBalance(settings.temperature.value, settings.tint.value); lutSheet.properties.SetVector(ShaderIDs.ColorBalance, colorBalance); lutSheet.properties.SetVector(ShaderIDs.ColorFilter, settings.colorFilter.value); float hue = settings.hueShift.value / 360f; // Remap to [-0.5;0.5] float sat = settings.saturation.value / 100f + 1f; // Remap to [0;2] float con = settings.contrast.value / 100f + 1f; // Remap to [0;2] lutSheet.properties.SetVector(ShaderIDs.HueSatCon, new Vector3(hue, sat, con)); var channelMixerR = new Vector3(settings.mixerRedOutRedIn, settings.mixerRedOutGreenIn, settings.mixerRedOutBlueIn); var channelMixerG = new Vector3(settings.mixerGreenOutRedIn, settings.mixerGreenOutGreenIn, settings.mixerGreenOutBlueIn); var channelMixerB = new Vector3(settings.mixerBlueOutRedIn, settings.mixerBlueOutGreenIn, settings.mixerBlueOutBlueIn); lutSheet.properties.SetVector(ShaderIDs.ChannelMixerRed, channelMixerR / 100f); // Remap to [-2;2] lutSheet.properties.SetVector(ShaderIDs.ChannelMixerGreen, channelMixerG / 100f); lutSheet.properties.SetVector(ShaderIDs.ChannelMixerBlue, channelMixerB / 100f); var lift = ColorUtilities.ColorToLift(settings.lift.value * 0.2f); var gain = ColorUtilities.ColorToGain(settings.gain.value * 0.8f); var invgamma = ColorUtilities.ColorToInverseGamma(settings.gamma.value * 0.8f); lutSheet.properties.SetVector(ShaderIDs.Lift, lift); lutSheet.properties.SetVector(ShaderIDs.InvGamma, invgamma); lutSheet.properties.SetVector(ShaderIDs.Gain, gain); lutSheet.properties.SetTexture(ShaderIDs.Curves, GetCurveTexture(false)); var tonemapper = settings.tonemapper.value; if (tonemapper == Tonemapper.Custom) { lutSheet.EnableKeyword("TONEMAPPING_CUSTOM"); m_HableCurve.Init( settings.toneCurveToeStrength.value, settings.toneCurveToeLength.value, settings.toneCurveShoulderStrength.value, settings.toneCurveShoulderLength.value, settings.toneCurveShoulderAngle.value, settings.toneCurveGamma.value ); lutSheet.properties.SetVector(ShaderIDs.CustomToneCurve, m_HableCurve.uniforms.curve); lutSheet.properties.SetVector(ShaderIDs.ToeSegmentA, m_HableCurve.uniforms.toeSegmentA); lutSheet.properties.SetVector(ShaderIDs.ToeSegmentB, m_HableCurve.uniforms.toeSegmentB); lutSheet.properties.SetVector(ShaderIDs.MidSegmentA, m_HableCurve.uniforms.midSegmentA); lutSheet.properties.SetVector(ShaderIDs.MidSegmentB, m_HableCurve.uniforms.midSegmentB); lutSheet.properties.SetVector(ShaderIDs.ShoSegmentA, m_HableCurve.uniforms.shoSegmentA); lutSheet.properties.SetVector(ShaderIDs.ShoSegmentB, m_HableCurve.uniforms.shoSegmentB); } else if (tonemapper == Tonemapper.ACES) lutSheet.EnableKeyword("TONEMAPPING_ACES"); else if (tonemapper == Tonemapper.Neutral) lutSheet.EnableKeyword("TONEMAPPING_NEUTRAL"); // Generate the lut context.command.BeginSample("HdrColorGradingLut2D"); context.command.BlitFullscreenTriangle(BuiltinRenderTextureType.None, m_InternalLdrLut, lutSheet, (int)Pass.LutGenHDR2D); context.command.EndSample("HdrColorGradingLut2D"); } var lut = m_InternalLdrLut; var uberSheet = context.uberSheet; uberSheet.EnableKeyword("COLOR_GRADING_HDR_2D"); uberSheet.properties.SetVector(ShaderIDs.Lut2D_Params, new Vector3(1f / lut.width, 1f / lut.height, lut.height - 1f)); uberSheet.properties.SetTexture(ShaderIDs.Lut2D, lut); uberSheet.properties.SetFloat(ShaderIDs.PostExposure, RuntimeUtilities.Exp2(settings.postExposure.value)); } // LDR color pipeline is rendered to a 2D strip lut (works on every platform) void RenderLDRPipeline2D(PostProcessRenderContext context) { // For the same reasons as in RenderHDRPipeline3D, regen LUT on evey frame { CheckInternalStripLut(); // Lut setup var lutSheet = context.propertySheets.Get(context.resources.shaders.lut2DBaker); lutSheet.ClearKeywords(); lutSheet.properties.SetVector(ShaderIDs.Lut2D_Params, new Vector4(k_Lut2DSize, 0.5f / (k_Lut2DSize * k_Lut2DSize), 0.5f / k_Lut2DSize, k_Lut2DSize / (k_Lut2DSize - 1f))); var colorBalance = ColorUtilities.ComputeColorBalance(settings.temperature.value, settings.tint.value); lutSheet.properties.SetVector(ShaderIDs.ColorBalance, colorBalance); lutSheet.properties.SetVector(ShaderIDs.ColorFilter, settings.colorFilter.value); float hue = settings.hueShift.value / 360f; // Remap to [-0.5;0.5] float sat = settings.saturation.value / 100f + 1f; // Remap to [0;2] float con = settings.contrast.value / 100f + 1f; // Remap to [0;2] lutSheet.properties.SetVector(ShaderIDs.HueSatCon, new Vector3(hue, sat, con)); var channelMixerR = new Vector3(settings.mixerRedOutRedIn, settings.mixerRedOutGreenIn, settings.mixerRedOutBlueIn); var channelMixerG = new Vector3(settings.mixerGreenOutRedIn, settings.mixerGreenOutGreenIn, settings.mixerGreenOutBlueIn); var channelMixerB = new Vector3(settings.mixerBlueOutRedIn, settings.mixerBlueOutGreenIn, settings.mixerBlueOutBlueIn); lutSheet.properties.SetVector(ShaderIDs.ChannelMixerRed, channelMixerR / 100f); // Remap to [-2;2] lutSheet.properties.SetVector(ShaderIDs.ChannelMixerGreen, channelMixerG / 100f); lutSheet.properties.SetVector(ShaderIDs.ChannelMixerBlue, channelMixerB / 100f); var lift = ColorUtilities.ColorToLift(settings.lift.value); var gain = ColorUtilities.ColorToGain(settings.gain.value); var invgamma = ColorUtilities.ColorToInverseGamma(settings.gamma.value); lutSheet.properties.SetVector(ShaderIDs.Lift, lift); lutSheet.properties.SetVector(ShaderIDs.InvGamma, invgamma); lutSheet.properties.SetVector(ShaderIDs.Gain, gain); lutSheet.properties.SetFloat(ShaderIDs.Brightness, (settings.brightness.value + 100f) / 100f); lutSheet.properties.SetTexture(ShaderIDs.Curves, GetCurveTexture(false)); // Generate the lut context.command.BeginSample("LdrColorGradingLut2D"); var userLut = settings.ldrLut.value; if (userLut == null) context.command.BlitFullscreenTriangle(BuiltinRenderTextureType.None, m_InternalLdrLut, lutSheet, (int)Pass.LutGenLDRFromScratch); else context.command.BlitFullscreenTriangle(userLut, m_InternalLdrLut, lutSheet, (int)Pass.LutGenLDR); context.command.EndSample("LdrColorGradingLut2D"); } var lut = m_InternalLdrLut; var uberSheet = context.uberSheet; uberSheet.EnableKeyword("COLOR_GRADING_LDR_2D"); uberSheet.properties.SetVector(ShaderIDs.Lut2D_Params, new Vector3(1f / lut.width, 1f / lut.height, lut.height - 1f)); uberSheet.properties.SetTexture(ShaderIDs.Lut2D, lut); } void CheckInternalLogLut() { // Check internal lut state, (re)create it if needed if (m_InternalLogLut == null || !m_InternalLogLut.IsCreated()) { RuntimeUtilities.Destroy(m_InternalLogLut); var format = GetLutFormat(); m_InternalLogLut = new RenderTexture(k_Lut3DSize, k_Lut3DSize, 0, format, RenderTextureReadWrite.Linear) { name = "Color Grading Log Lut", dimension = TextureDimension.Tex3D, hideFlags = HideFlags.DontSave, filterMode = FilterMode.Bilinear, wrapMode = TextureWrapMode.Clamp, anisoLevel = 0, enableRandomWrite = true, volumeDepth = k_Lut3DSize, autoGenerateMips = false, useMipMap = false }; m_InternalLogLut.Create(); } } void CheckInternalStripLut() { // Check internal lut state, (re)create it if needed if (m_InternalLdrLut == null || !m_InternalLdrLut.IsCreated()) { RuntimeUtilities.Destroy(m_InternalLdrLut); var format = GetLutFormat(); m_InternalLdrLut = new RenderTexture(k_Lut2DSize * k_Lut2DSize, k_Lut2DSize, 0, format, RenderTextureReadWrite.Linear) { name = "Color Grading Strip Lut", hideFlags = HideFlags.DontSave, filterMode = FilterMode.Bilinear, wrapMode = TextureWrapMode.Clamp, anisoLevel = 0, autoGenerateMips = false, useMipMap = false }; m_InternalLdrLut.Create(); } } Texture2D GetCurveTexture(bool hdr) { if (m_GradingCurves == null) { var format = GetCurveFormat(); m_GradingCurves = new Texture2D(Spline.k_Precision, 2, format, false, true) { name = "Internal Curves Texture", hideFlags = HideFlags.DontSave, anisoLevel = 0, wrapMode = TextureWrapMode.Clamp, filterMode = FilterMode.Bilinear }; } var hueVsHueCurve = settings.hueVsHueCurve.value; var hueVsSatCurve = settings.hueVsSatCurve.value; var satVsSatCurve = settings.satVsSatCurve.value; var lumVsSatCurve = settings.lumVsSatCurve.value; var masterCurve = settings.masterCurve.value; var redCurve = settings.redCurve.value; var greenCurve = settings.greenCurve.value; var blueCurve = settings.blueCurve.value; var pixels = m_Pixels; for (int i = 0; i < Spline.k_Precision; i++) { // Secondary/VS curves float x = hueVsHueCurve.cachedData[i]; float y = hueVsSatCurve.cachedData[i]; float z = satVsSatCurve.cachedData[i]; float w = lumVsSatCurve.cachedData[i]; pixels[i] = new Color(x, y, z, w); // YRGB if (!hdr) { float m = masterCurve.cachedData[i]; float r = redCurve.cachedData[i]; float g = greenCurve.cachedData[i]; float b = blueCurve.cachedData[i]; pixels[i + Spline.k_Precision] = new Color(r, g, b, m); } } m_GradingCurves.SetPixels(pixels); m_GradingCurves.Apply(false, false); return m_GradingCurves; } static RenderTextureFormat GetLutFormat() { // Use ARGBHalf if possible, fallback on ARGB2101010 and ARGB32 otherwise var format = RenderTextureFormat.ARGBHalf; if (!SystemInfo.SupportsRenderTextureFormat(format)) { format = RenderTextureFormat.ARGB2101010; // Note that using a log lut in ARGB32 is a *very* bad idea but we need it for // compatibility reasons (else if a platform doesn't support one of the previous // format it'll output a black screen, or worse will segfault on the user). if (!SystemInfo.SupportsRenderTextureFormat(format)) format = RenderTextureFormat.ARGB32; } return format; } static TextureFormat GetCurveFormat() { // Use RGBAHalf if possible, fallback on ARGB32 otherwise var format = TextureFormat.RGBAHalf; if (!SystemInfo.SupportsTextureFormat(format)) format = TextureFormat.ARGB32; return format; } public override void Release() { RuntimeUtilities.Destroy(m_InternalLdrLut); m_InternalLdrLut = null; RuntimeUtilities.Destroy(m_InternalLogLut); m_InternalLogLut = null; RuntimeUtilities.Destroy(m_GradingCurves); m_GradingCurves = null; } } }
56.953846
331
0.627199
[ "Apache-2.0" ]
an-garcia/GameKit2D
Assets/2DGamekit/Utilities/PostProcessing/Runtime/Effects/ColorGrading.cs
33,318
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. 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://aws.amazon.com/apache2.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. */ /* * Do not modify this file. This file is generated from the rds-2014-10-31.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.RDS.Model { /// <summary> /// Container for the parameters to the AuthorizeDBSecurityGroupIngress operation. /// Enables ingress to a DBSecurityGroup using one of two forms of authorization. First, /// EC2 or VPC security groups can be added to the DBSecurityGroup if the application /// using the database is running on EC2 or VPC instances. Second, IP ranges are available /// if the application accessing your database is running on the Internet. Required parameters /// for this API are one of CIDR range, EC2SecurityGroupId for VPC, or (EC2SecurityGroupOwnerId /// and either EC2SecurityGroupName or EC2SecurityGroupId for non-VPC). /// /// <note> /// <para> /// You can't authorize ingress from an EC2 security group in one AWS Region to an Amazon /// RDS DB instance in another. You can't authorize ingress from a VPC security group /// in one VPC to an Amazon RDS DB instance in another. /// </para> /// </note> /// <para> /// For an overview of CIDR ranges, go to the <a href="http://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing">Wikipedia /// Tutorial</a>. /// </para> /// </summary> public partial class AuthorizeDBSecurityGroupIngressRequest : AmazonRDSRequest { private string _cidrip; private string _dbSecurityGroupName; private string _ec2SecurityGroupId; private string _ec2SecurityGroupName; private string _ec2SecurityGroupOwnerId; /// <summary> /// Empty constructor used to set properties independently even when a simple constructor is available /// </summary> public AuthorizeDBSecurityGroupIngressRequest() { } /// <summary> /// Instantiates AuthorizeDBSecurityGroupIngressRequest with the parameterized properties /// </summary> /// <param name="dbSecurityGroupName">The name of the DB security group to add authorization to.</param> public AuthorizeDBSecurityGroupIngressRequest(string dbSecurityGroupName) { _dbSecurityGroupName = dbSecurityGroupName; } /// <summary> /// Gets and sets the property CIDRIP. /// <para> /// The IP range to authorize. /// </para> /// </summary> public string CIDRIP { get { return this._cidrip; } set { this._cidrip = value; } } // Check to see if CIDRIP property is set internal bool IsSetCIDRIP() { return this._cidrip != null; } /// <summary> /// Gets and sets the property DBSecurityGroupName. /// <para> /// The name of the DB security group to add authorization to. /// </para> /// </summary> [AWSProperty(Required=true)] public string DBSecurityGroupName { get { return this._dbSecurityGroupName; } set { this._dbSecurityGroupName = value; } } // Check to see if DBSecurityGroupName property is set internal bool IsSetDBSecurityGroupName() { return this._dbSecurityGroupName != null; } /// <summary> /// Gets and sets the property EC2SecurityGroupId. /// <para> /// Id of the EC2 security group to authorize. For VPC DB security groups, <code>EC2SecurityGroupId</code> /// must be provided. Otherwise, <code>EC2SecurityGroupOwnerId</code> and either <code>EC2SecurityGroupName</code> /// or <code>EC2SecurityGroupId</code> must be provided. /// </para> /// </summary> public string EC2SecurityGroupId { get { return this._ec2SecurityGroupId; } set { this._ec2SecurityGroupId = value; } } // Check to see if EC2SecurityGroupId property is set internal bool IsSetEC2SecurityGroupId() { return this._ec2SecurityGroupId != null; } /// <summary> /// Gets and sets the property EC2SecurityGroupName. /// <para> /// Name of the EC2 security group to authorize. For VPC DB security groups, <code>EC2SecurityGroupId</code> /// must be provided. Otherwise, <code>EC2SecurityGroupOwnerId</code> and either <code>EC2SecurityGroupName</code> /// or <code>EC2SecurityGroupId</code> must be provided. /// </para> /// </summary> public string EC2SecurityGroupName { get { return this._ec2SecurityGroupName; } set { this._ec2SecurityGroupName = value; } } // Check to see if EC2SecurityGroupName property is set internal bool IsSetEC2SecurityGroupName() { return this._ec2SecurityGroupName != null; } /// <summary> /// Gets and sets the property EC2SecurityGroupOwnerId. /// <para> /// AWS account number of the owner of the EC2 security group specified in the <code>EC2SecurityGroupName</code> /// parameter. The AWS access key ID isn't an acceptable value. For VPC DB security groups, /// <code>EC2SecurityGroupId</code> must be provided. Otherwise, <code>EC2SecurityGroupOwnerId</code> /// and either <code>EC2SecurityGroupName</code> or <code>EC2SecurityGroupId</code> must /// be provided. /// </para> /// </summary> public string EC2SecurityGroupOwnerId { get { return this._ec2SecurityGroupOwnerId; } set { this._ec2SecurityGroupOwnerId = value; } } // Check to see if EC2SecurityGroupOwnerId property is set internal bool IsSetEC2SecurityGroupOwnerId() { return this._ec2SecurityGroupOwnerId != null; } } }
38.58046
129
0.638463
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/RDS/Generated/Model/AuthorizeDBSecurityGroupIngressRequest.cs
6,713
C#
using Backtrace.Unity.Model; using System.Collections.Generic; namespace Backtrace.Unity.Runtime.Native { internal static class NativeClientFactory { internal static INativeClient CreateNativeClient(BacktraceConfiguration configuration, string gameObjectName, IDictionary<string, string> attributes, ICollection<string> attachments) { #if UNITY_STANDALONE_WIN return new Windows.NativeClient(gameObjectName, configuration, attributes, attachments); #elif UNITY_ANDROID return new Android.NativeClient(gameObjectName, configuration, attributes, attachments); #elif UNITY_IOS return new iOS.NativeClient(configuration, attributes, attachments); #else return null; #endif } } }
34.590909
190
0.7477
[ "MIT" ]
anchan828/backtrace-unity
Runtime/Native/NativeClientFactory.cs
763
C#
using JBP.ConnectionUtilities; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Sockets; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; namespace JBP.NetworkUtilities.Client { public class Client { private ManualResetEvent connectDone = new ManualResetEvent(false); private string recordType { get; set; } private TcpClient clientSocket = new TcpClient(); public Client(string _recordType) { recordType = _recordType; } /// <summary> /// Establish a connection with the server /// </summary> /// <param name="_ipAddress"></param> /// <param name="port"></param> /// <param name="_msgCallBack"></param> public void ConnectServer(IPAddress _ipAddress, int port, Action<string, string> _msgCallBack, [Optional]CancellationToken _cancelToken) { _msgCallBack(string.Format("<LOG>Attempting to connect {0}:{1}...", _ipAddress.ToString(), port.ToString()), "Green"); int _retryCount = 0; while (true) { try { if (_cancelToken != null && _cancelToken.IsCancellationRequested) break; clientSocket.Connect(_ipAddress, port); ConnectionUtility.WriteClientStream(clientSocket, recordType); _msgCallBack("<LOG>Connection established with server", "Green"); ThreadPool.QueueUserWorkItem(o => readStream(clientSocket, _msgCallBack, _cancelToken)); connectDone.WaitOne(); break; } catch (Exception ex) { _retryCount++; if (_retryCount > 10) { _msgCallBack("<LOG>Failed to connect the server specified, Retrying...", "Red"); _retryCount = 0; } } } } /// <summary> /// Read the record from server stream /// </summary> /// <param name="clientSocket">Connected Socket</param> /// <param name="_msgCallBack">Callback function on new message</param> public void readStream(object clientSocket, Action<string, string> _msgCallBack, [Optional]CancellationToken _cancelToken) { _msgCallBack("<LOG>Fetching Records...", recordType); try { while (true) { if (_cancelToken != null && _cancelToken.IsCancellationRequested) { connectDone.Set(); ((TcpClient)clientSocket).Close(); return; } var msg = ConnectionUtility.ReadClientStream((TcpClient)clientSocket); if (!string.IsNullOrEmpty(msg)) { _msgCallBack(msg, recordType); ConnectionUtility.WriteClientStream((TcpClient)clientSocket, "<ACK>"); } else break; } _msgCallBack(((TcpClient)clientSocket).Connected ? "<LOG>Finished Processing records." : "<LOG>Connection Terminated.", recordType); } catch (Exception ex) { } finally{ connectDone.Set(); connectDone.Reset(); } } } }
36.420561
149
0.49089
[ "BSD-2-Clause" ]
jamshi/MultiThreading-with-client-server-c-
NetworkUtilities/Client.cs
3,899
C#
using NUnit.Framework; using System; using WSharp.Compiler.Symbols; namespace WSharp.Compiler.Tests.Symbols { public static class TypeSymbolTests { [Test] public static void LookupUnknownTypeSymbol() => Assert.That(TypeSymbol.Lookup(Guid.NewGuid().ToString()), Is.Null); [TestCase(TypeSymbol.BooleanName)] [TestCase(TypeSymbol.ErrorName)] [TestCase(TypeSymbol.IntegerName)] [TestCase(TypeSymbol.StringName)] [TestCase(TypeSymbol.VoidName)] public static void VerifyTypeSymbol(string typeName) { var symbol = TypeSymbol.Lookup(typeName)!; Assert.Multiple(() => { Assert.That(symbol.Name, Is.EqualTo(typeName), nameof(symbol.Name)); Assert.That(symbol.Kind, Is.EqualTo(SymbolKind.Type), nameof(symbol.Kind)); }); } } }
26.413793
79
0.732376
[ "MIT" ]
JasonBock/WSharp
WSharp.Compiler.Tests/Symbols/TypeSymbolTests.cs
768
C#
using System.Data; using System.Data.Common; namespace Zephyr.Data.Providers.Common { internal class ConnectionFactory { public static IDbConnection CreateConnection(string providerName, string connectionString) { var factory = DbProviderFactories.GetFactory(providerName); var connection = factory.CreateConnection(); connection.ConnectionString = connectionString; return connection; } } }
23.111111
92
0.783654
[ "MIT" ]
zhupangithub/WEBERP
Code/Zephyr.Net/Zephyr.Data/Providers/Common/ConnectionFactory.cs
418
C#
#region Copyright (C) 2017-2020 Yaroslav Tatarenko // Copyright (C) 2017-2020 Yaroslav Tatarenko // This product uses MediaInfo library, Copyright (c) 2002-2020 MediaArea.net SARL. // https://mediaarea.net #endregion using System.Diagnostics; using Xunit; namespace MediaInfo.Wrapper.Tests { public class FactInDebugOnlyAttribute : FactAttribute { public FactInDebugOnlyAttribute() { if (!Debugger.IsAttached) { Skip = "Only running in interactive mode."; } } } }
20.56
84
0.698444
[ "BSD-2-Clause" ]
bejhanj/MP-MediaInfo
MediaInfo.Wrapper.Tests/FactInDebugOnlyAttribute.cs
516
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. 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://aws.amazon.com/apache2.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. */ /* * Do not modify this file. This file is generated from the organizations-2016-11-28.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.Organizations.Model { /// <summary> /// Container for the parameters to the AcceptHandshake operation. /// Sends a response to the originator of a handshake agreeing to the action proposed /// by the handshake request. /// /// /// <para> /// This operation can be called only by the following principals when they also have /// the relevant IAM permissions: /// </para> /// <ul> <li> /// <para> /// <b>Invitation to join</b> or <b>Approve all features request</b> handshakes: only /// a principal from the member account. /// </para> /// /// <para> /// The user who calls the API for an invitation to join must have the <code>organizations:AcceptHandshake</code> /// permission. If you enabled all features in the organization, then the user must also /// have the <code>iam:CreateServiceLinkedRole</code> permission so that Organizations /// can create the required service-linked role named <i>AWSServiceRoleForOrganizations</i>. /// For more information, see <a href="http://docs.aws.amazon.com/organizations/latest/userguide/orgs_integration_services.html#orgs_integration_service-linked-roles">AWS /// Organizations and Service-Linked Roles</a> in the <i>AWS Organizations User Guide</i>. /// </para> /// </li> <li> /// <para> /// <b>Enable all features final confirmation</b> handshake: only a principal from the /// master account. /// </para> /// /// <para> /// For more information about invitations, see <a href="http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_invites.html">Inviting /// an AWS Account to Join Your Organization</a> in the <i>AWS Organizations User Guide</i>. /// For more information about requests to enable all features in the organization, see /// <a href="http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_org_support-all-features.html">Enabling /// All Features in Your Organization</a> in the <i>AWS Organizations User Guide</i>. /// </para> /// </li> </ul> /// <para> /// After you accept a handshake, it continues to appear in the results of relevant APIs /// for only 30 days. After that it is deleted. /// </para> /// </summary> public partial class AcceptHandshakeRequest : AmazonOrganizationsRequest { private string _handshakeId; /// <summary> /// Gets and sets the property HandshakeId. /// <para> /// The unique identifier (ID) of the handshake that you want to accept. /// </para> /// /// <para> /// The <a href="http://wikipedia.org/wiki/regex">regex pattern</a> for handshake ID string /// requires "h-" followed by from 8 to 32 lower-case letters or digits. /// </para> /// </summary> public string HandshakeId { get { return this._handshakeId; } set { this._handshakeId = value; } } // Check to see if HandshakeId property is set internal bool IsSetHandshakeId() { return this._handshakeId != null; } } }
40.534653
174
0.658769
[ "Apache-2.0" ]
Bio2hazard/aws-sdk-net
sdk/src/Services/Organizations/Generated/Model/AcceptHandshakeRequest.cs
4,094
C#
using System.Reactive.Linq; using Avalonia; using BeUtl.Framework.Services; using Microsoft.Extensions.DependencyInjection; using Reactive.Bindings; using S = BeUtl.Language.StringResources; namespace BeUtl.ViewModels.Dialogs; public sealed class CreateNewProjectViewModel { public CreateNewProjectViewModel() { Location.Value = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); Name.Value = GenProjectName(Location.Value); Name.SetValidateNotifyError(n => { if (Directory.Exists(Path.Combine(Location.Value, n))) { return S.Warning.ItAlreadyExists; } else { return null; } }); Location.Subscribe(_ => Name.ForceValidate()); Size.SetValidateNotifyError(s => { if (s.Width <= 0 || s.Height <= 0) { return S.Warning.ValueLessThanOrEqualToZero; } else { return null; } }); FrameRate.SetValidateNotifyError(n => { if (n <= 0) { return S.Warning.ValueLessThanOrEqualToZero; } else { return null; } }); SampleRate.SetValidateNotifyError(n => { if (n <= 0) { return S.Warning.ValueLessThanOrEqualToZero; } else { return null; } }); CanCreate = Name.CombineLatest(Location, Size, FrameRate, SampleRate) .Select(t => { (string name, string location, PixelSize size, int framerate, int samplerate) = t; return !Directory.Exists(Path.Combine(location, name)) && size.Width > 0 && size.Height > 0 && framerate > 0 && samplerate > 0; }) .ToReadOnlyReactivePropertySlim(); Create = new ReactiveCommand(CanCreate); Create.Subscribe(() => { IProjectService service = ServiceLocator.Current.GetRequiredService<IProjectService>(); service.CreateProject( Size.Value.Width, Size.Value.Height, FrameRate.Value, SampleRate.Value, Name.Value, Location.Value); }); } public ReactiveProperty<PixelSize> Size { get; } = new(new PixelSize(1920, 1080)); public ReactiveProperty<int> FrameRate { get; } = new(30); public ReactiveProperty<int> SampleRate { get; } = new(44100); public ReactiveProperty<string> Name { get; } = new(); public ReactiveProperty<string> Location { get; } = new(); public ReadOnlyReactivePropertySlim<bool> CanCreate { get; } public ReactiveCommand Create { get; } private static string GenProjectName(string location) { const string name = "Project"; int n = 1; while (Directory.Exists(Path.Combine(location, name + n))) { n++; } return name + n; } }
26.858333
99
0.52901
[ "MIT" ]
b-editor/BeUtl
src/BeUtl/ViewModels/Dialogs/CreateNewProjectViewModel.cs
3,225
C#
using System.Reflection; using System.Runtime.CompilerServices; 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("Microsoft.Recognizers.Text.Number.Tests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Microsoft.Recognizers.Text.Number.Tests")] [assembly: AssemblyCopyright("Copyright © 2017")] [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("7333c1ed-a0cc-4f2c-aef4-b9dbc9ed988d")] // 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")]
39.432432
84
0.751199
[ "MIT" ]
SivilTaram/Recognizers-Text
Microsoft.Recognizers.Text.Number.Tests/Properties/AssemblyInfo.cs
1,462
C#
using Nager.Date.Contract; using Nager.Date.Model; using System; using System.Collections.Generic; using System.Linq; namespace Nager.Date.PublicHolidays { /// <summary> /// Barbados /// </summary> public class BarbadosProvider : IPublicHolidayProvider { private readonly ICatholicProvider _catholicProvider; /// <summary> /// BarbadosProvider /// </summary> /// <param name="catholicProvider"></param> public BarbadosProvider(ICatholicProvider catholicProvider) { this._catholicProvider = catholicProvider; } ///<inheritdoc/> public IEnumerable<PublicHoliday> Get(int year) { var countryCode = CountryCode.BB; var easterSunday = this._catholicProvider.EasterSunday(year); var firstMondayInAugust = DateSystem.FindDay(year, 8, DayOfWeek.Monday, 1); var items = new List<PublicHoliday>(); items.Add(new PublicHoliday(year, 1, 1, "New Year's Day", "New Year's Day", countryCode)); items.Add(new PublicHoliday(year, 1, 21, "Errol Barrow Day", "Errol Barrow Day", countryCode)); items.Add(new PublicHoliday(easterSunday.AddDays(-2), "Good Friday", "Good Friday", countryCode)); items.Add(new PublicHoliday(easterSunday.AddDays(1), "Easter Monday", "Easter Monday", countryCode)); items.Add(new PublicHoliday(year, 4, 28, "National Heroes' Day", "National Heroes' Day", countryCode)); items.Add(new PublicHoliday(year, 5, 1, "Labour Day", "Labour Day", countryCode)); items.Add(new PublicHoliday(easterSunday.AddDays(50), "Whit Monday", "Whit Monday", countryCode)); items.Add(new PublicHoliday(year, 8, 1, "Emancipation Day", "Emancipation Day", countryCode)); items.Add(new PublicHoliday(firstMondayInAugust, "Kadooment Day", "Kadooment Day", countryCode)); items.Add(new PublicHoliday(year, 11, 30, "Independence Day", "Independence Day", countryCode)); items.Add(new PublicHoliday(year, 12, 25, "Christmas Day", "Christmas Day", countryCode)); items.Add(new PublicHoliday(year, 12, 26, "Boxing Day", "Boxing Day", countryCode)); return items.OrderBy(o => o.Date); } ///<inheritdoc/> public IEnumerable<string> GetSources() { return new string[] { "https://en.wikipedia.org/wiki/Public_holidays_in_Barbados" }; } } }
42.383333
115
0.627998
[ "MIT" ]
raculus/Nager.Date
Src/Nager.Date/PublicHolidays/BarbadosProvider.cs
2,545
C#
namespace ThemeParkWorldRPC { public struct TpwMessageEventArgs { public string Message { get; } public TpwMessageEventArgs(string message) { Message = message; } } }
17.307692
50
0.582222
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
xezno/ThemeParkWorldRPC
ThemeParkWorldRPC/TpwMessageEventArgs.cs
227
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Mailer.WindowsService.Properties { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Mailer.WindowsService.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
43.84375
187
0.615467
[ "MIT" ]
EminentTechnology/Mailer
src/workers/Mailer.WindowsService/Properties/Resources.Designer.cs
2,808
C#
#region Copyright and License // Copyright 2010..2017 Alexander Reinert // // This file is part of the ARSoft.Tools.Net - C# DNS client/server and SPF Library (http://arsofttoolsnet.codeplex.com/) // // 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.Collections.Generic; namespace ARSoft.Tools.Net.Dns { /// <summary> /// The response of a secure DNS resolver /// </summary> public class DnsSecResult<T> where T : DnsRecordBase { /// <summary> /// The result of the validation process /// </summary> public DnsSecValidationResult ValidationResult { get; private set; } /// <summary> /// The records representing the response /// </summary> public List<T> Records { get; private set; } internal DnsSecResult(List<T> records, DnsSecValidationResult validationResult) { Records = records; ValidationResult = validationResult; } } }
32.222222
122
0.698621
[ "Apache-2.0" ]
Nicholi/ARSoft.Tools.Net
ARSoft.Tools.Net/Dns/Resolver/DnsSecResult.cs
1,452
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.IO; using Microsoft.Build.Evaluation; namespace Xamarin.MSBuild.Sdk { public sealed class ProjectDependencyNode : IDependencyNode { readonly List<ProjectDependencyNode> parents = new List<ProjectDependencyNode> (); public IReadOnlyList<ProjectDependencyNode> Parents => parents; readonly List<ProjectItem> projectReferenceItems = new List<ProjectItem> (); public IReadOnlyList<ProjectItem> ProjectReferenceItems => projectReferenceItems; public string ProjectPath { get; } public string Id { get; } public Project Project { get; } public string Label { get; } public Exception LoadException { get; } internal ProjectDependencyNode ( string projectPath, string id, Project project, Exception loadException) { ProjectPath = projectPath; Id = id; Project = project; Label = Path.GetFileNameWithoutExtension (projectPath); LoadException = loadException; } internal void AddParent (ProjectDependencyNode parent) { if (parent != null && !parents.Contains (parent)) parents.Add (parent); } internal void AddProjectReferenceItem (ProjectItem projectReferenceItem) { if (projectReferenceItem != null && !projectReferenceItems.Contains (projectReferenceItem)) projectReferenceItems.Add (projectReferenceItem); } public override string ToString () => $"{Id}:{Label}"; } }
32.703704
103
0.638165
[ "MIT" ]
KirillOsenkov/mirepoix
src/Xamarin.MSBuild.Sdk/ProjectDependencyNode.cs
1,766
C#
using Home.Neeo.Interfaces; using Home.Neeo.Models; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace Home.Neeo.Device.Handler { internal class HttpRequestHandler : IRequestHandler { private readonly RequestHandler _requestHandler; private readonly ILogger _logger; public HttpRequestHandler (RequestHandler requestHandler) { _requestHandler = requestHandler; _logger = NEEOEnvironment.Logger; } // /db/search public List<DataBase.SearchItem> DBSearchDevice(string query) { return _requestHandler.SearchDevice(query); } // /db/<deviceId> public DataBase.DeviceEntry DBGetDevice (int id) { return _requestHandler.GetDevice(id); } public async Task<HandlerParameter> GetHandler (string adapterId, string componentId) { var adapter = await _requestHandler.GetDeviceByAdapterId(adapterId); if (adapter != null) { HandlerParameter handler; adapter.Handler.TryGetValue(componentId, out handler); if (handler != null) { return handler; } else { _logger.LogWarning($"RequestHandler | GetHandler {adapterId}.{componentId} - no handler"); } } else { _logger.LogWarning($"RequestHandler | GetHandler {adapterId} - not found"); } return null; } // /device/<adapterId>/discover public async Task<NEEODiscoveredDevice[]> DeviceDiscover (string adapterId) { var handler = await GetHandler(adapterId, "discover"); if (handler == null) return null; return await _requestHandler.Discover(handler); } // /device/<adapterid>/<component>/<deviceid> public async Task<object> DeviceGetValue (string adapterId, string componentId, string deviceId) { var handler = await GetHandler(adapterId, componentId); if (handler == null) return null; return await _requestHandler.HandleGet (handler, deviceId); } public async Task<object> DeviceGetValue(HandlerParameter handler, string deviceId) { return await _requestHandler.HandleGet(handler, deviceId); } // /device/<adapterid>/<component>/<deviceid>/<value> public async Task<bool> DeviceSetValue (string adapterId, string componentId, string deviceId, string value) { var handler = await GetHandler(adapterId, componentId); if (handler == null) return false; return await _requestHandler.HandleSet(handler, deviceId, value); } // /<adapterName>/subscribe/<deviceId>/<eventUriPrefix> public Task<bool> Subscribe (string adapterId, string deviceId, string eventUriPrefix) { _logger.LogDebug ($"RequestHandler | NOT IMPLEMENTED: subscribe to { deviceId }, {eventUriPrefix }"); return Task.FromResult(true); } // /<adapterName>/unsubscribe/<deviceId> public Task<bool> Unsubscribe (string adapterId, string deviceId) { _logger.LogDebug($"RequestHandler | NOT IMPLEMENTED: unsubscribe from { deviceId }"); return Task.FromResult(true); } public async Task<object> HandleRequest(string path) { string[] split = path.Split('/'); if (split != null && split.Length > 2) { if (split[0] == "db") { if (split[1] == "search") { string query = split[2]; var searchResult = DBSearchDevice(query); return searchResult; } var result = DBGetDevice(Convert.ToInt32(split[1])); return result; } else if (split[0] == "device") { if (split.Length == 3 && split[2] == "discover") { var boolResult = await DeviceDiscover(split[1]); return boolResult; } else { if (split.Length == 4) { var getResult = await DeviceGetValue(split[1], split[2], split[3]); return getResult; } else if (split.Length == 5) { var setResult = await DeviceSetValue(split[1], split[2], split[3], split[4]); return setResult; } } } else if (split.Length == 4 && split[1] == "subscribe") { var subResult = Subscribe(split[0], split[2], split[3]); return subResult; } else if (split.Length == 3 && split[1] == "unsubscribe") { var unsubResult = Unsubscribe(split[0], split[2]); return unsubResult; } } return null; } } }
36.875
116
0.506155
[ "MIT" ]
MilanOTy/NeeoApi
NeeoApiLib/Device/Handler/HttpRequestHandler.cs
5,607
C#
using System; using System.Collections.Generic; using RimWorld; using Verse; using HarmonyLib; using System.Reflection; using TerrainMovement; using System.IO; using System.Linq; using Verse.AI; namespace Swimming { public sealed class SwimmingMod : Mod { public const String HarmonyId = "net.mseal.rimworld.mod.swimming"; public SwimmingMod(ModContentPack content) : base(content) { Assembly localAssembly = Assembly.GetExecutingAssembly(); string DLLName = localAssembly.GetName().Name; Version loadedVersion = localAssembly.GetName().Version; Version laterVersion = loadedVersion; List<ModContentPack> runningModsListForReading = LoadedModManager.RunningModsListForReading; foreach (ModContentPack mod in runningModsListForReading) { foreach (FileInfo item in from f in ModContentPack.GetAllFilesForMod(mod, "Assemblies/", (string e) => e.ToLower() == ".dll") select f.Value) { var newAssemblyName = AssemblyName.GetAssemblyName(item.FullName); if (newAssemblyName.Name == DLLName && newAssemblyName.Version > laterVersion) { laterVersion = newAssemblyName.Version; Log.Error(String.Format("{0} load order error detected. {1} is loading an older version {2} before {3} loads version {4}. Please put the {5}, or BiomesCore mods above this one if they are active.", DLLName, content.Name, loadedVersion, mod.Name, laterVersion, DLLName)); } } } var harmony = new Harmony(HarmonyId); harmony.PatchAll(localAssembly); } } [StaticConstructorOnStartup] public static class SwimmingLoader { public const float DefaultWaterSwimCost = 15; public const string SwimStat = "SwimSpeed"; public const string WaterTag = "Water"; public const string DeepWaterTag = "DeepWater"; public const string SaltWaterTag = "SaltWater"; public const string FreshWaterTag = "FreshWater"; public const string BridgeTag = "Bridge"; public static readonly IEnumerable<string> WaterTiles = new HashSet<string> { "WaterDeep", "WaterOceanDeep", "WaterMovingChestDeep", "WaterShallow", "WaterOceanShallow", "WaterMovingShallow", "Marsh" }; public static readonly Dictionary<string, float> WaterSwimCost = new Dictionary<string, float> { { "WaterDeep", 10 }, { "WaterOceanDeep", 10 }, { "WaterMovingChestDeep", 10 }, { "WaterShallow", 15 }, { "WaterOceanShallow", 15 }, { "WaterMovingShallow", 20 }, { "Marsh", 30 } }; public static readonly HashSet<string> SaltWaterTerrain = new HashSet<string>() { "WaterOceanShallow", "WaterOceanDeep" }; public static TerrainMovementStatDef WaterTerrainModExt = new TerrainMovementStatDef(); public static TerrainMovementTerrainRestrictions DeepWaterTerrainRestrictionModeExt = new TerrainMovementTerrainRestrictions(); static SwimmingLoader() { // Set our extension defaults (they can't have constructors) WaterTerrainModExt.terrainPathCostStat = "pathCostSwimming"; WaterTerrainModExt.pawnSpeedStat = SwimStat; DeepWaterTerrainRestrictionModeExt.disallowedPathCostStat = "pathCost"; PatchWater(); // We need to run this after other loaders since bridges also intializes with StaticConstructorOnStartup LongEventHandler.QueueLongEvent(() => PatchBridges(), null, false, null); } public static void PatchDeepWaterRestrictions(TerrainDef water) { if (water.passability == Traversability.Impassable) { water.passability = Traversability.Standable; if (water.tags == null) { water.tags = new List<string>(); } if (!water.tags.Contains(DeepWaterTag)) { // Helpful for assigning rules to deep water in extensions of the kit water.tags.Add(DeepWaterTag); } bool foundExtension = false; if (water.modExtensions == null) { water.modExtensions = new List<DefModExtension>(); } foreach (DefModExtension ext in water.modExtensions) { if (ext is TerrainMovementTerrainRestrictions) { TerrainMovementTerrainRestrictions restriction = ext as TerrainMovementTerrainRestrictions; if (restriction.disallowedPathCostStat == null || restriction.disallowedPathCostStat == "pathCost") { foundExtension = true; } } } if (!foundExtension) { water.modExtensions.Add(DeepWaterTerrainRestrictionModeExt); } } } public static void PatchSaltWaterTag(TerrainDef water) { if (SaltWaterTerrain.Contains(water.defName)) { if (water.tags == null) { water.tags = new List<string>(); } if (!water.tags.Contains(FreshWaterTag) && !water.tags.Contains(SaltWaterTag)) { // Allows for constraining aquatic animals to fresh/salt water water.tags.Add(SaltWaterTag); } } } public static void PatchFreshWaterTag(TerrainDef water) { if (!SaltWaterTerrain.Contains(water.defName)) { if (water.tags == null) { water.tags = new List<string>(); } if (!water.tags.Contains(FreshWaterTag) && !water.tags.Contains(SaltWaterTag)) { // Allows for constraining aquatic animals to fresh/salt water water.tags.Add(FreshWaterTag); } } } public static void PatchBridgeTag(TerrainDef bridge) { if (bridge.tags == null) { bridge.tags = new List<string>(); } if (!bridge.tags.Contains(BridgeTag)) { // Prevents water animals from trying to enter ontop of a bridge bridge.tags.Add(BridgeTag); } } public static void PatchPathCostSwimming(TerrainDef water) { bool foundStat = false; StatModifier pathCost = new StatModifier { stat = StatDef.Named(WaterTerrainModExt.terrainPathCostStat), value = WaterSwimCost.TryGetValue(water.defName, DefaultWaterSwimCost) }; if (water.statBases == null) { water.statBases = new List<StatModifier>(); } foreach (StatModifier statBase in water.statBases) { if (statBase.stat == pathCost.stat) { foundStat = true; } } if (!foundStat) { water.statBases.Add(pathCost); } } public static void PatchTerrainMovementStatDefs(TerrainDef water) { bool foundExtension = false; if (water.modExtensions == null) { water.modExtensions = new List<DefModExtension>(); } foreach (DefModExtension ext in water.modExtensions) { if (ext is TerrainMovementStatDef) { TerrainMovementStatDef moveStatDef = ext as TerrainMovementStatDef; if (moveStatDef.pawnSpeedStat == "pathCostSwimming") { foundExtension = true; } } } if (!foundExtension) { water.modExtensions.Add(WaterTerrainModExt); } } public static void PatchWater() { foreach (TerrainDef terrain in DefDatabase<TerrainDef>.AllDefs) { if (terrain.HasTag("Water")) { PatchDeepWaterRestrictions(terrain); PatchPathCostSwimming(terrain); PatchTerrainMovementStatDefs(terrain); PatchFreshWaterTag(terrain); PatchSaltWaterTag(terrain); } } } public static void PatchBridges() { foreach (TerrainDef terrain in DefDatabase<TerrainDef>.AllDefs) { if (terrain.defName.StartsWith("DeepWaterBridge") || terrain.defName.StartsWith("HeavyBridge") || terrain.defName.StartsWith("Bridge")) { PatchBridgeTag(terrain); } } } } public class AquaticExtension : DefModExtension { public bool aquatic = true; public bool saltWaterOnly = false; public bool freshWaterOnly = false; } [HarmonyPatch(typeof(ThingDefExtensions), "MovementExtensions")] class AquaticExtensionTranslator { static void Postfix(ref IEnumerable<TerrainMovementPawnRestrictions> __result, ThingDef race) { List<TerrainMovementPawnRestrictions> newResults = new List<TerrainMovementPawnRestrictions>(); foreach(var ext in __result) { newResults.Add(ext); } var modExtensions = race.modExtensions; if (modExtensions != null) { foreach (DefModExtension ext in modExtensions) { if (ext is AquaticExtension) { // First water rules AquaticExtension aqext = ext as AquaticExtension; TerrainMovementPawnRestrictions tmext = new TerrainMovementPawnRestrictions(); tmext.defaultMovementAllowed = false; tmext.stayOnTerrainTag = SwimmingLoader.WaterTag; if (aqext.saltWaterOnly) { tmext.stayOffTerrainTag = SwimmingLoader.FreshWaterTag; } else if (aqext.freshWaterOnly) { tmext.stayOffTerrainTag = SwimmingLoader.SaltWaterTag; } newResults.Add(tmext); // Second water rule to avoid bridges tmext = new TerrainMovementPawnRestrictions(); tmext.defaultMovementAllowed = false; tmext.stayOffTerrainTag = SwimmingLoader.BridgeTag; newResults.Add(tmext); } } } __result = newResults; } } [HarmonyPatch(typeof(GenGrid), "Walkable")] class ToggledDeepWaterWalkable { // A hack to temporarily treat deep water edge tiles as walkable or not public static bool DeepWaterValid = true; static void Postfix(ref bool __result, IntVec3 c, Map map) { if (__result && !DeepWaterValid) { TerrainDef terrain = map.terrainGrid.TerrainAt(c); if (terrain != null) { __result = !terrain.HasTag(SwimmingLoader.DeepWaterTag); } } } } /* For Raid WalkIn */ [HarmonyPatch(typeof(PawnsArrivalModeWorker_EdgeWalkIn), "TryResolveRaidSpawnCenter")] class DeepWaterNotPreferredForWalkIn { // A hack to allow second entry to a prefixed method to call the original static bool Entered = false; static bool Prefix(ref bool __result, ref PawnsArrivalModeWorker_EdgeWalkIn __instance, IncidentParms parms) { if (Entered) { return true; } try { Entered = true; // We need to make DeepWater look impassible for a moment ToggledDeepWaterWalkable.DeepWaterValid = false; __result = __instance.TryResolveRaidSpawnCenter(parms); } finally { ToggledDeepWaterWalkable.DeepWaterValid = true; Entered = false; } return !__result; } } /* For Raid GroupWalkIn & CaravanArrival */ [HarmonyPatch(typeof(RCellFinder), "TryFindRandomPawnEntryCell")] class DeepWaterNotPreferredForTryFindRandomPawnEntryCell { // A hack to allow second entry to a prefixed method to call the original static bool Entered = false; public static bool PreferNonDeepWater = false; static bool Prefix(ref bool __result, ref IntVec3 result, Map map, float roadChance, bool allowFogged, Predicate<IntVec3> extraValidator) { if (Entered || !PreferNonDeepWater) { return true; } try { Entered = true; // We need to make DeepWater look impassible for a moment ToggledDeepWaterWalkable.DeepWaterValid = false; __result = RCellFinder.TryFindRandomPawnEntryCell(out result, map, roadChance, allowFogged, extraValidator); } finally { ToggledDeepWaterWalkable.DeepWaterValid = true; Entered = false; } return !__result; } } [HarmonyPatch(typeof(PawnsArrivalModeWorker_EdgeWalkInGroups), "Arrive")] class DeepWaterNotPreferredForGroupWalkIn { static bool Prefix() { // Set downstream methods to toggle on preferences for avoiding deep water DeepWaterNotPreferredForTryFindRandomPawnEntryCell.PreferNonDeepWater = true; return true; } static void Postfix() { // Make sure we undo the setting DeepWaterNotPreferredForTryFindRandomPawnEntryCell.PreferNonDeepWater = false; } } [HarmonyPatch(typeof(IncidentWorker_TraderCaravanArrival), "TryExecuteWorker")] class DeepWaterNotPreferredForTraderCaravanArrival { static bool Prefix() { // Set downstream methods to toggle on preferences for avoiding deep water DeepWaterNotPreferredForTryFindRandomPawnEntryCell.PreferNonDeepWater = true; return true; } static void Postfix() { // Make sure we undo the setting DeepWaterNotPreferredForTryFindRandomPawnEntryCell.PreferNonDeepWater = false; } } [HarmonyPatch(typeof(IncidentWorker_ManhunterPack), "TryExecuteWorker")] class DeepWaterNotPreferredForManhunterPack { static bool Prefix(ref IncidentParms parms) { Map map = (Map)parms.target; // Set downstream methods to toggle on preferences for avoiding deep water PawnKindDef animalKind = parms.pawnKind; if ((animalKind == null && !ManhunterPackIncidentUtility.TryFindManhunterAnimalKind(parms.points, map.Tile, out animalKind)) || ManhunterPackIncidentUtility.GetAnimalsCount(animalKind, parms.points) == 0) { return true; } // Set the animal manually since we need to know ahead of time to determine if it swims parms.pawnKind = animalKind; // Check if the animal involved prefers to swim over walk if (animalKind.race.GetStatValueAbstract(StatDefOf.MoveSpeed) >= animalKind.race.GetStatValueAbstract(StatDef.Named(SwimmingLoader.SwimStat)) + 0.001) { DeepWaterNotPreferredForTryFindRandomPawnEntryCell.PreferNonDeepWater = true; } return true; } static void Postfix() { // Make sure we undo the setting DeepWaterNotPreferredForTryFindRandomPawnEntryCell.PreferNonDeepWater = false; } } [HarmonyPatch(typeof(IncidentWorker_HerdMigration), "TryFindAnimalKind")] class HerdTrackTryFindAnimalKind { public static PawnKindDef LastGenAnimal; static void Postfix(int tile, ref bool __result, ref PawnKindDef animalKind) { // Make sure we undo the setting LastGenAnimal = animalKind; } } // We must patch the wrapper in TMK, not the original method [HarmonyPatch(typeof(IncidentWorker_HerdMigration_Extensions), "TryFindStartAndEndCells")] class DeepWaterNotPreferredForHerdMigrationStartAndEnd { static bool Prefix() { // Set downstream methods to toggle on preferences for avoiding deep water PawnKindDef animalKind = HerdTrackTryFindAnimalKind.LastGenAnimal; // Check if the animal involved prefers to swim over walk if (animalKind != null && animalKind.race.GetStatValueAbstract(StatDefOf.MoveSpeed) >= animalKind.race.GetStatValueAbstract(StatDef.Named(SwimmingLoader.SwimStat)) + 0.001) { DeepWaterNotPreferredForTryFindRandomPawnEntryCell.PreferNonDeepWater = true; } return true; } static void Postfix() { // Make sure we undo the setting DeepWaterNotPreferredForTryFindRandomPawnEntryCell.PreferNonDeepWater = false; } } [HarmonyPatch()] class DeepWaterNotPreferredForAlphabeavers { static MethodBase TargetMethod() { // This is required because the class is internal ... var q = from t in Assembly.GetAssembly(typeof(Pawn)).GetTypes() where t.IsClass && t.Name == "IncidentWorker_Alphabeavers" select t; foreach (var t in q) { return t.GetMethod("TryExecuteWorker", AccessTools.all); } return null; } static bool Prefix(ref IncidentParms parms) { DeepWaterNotPreferredForTryFindRandomPawnEntryCell.PreferNonDeepWater = true; return true; } static void Postfix() { // Make sure we undo the setting DeepWaterNotPreferredForTryFindRandomPawnEntryCell.PreferNonDeepWater = false; } } [HarmonyPatch(typeof(IncidentWorker_ThrumboPasses), "TryExecuteWorker")] class DeepWaterNotPreferredForThrumbos { static bool Prefix(ref IncidentParms parms) { DeepWaterNotPreferredForTryFindRandomPawnEntryCell.PreferNonDeepWater = true; return true; } static void Postfix() { // Make sure we undo the setting DeepWaterNotPreferredForTryFindRandomPawnEntryCell.PreferNonDeepWater = false; } } [HarmonyPatch(typeof(IncidentWorker_TravelerGroup), "TryExecuteWorker")] class DeepWaterNotPreferredForTravelerGroup { static bool Prefix(ref IncidentParms parms) { DeepWaterNotPreferredForTryFindRandomPawnEntryCell.PreferNonDeepWater = true; return true; } static void Postfix() { // Make sure we undo the setting DeepWaterNotPreferredForTryFindRandomPawnEntryCell.PreferNonDeepWater = false; } } [HarmonyPatch(typeof(IncidentWorker_VisitorGroup), "TryExecuteWorker")] class DeepWaterNotPreferredForVisitorGroup { static bool Prefix(ref IncidentParms parms) { DeepWaterNotPreferredForTryFindRandomPawnEntryCell.PreferNonDeepWater = true; return true; } static void Postfix() { // Make sure we undo the setting DeepWaterNotPreferredForTryFindRandomPawnEntryCell.PreferNonDeepWater = false; } } [HarmonyPatch(typeof(IncidentWorker_WandererJoin), "TryExecuteWorker")] class DeepWaterNotPreferredForWandererJoin { static bool Prefix(ref IncidentParms parms) { DeepWaterNotPreferredForTryFindRandomPawnEntryCell.PreferNonDeepWater = true; return true; } static void Postfix() { // Make sure we undo the setting DeepWaterNotPreferredForTryFindRandomPawnEntryCell.PreferNonDeepWater = false; } } [HarmonyPatch(typeof(IncidentWorker_WildManWandersIn), "TryExecuteWorker")] class DeepWaterNotPreferredForWildMan { static bool Prefix(ref IncidentParms parms) { DeepWaterNotPreferredForTryFindRandomPawnEntryCell.PreferNonDeepWater = true; return true; } static void Postfix() { // Make sure we undo the setting DeepWaterNotPreferredForTryFindRandomPawnEntryCell.PreferNonDeepWater = false; } } // We must patch the wrapper in TMK, not the original method [HarmonyPatch(typeof(JobGiver_ExitMapBest), "TryFindGoodExitDest")] class DeepWaterNotPreferredForTryFindGoodExitDest { static bool Prefix(ref bool __result, Pawn pawn, bool canDig, out IntVec3 spot) { spot = IntVec3.Invalid; // Check if the animal involved prefers to swim over walk if (pawn.GetStatValue(StatDefOf.MoveSpeed) >= pawn.GetStatValue(StatDef.Named(SwimmingLoader.SwimStat)) + 0.001) { ToggledDeepWaterWalkable.DeepWaterValid = false; try { TraverseMode mode = canDig ? TraverseMode.PassAllDestroyableThings : TraverseMode.ByPawn; __result = RCellFinder.TryFindBestExitSpot(pawn, out spot, mode); } finally { ToggledDeepWaterWalkable.DeepWaterValid = true; } } return !__result; } } }
37.72093
221
0.577021
[ "MIT" ]
MSeal/RimworldSwimming
SwimmingMod/SwimmingPatches.cs
22,710
C#
// <auto-generated /> // Built from: hl7.fhir.r5.core version: 4.6.0 // Option: "NAMESPACE" = "fhirCsR5" using fhirCsR5.Models; namespace fhirCsR5.ValueSets { /// <summary> /// A code that specifies a type of context being specified by a usage context. /// </summary> public static class UsageContextTypeCodes { /// <summary> /// The age of the patient. For this context type, the value could be a range that specifies the applicable ages or a code from an appropriate value set such as the MeSH value set http://terminology.hl7.org/ValueSet/v3-AgeGroupObservationValue. /// </summary> public static readonly Coding AgeRange = new Coding { Code = "age", Display = "Age Range", System = "http://terminology.hl7.org/CodeSystem/usage-context-type" }; /// <summary> /// The clinical concept(s) addressed by the artifact. For example, disease, diagnostic test interpretation, medication ordering as in http://hl7.org/fhir/ValueSet/condition-code. /// </summary> public static readonly Coding ClinicalFocus = new Coding { Code = "focus", Display = "Clinical Focus", System = "http://terminology.hl7.org/CodeSystem/usage-context-type" }; /// <summary> /// The gender of the patient. For this context type, appropriate values can be found in the http://hl7.org/fhir/ValueSet/administrative-gender value set. /// </summary> public static readonly Coding Gender = new Coding { Code = "gender", Display = "Gender", System = "http://terminology.hl7.org/CodeSystem/usage-context-type" }; /// <summary> /// A program/project of work for which this artifact is applicable. /// </summary> public static readonly Coding Program = new Coding { Code = "program", Display = "Program", System = "http://terminology.hl7.org/CodeSystem/usage-context-type" }; /// <summary> /// The species to which an artifact applies. For example, SNOMED - 387961004 | Kingdom Animalia (organism). /// </summary> public static readonly Coding Species = new Coding { Code = "species", Display = "Species", System = "http://terminology.hl7.org/CodeSystem/usage-context-type" }; /// <summary> /// The context for the clinical task(s) represented by this artifact. For example, this could be any task context represented by the HL7 ActTaskCode value set http://terminology.hl7.org/ValueSet/v3-ActTaskCode. General categories include: order entry, patient documentation and patient information review. /// </summary> public static readonly Coding WorkflowTask = new Coding { Code = "task", Display = "Workflow Task", System = "http://terminology.hl7.org/CodeSystem/usage-context-type" }; /// <summary> /// The clinical specialty of the context in which the patient is being treated - For example, PCP, Patient, Cardiologist, Behavioral Professional, Oral Health Professional, Prescriber, etc... taken from a specialty value set such as the NUCC Health Care provider taxonomy value set http://hl7.org/fhir/ValueSet/provider-taxonomy. /// </summary> public static readonly Coding UserType = new Coding { Code = "user", Display = "User Type", System = "http://terminology.hl7.org/CodeSystem/usage-context-type" }; /// <summary> /// The venue in which an artifact could be used. For example, Outpatient, Inpatient, Home, Nursing home. The code value may originate from the HL7 ServiceDeliveryLocationRoleType value set (http://terminology.hl7.org/ValueSet/v3-ServiceDeliveryLocationRoleType). /// </summary> public static readonly Coding ClinicalVenue = new Coding { Code = "venue", Display = "Clinical Venue", System = "http://terminology.hl7.org/CodeSystem/usage-context-type" }; /// <summary> /// The settings in which the artifact is intended for use. For example, admission, pre-op, etc. For example, the ActEncounterCode value set http://terminology.hl7.org/ValueSet/v3-ActEncounterCode. /// </summary> public static readonly Coding WorkflowSetting = new Coding { Code = "workflow", Display = "Workflow Setting", System = "http://terminology.hl7.org/CodeSystem/usage-context-type" }; }; }
44.752577
334
0.679337
[ "MIT" ]
FirelyTeam/fhir-codegen
src/Microsoft.Health.Fhir.SpecManager/fhir/R5/ValueSets/UsageContextType.cs
4,341
C#
using Android.App; using Android.OS; using JobTest.Droid.Services; namespace JobTest.Droid.Views { [Activity()] public class MainView : BaseView { protected override int LayoutResource => Resource.Layout.FirstView; protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); SupportActionBar.SetDisplayHomeAsUpEnabled(false); var bitcoinPriceBackgroundServiceScheduler = new BitcoinPriceBackgroundServiceScheduler(); FindViewById(Resource.Id.serviceButton).Click += (e,a)=>{ bitcoinPriceBackgroundServiceScheduler.StartPeriodicBackgroundWorkUsingAlarmManager(); }; FindViewById(Resource.Id.jobSchedulerButton).Click += (e,a) => { bitcoinPriceBackgroundServiceScheduler.StartPeriodicBackgroundWorkUsingJobScheduler(); }; } } }
30.774194
103
0.641509
[ "MIT" ]
thefex/JobScheduler_vs_Service
JobTest.Service/JobTest/JobTest.Droid/Views/MainView.cs
954
C#
// The MIT License (MIT) // // Copyright (c) Andrew Armstrong/FacticiusVir 2019 // // 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. // This file was automatically generated and should not be edited directly. using System; namespace SharpVk.Multivendor { /// <summary> /// /// </summary> public delegate Bool32 DebugReportCallbackDelegate(SharpVk.Multivendor.DebugReportFlags flags, SharpVk.Multivendor.DebugReportObjectType objectType, ulong @object, HostSize location, int messageCode, string pLayerPrefix, string pMessage, IntPtr pUserData); }
46.852941
260
0.765223
[ "MIT" ]
Y-Less/SharpVk
src/SharpVk/Multivendor/DebugReportCallbackDelegate.gen.cs
1,593
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace PruebaWinForms.Properties { /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if ((resourceMan == null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("PruebaWinForms.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
38.680556
180
0.60395
[ "MIT" ]
rediberry/Estudio_contable_springfield
Estudio_Contable_Springfield/PruebaWinForms/Properties/Resources.Designer.cs
2,787
C#
namespace TDDInlamning1_MLarsson.GeometricThings { /// <summary> /// Class to handle the rectangle object. /// </summary> public class Rectangle : GeometricThing { public Rectangle(float width, float height) { this.Width = width; this.Height = height; } public float Height { get; set; } public float Width { get; set; } public override float GetArea() { return Width <= 0 || Height <= 0 ? 0 : Area = Width * Height; } public override float GetPerimeter() { return Width < 0 || Height < 0 ? 0 : Perimeter = (Width * 2) + (Height * 2); } } }
25.178571
88
0.524823
[ "MIT" ]
marcusjobb/NET20D
TDD/Inlämning1/Mikael/TDDInlamning1_MLarsson/GeometricThings/Rectangle.cs
707
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Net.Http.Headers; namespace Kartverket.Geonorge.Download.Areas.HelpPage { /// <summary> /// This is used to identify the place where the sample should be applied. /// </summary> public class HelpPageSampleKey { /// <summary> /// Creates a new <see cref="HelpPageSampleKey"/> based on media type. /// </summary> /// <param name="mediaType">The media type.</param> public HelpPageSampleKey(MediaTypeHeaderValue mediaType) { if (mediaType == null) { throw new ArgumentNullException("mediaType"); } ActionName = String.Empty; ControllerName = String.Empty; MediaType = mediaType; ParameterNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase); } /// <summary> /// Creates a new <see cref="HelpPageSampleKey"/> based on media type and CLR type. /// </summary> /// <param name="mediaType">The media type.</param> /// <param name="type">The CLR type.</param> public HelpPageSampleKey(MediaTypeHeaderValue mediaType, Type type) : this(mediaType) { if (type == null) { throw new ArgumentNullException("type"); } ParameterType = type; } /// <summary> /// Creates a new <see cref="HelpPageSampleKey"/> based on <see cref="SampleDirection"/>, controller name, action name and parameter names. /// </summary> /// <param name="sampleDirection">The <see cref="SampleDirection"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public HelpPageSampleKey(SampleDirection sampleDirection, string controllerName, string actionName, IEnumerable<string> parameterNames) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (controllerName == null) { throw new ArgumentNullException("controllerName"); } if (actionName == null) { throw new ArgumentNullException("actionName"); } if (parameterNames == null) { throw new ArgumentNullException("parameterNames"); } ControllerName = controllerName; ActionName = actionName; ParameterNames = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); SampleDirection = sampleDirection; } /// <summary> /// Creates a new <see cref="HelpPageSampleKey"/> based on media type, <see cref="SampleDirection"/>, controller name, action name and parameter names. /// </summary> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The <see cref="SampleDirection"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public HelpPageSampleKey(MediaTypeHeaderValue mediaType, SampleDirection sampleDirection, string controllerName, string actionName, IEnumerable<string> parameterNames) : this(sampleDirection, controllerName, actionName, parameterNames) { if (mediaType == null) { throw new ArgumentNullException("mediaType"); } MediaType = mediaType; } /// <summary> /// Gets the name of the controller. /// </summary> /// <value> /// The name of the controller. /// </value> public string ControllerName { get; private set; } /// <summary> /// Gets the name of the action. /// </summary> /// <value> /// The name of the action. /// </value> public string ActionName { get; private set; } /// <summary> /// Gets the media type. /// </summary> /// <value> /// The media type. /// </value> public MediaTypeHeaderValue MediaType { get; private set; } /// <summary> /// Gets the parameter names. /// </summary> public HashSet<string> ParameterNames { get; private set; } public Type ParameterType { get; private set; } /// <summary> /// Gets the <see cref="SampleDirection"/>. /// </summary> public SampleDirection? SampleDirection { get; private set; } public override bool Equals(object obj) { HelpPageSampleKey otherKey = obj as HelpPageSampleKey; if (otherKey == null) { return false; } return String.Equals(ControllerName, otherKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(ActionName, otherKey.ActionName, StringComparison.OrdinalIgnoreCase) && (MediaType == otherKey.MediaType || (MediaType != null && MediaType.Equals(otherKey.MediaType))) && ParameterType == otherKey.ParameterType && SampleDirection == otherKey.SampleDirection && ParameterNames.SetEquals(otherKey.ParameterNames); } public override int GetHashCode() { int hashCode = ControllerName.ToUpperInvariant().GetHashCode() ^ ActionName.ToUpperInvariant().GetHashCode(); if (MediaType != null) { hashCode ^= MediaType.GetHashCode(); } if (SampleDirection != null) { hashCode ^= SampleDirection.GetHashCode(); } if (ParameterType != null) { hashCode ^= ParameterType.GetHashCode(); } foreach (string parameterName in ParameterNames) { hashCode ^= parameterName.ToUpperInvariant().GetHashCode(); } return hashCode; } } }
37.526012
175
0.570548
[ "MIT" ]
kartverket/Geonorge.NedlastingAPI
Kartverket.Geonorge.Download/Areas/HelpPage/SampleGeneration/HelpPageSampleKey.cs
6,492
C#
/* * Copyright, 2021, LogicMonitor, Inc. * This Source Code Form is subject to the terms of the * Mozilla Public License, v. 2.0. If a copy of the MPL * was not distributed with this file, You can obtain * one at https://mozilla.org/MPL/2.0/. */ using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.ComponentModel.DataAnnotations; namespace LogicMonitor.DataSDK.Model { /// <summary> /// RestInstancePropertiesV1 /// </summary> [DataContract(Name = "RestInstancePropertiesV1")] public partial class RestInstancePropertiesV1 { public RestInstancePropertiesV1() { } /// <summary> /// Initializes a new instance of the <see cref="RestInstancePropertiesV1" /> class. /// </summary> /// <param name="dataSource">dataSource.</param> /// <param name="dataSourceDisplayName">dataSourceDisplayName.</param> /// <param name="instanceId">instanceId.</param> /// <param name="instanceName">instanceName.</param> /// <param name="instanceProperties">instanceProperties.</param> /// <param name="resourceIds">resourceIds.</param> public RestInstancePropertiesV1(string dataSource , string dataSourceDisplayName = default(string), int instanceId = default(int), string instanceName = default(string), Dictionary<string, string> instanceProperties = default(Dictionary<string, string>), Dictionary<string, string> resourceIds = default(Dictionary<string, string>)) { this.DataSource = dataSource; this.DataSourceDisplayName = dataSourceDisplayName; this.InstanceId = instanceId; this.InstanceName = instanceName; this.InstanceProperties = instanceProperties; this.ResourceIds = resourceIds; } /// <summary> /// Gets or Sets DataSource /// </summary> [DataMember(Name = "dataSource", EmitDefaultValue = false)] public string DataSource { get; set; } /// <summary> /// Gets or Sets DataSourceDisplayName /// </summary> [DataMember(Name = "dataSourceDisplayName", EmitDefaultValue = false)] public string DataSourceDisplayName { get; set; } /// <summary> /// Gets or Sets InstanceId /// </summary> [DataMember(Name = "instanceId", EmitDefaultValue = false)] public int InstanceId { get; set; } /// <summary> /// Gets or Sets InstanceName /// </summary> [DataMember(Name = "instanceName", EmitDefaultValue = false)] public string InstanceName { get; set; } /// <summary> /// Gets or Sets InstanceProperties /// </summary> [DataMember(Name = "instanceProperties", EmitDefaultValue = false)] public Dictionary<string, string> InstanceProperties { get; set; } /// <summary> /// Gets or Sets ResourceIds /// </summary> [DataMember(Name = "resourceIds", EmitDefaultValue = false)] public Dictionary<string, string> ResourceIds { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class RestInstancePropertiesV1 {\n"); sb.Append(" DataSource: ").Append(DataSource).Append("\n"); sb.Append(" DataSourceDisplayName: ").Append(DataSourceDisplayName).Append("\n"); sb.Append(" InstanceId: ").Append(InstanceId).Append("\n"); sb.Append(" InstanceName: ").Append(InstanceName).Append("\n"); sb.Append(" InstanceProperties{\n"); foreach (var item in InstanceProperties) { sb.Append(" " + item.Key).Append(": ").Append(item.Value).Append("\n"); } sb.Append(" }\n"); sb.Append(" ResourceIds{\n"); foreach (var item in ResourceIds) { sb.Append(" " + item.Key).Append(": ").Append(item.Value).Append("\n"); } sb.Append(" }\n"); sb.Append("}\n"); return sb.ToString(); } } }
38.743363
340
0.600731
[ "MPL-2.0" ]
AakashKhopade/lm-data-sdk-dotnet
LogicMonitor.DataSDK/Model/RestInstancePropertiesV1.cs
4,378
C#
using System; using System.Xml.Serialization; namespace Alipay.AopSdk.Core.Domain { /// <summary> /// KoubeiMarketingCampaignIntelligentPromoBatchqueryModel Data Structure. /// </summary> [Serializable] public class KoubeiMarketingCampaignIntelligentPromoBatchqueryModel : AopObject { /// <summary> /// 操作员上下文信息 /// </summary> [XmlElement("operator_context")] public PromoOperatorInfo OperatorContext { get; set; } /// <summary> /// 外部业务id,请保持足够的复杂,方便定位数据来源 /// </summary> [XmlElement("out_request_no")] public string OutRequestNo { get; set; } /// <summary> /// 活动拥有者信息 /// </summary> [XmlElement("owner_info")] public PromoOperatorInfo OwnerInfo { get; set; } /// <summary> /// 分页信息 /// </summary> [XmlElement("page_info")] public PromoPageInfo PageInfo { get; set; } } }
26.108108
83
0.586957
[ "MIT" ]
leixf2005/Alipay.AopSdk.Core
Alipay.AopSdk.Core/Domain/KoubeiMarketingCampaignIntelligentPromoBatchqueryModel.cs
1,048
C#
// ------------------------------------------------------------------------------ // <auto-generated> // This code was generated by SpecFlow (http://www.specflow.org/). // SpecFlow Version:1.9.0.77 // SpecFlow Generator Version:1.9.0.0 // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> // ------------------------------------------------------------------------------ #region Designer generated code #pragma warning disable namespace Orchard.Specs { using TechTalk.SpecFlow; [System.CodeDom.Compiler.GeneratedCodeAttribute("TechTalk.SpecFlow", "1.9.0.77")] [System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [NUnit.Framework.TestFixtureAttribute()] [NUnit.Framework.DescriptionAttribute("Content rights management")] public partial class ContentRightsManagementFeature { private static TechTalk.SpecFlow.ITestRunner testRunner; #line 1 "ContentRights.feature" #line hidden [NUnit.Framework.TestFixtureSetUpAttribute()] public virtual void FeatureSetup() { testRunner = TechTalk.SpecFlow.TestRunnerManager.GetTestRunner(); TechTalk.SpecFlow.FeatureInfo featureInfo = new TechTalk.SpecFlow.FeatureInfo(new System.Globalization.CultureInfo("en-US"), "Content rights management", " In order to ensure security\r\n As a root Orchard system operator\r\n I want only" + " the allowed users to edit the content", ProgrammingLanguage.CSharp, ((string[])(null))); testRunner.OnFeatureStart(featureInfo); } [NUnit.Framework.TestFixtureTearDownAttribute()] public virtual void FeatureTearDown() { testRunner.OnFeatureEnd(); testRunner = null; } [NUnit.Framework.SetUpAttribute()] public virtual void TestInitialize() { } [NUnit.Framework.TearDownAttribute()] public virtual void ScenarioTearDown() { testRunner.OnScenarioEnd(); } public virtual void ScenarioSetup(TechTalk.SpecFlow.ScenarioInfo scenarioInfo) { testRunner.OnScenarioStart(scenarioInfo); } public virtual void ScenarioCleanup() { testRunner.CollectScenarioErrors(); } [NUnit.Framework.TestAttribute()] [NUnit.Framework.DescriptionAttribute("Administrators can manage a Page")] public virtual void AdministratorsCanManageAPage() { TechTalk.SpecFlow.ScenarioInfo scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("Administrators can manage a Page", ((string[])(null))); #line 6 this.ScenarioSetup(scenarioInfo); #line 7 testRunner.Given("I have installed Orchard", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Given "); #line 8 testRunner.When("I have a user \"user1\" with roles \"Administrator\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "When "); #line 9 testRunner.Then("\"user1\" should be able to \"publish\" a \"Page\" owned by \"user1\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Then "); #line 10 testRunner.And("\"user1\" should be able to \"edit\" a \"Page\" owned by \"user1\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line hidden this.ScenarioCleanup(); } [NUnit.Framework.TestAttribute()] [NUnit.Framework.DescriptionAttribute("Users can\'t create a Page if they don\'t have the PublishContent permission")] public virtual void UsersCanTCreateAPageIfTheyDonTHaveThePublishContentPermission() { TechTalk.SpecFlow.ScenarioInfo scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("Users can\'t create a Page if they don\'t have the PublishContent permission", ((string[])(null))); #line 12 this.ScenarioSetup(scenarioInfo); #line 13 testRunner.Given("I have installed Orchard", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Given "); #line 14 testRunner.When("I have a role \"CustomRole\" with permissions \"EditContent, DeleteContent\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "When "); #line 15 testRunner.And("I have a user \"user1\" with roles \"CustomRole\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line 16 testRunner.Then("\"user1\" should not be able to \"publish\" a \"Page\" owned by \"user1\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Then "); #line 17 testRunner.And("\"user1\" should be able to \"edit\" a \"Page\" owned by \"user1\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line 18 testRunner.And("\"user1\" should be able to \"delete\" a \"Page\" owned by \"user1\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line hidden this.ScenarioCleanup(); } [NUnit.Framework.TestAttribute()] [NUnit.Framework.DescriptionAttribute("Users can create a Page of others if they have PublishContent permission")] public virtual void UsersCanCreateAPageOfOthersIfTheyHavePublishContentPermission() { TechTalk.SpecFlow.ScenarioInfo scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("Users can create a Page of others if they have PublishContent permission", ((string[])(null))); #line 20 this.ScenarioSetup(scenarioInfo); #line 21 testRunner.Given("I have installed Orchard", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Given "); #line 22 testRunner.When("I have a role \"CustomRole\" with permissions \"PublishContent\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "When "); #line 23 testRunner.And("I have a user \"user1\" with roles \"CustomRole\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line 24 testRunner.And("I have a user \"user2\" with roles \"Administrator\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line 25 testRunner.Then("\"user1\" should be able to \"publish\" a \"Page\" owned by \"user2\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Then "); #line 26 testRunner.And("\"user1\" should be able to \"edit\" a \"Page\" owned by \"user2\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line 27 testRunner.And("\"user1\" should not be able to \"delete\" a \"Page\" owned by \"user2\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line hidden this.ScenarioCleanup(); } [NUnit.Framework.TestAttribute()] [NUnit.Framework.DescriptionAttribute("Users can create a Page if they have PublishOwnContent for Page")] public virtual void UsersCanCreateAPageIfTheyHavePublishOwnContentForPage() { TechTalk.SpecFlow.ScenarioInfo scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("Users can create a Page if they have PublishOwnContent for Page", ((string[])(null))); #line 29 this.ScenarioSetup(scenarioInfo); #line 30 testRunner.Given("I have installed Orchard", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Given "); #line 31 testRunner.When("I have a role \"CustomRole\" with permissions \"Publish_Page\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "When "); #line 32 testRunner.And("I have a user \"user1\" with roles \"CustomRole\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line 33 testRunner.Then("\"user1\" should be able to \"publish\" a \"Page\" owned by \"user1\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Then "); #line 34 testRunner.And("\"user1\" should be able to \"edit\" a \"Page\" owned by \"user1\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line 35 testRunner.And("\"user1\" should not be able to \"delete\" a \"Page\" owned by \"user1\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line hidden this.ScenarioCleanup(); } [NUnit.Framework.TestAttribute()] [NUnit.Framework.DescriptionAttribute("Users can create and edit a Page even if they only have the PublishOwnContent per" + "mission")] public virtual void UsersCanCreateAndEditAPageEvenIfTheyOnlyHaveThePublishOwnContentPermission() { TechTalk.SpecFlow.ScenarioInfo scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("Users can create and edit a Page even if they only have the PublishOwnContent per" + "mission", ((string[])(null))); #line 37 this.ScenarioSetup(scenarioInfo); #line 38 testRunner.Given("I have installed Orchard", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Given "); #line 39 testRunner.When("I have a role \"CustomRole\" with permissions \"PublishOwnContent\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "When "); #line 40 testRunner.And("I have a user \"user1\" with roles \"CustomRole\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line 41 testRunner.Then("\"user1\" should be able to \"publish\" a \"Page\" owned by \"user1\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Then "); #line 42 testRunner.And("\"user1\" should be able to \"edit\" a \"Page\" owned by \"user1\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line 43 testRunner.And("\"user1\" should not be able to \"delete\" a \"Page\" owned by \"user1\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line hidden this.ScenarioCleanup(); } [NUnit.Framework.TestAttribute()] [NUnit.Framework.DescriptionAttribute("Users can\'t edit a Page if they don\'t have the EditContent permission")] public virtual void UsersCanTEditAPageIfTheyDonTHaveTheEditContentPermission() { TechTalk.SpecFlow.ScenarioInfo scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("Users can\'t edit a Page if they don\'t have the EditContent permission", ((string[])(null))); #line 45 this.ScenarioSetup(scenarioInfo); #line 46 testRunner.Given("I have installed Orchard", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Given "); #line 47 testRunner.When("I have a role \"CustomRole\" with permissions \"DeleteContent\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "When "); #line 48 testRunner.And("I have a user \"user1\" with roles \"CustomRole\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line 49 testRunner.Then("\"user1\" should not be able to \"publish\" a \"Page\" owned by \"user1\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Then "); #line 50 testRunner.And("\"user1\" should not be able to \"edit\" a \"Page\" owned by \"user1\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line 51 testRunner.And("\"user1\" should be able to \"delete\" a \"Page\" owned by \"user1\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line hidden this.ScenarioCleanup(); } [NUnit.Framework.TestAttribute()] [NUnit.Framework.DescriptionAttribute("Users can\'t create a Page for others if they only have PublishOwnContent")] public virtual void UsersCanTCreateAPageForOthersIfTheyOnlyHavePublishOwnContent() { TechTalk.SpecFlow.ScenarioInfo scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("Users can\'t create a Page for others if they only have PublishOwnContent", ((string[])(null))); #line 53 this.ScenarioSetup(scenarioInfo); #line 54 testRunner.Given("I have installed Orchard", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Given "); #line 55 testRunner.When("I have a role \"CustomRole\" with permissions \"PublishOwnContent\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "When "); #line 56 testRunner.And("I have a user \"user1\" with roles \"CustomRole\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line 57 testRunner.And("I have a user \"user2\" with roles \"Administrator\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line 58 testRunner.Then("\"user1\" should not be able to \"publish\" a \"Page\" owned by \"user2\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Then "); #line 59 testRunner.And("\"user1\" should not be able to \"edit\" a \"Page\" owned by \"user2\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line 60 testRunner.And("\"user1\" should not be able to \"delete\" a \"Page\" owned by \"user2\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line hidden this.ScenarioCleanup(); } [NUnit.Framework.TestAttribute()] [NUnit.Framework.DescriptionAttribute("Users can\'t create a Page for others if they only have Publish_Page")] public virtual void UsersCanTCreateAPageForOthersIfTheyOnlyHavePublish_Page() { TechTalk.SpecFlow.ScenarioInfo scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("Users can\'t create a Page for others if they only have Publish_Page", ((string[])(null))); #line 62 this.ScenarioSetup(scenarioInfo); #line 63 testRunner.Given("I have installed Orchard", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Given "); #line 64 testRunner.When("I have a role \"CustomRole\" with permissions \"Publish_Page\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "When "); #line 65 testRunner.And("I have a user \"user1\" with roles \"CustomRole\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line 66 testRunner.And("I have a user \"user2\" with roles \"Administrator\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line 67 testRunner.Then("\"user1\" should be able to \"publish\" a \"Page\" owned by \"user2\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Then "); #line 68 testRunner.And("\"user1\" should be able to \"edit\" a \"Page\" owned by \"user2\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line 69 testRunner.And("\"user1\" should not be able to \"delete\" a \"Page\" owned by \"user2\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line hidden this.ScenarioCleanup(); } [NUnit.Framework.TestAttribute()] [NUnit.Framework.DescriptionAttribute("Users can create a Page for others if they only have Publish_Page")] public virtual void UsersCanCreateAPageForOthersIfTheyOnlyHavePublish_Page() { TechTalk.SpecFlow.ScenarioInfo scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("Users can create a Page for others if they only have Publish_Page", ((string[])(null))); #line 71 this.ScenarioSetup(scenarioInfo); #line 72 testRunner.Given("I have installed Orchard", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Given "); #line 73 testRunner.When("I have a role \"CustomRole\" with permissions \"Publish_Page\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "When "); #line 74 testRunner.And("I have a user \"user1\" with roles \"CustomRole\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line 75 testRunner.And("I have a user \"user2\" with roles \"Administrator\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line 76 testRunner.Then("\"user1\" should be able to \"publish\" a \"Page\" owned by \"user2\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Then "); #line 77 testRunner.And("\"user1\" should be able to \"edit\" a \"Page\" owned by \"user2\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line 78 testRunner.And("\"user1\" should not be able to \"delete\" a \"Page\" owned by \"user2\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line hidden this.ScenarioCleanup(); } [NUnit.Framework.TestAttribute()] [NUnit.Framework.DescriptionAttribute("Users can delete a Page for others if they only have Delete_Page")] public virtual void UsersCanDeleteAPageForOthersIfTheyOnlyHaveDelete_Page() { TechTalk.SpecFlow.ScenarioInfo scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("Users can delete a Page for others if they only have Delete_Page", ((string[])(null))); #line 80 this.ScenarioSetup(scenarioInfo); #line 81 testRunner.Given("I have installed Orchard", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Given "); #line 82 testRunner.When("I have a role \"CustomRole\" with permissions \"Delete_Page\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "When "); #line 83 testRunner.And("I have a user \"user1\" with roles \"CustomRole\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line 84 testRunner.And("I have a user \"user2\" with roles \"Administrator\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line 85 testRunner.Then("\"user1\" should not be able to \"publish\" a \"Page\" owned by \"user2\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Then "); #line 86 testRunner.And("\"user1\" should not be able to \"edit\" a \"Page\" owned by \"user2\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line 87 testRunner.And("\"user1\" should be able to \"delete\" a \"Page\" owned by \"user2\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line hidden this.ScenarioCleanup(); } [NUnit.Framework.TestAttribute()] [NUnit.Framework.DescriptionAttribute("Users can\'t delete a Page for others if they only have DeleteOwn_Page")] public virtual void UsersCanTDeleteAPageForOthersIfTheyOnlyHaveDeleteOwn_Page() { TechTalk.SpecFlow.ScenarioInfo scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("Users can\'t delete a Page for others if they only have DeleteOwn_Page", ((string[])(null))); #line 90 this.ScenarioSetup(scenarioInfo); #line 91 testRunner.Given("I have installed Orchard", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Given "); #line 92 testRunner.When("I have a role \"CustomRole\" with permissions \"DeleteOwn_Page\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "When "); #line 93 testRunner.And("I have a user \"user1\" with roles \"CustomRole\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line 94 testRunner.And("I have a user \"user2\" with roles \"Administrator\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line 95 testRunner.Then("\"user1\" should not be able to \"publish\" a \"Page\" owned by \"user2\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Then "); #line 96 testRunner.And("\"user1\" should not be able to \"edit\" a \"Page\" owned by \"user2\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line 97 testRunner.And("\"user1\" should not be able to \"delete\" a \"Page\" owned by \"user2\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line hidden this.ScenarioCleanup(); } } } #pragma warning restore #endregion
58.296407
255
0.647065
[ "BSD-3-Clause" ]
1996dylanriley/Orchard
src/Orchard.Specs/ContentRights.feature.cs
19,473
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.Globalization; using TestLibrary; /// <summary> /// UInt64.ToString(System.IFormatProvider) /// </summary> public class UInt64ToString1 { #region Public Methods public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; TestLibrary.TestFramework.LogInformation("[Negative]"); if (TestLibrary.Utilities.IsWindows) { // retVal = NegTest1() && retVal; // Disabled until neutral cultures are available } return retVal; } #region Positive Test Cases public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: Convert UInt64MaxValue to string value and using cultureinfo \"en-US\""); try { UInt64 u64 = UInt64.MaxValue; CultureInfo cultureInfo = new CultureInfo("en-US"); string str = u64.ToString(cultureInfo); if (str != "18446744073709551615") { TestLibrary.TestFramework.LogError("001", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: Convert UInt64MinValue to string value and using cultureinfo \"fr-FR\""); try { UInt64 u64 = UInt64.MinValue; CultureInfo cultureInfo = new CultureInfo("fr-FR"); string str = u64.ToString(cultureInfo); if (str != "0") { TestLibrary.TestFramework.LogError("003", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest3: A UInt64 number begin with zeros and using cultureinfo \"en-US\""); try { UInt64 u64 = 00009876; CultureInfo cultureInfo = new CultureInfo("en-US"); string str = u64.ToString(cultureInfo); if (str != "9876") { TestLibrary.TestFramework.LogError("005", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest4: Convert a random uint64 to string value and using \"en-GB\""); try { UInt64 u64 = this.GetInt64(0, UInt64.MaxValue); CultureInfo cultureInfo = new CultureInfo("en-GB"); string str = u64.ToString(cultureInfo); string str2 = Convert.ToString(u64); if (str != str2) { TestLibrary.TestFramework.LogError("007", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest5: The provider is a null reference"); try { UInt64 u64 = 000217639083000; CultureInfo cultureInfo = null; string str = u64.ToString(cultureInfo); if (str != "217639083000") { TestLibrary.TestFramework.LogError("009", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("010", "Unexpected exception: " + e); retVal = false; } return retVal; } #endregion #region Nagetive Test Cases public bool NegTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest1: The provider argument is invalid"); try { UInt64 u64 = 1234500233; CultureInfo cultureInfo = new CultureInfo("pl"); string str = u64.ToString(cultureInfo); TestLibrary.TestFramework.LogError("101", "The NotSupportedException is not thrown as expected"); retVal = false; } catch (NotSupportedException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("102", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } #endregion #endregion public static int Main() { UInt64ToString1 test = new UInt64ToString1(); TestLibrary.TestFramework.BeginTestCase("UInt64ToString1"); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } #region ForTestObject private UInt64 GetInt64(UInt64 minValue, UInt64 maxValue) { try { if (minValue == maxValue) { return minValue; } if (minValue < maxValue) { return minValue + (UInt64)TestLibrary.Generator.GetInt64(-55) % (maxValue - minValue); } } catch { throw; } return minValue; } #endregion }
28.259414
132
0.550933
[ "MIT" ]
AaronRobinsonMSFT/coreclr
tests/src/CoreMangLib/cti/system/uint64/uint64tostring2.cs
6,754
C#
using System.Collections.Generic; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Primitives; namespace Arbor.AspNetCore.Host.Hosting { public class ConfigurationWrapper : IConfigurationRoot { private readonly IConfigurationRoot _hostingContextConfiguration; public ConfigurationWrapper(IConfigurationRoot hostingContextConfiguration, ServiceProviderHolder serviceProviderHolder) { ServiceProviderHolder = serviceProviderHolder; _hostingContextConfiguration = hostingContextConfiguration; } public ServiceProviderHolder ServiceProviderHolder { get; } public IEnumerable<IConfigurationProvider> Providers => _hostingContextConfiguration.Providers; public string this[string key] { get => _hostingContextConfiguration[key]; set => _hostingContextConfiguration[key] = value; } public IEnumerable<IConfigurationSection> GetChildren() => _hostingContextConfiguration.GetChildren(); public IChangeToken GetReloadToken() => _hostingContextConfiguration.GetReloadToken(); public IConfigurationSection GetSection(string key) => _hostingContextConfiguration.GetSection(key); public void Reload() => _hostingContextConfiguration.Reload(); } }
37.166667
110
0.738416
[ "MIT" ]
niklaslundberg/Arbor.AspNetCore.Host
src/Arbor.AspNetCore.Host/Hosting/ConfigurationWrapper.cs
1,340
C#
/* * Copyright Amazon.com, Inc. or its affiliates. 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://aws.amazon.com/apache2.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. */ /* * Do not modify this file. This file is generated from the securityhub-2018-10-26.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.SecurityHub.Model { /// <summary> /// Details about the network interface /// </summary> public partial class AwsEc2NetworkInterfaceDetails { private AwsEc2NetworkInterfaceAttachment _attachment; private List<AwsEc2NetworkInterfaceIpV6AddressDetail> _ipV6Addresses = new List<AwsEc2NetworkInterfaceIpV6AddressDetail>(); private string _networkInterfaceId; private List<AwsEc2NetworkInterfacePrivateIpAddressDetail> _privateIpAddresses = new List<AwsEc2NetworkInterfacePrivateIpAddressDetail>(); private string _publicDnsName; private string _publicIp; private List<AwsEc2NetworkInterfaceSecurityGroup> _securityGroups = new List<AwsEc2NetworkInterfaceSecurityGroup>(); private bool? _sourceDestCheck; /// <summary> /// Gets and sets the property Attachment. /// <para> /// The network interface attachment. /// </para> /// </summary> public AwsEc2NetworkInterfaceAttachment Attachment { get { return this._attachment; } set { this._attachment = value; } } // Check to see if Attachment property is set internal bool IsSetAttachment() { return this._attachment != null; } /// <summary> /// Gets and sets the property IpV6Addresses. /// <para> /// The IPv6 addresses associated with the network interface. /// </para> /// </summary> public List<AwsEc2NetworkInterfaceIpV6AddressDetail> IpV6Addresses { get { return this._ipV6Addresses; } set { this._ipV6Addresses = value; } } // Check to see if IpV6Addresses property is set internal bool IsSetIpV6Addresses() { return this._ipV6Addresses != null && this._ipV6Addresses.Count > 0; } /// <summary> /// Gets and sets the property NetworkInterfaceId. /// <para> /// The ID of the network interface. /// </para> /// </summary> public string NetworkInterfaceId { get { return this._networkInterfaceId; } set { this._networkInterfaceId = value; } } // Check to see if NetworkInterfaceId property is set internal bool IsSetNetworkInterfaceId() { return this._networkInterfaceId != null; } /// <summary> /// Gets and sets the property PrivateIpAddresses. /// <para> /// The private IPv4 addresses associated with the network interface. /// </para> /// </summary> public List<AwsEc2NetworkInterfacePrivateIpAddressDetail> PrivateIpAddresses { get { return this._privateIpAddresses; } set { this._privateIpAddresses = value; } } // Check to see if PrivateIpAddresses property is set internal bool IsSetPrivateIpAddresses() { return this._privateIpAddresses != null && this._privateIpAddresses.Count > 0; } /// <summary> /// Gets and sets the property PublicDnsName. /// <para> /// The public DNS name of the network interface. /// </para> /// </summary> public string PublicDnsName { get { return this._publicDnsName; } set { this._publicDnsName = value; } } // Check to see if PublicDnsName property is set internal bool IsSetPublicDnsName() { return this._publicDnsName != null; } /// <summary> /// Gets and sets the property PublicIp. /// <para> /// The address of the Elastic IP address bound to the network interface. /// </para> /// </summary> public string PublicIp { get { return this._publicIp; } set { this._publicIp = value; } } // Check to see if PublicIp property is set internal bool IsSetPublicIp() { return this._publicIp != null; } /// <summary> /// Gets and sets the property SecurityGroups. /// <para> /// Security groups for the network interface. /// </para> /// </summary> public List<AwsEc2NetworkInterfaceSecurityGroup> SecurityGroups { get { return this._securityGroups; } set { this._securityGroups = value; } } // Check to see if SecurityGroups property is set internal bool IsSetSecurityGroups() { return this._securityGroups != null && this._securityGroups.Count > 0; } /// <summary> /// Gets and sets the property SourceDestCheck. /// <para> /// Indicates whether traffic to or from the instance is validated. /// </para> /// </summary> public bool SourceDestCheck { get { return this._sourceDestCheck.GetValueOrDefault(); } set { this._sourceDestCheck = value; } } // Check to see if SourceDestCheck property is set internal bool IsSetSourceDestCheck() { return this._sourceDestCheck.HasValue; } } }
32.673684
146
0.602448
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/SecurityHub/Generated/Model/AwsEc2NetworkInterfaceDetails.cs
6,208
C#
using System; using FubuMVC.Core.Packaging; using FubuMVC.Spark.SparkModel; namespace FubuMVC.Spark { public interface ITemplateFinderConvention { void Configure(TemplateFinder finder); } public class LambdaTemplateFinderConvention : ITemplateFinderConvention { private readonly Action<TemplateFinder> _configure; public LambdaTemplateFinderConvention(Action<TemplateFinder> configure) { _configure = configure; } public void Configure(TemplateFinder finder) { _configure(finder); } } public class DefaultTemplateFinderConventions : ITemplateFinderConvention { public void Configure(TemplateFinder finder) { finder.IncludeFile("*spark"); // TODO: This is not automatically synched with what the attacher looks for. finder.IncludeFile("bindings.xml"); finder.ExcludeHostDirectory(FubuMvcPackageFacility.FubuPackagesFolder); finder.ExcludeHostDirectory(FubuMvcPackageFacility.FubuPackagesFolder, FubuMvcPackageFacility.FubuContentFolder); finder.ExcludeHostDirectory(FubuMvcPackageFacility.FubuContentFolder); } } }
31.975
126
0.6724
[ "Apache-2.0" ]
uluhonolulu/fubumvc
src/FubuMVC.Spark/ITemplateFinderConvention.cs
1,281
C#
namespace lab4_lpf { partial class Form1 { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.echipa_label = new System.Windows.Forms.Label(); this.echipa_comboBox = new System.Windows.Forms.ComboBox(); this.adaugaEchipa_button = new System.Windows.Forms.Button(); this.flowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel(); this.adaugaJucator_button = new System.Windows.Forms.Button(); this.SuspendLayout(); // // echipa_label // this.echipa_label.AutoSize = true; this.echipa_label.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.echipa_label.Location = new System.Drawing.Point(15, 17); this.echipa_label.Name = "echipa_label"; this.echipa_label.Padding = new System.Windows.Forms.Padding(10); this.echipa_label.Size = new System.Drawing.Size(78, 40); this.echipa_label.TabIndex = 0; this.echipa_label.Text = "Echipa"; this.echipa_label.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; // // echipa_comboBox // this.echipa_comboBox.DropDownHeight = 150; this.echipa_comboBox.FormattingEnabled = true; this.echipa_comboBox.IntegralHeight = false; this.echipa_comboBox.ItemHeight = 13; this.echipa_comboBox.Location = new System.Drawing.Point(99, 27); this.echipa_comboBox.Name = "echipa_comboBox"; this.echipa_comboBox.Size = new System.Drawing.Size(265, 21); this.echipa_comboBox.TabIndex = 1; // // adaugaEchipa_button // this.adaugaEchipa_button.Location = new System.Drawing.Point(370, 25); this.adaugaEchipa_button.Name = "adaugaEchipa_button"; this.adaugaEchipa_button.Size = new System.Drawing.Size(132, 23); this.adaugaEchipa_button.TabIndex = 2; this.adaugaEchipa_button.Text = "Adauga Echipa Noua"; this.adaugaEchipa_button.UseVisualStyleBackColor = true; this.adaugaEchipa_button.Click += new System.EventHandler(this.adaugaEchipa_button_Click); // // flowLayoutPanel1 // this.flowLayoutPanel1.Location = new System.Drawing.Point(19, 61); this.flowLayoutPanel1.Name = "flowLayoutPanel1"; this.flowLayoutPanel1.Size = new System.Drawing.Size(483, 331); this.flowLayoutPanel1.TabIndex = 3; this.flowLayoutPanel1.Paint += new System.Windows.Forms.PaintEventHandler(this.flowLayoutPanel1_Paint); // // adaugaJucator_button // this.adaugaJucator_button.Location = new System.Drawing.Point(370, 399); this.adaugaJucator_button.Name = "adaugaJucator_button"; this.adaugaJucator_button.Size = new System.Drawing.Size(131, 39); this.adaugaJucator_button.TabIndex = 4; this.adaugaJucator_button.Text = "Adauga Jucator"; this.adaugaJucator_button.UseVisualStyleBackColor = true; this.adaugaJucator_button.Click += new System.EventHandler(this.adaugaJucator_button_Click); // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(800, 450); this.Controls.Add(this.adaugaJucator_button); this.Controls.Add(this.flowLayoutPanel1); this.Controls.Add(this.adaugaEchipa_button); this.Controls.Add(this.echipa_comboBox); this.Controls.Add(this.echipa_label); this.Name = "Form1"; this.Text = "LPF"; this.Load += new System.EventHandler(this.Form1_Load); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label echipa_label; private System.Windows.Forms.ComboBox echipa_comboBox; private System.Windows.Forms.Button adaugaEchipa_button; private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel1; private System.Windows.Forms.Button adaugaJucator_button; } }
45.444444
172
0.617077
[ "MIT" ]
adrianB3/mtp_lab
lab4_lpf/lab4_lpf/Form1.Designer.cs
5,319
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.Globalization; using System.IO; using NuGet.Common; namespace NuGet.Packaging.Signing { public sealed class SigningOptions : IDisposable { private readonly Lazy<Stream> _inputPackageStream; private readonly Lazy<Stream> _outputPackageStream; private bool _isDisposed; /// <summary> /// Readable stream for the package that will be used as an input for any signing operation. /// </summary> public Stream InputPackageStream { get { if (_isDisposed) { throw new ObjectDisposedException(nameof(SigningOptions)); } return _inputPackageStream.Value; } } /// <summary> /// Readable and writeable stream for the output package for any signing operation. /// </summary> public Stream OutputPackageStream { get { if (_isDisposed) { throw new ObjectDisposedException(nameof(SigningOptions)); } return _outputPackageStream.Value; } } /// <summary> /// Switch used to indicate if an existing signature should be overwritten. /// </summary> public bool Overwrite { get; } /// <summary> /// Provider to create a Signature that can be added to the package. /// </summary> public ISignatureProvider SignatureProvider { get; } /// <summary> /// Logger to be used to display the logs during the execution of signing actions. /// </summary> public ILogger Logger { get; } /// <summary>Instantiates a new <see cref="SigningOptions" /> object.</summary> /// <param name="inputPackageStream">A readable stream for the package that will be used as input for any /// signing operation.</param> /// <param name="outputPackageStream">A readable and writeable stream for the output package for any signing /// operation.</param> /// <param name="overwrite">A flag indicating if an existing signature should be overwritten.</param> /// <param name="signatureProvider">A provider to create a Signature that can be added to the package.</param> /// <param name="logger">A logger.</param> /// <remarks>Signing operations cannot be done in place; therefore, <paramref name="inputPackageStream"/> /// and <paramref name="outputPackageStream" /> should be different streams.</remarks> /// <exception cref="ArgumentNullException">Thrown if <paramref name="inputPackageStream" /> is <c>null</c>.</exception> /// <exception cref="ArgumentNullException">Thrown if <paramref name="outputPackageStream" /> is <c>null</c>.</exception> /// <exception cref="ArgumentNullException">Thrown if <paramref name="signatureProvider" /> is <c>null</c>.</exception> /// <exception cref="ArgumentNullException">Thrown if <paramref name="logger" /> is <c>null</c>.</exception> /// <exception cref="ArgumentException">Thrown if <paramref name="inputPackageStream" /> and /// <paramref name="outputPackageStream"/> are the same object.</exception> public SigningOptions( Lazy<Stream> inputPackageStream, Lazy<Stream> outputPackageStream, bool overwrite, ISignatureProvider signatureProvider, ILogger logger) { _inputPackageStream = inputPackageStream ?? throw new ArgumentNullException(nameof(inputPackageStream)); _outputPackageStream = outputPackageStream ?? throw new ArgumentNullException(nameof(outputPackageStream)); SignatureProvider = signatureProvider ?? throw new ArgumentNullException(nameof(signatureProvider)); Logger = logger ?? throw new ArgumentNullException(nameof(logger)); Overwrite = overwrite; } /// <summary>Creates a new <see cref="SigningOptions" /> object from file paths.</summary> /// <param name="inputPackageFilePath">The file path of the package that will be used as input for any /// signing operation.</param> /// <param name="outputPackageFilePath">The file path of the package that will be the output for any signing /// operation.</param> /// <param name="overwrite">A flag indicating if an existing signature should be overwritten.</param> /// <param name="signatureProvider">A provider to create a Signature that can be added to the package.</param> /// <param name="logger">A logger.</param> /// <remarks>Signing operations cannot be done in place; therefore, <paramref name="inputPackageFilePath"/> /// and <paramref name="outputPackageFilePath" /> should be different file paths.</remarks> /// <exception cref="ArgumentException">Thrown if <paramref name="inputPackageFilePath" /> is <c>null</c>, /// an empty string, or equivalent to <paramref name="outputPackageFilePath" />.</exception> /// <exception cref="ArgumentException">Thrown if <paramref name="inputPackageFilePath" /> is <c>null</c>, /// an empty string, or equivalent to <paramref name="outputPackageFilePath" />.</exception> /// <exception cref="ArgumentNullException">Thrown if <paramref name="signatureProvider" /> is <c>null</c>.</exception> /// <exception cref="ArgumentNullException">Thrown if <paramref name="logger" /> is <c>null</c>.</exception> public static SigningOptions CreateFromFilePaths( string inputPackageFilePath, string outputPackageFilePath, bool overwrite, ISignatureProvider signatureProvider, ILogger logger) { if (string.IsNullOrEmpty(inputPackageFilePath)) { throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(inputPackageFilePath)); } if (string.IsNullOrEmpty(outputPackageFilePath)) { throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(outputPackageFilePath)); } if (StringComparer.OrdinalIgnoreCase.Equals(NormalizeFilePath(inputPackageFilePath), NormalizeFilePath(outputPackageFilePath))) { throw new ArgumentException( string.Format( CultureInfo.CurrentCulture, Strings.SigningCannotBeDoneInPlace, nameof(inputPackageFilePath), nameof(outputPackageFilePath))); } if (signatureProvider == null) { throw new ArgumentNullException(nameof(signatureProvider)); } if (logger == null) { throw new ArgumentNullException(nameof(logger)); } return new SigningOptions( new Lazy<Stream>(() => File.OpenRead(inputPackageFilePath)), new Lazy<Stream>(() => File.Open(outputPackageFilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite)), overwrite, signatureProvider, logger); } public void Dispose() { if (!_isDisposed) { if (_inputPackageStream.IsValueCreated) { _inputPackageStream.Value.Dispose(); } if (_outputPackageStream.IsValueCreated) { _outputPackageStream.Value.Dispose(); } GC.SuppressFinalize(this); _isDisposed = true; } } private static string NormalizeFilePath(string filePath) { return Path.GetFullPath(filePath).TrimEnd('\\'); } } }
45.311111
139
0.611329
[ "Apache-2.0" ]
BdDsl/NuGet.Client
src/NuGet.Core/NuGet.Packaging/Signing/Authoring/SigningOptions.cs
8,156
C#
// __ _ __ __ ___ __ ___ ___ // | \| |/__\ /' _/ / _//__\| _ \ __| // | | ' | \/ |`._`.| \_| \/ | v / _| // |_|\__|\__/ |___/ \__/\__/|_|_\___| // ----------------------------------- namespace NosCore.Packets.Enumerations { public enum FactionType : byte { Neutral = 0, Angel = 1, Demon = 2 } }
22.8
38
0.374269
[ "MIT" ]
Fizo55/NosCore.Packets
src/NosCore.Packets/Enumerations/FactionType.cs
344
C#
using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace verfiedShops { public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } }
25.703704
70
0.645533
[ "MIT" ]
85nnamdi/verifiedShops
verfiedShops/Program.cs
694
C#
#region copyright // ----------------------------------------------------------------------- // <copyright file="ApplicationVersionSpec.cs" company="Bartosz Sypytkowski"> // Copyright (C) 2015-2019 Red Bull Media House GmbH <http://www.redbullmediahouse.com> // Copyright (C) 2019-2019 Bartosz Sypytkowski <b.sypytkowski@gmail.com> // </copyright> // ----------------------------------------------------------------------- #endregion using FluentAssertions; using System; using System.Collections.Generic; using System.Text; using Xunit; namespace Eventuate.Tests { public class ApplicationVersionSpec { [Fact] public void ApplicationVersion_should_be_equal() { (ApplicationVersion.Parse("1.0") == ApplicationVersion.Parse("1.0")).Should().Be(true); (ApplicationVersion.Parse("1.0") == ApplicationVersion.Parse("1.1")).Should().Be(false); } [Fact] public void ApplicationVersion_should_be_less_than() { (ApplicationVersion.Parse("0.9") < ApplicationVersion.Parse("1.0")).Should().Be(true); (ApplicationVersion.Parse("1.0") < ApplicationVersion.Parse("0.9")).Should().Be(false); } [Fact] public void ApplicationVersion_should_be_greater_than() { (ApplicationVersion.Parse("1.0") >= ApplicationVersion.Parse("1.0")).Should().Be(true); (ApplicationVersion.Parse("1.1") >= ApplicationVersion.Parse("1.0")).Should().Be(true); (ApplicationVersion.Parse("0.9") >= ApplicationVersion.Parse("1.0")).Should().Be(false); } } }
37.790698
100
0.585231
[ "Apache-2.0" ]
Horusiath/Eventuate.NET
src/Eventuate.Tests/ApplicationVersionSpec.cs
1,627
C#
using Abp.EntityFrameworkCore.Configuration; using Abp.Modules; using Abp.Reflection.Extensions; using Abp.Zero.EntityFrameworkCore; using AnJingBolerplateProject.EntityFrameworkCore.Seed; namespace AnJingBolerplateProject.EntityFrameworkCore { [DependsOn( typeof(AnJingBolerplateProjectCoreModule), typeof(AbpZeroCoreEntityFrameworkCoreModule))] public class AnJingBolerplateProjectEntityFrameworkModule : AbpModule { /* Used it tests to skip dbcontext registration, in order to use in-memory database of EF Core */ public bool SkipDbContextRegistration { get; set; } public bool SkipDbSeed { get; set; } public override void PreInitialize() { if (!SkipDbContextRegistration) { Configuration.Modules.AbpEfCore().AddDbContext<AnJingBolerplateProjectDbContext>(options => { if (options.ExistingConnection != null) { AnJingBolerplateProjectDbContextConfigurer.Configure(options.DbContextOptions, options.ExistingConnection); } else { AnJingBolerplateProjectDbContextConfigurer.Configure(options.DbContextOptions, options.ConnectionString); } }); } } public override void Initialize() { IocManager.RegisterAssemblyByConvention(typeof(AnJingBolerplateProjectEntityFrameworkModule).GetAssembly()); } public override void PostInitialize() { if (!SkipDbSeed) { SeedHelper.SeedHostDb(IocManager); } } } }
34.27451
131
0.618421
[ "MIT" ]
396122519/AnJingBolerplateProject
src/AnJingBolerplateProject.EntityFrameworkCore/EntityFrameworkCore/AnJingBolerplateProjectEntityFrameworkModule.cs
1,750
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/mmdeviceapi.h in the Windows SDK for Windows 10.0.19041.0 // Original source is Copyright © Microsoft. All rights reserved. using NUnit.Framework; using System; using System.Runtime.InteropServices; using static TerraFX.Interop.Windows; namespace TerraFX.Interop.UnitTests { /// <summary>Provides validation of the <see cref="IActivateAudioInterfaceAsyncOperation" /> struct.</summary> public static unsafe class IActivateAudioInterfaceAsyncOperationTests { /// <summary>Validates that the <see cref="Guid" /> of the <see cref="IActivateAudioInterfaceAsyncOperation" /> struct is correct.</summary> [Test] public static void GuidOfTest() { Assert.That(typeof(IActivateAudioInterfaceAsyncOperation).GUID, Is.EqualTo(IID_IActivateAudioInterfaceAsyncOperation)); } /// <summary>Validates that the <see cref="IActivateAudioInterfaceAsyncOperation" /> struct is blittable.</summary> [Test] public static void IsBlittableTest() { Assert.That(Marshal.SizeOf<IActivateAudioInterfaceAsyncOperation>(), Is.EqualTo(sizeof(IActivateAudioInterfaceAsyncOperation))); } /// <summary>Validates that the <see cref="IActivateAudioInterfaceAsyncOperation" /> struct has the right <see cref="LayoutKind" />.</summary> [Test] public static void IsLayoutSequentialTest() { Assert.That(typeof(IActivateAudioInterfaceAsyncOperation).IsLayoutSequential, Is.True); } /// <summary>Validates that the <see cref="IActivateAudioInterfaceAsyncOperation" /> struct has the correct size.</summary> [Test] public static void SizeOfTest() { if (Environment.Is64BitProcess) { Assert.That(sizeof(IActivateAudioInterfaceAsyncOperation), Is.EqualTo(8)); } else { Assert.That(sizeof(IActivateAudioInterfaceAsyncOperation), Is.EqualTo(4)); } } } }
42.173077
150
0.681259
[ "MIT" ]
Ethereal77/terrafx.interop.windows
tests/Interop/Windows/um/mmdeviceapi/IActivateAudioInterfaceAsyncOperationTests.cs
2,195
C#
using Application.Interfaces; using Application.Photos; using CloudinaryDotNet; using CloudinaryDotNet.Actions; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Options; using System; namespace Infrastructure.Photos { public class PhotoAccessor : IPhotoAccessor { private readonly Cloudinary _cloudinary; public PhotoAccessor(IOptions<CloudinarySettings> config) { var acc = new Account(config.Value.CloudName, config.Value.ApiKey, config.Value.ApiSecret); _cloudinary = new Cloudinary(acc); } public PhotoUploadResult AddPhoto(IFormFile file) { var uploadResult = new ImageUploadResult(); if(file.Length > 0) { using (var stream = file.OpenReadStream()) { var uploadParams = new ImageUploadParams { File = new FileDescription(file.FileName, stream), Transformation = new Transformation().Height(500).Width(500).Crop("fill").Gravity("face") }; uploadResult = _cloudinary.Upload(uploadParams); } } if (uploadResult.Error != null) throw new Exception(uploadResult.Error.Message); return new PhotoUploadResult { PublicId = uploadResult.PublicId, Url = uploadResult.SecureUri.AbsoluteUri }; } public string DeletePhoto(string publicId) { var deleteParams = new DeletionParams(publicId); var result = _cloudinary.Destroy(deleteParams); return result.Result == "ok" ? result.Result : null; } } }
30.237288
113
0.579036
[ "MIT" ]
helderboone/reactivity
infrastructure/Photos/PhotoAccessor.cs
1,786
C#
// MIT License // // Copyright (c) 2016-2018 Wojciech Nagórski // Michael DeMond // // 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 ExtendedXmlSerializer.Configuration; using ExtendedXmlSerializer.ExtensionModel.Xml; using ExtendedXmlSerializer.Tests.Support; using ExtendedXmlSerializer.Tests.TestObject; using System; using System.Globalization; using System.Xml.Linq; using Xunit; using XmlWriter = System.Xml.XmlWriter; namespace ExtendedXmlSerializer.Tests.ExtensionModel.Xml { public class CustomXmlExtensionTests { [Fact] public void Verify() { var serializer = new ConfigurationContainer().Type<TestClassWithSerializer>() .CustomSerializer(new CustomSerializer()) .Create(); var support = new SerializationSupport(serializer); var expected = new TestClassWithSerializer("String", 17); var actual = support.Assert(expected, @"<?xml version=""1.0"" encoding=""utf-8""?><TestClassWithSerializer xmlns=""clr-namespace:ExtendedXmlSerializer.Tests.TestObject;assembly=ExtendedXmlSerializer.Tests""><String>String</String><Int>17</Int></TestClassWithSerializer>" ); Assert.Equal(expected.PropInt, actual.PropInt); Assert.Equal(expected.PropStr, actual.PropStr); } class CustomSerializer : IExtendedXmlCustomSerializer<TestClassWithSerializer> { public TestClassWithSerializer Deserialize(XElement element) { var xElement = element.Member("String"); var xElement1 = element.Member("Int"); if (xElement != null && xElement1 != null) { var strValue = xElement.Value; var intValue = Convert.ToInt32(xElement1.Value); return new TestClassWithSerializer(strValue, intValue); } throw new InvalidOperationException("Invalid xml for class TestClassWithSerializer"); } public void Serializer(XmlWriter writer, TestClassWithSerializer obj) { writer.WriteElementString("String", obj.PropStr); writer.WriteElementString("Int", obj.PropInt.ToString(CultureInfo.InvariantCulture)); } } } }
41.552632
263
0.728309
[ "MIT" ]
SuricateCan/ExtendedXmlSerializer
test/ExtendedXmlSerializer.Tests/ExtensionModel/Xml/CustomXmlExtensionTests.cs
3,161
C#
// <auto-generated> // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v4/enums/user_list_prepopulation_status.proto // </auto-generated> #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Google.Ads.GoogleAds.V4.Enums { /// <summary>Holder for reflection information generated from google/ads/googleads/v4/enums/user_list_prepopulation_status.proto</summary> public static partial class UserListPrepopulationStatusReflection { #region Descriptor /// <summary>File descriptor for google/ads/googleads/v4/enums/user_list_prepopulation_status.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static UserListPrepopulationStatusReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CkJnb29nbGUvYWRzL2dvb2dsZWFkcy92NC9lbnVtcy91c2VyX2xpc3RfcHJl", "cG9wdWxhdGlvbl9zdGF0dXMucHJvdG8SHWdvb2dsZS5hZHMuZ29vZ2xlYWRz", "LnY0LmVudW1zGhxnb29nbGUvYXBpL2Fubm90YXRpb25zLnByb3RvIocBCh9V", "c2VyTGlzdFByZXBvcHVsYXRpb25TdGF0dXNFbnVtImQKG1VzZXJMaXN0UHJl", "cG9wdWxhdGlvblN0YXR1cxIPCgtVTlNQRUNJRklFRBAAEgsKB1VOS05PV04Q", "ARINCglSRVFVRVNURUQQAhIMCghGSU5JU0hFRBADEgoKBkZBSUxFRBAEQvUB", "CiFjb20uZ29vZ2xlLmFkcy5nb29nbGVhZHMudjQuZW51bXNCIFVzZXJMaXN0", "UHJlcG9wdWxhdGlvblN0YXR1c1Byb3RvUAFaQmdvb2dsZS5nb2xhbmcub3Jn", "L2dlbnByb3RvL2dvb2dsZWFwaXMvYWRzL2dvb2dsZWFkcy92NC9lbnVtcztl", "bnVtc6ICA0dBQaoCHUdvb2dsZS5BZHMuR29vZ2xlQWRzLlY0LkVudW1zygId", "R29vZ2xlXEFkc1xHb29nbGVBZHNcVjRcRW51bXPqAiFHb29nbGU6OkFkczo6", "R29vZ2xlQWRzOjpWNDo6RW51bXNiBnByb3RvMw==")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::Google.Api.AnnotationsReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Ads.GoogleAds.V4.Enums.UserListPrepopulationStatusEnum), global::Google.Ads.GoogleAds.V4.Enums.UserListPrepopulationStatusEnum.Parser, null, null, new[]{ typeof(global::Google.Ads.GoogleAds.V4.Enums.UserListPrepopulationStatusEnum.Types.UserListPrepopulationStatus) }, null, null) })); } #endregion } #region Messages /// <summary> /// Indicates status of prepopulation based on the rule. /// </summary> public sealed partial class UserListPrepopulationStatusEnum : pb::IMessage<UserListPrepopulationStatusEnum> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<UserListPrepopulationStatusEnum> _parser = new pb::MessageParser<UserListPrepopulationStatusEnum>(() => new UserListPrepopulationStatusEnum()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<UserListPrepopulationStatusEnum> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Ads.GoogleAds.V4.Enums.UserListPrepopulationStatusReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public UserListPrepopulationStatusEnum() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public UserListPrepopulationStatusEnum(UserListPrepopulationStatusEnum other) : this() { _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public UserListPrepopulationStatusEnum Clone() { return new UserListPrepopulationStatusEnum(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as UserListPrepopulationStatusEnum); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(UserListPrepopulationStatusEnum other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(UserListPrepopulationStatusEnum other) { if (other == null) { return; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; } } } #endif #region Nested types /// <summary>Container for nested types declared in the UserListPrepopulationStatusEnum message type.</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static partial class Types { /// <summary> /// Enum describing possible user list prepopulation status. /// </summary> public enum UserListPrepopulationStatus { /// <summary> /// Not specified. /// </summary> [pbr::OriginalName("UNSPECIFIED")] Unspecified = 0, /// <summary> /// Used for return value only. Represents value unknown in this version. /// </summary> [pbr::OriginalName("UNKNOWN")] Unknown = 1, /// <summary> /// Prepopoulation is being requested. /// </summary> [pbr::OriginalName("REQUESTED")] Requested = 2, /// <summary> /// Prepopulation is finished. /// </summary> [pbr::OriginalName("FINISHED")] Finished = 3, /// <summary> /// Prepopulation failed. /// </summary> [pbr::OriginalName("FAILED")] Failed = 4, } } #endregion } #endregion } #endregion Designer generated code
37.743363
344
0.704572
[ "Apache-2.0" ]
GraphikaPS/google-ads-dotnet
src/V4/Types/UserListPrepopulationStatus.cs
8,530
C#
namespace Retlang.Channels { /// <summary> /// /// </summary> /// <typeparam name="R"></typeparam> /// <typeparam name="M"></typeparam> public interface IRequestPublisher<R, M> { /// <summary> /// Send request on the channel. /// </summary> /// <param name="request"></param> /// <returns></returns> IReply<M> SendRequest(R request); } }
24.222222
45
0.495413
[ "BSD-3-Clause" ]
David-Desmaisons/Fiber
src/Retlang/Channels/IRequestPublisher.cs
436
C#
// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // 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. // // ------------------------------------------------------------------------------- // SharpYaml is a fork of YamlDotNet https://github.com/aaubry/YamlDotNet // published with the following license: // ------------------------------------------------------------------------------- // // Copyright (c) 2008, 2009, 2010, 2011, 2012 Antoine Aubry // // 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 Stride.Core.Yaml.Serialization; namespace Stride.Core.Yaml.Tests.Serialization { public class TracingVisitor : YamlVisitor { private int indent = 0; private void WriteIndent() { for (int i = 0; i < indent; ++i) { Console.Write(" "); } } protected override void Visit(YamlDocument document) { WriteIndent(); Console.WriteLine("Visit(YamlDocument)"); ++indent; } protected override void Visit(YamlMappingNode mapping) { WriteIndent(); Console.WriteLine("Visit(YamlMapping, {0}, {1})", mapping.Anchor, mapping.Tag); ++indent; } protected override void Visit(YamlScalarNode scalar) { WriteIndent(); Console.WriteLine("Visit(YamlScalarNode, {0}, {1}) - {2}", scalar.Anchor, scalar.Tag, scalar.Value); ++indent; } protected override void Visit(YamlSequenceNode sequence) { WriteIndent(); Console.WriteLine("Visit(YamlSequenceNode, {0}, {1})", sequence.Anchor, sequence.Tag); ++indent; } protected override void Visit(YamlStream stream) { WriteIndent(); Console.WriteLine("Visit(YamlStream)"); ++indent; } protected override void Visited(YamlDocument document) { --indent; WriteIndent(); Console.WriteLine("Visited(YamlDocument)"); } protected override void Visited(YamlMappingNode mapping) { --indent; WriteIndent(); Console.WriteLine("Visited(YamlMappingNode)"); } protected override void Visited(YamlScalarNode scalar) { --indent; WriteIndent(); Console.WriteLine("Visited(YamlScalarNode)"); } protected override void Visited(YamlSequenceNode sequence) { --indent; WriteIndent(); Console.WriteLine("Visited(YamlSequenceNode)"); } protected override void Visited(YamlStream stream) { --indent; WriteIndent(); Console.WriteLine("Visited(YamlStream)"); } } }
37.112782
112
0.62581
[ "MIT" ]
Aggror/Stride
sources/core/Stride.Core.Yaml.Tests/Serialization/TracingVisitor.cs
4,936
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Translator { abstract public class Assembler { public const string FLAG_HANA_CONCAT = "HANAConcat"; private HashSet<string> flags = new HashSet<string>(); abstract public void Clear(); virtual public void NewLine() { } virtual public void IncreaseIndentation() { } virtual public void DecreaseIndentation() { } virtual public void Breakable() { } virtual public void Begin(GrammarNode node) { } virtual public void End(GrammarNode node) { } public void SetFlag(string flag) { flags.Add(flag); } public void ClearFlag(string flag) { flags.Remove(flag); } public bool IsFlag(string flag) { return flags.Contains(flag); } abstract public void AddSpace(); abstract public void AddToken(string right); abstract public void Add(string right); abstract public void Add(decimal right); abstract public void Add(int right); virtual public void Add(GrammarNode node) { node.Assembly(this); } virtual public void Add(Statement stmt) { stmt.Assembly(this); } virtual public void HandleComments(GrammarNode node) { } } }
21.71831
64
0.553178
[ "MIT" ]
B1SA/HanaTranslator-Src
Translator/Assembler.cs
1,544
C#
using System; using System.Collections.Generic; using System.Text; namespace CarManufacturer { public class Tire { private int year; private double pressure; public Tire(int year, double pressure) { this.Year = year; this.Pressure = pressure; } public int Year { get { return this.year; } set { this.year = value; } } public double Pressure { get { return this.pressure; } set { this.pressure = value; } } } }
18.935484
46
0.50937
[ "MIT" ]
aalishov/School
School-2021_2022/11_B/M01-OOP/S05-ClassesAndObjects/P04-CarWithEngineAndTires/Tire.cs
589
C#
using System.Collections.Generic; namespace AnalyzeMe.Tests.TestFixtures { public static class RxSubscribeMethodTestFixtures { private const string Source = @"using System; namespace System { public static class ObservableExtensions { public static IDisposable Subscribe<T>(this IObservable<T> source) { return null; } public static IDisposable Subscribe<T>(this IObservable<T> source, Action<T> onNext) { return null; } public static IDisposable Subscribe<T>(this IObservable<T> source, Action<T> onNext, Action onCompleted) { return null; } public static IDisposable Subscribe<T>(this IObservable<T> source, Action<T> onNext, Action<Exception> onError) { return null; } public static IDisposable Subscribe<T>(this IObservable<T> source, Action<T> onNext, Action<Exception> onError, Action onCompleted) { return null; } } } namespace Test { public class Foo { public void OnNextHandler(object val){} public void OnCompletedHandler(){} public void Bar() { IObservable<object> observable = null; {0} } } }"; public static IEnumerable<object[]> OnErrorParameterExists() { yield return new object[] { FormatSrc(@"observable.Subscribe(onError: _ => { }, onNext: _ => { }, onCompleted: () => { });") }; yield return new object[] { FormatSrc(@"observable.Subscribe(nextValue => { }, ex => { }, () => { });") }; yield return new object[] { FormatSrc(@"observable.Subscribe(nextValue => { }, ex => { });") }; } public static IEnumerable<object[]> MethodInvocationDoesNotHaveOnErrorParameter() { var actual = @"observable.Subscribe(OnNextHandler /*Comment*/);"; var expected = @"observable.Subscribe(OnNextHandler /*Comment*/, ex => { /*TODO: handle this!*/ });"; yield return new object[] { new SourceFixture(FormatSrc(actual), FormatSrc(expected)) }; actual = @"observable.Subscribe( OnNextHandler /*Comment*/);"; expected = @"observable.Subscribe( OnNextHandler /*Comment*/, ex => { /*TODO: handle this!*/ });"; yield return new object[] { new SourceFixture(FormatSrc(actual), FormatSrc(expected)) }; actual = @"observable.Subscribe( OnNextHandler /*Comment*/ );"; expected = @"observable.Subscribe( OnNextHandler /*Comment*/, ex => { /*TODO: handle this!*/ });"; yield return new object[] { new SourceFixture(FormatSrc(actual), FormatSrc(expected)) }; actual = @"observable.Subscribe( onNext: OnNextHandler /*Comment*/);"; expected = @"observable.Subscribe( onNext: OnNextHandler /*Comment*/, onError: ex => { /*TODO: handle this!*/ });"; yield return new object[] { new SourceFixture(FormatSrc(actual), FormatSrc(expected)) }; actual = @"observable.Subscribe( onNext: OnNextHandler /*Comment*/ );"; expected = @"observable.Subscribe( onNext: OnNextHandler /*Comment*/, onError: ex => { /*TODO: handle this!*/ });"; yield return new object[] { new SourceFixture(FormatSrc(actual), FormatSrc(expected)) }; actual = @"observable.Subscribe(OnNextHandler /*Comment*/, /*Comment*/OnCompletedHandler);"; expected = @"observable.Subscribe(OnNextHandler /*Comment*/, ex => { /*TODO: handle this!*/ }, /*Comment*/OnCompletedHandler);"; yield return new object[] { new SourceFixture(FormatSrc(actual), FormatSrc(expected)) }; actual = @"observable.Subscribe( OnNextHandler /*Comment*/, /*Comment*/OnCompletedHandler);"; expected = @"observable.Subscribe( OnNextHandler /*Comment*/, ex => { /*TODO: handle this!*/ }, /*Comment*/OnCompletedHandler);"; yield return new object[] { new SourceFixture(FormatSrc(actual), FormatSrc(expected)) }; actual = @"observable.Subscribe( OnNextHandler /*Comment*/, /*Comment*/OnCompletedHandler);"; expected = @"observable.Subscribe( OnNextHandler /*Comment*/, ex => { /*TODO: handle this!*/ }, /*Comment*/OnCompletedHandler);"; yield return new object[] { new SourceFixture(FormatSrc(actual), FormatSrc(expected)) }; actual = @"observable.Subscribe( OnNextHandler /*Comment*/, /*Comment*/OnCompletedHandler );"; expected = @"observable.Subscribe( OnNextHandler /*Comment*/, ex => { /*TODO: handle this!*/ }, /*Comment*/OnCompletedHandler );"; yield return new object[] { new SourceFixture(FormatSrc(actual), FormatSrc(expected)) }; actual = @"observable.Subscribe( onNext: OnNextHandler /*Comment*/, onCompleted: /*Comment*/OnCompletedHandler);"; expected = @"observable.Subscribe( onNext: OnNextHandler /*Comment*/, onCompleted: /*Comment*/OnCompletedHandler, onError: ex => { /*TODO: handle this!*/ });"; yield return new object[] { new SourceFixture(FormatSrc(actual), FormatSrc(expected)) }; actual = @"observable.Subscribe( onNext: OnNextHandler /*Comment*/, onCompleted: /*Comment*/OnCompletedHandler );"; expected = @"observable.Subscribe( onNext: OnNextHandler /*Comment*/, onCompleted: /*Comment*/OnCompletedHandler, onError: ex => { /*TODO: handle this!*/ });"; yield return new object[] { new SourceFixture(FormatSrc(actual), FormatSrc(expected)) }; actual = @"observable.Subscribe( _ => { } /* */);"; expected = @"observable.Subscribe( _ => { } /* */, ex => { /*TODO: handle this!*/ });"; yield return new object[] { new SourceFixture(FormatSrc(actual), FormatSrc(expected)) }; actual = @"observable.Subscribe( _ => { } /*Comment after onNext*/ , () => { });"; expected = @"observable.Subscribe( _ => { } /*Comment after onNext*/, ex => { /*TODO: handle this!*/ }, () => { });"; yield return new object[] { new SourceFixture(FormatSrc(actual), FormatSrc(expected)) }; actual = @"observable.Subscribe( _ => { } );"; expected = @"observable.Subscribe( _ => { }, ex => { /*TODO: handle this!*/ });"; yield return new object[] { new SourceFixture(FormatSrc(actual), FormatSrc(expected)) }; actual = @"observable.Subscribe(_ => { });"; expected = @"observable.Subscribe(_ => { }, ex => { /*TODO: handle this!*/ });"; yield return new object[] { new SourceFixture(FormatSrc(actual), FormatSrc(expected)) }; actual = @"observable.Subscribe( /* Comment before onNext */ nextValue => { } );"; expected = @"observable.Subscribe( /* Comment before onNext */ nextValue => { }, ex => { /*TODO: handle this!*/ });"; yield return new object[] { new SourceFixture(FormatSrc(actual), FormatSrc(expected)) }; actual = @"observable.Subscribe( /* Comment before onNext */ nextValue => { }, () => { } );"; expected = @"observable.Subscribe( /* Comment before onNext */ nextValue => { }, ex => { /*TODO: handle this!*/ }, () => { } );"; yield return new object[] { new SourceFixture(FormatSrc(actual), FormatSrc(expected)) }; actual = @"observable.Subscribe( nextValue => { } /*Trailing onNext comment*/, () => { } );"; expected = @"observable.Subscribe( nextValue => { } /*Trailing onNext comment*/, ex => { /*TODO: handle this!*/ }, () => { } );"; yield return new object[] { new SourceFixture(FormatSrc(actual), FormatSrc(expected)) }; actual = @"observable.Subscribe( nextValue => { }, /*Trailing onCompleted comma comment*/ () => { } );"; expected = @"observable.Subscribe( nextValue => { }, ex => { /*TODO: handle this!*/ }, /*Trailing onCompleted comma comment*/ () => { } );"; yield return new object[] { new SourceFixture(FormatSrc(actual), FormatSrc(expected)) }; actual = @"observable.Subscribe( /* Comment before onNext */ nextValue => { });"; expected = @"observable.Subscribe( /* Comment before onNext */ nextValue => { }, ex => { /*TODO: handle this!*/ });"; yield return new object[] { new SourceFixture(FormatSrc(actual), FormatSrc(expected)) }; actual = @"observable.Subscribe(nextValue => { Console.WriteLine(); }, () => { /*Some comment*/ });"; expected = @"observable.Subscribe(nextValue => { Console.WriteLine(); }, ex => { /*TODO: handle this!*/ }, () => { /*Some comment*/ });"; yield return new object[] { new SourceFixture(FormatSrc(actual), FormatSrc(expected)) }; actual = @"observable.Subscribe( nextValue => { Console.WriteLine(); }, () => { /*Some comment*/ });"; expected = @"observable.Subscribe( nextValue => { Console.WriteLine(); }, ex => { /*TODO: handle this!*/ }, () => { /*Some comment*/ });"; yield return new object[] { new SourceFixture(FormatSrc(actual), FormatSrc(expected)) }; actual = @"observable.Subscribe( /* Comment before onNext */ onNext: nextValue => { } /*OnNext argument trailing comment*/ );"; expected = @"observable.Subscribe( /* Comment before onNext */ onNext: nextValue => { } /*OnNext argument trailing comment*/, onError: ex => { /*TODO: handle this!*/ });"; yield return new object[] { new SourceFixture(FormatSrc(actual), FormatSrc(expected)) }; actual = @"observable.Subscribe( /* Comment before onNext */ onNext: nextValue => { } /*OnNext argument trailing comment*/);"; expected = @"observable.Subscribe( /* Comment before onNext */ onNext: nextValue => { } /*OnNext argument trailing comment*/, onError: ex => { /*TODO: handle this!*/ });"; yield return new object[] { new SourceFixture(FormatSrc(actual), FormatSrc(expected)) }; actual = @"observable.Subscribe(onCompleted: () => { }, onNext: nextValue => { } /*Trailing onNext comment*/);"; expected = @"observable.Subscribe(onCompleted: () => { }, onNext: nextValue => { } /*Trailing onNext comment*/, onError: ex => { /*TODO: handle this!*/ });"; yield return new object[] { new SourceFixture(FormatSrc(actual), FormatSrc(expected)) }; actual = @"observable.Subscribe( onCompleted: () => { }, onNext: nextValue => { } );"; expected = @"observable.Subscribe( onCompleted: () => { }, onNext: nextValue => { }, onError: ex => { /*TODO: handle this!*/ });"; yield return new object[] { new SourceFixture(FormatSrc(actual), FormatSrc(expected)) }; actual = @"observable.Subscribe( onCompleted: () => { }, onNext: nextValue => { });"; expected = @"observable.Subscribe( onCompleted: () => { }, onNext: nextValue => { }, onError: ex => { /*TODO: handle this!*/ });"; yield return new object[] { new SourceFixture(FormatSrc(actual), FormatSrc(expected)) }; actual = @"observable.Subscribe( onCompleted: () => { Console.WriteLine(); }, /* Comment before onNext*/ onNext: nextValue => { Console.WriteLine(); } /*Trailing onNext comment*/);"; expected = @"observable.Subscribe( onCompleted: () => { Console.WriteLine(); }, /* Comment before onNext*/ onNext: nextValue => { Console.WriteLine(); } /*Trailing onNext comment*/, onError: ex => { /*TODO: handle this!*/ });"; yield return new object[] { new SourceFixture(FormatSrc(actual), FormatSrc(expected)) }; } private static string FormatSrc(string insertionSrc) { return Source.Replace("{0}", insertionSrc); } } }
36.563981
140
0.45593
[ "MIT" ]
DrunkyBard/AnalyzeMe
src/AnalyzeMe/AnalyzeMe.Tests/TestFixtures/RxSubscribeMethodTestFixtures.cs
15,432
C#
#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) using System; using System.Threading; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.Digests; using Org.BouncyCastle.Crypto.Prng; using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Security { public class SecureRandom : Random { private static long counter = Times.NanoTime(); #if NETCF_1_0 || PORTABLE private static object counterLock = new object(); private static long NextCounterValue() { lock (counterLock) { return ++counter; } } private static readonly SecureRandom[] master = { null }; private static SecureRandom Master { get { lock (master) { if (master[0] == null) { SecureRandom sr = master[0] = GetInstance("SHA256PRNG", false); // Even though Ticks has at most 8 or 14 bits of entropy, there's no harm in adding it. sr.SetSeed(DateTime.Now.Ticks); // 32 will be enough when ThreadedSeedGenerator is fixed. Until then, ThreadedSeedGenerator returns low // entropy, and this is not sufficient to be secure. http://www.bouncycastle.org/csharpdevmailarchive/msg00814.html sr.SetSeed(new ThreadedSeedGenerator().GenerateSeed(32, true)); } return master[0]; } } } #else private static long NextCounterValue() { return Interlocked.Increment(ref counter); } private static readonly SecureRandom master = new SecureRandom(new CryptoApiRandomGenerator()); private static SecureRandom Master { get { return master; } } #endif private static DigestRandomGenerator CreatePrng(string digestName, bool autoSeed) { IDigest digest = DigestUtilities.GetDigest(digestName); if (digest == null) return null; DigestRandomGenerator prng = new DigestRandomGenerator(digest); if (autoSeed) { prng.AddSeedMaterial(NextCounterValue()); prng.AddSeedMaterial(GetNextBytes(Master, digest.GetDigestSize())); } return prng; } public static byte[] GetNextBytes(SecureRandom secureRandom, int length) { byte[] result = new byte[length]; secureRandom.NextBytes(result); return result; } /// <summary> /// Create and auto-seed an instance based on the given algorithm. /// </summary> /// <remarks>Equivalent to GetInstance(algorithm, true)</remarks> /// <param name="algorithm">e.g. "SHA256PRNG"</param> public static SecureRandom GetInstance(string algorithm) { return GetInstance(algorithm, true); } /// <summary> /// Create an instance based on the given algorithm, with optional auto-seeding /// </summary> /// <param name="algorithm">e.g. "SHA256PRNG"</param> /// <param name="autoSeed">If true, the instance will be auto-seeded.</param> public static SecureRandom GetInstance(string algorithm, bool autoSeed) { string upper = Platform.ToUpperInvariant(algorithm); if (Platform.EndsWith(upper, "PRNG")) { string digestName = upper.Substring(0, upper.Length - "PRNG".Length); DigestRandomGenerator prng = CreatePrng(digestName, autoSeed); if (prng != null) { return new SecureRandom(prng); } } throw new ArgumentException("Unrecognised PRNG algorithm: " + algorithm, "algorithm"); } [Obsolete("Call GenerateSeed() on a SecureRandom instance instead")] public static byte[] GetSeed(int length) { return GetNextBytes(Master, length); } protected readonly IRandomGenerator generator; public SecureRandom() : this(CreatePrng("SHA256", true)) { } /// <remarks> /// To replicate existing predictable output, replace with GetInstance("SHA1PRNG", false), followed by SetSeed(seed) /// </remarks> [Obsolete("Use GetInstance/SetSeed instead")] public SecureRandom(byte[] seed) : this(CreatePrng("SHA1", false)) { SetSeed(seed); } /// <summary>Use the specified instance of IRandomGenerator as random source.</summary> /// <remarks> /// This constructor performs no seeding of either the <c>IRandomGenerator</c> or the /// constructed <c>SecureRandom</c>. It is the responsibility of the client to provide /// proper seed material as necessary/appropriate for the given <c>IRandomGenerator</c> /// implementation. /// </remarks> /// <param name="generator">The source to generate all random bytes from.</param> public SecureRandom(IRandomGenerator generator) : base(0) { this.generator = generator; } public virtual byte[] GenerateSeed(int length) { return GetNextBytes(Master, length); } public virtual void SetSeed(byte[] seed) { generator.AddSeedMaterial(seed); } public virtual void SetSeed(long seed) { generator.AddSeedMaterial(seed); } public override int Next() { return NextInt() & int.MaxValue; } public override int Next(int maxValue) { if (maxValue < 2) { if (maxValue < 0) throw new ArgumentOutOfRangeException("maxValue", "cannot be negative"); return 0; } int bits; // Test whether maxValue is a power of 2 if ((maxValue & (maxValue - 1)) == 0) { bits = NextInt() & int.MaxValue; return (int)(((long)bits * maxValue) >> 31); } int result; do { bits = NextInt() & int.MaxValue; result = bits % maxValue; } while (bits - result + (maxValue - 1) < 0); // Ignore results near overflow return result; } public override int Next(int minValue, int maxValue) { if (maxValue <= minValue) { if (maxValue == minValue) return minValue; throw new ArgumentException("maxValue cannot be less than minValue"); } int diff = maxValue - minValue; if (diff > 0) return minValue + Next(diff); for (;;) { int i = NextInt(); if (i >= minValue && i < maxValue) return i; } } public override void NextBytes(byte[] buf) { generator.NextBytes(buf); } public virtual void NextBytes(byte[] buf, int off, int len) { generator.NextBytes(buf, off, len); } private static readonly double DoubleScale = System.Math.Pow(2.0, 64.0); public override double NextDouble() { return Convert.ToDouble((ulong) NextLong()) / DoubleScale; } public virtual int NextInt() { byte[] bytes = new byte[4]; NextBytes(bytes); uint result = bytes[0]; result <<= 8; result |= bytes[1]; result <<= 8; result |= bytes[2]; result <<= 8; result |= bytes[3]; return (int)result; } public virtual long NextLong() { return ((long)(uint) NextInt() << 32) | (long)(uint) NextInt(); } } } #endif
31.981273
140
0.513643
[ "MIT" ]
czlsy009/UnityAppMVCFramework
Framework/Assets/SilenceFramework/Libs/Best HTTP (Pro)/BestHTTP/SecureProtocol/security/SecureRandom.cs
8,539
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class LevelManager : MonoBehaviour { [SerializeField] List<GameObject> MaterialObjects = new List<GameObject>(); [SerializeField] GameObject levelTileMap; [SerializeField] public float xCoordLow = 0; [SerializeField] public float xCoordHigh = 0; [SerializeField] public float yCoordLow = 0; [SerializeField] public float yCoordHigh = 0; void Start() { Renderer tileRenderer = levelTileMap.GetComponent<Renderer>(); xCoordHigh = tileRenderer.bounds.max.x; yCoordHigh = tileRenderer.bounds.max.y; xCoordLow = tileRenderer.bounds.min.x; yCoordLow = tileRenderer.bounds.min.y; } void Update() { } }
27.892857
79
0.68886
[ "MIT" ]
Airtoum/EllumiTheFireSprite
Assets/Level Scripts/LevelManager.cs
781
C#
using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading.Tasks; using Dive.App.Data; using Xunit; namespace Dive.Tests.Integration.Authentication { public class RegisterTest : IClassFixture<TestApplicationFixture> { public HttpClient Client { get; } public DiveContext Context { get; } public RegisterTest(TestApplicationFixture app) { Client = app.CreateClient(); Context = app.CreateContext(); } [Fact] public async Task a_visitor_can_create_an_account() { var response = await Client.PostAsync("/register", new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("email", "jake@example.com"), new KeyValuePair<string, string>("username", "jake"), new KeyValuePair<string, string>("password", "Test1234!"), })); Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal("/login", TestUtilities.ResponseUrl(response)); Assert.Equal("jake", Context.Users.Where(u => u.Id == 3).First().UserName); } } }
32.128205
95
0.601756
[ "MIT" ]
Robert-Jan/dive
tests/Integration/Authentication/RegisterTest.cs
1,253
C#
namespace MassTransit.Middleware { using System; using System.Diagnostics; using System.Threading.Tasks; using Logging; /// <summary> /// Consumes a message via Consumer, resolved through the consumer factory and notifies the context that the message was consumed. /// </summary> /// <typeparam name="TConsumer">The consumer type</typeparam> /// <typeparam name="TMessage">The message type</typeparam> public class ConsumerMessageFilter<TConsumer, TMessage> : IFilter<ConsumeContext<TMessage>> where TConsumer : class where TMessage : class { readonly IConsumerFactory<TConsumer> _consumerFactory; readonly IPipe<ConsumerConsumeContext<TConsumer, TMessage>> _consumerPipe; public ConsumerMessageFilter(IConsumerFactory<TConsumer> consumerFactory, IPipe<ConsumerConsumeContext<TConsumer, TMessage>> consumerPipe) { _consumerFactory = consumerFactory; _consumerPipe = consumerPipe; } void IProbeSite.Probe(ProbeContext context) { var scope = context.CreateScope("consumer"); scope.Add("type", TypeCache<TConsumer>.ShortName); _consumerFactory.Probe(scope); _consumerPipe.Probe(scope); } [DebuggerNonUserCode] async Task IFilter<ConsumeContext<TMessage>>.Send(ConsumeContext<TMessage> context, IPipe<ConsumeContext<TMessage>> next) { StartedActivity? activity = LogContext.IfEnabled(OperationName.Consumer.Consume)?.StartConsumerActivity<TConsumer, TMessage>(context); var timer = Stopwatch.StartNew(); try { await _consumerFactory.Send(context, _consumerPipe).ConfigureAwait(false); await context.NotifyConsumed(timer.Elapsed, TypeCache<TConsumer>.ShortName).ConfigureAwait(false); await next.Send(context).ConfigureAwait(false); } catch (OperationCanceledException exception) { await context.NotifyFaulted(timer.Elapsed, TypeCache<TConsumer>.ShortName, exception).ConfigureAwait(false); if (exception.CancellationToken == context.CancellationToken) throw; throw new ConsumerCanceledException($"The operation was canceled by the consumer: {TypeCache<TConsumer>.ShortName}"); } catch (Exception ex) { await context.NotifyFaulted(timer.Elapsed, TypeCache<TConsumer>.ShortName, ex).ConfigureAwait(false); throw; } finally { activity?.Stop(); } } } }
37.383562
146
0.63723
[ "ECL-2.0", "Apache-2.0" ]
AlexanderMeier/MassTransit
src/MassTransit/Middleware/ConsumerMessageFilter.cs
2,729
C#
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/ // Portions Copyright 2000-2004 Jonathan de Halleux // // 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 Gallio.Common; namespace Gallio.Framework.Assertions { /// <summary> /// A delegate for the <see cref="AssertionHelper.Explain(Action, AssertionFailureExplanation)" /> decorator method which /// combines the specified inner failures into a single outer failure with a common explanation. /// </summary> /// <param name="innerFailures">The inner failures to combine together.</param> /// <returns>The composite assertion failure.</returns> public delegate AssertionFailure AssertionFailureExplanation(AssertionFailure[] innerFailures); }
44.642857
126
0.7456
[ "ECL-2.0", "Apache-2.0" ]
citizenmatt/gallio
src/Gallio/Gallio/Framework/Assertions/AssertionFailureExplanation.cs
1,250
C#
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; namespace NativeInterop.Dll { /// <summary> /// ネイティブ側とのやり取りにコールバック関数を使いたい場合。 /// .NET のデリゲートを、ネイティブ側の関数ポインターにマーシャリングしてくれる仕組みがある。 /// </summary> class CallbackSample { delegate void Callback(IntPtr param, uint value); [DllImport("Win32Dll.dll")] extern static void SetCallback(IntPtr param, Callback callback); [DllImport("Win32Dll.dll")] extern static void FireCallback(uint value); public static void Main() { StaticMethod(); //NonReferencedInstanceMethod(); // こいつは呼ぶと実行時エラー ReferencedInstanceMethod(); ViaCallbackParameter(); } /// <summary> /// ガベコレを誘発用に無駄にインスタンスを量産。 /// </summary> private static void MakeGarbage() { for (int i = 0; i < 1000; i++) { var x = new byte[1000]; } } /// <summary> /// static メソッドをコールバックとして渡す。 /// 問題なし。 /// </summary> private static void StaticMethod() { void SetHandler() { // 何のインスタンスも参照しないメソッドであれば、問題は特に怒らない。 // GC が起ころうと、消えないし動かない。 SetCallback((IntPtr)0, (param, value) => Console.WriteLine(value)); } MakeGarbage(); SetHandler(); MakeGarbage(); GC.Collect(2, GCCollectionMode.Forced); for (uint i = 0; i < 5; i++) FireCallback(i); } /// <summary> /// インスタンスメソッドをコールバックとして渡す。 /// そのインスタンスが GC 回収されてしまうとまずい。 /// この例では、エラーが起きる。 /// </summary> private static void NonReferencedInstanceMethod() { void SetHandler() { // クロージャにしてしまったので、インスタンスが作られて、ラムダ式もインスタンスメソッドになる。 // かつ、そのインスタンスはこのローカル関数を抜けた時点でGC回収の対象になってしまう。 uint sum = 0; SetCallback((IntPtr)0, (param, value) => Console.WriteLine(sum += value)); } MakeGarbage(); SetHandler(); MakeGarbage(); GC.Collect(2, GCCollectionMode.Forced); // ここで、上記ラムダ式はGC回収されてしまう。 for (uint i = 0; i < 5; i++) FireCallback(i); // ここで回収済みのインスタンスに触ろうとして、実行時エラーが起きる。 } /// <summary> /// <see cref="NonReferencedInstanceMethod"/> の問題を回避するためのコード。 /// </summary> private static void ReferencedInstanceMethod() { Callback SetHandler() { // NonReferencedInstanceMethod との差は、登録したハンドラーを戻り値で返して、呼び出し側で握り続けてもらうこと。 uint sum = 0; Callback c = (param, value) => Console.WriteLine(sum += value); SetCallback((IntPtr)0, c); return c; } MakeGarbage(); // ただ握ってるだけ。特に使わなくてもいいんでとにかく変数に受ける。 var callback = SetHandler(); MakeGarbage(); GC.Collect(2, GCCollectionMode.Forced); // GC は怒ってるので、Managed なデリゲートはコンパクションで場所が移動してる。 // それでもエラーにならなくなる。 // CLR 内部の挙動としては、 // - デリゲートを呼び出してくれる static な関数を用意してある // - その static な関数は、コンパクションによる移動はトラッキングしてくれる // - でも、デリゲートは GC の対象にはなる(弱参照的な挙動) // みたい。 for (uint i = 0; i < 5; i++) FireCallback(i); } /// <summary> /// <see cref="ReferencedInstanceMethod"/> のような挙動もちょっと特殊と言えば特殊で。 /// ネイティブに渡すコールバックは static で済むなら static がいい感じもあり。 /// /// 今回の場合、<see cref="SetCallback(IntPtr, Callback)"/> の第1引数に渡したパラメーターを、 /// <see cref="Callback"/> の第1引数で渡してもらえる作りになってる。 /// ここに、インスタンスを渡せないかを考える。 /// /// ネイティブ側を経由するので、pinned ポインターを使う必要がある。 /// <seealso cref="GCHandle.Alloc(object, GCHandleType)"/> /// <seealso cref="GCHandleType.Pinned"/> /// <seealso cref="GCHandle.AddrOfPinnedObject"/> /// </summary> private static void ViaCallbackParameter() { // コールバックに渡してほしいパラメーターを用意 var p = new CallbackParameter(); // ネイティブに渡しても大丈夫なように pinned (ピン止め)して、 var h = GCHandle.Alloc(p, GCHandleType.Pinned); // IntPtr 化する。 var ptr = GCHandle.ToIntPtr(h); void SetHandler() { // IntPtr 化したオブジェクト(のアドレス) SetCallback(ptr, (param, value) => { // ポインターからオブジェクトを復元 var p1 = (CallbackParameter)GCHandle.FromIntPtr(param).Target; Console.WriteLine(p1.Value += value); }); } MakeGarbage(); SetHandler(); MakeGarbage(); GC.Collect(2, GCCollectionMode.Forced); // コールバックは static なのでガベコレの影響を受けない。 // h.Free() しない限りは p もコンパクションの影響を受けない。 for (uint i = 0; i < 5; i++) FireCallback(i); // ただし、Free を忘れるとメモリリークする。 h.Free(); } // Sequential にしておかないと GCHandle.Alloc できない。 [StructLayout(LayoutKind.Sequential)] class CallbackParameter { public uint Value; } } }
29.502703
90
0.517772
[ "Apache-2.0" ]
ufcpp/UfcppSample
Chapters/Interop/NativeInterop/Dll/CallbackSample.cs
7,260
C#
// Copyright 2018 Google Inc. 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. // 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 System.Collections.Generic; using System.Linq; using Microsoft.AspNetCore.Http; using Moq; using Xunit; namespace Google.Cloud.Diagnostics.AspNetCore.Tests { public class HttpLogEntryLabelProviderTest { [Fact] public void ThrowsWithoutHttpContextAccessor() { Assert.Throws<ArgumentNullException>( "httpContextAccessor", () => new DummyHttpLogEntryLabelProvider(httpContextAccessor: null)); } [Fact] public void DoesNotCallInvokeCoreWhenNoHttpContext() { // Arrange var instance = new ThrowingHttpLogEntryLabelProvider(Mock.Of<IHttpContextAccessor>()); var labels = new Dictionary<string, string>(); // Act // Should not throw because InvokeCore is never called and add any labels instance.Invoke(labels); // Assert Assert.Empty(labels); } [Fact] public void CallsInvokeCore() { // Arrange var mockHttpContextAccessor = new Mock<IHttpContextAccessor>(); mockHttpContextAccessor.Setup(x => x.HttpContext).Returns(Mock.Of<HttpContext>()); var instance = new DummyHttpLogEntryLabelProvider(mockHttpContextAccessor.Object); var labels = new Dictionary<string, string>(); // Act instance.Invoke(labels); // Assert Assert.Single(labels); Assert.Equal("foo", labels.First().Key); Assert.Equal("bar", labels.First().Value); } private class DummyHttpLogEntryLabelProvider : HttpLogEntryLabelProvider { public DummyHttpLogEntryLabelProvider(IHttpContextAccessor httpContextAccessor) : base(httpContextAccessor) { } protected override void InvokeCore(Dictionary<string, string> labels, HttpContext httpContext) { labels["foo"] = "bar"; } } private class ThrowingHttpLogEntryLabelProvider : HttpLogEntryLabelProvider { public ThrowingHttpLogEntryLabelProvider(IHttpContextAccessor httpContextAccessor) : base(httpContextAccessor) { } protected override void InvokeCore(Dictionary<string, string> labels, HttpContext httpContext) => throw new NotImplementedException(); } } }
34.47191
146
0.643416
[ "Apache-2.0" ]
ArulMozhiVaradan/google-cloud-dotnet
apis/Google.Cloud.Diagnostics.AspNetCore/Google.Cloud.Diagnostics.AspNetCore.Tests/Logging/LabelProviders/HttpLogEntryLabelProviderTest.cs
3,070
C#
using Lyra.Core.API; using Lyra.Core.Blocks; using Lyra.Core.Decentralize; using Lyra.Exchange; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; namespace Lyra.Core.API { public class LyraRestClient : INodeAPI, INodeTransactionAPI, INodeDexAPI { private string _appName; private string _appVersion; private string _url; private HttpClient _client; public LyraRestClient(string platform, string appName, string appVersion, string url) { _url = url; _appName = appName; _appVersion = appVersion; if(platform == "iOS") { System.Net.ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => { if (certificate.Issuer.Equals("CN=localhost")) return true; return sslPolicyErrors == System.Net.Security.SslPolicyErrors.None; }; } var httpClientHandler = new HttpClientHandler(); // Return `true` to allow certificates that are untrusted/invalid if(platform == "Android" || platform == "Windows" || platform == "Win32NT") { httpClientHandler.ServerCertificateCustomValidationCallback = (a, b, c, d) => true; } System.Net.ServicePointManager.ServerCertificateValidationCallback = (a, b, c, d) => true; httpClientHandler.ServerCertificateCustomValidationCallback = (a, b, c, d) => true; _client = new HttpClient(httpClientHandler); _client.BaseAddress = new Uri(url); _client.DefaultRequestHeaders.Accept.Clear(); _client.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json")); #if DEBUG _client.Timeout = new TimeSpan(1, 0, 0); #endif } public static async Task<LyraRestClient> CreateAsync(string networkId, string platform, string appName, string appVersion, string apiUrl = null) { var url = apiUrl == null ? LyraGlobal.SelectNode(networkId) + "Node/" : apiUrl; var restClient = new LyraRestClient(platform, appName, appVersion, url); if (!await restClient.CheckApiVersion().ConfigureAwait(false)) throw new Exception("Unable to use API. Must upgrade your App."); else return restClient; } private async Task<AuthorizationAPIResult> PostBlock(string action, Block block) { return await PostBlock<AuthorizationAPIResult>(action, block).ConfigureAwait(false); } private async Task<T> PostBlock<T>(string action, object obj) { HttpResponseMessage response = await _client.PostAsJsonAsync( action, obj).ConfigureAwait(false); response.EnsureSuccessStatusCode(); if (response.IsSuccessStatusCode) { var result = await response.Content.ReadAsAsync<T>(); return result; } else throw new Exception("Web Api Failed."); } private async Task<T> Get<T>(string action, Dictionary<string, string> args) { var url = $"{action}/?" + args?.Aggregate(new StringBuilder(), (sb, kvp) => sb.AppendFormat("{0}{1}={2}", sb.Length > 0 ? "&" : "", kvp.Key, kvp.Value), sb => sb.ToString()); HttpResponseMessage response = await _client.GetAsync(url); if (response.IsSuccessStatusCode) { var result = await response.Content.ReadAsAsync<T>(); return result; } else throw new Exception("Web Api Failed."); } private async Task<bool> CheckApiVersion() { var ret = await GetVersion(LyraGlobal.ProtocolVersion, _appName, _appVersion); if (ret.MustUpgradeToConnect) return false; else return true; } public Task<BillBoard> GetBillBoardAsync() { return Get<BillBoard>("GetBillboard", null); } public Task<List<TransStats>> GetTransStatsAsync() { return Get<List<TransStats>>("GetTransStats", null); } public Task<string> GetDbStats() { return Get<string>("GetDbStats", null); } public async Task<GetSyncStateAPIResult> GetSyncState() { HttpResponseMessage response = await _client.GetAsync("GetSyncState"); if (response.IsSuccessStatusCode) { var result = await response.Content.ReadAsAsync<GetSyncStateAPIResult>(); return result; } else throw new Exception("Web Api Failed."); } public async Task<CreateBlockUIdAPIResult> CreateBlockUId(string AccountId, string Signature, string blockHash) { var args = new Dictionary<string, string>(); args.Add("AccountId", AccountId); args.Add("Signature", Signature); args.Add("blockHash", blockHash); return await Get<CreateBlockUIdAPIResult>("CreateBlockUId", args); } public async Task<GetVersionAPIResult> GetVersion(int apiVersion, string appName, string appVersion) { HttpResponseMessage response = await _client.GetAsync($"GetVersion/?apiVersion={apiVersion}&appName={appName}&appVersion={appVersion}"); if (response.IsSuccessStatusCode) { var result = await response.Content.ReadAsAsync<GetVersionAPIResult>(); return result; } else throw new Exception("Web Api Failed."); } public async Task<AuthorizationAPIResult> CreateToken(TokenGenesisBlock block) { return await PostBlock("CreateToken", block); } public async Task<AccountHeightAPIResult> GetAccountHeight(string AccountId, string Signature) { HttpResponseMessage response = await _client.GetAsync($"GetAccountHeight/?AccountId={AccountId}&Signature={Signature}"); if (response.IsSuccessStatusCode) { var result = await response.Content.ReadAsAsync<AccountHeightAPIResult>(); return result; } else throw new Exception("Web Api Failed."); } public Task<ActiveTradeOrdersAPIResult> GetActiveTradeOrders(string AccountId, string SellToken, string BuyToken, TradeOrderListTypes OrderType, string Signature) { throw new NotImplementedException(); } public async Task<BlockAPIResult> GetBlockByHash(string AccountId, string Hash, string Signature) { HttpResponseMessage response = await _client.GetAsync($"GetBlockByHash/?AccountId={AccountId}&Signature={Signature}&Hash={Hash}"); if (response.IsSuccessStatusCode) { var result = await response.Content.ReadAsAsync<BlockAPIResult>(); return result; } else throw new Exception("Web Api Failed."); } public async Task<BlockAPIResult> GetBlockByIndex(string AccountId, long Index, string Signature) { HttpResponseMessage response = await _client.GetAsync($"GetBlockByIndex/?AccountId={AccountId}&Signature={Signature}&Index={Index}"); if (response.IsSuccessStatusCode) { var result = await response.Content.ReadAsAsync<BlockAPIResult>(); return result; } else throw new Exception("Web Api Failed."); } public async Task<BlockAPIResult> GetLastServiceBlock(string AccountId, string Signature) { HttpResponseMessage response = await _client.GetAsync($"GetLastServiceBlock/?AccountId={AccountId}&Signature={Signature}"); if (response.IsSuccessStatusCode) { var result = await response.Content.ReadAsAsync<BlockAPIResult>(); return result; } else throw new Exception("Web Api Failed."); } public async Task<BlockAPIResult> GetLastConsolidationBlock(string AccountId, string Signature) { HttpResponseMessage response = await _client.GetAsync($"GetLastConsolidationBlock/?AccountId={AccountId}&Signature={Signature}"); if (response.IsSuccessStatusCode) { var result = await response.Content.ReadAsAsync<BlockAPIResult>(); return result; } else throw new Exception("Web Api Failed."); } public async Task<MultiBlockAPIResult> GetBlocksByConsolidation(string AccountId, string Signature, string consolidationHash) { HttpResponseMessage response = await _client.GetAsync($"GetBlocksByConsolidation/?AccountId={AccountId}&Signature={Signature}&consolidationHash={consolidationHash}"); if (response.IsSuccessStatusCode) { var result = await response.Content.ReadAsAsync<MultiBlockAPIResult>(); return result; } else throw new Exception("Web Api Failed."); } public async Task<MultiBlockAPIResult> GetConsolidationBlocks(string AccountId, string Signature, long startHeight) { HttpResponseMessage response = await _client.GetAsync($"GetConsolidationBlocks/?AccountId={AccountId}&Signature={Signature}&startHeight={startHeight}"); if (response.IsSuccessStatusCode) { var result = await response.Content.ReadAsAsync<MultiBlockAPIResult>(); return result; } else throw new Exception("Web Api Failed."); } public async Task<GetListStringAPIResult> GetUnConsolidatedBlocks(string AccountId, string Signature) { HttpResponseMessage response = await _client.GetAsync($"GetUnConsolidatedBlocks/?AccountId={AccountId}&Signature={Signature}"); if (response.IsSuccessStatusCode) { var result = await response.Content.ReadAsAsync<GetListStringAPIResult>(); return result; } else throw new Exception("Web Api Failed."); } public async Task<NonFungibleListAPIResult> GetNonFungibleTokens(string AccountId, string Signature) { HttpResponseMessage response = await _client.GetAsync($"GetNonFungibleTokens/?AccountId={AccountId}&Signature={Signature}"); if (response.IsSuccessStatusCode) { var result = await response.Content.ReadAsAsync<NonFungibleListAPIResult>(); return result; } else throw new Exception("Web Api Failed."); } public async Task<AccountHeightAPIResult> GetSyncHeight() { HttpResponseMessage response = await _client.GetAsync("GetSyncHeight"); if (response.IsSuccessStatusCode) { var result = await response.Content.ReadAsAsync<AccountHeightAPIResult>(); return result; } else throw new Exception("Web Api Failed."); } public async Task<BlockAPIResult> GetTokenGenesisBlock(string AccountId, string TokenTicker, string Signature) { HttpResponseMessage response = await _client.GetAsync($"GetTokenGenesisBlock/?AccountId={AccountId}&TokenTicker={TokenTicker}&Signature={Signature}"); if (response.IsSuccessStatusCode) { var result = await response.Content.ReadAsAsync<BlockAPIResult>(); return result; } else throw new Exception("Web Api Failed."); } public async Task<GetListStringAPIResult> GetTokenNames(string AccountId, string Signature, string keyword) { HttpResponseMessage response = await _client.GetAsync($"GetTokenNames/?AccountId={AccountId}&Signature={Signature}&keyword={keyword}"); if (response.IsSuccessStatusCode) { var result = await response.Content.ReadAsAsync<GetListStringAPIResult>(); return result; } else throw new Exception("Web Api Failed."); } public async Task<AuthorizationAPIResult> ImportAccount(ImportAccountBlock block) { return await PostBlock("ImportAccount", block); } public Task<TradeAPIResult> LookForNewTrade(string AccountId, string BuyTokenCode, string SellTokenCode, string Signature) { throw new NotImplementedException(); } public async Task<NewTransferAPIResult> LookForNewTransfer(string AccountId, string Signature) { HttpResponseMessage response = await _client.GetAsync($"LookForNewTransfer/?AccountId={AccountId}&Signature={Signature}"); if (response.IsSuccessStatusCode) { var result = await response.Content.ReadAsAsync<NewTransferAPIResult>(); return result; } else throw new Exception("Web Api Failed."); } public async Task<AuthorizationAPIResult> OpenAccountWithGenesis(LyraTokenGenesisBlock block) { return await PostBlock("OpenAccountWithGenesis", block); } public async Task<AuthorizationAPIResult> OpenAccountWithImport(OpenAccountWithImportBlock block) { return await PostBlock("OpenAccountWithImport", block); } public async Task<AuthorizationAPIResult> ReceiveTransfer(ReceiveTransferBlock block) { return await PostBlock("ReceiveTransfer", block); } public async Task<AuthorizationAPIResult> ReceiveTransferAndOpenAccount(OpenWithReceiveTransferBlock block) { return await PostBlock("ReceiveTransferAndOpenAccount", block); } public async Task<AuthorizationAPIResult> SendTransfer(SendTransferBlock block) { return await PostBlock("SendTransfer", block); } public async Task<AuthorizationAPIResult> SendExchangeTransfer(ExchangingBlock block) { return await PostBlock("SendExchangeTransfer", block); } public async Task<CancelKey> SubmitExchangeOrder(TokenTradeOrder order) { return await PostBlock<CancelKey>("SubmitExchangeOrder", order); } public async Task<APIResult> RequestMarket(string tokenName) { var args = new Dictionary<string, string>(); args.Add("TokenName", tokenName); return await Get<APIResult>("RequestMarket", args); } public async Task<List<ExchangeOrder>> GetOrdersForAccount(string AccountId, string Signature) { var args = new Dictionary<string, string>(); args.Add("AccountId", AccountId); args.Add("Signature", Signature); return await Get<List<ExchangeOrder>>("GetOrdersForAccount", args); } public async Task<ExchangeAccountAPIResult> CreateExchangeAccount(string AccountId, string Signature) { var args = new Dictionary<string, string>(); args.Add("AccountId", AccountId); args.Add("Signature", Signature); return await Get<ExchangeAccountAPIResult>("CreateExchangeAccount", args); } public async Task<ExchangeBalanceAPIResult> GetExchangeBalance(string AccountId, string Signature) { var args = new Dictionary<string, string>(); args.Add("AccountId", AccountId); args.Add("Signature", Signature); return await Get<ExchangeBalanceAPIResult>("GetExchangeBalance", args); } public async Task<APIResult> CancelExchangeOrder(string AccountId, string Signature, string cancelKey) { var args = new Dictionary<string, string>(); args.Add("AccountId", AccountId); args.Add("Signature", Signature); args.Add("cancelKey", cancelKey); return await Get<APIResult>("CancelExchangeOrder", args); } public Task<ExchangeAccountAPIResult> CloseExchangeAccount(string AccountId, string Signature) { throw new NotImplementedException(); } } }
40.842482
178
0.607959
[ "MIT" ]
wizd/WizardDAG
Core/Lyra.Core/API/LyraRestClient.cs
17,115
C#
using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace EasyAbp.CacheManagement.HttpApi.Client.ConsoleTestApp { class Program { static async Task Main(string[] args) { await CreateHostBuilder(args).RunConsoleAsync(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureServices((hostContext, services) => { services.AddHostedService<ConsoleTestAppHostedService>(); }); } }
28.863636
77
0.637795
[ "MIT" ]
DosSEdo/CacheManagement
test/EasyAbp.CacheManagement.HttpApi.Client.ConsoleTestApp/Program.cs
637
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable namespace Azure.ResourceManager.Storage.Models { /// <summary> An error response from the storage resource provider. </summary> internal partial class ErrorResponse { /// <summary> Initializes a new instance of ErrorResponse. </summary> internal ErrorResponse() { } /// <summary> Initializes a new instance of ErrorResponse. </summary> /// <param name="error"> Azure Storage Resource Provider error response body. </param> internal ErrorResponse(ErrorResponseBody error) { Error = error; } /// <summary> Azure Storage Resource Provider error response body. </summary> public ErrorResponseBody Error { get; } } }
29.931034
94
0.653226
[ "MIT" ]
93mishra/azure-sdk-for-net
sdk/storage/Azure.ResourceManager.Storage/src/Generated/Models/ErrorResponse.cs
868
C#
#region BSD License /* * Use of this source code is governed by a BSD-style * license that can be found in the LICENSE.md file or at * https://github.com/Wagnerp/Krypton-Toolkit-Suite-Extended-NET-5.450/blob/master/LICENSE * */ #endregion using System; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; namespace ExtendedControls.Base.Code.Utilities { public class Utility { #region Constructors public Utility() { } #endregion #region Methods /// <summary> /// Determines whether [is windows seven or above]. /// </summary> /// <returns> /// <c>true</c> if [is windows seven or above]; otherwise, <c>false</c>. /// </returns> public static bool IsWindowsSevenOrAbove() { bool result = false; Version currentOSVersion = Environment.OSVersion.Version; if (currentOSVersion.Major >= 6 && currentOSVersion.Minor >= 1) { result = true; } else { result = false; } return result; } public static StringFormat GetStringFormat(ContentAlignment contentAlignment) { if (!Enum.IsDefined(typeof(ContentAlignment), (int)contentAlignment)) { throw new InvalidEnumArgumentException("contentAlignment", (int)contentAlignment, typeof(ContentAlignment)); } StringFormat stringFormat = new StringFormat(); switch (contentAlignment) { case ContentAlignment.MiddleCenter: stringFormat.LineAlignment = StringAlignment.Center; stringFormat.Alignment = StringAlignment.Center; break; case ContentAlignment.MiddleLeft: stringFormat.LineAlignment = StringAlignment.Center; stringFormat.Alignment = StringAlignment.Near; break; case ContentAlignment.MiddleRight: stringFormat.LineAlignment = StringAlignment.Center; stringFormat.Alignment = StringAlignment.Far; break; case ContentAlignment.TopCenter: stringFormat.LineAlignment = StringAlignment.Near; stringFormat.Alignment = StringAlignment.Center; break; case ContentAlignment.TopLeft: stringFormat.LineAlignment = StringAlignment.Near; stringFormat.Alignment = StringAlignment.Near; break; case ContentAlignment.TopRight: stringFormat.LineAlignment = StringAlignment.Near; stringFormat.Alignment = StringAlignment.Far; break; case ContentAlignment.BottomCenter: stringFormat.LineAlignment = StringAlignment.Far; stringFormat.Alignment = StringAlignment.Center; break; case ContentAlignment.BottomLeft: stringFormat.LineAlignment = StringAlignment.Far; stringFormat.Alignment = StringAlignment.Near; break; case ContentAlignment.BottomRight: stringFormat.LineAlignment = StringAlignment.Far; stringFormat.Alignment = StringAlignment.Far; break; } return stringFormat; } public static bool IsWindowOpen(Type formType) { foreach (Form form in Application.OpenForms) { if (form.GetType().Name == form.Name) { return true; } } return false; } #endregion } }
29.813433
124
0.54418
[ "BSD-3-Clause" ]
Wagnerp/Krypton-Toolkit-Suite-Extended-NET-5.450
Source/Krypton Toolkit Suite Extended/Full Toolkit/Extended Controls/Base/Code/Utilities/Utility.cs
3,997
C#
using UnityEngine; using System.Collections; using System.Collections.Generic; #if TMP_PRESENT using TMPro; #endif /// <summary> /// The axis used in WMG_Axis_Chart for X / Y axes, as well as secondary Y axis in Dual Y axis charts. /// </summary> public class WMG_Axis : WMG_GUI_Functions { public WMG_Axis_Graph graph; public enum labelTypes {ticks, ticks_center, groups, manual}; public enum autoGrowShrinkType {BEYOND_BY_PERCENTAGE, DATA_MIN_MAX}; [SerializeField] private List<string> _axisLabels; public WMG_List<string> axisLabels = new WMG_List<string>(); /// <summary> /// Determines where each point / bar in a series gets positioned. /// </summary> /// <value>The axis minimum value.</value> public float AxisMinValue { get {return _AxisMinValue;} set { if (_AxisMinValue != value) { _AxisMinValue = value; graphC.Changed(); seriesC.Changed(); graph.autoPaddingC.Changed(); } } } /// <summary> /// Determines where each point / bar in a series gets positioned. /// </summary> /// <value>The axis minimum value.</value> public float AxisMaxValue { get {return _AxisMaxValue;} set { if (_AxisMaxValue != value) { _AxisMaxValue = value; graphC.Changed(); seriesC.Changed(); graph.autoPaddingC.Changed(); } } } /// <summary> /// This determines the number of ticks that appear on each axis. Each tick can also be associated with a tick label and the gridlines are also aligned with the ticks. /// This value must be 2 or higher. If there is no need to have ticks for your graph, set #hideTicks = true. /// </summary> /// <value>The axis number ticks.</value> public int AxisNumTicks { get {return _AxisNumTicks;} set { if (_AxisNumTicks != value) { _AxisNumTicks = value; if (_AxisNumTicks < 2) { Debug.LogWarning("Graph Maker - Axis Num Ticks must be > 1, use Hide Ticks instead"); _AxisNumTicks = 2; } graphC.Changed(); graph.autoPaddingC.Changed(); } } } /// <summary> /// Determines how #MinAutoGrow, #MaxAutoGrow, #MinAutoShrink, and #MaxAutoShrink work. For DATA_MIN_MAX the axes min / max are simply set directly to the min / max of the data. /// For BEYOND_BY_PERCENTAGE, the axes are auto growed / shrinked by the percentage WMG_Axis_Graph::autoGrowAndShrinkByPercent. /// </summary> /// <value>The type of the auto grow shrink.</value> public autoGrowShrinkType AutoGrowShrinkType { get {return _AutoGrowShrinkType;} set { if (_AutoGrowShrinkType != value) { _AutoGrowShrinkType = value; graphC.Changed(); seriesC.Changed(); graph.autoPaddingC.Changed(); } } } /// <summary> /// Determines whether the absolute value of #AxisMinValue automatically grows based on WMG_Series data, where growth amount is determined by WMG_Axis_Graph::autoGrowAndShrinkByPercent. /// </summary> /// <value><c>true</c> if minimum auto grow; otherwise, <c>false</c>.</value> public bool MinAutoGrow { get {return _MinAutoGrow;} set { if (_MinAutoGrow != value) { _MinAutoGrow = value; graphC.Changed(); seriesC.Changed(); graph.autoPaddingC.Changed(); } } } /// <summary> /// Determines whether the absolute value of #AxisMaxValue automatically grows based on WMG_Series data, where growth amount is determined by WMG_Axis_Graph::autoGrowAndShrinkByPercent. /// </summary> /// <value><c>true</c> if max auto grow; otherwise, <c>false</c>.</value> public bool MaxAutoGrow { get {return _MaxAutoGrow;} set { if (_MaxAutoGrow != value) { _MaxAutoGrow = value; graphC.Changed(); seriesC.Changed(); graph.autoPaddingC.Changed(); } } } /// <summary> /// Determines whether the absolute value of #AxisMinValue automatically shrinks based on WMG_Series data, where shrink occurs at WMG_Axis_Graph::autoShrinkAtPercent /// and shrink amount is determined by WMG_Axis_Graph::autoGrowAndShrinkByPercent. /// </summary> /// <value><c>true</c> if minimum auto shrink; otherwise, <c>false</c>.</value> public bool MinAutoShrink { get {return _MinAutoShrink;} set { if (_MinAutoShrink != value) { _MinAutoShrink = value; graphC.Changed(); seriesC.Changed(); graph.autoPaddingC.Changed(); } } } /// <summary> /// Determines whether the absolute value of #AxisMaxValue automatically shrinks based on WMG_Series data, where shrink occurs at WMG_Axis_Graph::autoShrinkAtPercent /// and shrink amount is determined by WMG_Axis_Graph::autoGrowAndShrinkByPercent. /// </summary> /// <value><c>true</c> if max auto shrink; otherwise, <c>false</c>.</value> public bool MaxAutoShrink { get {return _MaxAutoShrink;} set { if (_MaxAutoShrink != value) { _MaxAutoShrink = value; graphC.Changed(); seriesC.Changed(); graph.autoPaddingC.Changed(); } } } /// <summary> /// Controls how much more space is extended beyond the actual axis length, useful to control how far axis arrows are away from the last tick / gridline. /// </summary> /// <value>The axis line padding.</value> public float AxisLinePadding { get {return _AxisLinePadding;} set { if (_AxisLinePadding != value) { _AxisLinePadding = value; graphC.Changed(); graph.autoPaddingC.Changed(); } } } /// <summary> /// Whether or not axes are positioned based on percentages rather than on fixed grid ticks. This should be enabled when WMG_Axis_Graph::axesType is of an AUTO_ORIGIN type. /// </summary> /// <value><c>true</c> if axis use non tick percent; otherwise, <c>false</c>.</value> public bool AxisUseNonTickPercent { get {return _AxisUseNonTickPercent;} set { if (_AxisUseNonTickPercent != value) { _AxisUseNonTickPercent = value; graphC.Changed(); graph.autoPaddingC.Changed(); } } } /// <summary> /// The percentage (0-1) position of this axis. /// </summary> /// <value>The axis non tick percent.</value> public float AxisNonTickPercent { get {return _AxisNonTickPercent;} set { if (_AxisNonTickPercent != value) { _AxisNonTickPercent = value; graphC.Changed(); graph.autoPaddingC.Changed(); } } } /// <summary> /// Whether to hide the top / right axis arrow. /// </summary> /// <value><c>true</c> if hide axis arrow top right; otherwise, <c>false</c>.</value> public bool HideAxisArrowTopRight { get {return _HideAxisArrowTopRight;} set { if (_HideAxisArrowTopRight != value) { _HideAxisArrowTopRight = value; graphC.Changed(); graph.autoPaddingC.Changed(); } } } /// <summary> /// Whether to hide the bot / left axis arrow. /// </summary> /// <value><c>true</c> if hide axis arrow bot left; otherwise, <c>false</c>.</value> public bool HideAxisArrowBotLeft { get {return _HideAxisArrowBotLeft;} set { if (_HideAxisArrowBotLeft != value) { _HideAxisArrowBotLeft = value; graphC.Changed(); graph.autoPaddingC.Changed(); } } } /// <summary> /// Whether the top / right axis arrow is visible, this is automatically controlled by axes types, use #HideAxisArrowTopRight to always hide. /// </summary> /// <value><c>true</c> if axis arrow top right; otherwise, <c>false</c>.</value> public bool AxisArrowTopRight { get {return _AxisArrowTopRight;} set { if (_AxisArrowTopRight != value) { _AxisArrowTopRight = value; graphC.Changed(); graph.autoPaddingC.Changed(); } } } /// <summary> /// Whether the bot / left axis arrow is visible, this is automatically controlled by axes types, use #HideAxisArrowBotLeft to always hide. /// </summary> /// <value><c>true</c> if axis arrow bot left; otherwise, <c>false</c>.</value> public bool AxisArrowBotLeft { get {return _AxisArrowBotLeft;} set { if (_AxisArrowBotLeft != value) { _AxisArrowBotLeft = value; graphC.Changed(); graph.autoPaddingC.Changed(); } } } /// <summary> /// Whether axis ticks are to the right / above the axis line, this is automatically controlled by axes types. /// </summary> /// <value><c>true</c> if axis ticks right above; otherwise, <c>false</c>.</value> public bool AxisTicksRightAbove { get {return _AxisTicksRightAbove;} set { if (_AxisTicksRightAbove != value) { _AxisTicksRightAbove = value; graphC.Changed(); graph.autoPaddingC.Changed(); } } } /// <summary> /// Whether axis ticks are on the opposite side of the axis line. When true the ticks are drawn on the inside of the graph and the ticks where the axes meet are hidden. /// </summary> /// <value><c>true</c> if opposite side ticks; otherwise, <c>false</c>.</value> public bool OppositeSideTicks { get {return _OppositeSideTicks;} set { if (_OppositeSideTicks != value) { _OppositeSideTicks = value; graphC.Changed(); graph.autoPaddingC.Changed(); } } } /// <summary> /// The tick index at which this axis is placed, this is automatically controlled. /// </summary> /// <value>The axis tick.</value> public int AxisTick { get {return _AxisTick;} set { if (_AxisTick != value) { _AxisTick = value; graphC.Changed(); } } } /// <summary> /// Whether the tick label of #AxisTick is hidden, this is automatically controlled. /// </summary> /// <value><c>true</c> if hide tick; otherwise, <c>false</c>.</value> public bool hideTick { get {return _hideTick;} set { if (_hideTick != value) { _hideTick = value; graphC.Changed(); } } } /// <summary> /// The label type determines what labels are used and where they are positioned. /// - ticks: There are #AxisNumTicks labels, where each label is positioned next to a tick. The labels come from #axisLabels or automatically if #SetLabelsUsingMaxMin = true. /// - ticks_center: There are #AxisNumTicks - 1 labels, where each label is positioned between 2 ticks. The labels come from #axisLabels or automatically if #SetLabelsUsingMaxMin = true. /// - groups: The labels come from WMG_Axis_Graph::groups, and are positioned next to the data points / bars. /// - manual: The labels come from #axisLabels and are positioned based on #AxisLabelSpacing and #AxisLabelDistBetween. /// </summary> public labelTypes LabelType { get {return _LabelType;} set { if (_LabelType != value) { _LabelType = value; graphC.Changed(); graph.autoPaddingC.Changed(); } } } /// <summary> /// Determines how often a label is shown on the axes. For example at 0, all labels are shown, at 1, every other label, and at 2 every other 2 labels. /// Useful if you have alot of data (e.g. 365 day strings stored in WMG_Axis_Graph::groups, and only want to display every week or couple weeks worth. /// </summary> /// <value>The axis label skip interval.</value> public int AxisLabelSkipInterval { get {return _AxisLabelSkipInterval;} set { if (_AxisLabelSkipInterval != value) { _AxisLabelSkipInterval = value; graphC.Changed(); graph.autoPaddingC.Changed(); } } } /// <summary> /// Determines how many labels to skip at the start to show on the axis, e.g. a value of 1 will skip the first label. /// </summary> /// <value>The axis label skip start.</value> public int AxisLabelSkipStart { get {return _AxisLabelSkipStart;} set { if (_AxisLabelSkipStart != value) { _AxisLabelSkipStart = value; graphC.Changed(); graph.autoPaddingC.Changed(); } } } /// <summary> /// Rotates all the labels with the specified number of degrees. /// </summary> /// <value>The axis label rotation.</value> public float AxisLabelRotation { get {return _AxisLabelRotation;} set { if (_AxisLabelRotation != value) { _AxisLabelRotation = value; graphC.Changed(); graph.autoPaddingC.Changed(); } } } /// <summary> /// If this is true, then the #axisLabels get automatically set based on #AxisNumTicks, #AxisMaxValue, #AxisMinValue, and #numDecimalsAxisLabels. /// </summary> /// <value><c>true</c> if set labels using max minimum; otherwise, <c>false</c>.</value> public bool SetLabelsUsingMaxMin { get {return _SetLabelsUsingMaxMin;} set { if (_SetLabelsUsingMaxMin != value) { _SetLabelsUsingMaxMin = value; graphC.Changed(); graph.autoPaddingC.Changed(); } } } /// <summary> /// Gets or sets the size of the axis labels. /// </summary> /// <value>The size of the axis labels.</value> public int AxisLabelSize { get {return _AxisLabelSize;} set { if (_AxisLabelSize != value) { _AxisLabelSize = value; graphC.Changed(); graph.autoPaddingC.Changed(); } } } /// <summary> /// Gets or sets the color of the axis labels. /// </summary> /// <value>The color of the axis labels.</value> public Color AxisLabelColor { get {return _AxisLabelColor;} set { if (_AxisLabelColor != value) { _AxisLabelColor = value; graphC.Changed(); } } } /// <summary> /// Gets or sets the axis label font style. /// </summary> /// <value>The axis label font style.</value> public FontStyle AxisLabelFontStyle { get {return _AxisLabelFontStyle;} set { if (_AxisLabelFontStyle != value) { _AxisLabelFontStyle = value; graphC.Changed(); graph.autoPaddingC.Changed(); } } } /// <summary> /// Gets or sets the axis label font. /// </summary> /// <value>The axis label font.</value> #if TMP_PRESENT public TMP_FontAsset AxisLabelFont { get {return _AxisLabelFont;} set { if (_AxisLabelFont != value) { _AxisLabelFont = value; graphC.Changed(); graph.autoPaddingC.Changed(); } } } #else public Font AxisLabelFont { get {return _AxisLabelFont;} set { if (_AxisLabelFont != value) { _AxisLabelFont = value; graphC.Changed(); graph.autoPaddingC.Changed(); } } } #endif /// <summary> /// Gets or sets the number of decimals used in axis labels, used when #SetLabelsUsingMaxMin = true. /// </summary> /// <value>The number decimals axis labels.</value> public int numDecimalsAxisLabels { get {return _numDecimalsAxisLabels;} set { if (_numDecimalsAxisLabels != value) { _numDecimalsAxisLabels = value; graphC.Changed(); graph.autoPaddingC.Changed(); } } } /// <summary> /// Whether or not all the axes labels for this axis are hidden. /// </summary> /// <value><c>true</c> if hide labels; otherwise, <c>false</c>.</value> public bool hideLabels { get {return _hideLabels;} set { if (_hideLabels != value) { _hideLabels = value; graphC.Changed(); graph.autoPaddingC.Changed(); } } } /// <summary> /// Controls the amount of space between the axis line and the axis labels. /// </summary> /// <value>The axis label space offset.</value> public float AxisLabelSpaceOffset { get {return _AxisLabelSpaceOffset;} set { if (_AxisLabelSpaceOffset != value) { _AxisLabelSpaceOffset = value; graphC.Changed(); graph.autoPaddingC.Changed(); } } } /// <summary> /// Whether or not axis labels are bounded by the ends of the axes. This pivots the axis labels on the ends differently. /// </summary> /// <value><c>true</c> if axis bounded labels; otherwise, <c>false</c>.</value> public bool AxisBoundedLabels { get {return _AxisBoundedLabels;} set { if (_AxisBoundedLabels != value) { _AxisBoundedLabels = value; graphC.Changed(); graph.autoPaddingC.Changed(); } } } /// <summary> /// Whether axis labels are on the opposite side of the axis line. /// </summary> /// <value><c>true</c> if opposite side labels; otherwise, <c>false</c>.</value> public bool OppositeSideLabels { get {return _OppositeSideLabels;} set { if (_OppositeSideLabels != value) { _OppositeSideLabels = value; graphC.Changed(); graph.autoPaddingC.Changed(); } } } /// <summary> /// Only needs to be set manually for WMG_Axis_Graph::axesType = manual. Controls how much all of the labels are offset in the direction of the axis line. /// </summary> /// <value>The axis label spacing.</value> public float AxisLabelSpacing { get {return _AxisLabelSpacing;} set { if (_AxisLabelSpacing != value) { _AxisLabelSpacing = value; graphC.Changed(); } } } /// <summary> /// Only needs to be set manually for WMG_Axis_Graph::axesType = manual. This is the amount of space between each label. /// </summary> /// <value>The axis label dist between.</value> public float AxisLabelDistBetween { get {return _AxisLabelDistBetween;} set { if (_AxisLabelDistBetween != value) { _AxisLabelDistBetween = value; graphC.Changed(); } } } /// <summary> /// Determines whether grid lines for this axis appear. /// </summary> /// <value><c>true</c> if hide grid; otherwise, <c>false</c>.</value> public bool hideGrid { get {return _hideGrid;} set { if (_hideGrid != value) { _hideGrid = value; graphC.Changed(); } } } /// <summary> /// Determines whether tick marks for this axis appear. /// </summary> /// <value><c>true</c> if hide ticks; otherwise, <c>false</c>.</value> public bool hideTicks { get {return _hideTicks;} set { if (_hideTicks != value) { _hideTicks = value; graphC.Changed(); graph.autoPaddingC.Changed(); } } } /// <summary> /// Whether or not the axis line is visible. /// </summary> /// <value><c>true</c> if hide axis line; otherwise, <c>false</c>.</value> public bool hideAxisLine { get {return _hideAxisLine;} set { if (_hideAxisLine != value) { _hideAxisLine = value; graphC.Changed(); graph.autoPaddingC.Changed(); } } } /// <summary> /// Gets or sets the axis title string. /// </summary> /// <value>The axis title string.</value> public string AxisTitleString { get {return _AxisTitleString;} set { if (_AxisTitleString != value) { _AxisTitleString = value; graphC.Changed(); graph.autoPaddingC.Changed(); } } } /// <summary> /// Gets or sets the axis title offset position relative to the nearest content along the axis line including labels, ticks, and the axis line itself. /// </summary> /// <value>The axis title offset.</value> public Vector2 AxisTitleOffset { get {return _AxisTitleOffset;} set { if (_AxisTitleOffset != value) { _AxisTitleOffset = value; graphC.Changed(); graph.autoPaddingC.Changed(); } } } /// <summary> /// Gets or sets the size of the axis title font. /// </summary> /// <value>The size of the axis title font.</value> public int AxisTitleFontSize { get {return _AxisTitleFontSize;} set { if (_AxisTitleFontSize != value) { _AxisTitleFontSize = value; graphC.Changed(); graph.autoPaddingC.Changed(); } } } // Public variables without change tracking public GameObject AxisTitle; public GameObject GridLines; public GameObject AxisTicks; public GameObject AxisLine; public GameObject AxisArrowUR; public GameObject AxisArrowDL; public GameObject AxisObj; public GameObject AxisLabelObjs; // Private backing variables [SerializeField] private float _AxisMinValue; [SerializeField] private float _AxisMaxValue; [SerializeField] private int _AxisNumTicks; [SerializeField] private autoGrowShrinkType _AutoGrowShrinkType; [SerializeField] private bool _MinAutoGrow; [SerializeField] private bool _MaxAutoGrow; [SerializeField] private bool _MinAutoShrink; [SerializeField] private bool _MaxAutoShrink; [SerializeField] private float _AxisLinePadding; [SerializeField] private bool _AxisUseNonTickPercent; [SerializeField] private float _AxisNonTickPercent; [SerializeField] private bool _HideAxisArrowTopRight; [SerializeField] private bool _HideAxisArrowBotLeft; [SerializeField] private bool _AxisArrowTopRight; [SerializeField] private bool _AxisArrowBotLeft; [SerializeField] private bool _AxisTicksRightAbove; [SerializeField] private bool _OppositeSideTicks; [SerializeField] private int _AxisTick; [SerializeField] private bool _hideTick; [SerializeField] private labelTypes _LabelType; [SerializeField] private int _AxisLabelSkipStart; [SerializeField] private int _AxisLabelSkipInterval; [SerializeField] private float _AxisLabelRotation; [SerializeField] private bool _SetLabelsUsingMaxMin; [SerializeField] private int _AxisLabelSize; [SerializeField] private Color _AxisLabelColor = Color.white; [SerializeField] private FontStyle _AxisLabelFontStyle = FontStyle.Normal; #if TMP_PRESENT [SerializeField] private TMP_FontAsset _AxisLabelFont; #else [SerializeField] private Font _AxisLabelFont; #endif [SerializeField] private int _numDecimalsAxisLabels; [SerializeField] private bool _hideLabels; [SerializeField] private float _AxisLabelSpaceOffset; [SerializeField] private bool _AxisBoundedLabels; [SerializeField] private bool _OppositeSideLabels; [SerializeField] private float _AxisLabelSpacing; [SerializeField] private float _AxisLabelDistBetween; [SerializeField] private bool _hideGrid; [SerializeField] private bool _hideTicks; [SerializeField] private bool _hideAxisLine; [SerializeField] private string _AxisTitleString; [SerializeField] private Vector2 _AxisTitleOffset; [SerializeField] private int _AxisTitleFontSize; // Useful property getters public float AxisLength { get { if (isY) return graph.yAxisLength; else return graph.xAxisLength; } } // Private variables private float GridLineLength; private float AxisLinePaddingTot; private float AxisPercentagePosition; private float maxSpaceTakenByAxisLabels; // Original property values for use with dynamic resizing public int origAxisLabelSize { get; private set; } public float origAxisLabelSpaceOffset { get; private set; } public int origAxisTitleFontSize { get; private set; } public Vector2 origAxisTitleOffset { get; private set; } public float origAxisLinePadding { get; private set; } public Vector2 origAxisArrowSize { get; private set; } // Others private bool hasInit; private WMG_Axis otherAxis; private WMG_Axis otherAxis2; public bool isY { get; private set; } public bool isSecondary { get; private set; } public Vector2 anchorVec; public delegate string AxisLabelLabeler(WMG_Axis axis, int labelIndex); /// <summary> /// Use to override the default labeler for axis labels to put for example dollar signs for the labels. /// @code /// graph.yAxis.axisLabelLabeler = customYAxisLabelLabeler; /// string customYAxisLabelLabeler(WMG_Axis axis, int labelIndex) {} /// @endcode /// </summary> public AxisLabelLabeler axisLabelLabeler; private List<WMG_Change_Obj> changeObjs = new List<WMG_Change_Obj>(); private WMG_Change_Obj graphC = new WMG_Change_Obj(); private WMG_Change_Obj seriesC = new WMG_Change_Obj(); public void Init(WMG_Axis otherAxis, WMG_Axis otherAxis2, bool isY, bool isSecondary) { if (hasInit) return; hasInit = true; changeObjs.Add(graphC); changeObjs.Add(seriesC); this.otherAxis = otherAxis; this.otherAxis2 = otherAxis2; this.isY = isY; this.isSecondary = isSecondary; axisLabels.SetList (_axisLabels); axisLabels.Changed += axisLabelsChanged; graphC.OnChange += GraphChanged; seriesC.OnChange += SeriesChanged; axisLabelLabeler = defaultAxisLabelLabeler; setOriginalPropertyValues(); PauseCallbacks(); } public void PauseCallbacks() { for (int i = 0; i < changeObjs.Count; i++) { changeObjs[i].changesPaused = true; changeObjs[i].changePaused = false; } } public void ResumeCallbacks() { for (int i = 0; i < changeObjs.Count; i++) { changeObjs[i].changesPaused = false; if (changeObjs[i].changePaused) changeObjs[i].Changed(); } } void GraphChanged() { graph.graphC.Changed (); } void SeriesChanged() { graph.seriesNoCountC.Changed(); } private void axisLabelsChanged(bool editorChange, bool countChanged, bool oneValChanged, int index) { WMG_Util.listChanged (editorChange, ref axisLabels, ref _axisLabels, oneValChanged, index); graphC.Changed(); graph.autoPaddingC.Changed(); } // Set initial property values for use with percentage based dynamic resizing public void setOriginalPropertyValues() { origAxisLabelSize = AxisLabelSize; origAxisTitleFontSize = AxisTitleFontSize; origAxisTitleOffset = AxisTitleOffset; origAxisLabelSpaceOffset = AxisLabelSpaceOffset; origAxisLinePadding = AxisLinePadding; origAxisArrowSize = getSpriteSize (AxisArrowDL); } public void setDualYAxes() { // x-axis _AxisArrowTopRight = false; _AxisArrowBotLeft = false; _AxisTicksRightAbove = false; _hideTick = false; _AxisTick = 0; _AxisNonTickPercent = 0; // left y axis otherAxis.setOtherArrowTopRight(true); otherAxis.setOtherArrowBotLeft(false); otherAxis.setOtherRightAbove(false); otherAxis.setOtherHideTick (false); otherAxis.setOtherAxisTick (0); otherAxis.setOtherAxisNonTickPercent (0); // right y axis otherAxis2.setOtherArrowTopRight(true); otherAxis2.setOtherArrowBotLeft(false); otherAxis2.setOtherRightAbove(true); otherAxis2.setOtherHideTick (false); otherAxis2.setOtherAxisTick (AxisNumTicks - 1); otherAxis2.setOtherAxisNonTickPercent (1); } public void setDualYAxesTop() { // x-axis _AxisArrowTopRight = false; _AxisArrowBotLeft = false; _AxisTicksRightAbove = true; _hideTick = false; _AxisTick = otherAxis.AxisNumTicks - 1; _AxisNonTickPercent = 1; // left y axis otherAxis.setOtherArrowTopRight(false); otherAxis.setOtherArrowBotLeft(true); otherAxis.setOtherRightAbove(false); otherAxis.setOtherHideTick (false); otherAxis.setOtherAxisTick (0); otherAxis.setOtherAxisNonTickPercent (0); // right y axis otherAxis2.setOtherArrowTopRight(false); otherAxis2.setOtherArrowBotLeft(true); otherAxis2.setOtherRightAbove(true); otherAxis2.setOtherHideTick (false); otherAxis2.setOtherAxisTick (AxisNumTicks - 1); otherAxis2.setOtherAxisNonTickPercent (1); } public void setDualYAxesMid() { // x-axis _AxisArrowTopRight = false; _AxisArrowBotLeft = false; _AxisTicksRightAbove = false; _hideTick = true; _AxisTick = otherAxis.AxisNumTicks / 2; _AxisNonTickPercent = 0.5f; // left y axis otherAxis.setOtherArrowTopRight(true); otherAxis.setOtherArrowBotLeft(true); otherAxis.setOtherRightAbove(false); otherAxis.setOtherHideTick (false); otherAxis.setOtherAxisTick (0); otherAxis.setOtherAxisNonTickPercent (0); // right y axis otherAxis2.setOtherArrowTopRight(true); otherAxis2.setOtherArrowBotLeft(true); otherAxis2.setOtherRightAbove(true); otherAxis2.setOtherHideTick (false); otherAxis2.setOtherAxisTick (AxisNumTicks - 1); otherAxis2.setOtherAxisNonTickPercent (1); } public void setAxisTopRight(bool rightAbove) { _AxisArrowTopRight = true; _AxisArrowBotLeft = false; otherAxis.setOtherHideTick (false); otherAxis.setOtherAxisTick (0); otherAxis.setOtherAxisNonTickPercent (0); _AxisTicksRightAbove = rightAbove; } public void setAxisBotLeft(bool rightAbove) { _AxisArrowTopRight = false; _AxisArrowBotLeft = true; otherAxis.setOtherHideTick (false); otherAxis.setOtherAxisTick (AxisNumTicks - 1); otherAxis.setOtherAxisNonTickPercent (1); _AxisTicksRightAbove = rightAbove; } public void setAxisMiddle(bool rightAbove) { _AxisArrowTopRight = true; _AxisArrowBotLeft = true; otherAxis.setOtherHideTick (true); otherAxis.setOtherAxisTick (AxisNumTicks / 2); otherAxis.setOtherAxisNonTickPercent (0.5f); _AxisTicksRightAbove = rightAbove; } public void setOtherAxisNonTickPercent(float val) { _AxisNonTickPercent = val; } public void setOtherAxisTick(int val) { _AxisTick = val; } public void setOtherHideTick(bool val) { _hideTick = val; } public void setOtherRightAbove(bool val) { _AxisTicksRightAbove = val; } public void setOtherArrowBotLeft(bool val) { _AxisArrowBotLeft = val; } public void setOtherArrowTopRight(bool val) { _AxisArrowTopRight = val; } public void possiblyHideTickBasedOnPercent() { // Ensure tick is not hidden if percent is being used and num ticks is even if (otherAxis.AxisUseNonTickPercent && AxisNumTicks % 2 == 0) { _hideTick = false; } } public void ChangeOrientation() { labelTypes tLabelType = LabelType; float tAxisMaxValue = AxisMaxValue; float tAxisMinValue = AxisMinValue; int tAxisNumTicks = AxisNumTicks; int tnumDecimalsAxisLabels = numDecimalsAxisLabels; autoGrowShrinkType tAutoGrowShrinkType = AutoGrowShrinkType; bool tMinAutoGrow = MinAutoGrow; bool tMaxAutoGrow = MaxAutoGrow; bool tMinAutoShrink = MinAutoShrink; bool tMaxAutoShrink = MaxAutoShrink; bool tSetLabelsUsingMaxMin = SetLabelsUsingMaxMin; float tAxisLabelSpacing = AxisLabelSpacing; string tAxisTitleString = AxisTitleString; bool tHideTicks = hideTicks; bool tHideGrid = hideGrid; List<string> tLabels = new List<string>(_axisLabels); WMG_Axis otherAxis = this.otherAxis; if (!otherAxis) { otherAxis = graph.xAxis; } LabelType = otherAxis.LabelType; AxisMaxValue = otherAxis.AxisMaxValue; AxisMinValue = otherAxis.AxisMinValue; AxisNumTicks = otherAxis.AxisNumTicks; hideTicks = otherAxis.hideTicks; hideGrid = otherAxis.hideGrid; numDecimalsAxisLabels = otherAxis.numDecimalsAxisLabels; AutoGrowShrinkType = otherAxis.AutoGrowShrinkType; MinAutoGrow = otherAxis.MinAutoGrow; MaxAutoGrow = otherAxis.MaxAutoGrow; MinAutoShrink = otherAxis.MinAutoShrink; MaxAutoShrink = otherAxis.MaxAutoShrink; SetLabelsUsingMaxMin = otherAxis.SetLabelsUsingMaxMin; AxisLabelSpacing = otherAxis.AxisLabelSpacing; AxisTitleString = otherAxis.AxisTitleString; if (Application.isPlaying) { axisLabels.SetList(otherAxis.axisLabels); } else { axisLabels.SetListNoCb(otherAxis._axisLabels, ref _axisLabels); } otherAxis.ChangeOrientationEnd(tLabelType, tAxisMaxValue, tAxisMinValue, tAxisNumTicks, tnumDecimalsAxisLabels, tAutoGrowShrinkType, tMinAutoGrow, tMaxAutoGrow, tMinAutoShrink, tMaxAutoShrink, tSetLabelsUsingMaxMin, tAxisLabelSpacing, tAxisTitleString, tLabels, tHideTicks, tHideGrid); } public void ChangeOrientationEnd(labelTypes tLabelType, float tAxisMaxValue, float tAxisMinValue, int tAxisNumTicks, int tnumDecimalsAxisLabels, autoGrowShrinkType tAutoGrowShrinkType, bool tMinAutoGrow, bool tMaxAutoGrow, bool tMinAutoShrink, bool tMaxAutoShrink, bool tSetLabelsUsingMaxMin, float tAxisLabelSpacing, string tAxisTitleString, List<string> tLabels, bool tHideTicks, bool tHideGrid) { LabelType = tLabelType; AxisMaxValue = tAxisMaxValue; AxisMinValue = tAxisMinValue; AxisNumTicks = tAxisNumTicks; hideTicks = tHideTicks; hideGrid = tHideGrid; numDecimalsAxisLabels = tnumDecimalsAxisLabels; AutoGrowShrinkType = tAutoGrowShrinkType; MinAutoGrow = tMinAutoGrow; MaxAutoGrow = tMaxAutoGrow; MinAutoShrink = tMinAutoShrink; MaxAutoShrink = tMaxAutoShrink; SetLabelsUsingMaxMin = tSetLabelsUsingMaxMin; AxisLabelSpacing = tAxisLabelSpacing; AxisTitleString = tAxisTitleString; if (Application.isPlaying) { axisLabels.SetList(tLabels); } else { axisLabels.SetListNoCb(tLabels, ref _axisLabels); } } public void updateAxesRelativeToOrigin(float originVal) { if (graph.axesType == WMG_Axis_Graph.axesTypes.AUTO_ORIGIN || graph.axesType == (isY ? WMG_Axis_Graph.axesTypes.AUTO_ORIGIN_Y : WMG_Axis_Graph.axesTypes.AUTO_ORIGIN_X)) { bool otherRightAbove = otherAxis.AxisTicksRightAbove; if (originVal >= otherAxis.AxisMaxValue) { otherAxis.setAxisBotLeft(false); _AxisTicksRightAbove = true; } else if (originVal <= otherAxis.AxisMinValue) { otherAxis.setAxisTopRight(false); _AxisTicksRightAbove = false; } else { otherAxis.setAxisMiddle(false); _AxisTicksRightAbove = false; _AxisTick = Mathf.RoundToInt((originVal - otherAxis.AxisMinValue) / (otherAxis.AxisMaxValue - otherAxis.AxisMinValue) * (otherAxis.AxisNumTicks - 1)); _AxisNonTickPercent = (originVal - otherAxis.AxisMinValue) / (otherAxis.AxisMaxValue - otherAxis.AxisMinValue); } otherAxis.setOtherRightAbove(otherRightAbove); } } public void UpdateAxesGridsAndTicks() { // Calculate variables used in axis and grid positions // Ensure num ticks don't go below 1, update gridLineLength if (AxisNumTicks <= 1) { _AxisNumTicks = 1; GridLineLength = 0; } else { GridLineLength = AxisLength / (AxisNumTicks-1); } // update AxisPercentagePosition if (AxisUseNonTickPercent) { // position axis based on the percentage specified AxisPercentagePosition = AxisNonTickPercent; } else { // position axis based on the number of ticks and the specified tick if (otherAxis.AxisNumTicks == 1) AxisPercentagePosition = 1; else AxisPercentagePosition = AxisTick / (otherAxis.AxisNumTicks - 1f); } if (GridLines != null) { // Hide grids SetActive(GridLines, !hideGrid); if (!hideGrid) { // Update grid lines WMG_Grid gridLines = GridLines.GetComponent<WMG_Grid>(); if (isY) { gridLines.gridNumNodesY = AxisNumTicks; gridLines.gridLinkLengthY = GridLineLength; gridLines.gridLinkLengthX = otherAxis.AxisLength; } else { gridLines.gridNumNodesX = AxisNumTicks; gridLines.gridLinkLengthX = GridLineLength; gridLines.gridLinkLengthY = otherAxis.AxisLength; } gridLines.Refresh(); } } // Hide ticks SetActive(AxisTicks, !hideTicks); if (!hideTicks) { // Update ticks WMG_Grid ticks = AxisTicks.GetComponent<WMG_Grid>(); if (isY) { ticks.gridNumNodesY = AxisNumTicks; ticks.gridLinkLengthY = GridLineLength; } else { ticks.gridNumNodesX = AxisNumTicks; ticks.gridLinkLengthX = GridLineLength; } ticks.Refresh(); if (OppositeSideTicks ? AxisTicksRightAbove : !AxisTicksRightAbove) { if (isY) { changeSpritePositionToX(AxisTicks, AxisPercentagePosition * otherAxis.AxisLength - graph.axisWidth / 2 - graph.tickSize.y / 2 ); } else { changeSpritePositionToY(AxisTicks, AxisPercentagePosition * otherAxis.AxisLength - graph.axisWidth / 2 - graph.tickSize.y / 2 ); } } else { if (isY) { changeSpritePositionToX(AxisTicks, AxisPercentagePosition * otherAxis.AxisLength + graph.axisWidth / 2 + graph.tickSize.y / 2); } else { changeSpritePositionToY(AxisTicks, AxisPercentagePosition * otherAxis.AxisLength + graph.axisWidth / 2 + graph.tickSize.y / 2); } } // Update size of ticks, and whether enabled List<WMG_Node> tickNodes = GetAxisTickNodes(); for (int i = 0; i < tickNodes.Count; i++) { changeSpriteSize(tickNodes[i].objectToScale, Mathf.RoundToInt(isY ? graph.tickSize.y : graph.tickSize.x), Mathf.RoundToInt(isY ? graph.tickSize.x : graph.tickSize.y)); SetActive(tickNodes[i].gameObject, !(OppositeSideTicks && i == otherAxis.AxisTick)); } } // update axis visuals AxisLinePaddingTot = 2 * AxisLinePadding; float axisRepos = 0; if (AxisArrowTopRight) axisRepos += AxisLinePadding / 2f; else AxisLinePaddingTot -= AxisLinePadding; if (AxisArrowBotLeft) axisRepos -= AxisLinePadding / 2f; else AxisLinePaddingTot -= AxisLinePadding; if (isY) { changeSpriteSize(AxisLine, graph.axisWidth, Mathf.RoundToInt(AxisLength + AxisLinePaddingTot)); changeSpritePositionTo(AxisLine, new Vector3(0, axisRepos + AxisLength/2, 0)); changeSpritePositionToX(AxisObj, AxisPercentagePosition * otherAxis.AxisLength); } else { changeSpriteSize(AxisLine, Mathf.RoundToInt(AxisLength + AxisLinePaddingTot), graph.axisWidth); changeSpritePositionTo(AxisLine, new Vector3(axisRepos + AxisLength/2, 0, 0)); changeSpritePositionToY(AxisObj, AxisPercentagePosition * otherAxis.AxisLength); } // Update Arrows SetActiveAnchoredSprite(AxisArrowUR, HideAxisArrowTopRight ? false : AxisArrowTopRight); SetActiveAnchoredSprite(AxisArrowDL, HideAxisArrowBotLeft ? false : AxisArrowBotLeft); // Update axis line changeSpriteAlpha(AxisLine, hideAxisLine ? 0 : 1); } public void UpdateTitle() { if (AxisTitle != null) { changeLabelFontSize(AxisTitle, AxisTitleFontSize); changeLabelText(AxisTitle, AxisTitleString); // update rotation and position float tickOffset = 0; if (OppositeSideLabels == OppositeSideTicks) { // don't offset label positions based on tick size if ticks drawn on the opposite side of the labels if (LabelType == labelTypes.ticks || (LabelType == labelTypes.groups && AxisNumTicks == graph.groups.Count)) { tickOffset = graph.tickSize.y; } } float additionalOffset = (hideLabels ? 0 : (AxisLabelSpaceOffset + maxSpaceTakenByAxisLabels)) + (hideLabels && hideTicks ? 0 : tickOffset) + (hideLabels && hideTicks && hideAxisLine ? 0 : graph.axisWidth / 2f); if (isY) { if (anchorVec.x == 1) { // right AxisTitle.transform.localEulerAngles = new Vector3 (0, 0, 270); setAnchor(AxisTitle, anchorVec, new Vector2(0.5f, 0f), new Vector2(AxisTitleOffset.x + additionalOffset, AxisTitleOffset.y)); } else { // left AxisTitle.transform.localEulerAngles = new Vector3 (0, 0, 90); setAnchor(AxisTitle, anchorVec, new Vector2(0.5f, 0f), new Vector2(-AxisTitleOffset.x - additionalOffset, AxisTitleOffset.y)); } } else { if (anchorVec.y == 1) { // top setAnchor(AxisTitle, anchorVec, new Vector2(0.5f, 0f), new Vector2(AxisTitleOffset.x, AxisTitleOffset.y + additionalOffset)); } else { // bot setAnchor(AxisTitle, anchorVec, new Vector2(0.5f, 1f), new Vector2(AxisTitleOffset.x, -AxisTitleOffset.y - additionalOffset)); } } } } public void UpdateAxesMinMaxValues() { if (!MinAutoGrow && !MaxAutoGrow && !MinAutoShrink && !MaxAutoShrink) return; float min = Mathf.Infinity; float max = Mathf.NegativeInfinity; int lineSeriesCount = graph.lineSeries.Count; for (int j = 0; j < lineSeriesCount; j++) { if (!activeInHierarchy(graph.lineSeries[j])) continue; WMG_Series theSeries = graph.lineSeries[j].GetComponent<WMG_Series>(); if (graph.IsDualY) { if (isY && isSecondary && !theSeries.useSecondYaxis) continue; // secondary y-axis, but this series is for primary if (isY && !isSecondary && theSeries.useSecondYaxis) continue; // primary y-axis, but this series is for secondary } // Find the current max and min point value data int pointValuesCount = theSeries.pointValues.Count; if (graph.orientationType == WMG_Axis_Graph.orientationTypes.vertical) { for (int i = 0; i < pointValuesCount; i++) { if (isY) { if (theSeries.pointValues[i].y < min) min = theSeries.pointValues[i].y; if (theSeries.pointValues[i].y > max) max = theSeries.pointValues[i].y; if (graph.graphType == WMG_Axis_Graph.graphTypes.bar_stacked || graph.graphType == WMG_Axis_Graph.graphTypes.line_stacked) { if (graph.TotalPointValues[i] + AxisMinValue > max) max = graph.TotalPointValues[i] + AxisMinValue; } } else { if (theSeries.pointValues[i].x < min) min = theSeries.pointValues[i].x; if (theSeries.pointValues[i].x > max) max = theSeries.pointValues[i].x; } } } else { for (int i = 0; i < pointValuesCount; i++) { if (isY) { if (theSeries.pointValues[i].x < min) min = theSeries.pointValues[i].x; if (theSeries.pointValues[i].x > max) max = theSeries.pointValues[i].x; } else { if (theSeries.pointValues[i].y < min) min = theSeries.pointValues[i].y; if (theSeries.pointValues[i].y > max) max = theSeries.pointValues[i].y; if (graph.graphType == WMG_Axis_Graph.graphTypes.bar_stacked || graph.graphType == WMG_Axis_Graph.graphTypes.line_stacked) { if (graph.TotalPointValues[i] + AxisMinValue > max) max = graph.TotalPointValues[i] + AxisMinValue; } } } } } // If point data outside axis max / min then grow, if the point data significantly (percentage of total axis length variable) less than axis min / max then srhink if (MinAutoGrow || MaxAutoGrow || MinAutoShrink || MaxAutoShrink) { if (min == Mathf.Infinity || max == Mathf.NegativeInfinity) return; float origMax = AxisMaxValue; float origMin = AxisMinValue; // grow - max if (MaxAutoGrow && max > origMax) { if (AutoGrowShrinkType == autoGrowShrinkType.DATA_MIN_MAX) { AxisMaxValue = max; } else { AutoSetAxisMinMax(max, min, true, true, origMin, origMax); } } // grow - min if (MinAutoGrow && min < origMin) { if (AutoGrowShrinkType == autoGrowShrinkType.DATA_MIN_MAX) { AxisMinValue = min; } else { AutoSetAxisMinMax(min, max, false, true, origMin, origMax); } } if (max == min) return; // can't shrink when max and min are the same because it's percentage based and would shrink forever if (AutoGrowShrinkType == autoGrowShrinkType.DATA_MIN_MAX) { // shrink - max if (MaxAutoShrink && max < origMax) { AxisMaxValue = max; } // shrink - min if (MinAutoShrink && min > origMin) { AxisMinValue = min; } } else { // shrink - max if (MaxAutoShrink && graph.autoShrinkAtPercent > (max - origMin) / (origMax - origMin) ) { AutoSetAxisMinMax(max, min, true, false, origMin, origMax); } // shrink - min if (MinAutoShrink && graph.autoShrinkAtPercent > (origMax - min) / (origMax - origMin) ) { AutoSetAxisMinMax(min, max, false, false, origMin, origMax); } } } } // Helper function for update min max, ensures the new values have sensible level of precision void AutoSetAxisMinMax(float val, float val2, bool max, bool grow, float aMin, float aMax) { int numTicks = 0; numTicks = AxisNumTicks-1; float changeAmt = 1 + graph.autoGrowAndShrinkByPercent; // Find tentative new max / min value float temp = 0; if (max) { if (grow) temp = changeAmt * (val - aMin) / (numTicks); else temp = changeAmt * (val - val2) / (numTicks); } else { if (grow) temp = changeAmt * (aMax - val) / (numTicks); else temp = changeAmt * (val2 - val) / (numTicks); } if (temp == 0 || aMax <= aMin) return; // Determine level of precision of tentative new value float temp2 = temp; int pow = 0; if (Mathf.Abs(temp2) > 1) { while (Mathf.Abs(temp2) > 10) { pow++; temp2 /= 10f; } } else { while (Mathf.Abs(temp2) < 0.1f) { pow--; temp2 *= 10f; } } // Update tentative to sensible level of precision float temp3 = Mathf.Pow( 10f, pow-1); temp2 = temp - (temp % temp3) + temp3; float newVal = 0; if (max) { if (grow) newVal = (numTicks) * temp2 + aMin; else newVal = (numTicks) * temp2 + val2; } else { if (grow) newVal = aMax - (numTicks) * temp2; else newVal = val2 - (numTicks) * temp2; } // Set the min / max value to the newly calculated value if (max) { AxisMaxValue = newVal; } else { AxisMinValue = newVal; } } public void UpdateAxesLabels() { // Calculate the number of labels we have int numLabels = 0; if (LabelType == labelTypes.ticks) numLabels = AxisNumTicks; else if (LabelType == labelTypes.ticks_center) numLabels = AxisNumTicks - 1; else if (LabelType == labelTypes.groups) numLabels = graph.groups.Count; else numLabels = axisLabels.Count; // Update spacing between labels float distBetween = graph.getDistBetween(graph.groups.Count, AxisLength); if (LabelType == labelTypes.ticks) _AxisLabelDistBetween = AxisLength / (numLabels - 1); else if (LabelType == labelTypes.ticks_center) _AxisLabelDistBetween = AxisLength / numLabels; else if (LabelType == labelTypes.groups) _AxisLabelDistBetween = distBetween; // Actually create or delete the labels and apply the spacing WMG_Grid axisLabelGrid = AxisLabelObjs.GetComponent<WMG_Grid>(); if (isY) { axisLabelGrid.gridNumNodesY = numLabels; axisLabelGrid.gridLinkLengthY = AxisLabelDistBetween; } else { axisLabelGrid.gridNumNodesX = numLabels; axisLabelGrid.gridLinkLengthX = AxisLabelDistBetween; } axisLabelGrid.Refresh(); // Create or delete strings based on number of labels for (int i = 0; i < numLabels; i++) { if (axisLabels.Count <= i) { axisLabels.AddNoCb("", ref _axisLabels); } } for (int i = axisLabels.Count - 1; i >= 0; i--) { if (i >= numLabels) { axisLabels.RemoveAtNoCb(i, ref _axisLabels); } } // Update xSpacingx and ySpacingy if (LabelType == labelTypes.ticks) _AxisLabelSpacing = 0; else if (LabelType == labelTypes.ticks_center) { if (AxisNumTicks == 1) _AxisLabelSpacing = 0; else _AxisLabelSpacing = AxisLength / (AxisNumTicks - 1) / 2; } else if (LabelType == labelTypes.groups) { if (graph.graphType == WMG_Axis_Graph.graphTypes.line || graph.graphType == WMG_Axis_Graph.graphTypes.line_stacked) { _AxisLabelSpacing = 0; } else { if (graph.groups.Count == 0) _AxisLabelSpacing = 0; else _AxisLabelSpacing = AxisLength / (graph.groups.Count) / 2; } } // Position the label parent objects float tickOffset = 0; if (OppositeSideLabels == OppositeSideTicks) { // don't offset label positions based on tick size if ticks drawn on the opposite side of the labels if (LabelType == labelTypes.ticks || (LabelType == labelTypes.groups && AxisNumTicks == graph.groups.Count)) { tickOffset = graph.tickSize.y; } } if (isY) { if (OppositeSideLabels ? AxisTicksRightAbove : !AxisTicksRightAbove) { changeSpritePositionToX(AxisLabelObjs, AxisPercentagePosition * otherAxis.AxisLength - tickOffset - graph.axisWidth / 2); } else { changeSpritePositionToX(AxisLabelObjs, AxisPercentagePosition * otherAxis.AxisLength + tickOffset + graph.axisWidth / 2); } } else { if (OppositeSideLabels ? AxisTicksRightAbove : !AxisTicksRightAbove) { changeSpritePositionToY(AxisLabelObjs, AxisPercentagePosition * otherAxis.AxisLength - tickOffset - graph.axisWidth / 2); } else { changeSpritePositionToY(AxisLabelObjs, AxisPercentagePosition * otherAxis.AxisLength + tickOffset + graph.axisWidth / 2); } } // Get the label objects, change their position, and set their text List<WMG_Node> LabelNodes = GetAxisLabelNodes(); if (LabelNodes == null) return; maxSpaceTakenByAxisLabels = 0; for (int i = 0; i < axisLabels.Count; i++) { if (i >= LabelNodes.Count) break; // Hide labels SetActive(LabelNodes[i].gameObject,!hideLabels); // Hide label that is the same as the axis if (LabelType == labelTypes.ticks) { if (hideTick && i == otherAxis.AxisTick) SetActive(LabelNodes[otherAxis.AxisTick].gameObject,false); if (graph.IsDualY) { if (hideTick && i == otherAxis2.AxisTick) SetActive(LabelNodes[otherAxis2.AxisTick].gameObject,false); } } // Rotate the labels LabelNodes[i].objectToLabel.transform.localEulerAngles = new Vector3(0, 0, AxisLabelRotation); bool isFirst = i == 0; bool isLast = i == axisLabels.Count - 1; // Position and pivot the labels if (isY) { if (OppositeSideLabels ? AxisTicksRightAbove : !AxisTicksRightAbove) { if (AxisBoundedLabels && (isFirst || isLast)) { changeSpritePivot(LabelNodes[i].objectToLabel, isFirst ? WMG_Graph_Manager.WMGpivotTypes.BottomRight : WMG_Graph_Manager.WMGpivotTypes.TopRight); } else { changeSpritePivot(LabelNodes[i].objectToLabel, WMG_Graph_Manager.WMGpivotTypes.Right); } changeSpritePositionTo(LabelNodes[i].objectToLabel, new Vector3(-AxisLabelSpaceOffset, AxisLabelSpacing, 0)); } else { if (AxisBoundedLabels && (isFirst || isLast)) { changeSpritePivot(LabelNodes[i].objectToLabel, isFirst ? WMG_Graph_Manager.WMGpivotTypes.BottomLeft : WMG_Graph_Manager.WMGpivotTypes.TopLeft); } else { changeSpritePivot(LabelNodes[i].objectToLabel, WMG_Graph_Manager.WMGpivotTypes.Left); } changeSpritePositionTo(LabelNodes[i].objectToLabel, new Vector3(AxisLabelSpaceOffset, AxisLabelSpacing, 0)); } } else { if (OppositeSideLabels ? AxisTicksRightAbove : !AxisTicksRightAbove) { if (AxisLabelRotation > 0) { changeSpritePivot(LabelNodes[i].objectToLabel, WMG_Graph_Manager.WMGpivotTypes.TopRight); } else { if (AxisBoundedLabels && (isFirst || isLast)) { changeSpritePivot(LabelNodes[i].objectToLabel, isFirst ? WMG_Graph_Manager.WMGpivotTypes.TopLeft : WMG_Graph_Manager.WMGpivotTypes.TopRight); } else { changeSpritePivot(LabelNodes[i].objectToLabel, WMG_Graph_Manager.WMGpivotTypes.Top); } } changeSpritePositionTo(LabelNodes[i].objectToLabel, new Vector3(AxisLabelSpacing, -AxisLabelSpaceOffset, 0)); } else { if (AxisLabelRotation > 0) { changeSpritePivot(LabelNodes[i].objectToLabel, WMG_Graph_Manager.WMGpivotTypes.BottomLeft); } else { if (AxisBoundedLabels && (isFirst || isLast)) { changeSpritePivot(LabelNodes[i].objectToLabel, isFirst ? WMG_Graph_Manager.WMGpivotTypes.BottomLeft : WMG_Graph_Manager.WMGpivotTypes.BottomRight); } else { changeSpritePivot(LabelNodes[i].objectToLabel, WMG_Graph_Manager.WMGpivotTypes.Bottom); } } changeSpritePositionTo(LabelNodes[i].objectToLabel, new Vector3(AxisLabelSpacing, AxisLabelSpaceOffset, 0)); } } // Fontsize changeLabelFontSize(LabelNodes[i].objectToLabel, AxisLabelSize); // Font color changeLabelColor(LabelNodes[i].objectToLabel, AxisLabelColor); // Font Style changeLabelFontStyle(LabelNodes[i].objectToLabel, AxisLabelFontStyle); // Font if (AxisLabelFont != null) { changeLabelFont(LabelNodes[i].objectToLabel, AxisLabelFont); } // Update text string in the List of strings based on labeler function axisLabels.SetValNoCb(i, axisLabelLabeler(this, i), ref _axisLabels); // Actually set the text changeLabelText(LabelNodes[i].objectToLabel, axisLabels[i]); if (activeInHierarchy (LabelNodes [i].gameObject)) { Vector2 labelSize = getSpriteSize(LabelNodes[i].objectToLabel); if (isY) { maxSpaceTakenByAxisLabels = Mathf.Max (maxSpaceTakenByAxisLabels, labelSize.x * Mathf.Cos (Mathf.Abs(AxisLabelRotation) * Mathf.Deg2Rad) + labelSize.y * Mathf.Sin (Mathf.Abs(AxisLabelRotation) * Mathf.Deg2Rad) * 0.5f); } else { maxSpaceTakenByAxisLabels = Mathf.Max (maxSpaceTakenByAxisLabels, labelSize.y * Mathf.Cos (Mathf.Abs(AxisLabelRotation) * Mathf.Deg2Rad) + labelSize.x * Mathf.Sin (Mathf.Abs(AxisLabelRotation) * Mathf.Deg2Rad)); } } } } string defaultAxisLabelLabeler(WMG_Axis axis, int labelIndex) { if (axis.LabelType == WMG_Axis.labelTypes.groups) { // for groups return the string defined at the graph level for groups, respects skip settings return ((labelIndex - axis.AxisLabelSkipStart) % (axis.AxisLabelSkipInterval + 1) == 0) ? (labelIndex >= axis.AxisLabelSkipStart ? axis.graph.groups[labelIndex] : "") : ""; } else { // all other label types if (axis.SetLabelsUsingMaxMin) { // if setting based on axis max and min values float num = axis.AxisMinValue + labelIndex * (axis.AxisMaxValue - axis.AxisMinValue) / (axis.axisLabels.Count-1); if (labelIndex == 0) num = axis.AxisMinValue; if (axis.graph.graphType == WMG_Axis_Graph.graphTypes.bar_stacked_percent && ((axis.isY && axis.graph.orientationType == WMG_Axis_Graph.orientationTypes.vertical) || (!axis.isY && axis.graph.orientationType == WMG_Axis_Graph.orientationTypes.horizontal))) { num = labelIndex / (axis.axisLabels.Count-1f) * 100f; } float numberToMult = Mathf.Pow(10f, axis.numDecimalsAxisLabels); string returnString = ((labelIndex - axis.AxisLabelSkipStart) % (axis.AxisLabelSkipInterval + 1) == 0) ? (labelIndex >= axis.AxisLabelSkipStart ? (Mathf.Round(num*numberToMult)/numberToMult).ToString() : "") : ""; if (axis.graph.graphType == WMG_Axis_Graph.graphTypes.bar_stacked_percent && ((axis.isY && axis.graph.orientationType == WMG_Axis_Graph.orientationTypes.vertical) || (!axis.isY && axis.graph.orientationType == WMG_Axis_Graph.orientationTypes.horizontal))) { return string.IsNullOrEmpty(returnString) ? "" : (returnString + "%"); } else { return returnString; } } else { // otherwise just return the label that is in the string list return axis.axisLabels[labelIndex]; } } } void setLabelRotations(List<WMG_Node> LabelNodes, float rotation) { foreach (WMG_Node node in LabelNodes) { node.objectToLabel.transform.localEulerAngles = new Vector3 (0, 0, rotation); } } void setFontSizeLabels(List<WMG_Node> LabelNodes, int newLabelSize) { foreach (WMG_Node node in LabelNodes) { changeLabelFontSize(node.objectToLabel, newLabelSize); } } public void setLabelScales(float newScale) { foreach (WMG_Node node in GetAxisLabelNodes()) { node.objectToLabel.transform.localScale = new Vector3(newScale, newScale, 1); } } /// <summary> /// Gets the axis label nodes. /// </summary> /// <returns>The axis label nodes.</returns> public List<WMG_Node> GetAxisLabelNodes() { WMG_Grid labelsGrid = AxisLabelObjs.GetComponent<WMG_Grid>(); if (isY) { return labelsGrid.getColumn(0); } else { return labelsGrid.getRow(0); } } /// <summary> /// Gets the axis tick nodes. /// </summary> /// <returns>The axis tick nodes.</returns> public List<WMG_Node> GetAxisTickNodes() { WMG_Grid ticksGrid = AxisTicks.GetComponent<WMG_Grid>(); if (isY) { return ticksGrid.getColumn(0); } else { return ticksGrid.getRow(0); } } }
35.049673
223
0.704863
[ "MIT" ]
DrFrolicks/DiamondHandTrainer
Assets/Graph_Maker/Scripts/WMG_Axis.cs
53,628
C#
using Foundation; using System; using System.CodeDom.Compiler; using UIKit; namespace Mit4RobotApp { public class TBSHighScores : UITableViewSource { public event EventHandler<RowSelectedEventArgs> OnRowSelected; private string[] highScoreItems; private string cellIdentifier = "cell"; public TBSHighScores(string[] highScoreItems) { this.highScoreItems = highScoreItems; } public override nint RowsInSection(UITableView tableview, nint section) { return highScoreItems.Length; } public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) { UITableViewCell cell = tableView.DequeueReusableCell(cellIdentifier); if (cell == null) { cell = new UITableViewCell(UITableViewCellStyle.Default, cellIdentifier); } cell.TextLabel.Text = highScoreItems[indexPath.Row]; cell.TextLabel.TextColor = UIColor.White; cell.BackgroundColor = UIColor.Black; return cell; } public override void RowSelected(UITableView tableView, NSIndexPath indexPath) { if (OnRowSelected != null) { OnRowSelected(this, new RowSelectedEventArgs(tableView, indexPath)); } } public class RowSelectedEventArgs : EventArgs { public UITableView tableView { get; set; } public NSIndexPath indexPath { get; set; } public RowSelectedEventArgs(UITableView tableView, NSIndexPath indexPath) : base() { this.tableView = tableView; this.indexPath = indexPath; } } } }
23.349206
87
0.740313
[ "MIT" ]
ZuydUniversity/ProgramADroid
Mit4Robot/Mit4Robot_iOS/Resources/TableviewSources/TBSHighScores.cs
1,471
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace A3ColorConverter.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
34.548387
151
0.583567
[ "MIT" ]
Casperento/a3-color-converter
A3ColorConverter/A3ColorConverter/Properties/Settings.Designer.cs
1,073
C#
using UnityEngine; [CreateAssetMenu(fileName = "Vector3NullableVariable", menuName = "Variables/Vector3NullableVariable")] public class Vector3NullableVariable : BaseVariableAsset<Vector3?> { public bool HasValue() { return value.HasValue; } public override bool Equals(Vector3? other) { return value == other; } }
23.733333
103
0.699438
[ "Apache-2.0" ]
Marguelgtz/explorer
unity-client/Assets/Scripts/MainScripts/DCL/ScriptableObject/Variables/Vector3NullableVariable.cs
356
C#
using System.Diagnostics; using System.Runtime.CompilerServices; namespace Lutra { public class GameLoop { #region Public Properties public bool Active; public bool FixedTimeStep; public double TargetFrameRate { get; private set; } public TimeSpan TargetElapsedTime { get; private set; } public TimeSpan TotalGameTime { get; private set; } public TimeSpan ElapsedGameTime { get; private set; } #endregion #region Private Variables private Game game; private bool initialized = false; private bool suppressRender = false; private Stopwatch gameTimer; private TimeSpan accumulatedElapsedTime; private long previousTicks = 0; private static readonly TimeSpan MaxElapsedTime = TimeSpan.FromMilliseconds(500); private const double TicksPerSecond = (double)TimeSpan.TicksPerSecond; #endregion #region Constructor public GameLoop(Game gameInstance, double targetFrameRate) { game = gameInstance; SetTargetFrameRate(targetFrameRate); Active = false; FixedTimeStep = true; TotalGameTime = TimeSpan.Zero; ElapsedGameTime = TimeSpan.Zero; } #endregion #region Public Methods public void SetTargetFrameRate(double targetFrameRate) { TargetFrameRate = targetFrameRate; TargetElapsedTime = TimeSpan.FromTicks((long)Math.Round(TicksPerSecond / targetFrameRate)); } public void Exit() { Active = false; suppressRender = true; } public void SuppressDraw() { suppressRender = true; } public void Run() { if (!initialized) { game.Initialize(); initialized = true; } Active = true; gameTimer = Stopwatch.StartNew(); while (Active) { Tick(); } game.ShutDown(); } public void Tick() { AccumulateTime(); if (FixedTimeStep && accumulatedElapsedTime < TargetElapsedTime) { while (accumulatedElapsedTime < TargetElapsedTime) { System.Threading.Thread.Sleep(TargetElapsedTime - accumulatedElapsedTime); AccumulateTime(); } } if (accumulatedElapsedTime > MaxElapsedTime) { accumulatedElapsedTime = MaxElapsedTime; } if (FixedTimeStep) { ElapsedGameTime = TargetElapsedTime; int stepCount = 0; while (accumulatedElapsedTime >= TargetElapsedTime) { TotalGameTime += TargetElapsedTime; accumulatedElapsedTime -= TargetElapsedTime; stepCount += 1; game.Update(); } ElapsedGameTime = TimeSpan.FromTicks(TargetElapsedTime.Ticks * stepCount); } else { ElapsedGameTime = accumulatedElapsedTime; TotalGameTime += ElapsedGameTime; accumulatedElapsedTime = TimeSpan.Zero; game.Update(); } if (suppressRender) { suppressRender = false; } else { game.Render(); } } #endregion [MethodImpl(MethodImplOptions.AggressiveInlining)] private void AccumulateTime() { long currentTicks = gameTimer.Elapsed.Ticks; accumulatedElapsedTime += TimeSpan.FromTicks(currentTicks - previousTicks); previousTicks = currentTicks; } } }
25.660256
103
0.531601
[ "MIT" ]
emmyleaf/Lutra
Lutra/src/Systems/GameLoop.cs
4,003
C#
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Text.RegularExpressions; using System.Threading; using Regen.Builtins; using Regen.Compiler.Helpers; using Regen.DataTypes; using Regen.DataTypes.Wrappers; using Regen.Flee.PublicTypes; using Regen.Helpers; using Regen.Parser; using Regen.Parser.Expressions; using ExpressionCompileException = Regen.Exceptions.ExpressionCompileException; namespace Regen.Compiler { public partial class RegenCompiler : IEvaluator { /// <summary> /// Holds all global variables that were created during compiling by <see cref="CompileGlobal"/>. /// </summary> public Dictionary<string, object> GlobalVariables { get; } = new Dictionary<string, object>(); public ExpressionContext Context { get; set; } private static readonly ThreadLocal<ExpressionContext> _threadLocalContext = new ThreadLocal<ExpressionContext>(); private static readonly ThreadLocal<RegenCompiler> _threadLocalCompiler = new ThreadLocal<RegenCompiler>(); /// <summary> /// Gets the current context that is executing the expression. /// </summary> /// <remarks>Can be null if not used properly.</remarks> public static ExpressionContext CurrentContext => _threadLocalContext.Value; /// <summary> /// Gets the current compiler that is executing the expression. /// </summary> /// <remarks>Can be null if not used properly.</remarks> public static RegenCompiler CurrentCompiler => _threadLocalCompiler.Value; public RegenCompiler(params RegenModule[] modules) { Context = CreateContext(null, modules); Context.Imports.AddInstance(this, "__compiler__"); } public static ExpressionContext CreateContext(Dictionary<string, object> globalVariables = null, RegenModule[] modules = null) { // Allow the expression to use all static public methods of System.Math var ctx = new ExpressionContext(); ctx.Options.ParseCulture = CultureInfo.InvariantCulture; ctx.Imports.AddType(typeof(Math)); ctx.Imports.AddType(typeof(CommonExpressionFunctions)); ctx.Imports.AddType(typeof(CommonLinq)); ctx.Imports.AddInstance(new CommonRandom(), "random"); ctx.Imports.AddInstance(ctx, "__context__"); ctx.Imports.AddInstance(new VariableCollectionWrapper(ctx.Variables), "__vars__"); ctx.Imports.AddType(typeof(Regex)); ctx.Variables.ResolveFunction += (sender, args) => { ; }; ctx.Variables.ResolveVariableType += (sender, args) => { ; }; ctx.Variables.ResolveVariableValue += (sender, args) => { ; }; if (modules != null) foreach (var mod in modules) { ctx.Imports.AddInstance(mod.Instance, mod.Name); } if (globalVariables != null) foreach (var kv in globalVariables) { ctx.Variables.Add(kv.Key, kv.Value); } return ctx; } #region Modules /// <summary> /// Adds or override a module to <see cref="ExpressionContext.Imports"/>. /// </summary> /// <param name="mod">The module to add</param> public void AddModule(RegenModule mod) { Context.Imports.AddInstance(mod.Instance, mod.Name); //any changes, syncronize with CreateContext. } /// <summary> /// Adds or override a module to <see cref="ExpressionContext.Imports"/>. /// </summary> /// <remarks>Used as a simple accessor from a template.</remarks> public void AddModule(string name, object instance) { Context.Imports.AddInstance(instance, name); //any changes, syncronize with CreateContext. } /// <summary> /// Attempts to remove module from <see cref="ExpressionContext.Imports"/>. /// </summary> /// <param name="mod">The module to remove</param> /// <returns>true if successfully removed</returns> public bool RemoveModule(RegenModule mod) { var imprt = Context.Imports.RootImport.FirstOrDefault(ib => ib.Name.Equals(mod.Name)); if (imprt != null) { Context.Imports.RootImport.Remove(imprt); return !Context.Imports.RootImport.Contains(imprt); } return false; } /// <summary> /// Attempts to remove module from <see cref="ExpressionContext.Imports"/>. /// </summary> /// <param name="moduleName">The module's name to remove</param> /// <returns>true if successfully removed</returns> public bool RemoveModule(string moduleName) { var imprt = Context.Imports.RootImport.FirstOrDefault(ib => ib.Name.Equals(moduleName)); if (imprt != null) { Context.Imports.RootImport.Remove(imprt); return !Context.Imports.RootImport.Contains(imprt); } return false; } #endregion #region Evaluation public string EvaluateString(string expression, Line line = null) { var evaluated = EvaluateUnpackedObject(expression, line); return evaluated as string ?? evaluated?.ToString() ?? ""; } public Int32 EvaluateInt32(string expression, Line line = null) { return Evaluate<Int32>(expression, line); } public T Evaluate<T>(string expression, Line line = null) { var evaluated = EvaluateUnpackedObject(expression, line); if (typeof(T) == typeof(string)) return (T) (object) ((evaluated as string) ?? evaluated?.ToString() ?? ""); return (T) Convert.ChangeType(evaluated, typeof(T)); } public object EvaluateUnpackedObject(string expression, Line line = null) { var evaluated = EvaluateObject(expression, line); if (evaluated is Data data) return data.Value; return evaluated; } public object EvaluateObject(string expression, Line line = null) { //core between string to expr methods var eew = Expression.GetExpressionWithWalker(expression); return EvaluateObject(eew.Expression, line); } public string EvaluateString(Expression expression, ExpressionWalker ew, Line line = null) { var evaluated = EvaluateUnpackedObject(expression, ew, line); return evaluated as string ?? evaluated?.ToString() ?? ""; } public Int32 EvaluateInt32(Expression expression, ExpressionWalker ew, Line line = null) { return Evaluate<Int32>(expression, ew, line); } public T Evaluate<T>(Expression expression, ExpressionWalker ew, Line line = null) { var evaluated = EvaluateUnpackedObject(expression, ew, line); if (typeof(T) == typeof(string)) return (T) (object) ((evaluated as string) ?? evaluated?.ToString() ?? ""); return (T) Convert.ChangeType(evaluated, typeof(T)); } public object EvaluateUnpackedObject(Expression expression, ExpressionWalker ew, Line line = null) { var evaluated = EvaluateObject(expression, line); if (evaluated is Data data) return data.Value; return evaluated; } public object EvaluateObject(Expression expression, Line line = null) { //Core evaluation method. _threadLocalContext.Value = Context; _threadLocalCompiler.Value = this; try { return EvaluateExpression(expression); } catch (Flee.PublicTypes.ExpressionCompileException e) { throw new Regen.Exceptions.ExpressionCompileException($"Was unable to evaluate expression: {expression}\t At line ({line?.LineNumber}): {line?.Content}", e); } finally { _threadLocalContext.Value = null; _threadLocalCompiler.Value = null; } } #endregion } }
41.594059
174
0.618067
[ "MIT" ]
Nucs/Regen
src/Regen.Core/Compiler/RegenCompiler.cs
8,404
C#
// <copyright file="IUserProfile.Generated.cs" company="Okta, Inc"> // Copyright (c) 2014 - present Okta, Inc. All rights reserved. // Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information. // </copyright> // This file was automatically generated. Don't modify it directly. using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace Okta.Sdk { /// <summary>Represents a UserProfile resource in the Okta API.</summary> public partial interface IUserProfile : IResource { string Email { get; set; } string FirstName { get; set; } string LastName { get; set; } string Login { get; set; } string MobilePhone { get; set; } string SecondEmail { get; set; } } }
26.125
112
0.67823
[ "Apache-2.0" ]
cwoolum/okta-sdk-dotnet
src/Okta.Sdk/Generated/IUserProfile.Generated.cs
836
C#
using System; using System.Collections.Generic; using System.Linq; using FluentAssertions; using RezRouting.Configuration; using RezRouting.Resources; using Xunit; namespace RezRouting.Tests.Configuration { public class ResourceCustomPropertyConfigurationTests { [Fact] public void custom_properties_on_resource_should_be_empty_if_none_configured() { var resource = BuildResource(root => root.Singular("Profile", profile => { })); resource.CustomProperties.Should().BeEmpty(); } [Fact] public void should_add_custom_properties_configured_to_resource() { var resource = BuildResource(root => root.Singular("Profile", profile => { profile.CustomProperties(props => { props["key1"] = "value1"; props["key2"] = "value2"; }); })); var expectedData = new Dictionary<string, object> { { "key1", "value1" }, { "key2", "value2" } }; resource.CustomProperties.Should().Equal(expectedData); } [Fact] public void should_combine_all_custom_properties_configured_on_resource() { var resource = BuildResource(root => root.Singular("Profile", profile => { profile.CustomProperties(props => props["key1"] = "value1"); profile.CustomProperties(props => props["key2"] = "value2"); })); var expectedData = new Dictionary<string, object> { { "key1", "value1" }, { "key2", "value2" } }; resource.CustomProperties.Should().Equal(expectedData); } /// <summary> /// Configures resources using supplied action and returns the first child resource /// </summary> /// <param name="configure"></param> /// <returns></returns> private Resource BuildResource(Action<IRootResourceBuilder> configure) { var builder = RootResourceBuilder.Create(); configure(builder); var root = builder.Build(); return root.Children.Single(); } } }
32.760563
91
0.548581
[ "MIT" ]
danmalcolm/RezRouting.Net
src/RezRouting.Tests/Configuration/ResourceCustomPropertyConfigurationTests.cs
2,328
C#
using RATools.Data; using RATools.Parser.Internal; using System.Collections.Generic; using System.Linq; namespace RATools.Parser.Functions { internal abstract class ComparisonModificationFunction : TriggerBuilderContext.FunctionDefinition { public ComparisonModificationFunction(string name) : base(name) { Parameters.Add(new VariableDefinitionExpression("comparison")); } public override bool ReplaceVariables(InterpreterScope scope, out ExpressionBase result) { if (!IsInTriggerClause(scope, out result)) return false; var comparison = GetParameter(scope, "comparison", out result); if (comparison == null) return false; result = new FunctionCallExpression(Name.Name, new ExpressionBase[] { comparison }); return true; } public override ParseErrorExpression BuildTrigger(TriggerBuilderContext context, InterpreterScope scope, FunctionCallExpression functionCall) { var comparison = functionCall.Parameters.First(); return BuildTriggerCondition(context, scope, comparison); } protected ParseErrorExpression BuildTriggerCondition(TriggerBuilderContext context, InterpreterScope scope, ExpressionBase condition) { var builder = new ScriptInterpreterAchievementBuilder(); ExpressionBase result; if (!TriggerBuilderContext.ProcessAchievementConditions(builder, condition, scope, out result)) return (ParseErrorExpression)result; if (builder.AlternateRequirements.Count > 0) return new ParseErrorExpression(Name.Name + " does not support ||'d conditions", condition); if (builder.CoreRequirements.Count > 1) { var last = builder.CoreRequirements.Last(); foreach (var requirement in builder.CoreRequirements) { if (requirement.Type == RequirementType.None && !ReferenceEquals(requirement, last)) requirement.Type = RequirementType.AndNext; } } ParseErrorExpression error = ValidateSingleCondition(builder.CoreRequirements); if (error != null) return new ParseErrorExpression(error, condition); error = ModifyRequirements(builder); if (error != null) return error; foreach (var requirement in builder.CoreRequirements) context.Trigger.Add(requirement); return null; } protected ParseErrorExpression ValidateSingleCondition(ICollection<Requirement> requirements) { if (requirements.Count == 0 || requirements.Last().Operator == RequirementOperator.None || requirements.Last().Type != RequirementType.None) { return new ParseErrorExpression("comparison did not evaluate to a valid comparison"); } if (requirements.Count(r => r.Type == RequirementType.None) != 1) return new ParseErrorExpression(Name.Name + " does not support &&'d conditions"); return null; } protected abstract ParseErrorExpression ModifyRequirements(AchievementBuilder builder); } }
39.195402
149
0.631085
[ "MIT" ]
gdeOo/RATools
Parser/Functions/ComparisonModificationFunction.cs
3,412
C#
using Bridge.QUnit; using ClientTestLibrary.Utilities; using System.Linq; namespace ClientTestLibrary.Linq { class TestLinqSetOperators { public static void Test(Assert assert) { // TEST int[] a = { 1, 2 }; int[] b = { 1, 2 }; var result = a.Intersect(b).ToArray(); assert.Expect(8); // TEST int[] numbers = { 1, 2, 3, 3, 1, 5, 4, 2, 3 }; var uniqueNumbers = numbers.Distinct().ToArray(); assert.DeepEqual(uniqueNumbers, new[] { 1, 2, 3, 5, 4 }, "Distinct() to remove duplicate elements"); // TEST var distinctPersonGroups = (from p in Person.GetPersons() select p.Group).Distinct().ToArray(); assert.DeepEqual(distinctPersonGroups, new[] { "A", "C", "B", null }, "Distinct() to remove duplicate Group elements"); // TEST int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 }; int[] numbersB = { 1, 3, 5, 7, 8 }; var uniqueNumbersAB = numbersA.Union(numbersB).ToArray(); assert.DeepEqual(uniqueNumbersAB, new[] { 0, 2, 4, 5, 6, 8, 9, 1, 3, 7 }, "Union() to get unique number sequence"); // TEST var nameChars = from p in Person.GetPersons() select p.Name[0]; var cityChars = from p in Person.GetPersons() select p.City[0]; var uniqueFirstChars = nameChars.Union(cityChars).ToArray(); assert.DeepEqual(uniqueFirstChars, new[] { (int)'F', (int)'Z', (int)'J', (int)'B', (int)'D', (int)'I', (int)'M', (int)'N', (int)'E', (int)'T', (int)'L', (int)'P', (int)'R', (int)'O' }, "Union to get unique first letters of Name and City"); // TEST var commonNumbersCD = numbersA.Intersect(numbersB).ToArray(); assert.DeepEqual(commonNumbersCD, new[] { 5, 8 }, "Intersect() to get common number sequence"); // TEST nameChars = from p in Person.GetPersons() select p.Name[0]; cityChars = from p in Person.GetPersons() select p.City[0]; var commonFirstChars = nameChars.Intersect(cityChars).ToArray(); assert.DeepEqual(commonFirstChars, new[] { (int)'B', (int)'D' }, "Intersect() to get common first letters of Name and City"); // TEST var exceptNumbersCD = numbersA.Except(numbersB).ToArray(); assert.DeepEqual(exceptNumbersCD, new[] { 0, 2, 4, 6, 9 }, "Except() to get numbers from first sequence and does not contain the second sequence numbers"); // TEST var exceptFirstChars = nameChars.Except(cityChars).ToArray(); assert.DeepEqual(exceptFirstChars, new[] { (int)'F', (int)'Z', (int)'J', (int)'I', (int)'M', (int)'N' }, "Except() to get letters from Name sequence and does not contain City letters"); } } }
43.661765
137
0.546986
[ "Apache-2.0" ]
corefan/Bridge
Testing/tests/client/Tests/Linq/TestLinqSetOperators.cs
2,971
C#
using System.IO; using System.Runtime.Serialization; using GameEstate.Formats.Red.CR2W.Reflection; using FastMember; using static GameEstate.Formats.Red.Records.Enums; namespace GameEstate.Formats.Red.Types { [DataContract(Namespace = "")] [REDMeta] public class CBTTaskSendTutorialEvent : IBehTreeTask { [Ordinal(1)] [RED("onActivation")] public CBool OnActivation { get; set;} [Ordinal(2)] [RED("onDeactivation")] public CBool OnDeactivation { get; set;} [Ordinal(3)] [RED("guardSwordWarning")] public CBool GuardSwordWarning { get; set;} [Ordinal(4)] [RED("guardGeneralWarning")] public CBool GuardGeneralWarning { get; set;} [Ordinal(5)] [RED("guardLootingWarning")] public CBool GuardLootingWarning { get; set;} public CBTTaskSendTutorialEvent(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name){ } public static new CVariable Create(CR2WFile cr2w, CVariable parent, string name) => new CBTTaskSendTutorialEvent(cr2w, parent, name); public override void Read(BinaryReader file, uint size) => base.Read(file, size); public override void Write(BinaryWriter file) => base.Write(file); } }
35.969697
136
0.723673
[ "MIT" ]
smorey2/GameEstate
src/GameEstate.Formats.Red/Formats/Red/W3/RTTIConvert/CBTTaskSendTutorialEvent.cs
1,187
C#
using System; namespace p06RhombusOfStars { class Program { static void Main(string[] args) { int n = int.Parse(Console.ReadLine()); for (int row = 1; row <= n; row++) { Console.Write(new string(' ', n - row)); for (int i = 0; i < row; i++) { Console.Write("* "); } Console.WriteLine(); } for (int i = n - 1; i >= 0; i--) { Console.Write(new string(' ', n - i)); for (int j = 0; j < i; j++) { Console.Write("* "); } Console.WriteLine(); } } } }
20.891892
56
0.332471
[ "MIT" ]
vesy53/SoftUni
Programming Basics - C#/Exercises/06.DrawingFiguresWithLoops/p06RhombusOfStars/Program.cs
775
C#
using System; using System.Collections.Generic; using System.Text; namespace EP94.LgSmartThinq.Utils { public enum LogLevel { Fatal, Error, Warning, Information, Debug, Verbose } public class SmartThinqLogger { public static LogHandler OnNewLogMessage; public delegate void LogHandler(string message, LogLevel logLeve, params object[] parameters); internal static void Log(string message, LogLevel logLevel, params object[] parameters) { OnNewLogMessage?.Invoke(message, logLevel, parameters); } } }
24.076923
102
0.64377
[ "MIT" ]
evaanp/EP94.LgSmartThinq
Utils/SmartThinqLogger.cs
628
C#
using UnityEngine; public class MoveToClickPoint : NavMeshAgentMovement { [SerializeField] private GameObject m_clickedVisualPrefab; private bool m_hasClickedPrefab; private GameObject m_clickedVisualGameObject; private bool m_hasClickedVisualGameObject; [SerializeField] private CodedGameEventListener[] cutsceneEvents; #region Overrides of NavMeshAgentMovement private void OnEnable() { if (cutsceneEvents == null || cutsceneEvents.Length < 1) return; Debug.Assert(cutsceneEvents != null, nameof(cutsceneEvents) + " != null"); foreach (CodedGameEventListener t in cutsceneEvents) { t?.OnEnable(StopMovement); } } private void OnDisable() { if (cutsceneEvents == null || cutsceneEvents.Length < 1) return; Debug.Assert(cutsceneEvents != null, nameof(cutsceneEvents) + " != null"); foreach (CodedGameEventListener t in cutsceneEvents) { t?.OnDisable(); } DestroyClickedObject(); } /// <inheritdoc /> protected override void Start() { base.Start(); m_hasClickedPrefab = m_clickedVisualPrefab != null; } /// <inheritdoc /> protected override void SetDestination() { if (!Input.GetButtonDown("Fire1")) return; // ReSharper disable once PossibleNullReferenceException if (!Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out RaycastHit hit, 100)) return; destination = hit.point; if (!m_hasClickedPrefab) return; if (m_hasClickedVisualGameObject) { m_hasClickedVisualGameObject = false; Destroy(m_clickedVisualGameObject); m_clickedVisualGameObject = null; } m_clickedVisualGameObject = Instantiate(m_clickedVisualPrefab, destination, Quaternion.identity); m_hasClickedVisualGameObject = true; } protected override void StopMovement() { DestroyClickedObject(); } #endregion private void DestroyClickedObject() { if (!m_hasClickedVisualGameObject) return; m_hasClickedVisualGameObject = false; Destroy(m_clickedVisualGameObject); m_clickedVisualGameObject = null; } }
28.6125
113
0.659677
[ "MIT" ]
JamesLaFritz/TheGreatFleece
Assets/The Great Fleece/Game/Scripts/Movement/MoveToClickPoint.cs
2,289
C#
using ReserveBlockCore.Data; using ReserveBlockCore.Models; using ReserveBlockCore.Services; namespace ReserveBlockCore.Utilities { public class BlockchainRescanUtility { public static async Task<bool> ValidateBlock(Block block, bool blockDownloads = false) { bool result = false; if (block == null) return result; //null block submitted. reject if (block.Height == 0) { //Genesis Block result = true; //StateData.UpdateTreis(block); return result; } var verifyBlockSig = SignatureService.VerifySignature(block.Validator, block.Hash, block.ValidatorSignature); //validates the signature of the validator that crafted the block if (verifyBlockSig != true) { return result;//block rejected due to failed validator signature } //Validates that the block has same chain ref if (block.ChainRefId != BlockchainData.ChainRef) { return result;//block rejected due to chainref difference } var newBlock = new Block { Height = block.Height, Timestamp = block.Timestamp, Transactions = block.Transactions, Validator = block.Validator, ChainRefId = block.ChainRefId, }; newBlock.Rebuild(block); //This will also check that the prev hash matches too if (!newBlock.Hash.Equals(block.Hash)) { return result;//block rejected } if (!newBlock.MerkleRoot.Equals(block.MerkleRoot)) { return result;//block rejected } if (block.Height != 0) { var blockCoinBaseResult = BlockchainData.ValidateBlock(block); //this checks the coinbase tx //Need to check here the prev hash if it is correct! if (blockCoinBaseResult == false) return result;//block rejected if (block.Transactions.Count() > 0) { //validate transactions. bool rejectBlock = false; foreach (Transaction transaction in block.Transactions) { if (transaction.FromAddress != "Coinbase_TrxFees" && transaction.FromAddress != "Coinbase_BlkRwd") { var txResult = await TransactionValidatorService.VerifyTX(transaction, blockDownloads); rejectBlock = txResult == false ? rejectBlock = true : false; } else { //do nothing as its the coinbase fee } if (rejectBlock) break; } if (rejectBlock) return result;//block rejected due to bad transaction(s) result = true; } return result;//block accepted } else { //Genesis Block result = true; //StateData.UpdateTreis(block); return result; } //Need to add validator validation method. } } }
32.225225
122
0.488957
[ "MIT" ]
ReserveBlockIO/Core-CLI
ReserveBlockCore/Utilities/BlockchainRescanUtility.cs
3,579
C#
using System; using NUnit.Framework; using System.Collections.Generic; using System.Linq; using FluentAssertions; namespace CK.Text.Tests { [TestFixture] public class StringMatcherMatchJSONTests { [Test] public void match_JSON_objects() { { var j = @"{""A"":1,""B"":2}"; StringMatcher m = new StringMatcher( j ); object o; m.MatchJSONObject( out o ).Should().BeTrue(); var list = o as List<KeyValuePair<string, object>>; list.Select( k => k.Key + '|' + k.Value ).Concatenate().Should().Be( "A|1, B|2" ); } { var j = @"{ ""A"" : 1.0, ""B"" : 2 }"; StringMatcher m = new StringMatcher( j ); object o; m.MatchJSONObject( out o ).Should().BeTrue(); var list = o as List<KeyValuePair<string, object>>; list.Select( k => k.Key + '|' + k.Value ).Concatenate().Should().Be( "A|1, B|2" ); } { var j = @"{ ""A"" : [ ""a"" , 3 , null , 6], ""B"" : [ 2, 3, ""XX"" ] }"; StringMatcher m = new StringMatcher( j ); object o; m.MatchJSONObject( out o ).Should().BeTrue(); var list = o as List<KeyValuePair<string, object>>; list.Select( k => k.Key + '|' + ((List<object>)k.Value).Select( v => v?.ToString() ).Concatenate( "+" ) ) .Concatenate().Should().Be( "A|a+3++6, B|2+3+XX" ); } } [Test] public void match_JSON_empty_array_or_objects() { { var j = @"{}"; StringMatcher m = new StringMatcher( j ); object o; m.MatchJSONObject( out o ).Should().BeTrue(); var list = o as List<KeyValuePair<string, object>>; list.Should().BeEmpty(); } { var j = @"[]"; StringMatcher m = new StringMatcher( j ); object o; m.MatchJSONObject( out o ).Should().BeTrue(); var list = o as List<object>; list.Should().BeEmpty(); } } [TestCase( "1.2" )] [TestCase( "/* ... */1.2// ..." )] [TestCase( "1.2/* ..." )] [TestCase( "/* ... */1.2// ..." )] [TestCase( @"/* */ // ... /* 3 */ 1.2 //... /*" )] public void match_JSON_skips_JS_comments( string jsonWithComment ) { StringMatcher m = new StringMatcher( jsonWithComment ); object o; m.MatchJSONObject( out o ).Should().BeTrue(); o.Should().Be( 1.2 ); } } }
34.963855
123
0.4204
[ "MIT" ]
Kuinox/CK-Text
Tests/CK.Text.Tests/StringMatcherMatchJSONTests.cs
2,902
C#
// ----------------------------------------------------------------- // <copyright file="GameListenerTests.cs" company="2Dudes"> // Copyright (c) | Jose L. Nunez de Caceres et al. // https://linkedin.com/in/nunezdecaceres // // All Rights Reserved. // // Licensed under the MIT License. See LICENSE in the project root for license information. // </copyright> // ----------------------------------------------------------------- namespace Fibula.Communications.Listeners.Tests { using System; using System.ComponentModel.DataAnnotations; using System.Net.Sockets; using System.Threading; using System.Threading.Tasks; using Fibula.Common.TestingUtilities; using Fibula.Communications.Contracts.Abstractions; using Fibula.Communications.Listeners; using Fibula.Security.Contracts; using Microsoft.Extensions.Options; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using Serilog; /// <summary> /// Tests for the <see cref="GameListener{T}"/> class. /// </summary> [TestClass] public class GameListenerTests { /// <summary> /// Checks <see cref="GameListener{T}"/> initialization. /// </summary> [TestMethod] public void GameListener_Initialization() { Mock<ILogger> loggerMock = new Mock<ILogger>(); Mock<ISocketConnectionFactory> connectionFactoryMock = new Mock<ISocketConnectionFactory>(); Mock<IDoSDefender> defenderMock = new Mock<IDoSDefender>(); GameListenerOptions gameListenerOptions = new GameListenerOptions() { Port = 7171, }; // Initialize with null parameters, should throw. ExceptionAssert.Throws<ArgumentNullException>(() => new GameListener<ISocketConnectionFactory>(null, Options.Create(gameListenerOptions), connectionFactoryMock.Object, defenderMock.Object), "Value cannot be null. (Parameter 'logger')"); ExceptionAssert.Throws<ArgumentNullException>(() => new GameListener<ISocketConnectionFactory>(loggerMock.Object, null, connectionFactoryMock.Object, defenderMock.Object), "Value cannot be null. (Parameter 'options')"); ExceptionAssert.Throws<ArgumentNullException>(() => new GameListener<ISocketConnectionFactory>(loggerMock.Object, Options.Create(gameListenerOptions), null, defenderMock.Object), "Value cannot be null. (Parameter 'socketConnectionFactory')"); // A null DoS defender is OK. new GameListener<ISocketConnectionFactory>(loggerMock.Object, Options.Create(gameListenerOptions), connectionFactoryMock.Object, null); // And initialize with all good values. new GameListener<ISocketConnectionFactory>(loggerMock.Object, Options.Create(gameListenerOptions), connectionFactoryMock.Object, defenderMock.Object); } /// <summary> /// Checks the <see cref="GameListener{T}"/>'s options validation. /// </summary> [TestMethod] public void GameListener_OptionsValidation() { Mock<ILogger> loggerMock = new Mock<ILogger>(); Mock<ISocketConnectionFactory> connectionFactoryMock = new Mock<ISocketConnectionFactory>(); Mock<IDoSDefender> defenderMock = new Mock<IDoSDefender>(); GameListenerOptions goodGameListenerOptions = new GameListenerOptions() { Port = 7171 }; GameListenerOptions badGameListenerOptions = new GameListenerOptions(); // Initialize with null parameters, should throw. ExceptionAssert.Throws<ArgumentNullException>( () => new GameListener<ISocketConnectionFactory>(loggerMock.Object, null, connectionFactoryMock.Object, defenderMock.Object), "Value cannot be null. (Parameter 'options')"); ExceptionAssert.Throws<ValidationException>( () => new GameListener<ISocketConnectionFactory>(loggerMock.Object, Options.Create(badGameListenerOptions), connectionFactoryMock.Object, defenderMock.Object), "A port for the game listener must be speficied."); // And initialize with all good values. new GameListener<ISocketConnectionFactory>(loggerMock.Object, Options.Create(goodGameListenerOptions), connectionFactoryMock.Object, defenderMock.Object); } /// <summary> /// Checks that the <see cref="GameListener{T}"/> invokes the <see cref="IListener.NewConnection"/> event. /// </summary> /// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns> [TestMethod] public async Task GameListener_CallsNewConnectionEvent() { const ushort AnyEphemerealPort = 7171; const int ExpectedConnectionCount = 1; const int NewConnectionsToEmulate = 1; TimeSpan waitForConnectionDelay = TimeSpan.FromSeconds(2); Mock<ILogger> loggerMock = new Mock<ILogger>(); Mock<IDoSDefender> defenderMock = new Mock<IDoSDefender>(); Mock<ITcpListener> tcpListenerMock = this.SetupTcpListenerMock(NewConnectionsToEmulate); Mock<ISocketConnectionFactory> connectionFactoryMock = this.SetupSocketConnectionFactory(); GameListenerOptions gameListenerOptions = new GameListenerOptions() { Port = AnyEphemerealPort, }; IListener gameListener = new GameListener<ISocketConnectionFactory>( loggerMock.Object, Options.Create(gameListenerOptions), connectionFactoryMock.Object, defenderMock.Object, tcpListenerMock.Object); var connectionCount = 0; var listenerTask = gameListener.StartAsync(CancellationToken.None); gameListener.NewConnection += (connection) => { connectionCount++; }; // Delay for a second and check that the counter has gone up on connections count. await Task.Delay(waitForConnectionDelay).ContinueWith(prev => { Assert.AreEqual(ExpectedConnectionCount, connectionCount, "New connections events counter does not match."); }); } private Mock<ITcpListener> SetupTcpListenerMock(int newConnectionsToEmulate) { Mock<ITcpListener> tcpListenerMock = new Mock<ITcpListener>(); var bigEnoughTimeToWaitAfterGoal = TimeSpan.FromMinutes(1); var emulatedConnectionsCount = 0; async Task<Socket> WaitForSocketMock() { if (emulatedConnectionsCount++ == newConnectionsToEmulate) { // Wait for a minute if we've reached the target count of connections to emulate. await Task.Delay(bigEnoughTimeToWaitAfterGoal); } return new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); } tcpListenerMock.Setup(l => l.AcceptSocketAsync()).Returns(WaitForSocketMock); return tcpListenerMock; } private Mock<ISocketConnectionFactory> SetupSocketConnectionFactory() { var mockedCreatedConnection = new Mock<ISocketConnection>(); var connectionFactoryMock = new Mock<ISocketConnectionFactory>(); connectionFactoryMock.Setup(c => c.Create(It.IsAny<Socket>())) .Returns(mockedCreatedConnection.Object); return connectionFactoryMock; } } }
45.011765
254
0.646628
[ "MIT" ]
jlnunez89/fibula-mmo
src/Fibula.Communications.Tests/GameListenerTests.cs
7,652
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace Rwp { public partial class ReleaseNotes : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } } }
19.705882
60
0.635821
[ "MIT" ]
rlittletht/RWLLPracticeTool
Rwp/ReleaseNotes.aspx.cs
337
C#
// Copyright 2018 Esri. // // 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 ArcGISRuntime.Samples.Managers; using Esri.ArcGISRuntime.LocalServices; using Esri.ArcGISRuntime.Mapping; using System; using System.IO; using System.Windows; namespace ArcGISRuntime.WPF.Samples.LocalServerMapImageLayer { [ArcGISRuntime.Samples.Shared.Attributes.Sample( "Local Server map image layer", "Local Server", "This sample demonstrates how to display a Map Image Layer from a local map service", "This sample depends on the local server being installed and configured. See https://developers.arcgis.com/net/latest/wpf/guide/local-server.htm for details and instructions.\nSample data is loaded in the background. ")] [ArcGISRuntime.Samples.Shared.Attributes.OfflineData("dee5d8060a6048a4b063484199a9546b")] public partial class LocalServerMapImageLayer { // Hold a reference to the local map service private LocalMapService _localMapService; public LocalServerMapImageLayer() { InitializeComponent(); // set up the sample Initialize(); } private async void Initialize() { // Create a map and add it to the view MyMapView.Map = new Map(Basemap.CreateLightGrayCanvasVector()); try { // LocalServer must not be running when setting the data path. if (LocalServer.Instance.Status == LocalServerStatus.Started) { await LocalServer.Instance.StopAsync(); } // Set the local data path - must be done before starting. On most systems, this will be C:\EsriSamples\AppData. // This path should be kept short to avoid Windows path length limitations. string tempDataPathRoot = Directory.GetParent(Environment.GetFolderPath(Environment.SpecialFolder.Windows)).FullName; string tempDataPath = Path.Combine(tempDataPathRoot, "EsriSamples", "AppData"); Directory.CreateDirectory(tempDataPath); // CreateDirectory won't overwrite if it already exists. LocalServer.Instance.AppDataPath = tempDataPath; // Start the local server instance await LocalServer.Instance.StartAsync(); // Get the path to the map package that will be served string datapath = GetDataPath(); // Create the Map Service from the data _localMapService = new LocalMapService(datapath); // Start the feature service await _localMapService.StartAsync(); // Get the url to the map service Uri myServiceUri = _localMapService.Url; // Create the layer from the url ArcGISMapImageLayer myImageLayer = new ArcGISMapImageLayer(myServiceUri); // Add the layer to the map MyMapView.Map.OperationalLayers.Add(myImageLayer); // Wait for the layer to load await myImageLayer.LoadAsync(); // Set the viewpoint on the map to show the data MyMapView.SetViewpoint(new Viewpoint(myImageLayer.FullExtent)); } catch (Exception ex) { MessageBox.Show(string.Format("Please ensure that local server is installed prior to using the sample. See instructions in readme.md. Message: {0}", ex.Message), "Local Server failed to start"); } } private static string GetDataPath() { return DataManager.GetDataFolder("dee5d8060a6048a4b063484199a9546b", "RelationshipID.mpk"); } } }
44.375
228
0.649531
[ "Apache-2.0" ]
ChrisFrenchPDX/arcgis-runtime-samples-dotnet
src/WPF/ArcGISRuntime.WPF.Viewer/Samples/Local Server/LocalServerMapImageLayer/LocalServerMapImageLayer.xaml.cs
4,260
C#