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
7c264c075eb0a030bb20eb4598e9ab9cb07e2153
C#
severndweller/ProCSharp
/SimpleCSharpConsoleApp/IssuesWithNonGenericCollections/Program.cs
3.609375
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Collections; namespace IssuesWithNonGenericCollections { class Program { static void Main(string[] args) { object myBoxedInt; int myInt; myBoxedInt = SimpleBoxUnboxOperation(); Console.WriteLine("Boxed Int {0}", myBoxedInt); myInt = (int)myBoxedInt; Console.WriteLine("Boxed Int {0}", myInt); int[] myInts = { 6, 2, 1, 4, 9, 8, 3, 20, 15 }; Array.Sort(myInts); // Array.Sort<int>(myInts); foreach (int item in myInts) { Console.WriteLine("Next is {0}", item); } Console.ReadLine(); } static object SimpleBoxUnboxOperation() { //Make Value type (int) variable int myInt = 25; // Box the int into a refernce object object boxedInt = myInt; return boxedInt; } } }
52fd022caefd54135417722eab569bb1c602470d
C#
tectronics/filedb-database
/Setup/Files/Samples/Northwind Database/SalesTotals.linq
2.9375
3
<Query Kind="Statements"> </Query> // generate Aggregate totals from Orders var customerOrders = from c in Customers join o in Orders on c.CustomerID equals o.CustomerID into ordersGrp // "into" gives us hierarchical result sequence select new { CustomerId = c.CustomerID, CustomerName = c.CompanyName, Orders = from order in ordersGrp join od in OrderDetails on order.OrderID equals od.OrderID into orderDetailsGrp // "into" gives us hierarchical result sequence select new { OrderId = order.OrderID, OrderDate = (DateTime) order.OrderDate, NumItems = orderDetailsGrp.Count(), TotalSale = orderDetailsGrp.Sum( od => (float) od.UnitPrice * (int) od.Quantity ), AverageSale = orderDetailsGrp.Average( od => (float) od.UnitPrice * (int) od.Quantity ) } }; customerOrders.Dump();
9fd48f2636f0cbdeca87907e119368e7644a9d60
C#
evgenikolev98/TSP_Uprajneniq
/Lab_upr3/zad1/Form4.cs
3.125
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 zad1 { public partial class Form4 : Form { public Form4() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { double val1 = Double.Parse(textBox1.Text); double val2 = Double.Parse(textBox2.Text); double val3 = Double.Parse(textBox3.Text); try { Disc(val1, val2, val3); } catch { } } private void Disc(double a, double b, double c) { double discriminant = Math.Pow(b, 2) - 4 * a * c; double x1, x2; if (a == 0) { MessageBox.Show(" 'a' трябва да е различно от '0' ", ""); } else { textBox4.Text = discriminant.ToString(); if (discriminant > 0) { x1 = (-b + Math.Sqrt(discriminant)) / (2 * a); x2 = (-b - Math.Sqrt(discriminant)) / (2 * a); textBox5.Text = x1.ToString(); textBox6.Text = x1.ToString(); } else if (discriminant == 0) { x1 = -b / (2 * a); textBox5.Text = x1.ToString(); } else if (discriminant < 0) { MessageBox.Show(" Няма реални корени ", ""); } } } private void button2_Click(object sender, EventArgs e) { try { textBox1.Text = ""; textBox2.Text = ""; textBox3.Text = ""; textBox4.Text = ""; textBox5.Text = ""; textBox6.Text = ""; } catch { } } } }
12e405be02f5e44630f9f9c278a8d0f192a15a80
C#
webstorage119/EyeDisposable
/EyeDisposable/Program.cs
2.703125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.IO; using System.Diagnostics; using EyeDisposable.Core; using System.Reflection; namespace EyeDisposable { static class Program { static void Usage() { var selfName = Path.GetFileName(Assembly.GetEntryAssembly().Location); Console.WriteLine("EyeDisposable by Chris Yuen <chris@kizzx2.com> 2011"); Console.WriteLine(); Console.WriteLine("Instrument assembly to catch IDispose leaks."); Console.WriteLine(); Console.WriteLine("Example: {0} foo.exe", selfName); Console.WriteLine("Example: {0} foo.dll", selfName); } static void Main(string[] args) { if (args.Length != 1) { Usage(); return; } var targetDir = Path.GetDirectoryName(args[0]); new Instrumenter(targetDir).Instrument(args[0], args[0]); // Put EyeDisposable.Logger.dll next to my target File.Copy("EyeDisposable.Logger.dll", Path.Combine( targetDir, "EyeDisposable.Logger.dll"), true); if (File.Exists("EyeDisposable.Logger.pdb")) File.Copy("EyeDisposable.Logger.pdb", Path.Combine(targetDir, "EyeDisposable.Logger.pdb"), true); } } }
794ebfa85b5e8b4cdfdd0835673f180d42ca462e
C#
danielhampikian/GIMM-400
/AI/StateMachineAndBehaviorTree/Assets/BehaviorTreeCustom/SelectorNode.cs
2.71875
3
using System.Collections; using System.Collections.Generic; using UnityEngine; public class SelectorNode : Compositor { NodeStatus[] nodeStats; bool allNodesFailed = false; public SelectorNode(BehaviorTreeController btController) : base(btController) {} public override NodeStatus Tick() { nodeStats = new NodeStatus[children.Length]; NodeStatus nodeStatus = NodeStatus.RUNNING; while (!allNodesFailed) { RunAllNodes(nodeStatus); } if (allNodesFailed) { nodeStatus = NodeStatus.FAILURE; } return nodeStatus; } private void RunAllNodes(NodeStatus nodeStatus) { int i = 0; while (i < children.Length) { while (nodeStatus == NodeStatus.RUNNING) { nodeStatus = children[i].Tick(); //keep ticking in the children until something is not running } if (nodeStatus == NodeStatus.FAILURE) { nodeStats[i] = nodeStatus; } } //we're through all nodes, now we need to either loop or if all failed return failure foreach(NodeStatus ns in nodeStats) { if(ns == NodeStatus.SUCCESS) { RunAllNodes(nodeStatus); //run this function again until we get a failure on all nodes } } // if we get out of this for loop then we've got all failures allNodesFailed = true; } }
68b6402382dfd310fb2cdd1c627b8cd2b6105324
C#
jikoriko/Genus
/RpgEditor/SpriteViewerPanel.cs
2.84375
3
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace RpgEditor { public class SpriteViewerPanel : Panel { private Image Sprite; public SpriteViewerPanel() { Sprite = null; this.AutoScroll = true; } public void SetSprite(Image sprite) { Sprite = sprite; if (sprite != null) { this.AutoScrollMinSize = new Size(sprite.Width, sprite.Height); } else { this.AutoScrollMinSize = new Size(0, 0); } this.Refresh(); } protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); if (Sprite != null) { e.Graphics.DrawImage(Sprite, 0, 0, Sprite.Width, Sprite.Height); int spriteWidth = Sprite.Width / 4; int spriteHeight = Sprite.Height / 4; for (int x = 0; x < 4; x++) { for (int y = 0; y < 4; y++) { Point anchor = y == 0 || y == 3 ? EditorForm.Instance.GetSpriteVerticalAnchor() : EditorForm.Instance.GetSpriteHorizontalAnchor(); Point bounds = y == 0 || y == 3 ? EditorForm.Instance.GetSpriteVerticalBounds() : EditorForm.Instance.GetSpriteHorizontalBounds(); int xPos = (x * spriteWidth) + anchor.X; int yPos = (y * spriteHeight) + anchor.Y; e.Graphics.FillRectangle(new SolidBrush(Color.Red), xPos - 1, yPos - 1, 2, 2); e.Graphics.DrawRectangle(new Pen(Color.Red, 2), xPos - (bounds.X / 2), yPos - (bounds.Y / 2), bounds.X, bounds.Y); } } } } } }
58514663f3b1c404a0b03ede18fc9be76d8dc7de
C#
jjassobarba/DependencyInjection
/Game/Program.cs
3.015625
3
using System; using Game.Clases; using Game.Clases.Armas; using Game.Clases.Bindings; using Game.Clases.Personajes; using Game.Clases.Servicios; using Ninject; namespace Game { class Program { static void Main(string[] args) { var module = new Bindings(); var kernel = new StandardKernel(module); ServicioPersonaje instantiatedService = null; ServicioArmas instantiatedWeapon = null; Console.WriteLine("Selecciona un personaje:"); Console.WriteLine("1. Paladin"); Console.WriteLine("2. Elfo"); Console.WriteLine("3. Mago"); Console.WriteLine("4. Default"); var valorPersonaje = Console.ReadLine(); switch (valorPersonaje) { case "1": var paladin = new ServicioPersonaje(new Paladin()); instantiatedService = paladin; break; case "2": var elfo = new ServicioPersonaje(new Elfo()); instantiatedService = elfo; break; case "3": var mago = new ServicioPersonaje(new Mago()); instantiatedService = mago; break; default: var servicio = kernel.Get<ServicioPersonaje>(); var arma = kernel.Get<ServicioArmas>(); instantiatedService = servicio; instantiatedWeapon = arma; break; } Console.Clear(); if (valorPersonaje != "4") { Console.WriteLine("Selecciona un arma:"); Console.WriteLine("1. Espada"); Console.WriteLine("2. Arco"); Console.WriteLine("3. Hechizo"); } var valorArma = Console.ReadLine(); switch (valorArma) { case "1": var espada = new ServicioArmas(new Espada()); instantiatedWeapon = espada; break; case "2": var arco = new ServicioArmas(new Arco()); instantiatedWeapon = arco; break; case "3": var hechizo = new ServicioArmas(new Hechizo()); instantiatedWeapon = hechizo; break; default: var arma = kernel.Get<ServicioArmas>(); instantiatedWeapon = arma; break; } Console.Clear(); Console.WriteLine(instantiatedService.GetPersonaje() + instantiatedWeapon.Usar()); Console.ReadKey(); } } }
88633e7d07146ed9cb7a63b075e95dae77834f1e
C#
villdimova/SoftUniCSharpAdvanced
/Recursion/FactorielWithRecursion/Program.cs
3.703125
4
using System; namespace FactorielWithRecursion { class Program { static void Main(string[] args) { decimal num = decimal.Parse(Console.ReadLine()); Console.WriteLine( Factorial(num)); } static decimal Factorial(decimal num) { if (num==0) { return 1; } else { return num * Factorial(num - 1); } } } }
d9be9f957699785f1b133828883cef42d60036f9
C#
jchinnici/Ya-s-Program
/ChangeCalculatorApp/GetPair.cs
3.015625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ChangeCalculatorApp { public class GetPair { int[] intarray = new int[] { 1, 4, 2, 3, 3, 6, -1, 7, 5, 1 }; //this.intarray to use this instead of defining public GetPair(int[] intarray) { for (var i = 0; i < intarray.Length- 1; i++) if (intarray[i] + intarray[i + 1] == 6) Console.WriteLine($"{intarray[i]},{intarray[i + 1]}"); } } }
277774e68723182f66928aac373859de6e32da3c
C#
vaclavek/GymVod.PGM-2019-2020
/1. pololetí/Domácí úkoly/Provazník/MergeSort/MergeSort/Program.cs
3.828125
4
using System; namespace Merge { class Program { static int[] MergeSort(int[] arr) { if (arr.Length == 1) return arr; int midpoint = arr.Length / 2; var left = new int[midpoint]; var right = new int[arr.Length - midpoint]; for (int i = 0; i < midpoint; i++) left[i] = arr[i]; for (int i = 0; i < arr.Length - midpoint; i++) right[i] = arr[midpoint + i]; left = MergeSort(left); right = MergeSort(right); int l = 0; int r = 0; for (int i = 0; i < arr.Length; i++) { if (l >= left.Length) { arr[i] = right[r]; r++; } else if (r >= right.Length) { arr[i] = left[l]; l++; } else if (right[r] < left[l]) { arr[i] = right[r]; r++; } else if (right[r] >= left[l]) { arr[i] = left[l]; l++; } } return arr; } static void Main(string[] args) { int[] arr = { 3, 2, 6, 7, 3, 4, 5, 67, 8, 34, 32, 254, 345, 37, 4, 73, 45 }; Console.WriteLine(string.Join(" ", MergeSort(arr))); } } }
711c444e26b50a239256ac8a1888673c6dd7e6ee
C#
gaozeqian/data-structure
/00-LeetCode/数组/_1365_有多少小于当前数字的数字.cs
3.578125
4
using System; using System.Collections.Generic; using System.Text; namespace _00_LeetCode.数组 { /// <summary> /// https://leetcode-cn.com/problems/how-many-numbers-are-smaller-than-the-current-number/ /// </summary> public class _1365_有多少小于当前数字的数字 { public int[] SmallerNumbersThanCurrent(int[] nums) { int minVal = int.MaxValue; int maxVal = int.MinValue; foreach(int num in nums) { if (num < minVal) minVal = num; if (num > maxVal) maxVal = num; } int[] count = new int[maxVal - minVal + 1]; foreach (int num in nums) count[num - minVal]++; int[] preSum = new int[count.Length + 1]; for (int i = 1; i < preSum.Length; i++) preSum[i] = preSum[i - 1] + count[i - 1]; int[] answer = new int[nums.Length]; for (int i = 0; i < nums.Length; i++) answer[i] = preSum[nums[i] - minVal]; return answer; } } }
1ea0149fb0284c8f249d76394206f6319d8af0fa
C#
yan6pz/Telerik-Academy
/Telerik-OOP-DefiningClasses/DefiningClass/Test.cs/Program.cs
2.75
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Point.cs { public class Program //public to be reachable by every other class in solution { static void Main(string[] args) { Path q=new Path(); q.Adding(new Point(1, 2, 3),new Point(-1,-2,-3),new Point(-10,0,10)); PathStorage.Save(q); Path output = PathStorage.Load(); output.Print(); } } }
b0b95038a5a9269904db9ad720766c302e5729aa
C#
cs43/GroupProject
/dxcBookVehicleParkingService/Repo/EmployeeRepo.cs
2.859375
3
using dxcBookVehicleParkingService.Interfaces; using dxcBookVehicleParkingService.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace dxcBookVehicleParkingService.Repo { public class EmployeeRepo : IEmployee { ParkingContext parkingContext = new ParkingContext(); public void AddEmployee(Employee employee) { parkingContext.Employees.Add(employee); parkingContext.SaveChanges(); } public void DeleteEmployee(int id) { var delemp = parkingContext.Employees.Find(id); parkingContext.Employees.Remove(delemp); parkingContext.SaveChanges(); } public void EditEmployee(int id, Employee employee) { var editemp = parkingContext.Employees.Find(id); editemp.EmployeeFirstName = employee.EmployeeFirstName; editemp.EmployeeLastName = employee.EmployeeLastName; editemp.EmployeeMobileNo = employee.EmployeeMobileNo; editemp.EmployeeOfficeAddrs = employee.EmployeeOfficeAddrs; editemp.EmployeeEmail = employee.EmployeeEmail; editemp.EmployeeGender = employee.EmployeeGender; editemp.Password = employee.Password; editemp.UserName = employee.UserName; editemp.VehicleNumber = employee.VehicleNumber; parkingContext.SaveChanges(); } public List<Employee> GetEmployees() { return parkingContext.Employees.ToList(); } public Employee GetEmployee(int id) { var emp = parkingContext.Employees.Find(id); return emp; } public bool CheckCredentials(string username,string password) { var userrec = (from n in parkingContext.Employees where n.UserName == username && n.Password == password select n).FirstOrDefault(); if(userrec!=null) { return true; } return false; } } }
833dc2d6c1bd477e603cdb51adf1271bf79e5b40
C#
cmoro98/TraductorDeLenguaje_JS-PL
/ProcesadorDeLenguaje_JS-PL/ProcesadorDeLenguaje_JS-PL/Cuarteto.cs
2.65625
3
namespace ProcesadorDeLenguaje_JS_PL { public class Cuarteto { private Operador operador; private Atributo arg1; private Atributo arg2; private Atributo dest; public Cuarteto(Operador operador, Atributo arg1, Atributo arg2, Atributo dest) { this.operador = operador; this.arg1 = arg1; this.arg2 = arg2; this.dest = dest; } public Operador Operador { get => operador; set => operador = value; } public Atributo Arg1 { get => arg1; set => arg1 = value; } public Atributo Arg2 { get => arg2; set => arg2 = value; } public Atributo Dest { get => dest; set => dest = value; } } }
4c73dbce605b5e81991b9109380e4e049eca30dc
C#
LYJHub/HW2
/homework2/TestClass.cs
2.671875
3
using NUnit.Framework; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Homework2 { [TestFixture] public class test { [Test] public void fun1() { StringReader input = new StringReader("zhang n12345 3年"); StringReader input1 = new StringReader("${中文姓名}先生(身份证字号${身份证字号})为本校专任教师,聘期${年数}。"); StringWriter output = new StringWriter(); MergeDataAndDoc.Program.StringMethod(input, input1, output); Assert.That(output.ToString(), Is.EqualTo("zhang先生(身份证字号n12345)为本校专任教师,聘期3年。\r\n\r\n\r\n")); } [Test] public void fun2() { StringReader input = new StringReader("wang n12346 2年 "); StringReader input1 = new StringReader("${中文姓名}先生(身份证字号${身份证字号})为本校专任教师,聘期${年数}。"); StringWriter output = new StringWriter(); MergeDataAndDoc.Program.StringMethod(input, input1, output); Assert.That(output.ToString(), Is.EqualTo("wang先生(身份证字号n12346)为本校专任教师,聘期2年。\r\n\r\n\r\n")); } } }
d06fe65a837dfa0e8f3c24db69e4f61db77cefbf
C#
irimescu-maria/E-Commerce
/SweetShop.API/Controllers/ShoppingCartController.cs
2.6875
3
using System; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using SweetShop.API.Repository; namespace SweetShop.API.Controllers { [ApiController] [Route("api/[controller]")] public class ShoppingCartController : ControllerBase { private readonly ICakeRepository _cakeRepository; private readonly IShoppingCartRepository _shoppingCartRepository; public ShoppingCartController(ICakeRepository cakeRepository, IShoppingCartRepository shoppingCartRepository ) { _cakeRepository = cakeRepository; _shoppingCartRepository = shoppingCartRepository; } //GET: api/shoppingcart [HttpGet] public ActionResult GetCartItems() { var items = _shoppingCartRepository.GetShoppingCartItems(); return Ok(items); } //GET: api/shoppingcart [HttpGet] public ActionResult GetTotal(){ var items = _shoppingCartRepository.GetShoppingCartTotal(); return Ok(items); } //POST: api/shoppingCart/{id} [HttpPost("{id}")] public async Task<RedirectToActionResult> AddToShoppingCart(int id) { var selectedCake = await _cakeRepository.Get(id); if(selectedCake != null) { _shoppingCartRepository.AddToCart(selectedCake, 1); } return RedirectToAction("GetCartItems"); } //DELETE: api/shoppingCart/{id} [HttpDelete("{id}")] public async Task<ActionResult> RemoveFromShoppingCart(int id) { var selectedCake = await _cakeRepository.Get(id); if(selectedCake == null) { throw new ArgumentNullException(); } _shoppingCartRepository.RemoveToCart(selectedCake); return Ok(); } } }
9800aecb720593b80b4583a25a82b5b779dca7f7
C#
bernatvadell/WebApi.Proxy
/WebApi.Proxy/WebApi.Proxy/Attributes/HttpFormatterAttribute.cs
2.5625
3
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http.Formatting; using System.Text; using System.Threading.Tasks; namespace WebApi.Proxy.Attributes { [AttributeUsage(AttributeTargets.All, Inherited = true, AllowMultiple = false)] public class HttpFormatterAttribute : Attribute { public string Accept { get; set; } public MediaTypeFormatter Formatter { get; set; } public HttpFormatterAttribute(string accept, Type formatter) { Formatter = (MediaTypeFormatter)Activator.CreateInstance(formatter); Accept = accept; } } }
54710fe6a42ccf4fc7675f79c96bf168fd7a21ca
C#
RuchirSaxena/DependencyInjectionMVC_UnityFramework
/Dependency_Injection_MVC/Controllers/HomeController.cs
2.640625
3
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Dependency_Injection_MVC.Models; namespace Dependency_Injection_MVC.Controllers { public class HomeController : Controller { /* Promblem : The problem with the below approach for injecting service in the the home controlller is that a home controller is not responsible for creating the object of WeatherForecast class as it voilates the concept of SRP(Single Responsibility Principle) and we should invert the object creation to some other class as per Inversion of control principle */ //private IWeatherForecastServiceProvider _weatherForecastServiceProvider; //public HomeController() //{ // _weatherForecastServiceProvider = new WeatherForecast();//Dependency for our controller //} /* Solution The Solution to the above problem can be removing the object ceation work in Home Controller */ private IWeatherForecastServiceProvider _weatherForecastServiceProvider; private IFaceBookConfigurationManager _faceBookConfigurationManager; public HomeController(IWeatherForecastServiceProvider weatherForecastServiceProvider, IFaceBookConfigurationManager faceBookConfigurationManager) { _weatherForecastServiceProvider = weatherForecastServiceProvider; _faceBookConfigurationManager = faceBookConfigurationManager; } /* The problem with the above solution is that the dependent object is not created and will result in error if we execute the code AND the Solution to the above problem is to use UNITY Container , So after Implementing UNITY Containe the above code will work */ // GET: Home public ActionResult Index() { if (_faceBookConfigurationManager.Authenticate()) { ViewBag.Weather = _weatherForecastServiceProvider.GetForeCastByZipCode("201301"); } return View(); } } }
ef1679b790c932680387aefcac69c1d1f873a21e
C#
master369/ExternalTasks-EPAM-
/Projects/Task3/Task3.3/Program.cs
2.984375
3
using System; namespace Task3._3 { class Program { static void Main() { // DynamicArray a = new DynamicArray(); // Console.Write("a = "); // foreach (var item in a) // { // Console.Write("{0} ", item); // } // Console.WriteLine(); // a.AddRange(6, 7, 8); // Console.Write("new a = "); // foreach (var item in a) // { // Console.Write("{0} ", item); // } // Console.WriteLine(); // if (a.Remove(4)) // { // Console.WriteLine(); // foreach (var item in a) // { // Console.Write("{0} ", item); // } // } // else Console.WriteLine(false); } } }
00a4ed1e57bc65ecfe7a2200358a1443e58a0c32
C#
MythZ1225/CSharp-Practice
/346HouseDesign_polymorphism/346HouseDesign_polymorphism/Location.cs
3.671875
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _346HouseDesign_polymorphism { // Location : 抽象 父類 abstract class Location { // 父類建構子 : 屬性 名字 public Location(string name) { this.name = name; } // Location[] : 屬性 Exits public Location[] Exits; // Location : 私屬性 name private string name; // Location : 公屬性 Name ,取得並返回 私屬性 name public string Name { get { return name; } } // 虛擬 字串屬性 描述 public virtual string Description { get { //設立description = "你可以在"+ name + "這個地方看到出口" string description = "你可以在"+ name + "這個地方看到出口" ; //讓description = "你可以在"+ name + "這個地方看到出口" // + " " + Exits[i].Name // +Exits.Length!=0時 for (int i = 0; i < Exits.Length; i++) { description += " " + Exits[i].Name; if (i != Exits.Length-1) { description += ","; } } description += "."; return description; } } } }
f1cf356b4e5ddcc57a6f55b8c06ebdf45841425a
C#
JohanGl/Outworld-XNA
/System/Framework.Physics/CollisionSystem.cs
2.625
3
using System.Collections.Generic; using Framework.Physics.RigidBodies; using Jitter.LinearMath; namespace Framework.Physics { public class CollisionSystem { private Jitter.World World; private Dictionary<RigidBody, Jitter.Dynamics.RigidBody> WorldItems; private Jitter.Dynamics.RigidBody Body; public CollisionSystem(Jitter.World world, Dictionary<RigidBody, Jitter.Dynamics.RigidBody> worldItems) { World = world; WorldItems = worldItems; } public bool CanJump(RigidBody body) { Body = WorldItems[body]; Jitter.Dynamics.RigidBody resultingBody = null; JVector normal; float fraction; var positions = new JVector[] { new JVector(body.Position.X, body.Position.Y, body.Position.Z), new JVector(body.Position.X + 0.5f, body.Position.Y, body.Position.Z), new JVector(body.Position.X - 0.5f, body.Position.Y, body.Position.Z), new JVector(body.Position.X, body.Position.Y, body.Position.Z - 0.5f), new JVector(body.Position.X, body.Position.Y, body.Position.Z + 0.5f)}; for (int i = 0; i < positions.Length; i++) { bool result = World.CollisionSystem.Raycast(new JVector(positions[i].X, positions[i].Y, positions[i].Z), new JVector(0, -1, 0), RaycastCallback, out resultingBody, out normal, out fraction); if (result && fraction <= 1.3f && Body.LinearVelocity.Y < 0.5f) { return true; } } return false; } //public void RayCast(RigidBody body, Vector3 position, Vector3 direction) //{ // Body = WorldItems[body]; // Jitter.Dynamics.RigidBody resultingBody = null; // JVector normal; // float fraction; // float JumpVelocity = 0.5f; // bool result = World.CollisionSystem.Raycast(new JVector(position.X, position.Y, position.Z), // new JVector(direction.X, direction.Y, direction.Z), // RaycastCallback, // out resultingBody, // out normal, // out fraction); // var BodyWalkingOn = (result && fraction <= 0.2f) ? resultingBody : null; // bool canJump = (result && fraction <= 0.2f && Body.LinearVelocity.Y < JumpVelocity); //} private bool RaycastCallback(Jitter.Dynamics.RigidBody body, JVector normal, float fraction) { // prevent the ray to collide with ourself! return (body != Body); } } }
1875408f6775bd755f21a313725b7286baf0060a
C#
ComancheAk/ColorLinesUnity
/Assets/Scripts/GameBoardManager.cs
2.5625
3
using System; using UnityEngine; public class GameBoardManager : MonoBehaviour { public static GameBoardManager Instance; public GameObject ballSpace; public GameObject gameField; public GameObject ballExample; Vector3 leftTopAngle; float xPadding; float yPadding; public BallBehavior[,] field = new BallBehavior[9, 9]; void Awake() { Instance = this; var gameFieldSpriteRenderer = gameField.GetComponent<SpriteRenderer>(); var ballSpriteRenderer = ballExample.GetComponent<SpriteRenderer>(); leftTopAngle = Helpers.GetTopLeftPosition(gameFieldSpriteRenderer, ballSpriteRenderer); xPadding = gameFieldSpriteRenderer.bounds.size.x / 9; yPadding = -gameFieldSpriteRenderer.bounds.size.y / 9; PrepareField(); } private void PrepareField() { for (int x = 0; x < 9; x++) for (int y = 0; y < 9; y++) Instantiate(ballSpace, GetPos(x, y), Quaternion.identity); } public Vector3 GetPos(int x, int y) { return new Vector3(leftTopAngle.x + x * xPadding, leftTopAngle.y + y * yPadding); } public Point ScreenCoordToBoardCoords(Vector3 position) { var xCoord = (int)Math.Round((position.x - leftTopAngle.x) / xPadding); var yCoord = (int)Math.Round((position.y - leftTopAngle.y) / yPadding); return new Point(xCoord, yCoord); } }
0625cb26c49e80f593750a5b8205a05d5aac9767
C#
diogon1984/LocadoraAPI
/Locadora.Repositorio/Repositorios/BaseRepositorio.cs
2.828125
3
using Locadora.Dominio.Contratos; using Locadora.Repositorio.Contexto; using System.Collections.Generic; using System.Linq; namespace Locadora.Repositorio.Repositorios { public class BaseRepositorio<TEntity> : IBaseRepositorio<TEntity> where TEntity : class { protected readonly LocadoraContexto Contexto; public BaseRepositorio(LocadoraContexto locadoraContexto) { Contexto = locadoraContexto; } public void Adicionar(TEntity entity) { Contexto.Set<TEntity>().Add(entity); Contexto.SaveChanges(); } public void Atualizar(TEntity entity) { Contexto.Set<TEntity>().Update(entity); Contexto.SaveChanges(); } public TEntity ObterPorId(int id) { return Contexto.Set<TEntity>().Find(id); } public IEnumerable<TEntity> ObterTodos() { return Contexto.Set<TEntity>().ToList(); } public void Remover(TEntity entity) { Contexto.Remove(entity); Contexto.SaveChanges(); } public void RemoverSelecionados(IEnumerable<TEntity> entities) { Contexto.RemoveRange(entities); Contexto.SaveChanges(); } public void Dispose() { Contexto.Dispose(); } } }
fb7ddfecf379671889884131c44ae053607f5554
C#
210913-USF-NET/P0-Tenzin-Woesel
/StoreBL/BL.cs
2.703125
3
using System; using System.Collections.Generic; using Models; using DL; using System.Text.RegularExpressions; namespace StoreBL { public class BL : IBL { private ICustomerRepo _repo; public BL(ICustomerRepo repo) { _repo = repo; } public List<Customer> GetAllCustomers() { return _repo.GetAllCustomers(); } public Customer AddCustomer(Customer customer) { return _repo.AddCustomer(customer); } public Customer UpdateCustomer(Customer customerToUpdate) { return _repo.UpdateCustomer(customerToUpdate); } public List<Customer> SearchCustomer(string quertStr) { return _repo.SearchCustomer(quertStr); } public List<Product> GetAllProducts() { return _repo.GetAllProducts(); } public List<Order> GetAllOrders() { return _repo.GetAllOrders(); } public List<StoreFront> GetAllStores() { return _repo.GetAllStores(); } public List<LineItems> GetLineItems() { return _repo.GetLineItems(); } public void DeleteCustomer(string email) { _repo.DeleteCustomer(email); } public Product UpdateProduct(Product productToUpdate) { return _repo.UpdateProduct(productToUpdate); } public StoreFront SelectStore(int id) { return _repo.SelectStore(id); } public StoreFront AddStore(StoreFront storeFront) { return _repo.AddStore(storeFront); } public decimal CalculateTotal(Order orderToCalculate) { decimal total = 0; List<LineItems> lineItems = orderToCalculate.LineItems; foreach (LineItems item in lineItems) { int productId = item.ProductId; Product product = _repo.GetProductById(productId); total += product.Price; if(item.Quantity > 1) { total *= item.Quantity; } } return total; } public Order AddOrder(Order order) { return _repo.AddAnOrder(order); } public Product AddProduct(Product product) { return _repo.AddProduct(product); } public List<Inventory> GetAllInventories() { return _repo.GettAllInventories(); } public Customer GetCustomer(string name) { return _repo.GetCustomer(name); } public List<Inventory> GetInventoriesByStoreId(int storeId) { return _repo.GetInventoriesByStoreId(storeId); } public LineItems AddLineItem(LineItems itemToAdd) { return _repo.AddLineItem(itemToAdd); } public Inventory UpdateInventory(Inventory inventoryToUpdate) { return _repo.UpdateInventory(inventoryToUpdate); } public Order UpdateOrder(Order orderToUpdate) { return _repo.UpdateOrder(orderToUpdate); } // public List<LineItems> AddLineItems(List<LineItems> lineItems) // { // return _repo.AddLineItems(lineItems); // } // public List<LineItems> GetLineItemsByOrderId(int orderId) // { // return _repo.GetLineItemsById(orderId); // } } }
416e052cdc39fd61e3a967d6cd4e179e8a07ed85
C#
bubdm/LinqTee
/LinqTee.Tests/Wyer/SmokeTests.cs
3
3
using System.Linq; using LinqTee.Extensions; using NUnit.Framework; namespace LinqTee.Tests.Wyer { [TestFixture] public class SmokeTests { [Test] public void it_left_tees_and_wyes_without_making_changes() { var actual = Enumerable .Range(1, 10) //Only left side will have values .Tee(x => x <= 100) .Wye() .Concatenate(); var expected = Enumerable.Range(1, 10); Assert.That(actual, Is.EqualTo(expected)); } [Test] public void it_right_tees_and_wyes_without_making_changes() { var actual = Enumerable .Range(1, 10) //Only right side will have values .Tee(x => x >= 0) .Wye() .Concatenate(); var expected = Enumerable.Range(1, 10); Assert.That(actual, Is.EqualTo(expected)); } } }
62d519d063db756fbd51dfed3dbccf003f7da1ab
C#
kie0/CCD
/Hausaufgaben/KW_48/ViewCSVFiles.Tests/Mockups/IoMockup.cs
2.640625
3
using System.Collections.Generic; using ViewCSVFiles.Adapters; namespace ViewCSVFiles.Tests.Mockups { public class IoMockup:IIo { private string[] lines; /// <summary> /// Initialisiert eine neue Instanz der <see cref="T:System.Object"/>-Klasse. /// </summary> public IoMockup(params string[] lines) { this.lines = lines; } public IEnumerable<string> ReadCsv(string fileName) { return lines; } } }
9bca0cc9b81a25ded006733b97ac7c2188a36c96
C#
mlovyuan/BsTpe2019_Csharp
/Hw/hw4/hw4/hw4-2/Palindrome.cs
3.609375
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace hw4_2 { public class Palindrome { public static bool PalindromeJudge(string input) { var len = input.Length; bool ans; if (len % 2 == 0) { ans = Judge(input, true); } else { ans = Judge(input, false); } return ans; } private static bool Judge(string input, bool even) { var len = input.Length; var judge = true; if (even == true) { for (int i = 0; i < len; i++) { if (input[i] != input[input.Length - i - 1]) { judge = false; break; } if (i == len / 2) { break; } } } else { for (int i = 0; i < len; i++) { if (i == len / 2 ) { break; } if (input[i] != input[input.Length - i - 1]) { judge = false; break; } } } return judge; } } }
077ff7f23ea3a6d379ce5adbdd06f36afd6a1aaa
C#
verzhyk/lab3.6
/newLaba1Vlad/D1.cs
2.90625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace newLaba1Vlad { public class D1 { private string d1; public D1() { } public D1(string d1) { this.d1 = d1; } public virtual void Show() { Console.WriteLine($"Class type: {nameof(D1)}. d1 = {d1}."); } } }
626bcb4d4eeaf5e4bbb89033fef096ad8d4f24c9
C#
llenroc/Octokit.GraphQL
/Octokit.GraphQL/MentionedEvent.cs
2.515625
3
namespace Octokit.GraphQL { using System.Linq; using System.Linq.Expressions; using Octokit.GraphQL.Core; using Octokit.GraphQL.Core.Builders; /// <summary> /// Represents a 'mentioned' event on a given issue or pull request. /// </summary> public class MentionedEvent : QueryEntity { public MentionedEvent(IQueryProvider provider, Expression expression) : base(provider, expression) { } /// <summary> /// Identifies the actor (user) associated with the event. /// </summary> public User Actor => this.CreateProperty(x => x.Actor, Octokit.GraphQL.User.Create); /// <summary> /// Identifies the date and time when the object was created. /// </summary> public string CreatedAt { get; } public string Id { get; } /// <summary> /// Identifies the issue associated with the event. /// </summary> public Issue Issue => this.CreateProperty(x => x.Issue, Octokit.GraphQL.Issue.Create); /// <summary> /// Identifies the repository associated with the event. /// </summary> public Repository Repository => this.CreateProperty(x => x.Repository, Octokit.GraphQL.Repository.Create); /// <summary> /// Identifies the event type associated with the event. /// </summary> public IssueEventType Type { get; } internal static MentionedEvent Create(IQueryProvider provider, Expression expression) { return new MentionedEvent(provider, expression); } } }
53edd649e1d9b1c9bb79cb6d15b13d7b4e25943e
C#
rainbow23/cSharp
/Dokusyu/7章/PwrOfTwo.cs
3.859375
4
using System; class PwrOfTwo { public int this[int index] { get { if((index >= 0) && (index <16)) return Pwr(index); else return -1; } } int Pwr(int p) { int result = 1; for(int i = 0; i < p; i++) { result *= 2; } return result; } } class UsePwrOfTwo { public static void Main(string[] args) { PwrOfTwo pwr = new PwrOfTwo(); Console.Write("First 8 Power of Two "); for(int i=0; i<8; i++) { Console.WriteLine(pwr[i] + " "); } Console.WriteLine("1*2 " + (1*2) ); } }
a6d1b668048d49248677a8169302b57bf53ee9d9
C#
GataullinRR/EX1
/DeviceBase/IOModels/RichResponse.cs
2.921875
3
using Common; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Utilities; using Utilities.Extensions; namespace DeviceBase.IOModels { enum RichResponseType : ushort { OPERATION_STATUS = 0 } class RichResponse { static readonly EntityDescriptor TypeDescriptor = new EntityDescriptor( "Rich response type", 0, 2, DataEntityFormat.UINT16, v => v.To<ushort>().IsOneOf(EnumUtils.GetValues<RichResponseType>().Select(v2 => v2.To<ushort>()).ToArray())); public RichResponseType Type { get; } public IEnumerable<byte> Body { get; } /// <summary> /// Not null for <see cref="RichResponseType.OPERATION_STATUS"/> /// </summary> public StatusRichResponseData StatusResponseData { get; } public RichResponse(IEnumerable<byte> packetBody) { var raw = (ushort)TypeDescriptor.Deserialize(packetBody); Type = (RichResponseType)raw; if (TypeDescriptor.ValidateValueRange(raw)) { Logger.LogInfo(null, $"Получен ответ типа: {Type}"); switch (Type) { case RichResponseType.OPERATION_STATUS: StatusResponseData = new StatusRichResponseData(packetBody.Skip(TypeDescriptor.Length.Length)); break; default: throw new NotSupportedException(); } } else { Logger.LogErrorEverywhere($"Некорректный тип ответа: {raw:X4}"); } } } }
276d9583af9c2930afc857d852d7c18b89486c01
C#
dimspace/crackhead
/FlickrCache/PhotosetPhoto.cs
3
3
using System; namespace FlickrCache { /// <summary> /// Implement the Equals and GetHashCode method using Id. /// </summary> public partial class PhotosetPhoto { public override bool Equals (object obj) { if (obj == null) return false; if (ReferenceEquals (this, obj)) return true; if (obj.GetType () != typeof(PhotosetPhoto)) return false; PhotosetPhoto other = (PhotosetPhoto)obj; return Id == other.Id; } public override int GetHashCode () { unchecked { return (Id != null ? Id.GetHashCode () : 0); } } } }
1bcd56b23deeee746dc4b8628a5ff1267c06034a
C#
eamoreno/LR-parser
/LR1Parser/StringExtensions.cs
2.71875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace LR1Parser { public static class StringExtensions { public static string ToMeta(this string value) { var regexOperators = new[] { "-", "+", ".", "(", ")", "|", "?", "*" }; foreach (var regexOp in regexOperators){ value = value.Replace(regexOp, @"\" + regexOp); } return value; } } }
dced15b69c85360bd5be59e877030d0b605766cd
C#
PacktPublishing/-Learn-WinUI-3.0
/Chapter03/Start/MyMediaCollection/MainPage.xaml.cs
2.640625
3
using System; using System.Collections.Generic; using Microsoft.UI.Xaml.Controls; using MyMediaCollection.Model; using MyMediaCollection.Enums; using Windows.UI.Popups; using System.Linq; namespace MyMediaCollection { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class MainPage : Page { public IList<MediaItem> _items { get; set; } private IList<MediaItem> _allItems { get; set; } private IList<string> _mediums { get; set; } private bool _isLoaded; public MainPage() { this.InitializeComponent(); ItemList.Loaded += ItemList_Loaded; ItemFilter.Loaded += ItemFilter_Loaded; Loaded += MainPage_Loaded; } private void MainPage_Loaded(object sender, Microsoft.UI.Xaml.RoutedEventArgs e) { ItemFilter.SelectionChanged += ItemFilter_SelectionChanged; PopulateData(); } private async void AddButton_Click(object sender, Microsoft.UI.Xaml.RoutedEventArgs e) { var dialog = new MessageDialog("Adding items to the collection is not yet available.", "My Media Collection"); await dialog.ShowAsync(); } public void PopulateData() { if (_isLoaded) return; _isLoaded = true; var cd = new MediaItem { Id = 1, Name = "Classical Favorites", MediaType = ItemType.Music, MediumInfo = new Medium { Id = 1, MediaType = ItemType.Music, Name = "CD" } }; var book = new MediaItem { Id = 2, Name = "Classic Fairy Tales", MediaType = ItemType.Book, MediumInfo = new Medium { Id = 2, MediaType = ItemType.Book, Name = "Book" } }; var bluRay = new MediaItem { Id = 3, Name = "The Mummy", MediaType = ItemType.Video, MediumInfo = new Medium { Id = 3, MediaType = ItemType.Video, Name = "Blu Ray" } }; _items = new List<MediaItem> { cd, book, bluRay }; _allItems = new List<MediaItem> { cd, book, bluRay }; _mediums = new List<string> { "All", nameof(ItemType.Book), nameof(ItemType.Music), nameof(ItemType.Video) }; } private void ItemList_Loaded(object sender, Microsoft.UI.Xaml.RoutedEventArgs e) { var listView = (ListView)sender; PopulateData(); listView.ItemsSource = _items; } private void ItemFilter_Loaded(object sender, Microsoft.UI.Xaml.RoutedEventArgs e) { var filterCombo = (ComboBox)sender; PopulateData(); filterCombo.ItemsSource = _mediums; filterCombo.SelectedIndex = 0; } private void ItemFilter_SelectionChanged(object sender, Microsoft.UI.Xaml.Controls.SelectionChangedEventArgs e) { var updatedItems = (from item in _allItems where string.IsNullOrWhiteSpace(ItemFilter.SelectedValue.ToString()) || ItemFilter.SelectedValue.ToString() == "All" || ItemFilter.SelectedValue.ToString() == item.MediaType.ToString() select item).ToList(); ItemList.ItemsSource = updatedItems; } } }
f250bc572a719f34b64e850a2a851927ed9b96bf
C#
StackSmack007/OOP-Advanced
/Generics - Exercise/05GenericCountMethodString/StartUp.cs
3.125
3
using System; namespace GenericCountMethodString { public class StartUp { static void Main() { var evaluator = new Evaluator<string>(); int n = int.Parse(Console.ReadLine()); for (int i = 0; i < n; i++) { string item = Console.ReadLine(); evaluator.AddItem(item); } string baseItem = Console.ReadLine(); Console.WriteLine(evaluator.Evaluate(baseItem)); } } }
2d0aa31c2c0d0ab448d7e82d5db0dac3d21a9e3b
C#
andraguitar/Library-MVCProject-
/DALwhithDapper/DapperRepository/OrderDapRepository.cs
3.03125
3
using System; using System.Collections.Generic; using System.Data; using System.Linq; using BLL.Entities; using BLL.IRepo; using Dapper; namespace DALwhithDapper.DapperRepository { public class OrderDapRepository : IOrderRepository { private readonly IDbConnection _db; public List<string> CountOfBooksOnWeek() { var books = _db.Query<string>("select Name from Books where Id=(Select BookId From Orders Where DateOrder BETWEEN DATEADD(D, -7, GETDATE()) AND GETDATE())").ToList(); return books; } public OrderDapRepository(IDbConnection db) { _db = db; } public void Create(OrderEntity model) { var sqlQuery = "INSERT INTO Orders (DateOrder, DateDelivery, BookId, ReaderId) VALUES(@DateOrder, @DateDelivery, @BookId, @ReaderId)"; _db.Execute(sqlQuery, model); } public void Delete(int id) { var sqlQuery = "DELETE FROM Orders WHERE Id = @id"; _db.Execute(sqlQuery, new { id }); } public OrderEntity Get(int id) { var order = _db.Query<OrderEntity>("SELECT * FROM Orders WHERE Id = @id", new { id }).FirstOrDefault(); return order; } public List<OrderEntity> GetMany() { var orders = _db.Query<OrderEntity>("SELECT * FROM Orders").ToList(); return orders; } public List<string> GetBooks(int id) { var bookList = _db.Query<string>("SELECT Name FROM Books INNER " + "JOIN Orders ON Books.Id = Orders.BookId Where Orders.ReaderId = @Id", new { id }).ToList(); return bookList; } public void Update(OrderEntity model) { var sqlQuery = "UPDATE Orders SET DateOrder = @DateOrder, DateDelivery = @DateDelivery, BookId = @BookId, ReaderId =@ReaderId WHERE Id = @Id"; _db.Execute(sqlQuery, model); } public bool IsBookExist(int id) { var order = _db.Query<OrderEntity>("SELECT * FROM Orders WHERE BookId = @id", new { id }).FirstOrDefault(); return order != null; } } }
6304a837b2a002702a2fd1c167b6d8370136d9c1
C#
caiquesantosteixeira/MeuBanco
/MeuBanco/frmAdicionarCliente.cs
2.75
3
using JGourmet.UTIL; using MeuBanco.Models; using MeuBanco.Servvices; 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 MeuBanco { public partial class frmAdicionarCliente : Form { public frmAdicionarCliente() { InitializeComponent(); } private void btnCadastrar_Click(object sender, EventArgs e) { if (txtSenha.Text.Trim() != txtConfirmarSenha.Text.Trim()) { MessageBox.Show("Senha e confirmação de senha divergem."); return; } if (string.IsNullOrEmpty(txtConfirmarSenha.Text) || string.IsNullOrEmpty(txtSenha.Text) || string.IsNullOrEmpty(txtCpf.Text.Trim().RemoverPontos()) || string.IsNullOrEmpty(txtSenha.Text.Trim())) { MessageBox.Show("Dados inválidos"); return; } if (txtCpf.Text.Trim().RemoverPontos().Length != 11) { MessageBox.Show("cpf inválido"); return; } var usuario = new Usuario { UserName = txtCpf.Text.Trim().RemoverPontos(), Senha = txtSenha.Text.Trim(), Email = "" }; var usuarioRetorno = MeuBancoService.PostUsuario(usuario); var cliente = new Cliente(); if (usuarioRetorno != null) { cliente.Nome = txtNome.Text; cliente.Cpf = txtCpf.Text.RemoverPontos(); cliente.Saldo = 0m; cliente.Senha = txtSenha.Text.Trim(); cliente.IdUsuario = usuarioRetorno.Id; } if (validarCliente(cliente)) { if (MeuBancoService.PostCliente(cliente)) { MessageBox.Show("Cliente Cadastrado com sucesso"); } else { MessageBox.Show("Erro ao cadastrar cliente"); } } else { MessageBox.Show("Cliente Inválido.,"); } Close(); } public bool validarCliente(Cliente cliente) { if (string.IsNullOrEmpty(cliente.Nome)) { return false; } if (string.IsNullOrEmpty(cliente.Cpf)) { return false; } if (string.IsNullOrEmpty(cliente.Senha)) { return false; } return true; } } }
6e1c27f3367fcf0f8b18a71b3d720dd8d2fde3a7
C#
boogermanus/dotnet
/DesignPatterns/IteratorPattern/ConcreteAggregates/CandyCollection.cs
3.03125
3
using System.Collections.Generic; using IteratorPattern.Aggregates; using IteratorPattern.Iterators; using IteratorPattern.ConcreteIterators; using IteratorPattern.Models; namespace IteratorPattern.ConcreteAggregates { // the Concrete Aggregate public class CandyCollection : ICandyCollection { private readonly List<JellyBean> _items = new List<JellyBean>(); public IJellyBeanIterator CreateIterator() { return new JellyBeanIterator(this); } public int Count => _items.Count; public JellyBean this[int index] { get => _items[index]; set => _items.Add(value); } } }
d39e4e876277de4ca1e92fcb139cf11f9c7bd1f7
C#
Odonno/Modern-Gitter
/Gitter/Gitter.HtmlToXaml/HtmlToXaml.cs
2.859375
3
using Gitter.HtmlToXaml.Helpers; using HtmlAgilityPack; using System; using System.Collections.Generic; using System.Diagnostics; using Windows.UI.Xaml.Documents; using Windows.UI.Xaml.Input; namespace Gitter.HtmlToXaml { public static class HtmlToXaml { #region Fields public static string RoomName { get; set; } public static List<Block> Blocks { get; set; } public static Paragraph CurrentParagraph { get; set; } public static TappedEventHandler ImageTapped { get; set; } #endregion #region Methods public static void Execute(string html) { try { // Reset properties Blocks = new List<Block>(); CurrentParagraph = null; // Throw exception if HTML content does not exist if (string.IsNullOrEmpty(html)) throw new ArgumentNullException(nameof(html)); // Create an HTML document to search for elements inside (div, span, etc...) var htmlDoc = new HtmlDocument(); htmlDoc.LoadHtml(html); // Generate a complete paragraph based on the HTML content GenerateParagraphs(htmlDoc); } catch (Exception ex) { Debug.WriteLine(ex); } } public static Paragraph NextParagraph() { if (CurrentParagraph == null || CurrentParagraph.Inlines.Count > 0) CurrentParagraph = CreateNewParagraph(); return CurrentParagraph; } private static void GenerateParagraphs(HtmlDocument htmlDoc) { NextParagraph(); foreach (var childNode in htmlDoc.DocumentNode.ChildNodes) { var i = NodeHelper.GenerateBlockForNode(childNode); if (i != null) CurrentParagraph.Inlines.Add(i); } } private static Paragraph CreateNewParagraph() { var p = new Paragraph(); Blocks.Add(p); return p; } #endregion } }
ba0d6c4a77d7644735ac3e881ef6f5859d5d4377
C#
VolkmarR/T4-Runtime-Templates-Example
/TypeScriptCodeGen/Analyzers/AssemblyLoader.cs
2.71875
3
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; namespace TypeScriptCodeGen.Analyzers { static class AssemblyLoader { static Dictionary<string, Assembly> Dependencies = new Dictionary<string, Assembly>(); static Dictionary<string, string> DependenciesDllNames = new Dictionary<string, string>(); static AssemblyLoader() { AppDomain.CurrentDomain.AssemblyResolve += (sender, args) => { var domain = (AppDomain)sender; foreach (var assembly in domain.GetAssemblies()) { if (assembly.FullName == args.Name) return assembly; } if (Dependencies.ContainsKey(args.Name)) return Dependencies[args.Name]; if (DependenciesDllNames.ContainsKey(args.Name)) { var assembly = Assembly.LoadFile(DependenciesDllNames[args.Name]); Dependencies[args.Name] = assembly; return assembly; } return null; }; } public static Assembly LoadAssembly(string assemblyFileName) { foreach (var dll in Directory.GetFiles(Path.GetDirectoryName(assemblyFileName), "*.dll")) if (string.Compare(dll, assemblyFileName, false) != 0) { var an = AssemblyName.GetAssemblyName(dll); if (!DependenciesDllNames.ContainsKey(an.FullName)) DependenciesDllNames[an.FullName] = dll; } return Assembly.LoadFile(assemblyFileName); } } }
4b17b11934ff232152beeed2e02d620877a684bd
C#
devTryer31/Asymptotics_definer
/Tests/ConsoleTestApp/AsymptoticsDefiner.cs
2.984375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using static System.Math; namespace ConsoleTestApp { static class AsymptoticsDefiner { public struct TFunc { public Func<double, double> Exec; public string Str; public TFunc(Func<double, double> exec, string str) { Exec = exec; Str = str; } } public static readonly TFunc[] Funcs = new TFunc[] { new TFunc(x => Log2(Log2(x)), "log2(log2(N))"), new TFunc(x => Sqrt(Log2(x)/2), "sqrt(log2(N)/2)"), new TFunc(x => Log2(x), "log2(N)"), new TFunc(x => Sqrt(x), "sqrt(x)"), new TFunc(x => Pow(Log2(x),2), "log2(N)^2"), new TFunc(x => x, "N"), new TFunc(x => x*Log2(x), "Nlog2(N)"), new TFunc(x => Pow(x, Log2(x)), "N^log2(N)"), new TFunc(x => Pow(x, Sqrt(x)), "N^sqrt(N)"), new TFunc(x => Pow(2,x), "(2^N)"), new TFunc(x => Exp(x), "exp(N)"), new TFunc(x => Factorial(x), "N!"), }; public const int totalMaxN = 20_000_000; private static double Factorial(double numb) { double res = 1; for (double i = numb; i > 1; --i) res *= i; return res; } /// <summary> /// Calculation of the asymptotic complexity of the algorithm with the given N and O(N). /// </summary> /// <param name="NO">One ON pair of {3,5} mean N=3 and O(N)=5.</param> /// <param name="k_bound">The k upper bound where k=R(N)/O(N).</param> /// <returns>O(N)=a*R(N). Where R(N) - the founded asymptotic.</returns> public static (TFunc FuncItem, double a) Evaluate(Dictionary<int, int> NO, int k_bound = 2) { START:; (TFunc expr, double a) resHardCode = (new TFunc(), 0); //Future hardcode funcs (not pow funcs) result. double hardMink = double.MaxValue; //To find minimal k-coefficient. See the method description. for (int fi = 0; fi < Funcs.Length; ++fi) { //for fi-index hurdcode function. var R = Funcs[fi]; double curMax_a = double.MinValue, currMax_k = double.MinValue; double a, k; //O(N)=a*R(N) => a=O(N)/R(N). k=R(N)/O(N) => The greater the a the k smaller. //The smaller k the result varies less from reality. //For searching bad results we should find max a-coefficient. foreach (var pr in NO) { //Searching max a-coefficient. double r = R.Exec(pr.Key); r = (r == 0 ? 1 : r); //I consider that there can be no case a = (pr.Value == 0 ? 1 : pr.Value) / r; //in which no operations are performed. curMax_a = Max(curMax_a, a); //R(N) >= 1 } foreach (var pr in NO) { //Calculating max k-coefficient. double r = R.Exec(pr.Key); r = (r == 0 ? 1 : r); k = curMax_a * r / (pr.Value == 0 ? 1 : pr.Value); if (k > k_bound || k < 1) //If k-coefficient is out of bounds goto next hardcode func. goto END; else currMax_k = Max(currMax_k, k); } if (hardMink > currMax_k) { hardMink = currMax_k; resHardCode = (expr: Funcs[fi], curMax_a); //Set hardcode funcs (not pow funcs) tmp result. } END:; } //There we found (or not (if resHardCode.a == 0)) hardcode funcs result. //There we do similar actions for finde pow-func result //where a numerator=[1..10] and denumerator=[1..10]. double powMink = double.MaxValue; //Future pow-funcs result. (TFunc expr, double a) resPows = (new TFunc(), 0); for (double numer = 1; numer <= 10; ++numer) { for (int denumer = 1; denumer <= 10; ++denumer) { if (numer != denumer) { //Avoid pow is equal 1. double curMax_a = double.MinValue, currMax_k = 0; double a, k; Func<double, double> PowFunc = x => Pow(x, numer / denumer); foreach (var pr in NO) { double p = PowFunc(pr.Key); a = (pr.Value == 0 ? 1 : pr.Value) / (p == 0 ? 1 : p); curMax_a = Max(curMax_a, a); } foreach (var pr in NO) { k = curMax_a * PowFunc(pr.Key) / (pr.Value == 0 ? 1 : pr.Value); if (k > k_bound || k < 1) goto END2; else currMax_k = Max(currMax_k, k); } if (currMax_k < powMink) { powMink = currMax_k; //For beautiful output. if (numer % denumer == 0) { resPows = (new TFunc(PowFunc, $"N^{numer / denumer}"), curMax_a); } else { resPows = (new TFunc(PowFunc, $"N^({numer}/{denumer})"), curMax_a); } } END2:; } } } //If we dont found any answer we axpand the bound of k=[1..k_bound_i + 1] //and go to the start of function using goto to avoid stacko verflow. if (resPows.a == 0 && resHardCode.a == 0) { ++k_bound; goto START; } //We have at least one type of result. else if (resPows.a == 0) //If pow-func answer no found return hardcode func answer. return resHardCode; else if (resHardCode.a == 0) //If hardcode func answer no found return pow-func answer. return resPows; else return powMink < hardMink ? resPows : resHardCode; //Returning a less deviant function. } } }
11887ae0a0685c1a28af8d3b12c2b137542a05c4
C#
contensive/aoDistanceLearning
/Server/aoDistanceLearning/Controllers/QuizController.cs
2.515625
3
using Contensive.Addons.DistanceLearning.Models; using Contensive.BaseClasses; using Contensive.Models.Db; using System; using System.Collections.Generic; namespace Contensive.Addons.DistanceLearning.Controllers { public static class QuizController { // //==================================================================================================== /// <summary> /// Create a new quiz response. Call only if no response exists or the current one get close /// </summary> /// <param name="cp"></param> /// <param name="quiz"></param> /// <returns></returns> public static QuizResponseModel createNewQuizResponse(CPBaseClass cp, QuizModel quiz) { // // -- get the current user var user = DbBaseModel.create<PersonModel>(cp, cp.User.Id); if (user == null) { throw new ApplicationException("The current user [" + cp.User.Id + "] is not valid."); } return createNewQuizResponse(cp, quiz, user); } // //==================================================================================================== /// <summary> /// Create a new quiz response. Call only if no response exists or the current one get close /// </summary> /// <param name="cp"></param> /// <param name="quiz"></param> /// <returns></returns> public static QuizResponseModel createNewQuizResponse(CPBaseClass cp, QuizModel quiz, PersonModel user) { DistanceLearning.Models.QuizResponseModel response = null/* TODO Change to default(_) if this is not a reference type */; try { List<QuizResponseModel> previousResponses = DistanceLearning.Models.QuizResponseModel.getResponseList(cp, quiz.id, user.id); // // -- all previous responses must be complete if (previousResponses.Count > 0) { foreach (var responsex in previousResponses) { if ((!DistanceLearning.Controllers.GenericController.isDateEmpty(responsex.dateSubmitted))) { responsex.dateSubmitted = DateTime.Now; responsex.save(cp); } } } // // -- housekeep subject FK cp.Db.ExecuteNonQuery("update quizquestions set subjectid=null where id in (select q.id from quizquestions q left join quizsubjects s on s.id=q.subjectid where s.id is null)"); // // -- add a new response, and create all the response details (with no answer selected) response = DbBaseModel.addDefault<QuizResponseModel>(cp); response.quizID = quiz.id; response.name = user.name + ", " + quiz.name + ", attempt:" + (previousResponses.Count + 1) + ", " + DateTime.Now.ToShortDateString(); response.memberID = user.id; response.attemptNumber = previousResponses.Count + 1; response.save(cp); // List<QuizSubjectModel> quizSubjectList = DbBaseModel.createList<QuizSubjectModel>(cp, "(quizId=" + quiz.id + ")"); List<QuizQuestionModel> quizQuestionList = new List<QuizQuestionModel>(); List<QuizQuestionModel> quizQuestionFullList = QuizQuestionModel.getQuestionsForQuizList(cp, quiz.id); if ((quiz.maxNumberQuest == 0) | (quiz.maxNumberQuest >= quizQuestionFullList.Count)) { // // -- include all questions that have subjects, ordered by subject order foreach (DistanceLearning.Models.QuizSubjectModel subject in quizSubjectList) { foreach (DistanceLearning.Models.QuizQuestionModel quizQuestion in quizQuestionFullList) { if ((quizQuestion.subjectID == subject.id)) quizQuestionList.Add(quizQuestion); } } // // -- include all questions with no subjects foreach (DistanceLearning.Models.QuizQuestionModel quizQuestion in quizQuestionFullList) { if ((quizQuestion.subjectID == 0)) quizQuestionList.Add(quizQuestion); } } else { // // -- include a random set of questions Random random = new Random(); if ((quizSubjectList.Count > 0)) { // // -- subjects included, add maxNumberQuest to each subject foreach (DistanceLearning.Models.QuizSubjectModel subject in quizSubjectList) { // // -- create list of all questions in the subject List<DistanceLearning.Models.QuizQuestionModel> subjectQuestionList = new List<DistanceLearning.Models.QuizQuestionModel>(); foreach (DistanceLearning.Models.QuizQuestionModel question in quizQuestionFullList) { if (question.subjectID == subject.id) subjectQuestionList.Add(question); } // // -- add random maxNumberQuest to quizquestionList if ((subjectQuestionList.Count > 0)) { for (int questionPtr = 0; questionPtr <= quiz.maxNumberQuest - 1; questionPtr++) { if ((subjectQuestionList.Count == 0)) // // -- no more questions in this subject break; else { int indexTest = random.Next(0, subjectQuestionList.Count); DistanceLearning.Models.QuizQuestionModel question = subjectQuestionList[indexTest]; quizQuestionList.Add(question); subjectQuestionList.Remove(question); } } } } } else // // -- no subjects, add maxNumberQuest questions to quiz for (int questionPtr = 0; questionPtr <= quiz.maxNumberQuest - 1; questionPtr++) { int indexTest = random.Next(0, quizQuestionFullList.Count); DistanceLearning.Models.QuizQuestionModel question = quizQuestionFullList[indexTest]; quizQuestionList.Add(question); quizQuestionFullList.Remove(question); } } // // -- first create quiz pages that have subjects int pageNumber = 1; int detailSortOrder = 0; foreach (DistanceLearning.Models.QuizSubjectModel quizSubject in quizSubjectList) { int subjectQuestionCount = 0; foreach (DistanceLearning.Models.QuizQuestionModel quizQuestion in quizQuestionList) { if (quizQuestion.subjectID == quizSubject.id) { QuizResponseDetailModel detail = DbBaseModel.addDefault<QuizResponseDetailModel>(cp); detail.questionId = quizQuestion.id; detail.responseId = response.id; detail.pageNumber = pageNumber; detail.sortOrder = quizSubject.name + quizQuestion.sortOrder; // detailSortOrder.ToString.PadLeft(7, "0"c) detail.save(cp); if ((quiz.questionPresentation == (int)DistanceLearning.Models.QuizModel.questionPresentationEnum.OneQuestionPerPage)) pageNumber += 1; subjectQuestionCount += 1; detailSortOrder += 1; } } if ((subjectQuestionCount > 0) & (quiz.questionPresentation == (int)DistanceLearning.Models.QuizModel.questionPresentationEnum.OneSubjectPerPage)) pageNumber += 1; } // // -- then add pages for questions with no subjects foreach (DistanceLearning.Models.QuizQuestionModel quizQuestion in quizQuestionList) { bool addDetail = true; if (quizQuestion.subjectID > 0) { bool subjectFound = false; foreach (DistanceLearning.Models.QuizSubjectModel quizSubject in quizSubjectList) { subjectFound = Equals(quizQuestion.subjectID, quizSubject.id); if ((subjectFound)) break; } addDetail = !subjectFound; } if (addDetail) { QuizResponseDetailModel detail = DbBaseModel.addDefault<QuizResponseDetailModel>(cp); detail.questionId = quizQuestion.id; detail.responseId = response.id; detail.pageNumber = pageNumber; detail.sortOrder = detailSortOrder.ToString().PadLeft(7, '0'); detail.save(cp); if ((quiz.questionPresentation == (int)DistanceLearning.Models.QuizModel.questionPresentationEnum.OneQuestionPerPage)) pageNumber += 1; detailSortOrder += 1; } } } catch (Exception ex) { cp.Site.ErrorReport(ex); } return response; } // //==================================================================================================== /// <summary> /// get the current quiz response for the current user. if not valid, create a new one /// </summary> /// <param name="cp"></param> /// <param name="quiz"></param> /// <returns></returns> public static QuizResponseModel verifyQuizResponse(CPBaseClass cp, QuizModel quiz) { // // -- get the current user var user = DbBaseModel.create<PersonModel>(cp, cp.User.Id); if (user == null) { throw new ApplicationException("The current user [" + cp.User.Id + "] is not valid."); } return verifyQuizResponse(cp, quiz, user); } // //==================================================================================================== /// <summary> /// get the current quiz response. if not valid, create a new one /// </summary> /// <param name="cp"></param> /// <param name="quizId"></param> /// <param name="userId"></param> /// <returns></returns> public static QuizResponseModel verifyQuizResponse(CPBaseClass cp, QuizModel quiz, PersonModel user) { // // -- once response is created, the response details are expected to be correct QuizResponseModel response = QuizResponseModel.createLastForThisUser(cp, quiz.id, user.id); if (response == null) { return createNewQuizResponse(cp, quiz, user); } return response; } } }
108d6bdc9a46cfd81f64cebdcf2d54600bf39887
C#
tpham93/Kaibo_Crawler
/Classes/ParticleEmitter.cs
2.796875
3
using SharpDX; using SharpDX.Toolkit; using SharpDX.Toolkit.Graphics; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Kaibo_Crawler { class ParticleEmitter { public Vector2 position; int emitsPerSecond; List<Particle> particles; EParticleType type; public ParticleEmitter(Vector2 position, EParticleType type, int emitsPerSecond) { this.type = type; this.position = position; this.emitsPerSecond = emitsPerSecond; this.particles = new List<Particle>(); } public void update(GameTime gameTime) { //TODO: currently its tick based, make it timebased: emit(type, gameTime); // emit(type, gameTime); // emit(type, gameTime); for (int i = 0; i < particles.Count; i++) { Particle p = particles.ElementAt(i); p.update(gameTime); if (p.lifeTime <= 0) particles.Remove(p); } } public void draw(SpriteBatch sb) { foreach (Particle p in particles) p.draw(sb); } private void emit(EParticleType type, GameTime gametime) { switch (type) { case EParticleType.torchParticle: Vector2 target = new Vector2(position.X, position.Y - 128); Vector2 positionOffset = new Vector2(position.X + (float)Math.Sin(Math.PI*4*Kaibo_Crawler.random.NextDouble()) * 32.0f, position.Y); Vector2 direction = target - positionOffset; direction.Normalize(); float speed = 1; double lifeTime = 2.0d; particles.Add(new Particle(Kaibo_Crawler.particle, positionOffset, direction, speed, lifeTime)); break; } } } }
ca7bdd56f2b121d330c3104f8671da5e41203937
C#
MMDaemon/Voxel-Editor
/MVCCore/Handlers/InputHandler.cs
2.671875
3
using System.Collections.Generic; using System.Drawing; using System.Linq; using MVCCore.Interfaces; using OpenTK; using OpenTK.Input; namespace MVCCore.Handlers { public class InputHandler { private readonly GameWindow _gameWindow; private readonly List<(Key Key, int KeyAction)> _pressKeyActions; private readonly List<(Key Key, int KeyAction)> _holdKeyActions; private readonly List<(MouseButton MouseButton, int KeyAction)> _pressMouseButtonActions; private readonly List<(MouseButton MouseButton, int KeyAction)> _holdMouseButtonActions; private readonly Dictionary<Key, bool> _keyStatesBefore; private readonly Dictionary<Key, bool> _keyStates; private readonly Dictionary<MouseButton, bool> _mouseButtonStatesBefore; private readonly Dictionary<MouseButton, bool> _mouseButtonStates; public ModelInput ModelInput => CreateModelInput(); public InputHandler(GameWindow gameWindow) { _gameWindow = gameWindow; _pressKeyActions = new List<(Key Key, int KeyAction)>(); _holdKeyActions = new List<(Key Key, int KeyAction)>(); _pressMouseButtonActions = new List<(MouseButton MouseButton, int KeyAction)>(); _holdMouseButtonActions = new List<(MouseButton MouseButton, int KeyAction)>(); _keyStatesBefore = new Dictionary<Key, bool>(); _keyStates = new Dictionary<Key, bool>(); _mouseButtonStatesBefore = new Dictionary<MouseButton, bool>(); _mouseButtonStates = new Dictionary<MouseButton, bool>(); _gameWindow.KeyDown += (sender, args) => KeyDown(args.Key); _gameWindow.KeyUp += (sender, args) => KeyUp(args.Key); _gameWindow.MouseDown += (sender, args) => MouseDown(args.Button); _gameWindow.MouseUp += (sender, args) => MouseUp(args.Button); } public void AddPressKeyAction(Key key, int keyAction) { _pressKeyActions.Add((key, keyAction)); if (!_keyStatesBefore.ContainsKey(key)) _keyStatesBefore.Add(key, false); if (!_keyStates.ContainsKey(key)) _keyStates.Add(key, false); } public void AddPressKeyAction(MouseButton mouseButton, int keyAction) { _pressMouseButtonActions.Add((mouseButton, keyAction)); if (!_mouseButtonStatesBefore.ContainsKey(mouseButton)) _mouseButtonStatesBefore.Add(mouseButton, false); if (!_mouseButtonStates.ContainsKey(mouseButton)) _mouseButtonStates.Add(mouseButton, false); } public void AddHoldKeyAction(Key key, int keyAction) { _holdKeyActions.Add((key, keyAction)); if (!_keyStates.ContainsKey(key)) _keyStates.Add(key, false); } public void AddHoldKeyAction(MouseButton mouseButton, int keyAction) { _holdMouseButtonActions.Add((mouseButton, keyAction)); if (!_mouseButtonStates.ContainsKey(mouseButton)) _mouseButtonStates.Add(mouseButton, false); } private ModelInput CreateModelInput() { ModelInput modelInput = new ModelInput(_gameWindow.Mouse.GetState(), GetScreenCenter()); modelInput.KeyActions.AddRange(GetKeyActions()); return modelInput; } private void KeyDown(Key key) { if (_keyStates.ContainsKey(key)) { _keyStates[key] = true; } } private void KeyUp(Key key) { if (_keyStates.ContainsKey(key)) { _keyStates[key] = false; } } private void MouseDown(MouseButton mouseButton) { if (_mouseButtonStates.ContainsKey(mouseButton)) { _mouseButtonStates[mouseButton] = true; } } private void MouseUp(MouseButton mouseButton) { if (_mouseButtonStates.ContainsKey(mouseButton)) { _mouseButtonStates[mouseButton] = false; } } private Point GetScreenCenter() { return _gameWindow.PointToScreen(new Point(_gameWindow.Width / 2, _gameWindow.Height / 2)); } private IEnumerable<int> GetKeyActions() { List<int> keyActionList = new List<int>(); //get keyActions foreach (var pressKeyAction in _pressKeyActions) { if (!keyActionList.Contains(pressKeyAction.KeyAction) && _keyStates[pressKeyAction.Key] && !_keyStatesBefore[pressKeyAction.Key]) { keyActionList.Add(pressKeyAction.KeyAction); } } foreach (var holdKeyAction in _holdKeyActions) { if (!keyActionList.Contains(holdKeyAction.KeyAction) && _keyStates[holdKeyAction.Key]) { keyActionList.Add(holdKeyAction.KeyAction); } } foreach (var pressMouseButtonAction in _pressMouseButtonActions) { if (!keyActionList.Contains(pressMouseButtonAction.KeyAction) && _mouseButtonStates[pressMouseButtonAction.MouseButton] && !_mouseButtonStatesBefore[pressMouseButtonAction.MouseButton]) { keyActionList.Add(pressMouseButtonAction.KeyAction); } } foreach (var holdMouseButtonAction in _holdMouseButtonActions) { if (!keyActionList.Contains(holdMouseButtonAction.KeyAction) && _mouseButtonStates[holdMouseButtonAction.MouseButton]) { keyActionList.Add(holdMouseButtonAction.KeyAction); } } //set before states foreach (var key in _keyStatesBefore.Keys.ToList()) { _keyStatesBefore[key] = _keyStates[key]; } foreach (var mouseButton in _mouseButtonStatesBefore.Keys.ToList()) { _mouseButtonStatesBefore[mouseButton] = _mouseButtonStates[mouseButton]; } return keyActionList; } } }
e422dede93866290a94ff2f3083509b1f62a3c87
C#
isilveira/EntitySearch
/sample/StoreAPI/Core/Application/Categories/Commands/PatchCategory/PatchCategoryCommandHandler.cs
2.5625
3
using MediatR; using Microsoft.EntityFrameworkCore; using StoreAPI.Core.Application.Interfaces.Contexts; using System; using System.Threading; using System.Threading.Tasks; namespace StoreAPI.Core.Application.Categories.Commands.PatchCategory { public class PatchCategoryCommandHandler : IRequestHandler<PatchCategoryCommand, PatchCategoryCommandResponse> { public IStoreContext Context { get; set; } public PatchCategoryCommandHandler(IStoreContext context) { Context = context; } public async Task<PatchCategoryCommandResponse> Handle(PatchCategoryCommand request, CancellationToken cancellationToken) { var id = request.Project(x => x.CategoryID); var data = await Context.Categories.SingleOrDefaultAsync(x => x.CategoryID == id); if (data == null) { throw new Exception("Category not found!"); } request.Patch(data); await Context.SaveChangesAsync(); return new PatchCategoryCommandResponse { Message = "Successful operation!", Request = request.AsDictionary(ModelWrapper.EnumProperties.OnlySupplieds), Data = new PatchCategoryCommandResponseDTO { CategoryID = data.CategoryID, RootCategoryID = data.RootCategoryID, Name = data.Name, Description = data.Description } }; } } }
f9d897c4f392963108030420961074271c337cf5
C#
Slitthe/TechnicalTasks
/ExamplesDisplay/Examples/BoxingUnboxingExample.cs
2.96875
3
using System; using System.Collections.Generic; using System.Linq; using System.Reflection.Metadata; using System.Text; namespace ExamplesDisplay.Examples { public class BoxingUnboxingExample : IExample { public BoxingUnboxingExample() { StartMessage = ""; ; Name = "Boxing/unboxing example"; } public string StartMessage { get; set; } public string Name { get; set; } public string Display() { string consoleText = ""; int i = 42; object boxedI = i; int unboxedI = (int) boxedI; try { string wrongFormatToUnbox = (string) boxedI; } catch (InvalidCastException ex) { consoleText += DisplayFormatHelpers.DescriptionValueFormat("Trying to unbox with a wrong type", ex.Message); } return consoleText; } } }
2e13484121b886d49ed259f158f5a6575d6de805
C#
CyrillCyrillov/SoftUni-CSharp-Advanced-10-Exam-Preparation
/Openning/Bakery.cs
3.5
4
using System; using System.Collections.Generic; using System.Text; using System.Linq; namespace BakeryOpenning { public class Bakery { private List<Employee> data; public Bakery(string name, int capacity) { Name = name; Capacity = capacity; data = new List<Employee>(); } public string Name { get; set; } public int Capacity { get; set; } public int Count { get { return data.Count; } } public void Add(Employee employee) { if(data.Count < Capacity) { data.Add(employee); } } public bool Remove(string name) { Employee nameToRemove = data.FirstOrDefault(n => n.Name == name); if(nameToRemove == null) { return false; } data.Remove(nameToRemove); return true; } public Employee GetOldestEmployee() { //Employee lookFor = data.FirstOrDefault(n => n.Name == name); return data.OrderByDescending(n => n.Age).FirstOrDefault(); } public Employee GetEmployee(string name) { return data.FirstOrDefault(n => n.Name == name); } public string Report() { StringBuilder result = new StringBuilder(); result.AppendLine($"Employees working at Bakery: {Name}"); foreach (var item in data) { result.AppendLine($"Employee: {item.Name}, {item.Age} ({item.Country})"); } return result.ToString(); } } }
bc234d953ead3f80ff867dabe9b1a272bfd2f6f0
C#
hemantCC/WinformsApplication
/Assignment_WebAPI/Assignment.Service/Implementations/VehicleService.cs
2.921875
3
using Assignment.Entity.Entities.BusinessEntities; using Assignment.Repository.Interfaces; using Assignment.Service.Interfaces; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace Assignment.Service.Implementations { public class VehicleService : IVehicleService { #region Private Members /// <summary> /// The vehicle repository /// </summary> private readonly IVehicleRepository _vehicleRepository; #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="VehicleService"/> class. /// </summary> /// <param name="vehicleRepository">The vehicle repository.</param> public VehicleService(IVehicleRepository vehicleRepository) { _vehicleRepository = vehicleRepository; } #endregion #region Public Methods /// <summary> /// Adds the or edit vehicle asynchronous. /// </summary> /// <param name="vehicle">The vehicle.</param> /// <returns></returns> public async Task<bool> AddOrEditVehicleAsync(VehicleViewModel vehicle) { return await _vehicleRepository.AddOrEditVehicleAsync(vehicle); } /// <summary> /// Deletes the vehicle. /// </summary> /// <param name="Id">The identifier.</param> /// <returns></returns> public async Task<bool> DeleteVehicle(int Id) { return await _vehicleRepository.DeleteVehicle(Id); } /// <summary> /// Gets the fuel types. /// </summary> /// <returns></returns> public async Task<IEnumerable<string>> GetFuelTypes() { return await _vehicleRepository.GetFuelTypes(); } /// <summary> /// Gets the transmission types. /// </summary> /// <returns></returns> public async Task<IEnumerable<string>> GetTransmissionTypes() { return await _vehicleRepository.GetTransmissionTypes(); } /// <summary> /// Gets the vehicles asynchronous. /// </summary> /// <param name="searchString">The search string.</param> /// <returns></returns> public async Task<IEnumerable<VehicleViewModel>> GetVehiclesAsync(string searchString) { return await _vehicleRepository.GetVehiclesAsync(searchString); } /// <summary> /// Gets the vehicle types. /// </summary> /// <returns></returns> public async Task<IEnumerable<string>> GetVehicleTypes() { return await _vehicleRepository.GetVehicleTypes(); } #endregion } }
f6322aae9dc8b22bbf9dc18ee2adb000150cbb68
C#
felipealvin13/classificador-de-texto
/src/comparadores/ComparadorSimples.cs
3.515625
4
using System; using System.Linq; using System.Collections.Generic; using BagOfWords = System.Collections.Generic.IDictionary<string, int>; namespace ClassificadorDeTextos.Comparadores { public class ComparadorSimples { public double CalculaDistancia(BagOfWords bag1, BagOfWords bag2) { var palavras = bag1.Keys.Concat(bag2.Keys).Distinct(); double soma = 0; foreach(var palavra in palavras) { int valor1 = 0, valor2 = 0; bag1.TryGetValue(palavra, out valor1); bag2.TryGetValue(palavra, out valor2); soma += Math.Pow(valor1 - valor2, 2); } return Math.Sqrt(soma); } } }
56f43bcddb3521f3c542fd5a72cf43da30577f12
C#
saharSpark/Spark.MessengerApi
/Helper/AuthorizationUtils.cs
2.609375
3
using Newtonsoft.Json; using Spark.MessengerApi.Models; using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Security.Cryptography; using System.Web; namespace Spark.MessengerApi { public static class AuthorizationUtils { internal static UserDTO ResolveIdentity(this ClaimsPrincipal principal) { try { foreach (var claim in principal.Claims) { if (claim.Type == ClaimTypes.NameIdentifier) { var identity = claim.Value.Split(':'); return new UserDTO { Id = identity[0], Username = identity[1] }; } } } catch (Exception ex) { LogManager.WriteLog(null, null, null, JsonConvert.SerializeObject(principal.Claims), "BadRequest", ex.Message).Forget(); } return new UserDTO { }; } internal struct Password { public byte[] Hash { get; set; } public byte[] Salt { get; set; } } internal static byte[] Hash(string plaintext, byte[] salt) { SHA512Cng hashFunc = new SHA512Cng(); byte[] plainBytes = System.Text.Encoding.ASCII.GetBytes(plaintext); byte[] toHash = new byte[plainBytes.Length + salt.Length]; plainBytes.CopyTo(toHash, 0); salt.CopyTo(toHash, plainBytes.Length); return hashFunc.ComputeHash(toHash); } private static byte[] GenerateSalt() { RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); byte[] salt = new byte[256]; rng.GetBytes(salt); return salt; } internal static bool SlowEquals(byte[] a, byte[] b) { int diff = a.Length ^ b.Length; for (int i = 0; i < a.Length && i < b.Length; i++) { diff |= a[i] ^ b[i]; } return diff == 0; } internal static Password HashPassword(string clearPassword) { var salt = GenerateSalt(); return new Password { Salt = salt, Hash = Hash(clearPassword, salt) }; } } }
a1ea0cedf42136a2e3bafacb0ecbb9d1960331b1
C#
shendongnian/download4
/code4/586811-13738986-32811094-2.cs
2.828125
3
public void PopulateGameBoard() { XDocument gameFiles = XDocument.Parse(Properties.Resources.Jeopardy); IEnumerable<string> categories = from category in gameFiles.Descendants("category") select (string)category.Attribute("name"); Label[] cat1HeaderLabel= new Label[100]; int i = 0; categories.Each(p => { cat1HeaderLabel[i] = new Label(); cat1HeaderLabel[i].Text = p; this.Form.Controls.Add(cat1HeaderLabel[i]); i++; }); }
1aca181dbbd695ced069643dec78edca4c1007c6
C#
JessicaVDD/EnhancedReflection
/Product/Willow.Reflection/Reflection/ReflectionCache.cs
2.671875
3
using System; namespace Willow.Reflection { public class ReflectionCache { private readonly Type _OwnerType; private readonly IAccessorCache _Fields; private readonly IAccessorCache _Properties; private readonly IAccessorCache _StaticFields; private readonly IAccessorCache _StaticProperties; private readonly IMethodCache _Methods; private readonly IMethodCache _StaticMethods; public ReflectionCache(Type ownerType) { this._OwnerType = ownerType; this._Fields = new FieldAccessorCache(ownerType); this._Properties = new PropertyAccessorCache(ownerType); this._StaticFields = new StaticFieldAccessorCache(ownerType); this._StaticProperties = new StaticPropertyAccessorCache(ownerType); _Methods = new InstanceMethodCache(ownerType); _StaticMethods = new StaticMethodCache(ownerType); } public Type OwnerType { get { return this._OwnerType; } } public IAccessorCache Fields { get { return this._Fields; } } public IAccessorCache Properties { get { return this._Properties; } } public IAccessorCache StaticFields { get { return this._StaticFields; } } public IAccessorCache StaticProperties { get { return this._StaticProperties; } } public IMethodCache Methods { get { return this._Methods; } } public IMethodCache StaticMethods { get { return this._StaticMethods; } } } public class ReflectionCache<TOwner> { private readonly IAccessorCache<TOwner> _Fields = new FieldAccessorCache<TOwner>(); private readonly IAccessorCache<TOwner> _Properties = new PropertyAccessorCache<TOwner>(); private readonly IAccessorCache<TOwner> _StaticFields = new StaticFieldAccessorCache<TOwner>(); private readonly IAccessorCache<TOwner> _StaticProperties = new StaticPropertyAccessorCache<TOwner>(); private readonly IMethodCache<TOwner> _Methods = new InstanceMethodCache<TOwner>(); private readonly IMethodCache<TOwner> _StaticMethods = new StaticMethodCache<TOwner>(); public IAccessorCache<TOwner> Fields { get { return this._Fields; } } public IAccessorCache<TOwner> Properties { get { return this._Properties; } } public IAccessorCache<TOwner> StaticFields { get { return this._StaticFields; } } public IAccessorCache<TOwner> StaticProperties { get { return this._StaticProperties; } } public IMethodCache<TOwner> Methods { get { return this._Methods; } } public IMethodCache<TOwner> StaticMethods { get { return this._StaticMethods; } } } }
d25de980deb23b6c9ba402b7d0a6b691ab581150
C#
FOUND404F/proyectofinal-DAM
/Prueba/Shop.cs
2.765625
3
/* * NOMBRE Y APELLIDOS..... Raquel Heredia Díaz * CURSO..... 2º Desarrollo de aplicaciones multiplataforma * MODALIDAD..... Trabajo de fin de grado */ using MySql.Data.MySqlClient; using Prueba.Properties; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; namespace Prueba { /// <summary> /// Ventana de la tienda de la aplicación. Aqui se pueden comprar nuevas cartas y añadirlas al mazo /// básico del jugador. /// </summary> public partial class Shop : Form { private delegate void cerrarVentana(); private List<Card> cartasTienda = new List<Card>(); public Shop() { InitializeComponent(); cargarCartasTienda(); textDinero.Text = GameProgress.jugador.Dinero.ToString(); cajaTexto.Text = "¡Bienvenid@! Presiona una de las imágenes para saber sus detalles."; } private void btnAtras_Click(object sender, EventArgs e) { imagenDueñoTienda.Image = Resources.YellowBlue2_FINAL; cajaTexto.Text = "¡Hasta pronto!"; Task task = Task.Run(() => cerrar()); //Se crea un hilo secundario, que se ejecutará al pulsar el botón "Atrás". } /// <summary> /// Método que se ejecuta al cerrar la ventana mediante el botón "Atrás". /// </summary> private void cerrar() { Thread.Sleep(2000); this.Invoke(new cerrarVentana(this.cerrarHilo)); //Se usa Invoke por que no puede acceder al hilo principal. } /// <summary> /// Método que permite al jugador acceder a la ventana de MENÚ SECUNDARIO. /// </summary> private void cerrarHilo() { SecondaryMenu secundario = new SecondaryMenu(); secundario.Show(); this.Close(); } /// <summary> /// Método de compra de las cartas. /// </summary> private void comprar(object sender, EventArgs e) { var button = sender as Button; int posicionCarta = 0; if (button.Name.Contains("1")) { posicionCarta = 0; } else if (button.Name.Contains("2")) { posicionCarta = 1; } else if (button.Name.Contains("3")) { posicionCarta = 2; } else if (button.Name.Contains("4")) { posicionCarta = 3; } Card cartaComprada = cartasTienda[posicionCarta]; if(GameProgress.jugador.Dinero >= cartaComprada.Precio) { GameProgress.jugador.Mazo.Add(cartaComprada); //Se añade la carta al mazo básico. GameProgress.jugador.Dinero -= cartaComprada.Precio; //Se resta el dinero. textDinero.Text = GameProgress.jugador.Dinero.ToString(); //Se actualiza el dinero en la interfaz. MessageBox.Show("Carta " + cartaComprada.NombreCarta + " comprada"); BinaryController.guardarBinario(GameProgress.jugador); //Se guarda la partida. } else { MessageBox.Show("¡Insuficiente dinero!", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Error); } } /// <summary> /// Método que se encarga de cargar las cartas según su id. /// </summary> private void cargarCartasTienda() { ConnectionBD con = new ConnectionBD("proyectofinal"); con.prepareCommand("select * from carta where idCarta between 13 and 16"); MySqlDataReader reader = con.executeSelect(); while (reader.Read()) { int idCarta = reader.GetInt32(0); string nombreCarta = reader.GetString(1); string descripcionCarta = reader.GetString(2); int numeroMana = reader.GetInt32(3); int tipo = reader.GetInt32(4); int daño = reader.GetInt16(5); int curacion = reader.GetInt16(6); bool cartaTemporal = reader.GetBoolean(7); int precio = reader.GetInt16(8); Card carta = new Card (idCarta, nombreCarta, tipo, descripcionCarta, numeroMana, daño, curacion, precio, cartaTemporal); cartasTienda.Add(carta); } } /// <summary> /// Evento en el que aparece texto en la caja de texto al pulsar una imagen de las cartas. /// </summary> private void imagen1_Click(object sender, EventArgs e) { cajaTexto.Text = "Esta carta se llama ESTADILLO. Es una carta de DAÑO y tiene 8 de poder. " + "Cuesta 80 de oro ¿La quieres?"; } private void imagen2_Click(object sender, EventArgs e) { cajaTexto.Text = "Esta carta se llama CURA MÁXIMA. Es una carta de CURACIÓN y tiene 7 de poder." + " Cuesta 80 de oro ¿La quieres?"; } private void imagen3_Click(object sender, EventArgs e) { cajaTexto.Text = "Esta carta se llama ASALTO. Es una carta de ROBO. Te permitirá robar 3 cartas al enemigo." + " Cuesta 60 de oro ¿La quieres?"; } private void imagen4_Click(object sender, EventArgs e) { cajaTexto.Text = "Esta carta se llama INFECCIÓN. Es una carta de ROBO DE VIDA y tiene 7 de poder." + " Cuesta 80 de oro ¿La quieres?"; } } }
a8bd2a12b705d259878109a8cea08c7c5c5e6fa6
C#
thieugiakk-hhp/atb
/GameAttackBees/Function/ShowBees.cs
3.09375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using GameAttackBees.Bees; namespace GameAttackBees.Function { class ShowBees { public void Output(List<Bees.Bees> Bees, int amount) { int nor = 0; foreach (Bees.Bees item in Bees) { Console.Write("\t" + item.name + item.hp); nor++; if (nor % ((amount + 1) / 10) == 0) { Console.WriteLine(); } } } } }
3d3077ac414a2d67ce6edb1c2c1bfe27331e730d
C#
takechup/UnityGameTest
/Assets/Scripts/Scn/Main/Weapon.cs
2.53125
3
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Take.Scn.Main { public class Weapon : MonoBehaviour{ // コンストラクタ public Weapon () { } // 初期化 public void Initialize(GameObject aObj) { mHeroObj = aObj; mCount = 0.0f; mIsTimer = false; mWeapon = null; } /// 更新 public void Update() { /// キー if(Input.GetKeyDown(KeyCode.UpArrow) && !mIsTimer) { // タイマー mIsTimer = true; mCount = 0.8f; // 攻撃開始 var weapon = Resources.Load("Prefabs/Attack") as GameObject; mWeapon = Instantiate(weapon, mHeroObj.transform.position, Quaternion.identity); //mWeapon.transform.parent = mHeroObj.transform; } // タイマー不使用中は不要 if(!mIsTimer){ return; } if(mCount > 0.0f) { mCount -= Time.deltaTime; } if(mCount <= 0.0f) { mIsTimer = false; mCount = 0.0f; Debug.Log("Timer is End"); Destroy(mWeapon); } } /// -------------------------------------------------------------------- /// データ GameObject mHeroObj; GameObject mWeapon; /// タイマー bool mIsTimer; float mCount; } }
3b16ab8d28da2855d9c37d6b290eade87a9aa177
C#
shtwzrd/Rudi
/Game.cs
2.84375
3
using System; using System.Drawing; using OpenTK; using OpenTK.Graphics; using OpenTK.Graphics.OpenGL; using OpenTK.Audio; using OpenTK.Audio.OpenAL; using OpenTK.Input; using Rudi; namespace StarterKit { class Game : GameWindow { Renderer renderer; /// <summary>Creates a 800x600 window with the specified title.</summary> public Game() : base(800, 600, GraphicsMode.Default, "Rudi") { VSync = VSyncMode.On; renderer = new Renderer(); } /// <summary>Load resources here.</summary> /// <param name="e">Not used.</param> protected override void OnLoad(EventArgs e) { base.OnLoad(e); GL.ClearColor(0.1f, 0.2f, 0.5f, 0.0f); } /// <summary> /// Called when your window is resized. Set your viewport here. It is also /// a good place to set up your projection matrix (which probably changes /// along when the aspect ratio of your window). /// </summary> /// <param name="e">Not used.</param> protected override void OnResize(EventArgs e) { base.OnResize(e); /** GL.Viewport(ClientRectangle.X, ClientRectangle.Y, ClientRectangle.Width, ClientRectangle.Height); Matrix4 projection = Matrix4.CreatePerspectiveFieldOfView((float)Math.PI / 4, Width / (float)Height, 1.0f, 64.0f); GL.MatrixMode(MatrixMode.Projection); GL.LoadMatrix(ref projection); */ } /// <summary> /// Called when it is time to setup the next frame. Add you game logic here. /// </summary> /// <param name="e">Contains timing information for framerate independent logic.</param> protected override void OnUpdateFrame(FrameEventArgs e) { base.OnUpdateFrame(e); if (Keyboard[Key.Escape]) Exit(); } /// <summary> /// Called when it is time to render the next frame. Add your rendering code here. /// </summary> /// <param name="e">Contains timing information.</param> protected override void OnRenderFrame(FrameEventArgs e) { base.OnRenderFrame(e); GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit); renderer.Render(); SwapBuffers(); } /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { // The 'using' idiom guarantees proper resource cleanup. // We request 30 UpdateFrame events per second, and unlimited // RenderFrame events (as fast as the computer can handle). using (Game game = new Game()) { game.Run(30.0); } } } }
30f97f5bac32f9a06aa1a4c1f027e5500ea7f374
C#
jacobsylvan/INFC20
/GymShark/GymShark/Test.cs
2.640625
3
using System; using System.Collections.Generic; using MySql.Data.MySqlClient; namespace GymShark { /* public class Test { <<<<<<< HEAD static void Main(string[] args) { Dal dal = new Dal(); Customer customer = new Customer(); customer = dal.FindCustomer("9502181218"); List<Customer> allez = new List<Customer>(); allez=dal.GetAllCustomer(); foreach (Customer c in allez){ Console.WriteLine("Name: {0} {1},, SSN: {2}, Phone: {3}, Email: {4}", c.FirstName, c.LastName, c.SSN, c.PhoneNumber, c.Email); } } } }*/ } //======= /*static void Main(string[] args) { Dal dal = new Dal(); Customer customer = new Customer(); customer = dal.FindCustomer("9502181218"); List<Customer> allez = new List<Customer>(); allez=dal.GetAllCustomer(); foreach (Customer c in allez){ Console.WriteLine("Name: {0} {1},, SSN: {2}, Phone: {3}, Email: {4}", c.FirstName, c.LastName, c.SSN, c.PhoneNumber, c.Email); } } */ //>>>>>>> 428001b226983e11f1e4b95c26da8102f00908dd
1e0fb7f04cf1f197d1453c68be04733385ad1909
C#
juba97/CSharp
/Function/Function/Program.cs
3.78125
4
using System; namespace Function { class Program { static void Main(string[] args) { int Maxs = MaxNumber(1000, 200); Console.WriteLine($"LargestNumber is - {Maxs}"); double Sum = PrintNumber(10.5, 6.3); Console.WriteLine($"Sum is - {Sum}"); int print = Print(6, 6); Console.WriteLine($"Multiplication is - {print}"); programmer(); int Min = Minnumber(1000, 200); Console.WriteLine($"Minnumber is - {Min}"); } public static int MaxNumber(int numbers, int max) { if (numbers > max) { return numbers; } else { return max; } } public static int Minnumber(int Minnumbers, int Min) { if (Minnumbers < Min) { return Minnumbers; } else { return Min; } } public static int Print(int SecondM, int FirstM) { if ((SecondM > 5) && (FirstM > 5)) { return SecondM * FirstM; } return 0; } public static double PrintNumber(double FirstNumber, double SecondNumber) => FirstNumber + SecondNumber; public static void programmer() { Console.WriteLine("I'm a programmer"); } } }
d56b223000b1fedead74de69da307a4882aae0d5
C#
RedAlertTeach/HackerRankAndCodeWars
/PointsOnALine.cs
2.828125
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 Solution { static void Main(string[] args) { int n = Convert.ToInt32(Console.ReadLine()); List<int> xS = new List<int>(); List<int> yS = new List<int>(); for (int nItr = 0; nItr < n; nItr++) { string[] xy = Console.ReadLine().Split(' '); int x = Convert.ToInt32(xy[0]); xS.Add(x); int y = Convert.ToInt32(xy[1]); yS.Add(y); } int prevX = xS.ElementAt(0); string resultX = "YES"; foreach (int i in xS) { if (i != prevX) { resultX = "NO"; break; } prevX = i; } int prevY = yS.ElementAt(0); string resultY = "YES"; foreach (int i in yS) { if (i != prevY) { resultY = "NO"; break; } prevY = i; } if (resultX == "YES" || resultY == "YES") Console.WriteLine("YES"); else Console.WriteLine("NO"); } }
d306f0cdf3174135a9b645e8ceba21ac2750ecb3
C#
josevieiradasilvafilho/SigCorp_EfCore
/EfCore/Controler/Pessoa_Crud.cs
2.9375
3
using EfCore.Model; using System; using System.Linq; namespace EfCore.Controler { public class Pessoa_Crud { public Guid Id_ { get; set; } public string Nome_ { get; set; } public string Documento_ { get; set; } public string Email_ { get; set; } public string Telefone_ { get; set; } public void Buscar() { try { using (AppDbContext db = new AppDbContext()) { var query = from t1 in db.Pessoa where t1.Id.Equals(Id_) select new { t1.Id, t1.Nome, t1.Documento, t1.Email, t1.Telefone }; foreach (var item in query) { Console.WriteLine("Buscar():" + item.Id + ";" + item.Nome + ";" + item.Documento + ";" + item.Email + ";" + item.Telefone + ";" + " OK!"); } } } catch (Exception e) { if (e.Source != null) Console.WriteLine("Buscar(Erro): " + e.Source); } } public bool Buscar_Aux() { try { using (AppDbContext db = new AppDbContext()) { //var Pessoas = db.Set<Model.Pessoa>(); var registro = db.Pessoa.Find(Id_); if (registro.Id != null) { return true; } else return false; } } catch (Exception e) { if (e.Source != null) Console.WriteLine("Buscar_Aux(Erro)", e.Source); return false; } } public void Cadastrar() { try { using (AppDbContext db = new AppDbContext()) { var Pessoas = db.Set<Model.Pessoa>(); Pessoas.Add(new Model.Pessoa { Id = Id_, Nome = Nome_, Documento = Documento_, Email = Email_, Telefone = Telefone_ }); db.SaveChanges(); Console.WriteLine("Cadastrar(): {0}", "Ok!"); } } catch (Exception e) { if (e.Source != null) Console.WriteLine("Err: {0}", e.Source); throw; } } public void Atualizar() { try { using (AppDbContext db = new AppDbContext()) { var Pessoas = db.Set<Model.Pessoa>(); Pessoas.Update(new Model.Pessoa { Id = Id_, Nome = Nome_, Documento = Documento_, Email = Email_, Telefone = Telefone_ }); db.SaveChanges(); Console.WriteLine("Atualizar(): {0}", "Ok!"); } } catch (Exception e) { if (e.Source != null) Console.WriteLine("Err: {0}", e.Source); } } public void Remover() { try { using (AppDbContext db = new AppDbContext()) { var Pessoas = db.Set<Model.Pessoa>(); Pessoas.Remove(new Model.Pessoa { Id = Id_}); db.SaveChanges(); Console.WriteLine("Deletar(): {0}", "Ok!"); } } catch (Exception e) { if (e.Source != null) Console.WriteLine("Err: {0}", e.Source); } } } }
6a68fe26b171d9845320fa2ce4468e602e2495ff
C#
chrisortman/coulda
/vendor/xunit-ca12a1a520db/Main/xunit.extensions/AssumeIdentity/AssumeIdentityAttribute.cs
3.15625
3
using System; using System.Reflection; using System.Security.Principal; using System.Threading; namespace Xunit.Extensions { /// <summary> /// Apply this attribute to your test method to replace the /// <see cref="Thread.CurrentPrincipal"/> with another role. /// </summary> [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] public class AssumeIdentityAttribute : BeforeAfterTestAttribute { readonly string name; IPrincipal originalPrincipal; /// <summary> /// Replaces the identity of the current thread with <paramref name="name"/>. /// </summary> /// <param name="name">The role's name</param> public AssumeIdentityAttribute(string name) { if (string.IsNullOrEmpty(name)) throw new ArgumentException("Name cannot be null or empty", "name"); this.name = name; } /// <summary> /// Restores the original <see cref="Thread.CurrentPrincipal"/>. /// </summary> /// <param name="methodUnderTest">The method under test</param> public override void After(MethodInfo methodUnderTest) { Thread.CurrentPrincipal = originalPrincipal; } /// <summary> /// Stores the current <see cref="Thread.CurrentPrincipal"/> and replaces it with /// a new role identified in constructor. /// </summary> /// <param name="methodUnderTest">The method under test</param> public override void Before(MethodInfo methodUnderTest) { originalPrincipal = Thread.CurrentPrincipal; GenericIdentity identity = new GenericIdentity("xUnit"); GenericPrincipal principal = new GenericPrincipal(identity, new string[] { name }); Thread.CurrentPrincipal = principal; } } }
a944b58cd4a04c0ef18a1bc925c572b50fa7493c
C#
LasseTorp/SWT_Gruppe10_AirTraficMonitoring
/SWT_Gruppe10_AirTraficMonitoring/SortTrackData.cs
2.640625
3
using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading.Tasks; using TransponderReceiver; namespace SWT_Gruppe10_AirTraficMonitoring { public class SortTrackData : ISortTrackData { //Dette skal til for at hooke sig til DLL private ITransponderReceiver reciever_; public SortTrackData(ITransponderReceiver reciever)//Her skal den hooke sig på DLL. interfacet i DLL { reciever_ = reciever; //reciever_.TransponderDataReady += RecieverOnTransponderDataReady; reciever_.TransponderDataReady += SortData; } //// Klassen blev tilføjet for at se om der kunne printes fra dll filen. //private void RecieverOnTransponderDataReady(object sender, RawTransponderDataEventArgs e) //{ // //Dette blev gjort for at se om dataen kom ind og printet på konsollen // foreach (var c in e.TransponderData) // { // Console.WriteLine(c); // } // Console.WriteLine("\n\n"); //} public event EventHandler<AirTrafficEvent> SortDataEvent; public List<FlightDataDTO> data; public List<string> DataRecieved_ { set; get; } public void SortData(object sender, RawTransponderDataEventArgs e) { data = new List<FlightDataDTO>(); DataRecieved_ = new List<string>(); DataRecieved_ = e.TransponderData; string[] inputfields; foreach (var flightData in DataRecieved_) { inputfields = flightData.Split(';'); data.Add(new FlightDataDTO(inputfields[0], Convert.ToInt32(inputfields[1]), Convert.ToInt32(inputfields[2]), Convert.ToInt32(inputfields[3]), DateTime.ParseExact(inputfields[4], "yyyyMMddHHmmssfff", System.Globalization.CultureInfo.InvariantCulture), 0, 0, new CollidingFlightsDTO("", "", ""))); //Console.WriteLine(DateTime.ParseExact(inputfields[4], "yyyyMMddHHmmssfff", System.Globalization.CultureInfo.InvariantCulture)); } if (data.Count!=0) //!data.Contains(null)) { AirTrafficEvent airTrafficEvent = new AirTrafficEvent(data); SortDataEvent?.Invoke(this, airTrafficEvent); } } } }
439686bc7119278a6b1ed18ad931817c2e3e2948
C#
Caliohs/Examen3
/WBL/CompraService.cs
2.5625
3
using BD; using Entity; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WBL { public interface ICompraService { Task<DBEntity> Create(CompraEntity entity); Task<DBEntity> Delete(CompraEntity entity); Task<IEnumerable<CompraEntity>> Get(); Task<CompraEntity> GetById(CompraEntity entity); Task<DBEntity> Update(CompraEntity entity); } public class CompraService : ICompraService { private readonly IDataAccess sql; public CompraService(IDataAccess _sql) { sql = _sql; } public async Task<IEnumerable<CompraEntity>> Get() { try { var result = sql.QueryAsync<CompraEntity, ClientesEntity, ProductoEntity>(sp: "CompraObtener", split: "ClientesId,ProductoId"); return await result; } catch (Exception EX) { throw; } } public async Task<CompraEntity> GetById(CompraEntity entity) { try { var result = sql.QueryFirstAsync<CompraEntity>("CompraObtener", new { entity.IdCompra }); return await result; } catch (Exception) { throw; } } public async Task<DBEntity> Create(CompraEntity entity) { try { var result = sql.ExecuteAsync("CompraInsertar", new { entity.ClientesId, entity.ProductoId, entity.FechaCompra, entity.Monto, entity.Impuesto, Total = (entity.Monto * (entity.Impuesto / 100)) + entity.Monto, entity.Observaciones, entity.Estado, }); return await result; } catch (Exception) { throw; } } public async Task<DBEntity> Update(CompraEntity entity) { try { var result = sql.ExecuteAsync("CompraActualizar", new { entity.IdCompra, entity.ClientesId, entity.ProductoId, entity.FechaCompra, entity.Monto, entity.Impuesto, Total = (entity.Monto * (entity.Impuesto / 100)) + entity.Monto, entity.Observaciones, entity.Estado, }); return await result; } catch (Exception) { throw; } } public async Task<DBEntity> Delete(CompraEntity entity) { try { var result = sql.ExecuteAsync("CompraEliminar", new { entity.IdCompra, }); return await result; } catch (Exception) { throw; } } } }
5cf1407d138dce9118feabd5879d05e299ffdf0d
C#
Acoyan/Inventariode-itens-avalia-ao-1
/ConsoleApplication1/Program.cs
3.34375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; public class Itens { public string name; public Itens next = null; public Itens(string name) { this.name = name; } } namespace ConsoleApplication1 { class Program { private static void Main(string[] args) { Itens Itens1 = new Itens("poçaohp"); Itens Itens2 = new Itens("Poçaompo"); Itens Itens3 = new Itens("espada"); Itens Itens4 = new Itens("machado"); Itens Itens5 = new Itens("casaco"); Itens Itens6 = new Itens("manto"); Itens Itens7 = new Itens("colar"); Itens Itens8 = new Itens("joia"); Itens Itens9 = new Itens("berrante"); Itens Itens10 = new Itens("pokeball"); Itens1.next = Itens2; Itens2.next = Itens3; Itens3.next = Itens4; Itens4.next = Itens5; Itens5.next = Itens6; Itens6.next = Itens7; Itens7.next = Itens8; Itens8.next = Itens9; Itens9.next = Itens10; String x = Console.ReadLine(); Itens currentElement = Itens1; int pos = 1; while ((currentElement != null)) { if (x == currentElement.name) { Console.WriteLine("peguei o Item de nome: " + currentElement.name + (" - Item na posiçao:") + pos); return; } else{ Console.WriteLine("Item nao encontrado"); } currentElement = currentElement.next; pos++; } Console.ReadKey(); } } }
08d2f126899f0313bee8e256265a4402be556397
C#
vitor-giacomelli/ringba-file-statistics
/Program.cs
3.375
3
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text.RegularExpressions; namespace ringba_test { class Program { static void Main(string[] args) { string remoteUri = "https://ringba-test-html.s3-us-west-1.amazonaws.com/TestQuestions/output.txt"; string fileName = Directory.GetCurrentDirectory() + "file.txt"; WebClient webClient = new WebClient(); webClient.DownloadFile(remoteUri, fileName); int[] chars = new int[char.MaxValue]; int countUppercase = 0; string fileString = File.ReadAllText(fileName); string[] splitText = Regex.Split(fileString, @"(?<!^)(?=[A-Z])"); foreach (char t in fileString) { //Counting the characters frequency chars[(int)t]++; //Counting the capitalized letters if (char.IsUpper(t)) countUppercase++; } for (int i = 0; i < (int)char.MaxValue; i++) { if (chars[i] > 0 && char.IsLetterOrDigit((char)i)) { Console.WriteLine("Letter: {0} Frequency: {1}", (char)i, chars[i]); } } var prefixCount = GetPrefixCount(splitText); var wordCount = GetWordCount(splitText); Console.WriteLine("Number of capitalized letters: {0}", countUppercase); Console.WriteLine("Most common word: {0} Frequency: {1}", wordCount.FirstOrDefault().Key, wordCount.FirstOrDefault().Value); Console.WriteLine("Most common prefix: {0} Frequency: {1}", prefixCount.FirstOrDefault().Key, prefixCount.FirstOrDefault().Value); Console.ReadLine(); } private static IOrderedEnumerable<KeyValuePair<string, int>> GetWordCount(string[] list) { return list .SelectMany(x => x.Split()) .GroupBy(x => x) .Select(x => new KeyValuePair<string, int>(x.Key, x.Count())) .OrderByDescending(x => x.Value); } private static IOrderedEnumerable<KeyValuePair<string, int>> GetPrefixCount(string[] list) { //Filter by words with 3 or more letters since 2 letter ones aren't considered to have a valid prefix return list .Where(x => x.Length > 2) .SelectMany(x => x.Substring(0, 2).Split()) .GroupBy(x => x) .Select(x => new KeyValuePair<string, int>(x.Key, x.Count())) .OrderByDescending(x => x.Value); } } }
bc4288bd43f924d5ccec4f85204531811bd8be83
C#
Pranav95/CSE445
/Validate xml Project/Assignment3/Default.aspx.cs
2.734375
3
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace Assignment3 { public partial class _Default : Page { protected void Page_Load(object sender, EventArgs e) { } protected void Verification(object sender, EventArgs e) { ServiceReference1.Service1Client verify = new ServiceReference1.Service1Client(); TextBox5.Text = ""; //validating urls as given on https://stackoverflow.com/questions/7578857/how-to-check-whether-a-string-is-a-valid-http-url Uri url; if (Uri.TryCreate(TextBox2.Text,UriKind.Absolute,out url) && Uri.TryCreate(TextBox3.Text, UriKind.Absolute, out url)) { if(TextBox2.Text!=null && TextBox3.Text!=null) { TextBox5.Text = verify.verify(TextBox2.Text, TextBox3.Text); } else { TextBox5.Text = "Enter URLs first"; } } else { TextBox5.Text = "The URLs are invalid"; } } protected void Transform(object sender, EventArgs e) { ServiceReference2.Service1Client trans = new ServiceReference2.Service1Client(); Label1.Text = ""; Uri uri; if (Uri.TryCreate(TextBox1.Text, UriKind.Absolute, out uri) && Uri.TryCreate(TextBox4.Text, UriKind.Absolute, out uri)) { if(TextBox1.Text!=null && TextBox4.Text!=null) { string html = trans.transform(TextBox1.Text, TextBox4.Text); Label1.Text = html; } else { Label1.Text = "The URLs are invalid"; } } } } }
c12b4189d804336c4d0d2e8eef1a16a237133bf7
C#
agatl/Scale-Up
/OMIS675_Lab0/OMIS675_Lab0/Business Layer/BusinessLayer.cs
2.5625
3
using System; using System.Collections.Generic; using System.Linq; using System.Web; using OMIS675_Lab0.DataLayer; using System.Data; using System.Web.UI.WebControls; using System.Security.Cryptography; using System.Text; using System.IO; namespace OMIS675_Lab0.Business_Layer { public class BusinessLayer { DatabaseLayer db = new DatabaseLayer(); public UserDetails createUserSession(UserDetails user, string email) { DataTable dt = new DataTable(); dt = db.createUserSession(email.Trim()); foreach (DataRow dr in dt.Rows) { user.firstName = dr["first_name"].ToString().Trim(); user.lastName = dr["last_name"].ToString().Trim(); user.lastLogin = (DateTime)dr["last_login_time"]; user.examinee_id = (int)dr["examinee_id"]; } return user; } public void fetchSkills(int examinee_id, int skillid) { db.fetchSkills(examinee_id, skillid); } public DataSet getQuestions(int assessment_id, int examinee_id) { return db.getQuestions(assessment_id, examinee_id); } public int fetchAssessmentStatus(int assessment_id) { return db.fetchAssesmentStatus(assessment_id); } public void createAssessment(int examineeId, List<string> selectedSkills, string assessmentName) { db.createAssessment(examineeId, selectedSkills, assessmentName); } public void UpdateAssessmentStatus(int assessment_id) { db.updateAssessmentStatus(assessment_id); } public DataTable fetchResults(int assessment_id) { return db.fetchResults(assessment_id); } public void storeUserResult(int assessment_id, int correct_answers, int wrong_answers, int total, bool result) { db.storeUserResult(assessment_id, correct_answers, wrong_answers, total, result); } public void UpdateUserStatus(int examinee_id) { db.updateUserStatus(examinee_id); } public void removeSkills(int examineeId,int skillId) { db.removeSkills(examineeId, skillId); } } public class UserDetails { public string lastName { get; set; } public string firstName { get; set; } public string email_id { get; set; } public DateTime lastLogin { get; set; } public int examinee_id { get; set; } static readonly string PasswordHash = "P@@Sw0rd"; static readonly string SaltKey = "S@LT&KEY"; static readonly string VIKey = "@1B2c3D4e5F6g7H8"; public static string Encrypt(string plainText) { byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText); byte[] keyBytes = new Rfc2898DeriveBytes(PasswordHash, Encoding.ASCII.GetBytes(SaltKey)).GetBytes(256 / 8); var symmetricKey = new RijndaelManaged() { Mode = CipherMode.CBC, Padding = PaddingMode.Zeros }; var encryptor = symmetricKey.CreateEncryptor(keyBytes, Encoding.ASCII.GetBytes(VIKey)); byte[] cipherTextBytes; using (var memoryStream = new MemoryStream()) { using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write)) { cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length); cryptoStream.FlushFinalBlock(); cipherTextBytes = memoryStream.ToArray(); cryptoStream.Close(); } memoryStream.Close(); } return Convert.ToBase64String(cipherTextBytes); } public static string Decrypt(string encryptedText) { byte[] cipherTextBytes = Convert.FromBase64String(encryptedText); byte[] keyBytes = new Rfc2898DeriveBytes(PasswordHash, Encoding.ASCII.GetBytes(SaltKey)).GetBytes(256 / 8); var symmetricKey = new RijndaelManaged() { Mode = CipherMode.CBC, Padding = PaddingMode.None }; var decryptor = symmetricKey.CreateDecryptor(keyBytes, Encoding.ASCII.GetBytes(VIKey)); var memoryStream = new MemoryStream(cipherTextBytes); var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read); byte[] plainTextBytes = new byte[cipherTextBytes.Length]; int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length); memoryStream.Close(); cryptoStream.Close(); return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount).TrimEnd("\0".ToCharArray()); } } }
c57e8c8ee8fc4350ff6fbdc7d71fc0274d915c84
C#
Belorus/EventStream
/EventStream/Senders/DelegateEventSender.cs
2.703125
3
using System; using System.Collections.Generic; using EventStream.Abstractions; namespace EventStream.Senders { public class DelegateEventSender : IEventSender { private readonly Action<IList<Event>, Action<bool>> _eventSendAction; public DelegateEventSender(Action<IList<Event>, Action<bool>> eventSendAction) { _eventSendAction = eventSendAction; } public void SendEvents(IList<Event> events, Action<bool> callback) { _eventSendAction(events, callback); } } }
cae0a13976116664e97f0ff1e1f8a243c2fc199b
C#
DamianFCode/ConcretarProyect
/Projecto/Concretar.Services/ReunionService.cs
2.53125
3
using Concretar.Entities; using Concretar.Services.Models; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Concretar.Services { public class ReunionService { private readonly ILogger _logger; readonly UnitOfWork _uow = new UnitOfWork(); public ReunionService(ILogger logger) { _logger = logger; } public GridReunionModel GetAll(int rowPerPages, string FechaCreacionDesde = null, string FechaCreacionHasta = null, int? page = null, int? rows = null) { var model = _uow.ReunionRepository.All(); var gridReunionModel = new GridReunionModel(); if (!String.IsNullOrEmpty(FechaCreacionDesde) || !String.IsNullOrEmpty(FechaCreacionHasta)) { var dateCreateFrom = new DateTime(); var dateCreateTo = new DateTime(); if (FechaCreacionDesde == FechaCreacionHasta) { var fechaDesde = Convert.ToDateTime(FechaCreacionDesde); model = model.Where(x => x.Fecha == fechaDesde); } if (!String.IsNullOrEmpty(FechaCreacionDesde)) { dateCreateFrom = Convert.ToDateTime(FechaCreacionDesde); model = model.Where(x => x.Fecha >= dateCreateFrom); } if (!String.IsNullOrEmpty(FechaCreacionHasta)) { dateCreateTo = Convert.ToDateTime(FechaCreacionHasta); model = model.Where(x => x.Fecha <= dateCreateTo); } } var totalRows = model.Count(); model = model.Skip((page - 1 ?? 0) * (rows ?? rowPerPages)).Take(rows ?? rowPerPages); gridReunionModel.TotalRows = totalRows; var reunion = model.Select(x => new ReunionViewModel() { Cliente = x.Cliente, ClienteId = x.ClienteId, Usuario = x.Usuario, UsuarioId = x.UsuarioId, Fecha = x.Fecha, Motivo = x.Motivo, Resultado = x.Resultado, ReunionId = x.ReunionId }); gridReunionModel.ListReuniones = reunion.ToList(); return gridReunionModel; } public void Create (ReunionViewModel model) { try { var cliente = _uow.ClienteRepository.Find(x => x.ClienteId == model.ClienteId); var usuario = _uow.UsuarioRepository.Find(x => x.UsuarioId == model.UsuarioId); var reunion = new Reunion() { ClienteId = model.ClienteId, Fecha = model.Fecha, Motivo = model.Motivo, Resultado = model.Resultado, UsuarioId = model.UsuarioId, Cliente = cliente, Usuario = usuario }; _uow.ReunionRepository.Create(reunion); _uow.ReunionRepository.Save(); _logger.LogInformation("Reunion creada correctamente"); } catch(Exception e) { _logger.LogError("Ocurrio un error al crear la reunion. Error {0}", e); throw; } } public ReunionViewModel GetById(int id) { try { var model = _uow.ReunionRepository.Find(x => x.ReunionId == id); var reunion = new ReunionViewModel() { Cliente = model.Cliente, ClienteId = model.ClienteId, Fecha = model.Fecha, Motivo = model.Motivo, Resultado = model.Resultado, ReunionId = model.ReunionId, Usuario = model.Usuario, UsuarioId = model.UsuarioId }; _logger.LogInformation("Reunion obtenida correctamente"); return reunion; } catch (Exception e) { _logger.LogError("Ocurrio un error al obtener la reunion. Error {0}", e); throw; } } public void Edit (ReunionViewModel model) { try { var reunion = _uow.ReunionRepository.Find(x => x.ReunionId == model.ReunionId); reunion.Fecha = model.Fecha; reunion.ClienteId = model.ClienteId; reunion.UsuarioId = model.UsuarioId; reunion.Motivo = model.Motivo; reunion.Resultado = model.Resultado; _uow.ReunionRepository.Update(reunion); _uow.ReunionRepository.Save(); _logger.LogInformation("Reunion editada correctamente"); } catch(Exception e) { _logger.LogError("Ocurrio un error al editar la reunion. Error {0}", e); throw; } } public void Delete (int id) { try { var reunion = _uow.ReunionRepository.Find(x => x.ReunionId == id); _uow.ReunionRepository.Delete(reunion); _uow.ReunionRepository.Save(); _logger.LogInformation("Reunion eliminada correctamente"); } catch(Exception e) { _logger.LogError("Ocurrio un error al eliminar la reunion. Error {0}", e); throw; } } } }
5541874849e2bf4250fd17bde674a2ac6d33406e
C#
TibzZ/w3d4_csharp102_workshop-paradox
/ArraysAndLists/Program.cs
4.0625
4
using System; using System.Collections.Generic; namespace ArraysAndLists { class Program { static void Main(string[] args) { //Create a list of 5 num, console write it, return count var myNumList = new List<int>() { 1, 2, 3, 4, 5 }; foreach (int num in myNumList) { Console.WriteLine(num); } Console.WriteLine($"My List has {myNumList.Count} entries"); //Create array with same number of element // BONUS can this be done without writing number? var ListToArray = myNumList.ToArray(); Console.Write($"My Array has {ListToArray.Length} elements: "); foreach(int num in ListToArray){ //Console.Write($"{num}"); Console.Write(string.Join(",",num)); } } } }
59032cb600fa1edc67f5ad78db5658ed991b339b
C#
peterlambov/CSharp
/C#Homeworks/C#Part2Homeworks/07TextFiles/Ex02TwoFiles/Concat.cs
3.515625
4
//Write a program that concatenates two text files into another text file. using System; using System.IO; using System.Linq; namespace Ex02TwoFiles //To open the test.txt after executing the program and see the result you can click on "Show all files" //on the top of the Solution Explorer and the test.txt will appear right under Concat.cs //or to go to bin>debug>test.txt //Then you can delete the written text on the file and run the program again. { class Concat { static void Main() { StreamWriter writerFirst = new StreamWriter(@"..\..\test.txt",false); using (writerFirst) { StreamReader readFirstDoc = new StreamReader(@"..\..\Concat.cs"); //The first document is the Concat.cs. using (readFirstDoc) { string lineDoc1 = readFirstDoc.ReadLine(); while(lineDoc1!=null) { writerFirst.WriteLine(lineDoc1); lineDoc1=readFirstDoc.ReadLine(); } } } StreamWriter writerSecond = new StreamWriter(@"..\..\test.txt", true); using(writerSecond) { StreamReader readSecondDoc = new StreamReader(@"..\..\App.config"); //The second document is App.config using (readSecondDoc) { string lineDoc2 = readSecondDoc.ReadLine(); while (lineDoc2 != null) { writerSecond.WriteLine(lineDoc2); lineDoc2 = readSecondDoc.ReadLine(); } } } Console.WriteLine("Concatenation finished!"); } } }
6cfa342c41eb24e347b6a2d6fd3cba795f91fd87
C#
AbbaraoAnvitha/Joy-bot
/Joy_Bot/Controllers/EchoDialog.cs
2.71875
3
using Microsoft.Bot.Builder.Dialogs; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Threading.Tasks; using Microsoft.Bot.Connector; namespace Joy_Bot.Controllers { [Serializable] public class EchoDialog : IDialog<object> { public async Task StartAsync(IDialogContext context) { context.Wait(MessageReceivedAsync); } private async Task MessageReceivedAsync(IDialogContext context, IAwaitable<IMessageActivity> argument) { var message = await argument; string msg = message.Text; if (msg.ToLower().Contains("hi")) { await context.PostAsync("Hi , How are you today?"); context.Wait(MessageReceivedAsync); } else if (msg.ToLower().Contains("thanks") || msg.ToLower().Contains("thank") || msg.ToLower().Contains("thx")) { await context.PostAsync("No problem!"); context.Wait(MessageReceivedAsync); } else { await context.PostAsync("Can you say that again..."); context.Wait(MessageReceivedAsync); } } } }
7e2f75651b99f5ea98edbbe47e1ecb06475acaff
C#
sammosampson/AppliedMessagingExamples
/src/UnitTesting/Subscriber/ThirdPartyLibrary.cs
2.703125
3
namespace Subscriber { using System; public class ThirdPartyLibrary : IThirdPartyLibrary { public void AddActivity(string tenantId, string policyNumber, string text) { Console.WriteLine($"Adding activity for tenant: {tenantId}, policy: {policyNumber}, with text: {text}"); } public void AddPolicyHeader(string tenantId, string policyNumber) { Console.WriteLine($"Adding policy header for tenant: {tenantId}, policy: {policyNumber}"); } public void AddPolicyLines(string tenantId, string policyNumber) { Console.WriteLine($"Adding policy lines for tenant: {tenantId}, policy: {policyNumber}"); } } }
b7e068d36e0e084d982453777d7a60fea3c89a12
C#
Mingmoon52/ASAM_3D_1023
/3D_RPG/Assets/Script/LreanOperator.cs
2.671875
3
using System.Collections; using System.Collections.Generic; using UnityEngine; public class LreanOperator : MonoBehaviour { public int A = 10, B = 3; public int C = 1; public int prop = 1; public int D = 9; public float E = 99.9f , F = 10.5f; public float hp = 100; public bool key; public int enemy; // Start is called before the first frame update public void Start() { #region 數學運算子 //加減乘除餘 + - * / % print(A + B); print(A - B); print(A * B); print(A / B); print(A % B); //指派:先運算指派符號右邊再傳回左邊 C = 9 + 1; print("C運算結果:"+ C); // prop = prop + 1;原本寫法 print(prop++);//後置遞增:先輸出在運算-輸出結果為1,記憶體內存於3 print(++prop);//前置遞增:先運算在輸出-輸出結果為3,記憶體內存於1 //遞減-- //D = D +10; D += 10 ; #endregion #region 比較運算子 print(E > F); //true print(E < F); //false print(E >= F); //t print(E <= F); //f print(E == F); //f print(E != F); //t #endregion #region 邏輯運算子 //並且 && 只要有一個 false 結果就是false print(true && true); //true print(true && false); //false print(false && true); //false print(false && false); //false //並且 || 只要有一個 true 結果就是true print(true || true); //true print(true || false); //true print(false || true); //true print(false || false); //false //相反 print(!true); //false print(!false); //true #endregion } // Update is called once per frame private void Update() { print("死亡:" + (hp <= 0)); print("過關判定:" + (key && enemy >= 5)); } }
9f77a3296edeb508225d2ea65d1197a4ea8835f3
C#
mm2288/is421calculator
/CalculatorProjectTests/CalculatorTests.cs
2.96875
3
using Microsoft.VisualStudio.TestTools.UnitTesting; using CalculatorProject; using System; using System.Collections.Generic; using System.Text; using CalculatorProject.CalculatorFunctions; using CalculatorProject.Models; using System.Reflection; namespace CalculatorProject.Tests { [TestClass()] public class CalculatorTests { [TestMethod()] public void CalculatorTest() { Calculator _calculator = new Calculator(); Assert.IsInstanceOfType(_calculator, typeof(Calculator)); } [TestMethod()] public void SumTest() { //arrange double _a = 1; double _b =2; double _c; //act _c = Addition.Sum(_a, _b); //Assert Assert.AreEqual(_c, 3); } [TestMethod()] public void DifferenceTest() { //arrange double _a = 4; double _b = 2; double _c; //act _c = Subtraction.Difference(_a, _b); //Assert Assert.AreEqual(_c, 2); } [TestMethod()] public void ProductTest() { //arrange double _a = 3; double _b = 3; double _c; //act _c = Multiplication.Product(_a, _b); //Assert Assert.AreEqual(_c, 9); } [TestMethod()] public void QuotientTest() { //arrange double _a = 24; double _b = 3; double _c; //act _c = Division.Quotient(_a, _b); //Assert Assert.AreEqual(_c, 8); } [TestMethod()] public void CalculationTest() { double _a = 1; double _b = 2; string _action = "multiplication"; Calculator _calculator = new Calculator(_a, _b, _action); var _result = _calculator.Calculation[0].GetResult(); _action = "division"; _calculator.CreateCalculation(_a, _b, _action); _result = _calculator.Calculation[1].GetResult(); _calculator.Calculation.ForEach(delegate (Calculation calculation) { Console.WriteLine(calculation.GetResult()); }); } } }
aff508bc5166f104a7085870ac7f571d5a7bb598
C#
mono/coreclr
/src/mscorlib/src/System/Nullable.cs
2.53125
3
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; namespace System { using System.Globalization; using System.Reflection; using System.Collections.Generic; using System.Runtime; using System.Runtime.CompilerServices; using System.Security; using System.Diagnostics.Contracts; // Warning, don't put System.Runtime.Serialization.On*Serializ*Attribute // on this class without first fixing ObjectClone::InvokeVtsCallbacks // Also, because we have special type system support that says a a boxed Nullable<T> // can be used where a boxed<T> is use, Nullable<T> can not implement any intefaces // at all (since T may not). Do NOT add any interfaces to Nullable! // [Serializable] [System.Runtime.Versioning.NonVersionable] // This only applies to field layout public struct Nullable<T> where T : struct { private bool hasValue; internal T value; [System.Runtime.Versioning.NonVersionable] public Nullable(T value) { this.value = value; this.hasValue = true; } public bool HasValue { [System.Runtime.Versioning.NonVersionable] get { return hasValue; } } public T Value { get { if (!hasValue) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_NoValue); } return value; } } [System.Runtime.Versioning.NonVersionable] public T GetValueOrDefault() { return value; } [System.Runtime.Versioning.NonVersionable] public T GetValueOrDefault(T defaultValue) { return hasValue ? value : defaultValue; } public override bool Equals(object other) { if (!hasValue) return other == null; if (other == null) return false; return value.Equals(other); } public override int GetHashCode() { return hasValue ? value.GetHashCode() : 0; } public override string ToString() { return hasValue ? value.ToString() : ""; } [System.Runtime.Versioning.NonVersionable] public static implicit operator Nullable<T>(T value) { return new Nullable<T>(value); } [System.Runtime.Versioning.NonVersionable] public static explicit operator T(Nullable<T> value) { return value.Value; } // The following already obsoleted methods were removed: // public int CompareTo(object other) // public int CompareTo(Nullable<T> other) // public bool Equals(Nullable<T> other) // public static Nullable<T> FromObject(object value) // public object ToObject() // public string ToString(string format) // public string ToString(IFormatProvider provider) // public string ToString(string format, IFormatProvider provider) // The following newly obsoleted methods were removed: // string IFormattable.ToString(string format, IFormatProvider provider) // int IComparable.CompareTo(object other) // int IComparable<Nullable<T>>.CompareTo(Nullable<T> other) // bool IEquatable<Nullable<T>>.Equals(Nullable<T> other) } [System.Runtime.InteropServices.ComVisible(true)] public static class Nullable { [System.Runtime.InteropServices.ComVisible(true)] public static int Compare<T>(Nullable<T> n1, Nullable<T> n2) where T : struct { if (n1.HasValue) { if (n2.HasValue) return Comparer<T>.Default.Compare(n1.value, n2.value); return 1; } if (n2.HasValue) return -1; return 0; } [System.Runtime.InteropServices.ComVisible(true)] public static bool Equals<T>(Nullable<T> n1, Nullable<T> n2) where T : struct { if (n1.HasValue) { if (n2.HasValue) return EqualityComparer<T>.Default.Equals(n1.value, n2.value); return false; } if (n2.HasValue) return false; return true; } // If the type provided is not a Nullable Type, return null. // Otherwise, returns the underlying type of the Nullable type public static Type GetUnderlyingType(Type nullableType) { if((object)nullableType == null) { throw new ArgumentNullException("nullableType"); } Contract.EndContractBlock(); Type result = null; if( nullableType.IsGenericType && !nullableType.IsGenericTypeDefinition) { // instantiated generic type only Type genericType = nullableType.GetGenericTypeDefinition(); if( Object.ReferenceEquals(genericType, typeof(Nullable<>))) { result = nullableType.GetGenericArguments()[0]; } } return result; } // The following already obsoleted methods were removed: // public static bool HasValue<T>(Nullable<T> value) // public static T GetValueOrDefault<T>(Nullable<T> value) // public static T GetValueOrDefault<T>(Nullable<T> value, T valueWhenNull) // The following newly obsoleted methods were removed: // public static Nullable<T> FromObject<T>(object value) // public static object ToObject<T>(Nullable<T> value) // public static object Wrap(object value, Type type) // public static object Unwrap(object value) } }
5e0d43f49f2f6c4f1f041e8aefe421a0486664e5
C#
pradeepdhawan/icbc-report-builder
/ReportLib/ReportBuilder/ReportBuilder.cs
2.78125
3
using OfficeOpenXml; using ReportLib.ReportData; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace ReportLib { public class ReportBuilder : IReportBuilder { private List<ExcelWorksheet> worksheets; public IExcelTemplate ReportTemplate { get; set; } public IList<Report> ReportData { get; set; } public void Build() { worksheets = new List<ExcelWorksheet>(); foreach (Report report in ReportData) { var worksheet = ReportTemplate.Read(report.Name); var cells = worksheet.Cells; var dictionary = cells .GroupBy(c => new { c.Start.Row, c.Start.Column }) .ToDictionary( rcg => new KeyValuePair<int, int>(rcg.Key.Row, rcg.Key.Column), rcg => cells[rcg.Key.Row, rcg.Key.Column].Value == null ? String.Empty : cells[rcg.Key.Row, rcg.Key.Column].Value.ToString()); foreach (ReportVal val in report.ReportVal) { //find row that has value //find column that has value var matchingColumn = dictionary.Where(pair => pair.Value == val.ReportCol.ToString("000")).Select(pair => pair.Key); //since we are matching column, column that comes first will be given preference var maxc = matchingColumn.Max(kvp => kvp.Value); var col = matchingColumn.Where(kvp => kvp.Value == maxc).Select(kvp => kvp.Value).First(); var matchingRow = dictionary.Where(pair => pair.Value== val.ReportRow.ToString("000")).Select(pair => pair.Key); var maxr = matchingRow.Max(kvp => kvp.Key); var row = matchingRow.Where(kvp => kvp.Key == maxr).Select(kvp => kvp.Key).First(); cells[row, col].Value = val.Val; Console.WriteLine(cells[row, col].Address); Console.WriteLine(cells[row, col].Value); //set value } worksheets.Add(worksheet); } } public byte[] GetReport() { Build(); using (var package = new ExcelPackage()) { foreach (var ws in worksheets) { package.Workbook.Worksheets.Add(ws.Name, ws); } var excelData = package.GetAsByteArray(); var contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; return excelData; } //package.Save(); } } }
56023c3e0343fbdc1353ee08c39edb2881e8440b
C#
sampathnarine/wpf-demos
/Showcase/Diagram Builder/CS/Struct/ConnectorState.cs
2.75
3
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ConnectorState.cs" company=""> // // </copyright> // <summary> // Customizing the connector appearance using connectorstate class. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace DiagramBuilder { using System.Windows; using System.Windows.Media; /// <summary> /// Customizing the connector appearance using connectorstate class. /// </summary> public struct ConnectorState { /// <summary> /// Initializes a new instance of the <see cref="ConnectorState"/> struct. /// </summary> /// <param name="stroke"> /// The stroke values applies to the stroke property of the connector. /// </param> /// <param name="dasdot"> /// The dasdot values applies to the dashdot property of the connector.. /// </param> /// <param name="thickness"> /// The thickness values applies to the thickness property of the connector.. /// </param> /// <param name="scap"> /// The scap values applies to the sourcecap property of the connector.. /// </param> /// <param name="tcap"> /// The tcap values applies to the targetcap property of the connector.. /// </param> /// <param name="sdecorator"> /// The sdecorator values applies to the sourcedecorator property of the connector.. /// </param> /// <param name="Tdecorator"> /// The tdecorator value applies to the targetdecorator property of the connector. /// </param> /// <param name="sdecoratorstyle"> /// The sdecoratorstyle value applies to the sourcedecorator style property of the connector.. /// </param> /// <param name="tdecoratorstyle"> /// The tdecoratorstyle value applies to the targetdecorator style property of the connector.. /// </param> /// <param name="style"> /// The style value applies to the connectorgeometrystyle property of the connector.. /// </param> /// <param name="decorator"> /// The decorator value applies to the decorator property of the connector. /// </param> public ConnectorState( Brush stroke, string dasdot, double thickness, string scap, string tcap, object sdecorator, object Tdecorator, Style sdecoratorstyle, Style tdecoratorstyle, Style style, string decorator) { this._mConnectorGeometryStyle = style; this.mStroke = stroke; this._mDashDot = dasdot; this.mThickness = thickness; this._mSourceCap = scap; this.mTargetCap = tcap; this._mSourceDecorator = sdecorator; this._mTargetDecorator = Tdecorator; this._mSourceDecoratorStyle = sdecoratorstyle; this._mTargetDecoratorStyle = tdecoratorstyle; this._mDecorator = decorator; } /// <summary> /// Represents the _m connector geometry style. /// </summary> private Style _mConnectorGeometryStyle; /// <summary> /// Gets or sets the connector geometry style. /// </summary> public Style ConnectorGeometryStyle { get { return this._mConnectorGeometryStyle; } set { if (this._mConnectorGeometryStyle != value) { this._mConnectorGeometryStyle = value; } } } /// <summary> /// Represents the _m source cap. /// </summary> private string _mSourceCap; /// <summary> /// Gets or sets the source cap. /// </summary> public string SourceCap { get { return this._mSourceCap; } set { if (this._mSourceCap != value) { this._mSourceCap = value; } } } /// <summary> /// Represents the _m decorator. /// </summary> private string _mDecorator; /// <summary> /// Gets or sets the decorator. /// </summary> public string Decorator { get { return this._mDecorator; } set { if (this._mDecorator != value) { this._mDecorator = value; } } } /// <summary> /// Represents the _m target cap. /// </summary> private string mTargetCap; /// <summary> /// Gets or sets the target cap. /// </summary> public string TargetCap { get { return this.mTargetCap; } set { if (this.mTargetCap != value) { this.mTargetCap = value; } } } /// <summary> /// Represents the _m source decorator. /// </summary> private object _mSourceDecorator; /// <summary> /// Gets or sets the source decorator. /// </summary> public object SourceDecorator { get { return this._mSourceDecorator; } set { if (this._mSourceDecorator != value) { this._mSourceDecorator = value; } } } /// <summary> /// Represents the _m target decorator. /// </summary> private object _mTargetDecorator; /// <summary> /// Gets or sets the target decorator. /// </summary> public object TargetDecorator { get { return this._mTargetDecorator; } set { if (this._mTargetDecorator != value) { this._mTargetDecorator = value; } } } /// <summary> /// Represents the _m source decorator style. /// </summary> private Style _mSourceDecoratorStyle; /// <summary> /// Gets or sets the source decorator style. /// </summary> public Style SourceDecoratorStyle { get { return this._mSourceDecoratorStyle; } set { if (this._mSourceDecoratorStyle != value) { this._mSourceDecoratorStyle = value; } } } /// <summary> /// Represents the _m target decorator style. /// </summary> private Style _mTargetDecoratorStyle; /// <summary> /// Gets or sets the target decorator style. /// </summary> public Style TargetDecoratorStyle { get { return this._mTargetDecoratorStyle; } set { if (this._mTargetDecoratorStyle != value) { this._mTargetDecoratorStyle = value; } } } /// <summary> /// Represents the _m stroke. /// </summary> private Brush mStroke; /// <summary> /// Gets or sets the stroke. /// </summary> public Brush Stroke { get { return this.mStroke; } set { if (this.mStroke != value) { this.mStroke = value; } } } /// <summary> /// Represents the _m dash dot. /// </summary> private string _mDashDot; /// <summary> /// Gets or sets the dash dot. /// </summary> public string DashDot { get { return this._mDashDot; } set { if (this._mDashDot != value) { this._mDashDot = value; } } } /// <summary> /// Represents the _m thickness. /// </summary> private double mThickness; /// <summary> /// Gets or sets the thickness. /// </summary> public double Thickness { get { return this.mThickness; } set { if (this.mThickness != value) { this.mThickness = value; } } } } }
156389d31a27c8b4c41048ab86f2fafef1315458
C#
RafaelSantosBraz/Sistemas-Operacionais
/Scheduler_Project/System_Core/System_Core/Kernel.cs
2.828125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Timers; namespace System_Core { public static class Kernel { // cronômetro para controlar o Time Sharing private static Timer clock; // envio dos processos de alto nível para organização interna em baixo nível public static bool load_processes(List<Process> processes) { return Scheduler.insertion_processes(processes); } // responsável por inicializar os atributos do Time Sharing public static void start_time_sharing() { clock = new Timer(); clock.Interval = 6000; clock.Elapsed += Scheduler.schedule; clock.Enabled = true; } // apenas faz o cancelamento do Time Sharing public static void close_time_sharing() { clock.Enabled = false; } // solicita a mudança de regra ao escalonador public static bool change_rule_scheduler(int new_rule) { return Scheduler.change_rule(new_rule); } } }
11b83de3a022547ff986d29c2522984c79845f87
C#
kjifw/TAS2015
/Programming/03. OOP/02. DefiningClassesPartII/11. VersionAttribute/VersionAttributeTest.cs
3.625
4
// Problem 11. Version attribute // * Create a [Version] attribute that can be applied to structures, classes, // interfaces, enumerations and methods and holds a version in the format // major.minor (e.g. 2.11). // * Apply the version attribute to a sample class and display its version at runtime. namespace _11.VersionAttribute { using System; using System.Reflection; [VersionAttribute(1, 17)] enum DaysOfTheWeek { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday } [VersionAttribute(2, 11)] class VersionAttributeTest { static void Main(string[] args) { Type currentType = typeof(VersionAttributeTest); object[] allAttributes = currentType.GetCustomAttributes(false); foreach (var item in allAttributes) { Console.WriteLine(item); } currentType = typeof(DaysOfTheWeek); allAttributes = currentType.GetCustomAttributes(false); foreach (var item in allAttributes) { Console.WriteLine(item); } } } }
9bd9821d421e5131e986d2ea86cf5904953edfaf
C#
meridian34/Modul_2_Task_3
/Modul_2_Task_3/Services/Logger.cs
2.828125
3
using System; using Modul_2_Task_3.Model; using Modul_2_Task_3.Model.Enum; using Modul_2_Task_3.Services.Abstract; namespace Modul_2_Task_3.Services { public class Logger : ILoggerService { private readonly IFileService _fileService; private readonly LogConfigData _logConfig; private static readonly Logger _instance = new Logger(); private Logger() { var configService = new ConfigService(); _fileService = new FileService(); _logConfig = configService.GetConfig().LogConfigData; } public static Logger Instance { get { return _instance; } } public void Log(LogType logType, string message) { var logMessage = $"{DateTime.UtcNow}: {logType}: {message}"; _fileService.Write(logMessage, _logConfig); } public void LogInfo(string message) { Log(LogType.Info, message); } public void LogWarning(string message) { Log(LogType.Warning, message); } public void LogError(string message) { Log(LogType.Error, message); } } }
414dcfcd8893db7ad14c939e519f2ccbf1ac0087
C#
nayutalienx/adboard
/IdentityServer/IdentityServer/ExceptionHandler.cs
2.5625
3
using IdentityServer.Contracts; using IdentityServer.Exceptions; using Microsoft.AspNetCore.Http; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace IdentityServer { public sealed class ExceptionHandler { private readonly RequestDelegate _next; public ExceptionHandler(RequestDelegate next) => _next = next; public async Task InvokeAsync(HttpContext context) { try { await _next(context); } catch (UserReadableException exception) { // Добавить логирование. await SetErrorAsync(context, exception); context.Response.StatusCode = StatusCodes.Status200OK; } catch (Exception exception) { // Добавить логирование. await SetErrorAsync(context, exception); context.Response.StatusCode = StatusCodes.Status500InternalServerError; } } private static async Task SetErrorAsync(HttpContext context, Exception exception) { var error = new ApiResponse(exception.Message); var json = JsonConvert.SerializeObject(error); await context.Response.WriteAsync(json); } } }
741c4471183689843f81de72f5d438bd12a681df
C#
edwinchukus/sharp_gate_repo
/cod/fishSharp/exception handling/phone.cs
3.203125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace fishSharp.exception_handling { public class phone { public void DivideNumber(int a, int b) { try { double an = a / b; Console.WriteLine(an); } catch (Exception exception) { } } internal double DivideNumber() { throw new NotImplementedException(); } } }
98150a6b93ad2201d4e9f6a802942bca46e22e44
C#
thimh/Jaar-2-v2
/MODL3/Van BB/MODL3_Sokoban_Console_refactored/Domain/Maze.cs
3
3
using System; using System.Collections.Generic; namespace Sokoban.Domain { public class Maze { private List<Crate> _crates = new List<Crate>(); public bool IsSolved { get { int numberOfCrates = _crates.Count; int numberOfCratesOnTarget = 0; foreach(Crate crate in _crates) { if (crate.IsOnTarget()) { numberOfCratesOnTarget++; } } return (numberOfCrates == numberOfCratesOnTarget); } } public BaseField Origin { get; set; } public Truck TheTruck { set; get; } public int Width { get; set; } public int Height { get; set; } public void AddCrate(Crate k) { if(k != null) { _crates.Add(k); } else { throw new ArgumentNullException("crate"); } } public void moveTruck(Direction r) { TheTruck.Move(r); } } }
d2a39aca7f089e66ac1cfc930cebcc0a54206df2
C#
AdilBayraktar/ReCapProject
/DataAccess/Concrete/EntityFramework/EfCarDal.cs
2.5625
3
using Core.DataAccess.EntityFramework; using DataAccess.Abstracts; using Entities.Concrete; using Entities.DTOs; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; namespace DataAccess.Concrete.EntityFramework { public class EfCarDal : EfEntityRepositoryBase<Car,CarsDbContext> ,ICarDal { public List<CarDetailsDto> GetCarsDetails() { using (CarsDbContext context = new CarsDbContext()) { var result = from c in context.Car join co in context.Color on c.ColorId equals co.ColorId join b in context.Brand on c.BrandId equals b.BrandId select new CarDetailsDto { CarName = c.CarName, BrandName = b.BrandName, ColorName = co.ColorName, CarId = c.CarId }; return result.ToList(); } } } }
fd8a2475201693059a3d683189fba0507e783e5e
C#
green-fox-academy/arvaianett
/week-06/weekend/Zoo/Zoo/Animal.cs
2.578125
3
using System; using System.Collections.Generic; using System.Text; namespace Zoo { public abstract class Animal { public string name; public int age; public Animal(string name) { } public abstract string Greet(); public abstract string WantChild(); public abstract string GetName(); } }
9b4ea6444074bc798099fb1899f9ebe760fc8552
C#
Jalsson/SpaceCraft_264
/Assets/RGBColor.cs
2.515625
3
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class RGBColor : MonoBehaviour { public Image colorPreviewImage; public Slider[] RGBSliders; public Image[] fillAreaColors; public Image currentPreviewImage; public void ChangeColorSlider() { colorPreviewImage.color = new Color(RGBSliders[0].value , RGBSliders[1].value , RGBSliders[2].value ); currentPreviewImage.color = new Color(RGBSliders[0].value, RGBSliders[1].value, RGBSliders[2].value); } public void ChangeSliderColor() { fillAreaColors[0].color = new Color(RGBSliders[0].value, 0, 0); fillAreaColors[1].color = new Color(0, RGBSliders[1].value, 0); fillAreaColors[2].color = new Color(0, 0, RGBSliders[2].value); } public void ChangeSliderValues() { colorPreviewImage.color = currentPreviewImage.color; var redValue = colorPreviewImage.color.r; var greenValue = colorPreviewImage.color.g; var blueValue = colorPreviewImage.color.b; RGBSliders[0].value = redValue; RGBSliders[1].value = greenValue; RGBSliders[2].value = blueValue; } }
b1a58b7fa4a438f651322ebf50cb785f52800777
C#
pliekhus/Liekhus.Diagnostics.EventHubListener
/EventHubListener.cs
2.515625
3
using Microsoft.ServiceBus.Messaging; using System; using System.Configuration; using System.Diagnostics; using System.Reflection; using System.Text; namespace Diagnostics.EventHubListener { public class EventHubListener : TraceListener { private EventHubClient _client; public EventHubListener() { if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["EventHub.ConnectionString"])) { ConnectionString = ConfigurationManager.AppSettings["EventHub.ConnectionString"]; } if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["EventHub.UseJson"])) { UseJson = bool.Parse(ConfigurationManager.AppSettings["EventHub.UseJson"]); } if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["EventHub.LogPattern"])) { LogPattern = ConfigurationManager.AppSettings["EventHub.LogPattern"]; } _client = EventHubClient.CreateFromConnectionString(ConnectionString); } private string _logPattern = "%a% %e% %u% %t% %m%"; public string LogPattern { get { return _logPattern; } set { _logPattern = value; } } public string ConnectionString { get; set; } public override void Write(string message) { WriteLine(message); } public bool UseJson { get; set; } private string FormatMessage(string message) { string formattedMessage = LogPattern.Replace("%e%", Environment.MachineName); formattedMessage = formattedMessage.Replace("%a%", Assembly.GetEntryAssembly().FullName); formattedMessage = formattedMessage.Replace("%u%", Environment.UserName); formattedMessage = formattedMessage.Replace("%t%", string.Format("{0} {1}", DateTime.Now.ToShortDateString(), DateTime.Now.ToShortTimeString())); formattedMessage = formattedMessage.Replace("%m%", message); return formattedMessage; } private string JsonMessage(string message) { string json = string.Format("{{ \"dateTime\": \"{0} {1}\"", DateTime.Now.ToShortDateString(), DateTime.Now.ToShortTimeString()); if (LogPattern.Contains("%a%")) { json = string.Format("{0},\"assemblyName\": \"{1}\"", json, Assembly.GetEntryAssembly().FullName); } if (LogPattern.Contains("%e%")) { json = string.Format("{0},\"machineName\": \"{1}\"", json, Environment.MachineName); } if (LogPattern.Contains("%u%")) { json = string.Format("{0},\"userName\": \"{1}\"", json, Environment.UserName); } json = string.Format("{0},\"message\": \"{1}\"", json, message); json = string.Format("{0}}}", json); return json; } public override void WriteLine(string message) { string logMessage = string.Empty; if (UseJson) { logMessage = JsonMessage(message); } else { logMessage = FormatMessage(message); } _client.Send(new EventData(Encoding.UTF8.GetBytes(logMessage))); } public override void Write(object o) { base.Write(o); } public override void Write(object o, string category) { base.Write(o, category); } public override void Write(string message, string category) { base.Write(message, category); } public override void WriteLine(object o) { base.WriteLine(o); } public override void WriteLine(object o, string category) { base.WriteLine(o, category); } public override void WriteLine(string message, string category) { base.WriteLine(message, category); } public static void ShutdownLogging() { } } }
ecaa31413ff90f5cc188c1f5f54a9342db807397
C#
EbricenterOrg/Taller
/Taller Mecanico - Modulo Clientes V 3.0/Taller Mecanico/ControlEmpresarial Visual Studio 2010 c#/CONYMA/csTipoServicio.cs
2.640625
3
/*Autor: Cesar Estuardo Flore Escobar *Fecha: 27 Agosto del 2014 *Comentario:*/ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace EBRICENTER { public class csTipoServicio { //Propiedades de Tabla Cliente, campos que se encuentran en la base de datos public int iId_Tserv { get; set; } public string sDescripcion_serv { get; set; } public string sPrecio_serv { get; set; } public csTipoServicio() { } //Se utiliza para crear los objetos, ya que de esta forma no recibe parámetros public csTipoServicio(int piId_Tserv, string psDescripcion_serv, string psPrecio_serv) { //Asignacion de Parametros a Propiedades this.iId_Tserv = piId_Tserv; this.sDescripcion_serv = psDescripcion_serv; this.sPrecio_serv = psPrecio_serv; } } }
e52238ec7fe5db3bb1f180fa25e37576baa815fa
C#
fredrhae/automacao_sistema_web
/AutomacaoWeb/AutomacaoWeb/Pages/Pages.cs
2.53125
3
using AutomacaoWeb; using OpenQA.Selenium.Support.PageObjects; namespace AutomacaoWeb { public interface IPage { void Goto(); bool IsAt(); } public abstract class Pages<T> where T : IPage, new() { private static T _instance = default(T); public static T Instance { get { if (_instance == null) { _instance = GetPage(); } return _instance; } } public static T GetPage() { var page = new T(); PageFactory.InitElements(Browser.Driver, page); return page; } } }
c2819bbde97e0faf3a00e912dacececfe72a9894
C#
programmiertier/OperationOverLoad_ConsoleApplication
/OperationOverLoad_ConsoleApplication/Program.cs
3.265625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using static System.Console; namespace OperationOverLoad_ConsoleApplication { class Program { static void Main(string[] args) { Rechteck blumenbeet = new Rechteck(10, 15) { bepflanzung = "Gras" }; // string so hinzufügen, statt ein weiteres mal zu überladen /* blumenbeet.umfang = 0; // deswegen wird in Rechteck der setter ignoriert // Abruf hierdurch vom Setter */ WriteLine("Der Zaun um das Blumenbeet ist:\t{0} Meter lang", blumenbeet.umfang); WriteLine("Es müssen hier ganze {0,6:F2} m² Fläche begossen werden", blumenbeet.flaeche); WriteLine(blumenbeet.bepflanzung); // bepflanzung wird angezeigt ReadLine(); Kreis rund = new Kreis(10.5); WriteLine("Einmal um den Teich herum macht {0,6:F2} Meter gelaufen", rund.umfang); WriteLine("Der Seerosenteich hat eine Fläche von {0,6:F2} m²", rund.flaeche); WriteLine("Der Radius ist dann {0} m", rund.radius); ReadLine(); Rechteck rasen = new Rechteck(40, 80) { bepflanzung = "Gras" }; WriteLine("Der Linie um den Rasen ist:\t{0} Meter lang", rasen.umfang); WriteLine("Es müssen hier ganze {0,6:F2} m² Fläche begossen werden", rasen.flaeche); WriteLine(rasen.bepflanzung); ReadLine(); double gesamtFlaeche = rasen.flaeche + blumenbeet.flaeche; WriteLine(gesamtFlaeche); WriteLine(rasen.flaeche + blumenbeet.flaeche); double gesamtUmfang = rasen.umfang + blumenbeet.umfang; WriteLine(gesamtUmfang); ReadLine(); // neuesRechteck = rasen + blumenbeet; // Operatoren überladen, zusätzlich definieren was macht ein + zwischen zwei Objekten von Klasse Rechteck Rechteck neuesRechteck = rasen + blumenbeet; WriteLine("Die Gesamtlinie um Rasen und Blumenbeet sind :\t{0} Meter lang", neuesRechteck.umfang); WriteLine("Die Gesamtfläche von Rasen und Blumenbeet sind :\t{0} m²", neuesRechteck.flaeche); WriteLine("{0} mal {1}", neuesRechteck.breite, neuesRechteck.laenge); ReadLine(); Kreis runder1 = new Kreis(1); WriteLine("Einmal um den Teich1 herum macht {0,6:F2} Meter gelaufen", runder1.umfang); WriteLine("Der Seerosenteich1 hat eine Fläche von {0,6:F2} m²", runder1.flaeche); WriteLine("Der Radius ist dann {0} m", runder1.radius); ReadLine(); Kreis runder2 = new Kreis(1); WriteLine("Einmal um den Teich2 herum macht {0,6:F2} Meter gelaufen", runder2.umfang); WriteLine("Der Seerosenteich2 hat eine Fläche von {0,6:F2} m²", runder2.flaeche); WriteLine("Der Radius ist dann {0} m", runder2.radius); ReadLine(); Kreis neuerKreis = runder1 + runder2; WriteLine("Doppelteich Fläche {0,6:F2} m²", neuerKreis.flaeche); WriteLine("Doppelteich Radius {0,4:F2} Meter", neuerKreis.radius); } } }
3a1a25e6d71e8cc33b57c59d17afc2d477770269
C#
bluemaplelu/Common
/Common/InMemoryCache.cs
2.78125
3
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Caching; using System.Web; namespace QHW.Common { public class InMemoryCache { public static TValue Get<TValue>(string cacheKey) where TValue : class { TValue item = MemoryCache.Default.Get(cacheKey) as TValue; return item; } public static bool Add(string cacheKey, object cacheValue, int durationInMinutes = 5) { return MemoryCache.Default.Add(cacheKey, cacheValue, DateTime.Now.AddMinutes(durationInMinutes)); } public static void Remove(string cacheKey) { MemoryCache.Default.Remove(cacheKey); } } }
54b946449ef4f474ce5d1a3a4795a8a4bf373a4f
C#
xewelus/GitCharsetConverter
/src/Converter/Ude/UTF8Prober.cs
2.59375
3
namespace Ude.Core { public sealed class UTF8Prober : CharsetProber { public UTF8Prober() { this.numOfMBChar = 0; this.codingSM = new CodingStateMachine(new UTF8SMModel()); this.Reset(); } private static readonly float ONE_CHAR_PROB = 0.50f; private readonly CodingStateMachine codingSM; private int numOfMBChar; public override string GetCharsetName() { return "UTF-8"; } public override void Reset() { this.codingSM.Reset(); this.numOfMBChar = 0; this.state = ProbingState.Detecting; } public override ProbingState HandleData(byte[] buf, int offset, int len) { int max = offset + len; for (int i = offset; i < max; i++) { int codingState = this.codingSM.NextState(buf[i]); if (codingState == SMModel.ERROR) { this.state = ProbingState.NotMe; break; } if (codingState == SMModel.ITSME) { this.state = ProbingState.FoundIt; break; } if (codingState == SMModel.START) { if (this.codingSM.CurrentCharLen >= 2) this.numOfMBChar++; } } if (this.state == ProbingState.Detecting) if (this.GetConfidence() > SHORTCUT_THRESHOLD) this.state = ProbingState.FoundIt; return this.state; } public override float GetConfidence() { float unlike = 0.99f; float confidence; if (this.numOfMBChar < 6) { for (int i = 0; i < this.numOfMBChar; i++) unlike *= ONE_CHAR_PROB; confidence = 1.0f - unlike; } else { confidence = 0.99f; } return confidence; } } }
22b45e2b112f2030dc52d1d17a47c759ed3da343
C#
biagiopietro/CompanyAPI
/Services/JobService.cs
3.078125
3
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Interfaces; using Microsoft.EntityFrameworkCore; using Models; namespace Services { public class JobService : IJobService { private readonly CompanyContext _dbContext; public JobService(CompanyContext dbContext) { _dbContext = dbContext; } public async Task AddAsync(Job job) { _dbContext.Jobs.Add(job); await _dbContext.SaveChangesAsync(); } public IEnumerable<Job> All() { return _dbContext.Jobs; } public Job Find(long id) { return _dbContext.Jobs.Find(id); } public Job Find(string name) { return _dbContext.Jobs.FirstOrDefault(x => x.Name == name); } public async Task FindAsync(long id) { await _dbContext.Jobs.FindAsync(id); } public Job FindByNameOrDefault(string name) { return _dbContext.Jobs.SingleOrDefault(x => x.Name.ToLower().Equals(name.ToLower())); } public async Task RemoveAsync(Job job) { _dbContext.Jobs.Remove(job); await _dbContext.SaveChangesAsync(); } public async Task UpdateAsync(Job job) { _dbContext.Entry(job).State = EntityState.Modified; await _dbContext.SaveChangesAsync(); } } }
007ac5110952456ceff3163c8735954d2ff64569
C#
lekhasy/NetHealth
/NetHealth.DataCollector/NetPingResultProducer.cs
2.703125
3
using System; using System.Collections.Generic; using System.Linq; namespace NetHealth.DataCollector { public class NetPingResultProducer { readonly NetPing netPing; List<NetPingEntry> pingResultBuffer = new List<NetPingEntry>(); public string HostName { get { return netPing.HostName; } } public NetPingResultProducer(string hostName, int delayTime) { netPing = new NetPing(hostName, delayTime); netPing.PingResultReceived += NetPing_PingResultReceived; netPing.NewPingStarted += NetPing_NewPingStarted; } void NetPing_NewPingStarted(object sender, NetPingStartedEventArgs e) { pingResultBuffer.Add(new NetPingEntry(e.Sequence)); } void NetPing_PingResultReceived(object sender, NetPingReceivedEventArgs e) { lock (pingResultBuffer) { var entry = pingResultBuffer.Find(etr => etr.Sequence == e.Sequence); entry.MarkAsCompleted(new NetPingResult(e.PingReply.RoundtripTime, e.PingReply.Status, e.StartedMoment)); } } public List<NetPingResult> GetLatestPingResults() { lock (pingResultBuffer) { var first = pingResultBuffer.FirstOrDefault(); var firstInValidIndex = pingResultBuffer.FindIndex(en => !en.IsCompleted); if (firstInValidIndex == -1) return new List<NetPingResult>(); // the result belong to two separate day // so, just return for the previous day, not today if (pingResultBuffer[firstInValidIndex - 1].PingResult.StartedMoment.Day != pingResultBuffer.First().PingResult.StartedMoment.Day) { firstInValidIndex = pingResultBuffer .FindIndex(en => en.PingResult.StartedMoment.Day != pingResultBuffer.First().PingResult.StartedMoment.Day); } var returnedResult = pingResultBuffer.Take(firstInValidIndex); pingResultBuffer = pingResultBuffer.Skip(firstInValidIndex).ToList(); return returnedResult.Select(p => p.PingResult).ToList(); } } public void StartProduce() { netPing.Start(); } } }
3e5efa9ccbef6072ccb5fae2c1c1efd2c893bfcb
C#
andywhitfield/EasyPlayer
/EasyPlayer/Shell/WindowPersistence.cs
2.546875
3
using System; using System.Linq; using System.Windows; using System.Xml.Linq; using Caliburn.Micro; using EasyPlayer.Persistence; namespace EasyPlayer.Shell { static class WindowPersistence { private static readonly ILog log = LogManager.GetLog(typeof(WindowPersistence)); private const string WindowSettingsFilename = "window-settings.xml"; public static void RestoreWindowState(this Bootstrapper bootstrapper, IPersistence persistence) { if (!bootstrapper.Application.IsRunningOutOfBrowser) return; var mainWindow = bootstrapper.Application.MainWindow; var windowInfo = persistence.ReadTextFile(WindowSettingsFilename); if (string.IsNullOrWhiteSpace(windowInfo)) return; try { var posAndSize = XDocument.Parse(windowInfo).Descendants("MainWindow").FirstOrDefault(); if (posAndSize == null) return; if (bool.Parse(posAndSize.Attribute("IsMaximized").Value)) mainWindow.WindowState = WindowState.Maximized; else { mainWindow.Width = int.Parse(posAndSize.Attribute("Width").Value); mainWindow.Height = int.Parse(posAndSize.Attribute("Height").Value); mainWindow.Top = int.Parse(posAndSize.Attribute("Top").Value); mainWindow.Left = int.Parse(posAndSize.Attribute("Left").Value); } } catch (Exception ex) { log.Warn("Error setting window position from saved settings! {0}", ex); persistence.DeleteFile(WindowSettingsFilename); } } public static void SaveWindowState(this Bootstrapper bootstrapper, IPersistence persistence) { if (!bootstrapper.Application.IsRunningOutOfBrowser) return; var mainWindow = bootstrapper.Application.MainWindow; var xml = new XDocument( new XElement("WindowInfo", new XElement("MainWindow", new XAttribute("IsMaximized", mainWindow.WindowState == WindowState.Maximized), new XAttribute("Width", mainWindow.Width), new XAttribute("Height", mainWindow.Height), new XAttribute("Top", mainWindow.Top), new XAttribute("Left", mainWindow.Left) ) ) ); persistence.WriteTextFile(WindowSettingsFilename, xml.ToString(SaveOptions.DisableFormatting)); } } }
e35f4c5d41d2f9a96d05fde00fe9896baa0a7f9a
C#
Tinsae/.NET-Projects
/DieRollRandom.cs
3.28125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp9 { class Program { static void Main(string[] args) { Random rnd = new Random(); int die1 = 0; int die2 = 0; int[] frequency = new int[11]; int sum = 0; for (int i = 0; i < 36000; i++) { die1 = rnd.Next(1, 6); die2 = rnd.Next(1, 6); sum = die1 + die2; frequency[sum - 2] += 1; } for (int i = 0; i < frequency.Length; i++) { Console.WriteLine(frequency[i]); } Console.ReadKey(); } } }
b6550e7e72e286e56e175e312225d39fc90c3282
C#
zoro83/HomeWork
/SecondStage.OOP/ConsoleApp2test/Program.cs
3.9375
4
using System; namespace Events { class Program { public delegate double ResultOfNumbers(double x, double y); class Calculator { public event ResultOfNumbers NumbersOf; public void EventInvoke(double x, double y) { NumbersOf.Invoke(x, y); } public double YNumber(double y) { try { Console.WriteLine("Enter Y number"); y = double.Parse(Console.ReadLine()); } catch (FormatException) { Console.WriteLine("Please Enter Number!"); } return y; } public double XNumber(double x) { try { Console.WriteLine("Enter X number"); x = double.Parse(Console.ReadLine()); } catch (FormatException) { Console.WriteLine("Please Enter Number!"); } return x; } } static void Main(string[] args) { Calculator calculator = new Calculator(); double x = 0.0; double y = 0.0; x = calculator.XNumber(x); y = calculator.YNumber(y); Console.WriteLine("Please Chose An Operation wich one you wont to do: +,-,*,/ "); string Oper = Console.ReadLine(); switch (Oper) { case "-": calculator.NumbersOf += Sum; calculator.EventInvoke(x, y); break; case "*": calculator.NumbersOf += Mult; calculator.EventInvoke(x, y); break; case "/": calculator.NumbersOf += Divis; calculator.EventInvoke(x, y); break; case "+": calculator.NumbersOf += Add; calculator.EventInvoke(x, y); break; } Console.ReadKey(); } public static double Add(double x, double y) { double res = x + y; Console.WriteLine("Result of Operation: " + res); return res; } public static double Sum(double x, double y) { double res = x - y; Console.WriteLine("Result of Operation: " + res); return res; } public static double Mult(double x, double y) { double res = x * y; Console.WriteLine("Result of Operation: " + res); return res; } public static double Divis(double x, double y) { if (y != 0) { double res = x / y; Console.WriteLine("Result of Operation: " + res); return res; } else return 0; } public static double SmallistOddNumber(double x, double y) { int i; for (i = 1; i < x; i++) { if (i % 3 == 0) { Console.WriteLine(i); return i; break; } } return i; } } }
0eb5541dc99f44b4f3af9eaa8acfe73879843b1b
C#
Malcolmnixon/Chompies
/Shared/Chompies.Shared.Tests/SerializeWorld.cs
2.953125
3
using System; using System.Collections.Generic; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using Newtonsoft.Json; namespace Chompies.Shared.Tests { [TestClass] public class SerializeWorld { [TestMethod] public void SerializeDeserializeTest() { var world = new World(); world.Populate(20, 20, 8); // The players are Bob and Joe world.Players = new List<string>{ "Bob", "Joe" }; // Bob takes over a zombie world.Actors[0].Player = "Bob"; // Joe joins as a new hero world.Actors.Add(new Hero {Id = Guid.NewGuid(), Position = new Vec(10, 10), Orientation = 1.2f, Velocity = new Vec(-1, -1), Player = "Joe"}); var text = JsonConvert.SerializeObject( world, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto }); var world2 = JsonConvert.DeserializeObject<World>( text, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto }); Assert.AreEqual(world.Scenery.Count, world2.Scenery.Count); Assert.AreEqual(world.Actors.Count, world2.Actors.Count); Assert.AreEqual(world.Players.Count, world2.Players.Count); Assert.IsTrue(world2.Players.Contains("Bob")); Assert.IsTrue(world2.Players.Contains("Joe")); Assert.AreEqual(1, world2.Actors.Count(a => a.Player == "Bob")); Assert.AreEqual(1, world2.Actors.Count(a => a.Player == "Joe")); } } }
b2a99dcfd1a0f462d6bb95f2d102bbcb62fd71d8
C#
thmihnea/cs-utils
/Collection.cs
3.390625
3
using System; using System.Collections.Generic; namespace Collections { interface Collection<E> { int getSize(); bool isEmpty(); bool contains(object obj); E[] toArray(); bool add(E element); bool remove(object obj); bool containsAll<T>(Collection<T> collection) { bool contains_all = false; foreach(T t in collection.toArray()) { if (!this.contains(t)) contains_all = true; } return contains_all; } bool addAll<T>(Collection<T> collection) where T : E { foreach(T t in collection.toArray()) { this.add(t); } return true; } bool removeAll<T>(Collection<T> collection) { foreach(T t in collection.toArray()) { this.remove(t); } return true; } void clear(); } interface List<E> : Collection<E> { E get(int index); void set(int index, E element); void add(int index, E element); bool remove(int index); int indexOf(object obj); int lastIndexOf(object obj); List<E> getSubList(int fromIndex, int toIndex); } }