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
d2fbd9bd846bd2745bd6c344c404ee98e6a70f1a
C#
lihini223/C-Sharp-Programming
/CRUD-APP/CRUD_APP/SignUp.cs
2.6875
3
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace CRUD_APP { public partial class SignUp : Form { public SignUp() { InitializeComponent(); } private void label1_Click(object sender, EventArgs e) { } private void btnCancel_Click(object sender, EventArgs e) { txtFname.Text = null; txtLname.Text = null; txtUname.Text = null; txtPassword.Text = null; txtAge.Text = null; } private void btnhome_Click(object sender, EventArgs e) { Home home = new Home(); home.Show(); this.Hide(); } private void txtFname_TextChanged(object sender, EventArgs e) { } string FirstName, LastName, UserName, Password; int Age; private void btnSignUp_Click(object sender, EventArgs e) { FirstName = txtFname.Text; LastName = txtLname.Text; UserName = txtUname.Text; Password = txtPassword.Text; Age = int.Parse(txtAge.Text); SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=E:\CRUD APP\CRUD_APP\UserData.mdf;Integrated Security=True;Connect Timeout=30"); string qry = "Insert Into SignUp Values('"+FirstName+"','"+LastName+"','"+UserName+"','"+Password+"','"+Age+"');"; SqlCommand cmd = new SqlCommand(qry,con); try { con.Open(); cmd.ExecuteNonQuery(); MessageBox.Show("Data Inserted Successfully!"); } catch(SqlException sqlex) { MessageBox.Show("" + sqlex); } } } }
5f9fc4e35e7077ea59df8241615488a7e1afce13
C#
ProCodersPtyLtd/MasterDetailsDataEntry
/Platz.ObjectBuilder/Engine/FileProjectLoader.cs
2.5625
3
using Platz.ObjectBuilder; using Platz.SqlForms; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.Json; using System.Threading.Tasks; namespace Platz.ObjectBuilder.Engine { public class FileProjectLoader : IProjectLoader { public List<string> GetFolders(string location) { if (!Directory.Exists(location)) { Directory.CreateDirectory(location); } var result = Directory.GetDirectories(location).ToList(); return result; } /// <summary> /// /// </summary> /// <param name="name">full path to folder where project file *.project.json located</param> /// <returns></returns> public StoreProject Load(string folderName) { var result = new StoreProject(); result.Schemas = new Dictionary<string, StoreSchema>(); result.SchemaMigrations = new Dictionary<string, StoreSchemaMigrations>(); result.Queries = new Dictionary<string, StoreQuery>(); result.Forms = new Dictionary<string, StoreForm>(); var dir = folderName; if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } var name = Directory.GetFiles(dir, "*.project.json").FirstOrDefault(); if (name == null) { return result; } var projectJson = File.ReadAllText(name); result.Name = Path.GetFileName(name).Replace(".project.json", ""); result.Settings = JsonSerializer.Deserialize<StoreProjectSettings>(projectJson); var files = Directory.GetFiles(dir, "*.schema.json"); foreach (var file in files) { var json = File.ReadAllText(file); var schema = JsonSerializer.Deserialize<StoreSchema>(json); result.Schemas.Add(schema.Name, schema); var migrationFile = file.Substring(0, file.Length - ".schema.json".Length) + ".schema.migrations.json"; json = File.ReadAllText(migrationFile); var migration = JsonSerializer.Deserialize<StoreSchemaMigrations>(json); result.SchemaMigrations.Add(schema.Name, migration); } files = Directory.GetFiles(dir, "*.query.json"); foreach (var file in files) { var json = File.ReadAllText(file); var query = JsonSerializer.Deserialize<StoreQuery>(json); result.Queries.Add(query.Name, query); } files = Directory.GetFiles(dir, "*.form.json"); foreach (var file in files) { var json = File.ReadAllText(file); var form = JsonSerializer.Deserialize<StoreForm>(json); result.Forms.Add(form.Name, form); } return result; } public void SaveAll(StoreProject project, string location, List<ObjectRenameItem> renames) { SaveFile(location, project.Name, project.Settings, StoreProjectItemType.Project); // forms foreach (var form in project.Forms.Values) { SaveFile(location, form.Name, form, StoreProjectItemType.Form); } ClearRenamed(project, location, renames); } private void SaveFile(string location, string name, object data, StoreProjectItemType type) { if (string.IsNullOrWhiteSpace(name)) { throw new Exception("File cannot have empty name"); } var file = name + "." + GetProjectItemExtension(type); file = Path.Combine(location, file); var json = JsonSerializer.Serialize(data, new JsonSerializerOptions { WriteIndented = true }); File.WriteAllText(file, json); } private void ClearRenamed(StoreProject project, string location, List<ObjectRenameItem> renames) { foreach (var rn in renames) { var name = rn.OrignalName + "." + GetProjectItemExtension(rn.Type); var fileName = Path.Combine(location, name); if (File.Exists(fileName)) { File.Delete(fileName); } } } private string GetProjectItemExtension(StoreProjectItemType type) { switch (type) { case StoreProjectItemType.Project: return "project.json"; case StoreProjectItemType.Form: return "form.json"; case StoreProjectItemType.Query: return "query.json"; case StoreProjectItemType.Schema: return "schema.json"; } return ""; } public StoreSchema LoadSchema(string folderName, string name) { throw new NotImplementedException(); } public StoreQuery LoadQuery(string folderName, string name) { throw new NotImplementedException(); } } }
a0c6a0b10711f0883b6238413871dbb196de5bf0
C#
Serpen/Serpen.Uni
/Automat/ContextFree/PDAConfig.cs
2.59375
3
namespace Serpen.Uni.Automat.ContextFree { public class PDAConfig : IConfig { public uint State { get; } public string word { get; } public char[] Stack { get; } public PDAConfig Origin { get; } public string OriginPath() { var pcfg = this; var sw = new System.Text.StringBuilder(); sw.Append($"[{pcfg.ToString()}]"); while (pcfg.Origin != null) { pcfg = pcfg.Origin; sw.Append($"<-[{pcfg.ToString()}]"); } return sw.ToString(); } public PDAConfig(uint q, string w, char[] stack, PDAConfig origin) { this.State = q; this.word = w; this.Stack = stack; this.Origin = origin; } public override string ToString() => $"({State},'{word}','{string.Join("", Stack)}')"; public override bool Equals(object obj) => (obj is PDAConfig pobj) && string.Join(',', this.Stack)==string.Join(',', pobj.Stack) && this.State==pobj.State && this.word==pobj.word; public override int GetHashCode() => ToString().GetHashCode(); } }
23b195f4bf4393b4dd6ef14acbcea5f3e1e98d48
C#
Darius-D/AllFunAndGamesMathEdition
/AllFunAndGamesMathEdition/ConsoleApp.cs
3.71875
4
using System; using System.Runtime.InteropServices; namespace AllFunAndGamesMathEdition { public static class ConsoleApp { public static void StartUp() { MainScreen(); } private static void MainScreen() { Console.WriteLine("\nWelcome to All Fun and Games: Math Edition!\n"); Console.WriteLine("Please choose one of the selections below.\n"); Console.WriteLine("1. Play with Addition"); Console.WriteLine("2. Play with Subtraction"); Console.WriteLine("3. Play with Multiplication"); Console.WriteLine("4. Play with Division"); Console.WriteLine("5. Exit the Game."); Console.WriteLine("------------------------------------------------------ "); Console.Write("What game would you like to play?: "); try { var selection = int.Parse(Console.ReadLine() ?? "0"); switch (selection) { case 1: AdditionGame(); break; case 2: SubtractionGame(); break; case 3: MultiplicationGame(); break; case 4: DivisionGame(); break; case 5: Console.WriteLine("This game was created by Darius Dubose, I hope you enjoyed playing. See you next time!"); Environment.Exit(0); break; } MainScreen(); } catch (Exception) { Console.WriteLine("\nBe sure to use the menu numbers to make a selection.\n"); MainScreen(); } } private static void AdditionGame() { Console.WriteLine("You have selected to Play with Addition!"); Console.Write("Please choose the number of questions you would like to do: "); var questionCount = int.Parse(Console.ReadLine() ?? "0"); Console.WriteLine($"Great, {questionCount} questions! Let the games begin!\n"); var rdm = new Random(); var count = 1; while (questionCount > 0) { var valueOne = rdm.Next(0, 101); var valueTwo = rdm.Next(0, 101); int userAnswer; Console.Write($"\nQuestion {count}! If you had {valueOne} baby yoda dolls, but you won {valueTwo} more. \nHow many baby Yoda dolls do you now have? "); try { userAnswer = int.Parse(Console.ReadLine()); } catch (Exception) { Console.WriteLine("\nplease enter a valid Integer value: \n"); userAnswer = int.Parse(Console.ReadLine()); } var correctAnswer = valueOne + valueTwo; if (userAnswer == correctAnswer) { Console.WriteLine($"\nCorrect, the answer was {correctAnswer}! Way to Go!"); } else { Console.WriteLine($"\nSorry, the correct answer was {correctAnswer}. You've got this!"); } questionCount--; count++; } } private static void SubtractionGame() { Console.WriteLine("You have selected to Play with Addition!"); Console.Write("Please choose the number of questions you would like to do: "); var questionCount = int.Parse(Console.ReadLine() ?? "0"); Console.WriteLine($"Great, {questionCount} questions! Let the games begin!\n"); var rdm = new Random(); var count = 1; while (questionCount > 0) { var valueOne = rdm.Next(0, 101); var valueTwo = rdm.Next(0, 101); int userAnswer; if (valueOne < valueTwo) { var temp = valueOne; valueOne = valueTwo; valueTwo = temp; } Console.Write($"\nQuestion {count}! If you had {valueOne} baby Obi Wan Kenobi dolls, but you gave away {valueTwo} to friends and family. \nHow many baby Obi Wan Kenobi dolls do you have left? "); try { userAnswer = int.Parse(Console.ReadLine()); } catch (Exception) { Console.WriteLine("\nplease enter a valid Integer value: \n"); userAnswer = int.Parse(Console.ReadLine() ?? "0"); } var correctAnswer = valueOne - valueTwo; if (userAnswer == correctAnswer) { Console.WriteLine($"\nCorrect, the answer was {correctAnswer}! Way to Go!"); } else { Console.WriteLine($"\nSorry, the correct answer was {correctAnswer}. You've got this!"); } questionCount--; count++; } } private static void DivisionGame() { Console.WriteLine("You have selected to Play with Division, This will be fun!"); Console.Write("Please choose the number of questions you would like to do: "); var questionCount = int.Parse(Console.ReadLine() ?? "0"); Console.WriteLine($"Great, {questionCount} questions! Let the games begin!\n"); var rdm = new Random(); var count = 1; while (questionCount > 0) { var valueOne = rdm.Next(0, 101); var valueTwo = rdm.Next(0, 101); double userAnswer; if (valueOne < valueTwo) { var temp = valueOne; valueOne = valueTwo; valueTwo = temp; } Console.Write($"\nQuestion {count}! If you had {valueOne} bags of skittles, but you have {valueTwo} friends to share with. \nHow many bags of skittles can each friend have rounded to the nearest hundredth? "); try { userAnswer = double.Parse(Console.ReadLine()); } catch (Exception) { Console.WriteLine("\nplease enter a valid Integer value: \n"); userAnswer = double.Parse(Console.ReadLine() ?? "0"); } var correctAnswer = Math.Round((double)valueOne / valueTwo, 2); if (userAnswer == correctAnswer) { Console.WriteLine($"\nCorrect, the answer was {correctAnswer}! Way to Go!"); } else { Console.WriteLine($"\nSorry, the correct answer was {correctAnswer}. You've will get the next!"); } questionCount--; count++; } } private static void MultiplicationGame() { Console.WriteLine("You have selected to Play with Multiplication!"); Console.Write("Please choose the number of questions you would like to do: "); var questionCount = int.Parse(Console.ReadLine() ?? "0"); Console.WriteLine($"Great, {questionCount} questions! Let the games begin!\n"); var rdm = new Random(); var count = 1; while (questionCount > 0) { var valueOne = rdm.Next(0, 101); var valueTwo = rdm.Next(0, 101); int userAnswer; Console.Write($"\nQuestion {count}! If you had {valueOne} bags of silver and gold, but you a genie gave you {valueTwo} times more! \nHow many bags do you now have? "); try { userAnswer = int.Parse(Console.ReadLine()); } catch (Exception) { Console.WriteLine("\nplease enter a valid Integer value: \n"); userAnswer = int.Parse(Console.ReadLine() ?? "0"); } var correctAnswer = valueOne * valueTwo; if (userAnswer == correctAnswer) { Console.WriteLine($"\nCorrect, the answer was {correctAnswer}! Way to Go!"); } else { Console.WriteLine($"\nSorry, the correct answer was {correctAnswer}. You've got this!"); } questionCount--; count++; } } } }
0246e69f512ed10d174606ef7a37a4d3d16efa2c
C#
VitorNeilAvelino/ImpactaCSharpAcessoDados
/Roteiro/ImpactaCSharp2/CSharp2.Capitulo10.Wpf.Produtos/Converters/VisibilidadePedidoConverter.cs
2.640625
3
using System; using System.Windows.Data; namespace CSharp2.Capitulo10.Wpf.Produtos.Converters { public class VisibilidadePedidoConverter : IMultiValueConverter { public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture) { try { var podeVisualizar = (System.Convert.ToInt32(values[0]) == 1) && System.Convert.ToBoolean(values[1]); return podeVisualizar ? System.Windows.Visibility.Visible : System.Windows.Visibility.Hidden; } catch { return System.Windows.Visibility.Visible; } } public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture) { throw new NotSupportedException("Not implemented"); } } }
a656cb86119ab3ade1ebf0f05b7a11c61c6850d2
C#
deyantodorov/TelerikAcademy
/Object-Oriented-Programming/FinalExam2015/2. Army of Creatures_Description/Source/ArmyOfCreatures/Extended/Creatures/AncientBehemoth.cs
3.015625
3
namespace ArmyOfCreatures.Extended.Creatures { using ArmyOfCreatures.Logic.Creatures; using ArmyOfCreatures.Logic.Specialties; public class AncientBehemoth : Creature { private const int BaseDefense = 19; private const int BaseAttack = 19; private const int BaseHealthPoints = 300; private const int BaseDamage = 40; private const int BaseReduceEnemyDefenseByPercentage = 80; private const int BaseDoubleDefenseWhenDefending = 5; // with attack 19, defense 19, damage 40, health points 300 and has the following specialties public AncientBehemoth() : base(AncientBehemoth.BaseAttack, AncientBehemoth.BaseDefense, AncientBehemoth.BaseHealthPoints, AncientBehemoth.BaseDamage) { this.AddSpecialty(new ReduceEnemyDefenseByPercentage(AncientBehemoth.BaseReduceEnemyDefenseByPercentage)); this.AddSpecialty(new DoubleDefenseWhenDefending(AncientBehemoth.BaseDoubleDefenseWhenDefending)); } } }
fcca52adb6790ff8d3fd31291b96459702dd87ec
C#
jiaxy/CSharpCourse
/codes/ch03/PersonStudent/PersonStudent.cs
3.53125
4
using System; class Person { public string name; //ֶ public int age; public virtual void sayHello(){ //巽עvirtual Console.WriteLine("Hello! My name is " + name ); } public virtual void sayHello( Person another ){ // Console.WriteLine("Hello," + another.name + "! My name is " + name ); } public bool isOlderThan(int anAge){ //巽 return (age > anAge); } public Person(string n, int a){ //췽 name = n; age = a; } public Person(string n){ //췽 name = n; age = -1; } public Person():this("", 0 )//췽 { } } class Student : Person // { public string school; //ӵֶ public int score = 0; public bool isGoodStudent(){ //ӵķ return score>=90; } public override void sayHello(){ //дͬ base.sayHello(); Console.WriteLine( "My school is " + school ); } public void sayHello( Student another ){ //ط Console.WriteLine("Hi!"); if( school == another.school ) Console.WriteLine(" Shoolmates "); } public void testThisSuper(){ int a; a = age; //Чͬ a = this.age; //ʹthis a = base.age; //ʹbase } public Student(){ //췽 } public Student(string name, int age, string school ) : base( name, age ) //øĹ췽 { this.school = school; } public static void Main( string [] arggs ) { Person p = new Person( "Liming", 50 ); Student s = new Student( "Wangqiang", 20, "PKU" ); Person p2 = new Student( "Zhangyi", 18, "THU" ); Student s2 = (Student) p2; //ת s2.sayHello(); } }
e3d11e2dc5ec698251a905b8901380d5300723f0
C#
bhrnjica/GPImplementation
/chapter4/population.cs
2.953125
3
using System; using System.Linq; using System.Collections.Generic; using System.Threading.Tasks; namespace GPImplemenation { public class Population { //current population internal List<Chromosome> Chromosomes { get; set; } //offspring population internal List<Chromosome> m_Offspring; //default constructor public Population() => Chromosomes = new List<Chromosome>(); //Operations internal void Initialize(Parameters param, Function[] funSet, string[] terSet) { if (Chromosomes != null) Chromosomes.Clear(); else Chromosomes = new List<Chromosome>(); m_Offspring = new List<Chromosome>(); GenerateChromosomes(param.PopulationSize, param, funSet, terSet); } private void GenerateChromosomes(int size, Parameters param, Function[] funSet, string[] terSet) { //Chromosome generation for (int i = 0; i < size; i++) { //Randomly choose which level chromosome will have int levels = Node.Rand.Next(2, param.MaxInitLevel + 1); // generate new chromosome var ch = new Chromosome(); ch.Generate(levels, funSet, terSet); // add chromosome in to population Chromosomes.Add(ch); } } internal void Crossover(Parameters param, Function[] funSet, string[] terSet) { //if crossover is defined if (param.CrossoverProbability == 0) return; for (int i = 1; i < param.PopulationSize; i += 2) { if (Node.Rand.NextDouble() <= param.CrossoverProbability) { var p1 = SelectChromosome(Chromosomes, param); var p2 = SelectChromosome(Chromosomes, param); // cloning the chromosome and prepare for crossover var ch1 = p1.Clone(); var ch2 = p2.Clone(); // crossover ch1.Crossover(ch2, param.MaxOperationLevel, funSet, terSet); //reset fitness ch1.Fitness = float.MinValue; ch2.Fitness = float.MinValue; //add new chromosomes to chromosomes m_Offspring.Add(ch1); m_Offspring.Add(ch2); if (ch1.Node.Level > param.MaxOperationLevel) throw new Exception("Max level exceeded!"); if (ch1.Node.Level > param.MaxOperationLevel) throw new Exception("Max level exceeded!"); } } } internal void Mutate(Parameters param, Function[] funSet, string[] terSet) { //if mutation is defined if (param.MutationProbability == 0) return; for (int i = 0; i < param.PopulationSize; i++) { // if (Node.Rand.NextDouble() <= param.MutationProbability) { var p = SelectChromosome(Chromosomes, param); var ch = p.Clone(); ch.Mutate(param.MaxOperationLevel, funSet, terSet); ch.Fitness = float.MinValue; m_Offspring.Add(ch); } } } internal void EvaluatePopulation(Parameters param) { //perform evaluation on all chromosomes EvaluateParallel(Chromosomes, param); EvaluateParallel(m_Offspring, param); } private void Evaluate(List<Chromosome> chs, Parameters param) { if (chs == null || chs.Count == 0) return; for (int i = 0; i < chs.Count; i++) { if (chs[i].Fitness == float.MinValue) { chs[i].Fitness = param.FitnessFunction(chs[i].Node, param); } } } private void EvaluateParallel(List<Chromosome> chs, Parameters param) { if (chs == null || chs.Count == 0) return; Parallel.For(0, chs.Count, (i) => { if (chs[i].Fitness == float.MinValue) chs[i].Fitness = param.FitnessFunction(chs[i].Node, param); }); } internal void Reproduction(Parameters param, Function[] funSet, string[] terSet) { // probability of reproduction int repNumber = (int)(param.ReproductionProbability * param.PopulationSize) - param.Elitism >= 0 ? param.Elitism : 0; var chs = Chromosomes; //Elitism number of very best chromosome to survive to new generation if (param.Elitism > 0) { int i = param.Elitism; foreach (var c in chs.OrderByDescending(x => x.Fitness)) { if (i == 0) break; m_Offspring.Add(c.Clone()); i--; } } //reproduce repNumber of chromosomes in to new population for (int j = 0; j < repNumber; j++) { Chromosome c = SelectChromosome(chs, param); m_Offspring.Add(c); } } private Chromosome SelectChromosome(List<Chromosome> ch, Parameters par) { if (ch == null || par == null || ch.Count == 0) throw new Exception("Population cannot be empty."); //parameters of the selection double sumOfFitness = 0; //calculate sum of fitness for (int i = 0; i < ch.Count; i++) { //check for invalid fitness if (double.IsNaN(ch[i].Fitness) || double.IsInfinity(ch[i].Fitness)) sumOfFitness += 0; else sumOfFitness += ch[i].Fitness; } //generate random selection point var selPoint = Node.Rand.NextDouble() * sumOfFitness; //enumerate population from the best to the worst double currentScore = 0; foreach (var c in ch.OrderByDescending(x => x.Fitness)) { if (selPoint >= currentScore && selPoint <= currentScore + c.Fitness) return c.Clone() as Chromosome; currentScore += c.Fitness; } //this should not happen throw new Exception("Fitness proportionate selection exception."); } internal void CreateNewGeneration(Parameters par, Function[] funSet, string[] terSet) { // Chromosomes.Clear(); Chromosomes.AddRange(m_Offspring.OrderByDescending(x => x.Fitness).GroupBy(x => x.Fitness).Select(grp => grp.First()).Take(par.PopulationSize)); m_Offspring.Clear(); //if the population has less chromosomes than defined generate new one int size = par.PopulationSize - Chromosomes.Count; if (size > 0) { GenerateChromosomes(size, par, funSet, terSet); EvaluatePopulation(par); } } } }
aa7873a29b4e7a774c252b775da3646133b6377d
C#
PisalPrasad123/CrystalBox
/CITHEPLib/Converters/GreenRedConverter.cs
2.75
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Data; using System.Windows.Media; namespace CITHEPLib.Converters { public class GreenRedConverter: IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { bool v = (bool)value; SolidColorBrush ret = new SolidColorBrush((Color)ColorConverter.ConvertFromString(v ? "Green" : "Red")); return ret; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } }
a38e86aca092250eb08440d4cad68cc99a0df1ce
C#
IntelliTect/EssentialCSharp
/src/Chapter15/Listing15.11.ProjectionWithSystem.Linq.Enumerable.Select.cs
3.046875
3
namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15_11; using AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15; #region INCLUDE using System; using System.Collections.Generic; using System.Linq; public class Program { public static void Main() { IEnumerable<Patent> patents = PatentData.Patents; IEnumerable<Patent> patentsOf1800 = patents.Where( patent => patent.YearOfPublication.StartsWith("18")); #region HIGHLIGHT IEnumerable<string> items = patentsOf1800.Select( patent => patent.ToString()); #endregion HIGHLIGHT Print(items); } #region EXCLUDE private static void Print<T>(IEnumerable<T> items) { foreach(T item in items) { Console.WriteLine(item); } } #endregion EXCLUDE } #endregion INCLUDE
ed2e054816280f17e0ff70c8857114c89f801d0e
C#
unn-85m3/raytraysing
/Auxiliary Libraries/Auxiliary Raytracing Library/Primitive/Sphere.cs
2.859375
3
using System; using Auxiliary.MathTools; using Tao.OpenGl; namespace Auxiliary.Raytracing { /// <summary> ''. </summary> [Serializable] public class Sphere : Primitive { #region Public Fields /// <summary> . </summary> public float Radius = 1.0f; #endregion #region Constructor /// <summary> . </summary> public Sphere(float radius) : base() { Radius = radius; } /// <summary> . </summary> public Sphere(Transform transform) : base(transform) { } /// <summary> . </summary> public Sphere(float radius, Transform tranform) : base(tranform) { Radius = radius; } #endregion #region Protected Methods /// <summary> API OpenGL. </summary> protected override void DrawLocal() { Glu.GLUquadric sphere = Glu.gluNewQuadric(); Glu.gluSphere(sphere, Radius, 80, 80); Glu.gluDeleteQuadric(sphere); } #endregion #region Public Methods /// <summary> . </summary> public override IntersectInfo CalcIntersection(Ray ray) { Vector3D origin = Transform.InversePosition(ray.Origin); Vector3D direction = Transform.InverseDirection(ray.Direction); float a = Vector3D.Dot(direction, direction); float b = Vector3D.Dot(direction, origin); float c = Vector3D.Dot(origin, origin) - Radius * Radius; float det = b * b - a * c; if (det > 0.0f) { det = (float) Math.Sqrt(det); float min = (-b - det) / a; float max = (-b + det) / a; if (max > 0.0f) { if (min > 0.0f) { return new IntersectInfo(min, IntersectType.Outer); } else { return new IntersectInfo(max, IntersectType.Inner); } } } return IntersectInfo.None; } /// <summary> . </summary> public override Vector3D CalcNormal(Vector3D position) { Vector3D local = Transform.InversePosition(position); return Vector3D.Normalize(Transform.TransformNormal(local)); } /// <summary> . </summary> public override Vector3D CalcColor(Vector3D position, Vector3D normal) { Vector3D ip = Vector3D.Normalize(Transform.InversePosition(position)); //Vector3D texcoords = Vector3D.Asin(ip) / Util.PI + Vector3D.Unit / 2; float u = (float)Math.Atan(Math.Sqrt(ip.X * ip.X + ip.Y * ip.Y) / ip.Z); float v = (float)Math.Atan(ip.Y / ip.X); Vector3D color = Material.Color; if (null != Material.Texture) { color *= Material.Texture.CalcColor(new Vector2D(u / Util.PI, 0.5f * v / Util.PI)); } return color; } #endregion } }
d062942d9187b6a212a62350b068d92f7da347df
C#
gerpo/Siterm
/Siterm.Substance/Models/SubstanceTreeViewItem.cs
2.78125
3
using System.Collections.Generic; using System.IO; using System.Linq; using Siterm.Support.ControlModels; using File = Siterm.Support.ControlModels.File; namespace Siterm.Substance.Models { public class SubstanceTreeViewItem : GenericTreeViewItem<Domain.Models.Substance> { public SubstanceTreeViewItem(Domain.Models.Substance substance) { Model = substance; Children = GenerateFileSystemObjects(); } private IList<FileSystemObject> GenerateFileSystemObjects() { var substancePath = Model.Path; var substancePathInfo = new DirectoryInfo(substancePath); if (!substancePathInfo.Exists) return null; var childrenList = substancePathInfo.GetDirectories().Select(directoryInfo => new Folder(directoryInfo)) .Cast<FileSystemObject>().ToList(); childrenList.AddRange(substancePathInfo.GetFiles().Select(fileInfo => new File(fileInfo))); return childrenList; } } }
dfe52443512d3e0eae23d0cbb77cd153b12aee45
C#
kiryl-lenchyk/SocialNetwork
/WebUi/Filters/AutorizeRolesFromConfigAttribute.cs
2.71875
3
using System; using System.Linq; using System.Web.Configuration; using System.Web.Mvc; namespace WebUi.Filters { /// <summary> /// AuthorizeAttribute with role control, but roles names loaded from web.confir /// </summary> public class AutorizeRolesFromConfigAttribute : AuthorizeAttribute { /// <summary> /// Create attribute with one role to control acsses /// </summary> /// <param name="roleConfigKey">config key for role name</param> public AutorizeRolesFromConfigAttribute(String roleConfigKey) { base.Roles = WebConfigurationManager.AppSettings[roleConfigKey]; } /// <summary> /// Create attribute with many roles to control acsses /// </summary> /// <param name="rolesConfigKeys">config keys for roles names</param> public AutorizeRolesFromConfigAttribute(params String[] rolesConfigKeys) { base.Roles = String.Join(",", rolesConfigKeys.Select(x => WebConfigurationManager.AppSettings[x])); } } }
c08bd0b93b0fe203b1f785fe17140bec0a9cc7ce
C#
shendongnian/download4
/first_version_download2/366103-31426503-95131584-2.cs
2.890625
3
public void populateProductList() { string cmdString = "SELECT * FROM PRODUCT"; StockDbConnection dbcon = new StockDbConnection(); SqlCeConnection Conn = new SqlCeConnection(dbcon.ReturnConnection("ConnString")); SqlCeCommand cmd = new SqlCeCommand(cmdString, Conn); DataSet ds; try { Conn.Open(); SqlCeDataAdapter da = new SqlCeDataAdapter(cmd); da.fill(ds); lstvwProduct.DataSource=ds; } catch (Exception exp) { MessageBox.Show(exp.Message); } }
5f19cea985aefd7c8a1306258ec8a4bdab24ddd1
C#
medva1997/bmstu_sem5
/Croc/Банников/Services/ITBridgeService/Program.cs
2.71875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.ServiceProcess; using System.Configuration.Install; using System.Reflection; namespace ITBridgeService { /// <summary> /// Для установки сервиса в операционной системе его надо запустить с параметром install: /// ITBridgeService.exe install /// Для удаления сервиса из операционной системы его надо запустить с параметром delete: /// ITBridgeService.exe delete /// Для запуска сервиса как простой программы его надо запустить с параметром console /// ITBridgeService.exe console /// Запуск сервиса как сервиса осуществляется через панель управления или команду /// net start ITBridgeService /// </summary> class Program { /// <summary> /// Главная функция программы /// </summary> /// <param name="args"></param> static void Main(string[] args) { try { // Первый аргумент командной строки string cmd = (args.Count() > 0) ? args[0] : ""; // Имя файла самого сервиса string s = Assembly.GetExecutingAssembly().Location; BridgeService svc; // Селектор команд switch (cmd) { case "console": // Консольный запуск сервиса svc = new BridgeService(); svc.Start(); Console.WriteLine("Сервис запущен, для завершения нажмите Enter"); Console.ReadLine(); svc.Stop(); break; case "install": ManagedInstallerClass.InstallHelper(new string[] { s }); Console.WriteLine("Для завершения нажмите Enter"); Console.ReadLine(); break; case "uninstall": ManagedInstallerClass.InstallHelper(new string[] { "/u", s }); Console.WriteLine("Для завершения нажмите Enter"); Console.ReadLine(); break; default: // Запуск в виде сервиса svc = new BridgeService(); ServiceBase.Run(svc); break; } } catch (Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine("Для завершения нажмите Enter"); Console.ReadLine(); } } } }
784b027f8a8d138192bc07103cbb400e6c48f738
C#
ACalderwood93/Kafka
/KafkaTestConsume/JsonConsumer.cs
2.890625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Confluent.Kafka; using System.Threading; namespace KafkaTestConsume { class JsonConsumer<t3> : IAsyncConsumer<t3> { public event Action<t3> OnMessageRecieved; public event Action<ConsumeException> OnConsumeError; public Dictionary<string, string> Config { get; set; } public string Topic { get; set; } public JsonConsumer(Dictionary<string, string> config) { this.Config = config; } public void Consume(string topic) { Thread consumeThread = new Thread(() => { _Consume(topic); }); consumeThread.Start(); } public void Consume<T1>(string topic) { Thread consumeThread = new Thread(() => { _Consume<T1>(topic); }); consumeThread.Start(); } private void _Consume(string topic) { using (var c = new ConsumerBuilder<Ignore, string>(Config).Build()) { c.Subscribe(topic); try { while (true) { try { var cr = c.Consume(); var dMessage = Newtonsoft.Json.JsonConvert.DeserializeObject<t3>(cr.Value); OnMessageRecieved?.Invoke(dMessage); // Console.WriteLine($"Consumed message '{cr.Value}' at: '{cr.TopicPartitionOffset}'."); } catch (ConsumeException e) { OnConsumeError?.Invoke(e); // Console.WriteLine($"Error occured: {e.Error.Reason}"); } } } catch (OperationCanceledException) { // Ensure the consumer leaves the group cleanly and final offsets are committed. c.Close(); } } } private void _Consume<T1>(string topic) { using (var c = new ConsumerBuilder<T1, string>(Config).Build()) { c.Subscribe(topic); try { while (true) { try { var cr = c.Consume(); var dMessage = Newtonsoft.Json.JsonConvert.DeserializeObject<t3>(cr.Value); OnMessageRecieved?.Invoke(dMessage); // Console.WriteLine($"Consumed message '{cr.Value}' at: '{cr.TopicPartitionOffset}'."); } catch (ConsumeException e) { OnConsumeError?.Invoke(e); // Console.WriteLine($"Error occured: {e.Error.Reason}"); } } } catch (OperationCanceledException) { // Ensure the consumer leaves the group cleanly and final offsets are committed. c.Close(); } } } } }
5a6464d0c4b1d4f3807a04c536d9f74b732ab535
C#
skwasjer/SilentHunter
/src/SilentHunter.FileFormats/Dat/Chunks/BodyPartsChunk.cs
3.109375
3
using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using SilentHunter.FileFormats.Extensions; namespace SilentHunter.FileFormats.Dat.Chunks { /// <summary> /// /// </summary> /// <remarks> /// Probably poorly named. /// </remarks> public sealed class BodyPartsChunk : DatChunk { /// <summary> /// Initializes a new instance of the <see cref="BodyPartsChunk"/> class. /// </summary> public BodyPartsChunk() : base(DatFile.Magics.BodyParts) { Parts = new List<string>(); } /// <inheritdoc /> public override ulong Id { get => base.Id; set { if (value > uint.MaxValue) { throw new ArgumentOutOfRangeException(nameof(value), "The id for this chunk is only 4 bytes in length (UInt32)."); } base.Id = value; } } /// <summary> /// Gets the part names. /// </summary> public List<string> Parts { get; } /// <summary> /// Gets whether the chunk supports an id field. /// </summary> public override bool SupportsId => true; /// <summary> /// Deserializes the chunk. /// </summary> /// <param name="stream">The stream to read from.</param> protected override Task DeserializeAsync(Stream stream) { using (var reader = new BinaryReader(stream, FileEncoding.Default, true)) { Id = reader.ReadUInt32(); // Read an id as an uint. Parts.Clear(); int partCount = reader.ReadInt32(); for (int i = 0; i < partCount; i++) { Parts.Add(reader.ReadNullTerminatedString()); } } return Task.CompletedTask; } /// <summary> /// Serializes the chunk. /// </summary> /// <param name="stream">The stream to write to.</param> protected override Task SerializeAsync(Stream stream) { using (var writer = new BinaryWriter(stream, FileEncoding.Default, true)) { writer.Write((uint)Id); // Write an id as an uint. writer.Write(Parts.Count); foreach (string partName in Parts) { writer.Write(partName, '\0'); } } return Task.CompletedTask; } } }
5312d6726b9c44ab4be5edad55778ff17c142696
C#
ihristova11/TelerikAcademyAlpha
/02. MODULE 2/[Course] DSA/JudgeProblems/TribonacciTriangle/Program.cs
3.15625
3
using System; class Program { static void Main() { long firstNum = long.Parse(Console.ReadLine()); long secondNum = long.Parse(Console.ReadLine()); long thirdNum = long.Parse(Console.ReadLine()); long l = long.Parse(Console.ReadLine()); long prevF; long prevS; long prevT; long temp, tempS; long[] arr = new long[20]; string printLine = ""; prevF = firstNum + secondNum + thirdNum; prevS = secondNum + thirdNum + prevF; prevT = thirdNum + prevF + prevS; //print first and second line Console.WriteLine(firstNum); Console.WriteLine(secondNum + " " + thirdNum); if (l > 2) { Console.WriteLine(prevF + " " + prevS + " " + prevT); for (int i = 4; i <= l; i++) { for (int j = 0; j < i; j++) { //prevF = prevF + prevS + prevT; //prevS = prevF + prevS + prevT; //prevT = prevF + prevS + prevT; arr[j] = prevF + prevS + prevT; temp = prevT; tempS = prevS; prevT = arr[j]; prevS = temp; prevF = tempS; if (j == i - 1) { printLine += arr[j]; } else { printLine += arr[j] + " "; } //string.Format(" ", arr[j]); } Console.WriteLine(printLine); printLine = ""; //Console.WriteLine(prevF + " " + prevS + " " + prevT); // print the line } } } }
beb40493acc7911fadc4670d797bb4089bc5071f
C#
KonstantinaLa/ArmadaV3
/Armada.WebApp/Controllers/WebApi/EmperorController.cs
2.546875
3
using System.Collections.Generic; using System.Data.Entity.Infrastructure; using System.Linq; using System.Net; using System.Web.Http; using System.Web.Http.Description; using ArmadaV3.Entities; using ArmadaV3.RepositoryService; namespace Armada.WebApp.Controllers.WebApi { public class EmperorController : ApiController { private readonly IUnitOfWork unitOfWork; public EmperorController() { unitOfWork = new UnitOfWork(); } // GET: api/Emperor public IHttpActionResult GetEmperors() { var emperors = unitOfWork.Emperors.Get().Select(e => new { EmperorId = e.EmperorId, Name = e.Name, Age = e.Age, Photo = e.Photo, Species = e.Species.ToString(), AllSpecies =new List<string> {EmperorSpecies.Blorg.ToString() , EmperorSpecies.Vheln.ToString(), EmperorSpecies.Human.ToString() , EmperorSpecies.Lok.ToString() , EmperorSpecies.Orbis.ToString(),EmperorSpecies.Pasharti.ToString(),EmperorSpecies.Scyldari.ToString(),EmperorSpecies.Zoltan.ToString(),EmperorSpecies.Engi.ToString(), EmperorSpecies.Gecko.ToString() , EmperorSpecies.Mantis.ToString()}, Empire = e.Empire.Name }); return Ok(emperors); } // GET: api/Emperor/5 [ResponseType(typeof(Emperor))] public IHttpActionResult GetEmperor(int? id) { var emperor = unitOfWork.Emperors.FindById(id); if (emperor == null) return NotFound(); return Ok(new{EmperorId = emperor.EmperorId,Name = emperor.Name,Age = emperor.Age,Photo = emperor.Photo,EmpireId = emperor.Empire.EmpireId, EmpireName=emperor.Empire.Name , Species = emperor.Species.ToString(), Description = emperor.Description}); } // PUT: api/Emperor/5 [ResponseType(typeof(void))] public IHttpActionResult PutEmperor(int id, Emperor emperor) { if (!ModelState.IsValid) return BadRequest(ModelState); if (id != emperor.EmperorId) return BadRequest(); unitOfWork.Emperors.Edit(emperor); try { unitOfWork.Save(); } catch (DbUpdateConcurrencyException) { if (!unitOfWork.Emperors.Exists(id)) return NotFound(); else throw; } return Ok(new {Name = emperor.Name}); } // POST: api/Emperor [ResponseType(typeof(Emperor))] public IHttpActionResult PostEmperor(Emperor emperor) { if (!ModelState.IsValid) return BadRequest(ModelState); unitOfWork.Emperors.Create(emperor); try { unitOfWork.Save(); } catch (DbUpdateException) { if (unitOfWork.Emperors.Exists(emperor.EmperorId)) return Conflict(); } return CreatedAtRoute("DefaultApi", new {id = emperor.EmperorId },emperor); } // DELETE: api/Emperor/5 [ResponseType(typeof(Emperor))] public IHttpActionResult DeleteEmperor(int? id) { var emperor = unitOfWork.Emperors.FindById(id); if (emperor == null) return NotFound(); unitOfWork.Emperors.Delete(emperor); unitOfWork.Save(); return Ok(emperor); } protected override void Dispose(bool disposing) { if (disposing) unitOfWork.Dispose(); base.Dispose(disposing); } } }
13ac482f41dec7747ac228f7792f5b83a80725f8
C#
lemanas/BVKKMN
/BVKMN/FinancialFunctions.cs
2.625
3
using Excel.FinancialFunctions; namespace BVKMN { static class FinancialFunctions { public static double Pmt(double interestRate, int months, double sum) { return Financial.Pmt(interestRate / 12, months, sum * -1, 0, PaymentDue.BeginningOfPeriod); } public static double Rate(int months, double pmt, double sum) { return Financial.Rate(months, pmt, sum * -1, 0, PaymentDue.BeginningOfPeriod); } public static double Effect(double rate) { return Financial.Effect(rate * 12, 12); } } }
0e4859a8294c6aef498ce53c3e0b0d7b8287317e
C#
zeinabkalanaki/DDD_Course-CreationalPatterns
/Pattern04.Prototype/Program.cs
3.203125
3
using System; namespace Pattern04.Prototype { class Program { //زمانی که یک کلاس بزرگ داریم و نمونه سازی از آن سخت است //یک بار از آن نمونه ساخته و دفعات بعد از همان یک نمونه ساخته شده کپی می کنیم static void Main(string[] args) { //Method 1 //copy all member execpt of static and private member //is shallow copy just copy value type member and share refrence Type member between instances Method_1.LargeObject largeObject = new Method_1.LargeObject(); var instance1 = largeObject.Clone(); instance1.MyProperty++; instance1.MyInnerClass.MyProperty++; Console.WriteLine("instance1.MyProperty : " + instance1.MyProperty); Console.WriteLine("instance1.MyInnerClass.MyProperty : " + instance1.MyInnerClass.MyProperty); var instance2 = largeObject.Clone(); instance2.MyProperty++; instance2.MyInnerClass.MyProperty++; Console.WriteLine("instance2.MyProperty : " + instance2.MyProperty); Console.WriteLine("instance2.MyInnerClass.MyProperty : " + instance2.MyInnerClass.MyProperty); var instance3 = largeObject.Clone(); instance3.MyProperty++; instance3.MyInnerClass.MyProperty++; Console.WriteLine("instance3.MyProperty : " + instance3.MyProperty); Console.WriteLine("instance3.MyInnerClass.MyProperty : " + instance3.MyInnerClass.MyProperty); Console.ReadLine(); } } }
b00021279d5c2d0c94f203d4a18c300c867f278e
C#
igor27g/StudentDiary
/StudentDiary/Program.cs
3.6875
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace StudentDiary { class Program { static void Main(string[] args) { Diary diary = new Diary(); diary.AddRating(5); diary.AddRating(8.5f); diary.AddRating(4.7f); DiaryStatistics stats = diary.ComputerStatistics(); Console.WriteLine("Srednia wartosc" + stats.AverageGrade); Console.WriteLine("Maksymalna wartosc" + stats.MaxGrade); Console.WriteLine("Minimalna wartosc" + stats.MinGrade); /* for (; ; ) { Console.WriteLine("Poda ocenę z zakresu 1 - 10"); float rating; bool result = float.TryParse(Console.ReadLine(), out rating); diary.AddRating(rating); if(rating == 11) { break; } if (result == true) { if(rating > 0 && rating <= 10) { diary.AddRating(rating); } else { Console.WriteLine("Nie poprawna liczba. Podaj liczbę z zakresu 1 - 10"); } } } Console.WriteLine("Średnia Twoich ocen to : " + diary.CalculateAverage()); Console.WriteLine("Najwyższa ocena to : " + diary.GiveMaxRating()); Console.WriteLine("Najniższa ocena to : " + diary.GiveMinRating()); Console.ReadKey(); */ } } }
5c8ecbd1e61dc6a360abded76f6f6116b7f1ed12
C#
TunggNguyenn/ProgrammingCourseAPI
/ProgrammingCourse/ProgrammingCourse/Controllers/CategoriesController.cs
2.515625
3
using AutoMapper; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using ProgrammingCourse.Models; using ProgrammingCourse.Models.ViewModels; using ProgrammingCourse.Repositories; using ProgrammingCourse.Services; using System; using System.Linq; using System.Threading.Tasks; namespace ProgrammingCourse.Controllers0 { [Route("api/[controller]")] [ApiController] public class CategoriesController : ControllerBase { private readonly CategoryService categoryService; private readonly CourseService courseService; private readonly IMapper mapper; public CategoriesController(CategoryService categoryService, CourseService courseService, IMapper mapper) { this.categoryService = categoryService; this.courseService = courseService; this.mapper = mapper; } [HttpGet("{id}")] public async Task<IActionResult> GetWithAllInfoById(int id) { var category = await categoryService.GetWithAllInfoById(id); if (category != null) { return Ok(new { Results = category }); } else { return BadRequest(new { Errors = new { Code = "InvalidId", Description = "Invalid Id!" } }); } } [HttpGet] [Route("GetWithAllInfoByName")] public async Task<IActionResult> GetWithAllInfoByName([FromQuery] string name) { var category = await categoryService.GetWithAllInfoByName(name); if (category != null) { return Ok(new { Results = category }); } else { return BadRequest(new { Errors = new { Code = "InvalidId", Description = "Invalid Id!" } }); } } [HttpGet] [Route("CategoryListByCategoryTypeId")] public async Task<IActionResult> CategoryListByCategoryTypeId([FromQuery] int categoryId) { var categoryList = await categoryService.GetCategoryListByCategoryTypeId(categoryId); if (categoryList.Count != 0) { return Ok(new { Results = categoryList }); } else { return BadRequest(new { Errors = new { Code = "InvalidId", Description = "Invalid Id!" } }); } } [HttpGet] public async Task<IActionResult> GetAll() { var categories = await categoryService.GetAll(); return Ok(new { Results = categories }); } [HttpPost] public async Task<IActionResult> Add([FromForm] CategoryViewModel categoryViewModel) { try { Category categoryMapped = mapper.Map<Category>(categoryViewModel); await categoryService.Add(categoryMapped); return Ok(new { Results = categoryMapped }); } catch (Exception e) { Console.WriteLine($"ErrorMesages: {e}"); return BadRequest(new { Errors = new { Code = "InvalidInputParameters", Description = "Invalid Input Parameters!" } }); } } [HttpPut] public async Task<IActionResult> Update([FromForm] CategoryViewModel categoryViewModel) { try { Category categoryMapped = mapper.Map<Category>(categoryViewModel); await categoryService.Update(categoryMapped); return Ok(new { Results = categoryMapped }); } catch (Exception e) { Console.WriteLine($"ErrorMesages: {e}"); return BadRequest(new { Errors = new { Code = "InvalidInputParameters", Description = "Invalid Input Parameters!" } }); } } [HttpDelete("{id}")] public async Task<IActionResult> Remove(int id) { try { var courses = await courseService.GetByCategoryId(id); if (courses.Count > 0) { return BadRequest(new { Errors = new { Code = "ExistedCourse", Description = "Category has already existed course" } }); } var removedCategory = await categoryService.GetById(id); await categoryService.Remove(removedCategory); return Ok(new { Results = removedCategory }); } catch (Exception e) { Console.WriteLine($"ErrorMesages: {e}"); return BadRequest(new { Errors = new { Code = "InvalidId", Description = "Invalid Id!" } }); } } [HttpGet()] [Route("MostRegisteredCategories")] public async Task<IActionResult> MostRegisteredCategories() { var mostRegisteredCategories = await categoryService.GetMostRegisteredCategories(); return Ok(new { Results = mostRegisteredCategories }); } } }
74a52c7fae3d395f344b3cd40ea2ad9e6acde1d6
C#
snmuppa/ninjato
/src/Ninjato.Services.Activity/Domain/Repositories/ICategoryRepository.cs
2.6875
3
using System.Collections.Generic; using System.Threading.Tasks; using Ninjato.Services.Activity.Domain.Models; namespace Ninjato.Services.Activity.Domain.Repositories { /// <summary> /// Category repository. /// </summary> public interface ICategoryRepository { /// <summary> /// Fetches the category for a given name /// </summary> /// <returns>The async.</returns> /// <param name="name">Name.</param> Task<Category> GetAsync(string name); /// <summary> /// Fetches all the categories that are available /// </summary> /// <returns>The async.</returns> Task<IEnumerable<Category>> BrowseAsync(); /// <summary> /// Adds a category /// </summary> /// <returns>The async.</returns> /// <param name="category">Category.</param> Task AddAsync(Category category); } }
297e7e5525354874baab50bd28fed5f182575093
C#
JJPrimm/AdventOfCode2019
/AdventCode/Day8.cs
3.5625
4
using System; using System.Collections.Generic; using System.Linq; namespace AdventCode { public static class Day8 { public static void Problem1() { var input = Utilities.ReadStringArray(8)[0]; int layerCount = input.Length / 150; int leastZeroes = 1000; int leastZeroesLayer = 0; string layer; for (int l = 0; l < layerCount; l++) { layer = input.Substring(l * 150, 150); var zeroes = layer.Where(c => c == '0').Count(); if (zeroes < leastZeroes) { leastZeroes = zeroes; leastZeroesLayer = l; } } layer = input.Substring(leastZeroesLayer * 150, 150); var ones = layer.Where(c => c == '1').Count(); var twos = layer.Where(c => c == '2').Count(); var result = ones * twos; Console.WriteLine($"Day 8 - 1: {result}"); } public static void Problem2() { var input = Utilities.ReadStringArray(8)[0]; int layerCount = input.Length / 150; var layers = new List<string>(); for (int l = 0; l < layerCount; l++) { layers.Add(input.Substring(l * 150, 150)); } for (int p = 0; p < 150; p++) { if (p % 25 == 0) { Console.WriteLine(); } char color = ' '; for (int l = 0; l < layerCount; l++) { if (layers[l][p] != '2') { if (layers[l][p] == '1') { color = 'O'; } else { color = '.'; } break; } } Console.Write(color); } } } }
55b71457a72b1d889579eb96571a92217212e270
C#
unitycoder/UnityLauncherPro
/UnityLauncherPro/GetUnityUpdates.cs
2.9375
3
using System; using System.Collections.Generic; using System.Globalization; using System.Net; using System.Threading.Tasks; namespace UnityLauncherPro { public static class GetUnityUpdates { static bool isDownloadingUnityList = false; static readonly string unityVersionsURL = @"http://symbolserver.unity3d.com/000Admin/history.txt"; public static async Task<string> Scan() { if (isDownloadingUnityList == true) { Console.WriteLine("We are already downloading ..."); return null; } isDownloadingUnityList = true; //SetStatus("Downloading list of Unity versions ..."); string result = null; // download list of Unity versions using (WebClient webClient = new WebClient()) { Task<string> downloadStringTask = webClient.DownloadStringTaskAsync(new Uri(unityVersionsURL)); try { result = await downloadStringTask; } catch (WebException) { Console.WriteLine("It's a web exception"); } catch (Exception) { Console.WriteLine("It's not a web exception"); } isDownloadingUnityList = false; } return result; } public static Updates[] Parse(string items) { isDownloadingUnityList = false; //SetStatus("Downloading list of Unity versions ... done"); var receivedList = items.Split(new[] { Environment.NewLine }, StringSplitOptions.None); if (receivedList == null && receivedList.Length < 1) return null; Array.Reverse(receivedList); var releases = new Dictionary<string, Updates>(); // parse into data string prevVersion = null; for (int i = 0, len = receivedList.Length; i < len; i++) { var row = receivedList[i].Split(','); var versionTemp = row[6].Trim('"'); if (versionTemp.Length < 1) continue; if (prevVersion == versionTemp) continue; if (releases.ContainsKey(versionTemp) == false) { var u = new Updates(); u.ReleaseDate = DateTime.ParseExact(row[3], "MM/dd/yyyy", CultureInfo.InvariantCulture); u.Version = versionTemp; releases.Add(versionTemp, u); } prevVersion = versionTemp; } // convert to array var results = new Updates[releases.Count]; releases.Values.CopyTo(results, 0); return results; } } }
b3593946f774d8a6df2a7b2838743ca18240309c
C#
kaby76/Antlr4BuildTasks
/Antlr4BuildTasks/SharpCompress/Archives/IWritableArchiveExtensions.cs
2.859375
3
using System; using System.IO; using SharpCompress.Writers; namespace SharpCompress.Archives { public static class IWritableArchiveExtensions { public static void AddEntry(this IWritableArchive writableArchive, string entryPath, string filePath) { var fileInfo = new FileInfo(filePath); if (!fileInfo.Exists) { throw new FileNotFoundException("Could not AddEntry: " + filePath); } writableArchive.AddEntry(entryPath, new FileInfo(filePath).OpenRead(), true, fileInfo.Length, fileInfo.LastWriteTime); } public static void SaveTo(this IWritableArchive writableArchive, string filePath, WriterOptions options) { writableArchive.SaveTo(new FileInfo(filePath), options); } public static void SaveTo(this IWritableArchive writableArchive, FileInfo fileInfo, WriterOptions options) { using (var stream = fileInfo.Open(FileMode.Create, FileAccess.Write)) { writableArchive.SaveTo(stream, options); } } public static void AddAllFromDirectory( this IWritableArchive writableArchive, string filePath, string searchPattern = "*.*", SearchOption searchOption = SearchOption.AllDirectories) { using (writableArchive.PauseEntryRebuilding()) { foreach (var path in Directory.EnumerateFiles(filePath, searchPattern, searchOption)) { var fileInfo = new FileInfo(path); writableArchive.AddEntry(path.Substring(filePath.Length), fileInfo.OpenRead(), true, fileInfo.Length, fileInfo.LastWriteTime); } } } public static IArchiveEntry AddEntry(this IWritableArchive writableArchive, string key, FileInfo fileInfo) { if (!fileInfo.Exists) { throw new ArgumentException("FileInfo does not exist."); } return writableArchive.AddEntry(key, fileInfo.OpenRead(), true, fileInfo.Length, fileInfo.LastWriteTime); } } }
1b8bf15788244f5b1165b4e4b8f86d3237023def
C#
MelihSevsay/RegexConsoleTester
/Contracts/RegexBase.cs
3.21875
3
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using RegexConsoleTester.Utils; namespace Contracts { //How to decide when to use abstract class or interface. //if you are creating something that provides common functionality to unrelated classes, use an interface. //If you are creating something for objects that are closely related in a hierarchy, use an abstract class. public abstract class RegexBase { public string RegexName { get; set; } [Required(ErrorMessage = "Enter Regex ")] [Display(Name = "Regex Code")] public string RegexCodeRQ { get; set; } [Required(ErrorMessage = "Enter Text")] [Display(Name = "Text")] public string RegexTextRQ { get; set; } public RegexBase() { //Abstrack Factrory Method Pattern : //Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses. ExecPreReq(); } public abstract void ExecPreReq(); public abstract void ExecRegex(); /// <summary> /// Show regex result /// </summary> /// <param name="regexCode"></param> /// <param name="orginalText"></param> /// <param name="extra"></param> public virtual void ShowResult(string regexCode, string orginalText, string afterRegexText, Dictionary<string, string> extra = null) { Console.WriteLine("-----------------------------------------------------"); Console.WriteLine(string.Format(ConsoleWriteTemplate.TitleNewLine, "Regex Code", regexCode)); Console.WriteLine(string.Format(ConsoleWriteTemplate.TitleNewLine, "Text", orginalText)); Console.WriteLine(string.Format(ConsoleWriteTemplate.Title, "Result", afterRegexText)); if (extra!=null && extra.Count>0) { foreach (KeyValuePair<string, string> item in extra) { Console.WriteLine(string.Format(ConsoleWriteTemplate.Title, item.Key, item.Value)); } } } } }
f4cc48f7e717625ac1bffac9488b4eeb6bcc2d2e
C#
CyberBotX/sda-donation-tracker
/PrizeAssignContext.cs
2.8125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SDA_DonationTracker { public class PrizeAssignContext : ConnectionContext { public int PrizeId { get; private set; } public string Result { get; private set; } public event Action<string> Completed; public PrizeAssignContext(TrackerContext context, int prizeId) : base(context) { this.PrizeId = prizeId; } protected override void Run() { this.Result = this.Context.DrawPrize(this.PrizeId); if (this.Completed != null) this.Completed(this.Result); } } }
9349e888e2eeb5c82d83ac8a7e9818cc546f3514
C#
lesha1980/ConvertInvoices
/ConverterToParamTXT/App.xaml.cs
2.796875
3
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Linq; using System.Threading.Tasks; using System.Windows; using System.IO; using System.IO.IsolatedStorage; using System.Collections; using System.Diagnostics; namespace ConverterToParamTXT { /// <summary> /// Логика взаимодействия для App.xaml /// </summary> /// public enum ApplicationExitCode { Success = 0, Failure = 1, CantWriteToApplicationLog = 2, CantPersistApplicationState = 3 } public partial class App : Application { private void Application_Exit_1(object sender, ExitEventArgs e) { try { // Write entry to application log if (e.ApplicationExitCode == (int)ApplicationExitCode.Success) { WriteApplicationLogEntry("Failure", e.ApplicationExitCode); } else { WriteApplicationLogEntry("Success", e.ApplicationExitCode); } } catch { // Update exit code to reflect failure to write to application log e.ApplicationExitCode = (int)ApplicationExitCode.CantWriteToApplicationLog; } // Persist application state try { PersistApplicationState(); } catch { // Update exit code to reflect failure to persist application state e.ApplicationExitCode = (int)ApplicationExitCode.CantPersistApplicationState; } } void WriteApplicationLogEntry(string message, int exitCode) { // Write log entry to file in isolated storage for the user IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForAssembly(); using (Stream stream = new IsolatedStorageFileStream("log.txt", FileMode.Append, FileAccess.Write, store)) using (StreamWriter writer = new StreamWriter(stream)) { string entry = string.Format("{0}: {1} - {2}", message, exitCode, DateTime.Now); writer.WriteLine(entry); } } void PersistApplicationState() { // Persist application state to file in isolated storage for the user IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForAssembly(); using (Stream stream = new IsolatedStorageFileStream("state.txt", FileMode.Create, store)) using (StreamWriter writer = new StreamWriter(stream)) { foreach (DictionaryEntry entry in this.Properties) { writer.WriteLine(entry.Value); } } } } }
4e14cee3cdea71227bf3a911e149738c6da29933
C#
AlexandrSurkov/FlekoFramework
/FlekoFramework/UnitTests/Common/GuidReferenceTests.cs
2.53125
3
using System; using System.ComponentModel; using Flekosoft.Common; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Flekosoft.UnitTests.Common { class TestReference : GuidReference { public bool CheckReferenceResult { get; set; } protected override bool CheckReference() { return CheckReferenceResult; } } [TestClass] public class GuidReferenceTests { [TestMethod] public void Test() { var tr = new TestReference(); tr.PropertyChanged += Tr_PropertyChanged; tr.ValidityChanged += Tr_ValidityChanged; var guid = Guid.NewGuid(); Assert.AreEqual(Guid.Empty, tr.Guid); tr.Guid = guid; Assert.AreEqual(guid, tr.Guid); tr.CheckReferenceResult = false; ValidityChangedEvent = null; PropertyChangedEvent = null; tr.Guid = Guid.NewGuid(); Assert.AreEqual(nameof(tr.IsValid), PropertyChangedEvent?.PropertyName); Assert.AreEqual(tr.CheckReferenceResult, ValidityChangedEvent?.IsValid); Assert.AreEqual(tr.CheckReferenceResult, tr.IsValid); tr.CheckReferenceResult = true; ValidityChangedEvent = null; PropertyChangedEvent = null; tr.Guid = Guid.NewGuid(); Assert.AreEqual(nameof(tr.IsValid), PropertyChangedEvent?.PropertyName); Assert.AreEqual(tr.CheckReferenceResult, ValidityChangedEvent?.IsValid); Assert.AreEqual(tr.CheckReferenceResult, tr.IsValid); tr.Dispose(); tr.CheckReferenceResult = true; ValidityChangedEvent = null; PropertyChangedEvent = null; tr.Guid = Guid.NewGuid(); Assert.IsNull(ValidityChangedEvent); Assert.IsNull(PropertyChangedEvent); } private void Tr_ValidityChanged(object sender, ValidityChangedEventArgs e) { ValidityChangedEvent = e; } private void Tr_PropertyChanged(object sender, PropertyChangedEventArgs e) { PropertyChangedEvent = e; } public PropertyChangedEventArgs PropertyChangedEvent { get; set; } public ValidityChangedEventArgs ValidityChangedEvent { get; set; } } }
c6f74290938f592481a2387f495860ace5b6d0e3
C#
talecrafter/LudumDare32
/HoldSpaceToFart/Assets/_Library/Framework/Actors/Target.cs
2.515625
3
using UnityEngine; using System.Collections; using System.Collections.Generic; using CraftingLegends.Core; namespace CraftingLegends.Framework { public class Target { // ================================================================================ // types // -------------------------------------------------------------------------------- const float PATH_NODE_DISTANCE_SQUARED = 0.2f; public enum TargetType { Position, Transform, Actor, None } public TargetType type; // ================================================================================ // events // -------------------------------------------------------------------------------- public enum TargetEventType { TargetReached, CannotReachTarget } public delegate void TargetEventDelegate(TargetEventType type); public event TargetEventDelegate targetEvent; // ================================================================================ // public // -------------------------------------------------------------------------------- public bool isReached = true; public bool hasTarget { get { return type != TargetType.None; } } public bool hasActorTarget { get { return type == TargetType.Actor; } } // ================================================================================ // private // -------------------------------------------------------------------------------- private Transform _protagonistTransform; private Actor _protagonist; private Vector2 _targetPosition; private Transform _targetTransform; private Actor _otherActor; public Actor otherActor { get { return _otherActor; } } private float _targetReachedDistanceSquared; // saving squared value because of performance reasons when comparing vector length private bool _determined = false; private IPathField _pathField = null; private Vector2Path _path = null; private bool _hasPath = false; private int _ticker = 0; private int _maxTicker = 10; private bool _calculatePathAtNextPossibility = false; // ================================================================================ // constructor // -------------------------------------------------------------------------------- public Target(Actor protagonist, Transform protagonistTransform) { _protagonist = protagonist; _protagonistTransform = protagonistTransform; _ticker = Random.Range(0, _maxTicker); _path = new Vector2Path(80); } // ================================================================================ // public methods // -------------------------------------------------------------------------------- public void Update() { // make sure we follow no null target enemy if (type == TargetType.Actor && _otherActor == null) { DisableTarget(); return; } // performance heavy calculations only every few frames if (!isReached) PerformanceTicker(); if (type != TargetType.None) { Vector2 targetPos = GetFinalTargetPosition(); if (Utilities2D.Vector2SqrDistance(_protagonistTransform.position, targetPos) <= _targetReachedDistanceSquared) { ReachTarget(); } else { isReached = false; } // check for next target on path if (_hasPath && !isReached) { if (Utilities2D.Vector2SqrDistance(_protagonistTransform.position, GetCurrentTargetLocation()) <= PATH_NODE_DISTANCE_SQUARED) { NextNodeInPath(); if (!_hasPath) { _calculatePathAtNextPossibility = true; ReachTarget(); // TODO: this line was disabled in Indomitable - why? } } } } } public Vector2 GetFinalTargetPosition() { Vector2 targetPos = _targetPosition; if (type == TargetType.Transform || type == TargetType.Actor) { targetPos = _targetTransform.position; } return targetPos; } public Vector2 GetCurrentTargetLocation() { if (_hasPath && !_path.isFinished) { return _path.CurrentPosition; } else { return GetFinalTargetPosition(); } } // set position as target public void SetTarget(Vector2 targetPos, float targetDistance, bool newDetermination = false) { if (_determined == true && newDetermination == false) { return; } DisableTarget(); type = TargetType.Position; _targetPosition = targetPos; _targetReachedDistanceSquared = targetDistance * targetDistance; isReached = false; _determined = newDetermination; _calculatePathAtNextPossibility = true; } // set object as target public void SetTarget(Transform targetTransform, float targetDistance, bool newDetermination = false) { if (_determined == true && newDetermination == false) { return; } DisableTarget(); type = TargetType.Transform; _targetTransform = targetTransform; _targetReachedDistanceSquared = targetDistance * targetDistance; isReached = false; _determined = newDetermination; _calculatePathAtNextPossibility = true; } // set other Actor as target public void SetTarget(Actor otherActor, float targetDistance, bool newDetermination = false) { if (_determined == true && newDetermination == false) { return; } _determined = newDetermination; DisableTarget(); if (otherActor == null) return; type = TargetType.Actor; _otherActor = otherActor; _targetTransform = otherActor.transform; _targetReachedDistanceSquared = targetDistance * targetDistance; isReached = false; _determined = newDetermination; _otherActor.stateChanged += Actor_StateChanged; _calculatePathAtNextPossibility = true; } public void DisableTarget() { type = TargetType.None; if (_otherActor != null) { _otherActor.stateChanged -= Actor_StateChanged; _otherActor = null; } _targetTransform = null; // path parameters _hasPath = false; _calculatePathAtNextPossibility = false; isReached = true; _determined = false; } public void SetPathField(IPathField field) { DisableTarget(); _pathField = field; } // ================================================================================ // private methods // -------------------------------------------------------------------------------- private void PerformanceTicker() { _ticker++; if (_ticker >= _maxTicker) { _ticker = 0; if (_calculatePathAtNextPossibility) { _calculatePathAtNextPossibility = false; CalculatePath(); } } } private void ReachTarget() { isReached = true; // target reached if (type == TargetType.Position || type == TargetType.Transform) { DisableTarget(); } if (targetEvent != null) { targetEvent(TargetEventType.TargetReached); } } private void CalculatePath() { // if level grid exists and actor can move, otherwise ignore if (_pathField != null && _protagonist.movementSpeed > 0) { _pathField.GetPath(_protagonistTransform.position, GetFinalTargetPosition(), _path); _hasPath = _path.isValid; if (!_hasPath) { if (type == TargetType.Position) { ReachTarget(); } } } } private void NextNodeInPath() { if (_hasPath && _path.isValid) { _path.NextPosition(); } if (!_path.isValid || _path.isFinished) { _hasPath = false; } } private void Actor_StateChanged(IActor actor, ActorState state) { if (!actor.isAlive) { DisableTarget(); if (targetEvent != null) { targetEvent(TargetEventType.CannotReachTarget); } } } } }
71336be8c7b39899b1e260154ecffaf36bc75873
C#
reza-mesgaran/Console_Ex-Method
/Console_Ex-Method/Program.cs
3.921875
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; /* Note (Ex-Method ) 1. Should defines in static class 2. Should define as a static method 3. Can & Can't have a return value 4. Despite Ex-Method is Static but is accessible from instance of its target class (not directly from its class) */ namespace Console_Ex_Method { class Program { static void Main(string[] args) { Console.Write("Enter something here:"); string strInput = (Console.ReadLine().Trim()); strInput.WordCounter(); // Using Ex-Method for Native Class (string class) -- word counter Console.WriteLine(EX_Method.Tavan2(12)); // Using Ex-Method for Native Class (int class) -- calculate x*x Person p1 = new Person() { Id = 0, Fname = "Reza", Lname = "Mesgaran",Sex="Man"}; Console.WriteLine(p1.FullName(p1.Fname, p1.Lname, p1.Sex)); // Using Ex-Method for user-defined Class (person class) -- add prefix Console.ReadKey(); } } public static class EX_Method { public static void WordCounter(this string str) { char[] ch = str.ToCharArray(); int digit = 0; int letter = 0; foreach (char c in ch) { if (!char.IsWhiteSpace(c)) { if (char.IsDigit(c)) digit++; else if (char.IsLetter(c)) letter++; } } Console.WriteLine("Your entery has {0} letters and {1} digit ", letter, digit); } // Ex-Method for Native Classes - Without Return public static int Tavan2(this int n) // Ex-Method for Native Classes- With Return { return (n * n); } public static string FullName(this Person person, string Fname, string Lname ,string Sex) // Ex-Method for User-Defined Classes { if (Sex == "Man") //First value of Enum return "Mr. " + Fname + Lname; else if (Sex=="Woman") //Second value of Enum return "Mrs. " +Fname + Lname; return null; // Never Happen } } public class Person { public int Id { get; set; } public string Fname { get; set; } public string Lname { get; set; } public string Sex { get; set; } } }
c1df4675d52985b8e1bc44a1a2046da5082aadc5
C#
Trey0303/Artificial-Intelligence-for-Games
/Assets/Scenes/Djikstra/Scripts/DjikstraAlgorithm.cs
2.90625
3
using System.Collections; using System.Collections.Generic; using UnityEngine; public class DjikstraAlgorithm : MonoBehaviour { //Tile Generation public int gridWidth;//set grid width spawn public int gridHeight;//set grid height spawn public GameObject prefab;//set a gameobject to create public Tile[] tiles;//to create an array of tiles //public Tile debugStart; //public Tile debugEnd; //private Tile[] debugPath; private void Start() { tiles = new Tile[gridWidth * gridHeight];//set array to grid Vector3 offset = Vector3.zero;//create an offset an set to zero // spawn the tiles for (int i = 0; i < gridHeight; ++i) { for (int j = 0; j < gridWidth; ++j)//goes through grid a set number of times before going on to the next row on grid height { GameObject newTile = Instantiate(prefab, transform.position + offset, transform.rotation);//create new tile tiles[i * gridWidth + j] = newTile.GetComponent<Tile>();//add new tile to array newTile.name = string.Format("{0}, {1}", i, j);//name tile on graph offset.x += 1.0f;//when ever an object spawns shift x by one to create a row } offset.x = 0.0f;//starts on the left most object on grid to reset the offset offset.z += 1.0f;//goes up the grid by 1(going to the next row) to create a column } // setup connections for (int i = 0; i < tiles.Length; ++i) { List<Tile> connectedTiles = new List<Tile>(); // if we're not at the left-edge if (i % gridWidth != 0) { connectedTiles.Add(tiles[i - 1]); } // if we're not at the right-edge if ((i + 1) % gridWidth != 0) { connectedTiles.Add(tiles[i + 1]); } // if we're not at the upper-edge if (i < gridWidth * gridHeight - gridWidth) { connectedTiles.Add(tiles[i + gridWidth]); } // if we're not at the bottom-edge if (i > gridWidth - 1) { connectedTiles.Add(tiles[i - gridWidth]); } tiles[i].connectedTiles = connectedTiles.ToArray(); } } //Path Generation private Tile GetCheapestTile(Tile[] arr) { float bestGScore = float.MaxValue;//initialize Tile bestTile = null;//initialize for (int i = 0; i < arr.Length; ++i) { if (arr[i].gScore < bestGScore)//if current tile has the best score { bestTile = arr[i];//set to current index bestGScore = arr[i].gScore;//set to current index score } } return bestTile; } //private void Update() //{ // if (Input.GetKeyDown(KeyCode.G))//visually shows calculatedPath // { // debugPath = CalculatePath(debugStart, debugEnd); // } //} private void ResetNodes() { for(int i = 0; i < tiles.Length; ++i) { tiles[i].gScore = 0;//set tiles gscore to zero tiles[i].previousTile = null;//set previous tile to null } } public Tile[] CalculatePath(Tile origin, Tile destination)// CalculatePath(start and end) { ResetNodes();//clear old data List<Tile> openList = new List<Tile>();//nodes that have NOT been traversed through List<Tile> closedList = new List<Tile>();//nodes that have been traversed through openList.Add(origin);//add starting tile while (openList.Count != 0 && // still stuff left to explore !closedList.Contains(destination)) // AND we haven't reached the destination yet { // TODO: replace this with a proper sorted array implementation Tile current = GetCheapestTile(openList.ToArray());//update current openList.Remove(current);//remove current node from list closedList.Add(current);//add current node to list // TODO... // calculate g scores for connected tiles //throw new System.NotImplementedException(); for (int i = 0; i < current.connectedTiles.Length; ++i)//until it reaches the last connected tile { Tile adjTile = current.connectedTiles[i];//create adjTile and set to current connected tile int calGScore = current.gScore + adjTile.cost;//calculate gScore = current gScore + travel cost(hard-coded to 1) if (!adjTile.traversible) { continue; }//if not traversable move on to next node if (adjTile.previousTile == null || //if adjTile previous tile is equal to null(I think this condition is used because preiousTile starts off null) calGScore < adjTile.gScore)//or estScore is less than current adjTile gScore { adjTile.previousTile = current;//set adjTile previous tile to current(adjTile is one tile ahead of current) adjTile.gScore = calGScore; } if (!closedList.Contains(adjTile) && !openList.Contains(adjTile))//if neither of theses lists have this tile { openList.Add(adjTile);//add tile to openList } } } List<Tile> path = new List<Tile>();//create list if (closedList.Contains(destination))//if closedList destination was reached { Tile prevTile = destination;//start at the end of closedList while (prevTile != origin)//while on not at the start of closedList { path.Add(prevTile);//add a previous tile prevTile = prevTile.previousTile;//update previous tile so that it can be added the next loop } path.Add(prevTile);//add origin/start/first node to the end of the list } path.Reverse();//reverses path order return path.ToArray(); } //private void OnDrawGizmosSelected() //{ // if (debugPath == null) { return; } // Gizmos.color = Color.blue; // Vector3 drawOffset = new Vector3(0, 1.5f, 0.0f); // for (int i = 0; i < debugPath.Length - 1; ++i) // { // Gizmos.DrawLine(debugPath[i].transform.position + drawOffset, debugPath[i + 1].transform.position + drawOffset); // } //} }
34ae4a4566a62300590f8b40758f9606003ad0b6
C#
PedroNaretto/POO-grupo-5
/Console/Bitmons1/Program.cs
2.9375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Bitmons1 { public class Program { static void Main(string[] args) { Random rnd = new Random(); int filas; int columnas; int tiempo_simulacion; //datos que ingresa el usuario Console.WriteLine("Indique la configuracion inicial: "); Console.WriteLine("Indique el tamaño del mapa:"); Console.Write("Filas: "); string filasS = Console.ReadLine(); int.TryParse(filasS, out filas); while (filas.ToString() != filasS) { Console.Write("Numero de filas invalido \nFilas: "); filasS = Console.ReadLine(); int.TryParse(filasS, out filas); } Console.Write("Columnas: "); string columnasS = Console.ReadLine(); int.TryParse(columnasS, out columnas); while (columnas.ToString() != columnasS) { Console.Write("Numero de columnas invalido \nColumnas: "); columnasS = Console.ReadLine(); int.TryParse(columnasS, out columnas); } Controlador controlador = new Controlador(); Bitmons bitmons = new Bitmons(); Mapa mapa = new Mapa(); mapa.GenerarMapa(filas, columnas); bitmons.Spawn(mapa); Console.WriteLine("Configuracion inicial del mapa:"); controlador.generarMapas(mapa, bitmons); Console.ReadKey(); Console.Write("Periodo de tiempo en meses de la simulacion: "); string tiempo_simulacionS = Console.ReadLine(); int.TryParse(tiempo_simulacionS, out tiempo_simulacion); while (tiempo_simulacion.ToString() != tiempo_simulacionS) { Console.Write("Periodo de tiempo invalido \n Periodo de tiempo en meses de la simulacion: "); tiempo_simulacionS = Console.ReadLine(); int.TryParse(tiempo_simulacionS, out tiempo_simulacion); } //for de la simulacion //Ent no se pueden reproducir, cada 3 meses aparece uno //bitmon permanece un mes en un terreno con el cual tiene debilidad, entonces su tiempo de vida - 2 meses, en otro caso - 1 mes for (int meses = 1; meses <= tiempo_simulacion; meses++) { Console.WriteLine("-----------------------------"); Console.WriteLine($"Simulacion mes {meses}"); //Ent no se pueden reproducir, cada 3 meses aparece uno if (meses%3 == 0) { Bitmon bitmon = new Bitmon("Ent"); bool a = true; while (a) { int fila = rnd.Next(0, columnas+1); int colun = rnd.Next(0, filas+1); if (bitmons.bitmons_simulacion[colun, fila].Count() < 2) { bitmons.bitmons_simulacion[colun, fila].Add(bitmon); bitmons.bitmons_s.Add(bitmon); a = false; } else { continue; } } } for(int i = 0; i < filas; i++) { for (int j = 0; j < columnas; j++) { if (bitmons.bitmons_simulacion[i,j].Count() == 2) { Bitmon b1 = bitmons.bitmons_simulacion[i, j][0]; Bitmon b2 = bitmons.bitmons_simulacion[i, j][1]; if (b1.rivalidad.Contains(b2.especie)) { bitmons.Peleas(b1, b2); } else { bitmons.Relaciones(b1, b2, filas, columnas); } } } } controlador.Entorno(mapa, bitmons); bitmons.Bithalla(); bitmons.movimientos(mapa); controlador.generarMapas(mapa, bitmons); Console.ReadKey(); } Console.WriteLine("-----------------------------"); //tiempo vida promedio de bitmon double suma_tvida = 0; double total = Convert.ToDouble(bitmons.bitmons_simulacion.Length); foreach (Bitmon bitmon in bitmons.bitmons_s) { suma_tvida += bitmon.TiempoVida; } double TiempoVidaPromedio_Bit = suma_tvida / total; Console.WriteLine("Tiempo de vida promedio de los Bitmons: " + Convert.ToString(TiempoVidaPromedio_Bit)); Console.WriteLine("-----------------------------"); //tiempo de vida promedio de cada especie de bitmon float suma_tvida_taplan = 0, suma_tvida_wetar = 0, suma_tvida_gofue = 0, suma_tvida_dorvalo = 0, suma_tvida_doti = 0, suma_tvida_ent = 0; float total_taplan = 0, total_wetar = 0, total_gofue = 0, total_dorvalo = 0, total_doti = 0, total_ent = 0; foreach (Bitmon bitmon in bitmons.bitmons_s) { if (bitmon.especie == "Taplan") { suma_tvida_taplan += bitmon.TiempoVida; total_taplan += 1; } if (bitmon.especie == "Wetar") { suma_tvida_wetar += bitmon.TiempoVida; total_wetar += 1; } if (bitmon.especie == "Gofue") { suma_tvida_gofue += bitmon.TiempoVida; total_gofue += 1; } if (bitmon.especie == "Dorvalo") { suma_tvida_dorvalo += bitmon.TiempoVida; total_dorvalo += 1; } if (bitmon.especie == "Doti") { suma_tvida_doti += bitmon.TiempoVida; total_doti += 1; } if (bitmon.especie == "Ent") { suma_tvida_ent += bitmon.TiempoVida; total_ent += 1; } else { continue; } } Console.WriteLine("Tiempo de vida promedio de los Taplan: " + Convert.ToString(suma_tvida_taplan / total_taplan)); Console.WriteLine("Tiempo de vida promedio de los Wetar: " + Convert.ToString(suma_tvida_wetar / total_wetar)); Console.WriteLine("Tiempo de vida promedio de los Gofue: " + Convert.ToString(suma_tvida_gofue / total_gofue)); Console.WriteLine("Tiempo de vida promedio de los Dorvalo: " + Convert.ToString(suma_tvida_dorvalo / total_dorvalo)); Console.WriteLine("Tiempo de vida promedio de los Doti: " + Convert.ToString(suma_tvida_doti / total_doti)); Console.WriteLine("Tiempo de vida promedio de los Ent: " + Convert.ToString(suma_tvida_ent / total_ent)); Console.WriteLine("-----------------------------"); //tasa natalidad cada especie double hijos_taplan = 0, hijos_wetar = 0, hijos_gofue = 0, hijos_dorvalo = 0, hijos_doti = 0, hijos_ent = 0; foreach (Bitmon bitmon in bitmons.bitmons_s) { if (bitmon.especie == "Taplan") { if (bitmon.Hijos != 0) { hijos_taplan += Convert.ToDouble(bitmon.Hijos); } } if (bitmon.especie == "Wetar") { if (bitmon.Hijos != 0) { hijos_wetar += Convert.ToDouble(bitmon.Hijos); } } if (bitmon.especie == "Gofue") { if (bitmon.Hijos != 0) { hijos_gofue += Convert.ToDouble(bitmon.Hijos); } } if (bitmon.especie == "Dorvalo") { if (bitmon.Hijos != 0) { hijos_dorvalo += Convert.ToDouble(bitmon.Hijos); } } if (bitmon.especie == "Doti") { if (bitmon.Hijos != 0) { hijos_doti += Convert.ToDouble(bitmon.Hijos); } } if (bitmon.especie == "Ent") { if (bitmon.Hijos != 0) { hijos_ent += Convert.ToDouble(bitmon.Hijos); } } else { continue; } } Console.WriteLine("Tasa natalidad de los Taplan: " + Convert.ToString((hijos_taplan / total) * 100)); Console.WriteLine("Tasa natalidad de los Wetar: " + Convert.ToString((hijos_wetar / total) * 100)); Console.WriteLine("Tasa natalidad de los Gofue: " + Convert.ToString((hijos_gofue / total) * 100)); Console.WriteLine("Tasa natalidad de los Dorvalo: " + Convert.ToString((hijos_dorvalo / total) * 100)); Console.WriteLine("Tasa natalidad de los Doti: " + Convert.ToString((hijos_doti / total) * 100)); Console.WriteLine("Tasa natalidad de los Ent: " + Convert.ToString((hijos_ent / total) * 100)); Console.WriteLine("-----------------------------"); //tasa mortalidad cada especie double muertos_taplan = 0, muertos_wetar = 0, muertos_gofue = 0, muertos_dorvalo = 0, muertos_doti = 0, muertos_ent = 0; double total_bithalla = Convert.ToDouble(bitmons.bithalla.Count()); foreach (Bitmon bitmon in bitmons.bithalla) { if (bitmon.especie == "Taplan") { muertos_taplan += 1; } if (bitmon.especie == "Wetar") { muertos_wetar += 1; } if (bitmon.especie == "Gofue") { muertos_gofue += 1; } if (bitmon.especie == "Dorvalo") { muertos_dorvalo += 1; } if (bitmon.especie == "Doti") { muertos_doti += 1; } if (bitmon.especie == "Ent") { muertos_ent += 1; } else { continue; } } Console.WriteLine("Tasa mortalidad de los Taplan: " + Convert.ToString((muertos_taplan / total) * 100)); Console.WriteLine("Tasa mortalidad de los Wetar: " + Convert.ToString((muertos_wetar / total) * 100)); Console.WriteLine("Tasa mortalidad de los Gofue: " + Convert.ToString((muertos_gofue / total) * 100)); Console.WriteLine("Tasa mortalidad de los Dorvalo: " + Convert.ToString((muertos_dorvalo / total) * 100)); Console.WriteLine("Tasa mortalidad de los Doti: " + Convert.ToString((muertos_doti / total) * 100)); Console.WriteLine("Tasa mortalidad de los Ent: " + Convert.ToString((muertos_ent / total) * 100)); Console.WriteLine("-----------------------------"); //cantidad hijos en promedio por especie Console.WriteLine("Cantidad hijos en promedio de los Taplan: " + Convert.ToString((hijos_taplan / total_taplan) / 100)); Console.WriteLine("Cantidad hijos en promedio de los Wetar: " + Convert.ToString((hijos_wetar / total_wetar) / 100)); Console.WriteLine("Cantidad hijos en promedio Gofue: " + Convert.ToString((hijos_gofue / total_gofue) / 100)); Console.WriteLine("Cantidad hijos en promedio de los Dorvalo: " + Convert.ToString((hijos_dorvalo / total_dorvalo) / 100)); Console.WriteLine("Cantidad hijos en promedio de los Doti: " + Convert.ToString((hijos_doti / total_doti) / 100)); Console.WriteLine("Cantidad hijos en promedio de los Ent: " + Convert.ToString((hijos_ent / total_ent) / 100)); Console.WriteLine("-----------------------------"); //listado especies extintas List<string> extintas = new List<string>(); if (total_taplan == 0) { extintas.Add("Taplan"); } if (total_wetar == 0) { extintas.Add("Wetar"); } if (total_gofue == 0) { extintas.Add("Gofue"); } if (total_dorvalo == 0) { extintas.Add("Dorvalo"); } if (total_doti == 0) { extintas.Add("Doti"); } if (total_ent == 0) { extintas.Add("Ent"); } Console.WriteLine("Las especies extintas: " ); foreach(string especie in extintas) { Console.WriteLine(especie); } Console.WriteLine("-----------------------------"); //descripcion poblacion de Bitmons en bithalla (cantidad de cada especie, %) Console.WriteLine("Descripcion Taplan en bithalla: " + "cantidad: " + Convert.ToString(muertos_taplan) + Convert.ToString((muertos_taplan/total_bithalla)*100)); Console.WriteLine("Descripcion Wetar en bithalla: " + "cantidad: " + Convert.ToString(muertos_wetar) + Convert.ToString((muertos_wetar /total_bithalla)*100)); Console.WriteLine("Descripcion Gofue en bithalla: " + "cantidad: " + Convert.ToString(muertos_gofue) + Convert.ToString((muertos_gofue / total_bithalla)*100)); Console.WriteLine("Descripcion Dorvalo en bithalla: " + "cantidad: " + Convert.ToString(muertos_dorvalo) + Convert.ToString((muertos_dorvalo/total_bithalla)*100)); Console.WriteLine("Descripcion Doti en bithalla: " + "cantidad: " + Convert.ToString(muertos_doti) + Convert.ToString((muertos_doti/ total_bithalla)*100)); Console.WriteLine("Descripcion Ent en bithalla: " + "cantidad: " + Convert.ToString(muertos_ent) + Convert.ToString((muertos_ent / total_bithalla)*100)); Console.WriteLine("-----------------------------"); Console.ReadKey(); } } }
36f148f16e8c5aec7f0e77e0439f0cc302a4c89e
C#
jiowchern/GameProject1
/GameProject1-Backend.git/Regulus.Project.GameProject1.Data/Resource.cs
2.703125
3
using System; using System.Linq; namespace Regulus.Project.GameProject1.Data { public class Resource : Utility.Singleton<Resource> { public EntityData[] Entitys; public SkillData[] SkillDatas; public ItemPrototype[] Items; public ItemFormula[] Formulas; public EntityGroupLayout[] EntityGroupLayouts; public Resource() { EntityGroupLayouts = new EntityGroupLayout[0]; Entitys = new EntityData[0]; SkillDatas = new SkillData[0]; Items = new ItemPrototype[0]; Formulas = new ItemFormula[0]; } public EntityData FindEntity(ENTITY name) { return (from e in this.Entitys where e.Name == name select e).Single(); } public SkillData FindSkill(ACTOR_STATUS_TYPE name) { return (from e in this.SkillDatas where e.Id == name select e).Single(); } public ItemPrototype FindItem(string name) { return (from e in this.Items where e.Id == name select e).Single(); } public EntityGroupLayout FindEntityGroupLayout(string id) { return (from e in this.EntityGroupLayouts where e.Id == id select e).Single(); } } }
a2ec569226ab7f6334594acea3b39710b7916924
C#
denisgoriachev/eShop
/src/eShop.Domain/Entities/Purchasing/ProductPurchase.cs
2.671875
3
using eShop.Domain.ValueObjects; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace eShop.Domain.Entities.Purchasing { using static eShop.Domain.Events.ProductPurchaseEvents; public class ProductPurchase : Aggregate { public Guid ProductId { get; private set; } public Money Cost { get; private set; } private ProductPurchase() { Cost = null!; } public static ProductPurchase Create( Guid productPurchaseId, Guid productId, decimal cost, string currency, string description, string createdBy, DateTime createdAt) { Ensure.IsNotNullOrWhiteSpace("Product Purchase Description", description); Ensure.IsNotNullOrWhiteSpace("Product Purchase Creator", createdBy); var result = new ProductPurchase(); result.Apply(new V1.ProductPurchaseCreated(productPurchaseId, productId, cost, currency, description, createdBy, createdAt)); return result; } public void IncreaseCost(decimal newCost, string reason, string updatedBy, DateTime updatedAt) { if (newCost <= Cost.Value) throw new DomainException("New cost cannot be less or equal to current."); Ensure.IsNotNullOrWhiteSpace("Cost Increase Reason", reason); Ensure.IsNotNullOrWhiteSpace("Cost Increase Updater", updatedBy); Apply(new V1.ProductCostIncreased(Id, newCost, reason, updatedBy, updatedAt)); } public void DecreaseCost(decimal newCost, string reason, string updatedBy, DateTime updatedAt) { if (newCost >= Cost.Value) throw new DomainException("New cost cannot be greater or equal to current."); Ensure.IsNotNullOrWhiteSpace("Cost Increase Reason", reason); Ensure.IsNotNullOrWhiteSpace("Cost Increase Updater", updatedBy); Apply(new V1.ProductCostDecreased(Id, newCost, reason, updatedBy, updatedAt)); } protected override void When(IDomainEvent domainEvent) { switch (domainEvent) { case V1.ProductPurchaseCreated e: { Id = e.ProductPurchaseId; ProductId = e.ProductId; Cost = new Money(e.Cost, e.Currency); break; } case V1.ProductCostIncreased e: { Cost = new Money(e.NewCost, Cost.Currency); break; } case V1.ProductCostDecreased e: { Cost = new Money(e.NewCost, Cost.Currency); break; } } } } }
52b5e087b5b35b11c416bcba43b97f04386db641
C#
103pgu2020/languages
/Вильчинский Дмитрий/20.cs
3.453125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication20 { class Program { static void Main() { m: Console.Write("Введите k: "); double k = Double.Parse(Console.ReadLine()); if (k < 0) { Console.WriteLine("Ошибка! Введите другое значение!"); goto m; } double mile = 1.609344, km = 1.0; Console.WriteLine("| мили | км |"); for (double i = 1; i <= Math.Floor(k); i++) { if (i / 1.609344 < km) Console.WriteLine("|{0,6:0.0000} | {1:0.0000}|", i / mile, i); else { if (km * 1.609344 <= k) Console.WriteLine("|{0,6:0.0000} | {1:0.0000}|", km, km * mile); if (i <= k) Console.WriteLine("|{0,6:0.0000} | {1:0.0000}|", i / mile, i); km++; } } Console.WriteLine("Введите 1, чтобы повторить или другую цифру для продолжения: "); int x = Convert.ToInt32(Console.ReadLine()); if (x == 1) goto m; return; } } }
3b7d827643a44b59dcdf45a2b8c007bb65326466
C#
sjoerdteunisse/Cinema
/Cinema/Logic/StudentDiscountCalculator.cs
2.921875
3
using System; using Cinema.Domain; using Microsoft.VisualBasic; namespace Cinema.Logic { public class StudentDiscountCalculator : IOrderPriceCalculator { public double CalculatePrice(Order order) { double price = 0; var ticketCount = order.MovieTicket.Count; for (var i = 0; i < ticketCount; i++) { if (i != 0 && i + 1 <= ticketCount && (i + 1) % 2 == 0) continue; //local var to calculate with to see additions per ticket double localPrice = 0; var localTicket = order.MovieTicket[i]; if (localTicket.IsPremiumTicket) localPrice += 2; localPrice += localTicket.GetPrice(); price += localPrice; } return price; } } }
da9f476bd740e776a183bbfdcad3da8e33b90572
C#
YTRodi/Programacion-2-y-Lab-2
/Ejercicios de la guía/Métodos de extensión/Solucion_MetodosExtension_ejercicio_72/Entidades/Extension.cs
2.71875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Entidades { public static class Extension { public static string CantidadDigitos(this long digitosNumero) { string strCantDig = $"Número de: {digitosNumero.ToString().Length} dígitos"; return strCantDig; } } }
b31e36233264e0e922c13593a938149f4a454b01
C#
watermelonpizza/RgbTemperatureAlerter
/CorsairTemperatureAlert/Program.cs
2.6875
3
using RGB.NET.Core; using RGB.NET.Brushes; using RGB.NET.Devices.Corsair; using RGB.NET.Devices.Logitech; using System; using System.Threading.Tasks; using RGB.NET.Groups; using System.Linq; using System.IO.Pipes; using System.IO; using System.Reflection; using Polly; namespace CorsairTemperatureAlert { class Program { static async Task Main(string[] args) { double warnAt = 75; double dangerAt = 80; double temp = double.MinValue; double interval = .5; double seconds = 2; for (int i = 0; i < args.Length; i++) { if (args[i] == "-w" || args[i] == "--warn") { double.TryParse(args[i + 1], out warnAt); } if (args[i] == "-d" || args[i] == "--danger") { double.TryParse(args[i + 1], out dangerAt); } if (args[i] == "-i" || args[i] == "--inteval") { double.TryParse(args[i + 1], out interval); } if (args[i] == "-s" || args[i] == "--seconds") { double.TryParse(args[i + 1], out seconds); } if (args[i] == "-t" || args[i] == "--temperature") { double.TryParse(args[i + 1], out temp); } } if (temp == double.MinValue) { Console.Error.WriteLine("Temperature (`-t` or `--temperature`) is required"); return; } FileStream fileHandler = null; Policy.Handle<IOException>() .WaitAndRetry(10, _ => TimeSpan.FromSeconds(1)) .Execute( () => { fileHandler = File.Open( Path.GetFileName(Assembly.GetExecutingAssembly().Location) + "lock", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None); }); var surface = RGBSurface.Instance; surface.Exception += args => Console.WriteLine(args.Exception.Message); surface.LoadDevices(CorsairDeviceProvider.Instance); surface.LoadDevices(LogitechDeviceProvider.Instance); surface.AlignDevices(); foreach (var led in surface.Leds) Console.WriteLine($"{led.Device.DeviceInfo.DeviceName}: {led.Id}"); var group = new ListLedGroup(surface.Leds) { Brush = new SolidColorBrush(Color.Transparent) }; var decorator = new HeatWarningFlashDecorator( temp, warnAt, dangerAt, new Color(255, 255, 0), new Color(255, 0, 0), interval); group.Brush.AddDecorator(decorator); var updateTrigger = new TimerUpdateTrigger(); surface.RegisterUpdateTrigger(updateTrigger); await Task.Delay((int)Math.Floor(seconds * 1000)); await fileHandler.DisposeAsync(); } } }
55c0fed16e7c52661a49a4d93ce721c4bdf5c3f0
C#
Shreya12345608/BookStoreApplication
/BookStoreApplication/BookStoreRepository/BookStoreRepository/BookDetailsRL.cs
2.84375
3
using BookStoreModel.BooksModel; using BookStoreRepository.IBookStoreRepository; using Microsoft.Extensions.Configuration; using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Text; namespace BookStoreRepository.BookStoreRepository { public class BookDetailsRL : IBookDetailsRL { string connectionString; ///connection string public BookDetailsRL(IConfiguration configuration) { ///connection string connectionString = configuration.GetSection("ConnectionStrings").GetSection("bookStoreDB").Value; } /// <summary> /// add Book /// </summary> /// <param name="booksDetail"></param> /// <returns></returns> public object AddBookDetails(BooksModel booksDetail) { SqlConnection connection = new SqlConnection(connectionString); try { using (connection) { SqlCommand cmd = new SqlCommand("spAddBooks", connection); cmd.CommandType = CommandType.StoredProcedure; // cmd.Parameters.AddWithValue("@BookId", booksDetail.BookId); cmd.Parameters.AddWithValue("@BookName", booksDetail.BookName); cmd.Parameters.AddWithValue("@AuthorName", booksDetail.AuthorName); cmd.Parameters.AddWithValue("@Price", booksDetail.Price); cmd.Parameters.AddWithValue("@Quantity", booksDetail.Quantity); cmd.Parameters.AddWithValue("@Description", booksDetail.Description); cmd.Parameters.AddWithValue("@BookImage", booksDetail.BookImage); cmd.Parameters.AddWithValue("@Rating", booksDetail.Rating); connection.Open(); int i = cmd.ExecuteNonQuery(); connection.Close(); return true; } } catch { throw; } } /// <summary> /// get all books /// </summary> /// <returns></returns> public List<BooksModel> GetAllBooksDetails() { try { List<BooksModel> bookstorelist = new List<BooksModel>(); SqlConnection connection = new SqlConnection(connectionString); { SqlCommand command = new SqlCommand("spGetAllBooks", connection); command.CommandType = CommandType.StoredProcedure; connection.Open(); SqlDataReader sqlreader = command.ExecuteReader(); while (sqlreader.Read()) { BooksModel book = new BooksModel(); book.BookId = Convert.ToInt32(sqlreader["BookId"]); book.BookName = sqlreader["BookName"].ToString(); book.AuthorName = sqlreader["AuthorName"].ToString(); book.Price = Convert.ToDouble(sqlreader["Price"]); book.Quantity = Convert.ToInt32(sqlreader["Quantity"]); book.Description = sqlreader["Description"].ToString(); book.BookImage = sqlreader["BookImage"].ToString(); book.Rating = Convert.ToDouble(sqlreader["Rating"]); bookstorelist.Add(book); } connection.Close(); } return bookstorelist; } catch { throw; } } } }
394245d2feff25f6bd99c9171e4a7b19e8f1beff
C#
strykstaguy/pug_tools
/GomLib/Models/CodexCatByFaction.cs
2.5625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; namespace GomLib.Models { public class CodexCatByFaction: PseudoGameObject, IEquatable<CodexCatByFaction> { public string FactionName { get; set; } public Dictionary<string, Dictionary<string, long>> CdxOverviewByClass { get; set; } public Dictionary<string, Dictionary<string, Dictionary<string, long>>> PlanetValueByPlanetNameByCatNameByClassName { get; set; } public Dictionary<string, Dictionary<string, Dictionary<string, long>>> PlanetCatTotalByPlanetNameByCatNameByClassName { get; set; } public Dictionary<string, long> ClassCodexTotals { get; set; } public CodexCatByFaction() { ClassCodexTotals = new Dictionary<string, long>(); } public override bool Equals(object entry) { if (entry == null) return false; if (ReferenceEquals(this, entry)) return true; CodexCatByFaction factionTotals = entry as CodexCatByFaction; return Equals(factionTotals); } public bool Equals(CodexCatByFaction entry) { if (entry == null) return false; if (ReferenceEquals(this, entry)) return true; if (this.Id != entry.Id) return false; if (this.FactionName != entry.FactionName) return false; if (!this.CdxOverviewByClass.SequenceEqual(entry.CdxOverviewByClass)) return false; if (!this.ClassCodexTotals.SequenceEqual(entry.ClassCodexTotals)) return false; if (!this.PlanetValueByPlanetNameByCatNameByClassName.SequenceEqual(entry.PlanetValueByPlanetNameByCatNameByClassName)) return false; if (!this.PlanetCatTotalByPlanetNameByCatNameByClassName.SequenceEqual(entry.PlanetCatTotalByPlanetNameByCatNameByClassName)) return false; return true; } public override int GetHashCode() { int hash = this.Id.GetHashCode(); hash ^= this.FactionName.GetHashCode(); foreach(KeyValuePair<string, long> kvp in this.ClassCodexTotals) { hash ^= kvp.Key.GetHashCode(); hash ^= kvp.Value.GetHashCode(); } foreach (KeyValuePair<string, Dictionary<string, long>> cdxOverviewClass in CdxOverviewByClass) { hash ^= cdxOverviewClass.Key.GetHashCode(); foreach (KeyValuePair<string, long> planetTotalkvp in cdxOverviewClass.Value) { hash ^= planetTotalkvp.Key.GetHashCode(); hash ^= planetTotalkvp.Value.GetHashCode(); } } foreach (KeyValuePair<string, Dictionary<string, Dictionary<string, long>>> classCatDetailskvp in PlanetValueByPlanetNameByCatNameByClassName) { hash ^= classCatDetailskvp.Key.GetHashCode(); foreach (KeyValuePair<string, Dictionary<string, long>> planetTotalsByCatNamekvp in classCatDetailskvp.Value) { hash ^= planetTotalsByCatNamekvp.Key.GetHashCode(); foreach (KeyValuePair<string, long> planetValueByNamein in planetTotalsByCatNamekvp.Value) { hash ^= planetValueByNamein.Key.GetHashCode(); hash ^= planetValueByNamein.Value.GetHashCode(); } } } foreach (KeyValuePair<string, Dictionary<string, Dictionary<string, long>>> classPlanetDetailskvp in PlanetCatTotalByPlanetNameByCatNameByClassName) { hash ^= classPlanetDetailskvp.Key.GetHashCode(); foreach (KeyValuePair<string, Dictionary<string, long>> catDetailsDictByPlanetNamekvp in classPlanetDetailskvp.Value) { hash ^= catDetailsDictByPlanetNamekvp.Key.GetHashCode(); foreach (KeyValuePair<string, long> catValueByName in catDetailsDictByPlanetNamekvp.Value) { catValueByName.Key.GetHashCode(); catValueByName.Value.GetHashCode(); } } } return hash; } public override XElement ToXElement(bool verbose) { XElement factionElem = new XElement("Faction", new XAttribute("Id", FactionName)); XElement classTotalsElem = new XElement("CodexTotals"); foreach(KeyValuePair<string, long> ClassTotals in ClassCodexTotals) { classTotalsElem.Add(new XElement("Class", new XAttribute("Id", ClassTotals.Key), ClassTotals.Value)); } factionElem.Add(classTotalsElem); XElement cdxOverviewElement = new XElement("CodexOverview"); foreach(KeyValuePair<string, Dictionary<string, long>> cdxOverviewClass in CdxOverviewByClass) { XElement classOverview = new XElement("Class", new XAttribute("Id", cdxOverviewClass.Key)); foreach(KeyValuePair<string, long> planetTotalkvp in cdxOverviewClass.Value) { classOverview.Add(new XElement("Planet", new XAttribute("Id", planetTotalkvp.Key), planetTotalkvp.Value)); } cdxOverviewElement.Add(classOverview); } factionElem.Add(cdxOverviewElement); XElement catTotals = new XElement("CategoryPlanetTotals"); foreach (KeyValuePair<string, Dictionary<string, Dictionary<string, long>>> classCatDetailskvp in PlanetValueByPlanetNameByCatNameByClassName) { XElement classElem = new XElement("Class", new XAttribute("Id", classCatDetailskvp.Key)); foreach(KeyValuePair<string, Dictionary<string, long>> planetTotalsByCatNamekvp in classCatDetailskvp.Value) { XElement catElem = new XElement("Category", new XAttribute("Id", planetTotalsByCatNamekvp.Key)); foreach(KeyValuePair<string, long> planetValueByNamein in planetTotalsByCatNamekvp.Value) { catElem.Add(new XElement("Planet", new XAttribute("Id", planetValueByNamein.Key), planetValueByNamein.Value)); } classElem.Add(catElem); } catTotals.Add(classElem); } factionElem.Add(catTotals); XElement catContribs = new XElement("PlanetCodexCategorySource"); foreach (KeyValuePair<string, Dictionary<string, Dictionary<string, long>>> classPlanetDetailskvp in PlanetCatTotalByPlanetNameByCatNameByClassName) { XElement classElem = new XElement("Class", new XAttribute("Id", classPlanetDetailskvp.Key)); foreach(KeyValuePair<string, Dictionary<string, long>> catDetailsDictByPlanetNamekvp in classPlanetDetailskvp.Value) { XElement planetElem = new XElement("Planet", new XAttribute("Id", catDetailsDictByPlanetNamekvp.Key)); foreach(KeyValuePair<string, long> catValueByName in catDetailsDictByPlanetNamekvp.Value) { planetElem.Add(new XElement("Category", new XAttribute("Id", catValueByName.Key), catValueByName.Value)); } classElem.Add(planetElem); } catContribs.Add(classElem); } factionElem.Add(catContribs); return factionElem; } } }
00ebe1df90027a34d809ee1e327d88ae4d16b612
C#
tmatuszewski97/university-projects
/ai-programming/GraOczkoGraf/GraOczkoGraf/Wezel.cs
2.640625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GraOczkoGraf { public class Wezel { static int _licznik = 0; public int wartosc; public string kto; public int id; public int wynik; public Wezel (int wartosc, string kto) { this.wartosc = wartosc; this.kto = kto; _licznik++; id = _licznik; wynik = 666; } public override string ToString() { return kto.ToString() + " " + wartosc.ToString(); } } }
1143151aa01891866196ce9637d627f2a5d31094
C#
Oriant/TermPaper
/BLL/Services/ManagerService.cs
2.609375
3
using AutoMapper; using BLL.DTO; using BLL.Infrastructure; using BLL.Interfaces; using DAL.Entities; using DAL.Interfaces; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BLL.Services { public class ManagerService : IManagerService { IUnitOfWork Database { get; set; } public ManagerService(IUnitOfWork unitOfWork) { Database = unitOfWork; } public void ConfirmLot(int id) { Lot lot = Database.Lots.Get(id); if (lot == null) throw new DataValidationException("Lot not found", ""); lot.IsConfirmed = true; lot.StartDate = DateTime.Now; lot.FinishDate = DateTime.Now.AddMinutes(2); Database.Lots.Update(lot); Database.Save(); } public void DeclineLot(int id) { Lot lot = Database.Lots.Get(id); if (lot == null) throw new DataValidationException("Lot not found", ""); else { Database.Lots.Delete(lot); Database.Save(); } } public IEnumerable<LotDTO> GetUnconfirmedLots() { return Mapper.Map<IEnumerable<Lot>, IEnumerable<LotDTO>> (Database.Lots .GetAll() .Where(x => !x.IsConfirmed)); } } }
91af5cb49ddd3d6786c54d12a0b63bce50bf6470
C#
Spurch/ASP-.NET-WebForms
/WebFormsSampleApp/Default.aspx.cs
2.921875
3
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace WebFormsSampleApp { public partial class _Default : Page { protected void Page_Load(object sender, EventArgs e) { operationSubTitleLabel.Text = "Let's make some calculations!"; firstLabel.Text = "First value: "; secondLabel.Text = "Second value: "; resultLabel.Text = "Result: "; operationSelectLabel.Text = "Select operation: "; } protected void calculateBtn_Click(object sender, EventArgs e) { try { responseLabel.Attributes.Add("style", "display: none"); if (mathOperationSelector.SelectedValue.Equals("sum")) { resultTextBox.Text = (int.Parse(firstInputTextBox.Text) + int.Parse(secondInputTextBox.Text)).ToString(); } else { resultTextBox.Text = (int.Parse(firstInputTextBox.Text) * int.Parse(secondInputTextBox.Text)).ToString(); } } catch(Exception ex) { responseLabel.Text = "Please enter appropriate values!"; responseLabel.Attributes.Add("style", "display: block"); responseLabel.Attributes.Add("class", "label label-danger"); } } } }
2819027a937b59c86c433883ca0ce812a33ab611
C#
CYJB/Cyjb
/TestCyjb/Collections/ObjectModel/UnitTestReadOnlyListBase`1.cs
2.8125
3
using System; using System.Collections.Generic; using System.Linq; using Cyjb.Collections.ObjectModel; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace TestCyjb.Collections.ObjectModel { /// <summary> /// <see cref="ReadOnlyListBase{T}"/> ĵԪԡ /// </summary> [TestClass] public class UnitTestReadOnlyListBase { private class TestList : ReadOnlyListBase<int> { private readonly List<int> items = new(); public override int Count => items.Count; public override int IndexOf(int item) { return items.IndexOf(item); } protected override int GetItemAt(int index) { return items[index]; } public override IEnumerator<int> GetEnumerator() { return items.GetEnumerator(); } public void TestAdd(int item) { items.Add(item); } } /// <summary> /// <see cref="ReadOnlyListBase{T}"/> вԡ /// </summary> [TestMethod] public void TestReadOnlyListBase() { TestList list = new(); Assert.IsTrue(((ICollection<int>)list).IsReadOnly); Assert.AreEqual(0, list.Count); Assert.IsFalse(list.Contains(1)); list.TestAdd(1); Assert.AreEqual(1, list.Count); Assert.AreEqual(1, list[0]); Assert.IsTrue(list.Contains(1)); CollectionAssert.AreEqual(new int[] { 1 }, list.ToArray()); list.TestAdd(2); Assert.AreEqual(2, list.Count); Assert.AreEqual(1, list[0]); Assert.AreEqual(2, list[1]); Assert.IsTrue(list.Contains(1)); Assert.IsTrue(list.Contains(2)); CollectionAssert.AreEqual(new int[] { 1, 2 }, list.ToArray()); Assert.ThrowsException<NotSupportedException>(() => ((ICollection<int>)list).Add(3)); Assert.ThrowsException<NotSupportedException>(() => ((ICollection<int>)list).Remove(1)); Assert.ThrowsException<NotSupportedException>(() => ((ICollection<int>)list).Clear()); Assert.ThrowsException<NotSupportedException>(() => ((IList<int>)list).Insert(3, 3)); Assert.ThrowsException<NotSupportedException>(() => ((IList<int>)list)[4] = 3); Assert.ThrowsException<NotSupportedException>(() => ((IList<int>)list).RemoveAt(3)); } } }
fda35187071fff5c285698849cc00973e5f4f0ec
C#
siminarosioru/SQLServer_DataGridView_CSharp
/SQLServer_DataGridView_CSharp/Form1.cs
2.796875
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 System.Configuration; using System.Data.SqlClient; using System.Net.Configuration; namespace SQLServer_DataGridView_CSharp { public partial class Form1 : Form { //declare the classes + the names of the objects SqlDataAdapter sda; SqlCommandBuilder scb; DataTable dt; public Form1() { //constructor InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { } private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) { } private void buttonShowRecords_Click(object sender, EventArgs e) { //define the connection string SqlConnection connection = new SqlConnection("Data Source=DESKTOP-0U8N3MS\\MSSQLSERVER2020;Initial Catalog=MagazinDb;Integrated Security=True"); //the object instantiates the SqlDataAdapter class with arguments //specify which table (with the primary key) you will use as the first argument //and the second argument is the connection string sda = new SqlDataAdapter("SELECT * FROM Table_Users", connection); //the object instantiates the DataTable class without arguments dt = new DataTable(); //fill the data table sda.Fill(dt); //set the data source -> the dt object returns a data table dataGridView1.DataSource = dt; } private void buttonUpdateRecord_Click(object sender, EventArgs e) { //the object instantiates the SqlCommandBuilder class with argument(the sda object) scb = new SqlCommandBuilder(sda); //update the values in the database sda.Update(dt); } } }
1560ac8b3f190665e8ad03f54d1f67e989609cc3
C#
zhaoguohao/UnityEditorScripts
/Assets/Tut-5-MethodChooser/MethodChooserExample.cs
2.71875
3
using UnityEngine; using System.Collections; using System.Reflection; public class MethodChooserExample : MethodChooserExampleBase { public string strParameter; public int intParameter; void Start () { callAPublicMethod(); } public void someMethod() { Debug.Log("someMethod called"); } public void someOtherMethod(string value) { Debug.Log("someOtherMethod called with param "+value); } public void someOtherMethodWithIntParam(int value) { Debug.Log("someOtherMethod called with int param "+value); } void callAPublicMethod() { if(methods[methodToCall].GetParameters().Length<1) methods[methodToCall].Invoke(this,null); else { object p = variables[paramToCall].GetValue(this); Debug.Log("param "+p); methods[methodToCall].Invoke(this,new object[]{p }); } } }
b95b1c10a6016999d1dc677d3b751a705ce85b1b
C#
maxymnaumchyk/BSD
/Program.cs
3.265625
3
using System; using System.IO; using System.Threading; namespace ConsoleApplication205 { internal class Program { private static void Main(string[] args) { Console.Write("Robot's X: "); var x = int.Parse(Console.ReadLine()); Console.Write("Robot's Y: "); var y = int.Parse(Console.ReadLine()); var robot = new Robot { Location = new Point { X = x, Y = y } }; var robotas = new Robotas { Location = new Point { X = x+3, Y = y+2 } }; var maze = Maze.Load("c:\\1.txt"); var ai = new AI {Robot = robot, Maze = maze, Robotas = robotas}; var a = true; var b = true; do { DrawMaze(maze, robot, robotas); Thread.Sleep(200); a = ai.MakeStep(); b = ai.MakeStepas(); } while (a || b); DrawMaze(maze, robot, robotas); Console.ReadKey(); } private static void DrawMaze(Maze maze, Robot robot, Robotas robotas) { Console.Clear(); for(int row = 0;row < maze.Height;row++) { for (int col = 0; col < maze.Width; col++) switch(maze[col, row]) { case Cell.Wall: Console.Write('#'); break; case Cell.Exit: Console.Write('E'); break; default: Console.Write(' '); break; } Console.WriteLine(); } Console.SetCursorPosition(robot.Location.X, robot.Location.Y); Console.Write("*"); Console.SetCursorPosition(robotas.Location.X, robotas.Location.Y); Console.Write("*"); } } class AI { public Robot Robot; public Maze Maze; public Robotas Robotas; public bool MakeStep() { //достигли выхода? if (Maze[Robotas.Location] == Cell.Exit) return false; //получаем значение ячейки справа var left = Maze[Robotas.Location + Robotas.Direction.Rotate(-1)]; //если справа нет стены - поворачиваем направо if (left != Cell.Wall) Robotas.Direction = Robotas.Direction.Rotate(-1); else //пока впереди есть стена - поворачиваем налево while (Maze[Robotas.Location + Robotas.Direction] == Cell.Wall) Robotas.Direction = Robotas.Direction.Rotate(1); //идем вперед Robotas.GoForward(); return true; } public bool MakeStepas() { //достигли выхода? if (Maze[Robot.Location] == Cell.Exit) return false; //получаем значение ячейки слева var leftas = Maze[Robot.Location + Robot.Direction.Rotate(1)]; //если слева нет стены - поворачиваем налево if (leftas != Cell.Wall) Robot.Direction = Robot.Direction.Rotate(1); else //пока впереди есть стена - поворачиваем направо while (Maze[Robot.Location + Robot.Direction] == Cell.Wall) Robot.Direction = Robot.Direction.Rotate(-1); //идем вперед Robot.GoForward(); return true; } } public class Point { public int X; public int Y; public Point Rotate(int angle) { if (angle > 0) return new Point() { X = Y, Y = -X }; else return new Point() { X = -Y, Y = X }; } public static Point operator +(Point p1, Point p2) { return new Point {X = p1.X + p2.X, Y = p1.Y + p2.Y}; } } class Robot { public Point Location = new Point(); public Point Direction = new Point() { X = 1, Y = 0}; public void GoForward() { Location.X += Direction.X; Location.Y += Direction.Y; } } class Robotas { public Point Location = new Point(); public Point Direction = new Point() { X = 1, Y = 0}; public void GoForward() { Location.X += Direction.X; Location.Y += Direction.Y; } } class Maze { private Cell[,] Items; public static Maze Load(string filePath) { var lines = File.ReadAllLines(filePath); var res = new Maze(); res.Items = new Cell[lines[0].Length, lines.Length]; for(int row =0;row<lines.Length;row++) for(int col =0;col<lines[row].Length;col++) res.Items[col, row] = (Cell)byte.Parse(lines[row][col].ToString()); return res; } public Cell this[int col, int row] { get { return Items[col, row]; } } public Cell this[Point p] { get { return Items[p.X, p.Y]; } } public int Height{ get { return Items.GetLength(1); } } public int Width { get { return Items.GetLength(0); } } } enum Cell : byte { Empty = 0, Wall = 1, Exit = 2 } }
34c97f3ebeaa0fee8ec721a6e2613fc4135e0740
C#
Megaoski/MY-PONG
/MY_PONG/Assets/Scripts/LeftLogic.cs
2.59375
3
using System.Collections; using System.Collections.Generic; using UnityEngine; public class LeftLogic : MonoBehaviour { Ball ball; public bool Left1; public bool Left2; // Start is called before the first frame update void Start() { ball = GameObject.FindGameObjectWithTag("Ball").GetComponent<Ball>();//to call and reset the ball } // Update is called once per frame void Update() { } void OnTriggerEnter2D(Collider2D collision) { if (collision.gameObject.CompareTag("Ball")) { if(Left1) ball.LeftMovement(1); else if(Left2) ball.LeftMovement(2); Destroy(gameObject); } } }
8c94b158e662091696dee788c399f37789f5bb20
C#
ediux/tokiku2
/Tokiku.ViewModels/Finance/PaymentTypesManageViewModel.cs
2.546875
3
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; using System.Windows; using Tokiku.Controllers; using Tokiku.Entity; namespace Tokiku.ViewModels { public class PaymentTypesManageViewModelCollection : BaseViewModelCollection<PaymentTypesManageViewModel> { PaymentTypesManageController _controller; public PaymentTypesManageViewModelCollection() { } public PaymentTypesManageViewModelCollection(IEnumerable<PaymentTypesManageViewModel> source) : base(source) { } public override void Initialized() { base.Initialized(); _controller = new PaymentTypesManageController(); Query(); } public override void Query() { var result = _controller.QueryAll(); if (!result.HasError) { if (result.Result.Any()) { ClearItems(); foreach(var entity in result.Result) { PaymentTypesManageViewModel item = new PaymentTypesManageViewModel(); item.SetModel(entity); Add(item); } } } } } public class PaymentTypesManageViewModel : BaseViewModel { PaymentTypesManageController _controller; public PaymentTypesManageViewModel() { _controller = new PaymentTypesManageController(); } public PaymentTypesManageViewModel(PaymentTypesManageController controller) { _controller = controller; } /// <summary> /// 編號 /// </summary> public byte Id { get { return (byte)GetValue(IdProperty); } set { SetValue(IdProperty, value); } } // Using a DependencyProperty as the backing store for Id. This enables animation, styling, binding, etc... public static readonly DependencyProperty IdProperty = DependencyProperty.Register("Id", typeof(byte), typeof(PaymentTypesManageViewModel), new PropertyMetadata((byte)0)); /// <summary> /// 支付方式 /// </summary> public string PaymentTypeName { get { return (string)GetValue(PaymentTypeNameProperty); } set { SetValue(PaymentTypeNameProperty, value); } } // Using a DependencyProperty as the backing store for Name. This enables animation, styling, binding, etc... public static readonly DependencyProperty PaymentTypeNameProperty = DependencyProperty.Register("PaymentTypeName", typeof(string), typeof(PaymentTypesManageViewModel), new PropertyMetadata(string.Empty)); /// <summary> /// 查詢單一資料列 /// </summary> /// <param name="Key"></param> /// <returns></returns> public void Query(byte Key) { var result = _controller.Query(w => w.Id == Key); if (!result.HasError) { var k = result.Result.SingleOrDefault(); BindingFromModel(k, this); } } public override void SetModel(dynamic entity) { if (!Dispatcher.CheckAccess()) { Dispatcher.Invoke(new Action<dynamic>(SetModel), System.Windows.Threading.DispatcherPriority.Normal, entity); } else { PaymentTypes data = (PaymentTypes)entity; BindingFromModel(data, this); } } public override string ToString() { return PaymentTypeName; } } }
fe961624f759d607d5724d7c9e0e9905bb9957e5
C#
lincenses/iStudio
/Source/Studio/Configuration/ConfigurationItem.cs
2.625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Studio.Configuration { public class ConfigurationItem { #region 公有属性 #region 获取配置项的键 public string Key { get; private set; } = ""; #endregion #region 获取或设置配置项的值 public string Value { get; set; } = ""; #endregion #region 获取或设置配置项是否加密 public bool Encrypted { get; set; } = false; #endregion #region 获取所隶属的父系对象 public ConfigurationGroup Parent { get; private set; } = null; #endregion #endregion #region 构造函数 internal ConfigurationItem(string key, string value, bool encrypted, ConfigurationGroup parent) { Key = key; Value = value; Encrypted = encrypted; Parent = parent; } #endregion } }
9cf8224365632b563745b67ef86275b3d3900051
C#
raulmartinezg/Link-Oracle
/Service/Repository.cs
2.515625
3
using LinkOracle.Data; using LinkOracle.Entities; using LinkOracle.Interfaz; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace LinkOracle.Service { public class Repository : IRepository { private readonly SID_AutoCargaV3Context _context; public Repository(SID_AutoCargaV3Context context) { _context = context; } public async Task<bool> Insert(List<FolioViajeGeneral> list) { try { await _context.FolioViajeGenerals.AddRangeAsync(list); var response = _context.SaveChanges(); return response > 0; } catch (Exception ex) { throw new Exception("Verifica el servicio"); } } public async Task<bool> UpdateShip(List<TbmaeViaje> ship) { try { var c = ship.Count(); for(var i = 0; i < c; i++) { var data = _context.TbmaeViajes.FirstOrDefault(x => x.FolioViaje == ship[i].FolioViaje); if(data == null) { await _context.TbmaeViajes.AddAsync(ship[i]); _context.SaveChanges(); } } return true; } catch (Exception) { throw new Exception("Verifica el servicio"); } } public async Task<bool> UpdateStop(List<TbmaeStop> stop) { try { var e = stop.Count(); for (var j = 0; j < e; j++) { var data = _context.TbmaeStop.FirstOrDefault(x => x.ClaveViaje == stop[j].ClaveViaje && x.ShipUnitId ==stop[j].ShipUnitId); if (data == null) { await _context.TbmaeStop.AddAsync(stop[j]); _context.SaveChanges(); } } return true; } catch (Exception) { throw new Exception("Verifica el servicio"); } } public async Task<bool> UpdateLink(LinkShip stop) { try { var data = _context.TbmaeStop.FirstOrDefault(x => x.ClaveViaje == stop.ShipmentId && x.OrderRelease == stop.OrderReleaseId && x.Zone == stop.Zone); if(data == null) { throw new Exception(); } else { data.EnRuta = true; _context.TbmaeStop.Update(data); var response = await _context.SaveChangesAsync(); return response > 0; } } catch (Exception) { throw new Exception("Verifica el servicio"); } } public async Task Delete() { try { var items = _context.FolioViajeGenerals.ToList(); _context.FolioViajeGenerals.RemoveRange(items); await _context.SaveChangesAsync(); } catch (Exception e) { throw new Exception("Verifica el servicio" + e); } } } }
55881d507b85fd4d1d4263a5a6744ae055fa5111
C#
rstuannm/MVCProject
/MVCBusiness1/Repository/KhachHangRepository.cs
2.546875
3
using MVCBusiness1.DataContext; using MVCBusiness1.IRepository; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MVCBusiness1.Repository { public class KhachHangRepository : IKhachHangRepository { MVCDataContext _db = new MVCDataContext(); public bool Add(KhachHang model) { try { _db.KhachHangs.Add(model); _db.SaveChanges(); return true; } catch (Exception ex) { return false; } } public List<KhachHang> getLst() { var data = (from a in _db.KhachHangs select a).ToList(); return data; } } }
82445b612d541602ecc3d26cd170c220afdd2820
C#
hoangbd99/Project
/C#/DormitorySystem/Group2_Project/DAL/StudentDAO.cs
2.890625
3
using Group2_Project.DTL; using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; namespace Group2_Project.DAL { class StudentDAO { public static DataTable GetDataTable() { string cmd = "select * from Student"; return DAO.GetDataTable(cmd); } public static DataTable GetDataTableByUsername(string username) { string cmd = "select * from Student where username = '" + username + "'"; return DAO.GetDataTable(cmd); } public static List<Student> getStudents() { List<Student> list = new List<Student>(); SqlConnection conn = DAO.getConnections(); SqlCommand cmd = new SqlCommand("select * from Student"); cmd.Connection = conn; conn.Open(); SqlDataReader da = cmd.ExecuteReader(); while (da.Read()) { string stuID = da.GetValue(0).ToString(); string username = da.GetValue(1).ToString(); string name = da.GetValue(2).ToString(); DateTime dob = DateTime.Parse(da.GetValue(3).ToString()); int gender = int.Parse(da.GetValue(4).ToString()); string roomName = da.GetValue(5).ToString(); int bedNo = int.Parse(da.GetValue(6).ToString()); DateTime bookingDate = DateTime.Parse(da.GetValue(7).ToString()); int moneyAccount = int.Parse(da.GetValue(8).ToString()); int debt = int.Parse(da.GetValue(9).ToString()); Student hp = new Student(stuID, username, name, dob, gender, roomName, bedNo, bookingDate, moneyAccount, debt); list.Add(hp); } conn.Close(); return list; } public static Student getStudentByUsername(string username) { SqlConnection conn = DAO.getConnections(); string cmd1 = "select * from Student where username = '" + username + "'"; SqlCommand cmd = new SqlCommand(cmd1); cmd.Connection = conn; conn.Open(); SqlDataReader da = cmd.ExecuteReader(); while (da.Read()) { string stuID = da.GetValue(0).ToString(); string username1 = da.GetValue(1).ToString(); string name = da.GetValue(2).ToString(); DateTime dob = DateTime.Parse(da.GetValue(3).ToString()); int gender = int.Parse(da.GetValue(4).ToString()); string roomName = da.GetValue(5).ToString(); int bedNo = int.Parse(da.GetValue(6).ToString()); DateTime bookingDate = DateTime.Parse(da.GetValue(7).ToString()); int moneyAccount = int.Parse(da.GetValue(8).ToString()); int debt = int.Parse(da.GetValue(9).ToString()); Student hp = new Student(stuID, username1, name, dob, gender, roomName, bedNo, bookingDate, moneyAccount, debt); return hp; } conn.Close(); return null; } public static Student getStudentByStuID(string stuID) { SqlConnection conn = DAO.getConnections(); string cmd1 = "select * from Student where stuID = '" + stuID + "'"; SqlCommand cmd = new SqlCommand(cmd1); cmd.Connection = conn; conn.Open(); SqlDataReader da = cmd.ExecuteReader(); while (da.Read()) { string stuID1 = da.GetValue(0).ToString(); string username1 = da.GetValue(1).ToString(); string name = da.GetValue(2).ToString(); DateTime dob = DateTime.Parse(da.GetValue(3).ToString()); int gender = int.Parse(da.GetValue(4).ToString()); string roomName = da.GetValue(5).ToString(); int bedNo = int.Parse(da.GetValue(6).ToString()); DateTime bookingDate = DateTime.Parse(da.GetValue(7).ToString()); int moneyAccount = int.Parse(da.GetValue(8).ToString()); int debt = int.Parse(da.GetValue(9).ToString()); Student hp = new Student(stuID1, username1, name, dob, gender, roomName, bedNo, bookingDate, moneyAccount, debt); return hp; } conn.Close(); return null; } public static bool Insert(Student b) { SqlConnection conn = DAO.getConnections(); SqlCommand cmd = new SqlCommand("insert into Student(stuID,username,name, dob,gender,roomName,bedNo,bookingDate,moneyAccount,debt) values(@stuID,@username,@name, @dob,@gender,@roomName,@bedNo,@bookingDate,@moneyAccount,@debt)"); cmd.Connection = conn; cmd.Parameters.AddWithValue("@stuID", b.StuID); cmd.Parameters.AddWithValue("@username", b.Username); cmd.Parameters.AddWithValue("@name", b.Name); cmd.Parameters.AddWithValue("@dob", b.Dob); cmd.Parameters.AddWithValue("@gender", b.Gender); cmd.Parameters.AddWithValue("@roomName", b.RoomName); cmd.Parameters.AddWithValue("@bedNo", b.BedNo); cmd.Parameters.AddWithValue("@bookingDate", b.BookingDate); cmd.Parameters.AddWithValue("@moneyAccount", b.MoneyAccount); cmd.Parameters.AddWithValue("@debt", b.Debt); conn.Open(); cmd.ExecuteNonQuery(); conn.Close(); return true; } public static bool Update(Student b) { SqlCommand cmd = new SqlCommand("update Student set name=@name, dob=@dob,gender=@gender,roomName=@roomName,bedNo=@bedNo,bookingDate=@bookingDate,moneyAccount=@moneyAccount,debt=@debt where stuID=@stuID"); cmd.Parameters.AddWithValue("@name", b.Name); cmd.Parameters.AddWithValue("@dob", b.Dob); cmd.Parameters.AddWithValue("@gender", b.Gender); cmd.Parameters.AddWithValue("@roomName", b.RoomName); cmd.Parameters.AddWithValue("@bedNo", b.BedNo); cmd.Parameters.AddWithValue("@bookingDate", b.BookingDate); cmd.Parameters.AddWithValue("@moneyAccount", b.MoneyAccount); cmd.Parameters.AddWithValue("@debt", b.Debt); cmd.Parameters.AddWithValue("@stuID", b.StuID); return DAO.UpdateTable(cmd); } public static Boolean Delete(string stuID) { SqlCommand cmd = new SqlCommand("delete Student where stuID=@stuID"); cmd.Parameters.AddWithValue("@stuID", stuID); return DAO.UpdateTable(cmd); } } }
4ffed3ba917e9fe2b902ea5d3c9f7873ffc454b1
C#
yokyiii/RDIFramework.Test
/Test/ExportExcelTest.cs
2.578125
3
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using RDIFramework.Utilities; namespace RDIFramework.Test { /// <summary> /// RDIFramework.NET公共类型中的导出到Excel类的测试 /// </summary> public partial class ExportExcelTest : Form { private DataTable _table; private DataSet _dataSet; private Exporter _exporter; public ExportExcelTest() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { _exporter = new Exporter() { Company = "CSST", Subject = "books" }; LoadData(); } private void button1_Click(object sender, EventArgs e) { LoadData(); } private void LoadData() { if (_table != null) return; _table = CreateTable(1000); DataTable table2 = new DataTable("Category"); table2.Columns.Add("id"); table2.Columns.Add("name"); table2.Columns.Add("description"); for (int i = 0; i < 11; ++i) { table2.Rows.Add(i, "类型" + i.ToString(), "描述" + i.ToString()); } _dataSet = new DataSet(); _dataSet.Tables.Add(_table); _dataSet.Tables.Add(table2); this.dataGridView1.DataSource = this._table; } private DataTable CreateTable(int count) { DataTable table = new DataTable("books"); table.Columns.Add("id", typeof(int)); table.Columns.Add("title", typeof(string)); table.Columns.Add("author", typeof(string)); table.Columns.Add("publishDate", typeof(DateTime)); table.Columns.Add("quantity", typeof(int)); table.Columns.Add("unitPrice", typeof(decimal)); table.Columns.Add("isbn", typeof(string)); for (int i = 0; i < count; ++i) { table.Rows.Add(i, "图书" + i.ToString(), "作者" + i.ToString(), DateTime.Now, 99, 158, "XXXXXXXXX"); } return table; } private string GetFileName() { using (SaveFileDialog sfg = new SaveFileDialog()) { if (DialogResult.OK == sfg.ShowDialog(this)) { return sfg.FileName; } } return null; } // 导出 DataSet private void button2_Click(object sender, EventArgs e) { string fileName = GetFileName(); if (fileName != null) { try { this._exporter.NewExcel(); foreach (DataTable table in _dataSet.Tables) { DataTableExportable det = new DataTableExportable(table); this._exporter.NewSheet(table.TableName) .UnionHeader(det, null) .Union(det, null); } this._exporter.WriteTo(fileName); } finally { this._exporter.CloseExcel(); } } } // 导出 DataTable private void button3_Click(object sender, EventArgs e) { string fileName = GetFileName(); if (fileName != null) { this._exporter.ExportToExcel(_table, "books", fileName, null); } } // 导出 DataView private void button4_Click(object sender, EventArgs e) { string fileName = GetFileName(); if (fileName != null) { DataView dv = new DataView(_table); dv.RowFilter = "id % 2 <> 0"; this._exporter.ExportToExcel(dv, "books", fileName, null); } } // 过滤 private void button5_Click(object sender, EventArgs e) { string fileName = GetFileName(); if (fileName != null) { this._exporter.ExportToExcel(_table, "books", fileName, (ExportContext ctx) => { if (ctx.CellType == CellType.HeaderCell) { ctx.ColumnTag = ctx.StringValue; } if (ctx.ColumnTag as string == "publishDate") ctx.IsValid = false; }); } } // 改变表头 private void button6_Click(object sender, EventArgs e) { string fileName = GetFileName(); if (fileName != null) { this._exporter.ExportToExcel(_table, "books", fileName, (ExportContext ctx) => { if (ctx.CellType == CellType.HeaderCell) { switch (ctx.StringValue) { case "id": ctx.CellValue = "编号"; break; case "title": ctx.CellValue = "他说没错"; break; case "publishDate": ctx.CellValue = "出版日期"; break; default: break; } } }); } } // 分页 private void button7_Click(object sender, EventArgs e) { string fileName = GetFileName(); if (fileName != null) { this._exporter.ExportToExcelByPage(new DataGridViewExportable(this.dataGridView1), "books", 100, fileName, "分卷{0}.xls", null); } } // 导出 DataGridView private void button8_Click(object sender, EventArgs e) { string fileName = GetFileName(); if (fileName != null) { this._exporter.ExportToExcel(new DataGridViewExportable(this.dataGridView1), "books", fileName, (ExportContext ctx) => { if (ctx.CellType == CellType.DataCell && ctx.RowIndex % 2 == 0) ctx.IsValid = false; }); } } private void button9_Click(object sender, EventArgs e) { this._exporter.NewExcel() .NewSheet("generited") .Union(1, 10, (ExportContext ctx) => { ctx.CellValue = "一二三四五六七八九十"[ctx.ColumnIndex]; }).Union(10, 10, (ExportContext ctx)=>{ if (ctx.ColumnIndex > ctx.RowIndex) { ctx.IsValid = false; return; } ctx.CellValue = string.Format("{0,3} *{1,3} ={2,3}", ctx.RowIndex, ctx.ColumnIndex, ctx.RowIndex * ctx.ColumnIndex); }).WriteTo("d:\\rand.xls").CloseExcel(); } } }
7a2eafd80e661ce9f12badc2cc9a48cf93f297f0
C#
Nookiie/ComputerStore
/ComputerStore.Services/ProductItemService.cs
2.765625
3
using ComputerStore.Data.Data; using ComputerStore.Data.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ComputerStore.Services { public class ProductItemService : GenericService<ProductItem> { public ProductItemService(ComputerStoreDbContext context) : base(context) { categoryService = new GenericService<Category>(context); productItemCategoryService = new GenericService<ProductItemCategory>(context); } protected readonly GenericService<Category> categoryService; protected readonly GenericService<ProductItemCategory> productItemCategoryService; public async override Task<ProductItem> Create(ProductItem product) { var categoryStringList = product.Categories.ToList(); for (int i = 0; i < product.Categories.Count; i++) { categoryStringList[i] = categoryStringList[i].Replace(" ", ""); } foreach (var categoryString in categoryStringList) { if (categoryService.All().Any(x => x.Name == categoryString)) { continue; } await categoryService.Create(new Category(categoryString, "")); } await base.Create(product); // Assigning foreign keys in many-many table foreach (var categoryString in categoryStringList) { var category = categoryService.All().FirstOrDefault(x => x.Name == categoryString); if (category == null) { continue; } await productItemCategoryService.Create(new ProductItemCategory(category.ID, product.ID)); } return product; } } }
64ca9aead482ff3afa6b1e69501b97d9a89fcd08
C#
yilmazuur/SmsProject
/SmsProject.App.Operation.UnitTest/CountryOperationsTest.cs
2.734375
3
using Moq; using NUnit.Framework; using SmsProject.App.Data.DAL.Interface; using SmsProject.App.Model.Model.BusinessModel; using SmsProject.App.Operation.Interface; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SmsProject.App.Operation.UnitTest { [TestFixture] public class CountryOperationsTest { private ICountryOperations _countryOperations; private Mock<IGenericRepository<Int32, Country>> _fakeCountryRepo; private Mock<IUnitOfWork> _fakeUnitOfWork; private List<Country> _realCountries; [SetUp] public void Setup() { //Create Repo _fakeCountryRepo = new Mock<IGenericRepository<Int32, Country>>(); //Create unitOfWork and add Repo _fakeUnitOfWork = new Mock<IUnitOfWork>(); _fakeUnitOfWork.Setup(x => x.Repositories).Returns(new Dictionary<string, Object>()); _fakeUnitOfWork.Object.Repositories.Add(typeof(Country).Name, _fakeCountryRepo.Object); //Repositories mapped by entity names in unitOfWork(for detail check UnitOfWork.cs) //put mocked unitOfWork to the operation _countryOperations = new CountryOperations(_fakeUnitOfWork.Object); //get real countries from db and add it to repo memory //unit tests should not go to database, all logic should be in memory. using (var op = new CountryOperations()) { this._realCountries = op.GetAll(); } _fakeCountryRepo.Setup(r => r.All().ToList()).Returns(this._realCountries); } [Test] public void ShouldGetCountries() { List<Country> countries = _countryOperations.GetAll(); //check counts of realCountries we set earlier and the countries repo gave us Assert.AreEqual(countries.Count, this._realCountries.Count); } } }
396d94c7d64ab8bccd683247f99871e327bfe280
C#
nedjoooo/High-Qulaity-Code
/22.PhonebookSystem/PhonebookSystem/PhonebookEntry.cs
3.578125
4
namespace PhonebookSystem { using System; using System.Collections.Generic; public class PhonebookEntry : IComparable<PhonebookEntry> { private string name; public PhonebookEntry(string name) { this.Name = name; this.PhoneNumbers = new SortedSet<string>(); } public string Name { get; private set; } public SortedSet<string> PhoneNumbers { get; private set; } public override string ToString() { var joinedPhoneNumbers = string.Join(", ", this.PhoneNumbers); var entry = string.Format("[{0}: {1}]", this.Name, joinedPhoneNumbers); return entry; } public int CompareTo(PhonebookEntry other) { return string.Compare(this.name, other.name, StringComparison.InvariantCultureIgnoreCase); } } }
a207ea0bd5fb2bfbd4e3b4925486360f23d4a37f
C#
MyLegendLife/Bak.ThirdPlatforms
/src/Bak.ThirdPlatforms.Common/Helper/SqlHelper.cs
2.75
3
using Bak.ThirdPlatforms.Domain.Settings; using Microsoft.Data.SqlClient; using System; using System.Data; namespace Bak.ThirdPlatforms.Common.Helper { public class SqlHelper { public SqlHelper() { // // TODO: 在此处添加构造函数逻辑 // } /// <summary> /// 获取数据库连接字符串 /// </summary> /// <returns></returns> private static string sqlConnectionString { get { return AppSettings.Bak.ConnectionString; } } /// <summary> /// 获取数据库连接 /// </summary> /// <returns>Conn</returns> private static SqlConnection sqlConn { get { string ConnStrings = sqlConnectionString; SqlConnection Conn = new SqlConnection(); Conn.ConnectionString = ConnStrings; return Conn; } } /// <summary> /// 执行sql语句,返回DataSet /// </summary> /// <param name="sqlString">sql语句参数</param> /// <returns>DataSet</returns> public static DataSet ExecuteDataSet(string sqlString) { DataSet dsSet = new DataSet(); SqlDataAdapter adp = new SqlDataAdapter(sqlString, sqlConnectionString); try { adp.Fill(dsSet); } catch (Exception e) { throw (e); } finally { adp.Dispose(); } return dsSet; } /// <summary> /// 执行sql语句,返回DataTable /// </summary> /// <param name="sqlString">sql语句参数</param> /// <returns>DataTable</returns> public static DataTable ExecuteDataTable(string sqlString) { DataTable dt = new DataTable(); SqlDataAdapter adp = new SqlDataAdapter(sqlString, sqlConnectionString); try { adp.Fill(dt); } catch (Exception e) { throw (e); } finally { adp.Dispose(); } return dt; } /// <summary> /// 执行存储过程返回DataSet /// </summary> /// <param name="spName">存储过程名称</param> /// <param name="commandParameters">存储过程参数</param> /// <returns>DataSet</returns> public static DataSet ExecuteDataSet(string spName, SqlParameter[] commandParameters) { SqlConnection conn = sqlConn; conn.Open(); SqlCommand sqlcommand = new SqlCommand(); SqlDataAdapter adapter = new SqlDataAdapter(); DataSet dataSet = new DataSet(); sqlcommand.Connection = conn; sqlcommand.CommandText = spName; sqlcommand.CommandType = CommandType.StoredProcedure; if (commandParameters != null) { foreach (SqlParameter p in commandParameters) { if ((p.Direction == ParameterDirection.InputOutput) && (p.Value == null)) { p.Value = DBNull.Value; } sqlcommand.Parameters.Add(p); } } adapter.SelectCommand = sqlcommand; try { adapter.Fill(dataSet); } catch (Exception e) { throw (e); } finally { sqlcommand.Parameters.Clear(); sqlcommand.Dispose(); adapter.Dispose(); conn.Close(); } return dataSet; } /// <summary> /// 执行存储过程返回DataTable /// </summary> /// <param name="spName">存储过程名称</param> /// <param name="commandParameters">存储过程参数</param> /// <returns>DataTable</returns> public static DataTable ExecuteDataTable(string spName, SqlParameter[] commandParameters) { SqlConnection conn = sqlConn; conn.Open(); SqlCommand sqlcommand = new SqlCommand(); SqlDataAdapter adapter = new SqlDataAdapter(); DataTable dataTable = new DataTable(); sqlcommand.Connection = conn; sqlcommand.CommandText = spName; sqlcommand.CommandType = CommandType.StoredProcedure; if (commandParameters != null) { foreach (SqlParameter p in commandParameters) { if ((p.Direction == ParameterDirection.InputOutput) && (p.Value == null)) { p.Value = DBNull.Value; } sqlcommand.Parameters.Add(p); } } adapter.SelectCommand = sqlcommand; try { adapter.Fill(dataTable); } catch (Exception e) { throw (e); } finally { sqlcommand.Parameters.Clear(); sqlcommand.Dispose(); adapter.Dispose(); conn.Close(); } return dataTable; } /// <summary> /// 执行存储过程 /// </summary> /// <param name="spName">存储过程名称</param> /// <param name="commandParameters">存储过程参数</param> /// <returns>true or false</returns> public static bool ExecuteProcedure(string spName, SqlParameter[] commandParameters) { bool result = false; SqlConnection conn = sqlConn; conn.Open(); SqlCommand sqlcommand = new SqlCommand(); sqlcommand.Connection = conn; sqlcommand.CommandText = spName; sqlcommand.CommandType = CommandType.StoredProcedure; if (commandParameters != null) { foreach (SqlParameter p in commandParameters) { if ((p.Direction == ParameterDirection.InputOutput) && (p.Value == null)) { p.Value = DBNull.Value; } sqlcommand.Parameters.Add(p); } } try { sqlcommand.ExecuteNonQuery(); result = true; } catch (Exception e) { throw (e); } finally { sqlcommand.Parameters.Clear(); sqlcommand.Dispose(); conn.Close(); } return result; } /// <summary> /// 执行存储过程返回一个object对象 /// </summary> /// <param name="spName">存储过程名称</param> /// <param name="commandParameters">存储过程参数</param> /// <returns>object</returns> public static object ExecuteProcedures(string spName, SqlParameter[] commandParameters) { object ret = new object(); ret = DBNull.Value; SqlConnection conn = sqlConn; conn.Open(); SqlCommand sqlcommand = new SqlCommand(); sqlcommand.CommandText = spName; sqlcommand.CommandType = CommandType.StoredProcedure; if (commandParameters != null) { foreach (SqlParameter p in commandParameters) { if ((p.Direction == ParameterDirection.InputOutput) && (p.Value == null)) { p.Value = DBNull.Value; } sqlcommand.Parameters.Add(p); } } try { ret = sqlcommand.ExecuteScalar(); } catch (Exception e) { throw (e); } finally { sqlcommand.Parameters.Clear(); sqlcommand.Dispose(); conn.Close(); } return ret; } /// <summary> /// 执行sql语句,返回一个object对象 /// </summary> /// <param name="sqlString">自定义sql语句</param> /// <returns>object</returns> public static object ExecuteScalar(string sqlString) { object ret = new object(); ret = DBNull.Value; SqlConnection conn = sqlConn; conn.Open(); SqlCommand sqlcommand = new SqlCommand(sqlString, conn); try { ret = sqlcommand.ExecuteScalar(); } catch (Exception e) { throw (e); } finally { sqlcommand.Dispose(); conn.Close(); } return ret; } /// <summary> /// 执行自定义sql语句 /// </summary> /// <param name="sqlString">自定sql语句</param> /// <returns>true or false</returns> public static bool ExecuteNoQueryString(string sqlString) { bool result = false; SqlConnection conn = sqlConn; conn.Open(); SqlCommand sqlcommand = new SqlCommand(sqlString, conn); try { sqlcommand.ExecuteScalar(); result = true; } catch { result = false; } finally { sqlcommand.Dispose(); conn.Close(); } return result; } } }
8db4b35bf62475984afe80b9af80af8f26d37960
C#
TanjaDobrovoljski/HCI
/BookStore/Model/Language.cs
2.578125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BookStore.Model { class Language //da li da postavim mogucnost izbora vise jezika tj dodavanja??? { private string language = "serbian"; private int id = 2; public Language(string language) { this.language = language; } public Language(int i) { this.id = i; } public string getLanguage() { return language; } } }
38ff206179fc5bdf9c57c0e2c6c3e41b11cb3130
C#
nikolaZ/TelerikAcademy
/C#/MultidimensionalArrays/1MatrixB/MatrixB.cs
3.8125
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _1MatrixB { class MatrixB { static void Main() { int n =5; int[,] matrix = new int[n, n]; int counter = 1; for (int cols = 0; cols < n; cols++) { for (int rows = 0; rows < n; rows++) { matrix[rows, cols] = counter++; } cols++; if (cols>=n) { break; } for (int rows = n-1 ; rows >= 0; rows--) { matrix[rows, cols] = counter++; } } Console.WriteLine("The matrix is as follows:"); for (int row = 0; row < matrix.GetLength(0); row++) { for (int col = 0; col < matrix.GetLength(1); col++) { Console.Write("{0,3}" + " ", matrix[row, col]); } Console.WriteLine(); } } } }
56710841d85cd44a5b0df2de5b9d9ef7e531c510
C#
JoeHakai/CybellesCykler
/DataAccess/CommonDB.cs
2.890625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.SqlClient; using System.Data; namespace DataAccess { public class CommonDB { private readonly string connectionString = @"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog = OrderDB; Integrated Security = True; Connect Timeout = 30; Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"; public CommonDB(string connectionString) { if (String.IsNullOrWhiteSpace(connectionString)) { throw new ArgumentException(nameof(connectionString)); } try { using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); } } catch (ArgumentException) { throw; } catch (InvalidOperationException) { throw; } catch (SqlException) { throw; } this.connectionString = connectionString; } protected DataSet ExecuteQuery(string q) { DataSet ds = new DataSet(); using (SqlConnection con = new SqlConnection(connectionString)) using (SqlDataAdapter dap = new SqlDataAdapter(q, con)) { dap.Fill(ds); } return ds; } protected void ExecuteNonQuery(string q) { try { string query = "INSERT INTO Renters (Name,PhoneNumber,PhysAddress,RegisterDate)" + $"VALUES('{Name}','{PhoneNumber}','{PhysAddress}','{RegisterDate})"; using (SqlConnection connection = new SqlConnection(connectionString)) { { SqlCommand command = new SqlCommand(query, connection); command.Connection.Open(); command.ExecuteNonQuery(); } } } catch (ObjectDisposedException) { throw; } catch (InvalidOperationException) { throw; } catch (InvalidCastException) { throw; } catch (SqlException) { throw; } catch (System.IO.IOException) { throw; } } } }
79398cbaaec6442edbdfd8c3a3ddcb0ae32c4c55
C#
NikTJ777/CSNuoHarness
/TreeLoader/DataRepository.cs
2.71875
3
using System; using System.Data; using System.Data.Common; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NuoTest { class DataRepository : AbstractRepository<Data> { Logger dataLog = Logger.getLogger("DataRepository"); public DataRepository() : base("NuoTest.DATA", "groupId", "dataGuid", "instanceUID", "createdDateTime", "acquiredDateTime", "version", "active", "sizeOnDiskMB", "regionWeek") { } //@Override public override void init() { } /** * Check the uniqueness of a set of data rows. * Intended to be called prior to committing a set of new Data rows. * * This method marks any (and all) duplicate Data objects as inactive (leaving the original as active), * and returns the total number of unique rows. * * @param dataRows Map&lt;String, Data&gt; * * @return the total number of unique rows * * @throws PersistenceException */ public int checkUniqueness(Dictionary<String, Data> dataRows) { int total = dataRows.Count(); if (total == 0) return 0; Data data = dataRows.ElementAt(0).Value; //String sql = String.format(findBySql, getTableName(), "groupId", String.valueOf(data.getGroup())); long queryStart = Environment.TickCount; using (DbDataReader existing = queryBy("groupId", data.GroupId)) { dataLog.info("Uniqueness query complete; duration={0} ms", Environment.TickCount - queryStart); try { long readStart = Environment.TickCount; //for (int rx = 0; rx < total; rx++) { while (existing.Read()) { //existing.GetString(2); //if (dataRows.TryGetValue("xxyyz", out data)) if (dataRows.TryGetValue(existing.GetString(2), out data)) { data.Active = false; total--; } } dataLog.info("Uniqueness loop checked {0} items; duration={1} ms", dataRows.Values.Count, Environment.TickCount - readStart); return total; } catch (/*SQL*/ Exception e) { throw new PersistenceException(e, "Error DataRepository.checkUniqueness"); } } } //@Override protected override Data mapIn(DbDataReader row) { Data data = new Data(row.GetInt64(0), row.GetString(2)); data.GroupId = row.GetInt64(1); data.InstanceUID = row.GetString(3); data.CreatedDateTime = row.GetDateTime(4); data.AcquiredDateTime = row.GetDateTime(5); data.Version = row.GetInt16(6); data.Active = row.GetBoolean(7); data.SizeOnDiskMB = row.GetFloat(8); data.RegionWeek = row.GetString(9); return data; } //@Override protected override DataRow mapOut(Data data, SqlSession session) { DataTable table; if (! session.BatchTable.TryGetValue(tableName, out table)) { table = new DataTable(tableName); session.BatchTable[tableName] = table; table.Columns.Add("groupId", typeof(long)); table.Columns.Add("dataGuid", typeof(String)); table.Columns.Add("instanceUID", typeof(String)); table.Columns.Add("createdDateTime", typeof(DateTime)); table.Columns.Add("acquiredDateTime", typeof(DateTime)); table.Columns.Add("version", typeof(Int16)); table.Columns.Add("active", typeof(bool)); table.Columns.Add("sizeOnDiskMB", typeof(float)); table.Columns.Add("regionWeek", typeof(String)); } DataRow row = table.NewRow(); //Console.WriteLine("MapOut Data"); row[0] = data.GroupId; row[1] = data.DataGuid; row[2] = data.InstanceUID; row[3] = data.CreatedDateTime; row[4] = data.AcquiredDateTime; row[5] = data.Version; row[6] = data.Active; row[7] = data.SizeOnDiskMB; row[8] = data.RegionWeek; return row; } } }
5189292b0519bda8de34b251e37e73c108a6cf17
C#
ogolikhin/blueprint
/svc/FileStore/Helpers/MultipartPartParser.cs
2.90625
3
using ServiceLibrary.Repositories.ConfigControl; using System; using System.IO; using System.Text; using System.Text.RegularExpressions; namespace FileStore.Helpers { // NOTE: THIS CLASS WAS COPIED FROM http://www.codecutout.com/multipart-part-parser /// <summary> /// Parses a multipart/form-data stream without buffering the entire request into memory /// </summary> public class MultipartPartParser : Stream { protected IServiceLogRepository _log; /// <summary> /// Stream the multipart message is being read from /// </summary> public Stream MultipartStream { get; private set; } /// <summary> /// Encoding of the multipart stream header data /// </summary> public Encoding Encoding { get; private set; } /// <summary> /// The header element of the part /// </summary> public string Header { get; private set; } /// <summary> /// The content disposition of the part /// </summary> public string ContentDisposition { get; private set; } /// <summary> /// The content type of the part /// </summary> public string ContentType { get; private set; } /// <summary> /// The name of the form field that submitted this part /// </summary> public string Name { get; private set; } /// <summary> /// The filename if the submitted part was a file, otherwise null /// </summary> public string Filename { get; private set; } /// <summary> /// Determines if this is a full part or just a stub to indicate the /// end of the stream /// </summary> public bool IsEndPart { get; private set; } /// <summary> /// The next part in the multipart message /// </summary> protected MultipartPartParser NextPart { get; private set; } /// <summary> /// Buffer to store data extracted from the multipart stream but not yet returned /// </summary> protected MemoryStream LocalBuffer { get; private set; } /// <summary> /// The boundary between parts prependned with the newline element /// </summary> protected byte[] BoundaryWithNewLinePrepend; /// <summary> /// The bytes that represnt a new line character /// </summary> protected byte[] NewLine; public MultipartPartParser(Stream multipartStream, IServiceLogRepository log) : this(multipartStream, Encoding.UTF8, log) { } public MultipartPartParser(Stream multipartStream, Encoding encoding, IServiceLogRepository log, MemoryStream buffer = null) { this.MultipartStream = multipartStream; this.Encoding = encoding; this._log = log; LocalBuffer = new MemoryStream(); if (buffer != null) buffer.CopyTo(LocalBuffer); LocalBuffer.Position = 0; NewLine = Encoding.GetBytes("\r\n"); var DoubleNewLine = Encoding.GetBytes("\r\n\r\n"); // set boundary to empty for now, we dont know what it is until we process our header BoundaryWithNewLinePrepend = new byte[0]; byte[] headerBytes = new byte[1024]; int headerBytesRead = this.Read(headerBytes, 0, headerBytes.Length); int boundaryEnd; if (!SearchBytePattern(NewLine, headerBytes, out boundaryEnd)) throw new Exception("No multipart boundary found. Data must begin with a content boundary"); // copy our boundary so we can use it BoundaryWithNewLinePrepend = new byte[boundaryEnd + NewLine.Length]; Buffer.BlockCopy(NewLine, 0, BoundaryWithNewLinePrepend, 0, NewLine.Length); Buffer.BlockCopy(headerBytes, 0, BoundaryWithNewLinePrepend, NewLine.Length, boundaryEnd); // if we have reached the end of our stream at the end of our header then // this is the end of multipart part, we label this as the end part and return // we know we have reached the end when the number bytes we read was our header // plus our search pattern (newline) if (headerBytesRead == boundaryEnd + NewLine.Length) { IsEndPart = true; return; } int headerEnd; if (!SearchBytePattern(DoubleNewLine, headerBytes, boundaryEnd, out headerEnd)) { // if we cant find the end of the header it could mean our header is massive // and it wasnt in the initial block of bytes we read. throw new Exception("Content header is too large to process"); } headerEnd += DoubleNewLine.Length; // get the header and header derived fields Header = encoding.GetString(headerBytes, boundaryEnd, headerEnd - boundaryEnd).Trim(); ContentDisposition = RegexFirstGroup(Header, "^Content-Disposition:(.*)$"); ContentType = RegexFirstGroup(Header, "^Content-Type:(.*)$"); Filename = RegexFirstGroup(ContentDisposition, @"filename=""(.*?)"""); Name = RegexFirstGroup(ContentDisposition, @"name=""(.*?)"""); int CountOfNonHeaderBytes = headerBytesRead - headerEnd; // put back the extra non header content so it can be streamed out again ReinsertIntoLocalBuffer(headerBytes, headerEnd, CountOfNonHeaderBytes); } /// <summary> /// Re-Buffers data extracted from the read /// </summary> /// <param name="source"></param> /// <param name="offset"></param> /// <param name="count"></param> protected void ReinsertIntoLocalBuffer(byte[] source, int offset, int count) { // we have our header, but we potentially have read more than we need to // we have two cases // 1. we have exhausted our LocalBuffer and some of the data came from the MultipartStream // in this case we will reset our local buffer and write our remaining bytes back into // our local buffer // 2. We did not exhaust our local buffer, in which case the remaining bytes are still in // the local buffer so we will just rewind it so they are picked up next read if (LocalBuffer.Position == LocalBuffer.Length) { LocalBuffer.Position = 0; LocalBuffer.SetLength(0); LocalBuffer.Write(source, offset, count); LocalBuffer.Position = 0; } else { LocalBuffer.Position -= count; } } /// <summary> /// Helper method to easily get the first group of a regex expresion /// </summary> /// <param name="input"></param> /// <param name="pattern"></param> /// <returns></returns> private string RegexFirstGroup(string input, string pattern) { var match = Regex.Match(input, pattern, RegexOptions.Multiline); if (match.Success) return match.Groups[1].Value.Trim(); return null; } public override sealed int Read(byte[] buffer, int offset, int count) { MultipartPartParser nextPart; return ReadForNextPart(buffer, offset, count, out nextPart); } /// <summary> /// Moves the stream foward until a new part is found /// </summary> /// <param name="bufferSize"></param> /// <returns></returns> public MultipartPartParser ReadUntilNextPart(int bufferSize = 4096) { byte[] throwawayBuffer = new byte[bufferSize]; MultipartPartParser nextpart; while (ReadForNextPart(throwawayBuffer, 0, bufferSize, out nextpart) > 0) { } return nextpart; } /// <summary> /// Reads the stream, if this part has completed the nextpart is returned /// </summary> /// <param name="buffer"></param> /// <param name="offset"></param> /// <param name="count"></param> /// <param name="nextpart"></param> /// <returns></returns> public int ReadForNextPart(byte[] buffer, int offset, int count, out MultipartPartParser nextpart) { // If we have found our next part we have already finsihed this part and should stop here if (NextPart != null || IsEndPart) { nextpart = NextPart; return 0; } // the search buffer is the place where we will scan for part bounderies. We need it to be just // a bit bigger than than the size requested, to ensure we dont accidnetly send part of a boundary // without realising it byte[] searchBuffer = new byte[count + BoundaryWithNewLinePrepend.Length]; int bytesReadThisCall = 0; // first read from our local buffer int bytesToReadFromLocalBuffer = Math.Min((int)LocalBuffer.Length, searchBuffer.Length); if (bytesToReadFromLocalBuffer > 0) { bytesReadThisCall += LocalBuffer.Read(searchBuffer, bytesReadThisCall, bytesToReadFromLocalBuffer); } // if we could not fill our search buffer with our local buffer then read from the multipart stream int bytesToReadFromStream = searchBuffer.Length - bytesReadThisCall; bytesToReadFromStream = Math.Min(bytesToReadFromStream, (int)MultipartStream.Length - (int)MultipartStream.Position); if (bytesToReadFromStream > 0) { bytesReadThisCall += MultipartStream.Read(searchBuffer, bytesReadThisCall, bytesToReadFromStream); } // the number of bytes returned will be one of three cases // 1. There is still plenty to return so we will return the 'count' they asked for // 2. We have emptied the stream, we will return the bytes read // 3. We have run into a new boundary, we will return the bytes up to the boundary end int bytesReturned; bool isEndOfPart = SearchBytePattern(BoundaryWithNewLinePrepend, searchBuffer, out bytesReturned); // we can only return the parts we know for sure are not part of the next boundary // which is the bytes we read minus the boundary length. This will also ensure we // get back to the count we were originally asked for. We also need to make sure we // return 0 bytes if we can not gaurentee there are no boundaries parts in what we // did manage to read if (!isEndOfPart) bytesReturned = Math.Max(0, bytesReadThisCall - BoundaryWithNewLinePrepend.Length); Buffer.BlockCopy(searchBuffer, 0, buffer, offset, bytesReturned); // We need to handle the bytes that did not get returned by putting them back into // the local buffer int bytesNotReturned = bytesReadThisCall - bytesReturned; ReinsertIntoLocalBuffer(searchBuffer, bytesReturned, bytesNotReturned); nextpart = null; if (isEndOfPart) { // the boundary we were looking for had a newline appended to it // we dont want to send the newline to the next part so we will skip LocalBuffer.Position += NewLine.Length; NextPart = new MultipartPartParser(MultipartStream, Encoding, _log, LocalBuffer); // The next part may actually just the be end indicator, if thats the case // we will null it and not return it if (NextPart.IsEndPart) NextPart = null; nextpart = NextPart; } return bytesReturned; } /// <summary> /// Searches for a byte pattern in a block of bytes /// </summary> /// <param name="pattern"></param> /// <param name="bytes"></param> /// <param name="matchStartIndex"></param> /// <returns></returns> protected bool SearchBytePattern(byte[] pattern, byte[] bytes, out int matchStartIndex) { return SearchBytePattern(pattern, bytes, 0, out matchStartIndex); } /// <summary> /// Searches for a byte pattern in a block of bytes /// </summary> /// <param name="pattern"></param> /// <param name="bytes"></param> /// <param name="searchOffset"></param> /// <param name="matchStartIndex"></param> /// <returns></returns> protected bool SearchBytePattern(byte[] pattern, byte[] bytes, int searchOffset, out int matchStartIndex) { if (pattern == null || pattern.Length == 0 || bytes == null || bytes.Length == 0) { matchStartIndex = -1; return false; } matchStartIndex = Array.IndexOf<byte>(bytes, pattern[0]); int searchUpToIndex = bytes.Length - pattern.Length; while (matchStartIndex >= 0 && matchStartIndex < searchUpToIndex) { bool ismatch = true; for (int j = 1; j < pattern.Length && ismatch == true; j++) { if (bytes[matchStartIndex + j] != pattern[j]) ismatch = false; } if (ismatch) return true; matchStartIndex = Array.IndexOf<byte>(bytes, pattern[0], matchStartIndex + 1); } matchStartIndex = -1; return false; } public override bool CanRead { get { return true; } } public override bool CanSeek { get { return false; } } public override bool CanWrite { get { return false; } } public override void Flush() { } public override long Length { get { throw new NotSupportedException(); } } public override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } public override void SetLength(long value) { throw new NotSupportedException(); } public override void Write(byte[] buffer, int offset, int count) { throw new NotSupportedException(); } } }
08e2f21dafbf26dd1877465ac416fb727226633b
C#
thaynaramara28/DotnetFramework
/DotnetFrameworkMedia/Program.cs
3.171875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DotnetFrameworkMedia { class Program { static void Main(string[] args) { for (int i = 1; i<=4; i++) { Console.WriteLine("Digite o nome do " + i + " º aluno: "); string aluno1 = Convert.ToString(Console.ReadLine()); Console.WriteLine("Digite a primeira nota"); double nota1 = Convert.ToDouble(Console.ReadLine()); Console.WriteLine("Digite a segunda nota"); double nota2 = Convert.ToDouble(Console.ReadLine()); Console.WriteLine("Digite a terceira nota"); double nota3 = Convert.ToDouble(Console.ReadLine()); double soma = nota1 + nota2 + nota3; Console.WriteLine("A média da nota de: " + aluno1 + " é: " + (soma / 3)); Console.ReadLine(); } } } }
c6a0acb96b579f24c6b8c87290cfb40d7d0e1ba2
C#
cdart1/Problem_solving_algorithm_practice
/LeetCode_problems/LeetCode_Problems _C-Sharp/GreatestNumOfCandies/GreatestNumOfCandiesProblem.cs
4.125
4
using System; using System.Collections.Generic; using System.Text; namespace GreatestNumOfCandies { /* Steps: * 1. Find the greatest number in the array 'candies'. * 2. If we add three more candies to each kid's current number of candies, * would it be 5 or greater --> T or F. */ class GreatestNumOfCandiesProblem { public static int FindHighest(int[] candies) { int highest = 0; for (int i = 0; i < candies.Length; i++) { if (candies[i] > highest) { highest = candies[i]; } } return highest; } public static void GreatestNumOfCandies(int[] candies, int extraCandies) { int highest = FindHighest(candies); bool hasGreatest = false; foreach (int i in candies) { if (i + extraCandies >= highest) { hasGreatest = true; Console.Write(hasGreatest); } else { hasGreatest = false; Console.Write(hasGreatest); } } } } }
2f422b89de380ceeb34919d1ae9d086f00619d03
C#
arnelambrosio/practical-Xunit
/PracticalXUnitTestProject.Test/UnitTest1.cs
2.984375
3
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using Xunit; namespace ProductsApp.Tests { public class ProductsAppShould { // Add your test here [Fact] public void Return_argument_null_exception_when_product_is_null() { //arrange var sut = new Products(); Product product = null; //act var exception = Assert.Throws<ArgumentNullException>(() => sut.AddNew(product)); //assert Assert.NotNull(exception); Assert.IsType<ArgumentNullException>(exception); } [Fact] public void Add_product_should_store_the_item_in_the_list() { //arrange var sut = new Products(); var product01 = new Product() { Name = "Test 101", IsSold = false }; var product02 = new Product() { Name = "Test 102", IsSold = false }; //act sut.AddNew(product01); sut.AddNew(product02); //assert Assert.NotNull(sut.Items); Assert.Equal(2, sut.Items.Count()); } [Fact] public void Sold_product_should_update_the_item_status_in_the_list() { //arrange var sut = new Products(); var product01 = new Product() { Name = "Test 101", IsSold = false }; var product02 = new Product() { Name = "Test 102", IsSold = false }; var product03 = new Product() { Name = "Test 103", IsSold = false }; //act sut.AddNew(product01); sut.AddNew(product02); sut.AddNew(product03); sut.Sold(product01); //assert Assert.True(product01.IsSold); Assert.NotNull(sut.Items); Assert.Equal(2, sut.Items.Count()); } [Fact] public void Return_namerequiredexception_when_product_name_is_null() { //arrange var product = new Product() { Name = null, IsSold = false }; //act var exception = Assert.Throws<NameRequiredException>(() => product.Validate()); //assert Assert.NotNull(exception); Assert.IsType<NameRequiredException>(exception); } } internal class Products { private readonly List<Product> _products = new List<Product> (); public IEnumerable<Product> Items => _products.Where (t => !t.IsSold); public void AddNew (Product product) { product = product ?? throw new ArgumentNullException (); product.Validate (); _products.Add (product); } public void Sold (Product product) { product.IsSold = true; } } internal class Product { public bool IsSold { get; set; } public string Name { get; set; } internal void Validate () { Name = Name ?? throw new NameRequiredException (); } } [Serializable] internal class NameRequiredException : Exception { public NameRequiredException () { /* ... */ } public NameRequiredException (string message) : base (message) { /* ... */ } public NameRequiredException (string message, Exception innerException) : base (message, innerException) { /* ... */ } protected NameRequiredException (SerializationInfo info, StreamingContext context) : base (info, context) { /* ... */ } } }
82108335596f4f9c2c7d285b30c1d1db36e0789e
C#
NateGh/PeopleManager
/PeopleManager/PeopleManager.Data/Repositories/RepositoryBase.cs
3.015625
3
using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; namespace PeopleManager.Data.Repositories { public abstract class RepositoryBase<T> : IRepositoryBase<T> where T : class { protected readonly DbContext _context; protected readonly DbSet<T> _entities; public RepositoryBase(DbContext context) { _context = context; _entities = _context.Set<T>(); } public async Task<T> AddAsync(T entity) { await _entities.AddAsync(entity); await _context.SaveChangesAsync(); return entity; } public IEnumerable<T> Find(Expression<Func<T, bool>> predicate) { return _entities.Where(predicate); } public async Task<T> GetAsync(Guid id) { return await _entities.FindAsync(id); } public async Task<IEnumerable<T>> GetAllAsync() { return await _entities.ToListAsync(); } public void Remove(T entity) { _entities.Remove(entity); } } }
3599e4669f275d96e1856265641e2ec55e8526dc
C#
shendongnian/download4
/code9/1627126-45837325-154587398-6.cs
3.390625
3
public async Task MyAsyncMethod() { // Do your stuff that takes a long time } public async Task CallMyAsyncMethod() { // We can await Tasks, regardless of where they come from. await MyAsyncMethod(); }
ba589de69a39c7943ad4dc54c8c8d16110014073
C#
destinygit/Web_App_.Net_Bootstraap_library
/adminlogin.aspx.cs
2.78125
3
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Windows.Forms; namespace e_Library_mgmt { public partial class WebForm1 : System.Web.UI.Page { string Conx = ConfigurationManager.ConnectionStrings["cLibrary"].ConnectionString; protected void Page_Load(object sender, EventArgs e) { Session["role"] = ""; } protected void Button1_Click(object sender, EventArgs e) { SqlConnection Connx = new SqlConnection(Conx); try { //Conx stores the name of the server, the database we want to connect to, the username and password to connct to, provide that informatio to the "SqlConnection(Conx)" object, intergrated security means i am using the windows authentication if (Connx.State == ConnectionState.Closed) { Connx.Open(); } SqlCommand cmd = new SqlCommand("Select * from Admin_Login_tbl where " + "Admin_Id = '" + Texbox1.Text.Trim() + "' And Password='" + TextBox2.Text.Trim() + "';", Connx); //Execute this command that selects all records from the table, where the adminid and password has to be equal to the entry SqlDataReader dr = cmd.ExecuteReader(); // Execute the command, using the con object and return or retrieve the data if (dr.HasRows) //Returns the data returned, if it has rows { while (dr.Read()) //and while it reads and retrive the row with the relevant data, respond 'login Successful, then redirect to homepage { Response.Write("<script>alert('Login Successful' '"+ dr.GetValue(0).ToString()+"');</script>"); Session["Admin_Id"] = dr.GetValue(0).ToString(); //Sessin Variable, global to the entire project, store these values and active within 20 min of being idle Session["Full_Name"] = dr.GetValue(2).ToString(); Session["role"] = "admin"; Response.Redirect("homepage.aspx", false); } } else { Response.Write("<script>alert('Invalid Credentials');</script>"); } } catch (Exception ex) { // MessageBox.Show(ex.Message); Console.WriteLine("Error on ButtonClick " + ex.Message); } finally { Connx.Close(); } } } }
1ec5fef579cf87fc58c2fa169739169033478522
C#
KoseiYoshida/EasySlackEmojiCreator
/SlackEmojiCreator/TextImage.cs
3.078125
3
using SlackEmojiCreator.Utility; using System; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Media.Imaging; namespace SlackEmojiCreator { /// <summary> /// Text to be able to capture as image. /// </summary> public sealed class TextImage { private readonly TextBlock targetTextBlock; private readonly FrameworkElement captureElement; public FontFamily FontFamily = new FontFamily("impact"); public Color Color = Color.FromRgb(0, 0, 0); /// <summary> /// Constructor. /// </summary> /// <param name="targetTextBlock">Text</param> /// <param name="captureElement">Capture frame</param> /// <exception cref="ArgumentNullException">Throw if <paramref name="targetTextBlock"/> is null.</exception> /// <exception cref="ArgumentNullException">Throw if <paramref name="captureElement"/> is null.</exception> public TextImage(TextBlock targetTextBlock, FrameworkElement captureElement) { this.targetTextBlock = targetTextBlock ?? throw new ArgumentNullException(nameof(targetTextBlock)); this.captureElement = captureElement ?? throw new ArgumentNullException(nameof(captureElement)); } /// <summary> /// Get current text. /// </summary> /// <returns>Text</returns> public string GetText() { return targetTextBlock.Text; } /// <summary> /// Update text. /// </summary> /// <param name="newText">New text</param> public void UpdateText(string newText) { targetTextBlock.Text = newText; targetTextBlock.FontFamily = FontFamily; targetTextBlock.Foreground = new SolidColorBrush(Color); } /// <summary> /// Capture text as image. /// </summary> /// <param name="bitmapSource">Captured image</param> /// <returns>True if capture succeeded.</returns> /// <remarks><paramref name="bitmapSource"/> will be null if capture failed.</remarks> public bool TryCaptureAsImage(out BitmapSource bitmapSource) { bitmapSource = null; try { bitmapSource = ImageUtility.CaptureFrameworkElement(captureElement); return true; } catch(Exception ex) { Console.WriteLine($"Capture failed. Error message : {ex.Message}"); return false; } } } }
7fe88e9ec6a8eba1cc0f9ba978a597f298033f9d
C#
cazacov/AdventOfCode2020
/Day_18_2/Code/Calculator.cs
3.5
4
using System; using System.Collections.Generic; using System.Linq; namespace Day_18_2 { public class Calculator { private readonly List<string> tokens; public Calculator(string str) { var tok = new List<string>(); var pos = 0; do { var result = String.Empty; while (char.IsWhiteSpace(str[pos])) { pos++; } while (pos < str.Length) { result += str[pos]; pos++; if ("()+-".Contains(result)) { break; } if (pos >= str.Length || " ()+-".Contains(str[pos])) { break; } } tok.Add(result); } while (pos < str.Length); // Reverse tokens this.tokens = new List<string>(); foreach (var t in tok) { switch (t) { case "(": tokens.Insert(0, ")"); break; case ")": tokens.Insert(0, "("); break; default: tokens.Insert(0, t); break; } } } private string NextToken() { if (this.tokens.Count == 0) { return string.Empty; } var result = this.tokens.First(); this.tokens.RemoveAt(0); return result; } private void UndoToken(string token) { this.tokens.Insert(0, token); } private Expression ParseSimple() { var token = NextToken(); if (char.IsDigit(token[0])) { return new Expression(token); } if (token == "(") { var result = Parse(); if (NextToken() != ")") { throw new ApplicationException("Wrong input, ')' expected"); } return result; } var arguments = ParseSimple(); return new Expression(token, arguments); } private int Priority(string token) { return token switch { "+" => 2, "*" => 1, _ => 0 }; } private Expression ParseBinary(int minPriority) { var left = ParseSimple(); while (true) { var operation = NextToken(); if (operation == String.Empty) { return left; } if (operation == ")") { UndoToken(operation); return left; } var prio = Priority(operation); if (prio < minPriority) { UndoToken(operation); return left; } var right = ParseBinary(prio); left = new Expression(operation, left, right); } } private Expression Parse() { return ParseBinary(0); } public long Evaluate() { var ex = Parse(); return ex.Value; } } }
bd046c3f2bea5641b02d3615f0445d6a8e9fc56b
C#
fornetjob/InfinitySpace
/InfinitySpace/Assets/Game/Core/MappingAttribute.cs
3.25
3
namespace Assets.Game.Core { /// <summary> /// Атрибут для кешируемых компонентов /// </summary> public class MappingAttribute:System.Attribute { #region Ctor /// <summary> /// Кешировать дочерний компонент по его названию /// </summary> public MappingAttribute() : this(string.Empty) { } /// <summary> /// Кешировать дочерний компонент по указанному пути /// </summary> /// <param name="path">Путь до дочернего компонента</param> public MappingAttribute(string path) { Path = path; } #endregion #region Properties /// <summary> /// Абсолютный путь до компонента. Проверьте, что объект не является скрытым, иначе маппинга не произойдёт. /// </summary> public string AbsolutePath; /// <summary> /// Путь до дочернего компонента /// </summary> public string Path; /// <summary> /// Компонент может отсутствовать /// </summary> public bool CanEmpty; #endregion } }
cba6f6b32d1479ebe84b0e730665cc07bab6e753
C#
lvi1901/device_shop
/DeviceShop.Core/Repos/DeviceRepository.cs
2.625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using AutoMapper; using DeviceShop.Core.Entities; using DeviceShop.Core.Infrastructure; namespace DeviceShop.Core.Repos { public class DeviceRepository : IDeviceRepository { private readonly AppDbContext appDbContext; private readonly IEnumerable<DeviceDto> devices; public DeviceRepository(AppDbContext appDbContext) { this.appDbContext = appDbContext; devices = Mapper.Map<IEnumerable<DeviceDto>>(appDbContext.Devices); } public IEnumerable<DeviceDto> GetAll() => devices; public DeviceDto GetById(Guid id) => devices.FirstOrDefault(r => r.Id == id); } }
47ade9692674b91ae057022312e3f624e42dcc48
C#
pirahawk/bog-api
/Bog.Api.Web/Formatters/EntryContentFormatter.cs
2.578125
3
using Bog.Api.Domain.Models.Http; using Bog.Api.Domain.Values; using Microsoft.AspNetCore.Mvc.Formatters; using Microsoft.Net.Http.Headers; using System; using System.Text; using System.Threading.Tasks; namespace Bog.Api.Web.Formatters { public class EntryContentFormatter : TextInputFormatter { public EntryContentFormatter() { SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse(MediaTypesValueObject.TEXT_PLAIN)); } protected override object GetDefaultValueForType(Type modelType) { return CheckType(modelType)? null : base.GetDefaultValueForType(modelType); } public override bool CanRead(InputFormatterContext context) { return CanReadType(context.ModelType); } protected override bool CanReadType(Type type) { return CheckType(type); } public override async Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context, Encoding encoding) { return await ReadRequestBodyAsync(context); } public override async Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context) { return await ReadAsync(context); } public override async Task<InputFormatterResult> ReadAsync(InputFormatterContext context) { var httpContextRequest = context.HttpContext.Request; if (!httpContextRequest.ContentLength.HasValue || httpContextRequest.ContentLength == 0) { return await InputFormatterResult.FailureAsync(); } using (var reader = context.ReaderFactory(httpContextRequest.Body, Encoding.UTF8)) { var blogPost = new ArticleEntry(); string readToEndAsync = await reader.ReadToEndAsync(); blogPost.Content = readToEndAsync; return await InputFormatterResult.SuccessAsync(blogPost); } } private static bool CheckType(Type type) { return typeof(ArticleEntry).IsAssignableFrom(type); } } }
05c3ec0af8e3e8bbe320c03005cbcf6dd62ea1db
C#
shendongnian/download4
/first_version_download2/97815-6563572-14313330-4.cs
2.921875
3
string val; if(dictionary.TryGetValue("mykey", out val)) { //The key was found. The value is in val. } else { //The key was not present. }
b97a045c25a9b4c4a0924bde921f1409184c0440
C#
arslanaybars/ayb.miniprofiler.sample
/src/Data/Student.cs
2.65625
3
using System; using System.Collections.Generic; namespace Data { public class Student { public Student() { Name = Guid.NewGuid().ToString().Replace("-", string.Empty).Substring(0, 8); Address = new StudentAddress(); } public int Id { get; set; } public string Name { get; set; } public StudentAddress Address { get; set; } public IList<StudentCourse> StudentCourses { get; set; } } }
45de1c5942514c2ad8fa7dfd609f76b0b3ac793d
C#
Badmodo/Frameworks
/Assets/Framework/Scripts/InsertionSort/BaseSorter.cs
2.90625
3
using Sorting.Visualization; using System.Collections; using UnityEngine; namespace StatsFramework { // Sort algorithm base class public abstract class BaseSorter : MonoBehaviour { protected Visualizer visualizer; protected Node[] nodes; void Start() { visualizer = Visualizer.Instance; nodes = visualizer.Nodes; } // Run sorting algorithm public void RunSorter() { StartCoroutine(SortAscending()); } // Sorting coroutine protected abstract IEnumerator SortAscending(); // Swap nodes at 2 indexes protected void SwapNodes(int indexA, int indexB) { Node temp = nodes[indexA]; nodes[indexA] = nodes[indexB]; nodes[indexB] = temp; } // Highlight node to blue color protected void HighlightNodeBlue(int _node, bool isHighlighted) { visualizer.HighlightNodeBlue(_node, isHighlighted); //visualizer.SetNodes(nodes); } // Highlight node to red color protected void HighlightNodeRed(int _node, bool isHighlighted) { visualizer.HighlightNodeRed(_node, isHighlighted); //visualizer.SetNodes(nodes); } // Tell visualizer to updata visuals protected void UpdateNodes () { visualizer.SetNodes(nodes); } // Debug function for printing all node values protected void PrintNodes(int low, int high) { string log = ""; for (int i = low; i <= high; i++) { log = log + "[" + i + "] = " + nodes[i].Value + ", "; } Debug.Log(log); } } }
da5c513f370465fd5ada92b79dbfc3f0b420bec9
C#
kitofr/Cone
/Source/Expectations/BooleanExpect.cs
2.765625
3
using System; using System.Linq.Expressions; using System.Reflection; using Cone.Core; namespace Cone.Expectations { public interface IExpectValue { object Value { get; } string ToString(IFormatter<object> formatter); } public class ExpectValue : IExpectValue { readonly object value; public ExpectValue(object value) { this.value = value; } public object Value { get { return value; } } public string ToString(IFormatter<object> formatter) { return formatter.Format(Value); } public override string ToString() { return Value.ToString(); } } public class BooleanExpect : IExpect { readonly protected Expression body; readonly IExpectValue actual; public BooleanExpect(Expression body, IExpectValue actual) { if(actual == null) throw new ArgumentNullException("actual"); this.body = body; this.actual = actual; } public virtual string FormatExpression(IFormatter<Expression> formatter) { return formatter.Format(body); } public virtual string FormatMessage(IFormatter<object> formatter) { return string.Format(MessageFormat, FormatActual(formatter), FormatExpected(formatter)); } public string FormatActual(IFormatter<object> formatter) { return Actual.ToString(formatter); } public string FormatExpected(IFormatter<object> formatter) { return Expected.ToString(formatter); } public CheckResult Check() { return new CheckResult(CheckCore(), Maybe<object>.Some(ActualValue), Maybe<object>.Some(ExpectedValue)); } public virtual object ActualValue { get { return actual.Value; } } public object ExpectedValue { get { return Expected.Value; } } public virtual string MessageFormat { get { return ExpectMessages.EqualFormat; } } IExpectValue Actual { get { return actual; } } protected virtual IExpectValue Expected { get { return new ExpectValue(true); } } protected virtual bool CheckCore() { if(ActualValue != null) return ActualValue.Equals(ExpectedValue); return ExpectedValue.Equals(ActualValue); } } class ConversionExpect : BooleanExpect { readonly MethodInfo conversion; public ConversionExpect(Expression body, object actual, MethodInfo conversion) : base(body, new ExpectValue(actual)) { this.conversion = conversion; } protected override bool CheckCore() { if(ActualValue != null) return conversion.Invoke(null, new[]{ ActualValue }).Equals(ExpectedValue); return ExpectedValue.Equals(ActualValue); } } public class Expect : BooleanExpect { readonly IExpectValue expected; public Expect(Expression body, IExpectValue actual, IExpectValue expected) : base(body, actual) { this.expected = expected.Value != null ? expected : new ExpectValue(ExpectedNull.IsNull); } protected override IExpectValue Expected { get { return expected; } } } }
79136a358e3f8399a1ca5f3c6fb73ba385c5095a
C#
piotr-wyszkowski-chr/ChrWawCodingDojo
/Coding Dojo 17/Next smaller number/KataTests.cs
2.984375
3
using FluentAssertions; using Xunit; namespace Next_smaller_number { public class KataTests { [Theory] [InlineData(9, -1)] [InlineData(111, -1)] [InlineData(135, -1)] [InlineData(1027, -1)] [InlineData(1234560, 1234506)] [InlineData(123456, -1)] [InlineData(long.MaxValue, 9223372036854775780)] [InlineData(20, -1)] [InlineData(-1, -1)] [InlineData(71, 17)] [InlineData(531, 513)] public void NextSmallerNumber(long input, long expected) { Kata.NextSmallerNumber(input).Should().Be(expected); } } }
2f34afba2caa95d5e11f3590eba146b3dbab19d6
C#
s19191/APBD
/cw11/cw11/Configurations/PatientEfConfiguration.cs
2.671875
3
using cw11.Models; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace cw11.Configurations { public class PatientEfConfiguration : IEntityTypeConfiguration<Patient> { public void Configure(EntityTypeBuilder<Patient> builder) { { var patients = new List<Patient>(); patients.Add(new Patient { IdPatient = 1, FirstName = "Ala", LastName = "Kowalewska", BirthDate = DateTime.Today }); patients.Add(new Patient { IdPatient = 2, FirstName = "Ola", LastName = "Malanowska", BirthDate = DateTime.Today }); builder.HasData(patients); } } } }
d80de7413ce3c8ab272725e5ea70f254ce06241c
C#
Z3nk/Jungletribes-Monogame
/Jungletribes-Common/Action/GameAction.cs
2.515625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; namespace Jungletribes_Common { public class GameAction { public int angle; public Vector2 speed; public TimeSpan timer; public bool isRotate; public bool isPosition; public Vector2 position; public GameAction(int angle, Vector2 speed, TimeSpan timer, bool isRotate, bool isPosition, Vector2 position) { this.angle = angle; this.speed = speed; this.timer = timer; this.isRotate = isRotate; this.isPosition = isPosition; this.position = position; } } }
619c1fd998681245a516fc115632f2dd0469911b
C#
Nasko3/ProgrammingBasics
/Exam - 20 November 2016 - Evening/01. House Price/HousePrice.cs
3.4375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _01.House_Price { class HousePrice { static void Main(string[] args) { double smallRoomArea = double.Parse(Console.ReadLine()); double kitchenArea = double.Parse(Console.ReadLine()); double pricePerM2 = double.Parse(Console.ReadLine()); var secondRoomArea = (smallRoomArea * 1.1); var totalArea = smallRoomArea + (smallRoomArea * 0.5) + secondRoomArea + (secondRoomArea * 1.1) + kitchenArea; totalArea *= 1.05; var price = totalArea * pricePerM2; Console.WriteLine($"{price:f2}"); } } }
9a00c0834e443e4d67cefdfe0ee23f8bda75b52e
C#
Bilal334409/Payroll
/PayRoll/Calculate.cs
3.140625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PayRoll { class Calculate { public static void Salary(int BasicSalary, ref int ConvenceAllowance, ref int HouseRentAllowance, ref int MedicalAllowance) { if (BasicSalary >= 40000) { ConvenceAllowance = (int)(BasicSalary * 0.25); MedicalAllowance = (int)(BasicSalary * 0.15); HouseRentAllowance = (int)(BasicSalary * 0.10); } else if (BasicSalary >= 30000) { ConvenceAllowance = (int)(BasicSalary * 0.20); MedicalAllowance = (int)(BasicSalary * 0.12); HouseRentAllowance = (int)(BasicSalary * 0.10); } else if (BasicSalary < 30000) { ConvenceAllowance = 2000; MedicalAllowance = 1500; HouseRentAllowance = 1000; } } public static int GetTotalDaysOfMonth(DateTime MonthYear) { DateTime dt = MonthYear; int Count = int.Parse(DateTime.DaysInMonth(Int32.Parse(dt.Year.ToString()), Int32.Parse(dt.Month.ToString())).ToString()); return Count; } public static int GetSunday(DateTime MonthYear) { DateTime today = MonthYear; DateTime endOfMonth = new DateTime(today.Year, today.Month, DateTime.DaysInMonth(today.Year, today.Month)); int day = endOfMonth.Day; DateTime now = MonthYear; int count; count = 0; for (int i = 0; i < day; ++i) { DateTime d = new DateTime(now.Year, now.Month, i + 1); //Compare date with sunday //MessageBox.Show("d " + d); //MessageBox.Show("d.DayOfWeek " + d.DayOfWeek); //MessageBox.Show("DayOfWeek.Sunday " + DayOfWeek.Sunday); if (d.DayOfWeek == DayOfWeek.Sunday) { count = count + 1; } } return count; } public static int IncomeText(int GrossPay) { if (GrossPay >= 60000) { return (int)(GrossPay * 0.3); } else if (GrossPay >= 50000) { return (int)(GrossPay * 0.2); } else { return 0; } } } }
b3ba7daedba34b2c283e55caded1bbf23556c9ea
C#
CaveSystems/cave-io
/Cave.IO/MarshalStruct.cs
3.34375
3
using System; using System.Collections.Generic; using System.IO; using System.Runtime.InteropServices; using System.Text; namespace Cave.IO { /// <summary>Provides tools for manual struct marshalling.</summary> public static class MarshalStruct { #region Public Methods /// <summary>Marshalls the specified buffer to a new structure instance.</summary> /// <typeparam name="T">The type of the struct.</typeparam> /// <param name="buffer">Buffer to copy.</param> /// <param name="result">The new struct.</param> public static void Copy<T>(byte[] buffer, out T result) where T : struct => Copy(buffer, 0, out result); /// <summary>Marshalls the specified buffer to a new structure instance.</summary> /// <typeparam name="T">The type of the struct.</typeparam> /// <param name="buffer">Buffer to copy.</param> /// <param name="offset">Offset to start reading the byte buffer at.</param> /// <param name="result">The new struct.</param> public static void Copy<T>(byte[] buffer, int offset, out T result) where T : struct { var handle = GCHandle.Alloc(buffer, GCHandleType.Pinned); try { var address = handle.AddrOfPinnedObject(); if (offset != 0) { address = new IntPtr(address.ToInt64() + offset); } #if NET20 || NET35 || NET40 || NET45 result = (T)Marshal.PtrToStructure(address, typeof(T)); #else result = Marshal.PtrToStructure<T>(address); #endif } finally { handle.Free(); } } /// <summary>Marshalls the specified structure to a new byte[] instance.</summary> /// <typeparam name="T">The type of the struct.</typeparam> /// <param name="item">The item do marshal.</param> /// <param name="data">The new byte array.</param> public static void Copy<T>(T item, out byte[] data) where T : struct { var size = SizeOf<T>(); data = new byte[size]; var handle = GCHandle.Alloc(data, GCHandleType.Pinned); try { Marshal.StructureToPtr(item, handle.AddrOfPinnedObject(), true); } finally { handle.Free(); } } /// <summary>Gets a new byte buffer containing the data of the struct.</summary> /// <typeparam name="T">struct type.</typeparam> /// <param name="item">the struct to read.</param> /// <returns>returns a new byte buffer.</returns> public static byte[] GetBytes<T>(T item) where T : struct { Copy(item, out var data); return data; } /// <summary>Gets a new struct instance containing the data of the buffer.</summary> /// <typeparam name="T">struct type.</typeparam> /// <param name="data">byte buffer.</param> /// <returns>returns a new struct.</returns> public static T GetStruct<T>(byte[] data) where T : struct { if (data == null) { throw new ArgumentNullException(nameof(data)); } Copy(data, out T result); return result; } /// <summary>Reads a struct from a stream (see <see cref="DataReader"/> for a comfortable reader class supporting this, too).</summary> /// <typeparam name="T">struct type.</typeparam> /// <param name="stream">Stream to read from.</param> /// <returns>Returns a new struct instance.</returns> public static T Read<T>(Stream stream) where T : struct { if (stream == null) { throw new ArgumentNullException(nameof(stream)); } var size = SizeOf<T>(); var buffer = new byte[size]; if (stream.Read(buffer, 0, size) < size) { throw new EndOfStreamException(); } Copy(buffer, 0, out T result); return result; } /// <summary>Reads a struct from a byte buffer.</summary> /// <typeparam name="T">struct type.</typeparam> /// <param name="data">byte buffer.</param> /// <param name="offset">Offset at the byte buffer to start reading.</param> /// <returns>The new struct.</returns> public static T Read<T>(byte[] data, int offset = 0) where T : struct { if (data == null) { throw new ArgumentNullException(nameof(data)); } Copy(data, offset, out T result); return result; } /// <summary>Reads a native UTF8 string.</summary> /// <param name="address">The pointer.</param> /// <returns>The string.</returns> public static string ReadUtf8(IntPtr address) { if (address == IntPtr.Zero) { return null; } var data = new List<byte>(); var i = 0; while (true) { var b = Marshal.ReadByte(address, i++); if (b == 0) { break; } data.Add(b); } return Encoding.UTF8.GetString(data.ToArray()); } /// <summary>Reads a native UTF8 strings array.</summary> /// <remarks>utf8 string arrays are a memory reagon containing null terminated utf8 strings terminated by an empty utf8 string.</remarks> /// <param name="address">The pointer.</param> /// <returns>The array of strings.</returns> public static string[] ReadUtf8Strings(IntPtr address) { if (address == IntPtr.Zero) { return null; } var strings = new List<string>(); var current = new List<byte>(); for (var i = 0; ; i++) { var b = Marshal.ReadByte(address, i); if (b == 0) { if (current.Count == 0) { break; } strings.Add(Encoding.UTF8.GetString(current.ToArray())); current.Clear(); continue; } current.Add(b); } return strings.ToArray(); } /// <summary>Gets the size of the specified structure.</summary> /// <typeparam name="T">The type of the struct.</typeparam> /// <returns>The size.</returns> public static int SizeOf<T>() where T : struct => #if NET20 || NET35 || NET40 || NET45 Marshal.SizeOf(typeof(T)); #else Marshal.SizeOf<T>(); #endif /// <summary>Writes a struct to a stream (see <see cref="DataWriter"/> for a comfortable reader class supporting this, too).</summary> /// <typeparam name="T">struct type.</typeparam> /// <param name="stream">Stream to write to.</param> /// <param name="item">the struct to write.</param> public static void Write<T>(Stream stream, T item) where T : struct { if (stream == null) { throw new ArgumentNullException(nameof(stream)); } Copy(item, out var data); stream.Write(data, 0, data.Length); } /// <summary>Writes a struct to a byte buffer.</summary> /// <typeparam name="T">struct type.</typeparam> /// <param name="item">the struct to write.</param> /// <param name="buffer">byte buffer.</param> /// <param name="offset">Offset at the byte buffer to start writing.</param> public static void Write<T>(T item, byte[] buffer, int offset) where T : struct { if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } Copy(item, out var data); Array.Copy(data, 0, buffer, offset, data.Length); } #endregion Public Methods } }
c1f92e7f0cef749094ec67eafd2456db6b85e142
C#
yiclwh/ProblemSolving
/ProblemSolving/DAA/FindMin.cs
3.9375
4
/* • A strict concave-up array is an array in which the numbers first strictly decrease,then the numbers strictly increases. For example, [5,3,1,6,9,12] is a strict concave-up array. Note that, the decreasing part and/or the increasing part could be empty. So [5,3,1] and [1,6,9,12] are both strict concave-up arrays. Even the array [3] is also a strict concave-up array. A strict concave-up array always has a unique smallest element. In this problem, you are asked to present an O(lgn)-time algorithm in pseudo-code to find the smallest element in a given strict concave-up array. Please also specify your initial call (top level call). You need to justify the running time by stating the recurrence relation for the recursive algorithm. */ namespace ProblemSolving { public class FindMin { public static int FindMinInArray(int[] array, int start, int end) { int answer = 0; if (start == end) { return array[start]; } int mid = (start + end) / 2; if (array[mid] < array[mid + 1]) { answer = FindMinInArray(array, start, mid); } else if (array[mid] > array[mid + 1]) { answer = FindMinInArray(array, mid + 1, end); } return answer; } } }
dafb337f2fbb8fa61eff34e3ef785897d6439e70
C#
twistedtwig/CustomConfigurations
/CustomConfigurations/ObjectCreationAndPopulationFactory.cs
3.25
3
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Reflection; namespace CustomConfigurations.ObjectCreation { /// <summary> /// Wrapper class to do some reflection creation and property initialization. /// </summary> public class ObjectCreationAndPopulationFactory { public static T Create<T>() { return Create<T>(new ObjectCreationSettingsCollection()); } public static T Create<T>(ObjectCreationSettingsCollection creationSettings) { if (creationSettings == null) throw new ArgumentException("no creation settings provided."); var obj = InstantiateObject<T>(creationSettings.GetValidConstructorSettings()); //populate values. PopulateFieldsFromValuesItems(obj, creationSettings.GetValidPropertySettings(), creationSettings.OnlySetPublicProperties); //return T return obj; } public static void PopulateFieldsFromValuesItems<T>(T obj, IList<ObjectCreationSettingItem> propertySettings, bool onlySetPublicProperties) { //foreach field see if there is a field with the same name foreach (ObjectCreationSettingItem creationSettingItem in propertySettings) { SetPropertyValue(obj, onlySetPublicProperties, creationSettingItem.MapToName, creationSettingItem.Value); } } private static void SetPropertyValue<T>(T obj, bool onlySetPublicSetters, string key, string value) { PropertyInfo prop = GetProperty(obj, key, onlySetPublicSetters); if (prop != null) { if (Is(value, prop.PropertyType)) { prop.SetValue(obj, ConvertToType(value, prop.PropertyType), null); } } } /// <summary> /// Returns the <c>PropertyInfo</c> object for the given object and the property name /// </summary> /// <param name="objectToGetProperty"></param> /// <param name="propertyName"></param> /// <param name="onlyPublic"> </param> /// <returns></returns> private static PropertyInfo GetProperty(Object objectToGetProperty, string propertyName, bool onlyPublic) { if (objectToGetProperty == null) { throw new ArgumentException("objectToGetProperty was NULL"); } if (propertyName == null) { throw new ArgumentException("propertyName was NULL"); } PropertyInfo publicPropertyInfo = objectToGetProperty.GetType().GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public); if (publicPropertyInfo != null) { if (onlyPublic) { if (publicPropertyInfo.GetSetMethod() != null) { return publicPropertyInfo; } } return publicPropertyInfo; } return !onlyPublic ? objectToGetProperty.GetType().GetProperty(propertyName, BindingFlags.Instance | BindingFlags.NonPublic) : null; } private static T InstantiateObject<T>(IList<ObjectCreationSettingItem> constructorSettings) { ConstructorInfo constructor = DetermineBestConstructor<T>(constructorSettings); if (constructor == null) return default(T); //go through each paramater in constructor, get value from config by name and convert to parameter type and add into an object array. // create object ParameterInfo[] parameters = constructor.GetParameters(); object[] paramArray = new object[parameters.Length]; for (int i = 0; i < parameters.Length; i++) { //go through all constructor settingItems and create the object array with typed objects. paramArray[i] = ConvertToType(FindMatchingSetting(parameters[i].Name, constructorSettings).Value, parameters[i].ParameterType); } return (T)constructor.Invoke(paramArray); } private static ObjectCreationSettingItem FindMatchingSetting(string parameterName, IList<ObjectCreationSettingItem> constructorSettings) { ObjectCreationSettingItem orignalNameMatch = constructorSettings.FirstOrDefault(x => x.OriginalName.Equals(parameterName)); if (orignalNameMatch != null) { return orignalNameMatch; } ObjectCreationSettingItem mapToNameMatch = constructorSettings.FirstOrDefault(x => x.MapToName.Equals(parameterName)); if (mapToNameMatch != null) { return mapToNameMatch; } throw new ArgumentException("no constructor creation setting found for parameter: " + parameterName); } private static ConstructorInfo DetermineBestConstructor<T>(IList<ObjectCreationSettingItem> constructorSettings) { ConstructorInfo[] constructors = typeof(T).GetConstructors().OrderByDescending(x => x.GetParameters().Length).ToArray(); if (constructors.Length == 0) { return null; } foreach (ConstructorInfo constructor in constructors) { bool allMatched = true; ParameterInfo[] parameters = constructor.GetParameters(); foreach (ParameterInfo parameter in parameters) { if (!constructorSettings.Any(settingItem => (settingItem.OriginalName.Equals(parameter.Name) || settingItem.MapToName.Equals(parameter.Name)) && Is(settingItem.Value, parameter.ParameterType) && (settingItem.CreationSettingType == ObjectCreationSettingType.ConstructorOrProperty || settingItem.CreationSettingType == ObjectCreationSettingType.ConstructorOnly))) { allMatched = false; } } if (allMatched) return constructor; } return null; } private static bool Is(string input, Type targetType) { try { TypeDescriptor.GetConverter(targetType).ConvertFromString(input); return true; } catch { return false; } } private static object ConvertToType(string input, Type t) { if (!Is(input, t)) return null; var converter = TypeDescriptor.GetConverter(t); return converter.ConvertFromString(input); } } }
bfcfe9bae95b81e351cb668268e2ae8d9c8301d7
C#
wetstreet/Theircraft
/client/Assets/Plugins/Behavior Designer/Runtime/Tasks/Unity/Vector2/Distance.cs
2.515625
3
using UnityEngine; namespace BehaviorDesigner.Runtime.Tasks.Unity.UnityVector2 { [TaskCategory("Unity/Vector2")] [TaskDescription("Returns the distance between two Vector2s.")] public class Distance : Action { [Tooltip("The first Vector2")] public SharedVector2 firstVector2; [Tooltip("The second Vector2")] public SharedVector2 secondVector2; [Tooltip("The distance")] [RequiredField] public SharedFloat storeResult; public override TaskStatus OnUpdate() { storeResult.Value = Vector2.Distance(firstVector2.Value, secondVector2.Value); return TaskStatus.Success; } public override void OnReset() { firstVector2 = secondVector2 = Vector2.zero; storeResult = 0; } } }
a860463c1735adf9996026b335f7f73971ea952e
C#
vives-introduction-to-programming-2020/StringObjectDemo
/StringObjectDemo/Program.cs
3.8125
4
using System; namespace StringObjectDemo { class Program { static void Main(string[] args) { string hello = "Hello"; string hallo = new string("Hello"); if (hello == hallo) // INHOUDELIJKE VERGELIJKING { Console.WriteLine("Both are equal"); } int[] number = { 1, 2, 3 }; int[] values = { 1, 2, 3 }; if (number == values) // REFERENTIES WORDEN VERGELEKEN { Console.WriteLine("Numbers == values"); } Random generator1 = new Random(); Random generator2 = generator1; Random generator3 = new Random(); if (generator1 == generator2) { Console.WriteLine("generator1 == generator2"); } if (generator1 == generator3) { Console.WriteLine("generator1 == generator3"); } int a = 5; int b = a; if (b == a) { Console.WriteLine("1. b == a"); } b = 6; if (b == a) { Console.WriteLine("2. b == a"); } } } }
f51d92236a1095110196d7e6b7d3ee517870ccf6
C#
tjdamiwangyong20191115/blockchaindemo
/tjdamiblockchainclientdemo/JsonHepler.cs
2.875
3
using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Text; namespace tjdamiblockchainclientdemo { public class JsonHepler { static public string getvaluefromjson(string p_json, string p_key) { if (p_json == "") return ""; string strRet = ""; try { JObject jo = JObject.Parse(p_json); string[] keys = p_key.Split('|'); switch (keys.Length) { case 1: strRet = (string)jo[keys[0]]; break; case 2: strRet = (string)jo[keys[0]][keys[1]]; break; case 3: if (jo[keys[0]][keys[1]].GetType().ToString().Equals("Newtonsoft.Json.Linq.JArray")) { strRet = (string)jo[keys[0]][keys[1]][0][keys[2]]; } else { strRet = (string)jo[keys[0]][keys[1]][keys[2]]; } break; case 4: strRet = (string)jo[keys[0]][keys[1]][keys[2]][keys[3]]; break; } } catch (Exception ex) { Console.WriteLine(ex.Message); return ""; } return strRet; } } }
65e8a29cac6320cc565c83be01f5d1167ae60859
C#
edprado6/teste_admissao_soitic
/TesteAdmissao/Controllers/AutorController.cs
2.6875
3
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Contexto; using Dominio; namespace TesteAdmissao.Controllers { public class AutorController : Controller { /* * A classe que representa o DB é instanciada. */ private DBLivro db = new DBLivro(); /* GET: /Autor/ * Exibe lista com todos autores cadastrados. */ public ActionResult Index() { ViewBag.Title = "Autores"; var autores = db.Autores.ToList(); return View(autores); } /* GET: /Autor/Details/5 * Método de visualização de detalhes usando view. * Obs: Esse método foi substituído pelo método "Detalhes". */ //public ActionResult Details(int AutorId) //{ // var autor = db.Autores.ToList().FirstOrDefault(c => c.AutorId == AutorId); // if (autor == null) // { // return HttpNotFound(); // Personalizar página de erro. // } // ViewBag.Title = "Detalhes"; // return View(autor); //} /* GET: /Autor/Create * Abre o formulário para cadastro de autores. */ public ActionResult Create() { ViewBag.Title = "Cadastrar Autor"; return View(); } /* POST: /Autor/Create * recebe o POST do formulário de cadastro de autores. */ [HttpPost] public ActionResult Create(Autor autor) { autor.DataInsercao = DateTime.Now; autor.DataAlteracao = DateTime.Now; if (ModelState.IsValid) { db.Autores.Add(autor); db.SaveChanges(); Helpers.HelpersGeral.MensagensDeStatus(this, "OK", " Autor cadastrado com sucesso."); return RedirectToAction("Index"); } Helpers.HelpersGeral.MensagensDeStatus(this, "FAILED", " Problema ao cadastrar."); return View(); } /* GET: /Autor/Edit/5 * Recebe um id e busca um autor no bd. Se um autor for * encontrado, abre o formulário para edição. */ public ActionResult Edit(int AutorId) { var autor = db.Autores.ToList().FirstOrDefault(c => c.AutorId == AutorId); if (autor == null) { return HttpNotFound(); // Personalizar página de erro. } ViewBag.Title = "Editar Autor"; return View(autor); } /* POST: /Autor/Edit/5 * Recebe o post do formulário de edição de autores. */ [HttpPost] public ActionResult Edit(Autor autor) { try { var a = db.Autores.Find(autor.AutorId); a.NomeAutor = autor.NomeAutor; a.DataAlteracao = DateTime.Now; db.SaveChanges(); Helpers.HelpersGeral.MensagensDeStatus(this, "OK", " Autor editado com sucesso."); return RedirectToAction("Index"); } catch { Helpers.HelpersGeral.MensagensDeStatus(this, "FAILED", " Problema ao editar."); return View(); } } /* * Método de visualização de detalhes do autor. * Não utiliza view. * O retorno é Json que será exibido em uma janela modal. */ [HttpGet] public JsonResult Detalhes(int id) { var autor = db.Autores.ToList().FirstOrDefault(c => c.AutorId == id); if (autor == null) { var response = new { Status = "FAILED", Mensagem = "Não foi encontrado nenhum autor com o código informado." }; return Json(response, JsonRequestBehavior.AllowGet); } else { var response = new { AutorId = autor.AutorId, NomeAutor = autor.NomeAutor, DataInsercao = autor.DataInsercao, DataAlteracao = autor.DataAlteracao }; return Json(response, JsonRequestBehavior.AllowGet); } } /* GET: /Autor/Delete/5 * Recebe id e executa o método responsável pela * exclusão de elementos. */ [HttpGet] public ActionResult Delete(int id) { try { var autor = db.Autores.Find(id); db.Autores.Remove(autor); db.SaveChanges(); Helpers.HelpersGeral.MensagensDeStatus(this, "OK", " Autor excluído com sucesso."); return RedirectToAction("Index"); } catch { Helpers.HelpersGeral.MensagensDeStatus(this, "FAILED", " Problema ao excluir."); return View(); } } } }
76fa35fd9217e4848da12ccd503011765c43c34c
C#
jrialland/parsing
/JSourceObjectizerV1_07_CSharp/src/com/habelitz/jsobjectizer/jsom/api/statement/IfStatement.cs
2.671875
3
/* * BSD license * * Copyright (c) 2007-2011 by HABELITZ Software Developments * * All rights reserved. * * http://www.habelitz.com * * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY HABELITZ SOFTWARE DEVELOPMENTS ('HSD') ``AS IS'' * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL 'HSD' BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using com.habelitz.jsobjectizer.jsom.api.expression; namespace com.habelitz.jsobjectizer.jsom.api.statement { /** * This <code>Statement</code> type represents an <code>if</code> statement. * * @author Dieter Habelitz */ public interface IfStatement : Statement { /** * Returns the <code>if</code> statement's condition expression. * * @return The <code>if</code> statement's condition expression. */ Expression getCondition(); /** * Returns the statement that belongs to the optional <code>else</code> * clause that belongs to <code>this</code>, i.e. this is the statement * that should be executed if the <code>if</code> statement's condition * expression is <code>false</code>. * * @return The statement that belongs an <code>else</code> clause or <code> * null</code> if no <code>else</code> clause has been stated. */ Statement getElseStatement(); /** * Returns the statement that should be executed if the <code>if</code> * statement condition is <code>true</code>. * * @return The statement that should be executed if the <code>if</code> * statement condition is <code>true</code>. */ Statement getStatement(); /** * Tells if the <code>if</code> statement has an <code>else</code> branch. * * @return <code>true</code> if the <code>if</code> statement has an <code> * else</code> branch. */ bool hasElseClause(); } }
adc72f514367446a6bea33a316fa5f6b79c25932
C#
pkradioman/MigSharp
/MigSharp/SupportedPlatforms.cs
2.9375
3
using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; namespace MigSharp { /// <summary> /// Represents a collection of database versions that should be supported for all migrations. Validation of migrations is performed /// against providers contained within this list. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] public class SupportedPlatforms : IEnumerable<DbPlatform> { private readonly List<DbPlatform> _platforms = new List<DbPlatform>(); internal SupportedPlatforms() { } /// <summary> /// Adds or replaces a database platform whose <see cref="DbPlatform.MajorVersion"/> is taken to be the minimum requirement. /// </summary> /// <remarks> /// This method is added to support collection initializers. /// </remarks> public void Add(DbPlatform platform) { AddOrReplaceMinimumRequirement(platform); } /// <summary> /// Adds or replaces a database platform whose <see cref="DbPlatform.MajorVersion"/> is taken to be the minimum requirement. /// </summary> public void AddOrReplaceMinimumRequirement(DbPlatform platform) { _platforms.RemoveAll(p => p.Platform == platform.Platform && p.Driver == platform.Driver); _platforms.Add(platform); } /// <summary> /// Removes platforms by <see cref="Platform"/>. /// </summary> public void RemoveAll(Platform platform) { _platforms.RemoveAll(p => p.Platform == platform); } /// <summary> /// Removes platforms by <see cref="Driver"/>. /// </summary> public void RemoveAll(Driver driver) { _platforms.RemoveAll(p => p.Driver == driver); } /// <summary> /// Sets the collection of supported providers to <paramref name="names"/>. /// </summary> public void Set(IEnumerable<DbPlatform> names) { Clear(); _platforms.AddRange(names); } /// <summary> /// Clears the collection. /// </summary> public void Clear() { _platforms.Clear(); } #pragma warning disable 1591 public IEnumerator<DbPlatform> GetEnumerator() { return _platforms.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } #pragma warning restore 1591 } }
deb7310882e33400fa4c3500b30a98ae5efee7e0
C#
ealton/LDFW
/Assets/BaseInputDetector.cs
2.5625
3
using UnityEngine; using UnityEngine.EventSystems; using System; using System.Collections; /// <summary> /// Base class for all input detectors /// </summary> public class BaseInputDetector : MonoBehaviour, IPointerClickHandler, IDragHandler, IPointerDownHandler, IPointerUpHandler, IPointerEnterHandler, IPointerExitHandler { // Public Variables public int inputDetectorID; public Action<PointerEventData> onPointerEnterAction = null; public Action<PointerEventData> onPointerExitAction = null; public Action<PointerEventData> onPointerDownAction = null; public Action<PointerEventData> onPointerUpAction = null; public Action<PointerEventData> onDragAction = null; public Action<PointerEventData> onPointerClickAction = null; public void InitActions(Action<PointerEventData> pointerEnter, Action<PointerEventData> pointerExit, Action<PointerEventData> pointerDown, Action<PointerEventData> pointerUp, Action<PointerEventData> drag, Action<PointerEventData> click) { onPointerEnterAction = pointerEnter; onPointerExitAction = pointerExit; onPointerDownAction = pointerDown; onPointerUpAction = pointerUp; onDragAction = drag; onPointerClickAction = click; } public virtual void OnPointerDown(PointerEventData eventData) { CommonLog("Down"); if (onPointerDownAction != null) { onPointerDownAction(eventData); } } public virtual void OnPointerUp(PointerEventData eventData) { CommonLog("Up"); if (onPointerUpAction != null) { onPointerUpAction(eventData); } } public virtual void OnDrag(PointerEventData eventData) { CommonLog("Drag"); if (onDragAction != null) { onDragAction(eventData); } } public virtual void OnPointerEnter(PointerEventData eventData) { CommonLog("Enter"); if (onPointerEnterAction != null) { onPointerEnterAction(eventData); } } public virtual void OnPointerExit(PointerEventData eventData) { CommonLog("Exit"); if (onPointerExitAction != null) { onPointerExitAction(eventData); } } public virtual void OnPointerClick(PointerEventData eventData) { CommonLog("OnPointerClick"); if (onPointerClickAction != null) { onPointerClickAction(eventData); } } private void CommonLog(string str) { //DebugLogger.Log (gameObject.name + "." + this.GetType ().Name + ": " + str, gameObject); } }
cda952bf88e42c54ba9faa1938e59405cea59fa5
C#
lxq/waitan5hao
/elevator/elevator/Program.cs
3.46875
3
using System; using System.Collections.Generic; using System.Text; namespace Example { using System.Net.Json; class Program { const string jsonText = "{"+ " \"FirstValue\": 1.1,"+ " \"SecondValue\": \"some text\"," + " \"TrueValue\": true" + "}"; static void Main(string[] args) { // 1. parse sample Console.WriteLine(); Console.WriteLine("Source data:"); Console.WriteLine(jsonText); Console.WriteLine(); JsonTextParser parser = new JsonTextParser(); JsonObject obj = parser.Parse(jsonText); Console.WriteLine(); Console.WriteLine("Parsed data with indentation in JSON data format:"); Console.WriteLine(obj.ToString()); Console.WriteLine(); JsonUtility.GenerateIndentedJsonText = false; Console.WriteLine(); Console.WriteLine("Parsed data without indentation in JSON data format:"); Console.WriteLine(obj.ToString()); Console.WriteLine(); // enumerate values in json object Console.WriteLine(); Console.WriteLine("Parsed object contains these nested fields:"); foreach (JsonObject field in obj as JsonObjectCollection) { string name = field.Name; string value = string.Empty; string type = field.GetValue().GetType().Name; // try to get value. switch(type) { case "String": value = (string)field.GetValue(); break; case "Double": value = field.GetValue().ToString(); break; case "Boolean": value = field.GetValue().ToString(); break; default: // in this sample we'll not parse nested arrays or objects. throw new NotSupportedException(); } Console.WriteLine("{0} {1} {2}", name.PadLeft(15), type.PadLeft(10), value.PadLeft(15)); } Console.WriteLine(); // 2. generate sample Console.WriteLine(); // root object JsonObjectCollection collection = new JsonObjectCollection(); // nested values collection.Add(new JsonStringValue("FirstName", "Pavel")); collection.Add(new JsonStringValue("LastName", "Lazureykis")); collection.Add(new JsonNumericValue("Age", 23)); collection.Add(new JsonStringValue("Email", "me@somewhere.com")); collection.Add(new JsonBooleanValue("HideEmail", true)); Console.WriteLine("Generated object:"); JsonUtility.GenerateIndentedJsonText = true; Console.WriteLine(collection); Console.WriteLine(); Console.ReadLine(); } } }
2395b88cddbc32aa2d1408b2bb5fd700d9af6189
C#
c-eng/holbertonschool-csharp
/0x07-csharp-tdd/4-unique/Text.Tests/Text.Tests.cs
2.890625
3
using NUnit.Framework; namespace Tests { public class Tests { [SetUp] public void Setup() { } [Test] public void UniqueChar_Empty() { string s = ""; int result = Text.Str.UniqueChar(s); Assert.That(result, Is.EqualTo(-1)); } [Test] public void UniqueChar_Lol() { string s = "wwwwwwwwwwwwwwwwwwwwwwwww"; int result = Text.Str.UniqueChar(s); Assert.That(result, Is.EqualTo(-1)); } [Test] public void UniqueChar_String() { string s = "abcdefghijklmnopqrstuvwxyzabcdfghijkzxywvutsrponlm"; int result = Text.Str.UniqueChar(s); Assert.That(result, Is.EqualTo(4)); } } }
3b1acba5f93ac77e4a88b63c6cfa4f03e77c8ce6
C#
viniciusmzo/URI
/1164/1164/Program.cs
3.453125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _1164 { class Program { static void Main(string[] args) { int n, x, soma = 0; x = int.Parse(Console.ReadLine()); for (int j = 0; j < x; j++) { n = int.Parse(Console.ReadLine()); for (int i = 1; i < n; i++) { if (n % i == 0) { soma += i; } } if (soma == n) { Console.WriteLine(n + " eh perfeito"); } else if (soma != n) { Console.WriteLine(n + " nao eh perfeito"); } soma = 0; } Console.ReadKey(); } } }
8f9c0c679e34fd1820e3520aab2242059c58e58e
C#
JulienAndonov/C-Advanced
/Session_3_Matrix_Jagged_Array_Ex/P08_Bombs/Program.cs
3.4375
3
using System; using System.Collections.Generic; using System.Linq; namespace P08_Bombs { class Program { static void Main(string[] args) { int rowsCols = int.Parse(Console.ReadLine()); int[,] matrix = new int[rowsCols, rowsCols]; int aliveCells = 0; int sumAlivecells = 0; for (int row = 0; row < rowsCols; row++) { var currentRow = Console.ReadLine().Split().Select(int.Parse).ToArray(); for (int col = 0; col < rowsCols; col++) { matrix[row, col] = currentRow[col]; } } string[] commands = Console.ReadLine().Split(" ",StringSplitOptions.RemoveEmptyEntries).ToArray(); foreach (var command in commands) { var coordinates = command.Split(',', StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToArray(); int bombRow = coordinates[0]; int bombCol = coordinates[1]; for (int row = 0; row < rowsCols; row++) { for (int col = 0; col < rowsCols; col++) { var distance = Math.Pow(Math.Abs(row - bombRow), 2) + Math.Pow(Math.Abs(col - bombCol), 2); if(matrix[bombRow,bombCol] > 0) { if (distance <= 2 && distance != 0 && matrix[row,col] > 0) { matrix[row, col] -= matrix[bombRow, bombCol]; } } } } matrix[bombRow, bombCol] = 0; } for (int row = 0; row < rowsCols; row++) { for (int col = 0; col < rowsCols; col++) { if (matrix[row, col] > 0) { aliveCells++; sumAlivecells += matrix[row, col]; } } } Console.WriteLine($"Alive cells: {aliveCells}"); Console.WriteLine($"Sum: {sumAlivecells}"); for (int row = 0; row < rowsCols; row++) { for (int col = 0; col < rowsCols; col++) { Console.Write(matrix[row,col] + " "); } Console.WriteLine(); } } } }