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
028378b5549d350f1ef7438b538043f131bb8797
C#
kim4t/SEP
/C# 01/Exercise3/Program.cs
3.359375
3
using System; namespace Exersize3 { class Program { static void Main(string[] args) { Console.WriteLine("Input string: "); string input = Console.ReadLine(); printReverseString(input); } static void printReverseString(string s) { char[] charArr = s.ToCharArray(); Array.Reverse(charArr); Console.WriteLine(new string(charArr)); } } }
11a0e7674025f8fb7433fc4fda4a22303e74b322
C#
woods2011/AlgorithmsKR1
/AlgorithmsKR1.Delimost/RachThree.cs
3.34375
3
using System; namespace AlgorithmsKR1.Delimost { public class RachThree : DivisibilityBase { public override void Compute(int maxIterCount) { int a, b, bb, q, qq; int m, k; a = SplitNumber(P, out b); switch (b) { case 3: case 7: bb = b; break; case 1: case 9: bb = 10 - b; break; default: throw new ArgumentException("b не подходит, ежи"); } q = (P * bb + 1) / 10; qq = Math.Abs(P - q); var curN = N; var iterCount = 0; Console.WriteLine($"a = {a}, b = {b}, b* = {bb}, q = {q}, q* = {qq}"); while (curN > P && iterCount < maxIterCount) { m = SplitNumber(curN, out k); curN = m - k * qq; Console.WriteLine($"Offset: {Offset} | m = {m}, k = {k} | CurN = {curN}"); iterCount++; } } } }
f703ae27ebadd2e5334a252ef8639464cd8ba41b
C#
Xianbiao-Jiang/LeetCode-CS
/LeetCode.Test/0201-0250/0226-InvertBinaryTree-Test.cs
2.671875
3
using Microsoft.VisualStudio.TestTools.UnitTesting; namespace LeetCode.Test { [TestClass] public class _0226_InvertBinaryTree_Test { [TestMethod] public void InvertTreeTest() { var root = TestHelper.GenerateTree(new int?[] { 4, 2, 7, 1, 3, 6, 9 }); var solution = new _0226_InvertBinaryTree(); var newRoot = solution.InvertTree(root); AssertHelper.AssertTree(new int?[] { 4, 7, 2, 9, 6, 3, 1 }, newRoot); } } }
043923fc6fd2353dd8addd733a20858e9ea67af9
C#
FlamboyantRaccoon/Plugins
/Script/Lib/Formula/Parser/FormulaInternalSymbols.cs
2.578125
3
// Copyright 2016 Bigpoint, Lyon // // Maintainer: Sylvain Minjard <s.minjard@bigpoint.net> // // Date: 2017/03/14 using UnityEngine; using System.Collections.Generic; namespace FormulaParser { public static class InternalSymbols { // Variables public static readonly Dictionary<string, double> variables = new Dictionary<string, double>() { { "PI", Mathf.PI }, { "PHI", (1 + System.Math.Sqrt(5)) / 2 } }; public static string[] variableNames { get { if(ms_variableNames == null) { ms_variableNames = new string[variables.Count]; variables.Keys.CopyTo(ms_variableNames, 0); } return ms_variableNames; } } // Meta Functions public static readonly SymbolHandler.Method[] metaFunctions = new SymbolHandler.Method[] { new SymbolHandler.Method("SUM", 3, 4, "SUM(3-4)", 1), }; public static string[] metaFunctionNames { get { if(ms_metaFunctionNames == null) { ms_metaFunctionNames = System.Array.ConvertAll(metaFunctions, item => item.name); } return ms_metaFunctionNames; } } public static SymbolHandler.Method GetMetaFunction(string a_methodName) { if(ms_metaFunctions == null) { ms_metaFunctions = new Dictionary<string, SymbolHandler.Method>(); for(int metaFunctionIndex = 0; metaFunctionIndex < metaFunctions.Length; ++metaFunctionIndex) { ms_metaFunctions.Add(metaFunctions[metaFunctionIndex].name, metaFunctions[metaFunctionIndex]); } } lwTools.Assert(ms_metaFunctions.ContainsKey(a_methodName)); return ms_metaFunctions[a_methodName]; } public static readonly string[] metaFunctionVariableNames = new string[] { "i", "j", "k", "a", "b", "c", "d", "e", "f", "g", "h", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" }; // Methods public static readonly SymbolHandler.Method[] methods = new SymbolHandler.Method[] { SymbolHandler.Method.Parse("MIN(2-INF)"), SymbolHandler.Method.Parse("MAX(2-INF)"), SymbolHandler.Method.Parse("ABS(1)"), SymbolHandler.Method.Parse("COS(1)"), SymbolHandler.Method.Parse("SIN(1)"), SymbolHandler.Method.Parse("TAN(1)"), SymbolHandler.Method.Parse("POW(2)"), SymbolHandler.Method.Parse("SQRT(1)"), SymbolHandler.Method.Parse("INTDIV(2)"), SymbolHandler.Method.Parse("FLOOR(1)"), SymbolHandler.Method.Parse("CEIL(1)") }; public static string[] methodNames { get { if(ms_methodNames == null) { ms_methodNames = System.Array.ConvertAll(methods, item => item.name); } return ms_methodNames; } } public static SymbolHandler.Method GetMethod(string a_methodName) { if(ms_methods == null) { ms_methods = new Dictionary<string, SymbolHandler.Method>(); for(int methodIndex = 0; methodIndex < methods.Length; ++methodIndex) { ms_methods.Add(methods[methodIndex].name, methods[methodIndex]); } } lwTools.Assert(ms_methods.ContainsKey(a_methodName)); return ms_methods[a_methodName]; } public static bool TryMethodEvaluation(string a_methodName, double[] a_arguments, out double a_result) { SymbolHandler.Method method = GetMethod(a_methodName); lwTools.AssertFormat(a_arguments.Length >= method.minArgumentCount && a_arguments.Length <= method.maxArgumentCount, "Invalid number of arguments for formula method '{0}'. {1} arguments given but the amount of argument must be in [{2}; {3}].", a_methodName, a_arguments.Length, method.minArgumentCount, method.maxArgumentCount); switch(a_methodName) { case "MIN": { a_result = lwMath.Min(a_arguments); return true; } case "MAX": { a_result = lwMath.Max(a_arguments); return true; } case "ABS": { a_result = lwMath.Abs(a_arguments[0]); return true; } case "COS": { a_result = lwMath.Cos(a_arguments[0]); return true; } case "SIN": { a_result = lwMath.Sin(a_arguments[0]); return true; } case "TAN": { a_result = lwMath.Tan(a_arguments[0]); return true; } case "POW": { a_result = lwMath.Pow(a_arguments[0], a_arguments[1]); return true; } case "SQRT": { a_result = lwMath.Sqrt(a_arguments[0]); return true; } case "INTDIV": { a_result = lwMath.IntegerDivision(a_arguments[0], a_arguments[1]); return true; } case "FLOOR": { a_result = lwMath.Floor(a_arguments[0]); return true; } case "CEIL": { a_result = lwMath.Ceil(a_arguments[0]); return true; } default: { lwTools.AssertFormat(false, "Formula internal method '{0}' is defined but the evaluation method is not set.", a_methodName); a_result = 0.0; return false; } } } #region Private private static string[] ms_variableNames = null; private static string[] ms_metaFunctionNames = null; private static Dictionary<string, SymbolHandler.Method> ms_metaFunctions = null; private static string[] ms_methodNames = null; private static Dictionary<string, SymbolHandler.Method> ms_methods = null; #endregion } }
f30396954a8a55e0a0e64fcc656a40b58e41caa0
C#
ejb21/code-sample
/Unity Games/Space SHMUP Prototype/Assets/__Scripts/Weapon.cs
2.65625
3
using UnityEngine; using System.Collections; // This is an enum of the various possible weapon types // It also includes a "shield" type to allow a shield power-up // Items marked [NI] below are Not Implemented in this book public enum WeaponType { none , // The default / no weapon blaster , // A simple blaster spread , // Two shots simultaneously phaser , // Shots that move in waves [NI] missile , // Homing missiles [NI] laser , // Damage over time [NI] shield // Raise shieldLevel } // The WeaponDefinition class allows you to set the properties of a specific weapon in the Inspector. // Main has an array of WeaponDefinitions that makes this possible. // [System.Serializable] tells Unity to try to view WeaponDefinition in the Inspector pane. // It doesn't work for everything, but it will work for simple classes like this! [System.Serializable] public class WeaponDefinition { public WeaponType type = WeaponType.none ; public string letter ; // The letter to show on the power-up public Color color = Color.white ; // Color of Collar & power-up public GameObject projectilePrefab ; // Prefab for projectiles public Color projectileColor = Color.white ; public float damageOnHit = 0 ; // Amount of damage caused public float continuousDamage = 0 ; // Damage per second (laser) public float delayBetweenShots = 0 ; public float velocity = 20 ; // Speed of projectiles } // Note: weapon prefabs, colors, and so on are set in the class Main public class Weapon : MonoBehaviour { static public Transform PROJECTILE_ANCHOR ; public bool ____________________ ; [SerializeField] private WeaponType _type = WeaponType.blaster ; public WeaponDefinition def ; public GameObject collar ; public float lastShot ; // Time last shot was fired void Awake () { collar = transform.Find ( "Collar" ).gameObject ; } void Start () { // Call SetType() properly for the default _type SetType ( _type ) ; if ( PROJECTILE_ANCHOR == null ) { GameObject go = new GameObject ( "_Projectile_Anchor" ) ; PROJECTILE_ANCHOR = go.transform ; } // Find the fireDelegate of the parent GameObject parentGO = transform.parent.gameObject ; if ( parentGO.tag == "Hero" ) { Hero.S.fireDelegate += Fire ; } } public WeaponType type { get { return ( _type ) ; } set { SetType ( value ) ; } } public void SetType ( WeaponType wt ) { _type = wt ; if ( type == WeaponType.none ) { this.gameObject.SetActive ( false ) ; return ; } else { this.gameObject.SetActive ( true ) ; } def = Main.GetWeaponDefinition ( _type ) ; collar.GetComponent< Renderer >().material.color = def.color ; lastShot = 0 ; // You can always fire immediately after _type is set. } public void Fire () { // If this.gameObject is inactive, return if ( !gameObject.activeInHierarchy ) return ; // If it hasn't been enough time between shots, return if ( Time.time - lastShot < def.delayBetweenShots ) return ; Projectile p ; switch ( type ) { case WeaponType.blaster : p = MakeProjectile() ; p.GetComponent< Rigidbody >().velocity = Vector3.up * def.velocity ; break ; case WeaponType.spread : p = MakeProjectile() ; p.GetComponent< Rigidbody >().velocity = Vector3.up * def.velocity ; p = MakeProjectile() ; p.GetComponent< Rigidbody >().velocity = new Vector3 ( -.2f , 0.9f , 0 ) * def.velocity ; p = MakeProjectile() ; p.GetComponent< Rigidbody >().velocity = new Vector3 ( .2f , 0.9f , 0 ) * def.velocity ; break ; } } public Projectile MakeProjectile () { GameObject go = Instantiate ( def.projectilePrefab ) as GameObject ; if ( transform.parent.gameObject.tag == "Hero" ) { go.tag = "ProjectileHero" ; go.layer = LayerMask.NameToLayer ( "ProjectileHero" ) ; } else { go.tag = "ProjectileEnemy" ; go.layer = LayerMask.NameToLayer ( "ProjectileEnemy" ) ; } go.transform.position = collar.transform.position ; go.transform.parent = PROJECTILE_ANCHOR ; Projectile p = go.GetComponent< Projectile >() ; p.type = type ; lastShot = Time.time ; return ( p ) ; } }
09293a7530de190e8208fbfc5eb1cade1d41111e
C#
johnnyoshika/design-patterns
/DesignPatterns/Mvp/ManufacturerListPresenter.cs
3
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace DesignPatterns.Mvp { public class ManufacturerListPresenter { public ManufacturerListPresenter(IManufacturerListView listView, IManufacturerReader manufacturerReader) { ListView = listView; ManufacturerReader = manufacturerReader; } IManufacturerListView ListView { get; } IManufacturerReader ManufacturerReader { get; } public void Init() => ListView.Show(GetViewModel()); public void Sort(bool ascending) { var vm = GetViewModel(); vm.Manufacturers = ascending ? vm.Manufacturers.OrderBy(m => m) : vm.Manufacturers.OrderByDescending(m => m); vm.Ascending = ascending; ListView.Show(vm); } ManufacturerListViewModel GetViewModel() => new ManufacturerListViewModel { Title = "Manufacturers", Manufacturers = ManufacturerReader.ReadAll() }; } }
1e4d76b86c8586d90f3f0ea6f046a07ad5f9dc34
C#
LimGoSky/TradingPlatform
/Trading.Common/Common/UnitConvert.cs
2.609375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Trading.Common.Common { public class UnitConvert { private DateTime ConvertStringToDateTime(string timeStamp) { DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); long lTime = long.Parse(timeStamp + "0000"); TimeSpan toNow = new TimeSpan(lTime); return dtStart.Add(toNow); } } }
854d125ecf76763ab420805779bd17220001e314
C#
Teliesin/ChainOfResponsibilitiesDesignPatternExample
/Program.cs
2.609375
3
using IntersectonChainOfResponsibilities.Operators; using System; namespace IntersectonChainOfResponsibilities { class Program { static void Main(string[] args) { Intersection intersection = new Intersection(); intersection.IsPoliceOfficerPresent = true; intersection.AreRoadSignsPresent = true; intersection.AreRoadSignsPresent = true; IIntersectionOperator rightHandRuleOperator = new RightHandRuleOperator(); IIntersectionOperator roadSignsOperator = new RoadSignsOperator(); roadSignsOperator.NextOperator = rightHandRuleOperator; IIntersectionOperator trafficLightsOperator = new TrafficLightsOperator(); trafficLightsOperator.NextOperator = roadSignsOperator; IIntersectionOperator policeOfficerOperator = new PoliceOfficerOperator(); policeOfficerOperator.NextOperator = trafficLightsOperator; IIntersectionOperator mainOperator = policeOfficerOperator; mainOperator.Operation(intersection); Console.ReadKey(); } } }
9e6376015e97b6406f9aed005ff95cb3450d11aa
C#
Aeris94/VirtualLibrary
/VirtualLibrary/Library/ConsoleLibraryPresenter.cs
3.25
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using VirtualLibrary.Books; namespace VirtualLibrary.Library { public class ConsoleLibraryPresenter : ILibraryPresenter { public void DisplayList(IEnumerable<Book> list) { if(!list.Any()) { Console.WriteLine("No results."); return; } int index = 1; StringBuilder result = new StringBuilder(); foreach (var item in list) { result.Append($"\nResult {index} "); result.Append(RecordToString(item)); index++; } Console.WriteLine(result.ToString()); } public void DisplayBorrowedBooks(IDictionary<string, int> dictionary) { StringBuilder result = new StringBuilder(); foreach (var item in dictionary) { result.AppendLine($"{item.Key} - {item.Value}" + ((item.Value == 1) ? " book" : " books")); } Console.WriteLine((result.Length == 0) ? "No results." : result.ToString()); } private string RecordToString(Book item) { return string.Format( $"\n Title: {item.Title}" + $"\n Author: {item.Author}" + $"\n Isbn: {item.Isbn}" + $"\n Last borrowed on: {item.LastBorrowedOn}" + $"\n Borrower name: {item.BorrowerName}" + "\n"); } } }
a950f2bdd5cd85a8d1bee4b048bb7500052e0042
C#
VGeorgiev1/Prog-Fundamentals-su
/DictionariesExe/LegendaryFarming/Program.cs
3.25
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LegendaryFarming { class Program { static void Main(string[] args) { Dictionary<string, int> keyMaterials = new Dictionary<string, int>(); SortedDictionary<string, long> junk = new SortedDictionary<string,long>(); string[] input = Console.ReadLine().ToLower().Split(' '); bool found = false; int remaining = 0; string legitem=""; while (true) { for (int i = 1; i <= input.Length; i += 2) { int quantity = int.Parse(input[i - 1]); if (input[i] == "fragments" || input[i] == "shards" || input[i] == "motes") { if (!keyMaterials.ContainsKey(input[i])) { keyMaterials.Add(input[i], quantity); } else { keyMaterials[input[i]] += quantity; } } else { if (!junk.ContainsKey(input[i])) { junk.Add(input[i], quantity); } else { junk[input[i]] += quantity; } } foreach (var item in keyMaterials) { if (item.Value >= 250) { if (item.Key == "fragments") { Console.WriteLine("Valanyr obtained!"); } else if (item.Key == "shards") { Console.WriteLine("Shadowmourne obtained!"); } else { Console.WriteLine("Dragonwrath obtained!"); } found = true; legitem = item.Key; remaining = item.Value - 250; break; } } if (found == true) { break; } } if (found == true) { break; } input = Console.ReadLine().ToLower().Split(' '); } keyMaterials[legitem] = remaining; bool fragFound = false; bool shardsFound = false; bool motesFound = false; foreach (var item in keyMaterials) { if (item.Key == "fragments") { fragFound = true; } if (item.Key == "motes") { motesFound = true; } if (item.Key == "shards") { shardsFound = true; } } if (fragFound == false) { keyMaterials["fragments"] = 0; } if (shardsFound == false) { keyMaterials["shards"] = 0; } if (motesFound == false) { keyMaterials["motes"] = 0; } foreach (var item in keyMaterials.OrderByDescending(x => x.Value).ThenBy(x => x.Key)) { Console.WriteLine(item.Key + ": " + item.Value); } foreach (var item in junk) { Console.WriteLine(item.Key + ": " + item.Value); } } } }
b2a9fe577d36e6766fec278ba25e4f1fa218fdd4
C#
jjzhang166/C_Sharp
/Spocteni_radu_cifry/Program.cs
3.140625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Spocteni_radu_cifry { class Program { static void Main(string[] args) { Console.Write("Zadej hodnotu: "); string vstup = Console.ReadLine(); int velicina_u_ktere_zkoumam_rad; if (int.TryParse(vstup, out velicina_u_ktere_zkoumam_rad) == false) { Console.WriteLine("Špatně zadané parametry"); Console.ReadKey(); return; } int pomocna = velicina_u_ktere_zkoumam_rad; int rad = 1; int nasobitel = 1; while (velicina_u_ktere_zkoumam_rad != 0) { if ((velicina_u_ktere_zkoumam_rad % (10 * nasobitel)) == 0) { nasobitel *= 10; rad++; } velicina_u_ktere_zkoumam_rad = velicina_u_ktere_zkoumam_rad - nasobitel; } Console.WriteLine("\tČíslo {0} je řádu: {1}", pomocna, rad); Console.ReadKey(); } } }
cb309044432b2ffc4770ad167d4c1f721f11a44f
C#
IskraNikolova/Programming-Basics
/Programming-Basic/ConditionalStatements/Problem3-CheckForAPlayCard/CheckForAPlayCard.cs
4.21875
4
using System; using System.Linq; public class CheckForAPlayCard { /// <summary> /// Classical play cards use the following signs to designate the card /// face: 2, 3, 4, 5, 6, 7, 8, 9, 10, J, Q, K and A. Write a program that enters a string /// and prints “yes” if it is a valid card sign or “no” otherwise. /// </summary> public static void Main() { string[] playCard = new[] {"2", "3", "4", "5", "6", "7", "8", "9", "10","J", "Q", "K", "A"}; string checkSymbol = Console.ReadLine(); if (playCard.Contains(checkSymbol)) { Console.WriteLine("yes"); } else { Console.WriteLine("no"); } } }
ef72d45706b5f2265606c1b5edba209145abae2a
C#
ByAlexCod/MATe
/MATeV2/ContextManager.cs
2.671875
3
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.Serialization.Formatters.Binary; using System.Text; using System.Threading; using System.Threading.Tasks; namespace MATeV2 { public class ContextAndUserManager { readonly object _lock; readonly string _companyName; Context _context; Person _currentUser; string _mail; public ContextAndUserManager(string mail) { _mail = mail; _lock = new object(); } class ContextAccessor : IContextAccessor { readonly ContextAndUserManager _m; bool _disposed; internal ContextAccessor(ContextAndUserManager manager) { _m = manager; _m.Lock(); } public Context Context { get { if (_disposed) throw new ObjectDisposedException("ContextAccessor"); return _m._context; } } public void Dispose() { _disposed = true; _m.Unlock(); } } public ContextAndUserManager( string companyName, bool withNewContext = false ) { if (string.IsNullOrWhiteSpace(companyName)) throw new ArgumentNullException(nameof(companyName)); _companyName = companyName; if (withNewContext) { _context = new Context(_companyName); } _lock = new object(); } public Person CurrentUser { get { return _currentUser; } } public IContextAccessor ObtainAccessor() { return new ContextAccessor(this); } public string CompanyName => _companyName; public string Path { get; private set; } public bool IsContextAvailable => _context != null; public LoadContextResult Load(string path) { if (string.IsNullOrWhiteSpace(path)) throw new ArgumentException(nameof(path)); if (!File.Exists(path)) { return LoadContextResult.InvalidPath; } try { using (FileStream fs = new FileStream(path, FileMode.Open)) { Context loaded = null; try { BinaryFormatter bf = new BinaryFormatter(); loaded = (Context)bf.Deserialize(fs); _context = loaded; } catch { return LoadContextResult.UnableToReadContext; } if (loaded.CompanyName != _companyName) { return LoadContextResult.CompanyNameMismatch; } Lock(); try { _context = loaded; Path = path; return LoadContextResult.Success; } finally { Unlock(); } } } catch { return LoadContextResult.UnableToOpenFile; } } public Context Context => _context; public void Save() => SaveAs(Path); public void SaveAs(string path) { Lock(); try { if (_context == null) throw new InvalidOperationException( "Context is not available." ); using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate)) { BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(fs, _context); if (Path == null) Path = path; } using (FileStream fs = new FileStream(path + "1", FileMode.OpenOrCreate)) { BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(fs, _context); if (Path == null) Path = path; } } finally { Unlock(); } } void Lock() { Monitor.Enter(_lock); } void Unlock() { Monitor.Exit(_lock); } public bool Login(string mail) { if (_context == null) { throw new ArgumentNullException("Context cannot be null.", nameof(_context)); } if (_context.Login(mail) == null) return false; else { _currentUser = _context.Login(mail); return true; } } private void RequestContext() { } } }
fed5ed4c99fa11582dd1a73c8598bed1ce8e7f05
C#
WhatNick69/VotanScripts
/ShopSystem/UserResources.cs
2.578125
3
using CraftSystem; using UnityEngine; using VotanLibraries; namespace ShopSystem { /// <summary> /// Деньги и гемы пользователя, а также /// дерево и железо (если потребуется) /// </summary> public class UserResources : MonoBehaviour { #region Переменные private PlayerStats playerStats; private static bool onLoad; public long money; public long gems; public long experience; private int gemsBonus; private int goldBonus; private int hpPoints; #endregion #region Свойства public long Money { get { return money; } set { money = value; playerStats.RefreshUserMoney(money); SaveUserResources(); } } public long Gems { get { return gems; } set { gems = value; playerStats.RefreshUserGems(gems); SaveUserResources(); } } public int GemsBonus { get { return gemsBonus; } set { gemsBonus = value; } } public int GoldBonus { get { return goldBonus; } set { goldBonus = value; } } public int HpPoints { get { return hpPoints; } set { hpPoints = value; } } #endregion /// <summary> /// ========================== Инициализация ========================== /// </summary> private void Awake() { playerStats = GameObject.Find("ImportantComponents").GetComponent<PlayerStats>(); LoadUserResources(); if (!onLoad) { DontDestroyOnLoad(this); onLoad = true; } else { Destroy(gameObject); } } /// <summary> /// Обновить ресурсы /// </summary> public void RefreshResources() { if (playerStats==null) playerStats = GameObject.Find("ImportantComponents").GetComponent<PlayerStats>(); playerStats.RefreshUserGems(gems); playerStats.RefreshUserMoney(money); hpPoints = playerStats.RefreshUserExpAndReturnHP(experience); } /// <summary> /// Достаточно ли у нас денег и золота для покупки предмета /// </summary> /// <param name="tempMoney"></param> /// <param name="tempGems"></param> /// <returns></returns> public bool IsEnoughGemNMoney(long tempMoney,long tempGems) { if ((gems-tempGems) >= 0 && (money - tempMoney) >= 0) return true; else return false; } /// <summary> /// Загрузить локальные данные /// </summary> public void LoadUserResources() { string str = PlayerPrefs.GetString("playerResources"); if (str == null || str == "") { PlayerPrefs.SetString("playerResources", "50000_50_1"); LoadUserResources(); } else { int[] resources = LibraryObjectsWorker.StringSplitter(str, '_'); money = resources[0]; gems = resources[1]; experience = resources[2]; } } /// <summary> /// Сохранить локальные данные /// </summary> /// <param name="money"></param> /// <param name="gems"></param> public void SaveUserResources(long money=0, long gems=0,long experience=0) { if (money > 0) this.money += money; if (gems > 0) this.gems += money; if (experience > 0) this.experience += experience; PlayerPrefs.SetString("playerResources", (this.money+"_"+this.gems+"_"+this.experience).ToString()); } } }
ba061a3726ac7cc3fd6d6251ee0b3d97601e66f2
C#
AlexSydorenko/progbase2
/lab3/Program.cs
3.046875
3
using System; using System.IO; namespace lab3 { class Program { static void Main(string[] args) { // ConsoleLogger: dotnet run console // ChunkPlainFileLogger: dotnet run file {directory} {maxNumOfLines} ILogger logger = null; if (args.Length == 0) { logger = new ConsoleLogger(); } else if (args.Length == 1) { if (args[0] != "console") { throw new Exception($"ERROR! Command line argument should be `console`, but not `{args[0]}`"); } logger = new ConsoleLogger(); } else if (args.Length == 3) { if (args[0] != "file") { throw new Exception($"ERROR! 2nd argument should be `file`, but have `{args[0]}`"); } if (!Directory.Exists(args[1])) { throw new Exception($"ERROR! It is non-existing directory: `{args[1]}`!"); } int maxNumOfLines = 0; if (!int.TryParse(args[2], out maxNumOfLines)) { throw new Exception("ERROR! Max number of lines in file is positive integer!"); } if (maxNumOfLines <= 0) { throw new Exception("ERROR! Max number of lines in file is positive integer!"); } logger = new ChunkPlainFileLogger(args[1], maxNumOfLines); } else { throw new Exception($"ERROR! Incorrect number of command line arguments! Should be `1` or `3`, but have `{args.Length}`"); } // ILogger logger = new ChunkPlainFileLogger("/home/alex/projects/progbase2/lab3/fileLogger/", 10); CommandUserInterface cui = new CommandUserInterface(); cui.ProcessSets(logger); } } }
5eb1ecbfb5fc411225412184d89d2fb6f860ba94
C#
SapphireGirl/JA
/JA.Logging/Models/LoggerBase.cs
2.765625
3
using System; using log4net; using WebGrease; namespace JA.Logging.Models { // In Staging/Development: Set Log Level Minimum to DEBUG // In Production: Set Log Level Minimum to WARN // ALL DEBUG INFO WARN ERROR FATAL OFF //All //DEBUG DEBUG //INFO INFO INFO //WARN WARN WARN WARN //ERROR ERROR ERROR ERROR ERROR //FATAL FATAL FATAL FATAL FATAL FATAL //OFF OFF OFF OFF OFF OFF OFF public class LoggerBase : IDisposable { //public static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); protected static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private bool _isDebugEnabled; public LoggerBase() { LogSetup(); } private void LogSetup() { //XmlConfigurator.Configure(); _isDebugEnabled = log.IsDebugEnabled; } public bool GetIsDebugEnabled() { return _isDebugEnabled; } public virtual void WriteToDebugLog(string callingClass, string message) { log.Debug($"{DateTime.Now}: {callingClass}: {message}"); } public virtual void WriteToInfoLog(string callingClass, string message) { log.Info($"{DateTime.Now}: {callingClass}: {message}"); } public virtual void WriteToWarningLog(string callingClass, string message) { log.Warn($"{DateTime.Now}: {callingClass}: {message}"); } public virtual void WriteToErrorLog(string callingClass, string message) { log.Error($"{DateTime.Now}: {callingClass}: {message}"); } public virtual void WriteToFatalLog(string callingClass, string message) { log.Fatal($"{DateTime.Now}: {callingClass}: {message}"); } public virtual void WriteToConsole(string callingClass, string message) { Console.WriteLine("Class: {0}, Message: {1} ", callingClass, message); } public virtual string GetLogFileName() { string filename = null; //IAppender[] appenders = log.Logger.Repository.GetAppenders(); //// Check each appender this logger has //foreach (IAppender appender in appenders) //{ // Type t = appender.GetType(); // // Get the file name from the first FileAppender found and return // if (t.Equals(typeof(FileAppender)) || t.Equals(typeof(RollingFileAppender))) // { // filename = ((FileAppender)appender).File; // break; // } //} return filename; } // TODO: Need to implement: check https://sourceforge.net/projects/log4net-json/ public virtual void WriteJsonObjectToLog() { throw new NotImplementedException(); } public void Dispose() { } } }
d37342203021c34c432fcc455ee7ce3d37625e89
C#
MarckRDA/Testes-Unitarios-First-Exercise-Csharp-Entra21
/Test.Exercise6/Domain/Election.cs
3.046875
3
using System; using System.Collections.Generic; using System.Linq; namespace Domain { public class Election { private List<Candidate> candidates; public IReadOnlyCollection<Candidate> Candidates => candidates; public bool CreateCandidates(List<Candidate> candidatesForElection, string passwrd) { if (passwrd == "Pa$$w0rd") { candidates = candidatesForElection; return true; } return false; } public List<string> ShowCandidates() => candidates.Select(candidate => $"Vote {candidate.Id} for candidate {candidate.Name}").ToList(); public List<Candidate> GetCandidatesByName(string name) => candidates.Where(candidate => candidate.Name == name).ToList(); public Guid GetCandidateIdByCpf(string cpf) => candidates.First(candidate => candidate.Cpf == cpf).Id; public void VoteCandidate(Guid id) { candidates.First(candidates => candidates.Id == id).Vote(); } public bool VoteCandidateByCpf(string cpf) { var selectedCandidate = candidates.FirstOrDefault(x => x.Cpf == cpf); if (selectedCandidate == null) { return false; } else { selectedCandidate.Vote(); return true; } } public int GetVotes(Guid id) => candidates.First(x => x.Id == id).Votes; public List<Candidate> ShowWinners() { var winners = new List<Candidate>() { candidates[0] }; for (int i = 1; i < candidates.Count; i++) { if (candidates[i].Votes > winners[0].Votes) { winners.Clear(); winners.Add(candidates[i]); } else if (candidates[i].Votes == winners[0].Votes) { winners.Add(candidates[i]); } } return winners; } } }
4b2064e816f0a057259384fd877addfd5dd7f423
C#
mounicadammalapati/MultiThreading
/DatabaseMultiThreadedApplication/Parallelism.cs
3.140625
3
using System; using System.Collections.Generic; using System.Text; using DatabaseMultiThreadedApplication.database; using System.Threading.Tasks; using System.Linq; namespace DatabaseMultiThreadedApplication { public class Parallelism { public Parallelism() { } public void InsertData() { var db=new librarydbContext(); var personDetails = db.PersonDetails.Skip(20000).Take(20000).ToList(); Parallel.ForEach(personDetails, (x) => { var libraryReturnValue= InsertLibrary(x.LibraryName); if(libraryReturnValue!=null) { var insertBooks= InsertBooks(x.BookName, x.LibraryName); if(insertBooks!=null) { var insertPerson = InsertPerson(x.PersonName, x.LibraryName); } } InsertPerson(x.PersonName, x.BookName); }); Console.WriteLine("End time" + DateTime.Now); Console.ReadKey(); } public Library InsertLibrary(string libraryName) { var db = new librarydbContext(); try { var libraries = db.Library.Where(x => x.Libraryname == libraryName).FirstOrDefault(); if(libraries!=null) { return libraries; } else { var library = new Library() { Librarylocation = libraryName + "insert", Libraryname=libraryName }; db.Library.Add(library); db.SaveChanges(); db.Dispose(); return library; } }catch(Exception e) { Console.WriteLine(e.Message); return null; } } public Books InsertBooks(string bookName, string libraryName) { var db = new librarydbContext(); try { var libraryId = db.Library.Where(x => x.Libraryname == libraryName).FirstOrDefault(); if(libraryId.Libraryid>0) { var book = new Books() { Bookname=bookName, Libraryid=libraryId.Libraryid }; db.Books.Add(book); db.SaveChanges(); db.Dispose(); return book; } return null; }catch(Exception e) { Console.WriteLine(e.Message); return null; } } public Person InsertPerson(string person, string bookName) { var db = new librarydbContext(); try { var book = db.Books.Where(x => x.Bookname == bookName).FirstOrDefault(); if(book.Bookid>0) { var per = new Person() { PersonName=person, Bookid=book.Bookid }; db.Person.Add(per); db.SaveChanges(); db.Dispose(); return per; } else { return null; } }catch(Exception e) { return null; } } } }
c221a1515f5f4537a16b2d35734fb84ce54234fa
C#
conwid/CosmosDbContext
/CosmosDbContext.cs
2.546875
3
using CosmosDbContext.Collection; using CosmosDbContext.Extensions; using Microsoft.Azure.Documents; using Microsoft.Azure.Documents.Client; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace CosmosDbContext { /// <summary> /// This base class represents the connection to CosmosDb /// </summary> public abstract class CosmosDbContext : IDisposable { private readonly DocumentClient client; private readonly string database; /// <summary> /// This event is fired when a LInQ query executed on the server side. /// The query SQL text is the parameter /// </summary> public event Action<string> Log { add => Subscribe(value); remove => Unsubscribe(value); } /// <summary> /// Creates a new instance of the context /// </summary> /// <param name="baseUri">Database uri (see the Azure portal for details)</param> /// <param name="authKey">Authentication key for the database (see the portal for details)</param> /// <param name="database">The name of the database</param> public CosmosDbContext(Uri baseUri, string authKey, string database) { this.client = new DocumentClient(baseUri, authKey); this.database = database; Init(); } /// <summary> /// Creates a new instance of the context /// </summary> /// <param name="baseUri">Database uri (see the Azure portal for details)</param> /// <param name="authKey">Authentication key for the database (see the portal for details)</param> /// <param name="database">The name of the database</param> public CosmosDbContext(string baseUri, string authKey, string database) : this(new Uri(baseUri), authKey, database) { } /// <summary> /// Closes the connection to the database /// </summary> public void Dispose() => client?.Dispose(); private List<PropertyInfo> GetDocumentDbRelatedProperties() => this.GetType().GetProperties().Where(p => p.PropertyType.IsGenericType && (p.GetCustomAttribute<CosmosDbCollectionAttribute>() != null)).ToList(); private void Init() { var properties = GetDocumentDbRelatedProperties(); foreach (var property in properties) { // When initializing a collection, the algorithm looks at the value specified in the attribute // If no collection name is specified, then name of the property is used var composingType = property.PropertyType.GetGenericArguments()[0]; var collectionName = property.GetCustomAttribute<CosmosDbCollectionAttribute>()?.CollectionName ?? property.Name; var collectionType = typeof(CosmosDbCollection<>).MakeGenericType(composingType); property.SetValue(this, Activator.CreateInstance(collectionType, new object[] { database, collectionName, client })); } } // The event at the context level is an "aggregate event" for all the same events at collection level private void Unsubscribe(Action<string> value) { var properties = GetDocumentDbRelatedProperties(); foreach (var property in properties) { var propValue = property.GetValue(this); propValue.GetType().GetEvent(nameof(Log)).RemoveEventHandler(propValue, value); } } private void Subscribe(Action<string> value) { var properties = GetDocumentDbRelatedProperties(); foreach (var property in properties) { var propValue = property.GetValue(this); propValue.GetType().GetEvent(nameof(Log)).AddEventHandler(propValue, value); } } // These are used for executing stored procedures protected IEnumerable<T> ExecuteStoredProcedure<T>(string storedProcName, string collectionName, params dynamic[] parameters) { var r = client.ExecuteStoredProcedureAsync<string>(UriFactory.CreateStoredProcedureUri(database, collectionName, storedProcName), parameters).Result.Response; using (JsonTextReader reader = new JsonTextReader(new StringReader(r))) { if (!reader.Read()) return new List<T>().AsQueryable(); if (reader.TokenType == JsonToken.Null || reader.TokenType == JsonToken.None || reader.TokenType == JsonToken.Undefined) return new List<T>().AsQueryable(); if (reader.TokenType == JsonToken.StartObject) return new List<T>() { JsonConvert.DeserializeObject<T>(r) }.AsQueryable(); if (reader.TokenType == JsonToken.StartArray) return JsonConvert.DeserializeObject<List<T>>(r).AsQueryable(); if (reader.TokenType == JsonToken.Boolean || reader.TokenType == JsonToken.Date || reader.TokenType == JsonToken.Float || reader.TokenType == JsonToken.Integer || reader.TokenType == JsonToken.String) return new List<T>() { JsonConvert.DeserializeObject<T>(r) }.AsQueryable(); throw new InvalidOperationException($"Token {reader.TokenType} cannot be the first token in the result"); } } protected IEnumerable<dynamic> ExecuteDynamicStoredProcedure(string storedProcName, string collectionName, params dynamic[] parameters) { var r = client.ExecuteStoredProcedureAsync<string>(UriFactory.CreateStoredProcedureUri(database, collectionName, storedProcName), parameters).Result.Response; return JsonExtensions.ReadJsonAsDynamicQueryable(r); } } }
5c78698e750f4fdac4e5d9c99d8e2452c7ade143
C#
tiagonapoli/learning-polly-dotnet
/WeatherForecast.cs
3.265625
3
using System; using System.Threading; using System.Threading.Tasks; namespace learning_polly_dotnet { public class WeatherForecast { private static readonly string[] Summaries = new[] { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" }; public static async Task<WeatherForecast> GetForecast(int day, CancellationToken ct) { Console.WriteLine("Executed GetForecast"); var rng = new Random(); await Task.Delay(500); ct.ThrowIfCancellationRequested(); return new WeatherForecast { Date = DateTime.Now.AddDays(day), TemperatureC = rng.Next(-20, 55), Summary = Summaries[rng.Next(Summaries.Length)] }; } public DateTime Date { get; set; } public int TemperatureC { get; set; } public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); public string Summary { get; set; } } }
50ad4a181de469128f4979bfdf70e98c27f83c0e
C#
Illedan/SharpNN
/SharpNetwork/TicTacToe/Game/TicTacToe.cs
3.546875
4
using System; using System.Linq; namespace TicTacToe.Game { public class TicTacToe : IGame { private static readonly int[,] possibleWins = { {0, 1, 2}, {3, 4, 5}, {6, 7, 8}, {0, 3, 6}, {1, 4, 7}, {2, 5, 8}, {0, 4, 8}, {6, 4, 2} }; private int[] board = new int[9]; public bool IsPossible(int move) => move >= 0 && move < board.Length && board[move] == 0; public void DoMove(int move, int player) { if(!IsPossible(move)) throw new Exception("Invalid input"); board[move] = player; } public void RevertMove(int move) { board[move] = 0; } public bool IsGameOver() => GetWinner() != 0 || board.All(b => b > 0); public void Reset() { board = new int[9]; } public int GetWinner() { for (var i = 0; i < possibleWins.GetLength(0); i++) { var state = GetWinner(possibleWins[i, 0], possibleWins[i, 1], possibleWins[i, 2]); if (state != 0) return state; } return 0; } private int GetWinner(int p1, int p2, int p3) { if (board[p1] == 0) return 0; if (board[p1] == board[p2] && board[p2] == board[p3]) return board[p1]; return 0; } public void PrintBoard() { for (var i = 0; i < 9; i++) { if (i % 3 == 0) { Console.WriteLine(); Console.WriteLine(); } if(board[i] == 0) Console.Write(" _"); if(board[i] == 1) Console.Write(" x"); if(board[i] == 2) Console.Write(" o"); } } public IGame Clone() { var game = new TicTacToe(); game.board = (int[])board.Clone(); return game; } public int[] GetBoard() => board; } }
de236d82dd4d01aac6c185eb3241115ddeaf9ac3
C#
tomSagala/TEAM-FRE
/Assets/Scripts/Utility/ResourceManager.cs
2.828125
3
using System; using System.Collections.Generic; using UnityEngine; public static class ResourceManager { private static Dictionary<string, Texture2D> _textures; private static Dictionary<string, GameObject> _prefabs; static ResourceManager() { _textures = new Dictionary<string, Texture2D>(); _prefabs = new Dictionary<string, GameObject>(); } public static Texture2D GetTexture(string name) { if (_textures.ContainsKey(name)) return _textures[name]; Texture2D texture = Resources.Load(name) as Texture2D; _textures.Add(name, texture); return texture; } public static GameObject GetPrefab(string name) { if (_prefabs.ContainsKey(name)) return _prefabs[name]; GameObject prefab = Resources.Load(name) as GameObject; _prefabs.Add(name, prefab); return prefab; } }
889cef7f7eaa0230364ebd11ae731f6185e7d234
C#
kadiraciktan/YoreselSozluk
/YoreselSozluk.DataAccess/Operations/EntryOperations/Commands/DeleteEntry/DeleteEntryCommand.cs
2.640625
3
using AutoMapper; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using YoreselSozluk.DataAccess.Abstract; namespace YoreselSozluk.DataAccess.Operations.EntryOperations.Commands.DeleteEntry { public class DeleteEntryCommand { private readonly IContext _context; private readonly IMapper _mapper; public int EntryId { get; set; } public DeleteEntryCommand(IContext context, IMapper mapper) { _context = context; _mapper = mapper; } public void Handle() { var entry = _context.Entries.FirstOrDefault(x => x.Id == EntryId); if (entry is null) throw new InvalidOperationException("Entry Bulunamadı"); _context.Entries.Remove(entry); _context.SaveChanges(); } } }
fd28fc946e6c846808f80b7a8ba3d9a9bc5cfa62
C#
firament/fsap-utils-1706
/EntityMetadataClassGen/MDGenerator.cs
2.546875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using NLog; namespace fsap.EntityMetadataClassGen { public enum ReturnStatus // Value maps directly to return status { OK = 0, FILE_EXISTS = 1, SRC_ROOT_NO_ACCESS = 2, DEST_DIR_NO_ACCESS = 3, TEMPLATE_MISSING = 4, TEMPLATE_FORMAT_BAD = 5, SRC_FILE_NO_ACCESS = 6, SRC_FILE_READ_ERR = 7, SRC_FILE_PROCESS_ERR = 8, SOURCE_DATA_ERR = 9, DEST_FILE_WRITE_ERR = 10, UNKNOWN = 99 } public class InputData : IDisposable { public string SourceRootFolder { get; set; } public string DestinationFolder { get; set; } public string AnnotationNameSpaceSegment { get; set; } = @"Annotations"; public string MetaDataClassSuffix { get; set; } = @"_Metadata"; public string MetaDataFileTemplate { get; set; } = @"MDTemplate.txt"; public string PropertyPadLeft { get; set; } = "\t"; //@" "; public InputData(){} public void Dispose(){/* Nothing to be done*/} } class MDGenerator { static NLog.Logger log = NLog.LogManager.GetCurrentClassLogger(); private const string MC_KEY_NSPACE = @"namespace "; private const string MC_KEY_CLASS = @" public partial class "; private const string MC_KEY_PROP = @" public "; private const string MC_KEY_PROP_SKIP = @" public virtual "; private const string MC_DEF_TEMPLATE = @"MDTemplate.txt"; private const string MC_DEF_ATTR_DISP = "{1}[Display(Name = \"{0}\")]"; public MDGenerator(){} public static int? Generate(InputData poInput) { // Validation // input readable // output writable // log.Debug("START public static int? Generate(InputData poInput)"); int liRetVal = -1; string lsTemplateFile = string.Empty; string lsText = string.Empty; InputDataEx loInput = new InputDataEx(poInput); // Write out output recieved log.Info("Using INPUT DATA: _________ "); log.Info(" SourceRootFolder = '" + loInput.SourceRootFolder + "'"); log.Info(" DestinationFolder = '" + loInput.DestinationFolder + "'"); log.Info(" MetaDataClassSuffix = '" + loInput.MetaDataClassSuffix + "'"); log.Info("AnnotationNameSpaceSegment = '" + loInput.AnnotationNameSpaceSegment + "'"); log.Info(" MetaDataFileTemplate = '" + loInput.MetaDataFileTemplate + "'"); log.Info(" PropertyPadLeft = '" + loInput.PropertyPadLeft + "'"); log.Info(" DestinationRoot = '" + loInput.DestinationRoot + "'"); log.Info(" NameSpaceTag = '" + loInput.NameSpaceTag + "'"); log.Info(" NameSpaceAnnnoteTag = '" + loInput.NameSpaceAnnnoteTag + "'"); log.Info(" ClassNameTag = '" + loInput.ClassNameTag + "'"); log.Info(" MetaClassSfxTag = '" + loInput.MetaClassSfxTag + "'"); log.Info(" BodyTag = '" + loInput.BodyTag + "'"); log.Info(""); if (string.IsNullOrWhiteSpace(loInput.MetaDataFileTemplate)) { lsTemplateFile = MC_DEF_TEMPLATE; } else if (File.Exists(loInput.MetaDataFileTemplate)) { lsTemplateFile = loInput.MetaDataFileTemplate; } // If it is filename, get the contents if (!string.IsNullOrWhiteSpace(lsTemplateFile)) { try { lsText = File.ReadAllText(lsTemplateFile); if (!string.IsNullOrWhiteSpace(lsText)) { loInput.MetaDataFileTemplate = lsText; } else { liRetVal = (int)ReturnStatus.TEMPLATE_MISSING; } } catch (Exception Ex) { log.Error("Unable to get Template"); liRetVal = (int)ReturnStatus.TEMPLATE_MISSING; } } // Check if all tags exist in the template lsText = loInput.MetaDataFileTemplate; if ( (liRetVal <= 0) && (lsText.Contains(loInput.NameSpaceTag)) && (lsText.Contains(loInput.NameSpaceAnnnoteTag)) && (lsText.Contains(loInput.ClassNameTag)) && (lsText.Contains(loInput.MetaClassSfxTag)) && (lsText.Contains(loInput.BodyTag)) ) { // TAGS ARE GOOD } else { log.Error("TEMPLATE DATA IS UNUSABLE"); liRetVal = (int)ReturnStatus.TEMPLATE_FORMAT_BAD; } if (liRetVal > 0) { return liRetVal; } // All GOOD, process now DateTime ldtStart = DateTime.Now, ldtFinish; // Report processing time ExecuteStatus ES = ProcessFolder(loInput); ldtFinish = DateTime.Now; liRetVal = (int)ES.ExitStatus; // Write out summary log.Info("Processing Summary:"); log.Info("Files Total : " + ES.FilesTotal); log.Info("in Folders : " + ES.FoldersTotal); log.Info("Processed : " + ES.FilesGenerated); log.Info("Started at : " + ldtStart.ToString("HH:mm:ss.ffff")); log.Info("Finished at : " + ldtFinish.ToString("HH:mm:ss.ffff")); log.Info("Took (mS) : " + ldtFinish.Subtract(ldtStart).TotalMilliseconds); return liRetVal; } private static ExecuteStatus ProcessFolder(InputDataEx poInput) { ExecuteStatus voES, loES = new ExecuteStatus() { FoldersTotal = 1 }; log.Info(KEYS.FOLDER_NAME_LOG, poInput.SourceRootFolder); // Process all CS files foreach (string vsFilePath in Directory.EnumerateFiles(poInput.SourceRootFolder, "*.cs")) { voES = ProcessFile(poInput, Path.GetFileName(vsFilePath)); // Pass only file name, need to getit again later loES.FilesTotal++; if (voES.ExitStatus == ReturnStatus.OK) { loES.FilesGenerated += voES.FilesGenerated; } else { // add message to list loES.Messages.AppendLine(voES.Message); loES.Messages.AppendLine(voES.Messages.ToString()); } } // foreach (string vsFilePath in Dir // Process all Subfolders string lsDestFolder = poInput.DestinationFolder; // Remember stsrting folder, to POP foreach (string vSubDir in Directory.EnumerateDirectories(poInput.SourceRootFolder)) { // if same as target dir, skip if (vSubDir == poInput.DestinationRoot) { log.Info(KEYS.SKIP_DESTINATION, vSubDir); loES.Messages.AppendFormat(KEYS.SKIP_DESTINATION, vSubDir); loES.Messages.AppendLine(); continue; } // PUSH the subfolder poInput.SourceRootFolder = vSubDir; poInput.DestinationFolder = Path.Combine(lsDestFolder, Path.GetFileName(vSubDir)); // Call ourself, treating this as root voES = ProcessFolder(poInput); if (voES.ExitStatus == ReturnStatus.OK) { // Update counts for the report loES.FilesTotal += voES.FilesTotal; loES.FoldersTotal += voES.FoldersTotal; loES.FilesGenerated += voES.FilesGenerated; } else { // add messages to list. See if Enumeration is needed loES.Messages.AppendLine(voES.Messages.ToString()); } } // foreach (string vSubDir in Dir loES.ExitStatus = ReturnStatus.OK; return loES; } private static ExecuteStatus ProcessFile(InputDataEx poInput, string psSourceFileName) { bool lbHasError = false; ExecuteStatus ES = new ExecuteStatus(); string lsEntityNameSpace = null; string lsEntityClassName = null; string lsEntityBody = null; string lsAllLines = string.Empty; string lsText; int lsIndex = 0, lsLinesDone = 0; string[] lasTokens; char[] lacSplits = { ' ' }; StringBuilder lsbProps = new StringBuilder(); log.Info(KEYS.FILE_NAME_LOG, psSourceFileName, poInput.SourceRootFolder); // Check if file exists, we dont want to overwrite customized code if (File.Exists(Path.Combine(poInput.DestinationFolder, psSourceFileName))) { log.Debug("\tFile Exist in destination, Not processing."); ES.ExitStatus = ReturnStatus.FILE_EXISTS; ES.Message = psSourceFileName; ES.Messages.AppendLine("File Exists, skipping. " + psSourceFileName); return ES; } try { foreach (string lsLine in File.ReadAllLines(Path.Combine(poInput.SourceRootFolder, psSourceFileName))) { lbHasError = false; // reset for each loop, we dont want carry-overs lsLinesDone++; if (lsLine.StartsWith(MC_KEY_NSPACE)) { lsText = lsLine.Split(' ')[1] ?? string.Empty; // drop any comments after namespace lbHasError = string.IsNullOrWhiteSpace(lsText); if (lbHasError) { // create error note and exit } else { lsEntityNameSpace = lsText.Trim(); log.Debug("lsEntityNameSpace = {0}", lsEntityNameSpace); } } else if (lsLine.StartsWith(MC_KEY_CLASS)) { lsIndex = 0; lsText = lsLine.Remove(0, MC_KEY_CLASS.Length); lbHasError = string.IsNullOrWhiteSpace(lsText); if (lbHasError) { // create error note and exit } else { lsIndex = lsText.IndexOf(" "); if (lsIndex > 0) { lsText = lsText.Substring(0, lsIndex); } lsEntityClassName = lsText.Trim(); log.Debug("lsEntityClassName = {0}", lsEntityClassName); } } else if (lsLine.StartsWith(MC_KEY_PROP) && lsLine.Contains("{")) // Quick fix, identify constructor properly { if (lsLine.StartsWith(MC_KEY_PROP_SKIP)) continue; // Ignore reference keys lsbProps.AppendLine(); // need an blank line above to add annotations // Also add default attribute to all properties, using property name lasTokens = lsLine.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); lsbProps.AppendFormat(MC_DEF_ATTR_DISP, lasTokens[2], "\t\t\t"); lsbProps.AppendLine(); lsbProps.AppendLine(poInput.PropertyPadLeft + lsLine.Replace(" ", "\t")); log.Debug("lsLine (Property) = {0}", lsLine); } if (lbHasError) { // process errors for caller to get log.Error(lsLine); ES.Messages.AppendLine("Error Processing line"); ES.Messages.AppendLine(lsLine); ES.Messages.AppendLine("of File > " + psSourceFileName); //break; // analyze errors to see if any code fix needed continue; } } // foreach (string lsLine in log.Info("Lines Processed = {0}", lsLinesDone); lsEntityBody = lsbProps.ToString(); } catch (Exception Ex) { log.Error(Ex, psSourceFileName); ES.ExitStatus = ReturnStatus.SRC_FILE_PROCESS_ERR; ES.Message = psSourceFileName; } // Verify all tags have data if ( string.IsNullOrWhiteSpace(lsEntityNameSpace) || string.IsNullOrWhiteSpace(lsEntityClassName) || string.IsNullOrWhiteSpace(lsEntityBody) ) { log.Error(KEYS.DATA_MISSING); log.Error("lsEntityNameSpace = {0}", lsEntityNameSpace); log.Error("lsEntityClassName = {0}", lsEntityClassName); log.Error("lsEntityBody = \n{0}", lsEntityBody); ES.ExitStatus = ReturnStatus.SOURCE_DATA_ERR; ES.Message = psSourceFileName; return ES; } //log.Debug("Replacing placeholders in template"); //log.Debug("{0} -> {1}", poInput.NameSpaceTag, lsEntityNameSpace); //log.Debug("{0} -> {1}", poInput.NameSpaceAnnnoteTag, poInput.AnnotationNameSpaceSegment); //log.Debug("{0} -> {1}", poInput.ClassNameTag, lsEntityClassName); //log.Debug("{0} -> {1}", poInput.MetaClassSfxTag, poInput.MetaDataClassSuffix); //// log.Debug("{0} -> {1}", poInput.BodyTag, lsEntityBody); // log.Debug("INSPECT OUTPUT FOR CORRECTNESS"); // Process the template lsEntityBody = poInput.MetaDataFileTemplate .Replace(poInput.NameSpaceTag, lsEntityNameSpace) .Replace(poInput.NameSpaceAnnnoteTag, poInput.AnnotationNameSpaceSegment) .Replace(poInput.ClassNameTag, lsEntityClassName) .Replace(poInput.MetaClassSfxTag, poInput.MetaDataClassSuffix) .Replace(poInput.BodyTag, lsEntityBody) ; // Does destination exist? Create if needed, // do check just before write to avoid creating empty folders if (!Directory.Exists(poInput.DestinationFolder)) { DirectoryInfo vNewDir = null; try { vNewDir = Directory.CreateDirectory(poInput.DestinationFolder); } catch (Exception eX) { // log the error } // Check Again, to see if it is created if (!Directory.Exists(poInput.DestinationFolder)) { log.Error(KEYS.DEST_FOLDER_NOACCESS, poInput.DestinationFolder); ES.ExitStatus = ReturnStatus.DEST_DIR_NO_ACCESS; ES.Message = poInput.DestinationFolder; return ES; } } // if (!Directory.Exists(poInput.DestinationFolder)) try { File.WriteAllText(Path.Combine(poInput.DestinationFolder, psSourceFileName), lsEntityBody); ES.FilesGenerated++; ES.ExitStatus = ReturnStatus.OK; } catch (Exception Ex) { log.Error(Ex, psSourceFileName); ES.ExitStatus = ReturnStatus.DEST_FILE_WRITE_ERR; ES.Message = psSourceFileName; } return ES; } /**********************************************************************************************************/ /* HELPER FUNCTIONS /**********************************************************************************************************/ /* * * PRIVATE CLASSES FOR FUNCTIONALITY * */ private class KEYS { // log.Debug("[ FOLDER ]" + lsText); public const string FOLDER_NAME_LOG = @"[ FOLDER ] {0}"; public const string FILE_NAME_LOG = @"[ FILE ] {0} in {1}"; public const string DEST_FOLDER_NOACCESS = @"Unable to Create Destination Folder '{0}'"; public const string DATA_MISSING = @"Data for all tags is not availaible, aborting."; public const string SKIP_DESTINATION = @"[Not Processing] Destination Folder '{0}'"; public const string D = @""; public const string E = @""; public const string F = @""; public const string G = @""; public const string H = @""; public const string I = @""; } private class InputDataEx : InputData { public string DestinationRoot { get; set; } public string NameSpaceTag { get; set; } = @"${ENTITY_NAME_SPACE}"; public string NameSpaceAnnnoteTag { get; set; } = @"${ANNOTATION_NAME_SPACE}"; public string ClassNameTag { get; set; } = @"${ENTITY_CLASS_NAME}"; public string MetaClassSfxTag { get; set; } = @"${METADATA_CLASS_SUFFIX}"; public string BodyTag { get; set; } = @"${ENTITY_BODY}"; public InputDataEx(){} public InputDataEx(InputData pIData) { SourceRootFolder = pIData.SourceRootFolder; DestinationFolder = pIData.DestinationFolder; DestinationRoot = pIData.DestinationFolder; AnnotationNameSpaceSegment = pIData.AnnotationNameSpaceSegment; MetaDataClassSuffix = pIData.MetaDataClassSuffix; MetaDataFileTemplate = pIData.MetaDataFileTemplate; PropertyPadLeft = pIData.PropertyPadLeft; } } private class ExecuteStatus : IDisposable { public ReturnStatus ExitStatus { get; set; } = ReturnStatus.UNKNOWN; public int ExceptionCount { get; set; } = 0; public string Message { get; set; } public StringBuilder Messages { get; set; } = new StringBuilder(); public string ExceptionData { get; set; } // For summary reporting public int FilesTotal { get; set; } = 0; public int FoldersTotal { get; set; } = 0; public int FilesGenerated { get; set; } = 0; public ExecuteStatus():base(){} public void Dispose() {/* Nothing to be done*/} } } }
9a5d5291cc7bc763cb9d4ee3c0134de145f7086a
C#
Motivesoft/MotiveLogger
/MotiveLogger/DefaultLogger.cs
3.328125
3
namespace MotiveLogger { /// <summary> /// Generic API for logging services /// </summary> public abstract class DefaultLogger : Logger { protected DefaultLogger(string name) { Name = name; LogLevel = LogManager.DefaultLogLevel; } ~DefaultLogger() { } /// <summary> /// Log a message at the specified log level /// </summary> /// <param name="level">The log level</param> /// <param name="message">The text of the message</param> protected abstract void Log(LogLevel level, string message); /// <summary> /// Log a formatted message at the specified log level /// </summary> /// <param name="level">The log level</param> /// <param name="format">the message format</param> /// <param name="args">the values to insert into the format string</param> protected abstract void Log(LogLevel level, string format, params object[] args); /// <summary> /// Log an error message /// </summary> /// <param name="message">The text of the message</param> virtual public void Error(string message) { if( LogLevel.ERROR <= LogLevel ) { Log(LogLevel.ERROR, message); } } /// <summary> /// Log an error message with a formatted string and values. /// <para>If the last of <code>args</code> is a <code>System.Exception</code> then the logger may elect to record /// the exception's stacktrace.</para> /// </summary> /// <param name="format">the message format</param> /// <param name="args">the values to insert into the format string</param> virtual public void Error(string format, params object[] args) { if (LogLevel.ERROR <= LogLevel) { Log(LogLevel.ERROR, format, args); } } /// <summary> /// Log an warning message /// </summary> /// <param name="message">The text of the message</param> virtual public void Warning(string message) { if (LogLevel.WARN <= LogLevel) { Log(LogLevel.WARN, message); } } /// <summary> /// Log a warning message with a formatted string and values. /// <para>If the last of <code>args</code> is a <code>System.Exception</code> then the logger may elect to record /// the exception's stacktrace.</para> /// </summary> /// <param name="format">the message format</param> /// <param name="args">the values to insert into the format string</param> virtual public void Warning(string format, params object[] args) { if (LogLevel.WARN <= LogLevel) { Log(LogLevel.WARN, format, args); } } /// <summary> /// Log an information message /// </summary> /// <param name="message">The text of the message</param> virtual public void Info(string message) { if (LogLevel.INFO <= LogLevel) { Log(LogLevel.INFO, message); } } /// <summary> /// Log an information message with a formatted string and values. /// <para>If the last of <code>args</code> is a <code>System.Exception</code> then the logger may elect to record /// the exception's stacktrace.</para> /// </summary> /// <param name="format">the message format</param> /// <param name="args">the values to insert into the format string</param> virtual public void Info(string format, params object[] args) { if (LogLevel.INFO <= LogLevel) { Log(LogLevel.INFO, format, args); } } /// <summary> /// Log a debug message /// </summary> /// <param name="message">The text of the message</param> virtual public void Debug(string message) { if (LogLevel.DEBUG <= LogLevel) { Log(LogLevel.DEBUG, message); } } /// <summary> /// Log a debug message with a formatted string and values. /// <para>If the last of <code>args</code> is a <code>System.Exception</code> then the logger may elect to record /// the exception's stacktrace.</para> /// </summary> /// <param name="format">the message format</param> /// <param name="args">the values to insert into the format string</param> virtual public void Debug(string format, params object[] args) { if (LogLevel.DEBUG <= LogLevel) { Log(LogLevel.DEBUG, format, args); } } /// <summary> /// The name of the logger /// </summary> public string Name { get; private set; } /// <summary> /// The current log level /// </summary> public LogLevel LogLevel { get; set; } } }
2cfaef40da702cae2aee5b81570bdd5c7d7d44d8
C#
meian/relational-lock
/src/RelationalLock.Process/RelationalLockManager.cs
2.6875
3
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; namespace RelationalLock { /// <summary> /// Lock control instance by in process model. /// </summary> public class RelationalLockManager : IRelationalLockManager { private readonly TimeSpan defaultExpireIn; private readonly TimeSpan defaultTimeout; private readonly ImmutableDictionary<string, LockContainer> lockMap; private int disposed; internal RelationalLockManager(RelationalLockConfigurator configurator) { var infos = configurator.GetInfos(); var semaphoreMap = infos .SelectMany(info => info.LockKeys) .Distinct() .ToDictionary(lockKey => lockKey, lockKey => new NamedSemaphore(lockKey)); lockMap = infos.ToImmutableDictionary( info => info.Key, info => new LockContainer(info.Key, info.LockKeys.Select(key => semaphoreMap[key]))); AvailableKeys = lockMap.Keys.OrderBy(_ => _).ToImmutableArray(); defaultTimeout = configurator.DefaultTimeout; defaultExpireIn = configurator.DefaultExpireIn; } /// <summary> /// destructor /// </summary> ~RelationalLockManager() { Dispose(false); } /// <summary> /// Acquire a lock on key and related keys. /// </summary> /// <param name="key">key for locking</param> /// <param name="timeout">timeout for requesting acquirement</param> /// <param name="expireIn">expire period for acquired lock</param> /// <returns>true if acquired lock, false if timeout</returns> public bool AcquireLock(string key, TimeSpan? timeout = null, TimeSpan? expireIn = null) { CheckIsDisposed(); IsValidKey(key); var timeoutAt = (timeout ?? defaultTimeout).FromNowAt(); var expireInCorrected = expireIn != null ? expireIn.Value.Correct() : defaultExpireIn; return lockMap[key].Acquire(timeoutAt, expireInCorrected); } /// <summary> /// Acquire a lock on key and related keys. /// </summary> /// <param name="key">key for locking</param> /// <param name="timeout">timeout for requesting acquirement</param> /// <param name="expireAt">expiration for acquired lock</param> /// <returns>true if acquired lock, false if timeout</returns> public bool AcquireLock(string key, TimeSpan timeout, DateTime? expireAt = null) => AcquireLock(key, timeout, expireAt != null ? expireAt.Value.FromNow() : defaultExpireIn); /// <summary> /// Acquire a lock on key and related keys. /// </summary> /// <param name="key">key for locking</param> /// <param name="timeoutMilliseconds">timeout milliseconds for requesting acquirement</param> /// <param name="expireInMilliseconds">expire period milliseconds for acquired lock</param> /// <returns>true if acquired lock, false if timeout</returns> public bool AcquireLock(string key, int timeoutMilliseconds, int? expireInMilliseconds = null) { var timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds); var expireIn = expireInMilliseconds != null ? TimeSpan.FromMilliseconds(expireInMilliseconds.Value) : defaultExpireIn; return AcquireLock(key, timeout, expireIn); } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() => Dispose(true); /// <summary> /// Get all locking information on managed keys. /// </summary> /// <returns>locking information list</returns> public Dictionary<string, LockStateInfo> GetAllStates() => AvailableKeys.ToDictionary(key => key, GetState); /// <summary> /// Get locking information. /// </summary> /// <param name="key">key for locking information</param> /// <returns>locking information</returns> public LockStateInfo GetState(string key) { CheckIsDisposed(); IsValidKey(key); return lockMap[key].GetState(); } /// <summary> /// Release the lock by key. /// </summary> /// <param name="key">key for releasing lock</param> public void Release(string key) { IsValidKey(key); if (lockMap.TryGetValue(key, out var lockEntry)) { lockEntry.Release(); } } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> /// <param name="disposing">if true, call from <see cref="Dispose()"/></param> protected virtual void Dispose(bool disposing) { if (Interlocked.Exchange(ref disposed, 1) != 0) { return; } foreach (var lockObject in lockMap.Values) { lockObject.Dispose(); } if (disposing) { lockMap.Clear(); AvailableKeys = Array.Empty<string>(); } } private void CheckIsDisposed() { if (disposed != 0) { throw new ObjectDisposedException("disposable item"); } } private void IsValidKey(string key) { if (lockMap.ContainsKey(key) == false) { throw new ArgumentOutOfRangeException(nameof(key), $"not registered key: {key}"); } } /// <summary> /// List of keys available for locking. /// </summary> public IEnumerable<string> AvailableKeys { get; private set; } } }
90d59100ea368de6ebdc307aca5eb04e909e5302
C#
ILya-Lev/Codility.Solution
/Codility.Solvers/MinAvgTwoSlice.cs
2.875
3
using System; namespace Codility.Solvers { public class MinAvgTwoSlice { public int MinAverageSlice(int[] input) { var total = (input[0]+input[1])/2.0; var sliceStart = 0; for (int i = 1; i < input.Length-1; i++) { for (int j = 2; j < input.Length; j++) { } } return 0; } } }
1a6b8b2ecee64b3dd8ad0256c52a46bc14eb51a0
C#
AArnott/MessagePack-CSharp
/src/MessagePack.UnityClient/Assets/Scripts/Tests/ShareTests/DictionaryTest.cs
2.6875
3
// Copyright (c) All contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Xunit; namespace MessagePack.Tests { public class DictionaryTest { private T Convert<T>(T value) { return MessagePackSerializer.Deserialize<T>(MessagePackSerializer.Serialize(value)); } public static object[][] DictionaryTestData = new object[][] { new object[] { new Dictionary<int, int>() { { 1, 100 } }, null }, new object[] { new ReadOnlyDictionary<int, int>(new Dictionary<int, int>() { { 1, 100 } }), null }, new object[] { new SortedList<int, int>() { { 1, 100 } }, null }, new object[] { new SortedDictionary<int, int>() { { 1, 100 } }, null }, }; [Theory] [MemberData(nameof(DictionaryTestData))] public void DictionaryTestAll<T>(T x, T y) { this.Convert(x).IsStructuralEqual(x); this.Convert(y).IsStructuralEqual(y); } [Fact] public void InterfaceDictionaryTest() { var a = (IDictionary<int, int>)new Dictionary<int, int>() { { 1, 100 } }; var b = (IReadOnlyDictionary<int, int>)new Dictionary<int, int>() { { 1, 100 } }; var c = (IDictionary<int, int>)null; var d = (IReadOnlyDictionary<int, int>)null; this.Convert(a).IsStructuralEqual(a); this.Convert(b).IsStructuralEqual(b); this.Convert(c).IsStructuralEqual(c); this.Convert(d).IsStructuralEqual(d); } [Fact] public void ConcurrentDictionaryTest() { var cd = new ConcurrentDictionary<int, int>(); cd.TryAdd(1, 100); cd.TryAdd(2, 200); cd.TryAdd(3, 300); ConcurrentDictionary<int, int> conv = this.Convert(cd); conv[1].Is(100); conv[2].Is(200); conv[3].Is(300); cd = null; this.Convert(cd).IsNull(); } } }
ea1ed408dfdcfd547323edc8df82deea8749385b
C#
itabas016/onepiece
/src/OnePiece.Framework.SubSonic.Extension/Extensions/DbContextExtension.cs
2.65625
3
using OnePiece.Framework.Core; using SubSonic.Query; using SubSonic.Schema; using SubSonic.SqlGeneration.Schema; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; namespace OnePiece.Framework.SubSonic { public static class DbContextExtension { public static IQueryable<T> All<T>(this IDbContext dbContext) where T : EntityBase, new() { return dbContext.DbContext.All<T>(); } /// <summary> /// This method will return one queryable result instead of a result data after executing the sql text command. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="dbContext"></param> /// <param name="expression"></param> /// <returns></returns> public static IQueryable<T> Where<T>(this IDbContext dbContext, Expression<Func<T, bool>> expression) where T : EntityBase, new() { return dbContext.DbContext.All<T>().Where<T>(expression); } public static IList<T> Where<T>(this IDbContext dbContext, Expression<Func<T, bool>> dbSearchExpression, Predicate<T> inMemorySearchExpression) where T : EntityBase, new() { var resultSet = dbContext.DbContext.Find<T>(dbSearchExpression); if (resultSet != null) { return resultSet.ToList().FindAll(inMemorySearchExpression); } return new List<T>(); } /// <summary> /// Be careful to use this method if the table has lots of records. /// If you want to filter by the expression, you can try Where<T> method. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="dbContext"></param> /// <param name="expression"></param> /// <returns></returns> public static IList<T> All<T>(this IDbContext dbContext, Expression<Func<T, bool>> expression) where T : EntityBase, new() { return dbContext.DbContext.Find<T>(expression); } /// <summary> /// Get entity by Id /// </summary> /// <typeparam name="T"></typeparam> /// <param name="dbContext"></param> /// <param name="id"></param> /// <returns>Will return null if the entity with the id does not exist.</returns> public static T Single<T>(this IDbContext dbContext, int id) where T : EntityBase, new() { return dbContext.DbContext.Single<T>(id); } /// <summary> /// Get one entity by condition. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="dbContext"></param> /// <param name="expression"></param> /// <returns></returns> public static T Single<T>(this IDbContext dbContext, Expression<Func<T, bool>> expression) where T : EntityBase, new() { return dbContext.DbContext.Single<T>(expression); } /// <summary> /// Add the entity to db. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="dbContext"></param> /// <param name="model"></param> /// <param name="addedAction"></param> /// <returns></returns> public static object Add<T>(this IDbContext dbContext, T model, Action<T> addedAction = null) where T : EntityBase, new() { if (model != null) { model.CreatedDate = DateTime.Now; var ret = dbContext.DbContext.Add<T>(model); if (addedAction != null) { addedAction(model); } return ret; } return default(T); } public static void Add<T>(this IDbContext dbContext, IEnumerable<T> models) where T : EntityBase, new() { dbContext.DbContext.AddMany<T>(models); } public static int Update<T>(this IDbContext dbContext, T model, Action<T> updatedAction) where T : EntityBase, new() { var ret = dbContext.DbContext.Update<T>(model); if (updatedAction != null) { updatedAction(model); } return ret; } public static int Update<T>(this IDbContext dbContext, T model, bool getOrigin = true) where T : EntityBase, new() { if (model != null) { if (getOrigin) { var origin = dbContext.Single<T>(model.Id); if (origin != null) { model.LastModifiedDate = DateTime.Now; model.CreatedDate = origin.CreatedDate; return dbContext.DbContext.Update<T>(model); } } else { model.LastModifiedDate = DateTime.Now; return dbContext.DbContext.Update<T>(model); } } return -1; } public static int Update<T>(this IDbContext dbContext, IEnumerable<T> models) where T : EntityBase, new() { if (models != null && models.Any()) { foreach (var model in models) { model.LastModifiedDate = DateTime.Now; } return dbContext.DbContext.UpdateMany<T>(models); } return -1; } public static int Delete<T>(this IDbContext dbContext, int id, Action deletedAction = null) where T : EntityBase, new() { var ret = dbContext.DbContext.Delete<T>(id); if (deletedAction != null) deletedAction(); return ret; } public static int Delete<T>(this IDbContext dbContext, IEnumerable<T> models) where T : EntityBase, new() { return dbContext.DbContext.DeleteMany<T>(models); } public static int Delete<T>(this IDbContext dbContext, Expression<Func<T, bool>> expression) where T : EntityBase, new() { return dbContext.DbContext.DeleteMany<T>(expression); } public static bool Exists<T>(this IDbContext context, Expression<Func<T, bool>> expression) where T : EntityBase, new() { return context.DbContext.Exists<T>(expression); } public static IList<T> Find<T>(this IDbContext context, Expression<Func<T, bool>> expression) where T : EntityBase, new() { return context.DbContext.Find<T>(expression); } public static PagedList<T> GetPaged<T>(this IDbContext context, int pageIndex, int pageSize) where T : EntityBase, new() { return context.DbContext.GetPaged<T>(pageIndex, pageSize); } public static PagedList<T> GetPaged<T>(this IDbContext context, string sortBy, int pageIndex, int pageSize) where T : EntityBase, new() { return context.DbContext.GetPaged<T>(sortBy, pageIndex, pageSize); } /// </summary> /// <typeparam name="T"></typeparam> /// <param name="context"></param> /// <returns></returns> public static int Truncate<T>(this IDbContext context) where T : EntityBase, new() { var provider = SqlQuery.GetProvider(context.ConnectionStringName); var tableName = typeof(T).Name; var tblAttri = typeof(T).GetCustomAttributes(typeof(SubSonicTableNameOverrideAttribute), false).FirstOrDefault() as SubSonicTableNameOverrideAttribute; if (tblAttri != null) { tableName = tblAttri.TableName; } var sqlCmd = string.Empty; switch (provider.Name.ToLower()) { case "mysql.data.mysqlclient": sqlCmd = string.Format("truncate table {0};", tableName); break; default: sqlCmd = string.Format("IF OBJECT_ID('{0}') IS NOT NULL truncate table [{0}]", tableName); break; } var queryCommand = new QueryCommand(sqlCmd, provider); var ret = 0; try { ret = provider.ExecuteQuery(queryCommand); } catch { } return ret; } public static int Count<T>(this IDbContext context) where T : EntityBase, new() { var provider = SqlQuery.GetProvider(context.ConnectionStringName); var tableName = typeof(T).Name; var tblAttri = typeof(T).GetCustomAttributes(typeof(SubSonicTableNameOverrideAttribute), false).FirstOrDefault() as SubSonicTableNameOverrideAttribute; if (tblAttri != null) { tableName = tblAttri.TableName; } var sqlCmd = string.Format("SELECT COUNT(*) FROM {0}", tableName); var queryCommand = new QueryCommand(sqlCmd, provider); var result = provider.ExecuteDataSet(queryCommand); int count = 0; if (result != null) { if (result.Tables.Count >= 0 && result.Tables[0].Rows.Count >= 0 && result.Tables[0].Rows[0].ItemArray.Length >= 0) { int.TryParse(result.Tables[0].Rows[0][0].ToString(), out count); } } return count; } public static List<T> Top<T, TOrder>(this IDbContext dbContext, int topCount, Expression<Func<T, bool>> where, bool isDesc, params Expression<Func<T, TOrder>>[] orderByColumnExps) where T : EntityBase, new() { var result = dbContext.DbContext.All<T>().Where<T>(where); if (result != null) { var isFirst = true; foreach (var orderByColumnExp in orderByColumnExps) { if (isFirst) { result = isDesc ? result.OrderByDescending(orderByColumnExp) : result.OrderBy(orderByColumnExp); isFirst = false; } else { result = isDesc ? ((IOrderedQueryable<T>)result).ThenByDescending(orderByColumnExp) : ((IOrderedQueryable<T>)result).ThenBy(orderByColumnExp); } } result = result.Take(topCount); return result.ToList(); } else { return new List<T>(); } } public static T Save<T>(this IDbContext dbContext, Expression<Func<T, bool>> expression, T model) where T : EntityBase, new() { var existed = dbContext.DbContext.Single<T>(expression); if (existed == null) { dbContext.DbContext.Add<T>(model); } else { model.LastModifiedDate = DateTime.Now; model.Id = existed.Id; dbContext.DbContext.Update<T>(model); } return model; } public static IList<T> SelectByIds<T>(this IDbContext dbContext, IEnumerable<int> ids, string tblName, string colName, int queryCount = 30) where T : new() { var ret = new List<T>(); if (ids != null && ids.Any()) { var totalCount = ids.Count(); var batches = totalCount / queryCount + 1; for (int i = 0; i < batches; i++) { var skipCount = i * queryCount; var idStr = ids.Skip(skipCount).Take(50).Concatenate(x => x.ToString()); var models = dbContext.Execute<T>(@"select * from {1} where {2} in ({0})".FormatWith(idStr, tblName, colName)); ret.AddRange(models); } } return ret; } /// <summary> /// Get to know what it is, MySql or ms sql? /// </summary> /// <param name="dbContext"></param> /// <returns></returns> public static DbType GetDbType(this IDbContext dbContext) { var type = DbType.MSSql; if (dbContext != null) { type = DbContextFactory.GetDbType(dbContext.ConnectionStringName); } return type; } } }
099c701e8e9fb472a49fadb262715d1b4b0ab775
C#
sam210723/moRFctrl
/moRFctrl/Tools.cs
2.984375
3
using System; using System.Linq; namespace moRFctrl { /// <summary> /// Common methods used in multiple classes /// </summary> static class Tools { /// <summary> /// Output string to console /// </summary> public static void Log(string s) { Console.WriteLine(s); } /// <summary> /// Output string to console only if debug output is enabled /// </summary> public static void Debug(string s) { if (Program.debugOutput) { Console.WriteLine(s); } } public static bool ValidateIPv4(string ip) { if (String.IsNullOrWhiteSpace(ip)) { return false; } string[] splitValues = ip.Split('.'); if (splitValues.Length != 4) { return false; } byte tempForParsing; return splitValues.All(r => byte.TryParse(r, out tempForParsing)); } } }
37ed4f88276c8803db18271cc4c65862378c899f
C#
pollubnet/WalkaChomika2016
/WalkaChomika2016/Models/Frog.cs
2.515625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WalkaChomika.Models { class FrogSentry : Animal { public FrogSentry() { Name = "Żaba Strażnik"; HP = 10; Damage = 2; Mana = 0; Agility = 2; } public override int Fight() { return Attack(); } } }
0a02a6219ed9283fcbd5ab28ab73e36236cb2f41
C#
baidarka/BizUnit
/Src/BizUnit.Core/TestBuilder/StepValidationException.cs
2.921875
3
 using System; namespace BizUnit.Core.TestBuilder { /// <summary> /// TestStepExecutionException is thrown by BizUnit to indicate a validation step failed. /// </summary> /// <remarks>The ValidationStepExecutionException is thrown by BizUnit when a validation step fails, the /// framework automatically wraps the exception thrown by the validaiton step with an /// TestStepExecutionException</remarks> public class StepValidationException : Exception { private readonly TestStepBase _testStep; /// <summary> /// TestStepExecutionException constructor. /// </summary> /// <param name="message">The message associated with this exception.</param> /// <param name="testStep">The name of the BizUnit test step being validated.</param> public StepValidationException(string message, TestStepBase testStep) : base(message) { _testStep = testStep; } /// <summary> /// The name of the test step /// </summary> public string TestStepName { get { return _testStep.GetType().ToString(); } } } }
b3a7966accdaf09b05f04cf1a112a20f96607a09
C#
shendongnian/download4
/first_version_download2/409579-35791072-112386000-2.cs
2.734375
3
public enum MyEnum { Val1, Val2, } public class TestDefine { public string MyEnumPropSerialize { get { if (MyEnumProp.HasValue) { return MyEnumProp.ToString(); } return null; } set { MyEnum importValue; if (Enum.TryParse<MyEnum>(value, out importValue)) { MyEnumProp = importValue; }else { MyEnumProp.ToString(); } } } [XmlIgnore] public MyEnum? MyEnumProp { get; set; } }
db4b5a28e9d71daba0d6338a1a179dc9c9641404
C#
Fullance/space-egineers-API
/SE-2/VRage.Math/VRageMath/MatrixI.cs
2.734375
3
namespace VRageMath { using System; using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential)] public struct MatrixI { public Base6Directions.Direction Right; public Base6Directions.Direction Up; public Base6Directions.Direction Backward; public Vector3I Translation; public Base6Directions.Direction Left { get => Base6Directions.GetFlippedDirection(this.Right); set { this.Right = Base6Directions.GetFlippedDirection(value); } } public Base6Directions.Direction Down { get => Base6Directions.GetFlippedDirection(this.Up); set { this.Up = Base6Directions.GetFlippedDirection(value); } } public Base6Directions.Direction Forward { get => Base6Directions.GetFlippedDirection(this.Backward); set { this.Backward = Base6Directions.GetFlippedDirection(value); } } public Base6Directions.Direction GetDirection(Base6Directions.Direction direction) { switch (direction) { case Base6Directions.Direction.Backward: return this.Backward; case Base6Directions.Direction.Left: return this.Left; case Base6Directions.Direction.Right: return this.Right; case Base6Directions.Direction.Up: return this.Up; case Base6Directions.Direction.Down: return this.Down; } return this.Forward; } public void SetDirection(Base6Directions.Direction dirToSet, Base6Directions.Direction newDirection) { switch (dirToSet) { case Base6Directions.Direction.Forward: this.Forward = newDirection; return; case Base6Directions.Direction.Backward: this.Backward = newDirection; return; case Base6Directions.Direction.Left: this.Left = newDirection; return; case Base6Directions.Direction.Right: this.Right = newDirection; return; case Base6Directions.Direction.Up: this.Up = newDirection; return; case Base6Directions.Direction.Down: this.Down = newDirection; return; } } public Vector3I RightVector { get => Base6Directions.GetIntVector(this.Right); set { this.Right = Base6Directions.GetDirection(value); } } public Vector3I LeftVector { get => Base6Directions.GetIntVector(this.Left); set { this.Left = Base6Directions.GetDirection(value); } } public Vector3I UpVector { get => Base6Directions.GetIntVector(this.Up); set { this.Up = Base6Directions.GetDirection(value); } } public Vector3I DownVector { get => Base6Directions.GetIntVector(this.Down); set { this.Down = Base6Directions.GetDirection(value); } } public Vector3I BackwardVector { get => Base6Directions.GetIntVector(this.Backward); set { this.Backward = Base6Directions.GetDirection(value); } } public Vector3I ForwardVector { get => Base6Directions.GetIntVector(this.Forward); set { this.Forward = Base6Directions.GetDirection(value); } } public MatrixI(ref Vector3I position, Base6Directions.Direction forward, Base6Directions.Direction up) { this.Translation = position; this.Right = Base6Directions.GetFlippedDirection(Base6Directions.GetLeft(up, forward)); this.Up = up; this.Backward = Base6Directions.GetFlippedDirection(forward); } public MatrixI(Vector3I position, Base6Directions.Direction forward, Base6Directions.Direction up) { this.Translation = position; this.Right = Base6Directions.GetFlippedDirection(Base6Directions.GetLeft(up, forward)); this.Up = up; this.Backward = Base6Directions.GetFlippedDirection(forward); } public MatrixI(Base6Directions.Direction forward, Base6Directions.Direction up) : this(Vector3I.Zero, forward, up) { } public MatrixI(ref Vector3I position, ref Vector3I forward, ref Vector3I up) : this(ref position, Base6Directions.GetDirection(ref forward), Base6Directions.GetDirection(ref up)) { } public MatrixI(ref Vector3I position, ref Vector3 forward, ref Vector3 up) : this(ref position, Base6Directions.GetDirection(ref forward), Base6Directions.GetDirection(ref up)) { } public MatrixI(MyBlockOrientation orientation) : this(Vector3I.Zero, orientation.Forward, orientation.Up) { } public MyBlockOrientation GetBlockOrientation() => new MyBlockOrientation(this.Forward, this.Up); public Matrix GetFloatMatrix() => Matrix.CreateWorld(new Vector3(this.Translation), Base6Directions.GetVector(this.Forward), Base6Directions.GetVector(this.Up)); public static MatrixI CreateRotation(Base6Directions.Direction oldA, Base6Directions.Direction oldB, Base6Directions.Direction newA, Base6Directions.Direction newB) { MatrixI xi = new MatrixI { Translation = Vector3I.Zero }; Base6Directions.Direction cross = Base6Directions.GetCross(oldA, oldB); Base6Directions.Direction newDirection = Base6Directions.GetCross(newA, newB); xi.SetDirection(oldA, newA); xi.SetDirection(oldB, newB); xi.SetDirection(cross, newDirection); return xi; } public static void Invert(ref MatrixI matrix, out MatrixI result) { result = new MatrixI(); switch (matrix.Right) { case Base6Directions.Direction.Forward: result.Backward = Base6Directions.Direction.Left; break; case Base6Directions.Direction.Backward: result.Backward = Base6Directions.Direction.Right; break; case Base6Directions.Direction.Up: result.Up = Base6Directions.Direction.Right; break; case Base6Directions.Direction.Down: result.Up = Base6Directions.Direction.Left; break; default: result.Right = matrix.Right; break; } switch (matrix.Up) { case Base6Directions.Direction.Forward: result.Backward = Base6Directions.Direction.Down; break; case Base6Directions.Direction.Backward: result.Backward = Base6Directions.Direction.Up; break; case Base6Directions.Direction.Left: result.Right = Base6Directions.Direction.Down; break; case Base6Directions.Direction.Right: result.Right = Base6Directions.Direction.Up; break; default: result.Up = matrix.Up; break; } switch (matrix.Backward) { case Base6Directions.Direction.Left: result.Right = Base6Directions.Direction.Forward; break; case Base6Directions.Direction.Right: result.Right = Base6Directions.Direction.Backward; break; case Base6Directions.Direction.Up: result.Up = Base6Directions.Direction.Backward; break; case Base6Directions.Direction.Down: result.Up = Base6Directions.Direction.Forward; break; default: result.Backward = matrix.Backward; break; } Vector3I.TransformNormal(ref matrix.Translation, ref result, out result.Translation); result.Translation = -result.Translation; } public static void Multiply(ref MatrixI leftMatrix, ref MatrixI rightMatrix, out MatrixI result) { Vector3I vectori4; Vector3I vectori5; Vector3I vectori6; result = new MatrixI(); Vector3I rightVector = leftMatrix.RightVector; Vector3I upVector = leftMatrix.UpVector; Vector3I backwardVector = leftMatrix.BackwardVector; Vector3I.TransformNormal(ref rightVector, ref rightMatrix, out vectori4); Vector3I.TransformNormal(ref upVector, ref rightMatrix, out vectori5); Vector3I.TransformNormal(ref backwardVector, ref rightMatrix, out vectori6); Vector3I.Transform(ref leftMatrix.Translation, ref rightMatrix, out result.Translation); result.RightVector = vectori4; result.UpVector = vectori5; result.BackwardVector = vectori6; } public static MyBlockOrientation Transform(ref MyBlockOrientation orientation, ref MatrixI transform) { Base6Directions.Direction forward = transform.GetDirection(orientation.Forward); return new MyBlockOrientation(forward, transform.GetDirection(orientation.Up)); } } }
5c21ba55c066b4f2b3b8e1016d60b0a471ab5a52
C#
LazyTarget/Lux
/src/Lux/IO/Helpers/PathSorter.cs
3.125
3
using System.Collections.Generic; namespace Lux.IO { public class PathSorter : IComparer<string> { public int Compare(string x, string y) { var c = PathHelper.Compare(x, y); if (c == 0) return 0; c = 0; var xParts = PathHelper.GetPathParts(x); var yParts = PathHelper.GetPathParts(y); var xPath = ""; var yPath = ""; var lengthC = xParts.Length.CompareTo(yParts.Length); for (var i = 0; true ; i++) { if (lengthC != 0) { if (i >= xParts.Length) return lengthC; if (i >= yParts.Length) return lengthC; } if (c != 0) return c; xPath = PathHelper.Combine(xPath, xParts[i]); yPath = PathHelper.Combine(yPath, yParts[i]); c = PathHelper.Compare(xPath, yPath); } return 0; } } }
b813b54de28e3c63cf3a486676e6a3ab34862836
C#
vinanti/Skills
/DSA/Coding/AQueue03_QueueUsage.cs
3.78125
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Coding { class AQueue03_QueueUsage { public static void Main01() { // 1. Initialize a queue. Queue<int> q = new Queue<int>(); // 2. Get the first element - return null if queue is empty. if(q.Count==0) Console.WriteLine("Queue is empty"); else Console.WriteLine("The first element is: " + q.Peek()); // 3. Push new element. q.Enqueue(5); q.Enqueue(13); q.Enqueue(8); q.Enqueue(6); // 4. Pop an element. q.Dequeue(); // 5. Get the first element. Console.WriteLine("The first element is: " + q.Peek()); // 7. Get the size of the queue. Console.WriteLine("The size is: " + q.Count); } } }
0b5a068a385817100e2e5b77de60898063b428d7
C#
shendongnian/download4
/code1/178120-3369806-7007843-2.cs
2.859375
3
public class MyClass { public int Value { get { Console.WriteLine("Value called"); return 3; } } }
e107e766149789c16b456cc28a6e441c0751c8ff
C#
dotnet/dotnet-api-docs
/snippets/csharp/System.Threading.Tasks/Task/WhenAll/whenall2.cs
3.171875
3
// <Snippet2> using System; using System.Collections.Generic; using System.Threading.Tasks; public class Example { public static void Main() { var tasks = new Task<long>[10]; for (int ctr = 1; ctr <= 10; ctr++) { int delayInterval = 18 * ctr; tasks[ctr - 1] = Task.Run(async () => { long total = 0; await Task.Delay(delayInterval); var rnd = new Random(); // Generate 1,000 random numbers. for (int n = 1; n <= 1000; n++) total += rnd.Next(0, 1000); return total; } ); } var continuation = Task.WhenAll(tasks); try { continuation.Wait(); } catch (AggregateException) {} if (continuation.Status == TaskStatus.RanToCompletion) { long grandTotal = 0; foreach (var result in continuation.Result) { grandTotal += result; Console.WriteLine("Mean: {0:N2}, n = 1,000", result/1000.0); } Console.WriteLine("\nMean of Means: {0:N2}, n = 10,000", grandTotal/10000); } // Display information on faulted tasks. else { foreach (var t in tasks) Console.WriteLine("Task {0}: {1}", t.Id, t.Status); } } } // The example displays output like the following: // Mean: 506.38, n = 1,000 // Mean: 501.01, n = 1,000 // Mean: 505.36, n = 1,000 // Mean: 492.00, n = 1,000 // Mean: 508.36, n = 1,000 // Mean: 503.99, n = 1,000 // Mean: 504.95, n = 1,000 // Mean: 508.58, n = 1,000 // Mean: 490.23, n = 1,000 // Mean: 501.59, n = 1,000 // // Mean of Means: 502.00, n = 10,000 // </Snippet2>
ca07b4450f2ca6ba2ecc122e08c86fdb2e65488d
C#
arulface/Sameer
/DataMigration/DataMigration/SqlConnector.cs
2.515625
3
using DataMigration.Model; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DataMigration { public class SqlConnector : IConnection { private readonly DBProperties _dbProperties; public SqlConnector(string dbPropertiesJson) { _dbProperties = JsonConvert.DeserializeObject<DBProperties>(dbPropertiesJson); } public void CloseConnection(object connectionObject) { (connectionObject as SqlConnection).Close(); } public bool ExecuteNonQuery(object connectionObject, string query) { throw new NotImplementedException(); } public DataSet GetMultipleResultSet(object connectionObject, string query) { throw new NotImplementedException(); } public object OpenConnection() { string connectionString = string.Format("Data Source={0};Initial Catalog={1};Integrated Security=true;", _dbProperties.Server, _dbProperties.Database); SqlConnection connection = new SqlConnection(connectionString); connection.Open(); return connection; } } }
a06c098f2a2e55ff62ce6f75cd6c4f05b62594b2
C#
tools81/PnPVisualator
/Controls/DisplayTypes/ActionDisplay.cs
2.578125
3
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; namespace Pen_and_Paper_Visualator.Controls { public partial class ActionDisplay : UserControl { public static string ActionName { get; set; } //public static string Image { get; set; } public static string Extended { get; set; } public static string Success { get; set; } public static DataTable Data { get; set; } public static DataTable Contested { get; set; } public ActionDisplay() { InitializeComponent(); lblName.Text = ActionName; lblExtended.Text = Extended; lblSuccess.Text = Success; gridDetails.DataSource = Data; gridDetails.Columns[0].Width = 90; gridDetails.Columns[1].Width = 115; gridDetails.Columns[2].Width = 40; if (Contested.Rows.Count < 1) gridContested.Visible = false; else { gridContested.DataSource = Contested; gridContested.Columns[0].Width = 70; gridContested.Columns[1].Width = 80; gridContested.Columns[2].Width = 95; } int sum = 0; for (int i = 0; i < gridDetails.Rows.Count; ++i) { sum += Convert.ToInt32(gridDetails.Rows[i].Cells[2].Value); } lblTotal.Text = sum.ToString(); } } }
bd3440542daf7f7ea6a80e9a0962ec97bb8e903b
C#
chris-rogala/Tutorials.AzureFunctions
/src/Tutorials.AzureFunctions.DependencyInjection/Extensions/ConfigurationExtensions.cs
2.671875
3
using Microsoft.Extensions.Configuration; using System; using System.Linq; using System.Security.Cryptography.X509Certificates; namespace Tutorials.AzureFunctions.DependencyInjection.Extensions { public static class ConfigurationExtensions { private const string _clientThumbprint = "clientThumbprint"; public static X509Certificate2 GetClientCert(this IConfiguration configuration) { using (X509Store str = new X509Store()) { str.Open(OpenFlags.ReadOnly); X509Certificate2 result = str.Certificates .OfType<X509Certificate2>() .FirstOrDefault(x => x.Thumbprint.ToUpper().Trim() == configuration[_clientThumbprint]?.ToUpper()?.Trim()); str.Close(); return result; } } } }
c83b4ac8606504fd402ea940ad24c7aebcbfe235
C#
RendijsSmukulis/netBencodeReader
/netBencodeReader/netBencodeReader/InternalDeser/Deserializer.cs
2.828125
3
namespace netBencodeReader.InternalDeser { using System; using System.Diagnostics; using netBencodeReader.Types; using netBencodeReader.Tokenizer; public class Deserializer { public BEBaseObject GetBaseObject(BencodeReader reader) { if (reader.ReadState == ReadState.Initial) { reader.Read(); } this.AssertReaderState(reader); switch (reader.TokenType) { case BencodeToken.StartDictionary: var dict = this.GetDictionary(reader); Debug.WriteLine(dict); return dict; case BencodeToken.String: var str = this.GetByteString(reader); Debug.WriteLine(str); return str; case BencodeToken.Integer: var num = this.GetNumber(reader); Debug.WriteLine(num); return num; case BencodeToken.StartArray: var arr = this.GetList(reader); Debug.WriteLine(arr); return arr; } throw new Exception("TBD"); } public BEByteString GetByteString(BencodeReader reader) { this.AssertReaderState(reader); if (reader.TokenType != BencodeToken.String) { throw new Exception("TBD"); } var result = new BEByteString(reader.TokenByteStringValue); // Advance to the next token reader.Read(); return result; } public BENumber GetNumber(BencodeReader reader) { this.AssertReaderState(reader); if (reader.TokenType != BencodeToken.Integer) { throw new Exception("TBD"); } var result = new BENumber(reader.TokenStringValue); // Advance to the next token reader.Read(); return result; } public BEList GetList(BencodeReader reader) { this.AssertReaderState(reader); if (reader.TokenType != BencodeToken.StartArray) { throw new Exception("TBD"); } var list = new BEList(); // Advance past "StartArray" token reader.Read(); while (reader.TokenType != BencodeToken.EndArray) { var value = this.GetBaseObject(reader); list.Add(value); } // Pop off the EndArray reader.Read(); return list; } public BEDictionary GetDictionary(BencodeReader reader) { this.AssertReaderState(reader); if (reader.TokenType != BencodeToken.StartDictionary) { throw new Exception("TBD"); } var dict = new BEDictionary(); reader.Read(); while (reader.TokenType != BencodeToken.EndDictionary) { if (reader.TokenType != BencodeToken.DictionaryKey) { throw new Exception("TBD"); } var key = new BEByteString(reader.TokenByteStringValue); reader.Read(); var value = this.GetBaseObject(reader); dict.Add(key, value); } // Pop off the EndDictionary reader.Read(); return dict; } private void AssertReaderState(BencodeReader reader) { if (reader.ReadState != ReadState.Initial && reader.ReadState != ReadState.InProgress) { throw new Exception("TBD"); } } } }
ba0189cec4b431ef803b7217a4104450843697d0
C#
Petermarcu/Projects
/Pi/Raspberry.System/Timers/Timer.cs
3.25
3
#region References using System; using System.Threading; #endregion namespace Raspberry.Timers { /// <summary> /// Provides access to timing features. /// </summary> public static class Timer { #region Methods /// <summary> /// Creates a timer. /// </summary> /// <returns>The timer.</returns> /// <remarks> /// The created timer is the most suitable for the current platform. /// </remarks> public static ITimer Create() { return Board.Current.IsRaspberryPi ? (ITimer) new HighResolutionTimer() : new StandardTimer(); } /// <summary> /// Sleeps during the specified time. /// </summary> /// <param name="time">The time.</param> public static void Sleep(TimeSpan time) { if (time.TotalMilliseconds < 0) return; if (Board.Current.IsRaspberryPi) HighResolutionTimer.Sleep(time); else Thread.Sleep(time); } #endregion } }
909a3f48fb27605b86fe0e9b1bbab945d687e98d
C#
ByteKnightUNF/ClassroomConnectionSystem
/CCS2.0/DataLibrary/BusinessLogic/PhotoProccesor.cs
2.6875
3
using DataLibrary.DataAccess; using DataLibrary.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.SqlClient; using System.IO; namespace DataLibrary.BussinessLogic { public static class PhotoProccesor { public static int CreatePhoto(string Name, string Email, int SchoolYearBegin, int SchoolYearEnd , string Grade, string TeacherName, Byte[] ImageFile) { ImageModel data = new ImageModel { Name = Name, Email = Email, SchoolYearBegin = SchoolYearBegin, SchoolYearEnd = SchoolYearEnd, Grade = Grade, TeacherName = TeacherName, ImageFile = ImageFile }; string sql = @"insert into dbo.Image (Name, Email, SchoolYearBegin, SchoolYearEnd, Grade, TeacherName, ImageFile) values (@Name, @Email, @SchoolYearBegin, @SchoolYearEnd, @Grade, @TeacherName, @ImageFile );"; return SqlDataAccess.SaveData(sql, data); } public static int recordTag(int ImageId, Byte[] TagFile, int Tag) { TagModel data = new TagModel { ImageId = ImageId, TagFile = TagFile, Tag = Tag }; string sql = @"update dbo.Image " + "SET NumberOfPeople = @Tag, TaggedPhoto = @TagFile " + "where ImageId = @ImageId;"; return SqlDataAccess.SaveData(sql, data); } public static int recordGallery(int ImageId, Byte[] ImageFile) { GalleryModel data = new GalleryModel { ImageId = ImageId, ImageFile = ImageFile, }; string sql = @"insert into dbo.Gallery (ImageId, ImageFile) values(@ImageId, @ImageFile); "; return SqlDataAccess.SaveData(sql, data); } public static int CreateComment(string Comment, string Name, Boolean Flag, int ImageId) { CommentModel data = new CommentModel { Comment = Comment, Names = Name, Flag = Flag, ImageId = ImageId, CommentDate = DateTime.Today }; string sql = @"insert into dbo.Comment (Comment, Names, Flag, ImageId, CommentDate) values (@Comment, @Names, @Flag, @ImageId, @CommentDate);"; return SqlDataAccess.SaveData(sql, data); } public static int CreateTag(int ImageId, int Tag, string Name ) { AddingTagModel data = new AddingTagModel { ImageId = ImageId, Tag = Tag, Name = Name }; string sql = @"insert into dbo.Tag (ImageId, Tag, Name) values (@ImageId, @Tag, @Name);"; return SqlDataAccess.SaveData(sql, data); } public static List<ImageModel> GetPhotoId(int ImageId) { var parameters = new { ImageId = ImageId }; string sql = @"select * from dbo.Image Where ImageId = @ImageId ;"; return SqlDataAccess.LoadData<ImageModel>(sql, parameters); } public static int Edit_Image(int ImageId, string Name, string Email, int SchoolYearBegin, int SchoolYearEnd, string Grade, string TeacherName) { ImageModel data = new ImageModel { ImageId = ImageId, Name = Name, Email = Email, SchoolYearBegin = SchoolYearBegin, SchoolYearEnd = SchoolYearEnd, Grade = Grade, TeacherName = TeacherName }; string sql = @"update dbo.Image Set Name = @Name, Email = @Email, SchoolYearBegin = @SchoolYearBegin, SchoolYearEnd = @SchoolYearEnd, Grade = @Grade, TeacherName = @TeacherName where ImageId = @ImageId;"; return SqlDataAccess.SaveData(sql, data); } public static List<AddingTagModel> getTag() { string sql = @"select * from dbo.Tag;"; return SqlDataAccess.LoadData<AddingTagModel>(sql); } public static List<AddingTagModel> getTagId(int ImageId) { var parameters = new { ImageId = ImageId }; string sql = @"select * from dbo.Tag Where ImageId = @ImageId ;"; return SqlDataAccess.LoadData<AddingTagModel>(sql, parameters); } public static int GetPages(int ImageId) { var parameters = new { ImageId = ImageId }; string sql = @"SELECT count(*) FROM dbo.Comment Where ImageId = @ImageId;"; var page = SqlDataAccess.LoadData<int>(sql, parameters)[0]; return page; } public static int GetPages() { string sql = @"SELECT count(*) FROM dbo.Comment;"; var page = SqlDataAccess.LoadData<int>(sql)[0]; return page; } public static List<CommentModel> GetCommentId(int ImageId, int PageNumber) { var parameters = new { ImageId = ImageId, PageNumber = PageNumber, RowOfPage = 5 }; string sql = @"select * from dbo.Comment Where ImageId = @ImageId ORDER BY CommentId DESC OFFSET (@PageNumber-1)*@RowOfPage ROWS FETCH NEXT @RowOfPage ROWS ONLY;"; return SqlDataAccess.LoadData<CommentModel>(sql, parameters); } public static List<CommentModel> GetComment(int ImageId) { var parameters = new { ImageId = ImageId }; string sql = @"select * from dbo.Comment Where CommentId = @ImageId ;"; return SqlDataAccess.LoadData<CommentModel>(sql, parameters); } public static List<ImageModel> FindImg(string ImageId) { var parameters = new { ImageId = ImageId }; string sql = @"select * from dbo.Image Where Name Like '%'+@ImageId+'%' OR Email Like '%'+@ImageId+'%'" + "OR SchoolYearBegin Like '%'+@ImageId+'%' OR SchoolYearEnd Like '%'+@ImageId+'%'" + "OR Grade Like '%'+@ImageId+'%' OR TeacherName Like '%'+@ImageId+'%';"; return SqlDataAccess.LoadData<ImageModel>(sql, parameters); } public static List<ImageModel> FindTag(string ImageId) { var parameters = new { ImageId = ImageId }; string sql = @"select * from dbo.Image Where Name Like '%'+@ImageId+'%' OR Email Like '%'+@ImageId+'%'" + "OR SchoolYearBegin Like '%'+@ImageId+'%' OR SchoolYearEnd Like '%'+@ImageId+'%'" + "OR Grade Like '%'+@ImageId+'%' OR NumberOfPeople Like '%'+@ImageId+'%' OR TeacherName Like '%'+@ImageId+'%';"; return SqlDataAccess.LoadData<ImageModel>(sql, parameters); } public static List<CommentModel> FindCom(string search, int PageNumber) { var parameters = new { Search = search, PageNumber = PageNumber, RowOfPage = 15 }; string sql = @"select * from dbo.Comment "+ "Where Names Like '%'+@Search+'%' OR Comment Like '%'+@Search+'%' "+ "ORDER BY CommentId DESC " + "OFFSET (@PageNumber-1)*@RowOfPage ROWS " + "FETCH NEXT @RowOfPage ROWS ONLY;"; return SqlDataAccess.LoadData<CommentModel>(sql, parameters); } public static List<CommentModel> FindComi(string search, int id, int PageNumber) { var parameters = new { Search = search, ImageId = id, PageNumber = PageNumber, RowOfPage = 5 }; string sql = @"select * from dbo.Comment "+ "Where ImageId = @ImageId AND (Names Like '%'+@Search+'%' OR Comment Like '%'+@Search+'%') "+ "ORDER BY CommentId DESC "+ "OFFSET (@PageNumber-1)*@RowOfPage ROWS " + "FETCH NEXT @RowOfPage ROWS ONLY;"; return SqlDataAccess.LoadData<CommentModel>(sql, parameters); } public static int GetPagesSearchCom(string search) { var parameters = new { Search = search }; string sql = @"SELECT count(*) FROM dbo.Comment Where Names Like '%'+@Search+'%' OR Comment Like '%'+@Search+'%';"; var page = SqlDataAccess.LoadData<int>(sql, parameters)[0]; return page; } public static int GetPagesSearch(int ImageId, string search) { var parameters = new { ImageId = ImageId, Search = search }; string sql = @"SELECT count(*) FROM dbo.Comment Where ImageId = @ImageId AND (Names Like '%'+@Search+'%' OR Comment Like '%'+@Search+'%');"; var page = SqlDataAccess.LoadData<int>(sql, parameters)[0]; return page; } public static List<ImageModel> LoadPhoto() { string sql = @"select * from dbo.Image Order by SchoolYearBegin ASC ;"; return SqlDataAccess.LoadData<ImageModel>(sql); } public static List<GalleryModel> GetGallery(int ImageId) { GalleryModel data = new GalleryModel { ImageId = ImageId }; string sql = @"select * from dbo.Gallery where ImageId = @ImageId;"; return SqlDataAccess.LoadData<GalleryModel>(sql, data); } public static List<CommentModel> LoadComment(int page, int row = 10) { var parameters = new { PageNumber = page, RowOfPage = row }; string sql = @"select CommentId, Comment, Names, Flag, ImageId, CommentDate from dbo.Comment ORDER BY CommentId DESC OFFSET (@PageNumber-1)*@RowOfPage ROWS FETCH NEXT @RowOfPage ROWS ONLY;"; return SqlDataAccess.LoadData<CommentModel>(sql, parameters); } public static int RemoveImage(int ImageId) { ImageModel data = new ImageModel { ImageId = ImageId }; string sql = @"DELETE FROM dbo.Image WHERE ImageId= @ImageId; DELETE FROM dbo.Comment WHERE ImageId= @ImageId;"; return SqlDataAccess.SaveData(sql, data); } public static int RemoveTag(int ImageId) { ImageModel data = new ImageModel { ImageId = ImageId }; string sql = @"Update dbo.Image set NumberOfPeople = NULL , TaggedPhoto = NULL WHERE ImageId= @ImageId; Delete From dbo.Tag WHERE ImageId= @ImageId; "; return SqlDataAccess.SaveData(sql, data); } public static int DeleteComment(int Id) { CommentModel data = new CommentModel { CommentId = Id }; string sql = @"DELETE FROM dbo.Comment WHERE CommentId= @CommentId;"; return SqlDataAccess.SaveData(sql, data); } public static int Edit_Comment(int Id, string Comment, string Name, bool Flag, int ImageId) { CommentModel data = new CommentModel { CommentId = Id, Comment = Comment, Names = Name, Flag = Flag, ImageId = ImageId }; string sql = @"UPDATE dbo.Comment SET Comment = @Comment, Names = @Names, Flag = @Flag WHERE CommentId= @CommentId;"; return SqlDataAccess.SaveData(sql, data); } public static int Edit_Tag(int ImageId, int Tag, string Name) { AddingTagModel data = new AddingTagModel { ImageId = ImageId, Tag = Tag, Name = Name }; string sql = @"UPDATE dbo.Tag SET Name = @Name WHERE ImageId = @ImageId AND Tag = @Tag;"; return SqlDataAccess.SaveData(sql, data); } public static List<CommentModel> FlaggedComment() { string sql = @"select * from dbo.Comment Where Flag = 1;"; return SqlDataAccess.LoadData<CommentModel>(sql); } public static int FlagCount() { string sql = @"SELECT count(*) FROM dbo.Comment Where Flag = 1;"; var page = SqlDataAccess.LoadData<int>(sql)[0]; return page; } public static List<CommentModel> Sort(string option, int page) { var parameters = new { PageNumber = page, RowOfPage = 15 }; string sql = ""; if (option == "a") { sql = @"select * from dbo.Comment ORDER BY Names ASC OFFSET (@PageNumber-1)*@RowOfPage ROWS FETCH NEXT @RowOfPage ROWS ONLY;"; } else if (option == "d") { sql = @"select * from dbo.Comment ORDER BY Names DESC OFFSET (@PageNumber-1)*@RowOfPage ROWS FETCH NEXT @RowOfPage ROWS ONLY;"; } else if (option == "n") { sql = @"select * from dbo.Comment ORDER BY CommentId DESC OFFSET (@PageNumber-1)*@RowOfPage ROWS FETCH NEXT @RowOfPage ROWS ONLY;"; } else if (option == "o") { sql = @"select * from dbo.Comment ORDER BY CommentId ASC OFFSET (@PageNumber-1)*@RowOfPage ROWS FETCH NEXT @RowOfPage ROWS ONLY;"; } return SqlDataAccess.LoadData<CommentModel>(sql, parameters); } public static int CreateFlag(int Id, string Rea) { FlagModel data = new FlagModel { CommentId = Id, Reason = Rea }; string sql = @"insert into dbo.FlaggedComments (CommentId, Reason) values (@CommentId, @Reason);"; return SqlDataAccess.SaveData(sql, data); } public static int Flag(int Id, bool flag) { CommentModel data = new CommentModel { CommentId = Id, Flag = flag }; string sql = @"UPDATE dbo.Comment SET Flag = @Flag WHERE CommentId= @CommentId;"; return SqlDataAccess.SaveData(sql, data); } public static List<FlagModel> GetReason(int Id) { var parameters = new { Id = Id }; string sql = @"select * from dbo.FlaggedComments Where CommentId = @Id;"; return SqlDataAccess.LoadData<FlagModel>(sql, parameters); } public static int DeleteFlag(int Id) { FlagModel data = new FlagModel { CommentId = Id }; string sql = @"DELETE FROM dbo.FlaggedComments WHERE CommentId= @CommentId;"; return SqlDataAccess.SaveData(sql, data); } } }
bcf74a5a1775bcac3f6c64f187a248b0be7e4c0b
C#
VelizarVeli/SoftUni-Software-Engineering
/02.C#Fundamentals/03.OOPAdvanced/05.Generics/08.CustomListSorter/CustomList.cs
3.46875
3
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; public class CustomList<T> : ICustomList<T>, IEnumerable<T> where T : IComparable<T> { private const int Initialcapacity = 16; private T[] data; private int length; private IEnumerable<T> myList; public CustomList() { data = new T[Initialcapacity]; this.myList = new List<T>(); } public IEnumerable<T> Data => this.myList; public void Add(T element) { if (this.length == this.data.Length) { this.data = this.data.Concat(new T[this.length]).ToArray(); } this.data[this.length] = element; this.length++; } public T Remove(int index) { var element = this.data[index]; this.data = this.data.Take(index).Concat(this.data.Skip(index + 1)).ToArray(); this.length--; return element; } public bool Contains(T element) { if (this.length == 0) { return false; } var comparer = EqualityComparer<T>.Default; foreach (var item in this.data) { if (comparer.Equals(item, element)) { return true; } } return false; } public void Swap(int index1, int index2) { var temp = this.data[index1]; this.data[index1] = this.data[index2]; this.data[index2] = temp; } public int CountGreaterThan(T element) { var counter = 0; foreach (var currentElement in this.data) { if (element.CompareTo(currentElement) < 0) { counter++; } } return counter; } public T Max() { return this.data.Max(); } public T Min() { return this.data.Min(); } public IEnumerable<T> MyList { get; } public void Sort() { this.data = this.data .Take(this.length) .OrderBy(x => x) .Concat(new T[this.data.Length - this.length]) .ToArray(); } public IEnumerator<T> GetEnumerator() { return this.data.Take(this.length).GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return this.data.Take(this.length).GetEnumerator(); } public override string ToString() { var sb = new StringBuilder(); foreach (var element in this.Data) { sb.AppendLine(element.ToString()); } return sb.ToString().Trim(); } }
fe96030d2f135206641c4fae258476852d9104dd
C#
Morebis-GIT/CI
/xggameplanAPI/src/domain/ImagineCommunications.GamePlan.Domain/AutoBookApi/InstanceConfiguration/Objects/AutoBookInstanceConfigurarionCriteria.cs
3.0625
3
using System; namespace ImagineCommunications.GamePlan.Domain.AutoBookApi.InstanceConfiguration.Objects { /// <summary> /// Single criteria for an AutoBook to be suitable to be able to execute run /// /// The importance of the factors starting with most important is breaks, campaigns. /// </summary> public class AutoBookInstanceConfigurationCriteria { public int? MaxDays { get; set; } public int? MaxSalesAreas { get; set; } public int? MaxDemographics { get; set; } public int? MaxCampaigns { get; set; } public int? MaxBreaks { get; set; } /// <summary> /// Whether run parameters meet this criteria /// </summary> /// <param name="days"></param> /// <param name="campaigns"></param> /// <returns></returns> public bool MeetsCriteria(int days, int salesAreas, int campaigns, int demographics, int breaks) { bool meetsCriteria = false; if (days <= MaxDays.GetValueOrDefault(Int32.MaxValue)) { if (salesAreas <= MaxSalesAreas.GetValueOrDefault(Int32.MaxValue)) { if (demographics <= MaxDemographics.GetValueOrDefault(Int32.MaxValue)) { if (campaigns <= MaxCampaigns.GetValueOrDefault(Int32.MaxValue)) { if (breaks <= MaxBreaks.GetValueOrDefault(Int32.MaxValue)) { meetsCriteria = true; } } } } } return meetsCriteria; } } }
5640bba53adfda2986084dc77c1b2045dc142885
C#
hiyorin/Gamebase-SceneManagement
/Runtime/ISceneController.cs
2.515625
3
using System; using UniRx.Async; namespace Gamebase.Scene { public interface ISceneController { /// <summary> /// 初期化済みか /// </summary> bool Initialized { get; } /// <summary> /// 初期化 /// </summary> /// <returns></returns> UniTask Initialize(); /// <summary> /// シーンの切り替え /// </summary> /// <param name="sceneName"></param> void Change(string sceneName); /// <summary> /// シーンの切り替え /// </summary> /// <param name="sceneName"></param> /// <param name="transData"></param> void Change(string sceneName, object transData); /// <summary> /// 遷移元からのデータを取得する /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> T GetTransData<T>(); /// <summary> /// 遷移完了通知 /// </summary> /// <returns></returns> IObservable<string> OnTransCompleteAsObservable(); } }
a4b2de0ac571c6c08255e0f3e4fa9faa83bb75e6
C#
SometimesRain/IrcClientMinimal
/IrcClientMinimal/TcpClient.cs
2.890625
3
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; namespace IrcClientMinimal { public delegate void IOCallback(byte[] data, int numBytes); public class TcpClient { private byte[] recvBuffer; private Socket socket; private IOCallback onReceive; private IOCallback onSend; private IOCallback onDisconnect; public bool Connected => socket.Connected; public TcpClient(IOCallback onReceive, IOCallback onSend, IOCallback onDisconnect) { this.onReceive = onReceive; this.onSend = onSend; this.onDisconnect = onDisconnect; socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.NoDelay = true; recvBuffer = new byte[1024]; } //########################################## Operations ######################################## public void Connect(EndPoint endPoint) { socket.Connect(endPoint); } public void Disconnect() { socket.Shutdown(SocketShutdown.Both); socket.Close(); onDisconnect?.Invoke(null, 0); } public void Receive() { socket.BeginReceive(recvBuffer, 0, recvBuffer.Length, SocketFlags.None, new AsyncCallback(OnReceive), null); } public void Send(byte[] data) { socket.BeginSend(data, 0, data.Length, SocketFlags.None, new AsyncCallback(OnSend), data); } //########################################## Callbacks ######################################### private void OnReceive(IAsyncResult ar) { try { int dataAmount = socket.EndSend(ar); //Receiving 0 bytes via TCP means a disconnect if (dataAmount == 0) Disconnect(); else onReceive?.Invoke(recvBuffer, dataAmount); } catch (Exception e) { Console.WriteLine(e); } } private void OnSend(IAsyncResult ar) { try { int dataAmount = socket.EndSend(ar); byte[] data = (byte[])ar.AsyncState; onSend?.Invoke(data, dataAmount); } catch (Exception e) { Console.WriteLine(e); } } } }
d5dab9ae794c8a2cfceba49229139d34ec4e838b
C#
illuillu/Statistics_Project
/Statistics_Server/Statistics_Server/DAO/DAO.cs
2.796875
3
using System; using System.Collections.Generic; using System.Configuration; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data; namespace Statistics_Server { class DAO { private static DAO instance = null; public static DAO Get() { if (instance == null) instance = new DAO(); return instance; } /// <summary> /// 테이블에 있는 값들을 모두 지워주는 메서드 /// </summary> public void ResetTables () { string connectionString = ConfigurationManager.ConnectionStrings["StatisticsDB"].ConnectionString; using (SqlConnection sqlCon = new SqlConnection()) { sqlCon.ConnectionString = connectionString; sqlCon.Open(); SqlCommand cmd = new SqlCommand("usp_deleteAll", sqlCon); cmd.CommandType = CommandType.StoredProcedure; cmd.ExecuteNonQuery(); } } /// <summary> /// 처음 Form이 실행될 때 DB에 물품값 업데이트 (1000원으로) /// </summary> /// <param name="prodID"></param> /// <param name="prodName"></param> /// <param name="prodType"></param> /// <param name="prodPrcie"></param> /// <param name="currentTime"></param> public void FirstConnection (string prodID, string prodName, string prodType, int prodPrcie, DateTime currentTime) { string connectionString = ConfigurationManager.ConnectionStrings["StatisticsDB"].ConnectionString; using (SqlConnection sqlCon = new SqlConnection()) { sqlCon.ConnectionString = connectionString; sqlCon.Open(); SqlCommand cmd = new SqlCommand("usp_firstConnection", sqlCon); cmd.CommandType = CommandType.StoredProcedure; SqlParameter param = cmd.Parameters.Add("@prodID", SqlDbType.NVarChar, 2); param.Value = prodID; param = cmd.Parameters.Add("@prodName", SqlDbType.NVarChar, 10); param.Value = prodName; param = cmd.Parameters.Add("@prodType", SqlDbType.NVarChar, 5); param.Value = prodType; param = cmd.Parameters.Add("@prodPrice", SqlDbType.BigInt); param.Value = prodPrcie; param = cmd.Parameters.Add("@updatedDate", SqlDbType.DateTime); param.Value = currentTime; cmd.ExecuteNonQuery(); } } /// <summary> /// 랜덤 변동값을 DB에 적용시켜주는 메서드 /// </summary> /// <param name="prodID"></param> /// <param name="prodName"></param> /// <param name="prodType"></param> /// <param name="prodChange"></param> /// <param name="currentTime"></param> public void UpdatePrice (string prodID, string prodName, string prodType, int prodChange, DateTime currentTime) { string connectionString = ConfigurationManager.ConnectionStrings["StatisticsDB"].ConnectionString; using (SqlConnection sqlCon = new SqlConnection()) { sqlCon.ConnectionString = connectionString; sqlCon.Open(); SqlCommand cmd = new SqlCommand("usp_updatePrice", sqlCon); cmd.CommandType = CommandType.StoredProcedure; SqlParameter param = cmd.Parameters.Add("@prodID", SqlDbType.NVarChar, 2); param.Value = prodID; param = cmd.Parameters.Add("@prodName", SqlDbType.NVarChar, 10); param.Value = prodName; param = cmd.Parameters.Add("@prodType", SqlDbType.NVarChar, 5); param.Value = prodType; param = cmd.Parameters.Add("@prodChange", SqlDbType.Int); param.Value = prodChange; param = cmd.Parameters.Add("@updatedDate", SqlDbType.DateTime); param.Value = currentTime; cmd.ExecuteNonQuery(); } } } }
053a77f06f1a8562ee75aafa66d3821211a1c980
C#
PlumpMath/DesignPattern-1012
/Singleton/Singleton/Singleton.cs
3.6875
4
 namespace Singleton { /// <summary> /// 饿汉模式:类加载的时候创建类的实例 /// 饿汉模式的特点是加载类时比较慢,但运行时获取对象的速度比较快 /// 饿汉模式是线程安全的 /// </summary> class Singleton { //1.将构造方法私有化,不允许外部直接创建对象 private Singleton() { } //2.创建类的唯一实例,用private static修饰 private static Singleton instance = new Singleton(); //3.提供一个获取实例的方法,用public static修饰 public static Singleton getInstance() { return instance; } } }
18e4d62372b18e3b5bff39ee20aabfef9def9004
C#
konradr33/Rabbit-fox-grass
/Assets/Scripts/NeuralNetworkStorage.cs
3.234375
3
using Newtonsoft.Json.Linq; using System.Collections.Generic; using System.Text; namespace DefaultNamespace { public class NeuralNetworkStorage { public static void SaveToFile(string filePath, NeuralNetwork[] networks, float[] fitnesses) { var stringBuilder = new StringBuilder(); stringBuilder.AppendLine("{ \"networks\":"); stringBuilder.AppendLine("["); for (int i = 0; i < networks.Length; i++) { stringBuilder.Append(networks[i].ToString(fitnesses[i])); if (i < networks.Length - 1) stringBuilder.AppendLine(","); } stringBuilder.AppendLine("] }"); System.IO.File.WriteAllText(filePath, stringBuilder.ToString()); } public static NeuralNetwork[] ReadFromFile(string filePath) { var fileContent = System.IO.File.ReadAllText(filePath); var networksObject = JObject.Parse(fileContent); var networks = new List<NeuralNetwork>(); foreach (var networkObject in networksObject["networks"].Children()) { networks.Add(NeuralNetwork.NetworkFromString(networkObject)); } return networks.ToArray(); } } }
b1caa39aa3444023f5a15e5aad21e27d38abe851
C#
divya-harchandani/git4864
/gitworks/FirstApplicationSolution/FlowControl/ForEachExample.cs
3.734375
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FlowControl { class ForEachExample { static void Main() { string[] Gender = { "Male", "Female", "male", "female", "MALE" }; int male = 0; int female = 0; foreach(string g in Gender) { if (g.ToLower() == "male") male++; else if (g.ToLower() == "female") female++; } Console.WriteLine("NUmber of Males : {0}", male); Console.WriteLine("NUmber of Females : {0}", female); Console.ReadKey(); } } }
d62c1600e056b36d26553b684861abe27767019b
C#
MaxIvanov44/ComputerService
/Computer Service/Logic/LogicModels/LogicMaster.cs
3.03125
3
using Database.EntityModels; using System; using System.Data; using System.Linq; namespace Logic { public class LogicMaster { public static int GetIdMaster(string ID) { Model1 db = new Model1(); string[] NameArray = new string[1]; NameArray = ID.Split(' '); ID = NameArray[0]; int IDD = Convert.ToInt32(ID); return db.Masters.Where(n => n.id_master == IDD).FirstOrDefault().id_master; } public static void CurrentMaster(int id) { Model1 db = new Model1(); GETMASTERID.CurrentMaster = id; } public static Masters GetCurrentMaster() { Model1 db = new Model1(); return db.Masters.Find(GETMASTERID.CurrentMaster); } public static DataTable GetAllMasters() { Model1 db = new Model1(); DataTable dtord = new DataTable(); dtord.Columns.Add("ID"); dtord.Columns.Add("Фамилия"); dtord.Columns.Add("Имя"); dtord.Columns.Add("Отчество"); dtord.Columns.Add("Телефон"); dtord.Columns.Add("E-mail"); var data = from m in db.Masters select new { ID = m.id_master, F = m.last_name, I = m.first_name, O = m.middle_name, Phone = m.phone, email = m.email }; foreach (var dt in data) { dtord.Rows.Add(dt.ID, dt.F, dt.I, dt.O, dt.Phone, dt.email); } return dtord; } } }
fd625abe41487a75f1b4a5dfd44b2ed29b475bb8
C#
adamtuliper/csharp-features
/CSharp6/CollectionInitialization.cs
3.015625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace c_sharp_7.CSharp6 { public class Attendees { public Attendees() { //Old var list = new Dictionary<int, Attendee>(); list.Add(1029188, new Attendee() { FirstName = "Ravi", LastName = "Shankaran" }); //New var attendees = new Dictionary<int, Attendee> { [181212] = new Attendee { FirstName = "Mary", LastName = "Jones" }, [2121] = new Attendee { FirstName = "Doogie", LastName = "Abbott" }, [312412] = new Attendee { FirstName = "Lemon", LastName = "McOrangeFace" } }; } } public class Attendee { public string FirstName { get; set; } public string LastName { get; set; } } }
c080532a94c099ff81d129aaaeda85499463ea95
C#
jessetinell/ShopifyMessages
/ShopifyMessages.Api/Models/MessageJsonResponse.cs
2.609375
3
using ShopifyMessages.Core; using ShopifyMessages.Core.Models; using System.Collections.Generic; using System.Linq; namespace ShopifyMessages.Api.Models { public class MessageJsonResponse { public string Id { get; set; } public string Html { get; set; } public int MaxWidth { get; set; } public int MinHeight { get; set; } public Position Position { get; set; } public DisplayRules DisplayRules { get; set; } public bool UseModalBackground { get; set; } } public class ResponseHelper { public static List<MessageJsonResponse> ToJsonResponse(IEnumerable<Message> messages, List<Template> templates) { var list = new List<MessageJsonResponse>(); foreach (var message in messages) { var template = templates.FirstOrDefault(t => t.Id == message.TemplateId); if (template != null) { var placeholderValues = message.PlaceholderValues; placeholderValues.Add("messageId",message.Id); list.Add(new MessageJsonResponse { MinHeight = message.MinHeight, MaxWidth = message.MaxWidth, Id = message.Id, Html = TemplateParser.Parse(message,template.Html), Position = message.Position, DisplayRules = message.DisplayRules, UseModalBackground = message.UseModalBackground }); } } return list; } } }
e4e3449ddf3cd335366ffa8607592c79167a933d
C#
Thomas789-Tak/Rhythm
/RhythmiCar_Unity/Assets/1_Scripts/4_Data/SongDataContainer.cs
2.53125
3
using UnityEngine; using System.Collections.Generic; [CreateAssetMenu(fileName = "SongDataContainer", menuName = "Scriptable Object/Song Data Container")] public class SongDataContainer : ScriptableObject { public List<SongInformationData> songInformationDatas = new List<SongInformationData>(); public List<SongNoteData> songNoteDatas = new List<SongNoteData>(); } [System.Serializable] public class SongNoteData { public string name; [SerializeField] private SongInformationData info; public ESongDifficulty difficulty; public float speedAccel; public bool isOpend = false; public List<float> noteData; public List<EnumItemVO.EItemType> line = new List<EnumItemVO.EItemType>(); [SerializeField] public List<List<EnumItemVO.EItemType>> lines = new List<List<EnumItemVO.EItemType>>(); /// <summary> /// Line 안에 담긴 정보를 Debug.log를 통해 본다. /// </summary> [ContextMenu("LogLine")] public void LogLine() { string txt = ""; foreach (List<EnumItemVO.EItemType> line in lines) { foreach (EnumItemVO.EItemType item in line) { txt += item.ToString() + " "; } txt += "\n"; } Debug.Log(txt); } [ContextMenu("AddItemToLines")] public void AddItemToLines() { lines.Add(line); } public string title { get => info.title; } public string artist { get => info.artist; } public int BPM { get => info.BPM; } public AudioClip clip { get => info.clip; } public SoundManager.EBGM EBGM { get => info.EBGM; } public void SetSongInformaitonData(SongInformationData songInformationData) { info = songInformationData; } } [System.Serializable] public class SongInformationData { public string title; public string artist; public int BPM; public AudioClip clip; public SoundManager.EBGM EBGM; } public enum ESongDifficulty { Easy = 0, Normal, Hard }
8a4e81f8205346ac90810e824ce76388eb87d7e5
C#
RebeccaSeel/InheritancePolymorphismPractice
/InheritancePolymorphismPractice/Program.cs
3.484375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace InheritancePolymorphismPractice { class Program { static void Main(string[] args) //this is where the app/program is run from because it is the Main { //create instance of our boat Boat boat1 = new Boat(2, 500, "White and Yellow", 70.0d, .78); //hover over new Boat for structure boat1.Move(); //move the boat boat1.Move(); //move the boat again Console.WriteLine("Boat " + boat1.GetDistanceTraveled()); //prints Boat Distance Traveled: 109.2 //create instance of automobile Automobile car1 = new Automobile(4, 20, 4, 5, 500, "Red", 260); car1.Move(); car1.Color = "Gold"; Console.WriteLine("Automobile " + car1.GetDistanceTraveled()); //create instance of aircraft Aircraft plane1 = new Aircraft(100, 1000000, "Purple", 600); plane1.Move(); plane1.Move(); Console.WriteLine("Aircraft " + plane1.GetDistanceTraveled()); //Appliances stove = new Appliances(); //red squiggly because you can't create object for abstract class } } }
8edfd31f8c69057b9dd009536ba1018d49ceac70
C#
christianempire/ULima.CodeWarrior
/Assets/Scripts/Shared/PositionableEntity.cs
2.59375
3
using UnityEngine; namespace Assets.Scripts.Shared { public abstract class PositionableEntity : MonoBehaviour { public Vector2 GetColliderPosition() { return new Vector2(transform.position.x, transform.position.y) - GetColliderPositionOffset(); } public Vector2 GetPosition() { return new Vector2(transform.position.x, transform.position.y) - GetPositionOffset(); } public void SetPosition(Vector2 position) { transform.position = position + GetPositionOffset(); } protected abstract Vector2 GetColliderPositionOffset(); protected abstract Vector2 GetPositionOffset(); } }
07e89fe9835fc347eecf49e46fcbf19a52165d91
C#
kayleighagius/weather-forecast-web-api-kayleigh-agius
/Endpoints/WeatherBitEndpoint.cs
2.6875
3
using System; using System.Collections.Generic; using System.Text; namespace WeatherForecastWebClient.Endpoints { class WeatherBitEndpoint : Endpoint { //http://api.weatherbit.io/v2.0/current?key={your api key}&units=M&city{city name}&country={country code} //http://api.weatherbit.io/v2.0/forecast/daily?key={your api key}&units=M&city{city name}&country={country code} public WeatherBitEndpoint() : base("9f821d0ffc7145f693d26f40455b9fc6", "http://api.weatherbit.io", new Dictionary<EndpointType, string> { { EndpointType.CURRENT, "current"}, { EndpointType.FORECAST, "forecast" } }, "v2.0", "M") { } public string getCurrentWeatherEndpoint(string cityName) { StringBuilder stringBuilder = new StringBuilder(baseEndpoint); stringBuilder.Append($"/{version}"); stringBuilder.Append($"/{endpointTypeDictionary[EndpointType.CURRENT]}"); stringBuilder.Append("?key="); stringBuilder.Append(apiKey); stringBuilder.Append("&units="); stringBuilder.Append(units); stringBuilder.Append("&city="); stringBuilder.Append(cityName); return stringBuilder.ToString(); } public string getCurrentWeatherEndpoint(string cityName, string countryCode) { StringBuilder stringBuilder = new StringBuilder(baseEndpoint); stringBuilder.Append($"/{version}"); stringBuilder.Append($"/{endpointTypeDictionary[EndpointType.CURRENT]}"); stringBuilder.Append("?key="); stringBuilder.Append(apiKey); stringBuilder.Append("&units="); stringBuilder.Append(units); stringBuilder.Append("&city="); stringBuilder.Append(cityName); stringBuilder.Append("&country="); stringBuilder.Append(countryCode); return stringBuilder.ToString(); } public string getForecastEndpoint(string cityName) { StringBuilder stringBuilder = new StringBuilder(baseEndpoint); stringBuilder.Append($"/{version}"); stringBuilder.Append($"/{endpointTypeDictionary[EndpointType.FORECAST]}"); stringBuilder.Append("/daily"); stringBuilder.Append("?key="); stringBuilder.Append(apiKey); stringBuilder.Append("&units="); stringBuilder.Append(units); stringBuilder.Append("&city="); stringBuilder.Append(cityName); return stringBuilder.ToString(); } public string getForecastEndpoint(string cityName, string countryCode) { StringBuilder stringBuilder = new StringBuilder(baseEndpoint); stringBuilder.Append($"/{version}"); stringBuilder.Append($"/{endpointTypeDictionary[EndpointType.FORECAST]}"); stringBuilder.Append("/daily"); stringBuilder.Append("?key="); stringBuilder.Append(apiKey); stringBuilder.Append("&units="); stringBuilder.Append(units); stringBuilder.Append("&city="); stringBuilder.Append(cityName); stringBuilder.Append("&country="); stringBuilder.Append(countryCode); return stringBuilder.ToString(); } } }
46b506aa8557f562ee51798c87ae787749abbc69
C#
chuxuantinh/Software-Dev
/13.DS-Adv/exam28Nov2020/01. Classroom - Correctness_Skeleton/01.Classroom/Class.cs
2.796875
3
using System.Collections.Generic; namespace _01.Classroom { public class Class { public Class(string name) { this.Name = name; } public string Name { get; set; } public Dictionary<string, Student> Students { get; set; } = new Dictionary<string, Student>(); } }
c7ec852e5e05443ae8f41371fe1cfbdaab8010f6
C#
WickedFlame/RubberStamp
/src/RubberStamp.UnitTest/ValidatorTests.cs
2.859375
3
using System.Linq; using RubberStamp.Rules; using NUnit.Framework; using RubberStamp.Conditions; namespace RubberStamp.UnitTest { [TestFixture] public class ValidatorTests { [Test] public void RubberStamp_Validator_AddRule_Test() { var rule = new ValidationRule<TestClass, string>(p => p.Name) .AddCondition(new IsNotNullCondition<TestClass, string>(p => p.Name)); IValidator<TestClass> validator = new Validator<TestClass>() .AddRule(rule); Assert.AreSame(rule, validator.Rules.Single()); Assert.That(validator.Rules.Single().Conditions.Single(), Is.Not.Null); } [Test] public void RubberStamp_Validator_AddRuleByObjectExpression_Test() { IValidator<TestClass> validator = new Validator<TestClass>(); validator.AddRule(p => p.Name == string.Empty, "This is a error message"); var rule = validator.Rules.Single(); Assert.That(rule, Is.Not.Null); Assert.That(rule.Conditions.Single(), Is.Not.Null); } [Test] public void RubberStamp_Validator_AddRuleByExpressionAndCondition_Test() { IValidator<TestClass> validator = new Validator<TestClass>(); validator.AddRule(p => p.Name, con => con.IsNotNull()); var rule = validator.Rules.Single(); Assert.That(rule, Is.Not.Null); Assert.That(rule.Conditions.Single(), Is.Not.Null); } [Test] public void RubberStamp_Validator_AddRuleByExpressionAndConditions_Test() { IValidator<TestClass> validator = new Validator<TestClass>(); validator.AddRule(p => p.Name, con => con.Conditions(c=> c.IsNotNull(), c => c.IsEqual("Test"))); var rule = validator.Rules.Single(); Assert.That(rule, Is.Not.Null); Assert.That(rule.Conditions.Count(), Is.EqualTo(2)); } private class TestClass { public string Name { get; set; } } } }
748a19d37372eb716ff0d7a98e0b9e3931963e7a
C#
code-jtxzromx/projectHerbariumMgmtIS
/projectHerbariumMgmtIS/Model/SpeciesNomenclature.cs
2.6875
3
using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace projectHerbariumMgmtIS.Model { public class SpeciesNomenclature { // Properties public int AltNameID { get; set; } public string TaxonName { get; set; } public string Language { get; set; } public string AlternateName { get; set; } // Constructor public SpeciesNomenclature() { this.AltNameID = 0; this.TaxonName = ""; this.Language = ""; this.AlternateName = ""; } // Methods public List<SpeciesNomenclature> GetSpeciesNomenclatures() { List<SpeciesNomenclature> alternates = new List<SpeciesNomenclature>(); DatabaseConnection connection = new DatabaseConnection(); connection.setQuery("SELECT intAltNameID, strScientificName, strLanguage, strAlternateName " + "FROM viewSpeciesAlternate " + "WHERE intAltNameID IS NOT NULL " + "ORDER BY strScientificName, strLanguage"); SqlDataReader sqlData = connection.executeResult(); while (sqlData.Read()) { alternates.Add(new SpeciesNomenclature() { AltNameID = Convert.ToInt32(sqlData[0]), TaxonName = sqlData[1].ToString(), Language = sqlData[2].ToString(), AlternateName = sqlData[3].ToString() }); } connection.closeResult(); return alternates; } public int AddNomenclature() { int status; DatabaseConnection connection = new DatabaseConnection(); connection.setStoredProc("dbo.procInsertSpeciesNomenclature"); connection.addProcParameter("@isIDBase", SqlDbType.Bit, 0); connection.addProcParameter("@taxonName", SqlDbType.VarChar, TaxonName); connection.addProcParameter("@language", SqlDbType.VarChar, Language); connection.addProcParameter("@alternateName", SqlDbType.VarChar, AlternateName); status = connection.executeProcedure(); return status; } public int EditNomenclature() { int status; DatabaseConnection connection = new DatabaseConnection(); connection.setStoredProc("dbo.procUpdateSpeciesNomenclature"); connection.addProcParameter("@isIDBase", SqlDbType.Bit, 0); connection.addProcParameter("@altNameID", SqlDbType.VarChar, AltNameID); connection.addProcParameter("@taxonName", SqlDbType.VarChar, TaxonName); connection.addProcParameter("@language", SqlDbType.VarChar, Language); connection.addProcParameter("@alternateName", SqlDbType.VarChar, AlternateName); status = connection.executeProcedure(); return status; } } }
674b6fb32d703a2a025d5ab46fc609ecf9acf8e8
C#
KeRNeLith/QuikGraph
/tests/QuikGraph.Tests/Predicates/Graphs/GraphTestsBases/FilteredGraphTestsBase.cs
2.546875
3
using System; using System.Collections.Generic; using JetBrains.Annotations; using NUnit.Framework; using QuikGraph.Tests.Structures; using static QuikGraph.Tests.AssertHelpers; using static QuikGraph.Tests.GraphTestHelpers; namespace QuikGraph.Tests.Predicates { /// <summary> /// Base class for filtered graph tests. /// </summary> internal abstract class FilteredGraphTestsBase : GraphTestsBase { #region Vertices & Edges protected static void Vertices_Test<TGraph>( [NotNull] TGraph wrappedGraph, [NotNull] Func<VertexPredicate<int>, EdgePredicate<int, Edge<int>>, IVertexSet<int>> createFilteredGraph) where TGraph : IMutableVertexSet<int>, IMutableGraph<int, Edge<int>> { IVertexSet<int> filteredGraph = createFilteredGraph(_ => true, _ => true); AssertNoVertex(filteredGraph); wrappedGraph.AddVertexRange(new[] { 1, 2, 3 }); AssertHasVertices(filteredGraph, new[] { 1, 2, 3 }); wrappedGraph.Clear(); filteredGraph = createFilteredGraph(vertex => vertex < 3, _ => true); AssertNoVertex(filteredGraph); wrappedGraph.AddVertexRange(new[] { 1, 2, 3 }); AssertHasVertices(filteredGraph, new[] { 1, 2 }); } public void Edges_Test<TGraph>( [NotNull] TGraph wrappedGraph, [NotNull] Func<VertexPredicate<int>, EdgePredicate<int, Edge<int>>, IEdgeSet<int, Edge<int>>> createFilteredGraph) where TGraph : IMutableVertexAndEdgeSet<int, Edge<int>>, IMutableGraph<int, Edge<int>> { IEdgeSet<int, Edge<int>> filteredGraph = createFilteredGraph(_ => true, _ => true); AssertNoEdge(filteredGraph); var edge12 = new Edge<int>(1, 2); var edge13 = new Edge<int>(1, 3); var edge22 = new Edge<int>(2, 2); var edge31 = new Edge<int>(3, 1); var edge33 = new Edge<int>(3, 3); var edge41 = new Edge<int>(4, 1); wrappedGraph.AddVerticesAndEdgeRange(new[] { edge12, edge13, edge22, edge31, edge33, edge41 }); AssertHasEdges(filteredGraph, new[] { edge12, edge13, edge22, edge31, edge33, edge41 }); wrappedGraph.Clear(); filteredGraph = createFilteredGraph(vertex => vertex <= 3, _ => true); AssertNoEdge(filteredGraph); wrappedGraph.AddVerticesAndEdgeRange(new[] { edge12, edge13, edge22, edge31, edge33, edge41 }); AssertHasEdges(filteredGraph, new[] { edge12, edge13, edge22, edge31, edge33 }); wrappedGraph.Clear(); filteredGraph = createFilteredGraph(_ => true, edge => edge.Source != edge.Target); AssertNoEdge(filteredGraph); wrappedGraph.AddVerticesAndEdgeRange(new[] { edge12, edge13, edge22, edge31, edge33, edge41 }); AssertHasEdges(filteredGraph, new[] { edge12, edge13, edge31, edge41 }); wrappedGraph.Clear(); filteredGraph = createFilteredGraph(vertex => vertex <= 3, edge => edge.Source != edge.Target); AssertNoEdge(filteredGraph); wrappedGraph.AddVerticesAndEdgeRange(new[] { edge12, edge13, edge22, edge31, edge33, edge41 }); AssertHasEdges(filteredGraph, new[] { edge12, edge13, edge31 }); } #endregion #region Contains Vertex protected static void ContainsVertex_Test<TGraph>( [NotNull] TGraph wrappedGraph, [NotNull] Func<VertexPredicate<int>, EdgePredicate<int, Edge<int>>, IImplicitVertexSet<int>> createFilteredGraph) where TGraph : IMutableVertexSet<int>, IMutableGraph<int, Edge<int>> { IImplicitVertexSet<int> filteredGraph = createFilteredGraph( _ => true, _ => true); Assert.IsFalse(filteredGraph.ContainsVertex(1)); Assert.IsFalse(filteredGraph.ContainsVertex(2)); wrappedGraph.AddVertex(1); Assert.IsTrue(filteredGraph.ContainsVertex(1)); Assert.IsFalse(filteredGraph.ContainsVertex(2)); wrappedGraph.AddVertex(2); Assert.IsTrue(filteredGraph.ContainsVertex(1)); Assert.IsTrue(filteredGraph.ContainsVertex(2)); wrappedGraph.RemoveVertex(1); Assert.IsFalse(filteredGraph.ContainsVertex(1)); Assert.IsTrue(filteredGraph.ContainsVertex(2)); wrappedGraph.Clear(); filteredGraph = createFilteredGraph( vertex => vertex <= 2, _ => true); Assert.IsFalse(filteredGraph.ContainsVertex(1)); Assert.IsFalse(filteredGraph.ContainsVertex(2)); Assert.IsFalse(filteredGraph.ContainsVertex(3)); wrappedGraph.AddVertex(1); Assert.IsTrue(filteredGraph.ContainsVertex(1)); Assert.IsFalse(filteredGraph.ContainsVertex(2)); Assert.IsFalse(filteredGraph.ContainsVertex(3)); wrappedGraph.AddVertex(2); Assert.IsTrue(filteredGraph.ContainsVertex(1)); Assert.IsTrue(filteredGraph.ContainsVertex(2)); Assert.IsFalse(filteredGraph.ContainsVertex(3)); wrappedGraph.AddVertex(3); Assert.IsTrue(filteredGraph.ContainsVertex(1)); Assert.IsTrue(filteredGraph.ContainsVertex(2)); Assert.IsFalse(filteredGraph.ContainsVertex(3)); // Filtered wrappedGraph.RemoveVertex(1); Assert.IsFalse(filteredGraph.ContainsVertex(1)); Assert.IsTrue(filteredGraph.ContainsVertex(2)); Assert.IsFalse(filteredGraph.ContainsVertex(3)); } #endregion #region Contains Edge protected static void ContainsEdge_Test<TGraph>( [NotNull] TGraph wrappedGraph, [NotNull] Func<VertexPredicate<int>, EdgePredicate<int, Edge<int>>, IEdgeSet<int, Edge<int>>> createFilteredGraph) where TGraph : IMutableVertexAndEdgeSet<int, Edge<int>>, IMutableGraph<int, Edge<int>> { #region Part 1 IEdgeSet<int, Edge<int>> filteredGraph = createFilteredGraph( _ => true, _ => true); ContainsEdge_Test( filteredGraph, edge => wrappedGraph.AddVerticesAndEdge(edge)); #endregion #region Part 2 wrappedGraph.Clear(); filteredGraph = createFilteredGraph( vertex => vertex > 0 && vertex < 3, _ => true); var edge1 = new Edge<int>(1, 2); var edge2 = new Edge<int>(1, 3); var edge3 = new Edge<int>(2, 1); var edge4 = new Edge<int>(2, 2); var otherEdge1 = new Edge<int>(1, 2); Assert.IsFalse(filteredGraph.ContainsEdge(edge1)); Assert.IsFalse(filteredGraph.ContainsEdge(edge2)); Assert.IsFalse(filteredGraph.ContainsEdge(edge3)); Assert.IsFalse(filteredGraph.ContainsEdge(edge4)); Assert.IsFalse(filteredGraph.ContainsEdge(otherEdge1)); wrappedGraph.AddVerticesAndEdge(edge1); Assert.IsTrue(filteredGraph.ContainsEdge(edge1)); Assert.IsFalse(filteredGraph.ContainsEdge(edge2)); Assert.IsFalse(filteredGraph.ContainsEdge(edge3)); Assert.IsFalse(filteredGraph.ContainsEdge(edge4)); Assert.IsFalse(filteredGraph.ContainsEdge(otherEdge1)); wrappedGraph.AddVerticesAndEdge(edge2); Assert.IsTrue(filteredGraph.ContainsEdge(edge1)); Assert.IsFalse(filteredGraph.ContainsEdge(edge2)); // Filtered Assert.IsFalse(filteredGraph.ContainsEdge(edge3)); Assert.IsFalse(filteredGraph.ContainsEdge(edge4)); Assert.IsFalse(filteredGraph.ContainsEdge(otherEdge1)); wrappedGraph.AddVerticesAndEdge(edge3); Assert.IsTrue(filteredGraph.ContainsEdge(edge1)); Assert.IsFalse(filteredGraph.ContainsEdge(edge2)); // Filtered Assert.IsTrue(filteredGraph.ContainsEdge(edge3)); Assert.IsFalse(filteredGraph.ContainsEdge(edge4)); Assert.IsFalse(filteredGraph.ContainsEdge(otherEdge1)); wrappedGraph.AddVerticesAndEdge(edge4); Assert.IsTrue(filteredGraph.ContainsEdge(edge1)); Assert.IsFalse(filteredGraph.ContainsEdge(edge2)); // Filtered Assert.IsTrue(filteredGraph.ContainsEdge(edge3)); Assert.IsTrue(filteredGraph.ContainsEdge(edge4)); Assert.IsFalse(filteredGraph.ContainsEdge(otherEdge1)); wrappedGraph.AddVerticesAndEdge(otherEdge1); Assert.IsTrue(filteredGraph.ContainsEdge(edge1)); Assert.IsFalse(filteredGraph.ContainsEdge(edge2)); // Filtered Assert.IsTrue(filteredGraph.ContainsEdge(edge3)); Assert.IsTrue(filteredGraph.ContainsEdge(edge4)); Assert.IsTrue(filteredGraph.ContainsEdge(otherEdge1)); // Both vertices not in graph Assert.IsFalse(filteredGraph.ContainsEdge(new Edge<int>(0, 10))); // Source not in graph Assert.IsFalse(filteredGraph.ContainsEdge(new Edge<int>(0, 1))); // Target not in graph Assert.IsFalse(filteredGraph.ContainsEdge(new Edge<int>(1, 0))); #endregion #region Part 3 wrappedGraph.Clear(); filteredGraph = createFilteredGraph( _ => true, edge => edge.Source != edge.Target); Assert.IsFalse(filteredGraph.ContainsEdge(edge1)); Assert.IsFalse(filteredGraph.ContainsEdge(edge2)); Assert.IsFalse(filteredGraph.ContainsEdge(edge3)); Assert.IsFalse(filteredGraph.ContainsEdge(edge4)); Assert.IsFalse(filteredGraph.ContainsEdge(otherEdge1)); wrappedGraph.AddVerticesAndEdge(edge1); Assert.IsTrue(filteredGraph.ContainsEdge(edge1)); Assert.IsFalse(filteredGraph.ContainsEdge(edge2)); Assert.IsFalse(filteredGraph.ContainsEdge(edge3)); Assert.IsFalse(filteredGraph.ContainsEdge(edge4)); Assert.IsFalse(filteredGraph.ContainsEdge(otherEdge1)); wrappedGraph.AddVerticesAndEdge(edge2); Assert.IsTrue(filteredGraph.ContainsEdge(edge1)); Assert.IsTrue(filteredGraph.ContainsEdge(edge2)); Assert.IsFalse(filteredGraph.ContainsEdge(edge3)); Assert.IsFalse(filteredGraph.ContainsEdge(edge4)); Assert.IsFalse(filteredGraph.ContainsEdge(otherEdge1)); wrappedGraph.AddVerticesAndEdge(edge3); Assert.IsTrue(filteredGraph.ContainsEdge(edge1)); Assert.IsTrue(filteredGraph.ContainsEdge(edge2)); Assert.IsTrue(filteredGraph.ContainsEdge(edge3)); Assert.IsFalse(filteredGraph.ContainsEdge(edge4)); Assert.IsFalse(filteredGraph.ContainsEdge(otherEdge1)); wrappedGraph.AddVerticesAndEdge(edge4); Assert.IsTrue(filteredGraph.ContainsEdge(edge1)); Assert.IsTrue(filteredGraph.ContainsEdge(edge2)); Assert.IsTrue(filteredGraph.ContainsEdge(edge3)); Assert.IsFalse(filteredGraph.ContainsEdge(edge4)); // Filtered Assert.IsFalse(filteredGraph.ContainsEdge(otherEdge1)); wrappedGraph.AddVerticesAndEdge(otherEdge1); Assert.IsTrue(filteredGraph.ContainsEdge(edge1)); Assert.IsTrue(filteredGraph.ContainsEdge(edge2)); Assert.IsTrue(filteredGraph.ContainsEdge(edge3)); Assert.IsFalse(filteredGraph.ContainsEdge(edge4)); // Filtered Assert.IsTrue(filteredGraph.ContainsEdge(otherEdge1)); // Both vertices not in graph Assert.IsFalse(filteredGraph.ContainsEdge(new Edge<int>(0, 10))); // Source not in graph Assert.IsFalse(filteredGraph.ContainsEdge(new Edge<int>(0, 1))); // Target not in graph Assert.IsFalse(filteredGraph.ContainsEdge(new Edge<int>(1, 0))); #endregion #region Part 4 wrappedGraph.Clear(); filteredGraph = createFilteredGraph( vertex => vertex > 0 && vertex < 3, edge => edge.Source != edge.Target); Assert.IsFalse(filteredGraph.ContainsEdge(edge1)); Assert.IsFalse(filteredGraph.ContainsEdge(edge2)); Assert.IsFalse(filteredGraph.ContainsEdge(edge3)); Assert.IsFalse(filteredGraph.ContainsEdge(edge4)); Assert.IsFalse(filteredGraph.ContainsEdge(otherEdge1)); wrappedGraph.AddVerticesAndEdge(edge1); Assert.IsTrue(filteredGraph.ContainsEdge(edge1)); Assert.IsFalse(filteredGraph.ContainsEdge(edge2)); Assert.IsFalse(filteredGraph.ContainsEdge(edge3)); Assert.IsFalse(filteredGraph.ContainsEdge(edge4)); Assert.IsFalse(filteredGraph.ContainsEdge(otherEdge1)); wrappedGraph.AddVerticesAndEdge(edge2); Assert.IsTrue(filteredGraph.ContainsEdge(edge1)); Assert.IsFalse(filteredGraph.ContainsEdge(edge2)); // Filtered Assert.IsFalse(filteredGraph.ContainsEdge(edge3)); Assert.IsFalse(filteredGraph.ContainsEdge(edge4)); Assert.IsFalse(filteredGraph.ContainsEdge(otherEdge1)); wrappedGraph.AddVerticesAndEdge(edge3); Assert.IsTrue(filteredGraph.ContainsEdge(edge1)); Assert.IsFalse(filteredGraph.ContainsEdge(edge2)); // Filtered Assert.IsTrue(filteredGraph.ContainsEdge(edge3)); Assert.IsFalse(filteredGraph.ContainsEdge(edge4)); Assert.IsFalse(filteredGraph.ContainsEdge(otherEdge1)); wrappedGraph.AddVerticesAndEdge(edge4); Assert.IsTrue(filteredGraph.ContainsEdge(edge1)); Assert.IsFalse(filteredGraph.ContainsEdge(edge2)); // Filtered Assert.IsTrue(filteredGraph.ContainsEdge(edge3)); Assert.IsFalse(filteredGraph.ContainsEdge(edge4)); // Filtered Assert.IsFalse(filteredGraph.ContainsEdge(otherEdge1)); wrappedGraph.AddVerticesAndEdge(otherEdge1); Assert.IsTrue(filteredGraph.ContainsEdge(edge1)); Assert.IsFalse(filteredGraph.ContainsEdge(edge2)); // Filtered Assert.IsTrue(filteredGraph.ContainsEdge(edge3)); Assert.IsFalse(filteredGraph.ContainsEdge(edge4)); // Filtered Assert.IsTrue(filteredGraph.ContainsEdge(otherEdge1)); // Both vertices not in graph Assert.IsFalse(filteredGraph.ContainsEdge(new Edge<int>(0, 10))); // Source not in graph Assert.IsFalse(filteredGraph.ContainsEdge(new Edge<int>(0, 1))); // Target not in graph Assert.IsFalse(filteredGraph.ContainsEdge(new Edge<int>(1, 0))); #endregion } protected static void ContainsEdge_EquatableEdge_Test<TGraph>( [NotNull] TGraph wrappedGraph, [NotNull] Func<VertexPredicate<int>, EdgePredicate<int, EquatableEdge<int>>, IEdgeSet<int, EquatableEdge<int>>> createFilteredGraph) where TGraph : IMutableVertexAndEdgeSet<int, EquatableEdge<int>>, IMutableGraph<int, EquatableEdge<int>> { #region Part 1 IEdgeSet<int, EquatableEdge<int>> filteredGraph = createFilteredGraph( _ => true, _ => true); ContainsEdge_EquatableEdge_Test( filteredGraph, edge => wrappedGraph.AddVerticesAndEdge(edge)); #endregion #region Part 2 wrappedGraph.Clear(); filteredGraph = createFilteredGraph( vertex => vertex > 0 && vertex < 3, _ => true); var edge1 = new EquatableEdge<int>(1, 2); var edge2 = new EquatableEdge<int>(1, 3); var edge3 = new EquatableEdge<int>(2, 1); var edge4 = new EquatableEdge<int>(2, 2); var otherEdge1 = new EquatableEdge<int>(1, 2); Assert.IsFalse(filteredGraph.ContainsEdge(edge1)); Assert.IsFalse(filteredGraph.ContainsEdge(edge2)); Assert.IsFalse(filteredGraph.ContainsEdge(edge3)); Assert.IsFalse(filteredGraph.ContainsEdge(edge4)); Assert.IsFalse(filteredGraph.ContainsEdge(otherEdge1)); wrappedGraph.AddVerticesAndEdge(edge1); Assert.IsTrue(filteredGraph.ContainsEdge(edge1)); Assert.IsFalse(filteredGraph.ContainsEdge(edge2)); Assert.IsFalse(filteredGraph.ContainsEdge(edge3)); Assert.IsFalse(filteredGraph.ContainsEdge(edge4)); Assert.IsTrue(filteredGraph.ContainsEdge(otherEdge1)); wrappedGraph.AddVerticesAndEdge(edge2); Assert.IsTrue(filteredGraph.ContainsEdge(edge1)); Assert.IsFalse(filteredGraph.ContainsEdge(edge2)); // Filtered Assert.IsFalse(filteredGraph.ContainsEdge(edge3)); Assert.IsFalse(filteredGraph.ContainsEdge(edge4)); Assert.IsTrue(filteredGraph.ContainsEdge(otherEdge1)); wrappedGraph.AddVerticesAndEdge(edge3); Assert.IsTrue(filteredGraph.ContainsEdge(edge1)); Assert.IsFalse(filteredGraph.ContainsEdge(edge2)); // Filtered Assert.IsTrue(filteredGraph.ContainsEdge(edge3)); Assert.IsFalse(filteredGraph.ContainsEdge(edge4)); Assert.IsTrue(filteredGraph.ContainsEdge(otherEdge1)); wrappedGraph.AddVerticesAndEdge(edge4); Assert.IsTrue(filteredGraph.ContainsEdge(edge1)); Assert.IsFalse(filteredGraph.ContainsEdge(edge2)); // Filtered Assert.IsTrue(filteredGraph.ContainsEdge(edge3)); Assert.IsTrue(filteredGraph.ContainsEdge(edge4)); Assert.IsTrue(filteredGraph.ContainsEdge(otherEdge1)); wrappedGraph.AddVerticesAndEdge(otherEdge1); Assert.IsTrue(filteredGraph.ContainsEdge(edge1)); Assert.IsFalse(filteredGraph.ContainsEdge(edge2)); // Filtered Assert.IsTrue(filteredGraph.ContainsEdge(edge3)); Assert.IsTrue(filteredGraph.ContainsEdge(edge4)); Assert.IsTrue(filteredGraph.ContainsEdge(otherEdge1)); // Both vertices not in graph Assert.IsFalse(filteredGraph.ContainsEdge(new EquatableEdge<int>(0, 10))); // Source not in graph Assert.IsFalse(filteredGraph.ContainsEdge(new EquatableEdge<int>(0, 1))); // Target not in graph Assert.IsFalse(filteredGraph.ContainsEdge(new EquatableEdge<int>(1, 0))); #endregion #region Part 3 wrappedGraph.Clear(); filteredGraph = createFilteredGraph( _ => true, edge => edge.Source != edge.Target); Assert.IsFalse(filteredGraph.ContainsEdge(edge1)); Assert.IsFalse(filteredGraph.ContainsEdge(edge2)); Assert.IsFalse(filteredGraph.ContainsEdge(edge3)); Assert.IsFalse(filteredGraph.ContainsEdge(edge4)); Assert.IsFalse(filteredGraph.ContainsEdge(otherEdge1)); wrappedGraph.AddVerticesAndEdge(edge1); Assert.IsTrue(filteredGraph.ContainsEdge(edge1)); Assert.IsFalse(filteredGraph.ContainsEdge(edge2)); Assert.IsFalse(filteredGraph.ContainsEdge(edge3)); Assert.IsFalse(filteredGraph.ContainsEdge(edge4)); Assert.IsTrue(filteredGraph.ContainsEdge(otherEdge1)); wrappedGraph.AddVerticesAndEdge(edge2); Assert.IsTrue(filteredGraph.ContainsEdge(edge1)); Assert.IsTrue(filteredGraph.ContainsEdge(edge2)); Assert.IsFalse(filteredGraph.ContainsEdge(edge3)); Assert.IsFalse(filteredGraph.ContainsEdge(edge4)); Assert.IsTrue(filteredGraph.ContainsEdge(otherEdge1)); wrappedGraph.AddVerticesAndEdge(edge3); Assert.IsTrue(filteredGraph.ContainsEdge(edge1)); Assert.IsTrue(filteredGraph.ContainsEdge(edge2)); Assert.IsTrue(filteredGraph.ContainsEdge(edge3)); Assert.IsFalse(filteredGraph.ContainsEdge(edge4)); Assert.IsTrue(filteredGraph.ContainsEdge(otherEdge1)); wrappedGraph.AddVerticesAndEdge(edge4); Assert.IsTrue(filteredGraph.ContainsEdge(edge1)); Assert.IsTrue(filteredGraph.ContainsEdge(edge2)); Assert.IsTrue(filteredGraph.ContainsEdge(edge3)); Assert.IsFalse(filteredGraph.ContainsEdge(edge4)); // Filtered Assert.IsTrue(filteredGraph.ContainsEdge(otherEdge1)); wrappedGraph.AddVerticesAndEdge(otherEdge1); Assert.IsTrue(filteredGraph.ContainsEdge(edge1)); Assert.IsTrue(filteredGraph.ContainsEdge(edge2)); Assert.IsTrue(filteredGraph.ContainsEdge(edge3)); Assert.IsFalse(filteredGraph.ContainsEdge(edge4)); // Filtered Assert.IsTrue(filteredGraph.ContainsEdge(otherEdge1)); // Both vertices not in graph Assert.IsFalse(filteredGraph.ContainsEdge(new EquatableEdge<int>(0, 10))); // Source not in graph Assert.IsFalse(filteredGraph.ContainsEdge(new EquatableEdge<int>(0, 1))); // Target not in graph Assert.IsFalse(filteredGraph.ContainsEdge(new EquatableEdge<int>(1, 0))); #endregion #region Part 4 wrappedGraph.Clear(); filteredGraph = createFilteredGraph( vertex => vertex > 0 && vertex < 3, edge => edge.Source != edge.Target); Assert.IsFalse(filteredGraph.ContainsEdge(edge1)); Assert.IsFalse(filteredGraph.ContainsEdge(edge2)); Assert.IsFalse(filteredGraph.ContainsEdge(edge3)); Assert.IsFalse(filteredGraph.ContainsEdge(edge4)); Assert.IsFalse(filteredGraph.ContainsEdge(otherEdge1)); wrappedGraph.AddVerticesAndEdge(edge1); Assert.IsTrue(filteredGraph.ContainsEdge(edge1)); Assert.IsFalse(filteredGraph.ContainsEdge(edge2)); Assert.IsFalse(filteredGraph.ContainsEdge(edge3)); Assert.IsFalse(filteredGraph.ContainsEdge(edge4)); Assert.IsTrue(filteredGraph.ContainsEdge(otherEdge1)); wrappedGraph.AddVerticesAndEdge(edge2); Assert.IsTrue(filteredGraph.ContainsEdge(edge1)); Assert.IsFalse(filteredGraph.ContainsEdge(edge2)); // Filtered Assert.IsFalse(filteredGraph.ContainsEdge(edge3)); Assert.IsFalse(filteredGraph.ContainsEdge(edge4)); Assert.IsTrue(filteredGraph.ContainsEdge(otherEdge1)); wrappedGraph.AddVerticesAndEdge(edge3); Assert.IsTrue(filteredGraph.ContainsEdge(edge1)); Assert.IsFalse(filteredGraph.ContainsEdge(edge2)); // Filtered Assert.IsTrue(filteredGraph.ContainsEdge(edge3)); Assert.IsFalse(filteredGraph.ContainsEdge(edge4)); Assert.IsTrue(filteredGraph.ContainsEdge(otherEdge1)); wrappedGraph.AddVerticesAndEdge(edge4); Assert.IsTrue(filteredGraph.ContainsEdge(edge1)); Assert.IsFalse(filteredGraph.ContainsEdge(edge2)); // Filtered Assert.IsTrue(filteredGraph.ContainsEdge(edge3)); Assert.IsFalse(filteredGraph.ContainsEdge(edge4)); // Filtered Assert.IsTrue(filteredGraph.ContainsEdge(otherEdge1)); wrappedGraph.AddVerticesAndEdge(otherEdge1); Assert.IsTrue(filteredGraph.ContainsEdge(edge1)); Assert.IsFalse(filteredGraph.ContainsEdge(edge2)); // Filtered Assert.IsTrue(filteredGraph.ContainsEdge(edge3)); Assert.IsFalse(filteredGraph.ContainsEdge(edge4)); // Filtered Assert.IsTrue(filteredGraph.ContainsEdge(otherEdge1)); // Both vertices not in graph Assert.IsFalse(filteredGraph.ContainsEdge(new EquatableEdge<int>(0, 10))); // Source not in graph Assert.IsFalse(filteredGraph.ContainsEdge(new EquatableEdge<int>(0, 1))); // Target not in graph Assert.IsFalse(filteredGraph.ContainsEdge(new EquatableEdge<int>(1, 0))); #endregion } protected static void ContainsEdge_SourceTarget_Test<TGraph>( [NotNull] TGraph wrappedGraph, [NotNull] Func<VertexPredicate<int>, EdgePredicate<int, Edge<int>>, IIncidenceGraph<int, Edge<int>>> createFilteredGraph) where TGraph : IMutableVertexAndEdgeSet<int, Edge<int>>, IMutableGraph<int, Edge<int>> { #region Part 1 ContainsEdge_SourceTarget_ImmutableGraph_Test( wrappedGraph, () => createFilteredGraph(_ => true, _ => true)); #endregion #region Part 2 wrappedGraph.Clear(); IIncidenceGraph<int, Edge<int>> filteredGraph = createFilteredGraph( vertex => vertex > 0 && vertex < 3, _ => true); var edge1 = new Edge<int>(1, 2); var edge2 = new Edge<int>(1, 3); var edge3 = new Edge<int>(2, 2); Assert.IsFalse(filteredGraph.ContainsEdge(1, 2)); Assert.IsFalse(filteredGraph.ContainsEdge(2, 1)); wrappedGraph.AddVerticesAndEdge(edge1); Assert.IsTrue(filteredGraph.ContainsEdge(1, 2)); Assert.IsFalse(filteredGraph.ContainsEdge(2, 1)); wrappedGraph.AddVerticesAndEdge(edge2); Assert.IsFalse(filteredGraph.ContainsEdge(1, 3)); // Filtered Assert.IsFalse(filteredGraph.ContainsEdge(3, 1)); // Filtered wrappedGraph.AddVerticesAndEdge(edge3); Assert.IsTrue(filteredGraph.ContainsEdge(2, 2)); // Vertices is not present in the graph Assert.IsFalse(filteredGraph.ContainsEdge(0, 4)); Assert.IsFalse(filteredGraph.ContainsEdge(1, 4)); Assert.IsFalse(filteredGraph.ContainsEdge(4, 1)); #endregion #region Part 3 wrappedGraph.Clear(); filteredGraph = createFilteredGraph( _ => true, edge => edge.Source != edge.Target); Assert.IsFalse(filteredGraph.ContainsEdge(1, 2)); Assert.IsFalse(filteredGraph.ContainsEdge(2, 1)); wrappedGraph.AddVerticesAndEdge(edge1); Assert.IsTrue(filteredGraph.ContainsEdge(1, 2)); Assert.IsFalse(filteredGraph.ContainsEdge(2, 1)); wrappedGraph.AddVerticesAndEdge(edge2); Assert.IsTrue(filteredGraph.ContainsEdge(1, 3)); Assert.IsFalse(filteredGraph.ContainsEdge(3, 1)); wrappedGraph.AddVerticesAndEdge(edge3); Assert.IsFalse(filteredGraph.ContainsEdge(2, 2)); // Filtered // Vertices is not present in the graph Assert.IsFalse(filteredGraph.ContainsEdge(0, 4)); Assert.IsFalse(filteredGraph.ContainsEdge(1, 4)); Assert.IsFalse(filteredGraph.ContainsEdge(4, 1)); #endregion #region Part 4 wrappedGraph.Clear(); filteredGraph = createFilteredGraph( vertex => vertex > 0 && vertex < 3, edge => edge.Source != edge.Target); Assert.IsFalse(filteredGraph.ContainsEdge(1, 2)); Assert.IsFalse(filteredGraph.ContainsEdge(2, 1)); wrappedGraph.AddVerticesAndEdge(edge1); Assert.IsTrue(filteredGraph.ContainsEdge(1, 2)); Assert.IsFalse(filteredGraph.ContainsEdge(2, 1)); wrappedGraph.AddVerticesAndEdge(edge2); Assert.IsFalse(filteredGraph.ContainsEdge(1, 3)); // Filtered Assert.IsFalse(filteredGraph.ContainsEdge(3, 1)); // Filtered wrappedGraph.AddVerticesAndEdge(edge3); Assert.IsFalse(filteredGraph.ContainsEdge(2, 2)); // Filtered // Vertices is not present in the graph Assert.IsFalse(filteredGraph.ContainsEdge(0, 4)); Assert.IsFalse(filteredGraph.ContainsEdge(1, 4)); Assert.IsFalse(filteredGraph.ContainsEdge(4, 1)); #endregion } protected static void ContainsEdge_SourceTarget_UndirectedGraph_Test<TGraph>( [NotNull] TGraph wrappedGraph, [NotNull] Func<VertexPredicate<int>, EdgePredicate<int, Edge<int>>, IImplicitUndirectedGraph<int, Edge<int>>> createFilteredGraph) where TGraph : IMutableVertexAndEdgeSet<int, Edge<int>>, IMutableGraph<int, Edge<int>> { #region Part 1 ContainsEdge_SourceTarget_ImmutableGraph_UndirectedGraph_Test( wrappedGraph, () => createFilteredGraph(_ => true, _ => true)); #endregion #region Part 2 wrappedGraph.Clear(); IImplicitUndirectedGraph<int, Edge<int>> filteredGraph = createFilteredGraph( vertex => vertex > 0 && vertex < 3, _ => true); var edge1 = new Edge<int>(1, 2); var edge2 = new Edge<int>(1, 3); var edge3 = new Edge<int>(2, 2); Assert.IsFalse(filteredGraph.ContainsEdge(1, 2)); Assert.IsFalse(filteredGraph.ContainsEdge(2, 1)); wrappedGraph.AddVerticesAndEdge(edge1); Assert.IsTrue(filteredGraph.ContainsEdge(1, 2)); Assert.IsTrue(filteredGraph.ContainsEdge(2, 1)); wrappedGraph.AddVerticesAndEdge(edge2); Assert.IsFalse(filteredGraph.ContainsEdge(1, 3)); // Filtered Assert.IsFalse(filteredGraph.ContainsEdge(3, 1)); // Filtered wrappedGraph.AddVerticesAndEdge(edge3); Assert.IsTrue(filteredGraph.ContainsEdge(2, 2)); // Vertices is not present in the graph Assert.IsFalse(filteredGraph.ContainsEdge(0, 4)); Assert.IsFalse(filteredGraph.ContainsEdge(1, 4)); Assert.IsFalse(filteredGraph.ContainsEdge(4, 1)); #endregion #region Part 3 wrappedGraph.Clear(); filteredGraph = createFilteredGraph( _ => true, edge => edge.Source != edge.Target); Assert.IsFalse(filteredGraph.ContainsEdge(1, 2)); Assert.IsFalse(filteredGraph.ContainsEdge(2, 1)); wrappedGraph.AddVerticesAndEdge(edge1); Assert.IsTrue(filteredGraph.ContainsEdge(1, 2)); Assert.IsTrue(filteredGraph.ContainsEdge(2, 1)); wrappedGraph.AddVerticesAndEdge(edge2); Assert.IsTrue(filteredGraph.ContainsEdge(1, 3)); Assert.IsTrue(filteredGraph.ContainsEdge(3, 1)); wrappedGraph.AddVerticesAndEdge(edge3); Assert.IsFalse(filteredGraph.ContainsEdge(2, 2)); // Filtered // Vertices is not present in the graph Assert.IsFalse(filteredGraph.ContainsEdge(0, 4)); Assert.IsFalse(filteredGraph.ContainsEdge(1, 4)); Assert.IsFalse(filteredGraph.ContainsEdge(4, 1)); #endregion #region Part 4 wrappedGraph.Clear(); filteredGraph = createFilteredGraph( vertex => vertex > 0 && vertex < 3, edge => edge.Source != edge.Target); Assert.IsFalse(filteredGraph.ContainsEdge(1, 2)); Assert.IsFalse(filteredGraph.ContainsEdge(2, 1)); wrappedGraph.AddVerticesAndEdge(edge1); Assert.IsTrue(filteredGraph.ContainsEdge(1, 2)); Assert.IsTrue(filteredGraph.ContainsEdge(2, 1)); wrappedGraph.AddVerticesAndEdge(edge2); Assert.IsFalse(filteredGraph.ContainsEdge(1, 3)); // Filtered Assert.IsFalse(filteredGraph.ContainsEdge(3, 1)); // Filtered wrappedGraph.AddVerticesAndEdge(edge3); Assert.IsFalse(filteredGraph.ContainsEdge(2, 2)); // Filtered // Vertices is not present in the graph Assert.IsFalse(filteredGraph.ContainsEdge(0, 4)); Assert.IsFalse(filteredGraph.ContainsEdge(1, 4)); Assert.IsFalse(filteredGraph.ContainsEdge(4, 1)); #endregion } #endregion #region Out Edges protected static void OutEdge_Test<TGraph>( [NotNull] TGraph wrappedGraph, [NotNull] Func<VertexPredicate<int>, EdgePredicate<int, Edge<int>>, IImplicitGraph<int, Edge<int>>> createFilteredGraph) where TGraph : IMutableVertexAndEdgeSet<int, Edge<int>>, IMutableGraph<int, Edge<int>> { #region Part 1 OutEdge_ImmutableGraph_Test( wrappedGraph, () => createFilteredGraph(_ => true, _ => true)); #endregion #region Part 2 wrappedGraph.Clear(); var edge11 = new Edge<int>(1, 1); var edge12 = new Edge<int>(1, 2); var edge13 = new Edge<int>(1, 3); var edge24 = new Edge<int>(2, 4); var edge33 = new Edge<int>(3, 3); var edge34 = new Edge<int>(3, 4); var edge41 = new Edge<int>(4, 1); wrappedGraph.AddVerticesAndEdgeRange(new[] { edge11, edge12, edge13, edge24, edge33, edge34, edge41 }); IImplicitGraph<int, Edge<int>> filteredGraph = createFilteredGraph( vertex => vertex < 4, _ => true); Assert.AreSame(edge11, filteredGraph.OutEdge(1, 0)); Assert.AreSame(edge13, filteredGraph.OutEdge(1, 2)); Assert.AreSame(edge33, filteredGraph.OutEdge(3, 0)); // ReSharper disable once ReturnValueOfPureMethodIsNotUsed Assert.Throws<VertexNotFoundException>(() => filteredGraph.OutEdge(4, 0)); // Filtered #endregion #region Part 3 wrappedGraph.Clear(); wrappedGraph.AddVerticesAndEdgeRange(new[] { edge11, edge12, edge13, edge24, edge33, edge34, edge41 }); filteredGraph = createFilteredGraph( _ => true, edge => edge.Source != edge.Target); Assert.AreSame(edge12, filteredGraph.OutEdge(1, 0)); Assert.AreSame(edge13, filteredGraph.OutEdge(1, 1)); Assert.AreSame(edge34, filteredGraph.OutEdge(3, 0)); // ReSharper disable once ReturnValueOfPureMethodIsNotUsed AssertIndexOutOfRange(() => filteredGraph.OutEdge(3, 1)); // Filtered #endregion #region Part 4 wrappedGraph.Clear(); wrappedGraph.AddVerticesAndEdgeRange(new[] { edge11, edge12, edge13, edge24, edge33, edge34, edge41 }); filteredGraph = createFilteredGraph( vertex => vertex < 4, edge => edge.Source != edge.Target); Assert.AreSame(edge12, filteredGraph.OutEdge(1, 0)); Assert.AreSame(edge13, filteredGraph.OutEdge(1, 1)); // ReSharper disable ReturnValueOfPureMethodIsNotUsed AssertIndexOutOfRange(() => filteredGraph.OutEdge(3, 0)); // Filtered Assert.Throws<VertexNotFoundException>(() => filteredGraph.OutEdge(4, 1)); // Filtered // ReSharper restore ReturnValueOfPureMethodIsNotUsed #endregion } protected static void OutEdge_Throws_Test<TGraph>( [NotNull] TGraph wrappedGraph, [NotNull] Func<VertexPredicate<int>, EdgePredicate<int, Edge<int>>, IImplicitGraph<int, Edge<int>>> createFilteredGraph) where TGraph : IMutableVertexAndEdgeSet<int, Edge<int>>, IMutableGraph<int, Edge<int>> { #region Part 1 OutEdge_Throws_ImmutableGraph_Test( wrappedGraph, () => createFilteredGraph(_ => true, _ => true)); #endregion #region Part 2 // ReSharper disable ReturnValueOfPureMethodIsNotUsed const int vertex1 = 1; const int vertex2 = 2; const int vertex3 = 3; wrappedGraph.Clear(); wrappedGraph.AddVerticesAndEdgeRange(new[] { new Edge<int>(vertex1, vertex1), new Edge<int>(vertex1, vertex2), new Edge<int>(vertex1, vertex3), new Edge<int>(vertex2, vertex3), new Edge<int>(vertex3, vertex1) }); IImplicitGraph<int, Edge<int>> filteredGraph = createFilteredGraph( vertex => vertex < 3, _ => true); AssertIndexOutOfRange(() => filteredGraph.OutEdge(vertex1, 2)); Assert.Throws<VertexNotFoundException>(() => filteredGraph.OutEdge(vertex3, 0)); // ReSharper restore ReturnValueOfPureMethodIsNotUsed #endregion #region Part 3 // ReSharper disable ReturnValueOfPureMethodIsNotUsed const int vertex4 = 4; wrappedGraph.Clear(); wrappedGraph.AddVerticesAndEdgeRange(new[] { new Edge<int>(vertex1, vertex1), new Edge<int>(vertex1, vertex2), new Edge<int>(vertex1, vertex3), new Edge<int>(vertex2, vertex3), new Edge<int>(vertex3, vertex1) }); filteredGraph = createFilteredGraph( _ => true, edge => edge.Source != 1); AssertIndexOutOfRange(() => filteredGraph.OutEdge(vertex1, 0)); Assert.Throws<VertexNotFoundException>(() => filteredGraph.OutEdge(vertex4, 0)); // ReSharper restore ReturnValueOfPureMethodIsNotUsed #endregion #region Part 4 // ReSharper disable ReturnValueOfPureMethodIsNotUsed wrappedGraph.Clear(); wrappedGraph.AddVerticesAndEdgeRange(new[] { new Edge<int>(vertex1, vertex1), new Edge<int>(vertex1, vertex2), new Edge<int>(vertex1, vertex3), new Edge<int>(vertex2, vertex2), new Edge<int>(vertex2, vertex3), new Edge<int>(vertex3, vertex1) }); filteredGraph = createFilteredGraph( vertex => vertex < 3, edge => edge.Source != 1); AssertIndexOutOfRange(() => filteredGraph.OutEdge(vertex1, 0)); AssertIndexOutOfRange(() => filteredGraph.OutEdge(vertex2, 1)); Assert.Throws<VertexNotFoundException>(() => filteredGraph.OutEdge(vertex4, 0)); // ReSharper restore ReturnValueOfPureMethodIsNotUsed #endregion } protected static void OutEdges_Test<TGraph>( [NotNull] TGraph wrappedGraph, [NotNull] Func<VertexPredicate<int>, EdgePredicate<int, Edge<int>>, IImplicitGraph<int, Edge<int>>> createFilteredGraph) where TGraph : IMutableVertexAndEdgeSet<int, Edge<int>>, IMutableGraph<int, Edge<int>> { #region Part 1 OutEdges_ImmutableGraph_Test( wrappedGraph, () => createFilteredGraph(_ => true, _ => true)); #endregion #region Part 2 wrappedGraph.Clear(); var edge12 = new Edge<int>(1, 2); var edge13 = new Edge<int>(1, 3); var edge14 = new Edge<int>(1, 4); var edge15 = new Edge<int>(1, 5); var edge24 = new Edge<int>(2, 4); var edge31 = new Edge<int>(3, 1); var edge33 = new Edge<int>(3, 3); IImplicitGraph<int, Edge<int>> filteredGraph = createFilteredGraph( vertex => vertex < 4, _ => true); wrappedGraph.AddVertex(1); AssertNoOutEdge(filteredGraph, 1); wrappedGraph.AddVerticesAndEdgeRange(new[] { edge12, edge13, edge14, edge15, edge24, edge31, edge33 }); AssertHasOutEdges(filteredGraph, 1, new[] { edge12, edge13 }); // Filtered AssertNoOutEdge(filteredGraph, 2); // Filtered AssertHasOutEdges(filteredGraph, 3, new[] { edge31, edge33 }); #endregion #region Part 3 wrappedGraph.Clear(); filteredGraph = createFilteredGraph( _ => true, edge => edge.Source != edge.Target); wrappedGraph.AddVertex(1); AssertNoOutEdge(filteredGraph, 1); wrappedGraph.AddVerticesAndEdgeRange(new[] { edge12, edge13, edge14, edge15, edge24, edge31, edge33 }); AssertHasOutEdges(filteredGraph, 1, new[] { edge12, edge13, edge14, edge15 }); AssertHasOutEdges(filteredGraph, 2, new[] { edge24 }); AssertHasOutEdges(filteredGraph, 3, new[] { edge31 }); // Filtered #endregion #region Part 4 wrappedGraph.Clear(); filteredGraph = createFilteredGraph( vertex => vertex < 4, edge => edge.Source != edge.Target); wrappedGraph.AddVertex(1); AssertNoOutEdge(filteredGraph, 1); wrappedGraph.AddVerticesAndEdgeRange(new[] { edge12, edge13, edge14, edge15, edge24, edge31, edge33 }); AssertHasOutEdges(filteredGraph, 1, new[] { edge12, edge13 }); // Filtered AssertNoOutEdge(filteredGraph, 2); // Filtered AssertHasOutEdges(filteredGraph, 3, new[] { edge31 }); // Filtered #endregion } #endregion #region In Edges protected static void InEdge_Test<TGraph>( [NotNull] TGraph wrappedGraph, [NotNull] Func<VertexPredicate<int>, EdgePredicate<int, Edge<int>>, IBidirectionalIncidenceGraph<int, Edge<int>>> createFilteredGraph) where TGraph : IMutableVertexAndEdgeSet<int, Edge<int>>, IMutableGraph<int, Edge<int>> { #region Part 1 InEdge_ImmutableGraph_Test( wrappedGraph, () => createFilteredGraph(_ => true, _ => true)); #endregion #region Part 2 wrappedGraph.Clear(); var edge11 = new Edge<int>(1, 1); var edge13 = new Edge<int>(1, 3); var edge14 = new Edge<int>(1, 4); var edge21 = new Edge<int>(2, 1); wrappedGraph.AddVerticesAndEdgeRange(new[] { edge11, edge13, edge14, edge21 }); IBidirectionalIncidenceGraph<int, Edge<int>> filteredGraph = createFilteredGraph( vertex => vertex < 4, _ => true); Assert.AreSame(edge11, filteredGraph.InEdge(1, 0)); Assert.AreSame(edge21, filteredGraph.InEdge(1, 1)); Assert.AreSame(edge13, filteredGraph.InEdge(3, 0)); // ReSharper disable ReturnValueOfPureMethodIsNotUsed AssertIndexOutOfRange(() => filteredGraph.InEdge(1, 2)); // Filtered Assert.Throws<VertexNotFoundException>(() => filteredGraph.InEdge(4, 0)); // Filtered // ReSharper restore ReturnValueOfPureMethodIsNotUsed #endregion #region Part 3 wrappedGraph.Clear(); wrappedGraph.AddVerticesAndEdgeRange(new[] { edge11, edge13, edge14, edge21 }); filteredGraph = createFilteredGraph( _ => true, edge => edge.Source != edge.Target); Assert.AreSame(edge21, filteredGraph.InEdge(1, 0)); // Filtered Assert.AreSame(edge13, filteredGraph.InEdge(3, 0)); Assert.AreSame(edge14, filteredGraph.InEdge(4, 0)); #endregion #region Part 4 wrappedGraph.Clear(); wrappedGraph.AddVerticesAndEdgeRange(new[] { edge11, edge13, edge14, edge21 }); filteredGraph = createFilteredGraph( vertex => vertex < 4, edge => edge.Source != edge.Target); // ReSharper disable ReturnValueOfPureMethodIsNotUsed Assert.AreSame(edge21, filteredGraph.InEdge(1, 0)); // Filtered Assert.AreSame(edge13, filteredGraph.InEdge(3, 0)); AssertIndexOutOfRange(() => filteredGraph.InEdge(1, 2)); // Filtered Assert.Throws<VertexNotFoundException>(() => filteredGraph.InEdge(4, 0)); // Filtered // ReSharper restore ReturnValueOfPureMethodIsNotUsed #endregion } protected static void InEdge_Throws_Test<TGraph>( [NotNull] TGraph wrappedGraph, [NotNull] Func<VertexPredicate<int>, EdgePredicate<int, Edge<int>>, IBidirectionalIncidenceGraph<int, Edge<int>>> createFilteredGraph) where TGraph : IMutableVertexAndEdgeSet<int, Edge<int>>, IMutableGraph<int, Edge<int>> { #region Part 1 InEdge_Throws_ImmutableGraph_Test( wrappedGraph, () => createFilteredGraph(_ => true, _ => true)); #endregion #region Part 2 // ReSharper disable ReturnValueOfPureMethodIsNotUsed const int vertex1 = 1; const int vertex2 = 2; const int vertex3 = 3; wrappedGraph.Clear(); wrappedGraph.AddVerticesAndEdgeRange(new[] { new Edge<int>(vertex1, vertex1), new Edge<int>(vertex1, vertex3), new Edge<int>(vertex2, vertex1), new Edge<int>(vertex3, vertex1), new Edge<int>(vertex3, vertex2) }); IBidirectionalIncidenceGraph<int, Edge<int>> filteredGraph = createFilteredGraph( vertex => vertex < 3, _ => true); AssertIndexOutOfRange(() => filteredGraph.InEdge(vertex1, 2)); Assert.Throws<VertexNotFoundException>(() => filteredGraph.InEdge(vertex3, 0)); // ReSharper restore ReturnValueOfPureMethodIsNotUsed #endregion #region Part 3 wrappedGraph.Clear(); wrappedGraph.AddVerticesAndEdgeRange(new[] { new Edge<int>(vertex1, vertex1), new Edge<int>(vertex1, vertex3), new Edge<int>(vertex2, vertex1), new Edge<int>(vertex3, vertex1), new Edge<int>(vertex3, vertex2) }); filteredGraph = createFilteredGraph( _ => true, edge => edge.Source != edge.Target); // ReSharper disable once ReturnValueOfPureMethodIsNotUsed AssertIndexOutOfRange(() => filteredGraph.InEdge(vertex1, 2)); #endregion #region Part 4 // ReSharper disable ReturnValueOfPureMethodIsNotUsed wrappedGraph.Clear(); wrappedGraph.AddVerticesAndEdgeRange(new[] { new Edge<int>(vertex1, vertex1), new Edge<int>(vertex1, vertex3), new Edge<int>(vertex2, vertex1), new Edge<int>(vertex3, vertex1), new Edge<int>(vertex3, vertex2) }); filteredGraph = createFilteredGraph( vertex => vertex < 3, edge => edge.Source != edge.Target); AssertIndexOutOfRange(() => filteredGraph.InEdge(vertex1, 1)); Assert.Throws<VertexNotFoundException>(() => filteredGraph.InEdge(vertex3, 0)); // ReSharper restore ReturnValueOfPureMethodIsNotUsed #endregion } protected static void InEdges_Test<TGraph>( [NotNull] TGraph wrappedGraph, [NotNull] Func<VertexPredicate<int>, EdgePredicate<int, Edge<int>>, IBidirectionalIncidenceGraph<int, Edge<int>>> createFilteredGraph) where TGraph : IMutableVertexAndEdgeSet<int, Edge<int>>, IMutableGraph<int, Edge<int>> { #region Part 1 InEdges_ImmutableGraph_Test( wrappedGraph, () => createFilteredGraph(_ => true, _ => true)); #endregion #region Part 2 wrappedGraph.Clear(); var edge12 = new Edge<int>(1, 2); var edge13 = new Edge<int>(1, 3); var edge14 = new Edge<int>(1, 4); var edge24 = new Edge<int>(2, 4); var edge32 = new Edge<int>(3, 2); var edge33 = new Edge<int>(3, 3); IBidirectionalIncidenceGraph<int, Edge<int>> filteredGraph = createFilteredGraph( vertex => vertex < 4, _ => true); wrappedGraph.AddVertex(1); AssertNoInEdge(filteredGraph, 1); AssertNoOutEdge(filteredGraph, 1); wrappedGraph.AddVerticesAndEdgeRange(new[] { edge12, edge13, edge14, edge24, edge32, edge33 }); AssertHasOutEdges(filteredGraph, 1, new[] { edge12, edge13 }); // Filtered AssertNoOutEdge(filteredGraph, 2); // Filtered AssertHasOutEdges(filteredGraph, 3, new[] { edge32, edge33 }); AssertNoInEdge(filteredGraph, 1); AssertHasInEdges(filteredGraph, 2, new[] { edge12, edge32 }); AssertHasInEdges(filteredGraph, 3, new[] { edge13, edge33 }); #endregion #region Part 3 wrappedGraph.Clear(); filteredGraph = createFilteredGraph( _ => true, edge => edge.Source != edge.Target); wrappedGraph.AddVertex(1); AssertNoInEdge(filteredGraph, 1); AssertNoOutEdge(filteredGraph, 1); wrappedGraph.AddVerticesAndEdgeRange(new[] { edge12, edge13, edge14, edge24, edge32, edge33 }); AssertHasOutEdges(filteredGraph, 1, new[] { edge12, edge13, edge14 }); AssertHasOutEdges(filteredGraph, 2, new[] { edge24 }); AssertHasOutEdges(filteredGraph, 3, new[] { edge32 }); // Filtered AssertNoInEdge(filteredGraph, 1); AssertHasInEdges(filteredGraph, 2, new[] { edge12, edge32 }); AssertHasInEdges(filteredGraph, 3, new[] { edge13 }); // Filtered #endregion #region Part 4 wrappedGraph.Clear(); filteredGraph = createFilteredGraph( vertex => vertex < 4, edge => edge.Source != edge.Target); wrappedGraph.AddVertex(1); AssertNoInEdge(filteredGraph, 1); AssertNoOutEdge(filteredGraph, 1); wrappedGraph.AddVerticesAndEdgeRange(new[] { edge12, edge13, edge14, edge24, edge32, edge33 }); AssertHasOutEdges(filteredGraph, 1, new[] { edge12, edge13 }); // Filtered AssertNoOutEdge(filteredGraph, 2); // Filtered AssertHasOutEdges(filteredGraph, 3, new[] { edge32 }); // Filtered AssertNoInEdge(filteredGraph, 1); AssertHasInEdges(filteredGraph, 2, new[] { edge12, edge32 }); AssertHasInEdges(filteredGraph, 3, new[] { edge13 }); // Filtered #endregion } #endregion #region Adjacent Edges protected static void AdjacentEdge_Test<TGraph>( [NotNull] TGraph wrappedGraph, [NotNull] Func<VertexPredicate<int>, EdgePredicate<int, Edge<int>>, IImplicitUndirectedGraph<int, Edge<int>>> createFilteredGraph) where TGraph : IMutableVertexAndEdgeSet<int, Edge<int>>, IMutableGraph<int, Edge<int>> { #region Part 1 AdjacentEdge_ImmutableGraph_Test( wrappedGraph, () => createFilteredGraph(_ => true, _ => true)); #endregion #region Part 2 wrappedGraph.Clear(); var edge11 = new Edge<int>(1, 1); var edge12 = new Edge<int>(1, 2); var edge13 = new Edge<int>(1, 3); var edge24 = new Edge<int>(2, 4); var edge33 = new Edge<int>(3, 3); var edge41 = new Edge<int>(4, 1); wrappedGraph.AddVerticesAndEdgeRange(new[] { edge11, edge12, edge13, edge24, edge33, edge41 }); IImplicitUndirectedGraph<int, Edge<int>> filteredGraph = createFilteredGraph( vertex => vertex < 4, _ => true); Assert.AreSame(edge11, filteredGraph.AdjacentEdge(1, 0)); Assert.AreSame(edge13, filteredGraph.AdjacentEdge(1, 2)); Assert.AreSame(edge13, filteredGraph.AdjacentEdge(3, 0)); Assert.AreSame(edge33, filteredGraph.AdjacentEdge(3, 1)); // ReSharper disable once ReturnValueOfPureMethodIsNotUsed Assert.Throws<VertexNotFoundException>(() => filteredGraph.AdjacentEdge(4, 1)); // Filtered #endregion #region Part 3 wrappedGraph.Clear(); wrappedGraph.AddVerticesAndEdgeRange(new[] { edge11, edge12, edge13, edge24, edge33, edge41 }); filteredGraph = createFilteredGraph( _ => true, edge => edge.Source != edge.Target); Assert.AreSame(edge12, filteredGraph.AdjacentEdge(1, 0)); Assert.AreSame(edge13, filteredGraph.AdjacentEdge(1, 1)); Assert.AreSame(edge13, filteredGraph.AdjacentEdge(3, 0)); // ReSharper disable once ReturnValueOfPureMethodIsNotUsed AssertIndexOutOfRange(() => filteredGraph.AdjacentEdge(3, 1)); // Filtered #endregion #region Part 4 wrappedGraph.Clear(); wrappedGraph.AddVerticesAndEdgeRange(new[] { edge11, edge12, edge13, edge24, edge33, edge41 }); filteredGraph = createFilteredGraph( vertex => vertex < 4, edge => edge.Source != edge.Target); Assert.AreSame(edge12, filteredGraph.AdjacentEdge(1, 0)); Assert.AreSame(edge13, filteredGraph.AdjacentEdge(1, 1)); Assert.AreSame(edge13, filteredGraph.AdjacentEdge(3, 0)); // ReSharper disable ReturnValueOfPureMethodIsNotUsed AssertIndexOutOfRange(() => filteredGraph.AdjacentEdge(3, 1)); // Filtered Assert.Throws<VertexNotFoundException>(() => filteredGraph.AdjacentEdge(4, 1)); // Filtered // ReSharper restore ReturnValueOfPureMethodIsNotUsed #endregion } protected static void AdjacentEdge_Throws_Test<TGraph>( [NotNull] TGraph wrappedGraph, [NotNull] Func<VertexPredicate<int>, EdgePredicate<int, Edge<int>>, IImplicitUndirectedGraph<int, Edge<int>>> createFilteredGraph) where TGraph : IMutableVertexAndEdgeSet<int, Edge<int>>, IMutableGraph<int, Edge<int>> { #region Part 1 AdjacentEdge_Throws_ImmutableGraph_Test( wrappedGraph, () => createFilteredGraph(_ => true, _ => true)); #endregion #region Part 2 // ReSharper disable ReturnValueOfPureMethodIsNotUsed const int vertex1 = 1; const int vertex2 = 2; const int vertex3 = 3; wrappedGraph.Clear(); wrappedGraph.AddVerticesAndEdgeRange(new[] { new Edge<int>(vertex1, vertex1), new Edge<int>(vertex1, vertex2), new Edge<int>(vertex1, vertex3), new Edge<int>(vertex2, vertex3), new Edge<int>(vertex3, vertex1) }); IImplicitUndirectedGraph<int, Edge<int>> filteredGraph = createFilteredGraph( vertex => vertex < 3, _ => true); AssertIndexOutOfRange(() => filteredGraph.AdjacentEdge(vertex1, 2)); Assert.Throws<VertexNotFoundException>(() => filteredGraph.AdjacentEdge(vertex3, 0)); // ReSharper restore ReturnValueOfPureMethodIsNotUsed #endregion #region Part 3 // ReSharper disable ReturnValueOfPureMethodIsNotUsed const int vertex4 = 4; const int vertex5 = 5; wrappedGraph.Clear(); wrappedGraph.AddVerticesAndEdgeRange(new[] { new Edge<int>(vertex1, vertex1), new Edge<int>(vertex1, vertex2), new Edge<int>(vertex1, vertex3), new Edge<int>(vertex2, vertex3), new Edge<int>(vertex3, vertex4) }); filteredGraph = createFilteredGraph( _ => true, edge => edge.Source != 1); AssertIndexOutOfRange(() => filteredGraph.AdjacentEdge(vertex1, 0)); AssertIndexOutOfRange(() => filteredGraph.AdjacentEdge(vertex2, 1)); Assert.Throws<VertexNotFoundException>(() => filteredGraph.AdjacentEdge(vertex5, 0)); // ReSharper restore ReturnValueOfPureMethodIsNotUsed #endregion #region Part 4 // ReSharper disable ReturnValueOfPureMethodIsNotUsed wrappedGraph.Clear(); wrappedGraph.AddVerticesAndEdgeRange(new[] { new Edge<int>(vertex1, vertex1), new Edge<int>(vertex1, vertex2), new Edge<int>(vertex1, vertex3), new Edge<int>(vertex2, vertex2), new Edge<int>(vertex2, vertex3), new Edge<int>(vertex3, vertex1) }); filteredGraph = createFilteredGraph( vertex => vertex < 3, edge => edge.Source != 1); AssertIndexOutOfRange(() => filteredGraph.AdjacentEdge(vertex1, 0)); AssertIndexOutOfRange(() => filteredGraph.AdjacentEdge(vertex2, 1)); Assert.Throws<VertexNotFoundException>(() => filteredGraph.AdjacentEdge(vertex4, 0)); // ReSharper restore ReturnValueOfPureMethodIsNotUsed #endregion } protected static void AdjacentEdges_Test<TGraph>( [NotNull] TGraph wrappedGraph, [NotNull] Func<VertexPredicate<int>, EdgePredicate<int, Edge<int>>, IImplicitUndirectedGraph<int, Edge<int>>> createFilteredGraph) where TGraph : IMutableVertexAndEdgeSet<int, Edge<int>>, IMutableGraph<int, Edge<int>> { #region Part1 AdjacentEdges_ImmutableGraph_Test( wrappedGraph, () => createFilteredGraph(_ => true, _ => true)); #endregion #region Part 2 wrappedGraph.Clear(); var edge12 = new Edge<int>(1, 2); var edge13 = new Edge<int>(1, 3); var edge14 = new Edge<int>(1, 4); var edge24 = new Edge<int>(2, 4); var edge31 = new Edge<int>(3, 1); var edge33 = new Edge<int>(3, 3); IImplicitUndirectedGraph<int, Edge<int>> filteredGraph = createFilteredGraph( vertex => vertex <= 4, _ => true); wrappedGraph.AddVertex(1); AssertNoAdjacentEdge(filteredGraph, 1); wrappedGraph.AddVertex(5); var edge15 = new Edge<int>(1, 5); wrappedGraph.AddVerticesAndEdgeRange(new[] { edge12, edge13, edge14, edge15, edge24, edge31, edge33 }); AssertHasAdjacentEdges(filteredGraph, 1, new[] { edge12, edge13, edge14, edge31 }); AssertHasAdjacentEdges(filteredGraph, 2, new[] { edge12, edge24 }); AssertHasAdjacentEdges(filteredGraph, 3, new[] { edge13, edge31, edge33 }, 4); // Has self edge counting twice AssertHasAdjacentEdges(filteredGraph, 4, new[] { edge14, edge24 }); #endregion #region Part 3 wrappedGraph.Clear(); filteredGraph = createFilteredGraph( _ => true, edge => edge.Source != edge.Target); wrappedGraph.AddVertex(1); AssertNoAdjacentEdge(filteredGraph, 1); wrappedGraph.AddVertex(5); wrappedGraph.AddVerticesAndEdgeRange(new[] { edge12, edge13, edge14, edge15, edge24, edge31, edge33 }); AssertHasAdjacentEdges(filteredGraph, 1, new[] { edge12, edge13, edge14, edge15, edge31 }); AssertHasAdjacentEdges(filteredGraph, 2, new[] { edge12, edge24 }); AssertHasAdjacentEdges(filteredGraph, 3, new[] { edge13, edge31 }); AssertHasAdjacentEdges(filteredGraph, 4, new[] { edge14, edge24 }); #endregion #region Part 4 wrappedGraph.Clear(); filteredGraph = createFilteredGraph( vertex => vertex <= 4, edge => edge.Source != edge.Target); wrappedGraph.AddVertex(1); AssertNoAdjacentEdge(filteredGraph, 1); wrappedGraph.AddVertex(5); wrappedGraph.AddVerticesAndEdgeRange(new[] { edge12, edge13, edge14, edge15, edge24, edge31, edge33 }); AssertHasAdjacentEdges(filteredGraph, 1, new[] { edge12, edge13, edge14, edge31 }); AssertHasAdjacentEdges(filteredGraph, 2, new[] { edge12, edge24 }); AssertHasAdjacentEdges(filteredGraph, 3, new[] { edge13, edge31 }); AssertHasAdjacentEdges(filteredGraph, 4, new[] { edge14, edge24 }); #endregion } #endregion #region Degree protected static void Degree_Test<TGraph>( [NotNull] TGraph wrappedGraph, [NotNull] Func<VertexPredicate<int>, EdgePredicate<int, Edge<int>>, IBidirectionalIncidenceGraph<int, Edge<int>>> createFilteredGraph) where TGraph : IMutableVertexAndEdgeSet<int, Edge<int>>, IMutableGraph<int, Edge<int>> { #region Part 1 Degree_ImmutableGraph_Test( wrappedGraph, () => createFilteredGraph(_ => true, _ => true)); #endregion #region Part 2 // ReSharper disable ReturnValueOfPureMethodIsNotUsed wrappedGraph.Clear(); var edge1 = new Edge<int>(1, 2); var edge2 = new Edge<int>(1, 3); var edge3 = new Edge<int>(1, 4); var edge4 = new Edge<int>(2, 4); var edge5 = new Edge<int>(3, 2); var edge6 = new Edge<int>(3, 3); wrappedGraph.AddVerticesAndEdgeRange(new[] { edge1, edge2, edge3, edge4, edge5, edge6 }); wrappedGraph.AddVertex(5); IBidirectionalIncidenceGraph<int, Edge<int>> filteredGraph = createFilteredGraph( vertex => vertex < 4, _ => true); Assert.AreEqual(2, filteredGraph.Degree(1)); // Filtered Assert.AreEqual(2, filteredGraph.Degree(2)); // Filtered Assert.AreEqual(4, filteredGraph.Degree(3)); // Self edge Assert.Throws<VertexNotFoundException>(() => filteredGraph.Degree(4)); // Filtered Assert.Throws<VertexNotFoundException>(() => filteredGraph.Degree(5)); // Filtered // ReSharper restore ReturnValueOfPureMethodIsNotUsed #endregion #region Part 3 // ReSharper disable ReturnValueOfPureMethodIsNotUsed wrappedGraph.Clear(); wrappedGraph.AddVerticesAndEdgeRange(new[] { edge1, edge2, edge3, edge4, edge5, edge6 }); wrappedGraph.AddVertex(5); filteredGraph = createFilteredGraph( _ => true, edge => edge.Source != edge.Target); Assert.AreEqual(3, filteredGraph.Degree(1)); Assert.AreEqual(3, filteredGraph.Degree(2)); Assert.AreEqual(2, filteredGraph.Degree(3)); // Filtered Assert.AreEqual(2, filteredGraph.Degree(4)); Assert.AreEqual(0, filteredGraph.Degree(5)); // ReSharper restore ReturnValueOfPureMethodIsNotUsed #endregion #region Part 4 // ReSharper disable ReturnValueOfPureMethodIsNotUsed wrappedGraph.Clear(); wrappedGraph.AddVerticesAndEdgeRange(new[] { edge1, edge2, edge3, edge4, edge5, edge6 }); wrappedGraph.AddVertex(5); filteredGraph = createFilteredGraph( vertex => vertex < 4, edge => edge.Source != edge.Target); Assert.AreEqual(2, filteredGraph.Degree(1)); // Filtered Assert.AreEqual(2, filteredGraph.Degree(2)); // Filtered Assert.AreEqual(2, filteredGraph.Degree(3)); // Filtered Assert.Throws<VertexNotFoundException>(() => filteredGraph.Degree(4)); // Filtered Assert.Throws<VertexNotFoundException>(() => filteredGraph.Degree(5)); // Filtered // ReSharper restore ReturnValueOfPureMethodIsNotUsed #endregion } #endregion #region Try Get Edges protected static void TryGetEdge_Test<TGraph>( [NotNull] TGraph wrappedGraph, [NotNull] Func<VertexPredicate<int>, EdgePredicate<int, Edge<int>>, IIncidenceGraph<int, Edge<int>>> createFilteredGraph) where TGraph : IMutableVertexAndEdgeSet<int, Edge<int>>, IMutableGraph<int, Edge<int>> { #region Part 1 TryGetEdge_ImmutableGraph_Test( wrappedGraph, () => createFilteredGraph(_ => true, _ => true)); #endregion #region Part 2 wrappedGraph.Clear(); var edge1 = new Edge<int>(1, 2); var edge2 = new Edge<int>(1, 2); var edge3 = new Edge<int>(1, 3); var edge4 = new Edge<int>(2, 2); var edge5 = new Edge<int>(2, 4); var edge6 = new Edge<int>(3, 1); var edge7 = new Edge<int>(5, 2); wrappedGraph.AddVerticesAndEdgeRange(new[] { edge1, edge2, edge3, edge4, edge5, edge6, edge7 }); IIncidenceGraph<int, Edge<int>> filteredGraph = createFilteredGraph( vertex => vertex <= 4, _ => true); Assert.IsFalse(filteredGraph.TryGetEdge(0, 10, out _)); Assert.IsFalse(filteredGraph.TryGetEdge(0, 1, out _)); Assert.IsTrue(filteredGraph.TryGetEdge(2, 4, out Edge<int> gotEdge)); Assert.AreSame(edge5, gotEdge); Assert.IsTrue(filteredGraph.TryGetEdge(2, 2, out gotEdge)); Assert.AreSame(edge4, gotEdge); Assert.IsTrue(filteredGraph.TryGetEdge(1, 2, out gotEdge)); Assert.AreSame(edge1, gotEdge); Assert.IsFalse(filteredGraph.TryGetEdge(2, 1, out _)); Assert.IsFalse(filteredGraph.TryGetEdge(5, 2, out _)); // Filtered Assert.IsFalse(filteredGraph.TryGetEdge(2, 5, out _)); // Filtered #endregion #region Part 3 wrappedGraph.Clear(); wrappedGraph.AddVerticesAndEdgeRange(new[] { edge1, edge2, edge3, edge4, edge5, edge6, edge7 }); filteredGraph = createFilteredGraph( _ => true, edge => edge.Source != edge.Target); Assert.IsFalse(filteredGraph.TryGetEdge(0, 10, out _)); Assert.IsFalse(filteredGraph.TryGetEdge(0, 1, out _)); Assert.IsTrue(filteredGraph.TryGetEdge(2, 4, out gotEdge)); Assert.AreSame(edge5, gotEdge); Assert.IsFalse(filteredGraph.TryGetEdge(2, 2, out gotEdge)); // Filtered Assert.IsTrue(filteredGraph.TryGetEdge(1, 2, out gotEdge)); Assert.AreSame(edge1, gotEdge); Assert.IsFalse(filteredGraph.TryGetEdge(2, 1, out _)); Assert.IsTrue(filteredGraph.TryGetEdge(5, 2, out gotEdge)); Assert.AreSame(edge7, gotEdge); #endregion #region Part 4 wrappedGraph.Clear(); wrappedGraph.AddVerticesAndEdgeRange(new[] { edge1, edge2, edge3, edge4, edge5, edge6, edge7 }); filteredGraph = createFilteredGraph( vertex => vertex <= 4, edge => edge.Source != edge.Target); Assert.IsFalse(filteredGraph.TryGetEdge(0, 10, out _)); Assert.IsFalse(filteredGraph.TryGetEdge(0, 1, out _)); Assert.IsTrue(filteredGraph.TryGetEdge(2, 4, out gotEdge)); Assert.AreSame(edge5, gotEdge); Assert.IsFalse(filteredGraph.TryGetEdge(2, 2, out _)); // Filtered Assert.IsTrue(filteredGraph.TryGetEdge(1, 2, out gotEdge)); Assert.AreSame(edge1, gotEdge); Assert.IsFalse(filteredGraph.TryGetEdge(2, 1, out _)); Assert.IsFalse(filteredGraph.TryGetEdge(5, 2, out _)); // Filtered Assert.IsFalse(filteredGraph.TryGetEdge(2, 5, out _)); // Filtered #endregion } protected static void TryGetEdges_Test<TGraph>( [NotNull] TGraph wrappedGraph, [NotNull] Func<VertexPredicate<int>, EdgePredicate<int, Edge<int>>, IIncidenceGraph<int, Edge<int>>> createFilteredGraph) where TGraph : IMutableVertexAndEdgeSet<int, Edge<int>>, IMutableGraph<int, Edge<int>> { #region Part 1 TryGetEdges_Test( createFilteredGraph(_ => true, _ => true), edges => wrappedGraph.AddVerticesAndEdgeRange(edges)); #endregion #region Part 2 wrappedGraph.Clear(); var edge1 = new Edge<int>(1, 2); var edge2 = new Edge<int>(1, 2); var edge3 = new Edge<int>(1, 3); var edge4 = new Edge<int>(2, 2); var edge5 = new Edge<int>(2, 4); var edge6 = new Edge<int>(3, 1); wrappedGraph.AddVerticesAndEdgeRange(new[] { edge1, edge2, edge3, edge4, edge5, edge6 }); IIncidenceGraph<int, Edge<int>> filteredGraph = createFilteredGraph( vertex => vertex < 4, _ => true); Assert.IsFalse(filteredGraph.TryGetEdges(0, 10, out _)); Assert.IsFalse(filteredGraph.TryGetEdges(0, 1, out _)); Assert.IsTrue(filteredGraph.TryGetEdges(2, 2, out IEnumerable<Edge<int>> gotEdges)); CollectionAssert.AreEqual(new[] { edge4 }, gotEdges); Assert.IsFalse(filteredGraph.TryGetEdges(2, 4, out _)); // Filtered Assert.IsTrue(filteredGraph.TryGetEdges(1, 2, out gotEdges)); CollectionAssert.AreEqual(new[] { edge1, edge2 }, gotEdges); Assert.IsTrue(filteredGraph.TryGetEdges(2, 1, out gotEdges)); CollectionAssert.IsEmpty(gotEdges); #endregion #region Part 3 wrappedGraph.Clear(); wrappedGraph.AddVerticesAndEdgeRange(new[] { edge1, edge2, edge3, edge4, edge5, edge6 }); filteredGraph = createFilteredGraph( _ => true, edge => edge.Source != edge.Target); Assert.IsFalse(filteredGraph.TryGetEdges(0, 10, out _)); Assert.IsFalse(filteredGraph.TryGetEdges(0, 1, out _)); Assert.IsTrue(filteredGraph.TryGetEdges(2, 2, out gotEdges)); // Filtered CollectionAssert.IsEmpty(gotEdges); Assert.IsTrue(filteredGraph.TryGetEdges(2, 4, out gotEdges)); CollectionAssert.AreEqual(new[] { edge5 }, gotEdges); Assert.IsTrue(filteredGraph.TryGetEdges(1, 2, out gotEdges)); CollectionAssert.AreEqual(new[] { edge1, edge2 }, gotEdges); Assert.IsTrue(filteredGraph.TryGetEdges(2, 1, out gotEdges)); CollectionAssert.IsEmpty(gotEdges); #endregion #region Part 4 wrappedGraph.Clear(); wrappedGraph.AddVerticesAndEdgeRange(new[] { edge1, edge2, edge3, edge4, edge5, edge6 }); filteredGraph = createFilteredGraph( vertex => vertex < 4, edge => edge.Source != edge.Target); Assert.IsFalse(filteredGraph.TryGetEdges(0, 10, out _)); Assert.IsFalse(filteredGraph.TryGetEdges(0, 1, out _)); Assert.IsTrue(filteredGraph.TryGetEdges(2, 2, out gotEdges)); // Filtered CollectionAssert.IsEmpty(gotEdges); Assert.IsFalse(filteredGraph.TryGetEdges(2, 4, out _)); // Filtered Assert.IsTrue(filteredGraph.TryGetEdges(1, 2, out gotEdges)); CollectionAssert.AreEqual(new[] { edge1, edge2 }, gotEdges); Assert.IsTrue(filteredGraph.TryGetEdges(2, 1, out gotEdges)); CollectionAssert.IsEmpty(gotEdges); #endregion } protected static void TryGetEdge_UndirectedGraph_Test<TGraph>( [NotNull] TGraph wrappedGraph, [NotNull] Func<VertexPredicate<int>, EdgePredicate<int, Edge<int>>, IImplicitUndirectedGraph<int, Edge<int>>> createFilteredGraph) where TGraph : IMutableVertexAndEdgeSet<int, Edge<int>>, IMutableGraph<int, Edge<int>> { #region Part 1 TryGetEdge_ImmutableGraph_UndirectedGraph_Test( wrappedGraph, () => createFilteredGraph(_ => true, _ => true)); #endregion #region Part 2 wrappedGraph.Clear(); var edge1 = new Edge<int>(1, 2); var edge2 = new Edge<int>(1, 2); var edge3 = new Edge<int>(1, 3); var edge4 = new Edge<int>(2, 2); var edge5 = new Edge<int>(2, 4); var edge6 = new Edge<int>(3, 1); var edge7 = new Edge<int>(5, 2); wrappedGraph.AddVerticesAndEdgeRange(new[] { edge1, edge2, edge3, edge4, edge5, edge6, edge7 }); IImplicitUndirectedGraph<int, Edge<int>> filteredGraph = createFilteredGraph( vertex => vertex <= 4, _ => true); Assert.IsFalse(filteredGraph.TryGetEdge(0, 10, out _)); Assert.IsFalse(filteredGraph.TryGetEdge(0, 1, out _)); Assert.IsTrue(filteredGraph.TryGetEdge(2, 4, out Edge<int> gotEdge)); Assert.AreSame(edge5, gotEdge); Assert.IsTrue(filteredGraph.TryGetEdge(2, 2, out gotEdge)); Assert.AreSame(edge4, gotEdge); Assert.IsTrue(filteredGraph.TryGetEdge(1, 2, out gotEdge)); Assert.AreSame(edge1, gotEdge); // 1 -> 2 is present in this undirected graph Assert.IsTrue(filteredGraph.TryGetEdge(2, 1, out gotEdge)); Assert.AreSame(edge1, gotEdge); Assert.IsFalse(filteredGraph.TryGetEdge(5, 2, out _)); // Filtered Assert.IsFalse(filteredGraph.TryGetEdge(2, 5, out _)); // Filtered #endregion #region Part 3 wrappedGraph.Clear(); wrappedGraph.AddVerticesAndEdgeRange(new[] { edge1, edge2, edge3, edge4, edge5, edge6, edge7 }); filteredGraph = createFilteredGraph( _ => true, edge => edge.Source != edge.Target); Assert.IsFalse(filteredGraph.TryGetEdge(0, 10, out _)); Assert.IsFalse(filteredGraph.TryGetEdge(0, 1, out _)); Assert.IsTrue(filteredGraph.TryGetEdge(2, 4, out gotEdge)); Assert.AreSame(edge5, gotEdge); Assert.IsFalse(filteredGraph.TryGetEdge(2, 2, out gotEdge)); // Filtered Assert.IsTrue(filteredGraph.TryGetEdge(1, 2, out gotEdge)); Assert.AreSame(edge1, gotEdge); // 1 -> 2 is present in this undirected graph Assert.IsTrue(filteredGraph.TryGetEdge(2, 1, out gotEdge)); Assert.AreSame(edge1, gotEdge); Assert.IsTrue(filteredGraph.TryGetEdge(5, 2, out gotEdge)); Assert.AreSame(edge7, gotEdge); Assert.IsTrue(filteredGraph.TryGetEdge(2, 5, out gotEdge)); Assert.AreSame(edge7, gotEdge); #endregion #region Part 4 wrappedGraph.Clear(); wrappedGraph.AddVerticesAndEdgeRange(new[] { edge1, edge2, edge3, edge4, edge5, edge6, edge7 }); filteredGraph = createFilteredGraph( vertex => vertex <= 4, edge => edge.Source != edge.Target); Assert.IsFalse(filteredGraph.TryGetEdge(0, 10, out _)); Assert.IsFalse(filteredGraph.TryGetEdge(0, 1, out _)); Assert.IsTrue(filteredGraph.TryGetEdge(2, 4, out gotEdge)); Assert.AreSame(edge5, gotEdge); Assert.IsFalse(filteredGraph.TryGetEdge(2, 2, out _)); // Filtered Assert.IsTrue(filteredGraph.TryGetEdge(1, 2, out gotEdge)); Assert.AreSame(edge1, gotEdge); // 1 -> 2 is present in this undirected graph Assert.IsTrue(filteredGraph.TryGetEdge(2, 1, out gotEdge)); Assert.AreSame(edge1, gotEdge); Assert.IsFalse(filteredGraph.TryGetEdge(5, 2, out _)); // Filtered Assert.IsFalse(filteredGraph.TryGetEdge(2, 5, out _)); // Filtered #endregion } protected static void TryGetOutEdges_Test<TGraph>( [NotNull] TGraph wrappedGraph, [NotNull] Func<VertexPredicate<int>, EdgePredicate<int, Edge<int>>, IImplicitGraph<int, Edge<int>>> createFilteredGraph) where TGraph : IMutableVertexAndEdgeSet<int, Edge<int>>, IMutableGraph<int, Edge<int>> { #region Part 1 TryGetOutEdges_Test( createFilteredGraph(_ => true, _ => true), edges => wrappedGraph.AddVerticesAndEdgeRange(edges)); #endregion #region Part 2 wrappedGraph.Clear(); var edge1 = new Edge<int>(1, 2); var edge2 = new Edge<int>(1, 2); var edge3 = new Edge<int>(1, 3); var edge4 = new Edge<int>(2, 2); var edge5 = new Edge<int>(2, 3); var edge6 = new Edge<int>(2, 4); var edge7 = new Edge<int>(4, 3); var edge8 = new Edge<int>(4, 5); wrappedGraph.AddVerticesAndEdgeRange(new[] { edge1, edge2, edge3, edge4, edge5, edge6, edge7, edge8 }); IImplicitGraph<int, Edge<int>> filteredGraph = createFilteredGraph( vertex => vertex <= 4, _ => true); Assert.IsFalse(filteredGraph.TryGetOutEdges(0, out _)); Assert.IsFalse(filteredGraph.TryGetOutEdges(5, out _)); // Filtered Assert.IsTrue(filteredGraph.TryGetOutEdges(3, out IEnumerable<Edge<int>> gotEdges)); CollectionAssert.IsEmpty(gotEdges); Assert.IsTrue(filteredGraph.TryGetOutEdges(4, out gotEdges)); CollectionAssert.AreEqual(new[] { edge7 }, gotEdges); // Filtered Assert.IsTrue(filteredGraph.TryGetOutEdges(2, out gotEdges)); CollectionAssert.AreEqual(new[] { edge4, edge5, edge6 }, gotEdges); #endregion #region Part 3 wrappedGraph.Clear(); wrappedGraph.AddVerticesAndEdgeRange(new[] { edge1, edge2, edge3, edge4, edge5, edge6, edge7, edge8 }); filteredGraph = createFilteredGraph( _ => true, edge => edge.Source != edge.Target); Assert.IsFalse(filteredGraph.TryGetOutEdges(0, out _)); Assert.IsTrue(filteredGraph.TryGetOutEdges(5, out gotEdges)); CollectionAssert.IsEmpty(gotEdges); Assert.IsTrue(filteredGraph.TryGetOutEdges(3, out gotEdges)); CollectionAssert.IsEmpty(gotEdges); Assert.IsTrue(filteredGraph.TryGetOutEdges(4, out gotEdges)); CollectionAssert.AreEqual(new[] { edge7, edge8 }, gotEdges); Assert.IsTrue(filteredGraph.TryGetOutEdges(2, out gotEdges)); CollectionAssert.AreEqual(new[] { edge5, edge6 }, gotEdges); // Filtered #endregion #region Part 4 wrappedGraph.Clear(); wrappedGraph.AddVerticesAndEdgeRange(new[] { edge1, edge2, edge3, edge4, edge5, edge6, edge7, edge8 }); filteredGraph = createFilteredGraph( vertex => vertex <= 4, edge => edge.Source != edge.Target); Assert.IsFalse(filteredGraph.TryGetOutEdges(0, out _)); Assert.IsFalse(filteredGraph.TryGetOutEdges(5, out _)); // Filtered Assert.IsTrue(filteredGraph.TryGetOutEdges(3, out gotEdges)); CollectionAssert.IsEmpty(gotEdges); Assert.IsTrue(filteredGraph.TryGetOutEdges(4, out gotEdges)); CollectionAssert.AreEqual(new[] { edge7 }, gotEdges); // Filtered Assert.IsTrue(filteredGraph.TryGetOutEdges(2, out gotEdges)); CollectionAssert.AreEqual(new[] { edge5, edge6 }, gotEdges); // Filtered #endregion } protected static void TryGetInEdges_Test<TGraph>( [NotNull] TGraph wrappedGraph, [NotNull] Func<VertexPredicate<int>, EdgePredicate<int, Edge<int>>, IBidirectionalIncidenceGraph<int, Edge<int>>> createFilteredGraph) where TGraph : IMutableVertexAndEdgeSet<int, Edge<int>>, IMutableGraph<int, Edge<int>> { #region Part 1 TryGetInEdges_Test( createFilteredGraph(_ => true, _ => true), edges => wrappedGraph.AddVerticesAndEdgeRange(edges)); #endregion #region Part 2 wrappedGraph.Clear(); var edge1 = new Edge<int>(1, 2); var edge2 = new Edge<int>(1, 2); var edge3 = new Edge<int>(1, 3); var edge4 = new Edge<int>(2, 2); var edge5 = new Edge<int>(2, 4); var edge6 = new Edge<int>(3, 1); var edge7 = new Edge<int>(5, 3); wrappedGraph.AddVerticesAndEdgeRange(new[] { edge1, edge2, edge3, edge4, edge5, edge6, edge7 }); IBidirectionalIncidenceGraph<int, Edge<int>> filteredGraph = createFilteredGraph( vertex => vertex <= 4, _ => true); Assert.IsFalse(filteredGraph.TryGetInEdges(0, out _)); Assert.IsFalse(filteredGraph.TryGetInEdges(5, out _)); // Filtered Assert.IsTrue(filteredGraph.TryGetInEdges(4, out IEnumerable<Edge<int>> gotEdges)); CollectionAssert.AreEqual(new[] { edge5 }, gotEdges); Assert.IsTrue(filteredGraph.TryGetInEdges(2, out gotEdges)); CollectionAssert.AreEqual(new[] { edge1, edge2, edge4 }, gotEdges); #endregion #region Part 3 wrappedGraph.Clear(); wrappedGraph.AddVerticesAndEdgeRange(new[] { edge1, edge2, edge3, edge4, edge5, edge6, edge7 }); filteredGraph = createFilteredGraph( _ => true, edge => edge.Source != edge.Target); Assert.IsFalse(filteredGraph.TryGetInEdges(0, out _)); Assert.IsTrue(filteredGraph.TryGetInEdges(5, out gotEdges)); CollectionAssert.IsEmpty(gotEdges); Assert.IsTrue(filteredGraph.TryGetInEdges(4, out gotEdges)); CollectionAssert.AreEqual(new[] { edge5 }, gotEdges); Assert.IsTrue(filteredGraph.TryGetInEdges(2, out gotEdges)); CollectionAssert.AreEqual(new[] { edge1, edge2 }, gotEdges); // Filtered #endregion #region Part 4 wrappedGraph.Clear(); wrappedGraph.AddVerticesAndEdgeRange(new[] { edge1, edge2, edge3, edge4, edge5, edge6, edge7 }); filteredGraph = createFilteredGraph( vertex => vertex <= 4, edge => edge.Source != edge.Target); Assert.IsFalse(filteredGraph.TryGetInEdges(0, out _)); Assert.IsFalse(filteredGraph.TryGetInEdges(5, out _)); // Filtered Assert.IsTrue(filteredGraph.TryGetInEdges(4, out gotEdges)); CollectionAssert.AreEqual(new[] { edge5 }, gotEdges); Assert.IsTrue(filteredGraph.TryGetInEdges(2, out gotEdges)); CollectionAssert.AreEqual(new[] { edge1, edge2 }, gotEdges); // Filtered #endregion } #endregion } }
9cb60ebb4e381948330f621e8446bd23c0000aa0
C#
ShabnamZ/GoldBadgeChallenges
/02_ClaimConsole/ClaimUI.cs
3.28125
3
using _02_ClaimRepository; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _02_ClaimConsole { public class ProgramUI { private ClaimRepository _claimRepo = new ClaimRepository(); public void Run() { SeedClaimList(); RunMenu(); } private void RunMenu() { bool continueToRunMenu = true; while (continueToRunMenu) { Console.Clear(); Console.WriteLine("welcome to Komodo Claims Department.\n" + "1.See all claims list.\n" + "2.Take care of next claim.\n" + "3.Enter a new claim.\n" + "4.Exit."); string userInput = Console.ReadLine(); switch (userInput) { case "1": GetListOfClaims(); break; case "2": TakeNextClaim(); break; case "3": AddClaimToQueue(); break; case "4": continueToRunMenu = false; break; default: Console.WriteLine("Please enter a valid number between 1 and 5.\n" + "Press any key to continue..."); Console.ReadKey(); break; } } } private void GetListOfClaims() { Queue<Claim> queueOfClaims = _claimRepo.GetListOfClaims(); foreach (Claim claim in queueOfClaims) { Console.WriteLine($" {claim.ClaimID} {claim.TypeOfClaim} {claim.Description} {claim.ClaimAmount} {claim.DateOfIncident} {claim.DateOfClaim} {claim.IsValid}"); } Console.WriteLine("Press any key to continue...."); Console.ReadKey(); } private void AddClaimToQueue() { Claim claim = new Claim(); //Get Claim ID Console.Write("Please enter a claim ID: "); int claimID = int.Parse(Console.ReadLine()); //Get ClaimType Console.Write("What is the claim type?\n " + "1.Car\n" + "2.Home\n" + "3.Theft"); int claimNumber = int.Parse(Console.ReadLine()); claim.TypeOfClaim = (ClaimType)claimNumber; //Get Description Console.Write("Please enter a description...."); claim.Description = Console.ReadLine(); //ClaimAmount Console.Write("Please enter the claim amount: $ "); decimal claimAmount = decimal.Parse(Console.ReadLine()); //Date Of Incident Console.Write("Please enter the date of incident: mm/dd/yyyy "); claim.DateOfIncident = DateTime.Parse(Console.ReadLine()); //Date of Claim Console.Write("Please enter the date of claim: mm/dd/yyyy "); claim.DateOfClaim = DateTime.Parse(Console.ReadLine()); //Is claim valid Console.Write("This claim is valid."); Console.ReadKey(); TimeSpan difference = claim.DateOfClaim - claim.DateOfIncident; double Days = difference.TotalDays; if (difference.TotalDays <= 30) { claim.IsValid = true; } else claim.IsValid = false; _claimRepo.AddClaimToQueue(claim); } private void TakeNextClaim() { Console.WriteLine("ClaimID:\n" + "TypeOfClaim:\n" + "Description:\n" + "ClaimAmount:\n" + "DateOfIncident:\n" + "DateOfClaim:\n" + "IsValid:"); Console.WriteLine("Do you want to deal with this claim now(y/n)?" ); string respond = Console.ReadLine(); switch (respond) { case "y": _claimRepo.TakeNextClaim(); break; case "n": break; } Console.ReadKey(); } private void SeedClaimList() { Claim car = new Claim(1, ClaimType.Car, "Car accident on 465", 400, Convert.ToDateTime("2018/4/25"), Convert.ToDateTime("2018/4/27"), true); Claim house = new Claim(2, ClaimType.Home, "House in fire", 4000, Convert.ToDateTime("2018/4/26"), Convert.ToDateTime("2018/4/28"), true); Claim theft = new Claim(3, ClaimType.Theft, "Stolen lawnmover", 150, Convert.ToDateTime("2018/4/27"), Convert.ToDateTime("2018/8/16"), false); _claimRepo.AddClaimToQueue(car); _claimRepo.AddClaimToQueue(house); _claimRepo.AddClaimToQueue(theft); } } }
ef9dcc2f17cb57c78c39831601910f2d7ee91d2f
C#
Cormac131/A2Project
/C#/Application Test/MainControls/Login.cs
2.75
3
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Application_Test { public partial class Login : UserControl { string uname = "", pwd = ""; public Login() { InitializeComponent(); } private void _login() { if (txtUsername.Text == "" && txtPassword.Text == "") { Program.LoggedIn = false; MessageBox.Show("You must enter a username and password to log in!"); } else if (txtUsername.Text == "admin") { if (txtPassword.Text == "password") { Program.MainForm.ShowControl(ControlsEnum.DASHBOARD); Program.LoggedIn = true; } else { Program.LoggedIn = false; MessageBox.Show("Password is incorrect!"); txtPassword.Clear(); txtUsername.Clear(); } } else { Program.LoggedIn = false; MessageBox.Show("Username is incorrect!"); txtPassword.Clear(); txtUsername.Clear(); } } private void button1_Click(object sender, EventArgs e) { _login(); } private void txtUsername_TextChanged(object sender, EventArgs e) { uname = this.txtUsername.Text; } private void txtPassword_TextChanged(object sender, EventArgs e) { pwd = this.txtPassword.Text; } private void txtPassword_KeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar == Convert.ToChar(Keys.Return)) { _login(); } } } }
8e473a5e630d52b14d528d768917e7e49c453da2
C#
ZimingYuan/Cooking
/Assets/Scripts/CookingStepCollection.cs
2.546875
3
using System.Collections.Generic; using UnityEngine; using System.Linq; using UnityEngine.UI; public class CookingStepCollection { public List<CookingStep> CookingSteps; public CookingStepCollection() { CookingSteps = new List<CookingStep>(); } // 根据名字查找烹饪步骤对象 public CookingStep FindByName(string name) { return CookingSteps.Find((x) => x.Name == name); } private void Dfs(CookingStep x, List<CookingStep> y) { y.Add(x); x.DirectDepend.ForEach((z) => Dfs(z, y)); } // 计算烹饪步骤之间的依赖关系 public void CalcDepend() { CookingSteps.ForEach((x) => x.DirectDepend.ForEach((y) => Dfs(y, x.Depend))); CookingSteps.ForEach((x) => x.Depend.ForEach((y) => y.Control.Add(x))); } // 检查当前时间条上所有步骤是否合法,不合法变红色 public void CheckDepend() { var OnTimeHolder = (from x in CookingSteps where x.Belong != null select x).ToList(); OnTimeHolder.ForEach((cookingStep) => { Dragable dragable = cookingStep.GetComponent<Dragable>(); RectTransform dragRect = dragable.dragRect; bool f1 = (from x in cookingStep.Depend where x.Belong != null && x != cookingStep select x.GetComponent<RectTransform>()) .Any((x) => x.anchoredPosition.x + x.sizeDelta.x > dragRect.anchoredPosition.x); Rect t = new Rect(dragRect.anchoredPosition.x, 0, dragRect.sizeDelta.x, 1); bool f2 = CookingSteps .Where((x) => x.Belong != null && x != cookingStep && (!x.CanParallel && !cookingStep.CanParallel)) .Select((x) => x.GetComponent<RectTransform>()) .Select((x) => new Rect(x.anchoredPosition.x, 0, x.sizeDelta.x, 1)) .Any((x) => x.Overlaps(t)); bool f3 = cookingStep.Depend.Any((x) => x.Belong == null); if (f1 || f2 || f3) dragable.frameImage.GetComponent<Image>().color = Color.red; else { if (cookingStep.CanParallel) dragable.frameImage.GetComponent<Image>().color = Color.green; else dragable.frameImage.GetComponent<Image>().color = Color.white; } }); } }
033a362cdec349a64f48ada4a87d8b2234448abe
C#
Fantin-Verpillot/IziWatch
/IziWatch/DataAccess/Article.cs
2.75
3
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; namespace IziWatch.DataAccess { public class Article { public static bool CreateArticle(DBO.Article article) { using (IziWatchEntities bdd = new IziWatchEntities()) { try { T_Article t_article = new T_Article() { id = article.Id, title = article.Title, image = article.Image, category_id = article.CategoryId, text = article.Text, date = article.Date, views = article.Views }; bdd.T_Article.Add(t_article); bdd.SaveChanges(); return true; } catch (Exception e) { return false; } } } public static bool DeleteArticle(long id) { using (IziWatchEntities bdd = new IziWatchEntities()) { try { bdd.T_Article.Remove(bdd.T_Article.Where(x => x.id == id).FirstOrDefault()); bdd.SaveChanges(); return true; } catch (Exception e) { return false; } } } public static bool UpdateArticle(DBO.Article article) { using (IziWatchEntities bdd = new IziWatchEntities()) { try { T_Article t_article = bdd.T_Article.Where(x => x.id == article.Id).FirstOrDefault(); if (t_article != null) { t_article.id = article.Id; t_article.title = article.Title; t_article.image = article.Image; t_article.category_id = article.CategoryId; t_article.text = article.Text; t_article.date = article.Date; t_article.views = article.Views; bdd.SaveChanges(); return true; } else { return false; } } catch (Exception e) { return false; } } } public static DBO.Article GetArticle(long id) { using (IziWatchEntities bdd = new IziWatchEntities()) { try { var query = from article in bdd.T_Article where article.id == id select article; if (query.Any()) { return new DBO.Article() { Id = query.First().id, Title = query.First().title, Image = query.First().image, CategoryId = query.First().category_id, Text = query.First().text, Date = query.First().date, Views = query.First().views }; } else { return null; } } catch (Exception e) { return null; } } } public static List<DBO.Article> GetListArticle() { using (IziWatchEntities bdd = new IziWatchEntities()) { try { List<DBO.Article> listArticles = new List<DBO.Article>(); var query = from article in bdd.T_Article select article; foreach (var element in query) { listArticles.Add(new DBO.Article() { Id = element.id, Title = element.title, Image = element.image, CategoryId = element.category_id, Text = element.text, Date = element.date, Views = element.views }); } return listArticles; } catch (Exception e) { Debug.WriteLine(e.Message); return null; } } } } }
7169d19a4ca3de27a4821a77e0269fbb517bc119
C#
Titwin/TinyWorld
/Assets/Scripts/EquipementSystem/HeadItem.cs
2.578125
3
using System.Collections; using System.Collections.Generic; using UnityEngine; public class HeadItem : Item { public enum Type { None, NackedA, NackedB, NackedC, NackedD, NackedE, HeadbandA, HeadbandB, HeadbandC, HeadbandD, HeadbandE, HeadbandF, HoodA, HoodB, HoodC, HoodD, HoodE, ChainmailA, ChainmailB, ChainmailC, ChainmailD, ChainmailE, ChainmailF, SpangenhelmA, SpangenhelmB, SpangenhelmC, SalletA, SalletB, SalletC, SalletD, SalletE, SalletF, SalletG, HornA, HornB, HornC, HornD, HornE, HornF, HornG, HornH, HornI, SalletH, SalletI, SalletJ, BacinetA, BacinetB, BacinetC, BacinetD, BacinetE, HelmA, HelmB, HelmC, HelmD, HelmE, HelmF, HelmG, HelmH, HelmI, HelmJ, HatA, HatB, HatC, HatD, HatE, CrownA, CrownB, CrownC, CrownD, CrownE, HelmK, HelmL }; public enum Category { Cloth, Light, Medium, Heavy }; static public Type defaultType = Type.NackedA; [Header("Head Item")] public Type type = Type.None; public float armor = 0f; public List<string> crafting = new List<string>(); public void Clear() { type = Type.None; load = 0f; armor = 0f; } public override SummarizedItem Summarize() { SummarizedItem sumItem = base.Summarize(); sumItem.derivatedType = (int)type; return sumItem; } public bool IsDefault() { return type == defaultType; } public static void Copy(HeadItem source, HeadItem destination) { Item.Copy(source, destination); destination.type = source.type; destination.load = source.load; destination.armor = source.armor; } // helper for interaction system static public Category getCategory(Type type) { switch (type) { case Type.ChainmailA: case Type.ChainmailB: case Type.ChainmailC: case Type.ChainmailD: case Type.ChainmailE: case Type.ChainmailF: return Category.Light; case Type.SpangenhelmA: case Type.SpangenhelmB: case Type.SpangenhelmC: case Type.SalletA: case Type.SalletB: case Type.SalletC: case Type.SalletD: case Type.SalletE: case Type.SalletF: case Type.SalletG: case Type.SalletH: case Type.SalletI: case Type.SalletJ: case Type.BacinetA: case Type.BacinetB: case Type.BacinetC: case Type.BacinetD: case Type.BacinetE: case Type.HelmA: case Type.HelmB: case Type.HelmC: case Type.HelmD: case Type.HelmE: case Type.HelmF: case Type.HelmG: case Type.HelmH: case Type.HelmI: case Type.HelmJ: case Type.HelmK: case Type.HelmL: case Type.HornA: case Type.HornB: case Type.HornC: case Type.HornD: case Type.HornE: case Type.HornF: case Type.HornG: case Type.HornH: case Type.HornI: case Type.CrownC: case Type.CrownD: case Type.CrownE: return Category.Heavy; default: return Category.Cloth; } } }
805787d1cbf00f4da5c71de88f8139a03d4a1ab1
C#
RonnyVenegas/PaisMio
/Pais Mio Envasado/BL/BL_Insumo.cs
2.921875
3
using DAO; using DO; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BL { /// <summary> /// En esta clase se encuentra la logica de negocio de los insumos /// </summary> public class BL_Insumo { /// <summary> /// Con este método se puede guardar un insumo en la base de datos /// </summary> /// <param name="doInsumo">El insumo que se va a guardar</param> /// <returns></returns> public bool guardarInsumo(DO_Insumo doInsumo) { DAO_Insumo daoInsumo = new DAO_Insumo(); if (daoInsumo.guardarInsumo(doInsumo) > 0) { return true; } else { return false; } } /// <summary> /// Con este método se perminte sacar toda la lista de insumos /// </summary> /// <returns>La lista de insumos existentes</returns> public List<DO_Insumo> obtenerListaIsumos() { DAO_Insumo daoInsumo = new DAO_Insumo(); return daoInsumo.obtenerListaIsumos(); } } }
bc267ba27d31ed39c67fe35a75271b58afc161e4
C#
BorisLechev/Programming-Basics
/Documents/Github/Programming-Fundamentals/11. Programming Fundamentals Extended/Exams/Extended Exam - 20.08.2017/2.Entertrain/Program.cs
3.671875
4
namespace _2.Entertrain { using System; using System.Collections.Generic; using System.Linq; public class Entertrain { public static void Main() { int locomotivesPower = int.Parse(Console.ReadLine()); var wagonsAndWeight = new List<int>(); string input = string.Empty; while ((input = Console.ReadLine()) != "All ofboard!") { wagonsAndWeight.Add(int.Parse(input)); if (wagonsAndWeight.Sum() > locomotivesPower) { var closest = wagonsAndWeight.OrderBy(x => Math.Abs(x - wagonsAndWeight.Average())).First(); wagonsAndWeight.Remove(closest); } } wagonsAndWeight.Reverse(); Console.WriteLine(string.Join(" ", wagonsAndWeight) + " " + locomotivesPower); } } }
b7b1ff4ad72c926b1a843bfef5328da0e997755a
C#
Zagorouiko/Unity_SteamVR_Prototypes
/Assets/Scripts/RandomAgent.cs
2.515625
3
using UnityEngine; using System.Collections; [ RequireComponent (typeof(NavMeshAgent)) ] public class RandomAgent : MonoBehaviour { private NavMeshAgent agent; // Use this for initialization void Start () { agent = GetComponent<NavMeshAgent>(); } // Update is called once per frame void Update () { // Check if we've reached the destination if (!agent.pathPending) { if (agent.remainingDistance <= agent.stoppingDistance) { if (!agent.hasPath || agent.velocity.sqrMagnitude == 0f) { //Done NewDestination(); } } } } private void NewDestination() { Vector3 newDest = Random.insideUnitSphere * 15f; NavMeshHit hit; bool hasDestination = NavMesh.SamplePosition(newDest, out hit, 100f, 1); if (hasDestination) { agent.SetDestination(hit.position); } } }
94315bfbe5f8e75010df75232c8d7401af51caf3
C#
RafaNetow/TBGestor
/ManagerTool/ManagerTool/Clases/UserManager.cs
2.6875
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 System.Windows.Forms; using MySql.Data.MySqlClient; namespace ManagerTool.Clases { public class UserManager { public HandlerConnection ConnectionData; public UserManager(HandlerConnection connectionData) { this.ConnectionData = connectionData; } public DataTable GetFunctions() { var dataTable = new DataTable(); ConnectionData.conn.Open(); MySqlCommand myCommand = new MySqlCommand("SELECT SPECIFIC_NAME FROM INFORMATION_SCHEMA.ROUTINES WHERE ROUTINE_TYPE='FUNCTION'", ConnectionData.conn); MySqlDataReader myReader; try { myReader = myCommand.ExecuteReader(); if (myReader.HasRows) { MessageBox.Show("Alla va tu select vo"); dataTable.Load(myReader); ConnectionData.conn.Close(); myReader.Close(); return dataTable; } } catch (Exception ex) { MessageBox.Show(ex.Message); } ConnectionData.conn.Close(); return dataTable; } public DataTable GetTables() { var dataTable = new DataTable(); try { ConnectionData.conn.Open(); dataTable = ConnectionData.conn.GetSchema("Tables"); ConnectionData.conn.Close(); return dataTable; } catch (Exception ex) { MessageBox.Show(ex.Message); } return dataTable; } public DataTable GetColumnOfTable(String tableName) { var dataTable = new DataTable(); try { ConnectionData.conn.Open(); dataTable = ConnectionData.conn.GetSchema("Columns", new[] { null, null, tableName }); ConnectionData.conn.Close(); return dataTable; } catch (Exception ex) { MessageBox.Show(ex.Message); } return dataTable; } public DataTable getProcedureInformation() { var dataTable = new DataTable(); try { ConnectionData.conn.Open(); dataTable = ConnectionData.conn.GetSchema("Tables", new string[] {null, null, null, "TABLE"}); ConnectionData.conn.Close(); return dataTable; } catch (Exception ex) { MessageBox.Show(ex.Message); } return dataTable; } public TreeNode GeTreeNode(DataTable TableSchema, string NameRow,string TreeNodeName) { var rowTable = TableSchema.Select(NameRow+" <> ''"); var arrayTablas = rowTable.Select(row => new TreeNode((string)row[NameRow])).ToArray(); // var treeNode = new TreeNode(TreeNodeName, arrayTablas); return treeNode; } public DataTable GetProcedure() { var dataTable = new DataTable(); ConnectionData.conn.Open(); MySqlCommand myCommand = new MySqlCommand("SELECT SPECIFIC_NAME FROM INFORMATION_SCHEMA.ROUTINES WHERE ROUTINE_TYPE='PROCEDURE'", ConnectionData.conn); MySqlDataReader myReader; try { myReader = myCommand.ExecuteReader(); if (myReader.HasRows) { MessageBox.Show("Alla va tu select vo"); dataTable.Load(myReader); ConnectionData.conn.Close(); myReader.Close(); return dataTable; } } catch (Exception ex) { MessageBox.Show(ex.Message); } ConnectionData.conn.Close(); return dataTable; } public DataTable GetTrigger() { var dataTable = new DataTable(); try { ConnectionData.conn.Open(); dataTable = ConnectionData.conn.GetSchema("Triggers"); ConnectionData.conn.Close(); return dataTable; } catch (Exception ex) { MessageBox.Show(ex.Message); } return dataTable; } public DataTable GetView() { var dataTable = new DataTable(); try { ConnectionData.conn.Open(); dataTable = ConnectionData.conn.GetSchema("Views"); ConnectionData.conn.Close(); return dataTable; } catch (Exception ex) { MessageBox.Show(ex.Message); } return dataTable; } public DataTable GetTableSpace() { return new DataTable(); } } }
67b8288b44683aaff078c002a8fdef8a8362270b
C#
PeijinGit/EscapeRoute
/EscapeRoute/Business/UserBLL.cs
2.734375
3
using Business.Interfaces; using Microsoft.IdentityModel.Tokens; using Models; using System; using System.Collections.Generic; using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using System.Text; namespace Business { public class UserBLL : IUser { public User Login(string userName, string passWord) { List<User> userList = new List<User>() { new User(), new User("ASD","asd"), new User("ZXC","1241"), new User("hpjjphhpj","131415161718","Admin"), }; var user = userList.Find(ele => ele.UserId == userName && ele.Password == passWord); if (user != null) { var claims = new[] { new Claim(JwtRegisteredClaimNames.Nbf,$"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}") , new Claim (JwtRegisteredClaimNames.Exp,$"{new DateTimeOffset(DateTime.Now.AddMinutes(30)).ToUnixTimeSeconds()}"), new Claim(ClaimTypes.Name, userName) }; var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(ConstParam.SecurityKey)); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var token = new JwtSecurityToken( issuer: ConstParam.Domain, audience: ConstParam.Domain, claims: claims, expires: DateTime.Now.AddMinutes(30), signingCredentials: creds); user.Token = new JwtSecurityTokenHandler().WriteToken(token); user.Password = "Protected"; } return user; } } }
4226f1ec4d58d0a1c5ce0bd47a6a612bc4e7f252
C#
BHD233/OH-Record
/OHRecord/OHRecord/OHRecord/MainPage.xaml.cs
2.515625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace OHRecord { public class RecordTitle { public static string backGroundColor = "333333"; public Button summaryButton = new Button { Text = "...", BackgroundColor = Color.FromHex(backGroundColor), TextColor = Color.White, WidthRequest = Device.GetNamedSize(NamedSize.Small, typeof(Button)) * 3, FontSize = Device.GetNamedSize(NamedSize.Small, typeof(Button)), }; public Button viewButton = new Button { Text = "View", BackgroundColor = Color.FromHex(backGroundColor), TextColor = Color.White, WidthRequest = Device.GetNamedSize(NamedSize.Small, typeof(Button)) * 4, FontSize = Device.GetNamedSize(NamedSize.Small, typeof(Button)), }; public Button deleteButton = new Button { Text = "X", BackgroundColor = Color.FromHex(backGroundColor), TextColor = Color.White, WidthRequest = Device.GetNamedSize(NamedSize.Small, typeof(Button)) * 3, FontSize = Device.GetNamedSize(NamedSize.Small, typeof(Button)), }; public Label name = new Label { FontSize = Device.GetNamedSize(NamedSize.Large, typeof(Label)), HorizontalOptions = LayoutOptions.CenterAndExpand, BackgroundColor = Color.FromHex(backGroundColor), TextColor = Color.White, }; public StackLayout GetTitle() { StackLayout mainStack = new StackLayout { Orientation = StackOrientation.Horizontal, HorizontalOptions = LayoutOptions.FillAndExpand, }; mainStack.Children.Add(deleteButton); mainStack.Children.Add(name); mainStack.Children.Add(summaryButton); mainStack.Children.Add(viewButton); return mainStack; } } [XamlCompilation(XamlCompilationOptions.Compile)] public partial class MainPage : ContentPage { public static string endFile = ".BHD"; IFileHelper fileHelper = DependencyService.Get<IFileHelper>(); public MainPage() { Title = "Main Page"; InitializeComponent(); //RefreshList(); } private string GetFileName(string titleString) { string result = ""; //add to title string for (int i = titleString.Length - 1; i > 0 && titleString[i] != '/' && titleString[i] != '\\'; i--) { result += titleString[i]; } //revert it string temp = ""; for (int i = result.Length - 1; i >= 0; i--) { temp += result[i]; } return temp; } private string GetRidOfEndFile(string filename) { string result = ""; for (int i = 0; i < filename.Length - endFile.Length; i++) { result += filename[i]; } return result; } void RefreshList() { listStack.Children.Clear(); IEnumerable<string> titleStrings = fileHelper.GetFiles(); //ensure that it is all my file and get just file name List<string> filenames = new List<string>(); foreach (string title in titleStrings) { string filename = GetFileName(title); if (IsMyFile(filename)) { filename = GetRidOfEndFile(filename); filenames.Add(filename); } } //sort filename SortByDate(ref filenames); foreach (string filename in filenames) { RecordTitle currTitle = new RecordTitle(); //create handle and ID for button currTitle.summaryButton.StyleId = filename; currTitle.viewButton.StyleId = filename; currTitle.deleteButton.StyleId = filename; currTitle.summaryButton.Clicked += OnSummaryButtonClick; currTitle.viewButton.Clicked += OnViewButtonClick; currTitle.deleteButton.Clicked += OnDeleteButtonClick; //get tile to lable currTitle.name.Text = filename; //add to stack listStack.Children.Add(currTitle.GetTitle()); } } private bool IsMyFile(string filename) { int endFilePos = endFile.Length - 1; for (int i = filename.Length - 1; i > 0; i--) { //is match with end file if (endFilePos < 0) { break; } else if (filename[i] != endFile[endFilePos]) { return false; } else { endFilePos--; } } return true; } private int GetRelativeDateOfString(string filename) { int date = 0; int day = 0; int month = 0; bool isMonth = false; for (int i = 0; i < filename.Length; i++) { if (filename[i] >= '0' && filename[i] <= '9') { if (isMonth) { month = month * 10 + int.Parse(filename[i].ToString()); } else { day = day * 10 + int.Parse(filename[i].ToString()); ; } } if (filename[i] == '-') { isMonth = true; } } date = month * 100 + day; return date; } private List<int> GetRelativeDateOfList(List<string> filenames) { List<int> dates = new List<int>(); foreach (string filename in filenames) { dates.Add(GetRelativeDateOfString(filename)); } return dates; } private void Swap<T>(ref List<T> list, int a, int b) { T temp; temp = list[a]; list[a] = list[b]; list[b] = temp; } private void SortByDate(ref List<string> filenames) { //get ralative date to sort List<int> dates = GetRelativeDateOfList(filenames); //sort by relative date for (int i = 0; i < filenames.Count; i++) { for (int j = i + 1; j < filenames.Count; j++) { if (dates[i] < dates[j]) { Swap<int>(ref dates, i, j); Swap<string>(ref filenames, i, j); } } } } async void OnAddButtonClick(object sender, EventArgs args) { await Navigation.PushAsync(new NewRecordPage()); } async void OnSummaryButtonClick(object sender, EventArgs args) { Button button = (Button)sender; await Navigation.PushAsync(new SummaryPage(button.StyleId)); } async void OnViewButtonClick(object sender, EventArgs args) { Button button = (Button)sender; await Navigation.PushAsync(new OpenRecordPage(button.StyleId)); } async void OnDeleteButtonClick(object sender, EventArgs args) { bool isDeleteComfirmed = false; Button button = (Button)sender; Task<bool> comfirmDelete = DisplayAlert("Are you sure to delete the select item", "", "yes", "no"); isDeleteComfirmed = await comfirmDelete; if (true == isDeleteComfirmed) { string filename = button.StyleId; fileHelper.Delete(filename); RefreshList(); } } void OnRefreshButtonClick(object sender, EventArgs args) { RefreshList(); } protected override void OnAppearing() { base.OnAppearing(); RefreshList(); } } }
b3ea5c1a93d92eb0a71490b08088275b16ca5486
C#
shendongnian/download4
/code2/278537-5703518-12268816-2.cs
3.421875
3
public class Person { private string firstName; private string lastName; public Person(string firstName, string lastName) { //How could you set the first name passed in the constructor to the local variable if both have the same? this.firstName = firstName; this.lastName = lastName; } //... }
56a24cc819abdf6dcf5f6144bf7e95c27028e522
C#
GustavoCasco/Senai---Desenvolvimento-de-sistemas
/1° Semestre/exercicio em c#/média/Program.cs
3.3125
3
using System; namespace média { class Program { static void Main(string[] args) { double nota1= 0; double nota2 = 0; double nota3 = 0; double nota4 = 0; double média; Console.WriteLine("Digite a sua 1° nota:"); nota1 = double.Parse(Console.ReadLine()); Console.WriteLine ("Digite a sua 2° nota:"); nota2 = double.Parse(Console.ReadLine()); Console.WriteLine ("Digite a sua 3° nota:"); nota3 = double.Parse(Console.ReadLine()); Console.WriteLine ("Digite a sua 4° nota:"); nota4 = double.Parse(Console.ReadLine()); média = (nota1 + nota2 + nota3 + nota4) / 4 ; Console.WriteLine("Sua média é: " + média); if ( média >= 7){ Console.WriteLine("Aprovado"); }else { Console.WriteLine("Reprovado"); } } } }
523928522b40a36e93540e65ad791346d6a01ac5
C#
radtek/aria2gui
/Aria2/PortHelper.cs
2.625
3
using System; using System.Net; using System.Linq; using System.Net.NetworkInformation; namespace Aria2 { public class PortHelper { public int[] GetUsedPorts() { //获取本地计算机的网络连接和通信统计数据的信息 IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties(); //返回本地计算机上的所有Tcp监听程序 IPEndPoint[] ipsTCP = ipGlobalProperties.GetActiveTcpListeners(); //返回本地计算机上的所有UDP监听程序 IPEndPoint[] ipsUDP = ipGlobalProperties.GetActiveUdpListeners(); //返回本地计算机上的Internet协议版本4(IPV4 传输控制协议(TCP)连接的信息。 TcpConnectionInformation[] tcpConnInfoArray = ipGlobalProperties.GetActiveTcpConnections(); var list = tcpConnInfoArray.Where(en => en.State > TcpState.Closed && en.State < TcpState.CloseWait).Select(en => en.LocalEndPoint.Port).Concat(ipsTCP.Select(en => en.Port)).ToArray(); if (list.Contains(6800)) { } return list; } public int GetRandPort() { var usedPorts = GetUsedPorts(); var port = new Random().Next(1024, 65535); while (usedPorts.Contains(port)) { port = new Random().Next(1024, 65535); } return port; } } }
43fbf5528a38a8b9f31661cae100e6c8f8df79b5
C#
AndreasZach/CC_LagerSystem
/PizzaOrder.Tests/Fakes/TestHttpMessagehandlerTests.cs
2.734375
3
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Text; using System.Threading.Tasks; using Microsoft.VisualStudio.TestTools.UnitTesting; using Newtonsoft.Json; namespace PizzaOrder.Tests.Fakes { [TestClass] public class TestHttpMessageHandlerTests { [TestMethod] public async Task If_url_cannot_be_found_Should_throw_exception() { // Arrange var baseUri = "http://localhost:60479/"; var url = "Storage/RemoveItemAmount"; var jsonString = JsonConvert.SerializeObject(1); var httpResponseMessage = new HttpResponseMessage() { StatusCode = HttpStatusCode.OK, Content = new StringContent(jsonString) }; var client = CreateTestClient(baseUri, url, httpResponseMessage); // Act & Assert await Assert.ThrowsExceptionAsync<Exception>(() => client.GetAsync("wrongUrl")); } [TestMethod] public async Task If_url_cannot_be_found_Should_return_expected_result() { // Arrange var baseUri = "http://localhost:60479/"; var url = "Storage/RemoveItemAmount"; var jsonString = JsonConvert.SerializeObject(1); var httpResponseMessage = new HttpResponseMessage() { StatusCode = HttpStatusCode.OK, Content = new StringContent(jsonString) }; var client = CreateTestClient(baseUri, url, httpResponseMessage); // Act var result = await client.GetAsync(url); // Assert Assert.AreEqual(200, (int)result.StatusCode); var resultContent = await result.Content.ReadAsStringAsync(); Assert.AreEqual(jsonString, resultContent); } private HttpClient CreateTestClient(string baseUri, string url, HttpResponseMessage httpResponseMessage = null) { var requests = new Dictionary<string, HttpResponseMessage> { { baseUri + url, httpResponseMessage } }; var client = new HttpClient(new TestHttpMessageHandler(requests)) { BaseAddress = new Uri(baseUri) }; return client; } } }
0f9170ff4aecd47bb65e27b272f03d4a6217129a
C#
TalipSalihoglu/.NetCore-Patika
/MovieStore/Webapi/Application/MovieOperations/Commands/UpdateMovie/UpdateMovieCommand.cs
2.90625
3
using System.Collections.Generic; using System.Linq; using AutoMapper; using Webapi.DbOperations; using System; using Webapi.Entities; namespace WebApi.Application.MovieOperations.Commands.UpdateMovie{ public class UpdateMovieCommand{ private readonly MovieStoreDbContext _context; public UpdateMovieModel Model{get;set;} public int MovieId{get;set;} public UpdateMovieCommand(MovieStoreDbContext context) { _context = context; } public void Handle(){ var movie=_context.Movies.SingleOrDefault(x=>x.Id==MovieId); if(movie==null) throw new InvalidOperationException("Kayıt bulunamadı."); movie.GenreId=Model.GenreId!=default ? Model.GenreId:movie.GenreId; movie.DirectorId=Model.DirectorId!=default ? Model.DirectorId:movie.DirectorId; movie.Name=Model.Name!=default ? Model.Name:movie.Name; movie.Price=Model.Price!=default ? Model.Price:movie.Price; _context.SaveChanges(); } } public class UpdateMovieModel{ public string Name{get;set;} public int GenreId{get;set;} public int DirectorId{get;set;} public decimal Price{get;set;} } }
d4a37b333751ddfde86940a3b61fa4eb0ff7fdb5
C#
garnhold/CrunchyBox
/CrunchyDough/VectorI2/Extensions/VectorI2Extensions_With.cs
2.78125
3
using System; using System.Collections; using System.Collections.Generic; namespace Crunchy.Dough { static public class VectorI2Extensions_With { static public VectorI2 GetWithX(this VectorI2 item, int x) { return new VectorI2(x, item.y); } static public VectorI2 GetWithFlippedX(this VectorI2 item) { return item.GetWithX(-item.x); } static public VectorI2 GetWithAdjustedX(this VectorI2 item, int amount) { return item.GetWithX(item.x + amount); } static public VectorI2 GetWithY(this VectorI2 item, int y) { return new VectorI2(item.x, y); } static public VectorI2 GetWithFlippedY(this VectorI2 item) { return item.GetWithY(-item.y); } static public VectorI2 GetWithAdjustedY(this VectorI2 item, int amount) { return item.GetWithY(item.y + amount); } } }
2be6b51fc3d5deb707c06fb64a8c40ee6aea9b57
C#
vv-b-s/SoftUni
/C# OOP Advanced/Reflection and Attributes/Exercise/P02_BlackBoxInteger/BlackBoxIntegerTests.cs
3.28125
3
namespace P02_BlackBoxInteger { using System; public class BlackBoxIntegerTests { public static void Main() { var bbInstance = typeof(BlackBoxInteger).GetConstructor(System.Reflection.BindingFlags.NonPublic|System.Reflection.BindingFlags.Instance, null, new Type[0], null).Invoke(new object[0]); var input = ""; while ((input = Console.ReadLine()) != "END") { var data = input.Split('_'); var method = bbInstance.GetType().GetMethod(data[0],System.Reflection.BindingFlags.Instance|System.Reflection.BindingFlags.NonPublic); var argument = int.Parse(data[1]); method.Invoke(bbInstance, new object[] { argument }); var lastestResult = bbInstance.GetType() .GetField("innerValue", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic) .GetValue(bbInstance); Console.WriteLine(lastestResult); } } } }
251703aad5a78d4ea33ff62617e1304ccc65c781
C#
u3d-zhzw/GDX
/Runtime/CapsuleColliderExtensions.cs
2.6875
3
// Copyright (c) 2020-2021 dotBunny Inc. // dotBunny licenses this file to you under the BSL-1.0 license. // See the LICENSE file in the project root for more information. using System.Runtime.CompilerServices; using UnityEngine; namespace GDX { /// <summary> /// <see cref="UnityEngine.CapsuleCollider" /> Based Extension Methods /// </summary> [VisualScriptingCompatible(2)] public static class CapsuleColliderExtensions { /// <summary> /// Get a <see cref="Vector3" /> based orientation of the <paramref name="targetCapsuleCollider"/>. /// </summary> /// <param name="targetCapsuleCollider">The capsule collider</param> /// <returns>The direction of a <see cref="CapsuleCollider"/> in its local space.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Direction(this CapsuleCollider targetCapsuleCollider) { int direction = targetCapsuleCollider.direction; if(direction == 0) return Vector3.right; return direction == 1 ? Vector3.up : Vector3.forward; } /// <summary> /// Return into <paramref name="topPosition"/> and <paramref name="bottomPosition"/>, the respective world-space position of a <see cref="CapsuleCollider"/>'s spheres centers. /// </summary> /// <param name="targetCapsuleCollider">The <see cref="CapsuleCollider"/> having its spheres evaluated.</param> /// <param name="topPosition">The determined top spheres center position in world-space.</param> /// <param name="bottomPosition">The determined bottom spheres center position in world-space.</param> public static void OutSphereCenters(CapsuleCollider targetCapsuleCollider, out Vector3 topPosition, out Vector3 bottomPosition) { // Bring it local Vector3 cachedCenter = targetCapsuleCollider.center; topPosition = cachedCenter; // Calculate offset based on height/radius to center switch (targetCapsuleCollider.direction) { case 0: topPosition.x = targetCapsuleCollider.height * 0.5f - targetCapsuleCollider.radius; break; case 1: topPosition.y = targetCapsuleCollider.height * 0.5f - targetCapsuleCollider.radius; break; case 2: topPosition.z = targetCapsuleCollider.height * 0.5f - targetCapsuleCollider.radius; break; } // Invert bottom because the top was positive, now we need negative bottomPosition = -topPosition; // Convert positions to world-space topPosition = targetCapsuleCollider.transform.TransformPoint(topPosition); bottomPosition = targetCapsuleCollider.transform.TransformPoint(bottomPosition); } } }
44770207e35eed8632cf58bca4ad91f031f58e8f
C#
ebenzo/InmobiliariaNet
/ProgPuntoNet_bkp3/Inmobiliaria/Models/RepositorioContrato.cs
2.640625
3
using Microsoft.Extensions.Configuration; using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Threading.Tasks; namespace Inmobiliaria.Models { public class RepositorioContrato : RepositorioBase, IRepositorio<Contrato> { public RepositorioContrato(IConfiguration configuration) : base(configuration) { } public int Alta(Contrato c) { int res = -1; using (SqlConnection connection = new SqlConnection(connectionString)) { string sql = $"INSERT INTO Contrato ([IdInmueble], [IdInquilino], [FechaInicio], [FechaFin], [Monto], [IdContratoRenovado], [FechaContrato], [Descripcion]) " + $"VALUES ({c.IdInmueble}, {c.IdInquilino}, '{c.FechaInicio.ToString(System.Globalization.CultureInfo.InvariantCulture)}', '{c.FechaFin.ToString(System.Globalization.CultureInfo.InvariantCulture)}', {c.Monto.ToString(System.Globalization.CultureInfo.InvariantCulture)}, null, null, '{c.Descripcion}')"; using (SqlCommand command = new SqlCommand(sql, connection)) { command.CommandType = CommandType.Text; connection.Open(); res = command.ExecuteNonQuery(); command.CommandText = "SELECT SCOPE_IDENTITY()"; var id = command.ExecuteScalar(); c.IdContrato = Convert.ToInt32(id); connection.Close(); } } return res; } public int Baja(int id) { int res = -1; using (SqlConnection connection = new SqlConnection(connectionString)) { string sql = $"DELETE FROM Contrato WHERE IdContrato = {id}"; using (SqlCommand command = new SqlCommand(sql, connection)) { command.CommandType = CommandType.Text; connection.Open(); res = command.ExecuteNonQuery(); connection.Close(); } } return res; } public IList<Contrato> GetAll() { IList<Contrato> res = new List<Contrato>(); using (SqlConnection connection = new SqlConnection(connectionString)) { string sql = $"SELECT c.[IdContrato], c.[IdInmueble], c.[IdInquilino], c.[FechaInicio], c.[FechaFin], c.[Monto], c.[IdContratoRenovado], c.[FechaContrato], c.[Descripcion], i.Apellido, i.Nombre, p.Tipo, p.Direccion" + $" FROM Contrato c LEFT JOIN Inmueble p on (c.IdInmueble = p.IdInmueble) LEFT JOIN Inquilino i on (c.IdInquilino = i.IdInquilino)"; using (SqlCommand command = new SqlCommand(sql, connection)) { command.CommandType = CommandType.Text; connection.Open(); var reader = command.ExecuteReader(); while (reader.Read()) { Contrato c = new Contrato { IdContrato = (int)reader[nameof(c.IdContrato)], Descripcion = reader[nameof(c.Descripcion)].ToString(), IdInmueble = (int)reader[nameof(c.IdInmueble)], IdInquilino = (int)reader[nameof(c.IdInquilino)], FechaInicio = (DateTime)reader[nameof(c.FechaInicio)], FechaFin = (DateTime)reader[nameof(c.FechaFin)], Monto = (decimal)reader[nameof(c.Monto)], Inquilino = new Inquilino { IdInquilino = (int)reader[nameof(Inquilino.IdInquilino)], Nombre = reader[nameof(Inquilino.Nombre)].ToString(), Apellido = reader[nameof(Inquilino.Apellido)].ToString(), }, Inmueble = new Inmueble { //p.Tipo, p.Direccion IdInmueble = (int)reader[nameof(Inmueble.IdInmueble)], Tipo = reader[nameof(Inmueble.Tipo)].ToString(), Direccion = reader[nameof(Inmueble.Direccion)].ToString(), } }; res.Add(c); } connection.Close(); } } return res; } public Contrato GetById(int id) { Contrato c = null; using (SqlConnection connection = new SqlConnection(connectionString)) { string sql = $"SELECT c.[IdContrato], c.[IdInmueble], c.[IdInquilino], c.[FechaInicio], c.[FechaFin], c.[Monto], c.[IdContratoRenovado], c.[FechaContrato], c.[Descripcion], i.Apellido, i.Nombre, p.Tipo, p.Direccion" + $" FROM Contrato c LEFT JOIN Inmueble p on (c.IdInmueble = p.IdInmueble) LEFT JOIN Inquilino i on (c.IdInquilino = i.IdInquilino)" + $" WHERE IdContrato = @id"; using (SqlCommand command = new SqlCommand(sql, connection)) { command.Parameters.Add("@id", SqlDbType.Int).Value = id; command.CommandType = CommandType.Text; connection.Open(); var reader = command.ExecuteReader(); while (reader.Read()) { c = new Contrato { IdContrato = (int)reader[nameof(c.IdContrato)], IdInmueble = (int)reader[nameof(c.IdInmueble)], IdInquilino = (int)reader[nameof(c.IdInquilino)], Descripcion = reader[nameof(c.Descripcion)].ToString(), FechaInicio = (DateTime)reader[nameof(c.FechaInicio)], FechaFin = (DateTime)reader[nameof(c.FechaFin)], Monto = (decimal)reader[nameof(c.Monto)], Inquilino = new Inquilino { IdInquilino = (int)reader[nameof(Inquilino.IdInquilino)], Nombre = reader[nameof(Inquilino.Nombre)].ToString(), Apellido = reader[nameof(Inquilino.Apellido)].ToString(), }, Inmueble = new Inmueble { IdInmueble = (int)reader[nameof(Inmueble.IdInmueble)], Tipo = reader[nameof(Inmueble.Tipo)].ToString(), Direccion = reader[nameof(Inmueble.Direccion)].ToString(), } }; return c; } connection.Close(); } } return c; } public int Modificacion(Contrato c) { int res = -1; using (SqlConnection connection = new SqlConnection(connectionString)) { //[IdInmueble], [IdInquilino], [FechaInicio], [FechaFin], [Monto], [IdContratoRenovado], [FechaContrato] string sql = $"UPDATE Contrato" + $" SET IdInmueble={c.IdInmueble}, IdInquilino={c.IdInquilino}, Descripcion='{c.Descripcion}', FechaInicio='{c.FechaInicio.ToString(System.Globalization.CultureInfo.InvariantCulture)}', FechaFin='{c.FechaFin.ToString(System.Globalization.CultureInfo.InvariantCulture)}', Monto={c.Monto.ToString(System.Globalization.CultureInfo.InvariantCulture)} " + $" WHERE IdContrato = {c.IdContrato}"; using (SqlCommand command = new SqlCommand(sql, connection)) { command.CommandType = CommandType.Text; connection.Open(); res = command.ExecuteNonQuery(); connection.Close(); } } return res; } } }
e6487a7ac4ad16021fa62afeed5bbe3433b9dddc
C#
Pepsi4/Chat
/Server/IChat.cs
2.796875
3
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; using System.ServiceModel.Description; using System.ServiceModel; namespace Server { [ServiceContract(CallbackContract = typeof(IChatCallBack), SessionMode = SessionMode.Required)] interface IChat { /// <summary> /// If the user joined. Adds to the dictionary username and callback. Server side. /// </summary> [OperationContract(IsOneWay = true)] void LogginUser(string name); /// <summary> /// Tries to call on all callbacks that was registred: method GetMessage(msg) on user`s side. /// </summary> /// <param name="msg"></param> [OperationContract(IsOneWay = true)] void SendMessageToAll(string message); /// <summary> /// Checks if the element with the key is already exists. Or any others problems with the name. /// </summary> /// <param name="userName"></param> /// <returns>true if we added callback and userName to the our dictionary</returns> [OperationContract(IsOneWay = false)] bool CheckUser(string userName); /// <summary> /// Gets count of current connetions. /// </summary> /// <returns></returns> [OperationContract(IsOneWay = false)] int GetConnectionsCount(); /// <summary> /// Retruns the value of max connections to the server what is possible. /// </summary> /// <returns></returns> [OperationContract(IsOneWay = false)] int GetMaxConnetionsNumber(); /// <summary> /// Use this method if you can't send IChatCallBack /// </summary> [OperationContract(IsOneWay = true)] void UnLogginUser(); [OperationContract(IsOneWay = false)] List<string> GetOnlineUsers(); /// <summary> /// Const which is showing how much connections could be. /// </summary> [DataMember] int MaxConnections { get; set; } [DataMember] int CurrentConnections { get; set; } [OperationContract(IsOneWay = true)] void SendMessageDirectly(string name, string msg); } }
175b6aebdd82afa58e5d23e9b90729688c32f23e
C#
gastonm05/Cohesion
/CohesionTest/CohesionTest/Pages/AmazonHome.cs
2.515625
3
using OpenQA.Selenium; using OpenQA.Selenium.Support.UI; using System; using System.Collections.Generic; using System.Text; using SeleniumExtras.WaitHelpers; namespace CohesionTest.Pages { public class AmazonHome { private readonly IWebDriver _webDriver; public AmazonHome(IWebDriver driver) { _webDriver = driver; } private IWebElement SearchBar => _webDriver.FindElement(By.CssSelector("#twotabsearchtextbox")); internal void go(string url) { if (!url.StartsWith("http://")) url = "http://" + url; _webDriver.Navigate().GoToUrl(url); } public void doSearch(string wordToSearch) { SearchBar.SendKeys(wordToSearch); SearchBar.SendKeys(Keys.Enter); } public void openFirstResult() { WebDriverWait wait = new WebDriverWait(_webDriver, TimeSpan.FromSeconds(30)); string elementCss = "#search > div.s-desktop-width-max.s-desktop-content.s-opposite-dir.sg-row > div.s-matching-dir.sg-col-16-of-20.sg-col.sg-col-8-of-12.sg-col-12-of-16 > div > span:nth-child(4) > div.s-main-slot.s-result-list.s-search-results.sg-row > div:nth-child(8) > div"; wait.Until(ExpectedConditions.ElementToBeClickable(By.CssSelector(elementCss))); IWebElement firstResult = _webDriver.FindElement(By.CssSelector(elementCss)); firstResult.Click(); } } }
b22eeabfa1e5daefed3de330672534b08ddcbd1b
C#
foridulislam21/Datting-Application
/DatingApp/DatingApp.Repositories/PhotoRepository.cs
2.515625
3
using System.Linq; using System.Threading.Tasks; using DatingApp.Abstractions.Repository; using DatingApp.DbServer; using DatingApp.Models; using DatingApp.Repositories.Base; using Microsoft.EntityFrameworkCore; namespace DatingApp.Repositories { public class PhotoRepository : EfRepository<Photo>, IPhotoRepository { private readonly DatingAppData _db; public PhotoRepository(DbContext db) : base(db) { _db = db as DatingAppData; } public async override Task<Photo> GetById(long id) { return await _db.Photos.FirstOrDefaultAsync(p => p.Id == id); } public async Task<Photo> GetMainPhotoForUser(long userId) { return await _db.Photos.Where(u => u.UserId == userId).FirstOrDefaultAsync(p => p.IsMain); } } }
c7ec162ccb629157114e0cbdce57af713a18ca4a
C#
Notahina/PortGestion
/Models/Dao/FinPropositionDao.cs
2.546875
3
using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Web; namespace PortGestion.Models.Dao { public class FinPropositionDao { public void UpdateProposition(SqlConnection c,FinProposition[] liste) { DbConnect db = new DbConnect(); SqlCommand command = c.CreateCommand(); SqlTransaction transaction; // transaction = c.BeginTransaction("SampleTransaction"); command.Connection = c; try { for (int i = 0; i < liste.Length; i++) { string dateE = db.formatDate(liste[i].Dateentre); string dateS = db.formatDate(liste[i].Datesortie); string update = "Update Proposition set Dateentre='" +dateE + "',Datesortie='" +dateS+ "' where idpred='" + liste[i].Idpred + "'"; command.CommandText =update; command.ExecuteNonQuery(); } } catch(Exception e) { throw e; } } public FinProposition[] getProposition(SqlConnection c) { Boolean b = false; if (c == null) { c = new DbConnect().getConex(); c.Open(); b = true; } try { Object[] select = new DbConnect().Select2(new FinProposition(), "Proposition", c); FinProposition[] f = new FinProposition[select.Length]; for (int i = 0; i < f.Length; i++) { f[i] = (FinProposition)select[i]; } return f; } catch(Exception e) { throw e; } finally { if (b == true) c.Close(); } } public void MultiInsert(SqlConnection c,FinProposition[] liste) { Boolean b=false; if (c == null) { c = new DbConnect().getConex(); c.Open(); b = true; } SqlCommand command = c.CreateCommand(); SqlTransaction transaction; // transaction = c.BeginTransaction("SampleTransaction"); command.Connection = c; //command.Transaction = transaction; try { for(int i = 0; i < liste.Length; i++) { FinProposition f = new FinProposition(); string sql = f.insert(liste[i]); FinProposition res = f.VerifyDoublant(c,liste[i].Idpred); if (res != null) { throw new Exception("La prevision " + liste[i].Idpred + "existe deja"); } command.CommandText = sql; command.ExecuteNonQuery(); } // transaction.Commit(); } catch(Exception e) { //transaction.Rollback(); throw e; } finally { if (b == true) c.Close(); } } } }
844b566129b4ba7b4ce181c7208afb4e5422a3f4
C#
eugene-tt/hChallenges
/Challenge2/Data/Controllers/TransportController.cs
2.859375
3
using Challenge2.Data.Entities; using Challenge2.Data.Exceptions; using System; using System.Collections.Generic; namespace Challenge2.Data.Controllers { public class TransportController : BaseController { public int GetCount() { lock (context.SyncRoot) { return db.Table<Transport>().Count(); } } public List<Transport> List(TransportType? type) { try { lock (context.SyncRoot) { if (type.HasValue) { return db .Table<Transport>() .Where(t => t.Type == type.Value) .ToList(); } else { return db .Table<Transport>() .ToList(); } } } catch (Exception ex) { throw new HprException($"Failed to list transports. Error: {ex.Message}", ex); } } public void AddTransport(TransportType type, int capacity, string title) { if (capacity <= 0) { throw new ArgumentException(nameof(capacity)); } if (string.IsNullOrEmpty(title)) { throw new ArgumentException(nameof(title)); } try { lock (context.SyncRoot) { var transport = new Transport(); transport.DateCreated = DateTime.UtcNow; transport.DateUpdated = transport.DateCreated; transport.Type = type; transport.Capacity = capacity; transport.TransportName = title; db.Insert(transport); } } catch (Exception ex) { throw new HprException($"Failed to add a transport. Error: {ex.Message}", ex); } } public void AddShip(int capacity, string title) { AddTransport(TransportType.Ship, capacity, title); } public void AddTruck(int capacity, string title) { AddTransport(TransportType.Truck, capacity, title); } public Transport GetById(int id) { try { lock (context.SyncRoot) { var res = db .Table<Transport>() .Where(t => t.Id == id) .FirstOrDefault(); if(res == null) { throw new Exception("Not found"); } return res; } } catch (Exception ex) { throw new HprException($"Transport not found. Error: {ex.Message}", ex); } } public void Rename(int id, string title) { if (id <= 0) { throw new ArgumentException(nameof(id)); } if (string.IsNullOrEmpty(title)) { throw new ArgumentException(nameof(title)); } try { lock (context.SyncRoot) { var transport = GetById(id); transport.TransportName = title; db.Update(transport); } } catch (Exception ex) { throw new HprException($"Failed to rename the transport. Error: {ex.Message}", ex); } } public void Delete(int id) { if (id <= 0) { throw new ArgumentException(nameof(id)); } try { lock (context.SyncRoot) { var transport = GetById(id); if(transport.Load > 0) { throw new HprException("The transport is not empty. Unload its cargo first."); } db.Delete(transport); } } catch (Exception ex) { throw new HprException($"Failed to delete the transport. Error: {ex.Message}", ex); } } } }
04a4dd7ba1199d0eb41425bfb008f0ba5f8adf2b
C#
aramgyulbekyan/Zil_homeworks
/9/Program.cs
3.09375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _9 { class Program { static void Main(string[] args) { double N = 0; string input1 = Console.ReadLine(); if (string.IsNullOrEmpty(input1)) { Console.WriteLine("error"); } else { N = double.Parse(input1); } double result = 1; for (double i = 1; i < N; i++) { result += 1 / i; } Console.WriteLine(result); } } }
a0cab071428a939965c08172b6d7cebdfc4ed343
C#
lawrence-laz/Decor.NET
/Decor.UnitTests/DependencyLifeTimeTests.cs
2.703125
3
using Microsoft.Extensions.DependencyInjection; using System.Threading.Tasks; using Xunit; namespace Decor.UnitTests { public class DependencyLifeTimeTests { [Fact] public void I_can_decorate_with_decorator_that_has_scoped_dependency() { // Arrange var serviceProvider = new ServiceCollection() .AddScoped<Dependency>() .AddTransient<TestDecoratorWithDependency>() .AddScoped<ISomeInterface, SomeClass>() .Decorate<ISomeInterface>() .BuildServiceProvider(); // Act & Assert serviceProvider.GetRequiredService<ISomeInterface>(); } #region Setup public class Dependency { } public class TestDecoratorWithDependency : IDecorator { public TestDecoratorWithDependency(Dependency dependency) { Dependency = dependency; } public Dependency Dependency { get; } public Task OnInvoke(Call call) => Task.CompletedTask; } public interface ISomeInterface { void SomeMethod(); } public class SomeClass : ISomeInterface { [Decorate(typeof(TestDecoratorWithDependency))] public void SomeMethod() { } } #endregion } }
f58871b22e2dd3b7be1b16352ba8d55b5bb13d8f
C#
ImCarrot/Template10
/Services/Template10.Services.Container/Service/ContainerService.cs
2.765625
3
namespace Template10.Services.Container { public abstract class ContainerService : IContainerService { static IContainerService _Default; public static IContainerService Default { get => _Default; set => _Default = value; } public ContainerService(IContainerAdapter adapter, bool setAsDefault = true) { if (setAsDefault && _Default != null) { throw new System.Exception("Default ContainerService has already been set."); } _adapter = adapter; if (setAsDefault) { _Default = this; } } public IContainerAdapter _adapter { get; set; } public T Resolve<T>() where T : class => _adapter.Resolve<T>(); public void Register<F, T>() where F : class where T : class, F => _adapter.Register<F, T>(); public void Register<F>(F instance) where F : class => _adapter.Register<F>(instance); } }
aa61f3033601c5419bccaf5c1bb5f217e55b733b
C#
fafase/PopBlast
/Assets/Scripts/AppControl/ItemGenerator.cs
2.671875
3
using System.Collections; using System.Collections.Generic; using UnityEngine; using System; using PopBlast.Items; namespace PopBlast.AppControl { /// <summary> /// Component controlling the grid of items /// Main business logic of the system /// </summary> public class ItemGenerator : MonoBehaviour { #region MEMBERS [Tooltip("Waiting time for row creation of item")] [SerializeField] private float waitTimeForCreation = 0.5f; [Tooltip("Items prefabs")] [SerializeField] private GameObject[] items = null; private Transform[] spawns = null; private IItem[,] grid; private int width, height; /// <summary> /// Event triggered when no more moves are possible /// </summary> public event Action RaiseEndOfGame; /// <summary> /// Event raised when pop happens, parameter indicates how many items at once /// </summary> public event Action<int> RaiseItemPop; #endregion #region PUBLIC_METHODS /// <summary> /// Initializes the ItemGenerator with column (width) and row (height) /// </summary> /// <param name="col"></param> /// <param name="row"></param> /// <param name="onCompletion"></param> public void Init(int col, int row, Action onCompletion) { spawns = new Transform[col]; width = col; height = row; // Generate the spawn points for (int i = 0; i < col; i++) { GameObject obj = new GameObject($"Spawn_{i}"); spawns[i] = obj.transform; float posY = (float)row + 1f; obj.transform.position = new Vector3(i + 0.5f, posY, 0f); obj.transform.parent = transform; } // Generate all items grid = new Item[col, row]; for (int i = 0; i < col; i++) { Transform spawnTr = spawns[i]; for (int j = 0; j < row; j++) { int rand = UnityEngine.Random.Range(0, items.Length); GameObject obj = Instantiate<GameObject>(items[rand], spawnTr); obj.transform.position = spawnTr.position; IItem item = obj.GetComponent<IItem>(); item.SetGrid(i, j); item.GameObject.SetActive(false); grid[i, j] = item; } } SetNeighboursGrid(); StartCoroutine(EnableItemCoroutine(onCompletion)); } /// <summary> /// Checks the neighbours of the given game object /// Process a tree search to find all consecutive similar neighbours /// Clears them all from screen and loads new ones /// </summary> /// <param name="go"></param> /// <param name="onCompletion"></param> public void CheckItemNeighbours(GameObject go, Action onCompletion) { Item item = go.GetComponent<Item>(); if(item == null) { onCompletion?.Invoke(); return; } IItem[] results = item.GetSameTypeNeighbours(); if(results.Length == 0) { onCompletion?.Invoke(); return; } int amount = ProcessItemToRemove(item); CheckForEmptySpaces(); StartCoroutine(CreateNewItemsCoroutine(amount, ()=> { SetNeighboursGrid(); if (CheckForRemainingMovement() == false) { RaiseEndOfGame?.Invoke(); } onCompletion?.Invoke(); })); } #endregion private int ProcessItemToRemove(Item item) { // Using hashset to avoid duplicate HashSet<IItem> toRemove = new HashSet<IItem>(); // Add first item, the one that got tapped on toRemove.Add(item); Queue<IItem> queue = new Queue<IItem>(); // Enqueue item for tree search queue.Enqueue(item); while (queue.Count > 0) { // Get oldest item IItem current = queue.Dequeue(); // Get all neighbours with same type // Continue if none IItem[] items = current.GetSameTypeNeighbours(); if (items.Length == 0) { continue; } // For each of the neighbours, add to the queue // Using hashset, if a neighbour is already in the list, it is not added to the queue // It was either already processed or already added to the list foreach (IItem it in items) { if (toRemove.Add(it)) { queue.Enqueue(it); } } } // Forward how many items were found // Used for score and feedback RaiseItemPop?.Invoke(toRemove.Count); int amount = toRemove.Count; // Destroy item and set grid position to null foreach (IItem i in toRemove) { grid[i.Column, i.Row] = null; i.DestroyItem(); } return amount; } // Check for empty space in a column //Iterate from bottom to top // When a free space is found, it searches for next item in the column and assign its new grid position private void CheckForEmptySpaces() { for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { IItem temp = grid[i, j]; // if empty spot if (temp == null) { // iterate above for item for (int w = j; w < height; w++) { IItem t = grid[i, w]; // if item is found if (t != null) { // Assign item with empty spot location t.SetGrid(i, j); // Update grid grid[i, j] = t; // Set old item grid spot to null grid[i, w] = null; break; } } } } } } //Iterate the whole grid and search for an item with same neighbours indicating a possible move private bool CheckForRemainingMovement() { for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { IItem item = grid[i, j]; // If the item has a neighbour with same type, there is a possible move if (item.GetSameTypeNeighbours().Length > 0) { return true; } } } // No possible move left return false; } // Create new item and assign their grid position // Coroutine to allow items not to stack on top of each other private IEnumerator CreateNewItemsCoroutine(int amount, Action onCompletion) { for (int i = 0; i < height; i++) { for(int j = 0; j < width; j++) { if (grid[j, i] == null) { // Get the spawn point Transform spawnTr = spawns[j]; // Create new item with random value int rand = UnityEngine.Random.Range(0, items.Length); GameObject obj = Instantiate<GameObject>(items[rand], spawnTr); // Set position at spawn obj.transform.position = spawnTr.position; // Populate the IItem values IItem item = obj.GetComponent<IItem>(); item.SetGrid(j, i); // Sart the movement with callback item.StartMovement(()=> { // Decrease amount and check if all are done if (--amount == 0) { onCompletion?.Invoke(); } }); // Set the grid with new IItem grid[j, i] = item; } } yield return new WaitForSeconds(waitTimeForCreation); } // onCompletion?.Invoke(); } private IEnumerator EnableItemCoroutine(Action onCompletion) { for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { IItem item = grid[j, i]; item.GameObject.SetActive(true); item.StartMovement(null); yield return new WaitForSeconds(waitTimeForCreation); } } onCompletion?.Invoke(); } // Set all four neighbours for the items of the grid private void SetNeighboursGrid() { for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { IItem left = null, right = null, top = null, bottom = null; // for each item, checking if it is not on the edge to avoid out of bounds exception if (i > 0) { left = grid[i - 1, j]; } if (i < width - 1) { right = grid[i + 1, j]; } if (j > 0) { bottom = grid[i, j - 1]; } if (j < height - 1) { top = grid[i, j + 1]; } grid[i, j].SetNeighbors(left, right, top, bottom); } } } } }
75a9b930346a51e531d577ee28cb7494abf80e68
C#
toshko93/0.0.CSharp-Basics
/05.Conditional-Statements/05.Conditional-Statements/01.SwapIfGreater/SwapIfGreater.cs
4.28125
4
// Write an if-statement that takes two integer variables a and b and exchanges their values if the first one is greater than the second one. // As a result print the values a and b, separated by a space. using System; class SwapIfGreater { static void Main() { Console.WriteLine("Enter the first variable: "); double numA = double.Parse(Console.ReadLine()); Console.WriteLine("Enter the second variable: "); double numB = double.Parse(Console.ReadLine()); if (numA < numB) { Console.WriteLine(numA + " " + numB); } else { Console.WriteLine(numB + " " + numA); } } }
1d07c7a652209c3225bf8a01a27fafc148c437f8
C#
dazinator/FluentGit
/src/FluentGit/Builder/NewRemoteBuilder.cs
2.5625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace FluentGit { public class NewRemoteBuilder : INewRemoteBuilder { internal NewRemoteBuilder() { // _repo = repo; } INewRemoteBuilder INewRemoteBuilder.WithName(string name) { Name = name; return this; } INewRemoteBuilder INewRemoteBuilder.WithUrl(string url) { Url = url; return this; } INewRemoteBuilder INewRemoteBuilder.WithFetchRefSpec(Action<IRefSpecBuilder> refSpecBuilder) { var builder = (IRefSpecBuilder)new RefSpecBuilder("", "", false); refSpecBuilder(builder); this.FetchRefSpec = builder.ToRefSpec(); return this; } INewRemoteBuilder INewRemoteBuilder.WithFetchRefSpec(string fetchRefSpec) { this.FetchRefSpec = RefSpecInfo.Parse(fetchRefSpec); return this; } public string Name { get; set; } public string Url { get; set; } public RefSpecInfo FetchRefSpec { get; set; } } }
689b79f51d5576f3b87900044d8ce8a41d241bea
C#
vu111293/pat-design
/PAT-KWSN_20150204/PAT.Common/GUI/TAModule/TAModel.cs
2.5625
3
using System; using System.Collections.Generic; using System.Text; using System.Xml; using PAT.Common.GUI.Drawing; using Tools.Diagrams; namespace PAT.Common.GUI.TAModule { public class TAModel { public string Declaration; public List<TACanvas> Processes; public List<TACanvas> Properties; public TAModel() { Declaration = ""; this.Processes = new List<TACanvas>(); this.Properties = new List<TACanvas>(); } public TAModel(string declare, List<TACanvas> processes, List<TACanvas> properties) { this.Declaration = declare; this.Processes = processes; this.Properties = properties; } public static TAModel LoadLTSFromXML(string text) { TAModel lts = new TAModel(); XmlDataDocument doc = new XmlDataDocument(); doc.LoadXml(text); XmlNodeList sitesNodes = doc.GetElementsByTagName(Parsing.DECLARATION_NODE_NAME); foreach (XmlElement component in sitesNodes) { lts.Declaration = component.InnerText; } sitesNodes = doc.GetElementsByTagName(Parsing.PROCESSES_NODE_NAME); if (sitesNodes.Count > 0) { foreach (XmlElement component in sitesNodes[0].ChildNodes) { TACanvas canvas = new TACanvas(); canvas.LoadFromXml(component); lts.Processes.Add(canvas); } } sitesNodes = doc.GetElementsByTagName(Parsing.PROPERTIES_NODE_NAME.Replace(" ", "_")); if (sitesNodes.Count > 0) { foreach (XmlElement component in sitesNodes[0].ChildNodes) { TACanvas canvas = new TACanvas(); canvas.LoadFromXml(component); lts.Properties.Add(canvas); } } return lts; } public XmlDocument GenerateXML() { XmlDataDocument doc = new XmlDataDocument(); XmlElement LTS = doc.CreateElement(Parsing.LTS_NODE_NAME); doc.AppendChild(LTS); XmlElement declar = doc.CreateElement(Parsing.DECLARATION_NODE_NAME); declar.InnerText = Declaration; LTS.AppendChild(declar); XmlElement process = doc.CreateElement(Parsing.PROCESSES_NODE_NAME); foreach (TACanvas canvas in Processes) { process.AppendChild(canvas.WriteToXml(doc)); } LTS.AppendChild(process); XmlElement properties = doc.CreateElement(Parsing.PROPERTIES_NODE_NAME.Replace(" ", "_")); foreach (TACanvas canvas in Properties) { properties.AppendChild(canvas.WriteToXml(doc)); } LTS.AppendChild(properties); return doc; } public string ToSpecificationString() { StringBuilder sb = new StringBuilder(); sb.AppendLine(Declaration); string file = ""; foreach (string[] eraCanvase in ParsingException.FileOffset.Values) { file = eraCanvase[0]; } ParsingException.FileOffset.Clear(); ParsingException.FileOffset.Add(ParsingException.CountLinesInFile(sb.ToString()), new string[] { file, "Declaration" }); foreach (TACanvas canvas in Processes) { sb.AppendLine(canvas.ToSpecificationString()); ParsingException.FileOffset.Add(ParsingException.CountLinesInFile(sb.ToString()), new string[] { file,canvas.Node.Text}); } foreach (TACanvas canvas in Properties) { sb.AppendLine(canvas.ToSpecificationString().Replace("Process ", "Property ")); ParsingException.FileOffset.Add(ParsingException.CountLinesInFile(sb.ToString()), new string[] { file,canvas.Node.Text}); } return sb.ToString(); } public string ToSpectNewFormat() { StringBuilder sb = new StringBuilder(); sb.AppendLine(Declaration); foreach (TACanvas canvas in Processes) { string[] strings = canvas.Parameters.Trim().Split(new char[] { '$' }, StringSplitOptions.RemoveEmptyEntries); string clocks = string.Empty; string para = string.Empty; if (strings.Length == 1 && canvas.Parameters.Trim().StartsWith("$")) { clocks = strings[0]; } else if (strings.Length == 1 && !canvas.Parameters.Trim().StartsWith("$")) { para = strings[0]; } else if (strings.Length == 2) { para = strings[0]; clocks = strings[1]; } if(para != string.Empty) { para = "(" + para + ")"; } sb.AppendLine("TimedAutomaton " + canvas.Node.Text + para); sb.AppendLine("{"); if(clocks != string.Empty) { sb.AppendLine("\tclock: " + clocks + ";"); } sb.AppendLine(); StringBuilder otherStates = new StringBuilder(); foreach (var item in canvas.itemsList) { if (item.Item is TAState) { if ((item.Item as TAState).IsInitialState) { sb.AppendLine(StateToNewFormat(item.Item as TAState, canvas.diagramRouter.Routes)); } else { otherStates.AppendLine(StateToNewFormat(item.Item as TAState, canvas.diagramRouter.Routes)); } } } sb.Append(otherStates); sb.AppendLine("}"); sb.AppendLine(); } return sb.ToString(); } private string StateToNewFormat(TAState item, Route[] routes) { StringBuilder result = new StringBuilder(); result.AppendLine("\tstate " + item.GetName()); if (item.Invariant != string.Empty) { result.AppendLine("\tinv: " + item.Invariant + ";"); } string label = string.Empty; if(item.IsUrgent) { label += "urgent "; } if(item.IsCommitted) { label += "committed"; } if (item.IsError) { label += "error"; } if(label != string.Empty) { result.AppendLine("\t" + label + ";"); } foreach (var route in routes) { if ((route.From as TAState).GetName() == item.GetName()) { string clockGuard = (route.Transition.ClockGuard == string.Empty) ? string.Empty : "[[" + route.Transition.ClockGuard + "]]"; string guard = (route.Transition.Guard == string.Empty) ? string.Empty : "[" + route.Transition.Guard + "]"; string program = (route.Transition.Program == string.Empty) ? string.Empty : "{" + route.Transition.Program.Replace("\r\n", "") + "}"; string clockReset = (route.Transition.ClockReset == string.Empty) ? string.Empty : "<" + route.Transition.ClockReset + ">"; result.AppendLine("\ttrans:" + clockGuard + guard + route.Transition.GetEventPart() + program + clockReset + "->" + (route.To as TAState).GetName() + ";"); } } result.AppendLine("\tendstate"); return result.ToString(); } } }
1179ea430e97a012df3a45fccd43f6b9ac5036cf
C#
Suremaker/mapGenerator-proto
/LandTileGenerator/Generators/Heights/BorderHeightGenerator.cs
3.015625
3
namespace LandTileGenerator.Generators.Heights { public abstract class BorderHeightGenerator : HeightGenerator { private readonly float _ymargin; private readonly float _xmargin; protected BorderHeightGenerator(float xmargin, float ymargin) { _xmargin = xmargin; _ymargin = ymargin; } public sealed override float Generate(float x, float y, float precomputedHeight) { if (x > _xmargin && x + _xmargin < 1 && y > _ymargin && y + _ymargin < 1) return OnGenerate(x, y, precomputedHeight); return precomputedHeight; } protected abstract float OnGenerate(float x, float y, float precomputedHeight); } }
b1b84ff8bc6db1f6f0092a9095cd89ffc52011e7
C#
stryt2/syntec-unit-test-101
/money/1_BankAccount/BankAccountDebitTests.cs
2.921875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NUnit.Framework; namespace Demo._1_BankAccount { /// <summary> /// verify the behavior of the 'Debit' method of the BankAccount class. /// </summary> class BankAccountDebitTests { [Test] public void Debit_WithValidAmount_UpdatesBalance() { // TODO: Verify that a valid amount (that is, one that is less than the account // balance and greater than zero) withdraws the correct amount from the account. // Given beginning balance 11.99 // When debit with amount 4.55 // Then balance should be 7.44 with tolerance 0.001 // And should give reasonable error message like "Account not debited correctly" if failed. } // TODO: Add more tests to cover other behaviors: // 1. less than zero // 2. more than balance } }
779d279286c8006fad83c8c023b604d56a6f8b27
C#
stajs/Stajs.Rcon
/Stajs.Rcon.Core/Extensions/IntExtensions.cs
2.609375
3
using System; using Stajs.Rcon.Core.Responses; namespace Stajs.Rcon.Core.Extensions { internal static class IntExtensions { internal static ServerResponseType ToResponseType(this int i) { if (!Enum.IsDefined(typeof(ServerResponseType), i)) throw new InvalidCastException("Value is not defined in enum"); return (ServerResponseType) i; } } }
a7c6cce2d41e1e763cf2c776c875544c5302cc43
C#
mobydi/wikiapp
/WikiAppTest/MetricCalculation.cs
2.625
3
using System.Linq; using SimMetrics.Net.API; using SimMetrics.Net.Metric; using WikiApp.Models; using Xunit; using WikiApp.WikiApi; using Xunit.Abstractions; namespace WikiAppTest { public class MetricCalculation { private readonly ITestOutputHelper output; public MetricCalculation(ITestOutputHelper output) { this.output = output; } [Fact] public void Verbose_With_Levenstein() { const double latitude = 37.786971; const double longitude = -122.399677; IStringMetric metric = new Levenstein(); ITokenizer tokenizer = new Tokenizer(); var geopages = WikiApi.Geosearch(latitude, longitude); foreach (var geopage in geopages) { output.WriteLine($"[{geopage.Pageid}] {geopage.Title}"); var images = WikiApi.Images(geopage.Pageid); var imagesWithMetrics = images .Select(image => new {Image = image, Similarity = image.CalcMetric(geopage.Title, tokenizer, metric)}) .ToList(); var title = imagesWithMetrics.Aggregate((image, next) => next.Similarity > image.Similarity ? next : image); output.WriteLine($"\t*[{title.Image.Ns}] {title.Image.Title} {title.Similarity}"); foreach (var image in imagesWithMetrics) { output.WriteLine($"\t[{image.Image.Ns}] {image.Image.Title} {image.Similarity}"); } } } } }
08a45a4926d054621521000386bc2e0d5b45bfc4
C#
MichaelDouglasAmarante/learning
/CursoCSharp-Cod3rCursos/CursoCSharp/Fundamentos/Conversoes.cs
3.734375
4
using System; using System.Collections.Generic; using System.Text; namespace CursoCSharp.Fundamentos { class Conversoes { public static void Executar() { int inteiro = 10; double quebrado = inteiro; Console.WriteLine(quebrado); // Conversões que podem gerar perda de informação tem que ser explicitas double nota = 9.7; int notaTruncada = (int) nota; // Conversão de tipos ( casting ) Console.WriteLine($"Nota truncada: {notaTruncada}"); Console.WriteLine("Digite sua idade: "); string idadeString = Console.ReadLine(); int idadeInteiro = int.Parse(idadeString); Console.WriteLine($"Idade inserida: {idadeInteiro}"); idadeInteiro = Convert.ToInt32(idadeString); // Convert => classe interna Console.WriteLine($"Resultado: {idadeInteiro}"); Console.Write("Digite o primeiro número: "); string palavra = Console.ReadLine(); int numero1; int.TryParse(palavra, out numero1); // TryParse => tentar fazer um Parse | Pega palavra convertido e coloca em numero Console.WriteLine($"Resultado {numero1}"); //Otimizando o bloco do primeiro número Console.Write("Digite o segundo número: "); int.TryParse(Console.ReadLine(), out int numero2); // TryParse => tentar fazer um Parse | Pega palavra convertido e coloca em numero Console.WriteLine($"Resultado {numero2}"); } } }