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
66a817808860e0931c7bcb9622ba9f3cf106df8c
C#
GoverMP1990/FishyNotesRedux
/FishyNotesRedux/Forms/FishyNotes.cs
2.78125
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; // Program packages using FishyNotesRedux.Interfaces; using FishyNotesRedux.Logic; using FishyNotesRedux.Storage; using FishyNotesRedux.Delegators; using FishyNotesRedux.Forms; namespace FishyNotesRedux { public partial class FishyNotes : Form { // Declare new _noteLogic INoteLogic _noteLogic; // Declare new _fishyNote FishyNote _noteView; // Delcare int for tracking note identity int _noteIndex = 0; // Declare new note delegator for storing note tet in NoteDataElement NoteDel _noteDel; // Declare delegate for getting note from data element GetNoteDel _getNoteDel; // Declare new note data element INoteData _noteData; // Declare delegate for retrieving dictionary length DictLenDel _dictLenDel; // Declare delegate for deleting notes DeleteNoteDelegate _deleteNoteDelegate; /// <summary> /// FishyNotes class constructor /// </summary> public FishyNotes() { // Instantiate _noteData _noteData = new NoteDataElement(); // Assign _noteDel delegate to _noteData.SetNote method _noteDel = _noteData.SetNote; // Assign _getNoteDel delegate to _noteData.GetNote method _getNoteDel = _noteData.GetNote; // Assign _dictLenDel to _noteData.GetLen method _dictLenDel = _noteData.GetLen; _deleteNoteDelegate = _noteData.DeleteNote; InitializeComponent(); } /// <summary> /// METHOD: NewNote /// DESC: Creates and launches a new fishyNote form /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void NewNote(object sender, EventArgs e) { // Instantiate _noteLogic _noteLogic = new NoteLogic(); // Instantiate _noteView with new FishyNote _noteView = new FishyNote(); // Initialise _noteView by calling its init method and passing: // _noteIndex, _noteLogic, _noteLogic, _noteData, _noteDel _noteView.init(_noteIndex, _noteLogic, _noteData, _noteDel, _getNoteDel, _dictLenDel, _deleteNoteDelegate); // Increment noteIndex value _noteIndex++; //Console.WriteLine("Note index value: " + _noteIndex); } private void PrintDictLen(object sender, EventArgs e) { Console.WriteLine("Dictionary length : " + _dictLenDel(0)); } } }
a09a4f44d2b4c4fd122ebeff44dca5d4eb5569d1
C#
prohause/OOP-Basic-October-2018
/Exercise/DefiningClasses/DefiningClasses/Rectangle.cs
3.65625
4
namespace DefiningClasses { internal class Rectangle { private string _id; private double _width; private double _height; private double _positionX; private double _positionY; public Rectangle(string id, double width, double height, double positionX, double positionY) { _id = id; _width = width; _height = height; _positionX = positionX; _positionY = positionY; } public bool Intersects(Rectangle rectangle) { return rectangle._positionX + rectangle._width >= _positionX && rectangle._positionX <= _positionX + _width && rectangle._positionY >= _positionY - _height && rectangle._positionY - rectangle._height <= _positionY; } public string GetId() { return _id; } } }
2263d9e9be7af65c0292d542bbd6485a4cf3eb0c
C#
DanielStephens/Turn
/Assets/Routines/Routine/Promise.cs
2.765625
3
using System; using System.Collections.Generic; public class Promise<OUTPUT, PROGRESS> : Future<OUTPUT, PROGRESS> { private readonly object syncLock = new object(); private List<Action<PROGRESS>> onProgressActions = new List<Action<PROGRESS>>(); private List<Action<OUTPUT>> onCompletionActions = new List<Action<OUTPUT>>(); private List<Action<Exception>> onExceptionActions = new List<Action<Exception>>(); private Task task; private PROGRESS progress; private OUTPUT output; private Exception exception; private bool progression = false; private bool successful = false; private bool finished = false; public Promise(Task task) { this.task = task; } public bool Pause() { return task.Pause(); } public bool Resume() { return task.Resume(); } public bool Cancel() { lock (syncLock) { task.Cancel(); return CompleteExceptionally(null); // TODO cancel exception } } public PROGRESS Progress() { return progress; } public OUTPUT Get() { if (finished) { if (successful) { return output; } throw exception; } throw new InvalidOperationException("Get cannot be called on an incomplete Future."); } public bool IsDone() { return finished; } public bool Progress(PROGRESS progress) { lock (syncLock) { if (finished) { return false; } this.progression = true; this.progress = progress; foreach(Action<PROGRESS> a in onProgressActions) { a.Invoke(progress); } return true; } } public bool Complete(OUTPUT output) { lock (syncLock) { if (finished) { return false; } successful = true; finished = true; this.output = output; foreach (Action<OUTPUT> a in onCompletionActions) { a.Invoke(output); } return true; } } public bool CompleteExceptionally(Exception exception) { lock (syncLock) { if (finished) { return false; } successful = false; finished = true; this.exception = exception; foreach (Action<Exception> a in onExceptionActions) { a.Invoke(exception); } return true; } } public CompletionStage<R, PROGRESS> Then<R>(Func<OUTPUT, R> then) { Promise<R, PROGRESS> p = new Promise<R, PROGRESS>(new NoopTask()); lock (syncLock) { if (finished) { if (successful) { p.Complete(then.Invoke(output)); } else { p.CompleteExceptionally(exception); } } else { onCompletionActions.Add(o => p.Complete(then.Invoke(o))); onExceptionActions.Add(e => p.CompleteExceptionally(e)); } } return p as CompletionStage<R, PROGRESS>; } public CompletionStage<OUTPUT, PROGRESS> Then(Action<OUTPUT> then){ return Then<OUTPUT>(o => { then.Invoke(o); return o; }); } public bool OnProgression(Action<PROGRESS> progression) { lock (syncLock) { if (finished) { return false; } if (this.progression) { progression.Invoke(progress); } onProgressActions.Add(progression); return true; } } }
58e3308a6f111a931bf161c49fc19c7ce6d6da02
C#
artemmukhin/Glass
/Glass/Field.cs
3.046875
3
/* ************************************************************************* * Judge for AI ("Connect Five" game). * * * * This program should be used for Connect Five Competition. * * Connect Five is the game like Connect Four; for more information see * * http://www.math.spbu.ru/user/chernishev/connectfive/connectfive.html * * * * Author: Artem Mukhin * * Email: <first name>.m.<last name>@gmail.com * * Year: 2015 * * See the LICENSE file in the project root for more information. * ************************************************************************* */ namespace Glass { class Field { private char[][] cells; public char[][] Cells { get { return cells; } } private int[] freeCells; public int[,] winCells; public Field() { this.cells = new char[10][]; for (int i = 0; i < 10; i++) this.cells[i] = new char[10]; this.freeCells = new int[10]; for (int i = 0; i < 10; i++) freeCells[i] = 9; for (int row = 0; row < 10; row++) { for (int col = 0; col < 10; col++) { this.cells[row][col] = ' '; } } this.cells[9][4] = '-'; this.cells[9][5] = '-'; this.winCells = new int[5,2]; for (int i = 0; i < 5; i++) { this.winCells[i, 0] = -1; this.winCells[i, 1] = -1; } } /// <summary> /// Add X or O to column /// </summary> /// <param name="col">Column on which the move was made</param> /// <returns>false if step is invalid, true if step is valid</returns> public bool ChangeCell(int col, char xORo) { if (col < 0 || col > 9) return false; if (this.cells[0][col] != ' ') return false; char prev, curr; int start = ((col == 4 || col == 5) ? 8 : 9); prev = this.cells[start][col]; curr = this.cells[start - 1][col]; this.cells[start][col] = xORo; for (int row = start - 1; row >= 0; row--) { curr = this.cells[row][col]; this.cells[row][col] = prev; prev = curr; } return true; } /// <summary> /// Remove X or O from column /// This method is used for rewind steps /// </summary> /// <param name="col">Сolumn on which the move was made</param> /// <returns>false if step is invalid, true if step is valid</returns> public void DeleteCell(int col) { if (col == -1) return; // if timeout int start = ((col == 4 || col == 5) ? 8 : 9); for (int row = start; row > 0; row--) { this.cells[row][col] = this.cells[row-1][col]; } this.cells[0][col] = ' '; } } }
e79648cd0a4c104f383fb73a2badd6ee35de971b
C#
skarakasoglu-zz/Cet.PrinciplesOfDistanceEducation
/Cet.PrinciplesOfDistanceEducation.Service/CreditsService.cs
2.890625
3
using System; using System.Linq; using Cet.PrinciplesOfDistanceEducation.Data; using Cet.PrinciplesOfDistanceEducation.Data.Models; namespace Cet.PrinciplesOfDistanceEducation.Service { public class CreditsService : ICredits { private CetDbContext _context; public CreditsService(CetDbContext context) { _context = context; } public void Add(Credits credits) { _context.Add(credits); _context.SaveChanges(); } public void Update(Credits credits) { _context.Update(credits); _context.SaveChanges(); } public void Remove(Credits credits) { _context.Remove(credits); _context.SaveChanges(); } public void CreateCredits(string content, string userName) { var now = DateTime.Now; Credits credits = new Credits { Content = content, CreatedDate = now, CreateUser = _context.Users.FirstOrDefault(u => u.UserName == userName) }; Add(credits); } public string GetLastCreditsContent() { return _context.Credits .OrderByDescending(c => c.CreatedDate) .FirstOrDefault().Content; } } }
050b27ac951d18faa10f118a4a0a212497d979f5
C#
ArturoMora/SIGCOFOO
/INEEL.DataAccess.GEN/Repositories/CH/DesNivelCompetenciaRepository.cs
2.515625
3
using INEEL.DataAccess.GEN.Contexts; using INEEL.DataAccess.GEN.Models.CH; using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Text; using System.Threading.Tasks; namespace INEEL.DataAccess.GEN.Repositories.CH { public class DesNivelCompetenciaRepository : IDisposable { //----------- AYUDA: // DesNivelCompetenciaRepository: nombre de clase (y tipicamente el constructor) // FooDbContext.- tu Contexto : DbContext // DescripcionNivelCompetencias.- es el modelo // descripcionNivel.- es el nombre de la variable tipo DbSet en el DbContext ( // ejemplo: public virtual DbSet<Category> Categories { get; set; } // :: descripcionNivel =Categories ) // FooID.- es el ID del modelo (ID de la tabla) private SIGCOCHContext _db; public DesNivelCompetenciaRepository() { _db = new SIGCOCHContext(); } //public async Task<IEnumerable<DescripcionNivelCompetencias>> OtrosMetodos(){ ... } public async Task<IEnumerable<DescripcionNivelCompetencias>> GetAll() { try { var entities = await _db.descripcionNivel.AsNoTracking().ToListAsync(); return entities; } catch (Exception e) { throw new Exception(e.Message, e); } } public async Task<DescripcionNivelCompetencias> Get(int id) { try { var entities = await _db.descripcionNivel.AsNoTracking() // .Include(x=> x.FK) .FirstOrDefaultAsync(e => e.descNivelId == id); return entities; } catch (Exception e) { throw new Exception(e.Message, e); } } public async Task<DescripcionNivelCompetencias> GetByNivel(BusquedaNivel parametros) { try { var entities = await _db.descripcionNivel.AsNoTracking() .Where(e => e.Periodo == parametros.periodo) .Where(e => e.CompetenciaID == parametros.idCompetencia) .Where(e => e.Estado == 1) .FirstOrDefaultAsync(e => e.NivelId == parametros.idNivel); return entities; } catch (Exception e) { throw new Exception(e.Message, e); } } public async Task<IEnumerable<DescripcionNivelCompetencias>> GetByCompetencia(BusquedaNivel parametros) { try { var entities = await _db.descripcionNivel .Where(e => e.Periodo == parametros.periodo) .Where(e => e.CompetenciaID == parametros.idCompetencia) .Where(e => e.Estado == 1) .Where(e => e.nivel.Estado == 1) .Include(e=> e.nivel) .AsNoTracking().ToListAsync(); return entities; } catch (Exception e) { throw new Exception(e.Message, e); } } public async Task Create(DescripcionNivelCompetencias model) { try { _db.descripcionNivel.Add(model); await _db.SaveChangesAsync(); } catch (Exception e) { throw new Exception(e.Message, e); } } public async Task Update(DescripcionNivelCompetencias model) { try { var _model = await _db.descripcionNivel.FirstOrDefaultAsync(e => e.descNivelId == model.descNivelId); if (_model != null) { _db.Entry(_model).CurrentValues.SetValues(model); await _db.SaveChangesAsync(); } } catch (Exception e) { throw new Exception(e.Message, e); } } public async Task Delete(int id) { try { var _model = await _db.descripcionNivel.FirstOrDefaultAsync(e => e.descNivelId == id); if (_model != null) { _db.descripcionNivel.Remove(_model); await _db.SaveChangesAsync(); } } catch (Exception e) { throw new Exception(e.Message, e); } } public async Task UpdateEstado(DescripcionNivelCompetencias obj) { try { var _obj = await _db.descripcionNivel.FirstOrDefaultAsync(e => e.descNivelId == obj.descNivelId); if (_obj != null) { _obj.Estado = obj.Estado; await _db.SaveChangesAsync(); } } catch (Exception e) { throw new Exception(e.Message, e); } } public void Dispose() { _db.Dispose(); //ayudar al recolector de basura } } }
1d194a9d7c7b46b53e92e64330ac9630b27b6979
C#
SuraaKara/C-
/Clebra.Loopus.Service/Yarn Type Data Service/YarnTypeDataService.cs
2.53125
3
using Clebra.Loopus.DataAccess; using Clebra.Loopus.Model; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; namespace Clebra.Loopus.Service { public class YarnTypeDataService : IYarnTypeDataService { private readonly LoopusDataContext dataContext; public YarnTypeDataService(LoopusDataContext dataContext) { this.dataContext = dataContext; } public async Task<YarnType> GetAsync(Expression<Func<YarnType, bool>> query) => await dataContext.YarnTypes.FirstOrDefaultAsync(query); public async Task<IEnumerable<YarnType>> GetListAsync(Expression<Func<YarnType, bool>> query) => await dataContext.YarnTypes.Where(query).ToListAsync(); public async Task SubmitChangeAsync(YarnType entity) { try { dataContext.Entry<YarnType>(entity).State = await dataContext.YarnTypes.AnyAsync(a => a.Id == entity.Id) ? EntityState.Modified : EntityState.Added; await dataContext.SaveChangesAsync(); dataContext.Entry<YarnType>(entity).State = EntityState.Detached; } catch (Exception e) { Console.WriteLine(e); } } } }
a2c5f3fa32c5773cba6c32fa803fa4f40ff6aef9
C#
sunston/NetStudio
/LanguageForm.cs
2.515625
3
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using NetStudio.Document; namespace NetStudio { public partial class LanguageForm : Form { private bool m_Result = false; public LanguageForm() { InitializeComponent(); } private void buttonOk_Click(object sender, EventArgs e) { m_Result = true; this.Close(); } private void buttonCancel_Click(object sender, EventArgs e) { this.Close(); } public bool Result { get { return m_Result; } } public CCSLanguage Language { get { if (radioButtonCSharp.Checked) return CCSLanguage.CSharp; else return CCSLanguage.VisualBasic; } } } }
b55d325baa80f22098562eb709d29e7ac9fcf9eb
C#
pirocorp/CSharp-Fundamentals
/13. Files Directories and Exceptions - Exercises/03. User Database/User Database.cs
3.5
4
using System; using System.Collections.Generic; using System.IO; namespace _03.User_Database { class Program { private static string dbPath = "users.txt"; private static Dictionary<string, string> users = new Dictionary<string, string>(); private static bool isLogged = false; static void Main() { if (!File.Exists(dbPath)) { File.Create(dbPath).Close(); } var usersFromFile = File.ReadAllLines(dbPath); for (var i = 0; i < usersFromFile.Length; i++) { var currentUser = usersFromFile[i].Split(' '); var currentUsername = currentUser[0]; var currentPasword = currentUser[1]; users[currentUsername] = currentPasword; } var commands = File.ReadAllLines("Input.txt"); for (var i = 0; i < commands.Length; i++) { var currentCommand = commands[i].Split(' '); switch (currentCommand[0]) { case "register": var username = currentCommand[1]; var password = currentCommand[2]; var confirmPassword = currentCommand[3]; Register(username, password, confirmPassword); break; case "login": username = currentCommand[1]; password = currentCommand[2]; Login(username, password); break; case "logout": Logout(); break; } } } private static void Logout() { if (!isLogged) { Console.WriteLine($"There is no currently logged in user."); return; } isLogged = false; } private static void Login(string username, string password) { if (!users.ContainsKey(username)) { Console.WriteLine($"There is no user with the given username."); return; } if (users[username] != password) { Console.WriteLine($"The password you entered is incorrect."); return; } if (isLogged) { Console.WriteLine($"There is already a logged in user."); return; } isLogged = true; } private static void Register(string username, string password, string confirmPassword) { if (users.ContainsKey(username)) { Console.WriteLine($"The given username already exists."); return; } if (password != confirmPassword) { Console.WriteLine($"The two passwords must match."); return; } users[username] = password; var currentUser = new[] { $"{username} {password}" }; File.AppendAllLines(dbPath, currentUser); } } }
e5af294ef84c44a3c9cd830dce931631dcc30c4a
C#
DS2107/AesEncryption
/AesEncryption-main/AES_encryption/AES_encryption/Form1.cs
2.6875
3
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Text.RegularExpressions; using System.Threading; using System.Security.Cryptography; namespace AES_encryption { public partial class Form1 : Form { // Выбор файла OpenFileDialog SelectFile = new OpenFileDialog(); // указать папку для дешифровки файла FolderBrowserDialog saveFileDesc = new FolderBrowserDialog(); // мой класс в котором метод дешифровки и шифрования MyEncrypt myEncrypt = new MyEncrypt(); // Список выделенных файлов List<string> MyFiles; // Список файлов c расшиерением aes List<string> FilesAES; // полный путь выбранной папки string fullname_saveFile; public static Form1 MyForm; public Form1() { InitializeComponent(); // ставим для пароля * textBox_password.PasswordChar = '*'; // Что бы брать только один файл SelectFile.Multiselect = true; // Фильтр файлов SelectFile.Filter = "aes files (*.aes)|*.aes|All files (*.*)|*.*"; // Фильтр файлов open_key.Filter = "ka files (*.ka)|*.ka|All files (*.*)|*.*"; } public void StartEncryptThread() { CheckEncryption(MyFiles); } public void StartDecryptThread() { int count = 0; foreach (var file in MyFiles) { if (Path.GetExtension(file) == ".aes") { count++; } } MessageBox.Show("В файлах которые вы указали, были найдено: " + count + " .aes файлов"); if (count == 0) { textBox_password.Invoke((MethodInvoker)(() => textBox_password.Text = "")); } else { CheckDescryption(MyFiles); count = 0; } } private void button_openFile_Click(object sender, EventArgs e) { // Проверяю нажаk ли if (SelectFile.ShowDialog() == DialogResult.Cancel) return; else { listBox_SelectFiles.Items.Clear(); foreach (var file in SelectFile.FileNames.ToList()) { listBox_SelectFiles.Items.Add(Path.GetFileName(file)); MyFiles = SelectFile.FileNames.ToList(); } } } // button_openFile_Click // Штфрование private void button_Encryption_Click(object sender, EventArgs e) { if (checkBoxFileKEY.Checked) { if (MyFiles != null) { Thread thread1 = new Thread(FileKeyEncrypt); thread1.Start(); } // if else { label_problem.ForeColor = Color.Red; label_problem.Invoke((MethodInvoker)(() => label_problem.Text = "Выберите файл для шифрования")); } } // if else { Thread thread = new Thread(StartEncryptThread); thread.Start(); } } // button_Encryption_Click // Дешифровка private void button_NonEncryption_Click(object sender, EventArgs e) { if (saveFileDesc.ShowDialog() == DialogResult.Cancel) return; if (checkBoxFileKEY.Checked) { Thread thread1 = new Thread(FileKeyDecrypt); thread1.Start(); } else { Thread thread = new Thread(StartDecryptThread); thread.Start(); } } // button_NonEncryption_Click private void CheckDescryption(List<string> MyFiles) { // Проверяю выбрал и я файл if (MyFiles == null) { label_problem.ForeColor = Color.Red; label_problem.Text = "Такого файла не существует или вы его не выбрали"; } // if else { FilesAES = new List<string>(); foreach (var file in MyFiles) { if (Path.GetExtension(file) == ".aes") { FilesAES.Add(file); // MyFiles.Remove(file); } } // Задал ли я пароль if (String.IsNullOrEmpty(textBox_password.Text)) { label_problem.ForeColor = Color.Red; label_problem.Invoke((MethodInvoker)(() => label_problem.Text = "Вы не указали пароль")); } // if else { int i = 0; progressBar_encryption.Invoke((MethodInvoker)(() => progressBar_encryption.Maximum = FilesAES.Count)); progressBar_encryption.Minimum = 0; bool flag = true; button_Encryption.Invoke((MethodInvoker)(() => button_Encryption.Enabled = false)); button_NonEncryption.Invoke((MethodInvoker)(() => button_NonEncryption.Enabled = false)); button_openFile.Invoke((MethodInvoker)(() => button_openFile.Enabled = false)); button_SelectFolder.Invoke((MethodInvoker)(() => button_SelectFolder.Enabled = false)); foreach (var file in FilesAES) { fullname_saveFile = saveFileDesc.SelectedPath; fullname_saveFile = fullname_saveFile + @"\" + Path.GetFileName(file); fullname_saveFile = fullname_saveFile.Remove(fullname_saveFile.Length - 4); if (myEncrypt.FileDecrypt(file, fullname_saveFile, textBox_password.Text)) { i++; progressBar_encryption.Invoke((MethodInvoker)(() => progressBar_encryption.Value = i)); label_problem.ForeColor = Color.Green; label_problem.Invoke((MethodInvoker)(() => label_problem.Text = "Дешифровка...")); flag = true; } else { i++; progressBar_encryption.Invoke((MethodInvoker)(() => progressBar_encryption.Value = i)); label_problem.ForeColor = Color.Red; label_problem.Invoke((MethodInvoker)(() => label_problem.Text = "Проблемы с паролем...")); flag = false; } } Thread.Sleep(3000); button_Encryption.Invoke((MethodInvoker)(() => button_Encryption.Enabled = true)); button_NonEncryption.Invoke((MethodInvoker)(() => button_NonEncryption.Enabled = true)); button_openFile.Invoke((MethodInvoker)(() => button_openFile.Enabled = true)); button_SelectFolder.Invoke((MethodInvoker)(() => button_SelectFolder.Enabled = true)); i = 0; MyFiles.Clear(); progressBar_encryption.Invoke((MethodInvoker)(() => progressBar_encryption.Value = 0)); if (flag) { label_problem.ForeColor = Color.Green; label_problem.Invoke((MethodInvoker)(() => label_problem.Text = "Дешифровка закончена...")); textBox_password.Invoke((MethodInvoker)(() => textBox_password.Text = "")); listBox_SelectFiles.Invoke((MethodInvoker)(() => listBox_SelectFiles.Items.Clear())); MyFiles.Clear(); } else { label_problem.ForeColor = Color.Red; label_problem.Invoke((MethodInvoker)(() => label_problem.Text = "Дешифровка неудалась...")); textBox_password.Invoke((MethodInvoker)(() => textBox_password.Text = "")); // listBox_SelectFiles.Invoke((MethodInvoker)(() => listBox_SelectFiles.Items.Clear())); } } } } private void CheckEncryption(List<string> MyFiles) { // Проверяю выбрал и я файл if (MyFiles == null) { label_problem.ForeColor = Color.Red; label_problem.Invoke((MethodInvoker)(() => label_problem.Text = "Такого файла не существует или вы его не выбрали")); } // if else { // Задал ли я пароль if (String.IsNullOrEmpty(textBox_password.Text)) { label_problem.ForeColor = Color.Red; label_problem.Invoke((MethodInvoker)(() => label_problem.Text = "Вы не указали пароль")); } // if else { // Проверка пароля регуляркой и длину пароля if (textBox_password.Text.Length < 8) { label_problem.Invoke((MethodInvoker)(() => label_problem.Text = "Пароль меньше 8 символов")); label_problem.ForeColor = Color.Red; } // if else { string pattern = @"^((?=.*[a-z])|(?=.*[а-я]))((?=.*[A-Z])|(?=.*[А-Я]))(?=.*[0-9])(?=.*[^a-zA-Z0-9])\S"; bool myreg = Regex.IsMatch(textBox_password.Text, pattern); if (myreg) { label_problem.ForeColor = Color.Green; label_problem.Invoke((MethodInvoker)(() => label_problem.Text = "Идет процес шифрования ждите...")); progressBar_encryption.Invoke((MethodInvoker)(() => progressBar_encryption.Maximum = MyFiles.Count)); progressBar_encryption.Minimum = 0; int i = 0; // Шифруем button_NonEncryption.Invoke((MethodInvoker)(() => button_NonEncryption.Enabled = false)); button_openFile.Invoke((MethodInvoker)(() => button_openFile.Enabled = false)); button_SelectFolder.Invoke((MethodInvoker)(() => button_SelectFolder.Enabled = false)); button_Encryption.Invoke((MethodInvoker)(() => button_Encryption.Enabled = false)); foreach (var file in MyFiles) { i++; myEncrypt.FileEncrypt(file, textBox_password.Text); progressBar_encryption.Invoke((MethodInvoker)(() => progressBar_encryption.Value = i)); // progressBar_encryption.Value = i; } i = 0; Thread.Sleep(3000); button_Encryption.Invoke((MethodInvoker)(() => button_Encryption.Enabled = true)); button_NonEncryption.Invoke((MethodInvoker)(() => button_NonEncryption.Enabled = true)); button_openFile.Invoke((MethodInvoker)(() => button_openFile.Enabled = true)); button_SelectFolder.Invoke((MethodInvoker)(() => button_SelectFolder.Enabled = true)); progressBar_encryption.Invoke((MethodInvoker)(() => progressBar_encryption.Value = 0)); label_problem.ForeColor = Color.Green; label_problem.Invoke((MethodInvoker)(() => label_problem.Text = "Все удчано, обработанно файлов - " + MyFiles.Count)); textBox_password.Invoke((MethodInvoker)(() => textBox_password.Text = "")); listBox_SelectFiles.Invoke((MethodInvoker)(() => listBox_SelectFiles.Items.Clear())); MyFiles.Clear(); } //if else { label_problem.Invoke((MethodInvoker)(() => label_problem.Text = "Пароль должен иметь - (Хотя бы 1 заглавную букву, цифру, и спец символ)")); } } } } } private void button_SelectFolder_Click(object sender, EventArgs e) { // указать папку для дешифровки файла FolderBrowserDialog saveFileDesc = new FolderBrowserDialog(); if (saveFileDesc.ShowDialog() == DialogResult.Cancel) { return; } MyFiles = Directory.GetFiles(saveFileDesc.SelectedPath).ToList(); foreach (var file in MyFiles) { listBox_SelectFiles.Items.Add(Path.GetFileName(file)); } } // button_SelectFolder_Click // openFolder FolderBrowserDialog openFolder; private void button_HashFile_Click(object sender, EventArgs e) { openFolder = new FolderBrowserDialog(); if (openFolder.ShowDialog() == DialogResult.Cancel) return; var folder_file_key = openFolder.SelectedPath; // Создаю файл FileStream fsCrypt = new FileStream("Key.ka", FileMode.Create); myEncrypt.GeneratePassword(openFolder.SelectedPath+@"\Key.ka"); } // button_HashFile_Click private void checkBoxFileKEY_CheckStateChanged(object sender, EventArgs e) { if (checkBoxFileKEY.Checked ) { textBox_password.Enabled = false; checkBoxFileKEY.Text = "Режим: Файл-Ключ"; checkBoxFileKEY.ForeColor = Color.DarkGreen; if (open_key == null) { textBox_password.Enabled = false; button_Encryption.Enabled = false; button_NonEncryption.Enabled = false; textBox_password.Enabled = false; } else { button_Encryption.Enabled = true; button_NonEncryption.Enabled = true; } } else { checkBoxFileKEY.Text = "Режим: Ввод пароля"; checkBoxFileKEY.ForeColor = Color.DarkGreen; textBox_password.Enabled = true; button_Encryption.Enabled = true; button_NonEncryption.Enabled = true; } } private void FileKeyEncrypt() { if(MyFiles == null) { label_problem.ForeColor = Color.Red; label_problem.Invoke((MethodInvoker)(() => label_problem.Text = "Выберите файл для шифрования")); } int i = 0; button_Encryption.Invoke((MethodInvoker)(() => button_Encryption.Enabled = false)); button_NonEncryption.Invoke((MethodInvoker)(() => button_NonEncryption.Enabled = false)); button_openFile.Invoke((MethodInvoker)(() => button_openFile.Enabled = false)); button_SelectFolder.Invoke((MethodInvoker)(() => button_SelectFolder.Enabled = false)); progressBar_encryption.Invoke((MethodInvoker)(() => progressBar_encryption.Maximum = MyFiles.Count)); label_problem.ForeColor = Color.Green; label_problem.Invoke((MethodInvoker)(() => label_problem.Text = "Идет процес шифрования ждите...")); foreach (var file in MyFiles) { i++; myEncrypt.FileEncrypt(open_key.FileName, file, 1); progressBar_encryption.Invoke((MethodInvoker)(() => progressBar_encryption.Value = i)); } i = 0; Thread.Sleep(3000); progressBar_encryption.Invoke((MethodInvoker)(() => progressBar_encryption.Value = 0)); label_problem.ForeColor = Color.Green; button_Encryption.Invoke((MethodInvoker)(() => button_Encryption.Enabled = true)); button_NonEncryption.Invoke((MethodInvoker)(() => button_NonEncryption.Enabled = true)); button_openFile.Invoke((MethodInvoker)(() => button_openFile.Enabled = true)); button_SelectFolder.Invoke((MethodInvoker)(() => button_SelectFolder.Enabled = true)); label_problem.Invoke((MethodInvoker)(() => label_problem.Text = "Все удчано, обработанно файлов - " + MyFiles.Count)); textBox_password.Invoke((MethodInvoker)(() => textBox_password.Text = "")); listBox_SelectFiles.Invoke((MethodInvoker)(() => listBox_SelectFiles.Items.Clear())); MyFiles.Clear(); } private void FileKeyDecrypt() { // Проверяю выбрал и я файл if (MyFiles == null) { label_problem.ForeColor = Color.Red; label_problem.Text = "Такого файла не существует или вы его не выбрали"; } // if else { FilesAES = new List<string>(); foreach (var file in MyFiles) { if (Path.GetExtension(file) == ".aes") { FilesAES.Add(file); // MyFiles.Remove(file); } } if (FilesAES.Count != 0) { int i = 0; progressBar_encryption.Invoke((MethodInvoker)(() => progressBar_encryption.Maximum = FilesAES.Count)); progressBar_encryption.Minimum = 0; bool flag = true; button_Encryption.Invoke((MethodInvoker)(() => button_Encryption.Enabled = false)); button_NonEncryption.Invoke((MethodInvoker)(() => button_NonEncryption.Enabled = false)); button_openFile.Invoke((MethodInvoker)(() => button_openFile.Enabled = false)); button_SelectFolder.Invoke((MethodInvoker)(() => button_SelectFolder.Enabled = false)); foreach (var file in FilesAES) { fullname_saveFile = saveFileDesc.SelectedPath; fullname_saveFile = fullname_saveFile + @"\" + Path.GetFileName(file); fullname_saveFile = fullname_saveFile.Remove(fullname_saveFile.Length - 4); if (myEncrypt.FileDecrypt(file, fullname_saveFile, open_key.FileName, 1)) { i++; progressBar_encryption.Invoke((MethodInvoker)(() => progressBar_encryption.Value = i)); label_problem.ForeColor = Color.Green; label_problem.Invoke((MethodInvoker)(() => label_problem.Text = "Дешифровка...")); flag = true; } else { i++; progressBar_encryption.Invoke((MethodInvoker)(() => progressBar_encryption.Value = i)); label_problem.ForeColor = Color.Red; label_problem.Invoke((MethodInvoker)(() => label_problem.Text = "Проблемы с паролем...")); flag = false; } } Thread.Sleep(3000); button_Encryption.Invoke((MethodInvoker)(() => button_Encryption.Enabled = true)); button_NonEncryption.Invoke((MethodInvoker)(() => button_NonEncryption.Enabled = true)); button_openFile.Invoke((MethodInvoker)(() => button_openFile.Enabled = true)); button_SelectFolder.Invoke((MethodInvoker)(() => button_SelectFolder.Enabled = true)); i = 0; progressBar_encryption.Invoke((MethodInvoker)(() => progressBar_encryption.Value = 0)); if (flag) { label_problem.ForeColor = Color.Green; label_problem.Invoke((MethodInvoker)(() => label_problem.Text = "Дешифровка закончена...")); textBox_password.Invoke((MethodInvoker)(() => textBox_password.Text = "")); listBox_SelectFiles.Invoke((MethodInvoker)(() => listBox_SelectFiles.Items.Clear())); MyFiles.Clear(); } else { label_problem.ForeColor = Color.Red; label_problem.Invoke((MethodInvoker)(() => label_problem.Text = "Дешифровка неудалась...")); textBox_password.Invoke((MethodInvoker)(() => textBox_password.Text = "")); // listBox_SelectFiles.Invoke((MethodInvoker)(() => listBox_SelectFiles.Items.Clear())); } } else { label_problem.ForeColor = Color.Red; label_problem.Invoke((MethodInvoker)(() => label_problem.Text = "Выберете файл...")); } } } OpenFileDialog open_key = new OpenFileDialog(); private void button_searchKEY_Click(object sender, EventArgs e) { open_key.Multiselect = false; if (open_key.ShowDialog() == DialogResult.Cancel) return; if (open_key.FileName != "") { button_Encryption.Enabled = true; button_NonEncryption.Enabled = true; } } // button_searchKEY_Click } }
a906369f50fd73640530305f8a3e1720cc3ef419
C#
bradygetson/Notes-Application
/NoteApp/Commands/DeleteCommand.cs
2.828125
3
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Input; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; namespace NoteApp { public class DeleteCommand : ICommand { public event EventHandler CanExecuteChanged; private ViewModels.NotesViewModel notesViewModel; /// <summary> /// Default constructor that intializes our notesViewModel /// </summary> public DeleteCommand(ViewModels.NotesViewModel notesViewModel) { this.notesViewModel = notesViewModel; } /// <summary> /// Can execute if the selected note is not null /// </summary> public bool CanExecute(object parameter) { return notesViewModel.SelectedNote != null; } /// <summary> /// Deletes the selected file when executed /// </summary> public async void Execute(object parameter) { string noteToDelete = notesViewModel.NoteName; //Shows our SaveNoteDialog and waits for a response ContentDialog confirmDelete = new ContentDialog { Title = "Confirm Delete", Content = "Are you sure you want to delete?", PrimaryButtonText = "Confirm", SecondaryButtonText = "Cancel" }; ContentDialogResult result = await confirmDelete.ShowAsync(); if (result == ContentDialogResult.Primary) { try { Repositories.NotesRepo.DeleteNoteFromDB(noteToDelete); ContentDialog deleteDialog = new ContentDialog { Title = "Delete Successful", Content = "Note Deleted Successfully", PrimaryButtonText = "OK" }; await deleteDialog.ShowAsync(); notesViewModel.SelectedNote = null; //Source of refreshing page after delete: https://stackoverflow.com/questions/47792071/uwp-mvvm-refresh-page-after-change-of-language Frame rootframe = Window.Current.Content as Frame; rootframe?.Navigate(typeof(MainPage)); } catch (Exception) { ContentDialog errorDialog = new ContentDialog { Title = "Error deleting file", Content = "There was an error deleting the file", PrimaryButtonText = "OK" }; await errorDialog.ShowAsync(); } } } public void FireCanExecuteChanged() { CanExecuteChanged?.Invoke(this, EventArgs.Empty); } } }
99177062b2d7afd19754eec0ae8d05f0fc1d7582
C#
emphasis87/Emphasis.Algorithms
/src/Emphasis.Algorithms.Tests/TestHelper.cs
2.828125
3
using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; namespace Emphasis.Algorithms.Tests { public static class TestHelper { public static void Run(Bitmap bitmap, string name) { if (!Path.HasExtension(name)) name = $"{name}.png"; bitmap.Save(name); Run(name); } public static void Run(string path, string arguments = null) { if (!Path.IsPathRooted(path) && Path.HasExtension(path)) path = Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, path)); var info = new ProcessStartInfo(path) { UseShellExecute = true }; if (arguments != null) { info.Arguments = arguments; } Process.Start(info); } public static Bitmap ToBitmap(this byte[] data, int width, int height, int channels = 1) { var bitmap = new Bitmap(width, height); var bounds = new System.Drawing.Rectangle(0, 0, width, height); var bitmapData = bitmap.LockBits(bounds, ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); var bitmapPointer = bitmapData.Scan0; if (channels == 1) { var p = 0; var source = new byte[height * width * 4]; for (var i = 0; i < height * width; i++) { var value = data[i]; source[p++] = value; source[p++] = value; source[p++] = value; source[p++] = 255; } data = source; } var dataHandle = GCHandle.Alloc(data, GCHandleType.Pinned); var dataPointer = dataHandle.AddrOfPinnedObject(); for (var y = 0; y < height; y++) { SharpDX.Utilities.CopyMemory(bitmapPointer, dataPointer, width * 4); dataPointer = IntPtr.Add(dataPointer, width * 4); bitmapPointer = IntPtr.Add(bitmapPointer, width * 4); } bitmap.UnlockBits(bitmapData); dataHandle.Free(); return bitmap; } } }
a5fa8f65c03e3da5489b95e1218c1c71291af441
C#
raj153/C-AlgoDS
/AlGoLiv/OOP/ChessCompo.cs
3.234375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AlGoLiv.OOP1 { public class Board { int boardSize; Cell[][] cells; public Board(int boardSize, Cell[][] cells) { this.boardSize = boardSize; this.cells = cells; } /** * Helper method to return cell to the left of current cell. */ public Cell getLeftCell(Cell cell) { return getCellAtLocation(cell.x, cell.y - 1); } /** * Helper method to return cell to the right of current cell. */ public Cell getRightCell(Cell cell) { return getCellAtLocation(cell.x, cell.y + 1); } /** * Helper method to return cell to the up of current cell. */ public Cell getUpCell(Cell cell) { return getCellAtLocation(cell.x + 1, cell.y); } /** * Helper method to return cell to the down of current cell. */ public Cell getDownCell(Cell cell) { return getCellAtLocation(cell.x - 1, cell.y); } /** * Helper method to return cell at a given location. */ public Cell getCellAtLocation(int x, int y) { if (x >= boardSize || x < 0) { return null; } if (y >= boardSize || y < 0) { return null; } return cells[x][y]; } /** * Helper method to determine whether the player is on check on the current board. */ public bool isPlayerOnCheck(Player player) { return checkIfPieceCanBeKilled(player.getPiece(PieceType.KING), kingCheckEvaluationBlockers(), player); } private List<PieceCellOccupyBlocker> kingCheckEvaluationBlockers() { throw new NotImplementedException(); } /** * Method to check if the piece can be killed currently by the opponent as per the current board configuration. * * @param targetPiece Piece which is to be checked. * @param cellOccupyBlockers Blockers which make cell non occupiable. * @param player Player whose piece has to be checked. * @return bool indicating whether the piece is in danger or not. */ public bool checkIfPieceCanBeKilled(Piece targetPiece, List<PieceCellOccupyBlocker> cellOccupyBlockers, Player player) { for (int i = 0; i < boardSize; i++) { for (int j = 0; j < boardSize; j++) { Piece currentPiece = getCellAtLocation(i, j).currentPiece; if (currentPiece != null && !currentPiece.isPieceFromSamePlayer(targetPiece)) { List<Cell> nextPossibleCells = currentPiece.nextPossibleCells(this, cellOccupyBlockers, player); if (nextPossibleCells.Contains(targetPiece.currentCell)) { return true; } } } } return false; } } public class Cell { public int x; public int y; public Cell(int x, int y) { this.x = x; this.y = y; } public Piece currentPiece; public bool isFree() { return currentPiece == null; } } public enum Color { BLACK, WHITE } public class Piece { private bool isKilled = false; private Color _color; private List<PossibleMovesProvider> movesProviders; private int numMoves = 0; public PieceType pieceType; public Cell currentCell; public Piece(Color color, List<PossibleMovesProvider> movesProviders, PieceType pieceType) { this._color = color; this.movesProviders = movesProviders; this.pieceType = pieceType; } public void killIt() { this.isKilled = true; } /** * Method to move piece from current cell to a given cell. */ public void move(Player player, Cell toCell, Board board, List<PieceCellOccupyBlocker> additionalBlockers) { if (isKilled) { throw new InvalidMoveException(); } List<Cell> nextPossibleCells1 = nextPossibleCells(board, additionalBlockers, player); if (!nextPossibleCells1.Contains(toCell)) { throw new InvalidMoveException(); } killPieceInCell(toCell); this.currentCell.currentPiece = null; this.currentCell = toCell; this.currentCell.currentPiece = this; this.numMoves++; } /** * Helper method to kill a piece in a given cell. */ private void killPieceInCell(Cell targetCell) { if (targetCell.currentPiece != null) { targetCell.currentPiece.killIt(); } } /** * Method which tells what are all next possible cells to which the current piece can move from the current cell. * * @param board Board on which the piece is present. * @param additionalBlockers Blockers which make a cell non-occupiable for a piece. * @param player Player who owns the piece. * @return List of all next possible cells. */ public List<Cell> nextPossibleCells(Board board, List<PieceCellOccupyBlocker> additionalBlockers, Player player) { List<Cell> result = new List<Cell>(); foreach (PossibleMovesProvider movesProvider in movesProviders) { List<Cell> cells = movesProvider.possibleMoves(this, board, additionalBlockers, player); if (cells != null) { result.AddRange(cells); } } return removeDuplicates(result); } private List<Cell> removeDuplicates(List<Cell> result) { throw new NotImplementedException(); } /** * Helper method to check if two pieces belong to same player. */ public bool isPieceFromSamePlayer(Piece piece) { return piece._color.Equals(this._color); } } public class PieceCellOccupyBlocker { } public enum PieceType { KING, QUEEN, ROOK, KNIGHT, BISHOP, PAWN } public abstract class Player { List<Piece> pieces; public Player(List<Piece> pieces) { this.pieces = pieces; } public Piece getPiece(PieceType pieceType) { foreach (Piece piece in pieces) { if (piece.pieceType == pieceType) { return piece; } } throw new PieceNotFoundException(); } } /** * Given a cell, it will provide next cell which we can reach to. */ public interface NextCellProvider { Cell nextCell(Cell cell); } /** * Provider class which returns all the possible cells for a given type of moves. For example, horizontal type of move * will give all the cells which can be reached by making only horizontal moves. */ public abstract class PossibleMovesProvider { int maxSteps; MoveBaseCondition baseCondition; private PieceMoveFurtherCondition MoveFurtherCondition; private PieceCellOccupyBlocker baseBlocker; public PossibleMovesProvider(int maxSteps, MoveBaseCondition baseCondition, PieceMoveFurtherCondition moveFurtherCondition, PieceCellOccupyBlocker baseBlocker) { this.maxSteps = maxSteps; this.baseCondition = baseCondition; this.MoveFurtherCondition = moveFurtherCondition; this.baseBlocker = baseBlocker; } /** * Public method which actually gives all possible cells which can be reached via current type of move. */ public List<Cell> possibleMoves(Piece piece, Board inBoard, List<PieceCellOccupyBlocker> additionalBlockers, Player player) { //if (baseCondition.isBaseConditionFullfilled(piece)) //{ // return possibleMovesAsPerCurrentType(piece, inBoard, additionalBlockers, player); //} return null; } /** * Abstract method which needs to be implemented by each type of move to give possible moves as per their behaviour. */ protected abstract List<Cell> possibleMovesAsPerCurrentType(Piece piece, Board board, List<PieceCellOccupyBlocker> additionalBlockers, Player player); /** * Helper method used by all the sub types to create the list of cells which can be reached. */ protected List<Cell> findAllNextMoves(Piece piece, NextCellProvider nextCellProvider, Board board, List<PieceCellOccupyBlocker> cellOccupyBlockers, Player player) { List<Cell> result = new List<Cell>(); //Cell nextCell = nextCellProvider.nextCell(piece.getCurrentCell()); //int numSteps = 1; //while (nextCell != null && numSteps <= maxSteps) //{ // if (checkIfCellCanBeOccupied(piece, nextCell, board, cellOccupyBlockers, player)) // { // result.add(nextCell); // } // if (!moveFurtherCondition.canPieceMoveFurtherFromCell(piece, nextCell, board)) // { // break; // } // nextCell = nextCellProvider.nextCell(nextCell); // numSteps++; //} return result; } /** * Helper method which checks if a given cell can be occupied by the piece or not. It makes use of list of * {@link PieceCellOccupyBlocker}s passed to it while checking. Also each move has one base blocker which it should * also check. */ private bool checkIfCellCanBeOccupied(Piece piece, Cell cell, Board board, List<PieceCellOccupyBlocker> additionalBlockers, Player player) { //if (baseBlocker != null && baseBlocker.isCellNonOccupiableForPiece(cell, piece, board, player)) //{ // return false; //} //for (PieceCellOccupyBlocker cellOccupyBlocker : additionalBlockers) //{ // if (cellOccupyBlocker.isCellNonOccupiableForPiece(cell, piece, board, player)) // { // return false; // } //} return true; } } public class PieceMoveFurtherCondition { } public class PossibleMovesProviderDiagonal : PossibleMovesProvider { public PossibleMovesProviderDiagonal(int maxSteps, MoveBaseCondition baseCondition, PieceMoveFurtherCondition moveFurtherCondition, PieceCellOccupyBlocker baseBlocker) : base(maxSteps, baseCondition, moveFurtherCondition, baseBlocker) { } protected override List<Cell> possibleMovesAsPerCurrentType(Piece piece, Board board, List<PieceCellOccupyBlocker> additionalBlockers, Player player) { return null; } } public class PossibleMovesProviderHorizontal : PossibleMovesProvider { public PossibleMovesProviderHorizontal(int maxSteps, MoveBaseCondition baseCondition, PieceMoveFurtherCondition moveFurtherCondition, PieceCellOccupyBlocker baseBlocker) :base(maxSteps, baseCondition, moveFurtherCondition, baseBlocker) { } protected override List<Cell> possibleMovesAsPerCurrentType(Piece piece, Board board, List<PieceCellOccupyBlocker> additionalBlockers, Player player) { List<Cell> result = new List<Cell>(); //result.addAll(findAllNextMoves(piece, board::getLeftCell, board, additionalBlockers, player)); //result.addAll(findAllNextMoves(piece, board::getRightCell, board, additionalBlockers, player)); return result; } } public class PossibleMovesProviderVertical : PossibleMovesProvider { private VerticalMoveDirection verticalMoveDirection; public PossibleMovesProviderVertical(int maxSteps, MoveBaseCondition baseCondition, PieceMoveFurtherCondition moveFurtherCondition, PieceCellOccupyBlocker baseBlocker, VerticalMoveDirection verticalMoveDirection) : base(maxSteps, baseCondition, moveFurtherCondition, baseBlocker) { this.verticalMoveDirection = verticalMoveDirection; } protected override List<Cell> possibleMovesAsPerCurrentType(Piece piece, Board board, List<PieceCellOccupyBlocker> additionalBlockers, Player player) { List<Cell> result = new List<Cell>(); //if (this.verticalMoveDirection == UP || this.verticalMoveDirection == BOTH) //{ // result.addAll(findAllNextMoves(piece, board::getUpCell, board, additionalBlockers, player)); //} //if (this.verticalMoveDirection == DOWN || this.verticalMoveDirection == BOTH) //{ // result.addAll(findAllNextMoves(piece, board::getDownCell, board, additionalBlockers, player)); //} return result; } } public enum VerticalMoveDirection { UP, DOWN, BOTH } public class PieceNotFoundException : Exception { } public class InvalidMoveException : Exception { } /** * It provides the base condition for a piece to make a move.The piece would only be allowed to move from its current * position if the condition fulfills. */ public interface MoveBaseCondition { bool isBaseConditionFullfilled(Piece piece); } /** * This condition allows a move only if cell is making a move from its initial position. That is first move ever. */ public class MoveBaseConditionFirstMove : MoveBaseCondition { public bool isBaseConditionFullfilled(Piece piece) { return 0 == 0; } } }
df2f684366bc01a63f6712d611c5297454fdb851
C#
romos/funcprog
/14_1/14_1/14_1/Program.cs
3.640625
4
/* * Задача 14-1 * Одеров Роман, 545 гр. */ using System; using System.Linq; namespace _14_1 { class Program { static int[] nonZeroLastDigits(int[] a) { return a.Select(x => x % 10).Where(x => x > 0).ToArray(); } static void Main(string[] args) { int[] a = { 354, 20, 9, 31 }; int[] b = { 1, 2, 3, 4, 5, 10, 11, 20, 25, 1000, 1001, 5443 }; foreach (int x in nonZeroLastDigits(a)) { Console.Write(x+" "); } Console.WriteLine(); foreach (int x in nonZeroLastDigits(b)) { Console.Write(x + " "); } Console.ReadLine(); } } }
0cc19e2bd5533db14b9956d4394127af7391c846
C#
Supernaught/UnityTest
/Assets/Attackable.cs
2.671875
3
using UnityEngine; using System.Collections; public class Attackable : MonoBehaviour { public Transform sparkParticle, dieParticle; public int hp; public bool isFlash; public float flashCounter; // Use this for initialization public virtual void Start () { } // Update is called once per frame public virtual void Update () { UpdateFlash (); } void UpdateFlash(){ if (isFlash) { flashCounter += Time.deltaTime; if(flashCounter > 0.08f){ isFlash = false; flashCounter = 0; } } if (isFlash) { // flash sprite GetComponent<SpriteRenderer> ().color = Color.red; } else { // normal GetComponent<SpriteRenderer>( ).color = Color.white; } } public virtual void OnTriggerEnter2D(Collider2D col){ if(col.gameObject.tag == "playerbullet") BulletHit (col); } // hit by player melee or ranged public virtual void BulletHit(Collider2D col){ Bullet bullet = col.gameObject.GetComponent<Bullet> (); if (bullet != null) { // take damage Hit (bullet.damage); // instantiate particle if(sparkParticle != null) Instantiate (sparkParticle, transform.position, Quaternion.identity); // destroy bullet Destroy (bullet.gameObject); } } public virtual void Hit(int damage){ hp -= damage; if (hp <= 0) { Die (); } isFlash = true; } public virtual void Die(){ if (dieParticle != null) { Instantiate (dieParticle, transform.position, Quaternion.identity); Debug.Log ("enemy die"); } Destroy (this.gameObject); } }
2d91ba993ad06d8f728865e2e80991223e1c96d1
C#
swipswaps/UnityFx.Async
/src/UnityFx.Async.Tests/Tests/UnwrapTests.cs
2.6875
3
// Copyright (c) Alexander Bogarsukov. // Licensed under the MIT license. See the LICENSE.md file in the project root for more information. using System; using System.Threading; using System.Threading.Tasks; using Xunit; namespace UnityFx.Async { public class UnwrapTests { [Fact] public async Task Unwrap_SucceedsIfBothOperationsSucceed() { // Arrange var op1 = AsyncResult.Delay(1); var op2 = AsyncResult.FromResult(op1); // Act var op = op2.Unwrap(); await op; // Assert Assert.True(op.IsCompletedSuccessfully); Assert.True(op1.IsCompleted); Assert.True(op2.IsCompleted); } [Fact] public async Task Unwrap_FailsIfInnerOperationFails() { // Arrange var expectedException = new Exception(); var actualException = default(Exception); var op1 = AsyncResult.FromException(expectedException); var op2 = AsyncResult.FromResult(op1); var op = op2.Unwrap(); // Act try { await op; } catch (Exception e) { actualException = e; } // Assert Assert.True(op.IsFaulted); Assert.Equal(expectedException, actualException); } [Fact] public async Task Unwrap_FailsIfOuterOperationFails() { // Arrange var actualException = default(Exception); var op1 = AsyncResult.FromCanceled<AsyncResult>(); var op = op1.Unwrap(); // Act try { await op; } catch (OperationCanceledException e) { actualException = e; } // Assert Assert.True(op.IsCanceled); Assert.NotNull(actualException); } [Fact] public async Task Unwrap_ReturnsInnerResult() { // Arrange var op1 = AsyncResult.FromResult(1); var op2 = AsyncResult.FromResult(op1); // Act var op = op2.Unwrap(); await op; // Assert Assert.True(op.IsCompletedSuccessfully); Assert.Equal(1, op.Result); } } }
7902fe77fb7189a849d5f7287d68bbf7b7b7424c
C#
harishkmr2006/Harish
/Operational routines/XMLUtil.cs
2.5625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml; namespace BOPO.NUnit.ParallelTests { public class XMLUtil { public string readXmlData_SignleNode(string Node) { try { new SetUp(); string xmlfilepath = System.Environment.GetEnvironmentVariable("ProjectWorkingDirectory")+ "BOPO.NUnit.ParallelTests\\BOPO.NUnit.ParallelTests\\XMLFileData.xml"; XmlDocument doc = new XmlDocument(); doc.Load(xmlfilepath); string Value = doc.DocumentElement.SelectSingleNode(Node).InnerText; return Value; } catch (Exception ex) { Console.WriteLine(ex.Message); return ""; } } public void WriteXmlData_SingleNode(string Node,string value) { try { new SetUp(); string xmlfilepath = System.Environment.GetEnvironmentVariable("ProjectWorkingDirectory")+ "BOPO.NUnit.ParallelTests\\BOPO.NUnit.ParallelTests\\XMLFileData.xml"; XmlDocument doc = new XmlDocument(); doc.Load(xmlfilepath); doc.DocumentElement.SelectSingleNode(Node).InnerText = value; doc.Save(xmlfilepath); } catch (Exception ex) { Console.WriteLine(ex.Message); } } } }
3c37a0f5e96958ecd7105be354bf314c63920788
C#
logisketchUCSD/Old_6
/Old Recognizers/ClassifyWGL.cs
3.578125
4
using System; using System.Collections.Generic; using System.Text; namespace Svm { /// <summary> /// Class to classify Wires, Gates, and Labels /// </summary> public class ClassifyWGL : ClassifySVM { /// <summary> /// Constructor /// </summary> /// <param name="modelFile"></param> public ClassifyWGL(string modelFile) : base(modelFile) { } /// <summary> /// Get the type associated with the prediction /// </summary> /// <param name="predict"></param> /// <returns></returns> public override string predictToString(int predict) { switch (predict) { case 1: return "Wire"; case 2: return "Gate"; case 3: return "Label"; case 4: return "Nonwire"; case 5: return "Nongate"; case 6: return "Nonlabel"; default: return "Unknown"; } } /// <summary> /// Gets the color associated with a label for visual purposes /// </summary> /// <param name="label">Type to match</param> /// <returns>Color that matches the label</returns> public static System.Drawing.Color labelToColor(string label) { switch (label) { case "Wire": return System.Drawing.Color.Blue; case "Gate": return System.Drawing.Color.Red; case "Label": return System.Drawing.Color.Orange; case "Nonwire": return System.Drawing.Color.Purple; case "Nongate": return System.Drawing.Color.Green; case "Nonlabel": return System.Drawing.Color.Indigo; default: return System.Drawing.Color.Black; } } } }
4ef5dc68ce01a725f92737da0487047f5c8a2566
C#
chrisgeeraedts/Icarus
/Icarus.Logic.Shared/Managers/EnemyManager.cs
2.65625
3
using System.Collections.Generic; using Icarus.Logic.Support.Enums; namespace Icarus.Logic.Shared.Managers { public class EnemyManager : IManager { private readonly IGameWorldManager _gameWorldManager; public List<IEnemyInstance> Enemies { get; set; } public IEnemyInstance ActiveEnemyInstance { get; set; } public EnemyManager(IGameWorldManager gameWorldManager) { _gameWorldManager= gameWorldManager; } public void Reset() { Enemies = new List<IEnemyInstance>(); } public void DoDamage(int damage, IEnemyInstance enemyInstance) { ActiveEnemyInstance = enemyInstance; //TODO calculate actual damage var actualDamage = damage; _gameWorldManager.HeroManager.MetaInformation[MetaInformation.TimesPlayerGotAttacked] += 1; _gameWorldManager.HeroManager.MetaInformation[MetaInformation.TimesPlayerGotAttackedThisTurn] += 1; // Handle potential skills that do something with attacks against the player _gameWorldManager.GameTurnManager.ActivateActiveSkillCardsThisTurn(ActiveSkillTrigger.OnBeingAttacked); _gameWorldManager.HeroManager.TakeDamage(actualDamage); } } }
a787855352cad943129bdad7c6231ba6749010de
C#
daveaglick/NiceThreads
/NiceThreads/DisposableLock.cs
2.765625
3
/* * Copyright 2012 WildCard, LLC * * 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.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; namespace NiceThreads { /// <summary> /// Base class for Locker wrappers that implements the disposable pattern. /// </summary> public abstract class DisposableLock : IDisposable { private readonly Locker _locker; private bool _disposed = false; #if DEBUG private static readonly DisposableLockList WaitingLocks = new DisposableLockList(); private static readonly DisposableLockList HeldLocks = new DisposableLockList(); private LinkedListNode<DisposableLock> _node; private DateTime? _requested = null; private DateTime? _acquired = null; private StackTrace _stackTrace = null; private int? _threadId = null; internal int? ThreadId { get { return _threadId; } } internal StackTrace StackTrace { get { return _stackTrace; } } internal DateTime? Acquired { get { return _acquired; } } internal DateTime? Requested { get { return _requested; } } private void Waiting() { if (!Globals.EnableLogging) return; _stackTrace = new StackTrace(2, true); _threadId = Thread.CurrentThread.ManagedThreadId; _requested = DateTime.UtcNow; _node = WaitingLocks.AddLock(this); } private void Held() { if (!Globals.EnableLogging) return; WaitingLocks.RemoveLock(_node); _acquired = DateTime.UtcNow; _node = HeldLocks.AddLock(this); } /// <summary> /// Appends the log information (if logging is enabled) to the StringBuilder. /// </summary> /// <param name="builder">The builder to append log information to.</param> public static void AppendLog(StringBuilder builder) { if (!Globals.EnableLogging) return; builder.AppendLine("Waiting"); builder.AppendLine("-------"); WaitingLocks.AppendLog(builder); builder.AppendLine("Held"); builder.AppendLine("-------"); HeldLocks.AppendLog(builder); } /// <summary> /// Outputs log information (if logging is enabled). /// </summary> public static string Log() { StringBuilder builder = new StringBuilder(); AppendLog(builder); return builder.ToString(); } #endif /// <summary> /// Initializes a new instance. /// </summary> /// <param name="locker">The locker.</param> /// <param name="timeout">The timeout.</param> protected DisposableLock(Locker locker, TimeSpan timeout) { _locker = locker; #if DEBUG Waiting(); #endif try { EnterLock(timeout); } catch (Exception) { #if DEBUG if(_node != null) WaitingLocks.RemoveLock(_node); #endif throw; } #if DEBUG Held(); #endif } /// <summary> /// Initializes a new instance. /// </summary> /// <param name="locker">The locker.</param> protected DisposableLock(Locker locker) { _locker = locker; #if DEBUG Waiting(); if(Globals.Timeout.HasValue) { try { EnterLock(Globals.Timeout.Value); } catch (Exception) { #if DEBUG if(_node != null) WaitingLocks.RemoveLock(_node); #endif throw; } Held(); return; } #endif EnterLock(); #if DEBUG Held(); #endif } /// <summary> /// Gets the Locker that this lock wraps. /// </summary> public Locker Locker { get { return _locker; } } /// <summary> /// Unlocks the Locker. /// </summary> public void Dispose() { if (_disposed) return; #if DEBUG if(_node != null) HeldLocks.RemoveLock(_node); #endif ExitLock(); _disposed = true; } protected abstract void EnterLock(); protected abstract void EnterLock(TimeSpan timeout); protected abstract void ExitLock(); } }
bce67af33fa90d262f66e4e1b1d907423d22aafc
C#
praveenpX/data-structures
/numberswithoddfrequency.cs
3.78125
4
using System; using System.Collections.Generic; public class Program { public static void Main() { int[] arr = new int[]{2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2}; getOddOccurrence(arr); } public static void getOddOccurrence(int[] arr) { int length = arr.Length; Dictionary<int, int> keyfreqmap = new Dictionary<int, int>(); for (int i = 0; i < length - 1; i++) { if (!keyfreqmap.ContainsKey(arr[i])) { keyfreqmap.Add(arr[i], 1); //add it to dictionary } else { int count = keyfreqmap[arr[i]]; keyfreqmap[arr[i]] = count + 1; } } Console.Write("numbers with odd frequency: "); foreach (var kvp in keyfreqmap) { if (kvp.Value % 2 != 0) { Console.Write(kvp.Key + " "); } } } }
52ff85ec52da1cde393961e080b524c526d7af2a
C#
myclr08/SOLID-rnek-al-ma
/SolidPrinciples/DIP/BadPractice/MusteriServis.cs
2.9375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SolidPrinciples.DIP.BadPractice { //Musteri bilgilendirilmek ister //SMS, Email ürünler ile ilgili. public class MusteriServis { //Bir sınıfın içerisinde başka bir sınıfın instance direkt alamayız. bu durumda 1 tek sorumluluk ilkesine ters ve depedency inversion a ters. EmailServis email = new EmailServis(); public void MusteriKayıt() { //müşteri sisteme kaydolduktan sonra email atmamız lazım email.MesajAt("asdasda@gmail.com", "asdasd"); } public object MusteriAra(string name) { return null; } } }
5edbda0c41a23406de57f06bfeea6c5508621cd7
C#
IntelliTect-Samples/SpokaneNETUserGroupSamples
/2020.02.12-UnitTesting/UnitTestingExamples/Example7.cs
2.953125
3
using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq.AutoMock; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace UnitTestingExamples { [TestClass] public class Example7 { #region SUT public interface ILineSource { event EventHandler<string> ErrorOccured; IEnumerable<string> GetLines(); } public interface IAsyncLogger { Task LogAsync(string message); } public class CsvParser { private ILineSource LineSource { get; } public IAsyncLogger Logger { get; } public CsvParser(ILineSource lineSource, IAsyncLogger logger) { LineSource = lineSource ?? throw new ArgumentNullException(nameof(lineSource)); Logger = logger ?? throw new ArgumentNullException(nameof(logger)); LineSource.ErrorOccured += LineSource_ErrorOccured; } private async void LineSource_ErrorOccured(object sender, string message) { await Logger.LogAsync(message); } public IEnumerable<string[]> Parse() { foreach (string line in LineSource.GetLines()) { yield return ParseLine(line); } } private static string[] ParseLine(string line) { return line.Split(','); } } #endregion SUT #region Tests #region Simulator public class LineSourceSimulator : ILineSource { public LineSourceSimulator(string[] lines) { Lines = lines; } public string ErrorMessage { get; private set; } public string[] Lines { get; } public event EventHandler<string> ErrorOccured; public void WithError(string message) { ErrorMessage = message; } public IEnumerable<string> GetLines() { if (!string.IsNullOrEmpty(ErrorMessage)) { ErrorOccured?.Invoke(this, ErrorMessage); return Enumerable.Empty<string>(); } return Lines; } } #endregion Simulator public TestContext TestContext { get; set; } [TestMethod] public void WhenErrorOccursItIsLogged() { // Arrange var mocker = new AutoMocker(); var lineSource = new LineSourceSimulator(null); lineSource.WithError("Crash"); mocker.Use<ILineSource>(lineSource); //Force the async call to complete synchronously mocker .Setup<IAsyncLogger, Task>(x => x.LogAsync("Crash")) .Returns(Task.CompletedTask); var parser = mocker.CreateInstance<CsvParser>(); // Act var rows = parser.Parse().ToArray(); // Assert Assert.AreEqual(0, rows.Length); mocker.VerifyAll(); } #endregion Tests } }
3645377d07607e4958ee6d63b47535507774d97a
C#
rashadulrakib/Online-Exam-tool
/Entity/CandidateForExam.cs
2.875
3
using System; using System.Collections.Generic; using System.Text; namespace Entity { /// <summary> /// This is CandidateForExam entity class. /// It defines, which candidate is apeared for which exam /// </summary> [Serializable] public class CandidateForExam { public CandidateForExam() { Initialization(); } private Candidate oCandite; public Candidate CandidateForExamCandidate { get { return oCandite; } set { oCandite = value; } } private CandidateExam oCandidateExam; public CandidateExam CadidateCandidateExam { get { return oCandidateExam; } set { oCandidateExam = value; } } private void Initialization() { this.oCandite = new Candidate(); this.oCandidateExam = new CandidateExam(); } } }
d45dbb051998b5694310a1fa42657b626327d563
C#
Pathoschild/smapi-mod-dump
/source/What Are You Missing/PublicStardewMods/WhatAreYouMissing/LocationDisplayNames.cs
2.71875
3
/************************************************* ** ** You're viewing a file in the SMAPI mod dump, which contains a copy of every open-source SMAPI mod ** for queries and analysis. ** ** This is *not* the original file, and not necessarily the latest version. ** Source repository: https://github.com/LukeSeewald/PublicStardewValleyMods ** *************************************************/ using System.Collections.Generic; namespace WhatAreYouMissing { public class LocationDisplayNames { //<gameName<areaCode, locationDisplayName>> private Dictionary<string, Dictionary<int,string[]>> PossibleLocationDisplayNames; public LocationDisplayNames() { PossibleLocationDisplayNames = new Dictionary<string, Dictionary<int, string[]>>(); AddDisplayNames(); } public string[] GetLocationDisplayNames(string gameName, int areaCode) { if (PossibleLocationDisplayNames.ContainsKey(gameName)) { Dictionary<int, string[]> displayNames = PossibleLocationDisplayNames[gameName]; if (displayNames.ContainsKey(areaCode)) { return displayNames[areaCode]; } } if (Utilities.IsTempOrFishingGameOrBackwoodsLocation(gameName)) { return new string[1] { "" }; } if(areaCode == -1) { //Its availble everywhere in this area return new string[1] { gameName }; } else { return new string[1] { gameName + " " + Utilities.GetTranslation("AREA") + " " + areaCode }; } } private void AddDisplayNames() { AddName(Constants.GAME_NAME_SECRET_WOODS, Constants.DEFAULT_AREA_CODE, Utilities.GetTranslation("SECRET_WOODS_DISPLAY_NAME")); AddName(Constants.GAME_NAME_TOWN_RIVER, Constants.DEFAULT_AREA_CODE, Utilities.GetTranslation("TOWN_RIVER_DISPLAY_NAME")); AddName(Constants.GAME_NAME_MOUNTAIN_LAKE, Constants.DEFAULT_AREA_CODE, Utilities.GetTranslation("MOUNTAIN_LAKE_DISPLAY_NAME")); AddName(Constants.GAME_NAME_BEACH, Constants.DEFAULT_AREA_CODE, Utilities.GetTranslation("BEACH_DISPLAY_NAME")); AddName(Constants.GAME_NAME_SEWER, Constants.DEFAULT_AREA_CODE, Utilities.GetTranslation("SEWER_DISPLAY_NAME")); AddName(Constants.GAME_NAME_MUTANT_BUG_LAIR, Constants.DEFAULT_AREA_CODE, Utilities.GetTranslation("MUTANT_BUG_LAIR_DISPLAY_NAME")); AddName(Constants.GAME_NAME_MINES, Constants.DEFAULT_AREA_CODE, Utilities.GetTranslation("MINES_DISPLAY_NAME")); AddName(Constants.GAME_NAME_DESERT, Constants.DEFAULT_AREA_CODE, Utilities.GetTranslation("DESERT_DISPLAY_NAME")); AddName(Constants.GAME_NAME_WITCHS_SWAMP, Constants.DEFAULT_AREA_CODE, Utilities.GetTranslation("WITCHS_SWAMP_DISPLAY_NAME")); AddName(Constants.GAME_NAME_GINGER_ISLAND_N, Constants.DEFAULT_AREA_CODE, Utilities.GetTranslation("GINGER_ISLAND_N")); AddName(Constants.GAME_NAME_GINGER_ISLAND_S, Constants.DEFAULT_AREA_CODE, Utilities.GetTranslation("GINGER_ISLAND_S")); AddName(Constants.GAME_NAME_GINGER_ISLAND_SE, Constants.DEFAULT_AREA_CODE, Utilities.GetTranslation("GINGER_ISLAND_SE")); AddName(Constants.GAME_NAME_GINGER_ISLAND_SE_CAVE, Constants.DEFAULT_AREA_CODE, Utilities.GetTranslation("GINGER_ISLAND_SE_CAVE")); AddName(Constants.GAME_NAME_GINGER_ISLAND_SECRET, Constants.DEFAULT_AREA_CODE, Utilities.GetTranslation("GINGER_ISLAND_SECRET")); AddName(Constants.GAME_NAME_GINGER_ISLAND_N_CAVE, Constants.DEFAULT_AREA_CODE, Utilities.GetTranslation("GINGER_ISLAND_N_CAVE")); AddCindersapForestNames(); AddGingerIslandWestNames(); } private void AddName(string gameName, int areaCode, string displayName) { PossibleLocationDisplayNames.Add(gameName, new Dictionary<int, string[]> { [areaCode] = new string[1] { displayName } }); } private void AddGingerIslandWestNames() { Dictionary<int, string[]> gingerIslandWest = new Dictionary<int, string[]> { [Constants.GINGER_ILSAND_WEST_OCEAN_CODE] = new string[1] { Utilities.GetTranslation("GINGER_ISLAND_W_OCEAN") }, [Constants.GINGER_ISLAND_WEST_FRESHWATER_CODE] = new string[1] { Utilities.GetTranslation("GINGER_ISLAND_W_FRESHWATER") }, }; PossibleLocationDisplayNames.Add(Constants.GAME_NAME_GINGER_ISLAND_W, gingerIslandWest); } private void AddCindersapForestNames() { string[] pondAndRiver = new string[2] { Utilities.GetTranslation("CINDERSAP_POND_DISPLAY_NAME"), Utilities.GetTranslation("CINDERSAP_RIVER_DISPLAY_NAME")}; Dictionary<int, string[]> cindersapDict = new Dictionary<int, string[]> { [Constants.DEFAULT_AREA_CODE] = pondAndRiver, [Constants.CINDERSAP_POND_AREA_CODE] = new string[1] { Utilities.GetTranslation("CINDERSAP_POND_DISPLAY_NAME")}, [Constants.CINDERSAP_RIVER_AREA_CODE] = new string[1] { Utilities.GetTranslation("CINDERSAP_RIVER_DISPLAY_NAME")}, }; PossibleLocationDisplayNames.Add(Constants.GAME_NAME_CINDERSAP_FOREST, cindersapDict); } } }
9fcce5e70efab40e03e4f96d38b704ebc934bc8d
C#
jbautistam/ChessDataBase
/Libraries/LibChessGame.ViewModels/Pgn/PgnLibraryViewModel.cs
2.796875
3
using System; using System.Collections.ObjectModel; using System.Threading.Tasks; using Bau.Libraries.BauMvvm.ViewModels; using Bau.Libraries.LibChessGame.Models.Games; namespace Bau.Libraries.LibChessGame.ViewModels.Pgn { /// <summary> /// ViewModel para un <see cref="LibraryModel"/> /// </summary> public class PgnLibraryViewModel : BaseObservableObject { // Variables privadas private string _fileName; private PgnGameInfoViewModel _selectedGame; public PgnLibraryViewModel(Board.GameBoardViewModel gameBoardViewModel) { GameBoardViewModel = gameBoardViewModel; Init(); NextGameCommand = new BaseCommand(_ => GoGame(true), _ => CanGoGame(true)) .AddListener(this, FileName); PreviousGameCommand = new BaseCommand(_ => GoGame(false), _ => CanGoGame(false)) .AddListener(this, FileName); } /// <summary> /// Inicializa el ViewModel /// </summary> public void Init() { ConvertToViewModel(new LibraryModel()); } /// <summary> /// Carga un archivo /// </summary> public async Task<(bool loaded, string error)> LoadAsync(string fileName) { string error = string.Empty; // Inicializa el juego Library = new LibraryModel(); // Carga el juego if (!string.IsNullOrEmpty(fileName)) { // Carga el juego try { // Carga el juego Library = LoadLibrary(fileName); // Asigna el nombre de archivo FullFileName = fileName; FileName = System.IO.Path.GetFileName(fileName); } catch (Exception exception) { error = $"Error al cargar el juego: {exception.Message}"; } } else error = $"No existe el archivo: {fileName}"; // y lo muestra (lo hace fuera del try porque debe crear el modelo vacío) ConvertToViewModel(Library); // Devuelve el valor que indica si los datos son correctos return (string.IsNullOrEmpty(error), error); } /// <summary> /// Carga la librería de un archivo PGN /// </summary> private LibraryModel LoadLibrary(string fileName) { LibPgnReader.Models.LibraryPgnModel libraryPgn = new LibPgnReader.GamePgnParser().Read(fileName); // Convierte los datos del archivo PGN return new LibPgn.Conversor.GamePgnConversor().Convert(libraryPgn); } /// <summary> /// Convierte la librería en ViewModels /// </summary> private void ConvertToViewModel(LibraryModel library) { // Asigna el archivo Library = library; // Limpia la lista Games.Clear(); // Carga los juegos foreach (GameModel game in library.Games) Games.Add(new PgnGameInfoViewModel(this, game)); // Selecciona un elemento if (Games.Count > 0) SelectedGame = Games[0]; else SelectedGame = new PgnGameInfoViewModel(this, new GameModel()); } /// <summary> /// Modifica el juego seleccionado /// </summary> private void UpdateSelectedGame() { GameBoardViewModel.LoadMovements(SelectedGame?.Game); } /// <summary> /// Pasa a la partida siguiente o anterior /// </summary> private void GoGame(bool next) { if (next) SelectedGame = Games[SelectedGameIndex + 1]; else SelectedGame = Games[SelectedGameIndex - 1]; } /// <summary> /// Indica si puede ir a la partida siguiente o anterior /// </summary> private bool CanGoGame(bool next) { return SelectedGameIndex != -1 && ((next && SelectedGameIndex < Games.Count - 1) || (!next && SelectedGameIndex > 0)); } /// <summary> /// ViewModel del tablero /// </summary> public Board.GameBoardViewModel GameBoardViewModel { get; } /// <summary> /// Datos del archivo /// </summary> public LibraryModel Library { get; private set; } /// <summary> /// Nombre del archivo /// </summary> public string FullFileName { get; private set; } /// <summary> /// Nombre del archivo abierto /// </summary> public string FileName { get { return _fileName; } set { CheckProperty(ref _fileName, value); } } /// <summary> /// Partidas /// </summary> public ObservableCollection<PgnGameInfoViewModel> Games { get; } = new ObservableCollection<PgnGameInfoViewModel>(); /// <summary> /// Partida seleccionada /// </summary> public PgnGameInfoViewModel SelectedGame { get { return _selectedGame; } set { if (CheckObject(ref _selectedGame, value)) UpdateSelectedGame(); } } /// <summary> /// Indice de la partida seleccionada /// </summary> public int SelectedGameIndex { get { if (Games == null || Games.Count == 0 || SelectedGame == null) return -1; else return Games.IndexOf(SelectedGame); } } /// <summary> /// Comando para cargar la partida anterior /// </summary> public BaseCommand PreviousGameCommand { get; } /// <summary> /// Comando para cargar la siguiente partida /// </summary> public BaseCommand NextGameCommand { get; } } }
0e80d43a6d5f1f427cde322ef9b177625042c7ae
C#
MaximeCrp/C17-Developer
/C17e_BotFactory/BotFactory/Factories/UnitFactory.cs
2.6875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using BotFactory.Interfaces; using BotFactory.Common.Tools; using BotFactory.Models; using System.Threading; namespace BotFactory.Factories { public class UnitFactory : IUnitFactory { public Queue<IFactoryQueueElement> Queue { get; set; } private int _queueCapacity; private int _storageCapacity; public TimeSpan QueueTime { get; set; } public int QueueCapacity { get { return _queueCapacity; } } public int StorageCapacity { get { return _storageCapacity; } } public int QueueFreeSlots { get { return QueueCapacity - Queue.Count; } } public int StorageFreeSlots { get { return StorageCapacity - Storage.Count; } } public List<ITestingUnit> Storage { get; set; } public UnitFactory(int qcapa, int storcapa) { _queueCapacity = qcapa; _storageCapacity = storcapa; Queue = new Queue<IFactoryQueueElement>(); Storage = new List<ITestingUnit>(); } public bool AddWorkableUnitToQueue(Type model, string name, Coordinates workingPos, Coordinates parkingPos) { if (IsAddingPossible()) { IFactoryQueueElement unity_in = new FactoryQueueElement(model, name, workingPos, parkingPos); WorkingUnit EnqueuedUnit = Activator.CreateInstance((unity_in.Model), new object[] { unity_in.Name }) as WorkingUnit; TimeSpan TimeToCreate = TimeSpan.FromSeconds(EnqueuedUnit.BuildTime); Queue.Enqueue(unity_in); QueueTime += TimeToCreate; FactoryProgressEventArgs args_unity_in = new FactoryProgressEventArgs(); args_unity_in.returnUnit = unity_in; FactoryProgress(this, args_unity_in); startFactory(); return true; } return false; } public void AddStorage(ITestingUnit BuiltUnity) { Storage.Add(BuiltUnity); } private bool IsAddingPossible() { if (Queue.Count < QueueCapacity && Storage.Count + Queue.Count<StorageCapacity) { return true; } return false; } private bool IsFactoryBuildingFlag = false; public async Task<bool> BuildWorkableUnit() { IFactoryQueueElement unity_out = Queue.Peek(); WorkingUnit BuildingUnit = Activator.CreateInstance((unity_out.Model), new object[] { unity_out.Name }) as WorkingUnit; TimeSpan TimeToCreate = TimeSpan.FromSeconds(BuildingUnit.BuildTime); await Task.Delay(TimeToCreate); Queue.Dequeue(); QueueTime -= TimeToCreate; AddStorage(BuildingUnit); FactoryProgressEventArgs args_unity_out = new FactoryProgressEventArgs(); args_unity_out.returnUnit = unity_out; FactoryProgress(this, args_unity_out); return true; } public event FactoryProgressDelegate FactoryProgress; private void startFactory() { if(IsFactoryBuildingFlag) { return; } else { Task.Run(async () => { await startBuilding(); }); } } private async Task startBuilding() { IsFactoryBuildingFlag = true; while (Queue.Count != 0 && StorageFreeSlots>0) { bool builded = await BuildWorkableUnit(); } IsFactoryBuildingFlag = false; } } }
c17c6903d016bff5b69a81cf594fa4aee7c431d5
C#
ZilvinasTomkevicius/NoStarve4UApp_rep
/NoStarve4U/NoStarve4U/APITesting/UnitTestAsyncRecipeSerivices.cs
2.578125
3
using ClientServices; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using BusinessServices; using BusinessEntities; namespace APITesting { [TestClass] public class UnitTestAsyncRecipeSerivices { private AsyncRecipeServices reServices = new AsyncRecipeServices(); [TestMethod] public async Task Test_AddRecipe() { RecipeEntity recipe = new RecipeEntity(); recipe.Name = "hahahhaa"; recipe.Description = "pasijuokt garsiai"; recipe.CookingTime = 3; await reServices.AddRecipeAsync(recipe); //TODO: Add asserts! } [TestMethod] public async Task Test_UpdateRecipe() { RecipeEntity recipe = new RecipeEntity(); recipe.ID = 38; recipe.Name = "boboboboo"; recipe.Description = "paliudet"; recipe.CookingTime = 50; await reServices.UpdateRecipeAsync(recipe); //TODO: Add asserts! } [TestMethod] public async Task Test_DeleteRecipe() { int recipeID = 38; await reServices.DeleteRecipeAsync(recipeID); } [TestMethod] public async Task Test_GetRecipe() { RecipeEntity recipe = new RecipeEntity(); recipe.ID = 1; recipe.Name = "Sumuðtinis su sûriu"; recipe.Description = "Ant duonos uþtepti sviesto ir uþdëti sûrio."; recipe.CookingTime = 3; RecipeEntity recipe2 = await reServices.GetRecipeAsync("api/recipe/get?recipeID=1"); Assert.AreEqual(recipe.ID, recipe2.ID); Assert.AreEqual(recipe.Name, recipe2.Name); Assert.AreEqual(recipe.Description, recipe2.Description); Assert.AreEqual(recipe.CookingTime, recipe2.CookingTime); } [TestMethod] public async Task Test_GetRecipeList() { List<RecipeEntity> recipeList = new List<RecipeEntity>(); recipeList = await reServices.GetRecipeListAsync("api/recipe/getList"); //TODO: Add asserts! } } }
c3daa0518a297f44f993756331ecda86ff4c8cf6
C#
nkarg/rcadenasedu.net
/Back End/Pokedex Edu/InformatorioPokedexNextGen/InformatorioPokedex.Data/Pokemon.cs
2.75
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace InformatorioPokedex.Data { public class Pokemon: IBug, IDark, IDragon, IElectric, IFairy, IFighting, IFire, IFlying, IGhost, IGrass, IGround, IIce, INormal, IPoison, IPsychical, IRock, ISteel, IWater { public string nombre { get; set; } public PokemonName name { get; set; } public string tipo { get; set; } public string alias { get; set; } public float peso { get; set; } public float altura { get; set; } public Pokemon(string var_nombre,string var_tipo, string var_alias, float var_peso, float var_altura) { nombre = var_nombre; tipo = var_tipo; alias = var_alias; peso = var_peso; altura = var_altura; } public Pokemon(PokemonName var_name, string var_tipo, string var_alias, float var_peso, float var_altura) { name = var_name; tipo = var_tipo; alias = var_alias; peso = var_peso; altura = var_altura; } public string placaje() { return "pokemon ha usado PLACAJE!! ha restado 15 ps al enemigo"; } public string gruñido() { return "pokemon ha usado GRUÑIDO!! resistencia del enemigo ha bajado"; } public string descripcion(string name) { if (name == "Charmander") { return "La llama que tiene en la punta de la cola arde según sus sentimientos.\nLlamea levemente cuando está alegre y arde vigorosamente cuando está enfadado."; } else if(name == "Squirtle") { return "El caparazón de Squirtle no le sirve de protección únicamente. \nSu forma redondeada y las hendiduras que tiene le ayudan a deslizarse en el agua y le permiten nadar a gran velocidad."; } else { return "A Bulbasaur es fácil verle echándose una siesta al sol. \nLa semilla que tiene en el lomo va creciendo cada vez más a medida que absorbe los rayos del sol."; } } public void megahorn() { Console.WriteLine("Using its tough and impressive horn, the user rams into the target with no letup."); } public void hyperspaceFury() { Console.WriteLine("Hyperspace Fury deals damage but lowers the user's Defense by one stage after attacking. The move always hits, even if the target used a Protect-like move."); } public void roarOfTime() { Console.WriteLine("The user blasts the target with power that distorts even time. The user can’t move on the next turn."); } public void boltStrike() { Console.WriteLine("The user surrounds itself with a great amount of electricity and charges its target. This may also leave the target with paralysis."); } public void lightOfRuin() { Console.WriteLine("Light of Ruin deals damage, but the user receives 1⁄2 of the damage it inflicted in recoil. In other words, if the attack does 100 HP damage to the opponent, the user will lose 50 HP."); } public void focusPunch() { Console.WriteLine("The user focuses its mind before launching a punch. This move fails if the user is hit before it is used."); } public void hydroCannon() { Console.WriteLine("The target is hit with a watery blast. The user can’t move on the next turn."); } public void doomDesire() { Console.WriteLine("Two turns after this move is used, the user blasts the target with a concentrated bundle of light."); } public void vCreate() { Console.WriteLine("With a hot flame on its forehead, the user hurls itself at its target. It lowers the user’s Defense, Sp. Def, and Speed stats."); } public void skyAttack() { Console.WriteLine("A second-turn attack move where critical hits land more easily. This may also make the target flinch."); } public void shadowForce() { Console.WriteLine("The user disappears, then strikes the target on the next turn. This move hits even if the target protects itself."); } public void frenzyPlant() { Console.WriteLine("The user slams the target with an enormous tree. The user can’t move on the next turn."); } public void precipiceBlades() { Console.WriteLine("Precipice Blades deals damage and hits all adjacent opponents in double/triple battles."); } public void freezeShock() { Console.WriteLine("On the second turn, the user hits the target with electrically charged ice. This may also leave the target with paralysis."); } public void explosion() { Console.WriteLine("The user attacks everything around it by causing a tremendous explosion. The user faints upon using this move."); } public void gunkShot() { Console.WriteLine("The user shoots filthy garbage at the target to attack. This may also poison the target."); } public void psychoBoost() { Console.WriteLine("The user attacks the target at full power. The attack’s recoil harshly lowers the user’s Sp. Atk stat."); } public void headSmash() { Console.WriteLine("The user attacks the target with a hazardous, full-power headbutt. This also damages the user terribly."); } } }
20100f67ce042406e18c8c408a9287c9994cbc09
C#
Berryvr/Whatsup
/Whatsup-Her/Whatsup-Her/Models/MessageView.cs
2.53125
3
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Whatsup_Her.Models { public class MessageView { public int ChatId { get; set; } public string Message { get; set; } public string ContactName { get; set; } public string TimeSent { get; set; } public int OtherAccount { get; set; } public MessageView(int id, string message, Contact contact, DateTime TimeSent, int otherAccount) { this.ChatId = id; this.Message = message; this.ContactName = contact.Name; this.TimeSent = String.Format("{0}:{1:00} {2}/{3}/{4}", TimeSent.Hour, TimeSent.Minute, TimeSent.Day, TimeSent.Month, TimeSent.Year); this.OtherAccount = otherAccount; } public MessageView() { } } }
3582d83d5c4a18752a629710cbd6192c7d59a7f3
C#
shendongnian/download4
/first_version_download2/24802-49489466-169829552-2.cs
2.921875
3
public int myInt; public int MyInt { get { return myInt; } set { myInt = value } }
426528b0d04f1e363ec5a48728c3198e65168b19
C#
shorstok/musically-challenged-bot
/musicallychallenged/Services/Sync/TelegramPayloadExtractor.cs
2.53125
3
using System.IO; using System.Threading; using System.Threading.Tasks; using log4net; using musicallychallenged.Logging; using musicallychallenged.Services.Telegram; using Telegram.Bot.Types; using File = System.IO.File; namespace musicallychallenged.Services.Sync { public class TelegramPayloadExtractor : PayloadExtractor { private readonly ITelegramClient _telegramClient; private static readonly ILog logger = Log.Get(typeof(TelegramPayloadExtractor)); private readonly string _payloadStoragePath; public TelegramPayloadExtractor(ITelegramClient telegramClient) { _telegramClient = telegramClient; _payloadStoragePath = Path.Combine(PathService.AppData, "temp-payloads"); EnsurePayloadStoragePathExists(); } private void EnsurePayloadStoragePathExists() { if (Directory.Exists(_payloadStoragePath)) return; logger.Info($"Creating payload storage path {_payloadStoragePath}"); Directory.CreateDirectory(_payloadStoragePath); } public override Task DisposePayload(string payloadFile, CancellationToken token) { if (File.Exists(payloadFile)) File.Delete(payloadFile); else logger.Warn($"Dispose - payload not found: `{payloadFile}`"); return Task.CompletedTask; } public override async Task<string> ExtractPayloadToFile(Message container, CancellationToken cancellationToken) { if (container?.Audio == null) { logger.Warn($"No audio payload to extract from message {container?.MessageId}"); return null; } //Guess. FFMPEG wants some extension var extension = container?.Audio?.MimeType?.StartsWith("audio/")??false ? "mp3" : "mp4"; //lol var tempFilename = Path.Combine(_payloadStoragePath, $"{container?.MessageId}-{Path.GetRandomFileName()}.{extension}"); await using (var tempFileStream = File.Create(tempFilename)) { await _telegramClient.DownloadFile(container, tempFileStream, cancellationToken); } return Path.GetFullPath(tempFilename); } } }
a8a86a45364f05b2d434e393c5f273ab07304a17
C#
Kibolabs/SFCDentalGame
/SFCDentalGame/Models/DentalPractice.cs
2.75
3
using System; using System.Collections.Generic; using SFCDentalGame.DAL; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using SFCDentalGame.DAL.Entities; using System.Linq; using Microsoft.EntityFrameworkCore; namespace SFCDentalGame.Models { public class DentalPractice { public readonly SFCContext _Context; public DentalPractice(SFCContext Context) { _Context = Context; } public String DentalPracticeId{ get; set; } public List<DentalPracticeItem> PracticeItems { get; set; } public static DentalPractice GetPractice(IServiceProvider services) { ISession session = services.GetRequiredService<IHttpContextAccessor>()?.HttpContext.Session; var context = services.GetService<SFCContext>(); string practicesId = session.GetString("PracticeId") ?? Guid.NewGuid().ToString(); session.SetString("PracticeId",practicesId); return new DentalPractice(context) { DentalPracticeId = practicesId }; } public void AddToPractice(Behaviour behaviour, double score) { var practiceItem = _Context.PracticeItems.SingleOrDefault( s => s.Behaviour.BehaviourId == behaviour.BehaviourId && s.DentalPracticeId == DentalPracticeId); if(practiceItem==null){ practiceItem = new DentalPracticeItem { DentalPracticeId=DentalPracticeId, Behaviour=behaviour }; _Context.PracticeItems.Add(practiceItem); } else{ // tell them its been added already and return nothing return; } _Context.SaveChanges(); } public void RemoveFromPractice(Behaviour behaviour){ var practiceItem = _Context.PracticeItems.SingleOrDefault( s => s.Behaviour.BehaviourId == behaviour.BehaviourId && s.DentalPracticeId == DentalPracticeId); _Context.PracticeItems.Remove(practiceItem); _Context.SaveChanges(); } public List<DentalPracticeItem> GetDentalPracticeItems() { return PracticeItems ?? (PracticeItems = _Context.PracticeItems.Where(c => c.DentalPracticeId == DentalPracticeId) .Include(s => s.Behaviour) .ToList()); } public void ClearPractices() { var practiceListItems = _Context .PracticeItems .Where(prac => prac.DentalPracticeId == DentalPracticeId); _Context.PracticeItems.RemoveRange(practiceListItems); _Context.SaveChanges(); } public decimal GetTotolScore() { var total = _Context.PracticeItems.Where(c => c.DentalPracticeId == DentalPracticeId) .Select(c => c.Behaviour.Points ).Sum(); return (decimal)total; } } }
45f806fab8cbe5c70be1ac505f05c2cb75db68a3
C#
JonSnowbd/CoffeeMate
/CoffeeMate/AlternateGUI.xaml.cs
2.765625
3
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace CoffeeMate { /// <summary> /// Interaction logic for AlternateGUI.xaml /// </summary> public partial class AlternateGUI : Window { private List<string> greetings = new List<string>() { "Sit down and have a cuppa", "Enjoy your brew, just for you", "It's nice and hot", "Persistently consistent", "Niceeeee", "Grab your favorite mug", "That smells delicious", "Remember to pour high over the cup to oxidize coffee", "Dark roast or light roast?", "Strong bodied", "Start your day right" }; public AlternateGUI() { Closing += Shutdown; this.DataContext = new CoffeeViewModel(); InitializeComponent(); Random r = new Random(); this.Title = "CoffeeMate - " + greetings[r.Next(greetings.Count)]; this.AddGroundButton.Click += TryCreateGround; this.DeleteGroundButton.Click += TryDeleteGround; } private void Shutdown(object sender, CancelEventArgs e) { CoffeeViewModel x = (CoffeeViewModel)this.DataContext; Persistence.Save(x.GroundList); } private void TryCreateGround(object s, RoutedEventArgs e) { CoffeeViewModel x = (CoffeeViewModel)this.DataContext; x.GroundList.Add(new GroundModel() { Parent = x }); x.NotifyChange("GroundList"); } private void TryDeleteGround(object s, RoutedEventArgs e) { CoffeeViewModel x = (CoffeeViewModel)this.DataContext; if (x.GroundList.Count <= 1) return; int current_index = x.GroundList.IndexOf(x.CurrentGround); x.GroundList.Remove(x.CurrentGround); x.CurrentGround = x.GroundList[current_index-1 < 0? 0 : current_index -1]; } } }
d290e642d37771403219f53cc7b2df25a548cd1a
C#
TySatkowiak/Hearthstone
/Game.cs
3.15625
3
using System; using System.Collections.Generic; using System.Linq; namespace Hearthstone { public class Game { public static int Player1Mana = 0; public static int Player2Mana = 0; public static int Player1Health = 30; public static int Player2Health = 30; public static List<Creatures> Hand1 = new List<Creatures>(); public static List<Creatures> Hand2 = new List<Creatures>(); public static List<Creatures> Board1 = new List<Creatures>(); public static List<Creatures> Board2 = new List<Creatures>(); public static Deck player1 = new Deck(); public static Deck player2 = new Deck(); //Show deck list and draw each player's initial cards. public void PlayGame() { Program.ViewPlayerDecks(player1); Console.WriteLine(""); Hand1.AddRange(Deck.Draw(3, 1)); Hand2.AddRange(Deck.Draw(4, 2)); Hand2.Add(new Creatures("Coin", 0, 0, 0, "+1 to Mana", "",false)); //"ADD COIN TO HAND" Player1Turn(); } public void SummoningSickness(List<Creatures> board) { foreach (Creatures card in board) { card.CanAttack = true; } } //After Player 1 end's turn, turn to player 2 public void Player1Turn() { SummoningSickness(Board1); Player1Mana++; int useableMana = Player1Mana; Hand1.AddRange(Deck.Draw(1, 1)); Hand1 = Program.Discard(Hand1); int choose = 0; bool endTurn = true; while (endTurn) { ShowHand(Hand1, 1, Player1Health, useableMana, Player1Mana); Console.WriteLine("Select an option using the numbers on the left."); string entry = Console.ReadLine(); choose = Program.ValidateMenuChoice(entry, Hand1); if (choose > 1 && choose <= Hand1.Count) { if (Hand1[choose - 1].ManaCost > useableMana) { Console.WriteLine($"You don't have enough Mana to play {Hand1[choose - 1].CardName}"); } else { PrintToBoard(Hand1, Board1, choose, 1); useableMana -= Hand1[choose - 1].ManaCost; Hand1.RemoveAt(choose - 1); } } else if (choose == Hand1.Count + 1) { if(Board1.Count == 0) { Console.WriteLine("You don't have anything to attack with!"); Console.WriteLine(""); } else { Console.WriteLine(""); PrintBoards(Board1); Console.WriteLine(""); PrintBoards(Board2); int attack = AttackChoice(Board1); int defend = DefendChoice(Board2); } } else if (choose == Hand1.Count + 2) { Console.WriteLine("Do you want to end your turn?"); string q = Console.ReadLine().ToLower(); if (q == "y") { Console.Clear(); Player2Turn(); } } else if (choose == Hand1.Count + 3) { Program.Concede(); } else { Console.WriteLine("uhh......SMOKEBOMB!"); } } } public static void PrintBoards(List<Creatures> board) { for (int i = 0; i < board.Count; i++) { if (board.Count == 0) { Console.WriteLine("There is nothing on the board."); break; } Console.WriteLine($"{i + 1}. {board[i]}"); } } public static int DefendChoice(List<Creatures> board) { Console.WriteLine("What do you want to attack?"); string entry = Console.ReadLine(); if (!int.TryParse(entry, out int menuValue)) { Console.WriteLine("Please have a valid input."); return 0; } else if (menuValue > 0 && menuValue <= board.Count + 2) { return menuValue; } else { Console.WriteLine("Please have a valid input."); return 0; } } public static int AttackChoice(List<Creatures> board) { if (board.Count == 0) { Console.WriteLine("You don't have any minions to attack with."); return 0; } else { Console.WriteLine("Which creature do you want to attack with?"); string entry = Console.ReadLine(); if (!int.TryParse(entry, out int menuValue)) { Console.WriteLine("Please have a valid input."); return 0; } else if (menuValue > 0 && menuValue <= board.Count) { return menuValue; } else { Console.WriteLine("Please have a valid input."); return 0; } } } //Deal minion damage to the opposing hero //Deal ATK dmg to creature's health, if either reach 0, send to graveyard public static void Damage(List<Creatures> board1, int selection1, List<Creatures> board2, int selection2) { } //Similar to Player 1's turn, add a 'coin' to their hand. public void Player2Turn() { SummoningSickness(Board2); Player2Mana++; int useableMana = Player2Mana; Hand2.AddRange(Deck.Draw(1, 2)); Hand2 = Program.Discard(Hand2); int choose = 0; bool endTurn = true; while (endTurn) { ShowHand(Hand2, 2, Player2Health, useableMana, Player2Mana); Console.WriteLine("Select an option using the numbers on the left."); string entry = Console.ReadLine(); choose = Program.ValidateMenuChoice(entry, Hand2); if (choose > 1 && choose <= Hand2.Count) { if (Hand2[choose - 1].ManaCost > Player2Mana) { Console.WriteLine($"You don't have enough Mana to play {Hand2[choose - 1].CardName}"); } else if (Hand2[choose - 1].CardName == "Coin") { useableMana += 1; } else { PrintToBoard(Hand2, Board2, choose, 2); useableMana -= Hand2[choose - 1].ManaCost; Hand2.RemoveAt(choose - 1); } } else if (choose == Hand2.Count + 1) { AttackChoice(Board2); } else if (choose == Hand2.Count + 2) { Console.WriteLine("Do you want to end your turn?"); string q = Console.ReadLine().ToLower(); if (q == "y") { Console.Clear(); Player1Turn(); } } else if (choose == Hand2.Count + 3) { Program.Concede(); } else { Console.WriteLine("UHH....SMOKEBOMB!"); } } } //Send a minion from the player's hand onto the field. public static void PrintToBoard(List<Creatures> deck, List<Creatures> board, int choice, int playerNumber) { board.Add(deck[choice - 1]); Console.WriteLine($"Succesfully added to board for Player {playerNumber}"); for (int i = 0; i < board.Count; i++) { Console.WriteLine($"{i + 1}. {board[i]}"); } Console.WriteLine(""); } //Show hand, Health, Mana and option to pass turn public void ShowHand(List<Creatures> deck, int playerNumber, int health, int mana, int totalMana) { Console.WriteLine($"Player {playerNumber}'s hand:"); Console.WriteLine($"Current Health: {health}"); Console.WriteLine($"Total Mana: {totalMana}"); Console.WriteLine($"Useable Mana: {mana}"); Console.WriteLine(String.Format("{0,-25} {1,9} {2,6} {3,-6} {4,16} {5,8}", "Card Name", "Mana Cost", "Attack", "Health", "Ability", "Type")); for (int i = 0; i < deck.Count; i++) { if (deck.Count == 0) { Console.WriteLine("OH NO! You don't have any cards in hand."); } Console.WriteLine($"{i + 1}. {deck[i]}"); } Console.WriteLine($"{deck.Count + 1}. Attack"); Console.WriteLine($"{deck.Count + 2}. End turn?"); Console.WriteLine($"{deck.Count + 3}. Concede?"); Console.WriteLine(""); } } }
cdc2a5c199c52bd9a719b723854d2eaed4ce5b7b
C#
vladosfi/SoftUni
/C#/C# Advanced/C# Advanced - May 2019/Exam - 24 February 2019/01.ClubParty/StartUp.cs
3.46875
3
using System; using System.Collections.Generic; using System.Linq; namespace _01.ClubParty { class StartUp { static void Main(string[] args) { int hallsCapacity = int.Parse(Console.ReadLine()); string[] input = Console.ReadLine().Split(" ", StringSplitOptions.RemoveEmptyEntries); Stack<string> elements = new Stack<string>(input); List<int> allGroup = new List<int>(); Queue<string> halls = new Queue<string>(); while (elements.Count > 0) { string element = elements.Pop(); if (int.TryParse(element,out int company)) { if (halls.Count == 0) { continue; } if (allGroup.Sum() + company > hallsCapacity) { Console.WriteLine($"{halls.Dequeue()} -> {string.Join(", ", allGroup)}"); allGroup.Clear(); } if (halls.Count == 0) { continue; } allGroup.Add(company); } else { halls.Enqueue(element); } } } } }
414af8a915bee30d2161a78b9930252235b5827d
C#
turanbstc/MyDevop
/OOP2/Program.cs
2.75
3
using System; namespace OOP2 { class Program { static void Main(string[] args) { IndividualCustomer individualCustomer = new IndividualCustomer(); individualCustomer.Id = 1; individualCustomer.CustomerNumber = "12345"; individualCustomer.Name = "Turan"; individualCustomer.Surname = "Bastacioglu"; individualCustomer.TcNo = "324123123"; CorporateCustomer corporateCustomer = new CorporateCustomer(); corporateCustomer.Id = 2; corporateCustomer.CustomerNumber = "3241"; corporateCustomer.CompanyName = "BASTACIOGLU MUHENDISLIK"; corporateCustomer.VatNo = "1231231"; Customer customer1 = new CorporateCustomer(); Customer customer2 = new IndividualCustomer(); CustomerManager customerManager = new CustomerManager(); customerManager.Add(individualCustomer); customerManager.Add(corporateCustomer); } } }
4d1706970669a583f06e93c2d9da7391b4f5c319
C#
tekavec/TaskListKata
/TaskListKata.Tests/ShowCommandShould.cs
2.6875
3
using NSubstitute; using NUnit.Framework; namespace TaskListKata.Tests { [TestFixture] public class ShowCommandShould { private IConsole _fakeConsole; private TaskRepository _taskRepository; private ShowCommand _showCommand; [SetUp] public void Init() { _taskRepository = new TaskRepository(); var project = new Project("secrets"); var task = new Task("Eat more donuts.", project) {Id = 1L}; _taskRepository.Add(task); _fakeConsole = Substitute.For<IConsole>(); _showCommand = new ShowCommand(_fakeConsole, _taskRepository); } [Test] public void ShowProjectListWithTasks() { _showCommand.Execute(); Received.InOrder(() => { _fakeConsole.WriteLine("secrets"); _fakeConsole.WriteLine(" [{0}] {1}: {2}", ' ', 1L, "Eat more donuts."); _fakeConsole.WriteLine(); }); } } }
d2b599914d401376309aa1b05faa44c632e5aafd
C#
Raw-Bert/NetworkingPractical
/Networking Practical (Unity)/Networking Practical/Assets/_Scripts/Networking.cs
2.578125
3
using Unity.Collections.LowLevel.Unsafe; using System.Runtime.InteropServices; using System; public class Networking { public enum IPVersion : int { IPUnknown, IPv4, IPv6 }; public enum SocketOption : int { TCP_NoDelay }; public enum SocketType : int { TCP, UDP }; public enum PResult : int { P_Success, P_GenericError }; [StructLayout(LayoutKind.Sequential)] public struct SocketData { public IPVersion m_IPVersion; public UInt64 m_hnd; }; [StructLayout(LayoutKind.Sequential)] public struct IPEndpointData { //public IPEndpointData(IPVersion ver = IPVersion.IPUnknown, string host = "", string str = "", long bytessize = 0, string bytes = "", short port = 0) //{ // m_IPVersion = ver; m_hostname = host; m_ipString = str; // m_ipBytesSize = bytessize; m_ipBytes = bytes; m_port = port; //} public IPVersion m_IPVersion; [MarshalAs(UnmanagedType.LPStr)] [NativeDisableUnsafePtrRestriction] public IntPtr m_hostname; [MarshalAs(UnmanagedType.LPStr)] [NativeDisableUnsafePtrRestriction] public IntPtr m_ipString; public uint m_ipBytesSize; [NativeDisableUnsafePtrRestriction] public IntPtr m_ipBytes; public short m_port; }; const string DLL = "Networking.DLL"; //ERROR// ///<summary> ///gets the last error that happened ///</summary> [DllImport(DLL)] private static extern IntPtr getLastNetworkError(int idk); public static string getLastNetworkError() { IntPtr ptr = getLastNetworkError(0); return Marshal.PtrToStringAnsi(ptr); } //NETWORK// ///<summary> ///initializes Winsock ///</summary> [DllImport(DLL)] public static extern bool initNetwork(); ///<summary> ///Shutdown Winsoc ///</summary> [DllImport(DLL)] public static extern void shutdownNetwork(); //ENDPOINT// ///<summary> ///Creates a new IPEndpoint handle for a given IP and port. Multiple IPEndpoints can be created ///</summary> [DllImport(DLL)] public static extern IPEndpointData createIPEndpointData([MarshalAs(UnmanagedType.LPStr)]string ip, short port); //SOCKET// ///<summary> ///Creates a new Socket handle for manageing IPEndpoints. ///</summary> [DllImport(DLL)] public static extern SocketData initSocketData(); ///<summary> ///initializes the socket to use UDP or TCP conection types ///</summary> [DllImport(DLL)] public static extern PResult createSocket(ref SocketData soc, SocketType typ = SocketType.TCP); ///<summary> ///closes socket so it can not be used unless createSocket() is called once again. ///</summary> [DllImport(DLL)] public static extern PResult closeSocket(ref SocketData soc); ///<summary> ///Bind Endpoint to socket. ///</summary> [DllImport(DLL)] public static extern PResult bindEndpointToSocket(ref IPEndpointData ip, ref SocketData soc); ///<summary> ///Listens for endpoint connection to the socket. It will block until a new connection is found. ///</summary> [DllImport(DLL)] public static extern PResult listenEndpointToSocket(ref IPEndpointData ip, ref SocketData soc, int backlog = 5); ///<summary> ///Attempts to accept the listened connection. ///</summary> [DllImport(DLL)] public static extern PResult acceptSocket(ref SocketData soc, ref SocketData outsoc); ///<summary> ///Connects endpoint to socket ///</summary> [DllImport(DLL)] public static extern PResult connectEndpoint(ref IPEndpointData ip, ref SocketData soc); // Sending Data // TCP [DllImport(DLL)] private static extern PResult sendPacketData(ref SocketData soc, IntPtr data, int datasize, ref int bytesSent); ///<summary> ///Send packet over TCP server. Not guaranteed to send all bytes. ///</summary> public static PResult sendPacket<T>(SocketData soc, ref T data, int datasize, ref int bytesSent) { IntPtr tmp = Marshal.AllocHGlobal(Marshal.SizeOf<T>(data)); Marshal.StructureToPtr(data, tmp, true); PResult res = sendPacketData(ref soc, tmp, datasize, ref bytesSent); Marshal.FreeHGlobal(tmp); return res; } ///<summary> ///Send packet over TCP server. Not guaranteed to send all bytes. ///</summary> public static PResult sendPacket(SocketData soc, ref string data, int datasize, ref int bytesSent) { IntPtr tmp = Marshal.StringToHGlobalAnsi(data); PResult res = sendPacketData(ref soc, tmp, datasize, ref bytesSent); return res; } [DllImport(DLL)] private static extern PResult recvPacketData(ref SocketData soc, IntPtr dest, int numberOfBytes, ref int bytesRecv); ///<summary> ///Receive packet over TCP server. Not guaranteed to recieve all bytes. ///</summary> public static PResult recvPacket<T>(ref SocketData soc, ref T dest, int numberOfBytes, ref int bytesRecv) { IntPtr tmp = Marshal.AllocHGlobal(Marshal.SizeOf<T>(dest)); Marshal.StructureToPtr(dest, tmp, true); PResult res = recvPacketData(ref soc, tmp, numberOfBytes, ref bytesRecv); if (res == PResult.P_GenericError) dest = Marshal.PtrToStructure<T>(tmp); Marshal.FreeHGlobal(tmp); return res; } ///<summary> ///Receive packet over TCP server. Not guaranteed to recieve all bytes. ///</summary> public static PResult recvPacket(ref SocketData soc, ref string dest, int numberOfBytes, ref int bytesRecv) { IntPtr tmp = Marshal.AllocHGlobal(numberOfBytes); PResult res = recvPacketData(ref soc, tmp, numberOfBytes, ref bytesRecv); dest = Marshal.PtrToStringAnsi(tmp); Marshal.FreeHGlobal(tmp); return res; } [DllImport(DLL)] private static extern PResult sendAllPacketData(ref SocketData soc, IntPtr data, int numberOfBytes); ///<summary> ///Send entire packet over TCP server. guaranteed to send all bytes. ///</summary> public static PResult sendAllPacket<T>(ref SocketData soc, ref T data, int numberOfBytes) { IntPtr tmp = Marshal.AllocHGlobal(Marshal.SizeOf<T>(data)); Marshal.StructureToPtr(data, tmp, true); PResult res = sendAllPacketData(ref soc, tmp, numberOfBytes); Marshal.FreeHGlobal(tmp); return res; } ///<summary> ///Send entire packet over TCP server. guaranteed to send all bytes. ///</summary> public static PResult sendAllPacket(ref SocketData soc, ref string data) { IntPtr tmp = Marshal.StringToHGlobalAnsi(data); PResult res = sendAllPacketData(ref soc, tmp, data.Length + 1); return res; } [DllImport(DLL)] private static extern PResult recvAllPacketData(ref SocketData soc, IntPtr dest, int numberOfBytes); ///<summary> ///Receive entire packet over TCP server. guaranteed to recieve all bytes. ///</summary> public static PResult recvAllPacket<T>(ref SocketData soc, ref T dest, int numberOfBytes) { IntPtr tmp = Marshal.AllocHGlobal(Marshal.SizeOf<T>(dest)); Marshal.StructureToPtr(dest, tmp, true); PResult res = recvAllPacketData(ref soc, tmp, numberOfBytes); if (res == PResult.P_GenericError) dest = Marshal.PtrToStructure<T>(tmp); Marshal.FreeHGlobal(tmp); return res; } ///<summary> ///Receive entire packet over TCP server. guaranteed to recieve all bytes. ///</summary> public static PResult recvAllPacket(ref SocketData soc, ref string dest, int numberOfBytes) { IntPtr tmp = Marshal.AllocHGlobal(numberOfBytes); PResult res = recvAllPacketData(ref soc, tmp, numberOfBytes); dest = Marshal.PtrToStringAnsi(tmp); Marshal.FreeHGlobal(tmp); return res; } //UDP [DllImport(DLL)] private static extern PResult recvFromPacketDataEx(ref SocketData soc, IntPtr data, int numberOfBytes, ref int bytesSent, ref IPEndpointData ip); ///<summary> ///Receive packet over UDP server. Not guaranteed to recieve all bytes. ///</summary> public static PResult recvFromPacket<T>(ref SocketData soc, ref T data, int numberOfBytes, ref int bytesRecv, ref IPEndpointData ip) { IntPtr tmp = Marshal.AllocHGlobal(Marshal.SizeOf<T>(data)); Marshal.StructureToPtr(data, tmp, true); PResult res = recvFromPacketDataEx(ref soc, tmp, numberOfBytes, ref bytesRecv, ref ip); if (bytesRecv > 0) data = Marshal.PtrToStructure<T>(tmp); Marshal.FreeHGlobal(tmp); return res; } ///<summary> ///Receive packet over UDP server. Not guaranteed to recieve all bytes. ///</summary> public static PResult recvFromPacket(ref SocketData soc, ref string data, int numberOfBytes, ref int bytesSent, ref IPEndpointData ip) { IntPtr tmp = Marshal.AllocHGlobal(numberOfBytes);//allocates to unmanaged memory PResult res = recvFromPacketDataEx(ref soc, tmp, numberOfBytes, ref bytesSent, ref ip); data = Marshal.PtrToStringAnsi(tmp, numberOfBytes); Marshal.FreeHGlobal(tmp); return res; } [DllImport(DLL)] private static extern PResult recvFromPacketData(ref SocketData soc, IntPtr data, int numberOfBytes, ref IPEndpointData ip); ///<summary> ///Receive packet over UDP server. Not guaranteed to recieve all bytes. ///</summary> public static PResult recvFromPacket<T>(ref SocketData soc, ref T data, int numberOfBytes, ref IPEndpointData ip) { IntPtr tmp = Marshal.AllocHGlobal(Marshal.SizeOf<T>(data)); Marshal.StructureToPtr(data, tmp, true); PResult res = recvFromPacketData(ref soc, tmp, numberOfBytes, ref ip); if (res == PResult.P_GenericError) data = Marshal.PtrToStructure<T>(tmp); Marshal.FreeHGlobal(tmp); return res; } ///<summary> ///Receive packet over UDP server. Not guaranteed to recieve all bytes. ///</summary> public static PResult recvFromPacket(ref SocketData soc, ref string data, int numberOfBytes, ref IPEndpointData ip) { IntPtr tmp = Marshal.AllocHGlobal(numberOfBytes); PResult res = recvFromPacketData(ref soc, tmp, numberOfBytes, ref ip); data = Marshal.PtrToStringAnsi(tmp); Marshal.FreeHGlobal(tmp); return res; } [DllImport(DLL)] private static extern PResult sendToPacketDataEx(ref SocketData soc, IntPtr data, int numberOfBytes, ref int bytesSent, ref IPEndpointData ip); ///<summary> ///Send packet over UDP server. Not guaranteed to send all bytes. ///</summary> public static PResult sendToPacket<T>(ref SocketData soc, ref T data, int numberOfBytes, ref int bytesSent, ref IPEndpointData ip) { IntPtr tmp = Marshal.AllocHGlobal(Marshal.SizeOf<T>(data)); Marshal.StructureToPtr(data, tmp, true); PResult res = sendToPacketDataEx(ref soc, tmp, numberOfBytes, ref bytesSent, ref ip); Marshal.FreeHGlobal(tmp); return res; } ///<summary> ///Send packet over UDP server. Not guaranteed to send all bytes. ///</summary> public static PResult sendToPacket(ref SocketData soc, ref string data, ref int bytesSent, ref IPEndpointData ip) { IntPtr tmp = Marshal.StringToHGlobalAnsi(data); PResult res = sendToPacketDataEx(ref soc, tmp, data.Length + 1, ref bytesSent, ref ip); return res; } [DllImport(DLL)] private static extern PResult sendToPacketData(ref SocketData soc, IntPtr data, int numberOfBytes, ref IPEndpointData ip); ///<summary> ///Send packet over UDP server. Not guaranteed to send all bytes. ///</summary> public static PResult sendToPacket<T>(ref SocketData soc, ref T data, int numberOfBytes, ref IPEndpointData ip) { IntPtr tmp = Marshal.AllocHGlobal(Marshal.SizeOf<T>(data)); Marshal.StructureToPtr(data, tmp, true); PResult res = sendToPacketData(ref soc, tmp, numberOfBytes, ref ip); Marshal.FreeHGlobal(tmp); return res; } ///<summary> ///Send packet over UDP server. Not guaranteed to send all bytes. ///</summary> public static PResult sendToPacket(ref SocketData soc, ref string data, ref IPEndpointData ip) { IntPtr tmp = Marshal.StringToHGlobalAnsi(data); PResult res = sendToPacketData(ref soc, tmp, data.Length + 1, ref ip); return res; } }
cc225a30e801f127a67cb0fc0aa403559680fe7c
C#
Mosatt/CV
/Szakdolgozat/Projekt/Szakdolgozat_RZD/Szakdolgozat_RZD/Controller/C_Login.cs
2.515625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.IO; using System.Text.RegularExpressions; using MySql.Data.MySqlClient; using System.Security.Cryptography; namespace Szakdolgozat_RZD { class C_Login { string username { get; set; } string password { get; set; } public static string status { get; set; } bool check_username { get; set; } bool check_password { get; set; } public static int ID { get; set; } public C_Login() { } string Encript(string value) { using (MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider()) { UTF8Encoding utf8 = new UTF8Encoding(); byte[] data = md5.ComputeHash(utf8.GetBytes(value)); return Convert.ToBase64String(data); } } public void login(string tb_username, string tb_password) { M_db_loginf m_db_loginform = new M_db_loginf(); username = tb_username; password = Encript(tb_password).GetHashCode().ToString(); string sql_name = "SELECT username FROM users WHERE username = @login_name;"; string sql_pass = "SELECT password FROM users WHERE password = @login_password;"; string sql_status = "SELECT status FROM users WHERE username = '"+ username +"' and password = '"+ password +"'"; string sql_ID = "SELECT userID FROM users WHERE username = '" + username + "' and password = '" + password + "'"; MySqlParameter param = new MySqlParameter(); param.ParameterName = "@login_name"; param.Value = username; MySqlCommand cmd_username = new MySqlCommand(sql_name, Model_db.conn); cmd_username.Parameters.Add(param); MySqlParameter param2 = new MySqlParameter(); param2.ParameterName = "@login_password"; param2.Value = password; MySqlCommand cmd_password = new MySqlCommand(sql_pass, Model_db.conn); cmd_password.Parameters.Add(param2); if (!Regex.IsMatch(username.ToLower(), @"^[a-z]{9-16}$") && Regex.IsMatch(username.ToLower(), "select|drop|update|insert|delete|alter|create|group|order|from|where|having|;|>|<|-")) { MessageBox.Show("Rossz felhasználónév, vagy jelszó!"); username = string.Empty; password = string.Empty; } else if (!Regex.IsMatch(password.ToLower(), @"^[a-zA-Z0-9]{0-30}$") && Regex.IsMatch(password.ToLower(), "select|drop|update|insert|delete|alter|create|or|group|order|from|where|having|;|>|<|-")) { MessageBox.Show("Rossz felhasználónév, vagy jelszó!"); username = string.Empty; password = string.Empty; } else { check_username = m_db_loginform.login_hash_check(check_username, cmd_username); check_password = m_db_loginform.login_hash_check(check_password, cmd_password); try { Model_db.conn.Open(); MySqlCommand cmd_status = new MySqlCommand(sql_status, Model_db.conn); MySqlDataReader statusreader = cmd_status.ExecuteReader(); while (statusreader.Read()) { status = statusreader.GetString("status"); } } catch (Exception ex) { MessageBox.Show(ex.Message, "hibaüzenet", MessageBoxButtons.OK, MessageBoxIcon.Warning); } finally { Model_db.conn.Close(); } try { Model_db.conn.Open(); MySqlCommand cmd_ID = new MySqlCommand(sql_ID, Model_db.conn); MySqlDataReader IDreader = cmd_ID.ExecuteReader(); while (IDreader.Read()) { ID = int.Parse(IDreader.GetString("userID")); } } catch (Exception ex) { MessageBox.Show(ex.Message, "hibaüzenet", MessageBoxButtons.OK, MessageBoxIcon.Warning); } finally { Model_db.conn.Close(); } if (check_username == true && check_password == true) { if (status == "user") { MainForm mf = new MainForm(); mf.Show(); mf.mainpageToolStripMenuItem_Click(null, null); } else if (status == "admin") { AdminForm af = new AdminForm(); af.Show(); } LoginF lf = new LoginF(); lf.Hide(); } else { MessageBox.Show("Rossz felhasználónév, vagy jelszó!\n", "Hibaüzenet", MessageBoxButtons.OK, MessageBoxIcon.Warning); username = string.Empty; password = string.Empty; } } } } }
2f91b7828cd0837447e3b3a70e3b98e2d74a3904
C#
hoilaptrinhgame/OpenMU
/src/MUnique.OpenMU.Launcher/Models/DownloadTask.cs
2.609375
3
using System; using System.ComponentModel; using System.IO; using System.Net; using MUnique.OpenMU.Launcher.Enumerations; using NLog; namespace MUnique.OpenMU.Launcher.Models { public class DownloadTask : IDisposable { private static readonly Logger logger = LogManager.GetCurrentClassLogger(); #region Fields private readonly WebClient WClient = new WebClient { //Prevent proxies like Fiddler to sniff the url and contents Proxy = new WebProxy() }; #endregion internal bool StartedDownload { get; private set; } public void Dispose() { WClient?.Dispose(); URI = null; } internal void StartDownload() { if (StartedDownload) { return; } StartedDownload = true; if (!Directory.Exists(SaveDir)) { Directory.CreateDirectory(SaveDir); } if (OnlyIfDoesntExists && File.Exists(SavePath)) { Progress = 100; Finished = true; return; } File.Delete(SavePath); //Console.WriteLine(URI.ToString()); switch (UpdaterType) { case UpdaterTypes.HTTPS: DownloadHTTP(); break; case UpdaterTypes.Torrent: break; case UpdaterTypes.SFTP: DownloadFTP(); break; default: logger.Warn($"Updater of type ({UpdaterType}) is not supported."); break; } } private void DownloadHTTP() { WClient.DownloadFileAsync(URI, SavePath); } private void DownloadFTP() { WClient.Credentials = new NetworkCredential("username", "password"); WClient.DownloadFileAsync(URI, SavePath); } #region Constructors and Destructors public bool OnlyIfDoesntExists { get; set; } = false; public UpdaterTypes UpdaterType { get; set; } public DownloadTask(Uri uri, string savePath, UpdaterTypes type) { URI = uri; SavePath = savePath; SaveDir = Path.GetDirectoryName(savePath); FileName = Path.GetFileName(savePath); if (RequireRestart) { SavePath = SavePath + ".new"; FileName = FileName + ".new"; } WClient.DownloadProgressChanged += WClient_DownloadProgressChanged; WClient.DownloadFileCompleted += WClient_DownloadFileCompleted; } #endregion #region Public Events public delegate void OnDownloadCompleteDelegate(DownloadTask task); public delegate void OnProgressChangedDelegate(int progress); public event OnDownloadCompleteDelegate OnDownloadComplete; public event OnProgressChangedDelegate OnProgressChanged; #endregion #region Public Properties public string FileName { get; set; } public bool Finished { get; set; } public int Progress { get; set; } public string SaveDir { get; set; } public string SavePath { get; set; } public Uri URI { get; set; } public bool RequireRestart { get; set; } = false; #endregion #region Methods private void WClient_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e) { Progress = 100; Finished = true; OnDownloadComplete?.Invoke(this); } private void WClient_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e) { Progress = e.ProgressPercentage; OnProgressChanged?.Invoke(Progress); } #endregion } }
78163275f393a5f7b44472216160c6d03f82c1ff
C#
mindisk/C5
/C5/concurrent/lists/SprayList.cs
2.96875
3
using System; using SCG = System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace C5.concurrent { public class SprayList<T> : IConcurrentPriorityQueue<T> { internal class Node { internal object nodeLock = new object(); internal Node[] forward; internal T value; internal bool marked; internal int level = 0; internal bool tail = false; public Node(int level, T value) { this.forward = new Node[level + 1]; this.value = value; this.marked = false; this.level = level; } public override string ToString() { return string.Format("[{0} - {1} - {2} - {3}]", value, marked, tail, level); } } object levelLock = new object(); SCG.IComparer<T> comparer; SCG.IEqualityComparer<T> itemEquelityComparer; int size, maxLevel, p; Node header, tail; public SprayList(int p) : this(32, p) { } public SprayList(int maxlevel, int p) { this.comparer = SCG.Comparer<T>.Default; this.itemEquelityComparer = SCG.EqualityComparer<T>.Default; header = null; int max = 1; while (max < maxlevel) max <<= 1; maxLevel = max; this.p = p <= 0 ? 1 : p; tail = new Node(maxLevel - 1, default(T)); tail.tail = true; header = new Node(maxLevel - 1, default(T)); for (int i = 0; i < maxLevel; i++) { header.forward[i] = tail; tail.forward[i] = tail; } } public int Count { get { return size; } } public SCG.IEnumerable<T> All() { throw new NotImplementedException(); } public bool Check() { if (size == 0) return true; for (int i = 0; i <= maxLevel - 1; i++) { Node x = header; //header is 0 (and we allow for dupliates as of 21/11/2016), so we have to check if the previous node is greater then or equel to the current one while (!x.forward[i].tail && comparer.Compare(x.value, x.forward[i].value) <= 0) x = x.forward[i]; //If the the next element isen't null, there's an element next x (the supposed last and least element), and the list is out of order if (!x.forward[i].tail) return false; } return true; } public bool Add(T item) { int lvl = randomLevel(); //get number of levels a new node has to inserted into int l = 0; //starting level bool initialInsert = false; Node curr = new Node(0, item); while (true) { if (curr.marked) return true;//if curr logicall deleted, exit Node x = header; Node[] preds = new Node[maxLevel], succs = new Node[maxLevel]; if (!initialInsert) { //ne wnode have not been inserted yet. for (int i = maxLevel - 1; i >= 0; i--) { while (!x.forward[i].tail && comparer.Compare(x.forward[i].value, item) <= 0) //skip nodes until a position for new node is found. x = x.forward[i]; preds[i] = x; //fill with predecessors succs[i] = x.forward[i]; //fill with successors } } else { //new node have been inserted into the list Node next; bool hittail = false; for (int i = maxLevel - 1; i >= 0; i--) //for each level { while (!(next = x.forward[i]).tail && comparer.Compare(next.value, item) < 0) //skip nodes until a nodes with the same value as new node are found. x = next; preds[i] = x; //fill with predecessors succs[i] = x.forward[i];//fill with successors } for (int i = lvl; i >= l; i--) //for each level between lvl and l { x = preds[l - 1]; //assing as predecessor at level l-1 if (x.tail) continue; while (!curr.marked && !(next = x.forward[l - 1]).tail && !curr.Equals(next)) //skip nodes until new node is found { x = next; if (x.tail && x.Equals(curr)) { hittail = true; break; } if (x.level >= i) //if x node has number of levels at least as i { preds[i] = x; //assign new predecessor at level i succs[i] = x.forward[i]; //assign new successor at level i } } if (hittail) break; } if (hittail) continue; } bool breaking = false; while (l <= lvl) //continue until all levels are inserted { lock (preds[l].nodeLock) { Node pred = preds[l]; if (pred.tail || pred.level < 0) break; lock (curr.nodeLock) { if (curr.marked) return true; while (l <= lvl && l <= pred.level) //insert new node into single predecessor until l is not as big as lvl and until l matches predecessor level { if (Validate(pred, succs[l], l, item)) { Node[] newfor = new Node[l + 1]; //create array of size l for (int i = 0; i < curr.forward.Length; i++) //copy references to new array newfor[i] = curr.forward[i]; Interlocked.Exchange(ref newfor[l], succs[l]); //add successor at level l to the new array Interlocked.Exchange(ref curr.forward, newfor); //assign new array to be curr.forward Interlocked.Exchange(ref pred.forward[l], curr); //assign predecessor at level l to poin to new node if (l == 0) { Interlocked.Increment(ref size); initialInsert = true; } curr.level = l; //number of levels curr node is linked in if (curr.level == lvl) //all levels have been isnerted return true; l++; //next level } else { breaking = true; break; //exit while loop } } if (breaking) break; //exit while loopp and restart } } } } } public T DeleteMax() { if (header.forward[0].tail) throw new NoSuchItemException(); int l = int.MaxValue; Node curr = null; while (true) { if (header.forward[0].tail) throw new NoSuchItemException(); Node x = header; Node[] preds = new Node[maxLevel], succs = new Node[maxLevel]; for (int i = maxLevel - 1; i >= 0; i--) { while (x.level >= 0 && !x.forward[i].tail && !x.forward[i].forward[i].tail) x = x.forward[i]; preds[i] = x; succs[i] = x.forward[i]; } lock (preds[0].nodeLock) { if (!preds[0].marked && !preds[0].tail && preds[0].level >= 0 && !(curr = preds[0].forward[0]).tail) //check if predecessor fulfills constrains and get curr node { lock (curr.nodeLock) { if (!curr.tail && curr.forward[0].tail) { l = curr.level; //get node's number of levels } else { curr = null; continue; } } } else continue; } bool breaking = false; while (true) //proceed until all levels are inserted or sychcronization conflict os detected { lock (preds[l].nodeLock) { if (!preds[l].tail && preds[l].level >= 0) { lock (curr.nodeLock) { if (!curr.tail && curr.forward[0].tail && curr.level >= 0) { if (curr.level == l) { while (true) //proceed unlti predecessors at level l and l-1 are the same { if (ValidatePred(preds[l], curr, l) && curr.Equals(succs[l])) //validate { curr.marked = true; //logically delete Interlocked.Exchange(ref preds[l].forward[l], curr.forward[l]); curr.level = --l; if (l == -1) //curr have been removed from all levels { Interlocked.Decrement(ref size); return curr.value; } if (!preds[l + 1].Equals(preds[l])) //predecessor at level l+1 is not the same at level l break; //proceed with locking on another predecessor } else { breaking = true; break; //restart serach } } } else { l = curr.level; //get new level continue; //proceed with new level } } else { curr = null; break; //restart search } } } else { curr = null; break; //restart search } } if (breaking) break; //restart search } } } public T DeleteMin() { Node curr = null; int lvl = 0; while (true) { if (header.forward[0].tail) throw new NoSuchItemException(); if (curr == null) { int d = D(true); int h = H(2, d); int l = L(1); curr = Spray(h, l, d); } Node[] preds = new Node[maxLevel]; Node x = header, next; bool invalidNode = false; for (int i = maxLevel - 1; i >= 0; i--) //for each level { while (!(next = x.forward[i]).tail && comparer.Compare(next.value, curr.value) < 0) //skip nodes until a nodes with the same value as new node are found. x = next; preds[i] = x; //fill with predecessors } if ((lvl = curr.level) < 0) { curr = null; continue; } for (int i = lvl; i >= 0; i--) //for each level between lvl and l { x = preds[0]; //assing as predecessor at level l-1 if (x.tail) { invalidNode = true; break; } while (!(next = x.forward[0]).tail && !curr.Equals(next)) //skip nodes until new node is found { x = next; if (x.tail && x.Equals(curr)) { invalidNode = true; break; } if (x.level >= i) //if x node has number of levels at least as i preds[i] = x; //assign new predecessor at level i } if (invalidNode) break; } if (invalidNode) { continue; } bool breaking = false; while (true) //proceed until all levels are inserted or sychcronization conflict os detected { lock (preds[lvl].nodeLock) { if (!preds[lvl].tail && preds[lvl].level >= 0) { lock (curr.nodeLock) { if (ValidateNode(curr)) { if (curr.level == lvl) { while (true) //proceed unlti predecessors at level l and l-1 are the same { if (ValidatePred(preds[lvl], curr, lvl)) //validate { curr.marked = true; //logically delete Interlocked.Exchange(ref preds[lvl].forward[lvl], curr.forward[lvl]); curr.level = --lvl; if (lvl == -1) //curr have been removed from all levels { Interlocked.Decrement(ref size); return curr.value; } if (!preds[lvl + 1].Equals(preds[lvl])) //predecessor at level l+1 is not the same at level l break; //proceed with locking on another predecessor } else { breaking = true; break; //restart serach } } } else { lvl = curr.level; //get new level continue; //proceed with new level } } else { curr = null; break; //restart search } } } else { break; //restart search } } if (breaking) break; //restart search } } } public T FindMax() { while (true) { if (header.forward[0].tail) throw new NoSuchItemException(); Node x = header; Node curr = null; for (int i = maxLevel - 1; i >= 0; i--) { while (!x.forward[i].tail && !x.forward[i].marked && !x.forward[i].forward[i].tail) curr = x = x.forward[i]; } if (curr == null) continue; if (curr.forward[0].tail) { if (curr.tail) continue; else return curr.value; } else return curr.forward[0].value; } } public T FindMin() { if (header.forward[0].tail) throw new NoSuchItemException(); return header.forward[0].value; } public bool IsEmpty() { if (header.forward[0].tail) return true; return false; } private int randomLevel() { Random rng = new Random(Environment.TickCount + Thread.CurrentThread.ManagedThreadId); int level = 0; int p = 1; while (rng.Next(2) < p && level < maxLevel - 1) level = level + 1; return level; } private bool Validate(Node pred, Node succ, int level, T item) { if (succ.tail && !pred.marked && pred.level >= 0 && succ.level >= 0 && pred.forward[level].Equals(succ) && comparer.Compare(pred.value, item) <= 0) return true; if (!succ.tail && !pred.marked && pred.level >= 0 && succ.level >= 0 && !succ.marked && pred.forward[level].Equals(succ) && comparer.Compare(pred.value, item) <= 0 && comparer.Compare(succ.value, item) >= 0) return true; return false; } private bool ValidatePred(Node pred, Node succ, int level) { if (!succ.tail && !pred.marked && pred.level >= 0 && succ.level >= 0 && pred.forward[level].Equals(succ)) return true; return false; } private bool ValidateUnmarked(Node pred, Node succ, int level) { if (!succ.tail && !pred.marked && pred.level >= 0 && succ.level >= 0 && !succ.marked && pred.forward[level].Equals(succ)) return true; return false; } //private bool ValidateMarked(Node pred, Node succ, int level) //{ // if (!succ.tail && !pred.marked && pred.level >= 0 && succ.marked && succ.level >= 0 && succ.pid == Thread.CurrentThread.ManagedThreadId && pred.forward[level].Equals(succ)) // return true; // return false; //} private bool ValidateNode(Node n) { if (!n.tail && n.level >= 0) return true; return false; } private int H(int K, int D) { if (K < 2) K = 2; int H = (int)Math.Log(p) + K; while (H % D != 0) H++; return H; } private int D(bool defvalue) { if (defvalue) return 1; else return (int)Math.Max(1, Math.Floor(Math.Log(Math.Log(p)))); } private int L(int M) { if (M < 1) M = 1; int L = (int)(M * Math.Pow(Math.Log(p), 3)); return L == 0 ? 1 : L; } private Node Spray(int H, int L, int D) { Random rng = new Random(Environment.TickCount + Thread.CurrentThread.ManagedThreadId); Node x = header; do { x = header; int l = H; while (l >= 0) { int j = rng.Next(0, L + 1); while (j > 0 && !x.forward[l].tail) { x = x.forward[l]; j--; } l = l - D; } } while (x.marked || x.level < 0 || x.tail || x.Equals(header)); return x; } } }
c8d020c37cad4af6410fe9372608338ec410b920
C#
mgruesen/patient-portal
/PatientPortal.Api/Services/UserService.cs
2.625
3
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using PatientPortal.Api.Domain; using PatientPortal.Api.Extensions; using PatientPortal.Api.Mappers; using PatientPortal.Api.Models; namespace PatientPortal.Api.Services { public interface IUserService { UserModel Authenticate(string username, string password); IEnumerable<UserModel> GetByIds(Guid[] userIds); Task<UserModel> Update(UserModel user); Task<IEnumerable<Guid>> DeleteByIds(Guid[] userIds); } public class UserService : IUserService { private readonly IUserMapper _userMapper; private readonly IPasswordHash _passwordHash; private readonly PatientPortalDbContext _dbContext; public UserService(IPasswordHash passwordHash, PatientPortalDbContext dbContext, IUserMapper userMapper) { _passwordHash = passwordHash; _dbContext = dbContext; _userMapper = userMapper; } public UserModel Authenticate(string username, string password) { var user = _dbContext.Users.SingleOrDefault(u => u.Username == username); if (user == null) return null; return _passwordHash.Check(user.Password, password) ? _userMapper.MapUserModel(user) : null; } public IEnumerable<UserModel> GetByIds(params Guid[] userIds) { var users = userIds.Length == 0 ? _dbContext.Users.Where(u => !u.IsDeleted) : _dbContext.Users.Where(u => userIds.Contains(u.Id) && !u.IsDeleted); return users.Select(_userMapper.MapUserModel); } public async Task<UserModel> Update(UserModel userModel) { var user = _dbContext.Users .SingleOrDefault(u => u.Id == userModel.Id && !u.IsDeleted); if (user == null) { return null; } else { user.PatientId = userModel.PatientId; user.ProviderId = userModel.ProviderId; user.ContactId = userModel.ContactId; } await _dbContext.SaveChangesAsync(); return _userMapper.MapUserModel(user); } public async Task<IEnumerable<Guid>> DeleteByIds(params Guid[] userIds) { var users = _dbContext.Users .Where(p => userIds.Contains(p.Id) && !p.IsDeleted); var deletedIds = users.Select(p => p.Id).ToList(); foreach (var user in users) user.IsDeleted = true; await _dbContext.SaveChangesAsync(); return deletedIds; } } }
3b6a1ebc76b234e2be9f945a0d7e1d5f7501aeec
C#
royvandertuuk/unleash-client-dotnet
/src/Unleash/IUnleash.cs
2.59375
3
using System; using System.Collections.Generic; namespace Unleash { /// <inheritdoc /> /// <summary> /// Unleash Feature Toggle Service /// </summary> public interface IUnleash : IDisposable { /// <summary> /// Gets a value indicating a feature is available or not. /// </summary> /// <param name="toggleName">The name of the toggle</param> bool IsEnabled(string toggleName); /// <summary> /// Gets a value indicating a feature is available or not. /// </summary> /// <param name="toggleName">The name of the toggle</param> /// <param name="defaultSetting">If a toggle is not found, default fallback setting will be returned. (default: false)</param> /// <returns></returns> bool IsEnabled(string toggleName, bool defaultSetting); /// <summary> /// Gets a value indicating a feature is available or not. /// </summary> /// <param name="toggleName">The name of the toggle</param> /// <param name="properties"> /// Additional properties that are merged with the properties in the <see cref="UnleashContext"/>. /// These properties can be used in custom strategies and enable the strategy to act on runtime values. /// </param> /// <param name="defaultSetting">If a toggle is not found, default fallback setting will be returned. (default: false)</param> /// <returns></returns> bool IsEnabled(string toggleName, Dictionary<string, string> properties, bool defaultSetting = false); } }
07400cf546f2b2b60e7df2876379f3293e8d8b69
C#
olivelliputelli/EsCSharp_2016_17
/SoluzioneEserciziBase/EsFattoriale/Matematica.cs
3.859375
4
using System; namespace EsFattoriale { public static class Matematica { public static ulong Fattoriale(int n) { if (n > 64) //ulong non riesce a contenere 65! throw new ArgumentOutOfRangeException(); ulong fat = 1; for (ulong i = 1; i <= (ulong)n; i++) { fat *= i; } return fat; } /// <summary> /// Fattoriale ricorsivo /// </summary> /// <param name="n">numero compreso tra 1 e 64.</param> /// <returns></returns> public static ulong FattorialeRic(ulong n) { if (n > 64) throw new ArgumentOutOfRangeException(); if (n >= 1) return n * FattorialeRic(n - 1); else return 1; } public static void SpostaTorre(int nDischi, int da, int a, int perMezzoDi) { if (nDischi > 1) { SpostaTorre(nDischi - 1, da, perMezzoDi, a); SpostaDisco(da, a); SpostaTorre(nDischi - 1, perMezzoDi, a, da); } } static void SpostaDisco(int da, int a) { Console.Write($"sposta un disco dalla colonna {da} alla colonna {a}"); Console.ReadLine(); } public static int CoefficienteBinomiale(int n, int k) { if (!(k >= 0 && k <= n)) throw new IndexOutOfRangeException(); return (int) Fattoriale(n) / (int) (Fattoriale(k) * Fattoriale(n - k)); } } }
edba404866b8b8c3f97e1dcd54e4859c61b61c99
C#
angelofgrace/holbertonschool-csharp
/0x03-csharp-hashset_stack_queue_linkedlist/12-linkedlist_insert/12-linkedlist_insert.cs
3.40625
3
using System; using System.Collections.Generic; using System.Linq; class LList { public static LinkedListNode<int> Insert(LinkedList<int> myLList, int n) { LinkedListNode<int> current; if (myLList.First == null) { myLList.AddFirst(n); } current = myLList.First; while (current.Next != null && current.Next.Value < n) { current = current.Next; } if (current == myLList.First && current.Value > n) { myLList.AddFirst(n); } else { myLList.AddAfter(current, n); } current = current.Next; return (current); } }
d1056b1e45f52c59b68f6caa90655192ef7a1884
C#
Miahsmith45/codewars
/Csharp/Holiday viii duty free.cs
2.75
3
// https://www.codewars.com/kata/57e92e91b63b6cbac20001e5/train/csharp public class Kata { public static int DutyFree(int normPrice, int Discount, int hol) => hol * 100 / normPrice / Discount ; }
80413c458beb624123a6a212bba8d8679386a1a6
C#
ccollie/taste.net
/src/Taste/Common/FastMap.cs
2.640625
3
/* * Copyright 2007 and onwards, Sean Owen * * 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. */ namespace Taste.Common { using System; using System.Diagnostics; using System.Collections; using System.Collections.Generic; /** * <p>This is an optimized {@link Map} implementation, based on algorithms described in Knuth's * "Art of Computer Programming", Vol. 3, p. 529.</p> * * <p>It should be faster than {@link java.util.HashMap} in some cases, but not all. Its main feature is * a "max size" and the ability to transparently, efficiently and semi-intelligently evict old entries * when max size is exceeded.</p> * * <p>This is still a work in progress and I'm putting it in CVS so other devs can look at it. * I wouldn't go using it too much yet.</p> * * <p>This class is not a bit thread-safe.</p> * * <p>This implementation does not allow <code>null</code> as a key or value.</p> * * @author Sean Owen * @since 1.5.3 */ public class FastMap<K, V> : IDictionary<K, V>, IEnumerable<KeyValuePair<K,V>>, ICollection<KeyValuePair<K,V>> { /** The largest prime less than 2<sup>31</sup>-1 that is the smaller of a twin prime pair. */ private const int MAX_INT_SMALLER_TWIN_PRIME = 2147482949; public const int NO_MAX_SIZE = int.MaxValue; #region Private Member Variables /** * Dummy object used to represent a key that has been removed. Package-private to allow direct access * by inner classes. No harm in exposing it. */ private static readonly K REMOVED = default(K); private static readonly V NULL_VALUE = default(V); private K[] keys; private V[] values; private int hashSize; private int numEntries; private int numSlotsUsed; private ICollection<K> keyCollection; private ICollection<V> valueCollection; private int maxSize; private BitArray recentlyAccessed; private int generation = 0; #endregion #region Constructor /** * Creates a new {@link FastMap} with default capacity. */ public FastMap() : this(11, NO_MAX_SIZE) { } /** * Creates a new {@link FastMap} whose capacity can accommodate the given number of entries without rehash.</p> * * @param size desired capacity * @param maxSize max capacity * @throws ArgumentException if size is less than 1 or at least half of {@link #MAX_INT_SMALLER_TWIN_PRIME} */ public FastMap(int size, int maxSize) { if (size < 1) { throw new ArgumentException("size must be at least 1"); } if (size >= MAX_INT_SMALLER_TWIN_PRIME / 2) { throw new ArgumentException("size must be less than " + MAX_INT_SMALLER_TWIN_PRIME / 2); } if (maxSize < 1) { throw new ArgumentException("maxSize must be at least 1"); } hashSize = NextTwinPrime(2 * size); keys = new K[hashSize]; values = new V[hashSize]; this.maxSize = maxSize; this.recentlyAccessed = (maxSize == int.MaxValue) ? null : new BitArray(maxSize); } #endregion private int Find(Object key) { int theHashCode = key.GetHashCode() & 0x7FFFFFFF; // make sure it's positive int jump = 1 + theHashCode % (hashSize - 2); int index = theHashCode % hashSize; K currentKey = keys[index]; while (currentKey != null && (currentKey.Equals(REMOVED) || !key.Equals(currentKey))) { if (index < jump) { index += hashSize - jump; } else { index -= jump; } currentKey = keys[index]; } //Debug.Assert(currentKey == null || key.Equals(currentKey)); Debug.WriteIf(index < 0, index); return index; } public V get(Object key) { if (key == null) { return default(V); } int index = Find(key); if (recentlyAccessed != null) { recentlyAccessed[index] = true; } return values[index]; } public bool TryGetValue(K key, out V value) { if (key == null) throw new ArgumentNullException("key"); int index = Find(key); //cc - review if (index >= 0) // added by cc { if (recentlyAccessed != null && index < recentlyAccessed.Length) { recentlyAccessed.Set(index, true); } if (values[index] != null) { value = values[index]; return true; } } // we did not find the slot value = default(V); return false; } public V this[K key] { get { return get((object)key); } set { put(key, value); } } public int Count { get { return numEntries; } } public bool IsEmpty { get { return numEntries == 0; } } public bool ContainsKey(K key) { return key != null && keys[Find(key)] != null; } public bool ContainsValue(V value) { if (value == null) { return false; } foreach (V theValue in values) { if (theValue != null && value.Equals(theValue)) { return true; } } return false; } /** * @throws ArgumentNullException if key or value is null */ public void Add(K key, V value) { if (key == null || value == null) { throw new ArgumentNullException(); } Debug.Assert(numSlotsUsed <= hashSize / 2); if (numSlotsUsed >= hashSize / 2) { GrowAndRehash(); } // Here we may later consider implementing Brent's variation described on page 532 int index = Find(key); if (keys[index] == null) { // If size is limited, if (recentlyAccessed != null && numEntries >= maxSize) { // and we're too large, clear some old-ish entry ClearStaleEntry(index); } Debug.Assert(numEntries < maxSize); keys[index] = key; Debug.Assert(values[index] == null); values[index] = value; numEntries++; numSlotsUsed++; generation++; } else { throw new ArgumentException("The key already exists in the collection"); } } /** * @throws ArgumentNullException if key or value is null */ public V put(K key, V value) { if (key == null || value == null) { throw new ArgumentNullException(); } Debug.Assert(numSlotsUsed <= hashSize / 2); if (numSlotsUsed >= hashSize / 2) { GrowAndRehash(); } // Here we may later consider implementing Brent's variation described on page 532 int index = Find(key); if (keys[index] == null) { // If size is limited, if (recentlyAccessed != null && numEntries >= maxSize) { // and we're too large, clear some old-ish entry ClearStaleEntry(index); } Debug.Assert(numEntries < maxSize); keys[index] = key; Debug.Assert(values[index] == null); values[index] = value; numEntries++; numSlotsUsed++; generation++; return value; } else { V oldValue = values[index]; Debug.Assert(oldValue != null); values[index] = value; generation++; return oldValue; } } private void ClearStaleEntry(int index) { Debug.Assert(keys[index] == null); while (true) { K currentKey; do { Debug.Assert(index >= 0); if (index == 0) { index = hashSize - 1; } else { index--; } currentKey = keys[index]; } while (currentKey == null || currentKey.Equals(REMOVED)); Debug.Assert(recentlyAccessed != null); if (recentlyAccessed[index]) { recentlyAccessed[index] = false; } else { break; } } // Delete the entry keys[index] = REMOVED; numEntries--; Debug.Assert(numEntries >= 0); Debug.Assert(values[index] != null); values[index] = NULL_VALUE; } public void AddAll(IDictionary<K, V> map) { if (map == null) { throw new ArgumentNullException(); } foreach (KeyValuePair<K, V> entry in map) { Add(entry.Key, entry.Value); } } public bool Remove(K key) { if (key == null) { return false; } int index = Find(key); if (keys[index] == null) { return false; } else { keys[index] = REMOVED; numEntries--; Debug.Assert(numEntries >= 0); V oldValue = values[index]; Debug.Assert(oldValue != null); values[index] = NULL_VALUE; // don't decrement numSlotsUsed generation++; return true; } // Could un-set recentlyAccessed's bit but doesn't matter } public void Clear() { numEntries = 0; numSlotsUsed = 0; Array.Clear(keys, 0, keys.Length); Array.Clear(values, 0, values.Length); if (recentlyAccessed != null) { recentlyAccessed.SetAll(false); //recentlyAccessed.Length = 0; } generation++; } public ICollection<K> Keys { get { if (keyCollection == null) { keyCollection = new KeyCollection(this); } return keyCollection; } } public ICollection<V> Values { get { if (valueCollection == null) { valueCollection = new ValueCollection(this); } return valueCollection; } } #region Hashing public void Rehash() { Rehash(hashSize); } private void GrowAndRehash() { if (hashSize >= MAX_INT_SMALLER_TWIN_PRIME >> 1) { throw new IllegalStateException("Can't grow any more"); } Rehash(NextTwinPrime(2 * hashSize)); } private void Rehash(int newHashSize) { K[] oldKeys = keys; V[] oldValues = values; numEntries = 0; numSlotsUsed = 0; if (recentlyAccessed != null) { recentlyAccessed.SetAll(false); } hashSize = newHashSize; keys = new K[hashSize]; values = new V[hashSize]; int length = oldKeys.Length; for (int i = 0; i < length; i++) { K key = oldKeys[i]; if (key != null && !key.Equals(REMOVED)) { Add(key, oldValues[i]); } } } #endregion #region Iteration Helpers private void GotoNext(ref int position) { int length = values.Length; while (position < length && values[position] == null) { position++; } } private bool HasNext(ref int position) { GotoNext(ref position); return position < values.Length; } #endregion #region Simple methods for finding a next larger prime /** * <p>Finds next-largest "twin primes": numbers p and p+2 such that both are prime. Finds the smallest such p such * that the smaller twin, p, is greater than or equal to n. Returns p+2, the larger of the two twins.</p> */ private static int NextTwinPrime(int n) { if (n > MAX_INT_SMALLER_TWIN_PRIME) { throw new ArgumentException(); } int next = NextPrime(n); while (IsNotPrime(next + 2)) { next = NextPrime(next + 4); } return next + 2; } /** * <p>Finds smallest prime p such that p is greater than or equal to n.</p> */ private static int NextPrime(int n) { Debug.Assert(n > 1); // Make sure the number is odd. Is this too clever? n |= 0x1; // There is no problem with overflow since Integer.MAX_INT is prime, as it happens while (IsNotPrime(n)) { n += 2; } return n; } /** * @param n * @return <code>true</code> iff n is not a prime */ private static bool IsNotPrime(int n) { if (n < 2) { throw new ArgumentException(); } if ((n & 0x1) == 0) { // even return true; } int max = 1 + (int)Math.Sqrt((double)n); for (int d = 3; d <= max; d += 2) { if (n % d == 0) { return true; } } return false; } #endregion private void iteratorRemove(int lastNext) { if (lastNext >= values.Length) { throw new NoSuchElementException(); } if (lastNext < 0) { throw new IllegalStateException(); } values[lastNext] = NULL_VALUE; keys[lastNext] = REMOVED; numEntries--; } #region IEnumerator<KeyValuePair<K, V>> [Serializable] public struct KeyValueEnumerator : IEnumerator<KeyValuePair<K, V>>, IDisposable, IDictionaryEnumerator, IEnumerator { FastMap<K, V> map; int position; int stamp; internal KeyValueEnumerator(FastMap<K, V> dictionary) { this.map = dictionary; stamp = dictionary.generation; // The following stanza is identical to IEnumerator.Reset (), // but because of the definite assignment rule, we cannot call it here. position = 0; } public bool MoveNext() { VerifyState(); ++position; return map.HasNext(ref position); } public KeyValuePair<K, V> Current { get { VerifyCurrent(); return new KeyValuePair<K, V>( map.keys[position], map.values[position] ); } } internal K CurrentKey { get { VerifyCurrent(); return map.keys[position]; } } internal V CurrentValue { get { VerifyCurrent(); return map.values[position]; } } object IEnumerator.Current { get { return Current; } } void IEnumerator.Reset() { position = 0; } DictionaryEntry IDictionaryEnumerator.Entry { get { VerifyCurrent(); return new DictionaryEntry( map.keys[position], map.values[position] ); } } object IDictionaryEnumerator.Key { get { VerifyCurrent(); return map.keys[position]; } } object IDictionaryEnumerator.Value { get { VerifyCurrent(); return map.values[position]; } } void VerifyState() { if (map == null) throw new ObjectDisposedException(null); if (map.generation != stamp) throw new InvalidOperationException("out of sync"); } void VerifyCurrent() { VerifyState(); if (position == -1) throw new InvalidOperationException("Current is not valid"); } public void Dispose() { map = null; } } #endregion #region IEnumerable<KeyValuePair<K,V>> Members IEnumerator<KeyValuePair<K, V>> IEnumerable<KeyValuePair<K, V>>.GetEnumerator() { return new KeyValueEnumerator(this); } #endregion #region ICollection<KeyValuePair<K,V>> Members void ICollection<KeyValuePair<K, V>>.Add(KeyValuePair<K, V> item) { Add(item.Key, item.Value); } void ICollection<KeyValuePair<K, V>>.Clear() { throw new Exception("The method or operation is not implemented."); } bool ICollection<KeyValuePair<K, V>>.Contains(KeyValuePair<K, V> item) { int index = Find(item.Key); return ((keys[index] != null) && (values[index] != null)); } void ICollection<KeyValuePair<K, V>>.CopyTo(KeyValuePair<K, V>[] array, int arrayIndex) { if (array == null) throw new ArgumentNullException("array"); if (arrayIndex < 0) throw new ArgumentOutOfRangeException("arrayIndex"); if (array.Length - arrayIndex < this.Count) throw new ArgumentException("Destination array cannot hold the requested elements!"); int position = 0; while (HasNext(ref position)) { array[arrayIndex++] = new KeyValuePair<K, V>(keys[position], values[position++]); } } int ICollection<KeyValuePair<K, V>>.Count { get { return this.Count; } } bool ICollection<KeyValuePair<K, V>>.IsReadOnly { get { return true; } } bool ICollection<KeyValuePair<K, V>>.Remove(KeyValuePair<K, V> item) { return Remove(item.Key); } #endregion #region KeyCollection // This collection is a read only collection [Serializable] public sealed class KeyCollection : ICollection<K>, IEnumerable<K>, ICollection, IEnumerable { FastMap<K, V> map; public KeyCollection(FastMap<K, V> dictionary) { if (dictionary == null) throw new ArgumentNullException("dictionary"); this.map = dictionary; } public void CopyTo(K[] array, int index) { if (array == null) throw new ArgumentNullException("array"); if (index < 0) throw new ArgumentOutOfRangeException("index"); // we want no exception for index==array.Length && dictionary.Count == 0 if (index > array.Length) throw new ArgumentException("index larger than largest valid index of array"); if (array.Length - index < map.Count) throw new ArgumentException("Destination array cannot hold the requested elements!"); int position = 0; while (map.HasNext(ref position)) { array[index++] = map.keys[position++]; } } public Enumerator GetEnumerator() { return new Enumerator(map); } void ICollection<K>.Add(K item) { throw new NotSupportedException("this is a read-only collection"); } void ICollection<K>.Clear() { throw new NotSupportedException("this is a read-only collection"); } bool ICollection<K>.Contains(K item) { return map.ContainsKey(item); } bool ICollection<K>.Remove(K item) { throw new NotSupportedException("this is a read-only collection"); } IEnumerator<K> IEnumerable<K>.GetEnumerator() { //int position = 0; return this.GetEnumerator(); } void ICollection.CopyTo(Array array, int index) { CopyTo((K[])array, index); } IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } public int Count { get { return map.Count; } } bool ICollection<K>.IsReadOnly { get { return true; } } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { return ((ICollection)map).SyncRoot; } } [Serializable] public struct Enumerator : IEnumerator<K>, IDisposable, IEnumerator { FastMap<K, V>.KeyValueEnumerator host_enumerator; internal Enumerator(FastMap<K, V> host) { host_enumerator = new KeyValueEnumerator(host); } public void Dispose() { host_enumerator.Dispose(); } public bool MoveNext() { return host_enumerator.MoveNext(); } public K Current { get { return host_enumerator.CurrentKey; } } object IEnumerator.Current { get { return host_enumerator.CurrentKey; } } void IEnumerator.Reset() { ((IEnumerator)host_enumerator).Reset(); } } } #endregion #region ValueCollection // This collection is a read only collection [Serializable] public sealed class ValueCollection : ICollection<V>, IEnumerable<V>, ICollection, IEnumerable { FastMap<K, V> map; public ValueCollection(FastMap<K, V> map) { if (map == null) throw new ArgumentNullException("dictionary"); this.map = map; } public void CopyTo(V[] array, int index) { if (array == null) throw new ArgumentNullException("array"); if (index < 0) throw new ArgumentOutOfRangeException("index"); // we want no exception for index==array.Length && dictionary.Count == 0 if (index > array.Length) throw new ArgumentException("index larger than largest valid index of array"); if (array.Length - index < map.Count) throw new ArgumentException("Destination array cannot hold the requested elements!"); int position = 0; while (map.HasNext(ref position)) { array[index++] = map.values[position++]; } } public Enumerator GetEnumerator() { return new Enumerator(map); } void ICollection<V>.Add(V item) { throw new NotSupportedException("this is a read-only collection"); } void ICollection<V>.Clear() { throw new NotSupportedException("this is a read-only collection"); } bool ICollection<V>.Contains(V item) { return map.ContainsValue(item); } bool ICollection<V>.Remove(V item) { throw new NotSupportedException("this is a read-only collection"); } IEnumerator<V> IEnumerable<V>.GetEnumerator() { return this.GetEnumerator(); } void ICollection.CopyTo(Array array, int index) { CopyTo((V[])array, index); } IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } public int Count { get { return map.Count; } } bool ICollection<V>.IsReadOnly { get { return true; } } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { return ((ICollection)map).SyncRoot; } } [Serializable] public struct Enumerator : IEnumerator<V>, IDisposable, IEnumerator { FastMap<K, V>.KeyValueEnumerator host_enumerator; internal Enumerator(FastMap<K, V> host) { host_enumerator = new FastMap<K,V>.KeyValueEnumerator(host); } public void Dispose() { host_enumerator.Dispose(); } public bool MoveNext() { return host_enumerator.MoveNext(); } public V Current { get { return host_enumerator.CurrentValue; } } object IEnumerator.Current { get { return host_enumerator.CurrentValue; } } void IEnumerator.Reset() { ((IEnumerator)host_enumerator).Reset(); } } } #endregion #region IEnumerable Members IEnumerator IEnumerable.GetEnumerator() { return new KeyValueEnumerator(this); } #endregion } }
21962a9f44049201e8c4c8d9b40a26476b952f02
C#
wander0220/Linq
/Linq/Program.cs
3.4375
3
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) { List<int> input = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; var output = from i in input where i>5 && i%2 == 0 orderby i ascending select i; foreach( var i in output) { Console.WriteLine(i); } Console.WriteLine("####################"); var output2 = from i in input where i % 2 == 0 select new { A = i * 2, B = i * i, C = 100, name = "사람" + i }; foreach(var i in output2) { Console.WriteLine(i.A); } } } }
946367a426d44d85bfe2d32805e822e022cdc7d0
C#
Kopanskyi/TestTasks
/TestTasks/RailFenceCipher.cs
3.328125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Rail_Fence_Cipher { static class RailFenceCipher { public static string Encode(string stringToEncode, int railsNumber) { if (string.IsNullOrEmpty(stringToEncode)) { return string.Empty; } if (railsNumber < 2) { return stringToEncode; } var symbolsCollection = new List<char>[railsNumber]; for (int i = 0; i < symbolsCollection.Length; i++) { symbolsCollection[i] = new List<char>(); } var rail = 0; var increaseRailNumber = true; foreach (var symbol in stringToEncode) { symbolsCollection[rail].Add(symbol); if (rail == railsNumber - 1) { increaseRailNumber = false; } if (rail == 0 && !increaseRailNumber) { increaseRailNumber = true; } if (increaseRailNumber && rail < railsNumber - 1) { rail++; } if (!increaseRailNumber && rail > 0) { rail--; } } return EncodedToString(symbolsCollection); } public static string Decode(string stringToDecode, int railsNumber) { if (string.IsNullOrEmpty(stringToDecode)) { return string.Empty; } if (railsNumber < 2) { return stringToDecode; } var symbolsPerLineCount = new int[railsNumber]; for (int i = 0; i < symbolsPerLineCount.Length; i++) { symbolsPerLineCount[i] = 0; } var rail = 0; var increaseRailNumber = true; foreach (var symbol in stringToDecode) { symbolsPerLineCount[rail]++; if (rail == railsNumber - 1) { increaseRailNumber = false; } if (rail == 0 && !increaseRailNumber) { increaseRailNumber = true; } if (increaseRailNumber && rail < railsNumber - 1) { rail++; } if (!increaseRailNumber && rail > 0) { rail--; } } var symbolsCollection = new List<char>[railsNumber]; for (int startIndex = 0, i = 0; i < symbolsCollection.Length; i++) { symbolsCollection[i] = new List<char>(); symbolsCollection[i].AddRange(stringToDecode.Substring(startIndex, symbolsPerLineCount[i])); startIndex += symbolsPerLineCount[i]; } return DecodedToString(symbolsCollection, symbolsPerLineCount); } private static string EncodedToString(IEnumerable<char>[] symbolsCollection) { var text = new StringBuilder(); foreach (var symbolList in symbolsCollection) { foreach (var symbol in symbolList) { text.Append(symbol); } } return text.ToString(); } private static string DecodedToString(IList<char>[] symbolsCollection, IList<int> symbolsPerLineCount) { var totalSymbolsCount = 0; for (var i = 0; i < symbolsPerLineCount.Count(); i++) { totalSymbolsCount += symbolsPerLineCount[i]; symbolsPerLineCount[i] = 0; } var text = new StringBuilder(); var railsNumber = symbolsCollection.Length; var increaseRailNumber = true; for (int rail = 0; text.Length < totalSymbolsCount; ) { text.Append(symbolsCollection[rail][symbolsPerLineCount[rail]]); symbolsPerLineCount[rail]++; if (rail == railsNumber - 1) { increaseRailNumber = false; } if (rail == 0 && !increaseRailNumber) { increaseRailNumber = true; } if (increaseRailNumber && rail < railsNumber - 1) { rail++; } if (!increaseRailNumber && rail > 0) { rail--; } } return text.ToString(); } } }
9538ec8ff4e518f7fc86793e14044a0dc997af8e
C#
rohanvraju/apple-picker
/Assets/Scripts/PlayerMovement.cs
2.515625
3
using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; using UnityEngine; public class PlayerMovement : MonoBehaviour { public float moveSpeed; public GameObject KOstars; public float maxSpeed = 5f; private Vector3 input; private bool isHit = false;//if player is hit by enemy private bool isAlive = true;//if player is still alive private GameController gameController; // Start is called before the first frame update void Start() { GameObject controller = GameObject.FindWithTag("GameController"); if(controller != null) { gameController = controller.GetComponent<GameController>(); } else { Debug.Log("Couldn't find GameController"); } } // Update is called once per frame void Update() { input = new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical")); //allow player to move until hit by enemy if (!isHit) { if (GetComponent<Rigidbody>().velocity.magnitude < maxSpeed) { GetComponent<Rigidbody>().AddForce(input * moveSpeed); } } //LOSE CONDITION: if player falls off map if(this.transform.position.y < -0.25 && isAlive) { Debug.Log("Fell off map"); knockOut(); isAlive = false; } //print(input); } void OnCollisionEnter(Collision other) { if(other.transform.tag == "Enemy") { Debug.Log("Hit an enemy"); knockOut(); } else if(other.transform.tag == "Tree") { Debug.Log("tree"); gameController.addScore(1); } } void OnTriggerEnter(Collider other) { if(other.transform.tag == "Goal") { Debug.Log("Reached goal"); GameController.CompleteLevel(); } } void knockOut() { Instantiate(KOstars, this.transform.position, Quaternion.identity); isHit = true; } }
aaabb04d257d481399003ed1ce1e929f7379a785
C#
RagingKore/Raging.Toolbox
/Raging.Toolbox/Net/RouteAttribute.cs
2.609375
3
using System; namespace Raging.Toolbox.Net { [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] public class RouteAttribute : Attribute { public RouteAttribute(string address) { Guard.NullOrWhiteSpace(() => address); this.Address = address; } public RouteAttribute(string address, string name) : this(address) { Guard.NullOrWhiteSpace(() => name); this.Name = name; } public RouteAttribute(string address, string name, string queryString) : this(address, name) { this.QueryString = queryString; } public string Name { get; private set; } public string Address { get; private set; } public string QueryString { get; private set; } } }
bcf93c4c3fbfcc742837239c762855a114768a12
C#
shendongnian/download4
/first_version_download2/102144-6936197-15197666-2.cs
3.140625
3
public class Node { abstract void print(); } public class AddExpression : Node { Node Left; Node Right; virtual void print() { Left.Print(); Console.WriteLine("+"); Right.Print(); } }
7f3d8a94cdee8f540c7855bbfd46520c5059b804
C#
n4n0byte/LaraBar
/Topic4/Topic4/Services/Utility/CaptainsLogger.cs
2.59375
3
using System; using System.Collections.Generic; using System.Linq; using System.Web; using NLog; namespace Topic4.Services.Utility { public class CaptainsLogger : ILogger { private static CaptainsLogger _instance; private static Logger _logger; public static CaptainsLogger getInstace() { return _instance ?? (_instance = new CaptainsLogger()); } public static Logger getLogger() { return LogManager.GetLogger("loggerRules"); } public void Debug(string message, string arg = null) { if (arg == null) getLogger().Debug(message); else { getLogger().Debug(message, arg); } } public void Info(string message, string arg = null) { if (arg == null) getLogger().Info(message); else { getLogger().Info(message, arg); } } public void Warning(string message, string arg = null) { if (arg == null) getLogger().Warn(message); else { getLogger().Warn(message, arg); } } public void Error(string message, string arg = null) { if (arg == null) getLogger().Error(message); else { getLogger().Error(message, arg); } } } }
2599d61e79e555a9403108d4e7792ec47f0ffb9e
C#
HassanNahhal/CS_Proj
/SourceCode/ConsoleApplication1/ConsoleApplication1/GameBoard.cs
2.921875
3
/* GameBoard.cs * Final Project * Revision History * Changho Choi, 2015.07.28: Created */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Diagnostics; namespace Monopoly { public class GameBoard { const int NUM_OF_CELL = 40; const int FIX_CELL_PRICE = 2000; const int FIX_RENT_PRICE = 500; const int GOCELL_INDEX = 0; const int INCOMETAXCELL_INDEX = 4; const int JAILCELL_INDEX = 10; const int LOTCELL_INDEX = 20; const int GOTOJAIL_INDEX = 30; List<Cell> cells = new List<Cell> (); public GameBoard () { for ( int index = 0 ; index < NUM_OF_CELL ; index++ ) { switch (index) { case GOCELL_INDEX: cells.Add (new GoCell(index)); break; case INCOMETAXCELL_INDEX: cells.Add (new IncomeTaxCell(index)); break; case JAILCELL_INDEX: cells.Add (new JailCell(index)); break; case LOTCELL_INDEX: cells.Add (new LotCell(index)); break; case GOTOJAIL_INDEX : cells.Add(new GoToJailCell(index, GetCell(JAILCELL_INDEX))); break; default: cells.Add(new PropertyCell(index, FIX_CELL_PRICE, FIX_RENT_PRICE)); break; } } } public Cell MoveToAnotherCell (Cell curPosition , int distance , out bool isTurn ) { int newIndex; newIndex = ( curPosition.Index) + distance; if ( newIndex >= NUM_OF_CELL ) { isTurn = true; newIndex = newIndex - NUM_OF_CELL; } else { isTurn = false; } return cells.ElementAt ( newIndex ); } public Cell GetCell ( int index ) { return cells.ElementAt ( index); } public int GetCellNumber ( Cell curPosition ) { return curPosition.Index; } public void GetPropertiesInMonopoly () { //Not Need, Will be erased } public Cell QueryCell (String cellName) { return cells.Find(item => item.CellName.Equals(cellName)); } public int [] QueryCellIndex ( Player queryPlayer ) { int [] indexArrary = new int [ NUM_OF_CELL ]; int j = 0; for ( int i = 0 ; i < NUM_OF_CELL ; i++ ) { if ( cells.ElementAt ( i ).GetOwner () == queryPlayer ) { indexArrary [ j++ ] = i; } } return indexArrary; } } }
b8ac3d7b6eaee8bf834f56b0bdc10fa34aee8e7b
C#
datvtp/CarSales
/Source Code/CarManagement/DataSource/daos/CustomerDAO.cs
2.8125
3
using DataSource.dtos; using DataSource.utils; using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DataSource.daos { public class CustomerDAO { public List<CustomerDTO> GetListCustomer() { List<CustomerDTO> list = null; string SQL = "SELECT ID, Fullname, Phone, Email FROM Customers"; SqlConnection cnn = DBUtils.GetConnection(); SqlCommand cmd = new SqlCommand(SQL, cnn); try { if (cnn.State == ConnectionState.Closed) { cnn.Open(); SqlDataReader rd = cmd.ExecuteReader(CommandBehavior.CloseConnection); if (rd.HasRows) { while (rd.Read()) { if (list == null) list = new List<CustomerDTO>(); CustomerDTO cusDTO = new CustomerDTO { ID = rd.GetInt32(0), Fullname = rd.GetString(1), Phone = rd.GetString(2), Email = rd.GetString(3) }; list.Add(cusDTO); } } } } catch (SqlException ex) { throw new Exception(ex.Message); } return list; } public String FindNameByID(int id) { string name = null; string SQL = "SELECT Fullname FROM Customers WHERE ID = @ID"; SqlConnection cnn = DBUtils.GetConnection(); SqlCommand cmd = new SqlCommand(SQL, cnn); cmd.Parameters.AddWithValue("@ID", id); try { if (cnn.State == ConnectionState.Closed) { cnn.Open(); SqlDataReader rd = cmd.ExecuteReader(CommandBehavior.CloseConnection); if (rd.HasRows) { if (rd.Read()) { name = rd.GetString(0); } } } } catch (SqlException ex) { throw new Exception(ex.Message); } return name; } public CustomerDTO FindByPhone(string phone) { CustomerDTO result = null; string SQL = "SELECT ID, Fullname, Email FROM Customers WHERE Phone = @Phone"; SqlConnection cnn = DBUtils.GetConnection(); SqlCommand cmd = new SqlCommand(SQL, cnn); cmd.Parameters.AddWithValue("@Phone", phone); try { if (cnn.State == ConnectionState.Closed) { cnn.Open(); SqlDataReader rd = cmd.ExecuteReader(CommandBehavior.CloseConnection); if (rd.HasRows) { if (rd.Read()) { result = new CustomerDTO { ID = rd.GetInt32(0), Fullname = rd.GetString(1), Email = rd.GetString(2), Phone = phone }; } } } } catch (SqlException ex) { throw new Exception(ex.Message); } return result; } public int CreateCustomer(CustomerDTO cusDTO) { int result = -1; string SQL = "INSERT INTO Customers(Fullname, Phone, Email) VALUES(@Fullname, @Phone, @Email); " + "SELECT SCOPE_IDENTITY()"; SqlConnection cnn = DBUtils.GetConnection(); SqlCommand cmd = new SqlCommand(SQL, cnn); cmd.Parameters.AddWithValue("@Fullname", cusDTO.Fullname); cmd.Parameters.AddWithValue("@Phone", cusDTO.Phone); cmd.Parameters.AddWithValue("@Email", cusDTO.Email); try { if (cnn.State == ConnectionState.Closed) cnn.Open(); result = Convert.ToInt32(cmd.ExecuteScalar()); } catch (Exception ex) { throw new Exception(ex.Message); } finally { if (cnn.State == ConnectionState.Open) { cnn.Close(); } } return result; } } }
3607c5358b8d3730f786569015232ced9580e762
C#
jcanderson195/AnimalShelter
/AnimalShelter/SystemOperations.cs
3.328125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AnimalShelter { class SystemOperations { Dog dog = new Dog(); Cat cat = new Cat(); public SystemOperations() { } public void Introduction() { Console.WriteLine("Welcome DevCodeCamp Animal Shelter!"); Console.WriteLine("----------------------"); } public void SystemFlow() { Console.WriteLine("Are you looking to adopt a pet or donate an animal?"); Console.WriteLine("1. Adopt a pet"); Console.WriteLine("2. Donate an animal"); Console.WriteLine("3. Other"); int choice; choice = Convert.ToInt32(Console.ReadLine()); if (choice == 1) { Console.WriteLine("Are you adopting a dog or a cat?"); Console.WriteLine("1. Dog"); Console.WriteLine("2. Cat"); int choice2 = Convert.ToInt32(Console.ReadLine()); if (choice2 == 1) { dog.AdoptDogOption(); SystemFlow(); } else if (choice2 == 2) { cat.AdoptCatOption(); SystemFlow(); } else { Console.WriteLine("Sorry I don't recognize that command. Please enter the numerical value associated with your decision."); SystemFlow(); } } else if(choice == 2) { Console.WriteLine("Are you donating a dog or a cat?"); Console.WriteLine("1. Dog"); Console.WriteLine("2. Cat"); int choice2 = Convert.ToInt32(Console.ReadLine()); if (choice2 == 1) { dog.DonateDogOption(); SystemFlow(); } else if (choice2 == 2) { cat.DonateCatOption(); SystemFlow(); } else { Console.WriteLine("Sorry I don't recognize that command. Please enter the numerical value associated with your decision."); SystemFlow(); } } else if (choice == 3) { Console.WriteLine("What are you here for then?"); Console.WriteLine("1. View Animals"); Console.WriteLine("2.Exit"); Console.WriteLine("----------------------"); int choice3; choice3 = Convert.ToInt32(Console.ReadLine()); if (choice3 == 1) { Console.WriteLine("----------------------"); dog.DisplayListOfDogs(); Console.WriteLine("----------------------"); dog.DisplayShotStatusForDogs(); Console.WriteLine("----------------------"); Console.WriteLine("----------------------"); cat.DisplayListOfCats(); Console.WriteLine("----------------------"); cat.DisplayShotStatusForCats(); Console.WriteLine("----------------------"); SystemFlow(); } else if (choice3 == 2) { Console.WriteLine("Thank you for visiting DevCodeCamp Animal Shelter!"); Environment.Exit(0); } else { Console.WriteLine("Sorry I don't recgnize that command. Please enter the numerical value associated with your decision."); SystemFlow(); } } else { Console.WriteLine("Sorry I don't recgnize that command. Please enter the numerical value associated with your decision."); SystemFlow(); } } } }
0a0f659e45d25788183a8c4859749f8e2851ebdb
C#
Hual/LetterInvaders
/LetterInvaders/Invader.cs
3.171875
3
using System; using System.Collections.Generic; using System.Text; namespace LetterInvaders { class Invader : Entity { private ulong m_lastMoved; private Random seed; public ulong LastMoved { get { return m_lastMoved; } } public Invader(int x, int y) : base(x, y) { seed = new Random(); int multiplier = seed.Next(2); Character = (char)seed.Next(0x41 + 0x20 * multiplier, 0x5A + 0x20 * multiplier); Colour = (ConsoleColor)seed.Next(1, 15); m_lastMoved = 0; } public void step(ulong tickCount) { if (tickCount - m_lastMoved > 4) { stepDown(); m_lastMoved = tickCount; } } } }
03bfc917f04b61dc93fa60cfe2f81b594fa323dd
C#
manitra/dependency-reader
/src/DependencyReader.CLI/IStyleManager.cs
2.515625
3
using DependencyReader.CLI.Entities; namespace DependencyReader.CLI { /// <summary> /// Provides methods to set the Console style using semantics /// </summary> public interface IStyleManager { /// <summary> /// Set the style of the console /// </summary> /// <param name="style"></param> /// <param name="group"></param> void Set(Style style, StyleGroup group); } }
e5358bf79ba5f8c04a5661dea3757edf6c85d0da
C#
eSuiteInterfaceBootcamp/CS_eSuiteApiWrapper
/eSuite API Wrapper/RestApi.cs
2.59375
3
using System; using System.IO; using System.Net; using System.Text; namespace eSuiteApiWrapper { public class RestApi { private string _baseURL; private string _userAuthToken; public RestApi(string baseURL, string userAuthToken) { if (baseURL.EndsWith("/") == false) { baseURL += "/"; } if (baseURL.Contains("ws/rest/ecourt/") == false) { baseURL = baseURL + "ws/rest/ecourt/"; } _baseURL = baseURL; _userAuthToken = userAuthToken; } public RestApi(string baseURL, string username, string password) { _baseURL = baseURL; _userAuthToken = GetUserAuthToken(username, password); } public static string GetUserAuthToken(string username, string password) { return "Basic " + Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password)); } public string GetApiVersion() { return getData("apiVersion"); } public string GetEntitiesList() { return getData("entities"); } public string GetData(string path) { return getData(path); } public string InsertData(string path, string jsonData) { return postData(path, jsonData); } public string InsertData(string path, string jsonData, out int newId) { string result = postData(path, jsonData); newId = parseId(result); return result; } public string UpdateData(string path, string jsonData) { return putData(path, jsonData); } public void DeleteData(string path) { deleteData(path); } public string SearchByGet(string path, out int id) { path = "search/" + path; string result = getData(path); id = parseId(result); return result; } private WebRequest getWebRequest(string url, string method, string contentType) { WebRequest request = WebRequest.Create(url); if (request is HttpWebRequest == false) { throw new Exception("Incorrect WebRequest type returned."); } request.Method = method; request.ContentType = contentType; request.Headers.Add("Authorization", _userAuthToken); request.Timeout = 10000; return request; } private string getApiResponse(WebRequest request, string jsonData = null) { if (jsonData != null) { byte[] jsonBytes = Encoding.GetEncoding("iso-8859-1").GetBytes(jsonData); request.ContentLength = jsonBytes.Length; using (var WriteStream = request.GetRequestStream()) { WriteStream.Write(jsonBytes, 0, jsonBytes.Length); } } using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { if (response.StatusCode != HttpStatusCode.OK) { throw new Exception("API call failed with status code: " + response.StatusCode + "."); } using (var stream = response.GetResponseStream()) { if (stream != null) { using (StreamReader reader = new StreamReader(stream)) { string data = reader.ReadToEnd(); return data; } } else { return null; } } } } private string getData(string subUrl) { return getApiResponse(getWebRequest(_baseURL + subUrl, "GET", "text/xml")); } private string postData(string subUrl, string jsonData) { return getApiResponse(getWebRequest(_baseURL + subUrl, "POST", "application/json"), jsonData); } private string putData(string subUrl, string jsonData) { return getApiResponse(getWebRequest(_baseURL + subUrl, "PUT", "application/json"), jsonData); } private void deleteData(string subUrl) { getApiResponse(getWebRequest(_baseURL + subUrl, "DELETE", "application/json")); } private int parseId(string json) { int id = -1; int startId = json.IndexOf(",\"id\":"); if (startId > 0) { startId += 6; int endId = json.IndexOf(",", startId); if (endId > 0 && endId - startId < 5) { string idString = json.Substring(startId, endId - startId); if (!int.TryParse(idString, out id)) { id = -1; } } } return id; } } }
9bd11c7d2bccefffb4d37a071e1e5004b6925e16
C#
BenBtg/HybridStats
/HybridStats.Core/ViewModels/BaseViewModel.cs
2.75
3
using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using HybridStats.Core.ViewModels; namespace HybridStats.Core { public abstract class BaseViewModel : BaseNotifyPropertyChanged { public virtual string Title { get; set; } bool _isBusy; /// <summary> /// Gets or sets whether the ViewModel is busy. /// </summary> /// <value><c>true</c> if is busy; otherwise, <c>false</c>.</value> public bool IsBusy { get { return _isBusy; } set { if (RaiseAndUpdate(ref _isBusy, value)) Raise(nameof(IsNotBusy)); } } /// <summary> /// Gets a value indicating whether the ViewModel is not busy. /// </summary> /// <value><c>true</c> if is not busy; otherwise, <c>false</c>.</value> public bool IsNotBusy => !IsBusy; /// <summary> /// Initialilzes the ViewModel. /// </summary> /// <returns>Task with result.</returns> public virtual Task InitAsync() => Task.FromResult(true); } }
7d1b97bb1de3cb937f0d963bf03471201bbeefb2
C#
KondoSuguru/LoopGame
/LoopGame/LoopGame/Utility/Timer.cs
3.0625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Xna.Framework; namespace LoopGame.Utility { abstract class Timer { protected float mLimitTime; protected float mCurrentTime; public Timer(float second) { mLimitTime = 60 * second; } public Timer() : this(1) { } public abstract void Initialize(); public abstract void Update(GameTime gameTime); public abstract bool IsTime(); public abstract float Rate(); public void SetTime(float second) { mLimitTime = 60 * second; } public float Now() { return mCurrentTime / 60f; } } }
47040d0b0e91fb2e4097fda341b709ffa0a62f36
C#
senolakkas/ferrybooking
/ferrybooking/ByteCore.FerryBooking.Core/Dto/SeasonDto.cs
2.671875
3
using System; namespace ByteCore.FerryBooking.Core { [Serializable] public partial class SeasonDto { #region Fields private System.Int32 _SeasonID; private System.Int32? _OperatorId; private System.Int32? _StartMonth; private System.Int32? _StartDay; private System.Int32? _EndMonth; private System.Int32? _EndDay; #endregion #region Constructor public SeasonDto() { } public SeasonDto(Season season) { _SeasonID = season.ID; _OperatorId = season.OperatorId; _StartMonth = season.StartMonth; _StartDay = season.StartDay; _EndMonth = season.EndMonth; _EndDay = season.EndDay; } #endregion #region Properties public virtual System.Int32 SeasonID { get { return _SeasonID; } set { _SeasonID = value;} } public virtual System.Int32? OperatorId { get { return _OperatorId; } set { _OperatorId = value;} } public virtual System.Int32? StartMonth { get { return _StartMonth; } set { _StartMonth = value;} } public virtual System.Int32? StartDay { get { return _StartDay; } set { _StartDay = value;} } public virtual System.Int32? EndMonth { get { return _EndMonth; } set { _EndMonth = value;} } public virtual System.Int32? EndDay { get { return _EndDay; } set { _EndDay = value;} } #endregion } }
d011b29370be188dc1db8d400e4be715c92a183f
C#
lohbot/GLOH_Source
/Assembly-CSharp-firstpass/NkValueParse.cs
2.84375
3
using System; using System.Collections.Generic; public class NkValueParse<Type_> { private Dictionary<string, Type_> m_kDicValue; public NkValueParse() { this.m_kDicValue = new Dictionary<string, Type_>(); } ~NkValueParse() { } public void InsertCodeValue(string strCode, Type_ tCodeValue) { string key = strCode.ToUpper(); if (this.m_kDicValue.ContainsKey(key)) { return; } this.m_kDicValue.Add(key, tCodeValue); } public Type_ GetValue(string strCode) { Type_ result = default(Type_); if (!this.m_kDicValue.TryGetValue(strCode.ToUpper(), out result)) { return result; } return result; } public string[] GetKeys() { Dictionary<string, Type_>.KeyCollection keys = this.m_kDicValue.Keys; string[] array = new string[keys.Count]; int num = 0; foreach (string current in keys) { array[num] = current; num++; if (num >= keys.Count) { break; } } return array; } }
721a23c63aa04fec9662b47b239385bf665a2bcf
C#
natinusala/Steam-Apps-Manager
/Steam Apps Manager/SteamUtils/App.cs
2.703125
3
using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Steam_Apps_Manager.SteamUtils { public enum SteamAppStatus { READY_TO_MOVE, UPDATE_NEEDED } public class App { private string manifestPath; public uint appId { get; private set; } public string appName { get; private set; } private string installDir; private string fullInstallDir; private int appState; public long sizeOnDisk { get; private set; } public LibraryFolder folder { get; private set; } public App(string manifestPath, LibraryFolder directory) { this.manifestPath = manifestPath; this.folder = directory; ACFNode appState = (ACFNode) ACFNode.ParseACF(manifestPath)["AppState"]; this.appId = uint.Parse(((string)appState["appid"])); this.appName = (string)appState["name"]; this.installDir = (string)appState["installdir"]; this.fullInstallDir = this.folder.path + "\\common\\" + installDir; this.appState = int.Parse((string)appState["StateFlags"]); if (appState.ContainsKey("SizeOnDisk")) { sizeOnDisk = long.Parse(((string)appState["SizeOnDisk"])); } else { this.sizeOnDisk = Utils.GetDirectorySize(this.fullInstallDir); } } public string GetManifestPath() { return this.folder.path + "\\" + "appmanifest_" + this.appId + ".acf"; } public SteamAppStatus GetStatus() { return this.appState == 4 ? SteamAppStatus.READY_TO_MOVE : SteamAppStatus.UPDATE_NEEDED; } public void MoveAppFiles(LibraryFolder newFolder, BackgroundWorker worker) { try { string newFullDir = newFolder.path + "\\common\\" + installDir; foreach (string path in Directory.GetDirectories(this.fullInstallDir, "*", SearchOption.AllDirectories)) { Directory.CreateDirectory(path.Replace(fullInstallDir, newFullDir)); } foreach (string file in Directory.GetFiles(fullInstallDir, "*.*", SearchOption.AllDirectories)) { FileInfo info = new FileInfo(file); long fileSize = info.Length; File.Move(file, file.Replace(fullInstallDir, newFullDir)); if (worker != null && fileSize != 0) { worker.ReportProgress((int)Math.Round(((double)fileSize / (double)sizeOnDisk) * 1000.0f)); } } worker.ReportProgress(-1); Directory.Delete(this.fullInstallDir, true); this.folder = newFolder; this.fullInstallDir = this.folder.path + "\\common\\" + installDir; } catch (System.IO.DirectoryNotFoundException) { return; } } } }
1dd7e2ccc5753e527a97c8d867e487816d15e5d5
C#
evan-erdos/thermonuclear-darts
/Assets/Scripts/Elevator.cs
2.515625
3
using UnityEngine; using System.Collections; public class Elevator : MonoBehaviour { bool once; Vector3 speed; [SerializeField] float height; Vector3 initialPosition; void Start() { initialPosition = transform.position; } void OnTriggerEnter(Collider other) { if (!once && other.tag=="Player") StartCoroutine(Rising()); } IEnumerator Rising() { once = true; yield return new WaitForSeconds(0.5f); while (transform.position.y<(initialPosition.y+height)) { yield return new WaitForFixedUpdate(); transform.position = Vector3.SmoothDamp( transform.position, initialPosition+(Vector3.up*(height+1)), ref speed, 2f, Time.fixedDeltaTime*8f); } } }
44a5667107073d24570d47007c46d418c0763c50
C#
ThomasPiskol/battleship
/Network/GetIPAddress.cs
2.921875
3
using System; using System.Collections.Generic; using System.Net; using System.Net.NetworkInformation; using System.Net.Sockets; using System.Text; namespace Network { public class GetIPAddress { public static string GetHostName() { UnicastIPAddressInformation localIP = FindLocalIp(); if (localIP == null) { return Environment.MachineName; } if (localIP.Address.AddressFamily == AddressFamily.InterNetworkV6) { return $"[{localIP.Address}]"; } return localIP.Address.ToString(); } public static UnicastIPAddressInformation FindLocalIp() { UnicastIPAddressInformation bestGuess = null; NetworkInterface[] networkInterfaces = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface network in networkInterfaces) { if (network.OperationalStatus != OperationalStatus.Up) { continue; } IPInterfaceProperties properties = network.GetIPProperties(); if (properties.GatewayAddresses.Count == 0) { continue; } foreach (UnicastIPAddressInformation address in properties.UnicastAddresses) { if (address.Address.AddressFamily != AddressFamily.InterNetwork && address.Address.AddressFamily != AddressFamily.InterNetworkV6) { continue; } if (IPAddress.IsLoopback(address.Address)) { continue; } if (!address.IsDnsEligible && bestGuess == null) { bestGuess = address; continue; } if (address.PrefixOrigin == PrefixOrigin.Dhcp || address.PrefixOrigin == PrefixOrigin.RouterAdvertisement) { if (bestGuess?.IsDnsEligible != true) { bestGuess = address; continue; } } } } return bestGuess; } } }
21ad0292c88e622247a58fecb1daca45beb40a56
C#
Cysharp/MagicOnion
/src/MagicOnion.Client.Unity/Assets/Scripts/MessagePack/Resolvers/CachingFormatterResolver.cs
2.59375
3
// Copyright (c) All contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using MessagePack.Formatters; using MessagePack.Internal; namespace MessagePack.Resolvers { /// <summary> /// A base class for <see cref="IFormatterResolver"/> classes that want to cache their responses for perf reasons. /// </summary> internal abstract class CachingFormatterResolver : IFormatterResolver { /// <summary> /// The cache of types to their formatters. /// </summary> private readonly ThreadsafeTypeKeyHashTable<IMessagePackFormatter> formatters = new ThreadsafeTypeKeyHashTable<IMessagePackFormatter>(); /// <inheritdoc /> public IMessagePackFormatter<T> GetFormatter<T>() { if (!this.formatters.TryGetValue(typeof(T), out IMessagePackFormatter formatter)) { formatter = this.GetFormatterCore<T>(); this.formatters.TryAdd(typeof(T), formatter); } return (IMessagePackFormatter<T>)formatter; } /// <summary> /// Looks up a formatter for a type that has not been previously cached. /// </summary> /// <typeparam name="T">The type to be formatted.</typeparam> /// <returns>The formatter to use, or <c>null</c> if none found.</returns> protected abstract IMessagePackFormatter<T> GetFormatterCore<T>(); } }
cd06c1da36357697f1fbb6b0af7b90ee4bd8565b
C#
samuelsoares27/Jogo-da-matem-tica
/Jogo/Jogador.cs
2.625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Drawing; namespace Jogo { public class Jogador { private string nome; private int ponto; private Bitmap foto; private string dtinicio; public string Nome { get { return nome; } set { nome = value; } } public int Ponto { get { return ponto; } set { ponto = value; } } public Bitmap Foto { get { return foto; } set { foto = value; } } public string Dtinicio { get { return dtinicio; } set { dtinicio = value; } } public Jogador(){} } }
b520a70a4d18c5697a9ac0507efaf1b7a722b083
C#
Andrewsiii/msaproject
/msaproject/Data/AppDbContext.cs
2.515625
3
using Microsoft.EntityFrameworkCore; using msaproject.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace msaproject.Data { public class AppDbContext: DbContext { public AppDbContext(DbContextOptions options) : base(options) { } public DbSet<Character> Characters { get; set; } public DbSet<Town> Towns { get; set; } public DbSet<Comment> Comments { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Town>() .HasOne(t => t.Character) .WithMany(c => c.Towns) .HasForeignKey(t => t.CharacterId) .OnDelete(DeleteBehavior.NoAction); modelBuilder.Entity<Comment>() .HasOne(c => c.Character) .WithMany(s => s.Comments) .HasForeignKey(c => c.CharacterId) .OnDelete(DeleteBehavior.NoAction); modelBuilder.Entity<Comment>() .HasOne(c => c.Town) .WithMany(p => p.Comments) .HasForeignKey(c => c.TownId); } } }
0e602c45766f4abcde102efc96e145c2ff4a61d7
C#
eliasmichalczuk/study
/repos/Alura.Filmes/Alura.Filmes.App/ProgramParaFilmes.cs
2.734375
3
using Alura.Filmes.App.Dados; using Alura.Filmes.App.Extensions; using Alura.Filmes.App.Negocio; using System; using Microsoft.EntityFrameworkCore; using System.Linq; namespace Alura.Filmes.App { class ProgramParaFilmes { static void Main3(string[] args) { using(var context = new AluraFilmesContexto()) { context.LogSQLToConsole(); //foreach(var filme in context.Filmes) //{ // Console.WriteLine(filme); //} //foreach (var elenco in context.Elenco) //{ // var entidade = context.Entry(elenco); // var filmid = entidade.Property("film_id").CurrentValue; // var actorid = entidade.Property("actor_id").CurrentValue; // var lastUp = entidade.Property("last_update").CurrentValue; // Console.WriteLine(elenco); // Console.WriteLine($"Filme {filmid}, Ator {actorid}, lastup {lastUp}"); //} var filme = context.Filmes .Include(f => f.Atores)//join com tabela atores .ThenInclude(fa => fa.Ator) .First(); //aqui foi apenas criado lista de atores em filme, nao foi criado lista de filme em atores //assim o ef core implicita que é relacionamento de muitos para 1 //ao inves de n pra n //cria shadow property para 1 filme //necessario criarlista de filmeAtor Console.WriteLine("Elenco: "); foreach(var ator in filme.Atores) { Console.WriteLine(ator.Ator); } } } } //this //modelBuilder.Entity<Raca>() //.ToTable("lotr_races"); //modelBuilder.Entity<Raca>() //.Property(r => r.Id) //.HasColumnName("race_id"); //modelBuilder.Entity<Raca>() //.Property(r => r.Nome) //.HasColumnName("race_name") //.IsRequired(); //same as this //[Table("lotr_races")] //public class Raca //{ // [Column("race_id")] // public int Id { get; set; } // [Required] // [Column("race_name", TypeName = "varchar(60)")] // public string Nome { get; set; } }
b3504970731ab69568df5b3dc6b82e804055794a
C#
Loopc/Loopc
/Foundation/Loopc.Foundation/Log/LogManager.cs
2.65625
3
using System; using log4net; using log4net.Config; namespace Loopc.Foundation.Log { public class LogManager { private static ILog _log; private static ILog Log { get { if (_log == null) { XmlConfigurator.Configure(); _log = log4net.LogManager.GetLogger("Loopc.Log"); } return _log; } } public static void Error(string message) { if (Log.IsErrorEnabled) { Log.Error(message); } } public static void Error(Exception ex) { if (Log.IsErrorEnabled) { Log.Error(ex.ToString()); } } public static void Debug(string message) { if (Log.IsDebugEnabled) { Log.Debug(message); } } public static void Fatal(string message) { if (Log.IsFatalEnabled) { Log.Fatal(message); } } public static void Info(string message) { if (Log.IsInfoEnabled) { Log.Info(message); } } public static void Warn(string message) { if (Log.IsWarnEnabled) { Log.Warn(message); } } public static string NewLogSerial() { var maxSerialLength = 10; var now = DateTime.Now; var serial = (now - now.Date).Ticks.ToString("x").ToUpper(); serial = new String('0', maxSerialLength - serial.Length) + serial; return String.Format("{0}-{1:yyyyMMdd}-{2}", "E", now, serial); } } }
d67ec4a27d09044c384bb939610b3e3c473ffad6
C#
Maior1998/kmzilibrary
/OSULib/Maths/GamesTheory/GameWithNature.cs
3.125
3
using System; using System.Linq; namespace OSULib.Maths.GamesTheory { public class GameWithNature { /// <summary> /// Представляет собой матрицу весов выйгрышей (A). /// </summary> private readonly Matrix strategiesWeights; public GameWithNature(Matrix strategiesWeights) { this.strategiesWeights = strategiesWeights.Copy(); //double min = this.strategiesWeights.GetMin(); //if (min < 0) // this.strategiesWeights.IncrementBy(Math.Abs(min)); } private Matrix risksMatrix; /// <summary> /// Матрица рисков. /// </summary> public Matrix RisksMatrix { get { if (risksMatrix != null) return risksMatrix; Matrix bufferRiskMatrix = new Matrix(strategiesWeights.Values.GetLength(0), strategiesWeights.Values[0].Length); for (int j = 0; j < strategiesWeights.Values[0].Length; j++) { double maxInColumn = strategiesWeights.GetMaxAbsInColumn(j); for (int i = 0; i < strategiesWeights.Values.GetLength(0); i++) { bufferRiskMatrix[i, j] = maxInColumn - strategiesWeights[i, j]; } } return risksMatrix = bufferRiskMatrix; } } private Matrix lossMatrix; /// <summary> /// Матрица потерь. /// </summary> public Matrix LossMatrix { get { if (lossMatrix != null) return lossMatrix; lossMatrix = strategiesWeights.GetMultipliedCopy(-1); return lossMatrix; } } /// <summary> /// Критерий макси-макса по матрице стратегий. /// </summary> public double StrategiesMaxMaxCriteria => StrategiesGetGurwitsCriteria(0); /// <summary> /// Критерий макси-макса по матрице рисков. /// </summary> public double RisksMaxMaxCriteria => RisksGetGurwitsCriteria(0); /// <summary> /// Критерий Вальда по матрице стратегий. /// </summary> public double StrategiesWaldsMaximinModel => StrategiesGetGurwitsCriteria(1); /// <summary> /// Критерий Вальда по матрице рисков. /// </summary> public double RisksWaldsMaximinModel => RisksGetGurwitsCriteria(1); /// <summary> /// Вычисляет критерий Гурвица для заданного уровня пессимизма по матрице стратегий. /// </summary> /// <param name="pessimismLevel">Уровень пессимизма, для которого необходимо рассчитать критерий.</param> /// <returns>Вещественное число - критерий Гурвица.</returns> public double StrategiesGetGurwitsCriteria(double pessimismLevel) { if (pessimismLevel < 0 || pessimismLevel > 1) throw new InvalidOperationException("Уровень пессимизма должен лежать в отрезке от 0 до 1."); return strategiesWeights.Values.Select(x => pessimismLevel * x.Min() + (1 - pessimismLevel) * x.Max()).Max(); } /// <summary> /// Вычисляет критерий Гурвица для заданного уровня пессимизма по матрице рисков. /// </summary> /// <param name="pessimismLevel">Уровень пессимизма, для которого необходимо рассчитать критерий.</param> /// <returns>Вещественное число - критерий Гурвица.</returns> public double RisksGetGurwitsCriteria(double pessimismLevel) { if (pessimismLevel < 0 || pessimismLevel > 1) throw new InvalidOperationException("Уровень пессимизма должен лежать в отрезке от 0 до 1."); return RisksMatrix.Values.Select(x => pessimismLevel * x.Max() + (1 - pessimismLevel) * x.Min()).Min(); } /// <summary> /// Критерий Сэвиджа. /// </summary> public double SavageCriteria => RisksMatrix.Values.Select(x => x.Max()).Min(); /// <summary> /// Получает критерий Байеса для заданного массива вероятностей по матрице стратегий. /// </summary> /// <param name="probabilities">Массив вероятностей стратегий погоды.</param> /// <returns>Критерий Байеса.</returns> public double StrategiesGetBayesCriteria(double[] probabilities) { if (probabilities.Length != strategiesWeights.Values.First().Length) throw new InvalidOperationException("Длина массива вероятностей не равна числу стратегий природы!"); return strategiesWeights.Values .Select(x => x.Select((value, index) => value * probabilities[index]).Sum()).Max(); } /// <summary> /// Получает критерий Байеса для заданного массива вероятностей по матрице рисков. /// </summary> /// <param name="probabilities">Массив вероятностей стратегий погоды.</param> /// <returns>Критерий Байеса.</returns> public double RisksGetBayesCriteria(double[] probabilities) { if (probabilities.Length != strategiesWeights.Values.First().Length) throw new InvalidOperationException("Длина массива вероятностей не равна числу стратегий природы!"); return RisksMatrix.Values.Select(x => x.Select((value, index) => value * probabilities[index]).Sum()).Min(); } /// <summary> /// Простой критерий Байеса по матрице стратегий, когда все стратегии природы равновероятны. /// </summary> public double StrategiesSimpleBayesCriteria => StrategiesGetBayesCriteria(Enumerable.Range(0, strategiesWeights.LengthX).Select(x => 1d / strategiesWeights.LengthX).ToArray()); /// <summary> /// Простой критерий Байеса по матрице рисков, когда все стратегии природы равновероятны. /// </summary> public double RisksSimpleBayesCriteria => RisksGetBayesCriteria(Enumerable.Range(0, strategiesWeights.LengthX).Select(x => 1d / strategiesWeights.LengthX).ToArray()); } }
82b0e19e4b7023ecad3850dfb982ef262487238f
C#
shendongnian/download4
/code1/56886-8222312-18365255-1.cs
4.09375
4
using System; class demo { static void Main() { int number; Console.WriteLine("Enter Number you Should be Checked Number is Prime or not Prime"); number = Int32.Parse(Console.ReadLine()); for(int i =2;i<number/2;i++) { if(number % i == 0) { Console.WriteLine("Entered number is not Prime"); break; } } if(number % i !=0) { Console.WriteLine("Entered Number is Prime"); } Console.ReadLine(); } }
687de3467f74932778cd4548f86a54a49ad7b3e4
C#
Dannyyyy/ValueConverter
/ValueConverter/ValueConverter/Sagen.cs
2.6875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ValueConverter { //Сажень public class Sagen { double M = 2.134; double Dm = 21.34; double Sm = 213.4; double Mm = 2134; double Vershok = 48; double Pyad = 12; double Arshin = 3; double Inch = 84; double Foot = 7; double Yard = 2.333; double Cable = 0.0115; public double getMetr(double sagen) { return sagen * M; } public double getVershok(double sagen) { return sagen * Vershok; } public double getDm(double sagen) { return sagen * Dm; } public double getSm(double sagen) { return sagen * Sm; } public double getPyad(double sagen) { return sagen * Pyad; } public double getMm(double sagen) { return sagen * Mm; } public double getArshin(double sagen) { return sagen * Arshin; } public double getInch(double sagen) { return sagen * Inch; } public double getFoot(double sagen) { return sagen * Foot; } public double getYard(double sagen) { return sagen * Yard; } public double getCable(double sagen) { return sagen * Cable; } } }
64d00ba1b78eecb1ef3b4ff71eaf228c1bcd01cd
C#
neochen168/Algorithm
/Coding/Coding/ReverseWordsInString.cs
3.578125
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Coding { public class ReverseWordsInString { public static string ReverseWords(string str) { char[] tempWithSpaces = str.Trim().ToCharArray(); char[] temp = new char[tempWithSpaces.Length]; for(int i = 0; i < temp.Length; i++) { temp[i] = ' '; } int index = 0; for (int i = 0; i < tempWithSpaces.Length; i++) { if (tempWithSpaces[i] == ' ') continue; while (i < tempWithSpaces.Length && tempWithSpaces[i] != ' ' ) { temp[index++] = tempWithSpaces[i++]; } if (index < temp.Length) { temp[index++] = ' '; } } --index; for (int i = 0; i < index; i++) { if (temp[i] == ' ') { continue; } int j; for (j = i + 1; j < index; j++) { if (temp[j] != ' ') continue; else break; } j--; for (int ii = i; ii < j; ii++, j--) { char c = temp[ii]; temp[ii] = temp[j]; temp[j] = c; } i = j + 1; } for (int i = 0, j = index - 1; i < j; i++, j--) { char c = temp[i]; temp[i] = temp[j]; temp[j] = c; } string result = new string(temp); return result.Trim(); } public static void TestReverseWordsInString() { string s = " the sky is blue "; Console.Write(ReverseWords(s)); Console.Write(ReverseWords(s)); Console.Write(ReverseWords(s)); } } } //class Solution { //public: // void reverseWords(string &s) { // for(int i = 0; i < s.length;) // { // while(s[i] == ' ' && s[i+1] != '\0') // { // s[i] = s[i+1]; // } // } // for(int i = 0; i < s.length; i++) // { // if(s[i] == '') // { // continue; // } // for(int j = i+1; j < s.length; j++) // { // if(s[j]!='') continue; // else break; // } // j--; // for(int ii = i; ii < j ; ii++,j--) // { // char c = s[ii]; // s[ii] = s[j]; // s[j] = c; // } // } // for(int i = 0,j = s.length -1; i < j; i++,j--) // { // char c = s[i]; // s[i] = s[j]; // s[j] = c; // } // } //};
7cfa3086061d1c9fcf4e78cfd0c868b0c30a7824
C#
1059444127/Xian
/ImageViewer/Configuration/MultiValuedDictionary.cs
2.828125
3
#region License // Copyright (c) 2011, ClearCanvas Inc. // All rights reserved. // http://www.clearcanvas.ca // // This software is licensed under the Open Software License v3.0. // For the complete license, see http://www.clearcanvas.ca/OSLv3.0 #endregion using System; using System.Collections; using System.Collections.Generic; namespace ClearCanvas.ImageViewer.Configuration { /// <summary> /// Represents a generic collection of 1-to-n key-item mappings. /// </summary> /// <typeparam name="TKey">The type of keys in the dictionary.</typeparam> /// <typeparam name="TItem">The type of items in the dictionary.</typeparam> internal interface IMultiValuedDictionary<TKey, TItem> : IEnumerable<KeyValuePair<TKey, IEnumerable<TItem>>> { /// <summary> /// Gets an <see cref="IList{T}"/> of items mapped to the specified <paramref name="key"/>. /// </summary> /// <remarks> /// This interface does not specify whether or not implementations of this property must make the resulting lists /// static copies and, if not a static copy, whether or not the list should be read-only indepdendent of the /// dictionary's <see cref="IsReadOnly"/> property. /// </remarks> /// <param name="key">The key for which the list of mapped items is to be retrieved.</param> /// <returns>Returns a list of items mapped to the specified key. If no items are mapped to the specified key, this returns an empty list.</returns> /// <exception cref="ArgumentNullException">Thrown if <typeparamref name="TKey"/> is a reference type and <paramref name="key"/> is NULL.</exception> IList<TItem> this[TKey key] { get; } /// <summary> /// Gets the total number of mapped items the <see cref="IMultiValuedDictionary{TKey,TItem}"/>. /// </summary> /// <remarks> /// Accessing this property yields the same result as the <see cref="ICollection{T}.Count"/> property on <see cref="Items"/>. /// </remarks> int Count { get; } /// <summary> /// Gets an <see cref="ICollection{T}"/> of unique keys in the <see cref="IMultiValuedDictionary{TKey,TItem}"/>. /// </summary> ICollection<TKey> Keys { get; } /// <summary> /// Gets an <see cref="ICollection{T}"/> of mapped items in the <see cref="IMultiValuedDictionary{TKey,TItem}"/>. /// </summary> ICollection<TItem> Items { get; } /// <summary> /// Gets a value indicating whether or not the <see cref="IMultiValuedDictionary{TKey,TItem}"/> is read-only and thus immutable. /// </summary> bool IsReadOnly { get; } /// <summary> /// Adds a mapping for the provided item and not-necessarily unique key to the <see cref="IMultiValuedDictionary{TKey,TItem}"/>. /// </summary> /// <param name="key">The key to which the item should be mapped.</param> /// <param name="item">The item to be mapped.</param> /// <exception cref="ArgumentNullException">Thrown if <typeparamref name="TKey"/> is a reference type and <paramref name="key"/> is NULL.</exception> /// <exception cref="NotSupportedException">Thrown if the <see cref="IMultiValuedDictionary{TKey,TItem}"/> is read-only.</exception> void Add(TKey key, TItem item); /// <summary> /// Removes a mapping for the provided item and key from the <see cref="IMultiValuedDictionary{TKey,TItem}"/>. /// </summary> /// <param name="key">The key of the mapped item to be removed.</param> /// <param name="item">The mapped item to be removed.</param> /// <returns>True if the item mapping was removed; False if no mapping for the specified key and item existed, and thus no mapping was removed.</returns> /// <exception cref="ArgumentNullException">Thrown if <typeparamref name="TKey"/> is a reference type and <paramref name="key"/> is NULL.</exception> /// <exception cref="NotSupportedException">Thrown if the <see cref="IMultiValuedDictionary{TKey,TItem}"/> is read-only.</exception> bool Remove(TKey key, TItem item); /// <summary> /// Removes all mapped items to the specified key from the <see cref="IMultiValuedDictionary{TKey,TItem}"/>. /// </summary> /// <param name="key">The key for which all mapped items should be removed.</param> /// <returns>True if mappings were removed; False if no items were mapped to the provided key, and thus no mappings were removed.</returns> /// <exception cref="ArgumentNullException">Thrown if <typeparamref name="TKey"/> is a reference type and <paramref name="key"/> is NULL.</exception> /// <exception cref="NotSupportedException">Thrown if the <see cref="IMultiValuedDictionary{TKey,TItem}"/> is read-only.</exception> bool RemoveAll(TKey key); /// <summary> /// Clears all mapped items in the <see cref="IMultiValuedDictionary{TKey,TItem}"/>. /// </summary> /// <exception cref="NotSupportedException">Thrown if the <see cref="IMultiValuedDictionary{TKey,TItem}"/> is read-only.</exception> void Clear(); /// <summary> /// Checks for the presence of any items mapped to the specified key in the <see cref="IMultiValuedDictionary{TKey,TItem}"/>. /// </summary> /// <param name="key">The key for which to check for the presence of mapped items.</param> /// <returns>True if there is at least one item mapped to the specified key; False otherwise.</returns> /// <exception cref="ArgumentNullException">Thrown if <typeparamref name="TKey"/> is a reference type and <paramref name="key"/> is NULL.</exception> bool ContainsKey(TKey key); /// <summary> /// Copies the mappings of the <see cref="IMultiValuedDictionary{TKey,TItem}"/> to an array of <see cref="KeyValuePair{TKey,TValue}"/>s. /// </summary> /// <param name="array">The destination array to which the mappings are to be copied.</param> /// <param name="arrayIndex">The index in the destination array at which to start copying.</param> void CopyTo(KeyValuePair<TKey, IEnumerable<TItem>>[] array, int arrayIndex); /// <summary> /// Gets an <see cref="IEnumerable{T}"/> of items mapped to the specified key. /// </summary> /// <param name="key">The key for which the enumerable of mapped items is to be retrieved.</param> /// <param name="item">The retrieved enumerable of items mapped to the specified key. If no items were mapped to the specified key, this returns an empty enumerable.</param> /// <returns>True if there were items mapped to the specified key; False otherwise.</returns> /// <exception cref="ArgumentNullException">Thrown if <typeparamref name="TKey"/> is a reference type and <paramref name="key"/> is NULL.</exception> bool TryGetItems(TKey key, out IEnumerable<TItem> item); } /// <summary> /// Represents a generic collection of 1-to-n key-item mappings. /// </summary> /// <typeparam name="TKey">The type of keys in the dictionary.</typeparam> /// <typeparam name="TItem">The type of items in the dictionary.</typeparam> internal class MultiValuedDictionary<TKey, TItem> : IMultiValuedDictionary<TKey, TItem>, IDictionary<TKey, IEnumerable<TItem>> { private readonly Dictionary<TKey, List<TItem>> _dictionary; private readonly KeyCollection _keyCollection; private readonly ItemCollection _itemCollection; private readonly ItemListCollecion _itemListCollection; /// <summary> /// Initializes a new instance of <see cref="MultiValuedDictionary{TKey,TItem}"/> that is empty, has the /// default initial capacity, and uses the default equality comparer for the <typeparamref name="TKey"/>. /// </summary> public MultiValuedDictionary() : this((IEqualityComparer<TKey>) null) {} /// <summary> /// Initializes a new instance of <see cref="MultiValuedDictionary{TKey,TItem}"/> that is empty, has the /// default initial capacity, and uses the specified <see cref="IEqualityComparer{T}"/>. /// </summary> /// <param name="comparer">The <see cref="IEqualityComparer{T}"/> implementation to use when comparing keys, or NULL to use the default equality comparer for the <typeparamref name="TKey"/>.</param> public MultiValuedDictionary(IEqualityComparer<TKey> comparer) : this(new Dictionary<TKey, List<TItem>>(comparer)) {} /// <summary> /// Initializes a new instance of <see cref="MultiValuedDictionary{TKey,TItem}"/> that is empty, has the /// specified initial capacity, and uses the default equality comparer for the <typeparamref name="TKey"/>. /// </summary> /// <param name="capacity"></param> public MultiValuedDictionary(int capacity) : this(capacity, null) {} /// <summary> /// Initializes a new instance of <see cref="MultiValuedDictionary{TKey,TItem}"/> that is empty, has the /// specified initial capacity, and uses the specified <see cref="IEqualityComparer{T}"/>. /// </summary> /// <param name="capacity"></param> /// <param name="comparer">The <see cref="IEqualityComparer{T}"/> implementation to use when comparing keys, or NULL to use the default equality comparer for the <typeparamref name="TKey"/>.</param> public MultiValuedDictionary(int capacity, IEqualityComparer<TKey> comparer) : this(new Dictionary<TKey, List<TItem>>(capacity, comparer)) {} /// <summary> /// Initializes a new instance of <see cref="MultiValuedDictionary{TKey,TItem}"/> that contains values copied /// from the specified source, and uses the default equality comparer for the <typeparamref name="TKey"/>. /// </summary> /// <remarks> /// Any source values with duplicate keys are automatically collapsed to a single key entry with the individual items /// concatenanted sequentially into a single list. /// </remarks> /// <param name="source">The source enumerable whose values are to be coped to the new <see cref="MultiValuedDictionary{TKey,TItem}"/>.</param> /// <exception cref="ArgumentNullException">Thrown if <paramref name="source"/> is NULL.</exception> public MultiValuedDictionary(IEnumerable<KeyValuePair<TKey, TItem>> source) : this(source, null) {} /// <summary> /// Initializes a new instance of <see cref="MultiValuedDictionary{TKey,TItem}"/> that contains values copied /// from the specified source, and uses the specified <see cref="IEqualityComparer{T}"/>. /// </summary> /// <remarks> /// Any source values with duplicate keys are automatically collapsed to a single key entry with the individual items /// concatenanted sequentially into a single list. /// </remarks> /// <param name="source">The source enumerable whose values are to be coped to the new <see cref="MultiValuedDictionary{TKey,TItem}"/>.</param> /// <param name="comparer">The <see cref="IEqualityComparer{T}"/> implementation to use when comparing keys, or NULL to use the default equality comparer for the <typeparamref name="TKey"/>.</param> /// <exception cref="ArgumentNullException">Thrown if <paramref name="source"/> is NULL.</exception> public MultiValuedDictionary(IEnumerable<KeyValuePair<TKey, TItem>> source, IEqualityComparer<TKey> comparer) : this(new Dictionary<TKey, List<TItem>>(comparer)) { if (ReferenceEquals(source, null)) throw new ArgumentNullException("source"); foreach (KeyValuePair<TKey, TItem> pair in source) Add(pair.Key, pair.Value); } /// <summary> /// Initializes a new instance of <see cref="MultiValuedDictionary{TKey,TItem}"/> that contains values copied /// from the specified source, and uses the default equality comparer for the <typeparamref name="TKey"/>. /// </summary> /// <remarks> /// Any source values with duplicate keys are automatically collapsed to a single key entry with the individual items /// concatenanted sequentially into a single list. /// </remarks> /// <param name="source">The source enumerable whose values are to be coped to the new <see cref="MultiValuedDictionary{TKey,TItem}"/>.</param> /// <exception cref="ArgumentNullException">Thrown if <paramref name="source"/> is NULL.</exception> public MultiValuedDictionary(IEnumerable<KeyValuePair<TKey, IEnumerable<TItem>>> source) : this(source, null) {} /// <summary> /// Initializes a new instance of <see cref="MultiValuedDictionary{TKey,TItem}"/> that contains values copied /// from the specified source, and uses the specified <see cref="IEqualityComparer{T}"/>. /// </summary> /// <remarks> /// Any source values with duplicate keys are automatically collapsed to a single key entry with the individual items /// concatenanted sequentially into a single list. /// </remarks> /// <param name="source">The source enumerable whose values are to be coped to the new <see cref="MultiValuedDictionary{TKey,TItem}"/>.</param> /// <param name="comparer">The <see cref="IEqualityComparer{T}"/> implementation to use when comparing keys, or NULL to use the default equality comparer for the <typeparamref name="TKey"/>.</param> /// <exception cref="ArgumentNullException">Thrown if <paramref name="source"/> is NULL.</exception> public MultiValuedDictionary(IEnumerable<KeyValuePair<TKey, IEnumerable<TItem>>> source, IEqualityComparer<TKey> comparer) : this(new Dictionary<TKey, List<TItem>>(comparer)) { if (ReferenceEquals(source, null)) throw new ArgumentNullException("source"); foreach (KeyValuePair<TKey, IEnumerable<TItem>> pair in source) AddRange(pair.Key, pair.Value); } private MultiValuedDictionary(Dictionary<TKey, List<TItem>> dictionary) { _dictionary = dictionary; _keyCollection = new KeyCollection(this); _itemCollection = new ItemCollection(this); _itemListCollection = new ItemListCollecion(this); } /// <summary> /// Gets an <see cref="IList{T}"/> of items mapped to the specified <paramref name="key"/>. /// </summary> /// <remarks> /// The returned <see cref="IList{T}"/> is not a static copy; instead, the list is a wrapper that refers back to the original /// <see cref="MultiValuedDictionary{TKey,TItem}"/>. Therefore, changes to either the original dictionary or this list /// continue to be reflected in the other. /// </remarks> /// <param name="key">The key for which the list of mapped items is to be retrieved.</param> /// <returns>Returns a list of items mapped to the specified key. If no items are mapped to the specified key, this returns an empty list.</returns> /// <exception cref="ArgumentNullException">Thrown if <typeparamref name="TKey"/> is a reference type and <paramref name="key"/> is NULL.</exception> public IList<TItem> this[TKey key] { get { if (ReferenceEquals(key, null)) throw new ArgumentNullException("key"); return new ItemList(key, this); } } /// <summary> /// Gets the total number of mapped items in the <see cref="MultiValuedDictionary{TKey,TItem}"/>. /// </summary> /// <remarks> /// Accessing this property yields the same result as the <see cref="ItemCollection.Count"/> property on <see cref="Items"/>. /// </remarks> public int Count { get { return _itemCollection.Count; } } /// <summary> /// Gets a <see cref="KeyCollection"/> of unique keys in the <see cref="MultiValuedDictionary{TKey,TItem}"/>. /// </summary> /// <remarks> /// The returned <see cref="KeyCollection"/> is not a static copy; instead, the collection refers back to the keys in the original /// <see cref="MultiValuedDictionary{TKey,TItem}"/>. Therefore, changes in the original dictionary continue to be reflected /// in the collection. /// </remarks> public KeyCollection Keys { get { return _keyCollection; } } /// <summary> /// Gets an <see cref="ItemCollection"/> of mapped items in the <see cref="MultiValuedDictionary{TKey,TItem}"/>. /// </summary> /// <remarks> /// The returned <see cref="ItemCollection"/> is not a static copy; instead, the collection refers back to the items in the original /// <see cref="MultiValuedDictionary{TKey,TItem}"/>. Therefore, changes in the original dictionary continue to be reflected /// in the collection. /// </remarks> public ItemCollection Items { get { return _itemCollection; } } /// <summary> /// Gets the <see cref="IEqualityComparer{T}"/> that is used to determine the equality of keys for the dictionary. /// </summary> public IEqualityComparer<TKey> Comparer { get { return _dictionary.Comparer; } } /// <summary> /// Adds a mapping for the provided item and not-necessarily unique key to the <see cref="MultiValuedDictionary{TKey,TItem}"/>. /// </summary> /// <param name="key">The key to which the item should be mapped.</param> /// <param name="item">The item to be mapped.</param> /// <exception cref="ArgumentNullException">Thrown if <typeparamref name="TKey"/> is a reference type and <paramref name="key"/> is NULL.</exception> public void Add(TKey key, TItem item) { if (ReferenceEquals(key, null)) throw new ArgumentNullException("key"); if (!_dictionary.ContainsKey(key)) _dictionary.Add(key, new List<TItem>(new[] {item})); else _dictionary[key].Add(item); } /// <summary> /// Adds mappings for the provided items and not-necessarily unique key to the <see cref="MultiValuedDictionary{TKey,TItem}"/>. /// </summary> /// <param name="key">The key to which the provided items should be mapped.</param> /// <param name="collection">The items to be mapped.</param> /// <exception cref="ArgumentNullException">Thrown if <typeparamref name="TKey"/> is a reference type and <paramref name="key"/> is NULL.</exception> public void AddRange(TKey key, IEnumerable<TItem> collection) { if (ReferenceEquals(key, null)) throw new ArgumentNullException("key"); if (!_dictionary.ContainsKey(key)) _dictionary.Add(key, new List<TItem>(collection)); else _dictionary[key].AddRange(collection); } /// <summary> /// Removes a mapping for the provided item and key from the <see cref="MultiValuedDictionary{TKey,TItem}"/>. /// </summary> /// <param name="key">The key of the mapped item to be removed.</param> /// <param name="item">The mapped item to be removed.</param> /// <returns>True if the item mapping was removed; False if no mapping for the specified key and item existed, and thus no mapping was removed.</returns> /// <exception cref="ArgumentNullException">Thrown if <typeparamref name="TKey"/> is a reference type and <paramref name="key"/> is NULL.</exception> public bool Remove(TKey key, TItem item) { if (ReferenceEquals(key, null)) throw new ArgumentNullException("key"); if (!_dictionary.ContainsKey(key)) return false; try { return _dictionary[key].Remove(item); } finally { Compact(key); } } /// <summary> /// Removes all mapped items to the specified key from the <see cref="MultiValuedDictionary{TKey,TItem}"/>. /// </summary> /// <param name="key">The key for which all mapped items should be removed.</param> /// <returns>True if mappings were removed; False if no items were mapped to the provided key, and thus no mappings were removed.</returns> /// <exception cref="ArgumentNullException">Thrown if <typeparamref name="TKey"/> is a reference type and <paramref name="key"/> is NULL.</exception> public bool RemoveAll(TKey key) { if (ReferenceEquals(key, null)) throw new ArgumentNullException("key"); return _dictionary.Remove(key); } /// <summary> /// Clears all mapped items in the <see cref="MultiValuedDictionary{TKey,TItem}"/>. /// </summary> public void Clear() { _dictionary.Clear(); } /// <summary> /// Checks for the presence of any items mapped to the specified key in the <see cref="MultiValuedDictionary{TKey,TItem}"/>. /// </summary> /// <param name="key">The key for which to check for the presence of mapped items.</param> /// <returns>True if there is at least one item mapped to the specified key; False otherwise.</returns> /// <exception cref="ArgumentNullException">Thrown if <typeparamref name="TKey"/> is a reference type and <paramref name="key"/> is NULL.</exception> public bool ContainsKey(TKey key) { if (ReferenceEquals(key, null)) throw new ArgumentNullException("key"); return _keyCollection.Contains(key); } /// <summary> /// Checks for the presence of the a mapping for the specified item. /// </summary> /// <remarks> /// Calling this method yields the same result as calling the <see cref="ItemCollection.Contains"/> method on <see cref="Items"/>. /// </remarks> /// <param name="item">The item for which the presence of a mapping is to be checked.</param> /// <returns>True if a mapping exists fo the specified item; False otherwsie.</returns> public bool ContainsValue(TItem item) { return _itemCollection.Contains(item); } /// <summary> /// Searches for the first instance of a mapped item and returns the corresponding key. /// </summary> /// <remarks> /// If <typeparamref name="TKey"/> is a value type then the result will be indistinguishable as to whether or not /// the item was found and its key was the empty value, or the item was not found. In this scenario, consider /// using <see cref="FindKey(TItem,TKey)"/> with a value that is known to not be in the dictionary, or /// <see cref="TryFindKey(TItem,out TKey)"/>. /// </remarks> /// <param name="item">The item for which a key is to be found.</param> /// <returns>The key for the first instance of the specified item, or the default value for <typeparamref name="TKey"/> if the specified item was not found.</returns> public TKey FindKey(TItem item) { return FindKey(item, default(TKey)); } /// <summary> /// Searches for the first instance of a mapped item and returns the corresponding key. /// </summary> /// <param name="item">The item for which a key is to be found.</param> /// <param name="defaultValue">The value to be returned if the specified item is not found.</param> /// <returns>The key for the first instance of the specified item, or <paramref name="defaultValue"/> if the specified item was not found.</returns> public TKey FindKey(TItem item, TKey defaultValue) { TKey key; if (TryFindKey(item, out key)) return key; return defaultValue; } /// <summary> /// Searches for the first instance of a mapped item and returns the corresponding key. /// </summary> /// <param name="item">The item for which a key is to be found.</param> /// <param name="key">The key for the first instance of the specified item, or the default value for <typeparamref name="TKey"/> if the specified item was not found.</param> /// <returns>True if the item was found; False otherwise.</returns> public bool TryFindKey(TItem item, out TKey key) { foreach (KeyValuePair<TKey, List<TItem>> pair in _dictionary) { if (pair.Value.Contains(item)) { key = pair.Key; return true; } } key = default(TKey); return false; } /// <summary> /// Searches for the first item matching a given set of conditions and returns the corresponding key. /// </summary> /// <remarks> /// If <typeparamref name="TKey"/> is a value type then the result will be indistinguishable as to whether or not /// an item was found and its key was the empty value, or an item was not found. In this scenario, consider /// using <see cref="FindKey(System.Predicate{TItem},TKey)"/> with a value that is known to not be in the dictionary, or /// <see cref="TryFindKey(System.Predicate{TItem},out TKey)"/>. /// </remarks> /// <param name="predicate">A <see cref="Predicate{T}"/> delegate defining the conditions of the item to be found.</param> /// <returns>The key for the first instance of an item matching the <paramref name="predicate"/>, or the default value for <typeparamref name="TKey"/> if no matching item was found.</returns> public TKey FindKey(Predicate<TItem> predicate) { return FindKey(predicate, default(TKey)); } /// <summary> /// Searches for the first item matching a given set of conditions and returns the corresponding key. /// </summary> /// <param name="predicate">A <see cref="Predicate{T}"/> delegate defining the conditions of the item to be found.</param> /// <param name="defaultValue">The value to be returned if no matching item was found.</param> /// <returns>The key for the first instance of an item matching the <paramref name="predicate"/>, or <paramref name="defaultValue"/> if no matching item was found.</returns> public TKey FindKey(Predicate<TItem> predicate, TKey defaultValue) { TKey key; if (TryFindKey(predicate, out key)) return key; return defaultValue; } /// <summary> /// Searches for the first item matching a given set of conditions and returns the corresponding key. /// </summary> /// <param name="predicate">A <see cref="Predicate{T}"/> delegate defining the conditions of the item to be found.</param> /// <param name="key">The key for the first instance of an item matching the <paramref name="predicate"/>, or the default value for <typeparamref name="TKey"/> if no matching item was found.</param> /// <returns>True if a match was found; False otherwise.</returns> public bool TryFindKey(Predicate<TItem> predicate, out TKey key) { foreach (KeyValuePair<TKey, List<TItem>> pair in _dictionary) { int index = pair.Value.FindIndex(predicate); if (index >= 0) { key = pair.Key; return true; } } key = default(TKey); return false; } /// <summary> /// Searches for the first item matching a given set of conditions. /// </summary> /// <remarks> /// Tthe result of this method will be indistinguishable as to whether or not a match was found and it was the /// default value for <typeparamref name="TItem"/>, or if no matching item was found. In this scenario, consider /// using <see cref="Find(System.Predicate{TItem},TItem)"/> with a value that is known to not be in the dictionary, or /// <see cref="TryFind(System.Predicate{TItem},out TItem)"/>. /// </remarks> /// <param name="predicate">A <see cref="Predicate{T}"/> delegate defining the conditions of the item to be found.</param> /// <returns>The key for the first instance of an item matching the <paramref name="predicate"/>, or the default value for <typeparamref name="TKey"/> if no matching item was found.</returns> public TItem Find(Predicate<TItem> predicate) { return Find(predicate, default(TItem)); } /// <summary> /// Searches for the first item matching a given set of conditions. /// </summary> /// <param name="predicate">A <see cref="Predicate{T}"/> delegate defining the conditions of the item to be found.</param> /// <param name="defaultValue">The value to be returned if no matching item was found.</param> /// <returns>The key for the first instance of an item matching the <paramref name="predicate"/>, or <paramref name="defaultValue"/> if no matching item was found.</returns> public TItem Find(Predicate<TItem> predicate, TItem defaultValue) { TItem item; if (TryFind(predicate, out item)) return item; return defaultValue; } /// <summary> /// Searches for the first item matching a given set of conditions. /// </summary> /// <param name="predicate">A <see cref="Predicate{T}"/> delegate defining the conditions of the item to be found.</param> /// <param name="match">The key for the first instance of an item matching the <paramref name="predicate"/>, or the default value for <typeparamref name="TItem"/> if no matching item was found.</param> /// <returns>True if a match was found; False otherwise.</returns> public bool TryFind(Predicate<TItem> predicate, out TItem match) { foreach (TItem item in _itemCollection) { if (predicate.Invoke(item)) { match = item; return true; } } match = default(TItem); return false; } /// <summary> /// Gets an <see cref="IEnumerable{T}"/> of items mapped to the specified key. /// </summary> /// <param name="key">The key for which the enumerable of mapped items is to be retrieved.</param> /// <param name="item">The retrieved enumerable of items mapped to the specified key. If no items were mapped to the specified key, this returns an empty enumerable.</param> /// <returns>True if there were items mapped to the specified key; False otherwise.</returns> /// <exception cref="ArgumentNullException">Thrown if <typeparamref name="TKey"/> is a reference type and <paramref name="key"/> is NULL.</exception> public bool TryGetItems(TKey key, out IEnumerable<TItem> item) { if (ReferenceEquals(key, null)) throw new ArgumentNullException("key"); List<TItem> value; if (_dictionary.TryGetValue(key, out value)) { item = value.AsReadOnly(); return true; } item = new TItem[] {}; return false; } /// <summary> /// Returns a read-only <see cref="IMultiValuedDictionary{TKey,TItem}"/> wrapper for the current dictionary. /// </summary> /// <remarks> /// To prevent any modifications to <see cref="MultiValuedDictionary{TKey,TItem}"/>, only expose the dictionary through this wrapper. /// The returned wrapper is not a static copy; instead, it refers back to the items in the original /// <see cref="MultiValuedDictionary{TKey,TItem}"/>. Therefore, changes in the original dictionary continue to be reflected /// in the wrapper. /// </remarks> /// <returns>A read-only wrapper around the current <see cref="MultiValuedDictionary{TKey,TItem}"/>.</returns> public IMultiValuedDictionary<TKey, TItem> AsReadOnly() { return new ReadOnlyMultiValuedDictionaryWrapper(this); } /// <summary> /// Returns an enumerator that iterates through the <typeparamref name="TKey"/> and <see cref="IEnumerable{T}"/> pairs. /// </summary> /// <returns>An <see cref="IEnumerator"/> that can be used to iterate through the collection.</returns> public IEnumerator<KeyValuePair<TKey, IEnumerable<TItem>>> GetEnumerator() { foreach (KeyValuePair<TKey, List<TItem>> pair in _dictionary) yield return new KeyValuePair<TKey, IEnumerable<TItem>>(pair.Key, pair.Value.AsReadOnly()); } /// <summary> /// Returns an enumerator that iterates through the <typeparamref name="TKey"/> and <see cref="IEnumerable{T}"/> pairs. /// </summary> /// <returns>An <see cref="IEnumerator"/> that can be used to iterate through the collection.</returns> IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } private void Compact(TKey key) { if (_dictionary[key].Count == 0) _dictionary.Remove(key); } #region IMultiValuedDictionary<TKey, TItem> Members /// <summary> /// Gets an <see cref="KeyCollection"/> of unique keys in the <see cref="MultiValuedDictionary{TKey,TItem}"/>. /// </summary> /// <remarks> /// The returned <see cref="KeyCollection"/> is not a static copy; instead, the collection refers back to the keys in the original /// <see cref="MultiValuedDictionary{TKey,TItem}"/>. Therefore, changes in the original dictionary continue to be reflected /// in the collection. /// </remarks> ICollection<TKey> IMultiValuedDictionary<TKey, TItem>.Keys { get { return Keys; } } /// <summary> /// Gets an <see cref="ItemCollection"/> of mapped items in the <see cref="MultiValuedDictionary{TKey,TItem}"/>. /// </summary> /// <remarks> /// The returned <see cref="ItemCollection"/> is not a static copy; instead, the collection refers back to the items in the original /// <see cref="MultiValuedDictionary{TKey,TItem}"/>. Therefore, changes in the original dictionary continue to be reflected /// in the collection. /// </remarks> ICollection<TItem> IMultiValuedDictionary<TKey, TItem>.Items { get { return Items; } } /// <summary> /// Copies the mappings of the <see cref="MultiValuedDictionary{TKey,TItem}"/> to an array of <see cref="KeyValuePair{TKey,TValue}"/>s. /// </summary> /// <param name="array">The destination array to which the mappings are to be copied.</param> /// <param name="arrayIndex">The index in the destination array at which to start copying.</param> void IMultiValuedDictionary<TKey, TItem>.CopyTo(KeyValuePair<TKey, IEnumerable<TItem>>[] array, int arrayIndex) { foreach (KeyValuePair<TKey, IEnumerable<TItem>> pair in this) array[arrayIndex++] = pair; } /// <summary> /// This implementation of <see cref="IMultiValuedDictionary{TKey,TItem}"/> is never read-only. /// </summary> bool IMultiValuedDictionary<TKey, TItem>.IsReadOnly { get { return false; } } #endregion #region IDictionary<TKey, IList<TItem>> Members /// <summary> /// Gets or sets all the items mapped to a given key. /// </summary> /// <remarks> /// This property retrieves an enumerable of all items mapped to the specified key /// and replaces all items mapped to the specified key with those of the enumerable value. /// </remarks> /// <param name="key">The key for which all mapped items are to be retrieved or replaced.</param> /// <exception cref="ArgumentNullException">Thrown if <typeparamref name="TKey"/> is a reference type and <paramref name="key"/> is NULL.</exception> IEnumerable<TItem> IDictionary<TKey, IEnumerable<TItem>>.this[TKey key] { get { if (ReferenceEquals(key, null)) throw new ArgumentNullException("key"); return _dictionary[key].AsReadOnly(); } set { if (ReferenceEquals(key, null)) throw new ArgumentNullException("key"); _dictionary[key] = new List<TItem>(value); } } /// <summary> /// Gets the total number of unique keys in the <see cref="MultiValuedDictionary{TKey,TItem}"/>. /// </summary> /// <remarks> /// Accessing this property yields the same result as the <see cref="KeyCollection.Count"/> property on <see cref="Keys"/>. /// </remarks> int ICollection<KeyValuePair<TKey, IEnumerable<TItem>>>.Count { get { return _dictionary.Count; } } /// <summary> /// Gets a <see cref="KeyCollection"/> of unique keys in the <see cref="MultiValuedDictionary{TKey,TItem}"/>. /// </summary> /// <remarks> /// The returned <see cref="KeyCollection"/> is not a static copy; instead, the collection refers back to the keys in the original /// <see cref="MultiValuedDictionary{TKey,TItem}"/>. Therefore, changes in the original dictionary continue to be reflected /// in the collection. /// Accessing this property yields the same instance as the <see cref="Keys"/> property. /// </remarks> ICollection<TKey> IDictionary<TKey, IEnumerable<TItem>>.Keys { get { return _keyCollection; } } /// <summary> /// Gets a collection of mapped item enumerations grouped by key in the <see cref="MultiValuedDictionary{TKey,TItem}"/>. /// </summary> /// <remarks> /// The returned collection is not a static copy; instead, the collection refers back to the items in the original /// <see cref="MultiValuedDictionary{TKey,TItem}"/>. Therefore, changes in the original dictionary continue to be reflected /// in the collection. /// </remarks> ICollection<IEnumerable<TItem>> IDictionary<TKey, IEnumerable<TItem>>.Values { get { return _itemListCollection; } } /// <summary> /// This implementation of <see cref="IDictionary{TKey,TValue}"/> is never read-only. /// </summary> bool ICollection<KeyValuePair<TKey, IEnumerable<TItem>>>.IsReadOnly { get { return ((IMultiValuedDictionary<TKey, TItem>) this).IsReadOnly; } } /// <summary> /// Adds mappings for the provided items and not-necessarily unique key to the <see cref="MultiValuedDictionary{TKey,TItem}"/>. /// </summary> /// <remarks> /// Calling this method yields the same result as calling <see cref="AddRange"/>. /// </remarks> /// <param name="key">The key to which the provided items should be mapped.</param> /// <param name="value">The items to be mapped.</param> /// <exception cref="ArgumentNullException">Thrown if <typeparamref name="TKey"/> is a reference type and <paramref name="key"/> is NULL.</exception> void IDictionary<TKey, IEnumerable<TItem>>.Add(TKey key, IEnumerable<TItem> value) { AddRange(key, value); } /// <summary> /// Adds mappings for the provided items and not-necessarily unique key to the <see cref="MultiValuedDictionary{TKey,TItem}"/>. /// </summary> /// <remarks> /// Calling this method yields the same result as calling <see cref="AddRange"/>. /// </remarks> /// <param name="pair">The key-value pair specifying the key and associated items to be mapped.</param> /// <exception cref="ArgumentNullException">Thrown if <typeparamref name="TKey"/> is a reference type and the provided <paramref name="pair"/> has a NULL <see cref="KeyValuePair{TKey,TValue}.Key"/>.</exception> void ICollection<KeyValuePair<TKey, IEnumerable<TItem>>>.Add(KeyValuePair<TKey, IEnumerable<TItem>> pair) { AddRange(pair.Key, pair.Value); } /// <summary> /// Removes all mapped items to the specified key from the <see cref="MultiValuedDictionary{TKey,TItem}"/>. /// </summary> /// <remarks> /// Calling this method yields the same result as calling <see cref="RemoveAll"/>. /// </remarks> /// <param name="key">The key for which all mapped items should be removed.</param> /// <returns>True if mappings were removed; False if no items were mapped to the provided key, and thus no mappings were removed.</returns> /// <exception cref="ArgumentNullException">Thrown if <typeparamref name="TKey"/> is a reference type and <paramref name="key"/> is NULL.</exception> bool IDictionary<TKey, IEnumerable<TItem>>.Remove(TKey key) { return RemoveAll(key); } /// <summary> /// Removes mappings for all the specified items from the <see cref="MultiValuedDictionary{TKey,TItem}"/>. /// </summary> /// <param name="pair">The key-value pair specifying the key and associated items to be removed.</param> /// <returns>True if any of the speified item mappings were removed; False if none of the specified key and items existed, and thus no mappings were removed.</returns> /// <exception cref="ArgumentNullException">Thrown if <typeparamref name="TKey"/> is a reference type and the provided <paramref name="pair"/> has a NULL <see cref="KeyValuePair{TKey,TValue}.Key"/>.</exception> bool ICollection<KeyValuePair<TKey, IEnumerable<TItem>>>.Remove(KeyValuePair<TKey, IEnumerable<TItem>> pair) { if (ReferenceEquals(pair.Key, null)) throw new ArgumentNullException("pair"); bool result = false; if (_dictionary.ContainsKey(pair.Key)) { List<TItem> list = _dictionary[pair.Key]; foreach (TItem item in pair.Value) result |= list.Remove(item); } return result; } /// <summary> /// Checks for the presence of all items mapped to the specified key in the <see cref="MultiValuedDictionary{TKey,TItem}"/>. /// </summary> /// <param name="pair">The key-value pair specifying the key and associated items for which to check for presence in the dictionary.</param> /// <returns>True if there is all the specified items are mapped to the specified key; False otherwise.</returns> /// <exception cref="ArgumentNullException">Thrown if <typeparamref name="TKey"/> is a reference type and the provided <paramref name="pair"/> has a NULL <see cref="KeyValuePair{TKey,TValue}.Key"/>.</exception> bool ICollection<KeyValuePair<TKey, IEnumerable<TItem>>>.Contains(KeyValuePair<TKey, IEnumerable<TItem>> pair) { if (ReferenceEquals(pair.Key, null)) throw new ArgumentNullException("pair"); bool result = true; if (_dictionary.ContainsKey(pair.Key)) { List<TItem> list = _dictionary[pair.Key]; foreach (TItem item in pair.Value) result &= list.Contains(item); } return result; } /// <summary> /// Copies the mappings of the <see cref="MultiValuedDictionary{TKey,TItem}"/> to an array of <see cref="KeyValuePair{TKey,TValue}"/>s. /// </summary> /// <param name="array">The destination array to which the mappings are to be copied.</param> /// <param name="arrayIndex">The index in the destination array at which to start copying.</param> void ICollection<KeyValuePair<TKey, IEnumerable<TItem>>>.CopyTo(KeyValuePair<TKey, IEnumerable<TItem>>[] array, int arrayIndex) { ((IMultiValuedDictionary<TKey, TItem>) this).CopyTo(array, arrayIndex); } /// <summary> /// Gets an <see cref="IEnumerable{T}"/> of items mapped to the specified key. /// </summary> /// <remarks> /// Calling this method yields the same result as calling <see cref="TryGetItems"/>. /// </remarks> /// <param name="key">The key for which the enumerable of mapped items is to be retrieved.</param> /// <param name="value">The retrieved enumerable of items mapped to the specified key. If no items were mapped to the specified key, this returns an empty enumerable.</param> /// <returns>True if there were items mapped to the specified key; False otherwise.</returns> /// <exception cref="ArgumentNullException">Thrown if <typeparamref name="TKey"/> is a reference type and <paramref name="key"/> is NULL.</exception> bool IDictionary<TKey, IEnumerable<TItem>>.TryGetValue(TKey key, out IEnumerable<TItem> value) { return TryGetItems(key, out value); } #endregion #region KeyCollection Class /// <summary> /// Represents the collection of keys in a <see cref="MultiValuedDictionary{TKey,TItem}"/>. /// </summary> public sealed class KeyCollection : ICollection<TKey> { private readonly Dictionary<TKey, List<TItem>> _dictionary; /// <summary> /// Initializes a new instance of <see cref="KeyCollection"/> whose values reflect the keys in the specified <see cref="MultiValuedDictionary{TKey,TItem}"/>. /// </summary> /// <param name="multiValuedDictionary">The dictionary whose keys are to be reflected in this collection.</param> public KeyCollection(MultiValuedDictionary<TKey, TItem> multiValuedDictionary) { if (ReferenceEquals(multiValuedDictionary, null)) throw new ArgumentNullException("multiValuedDictionary"); _dictionary = multiValuedDictionary._dictionary; } public int Count { get { return _dictionary.Count; } } public bool Contains(TKey key) { if (ReferenceEquals(key, null)) throw new ArgumentNullException("key"); return _dictionary.ContainsKey(key); } public void CopyTo(TKey[] array, int arrayIndex) { foreach (TKey key in _dictionary.Keys) array[arrayIndex++] = key; } public IEnumerator<TKey> GetEnumerator() { return _dictionary.Keys.GetEnumerator(); } void ICollection<TKey>.Add(TKey key) { throw new NotSupportedException(); } void ICollection<TKey>.Clear() { throw new NotSupportedException(); } bool ICollection<TKey>.Remove(TKey key) { throw new NotSupportedException(); } bool ICollection<TKey>.IsReadOnly { get { return true; } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } #endregion #region ItemCollection Class /// <summary> /// Represents the collection of items regardless of key in a <see cref="MultiValuedDictionary{TKey,TItem}"/>. /// </summary> public class ItemCollection : ICollection<TItem> { private readonly Dictionary<TKey, List<TItem>> _dictionary; /// <summary> /// Initializes a new instance of <see cref="ItemCollection"/> whose values reflect the items in the specified <see cref="MultiValuedDictionary{TKey,TItem}"/>. /// </summary> /// <param name="multiValuedDictionary">The dictionary whose items are to be reflected in this collection.</param> public ItemCollection(MultiValuedDictionary<TKey, TItem> multiValuedDictionary) { if (ReferenceEquals(multiValuedDictionary, null)) throw new ArgumentNullException("multiValuedDictionary"); _dictionary = multiValuedDictionary._dictionary; } public int Count { get { int count = 0; foreach (List<TItem> list in _dictionary.Values) count += list.Count; return count; } } public bool Contains(TItem item) { foreach (List<TItem> list in _dictionary.Values) { if (list.Contains(item)) return true; } return false; } public void CopyTo(TItem[] array, int arrayIndex) { foreach (List<TItem> list in _dictionary.Values) { foreach (TItem item in list) array[arrayIndex++] = item; } } public IEnumerator<TItem> GetEnumerator() { foreach (List<TItem> list in _dictionary.Values) { foreach (TItem item in list) yield return item; } } void ICollection<TItem>.Add(TItem item) { throw new NotSupportedException(); } void ICollection<TItem>.Clear() { throw new NotSupportedException(); } bool ICollection<TItem>.Remove(TItem item) { throw new NotSupportedException(); } bool ICollection<TItem>.IsReadOnly { get { return true; } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } #endregion #region ItemListCollection Class private class ItemListCollecion : ICollection<IEnumerable<TItem>> { private readonly MultiValuedDictionary<TKey, TItem> _multiValuedDictionary; public ItemListCollecion(MultiValuedDictionary<TKey, TItem> multiValuedDictionary) { if (ReferenceEquals(multiValuedDictionary, null)) throw new ArgumentNullException("multiValuedDictionary"); _multiValuedDictionary = multiValuedDictionary; } public int Count { get { return _multiValuedDictionary._dictionary.Count; } } public void CopyTo(IEnumerable<TItem>[] array, int arrayIndex) { foreach (List<TItem> value in _multiValuedDictionary._dictionary.Values) array[arrayIndex++] = value.AsReadOnly(); } public IEnumerator<IEnumerable<TItem>> GetEnumerator() { foreach (List<TItem> value in _multiValuedDictionary._dictionary.Values) yield return value.AsReadOnly(); } void ICollection<IEnumerable<TItem>>.Add(IEnumerable<TItem> item) { throw new NotSupportedException(); } void ICollection<IEnumerable<TItem>>.Clear() { throw new NotSupportedException(); } bool ICollection<IEnumerable<TItem>>.Contains(IEnumerable<TItem> items) { foreach (TKey key in _multiValuedDictionary._dictionary.Keys) { bool result = true; List<TItem> list = _multiValuedDictionary._dictionary[key]; foreach (TItem item in items) result &= list.Contains(item); if (result) return true; } return false; } bool ICollection<IEnumerable<TItem>>.IsReadOnly { get { return true; } } bool ICollection<IEnumerable<TItem>>.Remove(IEnumerable<TItem> item) { throw new NotSupportedException(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } #endregion #region ItemList Members private class ItemList : IList<TItem> { private readonly MultiValuedDictionary<TKey, TItem> _source; private readonly TKey _key; public ItemList(TKey key, MultiValuedDictionary<TKey, TItem> source) { if (ReferenceEquals(key, null)) throw new ArgumentNullException("key"); if (ReferenceEquals(source, null)) throw new ArgumentNullException("source"); _key = key; _source = source; } private bool GetList(out IList<TItem> list) { if (_source._dictionary.ContainsKey(_key)) { list = _source._dictionary[_key]; return true; } list = null; return false; } public override int GetHashCode() { return 0x53836841 ^ _key.GetHashCode() ^ _source.GetHashCode(); } public override bool Equals(object obj) { if (obj is ItemList) { ItemList other = (ItemList) obj; return ReferenceEquals(_source, other._source) && _source.Comparer.Equals(_key, other._key); } return false; } public int IndexOf(TItem item) { IList<TItem> list; if (GetList(out list)) return list.IndexOf(item); return -1; } public void Insert(int index, TItem item) { IList<TItem> list; if (GetList(out list)) list.Insert(index, item); else if (index == 0) _source.Add(_key, item); else throw new IndexOutOfRangeException(); } public void RemoveAt(int index) { try { IList<TItem> list; if (GetList(out list)) list.RemoveAt(index); else throw new IndexOutOfRangeException(); } finally { _source.Compact(_key); } } public TItem this[int index] { get { IList<TItem> list; if (GetList(out list)) return list[index]; throw new IndexOutOfRangeException(); } set { IList<TItem> list; if (GetList(out list)) { list[index] = value; return; } throw new IndexOutOfRangeException(); } } public void Add(TItem item) { // this functionality is already directly exposed on the owner _source.Add(_key, item); } public void Clear() { // this functionality is already directly exposed on the owner _source.RemoveAll(_key); } public bool Contains(TItem item) { IList<TItem> list; if (GetList(out list)) return list.Contains(item); return false; } public void CopyTo(TItem[] array, int arrayIndex) { IList<TItem> list; if (GetList(out list)) list.CopyTo(array, arrayIndex); } public int Count { get { IList<TItem> list; if (GetList(out list)) return list.Count; return 0; } } public bool IsReadOnly { get { return false; } } public bool Remove(TItem item) { // this functionality is already directly exposed on the owner return _source.Remove(_key, item); } public IEnumerator<TItem> GetEnumerator() { IList<TItem> list; if (GetList(out list)) return list.GetEnumerator(); return GetNullEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } private static IEnumerator<TItem> GetNullEnumerator() { yield break; } } #endregion #region ReadOnlyMultiValuedDictionaryWrapper Class private class ReadOnlyMultiValuedDictionaryWrapper : IMultiValuedDictionary<TKey, TItem> { private readonly MultiValuedDictionary<TKey, TItem> _source; public ReadOnlyMultiValuedDictionaryWrapper(MultiValuedDictionary<TKey, TItem> source) { _source = source; } public IList<TItem> this[TKey key] { get { return _source._dictionary[key].AsReadOnly(); } } public int Count { get { return _source.Count; } } public ICollection<TKey> Keys { get { return _source.Keys; } } public ICollection<TItem> Items { get { return _source.Items; } } public bool IsReadOnly { get { return true; } } public void Add(TKey key, TItem item) { throw new NotSupportedException(); } public bool Remove(TKey key, TItem item) { throw new NotSupportedException(); } public bool RemoveAll(TKey key) { throw new NotSupportedException(); } public void Clear() { throw new NotSupportedException(); } public bool ContainsKey(TKey key) { return _source.ContainsKey(key); } public void CopyTo(KeyValuePair<TKey, IEnumerable<TItem>>[] array, int arrayIndex) { ((IMultiValuedDictionary<TKey, TItem>) _source).CopyTo(array, arrayIndex); } public bool TryGetItems(TKey key, out IEnumerable<TItem> item) { return _source.TryGetItems(key, out item); } public IEnumerator<KeyValuePair<TKey, IEnumerable<TItem>>> GetEnumerator() { return _source.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } #endregion } }
b2034e700bb0d86b0ade0674d2863cf0f12a4cee
C#
harounhajem/QuizGroupProject_WPF
/Quiz_WPFVersion/ViewModels/StatisticsViewModel2.cs
2.546875
3
using Quiz_WPFVersion.Data; using Quiz_WPFVersion.Models; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Quiz_WPFVersion.ViewModels { class StatisticsViewModel2 { Repository<Course> repo_Courses = new Repository<Course>(); Repository<Education> repo_Education = new Repository<Education>(); public ObservableCollection<Course> _Courses { get; private set; } public ObservableCollection<Education> _Education { get; private set; } public StatisticsViewModel2() { _Courses = new ObservableCollection<Course>(); _Education = new ObservableCollection<Education>(); var course_temp = repo_Courses.GetDataList().ToList(); course_temp.ForEach(u => _Courses.Add(u)); var education_temp = repo_Education.GetDataList().ToList(); education_temp.ForEach(u => _Education.Add(u)); } } }
6ec2b57a64d4d036a257e9501ee1dab65270d07b
C#
Thifall/Siedlisko
/pSiedlisko/Siedlisko/Models/DayModel.cs
2.9375
3
using SiedliskoCommon.Models.Enums; using System; namespace Siedlisko.Models { public class DayModel { #region Fields and Properties public DateTime Date { get; } public bool IsRegularMonthDay { get; } public ReservationStatus ReservationState { get; set; } public int ReservationCounter { get; set; } #endregion #region .ctor public DayModel(DateTime date, bool isRegularMonthDay) { ReservationCounter = 0; this.Date = date; this.IsRegularMonthDay = isRegularMonthDay; ReservationState = ReservationStatus.Free; } public DayModel(int year, int month, int day, bool isRegularMonthDay) : this(new DateTime(year, month, day), isRegularMonthDay) { } #endregion } }
e4c67da1ece5076d90bd6504dcaad6b0ca069de7
C#
pkucherov/PerpetuumServer
/src/Perpetuum/Zones/Terrains/Materials/Minerals/GravelLayer.cs
2.53125
3
using System; using System.Collections.Generic; using System.Drawing; using System.IO; using Perpetuum.IO; using Perpetuum.Zones.Terrains.Materials.Minerals.Generators; namespace Perpetuum.Zones.Terrains.Materials.Minerals { public class GravelConfiguration : IMineralConfiguration { public GravelConfiguration(IZone zone) { ZoneId = zone.Id; Type = MaterialType.Gravel; ExtractionType = MineralExtractionType.Solid; MaxNodes = 1; TotalAmountPerNode = 1500; } public int ZoneId { get; private set; } public MaterialType Type { get; private set; } public MineralExtractionType ExtractionType { get; private set; } public int MaxNodes { get; private set; } public int MaxTilesPerNode { get; private set; } public int TotalAmountPerNode { get; private set; } public double MinThreshold { get; private set; } } public class GravelRepository : IMineralNodeRepository { private readonly IFileSystem _fileSystem; public GravelRepository(IFileSystem fileSystem) { _fileSystem = fileSystem; } public void Insert(MineralNode node) { } public void Update(MineralNode node) { } public void Delete(MineralNode node) { } public List<MineralNode> GetAll() { var bmp = (Bitmap)Image.FromFile(_fileSystem.CreatePath( Path.Combine("layers", "mineral_gravel.0045.png"))); var minerals = new Dictionary<Point, uint>(); int minx = int.MaxValue, miny = int.MaxValue, maxx = 0, maxy = 0; for (int y = 0; y < bmp.Height; y++) { for (int x = 0; x < bmp.Width; x++) { var c = bmp.GetPixel(x, y); var b = c.GetBrightness() * 350000; if (b > 0) { minx = Math.Min(minx, x); miny = Math.Min(miny, y); maxx = Math.Max(maxx, x); maxy = Math.Max(maxy, y); var point = new Point(x, y); minerals.Add(point, (uint)b); } } } var area = new Area(minx, miny, maxx, maxy); var node = new MineralNode(MaterialType.Gravel,area) { Expirable = false }; foreach (var t in minerals) { node.SetValue(t.Key, t.Value); } return new List<MineralNode> { node }; } } public class GravelLayer : OreLayer { public GravelLayer(int width, int height, IMineralConfiguration configuration,GravelRepository repository) : base(width,height,configuration, repository,MineralNodeGeneratorFactory.None) { } public override void AcceptVisitor(MineralLayerVisitor visitor) { visitor.VisitGravelLayer(this); } } }
6c7f5256c222591af2d50a98bd46176aaa8216ac
C#
olegbondur/CSC_T
/CSC_T.BusinessLayer/DAL/Repositories/CountryBusinessRepository.cs
2.78125
3
using CSC_T.BusinessLayer.Entities; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; namespace CSC_T.BusinessLayer.DAL.Repositories { class CountryBusinessRepository : IRepository<CountryBusiness> { protected readonly CSCDbContext _dataContext; protected readonly DbSet<CountryBusiness> _dataSet; public CountryBusinessRepository(CSCDbContext dataContext) { _dataContext = dataContext; _dataSet = dataContext.CountryBusiness; } public void Add(CountryBusiness entity) { _dataSet.Add(entity); } public void AddRange(IEnumerable<CountryBusiness> entities) { _dataSet.AddRange(entities); } public IEnumerable<CountryBusiness> All() { return _dataSet.ToList(); } public async Task<IEnumerable<CountryBusiness>> AllAsync() { return await _dataSet.ToListAsync(); } public void Attach(CountryBusiness entity) { _dataContext.Entry(entity).State = EntityState.Modified; } public void Delete(CountryBusiness entity) { _dataSet.Remove(entity); } public void DeleteRange(IEnumerable<CountryBusiness> entities) { _dataSet.RemoveRange(entities); } public CountryBusiness Find(Func<CountryBusiness, bool> predicate) { return _dataSet.FirstOrDefault(predicate); } public IEnumerable<CountryBusiness> FindAll(Func<CountryBusiness, bool> predicate) { return _dataSet.ToList(); } public async Task<CountryBusiness> FindAsync(Expression<Func<CountryBusiness, bool>> predicate) { return await _dataSet.FirstOrDefaultAsync(predicate); } } }
d266e9f501437276bcbedb9284ef285541c7c097
C#
crawson7/CodeClass
/Assets/DevTools/RedTween/RedTween.cs
2.875
3
using UnityEngine; using System.Collections; using System.Collections.Generic; namespace Red { public delegate void TweenFunction(float value); public class RedTween : MonoBehaviour { private static List<Set> _sets; public static Set CreateSet(string tag="", System.Action end=null) { // Creates and returns a new RedTweenSet. Set is not added active _sets list until it is played. Set comp = new Set(tag, end); return comp; } public static void KillTweens() { // Kills all running tweens instantly without running any onCompletes for(int i=0; i<_sets.Count; i++) { _sets[i].Kill(); } } public static void EndTweens() { // Moves all tweens to thier final target condition instantly // and calls all of the OnComplete actions in the same order they would have been called if things had ended naturally. for(int i=0; i<_sets.Count; i++) { _sets[i].ForceEnd(); } } public static void KillTweensWithTag(string tag) { for(int i=0; i<_sets.Count; i++) { if(_sets[i].Tag == tag) { _sets[i].Kill(); } } } #region PRIVATE private void Awake() { DontDestroyOnLoad(this.gameObject); _sets = new List<Set>(); } private void Start () { } private void Update () { for(int i=0; i<_sets.Count; i++) { _sets[i].Update(); } } protected static bool PlaySet(Set set) { // Add the comp to RedTweens comps. // Make sure that RedTween does not already contain this comp. for(int i=0; i<_sets.Count; i++) { if(_sets[i] == set) { return false; } } _sets.Add(set); return true; } protected static void EndSet(Set set) { if(!_sets.Remove(set)) { Debug.LogWarning("The Set could not be removed"); return; } //Debug.Log("The Tween Set: " + set.Tag + " has completed - " + Time.time); } #endregion #region INSTANT PLAY public static Set StepFunction(TweenFunction function, float time, EaseType ease, System.Action endAction=null, float delay=0f) { Set set = new Set("Instant Step Clip", endAction); set.Track(1).AddStepFunction(function, time, ease, null); set.Play(); return set; } public static Set Wait(float time, System.Action endAction, string tag="") { string setTag = (string.IsNullOrEmpty(tag))? "Instant Wait Clip" : tag; Set set = new Set(setTag, endAction); set.Track(1).AddWait(time); set.Play(); return set; } public static Set MoveTo(GameObject obj, Vector3 target, float time, EaseType ease, System.Action end=null, float delay=0f, string tag="") { string setTag = (string.IsNullOrEmpty(tag))? "Instant MoveTo Clip" : tag; Set set = new Set(setTag, end); set.Track(1).AddMoveTo(obj, target, time, ease); set.SetDelay(delay); set.Play(); return set; } public static Set MoveBy(GameObject obj, Vector3 amount, float time, EaseType ease, System.Action end=null, float delay=0f, string tag="") { string setTag = (string.IsNullOrEmpty(tag))? "Instant MoveBy Clip" : tag; Set set = new Set(setTag, end); set.Track(1).AddMoveBy(obj, amount, time, ease); set.SetDelay(delay); set.Play(); return set; } public static Set LocalMoveTo(GameObject obj, Vector3 target, float time, EaseType ease, System.Action end=null, float delay=0f, string tag="") { string setTag = (string.IsNullOrEmpty(tag))? "Instant LocalMoveBy Clip" : tag; Set set = new Set(setTag, end); set.Track(1).AddLocalMoveTo(obj, target, time, ease); set.SetDelay(delay); set.Play(); return set; } public static Set LocalMoveBy(GameObject obj, Vector3 amount, float time, EaseType ease, System.Action end=null, float delay=0f, string tag="") { string setTag = (string.IsNullOrEmpty(tag))? "Instant LocalMoveBy Clip" : tag; Set set = new Set(setTag, end); set.Track(1).AddLocalMoveBy(obj, amount, time, ease); set.SetDelay(delay); set.Play(); return set; } public static Set UIMoveBy(RectTransform rect, Vector3 amount, float time, EaseType ease, System.Action end=null, float delay=0f, string tag="") { string setTag = (string.IsNullOrEmpty(tag))? "Instant UI Move By Clip" : tag; Set set = new Set(setTag, end); set.Track(1).AddUIMoveBy(rect, amount, time, ease); set.SetDelay(delay); set.Play(); return set; } public static Set UIFadeTo(UnityEngine.UI.Graphic graphic, float target, float time, EaseType ease, System.Action end=null, float delay=0, string tag="") { string setTag = (string.IsNullOrEmpty(tag))? "Instant UI Fade To Clip" : tag; Set set = new Set(setTag, end); set.Track(1).AddUIFadeTo(graphic, target, time, ease); set.SetDelay(delay); set.Play(); return set; } public static Set UIFadeTo(List<UnityEngine.UI.Graphic> graphics, float target, float time, EaseType ease, System.Action end=null, float delay=0, string tag="") { string setTag = (string.IsNullOrEmpty(tag))? "Instant MoveTo Clip" : tag; Set set = new Set(setTag, end); set.Track(1).AddUIFadeTo(graphics, target, time, ease); set.SetDelay(delay); set.Play(); return set; } public static Set UIFadeTo(UnityEngine.UI.Graphic[] graphics, float target, float time, EaseType ease, System.Action end=null, float delay=0, string tag="") { string setTag = (string.IsNullOrEmpty(tag))? "Instant UI Fade To Clip" : tag; Set set = new Set(setTag, end); List<UnityEngine.UI.Graphic> list = new List<UnityEngine.UI.Graphic>(); list.AddRange(graphics); set.Track(1).AddUIFadeTo(list, target, time, ease); set.SetDelay(delay); set.Play(); return set; } public static Set ScaleTo(GameObject obj, Vector3 target, float time, EaseType ease, System.Action end=null, float delay=0f, string tag="") { string setTag = (string.IsNullOrEmpty(tag))? "Instant Scale To Clip" : tag; Set set = new Set(setTag, end); set.Track(1).AddScaleTo(obj, target, time, ease, null); set.SetDelay(delay); set.Play(); return set; } public static Set ScaleTo(GameObject obj, float target, float time, EaseType ease, System.Action end=null, float delay=0f, string tag="") { Vector3 vScale = Vector3.one * target; return ScaleTo(obj, vScale, time, ease, end, delay, tag); } public static Set RotateTo(GameObject obj, Vector3 target, float time, EaseType ease, System.Action end=null, float delay=0f, string tag="") { string setTag = (string.IsNullOrEmpty(tag))? "Instant Rotate To Clip" : tag; Set set = new Set(setTag, end); set.Track(1).AddLocalRotateTo(obj, target, time, ease, null); set.SetDelay(delay); set.Play(); return set; } #endregion #region DEBUG public static void PrintSets() { System.Text.StringBuilder sb = new System.Text.StringBuilder("Red Tween Comps:\n"); if(_sets.Count==0) { sb.AppendLine("EMPTY"); Debug.Log(sb.ToString()); return; } for(int i=0; i<_sets.Count; i++) { sb.AppendLine("Set: " + _sets[i].Tag + (_sets[i].Active? " - Active" : " - Inactive")); } Debug.Log(sb.ToString()); } #endregion #region HELPER CLASSES public class Set { #region VARIABLES AND PROPERTIES private List<System.Action> mEndActions = new List<System.Action>(); private List<System.Action> mStartActions = new List<System.Action>(); private Dictionary<int, Track> mTracks = new Dictionary<int, Track>(); private bool mActive = false; private string _tag; private float mTimeScale = 1.0f; private bool mDelaySet = false; private float mDelay = 0.0f; private float mDelayTicker = 0.0f; private RTSetViz mVisualizer; public string Tag{get{return _tag;}} public bool Active{get{return mActive;}} public int TrackCount{get{return mTracks.Count;}} public Dictionary<int, Track> Tracks {get{return mTracks;}} public float Length { get { float length = 0; foreach(RedTween.Track track in mTracks.Values) { if(track.Length > length) { length = track.Length; } } return length; } } #endregion public Set(string tag, System.Action end) { _tag = tag; if(end!=null) { mEndActions.Add(end); } } public void Update() { if(!mActive){return;} float delta = Time.deltaTime * mTimeScale; // Wait for Delay if applicable. if(mDelaySet) { mDelayTicker += delta; if(mDelayTicker>=mDelay) { mDelaySet = false; } else { return; } } // Update all Tracks in parallel. foreach(Track track in mTracks.Values) { if(track.Update(delta)) { CheckCompletion(); } } if(mVisualizer!=null) { mVisualizer.Update(); } } public void Visualize(float height) { mVisualizer = RedTweenVisualizer.Display(this, height); } #region PRIVATE HELPERS private void CheckCompletion() { foreach(Track track in mTracks.Values) { if(!track.Complete){return;} } // All Tracks are complete. The Set is now complete. End(); } private void End() { mActive = false; RedTween.EndSet(this); for(int i=0; i<mEndActions.Count; i++) { if(mEndActions[i] !=null) { mEndActions[i](); } } mEndActions.Clear(); RedTweenVisualizer.RemoveVizualization(mVisualizer); } public void ForceEnd() { mActive = false; foreach(RedTween.Track track in mTracks.Values) { track.Kill(); } RedTween.EndSet(this); for(int i=0; i<mEndActions.Count; i++) { if(mEndActions[i] !=null) { mEndActions[i](); } } mEndActions.Clear(); RedTweenVisualizer.RemoveVizualization(mVisualizer); } #endregion #region SET MANIPULATIONS public void Play() { //Debug.Log("Starting Tween Set " + Tag + " - " + Time.time); if(mActive) { // Comp is already Active. Debug.LogWarning("This Tween Comp is already Active and cannot be played again."); return; } if(mTracks.Count==0) { // You cannot play a comp that has no sequences Debug.LogWarning("You cannot play this Comp because it does not contain any tracks."); return; } // Run any start actions that have been assigned. for(int i=0; i<mStartActions.Count; i++) { if(mStartActions[i] != null) { mStartActions[i](); } } mStartActions.Clear(); // Start the Set. RedTween.PlaySet(this); mActive = true; // Start Playing All Tracks. foreach(Track track in mTracks.Values) { track.StartInternal(); } } public void Play(float timeScale) { mTimeScale = timeScale; Play(); } public void Pause() { mActive = false; } public void SetTimeScale(float scale) { mTimeScale = scale; } public void SetEndAction(System.Action end) { if(end==null){return;} mEndActions.Add(end); } public void SetStartAction(System.Action start) { if(start == null){return;} mStartActions.Add(start); } public void Kill() { // Kills the Set and all of its tweens witout running any of the end actions. // It also does not attemtp to put all tweens to thier final targets. mEndActions.Clear(); mActive = false; foreach(RedTween.Track track in mTracks.Values) { track.Kill(); } RedTween.EndSet(this); RedTweenVisualizer.RemoveVizualization(mVisualizer); } public void SetDelay(float delay) { if(Mathf.Approximately(delay, 0.0f)) { mDelaySet = false; return; } if(mActive) { Debug.LogWarning("You canot set a delay once the TweenSet has started playing"); mDelaySet = false; return; } mDelay = delay; mDelayTicker = 0; mDelaySet = true; } #endregion public Track Track(int index, bool createIfNotFound=true) { // This will return the track at the specified index. // If the index is not found and create is true, a new track will be created and returned. // If create is false this function can be used to check if a track exists. if(mTracks.ContainsKey(index)) { return mTracks[index]; } if(createIfNotFound) { RedTween.Track t = new RedTween.Track(this, index); mTracks.Add(index, t); return t; } return null; } public Track AddTrack(int index) { return Track(index, true); } } public class Track { // If you play a track that has no clips it will end imediately. #region VARIABLES & PROPERTIES List<RedTweenClip> mClips = new List<RedTweenClip>(); int mActiveIndex; private bool mComplete; private Set mSet; private int mTrackIndex; private System.Action mEndAction; private int mLoops = 0; // The number of times this track should play before it is ended. private int mPlayCount = 0; // The number of times this track has played, counting the first play. private float mRunTime = 0; // The total length of this track in seconds. private float mCurrentTime = 0; public bool Complete{get{return mComplete;}} public List<RedTweenClip> Clips {get{return mClips;}} public float Length {get{return mRunTime;}} public float CurrentTime {get{return mCurrentTime;}} public int TrackId {get{return mTrackIndex;}} #endregion #region PUBLIC ACCESS public Track(RedTween.Set set, int setIndex) { mSet = set; mTrackIndex = setIndex; } public void Play(float timeScale=1.0f) { mSet.Play(timeScale); mPlayCount = 1; } public void StartInternal() { //Debug.Log("Starting Track " + mTrackIndex + " of Set " + mSet.Tag + " - " + Time.time); if(mClips.Count==0) { EndTrack(); return; } mComplete = false; mActiveIndex = 0; mClips[mActiveIndex].Start(Time.deltaTime); } public bool Update(float delta) { // Advances the current clip by the delta time. // delta is the amount of time (adjusted) that has passed since the last animation step. // Returns true if the entire track has completed. if(mComplete){return false;} float remainder = 0; mCurrentTime += delta; if(mClips[mActiveIndex].Update(delta, out remainder)) { // The active clip finished. return AdvanceClips(remainder); } return false; } public void Kill() { mEndAction = null; mComplete = true; } #endregion #region PRIVATE HELPERS private bool AdvanceClips(float startTime) { // Returns true if this is the end of the track. // Advances sequence to the next clip and updates it to the specified start time. mActiveIndex ++; if(mActiveIndex >= mClips.Count) { // There are no more clips. The sequence is complete. if(EndTrack()) {return true;} } mClips[mActiveIndex].Start(startTime); return Update(startTime); } private bool EndTrack() { //Debug.Log("Track " + mTrackIndex + " of Set " + mSet.Tag + " has Ended - " + Time.time); if(mLoops==0 || mPlayCount==mLoops) { mComplete = true; if(mEndAction!=null) { mEndAction(); } return true; } else { mPlayCount ++; mActiveIndex = 0; mCurrentTime = 0; return false; } } #endregion #region TRACK MANIPULATIONS public Track SetEndAction(System.Action endAction) { // Specifies an action that should run once the track is complete. mEndAction = endAction; return this; } public Track Loop(int count=-1) { // This will cause a track to loop. // if Count Less than 0 or no count is sent, the track will loop indefinitly. // The end action on the track will be called after the track finishes its last loop. mLoops = count; return this; } public Track PingPong(int count=-1) { // TODO: Implement return this; } #endregion #region CLIP ADDING public FunctionClip AddStepFunction(TweenFunction func, float time, EaseType ease, System.Action endAction=null) { FunctionClip functionClip = new FunctionClip(this, func, time, ease, endAction); mClips.Add(functionClip); Register(functionClip); return functionClip; } public WaitTweenClip AddWait(float time, System.Action endAction=null) { WaitTweenClip clip = new WaitTweenClip(this, time, endAction); mClips.Add(clip); Register(clip); return clip; } public MoveToTweenClip AddMoveTo(GameObject obj, Vector3 target, float time, EaseType ease, System.Action end=null) { MoveToTweenClip move = new MoveToTweenClip(this, obj, target, time, ease, end, false); mClips.Add(move); Register(move); return move; } public MoveByTweenClip AddMoveBy(GameObject obj, Vector3 amount, float time, EaseType ease, System.Action end=null) { // Check to see if there is a previous MoveBy Clip on this track MoveByTweenClip previous = null; if(mClips.Count>0 && mClips[mClips.Count-1].TweenType == RedTweenType.MoveBy) { previous = (MoveByTweenClip)mClips[mClips.Count-1]; } MoveByTweenClip move = new MoveByTweenClip(this, obj, amount, time, ease, end, previous, false, false); mClips.Add(move); Register(move); return move; } public MoveByTweenClip AddMoveToModifier(GameObject obj, Vector3 amount, float time, EaseType ease, System.Action end=null) { // Requires that this be adjusting the position of a move to track that runs on a higher priority. MoveByTweenClip previous = null; // Check to see if there is a previous MoveBy Clip on this track if(mClips.Count>0 && (mClips[mClips.Count-1].TweenType == RedTweenType.MoveBy || mClips[mClips.Count-1].TweenType == RedTweenType.MoveToModifier)) { previous = (MoveByTweenClip)mClips[mClips.Count-1]; } MoveByTweenClip move = new MoveByTweenClip(this, obj, amount, time, ease, end, previous, true, false); mClips.Add(move); Register(move); return move; } public MoveToTweenClip AddLocalMoveTo(GameObject obj, Vector3 target, float time, EaseType ease, System.Action end=null) { MoveToTweenClip move = new MoveToTweenClip(this, obj, target, time, ease, end, true); mClips.Add(move); Register(move); return move; } public MoveByTweenClip AddLocalMoveBy(GameObject obj, Vector3 amount, float time, EaseType ease, System.Action end=null) { // Check to see if there is a previous MoveBy Clip on this track MoveByTweenClip previous = null; if(mClips.Count>0 && (mClips[mClips.Count-1].TweenType == RedTweenType.LocalMoveBy || mClips[mClips.Count-1].TweenType == RedTweenType.MoveToModifier)) { previous = (MoveByTweenClip)mClips[mClips.Count-1]; } MoveByTweenClip move = new MoveByTweenClip(this, obj, amount, time, ease, end, previous, false, true); mClips.Add(move); Register(move); return move; } public UIMoveByTweenClip AddUIMoveBy(RectTransform obj, Vector3 amount, float time, EaseType ease, System.Action end=null) { UIMoveByTweenClip uiMove = new UIMoveByTweenClip(this, obj, amount, time, ease, end); mClips.Add(uiMove); Register(uiMove); return uiMove; } public UIFadeToTweenClip AddUIFadeTo(List<UnityEngine.UI.Graphic> graphics, float target, float time, EaseType ease, System.Action end=null) { UIFadeToTweenClip uiFade = new UIFadeToTweenClip(graphics, target, time, ease, end); mClips.Add(uiFade); Register(uiFade); return uiFade; } public UIFadeToTweenClip AddUIFadeTo(UnityEngine.UI.Graphic graphics, float target, float time, EaseType ease, System.Action end=null) { List<UnityEngine.UI.Graphic> list = new List<UnityEngine.UI.Graphic>(); list.Add(graphics); UIFadeToTweenClip uiFade = new UIFadeToTweenClip(list, target, time, ease, end); mClips.Add(uiFade); Register(uiFade); return uiFade; } public ScaleTweenClip AddScaleTo(GameObject obj, Vector3 scale, float time, EaseType ease, System.Action end=null) { ScaleTweenClip scaleClip = new ScaleTweenClip(this, obj, scale, time, ease, end); mClips.Add(scaleClip); Register(scaleClip); return scaleClip; } public ScaleTweenClip AddScaleTo(GameObject obj, float scale, float time, EaseType ease, System.Action end=null) { Vector3 vScale = Vector3.one * scale; ScaleTweenClip scaleClip = new ScaleTweenClip(this, obj, vScale, time, ease, end); mClips.Add(scaleClip); Register(scaleClip); return scaleClip; } public LocalRotateToTweenClip AddLocalRotateTo(GameObject obj, Vector3 angle, float time, EaseType ease, System.Action end=null) { LocalRotateToTweenClip rotateClip = new LocalRotateToTweenClip(this, obj, angle, time, ease, end); mClips.Add(rotateClip); Register(rotateClip); return rotateClip; } public RotateToTweenClip AddRotateTo(GameObject obj, Vector3 angle, float time, EaseType ease, System.Action end=null) { RotateToTweenClip rotateClip = new RotateToTweenClip(this, obj, angle, time, ease, end); mClips.Add(rotateClip); Register(rotateClip); return rotateClip; } private void Register(RedTweenClip clip) { mRunTime += clip.Length; #if DEV_MODE || TEST_MODE string stack = System.Environment.StackTrace; clip.SetSource(stack); #endif } #endregion } #endregion } }
597fa9381259afe6144f0145ce66ebace0e69dce
C#
tanghaijun/Fcuk
/DsModels/Models/Mapping/DsBuildingHouseNumberMap.cs
2.515625
3
using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.ModelConfiguration; namespace DsModels.Models.Mapping { public class DsBuildingHouseNumberMap : EntityTypeConfiguration<DsBuildingHouseNumber> { public DsBuildingHouseNumberMap() { // Primary Key this.HasKey(t => t.ID); // Properties this.Property(t => t.ID) .IsRequired() .HasMaxLength(32); this.Property(t => t.BuildingUnitID) .IsRequired() .HasMaxLength(32); this.Property(t => t.BuildingUnitName) .IsRequired() .HasMaxLength(50); this.Property(t => t.BuildingGroupHouseTypeID) .IsRequired() .HasMaxLength(32); this.Property(t => t.BuildingGroupHouseTypeName) .IsRequired() .HasMaxLength(50); this.Property(t => t.CreateUserID) .IsRequired() .HasMaxLength(32); // Table & Column Mappings this.ToTable("DsBuildingHouseNumber"); this.Property(t => t.ID).HasColumnName("ID"); this.Property(t => t.BuildingUnitID).HasColumnName("BuildingUnitID"); this.Property(t => t.BuildingUnitName).HasColumnName("BuildingUnitName"); this.Property(t => t.BuildingGroupHouseTypeID).HasColumnName("BuildingGroupHouseTypeID"); this.Property(t => t.BuildingGroupHouseTypeName).HasColumnName("BuildingGroupHouseTypeName"); this.Property(t => t.Name).HasColumnName("Name"); this.Property(t => t.IsDelete).HasColumnName("IsDelete"); this.Property(t => t.CreateTime).HasColumnName("CreateTime"); this.Property(t => t.UpdateTime).HasColumnName("UpdateTime"); this.Property(t => t.CreateUserID).HasColumnName("CreateUserID"); } } }
6a832d7079aaaf7e1dc888286919c52fc17991b2
C#
pscal4/DesignPatterns
/PizzaSimpleFactory/Program.cs
2.65625
3
using System; namespace PizzaSimpleFactory { class Program { static void Main(string[] args) { SimplePizzaFactory oFactory = new SimplePizzaFactory(); PizzaStore oStore = new PizzaStore(oFactory); oStore.OrderPizza("cheese"); oStore.OrderPizza("pepperoni"); Console.ReadLine(); } } }
77c31bab712ceb8fb40141a7544fd23612204142
C#
SiddharthMishraPersonal/StudyMaterials
/Documents/Common/Projects/StringCombination/StringCombination/StringCombination.cs
3.8125
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace StringCombination { class StringCombination { public static void GetCombinations(string str) { List<string> strColl = new List<string>(); char[] delimeter = " ".ToArray(); strColl.AddRange(str.Split(delimeter, StringSplitOptions.RemoveEmptyEntries).ToList()); Display(strColl); } public static void Display(List<string> strColl) { foreach (var item in strColl) { Console.WriteLine(item); } } } }
20d17f4198f9ad4b73d795230a4d31a761a0a97a
C#
rahuljain5/WPFSampleProjects
/SimpleCalculatorApp/MainWindow.xaml.cs
3.03125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace SimpleCalculatorApp { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { private double number1 = 0; private double number2 = 0; private string optr = string.Empty; public MainWindow() { InitializeComponent(); } private void Button_Click(object sender, RoutedEventArgs e) { } private void btn0_Click(object sender, RoutedEventArgs e) { UpdateNumber(0); } private void UpdateNumber(double d) { if (optr == string.Empty) { number1 = number1 * 10 + d; Result.Text = number1.ToString(); } else { number2 = number2 * 10 + d; Result.Text = number2.ToString(); } } private void btnEqual_Click(object sender, RoutedEventArgs e) { switch (optr) { case "+": Result.Text = (number1 + number2).ToString(); break; case "-": Result.Text = (number1 - number2).ToString(); break; case "*": Result.Text = (number1 * number2).ToString(); break; case "/": Result.Text = (number1 / number2).ToString(); break; case "%": Result.Text = (number1 % number2).ToString(); break; case "^": Result.Text = Math.Pow(number1, number2).ToString(); break; default: break; } number1 = double.Parse(Result.Text); number2 = 0; optr = string.Empty; } private void btn1_Click(object sender, RoutedEventArgs e) { UpdateNumber(1); } private void btn2_Click(object sender, RoutedEventArgs e) { UpdateNumber(2); } private void btn3_Click(object sender, RoutedEventArgs e) { UpdateNumber(3); } private void btnAdd_Click(object sender, RoutedEventArgs e) { optr = "+"; Result.Text = number2.ToString(); } private void btn4_Click(object sender, RoutedEventArgs e) { UpdateNumber(4); } private void btn5_Click(object sender, RoutedEventArgs e) { UpdateNumber(5); } private void btn6_Click(object sender, RoutedEventArgs e) { UpdateNumber(6); } private void btnSub_Click(object sender, RoutedEventArgs e) { optr = "-"; Result.Text = number2.ToString(); } private void btn7_Click(object sender, RoutedEventArgs e) { UpdateNumber(7); } private void btn8_Click(object sender, RoutedEventArgs e) { UpdateNumber(8); } private void btn9_Click(object sender, RoutedEventArgs e) { UpdateNumber(9); } private void btnMul_Click(object sender, RoutedEventArgs e) { optr = "*"; Result.Text = number2.ToString(); } private void btnDiv_Click(object sender, RoutedEventArgs e) { optr = "/"; Result.Text = number2.ToString(); } private void btnCE_Click(object sender, RoutedEventArgs e) { if (optr == string.Empty) { number1 = 0; Result.Text = number1.ToString(); } else { number2 = 0; Result.Text = number1.ToString(); } } private void C_Click(object sender, RoutedEventArgs e) { number1 = 0; number2 = 0; optr = string.Empty; Result.Text = string.Empty; } private void BackSpace_Click(object sender, RoutedEventArgs e) { if (optr == string.Empty) { number1 = (int)number1 / 10; Result.Text = number1.ToString(); } else { number2 = (int)number2 / 10; //number2= Math.Floor(number2); Result.Text = number2.ToString(); } } private void btnDecimal_Click(object sender, RoutedEventArgs e) { } private void btnMod_Click(object sender, RoutedEventArgs e) { optr = "%"; } private void btnSqrt_Click(object sender, RoutedEventArgs e) { if (number1 > 0) number1 = Math.Sqrt(number1); Result.Text = number1.ToString(); } private void btnPower_Click(object sender, RoutedEventArgs e) { optr = "^"; } private void Grid_Click(object sender, RoutedEventArgs e) { Button btn = e.Source as Button; if (btn != null) { } } } }
a18098a71f04addfef1caa675a5a369e0bfba2f7
C#
KevinGuedes/FinancialControl
/FinancialControl.DAL/Repositories/CategoryRepository.cs
2.71875
3
using FinancialControl.BLL.Models; using FinancialControl.DAL.Interfaces; using Microsoft.EntityFrameworkCore; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace FinancialControl.DAL.Repositories { public class CategoryRepository : GenericRepository<Category>, ICategoryRepository { private readonly Context _context; public CategoryRepository(Context context) : base(context) { _context = context; } public new async Task<IEnumerable<object>> GetAll() { try { IEnumerable<Category> categories = await _context.Categories.Include(c => c.Type).ToListAsync(); var x = categories .Select(c => new { c.Id, c.Name, c.Icon, c.TypeId, Type = new { c.Type.Id, c.Type.Name } }); return x; } catch (Exception ex) { throw; } } public new async Task<Category> GetById(int id) { try { return await _context.Categories.Include(c => c.Type).FirstOrDefaultAsync(c => c.Id == id); } catch (Exception ex) { throw; } } } }
a116c12f0872cd7a205b9852f7bbff161993fb22
C#
KoutaFurusawa/oci-sdk-net
/OCISDK.Core/LoadBalancer/Model/RuleDetails.cs
2.640625
3
using System; using System.Collections.Generic; using System.Text; namespace OCISDK.Core.LoadBalancer.Model { /// <summary> /// An object that represents an action to apply to a listener. /// </summary> // TODO: Cannot parse JSON with multiple subtype structures. public class RuleDetails { /// <summary> /// <para>Required: yes</para> /// </summary> public string Action { get; set; } /// <summary> /// A header name that conforms to RFC 7230. /// </summary> public string Header { get; set; } /// <summary> /// A header value that conforms to RFC 7230. /// </summary> public string Value { get; set; } /// <summary> /// A string to prepend to the header value. The resulting header value must conform to RFC 7230. /// </summary> public string Prefix { get; set; } /// <summary> /// A string to append to the header value. The resulting header value must conform to RFC 7230. /// </summary> public string Suffix { get; set; } /// <summary> /// The list of HTTP methods allowed for this listener. /// By default, you can specify only the standard HTTP methods defined in the HTTP Method Registry. /// You can also see a list of supported standard HTTP methods in the Load Balancing service documentation at Managing Rule Sets. /// Your backend application must be able to handle the methods specified in this list. /// The list of HTTP methods is extensible. If you need to configure custom HTTP methods, contact My Oracle Support to remove the restriction for your tenancy. /// </summary> public List<string> AllowedMethods { get; set; } /// <summary> /// The HTTP status code to return when the requested HTTP method is not in the list of allowed methods. /// The associated status line returned with the code is mapped from the standard HTTP specification. The default value is 405 (Method Not Allowed). /// </summary> public int? StatusCode { get; set; } /// <summary> /// A condition to apply to an access control rule. /// </summary> public List<RuleCondition> Conditions { get; set; } /// <summary> /// A brief description of the access control rule. Avoid entering confidential information. /// </summary> public string Description { get; set; } } /// <summary> /// An object that represents the action of adding a header to a request. This rule applies only to HTTP listeners. /// </summary> public class AddHttpRequestHeaderRule { /// <summary> /// Required value: ADD_HTTP_REQUEST_HEADER /// <para>Required: yes</para> /// </summary> public readonly string Action = "ADD_HTTP_REQUEST_HEADER"; /// <summary> /// A header name that conforms to RFC 7230. /// <para>Required: yes</para> /// </summary> public string Header { get; set; } /// <summary> /// A header value that conforms to RFC 7230. /// <para>Required: yes</para> /// </summary> public string Value { get; set; } } /// <summary> /// An object that represents the action of modifying a request header value. This rule applies only to HTTP listeners. /// /// This rule adds a prefix, a suffix, or both to the header value. /// </summary> public class ExtendHttpRequestHeaderValueRule { /// <summary> /// Required value: EXTEND_HTTP_REQUEST_HEADER_VALUE /// <para>Required: yes</para> /// </summary> public readonly string Action = "EXTEND_HTTP_REQUEST_HEADER_VALUE"; /// <summary> /// A header name that conforms to RFC 7230. /// <para>Required: yes</para> /// </summary> public string Header { get; set; } /// <summary> /// A string to prepend to the header value. The resulting header value must conform to RFC 7230. /// <para>Required: no</para> /// </summary> public string Prefix { get; set;} /// <summary> /// A string to append to the header value. The resulting header value must conform to RFC 7230. /// <para>Required: no</para> /// </summary> public string Suffix { get; set; } } /// <summary> /// An object that represents the action of removing a header from a request. This rule applies only to HTTP listeners. /// /// If the same header appears more than once in the request, the load balancer removes all occurances of the specified header. /// </summary> public class RemoveHttpRequestHeaderRule { /// <summary> /// Required value: REMOVE_HTTP_REQUEST_HEADER /// <para>Required: yes</para> /// </summary> public readonly string Action = "REMOVE_HTTP_REQUEST_HEADER"; /// <summary> /// A header name that conforms to RFC 7230. /// <para>Required: yes</para> /// </summary> public string Header { get; set; } } /// <summary> /// An object that represents the action of adding a header to a response. This rule applies only to HTTP listeners. /// </summary> public class AddHttpResponseHeaderRule { /// <summary> /// Required value: ADD_HTTP_RESPONSE_HEADER /// <para>Required: yes</para> /// </summary> public readonly string Action = "ADD_HTTP_RESPONSE_HEADER"; /// <summary> /// A header name that conforms to RFC 7230. /// <para>Required: yes</para> /// </summary> public string Header { get; set; } /// <summary> /// A header value that conforms to RFC 7230. /// <para>Required: yes</para> /// </summary> public string Value { get; set; } } /// <summary> /// An object that represents the action of modifying a response header value. This rule applies only to HTTP listeners. /// /// This rule adds a prefix, a suffix, or both to the header value. /// </summary> public class ExtendHttpResponseHeaderValueRule { /// <summary> /// Required value: EXTEND_HTTP_RESPONSE_HEADER_VALUE /// <para>Required: yes</para> /// </summary> public readonly string Action = "EXTEND_HTTP_RESPONSE_HEADER_VALUE"; /// <summary> /// A header name that conforms to RFC 7230. /// <para>Required: yes</para> /// </summary> public string Header { get; set; } /// <summary> /// A string to prepend to the header value. The resulting header value must conform to RFC 7230. /// <para>Required: no</para> /// </summary> public string Prefix { get; set; } /// <summary> /// A string to append to the header value. The resulting header value must conform to RFC 7230. /// <para>Required: no</para> /// </summary> public string Suffix { get; set; } } /// <summary> /// An object that represents the action of removing a header from a response. This rule applies only to HTTP listeners. /// /// If the same header appears more than once in the response, the load balancer removes all occurances of the specified header. /// </summary> public class RemoveHttpResponseHeaderRule { /// <summary> /// Required value: REMOVE_HTTP_RESPONSE_HEADER /// <para>Required: yes</para> /// </summary> public readonly string Action = "REMOVE_HTTP_RESPONSE_HEADER"; /// <summary> /// A header name that conforms to RFC 7230. /// <para>Required: yes</para> /// </summary> public string Header { get; set; } } /// <summary> /// An object that represents the action of returning a specified response code when the requested HTTP method is not in the list of allowed methods for the listener. /// The load balancer does not forward a disallowed request to the back end servers. The default response code is 405 Method Not Allowed. /// /// If you set the response code to 405 or leave it blank, the system adds an "allow" response header that contains a list of the allowed methods for the listener. /// If you set the response code to anything other than 405 (or blank), the system does not add the "allow" response header with a list of allowed methods. /// /// This rule applies only to HTTP listeners. No more than one ControlAccessUsingHttpMethodsRule object can be present in a given listener. /// </summary> public class ControlAccessUsingHttpMethodsRule { /// <summary> /// Required value: CONTROL_ACCESS_USING_HTTP_METHODS /// <para>Required: yes</para> /// </summary> public readonly string Action = "CONTROL_ACCESS_USING_HTTP_METHODS"; /// <summary> /// The list of HTTP methods allowed for this listener. /// <para>Required: yes</para> /// </summary> public List<string> AllowedMethods { get; set; } /// <summary> /// The HTTP status code to return when the requested HTTP method is not in the list of allowed methods. /// The associated status line returned with the code is mapped from the standard HTTP specification. /// The default value is 405 (Method Not Allowed). /// <para>Required: no</para> /// </summary> public int? StatusCode { get; set; } } /// <summary> /// An object that represents the action of configuring an access control rule. /// Access control rules permit access to application resources based on user-specified match conditions. /// This rule applies only to HTTP listeners. /// </summary> public class AllowRule { /// <summary> /// Required value: ALLOW /// <para>Required: yes</para> /// </summary> public readonly string Action = "ALLOW"; /// <summary> /// <para>Required: yes</para> /// </summary> public List<RuleCondition> Conditions { get; set; } /// <summary> /// A brief description of the access control rule. Avoid entering confidential information. /// <para>Required: no</para> /// </summary> public string Description { get; set; } } }
192cfbed1adf752ec7e78a6c58bac56277ed45aa
C#
clemzizer/VisualStudioProjects
/SocketProj/SocketProjClient/Program.cs
3.140625
3
using System; using System.Net; using System.Net.Sockets; using System.Text; namespace SocketProjClient { class MainClass { public static void Main(string[] args) { Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); IPEndPoint iep = new IPEndPoint(IPAddress.Loopback, 5000); for ( ; ; ) { String Message = Console.ReadLine(); sock.SendTo(Encoding.UTF8.GetBytes(Message), iep); if (Message == "quit") break; } } } }
8060515efaa1cf4ef6a1d079ca1cd6b43dccc9c4
C#
huwyss/KataCatalog
/KataTicTacToe/TicTacToe/PlayerManager.cs
3.3125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TicTacToe { public class PieceManager { public PlayerType FirstMover { get; set; } public Piece GetPiece(PlayerType player) { if (FirstMover == PlayerType.Human) { return player == PlayerType.Human ? Piece.X : Piece.O; } else { return player == PlayerType.Human ? Piece.O : Piece.X; } } public PlayerType GetRandomPlayerType() { Random rand = new Random(); if (rand.Next(0, 2) == 0) { return PlayerType.Computer; } else { return PlayerType.Human; } } } }
ead0f9d92fe92c0db084033f6d4706c7dcfa3021
C#
shendongnian/download4
/code8/1480335-40592825-131527736-2.cs
2.96875
3
public class MyNullableTextBox : TextBox { public bool IsEmpty {get{return String.IsNullOrEmpty(base.Text);} } public decimal Value { get { if (this.IsEmpty) return 0M; else { decimal parsedValue; bool parsed = Decimal.TryParse(base.Text, out parsedValue); if (!parsed) // decide what you want in this case else return parsedValue; } } } }
074ee28009e9a7d2259524de7cb471e4f15a5117
C#
JKorf/CoinEx.Net
/CoinEx.Net/Converters/KlineIntervalConverter.cs
2.78125
3
using CoinEx.Net.Enums; using CryptoExchange.Net.Converters; using System.Collections.Generic; namespace CoinEx.Net.Converters { internal class KlineIntervalConverter : BaseConverter<KlineInterval> { public KlineIntervalConverter() : this(true) { } public KlineIntervalConverter(bool quotes) : base(quotes) { } protected override List<KeyValuePair<KlineInterval, string>> Mapping => new List<KeyValuePair<KlineInterval, string>> { new KeyValuePair<KlineInterval, string>( KlineInterval.OneMinute, "1min"), new KeyValuePair<KlineInterval, string>(KlineInterval.ThreeMinutes, "3min"), new KeyValuePair<KlineInterval, string>(KlineInterval.FiveMinutes, "5min"), new KeyValuePair<KlineInterval, string>( KlineInterval.FifteenMinutes, "15min"), new KeyValuePair<KlineInterval, string>(KlineInterval.ThirtyMinutes, "30min"), new KeyValuePair<KlineInterval, string>( KlineInterval.OneHour, "1hour"), new KeyValuePair<KlineInterval, string>(KlineInterval.TwoHours, "2hour"), new KeyValuePair<KlineInterval, string>(KlineInterval.FourHours, "4hour"), new KeyValuePair<KlineInterval, string>(KlineInterval.SixHours, "6hour"), new KeyValuePair<KlineInterval, string>(KlineInterval.TwelveHours, "12hour"), new KeyValuePair<KlineInterval, string>(KlineInterval.OneDay, "1day"), new KeyValuePair<KlineInterval, string>(KlineInterval.ThreeDays, "3day"), new KeyValuePair<KlineInterval, string>( KlineInterval.OneWeek, "1week") }; } }
e71e55efb0fe5bbafc80332dfe82f2629c1eb377
C#
ZJU-CC98/Medal
/CC98.Medal/src/CC98.Medal/Data/MedalDataModel.cs
2.546875
3
using System.Collections; using JetBrains.Annotations; using Microsoft.EntityFrameworkCore; namespace CC98.Medal.Data { /// <summary> /// 为勋章系统提供数据库模型。 /// </summary> public class MedalDataModel : DbContext { #region 构造方法 /// <summary> /// 用指定的选项初始化一个数据连接的新实例。 /// </summary> /// <param name="options">数据库链接选项。</param> [UsedImplicitly(ImplicitUseKindFlags.Access)] public MedalDataModel(DbContextOptions<MedalDataModel> options) : base(options) { } #endregion #region 配置 /// <summary> /// Override this method to further configure the model that was discovered by convention from the entity types /// exposed in <see cref="Microsoft.EntityFrameworkCore.DbSet{TEntity}" /> properties on your derived context. The resulting model may be cached /// and re-used for subsequent instances of your derived context. /// </summary> /// <remarks> /// If a model is explicitly set on the options for this context (via <see cref="DbContextOptionsBuilder.UseModel(Microsoft.EntityFrameworkCore.Metadata.IModel)" />) /// then this method will not be run. /// </remarks> /// <param name="modelBuilder"> /// The builder being used to construct the model for this context. Databases (and other extensions) typically /// define extension methods on this object that allow you to configure aspects of the model that are specific /// to a given database. /// </param> protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity<UserMedalIssue>().HasKey(i => new { i.UserId, i.MedalId }); modelBuilder.Entity<UserMedalApply>().HasKey(i => new { i.UserId, i.MedalId }); } #endregion #region 数据表 /// <summary> /// 获取或设置数据库中包含的勋章的集合。 /// </summary> public virtual DbSet<Medal> Medals { get; set; } /// <summary> /// 获取或设置数据库中包含的用户勋章颁发记录的集合。 /// </summary> public virtual DbSet<UserMedalIssue> UserMedalIssues { get; set; } /// <summary> /// 获取或设置数据库中包含的勋章分类的集合。 /// </summary> public virtual DbSet<MedalCategory> MedalCategories { get; set; } /// <summary> /// 获取或设置数据库中包含的用户勋章申请记录的集合。 /// </summary> public virtual DbSet<UserMedalApply> UserMedalApplies { get; set; } /// <summary> /// 获取或设置数据库中包含的日志的集合。 /// </summary> public virtual DbSet<Log> Logs { get; set; } #endregion } }
daf9957b35576d86a01bcfc81ad51320f4940251
C#
CCClaudiu/LibraryManagementSystem
/Proiect biblioteca/Carte.cs
2.546875
3
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.OleDb; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Collections; namespace Proiect_Biblioteca { class Carte { static string conString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|/carti.accdb;"; OleDbConnection con = new OleDbConnection(conString); OleDbCommand cmd; OleDbDataAdapter adaptor; DataTable dt = new DataTable(); TextBox t1; TextBox t2; TextBox t3; TextBox t4; ComboBox c1; DataGridView g1; public void afiseaza(DataGridView g) { con.Open(); OleDbCommand cmd = con.CreateCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = "select * from carti"; cmd.ExecuteNonQuery(); DataTable dt = new DataTable(); OleDbDataAdapter adaptor = new OleDbDataAdapter(cmd); adaptor.Fill(dt); g.DataSource = dt; con.Close(); } public void adauga1(DataGridView dt, string titlu, string autor, string editura, string status) { string sql = "INSERT INTO carti(TC,Autor,Editura,Status) VALUES('" + titlu + "','" + autor + "','" + editura + "','" + status + "')"; cmd = new OleDbCommand(sql, con); try { con.Open(); if ((cmd.ExecuteNonQuery() > 0)) { MessageBox.Show("S-a adaugat cu succes"); } con.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message); con.Close(); } } public void adauga(DataGridView dt, string titlu, string autor, string editura, string status) { //sql STMT //cmd.CommandText = "insert into carti values('" + titlu + "','" + autor + "','" + Editura + "','" + status + "')"; string sql = "INSERT INTO carti(TC,Autor,Editura,Status) VALUES('" + titlu + "','" + autor + "','" + editura + "','" + status + "')"; cmd = new OleDbCommand(sql, con); //adauga param //cmd.Parameters.AddWithValue("@TITLU", titlu); //cmd.Parameters.AddWithValue("@AUTOR", autor); //cmd.Parameters.AddWithValue("@EDITURA",editura); //cmd.Parameters.AddWithValue("@STATUS", status); //deschide conexiunea si executa adaugarea try { con.Open(); if (cmd.ExecuteNonQuery() > 0) { //clearTxts(); MessageBox.Show("S-a adaugat cu succes"); } con.Close(); //receptie(); afiseaza(g1); } catch (Exception ex) { MessageBox.Show(ex.Message); con.Close(); } } public void editeaza(int id, string titlu, string autor, string editura, string status) { //sql stmt //string sql = "UPDATE carti SET TC='" + titlu + "',Autor='" + autor + "',Editura='" + editura + "'WHERE Status=" + status + ""; string sql = "UPDATE carti SET TC='" + titlu + "',Autor='" + autor + "',Editura='" + editura + "',Status='" + status + "' WHERE ID=" + id + ""; cmd = new OleDbCommand(sql, con); //OPEN CON,UPDATE,RETRIEVE DGVIEW try { con.Open(); adaptor = new OleDbDataAdapter(cmd); adaptor.UpdateCommand = con.CreateCommand(); adaptor.UpdateCommand.CommandText = sql; if (adaptor.UpdateCommand.ExecuteNonQuery() > 0) { //clearTxts(); MessageBox.Show("S-a editat cu succes"); } con.Close(); //refresh //receptie(); //afiseaza(g1); } catch (Exception ex) { MessageBox.Show(ex.Message); con.Close(); } } private void clearTxts(TextBox t1,TextBox t2,TextBox t3,TextBox t4,ComboBox c1) { t1.Text = ""; t2.Text = ""; t3.Text = ""; t4.Text = ""; c1.Text = ""; } } }
beefe2646373bd3f5b9077388aa2e16e1a0c26b6
C#
RodmanII/Tutorial
/Tutorial/Models/Person.cs
2.84375
3
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; using Tutorial.Utils; namespace Tutorial.Models { public class Person { public int Id { get; set; } [Required(ErrorMessage = ErrorMessages.required)] [StringLength(100, ErrorMessage = ErrorMessages.stringLength)] /*Name es el nombre de la propiedad en la clase indicada mediante ResourceType de la cual se tomara el valor de localizacion, no es el texto que va a mostrar en lugar del nombre del campo, eso lo define la propiedad Description*/ [Display(Name = "Name", ResourceType = typeof(Localization.Person))] public string Firstname { get; set; } [Required(ErrorMessage = ErrorMessages.required)] [StringLength(100, ErrorMessage = ErrorMessages.stringLength)] [Display(Name = "Lastname", ResourceType = typeof(Localization.Person))] public string Lastname { get; set; } [Required(ErrorMessage = ErrorMessages.required)] [RegularExpression(@"^\d{4}-((0\d)|(1[012]))-(([012]\d)|3[01])$", ErrorMessage = ErrorMessages.dateRegex)] [Display(Name = "Dob", Description = "Date of birth", ResourceType = typeof(Localization.Person))] public string DoB { get; set; } public int Age { get; set; } [Required(ErrorMessage = ErrorMessages.required)] [Range(1,500, ErrorMessage = ErrorMessages.range)] [Display(Name = "Wei", ResourceType = typeof(Localization.Person))] public Int16 Weight { get; set; } public Byte Enabled { get; set; } public Person() { } } }
26d58318d4bca9756b998b2c1575739974a0938d
C#
igorskir/MyTestProjects
/7. Patterns/Decorator/IceCreamDecorator/Program.cs
3.3125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IceCreamDecorator { class Program { static void Main(string[] args) { IComponent a = new PlainIceCream(); IComponent b = new CandyTopping(a); IComponent c = new NutsTopping(b); c.AddTopping(); Console.ReadLine(); } } public interface IComponent { void AddTopping(); } public class PlainIceCream : IComponent { public void AddTopping() { Console.WriteLine("Plain Ice Cream ready for some toppings"); } } public abstract class Topping : IComponent { protected IComponent input; public Topping(IComponent i) { input = i; //store the item to be decorated } public abstract void AddTopping(); } public class CandyTopping : Topping, IComponent { public CandyTopping(IComponent iceCream) :base(iceCream) { } public override void AddTopping() { input.AddTopping(); Console.WriteLine("Candy topping added"); } } public class NutsTopping : Topping, IComponent { public NutsTopping(IComponent iceCream) :base(iceCream) { } public override void AddTopping() { input.AddTopping(); Console.WriteLine("Nuts topping added"); } } }
d3b378236ea185cd713f1ceaca8e8ffd925f6bc5
C#
iskorotkov/matrix-multiplication
/src/TestGenerator/MatrixGenerator.cs
3.78125
4
using System; namespace TestGenerator { /// <summary> /// Generator for creating random matrices /// </summary> public class MatrixGenerator { private readonly double _min; private readonly double _max; private readonly Random _random = new Random(); /// <summary> /// Initialize new MatrixGenerator that uses values in range <paramref name="min"/>..<paramref name="max"/> /// </summary> /// <param name="min">Min value for RNG</param> /// <param name="max">Max value for RNG (exclusive)</param> public MatrixGenerator(double min, double max) { _min = min; _max = max; } /// <summary> /// Generate new matrix /// </summary> /// <param name="rows">Number of rows</param> /// <param name="columns">Number of columns</param> /// <returns>Generated matrix</returns> public double[,] NewMatrix(int rows, int columns) { var result = new double[rows, columns]; for (var i = 0; i < rows; i++) { for (var j = 0; j < columns; j++) { result[i, j] = NewValue(); } } return result; } /// <summary> /// Generate pair of matrices that can be multiplied /// </summary> /// <param name="aRows">Number of rows of the first matrix</param> /// <param name="aColumns">Number of columns of the first matrix (= number of rows of the second matrix)</param> /// <param name="bColumns">Number of columns of the second matrix</param> /// <returns>Pair of matrices</returns> public (double[,] A, double[,] B) NewMatrixPair(int aRows, int aColumns, int bColumns) => (NewMatrix(aRows, aColumns), NewMatrix(aColumns, bColumns)); /// <summary> /// Generate new value to use in matrix /// </summary> /// <returns>Random value in range</returns> private double NewValue() => _random.NextDouble() * (_max - _min) + _min; } }
4c7d2c98a50b577fea4d831a592b98af4d874444
C#
entvex/GoFSchoolCode
/GoFStateNasted/FlashlightStates.cs
2.84375
3
namespace GoFStateNasted { /// <summary> /// This is the abstract state /// </summary> public class FlashlightState { public virtual void OnEnter(Flashlight context) { } public virtual void HandlePower(Flashlight context) { } public virtual void ModePressed(Flashlight context) { } } /// <summary> /// This is the concrete State off /// </summary> public class Off : FlashlightState { public override void HandlePower(Flashlight context) { context.LightOn(); context.SetState(new On()); } } /// <summary> /// This is the concrete State on /// </summary> public class On : FlashlightState { public override void OnEnter(Flashlight context) { context.SetState(new SOLID()); } public override void HandlePower(Flashlight context) { context.LightOff(); context.SetState(new Off()); } } /// <summary> /// This is the concrete nested State SOLID /// </summary> public class SOLID : On { public override void OnEnter(Flashlight context) { } public override void ModePressed(Flashlight context) { context.solidLED(); context.SetState(new FLASHING()); } } /// <summary> /// This is the concrete nested State FLASHING /// </summary> public class FLASHING : On { public override void OnEnter(Flashlight context) { } public override void ModePressed(Flashlight context) { context.flashLEDs(); context.SetState(new SOLID()); } } }
2ec662e7215f6d07df3b864216365cafc3401da2
C#
n02378281/Algorithms
/Prep/ArrPartitionLabels.cs
3.828125
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace InterviewPrep.Prep { // 763. Partition Labels /*You are given a string s. * We want to partition the string into as many parts as possible so that each letter appears in at most one part. * Note that the partition is done so that after concatenating all the parts in order, the resultant string should be s. * Return a list of integers representing the size of these parts. * Input: s = "ababcbacadefegdehijhklij" * Output: [9,7,8] * Explanation: * The partition is "ababcbaca", "defegde", "hijhklij". * This is a partition so that each letter appears in at most one part. * A partition like "ababcbacadefegde", "hijhklij" is incorrect, because it splits s into less parts. */ public static class ArrPartitionLabels { public static IList<int> PartitionLabels(string s) { List<int> partitionLabels = new List<int>(); int[] lastindexes = new int[26]; for (int i = 0; i < s.Length; i++) { lastindexes[s[i] - 'a'] = i; } int x = 0; while (x < s.Length) { int end = lastindexes[s[x] - 'a']; int y = x; while (y != end) { end = Math.Max(end, lastindexes[s[y++] - 'a']); } partitionLabels.Add(y - x + 1); x = y + 1; } return partitionLabels; } } }
51120aff050c585fe366a0a182466600b260d1c8
C#
EnjiRouz/2D-Fantasy-Game
/Assets/Inventory/InventorySlot.cs
2.671875
3
using Assets.FantasyHeroes.Scripts; using UnityEngine; using UnityEngine.UI; /// <summary> /// Слот инвентаря. Интерфейсный элемент /// </summary> public class InventorySlot : MonoBehaviour { /// <summary> /// Кнопка с изображением предмета в слоте /// </summary> public GameObject imageButton; /// <summary> /// Кнопка удаления предмета. /// </summary> public Button removeButton; /// <summary> /// Герой, которому принадлежит инвентарь /// </summary> private GameObject player; /// <summary> /// Предмет в слоте /// </summary> Item item; /// <summary> /// Инвентарь, которому принадлежит слот /// </summary> Inventory inventory; /// <summary> /// Установить предмет в качестве содержимого слота. /// Интерфейсное действие - орисовывает предмет на кнопке и кнопку удаления. /// </summary> /// <param name="item">предмет</param> public void SetItem(Item item) { this.item = item; try { if (item != null) { imageButton.GetComponent<Image>().enabled = true; imageButton.GetComponent<Image>().sprite = item.image; if (removeButton != null) { removeButton.interactable = true; } imageButton.SetActive(true); } } catch { } } /// <summary> /// Обработчик нажатия на кнопку предмета. /// </summary> public void OnUse() { var hero = player.GetComponent<Character>(); item.PutOn(hero); } /// <summary> /// Обработчик нажатия на кнопку удаления предмета /// </summary> public void OnRemove() { inventory.Drop(item.type); imageButton.GetComponent<Image>().sprite = null; imageButton.GetComponent<Image>().enabled = false; removeButton.interactable = false; } /// <summary> /// Инициализация /// </summary> private void Start() { player = GameObject.FindGameObjectWithTag("Player"); inventory = player.GetComponent<Inventory>(); } }