Datasets:

blob_id
large_stringlengths
40
40
language
large_stringclasses
1 value
repo_name
large_stringlengths
5
119
path
large_stringlengths
4
271
score
float64
2.52
4.84
int_score
int64
3
5
text
stringlengths
26
4.09M
148816a733b59cb66943d72eb2cc135c64c486ae
C#
Liljan/Igloo-The-Final-Destruction
/Igloo - The Final Destruction/Assets/Scripts/Gameplay/PlayerHealth.cs
2.609375
3
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerHealth : Health { private bool isDead = false; public void Awake() { currentHP = MAX_HP; HUDManager.Instance().SetHealth(currentHP); } public override void HandleCollisions(Collision2D other) { string tag = other.transform.tag; if (tag.Equals("Enemy")) { TakeDamage(1); } } public void AddHealth(int health) { currentHP += health; currentHP = Mathf.Clamp(currentHP, 0, MAX_HP); HUDManager.Instance().SetHealth(currentHP); } public override void Kill() { Instantiate(DeathParticles, transform.position, Quaternion.identity); LevelManager.Instance().RespawnPlayer(); Destroy(this.gameObject); } public override void TakeDamage(int damage) { currentHP -= damage; if(currentHP >= 0) HUDManager.Instance().SetHealth(currentHP); else HUDManager.Instance().SetHealth(0); if (currentHP <= 0) Kill(); } }
5e973b8b152133d0132a1ee3684d3532fd5c12d6
C#
ivonaii/OnlineShop
/OnlineShop/Pants.cs
3.046875
3
using System; using System.Collections.Generic; using System.Text; namespace OnlineShop { class Pants : Clothes { public override void PrintInfo() { Console.WriteLine("P-riceless. A-wesome. N-ew. T-rendy. S-leek. = PANTS"); } public Pants(int index, string gender, string fabric, string color, string waist, double price) { Index = index; Gender = gender; Fabric = fabric; Color = color; Waist = waist; Price = price; } public Pants() {} } }
90c78759d1e9dba23eb72acf257eaedf610f04a2
C#
Alachisoft/NCache
/Src/NCSystemInternal/Diagnostics/PerformanceCounterCategory.cs
2.546875
3
using System; using System.Collections.Generic; using System.Runtime; using System.Text; namespace System.Diagnostics { // // Summary: // Represents a performance object, which defines a category of performance counters. public sealed class PerformanceCounterCategory { // // Summary: // Initializes a new instance of the System.Diagnostics.PerformanceCounterCategory // class, leaves the System.Diagnostics.PerformanceCounterCategory.CategoryName // property empty, and sets the System.Diagnostics.PerformanceCounterCategory.MachineName // property to the local computer. public PerformanceCounterCategory() { //TODO: ALACHISOFT } // // Summary: // Initializes a new instance of the System.Diagnostics.PerformanceCounterCategory // class, sets the System.Diagnostics.PerformanceCounterCategory.CategoryName property // to the specified value, and sets the System.Diagnostics.PerformanceCounterCategory.MachineName // property to the local computer. // // Parameters: // categoryName: // The name of the performance counter category, or performance object, with which // to associate this System.Diagnostics.PerformanceCounterCategory instance. // // Exceptions: // T:System.ArgumentException: // The categoryName is an empty string (""). // // T:System.ArgumentNullException: // The categoryName is null. [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] public PerformanceCounterCategory(string categoryName) { //TODO: ALACHISOFT } // // Summary: // Initializes a new instance of the System.Diagnostics.PerformanceCounterCategory // class and sets the System.Diagnostics.PerformanceCounterCategory.CategoryName // and System.Diagnostics.PerformanceCounterCategory.MachineName properties to the // specified values. // // Parameters: // categoryName: // The name of the performance counter category, or performance object, with which // to associate this System.Diagnostics.PerformanceCounterCategory instance. // // machineName: // The computer on which the performance counter category and its associated counters // exist. // // Exceptions: // T:System.ArgumentException: // The categoryName is an empty string ("").-or- The machineName syntax is invalid. // // T:System.ArgumentNullException: // The categoryName is null. public PerformanceCounterCategory(string categoryName, string machineName) { //TODO: ALACHISOFT } // // Summary: // Gets the category's help text. // // Returns: // A description of the performance object that this category measures. // // Exceptions: // T:System.InvalidOperationException: // The System.Diagnostics.PerformanceCounterCategory.CategoryName property is null. // The category name must be set before getting the category help. // // T:System.ComponentModel.Win32Exception: // A call to an underlying system API failed. public string CategoryHelp { get; } // // Summary: // Gets or sets the name of the performance object that defines this category. // // Returns: // The name of the performance counter category, or performance object, with which // to associate this System.Diagnostics.PerformanceCounterCategory instance. // // Exceptions: // T:System.ArgumentException: // The System.Diagnostics.PerformanceCounterCategory.CategoryName is an empty string // (""). // // T:System.ArgumentNullException: // The System.Diagnostics.PerformanceCounterCategory.CategoryName is null. public string CategoryName { get; set; } // // Summary: // Gets the performance counter category type. // // Returns: // One of the System.Diagnostics.PerformanceCounterCategoryType values. //public PerformanceCounterCategoryType CategoryType { get; } // // Summary: // Gets or sets the name of the computer on which this category exists. // // Returns: // The name of the computer on which the performance counter category and its associated // counters exist. // // Exceptions: // T:System.ArgumentException: // The System.Diagnostics.PerformanceCounterCategory.MachineName syntax is invalid. public string MachineName { get; set; } // // Summary: // Determines whether the specified counter is registered to the specified category // on the local computer. // // Parameters: // counterName: // The name of the performance counter to look for. // // categoryName: // The name of the performance counter category, or performance object, with which // the specified performance counter is associated. // // Returns: // true, if the counter is registered to the specified category on the local computer; // otherwise, false. // // Exceptions: // T:System.ArgumentNullException: // The categoryName is null.-or- The counterName is null. // // T:System.ArgumentException: // The categoryName is an empty string (""). // // T:System.InvalidOperationException: // The category name does not exist. // // T:System.ComponentModel.Win32Exception: // A call to an underlying system API failed. // // T:System.UnauthorizedAccessException: // Code that is executing without administrative privileges attempted to read a // performance counter. [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] public static bool CounterExists(string counterName, string categoryName) { //TODO: ALACHISOFT throw new NotImplementedException(); } // // Summary: // Determines whether the specified counter is registered to the specified category // on a remote computer. // // Parameters: // counterName: // The name of the performance counter to look for. // // categoryName: // The name of the performance counter category, or performance object, with which // the specified performance counter is associated. // // machineName: // The name of the computer on which the performance counter category and its associated // counters exist. // // Returns: // true, if the counter is registered to the specified category on the specified // computer; otherwise, false. // // Exceptions: // T:System.ArgumentNullException: // The categoryName is null.-or- The counterName is null. // // T:System.ArgumentException: // The categoryName is an empty string ("").-or- The machineName is invalid. // // T:System.InvalidOperationException: // The category name does not exist. // // T:System.ComponentModel.Win32Exception: // A call to an underlying system API failed. // // T:System.UnauthorizedAccessException: // Code that is executing without administrative privileges attempted to read a // performance counter. public static bool CounterExists(string counterName, string categoryName, string machineName) { //TODO: ALACHISOFT throw new NotImplementedException(); } // // Summary: // Registers the custom performance counter category containing a single counter // of type System.Diagnostics.PerformanceCounterType.NumberOfItems32 on the local // computer. // // Parameters: // categoryName: // The name of the custom performance counter category to create and register with // the system. // // categoryHelp: // A description of the custom category. // // categoryType: // One of the System.Diagnostics.PerformanceCounterCategoryType values specifying // whether the category is System.Diagnostics.PerformanceCounterCategoryType.MultiInstance, // System.Diagnostics.PerformanceCounterCategoryType.SingleInstance, or System.Diagnostics.PerformanceCounterCategoryType.Unknown. // // counterName: // The name of a new counter to create as part of the new category. // // counterHelp: // A description of the counter that is associated with the new custom category. // // Returns: // A System.Diagnostics.PerformanceCounterCategory that is associated with the new // system category, or performance object. // // Exceptions: // T:System.ArgumentException: // counterName is null or is an empty string ("").-or- The counter that is specified // by counterName already exists.-or- counterName has invalid syntax. It might contain // backslash characters ("\") or have length greater than 80 characters. // // T:System.InvalidOperationException: // The category already exists on the local computer. // // T:System.ArgumentNullException: // categoryName is null. -or-counterHelp is null. // // T:System.ComponentModel.Win32Exception: // A call to an underlying system API failed. // // T:System.UnauthorizedAccessException: // Code that is executing without administrative privileges attempted to read a // performance counter. //public static PerformanceCounterCategory Create(string categoryName, string categoryHelp, PerformanceCounterCategoryType categoryType, string counterName, string counterHelp); // // Summary: // Registers the custom performance counter category containing the specified counters // on the local computer. // // Parameters: // categoryName: // The name of the custom performance counter category to create and register with // the system. // // categoryHelp: // A description of the custom category. // // counterData: // A System.Diagnostics.CounterCreationDataCollection that specifies the counters // to create as part of the new category. // // Returns: // A System.Diagnostics.PerformanceCounterCategory that is associated with the new // custom category, or performance object. // // Exceptions: // T:System.ArgumentException: // A counter name that is specified within the counterData collection is null or // an empty string ("").-or- A counter that is specified within the counterData // collection already exists.-or- The counterName parameter has invalid syntax. // It might contain backslash characters ("\") or have length greater than 80 characters. // // T:System.ArgumentNullException: // The categoryName parameter is null. // // T:System.InvalidOperationException: // The category already exists on the local computer.-or- The layout of the counterData // collection is incorrect for base counters. A counter of type AverageCount64, // AverageTimer32, CounterMultiTimer, CounterMultiTimerInverse, CounterMultiTimer100Ns, // CounterMultiTimer100NsInverse, RawFraction, SampleFraction or SampleCounter has // to be immediately followed by one of the base counter types (AverageBase, MultiBase, // RawBase, or SampleBase). // // T:System.ComponentModel.Win32Exception: // A call to an underlying system API failed. // // T:System.UnauthorizedAccessException: // Code that is executing without administrative privileges attempted to read a // performance counter. //[Obsolete("This method has been deprecated. Please use System.Diagnostics.PerformanceCounterCategory.Create(string categoryName, string categoryHelp, PerformanceCounterCategoryType categoryType, CounterCreationDataCollection counterData) instead. http://go.microsoft.com/fwlink/?linkid=14202")] //[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] //public static PerformanceCounterCategory Create(string categoryName, string categoryHelp, CounterCreationDataCollection counterData); // // Summary: // Registers the custom performance counter category containing the specified counters // on the local computer. // // Parameters: // categoryName: // The name of the custom performance counter category to create and register with // the system. // // categoryHelp: // A description of the custom category. // // categoryType: // One of the System.Diagnostics.PerformanceCounterCategoryType values. // // counterData: // A System.Diagnostics.CounterCreationDataCollection that specifies the counters // to create as part of the new category. // // Returns: // A System.Diagnostics.PerformanceCounterCategory that is associated with the new // custom category, or performance object. // // Exceptions: // T:System.ArgumentException: // A counter name that is specified within the counterData collection is null or // an empty string ("").-or- A counter that is specified within the counterData // collection already exists.-or- counterName has invalid syntax. It might contain // backslash characters ("\") or have length greater than 80 characters. // // T:System.ArgumentNullException: // categoryName is null. -or-counterData is null. // // T:System.ArgumentOutOfRangeException: // categoryType value is outside of the range of the following values: MultiInstance, // SingleInstance, or Unknown. // // T:System.InvalidOperationException: // The category already exists on the local computer.-or- The layout of the counterData // collection is incorrect for base counters. A counter of type AverageCount64, // AverageTimer32, CounterMultiTimer, CounterMultiTimerInverse, CounterMultiTimer100Ns, // CounterMultiTimer100NsInverse, RawFraction, SampleFraction, or SampleCounter // must be immediately followed by one of the base counter types (AverageBase, MultiBase, // RawBase, or SampleBase). // // T:System.ComponentModel.Win32Exception: // A call to an underlying system API failed. // // T:System.UnauthorizedAccessException: // Code that is executing without administrative privileges attempted to read a // performance counter. //public static PerformanceCounterCategory Create(string categoryName, string categoryHelp, PerformanceCounterCategoryType categoryType, CounterCreationDataCollection counterData); // // Summary: // Registers a custom performance counter category containing a single counter of // type NumberOfItems32 on the local computer. // // Parameters: // categoryName: // The name of the custom performance counter category to create and register with // the system. // // categoryHelp: // A description of the custom category. // // counterName: // The name of a new counter, of type NumberOfItems32, to create as part of the // new category. // // counterHelp: // A description of the counter that is associated with the new custom category. // // Returns: // A System.Diagnostics.PerformanceCounterCategory that is associated with the new // system category, or performance object. // // Exceptions: // T:System.ArgumentException: // counterName is null or is an empty string ("").-or- The counter that is specified // by counterName already exists.-or- counterName has invalid syntax. It might contain // backslash characters ("\") or have length greater than 80 characters. // // T:System.InvalidOperationException: // The category already exists on the local computer. // // T:System.ArgumentNullException: // categoryName is null. -or-counterHelp is null. // // T:System.ComponentModel.Win32Exception: // A call to an underlying system API failed. // // T:System.UnauthorizedAccessException: // Code that is executing without administrative privileges attempted to read a // performance counter. [Obsolete("This method has been deprecated. Please use System.Diagnostics.PerformanceCounterCategory.Create(string categoryName, string categoryHelp, PerformanceCounterCategoryType categoryType, string counterName, string counterHelp) instead. http://go.microsoft.com/fwlink/?linkid=14202")] public static PerformanceCounterCategory Create(string categoryName, string categoryHelp, string counterName, string counterHelp) { //TODO: ALACHISOFT throw new NotImplementedException(); } // // Summary: // Removes the category and its associated counters from the local computer. // // Parameters: // categoryName: // The name of the custom performance counter category to delete. // // Exceptions: // T:System.ArgumentNullException: // The categoryName parameter is null. // // T:System.ArgumentException: // The categoryName parameter has invalid syntax. It might contain backslash characters // ("\") or have length greater than 80 characters. // // T:System.ComponentModel.Win32Exception: // A call to an underlying system API failed. // // T:System.InvalidOperationException: // The category cannot be deleted because it is not a custom category. // // T:System.UnauthorizedAccessException: // Code that is executing without administrative privileges attempted to read a // performance counter. public static void Delete(string categoryName) { //TODO: ALACHISOFT throw new NotImplementedException(); } // // Summary: // Determines whether the category is registered on the local computer. // // Parameters: // categoryName: // The name of the performance counter category to look for. // // Returns: // true if the category is registered; otherwise, false. // // Exceptions: // T:System.ArgumentNullException: // The categoryName parameter is null. // // T:System.ArgumentException: // The categoryName parameter is an empty string (""). // // T:System.ComponentModel.Win32Exception: // A call to an underlying system API failed. // // T:System.UnauthorizedAccessException: // Code that is executing without administrative privileges attempted to read a // performance counter. [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] public static bool Exists(string categoryName) { //TODO: ALACHISOFT throw new NotImplementedException(); } // // Summary: // Determines whether the category is registered on the specified computer. // // Parameters: // categoryName: // The name of the performance counter category to look for. // // machineName: // The name of the computer to examine for the category. // // Returns: // true if the category is registered; otherwise, false. // // Exceptions: // T:System.ArgumentNullException: // The categoryName parameter is null. // // T:System.ArgumentException: // The categoryName parameter is an empty string ("").-or- The machineName parameter // is invalid. // // T:System.ComponentModel.Win32Exception: // A call to an underlying system API failed. // // T:System.IO.IOException: // The network path cannot be found. // // T:System.UnauthorizedAccessException: // The caller does not have the required permission.-or-Code that is executing without // administrative privileges attempted to read a performance counter. public static bool Exists(string categoryName, string machineName) { //TODO: ALACHISOFT throw new NotImplementedException(); } // // Summary: // Retrieves a list of the performance counter categories that are registered on // the local computer. // // Returns: // An array of System.Diagnostics.PerformanceCounterCategory objects indicating // the categories that are registered on the local computer. // // Exceptions: // T:System.ComponentModel.Win32Exception: // A call to an underlying system API failed. // // T:System.UnauthorizedAccessException: // Code that is executing without administrative privileges attempted to read a // performance counter. [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] public static PerformanceCounterCategory[] GetCategories() { //TODO: ALACHISOFT throw new NotImplementedException(); } // // Summary: // Retrieves a list of the performance counter categories that are registered on // the specified computer. // // Parameters: // machineName: // The computer to look on. // // Returns: // An array of System.Diagnostics.PerformanceCounterCategory objects indicating // the categories that are registered on the specified computer. // // Exceptions: // T:System.ArgumentException: // The machineName parameter is invalid. // // T:System.ComponentModel.Win32Exception: // A call to an underlying system API failed. // // T:System.UnauthorizedAccessException: // Code that is executing without administrative privileges attempted to read a // performance counter. public static PerformanceCounterCategory[] GetCategories(string machineName) { //TODO: ALACHISOFT throw new NotImplementedException(); } // // Summary: // Determines whether the specified counter is registered to this category, which // is indicated by the System.Diagnostics.PerformanceCounterCategory.CategoryName // and System.Diagnostics.PerformanceCounterCategory.MachineName properties. // // Parameters: // counterName: // The name of the performance counter to look for. // // Returns: // true if the counter is registered to the category that is specified by the System.Diagnostics.PerformanceCounterCategory.CategoryName // and System.Diagnostics.PerformanceCounterCategory.MachineName properties; otherwise, // false. // // Exceptions: // T:System.ArgumentNullException: // The counterName is null. // // T:System.InvalidOperationException: // The System.Diagnostics.PerformanceCounterCategory.CategoryName property has not // been set. // // T:System.ComponentModel.Win32Exception: // A call to an underlying system API failed. // // T:System.UnauthorizedAccessException: // Code that is executing without administrative privileges attempted to read a // performance counter. public bool CounterExists(string counterName) { //TODO: ALACHISOFT throw new NotImplementedException(); } // // Summary: // Retrieves a list of the counters in a performance counter category that contains // exactly one instance. // // Returns: // An array of System.Diagnostics.PerformanceCounter objects indicating the counters // that are associated with this single-instance performance counter category. // // Exceptions: // T:System.ArgumentException: // The category is not a single instance. // // T:System.ComponentModel.Win32Exception: // A call to an underlying system API failed. // // T:System.InvalidOperationException: // The category does not have an associated instance. // // T:System.UnauthorizedAccessException: // Code that is executing without administrative privileges attempted to read a // performance counter. public PerformanceCounter[] GetCounters() { //TODO: ALACHISOFT throw new NotImplementedException(); } // // Summary: // Retrieves a list of the counters in a performance counter category that contains // one or more instances. // // Parameters: // instanceName: // The performance object instance for which to retrieve the list of associated // counters. // // Returns: // An array of System.Diagnostics.PerformanceCounter objects indicating the counters // that are associated with the specified object instance of this performance counter // category. // // Exceptions: // T:System.ArgumentNullException: // The instanceName parameter is null. // // T:System.InvalidOperationException: // The System.Diagnostics.PerformanceCounterCategory.CategoryName property for this // System.Diagnostics.PerformanceCounterCategory instance has not been set.-or- // The category does not contain the instance that is specified by the instanceName // parameter. // // T:System.ComponentModel.Win32Exception: // A call to an underlying system API failed. // // T:System.UnauthorizedAccessException: // Code that is executing without administrative privileges attempted to read a // performance counter. public PerformanceCounter[] GetCounters(string instanceName) { //TODO: ALACHISOFT throw new NotImplementedException(); } // // Summary: // Retrieves the list of performance object instances that are associated with this // category. // // Returns: // An array of strings representing the performance object instance names that are // associated with this category or, if the category contains only one performance // object instance, a single-entry array that contains an empty string (""). // // Exceptions: // T:System.InvalidOperationException: // The System.Diagnostics.PerformanceCounterCategory.CategoryName property is null. // The property might not have been set. -or-The category does not have an associated // instance. // // T:System.ComponentModel.Win32Exception: // A call to an underlying system API failed. // // T:System.UnauthorizedAccessException: // Code that is executing without administrative privileges attempted to read a // performance counter. public string[] GetInstanceNames() { //TODO: ALACHISOFT throw new NotImplementedException(); } // // Summary: // Determines whether a specified category on the local computer contains the specified // performance object instance. // // Parameters: // instanceName: // The performance object instance to search for. // // categoryName: // The performance counter category to search. // // Returns: // true if the category contains the specified performance object instance; otherwise, // false. // // Exceptions: // T:System.ArgumentNullException: // The instanceName parameter is null.-or- The categoryName parameter is null. // // T:System.ArgumentException: // The categoryName parameter is an empty string (""). // // T:System.ComponentModel.Win32Exception: // A call to an underlying system API failed. // // T:System.UnauthorizedAccessException: // Code that is executing without administrative privileges attempted to read a // performance counter. [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] public static bool InstanceExists(string instanceName, string categoryName) { //TODO: ALACHISOFT throw new NotImplementedException(); } } }
bf412360396eb1a39b38f6c57456573ef800ad0e
C#
shendongnian/download4
/code8/1487415-40888975-132762153-2.cs
3.140625
3
public static string LocalUserAppDataPath { get { return GetDataPath(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)); } } private static string GetDataPath(string basePath) { string format = @"{0}\{1}\{2}\{3}"; string companyName = "YOUR_COMPANYNAME"; string productName = "PRODUCTNAME"; string productVersion = "PRODUCTVERSION"; object[] args = new object[] { basePath, companyName, productName, productVersion }; string path = string.Format(CultureInfo.CurrentCulture, format, args); return path; }
060fcd9cd3cb973127a39105e5ce6c02b5ab0fa3
C#
benhofca/BootstrapModalContentControl
/Data/CustomAttribute.cs
2.734375
3
using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Resources; using System.Web; namespace Data { public class LocalizedDisplayNameAttribute : DisplayNameAttribute { public LocalizedDisplayNameAttribute(string tableName, string propertyName) : base(string.Format("{0}:{1}", tableName, propertyName)) { } public override string DisplayName { get { string displayName = null; if (DisplayNameValue.Contains(":")) { string[] tokens = DisplayNameValue.Split(':'); displayName = LocalizedAttributeHelper.GetMessageFromResource(tokens[0], tokens[1], "LABEL"); } return displayName; } } } public class LocalizedValidationAttribute : ValidationAttribute { public LocalizedValidationAttribute(string tableName, string propertyName) : base(string.Format("{0}:{1}", tableName, propertyName)) { } protected override ValidationResult IsValid(object value, ValidationContext validationContext) { if(value == null) { string errorMessage = null; if (ErrorMessageString.Contains(":")) { string[] tokens = ErrorMessageString.Split(':'); errorMessage = LocalizedAttributeHelper.GetMessageFromResource(tokens[0], tokens[1], "VALIDATION"); } return new ValidationResult(errorMessage); } return ValidationResult.Success; } } public class LocalizedAttributeHelper { public static string GetMessageFromResource(string tableName, string propertyName, string suffix = null) { Type resourceType = Type.GetType(string.Format("Resources.Models.{0}, Resources", tableName)); ResourceManager rm = new ResourceManager(resourceType); if(string.IsNullOrEmpty(suffix)) return rm.GetString(string.Format("{0}", propertyName)); else return rm.GetString(string.Format("{0}_{1}", suffix, propertyName)); } } }
0d6f79fdcbf727cc892c6c1bf5fbfe0d130129bf
C#
caixiong110/Cloud-port-forward
/ManagementAgent/Services/Memory.cs
2.84375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO.MemoryMappedFiles; using System.IO; using System.ComponentModel; using System.Threading; namespace ManagementAgent.Services { class Memory { public static int Connected { get; set; } public static int CLients { get; set; } public static UInt32 DataSent { get; set; } public static UInt32 DataRec { get; set; } public static void init() { MemoryMappedFile MemoryMapped = MemoryMappedFile.CreateFromFile( @"Mem.mp", // Any stream will do it FileMode.Create, "CloudAgent", // Name 1024, // Size in bytes MemoryMappedFileAccess.ReadWrite); // Access type MemoryMappedViewAccessor FileMapView = MemoryMapped.CreateViewAccessor(); int Number = 1234; FileMapView.Write(0, Number); //FileMapView.Write<Container>(4, ref MyContainer); } public static string OpenMem() { try { // Assumes another process has created the memory-mapped file. using (var mmf = MemoryMappedFile.OpenExisting("CloudAgent")) { using (var accessor = mmf.CreateViewAccessor(0, 1024, MemoryMappedFileAccess.Read)) { //StringBuilder outl = new StringBuilder("Connected ").Append(accessor.ReadByte(0).ToString()).Append(" : ") // .Append("Clients = ").Append(accessor.ReadByte(1).ToString()); Connected = accessor.ReadByte(0); CLients = accessor.ReadByte(1); DataSent = accessor.ReadUInt32(2); DataRec = accessor.ReadUInt32(6); return ""; //for (int i = 1; i < 1022; i++) //{ // outl.Append(accessor.ReadChar(i)); // i++; //} //return outl.ToString(); //int colorSize = Marshal.SizeOf(typeof(MyColor)); //MyColor color; // Make changes to the view. //for (long i = 0; i < 1500000; i += colorSize) //{ //accessor.Read(i, out color); //color.Brighten(20); //accessor.Write(i, ref color); //} } } } catch (Exception ex) { return ("Memory-mapped file does not exist. Run Process A first."); } return ""; } } }
3b735e0b4c5742350e21d116d32a9f4b31de4832
C#
dtrain157/DeepCat
/DeepCat/DeepCat/DeepCat.cs
2.703125
3
using DeepCat.Layers; using DeepCat.Loss; using DeepCat.Optimization; using MathNet.Numerics.LinearAlgebra; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DeepCat { public class DeepCat { public List<ILayer> _layers = new List<ILayer>(); public IOptimizer _optimizer; public ILoss _lossFunction; public void Add(ILayer layer) { _layers.Add(layer); } public void Compile(int inputSize, ILoss lossFunction, IOptimizer optimizer) { _optimizer = optimizer; _lossFunction = lossFunction; for (var i = 0; i < _layers.Count; i++) { int previousLayerSize; if (i == 0) { previousLayerSize = inputSize; } else { previousLayerSize = _layers[i - 1].LayerSize; } _layers[i].Compile(previousLayerSize); _layers[i].Optimizer = optimizer; } } public void Fit(Matrix<double> X, Matrix<double> Y, int epochs, int? batchSize = null) { var m = batchSize ?? X.ColumnCount; foreach (var layer in _layers) { layer.BatchSize = m; } for (int i = 0; i < epochs; i++) { Console.WriteLine(string.Format("Epoch: {0}", i + 1)); for (var batch = 0; batch < X.ColumnCount / m; batch++) { var xBatch = X.SubMatrix(0, X.RowCount, batch * m, m); var yBatch = Y.SubMatrix(0, Y.RowCount, batch * m, m); var yhat = ForwardPropegation(xBatch); var batchCost = _lossFunction.CalculateCost(yBatch, yhat); var dYhat = _lossFunction.CalculateCostDerivative(yBatch, yhat); BackwardPropegation(xBatch, dYhat); Update(); Console.WriteLine(string.Format("Batch: {0}; Cost: {1}", batch + 1, batchCost)); } //handle the last batch, which might not be complete if (X.ColumnCount % m != 0) { var xBatch = PadMatrix(X.SubMatrix(0, X.RowCount, (X.ColumnCount / m) * m, X.ColumnCount - (X.ColumnCount / m) * m), m); var yBatch = PadMatrix(Y.SubMatrix(0, Y.RowCount, (X.ColumnCount / m) * m, Y.ColumnCount - (Y.ColumnCount / m) * m), m); var yhat = ForwardPropegation(xBatch); var batchCost = _lossFunction.CalculateCost(yBatch, yhat); var dYhat = _lossFunction.CalculateCostDerivative(yBatch, yhat); BackwardPropegation(xBatch, dYhat); Update(); } } } internal void Compile(object p1, object p2) { throw new NotImplementedException(); } public Matrix<double> Predict(Matrix<double> X) { return ForwardPropegation(X); } private Matrix<double> ForwardPropegation(Matrix<double> X) { var A_prev = X; foreach (var layer in _layers) { A_prev = layer.Forward(A_prev); } return A_prev; } private void BackwardPropegation(Matrix<double> X, Matrix<double> dYhat) { var dA_next = dYhat; for (int i = _layers.Count - 1; i >= 0; i--) { Matrix<double> A_prev; if (i != 0) { A_prev = _layers[i - 1].GetActivation(); } else { A_prev = X; } dA_next = _layers[i].Backward(A_prev, dA_next); } } private void Update() { foreach (var layer in _layers) { layer.Update(); } } private Matrix<double> PadMatrix(Matrix<double> X, int m) { var padSize = X.ColumnCount - m; var zeroPadMatrix = Matrix<double>.Build.Dense(X.RowCount, padSize); return Matrix<double>.Build.DenseOfMatrixArray(new[,] { { X, zeroPadMatrix } }); } } }
29abfbe19ba7ff3623e019a4bbddf24b01ae7de6
C#
wim07101993/ClassLibrary
/Library.Serialization/Csv/HeaderElement.cs
2.8125
3
using System; using System.Collections.Generic; using System.Reflection; using System.Text; using Library.Core; using Library.Serialization.Extensions; namespace Library.Serialization.Csv { public class HeaderElement { public HeaderElement(PropertyInfo property, string parentName, char delimiter) { PropertyInfo = property; Delimiter = delimiter; Name = string.IsNullOrWhiteSpace(parentName) ? property.Name : $"{parentName}.{property.Name}"; Children = Type.GetCsvHeaderElements(Name, delimiter); } public PropertyInfo PropertyInfo { get; } public Type Type => PropertyInfo.PropertyType; public string Name { get; } public char Delimiter { get; } public IReadOnlyList<HeaderElement> Children { get; } public override string ToString() => Enumerable.IsNullOrEmpty(Children) ? Name : Children.ToString(Delimiter.ToString()); public string CreateRowElement(object obj) { if (Enumerable.IsNullOrEmpty(Children)) return PropertyInfo.GetValue(obj).ToString(); using (var childrenEnumerator = Children.GetEnumerator()) { var rowBuilder = new StringBuilder(); childrenEnumerator.MoveNext(); var rowElement = childrenEnumerator.Current.CreateRowElement(obj); rowBuilder.Append($"{rowElement}{Delimiter}"); while (childrenEnumerator.MoveNext()) { rowElement = childrenEnumerator.Current.CreateRowElement(obj); rowBuilder.Append(rowElement); } return rowBuilder.ToString(); } } } }
0a4830788358fa0d3e9a083fd75423c3c2b16bf5
C#
Ozone-Training-Service/OzoneTrainingBatch3
/Teaching/ConsoleApps/Day2/Program.cs
3.828125
4
using System; namespace Day2 { class Sample { public void Hello() { Console.WriteLine("Hello"); } public int GetMeARandomNum() { Random rn = new Random(); int num = rn.Next(100); return num; } public void Sum(int x, int y) { Console.WriteLine("{0}+{1}={2}",x,y,(x+y)); } public int Sub(int x, int y) { return (x - y); } } class Program { static void Main(string[] args) { Sample o = new Sample(); o.Hello(); int x=o.GetMeARandomNum(); Console.WriteLine("Random num="+x); o.Sum(10,10); int ans = o.Sub(10,5); Console.WriteLine("Sub="+ans); Console.ReadKey(); } } }
4120418b498fdec073524795a89726cb97aa9e44
C#
JorgeCota/GetBodyProduction
/Common/ResourcesGetInformationPC.cs
2.96875
3
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.NetworkInformation; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Common { public static class ResourcesGetInformationPC { public static string GetMacAdrs() { var macAddr = ( from nic in NetworkInterface.GetAllNetworkInterfaces() where nic.OperationalStatus == OperationalStatus.Up select nic.GetPhysicalAddress().ToString() ).FirstOrDefault(); return macAddr; } public static int[] GetSizeScreen() { int[] size = new int[2]; size[0] = Screen.PrimaryScreen.Bounds.Width; //Obtiene el alto de la pantalla principal en pixeles. size[1] = Screen.PrimaryScreen.Bounds.Height; //Obtiene el ancho de la pantalla principal en pixeles. return size; } public static List<string> GetInfoPC() { List<string> lstValues = new List<string>(); lstValues.Add(Environment.MachineName); lstValues.Add(Environment.UserName); lstValues.Add(Environment.UserDomainName); IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName()); foreach (IPAddress ip in host.AddressList) { if (ip.AddressFamily.ToString() == "InterNetwork") { lstValues.Add(ip.ToString()); } } lstValues.Add(GetMacAdrs()); return lstValues; } } }
1bd2bf514c8946c36764a1a3807f55eb62bb6431
C#
Ne-Ice/SUGAR-Unity
/PlayGen.SUGAR.Unity/PlayGen.SUGAR.Unity/CommandLineUtility.cs
2.8125
3
using System.Collections.Generic; using CommandLine; namespace PlayGen.SUGAR.Unity { public static class CommandLineUtility { public static Dictionary<string, string> CustomArgs; public static CommandLineOptions ParseArgs(string[] args) { var parser = new Parser(); var options = new CommandLineOptions(); if (args != null) { parser.ParseArguments(args, options); } var customArgs = options.Custom?.Split(';') ?? new string[0]; CustomArgs = new Dictionary<string, string>(); foreach (var arg in customArgs) { var keyValue = arg.Split('='); if (keyValue.Length == 2) { CustomArgs.Add(keyValue[0], keyValue[1]); } } return options; } } public class CommandLineOptions { [Option('a', "autologin", DefaultValue = false, Required = true, HelpText = "Sets flag to log in the user automatically.")] public bool AutoLogin { get; set; } [Option('s', "source", Required = true, HelpText = "Specify an authentication source.")] public string AuthenticationSource { get; set; } [Option('g', "class", Required = false, HelpText = "Specify the id of the class.")] public string ClassId { get; set; } [Option('u', "uid", Required = true, HelpText = "Specify the id of the user.")] public string UserId { get; set; } [Option('p', "pass", Required = false, HelpText = "Specify the password for the user.")] public string Password { get; set; } [Option('c', "custom", Required = false, HelpText = "Customs args list, dictionary pattern, separated by semi-colon. Eg: -c key=value;key=value etc.")] public string Custom { get; set; } } }
18d57277cc88bfc795a6db64e11e9207373c7cb7
C#
ivayloivanof/OOP.CSharp
/07.DelegatesAndEvents/DelegatesAndEvents.Homework/DelegatesAndEvents/CustomLinqExtensionMethods/Students.cs
2.984375
3
namespace CustomLinqExtensionMethods { class Students { private string name; private int grade; public Students(string name, int grade) { this.Name = name; this.Grade = grade; } public string Name { get; set; } public int Grade { get; set; } } }
5b5c183b3b7df01ba101b1b245595ba6cd0f4435
C#
vam-community/vam-party
/Party.Shared.Tests/PartyAssertions.cs
2.78125
3
using Newtonsoft.Json; using NUnit.Framework; namespace Party.Shared { internal static class PartyAssertions { internal static void AreDeepEqual(object expected, object actual) { var expectedJson = JsonConvert.SerializeObject(expected); var actualJson = JsonConvert.SerializeObject(actual); Assert.AreEqual(expectedJson, actualJson, $"Actual\n{JsonConvert.SerializeObject(actual, Formatting.Indented)}\nExpected:\n{JsonConvert.SerializeObject(expected, Formatting.Indented)}"); } } }
13c703d6618ceec2f45398009e05e5df1dd88a68
C#
ponlawat-w/OsmRoadLegSplitter
/OsmRoadLegSplitter/Models/RoadLeg.cs
2.5625
3
using NetTopologySuite.Geometries; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace OsmRoadLegSplitter.Models { public class RoadLeg { public IEnumerable<RoadNode> RoadNodes; public RoadLeg(IEnumerable<RoadNode> nodes) { RoadNodes = nodes.Select(n => n).ToList(); } public LineString ToLineString() { return new LineString(RoadNodes.Select(n => n.Coordinate).ToArray()); } } }
b6ea52734567fa247e1482fd830231b6d9d66724
C#
hanyeah/SimpleCircuit
/SimpleCircuit/Algebra/Matrix/SparseMatrix/Row.cs
3.5625
4
using System; namespace SimpleCircuit.Algebra { public partial class SparseMatrix<T> { /// <summary> /// A class that keeps track of a linked list of matrix elements for a row. /// </summary> protected class Row { /// <summary> /// Gets the first element in the row. /// </summary> /// <value> /// The first element in the row. /// </value> public Element FirstInRow { get; private set; } /// <summary> /// Gets the last element in the row. /// </summary> /// <value> /// The last element in the row. /// </value> public Element LastInRow { get; private set; } /// <summary> /// Gets an element in the row, or creates it if it doesn't exist yet. /// </summary> /// <param name="location">The location of the element.</param> /// <param name="result">The found or created element.</param> /// <returns><c>true</c> if the element was found, <c>false</c> if it was created.</returns> public bool CreateOrGetElement(MatrixLocation location, out Element result) { Element element = FirstInRow, lastElement = null; while (element != null) { if (element.Column > location.Column) break; if (element.Column == location.Column) { // Found the element result = element; return true; } lastElement = element; element = element.Right; } // Create a new element result = new Element(location); // Update links for last element if (lastElement == null) FirstInRow = result; else lastElement.Right = result; result.Left = lastElement; // Update links for next element if (element == null) LastInRow = result; else element.Left = result; result.Right = element; // Could not find existing element return false; } /// <summary> /// Find an element in the row without creating it. /// </summary> /// <param name="column">The column index.</param> /// <returns>The element at the specified column, or <c>null</c> if the element doesn't exist.</returns> public Element Find(int column) { var element = FirstInRow; while (element != null) { if (element.Column == column) return element; if (element.Column > column) return null; element = element.Right; } return null; } /// <summary> /// Remove an element from the row. /// </summary> /// <param name="element">The element to be removed.</param> public void Remove(Element element) { if (element.Left == null) FirstInRow = element.Right; else element.Left.Right = element.Right; if (element.Right == null) LastInRow = element.Left; else element.Right.Left = element.Left; } /// <summary> /// Clears all matrix elements in the row. /// </summary> public void Clear() { FirstInRow = null; LastInRow = null; } /// <summary> /// Swap two elements in the row, <paramref name="first"/> and <paramref name="columnFirst"/> /// are supposed to come first in the row. /// </summary> /// <param name="first">The first matrix element.</param> /// <param name="second">The second matrix element.</param> /// <param name="columnFirst">The first column.</param> /// <param name="columnSecond">The second column.</param> public void Swap(Element first, Element second, int columnFirst, int columnSecond) { if (first == null && second == null) throw new ArgumentNullException(nameof(first) + ", " + nameof(second)); if (first == null) { // Do we need to move the element? if (second.Left == null || second.Left.Column < columnFirst) { second.Column = columnFirst; return; } // Move the element back var element = second.Left; Remove(second); while (element.Left != null && element.Left.Column > columnFirst) element = element.Left; // We now have the first element below the insertion point if (element.Left == null) FirstInRow = second; else element.Left.Right = second; second.Left = element.Left; element.Left = second; second.Right = element; second.Column = columnFirst; } else if (second == null) { // Do we need to move the element? if (first.Right == null || first.Right.Column > columnSecond) { first.Column = columnSecond; return; } // Move the element forward var element = first.Right; Remove(first); while (element.Right != null && element.Right.Column < columnSecond) element = element.Right; // We now have the first element above the insertion point if (element.Right == null) LastInRow = first; else element.Right.Left = first; first.Right = element.Right; element.Right = first; first.Left = element; first.Column = columnSecond; } else { // Are they adjacent or not? if (first.Right == second) { // Correct surrounding links if (first.Left == null) FirstInRow = second; else first.Left.Right = second; if (second.Right == null) LastInRow = first; else second.Right.Left = first; // Correct element links first.Right = second.Right; second.Left = first.Left; first.Left = second; second.Right = first; first.Column = columnSecond; second.Column = columnFirst; } else { // Swap surrounding links if (first.Left == null) FirstInRow = second; else first.Left.Right = second; first.Right.Left = second; if (second.Right == null) LastInRow = first; else second.Right.Left = first; second.Left.Right = first; // Swap element links var element = first.Left; first.Left = second.Left; second.Left = element; element = first.Right; first.Right = second.Right; second.Right = element; first.Column = columnSecond; second.Column = columnFirst; } } } } } }
b86a7e4395a8cc3e704df52d00308767eb1214f5
C#
msc-judicial-information-services/Brickweave
/samples/Brickweave.Samples.Domain/Persons/Models/Person.cs
2.921875
3
using System.Collections.Generic; using Brickweave.EventStore; using Brickweave.Samples.Domain.Persons.Events; namespace Brickweave.Samples.Domain.Persons.Models { public class Person : EventSourcedAggregateRoot { Person() { Register<PersonCreated>(Apply); Register<NameChanged>(Apply); } public Person(PersonId id, Name name) : this() { RaiseEvent(new PersonCreated(id.Value, name.FirstName, name.LastName)); } public Person(IEnumerable<IAggregateEvent> events) : this() { ApplyEvents(events); } public PersonId Id { get; private set; } public Name Name { get; private set; } public void ChangeName(Name name) { RaiseEvent(new NameChanged(name.FirstName, name.LastName)); } public PersonInfo ToInfo() { return new PersonInfo(Id, Name); } private void Apply(PersonCreated @event) { Id = new PersonId(@event.Id); Name = new Name(@event.FirstName, @event.LastName); } private void Apply(NameChanged @event) { Name = new Name(@event.FirstName, @event.LastName); } } }
7a6612bcd88bb1aeb0cc396deec9ed912a39fa9b
C#
lilasquared/redux.NET
/src/Redux.DevTools/TimeMachineStore.cs
2.6875
3
using System; using System.Linq; using System.Reactive.Linq; namespace Redux.DevTools { public class TimeMachineStore<TState> : Store<TimeMachineState>, IStore<TState> { public TimeMachineStore(Reducer<TState> reducer, TState initialState = default(TState)) : base(new TimeMachineReducer((state, action) => reducer((TState)state, action)).Execute, new TimeMachineState(initialState)) { } public IDisposable Subscribe(IObserver<TState> observer) { return ((IObservable<TimeMachineState>)this) .Select(state => (TState)state.States[state.Position]) .DistinctUntilChanged() .Subscribe(observer); } TState IStore<TState>.GetState() { return ((IStore<TState>)this).GetState(); } } }
49b05e2360ac3aee3d2f6213e91d861ef37df98d
C#
huynht12/WaggerApp
/LogIn.cs
2.859375
3
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; using System.IO; using System.Windows; namespace WaggerApp { public partial class LogIn : Form { string[] users; public LogIn() { InitializeComponent(); } private void LogIn_Load(object sender, EventArgs e) { //load a file of all existing users //write users & password in container string try { //using (var sr = new StreamReader("Users.txt")) users = File.ReadAllLines(@".\Users.txt"); //Console.WriteLine(users); //sr.Close(); } catch (FileNotFoundException ex) { Console.WriteLine("Error: " + ex.Message); } } //Login //checks for match in username & password private void button1_Click(object sender, EventArgs e) { bool error = true; label4.Text = string.Empty; string username = textBox1.Text; string password = textBox2.Text; for (int i = 0; i < users.Length; i += 4) { if (username.Equals(users[i], StringComparison.OrdinalIgnoreCase) && password.Equals(users[i+1], StringComparison.Ordinal)) { error = false; String[] login = File.ReadAllLines(@".\" + username + " Profile.txt"); if(login[6]== "1") { Preferences pref = new Preferences(login[1], 1); //this.Hide(); pref.ShowDialog(); // this.Show(); } MainPage mainPage = new MainPage(login[1]); this.Hide(); mainPage.ShowDialog(); } } if (error) { label4.Text = "Username or Password is invalid, Please try again."; } } //Register private void button2_Click(object sender, EventArgs e) { Registration reg = new Registration(); reg.ShowDialog(); } //Exit private void button3_Click(object sender, EventArgs e) { Application.Exit(); } } }
7998d800ac7aa32a4e5f467cca0179d44e1b5fa1
C#
Juicern/HealthCheckIn
/CheckInHelper/辅助类/ManagerLoginHelper.cs
2.859375
3
using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; namespace CheckInHelper { public class ManagerLoginHelper { /// <summary> /// 从配置文件中读出管理员登录信息 /// </summary> /// <returns>管理员登录信息</returns> public static Manager GetLoginInfoFormConfig() { return new Manager { account = ConfigHelper.GetAppConfig(ParameterHelper.managerAccount), password = ConfigHelper.GetAppConfig(ParameterHelper.managerPassword) }; } /// <summary> /// 更新管理员登录信息的配置文件 /// </summary> /// <param name="manager">管理员登录信息</param> public static void UpdateLoginInfoToConfig(Manager manager) { ConfigHelper.UpdateAppConfig(ParameterHelper.managerAccount, manager.account); ConfigHelper.UpdateAppConfig(ParameterHelper.managerPassword, manager.password); } /// <summary> /// 判断账户是否在系统中你给 /// </summary> /// <param name="strAccount">账户</param> /// <returns></returns> public static bool CheckAccount(string strAccount) => DataBaseHelper.GetInstance().CheckAccount(ParameterHelper.managerInfo, strAccount); /// <summary> /// 判断密码是否正确 /// </summary> /// <param name="strAccount">账号</param> /// <param name="strPassword">密码</param> /// <returns></returns> public static bool CheckLogin(string strAccount, string strPassword) => DataBaseHelper.GetInstance().CheckLogin(ParameterHelper.managerInfo, strAccount, ToMD5(strPassword)); /// <summary> /// 注册管理员账户 /// </summary> /// <param name="strAccount">账号</param> /// <param name="strPassword">密码</param> /// <returns>(是否成功注册,错误信息)</returns> public static (bool, string) Register(string strAccount, string strPassword) => DataBaseHelper.GetInstance().Register(ParameterHelper.managerInfo, strAccount, ToMD5(strPassword)); /// <summary> /// MD5加密算法 /// </summary> /// <param name="strs">传入数据</param> /// <returns>加密后的数据</returns> private static string ToMD5(string strs) { MD5 md5 = new MD5CryptoServiceProvider(); byte[] bytes = Encoding.Default.GetBytes(strs); byte[] encryptdata = md5.ComputeHash(bytes); return Convert.ToBase64String(encryptdata); } } }
d72fda062cbb38024e95319faea172150c20727c
C#
Kezzo/GGJ18
/Assets/Scripts/Tuple.cs
2.5625
3
public struct Tuple<A, B> { public readonly A a; public readonly B b; public Tuple(A a, B b) { this.a = a; this.b = b; } }
a8e1d90e11811886bee08bf7ada36545e8b82980
C#
madRebellion/ThisLifeOfMine
/This Life of Mine/Assets/Scripts/Game State/SaveLoad.cs
2.734375
3
using UnityEngine; using System.IO; using System.Runtime.Serialization.Formatters.Binary; public static class SaveLoad { public static void SaveGame(PlayerController playerInfo, CameraController cameraInfo) { BinaryFormatter binaryFormatter = new BinaryFormatter(); string savePath = Application.persistentDataPath + "/Saves/game.sav"; FileStream fileStream = new FileStream(savePath, FileMode.Create); GameSaveFile gsFile = new GameSaveFile(playerInfo, cameraInfo); binaryFormatter.Serialize(fileStream, gsFile); fileStream.Close(); } public static GameSaveFile LoadGame() { string loadPath = Application.persistentDataPath + "/Saves/game.sav"; if (File.Exists(loadPath)) { BinaryFormatter binaryFormatter = new BinaryFormatter(); FileStream fileStream = new FileStream(loadPath, FileMode.Open); GameSaveFile gsFile = (GameSaveFile)binaryFormatter.Deserialize(fileStream); return gsFile; } else { return null; } } }
73185a0496d181756359d1c1b92b55e8f4a0ddc8
C#
malikamalik1/Horus
/Horus.Generator/Generator.cs
2.546875
3
using System; using System.Collections.Generic; using System.Configuration; using System.Data.SqlClient; using System.Diagnostics; using System.IO; using System.Runtime.CompilerServices; using Horus.Generator.Builders; using Horus.Generator.Models; using Horus.Generator.ReferenceData; using MigraDoc.DocumentObjectModel; using MigraDoc.Rendering; using Newtonsoft.Json; namespace Horus.Generator { static class Generator { static Random random = new Random(); public static readonly string saveExpectedResultsToScoreDatabase = ConfigurationManager.AppSettings["SaveExpectedResultsToScoreDatabase"]; public static GeneratorSpecification Generate(Supplier supplier, int numDocuments = 1, int baseDocumentNumber = 20000) { bool save = false; if (saveExpectedResultsToScoreDatabase.ToLower() == "true") { save = true; Console.WriteLine($"Expected results will be saved to scores database"); } else { Console.WriteLine($"Warning!! Expected results are not being saved."); } var gs = new GeneratorSpecification(); gs.Header = new GeneratorHeader { LogoFile = supplier.LogoFile, SupplierFullName = supplier.SupplierFullName, DocumentType = "INVOICE", SupplierKey = supplier.SupplierKey, SupplierName = supplier.SupplierName, BuilderAssembly = supplier.BuilderAssembly, BuilderType = supplier.BuilderType }; gs.Documents = new List<GeneratorDocument>(); for (int d = 0; d < numDocuments; d++) { GeneratorDocument gd = new GeneratorDocument(); gd.DocumentFormat = supplier.SupplierKey; gd.DocumentNumber = (baseDocumentNumber + 1 + d).ToString(); gd.FileName = $"{gs.Header.DocumentType}-{gd.DocumentNumber}.pdf"; gd.DocumentDate = DateTime.Now.Subtract(new TimeSpan(random.Next(1, 180), 0, 0, 0)); if (random.Next(1,10) <= 3) gd.Notes = "Need to do something with this"; var account = Accounts.GetRandomAccount(); gd.PostalCode = account.PostalCode; gd.SingleName = account.SingleName; gd.Account = account.AccountNumber; gd.AddressLine1 = account.AddressLine1; gd.AddressLine2 = account.AddressLine2; gd.City = account.City; gd.Lines = new List<GeneratorDocumentLineItem>(); var numLines = random.Next(1, supplier.MaxLines); for (int l = 0; l < numLines; l++) { var gdli = new GeneratorDocumentLineItem(); var product = Products.GetRandomProduct(); gdli.Discount = product.Discount; gdli.Isbn = product.Isbn; gdli.ItemNumber = (l+1).ToString(); gdli.Price = product.Price; gdli.Title = product.Title; gdli.Quantity = random.Next(1, 100); gdli.Taxable = product.Taxable; gd.Lines.Add(gdli); } gs.Documents.Add(gd); if (save) gd.Save(); } return gs; } } }
10a5262d21a0e6c2bdecdae14aa33d1fef1c94ea
C#
bpug/MetronaWT
/branches/developer/src/Metrona.Wt.Core/Extensions/DateTimeExtensions.cs
2.796875
3
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="DateTimeExtensions.cs" company="ip-connect GmbH"> // Copyright (c) ip-connect GmbH. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Metrona.Wt.Core.Extensions { using System; public static class DateTimeExtensions { public static DateTime GetFirstDayOfMonth(this DateTime myDate) { return new DateTime(myDate.Year, myDate.Month, 1); } public static DateTime GetLastDayOfMonth(this DateTime myDate) { return new DateTime(myDate.Year, myDate.Month, DateTime.DaysInMonth(myDate.Year, myDate.Month)); } public static DateTime GetPastDate(this DateTime startDate, int monthsNumber) { return startDate.AddMonths(-monthsNumber + 1); } } }
feb85626de2fe97afc141085b5551cac8a066435
C#
wesenu/CSharp-OOP-Advanced
/Unit Testing/UnitTesting-Exercise/PeopleDatabase/Database.cs
3.5625
4
using System.Collections.Generic; using System; using System.Linq; namespace PeopleDatabase { public class Database { private Dictionary<string, People> peopleByUsername; private Dictionary<long, People> peopleById; public Database() { peopleById = new Dictionary<long, People>(); peopleByUsername = new Dictionary<string, People>(); } public Database(IEnumerable<People> people) : this() { foreach (People person in people) { Add(person); } } public void Add(People people) { if (this.peopleByUsername.ContainsKey(people.Username) || peopleById.ContainsKey(people.Id)) { throw new InvalidOperationException("Username or id already exists in the database!"); } peopleById.Add(people.Id, people); peopleByUsername.Add(people.Username, people); } public void Remove() { if (peopleById.Count <= 0 || peopleByUsername.Count <= 0) { throw new InvalidOperationException("Database is empty!"); } long id = peopleById.Last().Key; peopleById.Remove(id); string username = peopleByUsername.Last().Key; peopleByUsername.Remove(username); } public People FindById(long id) { if (id < 0) { throw new ArgumentException("Id cannot be negative!"); } if (!this.peopleById.ContainsKey(id)) { throw new InvalidOperationException("There is no people with such id in the database!"); } return this.peopleById[id]; } public People FindByUsername(string username) { if (username == null) { throw new ArgumentException("Username is null!"); } if (!this.peopleByUsername.ContainsKey(username)) { throw new InvalidOperationException("There is no people with such username in the database!"); } return this.peopleByUsername[username]; } } }
28d933211f0cf53027269513178a510ffc2a8800
C#
Chris-SG/Snake
/Snake/src/Snake.cs
3.375
3
using System; using System.Collections.Generic; namespace Snake { public class SnakeObject { private SnakeDirection _direction, _directionToMove; private bool _grow; private int _moveCounter; private Tuple<int, int> _snakePos; private readonly int _speed; public SnakeObject(Tuple<int, int> aGridSize, int aSpeed = 15) { _snakePos = new Tuple<int, int>(aGridSize.Item1 / 2, aGridSize.Item2 / 2); _speed = aSpeed; Initialize(); } public SnakeObject(int x, int y, int aSpeed = 15) { _snakePos = new Tuple<int, int>(x / 2, y / 2); _speed = aSpeed; Initialize(); } public int X { get { return _snakePos.Item1; } } public bool Grow { set { _grow = value; } } public int Y { get { return _snakePos.Item2; } } public SnakeDirection Direction { get { return _direction; } set { _directionToMove = value; } } public int Length { get { return SnakePos.Count; } } public List<Tuple<int, int>> SnakePos { get; private set; } public int Lives { get; set; } public bool IsSnakeNew { get; private set; } private void Initialize() { SnakePos = new List<Tuple<int, int>>(); for (var i = 0; i < 3; i++) SnakePos.Add(_snakePos); _directionToMove = SnakeDirection.Right; _direction = _directionToMove; _grow = false; _moveCounter = _speed; IsSnakeNew = true; } public void Movement() { if (--_moveCounter == 0) { IsSnakeNew = false; _moveCounter = _speed; _direction = _directionToMove; //TODO: Maybe set a snake part length 50 to make it move faster switch (Direction) { case SnakeDirection.Up: //negative y _snakePos = new Tuple<int, int>(_snakePos.Item1, _snakePos.Item2 - 1); SnakePos.Add(_snakePos); break; case SnakeDirection.Right: //positive x _snakePos = new Tuple<int, int>(_snakePos.Item1 + 1, _snakePos.Item2); SnakePos.Add(_snakePos); break; case SnakeDirection.Down: //positive y _snakePos = new Tuple<int, int>(_snakePos.Item1, _snakePos.Item2 + 1); SnakePos.Add(_snakePos); break; case SnakeDirection.Left: //negative x _snakePos = new Tuple<int, int>(_snakePos.Item1 - 1, _snakePos.Item2); SnakePos.Add(_snakePos); break; } if (_grow != true) SnakePos.RemoveAt(0); _grow = false; } } } }
cb4111a15e3baa8ea1c94c01a427bfb6d11c9541
C#
maryekb94/HomeWork2-.NET-
/totalizator/totalizator/Gambler.cs
3.15625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Forms; namespace totalizator { //игрок public class Gambler { public string name_player; public int number_player; public int money_player; // Имя игрока public string NamePlayer { get { return name_player; } private set { name_player = value; } } //номер игрока. public int NumberPlayer { get { return number_player + 1; } private set { number_player = value; } } // Количество днег у игрока public int MoneyPlayer { get { return money_player; } set { money_player = value; } } //конструктор игрока public Gambler(string name, int num, int curMoney) { NamePlayer = name; NumberPlayer = num; MoneyPlayer = curMoney; } //метод который делает ставку игрока public Bet stavka(int money,Bug bug) { MoneyPlayer -= money; return new Bet(this, money, bug); } //игрок забирает выигрыш public void GetPrize(int money) { MoneyPlayer += money; } } }
89eb64a05084544aaf5620cac0a39bb775d217b3
C#
karamizrak/AnalyticHierarchyProcess
/AnalyticHierarchyProcess/AnalyticHierarchyProcess/Classes/AHP.cs
2.953125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AnalyticHierarchyProcess.Classes { public class AHP { private static AHP anchorInstance = null; public static AHP Instance { get { if (anchorInstance == null) { anchorInstance = new AHP(); } return anchorInstance; } } public List<Criterion> Criteria { get; private set; } private List<double?> evaluations; //Singleton costructor private AHP() { } public void PrepareDataStructure(List<string> namesOfCriteria, List<string> namesOfAlternatives) { Criteria = new List<Criterion>(); foreach (var criterionName in namesOfCriteria) { Criteria.Add(new Criterion(criterionName)); foreach (var alternativeName in namesOfAlternatives) { Criteria.Last().ValuesOfAlternatives.Add(new Alternative(alternativeName)); } } evaluations = new List<double?>(namesOfAlternatives.Count); for (int i = 0; i < evaluations.Capacity; i++) { evaluations.Add(null); } } public void SetCriteriaPairwiseValues(double[][] Matrix) { for (int i = 0; i < Criteria.Count; i++) { Criteria[i].PairwiseValues = Matrix[i]; } } private void ComputeCriteriaCoeffs() { double CoeffSum = 0.0; foreach (var item in Criteria) { foreach (var element in item.PairwiseValues) { if (item.Coeff == 0.0) { item.Coeff = element; } else { item.Coeff *= element; } } item.Coeff = Math.Pow(item.Coeff, 1.0 / item.PairwiseValues.Length); CoeffSum += item.Coeff; } foreach (var item in Criteria) { item.Coeff = (item.Coeff / CoeffSum) * item.PairwiseValues.Length; item.Coeff = Math.Round(item.Coeff, 3); } } public void ComputeEvaluationOfAlternatives() { ComputeCriteriaCoeffs(); foreach (var item in Criteria) { item.ComputeAlternativesCoeffs(); } for (int i = 0; i < evaluations.Count; i++) { evaluations[i] = 0.0; foreach (var item in Criteria) { evaluations[i] += item.Coeff * item.ValuesOfAlternatives[i].Coeff; } } } public string GetNameOfBestAlternative() { if (evaluations.Contains(null)) throw new Exception("Brak ocen alternatyw"); double? maxValue = evaluations.Max(); return Criteria[0].ValuesOfAlternatives[evaluations.IndexOf(maxValue)].Name; } public double? GetEvaluationOfBestAlternative() { return evaluations.Max(); } public bool CheckDataIntegrity() { List<double> RI = new List<double> { 0.0, 0.0, 0.52, 0.89, 1.11, 1.25, 1.35, 1.40, 1.45, 1.49 }; List<double> lMax = new List<double>(); List<double> CI = new List<double>(); List<double> CR = new List<double>(); double t1 = 0.0, t2 = 0.0; foreach (var item in Criteria) { t1 = 0.0; for (int i = 0; i < item.PairwiseValues.Length; i++) { t1 += item.PairwiseValues[i]; } t2 = t1 * item.Coeff; } lMax.Add(t2 / Criteria.Count); foreach (var item in Criteria[0].ValuesOfAlternatives) { t1 = 0.0; for (int i = 0; i < item.PairwiseValues.Length; i++) { t1 += item.PairwiseValues[i]; } t2 = t1 * item.Coeff; } return false; } } }
5e1b4fd87cbf9eecbd17457fcfce710e0c9bec8d
C#
brentstrandy/outpost-old
/Assets/Code/Utilities/SamplingExtensions.cs
2.90625
3
using System.Collections.Generic; using UnityEngine; using Settworks.Hexagons; public static class SamplingExtensions { public static float Sample(this IEnumerable<float> points, SamplingAlgorithm alg) { float output = 0f; int index = 0; foreach (var point in points) { output = CumulativeSampleFunc(output, point, index, alg); index++; } if (alg == SamplingAlgorithm.Mean) { output /= index; } return output; } public static Vector3 Sample(this IEnumerable<Vector3> points, SamplingAlgorithm alg) { Vector3 output = Vector3.zero; int index = 0; foreach (var point in points) { output.x = CumulativeSampleFunc(output.x, point.x, index, alg); output.y = CumulativeSampleFunc(output.y, point.y, index, alg); output.z = CumulativeSampleFunc(output.z, point.z, index, alg); index++; } if (alg == SamplingAlgorithm.Mean) { output.x /= index; output.y /= index; output.z /= index; } return output; } public static Vector3 Sample(this IEnumerable<Vector3> points, SamplingAlgorithm x, SamplingAlgorithm y, SamplingAlgorithm z) { Vector3 output = Vector3.zero; int index = 0; foreach (var point in points) { output.x = CumulativeSampleFunc(output.x, point.x, index, x); output.y = CumulativeSampleFunc(output.y, point.y, index, y); output.z = CumulativeSampleFunc(output.z, point.z, index, z); index++; } if (x == SamplingAlgorithm.Mean) { output.x /= index; } if (y == SamplingAlgorithm.Mean) { output.y /= index; } if (z == SamplingAlgorithm.Mean) { output.z /= index; } return output; } public static float SampleX(this IEnumerable<Vector3> points, SamplingAlgorithm alg) { float output = 0.0f; int index = 0; foreach (var point in points) { output = CumulativeSampleFunc(output, point.x, index, alg); index++; } if (alg == SamplingAlgorithm.Mean) { output /= index; } return output; } public static float SampleY(this IEnumerable<Vector3> points, SamplingAlgorithm alg) { float output = 0.0f; int index = 0; foreach (var point in points) { output = CumulativeSampleFunc(output, point.y, index, alg); index++; } if (alg == SamplingAlgorithm.Mean) { output /= index; } return output; } public static float SampleZ(this IEnumerable<Vector3> points, SamplingAlgorithm alg) { float output = 0.0f; int index = 0; foreach (var point in points) { output = CumulativeSampleFunc(output, point.z, index, alg); index++; } if (alg == SamplingAlgorithm.Mean) { output /= index; } return output; } public static float Sample(this IEnumerable<HexCoord> coords, Dictionary<HexCoord, float> points, SamplingAlgorithm alg) { float output = 0.0f; int index = 0; foreach (var coord in coords) { float value = 0.0f; points.TryGetValue(coord, out value); output = CumulativeSampleFunc(output, value, index, alg); index++; } if (alg == SamplingAlgorithm.Mean) { output /= index; } return output; } private static float CumulativeSampleFunc(float accumulation, float value, int index, SamplingAlgorithm alg) { switch (alg) { case SamplingAlgorithm.Mean: return accumulation + value; case SamplingAlgorithm.Min: return (index == 0) ? value : (value < accumulation ? value : accumulation); case SamplingAlgorithm.Max: return (index == 0) ? value : (value > accumulation ? value : accumulation); default: return value; } } }
9f84bedbc34114f491044ab4c75583de6733f9f0
C#
bailangfc/Restaurant
/ItcastCater/ItcastCaterBLL/RoomInfoBLL.cs
2.765625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ItcastCater.Model; using ItcastCater.DAL; namespace ItcastCater.BLL { public class RoomInfoBLL { RoomInfoDAL dal = new RoomInfoDAL(); /// <summary> /// 根据房间的Id删除该房间 /// </summary> /// <param name="roomId"></param> /// <returns></returns> public bool DeleteRoomInfoByRoomId(int roomId) { return dal.DeleteRoomInfoByRoomId(roomId) > 0 ? true : false; } /// <summary> /// 新增或是修改 /// </summary> /// <param name="room">房间对象</param> /// <param name="temp">1:表示新增,2:表示修改</param> /// <returns></returns> public bool SaveRoom(RoomInfo room,int temp) { int r = -1; if (temp==1) { r = dal.AddRoomInfo(room); }else if (temp == 2) { r = dal.UpdateRoomInfo(room); } return r > 0 ? true : false; } /// <summary> /// 查询所有未删除的房间 /// </summary> /// <param name="delFlag">删除标识</param> /// <returns>房间对象集合</returns> public List<RoomInfo> GetAllRoomInfoByDelflag(int delFlag) { return dal.GetAllRoomInfoByDelflag(delFlag); } /// <summary> /// 根据房间Id查询该房间信息 /// </summary> /// <param name="roomId">房间Id</param> /// <returns>房间对象</returns> public RoomInfo GetRoomInfoByRoomId(int roomId) { return dal.GetRoomInfoByRoomId(roomId); } } }
87b0aaaa241402a363e721fc504b01ba678fb6a7
C#
alvaromongon/windows-csharp-vosk-api
/Processor.VoskApi.ConsoleApp/Program.cs
2.765625
3
using System; using System.Threading.Tasks; using Processor.Abstractions; using Processor.Implementations; using Processor.VoskApi.ConsoleApp.Configuration; using Recorder.Abstractions; using Recorder.Implementations; namespace Processor.VoskApi.ConsoleApp { class Program { private static readonly IRecorderConfiguration _recorderConfiguration = new RecorderConfiguration(); private static readonly IProcessorConfiguration _processorConfiguration = new ProcessorConfiguration(); private static readonly IRecorder _recorder = new OpenTkRecorder(_recorderConfiguration); private static readonly IProcessor _processor = new VoskProcessor(_processorConfiguration); static async Task Main(string[] args) { Console.WriteLine("Program starting"); Console.WriteLine(string.Empty); Console.WriteLine($"Recorder will record for {_recorderConfiguration.SecondsToRecord} seconds, " + $"saving the wav file to folder '{_recorderConfiguration.WavFilesFolderName}' under the execution path."); Console.WriteLine($"Processor will run Python exe located in '{_processorConfiguration.PythonExeAbsolutePath}'."); Console.WriteLine("If you want to change this configuration, make the changes on the Configuration files in the ConsoleApp project."); Console.WriteLine(string.Empty); Console.WriteLine("Press Esc to close the app"); ConsoleKeyInfo pressedKey; do { Console.WriteLine("Press F2 to listen."); pressedKey = Console.ReadKey(); if (pressedKey.Key == ConsoleKey.F2) { var wavPath = await _recorder.RecordToWav(); var wordArray = await _processor.ProcessFromWav(wavPath); Console.WriteLine($"Words Listened: '{string.Join(",", wordArray)}'"); } } while (pressedKey.Key != ConsoleKey.Escape); Console.WriteLine("Clossing app"); } } }
e3d4b1a06027dc589d2f0b97b14b740a4d2ef195
C#
denmitchell/EDennis.EFBase
/EDennis.EFBase.Tests/PersonRepoTests.cs
2.640625
3
using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Text; using Xunit; using Xunit.Abstractions; namespace EDennis.EFBase.Tests { public class PersonRepoTests : UnitTestBase<PersonContext>{ private ITestOutputHelper output; private PersonRepo repo; public PersonRepoTests(ITestOutputHelper output) { this.output = output; repo = new PersonRepo(Context, Transaction); } [Theory] [InlineData(3)] [InlineData(4)] public void DeleteIdException(int id) { var ex = Assert.Throws<MissingEntityException>(() => repo.Delete(id)); Assert.Equal($"Cannot find Person object with key value = [{id}]", ex.Message); } [Fact] public void GetByLinq() { repo.Create(new Person { LastName = "Davis", FirstName = "John" }); repo.Create(new Person { LastName = "Jones", FirstName = "Bob" }); var actual = repo.GetByLinq(p => p.LastName == "Davis", 1, 2); Assert.Single(actual); } } }
e94a5185c1de581d60d4c022b37d563a06f66474
C#
Azure-Samples/iot-edge-opc-plc
/src/AlarmCondition/ParsedNodeId.cs
2.515625
3
/* ======================================================================== * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 * * 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. * * The complete license agreement can be found here: * http://opcfoundation.org/License/MIT/1.00/ * ======================================================================*/ using System; using System.Text; using Opc.Ua; namespace AlarmCondition { /// <summary> /// Stores the elements of a NodeId after it is parsed. /// </summary> /// <remarks> /// The NodeIds used by the samples are strings with an optional path appended. /// The RootType identifies the type of Root Node. The RootId is the unique identifier /// for the Root Node. The ComponentPath is constructed from the SymbolicNames /// of one or more children of the Root Node. /// </remarks> public class ParsedNodeId { #region Public Interface /// <summary> /// The namespace index that qualified the NodeId. /// </summary> public ushort NamespaceIndex { get { return m_namespaceIndex; } set { m_namespaceIndex = value; } } /// <summary> /// The identifier for the root of the NodeId. /// </summary> public string RootId { get { return m_rootId; } set { m_rootId = value; } } /// <summary> /// The type of root node. /// </summary> public int RootType { get { return m_rootType; } set { m_rootType = value; } } /// <summary> /// The relative path to the component identified by the NodeId. /// </summary> public string ComponentPath { get { return m_componentPath; } set { m_componentPath = value; } } /// <summary> /// Parses the specified node identifier. /// </summary> /// <param name="nodeId">The node identifier.</param> /// <returns>The parsed node identifier. Null if the identifier cannot be parsed.</returns> public static ParsedNodeId Parse(NodeId nodeId) { // can only parse non-null string node identifiers. if (NodeId.IsNull(nodeId)) { return null; } string identifier = nodeId.Identifier as string; if (String.IsNullOrEmpty(identifier)) { return null; } ParsedNodeId parsedNodeId = new ParsedNodeId(); parsedNodeId.NamespaceIndex = nodeId.NamespaceIndex; // extract the type of identifier. parsedNodeId.RootType = 0; int start = 0; for (int ii = 0; ii < identifier.Length; ii++) { if (!Char.IsDigit(identifier[ii])) { start = ii; break; } parsedNodeId.RootType *= 10; parsedNodeId.RootType += (byte)(identifier[ii] - '0'); } if (start >= identifier.Length || identifier[start] != ':') { return null; } // extract any component path. StringBuilder buffer = new StringBuilder(); int index = start+1; int end = identifier.Length; bool escaped = false; while (index < end) { char ch = identifier[index++]; // skip any escape character but keep the one after it. if (ch == '&') { escaped = true; continue; } if (!escaped && ch == '?') { end = index; break; } buffer.Append(ch); escaped = false; } // extract any component. parsedNodeId.RootId = buffer.ToString(); parsedNodeId.ComponentPath = null; if (end < identifier.Length) { parsedNodeId.ComponentPath = identifier.Substring(end); } return parsedNodeId; } /// <summary> /// Constructs a node identifier. /// </summary> /// <returns>The node identifier.</returns> public NodeId Construct() { return Construct(null); } /// <summary> /// Constructs a node identifier for a component with the specified name. /// </summary> /// <returns>The node identifier.</returns> public NodeId Construct(string componentName) { StringBuilder buffer = new StringBuilder(); // add the root type. buffer.Append(RootType); buffer.Append(':'); // add the root identifier. if (this.RootId != null) { for (int ii = 0; ii < this.RootId.Length; ii++) { char ch = this.RootId[ii]; // escape any special characters. if (ch == '&' || ch == '?') { buffer.Append('&'); } buffer.Append(ch); } } // add the component path. if (!String.IsNullOrEmpty(this.ComponentPath)) { buffer.Append('?'); buffer.Append(this.ComponentPath); } // add the component name. if (!String.IsNullOrEmpty(componentName)) { if (String.IsNullOrEmpty(this.ComponentPath)) { buffer.Append('?'); } else { buffer.Append('/'); } buffer.Append(componentName); } // construct the node id with the namespace index provided. return new NodeId(buffer.ToString(), this.NamespaceIndex); } #endregion #region Private Fields private ushort m_namespaceIndex; private string m_rootId; private int m_rootType; private string m_componentPath; #endregion } }
0f5487bba80fcaebfa3c745754c01b56c523cd3a
C#
Nthouvenot/CDA2005
/FOAD_DesignPattern/DesignPatternCompositeFigure/CompositeLibrary/Figures.cs
3.09375
3
using System; using System.Collections.Generic; using System.Text; namespace CompositeLibrary { public class Figures : Figure { private List<Figure> figuresToDraw; public Figures(Coordinate coordinate) : base(coordinate) { this.figuresToDraw = new List<Figure>(); } public void AddFigure(Figure figure) { this.figuresToDraw.Add(figure); } public override void Draw() { foreach(Figure figure in figuresToDraw) { figure.Draw(); } } } }
3d3d17aef3abebbbf84f1ed55cd299f91f8ef440
C#
Level0r0s/JSC-Cross-Compiler
/examples/java/Test/ReferenceObjectMembers/ReferenceObjectMembers/Class1.cs
2.5625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; using ScriptCoreLib; [assembly: Script, ScriptTypeFilter(ScriptType.Java)] namespace ReferenceObjectMembers { [Script] public class Class1 : ReferenceObjectMembers.IClass1 { public override bool Equals(object obj) { return base.Equals(obj); } public override int GetHashCode() { return base.GetHashCode(); } public override string ToString() { return base.ToString(); } } [Script] class MyClass { public static void UsingClass1(Class1 c) { var e = c.Equals(c); var h = c.GetHashCode(); var s = c.ToString(); } } } namespace ScriptCoreLibJava.BCLImplementation.System { [Script( Implements = typeof(global::System.Object), ImplementationType = typeof(global::java.lang.Object) //Implements = typeof(global::System.Object), //ImplementationType = typeof(object) )] internal class __Object { //[Script(ExternalTarget = "toString")] //public new string ToString() //{ // return default(string); //} //[Script(DefineAsStatic = true)] //new public Type GetType() //{ // return __Type.GetTypeFromValue(this); //} } } namespace java.lang { // http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Object.html [Script(IsNative = true)] public class Object { /// <summary> /// Indicates whether some other object is "equal to" this one. /// </summary> public override bool Equals(object @obj) { return default(bool); } /// <summary> /// Returns a hash code value for the object. /// </summary> public override int GetHashCode() { return default(int); } /// <summary> /// Returns a string representation of the object. /// </summary> public override string ToString() { return default(string); } } }
a536d6f7a8b0f3a2e778d1deb788c9a062cd6824
C#
georgimanov/Bloggable
/src/Bloggable.Common/Extensions/IEnumerableExtensions.cs
3.546875
4
namespace Bloggable.Common.Extensions { using System; using System.Collections.Generic; using System.Linq; public static class IEnumerableExtensions { public static void ForEach<T>(this IEnumerable<T> enumerable, Action<T> action) { if (enumerable == null) { throw new ArgumentNullException(nameof(enumerable)); } if (action == null) { throw new ArgumentNullException(nameof(action)); } foreach (var item in enumerable) { action(item); } } public static bool IsNullOrEmpty<T>(this IEnumerable<T> source) => source == null || !source.Any(); } }
381074f7504da70e2c3701c3d47fe3636658720f
C#
Auropath/OregonTrail
/src/Module/Tombstone/Tombstone.cs
3.359375
3
// Created by Ron 'Maxwolf' McDowell (ron.mcdowell@gmail.com) // Timestamp 01/03/2016@1:50 AM using System; namespace OregonTrailDotNet.Module.Tombstone { /// <summary> /// Facilitates a tombstone base class that supports shallow copies of itself to be created. /// </summary> public sealed class Tombstone { /// <summary> /// Initializes a new instance of the <see cref="Tombstone" /> class. /// Creates a shallow copy of the tombstone, generates a new tombstone ID in the process. /// </summary> public Tombstone() { // Loop through all the vehicle passengers and find the leader. foreach (var passenger in GameSimulationApp.Instance.Vehicle.Passengers) { // Skip if not the leader. if (!passenger.Leader) continue; // Add the leaders name to the Tombstone header. PlayerName = passenger.Name; break; } // Grabs the current mile marker where the player died on the trail for the Tombstone to sit at. MileMarker = GameSimulationApp.Instance.Vehicle.Odometer; // Epitaph is left empty by default and ready to be filled in. Epitaph = string.Empty; } /// <summary> /// Name of the player whom died and the Tombstone is paying respects to. /// </summary> public string PlayerName { get; } /// <summary> /// Defines where on the trail in regards to length in miles traveled. The purpose of this is so we can check for this /// Tombstone in the exact same spot where the player actually died on the trail. /// </summary> public int MileMarker { get; } /// <summary> /// Message that can be included on the Tombstone below the players name. It can only be a few characters long but /// interesting to see what people leave as warnings or just silliness for other travelers. /// </summary> public string Epitaph { get; set; } /// <summary> /// Creates a shallow copy of our tombstone, used to add to list without having direct copy still tied to it. /// </summary> /// <returns> /// The <see cref="object" />. /// </returns> public object Clone() { var clone = (Tombstone) MemberwiseClone(); return clone; } /// <summary> /// Creates a nice formatted version of the Tombstone for use in text renderer. /// </summary> /// <returns> /// The <see cref="string" />. /// </returns> public override string ToString() { // Only print the name if the epitaph is empty or null. if (string.IsNullOrEmpty(Epitaph)) return $"Here lies {PlayerName}{Environment.NewLine}"; // Print the name and epitaph message the player left for others to read. return $"Here lies {PlayerName}{Environment.NewLine}" + $"{Epitaph}{Environment.NewLine}"; } } }
250bc2bd314307801dd2bcbd2f5a1e436f3a5a8d
C#
grcodemonkey/iron_dotnet
/src/IronSharp.IronMQ/MessageOptions.cs
2.6875
3
using IronSharp.Core; using Newtonsoft.Json; namespace IronSharp.IronMQ { public class MessageOptions : IInspectable { /// <summary> /// The item will not be available on the queue until this many seconds have passed. /// Default is 0 seconds. /// Maximum is 604,800 seconds (7 days). /// </summary> [JsonProperty("delay", DefaultValueHandling = DefaultValueHandling.Ignore)] public int? Delay { get; set; } /// <summary> /// How long in seconds to keep the item on the queue before it is deleted. /// Default is 604,800 seconds (7 days). /// Maximum is 2,592,000 seconds (30 days). /// </summary> [JsonProperty("expires_in", DefaultValueHandling = DefaultValueHandling.Ignore)] public int? ExpiresIn { get; set; } /// <summary> /// After timeout (in seconds), item will be placed back onto queue. /// You must delete the message from the queue to ensure it does not go back onto the queue. /// Default is 60 seconds. /// Minimum is 30 seconds, and maximum is 86,400 seconds (24 hours). /// </summary> [JsonProperty("timeout", DefaultValueHandling = DefaultValueHandling.Ignore)] public int? Timeout { get; set; } } }
d241cf9e1beb08388b163fb0cbb542720152d22a
C#
wesseln1/LINQedList
/Program.cs
3.53125
4
using System; using System.Collections.Generic; using System.Linq; using System.Runtime; namespace LINQedList { class Program { static void Main(string[] args) { // Find the words in the collection that start with the letter 'L' List<string> fruits = new List<string>() { "Lemon", "Apple", "Orange", "Lime", "Watermelon", "Loganberry" }; List<string> LFruits = fruits.Where(fruit => { bool startsWithL = fruit.StartsWith("L"); return startsWithL; }).ToList(); foreach (string fruit in LFruits) { Console.WriteLine(fruit); } // Which of the following numbers are multiples of 4 or 6 List<int> numbers = new List<int>() { 15, 8, 21, 24, 32, 13, 30, 12, 7, 54, 48, 4, 49, 96 }; List<int> fourSixMultiples = numbers.Where(num => { bool isMultiple = num % 4 == 0 || num % 6 == 0; return isMultiple; }).ToList(); foreach (int number in fourSixMultiples) { Console.WriteLine(number); } // Order these student names alphabetically, in descending order (Z to A) List<string> names = new List<string>() { "Heather", "James", "Xavier", "Michelle", "Brian", "Nina", "Kathleen", "Sophia", "Amir", "Douglas", "Zarley", "Beatrice", "Theodora", "William", "Svetlana", "Charisse", "Yolanda", "Gregorio", "Jean-Paul", "Evangelina", "Viktor", "Jacqueline", "Francisco", "Tre" }; names.Sort(); foreach (string name in names) { Console.WriteLine(name); } // Build a collection of these numbers sorted in ascending order List<int> numbers2 = new List<int>() { 15, 8, 21, 24, 32, 13, 30, 12, 7, 54, 48, 4, 49, 96 }; numbers2.Sort(); foreach (int number in numbers2) { Console.WriteLine(number); } // Output how many numbers are in this list List<int> numbers3 = new List<int>() { 15, 8, 21, 24, 32, 13, 30, 12, 7, 54, 48, 4, 49, 96 }; int sumOfNumbers = numbers3.Sum(); Console.WriteLine(sumOfNumbers); // How much money have we made? List<double> purchases = new List<double>() { 2340.29, 745.31, 21.76, 34.03, 4786.45, 879.45, 9442.85, 2454.63, 45.65 }; double moneyMade = purchases.Sum(); Console.WriteLine(moneyMade); // What is our most expensive product? List<double> prices = new List<double>() { 879.45, 9442.85, 2454.63, 45.65, 2340.29, 34.03, 4786.45, 745.31, 21.76 }; double maxPrice = prices.Max(); Console.WriteLine(maxPrice); /* Store each number in the following List until a perfect square is detected. Ref: https://msdn.microsoft.com/en-us/library/system.math.sqrt(v=vs.110).aspx */ List<int> wheresSquaredo = new List<int>() { 66, 12, 8, 27, 82, 34, 7, 50, 19, 46, 81, 23, 30, 4, 68, 14 }; List<int> squareNumbers = wheresSquaredo.TakeWhile(num => { bool isSquared = Math.Sqrt(num) % 1 == 0; return !isSquared; }).ToList(); foreach (int num in squareNumbers) { Console.WriteLine(num); } List<Customer> customers = new List<Customer>() { new Customer() { Name = "Bob Lesman", Balance = 80345.66, Bank = "FTB" }, new Customer() { Name = "Joe Landy", Balance = 9284756.21, Bank = "WF" }, new Customer() { Name = "Meg Ford", Balance = 487233.01, Bank = "BOA" }, new Customer() { Name = "Peg Vale", Balance = 7001449.92, Bank = "BOA" }, new Customer() { Name = "Mike Johnson", Balance = 790872.12, Bank = "WF" }, new Customer() { Name = "Les Paul", Balance = 8374892.54, Bank = "WF" }, new Customer() { Name = "Sid Crosby", Balance = 957436.39, Bank = "FTB" }, new Customer() { Name = "Sarah Ng", Balance = 56562389.85, Bank = "FTB" }, new Customer() { Name = "Tina Fey", Balance = 1000000.00, Bank = "CITI" }, new Customer() { Name = "Sid Brown", Balance = 49582.68, Bank = "CITI" } }; var groups = customers.Where(num => { bool isMillionaire = num.Balance > 999999; return isMillionaire; }).GroupBy(customer => customer.Bank); foreach (var group in groups) { Console.WriteLine($"{group.Key} had {group.Count()} customers over $1,000,000 in their account!"); } } } }
7b23f6cf098c02d76845fd1b36e3c019e989dc26
C#
apterid/apterid-bootstrap
/Src/Apterid.Bootstrap.Parse.Tests/LexiconTests.cs
2.625
3
// Copyright (C) 2015 The Apterid Developers - See LICENSE using System; using System.Linq; using System.Numerics; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Apterid.Bootstrap.Parse.Tests { [TestClass] public class LexiconTests { ApteridParser parser = new ApteridParser(); [TestMethod] public void Parser_Lexicon_IntegerLiteral() { const string s1 = "123"; var m1 = parser.GetMatch(s1, parser.DecimalInteger); Assert.IsTrue(m1.Success); Assert.AreEqual(123, (int)((Syntax.Literal<BigInteger>)m1.Result).Value); const string s2 = "-34_56"; var m2 = parser.GetMatch(s2, parser.DecimalInteger); Assert.IsTrue(m2.Success); Assert.AreEqual(-3456, (int)((Syntax.Literal<BigInteger>)m2.Result).Value); } [TestMethod] public void Parser_Lexicon_QualifiedIdentifier() { const string s1 = "a.b.c"; var parser = new ApteridParser { SourceFile = new MemorySourceFile(s1) }; var m1 = parser.GetMatch(s1, parser.QualifiedIdentifier); Assert.IsTrue(m1.Success); Assert.IsInstanceOfType(m1.Result, typeof(Syntax.QualifiedIdentifier)); var r1 = m1.Result as Syntax.QualifiedIdentifier; Assert.AreEqual(5, r1.Children.Length); Assert.IsInstanceOfType(r1.Children[0], typeof(Syntax.Identifier)); Assert.IsInstanceOfType(r1.Children[1], typeof(Syntax.Punct)); Assert.IsInstanceOfType(r1.Children[2], typeof(Syntax.Identifier)); Assert.IsInstanceOfType(r1.Children[3], typeof(Syntax.Punct)); Assert.IsInstanceOfType(r1.Children[4], typeof(Syntax.Identifier)); Assert.AreEqual(2, r1.Qualifiers.Count()); Assert.AreEqual("a", r1.Qualifiers.ElementAt(0).Text); Assert.AreEqual("b", r1.Qualifiers.ElementAt(1).Text); } [TestMethod] public void Parser_Lexicon_Identifier() { const string s1 = "_"; var m1 = parser.GetMatch(s1, parser.Identifier); Assert.IsTrue(m1.Success); Assert.AreEqual(s1.Length, m1.NextIndex); const string s2 = "_1a"; var m2 = parser.GetMatch(s2, parser.Identifier); Assert.IsTrue(m2.Success); Assert.AreEqual(s2.Length, m2.NextIndex); const string s4 = "a3_b4"; var m4 = parser.GetMatch(s4, parser.Identifier); Assert.IsTrue(m4.Success); Assert.AreEqual(s4.Length, m4.NextIndex); const string s3 = "123b_c"; var m3 = parser.GetMatch(s3, parser.Identifier); Assert.IsFalse(m3.Success); const string s5 = " "; var m5 = parser.GetMatch(s5, parser.Identifier); Assert.IsFalse(m5.Success); const string s6 = ""; var m6 = parser.GetMatch(s6, parser.Identifier); Assert.IsFalse(m6.Success); const string s7 = "a"; var m7 = parser.GetMatch(s7, parser.Identifier); Assert.IsTrue(m7.Success); Assert.AreEqual(s7.Length, m7.NextIndex); } [TestMethod] public void Parser_Lexicon_InlineComment() { const string s1 = "/* baz */ foo */"; var m1 = parser.GetMatch(s1, parser.InlineComment); Assert.IsTrue(m1.Success); Assert.AreEqual(0, m1.StartIndex); Assert.AreEqual(9, m1.NextIndex); const string s2 = "foo */"; var m2 = parser.GetMatch(s2, parser.InlineComment); Assert.IsFalse(m2.Success); } [TestMethod] public void Parser_Lexicon_LineComment() { const string s1 = "// comment\nblahblahblah"; var m1 = parser.GetMatch(s1, parser.LineComment); Assert.IsTrue(m1.Success); Assert.AreEqual(0, m1.StartIndex); Assert.AreEqual(11, m1.NextIndex); const string s2 = "// comment"; var m2 = parser.GetMatch(s2, parser.LineComment); Assert.IsTrue(m2.Success); Assert.AreEqual(0, m2.StartIndex); Assert.AreEqual(10, m2.NextIndex); const string s3 = "ghuwrbgu8 48h2 //"; var m3 = parser.GetMatch(s3, parser.LineComment); Assert.IsFalse(m3.Success); const string s4 = "//\nhghg"; var m4 = parser.GetMatch(s4, parser.LineComment); Assert.IsTrue(m4.Success); const string s5 = ""; var m5 = parser.GetMatch(s5, parser.LineComment); Assert.IsFalse(m5.Success); } } }
bbffe080df8cbb30a47463cfa8500e51c39f59a2
C#
shendongnian/download4
/code8/1373030-37169575-117848146-2.cs
3.796875
4
class Program { static void Main(string[] args) { Instance.Instantiate(); Referent.Refer(Instance.GetInstance()); Console.ReadLine(); } } public class Instance { private static Instance myInstance; public void OnInstantiated() { Console.WriteLine("I have been instantiated."); } public void OnReferred() { Console.WriteLine("I have been referred to."); } public static void Instantiate() { myInstance = new Instance(); myInstance.OnInstantiated(); } public static Instance GetInstance() { return myInstance; } } public class Referent { public static void Refer(Instance instance) { if (instance != null) { instance.OnReferred(); } else { Console.WriteLine("No instance to refer to."); } } }
f5bcda63aec8620cd262b64b008beb2dc09964f3
C#
raccoon-repo/coursework
/DatabaseImpl/Database/Queries/Books.cs
2.625
3
namespace BookLibrary.Database.Queries { public static class Books { public const string FIND_BY_ID = "SELECT * FROM book AS b WHERE b.id = @id"; public const string FIND_ALL = "SELECT * FROM book"; public const string COUNT_BY_ID = "SELECT COUNT(*) FROM book AS b WHERE b.id = @id"; public const string FIND_BY_TITLE = "SELECT * FROM book AS b WHERE b.title LIKE @title"; public const string FIND_BY_SECTION = "SELECT DISTINCT * FROM book b WHERE b.section = @section"; public const string FIND_BY_RATING_IN_RANGE = "SELECT DISTINCT * FROM book b WHERE b.rating >= @from AND b.rating <= @to"; public const string FIND_BY_RATING = "SELECT DISTINCT * FROM book b WHERE b.rating LIKE @rating"; public const string FETCH_BOOKS = "SELECT DISTINCT b.id, b.title, b.section, b.description, b.rating FROM book b " + "LEFT JOIN book_author ba ON ba.book_id = b.id " + "LEFT JOIN author a ON ba.author_id = a.id WHERE a.id = @id"; public const string INSERT = "INSERT INTO book (title, section, description, rating) VALUES (@title, @section, @description, @rating)"; public const string UPDATE = "UPDATE book b SET " + "b.title = @title, b.section = @section, " + "b.description = @description, b.rating = @rating " + "WHERE b.id = @id"; public const string INSERT_QUANTITY = "INSERT INTO book_quantity (book_id, quantity) VALUES (@id, @quantity)"; public const string UPDATE_QUANTITY = "UPDATE book_quantity SET quantity = @quantity WHERE book_id = @id"; public const string DELETE = "DELETE FROM book WHERE id = @id"; } }
c21d728613902ffaea711ad980ac77545864cf44
C#
shendongnian/download4
/latest_version_download2/202900-42869011-147047553-2.cs
3.34375
3
interface IAnimal { } interface ICat { void MethodUniqueToCats(); } class Cat<T> : IAnimal, ICat { public void MethodUniqueToCats() { } }
3633b69a9ec2357b870a985db0f2a4badf7b7c81
C#
davewiebe/SpaceAlert
/Assets/Scripts/Player.cs
2.59375
3
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Player : MonoBehaviour { private Vector3 MoveTowards; public Room CurrentRoom { get; set; } public Actions Actions { get; set; } public bool Moving { get; set; } public string PlayerColour { get; set; } // Use this for initialization void Start() { Moving = false; } // Update is called once per frame void Update() { transform.position = Vector3.MoveTowards(transform.position, MoveTowards, 0.05f); if (transform.position == MoveTowards) Moving = false; } public void MoveCharacterToCurrentRoom() { Moving = true; MoveTowards = CurrentRoom.Vector; } public IEnumerator ExecuteNextAction() { Debug.Log("Player_ExecuteNextAction"); var action = Actions.GetNextAction(); if (action == 'L') MoveLeft(); else if (action == 'R') MoveRight(); else if (action == 'D') DeckChange(); else if (action == 'A') PushAButton(); else if (action == 'B') PushBButton(); yield return new WaitWhile(() => Moving); } private void PushAButton() { // Todo: Animation CurrentRoom.PushA(); } private void PushBButton() { // Todo: Animation CurrentRoom.PushB(); } private void DeckChange() { CurrentRoom = CurrentRoom.GetDeckChangeRoom(); MoveCharacterToCurrentRoom(); } private void MoveRight() { CurrentRoom = CurrentRoom.GetRightRoom(); MoveCharacterToCurrentRoom(); } private void MoveLeft() { CurrentRoom = CurrentRoom.GetLeftRoom(); MoveCharacterToCurrentRoom(); } }
25bf4b2dcd76d8b69c90fde14dbcd259c9493716
C#
k2zinger/CSM-Activities
/UiPathTeam.MSExcel.Activities.Test/GetColumnLetterTest.cs
2.5625
3
using Microsoft.VisualStudio.TestTools.UnitTesting; namespace UiPathTeam.MSExcel.Activities.Test { [TestClass] public class GetColumnLetterTest { [TestMethod] public void CalculateColumnLetterTest() { var columns = new [] { new object[] { 0, "A" }, new object[] { 26, "AA" }, new object[] { 702, "AAA" }, new object[] { 4082, "FAA" }, new object[] { 16383, "XFD" } }; foreach(var col in columns) { Assert.AreEqual(GetColumnLetter.CalculateColumnLetter((int)col[0] + 1), col[1]); } } [TestMethod] public void RetrieveColumnLetterByIndexTest() { var columns = new[] { new object[] { 1, "A" }, new object[] { 27, "AA" }, new object[] { 703, "AAA" }, new object[] { 4083, "FAA" }, new object[] { 16384, "XFD" } }; foreach (var col in columns) { Assert.AreEqual(GetColumnLetter. CalculateColumnLetter((int)col[0]), col[1]); } } } }
4a82c2d2d76a163601c1f3e2d6adf46091a812a1
C#
Qlevine20/Spring-Game-Jam-2016
/Assets/Scripts/Creatures/WallDog.cs
2.765625
3
using UnityEngine; using System.Collections; public class WallDog : Creature { public override Vector3 Spawn(){ return Camera.main.ScreenToWorldPoint(new Vector3( Random.Range(5, Screen.width-5), Random.Range(5, Screen.height-5), Camera.main.nearClipPlane*100)); } public override Vector3 Move(){ Vector3 cam = Camera.main.WorldToScreenPoint(transform.position); float[] values = new float[] {cam.x, cam.y, Screen.width - cam.x, Screen.height - cam.y}; var min = Min(values); return transform.position + ((min == values[0])? Vector3.left : (min == values[1])? Vector3.down : (min == values[2])? Vector3.right : Vector3.up); } private float Min(float a, float b){ float f = ((Mathf.Abs(a) < Mathf.Abs(b))? a : b); Debug.Log(a+" : " +b + " = " +f); return f; } private float Min(float[] a){ var min = a[a.Length-1]; for(var i = a.Length-1; i >= 0; i--){ min = Min(min, a[i]); } return min; } }
5d62f8413968cb3539cee541692105d077b74059
C#
AaronJessen/UnityAzureScavenger
/src/Server/GetDailyItems.cs
2.578125
3
using System; using System.Linq; using System.Net; using System.Net.Http; using System.Threading.Tasks; using Microsoft.Azure.Documents.Client; using Microsoft.Azure.WebJobs; using Microsoft.Azure.WebJobs.Extensions.Http; using Microsoft.Azure.WebJobs.Host; namespace ScavengerServer { public static class GetDailyItems { [FunctionName("GetDailyItems")] public static async Task<HttpResponseMessage> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "GET", Route="GetDailyItems")] HttpRequestMessage req, [DocumentDB(Constants.CosmosDbName, Constants.ItemsCollectionName, ConnectionStringSetting = Constants.ConnectionStringSettingName)] DocumentClient client, TraceWriter log) { log.Info($"GetDailyItems begin"); try { string playFabId = await PlayFab.AuthenticateUserAsync(req, log); string date = DateTime.Now.ToString(Constants.DateFormat); if (string.IsNullOrEmpty(playFabId)) return new HttpResponseMessage(HttpStatusCode.Unauthorized); // Get the list of items for today Uri collectionUri = UriFactory.CreateDocumentCollectionUri(Constants.CosmosDbName, Constants.ItemsCollectionName); IOrderedQueryable<DailyItems> query = client.CreateDocumentQuery<DailyItems>(collectionUri); IQueryable<DailyItems> dailyItemsDoc = from di in query where di.Date == date select di; DailyItems[] dailyItemsArray = dailyItemsDoc.ToArray(); if(dailyItemsArray.Length == 0) { log.Error($"No daily items found for {date}"); return req.CreateErrorResponse(HttpStatusCode.InternalServerError, $"No daily items found for {date}"); } // and pull back just today's items DailyItems dailyItems = dailyItemsArray.Single(); // get all items a user has found for today Uri foundUri = UriFactory.CreateDocumentCollectionUri(Constants.CosmosDbName, Constants.FoundItemsCollectionName); IOrderedQueryable<FoundItem> foundQuery = client.CreateDocumentQuery<FoundItem>(foundUri); IQueryable<FoundItem> foundItemsDoc = from found in foundQuery where found.PlayFabId == playFabId && found.Date == date select found; FoundItem[] foundItems = foundItemsDoc.ToArray(); // mark all found items by enumerating through both arrays foreach(Item i in dailyItems.Items) { foreach(FoundItem fi in foundItems) { if(fi.Item.Id == i.Id) { i.Found = true; break; } } } log.Info($"GetDailyItems complete"); return req.CreateResponse(HttpStatusCode.OK, dailyItems); } catch (Exception ex) { log.Error(ex.Message); return req.CreateResponse(HttpStatusCode.InternalServerError, ex.Message); } } } }
8deacea54d2113f7d4df130adb249790d542096e
C#
NasC0/Telerik_HW_2013-2014
/Data Structures and Algorithms/02. LinearDataStructures/08. SequenceMajorant/SequenceMajorant.cs
3.890625
4
/* 08. * The majorant of an array of size N is a value that occurs in it at least N/2 + 1 times. * Write a program to find the majorant of given array (if exists). Example: {2, 2, 3, 3, 2, 3, 4, 3, 3}  3 */ using System; using System.Collections.Generic; using System.Linq; class SequenceMajorant { static int FindSequnceMajorant(List<int> input) { Dictionary<int, int> occurencesByKeyValue = new Dictionary<int, int>(); for (int i = 0; i < input.Count; i++) { if (occurencesByKeyValue.ContainsKey(input[i])) { occurencesByKeyValue[input[i]]++; } else { occurencesByKeyValue.Add(input[i], 1); } } int majorantRequirements = (input.Count / 2) + 1; foreach (var entry in occurencesByKeyValue) { if (entry.Value >= majorantRequirements) { return entry.Key; } } throw new OperationCanceledException("No majorant found"); } static void Main() { List<int> originalList = new List<int>() { 2, 2, 3, 3, 2, 3, 4, 3, 3 }; try { Console.WriteLine(FindSequnceMajorant(originalList)); } catch (OperationCanceledException ex) { Console.WriteLine(ex.Message); } } }
e96f39f79e0defbb873ac2e66e768b821c4e9374
C#
adyksy-epam/RTL
/RTL.TvMazeScraper.Domain/Providers/ShowProvider.cs
2.6875
3
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using RTL.TvMazeScraper.Data.Entities; using RTL.TvMazeScraper.Data.Repository; using RTL.TvMazeScraper.Domain.DTO; using RTL.TvMazeScraper.Domain.Formatters; using RTL.TvMazeScraper.Domain.Queries; namespace RTL.TvMazeScraper.Domain.Providers { public class ShowProvider : IShowProvider { private readonly IReadOnlyRepository _repository; private readonly IDateTimeFormatter _dateTimeFormatter; public ShowProvider(IReadOnlyRepository repository, IDateTimeFormatter dateTimeFormatter) { _repository = repository; _dateTimeFormatter = dateTimeFormatter; } public async Task<PaginatedResult<ShowDto>> GetShowsAsync(GetShowsWithCastQuery query) { var totalItemsCount = await _repository.CountShowsAsync(); var items = await _repository.GetShowsWithPagingAsync(query.PageNumber, query.PageSize); return new PaginatedResult<ShowDto>(ShowsToDto(items), query.PageNumber, query.PageSize, totalItemsCount); } private IEnumerable<ShowDto> ShowsToDto(IEnumerable<Show> items) => items.Select(i => new ShowDto { Id = i.ExtId, Name = i.Name, Cast = i.Cast.Select(cs => cs.Character).OrderByDescending(c => c.Birthday).Select(c => new CharacterDto { Id = c.ExtId, Name = c.Name, Birthday = _dateTimeFormatter.Format(c.Birthday) }), }); } }
69cad1b645a435594358b2c82207b68a03e0f721
C#
NicolasWeissheimer/BullethellRPG
/Objects/Building.cs
2.765625
3
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Building : MonoBehaviour { SpriteRenderer building; byte alpha; private void Start() { building = GetComponent<SpriteRenderer>(); } public IEnumerator HideBuilding() { int i = 0; while (i < 19) { Color32 colorAlpha = building.color; alpha -= 13; if (alpha < 0) { alpha = 0; } colorAlpha.a = alpha; building.color = colorAlpha; yield return new WaitForSeconds(0.02f); i++; } Color32 color = building.color; alpha = 0; color.a = alpha; building.color = color; } public IEnumerator ShowBuilding() { int i = 0; while (i < 19) { Color32 colorAlpha = building.color; alpha += 13; if (alpha > 255) { alpha = 0; } colorAlpha.a = alpha; building.color = colorAlpha; yield return new WaitForSeconds(0.02f); i++; } Color32 color = building.color; alpha = 255; color.a = alpha; building.color = color; } }
51ac17c1954e7209f8ea61d0b5e9ee567a658321
C#
VRDate/json-everything
/JsonPath/QueryExpressions/GreaterThanOperator.cs
2.765625
3
using System; using System.Text.Json; using Json.More; namespace Json.Path.QueryExpressions { internal class GreaterThanOperator : IQueryExpressionOperator { public int OrderOfOperation => 4; public QueryExpressionType GetOutputType(QueryExpressionNode left, QueryExpressionNode right) { if (left.OutputType != right.OutputType) return QueryExpressionType.Invalid; return left.OutputType switch { QueryExpressionType.Number => QueryExpressionType.Boolean, QueryExpressionType.String => QueryExpressionType.Boolean, _ => QueryExpressionType.Invalid }; } public JsonElementProxy Evaluate(QueryExpressionNode left, QueryExpressionNode right, JsonElement element) { var lElement = left.Evaluate(element); var rElement = right.Evaluate(element); switch (lElement.ValueKind) { case JsonValueKind.Number: if (lElement.ValueKind != JsonValueKind.Number || rElement.ValueKind != JsonValueKind.Number) return default; return lElement.GetDecimal() > rElement.GetDecimal(); case JsonValueKind.String: if (lElement.ValueKind != JsonValueKind.String || rElement.ValueKind != JsonValueKind.String) return default; return string.Compare(lElement.GetString(), rElement.GetString(), StringComparison.Ordinal) > 0; default: return default; } } public string ToString(QueryExpressionNode left, QueryExpressionNode right) { var lString = left.MaybeAddParentheses(OrderOfOperation); var rString = right.MaybeAddParentheses(OrderOfOperation); return $"{lString}>{rString}"; } } }
b2438a9e3532f0b65e04fad997539f03da166381
C#
klavskruz/vaproofofconcept
/Extras/TableParser/TableParser.cs
3.03125
3
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Threading.Tasks; namespace MeetingApi.Extras.TableParser { public class TableParser { public static string ConvertToHtml(DataTable dt) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.AppendLine("<html>"); sb.AppendLine("<body>"); sb.AppendLine("<table BORDER ='1'>"); foreach (DataColumn dc in dt.Columns) { sb.AppendFormat("<th align = 'center'>{0}</th>", dc.ColumnName); } foreach (DataRow dr in dt.Rows) { sb.Append("<tr>"); foreach (DataColumn dc in dt.Columns) { string cellValue = dr[dc] != null ? dr[dc].ToString() : ""; sb.AppendFormat("<td>{0}</ td>", cellValue); } sb.AppendLine("</tr>"); } sb.AppendLine("</table>"); sb.AppendLine("</body>"); sb.AppendLine("</html>"); return sb.ToString(); } } }
f0384a0ff055641d5516085f53553ec02393b95e
C#
imonfire328/Cutlist
/MD/MdShapeWriter.cs
3.03125
3
using System; using iTextSharp.text; using iTextSharp.text.pdf; namespace CLGenerator.MD { public class MdShapeWriter : MdRectangleWriter { public MdShapeWriter() { } /// <summary> /// Returns a list of dimensions with zoom applied /// </summary> /// <returns>The proportions.</returns> /// <param name="point">Point.</param> /// <param name="dim">Dim.</param> /// <param name="zoom">Zoom.</param> public double[] Proportions(MdPoint point, MdDimension dim, int zoom = 1) { return new double[] { point.X * zoom, point.Y * zoom, dim.Y * zoom, dim.X * zoom }; } } /// <summary> /// Draws a rectangle to the given PdfContentByte /// </summary> public class MdRectangleWriter { public PdfContentByte DrawRectangle(PdfContentByte cb, double[] proportions, BaseColor color){ cb.SetColorFill(color); cb.Rectangle(proportions[0], proportions[1], proportions[3], proportions[2]); cb.FillStroke(); return cb; } } }
a1c7ae97e0efc24f3c80e41a3a16aa6bcc0f51ec
C#
LGM-AdrianHum/xbmcontrol
/Configuation.class.cs
2.734375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml; using System.Xml.Serialization; using System.IO; namespace XBMControl.Configuration { class XBMControlConfiguration { private string ip; private string username; private string password; private struct SConfigData { string ip, username, password; } public XBMControlConfiguration() { } public void SaveConfiguration(string ip, string username, string password) { XmlTextWriter XMLwriter = new XmlTextWriter("configuration.xml", System.Text.Encoding.UTF8); XMLwriter.WriteStartElement("configuration"); XMLwriter.WriteElementString("ip", ip); XMLwriter.WriteElementString("username", username); XMLwriter.WriteElementString("password", password); XMLwriter.WriteEndElement(); XMLwriter.Flush(); XMLwriter.Close(); } public void LoadConfiguration() { SConfigData ConfigData; FileStream fConfigStream = new FileStream("configuraion.xml", FileMode.Open); XmlSerializer ConfigSerialized = new XmlSerializer(typeof(SConfigData)); ConfigData = (SConfigData)ConfigSerialized.Deserialize(fConfigStream); fConfigStream.Close(); } } }
7bd4e37be014fda7c5bb093af475c4581bfde5d2
C#
pacefist/BoxDuino
/LiteSoftForCOMExchangeData/WindowsFormsApp1/WindowsFormsApp1/SerialClass.cs
2.765625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO.Ports; namespace WindowsFormsApp1 { // данный класс организует обмен данными с портом COM class SerialClass { public List<String> Ports = new List<String> { }; // список доступных портов public bool updated = false; // состояние окончания процесса поиска и обновления списка портов public int ComCounts = 0; // количество найденных портов public int ComActive = 0; // порт на котором найдено устройство public int NumberActualPort = 0; // количество портов на которых найдено наше устройство string indata = ""; // в данную перемнную будем читать данные приходящие в порт public void updatePorts() { int i = 0; String[] ports = SerialPort.GetPortNames(); // получаем список портов ComCounts = ports.Length; //просто сохраняем количество портов NumberActualPort = 0; // обнуляем количество портов с устройством updated = false; // порты еще ищутся и проверяются Ports.Clear(); // очищаем лист портов try { while (ports[i] != null) // проверяем каждый порт в цикле { SerialPort mySerialPort = new SerialPort(ports[i]); // подключаемся к порту string EnterWord=""; // переменная для строки отправки EnterWord = DataModify.DataGenerateForGetByte(1, 101); // формируем запрос на первый канал в регистр 101 define.ComSetupPreferences(mySerialPort); // указываем настройки порта mySerialPort.DataReceived += new SerialDataReceivedEventHandler (DataReceivedHandler); // указываем обработчик события по приему данных try { mySerialPort.Open(); // открываем порт indata = ""; // очищаем буфер приема if (mySerialPort.IsOpen) // если порт открылся { mySerialPort.Write(EnterWord); // отправка в порт запроса содержимого регистра 101 DateTime foo = DateTime.Now; // берем текущее время long unixTime = ((DateTimeOffset)foo).ToUnixTimeSeconds(); // переводим в формат unixTime while ((unixTime + 2) > ((DateTimeOffset)DateTime.Now).ToUnixTimeSeconds()) // ждем 2 секунды { } byte[] asciiBytes = Encoding.GetEncoding(1251).GetBytes(indata); // конвертируем принятые данные в кодировку CP-1251 int crc = CRC.CRC_calc_check(asciiBytes); // вычисляем CRC if (indata.Length > 5) // проверяем корректность полученных данных if (DataCheck.CheckAdressOk(1, indata) && DataCheck.CheckFunctionOk(3, indata) && crc == (asciiBytes[asciiBytes.Length - 1] * 256 + asciiBytes[asciiBytes.Length - 2]) && (asciiBytes[3] * 256 + asciiBytes[4]) == 140) // если данные корректны { NumberActualPort++; ComActive = i; } // сохраняем информацию о найденонм устройстве mySerialPort.Close(); // закрываем порт Ports.Add(ports[i]); // добавляем новую запись в порт } } catch { Ports.Add(ports[i]); // действие в случае, если ошибка открытия порта mySerialPort.Close(); } i++; } } catch { } updated = true; //поиск портов завершен } // чтение одного двухбайтового числового значения с устройства из заданного регистра public int ReadIntParam(SerialPort port, int adress) { if (port.IsOpen) { string data = ""; data = DataModify.DataGenerateForGetByte(1, adress); indata = ""; port.Write(data); DateTime foo = DateTime.Now; long unixTime = ((DateTimeOffset)foo).ToUnixTimeSeconds(); while ((unixTime + 2) > ((DateTimeOffset)DateTime.Now).ToUnixTimeSeconds()) { if (indata.Length >= 7) break; } byte[] asciiBytes = Encoding.GetEncoding(1251).GetBytes(indata); if (CRC.CRC_calc_check(asciiBytes) == (asciiBytes[asciiBytes.Length - 1] * 256 + asciiBytes[asciiBytes.Length - 2])) return asciiBytes[4]; } return -1; } //запись в заданный регистр одного двухбайтового числа public int WriteIntParam(SerialPort port, int adress, int value) { if (port.IsOpen) { string data = ""; data = DataModify.DataGenerateForSendByte(1, adress, value); indata = ""; port.Write(data); DateTime foo = DateTime.Now; long unixTime = ((DateTimeOffset)foo).ToUnixTimeSeconds(); while ((unixTime + 2) > ((DateTimeOffset)DateTime.Now).ToUnixTimeSeconds()) { if (indata.Length >= 8) break; } byte[] asciiBytes = Encoding.GetEncoding(1251).GetBytes(indata); if (CRC.CRC_calc_check(asciiBytes) == (asciiBytes[asciiBytes.Length - 1] * 256 + asciiBytes[asciiBytes.Length - 2])) return asciiBytes[5]; } return -1; } // функция события получения данных из порта public void DataReceivedHandler( object sender, SerialDataReceivedEventArgs e) { SerialPort sp = (SerialPort)sender; indata = indata+(sp.ReadExisting()); } } }
737631d9e277d7a37938ae5933035f09a6fca565
C#
Kostyancapral/Quest
/1.1/6 taxi/6 taxi/Program.cs
3.34375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _6_taxi { class Program { static void Main(string[] args) { int km, min,price; Console.WriteLine("какой километраж нужно преодолеть"); km = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("сколько минут простоя"); min = Convert.ToInt32(Console.ReadLine()); price = 20; if (km > 5) { price += (km - 5) * 3; } price += min; Console.WriteLine("Итого цена будет равна "+price+" гривен"); Console.ReadLine(); } } }
7d0fda2087f966b33e7524c24009acf1f0594556
C#
cholodev/asaf
/Asaf/Projects/Core/Ioc/IocManager.cs
2.625
3
using System; using System.IO; using System.Linq; using System.Reflection; namespace Core { public class IocManager { private const string LogFolderName = "Logs"; //burası ihtiyaç halinde bir ayara bağlanabilir. şimdilik bu şekilde kalsın. private static readonly string BinFolder = Path.GetDirectoryName(Uri.UnescapeDataString(new UriBuilder(Assembly.GetExecutingAssembly().GetName().CodeBase).Path)) ?? Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "bin"); private static Assembly[] LoadAssemblies() { string[] dlls; try { dlls = Directory.GetFiles(BinFolder, "*.dll"); } catch (Exception) { dlls = new string[0]; } return dlls.Select(Assembly.LoadFrom).ToArray(); } private static Assembly[] _assemblies; public static Assembly[] Assemblies { get { return _assemblies ?? (_assemblies = LoadAssemblies()); } } } }
be6f524ac80c47a7e5d74bf93cdbc9b4ef2c3aaa
C#
bilalalptekin/homeworks
/Bilal-Alptekin/131730026_Bilal-Alptekin/Form1.cs
2.625
3
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 _131730026_Bilal_Alptekin { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { } private void button3_Click(object sender, EventArgs e) { double sayi1 = Convert.ToInt32(tbxSayı1.Text); double sayi2 = Convert.ToInt32(tbxSayi2.Text); double sonuc = sayi1 * sayi2; lblSonuc.Text = $"Sonuç: {sonuc}"; } private void button1_Click(object sender, EventArgs e) { String gelendeger = comboBox1.Text; double sayi1 = Convert.ToInt32(tbxSayı1.Text); double sayi2 = Convert.ToInt32(tbxSayi2.Text); double sonuc; if (gelendeger=="Topla") { sonuc=sayi1 + sayi2; lblSonuc.Text = $"Sonuç: {sonuc}"; } else if(gelendeger=="Çıkar") { sonuc = sayi1 - sayi2; lblSonuc.Text = $"Sonuç: {sonuc}"; } else if (gelendeger == "Çarp") { sonuc = sayi1 * sayi2; lblSonuc.Text = $"Sonuç: {sonuc}"; } else if (gelendeger == "Böl") { sonuc = sayi1 / sayi2; lblSonuc.Text = $"Sonuç: {sonuc}"; } } private void btnTopla_Click(object sender, EventArgs e) { double sayi1 = Convert.ToInt32(tbxSayı1.Text); double sayi2 = Convert.ToInt32(tbxSayi2.Text); double sonuc = sayi1 + sayi2; lblSonuc.Text = $"Sonuç: {sonuc}"; } private void btnCikart_Click(object sender, EventArgs e) { double sayi1 = Convert.ToInt32(tbxSayı1.Text); double sayi2 = Convert.ToInt32(tbxSayi2.Text); double sonuc = sayi1 - sayi2; lblSonuc.Text = $"Sonuç: {sonuc}"; } private void btnBol_Click(object sender, EventArgs e) { double sayi1 = Convert.ToInt32(tbxSayı1.Text); double sayi2 = Convert.ToInt32(tbxSayi2.Text); double sonuc = sayi1 / sayi2; lblSonuc.Text = $"Sonuç: {sonuc}"; } } }
92022681d9529c23332c7c055837aaeeb1b5cc72
C#
bgroupru86/AskQ-Final
/ASKQ/Controllers/RealTimeQuestionController.cs
2.5625
3
using ASKQ.Models; using System; using System.Collections.Generic; using System.Web.Http; namespace ASKQ.Controllers { public class RealTimeQuestionController : ApiController { [HttpPost] [Route("api/RealTimeQuestion/post")] public void Post([FromBody]RealTimeQuestion q) { try { q.insert(); } catch (Exception ex) { throw new Exception("Error in insert" + ex); } } [HttpGet] [Route("api/RealTimeQuestion/get")] public IEnumerable<RealTimeQuestion> Get(int lessonCode) { RealTimeQuestion q = new RealTimeQuestion(); List<RealTimeQuestion> ql = q.ReadList(lessonCode); return ql; } [HttpPut] [Route("api/RealTimeQuestion/put")] public void PostUpdates(int Qid , string field) { RealTimeQuestion r= new RealTimeQuestion(); r.UpdateQuestion(Qid, field); } [HttpGet] [Route("api/RealTimeQuestion")] public RealTimeQuestion forYesNoQuestion(int id) { RealTimeQuestion r = new RealTimeQuestion(); return r.forYesNoQuestion(id); } } }
6fd844b3e545d4872afff218f8938ff3b75e8241
C#
tolosaadam/PracticaCSharp
/UsandoPropiedades/UsandoPropiedades/Program.cs
3.296875
3
using System; namespace UsandoPropiedades { class Program { static void Main(string[] args) { Empleado empleado1 = new Empleado("Adam"); empleado1.SALARIO = 1200; Console.WriteLine($"El salario del empleado1 es: {empleado1.SALARIO}"); empleado1.SALARIO += 500; Console.WriteLine($"El salario del empleado1 actualizado es: {empleado1.SALARIO}"); Empleado empleado2 = new Empleado("Enano"); empleado2.SALARIO = 400; Console.WriteLine($"El salario del empleado2 es: {empleado2.SALARIO}"); empleado2.SALARIO -= 1000; Console.WriteLine($"El salario del empleado2 actualizado es: {empleado2.SALARIO}"); /* Ver como aunque le reste de mas * nunca me devuelve un negativo * porque asi lo especifique en * el metodo */ } } class Empleado { public Empleado(String nombre) //CONSTRUCTOR { this.nombre = nombre; } public double evaluaSalario(double salario) { if (salario < 0) return 0; else return salario; } //DECLARANDO UNA PROPIEDAD, SIEMPRE EL NOMBRE EN MAYUSCULA public double SALARIO { get => this.salario; set => this.salario = evaluaSalario(value); } private double salario { get; set; } //CAMPOS DE CLASE private string nombre { get; set; } } }
4e2a3ae4b48852423631ea083968dc0ecd546c17
C#
grae22/Dorothy
/ui/SelectItemDlg.cs
2.78125
3
using System; using System.Windows.Forms; using System.Collections.Generic; using Dorothy.Data; namespace Dorothy.UI { public partial class SelectItemDlg : Form { //------------------------------------------------------------------------- private List<Item> _items; //------------------------------------------------------------------------- public SelectItemDlg( List<Item> items, List<Item> selectedItems, bool multiSelect, string title ) { InitializeComponent(); _items = items; Text = title; uiItems.SelectionMode = ( multiSelect ? SelectionMode.MultiExtended : SelectionMode.One ); PopulateItemsList(); foreach( Item item in selectedItems ) { if( uiItems.Items.Contains( item ) ) { uiItems.SelectedItems.Add( item ); } } } //------------------------------------------------------------------------- public Item FirstSelectedItem { get { return uiItems.SelectedItem as Item; } } //------------------------------------------------------------------------- private void uiOK_Click( object sender, EventArgs e ) { DialogResult = DialogResult.OK; Close(); } //------------------------------------------------------------------------- private void uiFilter_TextChanged( object sender, EventArgs e ) { PopulateItemsList(); } //------------------------------------------------------------------------- private void PopulateItemsList() { uiItems.Items.Clear(); string filter = uiFilter.Text.ToLower(); foreach( Item item in _items ) { if( filter.Length == 0 || item.ToString().ToLower().Contains( filter ) ) { uiItems.Items.Add( item ); } } } //------------------------------------------------------------------------- } }
0f4a9ce6db56451b0723fe7987970f727d848476
C#
shendongnian/download4
/code10/1728827-50066705-172252222-2.cs
2.75
3
public IActionResult Cheese(string firstName, string lastName) { @ViewData["Data"]=$"Hello, {firstName ?? "Dr."} {lastName ?? "Cheeseburger"}"; return View(); }
b508dbecc30b4de8f672a856e6ba7a535506b110
C#
jnm2/ApiContractGenerator
/src/ApiContractGenerator.Tests/Internal/StringSpanTests.cs
2.578125
3
using ApiContractGenerator.Internal; using NUnit.Framework; namespace ApiContractGenerator.Tests.Internal { public static class StringSpanTests { [Test] public static void IndexOf_applies_offset_to_return([Range(0, 5)] int beforeSlice) { var span = (new string('.', beforeSlice) + '!').Slice(beforeSlice); Assert.That(span.IndexOf('!'), Is.EqualTo(0)); } [Test] public static void LastIndexOf_applies_offset_to_return([Range(0, 5)] int beforeSlice) { var span = (new string('.', beforeSlice) + '!').Slice(beforeSlice); Assert.That(span.LastIndexOf('!'), Is.EqualTo(0)); } } }
3864d0e5847a27dbc6b0c0cd45c32fdb718aff44
C#
Coldani3/liskov-custom
/Program.cs
4.03125
4
using System; namespace liskovcustom { class Program { static void Main(string[] args) { Animal animal1 = new Animal(); Animal animal2 = new Dog(); //error version, mammoth returns different sort of value for .Alive() than the base //yes the other animals do something different for making noise but if they all did the exact same thing there'd //be no point to extending the first class in the first place and nothing to demonstrate LSP with //################################ //Animal animal3 = new Mammoth(); //success version Animal animal3 = new Cat(); if (animal1.Alive() && animal2.Alive() && animal3.Alive()) { DoTheThing(animal1); DoTheThing(animal2); DoTheThing(animal3); Console.WriteLine("followed liskov"); } else { Console.WriteLine("logic flow break, your program would crash"); throw new Exception("logic break"); } } public static void DoTheThing(Animal animal) { animal.MakeNoise(); } } }
72078932230b0946e3581362e0fcc2490ea330f6
C#
Mapasich/C_SharpLessons
/entity-framework-5-Oleg-Kulygin/002_EDM/002_EDM/007_Delete/Form1.cs
2.796875
3
using System; using System.Data.Entity; using System.Windows.Forms; namespace _007_Delete { public partial class Form1 : Form { readonly AWEntities context; public Form1() { InitializeComponent(); context = new AWEntities(); } private void Form1_Load(object sender, EventArgs e) { context.Customer.Load(); UpdateDataGridView(); } private void deleteButton_Click(object sender, EventArgs e) { var customer = dataGridView1.SelectedRows[0].DataBoundItem as Customer; context.Customer.Remove(customer); context.SaveChanges(); } private void UpdateDataGridView() { dataGridView1.DataSource = context.Customer.Local.ToBindingList(); } } }
7b7a1d86df21b4c7b771f2266df03d5557d805b4
C#
letsmedialab/Academy-CRM
/AcademyCRM.DAL.EF/Contexts/ModelBuilderExtensions.cs
2.875
3
using AcademyCRM.Core.Models; using Microsoft.EntityFrameworkCore; namespace AcademyCRM.DAL.EF.Contexts { public static class ModelBuilderExtensions { public static void Seed(this ModelBuilder modelBuilder) { var topic1 = new Topic() { Id = 1, Title = ".Net", Description = ".Net (ASP.NET, Unity)" }; var topic2 = new Topic() { Id = 2, Title = "Java", Description = "Full-stack, JS, Spring" }; modelBuilder.Entity<Topic>().HasData(topic1, topic2); var course1 = new Course() { Id = 10, Title = "Introduction to C#", Description = "Introduction to C#", Program = "1. Getting Started", TopicId = 1, Price = 1250, Level = CourseLevel.Beginner, DurationWeeks = 8 }; var course2 = new Course() { Id = 11, Title = "Introduction to Java", Description = "Introduction to Java", Program = "1. Getting Started", TopicId = 2, Price = 1550, Level = CourseLevel.Beginner, DurationWeeks = 7 }; var course3 = new Course() { Id = 12, Title = "ASP.NET", Description = "Web with ASP.NET", Program = "1. Controllers and MVC", TopicId = 1, Price = 1350, Level = CourseLevel.Advanced, DurationWeeks = 16 }; var course4 = new Course() { Id = 13, Title = "Unity", Description = "Unity Game Development", Program = "1. What is Unity", TopicId = 1, Price = 1850, Level = CourseLevel.Advanced, DurationWeeks = 20 }; var course5 = new Course() { Id = 15, Title = "Design Patterns", Description = "Design Patterns for Software development", Program = "1. Decorator, 2. Bridge", TopicId = 1, Price = 2850, Level = CourseLevel.Expert, DurationWeeks = 18 }; modelBuilder.Entity<Course>().HasData(course1, course2, course3, course4, course5); var teacher1 = new Teacher() { Id = 1, FirstName = "Vadim", LastName = "Korotkov", LinkToProfile = "https://www.linkedin.com/feed/" }; var teacher2 = new Teacher() { Id = 2, FirstName = "Sergey", LastName = "Gromov", LinkToProfile = "https://www.linkedin.com/feed/" }; modelBuilder.Entity<Teacher>().HasData(teacher1, teacher2); var group1 = new StudentGroup() { Id = 1, Title = "ASPNET_21_1", TeacherId = teacher1.Id, CourseId = course1.Id }; var group2 = new StudentGroup() { Id = 2, Title = "Java_23_4", TeacherId = teacher1.Id, CourseId = course2.Id }; modelBuilder.Entity<StudentGroup>().HasData(group1, group2); modelBuilder.Entity<Student>().HasData( new Student { Id = 1, FirstName = "Oleg", LastName = "Fedorov" }, new Student() { Id = 2, FirstName = "Andrey", LastName = "Antonov" }, new Student() { Id = 3, FirstName = "Ivan", LastName = "Petrov" }, new Student() { Id = 4, FirstName = "Sergey", LastName = "Ivashko" } ); } } }
2815a9bc26ce99f83aeeaada23bcc9c28fe35e2a
C#
lovebirdsx/TestCSharp
/csx/Parabola.csx
3.046875
3
float y0 = 1; float y1 = 4; float y2 = 0; float t = 2; void CalAccAndVec(float y0, float y1, float y2, float t, out float a, out float v) { float t1 = t / ((float)Math.Sqrt((y2 - y1) / (y0 - y1)) + 1); a = -(2 * (y1 - y0)) / (t1 * t1); v = -a * t1; } float a; float v; CalAccAndVec(y0, y1, y2, t, out a, out v); for (int i = 0; i < 21; i++) { float dt = (t / 20) *i; Console.WriteLine(Math.Round(y0 + v * dt + 0.5 * a * dt * dt, 2)); }
be34702ee95043f8486bfc759c6459f538e5ff44
C#
210503-Reston-NET/Lateu-Richard-P1
/StoreWebUI/Models/ItemVM.cs
2.734375
3
using StoreModels; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace StoreWebUI.Models { public class ItemVM { public int Id{ get; set; } public double UnitPrice { get; set; } public int ProductId { get; set; } public int Quantity { get; set; } public int OrderId { get; set; } public ItemVM() { } public ItemVM(int orderid, List<Product> l) { this.OrderId = orderid;this.Products = l; } public IEnumerable<Product> Products { set; get; } public ItemVM(Item item) { this.Id = item.Id; this.ProductId = item.ProductId; this.Quantity = item.Quantity; this.UnitPrice = item.UnitPrice; } public override string ToString() { return $"Id:{Id} Product:{ProductId}"; } } }
4c433e4b4006f2083756a39efb86b175890d8f7b
C#
devin5885/CodingProblems
/CodingProblems/String_/Permutations/GetPermutations1NoDuplicatesByCharCompleteTests.cs
3.34375
3
using System; using System.Collections.Generic; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace CodingProblems.String_.Permutations { /// <summary> /// Tests GetPermutations /// </summary> [TestClass] public class GetPermutations1NoDuplicatesByCharCompleteTests { /// <summary> /// Test null string. /// </summary> [TestMethod] public void GetPermutations1NoDuplicatesByCharCompleteTestsTestNullString() { var expected = new List<string>(); var actual = GetPermutations1NoDuplicatesByCharComplete.GetPermutations(null); CollectionAssert.AreEqual(expected, actual); } /// <summary> /// Test empty string. /// </summary> [TestMethod] public void GetPermutations1NoDuplicatesByCharCompleteTestsTestEmptyString() { var expected = new List<string>(); var str = string.Empty; var actual = GetPermutations1NoDuplicatesByCharComplete.GetPermutations(str); CollectionAssert.AreEqual(expected, actual); } /// <summary> /// Test single char string. /// </summary> [TestMethod] public void GetPermutations1NoDuplicatesByCharCompleteTestsTest1Char() { var expected = new List<string> { "a" }; const string str = "a"; var actual = GetPermutations1NoDuplicatesByCharComplete.GetPermutations(str); CollectionAssert.AreEqual(expected, actual); } /// <summary> /// Test 2 char string. /// </summary> [TestMethod] public void GetPermutations1NoDuplicatesByCharCompleteTestsTest2Char() { var expected = new List<string> { "ab", "ba" }; const string str = "ab"; var actual = GetPermutations1NoDuplicatesByCharComplete.GetPermutations(str); // Sort the list so it will always match expected. // The algorithm itself doesn't guarantee any particular order. actual.Sort(); CollectionAssert.AreEqual(expected, actual); } /// <summary> /// Test 3 char string. /// Result 6 perms 3! /// </summary> [TestMethod] public void GetPermutations1NoDuplicatesByCharCompleteTestsTest3Char() { var expected = new List<string> { "abc", "acb", "bac", "bca", "cab", "cba" }; const string str = "abc"; var actual = GetPermutations1NoDuplicatesByCharComplete.GetPermutations(str); // Sort the list so it will always match expected. // The algorithm itself doesn't guarantee any particular order. actual.Sort(); CollectionAssert.AreEqual(expected, actual); } /// <summary> /// Test 4 char string no duplicates. /// Result 24 perms 4! /// </summary> [TestMethod] public void GetPermutations1NoDuplicatesByCharCompleteTestsTest4Char() { var expected = new List<string> { @"abcd", @"abdc", @"acbd", @"acdb", @"adbc", @"adcb", @"bacd", @"badc", @"bcad", @"bcda", @"bdac", @"bdca", @"cabd", @"cadb", @"cbad", @"cbda", @"cdab", @"cdba", @"dabc", @"dacb", @"dbac", @"dbca", @"dcab", @"dcba" }; const string str = @"abcd"; var actual = GetPermutations1NoDuplicatesByCharComplete.GetPermutations(str); // Sort the list so it will always match expected. // The algorithm itself doesn't guarantee any particular order. actual.Sort(); CollectionAssert.AreEqual(expected, actual); } } }
df349486daab4ec19b6097a003fb58800b20b8e2
C#
KilmornaKid/CinemaSYS
/SD_CinemaSYS_Stack_Kirean/CinemaSYS/CinemaSYS/frmScheduleScreening.cs
2.578125
3
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 CinemaSYS { public partial class frmScheduleScreening : Form { Screening myScreening = new Screening(); public frmScheduleScreening() { InitializeComponent(); } private void frmScheduleScreening_Load(object sender, EventArgs e) { txtScreeningNumber.Text = Screening.nextScreening_Number().ToString("00"); dtpDateFrom.MinDate = DateTime.Today; String theDate = dtpDateFrom.Value.ToShortDateString(); dtpDateFrom.Format = DateTimePickerFormat.Custom; dtpDateFrom.CustomFormat = "dd-MM-yy"; String theDate2 = dtpDateTo.Value.ToShortDateString(); dtpDateTo.Format = DateTimePickerFormat.Custom; dtpDateTo.CustomFormat = "dd-MM-yy"; loadComboTimes(); loadComboScreen(); loadComboMovie(); } public void loadComboMovie() { // create instance of data set DataSet ds = new DataSet(); ds = Movie.getAllMovies(ds); //Remove existing items from combo box cboMovieId.Items.Clear(); //load data from ds to cboMovie for (int i = 0; i < ds.Tables["gam"].Rows.Count; i++) cboMovieId.Items.Add(ds.Tables[0].Rows[i][0].ToString().PadLeft(1, '0') + " " + ds.Tables[0].Rows[i][1].ToString()); cboMovieId.SelectedIndex = -1; } public void loadComboScreen() { DataSet ds = new DataSet(); ds = Screen.getAllAvailableScreens(ds); cboScreenNo.Items.Clear(); for (int i = 0; i < ds.Tables["gaas"].Rows.Count; i++) cboScreenNo.Items.Add("Screen".ToString() + " " + ds.Tables[0].Rows[i][0].ToString().PadLeft(2, '0')); cboScreenNo.SelectedIndex = -1; } public void loadComboTimes() { DataSet ds = new DataSet(); ds = ScreeningTimes.getAllScreeningTimes(ds); cboTimes.Items.Clear(); for (int i = 0; i < ds.Tables["gasct"].Rows.Count; i++) cboTimes.Items.Add(ds.Tables[0].Rows[i][0].ToString()+ ". "+ds.Tables[0].Rows[i][1].ToString()); cboTimes.SelectedIndex = -1; } private void btnScheduleScreening_Click(object sender, EventArgs e) { if (dtpDateTo.Value < dtpDateFrom.Value) { MessageBox.Show("Date To must be later than Date From", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error); dtpDateTo.Focus(); return; } if (cboScreenNo.SelectedIndex == -1) { MessageBox.Show("Please select an screen! ", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (cboTimes.SelectedIndex == -1) { MessageBox.Show("Please select a Time! ", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (cboMovieId.SelectedIndex == -1) { MessageBox.Show("Please select a movie! ", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } string time = cboTimes.Text.Substring(3, 5); string fromDate = dtpDateFrom.Value.ToShortDateString(); string toDate = dtpDateTo.Value.ToShortDateString(); if (Screening.isTimeBooked(time,cboScreenNo.Text.Substring(8, 2), fromDate, toDate) == true) { MessageBox.Show("This time for this screen is already booked!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } myScreening = new Screening(); myScreening.setScreeningNumber(Convert.ToInt32(txtScreeningNumber.Text)); myScreening.setDateFrom(Convert.ToDateTime(dtpDateFrom.Text)); myScreening.setDateTo(Convert.ToDateTime(dtpDateTo.Text)); myScreening.setTime(Convert.ToInt32(cboTimes.Text.Substring(0, 1))); myScreening.setSeatsAvailable(Convert.ToInt32(txtMaxSeats.Text)); myScreening.setMaxSeats(Convert.ToInt32(txtMaxSeats.Text)); myScreening.setScreenNo(Convert.ToInt32(cboScreenNo.Text.Substring(8, 2))); myScreening.setMovieId(Convert.ToInt32(cboMovieId.Text.Substring(0,1))); myScreening.regScreening(); //Display Confirmation Message MessageBox.Show("Screening " + txtScreeningNumber.Text + " Updated", "Confirmation", MessageBoxButtons.OK, MessageBoxIcon.Information); txtScreeningNumber.Text = Screening.nextScreening_Number().ToString("00"); dtpDateFrom.ResetText(); dtpDateTo.ResetText(); txtMaxSeats.ResetText(); txtseatsAvailable.ResetText(); loadComboScreen(); loadComboMovie(); loadComboTimes(); } private void cboScreenNo_SelectedIndexChanged(object sender, EventArgs e) { if (Screen.isAvailable(cboScreenNo.Text.Substring(8, 2)) == false) { MessageBox.Show("Cannot use screen as it is currently blocked"); loadComboScreen(); return; } Screen myScreen = new Screen(); myScreen.getScreen(Convert.ToInt32(cboScreenNo.Text.Substring(8, 2))); txtMaxSeats.Text = Convert.ToString(myScreen.getNumberOfSeats().ToString()); txtseatsAvailable.Text = Convert.ToString(myScreen.getNumberOfSeats().ToString()); } } }
033e1ca10c2d98607406bca7875e295367648903
C#
Kristen-Jaan/LOGITpe20-Week6Task
/Week6Task3/Program.cs
3.515625
4
using System; using System.Reflection.PortableExecutable; namespace Week6Task3 { class Program { static void Main(string[] args) { Console.WriteLine("Good Morning!"); Random rnd = new Random(); int[] array = new int[10]; for(int i = 0; i < array.Length; i++) { array[i] = rnd.Next(1, 11); } foreach(int num in array) { Console.WriteLine(num); } int min = array[0]; int max = array[0]; for(int i = 0; i < array.Length; i++) { if(min > array[i]) { min = array[i]; } if(max < array[i]) { max = array[i]; } } Console.WriteLine($"Max: {max}"); Console.WriteLine($"Min: {min}"); } } }
6c8fa2f014a2282e7cd4ac246105caddd8a4724e
C#
VelluVu/Backend_Exercises
/ASsignment2/Program.cs
2.953125
3
using System; using System.Collections.Generic; using System.Threading.Tasks; using System.Linq; namespace ASsignment2 { class Program { static void Main ( string [ ] args ) { List<IPlayer> players = new List<IPlayer> ( ); List<IPlayer> PlayerForAnotherGames = new List<IPlayer> ( ); Game<IPlayer> game1 = new Game<IPlayer> ( players ); Game<IPlayer> game2 = new Game<IPlayer> ( PlayerForAnotherGames ); var array1 = game1.GetTop10Players ( ); var array2 = game2.GetTop10Players ( ); for ( int i = 0 ; i < array1.Length ; i++ ) { Console.WriteLine ( array1 [ i ] ); } for ( int i = 0 ; i < array2.Length ; i++ ) { Console.WriteLine ( array2 [ i ] ); } ProcessEachItem ( (Player)players [ 0 ], PrintMessage ); ProcessEachItem ( (Player)players [ 0 ], item => Console.WriteLine ( item.Id + " " + item.Level ) ); } public static void PrintMessage ( Item item ) { Console.WriteLine ( item.Id + ", " + item.Level ); } public static void ProcessEachItem ( Player player, Action<Item> process ) { //if ( player.Items == null ) //{ //} //else //{ // foreach ( var item in player.Items ) // { // process ( item ); // } //} player.Items.ForEach ( item => process ( item ) ); } } }
f643184bf2eb47b6c3f6e4c88fab740b713bb2f1
C#
cysun/CS4540X19-CSharp
/LINQExamples/Company.cs
3.40625
3
using System; using System.Collections.Generic; using System.Text; namespace LINQExamples { public class Employee { public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public DateTime DateHired { get; set; } public int? SupervisorId { get; set; } public Employee() { } public Employee(int id, string firstName, string lastName, DateTime dateHired, int? supervisorId = null) { Id = id; FirstName = firstName; LastName = lastName; DateHired = dateHired; SupervisorId = supervisorId; } public override string ToString() { return $"{Id}, {FirstName} {LastName}, {DateHired:d}, {SupervisorId}"; } } public class Project { public int Id { get; set; } public string Name { get; set; } public Employee Leader { get; set; } public List<Employee> Members { get; set; } public Project() { Members = new List<Employee>(); } public Project(int id, string name) : this() { Id = id; Name = name; } public override string ToString() { return $"{Id} {Name}"; } } public class Company { public List<Employee> Employees { get; set; } public List<Project> Projects { get; set; } public Company() { var john = new Employee(1, "John", "Doe", new DateTime(2015, 1, 10)); var jane = new Employee(2, "Jane", "Doe", new DateTime(2015, 2, 20), 1); var tom = new Employee(3, "Tom", "Smith", new DateTime(2016, 6, 19), 2); var bob = new Employee(4, "Bob", "Lee", new DateTime(2016, 6, 20), 2); Employees = new List<Employee>(); Employees.Add(john); Employees.Add(jane); Employees.Add(tom); Employees.Add(bob); var firestone = new Project(1, "Firestone") { Leader = john, Members = new List<Employee> { john } }; var blue = new Project(2, "Blue") { Leader = jane, Members = new List<Employee> { john, jane } }; Projects = new List<Project>(); Projects.Add(firestone); Projects.Add(blue); } } }
13e59c6e7e4415f337b95d01a0966f27af3f16b4
C#
AndreOikawa/Projects
/Side Projects/Sorting Algo/Sorting Algo/Program.cs
3.390625
3
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using Sorting_Algo.Algorithms; namespace Sorting_Algo { class Program { static void Main(string[] args) { List<Algorithm> algorithms = new List<Algorithm>(); algorithms.Add(new BubbleSort()); algorithms.Add(new SelectionSort()); //algorithms.Add(new MergeSort()); algorithms.Add(new InsertionSort()); //algorithms.Add(new HeapSort()); //algorithms.Add(new RadixSort()); //algorithms.Add(new QuickSort()); algorithms.Add(new PushSort()); //algorithms.Add(new BogoSort()); List<int> array = new List<int>(); int max = 100; for (int i = 1; i <= max; i++) { array.Add(i); } Stopwatch timer = new Stopwatch(); Console.WriteLine($"Sorted List:"); foreach (var algorithm in algorithms) { timer.Start(); Console.WriteLine($"{algorithm.Name()}: {algorithm.Sort(new List<int>(array))}"); timer.Stop(); //Console.WriteLine(timer.ElapsedMilliseconds); timer.Reset(); } List<int> almostSorted = new List<int>(array); int temp = almostSorted[0]; almostSorted[0] = almostSorted[almostSorted.Count - 1]; almostSorted[almostSorted.Count - 1] = temp; Console.WriteLine(); Console.WriteLine($"Almost sorted List:"); foreach (var algorithm in algorithms) { timer.Start(); Console.WriteLine($"{algorithm.Name()}: {algorithm.Sort(new List<int>(almostSorted))}"); timer.Stop(); //Console.WriteLine(timer.ElapsedMilliseconds); timer.Reset(); } array.Reverse(); Console.WriteLine(); Console.WriteLine($"Reversed List:"); foreach (var algorithm in algorithms) { timer.Start(); Console.WriteLine($"{algorithm.Name()}: {algorithm.Sort(new List<int>(array))}"); timer.Stop(); //Console.WriteLine(timer.ElapsedMilliseconds); timer.Reset(); } var random = array.OrderBy(a => Guid.NewGuid()).ToList(); Console.WriteLine(); Console.WriteLine($"Random List:"); foreach (var algorithm in algorithms) { timer.Start(); Console.WriteLine($"{algorithm.Name()}: {algorithm.Sort(new List<int>(array))}"); timer.Stop(); //Console.WriteLine(timer.ElapsedMilliseconds); timer.Reset(); } Console.ReadKey(); } } }
378571227e661df270624d0617531ba72208549b
C#
liangliang-wang/WidgetDemo
/CommonTools/FrameWork/DynamicBuilderEntity.cs
2.515625
3
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Text; using System.Threading.Tasks; namespace CommonTools.FrameWork { /// <summary> /// 动态创建实体 /// </summary> /// <typeparam name="T"></typeparam> public class DynamicBuilderEntity<T> { private static readonly MethodInfo getValueMethod = typeof(IDataRecord).GetMethod("get_Item", new[] { typeof(int) }); private static readonly MethodInfo isDBNullMethod = typeof(IDataRecord).GetMethod("IsDBNull", new[] { typeof(int) }); private delegate T Load(IDataRecord dataRecord); private Load handler; private DynamicBuilderEntity() { } /// <summary> /// /// </summary> /// <param name="dataRecord"></param> /// <returns></returns> public T Build(IDataRecord dataRecord) { return handler(dataRecord); } /// <summary> /// 建立过程 /// </summary> /// <param name="dataRecord">取数据流字段</param> /// <returns></returns> public static DynamicBuilderEntity<T> CreateBuilder(IDataRecord dataRecord) { var dynamicBuilder = new DynamicBuilderEntity<T>(); var method = new DynamicMethod("DynamicCreateEntity", typeof(T), new[] { typeof(IDataRecord) }, typeof(T), true); ILGenerator generator = method.GetILGenerator(); LocalBuilder result = generator.DeclareLocal(typeof(T)); generator.Emit(OpCodes.Newobj, typeof(T).GetConstructor(Type.EmptyTypes)); generator.Emit(OpCodes.Stloc, result); for (int i = 0; i < dataRecord.FieldCount; i++) { var propertyInfo = typeof(T).GetProperty(dataRecord.GetName(i)); if (propertyInfo == null) { continue; } var endIfLabel = generator.DefineLabel(); if (propertyInfo.GetSetMethod() == null) continue; generator.Emit(OpCodes.Ldarg_0); generator.Emit(OpCodes.Ldc_I4, i); generator.Emit(OpCodes.Callvirt, isDBNullMethod); generator.Emit(OpCodes.Brtrue, endIfLabel); generator.Emit(OpCodes.Ldloc, result); generator.Emit(OpCodes.Ldarg_0); generator.Emit(OpCodes.Ldc_I4, i); generator.Emit(OpCodes.Callvirt, getValueMethod); generator.Emit(OpCodes.Unbox_Any, dataRecord.GetFieldType(i)); generator.Emit(OpCodes.Callvirt, propertyInfo.GetSetMethod()); generator.MarkLabel(endIfLabel); } generator.Emit(OpCodes.Ldloc, result); generator.Emit(OpCodes.Ret); dynamicBuilder.handler = (Load)method.CreateDelegate(typeof(Load)); return dynamicBuilder; } } }
1b866807083db47f30c0d8b263f2896375314b81
C#
DDollerup/DecisionMaking
/DecisionMaking/Controllers/HomeController.cs
2.765625
3
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace DecisionMaking.Controllers { public class HomeController : Controller { private int tal1 = 9; private int tal2 = 30; // GET: Home public ActionResult Index() { string resultat = ""; // Spørger, er tal1 + tal2 mellem 40 og 60 if (tal1 + tal2 >= 40 && tal1 + tal2 <= 60) { resultat = "Tallet er mellem 40 og 60 : " + (tal1 + tal2); } else if (tal1 + tal2 > 60) { resultat = "Tallet er større end 60 : " + (tal1 + tal2); } else { resultat = "Tallet er mindre end 40 : " + (tal1 + tal2); } ViewBag.Resultat = resultat; return View(); } } }
6c27f14518c670a85f40100f86372fd6d919eb95
C#
llenroc/XamUBot
/src/Dialogs/Features/TeamDialog.cs
2.625
3
using System; using System.Threading.Tasks; using Microsoft.Bot.Builder.Dialogs; using Microsoft.Bot.Connector; using XamUApi; using System.Collections.Generic; using System.Linq; using QnAMakerDialog; using System.Threading; namespace XamUBot.Dialogs { /// <summary> /// Allows querying the XamU team. /// Uses LUIS to get user's intent. /// </summary> [Serializable] public class TeamDialog : BaseDialog { IList<TeamResponse> _teamList; protected async override Task OnInitializeAsync(IDialogContext context) { await context.PostAsync(ResponseUtterances.GetResponse(ResponseUtterances.ReplyTypes.TeamWelcome)); _teamList = await ApiManagerFactory.Instance.GetTeamAsync(); WaitForNextMessage(context); } protected async override Task OnHelpReceivedAsync(IDialogContext context, Activity activity) { await context.PostAsync(ResponseUtterances.GetResponse(ResponseUtterances.ReplyTypes.TeamHelp)); WaitForNextMessage(context); } protected async override Task OnMessageReceivedAsync(IDialogContext context, Activity activity) { var result = await LuisHelper.PredictLuisAsync(activity.Text, LuisConstants.IntentPrefix_Team); if (result?.TopScoringIntent == null) { // Check Q&A if we don't have an answer from LUIS. This will forward to the Q&A dialog and make it // return immediately. await CheckFaqAsync(context, activity); return; } // We have an answer from LUIS! var reply = activity.CreateReply(); // Presort list. IEnumerable<TeamResponse> teamMembers = _teamList .OrderBy(m => m.Name); switch (result.TopScoringIntent.Name) { case LuisConstants.Intent_GetSpecialist: // The intent contains the technology the user is looking for. var technologyEntity = result.GetBestMatchingEntity(LuisConstants.Entity_Technology); if(technologyEntity == null) { await context.PostAsync("You seem to be looking for a specialist for some techonology but unfortunately I don't know an answer."); return; } await context.PostAsync($"Let me find some team members who know about '{technologyEntity.Name}'"); teamMembers = teamMembers .Where(m => m.Description.ToLowerInvariant().Contains(technologyEntity.Name.ToLowerInvariant()) || m.Title.ToLowerInvariant().Contains(technologyEntity.Name.ToLowerInvariant())); break; case LuisConstants.Intent_ShowTeamMember: // The intent contains the person the user is looking for. var personEntity = result.GetBestMatchingEntity(LuisConstants.Entity_Trainer); if (personEntity == null) { await context.PostAsync("You seem to be looking for a person but unfortunately I don't know an answer."); return; } await context.PostAsync($"I'm looking for team members named '{personEntity.Name}'"); teamMembers = teamMembers .Where(m => m.Name.ToLowerInvariant().Contains(personEntity.Name.ToLowerInvariant()) || m.Email.ToLowerInvariant().Contains(personEntity.Name.ToLowerInvariant())); break; case LuisConstants.Intent_ShowEntireTeam: // No further filtering. await context.PostAsync("Here's the entire team!"); break; } var finalMembers = teamMembers.ToList(); if (finalMembers.Count > 0) { foreach (var person in finalMembers) { reply.AttachHeroCard(person.Name, person.Description, person.HeadshotUrl, person.ShortDescription, new Tuple<string, string>[] { new Tuple<string, string>("Twitter", person.TwitterHandle), new Tuple<string, string>("Email", person.Email) }); } if (finalMembers.Count > 1) { reply.AttachmentLayout = "carousel"; } } else { reply.AttachHeroCard( "Hello, is it me you're looking for?", "Sorry, I couldn't find who you were looking for. Are you looking for a team member? Just tell me the name of the team member or provide any other keyword.", @"http://i.imgur.com/QsIsjo8.jpg"); } await context.PostAsync(reply); ShowYesNoPicker(context, OnAfterAnythingElse, "Anything else you'd like to know about the team?"); } async Task OnAfterAnythingElse(IDialogContext context, IAwaitable<string> result) { var answer = await result.GetValueAsync<string>(); if(answer == BaseDialog.ChoiceYes) { await context.PostAsync("Ok - what else would you like to know about the team?"); } else { PopDialog(context); } } } }
cf19b6303a262824af3c6532ba0c6e08c5be8419
C#
vudoan1708-cyber/Online_Diary
/DailyDiary/Pages/DiaryContent/AddedContent.cshtml.cs
2.609375
3
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using DailyDiary.Model; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.AspNetCore.Razor.Language; using Microsoft.EntityFrameworkCore; namespace DailyDiary.Pages.DiaryContent { public class AddedContentModel : PageModel { // Dependency Injection private readonly ApplicationDbContext _db; // Contructor public AddedContentModel(ApplicationDbContext db) { _db = db; } public Diary AddedDiary { get; set; } public async Task OnGet(int id) { // Check the variable type from the passing parameter Type t = id.GetType(); if (t.Equals(typeof(int)) | t.Equals(typeof(long))) { AddedDiary = await _db.Diary.FindAsync(id); } } } }
ce4ef84254772264d78eec8c4ed2a82c0fa6a36a
C#
Patypus/CsvAndXmlConverter
/CsvAndXmlConverter/Converters/XmlToCsvConverter.cs
2.671875
3
using CsvAndXmlConverter.Data; using CsvAndXmlConverter.IO; using CsvAndXmlConverter.Properties; using CsvAndXmlConverter.Validator; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; namespace CsvAndXmlConverter.Converters { public class XmlToCsvConverter : IConverter { private readonly IFileWriter _writer; private readonly IXMLFileReader _reader; private readonly IXmlValidator _validator; public XmlToCsvConverter(IFileWriter writer, IXMLFileReader reader, IXmlValidator validator) { _writer = writer; _reader = reader; _validator = validator; } public IConversionResult ConvertFile(string path) { XDocument documentToConvert; try { documentToConvert = _reader.ReadDataFromFile(path); } catch(Exception exception) { return HandleExceptionFromReadingFile(exception, path); } var validationResult = _validator.ValidateXml(documentToConvert); return validationResult.Item1 ? PerfromConversionForDataDocument(documentToConvert, path) : ReportValidationFailure(validationResult); } private IConversionResult ReportValidationFailure(Tuple<bool, string[]> validationResult) { return new ConversionResult { Success = validationResult.Item1, ResultMessage = CreateSingleStringFromArrayOfValidationFailures(validationResult.Item2) }; } private string CreateSingleStringFromArrayOfValidationFailures(string[] failures) { var introMessage = Resources.ValidationErrorsEncountered + Environment.NewLine; return introMessage + string.Join(Environment.NewLine, failures); } private IConversionResult PerfromConversionForDataDocument(XDocument documentToConvert, string path) { var convertedContent = ConvertXmlContentToCSV(documentToConvert); var writeResult = WriteDataToFile(convertedContent, CreatePathForConvertedFile(path)); return new ConversionResult { Success = true, ResultMessage = writeResult }; } private string ConvertXmlContentToCSV(XDocument content) { var resultBuilder = new StringBuilder(); resultBuilder.Append(CreateColumnTitlesRow(content)); var childElements = content.Root.Elements(); foreach (var element in childElements) { resultBuilder.Append(Environment.NewLine + MakeRowFromValuesInElementCollection(element.Elements())); } return resultBuilder.ToString(); } private string MakeRowFromValuesInElementCollection(IEnumerable<XElement> elements) { var elementValuesCollection = elements.Select(element => element.Value.ToString()); return string.Join(",", elementValuesCollection); } private string CreateColumnTitlesRow(XDocument document) { var resultBuilder = new StringBuilder(); var singleItemElement = document.Root.Elements().First(); var propertyElementTitles = singleItemElement.Elements().Select(element => element.Name.ToString()); return string.Join(",", propertyElementTitles); } private string WriteDataToFile(string data, string path) { return _writer.SaveDataToFile(TranscribeDataStringToStream(data), path); } private MemoryStream TranscribeDataStringToStream(string data) { var dataStream = new MemoryStream(); var dataWriter = new StreamWriter(dataStream); dataWriter.Write(data); dataWriter.Flush(); dataStream.Position = 0; return dataStream; } private string CreatePathForConvertedFile(string originalPath) { var filePath = Path.GetDirectoryName(originalPath); var newFileName = "converted_" + Path.GetFileNameWithoutExtension(originalPath) + ".csv"; return Path.Combine(filePath, newFileName); } private IConversionResult HandleExceptionFromReadingFile(Exception exception, string path) { if (exception.GetType() == typeof(FileNotFoundException)) { var message = string.Format(Resources.FileNotFoundMessage, path); return new ConversionResult { Success = false, ResultMessage = message }; } else if (exception.GetType() == typeof(DirectoryNotFoundException)) { var message = string.Format(Resources.DirectoryNotFoundMessage, Path.GetPathRoot(path)); return new ConversionResult { Success = false, ResultMessage = message }; } else { var message = string.Format(Resources.GenericUnableToOpenFile, exception.Message); return new ConversionResult { Success = false, ResultMessage = message }; } } } }
470c7b60ec7531e4f3313c3e37fb1168da7a623b
C#
kirill8000/.NET-2018-2
/Bulygin_Kirill_Task01/Task2/Program.cs
4.0625
4
using System; using System.Text; namespace Task2 { class Program { static int ReadPositiveInt() { int n; string nstr = Console.ReadLine(); while (!Int32.TryParse(nstr, out n) || n <= 0) { Console.Write("Ошибка! Нужно ввести целое положительное число. Попробуте еще раз: "); nstr = Console.ReadLine(); } return n; } static string ConstructPattern(int n) { StringBuilder builder = new StringBuilder(); for (int i = 1; i <= n; i++) { builder.Append('*', i); if (i != n) builder.Append('\n'); } return builder.ToString(); } static void Main(string[] args) { Console.Write("Введите цело число N: "); int n = ReadPositiveInt(); Console.WriteLine(ConstructPattern(n)); } } }
df9f0a3ea80ae87fa27e7f9abd3b442c3edf1c5f
C#
leodeg/CSharp.DesignPatterns
/DesignPatterns/Patterns/StructuralPatterns/StartBridge.cs
3.25
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Patterns.StructuralPatterns { public class StartBridge { } #region First Example public abstract class Shape { public LineStyle m_LineStyle; public abstract void Draw (); } public abstract class LineStyle { public abstract void Draw (); } public class DotLine : LineStyle { public override void Draw () { Console.WriteLine ("Draw Dot Line"); } } public class DashDotLine : LineStyle { public override void Draw () { Console.WriteLine ("Draw Dash Dot Line"); } } public class Pentagon : Shape { public override void Draw () { Console.WriteLine ("Draw Pentagon"); } } public class Square : Shape { public override void Draw () { Console.WriteLine ("Draw Square"); } } public class Triangle : Shape { public override void Draw () { Console.WriteLine ("Draw Triangle"); } } #endregion #region Second Example abstract class Abstraction { protected Implementator implementator; public Abstraction (Implementator imp) { implementator = imp; } public virtual void Operation () { implementator.OperationImp (); } } class RefinedAbstraction : Abstraction { public RefinedAbstraction (Implementator imp) : base (imp) { } public override void Operation () { base.Operation (); Console.WriteLine ("RefinedAbstraction Operation..."); } } abstract class Implementator { public abstract void OperationImp (); } class ConcreteImplementatorA : Implementator { public override void OperationImp () { Console.WriteLine ("ConcreteImplementatorA"); } } class ConcreteImplementatorB : Implementator { public override void OperationImp () { Console.WriteLine ("ConcreteImplementatorB"); } } #endregion }
e0b11c0827af5cd6d68993fa4e7763f8752f5f36
C#
dd86k/fwod
/Game.cs
2.8125
3
using System; /* * Game mechanics. */ //TODO: PlayIntro() -- Intro scene, etc. namespace fwod { class Game { #region Properties public static byte CurrentFloor = 0; #endregion #region Statistics public class Statistics { public static decimal EnemiesKilled = 0, StepsTaken = 0, MoneyGained = 0, DamageDealt = 0, DamageReceived = 0; } #endregion #region Methods public static void QuickIntro() { Console.SetCursorPosition(27, 0); Console.Write("|"); MainPlayer.HP = 10; Console.SetCursorPosition(43, 0); Console.Write("|"); MainPlayer.Money = 12; MainPlayer.Name = "Player"; } #endregion #region People /// <summary> /// Main player /// </summary> public static Player MainPlayer; public static PeopleManager People; #endregion #region Graphics public class Graphics { public class Objects { public const char Grass = '.', Chest = '±', Terminal = '#', ATM = '$', Trap = '+'; } } #endregion #region Events /* public static void TakeTurn() { foreach (Player Enemy in EnemyList) { } } */ public static void ClearMessage() { Console.SetCursorPosition(1, Utils.WindowHeight - 1); Console.Write(new string(' ', Utils.WindowWidth - 2)); } /// <summary> /// Display what's going on. /// </summary> /// <param name="text">Event entry.</param> public static void Message(string text) { //TODO: Clean this clutter. // Idea: Remove the array and use the substrings directly. string[] lines = new string[] { text }; int length = Utils.WindowWidth - 2; const string MoreText = " -- More --"; if (text.Length > length) { int ci = 0; int start = 0; lines = new string[text.Length / (length - MoreText.Length) + 1]; do { if (start + length > text.Length) { lines[ci] = text.Substring(start, text.Length - start); start += length; } else { lines[ci] = text.Substring(start, length - MoreText.Length) + MoreText; start += length - MoreText.Length; } ci++; } while (start < text.Length); } for (int i = 0; i < lines.Length; i++) { ClearMessage(); Console.SetCursorPosition(1, Utils.WindowHeight - 1); Console.Write(lines[i]); if (i < lines.Length - 1) Console.ReadKey(true); } } #endregion #region Save/Load //TODO: Save method //TODO: Load method /*static public bool SaveProgress() // Return true is saved properly { //TODO: Find a way to convert to binary blob and encode it (basE91?) using (TextWriter tw = }*/ /*static public <StructOfGameData> LoadGame() { }*/ #endregion } }
5214fc9d53b5fba6772a426f5cb2ba95bac26e17
C#
shendongnian/download4
/code2/205351-13807929-33005127-2.cs
2.765625
3
static void Main (string[] args) { TestOptional("A"); TestOptional("A", "B"); TestOptional("A", "{0}, {1} , {2}", "C1", "C2", "C3"); Console.ReadLine(); } public static void TestOptional (string A, string B = null, params object[] C) { Console.WriteLine(A); if (B != null) { Console.WriteLine(B, C); } }
9a18c8cf2d1dbceb068ec0fc93ed368ecf99e3b0
C#
CWKSC/MyLib_Csharp
/VisualStudioProject/MyLib_Csharp_Beta/Algorithm/Sort/Sort.cs
3.453125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MyLib_Csharp_Beta.Algorithm { public static partial class Sort { public static List<T> SortTwoSortedList<T>(List<T> A, List<T> B) where T : IComparable { int aLength = A.Count; int bLength = B.Count; if (aLength == 0) { return new List<T>(B); } if (bLength == 0) { return new List<T>(A); } List<T> result = new List<T>(); while (true) { if (A[0].CompareTo(B[0]) < 0) { result.Add(A[0]); A.RemoveAt(0); } else { result.Add(B[0]); B.RemoveAt(0); } if (A.Count == 0) { result.AddRange(B); break; } else if (B.Count == 0) { result.AddRange(A); break; } } return result; } public static T[] SortNSortedArray<T>(params T[][] arrays) where T : IComparable { int length = arrays.Aggregate(0, (pre, ele) => pre + ele.Length); T[] result = new T[length]; int[] indexs = arrays.Select((ele, i) => arrays[i].Length).ToArray(); for (int i = length - 1; i >= 0; i--) { int k = 0; while (indexs[k] == 0) k++; int maxIndex = k; T max = arrays[k][indexs[k] - 1]; for (int j = 1; j < arrays.Length; j++) { if (indexs[j] == 0) continue; if (arrays[j][indexs[j] - 1].CompareTo(max) > 0) { max = arrays[j][indexs[j] - 1]; maxIndex = j; } } indexs[maxIndex]--; result[i] = max; } return result; } } }
6c68caf4f219c72fe505d98d92b95d18351a97a2
C#
hoang2802/QuanLyNhanSu
/QuanLyNhanSu/ActorDAL/PhongBanDAL.cs
2.703125
3
using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; using QuanLyNhanSu.Models; namespace QuanLyNhanSu.ActorDAL { class PhongBanDAL { DataConnection dc; SqlDataAdapter da; SqlCommand cmd; public PhongBanDAL() { dc = new DataConnection(); } public DataTable getAllPhongBan() { //Tạo câu lệnh lấy toàn bộ nhân viên string sql = "SELECT * FROM PhongBan"; //Tạo kết nối đến sql SqlConnection con = dc.getConnect(); //Khởi tạo đối tượng của lớp DataAdapter da = new SqlDataAdapter(sql, con); con.Open(); //Do du lieu tu SqldataAdapter vao Database DataTable dt = new DataTable(); da.Fill(dt); con.Close(); return dt; } public bool InsertPhongBan(PhongBan pb) { string sql = "INSERT INTO PhongBan(MaPB,TenPB,DiaChi,SDTPhongBan) VALUES(@MaPB,@TenPB,@DiaChi,@SDTPhongBan)"; SqlConnection con = dc.getConnect(); try { cmd = new SqlCommand(sql, con); con.Open(); cmd.Parameters.Add("@MaPB", SqlDbType.VarChar).Value = pb.MaPB; cmd.Parameters.Add("@TenPB", SqlDbType.NVarChar).Value = pb.TenPB; cmd.Parameters.Add("@DiaChi", SqlDbType.NVarChar).Value = pb.DiaChi; cmd.Parameters.Add("@SDTPhongBan", SqlDbType.Int).Value = pb.SDTPhongBan; //Thuc thi cau lenh lop Command cmd.ExecuteNonQuery(); con.Close(); } catch (Exception e) { return false; } return true; } public bool UpdatePhongBan(PhongBan pb) { string sql = "UPDATE PhongBan SET TenPB=@TenPB,DiaChi=@DiaChi,SDTPhongBan=@SDTPhongBan WHERE MaPB=@MaPB"; SqlConnection con = dc.getConnect(); try { cmd = new SqlCommand(sql, con); con.Open(); cmd.Parameters.Add("@MaPB", SqlDbType.VarChar).Value = pb.MaPB; cmd.Parameters.Add("@TenPB", SqlDbType.NVarChar).Value = pb.TenPB; cmd.Parameters.Add("@DiaChi", SqlDbType.NVarChar).Value = pb.DiaChi; cmd.Parameters.Add("@SDTPhongBan", SqlDbType.Int).Value = pb.SDTPhongBan; //Thuc thi cau lenh lop Command cmd.ExecuteNonQuery(); con.Close(); } catch (Exception e) { return false; } return true; } public bool DeletePhongBan(PhongBan pb) { string sql = "DELETE FROM PhongBan WHERE MaPB=@MaPB"; SqlConnection con = dc.getConnect(); try { cmd = new SqlCommand(sql, con); con.Open(); cmd.Parameters.Add("@MaPB", SqlDbType.VarChar).Value = pb.MaPB; cmd.ExecuteNonQuery(); con.Close(); } catch (Exception e) { return false; } return true; } } }
813fc41c2e1158db45adc0d7bb7e8217f98095ef
C#
vviital/Project-5-semester
/ConsoleSmartHouse/ConsoleSmartHouse/DataReaders/DataReader.cs
3.0625
3
using System.IO; using System.Linq; using ConsoleSmartHouse.DataReaders; namespace ConsoleSmartHouse.DataReaders { class DataReader { private StreamReader streamReader; public DataReader(string fileName) { streamReader = new StreamReader(fileName); } public InputTree ReadFromFile() { InputTree inputTree = new InputTree(); Read(inputTree); return inputTree; } private void Read(InputTree inputTree) { while (true) { string str = streamReader.ReadLine(); if (str == "/") { if (inputTree.Node.Count==1) { if (inputTree.Node[0].Data == "") { inputTree.Node.Clear(); } } return; } inputTree.Data = str; InputTree newTree = new InputTree(); inputTree.Node.Add(newTree); Read(newTree); } } } }
e781d9e6fd8bf562a305c609899bda1b820b9dc3
C#
photo-bro/LeetCode
/LeetCode.Tests/Medium/BinaryTreeLevelOrderTraversal_102_Tests.cs
2.8125
3
using System; using System.Linq; using LeetCode.Solutions.Helper; using Xunit; using static LeetCode.Solutions.Medium.BinaryTreeLevelOrderTraversal_102; namespace LeetCode.Tests.Medium { public class BinaryTreeLevelOrderTraversal_102_Tests { [Theory] [InlineData("1","1")] [InlineData("3,9,20,null,null,15,7", "3;9,20;15,7")] [InlineData("1,2,2,3,4,4,3", "1;2,2;3,4,4,3")] [InlineData("1, 2,null, 3,4,null,null, 5,6,8", "1;2;3,4;5,6,8")] [InlineData("1,2,2,3,4,4,3,5,6,7,8,8,7,6,5", "1;2,2;3,4,4,3;5,6,7,8,8,7,6,5")] public void LevelOrder_Tests(string tree, string expected) { var exp = expected.Split(';').Select(s => s.Split(',').Select(int.Parse).ToList()).ToList(); var root = TreeNode.StringToTree(tree); var actual = LevelOrder(root); Assert.NotNull(actual); Assert.NotEmpty(actual); Assert.Equal(exp.Count, actual.Count); for (var i = 0; i < exp.Count; ++i) { Assert.NotNull(actual[i]); Assert.NotEmpty(actual[i]); Assert.Equal(exp[i].Count, actual[i].Count); Assert.True(exp[i].OrderBy(x => x).SequenceEqual(actual[i].OrderBy(x => x))); } } } }
0ea4f221c3ecd4592ecbd97fbd2bc93faee0a13b
C#
Fhernd/RecetasMultithreadingCSharp
/Ch05-UsingCSharp5Dot0/R0501/TPLvsAwait.cs
3.5
4
using System; using System.Threading; using System.Threading.Tasks; namespace Ch05_UsingCSharp5Dot0.R0501 { /// <summary> /// Clase para demostración de ejecución con TPL y await. /// </summary> public class TplVsAwait { /// <summary> /// Ejecuta las demostraciones de ejecuciones con TPL y await. /// </summary> public void Ejecutar() { Console.WriteLine(); Task t = AsincronismoConTpl(); t.Wait(); Console.WriteLine(); t = AsincronismoConAwait(); t.Wait(); } /// <summary> /// Demuestra el uso de TPL para llamada asincrónica. /// </summary> /// <returns></returns> private Task AsincronismoConTpl() { Task<string> tarea = ObtenerInfoAsincro("Tarea No. 1"); Task tarea2 = tarea.ContinueWith(t => Console.WriteLine(t.Result), TaskContinuationOptions.NotOnFaulted); Task tarea3 = tarea.ContinueWith(t => Console.WriteLine( t.Exception.InnerException), TaskContinuationOptions.OnlyOnFaulted); return Task.WhenAny(tarea2, tarea3); } /// <summary> /// Demuestra el uso del operador await para llamada asincrónica. /// </summary> /// <returns>Objeto Task con información de la tarea ejecutada.</returns> private async Task AsincronismoConAwait() { try { string resultado = await ObtenerInfoAsincro("Tarea No. 2"); Console.WriteLine(resultado); } catch (Exception ex) { Console.WriteLine(ex); } } /// <summary> /// Método asincrónico para demostrar la invocación desde TPL y await. /// </summary> /// <param name="nombre">Nombre de la tarea.</param> /// <returns>Información del thread del pool de threads.</returns> private async Task<string> ObtenerInfoAsincro(string nombre) { await Task.Delay(TimeSpan.FromSeconds(2)); return String.Format("`{0}` se está ejecutando en el ID de thread {1}. " + "¿Thread en el pool de threads?: {2}.", nombre, Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread); } } }
74bc88a841d228fc2fe7a35aa4a567462879fb28
C#
mayapeneva/Data-Structures
/EXAMS/2016.05.22/Problem-2-PitFortress/PitFortressTests/Performance/PerformanceAddMinion.cs
2.578125
3
using System; using System.Linq; namespace PitFortressTests.Performance { using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Diagnostics; using System.IO; [TestClass] public class PerformanceAddMinion : BaseTestClass { [TestCategory("Performance")] [TestMethod] public void PerformanceAddMinion_WithRandomAmounts1() { FileStream input = File.Open("../../Tests/AddMinion/addMinion.0.txt", FileMode.Open); using (StreamReader reader = new StreamReader(input)) { var commands = reader.ReadToEnd() .Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries) .Select(int.Parse) .ToList(); Stopwatch timer = new Stopwatch(); timer.Start(); for (int i = 0; i < commands.Count; i++) { this.PitFortressCollection.AddMinion(commands[i]); } timer.Stop(); Assert.IsTrue(timer.ElapsedMilliseconds < 120); Assert.AreEqual(commands.Count, this.PitFortressCollection.MinionsCount, "Minon Count did not match!"); var minions = this.PitFortressCollection.ReportMinions(); using (StreamReader reader2 = new StreamReader(File.Open("../../Results/AddMinion/addMinion.0.result.txt", FileMode.Open))) { foreach (var minion in minions) { var line = reader2.ReadLine().Split(' '); Assert.AreEqual(int.Parse(line[0]), minion.XCoordinate, "Minion Coordinates did not match!"); Assert.AreEqual(int.Parse(line[1]), minion.Id, "Minion Id did not match!"); Assert.AreEqual(int.Parse(line[2]), minion.Health, "Minion Health did not match!"); } } } } [TestCategory("Performance")] [TestMethod] public void PerformanceAddMinion_WithRandomAmounts2() { FileStream input2 = File.Open("../../Tests/AddMinion/addMinion.1.txt", FileMode.Open); using (StreamReader reader = new StreamReader(input2)) { var commands = reader.ReadToEnd() .Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries) .Select(int.Parse) .ToList(); Stopwatch timer = new Stopwatch(); timer.Start(); for (int i = 0; i < commands.Count; i++) { this.PitFortressCollection.AddMinion(commands[i]); } timer.Stop(); Assert.IsTrue(timer.ElapsedMilliseconds < 120); Assert.AreEqual(commands.Count, this.PitFortressCollection.MinionsCount, "Minon Count did not match!"); var minions = this.PitFortressCollection.ReportMinions(); using (StreamReader reader2 = new StreamReader(File.Open("../../Results/AddMinion/addMinion.1.result.txt", FileMode.Open))) { foreach (var minion in minions) { var line = reader2.ReadLine().Split(' '); Assert.AreEqual(int.Parse(line[0]), minion.XCoordinate, "Minion Coordinates did not match!"); Assert.AreEqual(int.Parse(line[1]), minion.Id, "Minion Id did not match!"); Assert.AreEqual(int.Parse(line[2]), minion.Health, "Minion Health did not match!"); } } } } [TestCategory("Performance")] [TestMethod] public void PerformanceAddMinion_WithRandomAmounts3() { FileStream input3 = File.Open("../../Tests/AddMinion/addMinion.2.txt", FileMode.Open); using (StreamReader reader = new StreamReader(input3)) { var commands = reader.ReadToEnd() .Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries) .Select(int.Parse) .ToList(); Stopwatch timer = new Stopwatch(); timer.Start(); for (int i = 0; i < commands.Count; i++) { this.PitFortressCollection.AddMinion(commands[i]); } timer.Stop(); Assert.IsTrue(timer.ElapsedMilliseconds < 120); Assert.AreEqual(commands.Count, this.PitFortressCollection.MinionsCount, "Minon Count did not match!"); var minions = this.PitFortressCollection.ReportMinions(); using (StreamReader reader2 = new StreamReader(File.Open("../../Results/AddMinion/addMinion.2.result.txt", FileMode.Open))) { foreach (var minion in minions) { var line = reader2.ReadLine().Split(' '); Assert.AreEqual(int.Parse(line[0]), minion.XCoordinate, "Minion Coordinates did not match!"); Assert.AreEqual(int.Parse(line[1]), minion.Id, "Minion Id did not match!"); Assert.AreEqual(int.Parse(line[2]), minion.Health, "Minion Health did not match!"); } } } } [TestCategory("Performance")] [TestMethod] public void PerformanceAddMinion_WithRandomAmounts4() { FileStream input4 = File.Open("../../Tests/AddMinion/addMinion.3.txt", FileMode.Open); using (StreamReader reader = new StreamReader(input4)) { var commands = reader.ReadToEnd() .Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries) .Select(int.Parse) .ToList(); Stopwatch timer = new Stopwatch(); timer.Start(); for (int i = 0; i < commands.Count; i++) { this.PitFortressCollection.AddMinion(commands[i]); } timer.Stop(); Assert.IsTrue(timer.ElapsedMilliseconds < 120); Assert.AreEqual(commands.Count, this.PitFortressCollection.MinionsCount, "Minon Count did not match!"); var minions = this.PitFortressCollection.ReportMinions(); using (StreamReader reader2 = new StreamReader(File.Open("../../Results/AddMinion/addMinion.3.result.txt", FileMode.Open))) { foreach (var minion in minions) { var line = reader2.ReadLine().Split(' '); Assert.AreEqual(int.Parse(line[0]), minion.XCoordinate, "Minion Coordinates did not match!"); Assert.AreEqual(int.Parse(line[1]), minion.Id, "Minion Id did not match!"); Assert.AreEqual(int.Parse(line[2]), minion.Health, "Minion Health did not match!"); } } } } [TestCategory("Performance")] [TestMethod] public void PerformanceAddMinion_WithRandomAmounts5() { FileStream input5 = File.Open("../../Tests/AddMinion/addMinion.4.txt", FileMode.Open); using (StreamReader reader = new StreamReader(input5)) { var commands = reader.ReadToEnd() .Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries) .Select(int.Parse) .ToList(); Stopwatch timer = new Stopwatch(); timer.Start(); for (int i = 0; i < commands.Count; i++) { this.PitFortressCollection.AddMinion(commands[i]); } timer.Stop(); Assert.IsTrue(timer.ElapsedMilliseconds < 120); Assert.AreEqual(commands.Count, this.PitFortressCollection.MinionsCount, "Minon Count did not match!"); var minions = this.PitFortressCollection.ReportMinions(); using (StreamReader reader2 = new StreamReader(File.Open("../../Results/AddMinion/addMinion.4.result.txt", FileMode.Open))) { foreach (var minion in minions) { var line = reader2.ReadLine().Split(' '); Assert.AreEqual(int.Parse(line[0]), minion.XCoordinate, "Minion Coordinates did not match!"); Assert.AreEqual(int.Parse(line[1]), minion.Id, "Minion Id did not match!"); Assert.AreEqual(int.Parse(line[2]), minion.Health, "Minion Health did not match!"); } } } } } }
cc8ee605c9624698284ab81910109576a80cea7e
C#
ArtiDandge/FundooNotesApp
/FundooModels/ResetPasswordModel.cs
2.53125
3
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Text; namespace FundooModels { public class ResetPasswordModel { [RegularExpression("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", ErrorMessage = "E-mail is not valid. Please Entet valid email")] public string UserEmail { get; set; } [Required] public string UserPassword { get; set; } [Required] public string ConfirmPassword { get; set; } } }
8192b651476dfa0ccc6f0931d6dd0cc5b5269ee0
C#
dineshjethoe/AllowBypassKey
/WPF/MainWindow.xaml.cs
2.5625
3
using Microsoft.Office.Interop.Access.Dao; using Microsoft.Win32; using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Windows; namespace WPF { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { private FileInfoModel file = new FileInfoModel(); public MainWindow() { InitializeComponent(); this.Title = string.Empty; fileText.DataContext = file; propsText.DataContext = file; } private void Browse_Click(object sender, RoutedEventArgs e) { var openFileDialog = new OpenFileDialog { Title = "Find and select the MS Access database file.", Filter = "Access Database (*.mdb) | *.mdb|Access Database (*.accdb) | *.accdb", Multiselect = false }; if (openFileDialog.ShowDialog() == true) { file.FileName = openFileDialog.FileName; file.Properties = ChangeAllowBypassKey(file.FileName); } } public class FileInfoModel : INotifyPropertyChanged { private string _fileName; public string FileName { get { return _fileName; } set { _fileName = value; OnPropertyChanged(); } } private string _properties; public string Properties { get { return _properties; } set { _properties = value; OnPropertyChanged(); } } public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged([CallerMemberName] string propertyName = "") { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } private string ChangeAllowBypassKey(string dbPath) { var strBuilder = new StringBuilder(); try { var dbe = new DBEngine(); var db = dbe.OpenDatabase(dbPath); Property prop = db.Properties["AllowBypassKey"]; switch (MessageBox.Show("Allow bypass key?", "Allow bypass key?", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No)) { case MessageBoxResult.Yes: prop.Value = true; strBuilder.AppendLine("Property 'AllowBypassKey' is set to 'True'."); strBuilder.AppendLine("You can access the design (developer) mode by keep pressing SHIFT key while opening the file."); break; case MessageBoxResult.No: prop.Value = false; strBuilder.AppendLine("Property 'AllowBypassKey' is set to 'False'."); strBuilder.AppendLine("You can no longer use the SHIFT key to enter the design mode."); break; } return ListProperties(db, strBuilder); } catch (Exception) { throw; } } private string ListProperties(Database db, StringBuilder strBuilder) { strBuilder.AppendLine(); strBuilder.AppendLine("Database properties:"); strBuilder.AppendLine(string.Concat(Enumerable.Repeat("_", 50))); foreach (var p in DumpProperties(db.Properties)) { strBuilder.AppendLine(p); } strBuilder.AppendLine(); strBuilder.AppendLine("Containers:"); strBuilder.AppendLine(string.Concat(Enumerable.Repeat("_", 50))); foreach (Microsoft.Office.Interop.Access.Dao.Container c in db.Containers) { Console.WriteLine("{0}:{1}", c.Name, c.Owner); foreach (var p in DumpProperties(c.Properties)) { strBuilder.AppendLine(p); } } strBuilder.AppendLine(); strBuilder.AppendLine("Documents and properties for a each container:"); strBuilder.AppendLine(string.Concat(Enumerable.Repeat("_", 50))); foreach (Document d in db.Containers["Databases"].Documents) { Console.WriteLine($"{d.Name}"); foreach (var p in DumpProperties(d.Properties)) { strBuilder.AppendLine(p); } } return strBuilder.ToString(); } private static IEnumerable<string> DumpProperties(Properties props) { foreach (Property p in props) { object val; try { val = (object)p.Value; } catch (Exception e) { val = e.Message; } yield return $"{p.Name} ({val}) = {(DataTypeEnum)p.Type}"; } } } }
fdf656c8f7bd0e6dd0e738ee1e586936b5211dce
C#
maziesmith/DiplomadoWebBackEnd
/DiplomadoWebBackEnd/Clase1/Herencia/Vehiculo.cs
3.21875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DiplomadoWebBackEnd.Clase1.Herencia { class Vehiculo { // forma implicita de get y set public string Color { get; set; } public string Marca { get; set; } public float Velocidad { get; set; } public int NumeroPasajeros { get; set; } private string modelo; // forma explicita de get y set public string Modelo { get { return modelo; } set { this.modelo = value; } } public Vehiculo() { Console.WriteLine("Constructor clase vehiculo"); } public Vehiculo(string marca, string color) { Console.WriteLine("Marca: {0}, Color: {1}", marca, color); } public void Encender() { Console.WriteLine("Enciende"); } public void Acelerar() { Console.WriteLine("Acelera"); } public void Apagar() { Console.WriteLine("Apaga"); } } }
3a4f6af3e4decdcb62c2ad6ef6ea2fcd16502db0
C#
snbbgyth/WorkFlowEngine
/WorkFlowEngine/Nhibernate/Transform/ToListResultTransformer.cs
2.765625
3
using System; using System.Collections; using System.Collections.Generic; namespace NHibernate.Transform { /// <summary> /// Tranforms each result row from a tuple into a <see cref="IList"/>, such that what /// you end up with is a <see cref="IList"/> of <see cref="IList"/>. /// </summary> [Serializable] public class ToListResultTransformer : IResultTransformer { private static readonly object Hasher = new object(); public object TransformTuple(object[] tuple, string[] aliases) { return new List<object>(tuple); } public IList TransformList(IList list) { return list; } public override bool Equals(object obj) { if (obj == null) { return false; } return obj.GetHashCode() == Hasher.GetHashCode(); } public override int GetHashCode() { return Hasher.GetHashCode(); } } }
1142faf4c1744205540acaa405c96e0950e64cb3
C#
ruinosus/projetopcs
/ProjetoPCS/ClassesBasicas/Pessoa.cs
3.046875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ClassesBasicas { public class Pessoa { private int codigo; public int Codigo { get { return codigo; } set { codigo = value; } } private string nome; public string Nome { get { return nome; } set { nome = value; } } private DateTime dataNascimento; public DateTime DataNascimento { get { return dataNascimento; } set { dataNascimento = value; } } private char sexo; public char Sexo { get { return sexo; } set { sexo = value; } } public Pessoa() { } public Pessoa(int codigo, string nome, DateTime dataNascimento, char sexo) { this.codigo = codigo; this.nome = nome; this.dataNascimento = dataNascimento; this.sexo = sexo; } } }
c8f4b510985e64a4cf5ad24b56937467d03fdc8c
C#
Sounour/uni-ER
/ER_Framework/WorldDisplay/MainWindow.xaml.cs
2.734375
3
using System.Collections.Generic; using System.Windows; using System.Windows.Media; using System.Windows.Shapes; using de.sounour.uni.er; using WorldDisplay.ViewModel; namespace WorldDisplay { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow { public MainWindow() { InitializeComponent(); SimulationProperties properties = (SimulationProperties) DataContext; RobotPath rbPath = new RobotPath((properties).Robot); // Get the path and draw it. PathCanvas.Children.Add(rbPath); PathCanvas.UpdateLayout(); } } public class RobotPath : UIElement { public Robot Robot { get; private set; } public RobotPath(Robot robot) { Robot = robot; Path p = DrawPath(robot); p.Stroke = new SolidColorBrush(Colors.Red); } public Path DrawPath(Robot robot) { Path p = new Path(); PathFigure f = new PathFigure(robot.StartinPoint, new List<PathSegment>(), false); foreach (Vector vector in robot.TakenPath) { LineSegment segment = new LineSegment(new Point(vector.X, vector.Y), true); f.Segments.Add(segment); } p.Data = new PathGeometry(new List<PathFigure> { f }); return p; } } }
e79a627f8bf537fd2d4f44633401190979bce0a2
C#
batbuild/duality
/UnitTesting/DualityTests/Utility/RawListTest.cs
2.796875
3
using System; using System.Text; using System.Collections.Generic; using System.Linq; using Duality; using NUnit.Framework; namespace Duality.Tests.Utility { [TestFixture] public class RawListTest { [Test] public void Basics() { RawList<int> intList = new RawList<int>(); intList.Add(10); intList.AddRange(new int[] { 17, 42, 94 }); Assert.AreEqual(4, intList.Count); Assert.IsTrue(intList.Contains(42)); Assert.AreEqual(2, intList.IndexOf(42)); CollectionAssert.AreEqual(new int[] { 10, 17, 42, 94 }, intList); CollectionAssert.AreEqual(new int[] { 10, 17, 42, 94 }, intList.Data.Take(4)); intList.ShrinkToFit(); Assert.AreEqual(intList.Count, intList.Capacity); intList.Remove(42); Assert.AreEqual(3, intList.Count); Assert.IsTrue(!intList.Contains(42)); Assert.AreEqual(-1, intList.IndexOf(42)); CollectionAssert.AreEqual(new int[] { 10, 17, 94 }, intList); CollectionAssert.AreEqual(new int[] { 10, 17, 94 }, intList.Data.Take(3)); intList.Insert(1, 100); CollectionAssert.AreEqual(new int[] { 10, 100, 17, 94 }, intList); CollectionAssert.AreEqual(new int[] { 10, 100, 17, 94 }, intList.Data.Take(4)); intList.InsertRange(2, new int[] { 150, 200, 250, 300 }); CollectionAssert.AreEqual(new int[] { 10, 100, 150, 200, 250, 300, 17, 94 }, intList); CollectionAssert.AreEqual(new int[] { 10, 100, 150, 200, 250, 300, 17, 94 }, intList.Data.Take(8)); intList.Clear(); Assert.AreEqual(0, intList.Count); Assert.IsTrue(!intList.Contains(94)); } [Test] public void Move() { int[] testArray = Enumerable.Range(0, 10).ToArray(); RawList<int> intList = new RawList<int>(); intList.AddRange(testArray); intList.Move(0, 3, 1); CollectionAssert.AreEqual(new int[] { 0, 0, 1, 2, 4, 5, 6, 7, 8, 9 }, intList); intList.Clear(); intList.AddRange(testArray); intList.Move(0, 3, 3); CollectionAssert.AreEqual(new int[] { 0, 1, 2, 0, 1, 2, 6, 7, 8, 9 }, intList); intList.Clear(); intList.AddRange(testArray); intList.Move(0, 3, 5); CollectionAssert.AreEqual(new int[] { 0, 1, 2, 3, 4, 0, 1, 2, 8, 9 }, intList); intList.Clear(); intList.AddRange(testArray); intList.Move(7, 3, -1); CollectionAssert.AreEqual(new int[] { 0, 1, 2, 3, 4, 5, 7, 8, 9, 9 }, intList); intList.Clear(); intList.AddRange(testArray); intList.Move(7, 3, -3); CollectionAssert.AreEqual(new int[] { 0, 1, 2, 3, 7, 8, 9, 7, 8, 9 }, intList); intList.Clear(); intList.AddRange(testArray); intList.Move(7, 3, -5); CollectionAssert.AreEqual(new int[] { 0, 1, 7, 8, 9, 5, 6, 7, 8, 9 }, intList); intList.Clear(); } [Test] public void Resize() { int[] testArray = Enumerable.Range(0, 10).ToArray(); RawList<int> intList = new RawList<int>(); intList.AddRange(testArray); CollectionAssert.AreEqual(testArray, intList); intList.Count = 20; Assert.IsTrue(intList.Count == 20); CollectionAssert.AreEqual(testArray.Concat(new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }), intList); intList[19] = 19; Assert.IsTrue(intList[19] == 19); Assert.IsTrue(intList.Data[19] == 19); } [Test] public void Sort() { int[] testArray = Enumerable.Range(0, 10).ToArray(); RawList<int> intList = new RawList<int>(); intList.AddRange(testArray.Reverse().ToArray()); CollectionAssert.AreEqual(testArray.Reverse(), intList); intList.Sort(); CollectionAssert.AreEqual(testArray, intList); } } }
08929dfa2df5da8b236513654cef7af988182576
C#
iorilan/EmguObjDetection
/FFImgProducer/MediaHelper.cs
2.546875
3
using System; using System.Configuration; using System.IO; using System.Linq; using System.Net.Mime; using System.Windows.Forms; namespace FFImgProducer { public class MediaHelper { public static string FFmpegImgfolder() { var ffPath = ConfigurationManager.AppSettings["ffmpegFolder"]; return ffPath; } public static string VcaImgfolder() { var vcaPath = ConfigurationManager.AppSettings["vcaFolder"]; return vcaPath; } public static string FileName(string path) { var fileName = path.Split('\\').Last(); return fileName; } public static string UniquePath(string path) { var fileName = FileName(path); var noExension = fileName.Split('.').First(); return path.Replace(noExension, Guid.NewGuid().ToString()); } public static void EnsureDirCreated(params string[] path) { foreach (var s in path) { if (!Directory.Exists(s)) { Directory.CreateDirectory(s); } } } } }
3e220ff3e9fe0310ae240e2b2a463510009f1e2a
C#
Derembas/IrbisDoors
/Калькулятор/ViewModels/Order/Order.cs
3.03125
3
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.Linq; using System.Text; using System.Threading.Tasks; using System.ComponentModel; using System.Windows; using System.Windows.Input; namespace Calculator { // Класс "Заказ" содержит информацию по всему заказу public class Order { public BaseClasses.Door SelectedDoor { get; set; } public ObservableCollection<BaseClasses.Door> Doors { get; set; } public Order() { Doors = new ObservableCollection<BaseClasses.Door>(); } #region Команды #region Добавление новой двери private ICommand addNewDoorCommand; public ICommand AddNewDoorCommand { get { if (addNewDoorCommand == null) addNewDoorCommand = new Helpers.RelayCommand(param => AddNewDoor()); return addNewDoorCommand; } } private void AddNewDoor() { var curSelectWindow = new SelectWindow(); var typeToAdd= curSelectWindow.SelectProductType(); BaseClasses.Door doorToAdd=null; switch (typeToAdd) { case Helpers.AllNames.ProductClasses.k1MDType: doorToAdd = new ViewModels.MDDoors.MDDoor(); break; case Helpers.AllNames.ProductClasses.k4RDType: doorToAdd = new ViewModels.RDDoors.RDDoor(); break; default: break; } if (doorToAdd != null) { doorToAdd.Edit(); Doors.Add(doorToAdd); } } #endregion #region Правка выбранной двери private ICommand editDoorCommand; public ICommand EditDoorCommand { get { if (editDoorCommand == null) editDoorCommand = new Helpers.RelayCommand(param => EditDoor(), param=> { return SelectedDoor != null; }); return editDoorCommand; } } private void EditDoor() { SelectedDoor.Edit(); } #endregion #region Удаление выбранной двери private ICommand deleteDoorCommand; public ICommand DeleteDoorCommand { get { if (deleteDoorCommand == null) deleteDoorCommand = new Helpers.RelayCommand(param => AddNewDoor(), param=> { return SelectedDoor != null; }); return deleteDoorCommand; } } private void DeleteDoor() { Doors.Remove(SelectedDoor); } #endregion #endregion } }
f5abba1b53d680549339e83f307d4a1e17813399
C#
amichaivaknin/lab2
/lab2/HelloPerson/Program.cs
3.953125
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace HelloPerson { class Program { static void Main(string[] args) { int spaces = 0; //The convention is to use the 'bool' alias of 'Boolean'. Boolean flag = false; Console.WriteLine("What's your name?"); var name = Console.ReadLine(); //it is better to use formatting. Fortuanatelly, we won't have to use string interpolation or string.Format since Console.WriteLine has an overload that accepts a formatted string Console.WriteLine("Hello " + name); Console.WriteLine("Enter a number between 1-10"); //Consider using do-while loop while (flag == false) { var space = Console.ReadLine(); spaces = int.Parse(space); if (spaces > 10 || spaces < 1) { Console.WriteLine("Worng number, insert new number between 1-10"); flag = false; } else //The convention in C# is to add braces for body-expressions even if they are oneliners. flag = true; } for (int i = 0; i < spaces; i++) { name = " " + name; Console.WriteLine(name); } } } }
3bf9f2907791de3faa307205e983958f6a944ec9
C#
jeremyyang824/Leetcode
/Leetcode.Test/OJ040_CombinationSumIITest.cs
2.875
3
using System; using System.Collections.Generic; using Leetcode.Core; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Leetcode.Test { [TestClass] public class OJ040_CombinationSumIITest { [TestMethod] public void OJ040_CombinationSumIITest1() { IList<IList<int>> result = new OJ040_CombinationSumII().CombinationSum2(new int[] { 10, 1, 2, 7, 6, 1, 5 }, 8); Assert.AreEqual(4, result.Count); Assert.AreEqual(1, result[0][0]); Assert.AreEqual(1, result[0][1]); Assert.AreEqual(6, result[0][2]); Assert.AreEqual(1, result[1][0]); Assert.AreEqual(2, result[1][1]); Assert.AreEqual(5, result[1][2]); Assert.AreEqual(1, result[2][0]); Assert.AreEqual(7, result[2][1]); Assert.AreEqual(2, result[3][0]); Assert.AreEqual(6, result[3][1]); } } }
2d984746d41409dd9aacf76f491d0a17cdb21fed
C#
gabrieldwight/ConsoleTest
/Console.DB/Class1.cs
2.734375
3
using System; using System.Data.SqlClient; namespace Console.DB { public class Class1 : IDataInterface { private SqlConnection cnn; // you can instatiate the connection in the class constructor (optional) public Class1() { } // Implemetation of the database CRUD methods on your tables public void insert(string query) { throw new NotImplementedException(); } public void select(string query) { throw new NotImplementedException(); } public void update(string query) { throw new NotImplementedException(); } public void connect() { string connetionString; connetionString = @"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=EFOnlineShopping;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"; cnn = new SqlConnection(connetionString); cnn.Open(); System.Console.WriteLine("Connection Open !"); cnn.Close(); } public string display() { return "Hello World"; } } }