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
a9a20cc608ab3c42f1724cc798b8bd39609a262e
C#
shakuu/Exams
/DBEXAM/Databases-and-sql-description/DbExam-10/DbExam/DbExam.Data.JsonImporter/Converters/SuperHeroConverter.cs
2.75
3
using System.Collections.Generic; using DbExam.Data.JsonImporter.Converters.Contracts; using DbExam.Data.JsonImporter.JsonModels; using DbExam.Models; using System; using System.Linq; namespace DbExam.Data.JsonImporter.Converters { /*{ "name": "Batman", "secretIdentity": "Bruce Wayne", "city": { "name": "Gotham", "country": "USA", "planet": "Earth" }, "alignment": "good", "story": "After losing his parents...", "powers": [ "Utility belt", "Intelligence", "Martial arts" ], "fractions": [ "Justice League", "The Bat Family" ] },*/ public class SuperHeroConverter : ISuperHeroConverter { public IEnumerable<Superhero> ConvertToSqlSuperhero(IEnumerable<JsonSuperhero> jsonSuperheros) { var result = new List<Superhero>(); foreach (var jsonSuperhero in jsonSuperheros) { var superhero = new Superhero(); superhero.Name = jsonSuperhero.name; superhero.SecretIdentity = jsonSuperhero.secretIdentity; superhero.Story = jsonSuperhero.story; jsonSuperhero.alignment = jsonSuperhero.alignment[0].ToString().ToUpper() + jsonSuperhero.alignment.Substring(1); superhero.AlignmentType = (AlignmentType)Enum.Parse(typeof(AlignmentType), jsonSuperhero.alignment); superhero.City = this.ResolveCity(jsonSuperhero.city); superhero.Powers = this.ResovlePowers(jsonSuperhero.powers); superhero.Fractions = this.ResolveFractions(jsonSuperhero.fractions); if (superhero.Fractions != null) { foreach (var freaction in superhero.Fractions) { freaction.AlignmentType = superhero.AlignmentType; } } result.Add(superhero); } return result; } private ICollection<Fraction> ResolveFractions(IEnumerable<string> fractionNames) { if (fractionNames == null) { return null; } var powers = new List<Fraction>(); foreach (var name in fractionNames) { var nextFraction = new Fraction() { Name = name }; powers.Add(nextFraction); } return powers; } private ICollection<Power> ResovlePowers(IEnumerable<string> powersNames) { if (powersNames == null) { return null; } var powers = new List<Power>(); foreach (var name in powersNames) { var nextPower = new Power() { Name = name }; powers.Add(nextPower); } return powers; } private City ResolveCity(JsonCity jsonCity) { var planet = new Planet() { Name = jsonCity.planet }; var country = new Country() { Name = jsonCity.country, Planet = planet }; var city = new City() { Name = jsonCity.name, Country = country }; return city; } } }
1470808e28971e01fc6b606b934ed623826f782e
C#
yogirajshakya/SMS
/iMailerData/code/iMailer/Emailer/MailMergeLib/PlainBodyBuilder.cs
2.65625
3
using System.Net.Mail; using System.Net.Mime; namespace Infolancers.iMailer.Emailer { internal class PlainBodyBuilder : BodyBuilderBase { private readonly string _plainText; public PlainBodyBuilder(string plainText) { _plainText = plainText; } /// <summary> /// Gets the ready made body part for a mail message. /// </summary> public override AlternateView Body { get { AlternateView plainBody = AlternateView.CreateAlternateViewFromString(Bugfixer.LimitLineLengthRfc2822(_plainText), CharacterEncoding, MediaTypeNames.Text.Plain); plainBody.TransferEncoding = Tools.IsSevenBit(plainBody.ContentStream) ? TransferEncoding.SevenBit : TextTransferEncoding != TransferEncoding.SevenBit ? TextTransferEncoding : TransferEncoding.QuotedPrintable; plainBody.ContentType.CharSet = CharacterEncoding.HeaderName; // RFC 2045 Section 5.1 - http://www.ietf.org return plainBody; } } /// <summary> /// Get the text representation of the source document /// </summary> public override string DocText { get { return _plainText; } } } }
f814f79806665e699e76c48b68efbf6c2724ba12
C#
NikiStanchev/SoftUni
/Algorithms/AlgorithmsExams/StarsInTheCube/Program.cs
3.46875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace StarsInTheCube { class Program { static char[,,] matrix; static SortedDictionary<char, int> cubes = new SortedDictionary<char, int>(); static int count; static void Main(string[] args) { int n = int.Parse(Console.ReadLine()); matrix = new char[n, n, n]; count = 0; for(int i = 0; i < n; i++) { var line = Console.ReadLine().Split('|'); for(int k = 0; k < n; k++) { for(int j = 0; j < n; j++) { var secondLine = line[k].Trim().Split(); matrix[i, k, j] = Char.Parse(secondLine[j]); } } } for(int x = 1; x < n - 1; x++) { for(int y = 1; y < n - 1; y++) { for(int z =1; z < n - 1; z++) { if (!cubes.ContainsKey(matrix[x, y, z])) { cubes.Add(matrix[x, y, z], 0); } if(matrix[x, y, z] == matrix[x, y, z + 1] && matrix[x, y, z] == matrix[x, y, z - 1] && matrix[x, y, z] == matrix[x, y + 1, z] && matrix[x, y, z] == matrix[x, y - 1, z] && matrix[x, y, z] == matrix[x + 1, y, z] && matrix[x, y, z] == matrix[x - 1, y, z]) { cubes[matrix[x, y, z]]++; count++; } } } } Console.WriteLine(count); foreach(var el in cubes) { if(el.Value > 0) { Console.WriteLine($"{el.Key} -> {el.Value}"); } } } } }
9c31729cab6d590e177561d7f90506d27ee26882
C#
fraga/randomizer
/Randomizer.Tests/RandomOrgV1Test.cs
2.515625
3
using System; using Microsoft.VisualStudio.TestPlatform.UnitTestFramework; using Randomizer.Utils; using System.Threading.Tasks; using System.Text.RegularExpressions; namespace Randomizer.Tests { [TestClass] public class RandomOrgV1Test { [TestMethod] public void TestConstructor() { Assert.IsNotNull(new RandomOrgV1()); } [TestMethod] public void TestBaseAddress() { Assert.AreEqual("http://random.org", new RandomOrgV1().GetRandomOrgAddress()); } [TestMethod] public void TestRequestAddressShouldNotBeNull() { var randomOrg = new RandomOrgV1(); Assert.IsNotNull(randomOrg.RequestAddress); } [TestMethod] public void TestFormatBase() { var randomOrg = new RandomOrgV1(); Assert.AreEqual("base2", randomOrg.FormatBase(NumericSystemEnum.Binary)); Assert.AreEqual("base8", randomOrg.FormatBase(NumericSystemEnum.Octal)); Assert.AreEqual("base10", randomOrg.FormatBase(NumericSystemEnum.Decimal)); Assert.AreEqual("base16", randomOrg.FormatBase(NumericSystemEnum.Hexa)); } [TestMethod] public void TestFluentIntegersAddress() { var randomOrg = new RandomOrgV1(); Assert.AreEqual("http://random.org/integers?num=1&min=1&max=100&col=1&base=10&format=plain&rnd=new", randomOrg.IntegerRequest(1, 100).RequestAddress.AbsoluteUri); } [TestMethod] public void TestFormatQueryString() { var randomOrg = new RandomOrgV1(); Assert.AreEqual("http://random.org/?num=1&min=1&max=6&col=1&base=10&format=plain&rnd=new", randomOrg.FormatQueryString(1, 6).AbsoluteUri); Assert.AreEqual("http://random.org/?num=1&min=1&max=60&col=1&base=10&format=plain&rnd=new", randomOrg.FormatQueryString(1, 60).AbsoluteUri); Assert.AreEqual("http://random.org/?num=1&min=10&max=60&col=1&base=10&format=plain&rnd=new", randomOrg.FormatQueryString(10, 60).AbsoluteUri); Assert.AreEqual("http://random.org/?num=1&min=-100&max=-60&col=1&base=10&format=plain&rnd=new", randomOrg.FormatQueryString(-100, -60).AbsoluteUri); } [TestMethod] public void TestMinGreaterThanMaxException() { var randomOrg = new RandomOrgV1(); Assert.ThrowsException<RandoOrgMinGreaterThanMaxException>(() => randomOrg.IntegerRequest(6, 1)); Assert.ThrowsException<RandoOrgMinGreaterThanMaxException>(() => randomOrg.IntegerRequest(-60, -100)); } [TestMethod] public void TestStripResult() { var randomOrg = new RandomOrgV1(); Assert.AreEqual("result", randomOrg.StripResult("result\r\n")); } public async Task<string> CallRequestAsync() { var randomOrg = new RandomOrgV1(); var result = await randomOrg.IntegerRequest(1, 100).Request(); return result; } } }
2e92ba41569a9b3fc94bfdf43c393565b944b31d
C#
Alejandro10-28/T02-.RodriguezSolisDanielAlejandro
/IOperacion.cs
3.25
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Calculadora1._2 { //Se crea la interfaz , cabe destacar que una interfaz ya es publica por eso no necesita el "public" interface IOperacion { //Se encapsulan las variables normalmente double Numero1 { get; set; } double Numero2 { get; set; } //Los metodos se crean pero no se inician aqui sino en la clase donde se vayan a utilizar. double Sumar(double N1, double N2); double Restar(double N1, double N2); double Dividir(double N1,double N2); double Multiplicar(double N1,double N2); } }
d64ed35cfa6abc20c4dd693d97082eb47b941ab6
C#
venkatpselvam1/chess
/ChessGameBusiness/Piece/Piece.cs
3.03125
3
using GameComponent.Enum; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GameComponent.Piece { public abstract class Piece { protected Board board { get; set;} [JsonConverter(typeof(StringEnumConverter))] public Colour Colour { get; protected set; } public Position CurrentPosition { get; protected set; } public string Name { get; protected set; } public abstract List<Position> ValidMoves(); public virtual void MakeMove(int x, int y) { this.CurrentPosition.X = x; this.CurrentPosition.Y = y; } public void FilterOutOfBoardMoves(List<Position> positions) { #region removing out of box moves positions.RemoveAll(x => (x.X > 8 || x.Y > 8 || x.X < 1 || x.Y < 1)); #endregion } public bool AddIfNotOurPiece(List<Position> validMoves, int x, int y) { if (!board.IsAnyPieceAvailable(x, y, this.Colour)) { validMoves.Add(new Position(x, y)); } return board.IsAnyPieceAvailable(x, y); } } }
e3a28cad05de5a1c978486df87e38efe1f9336f9
C#
rickinator9/SimTecPracticums
/SIMTEC3D Prac1/SIMTEC3D Prac1/Scripts/Flipper.cs
2.515625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; namespace SIMTEC3D_Prac1.Scripts { class Flipper : GameObject { protected Plane[] surfaces; private Vector3 pivot; private float rotation; private float maxAngle; private float rotationASecond; private Ball ball; public Flipper(Vector3 position, Vector3 pivot, float maxAngle, float rotationASecond, Vector3 rotation, float scale, Ball ball, GraphicsDevice device): base() { this.pivot = position + pivot * scale; this.rotation = 0; this.maxAngle = maxAngle; this.rotationASecond = rotationASecond; this.ball = ball; surfaces = new Plane[10]; //The box Vector3 botPosition = new Vector3(position.X, position.Y - scale, position.Z); Vector3 botRotation = new Vector3(rotation.X + (float)Math.PI, rotation.Y, rotation.Z); surfaces[0] = new Plane(botPosition, botRotation, scale, device); Vector3 botPosition2 = new Vector3(position.X + 2 * scale, position.Y - scale, position.Z); surfaces[1] = new Plane(botPosition2, botRotation, scale, device); Vector3 topPosition = new Vector3(position.X, position.Y + scale, position.Z); Vector3 topRotation = rotation; surfaces[2] = new Plane(topPosition, topRotation, scale, device); Vector3 topPosition2 = new Vector3(position.X + 2 * scale, position.Y + scale, position.Z); surfaces[3] = new Plane(topPosition2, topRotation, scale, device); Vector3 rightPosition = new Vector3(position.X + 3 * scale, position.Y, position.Z); Vector3 rightRotation = new Vector3(rotation.X, rotation.Y, rotation.Z - 0.5f*(float)Math.PI); surfaces[4] = new Plane(rightPosition, rightRotation, scale, device); Vector3 leftPosition = new Vector3(position.X - scale, position.Y, position.Z); Vector3 leftRotation = new Vector3(rotation.X, rotation.Y, rotation.Z + 0.5f * (float)Math.PI); surfaces[5] = new Plane(leftPosition, leftRotation, scale, device); Vector3 backPosition = new Vector3(position.X, position.Y, position.Z + scale); Vector3 backRotation = new Vector3(rotation.X + 0.5f * (float)Math.PI, rotation.Y, rotation.Z); surfaces[6] = new Plane(backPosition, backRotation, scale, device); Vector3 backPosition2 = new Vector3(position.X + 2 * scale, position.Y, position.Z + scale); surfaces[7] = new Plane(backPosition2, backRotation, scale, device); Vector3 frontPosition = new Vector3(position.X, position.Y, position.Z - scale); Vector3 frontRotation = new Vector3(rotation.X - 0.5f * (float)Math.PI, rotation.Y, rotation.Z); surfaces[8] = new Plane(frontPosition, frontRotation, scale, device); Vector3 front2Position = new Vector3(position.X + 2 * scale, position.Y, position.Z - scale); ; surfaces[9] = new Plane(front2Position, frontRotation, scale, device); } private int sign(float value) { return value < 0 ? -1 : 1; } private void rotate(float deltaTime) { //Calculate the rotation in this frame float rotation = sign(rotationASecond) * Math.Min(Math.Abs(rotationASecond) * deltaTime, maxAngle - Math.Abs(this.rotation)); Matrix rotationMatrix = Matrix.CreateRotationY(rotation); this.rotation += rotation; foreach (Plane plane in surfaces) { Vector3 oldDistanceVector = plane.getDistanceTillPoint(ball.getPivotWithPlane(plane.normal)); float oldDistance = oldDistanceVector.X + oldDistanceVector.Y + oldDistanceVector.Z; //Rotate a plane plane.translate(Matrix.CreateTranslation(-pivot)); plane.rotate(rotationMatrix, new Vector3(0, rotation, 0)); plane.translate(Matrix.CreateTranslation(pivot)); Vector3 newDistanceVector = plane.getDistanceTillPoint(ball.getPivotWithPlane(plane.normal)); float newDistance = newDistanceVector.X + newDistanceVector.Y + newDistanceVector.Z; if (Math.Sign(oldDistance) != Math.Sign(newDistance)) //Check if the ball is on the other side of the frame after this frame { Vector3 pivotWithPlane = plane.getPivotWithLine(ball.position, -plane.normal); Vector2 distanceTillBoundry = plane.getDistanceTillBoundry(pivotWithPlane); if (distanceTillBoundry.Length() == 0) //Check if the pivot with the plane is inside the boundries of the plane { Vector3 ballPosition = ball.position; //Rotate the bal around the turning point of the flipper ballPosition = Plane.vectorMatrixMultiplication(ballPosition, Matrix.CreateTranslation(-pivot)); ballPosition = Plane.vectorMatrixMultiplication(ballPosition, Matrix.CreateRotationY(rotation)); ballPosition = Plane.vectorMatrixMultiplication(ballPosition, Matrix.CreateTranslation(pivot)); //Lift the bal from teh ground, to prefent it the move past the ground plane ballPosition.Y += 0.2f; //Move the bal away from the plane ball.accelerate(plane.normal, ballPosition); } } } } private void rotateBack(float deltaTime) { float rotation = sign(rotationASecond) * Math.Max(-Math.Abs(rotationASecond) * deltaTime, -Math.Abs(this.rotation))/2; this.rotation += rotation; Matrix rotationMatrix = Matrix.CreateRotationY(rotation); foreach (Plane plane in surfaces) { plane.translate(Matrix.CreateTranslation(-pivot)); plane.rotate(rotationMatrix, new Vector3(0, rotation, 0)); plane.translate(Matrix.CreateTranslation(pivot)); } } public override void LoadContent(ContentManager content) { foreach (Plane plane in surfaces) { plane.LoadContent(content); } } public Plane[] planes { get { return surfaces; } } public override void update(float deltaTime) { KeyboardState keyboardState = Keyboard.GetState(); if (rotationASecond < 0 && keyboardState.IsKeyDown(Keys.Left) || rotationASecond > 0 && keyboardState.IsKeyDown(Keys.Right)) { rotate(deltaTime); } else { rotateBack(deltaTime); } foreach (Plane plane in surfaces) { plane.update(deltaTime); } } public override void draw(Matrix viewMatrix) { foreach (Plane plane in surfaces) { plane.draw(viewMatrix); } } } }
49827b2767b834edbcb82ccd88585c0d6594fe9e
C#
leomag/code_example_in_c_sharp
/code_example_in_c_sharp/Program.cs
2.875
3
using System; namespace code_example_in_c_sharp { class MainTeacher { public static void Main(string[] args) { Teacher assistant = new Teacher("Илья", "Исаев", "тестирование программного обеспечения", 34000); Console.WriteLine(assistant.GetInfoFull()); Console.WriteLine(assistant.GetInfo()); } } }
63f00eb16d1622406ff3c9cc8fb7ae1c2896ac19
C#
SheikhULAB/TicTacToeWindowsForm
/Form1.cs
2.9375
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 TicTac { public partial class TTT : Form { bool turn = true; int turn_count = 0; public TTT() { InitializeComponent(); } private void Button_click(object sender, EventArgs e) { Button button = (Button)sender; if (turn) { button.Text = "X"; } else { button.Text = "0"; } turn = !turn; button.Enabled = false; turn_count++; check_win(); } private void check_win() { bool is_winner = false; // horizontally if((button1.Text == button2.Text) && (button2.Text == button3.Text) && (!button1.Enabled && !button2.Enabled && !button3.Enabled)) { is_winner = true; } else if ((button4.Text == button5.Text) && (button5.Text == button6.Text) && (!button4.Enabled && !button5.Enabled && !button6.Enabled)) { is_winner = true; } else if ((button7.Text == button8.Text) && (button8.Text == button9.Text) && (!button7.Enabled && !button8.Enabled && !button9.Enabled)) { is_winner = true; } //vertically if ((button1.Text == button4.Text) && (button4.Text == button7.Text) && (!button1.Enabled && !button4.Enabled && !button7.Enabled)) { is_winner = true; } else if ((button2.Text == button5.Text) && (button5.Text == button8.Text) && (!button2.Enabled && !button5.Enabled && !button8.Enabled)) { is_winner = true; } else if ((button3.Text == button6.Text) && (button6.Text == button9.Text) && (!button3.Enabled && !button6.Enabled && !button9.Enabled)) { is_winner = true; } //diagonally if ((button1.Text == button5.Text) && (button5.Text == button9.Text) && (!button1.Enabled && !button5.Enabled && !button9.Enabled)) { is_winner = true; } else if ((button3.Text == button5.Text) && (button5.Text == button7.Text) && (!button3.Enabled && !button5.Enabled && !button7.Enabled)) { is_winner = true; } if (is_winner) { disable_button(); String winner = ""; if (turn) { winner = "0"; } else { winner = "X"; } MessageBox.Show(winner + " Wins"); } else { if(turn_count == 9) { MessageBox.Show("Game drawn"); } } } private void disable_button() { foreach(Control C in Controls) { Button button = (Button)C; button.Enabled = false; } } } }
82867f2a285bbaded61b7dcf10f658b0c608b32a
C#
AmirRiad/Singleton
/Lock/Lazy.cs
2.890625
3
using System; namespace Singleton.Lazy { public class Logger: interfaceForLogger.ILogger { private static readonly Lazy<Logger> _instance = new Lazy<Logger>(() => new Logger()); public static Logger Instance { get { return _instance.Value; } } public void LogError(string msg) { System.Console.WriteLine(msg); } } }
71f91bc5b02bf38649fe2f96f1b500a45d2fdc41
C#
radtek/fileshare
/r_SaveAsTest/NotepadSaveAsTests_Intigration/NotepadSaveAsImitationTestsIntegration.cs
2.734375
3
using NUnit.Framework; using NotepadSaveAs; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using System.Windows.Forms; namespace ConsoleApplication1.Tests { [TestFixture()] public class NotepadSaveAsImitationTests_integration { NotepadSaveAsImitation notepad; string path_correct, path_directory_nofile, path_empty, path_null, path_SaveAs; byte[] text_; [OneTimeSetUp()] public void Initialization() { path_correct = @"C:\TEMP\test.txt"; path_SaveAs = @"C:\TEMP\testSavedAs.txt"; path_directory_nofile = @"C:\TEMP\"; path_empty = string.Empty; path_null = null; text_ = Encoding.ASCII.GetBytes(@"C:\TEMP\"); notepad = new NotepadSaveAsImitation(); //remove test file from disk before test if (File.Exists(path_correct)) { File.Delete(path_correct); } } [TearDown] public void TearDown() { //remove test file from disk after test if (File.Exists(path_correct)) { File.Delete(path_correct); } if (File.Exists(path_SaveAs)) { File.Delete(path_SaveAs); } } [Test()] public void CheckDialogResultTest_FlaseForCancel() { Assert.IsFalse( notepad.CheckDialogResult(DialogResult.Cancel)); } [Test()] public void GetPathFromDialogTest_TrueForOk() { Assert.IsTrue(notepad.CheckDialogResult(DialogResult.OK)); } [Test()] public void SaveToPathTest_CorrectPath_SavesToDiskCheck() { notepad.SaveToPath(path_correct, text_); if (File.Exists(path_correct)) { Assert.Pass(); } Assert.Fail(); } [Test()] public void SaveToPathTest_EmptyFile_ThrowsIOException() { try { notepad.SaveToPath(path_directory_nofile, text_); } catch (IOException e) { Assert.Pass(); } Assert.Fail(); } [Test()] public void SaveToPathTest_EmptyPath_ThrowsEmptyException() { try { notepad.SaveToPath(path_empty, text_); } catch (EmptyFilepathException e) { Assert.Pass(); } Assert.Fail(); } [Test()] public void SaveToPathTest_NullPath_ThrowsEmptyException() { try { notepad.SaveToPath(path_null, text_); } catch (EmptyFilepathException e) { Assert.Pass(); } Assert.Fail(); } } }
01be59932a54206adb59a41d3fb2f10788e7abe9
C#
HaykSargsyan13/Asp.net-MVC5
/Homework7/Homework7/Models/Order.cs
2.625
3
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace Homework7.Models { public class Order { [Required(ErrorMessage = "Please Enter Name")] public string Name { get; set; } [Required(ErrorMessage = "Please Enter Address")] public string Address { get; set; } [Required(ErrorMessage = "Plesae enter Email")] [RegularExpression(@"(?i)\b[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b", ErrorMessage = "Email is not in Correct format")] public string Email { get; set; } [CorrectDate(ErrorMessage = "Enter correct Date")] public DateTime Data { get; set; } [MustToBeTrue(ErrorMessage = "You didn't Accept Terms")] public bool TermsAccepted { get; set; } } }
97632d5c936bf0b683999fee750f7007d8f8fc0c
C#
reyou/Ggg.GitHub
/apps/apps-web/app-dataflow-block/GggDataflowBlockSpecifyTaskSchedulerWinForms/Form1.cs
3.0625
3
using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Threading.Tasks.Dataflow; using System.Windows.Forms; namespace GggDataflowBlockSpecifyTaskSchedulerWinForms { public partial class Form1 : Form { // Broadcasts values to an ActionBlock<int> object that is associated // with each check box. /*BroadcastBlock<T> Class Provides a buffer for storing at most one element at time, overwriting each message with the next as it arrives*/ BroadcastBlock<int> broadcaster = new BroadcastBlock<int>(null); public Form1() { InitializeComponent(); /*In the Form1 constructor, after the call to InitializeComponent, create an ActionBlock<TInput> object that toggles the state of CheckBox objects.*/ // Create an ActionBlock<CheckBox> object that toggles the state // of CheckBox objects. // Specifying the current synchronization context enables the // action to run on the user-interface thread. ActionBlock<CheckBox> toggleCheckBox = new ActionBlock<CheckBox>(checkbox => { checkbox.Checked = !checkbox.Checked; }, new ExecutionDataflowBlockOptions() { TaskScheduler = TaskScheduler.FromCurrentSynchronizationContext() }); // Create a ConcurrentExclusiveSchedulerPair object. // Readers will run on the concurrent part of the scheduler pair. // The writer will run on the exclusive part of the scheduler pair. /*ConcurrentExclusiveSchedulerPair Class Provides task schedulers that coordinate to execute tasks while ensuring that concurrent tasks may run concurrently and exclusive tasks never do*/ ConcurrentExclusiveSchedulerPair taskSchedulerPair = new ConcurrentExclusiveSchedulerPair(); // Create an ActionBlock<int> object for each reader CheckBox object. // Each ActionBlock<int> object represents an action that can read // from a resource in parallel to other readers. // Specifying the concurrent part of the scheduler pair enables the // reader to run in parallel to other actions that are managed by // that scheduler. IEnumerable<ActionBlock<int>> readerActions = from checkbox in new[] { checkBox1, checkBox2, checkBox3, checkBox4 } select new ActionBlock<int>(milliseconds => { // Toggle the check box to the checked state. toggleCheckBox.Post(checkbox); // Perform the read action. For demostration, suspend the current // thread to simulate a length read operation. Thread.Sleep(milliseconds); // Toggle the check box to the unchecked state. toggleCheckBox.Post(checkbox); }, new ExecutionDataflowBlockOptions() { TaskScheduler = taskSchedulerPair.ConcurrentScheduler }); // Create an ActionBlock<int> object for the writer CheckBox object. // This ActionBlock<int> object represents an action that writes to // a resource, but cannot run in parallel to readers. // Specifying the exclusive part of the scheduler pair enables the // writer to run in exclusively with respect to other actions that are // managed by the scheduler pair. ActionBlock<int> writerAction = new ActionBlock<int>(milliseconds => { // Toggle the check box to the checked state. toggleCheckBox.Post(checkBox4); // Perform the write action. For demonstration, suspend the current // thread to simulate a lengthy write operation. Thread.Sleep(milliseconds); // Toggle the check box to the unchecked state. toggleCheckBox.Post(checkBox4); }, new ExecutionDataflowBlockOptions() { TaskScheduler = taskSchedulerPair.ExclusiveScheduler }); // Link the broadcaster to each reader and writer block. // The BroadcastBlock<T> class propagates values that it // receives to all connected targets. foreach (ActionBlock<int> readerAction in readerActions) { broadcaster.LinkTo(readerAction); } broadcaster.LinkTo(writerAction); timer1.Start(); } private void timer1_Tick(object sender, System.EventArgs e) { // Post a value to the broadcaster. The broadcaster // sends this message to each target. broadcaster.Post(1000); } } }
081224c5fe4bc13cac9c0321b7403b81ebc3f7b3
C#
Saroj404/FreeCodeCamp
/Freecodecamp/freecodecamp.cs
3.140625
3
 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Freecodecamp { class Codecamp { static void Main(string[] args) { #region functions //Madlib(); // Array(); //SayHi(); //PassPara("Saroj Shrestha",24); //Console.WriteLine(Cube(5)); //ifexp(); //Console.WriteLine(GetMax(6,9)); /*int num1, num2, num3; Console.Write("Enter first number:"); num1 = Convert.ToInt32(Console.ReadLine()); Console.Write("Enter second number:"); num2 = Convert.ToInt32(Console.ReadLine()); These are for same Console.Write("Enter third number:"); num3 = Convert.ToInt32(Console.ReadLine()); Console.WriteLine(GetMaxx(num1,num2,num3));*/ /* Console.Write("Enter day number:"); int x = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Today is: "+GetDay(x));*/ //This is switch example // While_Loop(); //Mul2(); // Guess(); //for_loop(); //for_array(); //Console.WriteLine("The output is: "+GetPow(4,2)); //this is exponent example // exp0f2darr(); //exceptionhandling(); //MyMethod(child1:"saroj",child2:"sanjay",child3:"sam"); //MyMethod2("child2"); /*int z = Overload(5, 6); //These are functions for overloading example double c = Overload(7, 8); Console.WriteLine("Int: " + z); Console.WriteLine("Double: " + c);*/ #endregion //Book(); //BookConstr(); Movie(); Console.ReadLine(); } static void Madlib() { Console.WriteLine("Enter color"); string color = Console.ReadLine(); Console.WriteLine("Enter noun"); string noun = Console.ReadLine(); Console.WriteLine("Enter celebrity name"); string celeb = Console.ReadLine(); Console.WriteLine("Roses are " + color); Console.WriteLine(noun + " are blue"); Console.WriteLine("i love " + celeb); Console.ReadLine(); } static void Array() { string[] friends = new string[5]; friends[0] = "Saroj"; friends[1] = "sanjay"; Console.WriteLine(friends[1]); Console.ReadLine(); //These are array examples. } static void SayHi() { Console.WriteLine("Hello"); } static void PassPara(string name,int age) { Console.WriteLine("Hello " + name + " you are " + age+" years old"); } static int Cube(int num) { int cube = num * num * num; return cube; } static void ifexp() { bool isMale = true; bool isTall = false; if(isMale && isTall) { Console.WriteLine("You are tall male"); } else if(isMale && !isTall) { Console.WriteLine("You are short male"); } else if(!isMale && isTall) { Console.WriteLine("You are tall female"); } else { Console.WriteLine("You are short female"); } } static int GetMax(int num1,int num2) { int result; if(num1>=num2) { result = num1; } else { result = num2; } return result; } static int GetMaxx(int num1,int num2,int num3) { int Maxx; if (num1>=num2 && num1>=num3) { Maxx = num1; } else if (num2 >= num1 && num2 >= num3) { Maxx = num2; } else { Maxx = num3; } return Maxx; } static string GetDay(int num) { string Dayname; switch(num) { case 0: Dayname = "Sunday"; break; case 1: Dayname = "Monday"; break; case 2: Dayname = "Tuesday"; break; case 3: Dayname = "Wednesday"; break; default: Dayname="Invalid number"; break; } return Dayname; } static void While_Loop() { int index = 1; while(index<=5) { Console.WriteLine(index); index++; } /*do { Console.WriteLine(index); index++; } while (index <= 5); */ } static void Mul2() { int index = 2; while(index <= 20) { if (index % 2 == 0) { Console.WriteLine(index); } index++; } } static void Guess() { Console.WriteLine("Hint: Its an animal"); string secret = "cat"; string guess=""; int guesscount = 0; int guesslimit = 5; bool outofguesses = false; while(guess !=secret && outofguesses==false) //!outofguesses and outofguesses=false is same { if (guesscount < guesslimit) { Console.Write("Enter your guess:"); guess = Console.ReadLine(); guesscount++; } else { outofguesses = true; } } if (!outofguesses) { Console.WriteLine("Congratulations! You guessed correctly."); } else { Console.WriteLine("Sorry! You lost the game."); } Console.ReadLine(); } static void for_loop() { int i = 1; for(i=1;i<=5;i++) { Console.WriteLine(i); } } static void for_array() { int i; int[] arrnum = { 1, 4, 5, 2, 6, 8, 10 }; for(i=0;i<arrnum.Length;i++) { Console.WriteLine(arrnum[i]); } } static int GetPow(int Basenum,int Pownum) { int result = 1; for(int i=0;i<Pownum;i++) { result = result *Basenum; } return result; } static void exp0f2darr() { int[,] number = { {1,2 }, { 2,2}, {3,3 } }; Console.WriteLine(number[2, 1]); /* int[,,] numg = new int[3,3,3]; foreach(int i in numg[]) { }*/ } static void exceptionhandling() { Console.WriteLine("Simple Dividor"); bool cont = true; try { while (cont) { Console.Write("Enter first number: "); double num1 = Convert.ToDouble(Console.ReadLine()); Console.Write("Enter second number: "); double num2 = Convert.ToDouble(Console.ReadLine()); double div = num1 / num2; Console.WriteLine(div); Console.WriteLine("Press \"1\" to continue || \"2\" to exit"); int i = Convert.ToInt32(Console.ReadLine()); if (i == 1) { cont = true; } else if (i == 2) { cont = false; } else { Console.WriteLine("Invalid option"); } } } catch(FormatException e) { Console.WriteLine(e.Message); exceptionhandling(); } } static void MyMethod(string child1,string child2,string child3) { Console.WriteLine("The first child is "+child2+" The second child is "+child1+" The third child is "+child3); } static void MyMethod2(string child1="saroj", string child2="sanjay", string child3="sam") { Console.WriteLine("The first child is " + child2); } static int Overload(int x,int y) { return x + y; } static double Overload(double x, double y) { return x + y; } static void Book() { book book1 = new book(); book1.title = "Game of Thrones"; book1.author = "JJ Martin"; book1.pages = 1000; //book.cs class book book2 = new book(); book2.title = "Lacasa De Papel"; book2.author = "Loronzo Rodriguez"; book2.pages = 700; Console.WriteLine("i love both " + book1.title + " & " + book2.title); } static void BookConstr() { BookConstr book1 = new BookConstr("Game of Thrones", "JJ Martin",1000); BookConstr book2 = new BookConstr("Lacasa De Papel", "Loronzo Rodriguez",700); Console.WriteLine(" i love both " + book1.title +" && "+book2.title); } static void Movie() { Movie Marvel = new Movie("Avengers", "Saroj", "PG-13"); Movie Shrek = new Movie("Shrek5", "Sanjay", "Damn"); Console.WriteLine(Shrek.Rating); } } }
abef80fc1b7ac78e4bf562b8b67fdfc50b00b842
C#
esandez93/untitled
/Assets/Scripts/Managers/CraftManager.cs
2.75
3
using UnityEngine; using UnityEngine.UI; using System; using System.Collections; using System.Collections.Generic; public class CraftManager : MonoBehaviour{ private static CraftManager instance; public bool initialized = false; private Inventory inventory; public static CraftManager Instance { get { if (instance == null) { instance = new GameObject("CraftManager").AddComponent<CraftManager>(); instance.initialize(); DontDestroyOnLoad(instance.gameObject); } return instance; } } private void initialize(){ if(!initialized){ inventory = Singleton.Instance.inventory; Debug.Log("CraftManager initialized."); initialized = true; } } public bool craft(string item1, string item2){ string sql = "SELECT DISTINCT * FROM CRAFTING WHERE ITEM_1 LIKE '" + item1 + "' OR ITEM_2 LIKE '" + item1 + "' OR ITEM_1 LIKE '" + item2 + "' OR ITEM_2 LIKE '" + item2 + "';"; List<Craft> crafts = DatabaseManager.Instance.getCrafts(sql); if(crafts.Count > 0){ Craft craft = crafts[0]; if(this.hasNeededItems(craft.item1, craft.item1Quantity, craft.item2, craft.item2Quantity)){ LanguageManager lm = LanguageManager.Instance; string message = "Crafted " + craft.resultQuantity + " " + lm.getMenuText(craft.result) + " using " + craft.item1Quantity + " " + lm.getMenuText(craft.item1) + " and " + craft.item2Quantity + " " + lm.getMenuText(craft.item2) + "."; inventory.removeItem(craft.item1, craft.item1Quantity); inventory.removeItem(craft.item2, craft.item2Quantity); inventory.addItem(craft.result, craft.resultQuantity); Gamestate.instance.showMessage(message); return true; } } return false; } private bool hasNeededItems(string item1, int item1Quantity, string item2, int item2Quantity){ if(item1.Equals(item2)){ return inventory.hasNeededItems(item1, (item1Quantity+item2Quantity)); } else{ return inventory.hasNeededItems(item1, item1Quantity) && inventory.hasNeededItems(item2, item2Quantity); } } public List<Craft> getRecipes(){ string sql = "SELECT * FROM CRAFTING;"; return DatabaseManager.Instance.getCrafts(sql); } public Craft getRecipe(string name){ string sql = "SELECT * FROM CRAFTING WHERE result = '" + name + "';"; return DatabaseManager.Instance.getCrafts(sql)[0]; } }
6237c054bf2c2bed29f5d84c9f4ef94a0b1cd2aa
C#
dotnet/dotnet-api-docs
/snippets/csharp/System.Timers/Timer/AutoReset/source.cs
3.8125
4
// <Snippet1> using System; using System.Timers; public class Example { private static Timer aTimer; public static void Main() { // Create a timer with a 1.5 second interval. double interval = 1500.0; aTimer = new System.Timers.Timer(interval); // Hook up the event handler for the Elapsed event. aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent); // Only raise the event the first time Interval elapses. aTimer.AutoReset = false; aTimer.Enabled = true; // Ensure the event fires before the exit message appears. System.Threading.Thread.Sleep((int) interval * 2); Console.WriteLine("Press the Enter key to exit the program."); Console.ReadLine(); } // Handle the Elapsed event. private static void OnTimedEvent(object source, ElapsedEventArgs e) { Console.WriteLine("Hello World!"); } } // This example displays the following output: // Hello World! // Press the Enter key to exit the program. // </Snippet1>
8d3f24ec19356d5c19879ef396d4615dbce3143f
C#
ArkadiuszStanislawLega/SWAM
/SWAM/Exceptions/BasicException.cs
3
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; namespace SWAM.Exceptions { /// <summary> /// The basic class that inherits from Exceptions is compatible with the application GUI. /// </summary> public abstract class BasicException : Exception { public BasicException(string message) : base (message) { } /// <summary> /// Displays information for the user. /// </summary> /// <param name="content">FrameworkElement during which an exception occurred.</param> public void ShowMessage(FrameworkElement content) { if(!InformationToUser(content)) MessageBox.Show(this.Message, "Błąd", MessageBoxButton.OK, MessageBoxImage.Information); } #region InformationToUser /// <summary> /// Changing content information label in main window. /// </summary> /// <param name="content">FrameworkElement during which an exception occurred.</param> /// <returns>False - when the parent was not found, true - if the parent was found and the information was displayed. </returns> private bool InformationToUser(FrameworkElement content) { try { if (SWAM.MainWindow.FindParent<SWAM.MainWindow>(content) is SWAM.MainWindow mainWindow) { mainWindow.InformationForUser($"{this.Message} {content.GetType().ToString()}", true); return true; } else throw new InformationLabelException(this.Message); } catch (InformationLabelException) { return false; } } #endregion } }
ee8c5ec283aee77f3f9ca32329086bfd67e36d1f
C#
kpocza/AbevWebForm
/src/WebForm/WebForm.Generator/Common/ContentBuilder.cs
2.609375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml; using System.IO; using WebForm.Generator.Model; namespace WebForm.Generator.Common { internal class ContentBuilder { private string InputFile { get; set; } internal ContentBuilder(string inputFile) { InputFile = inputFile; } internal FormContent Build() { var zipHandler = new ZipHandler(this.InputFile); var xmlDocument = new XmlDocument(); xmlDocument.Load(new MemoryStream(zipHandler.GetENYK())); var forms = xmlDocument.DocumentElement.SelectNodes("/FILE/FORMS/FORM"); if (forms.Count != 1) { throw new Exception("Nem pontosan egy formot tartalmaz az ENYK"); } return new FormContent((XmlElement)forms[0]); } } }
124324c6bb0375716867cc8ae3769bd5db2eee34
C#
chivass/icoSPVenta
/icoSPVenta/icoSPVenta.Datos/Objetos/Base.cs
2.890625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using icoSPVenta.Datos.Conexion; namespace icoSPVenta.Datos.Objetos { public class Base { public Base(Connection conn) { } private void Validate() { if (this.TableName() == "NoName") throw new NotImplementedException("Debe de implementar la funcion TableName para el tipo " + this.GetType().ToString()); } public virtual string TableName() { return "NoName"; } public virtual string CampoName() { return "NoName"; } internal string CrearSqlValidar(string Valor) { string sql = "SELECT COUNT({0}) FROM {1} WHERE {2}='" + Valor+"'"; sql = string.Format(sql, CampoName(), TableName(), CampoName()); return sql; } public virtual string CrearSqlInsert(List<Campos> CamposInsertar) { Validate(); string campos = ""; string valores = ""; foreach (Campos p in CamposInsertar) { campos = campos + p.Campo + ","; valores = valores + ToSQLValueFormat(p.Valor) + ","; } campos = campos.Substring(0, campos.Length - 1); valores = valores.Substring(0, valores.Length - 1); string sql = "INSERT INTO {0} ({1}) VALUES ({2})"; sql = string.Format(sql, TableName(), campos, valores); return sql; } internal string CrearSqlObtenerColeccion() { Validate(); return string.Format("SELECT * FROM {0}", TableName()); } internal string CrearSqlObtener(int OidObjeto) { Validate(); return string.Format("SELECT * FROM {0} WHERE OID = {1}", TableName(), OidObjeto); } public string ToSQLValueFormat(object obj) { if (obj == null) return "null"; string objType = obj.GetType().ToString(); string strFormat = "null"; switch (objType) { case "System.String": strFormat = String.Format("'{0}'", obj); break; case "System.Int32": strFormat = obj.ToString(); break; case "System.Decimal": strFormat = obj.ToString(); break; case "System.DateTime": strFormat = String.Format("'{0:M/d/yyyy HH:mm:ss}'", obj); break; case "System.Boolean": strFormat = String.Format("'{0}'", obj); break; default: break; } return strFormat; } } public class Campos { public string Campo; public object Valor; } }
857ceceadf5b90ab68063b78ff58096e10996ab6
C#
PoshSec/PoshSecFramework
/poshsecframework/Systems/SystemsListViewItem.cs
2.609375
3
using System; using System.Net; using System.Windows.Forms; using PoshSec.Framework.Strings; namespace PoshSec.Framework { public class SystemsListViewItem : ListViewItem, INetworkNode { private SystemsListViewItem() { ImageIndex = 2; SubItems.Add(new ListViewSubItem(this,string.Empty){Name = "ip"}); SubItems.Add(new ListViewSubItem(this,string.Empty){Name = "mac"}); SubItems.Add(new ListViewSubItem(this,string.Empty){Name = "description"}); SubItems.Add(new ListViewSubItem(this,string.Empty){Name = "status"}); SubItems.Add(new ListViewSubItem(this,string.Empty){Name = "installed"}); SubItems.Add(new ListViewSubItem(this,string.Empty){Name = "alerts"}); SubItems.Add(new ListViewSubItem(this,string.Empty){Name = "lastscanned"}); } public SystemsListViewItem(INetworkNode node) : this() { Name = node.Name; Text = node.Name; IpAddress = node.IpAddress; MacAddress = node.MacAddress; Description = node.Description; Status = node.Status; ClientInstalled = node.ClientInstalled; Alerts = node.Alerts; LastScanned = node.LastScanned; } public IPAddress IpAddress { get => IPAddress.TryParse(SubItems["ip"].Text, out var ipAddress) ? ipAddress : null; set => SubItems["ip"].Text = value.ToString(); } public string MacAddress { get => SubItems["mac"].Text; set => SubItems["mac"].Text = value; } public string Description { get => SubItems["description"].Text; set => SubItems["description"].Text = value; } public string Status { get => SubItems["status"].Text; set => SubItems["status"].Text = value; } public string ClientInstalled { get => SubItems["installed"].Text; set => SubItems["installed"].Text = value; } public int Alerts { get => int.Parse(SubItems["alerts"].Text); set => SubItems["alerts"].Text = value.ToString(); } public DateTime LastScanned { get => DateTime.Parse(SubItems["lastscanned"].Text); set => SubItems["lastscanned"].Text = value.ToString(StringValue.TimeFormat); } } }
6486da7da10aacba8afac4e973847d6ff02fa375
C#
dobrucki/PAS-project
/PAS-project/Models/UserManager.cs
3.21875
3
using System; using System.Collections.Generic; using System.Linq; namespace PAS_project.Models { public class UserManager { private readonly IDataRepository<User> _repository; public UserManager(IDataRepository<User> repository) { _repository = repository; } public User AddUser(User user) { if(user is null) throw new Exception("Given user is null"); if (_repository.GetAll().Any(m => m.Email == user.Email)) throw new Exception("Given user already exists!"); _repository.Add(user); return user; } public User GetUser(int id) { return _repository.Get(id); } public IEnumerable<User> GetAllUsers() { return _repository.GetAll(); } public User UpdateUser(User updatedUser) { if (updatedUser is null) throw new Exception("Given user is null!"); return _repository.Update(updatedUser); } public User DeleteUser(int id) { return _repository.Delete(id); } public void ActivateUser(User user) { if(user.Activity) throw new Exception("Given user is already activated!"); user.Activity = true; } public void DeactivateUser(User user) { if(user.Activity == false) throw new Exception("Given user is already deactivated!"); user.Activity = false; } public User FilterByEmails(string email) { var result = _repository.GetAll().FirstOrDefault(cl => cl.Email == email); if(result == null) throw new Exception("Given email does not match any user!"); return result; } } }
e2a6f97de5237dff43667a6233c0909b58d8017b
C#
ky2967/MVVM_Practice
/MVVM_Test/ViewModel/MainViewModel.cs
3.28125
3
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Input; namespace MVVM_Test.ViewModel { public class MainViewModel : INotifyPropertyChanged { #region > 생성자 public MainViewModel() { Number = 0; } #endregion #region > PropertyChanged public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged(string propertyName) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); #endregion #region > Data Binding private int iNumber; public int Number { get { return iNumber; } set { if(value < 0 || value > 10) { MessageBox.Show("올바르지 않은 숫자입니다."); return; } iNumber = value; OnPropertyChanged("Number"); MainText = value.ToString(); OnPropertyChanged("PlusEnable"); OnPropertyChanged("MinusEnable"); } } public bool PlusEnable { get { return Number >= 10 ? false : true; } } public bool MinusEnable { get { return Number < 1 ? false : true; } } private string sMainText; public string MainText { get { return sMainText; } set { sMainText = $"선택된 숫자는 {value}입니다."; OnPropertyChanged("MainText"); } } #endregion #region > Command private ICommand minusCommand; public ICommand MinusCommand { get { return minusCommand ?? (minusCommand = new DelegateCommand(Minus)); } } private ICommand plusCommand; public ICommand PlusCommand { get { return plusCommand ?? (plusCommand = new DelegateCommand(Plus)); } } #endregion #region > Method private void Minus() { Number--; } private void Plus() { Number++; } #endregion } }
1c8367f6fdfaf7809e461c7157ed62c20e91df5a
C#
RaeezLachporia/GoblinHunter
/GoblinHunter/Map.cs
3.09375
3
using System; using System.Collections.Generic; using System.Text; namespace GoblinHunter { class Map : Enemy { Map mmap = new Map(10, 10, " ", TileType.Empty,0,10,0,10,3,3); //declaring all the variables for the class private Tile [,] mapcontainer; public Tile [,] MAPCONTAINER { get {return mapcontainer;} set { mapcontainer = value;} } private Hero playercharacter; public Hero PLAYERCHARACTER { get { return playercharacter;} set { playercharacter = value;} } private List<Enemy> enemies; public List<Enemy> ENEMIES { get { return enemies;} set { enemies = value;} } private int mapwidth; public int MAPWIDTH { get { return mapwidth;} set { mapwidth = value;} } private int mapheight; public int MAPHEIGHT { get { return mapheight;} set { mapheight = value;} } private List<Item> items; public List<Item> ITEMS { get { return items; } set { items = value; } } //created a random number generator to determine the random values for the grid protected Random RANDOM_NUMBER_GENERATOR = new Random(); //declared a constructor for the class ad declaring newer variables for the minimum and maximum variables for the height and width public Map(int _EnemyX,int _EnemyY,String _ESYMBOL,TileType _TOT,int _MINWIDTH, int _MAXWIDTH, int _MINHEIGHT, int _MAXHEIGHT, int _NUMBEROFENEMIES, int _NUMGOLD) : base(_EnemyX, _EnemyY,_TOT," ",10,10,10) { MAPWIDTH = RANDOM_NUMBER_GENERATOR.Next(_MINWIDTH,_MAXWIDTH); MAPHEIGHT = RANDOM_NUMBER_GENERATOR.Next(_MINHEIGHT,_MAXHEIGHT); MAPCONTAINER = new Tile[MAPWIDTH,MAPHEIGHT]; ENEMIES = new List<Enemy>(_NUMBEROFENEMIES); generateMap(); UpdateVision(); ITEMS = new List<Item>(_NUMGOLD); } public void UpdateVision() { foreach(Enemy E in enemies)// What is happing in GOBVISION { if (E.X >0) { E.GobVision.Add(MAPCONTAINER[E.X - 1, E.Y]); } if(E.X < MAPWIDTH) { E.GobVision.Add(MAPCONTAINER[E.X + 1, E.Y]); } if(E.Y > 0) { E.GobVision.Add(MAPCONTAINER[E.X, Y - 1]); } if(E.Y< MAPHEIGHT) { E.GobVision.Add(MAPCONTAINER[E.X, E.Y + 1]); } } } //method generates the map with the "x" symbol used as the barrier blocks that the player cannot pass through public void generateMap() { for (int y = 0; y < MAPWIDTH; y++) { for (int x = 0; x <MAPHEIGHT; x++) { if (x == 0 || x == MAPWIDTH - 1 || y == 0 || y == MAPHEIGHT)//BORDER { //create the barrier blocks that the player cant move past Create(TileType.Barrier,x,y); } else { //creates empty tiles that the player can move around in Create(TileType.Empty,x,y); } } } Create(TileType.Hero); for (int e = 0; e < ENEMIES.Count; e++) { Create(TileType.Enemy); } } public void Create(TileType TOT, int x= 0, int y = 0) { switch (TOT) { case TileType.Barrier: Obstacle NewBarrier = new Obstacle(X,Y,TOT,"#"); MAPCONTAINER[X,Y] = NewBarrier; break; case TileType.Empty: EmptyTile NewEmptyTile = new EmptyTile(X,Y,TOT," "); MAPCONTAINER[X,Y] = NewEmptyTile; break; case TileType.Hero: int heroX = RANDOM_NUMBER_GENERATOR.Next(0,MAPWIDTH); int heroY = RANDOM_NUMBER_GENERATOR.Next(0,MAPHEIGHT); while(MAPCONTAINER[heroX,heroY].TOT != TileType.Empty) { heroX = RANDOM_NUMBER_GENERATOR.Next(0,MAPWIDTH); heroY = RANDOM_NUMBER_GENERATOR.Next(0,MAPHEIGHT); } Hero newHero = new Hero(heroX, heroY, TOT, "H", 10, 100,2); PLAYERCHARACTER = newHero; MAPCONTAINER[heroX,heroY] = newHero; break; case TileType.Enemy: int enemyX = RANDOM_NUMBER_GENERATOR.Next(0, MAPWIDTH); int enemyY = RANDOM_NUMBER_GENERATOR.Next(0,MAPHEIGHT); while(MAPCONTAINER[enemyX,enemyY].TOT != TileType.Empty) { enemyX = RANDOM_NUMBER_GENERATOR.Next(0,MAPWIDTH); enemyY = RANDOM_NUMBER_GENERATOR.Next(0, MAPHEIGHT); } Enemy NewEnemy = null; Random rnd = new Random(); int rndNumber = rnd.Next(1, 99); if (rndNumber%2 == 0) { NewEnemy = new Goblin(enemyX, enemyY, TOT, "G", eMAXHP, 10, 1); } else { NewEnemy = new Mage(enemyX, enemyY, TOT, "M", eMAXHP); } ENEMIES.Add(NewEnemy); MAPCONTAINER[enemyX,enemyY] = NewEnemy; break; case TileType.Gold: int goldX = RANDOM_NUMBER_GENERATOR.Next(0, MAPWIDTH); int goldY = RANDOM_NUMBER_GENERATOR.Next(0, MAPHEIGHT); while (MAPCONTAINER[goldX, goldY].TOT != TileType.Empty) { goldX = RANDOM_NUMBER_GENERATOR.Next(0, MAPWIDTH); goldY = RANDOM_NUMBER_GENERATOR.Next(0, MAPHEIGHT); } Gold newGold = new Gold(goldX, goldY, TOT, "G"); MAPCONTAINER[goldX, goldY] = newGold; break; } } public override string ToString() { String MapString = ""; for (int y = 0; y < MAPWIDTH; y++) { for (int x = 0; x < MAPHEIGHT; x++) { MapString += MAPCONTAINER[x,y].Symbol; } MapString+= "\n"; } return MapString; } public void updateVision(Goblin gobVision, int _mapMinHGHT, int _mapMaxHGHT, int _mapMinWDTH, int _mapMaxWDTH, int _enemies) { } public override int ReturnMove() { throw new NotImplementedException(); } } }
d9bdc113b3a9a2ce8dc2ade75046e87ea756104d
C#
jamolpe/TiendeoAssesment
/Server/TiendeoAPI/TiendeoAPI/Core/ServiceCore/ServiceCore.cs
2.828125
3
using System.Collections.Generic; using System.Linq; using AutoMapper; using ServicesLibrary.Interfaces; using TiendeoAPI.Core.Interfaces; using TiendeoAPI.Models; namespace TiendeoAPI.Core.ServiceCore { public class ServiceCore : IServiceCore { private readonly ILocalService _localService; private readonly ICityService _cityService; public ServiceCore(ILocalService localService,ICityService cityService) { this._localService = localService; this._cityService = cityService; } public List<ServiceModel> GetAllServicesFromACity(string city) { List<ServiceModel> serviceModels = new List<ServiceModel>(); var cityDto = this._cityService.GetCityByName(city); if (cityDto != null) { var serviceDtos = this._localService.GetAllServices().Where(s => s.CityId == cityDto.Id).ToList(); if (serviceDtos.Any()) { serviceDtos.ForEach(s => { var serviceModel = Mapper.Map<ServiceModel>(s); var cityModel = Mapper.Map<CityModel>(cityDto); serviceModel.City = cityModel; serviceModels.Add(serviceModel); }); } } return serviceModels; } } }
19e1206d5a63e463b7ebce5a0ceadd63f7803421
C#
eiashy/Csharp01_codes
/שיעור 22 12-25-19/Visual Studio Projects/Q3 25 12 19/Q3 25 12 19/Program.cs
3.59375
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Q3_25_12_19 { class Program { static int SumOf1ToNum(int num) { int sum = 0; for (int i = 1; i <= num; i++) sum += i; return sum; } static void Main(string[] args) { int num,sum; Console.WriteLine("enter number up 1"); num = int.Parse(Console.ReadLine()); sum = SumOf1ToNum(num); Console.WriteLine($"the sum of numbers from 1-{num} is {sum}"); Console.WriteLine($"the sum of numbers from 1-"+num +" is " + sum); Console.WriteLine($"the sum of numbers from 1-{num} is {SumOf1ToNum(num)}"); } } }
db530e2fc4fa09660b1b3fcd90673074ce73f271
C#
It3rate/MLTest
/MLTest/Vis/Primitives/Node.cs
2.96875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.ML.Probabilistic.Distributions; namespace MLTest.Vis { public class Node : IPrimitive { public IPath Reference { get; } // if reference is a stroke, this must be a joint public float Position { get; } public Node PreviousNode { get; private set; } public Node NextNode { get; private set; } // calculated public Point Anchor { get; protected set; } public float X => Anchor.X; public float Y => Anchor.Y; public virtual Point Start => Anchor; public virtual Point End => Anchor; public Node(IPath reference, float position) { Reference = reference; Position = position; Anchor = reference.GetPoint(position); } public Point GetPoint(float position, float offset=0) { throw new NotImplementedException(); } public float Similarity(IPrimitive p) => 0; public Point Sample(Gaussian g) => null; public override string ToString() { return Anchor.ToString(); } } /// <summary> /// Node that joins the reference path perpendicularly at the nearest point. Mostly for circles. If inside, connects to closest edge. If center connects to origin. /// Line: if it isn't valid for a line segment, it will connect to the imaginary extended line? /// Arc: Connects to imaginary edge if arc isn't complete. If inside, connects to nearest interior point on arc, if invalid behaves as circle. /// </summary> public class PerpendicularNode : Node { public PerpendicularNode(IPath reference): base(reference, 0) { } } // The first node on a circleRef needs to specify it's direction as there are two tangent lines. Points inside the circleRef will move to intersecting point of the second node's reference based on direction. public class TangentNode : Node { public ClockDirection Direction { get; } public Circle CircleRef; private Point _start; public override Point Start => _start; private Point _end; public override Point End => _end; public TangentNode(Circle circleRef, ClockDirection direction = ClockDirection.CW) : base(circleRef, 0) { CircleRef = circleRef; Direction = direction; } public Point GetTangentFromPoint(Node node) { // if node is null, get point on circumference using position. // if it is another Tangent node use circleRef tangents _start = CircleRef.FindTangentInDirection(node.End, Direction); return _start; } public Point GetTangentToPoint(Node node) { // if p is null, get point on circumference using position. // if it is another Tangent node use circleRef tangents _end = CircleRef.FindTangentInDirection(node.Start, Direction.Counter()); return _end; } public override string ToString() { return String.Format("tanNode:{0:0.##},{1:0.##} e{2:0.##},{3:0.##}", Start.X, Start.Y, End.X, End.Y); } } public class TipNode : Node { // Offset can't be zero in a middle node, as it causes overlap on lines that are tangent to each other. // The corner of a P is part of the shape with potential overlap on the serif. // Maybe X could be a V with overlap.H would be a half U with 0.5 overlap. Maybe this is too obfuscated. Yes it is. Might work for serifs though. public float Offset { get; } public TipNode(IPath reference, float position, float offset) : base(reference, position) { Offset = offset; Anchor = reference.GetPoint(position, offset); } //public TipNode(IPath reference, float position, float offset, float length) : base(reference, position) //{ // Offset = offset; // Length = length; //} public override string ToString() { return String.Format("tipNode:{0:0.##},{1:0.##} o{2:0.##}", Anchor.X, Anchor.Y, Offset); } } }
9256f3369e41479b0447025a66e3935d7c913b7e
C#
butoxors/SteamTradeNew
/PageObject/Widgets/BaseWidget.cs
2.703125
3
using OpenQA.Selenium; using System; namespace PageObject.Widgets { public abstract class BaseWidget<T> where T : BaseWidget<T> { protected IWebElement webElement; protected BaseWidget(IWebElement webElement) { this.webElement = webElement; } public IWebElement GetWrappedElement() { return webElement; } public T GetSelfReference() { return (T)this; } public IWebElement FindElement(By by) { try { return this.webElement.FindElement(by); } catch (Exception) { return null; } } } }
30e91a63f17bf9f63a4ce870146882975e8e637f
C#
MaksimGer/CSV_Cleaner
/CSV_Cleaner/CSV_Cleaner/forms/ShowDataForm.cs
2.75
3
using CSV_Cleaner.sources; 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 CSV_Cleaner.forms { public partial class ShowDataForm : Form { MainForm mainForm; Reader reader; public ShowDataForm() { InitializeComponent(); } public ShowDataForm(MainForm mainForm, ref Reader reader) { this.mainForm = mainForm; this.reader = reader; this.reader.refreshReader(); InitializeComponent(); fillTable(); } private void ShowDataForm_FormClosing(object sender, FormClosingEventArgs e) { mainForm.Show(); } private void fillTable() { int rowCount = reader.getRowCount() - 1; List<string> headers = reader.getHeaders(); foreach (string header in headers) { DataGridViewTextBoxColumn newCol = new DataGridViewTextBoxColumn(); newCol.Name = header + "Col"; newCol.HeaderText = header; dgvDataset.Columns.Add(newCol); } for (int i = 0; i < rowCount; i++) { int rowNumber = dgvDataset.Rows.Add(); string[] items = reader.getNextLine(); int index = 0; foreach (string item in items) { dgvDataset.Rows[rowNumber].Cells[index].Value = item; index++; } } } } }
9d41a995e763b6c93c7d7b0d616d2821005c188e
C#
ashburn-international/ecr-integration-samples
/src/windows/SingleThread/ConsoleGui.cs
3.09375
3
using System; using System.Collections.Generic; using System.Text; using System.Linq; namespace SingleThread { public class MenuItem { public string Key; public string Title; public Action Action; } public static class ConsoleGui { const ConsoleColor ConsoleColorError = ConsoleColor.Red; const ConsoleColor ConsoleColorOk = ConsoleColor.Green; const ConsoleColor ConsoleColorWarning = ConsoleColor.Yellow; public static bool LogTimeStamp = false; public enum CONSOLE_MESSAGE_TYPE { IDENT, OK, FAILED, WARN, NONE } static void ListMenu(List<MenuItem> menu, string Title = "") { Console.WriteLine(); if (!string.IsNullOrEmpty(Title)) Console.WriteLine($"==== {Title}"); menu.ForEach(i => Console.WriteLine($" {i.Key}. {i.Title}")); Console.WriteLine("To exit press enter without entering anything..."); } public static MenuItem GetChoiceMenu(List<MenuItem> menuItems, string Title = "") { if (menuItems == null || menuItems.Count == 0) throw new ArgumentException(nameof(menuItems)); var choice = null as string; MenuItem selectedItem = null; do { selectedItem = null; choice = Console.ReadLine().Trim().ToUpper(); if (string.IsNullOrEmpty(choice)) { // do nothing } else if (!menuItems.Select(i => i.Key).Contains(choice)) { Console.WriteLine($"unknown option [{choice}]"); } else { selectedItem = menuItems.First(i => i.Key.Trim().ToUpper() == choice); } } while (selectedItem == null); return selectedItem; } public static void LoopMenu(List<MenuItem> menuItems, string Title = "") { if (menuItems == null || menuItems.Count < 2) throw new ArgumentException(nameof(menuItems)); MenuItem selectedItem = null; while (selectedItem != menuItems.Last()) { ListMenu(menuItems, Title); selectedItem = GetChoiceMenu(menuItems, Title); selectedItem.Action?.Invoke(); } } public static T EnterValue<T>(string Prompt, string[] allowedValues = null) { var allowedValuesInUse = (allowedValues != null && allowedValues.Length > 0); var choices = ""; if (allowedValuesInUse) { allowedValues = allowedValues.Select(i => i.ToUpper()).ToArray(); choices = string.Join("/", allowedValues); if (!string.IsNullOrEmpty(choices)) choices = $" [{choices}]?"; } if (string.IsNullOrEmpty(choices)) choices = ":"; Console.ForegroundColor = ConsoleColor.White; Console.Write($"{Prompt}{choices} "); Console.ResetColor(); var valueString = Console.ReadLine().Trim(); try { if(allowedValuesInUse) { valueString = valueString.ToUpper(); if (!allowedValues.Contains(valueString)) throw new Exception("Invalid value"); } var valueConverted = (T)Convert.ChangeType(valueString, typeof(T)); if (typeof(T) == typeof(string) && string.IsNullOrEmpty(valueString)) return EnterValue<T>(Prompt, allowedValues); return valueConverted; } catch (Exception ex) { Error(ex.Message); return EnterValue<T>(Prompt, allowedValues); } } public static void Error(string message) { //Console.ForegroundColor = ConsoleColor.Red; //Console.WriteLine($"[ERROR] {message}"); //Console.ResetColor(); ConsoleLog(message, CONSOLE_MESSAGE_TYPE.FAILED); } public static void Warning(string message) { //Console.ForegroundColor = ConsoleColor.Yellow; //Console.WriteLine($"{message}"); //Console.ResetColor(); ConsoleLog(message, CONSOLE_MESSAGE_TYPE.WARN); } public static void Info(string message) { //Console.ForegroundColor = ConsoleColor.White; //Console.WriteLine($"{message}"); //Console.ResetColor(); ConsoleLog(message, CONSOLE_MESSAGE_TYPE.NONE); } public static void Ok(string message) { //Console.ForegroundColor = ConsoleColor.White; //Console.WriteLine($"{message}"); //Console.ResetColor(); ConsoleLog(message, CONSOLE_MESSAGE_TYPE.OK); } static void ConsoleLog( string txt, CONSOLE_MESSAGE_TYPE type = CONSOLE_MESSAGE_TYPE.IDENT, ConsoleColor color = ConsoleColor.Gray) { const string OK = " OK "; const string FAILED = "FAILED"; const string WARNING = " WARN "; const string EMPTY = " "; if (LogTimeStamp) Console.Write($"[{DateTime.Now:HH:mm:ss}] "); switch (type) { case CONSOLE_MESSAGE_TYPE.OK: Console.Write("["); Console.ForegroundColor = ConsoleColorOk; Console.Write(OK); Console.ResetColor(); Console.Write("] "); break; case CONSOLE_MESSAGE_TYPE.FAILED: Console.Write("["); Console.ForegroundColor = ConsoleColorError; Console.Write(FAILED); Console.ResetColor(); Console.Write("] "); break; case CONSOLE_MESSAGE_TYPE.WARN: Console.Write("["); Console.ForegroundColor = ConsoleColorWarning; Console.Write(WARNING); Console.ResetColor(); Console.Write("] "); break; case CONSOLE_MESSAGE_TYPE.NONE: break; default: Console.Write(EMPTY); break; } Console.ForegroundColor = color; Console.Write(txt); Console.WriteLine(); Console.ResetColor(); } } }
84d88e04b42fd9f26726472ef60de2a73438687c
C#
giokoguashvili/POOP
/SWIFT/SWIFT Integration/Swift.AltaSoftware.Wrapper/Swift/Common/SplitedByLines.cs
2.734375
3
using System; namespace Swift.AltaSoftware.Wrapper.Swift.Common { public class SplitedByLines { private readonly string _str; public SplitedByLines(string str) { _str = str; } public string[] Value() { return _str.Split(new[] {"\n", "\n\r", "\r"}, StringSplitOptions.RemoveEmptyEntries); } } }
a1b1fbdcfa8d82fa23a09e42686fc6a6f2754272
C#
WolfgangNS/scrabble-solver
/Program.cs
2.875
3
using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Linq; using System.Text.RegularExpressions; namespace scrabblerobot { class Program { static char[,] board = new char[15,15]; static int[,] LM = //letter multipliers {{1,1,1,2,1,1,1,1,1,1,1,2,1,1,1}, {1,1,1,1,1,3,1,1,1,3,1,1,1,1,1}, {1,1,1,1,1,1,2,1,2,1,1,1,1,1,1}, {2,1,1,1,1,1,1,2,1,1,1,1,1,1,2}, {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}, {1,3,1,1,1,3,1,1,1,3,1,1,1,3,1}, {1,1,2,1,1,1,2,1,2,1,1,1,2,1,1}, {1,1,1,2,1,1,1,1,1,1,1,2,1,1,1}, {1,1,2,1,1,1,2,1,2,1,1,1,2,1,1}, {1,3,1,1,1,3,1,1,1,3,1,1,1,3,1}, {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}, {2,1,1,1,1,1,1,2,1,1,1,1,1,1,2}, {1,1,1,1,1,1,2,1,2,1,1,1,1,1,1}, {1,1,1,1,1,3,1,1,1,3,1,1,1,1,1}, {1,1,1,2,1,1,1,1,1,1,1,2,1,1,1}}; static List<string> words; static void Main(string[] args) { for(int i = 0;i<=14;i++){ for(int j = 0;j<=14;j++){ board[i,j]= (char)32; //space } } var words = new List<string>(); StreamReader sr = new StreamReader("/home/wolfgang/Documents/words.txt"); for(int i = 0;i<=186029;i++){ words.Add(sr.ReadLine()); } string tiles = "AAAAAAAAABBCCDDDDEEEEEEEEEEEEFFGGGHHIIIIIIIIIJKLLLLMMNNNNNNOOOOOOOOPPQRRRRRRSSSSTTTTTTUUUUVVWWXYYZ"; //DRAW TILES string shuffled = ""; Random r = new Random(420692); //Random r = new Random(91169); string p1,p2 = ""; while(tiles!=""){ var i = r.Next(tiles.Length); shuffled += tiles[i]; tiles = tiles.Remove(i,1); } tiles = shuffled; //naming getting confusing lol p1 = tiles.Substring(0,7); tiles = tiles.Remove(0,7); p2 = tiles.Substring(0,7); tiles = tiles.Remove(0,7); Console.WriteLine("{0}, {1}, {2}", p1, p2, tiles); //int p1_blanks, p2_blanks = 0; //for blank tiles var arrangements = new List<string>(); //arrangements.Add("ARSON"); arrangements = longestwords(p2, ref words); arrangements = arrangements.OrderBy(x=>-x.Length).ToList<string>(); //TO-DO: switch properly between p1 and p2 between turns //I need to evaluate the letter scores for each next int k = 7; foreach(char a in arrangements[0]){ board[7,k] = a; k++; p2 = p2.Remove(p2.IndexOf(a),1); } print(); //draw new tiles from the bag var diff = 7-p2.Length; p2 += tiles.Substring(0,diff); tiles = tiles.Remove(0,diff); Console.WriteLine("{0}, {1}, {2}", p1, p2, tiles); //next: evaluate positions to see if they're valid //next: evaluate letter scores for valid positions var rows = new List<string>(); var cols = new List<string>(); for(int i=0;i<=14;i++){ string rowstring = ""; string colstring = ""; for(int j = 0;j<=14;j++){ rowstring+=board[j,i]; colstring+=board[i,j]; } rows.Add(rowstring); cols.Add(colstring); } //now for the Regex magic var capture = new Regex("[A-Z]? ?([A-Z ]*[A-Z]+[A-Z ]*) ?[A-Z]?"); var boardmatches = new List<string>(); foreach(string row in rows){ try{ string match = capture.Matches(row)[0].Groups[0].Value; //will throw an error on this Console.WriteLine(match.Replace(" ",".")); boardmatches.Add(match.Replace(" ",".?")); }catch{} }//TO-DO: repeat for columns arrangements.Clear(); //I could speed this up by regex-ing each dictionary entry? //But I need to speedtest that foreach(string pattern in boardmatches){ var longwords = longestwords(p2+pattern.Replace(".?",""),ref words); //brainstorms dictionary words with those letters foreach(string word in longwords){ if(Regex.IsMatch(word,pattern)){ //bias towards the top arrangements.Add(word); } } //the replace thing is a bit redundant //go back to the dictionary at this point to search by letter combinations? } arrangements = arrangements.OrderBy(x=>-x.Length).ToList<string>(); arrangements.Clear(); arrangements.Add("BRACKET"); //for debugging Console.WriteLine(arrangements[0]); k = 0; int rownum = 0, colnum = 0; foreach(string row in rows){ try{ //var pattern3 = Regex.Replace(row, "^ *([A-Z]+[A-Z ]*[A-Z]+) *","($1)").Replace(" ", "."); var pattern3 = Regex.Replace(row, "^ *", ""); var offset2 = row.Length-pattern3.Length; pattern3 = Regex.Replace(pattern3, " *$", "").Replace(" ","."); if(pattern3.Length==0){throw new Exception();} Console.WriteLine("regex: " + pattern3); if(Regex.IsMatch(arrangements[0], pattern3)){ var m = Regex.Match(arrangements[0], pattern3); var offset = m.Index; rownum = k; colnum = offset2-offset; //var t = v.Index; Console.WriteLine(rownum+", "+colnum); } }catch{} k++; } //change "arrangements" to "dicwords" for the lulz int k2 = colnum; //first column foreach(char a in arrangements[0]){ board[k2, rownum] = a; k2++; } print(); // are my rows and columns mixed up??? Console.WriteLine("Done."); } static void print(){ for(int j = 0;j<15;j++){ for(int i = 0;i<15;i++){ if(board[i,j]!=(char)32){ Console.Write(" " + board[i,j]); }else{ Console.Write(" ."); } } Console.Write("\n"); } } static List<string> longestwords(string tiles, ref List<string> words){ //var "words" is screwy, the way it's initialized var arrangements = new List<string>(); foreach(string word in words){ var tiles_2 = tiles; try{ foreach(char letter in word){ if(!tiles_2.Contains(letter)){ throw new Exception(); //there must be a better way to exit a loop } tiles_2 = tiles_2.Remove(tiles_2.IndexOf(letter),1); } arrangements.Add(word); }catch{} } //arrangements = arrangements.OrderBy(x=>-x.Length).ToList<string>(); //second letter //arrangements = arrangements.FindAll(x => x.Length==arrangements[0].Length); return arrangements; } } class Bot{ List<char> tiles = new List<char>(); //method firstmove //method regularmove } static class Board{ //do I need this? //properties: list of words, //like an api thing, that enforces the rules and whatnot } //create class for each word, and it's properties? // -> like length, letters containing, //linked list of words and their letters alphabetized? //or a tree of words? //or a tree of each word, letters alphabetized? (e.g. spider becomes ediprs) } //consulting between board, available tiles, and dictionary //https://csharp.net-tutorials.com/linq/linq-query-syntax-vs-method-syntax/ //https://stackoverflow.com/questions/1175645/find-an-item-in-list-by-linq
dd7f8810a1810c1c19dc4eb669d17067320cf8f2
C#
hyuntaeng/UnitySimultaneousModifiers
/Assets/TimedEffect.cs
2.859375
3
using UnityEngine; using System.Collections; using System; public class TimedEffect<V> : TemporaryEffect<V> { public float HoldTime = 0; private float startTime; //The time since the level loaded that this object was created public TimedEffect() : base() { startTime = Time.timeSinceLevelLoad; } public TimedEffect(V value) : base(value) { startTime = Time.timeSinceLevelLoad; } public override bool IsActive() //Has less time passed since this effect was created than TweenInTime + HoldTime? { return (Time.timeSinceLevelLoad - startTime) < (TweenInTime + HoldTime); } }
9bb019b4a569df176d0c3971bd1665f3eb4e5ed2
C#
nalaugh/dino-diner
/MenuTest/Drinks/SodaSaurusTest.cs
2.890625
3
using System; using System.Collections.Generic; using System.Text; using Xunit; using DinoDiner.Menu; namespace MenuTest.Drinks { public class SodaSaurusTest { //1.The ability to set each possible flavor //2.The correct default price, calories, ice, and size //3.The correct price and calories after changing to small, medium, and large sizes. //4.That invoking HoldIce() results in the Ice property being false. //5. The correct ingredients are given [Theory] [InlineData(SodasaurusFlavor.Cherry)] [InlineData(SodasaurusFlavor.Chocolate)] [InlineData(SodasaurusFlavor.Cola)] [InlineData(SodasaurusFlavor.Lime)] [InlineData(SodasaurusFlavor.Orange)] [InlineData(SodasaurusFlavor.RootBeer)] [InlineData(SodasaurusFlavor.Vanilla)] public void ShouldBeAbleToSetFlavor(SodasaurusFlavor flavor) { Sodasaurus soda = new Sodasaurus(); soda.Flavor = flavor; Assert.Equal<SodasaurusFlavor>(flavor, soda.Flavor); } /// <summary> /// Check the defualt Price /// </summary> [Fact] public void ShouldGiveDefaultSetting() { Sodasaurus soda = new Sodasaurus(); Assert.Equal<double>(1.50, soda.Price); Assert.Equal<uint>(112, soda.Calories); Assert.True(soda.Ice); Assert.Equal<Size>(Size.Small, soda.Size); } /// <summary> /// Checks the price of a small drink /// </summary> [Fact] public void ShouldGiveSmallSoda() { Sodasaurus sode = new Sodasaurus(); sode.Size = Size.Medium; sode.Size = Size.Small; Assert.Equal<double>(1.50, sode.Price); Assert.Equal<uint>(112, sode.Calories); } /// <summary> /// Checks the price of a Medium drink /// </summary> [Fact] public void ShouldGiveMediumSOda() { Sodasaurus sode = new Sodasaurus(); sode.Size = Size.Medium; Assert.Equal<double>(2.00, sode.Price); Assert.Equal<uint>(156, sode.Calories); } /// <summary> /// Checks the price of a Large drink /// </summary> [Fact] public void ShouldGiveLargeSoda() { Sodasaurus sode = new Sodasaurus(); sode.Size = Size.Large; Assert.Equal<double>(2.50, sode.Price); Assert.Equal<uint>(208, sode.Calories); } /// <summary> /// Checks the see that the Ice was held /// </summary> [Fact] public void ShouldHoldice() { Sodasaurus soda = new Sodasaurus(); soda.HoldIce(); Assert.False(soda.Ice); } /// <summary> /// CHecks defualt ingredience /// </summary> [Fact] public void ShouldGiveIngrediance() { Sodasaurus soda = new Sodasaurus(); List<string> ingredients = soda.Ingredients; Assert.Contains<string>("Water", ingredients); Assert.Contains<string>("Natural Flavors", ingredients); Assert.Contains<string>("Cane Sugar", ingredients); Assert.Equal<int>(3, ingredients.Count); } [Fact] public void SHouldhaveEmptySpaciallistByDefault() { Sodasaurus ty = new Sodasaurus(); Assert.Empty(ty.Special); } [Fact] public void ShouldShowPriceSmallPropertyChange() { Sodasaurus jv = new Sodasaurus(); jv.Size = Size.Small; Assert.PropertyChanged(jv, "Price", () => { jv.Size = Size.Small; }); } [Fact] public void ShouldShowPriceMediumPropertyChange() { Sodasaurus jv = new Sodasaurus(); jv.Size = Size.Medium; Assert.PropertyChanged(jv, "Price", () => { jv.Size = Size.Medium; }); } [Fact] public void ShouldShowPriceLargePropertyChange() { Sodasaurus jv = new Sodasaurus(); jv.Size = Size.Large; Assert.PropertyChanged(jv, "Price", () => { jv.Size = Size.Large; }); } } }
d8922e3ceaaad3986a1077d743243cbe35bc2b20
C#
pablo2000/EliteDangerousDataProvider
/EliteDangerousDataDefinitions/Commander.cs
2.671875
3
using System.Collections.Generic; namespace EliteDangerousDataDefinitions { /// <summary> /// Details about a commander /// </summary> public class Commander { public static string[] combatRanks = new string[9] { "Harmless", "Mostly Harmless", "Novice", "Competent", "Expert", "Master", "Dangerous", "Deadly", "Elite" }; public static string[] tradeRanks = new string[9] { "Penniless", "Mostly Penniless", "Peddlar", "Dealer", "Merchant", "Broker", "Entrepreneur", "Tycoon", "Elite" }; public static string[] exploreRanks = new string[9] { "Aimless", "Mostly Aimless", "Scout", "Surveyor", "Trailblzer", "Pathfinder", "Ranger", "Pioneer", "Elite" }; public static string[] empireRanks = new string[15] { "Unknown", "Outsider", "Serf", "Master", "Squire", "Knight", "Lord", "Baron", "Viscount", "Count", "Earl", "Marquis", "Duke", "Prince", "King" }; public static string[] federationRanks = new string[15] { "Unknown", "Recruit", "Cadet", "Midshipman", "Petty Officer", "Chief Petty Officer", "Warrant Officer", "Ensign", "Lieutenant", "Lieutenant Commander", "Post Commander", "Post Captain", "Rear Admiral", "Vice Admiral", "Admiral" }; /// <summary>The commander's name</summary> public string Name { get; set; } /// <summary>The commander's name as spoken</summary> public string PhoneticName { get; set; } /// <summary>The numeric combat rating, 0 to 8</summary> public int CombatRating { get; set; } /// <summary>The name of the combat rating</summary> public string CombatRank { get; set; } /// <summary>The numeric trade rating, 0 to 8</summary> public int TradeRating { get; set; } /// <summary>The name of the trade rating</summary> public string TradeRank { get; set; } /// <summary>The numeric explorer rating, 0 to 8</summary> public int ExploreRating { get; set; } /// <summary>The name of the explorer rating</summary> public string ExploreRank { get; set; } /// <summary>The numeric empire rating, 0 to 14</summary> public int EmpireRating { get; set; } /// <summary>The name of the empire rating</summary> public string EmpireRank { get; set; } /// <summary>The numeric federation rating, 0 to 14</summary> public int FederationRating { get; set; } /// <summary>The name of the federation rating</summary> public string FederationRank { get; set; } /// <summary>The number of credits the commander holds</summary> public long Credits { get; set; } /// <summary>The amount of debt the commander owes</summary> public long Debt { get; set; } /// <summary>The name of the current starsystem</summary> public string StarSystem { get; set; } /// <summary>The X co-ordinate of the current starsystem</summary> public decimal? StarSystemX { get; set; } /// <summary>The Y co-ordinate of the current starsystem</summary> public decimal? StarSystemY { get; set; } /// <summary>The Z co-ordinate of the current starsystem</summary> public decimal? StarSystemZ { get; set; } /// <summary>The commander's current ship</summary> public Ship Ship { get; set; } /// <summary>The commander's stored ships</summary> public List<Ship> StoredShips { get; set; } /// <summary>The name of the last station the commander docked at</summary> public string LastStation { get; set; } // The following shouldn't be in here but they come as part of the profile. Move them somewhere a little more sane when we can access this data separately /// <summary>The modules available at the station the commander last docked at</summary> public List<Module> Outfitting; public Commander() { StoredShips = new List<Ship>(); Outfitting = new List<Module>(); } } }
62133d1df8667ba8a5565cb2b7fae6afc3f74791
C#
marabu4a/CarFactory
/CarFactory/Factory/CarPartsFactory.cs
2.640625
3
using System; using System.Collections.Generic; using CarFactory.CarPart.ChassisModel; namespace CarFactory.Factory { public abstract class CarPartsFactory : IFactory<CarPart.CarPart> { public string GetRandomManufacturer() { return listOfManufacturers[randomGenerator.GetRandomValueInRange(0,listOfManufacturers.Count)]; } public IReadOnlyList<String> listOfManufacturers = new List<String> { "Mitsubishi motors", "VAG", "Nissan", "Renault-Nissan Group", "Ford", "Jaguar-Land Rover", "BMW Motors" }; } }
0c62a17711880e26058b25005dc5b2bea57bdaa1
C#
jb1361/Recipe-Backend
/Recipe.Api/Controllers/RecipeController.cs
2.578125
3
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; namespace Recipe.Api.Controllers { [Route("api/v1/[controller]")] [ApiController] public class RecipeController : BaseController { public RecipeController(BaseControllerDependencies dependencies) : base(dependencies) { } // GET: api/v1/Recipe [HttpGet] public async Task<ActionResult<IEnumerable<Models.DefaultContextModels.Recipe>>> GetRecipe() { return await DatabaseContext.Recipes.ToListAsync(); } // GET: api/v1/Recipe/5 [HttpGet("{id}")] public async Task<ActionResult<Models.DefaultContextModels.Recipe>> GetRecipe(int id) { var recipe = await DatabaseContext.Recipes.FindAsync(id); if (recipe == null) { return NotFound(); } return recipe; } // POST: api/v1/Recipe [HttpPost] public async Task<ActionResult<Models.DefaultContextModels.Recipe>> UpsertRecipe(Models.DefaultContextModels.Recipe recipe) { await DatabaseContext.Database.BeginTransactionAsync(); if (recipe.Id == 0) { DatabaseContext.Add(recipe); } else { recipe.DeleteRemovedRelationships(DatabaseContext); DatabaseContext.Recipes.Update(recipe); } await DatabaseContext.SaveChangesAsync(); DatabaseContext.Database.CommitTransaction(); return Ok(recipe); } // DELETE: api/v1/Recipe/5 [HttpDelete("{id}")] public async Task<ActionResult<Models.DefaultContextModels.Recipe>> DeleteRecipe(int id) { var recipe = await DatabaseContext.Recipes.FindAsync(id); if (recipe == null) { return NotFound(); } DatabaseContext.Recipes.Remove(recipe); await DatabaseContext.SaveChangesAsync(); return recipe; } private bool RecipeExists(int id) { return DatabaseContext.Recipes.Any(e => e.Id == id); } } }
50f5c0a8ad2c45a2b9340be9dd55048c686b6e58
C#
abhishekjhaa/coding-practice
/C#/ImmutableStrings/Program.cs
3.765625
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ImmutableStrings { class Program { static void Main(string[] args) { Compare(); Console.ReadLine(); } public static void Compare() { string a = "prince"; string b = a; Console.WriteLine(string.Format("a == '{0}', b =='{1}'", a, b)); Console.WriteLine(string.Format("(a == b) == {0}", (a == b))); Console.WriteLine("Object.ReferenceEquals(a,b) == " + ReferenceEquals(a, b) + "\n"); // Now "modify" a, the reference changes! a += "ss"; Console.WriteLine(string.Format("a == '{0}', b =='{1}'", a, b)); Console.WriteLine(string.Format("(a == b) == {0}", (a == b))); Console.WriteLine("Object.ReferenceEquals(a,b) == " + ReferenceEquals(a, b) + "\n"); // Restore the original value, the original reference returns! a = "prince"; Console.WriteLine(string.Format("a == '{0}', b =='{1}'", a, b)); Console.WriteLine(string.Format("(a == b) == {0}", (a == b))); Console.WriteLine("Object.ReferenceEquals(a,b) == " + ReferenceEquals(a, b) + "\n"); } } }
d110c6ad07b3526af075e092c62a33bf76c30700
C#
amberolive/CoffeeShop
/CoffeeShop/AddForm.cs
2.796875
3
using System; using System.Collections; 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 CoffeeShop { public partial class AddRemoveForm : Form { ArrayList flavors; ArrayList prices; CoffeeShopAdmin coffeeShop; public AddRemoveForm(CoffeeShopAdmin cShop, ArrayList flavors, ArrayList prices) { InitializeComponent(); this.flavors = flavors; this.prices = prices; coffeeShop = cShop as CoffeeShopAdmin; } private void btAdd_Click(object sender, EventArgs e) { String flavor = tbFlavor.Text.ToLower(); String strPrice = mtbPrice.Text.Replace("$", ""); MessageBox.Show(flavor); MessageBox.Show(flavors.Contains(flavor).ToString()); MessageBox.Show(strPrice); double price; if (flavor != null && flavor != "") { if (!flavors.Contains(flavor)) { if (double.TryParse(strPrice, out price)) { prices.Add(price); flavors.Add(flavor); coffeeShop.addFlavor(flavor); } else { MessageBox.Show("Please enter a price.", "Error"); } } else { MessageBox.Show("Flavor has already been added.", "Error"); } } else { MessageBox.Show("Please enter a flavor.", "Error"); } } private void btExit_Click(object sender, EventArgs e) { this.Close(); } } }
383c8f968ce64d6235502257bdd073dfabab732e
C#
Pauta-Regional/refer
/win-prog/ProgKeyCS/Chap32/StructureAndMethodsTwo/StructureAndMethodsTwo.cs
3.640625
4
// ------------------------------------------------------------- // StructureAndMethodsTwo.cs from "Programming in the Key of C#" // ------------------------------------------------------------- using System; class StructureAndMethodsTwo { static void Main() { Date dateMoonWalk = new Date(); dateMoonWalk.iYear = 1969; dateMoonWalk.iMonth = 7; dateMoonWalk.iDay = 20; Console.WriteLine("Moon walk: {0}/{1}/{2} Day of Year: {3}", dateMoonWalk.iMonth, dateMoonWalk.iDay, dateMoonWalk.iYear, Date.DayOfYear(dateMoonWalk)); } } struct Date { public int iYear; public int iMonth; public int iDay; public static bool IsLeapYear(int iYear) { return iYear % 4 == 0 && (iYear % 100 != 0 || iYear % 400 == 0); } static int[] aiCumulativeDays = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 }; public static int DayOfYear(Date dateParam) { return aiCumulativeDays[dateParam.iMonth - 1] + dateParam.iDay + (dateParam.iMonth > 2 && IsLeapYear(dateParam.iYear) ? 1 : 0); } }
87f301e0e121e9f41c4820db382b872ede2ad536
C#
emiaj/fubumvc
/src/Serenity/Jasmine/SpecificationFolder.cs
2.578125
3
using System; using System.Collections.Generic; using System.Linq; using FubuCore.Util; using FubuMVC.Core.Assets.Files; namespace Serenity.Jasmine { public class SpecificationFolder : ISpecNode { private readonly Cache<string, SpecificationFolder> _children; private readonly string _name; private readonly SpecificationFolder _parent; private readonly IList<Specification> _specifications = new List<Specification>(); public SpecificationFolder(string name) { _name = name; _children = new Cache<string, SpecificationFolder>(path => new SpecificationFolder(path, this)); } public SpecificationFolder(string name, SpecificationFolder parent) : this(name) { _parent = parent; } public void ApplyHelpers() { var helper = _specifications.FirstOrDefault(x => x.LibraryName == Specification.HelperName); if (helper != null) { _specifications.Remove(helper); AllSpecifications.Each(x => x.AddLibrary(helper.File)); } _children.Each(x => x.ApplyHelpers()); } public SpecificationFolder Parent { get { return _parent; } } public string FullName { get { return _parent == null ? _name : _parent.FullName + "/" + _name; } } public IEnumerable<ISpecNode> ImmediateChildren { get { foreach (var folder in _children) { yield return folder; } foreach (var specification in _specifications) { yield return specification; } } } public string TreeClass { get { return "folder"; } } ISpecNode ISpecNode.Parent() { return Parent; } public void AcceptVisitor(ISpecVisitor visitor) { visitor.Folder(this); } public IEnumerable<Specification> Specifications { get { return _specifications; } } public IEnumerable<Specification> AllSpecifications { get { foreach (var folder in _children) { foreach (var spec in folder.AllSpecifications) { yield return spec; } } foreach (var spec in _specifications) { yield return spec; } } } public IEnumerable<ISpecNode> AllNodes { get { foreach (var folder in _children) { yield return folder; foreach (var node in folder.AllNodes) { yield return node; } } foreach (var spec in _specifications) { yield return spec; } } } public SpecPath Path() { var list = new List<string>{ _name }; var parent = Parent; while (parent != null) { list.Add(parent._name); parent = parent.Parent; } list.Reverse(); return new SpecPath(list); } public SpecificationFolder ChildFolderFor(string name) { return ChildFolderFor(new SpecPath(name)); } public SpecificationFolder ChildFolderFor(SpecPath path) { return path.Parts.Count == 1 ? _children[path.TopFolder] : _children[path.TopFolder].ChildFolderFor(path.ChildPath()); } public void AddSpecs(IEnumerable<AssetFile> assetFiles) { var specs = assetFiles.Select(x => new Specification(x){ Parent = this }); _specifications.AddRange(specs); } } }
15c2bfcdcf9df250846b48ad7f90dea9b01a2b60
C#
EdouardGit/Formatio
/LePendu/Program.cs
3.15625
3
using System; using System.Collections.Generic; namespace LePendu { class Program { static void Main(string[] args) { #region version object GameInstances game = new GameInstances(); #endregion #region version procedural with struct // Pendu pendu = new Pendu(); // pendu.Init(); // // while (!pendu.Fin) // { // //demander les info => prg // Console.WriteLine("Entrez une lettre"); // char lettre = char.Parse(Console.ReadLine()); // //vérifier la lettre => struct // string message = pendu.fnJeu(lettre); // // //Afficher les info // Console.WriteLine(message); // Console.WriteLine(pendu.getStatus()); // } // if (pendu.pointVie == 0) Console.WriteLine("Désolé perdu"); // else Console.WriteLine("Bravo !"); #endregion } } }
9dcef1cd8a0b1e4d74a0f33dd106226c6f7b5e47
C#
genadi1980/SoftUni
/Fundamentals of proramming/Conditional Statements and Loops/08BonusScore/BonusScore.cs
3.53125
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _08BonusScore { public class BonusScore { public static void Main() { var input = Console.ReadLine(); var fiveEnd = input[input.Length - 1]; var inputNumber = double.Parse(input); var bonusScore = 0D; if (inputNumber <= 100) { bonusScore += 5; } else if (inputNumber>100 && inputNumber <= 1000) { bonusScore = inputNumber * 20 / 100; } else if (inputNumber > 1000) { bonusScore = inputNumber * 10 / 100; } if (inputNumber % 2 == 0) { bonusScore += 1; } else if ( fiveEnd == '5') { bonusScore += 2; } Console.WriteLine(bonusScore); Console.WriteLine(bonusScore + inputNumber); } } }
5acc433861647da5f3438036b37ad0754f6ca529
C#
YAFNET/YAFNET
/yafsrc/ServiceStack/ServiceStack/Common/Script/JsStatement.cs
2.625
3
// *********************************************************************** // <copyright file="JsStatement.cs" company="ServiceStack, Inc."> // Copyright (c) ServiceStack, Inc. All Rights Reserved. // </copyright> // <summary>Fork for YetAnotherForum.NET, Licensed under the Apache License, Version 2.0</summary> // *********************************************************************** using System; using System.Collections.Generic; namespace ServiceStack.Script; /// <summary> /// Class JsStatement. /// </summary> public abstract class JsStatement { } /// <summary> /// Class JsFilterExpressionStatement. /// Implements the <see cref="ServiceStack.Script.JsStatement" /> /// </summary> /// <seealso cref="ServiceStack.Script.JsStatement" /> public class JsFilterExpressionStatement : JsStatement { /// <summary> /// Gets the filter expression. /// </summary> /// <value>The filter expression.</value> public PageVariableFragment FilterExpression { get; } /// <summary> /// Initializes a new instance of the <see cref="JsFilterExpressionStatement" /> class. /// </summary> /// <param name="originalText">The original text.</param> /// <param name="expr">The expr.</param> /// <param name="filters">The filters.</param> public JsFilterExpressionStatement(ReadOnlyMemory<char> originalText, JsToken expr, List<JsCallExpression> filters) { FilterExpression = new PageVariableFragment(originalText, expr, filters); } /// <summary> /// Initializes a new instance of the <see cref="JsFilterExpressionStatement" /> class. /// </summary> /// <param name="originalText">The original text.</param> /// <param name="expr">The expr.</param> /// <param name="filters">The filters.</param> public JsFilterExpressionStatement(string originalText, JsToken expr, params JsCallExpression[] filters) { FilterExpression = new PageVariableFragment(originalText.AsMemory(), expr, new List<JsCallExpression>(filters)); } /// <summary> /// Equalses the specified other. /// </summary> /// <param name="other">The other.</param> /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns> protected bool Equals(JsFilterExpressionStatement other) => Equals(FilterExpression, other.FilterExpression); /// <summary> /// Determines whether the specified <see cref="System.Object" /> is equal to this instance. /// </summary> /// <param name="obj">The <see cref="System.Object" /> to compare with this instance.</param> /// <returns><c>true</c> if the specified <see cref="System.Object" /> is equal to this instance; otherwise, <c>false</c>.</returns> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != this.GetType()) return false; return Equals((JsFilterExpressionStatement)obj); } /// <summary> /// Returns a hash code for this instance. /// </summary> /// <returns>A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.</returns> public override int GetHashCode() => FilterExpression != null ? FilterExpression.GetHashCode() : 0; } /// <summary> /// Class JsBlockStatement. /// Implements the <see cref="ServiceStack.Script.JsStatement" /> /// </summary> /// <seealso cref="ServiceStack.Script.JsStatement" /> public class JsBlockStatement : JsStatement { /// <summary> /// Gets the statements. /// </summary> /// <value>The statements.</value> public JsStatement[] Statements { get; } /// <summary> /// Initializes a new instance of the <see cref="JsBlockStatement" /> class. /// </summary> /// <param name="statements">The statements.</param> public JsBlockStatement(JsStatement[] statements) { Statements = statements; } /// <summary> /// Initializes a new instance of the <see cref="JsBlockStatement" /> class. /// </summary> /// <param name="statement">The statement.</param> public JsBlockStatement(JsStatement statement) { Statements = new[] {statement}; } /// <summary> /// Equalses the specified other. /// </summary> /// <param name="other">The other.</param> /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns> protected bool Equals(JsBlockStatement other) => Statements.EquivalentTo(other.Statements); /// <summary> /// Determines whether the specified <see cref="System.Object" /> is equal to this instance. /// </summary> /// <param name="obj">The <see cref="System.Object" /> to compare with this instance.</param> /// <returns><c>true</c> if the specified <see cref="System.Object" /> is equal to this instance; otherwise, <c>false</c>.</returns> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != this.GetType()) return false; return Equals((JsBlockStatement)obj); } /// <summary> /// Returns a hash code for this instance. /// </summary> /// <returns>A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.</returns> public override int GetHashCode() => Statements != null ? Statements.GetHashCode() : 0; } /// <summary> /// Class JsExpressionStatement. /// Implements the <see cref="ServiceStack.Script.JsStatement" /> /// </summary> /// <seealso cref="ServiceStack.Script.JsStatement" /> public class JsExpressionStatement : JsStatement { /// <summary> /// Gets the expression. /// </summary> /// <value>The expression.</value> public JsToken Expression { get; } /// <summary> /// Initializes a new instance of the <see cref="JsExpressionStatement" /> class. /// </summary> /// <param name="expression">The expression.</param> public JsExpressionStatement(JsToken expression) { Expression = expression; } /// <summary> /// Equalses the specified other. /// </summary> /// <param name="other">The other.</param> /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns> protected bool Equals(JsExpressionStatement other) => Equals(Expression, other.Expression); /// <summary> /// Determines whether the specified <see cref="System.Object" /> is equal to this instance. /// </summary> /// <param name="obj">The <see cref="System.Object" /> to compare with this instance.</param> /// <returns><c>true</c> if the specified <see cref="System.Object" /> is equal to this instance; otherwise, <c>false</c>.</returns> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != this.GetType()) return false; return Equals((JsExpressionStatement)obj); } /// <summary> /// Returns a hash code for this instance. /// </summary> /// <returns>A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.</returns> public override int GetHashCode() => Expression != null ? Expression.GetHashCode() : 0; } /// <summary> /// Class JsPageBlockFragmentStatement. /// Implements the <see cref="ServiceStack.Script.JsStatement" /> /// </summary> /// <seealso cref="ServiceStack.Script.JsStatement" /> public class JsPageBlockFragmentStatement : JsStatement { /// <summary> /// Gets the block. /// </summary> /// <value>The block.</value> public PageBlockFragment Block { get; } /// <summary> /// Initializes a new instance of the <see cref="JsPageBlockFragmentStatement" /> class. /// </summary> /// <param name="block">The block.</param> public JsPageBlockFragmentStatement(PageBlockFragment block) { Block = block; } /// <summary> /// Equalses the specified other. /// </summary> /// <param name="other">The other.</param> /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns> protected bool Equals(JsPageBlockFragmentStatement other) => Equals(Block, other.Block); /// <summary> /// Determines whether the specified <see cref="System.Object" /> is equal to this instance. /// </summary> /// <param name="obj">The <see cref="System.Object" /> to compare with this instance.</param> /// <returns><c>true</c> if the specified <see cref="System.Object" /> is equal to this instance; otherwise, <c>false</c>.</returns> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != this.GetType()) return false; return Equals((JsPageBlockFragmentStatement)obj); } /// <summary> /// Returns a hash code for this instance. /// </summary> /// <returns>A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.</returns> public override int GetHashCode() => Block != null ? Block.GetHashCode() : 0; }
9b4e2bfbaf7ebb1f0b967bd7a936942ab3369a0e
C#
cosminiv/CosminMisc
/CosminMisc/ConsoleApp1/Algorithms/BucketSort.cs
3.671875
4
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp1.Algorithms { class BucketSort { public int[] Sort(int[] data, int max) { int bucketCount = max + 1; int[] buckets = new int[bucketCount]; InsertionSort insertionSort = new InsertionSort(); // Distribute numbers in buckets. Each bucket contains how many times that number appeared in the input array. int bucketIndex = 0; for (int i = 0; i < data.Length; i++) { int n = data[i]; bucketIndex = n; buckets[bucketIndex]++; } // Iterate through the buckets in order to produce the sorted output int[] result = new int[data.Length]; int resultIndex = 0; for (int i = 0; i < buckets.Length; i++) { for (int j = buckets[i]; j > 0; j--) { result[resultIndex] = i; //if (resultIndex > 0) // Debug.Assert(result[resultIndex] >= result[resultIndex-1]); resultIndex++; } } return result; } } }
ccb595f76347202ca8024060aaa0a5f83efa1d04
C#
Dmitry-Bychenko/Gloson.Standard.Solution
/Gloson.Standard/Collections/Generic/Gloson.Collections.Generic.DisjointSets.cs
3.28125
3
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; namespace Gloson.Collections.Generic { //------------------------------------------------------------------------------------------------------------------- // /// <summary> /// Union Find /// </summary> /// <see cref="https://en.wikipedia.org/wiki/Disjoint-set_data_structure"/> // //------------------------------------------------------------------------------------------------------------------- public sealed class DisjointSets<T> : IReadOnlyList<IReadOnlyCollection<T>>, IEquatable<DisjointSets<T>> { #region Internal Classes private class OrderedComparerClass : IEqualityComparer<DisjointSets<T>> { /// <summary> /// Equals /// </summary> public bool Equals(DisjointSets<T> x, DisjointSets<T> y) { if (ReferenceEquals(x, y)) return true; else if (x is null || y is null) return false; if (x.ItemsComparer != y.ItemsComparer) return false; if (x.m_Items.Count != y.m_Items.Count) return false; for (int i = 0; i < x.m_Items.Count; ++i) if (!x.m_Items[i].SetEquals(y.m_Items[i])) return false; return true; } /// <summary> /// Hash Code /// </summary> public int GetHashCode(DisjointSets<T> obj) => obj is null ? 0 : obj.Count; } private class UnOrderedComparerClass : IEqualityComparer<DisjointSets<T>> { /// <summary> /// Equals /// </summary> public bool Equals(DisjointSets<T> x, DisjointSets<T> y) { if (ReferenceEquals(x, y)) return true; else if (x is null || y is null) return false; if (x.ItemsComparer != y.ItemsComparer) return false; if (x.m_Items.Count != y.m_Items.Count) return false; var data = x.m_Items .GroupBy(item => item.Count) .ToDictionary(group => group.Key, group => group.ToList()); foreach (var item in y.m_Items) { if (!data.TryGetValue(item.Count, out var list)) return false; if (!list.Any(hs => hs.SetEquals(item))) return false; } return true; } /// <summary> /// Hash Code /// </summary> public int GetHashCode(DisjointSets<T> obj) => obj is null ? 0 : obj.Count; } #endregion Internal Classes #region Private Data private readonly List<HashSet<T>> m_Items; #endregion Private Data #region Create /// <summary> /// Standard constructor /// </summary> public DisjointSets(IEqualityComparer<T> itemComparer, int count) { ItemsComparer = itemComparer ?? EqualityComparer<T>.Default; m_Items = count <= 0 ? new List<HashSet<T>>() : new List<HashSet<T>>(count); } /// <summary> /// Standard constructor /// </summary> public DisjointSets(IEqualityComparer<T> itemComparer) : this(itemComparer, 0) { } /// <summary> /// Standard constructor /// </summary> public DisjointSets(int count) : this(null, count) { } /// <summary> /// Standard constructor /// </summary> public DisjointSets() : this(null, 0) { } #endregion Create #region Public /// <summary> /// Comparer /// </summary> public IEqualityComparer<T> ItemsComparer { get; } /// <summary> /// Ordered comparer /// </summary> public static IEqualityComparer<DisjointSets<T>> OrderedComparer { get; } = new OrderedComparerClass(); /// <summary> /// UnOrdered comparer /// </summary> public static IEqualityComparer<DisjointSets<T>> UnOrderedComparer { get; } = new UnOrderedComparerClass(); /// <summary> /// Try Union /// </summary> /// <param name="left">left index to union</param> /// <param name="right">right index to union</param> public bool TryUnion(int left, int right) { if (left < 0 || right < 0 || left >= m_Items.Count || right >= m_Items.Count) return false; else if (left == right) return true; if (left < right) m_Items[left].UnionWith(m_Items[right]); else m_Items[right].UnionWith(m_Items[left]); m_Items.RemoveAt(Math.Max(left, right)); return true; } /// <summary> /// Union /// </summary> /// <param name="left">left index to union</param> /// <param name="right">right index to union</param> public void Union(int left, int right) { if (left < 0 || left >= m_Items.Count) throw new ArgumentOutOfRangeException(nameof(left)); else if (right < 0 || right >= m_Items.Count) throw new ArgumentOutOfRangeException(nameof(right)); else if (left == right) return; if (left < right) m_Items[left].UnionWith(m_Items[right]); else m_Items[right].UnionWith(m_Items[left]); m_Items.RemoveAt(Math.Max(left, right)); } /// <summary> /// Find index which contains Value /// </summary> /// <param name="value">Value to find</param> /// <return>Index or -1</return> public int Find(T value) { for (int i = m_Items.Count - 1; i >= 0; --i) if (m_Items[i].Contains(value)) return i; return -1; } /// <summary> /// Find index which contains Value or create a new index if Value is not found /// </summary> /// <param name="value">Value to find</param> /// <return>Index</return> public int FindOrCreate(T value) { for (int i = m_Items.Count - 1; i >= 0; --i) if (m_Items[i].Contains(value)) return i; m_Items.Add(new HashSet<T>(ItemsComparer) { value }); return m_Items.Count - 1; } /// <summary> /// Try adding pair; pair is added if and only if both left and right are NOT in the same set /// </summary> /// <param name="left">left item</param> /// <param name="right">right item</param> /// <param name="index">index of set the pair has been added</param> /// <returns>true if pair is added, false otherwise</returns> public bool TryAddPair(T left, T right, out int index) { int leftIndex = Find(left); int rightIndex = Find(right); if (leftIndex >= 0 && rightIndex >= 0) { index = Math.Min(leftIndex, rightIndex); if (leftIndex == rightIndex) return false; Union(leftIndex, rightIndex); return true; } else if (leftIndex >= 0) { index = leftIndex; m_Items[index].Add(left); return true; } else if (rightIndex >= 0) { index = rightIndex; m_Items[index].Add(left); return true; } m_Items.Add(new HashSet<T>(ItemsComparer) { left, right }); index = m_Items.Count - 1; return true; } /// <summary> /// To String (debug) /// </summary> public override string ToString() { StringBuilder sb = new(); int length = (m_Items.Count - 1).ToString().Length; for (int i = 0; i < m_Items.Count; ++i) { if (sb.Length > 0) sb.AppendLine(); sb.Append("set #"); sb.Append(i.ToString().PadLeft(length)); sb.Append(" : {"); sb.Append(string.Join(", ", m_Items[i])); sb.Append('}'); } return sb.ToString(); } #endregion Public #region IReadOnlyList<ReadOnlyCollection<T>> /// <summary> /// Count /// </summary> public int Count => m_Items.Count; /// <summary> /// Set by it's index /// </summary> /// <param name="index">index</param> /// <returns>Set as read only colelction</returns> public IReadOnlyCollection<T> this[int index] { get { if (index < 0 || index >= m_Items.Count) throw new ArgumentOutOfRangeException(nameof(index)); return m_Items[index]; } } /// <summary> /// Typed Enumerator /// </summary> public IEnumerator<IReadOnlyCollection<T>> GetEnumerator() => m_Items.GetEnumerator(); /// <summary> /// Typeless enumerator /// </summary> IEnumerator IEnumerable.GetEnumerator() => this.GetEnumerator(); #endregion IReadOnlyList<ReadOnlyCollection<T>> #region IEquatable<UnionFind<T>> /// <summary> /// Equals /// </summary> public bool Equals(DisjointSets<T> other) => UnOrderedComparer.Equals(this, other); /// <summary> /// Equals /// </summary> public override bool Equals(object o) => Equals(o as DisjointSets<T>); /// <summary> /// Hash Code /// </summary> public override int GetHashCode() => UnOrderedComparer.GetHashCode(this); #endregion IEquatable<UnionFind<T>> } }
9171eb6e9531bbc433844775e1e0290f62105172
C#
pollo-garat/Technical-Challenge-Jam-City
/Assets/Pathfinding/Scripts/Gameplay/Domain/Views/WorldGrid.cs
2.578125
3
using System; using Pathfinding.Scripts.Gameplay.Domain.Services; using Pathfinding.Scripts.Gameplay.Domain.ValueObjects; using UniRx; using UnityEngine; namespace Pathfinding.Scripts.Gameplay.Domain.Views { public class WorldGrid : MonoBehaviour { public IObservable<HexaTile> OnTileClicked => onTileClicked; readonly ISubject<HexaTile> onTileClicked = new Subject<HexaTile>(); public GameObject HexPrefab; public int GridWidth; public int GridHeight; public float Gap; public Material GrassMaterial; public Material ForestMaterial; public Material DesertMaterial; public Material MountainMaterial; public Material WaterMaterial; float hexWidth = 1f; float hexHeight = 1f; Vector3 startPosition; HexaTile[,] grid; UnityHexaTile[,] unityGird; public void CreateGrid(HexaTile[,] grid, GridNeighbours girdNeighbours) { this.grid = grid; unityGird = new UnityHexaTile[GridWidth, GridHeight]; AddGap(); CalculateStartPosition(); Create(); } public UnityHexaTile[,] GetUnityGrid() => unityGird; void Create() { foreach (var tile in grid) { var hex = Instantiate(HexPrefab, transform); var gridPosition = new Vector2(tile.X, tile.Y); var unityHexaTile = hex.GetComponent<UnityHexaTile>(); unityHexaTile.Populate(tile); hex.transform.position = CalculateWorldPosition(gridPosition); hex.name = "Hexagon " + tile.X + "|" + tile.Y + " Type " + tile.Configuration.Type; SetTileMaterial(hex, tile.Configuration.Type); unityGird[tile.X, tile.Y] = unityHexaTile; unityHexaTile.OnTileClicked.Subscribe(onTileClicked.OnNext); } } void SetTileMaterial(GameObject hex, TileType type) { var unityHexaTile = hex.GetComponent<UnityHexaTile>(); switch (type) { case TileType.Grass: unityHexaTile.SetInitialMaterial(GrassMaterial); break; case TileType.Forest: unityHexaTile.SetInitialMaterial(ForestMaterial); break; case TileType.Desert: unityHexaTile.SetInitialMaterial(DesertMaterial); break; case TileType.Mountain: unityHexaTile.SetInitialMaterial(MountainMaterial); break; case TileType.Water: unityHexaTile.SetInitialMaterial(WaterMaterial); break; default: unityHexaTile.SetInitialMaterial(GrassMaterial); break; } } void AddGap() { hexWidth += hexWidth * Gap; hexHeight += hexHeight * Gap; } void CalculateStartPosition() { float offset = 0; if (GridHeight / 2 % 2 != 0) offset = hexWidth / 2; var x = -hexWidth * (GridWidth / 2) - offset; var z = hexHeight * 0.75f * (GridHeight / 2); startPosition = new Vector3(x, 0, z); } Vector3 CalculateWorldPosition(Vector2 gridPosition) { float offset = 0; if (gridPosition.y % 2 != 0) offset = hexWidth / 2; var x = startPosition.x + gridPosition.x * hexWidth + offset; var z = startPosition.z - gridPosition.y * hexHeight * 0.75f; return new Vector3(x, 0, z); } } }
0c0dfe6c21080d8ba6ad06328a352889a2a7e9c9
C#
gordonwatts/JetCutStudies
/libDataAccess/CutConstants.cs
2.734375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace libDataAccess { /// <summary> /// Some cut constants for the various files - this is common. /// </summary> public static class CutConstants { /// <summary> /// The smallest distance that an LLP can decay and be considered signal for a CalRatio jet. /// Units are mm. /// </summary> public const double InnerDistanceForSignalLLPBarrelDecay = 2 * 1000; /// <summary> /// The smallest disntace along z that an LLP decay can be considered signal for a CalRatio jet. /// </summary> public const double InnerDistanceForSignalLLPEndcapDecay = 4 * 1000; /// <summary> /// Cut for the log ratio when doing straight cuts. /// </summary> public static double LogRatioCut = 1.2; /// <summary> /// Cut in GeV for a track to violate isolation. /// </summary> public static double IsolationTrackPtCut = 2.0; /// <summary> /// How many tracks are allowed before isolation is violated? /// </summary> public static int IsolationTrackCountAllowed = 0; /// <summary> /// What limit should we have for jet eta? /// </summary> public static double JetEtaLimit = 2.5; } }
3d9fd367dad85ab0252c125fa92b75d5ec03b169
C#
adhikari-chayan/dotnetcore
/ReactiveExtensions/ObserverPattern/ObserverPattern/Application.cs
2.796875
3
namespace ObserverPattern { public class Application { public int JobId { get; set; } public string ApplicantName { get; set; } public Application(int jobId, string applicantName) { JobId = jobId; ApplicantName = applicantName; } } }
0a27653aa81f8c93809f932352d94618b6248ed6
C#
JeremyPlott/PWListHomework
/PWListHomework/Program.cs
3.21875
3
using System; using System.Collections.Generic; namespace PWListHomework { class Program { static void Main(string[] args) { var PWDict = new Dictionary<string, string>(); //dictionary is good collection tool when you don't want to allow duplicates. Cannot duplicate Key values. PWDict.Add("YouTube.com", "password1"); PWDict.Add("Yahoo.com", "password2"); PWDict.Add("gmail.com", "password3"); PWDict.Add("GitHub.com", "password4"); PWDict.Add("Bank.com", "password5"); PWDict.Add("Wikipedia.org", "password6"); PWDict.Add("RuneScape.com", "password7"); PWDict.Add("BDO.com", "password8"); PWDict.Add("Maplestory.com", "password9"); PWDict.Add("PassList.gov", "password10"); PWDict.Add("Car.com", "password11"); PWDict.Add("Glasses.net", "password12"); var password = PWDict["Maplestory.com"]; Console.WriteLine($"The password for Maplestory.com is {password}"); foreach(var keyValpair in PWDict) { //keyvalpair has both the key and value added in the dictionary. Console.WriteLine($"The password for {keyValpair.Key} is {keyValpair.Value}"); } var allkeys = PWDict.Keys; var allvalues = PWDict.Values; var exists = PWDict.ContainsKey("Bank.com"); } } }
55e00cb348ee4137b1f33b5a6fb050a44cbecfa7
C#
radtek/IO2
/DllProject/models/Messages/DivideProblemMessage.cs
2.515625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Serialization; namespace DllProject.Messages { [XmlRoot(ElementName = "DivideProblem", Namespace = "http://www.mini.pw.edu.pl/ucc/")] public class DivideProblemMessage : Message { public string ProblemType { get; set; } public ulong Id { get; set; } public byte[] Data {get;set;} public ulong ComputationalNodes { get; set; } public DivideProblemMessage() { } public DivideProblemMessage(string problemType,ulong id, byte[] data, ulong computationalNodes) { ProblemType = problemType; Id = id; Data = new byte[data.Length]; Array.Copy(data, Data,data.Length); ComputationalNodes = computationalNodes; } } }
7fdb8f0b45f4d360d53f1befd9e03d10da8f6ed1
C#
wernight/papps-manager
/PAppsManager/Core/PApps/EnvironmentVariables.cs
3.09375
3
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.RegularExpressions; namespace PAppsManager.Core.PApps { /// <summary> /// Expand/contract common and extra environment variables. /// /// Example: "%ProgramFiles%" to/from "C:\Program Files". /// </summary> internal class EnvironmentVariables { private readonly Dictionary<string, string> _replacementsDictionary; public EnvironmentVariables() { // Prepare an ordered dictionary of Key => Value. _replacementsDictionary = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase); foreach (string specialFolderName in Enum.GetNames(typeof(Environment.SpecialFolder))) { var specialFolder = (Environment.SpecialFolder)Enum.Parse(typeof(Environment.SpecialFolder), specialFolderName); string folderPath = Environment.GetFolderPath(specialFolder); if (!string.IsNullOrWhiteSpace(folderPath)) { Add(specialFolderName, folderPath); } } } public void Add(string key, string value) { _replacementsDictionary.Add(key, value); } public string Expand(string value) { return Regex.Replace(value, @"%([^%]*)%", Evaluator); } public string Contract(string value) { char invalid = Path.GetInvalidPathChars().First(); // In order to work properly the path should not contain that value. if (value.Contains(invalid)) throw new Exception("The path contain an invalid character: " + invalid); // Replace all values by their keys. return _replacementsDictionary .OrderByDescending(pair => pair.Value.Length) // That's more a heuristic to prefer %ProgramFiles(x86)% or %ProgramFiles% in 32-bit OS. .ThenByDescending(pair => pair.Key.Length) .Aggregate(value, (current, kvp) => Regex.Replace(current, Regex.Escape(kvp.Value), Regex.Escape(invalid + kvp.Key + invalid), RegexOptions.IgnoreCase | RegexOptions.CultureInvariant)) .Replace("%", "%%") .Replace(invalid, '%'); } private string Evaluator(Match match) { if (match.Value == "%%") return "%"; string expandedPath; if (_replacementsDictionary.TryGetValue(match.Groups[1].Value, out expandedPath)) return expandedPath; return match.Value; } } }
40113e8d22c3b92b08b077011175d866815cf481
C#
Kawser-nerd/CLCDSA
/Source Codes/CodeJamData/09/11/10.cs
3.5625
4
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace CodeJam { class MultibaseHappiness { int minHappyNumber(int[] bases) { int n = 2; while (true) { bool allHappy = true; foreach (int b in bases) { if (!isHappy(b, n)) { allHappy = false; break; } } if (allHappy) return n; n++; } } bool isHappy(int b, int n) { List<int> nn = new List<int>(); while (true) { if (n == 1) return true; if (nn.Contains(n)) return false; nn.Add(n); int newn = 0; while (n > 0) { int digit = n%b; n /= b; newn += digit*digit; } n = newn; } } public static void Main() { StreamReader sr = new StreamReader("A-small-attempt0.in"); StreamWriter sw = new StreamWriter("MultibaseHappiness.out"); var obj = new MultibaseHappiness(); int testsCount = int.Parse(sr.ReadLine()); for (int i = 0; i < testsCount; i++) { string[] bases = sr.ReadLine().Split(' '); int result = obj.minHappyNumber(bases.Select(s=>int.Parse(s)).ToArray()); sw.WriteLine("Case #{0}: {1}", i + 1, result); } sr.Close(); sw.Close(); } } }
9cfc414eceb82a3397ca994332e65b3ee6d33d86
C#
ivry216/dynamical-system-modeling
/LdeModeling/Models/Dynamical/SystemsS/CascadedPathawaySystemParameters.cs
2.859375
3
namespace TestApp.Models.Dynamical.SystemsS { public class CascadedPathawaySystemParameters { #region Fields private int _numberOfInputs; private int _numberOfOutputs; private int _sumOfInputsAndOutputs; private double[] _alpha; private double[] _betta; private double[,] _gMatrix; private double[,] _hMatrix; #endregion Fields #region Properties public double[] Alpha => _alpha; public double[] Betta => _betta; public double[,] G => _gMatrix; public double[,] H => _hMatrix; public int OutputsNumber => _numberOfOutputs; #endregion Properties #region Constructor public CascadedPathawaySystemParameters(int numberOfInputs, int numberOfOutputs) { _numberOfInputs = numberOfInputs; _numberOfOutputs = numberOfOutputs; _sumOfInputsAndOutputs = _numberOfInputs + _numberOfOutputs; _alpha = new double[numberOfOutputs]; _betta = new double[numberOfOutputs]; _gMatrix = new double[numberOfOutputs, _sumOfInputsAndOutputs]; _hMatrix = new double[numberOfOutputs, _sumOfInputsAndOutputs]; } #endregion Constructor #region Methods public void AssignWithArray(double[] parameters) { // Current vector position int vectorPosition = 0; // Assign vectors for (int i = 0; i < _numberOfOutputs; i++) { _alpha[i] = parameters[vectorPosition]; vectorPosition++; } for (int i = 0; i < _numberOfOutputs; i++) { _betta[i] = parameters[vectorPosition]; vectorPosition++; } // Assign matrixes for (int i = 0; i < _numberOfOutputs; i++) { for (int j = 0; j < _sumOfInputsAndOutputs; j++) { _gMatrix[i, j] = parameters[vectorPosition]; vectorPosition++; } } for (int i = 0; i < _numberOfOutputs; i++) { for (int j = 0; j < _sumOfInputsAndOutputs; j++) { _hMatrix[i, j] = parameters[vectorPosition]; vectorPosition++; } } } #endregion Methods } }
c0ca00b03f122e200673f15dcf8ef5407ba73a35
C#
tzachshabtay/MonoAGS
/Source/AGS.API/Misc/Geometry/RectangleF.cs
3.453125
3
using System; namespace AGS.API { /// <summary> /// Represents a rectangle in 2D space. /// </summary> public struct RectangleF { private readonly float _x, _y, _width, _height; /// <summary> /// Initializes a new instance of the <see cref="T:AGS.API.Rectangle"/> struct. /// </summary> /// <param name="x">The x coordinate.</param> /// <param name="y">The y coordinate.</param> /// <param name="width">Width.</param> /// <param name="height">Height.</param> public RectangleF(float x, float y, float width, float height) { _x = x; _y = y; _width = width; _height = height; } /// <summary> /// Gets the x coordinate. /// </summary> /// <value>The x.</value> public float X => _x; /// <summary> /// Gets the y coordinate. /// </summary> /// <value>The y.</value> public float Y => _y; /// <summary> /// Gets the width. /// </summary> /// <value>The width.</value> public float Width => _width; /// <summary> /// Gets the height. /// </summary> /// <value>The height.</value> public float Height => _height; /// <summary> /// Checkes if the rectangle contains the specified point. /// </summary> /// <returns>The contains.</returns> /// <param name="point">Point.</param> public bool Contains(Vector2 point) => point.X >= X && point.X <= X + Height && point.Y <= Y && point.Y >= Y - Height; public override string ToString() => $"[RectangleF: X={X:0.##}, Y={Y:0.##}, Width={Width:0.##}, Height={Height:0.##}]"; [CustomStringValue(CustomStringApplyWhen.CanWrite)] public string ToInspectorString() => $"{X:0.##},{Y:0.##},{Width:0.##},{Height:0.##}"; public override bool Equals(Object obj) { RectangleF? other = obj as RectangleF?; if (other == null) return false; return Equals(other.Value); } public bool Equals(RectangleF other) { return MathUtils.FloatEquals(X, other.X) && MathUtils.FloatEquals(Y, other.Y) && MathUtils.FloatEquals(Width, other.Width) && MathUtils.FloatEquals(Height, other.Height); } public override int GetHashCode() => (((int)X).GetHashCode() * 397) ^ ((int)Y).GetHashCode(); public static implicit operator RectangleF((float x, float y, float width, float height) rect) => new RectangleF(rect.x, rect.y, rect.width, rect.height); public void Deconstruct(out float x, out float y, out float width, out float height) { x = this.X; y = this.Y; width = this.Width; height = this.Height; } } }
2445f0672890b44e2aa36c25207a0c2efec0d117
C#
mc-imperial/sctbench
/benchmarks/chess-m/UnitTest/UnitTest/badthread.cs
2.75
3
/******************************************************** * * * Copyright (C) Microsoft. All rights reserved. * * * ********************************************************/ using System; using System.Text; using System.Threading; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace UnitTest { /// <summary> /// Summary description for badthread /// </summary> [TestClass] public class badthread { [TestMethod] [HostType("Chess")] // test is inconclusive, but we don't have a good error message about it. [TestProperty("ChessExpectedResult","invalidtest")] public void ThreadNotEnded() { // nobody does a set, so child thread never ends var eventHandle = new EventWaitHandle(false, EventResetMode.AutoReset); Thread child = new Thread(() => { eventHandle.WaitOne(); }); child.Start(); Thread.Sleep(1); // oops, we don't join } [TestMethod] [HostType("Chess")] // test is inconclusive, but we don't have a good error message about it. [TestProperty("ChessExpectedResult", "invalidtest")] public void ThreadNotEnded2() { Thread child = new Thread(() => { }); // child isn't even started, but CHESS counts it as running! } static int count = 0; [TestMethod] [HostType("Chess")] // test is inconclusive, but we don't have a good error message about it. [TestProperty("ChessExpectedResult", "incompleteinterleavingcoverage")] public void DoesntResetState() { Thread child = new Thread(() => { Thread.Sleep(1); }); child.Start(); if (count % 2 == 0) Thread.Sleep(1); count++; child.Join(); } } }
da373347889afdd5f380023627c1657c63598d97
C#
chelseashin/C-language-study
/07_WalkController.cs
2.703125
3
using System.Collections; using System.Collections.Generic; using UnityEngine; public class WalkController : MonoBehaviour { Animator animator; void Start() { animator = GetComponent<Animator>(); } void Update() { // Front if (Input.GetKey(KeyCode.W) == true) { animator.SetFloat("Walk", 1f, 0.1f, Time.deltaTime); } // Back else if (Input.GetKey(KeyCode.S) == true) { } // Left else if (Input.GetKey(KeyCode.A) == true) { animator.SetFloat("Direction", -1f, 0.1f, Time.deltaTime); } // Right else if (Input.GetKey(KeyCode.D) == true) { animator.SetFloat("Direction", 1f, 0.1f, Time.deltaTime); } else { animator.SetFloat("Direction", 0f, 0.1f, Time.deltaTime); animator.SetFloat("Walk", 0f, 0.1f, Time.deltaTime); // animator.SetFloat() 함수 : 우리가 지정한 변수에 값 세팅 } } }
7fd072711a13542885653730b11c327e8e5f261a
C#
Taylor-Fowler/TheWorkforce2D
/Assets/Entities/EntityData.cs
2.8125
3
using System; using UnityEngine; namespace TheWorkforce.Entities { using Interfaces; public abstract class EntityData : ScriptableObject, IEntityDisplay { public ushort Id; public string Name; public string Description; public Sprite Sprite; public byte MaxStackSize = 32; public byte Width = 1; public byte Height = 1; public virtual void Initialise(ushort id) { Id = id; } public virtual int PacketSize() { return sizeof(int) * 2; } public abstract void Display(EntityView entityView); /// <summary> /// Create Instance is called when an entity is added to the game, this can be through one of the following ways: /// 1. A new chunk is generated /// 2. World data is loaded /// 3. A player places an item in the world /// </summary> public abstract EntityInstance CreateInstance(uint id, int x, int y, Action<uint> onDestroy); /// <summary> /// Create Instance is called when an entity is added to the game, this can be through one of the following ways: /// 1. A new chunk is generated /// 2. World data is loaded /// 3. A player places an item in the world /// </summary> /// <param name="arr"></param> public abstract EntityInstance CreateInstance(uint id, int x, int y, Action<uint> onUnload, byte[] arr); public virtual GameObject Template() { GameObject gameObject = new GameObject(Name); gameObject.transform.localScale = new Vector3(Width, Height, 1.0f); gameObject.AddComponent<BoxCollider2D>(); return gameObject; } } }
6f8ca8cc248d31afe1b5d556e812437c9bb81c2d
C#
shendongnian/download4
/first_version_download2/429227-37805112-120372419-4.cs
2.921875
3
static void Main() { // allow more connections at a time ServicePointManager.DefaultConnectionLimit = 30; // don't wait the 100ms every request do ServicePointManager.Expect100Continue = false; for (int i = 0; i <= 200; i++) { var lines = File.ReadAllLines(@"D:\file_" + i.ToString().PadLeft(5, '0') + ".txt"); foreach (var line in lines) { Task.Run(() => { try { WebRequest request = WebRequest.Create("ftp://myftp/dir/" + line); request.Method = WebRequestMethods.Ftp.MakeDirectory; request.Credentials = new NetworkCredential("user", "pass"); request.GetResponse(); } catch (Exception ex) { } } ); } } }
4b81f98a260fc51b34cd97f14f79d2d8cc4b07b5
C#
donpp46/yogaa
/framework/core/Service.cs
2.625
3
using System; using System.Collections.Generic; using System.Text; using System.Web.UI; using System.Web.Script.Serialization; using System.Reflection; using System.Linq; namespace Medtrix.WebService { internal class Response { public Boolean iserror = false; public String message = String.Empty; public Object result = null; public int code = 0; } internal class Request<T> { public String service = String.Empty; public String command = String.Empty; public T Data; } public class ServiceException : Exception { public UInt64 ErrorCode = 0; public String ErrorMessage = String.Empty; public ServiceException(UInt64 ErrorCode, String ErrorMessage) { Exception ex = new Exception(); ex.Data["ErrorCode"] = ErrorCode; ex.Data["ErrorMessage"] = ErrorMessage; throw ex; } } public interface Service { } public class DateTimeJavaScriptConverter : JavaScriptConverter { public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer) { return new JavaScriptSerializer().ConvertToType(dictionary, type); } public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer) { if (!(obj is DateTime)) return null; return new CustomString(((DateTime)obj).ToUniversalTime().ToString("O")); } public override IEnumerable<Type> SupportedTypes { get { return new[] { typeof(DateTime) }; } } private class CustomString : Uri, IDictionary<string, object> { public CustomString(string str) : base(str, UriKind.Relative) { } void IDictionary<string, object>.Add(string key, object value) { throw new NotImplementedException(); } bool IDictionary<string, object>.ContainsKey(string key) { throw new NotImplementedException(); } ICollection<string> IDictionary<string, object>.Keys { get { throw new NotImplementedException(); } } bool IDictionary<string, object>.Remove(string key) { throw new NotImplementedException(); } bool IDictionary<string, object>.TryGetValue(string key, out object value) { throw new NotImplementedException(); } ICollection<object> IDictionary<string, object>.Values { get { throw new NotImplementedException(); } } object IDictionary<string, object>.this[string key] { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } void ICollection<KeyValuePair<string, object>>.Add(KeyValuePair<string, object> item) { throw new NotImplementedException(); } void ICollection<KeyValuePair<string, object>>.Clear() { throw new NotImplementedException(); } bool ICollection<KeyValuePair<string, object>>.Contains(KeyValuePair<string, object> item) { throw new NotImplementedException(); } void ICollection<KeyValuePair<string, object>>.CopyTo(KeyValuePair<string, object>[] array, int arrayIndex) { throw new NotImplementedException(); } int ICollection<KeyValuePair<string, object>>.Count { get { throw new NotImplementedException(); } } bool ICollection<KeyValuePair<string, object>>.IsReadOnly { get { throw new NotImplementedException(); } } bool ICollection<KeyValuePair<string, object>>.Remove(KeyValuePair<string, object> item) { throw new NotImplementedException(); } IEnumerator<KeyValuePair<string, object>> IEnumerable<KeyValuePair<string, object>>.GetEnumerator() { throw new NotImplementedException(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw new NotImplementedException(); } } } public class ServiceManager { private static Dictionary<string, Type> _serviceClasses = new Dictionary<string, Type>(); private static MethodInfo jsonDeserializeMethod = null; private ServiceManager() { } static ServiceManager() { //foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies()) { Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly(); foreach (Type type in assembly.GetTypes()) { if (typeof(Service).IsAssignableFrom(type) && type.IsClass) _serviceClasses[type.Name] = type; } } jsonDeserializeMethod = typeof(JavaScriptSerializer).GetMethods().FirstOrDefault(method => method.Name == "Deserialize" & method.IsGenericMethod); } private static Object GetService(string serviceName) { Object service = null; Type serviceClass = null; if (_serviceClasses.TryGetValue(serviceName, out serviceClass)) { service = Activator.CreateInstance(serviceClass); } return service; } public static void Register(Type service) { //if(!typeof(Service).IsAssignableFrom(service)) // throw new Exception(String.Format("Service {0} does not implement IService", service.Name)); _serviceClasses[service.Name] = service; } public static String DoService(String packet, System.Web.UI.Page ExecutingPage) { JavaScriptSerializer _json = new JavaScriptSerializer(); _json.MaxJsonLength = int.MaxValue; _json.RegisterConverters( new JavaScriptConverter[] { new DateTimeJavaScriptConverter()}); Request<Object> request = new Request<Object>(); Response response = new Response(); try { //Logger.Log(data); // convert the request packet into generic structure request = _json.Deserialize<Request<Object>>(packet); } catch (Exception) { if (_json == null) return "Failed to load json parser."; response.iserror = true; response.message = "Invalid data format."; response.code = 999; } try { if (request == null) throw new Exception("Invalid request"); Object service = GetService(request.service); if(service == null) throw new Exception("Invalid service requested."); MethodInfo method = service.GetType().GetMethod(request.command); ParameterInfo[] parameters = method.GetParameters(); if (parameters.Length == 2) { Type type = typeof(Request<>).MakeGenericType(parameters[0].ParameterType); MethodInfo deserialize = jsonDeserializeMethod.MakeGenericMethod(new Type[] { type }); var requestData = deserialize.Invoke(_json, new object[] { packet }); var dataField = type.GetField("Data"); object data = dataField.GetValue(requestData); response.result = method.Invoke(service, new Object[] { data, ExecutingPage }); } } catch (Exception ex) { response.iserror = true; response.message = ex.Message; if(ex.InnerException != null) response.message += ". Inner Exception : " + Convert.ToString(ex.InnerException.Message.ToString()); response.code = Convert.ToInt32((ex.Data["ErrorCode"] ?? (int)999).ToString()); response.result = ex.Data["result"] ?? new Object(); } //Logger.Log(_json.Serialize(response)); return _json.Serialize(response); } } }
48e0356cecd856a98f3831534eb79a5059b04759
C#
tgntr/emusic3-ddd
/Domain/Catalog/Models/MusicRecord.Fakes.cs
2.6875
3
namespace SimpleMusicStore.Domain.Catalog.Models { using Bogus; using FakeItEasy; using System; using System.Collections.Generic; using System.Linq; public class MusicRecordFakes { public class MusicRecordDummyFactory : IDummyFactory { public bool CanCreate(Type type) => type == typeof(MusicRecord); public object? Create(Type type) => Data.GenerateFakeMusicRecord(); public Priority Priority => Priority.Default; } public static class Data { public static int validFakeId = 1; public static string validFakeTitle = "MusicRecord"; public static IEnumerable<Artist> validFakeArtists = new List<Artist> { new Artist(validFakeId, "Artist", "https://image.url/image.jpg") }; public static Label validFakeLabel = new Label(validFakeId, "Label", "https://image.url/image.jpg"); public static DateTime validFakeDateReleased = DateTime.UtcNow; public static Genre validFakeGenre = new Genre(new List<string> { "electronic" }, new List<string> { "minimal", "techno" }); public static AudioFormat validFakeAudioFormat = AudioFormat.Vinyl; public static decimal validFakePrice = 1; public static IEnumerable<Track> validFakeTracklist = new List<Track> { new Track("track", "10:00", "https://audio.url/audio.mp3") }; public static string validFakeImageUrl = "https://image.url/image.jpg"; public static string invalidFakeString = string.Empty; public static IEnumerable<Artist> invalidFakeArtists = new List<Artist>(); public static DateTime invalidFakeDateReleased = new DateTime(1800, 1, 1); public static IEnumerable<string> invalidFakeStringCollection = new List<string>(); public static decimal invalidFakePrice = 0; public static IEnumerable<Track> invalidFakeTracklist = new List<Track>(); public static string invalidFakeImageUrl = "https://imageurl/image.jpg"; public static IEnumerable<MusicRecord> GetCarAds(int count = 10) => Enumerable .Range(1, count) .Select(i => GenerateFakeMusicRecord(i)) .Concat(Enumerable .Range(count + 1, count * 2) .Select(i => GenerateFakeMusicRecord(i, true))) .ToList(); public static MusicRecord GenerateFakeMusicRecord(int id = 1, bool isActive = true) { return new Faker<MusicRecord>() .CustomInstantiator(f => new MusicRecord( id, validFakeTitle, validFakeArtists, validFakeLabel, validFakeDateReleased, validFakeGenre, validFakeAudioFormat, validFakePrice, validFakeTracklist, validFakeImageUrl, isActive)) .Generate(); } } } }
c60c19e86ef2157c604da647314a81e9ccd28be6
C#
jcwmoore/ampache-net
/JohnMoore.AmpacheNet/TaskExtensions.cs
2.765625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace System.Threading.Tasks { /// <summary> /// http://blogs.msdn.com/b/pfxteam/archive/2011/11/10/10235834.aspx /// </summary> public static class TaskExtensions { internal struct VoidTypeStruct { } public static Task WithTimeout(this Task task, TimeSpan timeout) { if (task.IsCompleted || (timeout <= TimeSpan.Zero)) { return task; } // tcs.Task will be returned as a proxy to the caller var tcs = new TaskCompletionSource<VoidTypeStruct>(); // Set up a timer to complete after the specified timeout period Timer timer = new Timer(state => { var myTcs = (TaskCompletionSource<VoidTypeStruct>)state; myTcs.TrySetException(new TimeoutException()); if (task is CancelableTask) { ((CancelableTask)task).Cancel(); } }, tcs, (int)timeout.TotalMilliseconds, Timeout.Infinite); // Wire up the logic for what happens when source task completes var tuple = Tuple.Create(timer, tcs); task.ContinueWith((antecedent) => { tuple.Item1.Dispose(); MarshalTaskResults(antecedent, tuple.Item2); }, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.NotOnCanceled, TaskScheduler.Default); return tcs.Task; } public static Task<TResult> WithTimeout<TResult>(this Task<TResult> task, TimeSpan timeout) { if (task.IsCompleted || (timeout <= TimeSpan.Zero)) { return task; } // tcs.Task will be returned as a proxy to the caller var tcs = new TaskCompletionSource<TResult>(); // Set up a timer to complete after the specified timeout period Timer timer = new Timer(state => { var myTcs = (TaskCompletionSource<TResult>)state; myTcs.TrySetException(new TimeoutException()); if (task is CancelableTask<TResult>) { ((CancelableTask<TResult>)task).Cancel(); } }, tcs, (int)timeout.TotalMilliseconds, Timeout.Infinite); // Wire up the logic for what happens when source task completes var tuple = Tuple.Create(timer, tcs); task.ContinueWith((antecedent) => { //var tuple = (Tuple<Timer, TaskCompletionSource<TResult>>)state; tuple.Item1.Dispose(); MarshalTaskResults(antecedent, tuple.Item2); }, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.NotOnCanceled, TaskScheduler.Default); return tcs.Task; } internal static void MarshalTaskResults<TResult>(Task source, TaskCompletionSource<TResult> proxy) { switch (source.Status) { case TaskStatus.Faulted: proxy.TrySetException(source.Exception); break; case TaskStatus.Canceled: proxy.TrySetCanceled(); break; case TaskStatus.RanToCompletion: Task<TResult> castedSource = source as Task<TResult>; proxy.TrySetResult( castedSource == null ? default(TResult) : // source is a Task castedSource.Result); // source is a Task<TResult> break; } } public static CancelableTask StartCancelable(this TaskFactory factory, Action<CancellationToken> action) { var task = new CancelableTask(action, new CancellationTokenSource(), factory.CreationOptions); task.Start(); return task; } public static CancelableTask<TResult> StartCancelable<TResult>(this TaskFactory factory, Func<CancellationToken, TResult> action) { var task = new CancelableTask<TResult>(action, new CancellationTokenSource(), factory.CreationOptions); task.Start(); return task; } } public class CancelableTask : Task { private readonly CancellationTokenSource _source; public CancellationToken CancelationToken { get { return _source.Token; } } public CancelableTask(Action<CancellationToken> action, CancellationTokenSource source, TaskCreationOptions options) : base(Downcast(action), source.Token, source.Token, options) { _source = source; } private static Action<object> Downcast(Action<CancellationToken> a) { return (o) => a.Invoke((CancellationToken)o); } public void Cancel() { _source.Cancel(); } } public class CancelableTask<TResult> : Task<TResult> { private readonly CancellationTokenSource _source; public CancellationToken CancelationToken { get { return _source.Token; } } public CancelableTask(Func<CancellationToken, TResult> action, CancellationTokenSource source, TaskCreationOptions options) : base(Downcast(action), source.Token, source.Token, options) { _source = source; } private static Func<object, TResult> Downcast(Func<CancellationToken, TResult> a) { return (o) => a.Invoke((CancellationToken)o); } public void Cancel() { _source.Cancel(); } } }
f7d9ab863c79d8e5f20475ba2cc3f83925bb040f
C#
EvertonSolon/ImpactaAspNetAvancado
/Loja.Dominio/Carro.cs
2.671875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Loja.Dominio { public class Carro { public string Marca { get; set; } public string Modelo { get; set; } public string Cor { get; set; } void InstanciarCarro() { var meuCarro = new Carro(); meuCarro.Cor = "vermelho"; meuCarro.Marca = "Ford"; meuCarro.Modelo = "Ka"; var carroAntonio = new Carro { Cor = "Azul", Marca = "GM", Modelo = "Cobalt" }; } } }
40b52f77182b2cddf2d0c666d034ca0c1fe80b42
C#
shendongnian/download4
/first_version_download2/507982-46533829-157470588-2.cs
2.5625
3
public static void btnSummary_Click(object sender, EventArgs e) { string currentText = lblUsers.Text; int positionOfLastEntry = currentText.LastIndexOf("Name:"); string textWithoutLastEntry = currentText.Substring(0, positionOfLastEntry); lblUsers.Text = textWithoutLastEntry; lblUsers.Visible = true; }
4f7b4a385545a9a794d35bbd82f496eb9094f2ae
C#
markVaykhansky/technionProjectRepository
/KinectServer/BusinessLogic/MatlabDriver.cs
2.5625
3
using csmatio.io; using csmatio.types; using KinectServer.Common; using KinectServer.DTO; using System; using System.Collections.Generic; using System.Configuration; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Media.Media3D; namespace KinectServer.BusinessLogic { public static class MatlabDriver { #region Feilds private const int _jointsTimesCoordinate = 25*3; private const int _jointsTimesCoordinate2d = 25 * 2; private static string _folder; #endregion #region Public Methods public static void SetFolder() { var matlabFolder = ConfigurationManager.AppSettings["matlabFolder"]; var path = matlabFolder + DateTime.Now.ToString("dd-MM-yyyy h_mm_ss"); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } _folder = path; } public static event Action<string> WritingActionStateChanged; public static void ToMat(List<List<Point3D>> skeleton, string name = null) { Task.Factory.StartNew(() => { MLStructure sequenceStruct = new MLStructure("Skeletons", new int[] { 1, 1 }); sequenceStruct["UserName", 0] = new MLChar("", "igork"); MLSingle jointsMat = new MLSingle("", new int[] { _jointsTimesCoordinate, skeleton.Count }); int frameCount = 0; foreach (var frame in skeleton) { int jointCount = 0; foreach (var point in frame) { jointsMat.Set(point.X, jointCount * 3, frameCount); jointsMat.Set(point.Y, jointCount * 3 + 1, frameCount); jointsMat.Set(point.Z, jointCount * 3 + 2, frameCount); jointCount++; } frameCount++; } sequenceStruct["Skeletons"] = jointsMat; List<MLArray> matData = new List<MLArray>(); matData.Add(sequenceStruct); string filename = "skeletonData_" + DateTime.Now.Ticks + ".mat"; if (!string.IsNullOrEmpty(name)) { filename = name + "_" + DateTime.Now.Ticks + ".mat"; } if (WritingActionStateChanged != null) { WritingActionStateChanged("Started writing file: " + filename); } MatFileWriter mfw = new MatFileWriter(Path.Combine(_folder, filename), matData, false); if (WritingActionStateChanged != null) { WritingActionStateChanged("Done writing file: " + filename); } }); } public static void ToMatRandom(List<List<Point3D>> skeleton, List<Hit> hits, string name = null) { Task.Factory.StartNew(() => { MLStructure sequenceStruct = new MLStructure("RandomGame", new int[] { 1, 1 }); sequenceStruct["UserName", 0] = new MLChar("", "igork"); MLSingle jointsMat = new MLSingle("", new int[] { _jointsTimesCoordinate, skeleton.Count }); int frameCount = 0; foreach (var frame in skeleton) { int jointCount = 0; foreach (var point in frame) { jointsMat.Set(point.X, jointCount * 3, frameCount); jointsMat.Set(point.Y, jointCount * 3 + 1, frameCount); jointsMat.Set(point.Z, jointCount * 3 + 2, frameCount); jointCount++; } frameCount++; } sequenceStruct["Skeletons"] = jointsMat; if (hits.Count > 0) { MLSingle hitsMat = new MLSingle("", new int[] { 3, hits.Count }); int hitsCounter = 0; foreach (var hit in hits) { hitsMat.Set(hit.T1, 0, hitsCounter); hitsMat.Set(hit.T2, 1, hitsCounter); hitsMat.Set(hit.HitJointIndex, 2, hitsCounter++); } sequenceStruct["hits"] = hitsMat; } List<MLArray> matData = new List<MLArray>(); matData.Add(sequenceStruct); string filename = "skeletonData_" + DateTime.Now.Ticks + ".mat"; if (!string.IsNullOrEmpty(name)) { filename = name + "_" + DateTime.Now.Ticks + ".mat"; } if (WritingActionStateChanged != null) { WritingActionStateChanged("Started writing file: " + filename); } MatFileWriter mfw = new MatFileWriter(Path.Combine(_folder, filename), matData, false); if (WritingActionStateChanged != null) { WritingActionStateChanged("Done writing file: " + filename); } }); } public static void ToMat(List<Hit> hits, string name = null) { Task.Factory.StartNew(() => { MLStructure sequenceStruct = new MLStructure("hits", new int[] { 1, 1 }); sequenceStruct["UserName", 0] = new MLChar("", "igork"); MLSingle hitsMat = new MLSingle("", new int[] { 3, hits.Count }); int hitsCounter = 0; foreach (var hit in hits) { hitsMat.Set(hit.T1,0, hitsCounter); hitsMat.Set(hit.T2,1, hitsCounter); hitsMat.Set(hit.HitJointIndex, 2, hitsCounter++); } sequenceStruct["hits"] = hitsMat; List<MLArray> matData = new List<MLArray>(); matData.Add(sequenceStruct); string filename = "hitsData_" + DateTime.Now.Ticks + ".mat"; if (!string.IsNullOrEmpty(name)) { filename = name + "_" + DateTime.Now.Ticks + ".mat"; } if (WritingActionStateChanged != null) { WritingActionStateChanged("Started writing file: " + filename); } MatFileWriter mfw = new MatFileWriter(Path.Combine(_folder, filename), matData, false); if (WritingActionStateChanged != null) { WritingActionStateChanged("Done writing file: " + filename); } }); } public static void ToMatAll(List<List<Point3D>> skeleton, List<Hit> hits, List<Point3D> trajectories, List<List<ScreenPoint>> skeleton2d, List<ScreenPoint> trajectories2d,List<int> statesCues, string name = "") { Task.Factory.StartNew(() => { MLStructure sequenceStruct = new MLStructure("Game", new int[] { 1, 1 }); sequenceStruct["UserName", 0] = new MLChar("", name); MLStructure metadataStruct = new MLStructure("Metadata", new int[] { 1, 1 }); metadataStruct["CuesDbFilename"] = new MLChar("",ConfigurationManager.AppSettings["enemiesFile"]); sequenceStruct["Metadata"] = metadataStruct; MLSingle cuesMat = new MLSingle("", new int[] { 1, statesCues.Count }); for (int i = 0; i < statesCues.Count; i++) { cuesMat.Set(statesCues[i], i); } sequenceStruct["Cues"] = cuesMat; MLSingle jointsMat = new MLSingle("", new int[] { _jointsTimesCoordinate, skeleton.Count }); MLSingle jointsMat2d = new MLSingle("", new int[] { _jointsTimesCoordinate2d, skeleton2d.Count }); int frameCount = 0; foreach (var frame in skeleton) { int jointCount = 0; foreach (var point in frame) { jointsMat.Set(point.X, jointCount * 3, frameCount); jointsMat.Set(point.Y, jointCount * 3 + 1, frameCount); jointsMat.Set(point.Z, jointCount * 3 + 2, frameCount); jointCount++; } frameCount++; } frameCount = 0; foreach (var frame in skeleton2d) { int jointCount = 0; foreach (var point in frame) { jointsMat2d.Set(point.X, jointCount * 2, frameCount); jointsMat2d.Set(point.Y, jointCount * 2 + 1, frameCount); jointCount++; } frameCount++; } sequenceStruct["Skeletons"] = jointsMat; sequenceStruct["Skeletons2d"] = jointsMat2d; if (hits.Count > 0) { int maxTraj = 0; MLSingle hitsMat = new MLSingle("", new int[] { 3, hits.Count }); int hitsCounter = 0; foreach (var hit in hits) { hitsMat.Set(hit.T1, 0, hitsCounter); hitsMat.Set(hit.T2, 1, hitsCounter); hitsMat.Set(hit.HitJointIndex, 2, hitsCounter++); } sequenceStruct["hits"] = hitsMat; } if (trajectories.Count > 0) { MLSingle trajMat = new MLSingle("", new int[] { 3, trajectories.Count }); MLSingle trajMat2d = new MLSingle("", new int[] { 2, trajectories2d.Count }); int trajCounter = 0; foreach (var t in trajectories) { trajMat.Set(t.X, 0, trajCounter); trajMat.Set(t.Y, 1, trajCounter); trajMat.Set(t.Z, 2, trajCounter++); } trajCounter = 0; foreach (var t in trajectories2d) { trajMat2d.Set(t.X, 0, trajCounter); trajMat2d.Set(t.Y, 1, trajCounter++); } sequenceStruct["trajectories"] = trajMat; sequenceStruct["trajectories2d"] = trajMat2d; } List<MLArray> matData = new List<MLArray>(); matData.Add(sequenceStruct); string filename = "skeletonData_" + DateTime.Now.Ticks + ".mat"; if (!string.IsNullOrEmpty(name)) { filename = name + "_" + DateTime.Now.Ticks + ".mat"; } if (WritingActionStateChanged != null) { WritingActionStateChanged("Started writing file: " + filename); } MatFileWriter mfw = new MatFileWriter(Path.Combine(_folder, filename), matData, false); if (WritingActionStateChanged != null) { WritingActionStateChanged("Done writing file: " + filename); } }); } public static void ToMatMoving(List<Hit> hits,TrajectoriesData trajectories, string name = null) { Task.Factory.StartNew(() => { MLStructure sequenceStruct = new MLStructure("hits", new int[] { 1, 1 }); sequenceStruct["UserName", 0] = new MLChar("", "igork"); int maxTraj = 0; MLSingle hitsMat = new MLSingle("", new int[] { 3, hits.Count }); int hitsCounter = 0; foreach (var hit in hits) { hitsMat.Set(hit.T1, 0, hitsCounter); hitsMat.Set(hit.T2, 1, hitsCounter); hitsMat.Set(hit.HitJointIndex, 2, hitsCounter++); } sequenceStruct["hits"] = hitsMat; MLStructure trajectoryStruct = new MLStructure("hits", new int[] { 1, 1 }); trajectoryStruct["UserName", 0] = new MLChar("", "igork"); MLSingle trajMat = new MLSingle("", new int[] { 3, trajectories.Moving.Count }); int trajCounter = 0; foreach (var t in trajectories.Moving) { trajMat.Set(t.X, 0, trajCounter); trajMat.Set(t.Y, 1, trajCounter); trajMat.Set(t.Z, 2, trajCounter++); } sequenceStruct["trajectories"] = trajMat; List<MLArray> matData = new List<MLArray>(); matData.Add(sequenceStruct); string filename = "hitsData_" + DateTime.Now.Ticks + ".mat"; if (!string.IsNullOrEmpty(name)) { filename = name + "_" + DateTime.Now.Ticks + ".mat"; } if (WritingActionStateChanged != null) { WritingActionStateChanged("Started writing file: " + filename); } MatFileWriter mfw = new MatFileWriter(Path.Combine(_folder, filename), matData, false); if (WritingActionStateChanged != null) { WritingActionStateChanged("Done writing file: " + filename); } }); } #endregion } }
8e463eca8bdecd91a66b0acbaaca2b7cc1c0ab8d
C#
yesbirs56/Assignment2
/LatestInBuffer/Program.cs
3.53125
4
using Assesment2_BL; using System; namespace LatestInBuffer { internal class Program { public static void Main(string[] args) { FixedBuffer buffer = new FixedBuffer(10); while (true) { Console.Write($"Enter the Data : "); string data = Console.ReadLine(); if (data == "?") { break; } if (buffer.IsBufferFull()) { Console.Write($"Buffer is full want to over write oldest value \"{buffer.GetOldestData()}\" ?(y/n) : "); string ans = Console.ReadLine().ToLower(); if (ans != "n") { try { buffer.OverWriteOldestData(data); } catch (InvalidOperationException exc) { Console.WriteLine(exc.Message); return; } catch (Exception exc) { Console.WriteLine(exc.Message); return; } } continue; } buffer.AddData(data); } string[] values = buffer.GetBufferData(); PrintBuffer(values); } // Print The Buffer Data private static void PrintBuffer(string[] buffer) { Console.WriteLine("The Data in buffer "); foreach (string data in buffer) { Console.Write($"{data} "); } } } }
980f35e6ff3b00d8da70deb7d394a832211b131b
C#
shendongnian/download4
/code4/703402-16948700-41728657-2.cs
3.015625
3
TreeView treeView = new TreeView(); TreeNode parentNode = treeView.SelectedNode; if (parentNode.GetNodeCount(true) > 0) { foreach (TreeNode childNodes in parentNode.Nodes) { //// do stuff with nodes. } }
24c14e8eae3ac8484455be4fb1b0814a13b3acd7
C#
PMExtra/EntityExcel
/src/DataMapper/Models/TableMapper.cs
3.015625
3
using System.Collections; using System.Collections.Generic; using System.Data; using System.Linq; using DataMapper.Extensions; namespace DataMapper.Models { public class TableMapper<T> : IEnumerable<T> where T : new() { public TableMapper(DataTable table) { Table = table; } public DataTable Table { get; } public IEnumerator<T> GetEnumerator() { return (from DataRow row in Table.Rows select row.MapTo<T>()).GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return (from DataRow row in Table.Rows select row.MapTo<T>()).GetEnumerator(); } } }
53b34b72a6674c35c0780e0eaa62965a8e965a75
C#
1usama/Assigment-4
/MainWindow.xaml.cs
2.671875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace calculator { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void Button_Click(object sender, RoutedEventArgs e) { if (add.IsChecked == true) { ADDvalue(); } else if (sub.IsChecked== true) { SUBvalue(); } else if (mul.IsChecked == true) { MULvalue(); } else if (div.IsChecked == true) { DIVvalue(); } else if (rem.IsChecked == true) { REMvalue(); } } private void REMvalue() { int num1 ,num2, result; num1 = Convert.ToInt32(lft.Text); num2 = Convert.ToInt32(rgt.Text); result = num1 % num2; rslt.Text = result.ToString(); } private void DIVvalue() { int num1, num2, result; num1 = Convert.ToInt32(lft.Text); num2 = Convert.ToInt32(rgt.Text); result = num1 / num2; rslt.Text = result.ToString(); } private void MULvalue() { int num1, num2, result; num1 = Convert.ToInt32(lft.Text); num2 = Convert.ToInt16(rgt.Text); result = num1 * num2; rslt.Text = result.ToString(); } private void SUBvalue() { int num1, num2, result; num1 = Convert.ToInt32(lft.Text); num2 = Convert.ToInt32(rgt.Text); result = num1 - num2; rslt.Text = result.ToString(); } private void ADDvalue() { int num1, num2, result; num1 = Convert.ToInt32(lft.Text); num2 = Convert.ToInt32(rgt.Text); result = num1 + num2; rslt.Text = result.ToString(); } private void Button_Click_1(object sender, RoutedEventArgs e) { this.Close(); } } }
24a22f8b393a80c5469fb2901959ab5cdc6d327d
C#
legigor/GroceryStore
/C#/GroceryStore/GroceryStore.PoS/Products/ProductOffer.cs
3.203125
3
using System; namespace GroceryStore.PoS.Products { public sealed class ProductOffer { public string Code { get; } public string Title { get; } public decimal OfferPrice { get; } public string ProductCode { get; } public int ProductQty { get; } public ProductOffer(string code, string title, decimal offerPrice, string productCode, int productQty) { Code = !string.IsNullOrEmpty(code) ? code : throw new ArgumentOutOfRangeException($"[{nameof(code)}] parameter is empty."); Title = !string.IsNullOrEmpty(title) ? title : throw new ArgumentOutOfRangeException($"[{nameof(title)}] parameter is empty."); // Yep! Our store offers some product bundles for free occasionally OfferPrice = offerPrice >= 0 ? offerPrice : throw new ArgumentOutOfRangeException($"[{nameof(offerPrice)}] parameter is negative."); ProductCode = !string.IsNullOrEmpty(productCode) ? productCode : throw new ArgumentOutOfRangeException($"[{nameof(productCode)}] parameter is empty."); ProductQty = productQty > 0 ? productQty : throw new ArgumentOutOfRangeException($"[{nameof(productQty)}] parameter is not positive."); ; } public sealed class MatchResult { public bool IsMatch { get; } public string OfferCode { get; } public decimal OfferPrice { get; } public string ProductCode { get; } public int ProductQty { get; } public int RemainingProductQty { get; } public MatchResult(bool isMatch, string offerCode, decimal offerPrice, string productCode, int productQty, int remainingProductQty) { IsMatch = isMatch; OfferCode = offerCode; ProductCode = productCode; ProductQty = productQty; RemainingProductQty = remainingProductQty; OfferPrice = offerPrice; } } public MatchResult Matches(string productCode, int productQty) { var isMatch = string.Equals(productCode, ProductCode, StringComparison.InvariantCultureIgnoreCase) && productQty >= ProductQty; return new MatchResult(isMatch, Code, OfferPrice, ProductCode, productQty, productQty - ProductQty); } } }
3b7c60f17a723b147f720ea91cbb16a56dc46a10
C#
bakhyt/rsoi-lab3
/MvcApplication1/Controllers/Orders2Controller.cs
2.609375
3
using System; using System.Collections.Generic; using System.Linq; using System.Web; using Newtonsoft.Json; using ModelLib; using System.Web.Http; using RestSharp; namespace MvcApplication1.Controllers { public class Orders2Controller : ApiController { public ICollection<Order> Get(int page, int size) { MyOAuth.CheckAccessToken(); var client = new RestClient("http://localhost:8888/OrdersService/api"); var request = new RestRequest(string.Format("orders?page={0}&size={1}", page, size), Method.GET); IRestResponse<List<Order>> response2 = client.Execute<List<Order>>(request); if (response2 != null && response2.Data != null) { return response2.Data; } return null; } public int Post() { MyOAuth.CheckAccessToken(); var client = new RestClient("http://localhost:8888/OrdersService/api"); var request = new RestRequest("orders", Method.POST); IRestResponse<int> response2 = client.Execute<int>(request); if (response2 != null && response2.Data != null) { return response2.Data; } return -1; } public Order Post(int orderId, int goodId, int customerId, int deliveryId) { MyOAuth.CheckAccessToken(); var client = new RestClient("http://localhost:8888/OrdersService/api"); var request = new RestRequest(string.Format("orders?orderId={0}&goodId={1}&customerId={2}&deliveryId={3}", orderId, goodId, customerId, deliveryId), Method.POST); /*request.AddParameter("orderId", orderId); request.AddParameter("goodId", goodId); request.AddParameter("customerId", customerId); request.AddParameter("deliveryId", deliveryId); */ IRestResponse<Order> response2 = client.Execute<Order>(request); if (response2 != null && response2.Data != null) { return response2.Data; } return null; } /// <summary> /// Метод аггрегатора. Достаёт данные из 3 микросервисов /// </summary> /// <param name="id"></param> /// <returns></returns> public string Get(int id) { string res = ""; Order order = null; // получаем данные по заказу var client = new RestClient("http://localhost:8888/OrdersService/api"); var request = new RestRequest(string.Format("orders?id={0}", id), Method.GET); IRestResponse<Order> orderResp = client.Execute<Order>(request); if (orderResp != null && orderResp.Data != null) { order = orderResp.Data; } if (order == null) return null; Good good = null; client = new RestClient("http://localhost:7777/GoodsService/api"); request = new RestRequest(string.Format("goods?id={0}", order.GoodId), Method.GET); IRestResponse<Good> goodResp = client.Execute<Good>(request); if (goodResp != null && goodResp.Data != null) { good = goodResp.Data; } Customer customer = null; client = new RestClient("http://localhost:4444/CustomerAndDeliveryService/api"); request = new RestRequest(string.Format("customers?id={0}", order.CustomerId), Method.GET); IRestResponse<Customer> customerResp = client.Execute<Customer>(request); if (customerResp != null && customerResp.Data != null) { customer = customerResp.Data; } Delivery delivery = null; client = new RestClient("http://localhost:4444/CustomerAndDeliveryService/api"); request = new RestRequest(string.Format("deliveries?id={0}", order.DeliveryId), Method.GET); IRestResponse<Delivery> deliveryResp = client.Execute<Delivery>(request); if (deliveryResp != null && deliveryResp.Data != null) { delivery = deliveryResp.Data; } res = string.Format("Номер заказа: {0}; Товар: {1}; Покупатель: {2}; Доставка: {3}", id, (good == null ? "" : good.Title), (customer == null ? "" : customer.Title), (delivery == null ? "" : delivery.Title)); return res; } [HttpDelete] public string Delete(int orderId) { MyOAuth.CheckAccessToken(); bool res = false; var client = new RestClient("http://localhost:8888/OrdersService/api"); var request = new RestRequest(string.Format("orders?orderId={0}", orderId), Method.DELETE); IRestResponse<bool> response2 = client.Execute<bool>(request); if (response2 != null && response2.Data != null) { res = response2.Data; } if (res) return "Удалено - " + orderId; else return "Не удалось удалить -" + orderId; } } }
f6d67f2a3e5f7c553270b7b1bfddf1211ff9093c
C#
edhaker13/DiscordEdBot
/DiscordEdBot/MainHandler.cs
2.53125
3
namespace DiscordEdBot { using System; using System.Reflection; using System.Threading.Tasks; using Discord; using Discord.Commands; using Discord.WebSocket; using Microsoft.Extensions.DependencyInjection; internal static class MainHandler { public static Task LogAsync(LogMessage message) { var originalColor = Console.ForegroundColor; ConsoleColor newColor; switch (message.Severity) { case LogSeverity.Critical: case LogSeverity.Error: newColor = ConsoleColor.Red; break; case LogSeverity.Warning: newColor = ConsoleColor.Yellow; break; case LogSeverity.Info: newColor = ConsoleColor.White; break; case LogSeverity.Verbose: case LogSeverity.Debug: newColor = ConsoleColor.DarkGray; break; default: throw new ArgumentOutOfRangeException(); } Console.ForegroundColor = newColor; Console.WriteLine($"{DateTime.Now,-19} [{message.Severity,8}] {message.Source}: {message.Message}"); Console.ForegroundColor = originalColor; return Task.CompletedTask; } public static async Task MessageReceivedAsync(SocketMessage message, CommandService commandService, IServiceProvider serviceProvider = null) { // Ignore non-user messages. var userMessage = message as SocketUserMessage; if (userMessage == null) return; var client = serviceProvider.GetService<DiscordSocketClient>(); var prefixEndPosition = 0; // TODO: Configurable prefix(es). if (userMessage.HasCharPrefix('!', ref prefixEndPosition) || userMessage.HasCharPrefix('~', ref prefixEndPosition) || userMessage.HasMentionPrefix(client.CurrentUser, ref prefixEndPosition)) { var commandContext = new SocketCommandContext(client, userMessage); var unused = await commandService.ExecuteAsync(commandContext, prefixEndPosition, serviceProvider); } } public static async Task RegisterCommandService(CommandService commandService) { commandService.Log += LogAsync; await commandService.AddModulesAsync(Assembly.GetEntryAssembly()).ConfigureAwait(false); } } }
7d392e73fd6bc92b436a8fa667ddcb5b1cd5b7ef
C#
GeorgiPangev/C_Sharp-Fundamentals
/ObjectsAndClases/StoreBoxes/Program.cs
3.421875
3
using System; using System.Collections.Generic; using System.Linq; namespace StoreBoxes { class Program { static void Main(string[] args) { List<BoxInfo> boxes = new List<BoxInfo>(); List<PriceName> items = new List<PriceName>(); string[] input = Console.ReadLine() .Split(" ") .ToArray(); while (input[0] != "end"&& input[0] != "End") { PriceName item = new PriceName(); BoxInfo box = new BoxInfo(); item.Namee = input[1]; double pr = double.Parse(input[3]); item.Price = pr; double priceOfBox = double.Parse(input[3]) * double.Parse(input[2]); items.Add(item); box.SN = int.Parse(input[0]); box.Name = input[1]; box.Qusntity = int.Parse(input[2]); box.BoxPrice = priceOfBox; box.Price= double.Parse(input[3]) ; boxes.Add(box); input = Console.ReadLine() .Split(" ") .ToArray(); } for (int i = 0; i < boxes.Count; i++) { for (int j = i; j < boxes.Count; j++) { if (boxes[j].BoxPrice> boxes[i].BoxPrice) { BoxInfo dj = boxes[i]; boxes[i] = boxes[j]; boxes[j] = dj; // Console.WriteLine(boxes[j + 1].BoxPrice); } } } foreach (BoxInfo box in boxes) { Console.WriteLine($"{box.SN}"); Console.WriteLine($"-- {box.Name} - ${box.Price:F2}: {box.Qusntity}"); Console.WriteLine($"-- ${box.BoxPrice:F2}"); } } class BoxInfo { public int SN { get; set; } public string Name { get; set; } // public Item Item { get; set } public int Qusntity { get; set; } public double BoxPrice { get; set; } public double Price { get; set; } } class PriceName { public string Namee { get; set; } public double Price { get; set; } } } }
80bd139c9257f4470c699a0bd2268110cbe9bf6f
C#
nonnarat21/UnluckyDraw
/Implement/PointCardFactory.cs
2.96875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using UnluckyDraw.Interface; namespace UnluckyDraw.Implement { public class PointCardFactory : ICardFactory { public override IDrawCard CreateDrawCard(int playerScore) { PointCardDrawCard obj = new PointCardDrawCard(playerScore); return obj; } public override IChangePlayerState CreateChangePlayerState() { PointCardChangePlayerState obj = new PointCardChangePlayerState(); return obj; } } public class PointCardDrawCard : IDrawCard { private int score; public PointCardDrawCard(int cardScore) { score = cardScore; } public int GetPlayerScore(int playerScore) { return playerScore + score; } } public class PointCardChangePlayerState : IChangePlayerState { private string state; public PointCardChangePlayerState() { state = "Stop"; } public string ChangePlayerState() { return state; } } }
8b45645caa87ae20048ca61fbb874eb5a803dd98
C#
rvpetkov/SimpleChessGame
/Simple Chess Game/Assets/Scripts/AI.cs
3.15625
3
using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Linq; /// <summary> /// This class is a desperate attempt at creating an AI system that can play chess. /// The result so far is a "player" that can randomly choose a chess piece and move it. /// The move is chosen by the following rule: /// - if an enemy piece can be taken - do it /// - if more than one enemies can be taken choose in order: Queen, Rook, Bishop, Knight, Pawn /// - if no enemies are for the taking - choose randomly /// </summary> public class AI : MonoBehaviour { #region Provate variables private List<ChessPiece> allPieces; private List<ChessPiece> piecesWithMoves; private ChessPiece currentPieceToPlay; private bool isComputerInitialized = false; #endregion [HideInInspector] public static AI instance = null; public bool IsComputerInitialized { get { return isComputerInitialized; } } #region Initializations void Awake() { if (instance == null) { //Check if instance already exists instance = this; } else if (instance != this) { //If instance already exists and it's not this: //Then destroy this. This enforces our singleton pattern, meaning there can only ever be one instance of a GameManager. Destroy(gameObject); } } /// <summary> /// Use this method to return the AI to its original state /// </summary> public void Initialize() { allPieces = new List<ChessPiece>(); piecesWithMoves = new List<ChessPiece>(); for (int i = 0; i < BoardManager.BOARD_SIZE; i++) { for (int j = 0; j < BoardManager.BOARD_SIZE; j++) { ChessPiece piece = BoardManager.Instance.ChessBoardArr[i, j]; if (piece != null && piece.IsWhite == false) { allPieces.Add(piece); } } } isComputerInitialized = true; } #endregion /// <summary> /// Randomly chooses a piece that has at least one legal move to make. /// </summary> /// <returns>The chess piece.</returns> public ChessPiece ChooseChessPiece() { bool addPiece = false; piecesWithMoves.Clear(); foreach (ChessPiece p in allPieces.ToList()) { addPiece = false; bool[,] moves = p.PossibleMoves(); for (int i = 0; i < BoardManager.BOARD_SIZE; i++) { for (int j = 0; j < BoardManager.BOARD_SIZE; j++) { if (moves[i, j] == true) { addPiece = true; break; } } } if(addPiece) piecesWithMoves.Add(p); } currentPieceToPlay = piecesWithMoves.ElementAt(Random.Range(0, piecesWithMoves.Count)); return currentPieceToPlay; } /// <summary> /// Semi-randomly chooses a move to be made. /// Moves which lead to taking an enemy piece are more valuable. /// If there are no such legal moves, then it is decided at random. /// </summary> /// <returns>The ChessPiece target if any.</returns> /// <param name="x">The x coordinate of the chosen destination.</param> /// <param name="y">The y coordinate of the chosen destination.</param> public ChessPiece ChooseMove(out int x, out int y) { ChessPiece pieceToTake = null; ChessPiece[,] piecesOnTheBoard = BoardManager.Instance.ChessBoardArr; bool[,] moves = currentPieceToPlay.PossibleMoves(); int[] possibleX = new int[30]; int[] possibleY = new int[30]; int index = 0; for (int i = 0; i < BoardManager.BOARD_SIZE; i++) { for (int j = 0; j < BoardManager.BOARD_SIZE; j++) { if (moves[i, j]) { if (piecesOnTheBoard[i, j] != null) { if (piecesOnTheBoard[i, j].GetType() == typeof(Queen)) { pieceToTake = piecesOnTheBoard[i, j]; } else if (piecesOnTheBoard[i, j].GetType() == typeof(Rook)) { if(pieceToTake == null) pieceToTake = piecesOnTheBoard[i, j]; else if (pieceToTake.GetType() != typeof(Queen)) pieceToTake = piecesOnTheBoard[i, j]; } else if (piecesOnTheBoard[i, j].GetType() == typeof(Bishop)) { if (pieceToTake == null) pieceToTake = piecesOnTheBoard[i, j]; else if ((pieceToTake.GetType() != typeof(Rook)) || (pieceToTake.GetType() != typeof(Queen))) pieceToTake = piecesOnTheBoard[i, j]; } else if (piecesOnTheBoard[i, j].GetType() == typeof(Knight)) { if (pieceToTake == null) pieceToTake = piecesOnTheBoard[i, j]; else if ((pieceToTake.GetType() != typeof(Rook)) || (pieceToTake.GetType() != typeof(Queen)) || (pieceToTake.GetType() != typeof(Bishop))) { pieceToTake = piecesOnTheBoard[i, j]; } } else if (piecesOnTheBoard[i, j].GetType() == typeof(Pawn)) { if (pieceToTake == null) pieceToTake = piecesOnTheBoard[i, j]; else if ((pieceToTake.GetType() != typeof(Rook)) || (pieceToTake.GetType() != typeof(Queen)) || (pieceToTake.GetType() != typeof(Bishop)) || (pieceToTake.GetType() != typeof(Knight))) { pieceToTake = piecesOnTheBoard[i, j]; } } } else { if(index < 30) { possibleX[index] = i; possibleY[index] = j; index++; } } } } } if (pieceToTake != null) { x = pieceToTake.CurrentX; y = pieceToTake.CurrentY; } else //The randomly chosen piece can't take any of the enemy's pieces { int position = Random.Range(0, index); x = possibleX[position]; y = possibleY[position]; } return pieceToTake; } public void RemoveChessPiece(ChessPiece piece) { allPieces.Remove(piece); } public void AddChessPiece(ChessPiece piece) { allPieces.Add(piece); } public void DeactivateComputer() { isComputerInitialized = false; } }
7f35fe1b6bf5a741e0cacfcae400d4e5c09a0fe1
C#
HT200/Spell
/Spell/Assets/Scripts/Dataset/Node.cs
3.125
3
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Node : MonoBehaviour { public char Value { get; set; } public List<Node> Children { get; set; } public Node Parent { get; set; } public int Depth { get; set; } public Node(char value, int depth, Node parent) { Value = value; Children = new List<Node>(); Depth = depth; Parent = parent; } public bool IsLeaf() { return Children.Count == 0; } public Node FindChildNode(char c) { foreach (var child in Children) if (child.Value == c) return child; return null; } }
09525c781dee91881035f00eac926659d4b47c38
C#
Xavier227/Application
/GUI/Views/Game.cs
3.0625
3
using System; using System.Collections.Generic; using WinEchek.Core; using WinEchek.Engine; using WinEchek.Model; using WinEchek.Model.Piece; namespace WinEchek { public class Game { private Player _currentPlayer; public Player WhitePlayer { get; set; } public Player BlackPlayer { get; set; } public Engine.Engine Engine { get; internal set; } public Container Container { get; set; } /// <summary> /// Construct a game with an engine and two players /// </summary> /// <param name="engine">The engin the game will use</param> /// <param name="whitePlayer">White player</param> /// <param name="blackPlayer">Black player</param> /// <param name="container">Model container</param> public Game(Engine.Engine engine, Player whitePlayer, Player blackPlayer, Container container) { WhitePlayer = whitePlayer; BlackPlayer = blackPlayer; Engine = engine; Container = container; WhitePlayer.MoveDone += MoveHandler; BlackPlayer.MoveDone += MoveHandler; _currentPlayer = WhitePlayer; RaiseBoardState(); // TODO : trouver une meilleure solution _currentPlayer.Play(null); } //Convenience method to raise the StateChangedEvent private void RaiseBoardState() => StateChanged?.Invoke(Engine.CurrentState()); /// <summary> /// Délégué appelé quand un joueur réalise un coup. /// </summary> /// <remarks> /// On vérifie si le coup est valide et si c'est le cas on demande à l'autre joueur de jouer. /// Sinon on indique au joueur que le coup est invalide afin qu'il nous redonne un coup. /// On réalise ces actions tant que la partie n'est pas echec et mat ou echec et pat. /// </remarks> /// <param name="sender"></param> /// <param name="move"></param> private void MoveHandler(Player sender, Move move) { if (sender != _currentPlayer) return; //Tell the player it isn't his turn ? if (Engine.DoMove(move)) { _currentPlayer.Stop(); ChangePlayer(); RaiseBoardState(); } _currentPlayer.Play(move); } private void ChangePlayer() => _currentPlayer = _currentPlayer == WhitePlayer ? BlackPlayer : WhitePlayer; #region Undo Redo /// <summary> /// Demande au moteur d'annuler le dernier coup joué /// </summary> public void Undo() { if (Engine.Undo()) { _currentPlayer.Stop(); ChangePlayer(); RaiseBoardState(); } // TODO : Trouver une solution _currentPlayer.Play(null); } public void Undo(int count) { for (int i = 0; i < count; i++) { if (Engine.Undo()) { ChangePlayer(); } } RaiseBoardState(); //TODO trouver une solution _currentPlayer.Play(null); } /// <summary> /// Demande au moteur de refaire le dernier coup annulé /// </summary> public void Redo() { if (Engine.Redo()) { _currentPlayer.Stop(); ChangePlayer(); StateChanged?.Invoke(Engine.CurrentState()); } //TODO trouver une solution _currentPlayer.Play(null); } #endregion /// <summary> /// Liste les mouvements possibles pour une pièce. /// </summary> /// <param name="piece">Pièce a tester</param> /// <returns>Liste des mouvements</returns> public List<Square> PossibleMoves(Piece piece) => Engine.PossibleMoves(piece); public delegate void StateHandler(BoardState state); public event StateHandler StateChanged; } }
e63ae6a61d4dc964cc6bf24d2f4bcf311991397f
C#
drypa/FurnitureInRoom
/FurnitureInRoom.Tests/HomeStateTest.cs
2.828125
3
using System; using System.Linq; using FurnitureInRoom.Exceptions; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace FurnitureInRoom.Tests { [TestClass] public class HomeStateTest { [TestMethod] public void CreateRoomShouldCreateNewStateIfDateNotExists() { HomeState stateHolder = new HomeState(); const string roomName = "bedroom"; DateTime date = new DateTime(2015, 01, 05); stateHolder.CreateRoom(roomName, date); var history = stateHolder.GetHistory(); Assert.AreEqual(1, history.Count); Assert.AreEqual(date, history.First().Key); Assert.IsNotNull(history.First().Value); Assert.AreEqual(1, history.First().Value.GetRooms().Count); Assert.AreEqual(roomName, history.First().Value.GetRooms().First().Name); DateTime newDate = new DateTime(2015, 01, 06); stateHolder.CreateRoom(roomName, newDate); Assert.AreEqual(2, history.Count); newDate = new DateTime(2014, 01, 01); stateHolder.CreateRoom(roomName, newDate); Assert.AreEqual(3, history.Count); } [TestMethod] public void CreateRoomShouldCreateRoomInExistingState() { HomeState stateHolder = new HomeState(); const string roomName = "bedroom"; DateTime date = new DateTime(2015, 01, 05); stateHolder.CreateRoom(roomName, date); var history = stateHolder.GetHistory(); Assert.AreEqual(1, history.Count); stateHolder.CreateRoom(roomName, date); Assert.AreEqual(1, history.Count); Assert.AreEqual(2, history.First().Value.GetRooms().Count); } [TestMethod] public void CreateRoomShouldContainAllRoomsFromPreviousState() { HomeState stateHolder = new HomeState(); const string roomName = "bedroom"; DateTime date = new DateTime(2015, 01, 05); stateHolder.CreateRoom(roomName, date); var history = stateHolder.GetHistory(); Assert.AreEqual(1, history.Count); DateTime newDate = new DateTime(2015, 01, 06); stateHolder.CreateRoom(roomName, newDate); Assert.AreEqual(2, history.Count); Assert.AreEqual(2, history.Last().Value.GetRooms().Count); } [TestMethod] [ExpectedException(typeof(NoHomeForThisDateException))] public void RemoveRoomShouldThrowNoHomeForThisDateExceptionWhenNoDateFound() { HomeState stateHolder = new HomeState(); stateHolder.RemoveRoom("some room", "other room", DateTime.Now); } [TestMethod] public void CanRemoveRoomWithoutFurniture() { HomeState stateHolder = new HomeState(); DateTime date = DateTime.Now; const string roomName = "bedroom"; stateHolder.CreateRoom(roomName, date); stateHolder.RemoveRoom(roomName, null, date); Assert.AreEqual(0, stateHolder.GetHistory()[date].GetRooms().Count); stateHolder.CreateRoom(roomName, date); stateHolder.RemoveRoom(roomName, roomName, date); Assert.AreEqual(0, stateHolder.GetHistory()[date].GetRooms().Count); } [TestMethod] public void CanGetRoomsList() { HomeState stateHolder = new HomeState(); DateTime date = new DateTime(2015, 01, 01); const string roomName = "bedroom"; stateHolder.CreateRoom(roomName, date); var list = stateHolder.GetRoomsList(date); Assert.IsNotNull(list); Assert.AreEqual(1, list.Count); stateHolder.CreateRoom(roomName, date); list = stateHolder.GetRoomsList(date); Assert.IsNotNull(list); Assert.AreEqual(2, list.Count); DateTime anotherDate = new DateTime(2014, 10, 11); stateHolder.CreateRoom(roomName, anotherDate); list = stateHolder.GetRoomsList(date); Assert.IsNotNull(list); Assert.AreEqual(2, list.Count); list = stateHolder.GetRoomsList(anotherDate); Assert.IsNotNull(list); Assert.AreEqual(1, list.Count); } [TestMethod] public void CanCreateFurniture() { HomeState stateHolder = new HomeState(); DateTime date = new DateTime(2015, 01, 01); const string roomName = "bedroom"; const string furnitureName = "sofa"; stateHolder.CreateFurniture(furnitureName, roomName, date); Assert.AreEqual(1, stateHolder.GetRoomsList(date).Count); Assert.AreEqual(roomName, stateHolder.GetRoomsList(date).First().Name); Assert.AreEqual(1, stateHolder.GetRoomsList(date).First().GetFurnitures().Count); Assert.AreEqual(furnitureName, stateHolder.GetRoomsList(date).First().GetFurnitures().First().Type); stateHolder.CreateFurniture(furnitureName, roomName, date); Assert.AreEqual(1, stateHolder.GetRoomsList(date).Count); Assert.AreEqual(roomName, stateHolder.GetRoomsList(date).First().Name); Assert.AreEqual(2, stateHolder.GetRoomsList(date).First().GetFurnitures().Count); Assert.AreEqual(furnitureName, stateHolder.GetRoomsList(date).First().GetFurnitures().First().Type); Assert.AreEqual(furnitureName, stateHolder.GetRoomsList(date).First().GetFurnitures().Last().Type); } [TestMethod] public void CanMoveFurniture() { HomeState stateHolder = new HomeState(); DateTime date = new DateTime(2015, 01, 01); const string roomName = "bedroom"; const string anotherRoom = "anotherRoom"; const string furnitureName = "sofa"; stateHolder.CreateFurniture(furnitureName, roomName, date); stateHolder.CreateRoom(anotherRoom, date); stateHolder.MoveFurniture(furnitureName, roomName, anotherRoom, date); } [TestMethod] public void CanGetHomeChangeDates() { HomeState stateHolder = new HomeState(); DateTime date = new DateTime(2015, 01, 01); const string roomName = "bedroom"; const string furnitureName = "sofa"; stateHolder.CreateFurniture(furnitureName, roomName, date); var dates = stateHolder.GetHomeChangeDates(); Assert.IsNotNull(dates); Assert.AreEqual(1, dates.Count); Assert.AreEqual(date, dates.First()); DateTime anotherDate = new DateTime(2015, 01, 02); stateHolder.CreateFurniture(furnitureName, roomName, anotherDate); dates = stateHolder.GetHomeChangeDates(); Assert.IsNotNull(dates); Assert.AreEqual(2, dates.Count); Assert.IsTrue(dates.Contains(date)); Assert.IsTrue(dates.Contains(anotherDate)); } } }
7bc32df89fa03040eacdda48433fa34c45752522
C#
NewLifeWorks/Software_-Bulgaria
/Software_University_Bulgaria/Fundamental_Level/C#[Advance]/HomeWorks/04_StringsandTextProcessing/02_StringLength/StringLength.cs
3.890625
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TaskTwo.cs { class StringLength { /* * Task Two String Lenght * */ static void Main(string[] args) { Console.WriteLine("Give me your love , i mean your string...."); string love = Console.ReadLine(); StringBuilder outLove = new StringBuilder(love); int length = outLove.Length; if (length >= 20) { outLove.Remove(20,outLove.Length - 20); } else { outLove.Append('*',20 - outLove.Length); } Console.WriteLine(outLove.ToString()); } } }
6ecac2aa2c410f78f6b8dc63aacaf5099829e42d
C#
nschott/EgneOpgaverFraCkursus
/indkapsling_egenskaber/Program.cs
3.375
3
using System; namespace indkapsling_egenskaber { class Program { static void Main(string[] args) { Person p1 = new Person(); Console.WriteLine("Indtast fornavn"); p1.Fornavn = Console.ReadLine(); Console.WriteLine("Indtast efternavn"); p1.Efternavn = Console.ReadLine(); Console.WriteLine($"Indtastet navn er: {p1.FuldtNavn}"); if (System.Diagnostics.Debugger.IsAttached) { Console.Write("Press any key to continue . . . "); Console.ReadKey(); } } } public class Person { public string Fornavn { get; set; } private string _efternavn; public string Efternavn { get { return _efternavn; } set { if (value.Length <= 3) _efternavn = ""; else _efternavn = value; } } public string FuldtNavn { get { return Fornavn + " " + Efternavn; } } } }
1bbdb81c4ef37a17bfdbd31ec3f47c9fa288f826
C#
marklinmao/HoloGanttVR
/Assets/Scripts/POJOs.cs
3.046875
3
using System; using System.Collections.Generic; namespace HoloGanttVR { /// <summary> /// POJO of a person (team member) /// </summary> public class Member { private string id; private string name; public Member(string id, string name) { this.id = id; this.name = name; } public string GetId() { return this.id; } public string GetName() { return this.name; } } /// <summary> /// POJO of task /// </summary> public class Task { private string id; private string name; private Member owner; private DateTime startDateTime; private DateTime endDateTime; public Task(string id, string name, Member owner, DateTime startDateTime, DateTime endDateTime) { this.id = id; this.name = name; this.owner = owner; this.startDateTime = startDateTime; this.endDateTime = endDateTime; } public DateTime GetStartDateTime() { return this.startDateTime; } public void SetStartDateTime(DateTime newDateTime) { this.startDateTime = newDateTime; } public DateTime GetEndDateTime() { return this.endDateTime; } public void SetEndDateTime(DateTime newDateTime) { this.endDateTime = newDateTime; } public string GetId() { return this.id; } public string GetName() { return this.name; } public Member GetOwner() { return this.owner; } } /// <summary> /// POJO of task group /// </summary> public class TaskGroup { private string id; private string name; private Dictionary<string, Task> tasks = new Dictionary<string, Task>(); private DateTime startDateTime; private DateTime endDateTime; private int duration; public TaskGroup(string id, string name) { this.id = id; this.name = name; } public string GetId() { return this.id; } public void AddTask(Task newTask) { if(newTask != null) { if(this.tasks.ContainsKey(newTask.GetId())) { throw new ArgumentException("Duplicated task ID!"); } this.tasks.Add(newTask.GetId(), newTask); //update start/end datetime and duration UpdateDurationInfo(); } } public void RemoveTask(string taskId) { if(taskId != null && this.tasks.ContainsKey(taskId)) { this.tasks.Remove(taskId); //update start/end datetime and duration UpdateDurationInfo(); } } private void UpdateDurationInfo() { if (this.tasks.Count > 0) { List<string> keyList = new List<string>(this.tasks.Keys); DateTime currentMin = this.tasks[keyList[0]].GetStartDateTime(); DateTime currentMax = this.tasks[keyList[0]].GetEndDateTime(); for (int i = 0; i < keyList.Count; i++) { int compareMinResult = DateTime.Compare(currentMin, this.tasks[keyList[i]].GetStartDateTime()); if (compareMinResult > 0) currentMax = this.tasks[keyList[i]].GetStartDateTime(); int compareMaxResult = DateTime.Compare(currentMax, this.tasks[keyList[i]].GetEndDateTime()); if (compareMinResult < 0) currentMax = this.tasks[keyList[i]].GetEndDateTime(); } this.startDateTime = currentMin; this.endDateTime = currentMax; this.duration = Utils.GetWorkingDays(currentMin, currentMax); } } public DateTime GetStartDateTime() { return this.startDateTime; } public DateTime GetEndDateTime() { return this.endDateTime; } public int GetDuration() { return this.duration; } } /// <summary> /// POJO of a project /// </summary> public class Project { private string id; private string name; private DateTime startDateTime; private DateTime endDateTime; private int duration; private Dictionary<string, TaskGroup> taskGroups = new Dictionary<string, TaskGroup>(); private Dictionary<string, Member> members = new Dictionary<string, Member>(); public Project(string id, string name) { this.id = id; this.name = name; } public string GetId() { return this.id; } public string GetName() { return this.name; } public Dictionary<string, TaskGroup> GetTaskGroups() { return this.taskGroups; } public void AddTaskGroup(TaskGroup taskGroup) { if(taskGroup != null) { if (this.taskGroups.ContainsKey(taskGroup.GetId())) { throw new ArgumentException("Duplicated task group ID!"); } this.taskGroups.Add(taskGroup.GetId(), taskGroup); //update start/end datetime and duration UpdateDurationInfo(); } } public void RemoveTaskGroup(string taskGroupId) { if(taskGroupId != null && this.taskGroups.ContainsKey(taskGroupId)) { this.taskGroups.Remove(taskGroupId); //update start/end datetime and duration UpdateDurationInfo(); } } public Dictionary<string, Member> GetMembers() { return this.members; } public void AddMember(Member newMember) { this.members.Add(newMember.GetId(), newMember); } public void RemoveMember(string memberId) { if(memberId != null && this.members.ContainsKey(memberId)) this.members.Remove(memberId); } private void UpdateDurationInfo() { if(this.taskGroups.Count > 0) { List<string> keyList = new List<string>(this.taskGroups.Keys); DateTime currentMin = this.taskGroups[keyList[0]].GetStartDateTime(); DateTime currentMax = this.taskGroups[keyList[0]].GetEndDateTime(); for (int i = 0; i < keyList.Count; i++) { int compareMinResult = DateTime.Compare(currentMin, this.taskGroups[keyList[i]].GetStartDateTime()); if (compareMinResult > 0) currentMax = this.taskGroups[keyList[i]].GetStartDateTime(); int compareMaxResult = DateTime.Compare(currentMax, this.taskGroups[keyList[i]].GetEndDateTime()); if (compareMinResult < 0) currentMax = this.taskGroups[keyList[i]].GetEndDateTime(); } this.startDateTime = currentMin; this.endDateTime = currentMax; this.duration = Utils.GetWorkingDays(currentMin, currentMax); } } public DateTime GetStartDateTime() { return this.startDateTime; } public DateTime GetEndDateTime() { return this.endDateTime; } public int GetDuration() { return this.duration; } } }
511e4a007b1d666e362b4c3e37eb24b17b44cf9a
C#
ccerbusca/ubb-cs
/Parallel and Distributed Programming/Lab4/Lab4/Lab4/examples/Await.cs
3.25
3
// A server that accepts pairs of numbers, transmitted as text and separated by whitespace, and sends back their sums using System; using System.Net; using System.Net.Sockets; using System.Threading; using System.Threading.Tasks; class Session3 { private Session3(Socket conn) { _conn = conn; _buffer = new byte[10]; } private async Task<char> ReadNextChar() { if (_pos >= _size) { _pos = 0; _size = await Receive(_conn, _buffer, 0, _buffer.Length); if (_size == 0) { return '\0'; } } byte b = _buffer[_pos]; ++_pos; char c = (char)b; if (c == '\n' || c == '\r' || c == '\t') { c = ' '; } else if (c != ' ' && (c < '0' || c > '9')) { Console.WriteLine("Unexpected caracter: {0}", c); c = ' '; } return c; } private async Task Run() { _pos = 0; _size = await Receive(_conn, _buffer, 0, _buffer.Length); _a = 0; _b = 0; char c = await ReadNextChar(); while (true) { while (c == ' ') { c = await ReadNextChar(); } if (c == '\0') { Console.WriteLine("Connection closed"); _conn.Close(); return; } while (c != ' ') { if (c == '\0') { Console.WriteLine("Connection closed prematurely"); _conn.Close(); return; } _a = _a * 10 + (byte)c - 48; c = await ReadNextChar(); } while (c == ' ') { c = await ReadNextChar(); } while (c != ' ') { if (c == '\0') { await SendSum(); Console.WriteLine("Connection closed"); _conn.Close(); return; } _b = _b * 10 + (byte)c - 48; c = await ReadNextChar(); } await SendSum(); _a = 0; _b = 0; } } private async Task SendSum() { string s = string.Format("{0}", _a + _b); byte[] b = new byte[s.Length + 1]; for (int i = 0; i < s.Length; ++i) { b[i] = (byte)s[i]; } b[s.Length] = 10; await Send(_conn, b, 0, b.Length); } private static async Task MainLoop(Socket listeningSocket) { while (true) { Socket conn = await Accept(listeningSocket); Console.WriteLine("Connection opened"); Session3 session = new Session3(conn); Task dummy = session.Run(); } } /*public static void Main(string[] args) { try { int port = Int32.Parse(args[0]); Console.WriteLine("Listening on port {0} ...", port); IPEndPoint listeningEndpoint = new IPEndPoint(IPAddress.Any, port); using (Socket listeningSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Unspecified)) { listeningSocket.Bind(listeningEndpoint); listeningSocket.Listen(10); Task dummy = MainLoop(listeningSocket); dummy.Wait(); } } catch (Exception ex) { Console.WriteLine("Exception caught: {0}", ex); } }*/ static Task<int> Receive(Socket conn, byte[] buf, int index, int count) { TaskCompletionSource<int> promise = new TaskCompletionSource<int>(); conn.BeginReceive(buf, index, count, SocketFlags.None, (IAsyncResult ar) => promise.SetResult(conn.EndReceive(ar)), null); return promise.Task; } static Task<int> Send(Socket conn, byte[] buf, int index, int count) { TaskCompletionSource<int> promise = new TaskCompletionSource<int>(); conn.BeginSend(buf, index, count, SocketFlags.None, (IAsyncResult ar) => promise.SetResult(conn.EndSend(ar)), null); return promise.Task; } static Task<Socket> Accept(Socket listeningSocket) { TaskCompletionSource<Socket> promise = new TaskCompletionSource<Socket>(); listeningSocket.BeginAccept((IAsyncResult ar) => promise.SetResult(listeningSocket.EndAccept(ar)), null); return promise.Task; } private Socket _conn; private byte[] _buffer; private int _pos; private int _size; private int _a, _b; }
42a4d9425d5883c9af75238ee501fdb35b1f6ce4
C#
milescward/Data-Structures
/DataStructures/DoublyLinkedList/myDoublyLinkedList.cs
3.484375
3
using System; using System.Collections.Generic; using DataStructures.SinglyLinkedList; namespace DataStructures.DoublyLinkedList { public class myDoublyLinkedList<T> { public DNode<T> Head { get; private set; } public DNode<T> Tail { get; private set; } public int Count { get; private set; } public bool IsEmpty { get; set; } public void AddFront(T data) { var node = new DNode<T>(data); AddFront(node); } private void AddFront(DNode<T> node) { if (IsEmpty) { Head = node; Tail = node; Count++; IsEmpty = false; } else { node.Next = Head; Head.Previous = node; Head = node; Count++; } } public void AddBack(T data) { var node = new DNode<T>(data); AddBack(node); } private void AddBack(DNode<T> node) { if (IsEmpty) { Head = node; Tail = node; Count++; } else { node.Previous = Tail; Tail.Next = node; Tail = node; Count++; } } public void Delete(T target) { if(Compare(Head.Data, target)) { Head = Head.Next; Count--; } else { DNode<T> iterator = Head.Next; DNode<T> prev = Head; while(iterator != null) { if (Compare(iterator.Data, target)) { if (iterator == Tail) { Tail = Tail.Previous; } else { prev.Next = iterator.Next; iterator.Next.Previous = prev; iterator.Previous = null; iterator.Next = null; Count--; if (Count == 0) IsEmpty = true; return; } } iterator = iterator.Next; prev = prev.Next; } } } private bool Compare(T x, T y) { return EqualityComparer<T>.Default.Equals(x, y); } public void Insert(DNode<T> node1, DNode<T> node2, T data) { if (node1 == null || node2 == null) { throw new NullReferenceException(); } else if (node1.Next != node2) throw new InvalidOperationException(); var node = new DNode<T>(data); node.Next = node2; node.Previous = node1; node1.Next = node; node2.Previous = node; Count++; } public void Insert(DNode<T> node1, T data) { if (node1 == null || node1.Next == null) { throw new NullReferenceException(); } var node = new DNode<T>(data); node.Next = node1.Next; node.Previous = node1; node1.Next.Previous = node; node1.Next = node; Count++; } public myDoublyLinkedList() { this.IsEmpty = true; } } }
567ad08f26c9e267f7eb35d7ec95bae833ad1161
C#
StephaneVR/Website-Webshop
/Webshop.DAL/Repositories/CourseRepo.cs
2.8125
3
using System; using System.Collections.Generic; using System.Data.Entity; using System.Data.Entity.Migrations; using System.Linq; using Webshop.DAL.Entit; namespace Webshop.DAL.Repositories { public class CourseRepo : IRepository<Course> { private WebshopContext _webshopContext; public CourseRepo(WebshopContext context) { _webshopContext = context; } public Course Add(Course course) { try { _webshopContext._Courses.Add(course); return course; } catch (Exception e) { throw new Exception(e.Message); } } public Course FindById(int? id) { try { return _webshopContext._Courses.Find(id); } catch (Exception e) { throw new Exception(e.Message); } } public Course Modify(Course course) { try { _webshopContext._Courses.AddOrUpdate(course); return course; } catch (Exception e) { throw new Exception(e.Message); } } public List<Course> GetAll() { try { return _webshopContext._Courses.ToList(); } catch (Exception e) { throw new Exception(e.Message); } } public void Remove(Course t) { try { var course = FindById(t.Id); _webshopContext._Courses.Remove(course); } catch (Exception e) { throw new Exception(e.Message); } } } }
b432de53ec86ba1cc450eb484473751430ab89e9
C#
HarbingTarbl/GGJ2013
/src/AStar.cs
2.59375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Jammy.Collision; using Microsoft.Xna.Framework; namespace Memory { public class Pathfinder { public List<Vector2> FindPath (PolyLink Start, PolyLink End) { List<PolyLink> searched; PolyLink currentNode = Start; throw new NotImplementedException(); } private static int GetCost(PolyLink a, PolyLink b) { return (int) Vector2.Distance (a.GetVertex(), b.GetVertex()); } } }
dd10bbc6714559d1e6229796e82cb8f914be5a1c
C#
danieleg/cudumar-xmpp
/Frameworks/OAuth2/OAuth2Provider.cs
2.578125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections.Specialized; using System.Text.RegularExpressions; namespace Cudumar.Frameworks.OAuth2 { public abstract class OAuth2Provider { public string ClientID { get; protected set; } public string ClientSecret { get; protected set; } public Uri LoginUri { get; protected set; } public Uri ReturnUri { get; protected set; } public OAuth2Provider() { } public virtual string GetAccessToken() { Uri ResultLoginUri = LaunchBrowser(); return PerformLogin(ResultLoginUri); } protected abstract string PerformLogin(Uri ResultLoginUri); protected Uri LaunchBrowser() { AuthBrowser browser = new AuthBrowser(LoginUri, ReturnUri); browser.ShowDialog(); return browser.GetCurrentUri(); } protected NameValueCollection ParseQueryString(string s) { NameValueCollection nvc = new NameValueCollection(); // remove anything other than query string from url if (s.Contains("?")) { s = s.Substring(s.IndexOf('?') + 1); } foreach (string vp in Regex.Split(s, "&")) { string[] singlePair = Regex.Split(vp, "="); if (singlePair.Length == 2) { nvc.Add(singlePair[0], singlePair[1]); } else { // only one key with no value specified in query string nvc.Add(singlePair[0], string.Empty); } } return nvc; } } }
783a5c1ce95771e996af4a35d54b44625e34c733
C#
zyque-sys/aplicaciones-web
/visual studio repo/FUNPOO2020_2/ProyectoFinalCine/Ejecutable.cs
3.078125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProyectoFinalCine { class Ejecutable { static void Main(string[] args) { #region Campos int opcion; int inicioMenu = 1; int finMenu = 6; string menu = "1: Seleccion de pelicula \n2: Comprar boletos \n3: Comprar en dulceria \n4: Comprar en Cafe \n5: Validar Boleto\nOpción:"; CatalogoOHistorial catCartelera = new CatalogoOHistorial(); Pelicula[] peliculas = new Pelicula[10]; Pelicula funcion=new Pelicula(); ProductoDulceria[] productosDulceria; ProductoPlatillo[] productosCafe; Boleto[] historialBoletos=new Boleto[50]; Boleto boletoCliente = new Boleto(); #endregion do { do { Console.Clear(); Console.ForegroundColor = ConsoleColor.Magenta; Console.Write(menu); Console.ForegroundColor = ConsoleColor.Gray; int.TryParse(Console.ReadLine(), out opcion); if (opcion < inicioMenu || opcion > finMenu) Console.WriteLine("Opción invalida"); } while (opcion < inicioMenu || opcion > finMenu); switch (opcion) { case 1: //toDo int boton; Console.ForegroundColor = ConsoleColor.Magenta; Console.WriteLine("|-------------------------------------------|"); Console.WriteLine("|-------------------------------------------|"); Console.ForegroundColor = ConsoleColor.Gray; catCartelera.MostrarCatalogo(peliculas); funcion=SeleccionDeCartelera(peliculas,funcion); Console.WriteLine("⌐-----------------------------------¬\n" + "| |\n"+ "|¿Desea continuar a comprar boletos?|\n"+ "| |\n" + "| [1.Si] [Cualquier otra cosa.No] |\n" + "| |\n" + "┕-----------------------------------┘\nOpción:"); int.TryParse(Console.ReadLine(),out boton); if (boton==1) CompraBoletos(funcion); break; case 2: boletoCliente=CompraBoletos(funcion); break; case 3: //toDo //CompraProductos(productosDulceria,productosCafe); break; case 4: int id; bool realizo; do { Console.WriteLine("Ingrese el numero de identificación del boleto:"); realizo= int.TryParse(Console.ReadLine(),out id); if (realizo==false) Console.WriteLine("Ingrese solo numeros"); } while (realizo == false); Boleto temp = new Boleto(); boletoCliente.Id_boleto=temp.Id_boleto; if (ValidacionBoletos(temp,historialBoletos)) { Console.WriteLine("Disfrute la funcion! :D"); } break; } Console.ReadLine(); } while (opcion != finMenu); } static Pelicula SeleccionDeCartelera(Pelicula [] pelis,Pelicula pelicula) { //toDo int opcion; int inicioMenu = 1; int finMenu = 3; string titulo = " _________________________________\n" + "|======Selección de cartelera=====|\n" + "|_________________________________|\n"; string menu= "|-1-:Modificaciones de admin |\n" + "|2:Seleccion de pelicula |\n" + "| |\n" + "|[x]3.Salir |\n" + " _________________________________\nOpción:"; do { do { Console.ForegroundColor = ConsoleColor.Magenta; Console.Write(titulo); Console.ForegroundColor = ConsoleColor.Cyan; Console.Write(menu); Console.ForegroundColor = ConsoleColor.Gray; int.TryParse(Console.ReadLine(), out opcion); if (opcion < inicioMenu || opcion > finMenu) Console.WriteLine("Opción invalida"); } while (opcion < inicioMenu || opcion > finMenu); CatalogoOHistorial cartelera = new CatalogoOHistorial(); Pelicula funcion = new Pelicula(); switch (opcion) { case 1: MenuAdmin(pelis,pelicula,cartelera); break; case 2: //toDo int numPel=0; int indicePelicula=0; Console.WriteLine("Ingrese el numero de la pelicula a escoger:"); int.TryParse(Console.ReadLine(), out numPel); if (int.TryParse(Console.ReadLine(), out numPel)) { for (int i = 0; i < pelis.Length; i++) { if (pelis[i].NumPelicula == numPel) { indicePelicula = i; break; } else indicePelicula = -1; } if (indicePelicula >= 0) { pelis[indicePelicula].NumPelicula=funcion.NumPelicula; pelis[indicePelicula].NombrePelicula = funcion.NombrePelicula; pelis[indicePelicula].Sala = funcion.Sala; pelis[indicePelicula].Horario = funcion.Horario; } else Console.WriteLine("El numero de pelicula no se encontro"); }else Console.WriteLine("Dato invalido, ingrese solo numeros"); break; default: //toDo break; } if (funcion.NumPelicula>0) { Console.WriteLine("Se lleno la funcion con exito ! :)"); }else Console.WriteLine("No se pudo llenar la funcion"); return funcion; } while (opcion != finMenu); } #region MenuAdmin(sobrecargas) static void MenuAdmin(Pelicula[] peli,Pelicula funcion,CatalogoOHistorial cartelera) { int opcion; int inicioMenu = 1; int finMenu = 4; string menu = " _________________________________\n" + "|======Menu de administrador======|\n" + "|1:Añadir pelicula |\n" + "|2:Modificar pelicula |\n" + "|3:Eliminar pelicula |\n" + "| |\n" + "| |\n" + "|[x]4.Salir |\n" + " _________________________________\nOpción:"; do { do { Console.Clear(); Console.Write(menu); int.TryParse(Console.ReadLine(), out opcion); if (opcion < inicioMenu || opcion > finMenu) Console.WriteLine("Opción invalida"); } while (opcion < inicioMenu || opcion > finMenu); switch (opcion) { case 1: //1:Añadir pelicula cartelera.ActualizarCatalogo(peli); break; case 2: //2:Modificar pelicula int numPel = 0; Console.WriteLine("Ingrese el numero de la pelicula a la cual quiere modificar"); numPel = int.Parse(Console.ReadLine()); int indicePelicula = 0; for (int i = 0; i < 10; i++) { if (peli[i].NumPelicula == numPel) { indicePelicula = i; break; } else indicePelicula = -1; } if (indicePelicula>=0) { peli[indicePelicula].NombrePelicula = funcion.NombrePelicula; peli[indicePelicula].Horario = funcion.Horario; peli[indicePelicula].Sala = funcion.Sala; bool sePudo= cartelera.ActualizarCatalogo(funcion); if (sePudo) { Console.WriteLine("Pelicula actualizada!"); } else { Console.WriteLine("No se pudo actualizar la pelicula, revise sus valores :("); } } break; case 3: //3:Eliminar pelicula int numPel1 = 0; Console.WriteLine("Ingrese el numero de la pelicula a la cual quiere eliminar"); numPel1 = int.Parse(Console.ReadLine()); int indicePelicula1 = 0; for (int i = 0; i < 10; i++) { if (peli[i].NumPelicula == numPel1) { indicePelicula1 = i; break; } else indicePelicula1 = -1; } if (indicePelicula1 > 0) { peli[indicePelicula1].NombrePelicula = ""; peli[indicePelicula1].NumPelicula = 0; peli[indicePelicula1].Sala = 0; peli[indicePelicula1].Horario = ""; peli[indicePelicula1].AsientosDisponibles = 0; Console.WriteLine("Pelicula eliminada con exito"); } else { Console.WriteLine("El numero de pelicula seleccionado no se encontro"); } break; default: break; } } while (opcion != finMenu); } static void MenuAdmin(ProductoDulceria[] dulceria) { } static void MenuAdmin(ProductoPlatillo[] cafe) { } #endregion static Boleto CompraBoletos(Pelicula funcion) { //toDo Boleto boleto = new Boleto(); int cantidadBoletos=0; int cantidadBoletosNino=0; float total=0.00f; bool realizo; if (funcion.AsientosDisponibles<25) { do { Console.WriteLine("¿Cuántos boletos de adulto desea comprar"); realizo = int.TryParse(Console.ReadLine(), out cantidadBoletos); if (realizo == true) { total = cantidadBoletos * 75.5f; Console.WriteLine("¿Desea comprar boletos de niño?"); if (Console.ReadLine().ToUpper() == "SI") { Console.WriteLine("¿Cuántos boletos de niño desea comprar"); int.TryParse(Console.ReadLine(), out cantidadBoletosNino); total = total + (cantidadBoletosNino * 55.5f); } } else { Console.WriteLine("Ingrese solo numeros porfavor"); } } while (realizo == false); string descuento; float descuentOU = 0.00f; if (cantidadBoletos>0 || cantidadBoletosNino>0) { Console.WriteLine("Su total es de $ " + total + " mxn, ¿Desea agregar algún descuento?\n[Escriba solo si para continuar]"); if (Console.ReadLine().ToUpper() == "SI") { //VET5,SENIOR10,STUDENT10 Console.WriteLine("Escriba el codigo de descuento a seleccionar"); descuento = Console.ReadLine().ToUpper(); if (descuento == "SENIOR10" || descuento == "STUDENT10") { float desc = total * 0.10f; total = total - desc; boleto.Descuento = 0.10f; } else if (descuento == "VET5") { float desc = total * 0.05f; total = total - desc; boleto.Descuento = 0.05f; } else { Console.WriteLine("No tenemos registrado ese código de descuento"); } } Console.WriteLine("Su nuevo total es de $ "+total+"\n¿Desea confirmar su compra?\n[1]Si [Cualquier otra cosa]No"); int opcion = 0; if (opcion==1) { total = boleto.Total; descuentOU=boleto.Descuento; boleto.Id_boleto = 123456; Console.WriteLine("Gracias por su compra!Su número de boleto es "+boleto.Id_boleto+ "\nPelicula a ver:"+boleto.Funcion.NombrePelicula+ "\nDescuentos:"+descuentOU+"\nTotal[ $"+total+" mxn]\n--Disfrute la función!!--"); return boleto; } } } else { Console.WriteLine("No hay asientos suficientes, seleccione otra pelicula"); } return boleto; } #region CompraProductos(sobrecargas) static void CompraProductos(ProductoDulceria[] productosDulceria, CatalogoOHistorial inventarioDulceria) { inventarioDulceria.MostrarCatalogo(productosDulceria); } static void CompraProductos(ProductoPlatillo[] productosPlatillo, CatalogoOHistorial inventarioPlatillo) { inventarioPlatillo.MostrarCatalogo(productosPlatillo); } #endregion static bool ValidacionBoletos(Boleto funcion,Boleto [] boletos) { int indice; bool sePudo = false; for (int i = 0; i < boletos.Length; i++) { if (boletos[i].Id_boleto == funcion.Id_boleto) { sePudo = true; } else sePudo = false; } return sePudo; } } }
a79ff23307267ce769ca0ec25c887c781cc1cbb3
C#
alexkikos/House_Building
/BuildingParts/Basement.cs
3.046875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BuildingParts { class Basement : Ipart { string name_part; bool finished; int count; float time_for_build; public float TimeForBild { get => time_for_build; set => time_for_build = value; } public int Count { get => count; set => count = value; } /// <summary> /// basement only 1 /// </summary> /// <param name="time_for_build_one_item">exmp 12h == 12h time for build</param> public Basement(float time_for_build_one_item) { this.name_part = "Basement"; this.finished = false; count = 1; time_for_build = time_for_build_one_item; } public string CurrentNamePart { get => name_part; set => name_part= value; } public bool Finished { get => finished; set => finished=value; } public void DrawPart() { Console.SetCursorPosition(35, 25); for (int i = 0; i < 30; i++) { Console.Write("="); } } public void StartWork() { Console.WriteLine("start work at: " + name_part); } } }
fde02c4b3c5a51f191bc525e84503b18c46d53b7
C#
shendongnian/download4
/code11/1922384-57970687-205497410-1.cs
2.71875
3
private static readonly int beginIndex = 20; private void Delimite_Btn_Click(object sender, RoutedEventArgs e) { string barcode = Original_Code_TxtBox.Text; int endIndex = barcode.Length - 5; if (endIndex > beginIndex) { var selectedText = barcode.Substring(beginIndex, endIndex - beginIndex); } }
9dc9fa44c65b55561608e1db01e69507dc1f1d91
C#
3d1st/Pet
/TestWork/EquationProcessor/Rulers/CalculateAdditionVariableRule.cs
2.890625
3
using Contracts.Operations; using Contracts.Terms; namespace EquationProcessor.Rulers { public class CalculateAdditionVariableRule : IRule { public bool TermMatchRule(EquationTermBase term) { bool matched = term is EquationBinaryOperationBase operation && operation.Type == OperationsEnum.Addition && operation.Left is EquationVariable left && operation.Right is EquationVariable right && left.Name == right.Name; return matched; } public EquationTermBase Invoke(EquationTermBase term) { char variableName = ((EquationVariable) ((EquationBinaryOperationBase) term).Left).Name; return new MultiplicationOperation(new EquationConstant(2), new EquationVariable(variableName)); } } }
8af7685ef6310b748f672e38d4bb3e293af534e4
C#
gozderam/PolygonEditor
/PolygonEditor/Definitions/Polygon.cs
3.078125
3
using PolygonEditor.Utils; using System; using System.Collections.Generic; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using Line = PolygonEditor.Definitions.Line; namespace PolygonEditor.Definitions { //TODO IPolygon - ograniczenia /// <summary> /// Reprsents a single polygon. /// </summary> /// <remarks>The order of Vertices and Eges is important! </remarks> public class Polygon //: IShape { public string Id { get; set; } public Color FillColor { get; } = Color.Blue; public int FillOpacity { get; } = 50; public Color BackgroudColor { get; set; } = Color.White; public int VerticesCount { get { return vertices.Count; } } public int EdgesCount { get { return edges.Count; } } /// <summary> /// List of subsequent vertices: v_0, v_1, ..., v_n. /// </summary> private List<VerticePoint> vertices = new List<VerticePoint>(); /// <summary> /// List of subsequent edges: v_0v_1, v_1v_2, ..., v_(n-1)v_n. /// </summary> private List<Line> edges = new List<Line>(); public Polygon(List<VerticePoint> vertices, List<Line> edges) { Id = AppUtils.GeneratePolygonId(); this.vertices = vertices; this.edges = edges; SetSelfAsParent(); } #region getters /// <summary> /// Deep copy: copies the list of vertices and returns it (changes in the list won't be reflected in Polygon vertices list, but changes in elements of the list will). /// </summary> public List<VerticePoint> GetVerticesList() { return vertices.ConvertAll(v => v); } /// <summary> /// Deep copy: copies the list of edges and returns it (changes in the list won't be reflected in Polygon edges list, but changes in elements of the list will). /// </summary> public List<Line> GetEdgesList() { return edges.ConvertAll(e => e); } public int GetEdgeIndex(Line e) { return edges.IndexOf(e); } #endregion #region deleting vertice public (Line firstDeletedEdge, Line secondDeletedEdge, Line addedEdge) DeleteVertice(VerticePoint v) { #region CheckArgs if (v == null) return (null, null, null); if(vertices.Count==0) return (null, null, null); if (edges.Count == 0) return (null, null, null); #endregion int verticeIndex = vertices.IndexOf(v); if (verticeIndex == -1) return (null, null, null); // polygon must have at least 3 vertices and edges int newEdgeIndex = verticeIndex - 1 >=0 ? verticeIndex - 1 : edges.Count-2; // insert new edge at the end if deleting first vertice // delete vertice vertices.Remove(v); // delete incident edges edges.Remove(v.FirstIncidentEdge); edges.Remove(v.SecondIncidentEdge); // crete and add new Edge // TODO default color var newEdge = new Line(v.FirstIncidentEdge.start, v.SecondIncidentEdge.end, this, v.FirstIncidentEdge.Pen.Color, (int)v.FirstIncidentEdge.Pen.Width); edges.Insert(newEdgeIndex, newEdge); return (v.FirstIncidentEdge, v.SecondIncidentEdge, newEdge); } #endregion #region adding vertice public (Line deletedEdge, Line firstAddedEdge, Line secondAddedEdge, VerticePoint addedVertice) AddVerticeOnEdge(Line e) { #region CheckArgs if (e == null) return (null, null, null, null); if (vertices.Count == 0) return (null, null, null, null); if (edges.Count == 0) return (null, null, null, null); #endregion int edgeIndex = edges.IndexOf(e); if (edgeIndex == -1) return (null, null, null, null); // point for new vertice var point = e.LinePoints[e.LinePoints.Count / 2]; // ddelete old edge edges.RemoveAt(edgeIndex); // new vertce var newVertice = new VerticePoint(point.X, point.Y, this); vertices.Insert(edgeIndex + 1, newVertice); // new Edges var firsNewEgde = new Line(e.start, newVertice, this); var secondNewEdge = new Line(newVertice, e.end, this); edges.Insert(edgeIndex, firsNewEgde); edges.Insert(edgeIndex + 1, secondNewEdge); return (e, firsNewEgde, secondNewEdge, newVertice); } #endregion #region moving public void Move((double x, double y) vector) { // all constrains are fullfilled - no need to check vertices.ForEach(v => { v.IncreaseX(vector.x); v.IncreaseY(vector.y); }); } #endregion #region private methods private void SetSelfAsParent() { vertices.ForEach(v => v.Parent = this); edges.ForEach(e => e.Parent = this); } #endregion } }
598e2149f5bd6c1b23d2e679f4c89140e89cfb16
C#
stephen-cornwell/Bard
/src/Bard/Internal/PipelineBuilder.cs
2.71875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Bard.Infrastructure; using Bard.Internal.Exception; namespace Bard.Internal { internal class PipelineBuilder : IPipelineBuilder, IObserver<MessageLogged> { private readonly LogWriter _logWriter; private readonly List<PipelineStep> _pipelineSteps = new List<PipelineStep>(); private bool _messageLogged; private int _executionCount; internal PipelineBuilder(LogWriter logWriter) { _logWriter = logWriter; } public bool HasSteps => _pipelineSteps.Any(); public void OnCompleted() { } public void OnError(System.Exception error) { } public void OnNext(MessageLogged value) { _messageLogged = true; } public void AddStep(string stepName, Action stepAction) { _pipelineSteps.Add(new PipelineStep(stepName, stepAction)); } public void Execute(object? storyData) { if (HasSteps == false) return; var initialMessage = _executionCount > 0 ? "AND" : "GIVEN THAT"; StringBuilder stringBuilder = new StringBuilder(initialMessage); foreach (var pipelineStep in _pipelineSteps) { var humanizedName = Humanize.MethodName(pipelineStep.StepName); stringBuilder.Append(humanizedName); if (pipelineStep.StepAction == null) continue; _logWriter.LogHeaderMessage(stringBuilder.ToString()); try { _messageLogged = false; pipelineStep.StepAction(); if (_messageLogged == false) { // The API was not called through the context so log // the output instead. if (storyData != null) _logWriter.LogObject(storyData); } stringBuilder.Clear(); } catch (System.Exception exception) { throw new ChapterException($"Error executing story {pipelineStep.StepName}", exception); } } Reset(); _executionCount++; } private void Reset() { _pipelineSteps.Clear(); } } }
6833d8e4d3842b432c04bab416f330fe366496e7
C#
esrasnck/BitirmeProjesi
/Project.MODEL/Entities/Product.cs
2.71875
3
using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Project.MODEL.Entities { public class Product : BaseEntity { public Product() { Categories = new List<ProductCategory>(); } [Required(ErrorMessage = "{0} alanının girilmesi zorunludur."), DisplayName("Ürün Adı"), MaxLength(50, ErrorMessage = "{0} alanı en fazla {1} karakter olmalıdır."), DataType(DataType.Text)] public string ProductName { get; set; } [DisplayName("Ürün Resmi")] public string ImagePath { get; set; } [Required(ErrorMessage = "{0} alanının girilmesi zorunludur."), DisplayName("Stok Miktarı"), Range(0, ushort.MaxValue, ErrorMessage ="Geçerli bir değer giriniz.")] public int UnitsInStock { get; set; } [Required(ErrorMessage = "{0} alanının girilmesi zorunludur."), DisplayName("Ürün Fiyatı"), Range(0, int.MaxValue, ErrorMessage = "Geçerli bir değer giriniz."), DataType(DataType.Currency)] public decimal UnitPrice { get; set; } // Relational Properties public virtual List<ProductCategory> Categories { get; set; } public virtual List<OrderDetail> OrderDetails { get; set; } public virtual List<ProductFeature> ProductFeatures { get; set; } } }
8bfa030fc15e2bf14ce9c8860b5fb177c55acc2c
C#
tamaw/AGLWebBot
/HackathonBot/Phrases.cs
3.09375
3
using System.Collections.Generic; namespace HackathonBot { public static class Phrases { private static readonly Dictionary<string, string> Responses; static Phrases() { //A list of basic phrases and responses that end the conversation //to be used to return giffys Responses = new Dictionary<string, string> { {"thanks", "you're welcome"}, {"thank you", "you're welcome"}, {"bye", "bye"}, {"see you", "bye"}, {"shit", "suprise"}, {"i hate you", "cry"}, {"awesome", "awesome"}, {":(", "happy"}, {"ok", "you're welcome"}, {"cheers", "cheers"}, {"stuff you", "murder"}, {"bye bye", "bye" }, {"omg", "omg" }, {"you suck", "I hate you" }, {"haha", "haha" } }; } public static string GetPhraseResponse(string input) { return Responses[input]; } public static bool ContainsKey(string key) { return Responses.ContainsKey(key); } } }
b3d534704763d3e2ebeafd667697b1ccd8301eb6
C#
Csharp2020/csharp2020
/pmrvic/7_2_2_unos_imena/Program.cs
3.328125
3
using System; namespace _7_2_2_unos_imena { class Program { static void Main(string[] args) { Console.WriteLine("Ispisuje ime i pozdrav"); Pozdrav("Pero"); Console.WriteLine(); Pozdrav("Pero","Perić"); Console.WriteLine(); Pozdrav("Pero","Perić", 2021); Console.WriteLine(); Pozdrav(v2:"Pero", v1:"Perić", v3:2021); // Zamijenili smo redoslijed parametara } private static void Pozdrav(string v1, string v2, int v3=0) { // Opcija 1 //Console.WriteLine("Pozdrav {0} {1}!", v1,v2); Pozdrav(v1); Console.Write(" {0}",v2); if (v3 != 0) { Console.Write(" Sretna Nova {0}!", v3); } } private static void Pozdrav(string v) { Console.Write("Pozdrav {0}", v); } } }
fe2c49d35f3035b084f6164cab5e6d0cb3c7951a
C#
davidwyao/Rhythm-Master
/src/Assets/Scripts/ButtonController.cs
2.78125
3
using System.Collections; using System.Collections.Generic; using UnityEngine; /** * @name ButtonController * @brief Parses user inputs, applies effects to buttons, and checks validity of presses. * @date April 12, 2021 */ public class ButtonController : MonoBehaviour { /** * @brief The key that this controller checks for. */ public KeyCode keyToPress; /** * @brief True if the key is intersecting a note. */ public bool canBePressed; /** * @brief True if the key is intersecting a long note. */ public bool canBePressedLong; /** * @brief True if the key intersecting a long note is being pressed. */ public bool longBeingPressed; /** * @brief The colour of the specified key. */ public string colour; /** * @brief The code of the specified key. */ public int code; private bool finishedLong; // Start is called before the first frame update void Start() { keyToPress = (KeyCode)PlayerPrefs.GetInt(colour, code); } // Update is called once per frame void Update() { if (Input.GetKeyDown(keyToPress)) { transform.Translate(Vector3.back * 0.02f); // Move the key down if (canBePressed) { this.GetComponent<Renderer>().material.EnableKeyword("_EMISSION"); // Light up key this.GetComponent<CollisionDetector>().NoteHit(); // Pass to Collision Detector to check accuracy } else if (canBePressedLong) { this.GetComponent<Renderer>().material.EnableKeyword("_EMISSION"); this.GetComponent<CollisionDetector>().LongNoteClicked(); longBeingPressed = true; } else if (!canBePressed && !canBePressedLong) // Key isn't intersecting anything { this.GetComponent<CollisionDetector>().NoteMissed(); } } if (Input.GetKeyUp(keyToPress)) { if (longBeingPressed) { canBePressed = false; longBeingPressed = false; if (!finishedLong) { this.GetComponent<CollisionDetector>().NoteMissed(); // Premature release of long note } finishedLong = false; } transform.Translate(Vector3.forward * 0.02f); // Move the key back forward this.GetComponent<Renderer>().material.DisableKeyword("_EMISSION"); // Dim key } } /** * @brief Called when a long note intersects the key. */ public void CanPressLong() { canBePressedLong = true; } /** * @brief Called when a long note passes the key. * @detail Gives credit for a complete long note, if it has been hit. */ public void CantPressLong() { if (longBeingPressed) { finishedLong = true; this.GetComponent<CollisionDetector>().LongNoteHit(); } canBePressedLong = false; } /** * @brief Called when a short note intersects the key. */ public void CanPress() { canBePressed = true; } /** * @brief Called when a short note passes the key. */ public void CantPress() { canBePressed = false; } }
b59774cfedc2558b3ce3675110a414fb94f2bd64
C#
Furysoft/DynamicQuery
/src/Component/Furysoft.DynamicQuery/Logic/Helpers/ParserHelpers.cs
2.78125
3
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ParserHelpers.cs" company="Simon Paramore"> // © 2017, Simon Paramore // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Furysoft.DynamicQuery.Logic.Helpers { using System; /// <summary> /// The Parser Helpers. /// </summary> public static class ParserHelpers { /// <summary> /// Parses the specified source. /// </summary> /// <param name="source">The source.</param> /// <param name="type">The type.</param> /// <returns> /// The Object. /// </returns> public static object Parse(string source, string type = null) { var cleaned = source.Trim('"'); if (type != null) { return TypeParser.Parse(cleaned, type); } if (int.TryParse(cleaned, out var intType)) { return intType; } if (decimal.TryParse(cleaned, out var decimalType)) { return decimalType; } if (DateTime.TryParse(cleaned, out var dateTimeType)) { return dateTimeType; } return source; } } }
cad797cd10c5100ccc024d3c7675270c2543bbcc
C#
pedroivoabsilva/Dioflix
/Dioflix/Classes/FilmeRepositorio.cs
2.828125
3
using System; using System.Collections.Generic; using System.Text; using DioFlix.Interfaces; namespace DioFlix.Classes { class FilmeRepositorio : IRepositorio<Filme> { private List<Filme> filmes = new List<Filme>(); public void atualiza(int id, Filme filme) { filmes[id] = filme; } public void exclui(int id) { filmes[id].excluir(); } public void insere(Filme filme) { filmes.Add(filme); } public List<Filme> Lista() { return filmes; } public int ProximoId() { return filmes.Count; } public Filme RetornaPorId(int id) { return filmes[id]; } } }
cdb9373b96bb213631d1189b98bc40c33fbf1108
C#
shawon2jg/Day05
/HashtableApp/HashtableApp/Program.cs
3
3
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace HashtableApp { class Program { static void Main(string[] args) { Hashtable aHashtable = new Hashtable(); aHashtable.Add("111", "Shawon"); aHashtable.Add("112", "Rumel"); aHashtable.Add("113", "Atik"); string name = (string) aHashtable["111"]; Console.WriteLine(name); Console.ReadKey(); } } }
c6d5a43a22fe728380b1d47b788d64838fe93ca5
C#
racoltacalin/cryoprison
/Test/Cryoprison.Test/Inspectors/FileNotDestructivelyWritableTests.cs
2.515625
3
using System; using Cryoprison; using Xunit; using Cryoprison.Inspectors; using System.IO; namespace Cryoprison.Test.Inspectors { public class FileNotDestructivelyWritableTets { [Fact] public void HasCorrectId() { var env = new Ex.Env(); var i = new FileNotDestructivelyWritable().Init(env, "TEST", "file"); Assert.Equal("FILE_TEST_SHOULD_NOT_BE_DESTRUCTIVELY_WRITABLE", i.Id); } [Fact] public void DetectsFileWritable() { var env = new Ex.Env(); env.System.IO.File.Open = (path, mode, access, share) => { return new MemoryStream(new byte[100]); }; var deleted = false; env.System.IO.File.Delete = (path) => { deleted = true; }; var i = new FileNotDestructivelyWritable().Init(env, "TEST", "file"); Assert.False(i.Ok); Assert.True(deleted); } [Fact] public void DetectsDirectoryNotFound() { var env = new Ex.Env(); env.System.IO.File.Open = (path, mode, access, share) => { throw new DirectoryNotFoundException(); }; var i = new FileNotDestructivelyWritable().Init(env, "TEST", "file"); Assert.True(i.Ok); } [Fact] public void DetectsFileNotWritable() { var env = new Ex.Env(); env.System.IO.File.Open = (path, mode, access, share) => { throw new System.UnauthorizedAccessException("Cannot open in write mode"); }; var i = new FileNotDestructivelyWritable().Init(env, "TEST", "file"); Assert.True(i.Ok); } [Fact] public void IsRobust() { var env = new Ex.Env(); string message = null; Exception exception = null; env.Reporter.OnExceptionReported = (msg, ex) => { message = msg; exception = ex; }; env.System.IO.File.Open = (path, mode, access, share) => { throw new Exception("fubar"); }; var deleted = false; env.System.IO.File.Delete = (path) => { deleted = true; }; var i = new FileNotDestructivelyWritable().Init(env, "TEST", "file"); Assert.True(i.Ok); Assert.Equal("IsFileDestructivelyWritable bombed for file", message); Assert.Equal("fubar", exception.Message); Assert.True(deleted); } } }
3c1a6447f6ed6f49a7f6d4df3a3c1348086c44e9
C#
thenderson21/SocketClusterSharp
/SocketClusterSharp/Helpers/Timer.cs
2.828125
3
// // Timer.cs // // Author: // Todd Henderson <todd@todd-henderson.me> // // Copyright (c) 2015-2016 Todd Henderson // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN using System; using System.Threading.Tasks; using System.Threading; namespace SocketClusterSharp.Helpers { /// <summary> /// Generates a recurring events at a set interval while the callback returns true. /// </summary> public class Timer { Guid _id = Guid.NewGuid (); readonly CancellationTokenSource _cancellationTokenSourse = new CancellationTokenSource (); TimeSpan _interval = TimeSpan.FromMilliseconds (25); TimeSpan _maxInterval = TimeSpan.FromTicks (Int32.MaxValue); Func<bool> _csallback; /// <summary> /// Starts a recurring timer using the device clock capabilities. /// </summary> Timer Start () { bool success = false; _cancellationTokenSourse.CancelAfter (_maxInterval); Task.Run (() => { while (!success) { if (_cancellationTokenSourse.IsCancellationRequested) break; Task.Delay (_interval).Wait (); success = !_csallback (); } }, _cancellationTokenSourse.Token); return this; } /// <summary> /// Starts a recurring timer using the device clock capabilities. /// </summary> /// <remarks>While the callback returns true, the timer will keep recurring.</remarks> public static Timer Start (Func<bool> callback) { var timer = new Timer (); timer._csallback = callback; return timer.Start (); } /// <summary> /// Starts a recurring timer using the device clock capabilities. /// </summary> /// <remarks>While the callback returns true, the timer will keep recurring.</remarks> /// <param name="callback">The action to run when the timer elapses.</param> /// <param name="interval">The interval between invocations of the callback.</param> public static Timer Start (Func<bool> callback, TimeSpan interval) { var timer = new Timer (); timer._interval = interval; timer._csallback = callback; return timer.Start (); } /// <summary> /// Starts a recurring timer using the device clock capabilities. /// </summary> /// <remarks>While the callback returns true, the timer will keep recurring.</remarks> /// <param name="callback">The action to run when the timer elapses.</param> /// <param name="interval">The interval in miliseconds between invocations of the callback.</param> public static Timer Start (Func<bool> callback, double interval) { var timer = new Timer (); timer._interval = TimeSpan.FromMilliseconds (interval); timer._csallback = callback; return timer.Start (); } /// <summary> /// Starts a recurring timer using the device clock capabilities. /// </summary> /// <remarks>While the callback returns true, the timer will keep recurring or the max interval is reached.</remarks> /// <param name="callback">The action to run when the timer elapses.</param> /// <param name="interval">The interval between invocations of the callback.</param> /// <param name = "maxInterval">The maximum interval before timer stops.</param> public static Timer Start (Func<bool> callback, TimeSpan interval, TimeSpan maxInterval) { var timer = new Timer (); timer._interval = interval; timer._csallback = callback; timer._maxInterval = maxInterval; return timer.Start (); } /// <summary> /// Starts a recurring timer using the device clock capabilities. /// </summary> /// <remarks>While the callback returns true, the timer will keep recurring or the max interval is reached.</remarks> /// <param name="callback">The action to run when the timer elapses.</param> /// <param name="interval">The interval in miliseconds between invocations of the callback.</param> /// <param name = "maxInterval">The maximum interval in miliseconds before timer stops.</param> public static Timer Start (Func<bool> callback, double interval, double maxInterval) { var timer = new Timer (); timer._interval = TimeSpan.FromMilliseconds (interval); timer._csallback = callback; timer._maxInterval = TimeSpan.FromMilliseconds (maxInterval); return timer.Start (); } /// <summary> /// Manually stops the timer. /// </summary> public void Stop () { _cancellationTokenSourse.Cancel (); _csallback = () => { return true; }; } } }