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
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Runtime.InteropServices; namespace JekyllLibrary.Library { public partial class BlackOps3 { public class Localize : IXAssetPool { public override string Name => "Localize Entry"; public override int Index => (int)XAssetType.ASSET_TYPE_LOCALIZE_ENTRY; /// <summary> /// Structure of a Black Ops III LocalizeEntry. /// </summary> private struct LocalizeEntry { public long Value { get; set; } public long Name { get; set; } } /// <summary> /// Load the valid XAssets for the Localize XAsset Pool. /// </summary> /// <param name="instance"></param> /// <returns>List of Localize XAsset objects.</returns> public override List<GameXAsset> Load(JekyllInstance instance) { List<GameXAsset> results = new List<GameXAsset>(); XAssetPool pool = instance.Reader.ReadStruct<XAssetPool>(instance.Game.DBAssetPools + (Index * Marshal.SizeOf<XAssetPool>())); Entries = pool.Pool; ElementSize = pool.ItemSize; PoolSize = (uint)pool.ItemCount; if (IsValidPool(Name, ElementSize, Marshal.SizeOf<LocalizeEntry>()) == false) { return results; } Dictionary<string, string> entries = new Dictionary<string, string>(); for (int i = 0; i < PoolSize; i++) { LocalizeEntry header = instance.Reader.ReadStruct<LocalizeEntry>(Entries + (i * ElementSize)); if (IsNullXAsset(header.Name)) { continue; } string key = instance.Reader.ReadNullTerminatedString(header.Name).ToUpper(); if (entries.TryGetValue(key, out string _)) { continue; } string value = instance.Reader.ReadNullTerminatedString(header.Value, nullCheck:true); entries.Add(key, value); Console.WriteLine($"Exported {Name} {key}"); } string path = Path.Combine(instance.ExportPath, "localize.json"); Directory.CreateDirectory(Path.GetDirectoryName(path)); using (StreamWriter file = File.CreateText(path)) { file.Write(JsonConvert.SerializeObject(entries, Formatting.Indented)); } return results; } /// <summary> /// Exports the specified Localize XAsset. /// </summary> /// <param name="xasset"></param> /// <param name="instance"></param> /// <returns>Status of the export operation.</returns> public override JekyllStatus Export(GameXAsset xasset, JekyllInstance instance) { return JekyllStatus.Success; } } } }
34.935484
142
0.521083
[ "MIT" ]
EpicZombieSlayer115/Jekyll
Jekyll.Library/Game/BlackOps3/XAssets/Localize.cs
3,251
C#
// <auto-generated /> using GoldenForCongress.Data; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage; using Microsoft.EntityFrameworkCore.Storage.Internal; using System; namespace GoldenForCongress.Migrations { [DbContext(typeof(DB))] [Migration("20170911155827_Routes")] partial class Routes { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "2.0.0-rtm-26452") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("GoldenForCongress.Models.Route", b => { b.Property<Guid>("ID") .ValueGeneratedOnAdd(); b.Property<string>("Color"); b.Property<DateTime>("Date"); b.Property<int>("Day"); b.Property<string>("Description"); b.Property<string>("Path"); b.HasKey("ID"); b.ToTable("Routes"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => { b.Property<string>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Name") .HasMaxLength(256); b.Property<string>("NormalizedName") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("NormalizedName") .IsUnique() .HasName("RoleNameIndex") .HasFilter("[NormalizedName] IS NOT NULL"); b.ToTable("AspNetRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("RoleId") .IsRequired(); b.HasKey("Id"); b.HasIndex("RoleId"); b.ToTable("AspNetRoleClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUser", b => { b.Property<string>("Id") .ValueGeneratedOnAdd(); b.Property<int>("AccessFailedCount"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Email") .HasMaxLength(256); b.Property<bool>("EmailConfirmed"); b.Property<bool>("LockoutEnabled"); b.Property<DateTimeOffset?>("LockoutEnd"); b.Property<string>("NormalizedEmail") .HasMaxLength(256); b.Property<string>("NormalizedUserName") .HasMaxLength(256); b.Property<string>("PasswordHash"); b.Property<string>("PhoneNumber"); b.Property<bool>("PhoneNumberConfirmed"); b.Property<string>("SecurityStamp"); b.Property<bool>("TwoFactorEnabled"); b.Property<string>("UserName") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("NormalizedEmail") .HasName("EmailIndex"); b.HasIndex("NormalizedUserName") .IsUnique() .HasName("UserNameIndex") .HasFilter("[NormalizedUserName] IS NOT NULL"); b.ToTable("AspNetUsers"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("UserId") .IsRequired(); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("AspNetUserClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider"); b.Property<string>("ProviderKey"); b.Property<string>("ProviderDisplayName"); b.Property<string>("UserId") .IsRequired(); b.HasKey("LoginProvider", "ProviderKey"); b.HasIndex("UserId"); b.ToTable("AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.Property<string>("UserId"); b.Property<string>("RoleId"); b.HasKey("UserId", "RoleId"); b.HasIndex("RoleId"); b.ToTable("AspNetUserRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.Property<string>("UserId"); b.Property<string>("LoginProvider"); b.Property<string>("Name"); b.Property<string>("Value"); b.HasKey("UserId", "LoginProvider", "Name"); b.ToTable("AspNetUserTokens"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole") .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole") .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); #pragma warning restore 612, 618 } } }
33.266932
117
0.475928
[ "MIT" ]
stevedesmond-ca/GoldenForCongress
src/Migrations/20170911155827_Routes.Designer.cs
8,352
C#
using System.Collections.Generic; using System.Linq; using Newtonsoft.Json.Linq; namespace JsonDiffPatchDotNet.Formatters { public abstract class BaseDeltaFormatter<TContext, TResult> where TContext : IFormatContext<TResult>, new() { public delegate void DeltaKeyIterator(string key, string leftKey, MoveDestination movedFrom, bool isLast); private static readonly IComparer<string> s_arrayKeyComparer = new ArrayKeyComparer(); public virtual TResult Format(JToken delta) { var context = new TContext(); Recurse(context, delta, left: null, key: null, leftKey: null, movedFrom: null, isLast: false); return context.Result(); } protected abstract bool IncludeMoveDestinations { get; } protected abstract void NodeBegin(TContext context, string key, string leftKey, DeltaType type, NodeType nodeType, bool isLast); protected abstract void NodeEnd(TContext context, string key, string leftKey, DeltaType type, NodeType nodeType, bool isLast); protected abstract void RootBegin(TContext context, DeltaType type, NodeType nodeType); protected abstract void RootEnd(TContext context, DeltaType type, NodeType nodeType); protected abstract void Format(DeltaType type, TContext context, JToken delta, JToken leftValue, string key, string leftKey, MoveDestination movedFrom); protected void Recurse(TContext context, JToken delta, JToken left, string key, string leftKey, MoveDestination movedFrom, bool isLast) { var useMoveOriginHere = delta != null && movedFrom != null; var leftValue = useMoveOriginHere ? movedFrom.Value : left; if (delta == null && string.IsNullOrEmpty(key)) return; var type = GetDeltaType(delta, movedFrom); var nodeType = type == DeltaType.Node ? (delta["_t"]?.Value<string>() == "a" ? NodeType.Array : NodeType.Object) : NodeType.Unknown; if (!string.IsNullOrEmpty(key)) NodeBegin(context, key, leftKey, type, nodeType, isLast); else RootBegin(context, type, nodeType); Format(type, context, delta, leftValue, key, leftKey, movedFrom); if (!string.IsNullOrEmpty(key)) NodeEnd(context, key, leftKey, type, nodeType, isLast); else RootEnd(context, type, nodeType); } protected void FormatDeltaChildren(TContext context, JToken delta, JToken left) { ForEachDeltaKey(delta, left, Iterator); void Iterator(string key, string leftKey, MoveDestination movedFrom, bool isLast) { Recurse(context, delta[key], left?[leftKey], key, leftKey, movedFrom, isLast); } } protected void ForEachDeltaKey(JToken delta, JToken left, DeltaKeyIterator iterator) { var keys = new List<string>(); var arrayKeys = false; var movedDestinations = new Dictionary<string, MoveDestination>(); if (delta is JObject jObject) { keys = jObject.Properties().Select(p => p.Name).ToList(); arrayKeys = jObject["_t"]?.Value<string>() == "a"; } if (left != null && left is JObject leftObject) { foreach (var kvp in leftObject) { if (delta[kvp.Key] == null && (!arrayKeys || delta["_" + kvp.Key] == null)) { keys.Add(kvp.Key); } } } if (delta is JObject deltaObject) { foreach (var kvp in deltaObject) { var value = kvp.Value; if (value is JArray valueArray && valueArray.Count == 3) { var diffOp = valueArray[2].Value<int>(); if (diffOp == (int)DiffOperation.ArrayMove) { var moveKey = valueArray[1].ToString(); movedDestinations[moveKey] = new MoveDestination(kvp.Key, left?[kvp.Key.Substring(1)]); if (IncludeMoveDestinations && left == null && deltaObject.Property(moveKey) == null) keys.Add(moveKey); } } } } if (arrayKeys) keys.Sort(s_arrayKeyComparer); else keys.Sort(); for (var index = 0; index < keys.Count; index++) { var key = keys[index]; if (arrayKeys && key == "_t") continue; var leftKey = arrayKeys ? key.TrimStart('_') : key; var isLast = index == keys.Count - 1; var movedFrom = movedDestinations.ContainsKey(leftKey) ? movedDestinations[leftKey] : null; iterator(key, leftKey, movedFrom, isLast); } } protected static DeltaType GetDeltaType(JToken delta = null, MoveDestination movedFrom = null) { if (delta == null) return movedFrom != null ? DeltaType.MoveDestination : DeltaType.Unchanged; switch (delta.Type) { case JTokenType.Array: { var deltaArray = (JArray)delta; switch (deltaArray.Count) { case 1: return DeltaType.Added; case 2: return DeltaType.Modified; case 3: { switch ((DiffOperation)deltaArray[2].Value<int>()) { case DiffOperation.Deleted: return DeltaType.Deleted; case DiffOperation.TextDiff: return DeltaType.TextDiff; case DiffOperation.ArrayMove: return DeltaType.Moved; } break; } } break; } case JTokenType.Object: return DeltaType.Node; } return DeltaType.Unknown; } } }
29.886905
154
0.677953
[ "MIT" ]
Kairus101/jsondiffpatch.net
Src/JsonDiffPatchDotNet/Formatters/BaseDeltaFormatter.cs
5,021
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 Aliyun.Acs.Core.Transform; using Aliyun.Acs.Ess.Model.V20140828; using System; using System.Collections.Generic; namespace Aliyun.Acs.Ess.Transform.V20140828 { public class ModifyScalingConfigurationResponseUnmarshaller { public static ModifyScalingConfigurationResponse Unmarshall(UnmarshallerContext context) { ModifyScalingConfigurationResponse modifyScalingConfigurationResponse = new ModifyScalingConfigurationResponse(); modifyScalingConfigurationResponse.HttpResponse = context.HttpResponse; modifyScalingConfigurationResponse.RequestId = context.StringValue("ModifyScalingConfiguration.RequestId"); return modifyScalingConfigurationResponse; } } }
40.368421
117
0.775098
[ "Apache-2.0" ]
brightness007/unofficial-aliyun-openapi-net-sdk
aliyun-net-sdk-ess/Ess/Transform/V20140828/ModifyScalingConfigurationResponseUnmarshaller.cs
1,534
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.Text; using System.Collections.ObjectModel; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Type = Microsoft.VisualStudio.Debugger.Metadata.Type; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator { internal sealed partial class CSharpFormatter : Formatter { /// <summary> /// Singleton instance of CSharpFormatter (created using default constructor). /// </summary> internal readonly static CSharpFormatter Instance = new CSharpFormatter(); public CSharpFormatter() : base(defaultFormat: "{{{0}}}", nullString: "null", staticMembersString: Resources.StaticMembers) { } internal override bool IsValidIdentifier(string name) { return SyntaxFacts.IsValidIdentifier(name); } internal override bool IsIdentifierPartCharacter(char c) { return SyntaxFacts.IsIdentifierPartCharacter(c); } internal override bool IsPredefinedType(Type type) { return type.IsPredefinedType(); } internal override bool IsWhitespace(char c) { return SyntaxFacts.IsWhitespace(c); } internal override string TrimAndGetFormatSpecifiers(string expression, out ReadOnlyCollection<string> formatSpecifiers) { expression = RemoveComments(expression); expression = RemoveFormatSpecifiers(expression, out formatSpecifiers); return RemoveLeadingAndTrailingContent(expression, 0, expression.Length, IsWhitespace, ch => ch == ';' || IsWhitespace(ch)); } private static string RemoveComments(string expression) { var pooledBuilder = PooledStringBuilder.GetInstance(); var builder = pooledBuilder.Builder; var inMultilineComment = false; int length = expression.Length; for (int i = 0; i < length; i++) { var ch = expression[i]; if (inMultilineComment) { if (ch == '*' && i + 1 < length && expression[i + 1] == '/') { i++; inMultilineComment = false; } } else { if (ch == '/' && i + 1 < length) { var next = expression[i + 1]; if (next == '*') { i++; inMultilineComment = true; continue; } else if (next == '/') { // Ignore remainder of string. break; } } builder.Append(ch); } } if (builder.Length < length) { expression = builder.ToString(); } pooledBuilder.Free(); return expression; } } }
34.765306
160
0.509246
[ "Apache-2.0" ]
0x53A/roslyn
src/ExpressionEvaluator/CSharp/Source/ResultProvider/CSharpFormatter.cs
3,407
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using k8s.Models; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using NJsonSchema; using NJsonSchema.Generation; using NJsonSchema.Generation.TypeMappers; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace Microsoft.Kubernetes.CustomResources; /// <summary> /// Class CustomResourceDefinitionGenerator generates CRD documents for .NET types. /// Implements the <see cref="ICustomResourceDefinitionGenerator" />. /// </summary> /// <seealso cref="ICustomResourceDefinitionGenerator" />. public class CustomResourceDefinitionGenerator : ICustomResourceDefinitionGenerator { private readonly JsonSchemaGeneratorSettings _jsonSchemaGeneratorSettings; private readonly JsonSerializerSettings _serializerSettings; /// <summary> /// Initializes a new instance of the <see cref="CustomResourceDefinitionGenerator"/> class. /// </summary> /// <param name="client">The client.</param> public CustomResourceDefinitionGenerator() { _jsonSchemaGeneratorSettings = new JsonSchemaGeneratorSettings() { SchemaType = SchemaType.OpenApi3, TypeMappers = { new ObjectTypeMapper( typeof(V1ObjectMeta), new JsonSchema { Type = JsonObjectType.Object, }), }, }; _serializerSettings = new JsonSerializerSettings { Formatting = Formatting.None, DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter(), }, }; } /// <summary> /// generate custom resource definition as an asynchronous operation. /// </summary> /// <typeparam name="TResource">The type of the resource to generate.</typeparam> /// <param name="scope">The scope indicates whether the defined custom resource is cluster- or namespace-scoped. Allowed values are `Cluster` and `Namespaced`.</param> /// <returns>The generated V1CustomResourceDefinition instance.</returns> public Task<V1CustomResourceDefinition> GenerateCustomResourceDefinitionAsync(Type resourceType, string scope, CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); var names = GroupApiVersionKind.From(resourceType); var schema = GenerateJsonSchema(resourceType); return Task.FromResult(new V1CustomResourceDefinition( apiVersion: $"{V1CustomResourceDefinition.KubeGroup}/{V1CustomResourceDefinition.KubeApiVersion}", kind: V1CustomResourceDefinition.KubeKind, metadata: new V1ObjectMeta( name: names.PluralNameGroup), spec: new V1CustomResourceDefinitionSpec( group: names.Group, names: new V1CustomResourceDefinitionNames( kind: names.Kind, plural: names.PluralName), scope: scope, versions: new List<V1CustomResourceDefinitionVersion> { new V1CustomResourceDefinitionVersion( name: names.ApiVersion, served: true, storage: true, schema: new V1CustomResourceValidation(schema)), }))); } /// <summary> /// generate custom resource definition as an asynchronous operation. /// </summary> /// <typeparam name="TResource">The type of the resource to generate.</typeparam> /// <param name="scope">The scope indicates whether the defined custom resource is cluster- or namespace-scoped. Allowed values are `Cluster` and `Namespaced`.</param> /// <returns>The generated V1CustomResourceDefinition instance.</returns> public Task<V1CustomResourceDefinition> GenerateCustomResourceDefinitionAsync<TResource>(string scope, CancellationToken cancellationToken = default) { return GenerateCustomResourceDefinitionAsync(typeof(TResource), scope, cancellationToken); } private V1JSONSchemaProps GenerateJsonSchema(Type resourceType) { // start with JsonSchema var schema = JsonSchema.FromType(resourceType, _jsonSchemaGeneratorSettings); // convert to JToken to make alterations var rootToken = JObject.Parse(schema.ToJson()); rootToken = RewriteObject(rootToken); rootToken.Remove("$schema"); rootToken.Remove("definitions"); // convert to k8s.Models.V1JSONSchemaProps to return using var reader = new JTokenReader(rootToken); return JsonSerializer .Create(_serializerSettings) .Deserialize<V1JSONSchemaProps>(reader); } private JObject RewriteObject(JObject sourceObject) { var targetObject = new JObject(); var queue = new Queue<JObject>(); queue.Enqueue(sourceObject); while (queue.Count != 0) { sourceObject = queue.Dequeue(); foreach (var property in sourceObject.Properties()) { if (property.Name == "$ref") { // resolve the target of the "$ref" var reference = sourceObject; foreach (var part in property.Value.Value<string>().Split("/")) { if (part == "#") { reference = (JObject)reference.Root; } else { reference = (JObject)reference[part]; } } // the referenced object should be merged into the current target queue.Enqueue(reference); // and $ref property is not added continue; } if (property.Name == "additionalProperties" && property.Value.Type == JTokenType.Boolean && property.Value.Value<bool>() == false) { // don't add this property when it has a default value continue; } if (property.Name == "oneOf" && property.Value.Type == JTokenType.Array && property.Value.Children().Count() == 1) { // a single oneOf array item should be merged into current object queue.Enqueue(RewriteObject(property.Value.Children().Cast<JObject>().Single())); // and don't add the oneOf property continue; } // all other properties are added after the value is rewritten recursively if (!targetObject.ContainsKey(property.Name)) { targetObject.Add(property.Name, RewriteToken(property.Value)); } } } return targetObject; } private JToken RewriteToken(JToken sourceToken) { if (sourceToken is JObject sourceObject) { return RewriteObject(sourceObject); } else if (sourceToken is JArray sourceArray) { return new JArray(sourceArray.Select(RewriteToken)); } else { return sourceToken; } } }
38.57971
171
0.595667
[ "MIT" ]
ArchonSystemsInc/reverse-proxy
src/OperatorFramework/src/CustomResource/CustomResourceDefinitionGenerator.cs
7,988
C#
using GetcuReone.FactFactory; namespace MovieServiceExample.Facts { /// <summary> /// The fact stores information about the cost of buying a movie for the user /// </summary> public class MoviePurchasePriceFact : FactBase<int> { public MoviePurchasePriceFact(int value) : base(value) { } } }
22.8
81
0.649123
[ "Apache-2.0" ]
GetcuReone/FactFactory
FactFactory/MovieServiceExample/Facts/MoviePurchasePriceFact.cs
344
C#
using System; public enum DistanceToTargetType { None, FarFromTarget, NearByTarget, ReachedTarget }
11.4
33
0.72807
[ "MIT" ]
corefan/mobahero_src
DistanceToTargetType.cs
114
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; class TriangleSurface { static void Main() { double a = double.Parse(Console.ReadLine()); double b = double.Parse(Console.ReadLine()); double c = double.Parse(Console.ReadLine()); double h = double.Parse(Console.ReadLine()); double angle = Convert.ToDouble((Math.PI * 90) / 180); SurfaceBySideAndAttitude(a, h); SurfaceByThreeSides(a, b, c); SurfaceByTwoSidesAndAngleBetweenThem(a, b, angle); } static void SurfaceBySideAndAttitude(double side, double att) { double surface = (side * att) / 2; Console.WriteLine("Surface of the triangle by given side and attitude to it: {0}sm", surface); } static void SurfaceByThreeSides(double s1, double s2, double s3) { double p = (s1 + s2 + s3) / 2; double surface = Convert.ToDouble(Math.Sqrt(p * (p - s1) * (p - s2) * (p - s3))); Console.WriteLine("Surface of the triangle by given all its sides: {0}sm", surface); } static void SurfaceByTwoSidesAndAngleBetweenThem(double s1, double s2, double ang) { double surface = Convert.ToDouble((s1 * s2 * Math.Sin(ang)) / 2); Console.WriteLine("Surface of the triangle by given two sides and angle between them: {0}sm", surface); } }
39.2
111
0.642128
[ "MIT" ]
snukal/All-Telerik-Homeworks
C#2/Using-Classes-and-Objects/Triangle surface/4. Triangle surface.cs
1,374
C#
using Esri.ArcGISRuntime.Controls; using Esri.ArcGISRuntime.Geometry; using Esri.ArcGISRuntime.Layers; using Esri.ArcGISRuntime.Symbology; using Esri.ArcGISRuntime.Tasks.Query; using System; using System.Collections.Generic; using System.Linq; using System.Windows; using System.Windows.Controls; namespace ArcGISRuntimeSDKDotNet_DesktopSamples.Samples { /// <summary> /// This sample demonstrates how to search your data using the find task. The sample displays the results on the map and in tabular list view. /// </summary> /// <title>Find</title> /// <category>Tasks</category> /// <subcategory>Query</subcategory> public partial class FindTaskSample : UserControl { private Symbol _markerSymbol; private Symbol _lineSymbol; private Symbol _fillSymbol; private GraphicsOverlay _graphicsOverlay; /// <summary>Construct Find sample control</summary> public FindTaskSample() { InitializeComponent(); _markerSymbol = layoutGrid.Resources["MarkerSymbol"] as Symbol; _lineSymbol = layoutGrid.Resources["LineSymbol"] as Symbol; _fillSymbol = layoutGrid.Resources["FillSymbol"] as Symbol; _graphicsOverlay = MyMapView.GraphicsOverlays["graphicsOverlay"]; } // Find map service items with entered information in given fields private async void FindButton_Click(object sender, RoutedEventArgs e) { try { progress.Visibility = Visibility.Visible; resultsGrid.Visibility = Visibility.Collapsed; resultsGrid.ItemsSource = null; _graphicsOverlay.Graphics.Clear(); FindTask findTask = new FindTask( new Uri("http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Specialty/ESRI_StatesCitiesRivers_USA/MapServer")); var param = new FindParameters() { LayerIDs = new List<int> { 0, 1, 2 }, SearchFields = new List<string> { "CITY_NAME", "NAME", "SYSTEM", "STATE_ABBR", "STATE_NAME" }, ReturnGeometry = true, SpatialReference = MyMapView.SpatialReference, SearchText = txtFind.Text }; var findResults = await findTask.ExecuteAsync(param); if (findResults != null && findResults.Results.Count > 0) { resultsGrid.ItemsSource = findResults.Results; resultsGrid.Visibility = Visibility.Visible; } } catch (Exception ex) { MessageBox.Show(ex.Message, "Find Sample"); } finally { progress.Visibility = Visibility.Collapsed; } } // Highlight the selected grid view item on the map private void resultsGrid_SelectionChanged(object sender, SelectionChangedEventArgs e) { _graphicsOverlay.Graphics.Clear(); if (e.AddedItems != null && e.AddedItems.Count > 0) { var findItem = e.AddedItems.OfType<FindItem>().FirstOrDefault(); if (findItem != null) _graphicsOverlay.Graphics.Add(new Graphic(findItem.Feature.Geometry, ChooseGraphicSymbol(findItem.Feature.Geometry))); } } // Select a marker / line / fill symbol based on geometry type private Symbol ChooseGraphicSymbol(Geometry geometry) { if (geometry == null) return null; Symbol symbol = null; switch (geometry.GeometryType) { case GeometryType.Point: case GeometryType.Multipoint: symbol = _markerSymbol; break; case GeometryType.Polyline: symbol = _lineSymbol; break; case GeometryType.Polygon: case GeometryType.Envelope: symbol = _fillSymbol; break; } return symbol; } } }
35.601695
146
0.584147
[ "Apache-2.0" ]
mikedorais/arcgis-runtime-samples-dotnet
src/Desktop/ArcGISRuntimeSDKDotNet_DesktopSamples/Samples/QueryTasks/FindTaskSample.xaml.cs
4,203
C#
using System; using Zenject; using MessagePipe.Zenject; namespace MessagePipe { public static partial class DiContainerExtensions { // original is ServiceCollectionExtensions, trimed openegenerics register. public static MessagePipeOptions BindMessagePipe(this DiContainer builder) { return BindMessagePipe(builder, _ => { }); } public static MessagePipeOptions BindMessagePipe(this DiContainer builder, Action<MessagePipeOptions> configure) { MessagePipeOptions options = null; var proxy = new DiContainerProxy(builder); proxy.AddMessagePipe(x => { configure(x); options = x; // Zenject 6 does not allow regsiter multiple singleton, it causes annoying error. // https://github.com/modesttree/Zenject#upgrade-guide-for-zenject-6 // so force use Scoped. options.InstanceLifetime = (options.InstanceLifetime == InstanceLifetime.Singleton) ? InstanceLifetime.Scoped : options.RequestHandlerLifetime; options.RequestHandlerLifetime = (options.RequestHandlerLifetime == InstanceLifetime.Singleton) ? InstanceLifetime.Scoped : options.RequestHandlerLifetime; }); builder.Bind<IServiceProvider>().To<DiContainerProviderProxy>().AsCached(); return options; } /// <summary>Register IPublisher[TMessage] and ISubscriber[TMessage](includes Async/Buffered) to container builder.</summary> public static DiContainer BindMessageBroker<TMessage>(this DiContainer builder, MessagePipeOptions options) { var lifetime = options.InstanceLifetime; var services = new DiContainerProxy(builder); // keyless PubSub services.Add(typeof(MessageBrokerCore<TMessage>), lifetime); services.Add(typeof(IPublisher<TMessage>), typeof(MessageBroker<TMessage>), lifetime); services.Add(typeof(ISubscriber<TMessage>), typeof(MessageBroker<TMessage>), lifetime); // keyless PubSub async services.Add(typeof(AsyncMessageBrokerCore<TMessage>), lifetime); services.Add(typeof(IAsyncPublisher<TMessage>), typeof(AsyncMessageBroker<TMessage>), lifetime); services.Add(typeof(IAsyncSubscriber<TMessage>), typeof(AsyncMessageBroker<TMessage>), lifetime); // keyless buffered PubSub services.Add(typeof(BufferedMessageBrokerCore<TMessage>), lifetime); services.Add(typeof(IBufferedPublisher<TMessage>), typeof(BufferedMessageBroker<TMessage>), lifetime); services.Add(typeof(IBufferedSubscriber<TMessage>), typeof(BufferedMessageBroker<TMessage>), lifetime); // keyless buffered PubSub async services.Add(typeof(BufferedAsyncMessageBrokerCore<TMessage>), lifetime); services.Add(typeof(IBufferedAsyncPublisher<TMessage>), typeof(BufferedAsyncMessageBroker<TMessage>), lifetime); services.Add(typeof(IBufferedAsyncSubscriber<TMessage>), typeof(BufferedAsyncMessageBroker<TMessage>), lifetime); return builder; } /// <summary>Register IPublisher[TKey, TMessage] and ISubscriber[TKey, TMessage](includes Async) to container builder.</summary> public static DiContainer BindMessageBroker<TKey, TMessage>(this DiContainer builder, MessagePipeOptions options) { var lifetime = options.InstanceLifetime; var services = new DiContainerProxy(builder); // keyed PubSub services.Add(typeof(MessageBrokerCore<TKey, TMessage>), lifetime); services.Add(typeof(IPublisher<TKey, TMessage>), typeof(MessageBroker<TKey, TMessage>), lifetime); services.Add(typeof(ISubscriber<TKey, TMessage>), typeof(MessageBroker<TKey, TMessage>), lifetime); // keyed PubSub async services.Add(typeof(AsyncMessageBrokerCore<TKey, TMessage>), lifetime); services.Add(typeof(IAsyncPublisher<TKey, TMessage>), typeof(AsyncMessageBroker<TKey, TMessage>), lifetime); services.Add(typeof(IAsyncSubscriber<TKey, TMessage>), typeof(AsyncMessageBroker<TKey, TMessage>), lifetime); return builder; } /// <summary>Register IRequestHandler[TRequest, TResponse](includes All) to container builder.</summary> public static DiContainer BindRequestHandler<TRequest, TResponse, THandler>(this DiContainer builder, MessagePipeOptions options) where THandler : IRequestHandler { var lifetime = options.RequestHandlerLifetime; var services = new DiContainerProxy(builder); services.Add(typeof(IRequestHandlerCore<TRequest, TResponse>), typeof(THandler), lifetime); if (!builder.HasBinding<IRequestHandler<TRequest, TResponse>>()) { services.Add(typeof(IRequestHandler<TRequest, TResponse>), typeof(RequestHandler<TRequest, TResponse>), lifetime); services.Add(typeof(IRequestAllHandler<TRequest, TResponse>), typeof(RequestAllHandler<TRequest, TResponse>), lifetime); } return builder; } /// <summary>Register IAsyncRequestHandler[TRequest, TResponse](includes All) to container builder.</summary> public static DiContainer BindAsyncRequestHandler<TRequest, TResponse, THandler>(this DiContainer builder, MessagePipeOptions options) where THandler : IAsyncRequestHandler { var lifetime = options.RequestHandlerLifetime; var services = new DiContainerProxy(builder); services.Add(typeof(IAsyncRequestHandlerCore<TRequest, TResponse>), typeof(THandler), lifetime); if (!builder.HasBinding<IAsyncRequestHandler<TRequest, TResponse>>()) { services.Add(typeof(IAsyncRequestHandler<TRequest, TResponse>), typeof(AsyncRequestHandler<TRequest, TResponse>), lifetime); services.Add(typeof(IAsyncRequestAllHandler<TRequest, TResponse>), typeof(AsyncRequestAllHandler<TRequest, TResponse>), lifetime); } return builder; } public static DiContainer BindMessageHandlerFilter<T>(this DiContainer builder) where T : class, IMessageHandlerFilter { if (!builder.HasBinding<T>()) { builder.Bind<T>().AsTransient(); } return builder; } public static DiContainer BindAsyncMessageHandlerFilter<T>(this DiContainer builder) where T : class, IAsyncMessageHandlerFilter { if (!builder.HasBinding<T>()) { builder.Bind<T>().AsTransient(); } return builder; } public static DiContainer BindRequestHandlerFilter<T>(this DiContainer builder) where T : class, IRequestHandlerFilter { if (!builder.HasBinding<T>()) { builder.Bind<T>().AsTransient(); } return builder; } public static DiContainer BindAsyncRequestHandlerFilter<T>(this DiContainer builder) where T : class, IAsyncRequestHandlerFilter { if (!builder.HasBinding<T>()) { builder.Bind<T>().AsTransient(); } return builder; } } }
47.111801
146
0.647726
[ "MIT" ]
hadashiA/MessagePipe
src/MessagePipe.Unity/Assets/Plugins/MessagePipe.Zenject/Runtime/DiContainerExtensions.cs
7,585
C#
// © Anamnesis. // Licensed under the MIT license. namespace Anamnesis.Memory { using System; using System.Threading.Tasks; using Anamnesis.Connect; using Anamnesis.Services; public class ActorMemory : ActorBasicMemory { private const short RefreshDelay = 250; private short refreshDelay; private Task? refreshTask; private IntPtr? previousObjectKindAddressBeforeGPose; public enum RenderModes : int { Draw = 0, Unload = 2, } public enum AnimationModes : int { Normal = 0x3F, SlowMotion = 0x3E, } [Bind(0x008D)] public byte SubKind { get; set; } [Bind(0x00F0, BindFlags.Pointer)] public ActorModelMemory? ModelObject { get; set; } [Bind(0x0104)] public RenderModes RenderMode { get; set; } [Bind(0x01B4, BindFlags.ActorRefresh)] public int ModelType { get; set; } [Bind(0x01E2)] public byte ClassJob { get; set; } [Bind(0x07C4)] public bool IsAnimating { get; set; } [Bind(0x0C78)] public WeaponMemory? MainHand { get; set; } [Bind(0x0CE0)] public WeaponMemory? OffHand { get; set; } [Bind(0x0DB0)] public ActorEquipmentMemory? Equipment { get; set; } [Bind(0x0DD8)] public ActorCustomizeMemory? Customize { get; set; } [Bind(0x0F30)] public uint TargetAnimation { get; set; } [Bind(0x0F4C)] public uint NextAnimation { get; set; } [Bind(0x0FA7)] public AnimationModes AnimationMode { get; set; } [Bind(0x18B8)] public float Transparency { get; set; } public bool AutomaticRefreshEnabled { get; set; } = true; public bool IsRefreshing { get; set; } = false; public bool PendingRefresh { get; set; } = false; public bool IsPlayer => this.ModelObject != null && this.ModelObject.IsPlayer; public int ObjectKindInt { get => (int)this.ObjectKind; set => this.ObjectKind = (ActorTypes)value; } /// <summary> /// Refresh the actor to force the game to load any changed values for appearance. /// </summary> public void Refresh() { this.refreshDelay = RefreshDelay; if (this.refreshTask == null || this.refreshTask.IsCompleted) { this.refreshTask = Task.Run(this.RefreshTask); } } public override void Tick() { // Since writing is immadiate from poperties, we don't want to tick (read) anything // during a refresh. if (this.IsRefreshing || this.PendingRefresh) return; base.Tick(); } /// <summary> /// Refresh the actor to force the game to load any changed values for appearance. /// </summary> public async Task RefreshAsync() { if (this.IsRefreshing) return; if (!ActorRefreshService.Instance.CanRefresh) return; if (this.Address == IntPtr.Zero) return; try { Log.Information($"Begining actor refresh for actor address: {this.Address}"); this.IsRefreshing = true; if (AnamnesisConnectService.IsPenumbraConnected) { AnamnesisConnectService.PenumbraRedraw(this.Name); await Task.Delay(150); } else { await Task.Delay(16); if (this.ObjectKind == ActorTypes.Player) { this.ObjectKind = ActorTypes.BattleNpc; this.RenderMode = RenderModes.Unload; await Task.Delay(75); this.RenderMode = RenderModes.Draw; await Task.Delay(75); this.ObjectKind = ActorTypes.Player; this.RenderMode = RenderModes.Draw; } else { this.RenderMode = RenderModes.Unload; await Task.Delay(75); this.RenderMode = RenderModes.Draw; } await Task.Delay(150); } Log.Information($"Completed actor refresh for actor address: {this.Address}"); } catch (Exception ex) { Log.Error(ex, "Failed to refresh actor"); } finally { this.IsRefreshing = false; this.WriteDelayedBinds(); } this.RaisePropertyChanged(nameof(this.IsPlayer)); await Task.Delay(150); this.RaisePropertyChanged(nameof(this.IsPlayer)); } public void OnRetargeted() { GposeService gpose = GposeService.Instance; if (gpose.IsGpose && gpose.IsChangingState) { // Entering gpose if (this.ObjectKind == ActorTypes.Player) { this.previousObjectKindAddressBeforeGPose = this.GetAddressOfProperty(nameof(this.ObjectKind)); this.ObjectKind = ActorTypes.BattleNpc; // Sanity check that we do get turned back into a player Task.Run(async () => { await Task.Delay(3000); MemoryService.Write((IntPtr)this.previousObjectKindAddressBeforeGPose, ActorTypes.Player, "NPC face fix"); }); } } else if (gpose.IsGpose && !gpose.IsChangingState) { // Entered gpose if (this.previousObjectKindAddressBeforeGPose != null) { MemoryService.Write((IntPtr)this.previousObjectKindAddressBeforeGPose, ActorTypes.Player, "NPC face fix"); this.ObjectKind = ActorTypes.Player; } } } protected override void ActorRefresh(string propertyName) { if (!this.AutomaticRefreshEnabled) return; if (this.IsRefreshing) { // dont refresh because of a refresh! if (propertyName == nameof(this.ObjectKind) || propertyName == nameof(this.RenderMode)) { return; } } this.Refresh(); } protected override bool CanWrite(BindInfo bind) { if (this.IsRefreshing) { if (bind.Memory != this) { Log.Warning("Skipping Bind " + bind); // Do not allow writing of any properties form sub-memory while we are refreshing return false; } else { // do not allow writing of any properties except the ones needed for refresh during a refresh. return bind.Property.Name == nameof(this.ObjectKind) || bind.Property.Name == nameof(this.RenderMode); } } return base.CanWrite(bind); } private async Task RefreshTask() { // Double loops to handle case where a refresh delay was added // while the refresh was running while (this.refreshDelay > 0) { lock (this) this.PendingRefresh = true; while (this.refreshDelay > 0) { await Task.Delay(10); this.refreshDelay -= 10; } lock (this) this.PendingRefresh = false; await this.RefreshAsync(); } } } }
25.366667
112
0.666886
[ "MIT" ]
Maxunit/Anamnesis
Anamnesis/Memory/ActorMemory.cs
6,091
C#
using System; class SumDigits { static void Main(string[] args) { int number = int.Parse(Console.ReadLine()); int sum = 0; while (number > 0) { sum += number % 10; number = number / 10; } Console.WriteLine(sum); } }
16
51
0.473684
[ "MIT" ]
VladimirKyuranov/Programming-Basics-CSharp
HomeWorks/07-AdvancedLoops/09-SumDigits/SumDigits.cs
306
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.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.ImplementType; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ImplementAbstractClass { internal partial class AbstractImplementAbstractClassService<TClassSyntax> { private partial class Editor { private readonly Document _document; private readonly SemanticModel _model; private readonly State _state; public Editor( Document document, SemanticModel model, State state) { _document = document; _model = model; _state = state; } public async Task<Document> GetEditAsync(CancellationToken cancellationToken) { var unimplementedMembers = _state.UnimplementedMembers; var options = await _document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var propertyGenerationBehavior = options.GetOption(ImplementTypeOptions.PropertyGenerationBehavior); var memberDefinitions = GenerateMembers( unimplementedMembers, propertyGenerationBehavior, cancellationToken); var insertionBehavior = options.GetOption(ImplementTypeOptions.InsertionBehavior); var groupMembers = insertionBehavior == ImplementTypeInsertionBehavior.WithOtherMembersOfTheSameKind; return await CodeGenerator.AddMemberDeclarationsAsync( _document.Project.Solution, _state.ClassType, memberDefinitions, new CodeGenerationOptions( _state.Location.GetLocation(), autoInsertionLocation: groupMembers, sortMembers: groupMembers), cancellationToken).ConfigureAwait(false); } private ImmutableArray<ISymbol> GenerateMembers( ImmutableArray<(INamedTypeSymbol type, ImmutableArray<ISymbol> members)> unimplementedMembers, ImplementTypePropertyGenerationBehavior propertyGenerationBehavior, CancellationToken cancellationToken) { return unimplementedMembers.SelectMany(t => t.members) .Select(m => GenerateMember(m, propertyGenerationBehavior, cancellationToken)) .WhereNotNull() .ToImmutableArray(); } private ISymbol GenerateMember( ISymbol member, ImplementTypePropertyGenerationBehavior propertyGenerationBehavior, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // Check if we need to add 'unsafe' to the signature we're generating. var syntaxFacts = _document.Project.LanguageServices.GetService<ISyntaxFactsService>(); var addUnsafe = member.IsUnsafe() && !syntaxFacts.IsUnsafeContext(_state.Location); return GenerateMember(member, addUnsafe, propertyGenerationBehavior, cancellationToken); } private ISymbol GenerateMember( ISymbol member, bool addUnsafe, ImplementTypePropertyGenerationBehavior propertyGenerationBehavior, CancellationToken cancellationToken) { var modifiers = new DeclarationModifiers(isOverride: true, isUnsafe: addUnsafe); var accessibility = member.ComputeResultantAccessibility(_state.ClassType); switch (member) { case IMethodSymbol method: return GenerateMethod(method, modifiers, accessibility, cancellationToken); case IPropertySymbol property: return GenerateProperty(property, modifiers, accessibility, propertyGenerationBehavior, cancellationToken); case IEventSymbol @event: return CodeGenerationSymbolFactory.CreateEventSymbol( @event, accessibility: accessibility, modifiers: modifiers); } return null; } private ISymbol GenerateMethod( IMethodSymbol method, DeclarationModifiers modifiers, Accessibility accessibility, CancellationToken cancellationToken) { var syntaxFacts = _document.Project.LanguageServices.GetService<ISyntaxFactsService>(); var syntaxFactory = _document.Project.LanguageServices.GetService<SyntaxGenerator>(); var throwingBody = syntaxFactory.CreateThrowNotImplementedStatementBlock( _model.Compilation); method = method.EnsureNonConflictingNames(_state.ClassType, syntaxFacts, cancellationToken); return CodeGenerationSymbolFactory.CreateMethodSymbol( method, accessibility: accessibility, modifiers: modifiers, statements: throwingBody); } private IPropertySymbol GenerateProperty( IPropertySymbol property, DeclarationModifiers modifiers, Accessibility accessibility, ImplementTypePropertyGenerationBehavior propertyGenerationBehavior, CancellationToken cancellationToken) { if (property.GetMethod == null) { // Can't generate an auto-prop for a setter-only property. propertyGenerationBehavior = ImplementTypePropertyGenerationBehavior.PreferThrowingProperties; } var syntaxFactory = _document.Project.LanguageServices.GetService<SyntaxGenerator>(); var accessorBody = propertyGenerationBehavior == ImplementTypePropertyGenerationBehavior.PreferAutoProperties ? default(ImmutableArray<SyntaxNode>) : syntaxFactory.CreateThrowNotImplementedStatementBlock(_model.Compilation); var getMethod = ShouldGenerateAccessor(property.GetMethod) ? CodeGenerationSymbolFactory.CreateAccessorSymbol( property.GetMethod, attributes: default(ImmutableArray<AttributeData>), accessibility: property.GetMethod.ComputeResultantAccessibility(_state.ClassType), statements: accessorBody) : null; var setMethod = ShouldGenerateAccessor(property.SetMethod) ? CodeGenerationSymbolFactory.CreateAccessorSymbol( property.SetMethod, attributes: default(ImmutableArray<AttributeData>), accessibility: property.SetMethod.ComputeResultantAccessibility(_state.ClassType), statements: accessorBody) : null; return CodeGenerationSymbolFactory.CreatePropertySymbol( property, accessibility: accessibility, modifiers: modifiers, getMethod: getMethod, setMethod: setMethod); } private bool ShouldGenerateAccessor(IMethodSymbol method) => method != null && _state.ClassType.FindImplementationForAbstractMember(method) == null; } } }
47.238372
160
0.616369
[ "Apache-2.0" ]
amcasey/roslyn
src/Features/Core/Portable/ImplementAbstractClass/AbstractImplementAbstractClassService.Editor.cs
8,125
C#
using System; using System.Collections.Generic; using System.IO; namespace MNISTLoader { public class MNISTDigitLoader { public static MNISTDigitData LoadDigits(string imageIdxFilePath, string imageLabelIdxPath) { if (!File.Exists(imageIdxFilePath) || !File.Exists(imageLabelIdxPath)) { throw new FileNotFoundException(); } var digitData = new MNISTDigitData(); using (var imageReader = new BinaryReader(File.Open(imageIdxFilePath, FileMode.Open))) { using var labelReader = new BinaryReader(File.Open(imageLabelIdxPath, FileMode.Open)); var imagesFileMagicNumber = imageReader.ReadInt32BE(); var labelsFileMagicNumber = labelReader.ReadInt32BE(); var numberOfImages = imageReader.ReadInt32BE(); var numberOfLabels = labelReader.ReadInt32BE(); if (numberOfLabels != numberOfImages) { throw new Exception("Nums of labels and images are different!"); } var singleImageHeight = imageReader.ReadInt32BE(); var singleImageWidth = imageReader.ReadInt32BE(); digitData.ImageCount = numberOfImages; digitData.SingleImageHeight = singleImageHeight; digitData.SingleImageWidth = singleImageWidth; var pixelsPerImageCount = singleImageWidth * singleImageHeight; for (var i = 0; i < numberOfImages; i++) { var imageBytes = imageReader.ReadBytes(pixelsPerImageCount); var imageLabel = labelReader.ReadByte(); digitData.Images.Add(new Image { Height = digitData.SingleImageHeight, Width = digitData.SingleImageWidth, Pixels = imageBytes, Label = imageLabel }); } } return digitData; } } public static class BinaryReaderExtensions { public static int ReadInt32BE(this BinaryReader reader) { var data = reader.ReadBytes(4); Array.Reverse(data); return BitConverter.ToInt32(data, 0); } } public class MNISTDigitData { public int ImageCount { get; set; } public int SingleImageHeight { get; set; } public int SingleImageWidth { get; set; } /// <summary> /// Pixels are organized row-wise. Pixel values are 0 to 255. 0 means background (white), 255 means foreground (black). /// </summary> public List<Image> Images { get; set; } public MNISTDigitData() { Images = new List<Image>(); } } public class Image { public byte[] Pixels { get; set; } public byte Label { get; set; } public int Width { get; set; } public int Height { get; set; } } }
32.778947
127
0.552023
[ "MIT" ]
josipGrgic11235/ML.NET-Playground
DigitRecognition/MNISTLoader/MNISTDigitLoader.cs
3,116
C#
using NServiceBus; using NServiceBus.ProtoBuf; using ProtoBuf; public class EndToEnd { static ManualResetEvent manualResetEvent = new(false); string endpointName = "EndToEnd"; [Fact] public async Task Write() { var configuration = new EndpointConfiguration(endpointName); configuration.UsePersistence<LearningPersistence>(); configuration.UseTransport<LearningTransport>(); configuration.UseSerialization<ProtoBufSerializer>(); var typesToScan = TypeScanner.NestedTypes<EndToEnd>(); configuration.SetTypesToScan(typesToScan); var endpointInstance = await Endpoint.Start(configuration); var message = new MessageToSend { Property = "PropertyValue" }; await endpointInstance.SendLocal(message); manualResetEvent.WaitOne(); await endpointInstance.Stop(); } [ProtoContract] public class MessageToSend : IMessage { [ProtoMember(1)] public string? Property { get; set; } } class MessageHandler : IHandleMessages<MessageToSend> { public Task Handle(MessageToSend message, IMessageHandlerContext context) { manualResetEvent.Set(); return Task.CompletedTask; } } }
28.434783
81
0.654434
[ "MIT" ]
SimonCropp/NServiceBus.ProtoBuf
src/Tests/EndToEnd.cs
1,310
C#
using Gameloop.Vdf; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using System.Reflection; using System.Windows.Forms; namespace AltInjector { public partial class Manage : Form { private JObject JsonRepostiory = null; private JObject _versionSelected = null; private string _productSelected = "", _branchSelected = "", _tmpDownloadURL = "", _tmpDownloadPath = "", _tmpArchiveName = "", _tmpExtractionPath = Path.GetTempPath() + "\\SK-TinyInjector", _SpecialKRoot = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\My Mods\\SpecialK", _tmpDownloadRoot = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\My Mods\\SpecialK_Archives", InstallingVersion = "", InstallingBranch = "", TargetInstallPath = ""; // Used for Local + Steam installs private bool LocalInstall64bit = false; private ApiDialogResult LocalInstallAPI = ApiDialogResult.None; private static readonly NLog.Logger AppLog = NLog.LogManager.GetCurrentClassLogger(); private WebClient OngoingDownload = null; private bool CancelOperation = false; private List<string> SteamLibraries = new List<string>(); public bool ActiveOperation { get; private set; } public Manage() { InitializeComponent(); lCurrentBranch.Text = ""; lCurrentVersion.Text = ""; Icon = Properties.Resources.pokeball; Directory.CreateDirectory(_tmpDownloadRoot); Log("**WARNING**\r\nThis is still a work in progress, and isn't recommended for mainstream use yet!\r\nUse at your own risk!\r\n"); Log("Detecting Steam install folders..."); var SteamInstallPath = Microsoft.Win32.Registry.GetValue("HKEY_CURRENT_USER\\Software\\Valve\\Steam", "SteamPath", "not found"); if (SteamInstallPath != null && SteamInstallPath.ToString() != "not found") { string primaryLibrary = SteamInstallPath.ToString().Replace("/", "\\"); Log("Primary library: " + primaryLibrary); SteamLibraries.Add(primaryLibrary); if (File.Exists(SteamInstallPath.ToString() + "\\steamapps\\libraryfolders.vdf")) { Gameloop.Vdf.Linq.VProperty vProperty = VdfConvert.Deserialize(File.ReadAllText(SteamInstallPath.ToString() + "\\steamapps\\libraryfolders.vdf")); foreach (var item in vProperty.Value.Children()) { if (!IsNumeric(item.Key)) continue; Log("Additional library: " + item.Value); SteamLibraries.Add(item.Value.ToString()); } } } else { Log("Steam does not seem to be installed.\r\n"); } Log("Downloading repository data..."); using (WebClient wc = new WebClient()) { wc.DownloadProgressChanged += OnDownloadProgressChanged; wc.DownloadFileCompleted += (object sender, AsyncCompletedEventArgs e) => { tsProgress.Visible = false; if (e.Cancelled || e.Error != null) { if (e.Cancelled) { Log("Download cancelled!"); } else if (e.Error != null) { Log("Download failed!"); Log("Error message: " + e.Error.Message + "\r\n"); } Log("Cleaning up incomplete file repository_new.json"); if (File.Exists("repository_new.json")) File.Delete("repository_new.json"); Log("Download failed. Falling back to local repository copy."); Log("Error message: " + e.Error.Message + "\r\n"); } else { File.Delete("repository.json"); File.Move("repository_new.json", "repository.json"); } Log("Reading repository data..."); JsonRepostiory = JObject.Parse(File.ReadAllText("repository.json")); foreach (KeyValuePair<string, JToken> product in JsonRepostiory) { cbProducts.Items.Add(product.Key); } Log("Ready to be used!\r\n"); tbLog.Enabled = true; lSelectProduct.Enabled = true; lSelectBranch.Enabled = true; lSelectVersion.Enabled = true; cbProducts.Enabled = true; cbBranches.Enabled = true; cbVersions.Enabled = true; tbSelectedProduct.Enabled = true; tbSelectedBranch.Enabled = true; tbSelectedVersion.Enabled = true; }; wc.DownloadFileAsync(new Uri("https://raw.githubusercontent.com/Idearum/SK-AltInjector/master/64bitMainApp/repository.json"), "repository_new.json"); } } /* From https://stackoverflow.com/questions/197951/how-can-i-determine-for-which-platform-an-executable-is-compiled */ // the enum of known pe file types public enum FilePEType : ushort { IMAGE_FILE_MACHINE_UNKNOWN = 0x0, IMAGE_FILE_MACHINE_AM33 = 0x1d3, IMAGE_FILE_MACHINE_AMD64 = 0x8664, IMAGE_FILE_MACHINE_ARM = 0x1c0, IMAGE_FILE_MACHINE_EBC = 0xebc, IMAGE_FILE_MACHINE_I386 = 0x14c, IMAGE_FILE_MACHINE_IA64 = 0x200, IMAGE_FILE_MACHINE_M32R = 0x9041, IMAGE_FILE_MACHINE_MIPS16 = 0x266, IMAGE_FILE_MACHINE_MIPSFPU = 0x366, IMAGE_FILE_MACHINE_MIPSFPU16 = 0x466, IMAGE_FILE_MACHINE_POWERPC = 0x1f0, IMAGE_FILE_MACHINE_POWERPCFP = 0x1f1, IMAGE_FILE_MACHINE_R4000 = 0x166, IMAGE_FILE_MACHINE_SH3 = 0x1a2, IMAGE_FILE_MACHINE_SH3DSP = 0x1a3, IMAGE_FILE_MACHINE_SH4 = 0x1a6, IMAGE_FILE_MACHINE_SH5 = 0x1a8, IMAGE_FILE_MACHINE_THUMB = 0x1c2, IMAGE_FILE_MACHINE_WCEMIPSV2 = 0x169, } // pass the path to the file and check the return public static FilePEType GetFilePE(string path) { FilePEType pe = new FilePEType(); pe = FilePEType.IMAGE_FILE_MACHINE_UNKNOWN; if (File.Exists(path)) { using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { byte[] data = new byte[4096]; fs.Read(data, 0, 4096); ushort result = BitConverter.ToUInt16(data, BitConverter.ToInt32(data, 60) + 4); try { pe = (FilePEType)result; } catch (Exception) { pe = FilePEType.IMAGE_FILE_MACHINE_UNKNOWN; } } } return pe; } // From https://stackoverflow.com/questions/894263/identify-if-a-string-is-a-number public static bool IsNumeric(object Expression) { double retNum; bool isNum = Double.TryParse(Convert.ToString(Expression), System.Globalization.NumberStyles.Any, System.Globalization.NumberFormatInfo.InvariantInfo, out retNum); return isNum; } private void Log(string message) { tsStatus.Text = message; tbLog.Text += message + "\r\n"; AppLog.Info(message.Replace("\r\n\r\n", " ").Replace("\r\n", " ")); } private void OnDownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e) { if (!tsProgress.IsDisposed) { tsProgress.Value = e.ProgressPercentage; tsProgress.Visible = true; } } private void CbProducts_SelectedIndexChanged(object sender, System.EventArgs e) { bAutomatic.Enabled = false; bManual.Enabled = false; cbVersions.Items.Clear(); // Clear versions first cbBranches.Items.Clear(); // Next clear branches _productSelected = cbProducts.SelectedItem.ToString(); /* Populate Branches */ foreach (JToken branch in JsonRepostiory[_productSelected]["Branches"]) { string branchKey = branch.ToObject<JProperty>().Name; cbBranches.Items.Add(branchKey); } /* Populate Branches END */ // If global install, try to detect current installed branch if (_productSelected == "Global install") { cbCleanInstall.Enabled = true; if (File.Exists(_SpecialKRoot + "\\Version\\installed.ini")) { string[] InstalledINI = File.ReadAllLines(_SpecialKRoot + "\\Version\\installed.ini"); if (InstalledINI.Length >= 3) { string installedBranch = (InstalledINI[2].Length >= 7) ? InstalledINI[2].Substring(7) : ""; string installedPackage = (InstalledINI[1].Length >= 15) ? InstalledINI[1].Substring(15) : ""; switch (installedBranch) { case "Latest": installedBranch = "Main"; break; case "Compatibility": installedBranch = "0.9.x"; break; case "Ancient": installedBranch = "0.8.x"; break; } Log("Detecting existing install of the global injector:"); Log("Branch: " + installedBranch); lCurrentBranch.Text = installedBranch; if (installedPackage != "") { JToken version = JsonRepostiory.SelectToken("$.['" + _productSelected + "'].Versions[?(@.InstallPackage == '" + installedPackage + "')]"); if (version != null) { lCurrentVersion.Text = version["Name"].ToString(); Log("Version: " + lCurrentVersion.Text + "\r\n"); } if (installedBranch != "") cbBranches.SelectedItem = installedBranch; } else { Log("Version: Could not detect version.\r\n"); } } } } else { // For now, Clean Install option only available for global installs. cbCleanInstall.Checked = false; cbCleanInstall.Enabled = false; lCurrentBranch.Text = ""; lCurrentVersion.Text = ""; if (cbBranches.Items.Count > 0) { cbBranches.SelectedIndex = 0; } } tbSelectedProduct.Text = JsonRepostiory[_productSelected]["Description"].ToString(); } private void ClickedManual(object sender, EventArgs e) { if (ActiveOperation) return; _tmpDownloadURL = _versionSelected["Archive"].ToString(); _tmpArchiveName = _tmpDownloadURL.Split('/').Last(); _tmpDownloadPath = _tmpDownloadRoot + "\\" + _tmpArchiveName; switch (bManual.Text) { case "Local (game-specific)": PerformLocalInstall(); break; case "Manual": break; default: Log("Unsupported install method!"); break; } } private void PerformLocalInstall() { ActiveOperation = true; /* * 1. Browse for appropriate executable. * 2. Download and extract Special K archive to a dummy folder. * 3. Detect 32-bit or 64-bit from the file executable. * 4. Prompt user about API support (might be able to be automated in the future?) * 5. Move appropriate SpecialK32/64.dll files to the target folder. * */ ApiDialog apiDialog = new ApiDialog(); OpenFileDialog fileDialog = new OpenFileDialog { Filter = "Game executables (*.exe)|*.exe", Title = "Browse for game executable", CheckFileExists = true, CheckPathExists = true, Multiselect = false, ValidateNames = true, RestoreDirectory = true }; if(fileDialog.ShowDialog() == DialogResult.OK && apiDialog.ShowDialog() == DialogResult.OK) { LocalInstallAPI = apiDialog.Api; Log("Attempting to install local (game-specific) wrapper DLLs for " + fileDialog.FileName); FilePEType type = GetFilePE(fileDialog.FileName); if (type == FilePEType.IMAGE_FILE_MACHINE_AMD64) LocalInstall64bit = true; // 64-bit else if (type == FilePEType.IMAGE_FILE_MACHINE_I386) LocalInstall64bit = false; // 32-bit, or AnyCPU for .NET-based games else Log("Unknown executable architecture."); // Unknown TargetInstallPath = Path.GetDirectoryName(fileDialog.FileName); bool fileExists = File.Exists(_tmpDownloadPath); bool cancel = false; if (fileExists) { Log("A file called " + _tmpArchiveName + " was found in the downloads folder. Prompting user on how to proceed."); switch (MessageBox.Show("A file called " + _tmpArchiveName + " was found in the downloads folder.\r\nDo you want to use that one?\r\n\r\nClicking 'No' will redownload the file from the Internet.", "Found local file for selected version", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button3)) { case DialogResult.Yes: Log("User chose to reuse the local copy found."); break; case DialogResult.No: fileExists = false; Log("User chose to redownload the archive from the Internet."); break; case DialogResult.Cancel: cancel = true; ActiveOperation = false; Log("User canceled the install process."); break; } } if (cancel == false) { if (fileExists == false) { Log("Downloading " + _tmpDownloadURL); using (OngoingDownload = new WebClient()) { OngoingDownload.DownloadProgressChanged += OnDownloadProgressChanged; OngoingDownload.DownloadFileCompleted += (object sender, AsyncCompletedEventArgs e) => { if (!tsProgress.IsDisposed) { tsProgress.Visible = false; } if (e.Cancelled || e.Error != null) { if (e.Cancelled) { Log("Download cancelled!"); } else if (e.Error != null) { Log("Download failed!"); Log("Error message: " + e.Error.Message + "\r\n"); } Log("Cleaning up incomplete file " + _tmpDownloadPath); if (File.Exists(_tmpDownloadPath)) File.Delete(_tmpDownloadPath); ActiveOperation = false; CancelOperation = true; OngoingDownload.Dispose(); OngoingDownload = null; return; } Log("Download completed!"); FinalizeLocalInstall(); OngoingDownload.Dispose(); OngoingDownload = null; }; OngoingDownload.DownloadFileAsync(new Uri(_tmpDownloadURL), _tmpDownloadPath); } } else { FinalizeLocalInstall(); } } } else { ActiveOperation = CancelOperation = false; } } private void FinalizeLocalInstall() { if (CancelOperation) { ActiveOperation = CancelOperation = false; return; } try { string DLLFileName = (LocalInstall64bit) ? "SpecialK64.dll" : "SpecialK32.dll"; string TargetFileName = LocalInstallAPI.ToString().ToLower() + ".dll"; Directory.CreateDirectory(_tmpExtractionPath); Log("Extracting temporary files to " + _tmpExtractionPath); ExtractFile(_tmpDownloadPath, _tmpExtractionPath, DLLFileName); if (File.Exists(_tmpExtractionPath + "\\" + DLLFileName)) { if (File.Exists(TargetInstallPath + "\\" + TargetFileName)) { Log(TargetInstallPath + "\\" + TargetFileName + " already exists. Prompting user on how to proceed."); switch(MessageBox.Show(TargetInstallPath + "\\" + TargetFileName + " already exists.\r\n\r\nAre you sure you want to overwrite it?", "File already exists", MessageBoxButtons.YesNo, MessageBoxIcon.Question)) { case DialogResult.Yes: Log("User decided to overwrite the existing file."); File.Copy(_tmpExtractionPath + "\\" + DLLFileName, TargetInstallPath + "\\" + TargetFileName, true); Log("Copied " + DLLFileName + " to " + TargetInstallPath + "\\" + TargetFileName); break; case DialogResult.No: CancelOperation = true; Log("User decided to abort the installation!"); break; } // Fixes issue with window appearing behind another application. BringToFront(); } else { File.Copy(_tmpExtractionPath + "\\" + DLLFileName, TargetInstallPath + "\\" + TargetFileName); Log("Copied " + _tmpExtractionPath + "\\" + DLLFileName + " to " + TargetInstallPath + "\\" + TargetFileName); } // Remove existing install if 'Clean Install' is checked if (cbCleanInstall.Checked && File.Exists(TargetInstallPath + "\\" + LocalInstallAPI.ToString().ToLower() + ".ini") && !CancelOperation) { Log("Removing existing config file..."); File.Delete(TargetInstallPath + "\\" + LocalInstallAPI.ToString().ToLower() + ".ini"); } } else { Log("Failed to locate appropriate DLL file in the extracted files!"); } } catch { } Log("Cleaning up temporary files..."); Directory.Delete(_tmpExtractionPath, true); LocalInstallAPI = ApiDialogResult.None; LocalInstall64bit = false; TargetInstallPath = ""; ActiveOperation = CancelOperation = false; Log("\r\nInstallation finished!\r\n"); } private void ClickedAutomatic(object sender, EventArgs e) { if (ActiveOperation) return; _tmpDownloadURL = _versionSelected["Archive"].ToString(); _tmpArchiveName = _tmpDownloadURL.Split('/').Last(); _tmpDownloadPath = _tmpDownloadRoot + "\\" + _tmpArchiveName; switch (bAutomatic.Text) { case "Global": PerformGlobalInstall(); break; case "Automatic (Steam)": PerformSteamInstall(); break; default: Log("Unsupported install method!"); break; } } private void PerformSteamInstall() { ActiveOperation = true; string SteamAppID = ""; string RelativePath = ""; try { SteamAppID = JsonRepostiory[_productSelected]["SteamAppID"].ToString(); } catch (Exception ex) { Log("JSON object missing RelativePath parameter!"); ActiveOperation = false; throw ex; } try { RelativePath = JsonRepostiory[_productSelected]["RelativePath"].ToString(); } catch { Log("JSON object missing RelativePath parameter!"); RelativePath = ""; } string AppManifest = ""; string LibraryRoot = ""; foreach (string library in SteamLibraries) { string path = library + "\\steamapps\\appmanifest_" + SteamAppID + ".acf"; if (File.Exists(path)) { AppManifest = path; LibraryRoot = library; Log("AppManifest file detected at " + AppManifest + "."); break; } } if (AppManifest != "") { Gameloop.Vdf.Linq.VProperty vProperty = VdfConvert.Deserialize(File.ReadAllText(AppManifest)); string InstallDirectory = ""; try { InstallDirectory = vProperty.Value["installdir"].ToString(); } catch { } if (InstallDirectory != "") { TargetInstallPath = LibraryRoot + "\\steamapps\\common\\" + InstallDirectory + RelativePath; bool fileExists = File.Exists(_tmpDownloadPath); bool cancel = false; if (fileExists) { Log("A file called " + _tmpArchiveName + " was found in the downloads folder. Prompting user on how to proceed."); switch (MessageBox.Show("A file called " + _tmpArchiveName + " was found in the downloads folder.\r\nDo you want to use that one?\r\n\r\nClicking 'No' will redownload the file from the Internet.", "Found local file for selected version", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button3)) { case DialogResult.Yes: Log("User chose to reuse the local copy found."); break; case DialogResult.No: fileExists = false; Log("User chose to redownload the archive from the Internet."); break; case DialogResult.Cancel: cancel = true; ActiveOperation = false; Log("User canceled the install process."); break; } } if (cancel == false) { if (fileExists == false) { Log("Downloading " + _tmpDownloadURL); using (OngoingDownload = new WebClient()) { OngoingDownload.DownloadProgressChanged += OnDownloadProgressChanged; OngoingDownload.DownloadFileCompleted += (object sender, AsyncCompletedEventArgs e) => { if (!tsProgress.IsDisposed) { tsProgress.Visible = false; } if (e.Cancelled || e.Error != null) { if (e.Cancelled) { Log("Download cancelled!"); } else if (e.Error != null) { Log("Download failed!"); Log("Error message: " + e.Error.Message + "\r\n"); } Log("Cleaning up incomplete file " + _tmpDownloadPath); if (File.Exists(_tmpDownloadPath)) File.Delete(_tmpDownloadPath); ActiveOperation = false; CancelOperation = true; OngoingDownload.Dispose(); OngoingDownload = null; return; } Log("Download completed!"); FinalizeSteamInstall(); OngoingDownload.Dispose(); OngoingDownload = null; }; OngoingDownload.DownloadFileAsync(new Uri(_tmpDownloadURL), _tmpDownloadPath); } } else { FinalizeSteamInstall(); } } else { ActiveOperation = CancelOperation = false; } } } ActiveOperation = false; } private void FinalizeSteamInstall() { if (CancelOperation) { ActiveOperation = CancelOperation = false; return; } Directory.CreateDirectory(TargetInstallPath); Log("Extracting files to " + TargetInstallPath); ExtractFile(_tmpDownloadPath, TargetInstallPath); TargetInstallPath = ""; ActiveOperation = CancelOperation = false; Log("\r\nInstallation finished!\r\n"); } private void CbBranches_SelectedIndexChanged(object sender, EventArgs e) { _versionSelected = null; // Reset selected version cbVersions.Items.Clear(); // Clear versions tbSelectedVersion.Text = ""; _branchSelected = cbBranches.SelectedItem.ToString(); tbSelectedBranch.Text = JsonRepostiory[_productSelected]["Branches"][_branchSelected].ToString(); /* Populate Versions */ string token = "$.['" + _productSelected + "'].Versions[?(@.Branches[?(@ == '" + _branchSelected + "')])]"; // Fetches all versions applicable for the selected branch IEnumerable<JToken> versions = JsonRepostiory.SelectTokens(token); foreach (JToken item in versions) { cbVersions.Items.Add(item["Name"].ToString()); } if (cbVersions.Items.Count > 0) { /* Enable Buttons */ foreach (JToken method in JsonRepostiory[_productSelected]["Install"]) { switch (method.ToString()) { case "Global": // If global install, try to select current installed version if (lCurrentVersion.Text != "") { cbVersions.SelectedItem = lCurrentVersion.Text; } bAutomatic.Enabled = true; bAutomatic.Text = "Global"; bManual.Enabled = true; bManual.Text = "Local (game-specific)"; break; case "Steam": bAutomatic.Enabled = true; bAutomatic.Text = "Automatic (Steam)"; break; case "Manual": bManual.Enabled = true; bManual.Text = "Manual"; break; default: Log("Unsupported install method!"); break; } } /* Enable Buttons END */ if(cbVersions.SelectedIndex == -1) cbVersions.SelectedIndex = 0; } else { bAutomatic.Enabled = false; bManual.Enabled = false; } /* Populate Versions END */ } private void CbVersions_SelectedIndexChanged(object sender, EventArgs e) { string token = "$.['" + _productSelected + "'].Versions[?(@.Name == '" + cbVersions.SelectedItem + "')]"; // Fetches the specified version _versionSelected = JsonRepostiory.SelectToken(token).ToObject<JObject>(); tbSelectedVersion.Text = _versionSelected["Description"].ToString(); if (_versionSelected["ReleaseNotes"].ToString() != "") { linkReleaseNotes.Enabled = true; } else { linkReleaseNotes.Enabled = false; } } private void LinkReleaseNotes_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { Process.Start(_versionSelected["ReleaseNotes"].ToString()); } public void ExtractFile(string sourceArchive, string destination) { string zPath = @"7za.exe"; string args = string.Format("x \"{0}\" -y -o\"{1}\"", sourceArchive, destination); Log("Extracting using: 7za.exe " + args); try { ProcessStartInfo pro = new ProcessStartInfo(); pro.FileName = zPath; pro.Arguments = args; Process x = Process.Start(pro); x.WaitForExit(); } catch (Exception Ex) { //handle error Log("Error during extraction! " + Ex.Message); throw Ex; } Log("Extraction finished!"); } public void ExtractFile(string sourceArchive, string destination, string fileFilter) { string zPath = @"7za.exe"; string args = string.Format("x \"{0}\" -y -o\"{1}\" {2}", sourceArchive, destination, fileFilter); Log("Extracting using: 7za.exe " + args); try { ProcessStartInfo pro = new ProcessStartInfo(); pro.FileName = zPath; pro.Arguments = args; Process x = Process.Start(pro); x.WaitForExit(); } catch (Exception Ex) { //handle error Log("Error during extraction! " + Ex.Message); throw Ex; } Log("Extraction finished!"); } private void PerformGlobalInstall() { ActiveOperation = true; InstallingVersion = cbVersions.SelectedItem.ToString(); InstallingBranch = cbBranches.SelectedItem.ToString(); string _SpecialKRenamed = _SpecialKRoot + DateTime.Now.ToString("_yyyy-MM-dd_HH.mm.ss"); bool folderRenamed = false; if (lCurrentVersion.Text == InstallingVersion) { if (lCurrentBranch.Text == InstallingBranch && !cbCleanInstall.Checked) { switch(MessageBox.Show("The specified version seems to already be installed. Do you want to perform a clean install?", "Version already installed", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question)) { case DialogResult.Yes: cbCleanInstall.Checked = true; break; case DialogResult.No: break; case DialogResult.Cancel: ActiveOperation = false; InstallingVersion = ""; Log("User chose to abort the install."); return; } } else if (lCurrentBranch.Text != InstallingBranch && !cbCleanInstall.Checked) { switch (MessageBox.Show("Do you want to perform a quick branch migration, without reinstalling Special K?", "Perform a quick branch migration?", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question)) { case DialogResult.Yes: string[] InstalledINI = File.ReadAllLines(_SpecialKRoot + "\\Version\\installed.ini"); if (InstalledINI.Length >= 3) { string targetBranch = (InstallingBranch == "Main") ? "Latest" : "Testing"; InstalledINI[2] = "Branch=" + targetBranch; File.WriteAllLines(_SpecialKRoot + "\\Version\\installed.ini", InstalledINI); } ActiveOperation = false; InstallingVersion = ""; Log("Performed a quick branch migration from " + lCurrentBranch.Text + " to " + InstallingBranch + "!\r\n"); lCurrentBranch.Text = InstallingBranch; return; case DialogResult.No: break; case DialogResult.Cancel: ActiveOperation = false; InstallingVersion = ""; Log("User chose to abort the install."); return; } } } if (cbCleanInstall.Checked && Directory.Exists(_SpecialKRoot)) { DialogResult failedDialogResult = DialogResult.None; switch (MessageBox.Show("Performing a clean install will rename the Special K folder to:\r\n\r\n" + _SpecialKRenamed + "\r\n\r\nThis will disable any texture mods or game-specific profiles that might be installed until they're manually moved back.\r\n\r\nAre you sure you want to continue with the clean install?", "Perform clean install?", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2)) { case DialogResult.Yes: Log("User chose to perform a clean install. Renaming " + _SpecialKRoot + " to " + _SpecialKRenamed); do { failedDialogResult = DialogResult.None; try { Directory.Move(_SpecialKRoot, _SpecialKRenamed); Log("Successfully renamed the folder."); folderRenamed = true; } catch { Log("Failed to rename the folder!"); failedDialogResult = MessageBox.Show("Can not rename Special K folder to:\r\n\r\n" + _SpecialKRenamed + "\r\n\r\nThis is most likely because SKIM is currently running, the folder or its parent folder is opened in File Explorer, or a file therein is currently in-use by another application.", "Failed to move Special K folder", MessageBoxButtons.RetryCancel, MessageBoxIcon.Error, MessageBoxDefaultButton.Button2); } } while (failedDialogResult == DialogResult.Retry); if (failedDialogResult == DialogResult.Cancel) { ActiveOperation = false; return; } break; case DialogResult.No: ActiveOperation = false; InstallingVersion = ""; Log("User chose to abort the install."); return; } } bool fileExists = File.Exists(_tmpDownloadPath); bool cancel = false; if (fileExists) { Log("A file called " + _tmpArchiveName + " was found in the downloads folder. Prompting user on how to proceed."); switch (MessageBox.Show("A file called " + _tmpArchiveName + " was found in the downloads folder.\r\nDo you want to use that one?\r\n\r\nClicking 'No' will redownload the file from the Internet.", "Found local file for selected version", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button3)) { case DialogResult.Yes: Log("User chose to reuse the local copy found."); break; case DialogResult.No: fileExists = false; Log("User chose to redownload the archive from the Internet."); break; case DialogResult.Cancel: cancel = true; ActiveOperation = false; Log("User canceled the install process."); break; } } if (cancel == false) { if (fileExists == false) { Log("Downloading " + _tmpDownloadURL); using (OngoingDownload = new WebClient()) { OngoingDownload.DownloadProgressChanged += OnDownloadProgressChanged; OngoingDownload.DownloadFileCompleted += (object sender, AsyncCompletedEventArgs e) => { if (!tsProgress.IsDisposed) { tsProgress.Visible = false; } if (e.Cancelled || e.Error != null) { if(e.Cancelled) { Log("Download cancelled!"); } else if(e.Error != null) { Log("Download failed!"); Log("Error message: " + e.Error.Message + "\r\n"); } Log("Cleaning up incomplete file " + _tmpDownloadPath); if (File.Exists(_tmpDownloadPath)) File.Delete(_tmpDownloadPath); if (folderRenamed) { Log("Restoring original folder name"); Directory.Move(_SpecialKRenamed, _SpecialKRoot); } ActiveOperation = false; CancelOperation = true; OngoingDownload.Dispose(); OngoingDownload = null; return; } Log("Download completed!"); FinalizeGlobalInstall(); OngoingDownload.Dispose(); OngoingDownload = null; }; OngoingDownload.DownloadFileAsync(new Uri(_tmpDownloadURL), _tmpDownloadPath); } } else { FinalizeGlobalInstall(); } } else { ActiveOperation = CancelOperation = false; } } private void FinalizeGlobalInstall() { if (CancelOperation) { ActiveOperation = CancelOperation = false; return; } try { ExtractFile(_tmpDownloadPath, _SpecialKRoot); } catch { ActiveOperation = CancelOperation = false; return; } Directory.CreateDirectory(_SpecialKRoot + "\\Version"); Log("Downloading repository.ini..."); string versionINI = "https://raw.githubusercontent.com/Kaldaien/SpecialK/0.10.x/version.ini"; using (WebClient wc = new WebClient()) { wc.DownloadProgressChanged += OnDownloadProgressChanged; wc.DownloadFile(versionINI, _SpecialKRoot + "\\Version\\repository.ini"); } string tmpBranchName = ""; switch (InstallingBranch) { case "Main": tmpBranchName = "Latest"; break; case "0.9.x": tmpBranchName = "Compatibility"; break; case "0.8.x": tmpBranchName = "Ancient"; break; default: tmpBranchName = InstallingBranch; break; } string updateFrequency = "\r\nReminder=0"; DialogResult dialogResult = MessageBox.Show("Do you want to enable the internal auto-update checks of Special K? This may trigger an update prompt on the next injection of Special K into a game.", "Enable auto-updates for Special K?", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2); if (dialogResult == DialogResult.No) updateFrequency = "never"; string installedINI = "[Version.Local]\r\nInstallPackage=" + _versionSelected["InstallPackage"].ToString() + "\r\nBranch=" + tmpBranchName + "\r\n\r\n[Update.User]\r\nFrequency=" + updateFrequency + "\r\n"; Log("Creating appropriate installed.ini..."); File.WriteAllText(_SpecialKRoot + "\\Version\\installed.ini", installedINI); if (File.Exists(_SpecialKRoot + "\\SKIM64.exe")) { Log("Creating shortcut to SKIM64..."); Directory.CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.Programs) + "\\Special K"); string shortcutLocation = Environment.GetFolderPath(Environment.SpecialFolder.Programs) + "\\Special K\\SKIM64.lnk"; IWshRuntimeLibrary.WshShell shell = new IWshRuntimeLibrary.WshShell(); IWshRuntimeLibrary.IWshShortcut shortcut = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(shortcutLocation); shortcut.WorkingDirectory = _SpecialKRoot; shortcut.Description = "Special K Install Manager"; shortcut.IconLocation = _SpecialKRoot + "\\SKIM64.exe"; shortcut.TargetPath = _SpecialKRoot + "\\SKIM64.exe"; shortcut.Save(); } lCurrentBranch.Text = InstallingBranch; InstallingBranch = ""; lCurrentVersion.Text = InstallingVersion; InstallingVersion = ""; Log("\r\nInstallation finished!\r\n"); ActiveOperation = CancelOperation = false; } public void Cancel() { CancelOperation = true; if (OngoingDownload != null) OngoingDownload.CancelAsync(); } } }
43.83844
445
0.465879
[ "MIT" ]
Idearum/SK-AltInjector
64bitMainApp/Manage.cs
47,216
C#
using Newtonsoft.Json; namespace Nop.Plugin.Api.DTOs.Categories { public class CategoriesCountRootObject { [JsonProperty("count")] public int Count { get; set; } } }
19.5
42
0.651282
[ "MIT" ]
ApertureLabsInc/api-plugin-for-nopcommerce
Nop.Plugin.Api/DTOs/Categories/CategoriesCountRootObject.cs
197
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PingYourPackage.Domain.Services { public class OperationResult { public OperationResult(bool isSuccess) { IsSuccess = isSuccess; } public bool IsSuccess { get; private set; } } }
21.941176
52
0.651475
[ "MIT" ]
tugberkugurlu/PingYourPackage
src/apps/PingYourPackage.Domain/Services/OperationResult.cs
375
C#
namespace Todo { using UnityEngine; [System.Serializable] public class TodoEntry { public string Text; public string Note; public string Tag; public string File; public int Line; public string PathToShow; public TodoEntry(string text, string note, string tag, string file, int line) { Text = text; Note = note; Tag = tag; File = file; Line = line; PathToShow = File.Remove(0, Application.dataPath.Length - 6).Replace("\\", "/") + "(" + Line + ")"; } public override bool Equals(object obj) { var x = this; var y = (TodoEntry)obj; if(ReferenceEquals(x, y)) return true; if(ReferenceEquals(x, null)) return false; if(ReferenceEquals(y, null)) return false; if(x.GetType() != y.GetType()) return false; return string.Equals(x.Text, y.Text) && string.Equals(x.Note, y.Note) && string.Equals(x.Tag, y.Tag) && string.Equals(x.File, y.File) && x.Line == y.Line; } public override int GetHashCode() { unchecked { var obj = this; var hashCode = (obj.Text != null ? obj.Text.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (obj.Note != null ? obj.Note.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (obj.Tag != null ? obj.Tag.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (obj.File != null ? obj.File.GetHashCode() : 0); hashCode = (hashCode * 397) ^ obj.Line; return hashCode; } } } }
24.894737
157
0.618746
[ "MIT" ]
densylkin/ToDoManager
Editor/Scripts/Core/TodoEntry.cs
1,421
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 redshift-2012-12-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.Redshift.Model { /// <summary> /// The specified CIDR block or EC2 security group is already authorized for the specified /// cluster security group. /// </summary> #if !NETSTANDARD [Serializable] #endif public partial class AuthorizationAlreadyExistsException : AmazonRedshiftException { /// <summary> /// Constructs a new AuthorizationAlreadyExistsException with the specified error /// message. /// </summary> /// <param name="message"> /// Describes the error encountered. /// </param> public AuthorizationAlreadyExistsException(string message) : base(message) {} /// <summary> /// Construct instance of AuthorizationAlreadyExistsException /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> public AuthorizationAlreadyExistsException(string message, Exception innerException) : base(message, innerException) {} /// <summary> /// Construct instance of AuthorizationAlreadyExistsException /// </summary> /// <param name="innerException"></param> public AuthorizationAlreadyExistsException(Exception innerException) : base(innerException) {} /// <summary> /// Construct instance of AuthorizationAlreadyExistsException /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> /// <param name="errorType"></param> /// <param name="errorCode"></param> /// <param name="requestId"></param> /// <param name="statusCode"></param> public AuthorizationAlreadyExistsException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode) : base(message, innerException, errorType, errorCode, requestId, statusCode) {} /// <summary> /// Construct instance of AuthorizationAlreadyExistsException /// </summary> /// <param name="message"></param> /// <param name="errorType"></param> /// <param name="errorCode"></param> /// <param name="requestId"></param> /// <param name="statusCode"></param> public AuthorizationAlreadyExistsException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode) : base(message, errorType, errorCode, requestId, statusCode) {} #if !NETSTANDARD /// <summary> /// Constructs a new instance of the AuthorizationAlreadyExistsException class with serialized data. /// </summary> /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is null. </exception> /// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult" /> is zero (0). </exception> protected AuthorizationAlreadyExistsException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } /// <summary> /// Sets the <see cref="T:System.Runtime.Serialization.SerializationInfo" /> with information about the exception. /// </summary> /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is a null reference (Nothing in Visual Basic). </exception> #if BCL35 [System.Security.Permissions.SecurityPermission( System.Security.Permissions.SecurityAction.LinkDemand, Flags = System.Security.Permissions.SecurityPermissionFlag.SerializationFormatter)] #endif [System.Security.SecurityCritical] // These FxCop rules are giving false-positives for this method [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2134:MethodsMustOverrideWithConsistentTransparencyFxCopRule")] public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { base.GetObjectData(info, context); } #endif } }
48.304
178
0.688142
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/Redshift/Generated/Model/AuthorizationAlreadyExistsException.cs
6,038
C#
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using Harmony; using Oxide.Plugins; namespace OxideNoLimit { [HarmonyPatch] public static class OxideSandboxRemove { private static MethodBase GetSandboxMethod(Type typ) => AccessTools.FirstMethod(typ, info => info.IsAssembly && info.ReturnType == typeof(void) && info.GetParameters().FirstOrDefault()?.ParameterType.Name == "TypeDefinition"); internal static MethodBase TargetMethod() { MethodBase target = null; var targetDelegateType = AccessTools.FirstInner(typeof(CompiledAssembly), typ => { if (!typ.IsClass || !typ.IsDefined(typeof(CompilerGeneratedAttribute),false) || AccessTools.Field(typ, "patchModuleType") == null) return false; return (target=GetSandboxMethod(typ)) != null; }); if (targetDelegateType != null) return target; FileLog.Log("[OxideNoLimit] Can't find target in CompiledAssembly. Not patched."); return null; } internal static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { yield return new CodeInstruction(OpCodes.Ret); } } }
35.525
157
0.641802
[ "MIT" ]
virtyvoid/OxideNoLimit
OxideNoLimit/OxideSandboxRemove.cs
1,423
C#
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using log4net; [assembly: log4net.Config.XmlConfigurator(Watch = false)] namespace Framework.Log4NetImpl { public class Log4NetHelper { #region Atributos protected ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Métodos public static void Inicializacao() { log4net.Config.XmlConfigurator.Configure(); } #endregion } }
20.366667
103
0.675941
[ "MIT" ]
gabrielsimas/Framework_DotNET
Log4NetImpl/Log4NetHelper.cs
614
C#
using System; using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.AspNetCore.Razor.TagHelpers; using System.Text.Encodings.Web; namespace TagHelperSamples.Markdown.Tests.Helpers { public class MarkdownHelperToTheTagHelpers { private readonly TagHelperAttributeList _inputAttributes; private readonly Dictionary<object, object> _items = new Dictionary<object, object>(); private readonly TagHelperAttributeList _outputAttributes; public MarkdownHelperToTheTagHelpers() { _inputAttributes = new TagHelperAttributeList(); _outputAttributes = new TagHelperAttributeList(); } private Func<bool, HtmlEncoder, Task<TagHelperContent>> GetChildContent(string childContent) { var content = new DefaultTagHelperContent(); var tagHelperContent = content.SetContent(childContent); return (b, encoder) => Task.FromResult(tagHelperContent); } public TagHelperContext CreateContext(bool hasMarkdownAttribute) { if (hasMarkdownAttribute) _inputAttributes.Add(new TagHelperAttribute("markdown", "")); var context = new TagHelperContext(_inputAttributes, _items, Guid.NewGuid().ToString()); return context; } public TagHelperOutput CreateOutput(string tagName, bool hasMarkdownAttribute, string tagContent) { var childContent = GetChildContent(tagContent); if (hasMarkdownAttribute) _outputAttributes.Add(new TagHelperAttribute("markdown", "")); return new TagHelperOutput(tagName, _outputAttributes, GetChildContent(tagContent)); } } }
38.297872
105
0.665556
[ "Apache-2.0" ]
PerryCodes/TagHelperSamples
TagHelperSamples/src/TagHelperSamples.Markdown.Tests/Helpers/MarkdownHelperToTheTagHelpers.cs
1,800
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Lab4.Models { [System.SerializableAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)] [System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)] public partial class grades { private List<grade> gradeField = new List<grade>(); [System.Xml.Serialization.XmlElementAttribute("grade")] public List<grade> grade { get { return this.gradeField; } set { this.gradeField = value; } } } [System.SerializableAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)] public class grade { private int _indexNumber; private int _idSubject; public int id { get; set; } public int indexNumber { get { return this._indexNumber; } set { int czyIstnieje = (from n in new XmlStudent().getStudentsNew() where n.numerIndeksu == value select n).Count(); if (czyIstnieje < 1) throw new Exception("Nie ma takiego studenta o podanym indeksie!"); else this._indexNumber = value; } } public int idSubject { get { return this._idSubject; } set { int czyIstnieje = (from n in new XmlSubject().getSubjects() where n.id == value select n).Count(); if (czyIstnieje < 1) throw new Exception("Nie ma przedmiotu o takim ID!"); else this._idSubject = value; } } public double score { get; set; } public DateTime scoreDate { get; set; } public string description { get; set; } } }
33.4
128
0.53708
[ "Apache-2.0" ]
CavalornGothic/studia_laboratoria
Lab4/Lab4/Models/grade.cs
2,173
C#
// <auto-generated> // automatically generated by the FlatBuffers compiler, do not modify // </auto-generated> namespace Apache.Arrow.Flatbuf { using global::System; using global::FlatBuffers; /// Same as List, but with 64-bit offsets, allowing to represent /// extremely large data values. internal struct LargeList : IFlatbufferObject { private Table __p; public ByteBuffer ByteBuffer { get { return __p.bb; } } public static LargeList GetRootAsLargeList(ByteBuffer _bb) { return GetRootAsLargeList(_bb, new LargeList()); } public static LargeList GetRootAsLargeList(ByteBuffer _bb, LargeList obj) { return (obj.__assign(_bb.GetInt(_bb.Position) + _bb.Position, _bb)); } public void __init(int _i, ByteBuffer _bb) { __p.bb_pos = _i; __p.bb = _bb; } public LargeList __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } public static void StartLargeList(FlatBufferBuilder builder) { builder.StartObject(0); } public static Offset<LargeList> EndLargeList(FlatBufferBuilder builder) { int o = builder.EndObject(); return new Offset<LargeList>(o); } }; }
34.40625
148
0.742961
[ "Apache-2.0" ]
1mikegrn/arrow
csharp/src/Apache.Arrow/Flatbuf/Types/LargeList.cs
1,101
C#
//----------------------------------------------------------------------------- // Filename: RTSPURI.cs // // Description: RTSP URI. // // History: // 04 May 2007 Aaron Clauson Created. // // License: // This software is licensed under the BSD License http://www.opensource.org/licenses/bsd-license.php // // Copyright (c) 2007 Aaron Clauson (aaron@sipsorcery.com), SIP Sorcery PTY LTD, Hobart, Australia (www.sipsorcery.com) // 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 SIP Sorcery PTY LTD. // 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. //----------------------------------------------------------------------------- using System; using System.Collections; using System.Collections.Specialized; using System.Data; using System.Net; using System.Runtime.Serialization; using System.Text.RegularExpressions; using Logger4Net; #if UNITTEST using NUnit.Framework; #endif namespace SIPSorcery.GB28181.Net { /// <summary> /// RFC2326 3.2: /// rtsp_URL = ( "rtsp:" | "rtspu:" ) /// "//" host [ ":" port ] [ abs_path ] /// host = <A legal Internet host domain name of IP address (in dotted decimal form), as defined by Section 2.1 of RFC 1123 cite{rfc1123}> /// port = *DIGIT /// abs_path is defined in RFC2616 (HTTP 1.1) 3.2.1 which refers to RFC2396 (URI Generic Syntax) /// abs_path = "/" path_segments /// path_segments = segment *( "/" segment ) /// segment = *pchar *( ";" param ) /// param = *pchar /// pchar = unreserved | escaped | ":" | "@" | "&" | "=" | "+" | "$" | "," /// /// </summary> public class RTSPURL { public const int DNS_RESOLUTION_TIMEOUT = 2000; // Timeout for resolving DNS hosts in milliseconds. public const string TRANSPORT_ADDR_SEPARATOR = "://"; public const char HOST_ADDR_DELIMITER = '/'; public const char PARAM_TAG_DELIMITER = ';'; public const char HEADER_START_DELIMITER = '?'; private const char HEADER_TAG_DELIMITER = '&'; private const char TAG_NAME_VALUE_SEPERATOR = '='; //private static int m_defaultRTSPPort = RTSPConstants.DEFAULT_RTSP_PORT; private static string m_rtspTransport = RTSPConstants.RTSP_RELIABLE_TRANSPORTID; private static ILog logger = AssemblyStreamState.logger; public string URLTransport = m_rtspTransport; public string Host; public string Path; private RTSPURL() {} public static RTSPURL ParseRTSPURL(string url) { RTSPHeaderParserError notConcerned; return ParseRTSPURL(url, out notConcerned); } public static RTSPURL ParseRTSPURL(string url, out RTSPHeaderParserError parserError) { try { parserError = RTSPHeaderParserError.None; RTSPURL rtspURL = new RTSPURL(); if (url == null || url.Trim().Length == 0) { throw new ApplicationException("An RTSP URI cannot be parsed from an empty string."); } else { int transAddrPosn = url.IndexOf(TRANSPORT_ADDR_SEPARATOR); if (transAddrPosn == -1) { parserError = RTSPHeaderParserError.MandatoryColonMissing; return null; } else { rtspURL.URLTransport = url.Substring(0, transAddrPosn); string urlHostPortion = url.Substring(transAddrPosn + TRANSPORT_ADDR_SEPARATOR.Length); int hostDelimIndex = urlHostPortion.IndexOf(HOST_ADDR_DELIMITER); if (hostDelimIndex != -1) { rtspURL.Host = urlHostPortion.Substring(0, hostDelimIndex); rtspURL.Path = urlHostPortion.Substring(hostDelimIndex); } else { rtspURL.Host = urlHostPortion; } } return rtspURL; } } catch (ApplicationException appExcp) { throw appExcp; } catch (Exception excp) { throw new ApplicationException("There was an exception parsing an RTSP URL. " + excp.Message + " url=" + url); } } public new string ToString() { try { string urlStr = URLTransport + TRANSPORT_ADDR_SEPARATOR + Host; urlStr += (Path != null) ? Path : null; return urlStr; } catch(Exception excp) { logger.Error("Exception RTSPURL ToString. " + excp.Message); throw excp; } } } }
39.937107
161
0.586772
[ "BSD-2-Clause" ]
7956968/gb28181-sip
SIPSorcery.28181/Net/RTSP/RTSPURL.cs
6,350
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/wincrypt.h in the Windows SDK for Windows 10.0.20348.0 // Original source is Copyright © Microsoft. All rights reserved. using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace TerraFX.Interop { public unsafe partial struct CMSG_RECIPIENT_ENCODE_INFO { [NativeTypeName("DWORD")] public uint dwRecipientChoice; [NativeTypeName("_CMSG_RECIPIENT_ENCODE_INFO::(anonymous union at C:/Program Files (x86)/Windows Kits/10/Include/10.0.20348.0/um/wincrypt.h:7013:5)")] public _Anonymous_e__Union Anonymous; public ref CMSG_KEY_TRANS_RECIPIENT_ENCODE_INFO* pKeyTrans { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { fixed (_Anonymous_e__Union* pField = &Anonymous) { return ref pField->pKeyTrans; } } } public ref CMSG_KEY_AGREE_RECIPIENT_ENCODE_INFO* pKeyAgree { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { fixed (_Anonymous_e__Union* pField = &Anonymous) { return ref pField->pKeyAgree; } } } public ref CMSG_MAIL_LIST_RECIPIENT_ENCODE_INFO* pMailList { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { fixed (_Anonymous_e__Union* pField = &Anonymous) { return ref pField->pMailList; } } } [StructLayout(LayoutKind.Explicit)] public unsafe partial struct _Anonymous_e__Union { [FieldOffset(0)] [NativeTypeName("PCMSG_KEY_TRANS_RECIPIENT_ENCODE_INFO")] public CMSG_KEY_TRANS_RECIPIENT_ENCODE_INFO* pKeyTrans; [FieldOffset(0)] [NativeTypeName("PCMSG_KEY_AGREE_RECIPIENT_ENCODE_INFO")] public CMSG_KEY_AGREE_RECIPIENT_ENCODE_INFO* pKeyAgree; [FieldOffset(0)] [NativeTypeName("PCMSG_MAIL_LIST_RECIPIENT_ENCODE_INFO")] public CMSG_MAIL_LIST_RECIPIENT_ENCODE_INFO* pMailList; } } }
33.458333
158
0.610627
[ "MIT" ]
DaZombieKiller/terrafx.interop.windows
sources/Interop/Windows/um/wincrypt/CMSG_RECIPIENT_ENCODE_INFO.cs
2,411
C#
namespace MadHoneyStore.Web.ViewModels.Home { using System; using System.Collections.Generic; public class IndexViewModel { public IEnumerable<IndexCategoryViewModel> Categories { get; set; } public IEnumerable<IndexProductViewModel> Products { get; set; } } }
23.076923
75
0.703333
[ "MIT" ]
russeva/MadHoneyStore
src/Web/MadHoneyStore.Web.ViewModels/Home/IndexViewModel.cs
302
C#
namespace nayuta.Math { public static class Mathf { public static float Round(float a, int b = 0) => (float) System.Math.Round(a, b); public static float Min(float a, float b) => (float) System.Math.Min(a, b); public static float Max(float a, float b) => (float) System.Math.Max(a, b); public static float Ceil(float a) => (float) System.Math.Ceiling(a); public static float Floor(float a) => (float) System.Math.Floor(a); public static float Pow(float a, float b) => (float) System.Math.Pow(a, b); public static float Abs(float a) => (float) System.Math.Abs(a); public static float Log10(float a) => (float) System.Math.Log10(a); public static string FormatNumber(this float value) => ((double) value).FormatNumber(); } }
36.130435
95
0.616125
[ "MIT" ]
EngineerMark/nayuta-bot
nayuta/nayuta/Math/Mathf.cs
833
C#
 using AutoMapper; using MediatR; using Microsoft.EntityFrameworkCore; using SSW.Rewards.Application.Common.Interfaces; using SSW.Rewards.Application.Reward.Queries.Common; using System; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace SSW.Rewards.Application.Reward.Commands { public class ClaimRewardCommand : IRequest<ClaimRewardResult> { public string Code { get; set; } public bool ClaimInPerson { get; set; } = true; public class ClaimRewardCommandHandler : IRequestHandler<ClaimRewardCommand, ClaimRewardResult> { private readonly ICurrentUserService _currentUserService; private readonly ISSWRewardsDbContext _context; private readonly IMapper _mapper; private readonly IDateTimeProvider _dateTimeProvider; private readonly IRewardSender _rewardSender; public ClaimRewardCommandHandler( ICurrentUserService currentUserService, ISSWRewardsDbContext context, IMapper mapper, IDateTimeProvider dateTimeProvider, IRewardSender rewardSender) { _currentUserService = currentUserService; _context = context; _mapper = mapper; _dateTimeProvider = dateTimeProvider; _rewardSender = rewardSender; } public async Task<ClaimRewardResult> Handle(ClaimRewardCommand request, CancellationToken cancellationToken) { var reward = await _context .Rewards .Where(r => r.Code == request.Code) .FirstOrDefaultAsync(cancellationToken); if(reward == null) { return new ClaimRewardResult { status = RewardStatus.NotFound }; } var user = await _currentUserService.GetCurrentUserAsync(cancellationToken); var userRewards = await _context .UserRewards .Where(ur => ur.UserId == user.Id) .ToListAsync(cancellationToken); int pointsUsed = userRewards.Sum(ur => ur.Reward.Cost); int balance = user.Points - pointsUsed; if(balance < reward.Cost) { return new ClaimRewardResult { status = RewardStatus.NotEnoughPoints }; } // TECH DEBT: the following logic is intended to 'debounce' reward // claiming, to prevent users claiming the same reward twice // within a 5 minute window. This workaround is only required on // the current 'milestone' model for points. Once we move to the // 'currency' model, this will not be required anymore. // see: https://github.com/SSWConsulting/SSW.Rewards/issues/100 var userHasReward = userRewards .Where(ur => ur.RewardId == reward.Id) .FirstOrDefault(); if(userHasReward != null && userHasReward.AwardedAt >= _dateTimeProvider.Now.AddMinutes(-5)) { return new ClaimRewardResult { status = RewardStatus.Duplicate }; } await _context .UserRewards .AddAsync(new Domain.Entities.UserReward { UserId = user.Id, RewardId = reward.Id }, cancellationToken); await _context.SaveChangesAsync(cancellationToken); var dbUser = await _context.Users .Where(u => u.Id == user.Id) .FirstAsync(cancellationToken); await _rewardSender.SendRewardAsync(dbUser, reward, cancellationToken); var rewardModel = _mapper.Map<RewardViewModel>(reward); return new ClaimRewardResult { viewModel = rewardModel, status = RewardStatus.Claimed }; } } } }
36.512397
120
0.54029
[ "Apache-2.0" ]
SSWConsulting/SSW.Rewards
API/SSW.Rewards.Application/Reward/Commands/ClaimReward/ClaimRewardCommand.cs
4,420
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; namespace PtVzzlePrison.Tests { [TestClass] public class GraphTests { /// <summary> /// All ones in the 3x4 matrix with indices: /// 0 1 2 3 /// 4 5 6 7 /// 8 9 10 11 /// </summary> private static int[][] stars = new int[][] { new int[] { 1, 4 }, new int[] { 0, 2, 5 }, new int[] { 1, 3, 5 }, new int[] { 2, 7 }, new int[] { 0, 5, 8 }, new int[] { 1, 4, 6, 9 }, new int[] { 2, 5, 7, 10 }, new int[] { 3, 6, 11 }, new int[] { 4, 9 }, new int[] { 5, 8, 10 }, new int[] { 6, 9, 11 }, new int[] { 7, 10 } }; public static Graph TestGraph {get;} = new Graph(stars, 3, 4, (-1, -1)); [TestMethod] public void ConstructorTest() { var graph = new Graph(stars, 3, 4, (-1, -1)); Assert.IsNotNull(graph); Assert.AreEqual(3, graph.Rows); Assert.AreEqual(4, graph.Colums); Assert.AreEqual((-1,-1), graph.OpenLink); Assert.IsTrue(new IListIListComparer<int>().Equals(stars, graph.Stars)); } [TestMethod] public void GetStarTest() { for ( int i = 0; i < 12; i++) { CollectionAssert.AreEqual(stars[i], TestGraph.GetStar(i).ToArray()); } } } }
28.796296
84
0.424437
[ "MIT" ]
3Dmondo/PtVzzlePrison
PtVzzlePrison.Tests/GraphTests.cs
1,557
C#
using System.Collections.Generic; namespace BikeMates.Domain.Entities { public class MapData : Entity { public virtual Coordinate Start { get; set; } public virtual Coordinate End { get; set; } public virtual ICollection<Coordinate> Waypoints { get; set; } } }
24.916667
70
0.668896
[ "MIT" ]
BikeMates/bike-mates
BikeMates/BikeMates.Domain/Entities/MapData.cs
301
C#
using Jetsons.MsgPack.Formatters; using System.Linq; using Jetsons.MsgPack.Internal; using Jetsons.MsgPack.Resolvers; namespace Jetsons.MsgPack.Resolvers { /// <summary> /// Default composited resolver, builtin -> attribute -> dynamic enum -> dynamic generic -> dynamic union -> dynamic object -> primitive. /// </summary> public sealed class StandardResolver : IFormatterResolver { public static readonly IFormatterResolver Instance = new StandardResolver(); #if NETSTANDARD || NETFRAMEWORK public static readonly IMessagePackFormatter<object> ObjectFallbackFormatter = new DynamicObjectTypeFallbackFormatter(StandardResolverCore.Instance); #endif StandardResolver() { } public IMessagePackFormatter<T> GetFormatter<T>() { return FormatterCache<T>.formatter; } static class FormatterCache<T> { public static readonly IMessagePackFormatter<T> formatter; static FormatterCache() { if (typeof(T) == typeof(object)) { // final fallback #if NETSTANDARD || NETFRAMEWORK formatter = (IMessagePackFormatter<T>)ObjectFallbackFormatter; #else formatter = PrimitiveObjectResolver.Instance.GetFormatter<T>(); #endif } else { formatter = StandardResolverCore.Instance.GetFormatter<T>(); } } } } public sealed class ContractlessStandardResolver : IFormatterResolver { public static readonly IFormatterResolver Instance = new ContractlessStandardResolver(); #if NETSTANDARD || NETFRAMEWORK public static readonly IMessagePackFormatter<object> ObjectFallbackFormatter = new DynamicObjectTypeFallbackFormatter(ContractlessStandardResolverCore.Instance); #endif ContractlessStandardResolver() { } public IMessagePackFormatter<T> GetFormatter<T>() { return FormatterCache<T>.formatter; } static class FormatterCache<T> { public static readonly IMessagePackFormatter<T> formatter; static FormatterCache() { if (typeof(T) == typeof(object)) { // final fallback #if NETSTANDARD || NETFRAMEWORK formatter = (IMessagePackFormatter<T>)ObjectFallbackFormatter; #else formatter = PrimitiveObjectResolver.Instance.GetFormatter<T>(); #endif } else { formatter = ContractlessStandardResolverCore.Instance.GetFormatter<T>(); } } } } public sealed class StandardResolverAllowPrivate : IFormatterResolver { public static readonly IFormatterResolver Instance = new StandardResolverAllowPrivate(); #if NETSTANDARD || NETFRAMEWORK public static readonly IMessagePackFormatter<object> ObjectFallbackFormatter = new DynamicObjectTypeFallbackFormatter(StandardResolverAllowPrivateCore.Instance); #endif StandardResolverAllowPrivate() { } public IMessagePackFormatter<T> GetFormatter<T>() { return FormatterCache<T>.formatter; } static class FormatterCache<T> { public static readonly IMessagePackFormatter<T> formatter; static FormatterCache() { if (typeof(T) == typeof(object)) { // final fallback #if NETSTANDARD || NETFRAMEWORK formatter = (IMessagePackFormatter<T>)ObjectFallbackFormatter; #else formatter = PrimitiveObjectResolver.Instance.GetFormatter<T>(); #endif } else { formatter = StandardResolverAllowPrivateCore.Instance.GetFormatter<T>(); } } } } public sealed class ContractlessStandardResolverAllowPrivate : IFormatterResolver { public static readonly IFormatterResolver Instance = new ContractlessStandardResolverAllowPrivate(); #if NETSTANDARD || NETFRAMEWORK public static readonly IMessagePackFormatter<object> ObjectFallbackFormatter = new DynamicObjectTypeFallbackFormatter(ContractlessStandardResolverAllowPrivateCore.Instance); #endif ContractlessStandardResolverAllowPrivate() { } public IMessagePackFormatter<T> GetFormatter<T>() { return FormatterCache<T>.formatter; } static class FormatterCache<T> { public static readonly IMessagePackFormatter<T> formatter; static FormatterCache() { if (typeof(T) == typeof(object)) { // final fallback #if NETSTANDARD || NETFRAMEWORK formatter = (IMessagePackFormatter<T>)ObjectFallbackFormatter; #else formatter = PrimitiveObjectResolver.Instance.GetFormatter<T>(); #endif } else { formatter = ContractlessStandardResolverAllowPrivateCore.Instance.GetFormatter<T>(); } } } } } namespace Jetsons.MsgPack.Internal { internal static class StandardResolverHelper { public static readonly IFormatterResolver[] DefaultResolvers = new[] { BuiltinResolver.Instance, // Try Builtin AttributeFormatterResolver.Instance, // Try use [MessagePackFormatter] #if !(NETSTANDARD || NETFRAMEWORK) Jetsons.MsgPack.Unity.UnityResolver.Instance, #endif #if !ENABLE_IL2CPP && !UNITY_WSA && !NET_STANDARD_2_0 DynamicEnumResolver.Instance, // Try Enum DynamicGenericResolver.Instance, // Try Array, Tuple, Collection DynamicUnionResolver.Instance, // Try Union(Interface) #endif }; } internal sealed class StandardResolverCore : IFormatterResolver { public static readonly IFormatterResolver Instance = new StandardResolverCore(); static readonly IFormatterResolver[] resolvers = StandardResolverHelper.DefaultResolvers.Concat(new IFormatterResolver[] { #if !ENABLE_IL2CPP && !UNITY_WSA && !NET_STANDARD_2_0 DynamicObjectResolver.Instance, // Try Object #endif }).ToArray(); StandardResolverCore() { } public IMessagePackFormatter<T> GetFormatter<T>() { return FormatterCache<T>.formatter; } static class FormatterCache<T> { public static readonly IMessagePackFormatter<T> formatter; static FormatterCache() { foreach (var item in resolvers) { var f = item.GetFormatter<T>(); if (f != null) { formatter = f; return; } } } } } internal sealed class ContractlessStandardResolverCore : IFormatterResolver { public static readonly IFormatterResolver Instance = new ContractlessStandardResolverCore(); static readonly IFormatterResolver[] resolvers = StandardResolverHelper.DefaultResolvers.Concat(new IFormatterResolver[] { #if !ENABLE_IL2CPP && !UNITY_WSA && !NET_STANDARD_2_0 DynamicObjectResolver.Instance, // Try Object DynamicContractlessObjectResolver.Instance, // Serializes keys as strings #endif }).ToArray(); ContractlessStandardResolverCore() { } public IMessagePackFormatter<T> GetFormatter<T>() { return FormatterCache<T>.formatter; } static class FormatterCache<T> { public static readonly IMessagePackFormatter<T> formatter; static FormatterCache() { foreach (var item in resolvers) { var f = item.GetFormatter<T>(); if (f != null) { formatter = f; return; } } } } } internal sealed class StandardResolverAllowPrivateCore : IFormatterResolver { public static readonly IFormatterResolver Instance = new StandardResolverAllowPrivateCore(); static readonly IFormatterResolver[] resolvers = StandardResolverHelper.DefaultResolvers.Concat(new IFormatterResolver[] { #if !ENABLE_IL2CPP && !UNITY_WSA && !NET_STANDARD_2_0 DynamicObjectResolverAllowPrivate.Instance, // Try Object #endif }).ToArray(); StandardResolverAllowPrivateCore() { } public IMessagePackFormatter<T> GetFormatter<T>() { return FormatterCache<T>.formatter; } static class FormatterCache<T> { public static readonly IMessagePackFormatter<T> formatter; static FormatterCache() { foreach (var item in resolvers) { var f = item.GetFormatter<T>(); if (f != null) { formatter = f; return; } } } } } internal sealed class ContractlessStandardResolverAllowPrivateCore : IFormatterResolver { public static readonly IFormatterResolver Instance = new ContractlessStandardResolverAllowPrivateCore(); static readonly IFormatterResolver[] resolvers = StandardResolverHelper.DefaultResolvers.Concat(new IFormatterResolver[] { #if !ENABLE_IL2CPP && !UNITY_WSA && !NET_STANDARD_2_0 DynamicObjectResolverAllowPrivate.Instance, // Try Object DynamicContractlessObjectResolverAllowPrivate.Instance, // Serializes keys as strings #endif }).ToArray(); ContractlessStandardResolverAllowPrivateCore() { } public IMessagePackFormatter<T> GetFormatter<T>() { return FormatterCache<T>.formatter; } static class FormatterCache<T> { public static readonly IMessagePackFormatter<T> formatter; static FormatterCache() { foreach (var item in resolvers) { var f = item.GetFormatter<T>(); if (f != null) { formatter = f; return; } } } } } }
30.832861
181
0.583793
[ "MIT" ]
jetsons/JetPack.Data.Net
MsgPack/Resolvers/StandardResolver.cs
10,886
C#
using AdventOfCode.Core; namespace AdventOfCode2020 { public class WaitingAreaTwo : BaseWaitingArea { public WaitingAreaTwo(string filename) : base(filename.ReadAllLines()) { } internal override void UpdateBoard() { for (int y = 0; y < _h; y++) { for (int x = 0; x < _w; x++) { if (_board[x, y] == '.') continue; if (_board[x, y] == 'L') _newBoard[x, y] = VisibleSeats(x, y) == 0 ? '#' : 'L'; else _newBoard[x, y] = VisibleSeats(x, y) >= 5 ? 'L' : '#'; } } } internal int VisibleSeats(int x, int y) { int c = 0; // Up Left for (int x1 = x - 1, y1 = y - 1; x1 >= 0 && y1 >= 0; x1--, y1--) if (FindOccupied(ref c, x1, y1)) break; // Up for (int y1 = y - 1; y1 >= 0; y1--) if (FindOccupied(ref c, x, y1)) break; // Up Right for (int x1 = x + 1, y1 = y - 1; x1 < _w && y1 >= 0; x1++, y1--) if (FindOccupied(ref c, x1, y1)) break; // Left for (int x1 = x - 1; x1 >= 0; x1--) if (FindOccupied(ref c, x1, y)) break; // Right for (int x1 = x + 1; x1 < _w; x1++) if (FindOccupied(ref c, x1, y)) break; // Down Left for (int x1 = x - 1, y1 = y + 1; x1 >= 0 && y1 < _h; x1--, y1++) if (FindOccupied(ref c, x1, y1)) break; // Down for (int y1 = y + 1; y1 < _h; y1++) if (FindOccupied(ref c, x, y1)) break; // Down Right for (int x1 = x + 1, y1 = y + 1; x1 < _w && y1 < _h; x1++, y1++) if (FindOccupied(ref c, x1, y1)) break; return c; } bool FindOccupied(ref int c, int x, int y) { if (_board[x, y] == 'L') return true; if (_board[x, y] == '#') { c++; return true; } return false; } } }
28.3125
78
0.367329
[ "MIT" ]
rprouse/AdventOfCode
AdventOfCode2020/Day11/WaitingAreaTwo.cs
2,265
C#
using Catalog.API.Data; using Catalog.API.Entities; using MongoDB.Driver; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Catalog.API.Repositories { public class ProductRepository : IProductRepository { private readonly ICatalogContext context; public ProductRepository(ICatalogContext context) { this.context = context ?? throw new ArgumentNullException(nameof(context)); } public async Task CreateProduct(Product product) { await context.Products.InsertOneAsync(product); } public async Task<bool> DeleteProduct(string id) { var deleteResult = await context.Products.DeleteOneAsync(p => p.Id == id); return deleteResult.IsAcknowledged && deleteResult.DeletedCount > 0; } public async Task<Product> GetProduct(string id) { return await context.Products.Find(p => p.Id == id).FirstOrDefaultAsync(); } public async Task<IEnumerable<Product>> GetProductByCategory(string categoryName) { FilterDefinition<Product> filter = Builders<Product>.Filter.Eq(p => p.Category, categoryName); return await context.Products.Find(filter).ToListAsync(); //return await context.Products.Find(p => p.Category.Equals(categoryName)).ToListAsync(); } public async Task<IEnumerable<Product>> GetProductByName(string name) { return await context.Products.Find(p => p.Name.Equals(name)).ToListAsync(); } public async Task<IEnumerable<Product>> GetProducts() { return await context.Products.Find(p => true).ToListAsync(); } public async Task<bool> UpdateProduct(Product product) { var updateResult = await context.Products.ReplaceOneAsync(filter: g => g.Id == product.Id, replacement: product); return updateResult.IsAcknowledged && updateResult.ModifiedCount > 0; } } }
35.084746
125
0.650725
[ "MIT" ]
abolhoseinisina/eShop
src/Services/Catalog/Catalog.API/Repositories/ProductRepository.cs
2,072
C#
 using System.Drawing; namespace SuchByte.MacroDeck.GUI.CustomControls { partial class DialogForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(DialogForm)); this.btnClose = new SuchByte.MacroDeck.GUI.CustomControls.PictureButton(); ((System.ComponentModel.ISupportInitialize)(this.btnClose)).BeginInit(); this.SuspendLayout(); // // btnClose // this.btnClose.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.btnClose.BackColor = System.Drawing.Color.Transparent; this.btnClose.BackgroundImage = global::SuchByte.MacroDeck.Properties.Resources.Close_Normal; this.btnClose.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; this.btnClose.Cursor = System.Windows.Forms.Cursors.Hand; this.btnClose.Font = new System.Drawing.Font("Tahoma", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point); this.btnClose.ForeColor = System.Drawing.Color.White; this.btnClose.HoverImage = global::SuchByte.MacroDeck.Properties.Resources.Close_Hover; this.btnClose.Location = new System.Drawing.Point(1017, 3); this.btnClose.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4); this.btnClose.Name = "btnClose"; this.btnClose.Size = new System.Drawing.Size(25, 25); this.btnClose.TabIndex = 1; this.btnClose.TabStop = false; this.btnClose.Click += new System.EventHandler(this.Btn_close_Click); // // DialogForm // this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(45)))), ((int)(((byte)(45)))), ((int)(((byte)(45))))); this.ClientSize = new System.Drawing.Size(1045, 250); this.Controls.Add(this.btnClose); this.Font = new System.Drawing.Font("Tahoma", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point); this.ForeColor = System.Drawing.Color.White; this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4); this.Name = "DialogForm"; this.Padding = new System.Windows.Forms.Padding(1); this.ShowIcon = false; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "DialogForm"; this.Load += new System.EventHandler(this.DialogForm_Load); ((System.ComponentModel.ISupportInitialize)(this.btnClose)).EndInit(); this.ResumeLayout(false); } #endregion private PictureButton btnClose; } }
46.870588
156
0.623494
[ "Apache-2.0" ]
RecklessBoon/Macro-Deck
GUI/CustomControls/DialogForm.Designer.cs
3,986
C#
using System.Collections.Generic; using MongoDB.Driver; using Catalog.API.Entities; namespace Catalog.API.Data { public class CatalogContextSeed { public static void SeedData(IMongoCollection<Product> productCollection) { bool existProduct = productCollection.Find(product => true).Any(); if (!existProduct) { productCollection.InsertManyAsync(GetPreconfiguredProducts()); } } public static IEnumerable<Product> GetPreconfiguredProducts() { return new List<Product>() { new Product() { Id = "602d2149e773f2a3990b47f5", Name = "IPhone X", Summary = "This phone is the company's biggest change to its flagship smartphone in years. It includes a borderless.", Description = "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut, tenetur natus doloremque laborum quos iste ipsum rerum obcaecati impedit odit illo dolorum ab tempora nihil dicta earum fugiat. Temporibus, voluptatibus. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut, tenetur natus doloremque laborum quos iste ipsum rerum obcaecati impedit odit illo dolorum ab tempora nihil dicta earum fugiat. Temporibus, voluptatibus.", ImageFile = "product-1.png", Price = 950.00M, Category = "Smart Phone" }, new Product() { Id = "602d2149e773f2a3990b47f6", Name = "Samsung 10", Summary = "This phone is the company's biggest change to its flagship smartphone in years. It includes a borderless.", Description = "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut, tenetur natus doloremque laborum quos iste ipsum rerum obcaecati impedit odit illo dolorum ab tempora nihil dicta earum fugiat. Temporibus, voluptatibus. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut, tenetur natus doloremque laborum quos iste ipsum rerum obcaecati impedit odit illo dolorum ab tempora nihil dicta earum fugiat. Temporibus, voluptatibus.", ImageFile = "product-2.png", Price = 840.00M, Category = "Smart Phone" }, new Product() { Id = "602d2149e773f2a3990b47f7", Name = "Huawei Plus", Summary = "This phone is the company's biggest change to its flagship smartphone in years. It includes a borderless.", Description = "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut, tenetur natus doloremque laborum quos iste ipsum rerum obcaecati impedit odit illo dolorum ab tempora nihil dicta earum fugiat. Temporibus, voluptatibus. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut, tenetur natus doloremque laborum quos iste ipsum rerum obcaecati impedit odit illo dolorum ab tempora nihil dicta earum fugiat. Temporibus, voluptatibus.", ImageFile = "product-3.png", Price = 650.00M, Category = "White Appliances" }, new Product() { Id = "602d2149e773f2a3990b47f8", Name = "Xiaomi Mi 9", Summary = "This phone is the company's biggest change to its flagship smartphone in years. It includes a borderless.", Description = "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut, tenetur natus doloremque laborum quos iste ipsum rerum obcaecati impedit odit illo dolorum ab tempora nihil dicta earum fugiat. Temporibus, voluptatibus. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut, tenetur natus doloremque laborum quos iste ipsum rerum obcaecati impedit odit illo dolorum ab tempora nihil dicta earum fugiat. Temporibus, voluptatibus.", ImageFile = "product-4.png", Price = 470.00M, Category = "White Appliances" }, new Product() { Id = "602d2149e773f2a3990b47f9", Name = "HTC U11+ Plus", Summary = "This phone is the company's biggest change to its flagship smartphone in years. It includes a borderless.", Description = "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut, tenetur natus doloremque laborum quos iste ipsum rerum obcaecati impedit odit illo dolorum ab tempora nihil dicta earum fugiat. Temporibus, voluptatibus. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut, tenetur natus doloremque laborum quos iste ipsum rerum obcaecati impedit odit illo dolorum ab tempora nihil dicta earum fugiat. Temporibus, voluptatibus.", ImageFile = "product-5.png", Price = 380.00M, Category = "Smart Phone" }, new Product() { Id = "602d2149e773f2a3990b47fa", Name = "LG G7 ThinQ", Summary = "This phone is the company's biggest change to its flagship smartphone in years. It includes a borderless.", Description = "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut, tenetur natus doloremque laborum quos iste ipsum rerum obcaecati impedit odit illo dolorum ab tempora nihil dicta earum fugiat. Temporibus, voluptatibus. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut, tenetur natus doloremque laborum quos iste ipsum rerum obcaecati impedit odit illo dolorum ab tempora nihil dicta earum fugiat. Temporibus, voluptatibus.", ImageFile = "product-6.png", Price = 240.00M, Category = "Home Kitchen" } }; } } }
70.27907
468
0.622766
[ "MIT" ]
caique39/aspnet-microservices
src/Services/Catalog/Catalog.API/Data/CatalogContextSeed.cs
6,044
C#
using System.Threading.Tasks; using Shouldly; using Xunit; using VOU.Sessions; namespace VOU.Tests.Sessions { public class SessionAppService_Tests : VOUTestBase { private readonly ISessionAppService _sessionAppService; public SessionAppService_Tests() { _sessionAppService = Resolve<ISessionAppService>(); } [MultiTenantFact] public async Task Should_Get_Current_User_When_Logged_In_As_Host() { // Arrange LoginAsHostAdmin(); // Act var output = await _sessionAppService.GetCurrentLoginInformations(); // Assert var currentUser = await GetCurrentUserAsync(); output.User.ShouldNotBe(null); output.User.Name.ShouldBe(currentUser.Name); output.User.Surname.ShouldBe(currentUser.Surname); output.Tenant.ShouldBe(null); } [Fact] public async Task Should_Get_Current_User_And_Tenant_When_Logged_In_As_Tenant() { // Act var output = await _sessionAppService.GetCurrentLoginInformations(); // Assert var currentUser = await GetCurrentUserAsync(); var currentTenant = await GetCurrentTenantAsync(); output.User.ShouldNotBe(null); output.User.Name.ShouldBe(currentUser.Name); output.Tenant.ShouldNotBe(null); output.Tenant.Name.ShouldBe(currentTenant.Name); } } }
28.566038
87
0.625495
[ "MIT" ]
BugBear96/VOU
aspnet-core/test/VOU.Tests/Sessions/SessionAppService_Tests.cs
1,516
C#
using System; using System.ComponentModel; using System.Linq; using System.Threading.Tasks; using Discord; using Discord.Commands; using Discord.WebSocket; using OctoBot.Configs; using OctoBot.Configs.Server; using OctoBot.Configs.Users; using OctoBot.Custom_Library; using OctoBot.Handeling; using OctoBot.Helper; namespace OctoBot.Commands { public class ServerSetup : ModuleBase<ShardedCommandContextCustom> { [Command("build")] [RequireOwner] public async Task BuildExistingServer() { var guild = Global.Client.Guilds.ToList(); foreach (var t in guild) ServerAccounts.GetServerAccount(t); await CommandHandeling.ReplyAsync(Context, "Севера бобавлены, бууууль!"); } [Command("prefix")] public async Task CheckPrefix() { var guild = ServerAccounts.GetServerAccount(Context.Guild); await CommandHandeling.ReplyAsync(Context, $"boole: `{guild.Prefix}`"); } [Command("setPrefix")] [Alias("setpref")] [Description("Setuo prefix for currrent Guild")] [RequireUserPermission(GuildPermission.ManageRoles)] public async Task SetPrefix([Remainder] string prefix) { try { if (prefix.Length >= 5) { await CommandHandeling.ReplyAsync(Context, $"boole!! Please choose prefix using up to 4 characters"); return; } var guild = ServerAccounts.GetServerAccount(Context.Guild); guild.Prefix = prefix; ServerAccounts.SaveServerAccounts(); await CommandHandeling.ReplyAsync(Context, $"boole is now: `{guild.Prefix}`"); } catch { // } } [Command("offLog")] [RequireUserPermission(GuildPermission.Administrator)] public async Task SetServerActivivtyLogOff() { var guild = ServerAccounts.GetServerAccount(Context.Guild); guild.LogChannelId = 0; guild.ServerActivityLog = 0; ServerAccounts.SaveServerAccounts(); await CommandHandeling.ReplyAsync(Context, $"Boole."); } [Command("SetLog")] [Alias("SetLogs")] [RequireUserPermission(GuildPermission.Administrator)] public async Task SetServerActivivtyLog(IGuildChannel logChannel = null) { var guild = ServerAccounts.GetServerAccount(Context.Guild); if (logChannel != null) { try { var channel = logChannel; if ((channel as ITextChannel) == null) { await CommandHandeling.ReplyAsync(Context, $"Booole >_< **an error** Maybe I am not an Administrator of this server? I need this permission to access audit, manage channel, emojis and users."); return; } guild.LogChannelId = channel.Id; guild.ServerActivityLog = 1; ServerAccounts.SaveServerAccounts(); var text2 = $"Boole! Now we log everything to {((ITextChannel) channel).Mention}, you may rename and move it.\n"; // $"Btw, you may say `editIgnore 5` and we we will ignore the message where only 5 **characters** have been changed. This will reduce the number of non-spurious logs (you may say any number)"; await CommandHandeling.ReplyAsync(Context, text2); } catch { // await CommandHandeling.ReplyAsync(Context, // $"Booole >_< **an error** Maybe I am not an Administrator of this server? I need this permission to access audit, manage channel, emojis and users."); } return; } switch (guild.ServerActivityLog) { case 1: guild.ServerActivityLog = 0; guild.LogChannelId = 0; ServerAccounts.SaveServerAccounts(); await CommandHandeling.ReplyAsync(Context, $"Octopuses are not logging any activity now **:c**\n"); return; case 0: try { try { var tryChannel = Context.Guild.GetTextChannel(guild.LogChannelId); if (tryChannel.Name != null) { guild.LogChannelId = tryChannel.Id; guild.ServerActivityLog = 1; ServerAccounts.SaveServerAccounts(); var text2 = $"Boole! Now we log everything to {tryChannel.Mention}, you may rename and move it."; await CommandHandeling.ReplyAsync(Context, text2); } } catch { var channel = Context.Guild.CreateTextChannelAsync("OctoLogs"); guild.LogChannelId = channel.Result.Id; guild.ServerActivityLog = 1; ServerAccounts.SaveServerAccounts(); var text = $"Boole! Now we log everything to {channel.Result.Mention}, you may rename and move it."; await CommandHandeling.ReplyAsync(Context, text); } } catch { // await CommandHandeling.ReplyAsync(Context, // $"Booole >_< **an error** Maybe I am not an Administrator of this server? I need this permission to access audit, manage channel, emojis and users."); } break; } } [Command("SetLanguage")] [Alias("setlang")] [RequireUserPermission(GuildPermission.ManageRoles)] [Description("Setting language for this guild")] public async Task SetLanguage(string lang) { if (lang.ToLower() != "en" && lang.ToLower() != "ru") { await CommandHandeling.ReplyAsync(Context, $"boole! only available options for now: `en`(default) and `ru`"); return; } var guild = ServerAccounts.GetServerAccount(Context.Guild); guild.Language = lang.ToLower(); ServerAccounts.SaveServerAccounts(); await CommandHandeling.ReplyAsync(Context, $"boole~ language is now: `{lang.ToLower()}`"); } [Command("SetRoleOnJoin")] [Alias("RoleOnJoin")] [RequireUserPermission(GuildPermission.ManageRoles)] public async Task SetRoleOnJoin(string role = null) { string text; var guild = ServerAccounts.GetServerAccount(Context.Guild); if (role == null) { guild.RoleOnJoin = null; text = $"boole... No one will get role on join from me!"; } else { guild.RoleOnJoin = role; text = $"boole. Everyone will now be getting {role} role on join!"; } ServerAccounts.SaveServerAccounts(); await CommandHandeling.ReplyAsync(Context, text); } [Command("chanInfo")] [Alias("ci")] [Description("Showing usefull Server's Channels Statistics")] public async Task ChannelInfo(ulong guildId) { var channels = Global.Client.GetGuild(guildId).TextChannels.ToList(); var text = ""; var text2 = ""; for (var i = 0; i < channels.Count; i++) if (text.Length <= 900) text += $"{i + 1}) {channels[i].Name} - {channels[i].Users.Count}\n"; else text2 += $"{i + 1}) {channels[i].Name} - {channels[i].Users.Count}\n"; var embed = new EmbedBuilder(); embed.AddField($"{Global.Client.GetGuild(guildId).Name} Channel Info", $"{text}"); if (text2.Length > 1) embed.AddField($"Continued", $"{text2}"); await ReplyAsync("", false, embed.Build()); await Task.CompletedTask; } [Command("role")] [Description("Giving any available role to any user in this guild")] public async Task TeninzRole(SocketUser user, string role) { var check = Context.User as IGuildUser; var comander = UserAccounts.GetAccount(Context.User, Context.Guild.Id); if (check != null && (comander.OctoPass >= 100 || comander.IsModerator >= 1 || check.GuildPermissions.ManageRoles || check.GuildPermissions.ManageMessages)) { var guildUser = Global.Client.GetGuild(Context.Guild.Id).GetUser(user.Id); var roleToGive = Global.Client.GetGuild(Context.Guild.Id).Roles .SingleOrDefault(x => x.Name.ToString() == role); var roleList = guildUser.Roles.ToArray(); if (roleList.Any(t => t.Name == role)) { await guildUser.RemoveRoleAsync(roleToGive); await CommandHandeling.ReplyAsync(Context, "Буль!"); return; } await guildUser.AddRoleAsync(roleToGive); await CommandHandeling.ReplyAsync(Context, "Буль?"); } } [Command("add", RunMode = RunMode.Async)] public async Task AddCustomRoleToBotList(string command, [Remainder] string role) { var guild = ServerAccounts.GetServerAccount(Context.Guild); var check = Context.User as IGuildUser; var comander = UserAccounts.GetAccount(Context.User, Context.Guild.Id); if (check != null && (comander.OctoPass >= 100 || comander.IsModerator >= 1 || check.GuildPermissions.ManageRoles || check.GuildPermissions.ManageMessages)) { var serverRolesList = Context.Guild.Roles.ToList(); var ifSuccsess = false; for (var i = 0; i < serverRolesList.Count; i++) { if (!string.Equals(serverRolesList[i].Name, role, StringComparison.CurrentCultureIgnoreCase) || ifSuccsess) continue; var i1 = i; guild.Roles.AddOrUpdate(command, serverRolesList[i].Name, (key, value) => serverRolesList[i1].Name); ServerAccounts.SaveServerAccounts(); ifSuccsess = true; } if (ifSuccsess) { var embed = new EmbedBuilder(); embed.AddField("New Role Command Added To The List:", "Boole!\n" + $"`{guild.Prefix}{command}` will give the user `{role}` Role\n" + ".\n" + "**_____**\n" + "`ar` - see all Role Commands\n" + $"`dr {command}` - remove the command from the list" + "Btw, you can say **role @user role_name** as well."); embed.WithFooter("Tip: Simply edit the previous message instead of writing a new command"); await CommandHandeling.ReplyAsync(Context, embed); } else { await CommandHandeling.ReplyAsync(Context, "Error.\n" + "Example: `add KeyName RoleName` where **KeyName** anything you want(even emoji), and **RoleName** is a role, you want to get by using `*KeyName`\n" + "You can type **RoleName** all lowercase\n\n" + "Saying `*KeyName` you will get **RoleName** role."); } } } [Command("r")] public async Task AddCustomRoleToUser([Remainder] string role) { var guild = ServerAccounts.GetServerAccount(Context.Guild); var guildRoleList = guild.Roles.ToArray(); SocketRole roleToAdd = null; if (guildRoleList.Any(x => x.Key == role)) foreach (var t in guildRoleList) if (t.Key == role) roleToAdd = Context.Guild.Roles.SingleOrDefault(x => x.Name.ToString() == t.Value); else return; if (!(Context.User is SocketGuildUser guildUser) || roleToAdd == null) return; var roleList = guildUser.Roles.ToArray(); if (roleList.Any(t => t.Name == roleToAdd.Name)) { await guildUser.RemoveRoleAsync(roleToAdd); await CommandHandeling.ReplyAsync(Context, $"-{roleToAdd.Name}"); return; } await guildUser.AddRoleAsync(roleToAdd); await CommandHandeling.ReplyAsync(Context, $"+{roleToAdd.Name}"); } [Command("ar")] public async Task AllCustomRoles() { var guild = ServerAccounts.GetServerAccount(Context.Guild); var rolesList = guild.Roles.ToList(); var embed = new EmbedBuilder(); embed.WithColor(SecureRandomStatic.Random(254), SecureRandomStatic.Random(254), SecureRandomStatic.Random(254)); embed.WithAuthor(Context.User); var text = ""; foreach (var t in rolesList) text += $"{t.Key} - {t.Value}\n"; embed.AddField("All Custom Commands To Get Roles:", $"Format: **KeyName - RoleName**\n" + $"By Saying `{guild.Prefix}KeyName` you will get **RoleName** role.\n" + $"**______**\n\n" + $"{text}\n"); embed.WithFooter("Say **dr KeyName** to delete the Command from the list"); await CommandHandeling.ReplyAsync(Context, embed); } [Command("dr")] [Alias("rr")] [RequireUserPermission(ChannelPermission.ManageRoles)] public async Task DeleteCustomRoles(string role) { var guild = ServerAccounts.GetServerAccount(Context.Guild); var embed = new EmbedBuilder(); embed.WithColor(SecureRandomStatic.Random(254), SecureRandomStatic.Random(254), SecureRandomStatic.Random(254)); embed.WithAuthor(Context.User); var test = guild.Roles.TryRemove(role, out role); var text = test ? $"{role} Removed" : "error"; embed.AddField("Delete Custom Role:", $"{text}"); await CommandHandeling.ReplyAsync(Context, embed); } [Command("editIgnore")] public async Task LoggingMessEditIgnore(int ignore) { if (ignore < 0 || ignore > 2000) { await CommandHandeling.ReplyAsync(Context, "limit 0-2000"); return; } var guild = ServerAccounts.GetServerAccount(Context.Guild); guild.LoggingMessEditIgnoreChar = ignore; ServerAccounts.SaveServerAccounts(); await CommandHandeling.ReplyAsync(Context, $"Boole? From now on we will ignore {ignore} characters for logging **Message Edit**\n" + "Hint: Space is 1 char, an this: `1` is 3 characters (special formatting characters counts as well)"); } } }
42.310606
240
0.502059
[ "MIT" ]
OctoBot-Boole/OctoBot
OctoBot/Commands/ServerSetup.cs
16,787
C#
using System.Threading.Tasks; using DSharpPlus.CommandsNext; using DSharpPlus.CommandsNext.Attributes; namespace LaDOSE.DiscordBot.Command { [RequireRolesAttribute("SuperAdmin")] public class Shutdown { private readonly Dependencies dep; public Shutdown(Dependencies d) { dep = d; } [Command("shutdown")] public async Task ShutDownAsync(CommandContext ctx) { await ctx.RespondAsync("Hasta la vista, baby"); dep.Cts.Cancel(); } } }
22.04
59
0.61706
[ "MIT" ]
darkstack/LaDOSE
LaDOSE.Src/LaDOSE.DiscordBot/Command/Shutdown.cs
553
C#
// CivOne // // To the extent possible under law, the person who associated CC0 with // CivOne has waived all copyright and related or neighboring rights // to CivOne. // // You should have received a copy of the CC0 legalcode along with this // work. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>. using CivOne.Advances; using CivOne.Enums; namespace CivOne.Wonders { internal class HangingGardens : BaseWonder { public HangingGardens() : base(30) { Name = "Hanging Gardens"; RequiredTech = new Pottery(); ObsoleteTech = new Invention(); SetSmallIcon(4, 2); Type = Wonder.HangingGardens; } } }
24.538462
73
0.714734
[ "CC0-1.0" ]
Andersw88/CivOne
src/Wonders/HangingGardens.cs
638
C#
 namespace SSRSMigrate.Wrappers { public interface ISerializeWrapper { T DeserializeObject<T>(string value); string SerializeObject(object value); } }
18.9
46
0.645503
[ "MIT" ]
jpann/SSRSMigrate
SSRSMigrate/SSRSMigrate/Wrappers/ISerializeWrapper.cs
191
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("SwdPageRecorder.TestModel")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SwdPageRecorder.TestModel")] [assembly: AssemblyCopyright("Copyright © 2013")] [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("b443ccc3-f989-4f27-913d-243b2834d159")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.459459
84
0.748419
[ "MIT" ]
dzharii/swd-recorder
SwdPageRecorder/SwdPageRecorder.TestModel/Properties/AssemblyInfo.cs
1,426
C#
using System; using NHapi.Base; using NHapi.Base.Parser; using NHapi.Base.Model; using NHapi.Model.V251.Datatype; using NHapi.Base.Log; namespace NHapi.Model.V251.Segment{ ///<summary> /// Represents an HL7 GP1 message segment. /// This segment has the following fields:<ol> ///<li>GP1-1: Type of Bill Code (IS)</li> ///<li>GP1-2: Revenue Code (IS)</li> ///<li>GP1-3: Overall Claim Disposition Code (IS)</li> ///<li>GP1-4: OCE Edits per Visit Code (IS)</li> ///<li>GP1-5: Outlier Cost (CP)</li> ///</ol> /// The get...() methods return data from individual fields. These methods /// do not throw exceptions and may therefore have to handle exceptions internally. /// If an exception is handled internally, it is logged and null is returned. /// This is not expected to happen - if it does happen this indicates not so much /// an exceptional circumstance as a bug in the code for this class. ///</summary> [Serializable] public class GP1 : AbstractSegment { /** * Creates a GP1 (Grouping/Reimbursement - Visit) segment object that belongs to the given * message. */ public GP1(IGroup parent, IModelClassFactory factory) : base(parent,factory) { IMessage message = Message; try { this.add(typeof(IS), true, 1, 3, new System.Object[]{message, 455}, "Type of Bill Code"); this.add(typeof(IS), false, 0, 3, new System.Object[]{message, 456}, "Revenue Code"); this.add(typeof(IS), false, 1, 1, new System.Object[]{message, 457}, "Overall Claim Disposition Code"); this.add(typeof(IS), false, 0, 2, new System.Object[]{message, 458}, "OCE Edits per Visit Code"); this.add(typeof(CP), false, 1, 12, new System.Object[]{message}, "Outlier Cost"); } catch (HL7Exception he) { HapiLogFactory.GetHapiLog(GetType()).Error("Can't instantiate " + GetType().Name, he); } } ///<summary> /// Returns Type of Bill Code(GP1-1). ///</summary> public IS TypeOfBillCode { get{ IS ret = null; try { IType t = this.GetField(1, 0); ret = (IS)t; } catch (HL7Exception he) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he); throw new System.Exception("An unexpected error ocurred", he); } catch (System.Exception ex) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex); throw new System.Exception("An unexpected error ocurred", ex); } return ret; } } ///<summary> /// Returns a single repetition of Revenue Code(GP1-2). /// throws HL7Exception if the repetition number is invalid. /// <param name="rep">The repetition number (this is a repeating field)</param> ///</summary> public IS GetRevenueCode(int rep) { IS ret = null; try { IType t = this.GetField(2, rep); ret = (IS)t; } catch (System.Exception ex) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex); throw new System.Exception("An unexpected error ocurred", ex); } return ret; } ///<summary> /// Returns all repetitions of Revenue Code (GP1-2). ///</summary> public IS[] GetRevenueCode() { IS[] ret = null; try { IType[] t = this.GetField(2); ret = new IS[t.Length]; for (int i = 0; i < ret.Length; i++) { ret[i] = (IS)t[i]; } } catch (HL7Exception he) { HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he); throw new System.Exception("An unexpected error ocurred", he); } catch (System.Exception cce) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", cce); throw new System.Exception("An unexpected error ocurred", cce); } return ret; } ///<summary> /// Returns the total repetitions of Revenue Code (GP1-2). ///</summary> public int RevenueCodeRepetitionsUsed { get{ try { return GetTotalFieldRepetitionsUsed(2); } catch (HL7Exception he) { HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he); throw new System.Exception("An unexpected error ocurred", he); } catch (System.Exception cce) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", cce); throw new System.Exception("An unexpected error ocurred", cce); } } } ///<summary> /// Returns Overall Claim Disposition Code(GP1-3). ///</summary> public IS OverallClaimDispositionCode { get{ IS ret = null; try { IType t = this.GetField(3, 0); ret = (IS)t; } catch (HL7Exception he) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he); throw new System.Exception("An unexpected error ocurred", he); } catch (System.Exception ex) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex); throw new System.Exception("An unexpected error ocurred", ex); } return ret; } } ///<summary> /// Returns a single repetition of OCE Edits per Visit Code(GP1-4). /// throws HL7Exception if the repetition number is invalid. /// <param name="rep">The repetition number (this is a repeating field)</param> ///</summary> public IS GetOCEEditsPerVisitCode(int rep) { IS ret = null; try { IType t = this.GetField(4, rep); ret = (IS)t; } catch (System.Exception ex) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex); throw new System.Exception("An unexpected error ocurred", ex); } return ret; } ///<summary> /// Returns all repetitions of OCE Edits per Visit Code (GP1-4). ///</summary> public IS[] GetOCEEditsPerVisitCode() { IS[] ret = null; try { IType[] t = this.GetField(4); ret = new IS[t.Length]; for (int i = 0; i < ret.Length; i++) { ret[i] = (IS)t[i]; } } catch (HL7Exception he) { HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he); throw new System.Exception("An unexpected error ocurred", he); } catch (System.Exception cce) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", cce); throw new System.Exception("An unexpected error ocurred", cce); } return ret; } ///<summary> /// Returns the total repetitions of OCE Edits per Visit Code (GP1-4). ///</summary> public int OCEEditsPerVisitCodeRepetitionsUsed { get{ try { return GetTotalFieldRepetitionsUsed(4); } catch (HL7Exception he) { HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he); throw new System.Exception("An unexpected error ocurred", he); } catch (System.Exception cce) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", cce); throw new System.Exception("An unexpected error ocurred", cce); } } } ///<summary> /// Returns Outlier Cost(GP1-5). ///</summary> public CP OutlierCost { get{ CP ret = null; try { IType t = this.GetField(5, 0); ret = (CP)t; } catch (HL7Exception he) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he); throw new System.Exception("An unexpected error ocurred", he); } catch (System.Exception ex) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex); throw new System.Exception("An unexpected error ocurred", ex); } return ret; } } }}
34.142857
121
0.659059
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
AMCN41R/nHapi
src/NHapi.Model.V251/Segment/GP1.cs
7,887
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using Sys.Stdio; using Sys; using Sys.IO; namespace Sys.Stdio.Cli { class Batch { private readonly string path; private readonly IWorkspace workspace; public string EXT { get; set; } = ".sqc"; public bool IsBatch { get; } = false; public Batch(IWorkspace workspace, string path) { this.workspace = workspace; this.path = GetFullPath(path); this.IsBatch = EXT == Path.GetExtension(this.path); } private string GetFullPath(string path) { string fullPath = workspace.WorkingDirectory.GetFullPath(path, EXT); if (File.Exists(fullPath)) { return fullPath; } if (string.IsNullOrEmpty(workspace.Path)) { return string.Empty; } foreach (string _path in workspace.Path.Split(';')) { WorkingDirectory working = new WorkingDirectory(_path); try { fullPath = working.GetFullPath(path, EXT); if (File.Exists(fullPath)) { return fullPath; } } catch (Exception ex) { cerr.WriteLine($"invalid path:\"{_path}\", using ; as delimiter", ex); } } return string.Empty; } public bool Call(IShellTask task, string[] args) { if (!IsBatch) { cerr.WriteLine($"must be {EXT} file: {path}"); return false; } if (Exists) { var lines = ReadLines(args); IShellTask _task = task.CreateTask(); var _shell = new Shell(_task); //go to current theSide if (task != null) _task.SwitchTask(task); _shell.DoBatch(lines); return true; } else { cerr.WriteLine($"cannot find the file: {path}"); return false; } } /// <summary> /// parameters: %1 %2 %3 ... /// </summary> /// <param name="args"></param> private string[] ReadLines(string[] args) { string[] lines = File.ReadAllLines(path); List<string> L = new List<string>(); foreach (string line in lines) { string cmd = line.Trim(); if (cmd == string.Empty) continue; for (int i = 0; i < args.Length; i++) { cmd = cmd.Replace($"%{i}", args[i]); } //replace unassigned parameter by string.Empty int k = args.Length; while (cmd.IndexOf("%") > 0) { cmd = cmd.Replace($"%{k}", string.Empty); k++; if (k > 100) break; } L.Add(cmd); } return L.ToArray(); } public bool Exists => File.Exists(path); public override string ToString() { return Path.GetFullPath(this.path); } } }
26.198529
90
0.435869
[ "MIT" ]
fjiang2/sqlcli
systie/Console/CLI/Batch.cs
3,565
C#
// Decompiled with JetBrains decompiler // Type: BlueStacks.Core.TableLayoutStrategy // Assembly: BlueStacks.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null // MVID: C36AABCB-E7F4-4E86-A72F-981C56431F94 // Assembly location: C:\Program Files\BlueStacks\BlueStacks.Core.dll using System; using System.Collections.Generic; using System.Linq; using System.Windows; namespace BlueStacks.Core { public class TableLayoutStrategy : ILayoutStrategy { private readonly List<double> _rowHeights = new List<double>(); private int _columnCount; private double[] _colWidths; private int _elementCount; public Size ResultSize { get { return this._colWidths == null || !this._rowHeights.Any<double>() ? new Size(0.0, 0.0) : new Size(((IEnumerable<double>) this._colWidths).Sum(), this._rowHeights.Sum()); } } public void Calculate(Size availableSize, Size[] measures) { this.BaseCalculation(availableSize, measures); this.AdjustEmptySpace(availableSize); } private void BaseCalculation(Size availableSize, Size[] measures) { if (measures == null) return; this._elementCount = measures.Length; this._columnCount = TableLayoutStrategy.GetColumnCount(availableSize, measures); if (this._colWidths == null || this._colWidths.Length < this._columnCount) this._colWidths = new double[this._columnCount]; bool flag = true; while (flag) { flag = false; this.ResetSizes(); for (int index1 = 0; index1 * this._columnCount < measures.Length; ++index1) { double val1 = 0.0; for (int index2 = 0; index2 < this._columnCount; ++index2) { int index3 = index1 * this._columnCount + index2; if (index3 < measures.Length) { this._colWidths[index2] = Math.Max(this._colWidths[index2], measures[index3].Width); val1 = Math.Max(val1, measures[index3].Height); } else break; } if (this._columnCount > 1 && ((IEnumerable<double>) this._colWidths).Sum() > availableSize.Width) { --this._columnCount; flag = true; break; } this._rowHeights.Add(val1); } } } public Rect GetPosition(int index) { int index1 = index % this._columnCount; int index2 = index / this._columnCount; double x = 0.0; for (int index3 = 0; index3 < index1; ++index3) x += this._colWidths[index3]; double y = 0.0; for (int index3 = 0; index3 < index2; ++index3) y += this._rowHeights[index3]; return new Rect(new Point(x, y), new Size(this._colWidths[index1], this._rowHeights[index2])); } public int GetIndex(Point position) { int index1 = 0; for (double num = 0.0; num < position.X && this._columnCount > index1; ++index1) num += this._colWidths[index1]; int num1 = index1 - 1; int index2 = 0; for (double num2 = 0.0; num2 < position.Y && this._rowHeights.Count > index2; ++index2) num2 += this._rowHeights[index2]; int num3 = index2 - 1; if (num3 < 0) num3 = 0; if (num1 < 0) num1 = 0; if (num1 >= this._columnCount) num1 = this._columnCount - 1; int num4 = num3 * this._columnCount + num1; if (num4 > this._elementCount) num4 = this._elementCount - 1; return num4; } private void AdjustEmptySpace(Size availableSize) { double num1 = ((IEnumerable<double>) this._colWidths).Sum(); if (double.IsNaN(availableSize.Width) || availableSize.Width <= num1) return; double num2 = (availableSize.Width - num1) / (double) this._columnCount; for (int index = 0; index < this._columnCount; ++index) this._colWidths[index] += num2; } private void ResetSizes() { this._rowHeights.Clear(); for (int index = 0; index < this._colWidths.Length; ++index) this._colWidths[index] = 0.0; } private static int GetColumnCount(Size availableSize, Size[] measures) { double num1 = 0.0; for (int val2 = 0; val2 < measures.Length; ++val2) { double num2 = num1 + measures[val2].Width; if (num2 > availableSize.Width) return Math.Max(1, val2); num1 = num2; } return measures.Length; } } }
32.338129
177
0.602447
[ "MIT" ]
YehudaEi/Bluestacks-source-code
src/BlueStacks.Core/TableLayoutStrategy.cs
4,497
C#
using CFB.Application.Models; using CFB.Common.Utilities; using CFB.Domain.Commands; using CFB.Infrastructure.Persistence.CosmosGremlinClient; using Gremlin.Net.Driver; using Microsoft.Extensions.Logging; using System; using System.Threading.Tasks; namespace CFB.Application.CommandHandlers { public class CreateFlightCommandHandler : ICommandHandler<CreateFlightCommand> { private readonly IGremlinClient _gremlinClient; private readonly ILogger<CreateFlightCommandHandler> _logger; public CreateFlightCommandHandler(IGremlinClient gremlinClient, ILogger<CreateFlightCommandHandler> logger) { _gremlinClient = gremlinClient; _logger = logger; } public async Task<Result> Handle(CreateFlightCommand createFlightCommand) { try { var flightId = Guid.NewGuid(); var createFlightQuery = new GremlinQueryBuilder() .AddVertex("flight") .Property("type", "flight") .Property("id", flightId) .Property("from", createFlightCommand.From) .Property("originAirportInfo", createFlightCommand.OriginAirportInfo) .Property("to", createFlightCommand.To) .Property("destinationAirportInfo", createFlightCommand.DestinationAirportInfo) .Property("departure", createFlightCommand.Departure.ToIsoFormat()) .Property("duration", createFlightCommand.Duration) .AddEdge("has_flight") .From(createFlightCommand.From) .VertexAppend(flightId.ToString()) .AddEdge("flight_to") .To(new Guid(createFlightCommand.To)) .Build(); var result = await _gremlinClient.SubmitAsyncQuery(createFlightQuery); if (result.StatusCode >= 200 && result.StatusCode <= 299) { return Result.Success; } } catch (Exception ex) { _logger.LogError(ex, ex.Message); } return Result.Failure; } } }
38.366667
115
0.581668
[ "MIT" ]
velicko018/cfb
src/CFB.Application/CommandHandlers/CreateFlightCommandHandler.cs
2,304
C#
using System; using System.CodeDom.Compiler; using System.ComponentModel; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Xml.Serialization; namespace Workday.RevenueManagement { [GeneratedCode("System.Xml", "4.6.1590.0"), DesignerCategory("code"), DebuggerStepThrough, XmlType(Namespace = "urn:com.workday/bsvc")] [Serializable] public class Subrecipient_Response_GroupType : INotifyPropertyChanged { private bool include_ReferenceField; private bool include_ReferenceFieldSpecified; [method: CompilerGenerated] [CompilerGenerated] public event PropertyChangedEventHandler PropertyChanged; [XmlElement(Order = 0)] public bool Include_Reference { get { return this.include_ReferenceField; } set { this.include_ReferenceField = value; this.RaisePropertyChanged("Include_Reference"); } } [XmlIgnore] public bool Include_ReferenceSpecified { get { return this.include_ReferenceFieldSpecified; } set { this.include_ReferenceFieldSpecified = value; this.RaisePropertyChanged("Include_ReferenceSpecified"); } } protected void RaisePropertyChanged(string propertyName) { PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if (propertyChanged != null) { propertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } } }
23.116667
136
0.756309
[ "MIT" ]
matteofabbri/Workday.WebServices
Workday.RevenueManagement/Subrecipient_Response_GroupType.cs
1,387
C#
// ------------------------------------------------------------------------------ // <copyright company="Microsoft Corporation"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // ------------------------------------------------------------------------------ using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; namespace Ycs { public class ContentString : IContentEx { internal const int _ref = 4; private readonly List<object> _content; internal ContentString(string value) : this(value.Cast<object>().ToList()) { // Do nothing. } private ContentString(List<object> content) { _content = content; } int IContentEx.Ref => _ref; public bool Countable => true; public int Length => _content.Count; internal void AppendToBuilder(StringBuilder sb) { foreach (var c in _content) { sb.Append((char)c); } } public string GetString() { var sb = new StringBuilder(); foreach (var c in _content) { sb.Append((char)c); } return sb.ToString(); } public IReadOnlyList<object> GetContent() => _content.AsReadOnly(); public IContent Copy() => new ContentString(_content.ToList()); public IContent Splice(int offset) { var right = new ContentString(_content.GetRange(offset, _content.Count - offset)); _content.RemoveRange(offset, _content.Count - offset); // Prevent encoding invalid documents because of splitting of surrogate pairs. var firstCharCode = (char)_content[offset - 1]; if (firstCharCode >= 0xD800 && firstCharCode <= 0xDBFF) { // Last character of the left split is the start of a surrogate utf16/ucs2 pair. // We don't support splitting of surrogate pairs because this may lead to invalid documents. // Replace the invalid character with a unicode replacement character U+FFFD. _content[offset - 1] = '\uFFFD'; // Replace right as well. right._content[0] = '\uFFFD'; } return right; } public bool MergeWith(IContent right) { Debug.Assert(right is ContentString); _content.AddRange((right as ContentString)._content); return true; } void IContentEx.Integrate(Transaction transaction, Item item) { // Do nothing. } void IContentEx.Delete(Transaction transaction) { // Do nothing. } void IContentEx.Gc(StructStore store) { // Do nothing. } void IContentEx.Write(IUpdateEncoder encoder, int offset) { var sb = new StringBuilder(_content.Count - offset); for (int i = offset; i < _content.Count; i++) { sb.Append((char)_content[i]); } var str = sb.ToString(); encoder.WriteString(str); } internal static ContentString Read(IUpdateDecoder decoder) { return new ContentString(decoder.ReadString()); } } }
28.644628
108
0.523081
[ "MIT" ]
yjs/ycs
src/Ycs/Structs/ContentString.cs
3,468
C#
using ReMi.Common.Constants; using ReMi.Common.WebApi.Notifications; using System; using ReMi.Contracts.Cqrs.Events; namespace ReMi.Events { public class NotificationOccuredForUserEvent : IEvent, INotificationFilterForUser { public NotificationOccuredForUserEvent() { Type = NotificationOccuredEventType.Info; } public string Code { get; set; } public string Message { get; set; } public NotificationOccuredEventType Type { get; set; } public EventContext Context { get; set; } public Guid AccountId { get { return Context.UserId; } } public override string ToString() { return string.Format("[Code={0}, Message={1}, Context={2}]", Code, Message, Context); } } }
25.3125
85
0.630864
[ "MIT" ]
vishalishere/remi
ReMi.Api/ServiceBoundary/ReMi.Events/NotificationOccuredForUserEvent.cs
810
C#
namespace MVVM { public class JoystickUI : VMBase<JoystickUI> { protected override void RegisterActivationEvents() { } protected override void UnregisterActivationEvents() { } } }
17.285714
60
0.586777
[ "MIT" ]
mrvcmrvc/MMUIMenu
UMVVMFramework/Assets/UMVVMFramework/MVVMFramework/Runtime/JoystickController/Scripts/JoystickUI.cs
244
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information #region Usings using System; using System.Web.UI.WebControls; using DotNetNuke.Common; using DotNetNuke.Common.Utilities; using DotNetNuke.Entities.Portals; using DotNetNuke.Services.Exceptions; using DotNetNuke.Services.Localization; using DotNetNuke.Services.Mobile; using DotNetNuke.UI.Skins; #endregion namespace DotNetNuke.UI.Skins.Controls { /// ----------------------------------------------------------------------------- /// <summary>Skin object of portal links between desktop and mobile portals.</summary> /// <returns></returns> /// <remarks></remarks> /// ----------------------------------------------------------------------------- public partial class LinkToFullSite : SkinObjectBase { private const string MyFileName = "LinkToFullSite.ascx"; private string _localResourcesFile; private string LocalResourcesFile { get { if(string.IsNullOrEmpty(_localResourcesFile)) { _localResourcesFile = Localization.GetResourceFile(this, MyFileName); } return _localResourcesFile; } } #region "Event Handlers" protected override void OnLoad(EventArgs e) { base.OnLoad(e); var redirectionController = new RedirectionController(); var redirectUrl = redirectionController.GetFullSiteUrl(); if (!string.IsNullOrEmpty(redirectUrl)) { lnkPortal.NavigateUrl = redirectUrl; lnkPortal.Text = Localization.GetString("lnkPortal", LocalResourcesFile); } else { this.Visible = false; } } #endregion } }
29.333333
90
0.590909
[ "MIT" ]
Tychodewaard/Dnn.Platform
DNN Platform/Website/admin/Skins/LinkToFullSite.ascx.cs
1,938
C#
using System; using System.IO; using System.Linq; namespace _03.FileSystemTree { public class Startup { public static void Main() { var rootFolderName = @"..\.."; var rootFolder = new Folder(rootFolderName); BuildFileSystemTree(rootFolder); // TraverseFolders(folder); var filesTotalSize = GetFolderFilesSizes(rootFolder); Console.WriteLine(filesTotalSize); } public static long GetFolderFilesSizes(Folder folder) { if (folder.Files.Length == 0 && folder.Folders.Length == 0) { return 0; } var filesSize = folder.Files.Sum(x => x.Size); foreach (var dir in folder.Folders) { filesSize += GetFolderFilesSizes(dir); } return filesSize; } public static void BuildFileSystemTree(Folder folder) { var subFolders = Directory.GetDirectories(folder.Name); var files = Directory.GetFiles(folder.Name); folder.Files = new File[files.Length]; int index = 0; foreach (var file in files) { try { folder.Files[index] = new File(file, new FileInfo(file).Length); index++; } catch { } } folder.Folders = new Folder[subFolders.Length]; index = 0; foreach (var dir in subFolders) { try { folder.Folders[index] = new Folder(dir); BuildFileSystemTree(folder.Folders[index]); index++; } catch { } } } public static void TraverseFolders(Folder folder) { Console.WriteLine(folder.Name); if (folder.Folders == null) { return; } foreach (var file in folder.Files) { Console.WriteLine(" " + file.Name + " -> " + file.Size); } foreach (var f in folder.Folders) { TraverseFolders(f); } } } }
26.134831
84
0.461737
[ "MIT" ]
VVoev/Telerik-Academy
15.Data-Structures-and-Algorithms/BIG FAT CHEAT SHEET/Homeworks/05.TreesAndTraversals/03.FileSystemTree/Startup.cs
2,328
C#
using UnityEngine; using Febucci.Attributes; namespace Febucci.UI.Core { [System.Serializable] //Do not touch this script, but change the CustomDefaultValues one public class AppearanceDefaultValues { #region Default Effects' values //Do not add your custom effect's values here //Write them inside the CustomDefaultValues class instead (CustomEffects.cs) private const float defDuration = .3f; [System.Serializable] internal class Defaults { [PositiveValue] public float sizeDuration = defDuration; [Attributes.MinValue(0)] public float sizeAmplitude = 2; [PositiveValue] public float fadeDuration = defDuration; [PositiveValue] public float verticalExpandDuration = defDuration; public bool verticalFromBottom = false; [PositiveValue] public float horizontalExpandDuration = defDuration; public HorizontalExpandAppearance.ExpType horizontalExpandStart = HorizontalExpandAppearance.ExpType.Left; [PositiveValue] public float diagonalExpandDuration = defDuration; public bool diagonalFromBttmLeft = false; [NotZero] public Vector2 offsetDir = Vector2.one; [PositiveValue] public float offsetDuration = defDuration; [NotZero] public float offsetAmplitude = 1f; [PositiveValue] public float rotationDuration = defDuration; public float rotationStartAngle = 180; } [SerializeField, Header("Default Appearances")] internal Defaults defaults = new Defaults(); #endregion [SerializeField, Header("Preset Effects")] internal PresetAppearanceValues[] presets = new PresetAppearanceValues[0]; //your custom effects [SerializeField, Tooltip("Showing here the values for ALL your custom effects, if any.")] public CustomEffects.CustomAppearanceDefValues customs = new CustomEffects.CustomAppearanceDefValues(); } [System.Serializable] //Do not touch this script, but change the CustomDefaultValues one public class BehaviorDefaultValues { #region Default Effects' values //Do not add your custom effect's values here //Write them inside the CustomDefaultValues class instead (CustomEffects.cs) [System.Serializable] public class Defaults { //wiggle [NotZero] public float wiggleAmplitude = 0.15f; [NotZero] public float wiggleFrequency = 7.67f; //wave [NotZero] public float waveFrequency = 4.78f; [NotZero] public float waveAmplitude = .2f; public float waveWaveSize = .18f; [NotZero] public float angleSpeed = 180; public float angleDiffBetweenChars = 10; [NotZero] public float swingAmplitude = 27.5f; [NotZero] public float swingFrequency = 5f; public float swingWaveSize = 0; [NotZero] public float shakeStrength = 0.085f; [PositiveValue] public float shakeDelay = .04f; public float sizeAmplitude = 1.4f; [NotZero] public float sizeFrequency = 4.84f; public float sizeWaveSize = .18f; [NotZero] public float slideAmplitude = 0.12f; [NotZero] public float slideFrequency = 5; public float slideWaveSize = 0; [NotZero] public float bounceAmplitude = .08f; [NotZero] public float bounceFrequency = 1f; public float bounceWaveSize = 0.08f; [NotZero] public float hueShiftSpeed = 0.8f; public float hueShiftWaveSize = 0.08f; [PositiveValue] public float fadeDelay = 1.2f; } [SerializeField, Header("Default Behaviors")] public Defaults defaults = new Defaults(); #endregion [SerializeField, Header("Preset Effects")] internal PresetBehaviorValues[] presets = new PresetBehaviorValues[0]; //your custom effects [SerializeField, Tooltip("Showing here the values for ALL your custom effects, if any.")] public CustomEffects.CustomBehaviorDefValues customs = new CustomEffects.CustomBehaviorDefValues(); } }
37
118
0.652842
[ "Apache-2.0" ]
gerlogu/Shooter
Game/Assets/Game/Plugins/Febucci/Text Animator/Core/EffectsDefaultValues.cs
4,294
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using KnapsackProblem.Common; using static KnapsackProblem.Common.ArgumentHelpers; using static KnapsackProblem.Common.Helpers; namespace KnapsackProblem.SimulatedEvolution { class Program { /* args: [0] - a path to a test file [1] - a path to a solution file [2] - how many times repeat a test [3] - whether to save results [4 ...] - GA arguments */ static void Main(string[] args) { var genAlgArgs = ParseArguments(args); if (genAlgArgs == null) { Console.ReadLine(); return; } var ga = new GeneticAlgorithm(genAlgArgs); var results = new List<KnapsackSolution>(); foreach (var knapsack in KnapsackLoader.LoadKnapsacks(args[0], KnapsackLoader.KnapsackPerFile)) { Console.WriteLine($"---Starting knapsack {knapsack.Id}---"); results.Add(ga.Solve(knapsack)); } if (bool.Parse(args[3])) SaveSolutions(results); var bestPrices = LoadBestPricesFromSolutionFile(args[1]); var relativeErrors = results.Select((result, index) => ComputeRelativeError(bestPrices[index], result.BestPrice)).ToList(); Console.WriteLine($"Average relative error is {relativeErrors.Average()}."); Console.WriteLine($"Max relative error is {relativeErrors.Max()}."); Console.ReadLine(); } static GeneticAlgorithmArgs ParseArguments(string[] args) { if (args.Length == 0 || args[0] == "-?" || args[0] == "/?") { PrintHelp(); return null; } try { int populationSize = ParseInt32Option(args, "p", true, 0, int.MaxValue); int maxGenerations = ParseInt32Option(args, "g", true, int.MinValue, int.MaxValue); var parentSelection = (ParentSelection) ParseInt32Option(args, "ps", true, 0, 1); int tournamentSize = ParseInt32Option(args, "t", parentSelection == ParentSelection.Tournament, 0, populationSize); var popMngmnt = (PopulationManagement)ParseInt32Option(args, "pm", true, 0, 2); int elitesCount = ParseInt32Option(args, "e", popMngmnt == PopulationManagement.ReplaceAllButElites, 0, populationSize / 2); var mutateProb = ParseDoubleOption(args, "m", true, 0, 1); var printStatus = ParseInt32Option(args, "s", false, 0, 1); return new GeneticAlgorithmArgs(populationSize, maxGenerations, parentSelection, tournamentSize, popMngmnt, elitesCount, mutateProb, printStatus == 1); } catch { return null; } } static void PrintHelp() { var sb = new StringBuilder(); sb.AppendLine(); sb.AppendLine("Usage: -p size -g count -ps method -t size -pm method -e count -m probability [-s <0/1>]"); sb.AppendLine(); sb.AppendLine("Options:"); sb.AppendOption("-p size", "Population size."); sb.AppendOption("-g count", "Total # of generations if possitive, stop when converged after # of generations if negative."); sb.AppendOption("-ps method", "Parent selection method. 0 - tournament, 1 - roulette wheel."); sb.AppendOption("-t size", "Tournament size."); sb.AppendOption("-pm method", "Population management method. 0 - replace all, 1 - replace all but elites, 2 - replace weakest"); sb.AppendOption("-e count", "# of a population's fittest pass to the next generation."); sb.AppendOption("-m probability", "Probability that a single random offspring's gen is mutated."); sb.AppendOption("[-s <0/1>]", "Whether to print status with each new generation, 0 - no (default), 1 - yes."); Console.WriteLine(sb.ToString()); } } }
46.197802
168
0.573977
[ "MIT" ]
kovarmi/paa
KnapsackProblem.SimulatedEvolution/Program.cs
4,206
C#
using System.ComponentModel; namespace EncompassRest.Filters { /// <summary> /// StringFieldMatchType /// </summary> public enum StringFieldMatchType { /// <summary> /// Exact /// </summary> [Description("==")] Exact = 0, /// <summary> /// CaseInsensitive /// </summary> [Description("=")] CaseInsensitive = 1, /// <summary> /// StartsWith /// </summary> [Description("sw")] StartsWith = 2, /// <summary> /// Contains /// </summary> [Description("like")] Contains = 3 } }
21.193548
36
0.462709
[ "MIT" ]
EncompassRest/EncompassREST
src/EncompassRest/Filters/StringFieldMatchType.cs
659
C#
using System; using System.Collections.Generic; namespace GenericViewModels.Services { public class SelectedItemService<T> : ISelectedItemService<T> { private T _selectedItem; public T SelectedItem { get => _selectedItem; set { if (!EqualityComparer<T>.Default.Equals(_selectedItem, value)) { _selectedItem = value; SelectedItemChanged?.Invoke(this, _selectedItem); } } } public event EventHandler<T> SelectedItemChanged; } }
24.68
78
0.547812
[ "MIT" ]
CNinnovation/Generic.ViewModels
Generic.ViewModels/Services/SelectedItemService.cs
619
C#
using System; using System.Collections.Generic; using System.Linq; using DBUtil; namespace Models { /// <summary> /// 用户表 /// </summary> [AutoIncrement] public partial class SYS_USER { } }
12.882353
33
0.625571
[ "MIT" ]
0611163/DBHelper
DBHelper/Models/ExtModels/SYS_USER.cs
225
C#
using System; namespace program2 { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!"); } } }
13.538462
46
0.511364
[ "MIT" ]
sedc-codecademy/skwd9-net-05-oopcsharp
G5/class01 - Introduction/code/program/program2/Program.cs
178
C#
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.Management.DeviceProvisioningServices.Models { using Microsoft.Rest; using Newtonsoft.Json; using System.Linq; /// <summary> /// Input values for operation results call. /// </summary> public partial class OperationInputs { /// <summary> /// Initializes a new instance of the OperationInputs class. /// </summary> public OperationInputs() { CustomInit(); } /// <summary> /// Initializes a new instance of the OperationInputs class. /// </summary> /// <param name="name">The name of the Provisioning Service to /// check.</param> public OperationInputs(string name) { Name = name; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets the name of the Provisioning Service to check. /// </summary> [JsonProperty(PropertyName = "name")] public string Name { get; set; } /// <summary> /// Validate the object. /// </summary> /// <exception cref="ValidationException"> /// Thrown if validation fails /// </exception> public virtual void Validate() { if (Name == null) { throw new ValidationException(ValidationRules.CannotBeNull, "Name"); } } } }
28.925373
90
0.579979
[ "MIT" ]
0rland0Wats0n/azure-sdk-for-net
sdk/deviceprovisioningservices/Microsoft.Azure.Management.DeviceProvisioningServices/src/Generated/Models/OperationInputs.cs
1,938
C#
using AutoFixture; using NSubstitute; using Serilog; using System; using System.Collections.Generic; using Products.Service.Domain; using Products.Service.Interfaces.Business; using Products.Service.WebApi.Controllers; using Xunit; namespace Products.Service.WebApi.Tests { public partial class ProductControllerTests { private readonly Fixture _fixture = new Fixture(); private readonly ILogger _logger = Substitute.For<ILogger>(); private readonly IProductService _productService = Substitute.For<IProductService>(); private readonly ProductsController _systemUnderTest; private readonly Result<ListResult<Product>> _getProductsResult; private readonly ListResult<Product> _productsList; public ProductControllerTests() { // Arrange _systemUnderTest = new ProductsController(_productService, _logger); _productsList = _fixture.Create<ListResult<Product>>(); _getProductsResult = Result<ListResult<Product>>.Success(_productsList); SetUpGetAsyncSuccess(_getProductsResult); } } }
31.638889
93
0.719052
[ "MIT" ]
mendezgabriel/products-rest-api-demo-dotnet-core
Products.Service.WebApi.Tests/ProductControllerTests.cs
1,139
C#
using Zoro.IO; using Zoro.IO.Caching; using Zoro.IO.Data.LevelDB; using System; namespace Zoro.Persistence.LevelDB { internal class DbMetaDataCache<T> : MetaDataCache<T> where T : class, ICloneable<T>, ISerializable, new() { private readonly DB db; private readonly ReadOptions options; private readonly WriteBatch batch; private readonly byte prefix; public DbMetaDataCache(DB db, ReadOptions options, WriteBatch batch, byte prefix, Func<T> factory = null) : base(factory) { this.db = db; this.options = options ?? ReadOptions.Default; this.batch = batch; this.prefix = prefix; } protected override void AddInternal(T item) { batch?.Put(prefix, item.ToArray()); } protected override T TryGetInternal() { if (!db.TryGet(options, prefix, out Slice slice)) return null; return slice.ToArray().AsSerializable<T>(); } protected override void UpdateInternal(T item) { batch?.Put(prefix, item.ToArray()); } } }
27.511628
113
0.581572
[ "MIT" ]
ProDog/Zoro
Zoro/Persistence/LevelDB/DbMetaDataCache.cs
1,185
C#
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace ElementMapperExtension { public static class DictionaryExtension { public enum MapWith { Propertie, Attribute, All }; /// <summary> /// Map data from List Dictionnary to an Object /// </summary> /// <typeparam name="T">Object to map</typeparam> /// <param name="ListDict">List Dictionary</param> /// <param name="UseElementMapper">Map maked with ElementMapper Attribute</param> /// <returns>List of Object with data contains in List Dictionary</returns> public static List<T> MapToList<T>(this List<Dictionary<string, string>> ListDict, MapWith MappedWith = MapWith.Propertie) where T : new() { List<T> ListReturn = null; // Define object type var Entity = typeof(T); // Define dictionary var PropDict = new Dictionary<string, PropertyInfo>(); var AttrDict = new Dictionary<string, PropertyInfo>(); try { if (ListDict != null && ListDict.Count > 0) { ListReturn = new List<T>(); // Get each properties of the Object var Props = Entity.GetProperties(BindingFlags.Instance | BindingFlags.Public); PropDict = Props.ToDictionary(p => p.Name.ToUpper(), p => p); // Get each attribute of properites foreach (PropertyInfo PropInfo in Props) { object[] AttrCollection = PropInfo.GetCustomAttributes(true); foreach (object Attr in AttrCollection) { if (Attr is ElementMapper) { // Get the ElementMapper name ElementMapper Element = Attr as ElementMapper; if (Element != null) { AttrDict.Add(Element.ElementName.ToUpper(), PropInfo); } } } } foreach (Dictionary<string, string> Dict in ListDict) { T newObject = new T(); for (int Index = 0; Index < Dict.Count; Index++) { if((MappedWith == MapWith.Propertie) || (MappedWith == MapWith.All)) { if (PropDict.ContainsKey(Dict.ElementAt(Index).Key.ToUpper())) { var Info = PropDict[Dict.ElementAt(Index).Key.ToUpper()]; if ((Info != null) && Info.CanWrite) { var Val = Dict.ElementAt(Index).Value; if (Info.PropertyType == Val.GetType()) { Info.SetValue(newObject, Val); } else if (Info.PropertyType == typeof(string)) { Info.SetValue(newObject, Val.ToString()); } } } } if((MappedWith == MapWith.Attribute) || (MappedWith == MapWith.All)) { if (AttrDict.ContainsKey(Dict.ElementAt(Index).Key.ToUpper())) { var Info = AttrDict[Dict.ElementAt(Index).Key.ToUpper()]; if ((Info != null) && Info.CanWrite) { var Val = Dict.ElementAt(Index).Value; if (Info.PropertyType == Val.GetType()) { Info.SetValue(newObject, Val); } else if (Info.PropertyType == typeof(string)) { Info.SetValue(newObject, Val.ToString()); } } } } } ListReturn.Add(newObject); } } } catch (Exception ex) { Console.WriteLine("DataReaderExtension : " + ex.Message); throw; } return ListReturn; } /// <summary> /// Map data from Dictionnary to an Object /// </summary> /// <typeparam name="T">Object to map</typeparam> /// <param name="Dict">Dictionary</param> /// <param name="UseElementMapper">Map maked with ElementMapper Attribute</param> /// <returns>Object with data contains in Dictionary</returns> public static T MapToSingle<T>(this Dictionary<string, string> Dict, MapWith MappedWith = MapWith.Propertie) where T : new() { T ObjectReturn = new T(); // Define object type var Entity = typeof(T); // Define dictionary var PropDict = new Dictionary<string, PropertyInfo>(); var AttrDict = new Dictionary<string, PropertyInfo>(); try { if (Dict != null && Dict.Count > 0) { // Get each properties of the Object var Props = Entity.GetProperties(BindingFlags.Instance | BindingFlags.Public); PropDict = Props.ToDictionary(p => p.Name.ToUpper(), p => p); // Get each attribute of properites foreach (PropertyInfo PropInfo in Props) { object[] AttrCollection = PropInfo.GetCustomAttributes(true); foreach (object Attr in AttrCollection) { if (Attr is ElementMapper) { // Get the ElementMapper name ElementMapper Element = Attr as ElementMapper; if (Element != null) { AttrDict.Add(Element.ElementName.ToUpper(), PropInfo); } } } } for (int Index = 0; Index < Dict.Count; Index++) { if ((MappedWith == MapWith.Propertie) || (MappedWith == MapWith.All)) { if (PropDict.ContainsKey(Dict.ElementAt(Index).Key.ToUpper())) { var Info = PropDict[Dict.ElementAt(Index).Key.ToUpper()]; if ((Info != null) && Info.CanWrite) { var Val = Dict.ElementAt(Index).Value; if (Info.PropertyType == Val.GetType()) { Info.SetValue(ObjectReturn, Val); } else if (Info.PropertyType == typeof(string)) { Info.SetValue(ObjectReturn, Val.ToString()); } } } } if ((MappedWith == MapWith.Attribute) || (MappedWith == MapWith.All)) { if (AttrDict.ContainsKey(Dict.ElementAt(Index).Key.ToUpper())) { var Info = AttrDict[Dict.ElementAt(Index).Key.ToUpper()]; if ((Info != null) && Info.CanWrite) { var Val = Dict.ElementAt(Index).Value; if (Info.PropertyType == Val.GetType()) { Info.SetValue(ObjectReturn, Val); } else if (Info.PropertyType == typeof(string)) { Info.SetValue(ObjectReturn, Val.ToString()); } } } } } } } catch (Exception ex) { Console.WriteLine("DataReaderExtension : " + ex.Message); throw; } return ObjectReturn; } } }
45.358491
146
0.375416
[ "MIT" ]
Kaikon/ElementMapperExtension
ElementMapper/ElementMapper/DictionaryExtension.cs
9,618
C#
using System; namespace Pacco.Services.Orders.Application.Exceptions { public class OrderForReservedVehicleNotFoundException : AppException { public override string Code { get; } = "order_for_reserved_vehicle_not_found"; public Guid VehicleId { get; } public DateTime Date { get; } public OrderForReservedVehicleNotFoundException(Guid vehicleId, DateTime date) : base( $"Order for reserved vehicle: {vehicleId} for date: {date} was not found.") { VehicleId = vehicleId; Date = date; } } }
33.5
95
0.636816
[ "MIT" ]
Potapy4/Pacco.Services.Orders
src/Pacco.Services.Orders.Application/Exceptions/OrderForReservedVehicleNotFoundException.cs
603
C#
using System; using System.Globalization; using System.Windows; using System.Windows.Data; using System.Windows.Media; namespace VisualProgrammer.WPF.Util { internal static class DataTypeColorUtils { /// <summary> /// Resolves the line/node color for the given type. /// </summary> internal static Color ColorForDataType(this FrameworkElement el, Type type) => type != null && el.TryFindResource(new NodeTypeColorKey(type)) is Color color ? color : Colors.White; } /// <summary> /// Specialised key for specifying a color the visual node should appear in for a particular type (when using the default template). /// </summary> public class NodeTypeColorKey : ComponentResourceKey { /// <summary> /// Creates a new <see cref="NodeTypeColorKey"/> that marks the color for the nodes of the given type (for the default template). /// </summary> /// <param name="targetType">The type that this color is to be used for.</param> public NodeTypeColorKey(Type targetType) : base(typeof(NodeTypeColorKey), targetType) { } } /// <summary> /// MarkupExtension that takes a binding that points to a type and returns a SolidColorBrush of the color of that type as defined in the color dictionary. /// </summary> public class DataTypeColorBrushBinding : MultiBinding { private static readonly Binding selfBinding = new Binding { RelativeSource = new RelativeSource { Mode = RelativeSourceMode.Self } }; private static readonly IMultiValueConverter conv = new DataTypeColorConverter(); public DataTypeColorBrushBinding(Binding typeBinding) { Bindings.Add(selfBinding); Bindings.Add(typeBinding); Converter = conv; Mode = BindingMode.OneWay; } /// <summary> /// Converter for the DataTypeColorBrushBinding. Takes a FrameworkElement as the first parameter and a Type as the second to return the SolidColorBrush. /// </summary> class DataTypeColorConverter : IMultiValueConverter { public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) => new SolidColorBrush( values[0] is FrameworkElement fe && values[1] is Type type ? fe.ColorForDataType(type) : Colors.White ); public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) => throw new NotImplementedException(); } } }
38.766667
155
0.743336
[ "MIT" ]
Wibble199/VisualProgrammer
VisualProgrammer.WPF/Util/DataTypeColorUtils.cs
2,328
C#
using System; using System.Collections.Generic; using System.Configuration; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Windows; namespace Rapid.NET.Wpf { public class WindowConfig { public class Area { public double Left, Top, Width, Height; } private readonly FileInfo _File; private Area _Area; public static WindowConfig CreateEmpty() { return new WindowConfig(GetStandardFile(), null); } public WindowConfig(FileInfo file, Area area) { _File = file; _Area = area; } public static WindowConfig FromFile(string file) { if (file == null) file = GetStandardFile().FullName; if (!File.Exists(file)) return new WindowConfig(new FileInfo(file), null); Area a = JsonObject.Deserialize<Area>(File.ReadAllText(file)); return new WindowConfig(new FileInfo(file), a); } public void SetWindowArea(Window window) { if (_Area == null) return; var screens = System.Windows.Forms.Screen.AllScreens; double zoom = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Width / SystemParameters.PrimaryScreenWidth; bool isOk = false; double x = _Area.Left * zoom; double y = _Area.Top * zoom; foreach (var s in screens) { if (s.Bounds.Contains((int)x, (int)y)) { isOk = true; break; } } if (isOk) { window.Top = _Area.Top; window.Left = _Area.Left; window.Width = _Area.Width; window.Height = _Area.Height; } else { double w = SystemParameters.PrimaryScreenWidth; double h = SystemParameters.PrimaryScreenHeight; window.Left = w / 4; window.Top = h / 4; window.Width = 500; window.Height = 500; } } public void WriteToFile(Window window) { _Area = new Area { Left = window.Left, Top = window.Top, Width = window.Width, Height = window.Height, }; if (!_File.Directory.Exists) _File.Directory.Create(); File.WriteAllText(_File.FullName, JsonObject.Serialize(_Area)); } private static FileInfo GetStandardFile() { string root = ConfigurationManager.AppSettings.Get("RapidHistoryDir"); if (root == null) root = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); string assName = Assembly.GetEntryAssembly().GetName().Name; return new FileInfo(Path.Combine(root, "Rapid.NET\\" + assName + "\\WindowConfig.json")); } } }
28.017391
84
0.513035
[ "MIT" ]
maxsgit1234/Rapid.NET
Source/Rapid.NET.Wpf/WindowConfig.cs
3,224
C#
using System; using System.Collections.Generic; using System.Linq; using Kiota.Builder.Extensions; using static Kiota.Builder.CodeTypeBase; namespace Kiota.Builder.Writers.CSharp { public class CSharpConventionService : CommonLanguageConventionService { public override string StreamTypeName => "stream"; public override string VoidTypeName => "void"; public override string DocCommentPrefix => "/// "; private static readonly HashSet<string> NullableTypes = new(StringComparer.OrdinalIgnoreCase) { "int", "bool", "float", "double", "decimal", "long", "Guid", "DateTimeOffset", "TimeSpan", "Date","Time", "sbyte", "byte" }; public static readonly char NullableMarker = '?'; public static string NullableMarkerAsString => "?"; public override string ParseNodeInterfaceName => "IParseNode"; public override void WriteShortDescription(string description, LanguageWriter writer) { if(!string.IsNullOrEmpty(description)) writer.WriteLine($"{DocCommentPrefix}<summary>{description.CleanupXMLString()}</summary>"); } public override string GetAccessModifier(AccessModifier access) { return access switch { AccessModifier.Public => "public", AccessModifier.Protected => "protected", _ => "private", }; } #pragma warning disable CA1822 // Method should be static internal void AddRequestBuilderBody(CodeClass parentClass, string returnType, LanguageWriter writer, string urlTemplateVarName = default, string prefix = default, IEnumerable<CodeParameter> pathParameters = default) { var pathParametersProp = parentClass.GetPropertyOfKind(CodePropertyKind.PathParameters); var requestAdapterProp = parentClass.GetPropertyOfKind(CodePropertyKind.RequestAdapter); var pathParametersSuffix = !(pathParameters?.Any() ?? false) ? string.Empty : $", {string.Join(", ", pathParameters.Select(x => $"{x.Name.ToFirstCharacterLowerCase()}"))}"; var urlTplRef = urlTemplateVarName ?? pathParametersProp.Name.ToFirstCharacterUpperCase(); writer.WriteLine($"{prefix}new {returnType}({urlTplRef}, {requestAdapterProp.Name.ToFirstCharacterUpperCase()}{pathParametersSuffix});"); } public override string TempDictionaryVarName => "urlTplParams"; internal void AddParametersAssignment(LanguageWriter writer, CodeTypeBase pathParametersType, string pathParametersReference, params (CodeTypeBase, string, string)[] parameters) { if(pathParametersType == null) return; writer.WriteLine($"var {TempDictionaryVarName} = new {pathParametersType.Name}({pathParametersReference});"); if(parameters.Any()) writer.WriteLines(parameters.Select(p => $"{TempDictionaryVarName}.Add(\"{p.Item2}\", {p.Item3});" ).ToArray()); } #pragma warning restore CA1822 // Method should be static internal bool ShouldTypeHaveNullableMarker(CodeTypeBase propType, string propTypeName) { return propType.IsNullable && (NullableTypes.Contains(propTypeName) || (propType is CodeType codeType && codeType.TypeDefinition is CodeEnum)); } private static HashSet<string> _namespaceSegmentsNames; private static readonly object _namespaceSegmentsNamesLock = new(); private static HashSet<string> GetNamesInUseByNamespaceSegments(CodeElement currentElement) { if(_namespaceSegmentsNames == null) { lock(_namespaceSegmentsNamesLock) { var rootNamespace = currentElement.GetImmediateParentOfType<CodeNamespace>().GetRootNamespace(); var names = new List<string>(GetNamespaceNameSegments(rootNamespace).Distinct(StringComparer.OrdinalIgnoreCase)); _namespaceSegmentsNames = new (names, StringComparer.OrdinalIgnoreCase); _namespaceSegmentsNames.Add("keyvaluepair"); //workaround as System.Collections.Generic imports keyvalue pair } } return _namespaceSegmentsNames; } private static IEnumerable<string> GetNamespaceNameSegments(CodeNamespace ns) { if(!string.IsNullOrEmpty(ns.Name)) foreach(var segment in ns.Name.Split('.', StringSplitOptions.RemoveEmptyEntries).Distinct(StringComparer.OrdinalIgnoreCase)) yield return segment; foreach(var childNs in ns.Namespaces) foreach(var segment in GetNamespaceNameSegments(childNs)) yield return segment; } public override string GetTypeString(CodeTypeBase code, CodeElement targetElement, bool includeCollectionInformation = true) { if(code is CodeComposedTypeBase) throw new InvalidOperationException($"CSharp does not support union types, the union type {code.Name} should have been filtered out by the refiner"); else if (code is CodeType currentType) { var typeName = TranslateTypeAndAvoidUsingNamespaceSegmentNames(currentType, targetElement); var nullableSuffix = ShouldTypeHaveNullableMarker(code, typeName) ? NullableMarkerAsString : string.Empty; var collectionPrefix = currentType.CollectionKind == CodeTypeCollectionKind.Complex && includeCollectionInformation ? "List<" : string.Empty; var collectionSuffix = currentType.CollectionKind switch { CodeTypeCollectionKind.Complex when includeCollectionInformation => ">", CodeTypeCollectionKind.Array when includeCollectionInformation => "[]", _ => string.Empty, }; if (currentType.ActionOf) return $"Action<{collectionPrefix}{typeName}{nullableSuffix}{collectionSuffix}>"; else return $"{collectionPrefix}{typeName}{nullableSuffix}{collectionSuffix}"; } else throw new InvalidOperationException($"type of type {code.GetType()} is unknown"); } private string TranslateTypeAndAvoidUsingNamespaceSegmentNames(CodeType currentType, CodeElement targetElement) { var parentElements = new List<string>(); if(targetElement.Parent is CodeClass parentClass) parentElements.AddRange(parentClass.Methods.Select(x => x.Name).Union(parentClass.Properties.Select(x => x.Name))); var parentElementsHash = new HashSet<string>(parentElements, StringComparer.OrdinalIgnoreCase); var typeName = TranslateType(currentType); var areElementsInSameNamesSpace = DoesTypeExistsInSameNamesSpaceAsTarget(currentType, targetElement); if (currentType.TypeDefinition != null && ( GetNamesInUseByNamespaceSegments(targetElement).Contains(typeName) && !areElementsInSameNamesSpace // match if elements are not in the same namespace and the type name is used in the namespace segments || parentElementsHash.Contains(typeName) // match if type name is used in the parent elements segments || !areElementsInSameNamesSpace && DoesTypeExistsInTargetAncestorNamespace(currentType, targetElement) // match if elements are not in the same namespace and the type exists in target ancestor namespace ) ) return $"{currentType.TypeDefinition.GetImmediateParentOfType<CodeNamespace>().Name}.{typeName}"; else return typeName; } private static bool DoesTypeExistsInSameNamesSpaceAsTarget(CodeType currentType, CodeElement targetElement) { return currentType?.TypeDefinition?.GetImmediateParentOfType<CodeNamespace>()?.Name.Equals(targetElement?.GetImmediateParentOfType<CodeNamespace>()?.Name) ?? false; } private static bool DoesTypeExistsInTargetAncestorNamespace(CodeType currentType, CodeElement targetElement) { // Avoid type ambiguity on similarly named classes. Currently, if we have namespaces A and A.B where both namespaces have type T, // Trying to use type A.B.T in namespace A without using a qualified name will break the build. // Similarly, if we have type A.B.C.D.T1 that needs to be used within type A.B.C.T2, but there's also a type // A.B.T1, using T1 in T2 will resolve A.B.T1 even if you have a using statement with A.B.C.D. var hasChildWithName = false; if (currentType != null && currentType.TypeDefinition != null && !currentType.IsExternal && targetElement != null) { var typeName = currentType.TypeDefinition.Name; var ns = targetElement.GetImmediateParentOfType<CodeNamespace>(); var rootNs = ns?.GetRootNamespace(); while (ns is not null && ns != rootNs && !hasChildWithName) { hasChildWithName = ns.GetChildElements(true).OfType<CodeClass>().Any(c => c.Name?.Equals(typeName) == true); ns = ns.Parent is CodeNamespace n ? n : (ns.GetImmediateParentOfType<CodeNamespace>()); } } return hasChildWithName; } public override string TranslateType(CodeType type) { return type.Name switch { "integer" => "int", "boolean" => "bool", "int64" => "long", "string" or "float" or "double" or "object" or "void" or "decimal" or "sbyte" or "byte" => type.Name.ToLowerInvariant(),// little casing hack "binary" => "byte[]", _ => type.Name?.ToFirstCharacterUpperCase() ?? "object", }; } public bool IsPrimitiveType(string typeName) { if (string.IsNullOrEmpty(typeName)) return false; typeName = typeName.StripArraySuffix().TrimEnd('?').ToLowerInvariant(); return typeName switch { "string" => true, _ when NullableTypes.Contains(typeName) => true, _ => false, }; } public override string GetParameterSignature(CodeParameter parameter, CodeElement targetElement) { var parameterType = GetTypeString(parameter.Type, targetElement); var defaultValue = parameter switch { _ when !string.IsNullOrEmpty(parameter.DefaultValue) => $" = {parameter.DefaultValue}", _ when parameter.Optional => " = default", _ => string.Empty, }; return $"{parameterType} {parameter.Name.ToFirstCharacterLowerCase()}{defaultValue}"; } } }
65.446429
233
0.645566
[ "MIT" ]
ehtick/kiota
src/Kiota.Builder/Writers/CSharp/CSharpConventionService.cs
10,995
C#
// Copyright (c) Leonardo Brugnara // Full copyright and license information in LICENSE file using System.Collections.Generic; namespace Zenit.Ast { public class ExpressionListNode : Node { public List<Node> Expressions { get; } public ExpressionListNode(List<Node> args) { this.Expressions = args; } public int Count => this.Expressions?.Count ?? 0; } }
21.2
57
0.636792
[ "MIT" ]
lbrugnara/flsharp
FrontEnd/Ast/ExpressionListNode.cs
426
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("Apollo.DataAccess.EF")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Hewlett-Packard Company")] [assembly: AssemblyProduct("Apollo.DataAccess.EF")] [assembly: AssemblyCopyright("Copyright © Hewlett-Packard Company 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("8c2b0c23-5864-440b-86cd-dc33997e888f")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
39.297297
84
0.753095
[ "MIT" ]
hancheester/apollo
Data Access/Apollo.DataAccess.EF/Properties/AssemblyInfo.cs
1,457
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.Collections.Generic; using System.Diagnostics.CodeAnalysis; namespace System.Diagnostics.Eventing.Reader { /// <summary> /// The metadata for a specific Opcode defined by a Provider. /// An instance of this class is obtained from a ProviderMetadata object. /// </summary> public sealed class EventOpcode { private readonly int _value; private string _name; private string _displayName; private bool _dataReady; private readonly ProviderMetadata _pmReference; private readonly object _syncObject; internal EventOpcode(int value, ProviderMetadata pmReference) { _value = value; _pmReference = pmReference; _syncObject = new object(); } internal EventOpcode(string name, int value, string displayName) { _value = value; _name = name; _displayName = displayName; _dataReady = true; _syncObject = new object(); } internal void PrepareData() { lock (_syncObject) { if (_dataReady == true) return; // Get the data IEnumerable<EventOpcode> result = _pmReference.Opcodes; // Set the names and display names to null _name = null; _displayName = null; _dataReady = true; foreach (EventOpcode op in result) { if (op.Value == _value) { _name = op.Name; _displayName = op.DisplayName; _dataReady = true; break; } } } } // End Prepare Data public string Name { get { PrepareData(); return _name; } } public int Value { get { return _value; } } public string DisplayName { get { PrepareData(); return _displayName; } } } }
26.835165
77
0.484029
[ "MIT" ]
2m0nd/runtime
src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventOpcode.cs
2,442
C#
namespace Kyrodan.HiDrive.Requests { public class BaseRequestBuilder { public IBaseClient Client { get; private set; } public string RequestUrl { get; internal set; } public BaseRequestBuilder(string requestUrl, IBaseClient client) { this.Client = client; this.RequestUrl = requestUrl; } public string AppendSegmentToRequestUrl(string urlSegment) { return string.Format("{0}/{1}", this.RequestUrl, urlSegment); } } }
25.333333
73
0.612782
[ "MIT" ]
Breakpoint21/hidrive-dotnet-sdk
src/Kyrodan.HiDrive/Requests/BaseRequestBuilder.cs
532
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System.Text.Json; using Azure.Core; namespace Azure.ResourceManager.Sql.Models { public partial class PerformanceLevelCapability { internal static PerformanceLevelCapability DeserializePerformanceLevelCapability(JsonElement element) { Optional<double> value = default; Optional<PerformanceLevelUnit> unit = default; foreach (var property in element.EnumerateObject()) { if (property.NameEquals("value")) { value = property.Value.GetDouble(); continue; } if (property.NameEquals("unit")) { unit = new PerformanceLevelUnit(property.Value.GetString()); continue; } } return new PerformanceLevelCapability(Optional.ToNullable(value), Optional.ToNullable(unit)); } } }
30.361111
109
0.584629
[ "MIT" ]
AbelHu/azure-sdk-for-net
sdk/sqlmanagement/Azure.ResourceManager.Sql/src/Generated/Models/PerformanceLevelCapability.Serialization.cs
1,093
C#
namespace TESVSnip.Framework.Collections { using System; using System.Collections; /// <summary> /// The value comparer. /// </summary> public class ValueComparer : IComparer { /// <summary> /// The default comparer. /// </summary> private static readonly ValueComparer defaultComparer; /// <summary> /// Initializes static members of the <see cref="ValueComparer"/> class. /// </summary> static ValueComparer() { defaultComparer = new ValueComparer(); } /// <summary> /// Gets the default. /// </summary> /// <value> /// The default. /// </value> public static ValueComparer Default { get { return defaultComparer; } } /// <summary> /// The compare. /// </summary> /// <param name="x"> /// The x. /// </param> /// <param name="y"> /// The y. /// </param> /// <returns> /// The System.Int32. /// </returns> public static int Compare(object x, object y) { bool xEmpty = IsEmpty(x); bool yEmpty = IsEmpty(y); if (xEmpty) { return yEmpty ? 0 : -1; } else if (yEmpty) { return 1; } try { Type tx = x.GetType(); Type ty = y.GetType(); if (tx == ty) { if (x is IComparable) { return (x as IComparable).CompareTo(y); } } if ((IsNumeric(x) && IsNumericOrString(y)) || (IsNumeric(y) && IsNumericOrString(x))) { Type tt = IsNumeric(x) ? x.GetType() : y.GetType(); if (tt == typeof(int)) { int dx = Convert.ToInt32(x); int dy = Convert.ToInt32(y); return dx == dy ? 0 : dx < dy ? -1 : 1; } else if (tt == typeof(double)) { double dx = Convert.ToDouble(x); double dy = Convert.ToDouble(y); double diff = dx - dy; if (Math.Abs(diff) <= float.Epsilon) { return 0; } if ((double.IsNaN(dx) && double.IsNaN(dy)) || (double.IsInfinity(dx) && double.IsInfinity(dy))) { return 0; } return diff < 0 ? -1 : 1; } else if (tt == typeof(float)) { float dx = Convert.ToSingle(x); float dy = Convert.ToSingle(y); float diff = dx - dy; if (Math.Abs(diff) <= float.Epsilon) { return 0; } if ((float.IsNaN(dx) && float.IsNaN(dy)) || (float.IsInfinity(dx) && float.IsInfinity(dy))) { return 0; } return diff < 0 ? -1 : 1; } else if (tt == typeof(uint)) { var dx = Convert.ToUInt32(x); var dy = Convert.ToUInt32(y); return dx == dy ? 0 : dx < dy ? -1 : 1; } else if (tt == typeof(byte)) { var dx = Convert.ToByte(x); var dy = Convert.ToByte(y); return dx == dy ? 0 : dx < dy ? -1 : 1; } else if (tt == typeof(sbyte)) { var dx = Convert.ToSByte(x); var dy = Convert.ToSByte(y); return dx == dy ? 0 : dx < dy ? -1 : 1; } else if (tt == typeof(short)) { var dx = Convert.ToInt16(x); var dy = Convert.ToInt16(y); return dx == dy ? 0 : dx < dy ? -1 : 1; } else if (tt == typeof(ushort)) { var dx = Convert.ToUInt16(x); var dy = Convert.ToUInt16(y); return dx == dy ? 0 : dx < dy ? -1 : 1; } else if (tt == typeof(decimal)) { var dx = Convert.ToDecimal(x); var dy = Convert.ToDecimal(y); return dx == dy ? 0 : dx < dy ? -1 : 1; } } // handle string separately first if (x is IComparable && y is string) { object oy = Convert.ChangeType(y, tx); if (oy != null) { return (x as IComparable).CompareTo(oy); } } else if (y is IComparable && x is string) { object ox = Convert.ChangeType(x, ty); if (ox is IComparable) { return ((IComparable)ox).CompareTo(y); } } if (tx.IsPrimitive && ty.IsPrimitive) { // more generic convert and test if (x is IComparable && y is IConvertible) { object oy = Convert.ChangeType(y, tx); if (oy is IComparable) { return ((IComparable)x).CompareTo(oy); } } else if (y is IComparable && x is IConvertible) { object ox = Convert.ChangeType(x, ty); if (ox != null) { if (x is IComparable) { return ((IComparable)ox).CompareTo(y); } else { return -(y as IComparable).CompareTo(ox); } } } } } catch { } try { return Comparer.Default.Compare(x, y); } catch { return -1; } } /// <summary> /// The compare. /// </summary> /// <param name="x"> /// The x. /// </param> /// <param name="y"> /// The y. /// </param> /// <param name="tolerance"> /// The tolerance. /// </param> /// <returns> /// The System.Int32. /// </returns> public static int Compare(object x, object y, object tolerance) { if (tolerance == null) { return Compare(x, y); } bool xEmpty = IsEmpty(x); bool yEmpty = IsEmpty(y); if (xEmpty) { return yEmpty ? 0 : -1; } else if (yEmpty) { return 1; } try { if (IsNumeric(x) && IsNumericOrString(y) && IsNumericOrString(tolerance)) { Type tt = tolerance.GetType(); if (tt == typeof(double)) { double dx = Convert.ToDouble(x); double dy = Convert.ToDouble(y); var tol = (double)tolerance; double diff = dx - dy; if (diff == 0.0 || Math.Abs(diff) <= tol) { return 0; } if ((double.IsNaN(dx) && double.IsNaN(dy)) || (double.IsInfinity(dx) && double.IsInfinity(dy))) { return 0; } return diff < 0 ? -1 : 1; } else if (tt == typeof(int)) { int dx = Convert.ToInt32(x); int dy = Convert.ToInt32(y); var tol = (int)tolerance; int diff = dx - dy; if (diff == 0 || Math.Abs(diff) <= tol) { return 0; } return diff < 0 ? -1 : 1; } else if (tt == typeof(decimal)) { decimal dx = Convert.ToDecimal(x); decimal dy = Convert.ToDecimal(y); var tol = (decimal)tolerance; decimal diff = dx - dy; if (diff == 0 || Math.Abs(diff) <= tol) { return 0; } return diff < 0 ? -1 : 1; } else if (tt == typeof(float)) { float dx = Convert.ToSingle(x); float dy = Convert.ToSingle(y); var tol = (float)tolerance; float diff = dx - dy; if (diff == 0.0 || Math.Abs(diff) <= tol) { return 0; } if ((float.IsNaN(dx) && float.IsNaN(dy)) || (float.IsInfinity(dx) && float.IsInfinity(dy))) { return 0; } return diff < 0 ? -1 : 1; } else if (tt == typeof(uint)) { uint dx = Convert.ToUInt32(x); uint dy = Convert.ToUInt32(y); var tol = (uint)tolerance; uint diff = dx - dy; if (diff == 0 || Math.Abs(diff) <= tol) { return 0; } return diff < 0 ? -1 : 1; } else { double dx = Convert.ToDouble(x); double dy = Convert.ToDouble(y); double tol = Convert.ToDouble(tolerance); double diff = dx - dy; if (diff == 0.0 || Math.Abs(diff) <= tol) { return 0; } return diff < 0 ? -1 : 1; } } return Compare(x, y); } catch { } try { return Comparer.Default.Compare(x, y); } catch { return -1; } } /// <summary> /// The is numeric or string. /// </summary> /// <param name="t"> /// The t. /// </param> /// <returns> /// The System.Boolean. /// </returns> public static bool IsNumericOrString(object t) { return IsNumeric(t) || (t is string); } /// <summary> /// The compare. /// </summary> /// <param name="x"> /// The x. /// </param> /// <param name="y"> /// The y. /// </param> /// <returns> /// The System.Int32. /// </returns> int IComparer.Compare(object x, object y) { return Compare(x, y); } /// <summary> /// The is empty. /// </summary> /// <param name="obj"> /// The obj. /// </param> /// <returns> /// The System.Boolean. /// </returns> private static bool IsEmpty(object obj) { return obj == null || obj == DBNull.Value || (obj is string && ((string)obj).Length == 0); } /// <summary> /// The is numeric. /// </summary> /// <param name="t"> /// The t. /// </param> /// <returns> /// The System.Boolean. /// </returns> private static bool IsNumeric(object t) { TypeCode code = Convert.GetTypeCode(t); switch (code) { case TypeCode.Boolean: case TypeCode.DateTime: case TypeCode.Empty: case TypeCode.Object: case TypeCode.String: return false; } return true; } } }
31.860789
119
0.322386
[ "MIT" ]
Sharlikran/tesv-snip
Framework/Collections/ValueComparer.cs
13,734
C#
using DataAccessLibrary; using Microsoft.Extensions.Configuration; using System.IO; using System.Windows; namespace TextCopier { public partial class App : Application { protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); var dataAccess = new SqliteDataAccess(); var crud = new SqliteCrud(GetConnectionString(), dataAccess); Application.Current.MainWindow = new MainWindow(crud); Application.Current.MainWindow.Show(); } private static string GetConnectionString(string connectionStringName = "Default") { string output; var builder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json"); var config = builder.Build(); output = config.GetConnectionString(connectionStringName); return output; } } }
28.4
90
0.628773
[ "MIT" ]
MadalinCernat/TextCopier
TextCopierApp/TextCopier/App.xaml.cs
996
C#
using System; using System.Threading.Tasks; using Cheesebaron.MvxPlugins.Settings.Interfaces; using LiveHTS.Core.Interfaces.Services.Access; using LiveHTS.Core.Interfaces.Services.Config; using LiveHTS.Core.Model.Config; using LiveHTS.Core.Model.Subject; using LiveHTS.Core.Model.Survey; using LiveHTS.Core.Service.Config; using LiveHTS.Presentation.Interfaces; using LiveHTS.Presentation.Interfaces.ViewModel; using MvvmCross.Core.ViewModels; using Newtonsoft.Json; namespace LiveHTS.Presentation.ViewModel { public class SignInViewModel:MvxViewModel, ISignInViewModel { private readonly IAuthService _authService; private readonly IDialogService _dialogService; private readonly ISettings _settings; private readonly IDeviceSetupService _deviceSetupService; private string _username; private string _password; private IMvxCommand _signInCommand; private IMvxCommand _setUpCommand; private bool _isBusy; private string _facility; private string _version; public User User { get; private set; } public string Version { get { return $"v {_version}"; } set { _version = value; RaisePropertyChanged(() => Version); } } public string Facility { get { return _facility; } set { _facility = value; RaisePropertyChanged(() => Facility); } } public string Username { get { return _username; } set { _username = value; RaisePropertyChanged(() => Username); SignInCommand.RaiseCanExecuteChanged(); } } public string Password { get { return _password; } set { _password = value; RaisePropertyChanged(() =>Password); SignInCommand.RaiseCanExecuteChanged(); } } public bool IsBusy { get { return _isBusy; } set { _isBusy = value; RaisePropertyChanged(() => IsBusy); // ManageStatus(); } } public bool AutoSignIn { get; set; } public virtual IMvxCommand SignInCommand { get { _signInCommand = _signInCommand ?? new MvxCommand(AttemptSignIn, CanSignIn); return _signInCommand; } } public IMvxCommand SetUpCommand { get { _setUpCommand = _setUpCommand ?? new MvxCommand(SetUp, CanSetup); return _setUpCommand; } } public SignInViewModel(IAuthService authService, IDialogService dialogService, ISettings settings, IDeviceSetupService deviceSetupService) { _authService = authService; _dialogService = dialogService; _settings = settings; _deviceSetupService = deviceSetupService; IsBusy = false; //TODO : Disable auto sign in AutoSignIn = false; if (AutoSignIn) { Username = "admin"; Password = "c0nste11a"; } } public override void ViewAppeared() { var hapiFac = _settings.GetValue("livehts.practicename", ""); if (!string.IsNullOrWhiteSpace(hapiFac)) { Facility = hapiFac; } } public void LoadDeviceInfo(string serial, string name, string manufacturer) { var practice = _authService.GetDefaultPractice(); _settings.AddOrUpdateValue("livehts.practiceid", practice.Id.ToString()); _settings.AddOrUpdateValue("livehts.practicename", practice.Name); _settings.AddOrUpdateValue("livehts.practicecode", practice.Code); _deviceSetupService.CheckRegister(new Device(serial, serial, name,practice.Id)); var device = _authService.GetDefaultDevice(); _settings.AddOrUpdateValue("livehts.deviceid", device.Id.ToString()); _settings.AddOrUpdateValue("livehts.devicecode", device.Code ?? ""); var provider = _authService.GetDefaultProvider(); _settings.AddOrUpdateValue("livehts.providerid", provider.Id.ToString()); _settings.AddOrUpdateValue("livehts.providername", provider.Person.FullName); } public void LoadVersion(string version) { Version = $"{version}"; } public void UpdateSession() { throw new NotImplementedException(); } private bool CanSignIn() { return !string.IsNullOrWhiteSpace(Username) && !string.IsNullOrWhiteSpace(Password); } private void AttemptSignIn() { IsBusy = true; // _dialogService.ShowWait("Please wait..."); try { User = _authService.SignIn(Username, Password); _settings.AddOrUpdateValue("livehts.userid", User.Id.ToString()); _settings.AddOrUpdateValue("livehts.username", User.UserName); IsBusy = false; ShowViewModel<AppDashboardViewModel>(new { username= User.UserName }); } catch (Exception e) { IsBusy = false; _dialogService.Alert($"{e.Message}", "Sign In Failed", "OK"); } IsBusy = false; } private void SetUp() { ShowViewModel<SetupWizardViewModel>(); } private bool CanSetup() { return true; } public void Quit() { _dialogService.ConfirmExit(); } private void ManageStatus() { if(IsBusy) { Common.StatusInfo.Show(_dialogService); } else { Common.StatusInfo.Close(_dialogService); } } } }
29.611374
146
0.552657
[ "MIT" ]
palladiumkenya/afyamobile
LiveHTS.Presentation/ViewModel/SignInViewModel.cs
6,250
C#
/* * Users: Joao Ricardo / Joao Rodrigues * <description> * Esta Classe serve para Gerir os Pacientes dos Tratadores * </description> * <number> 18845 / 19431 <number> * <email> a18845@alunos.ipca.pt / a19431@alunos.ipca.pt <email> */ using System; using System.Collections.Generic; using System.Collections; using System.Linq; using System.Text; using System.Threading.Tasks; // Biblioteca Excecoes using System.Runtime.Serialization; using System.Security; // Biblioteca dos Ficheiros using System.IO; using System.Runtime.Serialization.Formatters.Binary; using System.Runtime.CompilerServices; using System.Net.Http; using Objetos_Negocio; namespace Dados_Negocio_Tratador { /// <summary> /// Classe que gere a Lista de Pacientes /// </summary> [Serializable] public class Lista_Pacientes { #region ATRIBUTOS static List<ListaPaciente> listaPaciente; #endregion #region METODOS #region CONSTRUTORES /// <summary> /// Construtor de Classe /// </summary> static Lista_Pacientes() { listaPaciente = new List<ListaPaciente>(100); } #endregion #region Ficheiros /// <summary> /// Guarda os dados num Ficherio Binario /// </summary> /// <param name="fileName">Name of the file.</param> /// <returns> /// "true" se conseguir guardar o ficheiro /// "false" caso nao consiga /// </returns> public static bool Save_Hash(string fileName) { try { Stream s = File.Open(fileName, FileMode.Create, FileAccess.ReadWrite); BinaryFormatter b = new BinaryFormatter(); b.Serialize(s,listaPaciente); s.Flush(); s.Close(); s.Dispose(); return true; } catch (ArgumentNullException e) { Console.WriteLine("Erro: " + e.Message); } catch (ArgumentOutOfRangeException e) { Console.WriteLine("Erro: " + e.Message); } catch (ArgumentException e) { Console.WriteLine("Erro: " + e.Message); } catch (PathTooLongException e) { Console.WriteLine("Erro: " + e.Message); } catch (DirectoryNotFoundException e) { Console.WriteLine("Erro: " + e.Message); } catch (FileNotFoundException e) { Console.WriteLine("Erro: " + e.Message); } catch (IOException e) { Console.WriteLine("Erro: " + e.Message); } catch (UnauthorizedAccessException e) { Console.WriteLine("Erro: " + e.Message); } catch (NotSupportedException e) { Console.WriteLine("Erro: " + e.Message); } catch (Exception e) { Console.WriteLine("Erro" + e.Message); } return true; } /// <summary> /// Carrega os dados guardados do Ficheiro /// </summary> /// <param name="fileName">Name of the file.</param> /// <returns> /// "true" caso consiga carregar o ficheiro /// "false" caso nao consiga /// </returns> public static bool Load_Hash(string fileName) { try { if (File.Exists(fileName)) { Stream s = File.Open(fileName, FileMode.Open, FileAccess.Read); BinaryFormatter b = new BinaryFormatter(); listaPaciente = (List<ListaPaciente>)b.Deserialize(s); s.Flush(); s.Close(); s.Dispose(); return true; } } catch (SecurityException e) { Console.WriteLine("Erro: " + e.Message); } catch (SerializationException e) { Console.WriteLine("Erro: " + e.Message); } catch (ArgumentNullException e) { Console.WriteLine("Erro: " + e.Message); } catch (ArgumentOutOfRangeException e) { Console.WriteLine("Erro: " + e.Message); } catch (ArgumentException e) { Console.WriteLine("Erro: " + e.Message); } catch (PathTooLongException e) { Console.WriteLine("Erro: " + e.Message); } catch (DirectoryNotFoundException e) { Console.WriteLine("Erro: " + e.Message); } catch (FileNotFoundException e) { Console.WriteLine("Erro: " + e.Message); } catch (IOException e) { Console.WriteLine("Erro: " + e.Message); } catch (UnauthorizedAccessException e) { Console.WriteLine("Erro: " + e.Message); } catch (NotSupportedException e) { Console.WriteLine("Erro: " + e.Message); } catch (Exception e) { Console.WriteLine("Erro" + e.Message); } return false; } #endregion #region HashTable /// <summary> /// Insere um Paciente /// </summary> /// <param name="nif">The nif.</param> /// <param name="nif_Paciente">The nif paciente.</param> /// <returns> /// "0" caso ja contenha esse Paciente ou ja nao possa conter mais Pacientes /// "1" caso tenha adicionado /// </returns> public static int Inserir_Paciente(ListaPaciente tratador,string nif_Paciente) { try { if (Tratadores.Pesquisa_na_ficha(tratador.Tratador.Cartao_Cidadao) == true) { listaPaciente.Add(tratador); if (tratador.Lst_Paciente.Contains(nif_Paciente) == true) return 0; tratador.Lst_Paciente.Add(nif_Paciente); } else { return 0; } } catch (NotSupportedException e) { Console.WriteLine("Erro: " + e.Message); } catch (ArgumentNullException e) { Console.WriteLine("Erro: " + e.Message); } catch (ArgumentException e) { Console.WriteLine("Erro: " + e.Message); } catch (Exception e) { Console.WriteLine("Erro: " + e.Message); } return 0; } /// <summary> /// Mostra os Pacientes de um Tratador /// </summary> /// <param name="nif"> Tipo string </param> /// <returns> /// "0" caso nao consiga mostrar os Pacientes /// "1" caso consiga /// </returns> public static int Mostrar_Pacientes_DTratador(string nif) { try { int contador = 0; if (Tratadores.Pesquisa_na_ficha(nif) == false) { Console.Clear(); Console.WriteLine("Erro... nao encontrado !\n"); return 0; } else { foreach (ListaPaciente tratador in listaPaciente) { if (string.Compare(tratador.Tratador.Cartao_Cidadao,nif) == 0) { Console.WriteLine("\nTratador: {0}\n", tratador.Tratador.Nome); foreach (string cartao in tratador.Lst_Paciente) { Console.WriteLine("-->{0}º Paciente: {1}\n",contador + 1,cartao); contador++; } return 1; } } } } catch (IOException e) { Console.WriteLine("Erro: " + e.Message); } catch (Exception e) { Console.WriteLine("Erro: " + e.Message); } return 0; } #endregion #endregion } }
31.530822
98
0.43934
[ "Apache-2.0" ]
RicardoPinto18845/-18845_19431_LP2_FII
ClassLibraryTratadores/Lista_Pacientes.cs
9,210
C#
using System.Resources; 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("MeetEric.Contracts")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("MeetEric.Contracts")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] // 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")]
35.193548
84
0.745188
[ "MIT" ]
MeetEric/meeteric-contracts
MeetEric.Contracts/Properties/AssemblyInfo.cs
1,094
C#
//========= Copyright 2016-2019, HTC Corporation. All rights reserved. =========== using UnityEngine.EventSystems; namespace HTC.UnityPlugin.ColliderEvent { public interface IColliderEventHoverEnterHandler : IEventSystemHandler { void OnColliderEventHoverEnter(ColliderHoverEventData eventData); } public interface IColliderEventHoverExitHandler : IEventSystemHandler { void OnColliderEventHoverExit(ColliderHoverEventData eventData); } public interface IColliderEventPressDownHandler : IEventSystemHandler { void OnColliderEventPressDown(ColliderButtonEventData eventData); } public interface IColliderEventPressUpHandler : IEventSystemHandler { void OnColliderEventPressUp(ColliderButtonEventData eventData); } public interface IColliderEventPressEnterHandler : IEventSystemHandler { void OnColliderEventPressEnter(ColliderButtonEventData eventData); } public interface IColliderEventPressExitHandler : IEventSystemHandler { void OnColliderEventPressExit(ColliderButtonEventData eventData); } public interface IColliderEventClickHandler : IEventSystemHandler { void OnColliderEventClick(ColliderButtonEventData eventData); } public interface IColliderEventDragStartHandler : IEventSystemHandler { void OnColliderEventDragStart(ColliderButtonEventData eventData); } public interface IColliderEventDragFixedUpdateHandler : IEventSystemHandler { void OnColliderEventDragFixedUpdate(ColliderButtonEventData eventData); } public interface IColliderEventDragUpdateHandler : IEventSystemHandler { void OnColliderEventDragUpdate(ColliderButtonEventData eventData); } public interface IColliderEventDragEndHandler : IEventSystemHandler { void OnColliderEventDragEnd(ColliderButtonEventData eventData); } public interface IColliderEventDropHandler : IEventSystemHandler { void OnColliderEventDrop(ColliderButtonEventData eventData); } public interface IColliderEventAxisChangedHandler : IEventSystemHandler { void OnColliderEventAxisChanged(ColliderAxisEventData eventData); } }
32.605634
84
0.741253
[ "MIT" ]
Insanious/VR-Graphical-Representation
Assets/HTC.UnityPlugin/ColliderEvent/ColliderEventInterfaces.cs
2,317
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Books.Api.Contexts; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; namespace Books.Api { public class Program { public static void Main(string[] args) { var host = CreateWebHostBuilder(args).Build(); //migrate the database. Best practice = in Main, using service scope using(var scope = host.Services.CreateScope()) { try { var context = scope.ServiceProvider.GetService<BooksContext>(); context.Database.Migrate(); } catch (Exception ex) { var logger = scope.ServiceProvider.GetRequiredService<ILogger<Program>>(); logger.LogError(ex, "An error occurred while migrating the database"); } } //run the web app host.Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>(); } }
31.613636
94
0.601725
[ "MIT" ]
codejoncode/Async-API
Books/Books.Api/Program.cs
1,393
C#
using System; using NServiceBus; using ServiceControl.Features; class MyClass { public void Configure_ServiceControl() { #region Heartbeats_Configure_ServiceControl var endpointConfiguration = new EndpointConfiguration("myendpoint"); endpointConfiguration.HeartbeatPlugin( serviceControlQueue: "ServiceControl_Queue"); #endregion } public void Interval() { #region Heartbeats_interval var endpointConfiguration = new EndpointConfiguration("myendpoint"); endpointConfiguration.HeartbeatPlugin( serviceControlQueue: "ServiceControl_Queue", frequency: TimeSpan.FromMinutes(2)); #endregion } public void Ttl() { #region Heartbeats_ttl var endpointConfiguration = new EndpointConfiguration("myendpoint"); endpointConfiguration.HeartbeatPlugin( serviceControlQueue: "ServiceControl_Queue", frequency: TimeSpan.FromSeconds(30), timeToLive: TimeSpan.FromMinutes(3)); #endregion } public void Disable() { #region Heartbeats_disable var endpointConfiguration = new EndpointConfiguration("myendpoint"); endpointConfiguration.DisableFeature<Heartbeats>(); #endregion } }
25.886792
77
0.645044
[ "Apache-2.0" ]
A-Franklin/docs.particular.net
Snippets/Heartbeats/Heartbeats6_2/Heartbeats.cs
1,322
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 Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview { using static Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Extensions; [Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.DoNotFormat] public partial class TeradataDataSource : Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.ITeradataDataSource, Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.ITeradataDataSourceInternal, Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.IValidates { /// <summary> /// Backing field for Inherited model <see cref= "Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.IDataSource" /// /> /// </summary> private Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.IDataSource __dataSource = new Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.DataSource(); [Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Origin(Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.PropertyOrigin.Inlined)] public global::System.DateTime? CollectionLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.IDataSourcePropertiesInternal)Property).CollectionLastModifiedAt; } [Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Origin(Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.PropertyOrigin.Inlined)] public string CollectionReferenceName { get => ((Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.IDataSourcePropertiesInternal)Property).CollectionReferenceName; set => ((Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.IDataSourcePropertiesInternal)Property).CollectionReferenceName = value ?? null; } [Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Origin(Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.PropertyOrigin.Inlined)] public string CollectionType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.IDataSourcePropertiesInternal)Property).CollectionType; set => ((Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.IDataSourcePropertiesInternal)Property).CollectionType = value ?? null; } [Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Origin(Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.PropertyOrigin.Inlined)] public global::System.DateTime? CreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.IDataSourcePropertiesInternal)Property).CreatedAt; } [Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Origin(Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.PropertyOrigin.Inlined)] public string Host { get => ((Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.ITeradataPropertiesInternal)Property).Host; set => ((Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.ITeradataPropertiesInternal)Property).Host = value ?? null; } [Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Origin(Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.PropertyOrigin.Inherited)] public string Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.IProxyResourceInternal)__dataSource).Id; } [Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Origin(Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.PropertyOrigin.Inherited)] public Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Support.DataSourceType Kind { get => ((Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.IDataSourceInternal)__dataSource).Kind; set => ((Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.IDataSourceInternal)__dataSource).Kind = value ; } [Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Origin(Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.PropertyOrigin.Inlined)] public global::System.DateTime? LastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.IDataSourcePropertiesInternal)Property).LastModifiedAt; } /// <summary>Internal Acessors for Scan</summary> Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.IScan[] Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.IDataSourceInternal.Scan { get => ((Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.IDataSourceInternal)__dataSource).Scan; set => ((Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.IDataSourceInternal)__dataSource).Scan = value; } /// <summary>Internal Acessors for Id</summary> string Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.IProxyResourceInternal.Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.IProxyResourceInternal)__dataSource).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.IProxyResourceInternal)__dataSource).Id = value; } /// <summary>Internal Acessors for Name</summary> string Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.IProxyResourceInternal.Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.IProxyResourceInternal)__dataSource).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.IProxyResourceInternal)__dataSource).Name = value; } /// <summary>Internal Acessors for Collection</summary> Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.ICollectionReference Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.ITeradataDataSourceInternal.Collection { get => ((Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.IDataSourcePropertiesInternal)Property).Collection; set => ((Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.IDataSourcePropertiesInternal)Property).Collection = value; } /// <summary>Internal Acessors for CollectionLastModifiedAt</summary> global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.ITeradataDataSourceInternal.CollectionLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.IDataSourcePropertiesInternal)Property).CollectionLastModifiedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.IDataSourcePropertiesInternal)Property).CollectionLastModifiedAt = value; } /// <summary>Internal Acessors for CreatedAt</summary> global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.ITeradataDataSourceInternal.CreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.IDataSourcePropertiesInternal)Property).CreatedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.IDataSourcePropertiesInternal)Property).CreatedAt = value; } /// <summary>Internal Acessors for LastModifiedAt</summary> global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.ITeradataDataSourceInternal.LastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.IDataSourcePropertiesInternal)Property).LastModifiedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.IDataSourcePropertiesInternal)Property).LastModifiedAt = value; } /// <summary>Internal Acessors for Property</summary> Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.ITeradataProperties Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.ITeradataDataSourceInternal.Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.TeradataProperties()); set { {_property = value;} } } [Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Origin(Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.PropertyOrigin.Inherited)] public string Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.IProxyResourceInternal)__dataSource).Name; } /// <summary>Backing field for <see cref="Property" /> property.</summary> private Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.ITeradataProperties _property; [Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Origin(Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.PropertyOrigin.Owned)] internal Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.ITeradataProperties Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.TeradataProperties()); set => this._property = value; } [Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Origin(Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.PropertyOrigin.Inherited)] public Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.IScan[] Scan { get => ((Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.IDataSourceInternal)__dataSource).Scan; } /// <summary>Creates an new <see cref="TeradataDataSource" /> instance.</summary> public TeradataDataSource() { } /// <summary>Validates that this object meets the validation criteria.</summary> /// <param name="eventListener">an <see cref="Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.IEventListener" /> instance that will receive validation /// events.</param> /// <returns> /// A < see cref = "global::System.Threading.Tasks.Task" /> that will be complete when validation is completed. /// </returns> public async global::System.Threading.Tasks.Task Validate(Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.IEventListener eventListener) { await eventListener.AssertNotNull(nameof(__dataSource), __dataSource); await eventListener.AssertObjectIsValid(nameof(__dataSource), __dataSource); } } public partial interface ITeradataDataSource : Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.IJsonSerializable, Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.IDataSource { [Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Info( Required = false, ReadOnly = true, Description = @"", SerializedName = @"lastModifiedAt", PossibleTypes = new [] { typeof(global::System.DateTime) })] global::System.DateTime? CollectionLastModifiedAt { get; } [Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Info( Required = false, ReadOnly = false, Description = @"", SerializedName = @"referenceName", PossibleTypes = new [] { typeof(string) })] string CollectionReferenceName { get; set; } [Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Info( Required = false, ReadOnly = false, Description = @"", SerializedName = @"type", PossibleTypes = new [] { typeof(string) })] string CollectionType { get; set; } [Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Info( Required = false, ReadOnly = true, Description = @"", SerializedName = @"createdAt", PossibleTypes = new [] { typeof(global::System.DateTime) })] global::System.DateTime? CreatedAt { get; } [Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Info( Required = false, ReadOnly = false, Description = @"", SerializedName = @"host", PossibleTypes = new [] { typeof(string) })] string Host { get; set; } [Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Info( Required = false, ReadOnly = true, Description = @"", SerializedName = @"lastModifiedAt", PossibleTypes = new [] { typeof(global::System.DateTime) })] global::System.DateTime? LastModifiedAt { get; } } internal partial interface ITeradataDataSourceInternal : Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.IDataSourceInternal { Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.ICollectionReference Collection { get; set; } global::System.DateTime? CollectionLastModifiedAt { get; set; } string CollectionReferenceName { get; set; } string CollectionType { get; set; } global::System.DateTime? CreatedAt { get; set; } string Host { get; set; } global::System.DateTime? LastModifiedAt { get; set; } Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.ITeradataProperties Property { get; set; } } }
78.612717
494
0.757426
[ "MIT" ]
Agazoth/azure-powershell
src/Purview/Purviewdata.Autorest/generated/api/Models/Api20211001Preview/TeradataDataSource.cs
13,428
C#
using System; using System.Collections.Generic; namespace _14_Osoba_Zivotinja { class Program { static void Main(string[] args) { //Klasični način kreiranja objekata //i popunjavanja svojstava Osoba partner = new Osoba(); partner.Ime = "Ava"; partner.Prezime = "Karabatić"; Osoba oso = new Osoba(); oso.Ime = "Mirko"; oso.Prezime = "Spirko"; oso.Partner = partner; Osoba clon = (Osoba)oso.Clone(); //Skraćeni Zivotinja medvjed = new Zivotinja() { LatinskiNaziv = "Ursus arctos", NarodniNaziv = "Mrki medvjed" }; Zivotinja medo = new Zivotinja(); medo.LatinskiNaziv = "Ursus..."; medo.NarodniNaziv = "medvjed"; // Na isti nacin ispisujemo dva razlicita objekta, koja djele isti IF Ispis(medo); Ispis(medvjed); Ispis(oso); Ispis(partner); Ispis(clon); Console.WriteLine("Ispis comperable"); List<Osoba> poredakPoPlaci = new List<Osoba>(); poredakPoPlaci.Add(partner); poredakPoPlaci.Add(clon); Console.WriteLine("Ispis comperable prije sort"); foreach (var item in poredakPoPlaci) { Ispis(item); } poredakPoPlaci.Sort(); oso.Dispose(); Console.WriteLine("Ispis comperable nakon sort"); foreach (var item in poredakPoPlaci) { Ispis(item); } Console.ReadKey(); } static void Ispis(IMojInterface klasaZaIspis) { Console.WriteLine(klasaZaIspis.PunoIme()); } } }
23.407407
81
0.494726
[ "MIT" ]
hrdasdominik/AlgebraC-2020
14_Osoba_Zivotinja/Program.cs
1,902
C#
using System; using System.Collections.Generic; namespace SKIT.FlurlHttpClient.Wechat.Api.Models { /// <summary> /// <para>表示 [POST] /merchant/shelf/getbyid 接口的请求。</para> /// </summary> public class MerchantShelfGetByIdRequest : WechatApiRequest { /// <summary> /// 获取或设置货架 ID。 /// </summary> [Newtonsoft.Json.JsonProperty("shelf_id")] [System.Text.Json.Serialization.JsonPropertyName("shelf_id")] public int ShelfId { get; set; } } }
26.789474
69
0.628684
[ "MIT" ]
KimMeng2015/DotNetCore.SKIT.FlurlHttpClient.Wechat
src/SKIT.FlurlHttpClient.Wechat.Api/Models/Merchant/Shelf/MerchantShelfGetByIdRequest.cs
543
C#
using System; using System.Net; using System.Linq; using System.Net.NetworkInformation; using System.Collections.Generic; namespace NetworkTrayGraph { public class InterfaceStatistics { public string Name; public string Id; public OperationalStatus Status; public long ReceivedBytes; public long SentBytes; public long LastReceivedBytes; public long LastSentBytes; public int BytesReceivedPerSecond; public int BytesSentPerSecond; public InterfaceStatistics() { } public InterfaceStatistics(InterfaceStatistics old) { Name = old.Name; Id = old.Id; Status = old.Status; SentBytes = old.SentBytes; ReceivedBytes = old.ReceivedBytes; LastSentBytes = old.LastSentBytes; LastReceivedBytes = old.LastReceivedBytes; BytesReceivedPerSecond = old.BytesReceivedPerSecond; BytesSentPerSecond = old.BytesSentPerSecond; } } /// <summary> /// Network monitor updates and stores data about all network interfaces on the computer. The update function is called by the main application /// and fetches the most recent bytes sent and received by the interface /// </summary> public class NetworkMonitor { public Dictionary<string, InterfaceStatistics> InterfaceStats { get; private set; } = new Dictionary<string, InterfaceStatistics>(); private List<NetworkInterface> _availableInterfaces = new List<NetworkInterface>(); public NetworkMonitor() { } public List<string> GetAvailableInterfaceNames() { // Update our internal list of adapters first UpdateAvailableAdapters(); // Return the name to the caller return _availableInterfaces.Select(x => x.Name).ToList(); } /// <summary> /// Removes old interfaces from the InterfaceStats Dictionary that aren't available or enabled anymore /// </summary> /// <param name="settings"></param> public void PruneInterfaceStatistics(GraphSettings settings) { List<string> enabledAdapterNames = settings.EnabledInterfaces.Where(i => i.Value == true).Select(x => x.Key).ToList(); List<string> keysToRemove = new List<string>(); foreach (var stat in InterfaceStats) { if (!enabledAdapterNames.Contains(stat.Key) || !_availableInterfaces.Select(x => x.Name).Contains(stat.Key)) keysToRemove.Add(stat.Key); } foreach (var key in keysToRemove) { InterfaceStats.Remove(key); } } /// <summary> /// Updates the InterfaceStats dictionary with the most current sent and received bytes, this is used to calculate that adapters /// bytes per second, which is displayed on the graph /// </summary> /// <param name="settings"></param> public void Update(GraphSettings settings) { List<string> enabledAdapterNames = settings.EnabledInterfaces.Where(i => i.Value == true).Select(x => x.Key).ToList(); // Loop through available and enabled adapters foreach (NetworkInterface nic in _availableInterfaces.Where(x => enabledAdapterNames.Contains(x.Name))) { string adapterName = nic.Name; if (!InterfaceStats.ContainsKey(adapterName)) { InterfaceStats.Add(adapterName, CreateAdapterStatistics(nic)); } else { InterfaceStats[adapterName] = UpdateAdapterStatistics(nic, InterfaceStats[adapterName], settings.UpdateInterval); ; } } } private void UpdateAvailableAdapters() { _availableInterfaces = NetworkInterface.GetAllNetworkInterfaces().ToList(); } private InterfaceStatistics CreateAdapterStatistics(NetworkInterface @interface) { IPv4InterfaceStatistics interfaceStats = @interface.GetIPv4Statistics(); InterfaceStatistics stats = new InterfaceStatistics() { Name = @interface.Name, Id = @interface.Id, Status = @interface.OperationalStatus, SentBytes = interfaceStats.BytesSent, ReceivedBytes = interfaceStats.BytesReceived, LastSentBytes = interfaceStats.BytesSent, LastReceivedBytes = interfaceStats.BytesReceived, BytesReceivedPerSecond = 0, BytesSentPerSecond = 0 }; return stats; } private InterfaceStatistics UpdateAdapterStatistics(NetworkInterface @interface, InterfaceStatistics oldStats, int updateIntervalMs) { IPv4InterfaceStatistics interfaceIPv4Stats = @interface.GetIPv4Statistics(); InterfaceStatistics newStats = new InterfaceStatistics(oldStats); newStats.Status = @interface.OperationalStatus; newStats.LastSentBytes = oldStats.SentBytes; newStats.LastReceivedBytes = oldStats.ReceivedBytes; newStats.SentBytes = interfaceIPv4Stats.BytesSent; newStats.ReceivedBytes = interfaceIPv4Stats.BytesReceived; try { newStats.BytesSentPerSecond = Convert.ToInt32((newStats.SentBytes - newStats.LastSentBytes) * (updateIntervalMs / 1000)); newStats.BytesReceivedPerSecond = Convert.ToInt32((newStats.ReceivedBytes - newStats.LastReceivedBytes) * (updateIntervalMs / 1000)); } catch(Exception) { newStats.BytesSentPerSecond = 0; newStats.BytesReceivedPerSecond = 0; } return newStats; } } }
36.634146
149
0.614181
[ "MIT" ]
Killeroo/Chasovoy
NetworkTrayGraph/NetworkMonitor.cs
6,010
C#
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using EventDrivenThinking.EventInference.Schema; using Humanizer; namespace EventDrivenThinking.Tests.Common { public class EventDictionary { private List<EventEntry> _events; private List<CommandEntry> _commands; private List<QueryEntry> _queries; public class QueryEntry { public Type QueryType { get; private set; } public IQuerySchema QuerySchema { get; private set; } public Statement Description { get; private set; } public QueryEntry(Type queryType, IQuerySchema querySchema) { string text = $"{querySchema.Category.Humanize()} {querySchema.Type.Name.Humanize()}"; QueryType = queryType; QuerySchema = querySchema; Description = new Statement(text); } } public class CommandEntry { public Type CommandType { get; private set; } public IClientCommandSchema CommandSchema { get; private set; } public Statement Description { get; private set; } public CommandEntry(Type commandType, IClientCommandSchema metadata) { string text = $"{metadata.Category.Humanize()} {commandType.Name.Humanize()}"; Description = new Statement(text); CommandType = commandType; CommandSchema = metadata; } } public class EventEntry { public Type EventType { get; private set; } public IAggregateSchema AggregateSchema { get; private set; } public Statement Description { get; private set; } public EventEntry(Type eventType, IAggregateSchema schema) { string text = $"{schema.Category.Humanize()} {eventType.Name.Humanize()}"; Description = new Statement(text); EventType = eventType; AggregateSchema = schema; } } private QuerySchemaRegister _querySchemaRegister; private AggregateSchemaRegister _aggregateSchemaRegister; private CommandsSchemaRegister _schemaRegister; private ProjectionSchemaRegister _projectionSchemaRegister; public IAggregateSchemaRegister AggregateSchemaRegister => _aggregateSchemaRegister; public IQuerySchemaRegister QuerySchemaRegister => _querySchemaRegister; public IProjectionSchemaRegister ProjectionSchemaRegister => _projectionSchemaRegister; public EventDictionary(params Assembly[] assemblies) { PrepareCommands(assemblies); PrepareEvents(assemblies); PrepareQueries(assemblies); PrepareProjections(assemblies); } private void PrepareProjections(Assembly[] assemblies) { _projectionSchemaRegister = new ProjectionSchemaRegister(); _projectionSchemaRegister.Discover(assemblies); } void PrepareQueries(params Assembly[] assemblies) { _querySchemaRegister = new QuerySchemaRegister(); _querySchemaRegister.Discover(assemblies); _queries = new List<QueryEntry>(); foreach (var q in _querySchemaRegister) { _queries.Add(new QueryEntry(q.Type, q)); } } void PrepareEvents(params Assembly[] assemblies) { this._aggregateSchemaRegister = new AggregateSchemaRegister(); _aggregateSchemaRegister.Discover(assemblies); _events = new List<EventEntry>(); foreach (IAggregateSchema i in _aggregateSchemaRegister) { foreach (var e in i.Events) _events.Add(new EventEntry(e.EventType, i)); } } void PrepareCommands(params Assembly[] assemblies) { this._schemaRegister = new CommandsSchemaRegister(); _schemaRegister.Discover(assemblies); _commands = new List<CommandEntry>(); foreach (var c in _schemaRegister) _commands.Add(new CommandEntry(c.Type, c)); } public Type FindEvent(string text) { Statement st = new Statement(text); var similarEntries = _events.Select(x => new { Entry = x, Similarity = st.ComputeSimilarity(x.Description) }).OrderByDescending(x => x.Similarity) .ToArray(); return similarEntries[0].Entry.EventType; } public (Type, IClientCommandSchema) FindCommand(string commandType) { Statement st = new Statement(commandType); var similarEntries = _commands.Select(x => new { Entry = x, Similarity = st.ComputeSimilarity(x.Description) }).OrderByDescending(x => x.Similarity) .ToArray(); var entry = similarEntries[0].Entry; return (entry.CommandType, entry.CommandSchema); } public Type FindQuery(string queryName) { Statement st = new Statement(queryName); var similarEntries = _queries.Select(x => new { Entry = x, Similarity = st.ComputeSimilarity(x.Description) }).OrderByDescending(x => x.Similarity) .ToArray(); var entry = similarEntries[0].Entry; return entry.QueryType; } } }
36.858065
102
0.589008
[ "MIT" ]
eventmodeling/eventdriventhinking
EventDrivenThinking.Tests/Common/EventDictionary.cs
5,715
C#
using Catalog.API.Entities; using Catalog.API.Repositories; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using System.Collections.Generic; using System.Net; using System.Threading.Tasks; namespace Catalog.API.Controllers { [Route("api/[controller]")] [ApiController] public class CatalogController : ControllerBase { private readonly IProductRepository _repository; private readonly ILogger<CatalogController> _logger; public CatalogController(IProductRepository repository, ILogger<CatalogController> logger) { _repository = repository; _logger = logger; } [HttpGet] [ProducesResponseType(typeof(IEnumerable<Product>), (int)HttpStatusCode.OK)] public async Task<ActionResult<IEnumerable<Product>>> GetProducts() { var products = await _repository.GetProducts(); return Ok(products); } [HttpGet("{id:length(24)}", Name = "GetProduct")] [ProducesResponseType((int)HttpStatusCode.NotFound)] [ProducesResponseType(typeof(Product), (int)HttpStatusCode.OK)] public async Task<ActionResult<Product>> GetProductById(string id) { var product = await _repository.GetProduct(id); if (product == null) { _logger.LogError($"Product with id: {id}, not found."); return NotFound(); } return Ok(product); } [Route("[action]/{category}", Name = "GetProductByCategory")] [HttpGet] [ProducesResponseType(typeof(IEnumerable<Product>), (int)HttpStatusCode.OK)] public async Task<ActionResult<IEnumerable<Product>>> GetProductByCategory(string category) { var products = await _repository.GetProductByCategory(category); return Ok(products); } [HttpPost] [ProducesResponseType(typeof(Product), (int)HttpStatusCode.OK)] public async Task<ActionResult<Product>> CreateProduct([FromBody] Product product) { await _repository.CreateProduct(product); return CreatedAtRoute("GetProduct", new { id = product.Id }, product); } [HttpPut] [ProducesResponseType(typeof(Product), (int)HttpStatusCode.OK)] public async Task<IActionResult> UpdateProduct([FromBody] Product product) { return Ok(await _repository.UpdateProduct(product)); } [HttpDelete("{id:length(24)}", Name = "DeleteProduct")] [ProducesResponseType(typeof(Product), (int)HttpStatusCode.OK)] public async Task<IActionResult> DeleteProductById(string id) { return Ok(await _repository.DeleteProduct(id)); } } }
35.024691
99
0.641523
[ "MIT" ]
sarun4jun90/.Net5Microservices
src/Services/Catalog/Catalog.API/Controllers/CatalogController.cs
2,839
C#
using System.Data.Common; namespace Weasel.Core { /// <summary> /// Interface for services that can create a new connection object /// to the underlying database /// </summary> public interface IConnectionSource: IConnectionSource<DbConnection> { } /// <summary> /// Interface for services that can create a new connection object /// to the underlying database /// </summary> /// <typeparam name="T"></typeparam> public interface IConnectionSource<T> where T : DbConnection { /// <summary> /// Fetch a connection to the tenant database /// </summary> /// <returns></returns> public T CreateConnection(); } }
25.535714
71
0.616783
[ "MIT" ]
JasperFx/weasel
src/Weasel.Core/IConnectionSource.cs
715
C#
using System.Windows; namespace SixtenLabs.Gluten { /// <summary> /// Configuration passed to WindowManager (normally implemented by BootstrapperBase) /// </summary> public interface IWindowManagerConfig { /// <summary> /// Returns the currently-displayed window, or null if there is none (or it can't be determined) /// </summary> /// <returns>The currently-displayed window, or null</returns> Window GetActiveWindow(); } }
26.058824
98
0.717833
[ "Unlicense" ]
SixtenLabs/Gluten
src/SixtenLabs.Gluten/Interfaces/IWindowManagerConfig.cs
445
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; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.Json; using System.Threading.Tasks; using CancellationToken = System.Threading.CancellationToken; namespace Microsoft.DotNet.HotReload.Utils.Generator.Script.Json; /// Read a diff script from a json file public class Parser { public readonly string Path; private readonly string _absDir; public Parser (string path) { Path = path; _absDir = System.IO.Path.GetDirectoryName(System.IO.Path.GetFullPath(path))!; } public async ValueTask<Script?> ReadRawAsync (Stream stream, CancellationToken ct = default) { var options = new JsonSerializerOptions { ReadCommentHandling = JsonCommentHandling.Skip, AllowTrailingCommas = true, PropertyNameCaseInsensitive = true, }; try { var result = await JsonSerializer.DeserializeAsync<Script>(stream, options: options, cancellationToken: ct); return result; } catch (JsonException exn) { throw new DiffyException($"error parsing diff script '{Path}'", exn, exitStatus: 15); } } private string AbsPath (string relativePath) { return System.IO.Path.GetFullPath(relativePath, _absDir); } public async ValueTask<ParsedScript> ReadAsync (Stream stream, CancellationToken ct = default) { var script = await ReadRawAsync(stream, ct); if (script == null) return ParsedScript.Empty; Plan.Change<string,string>[] changes; if (script.Changes == null) changes = Array.Empty<Plan.Change<string,string>>(); else changes = script.Changes.Select(c => Plan.Change.Create(AbsPath(c.Document), AbsPath(c.Update))).ToArray(); EnC.EditAndContinueCapabilities? caps = null; IEnumerable<string> unknowns = Array.Empty<string>(); if (script.Capabilities != null) { IEnumerable<EnC.EditAndContinueCapabilities> goodCaps; (goodCaps, unknowns) = EditAndContinueCapabilitiesParser.Parse(script.Capabilities); var totalCaps = EnC.EditAndContinueCapabilities.None; foreach (var cap in goodCaps) { totalCaps |= cap; } caps = totalCaps; } return ParsedScript.Make(changes, caps, unknowns); } }
38.242424
120
0.663629
[ "MIT" ]
ScriptBox99/dotnet-hotreload-utils
src/Microsoft.DotNet.HotReload.Utils.Generator/Script/Json/Parsing.cs
2,524
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace RMQWonderwareAdapter { public partial class FormWriteTag : Form { public FormWriteTag() { InitializeComponent(); } private void buttonOK_Click(object sender, EventArgs e) { this.DialogResult = DialogResult.OK; this.Close(); } private void FormWriteTag_Load(object sender, EventArgs e) { this.textBoxValue.Focus(); this.ActiveControl = this.textBoxValue; } } }
23.151515
67
0.609948
[ "MIT" ]
znoop333/RMQWonderwareAdapter
RMQWonderwareAdapter/RMQWonderwareAdapter/FormWriteTag.cs
766
C#
using System; using System.Collections.Generic; using System.Linq; using GR.Identity.Abstractions; using GR.Notifications.Abstractions; using GR.Notifications.Abstractions.Models.Config; using GR.Notifications.Abstractions.Models.Notifications; using Microsoft.AspNetCore.SignalR; namespace GR.Notifications.Hub.Hubs { public class CommunicationHub : ICommunicationHub { #region Injectable /// <summary> /// Inject hub /// </summary> private readonly IHubContext<GearNotificationHub> _hub; #endregion public CommunicationHub(IHubContext<GearNotificationHub> hub) { _hub = hub; } /// <inheritdoc /> /// <summary> /// Send notification /// </summary> /// <param name="users"></param> /// <param name="notification"></param> public virtual void SendNotification(IEnumerable<Guid> users, SystemNotifications notification) { if (notification == null) return; foreach (var user in users) { var userConnections = GearNotificationHub.UserConnections.Connections.GetConnectionsOfUserById(user); userConnections.ToList().ForEach(c => { notification.UserId = user; _hub.Clients.Client(c).SendAsync(SignalrSendMethods.SendClientNotification, notification); }); } } /// <summary> /// Send data /// </summary> /// <param name="users"></param> /// <param name="data"></param> public virtual void SendData(IEnumerable<Guid> users, Dictionary<string, object> data) { if (data == null) return; foreach (var user in users) { var userConnections = GearNotificationHub.UserConnections.Connections.GetConnectionsOfUserById(user); userConnections.ToList().ForEach(c => { _hub.Clients.Client(c).SendAsync(SignalrSendMethods.SendData, data); }); } } /// <summary> /// Send data /// </summary> /// <param name="users"></param> /// <param name="data"></param> public virtual void SendData(IEnumerable<Guid> users, object data) { if (data == null) return; foreach (var user in users) { var userConnections = GearNotificationHub.UserConnections.Connections.GetConnectionsOfUserById(user); userConnections.ToList().ForEach(c => { _hub.Clients.Client(c).SendAsync(SignalrSendMethods.SendData, data); }); } } /// <inheritdoc /> /// <summary> /// Check if user is online /// </summary> /// <param name="userId"></param> /// <returns></returns> public virtual bool GetUserOnlineStatus(Guid userId) { var userConnections = GearNotificationHub.UserConnections.Connections.GetConnectionsOfUserById(userId); return userConnections.Any(); } /// <inheritdoc /> /// <summary> /// Check if user is online /// </summary> /// <param name="user"></param> /// <returns></returns> public virtual bool IsUserOnline(GearUser user) { return user == null ? default : GetUserOnlineStatus(user.Id); } /// <inheritdoc /> /// <summary> /// Get sessions count /// </summary> /// <returns></returns> public virtual int GetSessionsCount() { return GearNotificationHub.UserConnections.Connections.GetSessionCount(); } /// <inheritdoc /> /// <summary> /// Get sessions by user id /// </summary> /// <param name="userId"></param> /// <returns></returns> public virtual int GetSessionsCountByUserId(Guid userId) { return GearNotificationHub.UserConnections.Connections.GetSessionsByUserId(userId); } /// <inheritdoc /> /// <summary> /// Get online users /// </summary> /// <returns></returns> public virtual IEnumerable<Guid> GetOnlineUsers() { return GearNotificationHub.UserConnections.Connections.GetUsersOnline(); } } }
32.854015
117
0.554766
[ "MIT" ]
indrivo/GEAR
src/GR.Extensions/GR.Notifications.Extension/GR.Notifications.Hub/Hubs/CommunicationHub.cs
4,503
C#
using System; using System.Collections.Generic; using Abp.Authorization.Users; using Abp.Extensions; namespace maarif.myproject.Authorization.Users { public class User : AbpUser<User> { public const string DefaultPassword = "123qwe"; public static string CreateRandomPassword() { return Guid.NewGuid().ToString("N").Truncate(16); } public static User CreateTenantAdminUser(int tenantId, string emailAddress) { var user = new User { TenantId = tenantId, UserName = AdminUserName, Name = AdminUserName, Surname = AdminUserName, EmailAddress = emailAddress, Roles = new List<UserRole>() }; user.SetNormalizedNames(); return user; } } }
25
83
0.564571
[ "MIT" ]
eminekiricii/maarifProject
aspnet-core/src/maarif.myproject.Core/Authorization/Users/User.cs
877
C#
using UnityEngine; using System.Collections.Generic; using OmiyaGames; using OmiyaGames.Audio; using OmiyaGames.Menu; namespace Project { ///----------------------------------------------------------------------- /// <copyright file="MenuTest.cs" company="Omiya Games"> /// The MIT License (MIT) /// /// Copyright (c) 2014-2018 Omiya Games /// /// 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. /// </copyright> /// <author>Taro Omiya</author> /// <date>8/21/2015</date> ///----------------------------------------------------------------------- /// <summary>A simple test script: displays the <code>PauseMenu</code>, <code>LevelFailedMenu</code>, or <code>LevelCompleteMenu</code></summary> /// <seealso cref="PauseMenu"/> /// <seealso cref="LevelFailedMenu"/> /// <seealso cref="LevelCompleteMenu"/> public class MenuTest : MonoBehaviour { [SerializeField] string[] popUpTexts; int popUpTextsIndex = 0; readonly List<KeyValuePair<ulong, string>> allPopUpTexts = new List<KeyValuePair<ulong, string>>(); public void OnPopUpClicked() { // Show a new dialog MenuManager manager = Singleton.Get<MenuManager>(); ulong id = manager.PopUps.ShowNewDialog(popUpTexts[popUpTextsIndex]); // Store information allPopUpTexts.Add(new KeyValuePair<ulong, string>(id, popUpTexts[popUpTextsIndex])); // Get next index ++popUpTextsIndex; if (popUpTextsIndex >= popUpTexts.Length) { popUpTextsIndex = 0; } } public void OnPopUpHideTopClicked() { if (allPopUpTexts.Count > 0) { MenuManager manager = Singleton.Get<MenuManager>(); manager.PopUps.RemoveDialog(allPopUpTexts[allPopUpTexts.Count - 1].Key); allPopUpTexts.RemoveAt(allPopUpTexts.Count - 1); } } public void OnPopUpHideBottomClicked() { if (allPopUpTexts.Count > 0) { MenuManager manager = Singleton.Get<MenuManager>(); ulong id = manager.PopUps.RemoveLastVisibleDialog(); for (int index = (allPopUpTexts.Count - 1); index >= 0; --index) { if (allPopUpTexts[index].Key == id) { allPopUpTexts.RemoveAt(index); break; } } } } public void OnPopUpHideRandomClicked() { if (allPopUpTexts.Count > 0) { MenuManager manager = Singleton.Get<MenuManager>(); int randomIndex = (allPopUpTexts.Count - manager.PopUps.MaximumNumberOfDialogs); if (randomIndex < 0) { randomIndex = 0; } randomIndex = Random.Range(randomIndex, allPopUpTexts.Count); manager.PopUps.RemoveDialog(allPopUpTexts[randomIndex].Key); allPopUpTexts.RemoveAt(randomIndex); } } public void OnPauseClicked() { Singleton.Get<MenuManager>().Show<PauseMenu>(); } public void OnFailedClicked() { Singleton.Get<MenuManager>().Show<LevelFailedMenu>(); } public void OnCompleteClicked() { Singleton.Get<MenuManager>().Show<LevelCompleteMenu>(); } public void OnSoundClicked() { SoundEffect sound = GetComponent<SoundEffect>(); if (sound != null) { sound.Play(); } } public void OnNextLevelClicked() { // Transition to the current level Singleton.Get<OmiyaGames.Scenes.SceneTransitionManager>().LoadNextLevel(); } } }
37.428571
150
0.546183
[ "MIT" ]
OmiyaGames/gamemakers-toolkit-jam-2018
Assets/Project/Scripts/MenuTest.cs
5,242
C#
using System.IO; using System.Text; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using SocketClient.Messages; namespace SocketClient.Protocols { public class JsonMessageProtocol : Protocol<Message> { static readonly JsonSerializer _serializer; static readonly JsonSerializerSettings _settings; static JsonMessageProtocol() { _settings = new JsonSerializerSettings { Formatting = Formatting.Indented, DateTimeZoneHandling = DateTimeZoneHandling.Utc, ContractResolver = new DefaultContractResolver { }, Converters = new JsonConverter[] { new MessageConverter() } }; _settings.PreserveReferencesHandling = PreserveReferencesHandling.None; _serializer = JsonSerializer.Create(_settings); } protected override Message Decode(byte[] message) => JsonConvert.DeserializeObject<Message>(Encoding.UTF8.GetString(message), _settings); protected override byte[] EncodeBody<T>(T message) { var sb = new StringBuilder(); var sw = new StringWriter(sb); _serializer.Serialize(sw, message); return Encoding.UTF8.GetBytes(sb.ToString()); } } }
33.717949
99
0.643346
[ "MIT" ]
MohamedAl-Hussein/janggi-game
JanggiGame/SocketClient/Protocols/JsonMessageProtocol.cs
1,317
C#
using System; namespace ExpressMapper.Tests.Model.Models.Structs { public struct Feature { public Guid Id { get; set; } public string Name { get; set; } public string Description { get; set; } public decimal Rank { get; set; } } }
21.307692
50
0.602888
[ "Apache-2.0" ]
Enegia/ExpressMapper
ExpressMapper.Tests.Model/Models/Structs/Feature.cs
279
C#
using System; namespace Whyvra.Tunnel.Domain.Entitites { public class ClientNetworkAddress : IEntity { public int Id { get; set; } public int ClientId { get; set; } public WireguardClient Client { get; set; } public int NetworkAddressId { get; set; } public NetworkAddress NetworkAddress { get; set; } public DateTime CreatedAt { get; set; } public DateTime UpdatedAt { get; set; } } }
21.904762
58
0.623913
[ "MIT" ]
whyvra/tunnel
Whyvra.Tunnel.Domain/Entities/ClientNetworkAddress.cs
460
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { using System; using Telerik.Web.UI; [Obsolete("Telerik support will be removed in DNN Platform 10.0.0. You will need to find an alternative solution")] public class DnnTreeList : RadTreeList { } }
30.3125
121
0.705155
[ "MIT" ]
Acidburn0zzz/Dnn.Platform
DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTreeList.cs
487
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; using Pliant.Builders; using Pliant.Grammars; using Pliant.LexerRules; namespace Pliant.Tests.Unit.Builders { [TestClass] public class GrammarModelTests { [TestMethod] public void GrammarModelShouldAddProductionModel() { var grammar = new GrammarModel(); grammar.Productions.Add( new ProductionModel("")); Assert.AreEqual(1, grammar.Productions.Count); } [TestMethod] public void GrammarModelShouldAddIgnoreLexerRuleModel() { var grammar = new GrammarModel(); var lexerRuleModel = new LexerRuleModel { Value = new StringLiteralLexerRule("this is a literal") }; grammar.IgnoreSettings.Add( new IgnoreSettingModel( lexerRuleModel)); grammar.LexerRules.Add(lexerRuleModel); Assert.AreEqual(1, grammar.LexerRules.Count); Assert.AreEqual(1, grammar.IgnoreSettings.Count); } [TestMethod] public void GrammarModelToGrammarShouldCreateGrammar() { var grammarModel = new GrammarModel(); var S = new ProductionModel("S"); var A = new ProductionModel("A"); var B = new ProductionModel("B"); var a = new StringLiteralLexerRule("a"); var b = new StringLiteralLexerRule("b"); var space = new StringLiteralLexerRule(" "); S.AddWithAnd(A.LeftHandSide); S.AddWithAnd(B.LeftHandSide); S.AddWithOr(B.LeftHandSide); A.AddWithAnd(new LexerRuleModel(a)); B.AddWithAnd(new LexerRuleModel(b)); grammarModel.Productions.Add(S); grammarModel.Productions.Add(A); grammarModel.Productions.Add(B); var lexerRuleModel = new LexerRuleModel(space); grammarModel.LexerRules.Add(lexerRuleModel); grammarModel.IgnoreSettings.Add( new IgnoreSettingModel(lexerRuleModel)); grammarModel.Start = S; var grammar = grammarModel.ToGrammar(); Assert.AreEqual(4, grammar.Productions.Count); Assert.AreEqual(1, grammar.Ignores.Count); } [TestMethod] public void GrammarModelToGrammarShouldResolverProductionReferencesFromOtherGrammars() { var S = new ProductionModel { LeftHandSide = new NonTerminalModel(new FullyQualifiedName("ns1", "S")) }; var A = new ProductionModel { LeftHandSide = new NonTerminalModel(new FullyQualifiedName("ns1", "A")) }; S.Alterations.Add( new AlterationModel( new[] { A })); A.Alterations.Add( new AlterationModel( new[] { new LexerRuleModel( new StringLiteralLexerRule("a"))}) ); var ns1GrammarModel = new GrammarModel { Start = S }; ns1GrammarModel.Productions.Add(S); ns1GrammarModel.Productions.Add(A); var ns1ProductionReferece = new ProductionReferenceModel(ns1GrammarModel.ToGrammar()); var Z = new ProductionModel { LeftHandSide = new NonTerminalModel(new FullyQualifiedName("ns2", "Z")) }; var X = new ProductionModel { LeftHandSide = new NonTerminalModel(new FullyQualifiedName("ns2", "X")) }; X.Alterations.Add( new AlterationModel( new SymbolModel[] { Z, ns1ProductionReferece })); var ns2GrammarModel = new GrammarModel { Start = Z }; ns2GrammarModel.Productions.Add(Z); ns2GrammarModel.Productions.Add(X); var ns2Grammar = ns2GrammarModel.ToGrammar(); Assert.AreEqual(4, ns2Grammar.Productions.Count); } [TestMethod] public void GrammarModelToGrammarShouldAddProductionWhenEmptyDefinition() { var S = new ProductionModel("S"); var grammarModel = new GrammarModel(S); var grammar = grammarModel.ToGrammar(); Assert.AreEqual(1, grammar.Productions.Count); } [TestMethod] public void GrammarModelConstructorGivenOnlyStartProductionShouldDiscoverLinkedProductions() { var S = new ProductionModel("S"); var A = new ProductionModel("A"); var B = new ProductionModel("B"); var C = new ProductionModel("C"); S.AddWithAnd(A); A.AddWithAnd(B); A.AddWithOr(C); B.AddWithAnd(new LexerRuleModel(new StringLiteralLexerRule("b"))); C.AddWithAnd(new LexerRuleModel(new StringLiteralLexerRule("c"))); var grammarModel = new GrammarModel(S); var grammar = grammarModel.ToGrammar(); Assert.AreEqual(5, grammar.Productions.Count); } [TestMethod] public void GrammarModelConstructorGivenOnlyStartProductionShouldTraverseRecursiveStructureOnlyOnce() { var S = new ProductionModel("S"); var A = new ProductionModel("A"); S.AddWithAnd(S); S.AddWithOr(A); A.AddWithAnd(new LexerRuleModel(new StringLiteralLexerRule("a"))); var grammarModel = new GrammarModel(S); var grammar = grammarModel.ToGrammar(); Assert.AreEqual(3, grammar.Productions.Count); } [TestMethod] public void GrammarModelGivenNullStartShouldResolveStartFromProductions() { var S = new ProductionModel("S"); var A = new ProductionModel("A"); var B = new ProductionModel("B"); S.AddWithAnd(A); S.AddWithAnd(B); A.AddWithAnd(new LexerRuleModel(new StringLiteralLexerRule("a"))); A.AddWithAnd(B); B.AddWithAnd(new LexerRuleModel(new StringLiteralLexerRule("b"))); var grammarModel = new GrammarModel(); grammarModel.Productions.Add(S); grammarModel.Productions.Add(A); grammarModel.Productions.Add(B); var grammar = grammarModel.ToGrammar(); Assert.AreEqual(3, grammar.Productions.Count); Assert.IsNotNull(grammar.Start); } [TestMethod] public void GrammarModelToGrammarShouldAddLexerRules() { var S = new ProductionModel("S"); var B = new LexerRuleModel(new WhitespaceLexerRule()); S.AddWithAnd(B); var grammarModel = new GrammarModel(); grammarModel.Productions.Add(S); grammarModel.LexerRules.Add(B); var grammar = grammarModel.ToGrammar(); Assert.AreEqual(1, grammar.Productions.Count); Assert.AreEqual(1, grammar.LexerRules.Count); } } }
36.469072
116
0.582756
[ "MIT" ]
patrickhuber/Earley
tests/Pliant.Tests.Unit/Builders/GrammarModelTests.cs
7,077
C#
// // ClassInterfaceDerivativeFinder.cs // // Author: // Alexander Bothe <info@alexanderbothe.com> // // Copyright (c) 2013 Alexander Bothe // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Collections.Generic; using D_Parser.Dom; using D_Parser.Resolver; using D_Parser.Resolver.ASTScanner; using D_Parser.Resolver.TypeResolution; namespace D_Parser.Refactoring { public class ClassInterfaceDerivativeFinder : AbstractVisitor { List<TemplateIntermediateType> results = new List<TemplateIntermediateType>(); List<INode> alreadyResolvedClasses = new List<INode>(); DClassLike typeNodeToFind; bool isInterface; ClassInterfaceDerivativeFinder (ResolutionContext ctxt) : base(ctxt) { } public static IEnumerable<TemplateIntermediateType> SearchForClassDerivatives(TemplateIntermediateType t, ResolutionContext ctxt) { if (!(t is ClassType || t is InterfaceType)) throw new ArgumentException ("t is expected to be a class or an interface, not " + (t != null ? t.ToString () : "null")); var f = new ClassInterfaceDerivativeFinder (ctxt); f.typeNodeToFind = t.Definition; var bt = t; while (bt != null) { f.alreadyResolvedClasses.Add (bt.Definition); bt = DResolver.StripMemberSymbols (bt.Base) as TemplateIntermediateType; } var filter = MemberFilter.Classes; if (t is InterfaceType) // -> Only interfaces can inherit interfaces. Interfaces cannot be subclasses of classes. { filter |= MemberFilter.Interfaces; f.isInterface = true; } f.IterateThroughScopeLayers (t.Definition.Location, filter); return f.results; // return them. } protected override bool PreCheckItem (INode n) { // Find all class+interface definitions var dc = n as DClassLike; return !(dc == null || dc.BaseClasses == null || dc.BaseClasses.Count == 0 || alreadyResolvedClasses.Contains (dc)); } protected override void HandleItem (INode n, AbstractType resolvedCurrentScope) { var dc = n as DClassLike; // resolve immediate base classes/interfaces; Rely on dc being either a class or an interface, nothing else. var t = ClassInterfaceResolver.ResolveClassOrInterface (dc,ctxt, null); alreadyResolvedClasses.Add (dc); // Look for classes/interfaces that match dc (check all dcs to have better performance on ambiguous lastresults), if (isInterface) { if(t.BaseInterfaces != null) foreach (var I in t.BaseInterfaces) { if (I.Definition == typeNodeToFind && !results.Contains(t)) results.Add(t); if (!alreadyResolvedClasses.Contains(I.Definition)) alreadyResolvedClasses.Add(I.Definition); } } else { var bt = DResolver.StripMemberSymbols(t.Base) as TemplateIntermediateType; while (bt != null) { var def = bt.Definition; if (def == typeNodeToFind) { if (!results.Contains(t)) results.Add(t); } if (!alreadyResolvedClasses.Contains(def)) alreadyResolvedClasses.Add(def); bt = DResolver.StripMemberSymbols(bt.Base) as TemplateIntermediateType; } } } protected override void HandleItem(PackageSymbol pack) { } } }
33.91129
131
0.722473
[ "Apache-2.0" ]
aBothe/D_Parser
DParser2/Refactoring/ClassInterfaceDerivativeFinder.cs
4,205
C#