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
d35913db6357ba9aa44404e90965e2b5553b6251
C#
microcreationsuk/MicroCreations
/MicroCreations.Batch/MicroCreations.Batch.Common/Extensions.cs
2.734375
3
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using MicroCreations.Batch.Common.Operations; using Newtonsoft.Json; namespace MicroCreations.Batch.Common { [ExcludeFromCodeCoverage] public static class Extensions { public static int ToInt(this OperationArgument instance) { return int.TryParse(instance?.Value.ToString() ?? string.Empty, out var result) ? result : 0; } public static uint ToUInt(this OperationArgument instance) { return uint.TryParse(instance?.Value.ToString() ?? string.Empty, out var result) ? result : 0U; } public static short ToShort(this OperationArgument instance) { return short.TryParse(instance?.Value.ToString() ?? string.Empty, out var result) ? result : (short)0; } public static ushort ToUShort(this OperationArgument instance) { return ushort.TryParse(instance?.Value.ToString() ?? string.Empty, out var result) ? result : (ushort)0; } public static long ToLong(this OperationArgument instance) { return long.TryParse(instance?.Value.ToString() ?? string.Empty, out var result) ? result : 0L; } public static ulong ToULong(this OperationArgument instance) { return ulong.TryParse(instance?.Value.ToString() ?? string.Empty, out var result) ? result : 0UL; } public static double ToDouble(this OperationArgument instance) { return double.TryParse(instance?.Value.ToString() ?? string.Empty, out var result) ? result : 0D; } public static float ToFloat(this OperationArgument instance) { return float.TryParse(instance?.Value.ToString() ?? string.Empty, out var result) ? result : 0F; } public static decimal ToDecimal(this OperationArgument instance) { return decimal.TryParse(instance?.Value.ToString() ?? string.Empty, out var result) ? result : 0M; } public static byte ToByte(this OperationArgument instance) { return byte.TryParse(instance?.Value.ToString() ?? string.Empty, out var result) ? result : (byte)0; } public static sbyte ToSByte(this OperationArgument instance) { return sbyte.TryParse(instance?.Value.ToString() ?? string.Empty, out var result) ? result : (sbyte)0; } public static bool ToBool(this OperationArgument instance) { return bool.TryParse(instance?.Value.ToString() ?? string.Empty, out var result) && result; } public static T ToEnum<T>(this OperationArgument instance) { if (instance?.Value == null) return default(T); return Enum.IsDefined(typeof(T), instance.Value) ? (T)Enum.ToObject(typeof(T), instance.Value) : default(T); } public static T Convert<T>(this OperationArgument instance) { return JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(instance.Value)); } public static OperationArgument Get(this IEnumerable<OperationArgument> instance, string key) { return instance.FirstOrDefault(x => string.Equals(x.Name, key, StringComparison.OrdinalIgnoreCase)); } public static T Convert<T>(this OperationResult instance) { return JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(instance.Value)); } public static OperationResult Get(this IEnumerable<OperationResult> instance, string supportedOperationName) { return instance.FirstOrDefault(x => x.OperationName == supportedOperationName); } } }
6e0db4d8b1b8344681b2a8f939bf271a93c1cb77
C#
Ricky-G/Framework
/Source/MVC5/Boilerplate.Web.Mvc5/OpenGraph/ObjectTypes/Standard/OpenGraphMusicRadioStation.cs
2.921875
3
namespace Boilerplate.Web.Mvc.OpenGraph { using System; using System.Text; /// <summary> /// This object represents a 'radio' station of a stream of audio. The audio properties should be used to identify the location of the stream itself. /// This object type is part of the Open Graph standard. /// See http://ogp.me/ /// See https://developers.facebook.com/docs/reference/opengraph/object-type/music.radio_station/ /// </summary> public class OpenGraphMusicRadioStation : OpenGraphMetadata { /// <summary> /// Initializes a new instance of the <see cref="OpenGraphMusicRadioStation"/> class. /// </summary> /// <param name="title">The title of the object as it should appear in the graph.</param> /// <param name="image">The default image.</param> /// <param name="url">The canonical URL of the object, used as its ID in the graph.</param> public OpenGraphMusicRadioStation(string title, OpenGraphImage image, string url = null) : base(title, image, url) { } /// <summary> /// Gets or sets the URL to the page about the creator of the radio station. This URL must contain profile meta tags <see cref="OpenGraphProfile"/>. /// </summary> public string CreatorUrl { get; set; } /// <summary> /// Gets the namespace of this open graph type. /// </summary> public override string Namespace => "music: http://ogp.me/ns/music#"; /// <summary> /// Gets the type of your object. Depending on the type you specify, other properties may also be required. /// </summary> public override OpenGraphType Type => OpenGraphType.MusicRadioStation; /// <summary> /// Appends a HTML-encoded string representing this instance to the <paramref name="stringBuilder"/> containing the Open Graph meta tags. /// </summary> /// <param name="stringBuilder">The string builder.</param> public override void ToString(StringBuilder stringBuilder) { base.ToString(stringBuilder); stringBuilder.AppendMetaPropertyContentIfNotNull("music:creator", this.CreatorUrl); } } }
15941f7ebd5b0f307970b96eb4d05261a6735c8b
C#
dotsudo/plus-clean
/Communication/Packets/Outgoing/Rooms/FloorPlan/FloorPlanFloorMapComposer.cs
2.671875
3
namespace Plus.Communication.Packets.Outgoing.Rooms.FloorPlan { using System.Collections.Generic; using System.Linq; using HabboHotel.Items; internal class FloorPlanFloorMapComposer : ServerPacket { public FloorPlanFloorMapComposer(ICollection<Item> items) : base(ServerPacketHeader.FloorPlanFloorMapMessageComposer) { WriteInteger(items.Count); //TODO: Figure this out, it pushes the room coords, but it iterates them, x,y|x,y|x,y|and so on. foreach (var item in items.ToList()) { WriteInteger(item.GetX); WriteInteger(item.GetY); } } } }
a2a4a5a31b0e38c6a0a606a200fe23a52bfcbba5
C#
SergeiWal/OOTP
/практика/Task2_6/Task2_6/User.cs
3.390625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Runtime.Serialization; namespace Task2_6 { enum State { signin, signout } [Serializable] class User: IComparable { private string email; private int password; private State status; public string Email { get => email; set => email = value; } public int Password { get => password; set => password = value; } public State Status { get => status; set => status = value; } public User() { } public User(string mail, int password, State st) { Email = mail; Password = password; Status = st; } public int CompareTo(object obj) { if (obj is User) { User us = (User)obj; if (Password > us.Password) return 1; else if (Password < us.Password) return -1; else return 0; } else throw new Exception("Данные типы не подлежат сравнению..."); } public override bool Equals(object obj) { if (obj is User) { User us = (User)obj; if (us.Email == email) return true; else return false; } else return false; } public override int GetHashCode() { return (email.GetHashCode() + base.GetHashCode())/2; } public override string ToString() { return $"User(email:{email}, password:*********, status:{status})"; } } }
3ebf4deac5608113814ec9acf8d8f8d68ea255cc
C#
brunoesantana/RockPaperScissors
/RockPaperScissors/RockPaperScissors.Tests/Helper/TestHelper.cs
2.640625
3
using RockPaperScissors.Domain.Entity; using RockPaperScissors.Domain.Enum; using System.Collections.Generic; namespace RockPaperScissors.Tests.Helper { public static class TestHelper { public static IList<Player> BuildInvalidPlayerList() { return new List<Player> { new Player("Armando", Movement.Rock), new Player("Dave", Movement.Paper), new Player("Richard", Movement.Scissors) }; } public static IList<Player> BuildPlayerList() { return new List<Player> { new Player("Armando", Movement.Rock), new Player("Dave", Movement.Paper), new Player("Richard", Movement.Rock), new Player("Michael", Movement.Scissors) }; } public static Player BuildPlayer(string name, Movement movement) { return new Player(name, movement); } public static IList<string> BuildTournamentStringPlayerList() { return new List<string> { "Armando,P", "Dave,S", "Richard,R", "Michael,S", "Allen,S", "Omer,P", "David E.,R", "Richard X.,P" }; } public static IList<string> BuildSimpleStringPlayerList() { return new List<string> { "Armando,P", "Dave,S" }; } } }
1fe5fcdd91b4d1f2bd3da4f3cd90870ce9d49815
C#
JamesTheBard/csharp-updatelist
/ConsoleApplication1/ConsoleApplication1/Program.cs
2.890625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Runtime.InteropServices; using WUApiLib; namespace ConsoleApplication1 { class Program { static int tableWidth = 99; static int widthTwo = 70; static void Main(string[] args) { GetInstalledUpdates(); } static void GetInstalledUpdates() { UpdateSessionClass uSession = new UpdateSessionClass(); IUpdateSearcher uSearcher = uSession.CreateUpdateSearcher(); ISearchResult uResult = uSearcher.Search("IsInstalled=1 and Type='Software'"); List<IUpdate> results = new List<IUpdate>{ }; foreach (IUpdate update in uResult.Updates) { results.Add(update); } results = results.OrderBy(x => Convert.ToInt32(x.KBArticleIDs[0])) .ToList(); PrintRow("KB Article", "Description", "Severity"); PrintLine(); foreach (IUpdate update in results) { PrintRow(update.KBArticleIDs[0], update.Title, update.MsrcSeverity); } PrintLine(); } static void PrintLine() { Console.WriteLine(new string('-', tableWidth)); } static void PrintRow(params string[] columns) { columns[0] = columns[0].PadLeft(10, ' '); columns[1] = columns[1].Length > widthTwo ? columns[1].Substring(0, widthTwo - 3) + "..." : columns[1].PadRight(widthTwo, ' '); string rowFormat = String.Format("{0, 10} {1, -70} {2, -10}", columns); Console.WriteLine(rowFormat); } static string AlignCenter(string text, int width) { text = text.Length > width ? text.Substring(0, width - 3) + "..." : text; if (string.IsNullOrEmpty(text)) { return new string(' ', width); } else { return text.PadRight(width - (width - text.Length) / 2).PadLeft(width); } } } }
6f524d59b267e07fa69450f023576547b117d6d8
C#
claudevan/CadastroPedidos
/CadastroPedido.Entity/Migrations/Configuration.cs
2.515625
3
namespace CadastroPedido.Entity.Migrations { using CadastroPedidos.Models; using System.Collections.Generic; using System.Data.Entity.Migrations; internal sealed class Configuration : DbMigrationsConfiguration<Contexto.CadastroPedidosDataContext> { public Configuration() { AutomaticMigrationsEnabled = true; } protected override void Seed(Contexto.CadastroPedidosDataContext context) { #region "Adiciona Clientes" IList<Cliente> clientes = new List<Cliente>(); clientes.Add(new Cliente() { CPF = "123456789", Nome = "Cliente Padro" }); clientes.Add(new Cliente() { CPF = "987654321", Nome = "Ubisoft" }); clientes.Add(new Cliente() { CPF = "123789654", Nome = "Valve" }); clientes.Add(new Cliente() { CPF = "654789321", Nome = "Steam" }); foreach (var cliente in clientes) { context.Clientes.AddOrUpdate(cliente); } #endregion #region "Adiciona Produtos" IList<Produto> produtos = new List<Produto>(); produtos.Add(new Produto() { Descricao = "CS GO", Valor = 25.50M }); produtos.Add(new Produto() { Descricao = "R6 Siege", Valor = 100.00M }); produtos.Add(new Produto() { Descricao = "FIFA 2017", Valor = 100.75M }); produtos.Add(new Produto() { Descricao = "Destiny 2", Valor = 250.50M }); produtos.Add(new Produto() { Descricao = "Overwatch", Valor = 90.89M }); produtos.Add(new Produto() { Descricao = "GOD OF WAR", Valor = 50.74M }); foreach (var produto in produtos) { context.Produtos.AddOrUpdate(produto); } #endregion base.Seed(context); } } }
f1ea67f1c01284c6d69fbc3ae50fdb66248cd020
C#
KaelTian/CustomizeIOCAOP
/IOCDL.service/TestServiceA.cs
2.75
3
using IOCDL.Interface; using System; namespace IOCDL.Service { public class TestServiceA : ITestServiceA { public TestServiceA() { //Console.WriteLine($"{nameof(TestServiceA)} is constructored."); } public string ShowMessage(string message) { return $"Test Service A show message:{message}"; } public string ShowMessage111(string message) { Console.WriteLine("Message111 is:" + message); return $"11111111:{message}"; } } }
6923733991a37c33916b7da3c6001bf1e1b12500
C#
CCRed95/opieandanthonylive
/src/Ccr.Dnc.Core/Dnc/Core/Numerics/Ranges/SByteRange.cs
2.5625
3
using System; // ReSharper disable BuiltInTypeReferenceStyle namespace Ccr.Dnc.Core.Numerics.Ranges { public class SByteRange : IntegralRangeBase<SByte> { public SByteRange( SByte minimum, SByte maximum) : base( minimum, maximum) { } public static implicit operator SByteRange( Tuple<SByte, SByte> value) { return new SByteRange( value.Item1, value.Item2); } public static implicit operator SByteRange( (SByte, SByte) value) { return new SByteRange( value.Item1, value.Item2); } } }
999694b9c264e7ec2d3cb09e9952940ae8ae32f9
C#
MilanBartl/Advent-of-Code-2019
/AdventCode2019/Day22/Worker.cs
3.171875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace AdventCode2019.Day22 { public class Worker : IWorker { public object Work1() { //var deck = Enumerable.Range(0, 10).ToArray(); var deck = Enumerable.Range(0, 10007).ToArray(); var commands = input.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); foreach (string command in commands) deck = ProcessCommand(command, deck); // display result /*for (int i = 0; i < deck.Length; i++) { Console.Write($"{deck[i]} "); }*/ return deck.ToList().IndexOf(2019); } public object Work2() { var deck = Enumerable.Range(0, 10).ToArray(); //var deck = Enumerable.Range(0, 119315717510047).ToArray(); var commands = input.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); foreach (string command in commands) deck = ProcessCommand(command, deck); return deck.ToList().IndexOf(2020); } private int[] ProcessCommand(string command, int[] deck) { var buffer = new int[deck.Length]; if (command.Contains("increment")) { int increment = int.Parse(Regex.Match(command, @"-?\d+$").Value); int index = 0; if (increment > 0) { for (int i = 0; i < deck.Length; i++) { buffer[index] = deck[i]; if (index + increment > deck.Length) index = index + increment - deck.Length; else index += increment; } } else { for (int i = 0; i < deck.Length; i++) { buffer[index] = deck[i]; if (index + increment <= 0) index = index + increment + deck.Length; else index += increment; } } } else if (command.Contains("cut")) { int cut = int.Parse(Regex.Match(command, @"-?\d+$").Value); if (cut > 0) { int[] cutarray = new int[cut]; Array.Copy(deck, cutarray, cut); Array.Copy(deck, cut, buffer, 0, deck.Length - cut); Array.Copy(cutarray, 0, buffer, deck.Length - cut, cut); } else { cut = Math.Abs(cut); int[] cutarray = new int[cut]; Array.Copy(deck, deck.Length - cut, cutarray, 0, cut); Array.Copy(cutarray, 0, buffer, 0, cut); Array.Copy(deck, 0, buffer, cut, deck.Length - cut); } } else // new stack { for (int i = 0; i < deck.Length; i++) { buffer[i] = deck[deck.Length - 1 - i]; } } return buffer; } private const string test = @"deal into new stack cut -2 deal with increment 7 cut 8 cut -4 deal with increment 7 cut 3 deal with increment 9 deal with increment 3 cut -1"; private const string input = @"deal with increment 64 deal into new stack cut 1004 deal with increment 31 cut 5258 deal into new stack deal with increment 5 cut -517 deal with increment 67 deal into new stack cut -4095 deal with increment 27 cut 4167 deal with increment 30 cut -5968 deal into new stack deal with increment 40 deal into new stack deal with increment 57 cut -5128 deal with increment 75 deal into new stack deal with increment 75 cut -1399 deal with increment 12 cut -2107 deal with increment 9 cut -7110 deal into new stack deal with increment 14 cut 3318 deal into new stack deal with increment 57 cut -8250 deal with increment 5 deal into new stack cut 903 deal with increment 28 deal into new stack cut 2546 deal with increment 68 cut 9343 deal with increment 67 cut -6004 deal with increment 24 deal into new stack cut -816 deal with increment 66 deal into new stack deal with increment 13 cut 5894 deal with increment 43 deal into new stack cut 4550 deal with increment 67 cut -3053 deal with increment 42 deal into new stack deal with increment 32 cut -5985 deal with increment 18 cut -2808 deal with increment 44 cut -1586 deal with increment 16 cut 2173 deal with increment 53 cut 5338 deal with increment 48 cut -2640 deal with increment 36 deal into new stack deal with increment 13 cut -5520 deal with increment 61 cut -3199 deal into new stack cut 4535 deal with increment 17 cut -4277 deal with increment 72 cut -7377 deal into new stack deal with increment 37 cut 6665 deal into new stack cut 908 deal into new stack cut 9957 deal with increment 31 cut 9108 deal with increment 44 cut -7565 deal with increment 33 cut -7563 deal with increment 23 cut -3424 deal with increment 63 cut -3513 deal with increment 74"; } }
14fa15f024e9ac0d9e1833421588296f75c01f3f
C#
try-inf/XT-2018Q4
/Epam.Task02/Epam.Task02.2_Triangle/Program.cs
3.828125
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Epam.Task02._2_Triangle { class Program { static int ReadInt(string str) { while (true) { Console.Write(str); string intStr = Console.ReadLine(); bool check = int.TryParse(intStr, out int result); if (check) { return result; } else { Console.WriteLine("Wrong input"); } } } static bool TriangleCheck(Triangle t, out string mistake) { bool result = (((t.A + t.B) > t.C) && ((t.A + t.C) > t.B) && ((t.B + t.C) > t.A)); mistake = ""; if ((t.A + t.B) <= t.C) { mistake = string.Format("Side C({0}) should be less than Side A({1}) + Side B({2})", t.C, t.A, t.B); } else if ((t.A + t.C) <= t.B) { mistake = string.Format("Side B({0}) should be less than Side A({1}) + Side C({2})", t.B, t.A, t.C); } else if ((t.B + t.C) <= t.A) { mistake = string.Format("Side A({0}) should be less than Side B({1}) + Side C({2})", t.A, t.B, t.C); } return result; } static void Main(string[] args) { while (true) { Triangle myTriangle = new Triangle(); Console.WriteLine("Please enter the values of the three sides" + " of the triangle"); myTriangle.A = ReadInt("Side A: "); myTriangle.B = ReadInt("Side B: "); myTriangle.C = ReadInt("Side C: "); if (TriangleCheck(myTriangle, out string mistake)) { Console.WriteLine(); Console.WriteLine("Perimeter of the trinagle is {0:N2}", myTriangle.GetPerimeter()); Console.WriteLine("The area of the triangle is {0:N2}", myTriangle.GetArea()); break; } else { Console.WriteLine("The sum of the two sides of the triangle " + "should be greater than the third one. The error is that {0}", mistake); } } Console.WriteLine(Environment.NewLine + "Press any key to exit."); Console.ReadKey(); } } }
47dbadd851205ab60b41b37b30ed448b88537bda
C#
bpallan/RetryAndCircuitBreakerTestSolution
/ResiliencyTests/SimpleRetryExampleTests.cs
2.53125
3
using System; using System.Collections.Generic; using System.Net.Http; using System.Text; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.TestHost; using Microsoft.VisualStudio.TestTools.UnitTesting; using SimpleRetry; using TestHarnessApi; namespace ResiliencyTests { [TestClass] public class SimpleRetryExampleTests { private static string _url = "/api/retry"; private static TestServer _server; private static HttpClient _client; [ClassInitialize] public static void Initialize(TestContext context) { _server = new TestServer(new WebHostBuilder().UseStartup<Startup>()); _client = _server.CreateClient(); } [TestMethod] [ExpectedException(typeof(HttpRequestException))] public async Task ExecuteAsync_WhenRetriesZero_ThrowsException() { // call twice to ensure at least 1 call errors await CallApi(retries: 0); await CallApi(retries: 0); } [TestMethod] public async Task ExecuteAsync_WhenRetriesGreaterThanZero_ReturnsResult() { // call twice to ensure at least 1 call errors (and is handled by retry) var response = await CallApi(retries: 1); await CallApi(retries: 1); Assert.IsTrue(!string.IsNullOrWhiteSpace(response)); } private static async Task<string> CallApi(int retries) { string response = ""; await SimpleRetryExample.ExecuteAsync(numberOfRetries: retries, delay: TimeSpan.FromMilliseconds(1000), action: async () => { response = await _client.GetStringAsync(_url); }); return response; } } }
ac9334e6146a9cedae40d6017589e6335849123f
C#
IvanPahaniuka/Patterns
/Adapter/Adapter.cs
3.46875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Adapter { public static class Adapter { public static void Test() { Sailor sailor = new Sailor(); Boat boat = new Boat(); sailor.Travel(boat); Horse horse = new Horse(); sailor.Travel(new HorseToBoatAdapter(horse)); } } public class Sailor { public void Travel(IBoat boat) { boat.Sail(); } } public interface IBoat { void Sail(); } public class Boat: IBoat { public void Sail() { Console.WriteLine("Лодка отплывает"); } } public interface IAnimal { void Move(); } public class Horse: IAnimal { public void Move() { Console.WriteLine("Лошадь движется"); } } public class HorseToBoatAdapter: IBoat { private Horse horse; public HorseToBoatAdapter(Horse horse) { if (horse == null) throw new Exception(); this.horse = horse; } public void Sail() { horse.Move(); } } }
73e71e3b38d8128a27ea90319ec78f22f4eefc49
C#
dterracino/Cyjb
/UnitTestCyjb/UnitTestStringExt.cs
2.8125
3
using System.Linq; using Cyjb; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace UnitTestCyjb { /// <summary> /// <see cref="Cyjb.StringExt"/> 类的单元测试。 /// </summary> [TestClass] public class UnitTestStringExt { /// <summary> /// 对 <see cref="Cyjb.StringExt.UnescapeUnicode"/> 方法进行测试。 /// </summary> [TestMethod] public void TestUnescapeUnicode() { Assert.AreEqual("English or 中文 or \u0061\u0308 or \uD834\uDD60", "English or 中文 or \\u0061\\u0308 or \\uD834\\uDD60".UnescapeUnicode()); Assert.AreEqual("English or 中文 or \u0061\u0308 or \uD834\uDD60", "English or 中文 or \\u0061\\u0308 or \\U0001D160".UnescapeUnicode()); Assert.AreEqual("English or 中文 or \u0061\u0308 or \uD834\uDD60", "English or 中文 or \\u0061\\u0308 or \\uD834\\uDD60".UnescapeUnicode()); Assert.AreEqual("\x25 \u0061\u0308 or \uD834\uDD60\\", "\x25 \\u0061\\u0308 or \\uD834\\uDD60\\".UnescapeUnicode()); Assert.AreEqual("\x25\\x\x2\x25 \x25\x25 \u0061\u0308 or \uD834\uDD60\\", "\x25\\x\\x02\\x25 \\x25\\x25 \\u0061\\u0308 or \\uD834\\uDD60\\".UnescapeUnicode()); Assert.AreEqual(null, StringExt.UnescapeUnicode(null)); Assert.AreEqual("", "".UnescapeUnicode()); Assert.AreEqual("\\", "\\".UnescapeUnicode()); Assert.AreEqual("\\\\", "\\\\".UnescapeUnicode()); Assert.AreEqual("\\\x1", "\\\\x01".UnescapeUnicode()); Assert.AreEqual("\\\\\\", "\\\\\\".UnescapeUnicode()); Assert.AreEqual("\\\\\x1", "\\\\\\x01".UnescapeUnicode()); Assert.AreEqual("\\\\\\x1\\x2", "\\\\\\x1\\x2".UnescapeUnicode()); Assert.AreEqual("\\ab", "\\ab".UnescapeUnicode()); Assert.AreEqual("\\a\\b#556", "\\a\\b\\x23556".UnescapeUnicode()); Assert.AreEqual("\\a\\b\u23556", "\\a\\b\\u23556".UnescapeUnicode()); Assert.AreEqual("\\a\\b\\U23556", "\\a\\b\\U23556".UnescapeUnicode()); } /// <summary> /// 对 <see cref="Cyjb.StringExt.EscapeUnicode"/> 方法进行测试。 /// </summary> [TestMethod] public void TestEscapeUnicode() { Assert.AreEqual("English or \\u4E2D\\u6587 or a\\u0308 or \\uD834\\uDD60", "English or 中文 or \u0061\u0308 or \uD834\uDD60".EscapeUnicode()); Assert.AreEqual("English or \\u4E2D\\u6587 or a\\u0308 or \\uD834\\uDD60", "English or 中文 or \u0061\u0308 or \U0001D160".EscapeUnicode()); Assert.AreEqual("% a\\u0308 or \\uD834\\uDD60\\", "\x25 \u0061\u0308 or \uD834\uDD60\\".EscapeUnicode()); Assert.AreEqual(null, StringExt.EscapeUnicode(null)); Assert.AreEqual("", "".EscapeUnicode()); Assert.AreEqual("\\", "\\".EscapeUnicode()); Assert.AreEqual("\\\\", "\\\\".EscapeUnicode()); Assert.AreEqual("\\\\u0001", "\\\x1".EscapeUnicode()); Assert.AreEqual("\\\\\\", "\\\\\\".EscapeUnicode()); Assert.AreEqual("\\\\\\u0001", "\\\\\x1".EscapeUnicode()); Assert.AreEqual("\\ab", "\\ab".EscapeUnicode()); Assert.AreEqual("\\a\\b\\u23556", "\\a\\b\u23556".EscapeUnicode()); Assert.AreEqual("\\a\\b\\U23556", "\\a\\b\\U23556".EscapeUnicode()); } /// <summary> /// 对 <see cref="Cyjb.StringExt.Reverse"/> 方法进行测试。 /// </summary> [TestMethod] public void TestReverse() { Assert.AreEqual("hsilgnE", "English".Reverse()); Assert.AreEqual("文中hsilgnE", "English中文".Reverse()); Assert.AreEqual("\u0061\u0308文中hsilgnE", "English中文\u0061\u0308".Reverse()); Assert.AreEqual("\u0061\u0308文中hsilgnE\U0001D160", "\U0001D160English中文\u0061\u0308".Reverse()); } } }
fff9a98866f3a4035f57fc8f336cf01512579064
C#
kimyeongseong/DangerousOutside
/Assets/Script/InGame/Item/Cleaner.cs
2.546875
3
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Cleaner { /// <summary> 세탁기 인덱스 </summary> public int index; /// <summary> 세탁기에 들어있는 주민 </summary> public Citizen citizen = null; /// <summary> 세탁중인 시간(Citizen.cleanTime과 비교하여 takeTime이 더 크면 세탁기 탈출) </summary> public float takeTime; /// <summary> 세탁기 동작 상태 </summary> public CleanerState cleanerState = CleanerState.Idle; public void CitizenOn(Citizen citizen) { this.citizen = citizen; this.citizen.cleanerOn = true; cleanerState = CleanerState.CitizenReady; } public void SetState(CleanerState cleanerState) { this.cleanerState = cleanerState; if (cleanerState == CleanerState.Cleaning) { takeTime = 0; } else if (cleanerState == CleanerState.CleaningEnd) { citizen.cleanerOn = false; Tile tile = GameManager.Ins.tileController.tiles[0, 4]; //var tile = GameObject.FindObjectOfType<TileController>().tiles[0, 4]; //citizen.transform.position = tile.transform.position; //citizen.pos = tile.pos; citizen.gameObject.SetActive(true); citizen.ChangeColor(CitizenColor.White); citizen.ResetPos(tile); citizen.GoHome(); //citizen.StartFSM(); /* if (citizen.Home != null) { citizen.SetCitizenHome(citizen.Home); } else { citizen.ChangePattern(); } */ citizen = null; cleanerState = CleanerState.Idle; } } } public enum CleanerState { /// <summary> 대기상태 </summary> Idle, /// <summary> 주민 픽업 하러 가는중 </summary> CitizenReady, /// <summary> 세탁중 </summary> Cleaning, /// <summary> 세탁 끝 </summary> CleaningEnd }
116b38f720066525da352542f96efcc1b3b7152f
C#
kozlyakovskaya-tatsiana/CarRentalAngular
/CarRental.Api/CarRental.DAL/Repositories/Realization/LocationRepository.cs
2.640625
3
using System; using System.Linq; using System.Threading.Tasks; using CarRental.DAL.EFCore; using CarRental.DAL.Entities; namespace CarRental.DAL.Repositories.Realization { public class LocationRepositoryBase : RepositoryBase<Location>, ILocationRepository { public LocationRepositoryBase(ApplicationContext context) : base(context) {} public async Task<Location> GetLocationByAddressAsync(string address) { return (await GetAsync()).FirstOrDefault(loc => loc.Address.Equals(address, StringComparison.OrdinalIgnoreCase)); } } }
8598831502038f18727634ac9c4bfcffef566eae
C#
Nimmi-Ghetia/soa-project
/Client/Client/methods/GetBooking.cs
2.609375
3
using Client.models; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Web; using System.Web.UI.WebControls; using System.Xml; namespace Client.methods { public class GetBooking { public Book GetBook(int id) { Book m = null; string y = ""; try { String uri = "http://107.170.65.250:8080/Hello1/webresources/book/" + id; HttpWebRequest req = WebRequest.Create(uri) as HttpWebRequest; req.KeepAlive = false; req.Method = "GET";//Method.ToUpper(); HttpWebResponse resp = req.GetResponse() as HttpWebResponse; Encoding enc = System.Text.Encoding.GetEncoding(1252); StreamReader loResponseStream = new StreamReader(resp.GetResponseStream(), enc); // string Response = loResponseStream.ReadToEnd(); XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(resp.GetResponseStream()); // return (xmlDoc); loResponseStream.Close(); resp.Close(); TreeNode root = new TreeNode(xmlDoc.DocumentElement.Name); foreach (XmlNode node in xmlDoc.DocumentElement.ChildNodes) // for each <testcase> node { if (node.HasChildNodes) { m= new Book(); foreach (XmlNode n in node.ChildNodes) { try { string i = n.InnerText + ""; // y += i; switch (n.Name) { case "book_id": m.setBook_id(Int32.Parse(i)); //y += m.getName(); break; case "cin_id": m.setCin_id(Int32.Parse(i)); //y += m.getCat_id(); break; case "mov_id": m.setMov_id(Int32.Parse(i)); //y += m.getMov_id(); break; case "no_of_seats": m.setNo_of_seats(Int32.Parse(i)); //y += m.getPrice(); break; case "total": m.setTotal(Int32.Parse(i)); //y += m.getRating(); break; case "date": m.setDate(DateTime.Parse(i)); //y += m.getRelease_date(); break; } } catch (Exception exq) { y += (exq.Message.ToString()); } } y += m.ToString(); y += "\n\n"; //ml.Add(m); } } } catch (Exception ex) { y += (ex.Message.ToString()); } return m; } public int getsize() { string i=""; string size = ""; try { string uri = "http://107.170.65.250:8080/Hello1/webresources/city/book"; HttpWebRequest req = WebRequest.Create(uri) as HttpWebRequest; req.KeepAlive = false; req.Method = "GET";//Method.ToUpper(); HttpWebResponse resp = req.GetResponse() as HttpWebResponse; Encoding enc = System.Text.Encoding.GetEncoding(1252); StreamReader loResponseStream = new StreamReader(resp.GetResponseStream(), enc); // string Response = loResponseStream.ReadToEnd(); XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(resp.GetResponseStream()); // return (xmlDoc); loResponseStream.Close(); resp.Close(); TreeNode root = new TreeNode(xmlDoc.DocumentElement.Name); // Node n=root size = xmlDoc.DocumentElement.InnerText; foreach (XmlNode node in xmlDoc.DocumentElement.ChildNodes) // for each <testcase> node { if (node.HasChildNodes) { //m = new Book(); foreach (XmlNode n in node.ChildNodes) { try { i = n.InnerText + ""; } catch (Exception exq) { //y += (exq.Message.ToString()); } } //y += m.ToString(); //y += "\n\n"; //ml.Add(m); } } } catch (Exception ex) { //y += (ex.Message.ToString()); } return Int32.Parse(size); } } }
6e08fe9bb0d2020172cbfd229753f24e7e4d7748
C#
shendongnian/download4
/code5/963794-24399197-67989368-2.cs
3.359375
3
using System; public class Program { public static void Main() { string s1=@"[q:6][ilvl:70](randomword)"; var tmp = s1.Split(new string [] {":","]" }, StringSplitOptions.None); string res1 = tmp[1]; string res2 = tmp[3]; string res3 = s1.Split(new string [] {"](",")" }, StringSplitOptions.None)[1]; Console.WriteLine("1 -> "+res1); Console.WriteLine("2 -> "+res2); Console.WriteLine("3 -> "+res3); } }
38a61759142c53dbe1fa71112e321b17ef916ac1
C#
adrianf223/DW.CodedUI
/DW.CodedUI/Utilities/DynamicSleep.cs
2.515625
3
#region License /* The MIT License (MIT) Copyright (c) 2012-2018 David Wendland Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE */ #endregion License using System.Threading; using DW.CodedUI.Internal; namespace DW.CodedUI.Utilities { /// <summary> /// Holds methods for a dynamic sleep. /// </summary> public static class DynamicSleep { /// <summary> /// Suspends the current thread for a specified time in milliseconds. The time can be adjusted in the <see cref="DW.CodedUI.CodedUIEnvironment.SleepSettings" />.Default. /// </summary> public static void Wait() { Wait(CodedUIEnvironment.SleepSettings.Default); } /// <summary> /// Suspends the current thread for a specified time in milliseconds. The time can be adjusted in the <see cref="DW.CodedUI.CodedUIEnvironment.SleepSettings" />. /// </summary> /// <param name="time">The length of time to suspend.</param> public static void Wait(Time time) { var milliseconds = 0; switch (time) { case Time.VeryShort: milliseconds = CodedUIEnvironment.SleepSettings.VeryShort; break; case Time.Short: milliseconds = CodedUIEnvironment.SleepSettings.Short; break; case Time.Medium: milliseconds = CodedUIEnvironment.SleepSettings.Medium; break; case Time.Long: milliseconds = CodedUIEnvironment.SleepSettings.Long; break; case Time.VeryLong: milliseconds = CodedUIEnvironment.SleepSettings.VeryLong; break; } Wait(milliseconds); } /// <summary> /// Suspends the current thread for a specified time in milliseconds. /// </summary> /// <param name="milliseconds">The time to suspend in milliseconds.</param> public static void Wait(int milliseconds) { LogPool.Append("Wait {0} milliseconds.", milliseconds); Thread.Sleep(milliseconds); } } }
316c70a033328abaa192362e2bbc9533c5e62738
C#
GDKsoftware/GitBitter
/GitBitterEdit/EditPackageDetails.xaml.cs
2.625
3
namespace GitBitterEdit { using System.Windows; using GitBitterLib; /// <summary> /// Interaction logic for EditDetails.xaml /// </summary> public partial class EditPackageDetails : Window { private Package package = null; private Package packageCopy = null; public EditPackageDetails() { InitializeComponent(); } public void SetObject(Package package) { this.package = package; packageCopy = (Package)package.Clone(); DataContext = packageCopy; } protected void Save() { package.Folder = packageCopy.Folder; package.Repository = packageCopy.Repository; package.Branch = packageCopy.Branch; } private void BtnOk_Click(object sender, RoutedEventArgs e) { Save(); DialogResult = true; } private void BtnCancel_Click(object sender, RoutedEventArgs e) { DialogResult = false; } } }
c577df70dcec0f118bae64f2284ccdc064f0b4dd
C#
Samin705/School-Management-System-Using-Web-Api-Jquerry-Entity-Framework
/Final_Project_APWDN_SMS/Repository/AdminRepository.cs
2.515625
3
using Final_Project_APWDN_SMS.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Final_Project_APWDN_SMS.Repository { public class AdminRepository:Repository<Admin>,IAdminrepository { public string GetNewTeacherID() { var oldID = (from Teachers in data.Teachers orderby Teachers.id descending select Teachers.teacherid).Take(1).FirstOrDefault(); string toBreak = oldID.ToString(); string[] idList = toBreak.Split('-');//20-0000-01 string id1 = idList[0]; string id2 = idList[1]; string id3 = idList[2]; int idInc = Convert.ToInt32(id2); idInc = idInc + 1; id2 = idInc.ToString("D" + 4); string newID = id1 + "-" + id2 + "-" + id3; return newID; } public string GetNewStudentID() { var oldID = (from Students in data.Students orderby Students.id descending select Students.studentid).Take(1).FirstOrDefault(); string toBreak = oldID.ToString(); string[] idList = toBreak.Split('-');//20-0000-01 string id1 = idList[0]; string id2 = idList[1]; string id3 = idList[2]; int idInc = Convert.ToInt32(id2); idInc = idInc + 1; id2 = idInc.ToString("D" + 4); string newID = id1 + "-" + id2 + "-" + id3; return newID; } public Admin GetInfo(string id) { return this.data.Admins.Where(x => x.adminid == id).FirstOrDefault(); } public void ManualUpdate(Admin ad, string id) { Admin A = data.Admins.Where(a => a.adminid == id).FirstOrDefault(); A.adminid = id; A.adminname = ad.adminname; A.adminpassword = ad.adminpassword; data.SaveChanges(); } } }
c3bad4426a768b8347341e27fda5a5e5fd879463
C#
ravisinghunnao/Xamarin.Forms.CustomControls
/CustomControls/CircleView.cs
2.984375
3
using System; using System.Runtime.CompilerServices; using Xamarin.Forms; namespace HS.Controls { public class CircleView : AbsoluteLayout { public double DotSize { get; set; } public Color LineColor { get; set; } protected override void OnPropertyChanged([CallerMemberName] string propertyName = null) { base.OnPropertyChanged(propertyName); switch (propertyName.ToUpper()) { case "WIDTH": case "HEIGHT": RenderControl(); break; default: break; } } private void RenderControl() { try { Children.Clear(); double Radius = Height / 2; if (Width < Height) { Radius = Width / 2; } for (double i = 0.0; i < 360.0; i += 1) { double angle = i * System.Math.PI / 180; int x = (int)(150 + Radius * System.Math.Cos(angle)); int y = (int)(150 + Radius * System.Math.Sin(angle)); putpixel( x, y); } } catch (Exception ex) { throw ex; } } private void putpixel(int x, int y) { BoxView fpx = new BoxView { BackgroundColor = LineColor }; fpx.HeightRequest = DotSize; fpx.WidthRequest = DotSize; Children.Add(fpx); Rectangle FirstPoint = new Rectangle(x, y, DotSize, DotSize); SetLayoutBounds(fpx, FirstPoint); } } }
e33f6d579fcb12b9dd9e2414645a41df8f8264b9
C#
MadalinaFN/AF-Curs
/Curs10/Program.cs
3.40625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Curs10 { class Program { static void Main(string[] args) { //FactoriPrimi(); //FactoriPrimi1(); } private static void FactoriPrimi1() { Console.Write(nrfp(90)); Console.WriteLine(); } static int nrfp(int n) { int max = 0; int poz = 0; for (int i = 1; i <= n; i++) { int tmp = fp(i); if (max < tmp) { max = tmp; poz = i; } } return poz; } private static void FactoriPrimi() { Console.Write("= " + fp(90)); Console.WriteLine(); } static int fp(int x) { int d = 2; int nr = 0; while (x != 1) { if (x % d == 0) { nr++; } while (x % d == 0) { x /= d; //Console.Write(d + " "); } if (d == 2) { d++; } else d += 2; } return nr; } } }
b6b0eaa94d21db9193daf18ca27df04ad92a5947
C#
gbuchholcz/ProjectEulerPlus-CSharp
/Solutions/Challenges/Euler22.cs
3.5625
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Solutions.Challenges { class Euler22 { static void main(String[] args) { using (System.IO.StreamReader input = new System.IO.StreamReader(Console.OpenStandardInput())) using (System.IO.StreamWriter output = new System.IO.StreamWriter(Console.OpenStandardOutput())) { Solve(input, output); } } private static void Solve(System.IO.TextReader input, System.IO.TextWriter output) { SortedSet<string> names = new SortedSet<string>(); for (int N = int.Parse(input.ReadLine()); N > 0; --N) { names.Add(input.ReadLine().Trim().ToUpper()); } Dictionary<string, int> results = new Dictionary<string, int>(); int i = 0; foreach (string name in names) { results.Add(name, GetNameHash(++i, name)); } for (int N = int.Parse(input.ReadLine()); N > 0; --N) { output.WriteLine(results[input.ReadLine().Trim().ToUpper()]); } } private static int GetNameHash(int i, string name) { int hash = 0; for (int j = 0; j < name.Length; ++j) { hash += (1 + name[j] - 'A'); } return i * hash; } public static void Test() { string inputData = @"5 ALEX LUIS JAMES BRIAN PAMELA 1 PAMELA"; using (System.IO.StringReader input = new System.IO.StringReader(inputData)) using (System.IO.StreamWriter output = new System.IO.StreamWriter(Console.OpenStandardOutput())) { Solve(input, output); } } } }
743bb111de65728702c5cff92d208a01bd4bdee0
C#
TorsteinUtne/FigmentAPI
/Util/StringExtensions.cs
2.65625
3
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace PowerService.Util { internal static class StringExtensions { internal static string ToCamelCase(this string value) { if (string.IsNullOrEmpty(value)) return value; return char.ToLowerInvariant(value[0]) + value.Substring(1); } } }
8025880b51f0da2951a01dc14c399161816de0d9
C#
Tolkata99/CSharp-Advanced
/CreateStackTest/03.StackSum/Program.cs
3.609375
4
using System; using System.Collections.Generic; using System.Linq; namespace _03.StackSum { class Program { static void Main(string[] args) { int[] receive = Console.ReadLine().Split().Select(int.Parse).ToArray(); Stack<int> stack = new Stack<int>(receive); string comand = Console.ReadLine().ToLower(); while (comand != "end") { string[] tokens = comand.Split(); if (tokens[0] == "add") { int firstAdd = int.Parse(tokens[1]); int secondAdd = int.Parse(tokens[2]); stack.Push(firstAdd); stack.Push(secondAdd); } else if (tokens[0] == "remove") { int removeCount = int.Parse(tokens[1]); if (removeCount <= stack.Count) { for (int i = 0; i < removeCount; i++) { stack.Pop(); } } } comand = Console.ReadLine().ToLower(); } int result = 0; while (stack.Count > 0) { result += stack.Pop(); } Console.WriteLine($"Sum: {result}"); } } }
ba86ae6b288f6c4a99b24f16c4fc728d46ced6e3
C#
Cdelim/Rope-Game
/Assets/Scripts/ButtonsScript.cs
2.53125
3
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ButtonsScript : MonoBehaviour { [HideInInspector] GameObject[] buttons; void Awake() { buttons = GameObject.FindGameObjectsWithTag("Button"); } public bool isHereFill(Vector3 position) { foreach (GameObject button in buttons) { if (button!=null && Vector3.Distance(button.transform.position, position) < 0.5f) return true; } return false; } public void deleteButton(GameObject button) { List<GameObject> tempList = new List<GameObject>(buttons); tempList.Remove(button.gameObject); buttons = tempList.ToArray(); } }
33ef09fda58ccefffc16ba373c86da21ea994cd3
C#
JediMasterSam/API.Builder
/Api.Builder/Status Codes/400/PayloadTooLargeAttribute.cs
2.828125
3
using System; using Microsoft.AspNetCore.Mvc; namespace Api.Builder { /// <summary> /// The server is refusing to process a request because the request payload is larger than the server is willing or able to process. /// </summary> [AttributeUsage(AttributeTargets.Method, Inherited = false)] public class PayloadTooLargeAttribute : ProducesResponseTypeAttribute { /// <summary> /// Creates a new instance of <see cref="PayloadTooLargeAttribute"/>. /// </summary> public PayloadTooLargeAttribute() : base(413) { } /// <summary> /// Creates a new instance of <see cref="PayloadTooLargeAttribute"/>. /// </summary> /// <param name="type">Response type.</param> public PayloadTooLargeAttribute(Type type) : base(type, 413) { } } }
081d63f945f53522bcdc3bbc83e04f2b6938462a
C#
bradbread/Research-and-apply-emerging-web-technology-trends-Challenge-2
/Shapes/Shapes/RightAngle.cs
3.1875
3
using System; using System.Collections.Generic; using System.Text; namespace Shapes { public class RightAngle : Triangle, IShapeCalc { public RightAngle(double pSideLength1, double pSideLength2) { SideLength1 = pSideLength1; SideLength2 = pSideLength2; SideLength3 = Math.Sqrt((SideLength1 * SideLength1) + (SideLength2 * SideLength2)); } public double GetArea() { return (SideLength1 * SideLength2) / 2; } public double GetPerimeter() { return SideLength1 + SideLength2 + SideLength3; } public override double Operation1() { throw new NotImplementedException(); } public void SetHypotenuse() { throw new NotImplementedException(); } } }
2ba3d5508fa403b4a438bef2047078b5896427e1
C#
alexismoura/CertificWeb
/CertificBr.Data/EntityFramework/Repositories/Containers/CertificadoRepository.cs
2.5625
3
using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Text; using CertificBr.Data.EntityFramework.Contexts; using CertificBr.Data.EntityFramework.Entity.Containers; namespace CertificBr.Data.EntityFramework.Repositories.Containers { public class CertificadoRepository { protected readonly GenDbContext _dbContext; protected readonly DbSet<Certificado> _dbSet; public CertificadoRepository(string stringConection) { _dbContext = new GenDbContext(stringConection); _dbSet = _dbContext.Set<Certificado>(); } #region Metodos sincronos public IEnumerable<Certificado> List() { return _dbSet.ToList(); } public void Dispose() { _dbContext.Dispose(); } #endregion } }
73aed709eb7f8445269b65d3929d0ea4a4ec3e79
C#
luckyzwei/SuperPunchMan
/RobbersRace/Assets/Scripts/LevelBuildUtilities.cs
2.6875
3
using System.Collections; using System.Collections.Generic; using UnityEngine; public class LevelBuildUtilities : MonoBehaviour { int RowNumber; int ColumnNumber; public bool upperLeft=true, upperRight=true, lowerLeft=true, lowerRight=true; int numberOfMissingTiles; private List<Vector2> emptyFloorTiles = new List<Vector2>(); public List<Vector2>GetEmptyFloorTilesList() { return emptyFloorTiles; } public LevelBuildUtilities(int rowNumber, int columnNumber,int noOfMissingTiles) { RowNumber = rowNumber; ColumnNumber = columnNumber; numberOfMissingTiles = noOfMissingTiles; FillEmptyTilesList(); } void FillEmptyTilesList() { if (upperLeft) LeftUpperCornerQuarterDiamondBuild(); if (upperRight) RightUpperCornerQuarterDiamondBuild(); if (lowerLeft) LeftBottomCornerQuarterDiamondBuild(); if (lowerRight) RightBottomCornerQuarterDiamondBuild(); } void LeftUpperCornerQuarterDiamondBuild() { Vector2 startPosition = new Vector2(RowNumber, numberOfMissingTiles); for (int i = 0; i <numberOfMissingTiles; i++) for (int j = numberOfMissingTiles-i; j > 0; j--) { Vector2 currentEmptyFloorTile = (startPosition - Vector2.up * i) + (startPosition - Vector2.right * j); emptyFloorTiles.Add(currentEmptyFloorTile); } } void RightUpperCornerQuarterDiamondBuild() { Vector2 startPosition = new Vector2(RowNumber, ColumnNumber); for (int i = 0; i < numberOfMissingTiles; i++) for (int j = 0; j < i; j++) { Vector2 currentEmptyFloorTile = (startPosition - Vector2.up * i) + (startPosition - Vector2.right * j); emptyFloorTiles.Add(currentEmptyFloorTile); } } void RightBottomCornerQuarterDiamondBuild() { Vector2 startPosition = new Vector2(0, ColumnNumber); for (int i = 0; i < numberOfMissingTiles; i++) for (int j = 0; j < i; j++) { Vector2 currentEmptyFloorTile = (startPosition + Vector2.up * i) + (startPosition - Vector2.right * j); emptyFloorTiles.Add(currentEmptyFloorTile); } } void LeftBottomCornerQuarterDiamondBuild() { Vector2 startPosition = new Vector2(0, numberOfMissingTiles); for (int i = 0; i < numberOfMissingTiles; i++) for (int j = 0; j < i; j++) { Vector2 currentEmptyFloorTile = (startPosition + Vector2.up * i) + (startPosition - Vector2.right * j); emptyFloorTiles.Add(currentEmptyFloorTile); } } }
d5fddd9d2ee32e5714366f2d12fc9979d205bb0f
C#
xinyuanZhuang/OrcaTestCI
/Orca2/Services/EventAggregator.cs
2.734375
3
using Microsoft.Extensions.Logging; using Orca.Database; using Orca.Entities; using Orca.Tools; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Orca.Services { public class EventAggregator : IEventAggregator { private readonly ISharepointManager _sharePointManager; private readonly ICourseCatalog _courseCatalog; private ILogger<EventAggregator> _logger; public EventAggregator(ISharepointManager sharePointManager, ICourseCatalog courseCatalog, ILogger<EventAggregator> logger) { _sharePointManager = sharePointManager; _courseCatalog = courseCatalog; _logger = logger; } public async Task ProcessEvent(StudentEvent studentEvent) { //Check courseId exist in the coursecatalog if (_courseCatalog.CheckCourseIdExist(studentEvent.CourseID)) { if (studentEvent.EventType == EventType.Attendance) { // Check the corresponding list of this course according to Catalog. string targetList = _courseCatalog.GetListNameForCourse(studentEvent.CourseID); _logger.LogInformation("Event aggregator will send event to list {0}.", targetList); SharepointListItem eventItem = new SharepointListItem(); // Event Detailed Information. eventItem["Title"] = "Event by " + studentEvent.Student.Email; eventItem["CourseID"] = studentEvent.CourseID.ToUpper(); eventItem["StudentName"] = studentEvent.Student.FirstName + " (" + studentEvent.Student.LastName + ")"; eventItem["StudentID"] = studentEvent.Student.ID; eventItem["StudentEmail"] = studentEvent.Student.Email; eventItem["EventType"] = studentEvent.EventType.ToString(); eventItem["ActivityType"] = studentEvent.ActivityType; eventItem["ActivityName"] = studentEvent.ActivityName; eventItem["Timestamp"] = studentEvent.Timestamp; // Assign to different list by course ID. await _sharePointManager.AddItemToList(targetList, eventItem); } StoreInDatabase(studentEvent); } else { _logger.LogInformation($"Cannot find the courseId '{studentEvent.CourseID}', event aggregator has cancelled current event."); } } private void StoreInDatabase(StudentEvent studentEvent) { _logger.LogInformation(studentEvent.ToString()); DatabaseConnect connect = new DatabaseConnect(); connect.StoreStudentToDatabase(studentEvent); connect.StoreEventToDatabase(studentEvent); } } }
4c155c976a94a8565e75a87f93135d72979414dd
C#
LibbaLawrence/azure-sdk-tools
/tools/test-proxy/Azure.Sdk.Tools.TestProxy/Sanitizers/HeaderRegexSanitizer.cs
2.703125
3
using Azure.Sdk.Tools.TestProxy.Common; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace Azure.Sdk.Tools.TestProxy.Sanitizers { /// <summary> /// This sanitizer operates on a RecordSession entry and applies itself to the headers containered therein. /// </summary> public class HeaderRegexSanitizer : RecordedTestSanitizer { private string _targetKey; private string _newValue; private string _regexValue = null; private string _groupForReplace = null; /// <summary> /// Can be used for multiple purposes: /// 1) To replace a key with a specific value, do not set "regex" value. /// 2) To do a simple regex replace operation, define arguments "key", "value", and "regex" /// 3) To do a targeted substitution of a specific group, define all arguments "key", "value", and "regex" /// </summary> /// <param name="key">The name of the header we're operating against.</param> /// <param name="value">The substitution or whole new header value, depending on "regex" setting.</param> /// <param name="regex">A regex. Can be defined as a simple regex replace OR if groupForReplace is set, a subsitution operation.</param> /// <param name="groupForReplace">The capture group that needs to be operated upon. Do not set if you're invoking a simple replacement operation.</param> public HeaderRegexSanitizer(string key, string value = "Sanitized", string regex = null, string groupForReplace = null) { _targetKey = key; _newValue = value; _regexValue = regex; _groupForReplace = groupForReplace; } public override void SanitizeHeaders(IDictionary<string, string[]> headers) { if (headers.ContainsKey(_targetKey)) { var originalValue = headers[_targetKey][0]; var replacement = StringSanitizer.SanitizeValue(originalValue, _newValue, _regexValue, _groupForReplace); headers[_targetKey] = new string[] { replacement }; } } } }
78db2bbd008e82d944c5721ddfe0200739fabba3
C#
tomerpq/All-Projects-Of-Tomer-Paz
/Desktop(C# XAML) Project/ass2/Src/FlightSimulator/Model/Commands.cs
3.125
3
using System.Net.Sockets; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FlightSimulator.Model { internal class Commands { private TcpClient client; #region singelton private static Commands m_Instance; public static Commands Instance { get { if (m_Instance == null) { m_Instance = new Commands(); } return m_Instance; } } private Commands() { client = new TcpClient(); } #endregion singelton public void Connect(string FlightServerIP, int FlightCommandsPort) { //connecting to client client = new TcpClient(FlightServerIP, FlightCommandsPort); } public void close() { client.Close(); } public void sendCommand(string Command) { //if we havnt connected yet we dont send nothing if (!client.Connected) { return; } Command = Command + "\n\r\n\r"; // Translate the passed message into ASCII and store it as a Byte array. byte[] data = System.Text.Encoding.ASCII.GetBytes(Command); // Get a client stream for reading and writing. NetworkStream stream = client.GetStream(); // Send the message to the connected TcpServer. stream.Write(data, 0, data.Length); } } }
ec3b28a25204d28b616e944d056a4da6034a47a9
C#
JorgeFlorido/ShoppingCart
/ShoppingCart.Data/Repository/ProductRepository.cs
2.625
3
using System.Collections.Generic; using System.Data.Entity; using System.Linq; namespace ShoppingCart.Data { public class ProductRepository : DatabaseContext { public IEnumerable<Products> GetAll() { return Set<Products>(); } public Products Get(int id) { return Set<Products>().Where(x => x.Id == id).FirstOrDefault(); } } }
92fc5e9b3434c90e021ee0c5b5bccf5fc7c2303c
C#
akrois22/EntityFrameworkCore2.1Migrations-04
/3-Domain/Festify.Domain.Plan/Presenter.cs
2.53125
3
using System.Collections.Generic; namespace Festify.Domain.Plan { public class Presenter { private List<Talk> _talks = new List<Talk>(); public int PresenterId { get; private set; } public IEnumerable<Talk> Talks => _talks; public Talk NewTalk() { var talk = new Talk(); _talks.Add(talk); return talk; } } }
ea43266c238e3059cf2d717eefae64e12c1db77b
C#
StingMcRay/anno-designer
/AnnoDesigner/Helper/CoordinateHelper.cs
3.203125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using AnnoDesigner.Core.Models; using AnnoDesigner.Models; namespace AnnoDesigner.Helper { public class CoordinateHelper : ICoordinateHelper { /// <summary> /// Convert a screen coordinate to a grid coordinate by determining in which grid cell the point is contained. /// </summary> /// <param name="screenPoint"></param> /// <returns></returns> public Point ScreenToGrid(Point screenPoint, int gridStep) { return new Point(Math.Floor(screenPoint.X / gridStep), Math.Floor(screenPoint.Y / gridStep)); } /// <summary> /// Convert a screen coordinate to a grid coordinate without flooring to the nearest full coordinate /// </summary> /// <param name="screenPoint"></param> /// <returns></returns> public Point ScreenToFractionalGrid(Point screenPoint, int gridStep) { return new Point(screenPoint.X / gridStep, screenPoint.Y / gridStep); } /// <summary> /// Converts a screen coordinate to a grid coordinate by determining which grid cell is nearest. /// </summary> /// <param name="screenPoint"></param> /// <returns></returns> public Point RoundScreenToGrid(Point screenPoint, int gridStep) { return new Point(Math.Round(screenPoint.X / gridStep), Math.Round(screenPoint.Y / gridStep)); } /// <summary> /// Converts a length given in (pixel-)units to grid coordinate by determining which grid edge is nearest. /// </summary> /// <param name="screenLength"></param> /// <returns></returns> public double RoundScreenToGrid(double screenLength, int gridStep) { return Math.Round(screenLength / gridStep); } /// <summary> /// Converts a length given in (pixel-)units to a length given in grid cells. /// </summary> /// <param name="screenLength"></param> /// <returns></returns> public double ScreenToGrid(double screenLength, int gridStep) { return screenLength / gridStep; } /// <summary> /// Converts a length given in (pixel-)units to a length given in grid cells. /// </summary> /// <param name="rect"></param> /// <param name="gridStep"></param> public Rect ScreenToGrid(Rect rect, int gridStep) { return new Rect(rect.Location.X / gridStep, rect.Location.Y / gridStep, rect.Width / gridStep, rect.Height / gridStep); } /// <summary> /// Convert a grid coordinate to a screen coordinate. /// </summary> /// <param name="rect"></param> /// <param name="gridStep"></param> public Rect GridToScreen(Rect rect, int gridStep) { return new Rect(rect.Location.X * gridStep, rect.Location.Y * gridStep, rect.Width * gridStep, rect.Height * gridStep); } /// <summary> /// Convert a grid coordinate to a screen coordinate. /// </summary> /// <param name="gridPoint"></param> /// <returns></returns> public Point GridToScreen(Point gridPoint, int gridStep) { return new Point(gridPoint.X * gridStep, gridPoint.Y * gridStep); } /// <summary> /// Converts a size given in grid cells to a size given in (pixel-)units. /// </summary> /// <param name="gridSize"></param> /// <returns></returns> public Size GridToScreen(Size gridSize, int gridStep) { return new Size(gridSize.Width * gridStep, gridSize.Height * gridStep); } /// <summary> /// Converts a length given in grid cells to a length given in (pixel-)units. /// </summary> /// <param name="gridLength"></param> /// <returns></returns> public double GridToScreen(double gridLength, int gridStep) { return gridLength * gridStep; } /// <summary> /// Calculates the exact center point of a given rect /// </summary> /// <param name="rect"></param> /// <returns></returns> public Point GetCenterPoint(Rect rect) { var pos = rect.Location; var size = rect.Size; pos.X += size.Width / 2; pos.Y += size.Height / 2; return pos; } /// <summary> /// Rotates the given Size object, i.e. switches width and height. /// </summary> /// <param name="size"></param> /// <returns></returns> public Size Rotate(Size size) { return new Size(size.Height, size.Width); } /// <summary> /// Rotates the given Rect object 90 degrees clockwise around point (0, 0). /// </summary> public Rect Rotate(Rect rect) { var position = rect.TopLeft; //Full formula left in for explanation //var xPrime = x * Math.Cos(angle) - y * Math.Sin(angle); //var yPrime = x * Math.Sin(angle) - y * Math.Cos(angle); //Cos 90 = 0, sin 90 = 1 //Therefore, the below is equivalent var xPrime = 0 - position.Y; var yPrime = position.X; //When the building is rotated, the xPrime and yPrime values no //longer represent the top left corner, they will represent the //top-right corner instead. We need to account for this, by //moving the xPrime position (still in grid coordinates). xPrime -= rect.Size.Height; return new Rect(new Point(xPrime, yPrime), Rotate(rect.Size)); } /// <summary> /// Rotates the given GridDirection object 90 degrees clockwise. /// </summary> /// <param name="direction"></param> /// <returns></returns> public GridDirection Rotate(GridDirection direction) { return (GridDirection)((int)(direction + 1) % 4); } } }
6d635dd7b70ca027d0e721fd5930e035bbdc1bf4
C#
shendongnian/download4
/first_version_download2/294983-24093894-66798544-3.cs
2.671875
3
const string MyFileName = "myExcelFile.xls"; string execPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase); var filePath = Path.Combine(execPath, MyFileName); Microsoft.Office.Interop.Excel.Application app = new Application(); Microsoft.Office.Interop.Excel.Workbook book = app.Workbooks.Open(filePath); book.SaveAs(saveFileDialog.FileName); //Save book.Close(); }
48d26e1a3a0155ee89069ceee42d8e1b5161c054
C#
SiroccoHub/MediumProxy
/src/MediumProxy/MediumProxyExtentions.cs
2.734375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Threading.Tasks; using MediumProxy.Model; namespace MediumProxy { public static class MediumProxyExtentions { private static readonly Regex RegexFirstImageUrl = new Regex("<img[^<]+src=\"([^<\"]+)\"[^<]+>"); public static async Task<Uri> GetFirstImageUriAsync(this Item item, Uri defaultUrl = null) { if (string.IsNullOrEmpty(item?.ContentEncoded)) return defaultUrl; var match = RegexFirstImageUrl.Match(item.ContentEncoded); if (match.Groups.Count < 1) return defaultUrl; try { return new Uri(match.Groups[1].Value); } catch (Exception ex) { return defaultUrl; } } } }
2e32c406974e667de7b90b3f696785b51991ab70
C#
shendongnian/download4
/latest_version_download2/131620-26353323-75499553-4.cs
3.359375
3
public List<Player> GetSpectators(Hashset<Player> playersInGame, Coordinate coord) { var playersInRange = new List<Player>(); // iterate through each player. foreach (var p in playersInGame) { // check if the tile the player is sitting on is in range of radius given. if ((p.CurrentTile.X < coord.X + 6 || p.CurrentTile.X > coord.X - 6) && (p.CurrentTile.Y < coord.Y + 6 || p.CurrentTile.Y > coord.Y - 6)) { // Player is within radius. playersInRange.Add(p); } } return playersInRange; }
c7b13566a22c7bb3fd8fd12456d9a5bca825f0ea
C#
danikf/tik4net
/tik4net.objects/TikListMerge.cs
2.71875
3
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Text; namespace tik4net.Objects { /// <summary> /// Provides support to merge actual state on mikrotik (list of entities) with expected state (list of entities). /// Provides fluent like api to setup merge operation. /// <see cref="Save"/> method should be called to perform modifications on mikrotik router. /// </summary> /// <typeparam name="TEntity"></typeparam> public class TikListMerge<TEntity> where TEntity : new() { /// <summary> /// Operation performed during merge process with single entity. /// </summary> public enum MergeOperation { /// <summary> /// Create new entity /// </summary> Insert, /// <summary> /// Update existing entity /// </summary> Update, /// <summary> /// Delete existing entity /// </summary> Delete, }; private readonly ITikConnection _connection; private readonly IEnumerable<TEntity> _expected; private readonly IEnumerable<TEntity> _original; private readonly TikEntityMetadata _metadata; private Func<TEntity, string> _keyExtractor; private Action<MergeOperation, TEntity, TEntity> _dmlLogCallback; //<MergeOperation, oldEntity, newEntity> private Action<TEntity, int, int> _moveLogCallback; //<Entity, oldIndex, newIndex> private Func<MergeOperation, TEntity, TEntity, bool> _filterCallback = (operation, oldE, newE) => true; //default filter - process all private readonly List<MemberExpression> _fields = new List<MemberExpression>(); private readonly List<MemberExpression> _justForInsertFields = new List<MemberExpression>(); internal TikListMerge(ITikConnection connection, IEnumerable<TEntity> expected, IEnumerable<TEntity> original) { _connection = connection; _metadata = TikEntityMetadataCache.GetMetadata<TEntity>(); _expected = expected; _original = original; } private static MemberExpression EnsureBodyIsMemberExpression<TProperty>(Expression<Func<TEntity, TProperty>> fieldExpression) { MemberExpression memberExpression = fieldExpression.Body as MemberExpression; if (memberExpression == null) throw new ArgumentException("Given expression must be MemberExpression.", "fieldExpression"); return memberExpression; } //private static TikPropertyAttribute EnsureTikProperty<TProperty>(Expression<Func<TEntity, TProperty>> fieldExpression) //{ // var memberExpression = EnsureBodyIsMemberExpression(fieldExpression); // TikPropertyAttribute attr = memberExpression.Type.CustomAttributes.OfType<TikPropertyAttribute>().Single(); //TODO check and better exception // return attr; //} /// <summary> /// Defines string representation of entity key (entities are the same, if extracted key has the same value). /// </summary> /// <param name="keyExtractor">Func to extract key value from entity</param> /// <returns>this (fluent like API)</returns> public TikListMerge<TEntity> WithKey(Func<TEntity, string> keyExtractor) { _keyExtractor = keyExtractor; return this; } /// <summary> /// Register DML log callback {operation, oldValue, newValue} - called on each DML operation. /// </summary> /// <param name="dmlLogCallback">log callback called on each DML operation - {operation, oldValue, newValue}</param> /// <returns>this (fluent like API)</returns> public TikListMerge<TEntity> WithDmlLogCallback(Action<MergeOperation, TEntity, TEntity> dmlLogCallback) { _dmlLogCallback = dmlLogCallback; return this; } /// <summary> /// Register move log callback {entity, oldIndex, newIndex} - called on each move operation. /// </summary> /// <param name="moveLogCallback">log callback called on each move operation - {entity, oldIndex, newIndex}</param> /// <returns>this (fluent like API)</returns> public TikListMerge<TEntity> WithMoveLogCallback(Action<TEntity, int, int> moveLogCallback) { _moveLogCallback = moveLogCallback; return this; } /// <summary> /// Defines field that will be merged (only defined fields will be compared and updated). /// </summary> /// <typeparam name="TProperty">Field property.</typeparam> /// <param name="fieldExpression">Field extraction expression. example: (entity=}entity.Name)</param> /// <returns>this (fluent like API)</returns> public TikListMerge<TEntity> Field<TProperty>(Expression<Func<TEntity, TProperty>> fieldExpression) { _fields.Add(EnsureBodyIsMemberExpression(fieldExpression)); return this; } /// <summary> /// Defines field that will be used just when creating new instance of entity (<see cref="MergeOperation.Insert"/>) (not used for update and compare). /// </summary> /// <typeparam name="TProperty">Field property.</typeparam> /// <param name="fieldExpression">Field extraction expression. example: (entity=}entity.Name)</param> /// <returns>this (fluent like API)</returns> public TikListMerge<TEntity> JustForInsertField<TProperty>(Expression<Func<TEntity, TProperty>> fieldExpression) { _justForInsertFields.Add(EnsureBodyIsMemberExpression(fieldExpression)); return this; } /// <summary> /// Register filter callback {operation, oldValue, newValue} - called on each DML operation. Operation will be performed only if true is returned. Otherwise DML operation will be skipped. /// </summary> /// <param name="filterCallback">log callback called on each DML operation - {operation, oldValue, newValue}. Operation will be performed only if true is returned. Otherwise DML operation will be skipped.</param> /// <returns>this (fluent like API)</returns> public TikListMerge<TEntity> WithOperationFilter(Func<MergeOperation, TEntity, TEntity, bool> filterCallback) { _filterCallback = filterCallback; return this; } private void UpdateEntityFields(TEntity destination, TEntity source) { foreach (var field in _fields) { PropertyInfo propInfo = ((PropertyInfo)field.Member); object sourceValue = propInfo.GetValue(source); propInfo.SetValue(destination, sourceValue); } } private bool EntityFieldEquals(TEntity entity1, TEntity entity2) { foreach (var field in _fields) { PropertyInfo propInfo = ((PropertyInfo)field.Member); object val1 = propInfo.GetValue(entity1); object val2 = propInfo.GetValue(entity2); if (Convert.ToString(val1) != Convert.ToString(val2)) return false; } return true; } private IEnumerable<string> ResolveFieldsFieldNames() { foreach(var field in _fields) { var attr = ((PropertyInfo)field.Member).GetCustomAttribute<TikPropertyAttribute>(true); yield return attr.FieldName; } } private IEnumerable<string> ResolveJustForInsertFieldNames() { foreach (var field in _justForInsertFields) { var attr = ((PropertyInfo)field.Member).GetCustomAttribute<TikPropertyAttribute>(true); yield return attr.FieldName; } } private void LogDml(MergeOperation operation, TEntity oldEntity, TEntity newEntity) { if (_dmlLogCallback != null) _dmlLogCallback(operation, oldEntity, newEntity); } private void LogMove(TEntity entity, int oldIndex, int newIndex) { if (_moveLogCallback != null) _moveLogCallback(entity, oldIndex, newIndex); } /// <summary> /// Performs update operations on mikrotik router. /// Items which are present in 'expected' and are not present in 'original' will be created on mikrotik router. /// Items which are present in both 'expected' and 'original' will be compared and updated (if are different - see <see cref="Field"/>, <see cref="WithKey"/>). /// Items which are not present in 'expected' and are present in 'original' will be deleted from mikrotik router. /// </summary> /// <returns>List of final entities on mikrotik router after save operation (with ids).</returns> /// <seealso cref="Simulate(out int, out int, out int, out int)"/> public IEnumerable<TEntity> Save() { int insertCnt, updateCnt, deleteCnt, moveCnt; return SaveInternal(false, out insertCnt, out updateCnt, out deleteCnt, out moveCnt); } /// <summary> /// Calculate update operations on mikrotik router. /// Items which are present in 'expected' and are not present in 'original' will be counted as created. /// Items which are present in both 'expected' and 'original' will be compared and counted as updated (if are different - see <see cref="Field"/>, <see cref="WithKey"/>). /// Items which are not present in 'expected' and are present in 'original' will be counted as deleted. /// </summary> /// <param name="insertCnt">Number of items to be created.</param> /// <param name="updateCnt">Number of items to be updated.</param> /// <param name="deleteCnt">Number of items to be deleted.</param> /// <param name="moveCnt">Number of items to be moved (note: inserted items are always inserted at the end of list and moved to the right place by move operation).</param> /// <returns>Expected list of final entities on mikrotik router after save operation.</returns> /// <seealso cref="Save"/> public IEnumerable<TEntity> Simulate(out int insertCnt, out int updateCnt, out int deleteCnt, out int moveCnt) { return SaveInternal(true, out insertCnt, out updateCnt, out deleteCnt, out moveCnt); } /// <summary> /// Calculate update operations on mikrotik router. /// Items which are present in 'expected' and are not present in 'original' will be counted as created. /// Items which are present in both 'expected' and 'original' will be compared and counted as updated (if are different - see <see cref="Field"/>, <see cref="WithKey"/>). /// Items which are not present in 'expected' and are present in 'original' will be counted as deleted. /// </summary> /// <param name="insertCnt">Number of items to be created.</param> /// <param name="updateCnt">Number of items to be updated.</param> /// <param name="deleteCnt">Number of items to be deleted.</param> /// <returns>Expected list of final entities on mikrotik router after save operation.</returns> /// <seealso cref="Save"/> public IEnumerable<TEntity> Simulate(out int insertCnt, out int updateCnt, out int deleteCnt) { int tmp; return SaveInternal(true, out insertCnt, out updateCnt, out deleteCnt, out tmp); } private IEnumerable<TEntity> SaveInternal(bool simulateOnly, out int insertCnt, out int updateCnt, out int deleteCnt, out int moveCnt) { insertCnt = 0; updateCnt = 0; deleteCnt = 0; moveCnt = 0; //TODO ensure all fields set List<TEntity> result = new List<TEntity>(); Dictionary<string, TEntity> expectedDict = _expected.ToDictionaryEx(_keyExtractor); Dictionary<string, TEntity> originalDict = _original.ToDictionaryEx(_keyExtractor); int idx = 0; Dictionary<string, int> originalIndexes = _original.ToDictionaryEx(_keyExtractor, i => idx++); //Delete foreach (var originalEntityPair in originalDict.Reverse()) //delete from end to begining of the list (just for better show in WinBox) { if (!expectedDict.ContainsKey(originalEntityPair.Key)) //present in original + not present in expected => delete { if (_filterCallback(MergeOperation.Delete, originalEntityPair.Value, default(TEntity))) { if (!simulateOnly) { LogDml(MergeOperation.Delete, originalEntityPair.Value, default(TEntity)); _connection.Delete(originalEntityPair.Value); } deleteCnt++; } } } //Insert+Update var mergedFieldNames = ResolveFieldsFieldNames().ToArray(); var insertedFieldNames = ResolveJustForInsertFieldNames().ToArray(); foreach (var expectedEntityPair in expectedDict.Reverse()) //from last to first ( <= move is indexed as moveBeforeEntity) { TEntity originalEntity; TEntity resultEntity; if (originalDict.TryGetValue(expectedEntityPair.Key, out originalEntity)) { //Update //present in both expected and original => update or NOOP //copy .id from original to expected & save if (!EntityFieldEquals(originalEntity, expectedEntityPair.Value)) //modified { if (_filterCallback(MergeOperation.Update, originalEntity, expectedEntityPair.Value)) { if (!simulateOnly) { LogDml(MergeOperation.Update, originalEntity, expectedEntityPair.Value); UpdateEntityFields(originalEntity, expectedEntityPair.Value); _connection.Save(originalEntity, mergedFieldNames); } updateCnt++; } } resultEntity = originalEntity; } else { //Insert //present in expected and not present in original => insert if (_filterCallback(MergeOperation.Insert, default(TEntity), expectedEntityPair.Value)) { if (!simulateOnly) { LogDml(MergeOperation.Insert, default(TEntity), expectedEntityPair.Value); _connection.Save(expectedEntityPair.Value, mergedFieldNames.Concat(insertedFieldNames)); } insertCnt++; } resultEntity = expectedEntityPair.Value; } //Move entity to the right position if (_metadata.IsOrdered) { if (result.Count > 0) // last one in the list (first taken) should be just added/leavedOnPosition and the next should be moved before the one which was added immediatelly before <=> result[0] { // only if is in different position (is not after result[0]) int resultEntityIdx, previousEntityIdx = -1; if (!originalIndexes.TryGetValue(_keyExtractor(resultEntity), out resultEntityIdx) || !originalIndexes.TryGetValue(_keyExtractor(result[0]), out previousEntityIdx) || resultEntityIdx != previousEntityIdx - 1) { if (!simulateOnly) { LogMove(resultEntity, resultEntityIdx, previousEntityIdx); _connection.Move(resultEntity, result[0]); //before lastly added entity (foreach in reversed order) } moveCnt++; } } } result.Insert(0, resultEntity); //foreach in reversed order => put as first in result list } return result; } } }
e4a7d02d88463d0dbe9f53b2cf9bdedebf42c62b
C#
juliebishopphotos/GoldBadgeChallenges
/02_Claims/ClaimsRepo.cs
3.28125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _02_Claims { public class ClaimsRepo { private Queue<Claims> _claimsDirectory = new Queue<Claims>(); public bool AddNewClaim(Claims input) { int startingCount = _claimsDirectory.Count; _claimsDirectory.Enqueue(input); bool wasAdded = (_claimsDirectory.Count > startingCount) ? true : false; return wasAdded; } public Queue<Claims> GetAllClaims() { return _claimsDirectory; } public Claims FindInputByClaimID(int claimID) { foreach (Claims input in _claimsDirectory) { if (input.ClaimID == claimID) { return input; } } return null; } public bool DeleteClaim() { int startingCount = _claimsDirectory.Count; _claimsDirectory.Dequeue(); bool wasDeleted = (_claimsDirectory.Count < startingCount) ? true : false; return wasDeleted; } } }
372112e82251841827e606380d84774c649f59bb
C#
SandyGlantz/Test
/Defaults/34b_Casino/34-mega-Challenge/valueTester.aspx.cs
2.6875
3
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace ValuesTest { public partial class Default : System.Web.UI.Page { int startBalance, totalCalc, newBalance; protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { int startBalance = 0; startingTotalLabel.Text = startBalance.ToString(); int newBalance = 0; newTotalLabel.Text = newBalance.ToString(); } } public void calcs() { // pulling starting balance int startBalance = int.Parse(newTotalLabel.Text); // pulling numbers to add int num1 = int.Parse(num1TextBox.Text); int num2 = int.Parse(num1TextBox.Text); // getting the current calc int totalCalc = num1 + num2; thisCalcTotalLabel.Text = totalCalc.ToString(); // getting the new total int newBalance = startBalance + totalCalc; newTotalLabel.Text = newBalance.ToString(); // clearing starting balance //startingTotalLabel.Text = ""; } protected void okButton_Click(object sender, EventArgs e) { calcs(); } } }
24d295f8ad9d70f0aea3c6c3460b79dd59f6f52d
C#
merche-o/FINFA
/Assets/Scripts/PlayerController.cs
2.59375
3
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerController : MonoBehaviour { public float moveSpeed = 1; private Animator anim; private bool isMoving; private Vector2 lastMove; // Use this for initialization void Start () { anim = GetComponent<Animator> (); isMoving = false; } // Update is called once per frame void Update () { isMoving = false; if (Input.GetAxisRaw ("Horizontal") > 0.5f || Input.GetAxisRaw ("Horizontal") < -0.5f) { transform.Translate (new Vector3 (Input.GetAxisRaw ("Horizontal") * moveSpeed * Time.deltaTime, 0f)); isMoving = true; lastMove = new Vector2 (Input.GetAxisRaw ("Horizontal"), 0); } if (Input.GetAxisRaw("Vertical") > 0.5f || Input.GetAxisRaw("Vertical") < -0.5f) { transform.Translate(new Vector3(0f,Input.GetAxisRaw("Vertical") * moveSpeed *Time.deltaTime)); isMoving = true; lastMove = new Vector2 (0, Input.GetAxisRaw ("Vertical")); } anim.SetFloat ("MoveX", Input.GetAxisRaw ("Horizontal")); anim.SetFloat ("MoveY", Input.GetAxisRaw ("Vertical")); anim.SetBool("isMoving", isMoving); anim.SetFloat ("LastMoveX", lastMove.x); anim.SetFloat ("LastMoveY", lastMove.y); } }
d561ec7e6c60df39240b7bceb6d730b576ddb73a
C#
revam/dotnet-shoko.shokofin
/Shokofin/Utils/TextUtil.cs
2.953125
3
using Shokofin.API.Models; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; namespace Shokofin.Utils { public class Text { /// <summary> /// Determines the language to construct the title in. /// </summary> public enum DisplayLanguageType { /// <summary> /// Let Shoko decide what to display. /// </summary> Default = 1, /// <summary> /// Prefer to use the selected metadata language for the library if /// available, but fallback to the default view if it's not /// available. /// </summary> MetadataPreferred = 2, /// <summary> /// Use the origin language for the series. /// </summary> Origin = 3, /// <summary> /// Don't display a title. /// </summary> Ignore = 4, } /// <summary> /// Determines the type of title to construct. /// </summary> public enum DisplayTitleType { /// <summary> /// Only construct the main title. /// </summary> MainTitle = 1, /// <summary> /// Only construct the sub title. /// </summary> SubTitle = 2, /// <summary> /// Construct a combined main and sub title. /// </summary> FullTitle = 3, } /// <summary> /// Based on ShokoMetadata's summary sanitizer which in turn is based on HAMA's summary sanitizer. /// </summary> /// <param name="summary">The raw AniDB summary</param> /// <returns>The sanitized AniDB summary</returns> public static string SanitizeTextSummary(string summary) { var config = Plugin.Instance.Configuration; if (config.SynopsisCleanLinks) summary = Regex.Replace(summary, @"https?:\/\/\w+.\w+(?:\/?\w+)? \[([^\]]+)\]", match => match.Groups[1].Value); if (config.SynopsisCleanMiscLines) summary = Regex.Replace(summary, @"^(\*|--|~) .*", "", RegexOptions.Multiline); if (config.SynopsisRemoveSummary) summary = Regex.Replace(summary, @"\n(Source|Note|Summary):.*", "", RegexOptions.Singleline); if (config.SynopsisCleanMultiEmptyLines) summary = Regex.Replace(summary, @"\n\n+", "", RegexOptions.Singleline); return summary; } public static ( string, string ) GetEpisodeTitles(IEnumerable<Title> seriesTitles, IEnumerable<Title> episodeTitles, string episodeTitle, string metadataLanguage) => GetTitles(seriesTitles, episodeTitles, null, episodeTitle, DisplayTitleType.SubTitle, metadataLanguage); public static ( string, string ) GetSeriesTitles(IEnumerable<Title> seriesTitles, string seriesTitle, string metadataLanguage) => GetTitles(seriesTitles, null, seriesTitle, null, DisplayTitleType.MainTitle, metadataLanguage); public static ( string, string ) GetMovieTitles(IEnumerable<Title> seriesTitles, IEnumerable<Title> episodeTitles, string seriesTitle, string episodeTitle, string metadataLanguage) => GetTitles(seriesTitles, episodeTitles, seriesTitle, episodeTitle, DisplayTitleType.FullTitle, metadataLanguage); public static ( string, string ) GetTitles(IEnumerable<Title> seriesTitles, IEnumerable<Title> episodeTitles, string seriesTitle, string episodeTitle, DisplayTitleType outputType, string metadataLanguage) { // Don't process anything if the series titles are not provided. if (seriesTitles == null) return ( null, null ); var originLanguage = GuessOriginLanguage(seriesTitles); return ( GetTitle(seriesTitles, episodeTitles, seriesTitle, episodeTitle, Plugin.Instance.Configuration.TitleMainType, outputType, metadataLanguage, originLanguage), GetTitle(seriesTitles, episodeTitles, seriesTitle, episodeTitle, Plugin.Instance.Configuration.TitleAlternateType, outputType, metadataLanguage, originLanguage) ); } public static string GetEpisodeTitle(IEnumerable<Title> seriesTitles, IEnumerable<Title> episodeTitles, string episodeTitle, string metadataLanguage) => GetTitle(seriesTitles, episodeTitles, null, episodeTitle, DisplayTitleType.SubTitle, metadataLanguage); public static string GetSeriesTitle(IEnumerable<Title> seriesTitles, string seriesTitle, string metadataLanguage) => GetTitle(seriesTitles, null, seriesTitle, null, DisplayTitleType.MainTitle, metadataLanguage); public static string GetMovieTitle(IEnumerable<Title> seriesTitles, IEnumerable<Title> episodeTitles, string seriesTitle, string episodeTitle, string metadataLanguage) => GetTitle(seriesTitles, episodeTitles, seriesTitle, episodeTitle, DisplayTitleType.FullTitle, metadataLanguage); public static string GetTitle(IEnumerable<Title> seriesTitles, IEnumerable<Title> episodeTitles, string seriesTitle, string episodeTitle, DisplayTitleType outputType, string metadataLanguage, params string[] originLanguages) => GetTitle(seriesTitles, episodeTitles, seriesTitle, episodeTitle, Plugin.Instance.Configuration.TitleMainType, outputType, metadataLanguage, originLanguages); public static string GetTitle(IEnumerable<Title> seriesTitles, IEnumerable<Title> episodeTitles, string seriesTitle, string episodeTitle, DisplayLanguageType languageType, DisplayTitleType outputType, string displayLanguage, params string[] originLanguages) { // Don't process anything if the series titles are not provided. if (seriesTitles == null) return null; // Guess origin language if not provided. if (originLanguages.Length == 0) originLanguages = GuessOriginLanguage(seriesTitles); switch (languageType) { // 'Ignore' will always return null, and all other values will also return null. default: case DisplayLanguageType.Ignore: return null; // Let Shoko decide the title. case DisplayLanguageType.Default: return __GetTitle(null, null, seriesTitle, episodeTitle, outputType); // Display in metadata-preferred language, or fallback to default. case DisplayLanguageType.MetadataPreferred: var title = __GetTitle(seriesTitles, episodeTitles, seriesTitle, episodeTitle, outputType, displayLanguage); if (string.IsNullOrEmpty(title)) goto case DisplayLanguageType.Default; return title; // Display in origin language without fallback. case DisplayLanguageType.Origin: return __GetTitle(seriesTitles, episodeTitles, seriesTitle, episodeTitle, outputType, originLanguages); } } private static string __GetTitle(IEnumerable<Title> seriesTitles, IEnumerable<Title> episodeTitles, string seriesTitle, string episodeTitle, DisplayTitleType outputType, params string[] languageCandidates) { // Lazy init string builder when/if we need it. StringBuilder titleBuilder = null; switch (outputType) { default: return null; case DisplayTitleType.MainTitle: case DisplayTitleType.FullTitle: { string title = (GetTitleByTypeAndLanguage(seriesTitles, "official", languageCandidates) ?? seriesTitle)?.Trim(); // Return series title. if (outputType == DisplayTitleType.MainTitle) return title; titleBuilder = new StringBuilder(title); goto case DisplayTitleType.SubTitle; } case DisplayTitleType.SubTitle: { string title = (GetTitleByLanguages(episodeTitles, languageCandidates) ?? episodeTitle)?.Trim(); // Return episode title. if (outputType == DisplayTitleType.SubTitle) return title; // Ignore sub-title of movie if it strictly equals the text below. if (title != "Complete Movie" && !string.IsNullOrEmpty(title?.Trim())) titleBuilder?.Append($": {title}"); return titleBuilder?.ToString() ?? ""; } } } public static string GetTitleByTypeAndLanguage(IEnumerable<Title> titles, string type, params string[] langs) { if (titles != null) foreach (string lang in langs) { string title = titles.FirstOrDefault(s => s.Language == lang && s.Type == type)?.Name; if (title != null) return title; } return null; } public static string GetTitleByLanguages(IEnumerable<Title> titles, params string[] langs) { if (titles != null) foreach (string lang in langs) { string title = titles.FirstOrDefault(s => lang.Equals(s.Language, System.StringComparison.OrdinalIgnoreCase))?.Name; if (title != null) return title; } return null; } /// <summary> /// Guess the origin language based on the main title. /// </summary> /// <returns></returns> private static string[] GuessOriginLanguage(IEnumerable<Title> titles) { string langCode = titles.FirstOrDefault(t => t?.Type == "main")?.Language.ToLower(); // Guess the origin language based on the main title. switch (langCode) { case null: // fallback case "x-other": case "x-jat": return new string[] { "ja" }; case "x-zht": return new string[] { "zn-hans", "zn-hant", "zn-c-mcm", "zn" }; default: return new string[] { langCode }; } } } }
9016e9720050aa8a5c116b030f250d2f92486e70
C#
skywalkeryin/Play-with-Data-Structures
/C#/DS_Graph/WeightedGraph/WeightedDenseGraph.cs
3.671875
4
using System; using System.Collections.Generic; using System.Text; namespace DS_Graph.WeightedGraph { // 稠密图 邻接表 public class WeightedDenseGraph<Weight> : IWeightedGraph<Weight> where Weight : struct, IComparable<Weight> { private int n; private int m; private bool directed; private Weight[][] g; public WeightedDenseGraph(int n, bool directed) { this.n = n; this.m = 0; this.directed = directed; g = new Weight[n][]; for (int i = 0; i < n; i++) { g[i] = new Weight[n]; //初始值为weight的初始值 } } public void AddEdge(Edge<Weight> edge) { if (edge.V() < 0 || edge.V() >= n) { throw new Exception("Ilegal vertex."); } if (edge.W() < 0 || edge.W() >= n) { throw new Exception("Ilegal vertex."); } g[edge.V()][edge.W()] = edge.Wt(); if (!directed) { g[edge.W()][edge.V()] = edge.Wt(); } } public IEnumerable<Edge<Weight>> Adj(int v) { if (v < 0 || v >= n) { throw new Exception("Ilegal vertex."); } List<Edge<Weight>> result = new List<Edge<Weight>>(); for (int i = 0; i < g[v].Length; i++) { result.Add(new Edge<Weight>(v, i, g[v][i])); } return result; } public int V() { return n; } public int E() { return m; } public bool HasEdge(int v, int w) { if (v < 0 || v >= n) { throw new Exception("Ilegal vertex."); } if (w < 0 || w >= n) { throw new Exception("Ilegal vertex."); } return g[v][w].CompareTo(default(Weight)) > 0; } public void Show() { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { Console.Write(g[i][j] + "\t"); } Console.Write("\n"); } } } }
86fa62a56c28f7af1634aa615082ebc07f02867d
C#
LittleLeah/EksamenMVC
/MVC API KALD/Controllers/HomeController.cs
2.578125
3
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using MVC_API_KALD.Models; using System.Threading.Tasks; using System.Net.Http; using System.Net.Http.Headers; using Newtonsoft.Json.Linq; namespace MVC_API_KALD.Controllers { public class HomeController : Controller { public List<Joke> JokeList = new List<Joke>(); public async Task<ActionResult> Index() { ViewBag.Title = "Home Page"; ViewModel vm = new ViewModel(); vm.Dadjoke = await GetDadJoke(); vm.ChuckNorris = await GetCNJoke(); return View(vm); } [System.Web.Mvc.HttpPost] public async Task<ActionResult> StoreJokes(string Vote, ViewModel vm) { if (Vote == "Dadjoke") { vm.Dadjoke.Votes++; } else { vm.ChuckNorris.Votes++; } JokeList.Add(vm.Dadjoke); JokeList.Add(vm.ChuckNorris); return RedirectToAction("Index"); } public async Task<Joke> GetDadJoke() { Joke joke = new Joke(); HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var content = await client.GetStringAsync("https://icanhazdadjoke.com/"); JObject jsonContent = JObject.Parse(content); joke.ID = jsonContent["id"].ToString(); joke.JokeContent = jsonContent["joke"].ToString(); joke.Votes = 0; joke.Type = true; return joke; } public async Task<Joke> GetCNJoke() { Joke joke = new Joke(); HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var content = await client.GetStringAsync("https://api.chucknorris.io/jokes/random"); JObject jsonContent = JObject.Parse(content); joke.ID = jsonContent["id"].ToString(); joke.JokeContent = jsonContent["value"].ToString(); joke.Votes = 0; joke.Type = false; return joke; } public ActionResult About() { Calendar c = new Calendar(); DateTime today = DateTime.Today; int daysThisMonth = DateTime.DaysInMonth(today.Year, today.Month); c.DaysInMonth = new string[6, 7]; int day = 1; int weekday; DateTime dayOfMonth = new DateTime(today.Year, today.Month, day); for (int i = 0; i < 6; i++) { int startweek = 1; for (int j = 0; j < 7; j++) { weekday = (int)dayOfMonth.DayOfWeek; if (startweek == 7) { startweek = 0; } if (day <= daysThisMonth) { if (startweek == weekday) { if (day == DateTime.Now.Day) { c.DaysInMonth[i, j] = "*"; } else { c.DaysInMonth[i, j] = day.ToString(); } dayOfMonth = dayOfMonth.AddDays(1); day++; } startweek++; } } } return View(c); } public ActionResult Contact() { ViewBag.Message = "Your contact page."; return View(); } } }
cc0e68bc893d005d4d0e6e1de05fc7ec51ef8883
C#
aguua/asp-test
/WebApplicationxD/WebApplicationxDTest/ModelsTests/BookModelTest.cs
2.625
3
using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using System; using System.Collections.Generic; using System.Text; using WebApplicationxD.Models; namespace WebApplicationxDTest.ModelsTests { [TestClass] public class BookModelTest { [TestMethod] public void Validate_Book_Not_Given_Data() { var model = new Book(); var results = TestModelHelper.Validate(model); Assert.AreEqual(3, results.Count); Assert.AreEqual("The Title field is required.", results[0].ErrorMessage); Assert.AreEqual("Category cannot be null", results[1].ErrorMessage); Assert.AreEqual("Please choose author", results[2].ErrorMessage); } [TestMethod] public void Validate_Book_Title_Only() { var model = new Book(); { model.Title = "Miecz Prawdy"; } var results = TestModelHelper.Validate(model); Assert.AreEqual(2, results.Count); Assert.AreEqual("Category cannot be null", results[0].ErrorMessage); Assert.AreEqual("Please choose author", results[1].ErrorMessage); } [TestMethod] public void Validate_Book_Title_And_Cathegory() { var model = new Book(); { model.Title = "Miecz Prawdy"; model.Category = "fantastyka"; } var results = TestModelHelper.Validate(model); Assert.AreEqual(1, results.Count); Assert.AreEqual("Please choose author", results[0].ErrorMessage); } [TestMethod] public void Validate_Book_Invalid_ReleaseDate() { Mock<Author> mockAuthor = new Mock<Author>(); var model = new Book(); { model.Title = "Miecz Prawdy"; model.Category = "fantastyka"; model.Author = mockAuthor.Object; model.ReleaseDate = new DateTime(3000, 1, 1); } var results = TestModelHelper.Validate(model); Assert.AreEqual(1, results.Count); Assert.AreEqual("Can not add not realised book.", results[0].ErrorMessage); } [TestMethod] public void Validate_Book_With_Mocked_Author() { Mock<Author> mockAuthor = new Mock<Author>(); mockAuthor.Setup(x => x.Id).Returns(1); mockAuthor.Setup(x => x.Name).Returns("Adam"); var model = new Book(); { model.Title = "Miecz Prawdy"; model.Category = "fantastyka"; model.Author = mockAuthor.Object; } var results = TestModelHelper.Validate(model); Assert.AreEqual(0, results.Count); } } }
c69e19d6b050cbdd826aa2a4824f90fc581193d1
C#
mlaga97/Wanderer
/Assets/Scripts/Taggable.cs
2.65625
3
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Taggable : MonoBehaviour { public enum TagType { Controllable, Attackable, Walkable, Unwalkable, Mineable, Cutable, Collectable, Talkable, Questable, Tradeable, Interactable, Traversable, Repairable } public TagType[] tags; bool hasTag(TagType tagToCheck) { foreach (TagType tag in tags) if (tag == tagToCheck) return true; return false; } }
6f8a97204b2daa5f9bb4663ecf66727ddfb13da7
C#
dannysy/algos
/Deck/Brackets/BracketParser.cs
3.609375
4
using System; using System.Collections.Generic; using System.Linq; namespace Brackets { public static class BracketParser { public static bool IsleftBracket(char bracket) { return '(' == bracket || '[' == bracket || '{' == bracket; } public static char ReverseBracket(char bracket) { if (bracket == '{') return '}'; if (bracket == '}') return '{'; if (bracket == '(') return ')'; if (bracket == ')') return '('; if (bracket == '[') return ']'; if (bracket == ']') return '['; throw new ArgumentException("illegal argument"); } public static bool IsClosed(char firstBracket, char secondBracket) { return (firstBracket == '(' && secondBracket == ')') || (firstBracket == '[' && secondBracket == ']') || (firstBracket == '{' && secondBracket == '}'); } public static string IsGood(string input) { var brackets = input.ToCharArray(); var bracketStack = new Stack<char>(); foreach (var bracket in brackets) { if (IsleftBracket(bracket)) { bracketStack.Push(bracket); } else if(bracketStack.Any() && IsClosed(bracketStack.Peek(), bracket)) { bracketStack.Pop(); } else { bracketStack.Push(bracket); } } if (!bracketStack.Any()) return input; var closed = false; var broken = false; var rightPart = string.Empty; var leftpart = string.Empty; var reversedStack = bracketStack.Reverse(); foreach (var bracket in reversedStack) { if (IsleftBracket(bracket)) { closed = true; rightPart = ReverseBracket(bracket) + rightPart; } else { if (closed) { return "IMPOSSIBLE"; } leftpart = ReverseBracket(bracket) + leftpart; } } return leftpart + input + rightPart; } } }
99bd9d131b196669a3d87bba7ac5886b7d479837
C#
Ivan1910/Battleship
/Model/squareTerminator.cs
3.09375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Vsite.Oom.Battleship.Model { public class squareTerminator : ISquareTerminator { public squareTerminator(int rows,int columns) { this.rows = rows; this.columns = columns; } public IEnumerable<Square> ToEliminate(IEnumerable<Square> shipSquares) { int left = shipSquares.First().column; if (left > 0) { --left; } int top = shipSquares.First().row; if (top > 0) { --top; } int right = shipSquares.Last().column+1; if (right < columns) { ++right; } int bottom = shipSquares.Last().row+1; if (bottom < rows) { ++bottom; } List<Square> toEliminate = new List<Square>(); for(int r = top;r<bottom;++r) { for(int c = left; c < right; ++c) { toEliminate.Add(new Square(r, c)); } } return toEliminate; } private readonly int rows; private readonly int columns; } }
8ab57ece932ef011cd034424755213660ed34036
C#
AlexAAguila/Hard-Breath
/Hard Breath Project/Assets/AlexAssets/AlexScripts/PotConditions.cs
2.671875
3
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PotConditions : MonoBehaviour { //I made this code myself //This code is designed so that conditions need to be met in order to leave the room //The bottles are the only assets that have triggers so if both triggers go in the pot //then the condition is fulfilled public float amountOfBottles = 0; public AudioSource build; public GameObject bomb; //To set conditions public GameObject bombPart; public GameObject bombString; //To set the visible gameobjects on the table public GameObject bombPartTable; public GameObject bombStringTable; // Start is called before the first frame update void Start() { build = GetComponent<AudioSource>(); bomb.SetActive(false); } // Update is called once per frame void Update() { if (amountOfBottles == 2) // Once both bottles are in then the condition is complete { Debug.Log("BOTTTLES!!!!"); bombPartTable.SetActive(false); bombStringTable.SetActive(false); bomb.SetActive(true); build.Play(); Destroy(this); } } private void OnTriggerEnter(Collider other) { //Instead of setting positions, I just destoyed the gameobject that can be moved. Then Set the preset gameobject to visible if (other.gameObject == bombPart) { bombPartTable.SetActive(true); } if (other.gameObject == bombString) { bombStringTable.SetActive(true); } Destroy(other.gameObject); amountOfBottles++; // Adding numbers of bottles Debug.Log("Bottle num = " + amountOfBottles); } }
dd3d285dd73d51965b0925ec359cdf0a2410a86d
C#
kahanu/CondorXE
/Src/Condor.Tests/CoreTests.cs
2.546875
3
using System; using System.Linq; using NUnit.Framework; using Condor.Core; namespace Condor.Tests { [TestFixture] public class CoreTests { [Test] public void pluralizer_factory_test() { // Arrange string tableName = "aspnet_Applications"; string result = tableName; ePluralizerTypes classType = EnumFactory.Parse<ePluralizerTypes>("Unchanged"); PluralizerFactory factory = new PluralizerFactory(); // Act result = factory.SetWord(tableName, classType); // Assert Assert.AreEqual(tableName, result); } [Test] public void pluralizer_factory_isentityset_returns_correct_result_for_input_with_underscore() { // Arrange string tableName = "aspnet_Applications"; string result = tableName; bool isEntitySet = true; ePluralizerTypes classType = EnumFactory.Parse<ePluralizerTypes>("Unchanged"); PluralizerFactory factory = new PluralizerFactory(); // Act result = factory.SetWord(tableName, classType, isEntitySet); // Assert Assert.AreEqual(tableName, result); } [Test] public void pluralizer_factory_isentityset_returns_plural_entitysetname_for_non_underscore_class_name() { // Arrange string tableName = "Project"; string result = tableName; bool isEntitySet = true; ePluralizerTypes classType = EnumFactory.Parse<ePluralizerTypes>("Unchanged"); PluralizerFactory factory = new PluralizerFactory(); // Act result = factory.SetWord(tableName, classType, isEntitySet); string expected = "Projects"; // Assert Assert.AreEqual(expected, result); } [Test] public void pluralizer_factory_returns_unchanged_class_name_for_non_entity_type() { // Arrange string tableName = "Customer"; string result = tableName; ePluralizerTypes classType = EnumFactory.Parse<ePluralizerTypes>("Unchanged"); PluralizerFactory factory = new PluralizerFactory(); // Act result = factory.SetWord(tableName, classType); // Assert Assert.AreEqual(tableName, result); } [Test] public void pluralizer_factory_returns_plural_result_for_singular_class_name_based_on_plural_setting() { // Arrange string tableName = "Customer"; string result = tableName; ePluralizerTypes classType = EnumFactory.Parse<ePluralizerTypes>("Plural"); PluralizerFactory factory = new PluralizerFactory(); // Act result = factory.SetWord(tableName, classType); string expected = "Customers"; // Assert Assert.AreEqual(expected, result); } } }
949abfd10fd9d129b197523d50e707ebe178be82
C#
LesterYehGood/FtxSynchroRestApi
/FtxRestSynchro/Rest/Data/AbstractRestData.cs
2.734375
3
using System; namespace FtxRestSynchro.Rest.Data { public abstract class AbstractRestData { public string Error { get; protected set; } public int ErrorCode { get; protected set; } public bool HasError => ErrorCode > 0; protected AbstractRestData(int errorCode) { ErrorCode = errorCode; } protected AbstractRestData(string error, int errorCode) { Error = error; ErrorCode = Math.Abs(errorCode); } protected AbstractRestData(string error) { Error = error; } protected AbstractRestData() { } public override string ToString() { return $"{nameof(Error)}: {Error}, {nameof(ErrorCode)}: {ErrorCode}"; } } }
af3640bca298eda79c2646620fbf422db2ef41e2
C#
AngleSharp/AngleSharp
/src/AngleSharp/Css/IStylingService.cs
2.65625
3
namespace AngleSharp.Css { using AngleSharp.Dom; using AngleSharp.Io; using System; using System.Threading; using System.Threading.Tasks; /// <summary> /// Defines the API of an available engine for computing the stylesheet. /// </summary> public interface IStylingService { /// <summary> /// Checks if the given type is supported. /// </summary> /// <param name="mimeType">The type of the style.</param> /// <returns>True if the type is supported, otherwise false.</returns> Boolean SupportsType(String mimeType); /// <summary> /// Parses a style sheet for the given response asynchronously. /// </summary> /// <param name="response"> /// The response with the stream representing the source of the /// stylesheet. /// </param> /// <param name="options"> /// The options with the parameters for evaluating the style. /// </param> /// <param name="cancel">The cancellation token.</param> /// <returns>The task resulting in the style sheet.</returns> Task<IStyleSheet> ParseStylesheetAsync(IResponse response, StyleOptions options, CancellationToken cancel); } }
c542e508106d64da30e14ee6ff627df15ab872ff
C#
Ansible2/Programming-Practice-Problems
/HackerRank Problems/HackerRank Easy Problems CS/Projects/Grading Students/Program.cs
3.234375
3
using System.CodeDom.Compiler; using System.Collections.Generic; using System.Collections; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.Serialization; using System.Text.RegularExpressions; using System.Text; using System; class Result { public static int getNearestIncriment(int number) { int incriment = 5; int newNumber = Math.Abs(number + (incriment / 2)); newNumber -= newNumber % incriment; return newNumber; } /* * Complete the 'gradingStudents' function below. * * The function is expected to return an INTEGER_ARRAY. * The function accepts INTEGER_ARRAY grades as parameter. */ public static List<int> gradingStudents(List<int> grades) { int minDontRound = 38; for (var index = 0; index < grades.Count; index++) { var grade = grades[index]; if (grade >= minDontRound) { int nearestGrade = getNearestIncriment(grade); // don't need to check if < 3 applies as it will have to be in order to round up with getNearestIncriment function if (nearestGrade > grade) { grades[index] = nearestGrade; } } } return grades; } } class Solution { public static void Main(string[] args) { //TextWriter textWriter = new StreamWriter(@System.Environment.GetEnvironmentVariable("OUTPUT_PATH"), true); int gradesCount = Convert.ToInt32(Console.ReadLine().Trim()); List<int> grades = new List<int>(); for (int i = 0; i < gradesCount; i++) { int gradesItem = Convert.ToInt32(Console.ReadLine().Trim()); grades.Add(gradesItem); } List<int> result = Result.gradingStudents(grades); Console.WriteLine(); foreach (int number in result) { Console.WriteLine(number); } //textWriter.WriteLine(String.Join("\n", result)); //textWriter.Flush(); //textWriter.Close(); } }
52ed68874237ff78a75a44487f3ec51b806aa5bb
C#
Artery/Portfolio
/HotKeySystem/HotKeySystem example/HotKeySystem/HelperClasses/HotKeyConfig.cs
2.609375
3
using System; namespace HotKeySystem_example.HotKeySystem { //Initializer-class for HotKeys public class HotKeyConfig { public Type CommandType { get; set; } public string Description { get; set; } public string hotkeyGestureString { get; set; } public HotKeyConfig(Type commandType, string hotkeyGestureString, string description) { this.CommandType = commandType; this.Description = description; this.hotkeyGestureString = hotkeyGestureString; } } }
33f8363284cb19788bdeffdb0c6172cf9ce93369
C#
forki/Nap
/src/Nap/Configuration/Base/ISerializersConfig.cs
2.78125
3
using System; using System.Collections.Generic; using System.Linq; using Nap.Serializers.Base; namespace Nap.Configuration { /// <summary> /// Represents a collection of serializers that can have additional serializers added. /// </summary> public interface ISerializersConfig : ICollection<ISerializerConfig> { /// <summary> /// Adds the specified serializer by specifying key/value pair. /// </summary> /// <param name="contentType">The key of the serializer to add (see MIME types).</param> /// <param name="serializerType">The full type name of the serializer to add.</param> void Add(string contentType, string serializerType); /// <summary> /// Adds the specified serializer generically. /// </summary> /// <typeparam name="T">The type of <see cref="INapSerializer"/> to add.</typeparam> void Add<T>() where T : INapSerializer, new(); /// <summary> /// Adds the specified serializer generically. /// </summary> /// <param name="contentType">The content type to apply the serializer to.</param> /// <typeparam name="T">The type of <see cref="INapSerializer"/> to add.</typeparam> void Add<T>(string contentType) where T : INapSerializer, new(); /// <summary> /// Adds the specified serializer by specifying an instance of the serializer. /// </summary> /// <param name="napSerializer">The serializer instance to add to the collection of serializers.</param> void Add(INapSerializer napSerializer); /// <summary> /// Adds the specified serializer by specifying an instance of the serializer. /// </summary> /// <param name="napSerializer">The serializer instance to add to the collection of serializers.</param> /// <param name="contentType">The content type to apply the serializer to.</param> void Add(INapSerializer napSerializer, string contentType); /// <summary> /// Remvoes the specified serializer by key, a string of appropriate MIME type. /// </summary> /// <param name="contentType">The MIME type key of the serializer to remove.</param> void Remove(string contentType); /// <summary> /// Converts the <see cref="ISerializersConfig"/> interface to a dicitonary. /// Note that operations on this object (such as <see cref="IDictionary{T1,T2}.Add(T1, T2)"/>) do not persist. /// </summary> /// <returns>The <see cref="ISerializersConfig"/> interface as a dictionary.</returns> IDictionary<string, INapSerializer> AsDictionary(); } }
14f94ef2e58486e056ba5ae19e75a4775eb68f35
C#
KrolKamil/Shooter
/Assets/scripts/GameController.cs
2.578125
3
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; public class GameController : MonoBehaviour { private int gainedPoints = 0; public Text boosses; // Start is called before the first frame update void Start() { Debug.Log("IM GAME CONTRLL"); boosses.text = (3 - gainedPoints).ToString(); } public void gainPoint() { gainedPoints++; int newScore = 3 - gainedPoints; boosses.text = newScore.ToString(); if (gainedPoints >= 3) { winGame(); } } public void winGame() { SceneManager.LoadScene("Win"); } // Update is called once per frame void Update() { } }
b909063ee51ea56a4d4c3541cfa860e577f519dc
C#
1904-apr22-net/thomas-project1
/Project1_CigarShop/CigarShop.DataAccess/Mapper.cs
2.703125
3
using System; using System.Collections.Generic; using System.Text; using System.Linq; using CigarShop.Library.Models; namespace CigarShop.DataAccess { public static class Mapper { public static Library.Models.Manufacturer Map(Entities.Manufacturer manufacturer) => new Library.Models.Manufacturer { Id = manufacturer.Id, ManufacturerName = manufacturer.Name, Cigars = Map(manufacturer.Cigar).ToList() }; public static Entities.Manufacturer Map(Library.Models.Manufacturer manufacturer) => new Entities.Manufacturer { Id = manufacturer.Id, Name = manufacturer.ManufacturerName, Cigar = Map(manufacturer.Cigars).ToList() }; public static Library.Models.Cigar Map(Entities.Cigar cigar) => new Library.Models.Cigar { Id = cigar.Id, CigarName = cigar.Name, }; public static Entities.Cigar Map(Library.Models.Cigar cigar) => new Entities.Cigar { Id = cigar.Id, Name = cigar.CigarName, }; public static IEnumerable<Library.Models.Cigar> Map(IEnumerable<Entities.Cigar> cigar) => cigar.Select(Map); public static IEnumerable<Entities.Cigar> Map(IEnumerable<Library.Models.Cigar> cigar) => cigar.Select(Map); public static IEnumerable<Library.Models.Manufacturer> Map(IEnumerable<Entities.Manufacturer> manufacturer) => manufacturer.Select(Map); public static IEnumerable<Entities.Manufacturer> Map(IEnumerable<Library.Models.Manufacturer> manufacturer) => manufacturer.Select(Map); } }
31cde8ec23829240e0cda6f33928b2965fbcf970
C#
RuiAAPereira/FormacaoDGR
/FormacaoDGR/Areas/Identity/Services/AppUserRoleService.cs
2.53125
3
using FormacaoDGR.Areas.Identity.Models; using FormacaoDGR.Data; using Microsoft.EntityFrameworkCore; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace FormacaoDGR.Areas.Identity.Services { public interface IAppUserRoleService { Task<IList<ApplicationUserRole>> GetAllUserRolesAsync(); Task<ApplicationUserRole> GetUserRoleAsync(string id); Task<ApplicationUserRole> AddUserRoleAsync(ApplicationUserRole appUserRole); Task<ApplicationUserRole> UpdateUserRoleAsync(ApplicationUserRole appUserRole); Task<ApplicationUserRole> DeleteUserRoleAsync(ApplicationUserRole appUserRole); Task<ApplicationUserRole> DeleteAllUserRolesAsync(string uid); } public class AppUserRoleService : IAppUserRoleService { private readonly ApplicationDbContext _db; public AppUserRoleService(ApplicationDbContext context) { _db = context; } public async Task<IList<ApplicationUserRole>> GetAllUserRolesAsync() { try { IList<ApplicationUserRole> userRolesList = await _db.ApplicationUserRoles.ToListAsync(); return userRolesList; } catch (System.Exception) { throw; } } public async Task<ApplicationUserRole> GetUserRoleAsync(string id) { try { ApplicationUserRole appUserRole = await _db.ApplicationUserRoles.Where(i => i.UserId == id).FirstOrDefaultAsync(); return appUserRole; } catch (System.Exception) { throw; } } public async Task<ApplicationUserRole> AddUserRoleAsync(ApplicationUserRole appUserRole) { try { _ = _db.ApplicationUserRoles.Add(appUserRole); _ = await _db.SaveChangesAsync(); return appUserRole; } catch (System.Exception) { throw; } } public async Task<ApplicationUserRole> UpdateUserRoleAsync(ApplicationUserRole appUserRole) { try { _ = _db.Entry(appUserRole).State = EntityState.Modified; _ = await _db.SaveChangesAsync(); return appUserRole; } catch (System.Exception) { throw; } } public async Task<ApplicationUserRole> DeleteUserRoleAsync(ApplicationUserRole appUserRole) { try { _ = _db.ApplicationUserRoles.Remove(appUserRole); _ = await _db.SaveChangesAsync(); return appUserRole; } catch (System.Exception) { throw; } } public async Task<ApplicationUserRole> DeleteAllUserRolesAsync(string uid) { try { IList<ApplicationUserRole> userRolesList = await _db.ApplicationUserRoles.Where(i => i.UserId == uid).ToListAsync(); foreach (var userRoles in userRolesList) { _db.ApplicationUserRoles.Remove(userRoles); } _ = await _db.SaveChangesAsync(); return null; } catch (System.Exception) { throw; } } } }
476135fef87fe3c9a0e6fca194dff67e5d6ff578
C#
vendethiel/retina
/Retina/Retina/Stages/ReplaceStage.cs
2.9375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using Retina.Replace; namespace Retina.Stages { public class ReplaceStage : RegexStage { string ReplacementString { get; set; } public ReplaceStage(Options options, string pattern, string replacement) : base(options, pattern) { ReplacementString = replacement; } protected override StringBuilder Process(string input) { var replacer = new Replacer(Pattern, ReplacementString); var builder = new StringBuilder(); int i = 0; IEnumerable<Match> matches = from Match m in Pattern.Matches(input) orderby m.Index, m.Length select m; int j = 0; foreach (Match m in matches) { builder.Append(input.Substring(i, m.Index - i)); if (!Options.IsInRange(0, j++, matches.Count())) builder.Append(m.Value); else builder.Append(replacer.Process(input, m)); i = m.Index + m.Length; } builder.Append(input.Substring(i)); return builder; } } }
bd791cd0b88622bcecdb5dedb0d7aa0f384ae261
C#
sawdyk/SoftlearnV1
/SoftLearnV1/Repositories/ReportDashboardRepo.cs
2.640625
3
using Microsoft.EntityFrameworkCore; using SoftLearnV1.Helpers; using SoftLearnV1.InterfaceRepositories; using SoftLearnV1.ResponseModels; using SoftLearnV1.Utilities; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace SoftLearnV1.Repositories { public class ReportDashboardRepo : IReportDashboardRepo { private readonly AppDbContext _context; public ReportDashboardRepo(AppDbContext context) { this._context = context; } //-------------------------Parent-------------------------------------------- public async Task<GenericResponseModel> getNoOfCampusesForChildrenAsync(Guid parentId) { try { IList<long> campusList = new List<long>(); var parent = await _context.Parents.Where(x => x.Id == parentId).FirstOrDefaultAsync(); if (parent == null) { return new GenericResponseModel { StatusCode = 400, StatusMessage = "Parent doesn't exist" }; } //Get children attached to parents var parentStudent = await _context.ParentsStudentsMap.Where(x => x.ParentId == parentId).ToListAsync(); if (parentStudent.Count() == 0) { return new GenericResponseModel { StatusCode = 401, StatusMessage = "No child is attached to this parent" }; } else { foreach(var child in parentStudent) { //Get child assigned to class var student = await _context.GradeStudents.Where(x => x.StudentId == child.StudentId && x.HasGraduated == false).FirstOrDefaultAsync(); if(student != null) { if (!campusList.Contains(student.CampusId)) { campusList.Add(student.CampusId); } } } } return new GenericResponseModel { StatusCode = 200, StatusMessage = "Successful", Data = campusList.Count() }; } catch (Exception exMessage) { ErrorLogger err = new ErrorLogger(); var logError = err.logError(exMessage); await _context.ErrorLog.AddAsync(logError); await _context.SaveChangesAsync(); return new GenericResponseModel { StatusCode = 500, StatusMessage = "An Error Occured!" }; } } public async Task<GenericResponseModel> getNoOfChildrenAsync(Guid parentId) { try { IList<object> studentList = new List<object>(); var parent = await _context.Parents.Where(x => x.Id == parentId).FirstOrDefaultAsync(); if (parent == null) { return new GenericResponseModel { StatusCode = 400, StatusMessage = "Parent doesn't exist" }; } //Get children attached to parents var parentStudent = await _context.ParentsStudentsMap.Where(x => x.ParentId == parentId).ToListAsync(); if (parentStudent.Count() == 0) { return new GenericResponseModel { StatusCode = 401, StatusMessage = "No child is attached to this parent" }; } else { foreach (var child in parentStudent) { //Get child assigned to class var student = await _context.GradeStudents.Where(x => x.StudentId == child.StudentId && x.HasGraduated == false).FirstOrDefaultAsync(); if (student != null) { studentList.Add(student); } } } return new GenericResponseModel { StatusCode = 200, StatusMessage = "Successful", Data = studentList.Count() }; } catch (Exception exMessage) { ErrorLogger err = new ErrorLogger(); var logError = err.logError(exMessage); await _context.ErrorLog.AddAsync(logError); await _context.SaveChangesAsync(); return new GenericResponseModel { StatusCode = 500, StatusMessage = "An Error Occured!" }; } } public async Task<GenericResponseModel> getNoOfClassesForChildrenAsync(Guid parentId) { try { IList<long> classList = new List<long>(); var parent = await _context.Parents.Where(x => x.Id == parentId).FirstOrDefaultAsync(); if (parent == null) { return new GenericResponseModel { StatusCode = 400, StatusMessage = "Parent doesn't exist" }; } //Get children attached to parents var parentStudent = await _context.ParentsStudentsMap.Where(x => x.ParentId == parentId).ToListAsync(); if (parentStudent.Count() == 0) { return new GenericResponseModel { StatusCode = 401, StatusMessage = "No child is attached to this parent" }; } else { foreach (var child in parentStudent) { //Get child detail var student = await _context.GradeStudents.Where(x => x.StudentId == child.StudentId && x.HasGraduated == false).FirstOrDefaultAsync(); if (student != null) { if (!classList.Contains(student.ClassId)) { classList.Add(student.ClassId); } } } } return new GenericResponseModel { StatusCode = 200, StatusMessage = "Successful", Data = classList.Count() }; } catch (Exception exMessage) { ErrorLogger err = new ErrorLogger(); var logError = err.logError(exMessage); await _context.ErrorLog.AddAsync(logError); await _context.SaveChangesAsync(); return new GenericResponseModel { StatusCode = 500, StatusMessage = "An Error Occured!" }; } } public async Task<GenericResponseModel> getTotalAmountPaidForCurrentTermAsync(Guid parentId) { try { long totalAmountPaid = 0; var parent = await _context.Parents.Where(x => x.Id == parentId).FirstOrDefaultAsync(); if (parent == null) { return new GenericResponseModel { StatusCode = 400, StatusMessage = "Parent doesn't exist" }; } //Get current term for school var academicSession = await _context.AcademicSessions.Where(x => x.IsCurrent == true && x.SchoolId == parent.SchoolId).FirstOrDefaultAsync(); if (academicSession == null) { return new GenericResponseModel { StatusCode = 402, StatusMessage = "Current term is not set" }; } //Get children attached to parents var parentStudent = await _context.ParentsStudentsMap.Where(x => x.ParentId == parentId).ToListAsync(); if (parentStudent.Count() == 0) { return new GenericResponseModel { StatusCode = 401, StatusMessage = "No child is attached to this parent" }; } else { foreach (var child in parentStudent) { //Get child detail var student = await _context.GradeStudents.Where(x => x.StudentId == child.StudentId && x.HasGraduated == false).FirstOrDefaultAsync(); if (student != null) { //Get approved payment var approvedPayment = await _context.SchoolFeesPayments.Where(x => x.StudentId == student.StudentId && x.TermId == academicSession.TermId).FirstOrDefaultAsync(); if (approvedPayment != null) { totalAmountPaid += approvedPayment.AmountPaid; } } } } return new GenericResponseModel { StatusCode = 200, StatusMessage = "Successful", Data = totalAmountPaid }; } catch (Exception exMessage) { ErrorLogger err = new ErrorLogger(); var logError = err.logError(exMessage); await _context.ErrorLog.AddAsync(logError); await _context.SaveChangesAsync(); return new GenericResponseModel { StatusCode = 500, StatusMessage = "An Error Occured!" }; } } //-------------------------Class Teacher-------------------------------------------- public async Task<GenericResponseModel> getNoOfStudentsInTeacherClassAsync(Guid teacherId) { try { long totalStudent = 0; var teacherUser = await _context.SchoolUsers.Where(x => x.Id == teacherId).FirstOrDefaultAsync(); if (teacherUser == null) { return new GenericResponseModel { StatusCode = 400, StatusMessage = "Teacher doesn't exist" }; } //Get all classGrade for teacher var gradeTeacher = await _context.GradeTeachers.Where(x => x.SchoolUserId == teacherId).ToListAsync(); if (gradeTeacher.Count() == 0) { return new GenericResponseModel { StatusCode = 401, StatusMessage = "Teacher hasn't been assigned to any class" }; } else { foreach (var teacher in gradeTeacher) { //Get child detail var students = await _context.GradeStudents.Where(x => x.ClassGradeId == teacher.ClassGradeId && x.HasGraduated == false).ToListAsync(); totalStudent += students.Count(); } } return new GenericResponseModel { StatusCode = 200, StatusMessage = "Successful", Data = totalStudent }; } catch (Exception exMessage) { ErrorLogger err = new ErrorLogger(); var logError = err.logError(exMessage); await _context.ErrorLog.AddAsync(logError); await _context.SaveChangesAsync(); return new GenericResponseModel { StatusCode = 500, StatusMessage = "An Error Occured!" }; } } public async Task<GenericResponseModel> getNoOfFemaleStudentsInTeacherClassAsync(Guid teacherId) { try { IList<object> totalFemaleStudent = new List<object>(); var teacherUser = await _context.SchoolUsers.Where(x => x.Id == teacherId).FirstOrDefaultAsync(); if (teacherUser == null) { return new GenericResponseModel { StatusCode = 400, StatusMessage = "Teacher doesn't exist" }; } //Get all classGrade for teacher var gradeTeacher = await _context.GradeTeachers.Where(x => x.SchoolUserId == teacherId).ToListAsync(); if (gradeTeacher.Count() == 0) { return new GenericResponseModel { StatusCode = 401, StatusMessage = "Teacher hasn't been assigned to any class" }; } else { foreach (var teacher in gradeTeacher) { //Get child detail var students = await _context.GradeStudents.Where(x => x.ClassGradeId == teacher.ClassGradeId && x.HasGraduated == false).ToListAsync(); foreach(var student in students) { var studentRecord = await _context.Students.Where(x => x.Id == student.StudentId && x.GenderId == Convert.ToInt64(EnumUtility.Gender.Female)).FirstOrDefaultAsync(); if(studentRecord != null) { totalFemaleStudent.Add(studentRecord); } } } } return new GenericResponseModel { StatusCode = 200, StatusMessage = "Successful", Data = totalFemaleStudent.Count() }; } catch (Exception exMessage) { ErrorLogger err = new ErrorLogger(); var logError = err.logError(exMessage); await _context.ErrorLog.AddAsync(logError); await _context.SaveChangesAsync(); return new GenericResponseModel { StatusCode = 500, StatusMessage = "An Error Occured!" }; } } public async Task<GenericResponseModel> getNoOfMaleStudentsInTeacherClassAsync(Guid teacherId) { try { IList<object> totalFemaleStudent = new List<object>(); var teacherUser = await _context.SchoolUsers.Where(x => x.Id == teacherId).FirstOrDefaultAsync(); if (teacherUser == null) { return new GenericResponseModel { StatusCode = 400, StatusMessage = "Teacher doesn't exist" }; } //Get all classGrade for teacher var gradeTeacher = await _context.GradeTeachers.Where(x => x.SchoolUserId == teacherId).ToListAsync(); if (gradeTeacher.Count() == 0) { return new GenericResponseModel { StatusCode = 401, StatusMessage = "Teacher hasn't been assigned to any class" }; } else { foreach (var teacher in gradeTeacher) { //Get child detail var students = await _context.GradeStudents.Where(x => x.ClassGradeId == teacher.ClassGradeId && x.HasGraduated == false).ToListAsync(); foreach (var student in students) { var studentRecord = await _context.Students.Where(x => x.Id == student.StudentId && x.GenderId == Convert.ToInt64(EnumUtility.Gender.Male)).FirstOrDefaultAsync(); if (studentRecord != null) { totalFemaleStudent.Add(studentRecord); } } } } return new GenericResponseModel { StatusCode = 200, StatusMessage = "Successful", Data = totalFemaleStudent.Count() }; } catch (Exception exMessage) { ErrorLogger err = new ErrorLogger(); var logError = err.logError(exMessage); await _context.ErrorLog.AddAsync(logError); await _context.SaveChangesAsync(); return new GenericResponseModel { StatusCode = 500, StatusMessage = "An Error Occured!" }; } } public async Task<GenericResponseModel> getNoOfSubjectsInTeacherClassAsync(Guid teacherId) { try { long totalSubject = 0; IList<object> subjectList = new List<object>(); var teacherUser = await _context.SchoolUsers.Where(x => x.Id == teacherId).FirstOrDefaultAsync(); if (teacherUser == null) { return new GenericResponseModel { StatusCode = 400, StatusMessage = "Teacher doesn't exist" }; } //Get all classGrade for teacher var gradeTeacher = await _context.GradeTeachers.Where(x => x.SchoolUserId == teacherId).ToListAsync(); if (gradeTeacher.Count() == 0) { return new GenericResponseModel { StatusCode = 401, StatusMessage = "Teacher hasn't been assigned to any class" }; } else { foreach (var teacher in gradeTeacher) { //Get child detail var subjects = await _context.SchoolSubjects.Where(x => x.ClassId == teacher.ClassId).ToListAsync(); foreach(var subject in subjects) { if (!subjectList.Contains(subject)) { subjectList.Add(subject); } } //totalSubject += subjects.Count(); } } return new GenericResponseModel { StatusCode = 200, StatusMessage = "Successful", Data = subjectList.Count() }; } catch (Exception exMessage) { ErrorLogger err = new ErrorLogger(); var logError = err.logError(exMessage); await _context.ErrorLog.AddAsync(logError); await _context.SaveChangesAsync(); return new GenericResponseModel { StatusCode = 500, StatusMessage = "An Error Occured!" }; } } //-------------------------School Admin-------------------------------------------- public async Task<GenericResponseModel> getNoOfNonTeachingStaffsInSchoolAsync(Guid schoolAdminId) { try { IList<object> userList = new List<object>(); var adminUser = await _context.SchoolUsers.Where(x => x.Id == schoolAdminId).FirstOrDefaultAsync(); if (adminUser == null) { return new GenericResponseModel { StatusCode = 400, StatusMessage = "Admin User doesn't exist" }; } var checkRole = await _context.SchoolUserRoles.Where(x => x.UserId == adminUser.Id && x.RoleId == (long)EnumUtility.SchoolRoles.SuperAdministrator).FirstOrDefaultAsync(); if (checkRole == null) { return new GenericResponseModel { StatusCode = 401, StatusMessage = "Only school super admin can perform this operation" }; } //get all school users var schoolUsers = await _context.SchoolUsers.Where(x => x.SchoolId == adminUser.SchoolId).ToListAsync(); foreach(var schoolUser in schoolUsers) { var userRole = await _context.SchoolUserRoles.Where(x => x.UserId == schoolUser.Id && !(x.RoleId == (long)EnumUtility.SchoolRoles.ClassTeacher || x.RoleId == (long)EnumUtility.SchoolRoles.SubjectTeacher)).FirstOrDefaultAsync(); if (userRole != null) { userList.Add(userRole); } } return new GenericResponseModel { StatusCode = 200, StatusMessage = "Successful", Data = userList.Count() }; } catch (Exception exMessage) { ErrorLogger err = new ErrorLogger(); var logError = err.logError(exMessage); await _context.ErrorLog.AddAsync(logError); await _context.SaveChangesAsync(); return new GenericResponseModel { StatusCode = 500, StatusMessage = "An Error Occured!" }; } } public async Task<GenericResponseModel> getNoOfSchoolCampusesAsync(Guid schoolAdminId) { try { IList<object> userList = new List<object>(); var adminUser = await _context.SchoolUsers.Where(x => x.Id == schoolAdminId).FirstOrDefaultAsync(); if (adminUser == null) { return new GenericResponseModel { StatusCode = 400, StatusMessage = "Admin User doesn't exist" }; } var checkRole = await _context.SchoolUserRoles.Where(x => x.UserId == adminUser.Id && x.RoleId == (long)EnumUtility.SchoolRoles.SuperAdministrator).FirstOrDefaultAsync(); if(checkRole == null) { return new GenericResponseModel { StatusCode = 401, StatusMessage = "Only school super admin can perform this operation" }; } var schoolCampuses = await _context.SchoolCampuses.Where(x => x.SchoolId == adminUser.SchoolId).ToListAsync(); return new GenericResponseModel { StatusCode = 200, StatusMessage = "Successful", Data = schoolCampuses.Count() }; } catch (Exception exMessage) { ErrorLogger err = new ErrorLogger(); var logError = err.logError(exMessage); await _context.ErrorLog.AddAsync(logError); await _context.SaveChangesAsync(); return new GenericResponseModel { StatusCode = 500, StatusMessage = "An Error Occured!" }; } } public async Task<GenericResponseModel> getNoOfStudentsInSchoolAsync(Guid schoolAdminId) { try { IList<object> userList = new List<object>(); var adminUser = await _context.SchoolUsers.Where(x => x.Id == schoolAdminId).FirstOrDefaultAsync(); if (adminUser == null) { return new GenericResponseModel { StatusCode = 400, StatusMessage = "Admin User doesn't exist" }; } var checkRole = await _context.SchoolUserRoles.Where(x => x.UserId == adminUser.Id && x.RoleId == (long)EnumUtility.SchoolRoles.SuperAdministrator).FirstOrDefaultAsync(); if (checkRole == null) { return new GenericResponseModel { StatusCode = 401, StatusMessage = "Only school super admin can perform this operation" }; } var gradeStudents = await _context.GradeStudents.Where(x => x.SchoolId == adminUser.SchoolId && x.HasGraduated == false).ToListAsync(); return new GenericResponseModel { StatusCode = 200, StatusMessage = "Successful", Data = gradeStudents.Count() }; } catch (Exception exMessage) { ErrorLogger err = new ErrorLogger(); var logError = err.logError(exMessage); await _context.ErrorLog.AddAsync(logError); await _context.SaveChangesAsync(); return new GenericResponseModel { StatusCode = 500, StatusMessage = "An Error Occured!" }; } } public async Task<GenericResponseModel> getNoOfTeachersInSchoolAsync(Guid schoolAdminId) { try { long totalSubject = 0; IList<object> userList = new List<object>(); var adminUser = await _context.SchoolUsers.Where(x => x.Id == schoolAdminId).FirstOrDefaultAsync(); if (adminUser == null) { return new GenericResponseModel { StatusCode = 400, StatusMessage = "Admin User doesn't exist" }; } var schoolUsers = await _context.SchoolUsers.Where(x => x.SchoolId == adminUser.SchoolId).ToListAsync(); foreach (var schoolUser in schoolUsers) { var userRole = await _context.SchoolUserRoles.Where(x => x.UserId == schoolUser.Id && (x.RoleId == (long)EnumUtility.SchoolRoles.ClassTeacher || x.RoleId == (long)EnumUtility.SchoolRoles.SubjectTeacher)).FirstOrDefaultAsync(); if (userRole != null) { userList.Add(userRole); } } return new GenericResponseModel { StatusCode = 200, StatusMessage = "Successful", Data = userList.Count() }; } catch (Exception exMessage) { ErrorLogger err = new ErrorLogger(); var logError = err.logError(exMessage); await _context.ErrorLog.AddAsync(logError); await _context.SaveChangesAsync(); return new GenericResponseModel { StatusCode = 500, StatusMessage = "An Error Occured!" }; } } } }
748d027e797f7a2e13a64e3d10fb18c878b4dce1
C#
Patplays852/ProjectEuler
/ProblemSolver/ProblemSolver/src/Problem004.cs
3.390625
3
/* Largest palindrome product Problem 4 A palindromic number reads the same both ways.The largest palindrome made from the product of two 2 - digit numbers is 9009 = 91 × 99. Find the largest palindrome made from the product of two 3 - digit numbers. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ProblemSolver.src { class Problem004 : SolvedProblems { public override void Solve() { ulong ret = 0; for (ulong x = 999; x > 0; x--) { for (ulong y = 999; y > 0; y--) { ulong prod = x * y; if (prod > ret && EulerHelper.isPalindrome(ret.ToString())) { ret = prod; } } } EulerHelper.printAns(ret.ToString()); } } }
a3a27f4f33d69f005b11702962817a0f30cd0f32
C#
excelexpress/WPF_CreateElement_GH
/Classes/CreateXMLShape.cs
2.578125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Reflection; using sp = ExcelExpress.ComplexShape.SectionProperties; using task = ExcelExpress.ComplexShape.ExcelTasks; namespace CreateElement { public partial class MainWindow : Window { public task.Shape CreateXMLShape(int elementID, string Material, string point, string xp, string yp, string theta, bool xmirror, bool ymirror) { IEnumerable<task.Shape> Eshape = ReflectiveEnumerator.GetEnumerableOfType<task.Shape>(); task.Shape shape = null; TreeViewItem selectedTVI = (TreeViewItem)treeView.SelectedItem; string selectedShape = selectedTVI.Header.ToString(); bool test = selectedTVI.HasItems; string parentName = null; if (selectedTVI.Parent.GetType() == typeof(TreeViewItem)) // verify that parent is TreeViewItem { TreeViewItem parent = (TreeViewItem)selectedTVI.Parent; parentName = parent.Header.ToString(); } int elmID = elementID; if (!test) { if (parentName == "Basic Shapes") { foreach (task.Shape sh in Eshape) { if (sh.GetType().Name == selectedShape.Replace(" ", string.Empty)) { sh.MatName = Material; sh.PointID = point; sh.xp_formula = xp; sh.yp_formula = yp; sh.theta_formula = theta; sh.MirrorX = xmirror; sh.MirrorY = ymirror; sh.ElementID = elmID; foreach (ShapeProperty shape_prop in ShapeProperties) { object[] myobject = new object[1]; //[shape_prop.Value]; myobject[0] = shape_prop.Value; //dynamic value = shape_prop.Value; string sh_property = shape_prop.Name + "_formula"; sh.GetType().InvokeMember(sh_property, BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty, Type.DefaultBinder, sh, myobject); } shape = sh; } } } if (parentName == "Machined Shapes") { foreach (task.Shape sh in Eshape) { if (sh.GetType().Name == "Machined" + selectedShape.Replace(" ", string.Empty)) { sh.MatName = Material; sh.PointID = point; sh.xp_formula = xp; sh.yp_formula = yp; sh.theta_formula = theta; sh.MirrorX = xmirror; sh.MirrorY = ymirror; sh.ElementID = elmID; foreach (ShapeProperty shape_prop in ShapeProperties) { object[] myobject = new object[1]; //[shape_prop.Value]; myobject[0] = shape_prop.Value; //dynamic value = shape_prop.Value; string sh_property = shape_prop.Name + "_formula"; sh.GetType().InvokeMember(sh_property, BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty, Type.DefaultBinder, sh, myobject); } shape = sh; } } } if (parentName == "Formed Shapes") { foreach (task.Shape sh in Eshape) { if (sh.GetType().Name == "Formed" + selectedShape.Replace(" ", string.Empty)) { sh.MatName = Material; sh.PointID = point; sh.xp_formula = xp; sh.yp_formula = yp; sh.theta_formula = theta; sh.MirrorX = xmirror; sh.MirrorY = ymirror; sh.ElementID = elmID; foreach (ShapeProperty shape_prop in ShapeProperties) { object[] myobject = new object[1]; //[shape_prop.Value]; myobject[0] = shape_prop.Value; //dynamic value = shape_prop.Value; string sh_property = shape_prop.Name + "_formula"; sh.GetType().InvokeMember(sh_property, BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty, Type.DefaultBinder, sh, myobject); } shape = sh; } } } } return shape; } } }
d388c495febe2a680ea22f7e678fb3722fd7aadc
C#
livianegrini/EplayersMVC
/Controllers/LoginController.cs
2.75
3
using System.Collections.Generic; using EPlayersMVC.Models; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace EplayersMVC.Controllers { [Route("Login")] public class LoginController : Controller { // TempData é para receber coisas curtas e temporárias [TempData] public string Mensagem { get; set; } Jogador jogadorModel = new Jogador(); public IActionResult Index() { return View(); } [Route("Logar")] public IActionResult Logar(IFormCollection form) { // Procurar se o usuário que está dentro do form está sendo encontrado dentro do meu arquivo csv List<string> jogadoresCSV = jogadorModel.LerTodasAsLinhasCSV("Database/jogador.csv"); // Método que busca dentro dessa lista / verificar se o usuário é nulo ou não var logado = jogadoresCSV.Find( // x = cada item x => x.Split(";")[3] == form["Email"] && x.Split(";")[4] == form["Senha"] // pegar as posições 3,4 e comparar com email e senha ); if (logado != null) { // comparando, se for diferente de nulo, é porque encontrou o jogador e redireciona pra tela inicial // Atribuir um valor dentro da sessao HttpContext.Session.SetString("_UserName", logado.Split(";")[1]); return LocalRedirect("~/"); // ~/ Faz voltar pra tela principal, pois pega o caminho raiz e mais nada } Mensagem = "Dados incorretos, tente novamente!"; return LocalRedirect("~/Login"); } [Route("Logout")] public IActionResult Logout() { HttpContext.Session.Remove("_UserName"); return LocalRedirect("~/"); } } }
dd115185fccd4e589abd976adb9d7eef6b17dd86
C#
smellyriver/tank-inspector-pro
/src/Smellyriver.TankInspector.Core/TankInspector.Pro/Data/Entities/Camouflage.cs
2.515625
3
using System; using System.Linq; namespace Smellyriver.TankInspector.Pro.Data.Entities { public class Camouflage : XQueryableWrapper { private static CamouflageKind ParseCamouflageKind(string kind) { switch(kind) { case "summer" : return CamouflageKind.Summer; case "winter": return CamouflageKind.Winter; case "desert": return CamouflageKind.Desert; default: throw new NotSupportedException(); } } public string Key { get { return this["@key"]; } } public string Texture { get { return this["texture"]; } } public double PriceFactor { get { return this.QueryDouble("priceFactor"); } } public double CamouflageFactor { get { return this.QueryDouble("invisibilityFactor"); } } public string Description { get { return this["description"]; } } public int Id { get { return this.QueryInt("@id"); } } public CamouflageKind Kind { get { return Camouflage.ParseCamouflageKind(this["kind"].Trim()); } } public CamouflageGroup Group { get; internal set; } public Camouflage(IXQueryable data) : base(data) { } private string[] LoadDeniedTankKeys() { var deny = this["deny"]; if (deny == null) return new string[0]; return deny.Split((char[])null, StringSplitOptions.RemoveEmptyEntries); } public bool GetIsDenied(string tankKey) { return this.QueryManyValues("deny").Any(d => d.Trim() == tankKey); } } }
6082387aec9843fbf51149c58767f79557f06b39
C#
TanBinh1601/BtapCSharp
/NguyenTanBinh/ModelEF/DAO/HangSXDao.cs
2.703125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ModelEF.Model; using PagedList; namespace ModelEF.DAO { public class HangSXDao { private NguyenTanBinhContext db; public HangSXDao() { db = new NguyenTanBinhContext(); } public List<HangSX> ListAll() { return db.HangSXes.ToList(); } public IEnumerable<HangSX> ListWhereAll(string keysearch, int page, int pagesize) { IQueryable<HangSX> model = db.HangSXes; if (!string.IsNullOrEmpty(keysearch)) model = model.Where(x => x.HangSX1.Contains(keysearch)); return model.OrderBy(x => x.HangSX1).ToPagedList(page, pagesize); } public string Insert(HangSX entityHsx) { var hsx = Find(entityHsx.IdHang); if (hsx == null) { db.HangSXes.Add(entityHsx); } else { hsx.IdHang = entityHsx.IdHang; } db.SaveChanges(); return entityHsx.HangSX1; } public string Edit(HangSX entityHsx) { var hsx = Find(entityHsx.IdHang); if (hsx == null) { db.HangSXes.Add(entityHsx); } else { hsx.IdHang = entityHsx.IdHang; hsx.HangSX1 = entityHsx.HangSX1; } db.SaveChanges(); return entityHsx.IdHang.ToString(); } public bool Delete(int id) { try { var hsx = db.HangSXes.Find(id); db.HangSXes.Remove(hsx); db.SaveChanges(); return true; } catch (Exception) { return false; } } public int find(string tenHang) { var query = db.HangSXes.SingleOrDefault(c => c.HangSX1.Contains(tenHang)); if (query == null) { return 1; } else { return 0; } } public HangSX Find(int id) { return db.HangSXes.Find(id); } } }
44a9351dc546dae72bd9082273a9da46fcba1e1f
C#
aplavin/olympchecker.gui
/Sources/CompilersManager.cs
2.9375
3
 using System.Collections.Generic; using System.IO; using System.Linq; using Nini.Config; namespace olympchecker_gui { static class CompilersManager { private static readonly string fileName = Path.Combine(Directory.GetCurrentDirectory(), "compilers.ini"); public static List<Compiler> compilers { get; set; } private static IConfigSource configSource; public static void Load() { try { configSource = new IniConfigSource(fileName); } catch (IOException) { Utils.FatalError("Ошибка при открытии файла \"" + fileName + "\""); } try { // Fill compilers list using data from configSource compilers = (from IConfig iConfig in configSource.Configs where iConfig.Name.StartsWith("Compiler_") select new Compiler( iConfig.Get("Name"), iConfig.Get("Path"), iConfig.Get("Options"), iConfig.Get("Extensions")) ) .ToList(); foreach (Compiler comp in compilers) { if (!Path.IsPathRooted(comp.path)) { comp.path = Path.Combine(Program.programDirectory, comp.path); } } } catch (Nini.Ini.IniException) { Utils.FatalError("Ошибка в формате файла \"" + fileName + "\""); } } public static void Save() { try { configSource.Configs.Clear(); for (int i = 0; i < compilers.Count; i++) { configSource.AddConfig("Compiler_" + i); configSource.Configs["Compiler_" + i].Set("Name", compilers[i].name); configSource.Configs["Compiler_" + i].Set("Extensions", compilers[i].extensions); string path = compilers[i].path; if (path.StartsWith(Program.programDirectory)) { path = path.Substring(Program.programDirectory.Length); } configSource.Configs["Compiler_" + i].Set("Path", path); configSource.Configs["Compiler_" + i].Set("Options", compilers[i].options); } configSource.Save(); } catch { Utils.FatalError("Ошибка при сохранении файла \"" + fileName + "\""); } } /// <summary> /// Returns first compiler from all the list, which can compile specified extension. If no such compiler if found, returns null. /// </summary> /// <param name="extension"></param> /// <returns></returns> public static Compiler GetCompiler(string extension) { extension = extension.TrimStart('.'); return (from Compiler comp in compilers where comp.CanCompile(extension) select comp). DefaultIfEmpty(null).FirstOrDefault(); } } }
f4cbf3c0c0b8a5ba1544918d63796d42b01cdfe0
C#
dsharlet/ComputerAlgebra
/ComputerAlgebra/Transform/LinearTransform.cs
3.234375
3
using System.Collections.Generic; using System.Linq; namespace ComputerAlgebra { /// <summary> /// Base class for a linear transform operation. /// </summary> public abstract class LinearTransform : VisitorTransform { /// <summary> /// Check if x is a constant for this transform. /// </summary> /// <param name="x"></param> /// <returns></returns> protected abstract bool IsConstant(Expression x); // V(x + y) = V(x) + V(y) protected override Expression VisitSum(Sum A) { return Sum.New(A.Terms.Select(i => Visit(i))); } // V(A*x) = A*V(x) protected override Expression VisitProduct(Product M) { IEnumerable<Expression> A = M.Terms.Where(i => IsConstant(i)); if (A.Any()) return Product.New(A.Append(Visit(Product.New(M.Terms.Where(i => !IsConstant(i)))))); return base.VisitProduct(M); } // V((A*x)^n) = A^(1/n)*V(x^n) protected override Expression VisitPower(Power P) { if (!IsConstant(P.Right)) return base.VisitPower(P); Expression L = P.Left.Factor(); IEnumerable<Expression> A = Product.TermsOf(L).Where(i => IsConstant(i)); if (A.Any()) return Product.New(Power.New(Product.New(A), 1 / P.Right), Visit(Product.New(Product.TermsOf(L).Where(i => !IsConstant(i))))); return base.VisitPower(P); } } }
7ab5aab3a6eb52ae429913ed42a1517761ef4b05
C#
jambake/csharp-exercises
/WorkingWithStrings/Program.cs
3.890625
4
using System; using System.Text; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace WorkingWithStrings { public class Program { public static void Main(string[] args) { // string myString = "Escape a \"character\" with a back-slash!"; // string myString = "Add a new line\nwith back-slash 'n'."; // string myString = "Go to your c:\\ drive."; // string myString = @"Go to your c:\ drive."; // @ char allows back-slashes to not escape // string myString = String.Format("{0} = {1}", "First", "Second"); // string myString = string.Format("Dollar Amount: {0:C}", 123.45); // 'C' formats with dollar value // string myString = string.Format("Display Number: {0:N}", 1234567890); // 'N' adds commas to display as written out number // string myString = string.Format("Percentage: {0:P}", .123); // 'P' displays as percentage // string myString = string.Format("Phone: {0:(###) ###-####}", 1234567890); // Shows as phone number // string myString = " I've made a huge mistake. "; // myString = myString.Substring(6, 14); // Starts at 6th position of string. Or add second parameter to only show range of chars // myString = myString.ToUpper(); // Makes all caps // myString = myString.Replace(" ", "--"); // Replaces all spaces with two dashes // myString = myString.Remove(6, 14); // Removes range of chars /* myString = String.Format("Start Length: {0} -- End Length: {1}", myString.Length, myString.Trim().Length); // Trim removes extra spaces before and after string */ /* string myString = ""; for (int i =0; i < 100; 1++) { myString += "--" + i.ToString(); } */ StringBuilder myString = new StringBuilder(); for (int i = 0; i < 100; i++) { myString.Append("--"); myString.Append(i); } Console.WriteLine(myString); Console.ReadLine(); } } }
72bdd5572acd997aabd4bbc7b29b9b46344b54e0
C#
anastasiiazhyla/Gifting
/Gifting.Core/Utils/Extensions/DictionaryExtensions.cs
3.234375
3
using System.Collections.Generic; namespace Gifting.Core.Utils.Extensions { /// <summary> /// Provides extensions for dictionary manipulations /// </summary> public static class DictionaryExtensions { /// <summary> /// Get value of dictonary kay and returns null if value is not found. /// </summary> public static TValue GetValueOrNull<TKey, TValue>(this Dictionary<TKey, TValue> dict, TKey key) where TValue : class { dict.TryGetValue(key, out TValue result); return result; } } }
78c4bae97b34eb2b4c017306e6f424867bc74637
C#
Soinou/Warmer
/Warmer/Localization/FrenchLocale.cs
2.59375
3
using System.Collections.Generic; namespace Warmer.Localization { /// <summary> /// Represents the french locale /// </summary> internal class FrenchLocale : LocaleBase { /// <inheritdoc /> protected override void Load(IDictionary<string, string> strings) { strings["About.Contact"] = "Contact: abricot.soinou@gmail.com"; strings["About.Bugs"] = "Reporter les problèmes sur https://github.com/Soinou/Warmer/issues"; strings["Tray.Show"] = "Afficher"; strings["Tray.Exit"] = "Quitter"; strings["Tray.About"] = "À propos"; strings["Main.On"] = "Activé"; strings["Main.Off"] = "Désactivé"; strings["Main.Temperature"] = "Température ({0}K)"; strings["Main.Interval"] = "Intervalle ({0}ms)"; strings["Main.StateTooltip"] = "Active/Désactive le chauffage de l'écran"; strings["Main.TemperatureTooltip"] = "'Température' de l'écran (Plus bas veut dire plus rouge, plus haut veut dire moins rouge)"; strings["Main.IntervalTooltip"] = "Intervalle entre deux mises à jour du gamma de l'écran (Changez si vous avez des problèmes avec d'autres applications modifiant le gamma de l'écran)"; strings["Restart.Title"] = "Warmer - Info"; strings["Restart.Message"] = "Vous devriez maintenant pouvoir utiliser une température d'écran inférieure à 3300K après avoir redémarré votre ordinateur."; strings["Extend.Message"] = "étendre l'intervalle de température"; } } }
1caeeecf0c94293db9f8ab62bcf41e63512710e1
C#
Arifdamar/BlogProject
/ArifOmer.BlogApp.Business/Concrete/CategoryManager.cs
2.609375
3
using System.Collections.Generic; using System.Threading.Tasks; using ArifOmer.BlogApp.Business.Abstract; using ArifOmer.BlogApp.DataAccess.Abstract; using ArifOmer.BlogApp.DTO.DTOs.CategoryBlogDtos; using ArifOmer.BlogApp.Entities.Concrete; namespace ArifOmer.BlogApp.Business.Concrete { public class CategoryManager : GenericManager<Category>, ICategoryService { private readonly IGenericDal<Category> _genericDal; private readonly ICategoryDal _categoryDal; public CategoryManager(IGenericDal<Category> genericDal, ICategoryDal categoryDal) : base(genericDal) { _genericDal = genericDal; _categoryDal = categoryDal; } public async Task<List<Category>> GetAllSortedByIdAsync() { return await _genericDal.GetAllSortedAsync(I => I.Id); } public async Task<List<CategoryWithBlogsCountDto>> GetAllWithCategoryBlogsAsync() { var categories = await _categoryDal.GetAllWithCategoryBlogsAsync(); var listCategory = new List<CategoryWithBlogsCountDto>(); foreach (var category in categories) { var dto = new CategoryWithBlogsCountDto { CategoryName = category.Name, CategoryId = category.Id, BlogsCount = category.CategoryBlogs.Count }; listCategory.Add(dto); } return listCategory; } } }
71dfe403e8e471cfccbe82a13b10f3e9dd464031
C#
rodolpholl/bakerymanager
/BakeryManager.InfraEstrutura.Helpers/Mvc/UploadControlExtention.cs
2.625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web.Mvc; namespace BakeryManager.InfraEstrutura.Helpers.Mvc { public static class UploadControlExtention { public static MvcHtmlString UploadControl(string Nome, string swfPath, string cancelButtonPath, string[] FileExtentionsAllowed, string UploadActionUrl, string UploadSuccessFunction, string UploadDialogCloseFunction) { return UploadControl(Nome, swfPath, cancelButtonPath, FileExtentionsAllowed, UploadActionUrl, UploadSuccessFunction, UploadDialogCloseFunction, ""); } public static MvcHtmlString UploadControl(string Nome, string swfPath, string cancelButtonPath, string UploadActionUrl, string UploadSuccessFunction) { return UploadControl(Nome, swfPath, cancelButtonPath, null, UploadActionUrl, UploadSuccessFunction, "", ""); } public static MvcHtmlString UploadControl(string Nome, string swfPath, string cancelButtonPath, string[] FileExtentionsAllowed, string UploadActionUrl, string UploadSuccessFunction) { return UploadControl(Nome, swfPath, cancelButtonPath, FileExtentionsAllowed, UploadActionUrl, UploadSuccessFunction,"",""); } public static MvcHtmlString UploadControl(string Nome,string swfPath,string cancelButtonPath, string[] FileExtentionsAllowed, string UploadActionUrl, string UploadSuccessFunction, string UploadDialogCloseFunction, string UploadErrorFunction) { /*<input type="file" name="fileLoad" id="fileLoad" class="form-control" /> <script type=\"text//javascript\"> $(function () { $('#fileLoad').uploadify({ 'swf': \"@Url.Content(\"~//Content//UploadfyContent//uploadify.swf\")\", 'cancelImg': \"@Url.Content(\"~//Content//UploadfyContent//uploadify-cancel.png\")\", 'fileTypeExts' : \"*.xlsx\", 'uploader': \"@Url.Action(\"CarregarArquivo\")\", 'onDialogClose': UploadDialogClose, 'onUploadSuccess': UploadSuccess, 'onUploadError': UploadError }); }); </script>*/ //Validações if (string.IsNullOrWhiteSpace(Nome)) throw new ArgumentNullException("Nome", "O Nome do Controle é obrigatório."); if (string.IsNullOrWhiteSpace(swfPath)) throw new ArgumentNullException("swfPath", "O Caminho do arquivo SWF é obrigatório."); if (string.IsNullOrWhiteSpace(cancelButtonPath)) throw new ArgumentNullException("cancelButtonPath", "O Caminho do ícone para o botão 'Cancelar' é obrigatório."); if (string.IsNullOrWhiteSpace(UploadActionUrl)) throw new ArgumentNullException("UploadActionUrl", "A URL da Action para o upload é obrigatória."); if (string.IsNullOrWhiteSpace(UploadSuccessFunction)) throw new ArgumentNullException("UploadSuccessFunction", "O nome da Função de retorno com sucesso do upload é obrigatória."); StringBuilder sb = new StringBuilder(); sb.Append(string.Format("<input type=\"file\" name=\"{0}\" id=\"{0}\" class=\"form-control\" />",Nome)); sb.Append("<script type=\"text/javascript\">"); sb.Append("$(function () {"); sb.Append("$(\"#"+Nome+"\").uploadify({"); sb.Append(string.Format("'swf': \"{0}\",", swfPath)); sb.Append(string.Format("'cancelImg': \"{0}\",", cancelButtonPath)); if (FileExtentionsAllowed != null) { string fileExt = ""; foreach (var ext in FileExtentionsAllowed) fileExt += string.Concat(ext, ";"); if (fileExt.Length > 0) fileExt = fileExt.Substring(0, fileExt.Length - 1); sb.Append(string.Format("'fileTypeExts' : \"{0}\",", fileExt)); } sb.Append("'successTimeout' : 3600,"); sb.Append("'method' : 'post',"); sb.Append(string.Format("'uploader': \"{0}\",",UploadActionUrl)); sb.Append(string.Format("'onUploadSuccess': {0}", UploadSuccessFunction)); if(!string.IsNullOrWhiteSpace(UploadDialogCloseFunction)) sb.Append(string.Format(",'onDialogClose': {0}", UploadDialogCloseFunction)); if (!string.IsNullOrWhiteSpace(UploadErrorFunction)) sb.Append(string.Format(",'onUploadError': {0}", UploadErrorFunction)); sb.Append("}); }); </script>"); return new MvcHtmlString(sb.ToString()); } } }
1223a8eb544a4e1c93fff0cd666ac037c930ec93
C#
Fraektsvin/Group6System
/Database/DatabaseTier/Repository/CustomerRepository.cs
3.015625
3
using System; using System.Collections.Generic; using System.Threading.Tasks; using DatabaseTier.Models; using DatabaseTier.Persistence; using Microsoft.EntityFrameworkCore; namespace DatabaseTier.Repository { public class CustomerRepository:IRepository<Customer> { private readonly CloudContext _context; public CustomerRepository() { _context = new CloudContext(); } public async Task<IList<Customer>> GetAllAsync() { return await _context.CustomersTable.ToListAsync(); } public async Task<Customer> AddAsync(Customer customer) { try { var newAddedCustomer = await _context.CustomersTable.AddAsync(customer); await _context.SaveChangesAsync(); return newAddedCustomer.Entity; } catch (AggregateException e) { Console.WriteLine(e.StackTrace); throw; } } public async Task RemoveAsync(int cprnumber) { Customer customerToRemove = await _context.CustomersTable.FirstOrDefaultAsync(c => c.CprNumber == cprnumber); if (customerToRemove != null) { _context.CustomersTable.Remove(customerToRemove); await _context.SaveChangesAsync(); } } public async Task<Customer> UpdateAsync(Customer customer) { try { Customer customerToUpdate = await _context.CustomersTable.FirstAsync(c=> c.CprNumber == customer.CprNumber); _context.Update(customerToUpdate); await _context.SaveChangesAsync(); return customerToUpdate; } catch (Exception e) { Console.WriteLine(e.StackTrace); throw new Exception($"User not found!"); } } public Task<Customer> GetAsync(Customer entity) { throw new NotImplementedException(); } } }
71dcc13e9b061458a0f4fcbfc78846cc47d1f952
C#
metrogo10/Final-Project-Oop
/FinalProject/FinalProject/Engines/RandomGenerator.cs
2.828125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FinalProject.Engines { public static class RandomGenerator { public static Character GenerateCharacter(Character template) { Character returnValue; List<Attribute> attributes = new List<Attribute>(); foreach(KeyValuePair<string, Attribute> atbPair in template.Attributes) { } throw new NotImplementedException(); } } }
20cd3208582da031697036354f1b1455b05af5f9
C#
Iamsdl/Kepler-Tasks
/20Ex/ex14.cs
3.390625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _20Ex { public static class ex14 { public class Customer { public Customer(string name) { Name = name; } public string Name { get; } public List<Order> Orders { get; } = new List<Order>(); public void addOrder(Order x) { if ((x != null) && (x.OrderDate < DateTime.Now)) //&&!string.IsNullOrEmpty(x.orderNumber) { Orders.Remove(Orders.FirstOrDefault(c => c.OrderNumber == x.OrderNumber)); Orders.Add(x); } } public List<string> history { get { List<string> temp = new List<string>(); temp = Orders.Select(c => (c.OrderNumber + c.OrderDate.ToString())).ToList(); return temp; } } } public class Order { public Order(string orderNumber, DateTime date) { OrderNumber = orderNumber; OrderDate = date; } public string OrderNumber { get; } public DateTime OrderDate { get; set; } = new DateTime(); } public static string exer14() { Customer gigel = new Customer("gigel"); Order ord = new Order("asdf", DateTime.Now); gigel.addOrder(null); gigel.addOrder(new Order("asdf", DateTime.Now)); Console.WriteLine(string.Join("\n",gigel.history)); return ""; } } }
55a5011ee13a2dac9ba6c0946856f5d0b9caa7b7
C#
colhountech/SoftwareArchitect.AspNet5
/Demos/02-AspNet5WebApi/After/src/HelloWebApi/GreetingsRepository.cs
3.078125
3
using System.Collections.Generic; using System.Threading.Tasks; namespace HelloWebApi { public class GreetingsRepository : IGreetingsRepository { private readonly List<string> _greetings = new List<string> { "Hello", "Howdy", "Aloha", "Yo", "Ciao" }; public async Task<string> GetGreetingAsync(int id) { return await Task.FromResult(_greetings[id - 1]); } } }
a861a9c5079b183697eded9e46776ea246afd415
C#
nrkn/NrknLib
/Console/Demos/ConsoleDemo/Program.cs
2.84375
3
using System; using System.Globalization; using NrknLib.ConsoleView; using NrknLib.ConsoleView.Demo; using NrknLib.Geometry; using NrknLib.Geometry.Extensions; namespace ConsoleDemo { class Program { static void Main( string[] args ) { var console = new SystemConsoleView(); //.NET Console.MoveBufferArea is too slow for the buffering to be useful. //it's actually faster to just update the whole screen var demo = new ConsoleViewDemo( console ) {UseBuffer = false}; var command = String.Empty; do { demo.Tick( command ); command = Console.ReadKey().Key.ToCommand(); } while( command != ConsoleKey.Escape.ToCommand() ); Console.ForegroundColor = ConsoleColor.Gray; Console.BackgroundColor = ConsoleColor.Black; Console.Clear(); Console.WriteLine( demo.Log ); /* var point = new Point( -120, 50 ); var rotated = point.Rotate( 45 ); Console.WriteLine( rotated.X + ", " + rotated.Y ); */ Console.ReadKey(); } } public static class Extensions { public static string ToCommand( this ConsoleKey info ) { return ( (int) info ).ToString( CultureInfo.InvariantCulture ); } } }
a3eaa5d59f0d3928e099fcf08505732fefb0e394
C#
Sitecore-Hackathon/2019-Team-Mapleton-Hill
/src/Project/Common/code/Providers/BulkMediaProvider.cs
2.53125
3
using Common.Web.Factories; using Common.Web.Models; using System.Collections.Generic; namespace Common.Web.Providers { public class BulkMediaProvider : IBulkMediaProvider { /// <summary> /// Get List of Image items to be saved in the Media Library /// </summary> /// <param name="sourceList"></param> /// <returns></returns> public List<IMedia> GetMediaList(List<ICsvMedia> sourceList) { List<IMedia> result = new List<IMedia>(); foreach (var sourceItem in sourceList) { IMedia item = MediaFactory.Build(sourceItem.FileLocation, sourceItem.FileName, sourceItem.ItemName); result.Add(item); } return result; } } }
1ca3c8c15ec956292aba50221f9cab422a8b0176
C#
khawaja-0304/ASSESSS2
/Controllers/firstController.cs
2.546875
3
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using ASSESSS2.Models; using Microsoft.AspNetCore.Mvc; namespace ASSESSS2.Controllers { public class firstController : Controller { private RMSContext R = null; public firstController(RMSContext _RM) { R = _RM; } public IActionResult Index() { return View(); } [HttpGet] public IActionResult AddNewAirline() { return View(); } [HttpPost] public IActionResult AddNewAirline(Airline A) { try { R.Airline.AddAsync(A); R.SaveChangesAsync(); ViewBag.Message = A.Name + " airline saved Succeesfully"; ViewBag.MessageType = "s"; } catch (Exception) { ViewBag.Message = "unable to save the Airline"; ViewBag.MessageType = "e"; } return View(); } public IActionResult AllAirlines() { return View(R.Airline.ToList()); } } }
e953d2a0dd6d8bda70e136ec5424cda3ef73d1ec
C#
TecnologiasIntech/DrCash_WPF
/DoctorCashWpf/DoctorCashWpf/Views/Authentication.xaml.cs
2.65625
3
using System; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media; //using System.Web.Script.Serialization; using System.IO; namespace DoctorCashWpf.Views { /// <summary> /// Interaction logic for Authentication.xaml /// </summary> /// class Person { public string name { get; set; } public int age { get; set; } public override string ToString() { return "Nombre: " + name + "\nEdad: " + age; } } public partial class Authentication : UserControl { public Authentication() { InitializeComponent(); // generar(); } private userService user = new userService(); private BrushConverter brushConverter = new BrushConverter(); private logService serviceslog = new logService(); private dateService date = new dateService(); private void authentification() { var userData = user.authentication(txtbox_username.Text, txtbox_password.Password.ToString()); if (userData != null) { labelError.Content = String.Empty; setLog(userData); userInformation.user = userData; closeDialog(); } else { labelError.Content = " Verify Data"+"\n"+ "Username or Password is Incorrect"; } } private void verifyFields() { if (txtbox_username.Text == String.Empty) { txtbox_username.Focus(); showErrorAndFocusField(txtbox_username); } else if (txtbox_password.Password.ToString() == "") { txtbox_password.Focus(); showErrorAndFocusField(txtbox_password); } else { authentification(); } } private void showErrorAndFocusField(TextBox txtBox) { txtBox.Foreground = (Brush)brushConverter.ConvertFrom("#e74c3c"); labelError.Content = "Complete the fields marked"; } private void showErrorAndFocusField(PasswordBox txtBox) { txtBox.Foreground = (Brush)brushConverter.ConvertFrom("#e74c3c"); labelError.Content = "Complete the fields marked"; } private void closeDialog() { MaterialDesignThemes.Wpf.DialogHost.CloseDialogCommand.Execute(null, null); } private void setLog(user userData) { var items = new log(); items.log_Username = txtbox_username.Text; items.log_DateTime = date.getCurrentDate(); items.log_Actions = "Login of: " + userData.usr_FirstName + " " + userData.usr_LastName + ", Level of user: " + userData.usr_SecurityLevel; serviceslog.CreateLog(items); } private void Button_Click(object sender, RoutedEventArgs e) { verifyFields(); } private void authentification_KeyUp(object sender, KeyEventArgs e) { labelError.Content = String.Empty; if (e.Key == Key.Enter) { verifyFields(); } } private void Button_Click_1(object sender, RoutedEventArgs e) { App.Current.Shutdown(); } //private void generar() //{ // JavaScriptSerializer ser = new JavaScriptSerializer(); // string outputJSON = File.ReadAllText("MiPrimerJSON.json"); // Person p1 = ser.Deserialize<Person>(outputJSON); // Console.WriteLine(p1.age.ToString()); // Console.ReadLine(); //} } }
4266704b83ae0ce0219e91a66c6a0095b74cba69
C#
Plamen-Angelov/OOP
/Exam/CarRacing/Repositories/Models/RacerRepository.cs
2.671875
3
using CarRacing.Models.Racers.Contracts; using CarRacing.Repositories.Contracts; using CarRacing.Utilities.Messages; using System; using System.Collections.Generic; using System.Linq; namespace CarRacing.Repositories.Models { public class RacerRepository : IRepository<IRacer> { private List<IRacer> racers; public IReadOnlyCollection<IRacer> Models { get; private set; } public RacerRepository() { racers = new List<IRacer>(); Models = new List<IRacer>(); } public void Add(IRacer model) { if (model == null) { throw new ArgumentException(ExceptionMessages.InvalidAddRacerRepository); } racers.Add(model); Models = racers as IReadOnlyList<IRacer>; } public IRacer FindBy(string property) { return racers.FirstOrDefault(r => r.Username == property); } public bool Remove(IRacer model) { bool isRemoved = racers.Remove(model); Models = racers as IReadOnlyList<IRacer>; if (isRemoved) { return true; } else { return false; } } } }
f5d53a79a5d406167534b0a130d87ed9f1079caf
C#
JeffHolla/Epam_External2021
/Task 3/Task_3_3/Task_3_3_1_SuperArray/Program.cs
3.125
3
using System; using System.Text; using System.Threading.Tasks; /* Задание * Расширьте массивы чисел методом, производящим действия с каждым конкретным элементом. * Действие должно передаваться в метод с помощью делегата. * * Кроме указанного функционала выше, добавьте методы расширения для поиска: * - суммы всех элементов; * - среднего значения в массиве; * - самого часто повторяемого элемента; * На данном этапе LINQ использовать разрешается. * * Консольный интерфейс-демонстрация для данного задания не обязателен, но постарайтесь * сделать интерфейсы ваших сущностей максимально понятными и готовыми к тестам. */ namespace Task_3_3_1_SuperArray { class Program { static void Main(string[] args) { LetsSee lets = new LetsSee(); lets.StartShow(); Console.ReadKey(); } } }
631709ff0e6ab10eb5402a71eab378306714cdc1
C#
ClintSu/DesignPattern
/DesignPattern.Weather.ObserverPattern/Program.cs
2.890625
3
using DesignPattern.Weather.ObserverPattern.DisplayElements; using System; namespace DesignPattern.Weather.ObserverPattern { internal class Program { private static void Main(string[] args) { WeatherData weatherData = new WeatherData(); //建立WeatherData对象 CurrentConditionsDisplay currentDisplay = new CurrentConditionsDisplay(weatherData); //建立订阅者 StatisticsDisplay statisticsDisplay = new StatisticsDisplay(weatherData); //建立订阅者 weatherData.SetMeasurements(80, 65, 30.4f); //模拟天气变化 weatherData.SetMeasurements(82, 75, 29.2f); weatherData.SetMeasurements(90, 80, 29.2f); Console.ReadLine(); } } }
98941cd8d0a0d20c479994b9c333630ef2f17efd
C#
shendongnian/download4
/code4/689485-16571134-40679947-4.cs
3.078125
3
//Create the connection using(SqlDbConnection connection = new SqlDbConnection("your_connection_string")) { //Create the Command using(SqlDbCommand command = new SqlDbCommand(query)) { //Set up the properties of the command and the parameters command.CommandType = CommandType.Text; command.Connection = connection; command.Parameters.AddWithValue("@read", Read); command.Parameters.AddWithValue("@ertnumber", rtNumber); command.Parameters.AddWithValue("@date", DateStamp); //Have to open the connection before we do anything with it connection.Open(); //Execute the command. As we don't need any results back we use ExecuteNonQuery command.ExecuteNonQuery(); } }//At this point, connection will be closed and disposed - you've cleaned up
6bfe47f13593abd17faf1bf477daccdc4c466a6a
C#
MiroslavKisov/Software-University
/CSharp Fundamentals/CSharp OOP Basics/DefiningClassesExercise/OpinionPoll/StartUp.cs
3.5
4
using System; public class StartUp { public static void Main() { Family family = new Family(); int N = int.Parse(Console.ReadLine()); for (int i = 0; i < N; i++) { string command = Console.ReadLine(); var commandArgs = command .Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries); Person person = new Person(commandArgs[0], int.Parse(commandArgs[1])); family.AddMember(person); } var prsn = family.GetOldestThan30(); foreach (var p in prsn) { Console.WriteLine($"{p.Name} - {p.Age}"); } } }
a5e79b3b9f2b98072c41e21d3d41e36d6726974f
C#
sufzoli/suf-electronics-motor-driver
/SW/Serial Logger/MotorCalibrationLogger/Program.cs
2.875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using System.IO.Ports; using MotorCalibrationLogger.Properties; namespace MotorCalibrationLogger { class Program { static void Main(string[] args) { string buff = null; Settings settings = new Settings(); StreamWriter calibrationfile = new StreamWriter(settings.LogFile); int i,j; SerialPort com = new SerialPort( settings.COM_Port, settings.COM_Baud, ToParity(settings.COM_Parity), settings.COM_Bits, ToStopBits(settings.COM_StopBits)); com.Open(); i = 0; j = 0; while (buff != ".") { i++; buff = com.ReadLine(); if (buff != null) { if(settings.Console) { Console.WriteLine(buff); } calibrationfile.WriteLine(buff); } if(i>1000) { calibrationfile.Flush(); i = 0; } if (settings.MaxSamples != 0) { if(settings.MaxSamples < j) { break; } j++; } } calibrationfile.Flush(); calibrationfile.Close(); } static Parity ToParity(string parityStr) { Parity retvalue; switch(parityStr.ToLower()) { case "n": retvalue = Parity.None; break; default: retvalue = Parity.None; break; } return retvalue; } static StopBits ToStopBits(string stopbitStr) { StopBits retvalue; switch(stopbitStr.Trim()) { case "0": retvalue = StopBits.None; break; case "1": retvalue = StopBits.One; break; case "1.5": retvalue = StopBits.OnePointFive; break; case "1,5": retvalue = StopBits.OnePointFive; break; case "2": retvalue = StopBits.Two; break; default: retvalue = StopBits.None; break; } return retvalue; } } }
2d148bfc72bc64f9156bd66f44127067bfd6b53e
C#
VictorT22844/DorsetOOP
/DorsetOOP/Views/Administrator/Teachers/AddTeacherView.xaml.cs
2.640625
3
using DorsetOOP.Models; using DorsetOOP.Models.Users; using DorsetOOP.ViewModels; using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace DorsetOOP { /// <summary> /// Interaction logic for AddTeacherView.xaml /// </summary> public partial class AddTeacherView : Window, INotifyPropertyChanged { #region View Model public event PropertyChangedEventHandler PropertyChanged; private Teacher _teacherToAdd = new Teacher(); public Teacher TeacherToAdd { get { return _teacherToAdd; } set { _teacherToAdd = value; PropertyChanged(this, new PropertyChangedEventArgs("TeacherToAdd")); } } private Address _addressToAdd = new Address(); public Address AddressToAdd { get { return _addressToAdd; } set { _addressToAdd = value; PropertyChanged(this, new PropertyChangedEventArgs("AddressToAdd")); } } #endregion public AddTeacherView() { InitializeComponent(); } private void cancelButton_Click(object sender, RoutedEventArgs e) { this.Close(); } private void addButton_Click(object sender, RoutedEventArgs e) { if (VirtualCollegeContext.CreateTeacher(TeacherToAdd, AddressToAdd)) { MessageBox.Show("Teacher created!", "Success", MessageBoxButton.OK, MessageBoxImage.Information); this.Close(); } else MessageBox.Show("Couldn't create user", "Error", MessageBoxButton.OK, MessageBoxImage.Error); } } }
7d26551076644a85e6ccea335e18ae2a8a18172d
C#
Luarkenbb/SDP2019
/SDP2019/SDP2019/Dialog/ReportChart.cs
2.59375
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 SDP2019.Dialog { public partial class ReportChart : Form { LinkedList<string> spareIDs; Boolean isShowPrevious; Boolean isQtyOrSales; DateTime date; DataTable valueCurr; DataTable valuePrevious; DBConnection conn; public ReportChart() { InitializeComponent(); } public ReportChart(LinkedList<string> spareIDs, Boolean isShowPrevious, Boolean isQtyOrSales, DateTime date) { InitializeComponent(); this.spareIDs = spareIDs; this.isShowPrevious = isShowPrevious; this.isQtyOrSales = isQtyOrSales; this.date = date; } private void ReportChart_Load(object sender, EventArgs e) { conn = new DBConnection(); /*var original = chart1.Series.Add("Original"); var modified = chart1.Series.Add("Modified"); chart1.Series["Original"].IsValueShownAsLabel = true; chart1.ChartAreas[0].AxisY.MajorGrid.Enabled = false; chart1.ChartAreas[0].AxisY.MinorGrid.Enabled = false; chart1.ChartAreas[0].AxisX.MajorGrid.Enabled = false; chart1.ChartAreas[0].AxisX.MinorGrid.Enabled = false; original.Points.AddXY("CPU", 7.6); modified.Points.AddXY("CPU", 1.6); */ conn.OpenConnection(); valueCurr = conn.ExecuteSelectQuery(getSQL(date)); if (isShowPrevious) { valuePrevious = conn.ExecuteSelectQuery(getSQL(new DateTime(date.Year, date.Month, 1).AddMonths(-1))); } conn.CloseConnection(); printCharts(); } private void printCharts() { string currMonth = date.ToString("MMMM"); string previousMonth = new DateTime(date.Year, date.Month, 1).AddMonths(-1).ToString("MMMM"); if (isShowPrevious) { printChart(previousMonth, valuePrevious); } printChart(currMonth, valueCurr); } private void printChart(string colName,DataTable dt) { var currBar = chart1.Series.Add(colName); chart1.Series[colName].IsValueShownAsLabel = true; chart1.ChartAreas[0].AxisY.MajorGrid.Enabled = false; chart1.ChartAreas[0].AxisY.MinorGrid.Enabled = false; chart1.ChartAreas[0].AxisX.MajorGrid.Enabled = false; chart1.ChartAreas[0].AxisX.MinorGrid.Enabled = false; DataRow currRow; foreach (string spareID in spareIDs) { currRow = isExistInDataTable(spareID, dt); if (currRow != null) { int qty = Convert.ToInt32(currRow[1].ToString()); int value = Convert.ToInt32(currRow[2].ToString()); if (isQtyOrSales) { currBar.Points.AddXY(spareID, qty); } else { currBar.Points.AddXY(spareID, value); } } } } private DataRow isExistInDataTable(string spareID, DataTable dt) { DataRow row; for (int i = 0; i < dt.Rows.Count; i++) { row = dt.Rows[i]; if (row[0].ToString().Equals(spareID)) { return row; } } return null; } private string getSQL(DateTime date) { DateTime firstDay = new DateTime(date.Year,date.Month,1); DateTime lastDate = new DateTime(date.Year,date.Month,1).AddMonths(1).AddDays(-1); string format = "yyyy-MM-dd HH:mm:ss"; string strFirstDay = "'" + firstDay.ToString(format) + "'"; string strlastDate = "'" + lastDate.ToString(format) + "'"; string sqlSpares = ""; foreach (string spareID in spareIDs) { sqlSpares += "'" + spareID + "',"; } sqlSpares = sqlSpares.Remove(sqlSpares.Length - 1, 1); string sql = ""; sql += "SELECT spareID, SUM(orderspare.toDeliverQuantity), SUM(toDeliverQuantity * pricePerItem), MONTH(orderlist.createDateTime) "; sql += "FROM orderspare, orderlist "; sql += "WHERE orderlist.createDateTime BETWEEN "+ strFirstDay + " AND "+ strlastDate + " "; sql += "AND orderspare.status = 'packaged' "; sql += "AND orderlist.orderSerial = orderspare.orderSerial "; sql += "AND orderspare.spareID in (" + sqlSpares +") "; sql += "GROUP BY orderspare.spareID,MONTH(orderlist.createDateTime) "; return sql; } } }
9f324e41f1594238d110fad7be7641f6b30bb729
C#
N-ickJones/Archive
/Sql/DatabasePopulation/SQLInterface.cs
3.5
4
using System; using System.Collections.Generic; using MySql.Data.MySqlClient; using System.Linq; using System.Data; namespace DatabasePopulation { public class SQLInterface { // You may need to change "port" in the string below to reflect the port you used in the initial setup. string connStr = "server=shsuse.mysql.database.azure.com;user=cashewclub@shsuse;database=shsuse;port=3306;password=D1ipDan*gDelux5e"; MySqlConnection conn; WordListManager words; public SQLInterface() { //Establish connection path to the database. conn = new MySqlConnection(connStr); this.words = new WordListManager(); } //Send a query wholesale to the server, and get back the raw data from its use. private List<List<string>> query(string q) { //Create storage container for query result: List<List<string>> result = new List<List<string>>(); //Create storage container for each row of the query: List<string> row = new List<string>(); //The connection attempt could fail, so try catch is used. try { //Attempt to connect to the database. //Console.WriteLine("Connecting to MySQL..."); conn.Open(); //Once connected, package and send the query to the database. MySqlCommand cmd = new MySqlCommand(q, conn); //Unpack the result from the database. MySqlDataReader rdr = cmd.ExecuteReader(); //For each row in the unpacked result, do the following: while (rdr.Read()) { //Create a new row to be added to the result list. row = new List<string>(); // for each element in the row of the result: for (int i = 0; i < rdr.FieldCount; i++) { // Add it to the row as a string. row.Add(rdr[i].ToString()); } //Add each complete row to the overall container. result.Add(row); } //IMPORTANT: Close the resulting temporary output from the database. rdr.Close(); } //If for some reason the connection failed, display the exception in the console and continue the program. catch (Exception ex) { Console.WriteLine(ex.ToString()); } //IMPORTANT: Close the connection to the server! If we failed to connect, it // will do nothing. If we connected, we must close the connection. We're done for now. conn.Close(); //Give the result to whatevr requested it. return result; } //Print a query directly to console. private void print_query(string s) { //Submit the query to the server. List<List<string>> result = query(s); //Console.WriteLine(s); //Break the query into columns and rows for output, and output on the fly. for (int i = 0; i < result.Count; i++) { for (int j = 0; j < result.ElementAt(i).Count; j++) { Console.Write(result.ElementAt(i).ElementAt(j) + "\t, "); } //Console.WriteLine(); } } //This generates a string identical to that which would be produced in the console by print_query. private string query_to_string(string s) { string output = ""; //Submit the query to the server. List<List<string>> result = query(s); //Generate a string in the same manner as would be used for printing the query results to the console. for (int i = 0; i < result.Count; i++) { for (int j = 0; j < result.ElementAt(i).Count; j++) { output += result.ElementAt(i).ElementAt(j) + "\t, "; } output += "\n"; } //Give the string to whatever asked for it. return output; } public List<Account> generateAccounts(int number) { //Console.WriteLine("Generating Accounts..."); //Create an account generator AccountGenerator ag = new AccountGenerator(this.words); //generate as many accounts as possible List<Account> accounts = ag.generateAccounts(number); //Begin query string generation string queryString = "insert into account(Username, Email, FirstName, LastName, Password, Skills, Theme, PicturePath) values "; //populate the values of the querystring foreach (Account account in accounts){ queryString += account.getAddTupleQuerryString() + ","; } //replace the last comma with a semi colon. queryString = queryString.Substring(0,queryString.Length-1)+";"; //Console.WriteLine("Submitting Accounts..."); //submit the query. query(queryString); //Console.WriteLine("Done."); return accounts; } public List<Organization> generateOrganizations(int number) { //Console.WriteLine("Generating Organizations..."); //Create an organization generator OrganizationGenerator org = new OrganizationGenerator(this.words); //generate as many organizations as possible List<Organization> organizations = org.generateOrganizations(number); //Begin query string generation string queryString = "insert into organization(Name, License, Activation, Expiration) values "; //populate the values of the querystring foreach (Organization organization in organizations) { queryString += organization.getAddTupleQuerryString() + ","; } //replace the last comma with a semi colon. queryString = queryString.Substring(0, queryString.Length - 1) + ";"; //submit the query. //Console.WriteLine("Submitting Organizations..."); query(queryString); //Console.WriteLine("Done."); return organizations; } //Generate a list of projects and add them to the database. public List<Project> generateProjects(int number) { //Console.WriteLine("Generating Projects"); //To do this, we'll need a Project Generator. ProjectGenerator proj = new ProjectGenerator(this.words); //We'll also create a list to store the projects. List<Project> projects = proj.generateProjects(number); //Prepare an insert query string. string queryString = "insert into project(projectid, projectdeadline, projectdescription) values "; //Populate the query string with the value tuples associated with the projects previously generated. foreach(Project project in projects) { queryString += project.getAddTupleQuerryString() + ","; } //Change the last character from a comma to a semicolon. queryString = queryString.Substring(0, queryString.Length - 1) + ";"; //submit the query. //Console.WriteLine("Submitting Projects..."); query(queryString); //Console.WriteLine("Done."); //return the project list to the caller if it's needed. return projects; } //This function is responsible for generating a certain number of project creation record batches. //In the process, it takes the active instance of SQLInterface and passes it through to //CreaetesGenerator for the purpose of generating and populating the database with the relevant //projects, organizations, and accounts required to validly construct a create record. public List<Create> generateCreateSets(int number) { //Console.WriteLine("Generating Create Sets..."); //Make a CreatesGenerator. CreatesGenerator c = new CreatesGenerator(this.words); //Prepare a new list for the create records. List<Create> createSet = new List<Create>(); List<Create> creates = new List<Create>(); //prime the query string for insertion. string queryString = "insert into creates(username, email, name, projectid) values "; //Generate the number of batches of create records requested by the user. for(int i = 0; i < number; i++) { Console.WriteLine("Beginning batch " + (i + 1) + ".\n"); //Console.WriteLine("Generating batch " + (i+1) + " of creates..."); //Pass the SQLInterface to the CreatesGenerator so that it can make the projects, accounts, and organizations //required to populate a create record. creates = c.generateCreateSet(this); //For every create record, store it in the list for output, and add the //value tuple to the query string. //Console.WriteLine("Beginning batch " + (i + 1) + ".\n"); foreach (Create create in creates) { createSet.Add(create); queryString += create.getAddTupleQuerryString() + ","; } Console.WriteLine("Finished batch " + (i+1) + ".\n"); } //Convert the last symbol from a comma to a semicolon. queryString = queryString.Substring(0, queryString.Length - 1) + ";"; //Console.WriteLine("Submitting Creates...."); //Submit the query. //submitProjectAssignmentSets(createSet); query(queryString); //Console.WriteLine("Done."); //Give the create record set back to the caller. return createSet; } //This function is responsible for generating a certain number of project creation record batches. //In the process, it takes the active instance of SQLInterface and passes it through to //CreaetesGenerator for the purpose of generating and populating the database with the relevant //projects, organizations, and accounts required to validly construct a create record. //public void submitProjectAssignmentSets(List<Create> creates) //{ // //Console.WriteLine("Generating Project Assignments Sets..."); // //Make a CreatesGenerator. // CreatesGenerator c = new CreatesGenerator(this.words); // //prime the query string for insertion. // string queryString = "insert into ProjectAssigned(username, email, name, projectid) values "; // //Generate the number of batches of create records requested by the user. // foreach (Create create in creates) // { // queryString += create.getAddTupleQuerryString() + ","; // } // //Convert the last symbol from a comma to a semicolon. // queryString = queryString.Substring(0, queryString.Length - 1) + ";"; // //Console.WriteLine("Submitting project assignments...."); // //Submit the query. // query(queryString); // //Console.WriteLine("Done."); //} //This function registers tasks to the projects under which they were created. public void addBuiltOnTuples(string builtOnValues) { //Console.WriteLine("Registering Tasks to project..."); string s = "insert into builton(projectId, taskId) values " + builtOnValues + ";"; query(s); //Console.WriteLine("Done."); } //This funtion ensures that the tasks are added to the task table. public void addTasks(List<Task> tasks) { //Console.WriteLine("Registering Tasks to Database..."); string s = "insert into task(TaskId, TaskDeadline, TaskCompleted, TaskDescription) values "; foreach(Task task in tasks) { s += task.getAddTupleQuerryString() + ","; } s = s.Substring(0, s.Length - 1) + ";"; query(s); //Console.WriteLine("Done."); } //Constructing the Task Hierarchy will register the tasks and assign them to the appropriate project. public void addTaskHierarchyTuples(List<TaskTree> taskTrees) { //Console.WriteLine("Registering task hierarchy..."); string s = "insert into parent(parentTaskId, childTaskId) values "; string tuples = ""; foreach (TaskTree taskTree in taskTrees) { addTasks(taskTree.getTaskList()); tuples += taskTree.getParentAddTupleString(); addBuiltOnTuples(taskTree.getBuiltOnTupleString()); } if (tuples.Length > 0) s += tuples.Substring(0, tuples.Length - 1) + ";"; else s += tuples + ";"; query(s); //Console.WriteLine("Done."); } //This will handle both project and task assignment registration to avoid redundancy. public void registerAssignments(List<Account> accounts, Project project, Account creator) { //Exctract the tasks from the project. List<TaskTree> taskTrees = project.getTaskTrees(); List<Task> tasks = new List<Task>(); foreach (TaskTree taskTree in taskTrees) tasks.AddRange(taskTree.getTaskList()); //Prepare the insertion strings. string taskString = "insert into TaskAssigned(username, email, taskid) values "; string projectString = "insert into ProjectAssigned(username, email, projectid) values "; //Prepare duplicate account registration prevention for project assignment. HashSet<Account> projectAssignments = new HashSet<Account>(); //Ensure that the creator is always considered registered, even if he doesn't get assigned a task. projectAssignments.Add(creator); //Prime the random number. Random rand = new Random(); int choice = rand.Next(0, accounts.Count()); //Console.WriteLine("Registering Tasks to Accounts..."); //For each task, choose a random account to register it to, and add the account to the HashSet. foreach(Task task in tasks) { choice = rand.Next(0, accounts.Count()); taskString += task.getTaskAssignedAddString(accounts[choice]) + ","; projectAssignments.Add(accounts[choice]); } //Replace the last comma with a semicolon. taskString = taskString.Substring(0, taskString.Length - 1) + ";"; //Console.WriteLine("Registering Accounts to Projects..."); //For each account in the HashSet (which removed duplicate entries), register the project assignment. foreach(Account account in projectAssignments) { projectString += project.getProjectAssignedAddString(account) + ","; } //Replace the last comma with a semicolon. projectString = projectString.Substring(0, projectString.Length - 1) + ";"; query(taskString + projectString); //Console.WriteLine("Done."); } //Completely clear generated data, and repopulate the database with the constants. public void reset() { //Console.WriteLine("Erradicating Database Contents..."); string resetString = ""; resetString += "SET SQL_SAFE_UPDATES = 0;"; resetString += "delete from organization where name != '';"; resetString += "delete from account where username != '';"; resetString += "delete from project where projectid != -1;"; resetString += "delete from task where taskid != -1;"; resetString += "delete from builton where taskid != '-1';"; resetString += "delete from creates where email != ''; "; resetString += "delete from projectAssigned where email != '';"; resetString += "delete from taskAssigned where email != '';" ; resetString += "delete from parent where parentTaskId != '';"; resetString += "SET SQL_SAFE_UPDATES = 1;"; resetString += "insert into account(Username, Email, FirstName, LastName, Password, Skills, Theme, PicturePath) values('un', 'someEmail@bullshit.com', 'Travis', 'Idlay', 'nope', '', '', ''),('georgey','mbmnbm@bnmn.com','fn1234','ln1234','password', '', '', ''),('TestUser12345','armyjonesn@gmail.com','Nicholas','Jones','password', '', '', ''),('TestUser321','armyjonesn@gmail.com','Nicholas','Jones','password', '', '', ''); "; query(resetString); //Console.WriteLine("Done."); } } }
c589d36cf06d0b6525bb1d6cebd12055afc2d25a
C#
nsmotritski/AutomationTraining
/AutomationTraining/AutomationTraining/TutByLoginTest.cs
2.84375
3
using NUnit.Framework; using OpenQA.Selenium; using System; using System.Threading; namespace AutomationTraining { /* * From Task 20: * Complete 2 task: * 1. Create test 1, which goes to https://www.tut.by/, * login with correct credentials (Username – seleniumtests@tut.by, * Password – 123456789zxcvbn; create new project for that in Visual Studio; * choose testing framework NUnit3*). Do not forget to add assertion in your test. * 2. Create By variables, which over all possible types of location in Selenium WebDriver (in separate class). * From Task 50: * Complete tasks: * 1. Add implicit waiter for WebDriver. * 2. Add Thread.sleep for login test, which was created on previous training. What type of waiter is it (add your answer as comment near sleep)? * 3. Add explicit waiter* for login test, which will wait until name appears (after login). Add polling frequency, which is differ from default value * 4. Create DDT test, which will login with different credentials */ public class Task20 { private IWebDriver _driver; [SetUp] public void StartBrowser() { _driver = WebDriverHelper.WebDriverHelper.DeployWebDriver(); _driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10); } [TestCase("seleniumtests@tut.by", "123456789zxcvbn", "Selenium Test")] [TestCase("seleniumtests2@tut.by", "123456789zxcvbn", "Selenium Test")] public void TutByLoginTest(string username, string password, string expectedUser) { //Open tut.by hompage _driver.Url = "https://tut.by"; _driver.Manage().Window.Maximize(); //wait for EnterButton displayed and open login popup _driver.WaitForElement(By.CssSelector(TutBySelectors.EnterButtonSelector)); var enterButton = _driver.FindElement(By.CssSelector(TutBySelectors.EnterButtonSelector)); enterButton.Click(); Thread.Sleep(1000); //Thread.Sleep() is a waiter without a condition to wait for. Bad example of waiter. //provide credentials and login _driver.WaitForElement(By.CssSelector(TutBySelectors.UsernameInputSelector)); var usernameInput = _driver.FindElement(By.CssSelector(TutBySelectors.UsernameInputSelector)); var passwordInput = _driver.FindElement(By.CssSelector(TutBySelectors.PasswordInputSelector)); _driver.TypeTextToElement(usernameInput, username); _driver.TypeTextToElement(passwordInput, password); var loginButton = _driver.FindElement(By.CssSelector(TutBySelectors.LoginButton)); loginButton.Click(); //validate that test user is logged in _driver.WaitForElement(By.CssSelector(TutBySelectors.UsernameSpanSelector)); var usernameSpan = _driver.FindElement(By.CssSelector(TutBySelectors.UsernameSpanSelector)); Assert.AreEqual(expectedUser, usernameSpan.Text, "User 'Selenium Test' is not logged in!"); } [TearDown] public void CloseBrowser() { _driver.Close(); } } }
029f0b2bdff5a15aecff7bc0eece15dc6bc8f7a7
C#
mtszpater/Authentication
/WWW/WWW/WWW/Models/Perm.cs
2.71875
3
using System; namespace Registering { public class Perm { static class Perms { public const int Admin = 1; public const int User = 0; } public User ReturnObjectWithPerm(User user){ if (user.returnUserPermId() == Perms.User) { return user; } User user_temp = null; if (user.returnUserPermId() == Perms.Admin) { user_temp = new Admin (user); } return user_temp; } } }
a83093a3a50b3028714a4f26304c016bf1de4428
C#
nholopoff/Ten-Day-Report-Automation
/source/repos/CapstoneProject/CapstoneProject/Form1.cs
2.859375
3
 /* TODO * DataSource to pull in information from spreadsheet * Professor selection handled by listview * LAST NAME, FIRST NAME, ... * Course output handled by either ListView or DataGrid depending on how much information is needed * agree on a design template * form goals of application * when selected, output the classes they teach, otherwise display whitespace * Make buttons work, EDIT ADD REMOVE * add failsafes in case user accidently removes wrong professor * Esc throws "are you sure you want to exit? Yes or no" * We can populate a DataGridView control with Excel spreadsheet data * OpenFileDialog needed to select spreadsheet data to view * Add print capabilities * Add compability with other file types * CONSIDER PORTING TO EPPlus library instead of OLEDB */ using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.OleDb; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace CapstoneProject { public partial class Form1 : Form { public Form1() { InitializeComponent(); } /* Esc closes app */ protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { if (keyData == Keys.Escape) { Close(); return true; } return base.ProcessCmdKey(ref msg, keyData); } /* Prompts user to select database file */ private void OpenButton_Click(object sender, EventArgs e) { OpenFileDialog fdial = new OpenFileDialog { InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyComputer), Title = "Course schedule", Filter = "Microsoft Excel 2007-2013 XML (*.xlsx)|*.xlsx|All Files (*.*)|*.*", //update this as file types are supported FilterIndex = 2, RestoreDirectory = true }; // Fill DataTable with .xlsb file if (fdial.ShowDialog() == DialogResult.OK) { if (fdial.FileName != null) { try { string filename = fdial.FileName.ToString(); string connectionString = "Provider = Microsoft.ACE.OLEDB.12.0; Data Source = " + filename + ";" + "Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\""; //connectionstrings.com OleDbConnection connection = new OleDbConnection(connectionString); // establish link to file OleDbDataAdapter command = new OleDbDataAdapter("select * from [Sheet1$]", connection); // select every cell on Sheet1 DataSet ds = new DataSet(); // initialize dataset for data grid command.Fill(ds); // fill data grid scheduleDataGridView.DataSource = ds.Tables[0]; connection.Close(); } catch (Exception ex) { Console.WriteLine(ex); MessageBox.Show(ex.ToString()); } } } } } }
d2d6b5eaa13c2b159af7e4d182ec58dfa4a260f9
C#
tdochev/TelerikAcademy
/Homeworks/CSharp-Part-2-2015/Arrays/SubsetWithSum/SubsetWithSumS.cs
3.625
4
//Problem 16.* Subset with sum S //We are given an array of integers and a number S. //Write a program to find if there exists a subset of the elements of the array that has a sum S. //Example: //input array S result //2, 1, 2, 4, 3, 5, 2, 6 14 yes using System; class SubsetWithSumS { static void Main() { int Sum = 14; int[] inputArray = { 20, 10, 20, 4, 30, 50, 20, 60 }; Console.WriteLine(subSetDP(inputArray, Sum)); } public static bool subSetDP(int[] A, int sum) { bool[,] solution = new bool[A.Length + 1,sum + 1]; // if sum is not zero and subset is 0, we can't make it for(int i=1;i<=sum;i++) { solution[0,i]=false; } // if sum is 0 the we can make the empty subset to make sum 0 for(int i=0;i<=A.Length;i++) { solution[i,0]=true; } // for(int i=1;i<=A.Length;i++){ for(int j=1;j<=sum;j++){ //first copy the data from the top solution[i,j] = solution[i-1,j]; //If solution[i][j]==false check if can be made if(solution[i,j]==false && j>=A[i-1]) solution[i,j] = solution[i,j] || solution[i-1,j-A[i-1]]; } } return solution[A.Length,sum]; } }
71749b638ba1524c6c93e6b7e8ebd0509b3f9270
C#
abeob1/sg-ae-suki
/1. Source/ai-sski/Suki/Xml/DocumentXML.cs
2.625
3
using System; using System.Collections.Generic; using System.Collections; using System.Linq; using System.Web; using System.Text; using System.Xml; using System.Data; namespace Suki { public class DocumentXML { public String ToXMLStringFromDS(String ObjType,DataSet ds) { try { GeneralFunctions gf = new GeneralFunctions(); StringBuilder XmlString = new StringBuilder(); XmlWriter writer = XmlWriter.Create(XmlString); writer.WriteStartDocument(); { writer.WriteStartElement("BOM"); { writer.WriteStartElement("BO"); { #region write ADMINFO_ELEMENT writer.WriteStartElement("AdmInfo"); { writer.WriteStartElement("Object"); { writer.WriteString(ObjType); } writer.WriteEndElement(); } writer.WriteEndElement(); #endregion #region Header&Line XML foreach (DataTable dt in ds.Tables) { writer.WriteStartElement(dt.TableName.ToString()); { foreach (DataRow row in dt.Rows) { writer.WriteStartElement("row"); { foreach (DataColumn column in dt.Columns) { if(column.DefaultValue.ToString()!="xx_remove_xx") { if (column.ColumnName != "No")//phan lon cac table deu co column No nay { if (row[column].ToString() != "") { writer.WriteStartElement(column.ColumnName); //Write Tag { writer.WriteString(row[column].ToString()); } writer.WriteEndElement(); } } } } } writer.WriteEndElement(); } } writer.WriteEndElement(); } #endregion } writer.WriteEndElement(); } writer.WriteEndElement(); } writer.WriteEndDocument(); writer.Flush(); return XmlString.ToString(); } catch (Exception ex) { return ex.ToString(); } } } }
2f6247490566dafcf46835d19a4d5050bb061caa
C#
shendongnian/download4
/code11/1965320-59823289-213299028-2.cs
2.75
3
public Task<T> DoSomeWorkAsync() { TaskCompletionSource<T> completionSource = new TaskCompletionSource<T>(); SomeBackgroundWorker worker = new SomeBackgroundWorker(); worker.OnWorkComplete += workComplete; worker.DoSomeWorkInABackgroundThread(); return completionSource.Task; void workComplete(T workResult) { worker.OnWorkComplete -= workComplete; completionSource.SetResult(workResult); } }
309a6835e3e7284cd8b8146f1ea19f12ade2c825
C#
onero/VideoApp
/VideoAppBLL/Converters/GenreConverter.cs
2.5625
3
using VideoAppBLL.BusinessObjects; using VideoAppDAL.Entities; namespace VideoAppBLL.Converters { public class GenreConverter : IConverter<Genre, GenreBO> { public Genre Convert(GenreBO entity) { if (entity == null) return null; return new Genre() { Id = entity.Id, Name = entity.Name }; } public GenreBO Convert(Genre entity) { if (entity == null) return null; return new GenreBO() { Id = entity.Id, Name = entity.Name }; } } }
8df33a106d7180a072e45c71ea7dafe4d120576f
C#
Sepp1324/OctoRepository
/OctoAwesome/OctoAwesome/FunctionalBlock.cs
2.78125
3
using engenious; using OctoAwesome.Components; namespace OctoAwesome { /// <summary> /// Base-Class for Functional Blocks /// </summary> public abstract class FunctionalBlock : ComponentContainer<IFunctionalBlockComponent> { /// <summary> /// Interaction with an <see cref="Entity" /> /// </summary> /// <param name="gameTime">Current GameTime</param> /// <param name="entity">InteractionPartner</param> public void Interact(GameTime gameTime, Entity entity) => OnInteract(gameTime, entity); /// <summary> /// Event for Interaction with an <see cref="Entity" /> /// </summary> /// <param name="gameTime">Current GameTime</param> /// <param name="entity">InteractionPartner</param> protected abstract void OnInteract(GameTime gameTime, Entity entity); } }