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
91ab3ca332268ea120419122bb0a025e9473f8a2
C#
melan335993/ConsoleTetris
/Tetris_NetFramework/Game.cs
2.703125
3
using System; using System.Threading; namespace Tetris_NetFramework { class Game { public int size_x; public int size_y; public const int gameSpeedConst = 500; public const int sizeGlobalMap_X = 29; public const int sizeGlobalMap_Y = 30; public const int sizeGameMap_X = 12; public const int sizeGameMap_Y = 22; public int gameSpeed = gameSpeedConst; public const int gameSpeedBoost = 70; public Map map; public GameMap gameMap = new GameMap(sizeGameMap_X, sizeGameMap_Y); Coord figCoord { get; set; } Coord figStartCoord { get; } public int figMax_X { get; set; } public int figMin_X { get; set; } public int score { get; set; } public bool isLeftClear { get; set; } public bool isRightClear { get; set; } public bool isRotatable { get; set; } public bool isDownClear { get; set; } public int figVer { get; set; } // 1 - J, 2 - O, 3 - L, 4 - I, 5 - S, 6 - Z, 7 - T public bool isSkipped = false; public bool isSettings = false; public bool isRestart = false; public bool pressLeft = false; public bool pressRight = false; public bool pressUp = false; public bool pressDown = false; public string space = " "; public string mainBackgroundSym = "."; public string gameBackgroundSym = " "; public string mainCounturSym = "#"; public string gameCounturSym = "#"; public string figSym = "O"; ConsoleKeyInfo ConsKeyInfo { get; set; } public Game(int size_x, int size_y) { this.size_x = size_x; this.size_y = size_y; isRotatable = true; score = 0; figStartCoord = new Coord(6, 1); map = new Map(size_x, size_y); Console.SetWindowSize(65, 32); Console.CursorVisible = false; Console.Title = "Console Tetris by Melnikov A.V."; figCoord = figStartCoord; } public void Settings() { Console.Clear(); Console.WriteLine("Введите символ пробела между символами:"); string input = Console.ReadLine(); space = input; Console.WriteLine("\nВведите символ для основного бэкграунда:"); input = Console.ReadLine(); mainBackgroundSym = input; Console.WriteLine("\nВведите символ для игрового бэкграунда:"); input = Console.ReadLine(); gameBackgroundSym = input; Console.WriteLine("\nВведите символ для основного контура:"); input = Console.ReadLine(); mainCounturSym = input; Console.WriteLine("\nВведите символ для игрового контура:"); input = Console.ReadLine(); gameCounturSym = input; Console.WriteLine("\nВведите символ для фигур:"); input = Console.ReadLine(); figSym = input; isSettings = false; } public void ReBuild() { Console.CursorVisible = false; Console.SetCursorPosition(0, 0); Coord xy; for (int y = 0; y < size_y; y++) { for (int x = 0; x < size_x; x++) { Console.CursorVisible = false; xy = new Coord(x, y); Console.Write(map.Get(xy) + space.ToString()); Console.CursorVisible = false; if (x == size_x - 1) { Console.CursorVisible = false; Console.WriteLine(); Console.CursorVisible = false; } Console.CursorVisible = false; } } } public void Fall() { while (!isRestart) { if (isDownClear) { figCoord = new Coord(figCoord.x, figCoord.y + 1); Thread.Sleep(gameSpeed); isDownClear = false; } } } public bool StartGame() { Console.Clear(); Coord xy; figCoord = figStartCoord; Console.SetCursorPosition(0, 0); Console.CursorVisible = false; gameMap.FillMap(gameBackgroundSym); gameMap.FillContour(gameCounturSym); map.FillMap(mainBackgroundSym); map.FillContour(mainCounturSym); Map.InsertMatrix(gameMap.map, map.map, 2, 3); for (int y = 0; y < size_y; y++) // анимация intro { for (int x = 0; x < size_x; x++) { xy = new Coord(x, y); Console.Write(map.Get(xy) + space); Console.CursorVisible = false; Thread.Sleep(5); /////////////////////////////////// if (x == size_x - 1) Console.WriteLine(); if (isSkipped) return true; } if (isSkipped) return true; } // INTRO Console.SetCursorPosition(7, 8); Console.Write("Welcome to Game"); Console.SetCursorPosition(10, 11); Console.Write("Use arrows"); Console.SetCursorPosition(9, 12); Console.Write("to control"); Console.SetCursorPosition(8, 14); Console.Write("\"Esc\" to START"); Console.SetCursorPosition(9, 21); Console.Write("S - settings"); Console.SetCursorPosition(9, 22); Console.Write("R - restart"); figCoord = figStartCoord; while (!isSkipped) { for (int y = 0; y < 1; y++) // анимация intro { Console.SetCursorPosition(0, 0); Console.CursorVisible = false; for (int x = 0; x < 1; x++) { Console.CursorVisible = false; xy = new Coord(x, y); Console.Write(map.Get(xy) + space); Thread.Sleep(5); /////////////////////////////////// if (x == size_x - 1) Console.WriteLine(); if (isSkipped) return true; } if (isSkipped) return true; } // INTRO } return false; } public void EndGame() { Console.Clear(); Console.SetCursorPosition(10, 9); Console.Write("The End"); Console.SetCursorPosition(7, 11); Console.Write($"Your Score is {score}"); Thread.Sleep(2000); Console.Clear(); Console.SetCursorPosition(0, 0); string[] str = { "\n"+ "\n ##############" + "\n #### #####" + "\n ##### #####"+ "\n #### ###"+ "\n ### #### #### ###"+ "\n ### ###### ###### ###"+ "\n ### ######## ######## ###"+ "\n ### ########## ########## ###"+ "\n ### ########## ########## ###"+ "\n ### ########## ########## ###"+ "\n ### ########## ########## ###"+ "\n### ########## ########## ###"+ "\n### ######## ######## ###"+ "\n### ###### ###### ###"+ "\n### ## ## ###"+ "\n ### #### #### ###"+ "\n ### ## ## ## ## ###"+ "\n ### ## ## ###"+ "\n ### ### ## ###"+ "\n ### ### ### ###"+ "\n ### ###### ####### ###"+ "\n #### ######### ########### ####"+ "\n #### ################# ####"+ "\n ##### #####"+ "\n #######################"+ ""}; foreach (string s in str) Console.Write(s); while (!isRestart) { Console.SetCursorPosition(23, 28); Console.Write("Press R to RESTART"); Thread.Sleep(500); Console.SetCursorPosition(23, 28); Console.Write(" R "); Thread.Sleep(500); } } public void MoveHero() { Console.CursorVisible = false; while (true) { ConsKeyInfo = Console.ReadKey(true); Thread.Sleep(10); if (ConsKeyInfo.Key == ConsoleKey.LeftArrow) { if (isLeftClear) { pressLeft = true; } } // LeftArrow else if (ConsKeyInfo.Key == ConsoleKey.RightArrow) { if (isRightClear) { pressRight = true; } } // RightArrow else if (ConsKeyInfo.Key == ConsoleKey.UpArrow) { pressUp = true; } // UpArrow else if (ConsKeyInfo.Key == ConsoleKey.DownArrow) { pressDown = true; } else if (ConsKeyInfo.Key == ConsoleKey.R) { score = 0; gameSpeed = gameSpeedConst; isRestart = true; }// R else if (ConsKeyInfo.Key == ConsoleKey.Escape) { isSkipped = true; } // Escape else if (ConsKeyInfo.Key == ConsoleKey.S) { isSkipped = true; isSettings = true; } } // end while } public void MainGame() { Thread thrSpeed = new Thread(Fall); // падение фигуры thrSpeed.Start(); thrSpeed.IsBackground = true; thrSpeed.Priority = ThreadPriority.Lowest; int size_x = this.size_x; int size_y = this.size_y; int line = 0; figVer = 1; int figVerNext = figVer; int figVerTemp = figVer; Map map = this.map; GameMap gameMap = this.gameMap; GameMap tempMap = new GameMap(sizeGameMap_X, sizeGameMap_Y); GameMap miniMap = new GameMap(6, 6); Coord xyMini = new Coord(18, 5); int sp = gameSpeed; Random rand = new Random(); int tempRnd = rand.Next(1, 8); int nextRnd = rand.Next(1, 8); map.FillMap(mainBackgroundSym); map.FillContour(mainCounturSym); gameMap.FillMap(gameBackgroundSym); miniMap.FillMap(mainBackgroundSym); gameMap.FillContour(gameCounturSym); miniMap.FillContour(mainCounturSym); Map.InsertMatrix(gameMap.map, map.map, 2, 3); Map.InsertMatrix(gameMap.map, tempMap.map, 0, 0); bool isTouched = false; bool touch = false; figCoord = figStartCoord; while (!isRestart) { touch = false; isRightClear = true; isLeftClear = true; isRotatable = true; if (!isTouched) { gameMap.FillMap(gameBackgroundSym); } else { Map.InsertMatrix(tempMap.map, gameMap.map, 0, 0); } { // модуль движения if (pressLeft) { figCoord.x = figCoord.x - 1; pressLeft = false; } if (pressRight) { figCoord.x = figCoord.x + 1; pressRight = false; } if (pressDown) { gameSpeed = gameSpeedBoost; pressDown = false; } } // модуль движения Coord[] figArray; Coord[] nextFigArray; figVerTemp = figVer; if (figVer == 4) figVerNext = 1; else figVerNext = figVer + 1; nextFigArray = gameMap.PutFig(figCoord, figSym, tempRnd, figVerNext, false); figArray = gameMap.PutFig(figCoord, figSym, tempRnd, figVerTemp, true); miniMap.FillMap(gameBackgroundSym); miniMap.FillContour(gameCounturSym); if (nextRnd == 1 || nextRnd == 3) // вставка следующей фигуры в миниатюрке miniMap.PutFig(new Coord(3, 2), figSym, nextRnd, 1, true); else miniMap.PutFig(new Coord(3, 3), figSym, nextRnd, 1, true); Map.InsertMatrix(miniMap.map, map.map, xyMini.x, xyMini.y); int max = 0; int min = size_x; int max_Y = 0; foreach (Coord xy in figArray) { if (max <= xy.x) max = xy.x; if (min >= xy.x) min = xy.x; if (max_Y <= xy.y) max_Y = xy.y; figMax_X = max; figMin_X = min; } gameMap.FillContour(gameCounturSym); Map.InsertMatrix(gameMap.map, map.map, 2, 3); foreach (Coord xy in nextFigArray) // проверка для вращения фигуры (чтобы при следующем положении не вылететь за пределы) { if (max <= xy.x) max = xy.x; if (min >= xy.x) min = xy.x; if (min < 1) isRotatable = false; if (max > 10) isRotatable = false; } if (pressUp && isRotatable) { if (figVer == 4) { figVer = 1; pressUp = false; } else { figVer = figVer + 1; pressUp = false; } } isDownClear = true; foreach (Coord xy in figArray) // проверка нет ли помех по сторонам для движения { if (tempMap.Get(new Coord(xy.x - 1, xy.y)).Contains(figSym) || tempMap.Get(new Coord(xy.x - 1, xy.y)).Contains(gameCounturSym)) isLeftClear = false; if (tempMap.Get(new Coord(xy.x + 1, xy.y)).Contains(figSym) || tempMap.Get(new Coord(xy.x + 1, xy.y)).Contains(gameCounturSym)) isRightClear = false; if (tempMap.Get(new Coord(xy.x, xy.y + 1)).Contains(gameCounturSym) && xy.y > 1 || tempMap.Get(new Coord(xy.x, xy.y + 1)).Contains(figSym) && xy.y > 1) isDownClear = false; } foreach (Coord xy in figArray) // проверка на косание дна { if (!isDownClear) { Map.InsertMatrix(gameMap.map, tempMap.map, 0, 0); figCoord = figStartCoord; isTouched = true; touch = true; if (xy.y < 2) { EndGame(); return; } } } if (touch) { tempRnd = nextRnd; nextRnd = rand.Next(1, 8); if (gameSpeed > 10) { sp -= 3; gameSpeed = sp; } } line = 0; for (int y = tempMap.size_y; y > 1; y--) // удаление заполненного ряда { line = 0; for (int x = 1; x < tempMap.size_x; x++) { if (tempMap.Get(new Coord(tempMap.size_x - x, y)).Contains(figSym)) { line++; } if (line == 10) { score++; for (int yy = y; yy > 1; yy--) { for (int xx = 1; xx < tempMap.size_x; xx++) { tempMap.Copy(new Coord(xx, yy - 1), new Coord(xx, yy)); } } } } // for x } // for y Console.SetCursorPosition(sizeGlobalMap_X - 4, sizeGlobalMap_Y); Console.WriteLine($"Score: {score}"); ReBuild(); } // end while thrSpeed.Abort(); } static void Main() { Game g = new Game(sizeGlobalMap_X, sizeGlobalMap_Y); while (!g.isRestart) { Thread thr = new Thread(g.MoveHero); // чтение кавиатуры thr.Start(); Thread thr2 = new Thread(g.MoveHero); // чтение кавиатуры if (g.StartGame()) { if (g.isSettings) { thr.Abort(); g.Settings(); thr2.Start(); g.MainGame(); } else { g.MainGame(); } if (g.isSkipped) { g.MainGame(); } } thr.Abort(); thr2.Abort(); g.isRestart = false; } } } }
cfc14f3718cb1293182ce50067b54bfdd1337b61
C#
DannyBerova/Exercises-Programming-Fundamentals-Extended-May-2017
/ArraysMoreExerciseExtended/06.PowerPlants/06.PowerPlants.cs
3.609375
4
 namespace _06.PowerPlants { using System; using System.Linq; public class Program { public static void Main() { int[] plants = Console.ReadLine(). Split(). Select(int.Parse). ToArray(); int seasonCount = 0; int daysSurvived = 0; int season = plants.Length; while (plants.Max() >= 0 ) { for (int days = 0; days < plants.Length; days++) { for (int eachPlant = 0; eachPlant < plants.Length; eachPlant++) { if (days != eachPlant && plants[eachPlant] > 0) { plants[eachPlant]--; } } daysSurvived++; if (plants.Max() == 0) { break; } } if (plants.Max() == 0) { break; } for (int seasonBreak = 0; seasonBreak < plants.Length; seasonBreak++) { if (plants[seasonBreak] > 0) { plants[seasonBreak]++; } } seasonCount++; } if (seasonCount == 1) { Console.WriteLine($"survived {daysSurvived} days ({seasonCount} season)"); } else { Console.WriteLine($"survived {daysSurvived} days ({seasonCount} seasons)"); } } } }
462153974b590efda25cb9d55db93fa697a2ca6e
C#
intrueder/BuildTreeQuest
/BuildTreeQuestConsole/Program.cs
2.8125
3
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Attributes.Jobs; using BenchmarkDotNet.Running; namespace BuildTreeQuestConsole { [ClrJob] public class Program { [Benchmark(Baseline = true)] public void Test_SimpleSlowTreeBuilder() { IList<ProjectLine> testData = TestDataLoader.LoadDemoData(TestDataLoader.DemoGenDataFileName); IList<ProjectLine> resTestData = SimpleSlowTreeBuilder.BuildTree(testData); } // put your test here //[Benchmark] //public void Test_TreeBuilderNick() //{ // IList<ProjectLine> testData = TestDataLoader.LoadDemoData(TestDataLoader.DemoGenDataFileName); // IList<ProjectLine> resTestData = TreeBuilderNick.BuildTree(testData); //} static void Main(string[] args) { // load source test data const int genChaptersCount = 500; var rnd = new Random(DateTime.Now.Millisecond); IList<ProjectLine> testData = TestDataLoader.GenerateDemoData(genChaptersCount); File.WriteAllLines(TestDataLoader.DemoGenDataFileName, testData.Select(i => i.Chapter).OrderBy(l => rnd.Next(genChaptersCount))); // simple slow build test RunTest(testData, SimpleSlowTreeBuilder.BuildTree); // put your test here //testData = TestDataLoader.LoadDemoData(TestDataLoader.DemoGenDataFileName); // load the same data again //RunTest(testData, TreeBuilderNick.BuildTree); var summary = BenchmarkRunner.Run<Program>(); Console.ReadKey(); } static void RunTest(IList<ProjectLine> testData, Func<IList<ProjectLine>, IList<ProjectLine>> buildTreeTestMethod) { Stopwatch sw = new Stopwatch(); Console.Write($"{buildTreeTestMethod.Method.DeclaringType?.Name ?? ""}.{buildTreeTestMethod.Method.Name}[{testData.Count}] "); sw.Restart(); IList<ProjectLine> resTestData = buildTreeTestMethod(testData); sw.Stop(); Console.WriteLine($"elapsed {sw.Elapsed} {(TestDataChecker.IsCorrectDataTreeList(resTestData) ? "PASSED" : "FAILED")}"); } } }
94b8d4b1b20e3e744cff91b6f39185fc9a7e1098
C#
LawrenceHan/Hearthstone-decompile
/IlSpyDecompile/Assembly-CSharp/Blizzard/Telemetry/WTCG/Client/Product.cs
2.734375
3
using System.IO; using System.Text; namespace Blizzard.Telemetry.WTCG.Client { public class Product : IProtoBuf { public bool HasProductId; private long _ProductId; public bool HasHsProductType; private string _HsProductType; public bool HasHsProductId; private int _HsProductId; public long ProductId { get { return _ProductId; } set { _ProductId = value; HasProductId = true; } } public string HsProductType { get { return _HsProductType; } set { _HsProductType = value; HasHsProductType = value != null; } } public int HsProductId { get { return _HsProductId; } set { _HsProductId = value; HasHsProductId = true; } } public override int GetHashCode() { int num = GetType().GetHashCode(); if (HasProductId) { num ^= ProductId.GetHashCode(); } if (HasHsProductType) { num ^= HsProductType.GetHashCode(); } if (HasHsProductId) { num ^= HsProductId.GetHashCode(); } return num; } public override bool Equals(object obj) { Product product = obj as Product; if (product == null) { return false; } if (HasProductId != product.HasProductId || (HasProductId && !ProductId.Equals(product.ProductId))) { return false; } if (HasHsProductType != product.HasHsProductType || (HasHsProductType && !HsProductType.Equals(product.HsProductType))) { return false; } if (HasHsProductId != product.HasHsProductId || (HasHsProductId && !HsProductId.Equals(product.HsProductId))) { return false; } return true; } public void Deserialize(Stream stream) { Deserialize(stream, this); } public static Product Deserialize(Stream stream, Product instance) { return Deserialize(stream, instance, -1L); } public static Product DeserializeLengthDelimited(Stream stream) { Product product = new Product(); DeserializeLengthDelimited(stream, product); return product; } public static Product DeserializeLengthDelimited(Stream stream, Product instance) { long num = ProtocolParser.ReadUInt32(stream); num += stream.Position; return Deserialize(stream, instance, num); } public static Product Deserialize(Stream stream, Product instance, long limit) { while (true) { if (limit >= 0 && stream.Position >= limit) { if (stream.Position == limit) { break; } throw new ProtocolBufferException("Read past max limit"); } int num = stream.ReadByte(); switch (num) { case -1: break; case 8: instance.ProductId = (long)ProtocolParser.ReadUInt64(stream); continue; case 18: instance.HsProductType = ProtocolParser.ReadString(stream); continue; case 24: instance.HsProductId = (int)ProtocolParser.ReadUInt64(stream); continue; default: { Key key = ProtocolParser.ReadKey((byte)num, stream); if (key.Field == 0) { throw new ProtocolBufferException("Invalid field id: 0, something went wrong in the stream"); } ProtocolParser.SkipKey(stream, key); continue; } } if (limit < 0) { break; } throw new EndOfStreamException(); } return instance; } public void Serialize(Stream stream) { Serialize(stream, this); } public static void Serialize(Stream stream, Product instance) { if (instance.HasProductId) { stream.WriteByte(8); ProtocolParser.WriteUInt64(stream, (ulong)instance.ProductId); } if (instance.HasHsProductType) { stream.WriteByte(18); ProtocolParser.WriteBytes(stream, Encoding.UTF8.GetBytes(instance.HsProductType)); } if (instance.HasHsProductId) { stream.WriteByte(24); ProtocolParser.WriteUInt64(stream, (ulong)instance.HsProductId); } } public uint GetSerializedSize() { uint num = 0u; if (HasProductId) { num++; num += ProtocolParser.SizeOfUInt64((ulong)ProductId); } if (HasHsProductType) { num++; uint byteCount = (uint)Encoding.UTF8.GetByteCount(HsProductType); num += ProtocolParser.SizeOfUInt32(byteCount) + byteCount; } if (HasHsProductId) { num++; num += ProtocolParser.SizeOfUInt64((ulong)HsProductId); } return num; } } }
f144197568e8f7040195e8293ca2773ae12a9b11
C#
gitReeQx/WebStore
/Common/WebStore.Domain/ViewModels/EmployeesViewModel.cs
2.9375
3
using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace WebStore.Domain.ViewModels { public class EmployeesViewModel { [HiddenInput(DisplayValue = false)] public int Id { get; set; } /// <summary>Имя</summary> [Display(Name = "Имя")] [Required(ErrorMessage = "Это обязательное поле")] [StringLength(15, MinimumLength = 3, ErrorMessage = "Длина должна быть от 3-х до 15-ти символов")] [RegularExpression(@"([A-Z][a-z]+)|([А-ЯЁ][а-яё]+)", ErrorMessage = "Ошибка формата имени")] public string FirstName { get; set; } /// <summary>Фамилия</summary> [Display(Name = "Фамилия")] [StringLength(15, MinimumLength = 2, ErrorMessage = "Длина должна быть от 2-х до 15-ти символов")] public string LastName { get; set; } /// <summary>Отчество</summary> [Display(Name = "Отчество")] public string Patronymic { get; set; } /// <summary>Возраст</summary> [Display(Name = "Возраст")] [Range(18, 55, ErrorMessage = "От 18-ти до 55-ти")] public int Age { get; set; } public IEnumerable<ValidationResult> Validate(ValidationContext context) { yield return ValidationResult.Success; } } }
46acb29d7b1ec964ffa90f1a66d0f0976a1218cb
C#
LarkLib/TestSolutionE430C
/LarkLab.DemoClass.Libray/SerializableFig.cs
2.78125
3
using LarkLab.DemoClass.Interface; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using System.Text; using System.Threading.Tasks; using System.Xml.Serialization; namespace LarkLab.DemoClass.Libray.DemoFig { public class SerializableFig : BaseFig, IDiscoverable<string> { public void ExecuteTest() { var animal = new Animal() { Name = "dog", Type = "tugou", Age = 13 }; var contentBuilder = new StringBuilder(); XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); ns.Add("", ""); var serializer = new XmlSerializer(typeof(Animal)); using (var writer = new StringWriter(contentBuilder)) { serializer.Serialize(writer, animal, ns); } var xmlContent = contentBuilder.ToString(); using (var reader = new StringReader(xmlContent)) { var animalDe = serializer.Deserialize(reader) as Animal; } IFormatter formatter = new BinaryFormatter(); byte[] objArray = new byte[1024]; var stream = new MemoryStream(objArray); formatter.Serialize(stream, animal); byte[] objDeserializeArray = new byte[1024]; objArray.CopyTo(objDeserializeArray, 0); stream = new MemoryStream(objDeserializeArray); var obj = formatter.Deserialize(stream); stream.Close(); } public string Description { get { return "Demo for ISerializable"; } } public string Code { get { throw new NotImplementedException(); } } public string Execut() { return "public string Execut()"; } } [Serializable] public class Animal : ISerializable { public string Name { get; set; } public string Type { get; set; } public int Age { get; set; } public Animal() { } protected Animal(SerializationInfo info, StreamingContext context) { Name = info.GetString($"{nameof(Animal)}{nameof(Name)}"); Type = info.GetString($"{nameof(Animal)}{nameof(Type)}"); Age = info.GetInt32($"{nameof(Animal)}{nameof(Age)}"); } public void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue($"{nameof(Animal)}{nameof(Name)}", Name); info.AddValue($"{nameof(Animal)}{nameof(Type)}", Type); info.AddValue($"{nameof(Animal)}{nameof(Age)}", Age); } } }
771d1679f3d72d2b743c3bf71385a8e333557c26
C#
oysterouy/oyster.core
/Core/Cache/CacheEntry.cs
2.765625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Oyster.Core.Cache { public class CacheEntry : IDisposable { protected object _value; protected ICache _engine; public string Key; public object Value { get { TouchTime = DateTime.Now; return _value; } internal set { TouchTime = DateTime.Now; _value = value; } } public TimeSpan TimeOut; public TimeSpan LastTouchTimeOut; public DateTime CreateTime; public DateTime TouchTime; public bool Expired { get { bool ret = false; if (TimeOut != TimeSpan.Zero) { if ((DateTime.Now - CreateTime) > TimeOut) { ret = true; } } else if (LastTouchTimeOut != TimeSpan.Zero) { if ((DateTime.Now - TouchTime) > LastTouchTimeOut) { ret = true; } } //实际过期,释放资源 if (ret) { Dispose(); return true; } else { double crtmout = CacheEngine.Instance.CurrentTimeOut; if (crtmout > 0) { if ((DateTime.Now - CreateTime) > TimeSpan.FromMilliseconds(crtmout)) { //当前过期 return true; } } } return false; } } /// <summary> /// 缓存实体 /// </summary> /// <param name="key">缓存Key</param> /// <param name="val">缓存数据</param> /// <param name="tspan">固定过期间隔时间</param> /// <param name="lasttouchspan">最后访问过期间隔时间</param> public CacheEntry(string key, object val, TimeSpan tspan = default(TimeSpan) , TimeSpan lasttouchspan = default(TimeSpan)) { Key = key; _value = val; CreateTime = DateTime.Now; TouchTime = DateTime.Now; TimeOut = tspan; LastTouchTimeOut = lasttouchspan; } /// <summary> /// 要实现失效自动移除缓存必须调用本方法设置缓存容器 /// </summary> /// <param name="engine"></param> public void SetEngine(ICache engine) { _engine = engine; } public void Dispose() { _value = null; if (_engine != null) { _engine.Remove(Key); } } } }
ae702b1e48a4f4bf7635ac5ccd21018e103212a6
C#
irimescu-maria/Problem-Solving-in-Data-Structures-Algorithms-using-C-
/Chapter 6 Sorting/InsertionSort/InsertionSort/InsertionSort.cs
3.734375
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace InsertionSort { public class InsertionSort { private int[] arr; public InsertionSort(int[] array) { arr = array; } public bool more(int value1, int value2) { return value1 > value2; } public virtual void sort() { int size = arr.Length; int i, j, temp; for (i = 0; i < size - 1; i++) { temp = arr[i]; for(j=i; j>0 && more(arr[j-1], temp); j--) { arr[j] = arr[j - 1]; } arr[j] = temp; } } } }
ae0de1500576a2eda2434f5999c8cf8b853b5378
C#
theplacefordev/CircularReferenceFinder
/src/CircularReferenceFinder/CircularReferenceFinder.cs
2.984375
3
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; namespace CircularReferenceFinder { public static class CircularReferenceFinder { private static readonly HashSet<Type> _IgnoredTypes = new HashSet<Type> { typeof(String), typeof(DateTime), typeof(TimeSpan), typeof(DateTimeOffset), typeof(Decimal), typeof(Guid) }; public static IList<CircularReference> FindCycles(object root) { if (root == null) throw new ArgumentNullException(nameof(root)); var cycles = new List<CircularReference>(); depthFirstSearch(root, new List<object>(), new ConditionalWeakTable<object, ObjectState>(), cycles); return cycles; } private static void depthFirstSearch(object node, List<object> parents, ConditionalWeakTable<object, ObjectState> visited, List<CircularReference> cycles) { if (node == null || isTypeShouldBeIgnored(node.GetType())) return; var state = visited.GetStateOrDefault(node, VisitState.NotVisited); if (state == VisitState.Visited) return; if (state == VisitState.Visiting) { // Do not report nodes not included in the cycle. cycles.Add(new CircularReference(parents.Concat(new[] { node }).SkipWhile(parent => !referenceEquals(parent, node)).ToList())); } else { var stateObject = visited.GetOrCreateValue(node); stateObject.State = VisitState.Visiting; parents.Add(node); foreach (var child in getMembers(node)) { depthFirstSearch(child, parents, visited, cycles); } parents.RemoveAt(parents.Count - 1); stateObject.State = VisitState.Visited; } } private static IEnumerable getMembers(object obj) { var res = new List<object>(); if (obj != null) { // if it's collection (array, list, dictionary etc.) - just return it members instead of properties var items = obj as IEnumerable; if (items != null) { return items; } // scan public properties var props = obj.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public); foreach (var propertyInfo in props) { if (!isTypeShouldBeIgnored(propertyInfo.PropertyType) && propertyInfo.GetIndexParameters().Length == 0) // ignore indexer properties { res.Add(propertyInfo.GetValue(obj)); } } } return res; } private static bool isTypeShouldBeIgnored(Type type) { // Note: following code intentionally doesn't ignore all value-type types, since custom structures may has reference type based properties return type.IsPrimitive || type.IsEnum || _IgnoredTypes.Contains(type); } private static bool referenceEquals(object objA, object objB) { return (objA != null && objB != null) && ReferenceEquals(objA, objB); } } }
41b5789f7c45aeda499c6a13bdb39bd515e8c27b
C#
abelenstrahn/db_hl7_export_gnu
/EstomedApp/src/NetUtil.cs
2.625
3
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Net; using System.Net.NetworkInformation; using System.Net.Sockets; using System.Text; using System.Text.RegularExpressions; using System.Windows; namespace EstomedApp { class NetUtil { private int minPort; private int maxPort; private ScanPortsCb cb; private string host; public interface ScanPortsCb { void onScanProgress(double pr); void onScanResult(List<int> usedPort); } public NetUtil(ScanPortsCb _cb, string _host = "localhost", int _minPort = 22, int _maxPort = 64000) { cb = _cb; host = _host; minPort = _minPort; maxPort = _maxPort; } public static bool IsLocalHost(string host) { IPAddress[] hosts; IPAddress[] locals; hosts = Dns.GetHostAddresses(host); locals = Dns.GetHostAddresses(Dns.GetHostName()); foreach (IPAddress hostAddress in hosts) { if (IPAddress.IsLoopback(hostAddress)) return true; else { foreach (IPAddress localAddress in locals) { if (hostAddress.Equals(localAddress)) return true; } } } return false; } public void ScanPorts() { List<int> usedPort = new List<int>(); if (IsLocalHost(host)) { IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties(); IPEndPoint[] tcpConnInfoArray = ipGlobalProperties.GetActiveTcpListeners(); int i = 0; foreach (IPEndPoint endpoint in tcpConnInfoArray) { if(!usedPort.Contains(endpoint.Port)) usedPort.Add(endpoint.Port); cb.onScanProgress(100 * i / tcpConnInfoArray.Length); } } else { cb.onScanProgress(0); Process p = new Process(); p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.FileName = "netstat"; p.StartInfo.CreateNoWindow = true; p.Start(); string output = p.StandardOutput.ReadToEnd(); p.WaitForExit(); string pattern = host + ":(\\d+)"; MessageBox.Show(pattern + " " + output); Regex rgx = new Regex(pattern); foreach (Match match in rgx.Matches(output)) { usedPort.Add(Int32.Parse(match.Groups[1].Value)); } } cb.onScanResult(usedPort); } } }
97855a54b975cf714d72254d8ea09d4d41ada259
C#
JMauricio-source/WordLadder
/WordLadder/TmpProcessingService.cs
2.578125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using WordLadder.Models; using System.Text.RegularExpressions; using System.IO; namespace WordLadder { public class TmpProcessingService { //private List<string> _wordList; //private string _startWord; //private string _finalWord; private List<string> _workingWordList; private List<string> _workingMatchList; // private JobPayload _payload; //private MatchResult rootSearchTree; private List<string> WorkingWordList { get { return _workingWordList == null ? _workingWordList = new List<string>() : _workingWordList; } } public TmpProcessingService() { //_wordList = wordList; //_startWord = payload.StartWord; //_finalWord = payload.EndWord; //_payload = payload; //rootSearchTree = new MatchResult(_startWord, null); } //public List<string> Process(List<string> wordList, JobPayload payload) //{ // var _startWord = payload.StartWord; // List<string> resultList = new List<string>() { _startWord }; // var _wordSize = _startWord.Length; // _workingWordList = wordList.Where(e => e.Length == _wordSize).Select(e => e).ToList(); // _workingWordList.Remove(_startWord); // List<string> _currentMatches = new List<string>() { _startWord }; // List<string> _nextMatches = new List<string>(); // bool keepProcessing = true; // while (keepProcessing) // { // foreach (var s in _currentMatches) // { // keepProcessing &= !MatchingCycle(_wordSize, s, _nextMatches, payload); // _nextMatches = RemoveDuplicates(_nextMatches); // } // _currentMatches = RemoveDuplicates(_nextMatches); // } // return resultList; //} public List<string> ProcessTwo(List<string> wordList, JobPayloadCommand payload) { var _startWord = payload.StartWord; var _wordSize = _startWord.Length; List<string> resultList = new List<string>() { _startWord }; _workingMatchList = new List<string>(); _workingWordList = wordList.Where(e => e.Length == _wordSize).Select(e => e).ToList(); _workingWordList.Remove(_startWord); bool keepProcessing = true; MatchResult mResult = new MatchResult(_startWord, null); MatchResult pointer = null; keepProcessing &= !MatchingCycleSearchable(_wordSize, mResult.SourceWord, mResult, payload); pointer = mResult; int counter = 0; while (keepProcessing) { Console.WriteLine($"Nível: {counter}"); foreach (var mr in pointer.MatchesList) { keepProcessing &= !MatchingCycleSearchable(_wordSize, mr.SourceWord, mr,payload); // _nextMatches = RemoveDuplicates(_nextMatches); //PrintNode(mr); if (!keepProcessing) break; } //_currentMatches = RemoveDuplicates(_nextMatches); pointer = NextNodeBreadFirst(pointer); keepProcessing &= pointer != null; counter++; } return resultList; } private MatchResult NextNodeBreadFirst(MatchResult current) { if (current.ParentMatch != null) { var n = current.ParentMatch.MatchesList.GetNextSibling(current); if (n != null) return n; } if (current.MatchesList.Count > 0) return current.MatchesList.First<MatchResult>(); return null; } //private bool MatchingCycle(int _wordSize, string _startWord, List<string> _matchedList, JobPayload payload) //{ // var mutations = GenerateMutations(_wordSize, _startWord); // var regexSet = GenerateRegex(_wordSize, mutations); // _matchedList.AddRange(GenerateMatchesForBreathFirst(regexSet)); // return IsFinal(_matchedList, payload.EndWord); //} private bool MatchingCycleSearchable(int _wordSize, string _startWord, MatchResult mResult, JobPayloadCommand payload) { var mutations = GenerateMutations(_wordSize, _startWord); var regexSet = GenerateRegex(_wordSize, mutations); GenerateMatchesForDeepFirst(regexSet, mResult); var isfinal = IsFinal(mResult.MatchesList.Select(e => e.SourceWord).ToList(), payload.EndWord); if (isfinal) { File.WriteAllText(payload.ResultPublicationPath, PrintPath(mResult, payload.EndWord)); //PrintPath(mResult); } return isfinal; } private string PrintPath(MatchResult mResult, string finalWord) { //Console.WriteLine(_startWord+"=>"); var sb = new StringBuilder(); var l = mResult.AncestorAndSelfList(); l.Reverse(); l.ForEach(e => sb.AppendLine(" => "+ e)); sb.AppendLine("<="+finalWord); var ret = sb.ToString(); Console.WriteLine(ret); return ret; } private void PrintNode(MatchResult mResult) { StringBuilder sb = new StringBuilder(); var _names = mResult.MatchesList.Select(e => e.SourceWord).ToList() ; foreach (var s in _names) sb.Append(s + " "); Console.WriteLine($"{mResult.SourceWord}=>{sb.ToString()}"); } private WordTokens[] GenerateMutations(int wordLength, string word) { WordTokens[] mutations = new WordTokens[wordLength]; for (int i = 0; i < wordLength; i++) { var left = new String(word.Take(i).ToArray()); var right = new String(word.Skip(i + 1).ToArray()); mutations[i] = new WordTokens() { LeftToken = left, RightToken = right }; } return mutations; } private Regex[] GenerateRegex(int wordLength, WordTokens[] tokens) { string oneCharToken = @"\D{1}"; Regex[] regexp = new Regex[wordLength]; for (int i = 0; i < wordLength; i++) { regexp[i] = new Regex(string.Concat(tokens[i].LeftToken, oneCharToken, tokens[i].RightToken), RegexOptions.IgnoreCase); } return regexp; } private List<string> GenerateMatchesForBreathFirst(Regex[] regexset) { List<string> matches = new List<string>(); regexset.ToList().ForEach((r) => matches.AddRange(_workingWordList.Where(e => r.IsMatch(e)).Select(e => e).ToList())); return matches; } private List<string> GenerateMatchesForDeepFirst(Regex[] regexset, MatchResult mResult) { List<string> matches = new List<string>(); regexset.ToList().ForEach((r) => matches.AddRange(_workingWordList.Where(e => r.IsMatch(e) && e != mResult.SourceWord ).Select(e => e).ToList())); matches = matches.Except(this._workingMatchList).ToList(); this._workingMatchList.AddRange(matches); matches.ForEach(e => mResult.MatchesList.AddLast(new MatchResult(e, mResult))); return matches; } private bool IsFinal(List<string> resultsList, string endWord) { return resultsList == null || resultsList.Contains(endWord); } private List<string> RemoveDuplicates(List<string> _list) { List<string> result = new List<string>(); foreach (var s in _list) { if (!result.Contains(s)) result.Add(s); } return result; } } }
c024be4e03a3715b951c2ecb6431216697dfe45d
C#
izmaxss22/Work
/Assets/ApiSetup.cs
2.8125
3
namespace Extension { public struct ApiSetup<T> { } class Api { public ApiSetup<T> For<T>(T obj) { return new ApiSetup<T>(); } } interface ISomeInterfaceA { } interface ISomeInterfaceB { } public class ObjectA : ISomeInterfaceA { } public class ObjectB : ISomeInterfaceB { } class SomeClass { public void Setup() { Api apiObject = new Api(); apiObject.For(new ObjectA()).SetupObjectA(); apiObject.For(new ObjectB()).SetupObjectB(); apiObject.For(new ObjectB()).SetupObjectB(); } } static class ExtensionApiSetup { public static void SetupObjectA(this ApiSetup<ObjectA> a) { } public static void SetupObjectB(this ApiSetup<ObjectB> b) { } } }
c63dddca5ee8fbb4a35bccc3a89d7c189d57cc56
C#
sykvel/Reinforced.Stroke
/Reinforced.Stroke.Demo/Program.cs
2.640625
3
using System; using Reinforced.SqlStroke.Demo.Data; using Reinforced.Stroke; namespace Reinforced.SqlStroke.Demo { class Program { static void Main(string[] args) { using (var dc = new MyDbContext()) { //---------- //dc.Stroke<Order>(x => $"DELETE FROM {x} WHERE {x.Subtotal} = 0"); //---------- //var old = DateTime.Today.AddDays(-30); //dc.Stroke<Customer>(x => $"UPDATE {x} SET {x.IsActive} = 0 WHERE {x.RegisterDate} < {old}"); //---------- dc.Stroke<Item, Order>((i, o) => $@" UPDATE {i} SET {i.Name} = '[FREE] ' + {i.Name} FROM {i} INNER JOIN {o} ON {i.OrderId} = {o.Id} WHERE {o.Subtotal} = 0" , fullQualified:true); } } } }
8debff5502085e97054b02e086780a3ee20f7616
C#
HermesPasser/ironpascal
/Lex/Lexer.cs
3.171875
3
using System; using System.Collections.Generic; using System.Globalization; namespace IronPascal.Lex { public class Lexer { public string Text; private int Position = 0; private char? CurrentChar; private Dictionary<string, Token> ReservedKeywords = new Dictionary<string, Token> { ["PROGRAM"] = new Token(TokenKind.KeyProgram, "PROGRAM"), ["VAR"] = new Token(TokenKind.KeyVar, "VAR"), ["DIV"] = new Token(TokenKind.IntDiv, "DIV"), ["BEGIN"] = new Token(TokenKind.KeyBegin, "BEGIN"), ["INTEGER"] = new Token(TokenKind.Int, "INTEGER"), // usar int mesmo? ["REAL"] = new Token(TokenKind.Real, "REAL"), ["PROCEDURE"] = new Token(TokenKind.KeyProcedure, "PROCEDURE"), ["END"] = new Token(TokenKind.KeyEnd, "END"), }; public Lexer(string text) { Text = text; CurrentChar = Text[Position]; } Exception ThrowError() => throw new LexerException($"Invalid character '{CurrentChar}'"); void Advance(int times = 1) { for(int i = 0; i < times; i++) CurrentChar = (++Position > Text.Length - 1) ? null : (char?)Text[Position]; } public char? Peek() => (Position + 1 > Text.Length - 1) ? null : (char?)Text[Position + 1]; void SkipWhiteSpace() { while (CurrentChar.HasValue && char.IsWhiteSpace(CurrentChar.Value)) Advance(); } void SkipComment() { while (CurrentChar != '}') Advance(); Advance(); // close } } // retornava int e agora token Token Number() { string result = ""; while (CurrentChar.HasValue && char.IsDigit(CurrentChar.Value)) { result += CurrentChar; Advance(); } if (CurrentChar == '.') { result += CurrentChar; Advance(); while (CurrentChar.HasValue && char.IsDigit(CurrentChar.Value)) { result += CurrentChar; Advance(); } return new Token(TokenKind.RealConst, result); } return new Token(TokenKind.IntConst, result); } Token Id() { string key = ""; // TODO: remove latin characters and add _ while(CurrentChar.HasValue && char.IsLetterOrDigit(CurrentChar.Value)) { key += CurrentChar; Advance(); } if (ReservedKeywords.ContainsKey(key.ToUpper())) return ReservedKeywords[key.ToUpper()]; return new Token(TokenKind.Id, key); } public Token NextToken() { while(CurrentChar.HasValue) { if (char.IsWhiteSpace(CurrentChar.Value)) { SkipWhiteSpace(); continue; } if (CurrentChar == '{') { Advance(); SkipComment(); continue; } // TODO: stills accepts latin letters if (char.IsLetter(CurrentChar.Value)) return Id(); if (char.IsDigit(CurrentChar.Value)) return Number(); if (CurrentChar == ':' && Peek() == '=') { Advance(2); return new Token(TokenKind.Assign, ":="); } if (CurrentChar == ';') { Advance(); return new Token(TokenKind.Semi, ";"); } if (CurrentChar == ':') { Advance(); return new Token(TokenKind.Colon, ":"); } if (CurrentChar == ',') { Advance(2); return new Token(TokenKind.Comma, ","); } if (CurrentChar == '+') { Advance(); return new Token(TokenKind.Plus, "+"); } if (CurrentChar == '-') { Advance(); return new Token(TokenKind.Minus, "-"); } if (CurrentChar == '*') { Advance(); return new Token(TokenKind.Mul, "*"); } if (CurrentChar == '/') { Advance(); return new Token(TokenKind.FloatDiv, "/"); } if (CurrentChar == '(') { Advance(); return new Token(TokenKind.LParen, "("); } if (CurrentChar == ')') { Advance(); return new Token(TokenKind.RParen, ")"); } if (CurrentChar == '.') { Advance(); return new Token(TokenKind.Dot, "."); } ThrowError(); } return new Token(TokenKind.Eof, null); } } }
ff23db7836d7deacafd2d8d64a6f900f27256106
C#
steve-salmond/LD33
/Assets/Scripts/Combat/Detonate/DetonateBehavior.cs
2.53125
3
using UnityEngine; using System.Collections; public class DetonateBehavior : MonoBehaviour { // Properties // ---------------------------------------------------------------------------- /** Detonation mask. */ public LayerMask DetonateMask; /** Destruction effect. */ public GameObject DetonateEffect; /** Probability of playing destruction effect. */ public float DetonateEffectProbability = 1; /** Location to place detonation. */ public Transform DetonateLocation; /** Blast radius. */ public float DetonateRadius = 2; /** Explosive force to apply. */ public float DetonateForce = 0; /** Minimum damage amount. */ public float MinDamage = 10; /** Maximum damage amount. */ public float MaxDamage = 10; /** Whether to return object to pool immediately. */ public bool ReturnToPool = true; public Attack Attack { get; private set; } private bool _detonated; void Start() { Attack = GetComponent<Attack>(); if (DetonateLocation == null) DetonateLocation = transform; } protected virtual void OnEnable() { _detonated = false; } /** Detonate the object. */ public void Detonate(Vector3 position, Quaternion rotation, Vector3 direction) { if (_detonated) return; _detonated = true; // Apply blast radius effect. ApplyBlast(transform.position, DetonateRadius); // Create the detonation effect. if (DetonateEffect != null && DetonateLocation != null && Random.value <= DetonateEffectProbability) { var go = ObjectPool.Instance.GetObject(DetonateEffect); go.transform.position = DetonateLocation.position; go.transform.rotation = DetonateLocation.rotation; } // Destroy this object. if (ReturnToPool) ObjectPool.Instance.ReturnObject(gameObject); } /** Damage everything in the blast radius. */ private void ApplyBlast(Vector3 location, float radius) { var hits = Physics.OverlapSphere(transform.position, DetonateRadius, DetonateMask); foreach (var hit in hits) { if (!hit.transform.gameObject.activeSelf) continue; var d = hit.transform.GetComponent<Destructible>(); if (d == null) continue; var delta = hit.transform.position - location; var t = 1 - delta.magnitude / radius; var damage = Mathf.Lerp(MinDamage, MaxDamage, t); d.Damage(damage, hit.transform.position, Attack); if (DetonateForce > 0) { var body = hit.GetComponent<Rigidbody>(); if (body) body.AddForce(delta.normalized * DetonateForce); } } } }
0e5f554cd6aaaf794994ff07ac9ac0ffeaed93a7
C#
hjgode/RAC_switch
/sdf_src/Samples/CSharp/PingSample/Program.cs
2.71875
3
using System; using System.Collections.Generic; using System.Text; using OpenNETCF.Net.NetworkInformation; using System.Net; using System.Diagnostics; namespace PingSample { class Program { static void Main(string[] args) { IPHostEntry hostEnt = Dns.GetHostEntry("www.opennetcf.com"); IPAddress ip = hostEnt.AddressList[0]; Ping ping = new Ping(); byte[] sendBuffer = new byte[] { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, }; Debug.WriteLine(string.Format("Pinging 'www.opennetcf.com' [{0}] with 32 bytes of data:", ip.ToString())); for (int i = 0; i < 4; i++) { try { PingReply reply = ping.Send(ip, sendBuffer, 200, null); if (reply.Status == IPStatus.Success) { Debug.WriteLine(string.Format("Reply from {0}: bytes=32 time={1}ms TTL={2}", reply.Address.ToString(), reply.RoundTripTime, reply.Options.Ttl)); } else { Debug.WriteLine(string.Format("Failed: {0}", reply.Status.ToString())); } } catch(Exception ex) { Debug.WriteLine(ex.Message); break; } } } } }
f302f1f072b26a0962ab1d3eb90b855dd82a4090
C#
JohnKarnel/StudentProgress
/StudentLogic/Teacher.cs
3
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Runtime.Serialization; using MyDataBaseFramework; using System.Data; namespace StudentLogic { [DataContract] public class Teacher : Base<Teacher> { [DataMember] private string _sname; [DataMember] private string _name; [DataMember] private string _pname; public string Name { get { return _name; } private set { _name = value; } } public string Sname { get { return _sname; } private set { _sname = value; } } public string Pname { get { return _pname; } private set { _pname = value; } } public Teacher(string sname, string name, string pname) { _name = name; _sname = sname; _pname = pname; } public Teacher(Guid id, string sname, string name, string pname) : base(id) { _name = name; _sname = sname; _pname = pname; } public static Teacher GetTeacherByLogin(string login, string password) { var result = TableData.SelectByRule("Teacher", "StudentProgressDB", new List<string>(){ "[Login]", "[Password]"}, new List<string>(){ login, password}); if(result.Rows.Count == 0) { throw new Exception("Такого користувача не існує"); } Guid id = Guid.Parse(result.Rows[0][0].ToString()); Teacher teacher; try { teacher = Teacher.Items[id]; } catch(Exception) { teacher = null; } if (teacher == null) { teacher = new Teacher(id, result.Rows[0][1].ToString(), result.Rows[0][2].ToString(), result.Rows[0][3].ToString()); } return teacher; } public static int RegistrateTeacher(Teacher teacher, string login, string password) { DataTable result = TableData.SelectByRule("Teacher", "StudentProgressDB", new List<string>(){ "[Login]"}, new List<string>(){ login}); if (result.Rows.Count != 0) throw new Exception("Вчитель з таким логіном вже існує"); return TableData.InsertInto("Teacher", "StudentProgressDB", new List<string>(){ teacher.Id.ToString(), teacher.Sname, teacher.Name, teacher.Pname, login, password}, new List<string>(){ "TeacherID", "SName", "Name", "PName", "[Login]", "[Password]"}); } public static List<Teacher> GetAllTeachers() { List<Teacher> teachers = new List<Teacher>(); DataTable teachersTable = TableData.SelectAll("Teacher", "StudentProgressDB"); if (teachersTable.Rows.Count == 0) return teachers; foreach (DataRow teach in teachersTable.Rows) { Guid teachId = Guid.Parse(teach[0].ToString()); if (Teacher.Items.Keys.Contains(teachId)) teachers.Add(Teacher.Items[teachId]); else { string teachSName = teach[1].ToString(); string teachName = teach[2].ToString(); string teachPName = teach[3].ToString(); teachers.Add(new Teacher(teachId, teachSName, teachName, teachPName)); } } return teachers; } public static Teacher GetById(Guid id) { Teacher result = null; foreach (var teach in GetAllTeachers()) { if (teach.Id == id) { result = teach; break; } } return result; } } }
fcaec6d6f6cf038985941ddcb0cab4ce5e852e2a
C#
diogolmenezes/OracleSessionEr
/Monitorador.cs
2.890625
3
using Framework.Log; using Oracle.DataAccess.Client; using System.Configuration; using System.Threading; namespace SessionEr { /// <summary> /// Monitora o numero de sessões do ORACLE /// </summary> public class Monitorador { public void Monitorar(string usuario, int intervalo, int vezes, bool detalhar = false) { LogHelper.Write(string.Format("Iniciando teste para o usuário {0} de {1} em {1} segundos por {2} vezes", usuario, intervalo, vezes)); using (var conexao = new OracleConnection(ConfigurationManager.ConnectionStrings["Oracle"].ConnectionString)) { for (int i = 1; i <= vezes; i++) { try { conexao.Open(); if (detalhar) Detalhado(conexao, usuario); else Simples(conexao, usuario); } finally { conexao.Close(); Thread.Sleep(intervalo * 1000); } } } } private void Simples(OracleConnection conexao, string usuario) { var SQL = string.Format("select count(1) as total from v$session where username = '{0}'", usuario); using (var reader = new OracleCommand(SQL, conexao).ExecuteReader()) { while (reader.Read()) { LogHelper.Write(reader["total"].ToString()); } } } private void Detalhado(OracleConnection conexao, string usuario) { Simples(conexao, usuario); var SQL = string.Format("select count(1) as total, osuser, machine, program, state from v$session where username = '{0}' group by osuser, machine, program, state", usuario); using (var reader = new OracleCommand(SQL, conexao).ExecuteReader()) { while (reader.Read()) { LogHelper.Write(string.Format("TOTAL[{0}] PROGRAM[{1}] STATE[{2}], OSUSER[{3}], MACHINE[{4}]", reader["total"], reader["program"], reader["state"], reader["osuser"], reader["machine"]).ToString()); } } } } }
b877ccd98399ca2dfa9517865f215b30f6f3b9d6
C#
D-bugging/CSharp-Repository
/JogoDaNova/Program.cs
3.296875
3
using System; namespace JogoDaNova { class Program { static void Show(char[,] velha) { for (int i = 0; i < 3; i++) { Console.WriteLine(velha[i, 0] + "|" + velha[i, 1] + "|" + velha[i, 2]); if (i < 2) Console.WriteLine("------"); } } static void Main(string[] args) { char[,] velha = new char[3, 3]; bool result = true; int linha, coluna; while (result) { Show(velha); Console.WriteLine("Primeiro jogador: "); Console.Write("Digite a linha: "); linha = int.Parse(Console.ReadLine()); Console.Write("Digite a coluna: "); coluna = int.Parse(Console.ReadLine()); velha[linha, coluna] = 'x'; Show(velha); Console.WriteLine("Segundo jogador: "); Console.Write("Digite a linha: "); linha = int.Parse(Console.ReadLine()); Console.Write("Digite a coluna: "); coluna = int.Parse(Console.ReadLine()); velha[linha, coluna] = 'o'; Console.Clear(); // Verifica x if (velha[0, 0] == 'x' && velha[0, 1] == 'x' && velha[0, 2] == 'x' || velha[0, 0] == 'x' && velha[1, 0] == 'x' && velha[2, 0] == 'x' || velha[0, 0] == 'x' && velha[1, 1] == 'x' && velha[2, 2] == 'x' || velha[0, 1] == 'x' && velha[1, 1] == 'x' && velha[2, 1] == 'x' || velha[0, 2] == 'x' && velha[1, 2] == 'x' && velha[2, 2] == 'x' || velha[0, 2] == 'x' && velha[1, 1] == 'x' && velha[2, 0] == 'x' || velha[1, 0] == 'x' && velha[1, 1] == 'x' && velha[1, 2] == 'x' || velha[2, 0] == 'x' && velha[2, 1] == 'x' && velha[2, 2] == 'x') { Console.WriteLine("Jogador 1 venceu!"); result = false; } // Verifica o else if (velha[0, 0] == 'o' && velha[0, 1] == 'o' && velha[0, 2] == 'o' || velha[0, 0] == 'o' && velha[1, 0] == 'o' && velha[2, 0] == 'o' || velha[0, 0] == 'o' && velha[1, 1] == 'o' && velha[2, 2] == 'o' || velha[0, 1] == 'o' && velha[1, 1] == 'o' && velha[2, 1] == 'o' || velha[0, 2] == 'o' && velha[1, 2] == 'o' && velha[2, 2] == 'o' || velha[0, 2] == 'o' && velha[1, 1] == 'o' && velha[2, 0] == 'o' || velha[1, 0] == 'o' && velha[1, 1] == 'o' && velha[1, 2] == 'o' || velha[2, 0] == 'o' && velha[2, 1] == 'o' && velha[2, 2] == 'o') { Console.WriteLine("Jogador 2 venceu!"); result = false; } // Verifica empate else if (char.IsLetter(velha[0, 0]) && char.IsLetter(velha[0, 1]) && char.IsLetter(velha[0, 2]) && char.IsLetter(velha[1, 0]) && char.IsLetter(velha[1, 1]) && char.IsLetter(velha[1, 2]) && char.IsLetter(velha[2, 0]) && char.IsLetter(velha[2, 1]) && char.IsLetter(velha[2, 2])) { Console.WriteLine("Empate!"); result = false; } } Console.WriteLine("GAME OVER"); Console.ReadKey(); } } }
0559e097896adeef11a54b79908ac0b8fe6ba063
C#
chesterhartin/BridgePattern
/BridgePattern/Abstraction.cs
2.703125
3
namespace BridgePattern { /// <summary> /// The 'Abstraction' class /// </summary> public class Abstraction { protected Implementor _implementor; // Property public Implementor Implementor { set { _implementor = value; } } public virtual void Operation() { _implementor.Operation(); } } }
ae923256eafe0c649e6b8a0c9c0b915c42cb63ba
C#
KanashinDmitry/spbu-se2019-autumn
/Task03/Program.cs
3.296875
3
using System; using System.Threading; namespace Task03 { class Program { static void CreateProducers() { Random random = new Random(); for (int currProd = 0; currProd < SharedRes<int>.amountProducers; ++currProd) { Producer<int> producer = new Producer<int>(); Thread thr = new Thread(() => producer.PutData(random.Next(1, 101))); thr.Start(); } } static void CreateConsumers() { for (int currCons = 0; currCons < SharedRes<int>.amountConsumers; ++currCons) { Consumer<int> consumer = new Consumer<int>(); Thread thr = new Thread(() => consumer.GetData()); thr.Start(); } } static void Main() { CreateProducers(); CreateConsumers(); Console.ReadKey(); Producer<int>.StopInserting(); Consumer<int>.StopGetting(); for (int i = 0; i < SharedRes<int>.amountConsumers; ++i) { SharedRes<int>.Empty.Release(); } } } }
b119d5c5a74b831f5ba59acf3f8dfc00b770ef9a
C#
nhnpro/devx_idle_crafting
/Assets/Standard Assets/Scripts/Pair.cs
3.265625
3
using System; using System.Collections.Generic; namespace UniRx { [Serializable] public struct Pair<T> : IEquatable<Pair<T>> { private readonly T previous; private readonly T current; public T Previous => previous; public T Current => current; public Pair(T previous, T current) { this.previous = previous; this.current = current; } public override int GetHashCode() { EqualityComparer<T> @default = EqualityComparer<T>.Default; int hashCode = @default.GetHashCode(previous); return ((hashCode << 5) + hashCode) ^ @default.GetHashCode(current); } public override bool Equals(object obj) { if (!(obj is Pair<T>)) { return false; } return Equals((Pair<T>)obj); } public bool Equals(Pair<T> other) { EqualityComparer<T> @default = EqualityComparer<T>.Default; return @default.Equals(previous, other.Previous) && @default.Equals(current, other.Current); } public override string ToString() { return $"({previous}, {current})"; } } }
abb3a7a8ba5ced811a152bd1f6eafaedf2911f8f
C#
lincolnyu/docassist
/RenameEnumerator/sample-scripts/sms-renamer.cs
3.0625
3
using System.IO; using System.Collections.Generic; using DocAssistRuntime; namespace RenameScript { class Program { static int CompareDate(int y1, int m1, int d1, int y2, int m2, int d2) { var c = y1.CompareTo(y2); if (c != 0) return c; c = m1.CompareTo(m2); return c != 0 ? c : d1.CompareTo(d2); } static bool IsAllDigit(string testee) { foreach (var ch in testee) { if (!char.IsDigit(ch)) { return false; } } return true; } static bool TryParseDate(string candidate, IEnumerable<char> delimiters, out int year, out int month, out int day) { year = month = day = 0; candidate = candidate.Trim(); candidate = candidate.Trim('"'); var segs = candidate.Split(' '); if (segs.Length < 2) return false; // has to be date + time var dateCand = segs[0]; dateCand = dateCand.Trim(','); string[] dateSegs = null; foreach (var delimiter in delimiters) { dateSegs = dateCand.Split(delimiter); if (dateSegs.Length == 3) break; } if (dateSegs == null || dateSegs.Length != 3) return false; if (dateSegs[2] == "??") dateSegs[2] = "0"; if (!int.TryParse(dateSegs[0], out year)) return false; if (!int.TryParse(dateSegs[1], out month)) return false; if (!int.TryParse(dateSegs[2], out day)) return false; if (year < 1900 || year > 2020) return false; if (month < 1 || month > 12) return false; if (day < 1 || day > 31) return false; return true; } static bool TryParseDate2(string candidate, out int year, out int month, out int day) { year = month = day = 0; candidate = candidate.Trim(); var segs = candidate.Split(','); if (segs.Length < 2) return false; // has to be date + time var dateCand = segs[1]; dateCand = dateCand.Trim(); string[] dateSegs = dateCand.Split('.'); if (dateSegs.Length != 3) return false; if (dateSegs[2] == "??") dateSegs[2] = "0"; if (!int.TryParse(dateSegs[0], out year)) return false; if (!int.TryParse(dateSegs[1], out month)) return false; if (!int.TryParse(dateSegs[2], out day)) return false; if (year < 1900 || year > 2020) return false; if (month < 1 || month > 12) return false; if (day < 1 || day > 31) return false; return true; } static string ProcessText(FileInfo file) { int minDateYear = 0, minDateMonth = 0, minDateDay = 0; int maxDateYear = 0, maxDateMonth = 0, maxDateDay = 0; var firstTime = true; using (var sr = new StreamReader(file.OpenRead())) { string line; while (!sr.EndOfStream && (line=sr.ReadLine())!=null) { int year, month, day; if (!TryParseDate(line, new []{'-','.'}, out year, out month, out day)) { if (!TryParseDate2(line, out year, out month, out day)) continue; } if (firstTime || CompareDate(year, month, day, minDateYear, minDateMonth, minDateDay) < 0) { minDateDay = day; minDateMonth = month; minDateYear = year; } if (firstTime || CompareDate(year, month, day, maxDateYear, maxDateMonth, maxDateDay) > 0) { maxDateDay = day; maxDateMonth = month; maxDateYear = year; } firstTime = false; } } if (firstTime) { return file.Name; } var origName = Path.GetFileNameWithoutExtension(file.Name); var segsOrigName = origName.Split('_'); string suffix=""; if (segsOrigName.Length>0 && segsOrigName[0] == "sms") { var i = 1; for ( ; i<segsOrigName.Length && IsAllDigit(segsOrigName[i]); i++); for ( ; i < segsOrigName.Length; i++) { suffix += "-"; suffix += segsOrigName[i]; } } var newName = string.Format("{0:0000}{1:00}{2:00}-{3:0000}{4:00}{5:00}{6}.txt", minDateYear, minDateMonth, minDateDay, maxDateYear, maxDateMonth, maxDateDay, suffix); return newName; } static string ProcessCsv(FileInfo file) { int minDateYear = 0, minDateMonth = 0, minDateDay = 0; int maxDateYear = 0, maxDateMonth = 0, maxDateDay = 0; var firstTime = true; using (var f = file.OpenRead()) { using (var sr = new StreamReader(f)) { string line; while (!sr.EndOfStream && (line=sr.ReadLine())!=null) { line = line.Trim(); if (line == string.Empty) continue; var segs = line.SplitCsvLine(); foreach (var seg in segs) { int year, month, day; if (TryParseDate(seg, new []{'.'}, out year, out month, out day)) { if (firstTime || CompareDate(year, month, day, minDateYear, minDateMonth, minDateDay) < 0) { minDateDay = day; minDateMonth = month; minDateYear = year; } if (firstTime || CompareDate(year, month, day, maxDateYear, maxDateMonth, maxDateDay) > 0) { maxDateDay = day; maxDateMonth = month; maxDateYear = year; } firstTime = false; break; } } } } } var origName = Path.GetFileNameWithoutExtension(file.Name); var segsOrigName = origName.Split('_'); string suffix=""; if (segsOrigName.Length>0 && segsOrigName[0] == "sms") { var i = 1; for ( ; i<segsOrigName.Length && IsAllDigit(segsOrigName[i]); i++); for ( ; i < segsOrigName.Length; i++) { suffix += "-"; suffix += segsOrigName[i]; } } var newName = string.Format("{0:0000}{1:00}{2:00}-{3:0000}{4:00}{5:00}{6}.csv", minDateYear, minDateMonth, minDateDay, maxDateYear, maxDateMonth, maxDateDay, suffix); return newName; } static int TestSmsType(FileInfo file) { using (var f = file.OpenRead()) { using (var sr = new StreamReader(f)) { string line; bool hasNonEmptyLine = false; while (!sr.EndOfStream && (line=sr.ReadLine())!=null) { line = line.Trim(); if (line == string.Empty) continue; hasNonEmptyLine = true; var segs = line.SplitCsvLine(); if (segs.Count==1) return 2; } return hasNonEmptyLine? 1 : 0; } } } public static IList<string> RenameFiles(IEnumerable<FileInfo> files) { var newNames = new List<string>(); foreach (var file in files) { var type = TestSmsType(file); if (type == 1) //csv { var newName = ProcessCsv(file); newNames.Add(newName); } else if (type == 2) //txt { var newName = ProcessText(file); newNames.Add(newName); } else { newNames.Add(""); } } return newNames; } } }
6ba8fe794692d1bbcb20584e3a76f5fc2bf2d35d
C#
TotalneSzefy/RPGproGAME
/Dane/Bohater.cs
2.5625
3
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RPG.Dane { public class Bohater : Postać, INotifyPropertyChanged { #region Pola private int doswiadczenie; private int zloto; private int sila; private int inteligencja; private int zrecznosc; private int wytrzymalosc; private int obrazenia; private int obrona; private int szansaUnik; private int szansaTrafienia; private Hełm helm; private Broń bron; private Tarcza tarcza; private Spodnie spodnie; private Zbroja zbroja; private Buty buty; #endregion public ObservableCollection<Przedmiot> Ekwipunek = new ObservableCollection<Przedmiot>(); public event PropertyChangedEventHandler PropertyChanged = delegate { }; protected void RaisePropertyChanged(string name) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name)); } public static Bohater Instancja { get; set; } #region Właściwości public int Zycie { get => życie; set { życie = value; PropertyChanged(this, new PropertyChangedEventArgs("Zycie")); } } public int Zloto { get => zloto; set { zloto = value; RaisePropertyChanged("Zloto"); } } public int Sila { get => sila; set { sila = value; aktualizujInfo(); PropertyChanged(this, new PropertyChangedEventArgs("Sila")); } } public int Inteligencja { get => inteligencja; set { inteligencja = value; aktualizujInfo(); PropertyChanged(this, new PropertyChangedEventArgs("Inteligencja")); } } public int Zrecznosc { get => zrecznosc; set { zrecznosc = value; aktualizujInfo(); PropertyChanged(this, new PropertyChangedEventArgs("Zrecznosc")); } } public int Wytrzymalosc { get => wytrzymalosc; set { wytrzymalosc = value; aktualizujInfo(); PropertyChanged(this, new PropertyChangedEventArgs("Wytrzymalosc")); } } public int Obrazenia { get { return obrazenia; } set { obrazenia = value; PropertyChanged(this, new PropertyChangedEventArgs("Obrazenia")); } } public int Obrona { get { return obrona; } set { obrona = value; PropertyChanged(this, new PropertyChangedEventArgs("Obrona")); } } public int SzansaUnik { get { return szansaUnik; } set { szansaUnik = value; PropertyChanged(this, new PropertyChangedEventArgs("SzansaUnik")); } } public int SzansaTrafienia { get { return szansaTrafienia; } set { szansaTrafienia = value; PropertyChanged(this, new PropertyChangedEventArgs("SzansaTrafienia")); } } public int Doświadczenie { get { return doswiadczenie; } set { doswiadczenie = value; if (doswiadczenie >= 1000) { doswiadczenie -= 1000; Poziom++; } PropertyChanged(this, new PropertyChangedEventArgs("Doświadczenie")); } } internal Hełm Helm { get => helm; set { helm = value; PropertyChanged(this, new PropertyChangedEventArgs("Helm")); } } public Broń Bron { get => bron; set { bron = value; PropertyChanged(this, new PropertyChangedEventArgs("Bron")); } } public Tarcza Tarcza { get => tarcza; set { tarcza = value; PropertyChanged(this, new PropertyChangedEventArgs("Tarcza")); } } public Spodnie Spodnie { get => spodnie; set { spodnie = value; PropertyChanged(this, new PropertyChangedEventArgs("Spodnie")); } } public Zbroja Zbroja { get => zbroja; set { zbroja = value; PropertyChanged(this, new PropertyChangedEventArgs("Zbroja")); } } public Buty Buty { get => buty; set { buty = value; PropertyChanged(this, new PropertyChangedEventArgs("Buty")); } } #endregion #region Kostruktory public Bohater(string imie, string sciezkaIkony, int poziom, int życie, int siła, int inteligencja, int zrecznosc, int wytrzymalosc) : base(imie, sciezkaIkony, poziom) { this.Sila = siła; this.Inteligencja = inteligencja; this.Zrecznosc = zrecznosc; this.Wytrzymalosc = wytrzymalosc; this.zloto = 500000; this.Zycie = życie; //string nazwa,int ilosc, int cena, int wymaganyLVL, string sciezkaIkony Ekwipunek.Add(new Hełm("Bylejaka Czapka", 1, 0, 0, "ms-appx:///Assets//NPCimages//helm.png")); Ekwipunek.Add(new Zbroja("Bylejaka Zbroja", 1, 0, 0, "ms-appx:///Assets//NPCimages//zbroja.png")); Ekwipunek.Add(new Tarcza("Bylejaka Tarcza", 1, 0, 0, "ms-appx:///Assets//NPCimages//tarcza.png")); Ekwipunek.Add(new Buty("Bylejakie Buty", 1, 0, 0, "ms-appx:///Assets//NPCimages//buty.png")); Ekwipunek.Add(new Spodnie("Bylejakie Spodnie", 1, 0, 0, "ms-appx:///Assets//NPCimages//spodnie.png")); Ekwipunek.Add(new Broń("Bylejaki miecz", 1, 0, 0, "ms-appx:///Assets//NPCimages//miecz.png")); } public static void CreateStaticInstance(string imie, string sciezkaIkony, int poziom, int życie, int siła, int inteligencja, int zrecznosc, int wytrzymalosc) { Instancja = new Bohater(imie, sciezkaIkony, poziom, życie, siła, inteligencja, zrecznosc, wytrzymalosc); } #endregion #region Metody public void ZaluzPrzedmiot(Przedmiot przedmiot) { if (przedmiot.WymaganyLVL <= Poziom) { if (przedmiot is Hełm) { if (Helm != null) Helm.Zalozony = false; Helm = (Hełm)przedmiot; } else if (przedmiot is Zbroja) { if (Zbroja != null) Zbroja.Zalozony = false; Zbroja = (Zbroja)przedmiot; } else if (przedmiot is Tarcza) { if (Tarcza != null) Tarcza.Zalozony = false; Tarcza = (Tarcza)przedmiot; } else if (przedmiot is Buty) { if (Buty != null) Buty.Zalozony = false; Buty = (Buty)przedmiot; } else if (przedmiot is Spodnie) { if (Spodnie != null) Spodnie.Zalozony = false; Spodnie = (Spodnie)przedmiot; } else if (przedmiot is Broń) { if (Bron != null) Bron.Zalozony = false; Bron = (Broń)przedmiot; Bron.Zalozony = true; } przedmiot.Zalozony = true; } aktualizujInfo(); } public void zdejmijPrzedmiot(Przedmiot przedmiot) { string obraz = "ms-appx:///Assets//przezroczysty.png"; //SEBA TU DAJ ITEM 100% PRZEZROCZYSTY if (przedmiot is Hełm) { if (Helm != null) Helm.Zalozony = false; Helm = new Hełm("", 0, 0, 0, obraz); Helm.ZerujStaty(); } else if (przedmiot is Zbroja) { Zbroja.Zalozony = false; Zbroja = new Zbroja("", 0, 0, 0, obraz); Zbroja.ZerujStaty(); } else if (przedmiot is Tarcza) { Tarcza.Zalozony = false; Tarcza = new Tarcza("", 0, 0, 0, obraz); Tarcza.ZerujStaty(); } else if (przedmiot is Buty) { Buty.Zalozony = false; Buty = new Buty("", 0, 0, 0, obraz); Buty.ZerujStaty(); } else if (przedmiot is Spodnie) { Spodnie.Zalozony = false; Spodnie = new Spodnie("", 0, 0, 0, obraz); Spodnie.ZerujStaty(); } else if (przedmiot is Broń) { Bron.Zalozony = false; Bron = new Broń("", 0, 0, 0, obraz); Bron.ZerujStaty(); } aktualizujInfo(); } public void obliczObrazenia() { double bazowa = Sila; double mnoznik = 1; if (Helm != null) { bazowa += Helm.ObrazeniaBonus; mnoznik += Helm.ObrazeniaMnoznik; } if (Zbroja != null) { bazowa += Zbroja.ObrazeniaBonus; mnoznik += Zbroja.ObrazeniaMnoznik; } if (Tarcza != null) { bazowa += Tarcza.ObrazeniaBonus; mnoznik += Tarcza.ObrazeniaMnoznik; } if (Buty != null) { bazowa += Buty.ObrazeniaBonus; mnoznik += Buty.ObrazeniaMnoznik; } if (Spodnie != null) { bazowa += Spodnie.ObrazeniaBonus; mnoznik += Spodnie.ObrazeniaMnoznik; } if (Bron != null) { bazowa += Bron.ObrazeniaBonus; mnoznik += Bron.ObrazeniaMnoznik; } double result = bazowa * mnoznik; Obrazenia = (int)result; } public void obliczObrona() { double bazowa = Wytrzymalosc; double mnoznik = 1; if (Helm != null) { bazowa += Helm.ObronaBonus; mnoznik += Helm.ObronaMnoznik; } if (Zbroja != null) { bazowa += Zbroja.ObronaBonus; mnoznik += Zbroja.ObronaMnoznik; } if (Tarcza != null) { bazowa += Tarcza.ObronaBonus; mnoznik += Tarcza.ObronaMnoznik; } if (Buty != null) { bazowa += Buty.ObronaBonus; mnoznik += Buty.ObronaMnoznik; } if (Spodnie != null) { bazowa += Spodnie.ObronaBonus; mnoznik += Spodnie.ObronaMnoznik; } if (Bron != null) { bazowa += Bron.ObronaBonus; mnoznik += Bron.ObrazeniaMnoznik; } double result = bazowa * mnoznik; Obrona = (int)result; } public void obliczSTrafienia() { double bazowa = Zrecznosc + 0.75 * Inteligencja; double mnoznik = 1; if (Helm != null) { bazowa += Helm.STrafieniaBonus; mnoznik += Helm.STrafieniaMnozniks; } if (Zbroja != null) { bazowa += Zbroja.STrafieniaBonus; mnoznik += Zbroja.STrafieniaMnozniks; } if (Tarcza != null) { bazowa += Tarcza.STrafieniaBonus; mnoznik += Tarcza.STrafieniaMnozniks; } if (Buty != null) { bazowa += Buty.STrafieniaBonus; mnoznik += Buty.STrafieniaMnozniks; } if (Spodnie != null) { bazowa += Spodnie.STrafieniaBonus; mnoznik += Spodnie.STrafieniaMnozniks; } if (Bron != null) { bazowa += Bron.STrafieniaBonus; mnoznik += Bron.STrafieniaMnozniks; } double result = bazowa * mnoznik; SzansaTrafienia = (int)result; } public void obliczSUnik() { double bazowa = Zrecznosc; double mnoznik = 1; if (Helm != null) { bazowa += Helm.SUnikBonus; mnoznik += Helm.SUnikMnoznik; } if (Zbroja != null) { bazowa += Zbroja.SUnikBonus; mnoznik += Zbroja.SUnikMnoznik; } if (Tarcza != null) { bazowa += Tarcza.SUnikBonus; mnoznik += Tarcza.SUnikMnoznik; } if (Buty != null) { bazowa += Buty.SUnikBonus; mnoznik += Buty.SUnikMnoznik; } if (Spodnie != null) { bazowa += Spodnie.SUnikBonus; mnoznik += Spodnie.SUnikMnoznik; } if (Bron != null) { bazowa += Bron.SUnikBonus; mnoznik += Bron.SUnikMnoznik; } double result = bazowa * mnoznik; SzansaUnik = (int)result; } private void aktualizujInfo() { obliczObrazenia(); obliczObrona(); obliczSTrafienia(); obliczSUnik(); } #endregion } }
a253b63197c72401bee4afb307483db9d559f7b1
C#
bertt/sharpmartini
/sharpmartini.demo.console/Program.cs
2.671875
3
using SixLabors.ImageSharp; using SixLabors.ImageSharp.Drawing.Processing; using SixLabors.ImageSharp.PixelFormats; using SixLabors.ImageSharp.Processing; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; namespace sharpmartini.demo.console { class Program { static void Main(string[] args) { ushort maxError = 100; var fuji = Image.Load<Rgba32>(@"fixtures/fuji.png"); var sw = new Stopwatch(); sw.Start(); var terrain = GridCreator.MapboxTerrainToGrid(fuji); var martini = new Martini(fuji.Width + 1); var tile = martini.CreateTile(terrain); var mesh = tile.getMesh(maxError); sw.Stop(); Console.WriteLine("Elpased: " + sw.Elapsed); var vertices1 = new List<Vertice>(); for (var i = 0; i < mesh.vertices.Length / 2; i++) { var x = mesh.vertices[i * 2]; var y = mesh.vertices[i * 2 + 1]; var z = terrain[y * (fuji.Width + 1) + x]; vertices1.Add(new Vertice { X = x, Y = y, Z = z }); ; } var vertices = vertices1.ToArray(); var pen = Pens.Solid(Color.Black, 1); fuji.Mutate(imageContext => { for (var j = 0; j < mesh.triangles.Length / 3; j++) { var v1 = vertices[mesh.triangles[j * 3]]; var v2 = vertices[mesh.triangles[j * 3 + 1]]; var v3 = vertices[mesh.triangles[j * 3 + 2]]; var line = new List<PointF>(); line.Add(new PointF(v1.X, v1.Y)); line.Add(new PointF(v2.X, v2.Y)); line.Add(new PointF(v3.X, v3.Y)); line.Add(new PointF(v1.X, v1.Y)); imageContext.DrawLines(pen,line.ToArray()); } }); using (var file = File.Create("DrawLinesTest.png")) { fuji.SaveAsPng(file); } } } }
9ac794bf876fc5f4a3df25c1986df18d89be8e88
C#
irakoze101/Payroll
/Payroll/Server/Mappings/EmployeeMappings.cs
2.609375
3
using Microsoft.EntityFrameworkCore.ChangeTracking.Internal; using MoreLinq; using Payroll.Server.Models; using Payroll.Shared.DTO; using System; using System.Collections.Generic; using System.Linq; namespace Payroll.Server.Mappings { // UnitTestTodo: Everything in this class public static class EmployeeMappings { /// <summary> /// Creates a new Employee from a DTO. Only suitable for creating a new Employee. /// </summary> /// <param name="dto"></param> /// <param name="employerId"></param> /// <returns></returns> public static Employee ToEmployee(this EmployeeDto dto, string employerId) { var dependents = dto.Children.Select(d => new Dependent { Id = d.Id, Name = d.Name, Relationship = Relationship.Child, }) .ToList(); if (dto.Spouse != null) { dependents.Add(new Dependent { Id = dto.Spouse.Id, Name = dto.Spouse.Name, Relationship = Relationship.Spouse, }); } return new Employee { AnnualSalary = dto.AnnualSalary, Dependents = dependents, EmployerId = employerId, Id = dto.Id, Name = dto.Name, }; } /// <summary> /// Requires <see cref="Employee.Dependents"/> to be included. /// </summary> public static EmployeeDto ToDto(this Employee employee) { var children = employee.Dependents!.Where(d => d.Relationship == Relationship.Child); var spouse = employee.Dependents?.FirstOrDefault(d => d.Relationship == Relationship.Spouse); return new EmployeeDto { AnnualSalary = employee.AnnualSalary, Children = children.Select(d => new DependentDto { Id = d.Id, Name = d.Name }).ToList(), Id = employee.Id, Name = employee.Name, Spouse = spouse == null ? null : new DependentDto { Id = spouse.Id, Name = spouse.Name }, }; } /// <summary> /// Maps the DTO onto the Employee model. Requires a model with <see cref="Employee.Dependents"/> loaded. /// Throws a <see cref="MappingException"/> on a mismatch between DTO and model. /// </summary> public static void UpdateFrom(this Employee to, EmployeeDto from) { if (to.Dependents == null) { throw new InvalidOperationException("Dependents must be loaded."); } if (to.Id != from.Id) { throw new MappingException($"IDs do not match (from: {from.Id}, to: {to.Id})"); } to.Name = from.Name; to.AnnualSalary = from.AnnualSalary; var toSpouse = to.Dependents.FirstOrDefault(d => d.Relationship == Relationship.Spouse); if (toSpouse != null) { switch (from.Spouse?.Id) { case 0: to.Dependents.Add(new Dependent { Name = from.Spouse.Name, Relationship = Relationship.Spouse }); // This is the first goto I've ever written in C#, but what I really wanted was a fallthrough goto case null; case null: to.Dependents.Remove(toSpouse); break; case var existingId when existingId == toSpouse.Id: toSpouse.Name = from.Spouse.Name; break; default: throw new MappingException("Spouse IDs do not match."); } } else if (from.Spouse != null) { if (from.Spouse.Id != 0) { // Can only update existing spouse or create new one throw new MappingException($"Spouse with ID {from.Spouse.Id} does not exist."); } to.Dependents.Add(new Dependent { Name = from.Spouse.Name, Relationship = Relationship.Spouse }); } // else from and to spouses both null, nothing to do // Update the name for any child DTO with an ID, create a dependent // for any child without an ID, and delete any child from the Employee // with no corresponding DTO present. var newChildDtos = new List<DependentDto>(); var updateChildDtos = new Dictionary<int, DependentDto>(); foreach (var child in from.Children) { if (child.Id != 0) { updateChildDtos[child.Id] = child; } else { newChildDtos.Add(child); } } var (updateChildren, deleteChildren) = to.Dependents.Where(d => d.Relationship == Relationship.Child) .Partition(d => updateChildDtos.ContainsKey(d.Id)); var invalidChild = updateChildDtos.Keys.FirstOrDefault(key => !updateChildren.Any(c => c.Id == key)); if (invalidChild != default) { throw new MappingException($"No child with key {invalidChild} for employee."); } foreach (var toChild in updateChildren) { toChild.Name = updateChildDtos[toChild.Id].Name; } foreach (var deleteChild in deleteChildren) { to.Dependents.Remove(deleteChild); } foreach (var newChildDto in newChildDtos) { to.Dependents.Add(new Dependent { Name = newChildDto.Name, Relationship = Relationship.Child }); } } } }
4baaed0846c031873f4cce0e7daee4f746ff4646
C#
Engin-Boot/review-case-s22b7
/Sender/Sender/Column_Number.cs
2.640625
3
using System; namespace Sender { public class ColumnNumber { public static string TakeColumnNumberForColumnFilter() { Console.WriteLine("Enter 1 for Date & Time column filter and 2 for Comments Column filter"); String columnNumber = Console.ReadLine(); return columnNumber; } } }
ce60b460783d4b4b7b2b988a73b3fb68872d9fa3
C#
JefersonMelo/03-UAM
/Aula_2.1-Desvio_Condicional_Desafios/Codigo_Funcionario/Processamento.cs
3.125
3
using System; using System.Collections.Generic; using System.Text; namespace Codigo_Funcionario { class Processamento { //calcular salário public string aumentoSalarial( int codCargo, double salario ) { switch (codCargo) { case 1: salario += salario * (50.0 / 100.0); return "Escriturário 50% de aumento. Novo salário: " + salario; case 2: salario += salario * (35.0 / 100.0); return "Secretário 35 % de aumento. Novo salário: " + salario; case 3: salario += salario * (20.0 / 100.0); return "Caixa 20% de aumento. Novo salário: " + salario; case 4: salario += salario * (10.0 / 100.0); return "Gerente 10% de aumento. Novo salário: " + salario; case 5: return "5 Diretor Não tem aumento: " + salario; } return "Código Inválido"; } } }
3b3eea4a98374e3eb72d10bdcc2772847d92a7cc
C#
BrettRegnier/Concur
/Concur/src/Views/AddView.cs
2.734375
3
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Concur { public partial class AddView : Form { public FileSync fileSyncer; public AddView(FileSync fs) { fileSyncer = fs; Init(); } public AddView() { Init(); } private void Init() { InitializeComponent(); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; if (fileSyncer != null) { for (int i = 0; i < fileSyncer.Folders().Count; i++) CreateLocationControl(fileSyncer.Folders()[i].Path); } else { CreateLocationControl(); CreateLocationControl(); } } private void CreateLocationControl(string location = "Example: C:\\MyFolder") { Panel panel = new Panel(); Label lbl = new Label(); TextBox txt = new TextBox(); Button browse = new Button(); Button delete = new Button(); lbl.Text = "Location " + (pnlLocations.Controls.Count + 1).ToString(); lbl.Width = 100; lbl.Height = 13; txt.Text = location; txt.ForeColor = Color.DarkGray; txt.GotFocus += RemoveText; txt.LostFocus += AddText; txt.Width = 197; browse.Text = "..."; browse.Width = 36; browse.Click += (sender, e) => { using (var fbd = new FolderBrowserDialog()) { DialogResult r = fbd.ShowDialog(); if (r == DialogResult.OK && !string.IsNullOrWhiteSpace(fbd.SelectedPath)) { txt.Text = fbd.SelectedPath; txt.ForeColor = Color.Black; } } }; delete.Text = "x"; delete.ForeColor = Color.Red; delete.Width = 36; delete.Click += (sender, e) => { bool find = false; for (int i = 0; i < pnlLocations.Controls.Count; i++) { if (find) pnlLocations.Controls[i].Top -= 52; if (panel == pnlLocations.Controls[i]) find = true; } pnlLocations.Controls.Remove(panel); }; lbl.Left = 1; lbl.Top = 2; txt.Left = 10; txt.Top = 20; browse.Left = 213; browse.Top = 20; delete.Left = 255; delete.Top = 20; panel.Controls.Add(lbl); panel.Controls.Add(txt); panel.Controls.Add(browse); panel.Controls.Add(delete); panel.Width = 300; panel.Height = 46; panel.Left = 0; panel.Top = pnlLocations.Controls.Count * 52; pnlLocations.Controls.Add(panel); } private void btnOk_Click(object sender, EventArgs e) { //TODO error check for bad folders, such as //C:/ //C:/Windows //C:/ProgramFiles/ // Error check if the source folder is empty, and ask if the user is okay with that string[] str = new string[pnlLocations.Controls.Count]; int i = 0; foreach (Control pnl in pnlLocations.Controls) { foreach (Control cntrl in pnl.Controls) { if (cntrl is TextBox) { str[i++] = cntrl.Text; continue; } } } // TODO fix up the missing pieces of this thing if (fileSyncer == null) fileSyncer = new FileSync("TODO", str); else fileSyncer.AddFolders(str); DialogResult = DialogResult.OK; this.Close(); } private void btnCancel_Click(object sender, EventArgs e) { DialogResult = DialogResult.No; this.Close(); } public void RemoveText(object sender, EventArgs e) { if (((TextBox)sender).Text == "Example: C:\\MyFolder") ((TextBox)sender).Text = ""; ((TextBox)sender).ForeColor = Color.Black; } public void AddText(object sender, EventArgs e) { if (string.IsNullOrWhiteSpace(((TextBox)sender).Text)) { ((TextBox)sender).Text = "Example: C:\\MyFolder"; ((TextBox)sender).ForeColor = Color.DarkGray; } } private void btnAdd_Click(object sender, EventArgs e) { CreateLocationControl(); } } }
4ecc5b52dc82927c9c83577ea3ff05cf78b81c7d
C#
gitprojectjockey/Dev2017
/MVC_AJAX/MvcAjaxDemo/MvcAjaxDemo.Data/Repositories/Concrete/ProductRepository.cs
2.5625
3
using MvcAjaxDemo.Data.Context; using MvcAjaxDemo.Data.Core.Domain; using MvcAjaxDemo.Data.Repositories.Abstract; using System; using System.Collections.Generic; using System.Linq; namespace MvcAjaxDemo.Data.Repositories.Concrete { public class ProductRepository : Repository<Product>, IProductRepository { public ProductRepository(EDataServContext context) : base(context) { } public IEnumerable<Product> GetProductsPaged(int pageIndex, int pageSize) { throw new NotImplementedException(); } public IEnumerable<Product> GetMostExpensiveProducts(int count) { return EDataServContext.Products.OrderByDescending(p => p.Price).Take(count).ToList(); } public IEnumerable<Product> GetLeastExpensiveProducts(int count) { return EDataServContext.Products.OrderBy(p => p.Price).Take(count).ToList(); } private EDataServContext EDataServContext { get { return _context as EDataServContext; } } } }
34adab65ddd21ee5f85be5239caf6210d24f3bb0
C#
Kwanhong/Black-Hole-Visualization
/Project/Scripts/Game/Photon.cs
2.6875
3
using SFML.System; using SFML.Graphics; using SFML.Window; using System; using System.Collections.Generic; using static BlackHoleVisualization.Utility; using static BlackHoleVisualization.Constants; using static BlackHoleVisualization.Data; namespace BlackHoleVisualization { public class Photon { public Vector2f Position { get; set; } public Vector2f Velocity { get; set; } public List<Vector2f> History { get; set; } public bool IsStopped { get; set; } public bool IsStuffed { get; set; } public bool IsDisappearing { get { return this.History.Count > 100 || ( !this.IsStuffed && this.IsStopped && this.History.Count > 0 ); } } public bool IsDisappeared { get { return !this.IsStuffed && this.IsStopped && this.History.Count <= 0; } } private byte alphaOffset; #region Instructor public Photon(float x, float y) { this.Velocity = new Vector2f(-C, 0); this.Position = new Vector2f(x, y); this.History = new List<Vector2f>(); alphaOffset = (byte)new Random().Next(100); } public Photon(Vector2f pos) { this.Position = pos; this.Velocity = new Vector2f(-C, 0); this.History = new List<Vector2f>(); } public Photon(Vector2f pos, Vector2f vel) { this.Velocity = vel; this.Position = pos; this.History = new List<Vector2f>(); } public Photon(float x, float y, Vector2f vel) { this.Velocity = vel; this.Position = new Vector2f(x, y); this.History = new List<Vector2f>(); } #endregion public void Update() { Move(); GenerateHistory(); } private void Move() { if (this.IsStopped) return; Vector2f DeltaVelocity = this.Velocity; DeltaVelocity *= DT; this.Position += DeltaVelocity; } private void GenerateHistory() { if (!this.IsStopped) this.History.Add(this.Position); if (this.IsDisappearing) History.RemoveAt(0); } public void Display() { if (this.IsDisappeared) return; //DisplayPhoton(); DisplayHistory(); } private void DisplayPhoton() { CircleShape photon = new CircleShape(0.1f); photon.Origin = new Vector2f(photon.Radius, photon.Radius); photon.OutlineThickness = (History.Count * 0.005f); photon.OutlineColor = new Color(255, 255, 255, (byte)(History.Count * 2.55f)); photon.FillColor = new Color(255, 255, 255, (byte)(History.Count * 2.55f)); photon.Position = this.Position; window.Draw(photon); } private void DisplayHistory() { // VertexArray line = new VertexArray(PrimitiveType.Lines); // foreach (var pos in History) // { // Color color = new Color(255, (byte)(History.IndexOf(pos) + 75), 100, (byte)History.IndexOf(pos)); // Vertex vertex = new Vertex(pos, color); // line.Append(vertex); // } // window.Draw(line); VertexArray line = new VertexArray(PrimitiveType.Lines, 2); for (int i = 1; i < History.Count; i++) { byte alpha = (byte)(Limit(MathF.Pow(Map(i, 0, 100, 0, 16), 2) - alphaOffset, 0, 255)); Color color = new Color(255, (byte)(i + 30), 75, alpha); line[0] = new Vertex(History[i - 1], color); line[1] = new Vertex(History[i], color); window.Draw(line); } } } }
8ae15b45d86bf86a68ed5dd05a8f84f089fb8a9b
C#
cyphertfa/top-down-shooter
/Shooter/Assets/Script/Health.cs
3.0625
3
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Health : MonoBehaviour { public int maxHealth = 10; public int currentHealth = 10; // Use this for initialization // Update is called once per frame void Update () { // Destroy this game object when health is less than or equal to 0 if (currentHealth <= 0) { //TODO: Need to hook into this for other systems (drops, game over ect.) Destroy(gameObject); //Debug.Log ("pew pew dead "); } } void OnCollisionEnter2D (Collision2D col) { //if statement to decrease health by 1 every time a game object with a tag "Bullet" hit if(col.gameObject.tag == "Bullet") { Damage(1); } } public void Damage(int amount) { currentHealth = Mathf.Max(currentHealth - amount, 0); Debug.Log(string.Format("Took {0} damage. {1} / {2} HP", amount, currentHealth, maxHealth)); } }
2ea5795b0c56e8c59924eab39064b96d81242a4c
C#
bydan/scode
/Me/Me/Global/DynamicCode/Base/BaseDatosCodeSmith/GrupoProceso.cs
2.578125
3
using System; using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Diagnostics; public class GrupoProceso { protected Int64 id; public Int64 getId() { return this.id; } public void setId(Int64 newId) { if(this.id!=newId) { } this.id=newId; } public Int64 id_sistema; public Int64 id_modulo; public String codigo; public String nombre; public GrupoProceso () { this.id=0L; this.id_sistema=-1L; this.id_modulo=-1L; this.codigo=""; this.nombre=""; } //PROPERTIES public Int64 idSistema_ { get { return this.id_sistema; } set { this.setid_sistema(value); //this.id_sistema = value; } } public Int64 idModulo_ { get { return this.id_modulo; } set { this.setid_modulo(value); //this.id_modulo = value; } } public String Codigo_ { get { return this.codigo; } set { this.setcodigo(value); //this.codigo = value; } } public String Nombre_ { get { return this.nombre; } set { this.setnombre(value); //this.nombre = value; } } public Int64 getid_sistema() { return this.id_sistema; } public Int64 getid_modulo() { return this.id_modulo; } public String getcodigo() { return this.codigo; } public String getnombre() { return this.nombre; } public void setid_sistema(Int64 newid_sistema) { try { if(this.id_sistema!=newid_sistema) { if(newid_sistema==null) { } this.id_sistema=newid_sistema; } } catch(Exception e) { throw e; } } public void setid_modulo(Int64 newid_modulo) { try { if(this.id_modulo!=newid_modulo) { if(newid_modulo==null) { } this.id_modulo=newid_modulo; } } catch(Exception e) { throw e; } } public void setcodigo(String newcodigo) { try { if(this.codigo!=newcodigo) { if(newcodigo==null) { } if(newcodigo!=null&&newcodigo.Length>50) { newcodigo=newcodigo.Substring(0,48); //System.out.println("GrupoProceso:Ha sobrepasado el numero maximo de caracteres permitidos,Maximo=50 en columna codigo"); } this.codigo=newcodigo; } } catch(Exception e) { throw e; } } public void setnombre(String newnombre) { try { if(this.nombre!=newnombre) { if(newnombre==null) { } if(newnombre!=null&&newnombre.Length>100) { newnombre=newnombre.Substring(0,98); //System.out.println("GrupoProceso:Ha sobrepasado el numero maximo de caracteres permitidos,Maximo=100 en columna nombre"); } this.nombre=newnombre; } } catch(Exception e) { throw e; } } public List<GrupoProceso> getGruposProcesos(String sWhere,String sDataBase,String sHost,String sUser,String sPassword) { List<GrupoProceso> grupos_procesos = new List<GrupoProceso>(); //using (SqlConnection connection = new SqlConnection("Data Source=(local);Initial Catalog="+sDataBase+";Integrated Security=SSPI")) String sSql="SELECT * FROM General.GrupoProceso "+sWhere; //Trace.WriteLine(sSql); using (SqlConnection connection = new SqlConnection("Data Source="+sHost+";Initial Catalog="+sDataBase+";Integrated Security=False;Connect Timeout=30;User="+sUser+";Pwd="+sPassword+";")) using (SqlCommand cmd = new SqlCommand(sSql, connection)) { connection.Open(); using (SqlDataReader reader = cmd.ExecuteReader()) { // Check is the reader has any rows at all before starting to read. if (reader.HasRows) { // Read advances to the next row. while (reader.Read()) { GrupoProceso grupo_proceso = new GrupoProceso(); // To avoid unexpected bugs access columns by name. grupo_proceso.id = reader.GetInt64(reader.GetOrdinal("id")); grupo_proceso.id_sistema = reader.GetInt64(reader.GetOrdinal("idSistema")); grupo_proceso.id_modulo = reader.GetInt64(reader.GetOrdinal("idModulo")); grupo_proceso.codigo=reader.GetString(reader.GetOrdinal("Codigo")); grupo_proceso.nombre=reader.GetString(reader.GetOrdinal("Nombre")); grupos_procesos.Add(grupo_proceso); //int middleNameIndex = reader.GetOrdinal("MiddleName"); // If a column is nullable always check for DBNull... /* if (!reader.IsDBNull(middleNameIndex)) { p.MiddleName = reader.GetString(middleNameIndex); } */ } } } } return grupos_procesos; } }
3f7a53262502d0bce725f5583877b628522e0621
C#
shendongnian/download4
/code3/561920-13088928-31022735-2.cs
2.828125
3
// You'd probably do this once and cache it, of course... var typeMap = someAssembly.GetTypes() .ToDictionary(t => t.FullName, t => t, StringComparer.OrdinalIgnoreCase); ... Type type; if (typeMap.TryGetValue(name, out type)) { ... } else { // Type not found }
b92cc05d9e7cd80aa6caa625cc19b0c913b2298e
C#
RubMertens/CSharp-Language-Features-Demos
/NullableReferenceTypesDemos/NullableSurveyExample/Program.cs
3.09375
3
using System; using System.CodeDom.Compiler; using System.ComponentModel; using System.Data.SqlTypes; namespace NullableSurveyExample { class Program { static void Main(string[] args) { var run = new SurveyRun(); run.AddQuestion(QuestionType.YesNo, "Did you eat the cookies?"); run.AddQuestion(QuestionType.Number, "How many did you eat?"); run.AddQuestion(QuestionType.Text, "What color box was it?"); run.PerformSurvey(50); foreach (var participant in run.AllParticipants) { Console.WriteLine($"Participant: {participant.Id}"); if (participant.AnsweredSurvey) { for (var i = 0; i < run.Questions.Count; i++) { var answer = participant.Answer(i); Console.WriteLine($"\t{run.GetQuestion(i).QuestionText} : {answer}"); } } else { Console.WriteLine($"\tNo reponses"); } } } } }
b4fad261439d15e6227ccb06472c23622f6f84c7
C#
OpenMacroBoard/StreamDeckSharp
/src/StreamDeckSharp/Internals/Throttle.cs
3.03125
3
using System; using System.Diagnostics; using System.Threading; namespace StreamDeckSharp.Internals { internal class Throttle { private readonly Stopwatch stopwatch = Stopwatch.StartNew(); private long sumBytesInWindow = 0; private int sleepCount = 0; public double BytesPerSecondLimit { get; set; } = double.PositiveInfinity; public int ByteCountBeforeThrottle { get; set; } = 16_000; public void MeasureAndBlock(int bytes) { sumBytesInWindow += bytes; var elapsedSeconds = stopwatch.Elapsed.TotalSeconds; var estimatedSeconds = sumBytesInWindow / BytesPerSecondLimit; if (sumBytesInWindow > ByteCountBeforeThrottle && elapsedSeconds < estimatedSeconds) { var delta = Math.Max(1, (int)((estimatedSeconds - elapsedSeconds) * 1000)); Thread.Sleep(delta); sleepCount++; } if (elapsedSeconds >= 1) { if (sleepCount > 1) { Debug.WriteLine($"[Throttle] {sumBytesInWindow / elapsedSeconds}"); } stopwatch.Restart(); sumBytesInWindow = 0; sleepCount = 0; } } } }
daaa31dc6c997dff1263b20c3bfdf54c6117fd50
C#
matishadow/ShortestCycleDirGraph
/ShortestCycleDirGraph/Pages/HomePages/AlgAbout.xaml.cs
2.8125
3
using System.Windows.Controls; namespace ShortestCycleDirGraph.Pages.HomePages { /// <summary> /// Interaction logic for AlgAbout.xaml /// </summary> public partial class AlgAbout : UserControl { public AlgAbout() { InitializeComponent(); AlgContent.Text = "W projekcie użyliśmy zmodyfikowanego algorytmu \"przeszukiwania wszerz\". \r\n\n" + "Modyfikacja polegała na zmianie warunku przechodzenia po kolejnych wierzchołkach.\r\n\n" + "W podstawowej wersji algorytmu warunkiem przejścia do wierzchołka jest aby jego odległość była równa Inf, " + "u nas pozwalamy jeszcze na wejście do wierzchołka gdy jego odległość jest równa 0 (jest wierzchołkiem początkowym). \n\n" + "Dzięki temu odnajdujemy najkrótszą ścieżkę z zadanego wierzchołka do niego samego - czyli najkrótszy cykl dla danego wierzchołka. \n\n" + "Aby znaleźć najkrótszy cykl w całym grafie wystarczy użyć wyżej opisanego algorytmu na każdym z wierzchołków."; } } }
f0680f8f2ba640291667866dcef9d994d00996a7
C#
MohdAwad/Acc
/Acc/Persistence/SupplierBankRepo.cs
2.53125
3
using Acc.Models; using Acc.Repositories; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Acc.Persistence { public class SupplierBankRepo : ISupplierBankRepo { private readonly ApplicationDbContext _context; public SupplierBankRepo(ApplicationDbContext context) { _context = context; } public void Add(SupplierBank ObjSave) { _context.SupplierBanks.Add(ObjSave); } public void Delete(SupplierBank ObjDelete) { var ObjToDelete = _context.SupplierBanks.SingleOrDefault(m => m.CompanyID == ObjDelete.CompanyID && m.SupplierBankID == ObjDelete.SupplierBankID); if (ObjToDelete != null) { _context.SupplierBanks.Remove(ObjToDelete); } } public IEnumerable<SupplierBank> GetAllSupplierBank(int CompanyID) { return _context.SupplierBanks.Where(m => m.CompanyID == CompanyID).ToList(); } public int GetMaxSerial(int CompanyID) { var Obj = _context.SupplierBanks.FirstOrDefault(m => m.CompanyID == CompanyID); if (Obj == null) { return 1; } else { return _context.SupplierBanks.Where(m => m.CompanyID == CompanyID).Max(p => p.SupplierBankID) + 1; } } public SupplierBank GetSupplierBankByID(int CompanyID, int SupplierBankID) { return _context.SupplierBanks.FirstOrDefault(m => m.CompanyID == CompanyID && m.SupplierBankID == SupplierBankID); } public void Update(SupplierBank ObjUpdate) { var ObjToUpdate = _context.SupplierBanks.FirstOrDefault(m => m.CompanyID == ObjUpdate.CompanyID && m.SupplierBankID == ObjUpdate.SupplierBankID); if (ObjToUpdate != null) { ObjToUpdate.ArabicName = ObjUpdate.ArabicName; ObjToUpdate.EnglishName = ObjUpdate.EnglishName; ObjToUpdate.InsDateTime = ObjUpdate.InsDateTime; ObjToUpdate.InsUserID = ObjUpdate.InsUserID; } } } }
d4899e186c8cbf77d197eac2b0849ee9c894bd2a
C#
AhlamHassen/RockPaperScissors
/gameLogic/gameClass/Game.cs
2.796875
3
using System; using Newtonsoft.Json; using System.Data.SqlClient; using CompClass; using player; using System.Collections.Generic; using RoundClass; namespace gameClass { public class Game { [JsonProperty("Player")] public Player Player1 { get; set; } [JsonProperty("DateTime")] public DateTime DateTimePlayed { get; set; } [JsonProperty("GameRound")] public int GameRound { get; set; } [JsonProperty("PlayerSelections")] public List<string> PlayerSelections { get; set; } [JsonProperty("CpuSelections")] public List<string> CpuSelections { get; set; } [JsonProperty("GameResult")] public string GameResult { get; set; } public Game() { this.Player1 = null; this.DateTimePlayed = DateTime.Now; this.PlayerSelections = new List<string>(); this.CpuSelections = new List<string>(); this.GameResult = ""; } public List<Round> getGameResultAgainstCPU(PlayerSelection player) { this.Player1 = new Player(player.UserName); this.DateTimePlayed = DateTime.Now; this.PlayerSelections = player.PlayerSelections; this.GameRound = player.GameRound; var round = 1; var pSelection = 0; var CpuChoice = ""; var drawCount = 0; var playerWinCount = 0; var CpuWinCount = 0; List<Round> rounds = new List<Round>(); while(round <= this.PlayerSelections.Count){ CPU cp = new CPU(); CpuChoice = cp.generateCpuChoice(); this.CpuSelections.Add(CpuChoice); Round rnd = new Round(); rnd.UserName = this.Player1.UserName; rnd.DateTimePlayed = DateTime.Now; rnd.RoundNumber = round; rnd.PlayerChoice = this.PlayerSelections[pSelection]; rnd.CpuChoice = CpuChoice; if (rnd.PlayerChoice == CpuChoice) { drawCount++; } else { switch (rnd.PlayerChoice) { case "rock": if (CpuChoice == "paper") { CpuWinCount++; } else { playerWinCount++; } break; case "paper": if (CpuChoice == "rock") { playerWinCount++; } else { CpuWinCount++; } break; case "scissors": if (CpuChoice == "paper") { playerWinCount++; } else { CpuWinCount++; } break; } } round++; pSelection++; rounds.Add(rnd); } if(playerWinCount == CpuWinCount){ this.GameResult = "Draw"; } else if(playerWinCount > CpuWinCount){ this.GameResult = "Win"; } else{ this.GameResult = "Lose"; } return rounds; } public void addGame(Game g){ string connectionString = @"Data Source=rpsdp.ctvssf2oqpbl.us-east-1.rds.amazonaws.com; Initial Catalog=TEST;User ID=admin; Password=kereneritrea"; SqlConnection con = new SqlConnection(connectionString); string queryString = "INSERT INTO Game (userName, DateTimePlayed, GameRound, GameResult)"; queryString += "VALUES (@userName, @date, @gameRound, @gameResult)"; var letter = ""; switch (g.GameResult) { case "Win": letter = "W"; break; case "Lose": letter = "L"; break; case "Draw": letter = "D"; break; } SqlCommand command = new SqlCommand(queryString, con); command.Parameters.AddWithValue("@userName", g.Player1.UserName); command.Parameters.AddWithValue("@date", g.DateTimePlayed); command.Parameters.AddWithValue("@gameRound", (int)g.GameRound); command.Parameters.AddWithValue("@gameResult", letter); con.Open(); command.ExecuteNonQuery(); con.Close(); } } }
59c00a843d5b13136b28ba1d6a2478ede78d8681
C#
vvolkgang/WarZ
/src/WarZ/WarZ/3D/Players/Ai/AiPlayerManager.cs
2.59375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Input; namespace WarZ { sealed class AiPlayerManager : Microsoft.Xna.Framework.DrawableGameComponent { private const int MAX_AI = 15; private List<AiPlayer> _aiPlayers; private int idCount = 0; private WarZGame WZGame; private Tank _defaultTank; private bool enableAll = true; public AiPlayerManager(WarZGame game, Tank tank) : base(game) { _aiPlayers = new List<AiPlayer>(MAX_AI); this.WZGame = game; _defaultTank = tank; } public List<AiPlayer> AiPlayers { get { return _aiPlayers; } } #region Inherited Methods public override void Update(GameTime gameTime) { HandleInput(gameTime); if (enableAll) { foreach (AiPlayer player in AiPlayers) { player.Update(gameTime); } } base.Update(gameTime); } public override void Draw(Microsoft.Xna.Framework.GameTime gameTime) { foreach (AiPlayer player in AiPlayers) { player.Draw(gameTime); } base.Draw(gameTime); } #endregion #region Class methods public void HandleInput(GameTime gameTime) { if (KeyboardHelper.IsKeyPressed(Keys.E)) enableAll = !enableAll; } public void AddBot(Camera camera) { AddBot(camera, Vector3.Forward * Vector3.Right); } public void AddBot(Camera camera, Vector3 Position) { AiPlayer newAi = new AiPlayer(WZGame, camera, _defaultTank, WZGame.Terrain, idCount++) { Position = Position }; //newAi.AddBehavior(new ChaseBehavior(WZGame, newAi, WZGame.Player1)); newAi.AddBehavior(new GoingForwardBehavior(WZGame, newAi)); //newAi.AddBehavior(new WanderBehavior(WZGame, newAi)); AiPlayers.Add(newAi); } public void AddBots(Camera camera, int number) { for (int i = 0; i < number; i++) { AddBot(camera); } } #endregion } }
9beafa3b9feb8494bf11bb10d1d8ca31de555aab
C#
burakexe/Simple-Movie-DB
/MovieDBFirst_WinUi/Form1.cs
2.59375
3
using MovieDBFirst_BLL.BaseRepository; using MovieDBFirst_DAL; using System; using System.Windows.Forms; namespace MovieDBFirst_WinUi { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private BaseRepository<Genre> genreService = new BaseRepository<Genre>(); private BaseRepository<Saloon> saloonService = new BaseRepository<Saloon>(); private BaseRepository<Session> sessionService = new BaseRepository<Session>(); private BaseRepository<Movy> movieService = new BaseRepository<Movy>(); private BaseRepository<Theater> theaterService = new BaseRepository<Theater>(); private BaseRepository<Director> directorService = new BaseRepository<Director>(); private void Form1_Load(object sender, EventArgs e) { GenreLoad(); SaloonLoad(); SessionLoad(); DirectorLoad(); GetAll(); IDHide(); } // Used Methods // private void IDHide() { dgGenre.Columns[0].Visible = false; dgSaloon.Columns[0].Visible = false; dgSessions.Columns[0].Visible = false; dgDirectors.Columns[0].Visible = false; } private void GenreLoad() { cmbGenre.DisplayMember = "Name"; cmbGenre.ValueMember = "GenreID"; cmbGenre.DataSource = genreService.SelectAll(); dgGenre.DataSource = genreService.SelectAll(); } private void SaloonLoad() { cmbSaloon.DisplayMember = "Name"; cmbSaloon.ValueMember = "SaloonID"; cmbSaloon.DataSource = saloonService.SelectAll(); dgSaloon.DataSource = saloonService.SelectAll(); } private void SessionLoad() { cmbSession.DisplayMember = "Sessions"; cmbSession.ValueMember = "SessionID"; cmbSession.DataSource = sessionService.SelectAll(); dgSessions.DataSource = sessionService.SelectAll(); } private void DirectorLoad() { cmbDirectors.DisplayMember = "DirectorName"; cmbDirectors.ValueMember = "DirectorID"; cmbDirectors.DataSource = directorService.SelectAll(); dgDirectors.DataSource = directorService.SelectAll(); } private void GetAll() { dgTheaters.DataSource = theaterService.SelectAll(); } // Genre Actions // private void AddGenre_Click(object sender, EventArgs e) { Genre genre = new Genre(); genre.Name = txtAddGenre.Text; genreService.Add(genre); ListViewItem lvi = new ListViewItem(); lvi.Text = genre.GenreID.ToString(); lvi.SubItems.Add(genre.Name); MessageBox.Show("" +genre.Name+ " movie type is added to list."); txtAddGenre.Text = ""; dgGenre.DataSource = genreService.SelectAll(); } private void AddSaloon_Click(object sender, EventArgs e) { Saloon saloon = new Saloon(); saloon.Name = txtSaloonName.Text; saloon.Capacity = Convert.ToInt32(txtSaloonCap.Text); saloonService.Add(saloon); txtSaloonCap.Text = ""; txtSaloonName.Text = ""; dgSaloon.DataSource = saloonService.SelectAll(); MessageBox.Show(saloon.Name + " Saloon is added with " + saloon.Capacity + " capacity."); } private void btnAddSession_Click(object sender, EventArgs e) { Session session = new Session(); session.Sessions = txtSessionAdd.Text; sessionService.Add(session); txtSessionAdd.Text = ""; MessageBox.Show("Session : " +session.Sessions.ToString()+ " is added"); dgSessions.DataSource = sessionService.SelectAll(); } private void btnAddMovie_Click(object sender, EventArgs e) { Movy movie = new Movy(); movie.Name = txtMovieName.Text; movie.Description = txtDescription.Text; movie.Duration = Convert.ToInt32(txtDuration.Text); movieService.Add(movie); dgTheaters.DataSource = movieService.SelectAll(); } // Directors Section // private void btnAddDirector_Click(object sender, EventArgs e) { Director dr = new Director(); dr.DirectorName = txtDirectorName.Text; dr.DirectorSurname = txtDirectorSurname.Text; directorService.Add(dr); txtDirectorName.Text = ""; txtDirectorSurname.Text = ""; dgDirectors.DataSource = directorService.SelectAll(); MessageBox.Show("Director : "+ dr.DirectorName + " " + dr.DirectorSurname + " is added"); } private void btnSaloonDelete_Click(object sender, EventArgs e) { if (dgSaloon.SelectedRows.Count>0) { int id = Convert.ToInt32(dgSaloon.CurrentRow.Cells[0].Value); saloonService.Delete(id); MessageBox.Show("Selected Saloon deleted"); SaloonLoad(); } else { MessageBox.Show("Please Select a row"); } } private void btnSessionDelete_Click(object sender, EventArgs e) { if (dgSessions.SelectedRows.Count > 0) { int id = Convert.ToInt32(dgSessions.CurrentRow.Cells[0].Value); sessionService.Delete(id); MessageBox.Show("Selected Session deleted"); SessionLoad(); } else { MessageBox.Show("Please Select a row"); } } private void btnDeleteDirector_Click(object sender, EventArgs e) { if (dgDirectors.SelectedRows.Count > 0) { int id = Convert.ToInt32(dgDirectors.CurrentRow.Cells[0].Value); directorService.Delete(id); MessageBox.Show("Selected Director deleted"); DirectorLoad(); } else { MessageBox.Show("Please Select a row"); } } private void btnDeleteGenre_Click(object sender, EventArgs e) { if (dgGenre.SelectedRows.Count > 0) { int id = Convert.ToInt32(dgGenre.CurrentRow.Cells[0].Value); genreService.Delete(id); MessageBox.Show("Selected Genre Type deleted"); GenreLoad(); } else { MessageBox.Show("Please Select a row"); } } private void btnExit_Click(object sender, EventArgs e) { if (MessageBox.Show("This will close down the whole application. Confirm?", "Close Application", MessageBoxButtons.YesNo) == DialogResult.Yes) { MessageBox.Show("The application has been closed successfully.", "Application Closed!", MessageBoxButtons.OK); System.Windows.Forms.Application.Exit(); } else { this.Activate(); } } } }
e4adafcbda5d0303800a6952578e34fc42979089
C#
shendongnian/download4
/first_version_download2/610337-59942045-213795177-4.cs
2.734375
3
public bool Save_Item_Drop(string Email, string value, string column) { try { SqlConnection SQLConn = new SqlConnection(cn); SqlCommand cmd = new SqlCommand("spHere", SQLConn); bool Success; cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Email", Email); cmd.Parameters.AddWithValue("@Value", value); cmd.Parameters.AddWithValue("@Column", column); SQLConn.Open(); Success = Convert.ToBoolean(cmd.ExecuteScalar()); SQLConn.Close(); return Success; } catch (Exception ex) { string _Product = "White Box Gaming API"; dynamic _Method = Convert.ToString(System.Reflection.MethodBase.GetCurrentMethod().Name); dynamic _Class = Convert.ToString(this.GetType().Name); string _Exception = Convert.ToString(ex.ToString()); Log_Product_Exception(_Product, _Class, _Method, _Exception); return false; } }
adce44c614512d22eef0f7eee89d0450b34b6a0f
C#
dotrungduchd/LUANVAN
/Duc/ActiveDomain/ActiveDomain/AuthUser.cs
2.59375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ActiveDomain { /// <summary> /// This class authenticate user by id+password or domain+username /// </summary> public class AuthUser { public static bool Authenticate(AuthType authType) { switch (authType) { case AuthType.IDPassword: break; case AuthType.DomainName: break; default: return false; } return false; } } public enum AuthType : int { IDPassword = 0, DomainName = 1 } public enum FilePermit : int { OnlyMe = 0, AllUserInDomain = 1, OnlySomeUserInDomain = 2 } }
134f9cfc2dd8ba008fa72beed4f3b15fe21c53ee
C#
sotnyk/gabook
/BookSamples/NukeGA/NukeGA/BitmapUtils.cs
3.484375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Drawing; using System.Drawing.Imaging; namespace NukeGA { public static class BitmapUtils { /// <summary> /// Метод конвертирует объект Bitmap в одномерный массив цветовых компонент R, G, B. /// Размеры массива соответствуют количеству точек в исходном изображении, умноженному на 3. /// Первой идет серия яркостей компоненты R, затем - G, последней - B. Внутри серии /// нумерация точек сквозная, построчная, сверху вниз (а в каждой строке - слева направо). /// </summary> /// <param name="bmp">Экземпляр Bitmap.</param> /// <param name="width">Ширина изображения.</param> /// <param name="height">Высота изображения.</param> /// <returns>Одномерный массив значений компонент.</returns> public unsafe static byte[] BitmapToByteRGB1D(Bitmap bmp, out int width, out int height) { width = bmp.Width; height = bmp.Height; byte[] rgb = new byte[3 * height * width]; BitmapData bd = bmp.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb); try { byte* curpos = (byte*)bd.Scan0; int rPos = 0, gPos = width * height, bPos = 2 * width * height; for (int h = 0; h < height; h++) { curpos = ((byte*)bd.Scan0) + h * bd.Stride; for (int w = 0; w < width; w++) { rgb[bPos++] = *(curpos++); rgb[gPos++] = *(curpos++); rgb[rPos++] = *(curpos++); } } } finally { bmp.UnlockBits(bd); } return rgb; } /// <summary> /// Метод предназначен для создания нового экземпляра класса Bitmap на /// базе имеющейся в виде float[]-массива информацией о яркости каждого пиксела. /// Размеры массива соответствуют количеству точек в исходном изображении, умноженному на 3. /// Первой идет серия яркостей компоненты R, затем - G, последней - B. Внутри серии /// нумерация точек сквозная, построчная, сверху вниз (а в каждой строке - слева направо). /// </summary> /// <param name="rgb">Float массив с данными о яркости каждой компоненты /// каждого пиксела</param> /// <param name="width">Ширина изображения.</param> /// <param name="height">Высота изображения.</param> /// <returns>Новый экземпляр класса Bitmap</returns> public unsafe static Bitmap RGBToBitmap(byte[] rgb, int width, int height) { if (rgb.Length != 3 * width * height) { throw new ArrayTypeMismatchException("Size of passed array must be 3*width*height"); } Bitmap result = new Bitmap(width, height, PixelFormat.Format24bppRgb); BitmapData bd = result.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb); try { byte* curpos = (byte*)bd.Scan0; int rPos = 0, gPos = width * height, bPos = 2 * width * height; for (int h = 0; h < height; h++) { curpos = ((byte*)bd.Scan0) + h * bd.Stride; for (int w = 0; w < width; w++) { *(curpos++) = rgb[bPos++]; *(curpos++) = rgb[gPos++]; *(curpos++) = rgb[rPos++]; } } } finally { result.UnlockBits(bd); } return result; } /// <summary> /// Метод подсчитывает количество черных точек в переданном /// экземпляре Bitmap. /// </summary> /// <param name="bitmap"></param> /// <returns></returns> public static int CalcBlackPoints(Bitmap bitmap) { int result = 0; int w, h; byte[] currentAsBytes = BitmapUtils.BitmapToByteRGB1D(bitmap, out w, out h); int shift = w * h; for (int r = 0, g = shift, b = shift * 2; r < shift; ++r, ++g, ++b) if (currentAsBytes[r] + currentAsBytes[g] + currentAsBytes[b] == 0) result++; return result; } } }
d9c9757ab264a4357ea01f66e001096ed1246673
C#
LaudableBauble/Bedlam
/Game/ContentPipelineExtension/ContentTypes/BoneContent.cs
2.71875
3
using System.Xml; using System.Collections.Generic; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Content.Pipeline; using Microsoft.Xna.Framework.Content.Pipeline.Graphics; namespace ContentPipelineExtension { /// <summary> /// A bone content instance keeps track of all the important information of a bone and can be transformed back into /// a boe whenever the crave can't be staved off any longer. /// </summary> [ContentSerializerRuntimeType("Library.Animate.Bone, Library")] public class BoneContent { #region Properties /// <summary> /// The name of this bone. /// </summary> public string Name { get; set; } /// <summary> /// The index of this bone. /// </summary> public int Index { get; set; } /// <summary> /// The index of this bone's parent. /// </summary> public int ParentIndex { get; set; } /// <summary> /// The position. /// </summary> public Vector2 Position { get; set; } /// <summary> /// The rotation. /// </summary> public float Rotation { get; set; } /// <summary> /// The bone's scale. /// </summary> public Vector2 Scale { get; set; } /// <summary> /// The length of the bone. /// </summary> public float Length { get; set; } #endregion #region Constructor /// <summary> /// Create the bone content. /// </summary> /// <param name="node">The xml node to get the information from.</param> /// <param name="context">The content importer context.</param> public BoneContent(XmlNode node, ContentImporterContext context) { //Parse the xml data. Name = node.Attributes["Name"].Value; Index = int.Parse(node.SelectSingleNode("Index").InnerText); ParentIndex = int.Parse(node.SelectSingleNode("ParentIndex").InnerText); Position = new Vector2(float.Parse(node.SelectSingleNode("Position/X").InnerText), float.Parse(node.SelectSingleNode("Position/Y").InnerText)); Rotation = float.Parse(node.SelectSingleNode("Rotation").InnerText); Scale = new Vector2(float.Parse(node.SelectSingleNode("Scale/X").InnerText), float.Parse(node.SelectSingleNode("Scale/Y").InnerText)); Length = float.Parse(node.SelectSingleNode("Length").InnerText); } #endregion } }
9e5f2b4e39a8117bba4fcae8ba107aa778edb0bc
C#
KamenYu/Csharp-Advanced
/DefiningClassesEX/5.CarSalesman/Program.cs
3.6875
4
using System; using System.Collections.Generic; using System.Linq; namespace _5.CarSalesman { class Program { static void Main(string[] args) { int n = int.Parse(Console.ReadLine()); List<Engine> engines = new List<Engine>(); // "{model} {power} {displacement} {efficiency}" // stirng int int string for (int i = 0; i < n; i++) { Engine currEngine = new Engine(); string[] engineInfo = Console.ReadLine().Split(' ', StringSplitOptions.RemoveEmptyEntries); currEngine.Model = engineInfo[0]; currEngine.Power = int.Parse(engineInfo[1]); if (engineInfo.Length == 2) { engines.Add(currEngine); } else if (engineInfo.Length == 3) { int displacement = 0; if (int.TryParse(engineInfo[2], out displacement)) { currEngine.Displacement = engineInfo[2]; engines.Add(currEngine); } else { currEngine.Efficiency = engineInfo[2]; engines.Add(currEngine); } } else if (engineInfo.Length == 4) { currEngine.Displacement = engineInfo[2]; currEngine.Efficiency = engineInfo[3]; engines.Add(currEngine); } } int m = int.Parse(Console.ReadLine()); List<Car> cars = new List<Car>(); // "{model} {engine} {weight} {colour}" // string string int string for (int i = 0; i < m; i++) { Car currentCar = new Car(); string[] carInfo = Console.ReadLine().Split(' ', StringSplitOptions.RemoveEmptyEntries); currentCar.Model = carInfo[0]; currentCar.Engine = engines.Where(x => x.Model == carInfo[1]).FirstOrDefault(); if (carInfo.Length == 2) { cars.Add(currentCar); } else if (carInfo.Length == 3) { int weight = 0; if (int.TryParse(carInfo[2], out weight)) { currentCar.Weight = carInfo[2]; cars.Add(currentCar); } else { currentCar.Colour = carInfo[2]; cars.Add(currentCar); } } else if (carInfo.Length == 4) { currentCar.Weight = carInfo[2]; currentCar.Colour = carInfo[3]; cars.Add(currentCar); } } foreach (var item in cars) { Console.WriteLine($"{item.Model}:"); Console.WriteLine($" {item.Engine.Model}:"); Console.WriteLine($" Power: {item.Engine.Power}"); Console.WriteLine($" Displacement: {item.Engine.Displacement}"); Console.WriteLine($" Efficiency: {item.Engine.Efficiency}"); Console.WriteLine($" Weight: {item.Weight}"); Console.WriteLine($" Color: {item.Colour}"); } } } }
1ac68a7d6db5ad141804b524dd3dec025569ad73
C#
RobertRisley/RWR.IssueTracker
/RWR.IssueTracker.DSBO/TasksTD.cs
2.515625
3
using System; using System.Data; using System.Data.SqlClient; using System.Windows.Forms; using RWR.Common; using TasksTableAdapter = RWR.IssueTracker.DSBO.TasksTDTableAdapters.TasksTableAdapter; namespace RWR.IssueTracker.DSBO { /// <summary> /// The Tasks Table DataSet BusinessObject. /// </summary> partial class TasksTD { /// <summary> /// Get all Tasks /// </summary> /// <returns>A TasksTD</returns> public static DataSet GetTasks() { TasksTD td = new TasksTD(); TasksTableAdapter ta = new TasksTableAdapter(); ta.Fill(td.Tasks); ta.Dispose(); return td; } /// <summary> /// Get Task row by TaskId /// </summary> /// <returns>A TasksDataTable with one row if TaskId exists</returns> public static DataTable GetTask(int taskId) { if (taskId == 0) throw new Exception("The TaskId is zero."); TasksTableAdapter ta = new TasksTableAdapter(); TasksDataTable tt = ta.GetDataByTaskId(taskId); ta.Dispose(); return tt; } /// <summary> /// Returns true or false if a Tasks exists /// </summary> /// <param name="taskId">The TaskId to check existance</param> /// <returns>true if Tasks exists, false if not</returns> public static bool IsExistingTask(int taskId) { if (taskId == 0) throw new Exception("The TaskId cannot be zero."); TasksTableAdapter ta = new TasksTableAdapter(); bool isExistingTask = (ta.IsExistingTask(taskId) == 1 ? true : false); ta.Dispose(); return isExistingTask; } /// <summary> /// Service callable code to Delete/Insert/Update Tasks /// </summary> /// <returns>A TasksTD. If ALL updated OK contains updated data, if not contains the RowErrors</returns> public static DataSet UpdateTasks(DataSet tasksDataSet, ref SqlTransaction transaction) { if (tasksDataSet == null || tasksDataSet.Tables["Tasks"] == null || tasksDataSet.Tables["Tasks"].Rows.Count == 0) throw new Exception("The DataSet and/or DataTable is null or empty."); TasksDataTable dtTasks = new TasksDataTable(); dtTasks.BeginLoadData(); dtTasks.Merge(tasksDataSet.Tables["Tasks"], false, MissingSchemaAction.Error); TasksTableAdapter taTasks = new TasksTableAdapter(); TableAdapterUtils.UseTransaction(taTasks, ref transaction); #region do deletes foreach (TasksRow deletedRow in dtTasks.Select("", "", DataViewRowState.Deleted)) { // get the primary key value(s) from the Original version (for child deletes) int taskId = (int)deletedRow["TaskId", DataRowVersion.Original]; // do child deletes (if any exist) //TasksChildrenDataSet.UpdateTasksChildren // delete the row taTasks.Delete(taskId); } #endregion #region do inserts foreach (TasksRow insertedRow in dtTasks.Select("", "", DataViewRowState.Added)) { //insertedRow["SubmitDt"] = DBNull.Value; // for testing SetDefaultValues insertedRow.SetDefaultValues(); if (insertedRow.IsValidRow()) taTasks.Update(insertedRow); else throw new Exception("A row to be inserted contains invalid data. Entire transaction cancelled."); } #endregion #region do updates foreach (TasksRow modifiedRow in dtTasks.Select("", "", DataViewRowState.ModifiedCurrent)) { // get the primary key value(s) from the Original version int taskId = (int)modifiedRow["TaskId", DataRowVersion.Original]; // do not allow key changes int taskIdCurr = (int)modifiedRow["TaskId", DataRowVersion.Current]; if (taskId != taskIdCurr) throw new Exception("Change of primary key(s) is not permitted. Entire transaction cancelled."); if (modifiedRow.IsValidRow()) taTasks.Update(modifiedRow); else throw new Exception("A row to be modified contains invalid data. Entire transaction cancelled."); } #endregion dtTasks.AcceptChanges(); tasksDataSet.Tables["Tasks"].Merge(dtTasks, false, MissingSchemaAction.Ignore); return tasksDataSet; } /// <summary> /// <para>Validate all of the column values in a DataRow.</para> /// <para>The RowError text is set and HasErrors property is true if exists RowError text.</para> /// </summary> /// <param name="row">the DataRow to be validated</param> /// <param name="cols">the DataColumnCollection to iterate through</param> public static void CheckTableRow(DataRow row, DataColumnCollection cols) { try { foreach (DataColumn col in cols) switch (col.ColumnName) { // TODO: code case for each column to be validated case "PrioritySequence": row.RowError += CheckPrioritySequence(row[col].ToString()); break; } } catch { row.RowError = "OOPS! ERROR checking DataRow!"; } } /// <summary> /// Validity-check the PrioritySequence value. /// </summary> /// <param name="value"></param> /// <returns>Error Text.</returns> public static string CheckPrioritySequence(string value) { string errorText = string.Empty; int seq; if (int.TryParse(value, out seq) == false) errorText = " SubPriority must be a number"; else if (seq < 0 || seq > 25) errorText = " SubPriority must be between 0 and 25"; return errorText; } /// <summary> /// Call this from the DataGridView.CellValidating event /// </summary> /// <param name="sender">The sender object (DataGridView) from CellValidatingEvent</param> /// <param name="e">The e DataGridViewCellValidatingEventArgs from CellValidatingEvent</param> public static void CheckGridColumn(object sender, DataGridViewCellValidatingEventArgs e) { DataGridView grid = (DataGridView)sender; //grid.CurrentCell.ErrorText = ""; try { switch (grid.Columns[e.ColumnIndex].Name) { case "PrioritySequence": grid.Rows[e.RowIndex].ErrorText = CheckPrioritySequence(e.FormattedValue as String); break; } if (grid.Rows[e.RowIndex].ErrorText != string.Empty) e.Cancel = true; } catch { grid.CurrentCell.ErrorText = "OOPS! ERROR!"; e.Cancel = true; } } /// <summary> /// A Tasks row. /// </summary> public partial class TasksRow { /// <summary> /// Set value for columns == DBNull to their DefaultValue (if DefaultValue specified in XSD) /// </summary> public void SetDefaultValues() { DataRowUtils.SetDefaultValues(this, Table.Columns); } /// <summary> /// Validates the current TasksRow /// </summary> /// <returns>The row is valid</returns> public bool IsValidRow() { CheckTableRow(this, Table.Columns); return !HasErrors; } } #region Authorization Rules /// <summary> /// /// </summary> public void AddAuthorizationRules() { //AuthorizationRules.AllowWrite( // "Name", "ProjectManager"); //AuthorizationRules.AllowWrite( // "Started", "ProjectManager"); //AuthorizationRules.AllowWrite( // "Ended", "ProjectManager"); //AuthorizationRules.AllowWrite( // "Description", "ProjectManager"); } /// <summary> /// /// </summary> /// <returns></returns> public static bool CanAddObject() { return true; //return Csla.ApplicationContext.User.IsInRole( // "ProjectManager"); } /// <summary> /// /// </summary> /// <returns></returns> public static bool CanGetObject() { return true; } /// <summary> /// /// </summary> /// <returns></returns> public static bool CanDeleteObject() { return true; //bool result = false; //if (Csla.ApplicationContext.User.IsInRole( // "ProjectManager")) // result = true; //if (Csla.ApplicationContext.User.IsInRole( // "Administrator")) // result = true; //return result; } /// <summary> /// /// </summary> /// <returns></returns> public static bool CanEditObject() { return true; //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); } #endregion } }
f9f7301133320b08f61e9d87544790164c6a0086
C#
creativedisplacement/library
/Library.Application/People/Queries/GetPerson/GetPersonQueryHandler.cs
2.671875
3
using Library.Application.Exceptions; using Library.Common.Models.Person; using Library.Domain.Entities; using Library.Persistence; using MediatR; using Microsoft.EntityFrameworkCore; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace Library.Application.People.Queries.GetPerson { public class GetPersonQueryHandler : IRequestHandler<GetPersonQuery, GetPersonModel> { private readonly LibraryDbContext _context; public GetPersonQueryHandler(LibraryDbContext context) { _context = context; } public async Task<GetPersonModel> Handle(GetPersonQuery request, CancellationToken cancellationToken) { var person = await _context.Persons .Include(i => i.Books) .SingleOrDefaultAsync(c => c.Id == request.Id, cancellationToken); if (person == null) { throw new NotFoundException(nameof(Person), request.Id); } return new GetPersonModel { Id = person.Id, Name = person.Name, Email = person.Email, IsAdmin = person.IsAdmin, Books = person.Books.Select(b => new GetPersonBookModel { Id = b.Id }).ToList() }; } } }
3825b9d83eebfa3887517a436a3cdb0c9901e015
C#
yuns-emre/ReCapProject
/Business/ValidationRules/FluentValidation/ColorValidator.cs
2.65625
3
using Entities.Concrete; using FluentValidation; using System; using System.Collections.Generic; using System.Text; namespace Business.ValidationRules.FluentValidation { public class ColorValidator : AbstractValidator<Color> { public ColorValidator() { RuleFor(c=>c.ColorName).NotEmpty(); RuleFor(c => c.ColorName).MinimumLength(3).WithMessage("Renk adı uzunluğu en az 3 karakter olmalı."); } } }
f653a65a01fcc196d106289807e87fb45bccb5c2
C#
skkushev/TelerikAcademy
/10.NumeralSystems/07.OneSystemToAnyOther/OneSystemToAnyOther.cs
3.984375
4
/* Problem 7. One system to any other• Write a program to convert from any numeral system of given base s to any other numeral system of base d (2 ≤ s , d ≤ 16). */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; class OneSystemToAnyOther { static void Main() { Console.Write("Please, enter numeral system you want to convert (2<= s <=16): "); int s = int.Parse(Console.ReadLine()); Console.Write("Please, enter number: "); string number = Console.ReadLine(); Console.Write("Please, enter numeral systerm you to convert to (2<= d <=16): "); int d = int.Parse(Console.ReadLine()); long decimalRepresantation = Convert.ToInt64(number, s); if (d == 10) { Console.WriteLine(decimalRepresantation); } else { string converted = ConvertNumber(decimalRepresantation, d); Console.WriteLine(converted); } } private static string ConvertNumber(long number, int endSystem) { StringBuilder result = new StringBuilder(); long remainder = 0; while (number > 0) { remainder = number % endSystem; result.Insert(0, SwitchRemainder(remainder)); number /= endSystem; } return result.ToString(); } private static string SwitchRemainder(long remainder) { switch (remainder) { case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8: case 9: return remainder.ToString(); case 10: return "A"; case 11: return "B"; case 12: return "C"; case 13: return "D"; case 14: return "E"; case 15: return "F"; default: throw new ArgumentOutOfRangeException("Invalid numeral system!"); } } }
b83b1de56c019f30ec7acb80caa0b70f1783806b
C#
Andrey-prog936/Csharp-DZ-7
/Csahrp 5.1/Program.cs
3.296875
3
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Csahrp_5._1 { abstract class Creature { public string Name { get; set; } public override string ToString() { return $"Name: {Name}\n"; } } abstract class Animal : Creature { public double weight { get; set; } public override string ToString() { return base.ToString() + $"Weight: {weight}"; } } class Fish : Animal, ISwimable { bool isSwiming = true; public bool IsSwiming { get { return isSwiming; } set { isSwiming = value; } } public string Swiming() { return "Swim....."; } public string Eat() { return "Eat...."; } } class Bird : Animal, IFlyable { bool isFly = true; public bool IsFly { get { return isFly; } set { isFly = value; } } public string Fly() { return "Fly....."; } public string Eat() { return "Eat...."; } } class Mammal : Animal, IRunable { bool isRun = true; public bool IsRun { get { return isRun; } set { isRun = value; } } public string Run() { return "Run....."; } public string Eat() { return "Eat...."; } } class Reptile : Animal, ICrowable { bool isCrowl = true; public bool IsCrowl { get { return isCrowl; } } public string Crowl() { return "Crowl....."; } public string Eat() { return "Eat...."; } } interface IRunable { bool IsRun { get; set; } string Run(); string Eat(); } interface ICrowable { bool IsCrowl { get; } string Crowl(); string Eat(); } interface IFlyable { bool IsFly { get; set; } string Fly(); string Eat(); } interface ISwimable { bool IsSwiming { get; set; } string Swiming(); string Eat(); } class Bear : Mammal, IRunable { public void Stop() { IsRun = false; } public void Say() { Console.WriteLine("Rrrrrrrrrrrrrrrr r r r rrrrrrr\n"); } } class Dolphin : Mammal, ISwimable { bool isSwiming = true; public bool IsSwiming { get { return isSwiming; } set { isSwiming = value; } } public void Say() { Console.WriteLine("....\n"); } public string Swiming() { return "Swim....."; } void EmergeJump() { Console.WriteLine("Jump out of the water"); } } class Carp : Fish, ISwimable { public void Stop() { IsSwiming = false; } public void Say() { Console.WriteLine("Bul-bullll\n"); } } class Eagle : Bird, IFlyable { public void ToLand() { Console.WriteLine("Landing...."); IsFly = false; } public void Say() { Console.WriteLine("....\n"); } } class Program { static void Main(string[] args) { Bear b = new Bear() { Name = "Balu", weight = 190 }; Console.WriteLine(b.ToString()); b.Say(); } } }
f35bb95dc5cc423055c5b6a71fb36cc9be538f34
C#
codesdog/CCCTest
/ZYWSunriseHotel/db.cs
2.96875
3
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Data.OleDb; namespace 东方日出大酒店 { class db { /// <summary> /// 数据库连接 /// </summary> private static string conicution { get { string C_conn = "Provider = Microsoft.ACE.OLEDB.12.0; Data Source =" + Application.StartupPath + "\\mydata.accdb"; return C_conn; } } /// <summary> /// 添加,删除,修改 /// </summary> /// <param name="sql"></param> /// <returns></returns> public static int My_sql(string sql) { OleDbConnection conn=null; try { string str = conicution; conn = new OleDbConnection(str); conn.Open(); OleDbCommand db = new OleDbCommand(sql, conn); db.ExecuteNonQuery(); return 1; } catch { return -1; } finally { conn.Close(); conn.Dispose(); } } /// <summary> /// 返回要显示的一张数据表 /// </summary> /// <param name="sql"></param> /// <returns></returns> public static DataTable tables(string sql) { OleDbConnection conn = null; try { string str = conicution; conn = new OleDbConnection(str); conn.Open(); OleDbDataAdapter mydb = new OleDbDataAdapter(sql, conn); DataTable dt = new DataTable(); mydb.Fill(dt); return dt; } catch (Exception e) { throw new Exception(e.Message, e); } finally { conn.Close(); conn.Dispose(); } } /// <summary> /// 从左截取串 scatitle 的 cid个字符 /// </summary> /// <param name="scatitle"></param> /// <param name="cid"></param> /// <returns></returns> public static string getleft(string scatitle, int cid) { string rtn = ""; if (scatitle.Trim().Length > cid) { rtn = scatitle.Substring(0, cid) + "..."; } else { rtn = scatitle; } return rtn; } /// <summary> /// 过滤非法字符 /// </summary> /// <param name="inputStr"></param> /// <returns></returns> public static string cutBadStr(string inputStr) { inputStr = inputStr.ToLower().Replace(",", ""); inputStr = inputStr.ToLower().Replace("<", ""); inputStr = inputStr.ToLower().Replace(">", ""); inputStr = inputStr.ToLower().Replace("%", ""); inputStr = inputStr.ToLower().Replace(".", ""); inputStr = inputStr.ToLower().Replace(":", ""); inputStr = inputStr.ToLower().Replace("#", ""); inputStr = inputStr.ToLower().Replace("&", ""); inputStr = inputStr.ToLower().Replace("$", ""); inputStr = inputStr.ToLower().Replace("^", ""); inputStr = inputStr.ToLower().Replace("*", ""); inputStr = inputStr.ToLower().Replace("`", ""); inputStr = inputStr.ToLower().Replace(" ", ""); inputStr = inputStr.ToLower().Replace("~", ""); inputStr = inputStr.ToLower().Replace("or", ""); inputStr = inputStr.ToLower().Replace("and", ""); inputStr = inputStr.ToLower().Replace("'", ""); return inputStr; } /// <summary> /// 说明:留言时按照标准形式显示留言格式;即格式化文本 /// </summary> /// <param name="str"></param> /// <returns></returns> public static string FormatString(string str) { str = str.Replace(" ", "&nbsp;&nbsp"); str = str.Replace("<", "&lt;"); str = str.Replace(">", "&glt;"); str = str.Replace('\n'.ToString(), "<br>"); return str; } /// <summary> /// 判断是否为数字 /// </summary> /// <param name="myObj">传递的参数</param> /// <returns>返回真假值</returns> public static bool isNumber(Object myObj) { try { int i = Convert.ToInt32(myObj); return (true); } catch { return (false); } } } }
1087907c141ee47e0982870d3415a931b2532c63
C#
ZoyuJ/CusCSV
/CusCSV.Shared/CSVField.cs
2.90625
3
namespace CusCSV { using CusCSV.Exceptions; using KatKits; using System; using System.Text; public class CSVField { internal CSVField() { } internal CSVField(CSVColumn Column) { this.Column = Column; } public CSVField(CSVTable Table, CSVRow Row, CSVColumn Column) { this.Table = Table; this.Row = Row; this.Column = Column; } public readonly CSVTable Table; public readonly CSVRow Row; public readonly CSVColumn Column; public string Text { get; set; } /// <summary> /// /// </summary> /// <param name="Char1"></param> /// <param name="Escaped"></param> /// <param name="StrBd"></param> /// <returns>0:need nore char,1:create new field,2:create new line</returns> internal CSVReaderStatus NextChar(int Char1, ref bool Escaped, ref StringBuilder StrBd) { switch (CSVExpress. CharByChar(Char1,ref Escaped,ref StrBd)) { case CSVReaderStatus.MoreChar: default: return CSVReaderStatus.MoreChar; case CSVReaderStatus.NewField: Text = StrBd.ToString(); StrBd.Clear(); return CSVReaderStatus.NewField; case CSVReaderStatus.NewRow: Text = StrBd.ToString(); StrBd.Clear(); return CSVReaderStatus.NewRow; case CSVReaderStatus.EndOfText: Text = StrBd.ToString(); StrBd.Clear(); return CSVReaderStatus.EndOfText; } } public void Set(object Obj) { if (Obj.GetType().IsBasicDataType()) { } } public object Get() { if (Column.DataType == null) throw new CSVFieldWithUnknowDataTypeException(Column.Text, Text); if (Column.DataType.Equals(typeof(string))) return Text; if (string.IsNullOrEmpty(Text)) return null; Type Target = Column.DataType; if (Column.DataType.IsNullableType()) { Target = Nullable.GetUnderlyingType(Column.DataType); } else if (Column.DataType.IsEnum) { return Enum.Parse(Column.DataType, Text); } if (Target.IsPrimitive) { return Convert.ChangeType(Text, Target); } else { if (Target.Equals(typeof(decimal))) return decimal.Parse(Text); else if (Target.Equals(typeof(DateTime))) return DateTime.Parse(Text); else if (Target.Equals(typeof(Guid))) return Guid.Parse(Text); else if (Target.Equals(typeof(TimeSpan))) return TimeSpan.Parse(Text); else if (Target.Equals(typeof(DateTimeOffset))) return DateTimeOffset.Parse(Text); } return null; } public T GetValue<T>() { return (T)Get(); } public override string ToString() => Text; public string ToCSVString() { StringBuilder StrBd = new StringBuilder(Text); bool HasToEnclosed = false; for (int i = StrBd.Length - 1; i >= 0; i--) { if (StrBd[i] == '\"') { StrBd.Insert(i, '\"'); HasToEnclosed = true; } else { if (!HasToEnclosed && ( StrBd[i] == ',' || (StrBd[i] == '\n' && i > 0 && StrBd[i - 1] == '\r') ) ) HasToEnclosed = true; } } if (HasToEnclosed) { StrBd.Insert(0, '\"'); StrBd.Append('\"'); } return StrBd.ToString(); } } }
58ea427b3f34af37b1ac17153ca60011c2854ee6
C#
zeng16107/Alala
/AlalaDocuments/AlalaDocuments/Interfaces/IOrders.cs
2.78125
3
using AlalaDocuments.Models; namespace AlalaDocuments.Interfaces { public interface IOrders { /// <summary> /// Gets the details of an order. /// </summary> /// <param name="docEntry">The entry of the order to be returned.</param> /// <returns>A model that represents the order info.</returns> OrderModel GetById(int docEntry); /// <summary> /// Creates an order to the database. /// </summary> /// <param name="invoice">A model that contains the order info /// to be created.</param> void Create(OrderModel order); /// <summary> /// Updates items of a given order. /// </summary> /// <param name="docEntry">The entry of the order to be updated.</param> /// <param name="invoice">A model that contains the order items to be updated.</param> /// <returns>A boolean value that is set to true whether the order /// found in the database.</returns> bool UpdateItems(int docEntry, OrderModel order); /// <summary> /// Deletes an order from the database. /// </summary> /// <param name="docEntry">The entry of the order to be deleted.</param> /// <returns>A boolean value that is set to true whether the order /// found in the database.</returns> bool Delete(int docEntry); } }
51ccf776c545902d0463a36fded4e1b23f9b5b21
C#
bgoonz/UsefulResourceRepo2.0
/MY_REPOS/misc-experiments/_FIREBFIRE/firebase-unity-sdk/editor/crashlytics/src/Storage/Associations.cs
3.203125
3
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * using UnityEngine; /// <summary> /// Unity does not support serializing Dictionary objects, /// C# doesn't either to be fair, but to facilitate a similar /// interface, these association classes allow one to /// pair a key and value in a list format. /// </summary> public class Associations { /// <summary> /// A base class for holding a Key, Value pair /// where the Key is a string and the Value /// is determined by the implementing class. /// /// Implementing classes must also be marked as /// [Serializable] for Unity to properly format/save them /// in a .asset file. /// /// WARNING (and another interesting thing about Unity serialization): /// Unity leverages reflection to set and get fields off of a /// class. Unity will not serialize out properties, only fields. It /// will by default serialize any public fields but will also /// serialize any private fields marked with [SerializeField]. /// </summary> /// <typeparam name="V">The type of value.</typeparam> [Serializable] public class Association<V> { [SerializeField] private string _key; [SerializeField] private V _value; /// <summary> /// The Key for this association. Used to determine /// uniqueness. /// </summary> public string Key { get { return _key; } set { _key = value; } } /// <summary> /// The Value for this association. /// </summary> public V Value { get { return _value; } set { _value = value; } } /// <summary> /// The hash code for this object is overriden /// and determined solely based on the key. /// </summary> /// <returns></returns> public override int GetHashCode() { return (_key != null ? _key.GetHashCode() : 0); } /// <summary> /// Equality for this object is determined solely /// based on the key's value. /// </summary> /// <param name="other">Another Association object</param> /// <returns>true if the objects are of the /// same type and have the same key, false otherwise. /// </returns> protected bool Equals(Association<V> other) { return string.Equals(_key, other._key); } /// <summary> /// Equality for this object is determined solely /// based on the key's value. /// </summary> /// <param name="obj">Another object</param> /// <returns>true if the objects are of the /// same type and have the same key, false otherwise. /// </returns> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != this.GetType()) return false; return Equals((Association<V>) obj); } /// <summary> /// Outputs the key and value in a well formatted string. /// </summary> /// <returns>A string representation of this Association</returns> public override string ToString() { return "{ " + Key + ": " + Value + " }"; } } /// <summary> /// A String implementation of the base Association class. /// </summary> [Serializable] public class StringAssociation : Association<string> {} /// <summary> /// An Int implementation of the base Association class. /// </summary> [Serializable] public class IntAssociation : Association<int> {} /// <summary> /// A Float implementation of the base Association class. /// </summary> [Serializable] public class FloatAssociation : Association<float> {} /// <summary> /// A Boolean implemenation of the base Association class. /// </summary> [Serializable] public class BoolAssociation : Association<bool> {} } }
6e4babf3987278ac45c8a62b34859d609090ec85
C#
GrognardsFromHell/OpenTemple
/Core/GFX/LinearColor.cs
2.84375
3
using System.Diagnostics.Contracts; using System.Numerics; using System.Runtime.InteropServices; using System.Text; using OpenTemple.Core.Ui.Styles; using SharpDX.Mathematics.Interop; namespace OpenTemple.Core.GFX; [StructLayout(LayoutKind.Sequential)] public struct LinearColor { public float R; public float G; public float B; public static LinearColor White => new(1, 1, 1); public LinearColor(float r, float g, float b) { R = r; G = g; B = b; } public LinearColor(PackedLinearColorA color) : this(color.R * 255, color.G * 255, color.B * 255) { } public static LinearColor Lerp(LinearColor from, LinearColor to, float factor) { return new LinearColor( from.R + (to.R - from.R) * factor, from.G + (to.G - from.G) * factor, from.B + (to.B - from.B) * factor ); } } [StructLayout(LayoutKind.Sequential)] public struct LinearColorA { public float R; public float G; public float B; public float A; public static LinearColorA White => new(1, 1, 1, 1); public static LinearColorA Black => new(0, 0, 0, 1); public static LinearColorA Transparent => new(0, 0, 0, 0); public LinearColorA(float r, float g, float b, float a) { R = r; G = g; B = b; A = a; } public static implicit operator RawColor4(LinearColorA color) { return new RawColor4(color.R, color.G, color.B, color.A); } public static implicit operator PackedLinearColorA(LinearColorA color) { return new PackedLinearColorA(color); } } /// <summary> /// A LinearColorA packed into a 32-bit BGRA integer. /// </summary> [StructLayout(LayoutKind.Explicit, Size = 4, Pack = 1)] public struct PackedLinearColorA { [FieldOffset(0)] public byte B; [FieldOffset(1)] public byte G; [FieldOffset(2)] public byte R; [FieldOffset(3)] public byte A; public PackedLinearColorA(LinearColorA color) : this((byte) (color.R * 255.0f), (byte) (color.G * 255.0f), (byte) (color.B * 255.0f), (byte) (color.A * 255.0f)) { } public PackedLinearColorA(LinearColor color, float alpha = 1.0f) : this((byte) (color.R * 255.0f), (byte) (color.G * 255.0f), (byte) (color.B * 255.0f), (byte) (alpha * 255.0f)) { } public PackedLinearColorA(uint packed) : this() { B = (byte) (packed & 0xFF); G = (byte) ((packed >> 8) & 0xFF); R = (byte) ((packed >> 16) & 0xFF); A = (byte) ((packed >> 24) & 0xFF); } [Pure] public uint Pack() { return (uint) (B | G << 8 | R << 16 | A << 24); } public PackedLinearColorA(byte r, byte g, byte b, byte a) { B = b; G = g; R = r; A = a; } public PackedLinearColorA WithAlpha(int alpha) { return new PackedLinearColorA(R, G, B, (byte) alpha); } public static PackedLinearColorA OfFloats(float r, float g, float b, float a) { return new PackedLinearColorA( (byte) (r * 255.0f), (byte) (g * 255.0f), (byte) (b * 255.0f), (byte) (a * 255.0f) ); } public static PackedLinearColorA White => new(255, 255, 255, 255); public static PackedLinearColorA Black => new(0, 0, 0, 255); public static PackedLinearColorA Transparent => new(0, 0, 0, 0); [Pure] public Vector4 ToRGBA() => new( R / 255.0f, G / 255.0f, B / 255.0f, A / 255.0f ); public bool Equals(PackedLinearColorA other) { return B == other.B && G == other.G && R == other.R && A == other.A; } public override bool Equals(object? obj) { return obj is PackedLinearColorA other && Equals(other); } public override int GetHashCode() { unchecked { var hashCode = B.GetHashCode(); hashCode = (hashCode * 397) ^ G.GetHashCode(); hashCode = (hashCode * 397) ^ R.GetHashCode(); hashCode = (hashCode * 397) ^ A.GetHashCode(); return hashCode; } } public static bool operator ==(PackedLinearColorA left, PackedLinearColorA right) { return left.Equals(right); } public static bool operator !=(PackedLinearColorA left, PackedLinearColorA right) { return !left.Equals(right); } public override string ToString() { var result = new StringBuilder(A != 255 ? 9 : 7); result.Append('#'); if (A != 255) { result.AppendFormat("{0:x2}", A); } result.AppendFormat("{0:x2}{1:x2}{2:x2}", R, G, B); return result.ToString(); } public static PackedLinearColorA FromHex(string text) { return JsonColorLoader.ParseColor(text); } }
e7cf5c4d5ca2b005ff8cca39b61e01184356d7db
C#
mEliehl/MorningBrewCrawler
/tests/Crawler.Test/Unit/Mappers/EnglishMonthsTest.cs
2.796875
3
using Crawler.Mappers; using System; using Xunit; namespace Crawler.Test.Mappers { [Trait(TraitConstants.Category, TraitConstants.Unit)] public class EnglishMonthsTest { [Fact] public void WithInvalidMonth_ThrowsException() { var month = "Decenuary"; Assert.Throws<ArgumentException>(() => EnglishMonths.Map(month)); } [Theory] [InlineData(EnglishMonths.January, 1)] [InlineData(EnglishMonths.February, 2)] [InlineData(EnglishMonths.March, 3)] [InlineData(EnglishMonths.April, 4)] [InlineData(EnglishMonths.May, 5)] [InlineData(EnglishMonths.June, 6)] [InlineData(EnglishMonths.July, 7)] [InlineData(EnglishMonths.August, 8)] [InlineData(EnglishMonths.September, 9)] [InlineData(EnglishMonths.October, 10)] [InlineData(EnglishMonths.November, 11)] [InlineData(EnglishMonths.December, 12)] public void WithValidMonth_ReturnExpectedInteger(string month, int expected) { var actual = EnglishMonths.Map(month); Assert.Equal(expected, actual); } } }
75d243adcfdf895657d345a604953d3f49171361
C#
Ed-Fi-Exchange-OSS/Ed-Fi-Roster-Sample-Application
/EdFi.Roster.Sdk/Services/ApiLogService.cs
2.703125
3
using EdFi.Roster.Sdk.Data; using EdFi.Roster.Sdk.Models; using RestSharp; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using System.Text.Json; using System.Threading; namespace EdFi.Roster.Sdk.Services { public class ApiLogService { private readonly string fullFilePath; public ApiLogService() { var filePath = Path.Combine(Directory.GetParent(Environment.CurrentDirectory).FullName, "EdFi.Roster.Sdk", "Data"); this.fullFilePath = Path.Combine(filePath, typeof(List<ApiLogEntry>).FullName) + ".json"; } public void WriteLog(IRestClient client, IRestRequest request, IRestResponse response) { var apiLogEntry = new ApiLogEntry { LogDateTime = DateTime.Now, Client = new ClientLog { BaseUrl = client.BaseUrl.OriginalString, FullUrl = client.BuildUri(request).OriginalString }, Request = new RequestLog { Resource = request.Resource, // Parameters are custom anonymous objects in order to have the parameter type as a nice string // otherwise it will just show the enum value Parameters = request.Parameters.Select(parameter => new ApiCallLogParameter { Name = parameter.Name, Value = parameter.Value, Type = parameter.Type.ToString() }).ToList(), // ToString() here to have the method as a nice string otherwise it will just show the enum value Method = request.Method.ToString(), // This will generate the actual Uri used in the request Uri = client.BuildUri(request), }, Response = new ResponseLog { StatusCode = response.StatusCode, Content = response.Content, Headers = response.Headers.Select(parameter => new ApiCallLogParameter { Name = parameter.Name, Value = parameter.Value, Type = parameter.Type.ToString() }).ToList(), // The Uri that actually responded (could be different from the requestUri if a redirection occurred) Uri = response.ResponseUri, ErrorMessage = response.ErrorMessage, } }; //var logData = dataService.Read<List<ApiLogEntry>>(); var logData = new List<ApiLogEntry> { apiLogEntry }; WriteApiLog(apiLogEntry); } static readonly ReaderWriterLockSlim locker = new ReaderWriterLockSlim(); private void WriteApiLog(ApiLogEntry apiLog) { //read it all var logEntries = new List<ApiLogEntry>(); try { locker.EnterWriteLock(); if (File.Exists(fullFilePath)) { logEntries = JsonSerializer.Deserialize<List<ApiLogEntry>>(File.ReadAllText(fullFilePath)); } logEntries.Add(apiLog); File.WriteAllText(fullFilePath, JsonSerializer.Serialize(logEntries)); } finally { locker.ExitWriteLock(); } } public void ClearLogs() { if (File.Exists(fullFilePath)) { File.Delete(fullFilePath); } } public async Task<List<ApiLogEntry>> ReadAllLogsAsync() { var apiLogs = new List<ApiLogEntry>(); if (File.Exists(fullFilePath)) { using (FileStream fs = File.OpenRead(fullFilePath)) { apiLogs = await JsonSerializer.DeserializeAsync<List<ApiLogEntry>>(fs); } } return apiLogs; } } //public sealed class JsonApiLogWriter:IDisposable //{ // private static FileStream fileStream; // public void WriteLog(List<ApiLogEntry> existingLogs, ApiLogEntry newEntry) // { // existingLogs.Add(newEntry); // using (StreamWriter sr = new StreamWriter(fileStream)) // { // // File writing as usual // sr.Write(JsonConvert.SerializeObject(existingLogs)); // } // } // private JsonApiLogWriter() // { // var filePath = Path.Combine(Directory.GetParent(Environment.CurrentDirectory).FullName, "EdFi.Roster.Sdk", "Data"); // string fullPath = Path.Combine(filePath, typeof(List<ApiLogEntry>).FullName) + ".json"; // fileStream = new FileStream(fullPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read); // } // public static JsonApiLogWriter Instance { get; } = new JsonApiLogWriter(); // public void Dispose() // { // fileStream.Close(); // } //} }
64b7334efd63230fb355535186c98676992f4130
C#
hrjakobsen/P2-AAU
/Programmer/Optimeringer/third_round/CS/Vertex.cs
3.046875
3
namespace Stegosaurus { public class Vertex { public short SampleValue1 { get; set; } public short SampleValue2 { get; set; } public byte Message { get; } public byte Modulo { get; } public Vertex(short sampleValue1, short sampleValue2, byte message, byte modulo) { SampleValue1 = sampleValue1; SampleValue2 = sampleValue2; Message = message; Modulo = modulo; } public override string ToString() { return $"({SampleValue1},{SampleValue2})"; } } }
fbe3c1c59cb406762d3ffb8c94b46156163b8caa
C#
1057337494/Gof4Demo
/Gof4Demo/SimplePolicy/MinAgePolicyHandler.cs
2.796875
3
using Microsoft.AspNetCore.Authorization; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Gof4Demo.SimplePolicy { public class MinAgePolicyHandler : AuthorizationHandler<MinAgePolicy> { protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, MinAgePolicy requirement) { if (!context.User.HasClaim(s => s.Type == "age")) { context.Fail(); } var age = Convert.ToDecimal(context.User.FindFirst("age")); if (age < requirement.Age) { context.Fail(); } context.Succeed(requirement); return Task.CompletedTask; } } }
ac46fce661a9d271efb1ce872a5cc680db03071d
C#
alexeyprov/MCPD
/70-487/WcfRestContrib/src/WcfRestContrib/ServiceModel/Channels/BinaryBodyReader.cs
2.515625
3
using System.Xml; namespace WcfRestContrib.ServiceModel.Channels { public class BinaryBodyReader { public const string BinaryElementName = "Binary"; private readonly byte[] _data; public BinaryBodyReader(XmlDictionaryReader reader) { reader.ReadStartElement(BinaryElementName); _data = reader.ReadContentAsBase64(); if (reader.NodeType == XmlNodeType.Text) reader.Read(); reader.ReadEndElement(); } public byte[] Data { get { return _data; } } } }
bf1509271f2557e3d5aeba37e9ac755ed8adb46d
C#
ronartcal/Unity-Simulation-Smart-Camera-Outdoor
/Assets/UnityScenarios/Scripts/ReversePointsOrder.cs
2.609375
3
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ReversePointsOrder : MonoBehaviour { public ObjectMovementManager source; public ObjectMovementManager destination; public void ReverseOrder() { destination.controlPoints.Clear(); Debug.Log(destination.controlPoints.Count); Debug.Log(source.controlPoints.Count); for (int i = source.controlPoints.Count-1; i > 0; i--) { Debug.Log(source.controlPoints[i]); destination.controlPoints.Add(source.controlPoints[i]); } Debug.Log(destination.controlPoints.Count); } }
3f91a7e97e014ff011de87da6bc15d15525b2f26
C#
hosboglot/24crypt
/Crypting/Crypting/Crypting/Gamma.cs
3.203125
3
using System; using System.Collections.Generic; namespace Crypting { public class Gamma { public static string Encrypt(string input, string gamma) { List<int> s1 = ConvertTC.TextToCode(input); List<int> s2 = ConvertTC.TextToCode(gamma); List<int> it = new List<int>(); for (int i = 0; i < s1.Count; i++) { it.Add((s1[i] + s2[i]) % alp.Length); } return ConvertTC.CodeToText(it); } public static string Decrypt(string sh, string gamma) { List<int> s2 = ConvertTC.TextToCode(sh); List<int> s3 = ConvertTC.TextToCode(gamma); List<int> res = new List<int>(); for (int i = 0; i < s2.Count; i++) { res.Add((s2[i] - s3[i] + alp.Length) % alp.Length); } return ConvertTC.CodeToText(res); } public static string alp = "¶абвгдеёжзийклмнопрстуфхцчшщьыъэюя" + "АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЬЫЪЭЮЯ" + "abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "0123456789" + ".,!?:-_=+\"\\#№$%^&*;()±§<>{}[] "; } }
2429bd5fc0293265128c3cac682f6501b9ce672f
C#
OliBomby/Mapping_Tools
/Mapping_Tools/Components/ViewHeaderComponent.xaml.cs
2.6875
3
using System; using Mapping_Tools.Classes.SystemTools; using System.Linq; using System.Reflection; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using Mapping_Tools.Classes.SystemTools.QuickRun; using Mapping_Tools.Views; namespace Mapping_Tools.Components { /// <summary> /// Interaction logic for ViewHeaderComponent.xaml /// </summary> public partial class ViewHeaderComponent { /// <summary> /// /// </summary> public static readonly DependencyProperty ParentControlProperty = DependencyProperty.Register(nameof(ParentControl), typeof(UserControl), typeof(ViewHeaderComponent)); /// <summary> /// /// </summary> public UserControl ParentControl { get => (UserControl)GetValue(ParentControlProperty); set => SetValue(ParentControlProperty, value); } /// <summary> /// /// </summary> public ViewHeaderComponent() { InitializeComponent(); } /// <summary>Invoked whenever the effective value of any dependency property on this <see cref="T:System.Windows.FrameworkElement" /> has been updated. The specific dependency property that changed is reported in the arguments parameter. Overrides <see cref="M:System.Windows.DependencyObject.OnPropertyChanged(System.Windows.DependencyPropertyChangedEventArgs)" />.</summary> /// <param name="e">The event data that describes the property that changed, as well as old and new values.</param> protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e) { Console.WriteLine(@"PROPERTY CHANGED!"); try { var type = e.NewValue.GetType(); if (type.GetCustomAttribute<DontShowTitleAttribute>() != null) { MainPanel.Visibility = Visibility.Collapsed; } else { MainPanel.Visibility = Visibility.Visible; QuickRunIcon.Visibility = typeof(IQuickRun).IsAssignableFrom(type) ? Visibility.Visible : Visibility.Collapsed; var name = ViewCollection.GetName(type); var description = ViewCollection.GetDescription(type); DescriptionIcon.Visibility = string.IsNullOrEmpty(description) ? Visibility.Collapsed : Visibility.Visible; HeaderTextBlock.Text = name; DescriptionTextBlock.Text = description; } } catch (Exception exception) { Console.WriteLine(exception); } } } }
7dfc6e4ac2960dcf1b19455894b9e6cdcfb7e2bb
C#
MarioHsiao/NuPattern
/Src/Runtime/Source/Runtime.Extensibility/Design/SettingsReferenceTypeConverter.cs
3.09375
3
using System; using System.Collections; using System.ComponentModel; using System.Globalization; using System.Linq; namespace NuPattern.Runtime.Design { /// <summary> /// Converter that lists automation settings of the type /// <typeparamref name="TSettings"/> available /// in the containing element of the current element. /// </summary> /// <typeparam name="TSettings">The type of the settings.</typeparam> public class SettingsReferenceTypeConverter<TSettings> : TypeConverter where TSettings : IAutomationSettings { /// <summary> /// Converts the given value object to the specified type, using the specified context and culture information. /// </summary> public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { var settings = value as IAutomationSettings; if (destinationType == typeof(string) && settings != null) { return settings.Name; } return base.ConvertTo(context, culture, value, destinationType); } /// <summary> /// Returns whether the collection of standard values returned from <see cref="M:System.ComponentModel.TypeConverter.GetStandardValues"/> is an exclusive list of possible values, using the specified context. /// </summary> public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { return true; } /// <summary> /// Returns whether this object supports a standard set of values that can be picked from a list, using the specified context. /// </summary> public override bool GetStandardValuesSupported(ITypeDescriptorContext context) { return true; } /// <summary> /// Returns a collection of standard values for the data type this type converter is designed for when provided with a format context. /// </summary> public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { if (context == null) { return new StandardValuesCollection(new ArrayList()); } var settings = (IAutomationSettings)context.Instance; return new StandardValuesCollection(settings .Owner .AutomationSettings .Select(s => s.As<TSettings>()) .Where(s => s != null) .ToArray()); } } }
4f79f76569a70cb9210d8f96d10b2f0c833caadf
C#
nrkn/NrknLib
/Color/Rgba.cs
2.546875
3
namespace NrknLib.Color { public struct Rgba { public Rgba( byte red, byte green, byte blue, byte alpha = (byte)255 ) { Red = red; Green = green; Blue = blue; Alpha = alpha; } public byte Red; public byte Blue; public byte Green; public byte Alpha; } }
b4ffd81fb269570d2907aa13892359c6f799540a
C#
bmsmith43/FireRegister
/FireRegister/FireRegister/Services/MockDataStore.cs
3.125
3
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using FireRegister.Models; namespace FireRegister.Services { public class MockDataStore : IDataStore<Employee> { readonly List<Employee> _employees; public MockDataStore() { _employees = new List<Employee>(); var mockItems = new List<Employee> { new Employee { Id = "First item", Name = "This is an item description." }, new Employee { Id = "Second item", Name = "This is an item description." }, new Employee { Id = "Third item", Name = "This is an item description." }, new Employee { Id = "Fourth item", Name = "This is an item description." }, new Employee { Id = "Fifth item", Name = "This is an item description." }, new Employee { Id = "Sixth item", Name = "This is an item description." }, }; foreach (var item in mockItems) { _employees.Add(item); } } public async Task<bool> AddEmployeeAsync(Employee item) { _employees.Add(item); return await Task.FromResult(true); } public async Task<bool> UpdateEmployeeAsync(Employee item) { var oldItem = _employees.FirstOrDefault(arg => arg.Id == item.Id); _employees.Remove(oldItem); _employees.Add(item); return await Task.FromResult(true); } public async Task<bool> DeleteEmployeeAsync(string id) { var oldItem = _employees.FirstOrDefault(arg => arg.Id == id); _employees.Remove(oldItem); return await Task.FromResult(true); } public async Task<Employee> GetEmployeeAsync(string id) { return await Task.FromResult(_employees.FirstOrDefault(s => s.Id == id)); } public async Task<IEnumerable<Employee>> GetEmployeesAsync(bool forceRefresh = false) { return await Task.FromResult(_employees); } } }
5b8ac0e044f2227626beefa152074d4e1c4ce03b
C#
Monkeybin11/000_MainProjects
/01Sub/SubProject/Rs232Lib.cs
2.96875
3
using System; using System.Collections.Generic; using System.IO.Ports; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace RS232_LibTest { public class RS232<TcommandList> where TcommandList : struct, IComparable, IConvertible, IFormattable { public SerialPort Port; public event Action<string> evtReadDone; public RS232( SerialPort port ) { Port = port; //Port.DataReceived += new SerialDataReceivedEventHandler( ReadDone ); } public bool? Open() { Port.Open(); return true; } public void Close() { Port.Close(); Port.Dispose(); } private void ReadDone( object sender, SerialDataReceivedEventArgs e ) { Console.WriteLine( "REad" ); var port = sender as SerialPort; var size = port.ReadBufferSize; string lineReadIn = ""; while ( port.BytesToRead > 0 ) { lineReadIn += port.ReadExisting(); Thread.Sleep( 25 ); } Console.WriteLine( "RS232 : " + lineReadIn.ToString() ); //try //{ // evtReadDone( (sender as SerialPort).ReadExisting() ); //} //catch ( Exception ) //{ // evtReadDone( null ); // throw; //} } byte[] Delimiter = new byte[] { 0x0d , 0x0a }; public string query( string text ) { Port.WriteLine( text ); Thread.Sleep( 300 ); var res = Port.ReadExisting().Replace("\r" , string.Empty ).Replace("\n" , string.Empty); Console.WriteLine( "Query Rescived : " + res ); return res; } public void Send( string text ) { // lock ( Port ) // { // try // { // // var arr = System.Text.Encoding.ASCII.GetBytes(text); // Port.Write( arr, 0, arr.Length ); // Port.Write( Delimiter, 0, Delimiter.Length ); // // // List<byte> recvPacket = new List<byte>(); // // Thread.Sleep( 1 ); // // DateTime TimeoutTime = DateTime.Now.AddMilliseconds(100); // while ( TimeoutTime > DateTime.Now ) // { // if ( Port.BytesToRead > 0 ) // { // byte[] readbyte = new byte[Port.BytesToRead]; // Port.Read( readbyte, 0, readbyte.Length ); // recvPacket.AddRange( readbyte ); // } // // if ( CheckDelimiter( recvPacket ) ) // { // break; // } // } // if ( recvPacket.Count > Delimiter.Length ) // { // var res = Encoding.ASCII.GetString( recvPacket.ToArray(), 0, recvPacket.Count - Delimiter.Length ); // } // } // catch ( ArgumentOutOfRangeException e ) // { // Console.WriteLine( "error = " + e.Message ); // } // } lock(Port) { Port.WriteLine( text ); } //byte[] Delimiter = new byte[] { 0x0d }; //var arr = Encoding.ASCII.GetBytes(text.Trim()); //Port.Write( arr, 0, arr.Length ); //Port.Write( Delimiter, 0, Delimiter.Length ); } private bool CheckDelimiter( List<byte> recvPacket ) { if ( recvPacket.Count >= Delimiter.Length ) { for ( int i = 0; i < Delimiter.Length; i++ ) { if ( recvPacket[recvPacket.Count - i - 1] != Delimiter[Delimiter.Length - i - 1] ) { return false; } } return true; } else { return false; } } public void Send( string text, double value ) { text = text + " " + value.ToString(); byte[] Delimiter = new byte[] { 0x0d }; var arr = Encoding.ASCII.GetBytes(text.Trim()); Port.Write( arr, 0, arr.Length ); Port.Write( Delimiter, 0, Delimiter.Length ); } public void Send( TcommandList command, double value ) { var text = command.ToString() + " " + value.ToString(); byte[] Delimiter = new byte[] { 0x0d }; var arr = Encoding.ASCII.GetBytes(text.Trim()); Port.Write( arr, 0, arr.Length ); Port.Write( Delimiter, 0, Delimiter.Length ); } } }
3fb59c900c143a577a54b7a37074cb83d2b947a8
C#
MarozauArtsiom/MarryMe
/MarryMe.Model/Factory/DBFactory.cs
2.65625
3
namespace MarryMe.Model.Factory { #region Using using System; using System.Configuration; using System.Data; using System.Data.Common; #endregion public class DBFactory { public const string StatisticOutData = "statistic"; #region private fields private const string DefaultConnectionStringName = "DefaultConnection"; private static string ConnectionString { get; set; } #endregion #region Singleton factory private static object _lockFactory = new object(); private static DbProviderFactory _connectionFactory = null; private static DbProviderFactory ConnectionFactory { get { if (_connectionFactory == null) { lock (_lockFactory) { if (_connectionFactory == null) { ConnectionStringSettings connectionString = GetConnectionString(DefaultConnectionStringName); if (connectionString != null) { _connectionFactory = DbProviderFactories.GetFactory(connectionString.ProviderName); ConnectionString = connectionString.ConnectionString; } } } } return _connectionFactory; } } #endregion public static void AddParameter(DbCommand cmd, string paramName, object value) { var dbParam = cmd.CreateParameter(); dbParam.Value = value; dbParam.ParameterName = paramName; cmd.Parameters.Add(dbParam); } public static DbConnection GetConnection() { DbConnection connection = null; if (ConnectionFactory != null) { connection = ConnectionFactory.CreateConnection(); connection.ConnectionString = ConnectionString; } return connection; } private static ConnectionStringSettings GetConnectionString(string connectionName) { ConnectionStringSettings connectionString = null; ConnectionStringSettingsCollection settings = ConfigurationManager.ConnectionStrings; foreach (ConnectionStringSettings cs in settings) { if (cs.Name == connectionName) { connectionString = cs; break; } } return connectionString; } } }
b93042f5ff53b799b4383779844666523b2b803d
C#
sthewissen/Xamarin.Forms
/Xamarin.Forms.Platform.iOS/CollectionView/SelectableItemsViewRenderer.cs
2.5625
3
using System; using System.ComponentModel; namespace Xamarin.Forms.Platform.iOS { public class SelectableItemsViewRenderer : StructuredItemsViewRenderer { SelectableItemsView SelectableItemsView => (SelectableItemsView)Element; SelectableItemsViewController SelectableItemsViewController => (SelectableItemsViewController)ItemsViewController; protected override ItemsViewController CreateController(ItemsView itemsView, ItemsViewLayout layout) { return new SelectableItemsViewController(itemsView as SelectableItemsView, layout); } protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs changedProperty) { base.OnElementPropertyChanged(sender, changedProperty); if (changedProperty.IsOneOf(SelectableItemsView.SelectedItemProperty, SelectableItemsView.SelectedItemsProperty)) { SelectableItemsViewController.UpdateNativeSelection(); } else if (changedProperty.Is(SelectableItemsView.SelectionModeProperty)) { SelectableItemsViewController.UpdateSelectionMode(); } } protected override void SetUpNewElement(ItemsView newElement) { if (newElement != null && !(newElement is SelectableItemsView)) { throw new ArgumentException($"{nameof(newElement)} must be of type {typeof(SelectableItemsView).Name}"); } base.SetUpNewElement(newElement); if (newElement == null) { return; } SelectableItemsViewController.UpdateSelectionMode(); SelectableItemsViewController.UpdateNativeSelection(); } } }
879edac37320a0d3d781cf7393729b7e616ee4f9
C#
bboyadzhiev/Telerik
/12.Algorithms/03.Trees_And_Traversals_HW/01.TreeTraversal/TreeNodeExtensions.cs
3.78125
4
namespace _01.TreeTraversal { using System; using System.Collections.Generic; public static class TreeNodeExtensions { public static void PrintChildren<T>(this TreeNode<T> node, int offset) where T : IComparable<T> { for (int i = 0; i < offset; i++) { Console.Write(" "); } if (node.Children.Count != 0) { Console.WriteLine("{0}", node.Value); foreach (var child in node.Children) { child.PrintChildren(offset + 1); } } else { Console.WriteLine("{0} - leaf", node.Value); } } public static List<TreeNode<T>> GetLeafNodes<T>(this TreeNode<T> treeNode) where T : IComparable<T> { var leafs = new List<TreeNode<T>>(); if (treeNode.Children.Count == 0) { leafs.Add(treeNode); } else { foreach (var child in treeNode.Children) { leafs.AddRange(child.GetLeafNodes()); } } return leafs; } public static List<TreeNode<T>> GetMiddleNodes<T>(this TreeNode<T> treeNode) where T : IComparable<T> { var middleNodesList = new List<TreeNode<T>>(); var children = treeNode.Children; if (children.Count > 0 && treeNode.HasParent) { middleNodesList.Add(treeNode); } foreach (var child in children) { foreach (var leaf in child.GetMiddleNodes()) { if (!middleNodesList.Contains(leaf)) { middleNodesList.Add(leaf); } } } return middleNodesList; } } }
a6869506beafc852dc8715ec0678aea539322d86
C#
rodriguesrm/rsoft-helpers
/src/RSoft.Helpers/Attribute/RoleNameAttribute.cs
2.890625
3
using sys = System; namespace RSoft.Helpers.Attribute { /// <summary> /// Represents a class of function attributes (Roles) /// </summary> public class RoleNameAttribute : sys.Attribute { #region Constructors /// <summary> /// Creates a new attribute instance /// </summary> /// <param name="name">Role name</param> public RoleNameAttribute(string name) { Name = name; } #endregion #region Properties /// <summary> /// Gets the role name /// </summary> public string Name { get; private set; } #endregion } }
c43b085e5c8dee6062798ba03ca5d0342cbe2c4b
C#
zrasco/SubSearch
/SubSearchUI/Models/VideoFileItem.cs
2.609375
3
using GalaSoft.MvvmLight.Command; using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Windows; using System.Windows.Input; using System.Windows.Media; using System.Windows.Navigation; namespace SubSearchUI.Models { public class SubtitleFileInfo { public SubtitleFileInfo(VideoFileItem parent) { Parent = parent; } public VideoFileItem Parent { get; set; } public CultureInfo CultureInfo { get; set; } public string Filebase { get; set; } public string FullPath { get; set; } public string Filename { get; set; } public bool Exists { get; set; } } public class VideoFileItem : ItemWithImage { public VideoFileItem() { SubtitleFileList = new List<SubtitleFileInfo>(); } public void RefreshColor() { if (SubtitleFileList.Where(x => x.Exists).Any()) TextColor = Brushes.Green; else TextColor = Brushes.Red; } /// <summary> /// The <see cref="IsSelected" /> property's name. /// </summary> public const string IsSelectedPropertyName = "IsSelected"; private bool _isSelected = false; /// <summary> /// Sets and gets the IsSelected property. /// Changes to that property's value raise the PropertyChanged event. /// </summary> public bool IsSelected { get { return _isSelected; } set { if (_isSelected == value) { return; } _isSelected = value; RaisePropertyChanged(IsSelectedPropertyName); } } /// <summary> /// The <see cref="FullPath" /> property's name. /// </summary> public const string FullPathPropertyName = "FullPath"; private string _fullPath; /// <summary> /// Sets and gets the FullPath property. /// Changes to that property's value raise the PropertyChanged event. /// </summary> public string FullPath { get { return _fullPath; } set { if (_fullPath == value) { return; } _fullPath = value; RaisePropertyChanged(FullPathPropertyName); } } /// <summary> /// The <see cref="SubtitleFileList" /> property's name. /// </summary> public const string SubtitleFileListPropertyName = "SubtitleFileList"; private IList<SubtitleFileInfo> _subtitleFileList; /// <summary> /// Sets and gets the SubtitleFileList property. /// Changes to that property's value raise the PropertyChanged event. /// </summary> public IList<SubtitleFileInfo> SubtitleFileList { get { return _subtitleFileList; } set { if (_subtitleFileList == value) { return; } _subtitleFileList = value; RaisePropertyChanged(SubtitleFileListPropertyName); } } private RelayCommand<string> _deleteFileCommand; /// <summary> /// Gets the DeleteFileCommand. /// </summary> public RelayCommand<string> DeleteFileCommand { get { return _deleteFileCommand ?? (_deleteFileCommand = new RelayCommand<string>(DeleteFileCommandMethod)); } } private void DeleteFileCommandMethod(string filename) { var result = MessageBox.Show($"Are you sure you wish to delete {filename}?", "Delete confirmation", MessageBoxButton.YesNo, MessageBoxImage.Exclamation); if (result == MessageBoxResult.Yes) { // Delete file } } public bool GenerateSubtitleInfo(string defaultLanguage, IList<CultureInfo> allCultureInfos) // Returns true if subtitle info was generated, otherwise false if unable to look up culture info for specified language { bool retval = false; string fileBase = $"{Path.GetDirectoryName(FullPath)}\\{Path.GetFileNameWithoutExtension(FullPath)}"; CultureInfo defaultCultureInfo = allCultureInfos.Where(x => x.DisplayName == defaultLanguage).FirstOrDefault(); if (defaultCultureInfo != null) { SubtitleFileList = new List<SubtitleFileInfo>(); SubtitleFileList.Add(new SubtitleFileInfo(this) { CultureInfo = defaultCultureInfo, Filebase = Path.GetFileName(fileBase), FullPath = fileBase + ".srt" }); SubtitleFileList.Add(new SubtitleFileInfo(this) { CultureInfo = defaultCultureInfo, Filebase = Path.GetFileName(fileBase), FullPath = fileBase + "." + defaultCultureInfo.TwoLetterISOLanguageName + ".srt" }); if (defaultCultureInfo.TwoLetterISOLanguageName != defaultCultureInfo.Name) SubtitleFileList.Add(new SubtitleFileInfo(this) { CultureInfo = defaultCultureInfo, Filebase = Path.GetFileName(fileBase), FullPath = fileBase + "." + defaultCultureInfo.Name + ".srt" }); foreach (var info in SubtitleFileList) { info.Filename = Path.GetFileName(info.FullPath); info.Exists = File.Exists(info.FullPath); } retval = true; } RefreshColor(); return retval; } } }
e2dadd2c5da30898300621905548e7019b34bebe
C#
carolineisnotonfire/GitC
/Usando DLLs/BoletimEscolar/RecebeFrequencia/Classes/Boletim.cs
3.421875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RecebeFrequencia.Classes { public class Boletim { public int SomaNotas(int nota1, int nota2, int nota3) { return (nota1 + nota2 + nota3) / 3; } public int frequencia(int totalAulas, int numeroFaltas) { return ((totalAulas - numeroFaltas) * 100) / totalAulas; } public void situacao(int media, int frequencia) { if ((media >= 7) && (frequencia >= 75)) { Console.WriteLine($"Aluno aprovado com média {media} e frequencia de {frequencia}%"); } else { Console.WriteLine($"Aluno reprovado com média {media} e frequencia de {frequencia}%"); } } public string RetornaSituacao(int media, int frequencia) { if ((media >= 7) && (frequencia >= 75)) { return "Aprovado"; } return "Reprovado"; } } }
a4e7f58db6fa7ed2bc44494183d294fd48674799
C#
FelixCukerman/BlackJackCore
/DataAccessLayer/Repositories/DapperRepositories/DapperGameRepository.cs
2.765625
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.Transactions; using Dapper.Contrib.Extensions; using DataAccessLayer.Interfaces; using EntitiesLayer.Entities; namespace DataAccessLayer.Repositories.DapperRepositories { public class DapperGameRepository : IGameRepository { private string connectionString = null; public DapperGameRepository(string connectionString) { this.connectionString = connectionString; } public async Task<IEnumerable<Game>> Get() { using (IDbConnection db = new SqlConnection(connectionString)) { return await db.GetAllAsync<Game>(); } } public async Task<Game> Get(int id) { using (IDbConnection db = new SqlConnection(connectionString)) { return await db.GetAsync<Game>(id); } } public async Task Create(Game game) { using (IDbConnection db = new SqlConnection(connectionString)) { var invoice = await db.InsertAsync(game); game.Id = invoice; } } public async Task CreateRange(IEnumerable<Game> games) { using (TransactionScope scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { using (IDbConnection db = new SqlConnection(connectionString)) { for(int i = 0; i < games.Count(); i++) { var invoice = await db.InsertAsync(games.ElementAt(i)); games.ElementAt(i).Id = invoice; } scope.Complete(); } } } public async Task Update(Game game) { using (IDbConnection db = new SqlConnection(connectionString)) { var invoice = await db.UpdateAsync(game); } } public async Task UpdateRange(IEnumerable<Game> games) { using (TransactionScope scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { using (IDbConnection db = new SqlConnection(connectionString)) { for(int i = 0; i < games.Count(); i++) { var invoice = await db.UpdateAsync(games.ElementAt(i)); } scope.Complete(); } } } public async Task Delete(Game game) { using (IDbConnection db = new SqlConnection(connectionString)) { var invoice = await db.DeleteAsync(game); } } public async Task DeleteRange(IEnumerable<Game> games) { using (TransactionScope scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { using (IDbConnection db = new SqlConnection(connectionString)) { for(int i = 0; i < games.Count(); i++) { var invoice = await db.DeleteAsync(games.ElementAt(i)); } scope.Complete(); } } } } }
97c1acffe83e4f2a8773f97cb12fa2daa734acfd
C#
lightbulbindustries/ProjectSapphire
/GridTest/Assets/Scripts/Buildings/Building Types/MiningHut.cs
2.53125
3
using UnityEngine; using System.Collections; public class MiningHut : Building { [SerializeField] float miningDelay = 2f; TileData map; ResourceManager resources; bool mining = false; // Use this for initialization void Start() { map = Toolbox.MapData; resources = Toolbox.Resources; StartCoroutine(Mining()); mining = true; } IEnumerator Mining() // Mine da fuggin' gold! { int amount = 0; while (true) { yield return new WaitForSeconds(miningDelay); amount = 0; // Get 4 gold from each tile that the mining hut is on foreach (Vector2 positions in placement.TileList) { amount += map.GetTile((int)(positions.x + position.x), (int)(positions.y + position.y)).MineGold(4); } if (amount > 0) { Debug.Log("Mining " + amount); resources.ModifyResource(amount, ResourceType.Gold); } else { Debug.Log("Mining nothing"); mining = false; break; } } } }
0520095f4d0830c456581a950cad5fc6cbf586b0
C#
lesterrentosa/Contact-Tracing
/Contact Tracing/Form1.cs
2.5625
3
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Contact_Tracing { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void lastNameTxtBox_TextChanged(object sender, EventArgs e) { } private void firstNameTxtBox_TextChanged(object sender, EventArgs e) { } private void MiddleNameTxtBox_TextChanged(object sender, EventArgs e) { } private void AgeTxtBox_TextChanged(object sender, EventArgs e) { } private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { } private void ContactTxtBox_TextChanged(object sender, EventArgs e) { } private void EmailTxtBox_TextChanged(object sender, EventArgs e) { } private void AddressTxtBox_TextChanged(object sender, EventArgs e) { } private void BrgyTxtBox_TextChanged(object sender, EventArgs e) { } private void CityTxtBox_TextChanged(object sender, EventArgs e) { } private void SubmitButton_Click(object sender, EventArgs e) { StreamWriter outputFile; outputFile = File.AppendText("Output.txt"); outputFile.WriteLine(""); outputFile.Write("Last Name: "); outputFile.WriteLine(lastNameTxtBox.Text); outputFile.Write("First Name: "); outputFile.WriteLine(firstNameTxtBox.Text); outputFile.Write("Middle Name: "); outputFile.WriteLine(MiddleNameTxtBox.Text); outputFile.Write("Age: "); outputFile.WriteLine(AgeTxtBox.Text); outputFile.Write("Gender: "); outputFile.WriteLine(comboBox1.Text); outputFile.Write("Contact Number: "); outputFile.WriteLine(ContactTxtBox.Text); outputFile.Write("Email: "); outputFile.WriteLine(EmailTxtBox.Text); outputFile.Write("Address: "); outputFile.WriteLine(AddressTxtBox.Text); outputFile.Write("Barangay: "); outputFile.WriteLine(BrgyTxtBox.Text); outputFile.Write("City: "); outputFile.WriteLine(CityTxtBox.Text); outputFile.Close(); lastNameTxtBox.Clear(); firstNameTxtBox.Clear(); MiddleNameTxtBox.Clear(); AgeTxtBox.Clear(); comboBox1.ResetText(); ContactTxtBox.Clear(); EmailTxtBox.Clear(); AddressTxtBox.Clear(); BrgyTxtBox.Clear(); CityTxtBox.Clear(); MessageBox.Show("Thank you!", "Done"); } private void LastNameLabel_Click(object sender, EventArgs e) { } private void FirstNameLabel_Click(object sender, EventArgs e) { } private void middleNameLabel_Click(object sender, EventArgs e) { } private void AgeLabel_Click(object sender, EventArgs e) { } } }
ad89fbc094465cdf3f4ee59580eb89e93b8019db
C#
rodrigoborgesmachado/devtools-topdown
/DevTools/Model/MD_Camposclasseretorno.cs
2.5625
3
using System; using System.Collections.Generic; using System.Data.Common; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Model { /// <summary> /// [CAMPOSCLASSERETORNO] Tabela da classe /// </summary> public class MD_CamposClasseRetorno { #region Atributos e Propriedades /// <summary> /// DAO que representa a classe /// </summary> public DAO.MD_CamposClasseRetorno DAO = null; #endregion Atributos e Propriedades #region Construtores public MD_CamposClasseRetorno(int codigo) { Util.CL_Files.WriteOnTheLog("MD_Camposclasseretorno()", Util.Global.TipoLog.DETALHADO); this.DAO = new DAO.MD_CamposClasseRetorno( codigo); } #endregion Construtores #region Métodos /// <summary> /// Método que retorna todas as rotas /// </summary> /// <param name="projeto">Código do projeto</param> /// <returns>Lista das tabelas</returns> public static List<MD_CamposClasseRetorno> RetornaRetornosCampoClasses(int codigoClasseRetorno) { string sentenca = "SELECT CAMPOS.CODIGO FROM CAMPOSCLASSERETORNO CAMPOS INNER JOIN ROTASREPOSITORY ROTA ON (ROTA.CODIGO = CAMPOS.CODIGOCLASSEREFERENTE) INNER JOIN CLASSERETORNOREPOSITORY RETORNO ON (RETORNO.ROTARETORNO = ROTA.CODIGO) WHERE RETORNO.CODIGO = " + codigoClasseRetorno; DbDataReader reader = DataBase.Connection.Select(sentenca); List<MD_CamposClasseRetorno> campos = new List<MD_CamposClasseRetorno>(); while (reader.Read()) { campos.Add(new MD_CamposClasseRetorno(int.Parse(reader["CODIGO"].ToString()))); } reader.Close(); return campos; } /// <summary> /// Método que retorna todas as rotas /// </summary> /// <param name="projeto">Código do projeto</param> /// <returns>Lista das tabelas</returns> public static List<MD_CamposClasseRetorno> RetornaRetornosCampoRota(int codigoClasseRetorno) { string sentenca = new DAO.MD_CamposClasseRetorno().table.CreateCommandSQLTable() + " WHERE CODIGOCLASSEREFERENTE = " + codigoClasseRetorno; DbDataReader reader = DataBase.Connection.Select(sentenca); List<MD_CamposClasseRetorno> campos = new List<MD_CamposClasseRetorno>(); while (reader.Read()) { campos.Add(new MD_CamposClasseRetorno(int.Parse(reader["CODIGO"].ToString()))); } reader.Close(); return campos; } #endregion Métodos } }
e67e9cb188ed96cc4ad3834517c9b1168e917b4f
C#
justinricheson/bogglesolver
/BoggleLib/PrefixTrie.cs
3.390625
3
using System; using System.Collections.Generic; namespace BoggleLib { public class PrefixTrie { private Node _root; public PrefixTrie() { _root = new Node(); } public bool WordStartsWith(string fragment) { if (string.IsNullOrEmpty(fragment)) return false; var n = _root; foreach (char c in fragment) { string key = c.ToString(); if (n.Nodes.ContainsKey(key)) n = n.Nodes[key]; else return false; } return true; } public void AddWord(string word) { if (string.IsNullOrEmpty(word)) return; var n = _root; foreach (char c in word) { string key = c.ToString(); if (!n.Nodes.ContainsKey(key)) n.Nodes.Add(key, new Node()); n = n.Nodes[key]; } } class Node { public Dictionary<string, Node> Nodes { get; private set; } public Node() { Nodes = new Dictionary<string, Node>( StringComparer.OrdinalIgnoreCase); } } } }
65899f780718c41c4ca582b749e71bc0d0f729f5
C#
Nixxis/ncs-client
/NixxisSupControls/NixxisSupervsionColumnDescriptions.cs
2.515625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections.ObjectModel; using System.Windows.Data; using System.Windows; using System.Windows.Controls; namespace Nixxis.Client.Supervisor { public class ColumnItemDescription { #region Enums public enum ColumnTypes { DataGridTextColumn, NixxisDataGridToggleDetailColumn, DataGridTemplateColumn, } public enum Categories { Default, Parameter, RealTime, History, Production, PeriodProduction, System, } #endregion #region Class Data private ColumnTypes m_Columntype = ColumnTypes.DataGridTextColumn; private IValueConverter m_Converter = null; private Visibility m_Visible = Visibility.Visible; private Categories m_Category = Categories.Default; private bool m_VisibleForUser = true; private string m_ControlTemplateKey; #endregion #region Properties /// <summary> /// The name of the column typically use as the name of the header in the datagrid /// </summary> public string ColumnName { get; set; } /// <summary> /// The description of the column. Extra information about this column, can be used as tooltip /// </summary> public string ColumnDescription { get; set; } /// <summary> /// Is the column default visible /// </summary> public Visibility Visible { get { return m_Visible; } set { m_Visible = value; } } /// <summary> /// Can a use select this field to make it visible /// </summary> public bool VisibleForUser { get { return m_VisibleForUser; } set { m_VisibleForUser = value; } } /// <summary> /// What is the binding value for this column. /// </summary> public string BindingValue { get; set; } /// <summary> /// >What is the category of this column /// </summary> public Categories Category { get { return m_Category; } set { m_Category = value; } } /// <summary> /// The converter to use for displaying this value /// </summary> public IValueConverter Convertor { get { return m_Converter; } set { m_Converter = value; } } /// <summary> /// What is the type of this column. This is the datagrid column type /// </summary> public ColumnTypes ColumnType { get { return m_Columntype; } set { m_Columntype = value; } } /// <summary> /// If this templatekey is filled it will be used to dispaly the data. For some columntypes it is mandatory (NixxisDataGridToggleDetailColumn and DataGridTemplateColumn) /// </summary> public string ControlTemplateKey { get { return m_ControlTemplateKey; } set { m_ControlTemplateKey = value; } } #endregion #region Members /// <summary> /// What is the text to display in the column selector /// </summary> /// <returns>Text to display</returns> public string ColumnSelectorText() { return this.Category + " " + this.ColumnName; } /// <summary> /// The override of the ToString value /// </summary> /// <returns>Returns the name of the column</returns> public override string ToString() { return this.ColumnName; } #endregion } public static class SupervisionColumns { private static List<ColumnItemDescription> m_Inbound = new List<ColumnItemDescription>(); public static List<ColumnItemDescription> Inbound { get { return m_Inbound; } } static SupervisionColumns() { InitInbound(); } private static void InitInbound() { m_Inbound.Clear(); m_Inbound.Add(new ColumnItemDescription() { Category = ColumnItemDescription.Categories.System, ColumnName = "", ColumnDescription = "", ColumnType = ColumnItemDescription.ColumnTypes.NixxisDataGridToggleDetailColumn, ControlTemplateKey = "NixxisInboundToggleButtonTemplate" }); #region Parameter m_Inbound.Add(new ColumnItemDescription() { Category = ColumnItemDescription.Categories.Parameter, ColumnName = "Id", BindingValue = "Id", Visible = Visibility.Hidden, ColumnDescription = "The unique identifier of the inbound activity." }); m_Inbound.Add(new ColumnItemDescription() { Category = ColumnItemDescription.Categories.Parameter, ColumnName = "Description", BindingValue = "Description", ColumnDescription = "Description of the activity." }); m_Inbound.Add(new ColumnItemDescription() { Category = ColumnItemDescription.Categories.Parameter, ColumnName = "GroupKey", BindingValue = "GroupKey", Visible = Visibility.Hidden, VisibleForUser = false, ColumnDescription = "" }); m_Inbound.Add(new ColumnItemDescription() { Category = ColumnItemDescription.Categories.Parameter, ColumnName = "CampaignId", BindingValue = "CampaignId", Visible = Visibility.Hidden, ColumnDescription = "The campaign identifier." }); m_Inbound.Add(new ColumnItemDescription() { Category = ColumnItemDescription.Categories.Parameter, ColumnName = "CampaignName", BindingValue = "CampaignName", ColumnDescription = "The name of the campaign." }); m_Inbound.Add(new ColumnItemDescription() { Category = ColumnItemDescription.Categories.Parameter, ColumnName = "MediaType", BindingValue = "MediaType", ColumnDescription = "" }); m_Inbound.Add(new ColumnItemDescription() { Category = ColumnItemDescription.Categories.Parameter, ColumnName = "MediaTypeId", BindingValue = "MediaTypeId", Visible = Visibility.Hidden, ColumnDescription = "" }); #endregion #region RealTime m_Inbound.Add(new ColumnItemDescription() { Category = ColumnItemDescription.Categories.RealTime, ColumnName = "ActiveContacts", BindingValue = "RealTime.ActiveContacts", ColumnDescription = "" }); m_Inbound.Add(new ColumnItemDescription() { Category = ColumnItemDescription.Categories.RealTime, ColumnName = "Closing", BindingValue = "RealTime.Closing", ColumnDescription = "" }); m_Inbound.Add(new ColumnItemDescription() { Category = ColumnItemDescription.Categories.RealTime, ColumnName = "SystemPreprocessing", BindingValue = "RealTime.SystemPreprocessing", Visible = Visibility.Hidden, ColumnDescription = "" }); m_Inbound.Add(new ColumnItemDescription() { Category = ColumnItemDescription.Categories.RealTime, ColumnName = "Ivr", BindingValue = "RealTime.Ivr", ColumnDescription = "" }); m_Inbound.Add(new ColumnItemDescription() { Category = ColumnItemDescription.Categories.RealTime, ColumnName = "Waiting", BindingValue = "RealTime.Waiting", ColumnDescription = "" }); m_Inbound.Add(new ColumnItemDescription() { Category = ColumnItemDescription.Categories.RealTime, ColumnName = "Online", BindingValue = "RealTime.Online", ColumnDescription = "" }); m_Inbound.Add(new ColumnItemDescription() { Category = ColumnItemDescription.Categories.RealTime, ColumnName = "WrapUp", BindingValue = "RealTime.WrapUp", ColumnDescription = "" }); m_Inbound.Add(new ColumnItemDescription() { Category = ColumnItemDescription.Categories.RealTime, ColumnName = "Overflowing", BindingValue = "RealTime.Overflowing", ColumnDescription = "" }); m_Inbound.Add(new ColumnItemDescription() { Category = ColumnItemDescription.Categories.RealTime, ColumnName = "Transfer", BindingValue = "RealTime.Transfer", ColumnDescription = "" }); m_Inbound.Add(new ColumnItemDescription() { Category = ColumnItemDescription.Categories.RealTime, ColumnName = "MaxQueueTime", BindingValue = "RealTime.MaxQueueTime", ColumnDescription = "" }); m_Inbound.Add(new ColumnItemDescription() { Category = ColumnItemDescription.Categories.RealTime, ColumnName = "ContactMsgSend", BindingValue = "RealTime.ContactMsgSend", Visible = Visibility.Hidden, ColumnDescription = "" }); m_Inbound.Add(new ColumnItemDescription() { ColumnName = "ContactMsgReceived", BindingValue = "RealTime.ContactMsgReceived", Visible = Visibility.Hidden, ColumnDescription = "" }); m_Inbound.Add(new ColumnItemDescription() { Category = ColumnItemDescription.Categories.RealTime, ColumnName = "AgentInReady", BindingValue = "RealTime.AgentInReady", ColumnDescription = "" }); m_Inbound.Add(new ColumnItemDescription() { Category = ColumnItemDescription.Categories.RealTime, ColumnName = "AlertLevel", BindingValue = "RealTime.AlertLevel", ColumnDescription = "" }); m_Inbound.Add(new ColumnItemDescription() { Category = ColumnItemDescription.Categories.RealTime, ColumnName = "NumericCustom1", BindingValue = "RealTime.NumericCustom1", ColumnDescription = "" }); m_Inbound.Add(new ColumnItemDescription() { Category = ColumnItemDescription.Categories.RealTime, ColumnName = "NumericCustom2", BindingValue = "RealTime.NumericCustom2", ColumnDescription = "" }); m_Inbound.Add(new ColumnItemDescription() { Category = ColumnItemDescription.Categories.RealTime, ColumnName = "NumericCustom3", BindingValue = "RealTime.NumericCustom3", ColumnDescription = "" }); m_Inbound.Add(new ColumnItemDescription() { Category = ColumnItemDescription.Categories.RealTime, ColumnName = "NumericCustom4", BindingValue = "RealTime.NumericCustom4", ColumnDescription = "" }); m_Inbound.Add(new ColumnItemDescription() { Category = ColumnItemDescription.Categories.RealTime, ColumnName = "NumericCustom5", BindingValue = "RealTime.NumericCustom5", ColumnDescription = "" }); m_Inbound.Add(new ColumnItemDescription() { Category = ColumnItemDescription.Categories.RealTime, ColumnName = "NumericCustom6", BindingValue = "RealTime.NumericCustom6", ColumnDescription = "" }); m_Inbound.Add(new ColumnItemDescription() { Category = ColumnItemDescription.Categories.RealTime, ColumnName = "NumericCustom7", BindingValue = "RealTime.NumericCustom7", ColumnDescription = "" }); m_Inbound.Add(new ColumnItemDescription() { Category = ColumnItemDescription.Categories.RealTime, ColumnName = "NumericCustom8", BindingValue = "RealTime.NumericCustom8", ColumnDescription = "" }); m_Inbound.Add(new ColumnItemDescription() { Category = ColumnItemDescription.Categories.RealTime, ColumnName = "NumericCustom9", BindingValue = "RealTime.NumericCustom9", ColumnDescription = "" }); m_Inbound.Add(new ColumnItemDescription() { Category = ColumnItemDescription.Categories.RealTime, ColumnName = "NumericCustom10", BindingValue = "RealTime.NumericCustom10", ColumnDescription = "" }); #endregion //<DataGridTextColumn Header="AgentId" Binding="{Binding AgentId}" /> } } }
426c3de6124ac3de5580da286029e8cd9f42bb60
C#
sebez/social-dance-jukebox
/csharp/Sources/SocialDanceJukebox.Domain/Calculs/SelecteurPlusDistantAvecLeMoinsDeVoisinsProche - Copier.cs
2.796875
3
using System; using System.Collections.Generic; using System.Linq; using SocialDanceJukebox.Domain.Calculs.Contracts; using SocialDanceJukebox.Domain.Dto; namespace SocialDanceJukebox.Domain.Calculs { /// <summary> /// Sélectionne le meilleur candidat en optimisant la distance avec les vecteurs restants. /// </summary> public class SelecteurMoinsDeVoisinsProchePlusDistant : IProchainVecteurSelecteur { public VecteurChanson Selectionne(VecteurChanson vecteurPrecedent, List<VecteurChanson> vecteursRestant, CalculData data) { /* Pour chaque vecteur restant, calcule celui qui a le plus de voisins proches */ var localDistanceSumMap = vecteursRestant.ToDictionary(v => v, v => vecteursRestant.Sum(w => data.MatriceSimilarite[v, w])); /* Groupe par somme croissante */ var groupByDistance = localDistanceSumMap.GroupBy(t => t.Value, t => t.Key).OrderBy(t => t.Key).ToList(); /* Prend le groupe avec les voisins les plus proches. */ var group = groupByDistance.First(); /* Prend l'élément le plus éloigné du vecteur précédent. */ var prochainVecteur = group.OrderBy(v => data.MatriceSimilarite[vecteurPrecedent, v]).Last(); return prochainVecteur; } } }
79d3ce5a0ac0c89ccf5187ad7937f0791aa0458e
C#
Calvin0630/GrapplingHook
/Assets/Resources/Scripts/HighScores.cs
2.515625
3
using UnityEngine; using System.Collections; using System.Collections.Generic; using System.Xml; using System.Xml.Serialization; using System.IO; using System; [Serializable] public class HighScores { [XmlArray("HighScores")] [XmlArrayItem(typeof(Score), ElementName = "ScoreElement")] public List<Score> list; //string path = "HighScores.xml"; public HighScores() { list = new List<Score>(); } public void AddScore(Score score) { list.Add(score); list.Sort(); ScoreManager.Write(); } public override string ToString() { string result = ""; for (int i=0;i<list.Count;i++) { result += list[i].ToString() + "\n"; } return result; } }
3617cf02ef23caf782120b619aa3b8e7923078f9
C#
bslupik/globalgamejam16
/Assets/Scripts/Utility/Countdown.cs
2.96875
3
using UnityEngine; using System.Collections; /// <summary> /// Wrapper class for IEnumerator Coroutines that simplifies pausing and restarting /// </summary> public class Countdown { //delegate types public delegate IEnumerator GetIEnumerator(); GetIEnumerator source; IEnumerator countdown; IEnumerator countdownWrapper; MonoBehaviour script; public bool active { get { return countdown != null && !paused; } } bool paused = false; public bool Paused { get { return paused; } } public Countdown(GetIEnumerator source, MonoBehaviour script) { this.source = source; this.script = script; } public Countdown(GetIEnumerator source, MonoBehaviour script, bool playOnAwake) : this(source, script) { if (playOnAwake) Play(); } public bool Play() { if (paused) { script.StartCoroutine(countdown); script.StartCoroutine(countdownWrapper); paused = false; return true; } else if (countdown == null) { countdownWrapper = CountdownWrapper(); script.StartCoroutine(countdownWrapper); return true; } return false; } public void Restart() { if (countdown != null) { paused = false; //the if to check if it's true is redundant script.StopCoroutine(countdown); script.StopCoroutine(countdownWrapper); } countdownWrapper = CountdownWrapper(); script.StartCoroutine(countdown); } public bool Pause() { if (active) { script.StopCoroutine(countdown); script.StopCoroutine(countdownWrapper); paused = true; return true; } return false; } public bool Stop() { if (countdown != null) { paused = false; //the if to check if it's true is redundant script.StopCoroutine(countdown); script.StopCoroutine(countdownWrapper); countdown = null; countdownWrapper = null; return true; } return false; } public IEnumerator CountdownWrapper() { countdown = source(); yield return script.StartCoroutine(countdown); countdown = null; } }
4e62cab9b15a87ec6e7eba7ab2e40e8ed17297fb
C#
stoneson/smartcore
/SmartCore.Services/Aop/TransactionAttribute.cs
2.703125
3
using System; using System.Collections.Generic; using System.Text; using System.Transactions; namespace SmartCore.Services.Attributes { /// <summary> /// 开启事务属性 /// </summary> /// <example>[Transaction]</example> /// <remarks>利用Autofac DynamicProxy+Castle 实现AOP事务 /// 优势主要表现在: /// 1.将通用功能从业务逻辑中抽离出来,就可以省略大量重复代码,有利于代码的操作和维护。 /// 2.在软件设计时,抽出通用功能(切面),有利于软件设计的模块化,降低软件架构的复杂程度。也就是说通用的功能就是一个单独的模块,在项目的主业务里面是看不到这些通用功能的设计代码的。 /// </remarks> [AttributeUsage(AttributeTargets.Method, Inherited = true)] public class TransactionAttribute : Attribute { /// <summary> /// 超时时间 /// </summary> public int Timeout { get; set; } /// <summary> /// 事务范围 /// </summary> public TransactionScopeOption ScopeOption { get; set; } /// <summary> /// 事务隔离级别 /// </summary> public IsolationLevel IsolationLevel { get; set; } public TransactionAttribute() { Timeout = 60; ScopeOption = TransactionScopeOption.Required; IsolationLevel = IsolationLevel.ReadCommitted; } } }
6c188b4d225b6135de081dbdb0a57d3d9fdbea1a
C#
Andreiiy/Sniffer_WPF
/IPHeader.cs
2.921875
3
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; namespace Sniffer_WPF { public class IPHeader { private byte byVersionAndHeaderLength; // Eight bits for version and header // length private byte byDifferentiatedServices; // Eight bits for differentiated // services private ushort usTotalLength; // Sixteen bits for total length private ushort usIdentification; // Sixteen bits for identification private ushort usFlagsAndOffset; // Eight bits for flags and frag. // offset private byte byTTL; // Eight bits for TTL (Time To Live) // Eight bits for the underlying private byte byProtocol; // protocol private short sChecksum; // Sixteen bits for checksum of the // header private uint uiSoursIPAdress; // Thirty two bit source IP Address private uint uiDestinationIPAdress; // Thirty two bit destination IP Address private byte byHeaderLength; private byte[] byIpData = new byte[4096]; public IPHeader(byte[] byBuffer, int nRecieved) { try { //Create MemoryStream out of the received bytes MemoryStream memoryStream = new MemoryStream(byBuffer, 0, nRecieved); //Next we create a BinaryReader out of the MemoryStream BinaryReader binariReader = new BinaryReader(memoryStream); //The first eight bits of the IP header contain the version and //header length so we read them byVersionAndHeaderLength = binariReader.ReadByte(); //The next eight bits contain the Differentiated services byDifferentiatedServices = binariReader.ReadByte(); //Next eight bits hold the total length of the datagram usTotalLength = (ushort)IPAddress.NetworkToHostOrder(binariReader.ReadInt16()); //Next sixteen have the identification bytes usIdentification = (ushort)IPAddress.NetworkToHostOrder(binariReader.ReadInt16()); //Next sixteen bits contain the flags and fragmentation offset usFlagsAndOffset = (ushort)IPAddress.NetworkToHostOrder(binariReader.ReadInt16()); //Next eight bits have the TTL value byTTL = binariReader.ReadByte(); //Next eight represent the protocol encapsulated in the datagram byProtocol = binariReader.ReadByte(); //Next sixteen bits contain the checksum of the header sChecksum = (short)IPAddress.NetworkToHostOrder(binariReader.ReadInt16()); //Next thirty two bits have the source IP address uiSoursIPAdress = (uint)IPAddress.NetworkToHostOrder(binariReader.ReadInt32()); //Next thirty two hold the destination IP address uiDestinationIPAdress = (uint)IPAddress.NetworkToHostOrder(binariReader.ReadInt32()); //Now we calculate the header length byHeaderLength = byVersionAndHeaderLength; //The last four bits of the version and header length field contain the //header length, we perform some simple binary arithmetic operations to //extract them byHeaderLength <<= 4; byHeaderLength >>= 4; //Multiply by four to get the exact header length byHeaderLength *= 4; //Copy the data carried by the datagram into another array so that //according to the protocol being carried in the IP datagram Array.Copy(byBuffer, byHeaderLength, //start copying from the end of the header byIpData, 0, usTotalLength - byHeaderLength); } catch { Console.WriteLine("Constructor IPHeader->ERROR"); } } public string VersionAndHeaderLength { get { return byVersionAndHeaderLength.ToString(); } } public string SourcePort { get { return byVersionAndHeaderLength.ToString(); } } public string DifferentiatedServices { get { return byDifferentiatedServices.ToString(); } } public string TotalLength { get { return usTotalLength.ToString(); } } public string Identification { get { return usIdentification.ToString(); } } public string FlagsAndOffset { get { return usFlagsAndOffset.ToString(); } } public string TTL { get { return byTTL.ToString(); } } public string Protocol() { if (byProtocol.ToString() == "6") return "TCP"; else if (byProtocol.ToString() == "17") return "UDP"; return null; } public string Checksum { get { return string.Format("0x{0:x2}", sChecksum); } } public string SoursIPAdress { get { return uiSoursIPAdress.ToString(); } } public string DestinationIPAdress { get { return uiDestinationIPAdress.ToString(); } } public byte[] Data { get { return byIpData; } } public int MessageLength() { return byHeaderLength; } } }
684ee04c58d6e4515bc4ff07156b061a1734f477
C#
vardars/ci-factory
/tags/1.0.0.51/Product/Production/Common/WebSpider/Spider/ResourceParser.cs
2.5625
3
namespace Zeta.WebSpider.Spider { #region Using directives. // ---------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Xml; using Sgml; using System.Text.RegularExpressions; // ---------------------------------------------------------------------- #endregion ///////////////////////////////////////////////////////////////////////// /// <summary> /// Parses a single HTML resource for links. /// </summary> internal class ResourceParser { #region Public methods. // ------------------------------------------------------------------ /// <summary> /// Constructor. /// </summary> /// <param name="settings">The settings.</param> /// <param name="uriInfo">The URI info.</param> /// <param name="textContent">Content of the text.</param> public ResourceParser( SpiderSettings settings, UriResourceInformation uriInfo, string textContent ) { _settings = settings; _uriInfo = uriInfo; _textContent = textContent; } /// <summary> /// Get all links from the text content. /// </summary> /// <returns></returns> public List<UriResourceInformation> ExtractLinks() { if ( string.IsNullOrEmpty( _textContent ) ) { return new List<UriResourceInformation>(); } else { XmlReader xml = GetDocReader( _textContent, _uriInfo.BaseUri ); List<UriResourceInformation> result = DoExtractLinks( xml, _uriInfo ); // Trace the extracted links. int index = 0; foreach ( UriResourceInformation information in result ) { Trace.WriteLine( string.Format( @"Extracted link {0}/{1}: Found '{2}' in document at URI '{3}'.", index + 1, result.Count, information.AbsoluteUri.AbsoluteUri, _uriInfo.AbsoluteUri.AbsoluteUri ) ); index++; } return result; } } // ------------------------------------------------------------------ #endregion #region Private methods. // ------------------------------------------------------------------ /// <summary> /// Does the extract links. /// </summary> /// <param name="xml">The XML.</param> /// <param name="uriInfo">The URI info.</param> /// <returns></returns> private List<UriResourceInformation> DoExtractLinks( XmlReader xml, UriResourceInformation uriInfo ) { List<UriResourceInformation> links = new List<UriResourceInformation>(); while ( xml.Read() ) { switch ( xml.NodeType ) { // Added 2006-03-27: Inside comments, too. case XmlNodeType.Comment: XmlReader childXml = GetDocReader( xml.Value, uriInfo.BaseUri ); List<UriResourceInformation> childLinks = DoExtractLinks( childXml, uriInfo ); links.AddRange( childLinks ); break; // A node element. case XmlNodeType.Element: string[] linkAttributeNames; UriType linkType; // If this is a link element, store the URLs to modify. if ( IsLinkElement( xml.Name, out linkAttributeNames, out linkType ) ) { while ( xml.MoveToNextAttribute() ) { links.AddRange( ExtractStyleUrls( uriInfo.BaseUriWithFolder, xml.Name, xml.Value ) ); foreach ( string a in linkAttributeNames ) { if ( string.Compare( a, xml.Name, true ) == 0 ) { string url = xml.Value; UriResourceInformation ui = new UriResourceInformation( _settings.Options, url, new Uri( url, UriKind.RelativeOrAbsolute ), uriInfo.BaseUriWithFolder, linkType ); bool isOnSameSite = ui.IsOnSameSite( uriInfo.BaseUri ); if ( (isOnSameSite || !_settings.Options.StayOnSite) && ui.IsProcessableUri ) { links.Add( ui ); } } } } } else { // Also, look for style attributes. while ( xml.MoveToNextAttribute() ) { links.AddRange( ExtractStyleUrls( uriInfo.BaseUriWithFolder, xml.Name, xml.Value ) ); } } break; } } return links; } /// <summary> /// Checks whether the given name is a HTML element (=tag) with /// a contained link. If true, linkAttributeNames contains a list /// of all attributes that are links. /// </summary> /// <returns>Returns true, if it is a link element, /// false otherwise.</returns> private static bool IsLinkElement( string name, out string[] linkAttributeNames, out UriType linkType ) { foreach ( LinkElement e in LinkElement.LinkElements ) { if ( string.Compare( name, e.Name, true ) == 0 ) { linkAttributeNames = e.Attributes; linkType = e.LinkType; return true; } } linkAttributeNames = null; linkType = UriType.Resource; return false; } /// <summary> /// Detects URLs in styles. /// </summary> /// <param name="baseUri">The base URI.</param> /// <param name="attributeName">Name of the attribute.</param> /// <param name="attributeValue">The attribute value.</param> /// <returns></returns> private List<UriResourceInformation> ExtractStyleUrls( Uri baseUri, string attributeName, string attributeValue ) { List<UriResourceInformation> result = new List<UriResourceInformation>(); if ( string.Compare( attributeName, @"style", true ) == 0 ) { if ( attributeValue != null && attributeValue.Trim().Length > 0 ) { MatchCollection matchs = Regex.Matches( attributeValue, @"url\s*\(\s*([^\)\s]+)\s*\)", RegexOptions.Singleline | RegexOptions.IgnoreCase ); if ( matchs.Count > 0 ) { foreach ( Match match in matchs ) { if ( match != null && match.Success ) { string url = match.Groups[1].Value; UriResourceInformation ui = new UriResourceInformation( _settings.Options, url, new Uri( url, UriKind.RelativeOrAbsolute ), baseUri, UriType.Resource ); bool isOnSameSite = ui.IsOnSameSite( baseUri ); if ( (isOnSameSite || !_settings.Options.StayOnSite) && ui.IsProcessableUri ) { result.Add( ui ); } } } } } } return result; } /// <summary> /// Gets the doc reader. /// </summary> /// <param name="html">The HTML.</param> /// <param name="baseUri">The base URI.</param> /// <returns></returns> private static XmlReader GetDocReader( string html, Uri baseUri ) { SgmlReader r = new SgmlReader(); if ( baseUri != null && !string.IsNullOrEmpty( baseUri.ToString() ) ) { r.SetBaseUri( baseUri.ToString() ); } r.DocType = @"HTML"; r.InputStream = new StringReader( html ); return r; } // ------------------------------------------------------------------ #endregion #region Private variables. // ------------------------------------------------------------------ private readonly SpiderSettings _settings; private readonly UriResourceInformation _uriInfo; private readonly string _textContent; // ------------------------------------------------------------------ #endregion } ///////////////////////////////////////////////////////////////////////// }
d4f8b1aca6b65b99e4591f6d6621bd32ee1c3666
C#
alezhu/.net-azLib
/Win32/activex.cs
2.546875
3
using System; using System.Runtime.InteropServices; namespace AZLib.Win32 { public class ActiveX { public const string Ole32Dll = "ole32.dll"; public const string OleAut32Dll = "oleaut32.dll"; public const string OlePro32Dll = "olepro32.dll"; //function FindWindowW(lpClassName, lpWindowName: PWideChar): HWND; stdcall; [DllImport(Windows.User32Dll,CharSet = CharSet.Unicode,EntryPoint="FindWindowW")] [return:MarshalAs(UnmanagedType.CustomMarshaler,MarshalType="AZLib.Win32.HWNDMarshaler")] private static extern HWND _FindWindow([MarshalAs(UnmanagedType.LPWStr)]string ClassName, [MarshalAs(UnmanagedType.LPWStr)]string WindowName); public static HWND FindWindow(string ClassName, string WindowName) { if (ClassName == String.Empty){ ClassName = null; } if (WindowName == String.Empty){ WindowName = null; } return _FindWindow(ClassName,WindowName); } //function FindWindowExW(Parent, Child: HWND; ClassName, WindowName: PWideChar): HWND; stdcall; [DllImport(Windows.User32Dll,CharSet = CharSet.Unicode,EntryPoint="FindWindowExW")] [return:MarshalAs(UnmanagedType.CustomMarshaler,MarshalType="AZLib.Win32.HWNDMarshaler")] private static extern HWND _FindWindowEx([MarshalAs(UnmanagedType.CustomMarshaler,MarshalType="AZLib.Win32.HWNDMarshaler")]HWND Parent, [MarshalAs(UnmanagedType.CustomMarshaler,MarshalType="AZLib.Win32.HWNDMarshaler")]HWND Child, [MarshalAs(UnmanagedType.LPWStr)]string ClassName, [MarshalAs(UnmanagedType.LPWStr)]string WindowName); public static HWND FindWindowEx(HWND Parent, HWND Child, string ClassName, string WindowName) { if (ClassName == String.Empty){ ClassName = null; } if (WindowName == String.Empty){ WindowName = null; } return _FindWindowEx(Parent, Child, ClassName,WindowName); } //function GetWindow(hWnd: HWND; uCmd: UINT): HWND; stdcall; [DllImport(Windows.User32Dll,CharSet = CharSet.Unicode,EntryPoint="GetWindow")] [return:MarshalAs(UnmanagedType.CustomMarshaler,MarshalType="AZLib.Win32.HWNDMarshaler")] private static extern HWND _GetWindow([MarshalAs(UnmanagedType.CustomMarshaler,MarshalType="AZLib.Win32.HWNDMarshaler")]HWND Wnd, [MarshalAs(UnmanagedType.U4)] GetWindowType uCmd); public static HWND GetWindow(HWND Wnd,GetWindowType uCmd) { return _GetWindow(Wnd,uCmd); } //function GetWindowTextW(hWnd: HWND; lpString: PWideChar; nMaxCount: Integer): Integer; stdcall; [DllImport(Windows.User32Dll,CharSet = CharSet.Unicode,EntryPoint="GetWindowTextW")] private static extern IntPtr _GetWindowText([MarshalAs(UnmanagedType.CustomMarshaler,MarshalType="AZLib.Win32.HWNDMarshaler")]HWND Wnd, [MarshalAs(UnmanagedType.LPWStr),Out]string lpString,int nMaxCount); public static string GetWindowText(HWND Wnd) { int length = GetWindowTextLength(Wnd); char[] chars = new char[length]; string res = new String(chars); _GetWindowText(Wnd,res,length+1); return res; } //function GetWindowTextLengthW(hWnd: HWND): Integer; stdcall; [DllImport(Windows.User32Dll,CharSet = CharSet.Unicode,EntryPoint="GetWindowTextLengthW")] private static extern IntPtr _GetWindowTextLength([MarshalAs(UnmanagedType.CustomMarshaler,MarshalType="AZLib.Win32.HWNDMarshaler")]HWND Wnd); public static int GetWindowTextLength(HWND Wnd) { IntPtr len = _GetWindowTextLength(Wnd); return (int) len; } //function GetWindowRect(hWnd: HWND; var lpRect: TRect): BOOL; stdcall; [DllImport(Windows.User32Dll,CharSet = CharSet.Unicode,EntryPoint="GetWindowRect")] private static extern IntPtr _GetWindowRect([MarshalAs(UnmanagedType.CustomMarshaler,MarshalType="AZLib.Win32.HWNDMarshaler")]HWND Wnd, [Out] RECT Rect); public static bool GetWindowRect(HWND Wnd, RECT Rect) { IntPtr p = _GetWindowRect(Wnd, Rect); return (p != IntPtr.Zero); } //function ShowWindow(hWnd: HWND; nCmdShow: Integer): BOOL; stdcall; [DllImport(Windows.User32Dll,CharSet = CharSet.Unicode,EntryPoint="ShowWindow")] private static extern IntPtr _ShowWindow([MarshalAs(UnmanagedType.CustomMarshaler,MarshalType="AZLib.Win32.HWNDMarshaler")]HWND Wnd, [MarshalAs(UnmanagedType.I4)] ShowWindowCommands nCmdShow); public static bool ShowWindow(HWND Wnd, ShowWindowCommands nCmdShow) { IntPtr p = _ShowWindow(Wnd, nCmdShow); return (p != IntPtr.Zero); } //function SendMessageW(hWnd: HWND; Msg: UINT; wParam: WPARAM; lParam: LPARAM): LRESULT; stdcall; [DllImport(Windows.User32Dll,CharSet = CharSet.Unicode,EntryPoint="SendMessageW")] public static extern IntPtr SendMessage([MarshalAs(UnmanagedType.CustomMarshaler,MarshalType="AZLib.Win32.HWNDMarshaler")]HWND Wnd, UInt32 Msg, IntPtr WParam, IntPtr lParam); public static int SendMessage(HWND Wnd, UInt32 Msg, int WParam, int lParam) { return (int) SendMessage(Wnd,Msg,new IntPtr(WParam), new IntPtr(lParam)); } [DllImport(Windows.User32Dll,CharSet = CharSet.Unicode,EntryPoint="SendMessageW")] public static extern IntPtr SendMessage([MarshalAs(UnmanagedType.CustomMarshaler,MarshalType="AZLib.Win32.HWNDMarshaler")]HWND Wnd, UInt32 Msg, [MarshalAs(UnmanagedType.I4)] MouseMessagesKeyState Keys, IntPtr lParam); }; }
9a95d61edd66e209c7296821c0155bec19ab254f
C#
mitkoostz/OnlineShop
/Core/Entities/ContactUs/ContactUsMessage.cs
2.671875
3
using System.ComponentModel.DataAnnotations; namespace Core.Entities.ContactUs { public class ContactUsMessage : BaseEntity { [Required] public string Name { get; set; } [Required] [RegularExpression(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", ErrorMessage = "The email is not valid!")] public string Email { get; set; } [Required] [RegularExpression(@"^\s*(?:\+?(\d{1,3}))?[-. (]*(\d{3})[-. )]*(\d{3})[-. ]*(\d{4})(?: *x(\d+))?\s*$", ErrorMessage = "The phone number is not valid!")] public string PhoneNumber { get; set; } [Required] [MinLength(30, ErrorMessage = "Minimum message characters 30.")] [MaxLength(600, ErrorMessage = "Maximum message characters 600!")] public string MessageText { get; set; } } }
037957f76647fef1ad1f652c6685747186688716
C#
DxGrumpzz/CustomToken
/Source/CustomToken.Server/HTTP handler/Request/HttpReqeustHandler.cs
3.53125
4
namespace CustomToken.Server { using System; using System.Linq; /// <summary> /// A class that is responsible for handling incoming HTTP requests /// </summary> public class HttpReqeustHandler { #region Constants /// <summary> /// An HTTP standard header end of line break /// </summary> private const string END_OF_LINE = "\r\n"; /// <summary> /// A constant that specifies a header's content length property /// </summary> private const string CONTENT_LENGTH_STRING = "Content-Length"; /// <summary> /// A constant that specifies a header's content length type /// </summary> private const string CONTENT_TYPE_STRING = "Content-Type"; #endregion /// <summary> /// Creates a new <see cref="HttpRequest"/> and fills it with data /// </summary> /// <param name="rawRequestString"> The raw header/request </param> /// <returns></returns> public HttpRequest CreateRequest(string rawRequestString) { // The receveid data as is string rawData = rawRequestString; // The data split after every break+newline character(s) var rawDataSplit = rawData.Split(END_OF_LINE); // Get HTTP method type var method = rawDataSplit.First().Split(" ")[0]; // Get the requested url as a single string var requestedUrl = rawDataSplit.First().Split(" ")[1]; // Split the url for every / var requestedUrlSplit = requestedUrl.Split('/', StringSplitOptions.RemoveEmptyEntries); // How much data is present in the content int contentLength = 0; // The type of the content string contentType = string.Empty; // The content as a raw string string rawContent = string.Empty; // Check if a content length header is present var contentLengthHeader = rawDataSplit.FirstOrDefault(header => header.Contains(CONTENT_LENGTH_STRING, StringComparison.OrdinalIgnoreCase)); // Check if a content type header is present var contentTypeHeader = rawDataSplit.FirstOrDefault(header => header.Contains(CONTENT_TYPE_STRING, StringComparison.OrdinalIgnoreCase)); // If request contains content length if (contentLengthHeader != null) { // Covnert the result to a string contentLength = Convert.ToInt32( // Split the header in 2 and get the 2nd result contentLengthHeader.Split(':')[1] // Remove empty strings .Replace(" ", "")); }; // If request contains content type if (contentTypeHeader != null) { // Split header in 2 and get the second result contentType = contentTypeHeader.Split(':')[1] // Replace empty strings .Replace(" ", ""); }; // If the end of the request isn't empty, meaning there is content if (string.IsNullOrWhiteSpace(rawDataSplit.Last()) == false) { // Get that content rawContent = rawDataSplit.Last(); }; return new HttpRequest() { RawData = rawData, RawDataSplit = rawDataSplit, Method = method, RequestedUrl = requestedUrl, RequestedUrlSplit = requestedUrlSplit, ContentLength = contentLength, ContentType = contentType, RawContent = rawContent, }; } }; };
37029667c90e8da96751868432f74ca25e928e8a
C#
chriscalviello/AddressValidation
/ApiUnitTesting/Services/Authentication/LocalAuthenticationServiceTest.cs
2.78125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text.Json; using Api.Models.User; using Api.Services.Authentication; using Xunit; namespace ApiUnitTesting.Services.Authentication { public class LocalAuthenticationServiceTest : IDisposable { private readonly LocalAuthenticationService sut; private readonly string filePath = "config/usersfortest.json"; public LocalAuthenticationServiceTest() { sut = new LocalAuthenticationService(filePath, "secret key for unit tests", 600); string json = @"[ { ""Username"": ""test"", ""Password"": ""123456"" }, { ""Username"": ""johndoe"", ""Password"": ""QWERTY"" } ]"; System.IO.File.WriteAllText(filePath, json); } public void Dispose() { System.IO.File.Delete(filePath); } [Fact] public void GivenNotExistingUsername_WhenSignin_ShouldReturnNull() { Assert.Null(sut.Signin(new Credentials("fake", "123456"))); } [Fact] public void GivenWrongPassword_WhenSignin_ShouldReturnNull() { Assert.Null(sut.Signin(new Credentials("test", "111111"))); } [Fact] public void GivenValidCredentials_WhenSignin_ShouldReturnValue() { var credential = new Credentials("test", "123456"); var loggedUser = sut.Signin(credential); Assert.NotNull(loggedUser); Assert.Equal("test", loggedUser.Username); Assert.NotNull(loggedUser.Token); Assert.NotEmpty(loggedUser.Token); } [Fact] public void GivenValidCredentials_WhenSignup_ShouldReturnValue() { var credential = new Credentials("newuser", "ASDFGH"); var loggedUser = sut.Signup(credential); Assert.NotNull(loggedUser); Assert.Equal("newuser", loggedUser.Username); Assert.NotNull(loggedUser.Token); Assert.NotEmpty(loggedUser.Token); } [Fact] public void GivenValidCredentials_WhenSignup_ShouldStoreCredentials() { var credential = new Credentials("newuser", "ASDFGH"); var loggedUser = sut.Signup(credential); var jsonString = System.IO.File.ReadAllText(filePath); var users = JsonSerializer.Deserialize<List<Credentials>>(jsonString); Assert.Contains(users, x => x.Username == credential.Username && x.Password == credential.Password); } [Fact] public void GivenExistingUsername_WhenSignup_ShouldThrow() { var credential = new Credentials("test", "123456"); Assert.Throws<InvalidOperationException>(() => sut.Signup(credential)); } } }
50d8cffee72c2a225eb3aceb74746134b986d698
C#
chenergy/jj-jc-project
/Assets/Scripts/MovingReflectionTrigger.cs
2.546875
3
using UnityEngine; using System.Collections; public class MovingReflectionTrigger: BasicReflectionTrigger { public float speed; public float maxSpeed; public Transform[] waypoints; private Vector3 targetPosition; private int currentWaypoint = 0; protected override void Start(){ this.targetPosition = this.waypoints [0].transform.position; } protected override void Update(){ Vector3 currentPosition = this.transform.position; if ((currentPosition - this.targetPosition).magnitude < 0.1f) { this.currentWaypoint++; this.currentWaypoint = this.currentWaypoint % waypoints.Length; this.targetPosition = this.waypoints [this.currentWaypoint].transform.position; } else { /*this.transform.position = Vector3.Lerp (this.transform.position, this.targetPosition, Time.deltaTime * this.speed);*/ this.transform.position += (this.targetPosition - this.transform.position).normalized * Time.deltaTime * this.speed; } } }
2d23a19cbf835d8e48bf85aa58e0a716268d1656
C#
NeatCrown/PaperMarioBattleSystem
/PaperMarioBattleSystem/PaperMarioBattleSystem/Classes/Collectibles/Items/SleepySheep.cs
2.796875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PaperMarioBattleSystem { /// <summary> /// The Sleepy Sheep item. It inflicts Sleep on all enemies. /// </summary> public sealed class SleepySheep : BattleItem, IStatusInflictingItem { public StatusChanceHolder[] StatusesInflicted { get; private set; } public SleepySheep() { Name = "Sleepy Sheep"; Description = "Targets all enemies and may cause them to fall asleep."; ItemType = ItemTypes.Damage; StatusesInflicted = new StatusChanceHolder[] { new StatusChanceHolder(100d, new SleepStatus(2)) }; SelectionType = TargetSelectionMenu.EntitySelectionType.All; EntityType = Enumerations.EntityTypes.Enemy; } } }
485e2cb33e0a619f4358022c6c71e1685348cf85
C#
Xushlin/PatternPracticeSimple
/PatternPractice/Adapter/ScoreOperation/App.cs
2.953125
3
using System; using System.ComponentModel; namespace PatternPractice.Adapter.ScoreOperation { [Description("7.Adapter")] public static class App { public static void Main() { Console.WriteLine("=============================="); Console.WriteLine("========Adapter ====="); Console.WriteLine("=============================="); IScoreOperation scoreOperation=ObjectBuildFactory<IScoreOperation>.Instance(ConfigManager.AdapterKey); int[] array = {50, 30, 56, 90, 100, 89, 80, 70, 60, 67, 88, 99, 95}; int[] result; int score; Console.WriteLine("Sort result:"); result = scoreOperation.Sort(array); var sortResult = string.Empty; for (var i = 0; i < result.Length; i++) { sortResult += result[i] + ","; } Console.WriteLine(sortResult); Console.WriteLine("Find score=90:"); score = scoreOperation.Search(result, 90); if (score != -1) { Console.WriteLine("Found the score=90 "); } else { Console.WriteLine("Not found the score=90 "); } Console.WriteLine("Find score=92:"); score = scoreOperation.Search(result, 92); if (score != -1) { Console.WriteLine("Found the score=90 "); } else { Console.WriteLine("Not found the score=92 "); } } } }
fcb5aa24b2e6e5bf3ce2ef0673660df98ab91f14
C#
Jaguararx/AutoPractice18
/COE.Core/Logging/COEHttpClientLogger.cs
3.0625
3
using System; using System.Text; namespace COE.Core.Logging { /// <summary> /// Logger class for HTTP requests /// </summary> public class COEHttpClientLogger : ICOEHttpClientLogger { private readonly ICOEMainLogger _logger; /// <summary> /// Initializes new instance of <see cref="DbLogger"/> that writes its message into underlying <see cref="ICOEMainLogger"/>. /// </summary> /// <param name="logger">Instance of <see cref="IMainLogger"/> class.</param> public COEHttpClientLogger(ICOEMainLogger logger) { _logger = logger; } /// <summary> /// Log http request starts executing. /// </summary> /// <param name="url">Url of API to call.</param> /// <param name="httpMethod">http method.</param> public void LogRequestStarting(string url, string httpMethod) { _logger.Log($"API {httpMethod} request starting. Url: {url}"); } /// <summary> /// Log http request starts executing. /// </summary> /// <param name="url">Url of API was call.</param> /// <param name="httpMethod">http method.</param> /// <param name="requestBody">Request body (for POST/PUT requests)</param> public void LogRequestStarting(string url, string httpMethod, string requestBody) { _logger.Log($"API {httpMethod} request starting. Url: {url}. Request body: {requestBody}"); } /// <summary> /// Log HTTP request has finished executing. /// </summary> /// <param name="url">Url of API was call.</param> /// <param name="httpMethod">http method.</param> /// <param name="result">Result object.</param> /// <param name="responseLength">Length of Response content in bytes.</param> /// <param name="period">Time spent on request.</param> public void LogRequestFinished(string url, string httpMethod, object result, int responseLength, TimeSpan period) { _logger.Log($"API {httpMethod} request finished. Url: {url}, Response length: {responseLength}, Time spent: {period.ToString("c")}"); } /// <summary> /// Log HTTP request failed with exception. /// </summary> /// <param name="ex">Exception.</param> public void LogHttpRequestFailed(Exception ex) { _logger.Error($"Http call failed. Exception: {FormatExceptionMessage(ex)}"); } private string FormatExceptionMessage(Exception ex) { StringBuilder errorMessage = new StringBuilder(); errorMessage.AppendFormat("\nSource: {0} \nMessage: {1} \nStackTrace: \n{2}", ex.Source, ex.Message, ex.StackTrace); return errorMessage.ToString(); } } }
f7eb6f2aad28915d0d70c859ec673be8c80c9de0
C#
Julie-lin/WorkflowSolutions
/Workflow/Thermo.Workflows/RealTime/DataHelperExtensions.cs
2.78125
3
using System.Activities.Tracking; using System.Collections.Generic; namespace AcquisitionActivities.RealTime { public static class DataHelperExtensions { public static T GetDataOrDefault<T>(this CustomTrackingRecord record, string key) { object value; if(record.Data.TryGetValue(key, out value)) { return (T) value; } return default(T); } public static T GetData<T>(this CustomTrackingRecord record, string key) { return (T)record.Data[key]; } } }
d334169eb449d9743ef4840194987453058a6acc
C#
swaphack/Kingdom
/Kindom/Assets/Football/Player/Team.cs
2.796875
3
using System; using System.Collections.Generic; namespace Football { /// <summary> /// 队伍 /// </summary> public class Team : Entity { public Team () { } void Start() { AddAgent<TeamAI> (); } /// <summary> /// 添加队员 /// </summary> /// <param name="player">Player.</param> public void AddPlayer(Player player) { if (player == null) { return; } this.AddChild (player); } /// <summary> /// 移除队员 /// </summary> /// <param name="player">Player.</param> public void RemovePlayer(Player player) { if (player == null) { return; } RemovePlayer (player.ID); } /// <summary> /// 移除队员 /// </summary> /// <param name="playerID">Player I.</param> public void RemovePlayer(int playerID) { Player player = this.FindChildByID<Player> (playerID); if (player == null) { return; } this.RemoveChild (player); } /// <summary> /// 查找球员 /// </summary> /// <returns>The play.</returns> /// <param name="playerID">Player I.</param> public Player FindPlay(int playerID) { return this.FindChildByID<Player> (playerID); } /// <summary> /// 替换球员 /// </summary> /// <param name="playerID">Player I.</param> /// <param name="newPlayer">New player.</param> public void Replace(int playerID, Player newPlayer) { this.RemovePlayer (playerID); this.AddPlayer (newPlayer); } } }
e6d9354a9d0db8dfa7fc342a86abec82299bb388
C#
Reillyminat/LexicalAnalyzator
/LexicalAnalyzerApplication/OperationTable.cs
3.09375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; namespace LexicalAnalyzerApplication { class OperationTable { List<string> _operations; public OperationTable() { _operations = new List<string>(); _operations.Add("+"); _operations.Add("-"); _operations.Add("*"); _operations.Add("/"); _operations.Add("="); _operations.Add("!="); _operations.Add("&&"); _operations.Add("||"); _operations.Add("<"); _operations.Add(">"); _operations.Add("=="); _operations.Add("<="); _operations.Add(">="); } public int Count { get => _operations.Count; } public bool Find(string str, ref int subClass) { string foud_name = _operations.Find(x => x == str); if (foud_name == null) return false; else { subClass=_operations.IndexOf(str); return true; } } } }
c6af3c920c2a15b8a0ee8a3473da9417568bcc2e
C#
2006-jun15-net/pamela-soulis-project1
/pamela-soulis-project1.Domain/Model/Customer.cs
2.953125
3
using System; using System.Collections.Generic; using System.Text; namespace pamela_soulis_project1.Domain.Model { /// <summary> /// Business Logic Customer, with a name and Id number /// </summary> public class Customer : BaseBusinessModel { private string _firstname; private string _lastname; //public Customer(string _firstname, string _lastname) //{ // FirstName = _firstname; // LastName = _lastname; //} /// <summary> /// Customer has a firstname /// </summary> public string FirstName { get => _firstname; set { if (string.IsNullOrEmpty(value)) { throw new ArgumentException("Customer firstname cannot be empty or null.", nameof(value)); } _firstname = value; } } /// <summary> /// And an ID number /// </summary> public int CustomerId { get; set; } /// <summary> /// And a lastname /// </summary> public string LastName { get => _lastname; set { if (string.IsNullOrEmpty(value)) { throw new ArgumentException("Customer lastname cannot be empty or null.", nameof(value)); } _lastname = value; } } public List<Orders> Orders { get; set; } = new List<Orders>(); } }
4b7b68d247d3f93156cc3d91539c1a7476fd708b
C#
tsdaemon/wikiDataRelationsParser
/ReloadConfigFromFile/Program.cs
2.75
3
using System.Collections.Generic; using System.IO; using System.Linq; using Core.Model; using MongoDB.Driver; namespace ReloadConfigFromFile { class Program { static List<string> ids = new List<string> { "person", "organization", "location" }; static void Main(string[] args) { var db = new MongoClient("mongodb://127.0.0.1:27017/").GetDatabase("wikidata"); var properties = db.GetCollection<Property>("property"); var categories = db.GetCollection<Category>("category"); var units = db.GetCollection<UnitPart>("unit"); units.DeleteMany(f => true); properties.DeleteMany(f => true); categories.DeleteMany(f => true); foreach (var id in ids) { var categoriesFile = "../../../categories_" + id + ".txt"; var propertiesFile = "../../../properties_" + id + ".txt"; using (var stream = new StreamReader(File.OpenRead(categoriesFile))) { categories.InsertMany(stream.ReadToEnd() .Split('\n') .Where(s => !(string.IsNullOrEmpty(s) || s[0] == '#')) .Select(s => { var vv = s.Trim().Split('\t'); var title = vv.Length > 1 ? vv[1] : null; return new Category { SectionId = id, Title = title, WikidataId = vv[0] }; })); } using (var stream = new StreamReader(File.OpenRead(propertiesFile))) { properties.InsertMany(stream.ReadToEnd() .Split('\n') .Where(s => !(string.IsNullOrEmpty(s) || s[0] == '#')) .Select(s => { var vv = s.Trim().Split('\t'); var qualifier = vv.Length > 2 ? vv[2] : null; var title = vv.Length > 1 ? vv[1] : null; return new Property { SectionId = id, Title = title, WikidataId = vv[0], Qualifier = qualifier }; })); } } } } }
4318a7f533bfc22ee4086e7975cf066e8bd3e28e
C#
mike-goodwin/securityheaders.io.badges
/Rater.cs
2.65625
3
using System; using System.Collections.Generic; using System.Configuration; using System.Diagnostics; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using HtmlAgilityPack; namespace SecurityHeaders.io.badges { internal class Rater { private const string SECURITYHEADERSIO = "SecurityHeadersIO"; private const string DEFAULT_RATING = "?"; private List<string> blackList = new List<string> { "securitybadges.azurewebsites.net" }; internal string Rate(string domain) { string rating; try { rating = Parse(GetPageContent(domain)); } catch(Exception e) { rating = DEFAULT_RATING; Trace.TraceError("Error ({0}) while rating domain {1}", e.Message, domain); } return rating; } private string GetPageContent(string domain) { string httpsDomain = WebUtility.UrlEncode(domain.ToLowerInvariant()); string uriTemplate = ConfigurationManager.AppSettings[SECURITYHEADERSIO]; string uri = string.Format(uriTemplate, httpsDomain); WebClient client = new WebClient(); return client.DownloadString(uri); } private string Parse(string pageContent) { HtmlDocument document = new HtmlDocument(); document.LoadHtml(pageContent); var score = document.DocumentNode .Descendants("div") .Where(d => d.Attributes.Contains("class") && d.Attributes["class"].Value.Contains("score")).Last() .Descendants("span").First().InnerText; return score; } } }