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
#region Snippet:Managing_Resource_Groups_Namespaces using System; using System.Threading.Tasks; using Azure.Core; using Azure.Identity; using Azure.ResourceManager.Resources; using Azure.ResourceManager.Resources.Models; #endregion using NUnit.Framework; namespace Azure.ResourceManager.Tests.Samples { class Sample2_ManagingResourceGroups { [Test] [Ignore("Only verifying that the sample builds")] public async Task SetUpWithDefaultSubscription() { #region Snippet:Managing_Resource_Groups_DefaultSubscription ArmClient armClient = new ArmClient(new DefaultAzureCredential()); Subscription subscription = await armClient.GetDefaultSubscriptionAsync(); #endregion Snippet:Managing_Resource_Groups_DefaultSubscription } [Test] [Ignore("Only verifying that the sample builds")] public async Task CreateResourceGroup() { #region Snippet:Managing_Resource_Groups_CreateAResourceGroup // First, initialize the ArmClient and get the default subscription ArmClient armClient = new ArmClient(new DefaultAzureCredential()); // Now we get a ResourceGroup collection for that subscription Subscription subscription = await armClient.GetDefaultSubscriptionAsync(); ResourceGroupCollection rgCollection = subscription.GetResourceGroups(); // With the collection, we can create a new resource group with an specific name string rgName = "myRgName"; AzureLocation location = AzureLocation.WestUS2; ResourceGroupData rgData = new ResourceGroupData(location); ArmOperation<ResourceGroup> operation = await rgCollection.CreateOrUpdateAsync(true, rgName, rgData); ResourceGroup resourceGroup = operation.Value; #endregion Snippet:Managing_Resource_Groups_CreateAResourceGroup } [Test] [Ignore("Only verifying that the sample builds")] public async Task GettingResourceGroupCollection() { #region Snippet:Managing_Resource_Groups_GetResourceGroupCollection ArmClient armClient = new ArmClient(new DefaultAzureCredential()); Subscription subscription = await armClient.GetDefaultSubscriptionAsync(); ResourceGroupCollection rgCollection = subscription.GetResourceGroups(); // code omitted for brevity string rgName = "myRgName"; #if !SNIPPET //Check if "myRgName" exists, if not, create it first or run CreateResourceGroup() ResourceGroup rg = await subscription.GetResourceGroups().GetIfExistsAsync(rgName); if (rg == null) { AzureLocation location = AzureLocation.WestUS2; ResourceGroupData rgData = new ResourceGroupData(location); _ = await rgCollection.CreateOrUpdateAsync(true, rgName, rgData); } #endif ResourceGroup resourceGroup = await rgCollection.GetAsync(rgName); #endregion Snippet:Managing_Resource_Groups_GetResourceGroupCollection } [Test] [Ignore("Only verifying that the sample builds")] public async Task ListAllResourceGroups() { #region Snippet:Managing_Resource_Groups_ListAllResourceGroup // First, initialize the ArmClient and get the default subscription ArmClient armClient = new ArmClient(new DefaultAzureCredential()); Subscription subscription = await armClient.GetDefaultSubscriptionAsync(); // Now we get a ResourceGroup collection for that subscription ResourceGroupCollection rgCollection = subscription.GetResourceGroups(); // We can then iterate over this collection to get the resources in the collection await foreach (ResourceGroup rg in rgCollection) { Console.WriteLine(rg.Data.Name); } #endregion Snippet:Managing_Resource_Groups_ListAllResourceGroup } [Test] [Ignore("Only verifying that the sample builds")] public async Task UpdateAResourceGroup() { #region Snippet:Managing_Resource_Groups_UpdateAResourceGroup // Note: Resource group named 'myRgName' should exist for this example to work. ArmClient armClient = new ArmClient(new DefaultAzureCredential()); Subscription subscription = await armClient.GetDefaultSubscriptionAsync(); string rgName = "myRgName"; #if !SNIPPET //Check if 'myRgName' exists, if not, create it first or run CreateResourceGroup() ResourceGroup rg = await subscription.GetResourceGroups().GetIfExistsAsync(rgName); if (rg == null) { AzureLocation location = AzureLocation.WestUS2; ResourceGroupCollection rgCollection = subscription.GetResourceGroups(); ResourceGroupData rgData = new ResourceGroupData(location); _ = await rgCollection.CreateOrUpdateAsync(true, rgName, rgData); } #endif ResourceGroup resourceGroup = await subscription.GetResourceGroups().GetAsync(rgName); resourceGroup = await resourceGroup.AddTagAsync("key", "value"); #endregion Snippet:Managing_Resource_Groups_UpdateAResourceGroup } [Test] [Ignore("Only verifying that the sample builds")] public async Task DeleteResourceGroup() { #region Snippet:Managing_Resource_Groups_DeleteResourceGroup ArmClient armClient = new ArmClient(new DefaultAzureCredential()); Subscription subscription = await armClient.GetDefaultSubscriptionAsync(); string rgName = "myRgName"; ResourceGroup resourceGroup = await subscription.GetResourceGroups().GetAsync(rgName); await resourceGroup.DeleteAsync(true); #endregion Snippet:Managing_Resource_Groups_DeleteResourceGroup } } }
47.348837
113
0.679273
[ "MIT" ]
AntonioVT/azure-sdk-for-net
sdk/resourcemanager/Azure.ResourceManager/tests/Samples/Sample2_ManagingResourceGroups.cs
6,110
C#
using Natasha; using System; using System.Collections.Generic; using System.Text; namespace DeepClone.Template { public class CtorTempalte { private readonly HashSet<Dictionary<string, Type>> _ctors; private readonly Dictionary<Dictionary<string, Type>, Dictionary<string, string>> _parametersMapping; //private Dictionary<Dictionary<string, Type>, int> _values; private readonly string _instanceName; public CtorTempalte(Type type,string instanceName) { _instanceName = instanceName; _ctors = new HashSet<Dictionary<string, Type>>(); //_values = new Dictionary<Dictionary<string, Type>, int>(); _parametersMapping = new Dictionary<Dictionary<string, Type>, Dictionary<string, string>>(); var temp = type.GetConstructors(); //获取所有构造函数 for (int i = 0; i < temp.Length; i++) { var dict = new Dictionary<string, Type>(); _ctors.Add(dict); //匹配频次字典 //_values[dict] = 0; //初始化构造字典 _parametersMapping[dict] = new Dictionary<string, string>(); var parameters = temp[i].GetParameters(); foreach (var item in parameters) { //缓存构造信息 dict[item.Name.ToUpper()] = item.ParameterType; _parametersMapping[dict][item.Name.ToUpper()] = item.Name; } } } public string GetCtor(IEnumerable<NBuildInfo> infos) { Dictionary<string, Type> pairs = default; int preResult = 0; foreach (var item in _ctors) { int value = 0; //遍历符合条件的成员 foreach (var info in infos) { //从参数缓存中查找是否存在该类型 var name = info.MemberTypeAvailableName; if (item.ContainsKey(name)) { if (item[name] == info.MemberType) { //频次+1 value += 1; } } } if (preResult < value) { //选择最大的匹配节点 preResult = value; pairs = item; } } if (pairs != default) { //通过最高频次的匹配字典找到参数真名缓存 var cache = _parametersMapping[pairs]; //生成脚本 StringBuilder scriptBuilder = new StringBuilder(); foreach (var item in infos) { var name = item.MemberTypeAvailableName; if (cache.ContainsKey(name)) { //如果名字和类型都匹配上了 if (pairs[name] == item.MemberType) { scriptBuilder.Append($"{cache[name]}:{_instanceName}.{item.MemberName},"); pairs.Remove(name); } } } //没匹配上的都传default foreach (var item in pairs) { scriptBuilder.Append($"{cache[item.Key]}:default,"); } if (scriptBuilder.Length>0) { scriptBuilder.Length -= 1; } return scriptBuilder.ToString(); } return default; } } }
25.134228
109
0.431242
[ "MIT" ]
night-moon-studio/DeepClone
src/DeepClone/Template/Class/CtorTempalte.cs
3,955
C#
using System; using System.Collections.Generic; using System.Threading.Tasks; namespace Xamarin.Android.Prepare { abstract partial class Scenario : AppObject { public string Name { get; } public string Description { get; } public string LogFilePath { get; protected set; } public List<Step> Steps { get; } = new List<Step> (); protected Scenario (string name, string description, Context context) { if (String.IsNullOrEmpty (name)) throw new ArgumentException ("must not be null or empty", nameof (name)); if (String.IsNullOrEmpty (description)) throw new ArgumentException ("must not be null or empty", nameof (description)); Name = name; Description = description; } public async Task Run (Context context, Log log = null) { Log = log; foreach (Step step in Steps) { context.Banner (step.Description ?? step.GetType ().FullName); bool success; Exception stepEx = null; try { success = await step.Run (context); } catch (Exception ex) { stepEx = ex; success = false; } if (success) continue; string message = $"Step {step.FailedStep ?? step} failed"; if (stepEx != null) throw new InvalidOperationException ($"{message}: {stepEx.Message}", stepEx); else throw new InvalidOperationException (message); } } public void Init (Context context) { AddStartSteps (context); AddSteps (context); AddEndSteps (context); } protected virtual void AddStartSteps (Context context) { // These are steps that have to be executed by all the scenarios Steps.Add (new Step_DownloadNuGet ()); } protected virtual void AddEndSteps (Context context) {} protected virtual void AddSteps (Context context) {} protected void AddSimpleStep (string description, Func<Context, bool> runner) { Steps.Add (new SimpleActionStep (description, runner)); } } }
25.546667
87
0.676931
[ "MIT" ]
06051979/xamarin-android
build-tools/xaprepare/xaprepare/Application/Scenario.cs
1,916
C#
using UnityEngine; class CameraRoll : MonoBehaviour { public Transform Target; //获取旋转目标 public int Speed; void Update() { transform.RotateAround(Target.position, Vector3.up, Speed * Time.deltaTime); //摄像机围绕目标旋转 } }
18.923077
96
0.674797
[ "Apache-2.0" ]
euphrat1ca/Asteroid
Assets/Script/CameraRoll.cs
278
C#
namespace System { public struct Int32 { public override string ToString() { return Internal.NumberFormatUtils.Int32ToString(this); } } }
17
66
0.57754
[ "MIT" ]
MishaTY/DotNetParser
mscorlib/MainTypes/Int32.cs
189
C#
using System.Resources; using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Veracity.Authentication.OpenIDConnect.AspNet")] [assembly: AssemblyDescription("Veracity authentication library for applications based on ASP.NET Framework")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("DNV GL Veracity")] [assembly: AssemblyProduct("Veracity.Authentication.OpenIDConnect.AspNet")] [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("4484e54b-bdf4-4cdc-b2d8-5dc4b925ed29")] // 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.1.0.0")] [assembly: AssemblyFileVersion("1.1.0.0")] [assembly: NeutralResourcesLanguage("en")]
40.384615
110
0.760635
[ "MIT" ]
AndyMason75/Veracity.Authentication.OpenIDConnect.AspNet
Veracity.Authentication.OpenIDConnect.AspNet/Properties/AssemblyInfo.cs
1,578
C#
/* * The MIT License (MIT) * * Copyright (c) 2013 Alistair Leslie-Hughes * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; namespace Microsoft.DirectX.DirectInput { [Flags] public enum CooperativeLevelFlags { NoWindowsKey = 16, Background = 8, Foreground = 4, NonExclusive = 2, Exclusive = 1 } }
35.657895
83
0.751292
[ "MIT" ]
alesliehughes/monoDX
Microsoft.DirectX.DirectInput/Microsoft.DirectX.DirectInput/CooperativeLevelFlags.cs
1,355
C#
/* * CharacterCreator.ConsoleHost * ITSE 1430 * Semester 2021 * Orlando Valdez */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CharacterCreator { /// <summary>Represents a character.</summary> public class Character { /// <summary>Gets or Sets Character Name.</summary> public string Name { get { return (_name != null) ? _name : ""; } set { _name = value; } } private string _name = " "; /// <summary>Gets or Sets Character Name.</summary> public string Profession { get { return (_profession != null) ? _profession : ""; } set { _profession = value; } } private string _profession = ""; /// <summary>Gets or Sets Character Name.</summary> public string Race { get { return (_race != null) ? _race : ""; } set { _race = value; } } private string _race = ""; /// <summary>Gets or Sets Optional Character Details.</summary> public string Biography { get { return (_biography != null) ? _biography : ""; } set { _biography = value; } } private string _biography = ""; /// <summary>Gets or Sets Strength Attribute.</summary> public int Strength { get; set; } = 0; /// <summary>Gets or Sets Intelligence Attribute.</summary> public int Intelligence { get; set; } = 0; /// <summary>Gets or Sets Agility Attribute.</summary> public int Agility { get; set; } = 0; /// <summary>Gets or Sets Constitution Attribute.</summary> public int Constitution { get; set; } = 0; /// <summary>Gets or Sets Strength Attribute.</summary> public int Charisma { get; set; } = 0; } }
23.947368
74
0.469011
[ "MIT" ]
orlandovaldez/itse1430
labs/Lab2/CharacterCreator/Character.cs
2,277
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using ConnectorGrasshopper.Properties; using GH_IO.Serialization; using Grasshopper.Kernel; using Grasshopper.Kernel.Data; using Grasshopper.Kernel.Types; using Rhino; using Speckle.Core.Api; using Speckle.Core.Credentials; using Speckle.Core.Kits; using Speckle.Core.Models; using Speckle.Core.Transports; using Logging = Speckle.Core.Logging; namespace ConnectorGrasshopper.Ops { public class SendComponentSync : GH_TaskCapableComponent<List<StreamWrapper>> { CancellationTokenSource source; const int delay = 100000; public ISpeckleConverter Converter; public ISpeckleKit Kit; public List<StreamWrapper> OutputWrappers { get; private set; } = new List<StreamWrapper>(); public bool UseDefaultCache { get; set; } = true; private GH_Structure<IGH_Goo> dataInput; private List<object> converted; public override GH_Exposure Exposure => GH_Exposure.secondary | GH_Exposure.obscure; /// <summary> /// Initializes a new instance of the SendComponentSync class. /// </summary> public SendComponentSync() : base("Synchronous Sender", "SS", "Send data to a Speckle server Synchronously. This will block GH untill all the data are received which can be used to safely trigger other processes downstream", ComponentCategories.SECONDARY_RIBBON, ComponentCategories.SEND_RECEIVE) { } /// <summary> /// Registers all the input parameters for this component. /// </summary> protected override void RegisterInputParams(GH_Component.GH_InputParamManager pManager) { pManager.AddGenericParameter("Data", "D", "The data to send.", GH_ParamAccess.tree); pManager.AddGenericParameter("Stream", "S", "Stream(s) and/or transports to send to.", GH_ParamAccess.item); pManager.AddTextParameter("Message", "M", "Commit message. If left blank, one will be generated for you.", GH_ParamAccess.item, ""); Params.Input[2].Optional = true; } protected override void RegisterOutputParams(GH_Component.GH_OutputParamManager pManager) { pManager.AddGenericParameter("Stream", "S", "Stream or streams pointing to the created commit", GH_ParamAccess.list); } public void SetConverterFromKit(string kitName) { if (Kit == null) return; if (kitName == Kit.Name) { return; } Kit = KitManager.Kits.FirstOrDefault(k => k.Name == kitName); Converter = Kit.LoadConverter(Extras.Utilities.GetVersionedAppName()); Converter.SetConverterSettings(SpeckleGHSettings.MeshSettings); SpeckleGHSettings.OnMeshSettingsChanged += (sender, args) => Converter.SetConverterSettings(SpeckleGHSettings.MeshSettings); Message = $"Using the {Kit.Name} Converter"; ExpireSolution(true); } protected override void AppendAdditionalComponentMenuItems(ToolStripDropDown menu) { Menu_AppendSeparator(menu); var menuItem = Menu_AppendItem(menu, "Select the converter you want to use:", null, false); menuItem.Enabled = false; var kits = KitManager.GetKitsWithConvertersForApp(Extras.Utilities.GetVersionedAppName()); foreach (var kit in kits) { Menu_AppendItem(menu, $"{kit.Name} ({kit.Description})", (s, e) => { SetConverterFromKit(kit.Name); }, true, kit.Name == Kit.Name); } Menu_AppendSeparator(menu); if (OutputWrappers != null) if (OutputWrappers.Count != 0) { Menu_AppendSeparator(menu); foreach (var ow in OutputWrappers) { Menu_AppendItem(menu, $"View commit {ow.CommitId} @ {ow.ServerUrl} online ↗", (s, e) => System.Diagnostics.Process.Start($"{ow.ServerUrl}/streams/{ow.StreamId}/commits/{ow.CommitId}")); } } Menu_AppendSeparator(menu); base.AppendAdditionalComponentMenuItems(menu); } public override bool Write(GH_IWriter writer) { writer.SetBoolean("UseDefaultCache", UseDefaultCache); writer.SetString("KitName", Kit.Name); var owSer = string.Join("\n", OutputWrappers.Select(ow => $"{ow.ServerUrl}\t{ow.StreamId}\t{ow.CommitId}")); writer.SetString("OutputWrappers", owSer); return base.Write(writer); } public override bool Read(GH_IReader reader) { UseDefaultCache = reader.GetBoolean("UseDefaultCache"); var wrappersRaw = reader.GetString("OutputWrappers"); var wrapperLines = wrappersRaw.Split('\n'); if (wrapperLines != null && wrapperLines.Length != 0 && wrappersRaw != "") { foreach (var line in wrapperLines) { var pieces = line.Split('\t'); OutputWrappers.Add(new StreamWrapper { ServerUrl = pieces[0], StreamId = pieces[1], CommitId = pieces[2] }); } } var kitName = ""; reader.TryGetString("KitName", ref kitName); if (kitName != "") { try { SetConverterFromKit(kitName); } catch (Exception) { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, $"Could not find the {kitName} kit on this machine. Do you have it installed? \n Will fallback to the default one."); SetDefaultKitAndConverter(); } } else { SetDefaultKitAndConverter(); } return base.Read(reader); } public override void AddedToDocument(GH_Document document) { SetDefaultKitAndConverter(); base.AddedToDocument(document); } private bool foundKit; private void SetDefaultKitAndConverter() { try { Kit = KitManager.GetDefaultKit(); Converter = Kit.LoadConverter(Extras.Utilities.GetVersionedAppName()); Converter.SetConverterSettings(SpeckleGHSettings.MeshSettings); SpeckleGHSettings.OnMeshSettingsChanged += (sender, args) => Converter.SetConverterSettings(SpeckleGHSettings.MeshSettings); Converter.SetContextDocument(Rhino.RhinoDoc.ActiveDoc); foundKit = true; } catch { AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "No default kit found on this machine."); foundKit = false; } } //GH_Structure<IGH_Goo> transportsInput; /// <summary> /// Registers all the output parameters for this component. /// </summary> /// <summary> /// This is the method that actually does the work. /// </summary> /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param> protected override void SolveInstance(IGH_DataAccess DA) { DA.DisableGapLogic(); if (!foundKit) { AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "No kit found on this machine."); return; } if (RunCount == 1) { CreateCancelationToken(); OutputWrappers = new List<StreamWrapper>(); DA.GetDataTree(0, out dataInput); //the active document may have changed Converter.SetContextDocument(RhinoDoc.ActiveDoc); // Note: this method actually converts the objects to speckle too converted = Extras.Utilities.DataTreeToNestedLists(dataInput, Converter, source.Token, () => { //ReportProgress("Conversion", Math.Round(convertedCount++ / (double)DataInput.DataCount, 2)); }); } //if (RunCount > 1) // return; if (InPreSolve) { string messageInput = ""; IGH_Goo transportInput = null; DA.GetData(1, ref transportInput); DA.GetData(2, ref messageInput); var transportsInput = new List<IGH_Goo> { transportInput }; //var transportsInput = Params.Input[1].VolatileData.AllData(true).Select(x => x).ToList(); var task = Task.Run(async () => { if (converted.Count == 0) { AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Zero objects converted successfully. Send stopped."); return null; } var ObjectToSend = new Base(); ObjectToSend["@data"] = converted; var TotalObjectCount = ObjectToSend.GetTotalChildrenCount(); if (source.Token.IsCancellationRequested) { Message = "Out of time"; return null; } // Part 2: create transports var Transports = new List<ITransport>(); if (transportsInput.Count() == 0) { // TODO: Set default account + "default" user stream } var transportBranches = new Dictionary<ITransport, string>(); int t = 0; foreach (var data in transportsInput) { var transport = data.GetType().GetProperty("Value").GetValue(data); if (transport is string s) { try { transport = new StreamWrapper(s); } catch (Exception e) { // TODO: Check this with team. AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, e.Message); } } if (transport is StreamWrapper sw) { if (sw.Type == StreamWrapperType.Undefined) { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Input stream is invalid."); continue; } if (sw.Type == StreamWrapperType.Commit) { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Cannot push to a specific commit stream url."); continue; } if (sw.Type == StreamWrapperType.Object) { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Cannot push to a specific object stream url."); continue; } Account acc; try { acc = sw.GetAccount().Result; } catch (Exception e) { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, e.InnerException?.Message ?? e.Message); continue; } Logging.Analytics.TrackEvent(acc, Logging.Analytics.Events.Send, new Dictionary<string, object>() { { "sync", true } }); var serverTransport = new ServerTransport(acc, sw.StreamId) { TransportName = $"T{t}" }; transportBranches.Add(serverTransport, sw.BranchName ?? "main"); Transports.Add(serverTransport); } else if (transport is ITransport otherTransport) { otherTransport.TransportName = $"T{t}"; Transports.Add(otherTransport); } t++; } if (Transports.Count == 0) { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Could not identify any valid transports to send to."); return null; } // Part 3: actually send stuff! if (source.Token.IsCancellationRequested) { Message = "Out of time"; return null; } // Part 3.1: persist the objects var BaseId = await Operations.Send( ObjectToSend, source.Token, Transports, useDefaultCache: UseDefaultCache, onProgressAction: y => { }, onErrorAction: (x, z) => { }, disposeTransports: true); var message = messageInput;//.get_FirstItem(true).Value; if (message == "") { message = $"Pushed {TotalObjectCount} elements from Grasshopper."; } var prevCommits = new List<StreamWrapper>(); foreach (var transport in Transports) { if (source.Token.IsCancellationRequested) { Message = "Out of time"; return null; } if (!(transport is ServerTransport)) { continue; // skip non-server transports (for now) } try { var client = new Client(((ServerTransport)transport).Account); var branch = transportBranches.ContainsKey(transport) ? transportBranches[transport] : "main"; var commitCreateInput = new CommitCreateInput { branchName = branch, message = message, objectId = BaseId, streamId = ((ServerTransport)transport).StreamId, sourceApplication = Extras.Utilities.GetVersionedAppName() }; // Check to see if we have a previous commit; if so set it. var prevCommit = prevCommits.FirstOrDefault(c => c.ServerUrl == client.ServerUrl && c.StreamId == ((ServerTransport)transport).StreamId); if (prevCommit != null) { commitCreateInput.parents = new List<string>() { prevCommit.CommitId }; } var commitId = await client.CommitCreate(source.Token, commitCreateInput); var wrapper = new StreamWrapper($"{client.Account.serverInfo.url}/streams/{((ServerTransport)transport).StreamId}/commits/{commitId}?u={client.Account.userInfo.id}"); prevCommits.Add(wrapper); } catch (Exception e) { AddRuntimeMessage(GH_RuntimeMessageLevel.Error, e.Message); return null; } } if (source.Token.IsCancellationRequested) { Message = "Out of time"; return null; } return prevCommits; }, source.Token); TaskList.Add(task); return; } if (source.IsCancellationRequested) { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Run out of time!"); } else if (!GetSolveResults(DA, out List<StreamWrapper> outputWrappers)) { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Not running multithread"); } else { OutputWrappers.AddRange(outputWrappers); DA.SetDataList(0, outputWrappers); return; } } private void CreateCancelationToken() { source = new CancellationTokenSource(delay); } /// <summary> /// Provides an Icon for the component. /// </summary> protected override System.Drawing.Bitmap Icon => Resources.SynchronousSender; /// <summary> /// Gets the unique ID for this component. Do not change this ID after release. /// </summary> public override Guid ComponentGuid { get { return new Guid("049e78bf-a400-4551-ac45-21a28843a222"); } } } }
32.881319
180
0.598824
[ "Apache-2.0" ]
connorivy/speckle-sharp
ConnectorGrasshopper/ConnectorGrasshopper/Ops/Operations.SendComponentSync.cs
14,965
C#
//----------------------------------------------------------------------- // <copyright file="BuildConfigurationViewModel.cs" company="Wohs Inc."> // Copyright © Wohs Inc. // </copyright> //----------------------------------------------------------------------- namespace Lurker.UI.ViewModels { using System; using System.Collections.ObjectModel; using System.Diagnostics; using System.Linq; using Caliburn.Micro; using Lurker.Models; using Lurker.Services; /// <summary> /// Class BuildConfigurationViewModel. /// Implements the <see cref="Caliburn.Micro.PropertyChangedBase" />. /// </summary> /// <seealso cref="Caliburn.Micro.PropertyChangedBase" /> public class BuildConfigurationViewModel : Caliburn.Micro.PropertyChangedBase { #region Fields private static readonly PathOfBuildingService PathOfBuildingService = new PathOfBuildingService(); private Build _build; private SimpleBuild _buildConfiguration; private string _ascendency; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="BuildConfigurationViewModel" /> class. /// </summary> /// <param name="build">The build.</param> public BuildConfigurationViewModel(SimpleBuild build) { this._buildConfiguration = build; this.Items = new ObservableCollection<UniqueItemViewModel>(); if (PathOfBuildingService.IsInitialize) { this.DecodeBuild(build); } else { var service = IoC.Get<GithubService>(); PathOfBuildingService.InitializeAsync(service).ContinueWith((t) => { this.DecodeBuild(build); }); } } #endregion #region Properties /// <summary> /// Gets the simple build. /// </summary> public SimpleBuild SimpleBuild => this._buildConfiguration; /// <summary> /// Gets the ascendancy. /// </summary> public string Ascendancy { get { return this._ascendency; } private set { this._ascendency = value; this.NotifyOfPropertyChange(); } } /// <summary> /// Gets or sets the gem view model. /// </summary> /// <value>The gem view model.</value> public GemViewModel GemViewModel { get; set; } /// <summary> /// Gets the items. /// </summary> public ObservableCollection<UniqueItemViewModel> Items { get; private set; } /// <summary> /// Gets the name. /// </summary> /// <value>The name.</value> public string DisplayName => this._build == null ? string.Empty : $"{this._build.Class} ({this._build.Ascendancy})"; /// <summary> /// Gets or sets the name. /// </summary> public string BuildName { get { return this._buildConfiguration.Name; } set { this._buildConfiguration.Name = value; this.NotifyOfPropertyChange(); this.NotifyOfPropertyChange("HasBuildName"); this.NotifyOfPropertyChange("HasNoBuildName"); } } /// <summary> /// Gets a value indicating whether this instance has build name. /// </summary> public bool HasBuildName => !string.IsNullOrEmpty(this.BuildName); /// <summary> /// Gets a value indicating whether this instance has youtube. /// </summary> public bool HasYoutube => !string.IsNullOrEmpty(this.Youtube); /// <summary> /// Gets a value indicating whether this instance has forum. /// </summary> public bool HasForum => !string.IsNullOrEmpty(this.Forum); /// <summary> /// Gets a value indicating whether this instance has no build name. /// </summary> public bool HasNoBuildName => !this.HasBuildName; /// <summary> /// Gets or sets the youtube. /// </summary> public string Youtube { get { return this._buildConfiguration.YoutubeUrl; } set { this._buildConfiguration.YoutubeUrl = value; this.NotifyOfPropertyChange(); this.NotifyOfPropertyChange("HasYoutube"); } } /// <summary> /// Gets or sets the forum post. /// </summary> public string Forum { get { return this._buildConfiguration.ForumUrl; } set { this._buildConfiguration.ForumUrl = value; this.NotifyOfPropertyChange(); this.NotifyOfPropertyChange("HasForum"); } } /// <summary> /// Gets the identifier. /// </summary> public string Id => this._buildConfiguration.Id; /// <summary> /// Gets or sets the notes. /// </summary> public string Notes { get { return this._buildConfiguration.Notes; } set { this._buildConfiguration.Notes = value; this.NotifyOfPropertyChange(); } } #endregion #region Methods /// <summary> /// Opens the tree. /// </summary> public void OpenTree() { if (this._build != null && !string.IsNullOrEmpty(this._build.SkillTreeUrl)) { Process.Start(this._build.SkillTreeUrl); } } /// <summary> /// Opens the youtube. /// </summary> public void OpenYoutube() { OpenUrl(this.Youtube); } /// <summary> /// Opens the forum. /// </summary> public void OpenForum() { OpenUrl(this.Forum); } /// <summary> /// Opens the URL. /// </summary> /// <param name="value">The value.</param> private static void OpenUrl(string value) { if (Uri.TryCreate(value, UriKind.Absolute, out Uri _)) { Process.Start(value); } } /// <summary> /// Decodes the build. /// </summary> /// <param name="simpleBuild">The simple build.</param> private void DecodeBuild(SimpleBuild simpleBuild) { this._build = PathOfBuildingService.Decode(simpleBuild.PathOfBuildingCode); this.Ascendancy = this._build.Ascendancy; this.NotifyOfPropertyChange("DisplayName"); var mainSkill = this._build.Skills.OrderByDescending(s => s.Gems.Count(g => g.Support)).FirstOrDefault(); if (mainSkill != null) { var gem = mainSkill.Gems.FirstOrDefault(g => !g.Support); if (gem != null) { this.GemViewModel = new GemViewModel(gem, false); this.NotifyOfPropertyChange("GemViewModel"); } } Caliburn.Micro.Execute.OnUIThread(() => { foreach (var item in this._build.Items.OrderBy(i => i.Level)) { this.Items.Add(new UniqueItemViewModel(item, false)); } }); } #endregion } }
28.948339
124
0.500319
[ "MIT" ]
C1rdec/Poe-Lurker
src/Lurker.UI/ViewModels/BuildConfigurationViewModel.cs
7,848
C#
using System.Collections.Generic; namespace TorebaCrawlerCore { public interface IDataAccess { List<Replay> GetReplayByReplayID(int replayID); void InsertMachine(Machine machine); void InsertReplay(Replay replay); } }
23.181818
55
0.705882
[ "MIT" ]
a-drianchan/TorebaCrawler
TorebaCrawler/IDataAccess.cs
257
C#
#region Copyright Notice // Copyright (c) by Achilles Software, All rights reserved. // // Licensed under the MIT License. See License.txt in the project root for license information. // // Send questions regarding this copyright notice to: mailto:todd.thomson@achilles-software.com #endregion namespace Achilles.Entities.Linq { /// <summary> /// Marker interface /// </summary> internal interface IEntityCollection { } }
22.5
95
0.715556
[ "Apache-2.0" ]
Achilles-Software/Entities.Sqlite
Achilles.Entities.Sqlite/Linq/IEntityCollection.cs
452
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.RecoveryServices.V20201001.Outputs { /// <summary> /// Validation for inquired protectable items under a given container. /// </summary> [OutputType] public sealed class InquiryValidationResponse { /// <summary> /// Error Additional Detail in case the status is non-success. /// </summary> public readonly string AdditionalDetail; /// <summary> /// Error Detail in case the status is non-success. /// </summary> public readonly Outputs.ErrorDetailResponse? ErrorDetail; /// <summary> /// Status for the Inquiry Validation. /// </summary> public readonly string? Status; [OutputConstructor] private InquiryValidationResponse( string additionalDetail, Outputs.ErrorDetailResponse? errorDetail, string? status) { AdditionalDetail = additionalDetail; ErrorDetail = errorDetail; Status = status; } } }
29.5
81
0.635225
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/RecoveryServices/V20201001/Outputs/InquiryValidationResponse.cs
1,357
C#
/* * Trade secret of Alibaba Group R&D. * Copyright (c) 2015 Alibaba Group R&D. * * All rights reserved. This notice is intended as a precaution against * inadvertent publication and does not imply publication or any waiver * of confidentiality. The year included in the foregoing notice is the * year of creation of the work. * */ using Aliyun.OTS.DataModel; namespace Aliyun.OTS.Response { /// <summary> /// 表示UpdateRow的返回 /// </summary> public class UpdateRowResponse : OTSResponse { /// <summary> /// ReturnType指定返回的值 /// </summary> public Row Row { get; set; } /// <summary> /// 本次操作消耗的读写能力单元。 /// </summary> public CapacityUnit ConsumedCapacityUnit { get; private set; } public UpdateRowResponse() {} public UpdateRowResponse(CapacityUnit consumedCapacityUnit, IRow row) { ConsumedCapacityUnit = consumedCapacityUnit; Row = row as Row; } } }
25.195122
77
0.608906
[ "Apache-2.0" ]
aliyun/aliyun-tablestore-csharp-sdk
sdk/Aliyun/OTS/Response/UpdateRowResponse.cs
1,085
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ // Generated from: proto/spheregeom.proto namespace Indriya.Core.Msgs { [global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"SphereGeom")] public partial class SphereGeom : global::ProtoBuf.IExtensible { public SphereGeom() {} private double _radius; [global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"radius", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)] public double radius { get { return _radius; } set { _radius = value; } } private global::ProtoBuf.IExtension extensionObject; global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing) { return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); } } }
38.033333
129
0.614373
[ "MIT" ]
praveenv4k/Indriya
src/indriya_msgs/csharp/spheregeom.cs
1,141
C#
namespace CsCss.Tests.Properties.Color { public class StaticsTests { } }
12.285714
39
0.662791
[ "MIT" ]
iantonge/CsCss
CsCss.Tests/Properties/Color/StaticsTests.cs
88
C#
// // Copyright (c) Microsoft Corporation. All rights reserved. // /*******************************************************************/ /* WARNING */ /* This file should be identical in the Bartok and Singularity */ /* depots. Master copy resides in Bartok Depot. Changes should be */ /* made to Bartok Depot and propagated to Singularity Depot. */ /*******************************************************************/ #if !SINGULARITY || (SINGULARITY_KERNEL && SINGULARITY_MP) #define USE_SPINLOCK #elif SINGULARITY_PROCESS #define USE_MUTEX #endif namespace System.GCs { using System.Runtime.CompilerServices; using System.Threading; #if SINGULARITY using Microsoft.Singularity; #endif internal unsafe class PageManager { // WARNING: don't initialize any static fields in this class // without manually running the class constructor at startup! // Makes old-generation collections take 5+ seconds: private static bool SlowDebug { get { return false; } } // Known to slow down selfhost if true: private static bool AggressiveMemReset { get { return false; } } internal static UIntPtr os_commit_size; private static UIntPtr heap_commit_size; private static UnusedBlockHeader [] unusedMemoryBlocks; private static bool avoidDirtyPages; private static OutOfMemoryException outOfMemoryException; #if USE_MUTEX private static Mutex mutex; #elif USE_SPINLOCK private static SpinLock Lock; #endif // Unused pages (clean and dirty combined) in the system are combined // into multi-page regions. Parts of the this struct are stored in the // first and last pages of each region. Since a region may be a single // page, it is necessary for the various first-page and last-page fields // to be stored at different offsets, which is why they are all declared // in this struct. The headers form a list of regions of approximately // the same size (see SlotFromCount). The head of each list is a dummy // node in the 'unusedMemoryBlocks' array. The last page of region // simply points back to the beginning of the region. internal struct UnusedBlockHeader { private const int magicNumber = 0x1234567; // Simply a sanity check against random overwrites of the region. private UIntPtr magic; // Built-in threading for the list of similarly sized regions. internal UnusedBlockHeader * next; private UnusedBlockHeader * prev; // Number of pages in this unused page region. internal UIntPtr count; // The 'curr' field is in the last block of the unused region. // However, the first and last blocks may be the same, so we // put the field in the same struct so that the layout can be // done automatically for us. The last block does not have the // normal header fields. internal UnusedBlockHeader * curr; internal static unsafe void Initialize(UnusedBlockHeader *header, UIntPtr count) { header->magic = (UIntPtr) magicNumber; header->next = null; header->prev = null; header->count = count; UnusedBlockHeader *tailBlock = (UnusedBlockHeader *) (((UIntPtr) header) + PageTable.RegionSize(count - 1)); tailBlock->curr = header; } [System.Diagnostics.Conditional("DEBUG")] internal static unsafe void Verify(UnusedBlockHeader *header) { VTable.Assert(header->magic == (UIntPtr) magicNumber, "Bad magic number in UnusedBlockHeader"); VTable.Assert(header->count > 0, "Count <= 0 in UnusedBlockHeader"); VTable.Assert(header->prev->next == header, "UnusedBlockHeader not linked properly (1)"); if (header->next != null) { VTable.Assert(header->next->prev == header, "UnusedBlockHeader not linked properly (2)"); } UIntPtr count = header->count; UnusedBlockHeader *tailBlock = (UnusedBlockHeader *) (((UIntPtr) header) + PageTable.RegionSize(count - 1)); VTable.Assert(tailBlock->curr == header, "UnusedBlockHeader tail->curr is incorrect"); if (PageManager.SlowDebug) { UIntPtr page = PageTable.Page((UIntPtr)header); for (UIntPtr i = UIntPtr.Zero; i < count; i++) { VTable.Assert(PageTable.IsUnusedPage(page+i) && PageTable.IsMyPage(page+i), "Incorrect page in unused region"); } } } internal static unsafe void InsertNext(UnusedBlockHeader *header, UnusedBlockHeader *newNext) { //Trace.Log(Trace.Area.Page, // "UnusedBlockHeader.InsertNext {0} count={1}", // __arglist(newNext, newNext->count)); UnusedBlockHeader *oldNext = header->next; header->next = newNext; newNext->next = oldNext; newNext->prev = header; if (oldNext != null) { oldNext->prev = newNext; } UnusedBlockHeader.Verify(newNext); } internal static unsafe UIntPtr Remove(UnusedBlockHeader *header) { //Trace.Log(Trace.Area.Page, // "UnusedBlockHeader.Remove {0} count={1}", // __arglist(this.prev->next, this.count)); UnusedBlockHeader.Verify(header); header->prev->next = header->next; if (header->next != null) { header->next->prev = header->prev; } UIntPtr result = header->count; header->magic = UIntPtr.Zero; header->prev = null; header->next = null; header->count = UIntPtr.Zero; UnusedBlockHeader *tailBlock = (UnusedBlockHeader *) (((UIntPtr) header) + PageTable.RegionSize(result - 1)); tailBlock->curr = null; return result; } } [NoBarriers] [PreInitRefCounts] internal static void Initialize(UIntPtr os_commit_size, UIntPtr heap_commit_size) { PageManager.os_commit_size = os_commit_size; PageManager.heap_commit_size = heap_commit_size; // unusedMemoryBlocks = new UnusedBlockHeader [32] unusedMemoryBlocks = (UnusedBlockHeader[]) BootstrapMemory.Allocate(typeof(UnusedBlockHeader[]), 32); // outOfMemoryException = new OutOfMemoryException(); outOfMemoryException = (OutOfMemoryException) BootstrapMemory.Allocate(typeof(OutOfMemoryException)); #if SINGULARITY_KERNEL #if USE_SPINLOCK Lock = new SpinLock(SpinLock.Types.PageManager); #endif avoidDirtyPages = true; #else avoidDirtyPages = false; #endif } internal static void FinishInitializeThread() { #if USE_MUTEX mutex = new Mutex(); GC.SuppressFinalize(mutex); #endif } private static bool EnterMutex(Thread currentThread) { bool iflag = false; if (currentThread != null #if !SINGULARITY || SEMISPACE_COLLECTOR || SLIDING_COLLECTOR || ADAPTIVE_COPYING_COLLECTOR || MARK_SWEEP_COLLECTOR && StopTheWorldGCData.CurrentPhase != StopTheWorldPhase.SingleThreaded #endif ) { #if SINGULARITY_KERNEL iflag = Processor.DisableInterrupts(); #endif // SINGULARITY_KERNEL #if USE_MUTEX if (mutex != null) { mutex.AcquireMutex(); } #elif USE_SPINLOCK PageManager.Lock.Acquire(currentThread); #endif } return iflag; } private static void LeaveMutex(Thread currentThread, bool iflag) { if (currentThread != null #if !SINGULARITY || SEMISPACE_COLLECTOR || SLIDING_COLLECTOR || ADAPTIVE_COPYING_COLLECTOR || MARK_SWEEP_COLLECTOR && StopTheWorldGCData.CurrentPhase != StopTheWorldPhase.SingleThreaded #endif ) { #if USE_MUTEX if (mutex != null) { mutex.ReleaseMutex(); } #elif USE_SPINLOCK PageManager.Lock.Release(currentThread); #endif #if SINGULARITY_KERNEL // Must happen after spinlock is released Processor.RestoreInterrupts(iflag); #endif // SINGULARITY_KERNEL } } [ManualRefCounts] private static void Clear(UIntPtr startAddr, UIntPtr regionSize) { VTable.Assert(PageTable.PageAligned(startAddr)); VTable.Assert(PageTable.PageAligned(regionSize)); MemoryManager.IgnoreMemoryContents(startAddr, regionSize); MarkUnusedPages(Thread.CurrentThread, PageTable.Page(startAddr), PageTable.PageCount(regionSize), false); } private static int SlotFromCount(UIntPtr count) { int slot = -1; do { slot++; count >>= 1; } while (count > UIntPtr.Zero); return slot; } internal static UIntPtr AllocateNonheapMemory(Thread currentThread, UIntPtr size) { bool iflag = EnterMutex(currentThread); try { UIntPtr result = MemoryManager.AllocateMemory(size); if (result != UIntPtr.Zero) { SetNonheapPages(result, size); } return result; } finally { LeaveMutex(currentThread, iflag); } } internal static void FreeNonheapMemory(UIntPtr startAddress, UIntPtr size) { SetUnallocatedPages(startAddress, size); MemoryManager.FreeMemory(startAddress, size); } private static void SetPageTypeClean(UIntPtr startPage, UIntPtr pageCount, PageType newType) { UIntPtr* tableAddr = (UIntPtr *) PageTable.PageAddr(startPage); UIntPtr* tableCursor = tableAddr + 1; UIntPtr dirtyCount = UIntPtr.Zero; UIntPtr endPage = startPage + pageCount; for (UIntPtr i = startPage; i < endPage; i++) { PageType pageType = PageTable.Type(i); if (pageType == PageType.UnusedDirty) { PageTable.SetType(i, newType); UIntPtr j = i+1; while (j < endPage && PageTable.Type(j)==PageType.UnusedDirty) { PageTable.SetType(j, newType); j++; } UIntPtr dirtyStartAddr = PageTable.PageAddr(i); UIntPtr dirtyEndAddr = PageTable.PageAddr(j); *tableCursor++ = dirtyStartAddr; *tableCursor++ = dirtyEndAddr - dirtyStartAddr; dirtyCount++; i = j-1; } else { PageTable.SetType(i, newType); } } *tableAddr = dirtyCount; PageTable.SetProcess(startPage, pageCount); } [ManualRefCounts] internal static UIntPtr EnsurePages(Thread currentThread, UIntPtr pageCount, PageType newType, ref bool fCleanPages) { if (currentThread != null) { GC.CheckForNeededGCWork(currentThread); } VTable.Deny(PageTable.IsUnusedPageType(newType)); // Try to find already allocated but unused pages UIntPtr foundPages = FindUnusedPages(currentThread, pageCount, newType); if (foundPages != UIntPtr.Zero) { if (fCleanPages) { CleanFoundPages(foundPages); } else { fCleanPages = FoundOnlyCleanPages(foundPages); } return foundPages; } // We need to allocate new pages bool iflag = EnterMutex(currentThread); try { UIntPtr bytesNeeded = PageTable.RegionSize(pageCount); UIntPtr allocSize = Util.Pad(bytesNeeded, heap_commit_size); UIntPtr startAddr = MemoryManager.AllocateMemory(allocSize); if (startAddr == UIntPtr.Zero) { if (heap_commit_size > os_commit_size) { allocSize = Util.Pad(bytesNeeded, os_commit_size); startAddr = MemoryManager.AllocateMemory(allocSize); } } if (startAddr == UIntPtr.Zero) { // BUGBUG: if in CMS, should wait on one complete GC cycle and // the retry. for STW, we may get here even if the collector // hasn't triggered just prior. PageTable.Dump("Out of memory"); throw outOfMemoryException; } UIntPtr startPage = PageTable.Page(startAddr); PageTable.SetType(startPage, pageCount, newType); PageTable.SetProcess(startPage, pageCount); UIntPtr extraPages = PageTable.PageCount(allocSize) - pageCount; if (extraPages > 0) { // Mark the new memory pages as allocated-but-unused MarkUnusedPages(/* avoid recursive locking */ null, startPage+pageCount, extraPages, true); } return startPage; } finally { LeaveMutex(currentThread, iflag); } } internal static void ReleaseUnusedPages(UIntPtr startPage, UIntPtr pageCount, bool fCleanPages) { if(VTable.enableDebugPrint) { VTable.DebugPrint("ClearPages({0}, {1})\n", __arglist(startPage, pageCount)); } UIntPtr startAddr = PageTable.PageAddr(startPage); UIntPtr endPage = startPage + pageCount; UIntPtr endAddr = PageTable.PageAddr(endPage); UIntPtr rangeSize = PageTable.RegionSize(pageCount); MarkUnusedPages(Thread.CurrentThread, PageTable.Page(startAddr), PageTable.PageCount(rangeSize), fCleanPages); if (PageManager.AggressiveMemReset) { // We cannot simply reset the memory range, as MEM_RESET can // only be used within a region returned from a single // VirtualAlloc call. UIntPtr regionAddr, regionSize; bool fUsed = MemoryManager.QueryMemory(startAddr, out regionAddr, out regionSize); if(VTable.enableDebugPrint) { VTable.DebugPrint(" 1 Query({0}, {1}, {2}) -> {3}\n", __arglist(startAddr, regionAddr, regionSize, fUsed)); } VTable.Assert(fUsed, "Memory to be cleared isn't used"); // We don't care if regionAddr < startAddr. We can MEM_RESET // part of the region. UIntPtr endRegion = regionAddr + regionSize; while (endRegion < endAddr) { if (VTable.enableDebugPrint) { VTable.DebugPrint("Clearing region [{0}, {1}]\n", __arglist(regionAddr, regionAddr+regionSize)); } MemoryManager.IgnoreMemoryContents(startAddr, endRegion - startAddr); startAddr = endRegion; fUsed = MemoryManager.QueryMemory(endRegion, out regionAddr, out regionSize); if(VTable.enableDebugPrint) { VTable.DebugPrint(" 2 Query({0}, {1}, {2}) -> {3}\n", __arglist(endRegion, regionAddr, regionSize, fUsed)); } VTable.Assert(fUsed, "Region to be freed isn't used"); endRegion = regionAddr + regionSize; } if (VTable.enableDebugPrint) { VTable.DebugPrint("Clearing final region [{0}, {1}]\n", __arglist(startAddr, endAddr)); } MemoryManager.IgnoreMemoryContents(startAddr, endAddr - startAddr); } if(VTable.enableDebugPrint) { VTable.DebugPrint(" --> ClearPages({0},{1})\n", __arglist(startPage, pageCount)); } } // Use this method to free heap pages. // There must be no contention regarding ownership of the pages. internal static void FreePageRange(UIntPtr startPage, UIntPtr endPage) { if(VTable.enableDebugPrint) { VTable.DebugPrint("FreePageRange({0}, {1})\n", __arglist(startPage, endPage)); } UIntPtr startAddr = PageTable.PageAddr(startPage); UIntPtr endAddr = PageTable.PageAddr(endPage); UIntPtr rangeSize = endAddr - startAddr; #if SINGULARITY // Singularity doesn't care if you free pages in different // chunks than you acquired them in MemoryManager.FreeMemory(startAddr, rangeSize); #else // We cannot simply release the memory range, as MEM_RELEASE // requires the pointer to be the same as the original call // to VirtualAlloc, and the length to be zero. UIntPtr regionAddr, regionSize; bool fUsed = MemoryManager.QueryMemory(startAddr, out regionAddr, out regionSize); if(VTable.enableDebugPrint) { VTable.DebugPrint(" 1 Query({0}, {1}, {2}) -> {3}\n", __arglist(startAddr, regionAddr, regionSize, fUsed)); } VTable.Assert(fUsed, "Memory to be freed isn't used"); UIntPtr endRegion = regionAddr + regionSize; if (regionAddr < startAddr) { // startAddr is in the middle of an allocation region -> skip if (endRegion >= endAddr) { // [startAddr, endAddr] is fully contained in a region PageManager.Clear(startAddr, endAddr - startAddr); return; } // Part of the address range falls into the next region PageManager.Clear(startAddr, endRegion - startAddr); fUsed = MemoryManager.QueryMemory(endRegion, out regionAddr, out regionSize); if(VTable.enableDebugPrint) { VTable.DebugPrint(" 2 Query({0}, {1}, {2}) -> {3}\n", __arglist(endRegion, regionAddr, regionSize, fUsed)); } VTable.Assert(fUsed, "Area to be freed isn't used"); endRegion = regionAddr + regionSize; } // [regionAddr, endRegion] is contained in [startAddr, endAddr] while (endRegion < endAddr) { if (VTable.enableDebugPrint) { VTable.DebugPrint("Freeing region [{0}, {1}]\n", __arglist(regionAddr, regionAddr+regionSize)); } SetUnallocatedPages(regionAddr, regionSize); MemoryManager.FreeMemory(regionAddr, regionSize); fUsed = MemoryManager.QueryMemory(endRegion, out regionAddr, out regionSize); if(VTable.enableDebugPrint) { VTable.DebugPrint(" 3 Query({0}, {1}, {2}) -> {3}\n", __arglist(endRegion, regionAddr, regionSize, fUsed)); } VTable.Assert(fUsed, "Region to be freed isn't used"); endRegion = regionAddr + regionSize; } if (endRegion == endAddr) { if (VTable.enableDebugPrint) { VTable.DebugPrint("Freeing final region [{0}, {1}]\n", __arglist(regionAddr, regionAddr + regionSize)); } SetUnallocatedPages(regionAddr, regionSize); MemoryManager.FreeMemory(regionAddr, regionSize); } else { PageManager.Clear(regionAddr, endAddr - regionAddr); } if(VTable.enableDebugPrint) { VTable.DebugPrint(" --> FreePageRange({0},{1})\n", __arglist(startPage, endPage)); } #endif // SINGULARITY } //=============================== // Routines to mark special pages private static unsafe void SetNonheapPages(UIntPtr startAddr, UIntPtr size) { UIntPtr startPage = PageTable.Page(startAddr); UIntPtr endAddr = startAddr + size; UIntPtr endPage = PageTable.Page(endAddr); if (!PageTable.PageAligned(endAddr)) { endPage++; } UIntPtr pageCount = endPage - startPage; if (pageCount == 1) { PageTable.SetType(startPage, PageType.System); } else { PageTable.SetType(startPage, pageCount, PageType.System); } } // Tell the GC that a certain data area is no longer allowed to // contain off-limits, non-moveable data. private static unsafe void SetUnallocatedPages(UIntPtr startAddr, UIntPtr size) { UIntPtr startPage = PageTable.Page(startAddr); UIntPtr endAddr = startAddr + size; UIntPtr endPage = PageTable.Page(endAddr); UIntPtr pageCount = endPage - startPage; if (pageCount == 1) { PageTable.SetExtra(startPage, 0); PageTable.SetType(startPage, PageType.Unallocated); PageTable.SetProcess(startPage, 0); } else { PageTable.SetExtra(startPage, pageCount, 0); PageTable.SetType(startPage, pageCount, PageType.Unallocated); PageTable.SetProcess(startPage, pageCount, 0); } } #if !SINGULARITY // Needed before Bartok runtime is initialized [NoStackLinkCheck] #endif internal static unsafe void SetStaticDataPages(UIntPtr startAddr, UIntPtr size) { #if SINGULARITY // It's perfectly fine to be given memory outside the page table region, so // long as we intend to treat that memory as NonGC anyway. if (startAddr < PageTable.baseAddr) { if (startAddr + size < PageTable.baseAddr) { // nothing to do. All pages are below the base covered by the page table return; } // The range overlaps with the region covered by the page table size -= (PageTable.baseAddr - startAddr); startAddr = PageTable.baseAddr; } UIntPtr endAddr = startAddr + size; if (endAddr > PageTable.limitAddr) { if (startAddr > PageTable.limitAddr) { // nothing to do. All pages are above the limit covered by the page table return; } // The range overlaps with the region covered by the page table size -= (PageTable.limitAddr - endAddr); } #endif UIntPtr startIndex = PageTable.Page(startAddr); UIntPtr pageCount = PageTable.PageCount(size); PageTable.SetType(startIndex, pageCount, PageType.NonGC); } #if !SINGULARITY // Bartok uses the extra field in the PageTable to easily // map from a stack address to the thread that owns that stack. // This is used to implement GetCurrentThread. // Singularity uses a different mechanism that does not involve // the extra data at all. private static unsafe void SetStackPages(UIntPtr startAddr, UIntPtr endAddr, Thread thread) { UIntPtr startPage = PageTable.Page(startAddr); UIntPtr endPage = PageTable.Page(endAddr); UIntPtr pageCount = endPage - startPage; PageTable.VerifyType(startPage, pageCount, PageType.Unallocated); PageTable.VerifyExtra(startPage, pageCount, 0); PageTable.SetType(startPage, pageCount, PageType.Stack); PageTable.SetExtra(startPage, pageCount, (uint) thread.threadIndex); } internal static unsafe void MarkThreadStack(Thread thread) { int stackVariable; UIntPtr stackBase = PageTable.PagePad(new UIntPtr(&stackVariable)); CallStack.SetStackBase(thread, stackBase); UIntPtr topPageAddr = PageTable.PageAlign(CallStack.StackBase(thread) - 1); SetStackPages(topPageAddr, CallStack.StackBase(thread), thread); UIntPtr regionAddr, regionSize; bool fUsed = MemoryManager.QueryMemory(topPageAddr, out regionAddr, out regionSize); VTable.Assert(fUsed); SetStackPages(regionAddr, topPageAddr, thread); } internal static unsafe void ClearThreadStack(Thread thread) { short threadIndex = (short) thread.threadIndex; UIntPtr endPage = PageTable.Page(CallStack.StackBase(thread)); UIntPtr startPage = endPage - 1; VTable.Assert(PageTable.IsStackPage(PageTable.Type(startPage))); VTable.Assert(PageTable.Extra(startPage) == threadIndex); while (startPage > 0 && PageTable.IsStackPage(PageTable.Type(startPage-1)) && PageTable.Extra(startPage-1) == threadIndex) { startPage--; } UIntPtr startAddr = PageTable.PageAddr(startPage); UIntPtr size = PageTable.RegionSize(endPage - startPage); SetUnallocatedPages(startAddr, size); } #endif //==================================== // Routines to manipulate unused pages [ManualRefCounts] private static void LinkUnusedPages(UIntPtr startPage, UIntPtr pageCount, bool asVictim) { if (PageManager.SlowDebug) { for (UIntPtr i = startPage; i < startPage + pageCount; i++) { VTable.Assert(PageTable.IsUnusedPage(i) && PageTable.IsMyPage(i), "Incorrect page to link into unused region"); } } Trace.Log(Trace.Area.Page, "LinkUnusedPages start={0:x} count={1:x}", __arglist(startPage, pageCount)); VTable.Deny(startPage > UIntPtr.Zero && PageTable.IsUnusedPage(startPage-1) && PageTable.IsMyPage(startPage-1)); VTable.Deny(startPage + pageCount > PageTable.pageTableCount); VTable.Deny(startPage + pageCount < PageTable.pageTableCount && PageTable.IsUnusedPage(startPage + pageCount) && PageTable.IsMyPage(startPage + pageCount)); UnusedBlockHeader *header = (UnusedBlockHeader *) PageTable.PageAddr(startPage); UnusedBlockHeader.Initialize(header, pageCount); int slot = SlotFromCount(pageCount); // Unused blocks are linked into the free list either as the result of a collection // or as a result of carving a big block into a smaller allocation and a remainder. // When such a remainder is linked back into the free list, it is identified as a // victim. We favor subsequent allocations from these victims, in an attempt to // reduce fragmentation. This is achieved by keeping victims at the head of the // free list. // // TODO: the long term solution is to perform best fit on the free list. if (asVictim || unusedMemoryBlocks[slot].next == null) { fixed (UnusedBlockHeader *listHeader = &unusedMemoryBlocks[slot]) { UnusedBlockHeader.InsertNext(listHeader, header); } } else { UnusedBlockHeader *listHeader = unusedMemoryBlocks[slot].next; UnusedBlockHeader.InsertNext(listHeader, header); } } private static UIntPtr UnlinkUnusedPages(UIntPtr startPage) { VTable.Assert(PageTable.IsUnusedPage(startPage) && PageTable.IsMyPage(startPage)); VTable.Deny(startPage > UIntPtr.Zero && PageTable.IsUnusedPage(startPage-1) && PageTable.IsMyPage(startPage-1)); UnusedBlockHeader *header = (UnusedBlockHeader *) PageTable.PageAddr(startPage); UIntPtr pageCount = UnusedBlockHeader.Remove(header); Trace.Log(Trace.Area.Page, "UnlinkUnusedPages start={0:x} count={1:x}", __arglist(startPage, pageCount)); return pageCount; } // The indicated pages will be marked with 'pageStatus' in the // page table. The region of unused memory will also be linked // into the table of blocks of unused memory [ManualRefCounts] private static void MarkUnusedPages(Thread currentThread, UIntPtr startPage, UIntPtr pageCount, bool fCleanPages) { Trace.Log(Trace.Area.Page, "MarkUnusedPages start={0:x} count={1:x}", __arglist(startPage, pageCount)); UIntPtr endPage = startPage + pageCount; if (avoidDirtyPages && !fCleanPages) { UIntPtr dirtyStartAddr = PageTable.PageAddr(startPage); UIntPtr dirtySize = PageTable.RegionSize(pageCount); Util.MemClear(dirtyStartAddr, dirtySize); fCleanPages = true; } bool iflag = EnterMutex(currentThread); try { if (endPage < PageTable.pageTableCount) { if (PageTable.IsUnusedPage(endPage) && PageTable.IsMyPage(endPage)) { UIntPtr regionSize = UnlinkUnusedPages(endPage); endPage += regionSize; } } UIntPtr queryStartPage = startPage - 1; UIntPtr newStartPage = startPage; if (PageTable.IsUnusedPage(queryStartPage) && PageTable.IsMyPage(queryStartPage)) { UnusedBlockHeader * tailUnused = (UnusedBlockHeader *) PageTable.PageAddr(queryStartPage); UIntPtr newStartAddr = (UIntPtr) tailUnused->curr; newStartPage = PageTable.Page(newStartAddr); UIntPtr regionSize = UnlinkUnusedPages(newStartPage); VTable.Assert(newStartPage + regionSize == startPage); } PageType pageType = fCleanPages ? PageType.UnusedClean : PageType.UnusedDirty; PageTable.SetType(startPage, pageCount, pageType); LinkUnusedPages(newStartPage, endPage - newStartPage, false); } finally { LeaveMutex(currentThread, iflag); } } internal static bool TryReserveUnusedPages(Thread currentThread, UIntPtr startPage, UIntPtr pageCount, PageType newType, ref bool fCleanPages) { Trace.Log(Trace.Area.Page, "TryReserveUnusedPages start={0:x} count={1:x}", __arglist(startPage, pageCount)); VTable.Deny(PageTable.IsUnusedPageType(newType)); VTable.Assert(pageCount > UIntPtr.Zero); VTable.Deny(startPage != UIntPtr.Zero && PageTable.IsUnusedPage(startPage-1) && PageTable.IsMyPage(startPage-1)); UIntPtr endPage = startPage + pageCount; if (endPage > PageTable.pageTableCount) { return false; } if (currentThread != null) { GC.CheckForNeededGCWork(currentThread); } bool iflag = EnterMutex(currentThread); try { // GC can occur and page can be collected. if (startPage != UIntPtr.Zero && PageTable.IsUnusedPage(startPage-1)) { return false; } if (!PageTable.IsUnusedPage(startPage) || !PageTable.IsMyPage(startPage)) { return false; } UnusedBlockHeader * header = (UnusedBlockHeader *) PageTable.PageAddr(startPage); if (header->count < pageCount) { return false; } UIntPtr regionPages = UnlinkUnusedPages(startPage); Trace.Log(Trace.Area.Page, "TryReserveUnusedPages found={0:x}", __arglist(regionPages)); SetPageTypeClean(startPage, pageCount, newType); if (regionPages > pageCount) { UIntPtr suffixPages = regionPages - pageCount; LinkUnusedPages(endPage, suffixPages, true); } } finally { LeaveMutex(currentThread, iflag); } // Now that we are outside the Mutex, we should perform the // real cleaning of the gotten pages if (fCleanPages) { CleanFoundPages(startPage); } else { fCleanPages = FoundOnlyCleanPages(startPage); } return true; } internal static bool TryReservePages(Thread currentThread, UIntPtr startPage, UIntPtr pageCount, PageType newType, ref bool fCleanPages) { Trace.Log(Trace.Area.Page, "TryReservePages start={0:x} count={1:x}", __arglist(startPage, pageCount)); VTable.Deny(PageTable.IsUnusedPageType(newType)); VTable.Assert(pageCount > UIntPtr.Zero); VTable.Deny(startPage != UIntPtr.Zero && PageTable.IsUnusedPage(startPage-1) && PageTable.IsMyPage(startPage-1)); UIntPtr endPage = startPage + pageCount; UIntPtr index = startPage; while (index < endPage && PageTable.IsUnusedPage(index) && PageTable.IsMyPage(index)) { index++; } if (PageTable.IsUnallocatedPage(PageTable.Type(index))) { // We should try to extend the region of allocated pages UIntPtr pagesNeeded = pageCount - (index - startPage); UIntPtr bytesNeeded = PageTable.RegionSize(pagesNeeded); UIntPtr allocSize = Util.Pad(bytesNeeded, heap_commit_size); UIntPtr startAddr = PageTable.PageAddr(index); bool gotMemory = false; bool iflag = EnterMutex(currentThread); try { gotMemory = MemoryManager.AllocateMemory(startAddr, allocSize); if (gotMemory) { UIntPtr allocPages = PageTable.PageCount(allocSize); MarkUnusedPages(/* avoid recursive locking */ null, index, allocPages, true); } } finally { LeaveMutex(currentThread, iflag); } if (gotMemory) { bool success = TryReserveUnusedPages(currentThread, startPage, pageCount, newType, ref fCleanPages); Trace.Log(Trace.Area.Page, "TryReservePages success={0}", __arglist(success)); return success; } } return false; } // Try to find a region of unused memory of a given size. If the // request can be satisfied, the return value is the first page // in the found region. If the request cannot be satisfied, the // return value is UIntPtr.Zero. [ManualRefCounts] private static UIntPtr FindUnusedPages(Thread currentThread, UIntPtr pageCount, PageType newType) { VTable.Deny(PageTable.IsUnusedPageType(newType)); int slot = SlotFromCount(pageCount); Trace.Log(Trace.Area.Page, "FindUnusedPages count={0:x} slot={1}", __arglist(pageCount, slot)); bool iflag = EnterMutex(currentThread); try { while (slot < 32) { UnusedBlockHeader *header = unusedMemoryBlocks[slot].next; while (header != null) { if (header->count >= pageCount) { UIntPtr startPage = PageTable.Page((UIntPtr) header); UIntPtr regionSize = UnlinkUnusedPages(startPage); SetPageTypeClean(startPage, pageCount, newType); if (regionSize > pageCount) { UIntPtr restCount = regionSize - pageCount; UIntPtr endPage = startPage + pageCount; LinkUnusedPages(endPage, restCount, true); } Trace.Log(Trace.Area.Page, "FindUnusedPages success {0:x}", __arglist(startPage)); return startPage; } header = header->next; } slot++; } return UIntPtr.Zero; } finally { LeaveMutex(currentThread, iflag); } } [ManualRefCounts] private static void CleanFoundPages(UIntPtr startPage) { UIntPtr *tableAddr = (UIntPtr *) PageTable.PageAddr(startPage); uint count = (uint) *tableAddr; UIntPtr* cursor = tableAddr + (count + count); while (count != 0) { UIntPtr dirtySize = *cursor; *cursor-- = UIntPtr.Zero; UIntPtr dirtyStartAddr = *cursor; *cursor-- = UIntPtr.Zero; Util.MemClear(dirtyStartAddr, dirtySize); count--; } *tableAddr = UIntPtr.Zero; } [ManualRefCounts] private static bool FoundOnlyCleanPages(UIntPtr startPage) { UIntPtr *tableAddr = (UIntPtr *) PageTable.PageAddr(startPage); uint count = (uint) *tableAddr; UIntPtr* cursor = tableAddr + (count + count); bool result = true; while (count != 0) { result = false; *cursor-- = UIntPtr.Zero; *cursor-- = UIntPtr.Zero; count--; } *tableAddr = UIntPtr.Zero; return result; } [ManualRefCounts] internal static UIntPtr TotalUnusedPages() { Thread currentThread = Thread.CurrentThread; UIntPtr pageCount = (UIntPtr) 0; bool iflag = EnterMutex(currentThread); try { for (int slot = 0; slot < 32; slot++) { UnusedBlockHeader *header = unusedMemoryBlocks[slot].next; while (header != null) { pageCount += header->count; header = header->next; } } return pageCount; } finally { LeaveMutex(currentThread, iflag); } } [System.Diagnostics.Conditional("DEBUG")] internal static void VerifyUnusedPage(UIntPtr page, bool containsHeader) { if (PageTable.Type(page) == PageType.UnusedDirty) { return; } // Verify that the page is indeed clean UIntPtr *startAddr = (UIntPtr *) PageTable.PageAddr(page); UIntPtr *endAddr = (UIntPtr *) PageTable.PageAddr(page + 1); // If the page contains a header then we can't expect the header // to be clean. if (containsHeader) { startAddr += (uint) (Util.UIntPtrPad((UIntPtr)sizeof(UnusedBlockHeader)) / (uint)sizeof(UIntPtr)); } while (startAddr < endAddr) { VTable.Assert(*startAddr == UIntPtr.Zero, "UnusedClean page contains nonzero data"); startAddr++; } } [System.Diagnostics.Conditional("DEBUG")] internal static void VerifyUnusedRegion(UIntPtr startPage, UIntPtr endPage) { // Verify that all of the pages are of the same Clean/Dirty type. PageType startType = PageTable.Type(startPage); for(UIntPtr page = startPage; page < endPage; ++page) { VTable.Assert(startType == PageTable.Type(page), "Unused page types don't match in region"); } if (startPage > UIntPtr.Zero && PageTable.IsUnusedPage(startPage-1) && PageTable.IsMyPage(startPage-1)) { // We have already checked the region return; } UIntPtr regionAddr = PageTable.PageAddr(startPage); UnusedBlockHeader * regionHeader = (UnusedBlockHeader *) regionAddr; UIntPtr pageCount = regionHeader->count; VTable.Assert (pageCount >= (endPage - startPage), "Region-to-verify is larger than its header specifies"); endPage = startPage + pageCount; for(UIntPtr page = startPage; page < endPage; ++page) { VTable.Assert(PageTable.IsUnusedPage(page) && PageTable.IsMyPage(page), "Non my-unused page in unused region"); PageManager.VerifyUnusedPage (page, (page == startPage) || (page == (endPage - 1))); } VTable.Assert(!(endPage < PageTable.pageTableCount && PageTable.IsUnusedPage(endPage) && PageTable.IsMyPage(endPage)), "My-unused page immediately after unused region"); // Verify that the region is correctly linked into the // list of unused memory blocks int slot = SlotFromCount(pageCount); UnusedBlockHeader *header = unusedMemoryBlocks[slot].next; UnusedBlockHeader.Verify(header); while (regionAddr != (UIntPtr) header) { header = header->next; VTable.Assert(header != null, "Unused region not list for its slot number"); UnusedBlockHeader.Verify(header); } } } }
44.238668
114
0.50023
[ "MIT" ]
pmache/singularityrdk
SOURCE/base/Imported/Bartok/runtime/shared/GCs/PageManager.cs
47,822
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 globalaccelerator-2018-08-08.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.GlobalAccelerator.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.GlobalAccelerator.Model.Internal.MarshallTransformations { /// <summary> /// DescribeListener Request Marshaller /// </summary> public class DescribeListenerRequestMarshaller : IMarshaller<IRequest, DescribeListenerRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((DescribeListenerRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(DescribeListenerRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.GlobalAccelerator"); string target = "GlobalAccelerator_V20180706.DescribeListener"; request.Headers["X-Amz-Target"] = target; request.Headers["Content-Type"] = "application/x-amz-json-1.1"; request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2018-08-08"; request.HttpMethod = "POST"; request.ResourcePath = "/"; request.MarshallerVersion = 2; using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { JsonWriter writer = new JsonWriter(stringWriter); writer.WriteObjectStart(); var context = new JsonMarshallerContext(request, writer); if(publicRequest.IsSetListenerArn()) { context.Writer.WritePropertyName("ListenerArn"); context.Writer.Write(publicRequest.ListenerArn); } writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } return request; } private static DescribeListenerRequestMarshaller _instance = new DescribeListenerRequestMarshaller(); internal static DescribeListenerRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static DescribeListenerRequestMarshaller Instance { get { return _instance; } } } }
36.657143
148
0.618342
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/GlobalAccelerator/Generated/Model/Internal/MarshallTransformations/DescribeListenerRequestMarshaller.cs
3,849
C#
using UnityEngine; using System; using System.Text; using System.IO; using System.IO.Ports; using System.Threading; namespace Bno055 { public class SerialReceiver : MonoBehaviour, IDataReceiver { public event DataReceivedEventHandler OnDataReceived; public bool IsRunning { get { return isRunning; } } public string portName = "COM6"; public int baudRate = 115200; public byte[] Delimiter = new byte[] { 10 }; private SerialPort serialPort; private Thread thread; private bool isRunning = false; private byte[] buffer = new byte[512]; private byte[] tmp = new byte[512]; private int byteCounter; void Awake() { Open(); } void OnDestroy() { Close(); } private bool Open() { #if UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX var portExists = File.Exists(portName); if (!portExists) { Debug.LogWarning(string.Format("Port {0} does not exist.", portName)); return false; } #endif bool openSuccess = false; serialPort = new SerialPort(portName, baudRate, Parity.None, 8, StopBits.One); for (int i = 0; i < 5; i++) { try { Debug.Log("Opening serial port..."); #if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN serialPort.ReadTimeout = 1; #else serialPort.ReadTimeout = 1000; #endif serialPort.WriteTimeout = 1000; serialPort.Open(); openSuccess = true; break; } catch (IOException ex) { Debug.LogWarning("error:" + ex.ToString()); } Thread.Sleep(1000); } if (!openSuccess) { return false; } Debug.Log("Opened"); isRunning = true; byteCounter = 0; thread = new Thread(Read); thread.Start(); return true; } private void Close() { isRunning = false; if (thread != null && thread.IsAlive) { thread.Join(); } if (serialPort != null && serialPort.IsOpen) { serialPort.Close(); serialPort.Dispose(); } } private void Read() { while (isRunning && serialPort != null && serialPort.IsOpen) { try { #if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN try { while (true) { var b = (byte)serialPort.ReadByte(); buffer[byteCounter++] = b; } } catch (System.TimeoutException e) { // ignore } #else if (serialPort.BytesToRead > 0) { //message_ = serialPort_.ReadTo(Encoding.ASCII.GetString()); int n = serialPort.Read(tmp, 0, serialPort.BytesToRead); Array.Copy(tmp, 0, buffer, byteCounter, byteCounter + n); byteCounter += n; #endif while (true) { var index = Utils.FindArray(buffer, byteCounter, Delimiter); if (index >= 0) { var data = new byte[index]; Array.Copy(buffer, data, index); // splice buffer and decrement byte counter. Array.Copy(buffer, index + Delimiter.Length, buffer, 0, byteCounter - index - Delimiter.Length); byteCounter -= (index + Delimiter.Length); var stringData = System.Text.Encoding.ASCII.GetString(data); if (OnDataReceived != null) { OnDataReceived(stringData); } } else { break; } } #if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN #else } #endif } catch (Exception e) { Debug.LogWarning(e.Message + ":" + e.StackTrace); } } } public void Write(string message) { try { serialPort.Write(message); } catch (System.Exception e) { Debug.LogWarning(e.Message); } } } }
28.544444
124
0.415726
[ "MIT" ]
curiosity-inc/bno055-unity
Assets/Scripts/SerialReceiver.cs
5,138
C#
namespace MassTransit.Containers.Tests.Common_Tests { using System; using System.Linq; using System.Threading.Tasks; using ConsumeContextTestSubjects; using Context; using NUnit.Framework; using TestFramework; using TestFramework.Messages; public abstract class Common_ConsumeContext : InMemoryTestFixture { protected abstract IBusRegistrationContext Registration { get; } protected abstract Task<ConsumeContext> ConsumeContext { get; } protected abstract Task<IPublishEndpoint> PublishEndpoint { get; } protected abstract Task<ISendEndpointProvider> SendEndpointProvider { get; } [Test] public async Task Should_provide_the_consume_context() { await InputQueueSendEndpoint.Send(new PingMessage()); var consumeContext = await ConsumeContext; Assert.That(consumeContext.TryGetPayload(out MessageConsumeContext<PingMessage> messageConsumeContext), "Is MessageConsumeContext"); var publishEndpoint = await PublishEndpoint; var sendEndpointProvider = await SendEndpointProvider; Assert.That(publishEndpoint, Is.TypeOf<MessageConsumeContext<PingMessage>>()); Assert.That(sendEndpointProvider, Is.TypeOf<MessageConsumeContext<PingMessage>>()); Assert.That(ReferenceEquals(publishEndpoint, sendEndpointProvider), "ReferenceEquals(publishEndpoint, sendEndpointProvider)"); Assert.That(ReferenceEquals(messageConsumeContext, sendEndpointProvider), "ReferenceEquals(messageConsumeContext, sendEndpointProvider)"); } protected void ConfigureRegistration(IBusRegistrationConfigurator configurator) { configurator.AddConsumer<DependentConsumer>(); configurator.AddBus(provider => BusControl); } protected override void ConfigureInMemoryReceiveEndpoint(IInMemoryReceiveEndpointConfigurator configurator) { configurator.ConfigureConsumers(Registration); } } public abstract class Common_ConsumeContext_Outbox : InMemoryTestFixture { protected Common_ConsumeContext_Outbox() { TestTimeout = TimeSpan.FromSeconds(3); } protected abstract IBusRegistrationContext Registration { get; } protected abstract Task<ConsumeContext> ConsumeContext { get; } protected abstract Task<IPublishEndpoint> PublishEndpoint { get; } protected abstract Task<ISendEndpointProvider> SendEndpointProvider { get; } [Test] public async Task Should_provide_the_outbox() { Task<ConsumeContext<Fault<PingMessage>>> fault = ConnectPublishHandler<Fault<PingMessage>>(); await InputQueueSendEndpoint.Send(new PingMessage()); var consumeContext = await ConsumeContext; Assert.That( consumeContext.TryGetPayload(out InMemoryOutboxConsumeContext<PingMessage> outboxConsumeContext), "Is ConsumerConsumeContext"); var publishEndpoint = await PublishEndpoint; var sendEndpointProvider = await SendEndpointProvider; Assert.That(publishEndpoint, Is.TypeOf<InMemoryOutboxConsumeContext<PingMessage>>()); Assert.That(sendEndpointProvider, Is.TypeOf<InMemoryOutboxConsumeContext<PingMessage>>()); Assert.That(ReferenceEquals(publishEndpoint, sendEndpointProvider), "ReferenceEquals(publishEndpoint, sendEndpointProvider)"); Assert.That(ReferenceEquals(outboxConsumeContext, sendEndpointProvider), "ReferenceEquals(outboxConsumeContext, sendEndpointProvider)"); await fault; Assert.That(InMemoryTestHarness.Published.Select<ServiceDidIt>().Any(), Is.False, "Outbox Did Not Intercept!"); } protected void ConfigureRegistration(IBusRegistrationConfigurator configurator) { configurator.AddConsumer<DependentConsumer>(); configurator.AddBus(provider => BusControl); } protected override void ConfigureInMemoryReceiveEndpoint(IInMemoryReceiveEndpointConfigurator configurator) { configurator.UseInMemoryOutbox(); configurator.ConfigureConsumers(Registration); } } public abstract class Common_ConsumeContext_Outbox_Solo : InMemoryTestFixture { protected Common_ConsumeContext_Outbox_Solo() { TestTimeout = TimeSpan.FromSeconds(3); } protected abstract IBusRegistrationContext Registration { get; } protected abstract Task<ConsumeContext> ConsumeContext { get; } protected abstract Task<IPublishEndpoint> PublishEndpoint { get; } protected abstract Task<ISendEndpointProvider> SendEndpointProvider { get; } [Test] public async Task Should_provide_the_outbox_to_the_consumer() { Task<ConsumeContext<Fault<PingMessage>>> fault = ConnectPublishHandler<Fault<PingMessage>>(); await InputQueueSendEndpoint.Send(new PingMessage()); var consumeContext = await ConsumeContext; Assert.That( consumeContext.TryGetPayload(out InMemoryOutboxConsumeContext<PingMessage> outboxConsumeContext), "Is ConsumerConsumeContext"); var publishEndpoint = await PublishEndpoint; var sendEndpointProvider = await SendEndpointProvider; Assert.That(publishEndpoint, Is.TypeOf<InMemoryOutboxConsumeContext<PingMessage>>()); Assert.That(sendEndpointProvider, Is.TypeOf<InMemoryOutboxConsumeContext<PingMessage>>()); Assert.That(ReferenceEquals(publishEndpoint, sendEndpointProvider), "ReferenceEquals(publishEndpoint, sendEndpointProvider)"); Assert.That(ReferenceEquals(outboxConsumeContext, sendEndpointProvider), "ReferenceEquals(outboxConsumeContext, sendEndpointProvider)"); await fault; Assert.That(InMemoryTestHarness.Published.Select<ServiceDidIt>().Any(), Is.False, "Outbox Did Not Intercept!"); } protected void ConfigureRegistration(IBusRegistrationConfigurator configurator) { configurator.AddConsumer<FlyingSoloConsumer>(); configurator.AddBus(provider => BusControl); } protected override void ConfigureInMemoryReceiveEndpoint(IInMemoryReceiveEndpointConfigurator configurator) { configurator.UseInMemoryOutbox(); configurator.ConfigureConsumers(Registration); } } namespace ConsumeContextTestSubjects { using TestFramework.Messages; class DependentConsumer : IConsumer<PingMessage> { readonly IService _service; readonly IAnotherService _anotherService; public DependentConsumer(IService service, IAnotherService anotherService) { _service = service; _anotherService = anotherService; } public async Task Consume(ConsumeContext<PingMessage> context) { await _service.DoIt(); _anotherService.Done(); throw new IntentionalTestException(); } } class FlyingSoloConsumer : IConsumer<PingMessage> { readonly TaskCompletionSource<ConsumeContext> _consumeContextTask; readonly IPublishEndpoint _publishEndpoint; public FlyingSoloConsumer(IPublishEndpoint publishEndpoint, ISendEndpointProvider sendEndpointProvider, TaskCompletionSource<ConsumeContext> consumeContextTask, TaskCompletionSource<IPublishEndpoint> publishEndpointTask, TaskCompletionSource<ISendEndpointProvider> sendEndpointProviderTask) { _publishEndpoint = publishEndpoint; _consumeContextTask = consumeContextTask; publishEndpointTask.TrySetResult(publishEndpoint); sendEndpointProviderTask.TrySetResult(sendEndpointProvider); } public async Task Consume(ConsumeContext<PingMessage> context) { _consumeContextTask.TrySetResult(context); await _publishEndpoint.Publish<ServiceDidIt>(new { }); throw new IntentionalTestException(); } } public interface ServiceDidIt { } interface IService { Task DoIt(); } class Service : IService { readonly IPublishEndpoint _publishEndpoint; public Service(IPublishEndpoint publishEndpoint, ISendEndpointProvider sendEndpointProvider, TaskCompletionSource<IPublishEndpoint> publishEndpointTask, TaskCompletionSource<ISendEndpointProvider> sendEndpointProviderTask) { _publishEndpoint = publishEndpoint; publishEndpointTask.TrySetResult(publishEndpoint); sendEndpointProviderTask.TrySetResult(sendEndpointProvider); } public async Task DoIt() { await _publishEndpoint.Publish<ServiceDidIt>(new { }); } } interface IAnotherService { void Done(); } class AnotherService : IAnotherService { readonly ConsumeContext _context; readonly TaskCompletionSource<ConsumeContext> _consumeContextTask; public AnotherService(ConsumeContext context, TaskCompletionSource<ConsumeContext> consumeContextTask) { _context = context; _consumeContextTask = consumeContextTask; } public void Done() { _consumeContextTask.TrySetResult(_context); } } } }
36.620438
150
0.664242
[ "ECL-2.0", "Apache-2.0" ]
LukePammant/MassTransit
tests/MassTransit.Containers.Tests/Common_Tests/Common_ConsumeContext.cs
10,034
C#
using Microsoft.Extensions.Options; using Silky.Core.DependencyInjection; using Silky.Core.Runtime.Rpc; using Silky.Rpc.Configuration; namespace Silky.Rpc.Security { public class CurrentRpcToken : ICurrentRpcToken, IScopedDependency { private string _token; public CurrentRpcToken(IOptionsMonitor<RpcOptions> rpcOptions) { _token = rpcOptions.CurrentValue.Token; rpcOptions.OnChange(options => { _token = rpcOptions.CurrentValue.Token; }); } public string Token { get; } = RpcContext.Context.GetInvokeAttachment(AttachmentKeys.RpcToken)?.ToString(); public void SetRpcToken() { RpcContext.Context.SetInvokeAttachment(AttachmentKeys.RpcToken, _token); } } }
30.88
115
0.693005
[ "MIT" ]
Dishone/silky
framework/src/Silky.Rpc/Security/CurrentRpcToken.cs
772
C#
// 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. namespace Fixtures.MirrorRecursiveTypes.Models { using Fixtures.MirrorRecursiveTypes; using Newtonsoft.Json; using System.Linq; public partial class Error { /// <summary> /// Initializes a new instance of the Error class. /// </summary> public Error() { } /// <summary> /// Initializes a new instance of the Error class. /// </summary> public Error(int? code = default(int?), string message = default(string), string fields = default(string)) { Code = code; Message = message; Fields = fields; } /// <summary> /// </summary> [JsonProperty(PropertyName = "code")] public int? Code { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "message")] public string Message { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "fields")] public string Fields { get; set; } } }
27.26
114
0.584006
[ "MIT" ]
brywang-msft/autorest
src/generator/AutoRest.CSharp.Tests/Expected/Mirror.RecursiveTypes/Models/Error.cs
1,363
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _5.Exam_Shopping { class ExamShopping { public static void Main(string[] args) { Dictionary<string, int> shopStock = new Dictionary<string, int>(); string[] input = Console.ReadLine().Split(' ').ToArray(); while (input[0] != "shopping" && input[1] != "time") { StockingTheShop(shopStock, input); input = Console.ReadLine().Split(' ').ToArray(); } input = Console.ReadLine().Split(' ').ToArray(); while (input[0] != "exam" && input[1] != "time") { BuyingProducts(shopStock, input); input = Console.ReadLine().Split(' ').ToArray(); } foreach (var product in shopStock) { if (product.Value > 0) { Console.WriteLine($"{product.Key} -> {product.Value}"); } } } public static void BuyingProducts(Dictionary<string, int> shopStock, string[] input) { string product = input[1]; int buyingQuantity = int.Parse(input[2]); if (shopStock.Keys.Contains(product)) { if (buyingQuantity <= shopStock[product]) { shopStock[product] -= buyingQuantity; } else { if (shopStock[product] == 0) { Console.WriteLine($"{product} out of stock"); } else { shopStock[product] = 0; } } } else { Console.WriteLine($"{product} doesn't exist"); } } public static void StockingTheShop(Dictionary<string, int> shopStock, string[] input) { string product = input[1]; int quantity = int.Parse(input[2]); if (!shopStock.Keys.Contains(product)) { shopStock[product] = quantity; } else { shopStock[product] += quantity; } } } }
27.724138
93
0.441128
[ "MIT" ]
msotiroff/Softuni-learning
Tech Module/Programming Fundamentals/Practice/Dictionaries/5. Exam Shopping/ExamShopping.cs
2,414
C#
// Problem 3. English digit // Write a method that returns the last digit of given integer as an English word. // Examples: // input output // 512 two // 1024 four // 12309 nine using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace P03_EnglishDigit { class EnglishDigit { public static void LastDigitAsWord(int n) { string[] digitsAsWords = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }; n = n % 10; Console.Write(digitsAsWords[n]); } static void Main(string[] args) { Console.Write("Plesa enter an int number: "); int numb = int.Parse(Console.ReadLine()); Console.Write("Last digit of {0} is ", numb); LastDigitAsWord(numb); Console.WriteLine("."); } } }
25.243243
120
0.577088
[ "MIT" ]
GAlex7/TA
02. CSharpPart2/03. Methods/P03-EnglishDigit/EnglishDigit.cs
936
C#
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using Fasterflect; using Testity.Common; namespace Testity.BuildProcess { public class SerializedMemberParser : ITypeMemberParser { public SerializedMemberParser() { } /// <summary> /// Creates a collection of <see cref="IEnumerable{TMemberInfoType}"/> that reference the <see cref="TTypeToParse"/> members. /// These members will also be decorated by the <see cref="ExposeDataMemeberAttribute"/>. /// </summary> /// <typeparam name="TTypeToParse">Type to be parsed</typeparam> /// <returns>A collection of <typeparamref name="MemberInfoType"/></returns> public IEnumerable<MemberInfo> Parse<TTypeToParse>(MemberTypes types) where TTypeToParse : class { return typeof(TTypeToParse).MembersWith<ExposeDataMemeberAttribute>(types, Flags.InstanceAnyVisibility); //get all members from current and base classes } /// <summary> /// Creates a collection of <see cref="IEnumerable{TMemberInfoType}"/> that reference the <see cref="TTypeToParse"/> members. /// These members will also be decorated by the <see cref="ExposeDataMemeberAttribute"/>. /// </summary> /// <returns>A collection of <typeparamref name="MemberInfoType"/></returns> public IEnumerable<MemberInfo> Parse(MemberTypes types, Type typeToParse) { return typeToParse.MembersWith<ExposeDataMemeberAttribute>(types, Flags.InstanceAnyVisibility); //get all members from current and base classes } } }
37.195122
155
0.752131
[ "MIT" ]
HelloKitty/Testity
src/Testity.BuildProcess/Parsing/Type/SerializedMemberParser.cs
1,527
C#
using System; namespace TripToWorldCup { class Program { static void Main(string[] args) { double ticketPriceForGoing = double.Parse(Console.ReadLine()); double ticketPriceForArriving = double.Parse(Console.ReadLine()); double ticketPriceForMatch = double.Parse(Console.ReadLine()); double matchesNumber = double.Parse(Console.ReadLine()); double discount = double.Parse(Console.ReadLine()) / 100; double sumForPlaneTickets = 6 * (ticketPriceForGoing + ticketPriceForArriving); double currentSum = sumForPlaneTickets * discount; double discountSum = sumForPlaneTickets - currentSum; double totalSumForMatches = 6 * matchesNumber * ticketPriceForMatch; double totalSum = discountSum + totalSumForMatches; double sumPerPerson = totalSum / 6; Console.WriteLine($"Total sum: {totalSum:F2} lv."); Console.WriteLine($"Each friend has to pay {sumPerPerson:F2} lv."); } } }
39.37037
91
0.639699
[ "MIT" ]
stanislavstoyanov99/SoftUni-Software-Engineering
Programming-Basics-with-C#/Final-Exams/ProgrammingBasicsExam28-29-July-18/TripToWorldCup/Program.cs
1,065
C#
using System; namespace TextExtract.Services { public class SuspensionState { public object Data { get; set; } public DateTime SuspensionDate { get; set; } } }
15.916667
52
0.633508
[ "MIT" ]
ThomasPe/TextExtract-UWP
TextExtract/Services/SuspensionState.cs
193
C#
using ALE.ETLBox; using ALE.ETLBox.ConnectionManager; using ALE.ETLBox.ControlFlow; using ALE.ETLBox.DataFlow; using ALE.ETLBox.Helper; using ALE.ETLBox.Logging; using ALE.ETLBoxTests.Fixtures; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Linq; using Xunit; namespace ALE.ETLBoxTests.DataFlowTests { [Collection("DataFlow")] public class BlockTransformationStringArrayTests { public SqlConnectionManager SqlConnection => Config.SqlConnection.ConnectionManager("DataFlow"); public BlockTransformationStringArrayTests(DataFlowDatabaseFixture dbFixture) { } [Fact] public void ModifyInputDataList() { //Arrange TwoColumnsTableFixture source2Columns = new TwoColumnsTableFixture("BlockTransSourceNonGeneric"); source2Columns.InsertTestData(); TwoColumnsTableFixture dest2Columns = new TwoColumnsTableFixture("BlockTransDestNonGeneric"); DbSource<string[]> source = new DbSource<string[]>("BlockTransSourceNonGeneric", SqlConnection); DbDestination<string[]> dest = new DbDestination<string[]>("BlockTransDestNonGeneric", SqlConnection); //Act BlockTransformation<string[]> block = new BlockTransformation<string[]>( inputData => { inputData.RemoveRange(1, 2); inputData.Add(new string[] { "4", "Test4" }); return inputData; }); source.LinkTo(block); block.LinkTo(dest); source.Execute(); dest.Wait(); //Assert Assert.Equal(2, RowCountTask.Count(SqlConnection, "BlockTransDestNonGeneric")); Assert.Equal(1, RowCountTask.Count(SqlConnection, "BlockTransDestNonGeneric", "Col1 = 1 AND Col2='Test1'")); Assert.Equal(1, RowCountTask.Count(SqlConnection, "BlockTransDestNonGeneric", "Col1 = 4 AND Col2='Test4'")); } } }
37
120
0.655528
[ "MIT" ]
HaSaM-cz/etlbox
TestsETLBox/src/DataFlowTests/BlockTransformationTests/BlockTransformationStringArrayTests.cs
2,035
C#
using System; using System.Collections.Generic; using System.Text; using System.Diagnostics; namespace Svt.Caspar.AMCP { internal class AMCPProtocolStrategy : Svt.Network.IProtocolStrategy { CasparDevice device_ = null; AMCPParser parser_ = new AMCPParser(); internal AMCPProtocolStrategy(CasparDevice device) { device_ = device; parser_.ResponseParsed += new EventHandler<AMCPParserEventArgs>(parser__ResponseParsed); } void parser__ResponseParsed(object sender, AMCPParserEventArgs e) { //A response is completely parsed //Info about it is in the eventArgs if (e.Error == AMCPError.None) { switch (e.Command) { case AMCPCommand.VERSION: device_.OnVersion(e.Data[0]); break; case AMCPCommand.CLS: OnCLS(e); break; case AMCPCommand.TLS: OnTLS(e); break; case AMCPCommand.INFO: OnInfo(e); break; case AMCPCommand.LOAD: device_.OnLoad((string)((e.Data.Count > 0) ? e.Data[0] : string.Empty)); break; case AMCPCommand.LOADBG: device_.OnLoadBG((string)((e.Data.Count > 0) ? e.Data[0] : string.Empty)); break; case AMCPCommand.PLAY: break; case AMCPCommand.STOP: break; case AMCPCommand.CG: break; case AMCPCommand.CINF: break; case AMCPCommand.DATA: OnData(e); break; } } else { if (e.Command == AMCPCommand.DATA) OnData(e); } } private void OnData(AMCPParserEventArgs e) { if (e.Error == AMCPError.FileNotFound) { device_.OnDataRetrieved(string.Empty); return; } if (e.Subcommand == "RETRIEVE") { if (e.Error == AMCPError.None && e.Data.Count > 0) device_.OnDataRetrieved(e.Data[0]); else device_.OnDataRetrieved(string.Empty); } else if (e.Subcommand == "LIST") { device_.OnUpdatedDataList(e.Data); } } private void OnTLS(AMCPParserEventArgs e) { List<TemplateInfo> templates = new List<TemplateInfo>(); foreach (string templateInfo in e.Data) { string pathName = templateInfo.Substring(templateInfo.IndexOf('\"')+1, templateInfo.IndexOf('\"', 1)-1); string folderName = ""; string fileName = ""; int delimIndex = pathName.LastIndexOf('\\'); if (delimIndex != -1) { folderName = pathName.Substring(0, delimIndex); fileName = pathName.Substring(delimIndex + 1); } else { fileName = pathName; } string temp = templateInfo.Substring(templateInfo.LastIndexOf('\"') + 1); string[] sizeAndDate = temp.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); Int64 size = Int64.Parse(sizeAndDate[0]); DateTime updated = DateTime.ParseExact(sizeAndDate[1], "yyyyMMddHHmmss", null); templates.Add(new TemplateInfo(folderName, fileName, size, updated)); } device_.OnUpdatedTemplatesList(templates); } private string ConvertToTimecode(double time, int fps) { int hour = (int)(time / 3600); int minutes = (int)((time - hour * 3600) / 60); int seconds = (int)(time - hour * 3600 - minutes * 60); int frames = (int)((time - hour * 3600 - minutes * 60 - seconds) * fps); return string.Format("{0:D2}:{1:D2}:{2:D2}:{3:D2}", hour, minutes, seconds, frames); } private void OnCLS(AMCPParserEventArgs e) { List<MediaInfo> clips = new List<MediaInfo>(); foreach (string mediaInfo in e.Data) { string pathName = mediaInfo.Substring(mediaInfo.IndexOf('\"') + 1, mediaInfo.IndexOf('\"', 1) - 1); string folderName = ""; string fileName = ""; int delimIndex = pathName.LastIndexOf('\\'); if (delimIndex != -1) { folderName = pathName.Substring(0, delimIndex); fileName = pathName.Substring(delimIndex + 1); } else { fileName = pathName; } string temp = mediaInfo.Substring(mediaInfo.LastIndexOf('\"') + 1); string[] param = temp.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); MediaType type = (MediaType)Enum.Parse(typeof(MediaType), param[0]); Int64 size = Int64.Parse(param[1]); DateTime updated = DateTime.ParseExact(param[2], "yyyyMMddHHmmss", null); string timecode = ""; if (param.Length > 3) { string totalFrames = param[3]; string timebase = param[4]; long frames = long.Parse(totalFrames); int fps = int.Parse(timebase.Split('/')[1]); double time = frames * (1.0 / fps); timecode = ConvertToTimecode(time, fps); } clips.Add(new MediaInfo(folderName, fileName, type, size, updated, timecode)); } device_.OnUpdatedMediafiles(clips); } void OnInfo(AMCPParserEventArgs e) { List<ChannelInfo> channelInfo = new List<ChannelInfo>(); foreach (string channelData in e.Data) { string[] data = channelData.Split(' '); int id = Int32.Parse(data[0]); // VideoMode vm = (VideoMode)Enum.Parse(typeof(VideoMode), data[1]); // ChannelStatus cs = (ChannelStatus)Enum.Parse(typeof(ChannelStatus), data[2]); channelInfo.Add(new ChannelInfo(id, VideoMode.Unknown, ChannelStatus.Stopped, "")); } device_.OnUpdatedChannelInfo(channelInfo); } #region IProtocolStrategy Members public string Delimiter { get { return AMCPParser.CommandDelimiter; } } public Encoding Encoding { get { return System.Text.Encoding.UTF8; } } public void Parse(string data, Svt.Network.RemoteHostState state) { parser_.Parse(data); } public void Parse(byte[] data, int length, Svt.Network.RemoteHostState state) { throw new NotImplementedException(); } #endregion } }
28.534314
120
0.624635
[ "MIT" ]
OssiPesonen/Eilium
framework/Svt.Caspar/AMCP/AMCPProtocolStrategy.cs
5,821
C#
using InfectedRose.Nif.Controllers; using InfectedRose.Core; using RakDotNet.IO; namespace InfectedRose.Nif { public class NiObjectNet : NiObject { public NiStringRef Name { get; set; } public NiRef<NiExtraData>[] ExtraData { get; set; } public NiRef<NiTimeController> Controller { get; set; } public override void Serialize(BitWriter writer) { writer.Write(Name); writer.Write((uint) ExtraData.Length); foreach (var extra in ExtraData) { writer.Write(extra); } writer.Write(Controller); } public override void Deserialize(BitReader reader) { Name = reader.Read<NiStringRef>(File); ExtraData = new NiRef<NiExtraData>[reader.Read<uint>()]; for (var i = 0; i < ExtraData.Length; i++) { ExtraData[i] = reader.Read<NiRef<NiExtraData>>(File); } Controller = reader.Read<NiRef<NiTimeController>>(File); } } }
25.511628
69
0.550593
[ "MIT" ]
UchuServer/InfectedRose
InfectedRose.Nif/Nodes/NiObjectNet.cs
1,097
C#
// *** WARNING: this file was generated by crd2pulumi. *** // *** 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.Kubernetes.Types.Outputs.Machinelearning.V1 { [OutputType] public sealed class SeldonDeploymentSpecPredictorsComponentSpecsSpecAffinityNodeAffinity { /// <summary> /// The scheduler will prefer to schedule pods to nodes that satisfy the affinity expressions specified by this field, but it may choose a node that violates one or more of the expressions. The node that is most preferred is the one with the greatest sum of weights, i.e. for each node that meets all of the scheduling requirements (resource request, requiredDuringScheduling affinity expressions, etc.), compute a sum by iterating through the elements of this field and adding "weight" to the sum if the node matches the corresponding matchExpressions; the node(s) with the highest sum are the most preferred. /// </summary> public readonly ImmutableArray<Pulumi.Kubernetes.Types.Outputs.Machinelearning.V1.SeldonDeploymentSpecPredictorsComponentSpecsSpecAffinityNodeAffinityPreferredDuringSchedulingIgnoredDuringExecution> PreferredDuringSchedulingIgnoredDuringExecution; /// <summary> /// If the affinity requirements specified by this field are not met at scheduling time, the pod will not be scheduled onto the node. If the affinity requirements specified by this field cease to be met at some point during pod execution (e.g. due to an update), the system may or may not try to eventually evict the pod from its node. /// </summary> public readonly Pulumi.Kubernetes.Types.Outputs.Machinelearning.V1.SeldonDeploymentSpecPredictorsComponentSpecsSpecAffinityNodeAffinityRequiredDuringSchedulingIgnoredDuringExecution RequiredDuringSchedulingIgnoredDuringExecution; [OutputConstructor] private SeldonDeploymentSpecPredictorsComponentSpecsSpecAffinityNodeAffinity( ImmutableArray<Pulumi.Kubernetes.Types.Outputs.Machinelearning.V1.SeldonDeploymentSpecPredictorsComponentSpecsSpecAffinityNodeAffinityPreferredDuringSchedulingIgnoredDuringExecution> preferredDuringSchedulingIgnoredDuringExecution, Pulumi.Kubernetes.Types.Outputs.Machinelearning.V1.SeldonDeploymentSpecPredictorsComponentSpecsSpecAffinityNodeAffinityRequiredDuringSchedulingIgnoredDuringExecution requiredDuringSchedulingIgnoredDuringExecution) { PreferredDuringSchedulingIgnoredDuringExecution = preferredDuringSchedulingIgnoredDuringExecution; RequiredDuringSchedulingIgnoredDuringExecution = requiredDuringSchedulingIgnoredDuringExecution; } } }
79.055556
618
0.809557
[ "Apache-2.0" ]
pulumi/pulumi-kubernetes-crds
operators/seldon-operator/dotnet/Kubernetes/Crds/Operators/SeldonOperator/Machinelearning/V1/Outputs/SeldonDeploymentSpecPredictorsComponentSpecsSpecAffinityNodeAffinity.cs
2,846
C#
using EPiServer.Core; using WebHookAlloy.Models.Pages; namespace WebHookAlloy.Models.ViewModels { /// <summary> /// Defines common characteristics for view models for pages, including properties used by layout files. /// </summary> /// <remarks> /// Views which should handle several page types (T) can use this interface as model type rather than the /// concrete PageViewModel class, utilizing the that this interface is covariant. /// </remarks> public interface IPageViewModel<out T> where T : SitePageData { T CurrentPage { get; } LayoutModel Layout { get; set; } IContent Section { get; set; } } }
33.45
109
0.678625
[ "MIT" ]
PaulGruffyddAmaze/kinandcarta-epi-webhooks
WebHookAlloy/Models/ViewModels/IPageViewModel.cs
669
C#
namespace ApertureLabs.Selenium.Css { /// <summary> /// Represents a css unit of measurement. /// </summary> /// <remarks> /// View https://drafts.csswg.org/css-values-4 for more details. /// </remarks> public enum CssUnit { /// <summary> /// There is no unit associated with the number. /// </summary> None, #region Absolute Lengths /// <summary> /// ('cm') /// </summary> Centimeters, /// <summary> /// ('mm') /// </summary> Millimeters, /// <summary> /// ('Q') /// </summary> QuarterMillimeters, /// <summary> /// ('in') /// </summary> Inches, /// <summary> /// ('pc') /// </summary> Picas, /// <summary> /// ('pt') /// </summary> Points, /// <summary> /// ('px') /// </summary> Pixels, #endregion #region Angles /// <summary> /// ('deg') Degrees. There are 360 degrees in a full circle. /// </summary> Degrees, /// <summary> /// ('grad') Gradians, also known as "gons" or "grades". There are 400 /// gradians in a full circle. /// </summary> Gradians, /// <summary> /// ('rad') Radians. There are 2π radians in a full circle. /// </summary> Radians, /// <summary> /// ('turn') Turns. There is 1 turn in a full circle. /// </summary> Turn, #endregion #region Durations /// <summary> /// ('s') Seconds. /// </summary> Seconds, /// <summary> /// ('ms') Milliseconds. There are 1000 milliseconds in a second. /// </summary> Milliseconds, #endregion #region Frequencies /// <summary> /// ('Hz') Hertz. It represents the number of occurrences per second. /// </summary> Hertz, /// <summary> /// ('kHz') KiloHertz. A kiloHertz is 1000 Hertz. /// </summary> KiloHertz, #endregion #region Relative Lengths /// <summary> /// ('%') Varies based on which style property it's being used with. /// </summary> Percent, /// <summary> /// ('em') Relative to the font size of the element. /// </summary> EM, /// <summary> /// ('ex') X-height of the element’s font. /// </summary> EX, /// <summary> /// ('cap') Relative to the cap height (the nominal height of capital /// letters) of the element’s font. /// </summary> CAP, /// <summary> /// ('ch') Relative to the average character advance of a narrow glyph /// in the element’s font, as represented by the “0” (ZERO, U+0030) /// glyph. /// </summary> CH, /// <summary> /// ('ic') Relative to the average character advance of a fullwidth /// glyph in the element’s font, as represented by the “水” (CJK water /// ideograph, U+6C34) glyph. /// </summary> IC, /// <summary> /// ('rem') Relative to the font size of the root element. /// </summary> REM, /// <summary> /// ('lh') Relative to the line height of the element. /// </summary> LineHeight, /// <summary> /// ('rlh') Relative to the line height of the root element. /// </summary> RootLineHeight, /// <summary> /// ('vw') Equal to 1% of the width of the initial containing block. /// </summary> ViewWidth, /// <summary> /// ('vh') Equal to 1% of the height of the initial containing block. /// </summary> ViewHeight, /// <summary> /// ('vi') Equal to 1% of the size of the initial containing block in /// the direction of the root element’s inline axis. /// </summary> ViewInline, /// <summary> /// ('vb') Equal to 1% of the size of the initial containing block in /// the direction of the root element’s block axis. /// </summary> ViewBlock, /// <summary> /// ('vmin') Equal to the smaller 'vw' or 'vh'. /// </summary> ViewMinimum, /// <summary> /// ('vmax') Equal to the larger 'vw' or 'vh'. /// </summary> ViewMaximum, #endregion #region Resolutions /// <summary> /// ('dpi') Dots per inch. /// </summary> DotsPerInch, /// <summary> /// ('dpcm') Dots per centimeter. /// </summary> DotsPerCentimeter, /// <summary> /// ('dppx' | 'x') Dots per 'px' unit. /// </summary> DotsPerPixelUnit #endregion } }
23.485981
78
0.462992
[ "Apache-2.0" ]
sai09451/ApertureLabs.Selenium
ApertureLabs.Selenium/Css/CssUnit.cs
5,051
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml; namespace Newtonsoft.Json.Tests.Documentation.Samples.Xml { public class ConvertXmlToJsonForceArray { public void Example() { #region Usage string xml = @"<person id='1'> <name>Alan</name> <url>http://www.google.com</url> <role>Admin1</role> </person>"; XmlDocument doc = new XmlDocument(); doc.LoadXml(xml); string json = JsonConvert.SerializeXmlNode(doc); Console.WriteLine(json); // { // "person": { // "@id": "1", // "name": "Alan", // "url": "http://www.google.com", // "role": "Admin1" // } // } xml = @"<person xmlns:json='http://james.newtonking.com/projects/json' id='1'> <name>Alan</name> <url>http://www.google.com</url> <role json:Array='true'>Admin</role> </person>"; doc = new XmlDocument(); doc.LoadXml(xml); json = JsonConvert.SerializeXmlNode(doc); Console.WriteLine(json); // { // "person": { // "@id": "1", // "name": "Alan", // "url": "http://www.google.com", // "role": [ // "Admin" // ] // } // } #endregion } } }
22.6
84
0.5
[ "MIT" ]
Chimpaneez/LiveSplit
LiveSplit/Libs/JSON.Net/Source/Src/Newtonsoft.Json.Tests/Documentation/Samples/Xml/ConvertXmlToJsonForceArray.cs
1,358
C#
// Copyright 2021 Google LLC // // 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 // // https://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. // Generated code. DO NOT EDIT! namespace Google.Cloud.Dialogflow.V2beta1.Snippets { using Google.Cloud.Dialogflow.V2beta1; public sealed partial class GeneratedConversationProfilesClientStandaloneSnippets { /// <summary>Snippet for DeleteConversationProfile</summary> /// <remarks> /// This snippet has been automatically generated for illustrative purposes only. /// It may require modifications to work in your environment. /// </remarks> public void DeleteConversationProfile() { // Create client ConversationProfilesClient conversationProfilesClient = ConversationProfilesClient.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/conversationProfiles/[CONVERSATION_PROFILE]"; // Make the request conversationProfilesClient.DeleteConversationProfile(name); } } }
39.410256
104
0.705921
[ "Apache-2.0" ]
googleapis/googleapis-gen
google/cloud/dialogflow/v2beta1/google-cloud-dialogflow-v2beta1-csharp/Google.Cloud.Dialogflow.V2beta1.StandaloneSnippets/ConversationProfilesClient.DeleteConversationProfileSnippet.g.cs
1,537
C#
using Microsoft.Extensions.Logging; using System; namespace HotelManagementApp.Services.Common { public class TimedLogger<T> : ILogger<T> { private readonly ILogger _logger; public TimedLogger(ILogger logger) => _logger = logger; public TimedLogger(ILoggerFactory loggerFactory) : this(new Logger<T>(loggerFactory)) { } public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter) => _logger.Log(logLevel, eventId, state, exception, (s, ex) => $"[{DateTime.UtcNow:HH:mm:ss.fff}]: {formatter(s, ex)}"); public bool IsEnabled(LogLevel logLevel) => _logger.IsEnabled(logLevel); public IDisposable BeginScope<TState>(TState state) => _logger.BeginScope(state); } }
36.285714
142
0.749344
[ "Unlicense" ]
Dasik/HotelManagementApp
HotelManagementApp/Services/Common/TimedLogger.cs
764
C#
namespace Discord { /// <summary> /// Represents a parameter recived with a Slash Command Interaction /// </summary> public class InteractionParameter { /// <summary> /// Name of the parameter /// </summary> public string Name { get; } /// <summary> /// Value of the parameter /// </summary> public object Value { get; } /// <summary> /// Type of the parameter /// </summary> public ApplicationCommandOptionType Type { get; } internal InteractionParameter (string name, object value, ApplicationCommandOptionType type) { Name = name; Value = value; Type = type; } } }
24.225806
100
0.532623
[ "MIT" ]
Cenngo/Discord.Net-Labs
src/Discord.Net.Core/Entities/SlashCommands/SocketInteractionParameter.cs
751
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace GraphLibrary { /// <summary> /// Interaction logic for PresentWindow1.xaml /// </summary> public partial class PresentWindow : UserControl { private ControlViewModel vm; public PresentWindow(GGraph G) { vm = new ControlViewModel(G); this.DataContext = vm; InitializeComponent(); } } }
24.363636
53
0.670398
[ "MIT" ]
vduseev/simple-graph-library
GraphLibrary/User control/Present/PresentWindow.xaml.cs
806
C#
#region Copyright notice and license // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // http://github.com/jskeet/dotnet-protobufs/ // Original C++/Java/Python code: // http://code.google.com/p/protobuf/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System; using System.Collections.Generic; using System.IO; using Google.ProtocolBuffers.Collections; using Google.ProtocolBuffers.Descriptors; using Google.ProtocolBuffers.DescriptorProtos; namespace Google.ProtocolBuffers { /// <summary> /// Used to keep track of fields which were seen when parsing a protocol message /// but whose field numbers or types are unrecognized. This most frequently /// occurs when new fields are added to a message type and then messages containing /// those fields are read by old software that was built before the new types were /// added. /// /// Every message contains an UnknownFieldSet. /// /// Most users will never need to use this class directly. /// </summary> public sealed class UnknownFieldSet { private static readonly UnknownFieldSet defaultInstance = new UnknownFieldSet(new Dictionary<int, UnknownField>()); private readonly IDictionary<int, UnknownField> fields; private UnknownFieldSet(IDictionary<int, UnknownField> fields) { this.fields = fields; } /// <summary> /// Creates a new unknown field set builder. /// </summary> public static Builder CreateBuilder() { return new Builder(); } /// <summary> /// Creates a new unknown field set builder /// and initialize it from <paramref name="original"/>. /// </summary> public static Builder CreateBuilder(UnknownFieldSet original) { return new Builder().MergeFrom(original); } public static UnknownFieldSet DefaultInstance { get { return defaultInstance; } } /// <summary> /// Returns a read-only view of the mapping from field numbers to values. /// </summary> public IDictionary<int, UnknownField> FieldDictionary { get { return Dictionaries.AsReadOnly(fields); } } /// <summary> /// Checks whether or not the given field number is present in the set. /// </summary> public bool HasField(int field) { return fields.ContainsKey(field); } /// <summary> /// Fetches a field by number, returning an empty field if not present. /// Never returns null. /// </summary> public UnknownField this[int number] { get { UnknownField ret; if (!fields.TryGetValue(number, out ret)) { ret = UnknownField.DefaultInstance; } return ret; } } /// <summary> /// Serializes the set and writes it to <paramref name="output"/>. /// </summary> public void WriteTo(CodedOutputStream output) { foreach (KeyValuePair<int, UnknownField> entry in fields) { entry.Value.WriteTo(entry.Key, output); } } /// <summary> /// Gets the number of bytes required to encode this set. /// </summary> public int SerializedSize { get { int result = 0; foreach (KeyValuePair<int, UnknownField> entry in fields) { result += entry.Value.GetSerializedSize(entry.Key); } return result; } } /// <summary> /// Converts the set to a string in protocol buffer text format. This /// is just a trivial wrapper around TextFormat.PrintToString. /// </summary> public override String ToString() { return TextFormat.PrintToString(this); } /// <summary> /// Serializes the message to a ByteString and returns it. This is /// just a trivial wrapper around WriteTo(CodedOutputStream). /// </summary> /// <returns></returns> public ByteString ToByteString() { ByteString.CodedBuilder codedBuilder = new ByteString.CodedBuilder(SerializedSize); WriteTo(codedBuilder.CodedOutput); return codedBuilder.Build(); } /// <summary> /// Serializes the message to a byte array and returns it. This is /// just a trivial wrapper around WriteTo(CodedOutputStream). /// </summary> /// <returns></returns> public byte[] ToByteArray() { byte[] data = new byte[SerializedSize]; CodedOutputStream output = CodedOutputStream.CreateInstance(data); WriteTo(output); output.CheckNoSpaceLeft(); return data; } /// <summary> /// Serializes the message and writes it to <paramref name="output"/>. This is /// just a trivial wrapper around WriteTo(CodedOutputStream). /// </summary> /// <param name="output"></param> public void WriteTo(Stream output) { CodedOutputStream codedOutput = CodedOutputStream.CreateInstance(output); WriteTo(codedOutput); codedOutput.Flush(); } /// <summary> /// Serializes the set and writes it to <paramref name="output"/> using /// the MessageSet wire format. /// </summary> public void WriteAsMessageSetTo(CodedOutputStream output) { foreach (KeyValuePair<int, UnknownField> entry in fields) { entry.Value.WriteAsMessageSetExtensionTo(entry.Key, output); } } /// <summary> /// Gets the number of bytes required to encode this set using the MessageSet /// wire format. /// </summary> public int SerializedSizeAsMessageSet { get { int result = 0; foreach (KeyValuePair<int, UnknownField> entry in fields) { result += entry.Value.GetSerializedSizeAsMessageSetExtension(entry.Key); } return result; } } public override bool Equals(object other) { if (ReferenceEquals(this, other)) { return true; } UnknownFieldSet otherSet = other as UnknownFieldSet; return otherSet != null && Dictionaries.Equals(fields, otherSet.fields); } public override int GetHashCode() { return Dictionaries.GetHashCode(fields); } /// <summary> /// Parses an UnknownFieldSet from the given input. /// </summary> public static UnknownFieldSet ParseFrom(CodedInputStream input) { return CreateBuilder().MergeFrom(input).Build(); } /// <summary> /// Parses an UnknownFieldSet from the given data. /// </summary> public static UnknownFieldSet ParseFrom(ByteString data) { return CreateBuilder().MergeFrom(data).Build(); } /// <summary> /// Parses an UnknownFieldSet from the given data. /// </summary> public static UnknownFieldSet ParseFrom(byte[] data) { return CreateBuilder().MergeFrom(data).Build(); } /// <summary> /// Parses an UnknownFieldSet from the given input. /// </summary> public static UnknownFieldSet ParseFrom(Stream input) { return CreateBuilder().MergeFrom(input).Build(); } /// <summary> /// Builder for UnknownFieldSets. /// </summary> public sealed class Builder { /// <summary> /// Mapping from number to field. Note that by using a SortedList we ensure /// that the fields will be serialized in ascending order. /// </summary> private IDictionary<int, UnknownField> fields = new SortedList<int, UnknownField>(); // Optimization: We keep around a builder for the last field that was // modified so that we can efficiently add to it multiple times in a // row (important when parsing an unknown repeated field). private int lastFieldNumber; private UnknownField.Builder lastField; internal Builder() { } /// <summary> /// Returns a field builder for the specified field number, including any values /// which already exist. /// </summary> private UnknownField.Builder GetFieldBuilder(int number) { if (lastField != null) { if (number == lastFieldNumber) { return lastField; } // Note: AddField() will reset lastField and lastFieldNumber. AddField(lastFieldNumber, lastField.Build()); } if (number == 0) { return null; } lastField = UnknownField.CreateBuilder(); UnknownField existing; if (fields.TryGetValue(number, out existing)) { lastField.MergeFrom(existing); } lastFieldNumber = number; return lastField; } /// <summary> /// Build the UnknownFieldSet and return it. Once this method has been called, /// this instance will no longer be usable. Calling any method after this /// will throw a NullReferenceException. /// </summary> public UnknownFieldSet Build() { GetFieldBuilder(0); // Force lastField to be built. UnknownFieldSet result = fields.Count == 0 ? DefaultInstance : new UnknownFieldSet(fields); fields = null; return result; } /// <summary> /// Adds a field to the set. If a field with the same number already exists, it /// is replaced. /// </summary> public Builder AddField(int number, UnknownField field) { if (number == 0) { throw new ArgumentOutOfRangeException("number", "Zero is not a valid field number."); } if (lastField != null && lastFieldNumber == number) { // Discard this. lastField = null; lastFieldNumber = 0; } fields[number] = field; return this; } /// <summary> /// Resets the builder to an empty set. /// </summary> public Builder Clear() { fields.Clear(); lastFieldNumber = 0; lastField = null; return this; } /// <summary> /// Parse an entire message from <paramref name="input"/> and merge /// its fields into this set. /// </summary> public Builder MergeFrom(CodedInputStream input) { while (true) { uint tag = input.ReadTag(); if (tag == 0 || !MergeFieldFrom(tag, input)) { break; } } return this; } /// <summary> /// Parse a single field from <paramref name="input"/> and merge it /// into this set. /// </summary> /// <param name="tag">The field's tag number, which was already parsed.</param> /// <param name="input">The coded input stream containing the field</param> /// <returns>false if the tag is an "end group" tag, true otherwise</returns> [CLSCompliant(false)] public bool MergeFieldFrom(uint tag, CodedInputStream input) { int number = WireFormat.GetTagFieldNumber(tag); switch (WireFormat.GetTagWireType(tag)) { case WireFormat.WireType.Varint: GetFieldBuilder(number).AddVarint(input.ReadUInt64()); return true; case WireFormat.WireType.Fixed64: GetFieldBuilder(number).AddFixed64(input.ReadFixed64()); return true; case WireFormat.WireType.LengthDelimited: GetFieldBuilder(number).AddLengthDelimited(input.ReadBytes()); return true; case WireFormat.WireType.StartGroup: { Builder subBuilder = CreateBuilder(); input.ReadUnknownGroup(number, subBuilder); GetFieldBuilder(number).AddGroup(subBuilder.Build()); return true; } case WireFormat.WireType.EndGroup: return false; case WireFormat.WireType.Fixed32: GetFieldBuilder(number).AddFixed32(input.ReadFixed32()); return true; default: throw InvalidProtocolBufferException.InvalidWireType(); } } /// <summary> /// Parses <paramref name="input"/> as an UnknownFieldSet and merge it /// with the set being built. This is just a small wrapper around /// MergeFrom(CodedInputStream). /// </summary> public Builder MergeFrom(Stream input) { CodedInputStream codedInput = CodedInputStream.CreateInstance(input); MergeFrom(codedInput); codedInput.CheckLastTagWas(0); return this; } /// <summary> /// Parses <paramref name="data"/> as an UnknownFieldSet and merge it /// with the set being built. This is just a small wrapper around /// MergeFrom(CodedInputStream). /// </summary> public Builder MergeFrom(ByteString data) { CodedInputStream input = data.CreateCodedInput(); MergeFrom(input); input.CheckLastTagWas(0); return this; } /// <summary> /// Parses <paramref name="data"/> as an UnknownFieldSet and merge it /// with the set being built. This is just a small wrapper around /// MergeFrom(CodedInputStream). /// </summary> public Builder MergeFrom(byte[] data) { CodedInputStream input = CodedInputStream.CreateInstance(data); MergeFrom(input); input.CheckLastTagWas(0); return this; } /// <summary> /// Convenience method for merging a new field containing a single varint /// value. This is used in particular when an unknown enum value is /// encountered. /// </summary> [CLSCompliant(false)] public Builder MergeVarintField(int number, ulong value) { if (number == 0) { throw new ArgumentOutOfRangeException("number", "Zero is not a valid field number."); } GetFieldBuilder(number).AddVarint(value); return this; } /// <summary> /// Merges the fields from <paramref name="other"/> into this set. /// If a field number exists in both sets, the values in <paramref name="other"/> /// will be appended to the values in this set. /// </summary> public Builder MergeFrom(UnknownFieldSet other) { if (other != DefaultInstance) { foreach(KeyValuePair<int, UnknownField> entry in other.fields) { MergeField(entry.Key, entry.Value); } } return this; } /// <summary> /// Checks if the given field number is present in the set. /// </summary> public bool HasField(int number) { if (number == 0) { throw new ArgumentOutOfRangeException("number", "Zero is not a valid field number."); } return number == lastFieldNumber || fields.ContainsKey(number); } /// <summary> /// Adds a field to the unknown field set. If a field with the same /// number already exists, the two are merged. /// </summary> public Builder MergeField(int number, UnknownField field) { if (number == 0) { throw new ArgumentOutOfRangeException("number", "Zero is not a valid field number."); } if (HasField(number)) { GetFieldBuilder(number).MergeFrom(field); } else { // Optimization: We could call getFieldBuilder(number).mergeFrom(field) // in this case, but that would create a copy of the Field object. // We'd rather reuse the one passed to us, so call AddField() instead. AddField(number, field); } return this; } internal void MergeFrom(CodedInputStream input, ExtensionRegistry extensionRegistry, IBuilder builder) { while (true) { uint tag = input.ReadTag(); if (tag == 0) { break; } if (!MergeFieldFrom(input, extensionRegistry, builder, tag)) { // end group tag break; } } } /// <summary> /// Like <see cref="MergeFrom(CodedInputStream, ExtensionRegistry, IBuilder)" /> /// but parses a single field. /// </summary> /// <param name="input">The input to read the field from</param> /// <param name="extensionRegistry">Registry to use when an extension field is encountered</param> /// <param name="builder">Builder to merge field into, if it's a known field</param> /// <param name="tag">The tag, which should already have been read from the input</param> /// <returns>true unless the tag is an end-group tag</returns> internal bool MergeFieldFrom(CodedInputStream input, ExtensionRegistry extensionRegistry, IBuilder builder, uint tag) { MessageDescriptor type = builder.DescriptorForType; if (type.Options.MessageSetWireFormat && tag == WireFormat.MessageSetTag.ItemStart) { MergeMessageSetExtensionFromCodedStream(input, extensionRegistry, builder); return true; } WireFormat.WireType wireType = WireFormat.GetTagWireType(tag); int fieldNumber = WireFormat.GetTagFieldNumber(tag); FieldDescriptor field; IMessage defaultFieldInstance = null; if (type.IsExtensionNumber(fieldNumber)) { ExtensionInfo extension = extensionRegistry[type, fieldNumber]; if (extension == null) { field = null; } else { field = extension.Descriptor; defaultFieldInstance = extension.DefaultInstance; } } else { field = type.FindFieldByNumber(fieldNumber); } // Unknown field or wrong wire type. Skip. if (field == null || wireType != WireFormat.GetWireType(field)) { return MergeFieldFrom(tag, input); } if (field.IsPacked) { int length = (int)input.ReadRawVarint32(); int limit = input.PushLimit(length); if (field.FieldType == FieldType.Enum) { while (!input.ReachedLimit) { int rawValue = input.ReadEnum(); object value = field.EnumType.FindValueByNumber(rawValue); if (value == null) { // If the number isn't recognized as a valid value for this // enum, drop it (don't even add it to unknownFields). return true; } builder.WeakAddRepeatedField(field, value); } } else { while (!input.ReachedLimit) { Object value = input.ReadPrimitiveField(field.FieldType); builder.WeakAddRepeatedField(field, value); } } input.PopLimit(limit); } else { object value; switch (field.FieldType) { case FieldType.Group: case FieldType.Message: { IBuilder subBuilder; if (defaultFieldInstance != null) { subBuilder = defaultFieldInstance.WeakCreateBuilderForType(); } else { subBuilder = builder.CreateBuilderForField(field); } if (!field.IsRepeated) { subBuilder.WeakMergeFrom((IMessage)builder[field]); } if (field.FieldType == FieldType.Group) { input.ReadGroup(field.FieldNumber, subBuilder, extensionRegistry); } else { input.ReadMessage(subBuilder, extensionRegistry); } value = subBuilder.WeakBuild(); break; } case FieldType.Enum: { int rawValue = input.ReadEnum(); value = field.EnumType.FindValueByNumber(rawValue); // If the number isn't recognized as a valid value for this enum, // drop it. if (value == null) { MergeVarintField(fieldNumber, (ulong)rawValue); return true; } break; } default: value = input.ReadPrimitiveField(field.FieldType); break; } if (field.IsRepeated) { builder.WeakAddRepeatedField(field, value); } else { builder[field] = value; } } return true; } /// <summary> /// Called by MergeFieldFrom to parse a MessageSet extension. /// </summary> private void MergeMessageSetExtensionFromCodedStream(CodedInputStream input, ExtensionRegistry extensionRegistry, IBuilder builder) { MessageDescriptor type = builder.DescriptorForType; // The wire format for MessageSet is: // message MessageSet { // repeated group Item = 1 { // required int32 typeId = 2; // required bytes message = 3; // } // } // "typeId" is the extension's field number. The extension can only be // a message type, where "message" contains the encoded bytes of that // message. // // In practice, we will probably never see a MessageSet item in which // the message appears before the type ID, or where either field does not // appear exactly once. However, in theory such cases are valid, so we // should be prepared to accept them. int typeId = 0; ByteString rawBytes = null; // If we encounter "message" before "typeId" IBuilder subBuilder = null; FieldDescriptor field = null; while (true) { uint tag = input.ReadTag(); if (tag == 0) { break; } if (tag == WireFormat.MessageSetTag.TypeID) { typeId = input.ReadInt32(); // Zero is not a valid type ID. if (typeId != 0) { ExtensionInfo extension = extensionRegistry[type, typeId]; if (extension != null) { field = extension.Descriptor; subBuilder = extension.DefaultInstance.WeakCreateBuilderForType(); IMessage originalMessage = (IMessage)builder[field]; if (originalMessage != null) { subBuilder.WeakMergeFrom(originalMessage); } if (rawBytes != null) { // We already encountered the message. Parse it now. // TODO(jonskeet): Check this is okay. It's subtly different from the Java, as it doesn't create an input stream from rawBytes. // In fact, why don't we just call MergeFrom(rawBytes)? And what about the extension registry? subBuilder.WeakMergeFrom(rawBytes.CreateCodedInput()); rawBytes = null; } } else { // Unknown extension number. If we already saw data, put it // in rawBytes. if (rawBytes != null) { MergeField(typeId, UnknownField.CreateBuilder().AddLengthDelimited(rawBytes).Build()); rawBytes = null; } } } } else if (tag == WireFormat.MessageSetTag.Message) { if (typeId == 0) { // We haven't seen a type ID yet, so we have to store the raw bytes for now. rawBytes = input.ReadBytes(); } else if (subBuilder == null) { // We don't know how to parse this. Ignore it. MergeField(typeId, UnknownField.CreateBuilder().AddLengthDelimited(input.ReadBytes()).Build()); } else { // We already know the type, so we can parse directly from the input // with no copying. Hooray! input.ReadMessage(subBuilder, extensionRegistry); } } else { // Unknown tag. Skip it. if (!input.SkipField(tag)) { break; // end of group } } } input.CheckLastTagWas(WireFormat.MessageSetTag.ItemEnd); if (subBuilder != null) { builder[field] = subBuilder.WeakBuild(); } } } } }
37.264012
145
0.605937
[ "BSD-3-Clause" ]
apkbox/nano-rpc
third_party/protobuf-csharp-port/src/src/ProtocolBuffers/UnknownFieldSet.cs
25,265
C#
namespace TPP.Core.Data.Entities { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; [Table("Microcycle")] public partial class Microcycle { public int Id { get; set; } [Column(TypeName = "text")] public string Name { get; set; } public DateTime? StartDate { get; set; } public DateTime? EndDate { get; set; } public int? TeamId { get; set; } public int? SubTeamId { get; set; } public int? SeasonId { get; set; } } }
23.357143
55
0.620795
[ "MIT" ]
Bhaskers-Blu-Org2/SPP_Public
src/api/Data/DataEntityGenerator/Microcycle.cs
654
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.Net.Sockets; namespace server { class Program { static Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); static void Main(string[] args) { Console.WriteLine("Server starting...."); Console.WriteLine("Waiting for connection"); bool conNumber; conNumber = server.Connected; Console.WriteLine(conNumber); Console.WriteLine("-----------------------------------------------------------------"); do{ Program.Listen(); }while(server.Accept()!=server.Accept()); } static byte[] buffer = new byte[1024]; static byte[] buffer1 = new byte[1024]; static public void Listen() { server.Bind(new IPEndPoint(0, 8000)); server.Listen(10); Socket axxept = server.Accept(); try { axxept.Receive(buffer,0,buffer.Length,0); Console.WriteLine(Encoding.Default.GetString(buffer)); axxept.Send(buffer1, 0, buffer.Length, 0); Console.WriteLine(Encoding.Default.GetString(buffer1)); } catch (Exception) { Console.WriteLine("Something went wrong"); } server.Close(); axxept.Close(); } } }
29.203704
106
0.507292
[ "MIT" ]
randomvi/network-group-message-tool
server/server/Program.cs
1,579
C#
// // Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #if !SILVERLIGHT && !__IOS__ namespace NLog.LayoutRenderers { using System; using System.Globalization; using System.Runtime.InteropServices; using System.Text; using NLog.Config; using NLog.Internal; /// <summary> /// ASP Application variable. /// </summary> [LayoutRenderer("asp-application")] public class AspApplicationValueLayoutRenderer : LayoutRenderer { /// <summary> /// Gets or sets the ASP Application variable name. /// </summary> /// <docgen category='Rendering Options' order='10' /> [RequiredParameter] [DefaultParameter] public string Variable { get; set; } /// <summary> /// Renders the specified ASP Application variable and appends it to the specified <see cref="StringBuilder" />. /// </summary> /// <param name="builder">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="logEvent">Logging event.</param> protected override void Append(StringBuilder builder, LogEventInfo logEvent) { AspHelper.IApplicationObject app = AspHelper.GetApplicationObject(); if (app != null) { if (this.Variable != null) { object variableValue = app.GetValue(this.Variable); builder.Append(Convert.ToString(variableValue, CultureInfo.InvariantCulture)); } Marshal.ReleaseComObject(app); } } } } #endif
39.481481
120
0.67636
[ "BSD-3-Clause" ]
YuLad/NLog
src/NLog/LayoutRenderers/AspApplicationValueLayoutRenderer.cs
3,198
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace YPIConnect.Xps.Result.ClientBillingDetailReportResult { public class ClientBillingDetailReportData : List<ClientBillingDetailReportDataAccessionOrder> { public ClientBillingDetailReportData() { } } }
21.470588
98
0.756164
[ "MIT" ]
SidHarder/ypi-connect
Xps/Result/ClientBillingDetailReportResult/ClientBillingDetailReportData.cs
367
C#
using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; namespace RESTAURANT.API.DAL { public class DrinkGroup : RestaurantBase { [ForeignKey("DrinkGroupId")] public virtual List<Drink> Drinks { get; set; } } }
24.545455
55
0.707407
[ "Apache-2.0" ]
tiepnx/restaurentAPI
source/RESTAURANT.API.DAL/DBModel/DrinkGroup.cs
272
C#
//---------------------------------------------------------------------------------------------- // <copyright file="ISettings.cs" company="Microsoft"> // Copyright (c) Microsoft. All rights reserved. // </copyright> //---------------------------------------------------------------------------------------------- namespace StickersTemplate.Interfaces { using System; /// <summary> /// Interface describing all of the app settings. /// </summary> public interface ISettings { /// <summary> /// Gets the Microsoft App Id. /// </summary> string MicrosoftAppId { get; } /// <summary> /// Gets the config uri for the Sticker set. /// </summary> Uri ConfigUri { get; } } }
28.296296
97
0.426702
[ "MIT" ]
AlexAhrens/microsoft-teams-apps-stickers
StickersTemplate/Interfaces/ISettings.cs
766
C#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Linq; using NUnit.Framework; using osu.Framework.Graphics.Containers; using osu.Framework.Testing; using osu.Framework.Utils; using osu.Game.Graphics.Containers; using osu.Game.Rulesets.Osu.Mods; using osu.Game.Rulesets.Osu.Objects.Drawables; namespace osu.Game.Rulesets.Osu.Tests.Mods { public class TestSceneOsuModDifficultyAdjust : OsuModTestScene { [Test] public void TestNoAdjustment() => CreateModTest(new ModTestData { Mod = new OsuModDifficultyAdjust(), Autoplay = true, PassCondition = checkSomeHit }); [Test] public void TestCircleSize1() => CreateModTest(new ModTestData { Mod = new OsuModDifficultyAdjust { CircleSize = { Value = 1 } }, Autoplay = true, PassCondition = () => checkSomeHit() && checkObjectsScale(0.78f) }); [Test] public void TestCircleSize10() => CreateModTest(new ModTestData { Mod = new OsuModDifficultyAdjust { CircleSize = { Value = 10 } }, Autoplay = true, PassCondition = () => checkSomeHit() && checkObjectsScale(0.15f) }); [Test] public void TestApproachRate1() => CreateModTest(new ModTestData { Mod = new OsuModDifficultyAdjust { ApproachRate = { Value = 1 } }, Autoplay = true, PassCondition = () => checkSomeHit() && checkObjectsPreempt(1680) }); [Test] public void TestApproachRate10() => CreateModTest(new ModTestData { Mod = new OsuModDifficultyAdjust { ApproachRate = { Value = 10 } }, Autoplay = true, PassCondition = () => checkSomeHit() && checkObjectsPreempt(450) }); private bool checkObjectsPreempt(double target) { var objects = Player.ChildrenOfType<DrawableHitCircle>(); if (!objects.Any()) return false; return objects.All(o => o.HitObject.TimePreempt == target); } private bool checkObjectsScale(float target) { var objects = Player.ChildrenOfType<DrawableHitCircle>(); if (!objects.Any()) return false; return objects.All(o => Precision.AlmostEquals(o.ChildrenOfType<ShakeContainer>().First().Children.OfType<Container>().Single().Scale.X, target)); } private bool checkSomeHit() { return Player.ScoreProcessor.JudgedHits >= 2; } } }
34.382716
159
0.582406
[ "MIT" ]
AaqibAhamed/osu
osu.Game.Rulesets.Osu.Tests/Mods/TestSceneOsuModDifficultyAdjust.cs
2,707
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections; using System.Collections.Generic; using System.Linq; using StarkPlatform.CodeAnalysis; using StarkPlatform.CodeAnalysis.Shared.Extensions; using StarkPlatform.VisualStudio.LanguageServices.Implementation.CodeModel.ExternalElements; using StarkPlatform.VisualStudio.LanguageServices.Implementation.Interop; using StarkPlatform.VisualStudio.LanguageServices.Implementation.Utilities; namespace StarkPlatform.VisualStudio.LanguageServices.Implementation.CodeModel.Collections { public sealed class ExternalNamespaceEnumerator : IEnumerator, ICloneable { internal static IEnumerator Create(CodeModelState state, ProjectId projectId, SymbolKey namespaceSymbolId) { var newEnumerator = new ExternalNamespaceEnumerator(state, projectId, namespaceSymbolId); return (IEnumerator)ComAggregate.CreateAggregatedObject(newEnumerator); } private ExternalNamespaceEnumerator(CodeModelState state, ProjectId projectId, SymbolKey namespaceSymbolId) { _state = state; _projectId = projectId; _namespaceSymbolId = namespaceSymbolId; _childEnumerator = ChildrenOfNamespace(state, projectId, namespaceSymbolId).GetEnumerator(); } private readonly CodeModelState _state; private readonly ProjectId _projectId; private readonly SymbolKey _namespaceSymbolId; private readonly IEnumerator<EnvDTE.CodeElement> _childEnumerator; public object Current { get { return _childEnumerator.Current; } } public object Clone() { return Create(_state, _projectId, _namespaceSymbolId); } public bool MoveNext() { return _childEnumerator.MoveNext(); } public void Reset() { _childEnumerator.Reset(); } internal static IEnumerable<EnvDTE.CodeElement> ChildrenOfNamespace(CodeModelState state, ProjectId projectId, SymbolKey namespaceSymbolId) { var project = state.Workspace.CurrentSolution.GetProject(projectId); if (project == null) { throw Exceptions.ThrowEFail(); } var namespaceSymbol = namespaceSymbolId.Resolve(project.GetCompilationAsync().Result).Symbol as INamespaceSymbol; if (namespaceSymbol == null) { throw Exceptions.ThrowEFail(); } var containingAssembly = project.GetCompilationAsync().Result.Assembly; foreach (var child in namespaceSymbol.GetMembers()) { if (child is INamespaceSymbol namespaceChild) { yield return (EnvDTE.CodeElement)ExternalCodeNamespace.Create(state, projectId, namespaceChild); } else { var namedType = (INamedTypeSymbol)child; if (namedType.IsAccessibleWithin(containingAssembly)) { if (namedType.Locations.Any(l => l.IsInMetadata || l.IsInSource)) { yield return state.CodeModelService.CreateCodeType(state, projectId, namedType); } } } } } } }
36.454545
161
0.632031
[ "Apache-2.0" ]
stark-lang/stark-roslyn
src/VisualStudio/Core/Impl/CodeModel/Collections/ExternalNamespaceEnumerator.cs
3,611
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("15.ReplaceTags")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("15.ReplaceTags")] [assembly: AssemblyCopyright("Copyright © 2015")] [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("f19946af-e672-476c-b571-9f723f3f0e83")] // 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")]
37.864865
84
0.744468
[ "MIT" ]
Andro0/TelerikAcademy
C#2/06.Homework_Strings_and_Text_Processing/15.ReplaceTags/Properties/AssemblyInfo.cs
1,404
C#
namespace ClassLib095 { public class Class005 { public static string Property => "ClassLib095"; } }
15
55
0.633333
[ "MIT" ]
333fred/performance
src/scenarios/weblarge2.0/src/ClassLib095/Class005.cs
120
C#
using Util = Saklient.Util; namespace Saklient.Cloud.Resources { /// <summary>FTPサーバのアカウント情報。 /// </summary> public class FtpInfo { internal string _HostName; public string Get_hostName() { return this._HostName; } /// <summary>ホスト名 /// </summary> public string HostName { get { return this.Get_hostName(); } } internal string _User; public string Get_user() { return this._User; } /// <summary>ユーザ名 /// </summary> public string User { get { return this.Get_user(); } } internal string _Password; public string Get_password() { return this._Password; } /// <summary>パスワード /// </summary> public string Password { get { return this.Get_password(); } } public FtpInfo(object obj) { this._HostName = ((string)((obj as System.Collections.Generic.Dictionary<string, object>)["HostName"])); this._User = ((string)((obj as System.Collections.Generic.Dictionary<string, object>)["User"])); this._Password = ((string)((obj as System.Collections.Generic.Dictionary<string, object>)["Password"])); } } }
17.793651
107
0.636931
[ "MIT" ]
223n/saklient.cs
src/Saklient/Cloud/Resources/FtpInfo.cs
1,171
C#
using Microsoft.AspNetCore.Mvc.ModelBinding; using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Reflection; using System.Threading.Tasks; namespace CompanyEmployees.ModelBinders { public class ArrayModelBinder : IModelBinder { public Task BindModelAsync(ModelBindingContext bindingContext) { if (!bindingContext.ModelMetadata.IsEnumerableType) { bindingContext.Result = ModelBindingResult.Failed(); return Task.CompletedTask; } var providedValue = bindingContext.ValueProvider .GetValue(bindingContext.ModelName) .ToString(); if (string.IsNullOrEmpty(providedValue)) { bindingContext.Result = ModelBindingResult.Success(null); return Task.CompletedTask; } var genericType = bindingContext.ModelType.GetTypeInfo().GenericTypeArguments[0]; var converter = TypeDescriptor.GetConverter(genericType); var objectArray = providedValue.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries) .Select(x => converter.ConvertFromString(x.Trim())) .ToArray(); var guidArray = Array.CreateInstance(genericType, objectArray.Length); objectArray.CopyTo(guidArray, 0); bindingContext.Model = guidArray; bindingContext.Result = ModelBindingResult.Success(bindingContext.Model); return Task.CompletedTask; } } }
37.418605
85
0.642014
[ "MIT" ]
DiegooDV/ASP.NET-CORE-3-Web-API-Project
CompanyEmployees/ModelBinders/ArrayModelBinder.cs
1,611
C#
using Cactus.IService.Store; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Cactus.SQLiteService.Store { public class CustomerService : ICustomerService { public bool Insert(Model.Store.Customer entity) { throw new NotImplementedException(); } public bool InsertBatch(List<Model.Store.Customer> datas) { throw new NotImplementedException(); } public void Update(Model.Store.Customer entity) { throw new NotImplementedException(); } public void Delete(string ids) { throw new NotImplementedException(); } public List<Model.Store.Customer> GetAll() { throw new NotImplementedException(); } public List<Model.Store.Customer> ToPagedList(int pageIndex, int pageSize, string keySelector, out int count) { throw new NotImplementedException(); } public Model.Store.Customer Find(int id) { throw new NotImplementedException(); } } }
25.479167
118
0.589534
[ "MIT" ]
MyFarmland/Cactus
Cactus.SQLiteService/Store/CustomerService.cs
1,225
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using ExcelDna.Integration; namespace CellAddressTests.AddIn.UI { public class UnitTestAddIn : IExcelAddIn { #region Implementation of IExcelAddIn public void AutoOpen() { Trace.Listeners.Add(new ConsoleTraceListener()); } public void AutoClose() { } #endregion } }
20.583333
60
0.661943
[ "MIT" ]
zwq00000/CellAddress
test/CellAddress.Tests.AddIn/UI/UnitTestAddIn.cs
496
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Xunit; namespace AppConfigTransforms.Tests { public class TargetsTests { private readonly string _thisAssembly; private readonly string _binRoot; private readonly string _testRoot; private readonly IEnumerable<string> _binConfigs; private readonly IEnumerable<string> _testConfigs; public TargetsTests() { var thisAssemblyUri = new Uri(Assembly.GetExecutingAssembly().CodeBase); _thisAssembly = Path.GetFileName(thisAssemblyUri.LocalPath); _binRoot = Path.GetDirectoryName(thisAssemblyUri.LocalPath); _testRoot = Path.Combine(_binRoot, "..\\..\\"); _testRoot = Path.GetFullPath(_testRoot); _binConfigs = Directory.GetFiles(_binRoot, "*.config").Select(x => Path.GetFileName(x)); _testConfigs = Directory.GetFiles(_testRoot, "App*.config").Select(x => Path.GetFileName(x)); } [Fact] public void should_copy_and_rename_app_config_transforms_to_output() { Assert.Equal(_testConfigs.Count(), 3); foreach(var transform in _testConfigs) { var expectedName = transform.Replace("App", _thisAssembly); Assert.Contains(expectedName, _binConfigs, StringComparer.OrdinalIgnoreCase); } } } }
35.325581
105
0.657011
[ "MIT" ]
dan-turner/AppConfigTransforms
src/AppConfigTransforms.Tests/TargetsTests.cs
1,521
C#
//GENERATED: CS Code using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace UnrealEngine{ public partial class ULocalMessage:UObject { [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern new IntPtr StaticClass(); } }
25
55
0.793333
[ "MIT" ]
RobertAcksel/UnrealCS
Engine/Plugins/UnrealCS/UECSharpDomain/UnrealEngine/GeneratedScriptFile/ULocalMessage.cs
300
C#
/* * Copyright 2012 The Netty Project * * The Netty Project 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. * * Copyright (c) 2020 The Dotnetty-Span-Fork Project (cuteant@outlook.com) All rights reserved. * * https://github.com/cuteant/dotnetty-span-fork * * Licensed under the MIT license. See LICENSE file in the project root for full license information. */ namespace DotNetty.Codecs.Http2 { using System; using System.Runtime.CompilerServices; /// <summary> /// A skeletal builder implementation of <see cref="InboundHttp2ToHttpAdapter"/> and its subtypes. /// </summary> public abstract class AbstractInboundHttp2ToHttpAdapterBuilder<TAdapter, TBuilder> where TAdapter : InboundHttp2ToHttpAdapter where TBuilder : AbstractInboundHttp2ToHttpAdapterBuilder<TAdapter, TBuilder> { private readonly IHttp2Connection _connection; private int _maxContentLength; private bool _validateHttpHeaders; private bool _propagateSettings; /// <summary> /// Creates a new <see cref="InboundHttp2ToHttpAdapter"/> builder for the specified <see cref="IHttp2Connection"/>. /// </summary> /// <param name="connection">the object which will provide connection notification events /// for the current connection.</param> protected AbstractInboundHttp2ToHttpAdapterBuilder(IHttp2Connection connection) { if (connection is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.connection); } _connection = connection; } [MethodImpl(InlineMethod.AggressiveInlining)] protected TBuilder Self() => (TBuilder)this; /// <summary> /// Gets the <see cref="IHttp2Connection"/>. /// </summary> public IHttp2Connection Connection => _connection; /// <summary> /// Gets or sets the maximum length of the message content. /// <para> /// If the length of the message content, exceeds this value, a <see cref="TooLongFrameException"/> will be raised /// </para> /// </summary> public int MaxContentLength { get => _maxContentLength; set => _maxContentLength = value; } /// <summary> /// Specifies whether validation of HTTP headers should be performed. /// </summary> public bool IsValidateHttpHeaders { get => _validateHttpHeaders; set => _validateHttpHeaders = value; } /// <summary> /// Specifies whether a read settings frame should be propagated along the channel pipeline. /// </summary> /// <remarks>if <c>true</c> read settings will be passed along the pipeline. This can be useful /// to clients that need hold off sending data until they have received the settings.</remarks> public bool IsPropagateSettings { get => _propagateSettings; set => _propagateSettings = value; } /// <summary> /// Builds/creates a new <see cref="InboundHttp2ToHttpAdapter"/> instance using this builder's current settings. /// </summary> /// <returns></returns> public virtual TAdapter Build() { TAdapter instance = null; try { instance = Build(_connection, _maxContentLength, _validateHttpHeaders, _propagateSettings); } catch (Exception t) { ThrowHelper.ThrowInvalidOperationException_FailedToCreateInboundHttp2ToHttpAdapter(t); } _connection.AddListener(instance); return instance; } /// <summary> /// Creates a new <see cref="InboundHttp2ToHttpAdapter"/> with the specified properties. /// </summary> /// <param name="connection"></param> /// <param name="maxContentLength"></param> /// <param name="validateHttpHeaders"></param> /// <param name="propagateSettings"></param> /// <returns></returns> protected abstract TAdapter Build(IHttp2Connection connection, int maxContentLength, bool validateHttpHeaders, bool propagateSettings); } }
39.211382
123
0.639643
[ "MIT" ]
cuteant/SpanNetty
src/DotNetty.Codecs.Http2/AbstractInboundHttp2ToHttpAdapterBuilder.cs
4,825
C#
using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEditor; namespace Utj.UnityChoseKun { [System.Serializable] public class SpriteView { [SerializeField] SpriteKun m_spriteKun; [SerializeField] bool m_spriteFoldout = false; public SpriteView(SpriteKun spriteKun) { m_spriteKun = spriteKun; } public void OnGUI() { if (string.IsNullOrEmpty(m_spriteKun.name)) { m_spriteFoldout = EditorGUILayout.Foldout(m_spriteFoldout,"UnKnown"); } else { m_spriteFoldout = EditorGUILayout.Foldout(m_spriteFoldout,m_spriteKun.name); } if (m_spriteFoldout) { using(new EditorGUI.IndentLevelScope()) { if (m_spriteKun.pivot != null) { EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("Pivot"); var sb = new StringBuilder(); sb.AppendFormat("X:{0},Y:{1}", m_spriteKun.pivot.x, m_spriteKun.pivot.y); var st = sb.ToString(); EditorGUILayout.LabelField(st); EditorGUILayout.EndHorizontal(); } if (m_spriteKun.border != null) { EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("Border"); var sb = new StringBuilder(); sb.AppendFormat("L:{0},B:{1},R{2},T:{3}", m_spriteKun.border.x, m_spriteKun.border.y, m_spriteKun.border.z, m_spriteKun.border.w); var st = sb.ToString(); EditorGUILayout.LabelField(st); EditorGUILayout.EndHorizontal(); } } } } } public class SpritesView { [SerializeField] static SpriteKun[] m_spriteKuns; [SerializeField] SpriteView[] m_spriteViews; [SerializeField] Vector2 m_scrollPos; static string[] m_spriteNames; public static SpriteKun[] spriteKuns { get { return m_spriteKuns; } } public static string[] spriteNames { get { return m_spriteNames; } } public void OnGUI() { int cnt = 0; if(m_spriteViews != null) { cnt = m_spriteViews.Length; EditorGUILayout.LabelField("Sprite List("+cnt+")"); } else { EditorGUILayout.HelpBox("Please Push Pull Button.", MessageType.Info); } if(cnt != 0) { using (new EditorGUI.IndentLevelScope()) { m_scrollPos = EditorGUILayout.BeginScrollView(m_scrollPos); for(var i = 0; i < cnt; i++) { m_spriteViews[i].OnGUI(); } EditorGUILayout.EndScrollView(); } } if(GUILayout.Button("Pull")) { var packet = new AssetPacket<SpriteKun>(); packet.isResources = true; packet.isScene = true; UnityChoseKunEditor.SendMessage<AssetPacket<SpriteKun>>(UnityChoseKun.MessageID.SpritePull,packet); } } public void OnMessageEvent(BinaryReader binaryReader) { var packet = new AssetPacket<SpriteKun>(); packet.Deserialize(binaryReader); m_spriteKuns = packet.assetKuns; m_spriteViews = new SpriteView[m_spriteKuns.Length]; m_spriteNames = new string[m_spriteKuns.Length]; for(var i = 0; i < m_spriteKuns.Length; i++) { m_spriteViews[i] = new SpriteView(m_spriteKuns[i]); m_spriteNames[i] = m_spriteKuns[i].name; } } } }
31.720588
154
0.486092
[ "MIT" ]
katsumasa/UnityChoseKun
Editor/Scripts/SpriteView.cs
4,316
C#
namespace CCCS { public enum TokenKind { Unknown, Reserved, Identifier, Number, String, EOF } }
13
25
0.461538
[ "MIT" ]
mtakagi/CCCS
Assets/Editor/Tokenizer/TokenKind.cs
158
C#
using Microsoft.Extensions.Logging; namespace BO4E { #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member // todo: this thing should be removed. public static class StaticLogger { public static ILogger Logger { get; set; } } #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member }
26.4
90
0.70202
[ "MIT" ]
Hochfrequenz/BO4E-dotnet
BO4E/StaticLogger.cs
384
C#
using System; using System.Windows.Media.Imaging; using System.Windows; using System.Windows.Controls; using MahApps.Metro.Controls; using System.IO; using Brew.HacPack; namespace Brew.NSPack.GUI { public partial class ProgramWindow : MetroWindow { public int PreSelect = 0; public Start start; public TitlePackager editor; public ContentCreator creator; public ProgramWindow() { InitializeComponent(); HacPack.Utils.initTemporaryDirectory(); GUI.Resources.resetTitle(); } private void OptionToggle_SelectionChanged(object sender, SelectionChangedEventArgs e) { if(PageHolder is null) return; int tsel = OptionToggle.SelectedIndex; if(PreSelect == tsel) return; PreSelect = tsel; switch(PreSelect) { case 0: if(start is null) start = new Start(); PageHolder.NavigationService.Navigate(start); break; case 1: if(editor is null) editor = new TitlePackager(); PageHolder.NavigationService.Navigate(editor); break; case 2: if(creator is null) creator = new ContentCreator(); PageHolder.NavigationService.Navigate(creator); break; } } private void Button_Next_Click(object sender, RoutedEventArgs e) { if(PreSelect > 3) return; OptionToggle.SelectedIndex++; switch(PreSelect) { case 0: if(start is null) start = new Start(); PageHolder.NavigationService.Navigate(start); break; case 1: if(editor is null) editor = new TitlePackager(); PageHolder.NavigationService.Navigate(editor); break; case 2: if(creator is null) creator = new ContentCreator(); PageHolder.NavigationService.Navigate(creator); break; } } protected override void OnClosing(System.ComponentModel.CancelEventArgs e) { HacPack.Utils.exitTemporaryDirectory(); base.OnClosing(e); } private void Button_Back_Click(object sender, RoutedEventArgs e) { if(PreSelect <= 0) return; OptionToggle.SelectedIndex--; switch(PreSelect) { case 0: if(start is null) start = new Start(); PageHolder.NavigationService.Navigate(start); break; case 1: if(editor is null) editor = new TitlePackager(); PageHolder.NavigationService.Navigate(editor); break; case 2: if(creator is null) creator = new ContentCreator(); PageHolder.NavigationService.Navigate(creator); break; } } } }
33.05102
94
0.5159
[ "MIT" ]
tiliarou/Brew.NET
NSPack/GUI/ProgramWindow.xaml.cs
3,241
C#
using UnityEngine; using System.Collections; using System.Collections.Generic; public class Matrix<T> : IEnumerable<T> { int _width; int _height; int _capacity; T[,] data; Matrix<T> auxData; public int width { get { return _width; } } public int height { get { return _height; } } public int Capacity { get { return _capacity; } } public Matrix(int width, int height) { _width = width; _height = height; _capacity = _width * _height; data = new T[_width, _height]; } public Matrix(T[,] copyFrom) { _width = copyFrom.GetLength(0); _height = copyFrom.GetLength(1); _capacity = _width * _height; data = new T[_width, _height]; for (int y = 0; y < _height; y++) { for (int x = 0; x < _width; x++) { data[x, y] = copyFrom[x, y]; } } } public Matrix<T> Clone() { Matrix<T> aux = new Matrix<T>(width, height); for (int y = 0; y < _height; y++) { for (int x = 0; x < _width; x++) { aux.data[x, y] = data[x, y]; } } return aux; } public void SetRangeTo(int x0, int y0, int x1, int y1, T item) { for (int y = y0; y < y1; y++) { for (int x = x0; x < x1; x++) { data[x, y] = item; } } } public List<T> GetRange(int x0, int y0, int x1, int y1) { List<T> l = new List<T>(); for (int y = y0; y < y1; y++) { for (int x = x0; x < x1; x++) { l.Add(data[x, y]); } } return l; } public T this[int x, int y] { get { return data[x,y]; } set { data[x, y] = value; } } public IEnumerator<T> GetEnumerator() { for (int y = 0; y < _height; y++) { for (int x = 0; x < _width; x++) { if (data[x, y] == null) yield return default(T); else yield return data[x, y]; } } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } }
21.754902
65
0.451104
[ "Apache-2.0" ]
TaaroBravo/Monsterfall
Assets/Scripts/Utility/Matrix.cs
2,221
C#
namespace BarraksWars.Core.CommandsPackage { public class Fight : Command { public Fight(string[] data) : base(data) { } public override string Execute() { return "end"; } } }
16.4375
43
0.48289
[ "MIT" ]
valkin88/CSharp-Fundamentals
CSharp OOP Advanced/Reflection and Attributes - Exercises/BarraksWars/BarraksWars/Core/CommandsPackage/Fight.cs
265
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.ComponentModel; using Pulumi; namespace Pulumi.AzureNextGen.ImportExport.V20210101 { /// <summary> /// The drive's current state. /// </summary> [EnumType] public readonly struct DriveState : IEquatable<DriveState> { private readonly string _value; private DriveState(string value) { _value = value ?? throw new ArgumentNullException(nameof(value)); } public static DriveState Specified { get; } = new DriveState("Specified"); public static DriveState Received { get; } = new DriveState("Received"); public static DriveState NeverReceived { get; } = new DriveState("NeverReceived"); public static DriveState Transferring { get; } = new DriveState("Transferring"); public static DriveState Completed { get; } = new DriveState("Completed"); public static DriveState CompletedMoreInfo { get; } = new DriveState("CompletedMoreInfo"); public static DriveState ShippedBack { get; } = new DriveState("ShippedBack"); public static bool operator ==(DriveState left, DriveState right) => left.Equals(right); public static bool operator !=(DriveState left, DriveState right) => !left.Equals(right); public static explicit operator string(DriveState value) => value._value; [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object? obj) => obj is DriveState other && Equals(other); public bool Equals(DriveState other) => string.Equals(_value, other._value, StringComparison.Ordinal); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value?.GetHashCode() ?? 0; public override string ToString() => _value; } /// <summary> /// The type of kek encryption key /// </summary> [EnumType] public readonly struct EncryptionKekType : IEquatable<EncryptionKekType> { private readonly string _value; private EncryptionKekType(string value) { _value = value ?? throw new ArgumentNullException(nameof(value)); } public static EncryptionKekType MicrosoftManaged { get; } = new EncryptionKekType("MicrosoftManaged"); public static EncryptionKekType CustomerManaged { get; } = new EncryptionKekType("CustomerManaged"); public static bool operator ==(EncryptionKekType left, EncryptionKekType right) => left.Equals(right); public static bool operator !=(EncryptionKekType left, EncryptionKekType right) => !left.Equals(right); public static explicit operator string(EncryptionKekType value) => value._value; [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object? obj) => obj is EncryptionKekType other && Equals(other); public bool Equals(EncryptionKekType other) => string.Equals(_value, other._value, StringComparison.Ordinal); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value?.GetHashCode() ?? 0; public override string ToString() => _value; } }
42.961039
117
0.685611
[ "Apache-2.0" ]
pulumi/pulumi-azure-nextgen
sdk/dotnet/ImportExport/V20210101/Enums.cs
3,308
C#
using IqOption.Client.Models; using IqOption.Client.Ws.Base; using Newtonsoft.Json; namespace IqOption.Client.Ws.Request.Portfolio { //{"name":"subscribeMessage","request_id":"s_5","msg":{"name":"portfolio.position-changed","version":"2.0","params":{"routingFilters":{"user_balance_id":xxxx,"instrument_type":"forex"}}} internal class SubscribeBalanceChangedRequestBody { [JsonProperty("name")] public string Name { get; set; } = "portfolio.position-changed"; [JsonProperty("params")] public InstrumentRoutingFilterParameters Parameters { get; set; } [JsonProperty("version")] public string Version { get; set; } = "2.0"; internal class InstrumentRoutingFilterParameters { [JsonProperty("routingFilters")] public RequestFilter Filter { get; set; } internal class RequestFilter { [JsonProperty("user_balance_id")] public long UserBalanceId { get; set; } [JsonProperty("instrument_type")] public string InstrumentType { get; set; } } } } internal class SubscribeBalanceChangedRequest : WsMessageBase<SubscribeBalanceChangedRequestBody> { public override string Name => MessageType.SubscribeMessage; public SubscribeBalanceChangedRequest(long userBalanceId, InstrumentType instrumentType) { string instrumentTypeName = ""; if (instrumentType == InstrumentType.Forex) instrumentTypeName = "forex"; else if (instrumentType == InstrumentType.CFD) instrumentTypeName = "cfd"; else if (instrumentType == InstrumentType.Crypto) instrumentTypeName = "crypto"; else if (instrumentType == InstrumentType.DigitalOption) instrumentTypeName = "digital-option"; else if (instrumentType == InstrumentType.BinaryOption) instrumentTypeName = "binary-option"; else if (instrumentType == InstrumentType.TurboOption) instrumentTypeName = "turbo-option"; else if (instrumentType == InstrumentType.FxOption) instrumentTypeName = "fx-option"; else return; //msg base.Message = new SubscribeBalanceChangedRequestBody { // name Name = "portfolio.position-changed", //version Version = "2.0", //params Parameters = new SubscribeBalanceChangedRequestBody.InstrumentRoutingFilterParameters { //routingFilters Filter = new SubscribeBalanceChangedRequestBody.InstrumentRoutingFilterParameters.RequestFilter { //user_balance_id UserBalanceId = userBalanceId, //instrument_type InstrumentType = instrumentTypeName } } }; } } }
40.5
190
0.591943
[ "MIT" ]
aritters/IqOptionApiDotNet
src/IqOption.Client/Wss/Request/SubscribeMessages/SubscribeBalanceChangedRequest.cs
3,078
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; namespace Calendar.Pages { public class PrivacyModel : PageModel { public void OnGet() { } } }
19
42
0.700658
[ "MIT" ]
telebovich/Calendar
Calendar/Pages/Privacy.cshtml.cs
306
C#
using System; using System.Collections.Generic; using System.Text; using System.Net; using Acn.ArtNet.IO; namespace Acn.ArtNet.Packets { public enum ArtTodControlCommand { AtcNone = 0, AtcFlush = 1 } public class ArtTodControlPacket : ArtNetPacket { public ArtTodControlPacket() : base(ArtNetOpCodes.TodControl) { } public ArtTodControlPacket(ArtNetReceiveData data) : base(data) { } #region Packet Properties public byte Net { get; set; } public ArtTodControlCommand Command { get; set; } public byte Address { get; set; } #endregion public override void ReadData(ArtNetBinaryReader data) { base.ReadData(data); data.BaseStream.Seek(9, System.IO.SeekOrigin.Current); Net = data.ReadByte(); Command = (ArtTodControlCommand) data.ReadByte(); Address = data.ReadByte(); } public override void WriteData(ArtNetBinaryWriter data) { base.WriteData(data); data.Write(new byte[9]); data.Write(Net); data.Write((byte) Command); data.Write(Address); } } }
20.935484
66
0.561633
[ "MIT" ]
HakanL/ACN
Acn/ArtNet/Packets/ArtTodControlPacket.cs
1,298
C#
using System; namespace JetBrains.ReSharper.Plugins.Unity.CSharp.Daemon.Stages.PerformanceCriticalCodeAnalysis.Analyzers { [Flags] public enum UnityProblemAnalyzerContext : byte { NONE = 0, PERFORMANCE_CONTEXT = 1 << 0, BURST_CONTEXT = 1 << 1 } public static class UnityProblemAnalyzerContextUtil { public const byte UnityProblemAnalyzerContextSize = 2; } }
23.777778
106
0.67757
[ "Apache-2.0" ]
terrorizer1980/resharper-unity
resharper/resharper-unity/src/CSharp/Daemon/Stages/UnityProblemAnalyzerContext.cs
428
C#
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- namespace Microsoft.Azure.Commands.Resources.Test { using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation; using Microsoft.Azure.Commands.ResourceManager.Cmdlets.SdkClient; using Microsoft.Azure.Commands.ResourceManager.Cmdlets.SdkModels; using Microsoft.Azure.Commands.Resources.Models; using Microsoft.Azure.Management.ResourceManager; using Microsoft.Azure.Management.ResourceManager.Models; using Microsoft.Azure.ServiceManagemenet.Common.Models; using Microsoft.Rest.Azure; using Microsoft.WindowsAzure.Commands.Common.Test.Mocks; using Microsoft.WindowsAzure.Commands.ScenarioTest; using Moq; using System; using System.Collections.Generic; using System.Management.Automation; using System.Threading; using System.Threading.Tasks; using WindowsAzure.Commands.Test.Utilities.Common; using Xunit; using Xunit.Abstractions; /// <summary> /// Tests the AzureProvider cmdlets /// </summary> public class UnregisterAzureProviderCmdletTests : RMTestBase { /// <summary> /// An instance of the cmdlet /// </summary> private readonly UnregisterAzureProviderCmdlet cmdlet; /// <summary> /// A mock of the client /// </summary> private readonly Mock<IProvidersOperations> providerOperationsMock; /// <summary> /// A mock of the command runtime /// </summary> private readonly Mock<ICommandRuntime> commandRuntimeMock; private MockCommandRuntime mockRuntime; /// <summary> /// Initializes a new instance of the <see cref="GetAzureProviderCmdletTests"/> class. /// </summary> public UnregisterAzureProviderCmdletTests(ITestOutputHelper output) { this.providerOperationsMock = new Mock<IProvidersOperations>(); XunitTracingInterceptor.AddToContext(new XunitTracingInterceptor(output)); var resourceManagementClient = new Mock<IResourceManagementClient>(); resourceManagementClient .SetupGet(client => client.Providers) .Returns(() => this.providerOperationsMock.Object); this.commandRuntimeMock = new Mock<ICommandRuntime>(); this.commandRuntimeMock .Setup(m => m.ShouldProcess(It.IsAny<string>(), It.IsAny<string>())) .Returns(() => true); this.cmdlet = new UnregisterAzureProviderCmdlet { CommandRuntime = commandRuntimeMock.Object, ResourceManagerSdkClient = new ResourceManagerSdkClient { ResourceManagementClient = resourceManagementClient.Object } }; PSCmdletExtensions.SetCommandRuntimeMock(cmdlet, commandRuntimeMock.Object); mockRuntime = new MockCommandRuntime(); commandRuntimeMock.Setup(f => f.Host).Returns(mockRuntime.Host); } /// <summary> /// Validates all Unregister-AzureRmResourceProvider scenarios /// </summary> [Fact] [Trait(Category.AcceptanceType, Category.CheckIn)] public void UnregisterResourceProviderTests() { const string ProviderName = "Providers.Test"; var provider = new Provider { NamespaceProperty = ProviderName, RegistrationState = ResourcesClient.RegisteredStateName, ResourceTypes = new[] { new ProviderResourceType { Locations = new[] {"West US", "East US"}, //Name = "TestResource2" } } }; var unregistrationResult = provider; this.providerOperationsMock .Setup(client => client.UnregisterWithHttpMessagesAsync(It.IsAny<string>(), null, It.IsAny<CancellationToken>())) .Callback((string providerName, Dictionary<string, List<string>> customHeaders, CancellationToken ignored) => Assert.Equal(ProviderName, providerName, StringComparer.OrdinalIgnoreCase)) .Returns(() => Task.FromResult(new AzureOperationResponse<Provider>() { Body = unregistrationResult })); this.providerOperationsMock .Setup(f => f.GetWithHttpMessagesAsync(It.IsAny<string>(), null, null, It.IsAny<CancellationToken>())) .Returns(() => Task.FromResult(new AzureOperationResponse<Provider>() { Body = provider })); this.cmdlet.ProviderNamespace = ProviderName; // 1. Unregister succeeds this.commandRuntimeMock .Setup(m => m.WriteObject(It.IsAny<object>())) .Callback((object obj) => { Assert.IsType<PSResourceProvider>(obj); var providerResult = (PSResourceProvider)obj; Assert.Equal(ProviderName, providerResult.ProviderNamespace, StringComparer.OrdinalIgnoreCase); }); //unregistrationResult.StatusCode = HttpStatusCode.OK; this.cmdlet.ExecuteCmdlet(); this.VerifyCallPatternAndReset(succeeded: true); // 2. Unregister fails w/ error //unregistrationResult.StatusCode = HttpStatusCode.NotFound; unregistrationResult = null; try { this.cmdlet.ExecuteCmdlet(); Assert.False(true, "The cmdlet succeeded when it should have failed."); } catch (KeyNotFoundException) { this.VerifyCallPatternAndReset(succeeded: false); } } /// <summary> /// Verifies the right call patterns are made /// </summary> private void VerifyCallPatternAndReset(bool succeeded) { this.providerOperationsMock.Verify(f => f.UnregisterWithHttpMessagesAsync(It.IsAny<string>(), null, It.IsAny<CancellationToken>()), Times.Once()); this.commandRuntimeMock.Verify(f => f.WriteObject(It.IsAny<object>()), succeeded ? Times.Once() : Times.Never()); this.providerOperationsMock.ResetCalls(); this.commandRuntimeMock.ResetCalls(); } } }
42.970588
159
0.59822
[ "MIT" ]
FosterMichelle/azure-powershell
src/ResourceManager/Resources/Commands.Resources.Test/Providers/UnregisterResourceProviderCmdletTests.cs
7,138
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Fap.Workflow.Engine.Xpdl { /// <summary> /// 执行活动的可选类型 /// </summary> public class NextActivityMatchedResult { #region 属性和构造函数 internal static string Unkonwn = "未知原因"; internal static string Exceptional = "未能获取下一步节点"; internal static string Successed = "已经成功获取下一步节点"; internal static string NoneTransitionAsBeingFiltered = "并行分支上的条件不满足,无路径可达后续节点"; internal static string NoneWayMatchedToSplit = "该分支上的条件不成立,不能到后续节点"; internal static string WaitingForOthersJoin = "要合并的分支上的条件不是全部成立,无法合并到后续节点"; internal static string NotMadeItselfToJoin = "没有满足条件的路径,无法合并到后续节点"; internal static string NoneTransitionFilteredByCondition = "无法获取下一步节点列表,因为条件表达式未被满足,请查看必填字段是否已经填写!"; public string Message { get; set; } public NextActivityMatchedType MatchedType { get; set; } public NextActivityComponent Root { get; set; } private NextActivityMatchedResult(NextActivityMatchedType matchedType, NextActivityComponent root) { MatchedType = matchedType; Root = root; } #endregion #region 创建方法 /// <summary> /// 创建方法 /// </summary> /// <param name="scheduleStatus"></param> /// <param name="root"></param> /// <returns></returns> internal static NextActivityMatchedResult CreateNextActivityMatchedResultObject(NextActivityMatchedType matchedType, NextActivityComponent root) { NextActivityMatchedResult result = new NextActivityMatchedResult(matchedType, root); switch (matchedType) { case NextActivityMatchedType.Unknown: result.Message = NextActivityMatchedResult.Unkonwn; break; case NextActivityMatchedType.Failed: result.Message = NextActivityMatchedResult.Exceptional; break; case NextActivityMatchedType.Successed: result.Message = NextActivityMatchedResult.Successed; break; case NextActivityMatchedType.NoneTransitionFilteredByCondition: result.Message = NextActivityMatchedResult.NoneTransitionFilteredByCondition; break; case NextActivityMatchedType.WaitingForSplitting: result.Message = NextActivityMatchedResult.NoneTransitionAsBeingFiltered; break; case NextActivityMatchedType.NoneTransitionMatchedToSplit: result.Message = NextActivityMatchedResult.NoneWayMatchedToSplit; break; case NextActivityMatchedType.WaitingForOthersJoin: result.Message = NextActivityMatchedResult.WaitingForOthersJoin; break; case NextActivityMatchedType.NotMadeItselfToJoin: result.Message = NextActivityMatchedResult.NotMadeItselfToJoin; break; } return result; } #endregion } }
36.225806
124
0.606411
[ "Apache-2.0" ]
48355746/FapCore3.0
src/Fap.Workflow/Engine/Xpdl/NextActivityMatchedResult.cs
3,711
C#
using AutoMapper; using MediatR; using Microsoft.Extensions.Logging; using Opdex.Platform.Domain.Models.LiquidityPools; using Opdex.Platform.Infrastructure.Abstractions.Data; using Opdex.Platform.Infrastructure.Abstractions.Data.Commands.LiquidityPools; using Opdex.Platform.Infrastructure.Abstractions.Data.Extensions; using Opdex.Platform.Infrastructure.Abstractions.Data.Models.LiquidityPools; using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace Opdex.Platform.Infrastructure.Data.Handlers.LiquidityPools.Summaries; public class PersistLiquidityPoolSummaryCommandHandler : IRequestHandler<PersistLiquidityPoolSummaryCommand, ulong> { private static readonly string InsertSqlCommand = $@"INSERT INTO pool_liquidity_summary ( {nameof(LiquidityPoolSummaryEntity.LiquidityPoolId)}, {nameof(LiquidityPoolSummaryEntity.LiquidityUsd)}, {nameof(LiquidityPoolSummaryEntity.DailyLiquidityUsdChangePercent)}, {nameof(LiquidityPoolSummaryEntity.VolumeUsd)}, {nameof(LiquidityPoolSummaryEntity.StakingWeight)}, {nameof(LiquidityPoolSummaryEntity.DailyStakingWeightChangePercent)}, {nameof(LiquidityPoolSummaryEntity.LockedCrs)}, {nameof(LiquidityPoolSummaryEntity.LockedSrc)}, {nameof(LiquidityPoolSummaryEntity.CreatedBlock)}, {nameof(LiquidityPoolSummaryEntity.ModifiedBlock)} ) VALUES ( @{nameof(LiquidityPoolSummaryEntity.LiquidityPoolId)}, @{nameof(LiquidityPoolSummaryEntity.LiquidityUsd)}, @{nameof(LiquidityPoolSummaryEntity.DailyLiquidityUsdChangePercent)}, @{nameof(LiquidityPoolSummaryEntity.VolumeUsd)}, @{nameof(LiquidityPoolSummaryEntity.StakingWeight)}, @{nameof(LiquidityPoolSummaryEntity.DailyStakingWeightChangePercent)}, @{nameof(LiquidityPoolSummaryEntity.LockedCrs)}, @{nameof(LiquidityPoolSummaryEntity.LockedSrc)}, @{nameof(LiquidityPoolSummaryEntity.CreatedBlock)}, @{nameof(LiquidityPoolSummaryEntity.ModifiedBlock)} ); SELECT LAST_INSERT_ID();".RemoveExcessWhitespace(); private static readonly string UpdateSqlCommand = $@"UPDATE pool_liquidity_summary SET {nameof(LiquidityPoolSummaryEntity.LiquidityUsd)} = @{nameof(LiquidityPoolSummaryEntity.LiquidityUsd)}, {nameof(LiquidityPoolSummaryEntity.DailyLiquidityUsdChangePercent)} = @{nameof(LiquidityPoolSummaryEntity.DailyLiquidityUsdChangePercent)}, {nameof(LiquidityPoolSummaryEntity.VolumeUsd)} = @{nameof(LiquidityPoolSummaryEntity.VolumeUsd)}, {nameof(LiquidityPoolSummaryEntity.StakingWeight)} = @{nameof(LiquidityPoolSummaryEntity.StakingWeight)}, {nameof(LiquidityPoolSummaryEntity.DailyStakingWeightChangePercent)} = @{nameof(LiquidityPoolSummaryEntity.DailyStakingWeightChangePercent)}, {nameof(LiquidityPoolSummaryEntity.LockedCrs)} = @{nameof(LiquidityPoolSummaryEntity.LockedCrs)}, {nameof(LiquidityPoolSummaryEntity.LockedSrc)} = @{nameof(LiquidityPoolSummaryEntity.LockedSrc)}, {nameof(LiquidityPoolSummaryEntity.ModifiedBlock)} = @{nameof(LiquidityPoolSummaryEntity.ModifiedBlock)} WHERE {nameof(LiquidityPoolSummaryEntity.Id)} = @{nameof(LiquidityPoolSummaryEntity.Id)};" .RemoveExcessWhitespace(); private readonly IDbContext _context; private readonly IMapper _mapper; private readonly ILogger _logger; public PersistLiquidityPoolSummaryCommandHandler(IDbContext context, IMapper mapper, ILogger<PersistLiquidityPoolSummaryCommandHandler> logger) { _context = context ?? throw new ArgumentNullException(nameof(context)); _mapper = mapper ?? throw new ArgumentNullException(nameof(mapper)); _logger = logger ?? throw new ArgumentNullException(nameof(logger)); } public async Task<ulong> Handle(PersistLiquidityPoolSummaryCommand request, CancellationToken cancellationToken) { try { var entity = _mapper.Map<LiquidityPoolSummaryEntity>(request.Summary); var isUpdate = entity.Id >= 1; var sql = isUpdate ? UpdateSqlCommand : InsertSqlCommand; var command = DatabaseQuery.Create(sql, entity, cancellationToken); var result = await _context.ExecuteScalarAsync<ulong>(command); return isUpdate ? entity.Id : result; } catch (Exception ex) { using (_logger.BeginScope(new Dictionary<string, object>() { { "LiquidityPoolId" , request.Summary.LiquidityPoolId}, { "BlockHeight" , request.Summary.ModifiedBlock} })) { _logger.LogError(ex, $"Unable to persist liquidity pool summary."); } return 0; } } }
52.464646
161
0.686369
[ "MIT" ]
Opdex/opdex-v1-api
src/Opdex.Platform.Infrastructure/Data/Handlers/LiquidityPools/Summaries/PersistLiquidityPoolSummaryCommandHandler.cs
5,194
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // using System; struct S { public String str; } class Test { public static void c(S s1) { GC.Collect(); Console.WriteLine(s1.str); GC.Collect(); } public static int Main() { S sM; sM.str = "test"; c(sM); return 100; } }
14.451613
71
0.555804
[ "MIT" ]
2m0nd/runtime
src/tests/JIT/Regression/VS-ia64-JIT/V1.2-M02/b27980/struct1.cs
448
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ES.Activation { class Activator:IActivator { public T Activate<T>() { return System.Activator.CreateInstance<T>(); } public object Activate(Type type) { return System.Activator.CreateInstance(type); } } }
19
57
0.619617
[ "MIT" ]
danryd/es
src/ES/ES/Activation/Activator.cs
420
C#
using System; namespace S2Geometry.S2BuilderUtil { // A SnapFunction that snaps every vertex to itself. It should be used when // vertices do not need to be snapped to a discrete set of locations (such as // E7 lat/lngs), or when maximum accuracy is desired. // // If the given "snap_radius" is zero, then all input vertices are preserved // exactly. Otherwise, S2Builder merges nearby vertices to ensure that no // vertex pair is closer than "snap_radius". Furthermore, vertices are // separated from non-incident edges by at least "min_edge_vertex_separation", // equal to (0.5 * snap_radius). For example, if the snap_radius is 1km, then // vertices will be separated from non-incident edges by at least 500m. public class IdentitySnapFunction : SnapFunction { // The defaultructor uses a snap_radius of zero (i.e., no snapping). public IdentitySnapFunction() { snap_radius_ = S1Angle.Zero; } // Convenience constructor that calls set_snap_radius(). public IdentitySnapFunction(S1Angle snap_radius) { SnapRadius = (snap_radius); } // REQUIRES: snap_radius <= SnapFunction.kMaxSnapRadius() public override S1Angle SnapRadius { get => snap_radius_; set { Assert.True(value <= SnapFunction.kMaxSnapRadius); snap_radius_ = value; } } private S1Angle snap_radius_; // For the identity snap function, all vertex pairs are separated by at // least snap_radius(). public override S1Angle MinVertexSeparation() { // Since SnapFunction does not move the input point, output vertices are // separated by the full snap_radius(). return snap_radius_; } // For the identity snap function, edges are separated from all non-incident // vertices by at least 0.5 * snap_radius(). public override S1Angle MinEdgeVertexSeparation() { // In the worst case configuration, the edge separation is half of the // vertex separation. return 0.5 * snap_radius_; } public override S2Point SnapPoint(S2Point point) { return point; } public override object Clone() { return new IdentitySnapFunction(snap_radius_); } } // A SnapFunction that snaps vertices to S2CellId centers. This can be useful // if you want to encode your geometry compactly using S2Polygon.Encode(), // for example. You can snap to the centers of cells at any level. // // Every snap level has a corresponding minimum snap radius, which is simply // the maximum distance that a vertex can move when snapped. It is // approximately equal to half of the maximum diagonal length for cells at the // chosen level. You can also set the snap radius to a larger value; for // example, you could snap to the centers of leaf cells (1cm resolution) but // set the snap_radius() to 10m. This would result in significant extra // simplification, without moving vertices unnecessarily (i.e., vertices that // are at least 10m away from all other vertices will move by less than 1cm). public class S2CellIdSnapFunction : SnapFunction { // The defaultructor snaps to S2Constants.kMaxCellLevel (i.e., the centers // of leaf cells), and uses the minimum allowable snap radius at that level. public S2CellIdSnapFunction() { Level = (S2Constants.kMaxCellLevel); } // Convenience constructor equivalent to calling set_level(level). public S2CellIdSnapFunction(int level) { Level = (level); } private S2CellIdSnapFunction(int level, S1Angle snap_radius) { Level = level; SnapRadius = snap_radius; } // Snaps vertices to S2Cell centers at the given level. As a side effect, // this method also resets "snap_radius" to the minimum value allowed at // this level: // // set_snap_radius(MinSnapRadiusForLevel(level)) // // This means that if you want to use a larger snap radius than the minimum, // you must call set_snap_radius() *after* calling set_level(). public int Level { get => level_; set { Assert.True(value >= 0); Assert.True(value <= S2Constants.kMaxCellLevel); level_ = value; SnapRadius = (MinSnapRadiusForLevel(value)); } } private int level_; // Defines the snap radius to be used (see s2builder.h). The snap radius // must be at least the minimum value for the current level(), but larger // values can also be used (e.g., to simplify the geometry). // // REQUIRES: snap_radius >= MinSnapRadiusForLevel(level()) // REQUIRES: snap_radius <= SnapFunction.kMaxSnapRadius() public override S1Angle SnapRadius { get => snap_radius_; set { Assert.True(value >= MinSnapRadiusForLevel(Level)); Assert.True(value <= SnapFunction.kMaxSnapRadius); snap_radius_ = value; } } private S1Angle snap_radius_; // Returns the minimum allowable snap radius for the given S2Cell level // (approximately equal to half of the maximum cell diagonal length). public static S1Angle MinSnapRadiusForLevel(int level) { // snap_radius() needs to be an upper bound on the true distance that a // point can move when snapped, taking into account numerical errors. // // The maximum error when converting from an S2Point to an S2CellId is // S2.kMaxDiag.deriv() * S2Constants.DoubleEpsilon. The maximum error when converting an // S2CellId center back to an S2Point is 1.5 * S2Constants.DoubleEpsilon. These add up to // just slightly less than 4 * S2Constants.DoubleEpsilon. return S1Angle.FromRadians(0.5 * S2Metrics.kMaxDiag.GetValue(level) + 4 * S2Constants.DoubleEpsilon); } // Returns the minimum S2Cell level (i.e., largest S2Cells) such that // vertices will not move by more than "snap_radius". This can be useful // when choosing an appropriate level to snap to. The return value is // always a valid level (out of range values are silently clamped). // // If you want to choose the snap level based on a distance, and then use // the minimum possible snap radius for the chosen level, do this: // // S2CellIdSnapFunction f( // S2CellIdSnapFunction.LevelForMaxSnapRadius(distance)); public static int LevelForMaxSnapRadius(S1Angle snap_radius) { // When choosing a level, we need to acount for the error bound of // 4 * S2Constants.DoubleEpsilon that is added by MinSnapRadiusForLevel(). return S2Metrics.kMaxDiag.GetLevelForMaxValue( 2 * (snap_radius.Radians - 4 * S2Constants.DoubleEpsilon)); } // For S2CellId snapping, the minimum separation between vertices depends on // level() and snap_radius(). It can vary between 0.5 * snap_radius() // and snap_radius(). public override S1Angle MinVertexSeparation() { // We have three different bounds for the minimum vertex separation: one is // a constant bound, one is proportional to snap_radius, and one is equal to // snap_radius minus a constant. These bounds give the best results for // small, medium, and large snap radii respectively. We return the maximum // of the three bounds. // // 1. Constant bound: Vertices are always separated by at least // kMinEdge(level), the minimum edge length for the chosen snap level. // // 2. Proportional bound: It can be shown that in the plane, the worst-case // configuration has a vertex separation of 2 / Math.Sqrt(13) * snap_radius. // This is verified in the unit test, except that on the sphere the ratio // is slightly smaller at cell level 2 (0.54849 vs. 0.55470). We reduce // that value a bit more below to be conservative. // // 3. Best asymptotic bound: This bound bound is derived by observing we // only select a new site when it is at least snap_radius() away from all // existing sites, and the site can move by at most 0.5 * kMaxDiag(level) // when snapped. S1Angle min_edge = S1Angle.FromRadians(S2Metrics.kMinEdge.GetValue(level_)); S1Angle max_diag = S1Angle.FromRadians(S2Metrics.kMaxDiag.GetValue(level_)); return S1Angle.Max(min_edge, S1Angle.Max(0.548 * snap_radius_, // 2 / Math.Sqrt(13) in the plane snap_radius_ - 0.5 * max_diag)); } // For S2CellId snapping, the minimum separation between edges and // non-incident vertices depends on level() and snap_radius(). It can // be as low as 0.219 * snap_radius(), but is typically 0.5 * snap_radius() // or more. public override S1Angle MinEdgeVertexSeparation() { // Similar to min_vertex_separation(), in this case we have four bounds: a // constant bound that holds only at the minimum snap radius, a constant // bound that holds for any snap radius, a bound that is proportional to // snap_radius, and a bound that is equal to snap_radius minus a constant. // // 1. Constant bounds: // // (a) At the minimum snap radius for a given level, it can be shown that // vertices are separated from edges by at least 0.5 * kMinDiag(level) in // the plane. The unit test verifies this, except that on the sphere the // worst case is slightly better: 0.5652980068 * kMinDiag(level). // // (b) Otherwise, for arbitrary snap radii the worst-case configuration // in the plane has an edge-vertex separation of Math.Sqrt(3/19) * // kMinDiag(level), where Math.Sqrt(3/19) is about 0.3973597071. The unit // test verifies that the bound is slighty better on the sphere: // 0.3973595687 * kMinDiag(level). // // 2. Proportional bound: In the plane, the worst-case configuration has an // edge-vertex separation of 2 * Math.Sqrt(3/247) * snap_radius, which is // about 0.2204155075. The unit test verifies this, except that on the // sphere the bound is slightly worse for certain large S2Cells: the // minimum ratio occurs at cell level 6, and is about 0.2196666953. // // 3. Best asymptotic bound: If snap_radius() is large compared to the // minimum snap radius, then the best bound is achieved by 3 sites on a // circular arc of radius "snap_radius", spaced "min_vertex_separation" // apart. An input edge passing just to one side of the center of the // circle intersects the Voronoi regions of the two end sites but not the // Voronoi region of the center site, and gives an edge separation of // (min_vertex_separation ** 2) / (2 * snap_radius). This bound // approaches 0.5 * snap_radius for large snap radii, i.e. the minimum // edge-vertex separation approaches half of the minimum vertex // separation as the snap radius becomes large compared to the cell size. S1Angle min_diag = S1Angle.FromRadians(S2Metrics.kMinDiag.GetValue(level_)); if (SnapRadius== MinSnapRadiusForLevel(level_)) { // This bound only holds when the minimum snap radius is being used. return 0.565 * min_diag; // 0.500 in the plane } // Otherwise, these bounds hold for any snap_radius(). S1Angle vertex_sep = MinVertexSeparation(); return S1Angle.Max(0.397 * min_diag, // Math.Sqrt(3 / 19) in the plane S1Angle.Max(0.219 * snap_radius_, // 2 * Math.Sqrt(3 / 247) in the plane 0.5 * (vertex_sep / snap_radius_) * vertex_sep)); } public override S2Point SnapPoint(S2Point point) { return new S2CellId(point).Parent(level_).ToPoint(); } public override object Clone() { return new S2CellIdSnapFunction(level_, snap_radius_); } } // A SnapFunction that snaps vertices to S2LatLng E5, E6, or E7 coordinates. // These coordinates are expressed in degrees multiplied by a power of 10 and // then rounded to the nearest integer. For example, in E6 coordinates the // point (23.12345651, -45.65432149) would become (23123457, -45654321). // // The main argument of the SnapFunction is the exponent for the power of 10 // that coordinates should be multipled by before rounding. For example, // IntLatLngSnapFunction(7) is a function that snaps to E7 coordinates. The // exponent can range from 0 to 10. // // Each exponent has a corresponding minimum snap radius, which is simply the // maximum distance that a vertex can move when snapped. It is approximately // equal to 1/Math.Sqrt(2) times the nominal point spacing; for example, for // snapping to E7 the minimum snap radius is (1e-7 / Math.Sqrt(2)) degrees. // You can also set the snap radius to any value larger than this; this can // result in significant extra simplification (similar to using a larger // exponent) but does not move vertices unnecessarily. public class IntLatLngSnapFunction : SnapFunction { #pragma warning disable IDE1006 // Estilos de nombres // The minum exponent supported for snapping. public const int kMinExponent = 0; // The maximum exponent supported for snapping. public const int kMaxExponent = 10; #pragma warning restore IDE1006 // Estilos de nombres // The defaultructor yields an invalid snap function. You must set // the exponent explicitly before using it. public IntLatLngSnapFunction() { Exponent = -1; snap_radius_ = S1Angle.Zero; from_degrees_ = 0; to_degrees_ = 0; } // Convenience constructor equivalent to calling set_exponent(exponent). public IntLatLngSnapFunction(int exponent) { Exponent = exponent; } private IntLatLngSnapFunction(IntLatLngSnapFunction sf) { Exponent = sf.Exponent; snap_radius_ = sf.snap_radius_; from_degrees_ = sf.from_degrees_; to_degrees_ = sf.to_degrees_; } // Snaps vertices to points whose (lat, lng) coordinates are integers after // converting to degrees and multiplying by 10 raised to the given exponent. // For example, (exponent == 7) yields E7 coordinates. As a side effect, // this method also resets "snap_radius" to the minimum value allowed for // this exponent: // // set_snap_radius(MinSnapRadiusForExponent(exponent)) // // This means that if you want to use a larger snap radius than the minimum, // you must call set_snap_radius() *after* calling set_exponent(). // // REQUIRES: kMinExponent <= exponent <= kMaxExponent public int Exponent { get => _exponent; set { Assert.True(value >= kMinExponent); Assert.True(value <= kMaxExponent); _exponent = value; SnapRadius = (MinSnapRadiusForExponent(value)); // Precompute the scale factors needed for snapping. Note that these // calculations need to exactly match the ones in s1angle.h to ensure // that the same S2Points are generated. double power = 1; for (int i = 0; i < value; ++i) power *= 10; from_degrees_ = power; to_degrees_ = 1 / power; } } private int _exponent; // Defines the snap radius to be used (see s2builder.h). The snap radius // must be at least the minimum value for the current exponent(), but larger // values can also be used (e.g., to simplify the geometry). // // REQUIRES: snap_radius >= MinSnapRadiusForExponent(exponent()) // REQUIRES: snap_radius <= SnapFunction.kMaxSnapRadius() public override S1Angle SnapRadius { get => snap_radius_; set { Assert.True(value >= MinSnapRadiusForExponent(Exponent)); Assert.True(value <= SnapFunction.kMaxSnapRadius); snap_radius_ = value; } } private S1Angle snap_radius_; // Returns the minimum allowable snap radius for the given exponent // (approximately equal to (Math.Pow(10, -exponent) / Math.Sqrt(2)) degrees). public static S1Angle MinSnapRadiusForExponent(int exponent) { // snap_radius() needs to be an upper bound on the true distance that a // point can move when snapped, taking into account numerical errors. // // The maximum errors in latitude and longitude can be bounded as // follows (as absolute errors in terms of S2Constants.DoubleEpsilon): // // Latitude Longitude // Convert to S2LatLng: 1.000 1.000 // Convert to degrees: 1.032 2.063 // Scale by 10**exp: 0.786 1.571 // Round to integer: 0.5 * S1Angle.Degrees(to_degrees_) // Scale by 10**(-exp): 1.375 2.749 // Convert to radians: 1.252 1.503 // ------------------------------------------------------------ // Total (except for rounding) 5.445 8.886 // // The maximum error when converting the S2LatLng back to an S2Point is // // Math.Sqrt(2) * (maximum error in latitude or longitude) + 1.5 * S2Constants.DoubleEpsilon // // which works out to (9 * Math.Sqrt(2) + 1.5) * S2Constants.DoubleEpsilon radians. Finally // we need to consider the effect of rounding to integer coordinates // (much larger than the errors above), which can change the position by // up to (Math.Sqrt(2) * 0.5 * to_degrees_) radians. double power = 1; for (int i = 0; i < exponent; ++i) power *= 10; return (S1Angle.FromDegrees(S2Constants.M_SQRT1_2 / power) + S1Angle.FromRadians((9 * S2Constants.M_SQRT2 + 1.5) * S2Constants.DoubleEpsilon)); } // Returns the minimum exponent such that vertices will not move by more // than "snap_radius". This can be useful when choosing an appropriate // exponent for snapping. The return value is always a valid exponent // (out of range values are silently clamped). // // If you want to choose the exponent based on a distance, and then use // the minimum possible snap radius for that exponent, do this: // // IntLatLngSnapFunction f( // IntLatLngSnapFunction.ExponentForMaxSnapRadius(distance)); public static int ExponentForMaxSnapRadius(S1Angle snap_radius) { // When choosing an exponent, we need to acount for the error bound of // (9 * Math.Sqrt(2) + 1.5) * S2Constants.DoubleEpsilon added by MinSnapRadiusForExponent(). snap_radius -= S1Angle.FromRadians((9 * S2Constants.M_SQRT2 + 1.5) * S2Constants.DoubleEpsilon); snap_radius = S1Angle.Max(snap_radius, S1Angle.FromRadians(1e-30)); double exponent = Math.Log10(S2Constants.M_SQRT1_2 / snap_radius.Degrees); // There can be small errors in the calculation above, so to ensure that // this function is the inverse of MinSnapRadiusForExponent() we subtract a // small error tolerance. return Math.Max(kMinExponent, Math.Min(kMaxExponent, (int)(Math.Ceiling(exponent - 2 * S2Constants.DoubleEpsilon)))); } // For IntLatLng snapping, the minimum separation between vertices depends on // exponent() and snap_radius(). It can vary between snap_radius() // and snap_radius(). public override S1Angle MinVertexSeparation() { // We have two bounds for the minimum vertex separation: one is proportional // to snap_radius, and one is equal to snap_radius minus a constant. These // bounds give the best results for small and large snap radii respectively. // We return the maximum of the two bounds. // // 1. Proportional bound: It can be shown that in the plane, the worst-case // configuration has a vertex separation of (Math.Sqrt(2) / 3) * snap_radius. // This is verified in the unit test, except that on the sphere the ratio // is slightly smaller (0.471337 vs. 0.471404). We reduce that value a // bit more below to be conservative. // // 2. Best asymptotic bound: This bound bound is derived by observing we // only select a new site when it is at least snap_radius() away from all // existing sites, and snapping a vertex can move it by up to // ((1 / Math.Sqrt(2)) * to_degrees_) degrees. return S1Angle.Max(0.471 * snap_radius_, // Math.Sqrt(2) / 3 in the plane snap_radius_ - S1Angle.FromDegrees(S2Constants.M_SQRT1_2 * to_degrees_)); } // For IntLatLng snapping, the minimum separation between edges and // non-incident vertices depends on level() and snap_radius(). It can // be as low as 0.222 * snap_radius(), but is typically 0.39 * snap_radius() // or more. public override S1Angle MinEdgeVertexSeparation() { // Similar to min_vertex_separation(), in this case we have three bounds: // one is a constant bound, one is proportional to snap_radius, and one is // equal to snap_radius minus a constant. // // 1. Constant bound: In the plane, the worst-case configuration has an // edge-vertex separation of ((1 / Math.Sqrt(13)) * to_degrees_) degrees. // The unit test verifies this, except that on the sphere the ratio is // slightly lower when small exponents such as E1 are used // (0.2772589 vs 0.2773501). // // 2. Proportional bound: In the plane, the worst-case configuration has an // edge-vertex separation of (2 / 9) * snap_radius (0.222222222222). The // unit test verifies this, except that on the sphere the bound can be // slightly worse with large exponents (e.g., E9) due to small numerical // errors (0.222222126756717). // // 3. Best asymptotic bound: If snap_radius() is large compared to the // minimum snap radius, then the best bound is achieved by 3 sites on a // circular arc of radius "snap_radius", spaced "min_vertex_separation" // apart (see S2CellIdSnapFunction.min_edge_vertex_separation). This // bound approaches 0.5 * snap_radius as the snap radius becomes large // relative to the grid spacing. S1Angle vertex_sep = MinVertexSeparation(); return S1Angle.Max(0.277 * S1Angle.FromDegrees(to_degrees_), // 1/Math.Sqrt(13) in the plane S1Angle.Max(0.222 * snap_radius_, // 2/9 in the plane 0.5 * (vertex_sep / snap_radius_) * vertex_sep)); } public override S2Point SnapPoint(S2Point point) { Assert.True(Exponent >= 0); // Make sure the snap function was initialized. var input = new S2LatLng(point); var lat = Math.Round(input.LatDegrees * from_degrees_); var lng = Math.Round(input.LngDegrees * from_degrees_); return S2LatLng.FromDegrees(lat * to_degrees_, lng * to_degrees_).ToPoint(); } public override object Clone() { return new IntLatLngSnapFunction(this); } private double from_degrees_, to_degrees_; } // A SnapFunction restricts the locations of the output vertices. For // example, there are predefined snap functions that require vertices to be // located at S2CellId centers or at E5/E6/E7 coordinates. The SnapFunction // can also specify a minimum spacing between vertices (the "snap radius"). // // A SnapFunction defines the following methods: // // 1. The SnapPoint() method, which snaps a point P to a nearby point (the // "candidate snap site"). Any point may be returned, including P // itself (this is the "identity snap function"). // // 2. "snap_radius", the maximum distance that vertices can move when // snapped. The snap_radius must be at least as large as the maximum // distance between P and SnapPoint(P) for any point P. // // 3. "max_edge_deviation", the maximum distance that edges can move when // snapped. It is slightly larger than "snap_radius" because when a // geodesic edge is snapped, the center of the edge moves further than // its endpoints. This value is computed automatically by S2Builder. // // 4. "min_vertex_separation", the guaranteed minimum distance between // vertices in the output. This is generally a fraction of // "snap_radius" where the fraction depends on the snap function. // // 5. A "min_edge_vertex_separation", the guaranteed minimum distance // between edges and non-incident vertices in the output. This is // generally a fraction of "snap_radius" where the fraction depends on // the snap function. // // It is important to note that SnapPoint() does not define the actual // mapping from input vertices to output vertices, since the points it // returns (the candidate snap sites) are further filtered to ensure that // they are separated by at least the snap radius. For example, if you // specify E7 coordinates (2cm resolution) and a snap radius of 10m, then a // subset of points returned by SnapPoint will be chosen (the "snap sites"), // and each input vertex will be mapped to the closest site. Therefore you // cannot assume that P is necessarily snapped to SnapPoint(P). // // S2Builder makes the following guarantees: // // 1. Every vertex is at a location returned by SnapPoint(). // // 2. Vertices are within "snap_radius" of the corresponding input vertex. // // 3. Edges are within "max_edge_deviation" of the corresponding input edge // (a distance slightly larger than "snap_radius"). // // 4. Vertices are separated by at least "min_vertex_separation" // (a fraction of "snap_radius" that depends on the snap function). // // 5. Edges and non-incident vertices are separated by at least // "min_edge_vertex_separation" (a fraction of "snap_radius"). // // 6. Vertex and edge locations do not change unless one of the conditions // above is not already met (idempotency / stability). // // 7. The topology of the input geometry is preserved (up to the creation // of degeneracies). This means that there exists a continuous // deformation from the input to the output such that no vertex // crosses an edge. public abstract class SnapFunction : ICloneable { // The maximum supported snap radius (equivalent to about 7800km). // // The maximum snap radius is just large enough to support snapping to // S2CellId level 0. It is equivalent to 7800km on the Earth's surface. // // This value can't be larger than 85.7 degrees without changing the code // related to min_edge_length_to_split_ca_, and increasing it to 90 degrees // or more would most likely require significant changes to the algorithm. #pragma warning disable IDE1006 // Estilos de nombres public static readonly S1Angle kMaxSnapRadius = S1Angle.FromDegrees(70); #pragma warning restore IDE1006 // Estilos de nombres // The maximum distance that vertices can move when snapped. // // If the snap radius is zero, then vertices are snapped together only if // they are identical. Edges will not be snapped to any vertices other // than their endpoints, even if there are vertices whose distance to the // edge is zero, unless split_crossing_edges() is true. // // REQUIRES: snap_radius() <= SnapFunction.kMaxSnapRadius public abstract S1Angle SnapRadius { get; set; } // The maximum distance that the center of an edge can move when snapped. // This is slightly larger than "snap_radius" because when a geodesic edge // is snapped, the center of the edge moves further than its endpoints. public S1Angle MaxEdgeDeviation() { // We want max_edge_deviation() to be large enough compared to snap_radius() // such that edge splitting is rare. // // Using spherical trigonometry, if the endpoints of an edge of length L // move by at most a distance R, the center of the edge moves by at most // asin(sin(R) / cos(L / 2)). Thus the (max_edge_deviation / snap_radius) // ratio increases with both the snap radius R and the edge length L. // // We arbitrarily limit the edge deviation to be at most 10% more than the // snap radius. With the maximum allowed snap radius of 70 degrees, this // means that edges up to 30.6 degrees long are never split. For smaller // snap radii, edges up to 49 degrees long are never split. (Edges of any // length are not split unless their endpoints move far enough so that the // actual edge deviation exceeds the limit; in practice, splitting is rare // even with long edges.) Note that it is always possible to split edges // when max_edge_deviation() is exceeded; see MaybeAddExtraSites(). Assert.True(SnapRadius<= kMaxSnapRadius); double kMaxEdgeDeviationRatio = 1.1; return kMaxEdgeDeviationRatio * SnapRadius; } // The guaranteed minimum distance between vertices in the output. // This is generally some fraction of "snap_radius". public abstract S1Angle MinVertexSeparation(); // The guaranteed minimum spacing between edges and non-incident vertices // in the output. This is generally some fraction of "snap_radius". public abstract S1Angle MinEdgeVertexSeparation(); // Returns a candidate snap site for the given point. The final vertex // locations are a subset of the snap sites returned by this function // (spaced at least "min_vertex_separation" apart). // // The only requirement is that SnapPoint(x) must return a point whose // distance from "x" is no greater than "snap_radius". public abstract S2Point SnapPoint(S2Point point); // Returns a deep copy of this SnapFunction. public abstract object Clone(); } }
52.180511
113
0.619042
[ "Apache-2.0" ]
alas/s2geometry
S2Geometry/S2BuilderUtil/SnapFunctions.cs
32,665
C#
#region Copyright /* This file came from Managed Media Aggregation, You can always find the latest version @ https://net7mma.codeplex.com/ Julius.Friedman@gmail.com / (SR. Software Engineer ASTI Transportation Inc. http://www.asti-trans.com) 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: * * * JuliusFriedman@gmail.com should be contacted for further details. 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. * * v// */ #endregion namespace Media.Common.Extensions.IPEndPoint { public static class IPEndPointExtensions { public const char PortSeperator = ':'; public const string SchemeSeperator = "://"; public static readonly System.Net.IPEndPoint Any = new System.Net.IPEndPoint(System.Net.IPAddress.Any, 0); public static readonly System.Net.IPEndPoint IPv6Any = new System.Net.IPEndPoint(System.Net.IPAddress.IPv6Any, 0); public static bool IsMulticast(this System.Net.IPEndPoint endPoint) { return Common.Extensions.IPAddress.IPAddressExtensions.IsMulticast(endPoint.Address); } public static System.Uri ToUri(this System.Net.IPEndPoint endPoint, string scheme = null) { if (endPoint == null) throw new System.ArgumentNullException(); return new System.Uri(string.IsNullOrWhiteSpace(scheme) ? endPoint.ToString() : string.Join(SchemeSeperator, scheme, endPoint.ToString())); } public static System.Net.IPEndPoint Parse(string text) { if (string.IsNullOrWhiteSpace(text)) throw new System.ArgumentNullException(); string[] parts = text.Split(PortSeperator); if (parts.Length > 1) { return new System.Net.IPEndPoint(System.Net.IPAddress.Parse(parts[0]), int.Parse(parts[1])); } return new System.Net.IPEndPoint(System.Net.IPAddress.Parse(parts[0]), 0); } public static bool TryParse(string text, out System.Net.IPEndPoint result) { try { result = Parse(text); return true; } catch { result = null; return false; } } } }
35.846154
165
0.664623
[ "Apache-2.0" ]
Sergey-Terekhin/net7mma
Common/Extensions/IPEndPointExtensions.cs
3,264
C#
// <copyright file="PrivateMessageList.cs" company="Drastic Actions"> // Copyright (c) Drastic Actions. All rights reserved. // </copyright> using System; using System.Collections.Generic; namespace Awful.Core.Entities.Messages { /// <summary> /// Private Message List. /// </summary> public class PrivateMessageList : SAItem { /// <summary> /// Initializes a new instance of the <see cref="PrivateMessageList"/> class. /// </summary> /// <param name="list">List of <see cref="PrivateMessage"/>.</param> public PrivateMessageList(List<PrivateMessage> list) { this.PrivateMessages = list; } /// <summary> /// Gets a list of private messages. /// </summary> public List<PrivateMessage> PrivateMessages { get; internal set; } } }
28.5
85
0.612865
[ "MIT" ]
AlanGraham/Awful.NET
Awful.Core/Entities/Messages/PrivateMessageList.cs
857
C#
using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; namespace TravelRecords.iOS { public class Application { // This is the main entry point of the application. static void Main(string[] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. UIApplication.Main(args, null, "AppDelegate"); } } }
23.095238
91
0.635052
[ "Apache-2.0" ]
ccruz182/Xamarin
TravelRecords/TravelRecords/TravelRecords.iOS/Main.cs
487
C#
// // Copyright (c) 2008-2011, Kenneth Bell // // 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. // namespace DiscUtils.Iso9660Ps1 { internal sealed class PaddingSystemUseEntry : SystemUseEntry { public PaddingSystemUseEntry(string name, byte length, byte version) { CheckAndSetCommonProperties(name, length, version, 4, 1); } } }
43.8125
78
0.742511
[ "MIT" ]
KuromeSan/chovy-sign
CHOVY-SIGN/DiscUtils/Iso9660Ps1/Susp/PaddingSystemUseEntry.cs
1,404
C#
using System; using System.Collections.Generic; using System.Text; namespace InheritanceMammalCatHuman { /*add the modifier so that this class won't be instantiated*/ abstract class Mammal { public bool hasFur = true; public int numLegs { get; set; } public int avgHeartRate { get; set; } public String breathsWith = "lungs"; //default constructor public Mammal() { } //parameterized override constructor public Mammal(bool hasFur, int numLegs, int avgHeartRate, string breathsWith) { this.hasFur = hasFur; this.numLegs = numLegs; this.avgHeartRate = avgHeartRate; this.breathsWith = breathsWith; } public abstract String Says(); public int GetAvgHeartRate() { /*how many beats per minute?*/ return avgHeartRate; } } }
22.697674
85
0.566598
[ "MIT" ]
2002-feb24-net/jacob-code
Week1/Inheritance/Mammal.cs
978
C#
using System; using System.Collections.Generic; using Elasticsearch.Net; using Nest; using Tests.Framework; using Tests.Framework.Integration; using Tests.Framework.ManagedElasticsearch.Clusters; using Xunit; namespace Tests.Indices.IndexSettings.IndexTemplates.PutIndexTemplate { public class PutIndexTemplateApiTests : ApiTestBase<WritableCluster, IPutIndexTemplateResponse, IPutIndexTemplateRequest, PutIndexTemplateDescriptor, PutIndexTemplateRequest> { public PutIndexTemplateApiTests(WritableCluster cluster, EndpointUsage usage) : base(cluster, usage) { } protected override LazyResponses ClientUsage() => Calls( fluent: (client, f) => client.PutIndexTemplate(CallIsolatedValue, f), fluentAsync: (client, f) => client.PutIndexTemplateAsync(CallIsolatedValue, f), request: (client, r) => client.PutIndexTemplate(r), requestAsync: (client, r) => client.PutIndexTemplateAsync(r) ); protected override HttpMethod HttpMethod => HttpMethod.PUT; protected override string UrlPath => $"/_template/{CallIsolatedValue}?create=false"; protected override bool SupportsDeserialization => false; protected override object ExpectJson { get; } = new { order = 1, template = "nestx-*", settings = new Dictionary<string, object> { { "index.number_of_shards", 1 } }, mappings = new { _default_ = new { dynamic_templates = new object[] { new { @base = new { match = "*", match_mapping_type = "*", mapping = new { index = "no" } } } } } } }; protected override PutIndexTemplateDescriptor NewDescriptor() => new PutIndexTemplateDescriptor(CallIsolatedValue); protected override Func<PutIndexTemplateDescriptor, IPutIndexTemplateRequest> Fluent => d => d .Order(1) .Template("nestx-*") .Create(false) .Settings(p=>p.NumberOfShards(1)) .Mappings(m => m .Map("_default_", tm => tm .DynamicTemplates(t => t .DynamicTemplate("base", dt => dt .Match("*") .MatchMappingType("*") .Mapping(mm => mm .Generic(g => g .Index(FieldIndexOption.No) ) ) ) ) ) ); protected override PutIndexTemplateRequest Initializer => new PutIndexTemplateRequest(CallIsolatedValue) { Order = 1, Template = "nestx-*", Create = false, Settings = new Nest.IndexSettings { NumberOfShards = 1 }, Mappings = new Mappings { { "_default_", new TypeMapping { DynamicTemplates = new DynamicTemplateContainer { { "base", new DynamicTemplate { Match = "*", MatchMappingType = "*", Mapping = new GenericProperty { Index = FieldIndexOption.No } } } } } } } }; } }
24.791304
138
0.638022
[ "Apache-2.0" ]
BedeGaming/elasticsearch-net
src/Tests/Indices/IndexSettings/IndexTemplates/PutIndexTemplate/PutIndexTemplateApiTests.cs
2,853
C#
using Mirai_CSharp.Models; using System; using System.Threading.Tasks; #pragma warning disable CA1031 // Do not catch general exception types namespace Mirai_CSharp.Example { public partial class ExamplePlugin { public async Task<bool> Disconnected(MiraiHttpSession session, IDisconnectedEventArgs e) { // e.Exception: 引发掉线的响应异常, 按需处理 MiraiHttpSessionOptions options = new MiraiHttpSessionOptions("127.0.0.1", 33111, "8d726307dd7b468d8550a95f236444f7"); while (true) { try { await session.ConnectAsync(options, 0); // 连到成功为止, QQ号自填, 你也可以另行处理重连的 behaviour return true; } catch (Exception) { await Task.Delay(1000); } } } } }
30.275862
130
0.559226
[ "MIT" ]
PoH98/QQBotXClashOfClans
Mirai-CSharp-release-1.0.2.2/Mirai-CSharp.Example/ExamplePlugin.Disconnected.cs
946
C#
using System; using NUnit.Framework; namespace PostalCodes.UnitTests.Generated { [TestFixture] internal class TWPostalCodeTests { [TestCase("11234","11233")] [TestCase("82888","82887")] [TestCase("00001","00000")] public void Predecessor_ValidInput_ReturnsCorrectPostalCode(string postalCode, string postalCodePredecessor) { var code = new TWPostalCode(postalCode); var codePredecessor = new TWPostalCode(postalCodePredecessor); Assert.AreEqual(codePredecessor, code.Predecessor); Assert.AreEqual(codePredecessor.ToString(), code.Predecessor.ToString()); Assert.AreEqual(codePredecessor.ToHumanReadableString(), code.Predecessor.ToHumanReadableString()); } [TestCase("14234","14235")] [TestCase("44852","44853")] [TestCase("99998","99999")] public void Successor_ValidInput_ReturnsCorrectPostalCode(string postalCode, string postalCodeSuccessor) { var code = new TWPostalCode(postalCode); var codeSuccessor = new TWPostalCode(postalCodeSuccessor); Assert.AreEqual(codeSuccessor, code.Successor); Assert.AreEqual(codeSuccessor.ToString(), code.Successor.ToString()); Assert.AreEqual(codeSuccessor.ToHumanReadableString(), code.Successor.ToHumanReadableString()); } [TestCase("00000")] public void Predecessor_FirstInRange_ReturnsNull(string postalCode) { Assert.IsNull((new TWPostalCode(postalCode)).Predecessor); } [TestCase("99999")] public void Successor_LastInRange_ReturnsNull(string postalCode) { Assert.IsNull((new TWPostalCode(postalCode)).Successor); } [TestCase("122345")] [TestCase("1223s")] [TestCase("x12u3")] public void InvalidCode_ThrowsArgumentException(string postalCode) { Assert.Throws<ArgumentException>(() => new TWPostalCode(postalCode)); } public void CompareTo_ReturnsExpectedSign(string postalCodeBefore, string postalCodeAfter) { var b = new TWPostalCode(postalCodeBefore); var a = new TWPostalCode(postalCodeAfter); Assert.AreEqual(Math.Sign(-1), Math.Sign(b.CompareTo(a))); Assert.AreEqual(Math.Sign( 1), Math.Sign(a.CompareTo(b))); } [TestCase("12234")] [TestCase("52678")] public void Equals_WithNull_DoesntThrowAndReturnsFalse(string code) { var x = (new TWPostalCode(code)).Predecessor; bool result = true; TestDelegate equals = () => result = x.Equals(null); Assert.DoesNotThrow(equals); Assert.IsFalse(result); } [TestCase("12234")] [TestCase("52678")] public void Equals_WithOtherObject_DoesntThrowAndReturnsFalse(string code) { var x = (new TWPostalCode(code)).Predecessor; bool result = true; TestDelegate equals = () => result = x.Equals(new object()); Assert.DoesNotThrow(equals); Assert.IsFalse(result); } [TestCase("12234")] [TestCase("52678")] public void Predecessor_ValidInput_ReturnsCorrectPostalCodeObject(string code) { var x = (new TWPostalCode(code)).Predecessor; Assert.IsTrue(x.GetType() == typeof(TWPostalCode)); } [TestCase("12234")] [TestCase("52678")] public void Successor_ValidInput_ReturnsCorrectPostalCodeObject(string code) { var x = (new TWPostalCode(code)).Successor; Assert.IsTrue(x.GetType() == typeof(TWPostalCode)); } [TestCase("12234")] [TestCase("52678")] public void ExpandPostalCodeAsHighestInRange_ValidInput_ReturnsCorrectPostalCodeObject(string code) { var x = (new TWPostalCode(code)).ExpandPostalCodeAsHighestInRange(); Assert.IsTrue(x.GetType() == typeof(TWPostalCode)); } [TestCase("12234")] [TestCase("52678")] public void ExpandPostalCodeAsLowestInRange_ValidInput_ReturnsCorrectPostalCodeObject(string code) { var x = (new TWPostalCode(code)).ExpandPostalCodeAsLowestInRange(); Assert.IsTrue(x.GetType() == typeof(TWPostalCode)); } [TestCase("12234")] [TestCase("52678")] public void GetHashCode_WithEqualObject_EqualHashes(string code) { var x = new TWPostalCode(code); var y = new TWPostalCode(code); Assert.IsTrue(x.GetHashCode() == y.GetHashCode()); } [TestCase("12234")] [TestCase("52678")] public void AreAdjacent_WithAdjacentPostalCodes_ReturnsTrue(string code) { var x = new TWPostalCode(code); var xPred = x.Predecessor; var xSucc = x.Successor; Assert.IsTrue(PostalCode.AreAdjacent(x, xPred)); Assert.IsTrue(PostalCode.AreAdjacent(xPred, x)); Assert.IsTrue(PostalCode.AreAdjacent(x, xSucc)); Assert.IsTrue(PostalCode.AreAdjacent(xSucc, x)); Assert.IsFalse(PostalCode.AreAdjacent(xPred, xSucc)); } [TestCase("12234")] [TestCase("52678")] public void CreateThroughFactoryIsSuccessful(string code) { var country = CountryFactory.Instance.CreateCountry("TW"); var x = PostalCodeFactory.Instance.CreatePostalCode(country, code); Assert.IsTrue(x.GetType() == typeof(TWPostalCode)); } } }
39.756757
117
0.598572
[ "Apache-2.0" ]
twiho2/PostalCodes.Net
src/PostalCodes.UnitTests/Generated/TWPostalCodeTests.gen.cs
5,737
C#
using System; using System.Collections.Generic; using Context = VM.Interpreter.Context; namespace VM { public class Tracer : IDebugger { private readonly Bytecode _bytecode; public Tracer() { _bytecode = new Bytecode(); } public Context BeforeInstruction(Context ctx) { var opcode = ctx.Code[ctx.IP]; Console.Error.Write("{0:0000}: {1,-10} {2}\t\t", ctx.IP, _bytecode.FindNameByOpcode(opcode), String.Join(", ", buildArgsList(ctx, _bytecode.GetNumArgs(opcode)))); return ctx; } public Context AfterInstruction(Context ctx) { Console.Error.Write("[SP: {0}] \t", ctx.SP); Console.Error.Write("| Stack: {0}", String.Join(", ", buildStackTrace(ctx).ToArray())); Console.Error.Write("\n"); return ctx; } private List<int> buildArgsList(Context ctx, int numArgs) { var args = new List<int>(); for (int i = ctx.IP+1; i <= ctx.IP + numArgs; i++) { args.Add(ctx.Code[i]); } return args; } private List<int> buildStackTrace(Context ctx) { var stackTrace = new List<int>(); if (ctx.SP < 0) { return stackTrace; } for (int i = 0; i <= ctx.SP; i++) { stackTrace.Add(ctx.Stack[i]); } return stackTrace; } } }
25.080645
174
0.490675
[ "MIT" ]
dragonquest/stack-based-vm-csharp
src/VM/Tracer.cs
1,555
C#
using System.Collections.Generic; using UnicornHack.Generation; using UnicornHack.Generation.Effects; using UnicornHack.Primitives; namespace UnicornHack.Data.Items { public static partial class ItemData { public static readonly Item Shortbow = new Item { Name = "shortbow", Abilities = new HashSet<Ability> { new Ability { Activation = ActivationType.OnRangedAttack, Trigger = ActivationType.OnRangedAttack, Range = 20, Action = AbilityAction.Shoot, SuccessCondition = AbilitySuccessCondition.NormalAttack, Accuracy = "10+RequirementsModifier()", Delay = "100*RequirementsModifier()", Effects = new List<Effect> { new PhysicalDamage {Damage = "30*RequirementsModifier()"}, new Activate {Projectile = "arrow"} } } }, Type = ItemType.WeaponRangedLong, Material = Material.Wood, Weight = 5, EquipableSizes = SizeCategory.Small | SizeCategory.Medium, EquipableSlots = EquipmentSlot.GraspRanged, RequiredMight = 5, RequiredPerception = 5, RequiredSpeed = 10 }; } }
34.238095
82
0.52573
[ "Apache-2.0" ]
AndriySvyryd/UnicornHack
src/UnicornHack.Core/Data/Items/ShortBow.cs
1,438
C#
using CleanCoder; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeFixes; using NUnit.Framework; using RoslynTestKit; namespace CsharpMacros.Test.General { public class GeneralTest : CodeFixTestFixture { [Test] public void should_be_able_to_add_single_filter() { TestCodeFixAtLine(TestCases._001_WithSingleFilter, TestCases._001_WithSIngleFilter_FIXED, MacroCodeAnalyzer.Rule, 21); } [Test] public void should_be_able_to_add_multiple_filters() { TestCodeFixAtLine(TestCases._002_WithMultipleFilters, TestCases._002_WIthMultipleFIlters_FIXED, MacroCodeAnalyzer.Rule, 21); } [Test] public void should_be_able_to_execute_macro_below_the_comment() { TestCodeFixAtLine(TestCases._003_CommentAboveTheMacro, TestCases._003_CommentAboveTheMacro_FIXED, MacroCodeAnalyzer.Rule, 22); } [Test] public void should_be_able_to_execute_macro_when_is_single_expression_in_method() { TestCodeFixAtLine(TestCases._004_WhenMacroIsSingleExpressionInMethod, TestCases._004_WhenMacroIsSingleExpressionInMethod_FIXED, MacroCodeAnalyzer.Rule, 14); } [Test] public void should_be_able_to_execute_macro_when_is_first_expression_in_method() { TestCodeFixAtLine(TestCases._005_WhenMacroIsFirstExpressionInMethod, TestCases._005_WhenMacroIsFirstExpressionInMethod_FIXED, MacroCodeAnalyzer.Rule, 14); } [Test] public void should_be_able_to_execute_macro_when_is_last_expression_in_method() { TestCodeFixAtLine(TestCases._006_WhenMacroIsLastExpressionInMethod, TestCases._006_WhenMacroIsLastExpressionInMethod_FIXED, MacroCodeAnalyzer.Rule, 15); } [Test] public void should_be_able_to_execute_macro_inside_if() { TestCodeFixAtLine(TestCases._007_WhenMacroIsInsideIf_, TestCases._007_WhenMacroIsInsideIf_FIXED, MacroCodeAnalyzer.Rule, 16); } [Test] public void should_be_able_to_execute_macro_inside_if_without_bracket() { TestCodeFixAtLine(TestCases._008_WhenMacroIsInsideIfWithoutBracket, TestCases._008_WhenMacroIsInsideIfWithoutBracket_FIXED, MacroCodeAnalyzer.Rule, 15); } [Test] public void should_be_able_to_execute_macro_outside_method() { TestCodeFixAtLine(TestCases._009_WhenMacroIsOutsideMethod, TestCases._009_WhenMacroIsOutsideMethod_FIXED, MacroCodeAnalyzer.Rule, 5); } [Test] public void should_be_able_to_execute_macro_outside_method_and_nothing_more() { TestCodeFixAtLine(TestCases._010_WhenMacroIsOutsideMethodAndNothingMore, TestCases._010_WhenMacroIsOutsideMethodAndNothingMore_FIXED, MacroCodeAnalyzer.Rule, 5); } protected override string LanguageName => LanguageNames.CSharp; protected override CodeFixProvider CreateProvider() { return new CsharpMacrosCodeFixProvider(); } } }
40.21519
174
0.714196
[ "MIT" ]
EMostafaAli/CsharpMacros
src/CsharpMacros.Test/General/GeneralTest.cs
3,101
C#
using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using Xunit; using DeezerSync.Models; namespace DeezerSync.Test.MusicProvider { public class SoundCloud { [Theory] [InlineData("omg-network-radio")] public async Task CheckPlaylistType(string username) { DeezerSync.MusicProvider.SoundCloud sc = new DeezerSync.MusicProvider.SoundCloud(username); var res = await sc.GetStandardPlaylists(); Assert.IsType<List<StandardPlaylist>>(res); } } }
25.086957
103
0.679376
[ "MIT" ]
BackInBash/DeezerSync
DeezerSync/DeezerSync.Test/MusicProvider/SoundCloud.cs
579
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.DocumentDB.V20200301 { /// <summary> /// An Azure Cosmos DB userDefinedFunction. /// </summary> [AzureNativeResourceType("azure-native:documentdb/v20200301:SqlResourceSqlUserDefinedFunction")] public partial class SqlResourceSqlUserDefinedFunction : Pulumi.CustomResource { /// <summary> /// The location of the resource group to which the resource belongs. /// </summary> [Output("location")] public Output<string?> Location { get; private set; } = null!; /// <summary> /// The name of the ARM resource. /// </summary> [Output("name")] public Output<string> Name { get; private set; } = null!; [Output("resource")] public Output<Outputs.SqlUserDefinedFunctionGetPropertiesResponseResource?> Resource { get; private set; } = null!; /// <summary> /// Tags are a list of key-value pairs that describe the resource. These tags can be used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can be provided for a resource. Each tag must have a key no greater than 128 characters and value no greater than 256 characters. For example, the default experience for a template type is set with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", "Graph", "DocumentDB", and "MongoDB". /// </summary> [Output("tags")] public Output<ImmutableDictionary<string, string>?> Tags { get; private set; } = null!; /// <summary> /// The type of Azure resource. /// </summary> [Output("type")] public Output<string> Type { get; private set; } = null!; /// <summary> /// Create a SqlResourceSqlUserDefinedFunction 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 SqlResourceSqlUserDefinedFunction(string name, SqlResourceSqlUserDefinedFunctionArgs args, CustomResourceOptions? options = null) : base("azure-native:documentdb/v20200301:SqlResourceSqlUserDefinedFunction", name, args ?? new SqlResourceSqlUserDefinedFunctionArgs(), MakeResourceOptions(options, "")) { } private SqlResourceSqlUserDefinedFunction(string name, Input<string> id, CustomResourceOptions? options = null) : base("azure-native:documentdb/v20200301:SqlResourceSqlUserDefinedFunction", 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:documentdb/v20200301:SqlResourceSqlUserDefinedFunction"}, new Pulumi.Alias { Type = "azure-native:documentdb:SqlResourceSqlUserDefinedFunction"}, new Pulumi.Alias { Type = "azure-nextgen:documentdb:SqlResourceSqlUserDefinedFunction"}, new Pulumi.Alias { Type = "azure-native:documentdb/v20190801:SqlResourceSqlUserDefinedFunction"}, new Pulumi.Alias { Type = "azure-nextgen:documentdb/v20190801:SqlResourceSqlUserDefinedFunction"}, new Pulumi.Alias { Type = "azure-native:documentdb/v20191212:SqlResourceSqlUserDefinedFunction"}, new Pulumi.Alias { Type = "azure-nextgen:documentdb/v20191212:SqlResourceSqlUserDefinedFunction"}, new Pulumi.Alias { Type = "azure-native:documentdb/v20200401:SqlResourceSqlUserDefinedFunction"}, new Pulumi.Alias { Type = "azure-nextgen:documentdb/v20200401:SqlResourceSqlUserDefinedFunction"}, new Pulumi.Alias { Type = "azure-native:documentdb/v20200601preview:SqlResourceSqlUserDefinedFunction"}, new Pulumi.Alias { Type = "azure-nextgen:documentdb/v20200601preview:SqlResourceSqlUserDefinedFunction"}, new Pulumi.Alias { Type = "azure-native:documentdb/v20200901:SqlResourceSqlUserDefinedFunction"}, new Pulumi.Alias { Type = "azure-nextgen:documentdb/v20200901:SqlResourceSqlUserDefinedFunction"}, new Pulumi.Alias { Type = "azure-native:documentdb/v20210115:SqlResourceSqlUserDefinedFunction"}, new Pulumi.Alias { Type = "azure-nextgen:documentdb/v20210115:SqlResourceSqlUserDefinedFunction"}, new Pulumi.Alias { Type = "azure-native:documentdb/v20210301preview:SqlResourceSqlUserDefinedFunction"}, new Pulumi.Alias { Type = "azure-nextgen:documentdb/v20210301preview:SqlResourceSqlUserDefinedFunction"}, new Pulumi.Alias { Type = "azure-native:documentdb/v20210315:SqlResourceSqlUserDefinedFunction"}, new Pulumi.Alias { Type = "azure-nextgen:documentdb/v20210315:SqlResourceSqlUserDefinedFunction"}, new Pulumi.Alias { Type = "azure-native:documentdb/v20210401preview:SqlResourceSqlUserDefinedFunction"}, new Pulumi.Alias { Type = "azure-nextgen:documentdb/v20210401preview:SqlResourceSqlUserDefinedFunction"}, new Pulumi.Alias { Type = "azure-native:documentdb/v20210415:SqlResourceSqlUserDefinedFunction"}, new Pulumi.Alias { Type = "azure-nextgen:documentdb/v20210415:SqlResourceSqlUserDefinedFunction"}, new Pulumi.Alias { Type = "azure-native:documentdb/v20210515:SqlResourceSqlUserDefinedFunction"}, new Pulumi.Alias { Type = "azure-nextgen:documentdb/v20210515:SqlResourceSqlUserDefinedFunction"}, new Pulumi.Alias { Type = "azure-native:documentdb/v20210615:SqlResourceSqlUserDefinedFunction"}, new Pulumi.Alias { Type = "azure-nextgen:documentdb/v20210615:SqlResourceSqlUserDefinedFunction"}, new Pulumi.Alias { Type = "azure-native:documentdb/v20210701preview:SqlResourceSqlUserDefinedFunction"}, new Pulumi.Alias { Type = "azure-nextgen:documentdb/v20210701preview:SqlResourceSqlUserDefinedFunction"}, }, }; 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 SqlResourceSqlUserDefinedFunction 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 SqlResourceSqlUserDefinedFunction Get(string name, Input<string> id, CustomResourceOptions? options = null) { return new SqlResourceSqlUserDefinedFunction(name, id, options); } } public sealed class SqlResourceSqlUserDefinedFunctionArgs : Pulumi.ResourceArgs { /// <summary> /// Cosmos DB database account name. /// </summary> [Input("accountName", required: true)] public Input<string> AccountName { get; set; } = null!; /// <summary> /// Cosmos DB container name. /// </summary> [Input("containerName", required: true)] public Input<string> ContainerName { get; set; } = null!; /// <summary> /// Cosmos DB database name. /// </summary> [Input("databaseName", required: true)] public Input<string> DatabaseName { get; set; } = null!; /// <summary> /// The location of the resource group to which the resource belongs. /// </summary> [Input("location")] public Input<string>? Location { get; set; } /// <summary> /// A key-value pair of options to be applied for the request. This corresponds to the headers sent with the request. /// </summary> [Input("options", required: true)] public Input<Inputs.CreateUpdateOptionsArgs> Options { get; set; } = null!; /// <summary> /// The standard JSON format of a userDefinedFunction /// </summary> [Input("resource", required: true)] public Input<Inputs.SqlUserDefinedFunctionResourceArgs> Resource { get; set; } = null!; /// <summary> /// The name of the resource group. The name is case insensitive. /// </summary> [Input("resourceGroupName", required: true)] public Input<string> ResourceGroupName { get; set; } = null!; [Input("tags")] private InputMap<string>? _tags; /// <summary> /// Tags are a list of key-value pairs that describe the resource. These tags can be used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can be provided for a resource. Each tag must have a key no greater than 128 characters and value no greater than 256 characters. For example, the default experience for a template type is set with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", "Graph", "DocumentDB", and "MongoDB". /// </summary> public InputMap<string> Tags { get => _tags ?? (_tags = new InputMap<string>()); set => _tags = value; } /// <summary> /// Cosmos DB userDefinedFunction name. /// </summary> [Input("userDefinedFunctionName")] public Input<string>? UserDefinedFunctionName { get; set; } public SqlResourceSqlUserDefinedFunctionArgs() { } } }
56.812834
509
0.65305
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/DocumentDB/V20200301/SqlResourceSqlUserDefinedFunction.cs
10,624
C#
// ArrayMapCallback.cs // Script#/Libraries/jQuery/Core // This source code is subject to terms and conditions of the Apache License, Version 2.0. // using System; using System.Runtime.CompilerServices; namespace jQueryApi { /// <summary> /// A callback to be invoked for each item in an array being mapped. /// </summary> /// <param name="item">The item within the array.</param> /// <param name="index">The index of the item.</param> /// <returns>The value that the item was mapped to.</returns> [IgnoreNamespace] [Imported] public delegate object ArrayMapCallback(object item, int index); }
30.142857
90
0.690363
[ "Apache-2.0" ]
doc22940/scriptsharp
src/Libraries/jQuery/jQuery.Core/ArrayMapCallback.cs
633
C#
using UnityEngine; using Unity.Jobs; using Unity.Burst; using Unity.Collections; using Unity.Mathematics; using static Unity.Mathematics.math; namespace Deform { [Deformer (Name = "Skew", Description = "Skews mesh", Type = typeof (SkewDeformer))] [HelpURL("https://github.com/keenanwoodall/Deform/wiki/SkewDeformer")] public class SkewDeformer : Deformer, IFactor { public float Factor { get => factor; set => factor = value; } public BoundsMode Mode { get => mode; set => mode = value; } public float Top { get => top; set => top = Mathf.Max (value, bottom); } public float Bottom { get => bottom; set => bottom = Mathf.Min(value, top); } public Transform Axis { get { if (axis == null) axis = transform; return axis; } set => axis = value; } [SerializeField, HideInInspector] private float factor; [SerializeField, HideInInspector] private BoundsMode mode = BoundsMode.Unlimited; [SerializeField, HideInInspector] private float top = 0.5f; [SerializeField, HideInInspector] private float bottom = -0.5f; [SerializeField, HideInInspector] private Transform axis; public override DataFlags DataFlags => DataFlags.Vertices; public override JobHandle Process (MeshData data, JobHandle dependency = default (JobHandle)) { if (Mathf.Approximately (Factor, 0f)) return dependency; var meshToAxis = DeformerUtils.GetMeshToAxisSpace (Axis, data.Target.GetTransform ()); switch (Mode) { default: case BoundsMode.Unlimited: return new UnlimitedSkewJob { factor = Factor, meshToAxis = meshToAxis, axisToMesh = meshToAxis.inverse, vertices = data.DynamicNative.VertexBuffer }.Schedule (data.Length, DEFAULT_BATCH_COUNT, dependency); case BoundsMode.Limited: return new LimitedSkewJob { factor = Factor, top = Top, bottom = Bottom, meshToAxis = meshToAxis, axisToMesh = meshToAxis.inverse, vertices = data.DynamicNative.VertexBuffer }.Schedule (data.Length, DEFAULT_BATCH_COUNT, dependency); } } [BurstCompile (CompileSynchronously = COMPILE_SYNCHRONOUSLY)] public struct UnlimitedSkewJob : IJobParallelFor { public float factor; public float4x4 meshToAxis; public float4x4 axisToMesh; public NativeArray<float3> vertices; public void Execute (int index) { var point = mul (meshToAxis, float4 (vertices[index], 1f)); point.z += point.y * factor; vertices[index] = mul (axisToMesh, point).xyz; } } [BurstCompile (CompileSynchronously = COMPILE_SYNCHRONOUSLY)] public struct LimitedSkewJob : IJobParallelFor { public float factor; public float top; public float bottom; public float4x4 meshToAxis; public float4x4 axisToMesh; public NativeArray<float3> vertices; public void Execute (int index) { var point = mul (meshToAxis, float4 (vertices[index], 1f)); var samplePoint = clamp (point.y, bottom, top); point.z += samplePoint * factor; vertices[index] = mul (axisToMesh, point).xyz; } } } }
26.508197
96
0.659246
[ "Unlicense" ]
chrsjwilliams/6feetunder
6FeetUnder/Assets/Deform/Code/Runtime/Mesh/Deformers/SkewDeformer.cs
3,236
C#
//------------------------------------------------------------------------------ // 此代码版权(除特别声明或在RRQMCore.XREF命名空间的代码)归作者本人若汝棋茗所有 // 源代码使用协议遵循本仓库的开源协议及附加协议,若本仓库没有设置,则按MIT开源协议授权 // CSDN博客:https://blog.csdn.net/qq_40374647 // 哔哩哔哩视频:https://space.bilibili.com/94253567 // Gitee源代码仓库:https://gitee.com/RRQM_Home // Github源代码仓库:https://github.com/RRQM // 交流QQ群:234762506 // 感谢您的下载和使用 //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RRQMSocket.WebSocket { /// <summary> /// WebSocket数据类型 /// </summary> public enum WSDataType:ushort { /// <summary> /// 表示一个中间数据包,denotes a continuation frame /// </summary> Cont = 0, /// <summary> /// 表示一个text类型数据包 /// </summary> Text = 1, /// <summary> /// 表示一个binary类型数据包 /// </summary> Binary = 2, /// <summary> /// 表示一个断开连接类型数据包 /// </summary> Close = 8, /// <summary> /// 表示一个ping类型数据包 /// </summary> Ping = 9, /// <summary> /// 表示一个pong类型数据包 /// </summary> Pong = 10 } }
26.882353
80
0.459519
[ "Apache-2.0" ]
850wyb/RRQMSocket
RRQMSocket.WebSocket/Enum/WSDataType.cs
1,711
C#
using Mirror; using UnityEngine; namespace WeaverMonoBehaviourTests.MonoBehaviourClientCallback { class MonoBehaviourClientCallback : MonoBehaviour { [ClientCallback] void ThisCantBeOutsideNetworkBehaviour() { } } }
20.416667
62
0.746939
[ "MIT" ]
10allday/OpenMMO
Plugins/3rdParty/Mirror/Tests/Editor/Weaver/WeaverMonoBehaviourTests~/MonoBehaviourClientCallback.cs
245
C#
using Microsoft.Extensions.Hosting; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using websocketschat.Bot.Interfaces; namespace websocketschat.Web.BackgroundService { public class BotBackgroundService : IHostedService { IBotManager _bot; public BotBackgroundService(IBotManager bot) { _bot = bot; } public Task StartAsync(CancellationToken stoppingToken) { _bot.RegisterBotAsync("http://79.143.31.13/api/accounts/register"); _bot.AuthBotAsync("http://79.143.31.13/api/accounts/token", "http://79.143.31.13/chat/negotiate?negotiateVersion=1", "http://79.143.31.13/chat"); try { _bot.OnAsync(); } catch { StartAsync(stoppingToken); } return Task.CompletedTask; } public Task StopAsync(CancellationToken cancellationToken) { _bot.DisconnectAsync(); return Task.CompletedTask; } } }
25.933333
79
0.582691
[ "MIT" ]
gena56rus1/websocketschat_v2
src/websocketschat.Web/BackgroundService/BotBackgroundService.cs
1,169
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Z.Test { [TestClass] public partial class Bulk_BulkAction_BulkMerge_ManySelector { } }
13.75
63
0.757576
[ "MIT" ]
VagrantKm/Dapper-Plus
src/test/Z.Test/Bulk_BulkAction/BulkMerge_ManySelector/global_class.cs
165
C#
// <copyright file="CompositeProcessor.cs" company="OpenTelemetry Authors"> // Copyright The OpenTelemetry Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading; using OpenTelemetry.Internal; namespace OpenTelemetry { public class CompositeProcessor<T> : BaseProcessor<T> { private readonly DoublyLinkedListNode head; private DoublyLinkedListNode tail; private bool disposed; public CompositeProcessor(IEnumerable<BaseProcessor<T>> processors) { Guard.ThrowIfNull(processors); using var iter = processors.GetEnumerator(); if (!iter.MoveNext()) { throw new ArgumentException($"'{iter}' is null or empty", nameof(iter)); } this.head = new DoublyLinkedListNode(iter.Current); this.tail = this.head; while (iter.MoveNext()) { this.AddProcessor(iter.Current); } } public CompositeProcessor<T> AddProcessor(BaseProcessor<T> processor) { Guard.ThrowIfNull(processor); var node = new DoublyLinkedListNode(processor) { Previous = this.tail, }; this.tail.Next = node; this.tail = node; return this; } /// <inheritdoc/> public override void OnEnd(T data) { for (var cur = this.head; cur != null; cur = cur.Next) { cur.Value.OnEnd(data); } } /// <inheritdoc/> public override void OnStart(T data) { for (var cur = this.head; cur != null; cur = cur.Next) { cur.Value.OnStart(data); } } /// <inheritdoc/> protected override bool OnForceFlush(int timeoutMilliseconds) { var result = true; var sw = timeoutMilliseconds == Timeout.Infinite ? null : Stopwatch.StartNew(); for (var cur = this.head; cur != null; cur = cur.Next) { if (sw == null) { result = cur.Value.ForceFlush(Timeout.Infinite) && result; } else { var timeout = timeoutMilliseconds - sw.ElapsedMilliseconds; // notify all the processors, even if we run overtime result = cur.Value.ForceFlush((int)Math.Max(timeout, 0)) && result; } } return result; } /// <inheritdoc/> protected override bool OnShutdown(int timeoutMilliseconds) { var result = true; var sw = timeoutMilliseconds == Timeout.Infinite ? null : Stopwatch.StartNew(); for (var cur = this.head; cur != null; cur = cur.Next) { if (sw == null) { result = cur.Value.Shutdown(Timeout.Infinite) && result; } else { var timeout = timeoutMilliseconds - sw.ElapsedMilliseconds; // notify all the processors, even if we run overtime result = cur.Value.Shutdown((int)Math.Max(timeout, 0)) && result; } } return result; } /// <inheritdoc/> protected override void Dispose(bool disposing) { if (!this.disposed) { if (disposing) { for (var cur = this.head; cur != null; cur = cur.Next) { try { cur.Value?.Dispose(); } catch (Exception ex) { OpenTelemetrySdkEventSource.Log.SpanProcessorException(nameof(this.Dispose), ex); } } } this.disposed = true; } base.Dispose(disposing); } private class DoublyLinkedListNode { public readonly BaseProcessor<T> Value; public DoublyLinkedListNode(BaseProcessor<T> value) { this.Value = value; } public DoublyLinkedListNode Previous { get; set; } public DoublyLinkedListNode Next { get; set; } } } }
29.88
109
0.503538
[ "Apache-2.0" ]
BearerPipelineTest/opentelemetry-dotnet
src/OpenTelemetry/CompositeProcessor.cs
5,229
C#
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.DependencyInjection; using aspnetHosting = Microsoft.AspNetCore.Hosting; namespace HelloWorld.Server { public class Startup { // This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.AddRazorComponents<App.Startup>(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, aspnetHosting.IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseStaticFiles(); app.UseRazorComponents<App.Startup>(); } } 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>(); webBuilder.UseEnvironment(aspnetHosting.EnvironmentName.Development); }); } }
33.428571
122
0.644078
[ "MIT" ]
JozefR/practical-aspnetcore
projects/3-0/razor-component/hello-world/HelloWorld.Server/Program.cs
1,638
C#
using System; using System.Collections.Generic; using System.ComponentModel; using UnityEngine; namespace traVRsal.SDK { [Serializable] public class Game { public enum ReleaseChannel { Live = 0, Beta = 1, Alpha = 2 } public enum PublishingEnvironment { Other = 0, Oculus = 1 } [Header("Configuration")] [DefaultValue("game")] public string key = "game"; public ReleaseChannel channel = ReleaseChannel.Live; public PublishingEnvironment environment = PublishingEnvironment.Other; [DefaultValue("Development Mode")] public string name = "Development Mode"; public List<string> worlds; [DefaultValue("Intro")] public string introWorld = "Intro"; [DefaultValue("Menu-traVRsal")] public string menuScene = "Menu-traVRsal"; [DefaultValue("Pause-traVRsal")] public string pauseScene = "Pause-traVRsal"; [DefaultValue("GameOver-traVRsal")] public string gameOverScene = "GameOver-traVRsal"; [DefaultValue("Theater-traVRsal")] public string theaterScene = "Theater-traVRsal"; public bool devMode; public bool enableMultiplayer; // derived public bool offlineMode; public Game() { worlds = new List<string>(); } public void NullifyEmpties() { if (worlds != null && worlds.Count == 0) worlds = null; } public override string ToString() { return $"Game '{name}' ({key}, {worlds.Count} worlds, " + (devMode ? "Dev-Mode" : "Game-Mode") + ")"; } } }
29.258621
113
0.58574
[ "MIT" ]
studentutu/traVRsal-sdk
Runtime/Construction/Game.cs
1,699
C#
using AemonsNookMono.Admin; using AemonsNookMono.Player; using Microsoft.Xna.Framework; using System; using System.Collections.Generic; using System.Text; namespace AemonsNookMono.Menus.World { public class ProfileMenu : Menu { public ProfileMenu(StateManager.State originalState) : base("Profile", (int)((float)Graphics.Current.ScreenWidth * 0.75f), (int)((float)Graphics.Current.ScreenHeight * 0.7f), Graphics.Current.ScreenMidX, Graphics.Current.ScreenMidY, ((int)((float)Graphics.Current.ScreenWidth * 0.75f) / 16), (int)((float)Graphics.Current.ScreenHeight * 0.7f) / 16, null, string.Empty) { SaveManager.Current.SaveProfile(ProfileManager.Current.Loaded); this.InitButtons(); this.OriginalState = originalState; } #region Public Properties public StateManager.State OriginalState { get; set; } #endregion #region Interface public override void InitButtons() { this.CellGroupings.Clear(); this.StaticCells.Clear(); int bottomRowHeight = this.Height / 12; Span columns = new Span(this.CenterX, this.CenterY - (bottomRowHeight / 2), this.Width, this.Height - bottomRowHeight, this.PadWidth, this.PadHeight, Span.SpanType.Horizontal); columns.InnerPadScale = 0.1f; Span leftside = new Span(Span.SpanType.Vertical); //leftside.AddColorButton("Left", "Left", Color.Red, true); leftside.AddText($"{ProfileManager.Current.Loaded.Name}"); leftside.AddColorButton("", "", null, false); leftside.AddColorButton("", "", null, false); leftside.AddSprite("profile-portrait-temp", 256, 256); leftside.AddColorButton("", "", null, false); leftside.AddColorButton("", "", null, false); leftside.AddColorButton("", "", null, false); leftside.AddColorButton("", "", null, false); leftside.AddColorButton("", "", null, false); leftside.AddColorButton("Load", "Load", ProfileManager.Current.ColorPrimary, true); columns.AddSpan(leftside); Span middle = new Span(Span.SpanType.Vertical); //middle.AddColorButton("Middle", "Middle", Color.Red, true); middle.AddColorButton("", "", null, false); middle.AddText($"Total Time Played: {ProfileManager.Current.GetTotalPlaytimeString()}", "couriernew", Color.Bisque, Textbox.HorizontalAlign.Left, Textbox.VerticalAlign.Center); middle.AddText($"Stone Collected: {ProfileManager.Current.Loaded.TotalStoneCollected} stone", "couriernew", Color.Bisque, Textbox.HorizontalAlign.Left, Textbox.VerticalAlign.Center); middle.AddText($"Wood Collected: {ProfileManager.Current.Loaded.TotalWoodCollected} wood", "couriernew", Color.Bisque, Textbox.HorizontalAlign.Left, Textbox.VerticalAlign.Center); middle.AddColorButton("", "", null, false); middle.AddColorButton("", "", null, false); middle.AddColorButton("", "", null, false); middle.AddColorButton("", "", null, false); middle.AddColorButton("", "", null, false); middle.AddColorButton("Create", "Create", ProfileManager.Current.ColorPrimary, true); columns.AddSpan(middle); //Span rightside = new Span(Span.SpanType.Vertical); ////rightside.AddColorButton("Right", "Right", Color.Red, true); //rightside.AddColorButton("", "", null, false); //rightside.AddText("Test:", "couriernew", Color.Bisque, Textbox.HorizontalAlign.Left, Textbox.VerticalAlign.Center); //rightside.AddText("Test 2:", "couriernew", Color.Bisque, Textbox.HorizontalAlign.Left, Textbox.VerticalAlign.Center); //rightside.AddText("Test 3:", "couriernew", Color.Bisque, Textbox.HorizontalAlign.Left, Textbox.VerticalAlign.Center); //rightside.AddColorButton("", "", null, false); //rightside.AddColorButton("", "", null, false); //rightside.AddColorButton("", "", null, false); //rightside.AddColorButton("", "", null, false); //rightside.AddColorButton("", "", null, false); //columns.AddSpan(rightside); this.CellGroupings.Add(columns); foreach (Span span in this.CellGroupings) { span.Refresh(); } Button BackButton = new Button( "Back", "Back", this.CenterX, // x this.TopY + (int)(this.Height - (bottomRowHeight)), // y this.Width - (this.PadWidth * 2), // width bottomRowHeight, // height null, // sprite Color.Black, // color Collision.CollisionShape.Rectangle, true); this.StaticCells.Add(BackButton); } public override void Refresh() { this.Width = (int)((float)Graphics.Current.ScreenWidth * 0.75f); this.Height = (int)((float)Graphics.Current.ScreenHeight * 0.7f); this.CenterX = Graphics.Current.ScreenMidX; this.CenterY = Graphics.Current.ScreenMidY; this.PadWidth = (int)((float)Graphics.Current.ScreenWidth * 0.75f) / 16; this.PadHeight = ((int)((float)Graphics.Current.ScreenHeight * 0.7f) / 16); base.Refresh(); this.InitButtons(); } public override bool HandleLeftClick(int x, int y) { Button clicked = this.CheckButtonCollisions(x, y); if (clicked != null) { Debugger.Current.AddTempString($"You clicked on the {clicked.ButtonCode} button!"); switch (clicked.ButtonCode) { case "Back": SaveManager.Current.SaveProfile(ProfileManager.Current.Loaded); StateManager.Current.CurrentState = this.OriginalState; MenuManager.Current.CloseTop(); return true; case "Create": ProfileCreateMenu createmenu = new ProfileCreateMenu(); MenuManager.Current.AddMenu(createmenu); return true; case "Load": SaveManager.Current.SaveProfile(ProfileManager.Current.Loaded); ProfileLoadMenu loadmenu = new ProfileLoadMenu(); MenuManager.Current.AddMenu(loadmenu); return true; case "Save": SaveManager.Current.SaveProfile(ProfileManager.Current.Loaded); StateManager.Current.CurrentState = this.OriginalState; MenuManager.Current.CloseTop(); return true; default: return false; } } return false; } #endregion } }
47.666667
194
0.55702
[ "MIT" ]
JamCamAbreu/AemonsNookMono
AemonsNookMono/Menus/World/ProfileMenu.cs
7,438
C#
#region License /* The MIT License Copyright (c) 2008 Sky Morey 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. */ #endregion using System.Collections.Generic; namespace System { /// <summary> /// NparamsManager /// </summary> public class NparamsManager { /// <summary> /// Creates this instance. /// </summary> /// <returns></returns> public static Nparams Create() { return new Nparams(new StdParams()); } /// <summary> /// Parses the specified args. /// </summary> /// <param name="args">The args.</param> /// <returns></returns> public static Nparams Parse(IDictionary<string, object> args) { if (args == null) throw new ArgumentNullException("args"); return new Nparams(new StdParams(args)); } /// <summary> /// Parses the specified args. /// </summary> /// <param name="args">The args.</param> /// <returns></returns> public static Nparams Parse(string[] args) { if (args == null) throw new ArgumentNullException("args"); return new Nparams(new StdParams(args)); } /// <summary> /// Parses the specified args. /// </summary> /// <param name="args">The args.</param> /// <returns></returns> public static Nparams Parse(object args) { if (args == null) throw new ArgumentNullException("args"); return new Nparams(new StdParams(args)); } } }
36.121622
80
0.61691
[ "MIT" ]
Grimace1975/bclcontrib-abstract
src/System.Abstract/+Nparams+Impl/NparamsManager.cs
2,675
C#
using System; using System.Text; class UnicodeCharacters { static void Main() { string input = Console.ReadLine(); foreach (char c in input) { Console.Write("\\u{0:X4}", getUnicodeCode(c)); } Console.WriteLine(); } private static int getUnicodeCode(char character) { UTF32Encoding encoding = new UTF32Encoding(); byte[] bytes = encoding.GetBytes(character.ToString().ToCharArray()); //return BitConverter.ToInt32(bytes, 0).ToString("X"); return BitConverter.ToInt32(bytes, 0); } }
23.72
77
0.60371
[ "MIT" ]
sholev/SoftUni
Fundamentals-2.0/C#-Advanced/Homework/2015-09/StringsAndTextProcessing/UnicodeCharacters/UnicodeCharacters.cs
595
C#
using CompanyName.MyMeetings.Modules.Meetings.Domain.Meetings; using CompanyName.MyMeetings.Modules.Meetings.Domain.Meetings.Events; using CompanyName.MyMeetings.Modules.Meetings.Domain.Meetings.Rules; using CompanyName.MyMeetings.Modules.Meetings.Domain.UnitTests.SeedWork; using NUnit.Framework; using System; namespace CompanyName.MyMeetings.Modules.Meetings.Domain.UnitTests.Meetings { [TestFixture] public class MeetingRolesTests : MeetingTestsBase { [Test] public void SetHostRole_WhenMeetingHasStarted_IsNotPossible() { var creatorId = new MemberId(Guid.NewGuid()); var meetingTestData = CreateMeetingTestData(new MeetingTestDataOptions { CreatorId = creatorId, MeetingTerm = MeetingTerm.CreateNewBetweenDates(DateTime.UtcNow.AddDays(-2), DateTime.UtcNow.AddDays(-1)) }); AssertBrokenRule<MeetingCannotBeChangedAfterStartRule>(() => { meetingTestData.Meeting.SetHostRole(meetingTestData.MeetingGroup, creatorId, creatorId); }); } [Test] public void SetHostRole_WhenSettingMemberIsNotAOrganizerOrHostMeeting_IsNotPossible() { var creatorId = new MemberId(Guid.NewGuid()); var meetingTestData = CreateMeetingTestData(new MeetingTestDataOptions { CreatorId = creatorId }); var settingMemberId = new MemberId(Guid.NewGuid()); var newOrganizerId = new MemberId(Guid.NewGuid()); meetingTestData.MeetingGroup.JoinToGroupMember(newOrganizerId); meetingTestData.MeetingGroup.JoinToGroupMember(settingMemberId); meetingTestData.Meeting.AddAttendee(meetingTestData.MeetingGroup, newOrganizerId, 0); AssertBrokenRule<OnlyMeetingOrGroupOrganizerCanSetMeetingMemberRolesRule>(() => { meetingTestData.Meeting.SetHostRole(meetingTestData.MeetingGroup, settingMemberId, newOrganizerId); }); } [Test] public void SetHostRole_WhenSettingMemberIsGroupOrganizer_IsSuccessful() { var creatorId = new MemberId(Guid.NewGuid()); var meetingTestData = CreateMeetingTestData(new MeetingTestDataOptions { CreatorId = creatorId }); var newOrganizerId = new MemberId(Guid.NewGuid()); meetingTestData.MeetingGroup.JoinToGroupMember(newOrganizerId); meetingTestData.Meeting.AddAttendee(meetingTestData.MeetingGroup, newOrganizerId, 0); meetingTestData.Meeting.SetHostRole(meetingTestData.MeetingGroup, creatorId, newOrganizerId); var newMeetingHostSet = AssertPublishedDomainEvent<NewMeetingHostSetDomainEvent>(meetingTestData.Meeting); Assert.That(newMeetingHostSet.HostId, Is.EqualTo(newOrganizerId)); } [Test] public void SetHostRole_WhenSettingMemberIsMeetingHost_IsSuccessful() { var creatorId = new MemberId(Guid.NewGuid()); var meetingTestData = CreateMeetingTestData(new MeetingTestDataOptions { CreatorId = creatorId }); var newOrganizerId = new MemberId(Guid.NewGuid()); var settingMemberId = new MemberId(Guid.NewGuid()); meetingTestData.MeetingGroup.JoinToGroupMember(newOrganizerId); meetingTestData.MeetingGroup.JoinToGroupMember(settingMemberId); meetingTestData.Meeting.AddAttendee(meetingTestData.MeetingGroup, newOrganizerId, 0); meetingTestData.Meeting.AddAttendee(meetingTestData.MeetingGroup, settingMemberId, 0); meetingTestData.Meeting.SetHostRole(meetingTestData.MeetingGroup, creatorId, settingMemberId); DomainEventsTestHelper.ClearAllDomainEvents(meetingTestData.Meeting); meetingTestData.Meeting.SetHostRole(meetingTestData.MeetingGroup, settingMemberId, newOrganizerId); var newMeetingHostSetEvent = AssertPublishedDomainEvent<NewMeetingHostSetDomainEvent>(meetingTestData.Meeting); Assert.That(newMeetingHostSetEvent.HostId, Is.EqualTo(newOrganizerId)); } [Test] public void SetAttendeeRole_WhenMeetingHasStarted_IsNotPossible() { var creatorId = new MemberId(Guid.NewGuid()); var meetingTestData = CreateMeetingTestData(new MeetingTestDataOptions { CreatorId = creatorId, MeetingTerm = MeetingTerm.CreateNewBetweenDates(DateTime.UtcNow.AddDays(-2), DateTime.UtcNow.AddDays(-1)) }); AssertBrokenRule<MeetingCannotBeChangedAfterStartRule>(() => { meetingTestData.Meeting.SetAttendeeRole(meetingTestData.MeetingGroup, creatorId, creatorId); }); } [Test] public void SetAttendeeRole_WhenSettingMemberIsNotAOrganizerOrHostMeeting_IsNotPossible() { var creatorId = new MemberId(Guid.NewGuid()); var meetingTestData = CreateMeetingTestData(new MeetingTestDataOptions { CreatorId = creatorId }); var settingMemberId = new MemberId(Guid.NewGuid()); var newOrganizerId = new MemberId(Guid.NewGuid()); meetingTestData.MeetingGroup.JoinToGroupMember(newOrganizerId); meetingTestData.MeetingGroup.JoinToGroupMember(settingMemberId); meetingTestData.Meeting.AddAttendee(meetingTestData.MeetingGroup, newOrganizerId, 0); AssertBrokenRule<OnlyMeetingOrGroupOrganizerCanSetMeetingMemberRolesRule>(() => { meetingTestData.Meeting.SetAttendeeRole(meetingTestData.MeetingGroup, settingMemberId, newOrganizerId); }); } [Test] public void SetAttendeeRole_WhenMemberIsOrganizer_IsSuccessful() { var creatorId = new MemberId(Guid.NewGuid()); var meetingTestData = CreateMeetingTestData(new MeetingTestDataOptions { CreatorId = creatorId }); var newOrganizerId = new MemberId(Guid.NewGuid()); meetingTestData.MeetingGroup.JoinToGroupMember(newOrganizerId); meetingTestData.Meeting.AddAttendee(meetingTestData.MeetingGroup, newOrganizerId, 0); meetingTestData.Meeting.SetHostRole(meetingTestData.MeetingGroup, creatorId, newOrganizerId); meetingTestData.Meeting.SetAttendeeRole(meetingTestData.MeetingGroup, creatorId, newOrganizerId); var newMeetingHostSet = AssertPublishedDomainEvent<MemberSetAsAttendeeDomainEvent>(meetingTestData.Meeting); Assert.That(newMeetingHostSet.HostId, Is.EqualTo(newOrganizerId)); } [Test] public void SetAttendeeRole_WhenMemberIsAlreadyAttendee_IsNotPossible() { var creatorId = new MemberId(Guid.NewGuid()); var meetingTestData = CreateMeetingTestData(new MeetingTestDataOptions { CreatorId = creatorId }); var attendeeId = new MemberId(Guid.NewGuid()); meetingTestData.MeetingGroup.JoinToGroupMember(attendeeId); meetingTestData.Meeting.AddAttendee(meetingTestData.MeetingGroup, attendeeId, 0); AssertBrokenRule<MemberCannotHaveSetAttendeeRoleMoreThanOnceRule>(() => { meetingTestData.Meeting.SetAttendeeRole(meetingTestData.MeetingGroup, creatorId, attendeeId); }); } [Test] public void SetAttendeeRole_ForLastOrganizer_BreaksMeetingMustHaveAtLeastOneHostRule() { var creatorId = new MemberId(Guid.NewGuid()); var meetingTestData = CreateMeetingTestData(new MeetingTestDataOptions { CreatorId = creatorId }); AssertBrokenRule<MeetingMustHaveAtLeastOneHostRule>(() => { meetingTestData.Meeting.SetAttendeeRole(meetingTestData.MeetingGroup, creatorId, creatorId); }); } } }
45.433333
123
0.671191
[ "MIT" ]
GamilYassin/modular-monolith-with-ddd
src/Modules/Meetings/Tests/UnitTests/Meetings/MeetingRolesTests.cs
8,180
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System; using System.Collections.Generic; using Aliyun.Acs.Core.Transform; using Aliyun.Acs.EHPC.Model.V20180412; namespace Aliyun.Acs.EHPC.Transform.V20180412 { public class DescribeGWSClusterPolicyResponseUnmarshaller { public static DescribeGWSClusterPolicyResponse Unmarshall(UnmarshallerContext context) { DescribeGWSClusterPolicyResponse describeGWSClusterPolicyResponse = new DescribeGWSClusterPolicyResponse(); describeGWSClusterPolicyResponse.HttpResponse = context.HttpResponse; describeGWSClusterPolicyResponse.RequestId = context.StringValue("DescribeGWSClusterPolicy.RequestId"); describeGWSClusterPolicyResponse.Clipboard = context.StringValue("DescribeGWSClusterPolicy.Clipboard"); describeGWSClusterPolicyResponse.UsbRedirect = context.StringValue("DescribeGWSClusterPolicy.UsbRedirect"); describeGWSClusterPolicyResponse.Watermark = context.StringValue("DescribeGWSClusterPolicy.Watermark"); describeGWSClusterPolicyResponse.LocalDrive = context.StringValue("DescribeGWSClusterPolicy.LocalDrive"); return describeGWSClusterPolicyResponse; } } }
44.5
111
0.790092
[ "Apache-2.0" ]
bbs168/aliyun-openapi-net-sdk
aliyun-net-sdk-ehpc/EHPC/Transform/V20180412/DescribeGWSClusterPolicyResponseUnmarshaller.cs
1,958
C#