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
a692f5c6ed6130745d2915ff954439ac393817a4
C#
dkultasev/GamePriceChecker
/GamesPriceChecker/PsPriceClient.cs
2.84375
3
using System; using System.Collections.Generic; using System.Linq; namespace GamesPriceChecker { public class PsPriceClient : IPsPriceClient { private readonly IWebBrowserOperations _browserOperations; private const string BaseUrl = "https://psprices.com/region-ua/discounts?sort=date&platform=PS4"; public PsPriceClient(IWebBrowserOperations browserOperations) { if (browserOperations == null) throw new ArgumentNullException(nameof(browserOperations)); _browserOperations = browserOperations; } public List<GamePrice> GetAllGames() { var gamesList = new List<GamePrice>(); var page = _browserOperations.GetSourceByUrl(GetUrlByPage(1)); int pagesCount = GetPageCount(page); for (var i = 0; i < pagesCount; i++) { var gamesFromPage = GetGamesFromPage(_browserOperations.GetSourceByUrl(GetUrlByPage(i + 1))); gamesList.AddRange(gamesFromPage); } return gamesList; } public int GetPageCount(string source) { HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument(); doc.LoadHtml(source); var test = doc.DocumentNode.SelectNodes("//*[@id=\"pjax-container\"]/div[3]/div/div[4]/ul/li[*]"); return int.Parse(test.Last().InnerText); } public List<GamePrice> GetGamesFromPage(string page) { var games = new List<GamePrice>(); var doc = new HtmlAgilityPack.HtmlDocument(); doc.LoadHtml(page); var nodes = doc.DocumentNode.SelectNodes("//*[@id=\"pjax-container\"]/div[2]/div/div[*]/div"); foreach (var game in nodes) { if (game.ChildNodes.Count == 7) continue; var i = 0; var newGame = new GamePrice() { Platform = "PS4" }; foreach (var gameChildNode in game.ChildNodes) { var temp = gameChildNode.InnerText; if (i == 3) { newGame.Name = temp; } if (i == 5) { var rate = GetRatingFromString(temp); newGame.PsPriceRating = rate[0]; newGame.PsPriceRatingQty = (int)rate[1]; if ((int)rate[1] == 0) i += 2; } if (i == 11) { if (!temp.Contains(newGame.Platform)) { newGame.OfferFinishesAt = GetDateTimeFromString(temp); } else { i += 2; } } if (i == 15) { var prices = GetPricesFromString(temp); newGame.ActualPrice = prices[1]; newGame.OriginalPrice = prices[0]; if (prices.Length == 3) { newGame.SubscriptionPrice = prices[2]; } } i++; } games.Add(newGame); } return games; } public DateTime GetDateTimeFromString(string dateString) { var temp = dateString.Replace("закончится ", ""); return Convert.ToDateTime(temp).ToUniversalTime(); } public double[] GetRatingFromString(string rating) { var temp = rating.Trim().Split(); try { return new double[2] { double.Parse(temp.First()), double.Parse(temp.Last()) }; } catch { return new double[2]; } } private string GetUrlByPage(int page) { return $"{BaseUrl}&page={page}"; } public double[] GetPricesFromString(string prices) { string[] temp; var result = new double[3]; if (prices.Contains("nbsp") || prices.Contains("Бесплатно")) { double a = 0; temp = prices.Trim().Replace("Бесплатно", "0").Replace("UAH", "").Replace(" &rarr;", "").Replace("&nbsp; ", "").Split(); var newList = temp.Where(x => double.TryParse(x, out a)).ToList(); result[0] = double.Parse(newList[0]); result[1] = prices.Contains("rarr") && !prices.Contains("Бесплатно") ? double.Parse(newList[1]) : double.Parse(newList[0]); result[2] = double.Parse(newList.Last()); } else { temp = prices.Trim().Replace("UAH", "").Replace(" &rarr;", "").Split(); result[0] = double.Parse(temp.First()); result[1] = double.Parse(temp.Last()); result[2] = double.Parse(temp.Last()); } return result; } } }
3eafb5331e926282c8ba26c6942a559a4db15540
C#
Gurlox/file-manager
/DataModels/DiscElement.cs
2.65625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DataModels { public abstract class DiscElement { string path; public DiscElement(string path) { this.path = path; } public string Path { get { return path; } } public abstract DateTime CreationTime { get; } public abstract string Name { get; } public string ParentDirectory { get { return System.IO.Path.GetDirectoryName(Path); } } string parentDirectory; } }
d5801ee008a9afa6fbd62ebe6cfd11a3fa68af51
C#
AlVSkvortsov/TestForVeeamSoftware
/TestForVeeamSoftware/Program.cs
2.890625
3
using System; using System.IO; using System.IO.Compression; using TestForVeeamSoftware.CheckInputParameters; using TestForVeeamSoftware.DataObjects; using TestForVeeamSoftware.FileProcessing; using TestForVeeamSoftware.ResultOutputManager; namespace TestForVeeamSoftware { class Program { static void Main(string[] args) { try { IResultOutputManager resultOutput = new ConsoleResultOutputManager(); ICheckInputParameters checkInputParameters = new SimpleCheckInputParameters(resultOutput, args); if (checkInputParameters.CheckParameters()) { IInputParameters inputParameters = new InputParameters(args); IFileProcessing fileProcessing; switch (inputParameters.OperationName) { case Operation.compress: fileProcessing = new CompressProcessing(inputParameters); break; case Operation.decompress: fileProcessing = new DecompressProcessing(inputParameters); break; default: throw new Exception("Некорректное наименование операции."); }; fileProcessing.Processing(); //Compress(inputParameters.SourceFileName, inputParameters.ResultFileName); //Decompress(inputParameters.ResultFileName, Path.GetDirectoryName(inputParameters.SourceFileName) + @"\result.mpq"); } resultOutput.RenderResult(); } catch(Exception ex) { Console.WriteLine($"Fatal error: {ex.Message}"); } #if DEBUG Console.ReadKey(); #endif } public static void Compress(string sourceFile, string compressedFile) { // поток для чтения исходного файла using (FileStream sourceStream = new FileStream(sourceFile, FileMode.OpenOrCreate)) { // поток для записи сжатого файла using (FileStream targetStream = File.Create(compressedFile)) { // поток архивации using (GZipStream compressionStream = new GZipStream(targetStream, CompressionMode.Compress)) { sourceStream.CopyTo(compressionStream); // копируем байты из одного потока в другой Console.WriteLine("Сжатие файла {0} завершено. Исходный размер: {1} сжатый размер: {2}.", sourceFile, sourceStream.Length.ToString(), targetStream.Length.ToString()); } } } } public static void Decompress(string compressedFile, string targetFile) { // поток для чтения из сжатого файла using (FileStream sourceStream = new FileStream(compressedFile, FileMode.OpenOrCreate)) { // поток для записи восстановленного файла using (FileStream targetStream = File.Create(targetFile)) { // поток разархивации using (GZipStream decompressionStream = new GZipStream(sourceStream, CompressionMode.Decompress)) { decompressionStream.CopyTo(targetStream); Console.WriteLine("Восстановлен файл: {0}", targetFile); } } } } } }
5519473d20dff3a99170b67449f0693af45e03a8
C#
PiotrZalfresso/SWDiSK
/Symulator/GeneticAlgorithm.cs
3.15625
3
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Symulator { class GeneticInstanceIComparer : IComparer { int IComparer.Compare(Object x, Object y) { Tuple<int[], long> t1 = (Tuple<int[], long>)x; Tuple<int[], long> t2 = (Tuple<int[], long>)y; if (t1.Item2 < t2.Item2) // Item2 zawiera odległości między miastami { return -1; } else if (t1.Item2 > t2.Item2) { return 1; } else return 0; } } public class GeneticAlgorithm { int populationSize; int generationsNmb; Random generator = new Random(); public int PopulationSize { get { return populationSize; } set { populationSize = value; } } public int GenerationsNmb { get { return generationsNmb; } set { generationsNmb = value; } } public GeneticAlgorithm(int populationSize = 200, int generationsNmb = 500) { this.populationSize = populationSize; this.generationsNmb = generationsNmb; } public int[] Calculate(IGeneticAlgorithm instance) { int[][] popul = new int[populationSize][]; for (int i=0; i < populationSize; i++) { popul[i] = instance.GetInitialSolution(); int c = 0; while (instance.Check(popul, i) && c < 10) { popul[i] = instance.Mutate(popul[i]); c++; } } popul = Sort(popul, instance); for (int k = 0; k < generationsNmb; k++) { for (int i = populationSize / 2; i < populationSize - 1; i += 2) { if (popul[i - populationSize / 2] == null) { Console.WriteLine("null!"); } Array.Copy(popul[i - populationSize / 2], popul[i], instance.GetInstanceSize()); Array.Copy(popul[i + 1 - populationSize / 2], popul[i + 1], instance.GetInstanceSize()); Tuple<int[], int[]> afterCross = instance.Crossover(popul[i], popul[i + 1]); popul[i] = afterCross.Item1; popul[i + 1] = afterCross.Item2; int c = 0; while (instance.Check(popul, i) && c < 10) { popul[i] = instance.Mutate(popul[i]); c++; } c = 0; while (instance.Check(popul, i + 1) && c < 10) { popul[i + 1] = instance.Mutate(popul[i + 1]); c++; } } popul = Sort(popul, instance); for (int i = 1; i < populationSize; i++) { if (generator.Next(100) < 20) popul[i] = instance.Mutate(popul[i]); int c = 0; while (instance.Check(popul, i) && c < 10) { popul[i] = instance.Mutate(popul[i]); c++; } } popul = Sort(popul, instance); } return instance.ConvertToFinalSolution(popul[0]); } private int[][] Sort(int[][] popul, IGeneticAlgorithm instance) { Tuple<int[], long>[] temp = new Tuple<int[], long>[populationSize]; for (int i = 0; i < populationSize; i++) { temp[i] = new Tuple<int[], long>(popul[i], instance.GetCost(popul[i])); } Array.Sort(temp, new GeneticInstanceIComparer()); int[][] sorted = new int[populationSize][]; for (int i = 0; i < populationSize; i++) { sorted[i] = new int[instance.GetInstanceSize()]; Array.Copy(temp[i].Item1, sorted[i], instance.GetInstanceSize()); } // Console.WriteLine($"Element 0 {temp[0].Item2}, a element 2 ma {temp[1].Item2}, a populacja {PopulationSize}, a ostatni... {temp[PopulationSize-1].Item2}"); return sorted; } } }
a7bb27ae665b54dfe09562ccc054eb57bdcc217f
C#
ViennaAdvantage/ERP-CMR-DMS
/ViennaAdvantageWeb/ModelLibrary/Process/NoteDelete.cs
2.515625
3
/******************************************************** * Module Name : Process * Purpose : Delere Notes (Notice) * Author : Jagmohan Bhatt * Date : 10-Nov-2009 ******************************************************/ using System; using System.Collections.Generic; using System.Linq; using System.Text; using VAdvantage.Logging; using VAdvantage.DataBase; using VAdvantage.ProcessEngine;namespace VAdvantage.Process { public class NoteDelete : ProcessEngine.SvrProcess { private int p_AD_User_ID = -1; //Prepare protected override void Prepare() { ProcessInfoParameter[] para = GetParameter(); for (int i = 0; i < para.Length; i++) { String name = para[i].GetParameterName(); if ((para[i].GetParameter() == null) || (para[i].GetParameter().ToString() == "")) { } else if (name.Equals("AD_User_ID")) { p_AD_User_ID = Utility.Util.GetValueOfInt(para[i].GetParameter()); } else log.Log(Level.SEVERE, "prepare - Unknown Parameter: " + name); } } /// <summary> /// Do IT /// </summary> /// <returns></returns> protected override string DoIt() { log.Info("doIt - AD_User_ID=" + p_AD_User_ID); String sql = "DELETE FROM AD_Note WHERE AD_Client_ID=" + GetAD_Client_ID(); if (p_AD_User_ID > 0) { sql += " AND AD_User_ID=" + p_AD_User_ID; } // int no = DataBase.DB.ExecuteQuery(sql, null, Get_TrxName()); return "@Deleted@ = " + no; } } }
c30bf113894647325097cb05e7c931b656164ed6
C#
moxixuan/Rediska
/Rediska/Commands/Lists/LINSERT.cs
2.5625
3
namespace Rediska.Commands.Lists { using System; using System.Collections.Generic; using System.Globalization; using Protocol; using Protocol.Visitors; public sealed class LINSERT : Command<LINSERT.Result> { private static readonly PlainBulkString name = new PlainBulkString("LINSERT"); private static readonly PlainBulkString before = new PlainBulkString("BEFORE"); private static readonly PlainBulkString after = new PlainBulkString("AFTER"); private readonly Key key; private readonly Where where; private readonly BulkString pivot; private readonly BulkString element; public LINSERT(Key key, Where where, BulkString pivot, BulkString element) { this.key = key; this.where = where; this.pivot = pivot; this.element = element; } public override IEnumerable<BulkString> Request(BulkStringFactory factory) => new[] { name, key.ToBulkString(factory), where == Where.BEFORE ? before : after, pivot, element }; public override Visitor<Result> ResponseStructure => IntegerExpectation.Singleton.Then(reply => new Result(reply)); public enum Status : byte { PivotNotFound, ListIsEmpty, Ok } public enum Where : byte { BEFORE, AFTER } public readonly struct Result { public Result(long reply) { if (reply < -1) { throw new ArgumentOutOfRangeException(nameof(reply), "Reply must be -1 or greater"); } Reply = reply; } public Status Status => Reply switch { -1 => Status.PivotNotFound, 0 => Status.ListIsEmpty, _ => Status.Ok }; public long ListLength => Status == Status.Ok || Status == Status.ListIsEmpty ? Reply : throw new InvalidOperationException("Pivot not found"); public long Reply { get; } public override string ToString() => Reply.ToString(CultureInfo.InvariantCulture); } } }
4b4f2db52953ef7b48ee2bd3df053c56331e2fe7
C#
devmsc/Catalog
/Catalog/Features/QuestionFeatures/AddQuestion/AddQuestionRequestHandler.cs
2.609375
3
using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Catalog.Models.Questions; using Catalog.Repositories.Questions; using MediatR; namespace Catalog.Features.QuestionFeatures.AddQuestion { public class AddQuestionRequestHandler : IRequestHandler<AddQuestionRequest, AddQuestionResponse> { private IQuestionsRepository _questionsRepository; public AddQuestionRequestHandler(IQuestionsRepository questionsRepository) { _questionsRepository = questionsRepository; } public async Task<AddQuestionResponse> Handle(AddQuestionRequest request, CancellationToken cancellationToken) { var triggers = request.Triggers.Select(item => new Trigger(item)).ToList(); var questionId = await _questionsRepository.Insert(new Question(request.Content, request.QuestionType, triggers), cancellationToken); return await Task.FromResult(AddQuestionResponse.GetSuccess(questionId)); } } }
40136340fcde07233d7df4532aebecf33d64a5f5
C#
kimykunjun/test
/Acms.Core/Domain/EmployeeBranchRights.cs
2.609375
3
using System; namespace Acms.Core.Domain { /// <summary> /// Summary description for EmployeeBranchRights. /// </summary> public class EmployeeBranchRights { protected Branch _branch; protected Employee _employee; public EmployeeBranchRights() { // // TODO: Add constructor logic here // } public EmployeeBranchRights(Branch branch, Employee employee) { this._branch = branch; this._employee = employee; } public Branch Branch { set{_branch = value;} get{return _branch;} } public Employee Employee { set{_employee = value;} get{return _employee;} } } }
f13699bc77b04fbb7f7ed4fd7b99d8d230b5efdd
C#
Betclic/CodingDojo-Katas
/FRUITSHOP/y.guillin_w.delmas/CodeDojo.Model/Cashier.cs
3.171875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CodeDojo.Model { public class Cashier { List<Product> _products; List<Promotion> _promotions; private string _countryCode; public Cashier(string countryCode) { _countryCode = countryCode; _promotions = new List<Promotion>(); _products = new List<Product>(); } public Cashier() { _countryCode = string.Empty; _promotions = new List<Promotion>(); _products = new List<Product>(); } public void AddPromotion(Promotion promotion) { _promotions.Add(promotion); } public void Add(Product product) { _products.Add(product); } public int Total() { int somme = 0; foreach (var item in _products) { somme += item.Price; } return somme - GetRemise(); } private int GetRemise() { var somme = 0; foreach (var promotion in _promotions) { if (String.IsNullOrEmpty(promotion.ProductName)) { var productQuantity = _products.Count(p => p.CountryCode == promotion.CountryCode); var t = Convert.ToInt16(productQuantity / promotion.QuantityTrigger); somme += t * promotion.Remise; } else { var productQuantity = _products.Count(p => (p.Name == promotion.ProductName) && p.CountryCode == promotion.CountryCode); var t = Convert.ToInt16(productQuantity / promotion.QuantityTrigger); somme += t * promotion.Remise; } } return somme; } public override string ToString() { return Total().ToString(); } } }
7a7aba837ea2453c1e9d1652b2850cd3564de1f7
C#
urpablo/ConstruccionAppsInformaticas
/Ejercicio.41/Program.cs
3.390625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Ejercicio._41 { class Program { static void Main(string[] args) { string strFecha; bool flag = false; DateTime Fecha; bool RtaFlag = false; int i = 0; string Rta; var numeros = new List<DateTime>(); do { do { Console.WriteLine("Ingrese una fecha"); strFecha = Console.ReadLine(); flag = DateTime.TryParse(strFecha, out Fecha); if (flag == false) { Console.WriteLine("Debe ingresar una fecha no vacia"); } } while (flag == false); i = i + 1; numeros.Add(Fecha); Console.WriteLine("Desea seguir agregando Fechas?"); Rta = Console.ReadLine(); if (Rta == "No") { RtaFlag = true; } } while (RtaFlag == false); numeros.Sort(); foreach (DateTime value in numeros) { Console.WriteLine(value); } //foreach (DateTime s in numeros) // Console.WriteLine(s.ToString("dd/MM/yyyy")); // do // { // Console.WriteLine(numeros[i - 1].ToString("dd/MM/yyyy")); // i = i - 1; // } while (i != 0); Console.ReadKey(); } } }
3e3c45fd6d0eb441f168e97f16b0f7f1cf2a86ea
C#
coolnk/AzureNet
/ProductsServer/ProductsServer/Program.cs
3.40625
3
namespace ProductsServer { using System; using System.Linq; using System.Collections.Generic; using System.ServiceModel; // Implement the IProducts interface. class ProductsService : IProducts { // Populate array of products for display on website ProductData[] products = new[] { new ProductData{ Id = "1", Name = "Rock", Quantity = "1"}, new ProductData{ Id = "2", Name = "Paper", Quantity = "3"}, new ProductData{ Id = "3", Name = "Scissors", Quantity = "5"}, new ProductData{ Id = "4", Name = "Well", Quantity = "2500"}, }; // Display a message in the service console application // when the list of products is retrieved. public IList<ProductData> GetProducts() { Console.WriteLine("GetProducts called."); return products; } } class Program { // Define the Main() function in the service application. static void Main(string[] args) { var sh = new ServiceHost(typeof(ProductsService)); sh.Open(); Console.WriteLine("Press ENTER to close"); Console.ReadLine(); sh.Close(); } } }
e54e54912f54ab8ad88975cb8fc12c7cf70f2aa6
C#
narojay/csharp-design-pattern
/模板方法模式/Program.cs
3.34375
3
using System; namespace 模板方法模式 { public abstract class Recipe { public void Cook() { AddOil(); AddVegatable(); AddWater(); } public void AddOil() { Console.WriteLine("add oil"); } public void AddWater() { Console.WriteLine("add water"); } public abstract void AddVegatable(); } public class TomatoRecipe : Recipe { public override void AddVegatable() { Console.WriteLine("add tomato"); } } public class PotatoRecipe : Recipe { public override void AddVegatable() { Console.WriteLine("add Potato"); } } public class Client { public static void Main(string[] args) { Recipe recipe1 = new PotatoRecipe(); recipe1.Cook(); Console.WriteLine("===================================="); Recipe recipe2 = new TomatoRecipe(); recipe2.Cook(); } } }
71f22186338afb3a7e445f136f350398f43735d5
C#
shendongnian/download4
/code11/1928796-58226591-206559495-2.cs
2.609375
3
public static void SetFileProtection(string filePath) { NSMutableDictionary dict = new NSMutableDictionary (); var protection = new NSString("NSFileProtectionCompleteUnlessOpen"); dict.Add((new NSString("NSFileProtectionKey") as NSObject), (protection as NSObject)); NSError error; NSFileManager.DefaultManager.SetAttributes(dict, filePath, out error); if (error != null) System.Console.WriteLine("SetFileProtection Error: " + error.Description); } You can test the functionality using [iExplorer][2]. You will see that the data won't be accessible unless the device is trusted. Choose the appropriate Protection level with the help of the Data Protection Classes in the official docs: > (NSFileProtectionComplete): The class key is protected with a key derived from the user passcode and the device UID. Shortly after the user locks a device (10 seconds, if the Require Password setting is Immediately), the decrypted class key is discarded, rendering all data in this class inaccessible until the user enters the passcode again or unlocks the device using Touch ID or Face ID. [1]: https://www.apple.com/business/docs/site/iOS_Security_Guide.pdf [2]: https://macroplant.com/iexplorer
b6ce00cbe08ccc228e44210255e02f40e6baafd8
C#
Baltiyski/Terelik-Academy
/00.Exams/2013-2014/C# Exam 1/Exam 1 - 6 December 2013 Morning/03.XExpression/XExpression.cs
3.71875
4
using System; class XExpression { static void Main(string[] args) { string expression = Console.ReadLine(); decimal sum = 0; decimal bracketResult = 0; char currOperator = '+'; char bracketOperator = '+'; bool inBraket = false; foreach (var symbol in expression) { if (symbol == '(') { inBraket = true; continue; } if (symbol == ')') { inBraket = false; switch (currOperator) { case '+': sum += bracketResult; break; case '-': sum -= bracketResult; break; case '*': sum *= bracketResult; break; case '/': sum /= bracketResult; break; default: break; } bracketResult = 0; bracketOperator = '+'; } if (symbol == '+' || symbol == '-' || symbol == '*' || symbol == '/') { if (inBraket) { bracketOperator = symbol; } else { currOperator = symbol; } } if (char.IsDigit(symbol)) { int currNum = symbol - '0'; if (inBraket) { switch (bracketOperator) { case '+': bracketResult += currNum; break; case '-': bracketResult -= currNum; break; case '*': bracketResult *= currNum; break; case '/': bracketResult /= currNum; break; default: break; } } else { switch (currOperator) { case '+': sum += currNum; break; case '-': sum -= currNum; break; case '*': sum *= currNum; break; case '/': sum /= currNum; break; default: break; } } } } Console.WriteLine("{0:F2}",sum); } }
4874415b95af05b4bb58eb1a611d76d50725dd5e
C#
NedSheynji13/SecretsOfLight
/Assets/Scripts/ParallaxScrolling.cs
2.609375
3
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ParallaxScrolling : MonoBehaviour { //empty GameObject notwendig, script wird auf dieses gelegt. beim ausrichten der Ebenen: wenn man eine Ebene näher an der Kamera platziert bewegt sie sich schneller und umgekehrt public Transform[] backgrounds; //array für die ebenen private float[] parallaxScales; public float parallaxAmount = 1f; //muss über 0 sein damit Parallax scrolling angewand wird private Transform cam; private Vector3 previousCamPos; private void Awake() { cam = Camera.main.transform; } // Use this for initialization void Start () { previousCamPos = cam.position; parallaxScales = new float[backgrounds.Length]; for (int i = 0; i < backgrounds.Length; i++) { parallaxScales[i] = backgrounds[i].position.z * -1; } } // Update is called once per frame void Update () { for (int i = 0; i < backgrounds.Length; i++) { float parallax = (previousCamPos.x - cam.position.x) * parallaxScales[i]; float backgroundTargetPosX = backgrounds[i].position.x + parallax; Vector3 backgroundTargetPos = new Vector3(backgroundTargetPosX, backgrounds[i].position.y, backgrounds[i].position.z); //fade zwischen currPos und targetPos backgrounds[i].position = Vector3.Lerp(backgrounds[i].position, backgroundTargetPos, parallaxAmount * Time.deltaTime); } previousCamPos = cam.position; } }
a217407b85d5d8320aaa7464721735de75cc8516
C#
grofab95/ExcelUtilities
/PeselUtilities/Pesel.cs
2.65625
3
using System; namespace PeselUtilities { public class Pesel { public string InString { get; set; } public long InNumber { get; set; } public string CellLocalization { get; set; } public PeselFactors PeselFactors { get; set; } public DateTime BornDate { get; set; } public Pesel(string inString, string cellLocalization) { InString = inString; CellLocalization = cellLocalization; PeselValidations.ValidatePeselLengthInCell(InString, CellLocalization); PeselFactors = new PeselMonthTranslator( PeselNumberTranslator.ExtractPeselFactors(InString), Enums.ReturnTypeWhenStWrong.Exception, cellLocalization) .GetCorrectPeselFactors(); PeselValidations.ValidateMonthLenghtByYear(PeselFactors, CellLocalization); BornDate = GetBornDateFromPesel(); InNumber = long.Parse(inString); } private DateTime GetBornDateFromPesel() => new DateTime(PeselFactors.Year, PeselFactors.Month, PeselFactors.Day); } }
75f3d58fe3e00a3635590c8180d0dcbe13b8937b
C#
srsarangi/AutonomousDriving
/city/Assets/Scripts/WorldState/WorldState.cs
2.65625
3
using System.Collections.Generic; using UnityEngine; namespace CarWorld { public class WorldState: MonoBehaviour { #region Singelton public static WorldState _instance; public static WorldState Instance { get { return _instance; } } private void SetupSingelton() { if (_instance != null) { Debug.LogError("Error in settings. Multiple singeltons exists: "); } else { _instance = this; } } #endregion [field: SerializeField] public float SteerAngle { get; set; } [field: SerializeField] public int TotalNumberOfPoints { get; set; } [field: SerializeField] public int LeftLanes { get; set; } [field: SerializeField] public int RightLanes { get; set; } public int MyLane { get; set; } [field: SerializeField] public char TrafficLightColor { get; set; } public BBox[] CarBBoxes { get; set; } public BBox[] BikeBBoxes { get; set; } public BBox[] PedestrianBBoxes { get; set; } private void Awake() { SetupSingelton(); WorldState.Instance.SteerAngle = 0; WorldState.Instance.TotalNumberOfPoints = 0; WorldState.Instance.LeftLanes = 0; WorldState.Instance.RightLanes = 0; WorldState.Instance.TrafficLightColor = 'u'; WorldState.Instance.CarBBoxes = new BBox[] { }; WorldState.Instance.BikeBBoxes = new BBox[] { }; WorldState.Instance.PedestrianBBoxes = new BBox[] { }; } // private static void updateObjects(Dictionary<string, List<List<float>>> json) // { // BBox[] carBoxes = new BBox[json["c"].Count] { }; // foreach (var l in json["c"]) // { // float x = l[0], y = l[1], z = l[2]; // float dx = l[3], dy = l[4], dz = l[5]; // float direction = l[7]; // BBox b = new BBox(x, y, z, dx, dy, dz, direction); // // } // } public void ChangeLane(char direction) { // Move left if (direction == 'l') { } // Move right else { } } public class BBox { public BBox(float x, float y, float z, float dx, float dy, float dz, float direction) { this.Center = new Vector3(x, y, z); this.Length = dx * 2; this.Breadth = dy * 2; this.Height = dz * 2; this.Direction = direction; } private Vector3 Center { get; set; } private float Length { get; set; } private float Breadth { get; set; } private float Height { get; set; } private float Direction { get; set; } public Vector3[] GETCornerCoordinates() { Vector3[] cords = { new Vector3(Center.x + Length/2,Center.y + Breadth/2, Center.z + Height/2), new Vector3(Center.x + Length/2,Center.y + Breadth/2, Center.z - Height/2), new Vector3(Center.x + Length/2,Center.y - Breadth/2, Center.z + Height/2), new Vector3(Center.x + Length/2,Center.y - Breadth/2, Center.z - Height/2), new Vector3(Center.x - Length/2,Center.y + Breadth/2, Center.z + Height/2), new Vector3(Center.x - Length/2,Center.y + Breadth/2, Center.z - Height/2), new Vector3(Center.x - Length/2,Center.y - Breadth/2, Center.z + Height/2), new Vector3(Center.x - Length/2,Center.y - Breadth/2, Center.z - Height/2), }; return cords; } } } }
b2a72a685bf1d56c4fc6636fcf26505ca72c5e88
C#
shyoutarou/Exam-70-483_Gerenciar_fluxo
/Exemplos/3_Fluxo_Prog/switch statement/switch statement/Program.cs
3.625
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace switch_statement { class Program { static void Main(string[] args) { var input = Console.ReadLine(); Check(input[0]); CheckWithSwitch(input[0]); Switch_Goto(); Console.ReadLine(); } static void Check(char input) { if (input == 'a' || input == 'e' || input == 'i' || input == 'o' || input == 'u') Console.WriteLine("Input is a vowel"); else Console.WriteLine("Input is a consonant"); } static void CheckWithSwitch(char input) { switch (input) { case 'a': case 'e': case 'i': case 'o': case 'u': { Console.WriteLine("Input is a vowel"); break; } case 'y': { Console.WriteLine("Input is sometimes a vowel."); break; } default: { Console.WriteLine("Input is a consonant"); break; } } } static void Switch_Goto() { int i = 1; switch (i) { case 1: { Console.WriteLine("Case 1"); goto case 2; } case 2: { Console.WriteLine("Case 2"); break; } } } } }
48ee131396dc2ac3360602640b41020872b5633b
C#
basizov/Timetable
/Application/Messages/Create.cs
2.640625
3
using System; using System.Threading; using System.Threading.Tasks; using Application.Core; using Application.DTOs; using Application.Interfaces; using AutoMapper; using Domain.Entities; using MediatR; using Microsoft.EntityFrameworkCore; using Persistence; namespace Application.Messages { public class Create { public class Command : IRequest<Result<MessageDTO>> { public string Body { get; set; } public Guid PostId { get; set; } } public class Handler : IRequestHandler<Command, Result<MessageDTO>> { private readonly DataContext _context; private readonly IUserAccessor _userAccessor; private readonly IMapper _mapper; public Handler(DataContext context, IMapper mapper, IUserAccessor userAccessor) { _mapper = mapper; _userAccessor = userAccessor; _context = context; } public async Task<Result<MessageDTO>> Handle(Command request, CancellationToken cancellationToken) { var post = await _context.Posts.FindAsync(request.PostId); if (post == null) return (null); var user = await _context.Users .Include(u => u.Photo) .SingleOrDefaultAsync(u => u.UserName == _userAccessor.GetUsername()); var comment = new Comment { AuthorId = user.Id, Author = user, Body = request.Body, PostId = post.Id, Post = post }; post.Comments.Add(comment); var success = await _context.SaveChangesAsync() > 0; if (success) return (Result<MessageDTO>.Success(_mapper.Map<MessageDTO>(comment))); return (Result<MessageDTO>.Failure("Ошибка при добавлении комментария")); } } } }
aae5c3151ce0a7fb84e0b2df6dd6f0e32d123a3c
C#
gabrieljakubek/Programacion_y_Laboratorio_2D_2019
/Ejercicios/Jakubek.Gabriel.2.D.Ejercicios/Ejercicio07/Program.cs
3.125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Ejercicio07 { class Program { static int ingreso; static bool auxBool; static bool anoBisiesto = false; static int diaNacimiento; static int mesNacimiento; static int anoNacimiento; static int diasTotales; static DateTime esteAno = DateTime.Now; static void Main(string[] args) { Console.Title = "Ejercicio 07"; do { Console.Write("Ingrese su año de nacimiento: "); int.TryParse(Console.ReadLine(), out ingreso); if (ingreso <= 0) { Console.WriteLine("Error. Reingresar el año!"); } else { anoNacimiento = ingreso; if (DateTime.IsLeapYear( anoNacimiento))// % 4 == 0 || anoNacimiento % 100 == 0 && anoNacimiento % 400 == 0) { anoBisiesto = true; } auxBool = true; } } while (!auxBool); auxBool = false; do { Console.Write("Ingrese su mes de nacimiento: "); int.TryParse(Console.ReadLine(), out ingreso); if (ingreso <= 0 || ingreso > 12) { Console.WriteLine("Error. Reingresar el mes!"); } else { mesNacimiento = ingreso; auxBool = true; } } while (!auxBool); auxBool = false; do { Console.Write("Ingrese su dia de nacimiento: "); int.TryParse(Console.ReadLine(), out ingreso); if (ingreso <= 0 || (mesNacimiento == 1 || mesNacimiento == 3 || mesNacimiento == 5 || mesNacimiento == 7 || mesNacimiento == 8 || mesNacimiento == 10 || mesNacimiento == 12) && ingreso > 31 || mesNacimiento == 2 && anoBisiesto == false && ingreso > 28 || mesNacimiento == 2 && anoBisiesto == true && ingreso > 29 || (mesNacimiento == 4 || mesNacimiento == 6 || mesNacimiento == 9 || mesNacimiento == 11) && ingreso > 30) { Console.WriteLine("Error. Reingresar el dia!"); } else { diaNacimiento = ingreso; auxBool = true; } } while (!auxBool); for (int i = mesNacimiento; i <= 12; i++) { diasTotales += DateTime.DaysInMonth(anoNacimiento, i); } diasTotales -= diaNacimiento; for (int j = anoNacimiento + 1; j < DateTime.Now.Year; j++) { for (int k = 1; k <= 12; k++) { diasTotales += DateTime.DaysInMonth(j, k); } } diasTotales += esteAno.DayOfYear; Console.Write("Usted a vivido {0} dias", diasTotales); Console.ReadKey(); } } }
55ef135d0ca52bca41910b24d6e5106195f2036b
C#
ShimizuShiori/Reface.AppStarter.NPI
/src/Reface.AppStarter.NPI/Reface.AppStarter.NPI/DbConnectionContext.cs
2.8125
3
using System; using System.Data; using Reface.AppStarter.NPI.Attributes; namespace Reface.AppStarter.NPI { /// <summary> /// 数据库连接上下文 /// </summary> public class DbConnectionContext { /// <summary> /// 唯一标识 /// </summary> public Guid Id { get; private set; } /// <summary> /// 数据库连接 /// </summary> public IDbConnection DbConnection { get; private set; } /// <summary> /// 数据库事务 /// </summary> public IDbTransaction DbTransaction { get; private set; } /// <summary> /// 嵌套的深度 /// </summary> private int deep = 0; public DbConnectionContext(IDbConnection dbConnection) { DbConnection = dbConnection; this.Id = Guid.NewGuid(); DebugLogger.Debug($"{nameof(DbConnectionContext)}.Ctor : Id = {Id}"); } /// <summary> /// 开启事务。 /// 由于 <see cref="TransactionAttribute"/> 会存在事务嵌套的问题, /// 对于同一个 <see cref="DbConnectionContext"/> 实例,当事务已经开启,再使用此方法将不会再次开启事务。 /// </summary> public void BeginTran() { if (++deep == 1) { if (this.DbConnection.State != ConnectionState.Open) this.DbConnection.Open(); DebugLogger.Info($"BeginTran Deep = {deep} , Id = {Id} "); this.DbTransaction = this.DbConnection.BeginTransaction(); return; } DebugLogger.Warning($"SkipBeginTran Deep = {deep} , Id = {Id}"); } /// <summary> /// 回滚事务。 /// 由于 <see cref="TransactionAttribute"/> 会存在事务嵌套的问题, /// 对于是调用了多次的 <see cref="BeginTran"/> 的 <see cref="DbConnectionContext"/> 实例,第一次回滚的调用,就会对所有任务进行回滚。 /// 设计意图是,当遇到一个异常时,就回滚所有事务。 /// </summary> public void RollbackTran() { if (this.DbTransaction == null) { DebugLogger.Warning($"SkipRollbackTran Tran is null"); return; } deep = 0; DebugLogger.Info($"RollbackTran Deep = {deep} , Id = {Id} "); this.DbTransaction.Rollback(); this.DbTransaction.Dispose(); this.DbTransaction = null; } /// <summary> /// 提交事务。 /// 由于 <see cref="TransactionAttribute"/> 会存在事务嵌套的问题, /// 因此对于执行了多次 <see cref="BeginTran"/> 的 <see cref="DbConnectionContext"/> 实例,只有第一次开启事务所对应的提交事务,才会真正的提交事务。 /// </summary> public void CommitTran() { if (this.DbTransaction == null) { DebugLogger.Warning($"SkipCommitTran Tran is null"); return; } if (deep-- != 1) { DebugLogger.Warning($"SkipCommitTran Deep = {deep} , Id = {Id}"); return; } DebugLogger.Info($"CommitTran Deep = {deep} , Id = {Id} "); this.DbTransaction.Commit(); this.DbTransaction.Dispose(); this.DbTransaction = null; } } }
ec4529d0ac49dd1e937eb63c5abe0ce7a4a419ab
C#
ACMH1/CSExercises
/CSExercises/SectionC/ExC4.cs
3.6875
4
using System; namespace CSExercises { //ABC Taxi Company has the following meter charges based on the kilometres travelled. //Minimum charge: $2.40 (first 0.5 km no additional charges apply) //For the next 8.5 kms the rate is 4 cents for every 100 meters //After that: 5 cents for evey 100 meters //In the above example you should assume that the meter falls every 100 meters.So assume that if the distance travelled(i.e.input) is 12.13 km then it is rounded to 12.20 and the cost would be: //$ 2.40 (first 0.5 km) + //$ 85 * 0.04 (next 8.5 km) + //$ (122 -90) * 0.05 (for distance over 9.0 km) //= $7.40 public class ExC4 { public static void Main(string[] args) { string distanceStr = Console.ReadLine(); double distanceDbl = Convert.ToDouble(distanceStr); Console.WriteLine("${0:0.00}", CalculateFare(distanceDbl)); } public static double CalculateFare(double distance) { double result = 2.4; if (distance > 0.5 && distance <= 9) { result = result + 0.04 * Math.Ceiling((distance - 0.5) * 10); } if (distance > 9) { result = result + 0.4 * 8.5 + 0.05 * Math.Ceiling((distance - 9) * 10); } return result; } } }
9c4d1bab2586fe7ca8b42e6c2e0b0ea67e8c7a10
C#
welshdave/SqlDocStore
/src/SqlDocStore/ChangeTracker.cs
2.59375
3
namespace SqlDocStore { using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; public class ChangeTracker { private readonly ConcurrencyModel _concurrencyModel; public ChangeTracker(ConcurrencyModel concurrencyModel) { _concurrencyModel = concurrencyModel; } public readonly ConcurrentDictionary<object, TrackedDocument> Documents = new ConcurrentDictionary<object, TrackedDocument>(); public IEnumerable<TrackedDocument> Changes => Documents.Values.Where(x => x.State != DocumentState.Unchanged); public IEnumerable<object> Inserts => from doc in Documents where doc.Value.State == DocumentState.Added select doc.Value.Document; public IEnumerable<object> Updates => from doc in Documents where doc.Value.State == DocumentState.Modified select doc.Value.Document; public IEnumerable<object> Deletions => from doc in Documents where doc.Value.State == DocumentState.Deleted select doc.Value.Document; public IEnumerable<T> InsertsFor<T>() { return from doc in Documents where doc.Value.State == DocumentState.Added && doc.Value.Type == typeof(T) select (T) doc.Value.Document; } public IEnumerable<T> UpdatesFor<T>() { return from doc in Documents where doc.Value.State == DocumentState.Modified && doc.Value.Type == typeof(T) select (T) doc.Value.Document; } public IEnumerable<T> DeletionsFor<T>() { return from doc in Documents where doc.Value.State == DocumentState.Deleted && doc.Value.Type == typeof(T) select (T) doc.Value.Document; } public void Track<T>(T document, Guid eTag) { if (UseOptimisticConcurrency) return; var id = IdentityHelper.GetIdFromDocument(document); Documents.AddOrUpdate( id, new TrackedDocument { Document = document, Type = typeof(T), State = DocumentState.Unchanged, ETag = eTag }, (key, oldValue) => { oldValue.Document = document; oldValue.Type = typeof(T); oldValue.ETag = eTag; return oldValue; }); } public void Insert<T>(T document) { var id = IdentityHelper.GetIdFromDocument(document); Documents.AddOrUpdate(id, new TrackedDocument { Document = document, Type = typeof(T), State = DocumentState.Added, ETag = Guid.NewGuid() }, (key, oldValue) => { oldValue.Document = document; oldValue.Type = typeof(T); return oldValue; }); } public void Update<T>(T document) { var id = IdentityHelper.GetIdFromDocument(document); if (!UseOptimisticConcurrency) if (!Documents.TryGetValue(id, out _)) throw new InvalidOperationException("Can't update unknown document"); Documents.AddOrUpdate(id, new TrackedDocument { Document = document, State = DocumentState.Modified, Type = typeof(T) }, (key, oldValue) => { oldValue.Document = document; oldValue.Type = typeof(T); oldValue.State = DocumentState.Modified; return oldValue; }); } public void DeleteById(object id) { if (!UseOptimisticConcurrency) if (!Documents.TryGetValue(id, out _)) throw new InvalidOperationException("Can't delete unknown document"); Documents.AddOrUpdate(id, new TrackedDocument { Document = new DeletedDocument(id), State = DocumentState.Deleted, Type = typeof(object) }, (key, oldValue) => { oldValue.State = DocumentState.Deleted; return oldValue; }); } public void Delete<T>(T document) { var id = IdentityHelper.GetIdFromDocument(document); DeleteById(id); } public void MarkChangesSaved() { foreach (var document in Documents) document.Value.State = DocumentState.Unchanged; } private bool UseOptimisticConcurrency => _concurrencyModel == ConcurrencyModel.Optimistic; } }
05c2945dfac96c7353a422c70fe4ae63f575409d
C#
HRAshton/SetEliteClient
/SetElite.Client/ParameterEntities/Virtual/ParameterEntity.cs
2.609375
3
using System; using MyToolkit.Command; using MyToolkit.Model; using Newtonsoft.Json; namespace SetElite.Client.ParameterEntities.Virtual { public abstract class VirtualParameterModel : ObservableObject { [JsonProperty(PropertyName = "IsEnabled")] private bool _isEnabled; /// <summary> /// Команда сброса параметра. /// </summary> public virtual RelayCommand ResetCommand => new RelayCommand(Reset); /// <summary> /// Включена ли синхронизация параметра. /// </summary> public virtual bool IsEnabled { get => _isEnabled; set => Set(ref _isEnabled, value); } /// <summary> /// Применить параметр. /// </summary> public abstract void Apply(); /// <summary> /// Сбросить значение параметра. /// </summary> public abstract void Reset(); } }
8f8e80a7b224e1fc1e6d83a17f00bfdf13c8961a
C#
RiderSet/CalculaJuros
/Calcula/Models/Calculo.cs
2.5625
3
using System.ComponentModel.DataAnnotations; namespace Calcula.Models { public class Calculo { public int Id { get; set; } public double ValorInicial{ get; set; } // public decimal ValorFinal { get; set; } public double Juros { get; set; } public int Tempo { get; set; } } //public decimal CalculaJuros(decimal valorInical, decimal juros, int tempo) //{ // this.ValorFinal = (valorInical * (1 + juros)) ^ tempo; //} }
06f970db1fb0fe96e1128e5adacadce0a91b441c
C#
SebastianSinozic/sinozicSebastianKonstruktori
/sinozicSebastianKonstruktori/sinozicSebastianKonstruktori/Program.cs
3.265625
3
using System; namespace sinozicSebastianKonstruktori { class Program { static void Main(string[] args) { Proceduralni x = new Proceduralni(); Objektni y = new Objektni(); Funkcionalni z = new Funkcionalni(); Console.WriteLine("Upišite x vrijednost: "); x.Postotak = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Upišite z vrijednost: "); z.Postotak = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Upišite y vrijednost: "); y.Postotak = Convert.ToInt32(Console.ReadLine()); if (x.Postotak + z.Postotak + y.Postotak != 100) { Console.WriteLine("Neispravan unos podataka!"); } else { if (x.Postotak > y.Postotak && x.Postotak > z.Postotak) { Console.WriteLine("Najviše se koristi Proceduralni!"); } else if (y.Postotak > x.Postotak && y.Postotak > z.Postotak) { Console.WriteLine("Najviše se koristi Objektni!"); } else if (z.Postotak > x.Postotak && z.Postotak > y.Postotak) { Console.WriteLine("Najviše se koristit Funkcionalni!"); } } Console.ReadKey(); } } }
bcd999a7f942ae85aa0d2c4fbe2d5673f5a9e9a1
C#
FlatFishPrincess/clientserver_second
/WEEK5(Windo forms and file IO)/Class 05 Exercises/LinqToXmlFirstLook/LinqToXmlFirstLookProgram.cs
3.390625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; // For older DOM support. using System.Xml; // For newer LINQ to XML support. using System.Xml.Linq; namespace LinqToXmlFirstLook { class LinqToXmlFirstLookProgram { static void Main(string[] args) { Console.WriteLine("***** A Tale of Two XML APIs *****"); BuildXmlDocWithDOM(); BuildXmlDocWithLINQToXml(); Console.WriteLine("XML data saved to output directory."); // Delete a node. DeleteNodeFromDoc(); Console.ReadLine(); } #region Build XML file using System.Xml.dll types. private static void BuildXmlDocWithDOM() { Console.WriteLine("XmlDocwithDOM()"); // Make a new XML document in memory. XmlDocument doc = new XmlDocument(); // Fill this document with a root element // named <Inventory>. XmlElement inventory = doc.CreateElement("Inventory"); // Now, make a sub element named <Car> with // an ID attribute. XmlElement car = doc.CreateElement("Car"); car.SetAttribute("ID", "1000"); // Build the data within the <Car> element. XmlElement name = doc.CreateElement("Name"); // name.Value = "Jimbo"; // this won't work! name.InnerText = "Jimbo"; XmlElement color = doc.CreateElement("Color"); color.InnerText = "Red"; XmlElement make = doc.CreateElement("Make"); make.InnerText = "Ford"; // Add <Name>, <Color> and <Make> to the <Car> // element. car.AppendChild(name); car.AppendChild(color); car.AppendChild(make); // Add the <Car> element to the <Inventory> element. inventory.AppendChild(car); // Insert the complete XML into the XmlDocument object, // and save to file. doc.AppendChild(inventory); doc.Save("Inventory.xml"); } #endregion #region Build XML doc with LINQ to XML private static void BuildXmlDocWithLINQToXml() { Console.WriteLine("XmlDocwithLINQ()"); // Create a 'functional' XML document. XElement doc = new XElement("Inventory", // Root new XElement("Car", new XAttribute("ID", "1000"), // Car node with ID new XElement("Name", "Jimbo"), // Car elements and values new XElement("Color", "Red"), new XElement("Make", "Ford") ) ); // Save to file. doc.Save("InventoryWithLINQ.xml"); } #endregion #region Remove an element. private static void DeleteNodeFromDoc() { // Create a 'functional' XML document. XElement doc = new XElement("Inventory", new XElement("Car", new XAttribute("ID", "1000"), new XElement("Name", "Jimbo"), new XElement("Color", "Red"), new XElement("Make", "Ford") ) ); Console.WriteLine("DeleteNodeFromDoc()\nIn memory inventory XML doc"); Console.WriteLine(doc); Console.WriteLine("Now remove the Name element"); // Delete the Name element from the tree. doc.Descendants("Name").Remove(); Console.WriteLine("Revised car document"); Console.WriteLine(doc); } #endregion } }
6b040ae500a629bafb9a511495c49992d5634c60
C#
Pavlo7/AEVIProject
/AEVIDomain/CShared.cs
2.515625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using System.Data.SqlClient; namespace AEVIDomain { public static class CShared { public static bool IsConnect(string connectionstring, out string msg) { bool ret = false; msg = null; SqlConnection connect; try { connect = new SqlConnection(connectionstring); connect.Open(); if (connect.State == ConnectionState.Open) { ret = true; connect.Close(); } else ret = false; } catch (Exception ex) { msg = ex.Message; ret = false; } return ret; } } }
aa097a8df463070b8a151cf3ea30dae3bf690fc7
C#
tnqv447/ElectronicsStoreManager
/WinformUI/Dialogs/EditItemRelationDialog.cs
2.515625
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; using AppCore.Interfaces; using AppCore.Models; namespace Winform.Dialogs { public partial class EditItemRelationDialog : Form { private readonly IUnitOfWork _unitOfWork; private ItemRelation _model; private IList<ItemRelation> _modifieds; public EditItemRelationDialog(IUnitOfWork unitOfWork, ItemRelation relation, IList<ItemRelation> modifieds) { InitializeComponent(); _unitOfWork = unitOfWork; _modifieds = modifieds; if (relation is null) { MessageBox.Show("Chi tiết truyền vào không tìm thấy", "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Warning); this.Close(); } _model = relation; } private void btnOk_Click(object sender, EventArgs e) { var amount = (int)this.numberAmount.Value; if (amount <= 0) { MessageBox.Show("Số lượng phải lớn hơn 0", "Cánh báo", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } var check = MessageBox.Show("Xác nhận số lượng nhập là " + amount + " ?", "Xác nhận", MessageBoxButtons.OKCancel, MessageBoxIcon.Question); if (check.Equals(DialogResult.Cancel)) return; _model.Amount = amount; var res = _modifieds.Where(m => m.ChildId.Equals(_model.ChildId)); if (res.Any()) res.First().Amount = amount; else _modifieds.Add(_model); this.DialogResult = DialogResult.OK; this.Close(); } private void btnCancel_Click(object sender, EventArgs e) { var check = MessageBox.Show("Hủy thao tác?", "Xác nhận", MessageBoxButtons.OKCancel, MessageBoxIcon.Question); if (check.Equals(DialogResult.Cancel)) return; this.DialogResult = DialogResult.Cancel; this.Close(); } } }
f97d266e501d590ca75790a089b0dde23184c631
C#
PRJ4-GR3-SWT-1/GameOfLife
/GameOfLife/Program.cs
3.046875
3
using System; using System.Diagnostics; namespace GameOfLife { class Program { static void Main(string[] args) { var gol = new GameOfLife(1000); var sw = new Stopwatch(); Console.WriteLine("TaskBarrier:"); sw.Restart(); var golTB = new GameOfLifeTB(1000); golTB.Run(50); Console.WriteLine(sw.Elapsed); Console.WriteLine("Sequential:"); sw.Restart(); gol.Run(50); sw.Stop(); Console.WriteLine(sw.Elapsed); Console.WriteLine("Parallel:"); sw.Restart(); var golP = new GameOfLifeP(1000); golP.Run(50); Console.WriteLine(sw.Elapsed); } } }
6e3f08a6e8e4a80b5df12600da88cdf08bdfd161
C#
dylanlafontaine/Mission-Planner-3D
/Assets/Scripts/MoveUp.cs
2.859375
3
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.Events; using UnityEngine.EventSystems; ///<summary> ///Commented by Dylan L. ///MoveUp -- This class handles the initial behavior of moving a waypoint either up or down. ///It adds Event Handlers to the MoveUpList and MoveDownList buttons that changes the order in the Waypoints list. ///When the user clicks the up or down button then the function to handle the moving occurs in the waypoints class ///and the waypoint that was selected moves either up or down based on the button pressed. This change will be re-renderd and ///the directional "arrow" will be facing the correct way. ///</summary> public class MoveUp : MonoBehaviour { //up represents the button labeled "Up" in the MoveUp script object //down represents the button labeled "Down" in the MoveUp script object public Button up, down; //waypoints represents a GameObject of class type "Waypoints" private Waypoints waypoints; //selectedSphere is not initially assigned to any value public GameObject selectedSphere; //selectedWaypoint is not initially assigned to any value public Waypoint selectedWaypoint; // Start is called before the first frame update void Start() { //Adds Event Listeners to the "up" and "down" buttons that call the "moveUp" and "moveDown" functions respectively up.onClick.AddListener(moveUp); down.onClick.AddListener(moveDown); //waypoints is initialized to the Waypoints class waypoints = (Waypoints)FindObjectOfType(typeof(Waypoints)); } private void moveUp() { //calls the moveWaypointUp function defined in the Waypoints class waypoints.moveWaypointUp(SpawnUI.selectedWaypoint); } private void moveDown() { //calls the moveWaypointDown function defined in the Waypoints class waypoints.moveWaypointDown(SpawnUI.selectedWaypoint); } }
949bfa54d9c29e4253121268dc545e7f31978a01
C#
shendongnian/download4
/latest_version_download2/140733-28576472-84017022-4.cs
2.6875
3
List<BudgtedData> budgetData = new List<BudgtedData>(); budgetData.Add(new BudgtedData() { BudgetedCpmDataId = 1, ForecastMonth = 12, ForecastYear = 2014 }); budgetData.Add(new BudgtedData() { BudgetedCpmDataId = 1, ForecastMonth = 1, ForecastYear = 2014 }); budgetData.Add(new BudgtedData() { BudgetedCpmDataId = 1, ForecastMonth = 1, ForecastYear = 2013 }); budgetData.Add(new BudgtedData() { BudgetedCpmDataId = 2, ForecastMonth = 2, ForecastYear = 2014 }); budgetData.Add(new BudgtedData() { BudgetedCpmDataId = 2, ForecastMonth = 1, ForecastYear = 2015 }); var res = budgetData.Where(r => ((r.ForecastYear == (DateTime.Today.Year - 1) && r.ForecastMonth >= DateTime.Today.Month) || (r.ForecastYear == DateTime.Today.Year && r.ForecastMonth < DateTime.Today.Month))).ToList(); foreach (BudgtedData item in res) { Console.WriteLine(item.ForecastYear + " "+ item.ForecastMonth); }
1d6f2a07c95ba5d93f822274a2800a67f408a633
C#
lampenlampen/PrivateWiki
/PrivateWiki.Dependencies/Components/NLog/NLogAdapter.cs
2.515625
3
using System; using NLog; using PrivateWiki.Services.Logger; using ILogger = PrivateWiki.Services.Logger.ILogger; namespace PrivateWiki.Dependencies.Components.NLog { public class NLogAdapter : ILogger { private readonly Logger _logger = LogManager.GetLogger("PrivateWiki"); public void Log(LogEntry entry) { if (entry.Exception is null) { _logger.Log(entry.Severity.ToNLogSeverity(), entry.Message); } else { _logger.Log(entry.Severity.ToNLogSeverity(), entry.Exception, entry.Message); } } } internal static class LoggingEventTypeExtensions { internal static LogLevel ToNLogSeverity(this LoggingEventType severity) { return severity switch { LoggingEventType.Debug => LogLevel.Debug, LoggingEventType.Information => LogLevel.Info, LoggingEventType.Warning => LogLevel.Warn, LoggingEventType.Error => LogLevel.Error, LoggingEventType.Fatal => LogLevel.Fatal, _ => throw new ArgumentOutOfRangeException(nameof(severity), severity, null) }; } } }
b7dcff4bfc11fb3db51ca1757ce9fe6a54712c52
C#
dimixar/JumpyPants-XNA
/JumpyPantsTry1/JumpyPantsTry1/ScreenManager/GameScreen.cs
2.703125
3
using System; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Input.Touch; using System.IO; namespace JumpyPants { /// <summary> /// Enum-ul descrie stările de tranziție a unui screen /// </summary> public enum ScreenState { TransitionOn, Active, TransitionOff, Hidden, } /// <summary> /// Colecția de proprietăți și metode, care vor fi folosite pentru controlul mai ușor a stării jocului /// </summary> public abstract class GameScreen { #region Proprietati /// <summary> /// Indica daca screen-ul care trebuie să se deschidă e de tip popup sau nu. /// </summary> public bool IsPopup { get { return isPopup; } protected set { isPopup = value; } } bool isPopup = false; /// <summary> /// Determină cât timp are nevoie ca să facă o tranziție screen-ul activat. /// </summary> public TimeSpan TransitionOnTime { get { return transitionOnTime; } protected set { transitionOnTime = value; } } TimeSpan transitionOnTime = TimeSpan.Zero; /// <summary> /// Determină cât timp are nevoie ca să facă o tranziție screen-ul dezactivat. /// </summary> public TimeSpan TransitionOffTime { get { return transitionOffTime; } protected set { transitionOffTime = value; } } TimeSpan transitionOffTime = TimeSpan.Zero; /// <summary> /// Determină poziția curentă a tranziției, începînd de la zero /// (activat) pînă la unu (tranziționat pînă la sfârșit). /// </summary> public float TransitionPosition { get { return transitionPosition; } protected set { transitionPosition = value; } } float transitionPosition = 1; /// <summary> /// Primește alpha curentă de la tranziția screen-ului, începînd de la zero /// (activat) pînă la unu (tranziționat pînă la sfârșit). /// </summary> public float TransitionAlpha { get { return 1f - TransitionPosition; } } /// <summary> /// Primește și determină starea curentă a tranziției screen-ului. /// </summary> public ScreenState ScreenState { get { return screenState; } protected set { screenState = value; } } ScreenState screenState = ScreenState.TransitionOn; /// <summary> /// Determină dacă screen-ul trebuie să iese din memorie total sau pur și simplu /// să se ducă în spatele screen-ului activ. /// </summary> public bool IsExiting { get { return isExiting; } protected internal set { isExiting = value; } } bool isExiting = false; /// <summary> /// Verifică dacă screen-ul este activ și este capabil la răspuns de la utilizator /// </summary> public bool IsActive { get { return !otherScreenHasFocus && (screenState == ScreenState.TransitionOn || screenState == ScreenState.Active); } } bool otherScreenHasFocus; /// <summary> /// Primește manager-ul screen-ului corespunzător /// </summary> public ScreenManager ScreenManager { get { return screenManager; } internal set { screenManager = value; } } ScreenManager screenManager; /// <summary> /// Primește index-ul jucătorului care controlează la moment screen-ul jocului /// </summary> public PlayerIndex? ControllingPlayer { get { return controllingPlayer; } internal set { controllingPlayer = value; } } PlayerIndex? controllingPlayer; public GestureType EnabledGestures { get { return enabledGestures; } protected set { enabledGestures = value; if (ScreenState == ScreenState.Active) { TouchPanel.EnabledGestures = value; } } } GestureType enabledGestures = GestureType.None; #endregion #region Inițializare /// <summary> /// Încărcăm contentul grafic pentru screen /// </summary> public virtual void LoadContent() { } /// <summary> /// Eliberăm memoria de contentul, care nu este necesar /// </summary> public virtual void UnloadContent() { } #endregion #region Update and Draw public virtual void Update(GameTime gameTime, bool otherScreenHasFocus, bool coveredByOtherScreen) { this.otherScreenHasFocus = otherScreenHasFocus; if (isExiting) { screenState = ScreenState.TransitionOff; if (!UpdateTransition(gameTime, transitionOffTime, 1)) { ScreenManager.RemoveScreen(this); } } else if (coveredByOtherScreen) { if (UpdateTransition(gameTime, transitionOffTime, 1)) { //Încă e ocupat cu tranziția screenState = ScreenState.TransitionOff; } else { //Tranziția a avut loc cu succes screenState = JumpyPants.ScreenState.Hidden; } } else { if (UpdateTransition(gameTime, transitionOnTime, -1)) { screenState = JumpyPants.ScreenState.TransitionOn; } else { screenState = JumpyPants.ScreenState.Active; } } } /// <summary> /// Ajutător pentru actualizarea poziției tranziției screen-ului /// </summary> bool UpdateTransition(GameTime gameTime, TimeSpan time, int direction) { //cât de mult trebuie să ne mișcăm? float transitionDelta; if (time == TimeSpan.Zero) transitionDelta = 1; else { transitionDelta = (float)(gameTime.ElapsedGameTime.TotalMilliseconds / time.TotalMilliseconds); } //Actualizăm poziția tranziției. transitionPosition += transitionDelta * direction; if (((direction < 0) && (transitionPosition <= 0)) || ((direction > 0) && (transitionPosition >= 1))) { transitionPosition = MathHelper.Clamp(transitionPosition, 0, 1); return false; } //Dacă încă e în tranziție, atunci este TRUE. return true; } /// <summary> /// Permite screen-ul să aibă posibilitatea de a face o acțiune de la tastieră sau touch /// </summary> public virtual void HandleInput(InputState input) { } /// <summary> /// Aceasta trebuie apelată atunci când screen-ul trebuie să se desene singur pe dânsul /// </summary> public virtual void Draw(GameTime gameTime) { } #endregion #region Metode Publice /// <summary> /// Spune screen-ului să plece de pe ecran. Această metodă așteaptă pînă ce screen-ul /// a tranziționat complet de pe ecran șî după aceea îl distruge. /// </summary> public void ExitScreen() { if (TransitionOffTime == TimeSpan.Zero) { ScreenManager.RemoveScreen(this); } else { isExiting = true; } } #endregion } }
704e2adff26b12a8d0c8a4be91f42cb975d75f56
C#
jsliugang/FileHelper
/LanguageHelper/TranslateHelper.cs
3.109375
3
using System.Windows.Forms; namespace LanguageHelper { /// <summary> /// 语言翻译工具类 /// </summary> public class TranslateHelper { #region 属性 /// <summary> /// 翻译文件 /// </summary> private static string TranslateFile { get; set; } /// <summary> /// 源语言 /// </summary> private static LanguageType SourceLanguage { get; set; } /// <summary> /// 目标语言 /// </summary> private static LanguageType DestinationLanguage { get; set; } /// <summary> /// 语言类型,缩写abbr /// </summary> public enum LanguageType { /// <summary> /// 简体中文 /// </summary> zh_cn, /// <summary> /// 繁体中文 /// </summary> zh_tw, en_us, en_gb, ja, ko, de, } #endregion public TranslateHelper() { //获取默认翻译文件,同路径下程序名称或窗口名称.json TranslateFile = ""; //默认属性 SourceLanguage = LanguageType.en_us; DestinationLanguage = LanguageType.zh_cn; } #region 获取翻译文件 /// <summary> /// 获取指定翻译文件 /// </summary> /// <param name="FilePath">多语言翻译文件全路径</param> private static void GetTranslateFile(string FilePath) { TranslateFile = FilePath; } #endregion #region 翻译字符串 /// <summary> /// 使用默认翻译文件翻译给定字符串,英文->简体中文 /// </summary> /// <param name="sourcestring">原始字符串</param> /// <returns></returns> public static string Translate_en_2_cn(string sourcestring) { return Translate(sourcestring, SourceLanguage, DestinationLanguage); } /// <summary> /// 使用默认翻译文件翻译给定字符串 /// </summary> /// <param name="sourcestring">原始字符串</param> /// <param name="SourceLanguage">源语言</param> /// <param name="DestinationLanguage">目标语言</param> /// <returns></returns> public static string Translate(string sourcestring, LanguageType SourceLanguage, LanguageType DestinationLanguage) { string result = null; TranslateDetail(sourcestring, TranslateFile, SourceLanguage, DestinationLanguage, ref result); return result; } /// <summary> /// 使用指定翻译文件翻译给定字符串 /// </summary> /// <param name="sourcestring">原始字符串</param> /// <param name="TranslateFile">翻译文件全路径</param> /// <param name="SourceLanguage">源语言</param> /// <param name="DestinationLanguage">目标语言</param> /// <returns></returns> public static string Translate(string sourcestring, string TranslateFile, LanguageType SourceLanguage, LanguageType DestinationLanguage) { string result = null; GetTranslateFile(TranslateFile); TranslateDetail(sourcestring, TranslateFile, SourceLanguage, DestinationLanguage, ref result); return result; } #endregion #region 翻译控件 /// <summary> /// 翻译winform中的控件显示文字,英语->简体中文 /// </summary> /// <param name="f"></param> public static void TranslateControlsInWinform(Form f) { f.Text = Translate_en_2_cn(f.Text); foreach (Control control in f.Controls) { TranslateControl_Recursion(control); } } /// <summary> /// 翻译控件显示文字,递归 /// </summary> /// <param name="c"></param> public static void TranslateControl_Recursion(Control c) { c.Text = Translate_en_2_cn(c.Text); foreach (Control control in c.Controls) { TranslateControl_Recursion(control); } } public static void TranslateControlDetail(Control control) { TranslateControlDetail(c); if (control is TextBox txt) { txt.Text = Translate_en_2_cn(txt.Text); } else if (control is Label lbl) { lbl.Text = Translate_en_2_cn(lbl.Text); } else if (control is Button btn) { btn.Text = Translate_en_2_cn(btn.Text); } else if (control is RichTextBox rtx) { rtx.Text = Translate_en_2_cn(rtx.Text); } else if (control is GroupBox grp) { grp.Text = Translate_en_2_cn(grp.Text); } else if (control is TabControl tab) { for (int i = 0; i < tab.TabPages.Count; i++) { tab.TabPages[i].Text = Translate_en_2_cn(tab.TabPages[i].Text); } } else if (control is MenuStrip menu) { foreach (ToolStripMenuItem subitem in menu.Items) { TranslateMenuStrip_Recursion(subitem); } } else if (control is DataGridView dgv) { for (int i = 0; i < dgv.Columns.Count; i++) { dgv.Columns[i].HeaderText = Translate_en_2_cn(dgv.Columns[i].HeaderText); } } else if (control is TreeView tree) { foreach (TreeNode treeNode in tree.Nodes) { TranslateTreeView_Recursion(treeNode); } } } /// <summary> /// 翻译menustrip控件,递归 /// </summary> /// <param name="toolStripMenuItem"></param> private static void TranslateMenuStrip_Recursion(ToolStripMenuItem toolStripMenuItem) { toolStripMenuItem.Text = Translate_en_2_cn(toolStripMenuItem.Text); foreach (ToolStripMenuItem subitem in toolStripMenuItem.DropDownItems) { subitem.Text = Translate_en_2_cn(subitem.Text); TranslateMenuStrip_Recursion(subitem); } } /// <summary> /// 翻译TreeView控件,递归 /// </summary> /// <param name="treenode"></param> private static void TranslateTreeView_Recursion(TreeNode treenode) { treenode.Text = Translate_en_2_cn(treenode.Text); foreach (TreeNode node in treenode.Nodes) { node.Text = Translate_en_2_cn(node.Text); TranslateTreeView_Recursion(node); } } #endregion #region 翻译细节 /// <summary> /// 使用文件翻译字符串 /// </summary> /// <param name="SourceString">原始字符串</param> /// <param name="TranslateFile">翻译文件</param> /// <param name="SourceLanguage">源语言</param> /// <param name="DestinationLanguage">目标语言</param> /// <param name="DestinationString">翻译结果</param> private static void TranslateDetail(string SourceString, string TranslateFile, LanguageType SourceLanguage, LanguageType DestinationLanguage, ref string DestinationString) { //打开文件 //读取翻译列表 //检查是否有源语言SourceLanguage和源字段SourceString //检查是否有目标语言DestinationLanguage、目标字段DestinationString是否有内容 //返回目标字段内容 DestinationString = SourceString; } #endregion } }
78af468a68b050ae0c31a90462d9d78053ddb05f
C#
Lrs121/WindowsDeviceRecoveryTool_components_decompiled
/System.Spatial/System.Spatial/GeographyCollection.cs
2.65625
3
using System; using System.Collections.ObjectModel; using System.Linq; namespace System.Spatial { // Token: 0x0200001A RID: 26 public abstract class GeographyCollection : Geography { // Token: 0x060000EA RID: 234 RVA: 0x000038F0 File Offset: 0x00001AF0 protected GeographyCollection(CoordinateSystem coordinateSystem, SpatialImplementation creator) : base(coordinateSystem, creator) { } // Token: 0x17000012 RID: 18 // (get) Token: 0x060000EB RID: 235 public abstract ReadOnlyCollection<Geography> Geographies { get; } // Token: 0x060000EC RID: 236 RVA: 0x000038FC File Offset: 0x00001AFC public bool Equals(GeographyCollection other) { bool? flag = base.BaseEquals(other); if (flag == null) { return this.Geographies.SequenceEqual(other.Geographies); } return flag.GetValueOrDefault(); } // Token: 0x060000ED RID: 237 RVA: 0x00003933 File Offset: 0x00001B33 public override bool Equals(object obj) { return this.Equals(obj as GeographyCollection); } // Token: 0x060000EE RID: 238 RVA: 0x00003941 File Offset: 0x00001B41 public override int GetHashCode() { return Geography.ComputeHashCodeFor<Geography>(base.CoordinateSystem, this.Geographies); } } }
f1d34dfeff786a470988a58d22a87032c7e3a512
C#
imanavaz/CONVErT
/CONVErT/ToolBox/ItemsViewModel.cs
3.15625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections.ObjectModel; using System.Windows; using System.Xml; using System.Windows.Media; namespace CONVErT { public class ItemsViewModel { public ObservableCollection<ToolboxItem> items = new ObservableCollection<ToolboxItem>(); public ItemsViewModel() { } public ItemsViewModel(String path) { loadItems(path); } public void loadItems(string XMLItemsFile) { if (System.IO.File.Exists(XMLItemsFile)) { try { XmlReaderSettings readerSettings = new XmlReaderSettings(); readerSettings.IgnoreComments = true; using (XmlReader reader = XmlReader.Create(XMLItemsFile, readerSettings)) { // SECTION 1. Create a DOM Document and load the XML data into it. XmlDocument dom = new XmlDocument(); dom.Load(reader); // SECTION 2. Initialize Elements XmlNode inXmlNode = dom.DocumentElement; // SECTION 3. Populate Items with the DOM nodes. foreach (XmlNode xnode in inXmlNode.ChildNodes) { if (xnode.Name.Equals("item")) { ToolboxItem t = new ToolboxItem((XmlElement)xnode); if (t!= null) items.Add(t); } } } } catch (XmlException xmlEx) { System.Windows.MessageBox.Show(xmlEx.Message); } catch (Exception ex) { System.Windows.MessageBox.Show(ex.Message); } } else MessageBox.Show("Could not load Items file : " + XMLItemsFile, "Error", MessageBoxButton.OK, MessageBoxImage.Error); } /*private ToolboxItem createItem(XmlNode itemXmlNode) { ToolboxItem item = new ToolboxItem(); foreach (XmlNode xnode in itemXmlNode.ChildNodes) { //<shape>Rectangle</shape> //<color> // <foreground>Black</foreground> // <background>White</background> //</color> //<size> // <width>10</width> // <height>20</height> //</size> switch (xnode.Name) { case "shape": //item.Shape = xnode.FirstChild.Value; //MessageBox.Show(xnode.Name + " " + item.Shape); break; case "color": XmlNode xfor = xnode.SelectSingleNode("//foreground"); // best, using Color's static method item.Foreground = (SolidColorBrush)new BrushConverter().ConvertFromString(xfor.FirstChild.Value); item.BorderBrush = (SolidColorBrush)new BrushConverter().ConvertFromString(xfor.FirstChild.Value); XmlNode xback = xnode.SelectSingleNode("//background"); item.Background = (SolidColorBrush)new BrushConverter().ConvertFromString(xback.FirstChild.Value); //MessageBox.Show(xnode.Name + " " + item.Foreground.ToString() + " " + item.Background.ToString()); break; case "size": XmlNode xWidth = xnode.SelectSingleNode("//width"); item.Width = Convert.ToDouble(xWidth.FirstChild.Value); XmlNode xHeight = xnode.SelectSingleNode("//height"); item.Height = Convert.ToDouble(xHeight.FirstChild.Value); //MessageBox.Show(xnode.Name + " " + item.width + " " + item.height); break; default: MessageBox.Show("Something new came in items xml file!"); break; } } return item; }*/ } }
5b76505c8e07597698cdd102881f172525748e3c
C#
ConflictReaper/ConflictReaper
/Client/ConflictReaperClient/ConflictReaperClient/FlowMeasureDevicePool.cs
2.640625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConflictReaperClient { class FlowMeasureDevicePool : IDisposable { private string localIP; private List<FlowMeasureDevice> devices = new List<FlowMeasureDevice>(); public FlowMeasureDevicePool() { System.Net.Sockets.TcpClient c = new System.Net.Sockets.TcpClient(); c.Connect("58.205.208.74", 2013); localIP = ((System.Net.IPEndPoint)c.Client.LocalEndPoint).Address.ToString(); c.Close(); for (int i = 0; i < 20; i++) { devices.Add(new FlowMeasureDevice(localIP)); } } public FlowMeasureDevice getDevice() { FlowMeasureDevice dev = null; for (int i = 0; i < devices.Count; i++) { if (!devices[i].isUsed) dev = devices[i]; } if (dev == null) { dev = new FlowMeasureDevice(localIP); devices.Add(dev); } return dev; } public void Dispose() { for (int i = 0; i < devices.Count; i++) { devices[i].Stop(); devices[i].Close(); } devices.Clear(); } } }
50aee56879d3c49f4a45098e83c3dd69a2ad9472
C#
hiteshsalian/CSharp_6_Features
/String_Interpolation/String_Interpolation/Person.cs
2.8125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace String_Interpolation { public class Performer { public string FirstName { get; set; } public string LastName { get; set; } public int Age { get; set; } public Gender Gender { get; set; } public string Profession { get; set; } public int ShowPrice { get; set; } } public enum Gender { Male, Female } }
322cc1cd035744b341c7103e211449a98dbb7457
C#
shladdergoo/sensus-playlist
/SensusPlaylist/FileSystem.cs
3.1875
3
using System; using System.IO; namespace SensusPlaylist { public class FileSystem : IFileSystem { public bool FileExists(string filename) { if (filename == null) throw new ArgumentNullException(nameof(filename)); return File.Exists(filename); } public Stream FileOpen(string filename, FileMode fileMode, FileAccess fileAccess) { if (filename == null) throw new ArgumentNullException(nameof(filename)); return new FileStream(filename, fileMode, fileAccess); } public void FileCopy(string source, string destination, bool overwrite) { if (source == null) throw new ArgumentNullException(nameof(source)); if (destination == null) throw new ArgumentNullException(nameof(destination)); File.Copy(source, destination, overwrite); } public bool DirectoryExists(string path) { if (path == null) throw new ArgumentNullException(nameof(path)); return Directory.Exists(path); } public void CreateDirectory(string path) { if (path == null) throw new ArgumentNullException(nameof(path)); Directory.CreateDirectory(path); } public void CleanDirectory(string path) { if (path == null) throw new ArgumentNullException(nameof(path)); if (!Directory.Exists(path)) throw new FileNotFoundException(); DirectoryInfo directory = new DirectoryInfo(path); foreach (FileInfo file in directory.GetFiles()) { file.Delete(); } foreach (System.IO.DirectoryInfo subDirectory in directory.GetDirectories()) { subDirectory.Delete(true); } } public string GetDirectory(string path) { if (Directory.Exists(path)) return path; if (File.Exists(path)) return new FileInfo(path).DirectoryName; throw new FileNotFoundException(); } public string GetRelativePath(string path, string rootPath) { if (path == null) throw new ArgumentNullException(nameof(path)); if (rootPath == null) throw new ArgumentNullException(nameof(rootPath)); if (!rootPath.EndsWith(Path.DirectorySeparatorChar.ToString())) { rootPath = string.Concat(rootPath, Path.DirectorySeparatorChar); } Uri target = new Uri(path); Uri root = new Uri(rootPath); Uri relativeUri = root.MakeRelativeUri(target); return Uri.UnescapeDataString(relativeUri.ToString()) .Replace('/', Path.DirectorySeparatorChar); } public string GetShortName(string path) { if (File.Exists(path)) return new FileInfo(path).Name; if (Directory.Exists(path)) return new DirectoryInfo(path).Name; throw new FileNotFoundException(); } } }
82a01dc294e6e8077fe56d4f35e4136783a10605
C#
ZainVirani/COMP521A2ZainVirani260567997
/Assets/Scripts/windBehaviour.cs
2.65625
3
using System.Collections; using System.Collections.Generic; using UnityEngine; public class windBehaviour : MonoBehaviour { float windSpeed; public float maxSpeed = 1f; public GameObject arrow; public GameObject head; // Use this for initialization void Start () { windSpeed = 0; //init arrow = GameObject.FindGameObjectWithTag("arrow"); head = GameObject.FindGameObjectWithTag("head"); InvokeRepeating("randomWind", 0f, 0.5f); //randomize wind starting now, repeating every half a second } void randomWind() { windSpeed = Random.Range(-maxSpeed, maxSpeed + 0.001f); //min is inclusive, max exclusive so we add a minimal amount to account for it arrow.transform.localScale = new Vector3((windSpeed) / maxSpeed, 1, 1); //arrow represents wind direction and speed, scale accordingly head.transform.localScale = new Vector3(.45f, .3f, 1); } public float getWind() //public get { return windSpeed; } }
5ea1071a841348a51d87c9ebe41b236cd51f538d
C#
kathiazf/TrabalhoFinalKATHIA
/Biblioteca.Apresentacao/Controls/LivroForms/LivroControl.cs
2.640625
3
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Windows.Forms; using Biblioteca.Dominio.Repositorios; using Biblioteca.Dominio; namespace Biblioteca.Apresentacao.Controls.LivroForms { public partial class LivroControl : UserControl { private readonly ILivroRepository _repository; public LivroControl() { InitializeComponent(); } public LivroControl(ILivroRepository repository) : this() { _repository = repository; } public Livro GetLivro() { return listAutores.SelectedItem as Livro; } /// <summary> /// É responsável por atualizar as tarefas que estão sendo mostradas no ListBox /// Esta função é chamada nos métodos AddData, EditData, DeleteData e na primeira vez /// que passa pelo método GetControl da classe TarefaDataManager /// </summary> /// <returns></returns> public void RefreshGrid() { var livros = _repository.Getall(); listAutores.Items.Clear(); foreach (var livro in livros) { listAutores.Items.Add(livro); } } } }
df2a213cdf058565b9de0092b8e972f7b03ebb48
C#
andreiconoval/AlgorithmsApp
/AlgorithmsApp.API/Algorithms/Sorting/BubbleSorter.cs
3.09375
3
namespace AlgorithmsApp.API.Algorithms.Sorting { public class BubbleSorter: SortBase, ISortAlg { public long Iterative(int[] arr) { stopWatch.Start(); for (int i = 0; i < arr.Length-1; i++) { for (int j = 0; j < arr.Length-1; j++) { if (arr[j] < arr[j+1]) { Swap(ref arr,j, j+1); } } } stopWatch.Stop(); return stopWatch.ElapsedMilliseconds; } public long Recursive(int[] arr) { throw new System.NotImplementedException(); } } }
6908a4f6e9e1b4319cc3ecb9dbf346b79fb2b1ec
C#
shendongnian/download4
/latest_version_download2/24185-3625707-7629970-2.cs
2.53125
3
public void UploadXmlFile(string xmlContent, int orderNumber) { string filename = DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss") + "_" + orderNumber + ".xml"; ClientContext context = new ClientContext(absoluteHostUrl + relativeWebUrl); using (MemoryStream stream = new MemoryStream()) { // use a MemoryStream for the file contents StreamWriter writer = new StreamWriter(stream); writer.Write(xmlContent); writer.Flush(); stream.Position = 0; // ... and upload it. Microsoft.SharePoint.Client.File.SaveBinaryDirect( context, "/" + relativeWebUrl + "Lists/" + libraryName + "/" + filename, stream, false); } // ...
6e9e1976e7dccb685c491da1ec5752d6fc61a5fd
C#
mbryxan/sweepstakesproject
/Sweepstakes/UserInterface.cs
3.421875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Sweepstakes { // Make this class static // Create methods to get user input for the properties on the contestant class // These methods should return a string of what the user typed in public static class UserInterface { public static string SetFirstName() { Console.WriteLine("What is your first name?"); string FirstName = Console.ReadLine(); return FirstName; } public static string SetLastName() { Console.WriteLine("What is your last name?"); string LastName = Console.ReadLine(); return LastName; } public static string SetEmailAddress() { Console.WriteLine("What is your email address?"); string EmailAddress = Console.ReadLine(); return EmailAddress; } public static int SetRegistrationNumber() { Console.WriteLine("What is your registration number?"); string userInput = Console.ReadLine(); int RegistrationNumber = Int32.Parse(userInput); return RegistrationNumber; } } }
f0ef38232d3ac0948c494eeafed23f0aaed79810
C#
addixon/ErgCompetePM
/PM.BO/Location.cs
3.3125
3
using System; namespace PM.BO { public struct Location : IEquatable<Location> { public int BusNumber { get; } public int Address { get; } public Location(int busNumber, int address) { BusNumber = busNumber; Address = address; } public bool Equals(Location otherLocation) { return BusNumber == otherLocation.BusNumber && Address == otherLocation.Address; } public override bool Equals(object? obj) { return obj != null && obj is Location location && Equals(location); } public override int GetHashCode() { var calculation = BusNumber ^ Address; return calculation.GetHashCode(); } public static bool operator == (Location l1, Location l2) { return l1.Equals(l2); } public static bool operator != (Location l1, Location l2) { return !l1.Equals(l2); } } }
ce58b5f424674c4c107f03b0d0f5c6277078491f
C#
shendongnian/download4
/code9/1664935-47390021-161016959-2.cs
2.796875
3
using System; using Excel = Microsoft.Office.Interop.Excel; class Startup { static void Main() { Excel.Application excelApp = new Excel.Application(); Excel.Workbook wkbReport = Open(excelApp, @"C:\Users\v.doynov\Desktop\Testing.xlsx"); Excel.Worksheet ws = wkbReport.Worksheets[1]; Console.WriteLine(ws._CodeName); ws.Name = "ABC"; Console.WriteLine("END"); excelApp.Visible = true; } public static Excel.Workbook Open(Excel.Application excelInstance, string fileName, bool readOnly = false, bool editable = true, bool updateLinks = true) { Excel.Workbook book = excelInstance.Workbooks.Open( fileName, updateLinks, readOnly, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, editable, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); return book; } }
57fa2e1df388e4bca3abaf2a266d8031e5219f47
C#
MobiliyaTechnologies/AMSRESTServer
/AssetMonitoring/AssetMonitoring.Services.Impl/Mappings/SensorMapping.cs
2.5625
3
namespace AssetMonitoring.Services.Impl.Mappings { using System.Collections.Generic; using System.Linq; using AssetMonitoring.Contracts; public class SensorMapping { public IQueryable<Sensor> Map(IQueryable<Entities.Sensor> source) { return from s in source select new Sensor { Id = s.Id, Name = s.Name, Description = s.Description, SensorKey = s.SensorKey, SensorTypeId = s.SensorTypeId.Value, SensorGroupId = s.SensorGroupId ?? default(int), SensorGroupName = s.SensorGroup != null ? s.SensorGroup.Name : default(string) }; } public Sensor Map(Entities.Sensor source) { return source == null ? null : this.Map(new List<Entities.Sensor> { source }.AsQueryable()).First(); } } }
e222abd7a26b00c8ae5ce4712ed59a93b9f11f29
C#
equinor/procosys-preservation-api
/src/Equinor.ProCoSys.Preservation.WebApi/Behaviors/CheckAccessBehavior.cs
2.515625
3
using System; using System.Threading; using System.Threading.Tasks; using Equinor.ProCoSys.Common.Misc; using Equinor.ProCoSys.Preservation.WebApi.Misc; using Equinor.ProCoSys.Preservation.WebApi.Authorizations; using MediatR; using Microsoft.Extensions.Logging; namespace Equinor.ProCoSys.Preservation.WebApi.Behaviors { public class CheckAccessBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse> where TRequest : IRequest<TResponse> { private readonly ILogger<CheckAccessBehavior<TRequest, TResponse>> _logger; private readonly IAccessValidator _accessValidator; public CheckAccessBehavior(ILogger<CheckAccessBehavior<TRequest, TResponse>> logger, IAccessValidator accessValidator) { _logger = logger; _accessValidator = accessValidator; } public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken cancellationToken) { var typeName = request.GetGenericTypeName(); _logger.LogInformation($"----- Checking access for {typeName}"); if (!await _accessValidator.ValidateAsync(request as IBaseRequest)) { _logger.LogWarning($"User do not have access - {typeName}"); throw new UnauthorizedAccessException(); } return await next(); } } }
a45feccdd853f1c620ecc3ac9d7c69aa00c5b190
C#
Wojtek-Cz7/MongoFunWojtek
/BookRepository.cs
2.796875
3
using MongoDB.Bson; using MongoDB.Driver; using MongoFunWojtek.Models; using MongoFunWojtek.Reviews; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MongoFunWojtek { public class BookRepository : IBookRepository { private string CollectionName = "books"; private IMongoCollection<BookModel> _collection; public BookRepository(IMongoDatabase mongoDatabase) { // opcjonalne - dodwanie indexu var options = new CreateIndexOptions { Name = "AuthorIndex" }; //var model = new CreateIndexModel<BookModel>(Builders<BookModel>.IndexKeys.Ascending(x => x.Author), options); //_collection.Indexes.CreateOneAsync(model); _collection = mongoDatabase.GetCollection<BookModel>(CollectionName); } public async Task<bool> AddBookAsync(BookModel bookModel) { try { await _collection.InsertOneAsync(bookModel); return true; } catch (MongoWriteException) { return false; } } public async Task<List<BookModel>> GetBooksAsync() { var filter = Builders<BookModel>.Filter.Empty; return await _collection.Find(filter).ToListAsync(); } public async Task<bool> RemoveBookAsync(string bookId) { var filter = Builders<BookModel>.Filter.Eq(x => x.Idek, bookId); // to jest filtr wskazujący na rekord do usunięcia var result = await _collection.DeleteOneAsync(filter); return result.DeletedCount > 0; } public async Task<bool> AddBooksAsync(List<BookModel> bookModels) { try { await _collection.InsertManyAsync(bookModels); return true; } catch (MongoWriteException) { return false; } } public async Task<List<BookModel>> GetBooksByAuthorAsync(string author) { var filter = Builders<BookModel>.Filter.Eq(x => x.Author, author); return await _collection.Find(filter).ToListAsync(); } public async Task<bool> RemoveBooksAsync(List<string> booksIds) { var filter = Builders<BookModel>.Filter.In(x => x.Idek, booksIds); var result = await _collection.DeleteManyAsync(filter); return result.DeletedCount > 0; } public async Task<List<BookModel>> GetBooksNewerThanAsync(int year) { var filter = Builders<BookModel>.Filter.Gt(x => x.ReleaseDate, new DateTime(year,1,1)); return await _collection.Find(filter).ToListAsync(); } public async Task<bool> AddReviewToBookAsync(IReview review, string bookId) { var filter = Builders<BookModel>.Filter.Eq(x => x.Idek, bookId.ToString()); var update = Builders<BookModel>.Update.Push(x => x.Reviews, review); var result = await _collection.UpdateOneAsync(filter, update); return result.ModifiedCount == 1; } public async Task<List<BookModel>> GetBooksWithSimpleReviewsAsync() { var filter = Builders<BookModel>.Filter.ElemMatch(x => x.Reviews, Builders<IReview>.Filter.OfType<SimpleReview>()); return await _collection.Find(filter).ToListAsync(); } public async Task<List<BookModel>> GetBooksWithGradeReviewsAsync() { var filter = Builders<BookModel>.Filter.ElemMatch(x => x.Reviews, Builders<IReview>.Filter.OfType<GradeReview>()); return await _collection.Find(filter).ToListAsync(); } public async Task RemoveAllBooks() { var filter = Builders<BookModel>.Filter.Empty; await _collection.DeleteManyAsync(filter); } public async Task<long> CountBooksAsync() { var result = await _collection .Aggregate() .Count() .SingleOrDefaultAsync(); return result?.Count ?? 0; } public async Task<long> CountBooksNewerThanAsync(DateTime dateTime) { var countResult = await _collection .Aggregate() .Match(Builders<BookModel>.Filter.Gt(x => x.ReleaseDate, dateTime)) .Count() .SingleOrDefaultAsync(); return countResult?.Count ?? 0; } public async Task<long> CountBooksWithAtLeastOneReviewAsync() { var countResult = await _collection .Aggregate() .Match(Builders<BookModel>.Filter.SizeGt(x => x.Reviews, 0)) .Count() .SingleOrDefaultAsync(); return countResult?.Count ?? 0; } public async Task<List<BookTypeCount>> GroupByTypesAsync() { //var filter = Builders<BookModel>.Filter.Empty; var result = await _collection .Aggregate() //.Match(filter) .Group(x => x.Type, grouping => new BookTypeCount { Type = grouping.Key, Count = grouping.Count() }) .ToListAsync(); return result; } public async Task<List<AuthorBookCountWithNewestDate>> GroupByAuthorsWithAtLeast1BookAsync() { var result = await _collection .Aggregate() .Group(x => x.Author, grouping => new AuthorBookCountWithNewestDate { Author = grouping.Key, Count = grouping.Count(), NewestDate = grouping.Max(x => x.ReleaseDate) }) .Match(Builders<AuthorBookCountWithNewestDate>.Filter.Gt(x => x.Count, 1)) .ToListAsync(); return result; } public async Task<List<string>> GetBooksTitlesAsync() { var result = await _collection .Aggregate() .Project(x => new { x.Title }) .ToListAsync(); return result.Select(x => x.Title).ToList(); } public async Task<(List<BookCountByDateStart> Centuries, List<BookCountByDateStart> Decades)> GetBooksCountInCenturiesAndDecadesAsync() { var centuriesDates = new List<DateTime>(); for (var i = 1400; i <= 2100; i += 100) centuriesDates.Add(new DateTime(i, 1, 1, 0, 0, 0, DateTimeKind.Utc)); var decadesDates = new List<DateTime>(); for (var i = 1940; i <= 2030; i += 10) decadesDates.Add(new DateTime(i, 1, 1, 0, 0, 0, DateTimeKind.Utc)); var result = await _collection .Aggregate() .Facet(AggregateFacet.Create("Centuries", new EmptyPipelineDefinition<BookModel>().Bucket( x => x.ReleaseDate, centuriesDates, x => new { _id = default(DateTime), // musi być _id count = x.Count() }, new AggregateBucketOptions<DateTime> { DefaultBucket = new DateTime(1, 1, 1) } ) ), AggregateFacet.Create("Decades", new EmptyPipelineDefinition<BookModel>().Bucket( x => x.ReleaseDate, decadesDates, x => new { _id = default(DateTime), count = x.Count() }, new AggregateBucketOptions<DateTime> { DefaultBucket = new DateTime(1, 1, 1) } ) ) ).SingleAsync(); var result1 = FacetOutput(new { _id = default(DateTime), count = default(int) }, result.Facets[0]); var result2 = FacetOutput(new { _id = default(DateTime), count = default(int) }, result.Facets[1]); var centuries = result1.Select(x => new BookCountByDateStart { DateStart = x._id, Count = x.count }).ToList(); var decades = result2.Select(x => new BookCountByDateStart { DateStart = x._id, Count = x.count }).ToList(); return (centuries, decades); } // to jest trudne :O private static IReadOnlyList<T> FacetOutput<T>(T _, AggregateFacetResult result) => result.Output<T>(); // opcja prosta, ale mało wydajna public async Task<List<AuthorAverageOverallOfExpertReviews>> AverageOverallOfExpertReviewsByAuthorAsync() { var result = await _collection.Aggregate() .Unwind<BookModel, BookAuthorUnwindReviewModel>(x => x.Reviews) .Match(Builders<BookAuthorUnwindReviewModel>.Filter.OfType<IReview, ExpertReview>(x => x.Reviews)) .Group(x => x.Author, grouping => new AuthorAverageOverallOfExpertReviews { Author = grouping.Key, Average = grouping.Average(x => ((ExpertReview)x.Reviews).Overall) }) .ToListAsync(); return result; } // OPCJA EXPERT // public async Task<List<AuthorAverageOverallOfExperts>> GetAverageOverallOfExpertReviewsByAuthorAsync() // { // var result = await _collection // .Aggregate() // .Project( // (ProjectionDefinition<BookModel, BookAuthorFilteredReviewModel>) // $@"{{ // 'author' : '$author', // 'reviews' : {{ // '$filter' : {{ // 'input' : '$reviews', // 'as' : 'item', // 'cond' : {{ // '$eq' : ['$$item._t', 'Expert'] // }} // }} // }} //}}") // .Unwind<BookAuthorFilteredReviewModel, BookAuthorReviewUnwindModel>(x => x.Reviews) // .Group(x => x.Author, grouping => new AuthorAverageOverallOfExperts // { // Author = grouping.Key, // Average = grouping.Average(x => ((ExpertReview)x.Reviews).Overall) // }) // .ToListAsync(); // return result; // } } }
febd0a5da978652543d7c5c382d4cd328fa94f3e
C#
knji/mvvmcross.plugins
/mapping/Pidac.MvvmCross.Plugins.Mapping/Geometries/Polygon.cs
2.609375
3
using System.Collections.ObjectModel; namespace Pidac.MvvmCross.Plugins.Mapping.Geometries { public class Polygon : Surface { public override GeometryType GeometryType { get { return GeometryType.Polygon;} } public override bool Equals(Geometry other) { throw new System.NotImplementedException(); } public override Geometry BufferBy(double d) { throw new System.NotImplementedException(); } public override string AsText() { throw new System.NotImplementedException(); } public override BoundingBox GetBoundingBox() { var bb = new BoundingBox(); foreach (var ring in Rings) { bb.Union(ring.GetBoundingBox()); } return bb; } public Collection<LinearRing> Rings { get; set; } } }
59e44e075aaff77a6a57c7f3a66fdd2b824c3476
C#
tscislo/sample-api-asp-dot-net
/Controllers/WeatherForecastController.cs
2.625
3
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using SampleWebAPI.Model; using SampleWebAPI.Services; namespace SampleWebAPI.Controllers { [ApiController] [Route("api/[controller]")] public class WeatherForecastController : ControllerBase { private readonly IWeatherForecastService _weatherForecastService; private readonly ILogger<WeatherForecastController> _logger; public WeatherForecastController( ILogger<WeatherForecastController> logger, IWeatherForecastService weatherForecastService ) { _logger = logger; _weatherForecastService = weatherForecastService; } [HttpGet] public IEnumerable<WeatherForecast> GetAll() { return _weatherForecastService.Get(); } [HttpGet("{city}")] public WeatherForecast GetOne(string city) { var cieplo = _weatherForecastService.Get() .FirstOrDefault(forecast => forecast.City == city); return cieplo; } } }
3d1b70c62465b27d5615350170b663cdfdcf6a91
C#
ravirai7791/DemoRepository
/GenerateSeries/UnitTestNumbers/UnitTest1.cs
2.59375
3
using Microsoft.VisualStudio.TestTools.UnitTesting; using NumberGeneratorProcessor; using System.Collections.Generic; namespace UnitTestNumbers { [TestClass] public class UnitTest1 { [TestMethod] public void TestMethod1() { List<int> generatedNo = new Processor().GenerateNumber(10); Assert.IsNotNull(generatedNo); Assert.IsTrue(generatedNo.Count == 11); } [TestMethod] public void TestDevideNumber() { string generatedNo = new Processor().GetValues(3,3); Assert.IsNotNull(generatedNo); } } }
baf3668cc5349ec972238eb0fa90d2cd07d8263d
C#
t-ujino/MediaLBAnalyzerLogViewer
/MediaLBAnalyzerLogViewerLib/AudioSampleUtils.cs
3
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MediaLBAnalyzerLogViewerLib { public enum Endian { LittleEndian, BigEndian } public class AudioSampleUtils { static public double Convert16bitToDouble(byte[] data, Endian endian = Endian.LittleEndian) { var array = (endian == Endian.LittleEndian) ? data : data.Reverse().ToArray(); var value = BitConverter.ToInt16(array); return value / Math.Abs((double)Int16.MinValue); } static public double Convert32bitToDouble(byte[] data, Endian endian = Endian.LittleEndian) { var array = (endian == Endian.LittleEndian) ? data : data.Reverse().ToArray(); var value = BitConverter.ToInt32(array); return value / Math.Abs((double)Int32.MinValue); } static public double Convert24bitToDouble(byte[] data, Endian endian = Endian.LittleEndian) { var array = (endian == Endian.LittleEndian) ? new byte[] { 0x00 }.Concat(data) : new byte[] { 0x00 }.Concat(data.Reverse()); return Convert32bitToDouble(array.ToArray()); } } }
8d3e06a97685a686fe4d29c8633c1919328c43a6
C#
WhiteGrouse/SimpleBNF
/src/Syntax/TagElement.cs
3.140625
3
using System; using System.Collections.Generic; namespace SimpleBNF.Syntax { public class TagElement : ISyntaxElement { public enum RepeatKind { NotRepeat, Star, Plus } public string TagName { get; } public RepeatKind Repeat { get; } public bool IsOptional { get; } public TagElement(string tagName) : this(tagName, RepeatKind.NotRepeat, false) { } public TagElement(string tagName, RepeatKind repeat) : this(tagName, repeat, false) { } public TagElement(string tagName, bool isOptional) : this(tagName, RepeatKind.NotRepeat, isOptional) { } public TagElement(string tagName, RepeatKind repeat, bool isOptional) { TagName = tagName; Repeat = repeat; IsOptional = isOptional; if(Repeat == RepeatKind.Star) { IsOptional = true; } if(repeat == RepeatKind.Plus && IsOptional) { Repeat = RepeatKind.Star; } } } }
a62de3750bd0c4af4e5d8d08b1cb0e45520e6870
C#
krnets/codewars-practice
/7kyu/Simple Equation 2/Kata.cs
2.828125
3
/*using System.Data; namespace SolveIt { public class Kata { public static int result(string stringInput) { return (int) new DataTable().Compute(stringInput, null); } } }*/ using System.Linq; using System.Text.RegularExpressions; namespace SolveIt { public class Kata { public static int result(string stringInput) { return Regex.Split(stringInput.Replace(" ", ""), "(?=[-+])").Sum(int.Parse); } } }
58a94646ff23647294e825d46822c91329d0e32e
C#
MadalinPuscas/licenta
/AdventureGame2/Engine.cs/RandomGenerator.cs
2.640625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Engine { public static class RandomGenerator { private static Random rnd = new Random(); public static int Number(int minimumValue, int maximumValue) { return rnd.Next(minimumValue, maximumValue + 1); } } }
7e0b2ad7ccef7459f9ea43697a4c8d1f4202e294
C#
AlexanderOkochutin/NET.W.2016.01.Okochutin.01
/Task4.ConsoleUI/Program.cs
3.25
3
using System; using System.Collections.Generic; using System.Linq; using Task4.Logic; namespace Task4.ConsoleUI { class Program { static void Main(string[] args) { do { Console.WriteLine("Enter array of int in next format -m a0,a1,a2 or -r min,max,count "); // -m manual enter array in next format 1,2,3... or 1 2 3 Console.WriteLine("example of input info: -m 1,14,3,8,19 or -r -5,20,10"); // -r random array in range from min to max and count of elem Console.WriteLine(new string('*',67)); string inputData = Console.ReadLine(); // get input data in format -param a,b,c... Random rand = new Random(); int[] rsltArray = null; bool tryAgain = true; string cmdParam = "noParam"; if (inputData.Length >= 2) { cmdParam = inputData.Substring(0, 2); } if (cmdParam == "-m") // manual input array { while (tryAgain) // in case of fail repeat { try { rsltArray = Array.ConvertAll(inputData.Substring(3).Split(new char[] { ' ', ',' }), int.Parse); // parse string[] into int[] tryAgain = false; // set in case of success } catch { Console.WriteLine("****Please check input information, and try again!****"); Console.WriteLine("****example of input info: -m 1,2,3 or -m 1 2 3 ****"); inputData = Console.ReadLine(); // in case of fail repeat enter of info } } } if (cmdParam == "-r") // random input array { while (tryAgain) // in case of fail repeat { try { int[] randParam = Array.ConvertAll(inputData.Substring(3).Split(new char[] { ' ', ',' }), int.Parse); // parse string[] into int[] if (randParam[2] <= 0) { throw new Exception(); } rsltArray = new int[randParam[2]]; Console.WriteLine("not sorted array:"); for (int i = 0; i < randParam[2]; i++) { rsltArray[i] = rand.Next((int)randParam[0], (int)randParam[1]); Console.Write(rsltArray[i].ToString() + ","); } Console.WriteLine(); tryAgain = false; // set in case of success } catch { Console.WriteLine("****Please check input information, and try again!****"); Console.WriteLine("****example of input info: -r min,max,count or -r min max count ****"); inputData = Console.ReadLine(); // in case of fail repeat enter of info } } } if (tryAgain == false) // if parse is successfull than choose type of sort increase or decrease { Console.WriteLine("enter -i for increase sort or -d for decrease sort"); string sortType = Console.ReadLine(); if (sortType == "-i") // increase { rsltArray.MergeSort(new ExtensionToolsForArray.IncComparer<int>()); Console.WriteLine("Sorted array"); } else if (sortType == "-d") // decrease { rsltArray.MergeSort(new ExtensionToolsForArray.DecComparer<int>()); Console.WriteLine("Sorted array"); } else { Console.WriteLine("Not correct sort_type"); } foreach (int i in rsltArray) { Console.WriteLine(i); } } else // if parse fail repeat enter info { Console.WriteLine("check input information!"); } Console.WriteLine("enter 'stop' to exit program or press 'enter' to continue"); } while (Console.ReadLine() != "stop"); } } }
9f7b59e17b4a52bae04195407678387bb75fd9de
C#
127-0-0-l/Bouncer
/Bouncer/Form1.cs
2.84375
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 Bouncer { public partial class Form1 : Form { int mouseX; int mouseY; double bouncerX; double bouncerY; int speed = 1; int tickNum; double distance; double stepX; double stepY; public Form1() { InitializeComponent(); } private void Form1_MouseDown(object sender, MouseEventArgs e) { mouseX = e.X; mouseY = e.Y; bouncerX = Bouncer.Location.X + 11; bouncerY = Bouncer.Location.Y + 11; distance = Math.Sqrt(Math.Pow(bouncerX - mouseX, 2) + Math.Pow(bouncerY - mouseY, 2)); tickNum = Convert.ToInt32(distance / speed); stepX = Math.Abs(bouncerX - mouseX) / tickNum; stepY = Math.Abs(bouncerY - mouseY) / tickNum; if (bouncerX - mouseX > 0) stepX *= -1; if (bouncerY - mouseY > 0) stepY *= -1; timer.Start(); } private void Form1_Load(object sender, EventArgs e) { } private void Timer_Tick(object sender, EventArgs e) { if (Bouncer.Location.X < 0 || Bouncer.Location.X > 279) { stepX *= -1; } if (Bouncer.Location.Y < 0 || Bouncer.Location.Y > 179) { stepY *= -1; } bouncerX += stepX; bouncerY += stepY; Bouncer.Location = new Point(Convert.ToInt32(bouncerX - 11), Convert.ToInt32(bouncerY - 11)); } } }
03ffaad59db20577d91980ee582be1d5ab0fc6f3
C#
monobelisk/DFUnity-InterestingTerrains
/Scripts/ModMessageHandler.cs
2.59375
3
using UnityEngine; using System.Collections; using DaggerfallWorkshop.Game.Utility.ModSupport; namespace Monobelisk { public static class ModMessageHandler { // Requests private const string GET_TILEDATA = "getTileData"; // Responses private const string TILEDATA = "tileData"; private const string ERROR = "error"; public static void Init() { InterestingTerrains.Mod.MessageReceiver = ( string message, object data, DFModMessageCallback callBack ) => { switch (message) { case GET_TILEDATA: GetTileData(data, callBack); break; default: callBack(ERROR, "Message '" + message + "' is invalid."); break; } }; } private static void GetTileData(object data, DFModMessageCallback callBack) { var dataErrMsg = "Data for message '" + GET_TILEDATA + "' must be an int array, where [0] is MapPixelX and [1] is MapPixelY."; if (data.GetType() != typeof(int[])) { callBack(ERROR, dataErrMsg); return; } var mapPixelPos = (int[])data; if (mapPixelPos.Length < 2) { callBack(ERROR, dataErrMsg); return; } var mpx = Mathf.Clamp(mapPixelPos[0], 0, 999); var mpy = Mathf.Clamp(mapPixelPos[1], 0, 499); var tileData = InterestingTerrains.tileDataCache.Get(mpx, mpy); if (tileData == null) { callBack(ERROR, "tileData does not exist for map pixel " + mpx + "x" + mpy + ". Either it hasn't been generated yet, or it's been used by another process."); return; } callBack(TILEDATA, tileData); } } }
d3ae94c94ca33207f00cdc83961e1736ec9a6160
C#
cretumarius/DocScan
/server/Business/MergeService.cs
2.53125
3
using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Threading.Tasks; using Business.Base; using Business.BusinessContract; using Business.Constants; using IronPdf; namespace Business { public class MergeService : IMergeService { private readonly IAzureBlobContainerClient _blobContainerClient; public MergeService(AzureBlobContainerClientFactory azureBlobContainerFactory) { _blobContainerClient = azureBlobContainerFactory(BlobContainerNames.DocumentsContainerName); } public async Task<MemoryStream> Merge(string folder) { PdfDocument mergedPdf = null; var resultSegment = _blobContainerClient.GetBlobsAsync(folder); await foreach (var blobPage in resultSegment) { foreach (var blobItem in blobPage.Values) { var blobClient = _blobContainerClient.GetBlobClient(blobItem.Name); PdfDocument toAppend = null; string extension = Path.GetExtension(blobItem.Name); if (extension == FileExtensions.PdfExtension) { if (mergedPdf != null) toAppend = new PdfDocument(blobClient.OpenRead()); else mergedPdf = new PdfDocument(blobClient.OpenRead()); } else { if (mergedPdf != null) toAppend = ImageToPdfConverter.ImageToPdf(Image.FromStream(blobClient.OpenRead())); else mergedPdf = ImageToPdfConverter.ImageToPdf(Image.FromStream(blobClient.OpenRead())); } if (toAppend != null) { mergedPdf.AppendPdf(toAppend); } } } return mergedPdf.Stream; } } }
ed41f0fb90cb80a3f45c62c6f9e708af09129aa2
C#
colgreen/sharpneat
/src/SharpNeat/Graphs/WeightedDirectedConnection.cs
2.953125
3
// This file is part of SharpNEAT; Copyright Colin D. Green. // See LICENSE.txt for details. namespace SharpNeat.Graphs; #pragma warning disable CA1036 // Override methods on comparable types /// <summary> /// Represents a connection between two nodes, combined with a connection weight. /// </summary> /// <remarks> /// This type does not inherit from DirectedConnection as might be expected because these are structs (value types) /// and therefore inheritance is not possible. /// </remarks> /// <typeparam name="T">Connection weight data type.</typeparam> public readonly struct WeightedDirectedConnection<T> : IComparable<WeightedDirectedConnection<T>> where T : struct { /// <summary> /// Connection source node ID. /// </summary> public int SourceId { get; } /// <summary> /// Connection target node ID. /// </summary> public int TargetId { get; } /// <summary> /// Connection weight. /// </summary> public T Weight { get; } /// <summary> /// Construct with the provided source and target node IDs, and weight. /// </summary> /// <param name="srcId">Connection source node ID.</param> /// <param name="tgtId">Connection target node ID.</param> /// <param name="weight">Connection weight.</param> public WeightedDirectedConnection(int srcId, int tgtId, T weight) { SourceId = srcId; TargetId = tgtId; Weight = weight; } #region IComparable<T> /// <inheritdoc/> public int CompareTo(WeightedDirectedConnection<T> other) { // Notes. // The comparison here uses subtraction rather than comparing IDs, this eliminates a number of branches // which gives better performance. The code works and is safe because the source and target node IDs // always have non-negative values, and therefore have a possible range of [0, (2^31)-1]. And if we // subtract the largest possible value from zero we get -(2^31)-1 which is still within the range of // an Int32, i.e., the result of that subtraction does not overflow and is therefore a negative value // as required, giving a valid comparison result. int diff = SourceId - other.SourceId; if(diff != 0) return diff; return TargetId - other.TargetId; } #endregion }
e32e881bb3efe5f6e844e98225ebaa831b8ea28f
C#
ChenFengYe/AutoSweep_CircleReconstruction
/IBrushes/MyGeometry/MyModel.cs
2.890625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Threading.Tasks; using Accord.Math; using Accord.Math.Distances; using Accord.MachineLearning; using Accord.Statistics.Distributions.DensityKernels; namespace MyGeometry { public class MyDistance : IMetric<double[]> { public double Distance (double[] a, double[] b) { double squaresum = 0; for (int i = 0; i < a.Length; i++) { squaresum += Math.Pow(a[i] - b[i], 2); } return squaresum; } } public class MyModel { private List<MyVector3> vertices = new List<MyVector3>(); public MyModel (string filename) { List<MyVector3> model = new List<MyVector3>(); using (StreamReader sr = new StreamReader(filename, Encoding.Default)) { int point_num = int.Parse(sr.ReadLine()); string[] arr = null; for (int i = 0; i < point_num; i++) { arr = sr.ReadLine().Split(new char[] { ' ' }); model.Add(new MyVector3(Convert.ToDouble(arr[0]), Convert.ToDouble(arr[1]), Convert.ToDouble(arr[2]))); } } } public MyModel (List<MyVector3> vs) { vertices.AddRange(vs); } public List<MyVector3> Vertices { get { return vertices; } set { vertices = value; } } public void AddVertexToModel (MyVector3 vert) { vertices.Add(vert); } public void SaveModelToFile (string commonprefix) { using (StreamWriter sw = new StreamWriter(commonprefix + ".model", false)) { sw.WriteLine(vertices.Count); foreach (MyVector3 vert in vertices) { sw.WriteLine(vert); } sw.Flush(); sw.Close(); } } public void SaveModelToPly (string commonprefix) { using (StreamWriter sw = new StreamWriter(commonprefix + ".ply", false)) { sw.WriteLine("ply"); sw.WriteLine("format ascii 1.0"); sw.WriteLine("comment"); sw.WriteLine("element vertex {0}", vertices.Count); sw.WriteLine("property float x"); sw.WriteLine("property float y"); sw.WriteLine("property float z"); sw.WriteLine("element face 0"); sw.WriteLine("property list uchar int vertex_indices"); sw.WriteLine("end_header"); foreach (MyVector3 vert in vertices) { sw.WriteLine(vert); } sw.Flush(); sw.Close(); } } public static double ComputeHeight(MyModel m, MyPlane p) { double height = double.MinValue; for (int i = 0; i < m.Vertices.Count; i++) { double dist = p.DistanceToPoint(m.Vertices[i]); if (dist > height) { height = dist; } } return height; } public void Slicing(List<MyPolygon> planes) { } } }
241fe1d3fc3ffd7442381bf750e0e2013aeee4ec
C#
andrecarlucci/CustomVisionApp
/CustomVisionApp/StreetFighter/ExecuteAfter.cs
3.0625
3
using System; using System.Collections.Generic; using System.Threading; namespace CustomVisionApp.StreetFighter { public static class ExecuteWhen { private static string _current = ""; private static int _count = 0; private static Dictionary<string, Action> _dic = new Dictionary<string, Action>(); public static void Register(string value, Action action) { _dic[value] = action; } public static void SameValueThreeTimes(string value) { if(!_dic.ContainsKey(value) || _current != value) { _count = 0; _current = value; return; } _count++; if(_count == 3) { _dic[value].Invoke(); _count = 0; Thread.Sleep(1000); } } } }
a5aba4f213bbaf365e904d3bb0d4246d7b1036df
C#
epitsin/TelerikHomeworks
/Introduction to Programming with C# Part Two/Methods/4.CountOfNumbers/CountOfNumbers.cs
4.21875
4
using System; namespace _4.CountOfNumbers { class CountOfNumbers { static int Count(int[] someArray, int number) { int count = 0; for (int i = 0; i < someArray.Length; i++) { if (someArray[i] == number) { count++; } } return count; } static void Main() { int[] array = new int[] { 2, 4, 7, 1, 3, 10, 11, 5, 2 }; //Console.WriteLine("Please, enter a number from the array: "); //int wantedNumber = int.Parse(Console.ReadLine()); int wantedNumber = 2; Console.WriteLine("The count of {0} in the array is {1} times.", wantedNumber, Count(array, wantedNumber)); } } }
93552e0b47d516c0755c5ad818bd4d0f214d8dc9
C#
bankoViktor/sharp_node_render
/NodeRender.cs
2.875
3
using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; namespace NodeInterface { public class Node { public int NodeID; public Point Location; public Size Size; public Color BackColor; // TODO нод хранит цвет своего фона, для примера public virtual void Draw(NodeDrawArgs e) { // TODO нужно ли освобождать перья и кисти методом Dispose() или нет? Rectangle rect = new Rectangle(Location, Size); Color HighlightColor = Color.Red; Color SelectedColor = Color.Blue; e.Graphics.FillRectangle(new SolidBrush(BackColor), rect); e.Graphics.DrawString( NodeID.ToString(), new Font(FontFamily.GenericMonospace, 20.0f, FontStyle.Regular, GraphicsUnit.Pixel), new SolidBrush(Color.Blue), new Point(Location.X + 10, Location.Y + 10)); // Подсветка при наведении if (e.HighlightID == NodeID) e.Graphics.DrawRectangle(new Pen(HighlightColor), rect); else { if (e.Selected.Contains(this)) { e.Graphics.DrawRectangle(new Pen(SelectedColor), rect); } } } } public class NodeDrawArgs { public Graphics Graphics; public int HighlightID; public List<Node> Selected; } public partial class NodeRender : Control { [Category("Сетка"), Description("Включает отрисовку сетки на фоне")] public bool Grid { get; set; } = true; [Category("Сетка"), Description("Задает шаг сетки")] public int GridStep { get; set; } = 25; [Category("Сетка"), Description("Задает ширину линий сетки")] public float GridWidth { get; set; } = 2f; [Category("Сетка"), Description("Задает цвет линий сетки")] public Color GridColor { get; set; } = Color.LightGray; public int Highlight { get; private set; } = -1; public List<Node> Selected { get; private set; } = new List<Node>(); // TODO хранить ID выделенных нодов? public List<Node> Nodes { get; private set; } = new List<Node>(); public int deb_paint = 0; // TODO private Color SelectingColorToRight = Color.LightBlue; private Color SelectingColorToLeft = Color.LightGreen; private int SelectingAlpha = 100; private Color SelectingBorderColor = Color.BlueViolet; private float SelectingBorderWidth = 2f; private bool IsLeftPressed; // флаг нажатия ЛКМ private Point LastMousePos; // Последняя позиция щелчка мыши private Point NewMousePos; // Новая позиция курсора выделения // меняется каждый выхов MouseMove для перерисовки прямоугольника выделения //private Node TopNode; // Верхний нод // TODO последний выделенный нод отрисовывать поверх всех (последним) public NodeRender() { DoubleBuffered = true; MouseMove += NodeRender_MouseMove; MouseDown += NodeRender_MouseDown; MouseUp += NodeRender_MouseUp; } private Node GetNodeUnderCursor(int Cursor_X, int Cursor_Y) { Node node = null; foreach (Node n in Nodes) { if (PointIntoRectangle(new Point(Cursor_X, Cursor_Y), new Rectangle(n.Location, n.Size))) { node = n; break; } } return node; } private bool PointIntoRectangle(Point point, Rectangle rectangle) { if (point.X >= rectangle.Left && point.X < rectangle.Right && point.Y >= rectangle.Top && point.Y < rectangle.Bottom) return true; else return false; } private Rectangle GetSelectingRect() { Point point; Size size; if (NewMousePos.X > LastMousePos.X) { // Вправо if (NewMousePos.Y > LastMousePos.Y) { // Вниз point = new Point(LastMousePos.X, LastMousePos.Y); size = new Size(NewMousePos.X - LastMousePos.X, NewMousePos.Y - LastMousePos.Y); } else { // Вверх point = new Point(LastMousePos.X, NewMousePos.Y); size = new Size(NewMousePos.X - LastMousePos.X, LastMousePos.Y - NewMousePos.Y); } } else { // Влево if (NewMousePos.Y > LastMousePos.Y) { // Вниз point = new Point(NewMousePos.X, LastMousePos.Y); size = new Size(LastMousePos.X - NewMousePos.X, NewMousePos.Y - LastMousePos.Y); } else { // Вверх point = new Point(NewMousePos.X, NewMousePos.Y); size = new Size(LastMousePos.X - NewMousePos.X, LastMousePos.Y - NewMousePos.Y); } } return new Rectangle(point, size); } private void DrawGrid(Graphics g, Color color, int Step, float Width) { Pen pen = new Pen(color, Width); // TODO нужно ли освобождать перья и кисти методом Dispose() или нет? // Вертикальные линии for (int с = Step; с < Size.Width; с += Step) { g.DrawLine( pen, new Point(с, 0), new Point(с, Size.Height)); } // Горизонтальные линии for (int r = Step; r < Size.Height; r += Step) { g.DrawLine( pen, new Point(0, r), new Point(Size.Width, r)); } } private void NodeRender_MouseDown(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { IsLeftPressed = true; LastMousePos = new Point(e.X, e.Y); NewMousePos = LastMousePos; Node node = GetNodeUnderCursor(e.X, e.Y); if (node == null) // Клик по рабочей области Selected.Clear(); else { // Клик по элементу if (Selected.Count > 1) { // Выбран как минимум 2 элемента -> множественный выбор if (Selected.Contains(node) == false) { // Среди выбранный элементов текущего нет -> новый одиночный выбор Selected.Clear(); Selected.Add(node); } } else { // Выбран всего 1 элемент -> одиночный выбор Selected.Clear(); Selected.Add(node); //TopNode = node; // TODO может лучше хранить ID нода? и искать его по его ID в сипике Nodes } } Refresh(); } } private void NodeRender_MouseUp(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { IsLeftPressed = false; Rectangle selectRect = GetSelectingRect(); foreach (Node node in Nodes) { Rectangle intersectRect = selectRect; intersectRect.Intersect(new Rectangle(node.Location, node.Size)); if (intersectRect.Width == node.Size.Width && intersectRect.Height == node.Size.Height) { Selected.Add(node); } } } Refresh(); } private void NodeRender_MouseMove(object sender, MouseEventArgs e) { if (IsLeftPressed) { if (Selected.Count > 0) { // режим перемещения foreach (Node node in Selected) { node.Location.X += e.X - LastMousePos.X; node.Location.Y += e.Y - LastMousePos.Y; } LastMousePos = new Point(e.X, e.Y); Refresh(); } else { // режим выделения NewMousePos = new Point(e.X, e.Y); Refresh(); } } else { int newHighlightID = -1; Node node = GetNodeUnderCursor(e.X, e.Y); if (node != null) newHighlightID = node.NodeID; if (Highlight != newHighlightID) { Highlight = newHighlightID; Refresh(); } } } protected override void OnPaintBackground(PaintEventArgs pevent) { base.OnPaintBackground(pevent); // Цвет фона задется родительским свойством BackColor, а цвет сетки свойством GridColor if (Grid) DrawGrid(pevent.Graphics, GridColor, GridStep, GridWidth); } protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); deb_paint++; foreach (Node node in Nodes) { NodeDrawArgs args = new NodeDrawArgs() { Graphics = e.Graphics, HighlightID = Highlight, Selected = Selected }; node.Draw(args); } if (IsLeftPressed && Highlight == -1 & NewMousePos != LastMousePos) { Color color; if (NewMousePos.X > LastMousePos.X) color = SelectingColorToRight; // Вправо else color = SelectingColorToLeft; // Влево Rectangle selRect = GetSelectingRect(); // Рисуем прямоугольник выделения e.Graphics.FillRectangle( new SolidBrush(Color.FromArgb(SelectingAlpha, color)), selRect); e.Graphics.DrawRectangle( new Pen(SelectingBorderColor, SelectingBorderWidth), selRect); } } } }
820f307a5d0dab084f160e6102e15d6200910e55
C#
suha1515/RoadKillZombie
/GameCamp2/Assets/Script/LKZ_StagePointManager.cs
2.53125
3
using System.Collections; using System.Collections.Generic; using UnityEngine; public class LKZ_StagePointManager : MonoBehaviour { Vector3 mousePos = new Vector3(); [SerializeField] LayerMask ExclusiveLayers; //스테이지 포인트 오브젝트의 이름을 담을 문자열 -> 이걸로 스테이지 정보를 받아오면 됨 public string SelectedStage = null; static GameObject curStage = null; private void Update() { //PC 및 에디터에서 클릭 업 시 if (Input.GetMouseButtonUp(0)) { mousePos = Input.mousePosition; SelectedStage = GetStageNameByRaycast(mousePos); } //모바일에서 터치 업 시 if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Ended) { mousePos = Input.GetTouch(0).position; SelectedStage = GetStageNameByRaycast(mousePos); } } private string GetStageNameByRaycast(Vector3 _rayOrigin) { string _stage = null; Ray ray = Camera.main.ScreenPointToRay(_rayOrigin); RaycastHit hit; if (Physics.Raycast(ray, out hit, 100, ~ExclusiveLayers)) { if (hit.collider.gameObject.layer == LayerMask.NameToLayer("StagePoint")) { if (curStage == null) { curStage = hit.collider.gameObject; } else { //화면이 터치는 됬는데 스테이지 포인트가 이전과 다른것 터치한 경우 if (curStage != hit.collider.gameObject) { curStage.GetComponent<LKZ_StagePoint>().NotSelected(); curStage = hit.collider.gameObject; } } _stage = curStage.name; curStage.GetComponent<LKZ_StagePoint>().OnSelected(); } else { //화면이 터치는 됬는데 스테이지 포인트가 아닌 다른 것 터치한 경우 if (curStage != null) { if (curStage != hit.collider.gameObject) { curStage.GetComponent<LKZ_StagePoint>().NotSelected(); curStage = null; _stage = null; } } } Debug.DrawLine(ray.origin, ray.direction); } else { //화면이 터치는 됬는데 스테이지 포인트가 아닌 다른것 터치한 경우 중 레이캐스트에 아무것도 충돌하지 않은 경우 //이건 쓸지 말지 고민중 if (curStage != null) { curStage.GetComponent<LKZ_StagePoint>().NotSelected(); curStage = null; _stage = null; } } return _stage; } }
bffabe443129088147166c2d038483117e21153e
C#
saikrishnaudatha/Entity-Frame-Core-and-ADO.NET
/HandsOnEFCodeFirst/Program.cs
3.265625
3
using HandsOnEFCodeFirst.Context; using HandsOnEFCodeFirst.Models; using System.Linq; using System; using System.Collections.Generic; namespace HandsOnEFCodeFirst { class Program { static void Main(string[] args) { // Console.WriteLine("Hello World!"); using(MyContext db=new MyContext()) { // Student s = new Student() { Sname = "krish", Age = 23, Std = "XVI" }; // db.Students.Add(s); // db.SaveChanges(); //Student s= db.Students.Find(1); // Console.WriteLine("Welcome {0}", s.Sname); Student s1= db.Students.SingleOrDefault(i => i.Sname == "Sai"); List<Student> list = db.Students.Where(i => i.Age == 10).ToList(); List<Student> list1 = db.Students.Where(i => i.Age == 10 && i.Std=="XV").ToList(); Student s2 = db.Students.SingleOrDefault(i => i.Sname == "Sai"); db.Students.Remove(s2); db.SaveChanges(); } } } }
79aa1bfc38da45dc0f69961a210e9d11f21df824
C#
jsusanto/ASP.NET_MVC5_20486
/Day-3/PhotoSharingApplication_08_solution/PhotoSharingTests/RoutingTests.cs
2.671875
3
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Web.Routing; using System.Web.Mvc; using PhotoSharingTests.Doubles; using PhotoSharingApplication; namespace PhotoSharingTests { [TestClass] public class RoutingTests { [TestMethod] public void Test_Default_Route_ControllerOnly() { var context = new FakeHttpContextForRouting(requestUrl: "~/ControllerName"); /* * Writing a Routing Test * After creating an HTTP context test double, you can write unit tests for each route * in the routing table. These unit tests adopt the following general phases: */ /* * Arrange. * In the Arrange phase of the test, you can create a new HTTP context from your test * double class. * You can set the request URL for this object to be the URL you want to test. * You can then create a new route collection and call the RouteConfig.RegisterRoutes() method * in your web application. */ var routes = new RouteCollection(); RouteConfig.RegisterRoutes(routes); /* * Act. * In the Act phase, you can test the routes by calling the GetRouteData() method of the route collection. * You can then pass the fake HTTP context to this method. */ RouteData routeData = routes.GetRouteData(context); /* * Assert. * In the Assert phase, you can use the RouteData.Values collection to check that * the controller, action and other values are assigned correctly. */ Assert.IsNotNull(routeData); Assert.AreEqual("ControllerName", routeData.Values["controller"]); Assert.AreEqual("Index", routeData.Values["action"]); Assert.AreEqual(UrlParameter.Optional, routeData.Values["id"]); } [TestMethod] public void Test_Photo_Route_With_PhotoID() { var context = new FakeHttpContextForRouting(requestUrl: "~/photo/2"); var routes = new RouteCollection(); RouteConfig.RegisterRoutes(routes); RouteData routeData = routes.GetRouteData(context); Assert.IsNotNull(routeData); Assert.AreEqual("Photo", routeData.Values["controller"]); Assert.AreEqual("Display", routeData.Values["action"]); Assert.AreEqual("2", routeData.Values["id"]); } [TestMethod] public void Test_Photo_Title_Route() { var context = new FakeHttpContextForRouting(requestUrl: "~/photo/title/my%20title"); var routes = new RouteCollection(); RouteConfig.RegisterRoutes(routes); RouteData routeData = routes.GetRouteData(context); Assert.IsNotNull(routeData); Assert.AreEqual("Photo", routeData.Values["controller"]); Assert.AreEqual("DisplayByTitle", routeData.Values["action"]); Assert.AreEqual("my%20title", routeData.Values["title"]); } } }
ced45a36e0624c1104e64af8105a0bb5fa50305d
C#
vioan12/Verificarea-si-Testarea-Sistemelor-de-Calcul
/Lab1/OutputProcessing.cs
3.09375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lab1 { public class OutputProcessing { private Output _output; public OutputProcessing(Output output) { _output = output; } public void PutData(Solution solution) { string line1, line2; string[] newSolution = Decimals.Round(solution, 2); line1 = "x1=" + newSolution[0]; line2 = "x2=" + newSolution[1]; _output.WriteData(new string[2] {line1, line2}); } } }
3ddf2eff89a99e1f858330a74828f00c71424320
C#
chandlerpl/CPLibrary
/CP.Common/Utilities/ClassLoader.cs
2.890625
3
/* * Copyright (C) Pope Games, Inc - All Rights Reserved * Unauthorized copying of this file, via any medium is strictly prohibited * Proprietary and confidential * Author: Chandler Pope-Lewis <c.popelewis@gmail.com> */ using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; namespace CP.Common.Utilities { public static class ClassLoader { public static List<T> Load<T>() { List<T> objects = new List<T>(); if(typeof(T).IsInterface) { foreach (Type type in AppDomain.CurrentDomain.GetAssemblies().SelectMany(x => x.GetTypes()).Where(x => typeof(T).IsAssignableFrom(x) && !x.IsInterface && !x.IsAbstract)) { objects.Add((T)Activator.CreateInstance(type)); } } else { foreach (Type type in AppDomain.CurrentDomain.GetAssemblies().SelectMany(s => s.GetTypes()).Where(myType => myType.IsClass && !myType.IsAbstract && myType.IsSubclassOf(typeof(T)))) { objects.Add((T)Activator.CreateInstance(type)); } } return objects; } } }
676c9c64ad16ccfd057ab29e6d7d6ff8f577c365
C#
Alandeb/Csharp-19
/Nueva carpeta/Ejercicios 31-33/MisClases/MisClases/Cliente.cs
3.6875
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MisClases { public class Cliente { #region ATRIBUTOS private string nombre; private int numero; #endregion #region CONSTRUCTOR public Cliente(int numero) { this.numero = numero; } public Cliente(int numero, string nombre) :this(numero) { Nombre = nombre; } #endregion #region PROPIEDADES public string Nombre { get { return this.nombre; } set { this.nombre = (value); } } public int Numero { get { return this.numero; } } #endregion #region METODOS /// <summary> /// Compara clientes /// </summary> /// <param name="cl1">Cliente nro 1</param> /// <param name="cl2">Cliente nro 2</param> /// <returns>Si son iguales devuelve verdadero, caso contrario, falso.</returns> public static bool operator == (Cliente cl1, Cliente cl2) { return (cl1 == cl2); } public static bool operator !=(Cliente cl1, Cliente cl2) { return !(cl1 == cl2); } #endregion } }
4ca7b2afb6819e963a0f255dd1e452d21df55d6e
C#
slincastro/load
/GGLoader.BLL/Domain/ProcessResponse.cs
2.859375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GGLoader.BLL.Domain { public class ProcessResponse { public ProcessResponse(List<Line> lines, string process) { Lines = lines; Id = process; Messages = lines.GroupBy(item => item.Id) .Select(group => new ProcessMessage { Id = group.Key, SendedMessage = group.FirstOrDefault(sm => !sm.IsProcessed), ProcessedMessage = group.FirstOrDefault(sm => sm.IsProcessed), ProcessingTime = GetTimeProcess(group) }).ToList(); AverageProcess = Messages.Average(p => Convert.ToInt32(p.ProcessingTime.Milliseconds)); } private TimeSpan GetTimeProcess(IGrouping<string, Line> group) { var sendedMessage = group.FirstOrDefault(sm => !sm.IsProcessed).TimeProcess; var processedMessage = group.FirstOrDefault(sm => sm.IsProcessed).TimeProcess; return processedMessage.Subtract(sendedMessage); } public string Id { get; set; } public List<Line> Lines { get; set; } public List<ProcessMessage> Messages { get; set; } public double AverageProcess { get; internal set; } } public class ProcessMessage { public string Id { get; set; } public TimeSpan ProcessingTime { get; set; } public Line SendedMessage { get; set; } public Line ProcessedMessage { get; set; } } }
9eac2ea5a25440e14a2d21206465528f1a0e9331
C#
tenderpaw/Biocide
/Assets/OwlTawitTawoo/Scripts/StateManager.cs
2.640625
3
using UnityEngine; using UnityEngine.Events; #if UNITY_EDITOR using UnityEditor; #endif namespace OwlTawitTawoo { public static class StateManager { public enum State { None, // start Intro, Game, Main, End, Shop } public static State state { get; private set; } = State.None; public static event UnityAction<State> stateChangedEvent; public static void Set(State newState) { if (state == newState) return; state = newState; stateChangedEvent?.Invoke(state); } public static bool Compare(State tgtState) { return state == tgtState; } #if UNITY_EDITOR [MenuItem("Debug/State")] private static void PrintState() { Debug.LogFormat("State:{0}", state); } #endif } }
1bd74e1278d4378523a6de72bfd9bbe5f78efff9
C#
PasanAvi/CommandRestAPI
/RestAPILearning/RestAPILearning/Data/MockCommanderRepo.cs
2.859375
3
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using RestAPILearning.Models; namespace RestAPILearning.Data { public class MockCommanderRepo : ICommanderRepo { public IEnumerable<Command> GetAllCommands() { var Commands = new List<Command> { new Command(){ID = 0, HowTo = "Method 1", Line = "do as Method 1", Platform = "Platform 1"}, new Command(){ID = 1, HowTo = "Method 2", Line = "do as Method 2", Platform = "Platform 2"}, new Command(){ID = 2, HowTo = "Method 3", Line = "do as Method 3", Platform = "Platform 3"}, new Command(){ID = 3, HowTo = "Method 4", Line = "do as Method 4", Platform = "Platform 4"} }; return Commands; } public Command GetCommandById(int Id) { return new Command() { ID = 0, HowTo = "Method 1", Line = "do as Method 1", Platform = "Platform 1" }; } } }
d6b581ac6ecc0333e77a54b9a4bf8f2fed438ce2
C#
valdisiljuconoks/ImageResizer.Plugins.EPiServerBlobReader
/src/ImageResizer.Plugins.EPiServerBlobReader/HtmlHelperExtensionsForPicture.cs
2.5625
3
using System; using System.Linq; using System.Text; using System.Web.Mvc; using EPiServer; using EPiServer.Core; namespace ImageResizer.Plugins.EPiServer { public static class HtmlHelperExtensionsForPicture { public static MvcHtmlString ResizePictures(this HtmlHelper helper, UrlBuilder[] urls, PictureProfile profile, string alternateText = "", string cssClass = "") { if(urls == null) throw new ArgumentNullException(nameof(urls)); if(urls.Length == 0) throw new ArgumentException($"{nameof(urls)} contains no elements"); if(profile == null) throw new ArgumentNullException(nameof(profile)); if(profile.SrcMedias == null) throw new ArgumentNullException(nameof(profile.SrcMedias)); if(profile.SrcMedias.Length == 0) throw new ArgumentException($"{nameof(profile.SrcMedias)} contains no elements"); if(urls.Length != profile.SrcMedias?.Length) throw new ArgumentException($"Length for `{nameof(urls)}` ({urls.Length}) and `{nameof(profile.SrcMedias)}` ({profile.SrcMedias.Length}) does not match."); var picture = new TagBuilder("picture"); var sources = new StringBuilder(); for (var i = 0; i < urls.Length; i++) { var source = new TagBuilder("source"); var media = profile.SrcMedias[i]; var width = profile.SrcSetWidths[i]; var url = urls[i].Clone(); url.QueryCollection["w"] = width.ToString(); source.Attributes.Add("srcset", url.ToString()); source.Attributes.Add("media", media); sources.Append(source.ToString(TagRenderMode.SelfClosing)); } var img = new TagBuilder("img"); var defaultUrl = urls.First().Clone(); defaultUrl.QueryCollection["w"] = profile.DefaultWidth.ToString(); img.Attributes.Add("src", defaultUrl.ToString()); img.Attributes.Add("alt", alternateText); if (!string.IsNullOrEmpty(cssClass)) img.Attributes.Add("class", cssClass); picture.InnerHtml = sources + img.ToString(TagRenderMode.SelfClosing); return new MvcHtmlString(picture.ToString()); } public static MvcHtmlString ResizePictures(this HtmlHelper helper, ContentReference[] images, PictureProfile profile, string alternateText = "", string cssClass = "") { if(images == null) throw new ArgumentNullException(nameof(images)); return helper.ResizePictures(images.Select((c, i) => helper.ResizeImage(c, profile.SrcSetWidths[i])).ToArray(), profile, alternateText, cssClass); } public static MvcHtmlString ResizePictureWithFallback(this HtmlHelper helper, ContentReference image, PictureProfile profile, string fallbackImage, string alternateText = "", string cssClass = "") { return image == null || image == ContentReference.EmptyReference ? ResizePicture(helper, new UrlBuilder(fallbackImage), profile, alternateText, cssClass) : ResizePicture(helper, image, profile, alternateText, cssClass); } public static MvcHtmlString ResizePicture(this HtmlHelper helper, UrlBuilder url, PictureProfile profile, string alternateText = "", string cssClass = "") { var imgUrl = url.Clone(); imgUrl.QueryCollection["w"] = profile.DefaultWidth.ToString(); var sourceSets = profile.SrcSetWidths.Select(w => { var sourceUrl = url.Clone(); sourceUrl.QueryCollection["w"] = w.ToString(); return $"{sourceUrl} {w}w"; }).ToArray(); return GeneratePictureElement(profile, imgUrl.ToString(), sourceSets, alternateText, cssClass); } public static MvcHtmlString ResizePicture(this HtmlHelper helper, ContentReference image, PictureProfile profile, string alternateText = "", string cssClass = "") { var imgUrl = helper.ResizeImage(image, profile.DefaultWidth); var sourceSets = profile.SrcSetWidths.Select(w => $"{helper.ResizeImage(image, w)} {w}w").ToArray(); return GeneratePictureElement(profile, imgUrl.ToString(), sourceSets, alternateText, cssClass); } private static MvcHtmlString GeneratePictureElement(PictureProfile profile, string imgUrl, string[] sourceSets, string alternateText = "", string cssClass = "") { var picture = new TagBuilder("picture"); var source = new TagBuilder("source"); if(profile.SrcSetSizes != null && profile.SrcSetSizes.Length > 0) source.Attributes.Add("sizes", string.Join(", ", profile.SrcSetSizes)); source.Attributes.Add("srcset", string.Join(", ", sourceSets)); var img = new TagBuilder("img"); img.Attributes.Add("src", imgUrl); img.Attributes.Add("alt", alternateText); if(!string.IsNullOrEmpty(cssClass)) img.Attributes.Add("class", cssClass); picture.InnerHtml = source.ToString(TagRenderMode.SelfClosing) + img.ToString(TagRenderMode.SelfClosing); return new MvcHtmlString(picture.ToString()); } } }
196064fae92e28884a670fdf6e31600f0bb7d4ba
C#
Yaroslav8Koledin/GitForEpam
/Task 3/Task 3.1/Epam.Tasks_3.1/Epam.Task_3.1.1. WEAKEST LINK/Program.cs
3.578125
4
using System; using System.Collections.Generic; namespace Epam.Task_3._1._1._WEAKEST_LINK { internal class Program { private static void Main() { var queue = new Queue<int>(); Console.WriteLine("ВЫВОД: Введите N"); int numberOfPeople = GetNumberOfPeople(); Console.WriteLine("ВЫВОД: Введите, какой по счету человек будет вычеркнут каждый раунд:"); int numToStrikeOut = GetNumberOfPeople(); Console.WriteLine($"ВЫВОД: Сгенерирован круг людей. Начинаем вычеркивать каждого {numToStrikeOut}."); for (int i = 0; i < numberOfPeople; i++) { queue.Enqueue(i + 1); } CrossOutEveryN(queue, numToStrikeOut); Console.WriteLine("ВЫВОД: Игра окончена. Невозможно вычеркнуть больше людей."); } private static void CrossOutEveryN(Queue<int> queue, int numToStrikeOut) { int round = 1; while (queue.Count >= numToStrikeOut) { for (int i = 0; i < numToStrikeOut-1; i++) { queue.Enqueue(queue.Dequeue()); } queue.Dequeue(); Console.WriteLine($"ВЫВОД: Раунд {round}. Вычеркнут человек. Людей осталось: {queue.Count}"); round++; } } private static int GetNumberOfPeople() { int inputNumberOfPeople; bool flag; do { Console.Write("ВЫВОД: "); flag = int.TryParse(Console.ReadLine(), out inputNumberOfPeople); } while (!flag); return inputNumberOfPeople; } } }
4d8d31b519dba5b1f3c767d4b25a767905d4f71e
C#
develorem/VisualProjectDependencies
/src/VisualProjectDependencies.Tests/ProjectParsingTests.cs
2.59375
3
using NUnit.Framework; using System.Linq; namespace VisualProjectDependencies.Tests { public class ProjectParsingTests { [SetUp] public void Setup() { } [Test] public void EnsureCanParseProjectFile() { var projectText = TestData.LoadSampleProjectText(); var projectReader = new ProjectReader(); var dependencies = projectReader.Read(projectText); Assert.AreEqual(2, dependencies.ProjectDependencyPaths.Count()); Assert.AreEqual(@"..\Home.Common\Home.Common.csproj", dependencies.ProjectDependencyPaths.ElementAt(0)); } } }
6aa9dc0be35a9c96f7bceafc1cc85b5cd62830be
C#
ivandobrinovv/dotNet
/UnitOfWorkSample_Completed3/UnitOfWorkSample_Completed/UnitOfWorkSample/Models/CategoryViewModel.cs
3
3
using System; using System.Collections.Generic; using System.Linq; using System.Web; using DataAccess; using System.ComponentModel.DataAnnotations; namespace UnitOfWorkSample.Models { /// <summary> /// The ViewModel class for the Index.cshtml and Edit.cshtml /// Usually we have to use always 1 ViewModel class for 1 view, but the information for the both views quite similar /// </summary> public class CategoryViewModel { #region Properties public int ID { get; set; } [Required] [DisplayFormat(ConvertEmptyStringToNull = false)] public string Name { get; set; } #endregion #region Constructors public CategoryViewModel() { // create a default constructor, because the MVC needs it when the form is submitted, // in order to create object of this type as parameter in an action } public CategoryViewModel(Category category) { this.Name = category.Name; this.ID = category.ID; } #endregion #region public methods public void UpdateDbModel(Category dbCategory) { dbCategory.Name = this.Name; } #endregion } }
183e874ab029aef2bd72be0a91820ea6f582cb91
C#
ThorvaldMortele/BrackeysGameJam
/Assets/Scripts/BossSystem/Cannons/ObjectPoolBoss.cs
2.71875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using UnityEngine; namespace BossSystem { public class ObjectPoolBoss : MonoBehaviour { public static ObjectPoolBoss Instance; public List<GameObject> PooledObjects; public GameObject ObjectToPool; public int AmountToPool; private void Awake() { Instance = this; PooledObjects = new List<GameObject>(); GameObject tmp; for (int i = 0; i < AmountToPool; i++) { tmp = Instantiate(ObjectToPool, this.gameObject.transform); tmp.SetActive(false); PooledObjects.Add(tmp); } } public GameObject GetPooledObject() //Possibly a problem with the deactivation { for (int i = 0; i < AmountToPool; i++) { if (!PooledObjects[i].activeInHierarchy) { return PooledObjects[i]; //"Het werkt" - Dizz 2021 } } return null; } } }
66aa5b266ebf23bd67d3c93764a5cf52dbbbbf0c
C#
nataliii1245/StackGame
/StackGame/Commands/ChangeCountOfMovementsCommand.cs
2.921875
3
using StackGame.Loggers; using StackGame.Game; namespace StackGame.Commands { /// <summary> /// Команда для изменения количества ходов /// </summary> public class ChangeCountOfMovementsCommand : ICommand { #region Свойства /// <summary> /// Исходное количество ходов /// </summary> private readonly int CountOfMovements; /// <summary> /// Новое количество ходов /// </summary> private readonly int newCountOfMovements; #endregion #region Инициализация public ChangeCountOfMovementsCommand(int CountOfMovements, int newCountOfMovements) { this.CountOfMovements = CountOfMovements; this.newCountOfMovements = newCountOfMovements; } #endregion #region Методы public void Execute(ILogger logger) { Engine.GetInstance().CountOfMovements = newCountOfMovements; } public void Undo(ILogger logger) { Engine.GetInstance().CountOfMovements = CountOfMovements; } #endregion } }
378ed9643414965ffa79c3c52225215f55abf97f
C#
VolodymyrNahornyi/Online-Concert-Ticket-Sales
/Repository/GenreRepository.cs
2.765625
3
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Contracts; using Entities; using Entities.Models.Concerts; using Microsoft.EntityFrameworkCore; namespace Repository { public class GenreRepository : RepositoryBase<Genre>, IGenreRepository { public GenreRepository(RepositoryContext repositoryContext) : base(repositoryContext) { } public async Task<IEnumerable<Genre>> GetAllGenresAsync(bool trackChanges) { return await FindAll(trackChanges) .OrderBy(g => g.GenreName) .ToListAsync(); } public async Task<Genre> GetGenreAsync(Guid genreId, bool trackChanges) { return await FindByCondition(g => g.Id.Equals(genreId), trackChanges) .SingleOrDefaultAsync(); } public void CreateGenre(Genre genre) { Create(genre); } public async Task<IEnumerable<Genre>> GetGenresByIdsAsync(IEnumerable<Guid> Ids, bool trackChanges) { return await FindByCondition(x => Ids.Contains(x.Id), trackChanges) .ToListAsync(); } public void DeleteGenre(Genre genre) { Delete(genre); } } }
7db4f127c97995f93e5ceeee5d592948fb5d593e
C#
Azzariah/Personal-Projects
/C# Projects/InstaWarp2 sources/InstaWarp2 - For Dll - Copy/Core/Classes/Memory.cs
2.96875
3
 namespace Core.Classes { using System; using System.Diagnostics; using System.Runtime.InteropServices; /// <summary> /// Memory Helper Class /// /// Wraps ReadProcessMemory and WriteProcessMemory API for easier usage. /// </summary> public static class Memory { /// <summary> /// Reads the amount of bytes from the given location. /// </summary> /// <param name="p"></param> /// <param name="lpAddress"></param> /// <param name="btBuffer"></param> /// <returns></returns> public static bool Peek(Process p, IntPtr lpAddress, byte[] btBuffer) { if (p == null || btBuffer == null || btBuffer.Length == 0) return false; var read = new IntPtr(0); return NativeMethods.ReadProcessMemory(p.Handle, lpAddress, btBuffer, (uint)btBuffer.Length, ref read); } /// <summary> /// Writes the given bytes to the given memory location. /// </summary> /// <param name="p"></param> /// <param name="lpAddress"></param> /// <param name="btBuffer"></param> /// <returns></returns> public static bool Poke(Process p, IntPtr lpAddress, byte[] btBuffer) { if (p == null) return false; var written = new IntPtr(0); return NativeMethods.WriteProcessMemory(p.Handle, lpAddress, btBuffer, (uint)btBuffer.Length, ref written); } } /// <summary> /// Internal NativeMethods Import Definitions /// /// </summary> internal static class NativeMethods { /// <summary> /// kernel32.ReadProcessMemory Import /// </summary> /// <param name="hProcess"></param> /// <param name="lpBaseAddress"></param> /// <param name="lpBuffer"></param> /// <param name="nSize"></param> /// <param name="lpNumberOfBytesRead"></param> /// <returns></returns> [DllImport("kernel32.dll", SetLastError = true)] internal static extern bool ReadProcessMemory( IntPtr hProcess, IntPtr lpBaseAddress, [In, Out] byte[] lpBuffer, UInt32 nSize, ref IntPtr lpNumberOfBytesRead ); /// <summary> /// kernel32.WriteProcessMemory Import /// </summary> /// <param name="hProcess"></param> /// <param name="lpBaseAddress"></param> /// <param name="lpBuffer"></param> /// <param name="nSize"></param> /// <param name="lpNumberOfBytesWritten"></param> /// <returns></returns> [DllImport("kernel32.dll", SetLastError = true)] internal static extern bool WriteProcessMemory( IntPtr hProcess, IntPtr lpBaseAddress, [In, Out] byte[] lpBuffer, UInt32 nSize, ref IntPtr lpNumberOfBytesWritten ); } }
f4725bc601fa7f9f6e4e150de4e5c03bcd40b116
C#
alexsrd/lr4graphics
/Pupil.cs
2.828125
3
using SharpGL; namespace lr4graphics { class Pupil { bool IsLeft = false; public Pupil(bool IsLeft) { this.IsLeft = IsLeft; } public void Draw(OpenGL gl) { DrawLeftPupil(gl); DrawRightPupil(gl); } private void DrawLeftPupil(OpenGL gl) { gl.LoadIdentity(); gl.Translate(0f, 0f, -5f); gl.Rotate(TransformInfo.AngleX, TransformInfo.AngleY, TransformInfo.AngleZ); gl.Translate(0, 0f, 5); gl.Scale(TransformInfo.ScaleX, TransformInfo.ScaleY, TransformInfo.ScaleZ); gl.Translate(-0.25f, 0.7f, -4.319f); gl.Rotate(180, 0, 1, 0); gl.Begin(OpenGL.GL_QUADS); var quadric = gl.NewQuadric(); gl.Color(0f, 0f, 0f); gl.Sphere(quadric, 0.05, 10, 10); gl.End(); } private void DrawRightPupil(OpenGL gl) { gl.LoadIdentity(); gl.Translate(0f, 0f, -5f); gl.Rotate(TransformInfo.AngleX, TransformInfo.AngleY, TransformInfo.AngleZ); gl.Translate(0, 0f, 5); gl.Scale(TransformInfo.ScaleX, TransformInfo.ScaleY, TransformInfo.ScaleZ); gl.Translate(0.25f, 0.7f, -4.319f); gl.Rotate(180, 0, 1, 0); gl.Begin(OpenGL.GL_QUADS); var quadric = gl.NewQuadric(); gl.Color(0f, 0f, 0f); gl.Sphere(quadric, 0.05, 10, 10); gl.End(); } } }
68d32ae05cd9b23943d406e15590faeb0f2acb29
C#
Rzilinski77/RoomSizeCalculator
/RoomSizeGenerator/RoomSizeGenerator/Program.cs
3.5
4
using Microsoft.VisualBasic.CompilerServices; using System; using System.Reflection.Metadata; namespace RoomSizeGenerator { class Program { static void Main(string[] args) { Console.WriteLine("Welcome to the Room Size Generator!"); Console.WriteLine("----------------------------------------\n"); string more = "y"; do { Console.Write("Enter the width of the room in inches:"); int width = int.Parse(Console.ReadLine()); Console.Write("Enter the length of the room in inches:"); int length = int.Parse(Console.ReadLine()); int perimeter = (2 * width) + (2 * length); int area = (width * length); Console.WriteLine(); Console.WriteLine($"Perimeter = {perimeter} inches"); Console.WriteLine($"Area = {area} square inches"); Console.WriteLine(); Console.WriteLine("Would you like to continue? (y/n)"); more = Console.ReadLine(); } while (more == "y"); Console.WriteLine("Goodbye"); } } }
78e777fc2d71c20f2d2d4f78f2bb6dbf7559271c
C#
RavitejaPatel/C-_CORE_PROGRAMS
/WhilePract1.cs
3.265625
3
using System; class whilePract { public static void Main() { int n=int.Parse(Console.ReadLine()); Console.Write("sum is 1"); int i=1; int sum=1; while(i<n) { i++; sum=sum+i; Console.Write("+"+i); } Console.Write("="+sum); } }
81230568ec85b20545986b1b4aa2ed0c467aa367
C#
Archaeren/HauntingMemory
/MatchGame/Form1.cs
3.3125
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 MatchGame { public partial class HauntingMemory : Form { // firstClicked points to the first Label control // that the player clicks, but it will be null // if the player hasn't clicked a label yet Label firstClicked = null; // secondClicked points to the second Label control // that the player clicks Label secondClicked = null; // Use this Random object to choose random icons for the squares Random random = new Random(); bool victoryTrue = false; //This integer variable keeps track of pairs clicked int clickCount; //This integer variable keeps track of how many matches have been made int matchMade; //This integer variable keeps track of how many total matches are possible int matchTotal; // This integer variable keeps track of the time. int timeCount; /* Each of these letters is an spooky icon in the Webdings font, and each icon appears twice in this list Had to create a variable to define one of them because it's an invisible character */ private static readonly string shy = ((char)173).ToString(); List<string> icons = new List<string>() { "!", "!", "\"", "\"", "N", "N", "Z", "Z", "•", "•", "˜", "˜", "¡", "¡", "Ñ", "Ñ", "ó", "ó", "ö", "ö", "«", "«", shy, shy }; private void AssignIconsToSquares() { //This foreach loop selects an icon randomly from the icon list foreach (Control control in tableLayoutPanel1.Controls) { //checks to see if the instance of 'control' is a label //if it is, tells the program it's okay to use as a label //if not a label, returns null Label iconLabel = control as Label; if (iconLabel != null && iconLabel.Text == "c") { //creates a variable, randomNumber, by selecting a number //between 0 and the end of the icons list int randomNumber = random.Next(icons.Count); //chooses the text string from the list based on the //number chosen in the previous line iconLabel.Text = icons[randomNumber]; //changes the icon's color so the player can't see them iconLabel.ForeColor = iconLabel.BackColor; //removes the text string for the icon we just used //so it doesn't get repeated icons.RemoveAt(randomNumber); } } } public HauntingMemory() { InitializeComponent(); timer2.Start(); matchTotal = (icons.Count / 2); AssignIconsToSquares(); } private void label_Click(object sender, EventArgs e) { // The timer is only on after two non-matching // icons have been shown to the player, // so ignore any clicks if the timer is running if (timer1.Enabled == true) return; Label clickedLabel = sender as Label; if (clickedLabel != null) { // If the clicked label is black, the player clicked // an icon that's already been revealed -- // ignore the click if (clickedLabel.ForeColor == Color.Black) return; // If firstClicked is null, this is the first icon // in the pair that the player clicked, // so set firstClicked to the label that the player // clicked, change its color to black, and return if (firstClicked == null) { firstClicked = clickedLabel; firstClicked.ForeColor = Color.Black; clickCount += 1; return; } // If the player gets this far, the timer isn't // running and firstClicked isn't null, // so this must be the second icon the player clicked // Set its color to black secondClicked = clickedLabel; secondClicked.ForeColor = Color.Black; // If the player clicked two matching icons, keep them // black and reset firstClicked and secondClicked // so the player can click another icon if (firstClicked.Text == secondClicked.Text) { matchMade += 1; firstClicked = null; secondClicked = null; // Check to see if the player won CheckForWinner(); return; } // If the player gets this far, the player // clicked two different icons, so start the // timer (which will wait three quarters of // a second, and then hide the icons) timer1.Start(); } } private void timer1_Tick(object sender, EventArgs e) { // Stop the timer timer1.Stop(); // Hide both icons firstClicked.ForeColor = firstClicked.BackColor; secondClicked.ForeColor = secondClicked.BackColor; // Reset firstClicked and secondClicked // so the next time a label is // clicked, the program knows it's the first click firstClicked = null; secondClicked = null; } private void CheckForWinner() { if (matchMade == matchTotal) { timer2.Stop(); MessageBox.Show("You are the spookiest!!", "Your soul is dark as night"); Close(); } else { return; } // Go through all of the labels in the TableLayoutPanel, // checking each one to see if its icon is matched /*foreach (Control control in tableLayoutPanel1.Controls) { Label iconLabel = control as Label; if (iconLabel != null) { if (iconLabel.ForeColor == iconLabel.BackColor) return; } }*/ // If the loop didn't return, it didn't find // any unmatched icons // That means the user won. Show a message and close the form } private void timer2_Tick(object sender, EventArgs e) { timeCount = timeCount + 1; timeLabel.Text = timeCount.ToString(); //if the player hasn't won yet, add 1 to the counter every second //if (victoryTrue == false) { //adds 1 to the counter //timeCount = timeCount + 1; //Should display the time in the label. Commented out because it's causing a refresh issue. //timeLabel.Text = timeCount.ToString(); } //else //Theoretically stops the timer upon winning //can't test because form area currently too small to display //timer2.Stop(); } } }
3f3b294f6c2092aed1598b8e6866ffd8e5bd9b3b
C#
zadontseva/project1
/Form1.cs
2.640625
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 WindowsFormsApp1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private async void dateTimePicker1_ValueChanged(object sender, EventArgs e) { dateTimePicker1.Enabled = false; var count = await Task<int>.Factory.StartNew(()=> { int year = (DateTime.Now.Date.Year - dateTimePicker1.Value.Date.Year); return year; }); if (count > -1 && count < 135) textBox1.Text = count.ToString(); else { MessageBoxButtons button = MessageBoxButtons.OK; string message = "Необхідно ввести вік, що не перевищує 135 років"; string caption = "Помилка вводу віку"; DialogResult result = MessageBox.Show(message, caption, button); if (result == System.Windows.Forms.DialogResult.OK) dateTimePicker1.Value = DateTime.Now.AddDays(-1); } var zodiac1 = await Task<string>.Factory.StartNew(() => { int day = dateTimePicker1.Value.Day; int month = dateTimePicker1.Value.Month; string sign; switch (month) { case 1: sign = (day <= 20) ? "Козеріг" : "Водолій"; break; case 2: sign = (day <= 19) ? "Водолій" : "Риби"; break; case 3: sign = (day <= 20) ? "Риби" : "Овен"; break; case 4: sign = (day <= 20) ? "Овен" : "Телець"; break; case 5: sign = (day <= 21) ? "Телець" : "Близнюки"; break; case 6: sign = (day <= 21) ? "Близнюки" : "Рак"; break; case 7: sign = (day <= 22) ? "Рак" : "Лев"; break; case 8: sign = (day <= 23) ? "Лев" : "Діва"; break; case 9: sign = (day <= 23) ? "Діва" : "Терези"; break; case 10: sign = (day <= 23) ? "Терези" : "Скорпіон"; break; case 11: sign = (day <= 22) ? "Скорпіон" : "Стрілець"; break; case 12: sign = (day <= 23) ? "Стрілець" : "Козеріг"; break; default: sign = ""; break; } return sign; }); var zodiac2 = await Task<string>.Factory.StartNew(() => { int ch_year = dateTimePicker1.Value.Year % 12; string output; switch (ch_year) { case 0: output = "Мавпа"; break; case 1: output = "Півень"; break; case 2: output = "Собака"; break; case 3: output = "Свиня"; break; case 4: output = "Пацюк"; break; case 5: output = "Бик"; break; case 6: output = "Тигр"; break; case 7: output = "Кролик"; break; case 8: output = "Дракон"; break; case 9: output = "Змія"; break; case 10: output = "Кінь"; break; case 11: output = "Коза"; break; default: output = ""; break; } return output; }); textBox2.Text = zodiac1; textBox3.Text = zodiac2; dateTimePicker1.Enabled = true; } private void textBox2_TextChanged(object sender, EventArgs e) { } private void label1_Click(object sender, EventArgs e) { } } }
ce5e84820b2501639a498de93ca55e9cc8ebb6b6
C#
GregSmalter/TEWL
/Tewl/IO/IoMethods.cs
2.890625
3
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Threading; using JetBrains.Annotations; using Tewl.Tools; namespace Tewl.IO { /// <summary> /// A collection of IO-related static methods. /// </summary> [ PublicAPI ] public static class IoMethods { /// <summary> /// Creates the destination path if it does not exist, and downloads the file to that destination path. /// </summary> public static void DownloadFile( string url, string destinationPath, NetworkCredential credentials = null, string customAuthorizationHeaderValue = "" ) { Directory.CreateDirectory( Path.GetDirectoryName( destinationPath ) ); using( var webClient = new WebClient() ) { if( credentials != null ) webClient.Credentials = credentials; else if( customAuthorizationHeaderValue.Any() ) webClient.Headers.Add( HttpRequestHeader.Authorization, customAuthorizationHeaderValue ); webClient.DownloadFile( url, destinationPath ); } } /// <summary> /// Recursively copies the contents of the specified source directory to the specified destination directory. Creates the /// destination directory if it /// doesn't already exist. Does not overwrite anything in the destination folder if it already exists. /// </summary> public static void CopyFolder( string src, string dest, bool overwriteExistingFiles ) { var di = new DirectoryInfo( src ); Directory.CreateDirectory( dest ); foreach( var fsi in di.GetFileSystemInfos() ) { var destName = Path.Combine( dest, fsi.Name ); if( fsi is FileInfo ) File.Copy( fsi.FullName, destName, overwriteExistingFiles ); else if( fsi is DirectoryInfo ) CopyFolder( fsi.FullName, destName, overwriteExistingFiles ); } } /// <summary> /// Deletes the specified directory and its contents, if the directory exists. Supports deletion of partially or fully /// read-only directories. /// </summary> public static void DeleteFolder( string path ) { var numberOfFailures = 0; while( Directory.Exists( path ) ) { try { RecursivelyRemoveReadOnlyAttributeFromItem( path ); Directory.Delete( path, true ); } catch( IOException e ) { handleFailedDeletion( path, ref numberOfFailures, e ); } catch( UnauthorizedAccessException e ) { handleFailedDeletion( path, ref numberOfFailures, e ); } } } /// <summary> /// Deletes the file at the given path, or does nothing if it does not exist. Supports deletion of partially or fully /// read-only files. /// </summary> public static void DeleteFile( string path ) { var numberOfFailures = 0; while( File.Exists( path ) ) { try { RecursivelyRemoveReadOnlyAttributeFromItem( path ); File.Delete( path ); } catch( IOException e ) { handleFailedDeletion( path, ref numberOfFailures, e ); } catch( UnauthorizedAccessException e ) { handleFailedDeletion( path, ref numberOfFailures, e ); } } } private static void handleFailedDeletion( string path, ref int numberOfFailures, Exception exception ) { if( ++numberOfFailures >= 100 ) throw new IOException( "Failed to delete " + path + " 100 times in a row. The inner exception is the most recent failure.", exception ); Thread.Sleep( 100 ); } /// <summary> /// Overwrites the destination path. /// </summary> public static void MoveFile( string sourcePath, string destinationPath ) { CopyFile( sourcePath, destinationPath ); DeleteFile( sourcePath ); } /// <summary> /// Creates the destination folder if it does not exist. Overwrites the destination file if it already exists. /// </summary> public static void CopyFile( string sourcePath, string destinationPath ) { DeleteFile( destinationPath ); Directory.CreateDirectory( Path.GetDirectoryName( destinationPath ) ); File.Copy( sourcePath, destinationPath ); } /// <summary> /// Recursively removes the read-only attribute from the specified file or folder. /// </summary> public static void RecursivelyRemoveReadOnlyAttributeFromItem( string path ) { var attributes = File.GetAttributes( path ); if( ( attributes & FileAttributes.ReadOnly ) == FileAttributes.ReadOnly ) File.SetAttributes( path, attributes & ~FileAttributes.ReadOnly ); if( Directory.Exists( path ) ) { foreach( var childPath in Directory.GetFileSystemEntries( path ) ) RecursivelyRemoveReadOnlyAttributeFromItem( childPath ); } } /// <summary> /// Gets a list of file names (not including path) in the specified folder, ordered by modified date descending, that match /// the specified search pattern. /// Does not include files in subfolders. If the folder does not exist, returns an empty collection. /// </summary> public static IEnumerable<string> GetFileNamesInFolder( string folderPath, string searchPattern = "*" ) => GetFilePathsInFolder( folderPath, searchPattern ).Select( Path.GetFileName ); /// <summary> /// Gets a list of file paths in the specified folder, ordered by last modified date descending, that match the specified /// search pattern. The default search /// option is to not include files in subfolders. If the folder does not exist, returns an empty collection. /// </summary> public static IEnumerable<string> GetFilePathsInFolder( string folderPath, string searchPattern = "*", SearchOption searchOption = SearchOption.TopDirectoryOnly ) { if( !Directory.Exists( folderPath ) ) return Enumerable.Empty<string>(); return new DirectoryInfo( folderPath ).EnumerateFiles( searchPattern, searchOption ).OrderByDescending( f => f.LastWriteTime ).Select( f => f.FullName ); } /// <summary> /// Gets a list of folder names in the specified folder. /// </summary> public static List<string> GetFolderNamesInFolder( string folderPath ) => Directory.GetDirectories( folderPath ).Select( Path.GetFileName ).ToList(); /// <summary> /// Gets the sum size, in bytes, of everything in the folder at the given path (recursive). /// </summary> public static long GetFolderSize( string path ) => File.Exists( path ) ? new FileInfo( path ).Length : Directory.GetFileSystemEntries( path ).Sum( filePath => GetFolderSize( filePath ) ); /// <summary> /// Returns a text writer for writing a new file or overwriting an existing file. /// Automatically creates any folders needed in the given path, if necessary. /// We recommend passing an absolute path. If a relative path is passed, the working folder /// is used as the root path. /// Caller is responsible for properly disposing the stream. /// </summary> public static TextWriter GetTextWriterForWrite( string filePath ) => new StreamWriter( GetFileStreamForWrite( filePath ) ); /// <summary> /// Returns a file stream for writing a new file or overwriting an existing file. /// Automatically creates any folders needed in the given path, if necessary. /// We recommend passing an absolute path. If a relative path is passed, the working folder /// is used as the root path. /// Caller is responsible for properly disposing the stream. /// </summary> public static FileStream GetFileStreamForWrite( string filePath ) { Directory.CreateDirectory( Path.GetDirectoryName( filePath ) ); return File.Create( filePath ); } /// <summary> /// Executes the specified method with a stream for a temporary file. The file will be deleted after the method executes. /// </summary> public static void ExecuteWithTempFileStream( Action<FileStream> method ) { const int bufferSize = 4096; // This was the FileStream default as of 13 October 2014. // Instead of deleting the file in a finally block, we pass FileOptions.DeleteOnClose because it will ensure that the file gets deleted even if our // process terminates unexpectedly. using( var stream = new FileStream( Path.GetTempFileName(), FileMode.Open, FileAccess.ReadWrite, FileShare.None, bufferSize, FileOptions.DeleteOnClose ) ) method( stream ); } /// <summary> /// Automatically creates and cleans up a temporary folder for the given method to use. Passes the folder path to the given /// action. /// There is a race condition here: another process could create a directory after we check if our folder path exists, but /// before we create the folder. See /// http://stackoverflow.com/a/217198/35349. We believe this is unlikely and is an acceptable risk. /// </summary> public static void ExecuteWithTempFolder( Action<string> method ) { string folderPath; do folderPath = Path.Combine( Path.GetTempPath(), Path.GetRandomFileName() ); while( File.Exists( folderPath ) || Directory.Exists( folderPath ) ); Directory.CreateDirectory( folderPath ); try { method( folderPath ); } finally { DeleteFolder( folderPath ); } } /// <summary> /// Given a list of possible paths, returns the first one that exists, or throws an ApplicationException if none exist. /// This method is useful when you know one of many possible SDK or tool paths exist but you aren't sure which one. /// </summary> public static string GetFirstExistingFolderPath( IReadOnlyCollection<string> folderPaths, string folderAdjective ) { var first = folderPaths.FirstOrDefault( Directory.Exists ); if( first == null ) { throw new ApplicationException( $"Unable to find a {folderAdjective} folder. The following paths do not exist or are inaccessible: {folderPaths.GetCommaDelimitedStringFromCollection()}" ); } return first; } } }
c572bfb7408f9b513fdac44c249fe1c3f2616d05
C#
ajcampbell1333/DOFSCII
/Assets/DOFSCII/Scripts/UDP/SendKeystrokes.cs
2.625
3
using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Text; using System.Net; using System.Net.Sockets; using CrossplatformVRInput; using UnityEngine.UI; using System; namespace DOFSCII { public class SendKeystrokes : VRInputSubscriber { [SerializeField] int port; KeyMode currentKeyMode = KeyMode.Alphanumeric; /// <summary> /// the inputs collected during a given check loop /// </summary> DOFSCIIMap inputFlags; /// <summary> /// The time buffer from the beginning of the last intended simultaneous input to the time the input combination is /// interpreted as a keystroke. We need a small buffer to compensate for user latency between multiple inputs that /// have simultaneous intent, but we also need to keep the buffer very short to prevent it from overlapping a future keystroke. /// </summary> [SerializeField] float checkLoopDuration; /// <summary> /// The clock time at which a keystroke is received from the user. If a new stroke is received within the checkLoopDuration of the previous /// stroke, the current stroke is considered to be simultaneous with the previous. /// </summary> float timeCheckLoopBegan; /// <summary> /// A coroutine which runs while keyboard input is happening and stops when keyboard input is done. The loop waits for the duration, /// and if a new stroke occurs during the wait, the wait starts over. When the wait is over, the loop calls back to interpret the key stroke. /// </summary> IEnumerator combinationCheckLoop; /// <summary> /// Is the input supposed to be capitalized? /// </summary> bool caps; /// <summary> /// This counter is distinct from the HammingWeight function in that it tracks the # of buttons currently pressed during the check loop. /// This number always reaches zero the moment the loop ends. Hamming Weight tallies the total # of flags tripped during the loop, /// but it does so after the loop is finished. /// This number needs to go to zero to allow the loop to end when all inputs are released, /// and then Hamming Weight tallies the results afterwards. /// </summary> int inputsActiveTally = 0; /// <summary> /// The client through which to send input to the keystroke server /// </summary> UdpClient client; void Awake() { Application.runInBackground = true; IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(Network.player.ipAddress), port); client = new UdpClient(); client.Connect(endPoint); } void StartCheckLoop() { if (combinationCheckLoop != null) StopCoroutine(combinationCheckLoop); combinationCheckLoop = CheckLoop(); timeCheckLoopBegan = Time.time; StartCoroutine(combinationCheckLoop); } void EndCheckLoop() { // Avoid duplicate checks by only running the check if the loop iEnumerator is not null if (combinationCheckLoop != null) { Send(); StopCoroutine(combinationCheckLoop); combinationCheckLoop = null; } inputFlags = 0; } /// <summary> /// Send the desired input to the keystroke server /// </summary> public void Send() { byte[] packetData = BitConverter.GetBytes((Int32)inputFlags); client.Send(packetData, packetData.Length); } /// <summary> /// The check loop exists simply to await keystrokes that were intended as simultaneous. /// If a second keystroke happens soon enough after the first, it will reset timeCheckLoopBegan /// and allow the loop to continue waiting. /// Assign the checkLoopDuration at a small fraction of a second for proper performance. /// If duration is too long, some keystrokes intended as separate will be interpreted as simultaneous. /// If duration is too short, some keystrokes intended as simultaneous will be interpreted as separate. /// </summary> /// <returns></returns> IEnumerator CheckLoop() { yield return new WaitUntil(() => Time.time > timeCheckLoopBegan + checkLoopDuration); EndCheckLoop(); } /// <summary> /// For each input activation event, update the input flags to show the given button was pressed and reset the starting time of the loop. /// </summary> void InputDownEventHelper(string inputLogName, DOFSCIIMap inputFlag) { //Debug.Log(inputLogName + " button pressed"); inputFlags |= inputFlag; timeCheckLoopBegan = Time.time; inputsActiveTally++; if (combinationCheckLoop == null) StartCheckLoop(); } #region Input Activation Events protected override void OnMainRightDown() { InputDownEventHelper("main right", DOFSCIIMap.mainRight); } protected override void OnMainLeftDown() { InputDownEventHelper("main left", DOFSCIIMap.mainLeft); } protected override void OnForceClickLeftDown() { InputDownEventHelper("left thumb click", DOFSCIIMap.forceClickLeft); } protected override void OnForceClickRightDown() { InputDownEventHelper("right thumb click", DOFSCIIMap.forceClickRight); } protected override void OnGripLeftDown() { InputDownEventHelper("left grip", DOFSCIIMap.gripLeft); } protected override void OnGripRightDown() { InputDownEventHelper("right grip", DOFSCIIMap.gripRight); } protected override void OnTriggerLeftDown() { InputDownEventHelper("left trigger", DOFSCIIMap.triggerLeft); } protected override void OnTriggerRightDown() { InputDownEventHelper("right trigger", DOFSCIIMap.triggerRight); } #endregion /// <summary> /// For each input deactivation event, check to see if there are still any buttons pressed. If not, end the check loop. /// </summary> /// <param name="inputLogName">the name of the input to be printed in the log</param> void InputUpEventHelper(string inputLogName) { //Debug.Log(inputLogName + " button released"); inputsActiveTally--; if (inputsActiveTally <= 0) inputsActiveTally = 0; if (inputsActiveTally == 0) EndCheckLoop(); } #region Input Release Events protected override void OnMainRightUp() { InputUpEventHelper("main right"); } protected override void OnMainLeftUp() { InputUpEventHelper("left right"); } protected override void OnForceClickLeftUp() { InputUpEventHelper("left thumb click"); } protected override void OnForceClickRightUp() { InputUpEventHelper("right thumb click"); } protected override void OnGripLeftUp() { InputUpEventHelper("left grip"); } protected override void OnGripRightUp() { InputUpEventHelper("right grip"); } protected override void OnTriggerLeftUp() { InputUpEventHelper("left trigger"); } protected override void OnTriggerRightUp() { InputUpEventHelper("right trigger"); } #endregion } }
9ca2d0493ee36d710aca052313f40077f29e32a7
C#
solomoto-dev/MongoDBQueue
/MongoQueue.Legacy/LegacySubscriptionAgent.cs
2.546875
3
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using MongoDB.Driver.Builders; using MongoQueue.Core.AgentAbstractions; using MongoQueue.Core.Entities; namespace MongoQueue.Legacy { public class LegacySubscriptionAgent : ISubscriptionAgent { private readonly LegacyMongoAgent _mongoAgent; public LegacySubscriptionAgent(LegacyMongoAgent mongoAgent) { _mongoAgent = mongoAgent; } public List<Subscriber> GetSubscribers(string topic) { var subscribersCollection = _mongoAgent.GetSubscribers(); var subscribers = subscribersCollection.Find(Query<Subscriber>.All(x => x.Topics, new[] { topic })).ToList(); return subscribers; } public async Task<List<Subscriber>> GetSubscribersAsync(string topic) { return GetSubscribers(topic); } public async Task UpdateSubscriber(string route, string[] topics) { var subscriber = new Subscriber(route, topics); var subscribersCollection = _mongoAgent.GetSubscribers(); var query = Query<Subscriber>.EQ(x => x.Name, route); var existingSubscriber = subscribersCollection.Find(query).FirstOrDefault(); if (existingSubscriber != null) { subscriber.Id = existingSubscriber.Id; subscribersCollection.Update(query, Update<Subscriber>.Replace(subscriber)); } else { subscribersCollection.Insert(subscriber); } } } }
4879861b31cfa628712ca965efef22fa1bc8494a
C#
canslab/ImageBasedLocalizer
/ImageLocalizer/Place.cs
2.671875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using OpenCvSharp; namespace ImageLocalizer { class Place { public string PlaceName { get; private set; } public int Size { get; private set; } public Dictionary<Tuple<int, int, int>, List<Mat>> GridDescriptor { get; private set; } private ORB m_orbDetector = null; private BFMatcher m_matcher = new OpenCvSharp.BFMatcher(NormTypes.Hamming2); private int m_nORBFeatures = 0; public Dictionary<Tuple<int, int, int>, String> RepImages { get; private set; } public Place(string[] images, int nORBFeatures, float scaleFactor) { m_orbDetector = ORB.Create(nORBFeatures); GridDescriptor = new Dictionary<Tuple<int, int, int>, List<Mat>>(); RepImages = new Dictionary<Tuple<int, int, int>, string>(); m_nORBFeatures = nORBFeatures; // Iterate over all image paths in images foreach (var imagePath in images) { Tuple<int, int, int> currentImagePose = null; // Read the current Image var currentImageMat = Cv2.ImRead(imagePath, ImreadModes.Grayscale); Cv2.Resize(currentImageMat, currentImageMat, new OpenCvSharp.Size(currentImageMat.Width * scaleFactor, currentImageMat.Height * scaleFactor)); var temp = imagePath.Split('\\'); var fileName = temp[temp.Length - 1]; // Tokenize to extract the information from the image string[] tokens = fileName.Split('_'); if (tokens.Length == 5) { int x, y, rotIdx; bool bParseSuccess = true; bParseSuccess = Int32.TryParse(tokens[1], out x); if (bParseSuccess == false) { // Parse Failed.. Console.WriteLine("Check names of images"); } bParseSuccess = Int32.TryParse(tokens[2], out y); if (bParseSuccess == false) { // Parse Failed.. Console.WriteLine("Check names of images"); } bParseSuccess = Int32.TryParse(tokens[3], out rotIdx); if (bParseSuccess == false) { // Parse Failed.. Console.WriteLine("Check names of images"); } // Allocate the coordinate for this image PlaceName = tokens[0]; currentImagePose = new Tuple<int, int, int>(x, y, rotIdx); // Increment the count of images for this place Size++; // If there is no key (currentImageLocation), allocate if (GridDescriptor.ContainsKey(currentImagePose) == false) { GridDescriptor.Add(currentImagePose, new List<Mat>(0)); RepImages.Add(currentImagePose, imagePath); } // Detect and compute using ORB Mat descriptor = new Mat(); KeyPoint[] keypoints; m_orbDetector.DetectAndCompute(currentImageMat, null, out keypoints, descriptor); GridDescriptor[currentImagePose].Add(descriptor); Console.WriteLine("Storing Images.. Place = {0}, (x={1}, y={2}, thetaIdx={3})", PlaceName, currentImagePose.Item1, currentImagePose.Item2, currentImagePose.Item3); } } } private void CalculateSimilarity(Mat query_desc, Mat train_desc, out List<float> distances) { distances = new List<float>(); if (train_desc.Rows >= 2) { var matches = m_matcher.KnnMatch(query_desc, train_desc, 2); for (int i = 0; i < matches.Length; ++i) { if (matches[i][0].Distance < 0.75 * matches[i][1].Distance) { distances.Add(matches[i][0].Distance); } } } } //public void GetNearestOne(string givenImageFullPath, out Tuple<int, int, int> mostSimilarPose, out float maxSimilarity) //{ // KeyPoint[] keypoints = null; // Mat queryDescriptor = new Mat(); // var queryMat = Cv2.ImRead(givenImageFullPath, OpenCvSharp.ImreadModes.Grayscale); // Cv2.Resize(queryMat, queryMat, new OpenCvSharp.Size(queryMat.Width / 2, queryMat.Height / 2)); // m_orbDetector.DetectAndCompute(queryMat, null, out keypoints, queryDescriptor); // GetNearestOne(queryMat, out mostSimilarPose, out maxSimilarity); //} public void GetNearestOne(Mat givenImageMat, out Tuple<int, int, int> mostSimilarPose, out float maxSimilarity) { KeyPoint[] keypoints = null; Mat queryDescriptor = new Mat(); m_orbDetector.DetectAndCompute(givenImageMat, null, out keypoints, queryDescriptor); Tuple<int, int, int> currentMaxPose = null; float currentMaxVal = 0.0f; // For each pose, find the nearest image! foreach (var eachPose in this.GridDescriptor.Keys) { List<float> similaritiesForEachPose = new List<float>(); var correspondingDescriptorList = GridDescriptor[eachPose]; foreach (var eachDescriptor in correspondingDescriptorList) { CalculateSimilarity(queryDescriptor, eachDescriptor, out List<float> distances); similaritiesForEachPose.Add(distances.Count); } if (currentMaxVal <= similaritiesForEachPose.Max()) { currentMaxPose = eachPose; currentMaxVal = similaritiesForEachPose.Max(); } } mostSimilarPose = currentMaxPose; maxSimilarity = currentMaxVal / m_nORBFeatures; } } }
e8095ce53e6dfb48ef2e20f0006180cb2e6736c5
C#
drzott/DevToolbox
/C#/Office Automatisierung/Report.Util/DateUtil.cs
2.90625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Report.Util { public static class DateUtil { /// <summary> /// Gibt einen Datumswert zurück der direkt im Report verwendet werden kann /// </summary> public static string GetReportDate(string dateRange) { if (string.IsNullOrEmpty(dateRange)) return string.Empty; if (dateRange.ToLower() == "|aktuelles datum|") return DateTime.Now.ToString("dd.MM.yyyy"); if (dateRange.ToLower() == "|aktuelles jahr|") return DateTime.Now.Year.ToString(); if (dateRange.ToLower() == "|aktueller monat|") return DateTime.Now.Month.ToString(); if (dateRange.ToLower() == "|aktuelles quartal|") return ((int)((DateTime.Now.Month + 2) / 3)).ToString(); if (dateRange.ToLower() == "|vorjahr|") return (DateTime.Now.AddYears(-1)).Year.ToString(); if (dateRange.ToLower() == "|letzter abgeschlossener monat|") return (DateTime.Now.AddMonths(-1)).Month.ToString(); if (dateRange.ToLower() == "|vorletzter abgeschlossener monat|") return (DateTime.Now.AddMonths(-2)).Month.ToString(); if (dateRange.ToLower() == "|letztes abgeschlossenes quartal|") { if (DateTime.Now.Month <= 3) return "4"; if (DateTime.Now.Month <= 6) return "1"; if (DateTime.Now.Month <= 9) return "2"; return "3"; } if (dateRange.ToLower() == "|vorletztes abgeschlossenes quartal|") { if (DateTime.Now.Month <= 3) return "3"; if (DateTime.Now.Month <= 6) return "4"; if (DateTime.Now.Month <= 9) return "1"; return "2"; } return string.Empty; } /// <summary> /// Gibt den auswertungszeitraum eines Report-Elements des KPI Designers zurück /// </summary> public static ReportRange GetReportRange(string reportFrom, string reportTo, string reportFromRange, int reportFromRange_int, DateTime reportDateFrom, DateTime reportDateTo) { if (string.IsNullOrEmpty(reportFrom) && string.IsNullOrEmpty(reportTo)) return null; // Tag heute if ((!string.IsNullOrEmpty(reportFrom)) && reportFrom.ToLower() == "tag heute" && reportTo.ToLower() == "tag heute") return new ReportRange(DateTime.Today, DateTime.Today); // festes Datum ist gesetzt if ((!string.IsNullOrEmpty(reportFrom)) && reportFrom.ToLower() == "festes datum" && (!string.IsNullOrEmpty(reportTo)) && reportTo.ToLower() == "festes datum" && reportDateFrom != DateTime.MinValue && reportDateTo != DateTime.MinValue) { // unsinnig eingabe if (reportDateFrom > reportDateTo) return null; return new ReportRange(reportDateFrom, reportDateTo); } // Kombination aus Tag heute und festes Datum if ((!string.IsNullOrEmpty(reportFrom)) && reportFrom.ToLower() == "festes datum" && (!string.IsNullOrEmpty(reportTo)) && reportTo.ToLower() == "tag heute" && reportDateFrom != DateTime.MinValue) { if (reportDateFrom > DateTime.Today) return null; return new ReportRange(reportDateFrom, DateTime.Today); } if ((!string.IsNullOrEmpty(reportFrom)) && reportFrom.ToLower() == "tag heute" && (!string.IsNullOrEmpty(reportTo)) && reportTo.ToLower() == "festes datum" && reportDateTo != DateTime.MinValue) { if (DateTime.Today > reportDateTo) return null; return new ReportRange(DateTime.Today, reportDateTo); } // abgeschlossene Zeiträume if ((!string.IsNullOrEmpty(reportTo)) && reportTo.ToLower() == "letzter abgeschlossener monat") { DateTime from = FirstDayOfPreviousMonth(DateTime.Today); DateTime to = LastDayOfPreviousMonth(DateTime.Today); return new ReportRange(from, to); } if ((!string.IsNullOrEmpty(reportTo)) && reportTo.ToLower() == "vorletzter abgeschlossener monat") { DateTime from = FirstDayOfPrePreviousMonth(DateTime.Today); DateTime to = LastDayOfPrePreviousMonth(DateTime.Today); return new ReportRange(from, to); } if ((!string.IsNullOrEmpty(reportTo)) && reportTo.ToLower() == "letztes abgeschlossenes quartal") { DateTime dto = LastDayOfPreviousMonth(DateTime.Today); dto.AddDays(1); if (dto.Month > 9) { DateTime from = new DateTime(dto.Year, 7, 1); DateTime to = new DateTime(dto.Year, 9, 30); return new ReportRange(from, to); } if (dto.Month > 6) { DateTime from = new DateTime(dto.Year, 4, 1); DateTime to = new DateTime(dto.Year, 6, 30); return new ReportRange(from, to); } if (dto.Month > 3) { DateTime from = new DateTime(dto.Year, 1, 1); DateTime to = new DateTime(dto.Year, 3, 31); return new ReportRange(from, to); } if (dto.Month <= 3) { DateTime from = new DateTime(dto.Year - 1, 10, 1); DateTime to = new DateTime(dto.Year - 1, 12, 31); return new ReportRange(from, to); } return null; } if ((!string.IsNullOrEmpty(reportTo)) && reportTo.ToLower() == "vorletztes abgeschlossenes quartal") { DateTime dto = LastDayOfPreviousMonth(DateTime.Today); if (dto.Month > 9) { DateTime from = new DateTime(dto.Year, 4, 1); DateTime to = new DateTime(dto.Year, 6, 30); return new ReportRange(from, to); } if (dto.Month > 6) { DateTime from = new DateTime(dto.Year, 1, 1); DateTime to = new DateTime(dto.Year, 3, 31); return new ReportRange(from, to); } if (dto.Month > 3) { DateTime from = new DateTime(dto.Year -1 , 10, 1); DateTime to = new DateTime(dto.Year -1, 12, 31); return new ReportRange(from, to); } if (dto.Month <= 3) { DateTime from = new DateTime(dto.Year - 1, 7, 1); DateTime to = new DateTime(dto.Year - 1, 9, 30); return new ReportRange(from, to); } return null; } if ((!string.IsNullOrEmpty(reportTo)) && reportTo.ToLower() == "letztes abgeschlossenes halbjahr") { DateTime dto = LastDayOfPreviousMonth(DateTime.Today); if (dto.Month > 6) { DateTime from = new DateTime(dto.Year, 1, 1); DateTime to = new DateTime(dto.Year, 6, 30); return new ReportRange(from, to); } else { DateTime from = new DateTime(dto.Year - 1, 7, 1); DateTime to = new DateTime(dto.Year - 1, 12, 31); return new ReportRange(from, to); } } if ((!string.IsNullOrEmpty(reportTo)) && reportTo.ToLower() == "vorletztes abgeschlossenes halbjahr") { DateTime dto = LastDayOfPreviousMonth(DateTime.Today); if (dto.Month > 6) { DateTime from = new DateTime(dto.Year -1, 7, 1); DateTime to = new DateTime(dto.Year -1, 12, 31); return new ReportRange(from, to); } else { DateTime from = new DateTime(dto.Year - 1, 1, 1); DateTime to = new DateTime(dto.Year - 1, 6, 30); return new ReportRange(from, to); } } if ((!string.IsNullOrEmpty(reportTo)) && reportTo.ToLower() == "letztes abgeschlossenes jahr") { DateTime from = new DateTime(DateTime.Today.Year - 1, 1, 1); DateTime to = new DateTime(DateTime.Today.Year - 1, 12, 31); return new ReportRange(from, to); } if ((!string.IsNullOrEmpty(reportTo)) && reportTo.ToLower() == "vorletztes abgeschlossenes jahr") { DateTime from = new DateTime(DateTime.Today.Year - 2, 1, 1); DateTime to = new DateTime(DateTime.Today.Year - 2, 12, 31); return new ReportRange(from, to); } // Zeitraum if ((!string.IsNullOrEmpty(reportFrom)) && reportFrom.ToLower() == "zeitraum" && (!string.IsNullOrEmpty(reportFromRange)) && (reportFromRange.ToLower() == "jahr(e)" || reportFromRange.ToLower() == "monat(e)" || reportFromRange.ToLower() == "woche(n)" || reportFromRange.ToLower() == "tag(e)") && (!string.IsNullOrEmpty(reportTo)) && (reportTo.ToLower() == "tag heute" || reportTo.ToLower() == "festes datum") ) { DateTime to = DateTime.Today; DateTime from = DateTime.Today; if (reportTo.ToLower() == "festes datum") to = reportDateTo; if (reportFromRange.ToLower() == "jahr(e)") from = from.AddYears(-reportFromRange_int); if (reportFromRange.ToLower() == "monat(e)") from = from.AddMonths(-reportFromRange_int); if (reportFromRange.ToLower() == "woche(n)") from = from.AddDays(-(reportFromRange_int * 7)); if (reportFromRange.ToLower() == "tag(n)") from = from.AddDays(-(reportFromRange_int)); return new ReportRange(from, to); } return null; } public static string GetReportRangeText(string reportFrom, string reportTo, string reportFromRange, int reportFromRange_int, DateTime reportDateFrom, DateTime reportDateTo) { if (string.IsNullOrEmpty(reportFrom) && string.IsNullOrEmpty(reportTo)) return string.Empty; // Tag heute if ((!string.IsNullOrEmpty(reportFrom)) && reportFrom.ToLower() == "tag heute" && reportTo.ToLower() == "tag heute") return "Tag heute - Tag heute"; // festes Datum ist gesetzt if ((!string.IsNullOrEmpty(reportFrom)) && reportFrom.ToLower() == "festes datum" && (!string.IsNullOrEmpty(reportTo)) && reportTo.ToLower() == "festes datum" && reportDateFrom != DateTime.MinValue && reportDateTo != DateTime.MinValue) { // unsinnig eingabe if (reportDateFrom > reportDateTo) return string.Empty; return reportDateFrom.ToShortDateString() + "-" + reportDateTo.ToShortDateString(); } // Kombination aus Tag heute und festes Datum if ((!string.IsNullOrEmpty(reportFrom)) && reportFrom.ToLower() == "festes datum" && (!string.IsNullOrEmpty(reportTo)) && reportTo.ToLower() == "tag heute" && reportDateFrom != DateTime.MinValue) { if (reportDateFrom > DateTime.Today) return null; return reportDateFrom.ToShortDateString() + "- Tag heute"; } if ((!string.IsNullOrEmpty(reportFrom)) && reportFrom.ToLower() == "tag heute" && (!string.IsNullOrEmpty(reportTo)) && reportTo.ToLower() == "festes datum" && reportDateTo != DateTime.MinValue) { if (DateTime.Today > reportDateTo) return null; return "Tag heute - " + reportDateTo.ToShortDateString(); } // abgeschlossene Zeiträume if ((!string.IsNullOrEmpty(reportTo)) && reportTo.ToLower() == "letzter abgeschlossener monat") { return "letzter abgeschlossener Monat"; } if ((!string.IsNullOrEmpty(reportTo)) && reportTo.ToLower() == "letztes abgeschlossenes quartal") { return "letztes abgeschlossenes Quartal"; } if ((!string.IsNullOrEmpty(reportTo)) && reportTo.ToLower() == "letztes abgeschlossenes halbjahr") { return "letztes abgeschlossenes Halbjahr"; } if ((!string.IsNullOrEmpty(reportTo)) && reportTo.ToLower() == "letztes abgeschlossenes jahr") { return "letztes abgeschlossenes Jahr"; } if ((!string.IsNullOrEmpty(reportTo)) && reportTo.ToLower() == "vorletzter abgeschlossener monat") { return "vorletzter abgeschlossener monat"; } if ((!string.IsNullOrEmpty(reportTo)) && reportTo.ToLower() == "vorletztes abgeschlossenes quartal") { return "vorletztes abgeschlossenes quartal"; } if ((!string.IsNullOrEmpty(reportTo)) && reportTo.ToLower() == "vorletztes abgeschlossenes halbjahr") { return "vorletztes abgeschlossenes halbjahr"; } if ((!string.IsNullOrEmpty(reportTo)) && reportTo.ToLower() == "vorletztes abgeschlossenes jahr") { return "vorletztes abgeschlossenes jahr"; } // Zeitraum if ((!string.IsNullOrEmpty(reportFrom)) && reportFrom.ToLower() == "zeitraum" && (!string.IsNullOrEmpty(reportFromRange)) && (reportFromRange.ToLower() == "jahr(e)" || reportFromRange.ToLower() == "monat(e)" || reportFromRange.ToLower() == "woche(n)" || reportFromRange.ToLower() == "tag(e)") && (!string.IsNullOrEmpty(reportTo)) && (reportTo.ToLower() == "tag heute" || reportTo.ToLower() == "festes datum") ) { string r = "Tag heute"; if (reportTo.ToLower() == "festes datum") r = reportDateTo.ToShortDateString(); if (reportFromRange.ToLower() == "jahr(e)") r += " - " + reportFromRange_int + " Jahre(e)"; if (reportFromRange.ToLower() == "monat(e)") r += " - " + reportFromRange_int + " Monat(e)"; if (reportFromRange.ToLower() == "woche(n)") r += " - " + reportFromRange_int + " Woche(n)"; if (reportFromRange.ToLower() == "tag(n)") r += " - " + reportFromRange_int + " Tag(e)"; return r; } return string.Empty; } public static DateTime LastDayOfPreviousMonth(DateTime dto) { return dto.AddDays(-dto.Day); } public static DateTime LastDayOfPrePreviousMonth(DateTime dto) { return ((FirstDayOfPrePreviousMonth(dto)).AddMonths(1)).AddDays(-1); } public static DateTime FirstDayOfPrePreviousMonth(DateTime dto) { return (FirstDayOfPreviousMonth(dto)).AddMonths(-1); } public static DateTime FirstDayOfPreviousMonth(DateTime dto) { DateTime lastDayPrevMonth = dto.AddDays(-dto.Day); return new DateTime(lastDayPrevMonth.Year, lastDayPrevMonth.Month, 1); } } public class ReportRange { public DateTime From = DateTime.MinValue; public DateTime To = DateTime.MinValue; public ReportRange(DateTime from, DateTime to) { From = from; To = to; } } }
24a74b587ea83b4887d89a60bd6d892248cddb74
C#
FredrikLundvall/RealtimeRaytrace
/RealtimeRaytrace/Rendering/Texture/SolidColorMap.cs
2.75
3
using System; using Microsoft.Xna.Framework; namespace RealtimeRaytrace { public class SolidColorMap : ITextureMap { protected readonly Color _color; public SolidColorMap(Color color) { _color = color; } public Color GetColorFromDirection(Vector3 direction, bool flipU = false, bool flipV = false, float offsetU = 0, float offsetV = 0, float scaleU = 0, float scaleV = 0) { return _color; } } }
46b812592c9234b47e22e096d00e97acc49ade9c
C#
kamranAeff/WebApiSolution
/Lesson01/Binders/ColorTypeConverter.cs
3.15625
3
using Lesson01.Models; using Lesson01.Utils; using System; using System.ComponentModel; using System.Globalization; namespace Lesson01.Binders { /// <summary> /// TypeConverter bizə simple tipləri complex tiplərə çevirmək imkanı verir /// Yəni string olaraq gələn 123,12,13 tipli RGB dəyərini ColorType-a çevirməyi bu üsulla yerinə yetirəcəyik. /// </summary> public class ColorTypeConverter : TypeConverter { public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { if (sourceType==typeof(string)) return true; return base.CanConvertFrom(context, sourceType); } public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { if (value is string) { var parameters = value.ToString().Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries); byte red = 0, green = 0, blue = 0; if (Byte.TryParse(parameters.Get(0), out red) && Byte.TryParse(parameters.Get(1), out green) && Byte.TryParse(parameters.Get(2), out blue)) return new Color { Red = red, Blue = blue, Green = green }; } if (context != null) return base.ConvertFrom(context, culture, value); else return null; } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if (typeof(string) == destinationType) { var color = (Color)value; return $"{color.Red},{color.Green},{color.Blue}"; } return base.ConvertTo(context, culture, value, destinationType); } } }
58cbb036892ac629d4d1006ab4d3f7f4e30b742c
C#
maheshkutty/crimeregistration
/civilian/reg.aspx.cs
2.578125
3
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data; using System.Data.SqlClient; using System.Web.UI; using System.Web.UI.WebControls; namespace police_and_automation { public partial class reg : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { //Label1.Text = "hi"; } protected void Button1_Click(object sender, EventArgs e) { try { SqlConnection con = new SqlConnection(); SqlCommand cmd = new SqlCommand(); //to estblish connection with database con.ConnectionString = @"Data Source=DESKTOP-R083DVH\SQLEXPRESS;Initial Catalog=police;Integrated Security=True"; con.Open(); cmd.Connection = con; //Query to database cmd.CommandText = "select email from jass where email=@email1"; SqlDataReader reader; cmd.Parameters.AddWithValue("@email1", TextBox8.Text); reader = cmd.ExecuteReader(); if (reader.Read()) { //Checking for existing user Label1.Visible = true; Label1.Text = "you already registered"; } else { con.Close(); con.Open(); cmd.CommandText = "insert into jass (cfname,clname,gender,email,pass,bname,local,street,pincode,station,dob,phone)" + "values(@cfname,@clname,@gender,@email,@pass,@bname,@local,@street,@pincode,@station,@dob,@phone)"; cmd.Parameters.AddWithValue("@cfname", TextBox1.Text); cmd.Parameters.AddWithValue("@clname", TextBox2.Text); cmd.Parameters.AddWithValue("@gender", RadioButtonList1.Text); cmd.Parameters.AddWithValue("@bname", TextBox3.Text); cmd.Parameters.AddWithValue("@street", TextBox4.Text); cmd.Parameters.AddWithValue("@local", TextBox5.Text); cmd.Parameters.AddWithValue("@station", TextBox6.Text); cmd.Parameters.AddWithValue("@pincode", Convert.ToInt32(TextBox7.Text)); cmd.Parameters.AddWithValue("@email", TextBox8.Text); cmd.Parameters.AddWithValue("@pass", TextBox9.Text); cmd.Parameters.AddWithValue("@dob", TextBox10.Text); cmd.Parameters.AddWithValue("@phone",TextBox11.Text); cmd.ExecuteNonQuery(); //HyperLink1.Visible = true; con.Close(); Label1.Visible = true; Label1.Text = "you are registered"; } } catch (Exception ex) { Label2.Text =ex.Message; } } protected void Button1_Click1(object sender, EventArgs e) { } protected void date_changed(object sender, EventArgs e) { string a = TextBox10.Text; DateTime d = new DateTime(); d = Convert.ToDateTime(a); DateTime d1 = new DateTime(); d1 = DateTime.Now; //comapre current date with civilian date of birth int c = DateTime.Compare(d, d1); if (c < 0 || c == 0) { Label3.Visible = false; } else { TextBox5.Text = null; Label3.Visible = true; Label3.Text = "date should not exceed current date"; } } protected void phone_checked(object sender, EventArgs e) { string a = TextBox11.Text; char[] b = a.ToCharArray(); // int c = Convert.ToInt32(b[0]); if (b[0].Equals('0')) { TextBox11.Text = null; Label4.Visible = true; Label4.Text = "Number Should not start with zero"; } Label4.Visible = false; } } }
5eb62c39dd8c88575af8745a1be6eab6ba18e58f
C#
MarceloBritoWD/csharp-first-steps
/Command-Line-Project/OdontologyClinic/Program.cs
3.28125
3
using System; using System.Collections.Generic; using OdontologyClinic.Model; namespace OdontologyClinic { class MainClass { private static Clinic clinic = new Clinic(); public static void Main(string[] args) { do { Console.Clear(); Console.WriteLine("Welcome to the greatest odontology clinic system!"); Console.WriteLine("Please, select what you wanna do:"); Console.WriteLine("1 - Register a new patient"); Console.WriteLine("2 - List all patients"); Console.WriteLine("3 - Register a procedure"); Console.WriteLine("4 - List all procedures"); Console.WriteLine("5 - Perform a medical care"); Console.WriteLine("6 - List all medical cares"); Console.WriteLine("7 - Exit"); string valuereaded = Console.ReadLine(); switch (int.Parse(valuereaded)) { case 1: Console.WriteLine("You selected the option 1, lets proced with that:"); ResgisterPatient(); break; case 2: Console.WriteLine("You selected the option 2, lets proced with that:"); ListAllPatients(); break; case 3: Console.WriteLine("You selected the option 3, lets proced with that:"); ResgisterProcedure(); break; case 4: Console.WriteLine("You selected the option 3, lets proced with that:"); ListAllProcedures(); break; case 5: Console.WriteLine("You selected the option 4, lets proced with that:"); performMedicalCare(); break; case 6: Console.WriteLine("You selected the option 3, lets proced with that:"); ListAllMedicalCare(); break; case 7: Environment.Exit(0); break; } Console.ReadKey(); } while (true); } private static void ResgisterPatient() { Console.WriteLine("### Insert the name of the patient ###"); string name = Console.ReadLine(); clinic.ResgisterPatient(new Patient(name, new DateTime(1995, 5, 3))); Console.WriteLine("Patient registered!"); } private static void ListAllPatients() { Console.WriteLine("#### Listing all the patients ####"); List<Patient> patients = clinic.GetPatients(); int index = 1; patients.ForEach((Patient obj) => { Console.WriteLine(index + " - " + obj.Name); index++; }); } private static void ListAllProcedures() { Console.WriteLine("#### Listing all the procedures ####"); List<Procedure> procedures = clinic.GetProcedures(); int index = 1; procedures.ForEach((Procedure obj) => { Console.WriteLine(index + " - " + obj.Name); index++; }); } private static void ListAllMedicalCare() { Console.WriteLine("#### Listing all the medical cares ####"); List<MedicalCare> mcs = clinic.GetMedicalCares(); mcs.ForEach((MedicalCare obj) => { Console.WriteLine("Patient Name - " + obj.Patient.Name); Console.WriteLine("Procedure Name - " + obj.Procedure.Name); Console.WriteLine("Date - " + obj.Date); }); } private static void ResgisterProcedure() { Console.WriteLine("### Insert the name of the procedure ###"); string name = Console.ReadLine(); double price = double.Parse(Console.ReadLine()); clinic.ResgisterProcedure(new Procedure(name, price)); Console.WriteLine("Procedure registered!"); } private static void performMedicalCare() { ListAllPatients(); ListAllProcedures(); MedicalCare medicalCare = new MedicalCare(); Console.WriteLine("### Insert the id of the Patient ###"); int patientId = int.Parse(Console.ReadLine()); int count = 1; clinic.GetPatients().ForEach((item) => { if(count == patientId) { medicalCare.Patient = item; } count++; }); Console.WriteLine("### Patient added to the medical care: " + medicalCare.Patient.Name + " ###"); Console.WriteLine("### Insert the id of the Procedure ###"); int procedureId = int.Parse(Console.ReadLine()); int count2 = 1; clinic.GetProcedures().ForEach((item) => { if (count2 == patientId) { medicalCare.Procedure = item; } count2++; }); Console.WriteLine("### Procedure added to the medical care " + medicalCare.Procedure.Name + " ###"); medicalCare.Date = new DateTime(); clinic.MedicalCares.Add(medicalCare); } } }
4485fb09e0b936d792e07da0a978eed3df2d2eba
C#
WarpedDemon/BasicAPI
/EndProject/EndProject/EndProject/Weather.cs
3.015625
3
using System; using System.Collections.Generic; using System.Text; using System.Net; using System.Xml; namespace EndProject { public class WeatherAPI { public WeatherAPI(string city) { SetCurrentURL(city); xmlDocument = GetXML(CurrentURL); } public float GetTemp() { XmlNode temp = xmlDocument.SelectSingleNode("//temperature"); XmlAttribute value = temp.Attributes["value"]; string temp_string = value.Value; return float.Parse(temp_string); } private const string APIKEY = "d6e6f945cec7e220a39ed368194db3e8"; private string CurrentURL; private XmlDocument xmlDocument; private void SetCurrentURL(string location) { CurrentURL = "http://api.openweathermap.org/data/2.5/weather?q=" + location + "&mode=xml&units=metric&APPID=" + APIKEY; } private XmlDocument GetXML(string CurrentURL) { using (WebClient client = new WebClient()) { string xmlContent = client.DownloadString(CurrentURL); XmlDocument xmlDocument = new XmlDocument(); xmlDocument.LoadXml(xmlContent); return xmlDocument; } } } public class WeatherData { public WeatherData(string City) { city = City; } private string city; private float temp; private float tempMax; private float tempMin; public void CheckWeather() { WeatherAPI DataAPI = new WeatherAPI(City); temp = DataAPI.GetTemp(); } public string City { get => city; set => city = value; } public float Temp { get => temp; set => temp = value; } public float TempMax { get => tempMax; set => tempMax = value; } public float TempMin { get => tempMin; set => tempMin = value; } } }
821cd9929affa332a369d0671ec8db292ec66a95
C#
ByteDev/ByteDev.Reflection
/src/ByteDev.Reflection/TypeIsExtensions.cs
3.140625
3
using System; using System.Reflection; namespace ByteDev.Reflection { /// <summary> /// Extension methods for <see cref="T:System.Type" />. /// </summary> public static class TypeIsExtensions { /// <summary> /// Indicates if a type is in a particular namespace hierarchy. /// </summary> /// <param name="source">The type to perform the operation on.</param> /// <param name="namespace">The namespace.</param> /// <returns>True if the type is in the namespace hierarchy; otherwise false.</returns> public static bool IsInNamespace(this Type source, string @namespace) { if (source == null) throw new ArgumentNullException(nameof(source)); if (string.IsNullOrEmpty(@namespace)) throw new ArgumentException("Namespace was null or empty.", nameof(@namespace)); var typeNamespace = source.Namespace ?? string.Empty; if (@namespace == typeNamespace) return true; if (@namespace.Length > typeNamespace.Length) return false; var typeSubNamespace = typeNamespace.Substring(0, @namespace.Length); if (typeSubNamespace == @namespace) { return typeNamespace[@namespace.Length] == '.'; } return false; } /// <summary> /// Indicates if a type can be set to null. /// </summary> /// <param name="source">The type to perform the operation on.</param> /// <returns>True the type can be set to null; otherwise false.</returns> public static bool IsNullable(this Type source) { if (source == null) throw new ArgumentNullException(nameof(source)); if (!source.IsValueType) return true; return Nullable.GetUnderlyingType(source) != null; } /// <summary> /// Indicates if a type is a test class. Determined by the class's /// name suffix. /// </summary> /// <param name="source">The type to perform the operation on.</param> /// <returns>True if the class is a test class; otherwise false.</returns> public static bool IsTestClass(this Type source) { if (source == null) throw new ArgumentNullException(nameof(source)); var typeInfo = source.GetTypeInfo(); return typeInfo.IsClass && (typeInfo.Name.EndsWith("Tests") || typeInfo.Name.EndsWith("Test")); } } }
9350a0f7188a508672c6cf25aed7150ad1b0aaf8
C#
RonnyWyss/VPA_Manager
/Verwaltung/Verwaltung/ViewModels/CreateCustomerViewModel.cs
2.578125
3
using System; using System.Windows; using Prism.Commands; using Prism.Mvvm; namespace Verwaltung.ViewModels { public class CreateCustomerViewModel : BindableBase { private readonly Action _navigateBack; private string _benutzer; private DateTime _erfassungsdatum; private string _hausnummer; private string _kundenname; private string _ort; private string _plz; private string _strasse; public CreateCustomerViewModel(string benutzername) { Benutzer = benutzername; Erfassungsdatum = DateTime.Now; CmdSpeichern = new DelegateCommand(OnCmdSpeichern); } public string Benutzer { get => _benutzer; set => SetProperty(ref _benutzer, value); } public string Kundenname { get => _kundenname; set => SetProperty(ref _kundenname, value); } public string Strasse { get => _strasse; set => SetProperty(ref _strasse, value); } public string Hausnummer { get => _hausnummer; set => SetProperty(ref _hausnummer, value); } public string Plz { get => _plz; set => SetProperty(ref _plz, value); } public string Ort { get => _ort; set => SetProperty(ref _ort, value); } public DateTime Erfassungsdatum { get => _erfassungsdatum; set => SetProperty(ref _erfassungsdatum, value); } public DelegateCommand CmdSpeichern { get; } private void OnCmdSpeichern() { if (CheckRequiredFields()) { MessageBox.Show("Navigiert Zurück"); _navigateBack(); } else { MessageBox.Show("Es müssen alle Pflichtfelder ausgewählt werden"); } } private bool CheckRequiredFields() { var kundenname = !string.IsNullOrEmpty(Kundenname); var strasse = !string.IsNullOrEmpty(Strasse); var hausnummer = !string.IsNullOrEmpty(Hausnummer); var plz = !string.IsNullOrEmpty(Plz); var ort = !string.IsNullOrEmpty(Ort); return kundenname && strasse && hausnummer && plz && ort; } } }