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
d16cc5e3a7e49cd5cb965bde321e919782f6458e
C#
skAeglund/Chessders
/Assets/Scripts/Game/Systems/MoveGenerator.cs
2.6875
3
using System.Collections; using System.Collections.Generic; using UnityEngine; public class MoveGenerator : MonoBehaviour { public static string GetStockfishMove(string FENstring, int difficulty = 1) { var process = new System.Diagnostics.Process(); //p.StartInfo.FileName = "C:\\Users\\AndersHgglund\\Unity projects\\Chessders\\Assets\\Applications\\stockfishExecutable.exe"; //process.StartInfo.FileName = Application.dataPath + "/Applications/stockfishExecutable.exe"; process.StartInfo.FileName = Application.streamingAssetsPath + "/stockfishExecutable.exe"; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardInput = true; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.CreateNoWindow = true; process.Start(); process.StandardInput.WriteLine($"setoption name Skill Level value {difficulty}"); string setupString = "position fen " + FENstring; process.StandardInput.WriteLine(setupString); string processString = $"go depth {difficulty}"; process.StandardInput.WriteLine(processString); string stockfishMove = null; while (!process.StandardOutput.EndOfStream) { stockfishMove = process.StandardOutput.ReadLine(); if (stockfishMove.Contains("bestmove")) break; } if (!stockfishMove.Contains("bestmove")) { process.CloseMainWindow(); return "fail"; } //Debug.Log(stockfishMove); string[] words = stockfishMove.Split(' '); stockfishMove = words[1]; //p.Close(); process.CloseMainWindow(); return stockfishMove; } }
397829a6638d88d3ff95392e244f1d071ac1b402
C#
yeffry056/PreoyectoFinal_Aplicada1_Eladio_Mario
/ProyectoFinalAplicada1/BLL/CategoriasBLL.cs
2.78125
3
using Microsoft.EntityFrameworkCore; using ProyectoFinalAplicada1.DAL; using ProyectoFinalAplicada1.Entidades; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; namespace ProyectoFinalAplicada1.BLL { public class CategoriasBLL { //Metodo Existe. public static bool Existe(int id) { Contexto contexto = new Contexto(); bool encontrado = false; try { encontrado = contexto.Categorias.Any(c => c.CategoriaId == id); } catch (Exception) { throw; } finally { contexto.Dispose(); } return encontrado; } //Metodo Insertar. private static bool Insertar(Categorias categorias) { bool key = false; Contexto contexto = new Contexto(); try { contexto.Categorias.Add(categorias); key = contexto.SaveChanges() > 0; } catch (Exception) { throw; } finally { contexto.Dispose(); } return key; } //Metodo Modificar. private static bool Modificar(Categorias categorias) { bool key = false; Contexto contexto = new Contexto(); try { contexto.Entry(categorias).State = EntityState.Modified; key = contexto.SaveChanges() > 0; } catch (Exception) { throw; } finally { contexto.Dispose(); } return key; } //Metodo Guardar. public static bool Guardar(Categorias categorias) { if (!Existe(categorias.CategoriaId)) { return Insertar(categorias); } else { return Modificar(categorias); } } //Metodo Eliminar. public static bool Eliminar(int id) { bool key = false; Contexto contexto = new Contexto(); try { var categorias = contexto.Categorias.Find(id); if (categorias != null) { contexto.Categorias.Remove(categorias); key = contexto.SaveChanges() > 0; } } catch (Exception) { throw; } finally { contexto.Dispose(); } return key; } //Metodo Buscar. public static Categorias Buscar(int id) { Contexto contexto = new Contexto(); Categorias categorias; try { categorias = contexto.Categorias.Find(id); } catch (Exception) { throw; } finally { contexto.Dispose(); } return categorias; } public static List<Categorias> GetCategorias() { Contexto contexto = new Contexto(); List<Categorias> categorias = new List<Categorias>(); try { categorias = contexto.Categorias.ToList(); } catch (Exception) { throw; } finally { contexto.Dispose(); } return categorias; } public static List<Categorias> GetList(Expression<Func<Categorias, bool>> categorias) { List<Categorias> lista = new List<Categorias>(); Contexto contexto = new Contexto(); try { lista = contexto.Categorias.Where(categorias).ToList(); } catch { throw; } finally { contexto.Dispose(); } return lista; } //Datos duplicado public static bool DuplicadoDescripcion(string descripcion) { bool paso = false; Contexto contexto = new Contexto(); try { paso = contexto.Categorias.Any(u => u.Descripcion.Equals(descripcion)); } catch (Exception) { throw; } finally { contexto.Dispose(); } return paso; } } }
6553b867e7db94e92cb203b2df604b7011ff1640
C#
VesiBaleva/MilhouseProject
/Inventory management/Inventory.UI/Menu.cs
2.609375
3
using System.Collections.Generic; using System; public class Menu { public List<MenuItem> MenuItems { get; set; } public string Title { get; set; } public Menu(string title) { this.Title = title; this.MenuItems = new List<MenuItem>(); } public Menu(string title, List<MenuItem> menuItems) { this.Title = title; this.MenuItems = menuItems; } }
6c5cfa814c6da1c41cd45af8291a182da549005f
C#
maoxx241/bike
/bike/Login.cs
2.71875
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.Data.SQLite; namespace bike { public partial class Login : Form { public Login() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { Register reg = new Register(); reg.BringToFront(); reg.Show(); } private static string connstr = ConfigService.ConnectionString; private int loginprocess() { var SQLiteConnection = new SQLiteConnection(connstr); SQLiteConnection.Open(); try { var cmd = new SQLiteCommand(SQLiteConnection); cmd.CommandText = "SELECT * FROM person WHERE username=@username"; cmd.Parameters.AddWithValue("@username", usernamebox.Text.Trim()); SQLiteDataReader rdr = cmd.ExecuteReader(); while (rdr.Read()) { string us = rdr.GetString(0); string pw = rdr.GetString(1); int op = rdr.GetInt32(2); if (us == usernamebox.Text.Trim() && pw == passwordbox.Text.Trim() && op == 1 && checkBox2.Checked) { return 2; } if (us==usernamebox.Text.Trim() && pw == passwordbox.Text.Trim()) { return 1; } } } catch { } return 0; } private void button2_Click(object sender, EventArgs e) { switch (loginprocess()) { case 0: Msg warning = new Msg("Wrong username or password"); warning.BringToFront(); warning.Show(); break; case 1: MainForm mf = new MainForm(usernamebox.Text.Trim(), checkBox1.Checked); mf.BringToFront(); mf.Show(); this.Hide(); break; case 2: OperatorForm operatorForm = new OperatorForm(usernamebox.Text.Trim(), checkBox1.Checked); operatorForm.BringToFront(); operatorForm.Show(); this.Hide(); break; } } } }
3d01d96741f7586246ee344e4a322619afa3df6c
C#
deefault/LabApp
/Shared/Dto/UserRegisterDto.cs
2.53125
3
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace LabApp.Shared.Dto { public abstract class UserRegisterDto { [EmailAddress] [Required] public string Email { get; set; } [Required] public short PhoneCode { get; set; } [Required] public long Phone { get; set; } [Required] [DataType(DataType.Password)] public string Password { get; set; } [EmailAddress] public string ContactEmail { get; set; } [Required] public string Name { get; set; } [Required] public string Surname { get; set; } public string Middlename { get; set; } public DateTime DateBirth { get; set; } = new DateTime(1970,1,1); } public class StudentRegisterDto : UserRegisterDto { } public class TeacherRegisterDto : UserRegisterDto { public int? AcademicRankId { get; set; } } }
6abc6b57745931f23df528afb12d751fa9878832
C#
nicoletaraiu/JuniorMind
/Anagrams/Anagrams/AnagramsTests.cs
3.453125
3
/*Anagrame Pentru un cuvânt dat calculează numărul de anagramări posibile. Nu trebuie ca cuvintele rezultate să existe în dicționar. Anagramările nu trebuie să se repete și nu trebuie generate anagramările, doar să se calculeze numărul lor.*/ using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Linq; namespace Anagrams { [TestClass] public class AnagramsTests { [TestMethod] public void TestIfUniques() { Assert.AreEqual("abcd", GetUniques("aaabbccd")); } [TestMethod] public void TestIfMatch() { Assert.AreEqual(2, CountMatches("casa", 'a')); } [TestMethod] public void TestFactorial() { Assert.AreEqual(120, GetFactorial(5)); } [TestMethod] public void TestNoOfAnagrams() { Assert.AreEqual(3, GetNumberOfAnagrams("aba")); } [TestMethod] public void TestNoOfAnagrams3() { Assert.AreEqual(6, GetNumberOfAnagrams("abc")); } [TestMethod] public void TestNoOfAnagrams2() { Assert.AreEqual(105, GetNumberOfAnagrams("aabbaac")); } string GetUniques(string word) { string uniques = string.Empty; for (int i = 0; i < word.Length; i++) { if (!uniques.Contains(word[i])){ uniques += word[i]; } } return uniques; } int CountMatches(string word, char match) { int matches = 0; for (int i = 0; i < word.Length; i++) { if (word[i].Equals(match)) matches++; } return matches; } int GetFactorial(int numberOfLetters) { int factorial = 1; for (int i = 1; i <= numberOfLetters; i++) { factorial *= i; } return factorial; } int GetNumberOfAnagrams(String word) { int noOfAnagrams = GetFactorial(word.Length); String uniques = GetUniques(word); for(int i = 0; i < uniques.Length; i++) { int matchesOfUniqueLetter = CountMatches(word, uniques[i]); noOfAnagrams /= GetFactorial(matchesOfUniqueLetter); } return noOfAnagrams; } } }
73805436a3e9ea997b6933c8f738e08bca31c607
C#
desla/SlabGeometryControl
/Круглые слитки/SlabGeometryControl/SensorConfiguration/ISensorConfigurationListener.cs
2.703125
3
namespace Alvasoft.SensorConfiguration { /// <summary> /// Подписчик на изменение конфигурации датчиков. /// </summary> public interface ISensorConfigurationListener { /// <summary> /// Возникает при добавлении датчика. /// </summary> /// <param name="aConfiguration">Конфигурация.</param> /// <param name="aSensorId">Идентификатор нового датчика.</param> void OnSensorCreated(ISensorConfiguration aConfiguration, int aSensorId); /// <summary> /// Возникает при обновлении датчика. /// </summary> /// <param name="aConfiguration">Конфигурация.</param> /// <param name="aSensorId">Идентификатор датчика.</param> void OnSensorUpdated(ISensorConfiguration aConfiguration, int aSensorId); /// <summary> /// Возникает при удалении датчика. /// </summary> /// <param name="aConfiguration">Конфигурация.</param> /// <param name="aSensorId">Идентификатор удаленного датчика.</param> void OnSensorDeleted(ISensorConfiguration aConfiguration, int aSensorId); } }
cb970c07ea23437af4365814a21000df255283ff
C#
thomasemmerson/CSharp-BrightHR-CodeKatas
/SweetAssKata/SweetAssKataTests.cs
3.15625
3
using System; using NUnit.Framework; namespace SweetAssKata { [TestFixture] public class SweetAssKataTests { private const string Word = "ass"; private readonly string[] _adjectives = { "sweet", "nice", "cool" }; private readonly string[] _nouns = { "car", "bike", "train" }; [TestCase("sweet-ass car", "sweet ass-car")] [TestCase("nice-ass car", "nice ass-car")] [TestCase("Man, that's a sweet-ass car.", "Man, that's a sweet ass-car.")] [TestCase("Man, that sweet-ass car is a nice-ass vehicle.", "Man, that sweet ass-car is a nice ass-vehicle.")] [TestCase("Man, that sweet-ass car is a nice-ass vehicle.", "Man, that sweet ass-car is a nice ass-vehicle.")] public void SentenceMatchesPattern_HyphenIsMoved(string sentence, string expected) { var result = sentence.MoveHyphen(Word); Assert.AreEqual(expected, result); } [TestCase("Man, that's a sweet ass car.")] [TestCase("Man, that's a sweetass car.")] [TestCase("Man, that's a sweet car.")] [TestCase("-ass car")] [TestCase("sweet-ass")] public void SentenceDoesNotMatchPattern_HyphenIsNotMoved(string sentence) { Assert.AreEqual(sentence, sentence.MoveHyphen(Word)); } [Test] public void SentenceHasRandomAdjectiveAndNoun_HyphenIsMoved() { var adjective = GetRandomString(_adjectives); var noun = GetRandomString(_nouns); var sentence = "Man, that's a " + adjective + "-ass " + noun + "."; var result = sentence.MoveHyphen(Word); Assert.AreEqual("Man, that's a " + adjective + " ass-" + noun + ".", result); } private string GetRandomString(string[] strings) { return strings[new Random().Next(strings.Length)]; } } }
37747cf1041c4f0e53ae30c7eb0e045cd86893d8
C#
niteshrai02/C-Sample
/StaticSample/Program.cs
3.328125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using static System.Console; namespace StaticSample { class Program { static void Main(string[] args) { string s = "hello"; var val = s.ConvertString(s); int count = 0; int countNumber = count.CountNumber(val); WriteLine(val + countNumber); ReadKey(); } } public static class StaticTest { static int abc = 0; static DateTime currentDate = DateTime.Now; static StaticTest() { } public static DateTime CurrentDate() { return currentDate; } public static int Sum(int x, int y) { return x + y; } public static string ConvertString(this String abc, string value) { return abc = value; } public static int CountNumber(this int countNumber, string value) { return value.Split(new char[] { ' ', '.', ',' }).Length; } } }
11d15605ef55e882bfd056b21c4aea19ae8fadad
C#
Umut93/BoldQuiz
/BoldQuizMVC/BoldQuizMVC/Controllers/QuizController.cs
2.59375
3
using BLL; using BoldQuizMVC.Models; using Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Microsoft.AspNet.Identity; namespace BoldQuizMVC.Controllers { public class QuizController : Controller { private UserLogic UserLogic; private QuestionLogic questionLogic; private Room_LevelsLogic room_LevelsLogic; private Player_StatusLogic player_StatusLogic; private RoomLogic RoomLogic; // Instantiating the questionLogic public QuizController() { questionLogic = new QuestionLogic(); room_LevelsLogic = new Room_LevelsLogic(); player_StatusLogic = new Player_StatusLogic(); UserLogic = new UserLogic(); RoomLogic = new RoomLogic(); } // GET: Quiz //PlayArena: In that momemnt you click a level in a specific room. //UserID = ID number in AspnetUser //x (models.Question). It is main question (question.id) and its possible answers. Loops 10 times. It orders the id of the questions! //The player_status is based on the specifik room on a specific level. Afterwards finding that player and adding it in the table! //57: For each questions (10) populating them and its answers in the viewmodel. //Getting the 10 questions by giving a levelID. Afterwards populating the data in the viewModels! If questions is empty, then generate 10 random questions. //Linie 43 if 10 keep going or empty generate! //Creating a player_status. Populating level,room as objects and get a specific room_level_id (info). //If the list of questions are empty then it should generate random-questions (loading the page for first time), if not then we keep the questions until the user is finished (loading for second time). // Linie 48: It retrieves the already generated questions which are not finished yet and then ordering the questions by their ID's. We save them as well for resuming the game. //Populating the viewmodel properties withe question and answers --> because of validating the correct ID's //Players are connected on (same level id and roomID) = same questions. public ActionResult Index(int levelID, int roomID) { int userID = int.Parse(User.Identity.GetUserId()); List<Question> question; question = questionLogic.playerQuestion(roomID, levelID); if (question.Count == 0) { question = questionLogic.Get10Questions(levelID); questionLogic.savePlayerUnfinishedQuiz(question, levelID, roomID); } question = question.OrderBy(x => x.ID).ToList(); QuizViewModel viewModel = new QuizViewModel(); viewModel.LevelID = levelID; viewModel.RoomID = roomID; viewModel.questions = new List<QuestionViewModels>(); foreach (var item in question) { QuestionViewModels questionViewModel = new QuestionViewModels(); questionViewModel.QuestionID = item.ID; questionViewModel.QuestionTitle = item.Title; questionViewModel.Answers = new List<AnswerViewModel>(); foreach (var answers in item.Answers) { AnswerViewModel answerViewModel = new AnswerViewModel(); answerViewModel.AnswerText = answers.AnswerText; answerViewModel.ID = answers.ID; questionViewModel.Answers.Add(answerViewModel); } viewModel.questions.Add(questionViewModel); } return View(viewModel); } //Couting the right answers x/x in a specifik Room_level. // The logic finds the right RoomID and levelID as well. //For every questions(10) --> examines every questions questionID and selectedAnswerID for valdidating whether is true or not //After calculating the results, we find that person and m //Getting the player who is logged in and getting all his specific room_levels by searching the room and level he is on. //For every question he has selected right is assigned to isCorrect. //If the player score is less than the requirement then he gets a warning //room_level (25) [HttpPost] public string submitQuiz(QuizViewModel model) { int userid = int.Parse(User.Identity.GetUserId()); var room_level = room_LevelsLogic.getRoom_level(model.RoomID, model.LevelID); int correctedAnswers = 0; foreach (var question in model.questions) { var isCorrect = questionLogic.isAnsweredCorrect(question.SelectedAnswerID); if (isCorrect) { correctedAnswers++; } } Player player = UserLogic.findPLayer(userid); Player_Status playerStatus = player_StatusLogic.findPlayerStatus(player, room_level); playerStatus.SavedScore = correctedAnswers; if(playerStatus.SavedScore < room_level.Level.Score) { playerStatus.Warnings++; } player_StatusLogic.updatePlayerStatus(playerStatus); //Getting all the players in the room. The first room_level is open and looking at their results in a given level. If the player is done yet or the score is less than score, they are not carrying on. //If they have cope with the score, they go to the next level. //For all players we are looking at their room_levels (player_status) (player_room_levels). Still setting the same room_level. List<Player> players = RoomLogic.FindAllPlayerOneRoom(model.RoomID); bool isCompleted = true; foreach (Player roomPlayer in players) { Player_Status player_status = player_StatusLogic.findPlayerStatus(roomPlayer, room_level); if(player_status == null || player_status.SavedScore < room_level.Level.Score ) { isCompleted = false; } } //If completed we find the next room_level id and open it up for each players. if (isCompleted) { foreach (Player roomPlayer in players) { Room_levels nextRoomLevel = room_LevelsLogic.getRoom_level(model.RoomID, room_level.Level.Next_level); Player_Status nextPlayerStatus = player_StatusLogic.findPlayerStatus(roomPlayer, nextRoomLevel); nextPlayerStatus.IsUnlocked = true; player_StatusLogic.updatePlayerStatus(nextPlayerStatus); } } //Udpdating the current one u have played room_LevelsLogic.updateRoomLevel(room_level); questionLogic.deletePlayerQuestions(model.LevelID, model.RoomID); if(playerStatus.Warnings == 1) { //gult kort return "Du har svaret rigtigt på " + correctedAnswers.ToString() + "/10. Det er ikke nok. Du har fået et gult kort!"; } else if(playerStatus.Warnings == 2) { //rødt kort return "Du har svaret rigtigt på " + correctedAnswers.ToString() + "/10. Det er ikke nok. Du har fået rødt kort og er blevet sparket af holdet!!"; } return "Du har svaret rigtigt på " + correctedAnswers.ToString() + "/10"; } } }
5e9b8a2f63c28c9f16b4b402edb8bb6adb6b3169
C#
wolfghost9898/cql-teacher-server
/chat-teacher-server/CQL/Componentes/Collections/Clear.cs
2.8125
3
using cql_teacher_server.CQL.Arbol; using cql_teacher_server.Herramientas; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace cql_teacher_server.CQL.Componentes { public class Clear : InstruccionCQL { Expresion id { set; get; } int l { set; get; } int c { set; get; } /* * Constructor de la clase * @param {id} Tipo de expresion * @param {l} linea del id * @param {c} columna del id */ public Clear(Expresion id, int l, int c) { this.id = id; this.l = l; this.c = c; } /* * Constructor de la clase padre * @ts tabla de simbolos padre * @user usuario que esta ejecutando las acciones * @baseD string por referencia de que base de datos estamos trabajando * @mensajes el output de la ejecucion */ public object ejecutar(TablaDeSimbolos ts,Ambito ambito, TablaDeSimbolos tsT) { Mensaje ms = new Mensaje(); object mp = (id == null) ? null : id.ejecutar(ts,ambito, tsT); if (mp != null) { if (mp.GetType() == typeof(Map)) { Map temp = (Map)mp; temp.datos.Clear(); return ""; } else if(mp.GetType() == typeof(List)) { List temp = (List)mp; temp.lista.Clear(); return ""; } else if (mp.GetType() == typeof(Set)) { Set temp = (Set)mp; temp.datos.Clear(); return ""; } else ambito.mensajes.AddLast(ms.error("No se puede aplicar un REMOVE en un tipo no Collection, no se reconoce: " + mp, l, c, "Semantico")); } else ambito.mensajes.AddLast(ms.error("No se puede insertar en un null", l, c, "Semantico")); return null; } } }
026c89a23159f9b98f16470dd57e3d2d55540f76
C#
TheFree-Man/Object-Orientated-Development
/Final Exam May 2021/UnitTestGameApplication/UnitTest1.cs
2.5625
3
using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using GameApplication; namespace UnitTestGameApplication { [TestClass] public class UnitTest1 { [TestMethod] public void TestPriceDecrease() { Game g1 = new Game("Minecraft", 88, "Test Description", "PC", 20, ""); decimal finalPrice = 10; g1.DecreasePrice(2); Assert.AreEqual(finalPrice, g1.Price); } } }
933b4e7575c77f97195ef192fd957831733192ef
C#
VictorHugoAguilar/webApiClubDeport
/webApiClubDeport/Object/Result.cs
2.765625
3
using Newtonsoft.Json; using System; namespace webApiClubDeport.Object { public class Result { private int Code { get; set; } private Boolean Resultado { get; set; } private String Message { get; set; } public Result(int code, Boolean result, string message) { this.Resultado = result; this.Code = code; this.Message = message; } public string GetResultJson() { return JsonConvert.SerializeObject(new { resultado = this.Resultado, this.Code, this.Message }); } } }
ce8dba7ae8391f750176a66992e0a9fe695dd08c
C#
newcat/LedMusic2
/LedMusic2/Nodes/DotNode.cs
2.578125
3
using LedMusic2.Attributes; using LedMusic2.Enums; using LedMusic2.Models; using LedMusic2.ViewModels; using System; using System.Windows; namespace LedMusic2.Nodes { [Node("Dot", NodeCategory.GENERATOR)] public class DotNode : NodeBase { public DotNode(Point initPosition) : base(initPosition) { Inputs.Add(new NodeInterface<double>("Center Position", ConnectionType.NUMBER, this, true, 0)); Inputs.Add(new NodeInterface<double>("Alpha", ConnectionType.NUMBER, this, true, 1)); Inputs.Add(new NodeInterface<LedColor>("Color", ConnectionType.COLOR, this, true, new LedColorRGB(0, 0, 0))); Inputs.Add(new NodeInterface<double>("Glow", ConnectionType.NUMBER, this, true, 0)); Inputs.Add(new NodeInterface<bool>("Symmetric", ConnectionType.BOOL, this, true, false)); Outputs.Add(new NodeInterface<LedColor[]>("Colors", ConnectionType.COLOR_ARRAY, this, false)); Calculate(); } public override bool Calculate() { int ledCount = GlobalProperties.Instance.LedCount; int centerPosition = (int)clamp( ((NodeInterface<double>)Inputs.GetNodeInterface("Center Position")).Value, 0, ledCount); double alpha = clamp( ((NodeInterface<double>)Inputs.GetNodeInterface("Alpha")).Value, 0, 1); double glow = clamp( ((NodeInterface<double>)Inputs.GetNodeInterface("Glow")).Value, 0, ledCount); LedColorHSV color = ((NodeInterface<LedColor>)Inputs.GetNodeInterface("Color")).Value.GetColorHSV(); bool symmetric = ((NodeInterface<bool>)Inputs.GetNodeInterface("Symmetric")).Value; LedColorHSV[] buffer = new LedColorHSV[ledCount]; for (int i = (int)Math.Floor(centerPosition - glow); i <= (int)Math.Ceiling(centerPosition + glow); i++) { if (i >= 0 && i < ledCount) buffer[i] = new LedColorHSV( color.H, color.S, alpha * Math.Max((-Math.Abs(i - centerPosition)) / (glow + 1) + 1, 0) * color.V); } if (symmetric) { LedColorHSV[] reverseColors = new LedColorHSV[ledCount]; for (int i = 0; i < ledCount; i++) { if (buffer[i] == null) buffer[i] = new LedColorHSV(0, 0, 0); reverseColors[ledCount - i - 1] = buffer[i]; } for (int i = 0; i < ledCount; i++) { buffer[i] = buffer[i].Add(reverseColors[i]); } } ((NodeInterface<LedColor[]>)Outputs.GetNodeInterface("Colors")).SetValue(buffer); return true; } private double clamp(double value, double min, double max) { return Math.Max(min, Math.Min(max, value)); } } }
488cdecd18020b69107a2e74bf82d4a9956ec1f5
C#
SudokuMonster/Sudoku
/old/Sudoku.Core.Old/Checking/PuzzleAttributeChecker.cs
2.75
3
using Sudoku.Data.Meta; using Sudoku.Solving; using Sudoku.Solving.Bf.Dlx; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Linq; namespace Sudoku.Checking { public static class PuzzleAttributeChecker { public static bool IsUnique(this Grid grid, [NotNullWhen(true)] out Grid? resultIfUnique) { try { var result = new DancingLinksSolver().Solve(grid, out _); resultIfUnique = result; return !(result is null); } catch { resultIfUnique = default; return false; } } public static bool IsMinimal(this Grid grid) { Contract.Assume(!(grid is null)); int hintCount = 0; var array = grid.ToArray(); var valueList = new Queue<(int, int)>(); for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { if (array[i, j] != 0) { hintCount++; valueList.Enqueue((i, j)); } } } var tempArrays = new int[hintCount][,]; for (int i = 0; i < hintCount; i++) { var (r, c) = valueList.Dequeue(); tempArrays[i] = (int[,])array.Clone(); tempArrays[i][r, c] = 0; } var solver = new DancingLinksSolver(); return tempArrays.All(gridArray => solver.Solve(gridArray, out _) is null); } public static bool IsPearl(this Grid grid) { // Using a faster solver to check the grid is unique or not. if (grid.IsUnique(out _)) { new ManualSolver().Solve(grid, out var info); var (er, pr) = (info.PuzzleDifficulty, info.PearlDifficulty); return er == pr; } else { // The puzzle does not have unique solution, neither pearl nor diamond one. return false; } } public static bool IsDiamond(this Grid grid) { // Using a faster solver to check the grid is unique or not. if (grid.IsUnique(out _)) { new ManualSolver().Solve(grid, out var info); var (er, pr, dr) = (info.PuzzleDifficulty, info.PearlDifficulty, info.DiamondDifficulty); return er == pr && er == dr; } else { // The puzzle does not have unique solution, neither pearl nor diamond one. return false; } } } }
7e6f072a8d47a1c7d972ea23a1f1772189a85b98
C#
srl295/NCLDR
/NCldr/Types/Calendar.cs
3.15625
3
namespace NCldr.Types { using System; using System.Collections.Generic; using System.Globalization; using System.Linq; /// <summary> /// Calendar is a CLDR calendar /// </summary> /// <remarks>CLDR reference: http://www.unicode.org/reports/tr35/#Calendar_Elements </remarks> [Serializable] public class Calendar { /// <summary> /// Gets or sets the calendar's identifier /// </summary> public string Id { get; set; } /// <summary> /// Gets or sets the calendar's localized display names /// </summary> public CalendarDisplayNames CalendarDisplayNames { get; set; } /// <summary> /// Gets or sets the calendar's date formats /// </summary> public DateFormat[] DateFormats { get; set; } /// <summary> /// Gets or sets the calendar's sets of day names /// </summary> public DayNameSet[] DayNameSets { get; set; } /// <summary> /// Gets or sets the calendar's sets of day period names /// </summary> public DayPeriodNameSet[] DayPeriodNameSets { get; set; } /// <summary> /// Gets or sets the calendar's sets of era names /// </summary> public EraNameSet[] EraNameSets { get; set; } /// <summary> /// Gets or sets the calendar's sets of month names /// </summary> public MonthNameSet[] MonthNameSets { get; set; } /// <summary> /// Gets or sets the calendar's time formats /// </summary> public TimeFormat[] TimeFormats { get; set; } /// <summary> /// Gets the calendar's CalendarType (corresponding to the calendar's Id) /// </summary> public CalendarType CalendarType { get { if (NCldr.CalendarTypes == null) { return null; } return (from ct in NCldr.CalendarTypes where string.Compare(ct.Id, this.Id, StringComparison.InvariantCulture) == 0 select ct).FirstOrDefault(); } } /// <summary> /// Gets an array of localized abbreviated day names /// </summary> public string[] AbbreviatedDayNames { get { return this.GetDayNames("abbreviated"); } } /// <summary> /// Gets an array of localized day names /// </summary> public string[] DayNames { get { return this.GetDayNames("wide"); } } /// <summary> /// Gets an array of localized shortest day names /// </summary> public string[] ShortestDayNames { get { return this.GetDayNames("stand-alone"); } } /// <summary> /// Gets an array of localized abbreviated month names /// </summary> public string[] AbbreviatedMonthNames { get { return this.GetMonthNames("abbreviated"); } } /// <summary> /// Gets an array of localized month names /// </summary> public string[] MonthNames { get { return this.GetMonthNames("wide"); } } /// <summary> /// Gets an array of localized shortest month names /// </summary> public string[] ShortestMonthNames { get { return this.GetMonthNames("stand-alone"); } } /// <summary> /// Gets the localized AM designator /// </summary> public string AMDesignator { get { DayPeriodName[] dayPeriodNames = this.GetDayPeriods("wide"); if (dayPeriodNames != null) { return (from dpn in dayPeriodNames where string.Compare(dpn.Id, "am", StringComparison.InvariantCulture) == 0 select dpn.Name).FirstOrDefault(); } return null; } } /// <summary> /// Gets the localized PM designator /// </summary> public string PMDesignator { get { DayPeriodName[] dayPeriodNames = this.GetDayPeriods("wide"); if (dayPeriodNames != null) { return (from dpn in dayPeriodNames where string.Compare(dpn.Id, "pm", StringComparison.InvariantCulture) == 0 select dpn.Name).FirstOrDefault(); } return null; } } /// <summary> /// Gets the CLDR full date pattern /// </summary> public string FullDatePattern { get { return this.GetDateFormatPattern("full"); } } /// <summary> /// Gets the .NET full date pattern /// </summary> public string FullDotNetDatePattern { get { string dateFormatPattern = this.FullDatePattern; if (dateFormatPattern == null) { return null; } return DateTimeFormat.GetDotNetFormat(dateFormatPattern); } } /// <summary> /// Gets the CLDR long date pattern /// </summary> public string LongDatePattern { get { return this.GetDateFormatPattern("long"); } } /// <summary> /// Gets the .NET long date pattern /// </summary> public string LongDotNetDatePattern { get { string dateFormatPattern = this.LongDatePattern; if (dateFormatPattern == null) { return null; } return DateTimeFormat.GetDotNetFormat(dateFormatPattern); } } /// <summary> /// Gets the CLDR short date pattern /// </summary> public string ShortDatePattern { get { return this.GetDateFormatPattern("short"); } } /// <summary> /// Gets the .NET short date pattern /// </summary> public string ShortDotNetDatePattern { get { string dateFormatPattern = this.ShortDatePattern; if (dateFormatPattern == null) { return null; } return DateTimeFormat.GetDotNetFormat(dateFormatPattern); } } /// <summary> /// Gets the CLDR long time pattern /// </summary> public string LongTimePattern { get { return this.GetTimeFormatPattern("long"); } } /// <summary> /// Gets the .NET long time pattern /// </summary> public string LongDotNetTimePattern { get { string timeFormatPattern = this.LongTimePattern; if (timeFormatPattern == null) { return null; } return DateTimeFormat.GetDotNetFormat(timeFormatPattern); } } /// <summary> /// Gets the CLDR short time pattern /// </summary> public string ShortTimePattern { get { return this.GetTimeFormatPattern("short"); } } /// <summary> /// Gets the .NET short time pattern /// </summary> public string ShortDotNetTimePattern { get { string timeFormatPattern = this.ShortTimePattern; if (timeFormatPattern == null) { return null; } return DateTimeFormat.GetDotNetFormat(timeFormatPattern); } } /// <summary> /// Gets the date separator /// </summary> /// <remarks>CLDR does not have a specific value for a date separator so this algorithm makes /// a guess based on the short date format</remarks> public string DateSeparator { get { string shortDotNetDatePattern = this.ShortDotNetDatePattern; if (string.IsNullOrEmpty(shortDotNetDatePattern)) { return "-"; } // strip away everything that isn't a date separator shortDotNetDatePattern = shortDotNetDatePattern.Replace("y", string.Empty); shortDotNetDatePattern = shortDotNetDatePattern.Replace("M", string.Empty); shortDotNetDatePattern = shortDotNetDatePattern.Replace("d", string.Empty); shortDotNetDatePattern = shortDotNetDatePattern.Replace(" ", string.Empty); shortDotNetDatePattern = shortDotNetDatePattern.Replace("e", string.Empty); if (shortDotNetDatePattern.Length > 0) { // all that should be left now is one or more date separators char dateSeparator = shortDotNetDatePattern[0]; if (dateSeparator == '-' || dateSeparator == '/') { // it is a known date separator return dateSeparator.ToString(); } } return "-"; } } /// <summary> /// Gets the time separator /// </summary> /// <remarks>CLDR does not have a specific setting for a time separator so this is a guess</remarks> public string TimeSeparator { get { return ":"; } } /// <summary> /// GetDayNames gets an array of day names for the given DayNameSet Id /// </summary> /// <param name="id">The Id of the DayNameSet</param> /// <returns>An array of day names for the given DayNameSet Id</returns> private string[] GetDayNames(string id) { if (this.DayNameSets == null) { return null; } DayName[] dayNames = (from dns in this.DayNameSets where string.Compare(dns.Id, id, StringComparison.InvariantCulture) == 0 select dns.Names).FirstOrDefault(); if (dayNames != null) { return (from dn in dayNames select dn.Name).ToArray(); } return null; } /// <summary> /// GetMonthNames gets an array of month names for the given MonthNameSet Id /// </summary> /// <param name="id">The Id of the MonthNameSet</param> /// <returns>An array of month names for the given MonthNameSet Id</returns> private string[] GetMonthNames(string id) { if (this.MonthNameSets == null) { return null; } MonthName[] monthNames = (from dns in this.MonthNameSets where string.Compare(dns.Id, id, StringComparison.InvariantCulture) == 0 select dns.Names).FirstOrDefault(); if (monthNames != null) { List<string> monthNamesList = (from dn in monthNames select dn.Name).ToList(); // the list of month names must be 13 names long while (monthNamesList.Count < 13) { monthNamesList.Add(string.Empty); } return monthNamesList.ToArray(); } return null; } /// <summary> /// GetDayPeriods gets an array of day period names for the given DayPeriodNameSet Id /// </summary> /// <param name="id">The Id of the DayNameSet</param> /// <returns>An array of day names for the given DayNameSet Id</returns> private DayPeriodName[] GetDayPeriods(string id) { if (this.DayPeriodNameSets == null) { return null; } DayPeriodName[] dayPeriodNames = (from dns in this.DayPeriodNameSets where string.Compare(dns.Id, id, StringComparison.InvariantCulture) == 0 select dns.Names).FirstOrDefault(); if (dayPeriodNames != null) { return (from dn in dayPeriodNames select dn).ToArray(); } return null; } /// <summary> /// GetDateFormatPattern gets the CLDR date format pattern for the given date format Id /// </summary> /// <param name="dateFormatId">The Id of the date format pattern to get</param> /// <returns>The CLDR date format pattern for the given date format Id</returns> private string GetDateFormatPattern(string dateFormatId) { if (this.DateFormats == null) { return null; } return (from df in this.DateFormats where string.Compare(df.Id, dateFormatId, StringComparison.InvariantCulture) == 0 select df.Pattern).FirstOrDefault(); } /// <summary> /// GetTimeFormatPattern gets the CLDR time format pattern for the given time format Id /// </summary> /// <param name="timeFormatId">The Id of the time format pattern to get</param> /// <returns>The CLDR time format pattern for the given time format Id</returns> private string GetTimeFormatPattern(string timeFormatId) { if (this.TimeFormats == null) { return null; } return (from tf in this.TimeFormats where string.Compare(tf.Id, timeFormatId, StringComparison.InvariantCulture) == 0 select tf.Pattern).FirstOrDefault(); } } }
a60128b278dd3eb7e34473efbe11b4560bb7c93e
C#
hdwangTW/01_NewbieVillage
/src/LanguageBasics/18_Disposable.cs
2.953125
3
using System.Text; using LanguageBasics.Common; using Xunit; namespace LanguageBasics { // ReSharper disable UnusedVariable public class Disposable { [Fact] public void should_call_dispose_anyway_using_try_finally() { var tracer = new StringBuilder(); DisposableWithTracingDemoClass demoDisposable = null; try { demoDisposable = new DisposableWithTracingDemoClass(tracer); } finally { if (demoDisposable != null) { demoDisposable.Dispose(); } } // change variable value to fix test. const string expectedTracingMessage = "constructor called.\r\ndispose called.\r\n"; Assert.Equal(expectedTracingMessage, tracer.ToString()); } [Fact] public void should_use_using_statement_for_simplicity() { var tracer = new StringBuilder(); using (var demoDisposable = new DisposableWithTracingDemoClass(tracer)) { // blah, blah, ... } // change the variable value to fix the test. const string expectedTracingMessage = "constructor called.\r\ndispose called.\r\n"; Assert.Equal(expectedTracingMessage, tracer.ToString()); } } // ReSharper restore UnusedVariable }
e13032406e1787e8a600f666c1e4f4401df51354
C#
Flavian/SemiCNTK
/SemiCNTK-1-Csaba/SzabolcsLecke1/ViewModel.cs
2.734375
3
using System.Collections.ObjectModel; using System.IO; using System.Linq; using System.Windows.Input; using SzabolcsLecke1.Models; namespace SzabolcsLecke1 { public class ViewModel : NotifyBase { const string SourceFolder = "SourceFiles"; #region Declaration #region Measurements private ObservableCollection<Measurement> _measurements; public ObservableCollection<Measurement> Measurements { get { return _measurements; } set { _measurements = value; OnPropertyChanged(nameof(Measurements)); } } #endregion #region Measurements private Measurement _selectedMeasurement; public Measurement SelectedMeasurement { get { return _selectedMeasurement; } set { _selectedMeasurement = value; OnPropertyChanged(nameof(SelectedMeasurement)); UpdateAfterSelectedMeasurementChange(); } } #endregion #region Measurements private LineModel _lineData; public LineModel LineData { get { return _lineData; } set { _lineData = value; OnPropertyChanged(nameof(LineData)); } } #endregion #region Alpha private double _alpha; public double Alpha { get { return _alpha; } set { _alpha = value; OnPropertyChanged(nameof(Alpha)); } } #endregion #region LogisticRegression private LogisticRegressionModel _logisticRegression; public LogisticRegressionModel LogisticRegression { get { return _logisticRegression; } set { _logisticRegression = value; OnPropertyChanged(nameof(LogisticRegression)); } } #endregion #endregion #region Commands #region CalculateOneStepCommand private ICommand _calculateOneStepCommand; public ICommand CalculateOneStepCommand { get { return _calculateOneStepCommand; } set { _calculateOneStepCommand = value; OnPropertyChanged(nameof(CalculateOneStepCommand)); } } #endregion #region CalculateOneStepCommand private ICommand _redrawLineCommand; public ICommand RedrawLineCommand { get { return _redrawLineCommand; } set { _redrawLineCommand = value; OnPropertyChanged(nameof(RedrawLineCommand)); } } #endregion #region StartCalculationCommand private ICommand _startCalculationCommand; public ICommand StartCalculationCommand { get { return _startCalculationCommand; } set { _startCalculationCommand = value; OnPropertyChanged(nameof(StartCalculationCommand)); } } #endregion #region StopCalculationCommand private ICommand _stopCalculationCommand; public ICommand StopCalculationCommand { get { return _stopCalculationCommand; } set { _stopCalculationCommand = value; OnPropertyChanged(nameof(StopCalculationCommand)); } } #endregion #endregion // ******************************************************************** #region Constructor public ViewModel() { Measurements = new ObservableCollection<Measurement>(); LineData = new LineModel(); LogisticRegression = new LogisticRegressionModel(); CreateCommands(); Alpha = 0.05; } #endregion // ******************************************************************** #region Init public void Init() { LoadDataFiles(); SelectedMeasurement = Measurements.FirstOrDefault(); LogisticRegression.CalculateCost(SelectedMeasurement?.MeasurementDatas); } private void LoadDataFiles() { if (!Directory.Exists(SourceFolder)) throw new DirectoryNotFoundException($"Directory not found: {SourceFolder}"); var files = Directory.GetFiles(SourceFolder); foreach (var file in files) { var measurement = new Measurement(); measurement.Init(file); Measurements.Add(measurement); } } #endregion // ******************************************************************** #region Commands private void CreateCommands() { CalculateOneStepCommand = new SimpleCommand(ExecuteCalculateOneStepCommand); RedrawLineCommand = new SimpleCommand(ExecuteRedrawLineCommand); StartCalculationCommand = new SimpleCommand(ExecuteStartCalculationCommand); StopCalculationCommand = new SimpleCommand(ExecuteStopCalculationCommand); } private void ExecuteCalculateOneStepCommand() { LogisticRegression.CalculateNewTheta(SelectedMeasurement.MeasurementDatas, Alpha); LogisticRegression.CalculateCost(SelectedMeasurement.MeasurementDatas); } private void ExecuteRedrawLineCommand() { LogisticRegression.CalculateCost(SelectedMeasurement.MeasurementDatas); } private void ExecuteStartCalculationCommand() { LogisticRegression.Start(SelectedMeasurement.MeasurementDatas, Alpha); } private void ExecuteStopCalculationCommand() { LogisticRegression.Stop(); } #endregion // ******************************************************************** #region Methods called from property setters public void UpdateAfterSelectedMeasurementChange() { var x1 = SelectedMeasurement.GetFirstXPosition(); var x2 = SelectedMeasurement.GetLastXPosition(); LineData.UpdateLineEndXPoints(x1, x2); } #endregion } }
3cb8b6f505a23927ac913fd20565318b5123a299
C#
yuriity/VSCThemesStore
/api/Domain/Repositories/ThemeRepository.cs
2.640625
3
using System.Threading.Tasks; using VSCThemesStore.WebApi.Domain.Models; using MongoDB.Driver; namespace VSCThemesStore.WebApi.Domain.Repositories { public interface IThemeRepository { Task<VSCodeTheme> GetTheme(string id); Task Create(VSCodeTheme theme); Task<bool> Update(VSCodeTheme theme); } public class ThemeRepository : IThemeRepository { private readonly IStoreContext _context; public ThemeRepository(IStoreContext context) => _context = context; public Task<VSCodeTheme> GetTheme(string id) { var filter = Builders<VSCodeTheme>.Filter.Eq(m => m.Id, id); return _context.Themes .Find(filter) .FirstOrDefaultAsync(); } public async Task Create(VSCodeTheme theme) => await _context.Themes.InsertOneAsync(theme); public async Task<bool> Update(VSCodeTheme theme) { var updateResult = await _context.Themes .ReplaceOneAsync( filter: g => g.Id == theme.Id, replacement: theme ); return updateResult.IsAcknowledged && updateResult.ModifiedCount > 0; } } }
171fdb926b1962b0e329c7c4dd7824afb3ed2a5b
C#
1tsTheLuffy/Project-1-a-game-R
/Project 1(A Game)/Assets/Scripts/EnemyScripts/Insect.cs
2.640625
3
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Insect : MonoBehaviour { private int randomInt; [SerializeField] float speed; [SerializeField] float timer; [SerializeField] float timeBtwNextMove; [SerializeField] Transform[] movepoints; private void Start() { randomInt = Random.Range(0, movepoints.Length); timer = timeBtwNextMove; } private void Update() { Vector2 direction = new Vector2(movepoints[randomInt].position.x - transform.position.x, movepoints[randomInt].position.y - transform.position.y); transform.up = direction; transform.position = Vector2.MoveTowards(transform.position, movepoints[randomInt].position, speed * Time.deltaTime); if(Vector2.Distance(transform.position, movepoints[randomInt].position) < 0.2f) { if(timer <= 0) { randomInt = Random.Range(0, movepoints.Length); Vector2 directionToNextMovepoint = new Vector2(movepoints[randomInt].position.x - transform.position.x, movepoints[randomInt].position.y - transform.position.y); transform.up = directionToNextMovepoint; timer = timeBtwNextMove; }else { timer -= Time.deltaTime; } } } }
0594656ad3153f9f9fd71172360b5ee5635e81c3
C#
sebastienalvarez/VisibilitePlanetes
/VisibilitePlanetes/VisibilitePlanetes/VisibilitePlanetes/MoonAndPlanetInfoPage.xaml.cs
2.65625
3
/**************************************************************************************************************************************** * * Classe MoonAndPlanetInfoPage * Auteur : S. ALVAREZ * Date : 28-07-2019 * Statut : Release * Version : 1 * Revisions : NA * * Objet : Classe permettant de représenter la page des données de visibilité avec la Lune et les planètes. * C'est une des pages de la page à onglets InfoPage. * ****************************************************************************************************************************************/ using System; using VisibilitePlanetes.ViewModel; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace VisibilitePlanetes { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class MoonAndPlanetInfoPage : ContentPage { public MoonAndPlanetInfoPage () { InitializeComponent (); } // Méthode permettant de recalculer les données de visibilité (pour raffraichissement) protected override void OnAppearing() { base.OnAppearing(); Refresh(); } // Méthode permettant de rafraichir la page suite à une action utilisateur private void ListView_Refreshing(object sender, EventArgs e) { ListView lv = (ListView)sender; Refresh(); lv.IsRefreshing = false; } // Méthode permettant de rafraichir la page private void Refresh() { MoonAndPlanetInfoViewModel vm = null; if (BindingContext != null) { vm = (MoonAndPlanetInfoViewModel)BindingContext; } if (vm != null) { vm.MoonAndPlanetsList.Clear(); vm.Compute(); } } // Méthode permettant de désactiver la mise en évidence d'une sélection (inutile et peu esthétique dans cette application) private void ListView_ItemTapped(object sender, ItemTappedEventArgs e) { ((ListView)sender).SelectedItem = null; } } }
df1c0e9b555b5ee8ae74f1a9235468a5edbf8887
C#
nnaabbcc/exercise
/windows/pw6e.official/CSharp/Chapter17/PrintMonthlyPlanner/PrintMonthlyPlanner/MonthYearSelect.xaml.cs
2.90625
3
using System; using Windows.Globalization; using Windows.Globalization.DateTimeFormatting; using Windows.UI.Xaml.Controls; namespace PrintMonthlyPlanner { public sealed partial class MonthYearSelect : UserControl { public event EventHandler MonthYearChanged; public MonthYearSelect() { this.InitializeComponent(); // Create Calendar with current date Calendar calendar = new Calendar(); calendar.SetToNow(); // Fill the first FlipView with the abbreviated month names DateTimeFormatter monthFormatter = new DateTimeFormatter(YearFormat.None, MonthFormat.Abbreviated, DayFormat.None, DayOfWeekFormat.None); for (int month = 1; month <= 12; month++) { string strMonth = monthFormatter.Format( new DateTimeOffset(2000, month, 15, 0, 0, 0, TimeSpan.Zero)); monthFlipView.Items.Add(strMonth); } // Fill the second FlipView with years (5 years before current, 25 after for (int year = calendar.Year - 5; year <= calendar.Year + 25; year++) { yearFlipView.Items.Add(year); } // Set the FlipView's to the current month and year monthFlipView.SelectedIndex = calendar.Month - 1; yearFlipView.SelectedItem = calendar.Year; this.MonthYear = calendar; } public Calendar MonthYear { private set; get; } void OnMonthYearSelectionChanged(object sender, SelectionChangedEventArgs args) { if (this.MonthYear == null) return; if (monthFlipView.SelectedIndex != -1) this.MonthYear.Month = (int)monthFlipView.SelectedIndex + 1; if (yearFlipView.SelectedIndex != -1) this.MonthYear.Year = (int)yearFlipView.SelectedItem; // Fire the event if (MonthYearChanged != null) MonthYearChanged(this, EventArgs.Empty); } } }
ed17307198c97e51f78864b630c61a7af4fa8713
C#
CountrySideEngineer/Ev3ConsoleDeepLearning
/dev/Ev3ConsoleDeepLearning/Model/ConnectState.cs
2.84375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; //using System.Windows.Media.Imaging; namespace Ev3Controller.Model { public enum ConnectionState { /// <summary> /// Device is disconnected. /// </summary> Disconnected, /// <summary> /// Canceling the connection. /// </summary> Disconnecting, /// <summary> /// Establishing device connection. /// </summary> Connecting, /// <summary> /// Established device connection. /// </summary> Connected, /// <summary> /// Sending data to device. /// </summary> Sending, /// <summary> /// Receiving data from device. /// </summary> Receiving, /// <summary> /// Connection state with device is unknown. /// </summary> Unknown, }; /// <summary> /// Represents the connection state with device. /// </summary> public class ConnectState { #region Private fields and constants (in a region) protected static Dictionary<ConnectionState, string> ResourceDictionary = new Dictionary<ConnectionState, string> { { ConnectionState.Disconnected, @"../Resource/pict/disconnected.png" }, { ConnectionState.Disconnecting,@"../Resource/pict/disconnecting.png" }, { ConnectionState.Connecting, @"../Resource/pict/connecting.png" }, { ConnectionState.Connected, @"../Resource/pict/connected.png" }, { ConnectionState.Sending, @"../Resource/pict/connected.png" }, { ConnectionState.Receiving, @"../Resource/pict/connected.png" }, { ConnectionState.Unknown, @"../Resource/pict/disconnected.png" }, }; #endregion #region Constructors and the Finalizer /// <summary> /// Constructor /// </summary> /// <param name="State">Connection state to set to State property.</param> public ConnectState(ConnectionState State) { this.State = State; this.StateImage = ConnectState.ResourceDictionary[this.State]; } #endregion #region Public properties /// <summary> /// Represent state of connection with device. /// </summary> public ConnectionState State { get; protected set; } /// <summary> /// Bitmap image which shows state. /// </summary> public string StateImage { get; protected set; } #endregion #region Other methods and private properties in calling order. #endregion } }
0e9151ced46bc2ba3105d7017a2f83b4a9ffdb8e
C#
scott-vincent/CSharp-Rules-Engine
/RulesEngine/Models/Condition.cs
2.9375
3
namespace RulesEngine.Models { public class Condition { public enum Oper { And, Or, NotDefined, IsDefined, Equal, NotEqual, LessThan, GreaterThan, LessThanOrEqual, GreaterThanOrEqual } public string Id { get; set; } public Oper Op { get; set; } public Value Value { get; set; } public override string ToString() { return $"{Id} {Op.ToString()} {Value}"; } } }
5c673495ea8664d48010c4dc445190228631ac54
C#
Akmoore7/Knightmare_OLD
/Assets/Scripts/Player/PlayerHealth.cs
2.515625
3
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerHealth : MonoBehaviour { private float health; private bool alive; public float invulCD = 0.2f; public float invulTimer = 0.0f; // Start is called before the first frame update void Start() { health = 100.0f; alive = true; } // Update is called once per frame void Update() { if(health <= 0 && alive){ alive = false; //Destroy(gameObject); } } void ApplyDamage(float[] values) { // 0 is damage[0], 1 is xMove[0], 2 is yMove[0], 3 is knockback[0] if (Time.time > invulTimer) { invulTimer = Time.time + invulCD; Debug.Log("Player Damage Applied"); health -= values[0]; //if (playerLoc.position.x - transform.position.x < 0) //{ // moveDirection.x += values[1]; // moveDirection.y = values[2]; //} //else //{ // moveDirection.x -= values[1]; // moveDirection.y = values[2]; //} } } }
e8a1d127cf205b59e3ac6bf38f2b95bf58a35776
C#
mrlvr/robocup-2014
/MRLUtilities/Commons/Tree/GNode.cs
2.8125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MRL.Commons.Tree { public class GNode<T> : ICloneable { #region Public Variables public T Data; public List<GNode<T>> Childs { set; get; } public GNode<T> Parent { set; get; } #endregion #region Private Variables private long id; public long ID { get { return id; } } #endregion #region CTor public GNode() { long newId = 1; foreach (byte b in Guid.NewGuid().ToByteArray()) newId *= ((int)b + 1); id = newId; Childs = new List<GNode<T>>(); } #endregion #region Public Methods public object Clone() { return new GNode<T>() { Childs = this.Childs.ToList(), Data = this.Data, Parent = Parent }; } #endregion } }
0e3e4f4203269cd60f27325e7bb6994209d5eb83
C#
BunkerSoft/BunkerSoft
/BunkerSoftServidor/Models/ApplicationRepository.cs
2.578125
3
using BunkerSoftServidor.Models; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; public abstract class ApplicationRepository<T> : IApplicationRepository<T> where T : class, IEntity { private DbContext _context; public ApplicationRepository(ApplicationDbContext context) { _context = context; } public async Task<IEnumerable<T>> FindAllAsync() { return await this._context.Set<T>().ToListAsync(); } public async Task<IEnumerable<T>> FindByConditionAync(Expression<Func<T, bool>> expression) { return await this._context.Set<T>().Where(expression).ToListAsync(); } public void Create(T entity) { this._context.Set<T>().Add(entity); } public void Update(T entity) { this._context.Set<T>().Update(entity); } public void Delete(T entity) { this._context.Set<T>().Remove(entity); } public async Task SaveAsync() { await this._context.SaveChangesAsync(); } public void Dispose() { if(this._context != null) { this._context.Dispose(); this._context = null; } } }
33f841200a4a8e4bf35c9d5cc1b422b2c3bf723d
C#
joshjcarrier/OpenAnt.NET
/OpenAnt.NET/OpenAnt/Services/EntityFactory.cs
2.921875
3
namespace OpenAnt.Services { using Data; using Entity; using Entity.Sprite; using Entity.Terrain; /// <summary> /// Generates game entities from world tiles. /// </summary> public class EntityFactory { /// <summary> /// The content provider. /// </summary> private readonly ContentProvider contentProvider; /// <summary> /// Initializes a new instance of the <see cref="EntityFactory"/> class. /// </summary> /// <param name="contentProvider"> /// The content provider. /// </param> public EntityFactory(ContentProvider contentProvider) { this.contentProvider = contentProvider; } /// <summary> /// Generates a game entity from a world data. /// </summary> /// <param name="data"> /// The data to generate from. /// </param> /// <returns> /// A game entity. /// </returns> public GameEntityBase Create(WorldData data) { // TODO better conversion switch (data.Type) { case EntityType.TerrainSurface: return TerrainEntity.CreateSurface(this.contentProvider.GetTerrainTexture(data.Subtype), data.Position); case EntityType.TerrainObstacle: return TerrainEntity.CreateObstacle(this.contentProvider.GetTerrainTexture(data.Subtype), data.Position, data.Size); case EntityType.Ant: return YellowAntEntity.Create(this.contentProvider, data.Position); } return null; } } }
74ed6c232202c32ff77082c746d902a82ed6d2b2
C#
GoryMoon/Bannerlord-Twitch
/BannerlordTwitch/BannerlordTwitch/Util/FileSystem.cs
2.5625
3
#if e159 using System.IO; using Path = System.IO.Path; #endif using System.Linq; using TaleWorlds.Engine; using TaleWorlds.Library; namespace BannerlordTwitch.Util { #if e159 public struct PlatformDirectoryPath { public PlatformDirectoryPath(string path) { Path = path; } public string Path; public override string ToString() => Path } public struct PlatformFilePath { private readonly PlatformDirectoryPath dir; public PlatformFilePath(PlatformDirectoryPath dir, string partialPath) { this.dir = dir; this.partialPath = partialPath; } private readonly string partialPath; public string FilePath => Path.Combine(dir.Path, partialPath); public override string ToString() => FilePath; } #endif public static class FileSystem { #if e159 public static PlatformDirectoryPath GetConfigDir() => new(Path.Combine(Common.PlatformFileHelper.DocumentsPath, "Mount and Blade II Bannerlord", "Configs")); public static PlatformFilePath GetConfigPath(string fileName) => new PlatformFilePath(GetConfigDir(), fileName); public static bool FileExists(PlatformFilePath path) => File.Exists(path.FilePath); public static void SaveFileString(PlatformFilePath path, string str) => File.WriteAllText(path.FilePath, str); public static string GetFileContentString(PlatformFilePath path) => File.ReadAllText(path.FilePath); public static PlatformFilePath[] GetFiles(PlatformDirectoryPath path, string searchPattern) => Directory.GetFiles(path.Path, searchPattern).Select(p => new PlatformFilePath(path, Path.GetFileName(p))).ToArray(); public static void DeleteFile(PlatformFilePath path) => File.Delete(path.FilePath); #else public static PlatformDirectoryPath GetConfigDir() => EngineFilePaths.ConfigsPath; public static PlatformFilePath GetConfigPath(string fileName) => new (GetConfigDir(), fileName); public static bool FileExists(PlatformFilePath path) => Common.PlatformFileHelper.FileExists(path); public static void SaveFileString(PlatformFilePath path, string str) => Common.PlatformFileHelper.SaveFileString(path, str); public static string GetFileContentString(PlatformFilePath path) => Common.PlatformFileHelper.GetFileContentString(path); public static PlatformFilePath[] GetFiles(PlatformDirectoryPath path, string searchPattern) => Common.PlatformFileHelper.GetFiles(path, searchPattern); public static void DeleteFile(PlatformFilePath path) => Common.PlatformFileHelper.DeleteFile(path); #endif } }
0117f89d96b8d18bb78618a223e1d6a238de4020
C#
zurachan/ACAG
/ACAG.Abacus.CalendarConnector.Exchange/EWSHelper.cs
2.6875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ACAG.Abacus.CalendarConnector.Models.Abacus.V1_0; using Newtonsoft.Json; namespace ACAG.Abacus.CalendarConnector.Exchange { public static class EWSHelper { private static string ToHexString(string str) { var sb = new StringBuilder(); var bytes = Encoding.UTF8.GetBytes(str); foreach (var t in bytes) { sb.Append(t.ToString("X2")); } return sb.ToString(); } private static string FromHexString(string hexStr) { var bytes = new byte[hexStr.Length / 2]; for (int i = 0; i < bytes.Length; i++) { bytes[i] = Convert.ToByte(hexStr.Substring(i * 2, 2), 16); } return Encoding.UTF8.GetString(bytes); } private static JsonSerializerSettings GetJsonSetting() { return new JsonSerializerSettings { StringEscapeHandling = StringEscapeHandling.EscapeHtml, Formatting = Formatting.Indented }; } public static string ObjectToString<T>(T item) { var itemValue = ToHexString(JsonConvert.SerializeObject(item, GetJsonSetting())); return itemValue; } public static T StringToObject<T>(string itemValue) { return JsonConvert.DeserializeObject<T>(FromHexString(itemValue)); } /// <summary> /// You can modify this logic style to generate itemId for appointment /// </summary> /// <param name="data"></param> /// <returns></returns> public static string CreateItemId(AppointmentModel data, int tenantId) { return ToHexString(string.Format("{0}{1}{2}", tenantId, data.AbacusID, data.MailAccount)); } } }
3ce0d2334d2431b34f370cbbd3e57c7656e33cac
C#
khughes0123/GoldBadgeConsoleChallenges
/KomodoCafeRepo/MenuItem_Repo.cs
3.078125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace KomodoCafeRepo { public class MenuItem_Repo { private readonly List<MenuItem> _directory = new List<MenuItem>(); public bool AddMenuItemtoDirectory(MenuItem item) { int directoryLength = _directory.Count(); _directory.Add(item); bool wasAdded = directoryLength + 1 == _directory.Count(); return wasAdded; } public List<MenuItem> GetItems() { return _directory; } public MenuItem GetItemsByName(string name) { foreach (MenuItem item in _directory) { if (name.ToLower() == item.MealName.ToLower()) { return item; } } return null; } public bool DeleteItemFromDirectory(string name) { MenuItem itemToDelete = GetItemsByName(name); return _directory.Remove(itemToDelete); } } }
ab3777d59968a62f9be0da2b608c8b7d2ac60c92
C#
joel-chen/EmrWorkflow
/EmrWorkflow/Run/Activities/StartJobActivity.cs
2.515625
3
using Amazon.ElasticMapReduce; using Amazon.ElasticMapReduce.Model; using EmrWorkflow.Model; using EmrWorkflow.RequestBuilders; using System.Threading.Tasks; using System.Xml; namespace EmrWorkflow.Run.Activities { /// <summary> /// A strategy to start a new cluster to run an EMR Job /// </summary> public class StartJobActivity : EmrActivity { private JobFlow jobFlow; /// <summary> /// Constructor /// </summary> /// <param name="name">Name of the activity</param> /// <param name="jobFlowXml">XML Document describing JobFlow</param> public StartJobActivity(string name, XmlDocument jobFlowXml) : base(name) { this.jobFlow = JobFlow.GetRecord(jobFlowXml.OuterXml); } /// <summary> /// Constructor /// </summary> /// <param name="name">Name of the activity</param> /// <param name="jobFlow">JobFlow object</param> public StartJobActivity(string name, JobFlow jobFlow) : base(name) { this.jobFlow = jobFlow; } /// <summary> /// Send a request to EMR service to start and configure a new job /// </summary> /// <param name="emrClient">EMR Client to make requests to the Amazon EMR Service</param> /// <param name="settings">Settings to replace placeholders</param> /// <param name="jobFlowId">Existing jobflow Id, can be null for the new job.</param> /// <returns>JobFlow Id, if request failed -> returns null</returns> public override async Task<string> SendAsync(IAmazonElasticMapReduce emrClient, IBuilderSettings settings, string jobFlowId) { RunJobFlowRequestBuilder builder = new RunJobFlowRequestBuilder(settings); RunJobFlowRequest request = builder.Build(this.jobFlow); RunJobFlowResponse response = await emrClient.RunJobFlowAsync(request); if (!this.IsOk(response)) return null; return response.JobFlowId; } } }
213fee6c6557ebf21bae6b18884203fb4e357184
C#
yu-zyu/Design_Pattern_of_Unity
/Assets/13_Visitor/exercises/Entry.cs
2.625
3
using System.Collections; using System.Collections.Generic; using UnityEngine; using System; namespace VisitorPattern_exercises { public abstract class Entry : Element { public abstract string getName(); public abstract int getSize(); public Entry Add(Entry entry) { throw new FileTreatmentException(); } public abstract void Accept(Visitor v); public IEnumerator Iterator() { throw new FileTreatmentException(); } public string toString() { return getName() + " (" + getSize() + ")"; } } }
045634b9696ca7e35f2a9521285c95142ab0a8e6
C#
danieltadresu/ferme-app
/ferme-api/utils/templates/Bill.cs
2.96875
3
using System; using System.Text; using Models; using System.Collections.Generic; namespace utils.templates { public static class Bill { public static string GetHTMLString( Order order ) { List<Models.CartItem> cartItems = Connection.CartItemConnection.GetEntitiesByOrderId(order.Id); foreach(var item in cartItems) { Models.Product product = Connection.ProductConnection.GetEntity(item.ProductId); item.ProductName = product.Name.ToUpper(); item.ProductUnitPrice = product.Price; }; Models.Person customerPurchasePerson = Connection.PersonConnection .GetEntity(order.CustomerId); Models.User customerPurchaseUser = Connection.UserConnection .GetEntityByPersonId(customerPurchasePerson.Id); Models.UserRole customerPurchaseUserRole = Connection.UserRoleConnection .GetEntityByUserId(customerPurchaseUser.Id); String documentType = null; if (order.PaymentMethodId == 1) { documentType = "TARJETA DE CRÉDITO"; } else { documentType = "EN EFECTIVO"; }; var sb = new StringBuilder(); #region HEADER SECTION sb.Append(@" <html> <head> </head> <body> <div class='header'> <p class='header-title'> Ferme Store </p> <p class='header-date'> 29 de junio de 2021 </p> <hr /> </div> "); #endregion #region SUB HEADER SECTION sb.Append(@" <div class='sub-header'> <p class='sub-header-title'> Gracias por tu compra, "); sb.Append($"{customerPurchasePerson.FirstName} {customerPurchasePerson.LastName}"); sb.Append(@" </p> <p class='sub-header-message'> Este es el recibo de tu compra </p> </div>" ); #endregion #region PAYMENT DETAILS SECTION sb.Append($@" <div class='payment-detail-section'> <p class='payment-detail-title'>Total</p> <p class='payment-detail-total-price'>{order.TotalPurchase} CLP</p> <hr /> </div> "); sb.Append(@"<div class='payment-detail-section'>"); foreach(var item in cartItems) { sb.Append($@" <div> <a class='paymental-detail-name'> {item.ProductName} </a> <a class='paymental-detail-name'> {item.ProductUnitPrice} CLP. Precio Unitario </a> <a class='paymental-detail-price'> {item.ProductQuantity} UDS. Cantidad </a> <a class='payment-detail-item'> {item.ProductUnitPrice * item.ProductQuantity} </a> <hr /> </div>" ); } sb.Append(@"</div>"); #endregion #region PAYMENT METHOD TYPE SECTION #endregion sb.Append(@" </body> </html>"); return sb.ToString(); } } }
bfff42f83d079436425d02ce4070a5ffb008b227
C#
ZhenDeng/ProductOrderSystem
/Trojantrading/Repositories/Generic/GenericRepositoryV2.cs
2.703125
3
using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq.Expressions; using System.Threading.Tasks; namespace Trojantrading.Repositories.Generic { public class GenericRepositoryV2<TEntity> : ReadOnlyRelationshipRepositoryV2<TEntity>, IRepositoryV2<TEntity> where TEntity : class { public GenericRepositoryV2(TrojantradingDbContext context) : base(context) { } public void Delete(object id) { var entity = _dbSet.Find(id); Delete(entity); } public void Delete(TEntity entity) { var entry = _context.Entry(entity); if (entry != null && entry.State != EntityState.Detached) entity = (TEntity)entry.Entity; else if (_context.Entry(entity).State == EntityState.Detached) _dbSet.Attach(entity); _dbSet.Remove(entity); } public void DeleteRange(List<TEntity> entity) { _dbSet.RemoveRange(entity); } public virtual Task SaveChangesAsync() { return _context.SaveChangesAsync(); } public virtual void Create(TEntity entity) { _dbSet.Add(entity); } public virtual void CreateRange(List<TEntity> entity) { _dbSet.AddRange(entity); } public virtual void UpdateRange(List<TEntity> entity) { _dbSet.UpdateRange(entity); } public virtual void Update( TEntity entity, Expression<Func<TEntity, object[]>> excludeProperties = null, Expression<Func<TEntity, object[]>> includeProperties = null) { var entry = _context.Entry(entity); if (entry != null && entry.State != EntityState.Detached) { _dbSet.Update(entity); entity = (TEntity)entry.Entity; } else { _dbSet.Attach(entity); _context.Entry(entity).State = includeProperties != null ? EntityState.Unchanged : EntityState.Modified; } StringCollection strCollection = new StringCollection(); NewArrayExpression array = null; if (excludeProperties != null) array = excludeProperties.Body as NewArrayExpression; else if (includeProperties != null) array = includeProperties?.Body as NewArrayExpression; if (array != null) foreach (var expression in array.Expressions) { string propertyName; if (expression is UnaryExpression) { propertyName = ((MemberExpression)((UnaryExpression)expression).Operand).Member.Name; } else { propertyName = ((MemberExpression)expression).Member.Name; } strCollection.Add(propertyName); } if (excludeProperties != null) { foreach (var propName in strCollection) _context.Entry(entity).Property(propName).IsModified = false; } else if (includeProperties != null) { foreach (var propName in strCollection) _context.Entry(entity).Property(propName).IsModified = true; } } } }
fb0a4992f7f58c35adab31663b48d77df4d9810a
C#
aonuryilmaz/BasketApi
/Basket.Core/Domain/Models/BasketItem.cs
2.703125
3
using System; namespace Basket.Core.Domain.Models { public class BasketItem { public string Sku { get; set; } public string Name { get; set; } public int Quantity { get; set; } public int UnitPrice { get; set; } public static BasketItem FromProduct(Product product,int quantity=1) { return new BasketItem { Sku = product.Sku, Name = product.Name, UnitPrice = product.UnitPrice, Quantity = quantity }; } } }
138e99eb867fa3e6724f396be8b8a78eec20761d
C#
ABErlich/CoreAngular7Template
/Organigrama.Repositories/BaseRepository.cs
2.546875
3
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Linq.Expressions; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.ChangeTracking; using Microsoft.EntityFrameworkCore.Storage; using Organigrama.Interfaces.Repositories; using Organigrama.Models; using Organigrama.Models.Context; using Organigrama.Models.EntityBase; namespace Organigrama.Repositories { public class BaseRepository<T>: IBaseRepository<T> where T: EntityBase { //protected IApplicationContext context; protected readonly DbContext context; protected IDbContextTransaction contextTransaction; public BaseRepository(ApplicationContext _context){ context = _context; } public DbContext GetContext() { return context; } public void Save(T domain) { try { domain.CreatedOn = DateTime.Now; context.Set<T>().Add(domain); } catch (Exception ex) { // handle throw ex; } } public bool Update(T domain) { try { domain.UpdatedOn = DateTime.Now; var entry = this.context.Entry(domain); var key = this.GetPrimaryKey(entry); if (entry.State == EntityState.Detached) { var currentEntry = this.context.Set<T>().Find(key); if (currentEntry != null) { var attachedEntry = this.context.Entry(currentEntry); attachedEntry.CurrentValues.SetValues(domain); } else { this.context.Set<T>().Attach(domain); entry.State = EntityState.Modified; } } Update(domain); return true; } catch (Exception ex) { //ErrorManager.ErrorHandler.HandleError(ex); throw ex; } } public void SaveOrUpdate(T domain) { var entry = this.context.Entry(domain); var key = GetPrimaryKey(entry); if (entry.State == EntityState.Detached) { var currentEntry = this.context.Set<T>().Find(key); if (currentEntry != null) { var attachedEntry = this.context.Entry(currentEntry); domain.UpdatedOn = DateTime.Now; attachedEntry.CurrentValues.SetValues(domain); } else { this.context.Set<T>().Attach(domain); entry.State = EntityState.Added; } } } public void Delete(T domain) { try { context.Set<T>().Remove(domain); } catch (Exception ex) { //ErrorManager.ErrorHandler.HandleError(ex); throw ex; } } public IQueryable<T> GetAll() { try { return context.Set<T>(); } catch (Exception ex) { //ErrorManager.ErrorHandler.HandleError(ex); throw ex; } } public T GetById(int id){ try{ return context.Set<T>().Find(id); }catch(Exception ex){ throw ex; } } public IQueryable<T> Where(Expression<Func<T, bool>> predicate) { return context.Set<T>().Where(predicate); } private int GetPrimaryKey(EntityEntry entry) { var myObject = entry.Entity; var property = myObject.GetType() .GetProperties().FirstOrDefault(prop => Attribute.IsDefined(prop, typeof(KeyAttribute))); return (int)property.GetValue(myObject, null); } } }
b2657769ee604bcf49ac0dc5b347a75f2b2fc4f0
C#
rattarius/BLOODYFANTASTICPLATFORMER
/Player.cs
2.625
3
 using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using System; using System.Collections; namespace AwesomePlatformer { /// <summary> /// This is the main type for your game. /// </summary> class Player { Sprite sprite = new Sprite(); public Player() { } public void Load(ContentManager content) { sprite.Load(content, "hero"); } public void Update(float deltaTime) { sprite.Update(deltaTime); } public void Draw(SpriteBatch spriteBatch) { sprite.Draw(spriteBatch); } } }
ec22842e0ac92615f3392028d16a89339b6831ed
C#
Refocosta/Refosus
/Refosus.Web/Helpers/FileHelper.cs
2.625
3
using Microsoft.AspNetCore.Http; using System; using System.IO; using System.Threading.Tasks; namespace Refosus.Web.Helpers { public class FileHelper : IFileHelper { public async Task<string> UploadFileAsync(IFormFile File, string folder) { string guid = Guid.NewGuid().ToString(); string ext = Path.GetExtension(File.FileName); string file = $"{guid}" + ext; string path = Path.Combine( Directory.GetCurrentDirectory(), $"wwwroot\\Message\\{folder}", file); using (FileStream stream = new FileStream(path, FileMode.Create)) { await File.CopyToAsync(stream); } return $"~/Message/{folder}/{file}"; } } }
84460899e8e9679606c580dc225f6a04802a6874
C#
KristaRutz/Scrabble-scorer-ConsoleApp
/ScrabbleScore/Program.cs
3.46875
3
using System; using ScrabbleScore.Models; namespace ScrabbleScore { public class Program { public static void Main() { Console.WriteLine("Enter your word to calculate it's Scrabble score."); string userInput = Console.ReadLine(); try { int score = ScrabbleScorer.Score(userInput); Console.WriteLine($"'{userInput}' is worth {score} points."); } catch (Exception ex) { Console.WriteLine("ERROR: {0}", ex.Message); } Main(); } } }
ae3c74817c3af59ac73a3b7c4e6878df3345e5c5
C#
tuboring/tuboring
/WindowsFormsApp1/Tickets.cs
2.71875
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.Data.SqlClient; namespace WindowsFormsApp1 { public partial class Tickets : Form { SqlConnection con = Program.con; public Tickets() { InitializeComponent(); } private void Tickets_Load(object sender, EventArgs e) { // TODO: данная строка кода позволяет загрузить данные в таблицу "databaseVolleyBallDataSet1.Event". При необходимости она может быть перемещена или удалена. this.eventTableAdapter.Fill(this.databaseVolleyBallDataSet1.Event); comboBox2.SelectedIndex = -1; } DateTime DateStart; private void comboBox2_SelectedIndexChanged(object sender, EventArgs e) { if (comboBox2.SelectedIndex != -1) { string query = "SELECT [Event].[CityName], [Event].[StartDateTime] From [Event] where [Event].[EventId] = '" + comboBox2.SelectedValue + "'"; con.Open(); SqlDataAdapter da = new SqlDataAdapter(query, con); DataTable dt = new DataTable(); da.Fill(dt); textBox1.Text = dt.Rows[0][0].ToString(); DateStart = Convert.ToDateTime(dt.Rows[0][1]); con.Close(); } } private void button1_Click(object sender, EventArgs e) { if (comboBox2.SelectedIndex != -1 && numericUpDown1.Value > 0 && numericUpDown1.Value < 100 && comboBox5.SelectedIndex != -1) { int Sale = 0; if (comboBox5.SelectedIndex == 2) Sale += 5; if (numericUpDown1.Value > 2) Sale += 20; TimeSpan diff = DateStart - dateTimePicker1.Value; if (diff.Days >= 35) Sale += 10; label4.Text = Sale.ToString() + "%"; } } } }
caa207cfcdca7b007abdbbdfbc16899dd0e72311
C#
technos12/AdventOfCode_2020
/Day5/Data.cs
2.5625
3
using System; using System.Collections.Generic; using System.Text; namespace Day5 { public static class Data { public static List<string> GetInputs() { return new List<string> { "FFBBFFFLRL", "FFBBFBBRRL", "FBBBFFBLRL", "BBFBFFBLRR", "BFBBBFFLLL", "BFBBBBBLLR", "FBFBFBFLLR", "BFBFBBFLLR", "FBBFBFBLLL", "BBBFBFBRLL", "BFBBBFBLRL", "FBBFFFBLLR", "BFFBFBFLRL", "FBBBBFBRLR", "FFBBBBBRRL", "FBBFBFFLRL", "FBBBBBBLLR", "FBBFBBBRRL", "FBBFFBFRLL", "FBFBBBBRRR", "BFFBFBFRRL", "BFBFBBBLLR", "FFFFBFBLRL", "FBFFBFFLRL", "FFBFBBBRRR", "FFBFFFFLRR", "FBBBFFFLLR", "FFFFFBFLLL", "BFFFFFFLRL", "FBBBBBFRLR", "BBBFFBBRRR", "FFFFBBBRLL", "FBFFBBBRLR", "BFBBBFFRRL", "BBFBBFBLRL", "BFBFBFFRRR", "BBFBFFFLLL", "FBFBFBFRRR", "BFBFBFFRRL", "BBFBBFBRRL", "FFBBFBFLRL", "FBFFFFFRLR", "FBBFFFBLLL", "FBBBBFFRLL", "FFBBBBBLLL", "BFFBBFFRLR", "FFFBBFBRRR", "FBBBFFFRLL", "FFFBFBFLRL", "BFFBBFFLRL", "BFBBBBBLRL", "BFFFFFBRRR", "FFFBBFBLRL", "FBBBFBFRLL", "FBBFBFBLRR", "BBFBBFFLRR", "FBFFBBFLLL", "FFFFFBBRLL", "FFBBFFBRLR", "BBFFFFFLLL", "BFFFFBFLRR", "FBFBBFFRRL", "BFBFFBBLLR", "FBBBFBBRLR", "BBBFBFFRLL", "BBFFBBFRLR", "FFBFFBBRLR", "FFBBBFBRLR", "BBBFFFBLRR", "BBFBFBFLRR", "BFBBBBBRLR", "BFFFFFBLLR", "FBFFBFFRLL", "BBBFFBBRLR", "FFBBBFBRRR", "BFBBBFBRLR", "FBFFFBBLRL", "FFFBFFFRLL", "BBFFBFFLLL", "BFFBBFFRRR", "FFBFBFBRRL", "FFBBBFBRRL", "FBBFFBBRLR", "FBFFBBFRLR", "BFBFFBBRRR", "BBFBFBBRLR", "FFBFFFFRRL", "BBFFBFFLLR", "FBBFBFBRRR", "BFBFBBBRRL", "FBFBFFBRRL", "FFFBBFFRLL", "BFBFFFFRRR", "FBBFFBFLLR", "FFBFBFFRLL", "FBFFBFBLLL", "FBFBFFFLRL", "BBFFFFFRRR", "FBFFBBFLRR", "FBFFFBFLRL", "FBBBFBBRRL", "BFFBFFFRLR", "FFBBBBFLLR", "BFFFFBFLRL", "BFFBFFBRRR", "FFBFBFBLRL", "BBFFFBBRLL", "FFBFBBFRRR", "FFFBFBFRRL", "FBFFBFBRRR", "FBBBBFBRRL", "FBFFFFFLLR", "FFBFFFFLLR", "FBBBBFFRLR", "BBBFFBBLRR", "BBBFFBFLRR", "FBBFBBBLRR", "FBBFBBFRRL", "FFFBFFBLLL", "FBFFFFBLLL", "BBFFFFBLLL", "FBFFFBFLRR", "FFBFBFFLRR", "BBFBFFFRLL", "FFFBBBFRLR", "FFBFFBBRLL", "BBBFBFFRRL", "BFFBBBBLRR", "BFFFFFFLLL", "BBBFFFBLLL", "FBBBBBFRLL", "FBBFBBBLLR", "BBFBFFFRRR", "BBFFFBBLLL", "FBBFFBFLRL", "BBFBFFFLRR", "BFBFFBFRLL", "BFFFBFBLLR", "BBBFBFBLLL", "BBBFFBFRLR", "FBFFBFBRLR", "BFBBFFFLLL", "BBFFFFBLRR", "BBFFFBBRRL", "BBBFBFFLLL", "BFBFFBFLLL", "FBBBBFFLLR", "FFBFFFFRLR", "FFBBBFBRLL", "BFFFFFFRRL", "BFBFFBBLRL", "BBFBBBFRLL", "BFFFBFFLLR", "BBFBFFBRLL", "BFBBFFFRLL", "BBFBBFBRLR", "FFFBBFBRLR", "BFFFBBFLRL", "FFBFFBFRLL", "FFFBFFBLRL", "BFBBBFFRLR", "BBBFFBBLRL", "BFFBBBBRRL", "FFBBFFFRLL", "BFBFFBFLRL", "BFFBBBBRRR", "BBFBFBFRRL", "BBBFFBFRRL", "BFFFBFBLRL", "FFFBFBFRLR", "FBFFBBBLRR", "FFFFBBBLLL", "BBBFBBFLLR", "BFFBFBFRRR", "BFBFFFBRRR", "BBFBBBBLLR", "FFBBBBBLRL", "FFBFFBFLRR", "FFBBBFBLRR", "BBFBBFBRRR", "FFFFFFBRRR", "BFBFBFBRRL", "BBFFBBBLRR", "BBFBFFFRLR", "FBBFBFBLLR", "BFBBFFBRLL", "FFFFBFBLLR", "BFBFFBBRLR", "FBFFFBFRRR", "BFFBFFFRLL", "FBBBFFFRRR", "FFFBBBFLLL", "FBBBBBBRRL", "FBBFFBBLLR", "BBBFBFFLRR", "BFBBFBFLRR", "FFFBBBBRRR", "BFFFBBFRLR", "FBFFBBFLLR", "FBFFFFFRRL", "BBBFBBFLLL", "BBBFFFFRLR", "FFFFBBBRRR", "FBBBFBBLLL", "BFFBFFBLLL", "FBFBBFBRLR", "FFBFFBBLLR", "FFFFBFFLRR", "FBBFFBFLLL", "FBFBBFBRRR", "BBBFBFBLLR", "BBFFBFBLLL", "FFBFFBFRLR", "FBBBFBBLRR", "BBFBBFBLLL", "FFBFFBFRRR", "FBBBBFFLRL", "BFBBFBFLLR", "FBFBBBFRLR", "BFBBFFBLLR", "FFFBBBFLLR", "FFFBBBFRRL", "BFFFBFBRLR", "BBBFBBFLRR", "BBFBBFFLLR", "BBFBBBBRLR", "FBBFFFFLRR", "FBFBBFFRLL", "FFBFFFFRRR", "FFFBBFFRRL", "FFFBBFBRRL", "FFFBFBFLLR", "FFBBBBFRRR", "BFFFFBBRRL", "BFFFFBFRRR", "BFBBBFBLRR", "FFBBFFFRRL", "FBBBBBBRRR", "BBFBFFBLLR", "FBFFFFBRLL", "BFBBFBFLLL", "FBFFFBBRLL", "FBBBFFBLLR", "BBFBBBFRLR", "FBFBBFBLRR", "FFFFFBFLLR", "FBFBBBFLRL", "FFBFFFBRRR", "FFFBBFFLRL", "BBBFFFFLLR", "BFBFFFFRRL", "FBFBFBBLLR", "FBBBFBFRRL", "BBFBBBBRRL", "BFBBFBFLRL", "BFFBBFFLLR", "BFBFFBBRLL", "FBFFBFFRLR", "FBFBFBFLRR", "BFBFBBFRRR", "FBBBBFBLRL", "FFBBBFFRRR", "FFBBFFBRLL", "FFBBBBBRLL", "FBFFFBFRRL", "FFFBBBFLRL", "BBBFBFFRRR", "FFFBFFFRRR", "FBFFBFFLLL", "FFBBFFBRRL", "BFFBFFBRRL", "FFBBBFFRLR", "BBBFFFFRRR", "BBFBFBBRRR", "FBFBBBBLRR", "BFBFBFBLLL", "FFBBFFBLLR", "BFFFBBBRLR", "BFBBFBBRLR", "BFFFFBBLLR", "FBFBFBBRLR", "BFFBBBFLLR", "FBFFBFBLRL", "BFBFBBBRLL", "BFBBBFFLRL", "FFFBFFFLRR", "BFFBBFBRLL", "FFBBBBFRLL", "BBFFFBBLLR", "FBFBFBFRLR", "BBBFFFBRLR", "BFFFFFBRLR", "BBBFFFFLLL", "FFFBBFBRLL", "BFFFFFBRRL", "FBFFBBBRRL", "FBFBFBBLLL", "FBFBBFBRRL", "FBBFBBBRRR", "BFBFFBBRRL", "FBBBBFBLLL", "FBBBBBBRLR", "BBFFFBFRRL", "FFFFBFBLLL", "FFFFBBFLRR", "FFFFBFFLRL", "BFFFBBFRLL", "BBFFFFBRRR", "BFBFFFFRLL", "BFFFFBFLLR", "BBBFFBBRRL", "BBFBBFBLLR", "BFFFFBFRLR", "FBBBFBFLLR", "FFFFFBBLRR", "BFBFFFFLRR", "FBFBBFFLRL", "FBFFFBBRRR", "BBFBBBFLRL", "BFBBBFFLLR", "BFBFBBFRRL", "FBFFFFBLRL", "FBBFBFFRLR", "BFBFBBBLRR", "BFBFBBFLRL", "BBFFBFFRLL", "FBFFBBBLRL", "BFBFBFFLLR", "FFFBFFBLLR", "FFFBFBBRRR", "BBFBFFFLLR", "FBBBFBFRLR", "FBFFBBBLLL", "FFBFBBFLRR", "FBFBFFFLLL", "BBFFFFFLRL", "FBFBBFBLRL", "BBFFFBFLLR", "BBFBBBBRRR", "BFBBBFFRRR", "FFFBFFBRLL", "FBBBFFFRLR", "BBBFBFBLRL", "FBFFFFBRLR", "BFFFFFBLLL", "FBFFFFBLLR", "BFBBFFBLRR", "BFBFBBBRRR", "BBBFBFBRRR", "FFFBBFFRRR", "FBBBFFFLRR", "BBFBFFFRRL", "BFBFBBFRLR", "BFFFBFBRLL", "FBFFFFFLLL", "FFFBBBBLRL", "FFFBBFFLLL", "FBFFFFBRRR", "FFBFBFBRLR", "BFBFFFBLRR", "BFFFBFBLLL", "FBBFBFFRLL", "FBFBFFFRLL", "FBBBFFBRRR", "FBBBFFBRLL", "FFBBFBBLLL", "FBBBBFBRRR", "BFBBBFBLLR", "FBBBBBFLLR", "FFBBFBFLRR", "BFFBBFBLLR", "FBFFFFBLRR", "BFFBFFFRRR", "BFFFBBBRLL", "FBFBBBFRLL", "BFBBBFBRRL", "FFBFFFBRRL", "FBBFFFFRLR", "BFBFBFFLLL", "FFBFBFBLLL", "FBFBBFBRLL", "FBFBFFBRLR", "BFFFFFBLRR", "FBBBFFBRLR", "BFBBFBBLLL", "BBFFBFBRRR", "FFFBFBBRRL", "FFBBBFFRLL", "BFFFFFFRLL", "BFBFFFBRLL", "FFFFFBFRLL", "BBBFFFBRRL", "FFBBBBFRRL", "BFFFBBBLRL", "FFFFFBBLLR", "BFFFFBBLRR", "BFBFFFBLLL", "FFFFFBBRLR", "BBFBFBFLLL", "FBFBBBBRLR", "FBBFBFBRRL", "FFBFBFBRRR", "FBBBBBFLRL", "BBFBFFBLLL", "BBFFFFBRLL", "BBBFBFBRLR", "BBFBFBBLLL", "BFBBBBBLRR", "BBFFFBFRRR", "FFFBFBFRLL", "BFFBBFBLLL", "FBFFBBBRRR", "FFFBFBFLLL", "BBFFBBFLRL", "BBFFFFBRLR", "BFBFBBBRLR", "BBBFBFFLLR", "FFBBBBFRLR", "BBFFBFFRRL", "BBFBFFBRRR", "BFBFFBFLLR", "FBFFBBFRLL", "BBFFFFBLLR", "FBFBFFFRLR", "FFBFBFBLLR", "BFBBFFBRRL", "FBBFFBBRRL", "BBFFBFBRLR", "FFFFBFBLRR", "FFFFBBBLRR", "FFBFBFFLLL", "FFBBBFFRRL", "BBFFFBFRLL", "FBFBBBFLRR", "FBBFBFFRRR", "FBBFBFFLLR", "BFFBBBFLRR", "FBBFBBFRLR", "BFFBBBFLLL", "BBFBBFBRLL", "BBBFFBBLLR", "BBBFBFBRRL", "FBFBBBFRRL", "FBBFFFBRLR", "BFBBFBBLRL", "FFBBFFFRRR", "BFBFFFFRLR", "BBFFFFFLLR", "BBFBFFBRLR", "BBFBFBFLRL", "FBFFFFFLRL", "FFBBBFFLRL", "FBFBFBBLRR", "FFBFBBBRLL", "FFBFBFFRLR", "FBBBFBFLRR", "FBFFBFFLRR", "BBFFBFBRRL", "FBBFFFFLRL", "FFFFBBFLRL", "FFBBFFBLRR", "BFBFFFBLLR", "BFBFBBFLRR", "BFBFBFBLLR", "BFBBFBFRLL", "BFBBFFBRLR", "FBFFFBBLLL", "FFFBBBBRRL", "FBBFBFFLLL", "FBFFBFBRLL", "BFFBFFFRRL", "FBFBFFBLLR", "BBFFBBFLLL", "FFBBBFBLLR", "BFBBFFFLLR", "FBBBFBFRRR", "FBBBFFBRRL", "FFFFBBFRRR", "FFBFFFFLRL", "FBBFBBFLRR", "FFBBBFBLLL", "FBFFFBFRLR", "FFBFFBBRRL", "FFFFBBFRRL", "BBBFFFFLRL", "FBBFFFBLRL", "FFBFBFBLRR", "FFFFBFFRRR", "FFFBFBFRRR", "BBFBBBBLLL", "FFBBFFBRRR", "FBBFFBBLRR", "FBBFBBFLLL", "BBFBBBFRRL", "FFFBBBBLLR", "FFBFFBBLRR", "BBFBBFFRLL", "BFBBBBFRLL", "BBFBFFBRRL", "BFFFBBFRRL", "FBBBBBBLLL", "FFBBFFBLLL", "FFBBFBBLRR", "BFBFBFBLRR", "FBBBFBBLLR", "BBFBFBFRLL", "FBBFBFFLRR", "FBBBFBFLLL", "FFBBFFFLRR", "BFFBBBFRLL", "FBBBBFBLLR", "BFBFFFFLRL", "FFBFBBBLLL", "FFBFFFBLRR", "BFBFBFBRLL", "FBFBFBFRLL", "BFBBBBBLLL", "FFBFBFBRLL", "BFBFFFFLLR", "BFFBBBBLLL", "FFBBFBBRLL", "FFFFBFBRLR", "FBFBBFFLLR", "BFBFBBFRLL", "FFBFFFFLLL", "FBBFFBFLRR", "FFBFFFBRLL", "FFFFBBBLLR", "BFBBBBBRLL", "FBBFBBBLRL", "FBFFBBBRLL", "FBFFFBBLLR", "FFBBBFBLRL", "FFFFBFFRLL", "BBFFFBBLRL", "BFFFBFFRRL", "BFFBFBFLLL", "BBFFFBFLLL", "FFFFFBFLRL", "FBBFFFFRRR", "FBBBBBFLRR", "FFBFFFBRLR", "FBBBFFFLLL", "FFBFBBBLRL", "FFBFFFBLLL", "FBFFBBBLLR", "BBBFBFFRLR", "FFFBFFFRLR", "BBFBBBFLLR", "FFBBFFFRLR", "FFFFFBFRLR", "FBBFFFBRRL", "BFFBBBBRLR", "BFFBFFBRLL", "BFBBBFBRLL", "FBFFBBFRRR", "FBFBBFFLLL", "BBFBFBBLRL", "BBBFBBFLRL", "FBFBFFBLRR", "FBFFFFFRLL", "BFBBFBFRRR", "BFBFBBBLLL", "FFBBBFFLRR", "BFBBFBBLLR", "FBBBBFFRRR", "BFFFBFFLRL", "FFFFBFBRLL", "BFFFFBBLLL", "BFFBFBBLLL", "BFFBFBBRRL", "BBBFFFBLRL", "BBBFFFBRRR", "BFFFBBFLRR", "FFBBFBFRLL", "BFFBBFBRLR", "FFBFFBFLLR", "FBFBBBBLRL", "BFFBBFFRRL", "BBFFFBBRRR", "FBBBFBBRRR", "BFFFFBFRRL", "FFBFBBBRRL", "BFFFBBBRRR", "BFBBBFBRRR", "BFBFBFFRLR", "FFFFFBBRRR", "FBFBFBFLRL", "FFBBBBBLRR", "BBFFFFBLRL", "FFFBFFFLLR", "FFFBFFFRRL", "FBBBFBBLRL", "BBFFBBFLLR", "BBFFBFFLRR", "BFFFFFFRLR", "FBBFBBFRLL", "BFBBBBFRRR", "FBFBBBBLLR", "FFFBBFFRLR", "FBBFBBBRLR", "FBBFBFBRLR", "FBBBFFFLRL", "FFBBFBBRLR", "BFFFBBBLLL", "BBFBBFFRRR", "FBFBFFFLRR", "BBFFBBFRRR", "FBBFBFFRRL", "BFFFFBFLLL", "BBBFFBBLLL", "BFBBBBFRRL", "FBBFFFBRRR", "BFBBBBFLLL", "FFFBFFBRRL", "BFFBFFBLLR", "FFBBFBFRRL", "FBFFFBBRLR", "BFFFBBBLRR", "FFBFBFFRRR", "FBFBFFBRLL", "BFBBBBFLRL", "BFBBFFFRRR", "FBFBFBFRRL", "BBFBBFFLRL", "FBBFFFFLLL", "BBBFFBBRLL", "FBFFFBBRRL", "FFBFBFFLRL", "FBFFBBFLRL", "BFFBFBFLRR", "BFFFFBBLRL", "BBFBBBBLRL", "FFBFBBFRLL", "FBFFFBFLLL", "BFFBFFBLRL", "FBBFFFBLRR", "FFFFBFFRRL", "FBBFFBFRLR", "BFFFBFFRRR", "FFFFBFBRRL", "BBFFBFBLRL", "FBBFBFBRLL", "BFBBFFFLRL", "FFFBBBFRRR", "BFFFFFFLLR", "FBFBBFFRRR", "BFFFFFBRLL", "FFFFBBBRRL", "BFFBFBFLLR", "FFFFBFFRLR", "BFFBBBFRRL", "BFBBFBBRLL", "FFFFFBFRRL", "FFBBBBFLRL", "FFBBFBFLLR", "BBFFBBBRLL", "BFFBFFFLLR", "BBFBBBBRLL", "BFFBFBBRLR", "FFBFBFFRRL", "FBBFBBFLRL", "FFBFFBBLRL", "BFBFFFBRLR", "BFFBFFFLRR", "BFFBBBBLRL", "FFFBFBBRLR", "FBBBBBFRRR", "BFBFBFFLRL", "BFBFFFBLRL", "FBBBFBBRLL", "FBFBFBFLLL", "FBBFFBFRRR", "FFFBFBBLRR", "FFFBFFFLRL", "BFBFBFBRRR", "BFFBBFFLLL", "BFFBFBBRRR", "FFBFFBFRRL", "FBFFFBFRLL", "FFBFBBFLLL", "FFBBFFBLRL", "FBFBBBBRRL", "BFFBBFBRRL", "FBFBFBBLRL", "BBFBFBFRLR", "FBFFFFFLRR", "BBBFFBFRLL", "BFBFBFFRLL", "FBBFFBBLRL", "FBFBFBBRRL", "FFBBBBBRLR", "FBBFBBFLLR", "FFFBFBBRLL", "BBFFFFBRRL", "BFBFBFBLRL", "FBFBBFBLLR", "BBBFBFBLRR", "FFFFBBFRLL", "FFBBBBBRRR", "BFBBFFBRRR", "BFFFBBBLLR", "FBBBBBBRLL", "FFBFBBFRLR", "BBFFBBFRLL", "BFFBFFFLRL", "FFBBFFFLLL", "BFFBFBBLRL", "BBBFFFFRLL", "BBFBBBFRRR", "FBFFBFFRRR", "FBBFFFFRLL", "BFFFBBBRRL", "FBFBBBFLLL", "FFFFBBFLLR", "FBBFBBFRRR", "BBFFBBBRLR", "BBFBBFBLRR", "BFFFBFFLLL", "BBFBFBFRRR", "FFBFFFBLRL", "BBFFFBBRLR", "FBFBFBBRRR", "BFBBFFBLRL", "BFFFFBFRLL", "BBFBFBBRLL", "BFFFFBBRLL", "FFFFBFFLLR", "FFBBBBFLRR", "FBFBFFFRRR", "FFFBBFBLLR", "FFBBFBFRRR", "BFBBFBBRRR", "FFBFBBBLLR", "FFBFFBFLLL", "FFFFBBBLRL", "FFBFBFFLLR", "BFBBBFFLRR", "FBBFFFFLLR", "FBFFFFBRRL", "BFFBBFFLRR", "FFBBFBBRRR", "FFFFBFBRRR", "BFBBBBFLLR", "FBBFFBBRRR", "BBFBFBBLRR", "FFFBBBBLRR", "FBFFFBBLRR", "BFFBFBFRLR", "BFBFFBFRLR", "BFBBFFFRLR", "FFBBFFFLLR", "FFFFFBFLRR", "BFFBBFBLRR", "FFFFBBFRLR", "BFFFBBFLLR", "FBFBFFBRRR", "BBFBFBBRRL", "FBFBBFFLRR", "BFBFFBFLRR", "BBFFFBBLRR", "FBFFBBFRRL", "FBBBBBBLRL", "FBBFFBBLLL", "BFBFBBBLRL", "BBBFFFBLLR", "BFFFBFFLRR", "BBFFBBFRRL", "BFBFBBFLLL", "FFBBBFFLLR", "BFBBFBFRRL", "FBFFBFFRRL", "BFFFBFBLRR", "BFBBFBBRRL", "BBFBFFBLRL", "BFFBBBFRRR", "FBFBBFBLLL", "BBFFBFFRRR", "BBFFBFBRLL", "BBBFFBFLLR", "FFFBBFBLLL", "FBBBFFFRRL", "BFFBFFBLRR", "BBFBFBBLLR", "FFBBFBFRLR", "BBFFFFFRLR", "FBFFBFBLRR", "BFFFFFFRRR", "FFBBFBFLLL", "BFBBFBBLRR", "BBFFFBFRLR", "BBBFFBFRRR", "FFFFBBFLLL", "BBFFBFBLRR", "BFFBFBBRLL", "FBFFFBFLLR", "BFFFBBFRRR", "FFBFBBFRRL", "BFBFFBBLRR", "FBBFFBFRRL", "FFBBBBBLLR", "BFBFFBBLLL", "BFBBBBFLRR", "FFFFBBBRLR", "BFFBBBBLLR", "BFFFFFFLRR", "BFFFFBBRLR", "FFFBBBBRLL", "BFBBFFFLRR", "BFFBBBFRLR", "BFFBBFFRLL", "FBFBBBBLLL", "BFBFBFBRLR", "BBFBBFFLLL", "BBFBBBBLRR", "FFBBFBBLLR", "FBBFFFBRLL", "FBBBBFFRRL", "FFFBBFBLRR", "FFFBFBBLLR", "FFFFFBBRRL", "FBFBBBFRRR", "BBFFFBFLRL", "FBFBFFBLLL", "FBFBFFFRRL", "BFBFFFBRRL", "BBFFBFFRLR", "BBFFBFBLLR", "FFFBFBFLRR", "BBFBBBFLLL", "BFBBBFFRLL", "BFFFBFBRRL", "FFFFBFFLLL", "FBBBBBFRRL", "FBFBFFBLRL", "FBBBBBBLRR", "FFFBBBBRLR", "BFFBFBBLLR", "BBFFBBFLRR", "BFFFFFBLRL", "FFBBBBFLLL", "BFFBFBBLRR", "FFFBBBFLRR", "FFBFBBFLRL", "FBBFBFBLRL", "BBBFFFFRRL", "BBFBFBFLLR", "BFBBBFBLLL", "FFBFBBBLRR", "BFFBFFBRLR", "FFFBBBBLLL", "BFFFBFFRLR", "BFFFBBFLLL", "FBBBBFBLRR", "FBBFBBBRLL", "BFBFFBFRRL", "BFFFFBBRRR", "BBFFBBBLRL", "FBBBBFBRLL", "BFBBFFFRRL", "BBBFFBFLLL", "BFBFFBFRRR", "FFBFFBBRRR", "FFBFBBBRLR", "FBBBBFFLRR", "BFBFBFFLRR", "BFBBBBFRLR", "FFFFFBFRRR", "BFFBBFBRRR", "BFBBBBBRRL", "BFFBBFBLRL", "FFFBFBBLRL", "FFFBFBBLLL", "FFBBFBBLRL", "BBBFFFFLRR", "FFFFFBBLRL", "FBFFBFBLLR", "FBFBBBBRLL", "BFFBFBFRLL", "BFFFBFFRLL", "BFFFBFBRRR", "BBBFBFFLRL", "BFFBFFFLLL", "BBFFFFFRRL", "FBFBFFFLLR", "FFBFFBBLLL", "BBFFBFFLRL", "BBFFBBBLLL", "FFFFFBBLLL", "BFBBFFBLLL", "FFFBFFBRLR", "FBBFFBBRLL", "FBFBFBBRLL", "BFFBBBFLRL", "FFFBFFBLRR", "FBFBBFFRLR", "FFFBBFFLLR", "FBFBBBFLLR", "FBBFFFFRRL", "BBFBBBFLRR", "BFBBFBFRLR", "FFBFFFBLLR", "FFBFFBFLRL", "BBFFBBBRRR", "BBFFFFFLRR", "FBFFBFBRRL", "FBFFBFFLLR", "FBBBFFBLLL", "FBBBFFBLRR", "BFBBBBBRRR", "BBBFFFBRLL", "FBFFFFFRRR", "BBFBBFFRLR", "BBFFBBBLLR", "BBBFFBFLRL", "BBFFFBFLRR", "FFFBFFFLLL", "FFBFBBFLLR", "BBFFFFFRLL", "BBFBBFFRRL", "FBBFBBBLLL", "FFFBFFBRRR", "FBBBBFFLLL", "FFFBBFFLRR", "BBFFBBBRRL", "FFBBBFFLLL", "FBBBFBFLRL", "BBFBFFFLRL", "FFBFFFFRLL", "FFFBBBFRLL", "FBBBBBFLLL", "BFBFFFFLLL", }; } } }
b442bf7f0f6c9333e95d8b7fe5b3adff412d3c42
C#
JTRaffield/C-apps
/MilitaryUnit/MilitaryUnit/Juniors.cs
2.9375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MilitaryUnit { class Juniors: PersonnelClass { //updates the Position based on the object instance public override void Position() { Console.WriteLine("Junior Marine"); } //updates the Role based on the object instance public override void Role() { Console.WriteLine("Serves as a worker drone"); } //updates the Credit based on the object instance public override void Credit() { Console.WriteLine("receives little credit"); } } }
589b1ffa522b222616f20292b386b717a88a381c
C#
manosh7n/gibdd
/gibdd/gibdd/assets/Validator.cs
3.15625
3
using System; using System.Text.RegularExpressions; namespace gibdd { public static class Validator { public static bool nameValidator(string name) { try { return Regex.IsMatch(name, @"^[а-я]+(?:\W[а-я]+)+$", RegexOptions.IgnoreCase); } catch (Exception) { return false; } } public static bool emailValidator(string email) { try { var pattern = @"^(?!\.)(""([^""\r\\]|\\[""\r\\])*""|" + @"([-a-z0-9!#$%&'*+/=?^_`{|}~]|(?<!\.)\.)*)(?<!\.)" + @"@[a-z0-9][\w\.-]*[a-z0-9]\.[a-z][a-z\.]*[a-z]$"; var regex = new Regex(pattern, RegexOptions.IgnoreCase); return regex.IsMatch(email); } catch { return false; } } } }
ea8247726fc35209fa1d11994e7720483b7b3d33
C#
JoshWAMiasco/Jcon_Contact_Tracing
/LTXJconLibrary/SystemBoard.cs
2.71875
3
using System; using System.Collections.Generic; using System.Text; /* * Title: System Board * Putpose: to Find SystemBoard name by providing jcon path information * Version: 1 * Author: Joshua Miasco * Date Start: * Date End: 11/24/2020 */ namespace LTXJconLibrary { public class SystemBoard : JconTable { /// <summary> /// Search for System Board with specific Jcon path /// </summary> /// <param name="JconTableName"></param> /// Jcon Table Name /// <param name="column"></param> /// Column /// <param name="Row"></param> /// Row /// <returns></returns> public static string Search(string JconTableName, char column, byte Row) { byte ColumnInDigit = (byte) (Enum.Parse(typeof(Column), column.ToString())); switch (JconTableName) { case "J100": return j100[ColumnInDigit, Row]; case "J101": return j101[ColumnInDigit, Row]; case "J102": return j102[ColumnInDigit, Row]; case "J103": return j103[ColumnInDigit, Row]; case "J201": return j201[ColumnInDigit, Row]; case "J203": return j203[ColumnInDigit, Row]; default: return "Not Found"; } } } }
5420e635cf24b598b86de078d69183a5a4fe3655
C#
Kakaranish/OwnFluentValidation
/CustomValidation/PropertyValidators/SyncPropertyValidator.cs
2.625
3
using CustomValidation.Rules; using CustomValidation.Types; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace CustomValidation.PropertyValidators { public class SyncPropertyValidator<TObject, TProperty> : PropertyValidatorBase, ISyncPropertyValidator { public SyncPropertyValidator(PropertyInfo property) : base(property) { } public PropertyValidationResult Validate(object obj) { return Validate((TObject)obj); } private PropertyValidationResult Validate(TObject obj) { var propertyValueAsObj = Property.GetValue(obj); var propertyValue = (TProperty)Convert.ChangeType(propertyValueAsObj, typeof(TProperty)); var ruleValidationErrors = new List<RuleValidationError>(); foreach (var rule in Rules.Cast<SyncValidationRule<TProperty>>()) { var ruleValidationError = rule.Validate(propertyValue); if (ruleValidationError != null) { ruleValidationErrors.Add(ruleValidationError); if (rule.StopValidationAfterFailure) { break; } } } return new PropertyValidationResult(PropertyDisplayName, ruleValidationErrors); } } }
81e71a364a7be99bead0440531453f9b2e318c93
C#
azizsagi/Radio-Frequency-Identity-Reader-RFID-in-C-Sharp
/mainrfid/XmlParser/XmlParser_Alarm.cs
2.703125
3
using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Xml.Serialization; using System.Xml; using System.IO; using Siemens.Simatic.RfReader; namespace Siemens.Simatic.RfReader.ReaderApi.XmlBinding { /// <summary> /// This class parses the replys got from our reader service. /// </summary> internal partial class XmlParser { private int alarmCount = 0; private int alarmIndex = 0; internal RfAlarm[] ParseAlarms(string alarmMsg) { RfAlarm[] alarmList = null; StringReader strReader = new StringReader(alarmMsg); XmlTextReader alarmReader = new XmlTextReader(strReader); this.alarmCount = 0; this.alarmIndex = 0; //RfReaderInfo currentReaderInfo = new RfReaderInfo(); while (alarmReader.Read()) { switch (alarmReader.NodeType) { case XmlNodeType.Element: switch (alarmReader.Name) { case "error": RfAlarm[] oldAlarmList = alarmList; // Create a new list one element longer than the old one alarmList = new RfAlarm[this.alarmIndex + 1]; for (int pos = 0; pos < this.alarmIndex; pos++) { alarmList[pos] = oldAlarmList[pos]; } // Yippieh! Create a new alarm alarmList[this.alarmIndex] = new RfAlarm(); alarmList[this.alarmIndex].AdditionalAlarmData = new Hashtable(); break; case "utcTime": if (alarmReader.Read()) { if (XmlNodeType.Text == alarmReader.NodeType) { alarmList[this.alarmIndex].UtcTime = alarmReader.Value; } } break; case "errorNumber": if (alarmReader.Read()) { if (XmlNodeType.Text == alarmReader.NodeType) { alarmList[this.alarmIndex].ErrorNumber = alarmReader.Value; } } break; case "errorText": if (alarmReader.Read()) { if (XmlNodeType.Text == alarmReader.NodeType) { alarmList[this.alarmIndex].ErrorText = alarmReader.Value; } } break; default : string Name = alarmReader.Name; if (alarmReader.Read()) { if (XmlNodeType.Text == alarmReader.NodeType) { alarmList[this.alarmIndex].AdditionalAlarmData[Name] = alarmReader.Value; } } break; } break; case XmlNodeType.EndElement: if (alarmReader.Name == "error") { this.alarmIndex++; this.alarmCount++; } break; default: break; } } return alarmList; } } }
dbb0624aa80f0f649828214aefae1d993191b394
C#
Hengle/sbox-extraction
/code/Hero/HeroCollection.cs
2.5625
3
using System.Collections.Generic; using System.IO; using Sandbox; namespace Extraction.Hero { /// <summary> /// This is just a container for all hero data stuff /// </summary> public class HeroCollection { public static Dictionary<string, HeroData> HeroDatas = new (); /// <summary> /// Loads all hero data json files from the filesystem /// </summary> public static void Load() { HeroDatas = new(); foreach ( var file in FileSystem.Mounted.FindFile( "/data/heroes", "*.json" ) ) { string rawFileName = Path.GetFileNameWithoutExtension( file ); Log.Info( $"Loading {rawFileName}" ); HeroDatas.Add( rawFileName, FileSystem.Mounted.ReadJson<HeroData>( $"data/heroes/{rawFileName}.json" ) ); } } /// <summary> /// Reloads whenever the client is hotloaded /// </summary> [Event( "client.hotloaded" )] public static void OnHotload() { Load(); } } }
5370c8e1e77aafe0c1dddfc15dcafbbb24507fd5
C#
alinemokfa/e16_class_notes
/week_10/c_sharp_course/week_1/day_3/polymorphism/end_code/Library.cs
3.296875
3
using System.Collections.Generic; namespace Library { class Library { private string name; private int capacity; private List<ICanBorrow> items; public string Name { get { return this.name; } set { this.name = value; } } public int Capacity { get { return this.capacity; } set { this.capacity = value; } } public Library (string name, int capacity) { this.name = name; this.capacity = capacity; this.items = new List<ICanBorrow>(); } public int ItemCount() { return this.items.Count; } public void AddItem(ICanBorrow item) { this.items.Add(item); } public void ClearShelves() { this.items.Clear(); } } }
0dbdda4312be395a94999f2a03ddc5d77bbfa980
C#
patrinhani-ciandt/BohriumNET
/test/Bohrium.Core.Test/Extensions/ByteArrayExtensionMethodsTestFixture.cs
2.828125
3
using Bohrium.Core.Extensions; using Bohrium.Core.Test.TestHelpers; using NUnit.Framework; namespace Bohrium.Core.Test.Extensions { [TestFixture] public class ByteArrayExtensionMethodsTestFixture : TestFixtureBase { /* Test is covering the methods bellow: * T ToObject<T>(this byte[] value) */ [Test] public void should_be_able_to_deserialize_a_byte_array_to_a_serializable_type() { var dataTestObject = DataTestObject.CreateDefault(); var byteArrayDataTestObject = dataTestObject.ToByteArray(); var expectedDataTestObject = byteArrayDataTestObject.ToObject<DataTestObject>(); var dataTestObjectMD5 = dataTestObject.ComputeMD5Hash(); var expectedDataTestObjectMD5 = expectedDataTestObject.ComputeMD5Hash(); Assert.IsNotNull(expectedDataTestObject); Assert.IsInstanceOf<DataTestObject>(expectedDataTestObject); Assert.AreEqual(dataTestObjectMD5, expectedDataTestObjectMD5); Assert.AreNotSame(dataTestObject, expectedDataTestObject); } /* Test is covering the methods bellow: * byte[] Compress(this byte[] value) * byte[] Decompress(this byte[] value) */ [Test] public void should_be_able_to_compress_and_decompress_an_object() { var dataTestObject = DataTestObject.CreateDefault(); var byteArrayDataTestObject = dataTestObject.ToByteArray(); var dataTestObjectCompressed = byteArrayDataTestObject.Compress(); Assert.AreNotEqual(byteArrayDataTestObject, dataTestObjectCompressed); Assert.IsTrue(dataTestObjectCompressed.Length < byteArrayDataTestObject.Length); var dataTestObjectDecompressed = dataTestObjectCompressed.Decompress(); Assert.AreEqual(byteArrayDataTestObject, dataTestObjectDecompressed); } /* Test is covering the methods bellow: * string ToHex(this byte[] bytes) */ [Test] public void should_be_able_to_convert_a_byte_array_to_a_hex_string() { var bytes = new byte[] { 0xF1, 0x00, 0x40, 0xAA }; Assert.AreEqual(bytes.ToHex(), "f10040aa"); } } }
004a93c05a74e388ed27f47fa9c9d27a95c1531b
C#
kuboj86/Lab10Alt
/Lab10Alt/Car.cs
2.96875
3
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Text; using System.Threading.Tasks; namespace Lab10Alt { class Car { public Car() { this.Make = "Fiat"; this.Model = "500e"; this.Year = 2017; this.Price = 32_975; } public Car(string make, string model, int year, double price) { this.Make = make; this.Model = model; this.Year = year; this.Price = price; } public string Make { get; set; } public string Model { get; set; } public int Year { get; set; } public double Price { get; set; } public override string ToString() { return $"{Make}\t{Model}\t{Year}\t${Price}"; } } }
f4bee908b5f2594c377c8cd28a12af84c7ad6290
C#
ruinosus/empresafarias
/EmpresaFarias/Repositorio/implementacoes/RepositorioPlano.cs
2.8125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Repositorio.interfaces; using ClassesBasicas; using System.Data.SqlClient; using Excecoes; namespace Repositorio.implementacoes { /// <summary> /// Classe responsavel por implementar a IRepositorioPlano. /// </summary> public class RepositorioPlano : IRepositorioPlano { #region Sql Tabela Plano private static String QUERY_INSERT = "INSERT INTO Plano (Nome,Descricao,ValorPadrao) VALUES (@Nome,@Descricao,@ValorPadrao)"; private static String QUERY_UPDATE = "UPDATE Plano SET Nome= @Nome,Descricao = @Descricao,ValorPadrao = @ValorPardao WHERE Id = @Id"; private static String QUERY_DELETE = "DELETE FROM Plano WHERE Id = @Id"; private static String QUERY_SELECT_ID = "SELECT Id,Nome,Descricao,ValorPadrao FROM Plano WHERE Id = @Id"; private static String QUERY_SELECT_ALL = "SELECT Id,Nome,Descricao,ValorPadrao FROM Plano"; #endregion #region Membros de IRepositorioPlano /// <summary> /// Metodo responsavel por inserir um Plano. /// </summary> /// <param name="plano">Objeto do tipo Plano a ser inserido</param> public void Inserir(Plano plano) { UtilBD banco = new UtilBD(); SqlConnection conexao = banco.ObterConexao(); try { SqlCommand comando = new SqlCommand(QUERY_INSERT, conexao); comando.Parameters.AddWithValue("@Nome", plano.Nome); comando.Parameters.AddWithValue("@Descricao", plano.Descricao); comando.Parameters.AddWithValue("@ValorPadrao", plano.ValorPadrao); conexao.Open(); int regitrosAfetados = comando.ExecuteNonQuery(); } catch (SqlException e) { throw new ErroBanco(e.Message); } finally { banco.FecharConexao(conexao); } } /// <summary> /// Metodo responsavel por alterar um Plano. /// </summary> /// <param name="plano">Objeto do tipo Plano a ser alterado</param> public void Alterar(Plano plano) { UtilBD banco = new UtilBD(); SqlConnection conexao = banco.ObterConexao(); try { SqlCommand comando = new SqlCommand(QUERY_UPDATE, conexao); comando.Parameters.AddWithValue("@Nome", plano.Nome); comando.Parameters.AddWithValue("@Descricao", plano.Descricao); comando.Parameters.AddWithValue("@ValorPadrao", plano.ValorPadrao); comando.Parameters.AddWithValue("@Id", plano.Id); conexao.Open(); int regitrosAfetados = comando.ExecuteNonQuery(); } catch (SqlException e) { throw new ErroBanco(e.Message); } finally { banco.FecharConexao(conexao); } } /// <summary> /// Metodo responsavel por remover um Plano. /// </summary> /// <param name="id">Id do Plano a ser removido.</param> public void Remover(int id) { UtilBD banco = new UtilBD(); SqlConnection conexao = banco.ObterConexao(); try { SqlCommand comando = new SqlCommand(QUERY_DELETE, conexao); comando.Parameters.AddWithValue("@Id", id); conexao.Open(); int regitrosAfetados = comando.ExecuteNonQuery(); } catch (SqlException e) { throw new ErroBanco(e.Message); } finally { banco.FecharConexao(conexao); } } /// <summary> /// Metodo responsavel por consultar um Plano. /// </summary> /// <param name="id">Id a ser consultado.</param> /// <returns>retorna um Plano com o Id informado.</returns> public Plano Consultar(int id) { UtilBD banco = new UtilBD(); SqlConnection conexao = banco.ObterConexao(); Plano plano = null; try { SqlCommand comando = new SqlCommand(QUERY_SELECT_ID, conexao); SqlDataReader resultado; comando.Parameters.AddWithValue("@Id", id); conexao.Open(); resultado = comando.ExecuteReader(); resultado.Read(); if (resultado.HasRows) { plano = this.CriarPlano(resultado); } resultado.Close(); } catch (SqlException e) { throw new ErroBanco(e.Message); } finally { banco.FecharConexao(conexao); } return plano; } /// <summary> /// Metodo responsavel por consultar todos os Planos cadastrados. /// </summary> /// <returns>retorna uma Lista com todos os Planos cadastrador.</returns> public List<Plano> Consultar() { UtilBD banco = new UtilBD(); SqlConnection conexao = banco.ObterConexao(); List<Plano> planos = new List<Plano>(); try { SqlCommand comando = new SqlCommand(QUERY_SELECT_ALL, conexao); SqlDataReader resultado; conexao.Open(); resultado = comando.ExecuteReader(); if (resultado.HasRows) { while (resultado.Read()) { planos.Add(this.CriarPlano(resultado)); } } resultado.Close(); } catch (SqlException e) { throw new ErroBanco(e.Message); } finally { banco.FecharConexao(conexao); } return planos; } #endregion /// <summary> /// Metodo para montar um Plano recebendo um SqlDataReader como parametro. /// </summary> /// <param name="resultado">SqlDataReader</param> /// <returns>Retorna um Plano</returns> private Plano CriarPlano(SqlDataReader resultado) { Plano plano = new Plano(); if (resultado["Id"] != DBNull.Value) { plano.Id = Convert.ToInt32(resultado["Id"]); } if (resultado["Nome"] != DBNull.Value) { plano.Nome = Convert.ToString(resultado["Nome"]); } if (resultado["Descricao"] != DBNull.Value) { plano.Descricao = Convert.ToString(resultado["Descricao"]); } if (resultado["ValorPadrao"] != DBNull.Value) { plano.ValorPadrao = Convert.ToDecimal(resultado["ValorPadrao"]); } return plano; } } }
e6b7cab56f036dbf424afa6b4ae073809ef251fd
C#
juanUrdaneta/DesignPatternsPractice
/DIContainerDemo/ClassB.cs
2.703125
3
using System; using System.Collections.Generic; using System.Text; namespace DIContainerDemo { public class ClassB : IB { private IA _classA; public ClassB(IA classA) { _classA = classA; } public void doB() { _classA.doA(); Console.WriteLine("Doing B"); } } }
e31c56e49ede2b174a6aba806744842f4ef968a3
C#
wangzq/resharper-template-compiler
/src/resharper-template-compiler/SettingsSerialisation.cs
2.640625
3
using System.Collections.Generic; using System.IO; using System.Linq; using System.Windows; using System.Windows.Markup; using System.Xml; namespace CitizenMatt.ReSharper.TemplateCompiler { public class SettingsSerialisation { private readonly IDictionary<string, object> dictionary; public SettingsSerialisation(IDictionary<string, object> dictionary) { this.dictionary = dictionary; } public SettingsStore GetSettings(params string[] pathSegments) { return new SettingsStore(dictionary, "/" + string.Join("/", pathSegments)); } public static void SerialiseToXaml(TextWriter textWriter, SettingsSerialisation serialisation) { //var resourceDictionary = new ResourceDictionary(); //foreach (var pair in serialisation.dictionary) // resourceDictionary.Add(pair.Key, pair.Value); // Writes correctly, but in indeterminate order, annoyingly //var xmlWriter = XmlWriter.Create(textWriter, new XmlWriterSettings //{ // Indent = true //}); //XamlWriter.Save(resourceDictionary, xmlWriter); using (var xmlWriter = XmlWriter.Create(textWriter, new XmlWriterSettings { ConformanceLevel = ConformanceLevel.Auto, Indent = true, IndentChars = "\t", NewLineHandling = NewLineHandling.Entitize })) { xmlWriter.WriteStartElement("wpf", "ResourceDictionary", "http://schemas.microsoft.com/winfx/2006/xaml/presentation"); xmlWriter.WriteAttributeString("xml", "space", null, "preserve"); xmlWriter.WriteAttributeString("xmlns", "x", null, "http://schemas.microsoft.com/winfx/2006/xaml"); xmlWriter.WriteAttributeString("xmlns", "s", null, "clr-namespace:System;assembly=mscorlib"); xmlWriter.WriteAttributeString("xmlns", "ss", null, "urn:shemas-jetbrains-com:settings-storage-xaml"); foreach (var entry in serialisation.dictionary.OrderBy(p => p.Key).Where(p => p.Value != null)) { xmlWriter.WriteStartElement("s", entry.Value.GetType().Name, "clr-namespace:System;assembly=mscorlib"); xmlWriter.WriteAttributeString("x", "Key", "http://schemas.microsoft.com/winfx/2006/xaml", entry.Key); xmlWriter.WriteValue(entry.Value); xmlWriter.WriteEndElement(); } xmlWriter.WriteEndElement(); } } public static SettingsDeserialisation DeserialiseFromXaml(TextReader textReader) { using(var xmlReader = XmlReader.Create(textReader)) { var resourceDictionary = (ResourceDictionary)XamlReader.Load(xmlReader); var dictionary = new Dictionary<string, object>(); foreach (var key in resourceDictionary.Keys) dictionary.Add((string) key, resourceDictionary[key]); return new SettingsDeserialisation(dictionary); } } } }
7071321ade05dfbd4037871f2bd62b1f5c209d5e
C#
ynatt/JPEGAlgorithm
/JPEGAlgorithm/vilenklin/ExpansionBase.cs
3.34375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace JPEGAlgorithm { class ExpansionBase { private List<int> p; private List<int> m; public ExpansionBase(List<int> p) { this.p = p; m = BuildM(p); } private List<int> BuildM(List<int> p) { List<int> result = new List<int>(p.Count()) { 1 }; for (int i = 1; i < p.Count(); i++) { result.Insert(i, result.ElementAt(i - 1) * p.ElementAt(i - 1)); } return result; } public int GetK() { return p.Count; } public int getMSize() { return m.Count; } public int Pk(int k) { return p.ElementAt(k); } public int Mk(int k) { return m.ElementAt(k); } public override string ToString() { return ArrayUtils.ArrayToString(p, "p") + ArrayUtils.ArrayToString(m, "m"); } } }
869d5dcd1fe91d4c263151f679ed3ec7c95fe5df
C#
ezavgorodniy/problemSolving
/src/LeetCode/227_BasciCalculator/227_BasciCalculator/Program.cs
3.828125
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _227_BasciCalculator { public class Solution { private abstract class PolishNotationToken { } private class PolishNotationTokenOperator : PolishNotationToken { public PolishNotationTokenOperator(char c) { Operator = c; } public char Operator { get; } public int OperatorPrecedence { get { if (Operator == '+' || Operator == '-') { return 0; } if (Operator == '*' || Operator == '/') { return 1; } throw new NotImplementedException(); } } public static bool IsOperator(char c) { return c == '+' || c == '-' || c == '*' || c == '/'; } } private class PolishNotationTokenNumber : PolishNotationToken { public PolishNotationTokenNumber(int i) { Value = i; } public int Value { get; } } private bool IsDigit(char c) { return '0' <= c && c <= '9'; } private int CharToInt(char c) { return c - '0'; } private int PerformOperation(int left, int right, PolishNotationTokenOperator op) { switch (op.Operator) { case '+': return left + right; case '*': return left * right; case '-': return left - right; case '/': return left / right; default: throw new NotImplementedException(); } } private List<PolishNotationToken> ReversePolishNotation(string s) { var result = new List<PolishNotationToken>(); var operatorsStack = new Stack<PolishNotationTokenOperator>(); int i = 0; while (i < s.Length) { if (IsDigit(s[i])) { int d = 0; while (i < s.Length && IsDigit(s[i])) { d = d * 10 + CharToInt(s[i]); i++; } result.Add(new PolishNotationTokenNumber(d)); } else if (s[i] == ' ') { while (i < s.Length && s[i] == ' ') { i++; } } else if (PolishNotationTokenOperator.IsOperator(s[i])) { var newOperator = new PolishNotationTokenOperator(s[i]); while (operatorsStack.Count != 0 && operatorsStack.Peek().OperatorPrecedence >= newOperator.OperatorPrecedence) { result.Add(operatorsStack.Pop()); } operatorsStack.Push(newOperator); i++; } } while (operatorsStack.Count != 0) { result.Add(operatorsStack.Pop()); } return result; } private int Calculate(List<PolishNotationToken> polishNotation) { var numbersStack = new Stack<int>(); foreach (var token in polishNotation) { if (token is PolishNotationTokenNumber numberToken) { numbersStack.Push(numberToken.Value); } else if (token is PolishNotationTokenOperator operatorToken) { var right = numbersStack.Pop(); var left = numbersStack.Pop(); numbersStack.Push(PerformOperation(left, right, operatorToken)); } } return numbersStack.Pop(); } public int Calculate(string s) { var polishNotation = ReversePolishNotation(s); return Calculate(polishNotation); } } class Program { static void Main(string[] args) { var sln = new Solution(); Console.WriteLine(sln.Calculate(" 3+5 / 2 ")); } } }
0cabaa49715e4cf61f6f85c6b090cdcd346ae52f
C#
mogatti/hazelcast-csharp-client
/Hazelcast.Examples/Map/MapJsonExample.cs
2.609375
3
// Copyright (c) 2008-2020, Hazelcast, Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Linq; using Hazelcast.Client; using Hazelcast.Config; using Hazelcast.Core; namespace Hazelcast.Examples.Map { internal class MapJsonExample { public static void Run(string[] args) { Environment.SetEnvironmentVariable("hazelcast.logging.level", "info"); Environment.SetEnvironmentVariable("hazelcast.logging.type", "console"); var config = new Configuration(); config.NetworkConfig.AddAddress("127.0.0.1"); var client = HazelcastClient.NewHazelcastClient(config); var map = client.GetMap<string, HazelcastJsonValue>("json-example"); map.Put("item1", new HazelcastJsonValue("{ \"age\": 4 }")); map.Put("item2", new HazelcastJsonValue("{ \"age\": 20 }")); var result = map.Values(Predicates.IsLessThan("age", 6)); Console.WriteLine("Retrieved " + result.Count + " values whose age is less than 6."); Console.WriteLine("Entry is: " + result.First().ToString()); Console.WriteLine("Finished"); client.Shutdown(); } } }
5371ee99b7fc54dc54dad61fd0f8ec9a4c615544
C#
rockfordlhotka/mcmreporting
/mcmmodels/Dal/Schools.cs
2.890625
3
using System.Collections.Generic; using Dapper; using System.Linq; namespace mcmmodels.Dal { public class Schools { public List<SchoolDal> Get() { using (var conn = Database.GetConnection()) { var result = conn.Query<SchoolDal>("select id, school_name AS name from Schools;").AsList(); return result; } } public SchoolDal Get(int id) { using (var conn = Database.GetConnection()) { var result = conn.Query<SchoolDal>("select id, school_name AS name from Schools where id=@id;", new { id }); return result.FirstOrDefault(); } } public int Insert(SchoolDal school) { using (var conn = Database.GetConnection()) { conn.Execute("insert into Schools (school_name) values (@name);", new { name = school.Name }); var result = conn.Query<SchoolDal>("select id, school_name AS name from Schools where school_name=@name;", new { name = school.Name }).FirstOrDefault(); return result == null ? -1 : result.Id; } } public void Update(SchoolDal school) { using (var conn = Database.GetConnection()) { conn.Execute("update Schools set school_name=@name where id=@id;", new { id = school.Id, name = school.Name }); } } public void Delete(int id) { using (var conn = Database.GetConnection()) { conn.Execute("delete from Schools where id=@id;", new { id }); } } } public class SchoolDal { public int Id { get; set; } public string Name { get; set; } } }
ad13047ae2f02c1c0f72a9d4c670a47d8e7ca776
C#
zapoutix/DBreeze
/Deployment/XamarinStore/v1/samples/android/DBreeze.Android/AndroidTest/MainActivity.cs
2.59375
3
using System; using Android.App; using Android.Content; using Android.Runtime; using Android.Views; using Android.Widget; using Android.OS; using DBreeze; namespace AndroidTest { [Activity(Label = "AndroidTest", MainLauncher = true, Icon = "@drawable/icon")] public class MainActivity : Activity { int count = 1; DBreezeEngine engine = null; protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); // Set our view from the "main" layout resource SetContentView(Resource.Layout.Main); // Get our button from the layout resource, // and attach an event to it Button button = FindViewById<Button>(Resource.Id.MyButton); if (engine == null) { engine = new DBreezeEngine(@"./sdcard/tiesky.com/DBreezeTest"); } button.Click += delegate { using (var tran = engine.GetTransaction()) { tran.Insert<int, string>("t1", count, "val" + count); tran.Commit(); } using (var tran = engine.GetTransaction()) { button.Text = "Please, read detailed documentation on http://dbreeze.codeplex.com/ or http://dbreeze.tiesky.com/" + "... Inserted value is " + tran.Select<int, string>("t1", count).Value; } count++; }; } } }
bcd68ccc60d142fc7a157c873e4b143aa154b9b8
C#
HatiGamedev/GGJ2016
/Assets/Prefabs/Finished/Font/Font.cs
2.5625
3
using UnityEngine; using System.Collections; using System.Collections.Generic; public class Font : MonoBehaviour { public List<GameObject> ObjectFont; public string Text; public string Target; public const float LetterDistance = 0.8f; public List<GameObject> GetObjs(string s) { s = s.ToLower(); List<GameObject> Result = new List<GameObject>(); for (int i = 0; i < s.Length; i++) { if (s[i] == '?') Result.Add(ObjectFont[26]); else if (s[i] == '!') Result.Add(ObjectFont[27]); else if (s[i] == ' ') Result.Add(new GameObject()); else { int nr = s[i] - 'a'; Result.Add(ObjectFont[nr]); } } return Result; } public void Spawn(string s, Vector3 tPosition) { List<GameObject> BluePrints = GetObjs(s); for (int i = 0; i < BluePrints.Count; i++) { Vector3 Pos = new Vector3(-s.Length * LetterDistance / 2 + LetterDistance * i, 0, 0); Pos =transform.rotation * Pos; Pos = Quaternion.Euler(0, 0, 0) * Pos; GameObject letter = (GameObject)Instantiate(BluePrints[i],tPosition + Pos, new Quaternion()); letter.transform.rotation = Quaternion.Euler(-90,0,0); Klickable t = letter.AddComponent<Klickable>(); t.Target = Target; letter.transform.parent = transform; } } // Use this for initialization void Start () { Spawn(Text,transform.position); } // Update is called once per frame void Update () { } }
e4eb09553d4f5a44b280e200907858ac6146738f
C#
Nadeem-edu/OPTICS
/OM EYE CARE/DAL/usersDAL.cs
2.890625
3
using OM_EYE_CARE.BLL; using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace OM_EYE_CARE.DAL { class usersDAL { static string myconnstrng = ConfigurationManager.ConnectionStrings["connstrng"].ConnectionString; #region Select Data From Database public DataTable select() { //static method to connect database SqlConnection conn = new SqlConnection(myconnstrng); //To hold the data form database DataTable dt = new DataTable(); try { //SQL Query to Get Data form Database String sql = "select * from tbl_user"; //For Excecuting Command SqlCommand cmd = new SqlCommand(sql, conn); //Getting Data form Database SqlDataAdapter adapter = new SqlDataAdapter(cmd); //Database Connection Open conn.Open(); //Fill data in dataTable adapter.Fill(dt); } catch (Exception ex) { //Throw Message if there any error MessageBox.Show(ex.Message); } finally { //Closing Connection conn.Close(); } //Return the value in DataTable return dt; } #endregion #region Insert Data In Database public bool Insert(userBLL u) { bool isSuccess = false; SqlConnection conn = new SqlConnection(myconnstrng); try { string sql = "INSERT INTO tbl_user (first_name, last_name, username, password, email_id, address, contact_no, gender, added_by) VALUES(@first_name, @last_name, @username, @password, @email_id, @address, @contact_no, @gender, @added_by)"; SqlCommand cmd = new SqlCommand(sql, conn); cmd.Parameters.AddWithValue("@user_id", u.user_id); cmd.Parameters.AddWithValue("@first_name", u.first_name); cmd.Parameters.AddWithValue("@last_name", u.last_name); cmd.Parameters.AddWithValue("@username", u.username); cmd.Parameters.AddWithValue("@password", u.password); cmd.Parameters.AddWithValue("@email_id", u.email_id); cmd.Parameters.AddWithValue("@address", u.address); cmd.Parameters.AddWithValue("@contact_no", u.contact_no); cmd.Parameters.AddWithValue("@gender", u.gender); cmd.Parameters.AddWithValue("@added_by", u.added_by); conn.Open(); int rows = cmd.ExecuteNonQuery(); //if the query is executed sucessfully then the value of rows will be greate than 0 else it will be less than 0 if (rows > 0) { //Query Sucessfull isSuccess = true; } else { //Query Failed isSuccess = false; } } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { conn.Close(); } return isSuccess; } #endregion #region Update Data Form Database public bool Update(userBLL u) { bool isSuccess = false; SqlConnection conn = new SqlConnection(myconnstrng); try { string sql = "UPDATE tbl_user SET first_name=@first_name, last_name=@last_name, username=@username, password=@password, email_id=@email_id, address=@address, contact_no=@contact_no, gender=@gender WHERE user_id=@user_id"; SqlCommand cmd = new SqlCommand(sql, conn); cmd.Parameters.AddWithValue("@first_name", u.first_name); cmd.Parameters.AddWithValue("@last_name", u.last_name); cmd.Parameters.AddWithValue("@username", u.username); cmd.Parameters.AddWithValue("@password", u.password); cmd.Parameters.AddWithValue("@email_id", u.email_id); cmd.Parameters.AddWithValue("@address", u.address); cmd.Parameters.AddWithValue("@contact_no", u.contact_no); cmd.Parameters.AddWithValue("@gender", u.gender); cmd.Parameters.AddWithValue("@added_by", u.added_by); cmd.Parameters.AddWithValue("@user_id", u.user_id); conn.Open(); int rows = cmd.ExecuteNonQuery(); if (rows > 0) { //Query Successfull isSuccess = true; } else { //Query Failed isSuccess = false; } } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { conn.Close(); } return isSuccess; } #endregion #region Delete Data Form Database public bool Delete(userBLL c) { bool isSuccess = false; SqlConnection conn = new SqlConnection(myconnstrng); try { string sql = "DELETE FROM tbl_user WHERE user_id=@user_id"; SqlCommand cmd = new SqlCommand(sql, conn); cmd.Parameters.AddWithValue("@user_id", c.user_id); conn.Open(); int rows = cmd.ExecuteNonQuery(); if (rows > 0) { //Query Successfull isSuccess = true; } else { //Query Failed isSuccess = false; } } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { conn.Close(); } return isSuccess; } #endregion #region Search Data Form Database public DataTable Search(string keywords) { //static method to connect database SqlConnection conn = new SqlConnection(myconnstrng); //To hold the data form database DataTable dt = new DataTable(); try { //SQL Query to Get Data form Database String sql = "select * from tbl_user WHERE user_id LIKE '%"+keywords+"%' OR first_name LIKE '%"+keywords+"%' OR contact_no LIKE '%"+keywords+"%'"; //For Excecuting Command SqlCommand cmd = new SqlCommand(sql, conn); //Getting Data form Database SqlDataAdapter adapter = new SqlDataAdapter(cmd); //Database Connection Open conn.Open(); //Fill data in dataTable adapter.Fill(dt); } catch (Exception ex) { //Throw Message if there any error MessageBox.Show(ex.Message); } finally { //Closing Connection conn.Close(); } //Return the value in DataTable return dt; } #endregion #region Getting User ID from Username public userBLL GetIDFromUsername(string username) { userBLL u = new userBLL(); SqlConnection conn = new SqlConnection(myconnstrng); DataTable dt = new DataTable(); try { String sql = "SELECT user_id FROM tbl_user WHERE username='" + username + "'"; SqlDataAdapter adapter = new SqlDataAdapter(sql, conn); conn.Open(); adapter.Fill(dt); if(dt.Rows.Count>0) { u.user_id = int.Parse(dt.Rows[0]["user_id"].ToString()); } } catch(Exception ex) { MessageBox.Show(ex.Message); } finally { conn.Close(); } return u; } #endregion } }
b169911aa4b299cc46b0d522613923d777f1e0a0
C#
leon-mil/DesignPatternFramework_4.5
/DoFactory.GangOfFour.Memento.NETOptimized/MainApp.cs
3.359375
3
using System; using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Soap; namespace DoFactory.GangOfFour.Memento.NETOptimized { /// <summary> /// MainApp startup class for .NET optimized /// Memento Design Pattern. /// </summary> class MainApp { /// <summary> /// Entry point into console application. /// </summary> static void Main() { // Init sales prospect through object initialization var s = new SalesProspect { Name = "Joel van Halen", Phone = "(412) 256-0990", Budget = 25000.0 }; // Store internal state var m = new ProspectMemory(); m.Memento = s.SaveMemento(); // Change originator s.Name = "Leo Welch"; s.Phone = "(310) 209-7111"; s.Budget = 1000000.0; // Restore saved state s.RestoreMemento(m.Memento); // Wait for user Console.ReadKey(); } } /// <summary> /// The 'Originator' class /// </summary> [Serializable] class SalesProspect { string name; string phone; double budget; // Gets or sets name public string Name { get { return name; } set { name = value; Console.WriteLine("Name: " + name); } } // Gets or sets phone public string Phone { get { return phone; } set { phone = value; Console.WriteLine("Phone: " + phone); } } // Gets or sets budget public double Budget { get { return budget; } set { budget = value; Console.WriteLine("Budget: " + budget); } } // Stores (serializes) memento public Memento SaveMemento() { Console.WriteLine("\nSaving state --\n"); var memento = new Memento(); return memento.Serialize(this); } // Restores (deserializes) memento public void RestoreMemento(Memento memento) { Console.WriteLine("\nRestoring state --\n"); var s = (SalesProspect)memento.Deserialize(); this.Name = s.Name; this.Phone = s.Phone; this.Budget = s.Budget; } } /// <summary> /// The 'Memento' class /// </summary> class Memento { MemoryStream stream = new MemoryStream(); SoapFormatter formatter = new SoapFormatter(); public Memento Serialize(object o) { formatter.Serialize(stream, o); return this; } public object Deserialize() { stream.Seek(0, SeekOrigin.Begin); object o = formatter.Deserialize(stream); stream.Close(); return o; } } /// <summary> /// The 'Caretaker' class /// </summary> class ProspectMemory { public Memento Memento { get; set; } } }
fe4281c806d9aec9c22b242eb6949789ff885159
C#
JOLLY-USS/calculatorivt164
/calculator/calculator.Tests/TwoArg/MaxTest.cs
2.703125
3
using calculator.TwoArg; using NUnit.Framework; namespace calculator.Tests.TwoArg { [TestFixture] class MaxTest { [TestCase(2, 3, 3)] [TestCase(3, 2, 3)] [TestCase(6, 2, 6)] public void MinTest(double firstValue, double secondValue, double expected) { var calculator = new Max(); var actualResult = calculator.Calculate(firstValue, secondValue); Assert.AreEqual(expected, actualResult); } } }
660bcd10ec246261b2aadf7ad5282d78e3d67a6a
C#
papnkukn/wmf
/library/WmfReader.cs
2.921875
3
using System; using System.IO; using Oxage.Wmf.Records; namespace Oxage.Wmf { /// <summary> /// Low-level WMF parser /// </summary> public class WmfReader : IDisposable { private Stream stream; private BinaryReader reader; public WmfReader(Stream stream) { this.stream = stream; this.reader = new BinaryReader(stream); } public bool IsFormatRead { get; protected set; } public bool IsHeaderRead { get; protected set; } public bool IsEndOfFile { get { return stream.Length == stream.Position; } } public IBinaryRecord Read() { if (!this.IsFormatRead) { this.IsFormatRead = true; var format = new WmfFormat(); format.Read(reader); return format; } if (!this.IsHeaderRead) { this.IsHeaderRead = true; var header = new WmfHeader(); header.Read(reader); return header; } long begin = reader.BaseStream.Position; uint length = reader.ReadUInt32(); //Length in WORDs ushort type = reader.ReadUInt16(); var rt = (RecordType)type; var record = WmfHelper.GetRecordByType(rt) as WmfBinaryRecord; if (record == null) { record = new WmfUnknownRecord(); record.RecordType = rt; //Only set for UnknownRecord otherwise it is already defined by attribute above the class } record.RecordSize = length; record.Read(reader); long end = reader.BaseStream.Position; long rlen = end - begin; //Read length long excess = 2 * length - rlen; if (excess > 0) { //Oops, reader did not read whole record?! reader.Skip((int)excess); } return record; } public void Dispose() { if (this.reader != null) { this.reader.Close(); this.reader = null; } } } }
ce69ffc18db7a08d2909a7c13febaa3fdf501ec0
C#
AdelaToderici/Algorithms
/SearchRotatedArray/LevelOrderTraversal.cs
3.65625
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SearchRotatedArray { class LevelOrderTraversal { public static List<Tuple<int, int>> Iterate(TreeNode root) { Queue<TreeNode> q = new Queue<TreeNode>(); q.Enqueue(root); List<Tuple<int, int>> list = new List<Tuple<int, int>>(); Tuple<int, int> t = Tuple.Create(root.value, 0); list.Add(t); while (q.Count > 0) { TreeNode node = q.Dequeue(); if (node.left != null) { q.Enqueue(node.left); int index = list.First(m => m.Item1 == node.value).Item2; Tuple<int, int> tuple1 = Tuple.Create(node.left.value, index + 1); list.Add(tuple1); } if (node.right != null) { q.Enqueue(node.right); int index = list.First(m => m.Item1 == node.value).Item2; Tuple<int, int> tuple2 = Tuple.Create(node.right.value, index + 1); list.Add(tuple2); } } for (int i = 0; i <= list.Max(x=>x.Item2); i++) { Console.WriteLine(String.Join(" ", list.Where(x => x.Item2 == i).Select(x => x.Item1).ToArray())); } return list; } } }
06e185f5aca1dfdefd3caf87d1687d047a66e4c8
C#
Infarh/MathCore.WPF
/MathCore.WPF/ObservableCollectionSyncWrapper.cs
2.5625
3
using System.Collections; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Windows.Threading; namespace MathCore.WPF; /// <summary>Потокобезопасная обёртка для <see cref="T:System.Collection.ObjectModel.ObservableCollection[T]"/></summary> /// <typeparam name="T">Тип элемента коллекции</typeparam> public class ObservableCollectionSyncWrapper<T> : ICollection<T>, INotifyCollectionChanged, INotifyPropertyChanged { public event NotifyCollectionChangedEventHandler? CollectionChanged; protected virtual void OnCollectionChanged(NotifyCollectionChangedEventArgs E) => _AsyncOp.Post(_CollectionChanged, E); public event PropertyChangedEventHandler? PropertyChanged; //[NotifyPropertyChangedInvocator] protected virtual void OnPropertyChanged(string PropertyName) => _AsyncOp.Post(_PropertyChanged, new PropertyChangedEventArgs(PropertyName)); private readonly ObservableCollection<T> _Collection; private readonly AsyncOperation _AsyncOp = AsyncOperationManager.CreateOperation(null); private readonly SendOrPostCallback _CollectionChanged; private readonly SendOrPostCallback _PropertyChanged; public object? SyncRoot { get; set; } public ObservableCollectionSyncWrapper() : this(new ObservableCollection<T>()) { } public ObservableCollectionSyncWrapper(ObservableCollection<T> Collection) { _CollectionChanged = o => CollectionChanged?.Invoke(this, (NotifyCollectionChangedEventArgs)o!); _PropertyChanged = o => PropertyChanged?.Invoke(this, (PropertyChangedEventArgs)o!); _Collection = Collection; _Collection.CollectionChanged += (_, e) => OnCollectionChanged(e); ((INotifyPropertyChanged)_Collection).PropertyChanged += (_, e) => OnPropertyChanged(e.PropertyName ?? throw new InvalidOperationException("Не указана ссылка на строку с именем свойства")); } public IEnumerator<T> GetEnumerator() => _Collection.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => ((IEnumerable)_Collection).GetEnumerator(); public void Add(T item) { if (SyncRoot != null) lock (SyncRoot) _Collection.Add(item); else _Collection.Add(item); } public void Clear() { if (SyncRoot != null) lock (SyncRoot) _Collection.Clear(); else _Collection.Clear(); } public bool Contains(T item) { bool result; if (SyncRoot != null) lock (SyncRoot) result = _Collection.Contains(item); else result = _Collection.Contains(item); return result; } public void CopyTo(T[] array, int Index) { if (SyncRoot != null) lock (SyncRoot) _Collection.CopyTo(array, Index); else _Collection.CopyTo(array, Index); } public bool Remove(T item) { bool result; if (SyncRoot != null) lock (SyncRoot) result = _Collection.Remove(item); else result = _Collection.Remove(item); return result; } public int Count => _Collection.Count; public bool IsReadOnly => ((ICollection<T>)_Collection).IsReadOnly; public static implicit operator ObservableCollectionSyncWrapper<T>(ObservableCollection<T> collection) => new(collection); public static explicit operator ObservableCollection<T>(ObservableCollectionSyncWrapper<T> wrapper) => wrapper._Collection; } public class RangeObservableCollection<T> : ObservableCollection<T> { private bool _SuppressNotification; protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e) { if (!_SuppressNotification) base.OnCollectionChanged(e); } public void AddRange(IEnumerable<T> list) { if (list is null) throw new ArgumentNullException(nameof(list)); _SuppressNotification = true; foreach (var item in list) Add(item); _SuppressNotification = false; OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); } } public class DeferEventObservableCollection<T> : ObservableCollection<T> { private readonly List<NotifyCollectionChangedEventArgs> _DeferredEvents = new(); private bool _HasQueuedDispatcherUpdate; private readonly int _Threshold; private readonly object _SyncRoot = new(); public DeferEventObservableCollection(int threshold = 10) => _Threshold = threshold; protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e) { lock (_SyncRoot) { _DeferredEvents.Add(e); if (!_HasQueuedDispatcherUpdate) Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() => { lock (_SyncRoot) { if (_DeferredEvents.Count > _Threshold) base.OnCollectionChanged( new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); else foreach (var ev in _DeferredEvents) base.OnCollectionChanged(ev); _DeferredEvents.Clear(); _HasQueuedDispatcherUpdate = false; } })); _HasQueuedDispatcherUpdate = true; } } } public class DeferredRefreshObservableCollection<T> : ObservableCollection<T> { private int _RefreshDeferred; private bool _Modified; /// <summary>Raises the <see cref="E:CollectionChanged" /> event.</summary> /// <param name="e">The instance containing the event data.</param> protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e) { if (_RefreshDeferred > 0) { _Modified = true; return; } base.OnCollectionChanged(e); } /// <summary>Отложить посылку уведомлений об изменении состава коллекции</summary><returns>Дескриптор</returns> public DeferRefreshHelper DeferRefresh() => new(this); /// <summary>Дескриптор отложенных изменений</summary> public struct DeferRefreshHelper : IDisposable { private DeferredRefreshObservableCollection<T> _Owner; internal DeferRefreshHelper(DeferredRefreshObservableCollection<T> owner) { _Owner = owner ?? throw new ArgumentNullException(nameof(owner)); _Owner._RefreshDeferred++; } /// <summary>Уменьшить счетчик отложенной посылки обновлений</summary> public void Dispose() { if (null == _Owner) return; var temp = _Owner; _Owner = null; if (0 == --temp._RefreshDeferred && temp._Modified) temp.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); } } } public class SynchronizationObservableCollection<T> : ObservableCollection<T> { private readonly SynchronizationContext _Context = SynchronizationContext.Current; public SynchronizationObservableCollection() { } public SynchronizationObservableCollection(IEnumerable<T> list) : base(list) { } protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e) { if (SynchronizationContext.Current == _Context) RaiseCollectionChanged(e); // Execute the CollectionChanged event on the current thread else _Context.Send(RaiseCollectionChanged, e); // Raises the CollectionChanged event on the creator thread } private void RaiseCollectionChanged(object param) => base.OnCollectionChanged((NotifyCollectionChangedEventArgs)param); protected override void OnPropertyChanged(PropertyChangedEventArgs e) { if (SynchronizationContext.Current == _Context) RaisePropertyChanged(e); // Execute the PropertyChanged event on the current thread else _Context.Send(RaisePropertyChanged, e); // Raises the PropertyChanged event on the creator thread } private void RaisePropertyChanged(object param) => base.OnPropertyChanged((PropertyChangedEventArgs)param); } public class ObservableRangeCollection<T> : ObservableCollection<T> { private const string __CountString = "Count"; private const string __IndexerName = "Item[]"; public ObservableRangeCollection() { } public ObservableRangeCollection(IEnumerable<T> collection) : base(collection) { } public ObservableRangeCollection(List<T> list) : base(list) { } public void AddRange(IEnumerable<T> items) { var new_items = new List<T>(); foreach (var item in items) { Items.Add(item); new_items.Add(item); } if (new_items.Count == 0) return; OnPropertyChanged(new PropertyChangedEventArgs(__CountString)); OnPropertyChanged(new PropertyChangedEventArgs(__IndexerName)); var e = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, new_items); OnCollectionChanged(e); } public void RemoveRange(IEnumerable<T> items) { var old_items = new List<T>(); foreach (var item in items) { Items.Remove(item); old_items.Add(item); } if (old_items.Count == 0) return; OnPropertyChanged(new PropertyChangedEventArgs(__CountString)); OnPropertyChanged(new PropertyChangedEventArgs(__IndexerName)); var e = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, old_items); OnCollectionChanged(e); } }
5ab0d5c74d61aea5c8eae5f308d9ebd369cb0550
C#
shendongnian/download4
/first_version_download2/338239-28554024-83931532-2.cs
2.6875
3
private async void Button_Click(object sender, RoutedEventArgs e) { TextBoxOutput.Text = "calculating..."; var result = await Task.Run(Calculate); TextBoxOutput.Text = result.ToString(CultureInfo.InvariantCulture); } private int Calculate() { Thread.Sleep(2000); //--similate working.... return Environment.TickCount ^ 43; }
1a888d3292f764f31e27f50bf4ddb53854d80bd3
C#
thodoriskonstantoulias/Csharp_OOP_Course
/CsharpOOP_Course/CsharpOOP_Course/Advanced/DictionaryGeneric.cs
4.03125
4
using System; using System.Collections.Generic; using System.Text; namespace CsharpOOP_Course.Advanced { public class DictionaryGeneric { public static void PlayingWithDictionaries() { Dictionary<string, string> dict = new Dictionary<string, string>(); Console.WriteLine("Adding to dictionary"); dict.Add("France", "Paris"); dict.Add("Spain", "Barcelona"); foreach (var item in dict) { Console.WriteLine(item.Key + " : " + item.Value); } Console.WriteLine("------------------"); Console.WriteLine("Counting items in dictionary"); Console.WriteLine(dict.Count); Console.WriteLine("------------------"); Console.WriteLine("Getting items in dictionary"); Console.WriteLine(dict.TryGetValue("France", out string value)); Console.WriteLine("------------------"); } } }
0a23497ed67335d9712299c1bc048eb60f7ff51b
C#
ViktorMamyan/examples
/C#/LINQ/Aggregate Functions/1/Program.cs
3.5
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LINQ { class Program { static void Main(string[] args) { IList<int> numbers = new List<int> { 1,2,3,10,100,-250,-500,5000}; Console.WriteLine("Min: {0}",numbers.Min()); Console.WriteLine("Max: {0}", numbers.Max()); Console.WriteLine("Avg: {0}", numbers.Average()); Console.WriteLine("Positiv elements count: {0}", numbers.Where(x => x > 0).Count()); Console.WriteLine("Positiv elements count: {0}", numbers.Count(x => x > 0)); Console.WriteLine("Sum of negative elements: {0}", numbers.Where(x => x < 0).Sum()); Console.ReadKey(); } } }
1bbac3d7f72596e71976c635afa9aa2cb0fcd789
C#
TomoyukiYajima/TrapScissors_Team
/Assets/Kageyama/Script/Trap.cs
2.75
3
using UnityEngine; using System.Collections; public class Trap : MonoBehaviour { public enum TrapState { WAIT, //動物が掛かるのを待っている状態 CAPTURE, //動物を捕まえている状態 } public TrapState _state; #region 鋏むときに必要な変数 //鋏むんでいるオブジェクトを入れる [SerializeField] private GameObject _targetAnimal; #endregion //スタートよりも前に動く変数 void Awake() { } // Use this for initialization void Start() { _targetAnimal = null; _state = TrapState.WAIT; } // Update is called once per frame void Update() { } //当たっている最中も取得する当たり判定 void OnTriggerEnter(Collider col) { if(col.tag == "Enemy") { ChengeState(TrapState.CAPTURE); } } public void ChengeState(TrapState state) { _state = state; } }
50079ed5c37ac64f33cbab7b972b0fab6a1e2d53
C#
iamceren/YourLibraryProject
/YourLibrary/Controllers/LibrariesController.cs
2.53125
3
using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.IO; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; using YourLibrary.Models; namespace YourLibrary.Controllers { public class LibrariesController : Controller { private YourLibraryDBEntities db = new YourLibraryDBEntities(); // GET: Libraries public ActionResult Index(string currentFilter, string searchString) { var user = Session["mydata"] as User; var library = db.Users.SelectMany(i => i.Books).Include(b => b.Category1); if (searchString != null) { } else { searchString = currentFilter; } ViewBag.CurrentFilter = searchString; if (!String.IsNullOrEmpty(searchString)) { library = library.Where(p => p.Title.Contains(searchString) || p.Author.Contains(searchString)); } return View(library.ToList()); } public ActionResult GetBook(int id) { Book book = db.Books.Find(id); string path = Path.Combine(@"C:\Users\aktas\source\repos\YourLibrary\YourLibrary\uploads\", book.Title + ".pdf"); return File(path, "application/pdf"); } public ActionResult Details(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Book book = db.Books.Find(id); if (book == null) { return HttpNotFound(); } return View(book); } public ActionResult Delete(int id) { User user = Session["mydata"] as User; Book book = db.Books.Find(id) ; var library = db.Users.Find(user.Id); library.Books.Remove(book); db.SaveChanges(); return RedirectToAction("Index"); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } } }
8047fa552c18631689b2684e96c5a9bd5ed23065
C#
VRinaldi/Mapa-de-matriz
/MatrizExercicio/Program.cs
3.796875
4
using System; namespace MatrizExercicio { class Program { static void Main(string[] args) { Console.Write("Digite o número de Colunas: "); int M = int.Parse(Console.ReadLine()); Console.Write("Digite um número de Linhas: "); int N = int.Parse(Console.ReadLine()) - 1; int[,] mat = new int[M, N]; Console.WriteLine($"Digite o valor das linhas ({M} números por linha):"); for (int i = 0; i < M; i++) { string[] values = Console.ReadLine().Split(' '); for (int j = 0; j < N; j++) { mat[i, j] = int.Parse(values[j]); } } Console.WriteLine(); Console.Write("Digite o valor a ser procurado: "); int Valor = int.Parse(Console.ReadLine()); for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { if (mat[i,j] == Valor) { Console.WriteLine("Posição: " + i + ", " + j); if (j != 0) { Console.WriteLine("Esquerda: " + mat[i, j - 1]); } if(j != (N - 1)) { Console.WriteLine("Direita: " + mat[i, j + 1]); } if (i != 0) { Console.WriteLine("Acima: " + mat[i - 1, j]); } if (i != (M - 1)) { Console.WriteLine("Abaixo: " + mat[i + 1, j]); } Console.WriteLine(); } } } } } }
aafa607306c6f31435af0909d88f48e5c115e8d9
C#
NtuthukoM/Blackjack21GameLogic
/BlackJack21.Core/Implementation/Player.cs
3.5625
4
using BlackJack21.Core.Interfaces; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BlackJack21.Core.Implementation { public class Player : IPlayer { public string Name { get; set; } public int Score { get; set; } public string Result { get; set; } public Card[] Hand { get; set; } public void DrawCards(Card[] cards) { Hand = cards; Result = string.Empty; Score = 0; } public void RevealHand(int dealerScore = 0) { if(Hand == null) { throw new ApplicationException("Cards not dealt."); } foreach (Card card in Hand) { Score += card.Value; } //0 is passed if player is the actual dealer if(dealerScore > 0) { if(Score < 21 && Hand.Length == 5) { Result = "Beats the dealer"; } else if(Score >= dealerScore && Score <= 21) { Result = "Beats the dealer"; } else { Result = "Loses"; } } } public override string ToString() { string display = ""; display += string.Format("Player name: {0}\n", Name); if(Hand != null) { display += "\t\t--- Hand --\n"; foreach(Card card in Hand) { display += string.Format("{0}, ", card.Name); } display += "\t\t-----------\n"; display += string.Format("Player score: {0}\n", Score); if (!string.IsNullOrEmpty(Result)) { display += string.Format("Player result: {0}\n", Result); } } return display; } } }
44106a0c1534297dffa380cdb8212d9d2356438b
C#
ricardorinco/CoursesCenter
/src/RR.CoursesCenter.Domain/Validation/Instructors/InstructorIsConsistentValidation.cs
2.640625
3
using DomainValidation.Validation; using RR.CoursesCenter.Domain.Models; using RR.CoursesCenter.Domain.Specification.Instructors; namespace RR.CoursesCenter.Domain.Validation.Instructors { public class InstructorIsConsistentValidation : Validator<Instructor> { public InstructorIsConsistentValidation() { var instructorIdentification = new InstructorMustContainIdentificationSpecification(); var instructorEmail = new InstructorMustHaveEmailValidSpecification(); var instructorBeOlder = new InstructorMustBeOlderSpecification(); Add("instructorIdentification", new Rule<Instructor>(instructorIdentification, "A identificação do Instrutor deve conter no mínimo 3 caracteres.")); Add("instructorEmail", new Rule<Instructor>(instructorEmail, "Instrutor informou um e-mail inválido.")); Add("instructorBeOlder", new Rule<Instructor>(instructorBeOlder, "Instrutor não tem maioridade para cadastro.")); } } }
eed5d7c7e48a9414f37e9f78477959f6e89147a0
C#
davidkeeton821/ITSE1430
/Labs/Lab3/DavidKeeton.MovieLib.Windows/MovieDetailForm.cs
3.015625
3
/* * David Keeton * 3/29/2018 * Lab3 ITSE 1430 */ using System; using System.ComponentModel; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel.DataAnnotations; using System.Windows.Forms; using System.Linq; namespace DavidKeeton.MovieLib.Windows { /// <summary>Provides a form for adding/editing <see cref=" Movie"/>.</summary> public partial class MovieDetailForm : Form { #region Construction public MovieDetailForm() { InitializeComponent(); } public MovieDetailForm(string title) :this() { Text = title; } public MovieDetailForm( Movie movie ) : this("Edit Movie") { Movie = movie; } #endregion /// <summary>Gets and sets the movie property</summary> public Movie Movie { get; set; } protected override void OnLoad( EventArgs e ) { base.OnLoad(e); //Load Product if(Movie != null) { _textTitle.Text = Movie.Title; _textDescription.Text = Movie.Description; _textLength.Text = Movie.Length.ToString(); _chkIsOwned.Checked = Movie.Owned; } ValidateChildren(); } #region Event Handlers private void OnSave( object sender, EventArgs e ) { //Create product var movie = new Movie() { Title = _textTitle.Text, Description = _textDescription.Text, Length = ConvertToInt(_textLength), Owned = _chkIsOwned.Checked }; //Validate movie using IValidatableObject var context = new ValidationContext(movie as IValidatableObject); var errors = movie.Validate(context); if(errors.Count() > 0) { //Get first error DisplayError(errors.ElementAt(0).ErrorMessage); return; } //Return from form Movie = movie; DialogResult = DialogResult.OK; Close(); } #endregion private void DisplayError( string message ) { MessageBox.Show(this, message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } private int ConvertToInt( TextBox control ) { if (Int32.TryParse(control.Text, out var length)) return length; return -1; } private void _textTitle_Validating( object sender, CancelEventArgs e ) { var textbox = sender as TextBox; if (String.IsNullOrEmpty(textbox.Text)) { _errorProvider.SetError(textbox, "Title is required"); e.Cancel = true; } else _errorProvider.SetError(textbox, ""); } private void _textLength_Validating( object sender, CancelEventArgs e ) { var textbox = sender as TextBox; if (ConvertToInt(textbox) <= 0) { _errorProvider.SetError(textbox, "Length must be >= 0"); e.Cancel = true; } else _errorProvider.SetError(textbox, ""); } } }
521876c34ec3ad60cb2f1c3578e6b869057279de
C#
Zlobynja/CSharp_Dobrynin
/Asssressbook_web_tests/Asssressbook_web_tests/tests/AddingContactToGroupTests.cs
2.9375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NUnit.Framework; namespace Addressbook_web_tests { public class AddingContactToGroupTests : AuthTestBase { [Test] public void AddingContactToGroupTest() { ContactData contact = new ContactData("1", "2"); GroupData group = null; int j = 0; app.Contact.IsContactExists(); app.Groups.IsGroupExists(); List<GroupData> groupsList = GroupData.GetAll(); List<ContactData> contacts = ContactData.GetAll(); int contactsCount = contacts.Count(); int groupsCount = groupsList.Count; bool contactToAddExist = false; List<ContactData> oldList = null; int i = 0; while (i < groupsCount && !contactToAddExist) { oldList = groupsList[i].GetContacts(); if (oldList.Count == 0) //в группе нет контактов, добавляем первый из списка { contact = ContactData.GetAll().First(); } else if (oldList.Count == contactsCount) // в группу добавлены все контакты,п.э. создаем новый контакт { contact = new ContactData("firstname1234", "lastname123"); app.Contact.Create(contact); } else if (oldList.Count < contactsCount) // есть контакт, который можно добавить в группу { contact = ContactData.GetAll().Except(oldList).First(); } contacts[0] = contact; group = groupsList[i]; contactToAddExist = true; j = i; i++; } if (contactToAddExist) { oldList = groupsList[j].GetContacts(); app.Contact.AddContactToGrooup(contacts[0], groupsList[j]); List<ContactData> newList = groupsList[j].GetContacts(); oldList.Add(contact); oldList.Sort(); newList.Sort(); Assert.AreEqual(oldList, newList); } else { System.Console.Out.WriteLine("No contact to add to group"); } } } }
cb35690dc5d5373390a4cf415f12b3c58d731b19
C#
shendongnian/download4
/first_version_download2/568373-54192178-189561839-2.cs
3.28125
3
using System; using System.Linq; using MoreLinq; namespace Test { class Program { static void Main(string[] args) { double[] x = new double[20] { 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1 }; var results = x.Select((value, index) => new { value, index }) .GroupAdjacent(z => z.value) .Where(z => z.Count() >= 4) .Select(z => new { value = z.Key, firstIndex = z.First().index, lastIndex = z.Last().index }) .ToList(); Console.WriteLine(string.Join(Environment.NewLine, results.Select(z => $"{z.value} - {z.firstIndex} - {z.lastIndex}"))); Console.ReadLine(); } } }
aac9b5801ae40e16d95314e71693d92866fb0a01
C#
markmontymark/patterns
/csharp/src/Creational/Abstract_Factory/TestAbstractFactory.cs
2.9375
3
//TestAbstractSoupFactory.java - Testing the abstract factory namespace Creational.Abstract_Factory { using tap; using common; class TestAbstractFactory { public static Soup MakeSoupOfTheDay(AbstractSoupFactory concreteSoupFactory) { Soup s ; /* Calendar todayCalendar = Calendar.getInstance(); //int dayOfWeek = todayCalendar.get(Calendar.DAY_OF_WEEK); int dayOfWeek = Calendar.TUESDAY; switch( dayOfWeek ) { case Calendar.MONDAY: s = concreteSoupFactory.makeChickenSoup(); break; case Calendar.TUESDAY: s = concreteSoupFactory.makeClamChowder(); break; case Calendar.WEDNESDAY : s = concreteSoupFactory.makeFishChowder(); break; case Calendar.THURSDAY : s = concreteSoupFactory.makeMinnestrone(); break; case Calendar.FRIDAY : s = concreteSoupFactory.makePastaFazul(); break; case Calendar.SATURDAY : */ s = concreteSoupFactory.makeTofuSoup(); /* break; case Calendar.SUNDAY : s = concreteSoupFactory.makeVegetableSoup(); break; } */ return s; } public static void Main() { AbstractSoupFactory concreteSoupFactory = new BostonConcreteSoupFactory(); Soup soupOfTheDay = MakeSoupOfTheDay(concreteSoupFactory); Tapper tap = new Tapper(); tap.test("Boston soup of the day test " , ("The Soup of the day " + concreteSoupFactory.getFactoryLocation() + " is " + soupOfTheDay.getSoupName() ) , ("The Soup of the day Boston is Tofu Soup")); concreteSoupFactory = new HonoluluConcreteSoupFactory(); soupOfTheDay = MakeSoupOfTheDay(concreteSoupFactory); tap.test("Honolulu soup of the day test " , ("The Soup of the day " + concreteSoupFactory.getFactoryLocation() + " is " + soupOfTheDay.getSoupName() ) , ("The Soup of the day Honolulu is Tofu Soup")); tap.done(); } } }
debced35dddea65fd1e35eb8298bc77c9fa9b4d6
C#
shendongnian/download4
/code1/43136-674484-1166942-2.cs
2.921875
3
static TObject FindVisualParent<TObject>(UIElement child) where TObject : UIElement { if (child == null) { return null; } UIElement parent = VisualTreeHelper.GetParent(child) as UIElement; while (parent != null) { TObject found = parent as TObject; if (found != null) { return found; } else { parent = VisualTreeHelper.GetParent(parent) as UIElement; } } return null; }
6d04188d5e052e7d6766d6e58d781f2a46a36701
C#
AlxxlA/OOPWorkshops
/04. Dependency Inversion/Olympics-Task/OlympicGames/OlympicGames/Olympics/Sprinter.cs
3.078125
3
using System.Collections.Generic; using System.Linq; using System.Text; using OlympicGames.Olympics.Contracts; using OlympicGames.Utils; namespace OlympicGames.Olympics { public class Sprinter : Olympian, ISprinter { public Sprinter(string firstName, string lastName, string country, IDictionary<string, double> records) : base(firstName, lastName, country) { this.PersonalRecords = records; } public IDictionary<string, double> PersonalRecords { get; private set; } protected override string PrintAdditionalInfo() { var stringBuilder = new StringBuilder(); if (!this.PersonalRecords.Any()) { stringBuilder.AppendLine(GlobalConstants.NoPersonalRecordsSet); return stringBuilder.ToString(); } else { stringBuilder.AppendLine(GlobalConstants.PersonalRecords); foreach (var record in this.PersonalRecords) { stringBuilder.AppendLine(string.Format("{0}m: {1}s", record.Key, record.Value)); } } return stringBuilder.ToString(); } } }
1fcfef0a05e05c5c7eb4366e4ec2b9f2c03aac27
C#
fdafadf/colossus
/Program.cs
2.703125
3
using C64.Chess.Forms; using C64.Chess.Forms.Controller; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; namespace C64.Chess { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main(string[] args) { string mode; Controller controller = null; Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); if (args.Length == 1) { mode = args[0]; } else { var modeForm = new ModeForm(); if (modeForm.ShowDialog() == DialogResult.OK) { mode = modeForm.Mode; } else { return; } } switch (mode) { case "play": controller = new BotController(); break; case "colossus": controller = new ColossusController(); break; case "explore": controller = new ExploreController(); break; default: MessageBox.Show($@"Unknown mode ""{args[0]}""."); break; } if (controller != null) { var form = new MainForm(); form.Controller = controller; Application.AddMessageFilter(form); Application.Run(form); } } } }
84a5f391cd32003e1ea83df42c19afa1aed74182
C#
frank229osu/BankingSolutionMay2021
/BankingDomain/StandardBonusCalculator.cs
2.828125
3
using System; namespace BankingDomain { public class StandardBonusCalculator : ICalculateBonuses { private readonly ISystemTime _systemTime; public StandardBonusCalculator(ISystemTime systemTime) { _systemTime = systemTime; } public decimal CalculateTheBonusFor(decimal amountToDeposit, decimal balance) { return _systemTime.GetCurrent().Hour >= 17 ? amountToDeposit * .05M : amountToDeposit * .07M; } } } /* * "The best way to work with untestable code is to kick it into a corner until it learns to play nice * - Jeremy D. Miller * * * "Make all variables explicit." * */
7b90fc569b254d9fca4e9a70b7fc48f77b4e4639
C#
jol6932/src
/TD_HR2/App_Code/DataAccess.cs
2.578125
3
using System; using System.Data; using System.Configuration; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using System.Data.SqlClient; /// <summary> /// DataAccess의 요약 설명입니다. /// </summary> public class DataAccess { SqlConnection Conn; SqlDataAdapter DA= new SqlDataAdapter(); SqlCommandBuilder CB; DataTable DT; public SqlConnection OpenConnection() { Conn = new SqlConnection(ConfigurationManager.ConnectionStrings["PLMDB"].ConnectionString); return Conn; } public Array CallStoredProcedure(string[,] MyINPram, string[,] MyOUTPram, string MySPName) { string Result; Conn = OpenConnection(); SqlCommand CmdSp = new SqlCommand(); CmdSp.Connection = Conn; CmdSp.CommandText = MySPName.ToString(); CmdSp.CommandType = CommandType.StoredProcedure; //input parameters for (int i = 0; i < MyINPram.Length / 2; i++) { CmdSp.Parameters.AddWithValue(MyINPram[i, 0], MyINPram[i, 1]); } //outparameters for (int i = 0; i < MyOUTPram.Length / 2; i++) { if (MyOUTPram[i, 1] == "SqlDbType.VarChar") { CmdSp.Parameters.Add(MyOUTPram[i, 0], SqlDbType.VarChar, 150); } else { CmdSp.Parameters.Add(MyOUTPram[i, 0], SqlDbType.Int, 4); } CmdSp.Parameters[MyOUTPram[i, 0]].Direction = ParameterDirection.Output; } Conn.Open(); CmdSp.ExecuteNonQuery(); Conn.Close(); string[,] Temparray = new string[MyOUTPram.Length / 2, 2]; for (int i = 0; i < MyOUTPram.Length / 2; i++) { if (MyOUTPram[i, 1] == "SqlDbType.VarChar") { Result = (string)CmdSp.Parameters[MyOUTPram[i, 0]].Value; } else { Result = Convert.ToString(CmdSp.Parameters[MyOUTPram[i, 0]].Value); } Temparray[i, 0] = MyOUTPram[i, 0]; Temparray[i, 1] = Result; } return Temparray; } public DataTable CallStoredProcedure(string MySPName) { Conn = OpenConnection(); SqlCommand cm = new SqlCommand(MySPName, Conn); cm.CommandType = CommandType.StoredProcedure; DA.SelectCommand = cm; DT = new DataTable(); DA.Fill(DT); return DT; } }
70c3bc7cbeb81ab1a69b6958611c059bb1081fb9
C#
KillenNolan/CSharpPractise
/CSharpLesson_1/Lesson5_switch/Program.cs
3.515625
4
using System; namespace Lesson5_switch { class Program { static void Main(string[] args) { /*string input = Console.ReadLine(); switch (input) { case "A": Console.WriteLine("the ouput is A"); break; case "B": Console.WriteLine("the input is B"); break; default: Console.WriteLine("Not AB"); break; } if (input=="A") { Console.WriteLine("the ouput is A"); } else if (input =="B") { Console.WriteLine("the ouput is B"); } else { Console.WriteLine( "Not AB"); }*/ /*int salary = 4000; int performance = 0; Console.WriteLine("Please rate the teacher:"); char c = Console.ReadKey().KeyChar; switch (c) { case 'A': performance = 400; break; case 'B': performance = 0; break; case 'C': performance = -300; break; case 'D': performance = -500; break; case 'E': performance = -800; break; } Console.WriteLine("the salary of teacher zhang:" + salary + performance);*/ /*Console.WriteLine("Please enter a score:"); string input = Console.ReadLine(); int score; int.TryParse(input, out score); score = score / 10; switch (score) { case 10: Console.WriteLine("perfect"); break; case 9: Console.WriteLine("perfect"); break; case 8: Console.WriteLine("excellent"); break; case 7: Console.WriteLine("good"); break; case 6: Console.WriteLine("pass"); break; default: Console.WriteLine("Keep working hard"); break; } */ /*// switch 贯穿 int num = 3; switch (num) { case 1: case 2: Console.WriteLine("1-2"); break; case 3: case 4: case 5: Console.WriteLine("3-5"); break; }*/ Console.WriteLine("Please enter year:"); string strYear = Console.ReadLine(); Console.WriteLine("Please enter month"); string strMonth = Console.ReadLine(); int year, month; int.TryParse(strYear, out year); int.TryParse(strMonth, out month); bool borunnian = false; if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) { borunnian = true; } // 31:1,3,5,7,8,10,12 // 30:4,6,9,11 // 28/29:2 switch (month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: Console.WriteLine("31"); break; case 4: case 6: case 9: case 11: Console.WriteLine("30"); ; break; case 2: if (borunnian) { Console.WriteLine("29"); } else { Console.WriteLine("28"); } break; } } } }
5806e18573c9f8352ff9f1934f82478cc7ea6cd0
C#
debop/NFramework
/src/NFramework.Numerics/Core/VectorTool.cs
3.421875
3
using System; using System.Collections.Generic; using System.Linq; using NSoft.NFramework.Threading; namespace NSoft.NFramework.Numerics { /// <summary> /// Utility class for <see cref="Vector"/> /// </summary> public static class VectorTool { /// <summary> /// 난수발생기 /// </summary> public static readonly Random Rnd = ThreadTool.CreateRandom(); /// <summary> /// 두 Vector의 창원이 같은지 검사한다. /// </summary> /// <param name="u"></param> /// <param name="v"></param> public static void CheckDimension(Vector u, Vector v) { Guard.Assert(IsSameDimension(u, v), "Vector dimension is not equal."); } /// <summary> /// 두 Vector가 같은 Dimension을 가졌는지 검사한다. /// </summary> public static bool IsSameDimension(Vector u, Vector v) { if(u == null || v == null) return false; return u.Length == v.Length; } /// <summary> /// 무작위 벡터를 만듭니다. /// </summary> public static Vector RandomVector(int length) { length.ShouldBePositive("length of vector"); var vector = new Vector(length); for(int i = 0; i < length; i++) vector[i] = Rnd.NextDouble(); return vector; } /// <summary> /// 무작위 벡터를 <paramref name="count"/> 갯수만큼 생성합니다. /// </summary> /// <param name="count"></param> /// <param name="length"></param> /// <returns></returns> public static IEnumerable<Vector> RandomVector(int count, int length) { length.ShouldBePositive("length of vector"); for(int c = 0; c < count; c++) yield return RandomVector(length); } /// <summary> /// Vector의 절대값을 계산한다. /// </summary> /// <param name="v">Vector</param> /// <returns>Vector의 절대값</returns> public static double AbsSum(this Vector v) { return v.Data.AbsSum(); } /// <summary> /// 두 벡터의 Dot 를 구한다. (요소 순서별로 곱하기의 합) /// </summary> /// <param name="u">First Vector</param> /// <param name="v">Second Vector</param> /// <returns>Dot of vector</returns> public static double Dot(this Vector u, Vector v) { CheckDimension(u, v); double sum = 0.0; for(int i = 0; i < u.Length; i++) sum += u[i] * v[i]; return sum; } /// <summary> /// 절대값이 가장 큰 요소를 반환한다. /// </summary> public static double Norm1(this Vector v) { return v.Data.Max(x => Math.Abs(x)); } /// <summary> /// 두 벡터의 Dot의 제곱근 /// </summary> /// <param name="u">First Vector</param> /// <param name="v">Second Vector</param> /// <returns></returns> public static double Norm2(this Vector u, Vector v) { return Math.Sqrt(Dot(u, v)); } /// <summary> /// 벡터의 요소 중 가장 큰 값 반환한다. /// </summary> /// <param name="v">Vector</param> /// <returns></returns> public static double NormInf(this Vector v) { return v.Norm1(); } /// <summary> /// 벡터의 길이를 구한다. /// </summary> /// <param name="v">Vector</param> /// <returns>벡터의 길이</returns> public static double NormF(this Vector v) { return v.Aggregate<double, double>(0, (sum, t) => sum.Hypot(t)); } } }
a960ecff086dc4bff4a0985efb284033f24a9301
C#
shroommu/AmazonSim
/AmazonSim1.2/Assets/Scripts/UI/Stats.cs
2.65625
3
using System; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class Stats : MonoBehaviour { public List<string> lines; private Text text; public void OnGameOver() { text = GetComponent<Text>(); lines.Add(string.Format("{0}\n", GameData.instance.numberOfPoints.ToString())); lines.Add(string.Format("{0}\n", GameData.instance.numberOfDrones.ToString())); lines.Add(string.Format("{0}\n", GameData.instance.numberOfDeliveries.ToString())); lines.Add(string.Format("{0} s\n", GameData.instance.totalTimeInGame.ToString())); lines.Add(string.Format("{0:0.00} lbs\n", GameData.instance.avgWeightPackages)); lines.Add(string.Format("{0:0.00} s\n", GameData.instance.avgDeliveryTime)); lines.Add(string.Format("{0:0.00}\n", GameData.instance.avgDeliveriesPerMin)); lines.Add(string.Format("{0:0.00}\n", GameData.instance.avgFuelConsumedPerDelivery)); foreach (string current in lines) { Text expr_163 = text; expr_163.text += current; } } }
580edba278636c6e22878d29d9f976758525e928
C#
shendongnian/download4
/first_version_download2/339966-28736526-84642536-2.cs
2.609375
3
public ActionResult GetReturnShippingLabel(int orderId, bool showFull) { string shippingLabel = new OrderRepository().GetOrderReturnShippingLabel(orderId); if (!string.IsNullOrEmpty(shippingLabel)) { byte[] bytes = Convert.FromBase64String(shippingLabel); Image image = null; MemoryStream ms = new MemoryStream(bytes, 0, bytes.Length); ms.Write(bytes, 0, bytes.Length); image = Image.FromStream(ms, true); image.RotateFlip(RotateFlipType.Rotate90FlipNone); if (!showFull) image = image.GetThumbnailImage(326, 570, null, IntPtr.Zero); ImageConverter converter = new ImageConverter(); byte[] imgArray = (byte[])converter.ConvertTo(image, typeof(byte[])); return File(imgArray.ToArray(), "image/gif"); } else { return null; } }
070cee02c62cc45d03c5968cd313e99f548dddeb
C#
garridoalex77/HelloWorld-.NET-Core-API
/XUnitTestProject/UnitTest1.cs
2.5625
3
using HelloWorld; using System; using Xunit; namespace XUnitTestProject { public class UnitTest1 { [Fact] public void Test1() { var service = new HelloService(); Assert.True(!string.IsNullOrEmpty(service.GetWorldName())); } [Fact] public void Test2() { var service = new HelloService(); Assert.True(service.GetWorldName().Length > 0); } } }
7a57ca1d8db3970dc6ad103380ae5d2b292bc533
C#
JoepS/Portfolio
/Zeilgame/Assets/2_Scritps/Database/Models/Track.cs
2.546875
3
using System.Collections; using System.Collections.Generic; using UnityEngine; using SQLite4Unity3d; [Table("Track")] public class Track : Model { public string Name { get; set; } public string Waypoints { get; set; } public string WaypointOrder { get; set; } public ListV2 _waypoints; public ListInt _waypointOrder; public List<Vector2> GetWaypoints() { if (_waypoints == null) _waypoints = JsonUtility.FromJson<ListV2>(Waypoints); return _waypoints.list; } public List<int> GetWaypointOrder() { if (_waypointOrder == null) _waypointOrder = JsonUtility.FromJson<ListInt>(WaypointOrder); return _waypointOrder.list; } public override string ToString() { return id + " / " + Name + " / " + Waypoints + " / " + WaypointOrder; } public override void Copy(Model m) { Track t = (Track)m; this.Name = t.Name; this.Waypoints = t.Waypoints; this.WaypointOrder = t.WaypointOrder; } }
68ff38c8483cf5eee2bbc14c9dad7c61325a08cd
C#
murariguilherme/SOLID
/L_Wrong/Program.cs
3.046875
3
using L_Wrong.Domains; using System; namespace L_Wrong { class Program { //People think that monkeys and apes are the same thing. Isn't! //While monkeys have tails and don't have appendix, the apes are the opposite. //So.. we've a problem with de Liskov principle, if a chimpanzee is not a monkey, the chimpanzee class cannot be substituted //by monkey class static void Main(string[] args) { Monkey monkey = new Monkey(); monkey.ShowTail(); Monkey chimpanzee = new Chimpanzee(); chimpanzee.ShowTail(); Console.ReadLine(); } } }
0ffa294e391ab27c0e180a8baee3cc8c8d3a6ba0
C#
ks489/CO7515Assignment2
/MeetingScheduler/UserService/UserSvc.svc.cs
2.59375
3
using MeetingScheduler.Core; using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.Text; namespace UserService { /// <summary> /// All User service related functions /// </summary> public class UserSvc : IUserSvc { /// <summary> /// Gets the user's representitive that would fill in for that user when they are not available /// </summary> /// <param name="user">The absent user</param> /// <returns>The representitive user</returns> public User GetRepresentitive(User user) { //Go to database and get user's presentitive //Return Representitive return new User() { UserID = 2, ContactDetails = "07858467459", ContactPreference = ContactType.SMS, FirstName = "Tom", Surname = "Smith" }; } } }
aee238e880bece48ecd2af6d593fc430c5e6c228
C#
electricsheep/Advent-of-Code
/AdventOfCode/Challenges/Day09.cs
3.546875
4
using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace AdventOfCode.Challenges { public class Day09 { public static void Run() { var numbers = File.ReadAllLines($"{AppContext.BaseDirectory}/9.txt"); RunPart1(numbers.Select(long.Parse).ToList()); } public static void RunPart1(List<long> numbers) { const int take = 25; var skip = 0; var index = 25; while (skip < numbers.Count - 25) { var previousNumbers = numbers.Skip(skip).Take(take).ToList(); var current = numbers[index]; if (HasSum(previousNumbers, current)) { index++; skip++; } else { Console.WriteLine($"no sum found for {current}"); break; } } } private static bool HasSum(List<long> preamble, long number) { var dictionary = preamble.ToDictionary(x => x, x => x); return dictionary.Select(item => number - item.Value).Any(otherNumber => dictionary.ContainsKey(otherNumber)); } } }
f6798282c8b5f69f5847891843bcaa8192393d59
C#
IceyL812/EventTicketSystem
/System Classes/World.cs
3.390625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EventTicketSystem.System_Classes { /// <summary> /// Handles the coordinates system, and store all the events and tickets data /// </summary> class World { #region Local variables protected static Range axisX; // The size of the world in Vector2 protected static Range axisY; // The size of the world in Vector2 protected static int maxEventAmountInSamecoord; //The maximum quantity of events a pair of coordinates can hold protected static List<Event> events; // A list of Event object protected static List<Ticket> tickets; //A list of Tickets (inside all the events) protected static int nextEventId; //The id for the next event being added to list protected static int decimalPlacesForDecimalCoordinateSystem; //The decimal places for the decimal coordinate system public enum coordinateSystem { Integer, Decimal } //Enum for coordinate System #endregion #region Properties //Properties for set and get variables public static Range AxisX { get { return axisX; } set { axisX = value;} } public static Range AxisY { get { return axisY; } set { axisY = value; } } public static int MaxEventAmountInSamecoord { get { return maxEventAmountInSamecoord; } set { maxEventAmountInSamecoord = (value > 1) ? value : 1; } } public static List<Event> Events { get { return events; } set { events = value; } } public static List<Ticket> Tickets { get { return tickets; } set { tickets = value; } } public static int NextEventId { get { return nextEventId; } set { nextEventId = value; } } public static coordinateSystem CoordinateSystem { get; set; } public static int DecimalPlacesForDecimalCoordinateSystem { get { return decimalPlacesForDecimalCoordinateSystem; } set { Range clampRange = new Range(1, 8); decimalPlacesForDecimalCoordinateSystem = (int)Mathc.Clamp(value, clampRange); } } //Properties for get a calculated value public static Vector2 MidPoint { get { double x = (AxisX.max + AxisX.min) / 2; double y = (AxisY.max + axisY.min) / 2; if (CoordinateSystem == coordinateSystem.Integer) { x = (int)x; y = (int)y; } else { x = Mathc.ConvertToDecimalPlace(x, decimalPlacesForDecimalCoordinateSystem); y = Mathc.ConvertToDecimalPlace(y, decimalPlacesForDecimalCoordinateSystem); } return new Vector2(x, y); } } //The middle point of the world public static int TotalEvents { get { return events.Count; } } //The number of total events in the world public static int TotalTickets { get { int temp = 0; foreach (Ticket t in tickets) { temp += t.Quantity; } return temp; } } //The number of total tickets quantity in the world public static Range PriceRangeOfAllEventTickets { get { List<Ticket> sortedTickets = TicketFinder.SortedTicketsInPrice(World.Tickets); return new Range(sortedTickets[0].Price, sortedTickets[sortedTickets.Count - 1].Price); } } //The price range of all event tickets public static int MaxEventCapacity { get { //The Maximum world capcacity of events under integer coordinate system int maxEventCapacity = (int)(World.AxisX.size * World.AxisY.size * World.MaxEventAmountInSamecoord); //Multiply 10^(Decimal Places) to get the real limit under decimal coordinate system if (World.CoordinateSystem == World.coordinateSystem.Decimal) maxEventCapacity *= (int)Math.Pow(10, World.DecimalPlacesForDecimalCoordinateSystem); return maxEventCapacity; } } //Returns the maximum world capcacity of events public static int RemainingEventCapacity { get { return MaxEventCapacity - TotalEvents; } } //Returns the remaining world capacity (How many more events can be hold) #endregion #region Methods //Constructor public World() { axisX = new Range(-10, 10, Range.RangeType.Axis); axisY = new Range(-10, 10, Range.RangeType.Axis); maxEventAmountInSamecoord = 1; CoordinateSystem = coordinateSystem.Integer; DecimalPlacesForDecimalCoordinateSystem = 4; events = new List<Event>(); tickets = new List<Ticket>(); nextEventId = 0; } /// <summary> /// Add a single Event object to List /// </summary> /// <param name="evt">Event object to be added</param> public static void AddEvent(Event evt) { //Set the id variable inside the Event object evt.ID = nextEventId; //Add the event to the list events.Add(evt); //Check if the event contains any tickets if (evt.Tickets.Count > 0) { foreach(Ticket t in evt.Tickets) { //Add the Ticket object inside the event to the tickets list tickets.Add(t); } } nextEventId++; //increase the nextEventId } /// <summary> /// Add a list of Event objects to List /// </summary> /// <param name="_events">A list of Event objects to be added</param> public static void AddEvents(List<Event> _events) { foreach (Event e in _events) AddEvent(e); } #endregion } }
a03675e16e53eb9275ca5eade041e3767605223d
C#
Euikyu/PLCProtocol
/PLCProtocol_TestApp/Converters.cs
2.703125
3
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Data; namespace PLCProtocol_TestApp { public class BoolToRadioButtonConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value is bool val) return !val; else return false; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { if (value is bool val) return !val; else return false; } } public class BoolToGreenRedColorConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value is bool val) { if (val) return "LimeGreen"; else return "Red"; } else return "Black"; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } }
f24955427923c1b4c56db103100fd6b353156565
C#
zogvm/CSharpGL
/CSharpGL/OpenGLObjects/ModernRendering/RendererBase.cs
2.828125
3
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing.Design; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CSharpGL { /// <summary> /// 用OpenGL初始化和渲染一个元素。 /// 只做初始化和渲染这两件事。 /// 一个<see cref="RendererBase"/>对象对应一个(vertex shader+fragment shader)的shader program。 /// </summary> [Editor(typeof(RendererBaseEditor), typeof(UITypeEditor))] public abstract class RendererBase : IRenderable, IDisposable { public string Name { get; set; } /// <summary> /// 为便于调试而设置的ID值,没有应用意义。 /// </summary> public int ID { get; private set; } public static int idCounter = 0; public override string ToString() { return string.Format("[{0}]: [{1}]", this.ID, this.Name); } /// <summary> /// 用OPENGL渲染一个元素。 /// </summary> public RendererBase() { this.ID = idCounter++; } private bool initialized = false; /// <summary> /// 初始化此Element,此方法应且只应执行1次。 /// </summary> public void Initialize() { if (!initialized) { DoInitialize(); initialized = true; } } /// <summary> /// 初始化此Element,此方法应且只应执行1次。 /// </summary> protected abstract void DoInitialize(); /// <summary> /// 渲染 /// </summary> /// <param name="renderMode"></param> public void Render(RenderEventArgs arg) { if (!initialized) { Initialize(); } DoRender(arg); } /// <summary> /// 执行渲染操作 /// </summary> /// <param name="arg"></param> protected abstract void DoRender(RenderEventArgs arg); #region IDisposable Members /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } // end sub /// <summary> /// Destruct instance of the class. /// </summary> ~RendererBase() { this.Dispose(false); } /// <summary> /// Backing field to track whether Dispose has been called. /// </summary> private bool disposedValue = false; /// <summary> /// Dispose managed and unmanaged resources of this instance. /// </summary> /// <param name="disposing">If disposing equals true, managed and unmanaged resources can be disposed. If disposing equals false, only unmanaged resources can be disposed. </param> private void Dispose(bool disposing) { if (this.disposedValue == false) { if (disposing) { // Dispose managed resources. DisposeManagedResources(); } // end if // Dispose unmanaged resources. DisposeUnmanagedResources(); } // end if this.disposedValue = true; } // end sub #endregion /// <summary> /// 释放.net托管资源。 /// </summary> protected virtual void DisposeManagedResources() { } /// <summary> /// 释放.net非托管资源,例如释放OpenGL相关的资源。 /// 此类型用于OpenGL渲染,因此必有要释放的OpenGL资源。因此设置为abstract。 /// </summary> protected abstract void DisposeUnmanagedResources(); } }
bbf0331fef735f1cebcb684bb0fbb652e17ebaab
C#
tectronics/battlesquadron
/ERF/PlayerHandler.cs
2.734375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Net; namespace ERF { /// <summary> /// Class for handling all players in game. /// </summary> abstract public class PlayerHandler { protected ERFGame game; protected ERF.NetworkHandler networkHandler; public PlayerHandler(ERFGame game) { this.game = game; this.networkHandler = game.NetworkHandler; this.HookNetwork(); } /// <summary> /// Binds gamerjoined and gamerleft to functions. /// </summary> private void HookNetwork() { this.networkHandler.GamerJoined += new EventHandler<GamerJoinedEventArgs>(this.network_GamerJoined); this.networkHandler.GamerLeft += new EventHandler<GamerLeftEventArgs>(this.network_GamerLeft); } /// <summary> /// Called when gamer joins game. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected abstract void network_GamerJoined(object sender, GamerJoinedEventArgs e); /// <summary> /// Called when gamer leaves game. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected abstract void network_GamerLeft(object sender, GamerLeftEventArgs e); } }
2df502758f4611da2e3ecded2569bcff7f8884aa
C#
anyoddthing/XamarinSynth
/SynthTest.iOSIntegrationTests/AudioBasics/Buffers/AudioSampleBufferTest.cs
2.9375
3
using System; using NUnit.Framework; using System.Diagnostics; namespace AudioBasics { [TestFixture] public unsafe class AudioSampleBufferTest { [Test] public void Can_Allocate_New_Buffer() { using (var fixture = new AudioSampleBuffer(2, 1024)) { Assert.NotNull(fixture); } } [Test] public void Initial_Buffer_Is_Zeroed_Out() { var numSamples = 1024; using (var fixture = new AudioSampleBuffer(2, numSamples)) { var readPtr = fixture.GetReadPointer(0); while (numSamples-- > 0) { Assert.AreEqual(0, *(readPtr++)); } numSamples = 1024; readPtr = fixture.GetReadPointer(1); while (numSamples-- > 0) { Assert.AreEqual(0, *(readPtr++)); } } } [Test] public void Can_Clear_Single_Channel() { var numSamples = 1024; using (var fixture = new AudioSampleBuffer(3, numSamples)) { var readPtr = fixture.GetReadPointer(1); var writePtr = fixture.GetWritePointer(0); for (var i = 0; i < 3 * 1024; ++i) { *writePtr++ = 127.0f; } Assert.AreEqual(127.0f, *readPtr); fixture.ClearChannel(1); Assert.AreEqual(0f, *readPtr); } } [Test] public void Can_Write_And_Read_Back() { var fixture = new AudioSampleBuffer(2, 1024); var writePtr = fixture.GetWritePointer(0); (*writePtr) = 126.0f; Assert.AreEqual(126.0f, *fixture.GetReadPointer(0)); fixture.Dispose(); } [Test] public void Set_Sample_Stores_Value() { using (var fixture = new AudioSampleBuffer(2, 1024)) { var readPtr = fixture.GetReadPointer(1); fixture.SetSample(1, 20, 127); Assert.AreEqual(127.0f, *(readPtr + 20)); } } [Test] public void Add_Sample_Updates_Prior_Value() { using (var fixture = new AudioSampleBuffer(2, 1024)) { var readPtr = fixture.GetReadPointer(1); fixture.SetSample(1, 20, 127.0f); fixture.AddSample(1, 20, 23.0f); Assert.AreEqual(127.0f + 23.0f, *(readPtr + 20)); } } // Performance Tests static float[][] _testBuffer; static AudioSampleBufferTest() { _testBuffer = new float[2][]; _testBuffer[0] = new float[1024]; _testBuffer[1] = new float[1024]; } [Test] [Ignore] public void Compare_Access_Patterns() { int runs = 1000; var stopWatch = new Stopwatch(); var numSamples = 1024; var fixture = new AudioSampleBuffer(1, numSamples); stopWatch.Start(); for (int i = 0; i != runs; ++i) { for (int j = 0; j < numSamples; j++) { if (_testBuffer[0][j] != 0) { Assert.Fail(); } } } stopWatch.Stop(); var arrayTime = stopWatch.ElapsedTicks; stopWatch.Restart(); for (int i = 0; i != runs; ++i) { var readPtr = fixture.GetReadPointer(0); for (int j = 0; j < numSamples; j++) { if (*(readPtr++) != 0) { Assert.Fail(); } } } stopWatch.Stop(); var pointerTime = stopWatch.ElapsedTicks; stopWatch.Restart(); for (int i = 0; i != runs; ++i) { for (int j = 0; j < numSamples; j++) { if (fixture.GetSample(0, j) != 0) { Assert.Fail(); } } } stopWatch.Stop(); var accessorTime = stopWatch.ElapsedTicks; fixture.Dispose(); Console.WriteLine("Pointer: {0} vs Accessor: {1} vs Array: {2}", pointerTime, accessorTime, arrayTime); } } }
d712bff561069ebb857092328472044b48f9bffb
C#
FugEbinMeme/PPT-Sandbox
/PPT-Sandbox/OptionalRadioButton.cs
2.75
3
using System.Collections.Generic; using System.Windows; using System.Windows.Controls; namespace Sandbox { public class OptionalRadioButton: RadioButton { static Dictionary<string, OptionalRadioButton> groupSelects = new Dictionary<string, OptionalRadioButton>(); public static void OverrideSelected(string groupName, OptionalRadioButton selected) => groupSelects[groupName] = selected; public static OptionalRadioButton GetSelected(string groupName) => groupSelects.ContainsKey(groupName)? groupSelects[groupName] : null; public static DependencyProperty IsOptionalProperty = DependencyProperty.Register( "IsOptional", typeof(bool), typeof(OptionalRadioButton), new PropertyMetadata(true, (obj, args) => { ((OptionalRadioButton)obj).OnIsOptionalChanged(args); })); public bool IsOptional { get => (bool)GetValue(IsOptionalProperty); set => SetValue(IsOptionalProperty, value); } private void OnIsOptionalChanged(DependencyPropertyChangedEventArgs args) { // TODO: Add event handler if needed } protected override void OnClick() { bool? wasChecked = IsChecked; base.OnClick(); if (IsOptional && wasChecked == true) { IsChecked = false; groupSelects[GroupName] = null; } if (IsChecked == true) groupSelects[GroupName] = this; } public OptionalRadioButton() => Style = (Style)Application.Current.FindResource(typeof(RadioButton)); } }
9a5956f53d82f3312bcee1202f8b0324a0ecdb93
C#
dragobaltov/Programming-Basics-And-Fundamentals
/Pyramidic/Pyramidic/Program.cs
3.6875
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Pyramidic { class Program { static void Main(string[] args) { int n = int.Parse(Console.ReadLine()); List<string> lines = new List<string>(); for (int i = 0; i < n; i++) { string text = Console.ReadLine(); lines.Add(text); } string biggestPyramid = ""; for (int i = 0; i < lines.Count; i++) { string currentLine = lines[i]; for (int j = 0; j < currentLine.Length; j++) { char symbol = currentLine[j]; string pyramid = FindPyramid(lines, symbol, i); if (pyramid.Length > biggestPyramid.Length) { biggestPyramid = pyramid; } } } Console.WriteLine(biggestPyramid); } private static string FindPyramid(List<string> lines, char symbol, int line) { string pyramid = "" + symbol + "\r\n"; int count = 3; for (int i = line + 1; i < lines.Count; i++) { string stringToFind = new string(symbol, count); if (lines[i].Contains(stringToFind)) { pyramid += stringToFind + "\r\n"; count += 2; } else { return pyramid; } } return pyramid; } } }
a3acb19b2227cede7e078378b1b180d225899494
C#
nhatvu148/local-browser
/StaticServer/Program.cs
2.71875
3
namespace StaticServer { using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Hosting; using System; using System.IO; using System.Net.Sockets; using System.Reflection; public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { int port = 3089; bool isPortInUse = true; while (isPortInUse) { isPortInUse = IsPortOpen("localhost", port, TimeSpan.FromMilliseconds(500)); if (isPortInUse) { Console.WriteLine($"Port {port++} is being used by another process"); } else { Console.WriteLine($"Port {port} is available"); } } webBuilder .UseStartup<Startup>() .UseUrls($"http://localhost:{port}/"); string pathDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); File.WriteAllText($"{pathDirectory}/../Logs.txt", port.ToString()); }); public static bool IsPortOpen(string host, int port, TimeSpan timeout) { try { using (var client = new TcpClient()) { var result = client.BeginConnect(host, port, null, null); var success = result.AsyncWaitHandle.WaitOne(timeout); client.EndConnect(result); return success; } } catch { return false; } } } }