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
1dd107ffa1367d973eadf02ecdd0d0f93a549115
C#
sgyalta/dotNet-turbo
/src/Qoollo.Turbo/Threading/PartialThreadBlocker.cs
2.828125
3
using Qoollo.Turbo.Threading.ServiceStuff; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Qoollo.Turbo.Threading { /// <summary> /// Primitive that limits the number of simultaniously executing threads (transfers specified number of threads to Wait state) /// </summary> [DebuggerDisplay("RealWaiterCount = {RealWaiterCount}, ExpectedWaiterCount = {ExpectedWaiterCount}")] internal class PartialThreadBlocker { private static readonly int _processorCount = Environment.ProcessorCount; private static readonly Action<object> _cancellationTokenCanceledEventHandler = new Action<object>(CancellationTokenCanceledEventHandler); /// <summary> /// CancellationToken cancellation handler /// </summary> /// <param name="obj"><see cref="PartialThreadBlocker"/> instance</param> private static void CancellationTokenCanceledEventHandler(object obj) { PartialThreadBlocker blocker = obj as PartialThreadBlocker; TurboContract.Assert(blocker != null, conditionString: "blocker != null"); lock (blocker._lockObj) { Monitor.PulseAll(blocker._lockObj); } } // ====================== private volatile int _expectedWaiterCount; private volatile int _realWaiterCount; private readonly object _lockObj = new object(); /// <summary> /// <see cref="PartialThreadBlocker"/> constructor /// </summary> /// <param name="expectedWaiterCount">Number of threads to be blocked</param> public PartialThreadBlocker(int expectedWaiterCount) { if (expectedWaiterCount < 0) throw new ArgumentOutOfRangeException(nameof(expectedWaiterCount), "expectedWaiterCount should be greater or equal to 0"); _expectedWaiterCount = expectedWaiterCount; _realWaiterCount = 0; } /// <summary> /// <see cref="PartialThreadBlocker"/> constructor /// </summary> public PartialThreadBlocker() : this(0) { } /// <summary> /// Gets the number of threads that should be blocked /// </summary> public int ExpectedWaiterCount { get { return _expectedWaiterCount; } } /// <summary> /// Gets the number of threads that already was blocked /// </summary> public int RealWaiterCount { get { return _realWaiterCount; } } /// <summary> /// Notifies waiting threads that several of them can continue execution /// </summary> /// <param name="diff">The number of threads that potentially should be unblocked</param> private void WakeUpWaiters(int diff) { if (diff >= 0) return; lock (_lockObj) { if (Math.Abs(diff) == 1) Monitor.Pulse(_lockObj); else Monitor.PulseAll(_lockObj); } } /// <summary> /// Sets the number of threads that should be blocked (<see cref="ExpectedWaiterCount"/>) /// </summary> /// <param name="newValue">New value</param> /// <returns>Previous value that was stored in <see cref="ExpectedWaiterCount"/></returns> public int SetExpectedWaiterCount(int newValue) { TurboContract.Requires(newValue >= 0, conditionString: "newValue >= 0"); int prevValue = Interlocked.Exchange(ref _expectedWaiterCount, newValue); WakeUpWaiters(newValue - prevValue); return prevValue; } /// <summary> /// Increases the number of threads that should be blocked /// </summary> /// <param name="addValue">The value by which it is necessary to increase the number of blocked threads</param> /// <returns>Updated value stored in <see cref="ExpectedWaiterCount"/></returns> public int AddExpectedWaiterCount(int addValue) { SpinWait sw = new SpinWait(); int expectedWaiterCount = _expectedWaiterCount; TurboContract.Assert(expectedWaiterCount + addValue >= 0, "Negative ExpectedWaiterCount. Can be commented"); int newExpectedWaiterCount = Math.Max(0, expectedWaiterCount + addValue); while (Interlocked.CompareExchange(ref _expectedWaiterCount, newExpectedWaiterCount, expectedWaiterCount) != expectedWaiterCount) { sw.SpinOnce(); expectedWaiterCount = _expectedWaiterCount; TurboContract.Assert(expectedWaiterCount + addValue >= 0, "Negative ExpectedWaiterCount. Can be commented"); newExpectedWaiterCount = Math.Max(0, expectedWaiterCount + addValue); } WakeUpWaiters(newExpectedWaiterCount - expectedWaiterCount); return newExpectedWaiterCount; } /// <summary> /// Decreases the number of threads that should be blocked /// </summary> /// <param name="subValue">The value by which it is necessary to decrease the number of blocked threads</param> /// <returns>Updated value stored in <see cref="ExpectedWaiterCount"/></returns> public int SubstractExpectedWaiterCount(int subValue) { return AddExpectedWaiterCount(-subValue); } /// <summary> /// Blocks the current thread if it is required /// </summary> /// <param name="timeout">Waiting timeout in milliseconds</param> /// <param name="token">Cancellation token</param> /// <returns>True if the current thread successfully passed the <see cref="PartialThreadBlocker"/> (false - exited by timeout)</returns> public bool Wait(int timeout, CancellationToken token) { token.ThrowIfCancellationRequested(); if (timeout < 0) timeout = Timeout.Infinite; if (_realWaiterCount >= _expectedWaiterCount) return true; if (timeout == 0) return false; uint startTime = 0; int currentTime = Timeout.Infinite; if (timeout != Timeout.Infinite) startTime = TimeoutHelper.GetTimestamp(); for (int i = 0; i < 10; i++) { if (_realWaiterCount >= _expectedWaiterCount) return true; if (i == 5) Thread.Yield(); else SpinWaitHelper.SpinWait(16 + 4 * i); } using (CancellationTokenHelper.RegisterWithoutECIfPossible(token, _cancellationTokenCanceledEventHandler, this)) { lock (_lockObj) { if (_realWaiterCount < _expectedWaiterCount) { try { _realWaiterCount++; while (_realWaiterCount <= _expectedWaiterCount) { token.ThrowIfCancellationRequested(); if (timeout != Timeout.Infinite) { currentTime = TimeoutHelper.UpdateTimeout(startTime, timeout); if (currentTime <= 0) return false; } if (!Monitor.Wait(_lockObj, currentTime)) return false; } } finally { _realWaiterCount--; } } } } return true; } /// <summary> /// Blocks the current thread if it is required /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Wait() { bool semaphoreSlotTaken = Wait(Timeout.Infinite, new CancellationToken()); TurboContract.Assert(semaphoreSlotTaken, conditionString: "semaphoreSlotTaken"); } /// <summary> /// Blocks the current thread if it is required /// </summary> /// <param name="token">Cancellation token</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Wait(CancellationToken token) { bool semaphoreSlotTaken = Wait(Timeout.Infinite, token); TurboContract.Assert(semaphoreSlotTaken, conditionString: "semaphoreSlotTaken"); } /// <summary> /// Blocks the current thread if it is required /// </summary> /// <param name="timeout">Waiting timeout in milliseconds</param> /// <returns>True if the current thread successfully passed the <see cref="PartialThreadBlocker"/> (false - exited by timeout)</returns> public bool Wait(TimeSpan timeout) { long timeoutMs = (long)timeout.TotalMilliseconds; if (timeoutMs > int.MaxValue) throw new ArgumentOutOfRangeException(nameof(timeout)); return Wait((int)timeoutMs, new CancellationToken()); } /// <summary> /// Blocks the current thread if it is required /// </summary> /// <param name="timeout">Waiting timeout in milliseconds</param> /// <param name="token">Cancellation token</param> /// <returns>True if the current thread successfully passed the <see cref="PartialThreadBlocker"/> (false - exited by timeout)</returns> public bool Wait(TimeSpan timeout, CancellationToken token) { long timeoutMs = (long)timeout.TotalMilliseconds; if (timeoutMs > int.MaxValue) throw new ArgumentOutOfRangeException(nameof(timeout)); return Wait((int)timeoutMs, token); } /// <summary> /// Blocks the current thread if it is required /// </summary> /// <param name="timeout">Waiting timeout in milliseconds</param> /// <returns>True if the current thread successfully passed the <see cref="PartialThreadBlocker"/> (false - exited by timeout)</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Wait(int timeout) { return Wait(timeout, new CancellationToken()); } } }
13ef8cf574649801cc4fdcc5ee1e516f8010375b
C#
ButinVladimir/Training-Algorithms
/Algorithms/Fun 4/MarsExploration.cs
3.296875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Algorithms.Fun_4 { public static class MarsExploration { public static int Solve(string s) { int m = 0; int result = 0; for (int i = 0; i < s.Length; i++) { if (m == 1 && s[i] != 'O' || m != 1 && s[i] != 'S') { result++; } m = (m + 1) % 3; } return result; } } }
c76c2dbfbce89ab7fd1bbcf5e2d828340a1d3adc
C#
MaximePerso/AppForceSensor
/Classe/ClassXml.cs
2.828125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml; using System.Xml.Serialization; namespace K2000Rs232App { class ClassXml { public static void Serialize(Object data, string fileName) { Type type = data.GetType(); XmlSerializer xs = new XmlSerializer(type); XmlTextWriter xmlWriter = new XmlTextWriter(fileName, System.Text.Encoding.UTF8); xmlWriter.Formatting = Formatting.Indented; xs.Serialize(xmlWriter, data); xmlWriter.Close(); } public static Object Deserialize(Type type, string fileName) { XmlSerializer xs = new XmlSerializer(type); XmlTextReader xmlReader = new XmlTextReader(fileName); Object data = xs.Deserialize(xmlReader); xmlReader.Close(); return data; } } }
d0d238fcc29ea0aa6945aa745b09893b0187ec21
C#
William-Larsson/dotnet-advertiser-subscriber-api
/advertising/Models/CurrencyConverter.cs
2.90625
3
using System; using System.IO; using System.Net.Http; using System.Text.RegularExpressions; using System.Threading.Tasks; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace advertising.Models { public class CurrencyConverter { // Rapid API info for API calls. public string APIKey = Environment.GetEnvironmentVariable("API_KEY"); public string APIHost = Environment.GetEnvironmentVariable("API_HOST"); public HttpClient client { get; set; } // Constructor, setup Http client with SSL certificate. public CurrencyConverter(){ // Bypass SSL certificate to get a proper SSL connection. HttpClientHandler clientHandler = new HttpClientHandler(); clientHandler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return true; }; client = new HttpClient(clientHandler); } // TODO Return convertion rate public async Task<double> GetExchangeRate(string from, string to) { var fromTo = $"{from}_{to}"; var request = new HttpRequestMessage { Method = HttpMethod.Get, RequestUri = new Uri($"{APIHost}?q={from}_{to}&compact=ultra&apiKey={APIKey}"), }; using (var response = await client.SendAsync(request)) { response.EnsureSuccessStatusCode(); string json = await response.Content.ReadAsStringAsync(); var data = (JObject)JsonConvert.DeserializeObject(json); return (double)data[fromTo]; } } } }
0a6b3d5a3a513fbfdbd686c5d74850f49c2e3172
C#
PeterSolnet/PIP
/Provisioning/Extensions/StringExtensions.cs
3.828125
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Provisioning.Extensions { public static class StringExtensions { /// <summary> /// Returns a new string containing the leftmost <paramref name="len"/> characters of this string. /// </summary> /// <param name="str"></param> /// <param name="len"> /// The number of characters to return. If greater than the length of the string, the entire string is returned. /// </param> /// <returns>A new string</returns> public static string Left(this string str, int len) { return str.Substring(0, Math.Min(len, str.Length)); } /// <summary> /// Returns a new string containing the rightmost <paramref name="len"/> characters of this string. /// </summary> /// <param name="str"></param> /// <param name="len"> /// The number of characters to return. If greater than the length of the string, the entire string is returned. /// </param> /// <returns>A new string</returns> public static string Right(this string str, int len) { return str.Substring(Math.Max((str.Length - len), 0)); } /// <summary> /// Converts a comma separated string of ints e.g. 1,2,3,4,5 to a generic List of ints /// </summary> /// <param name="str">A comma separated list of ints</param> /// <returns>List of ints in the given string</returns> public static List<int> ToIntArray(this string str) { string[] splitted = System.Text.RegularExpressions.Regex.Split(str, ","); return Array.ConvertAll<string, int>(splitted, int.Parse).ToList(); } } }
457a6bf550c8515ba4cfc3bbf7ee7bb98edd0190
C#
mFireworks/Mystery-Dungeon-Engine
/Assets/Scripts/GameEngine/DungeonEngine/DungeonGen/DungeonLevel.cs
2.515625
3
using System.Collections; using System.Collections.Generic; using UnityEngine; using Assets.GameEngine.DungeonEngine.DungeonGen.Generators; using Assets.GameEngine.DungeonEngine.DungeonGen.Enviroment; using Assets.GameEngine.Entities; namespace Assets.GameEngine.DungeonEngine.DungeonGen { public class DungeonLevel : MonoBehaviour { [Tooltip("What is the horizontial bounds of this dungeon level?")] [Min(10)] public int xRadius = 10; [Tooltip("What is the vertical bounds of this dungeon level?")] [Min(10)] public int yRadius = 10; [Tooltip("Which enviroment controller is this dungeon using?")] public EnviromentController enviroment; [Tooltip("What are the different generators that can be used to generate the levels of this dungeon")] public List<GeneratorInterface> generators; private DungeonMap currentFloor = null; // Deff more information will be needed in here, like creature/item/tile spawn lists public void GenerateFloor() { enviroment.clearEnviroment(); currentFloor = generators[Random.Range(0, generators.Count - 1)].GenerateLevel(xRadius, yRadius); enviroment.produceEnviroment(currentFloor.getMap()); PlayerCreature[] players = FindObjectsOfType<PlayerCreature>(); foreach (PlayerCreature player in players) { (int, int) roomLoc = getRandomRoomLocation(currentFloor.getRooms()); player.transform.position = new Vector2(roomLoc.Item1, roomLoc.Item2); } (int, int) stairsLoc = getRandomRoomLocation(currentFloor.getRooms()); transform.parent.gameObject.transform.position = new Vector2(stairsLoc.Item1, stairsLoc.Item2); } private (int, int) getRandomRoomLocation(List<Room> roomList) { Room startRoom = roomList[Random.Range(0, roomList.Count - 1)]; int startX = startRoom.getRoomCorner().Item1 + Random.Range(0, startRoom.getRoomSpace().GetLength(1)); int startY = startRoom.getRoomCorner().Item2 + Random.Range(0, startRoom.getRoomSpace().GetLength(0)); return (startX, startY); } } }
b279cf6c66ab0269d97c9b05ec2d4eef497b361d
C#
thewakingsands/SaintCoinach
/SaintCoinach/Text/Expressions/GenericExpression.cs
3.125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SaintCoinach.Text.Expressions { public class GenericExpression : IValueExpression { public static readonly GenericExpression Empty = new GenericExpression(null); private readonly object _Value; public object Value { get { return _Value; } } public GenericExpression(object value) { _Value = value; } public override string ToString() { if (Value == null) return string.Empty; return Value.ToString(); } public void ToString(StringBuilder output) { output.Append(Value); } } }
bf88e56c88b7d1e6a4c339d965265e8545d23034
C#
Morales-10/Morales.CompulsoryAssignment1PetShop
/Morales.CompulsoryPetShop.Domain/Services/PetService.cs
2.671875
3
using System.Collections.Generic; using Morales.CompulsoryPetShop.Core.IServices; using Morales.CompulsoryPetShop.Core.Models; using Morales.CompulsoryPetShop.Domain.IRepositories; namespace Morales.CompulsoryPetShop.Domain.Services { public class PetService : IPetService { private IPetRepository _petRepository; public PetService(IPetRepository petRepository) { _petRepository = petRepository; } public Pet CreatePet(Pet pet) { return _petRepository.CreatePet(pet); } public Pet RemovePet(int id) { return _petRepository.RemovePet(id); } public Pet UpdatePet(Pet pet) { return _petRepository.UpdatePet(pet); } public Pet ReadByPetId(int id) { return _petRepository.ReadByPetId(id); } public List<Pet> ReadAllPets() { return _petRepository.ReadAllPets(); } public Pet Create(Pet pet) { throw new System.NotImplementedException(); } public object GetById(int id) { throw new System.NotImplementedException(); } public void Delete(int id) { throw new System.NotImplementedException(); } public void UpdatePetName(int id, string name) { throw new System.NotImplementedException(); } } }
8d3da76803d7124fbd468212f4043b9a401205f3
C#
Ciuriya/WonderJam-Hiver-2020
/Assets/Code/Components/WordCleaner.cs
2.515625
3
using System.Collections; using UnityEngine; using Photon.Pun; /* * Detects combo breaks and deletes words that require deletion. */ public class WordCleaner : MonoBehaviour { [Tooltip("The score handler linked to this combo break updater")] public ScoreHandler Score; [Tooltip("The active set of words on screen")] public FallingWordSet ActiveWordSet; [Tooltip("The player ID linked to this cleaner")] public int ValidPlayerID; [Tooltip("Sound to play when the combo is broken")] public AudioClip ComboBreakSound; private AudioSource audioSource; void Awake() { audioSource = GetComponent<AudioSource>(); StartCoroutine(UpdateWords()); } private IEnumerator UpdateWords() { while(PhotonNetwork.InRoom) { yield return new WaitForSeconds(0.1f); for(int i = ActiveWordSet.Count() - 1; i >= 0; i--) { FallingWord word = ActiveWordSet._items[i]; if(!word) continue; if(word.BrokeCombo && PhotonNetwork.LocalPlayer.ActorNumber == ValidPlayerID) { Score.BreakCombo(); audioSource.PlayOneShot(ComboBreakSound); } if(word.RequiresDeletion) { ActiveWordSet.Remove(word); Destroy(word.gameObject); } } } } }
9d1244993c2d6ace49e0e06baba7576fc13614c7
C#
PakornAbiz/GoLogger
/GoLogger/CreateTable.cs
2.625
3
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace GoLogger { public partial class CreateTable : Form { public CreateTable() { InitializeComponent(); } public List<int> GetDivisionIndex() { List<int> indexChecked = new List<int>(); for (int i = 2; i < clbTable.Items.Count; i++) { if (clbTable.GetItemChecked(i)) { indexChecked.Add(i); } } return indexChecked; } public int GetTotalColumn() => clbTable.Items.Count; public List<string> GetColumn() { List<string> columnList = new List<string>(); foreach (string item in clbTable.Items) { columnList.Add(item); } return columnList; } private void btnAdd_Click(object sender, EventArgs e) { if (!string.IsNullOrEmpty(tbAdd.Text)) { clbTable.Items.Add(tbAdd.Text); tbAdd.Clear(); } } private void btnCancel_Click(object sender, EventArgs e) { this.Close(); } private void btnDel_Click(object sender, EventArgs e) { if (clbTable.Items.Count > 0) { clbTable.Items.RemoveAt(clbTable.SelectedIndex); } } private void btnOk_Click(object sender, EventArgs e) { this.DialogResult = DialogResult.OK; } private void tbAdd_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { btnAdd_Click(sender, e); } } } }
abb0cd0540606dd065a529db541c8d1a706eaece
C#
PatrykPodworski/Mieszkando
/MarklogicDataLayer/XQuery/Sequence.cs
3.03125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MarklogicDataLayer.XQuery { public class Sequence : Expression { readonly List<Expression> _elements; public Sequence(IEnumerable<string> strings) : this(strings.Select(x => new Literal(x))) { } public Sequence(params Expression[] elements) { _elements = new List<Expression>(elements); } public Sequence(IEnumerable<Expression> elements) { _elements = new List<Expression>(elements); } public override string Query { get { var qb = new StringBuilder("("); var idx = 0; foreach (var element in _elements) { qb.Append(element.Query); if (++idx < _elements.Count) { qb.Append(", "); } } qb.Append(")"); return qb.ToString(); } } public override string RawQuery { get { var qb = new StringBuilder("("); var idx = 0; foreach (var element in _elements) { qb.Append(element.RawQuery); if (++idx < _elements.Count) { qb.Append(", "); } } qb.Append(")"); return qb.ToString(); } } } }
b46bda5422a50a299612d17ffef26616c106da09
C#
Berk1034/ObjFormatParcer
/ObjFormatParcer/Types/Face.cs
2.890625
3
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; namespace ObjFormatParcer.Types { public class Face { private char indexesSeparator = '/'; public List<int> VertexIndexes { get; private set; } = new List<int>(); public List<int> VertexTextureIndexes { get; private set; } = new List<int>(); public List<int> VertexNormalIndexes { get; private set; } = new List<int>(); public Face() { } public Face(int[] vertexIndexes, int[] vertexTextureIndexes, int[] vertexNormalIndexes) { this.VertexIndexes.AddRange(vertexIndexes); this.VertexTextureIndexes.AddRange(vertexTextureIndexes); this.VertexNormalIndexes.AddRange(vertexNormalIndexes); } public void LoadIndexes(string[] rawIndexes) { foreach (var rawIndex in rawIndexes) { var indexes = rawIndex.Split(indexesSeparator); this.VertexIndexes.Add(Convert.ToInt32(indexes[0])); if (indexes.Length == 2) { this.VertexTextureIndexes.Add(Convert.ToInt32(indexes[1])); } else if (indexes[1].Trim().Length == 1) { this.VertexTextureIndexes.Add(Convert.ToInt32(indexes[1])); this.VertexNormalIndexes.Add(Convert.ToInt32(indexes[2])); } else { this.VertexNormalIndexes.Add(Convert.ToInt32(indexes[2])); } } } } }
22ee740a5f6295cdbb20789bb6740c80bf6e9079
C#
jenha88/practice2
/PartPractice/PP3/MainWindow.xaml.cs
2.9375
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 PP3 { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void btb_Click(object sender, RoutedEventArgs e) { string manufacturer, name, image; manufacturer = txtM.Text; name = txtN.Text; image = txtI.Text; //validating if there is any empty spaces if (string.IsNullOrEmpty(manufacturer)==true) { MessageBox.Show("Sorry that is an invalid Manufacturer"); } if (string.IsNullOrEmpty(name)==true) { MessageBox.Show("Sorry that is an invalid Name"); } double price; if (double.TryParse(txtP.Text,out price)==false) { MessageBox.Show("Sorry that is an invalid price"); } if (string.IsNullOrEmpty(image)==true) { MessageBox.Show("Sorry that is an invalid image"); } //overloaded c Toys TT = new Toys() { Manufacturer = manufacturer, Name=name, Price=price, Image=image }; //adding it to the listbox lstBox.Items.Add(TT); } private void lstBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { //casting in the class Toys selectedToy = (Toys)lstBox.SelectedItem; var uri = new Uri(selectedToy.Image); var img = new BitmapImage(uri); image.Source = img; MessageBox.Show($"{selectedToy.GetAisle()}"); } } }
4c2e70cb1373fb5b34c046e1e77a3aa83be19ab2
C#
ovidiu-porumb/RememberTheDate
/OP.RememberTheDate.Storage.SQL/SqlReadStorage.cs
2.765625
3
using System; using System.Collections.Generic; using System.Linq; using NPoco; using OP.RememberTheDate.Storage.Contracts; using OP.RememberTheDate.Storage.Model; // ReSharper disable InconsistentNaming namespace OP.RememberTheDate.Storage.SQL { // ReSharper disable ClassNeverInstantiated.Global public class SqlReadStorage : IReadStorage<DateModel> { private readonly Database database; public SqlReadStorage() { database = StorageFactory.Database.GetDatabase(); } public IEnumerable<DateModel> GetRegisteredDatesFromYear(int year) { //nasty hack 'cause the where clause apparently cannot access a property of the datetime value return database.Query<DateModel>().ToList().Where(e => e.Date.Year == year); } public IEnumerable<DateModel> GetRegisteredDatesNamedLike(string eventName) { return database.Query<DateModel>().Where(e => e.EventToMark.ToLower().Contains(eventName.ToLower())).ToList(); } public IEnumerable<DateModel> GetRegisteredDatesInsideInterval(DateTime from, DateTime to) { return database.Query<DateModel>().Where(e => e.Date > from && e.Date < to).ToList(); } public IEnumerable<DateModel> GetRegisteredDatesFromMonth(int month) { //nasty hack 'cause the where clause apparently cannot access a property of the datetime value return database.Query<DateModel>().ToList().Where(e => e.Date.Month == month); } } }
0d78d6f81f9c275cfa94b2867c8d0fe59417453f
C#
NewLifeX/X
/NewLife.Core/Log/LogLevel.cs
2.859375
3
 namespace NewLife.Log { /// <summary>日志等级</summary> public enum LogLevel : System.Byte { /// <summary>打开所有日志记录</summary> All = 0, /// <summary>最低调试。细粒度信息事件对调试应用程序非常有帮助</summary> Debug, /// <summary>普通消息。在粗粒度级别上突出强调应用程序的运行过程</summary> Info, /// <summary>警告</summary> Warn, /// <summary>错误</summary> Error, /// <summary>严重错误</summary> Fatal, /// <summary>关闭所有日志记录</summary> Off = 0xFF } }
f1d391ff70f8a5481a5aaa3d1cb9fc0ddf6cbd38
C#
fabien-chevalley/RaspberryPi.IoT
/MMALSharp/src/MMALSharp.Common/Handlers/StreamCaptureHandler.cs
3.28125
3
using System; using System.Collections.Generic; using System.IO; namespace MMALSharp.Handlers { /// <summary> /// Processes the image data to a stream. /// </summary> public abstract class StreamCaptureHandler : ICaptureHandler { /// <summary> /// A Stream instance that we can process image data to /// </summary> protected Stream CurrentStream { get; set; } /// <summary> /// A list of files that have been processed by this capture handler /// </summary> public List<ProcessedFileResult> ProcessedFiles { get; set; } = new List<ProcessedFileResult>(); /// <summary> /// The total size of data that has been processed by this capture handler /// </summary> protected int Processed { get; set; } /// <summary> /// The directory to save to (if applicable) /// </summary> public string Directory { get; protected set; } /// <summary> /// The extension of the file (if applicable) /// </summary> public string Extension { get; protected set; } protected StreamCaptureHandler(string directory, string extension) { this.Directory = directory.TrimEnd('/'); this.Extension = extension.TrimStart('.'); System.IO.Directory.CreateDirectory(this.Directory); } /// <summary> /// Creates a new File (FileStream), assigns it to the Stream instance of this class and disposes of any existing stream. /// </summary> public void NewFile() { this.CurrentStream?.Dispose(); var now = DateTime.Now.ToString("dd-MMM-yy HH-mm-ss"); var filename = this.Directory + "/" + now + "." + this.Extension; int i = 0; while(File.Exists(filename)) { filename = this.Directory + "/" + now + " " + i + "." + this.Extension; i++; } this.CurrentStream = File.Create(filename); } public virtual ProcessResult Process() { return new ProcessResult(); } /// <summary> /// Processes the data passed into this method to this class' Stream instance. /// </summary> /// <param name="data">The image data</param> public virtual void Process(byte[] data) { this.Processed += data.Length; if (this.CurrentStream.CanWrite) this.CurrentStream.Write(data, 0, data.Length); else throw new IOException("Stream not writable."); } /// <summary> /// Allows us to do any further processing once the capture method has completed. /// </summary> public virtual void PostProcess() { try { if (this.CurrentStream.GetType() == typeof(FileStream)) { this.ProcessedFiles.Add(new ProcessedFileResult(this.Directory, this.GetFilename(), this.Extension)); } MMALLog.Logger.Info($"Successfully processed {Helpers.ConvertBytesToMegabytes(this.Processed)}"); } catch(Exception e) { MMALLog.Logger.Warn($"Something went wrong while processing stream: {e.Message}"); } } /// <summary> /// Gets the filename that a FileStream points to /// </summary> /// <returns>The filename</returns> public string GetFilename() { if (this.CurrentStream.GetType() == typeof(FileStream)) { return Path.GetFileNameWithoutExtension(((FileStream)this.CurrentStream).Name); } throw new NotSupportedException("Cannot get filename from non FileStream object"); } public string GetFilepath() { if (this.CurrentStream.GetType() == typeof(FileStream)) { return ((FileStream)this.CurrentStream).Name; } throw new NotSupportedException("Cannot get path from non FileStream object"); } public void Dispose() { CurrentStream?.Dispose(); } } }
0259a38da0b2cb73809689ef29ae4bb1fca49fa2
C#
shuheydev/XamarinEssentialsCompassTest
/XamarinEssentialsCompassTest/XamarinEssentialsCompassTest/MainPage.xaml.cs
2.640625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Essentials; using Xamarin.Forms; namespace XamarinEssentialsCompassTest { public partial class MainPage : ContentPage { public MainPage() { InitializeComponent(); //値を取得したときのイベントハンドラをセット Compass.ReadingChanged += Compass_ReadingChanged; //コンパス値の取得開始 Compass.Start(SensorSpeed.UI); } //値を取得したときに実行される private void Compass_ReadingChanged(object sender, CompassChangedEventArgs e) { var data = e.Reading; //ラベルに表示 LabelCompass.Text = data.HeadingMagneticNorth.ToString(); } } }
0a61529d173d2cd7a1767ea5e1cb320d8b5510bc
C#
zzxxhhzxh/EmergenceGuardian.Encoder
/FFmpeg/Models/CloseProcessEventArgs.cs
2.546875
3
using System; using HanumanInstitute.FFmpeg.Services; namespace HanumanInstitute.FFmpeg { /// <summary> /// Represents a method that will be called when a process needs to be closed. /// </summary> public delegate void CloseProcessEventHandler(object sender, CloseProcessEventArgs e); /// <summary> /// Provides process information for CloseProcess event. /// </summary> public class CloseProcessEventArgs : EventArgs { public IProcess Process { get; set; } public bool Handled { get; set; } = false; //public CloseProcessEventArgs() { } public CloseProcessEventArgs(IProcess process) { Process = process; } } }
ac20200e853b7ba70f2449c42ce06dd623893506
C#
patrickCode/Design-Patterns
/PipelineFramework.v2/PipelineFramework/Shared/Common/Enum/MiddlewareStatus.cs
2.796875
3
namespace PipelineFramework.Common.Enum { public class MiddlewareStatus: Enumeration { private readonly string _description; private readonly bool _isExecutionCompleted; public string Description { get => _description; } public bool IsExecutionCompleted { get => _isExecutionCompleted; } public MiddlewareStatus() : base() { } public MiddlewareStatus(int code, string name, string description, bool isExecutionCompleted): base(code, name) { _description = description; _isExecutionCompleted = isExecutionCompleted; } public static MiddlewareStatus Created = new CreatedStatusEnum(); public static MiddlewareStatus Running = new RunningStatusEnum(); public static MiddlewareStatus Executing = new ExecutingStatusEnum(); public static MiddlewareStatus Completed = new CompletedStatusEnum(); public static MiddlewareStatus Faulted = new FaultedStatusEnum(); private class CreatedStatusEnum: MiddlewareStatus { public CreatedStatusEnum(): base(1, "Created", "The middleware has been created.", false) { } } private class RunningStatusEnum : MiddlewareStatus { public RunningStatusEnum() : base(2, "Running", "The middleware is running and is ready to accept incoming mails.", false) { } } private class ExecutingStatusEnum : MiddlewareStatus { public ExecutingStatusEnum() : base(3, "Executing", "The middleware has receiveid a message and is executing the message.", false) { } } private class CompletedStatusEnum : MiddlewareStatus { public CompletedStatusEnum() : base(4, "Completed", "The middleware has succesfully completed executing the message.", true) { } } private class FaultedStatusEnum : MiddlewareStatus { public FaultedStatusEnum() : base(5, "Fauled", "The middleware has encountered an error while excuting the message.", true) { } } } }
b17ed03e839d86e740f44b39eb0b448a2c630e11
C#
flufy3d/Akvfx
/Assets/Akvfx/Internal/XYTable.cs
2.625
3
using Microsoft.Azure.Kinect.Sensor; using System.Runtime.InteropServices; using System.Threading.Tasks; namespace Akvfx { // // Per pixel ray table ("XY table") used to unproject depth samples to the // 3D camera space // // This directly invokes a native method in libk4a to avoid double symbol // definition problem between System.Numerics and System.Numerics.Vectors. // sealed class XYTable { // Public property: Table data public float [] Data { get; private set; } // Float vvector types struct Float2 { public float x, y; } struct Float3 { public float x, y, z; } // Constructor public XYTable(Calibration calibration, int width, int height) { // Data storage allocation var table = new float [width * height * 2]; // Initialize the xy table in a parallel way. Parallel.For(0, height, y => { Float2 v2; Float3 v3; bool isValid; v2.y = y; var offs = width * 2 * y; for (var x = 0; x < width; x++) { v2.x = x; k4a_calibration_2d_to_3d( ref calibration, ref v2, 1, CalibrationDeviceType.Color, CalibrationDeviceType.Color, out v3, out isValid ); table[offs++] = v3.x; table[offs++] = v3.y; } }); // Publish the table data. Data = table; } // k4a_calibration_2d_to_3d native method in libk4a [DllImport("k4a", CallingConvention = CallingConvention.Cdecl)] static extern int k4a_calibration_2d_to_3d( [In] ref Calibration calibration, ref Float2 source_point2d, float source_depth, CalibrationDeviceType source_camera, CalibrationDeviceType target_camera, out Float3 target_point3d, out bool valid ); } }
77013b054b088c293077a91ec78a308497dde6dc
C#
trayburn/BlogPosts
/DictionaryAdapterIsLove/Part2/IUserData.cs
2.71875
3
using System; using Castle.Components.DictionaryAdapter; using System.Collections.Generic; using System.Collections; namespace Part2 { [NestedDictionaryGetterBehavior] public interface IUserData { [Key("UserId")] int Id { get; set; } [Key("UserName")] IUserName Name { get; set; } } public interface IUserName { [Key("UserFirstName")] string FirstName { get; set; } [Key("UserMiddleName")] string MiddleName { get; set; } [Key("UserLastName")] string LastName { get; set; } } public class CustomName : IUserName { private IDictionary dict; public CustomName(IDictionary dictionary) { this.dict = dictionary; } public string FirstName { get; set; } public string MiddleName { get; set; } public string LastName { get; set; } } }
dc0323d7c7757c1197f2fbe28a53465a13dfb10b
C#
ibnuS78/TestKaryaMurni
/KaryaMurniTask/Services/TaskToDoServices.cs
2.625
3
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Data.SqlClient; using System.Data; using System.IO; using KaryaMurniTask.Helper; using KaryaMurniTask.Models; namespace KaryaMurniTask { public class TaskToDoServices : ITaskToDoServices { SQLHelper sqlh; private string spProcess = "exec uspProcessMstTask "; private string spGetData = "exec uspVwGetTask "; public TaskToDoServices(SQLHelper SqlHelper) { this.sqlh = SqlHelper; this.sqlh.switchConnection("1"); } public string CreateTask(MstTask data) { try { var ExpressinSQL = spProcess; ExpressinSQL += "'CREATE','" + data.TaskTitle + "','" + data.TaskDescription + "'," + data.Progress; ExpressinSQL += ",'" + data.ExpiredDate.ToString() + "'"; var rst = sqlh.Execute(ExpressinSQL); sqlh.Dispose(); return "Success To Create Task With ID = " + rst["ID"]; } catch (Exception ex) { sqlh.Dispose(); return ex.Message; } } public string UpdateTask(MstTask data) { try { var ExpressinSQL = spProcess; ExpressinSQL += "'UPDATE','" + data.TaskTitle + "','" + data.TaskDescription + "'," + data.Progress; ExpressinSQL += ",'" + data.ExpiredDate.ToString() + "'," + data.ID; var rst = sqlh.Execute(ExpressinSQL); sqlh.Dispose(); return "Success To Update Task ID = " + rst["ID"]; } catch (Exception ex) { sqlh.Dispose(); return ex.Message; } } public List<MstTask> GetData(string gettype,int Id = 0) { List<MstTask> rst = new List<MstTask>(); try { var ExpressinSQL = spGetData; ExpressinSQL += "'" + gettype + "'," + Id.ToString(); var dr = sqlh.Execute(ExpressinSQL); while (dr.Read()) { rst.Add(new MstTask() { TaskTitle = dr["TaskTitle"].ToString(), TaskDescription = dr["TaskDescription"].ToString(), Progress = decimal.Parse(dr["Progress"].ToString()), ExpiredDate = DateTime.Parse(dr["ExpiredDate"].ToString()), ID = Int32.Parse(dr["ID"].ToString()), }); } sqlh.Dispose(); return rst; } catch (Exception ex) { rst.Add(new MstTask() { TaskTitle = ex.Message }); sqlh.Dispose(); return rst; } } public string UpdatePercentage(MstTask data) { try { var ExpressinSQL = spProcess; ExpressinSQL += "'PCT','" + data.TaskTitle + "','" + data.TaskDescription + "'," + data.Progress; ExpressinSQL += ",'" + data.ExpiredDate.ToString() + "'," + data.ID; var rst = sqlh.Execute(ExpressinSQL); sqlh.Dispose(); return "Success To Update Task ID = " + rst["ID"]; } catch (Exception ex) { sqlh.Dispose(); return ex.Message; } } public string UpdateDone(MstTask data) { try { var ExpressinSQL = spProcess; ExpressinSQL += "'DONE','" + data.TaskTitle + "','" + data.TaskDescription + "'," + data.Progress; ExpressinSQL += ",'" + data.ExpiredDate.ToString() + "'," + data.ID; var rst = sqlh.Execute(ExpressinSQL); sqlh.Dispose(); return "Success To Update Task ID = " + rst["ID"]; } catch (Exception ex) { sqlh.Dispose(); return ex.Message; } } } }
c4a9fda91d94ae431287fd23d267cc1da307abd2
C#
veilandwp/DOAJ
/AM/AMsolution/WinformAM/Tool/Tools.cs
2.953125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.IO; namespace WinformAM.Tool { class Tools { /*************************************************************************/ /*描 述:从给定的一串字符中提取出位于开始标识符和结束标识符之间的所有字符 *输入参数:[string str:待处理的字符串] * [string startFlag:信息起始标识串] * [char endFlag:信息结束标识字符] *返 回 值:【string】 *开发日期:2012-11-20 */ public static string StringExtractor(string str, string startFlag, char endFlag) { try { if (str == null) return null; StringBuilder sb = new StringBuilder(); int startPos = str.IndexOf(startFlag); if (startPos == -1) return null; startPos += startFlag.Length; while (startPos < str.Length && str[startPos] != endFlag) { sb.Append(str[startPos]); ++startPos; } return sb.ToString(); } catch (Exception ex) { ex.ToString(); return null; } } public static string StringExtractor(string str, string startFlag, char endFlag, int startIndex) { try { if (str == null) return null; StringBuilder sb = new StringBuilder(); int startPos = str.IndexOf(startFlag, startIndex); if (startPos == -1) return null; startPos += startFlag.Length; while (startPos < str.Length && str[startPos] != endFlag) { sb.Append(str[startPos]); ++startPos; } return sb.ToString(); } catch (Exception ex) { ex.ToString(); return null; } } /// <summary> /// 从str中获得从startIndex开始的startFlag和endFlag之前的字符串 /// </summary> /// <param name="str"></param> /// <param name="startFlag">开始标识</param> /// <param name="endFlag">接受标识</param> /// <param name="startIndex">开始偏移量</param> /// <returns></returns> public static string StringExtractor(string str, string startFlag, string endFlag, int startIndex) { try { if (str == null) return null; StringBuilder sb = new StringBuilder(); int startPos = str.IndexOf(startFlag, startIndex); if (startPos == -1) return null; startPos += startFlag.Length; while (startPos + endFlag.Length < str.Length) { int cnt = 0; for (int i = 0; i < endFlag.Length; i++) { if (str[startPos + i] == endFlag[i]) ++cnt; } if (cnt == endFlag.Length) break; sb.Append(str[startPos]); ++startPos; } return sb.ToString(); } catch (Exception ex) { ex.ToString(); return null; } } public static string StringBackExtractor(string str, string endFlag, string startFlag, int endIndex) { try { if (str == null || endIndex == -1) return null; StringBuilder sb = new StringBuilder(); int endPos = str.IndexOf(endFlag, endIndex); if (endPos == -1) return null; while (endPos - startFlag.Length >= 0) { int cnt = 0; int j = endPos - startFlag.Length; for (int i = 0; i < startFlag.Length; i++) { if (str[j + i] == startFlag[i]) ++cnt; else break; } if (cnt == startFlag.Length) { return str.Substring(endPos, endIndex - endPos); } else --endPos; } return null; } catch (Exception ex) { ex.ToString(); return null; } } /*************************************************************************/ /*描 述:从给定的一串字符中提取出位于开始标识符和结束标识符之间的所有字符 *输入参数:[string str:待处理的字符串] * [string startFlag:信息起始标识串] * [char endFlag:信息结束标识字符] *返 回 值:【string】 *开发日期:2012-11-20 */ public static string PageDownloader(string url) { try { string result = ""; string err = ""; HttpClient httpClient = new HttpClient(); result = httpClient.GetSrc(url, "UTF-8", out err); return result; } catch (Exception ex) { ex.ToString(); return null; } } public static string HttpPageDownloadToFile(string url, string filePath) { try { HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest; req.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2)"; WebResponse res = req.GetResponse(); System.IO.Stream stream = res.GetResponseStream(); byte[] buffer = new byte[32 * 1024]; int bytesProcessed = 0; System.IO.FileStream fs = System.IO.File.Create(filePath); int bytesRead; do { bytesRead = stream.Read(buffer, 0, buffer.Length); fs.Write(buffer, 0, bytesRead); bytesProcessed += bytesRead; } while (bytesRead > 0); fs.Flush(); fs.Close(); res.Close(); } catch (Exception ex) { return ex.ToString(); } return "success"; } /*************************************************************************/ /*描 述:将指定内容写到指定文件中 *输入参数:[string filePath:文件路径] * [string fileText:待写的文件内容] *返 回 值:【bool:写文件成功返回True,反之则返回false】 *开发日期:2012-11-20 */ public static bool FileWirter(string filePath, string fileText) { try { if (File.Exists(filePath) == false || File.ReadAllText(filePath).Length == 0) { FileStream fs = new FileStream(filePath, FileMode.Create); StreamWriter sw = new StreamWriter(fs); sw.Write(fileText); sw.Close(); return true; } return false; } catch (Exception ex) { ex.ToString(); return false; } } /*************************************************************************/ /*描 述:判断文件是否存在并不为空文件 *输入参数:[string filePath:文件路径] *返 回 值:【bool:文件存在返回True,反之则返回false】 *开发日期:2012-11-20 */ public static bool FileExsits(string filePath) { try { if (File.Exists(filePath) == true && File.ReadAllText(filePath).Length > 0) return true; return false; } catch (Exception ex) { ex.ToString(); return false; } } /*************************************************************************/ /*描 述:去除字符串str中非法的字符,只保留英文字母、数字、空格、下划线 *输入参数:[string str:待处理字符] *返 回 值:【string】 *开发日期:2012-11-20 */ public static string RemoveInvalidChar(string str) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < str.Length; i++) { if ((str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z') || (str[i] >= '0' && str[i] <= '9') || str[i] == ' ' || str[i] == '_') { sb.Append(str[i]); } } return sb.ToString(); } /*************************************************************************/ /*描 述:阻止线程,时长milliseconds *输入参数:[int milliseconds] *返 回 值: *开发日期:2012-11-20 */ public static void Sleep(int milliseconds) { if (milliseconds < 0) milliseconds = 0; System.Threading.Thread.Sleep(milliseconds); } /*************************************************************************/ /*描 述:删去括号中的字符 *输入参数:[string str]待处理字符串 * [char leftParent]左括号 * [char rightParent]右括号 *返 回 值:string *开发日期:2012-11-20 */ public static string DeleteStringInParent(string str, char leftParent, char rightParent) { try { StringBuilder sb = new StringBuilder(); string text = str; int leftPos = text.IndexOf(leftParent); int rightPos = 0; while (leftPos != -1) { rightPos = text.IndexOf(rightParent, leftPos); if (rightPos == -1) break; sb.Remove(0, sb.Length); sb.Append(text.Substring(0, leftPos)); sb.Append(text.Substring(rightPos + 1, text.Length - rightPos - 1)); text = sb.ToString(); leftPos = text.IndexOf(leftParent); } return text; } catch (Exception ex) { ex.ToString(); return str; } } public static string ReadFile(string filePath) { try { FileStream fs = new FileStream(filePath, FileMode.Open); StreamReader sr = new StreamReader(fs); string text = sr.ReadToEnd(); sr.Close(); return text; } catch (Exception ex) { ex.ToString(); return null; } } public static bool PDFDownload(string url,string pdfFilePath,out string message) { bool result = false; message = ""; try { WebClient pdfClient = new WebClient(); string localPath = pdfFilePath; pdfClient.DownloadFile(url, localPath); result=true; } catch (Exception ex) { message = ex.Message; result = false; } return result; } public static string PDFToText(string pdfPath) { using (FileStream fs = new FileStream(pdfPath, FileMode.Open)) { StreamReader sr = new StreamReader(fs, System.Text.Encoding.GetEncoding("UTF-8")); string text = sr.ReadToEnd(); sr.Close(); return text; } } /// <summary> /// 从指定的字符串中获得用空格隔开的两个字符串 /// </summary> /// <param name="str"></param> /// <returns></returns> public static IList<string> GetISSNAndEISSN(string str) { IList<string> strList = new List<string>(); int j = 0; for(int i = 0; i < 2; i++) { StringBuilder sb = new StringBuilder(); while (j < str.Length && !IsLegalChar(str[j])) j++; while (j < str.Length && IsLegalChar(str[j])) { sb.Append(str[j]); j++; } if (sb.Length > 0) strList.Add(sb.ToString()); } return strList; } public static bool IsLegalChar(char s) { if (s == ' ' || s == '\n' || s == '\r') return false; return true; } public static string DeleteBeginAndEndIllegalChar(string str) { int i = 0; while (i < str.Length && !IsLegalChar(str[i])) i++; int j = str.Length - 1; while (j >= 0 && !IsLegalChar(str[j])) j--; if (j >= i) { return str.Substring(i, j - i + 1); } else return null; } public static string GetFolderName(string url) { int i; for(i = 0; i < url.Length; i++) { if(url[i] == '?') break; } return url.Substring(i+1); } } }
7b6848637a77a067e5f44397d0ad89078ddc0612
C#
rog1039/UniqueDb-ConnectionProvider
/src/UniqueDb.ConnectionProvider.Tests/UnitTestBaseWithConsoleRedirection.cs
2.578125
3
using System.Text; using Xunit.Abstractions; namespace UniqueDb.ConnectionProvider.Tests; public class TestOutputHelperToTextWriterAdapter : TextWriter { ITestOutputHelper _output; public TestOutputHelperToTextWriterAdapter(ITestOutputHelper output) { _output = output; } public override Encoding Encoding { get { return Encoding.ASCII; } } public override void WriteLine(string message) { _output.WriteLine(message); } public override void WriteLine(string format, params object[] args) { _output.WriteLine(format, args); } public override void Write(char value) { } public override void Write(string message) { _output.WriteLine(message); } } public class UnitTestBaseWithConsoleRedirection { protected ITestOutputHelper _outputHelper; public UnitTestBaseWithConsoleRedirection(ITestOutputHelper outputHelperHelper) { Console.SetOut(new TestOutputHelperToTextWriterAdapter(outputHelperHelper)); _outputHelper = outputHelperHelper; } }
31f62afef5be3dadb467643068b97aedcbff4400
C#
Bmalone100/Shop-UI
/Shop.cs
3.15625
3
using System; using System.Collections.Generic; namespace ShopUI{ public class Shop{ private Guid _UniqueID; public Guid UniqueID{ get{ return _UniqueID; } set{ _UniqueID = value; } } private string _Name; public string Name{ get{ return _Name; } set{ _Name = value; } } //List of shops List<Shop> shops = new List<Shop>(); public List<Shop> Shops{ get {return shops;} } //List of products List<Product> products = new List<Product>(); public List<Product> Products{ get {return products;} } public Shop(string name){ Guid uniqueID = Guid.NewGuid(); _UniqueID = uniqueID; Name = name; } public override string ToString() { return "Shop: " + Name; } public void addShop(Shop shop){ shops.Add(shop); } public void editShop(Shop shop, string name, string edit){ foreach(Shop element in shops) { if(element.Name == name){ shop.Name = edit; } } } public void deleteShop(Shop shop, string name){ if(shop.Name == name){ shops.Remove(shop); } } public void addProduct(Product product){ products.Add(product); } public void editProduct(Product product, string name, string edit){ foreach(Product element in products) { if(element.Name == name){ product.Name = edit; } } } public void deleteProduct(Product product, string name){ if(product.Name == name){ products.Remove(product); } } } }
f12be312b5f43348ea8cdbf8ffdfff8a9a18cdf7
C#
A-Dln/project2mvc
/PROJECT2MVC/Controllers/ProductenController.cs
2.515625
3
using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Web; using System.Web.Mvc; using PROJECT2MVC.Models; namespace PROJECT2MVC.Controllers { [Authorize] public class ProductenController : Controller { private CRMEntities db = new CRMEntities(); // // GET: /Producten/ public ActionResult Index() { return View(db.Producten.ToList()); } // // GET: /Producten/Details/5 public ActionResult Details(int id = 0) { Product product = db.Producten.Find(id); if (product == null) { return HttpNotFound(); } return View(product); } // // GET: /Producten/Create public ActionResult Create() { return View(); } // // POST: /Producten/Create [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create(Product product) { //laatste productId opvragen en verhogen met 1 om de nieuwe productId te creëren //- foutmelding "Violation of PK constraint" vermijden //- EF voegt anders steeds product met productId 0 toe product.ProductId = db.Producten.Max(p => p.ProductId) + 1; if (ModelState.IsValid) { db.Producten.Add(product); db.SaveChanges(); return RedirectToAction("Index"); } return View(product); } // // GET: /Producten/Edit/5 public ActionResult Edit(int id = 0) { Product product = db.Producten.Find(id); if (product == null) { return HttpNotFound(); } return View(product); } // // POST: /Producten/Edit/5 [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit(Product product) { if (ModelState.IsValid) { db.Entry(product).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } return View(product); } // // GET: /Producten/Delete/5 public ActionResult Delete(int id = 0) { Product product = db.Producten.Find(id); if (product == null) { return HttpNotFound(); } return View(product); } // // POST: /Producten/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public ActionResult DeleteConfirmed(int id) { Product product = db.Producten.Find(id); db.Producten.Remove(product); db.SaveChanges(); return RedirectToAction("Index"); } protected override void Dispose(bool disposing) { db.Dispose(); base.Dispose(disposing); } } }
198a0beed416cbfaf2bc02f7c52d0ab3545c2be8
C#
toraleap/farmtick
/FarmTick/Friends.cs
2.75
3
using System; using System.Collections.Generic; using System.IO; using System.Runtime.Serialization.Formatters.Binary; using System.Text; using System.Text.RegularExpressions; using FarmTick.Properties; namespace FarmTick { /// <summary> /// 解析、维护好友列表数据类 /// </summary> public static class Friends { public static Dictionary<int, string> FriendMapXiaoyou = new Dictionary<int, string>(); public static Dictionary<int, string> FriendMapQzone = new Dictionary<int, string>(); public static int MasterId; static Regex regexsource = new Regex(@"(?:http://)?(?:happyfarm|nc|mc)\.(?<source>xiaoyou|qzone)\.qq\.com/"); static Regex regexfriend = new Regex(@"""(?:userId|uId)"":(?<userid>\d+),.*?""userName"":""(?<username>.*?)"""); /// <summary> /// 解析含有自己昵称信息的封包 /// </summary> /// <param name="request">本地请求字符串</param> /// <param name="response">服务器返回的响应json字符串</param> public static void ParseMaster(string request, string response) { Match ms = regexsource.Match(request); MatchCollection mc = regexfriend.Matches(response); foreach (Match m in mc) { MasterId = int.Parse(m.Groups["userid"].Value); } FarmTickManager.NotifyFarmsChanged(); } /// <summary> /// 解析含有好友昵称信息的封包 /// </summary> /// <param name="request">本地请求字符串</param> /// <param name="response">服务器返回的响应json字符串</param> public static void ParseFriend(string request, string response) { Match ms = regexsource.Match(request); MatchCollection mc = regexfriend.Matches(response); foreach (Match m in mc) { int uid = int.Parse(m.Groups["userid"].Value); string username = UniescapeToString(m.Groups["username"].Value); UpdateFriend(ms.Groups["source"].Value, uid, username); } FarmTickManager.NotifyFarmsChanged(); } /// <summary> /// 添加或更新一条昵称记录 /// </summary> /// <param name="source">昵称类型字符串(xiaoyou或qzone)</param> /// <param name="uid">欲添加或更新的用户ID</param> /// <param name="username">新的昵称字符串</param> private static void UpdateFriend(string source, int uid, string username) { if (username == String.Empty) username = " "; if (source.ToLower() == "xiaoyou") { if (FriendMapXiaoyou.ContainsKey(uid)) FriendMapXiaoyou[uid] = username; else FriendMapXiaoyou.Add(uid, username); } else if (source.ToLower() == "qzone") { if (FriendMapQzone.ContainsKey(uid)) FriendMapQzone[uid] = username; else FriendMapQzone.Add(uid, username); } } /// <summary> /// 载入已存储的好友昵称对照表 /// </summary> public static void Load() { if (File.Exists("./friends.dat")) { BinaryFormatter bf = new BinaryFormatter(); FileStream fs = new FileStream("./friends.dat", FileMode.Open); FriendMapXiaoyou = bf.Deserialize(fs) as Dictionary<int, string>; FriendMapQzone = bf.Deserialize(fs) as Dictionary<int, string>; MasterId = (int)bf.Deserialize(fs); fs.Close(); } } /// <summary> /// 保存当前好友昵称对照表到磁盘 /// </summary> public static void Save() { BinaryFormatter bf = new BinaryFormatter(); FileStream fs = new FileStream("./friends.dat", FileMode.Create); bf.Serialize(fs, FriendMapXiaoyou); bf.Serialize(fs, FriendMapQzone); bf.Serialize(fs, MasterId); fs.Close(); } /// <summary> /// 获取自己或好友的显示昵称 /// </summary> /// <param name="uid">欲获取的用户ID</param> /// <returns>根据系统设置返回对应表达方式的昵称(若无数据返回“未知用户”及其ID号)</returns> public static string GetName(int uid) { if (Settings.Default.NameMode == (int)fViewUI.NameModes.Both) { if (FriendMapXiaoyou.ContainsKey(uid) && FriendMapQzone.ContainsKey(uid)) return (uid == MasterId ? "★" : "") + FriendMapXiaoyou[uid] + " | " + FriendMapQzone[uid]; else if (FriendMapXiaoyou.ContainsKey(uid)) return (uid == MasterId ? "★" : "") + FriendMapXiaoyou[uid]; else if (FriendMapQzone.ContainsKey(uid)) return (uid == MasterId ? "★" : "") + FriendMapQzone[uid]; else return (uid == MasterId ? "★" : "") + "未知用户[" + uid.ToString() + "]"; } else if (Settings.Default.NameMode == (int)fViewUI.NameModes.Xiaoyou) { if (FriendMapXiaoyou.ContainsKey(uid)) return (uid == MasterId ? "★" : "") + FriendMapXiaoyou[uid]; else if (FriendMapQzone.ContainsKey(uid)) return (uid == MasterId ? "★" : "") + FriendMapQzone[uid]; else return (uid == MasterId ? "★" : "") + "未知用户[" + uid.ToString() + "]"; } else { if (FriendMapQzone.ContainsKey(uid)) return (uid == MasterId ? "★" : "") + FriendMapQzone[uid]; else if (FriendMapXiaoyou.ContainsKey(uid)) return (uid == MasterId ? "★" : "") + FriendMapXiaoyou[uid]; else return (uid == MasterId ? "★" : "") + "未知用户[" + uid.ToString() + "]"; } } /// <summary> /// 将UTF8编码的字符串转换为系统默认编码的字符串 /// </summary> /// <param name="str">源字符串</param> /// <returns>转换后的字符串</returns> public static string UTF8ToString(string str) { return Encoding.Default.GetString(Encoding.Convert(Encoding.UTF8, Encoding.Default, Encoding.Default.GetBytes(str))); } /// <summary> /// 将字符串中表示为Unicode转义(类似\uA0E3形式)的字符还原为对应的字符 /// </summary> /// <param name="str">源字符串</param> /// <returns>还原后的字符串</returns> public static string UniescapeToString(string str) { int i = 0; while ((i = str.IndexOf(@"\u", 0, StringComparison.OrdinalIgnoreCase)) >= 0) { str = str.Replace(str.Substring(i, 6), Convert.ToChar(Convert.ToInt32(str.Substring(i + 2, 4), 16)).ToString()); } return str; } } }
983c7656a66ea84c5a465859053d0c1a76830ec6
C#
eriksena16/MonitorPrint
/MonitorPrint/Form1.cs
2.796875
3
using System; using System.Windows.Forms; using System.Printing; using System.IO; using System.Xml; namespace MonitorPrint { public partial class Form1 : Form { private const string ARQUIVO = @"C:\Users\erik_\Documents\Disco E\log"; int ANTERIOR; public Form1() { InitializeComponent(); } private void Button1_Click(object sender, EventArgs e) { if (button1.Text == "INICIAR") { timer1.Interval = 500; timer1.Start(); button1.Text = "PARAR"; } else { timer1.Stop(); button1.Text = "INICIAR"; } } private void Timer1_Tick(object sender, EventArgs e) { PrintServer SERVIDOR = new PrintServer(); PrintQueueCollection IMPRESSORAS = SERVIDOR.GetPrintQueues(); foreach(PrintQueue IMPRESSORA in IMPRESSORAS) { int PAGINAS = 0; int IDENTIFICADOR = 0; string DOCUMENTO = ""; try { if(IMPRESSORA.NumberOfJobs > 0) { IMPRESSORA.Refresh(); PrintJobInfoCollection IMPRESSOES = IMPRESSORA.GetPrintJobInfoCollection(); foreach (var IMPRESSAO in IMPRESSOES) { PAGINAS = IMPRESSAO.NumberOfPages; IDENTIFICADOR = IMPRESSAO.JobIdentifier; DOCUMENTO = IMPRESSAO.Name; } } } catch(Exception) { } if((PAGINAS > 0) && (IDENTIFICADOR != ANTERIOR)) { ListViewItem LINHA = new ListViewItem(DateTime.Now.ToString()); LINHA.SubItems.Add(PAGINAS.ToString()); LINHA.SubItems.Add(IMPRESSORA.Name); LINHA.SubItems.Add(Environment.UserName); LINHA.SubItems.Add(Environment.MachineName); listView1.Items.Add(LINHA); ANTERIOR = IDENTIFICADOR; // Cria o nome do arquivo com ano, mês, dia, hora minuto e segundo string nomeArquivo = ARQUIVO + DateTime.Now.ToString("ddMMyyyyHHmmss") + ".xml"; // Cria um novo arquivo e devolve um StreamWriter para ele StreamWriter writer = new StreamWriter(nomeArquivo); // Agora é só sair escrevendo writer.WriteLine(DateTime.Now.ToString()); writer.WriteLine(IMPRESSORA.Name); writer.WriteLine(PAGINAS); writer.WriteLine(Environment.UserName); writer.WriteLine(Environment.MachineName); writer.WriteLine(DOCUMENTO); writer.WriteLine(IDENTIFICADOR); // Não esqueça de fechar o arquivo ao terminar writer.Close(); } } } private void ListView1_SelectedIndexChanged(object sender, EventArgs e) { } private void Button1_Paint(object sender, PaintEventArgs e) { } } }
2db7f6c64c14aa00f020b825a7da938bb59b3be5
C#
vlucaciu/FeaaAutomationCourse
/PageObjects/LoginPage.cs
2.5625
3
using OpenQA.Selenium; namespace UnitTestProject1.PageObjects { public class LoginPage { private IWebDriver driver; public LoginPage(IWebDriver browser) { driver = browser; } //TODO: move it in a generic class private IWebElement BtnSignIn() { return driver.FindElement(By.Id("sign-in")); } private IWebElement TxtUsername() { return driver.FindElement(By.Id("session_email")); } private IWebElement TxtPassword() { return driver.FindElement(By.Id("session_password")); } private IWebElement BtnLogin() { return driver.FindElement(By.Name("commit")); } public void NavigateToLoginPage() { BtnSignIn().Click(); } public void LoginApplication(string username, string password) { TxtUsername().SendKeys(username); TxtPassword().SendKeys(password); BtnLogin().Click(); } } }
1bed74855583c55f9e4626cfc4bbf0173c9d8c9e
C#
amironov73/ManagedIrbis
/Source/Classic/Libs/AM.Core/AM/FuncUtility.cs
2.515625
3
// This is an open source non-commercial project. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com /* FuncUtility.cs -- * Ars Magna project, http://arsmagna.ru * ------------------------------------------------------- * Status: poor */ #region Using directives using System; using AM.Logging; using CodeJam; using JetBrains.Annotations; using MoonSharp.Interpreter; #endregion namespace AM { /// <summary> /// /// </summary> [PublicAPI] [MoonSharpUserData] public static class FuncUtility { #region Public methods /// <summary> /// Memoizes the specified function. /// </summary> public static Func<TArg, TRes> Memoize<TArg, TRes> ( [NotNull] this Func<TArg, TRes> func ) { #if WINMOBILE || POCKETPC || SILVERLIGHT throw new NotImplementedException(); #else var dictionary = new System.Collections.Concurrent.ConcurrentDictionary<TArg, TRes>(); return arg => dictionary.GetOrAdd(arg, func); #endif } /// <summary> /// Borrowed from Stephen Toub book. /// </summary> public static T RetryOnFault<T> ( Func<T> function, int maxTries ) { Code.NotNull(function, "function"); Code.Positive(maxTries, "maxTries"); for (int i = 0; i < maxTries; i++) { try { return function(); } catch (Exception exception) { Log.TraceException ( "FuncUtility::RetryOnFault", exception ); if (i == maxTries - 1) { Log.Error ( "FuncUtility::RetryOnFault: " + "giving up" ); throw; } } } return default(T); } #endregion } }
7afbdcdb88b5f53076df6ef09b3dab83b3394a08
C#
wfowler1/Unity3D-BSP-Importer
/Runtime/External/LibBSP/LibBSP/Source/Structs/Common/Lumps/Entities.cs
3.046875
3
using System; using System.IO; using System.Collections.Generic; using System.Text; namespace LibBSP { /// <summary> /// Class representing a group of <see cref="Entity"/> objects. Contains helpful methods to handle Entities in the <c>List</c>. /// </summary> [Serializable] public class Entities : Lump<Entity> { /// <summary> /// Gets the length of this lump in bytes. /// </summary> public override int Length { get { int length = 1; foreach (Entity ent in this) { length += ent.ToString().Length; } return length; } } /// <summary> /// Initializes a new empty <see cref="Entities"/> object. /// </summary> public Entities() : base(null, default(LumpInfo)) { } /// <summary> /// Initializes a new instance of an <see cref="Entities"/> object copying a passed <c>IEnumerable</c> of <see cref="Entity"/> objects. /// </summary> /// <param name="entities">Collection of <see cref="Entity"/> objects to copy.</param> /// <param name="bsp">The <see cref="BSP"/> this lump came from.</param> /// <param name="lumpInfo">The <see cref="LumpInfo"/> associated with this lump.</param> public Entities(IEnumerable<Entity> entities, BSP bsp = null, LumpInfo lumpInfo = default(LumpInfo)) : base(entities, bsp, lumpInfo) { } /// <summary> /// Initializes a new instance of an <see cref="Entities"/> object with a specified initial capacity. /// </summary> /// <param name="initialCapacity">Initial capacity of the <c>List</c> of <see cref="Entity"/> objects.</param> /// <param name="bsp">The <see cref="BSP"/> this lump came from.</param> /// <param name="lumpInfo">The <see cref="LumpInfo"/> associated with this lump.</param> public Entities(int initialCapacity, BSP bsp = null, LumpInfo lumpInfo = default(LumpInfo)) : base(initialCapacity, bsp, lumpInfo) { } /// <summary> /// Initializes a new <see cref="Entities"/> object. /// </summary> /// <param name="bsp">The <see cref="BSP"/> this lump came from.</param> /// <param name="lumpInfo">The <see cref="LumpInfo"/> associated with this lump.</param> public Entities(BSP bsp = null, LumpInfo lumpInfo = default(LumpInfo)) : base(bsp, lumpInfo) { } /// <summary> /// Initializes a new <see cref="Entities"/> object, parsing all the bytes in the passed <paramref name="file"/>. /// </summary> /// <remarks> /// This will not populate Bsp or LumpInfo since a file is being read directly. This should not be used to read a /// lump file, they should be handled through <see cref="BSPReader"/>. Use this to read raw MAP formats instead. /// </remarks> /// <param name="file">The file to read.</param> public Entities(FileInfo file) : this(File.ReadAllBytes(file.FullName)) { } /// <summary> /// Initializes a new <see cref="Entities"/> object, and parses the passed <c>byte</c> array as a <c>string</c>. /// </summary> /// <param name="data"><c>Byte</c>s read from a file.</param> /// <param name="bsp">The <see cref="BSP"/> this lump came from.</param> /// <param name="lumpInfo">The <see cref="LumpInfo"/> associated with this lump.</param> public Entities(byte[] data, BSP bsp = null, LumpInfo lumpInfo = default(LumpInfo)) : base(bsp, lumpInfo) { // Keep track of whether or not we're currently in a set of quotation marks. // I came across a map where the map maker used { and } within a value. bool inQuotes = false; int braceCount = 0; // The current character being read in the file. This is necessary because // we need to know exactly when the { and } characters occur and capture // all text between them. char currentChar; // This will be the resulting entity, fed into Entity.FromString StringBuilder current = new StringBuilder(); for (int offset = 0; offset < data.Length; ++offset) { currentChar = (char)data[offset]; if (currentChar == '\"') { if (offset == 0) { inQuotes = !inQuotes; } else if ((char)data[offset - 1] != '\\') { // Allow for escape-sequenced quotes to not affect the state machine, but only if the quote isn't at the end of a line. // Some Source engine entities use escape sequence quotes in values, but MoHAA has a map with an obvious erroneous backslash before a quote at the end of a line. if (inQuotes && (offset + 1 >= data.Length || (char)data[offset + 1] == '\n' || (char)data[offset + 1] == '\r')) { inQuotes = false; } } else { inQuotes = !inQuotes; } } if (!inQuotes) { if (currentChar == '{') { // Occasionally, texture paths have been known to contain { or }. Since these aren't always contained // in quotes, we must be a little more precise about how we want to select our delimiters. // As a general rule, though, making sure we're not in quotes is still very effective at error prevention. if (offset == 0 || (char)data[offset - 1] == '\n' || (char)data[offset - 1] == '\t' || (char)data[offset - 1] == ' ' || (char)data[offset - 1] == '\r') { ++braceCount; } } } if (braceCount > 0) { current.Append(currentChar); } if (!inQuotes) { if (currentChar == '}') { if (offset == 0 || (char)data[offset - 1] == '\n' || (char)data[offset - 1] == '\t' || (char)data[offset - 1] == ' ' || (char)data[offset - 1] == '\r') { --braceCount; if (braceCount == 0) { Entity entity = new Entity(this); entity.ParseString(current.ToString()); Add(entity); // Reset StringBuilder current.Length = 0; } } } } } if (braceCount != 0) { throw new ArgumentException(string.Format("Brace mismatch when parsing entities! Entity: {0} Brace level: {1}", Count, braceCount)); } } /// <summary> /// Deletes all <see cref="Entity"/> objects with "<paramref name="key"/>" set to "<paramref name="value"/>". /// </summary> /// <param name="key">Attribute to match.</param> /// <param name="value">Desired value of attribute.</param> /// <returns>The number of entities removed from the lump.</returns> public int RemoveAllWithAttribute(string key, string value) { return RemoveAll(entity => { return entity[key].Equals(value, StringComparison.InvariantCultureIgnoreCase); }); } /// <summary> /// Deletes all <see cref="Entity"/> objects with the specified classname. /// </summary> /// <param name="classname">Classname attribute to find.</param> /// <returns>The number of entities removed from the lump.</returns> public int RemoveAllOfType(string classname) { return RemoveAll(entity => { return entity.ClassName.Equals(classname, StringComparison.InvariantCultureIgnoreCase); }); } /// <summary> /// Gets a <c>List</c> of all <see cref="Entity"/> objects with "<paramref name="key"/>" set to "<paramref name="value"/>". /// </summary> /// <param name="key">Name of the attribute to search for.</param> /// <param name="value">Value of the attribute to search for.</param> /// <returns><c>List</c>&lt;<see cref="Entity"/>&gt; that have the specified key/value pair.</returns> public List<Entity> GetAllWithAttribute(string key, string value) { return FindAll(entity => { return entity[key].Equals(value, StringComparison.InvariantCultureIgnoreCase); }); } /// <summary> /// Gets a <c>List</c> of <see cref="Entity"/>s objects with the specified classname. /// </summary> /// <param name="classname">Classname attribute to find.</param> /// <returns><c>List</c>&lt;<see cref="Entity"/>&gt; with the specified classname.</returns> public List<Entity> GetAllOfType(string classname) { return FindAll(entity => { return entity.ClassName.Equals(classname, StringComparison.InvariantCultureIgnoreCase); }); } /// <summary> /// Gets a <c>List</c> of <see cref="Entity"/>s objects with the specified targetname. /// </summary> /// <param name="targetname">Targetname attribute to find.</param> /// <returns><c>List</c>&lt;<see cref="Entity"/>&gt; with the specified targetname.</returns> public List<Entity> GetAllWithName(string targetname) { return FindAll(entity => { return entity.Name.Equals(targetname, StringComparison.InvariantCultureIgnoreCase); }); } /// <summary> /// Gets the first <see cref="Entity"/> with "<paramref name="key"/>" set to "<paramref name="value"/>". /// </summary> /// <param name="key">Name of the attribute to search for.</param> /// <param name="value">Value of the attribute to search for.</param> /// <returns><see cref="Entity"/> with the specified key/value pair, or null if none exists.</returns> public Entity GetWithAttribute(string key, string value) { return Find(entity => { return entity[key].Equals(value, StringComparison.InvariantCultureIgnoreCase); }); } /// <summary> /// Gets the first <see cref="Entity"/> with the specified classname. /// </summary> /// <param name="classname">Classname attribute to find.</param> /// <returns><see cref="Entity"/> object with the specified classname.</returns> public Entity GetOfType(string classname) { return Find(entity => { return entity.ClassName.Equals(classname, StringComparison.InvariantCultureIgnoreCase); }); } /// <summary> /// Gets the first <see cref="Entity"/> with the specified targetname. /// </summary> /// <param name="targetname">Targetname attribute to find.</param> /// <returns><see cref="Entity"/> object with the specified targetname.</returns> public Entity GetWithName(string targetname) { return Find(entity => { return entity.Name.Equals(targetname, StringComparison.InvariantCultureIgnoreCase); }); } /// <summary> /// Gets all the data in this lump as a byte array. /// </summary> /// <param name="lumpOffset">The offset of the beginning of this lump.</param> /// <returns>The data.</returns> public override byte[] GetBytes(int lumpOffset = 0) { if (Count == 0) { return new byte[] { 0 }; } StringBuilder sb = new StringBuilder(); foreach (Entity ent in this) { sb.Append(ent.ToString()); } sb.Append((char)0x00); return Encoding.ASCII.GetBytes(sb.ToString()); } } }
7e0817fd41aa7713f15ab814da52e3149808e75f
C#
yarzakimi/Bars-Test-Task
/TestTaskBars/ConnectPostgres.cs
2.953125
3
using System; using System.Collections.Generic; using System.Data; using Npgsql; namespace TestTaskBars { class ConnectPostgres { private readonly string _serverName; private readonly string _connectionParams; public ConnectPostgres(string serverName, string connectionParams) { this._serverName = serverName; this._connectionParams = connectionParams; } public IList<IList<Object>> GetTable() { List<IList<Object>> table = new List<IList<Object>>(); DataTable test_table = new DataTable(); string sql_request = @"SELECT pg_database.datname AS database_name, pg_database_size(pg_database.datname) AS database_size_bytes FROM pg_database UNION ALL SELECT 'Свободно' AS database_name, sum(pg_database_size(pg_database.datname)) AS database_size_bytes FROM pg_database;"; NpgsqlConnection connection = new NpgsqlConnection(this._connectionParams); NpgsqlCommand execute_command = new NpgsqlCommand(sql_request, connection); try { connection.Open(); Console.WriteLine(DateTime.Now.ToString() + ": Successful connection to server {0}", this._serverName); } catch (Exception ex) { Console.WriteLine(DateTime.Now.ToString() + ": Failed connection to server {0}: {1}", this._serverName, ex.ToString()); } NpgsqlDataReader reader; reader = execute_command.ExecuteReader(); while (reader.Read()) { try { IList<Object> current_row = new List<Object>(); current_row.Add(this._serverName); current_row.Add(reader.GetString(0)); current_row.Add(reader.GetValue(1)); current_row.Add(DateTime.Now.ToString("dd.MM.yyyy")); table.Add(current_row); } catch (Exception ex) { Console.WriteLine(DateTime.Now.ToString() + ": Error in processing sql-request: {0}", ex.ToString()); } } connection.Close(); return table; } } }
03f0d7b9789150a3e21257c500bc1458b770173d
C#
KevinByrd-28/GoldBadge_Challenges
/Challenge6_GreenPlan/RealGreenCar.cs
3.03125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Challenge6_GreenPlan { public enum Color { Green, LimeGreen, DarkGreen, BrightGreen, NeonGreen, ArmyGreen } public class RealGreenCar : GasCar { public decimal PriceDiscount { get; } = -100.00m; public Color Color { get; set; } public RealGreenCar() { } public RealGreenCar(string aName, int aMileage, Color aColor) { Name = aName; GasMileage = aMileage; Color = aColor; } } }
6d88d0c24cac546c7797d9210a7d198c5aa5e6f5
C#
shendongnian/download4
/first_version_download2/170703-50088101-172353091-1.cs
2.734375
3
using Routing.Models; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; namespace Routing.Controllers { public class StudentsController : ApiController { static List<Students> Lststudents = new List<Students>() { new Students { id=1, name="kim" }, new Students { id=2, name="aman" }, new Students { id=3, name="shikha" }, new Students { id=4, name="ria" } }; [HttpGet] public IEnumerable<Students> getlist() { return Lststudents; } [HttpGet] public Students getcurrentstudent(int id) { return Lststudents.FirstOrDefault(e => e.id == id); } [HttpGet] [Route("api/Students/{id}/course")] public IEnumerable<string> getcurrentCourse(int id) { if (id == 1) return new List<string>() { "emgili", "hindi", "pun" }; if (id == 2) return new List<string>() { "math" }; if (id == 3) return new List<string>() { "c#", "webapi" }; else return new List<string>() { }; } [HttpGet] [Route("api/students/{id}/{name}")] public IEnumerable<Students> getlist(int id, string name) { return Lststudents.Where(e => e.id == id && e.name == name).ToList(); } [HttpGet] public IEnumerable<string> getlistcourse(int id, string name) { if (id == 1 && name == "kim") return new List<string>() { "emgili", "hindi", "pun" }; if (id == 2 && name == "aman") return new List<string>() { "math" }; else return new List<string>() { "no data" }; } } }
65e5ed4c63e245cc3b07b1b914141d0e4dc9efa4
C#
gohce/computergame_gce
/Practical 2/Assets/Scripts/GameController.cs
2.609375
3
using System.Collections; using System.Collections.Generic; using UnityEngine; using TMPro; public class GameController : MonoBehaviour { public TextMeshProUGUI victoryText; public TextMeshProUGUI text; public GameObject textDisplay; public int score = 0; public void changeScore(int gemValue) { score += gemValue; text.text = score.ToString(); if (score >= 100) { victoryText.text = "Well Done!"; } } }
c5bb68ae82826167f7efcfdf37d8a7e21aa8cffd
C#
TN8001/SimpleAudioPlayer
/SimpleAudioPlayer/View/MarqueeControl.xaml.cs
2.625
3
using System; using System.ComponentModel; using System.Windows; using System.Windows.Controls; using System.Windows.Media.Animation; namespace SimpleAudioPlayer { public partial class MarqueeControl : UserControl { [Category("Common Properties")] [Description("この要素のテキスト内容を取得または設定します。")] public string Text { get => (string)GetValue(TextProperty); set => SetValue(TextProperty, value); } public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(MarqueeControl), new PropertyMetadata(null)); public MarqueeControl() { InitializeComponent(); Loaded += (s, e) => RestAnimation(); marquee.SizeChanged += (s, e) => RestAnimation(); } private void RestAnimation() { marquee.BeginAnimation(Canvas.LeftProperty, null); tb2.Visibility = Visibility.Hidden; if(userControl.ActualWidth > tb.ActualWidth) return; tb2.Visibility = Visibility.Visible; var doubleAnimation = new DoubleAnimation() { Duration = new Duration(TimeSpan.FromSeconds(tb.ActualWidth / 50)), From = 0, To = -marquee.ActualWidth / 2 - 25, RepeatBehavior = RepeatBehavior.Forever, }; marquee.BeginAnimation(Canvas.LeftProperty, doubleAnimation); } } }
0757acec61db7edcfb5f9724464b440c6cc2613f
C#
kiyo7447/SETools
/Console/Program.cs
3.015625
3
using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Reflection; using System.Diagnostics; using System.Collections; using System.Threading; namespace SConsole { class Program { static int Main(string[] args) { if (args.Length < 1) { Console.WriteLine("p[^‚܂B}jAmFĂB"); return 1; } if (args[0].ToUpper() == "SHOW") { ShowCommand show = new ShowCommand(Console.Out); if (args.Length == 1) { return show.ShowAll(); } else { return show.Show(args[1]); } } if (args[0].ToUpper() == "CLEAR") { Console.Clear(); return 0; } /* *͂߂܂BR̓vZXԂ̒l̕ێ‹ϐł͂łȂ߂łB if (args[0].ToUpper() == "SW") { if (args[1].ToUpper() == "START") { Environment.SetEnvironmentVariable("SW", DateTime.Now.ToString(), EnvironmentVariableTarget.User); return 0; } else if (args[1].ToUpper() == "STOP") { string v = Environment.GetEnvironmentVariable("SW", EnvironmentVariableTarget.User); Console.Out.WriteLine(v); return 0; } } */ if (args[0].ToUpper() == "BEEP") { BeepCommand beep = new BeepCommand(); if (args.Length == 1) { Console.Beep(); } else { beep.Beep(args[1]); } return 0; } if (args[0].ToUpper() == "SET") { string[] kv = args[1].Split(new char[]{ '=' }); Type con = typeof(Console); PropertyInfo propertyInfo = con.GetProperty(kv[0]); if (propertyInfo == null) { Console.Out.WriteLine("w肳ꂽL[݂͑܂BKey=" + kv[0]); return 1; } Debug.WriteLine(propertyInfo.Name); object o = null; if (propertyInfo.PropertyType.FullName == "System.Int32") { o = Convert.ToInt32(kv[1]); } else if (propertyInfo.PropertyType.FullName == "System.Boolean") { o = Convert.ToBoolean(kv[1]); } else if (propertyInfo.PropertyType.FullName == "System.ConsoleColor") { ConsoleColor color = ConsoleColor.Red; color = (ConsoleColor)Enum.Parse(color.GetType(), kv[1]); o = color; } else if (propertyInfo.PropertyType.FullName == "System.Text.Encoding") { Encoding encoding = null; try { int codePage; if (int.TryParse(kv[1], out codePage) == true) { encoding = Encoding.GetEncoding(codePage); } else { encoding = Encoding.GetEncoding(kv[1]); } } catch (Exception ex) { throw new SystemException("w肳ĂR[hy[WsłBR[hy[W=" + kv[1], ex); } o = encoding; //Console.OutputEncoding = System.Text.Encoding.UTF8; //Console.OutputEncoding = System.Text.Encoding.Unicode; //Console.InputEncoding = System.Text.Encoding.UTF8; //return 0; } else if (propertyInfo.PropertyType.FullName == "System.String") { o = Convert.ToString(kv[1]); } else { //erorr o = kv[1]; } // propertyInfo.SetValue(null, o, null); //con.InvokeMember(kv[0], BindingFlags.SetField, null, null, new object[]{kv[1]}); return 0; } Console.WriteLine("p[^ԈĂ܂B}jAmFĂB"); return 1; } } }
afc337137d2eb08acf4ab4403b000032ff09cc5b
C#
ChrisMenning/Stego_Crypto
/StegoCryptoUnitTesting/RoundtripTest.cs
2.6875
3
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using StegoCrypto; using System.Drawing; using System.Threading.Tasks; namespace StegoCryptoUnitTesting { [TestClass] public class RoundtripTest { [TestMethod] public void TestRoundtrip() { // ARRANGE // ======= // File FileInformation fi = new FileInformation(); byte[] sourceFile = fi.FileContents; // Encryption and Decryption FormMain mainForm = new FormMain(); // MainForm also holds user preferences in memory. PasswordHandler pwh = new PasswordHandler("password", mainForm); AESencrypter aesEnc = new AESencrypter(fi.GenerateFileInfoHeader(), fi.FileContents, mainForm); AESdecrypter aesDec = new AESdecrypter(mainForm); byte[] encryptedFile; byte[] decryptedFile; // Bitmap Encoder and Decoder BitmapEncoder bmpEncoder = new BitmapEncoder(); BitmapDecoder bmpDecoder = new BitmapDecoder(false); Bitmap encodedBitmap; byte[] bytesFromImage; // Header Parser HeaderParser hp = new HeaderParser(); byte[] parsedDecrypted; // ACT // === Task.Run(async () => { // Encrypt the file. encryptedFile = aesEnc.EncryptBytes(); // Encode the encrypted file into the bitmap. encodedBitmap = await bmpEncoder.EncodedBitmap(encryptedFile, aesEnc.InitializationVector); // Retrieve the encrypted bytes back out of the bitmap. bytesFromImage = await bmpDecoder.BytesFromImage(encodedBitmap); // Decrypt the bytes pulled from the image. decryptedFile = aesDec.DecryptedBytes(bytesFromImage, mainForm.EncryptionKey, aesEnc.InitializationVector); // Parse the header from the decrypted file. parsedDecrypted = hp.fileContentsWithoutHeader(decryptedFile); // ASSERT // ====== for (int i = 0; i < fi.FileContents.Length; i++) { // Assert that the bytes that went in are the same as the bytes that came out. Assert.AreEqual(fi.FileContents[i], parsedDecrypted[i]); } }).GetAwaiter().GetResult(); } } }
f87f486a8ab4d034e73802fed8b9353734801b27
C#
RodrigoUngo/RAUM_00075419_2EP
/SourceCode/Parcial02/VerOrdenes.cs
2.65625
3
using System; using System.Windows.Forms; namespace Parcial02 { public partial class VerOrdenes : UserControl { public VerOrdenes() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { try { var dt = ConnectionDB.ExecuteQuery("SELECT ao.idOrder, ao.createDate, pr.name, au.fullname, ad.address " + "FROM APPORDER ao, ADDRESS ad, PRODUCT pr, APPUSER au " + "WHERE ao.idProduct = pr.idProduct " + "AND ao.idAddress = ad.idAddress " + "AND ad.idUser = au.idUser " + $"AND au.idUser = {textBox1.Text};"); dataGridView1.DataSource = dt; MessageBox.Show("Datos obtenidos exitosamente"); } catch (Exception ex) { MessageBox.Show("Ha ocurrido un error"); } } } }
c7a228588a2710373cd56f9895440b4326a523b0
C#
Plan9-Archive/SixthCircle
/SixthCircle/DataViewer.cs
2.78125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SixthCircle { public unsafe class DataViewer { byte[] _data; public DataViewer (byte[] data) { _data = data; } public Int16 AsInt16 (int offset) { fixed (void* ptr = &_data[offset]) return *(Int16*) ptr; } public Int32 AsInt32 (int offset) { fixed (void* ptr = &_data[offset]) return *(Int32*) ptr; } public Int64 AsInt64 (int offset) { fixed (void* ptr = &_data[offset]) return *(Int64*) ptr; } public Single AsSingle (int offset) { fixed (void* ptr = &_data[offset]) return *(Single*) ptr; } public Double AsDouble (int offset) { fixed (void* ptr = &_data[offset]) return *(Double*) ptr; } } }
f0d449052d3dc0b089737d08d88e9143b1962aff
C#
Kvseshwary/ShopBridge
/ShopBridge/ShopBridge.Models/ItemModel.cs
2.984375
3
using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Text; namespace ShopBridge.Models { public class ItemModel { public int ItemId { get; set; } [Required] [MaxLength(20,ErrorMessage ="You need to keep the name to a max of 20 characters")] [MinLength(3,ErrorMessage ="You need to enter atleast 3 characters for an Item Name")] [DisplayName("Product Name")] public string Name { get; set; } public string Description { get; set; } [Required] [Range(1,500,ErrorMessage ="Price lies outside of 1 to 500 range")] public decimal Price { get; set; } [Required] [Range(1,20,ErrorMessage ="You can add upto 20 quantities")] public int Quantity { get; set; } } }
4bbae15fe5ecae1b9ef391b2dae437ee24b72f94
C#
skytecgames/SkillTestProject
/Assets/Scripts/GameCore/Pathfinding/ZStar/SquareZone.cs
3.265625
3
using UnityEngine; using System.Collections; namespace Pathfinding.ZStar { //Класс для работы с квадратной областью с тайлами (не обязательно связанными) public class SquareZone { public const int size = 8; public int x_min; public int y_min; public int x_max { get { return x_min + size; } } public int y_max { get { return y_min + size; } } private int[,] map; //Создает чистую зону в которую входит тайл с указанными координатами public void Reset(int x, int y) { //определяем границы зоны x_min = (int)(x / size) * size; y_min = (int)(y / size) * size; //пересоздаем карту помеченных элементов if (map == null || map.GetLength(0) != size || map.GetLength(1) != size) { map = new int[size, size]; } //сбрасываем значения в карте помеченных элементов for (int i = 0; i < size; ++i) { for (int j = 0; j < size; ++j) { map[i, j] = 0; } } } public void Mark(int x, int y) { if (isInside(x, y) == false) { Debug.LogErrorFormat("tile [{0},{1}] outsize of square zone [{2},{3},{4},{5}", x, y, x_min, y_min, x_min + size, y_min + size); return; } map[x - x_min, y - y_min] = 1; } //Возвращает true если элемент вне зоны или отмечен public bool isMarkOrOutside(int x, int y) { //Если вне зоны, то возвращаем if (isInside(x, y) == false) return true; return map[x - x_min, y - y_min] == 1; } public bool isInside(int x, int y) { return (x >= x_min) && (x < x_min + size) && (y >= y_min) && (y < y_min + size); } } }
2533d88692146aacc62d4900b31b65cce0987beb
C#
edge33/Materiale-didattico
/C#/CentroResidenziale/CentroResidenziale/CentroResidenziale.cs
2.8125
3
using CentroResidenziale.Models; using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Text; using System.Transactions; namespace CentroResidenziale { public class CentroResidenziale { private List<Studente> StudentiImmatricolati { get; set; } private int NumeroMatricolaCorrente; public CentroResidenziale() { this.NumeroMatricolaCorrente = 0; this.StudentiImmatricolati = new List<Studente>(); } public Studente ImmatricolaStudente(Persona persona) { Studente studente = (Studente) persona; int numeroMatricola = NumeroMatricolaCorrente++; studente.Matricola = numeroMatricola; this.StudentiImmatricolati.Add(studente); Tesserino tesserino = new Tesserino(numeroMatricola); tesserino.FasciaReddito = CalcolaFasciaReddito(studente); studente.Tesserino = tesserino; return studente; } private int CalcolaFasciaReddito(Studente studente) { double reddito = studente.RedditoFamiliare; if (reddito <= 0) { return 0; } else if (reddito <= 10000) { return 1; } else if (reddito <= 20000) { return 2; } else { return 3; } } } }
05ffdf035ab20fa80d4d347e04ac6a41dc47559d
C#
EmilieMacary/ProjetGit
/DecouverteEntityFrameworkCodeFirst/Models/Costumer.cs
2.546875
3
using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace DecouverteEntityFrameworkCodeFirst { public class Customer { public int Id { get; set; } [Required] [MaxLength(30)] public string Name { get; set; } [Required] [MaxLength(30)] public string FirstName { get; set; } [Required] [MaxLength(50)] public string Email { get; set; } [Column(TypeName = "char(10)")] public string PhoneNumber { get; set; } [MaxLength(30)] public string City { get; set; } public DateTime? BirthDay { get; set; } } }
a4b25a2c9f8c9d6f4a7ca481753e60b81e412578
C#
HathWallace/LeetCode
/CSharp/SolutionLib/0101-0200/142. 环形链表 II/Solution.cs
3.1875
3
using System.Collections.Generic; namespace SolutionLib._142._环形链表_II { /** * Definition for singly-linked list. * public class ListNode { * public int val; * public ListNode next; * public ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public ListNode DetectCycle(ListNode head) { var pt = head; while (pt!=null) { if (pt.val == int.MaxValue) return pt; pt.val = int.MaxValue; pt = pt.next; } return null; } } public class _Solution { public ListNode DetectCycle(ListNode head) { var set = new HashSet<ListNode>(); var pt = head; while (pt != null) { if (!set.Add(pt)) return pt; pt = pt.next; } return null; } } }
ba8cee938e6727e20c34d77d48b6384c25f8da8e
C#
hillinworks/tabml
/Source/TabML.Parser/Parsing/Bar/RhythmSegmentParserBase.cs
2.515625
3
using TabML.Core.Logging; using TabML.Parser.AST; namespace TabML.Parser.Parsing.Bar { abstract class RhythmSegmentParserBase<TNode> : ParserBase<TNode> where TNode : RhythmSegmentNodeBase, new() { public bool OptionalBrackets { get; } protected RhythmSegmentParserBase(bool optionalBrackets = false) { this.OptionalBrackets = optionalBrackets; } protected bool TryParseRhythmDefinition(Scanner scanner, ref TNode node) { var anchor = scanner.MakeAnchor(); var hasBrackets = scanner.Expect('['); if (!this.OptionalBrackets && !hasBrackets) { this.Report(LogLevel.Error, scanner.LastReadRange, Messages.Error_RhythmSegmentExpectOpeningBracket); node = null; return false; } scanner.SkipWhitespaces(); if (!RhythmSegmentParser.IsEndOfSegment(scanner)) { VoiceNode voice; if (scanner.Expect(';')) { if (!this.ReadBassVoice(scanner, node)) return false; } else if (new VoiceParser().TryParse(scanner, out voice)) { node.TrebleVoice = voice; scanner.SkipWhitespaces(); if (scanner.Expect(';')) if (!this.ReadBassVoice(scanner, node)) return false; } else { this.Report(LogLevel.Error, scanner.Pointer.AsRange(scanner.Source), Messages.Error_UnrecognizableRhythmSegmentElement); node = null; return false; // todo: should we fail so fast? } } if (hasBrackets) { if (scanner.Expect(']')) return true; if (this.OptionalBrackets) this.Report(LogLevel.Warning, scanner.LastReadRange, Messages.Warning_RhythmSegmentMissingCloseBracket); else { this.Report(LogLevel.Error, scanner.LastReadRange, Messages.Error_RhythmSegmentMissingCloseBracket); node = null; return false; } } if (node.BassVoice == null && node.TrebleVoice == null) { this.Report(LogLevel.Warning, scanner.LastReadRange, Messages.Warning_EmptyRhythmSegment); } node.Range = anchor.Range; return true; } private bool ReadBassVoice(Scanner scanner, TNode node) { VoiceNode voice; if (new VoiceParser().TryParse(scanner, out voice)) { node.BassVoice = voice; scanner.SkipWhitespaces(); if (scanner.Peek() == ';') { this.Report(LogLevel.Error, scanner.Pointer.AsRange(scanner.Source), Messages.Error_UnrecognizableRhythmSegmentElement); return false; } } else { this.Report(LogLevel.Error, scanner.Pointer.AsRange(scanner.Source), Messages.Error_UnrecognizableRhythmSegmentElement); return false; } return true; } } }
054831378a2d72da86128558aa3487c40dcc0f53
C#
andreaskoumoundouros/HydroBot
/Hydrobot/Program.cs
2.6875
3
using System; using System.Reflection; using System.Threading.Tasks; using Discord; using Discord.WebSocket; using Discord.Commands; using Microsoft.Extensions.Configuration; namespace Hydrobot { public class Program { private DiscordSocketClient client; private CommandService commands; static void Main() { new Program().MainAsync().GetAwaiter().GetResult(); } private async Task MainAsync() { client = new DiscordSocketClient(new DiscordSocketConfig { LogLevel = LogSeverity.Debug }); commands = new CommandService(new CommandServiceConfig { CaseSensitiveCommands = true, DefaultRunMode = RunMode.Async, LogLevel = LogSeverity.Debug }); client.MessageReceived += Client_MessageRecieved; await commands.AddModulesAsync(Assembly.GetEntryAssembly(), null); client.Ready += Client_Ready; client.Log += Client_Log; // *Add an environment variable called 'hydrationToken' with the value of the bot token to actually run the bot.* await client.LoginAsync(TokenType.Bot, Environment.GetEnvironmentVariable("hydrationToken", EnvironmentVariableTarget.User)); await client.StartAsync(); await Task.Delay(-1); } private async Task Client_Log(LogMessage message) { Console.WriteLine($"{DateTime.Now} at {message.Source} {message.Message}"); } private async Task Client_Ready() { await client.SetGameAsync("REEEEEEEEEeeeeeeeeeee!"); } private async Task Client_MessageRecieved(SocketMessage messageParam) { var message = messageParam as SocketUserMessage; var context = new SocketCommandContext(client, message); if (context.Message == null || context.Message.Content == "") { return; } if (context.User.IsBot) { return; } int argPos = 0; if (!(message.HasStringPrefix(":)", ref argPos)) || message.HasMentionPrefix(client.CurrentUser, ref argPos)) { return; } RequestOptions options = new RequestOptions(); options.Timeout = 5000; await context.Channel.TriggerTypingAsync(options); var result = await commands.ExecuteAsync(context, argPos, null); if (!result.IsSuccess) { Console.WriteLine($"{DateTime.Now} at commands - something went wrong when executing a command. Text: {context.Message.Content} | Error: {result.ErrorReason}"); } } public System.Collections.Generic.IEnumerable<CommandInfo> GetCommandList() { return commands.Commands; } } }
ffc22eae31901b04f553c55ef7ae440cb51fb62f
C#
mohan-1990/Open-API-Visual-Studio-Solution-Creator
/Open_API_VisualStudio_Solution_Creator/Program.cs
2.953125
3
using System; using System.Collections.Generic; using System.IO; using System.Text; namespace BSG_API_Solution_BoilerPlate_Tool { class Program { public static string pwd = System.IO.Directory.GetCurrentDirectory(); static void Main(string[] args) { Console.WriteLine("Hello and Welcome!"); Console.WriteLine("This tool can create an Open API Visual Studio Solution for you."); Console.WriteLine("Please answer the following few questions."); string apiBaseURL; string apiName; int numberOfControllers; string numberOfControllersTemp; string[] controllerNames; int numberOfModels; string numberOfModelsTemp; string[] modelNames; do { Console.WriteLine("API Name? For example, Service Management"); apiName = Console.ReadLine(); } while (string.IsNullOrEmpty(apiName)); do { Console.WriteLine("Base URL of the API? \nNotes:- \n1) Need to start with api/ \n2) Ends without trailing / \nValid Example:- \napi/services/v1 \nInvalid Example \n/api/cahce/v1/"); apiBaseURL = Console.ReadLine(); } while (!apiBaseURL.StartsWith("api/") || apiBaseURL.EndsWith("/")); do { Console.WriteLine("How many controllers the API needs? For example 2. Minimum 1."); numberOfControllersTemp = Console.ReadLine(); } while (!int.TryParse(numberOfControllersTemp, out numberOfControllers) && numberOfControllers < 1); controllerNames = new string[numberOfControllers]; for (int i = 1; i <= numberOfControllers; ++i) { string msgToPrint; string controllerName; if (i == 1) { msgToPrint = "Name of controller " + i + "? For example Service"; } else { msgToPrint = "Name of controller " + i + "?"; } do { Console.WriteLine(msgToPrint); controllerName = Console.ReadLine(); } while (string.IsNullOrEmpty(controllerName)); controllerNames[i - 1] = controllerName; } do { Console.WriteLine("How many database models the API needs? For example 3. Enter 0 if you want to generate database models later."); numberOfModelsTemp = Console.ReadLine(); } while (!int.TryParse(numberOfModelsTemp, out numberOfModels)); modelNames = new string[numberOfModels]; for (int i = 1; i <= numberOfModels; ++i) { string msgToPrint; string modelName; if (i == 1) { msgToPrint = "Name of database model " + i + "? For example Service"; } else { msgToPrint = "Name of database model " + i + "?"; } do { Console.WriteLine(msgToPrint); modelName = Console.ReadLine(); } while (string.IsNullOrEmpty(modelName)); modelNames[i - 1] = modelName; } // Prepare the required template variables // @SolutionName@ string solutionName = apiName; // @SolutionName_UnderscoreSeperated@ string solutionNameUnderscoreSeperated = solutionName.Replace(" ", "_"); // @SolutionName_WhiteSpaceRemoved@ string solutionNameWhiteSpaceRemoved = solutionName.Replace(" ", ""); // @TCPPort1@ Random random1 = new Random(); int tcpPort1 = random1.Next(51500, 51999); // @TCPPort2@ Random random2 = new Random(); int tcpPort2 = random2.Next(44300, 44399); // Mapping Dictionary<string, object> templateVariableToValueMap = new Dictionary<string, object>(); templateVariableToValueMap.Add("@SolutionName@", solutionName); templateVariableToValueMap.Add("@SolutionName_UnderscoreSeperated@", solutionNameUnderscoreSeperated); templateVariableToValueMap.Add("@SolutionName_WhiteSpaceRemoved@", solutionNameWhiteSpaceRemoved); templateVariableToValueMap.Add("@ProjectName@", solutionName); templateVariableToValueMap.Add("@ProjectName_UnderscoreSeperated@", solutionNameUnderscoreSeperated); templateVariableToValueMap.Add("@ProjectName_WhiteSpaceRemoved@", solutionNameWhiteSpaceRemoved); templateVariableToValueMap.Add("@TCPPort1@", tcpPort1); templateVariableToValueMap.Add("@TCPPort2@", tcpPort2); templateVariableToValueMap["@BaseURL@"] = apiBaseURL; // Recepie // Step 1 Create Base solution Console.WriteLine("Step 1: Creating Visual Studio solution " + solutionName + ".sln"); BaseSolution(templateVariableToValueMap); // Step 2 Create Base project folders and files Console.WriteLine("Step 2: Creating .NET Core Web API project " + solutionName + ".csproj"); BaseProject(templateVariableToValueMap); // Step 3 Create Base project properties folders and files Console.WriteLine("Step 3: Creating " + solutionName + " properties folders and files"); ProjectProperties(templateVariableToValueMap); // Step 4 Create Controllers templateVariableToValueMap.Add("@ControllerNames@", controllerNames); Console.WriteLine("Step 4: Creating controllers"); Controllers(templateVariableToValueMap); if (numberOfModels > 0) // Step 5 Create Models { templateVariableToValueMap.Add("@ModelNames@", modelNames); templateVariableToValueMap.Add("@ModelReference@", "public DbSet<@ModelName@> @ModelName@s { get; set; }"); Console.WriteLine("Step 5: Creating database models"); Models(templateVariableToValueMap); DataBase(templateVariableToValueMap); } // Step 6 Create Filters Filters(templateVariableToValueMap); } static void BaseSolution(Dictionary<string, object> templateVariableToValueMap) { string solutionDirectory = Path.Combine(pwd, templateVariableToValueMap["@SolutionName@"].ToString()); Directory.CreateDirectory(solutionDirectory); string solutionFileTemplate = File.ReadAllText(Path.Combine(pwd, "Templates", "@SolutionName@.sln.template")); solutionFileTemplate = solutionFileTemplate.Replace("@SolutionName@", templateVariableToValueMap["@SolutionName@"].ToString()); solutionFileTemplate = solutionFileTemplate.Replace("@ProjectName@", templateVariableToValueMap["@ProjectName@"].ToString()); solutionFileTemplate = solutionFileTemplate.Replace("@Guid1@", Guid.NewGuid().ToString()); solutionFileTemplate = solutionFileTemplate.Replace("@Guid2@", Guid.NewGuid().ToString()); solutionFileTemplate = solutionFileTemplate.Replace("@Guid3@", Guid.NewGuid().ToString()); StreamWriter solutionFileWriter = new StreamWriter(File.Open(Path.Combine(solutionDirectory, templateVariableToValueMap["@SolutionName@"].ToString() + ".sln"), FileMode.OpenOrCreate)); solutionFileWriter.Write(solutionFileTemplate); #if DEBUG Console.WriteLine("Writing the following content to " + templateVariableToValueMap["@SolutionName@"].ToString() + ".sln"); Console.WriteLine("--------------------------------------------------"); Console.WriteLine(solutionFileTemplate); #endif solutionFileWriter.Flush(); solutionFileWriter.Close(); } static void BaseProject(Dictionary<string, object> templateVariableToValueMap) { string projectDirectory = Path.Combine(pwd, templateVariableToValueMap["@SolutionName@"].ToString(), templateVariableToValueMap["@ProjectName@"].ToString()); Directory.CreateDirectory(projectDirectory); // Create ProjectName.csproj file string projectFileTemplate = File.ReadAllText(Path.Combine(pwd, "Templates", "@SolutionName@.@ProjectName@.csproj.template")); projectFileTemplate = projectFileTemplate.Replace("@ProjectName_UnderscoreSeperated@", templateVariableToValueMap["@ProjectName_UnderscoreSeperated@"].ToString()); StreamWriter projectFileWriter = new StreamWriter(File.Open(Path.Combine(projectDirectory, templateVariableToValueMap["@ProjectName@"].ToString() + ".csproj"), FileMode.OpenOrCreate)); projectFileWriter.Write(projectFileTemplate); #if DEBUG Console.WriteLine("Writing the following content to " + templateVariableToValueMap["@SolutionName@"].ToString() + "/" + templateVariableToValueMap["@ProjectName@"].ToString() + ".csproj"); Console.WriteLine("--------------------------------------------------"); Console.WriteLine(projectFileTemplate); #endif projectFileWriter.Flush(); projectFileWriter.Close(); // Create ProjectName/Program.cs file string programFileTemplate = File.ReadAllText(Path.Combine(pwd, "Templates", "@SolutionName@.Program.cs.template")); programFileTemplate = programFileTemplate.Replace("@ProjectName_UnderscoreSeperated@", templateVariableToValueMap["@ProjectName_UnderscoreSeperated@"].ToString()); StreamWriter programFileWriter = new StreamWriter(File.Open(Path.Combine(projectDirectory, "Program.cs"), FileMode.OpenOrCreate)); programFileWriter.Write(programFileTemplate); #if DEBUG Console.WriteLine("Writing the following content to " + projectDirectory + "/Program.cs"); Console.WriteLine("--------------------------------------------------"); Console.WriteLine(programFileTemplate); #endif programFileWriter.Flush(); programFileWriter.Close(); // Create ProjectName/Startup.cs file string startupFileTemplate = File.ReadAllText(Path.Combine(pwd, "Templates", "@SolutionName@.Startup.cs.template")); startupFileTemplate = startupFileTemplate.Replace("@ProjectName_UnderscoreSeperated@", templateVariableToValueMap["@ProjectName_UnderscoreSeperated@"].ToString()); startupFileTemplate = startupFileTemplate.Replace("@SolutionName_WhiteSpaceRemoved@", templateVariableToValueMap["@SolutionName_WhiteSpaceRemoved@"].ToString()); startupFileTemplate = startupFileTemplate.Replace("@SolutionName@", templateVariableToValueMap["@SolutionName@"].ToString()); StreamWriter startupFileWriter = new StreamWriter(File.Open(Path.Combine(projectDirectory, "Startup.cs"), FileMode.OpenOrCreate)); startupFileWriter.Write(startupFileTemplate); #if DEBUG Console.WriteLine("Writing the following content to " + templateVariableToValueMap["@SolutionName@"].ToString() + "/Startup.cs"); Console.WriteLine("--------------------------------------------------"); Console.WriteLine(startupFileTemplate); #endif startupFileWriter.Flush(); startupFileWriter.Close(); // Create ProjectName/appSettings.json file string appSettingsFileTemplate = File.ReadAllText(Path.Combine(pwd, "Templates", "@SolutionName@.appSettings.json.template")); appSettingsFileTemplate = appSettingsFileTemplate.Replace("@SolutionName_WhiteSpaceRemoved@", templateVariableToValueMap["@SolutionName_WhiteSpaceRemoved@"].ToString()); appSettingsFileTemplate = appSettingsFileTemplate.Replace("@SolutionName@", templateVariableToValueMap["@SolutionName@"].ToString()); appSettingsFileTemplate = appSettingsFileTemplate.Replace("@BaseURL@", templateVariableToValueMap["@BaseURL@"].ToString()); StreamWriter appSettingsFileWriter = new StreamWriter(File.Open(Path.Combine(projectDirectory, "appSettings.json"), FileMode.OpenOrCreate)); appSettingsFileWriter.Write(appSettingsFileTemplate); #if DEBUG Console.WriteLine("Writing the following content to " + projectDirectory + "/appSettings.json"); Console.WriteLine("--------------------------------------------------"); Console.WriteLine(appSettingsFileTemplate); #endif appSettingsFileWriter.Flush(); appSettingsFileWriter.Close(); // Create ProjectName/appSettings.Development.json file string appSettingsDevelopmentFileTemplate = File.ReadAllText(Path.Combine(pwd, "Templates", "@SolutionName@.appSettings.Development.json.template")); StreamWriter appSettingsDevelopmentFileWriter = new StreamWriter(File.Open(Path.Combine(projectDirectory, "appSettings.Development.json"), FileMode.OpenOrCreate)); appSettingsDevelopmentFileWriter.Write(appSettingsDevelopmentFileTemplate); #if DEBUG Console.WriteLine("Writing the following content to " + projectDirectory + "/appSettings.Development.json"); Console.WriteLine("--------------------------------------------------"); Console.WriteLine(appSettingsDevelopmentFileTemplate); #endif appSettingsDevelopmentFileWriter.Flush(); appSettingsDevelopmentFileWriter.Close(); } static void ProjectProperties(Dictionary<string, object> templateVariableToValueMap) { string projectDirectory = Path.Combine(pwd, templateVariableToValueMap["@SolutionName@"].ToString(), templateVariableToValueMap["@ProjectName@"].ToString()); string propertiesDirectory = Path.Combine(projectDirectory, "Properties"); Directory.CreateDirectory(propertiesDirectory); string launchSettingsFileTemplate = File.ReadAllText(Path.Combine(pwd, "Templates", "@SolutionName@.Properties.launchSettings.json.template")); launchSettingsFileTemplate = launchSettingsFileTemplate.Replace("@SolutionName_UnderscoreSeperated@", templateVariableToValueMap["@SolutionName_UnderscoreSeperated@"].ToString()); launchSettingsFileTemplate = launchSettingsFileTemplate.Replace("@BaseURL@", templateVariableToValueMap["@BaseURL@"].ToString()); launchSettingsFileTemplate = launchSettingsFileTemplate.Replace("@TCPPort1@", templateVariableToValueMap["@TCPPort1@"].ToString()); launchSettingsFileTemplate = launchSettingsFileTemplate.Replace("@TCPPort2@", templateVariableToValueMap["@TCPPort2@"].ToString()); StreamWriter launchSettingsFileWriter = new StreamWriter(File.Open(Path.Combine(propertiesDirectory, "launchSettings.json"), FileMode.OpenOrCreate)); launchSettingsFileWriter.Write(launchSettingsFileTemplate); #if DEBUG Console.WriteLine("Writing the following content to " + projectDirectory + "/Properties/launchSettings.json"); Console.WriteLine("--------------------------------------------------"); Console.WriteLine(launchSettingsFileTemplate); #endif launchSettingsFileWriter.Flush(); launchSettingsFileWriter.Close(); } static void Controllers(Dictionary<string, object> templateVariableToValueMap) { string projectDirectory = Path.Combine(pwd, templateVariableToValueMap["@SolutionName@"].ToString(), templateVariableToValueMap["@ProjectName@"].ToString()); string controllersDirectory = Path.Combine(projectDirectory, "Controllers"); Directory.CreateDirectory(controllersDirectory); string[] controllerNames = (string[]) templateVariableToValueMap["@ControllerNames@"]; foreach(string controllerName in controllerNames) { string controllerFileTemplate = File.ReadAllText(Path.Combine(pwd, "Templates", "@SolutionName@.Controllers.@ControllerName@.cs.template")); controllerFileTemplate = controllerFileTemplate.Replace("@ProjectName_UnderscoreSeperated@", templateVariableToValueMap["@ProjectName_UnderscoreSeperated@"].ToString()); controllerFileTemplate = controllerFileTemplate.Replace("@SolutionName_WhiteSpaceRemoved@", templateVariableToValueMap["@SolutionName_WhiteSpaceRemoved@"].ToString()); controllerFileTemplate = controllerFileTemplate.Replace("@BaseURL@", templateVariableToValueMap["@BaseURL@"].ToString()); controllerFileTemplate = controllerFileTemplate.Replace("@ControllerName@", controllerName); controllerFileTemplate = controllerFileTemplate.Replace("@SolutionName_WhiteSpaceRemoved_FirstLetterLowerCase@", ToLowerFirstChar(templateVariableToValueMap["@SolutionName_WhiteSpaceRemoved@"].ToString())); StreamWriter controllerFileWriter = new StreamWriter(File.Open(Path.Combine(controllersDirectory, controllerName + "Controller.cs"), FileMode.OpenOrCreate)); controllerFileWriter.Write(controllerFileTemplate); #if DEBUG Console.WriteLine("Writing the following content to " + projectDirectory + "/Controllers/" + controllerName + "Controller.cs"); Console.WriteLine("--------------------------------------------------"); Console.WriteLine(controllerFileTemplate); #endif controllerFileWriter.Flush(); controllerFileWriter.Close(); } } static void Models(Dictionary<string, object> templateVariableToValueMap) { string projectDirectory = Path.Combine(pwd, templateVariableToValueMap["@SolutionName@"].ToString(), templateVariableToValueMap["@ProjectName@"].ToString()); string modelsDirectory = Path.Combine(projectDirectory, "Models"); Directory.CreateDirectory(modelsDirectory); string[] modelNames = (string[])templateVariableToValueMap["@ModelNames@"]; foreach (string modelName in modelNames) { string modelFileTemplate = File.ReadAllText(Path.Combine(pwd, "Templates", "@SolutionName@.Models.@ModelName@.cs.template")); modelFileTemplate = modelFileTemplate.Replace("@ProjectName_UnderscoreSeperated@", templateVariableToValueMap["@ProjectName_UnderscoreSeperated@"].ToString()); modelFileTemplate = modelFileTemplate.Replace("@ModelName@", modelName); StreamWriter modelFileWriter = new StreamWriter(File.Open(Path.Combine(modelsDirectory, modelName + ".cs"), FileMode.OpenOrCreate)); modelFileWriter.Write(modelFileTemplate); #if DEBUG Console.WriteLine("Writing the following content to " + projectDirectory + "/Models/" + modelName + ".cs"); Console.WriteLine("--------------------------------------------------"); Console.WriteLine(modelFileTemplate); #endif modelFileWriter.Flush(); modelFileWriter.Close(); } } static void DataBase(Dictionary<string, object> templateVariableToValueMap) { string projectDirectory = Path.Combine(pwd, templateVariableToValueMap["@SolutionName@"].ToString(), templateVariableToValueMap["@ProjectName@"].ToString()); string databaseDirectory = Path.Combine(projectDirectory, "Database"); Directory.CreateDirectory(databaseDirectory); string databaseFileTemplate = File.ReadAllText(Path.Combine(pwd, "Templates", "@SolutionName@.Database.@SolutionName_WhiteSpaceRemoved@Context.cs.template")); databaseFileTemplate = databaseFileTemplate.Replace("@ProjectName_UnderscoreSeperated@", templateVariableToValueMap["@ProjectName_UnderscoreSeperated@"].ToString()); databaseFileTemplate = databaseFileTemplate.Replace("@SolutionName_WhiteSpaceRemoved@", templateVariableToValueMap["@SolutionName_WhiteSpaceRemoved@"].ToString()); string[] modelNames = (string[])templateVariableToValueMap["@ModelNames@"]; StringBuilder modelReferences = new StringBuilder(); foreach (string modelName in modelNames) { string modelReference = templateVariableToValueMap["@ModelReference@"].ToString().Replace("@ModelName@", modelName); modelReferences.Append(modelReference + "\n"); } databaseFileTemplate = databaseFileTemplate.Replace("@ModelReferences@", modelReferences.ToString()); StreamWriter databaseFileWriter = new StreamWriter(File.Open(Path.Combine(databaseDirectory, templateVariableToValueMap["@SolutionName_WhiteSpaceRemoved@"].ToString() + "Context.cs"), FileMode.OpenOrCreate)); databaseFileWriter.Write(databaseFileTemplate); #if DEBUG Console.WriteLine("Writing the following content to " + projectDirectory + "/Database/" + templateVariableToValueMap["@SolutionName_WhiteSpaceRemoved@"].ToString() + "Context.cs"); Console.WriteLine("--------------------------------------------------"); Console.WriteLine(databaseFileTemplate); #endif databaseFileWriter.Flush(); databaseFileWriter.Close(); } static void Filters(Dictionary<string, object> templateVariableToValueMap) { string projectDirectory = Path.Combine(pwd, templateVariableToValueMap["@SolutionName@"].ToString(), templateVariableToValueMap["@ProjectName@"].ToString()); string filtersDirectory = Path.Combine(projectDirectory, "Filters"); Directory.CreateDirectory(filtersDirectory); string filterFileTemplate = File.ReadAllText(Path.Combine(pwd, "Templates", "@SolutionName@.Filters.AddAuthHeaderOperationFilter.cs.template")); filterFileTemplate = filterFileTemplate.Replace("@ProjectName_UnderscoreSeperated@", templateVariableToValueMap["@ProjectName_UnderscoreSeperated@"].ToString()); StreamWriter filterFileWriter = new StreamWriter(File.Open(Path.Combine(filtersDirectory, "AddAuthHeaderOperationFilter.cs"), FileMode.OpenOrCreate)); filterFileWriter.Write(filterFileTemplate); #if DEBUG Console.WriteLine("Writing the following content to " + projectDirectory + "/Filters/" + templateVariableToValueMap["@SolutionName_WhiteSpaceRemoved@"].ToString() + "AddAuthHeaderOperationFilter.cs"); Console.WriteLine("--------------------------------------------------"); Console.WriteLine(filterFileTemplate); #endif filterFileWriter.Flush(); filterFileWriter.Close(); } static string ToLowerFirstChar(string input) { if (string.IsNullOrEmpty(input)) return input; return char.ToLower(input[0]) + input.Substring(1); } } }
94eabd663064422dfed5e6f0c089b80f923e359a
C#
grenadin/WinFS
/WindowsFormsApp1/WindowsFormsApp1/Form1.cs
2.65625
3
using System; using System.Windows.Forms; using System.IO; namespace WindowsFormsApp1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { if(saveFileDialog1.ShowDialog()==DialogResult.OK) { using (Stream fs = File.Open(saveFileDialog1.FileName, FileMode.Create)) { byte[] bytes = System.Text.Encoding.UTF8.GetBytes(textBox1.Text); fs.Write(bytes, 0, bytes.Length); } } } } }
7971954d19c7ea8e60bef1f73ea64468e3f13c59
C#
andreltgribeiro/SenaiCarfel
/CheckPoint/Senai.Projeto.Carfel.CheckPoint.MVC/Repositorios/UsuarioRepositorioCSV.cs
2.90625
3
using System.Collections.Generic; using System.IO; using Senai.Projeto.Carfel.CheckPoint.MVC.Interfaces; using Senai.Projeto.Carfel.CheckPoint.MVC.Models; namespace Senai.Projeto.Carfel.CheckPoint.MVC.Repositorios { public class UsuarioRepositorioCSV : IUsuario { public UsuarioModel EmailSenha(string email, string senha) { List<UsuarioModel> usuariosCadastrados = LerCSV(); foreach (UsuarioModel usuario in usuariosCadastrados) { if (usuario.Email == email && usuario.Senha == senha) { return usuario; } } return null; } public List<UsuarioModel> Listar() => LerCSV(); private List<UsuarioModel> LerCSV() { List<UsuarioModel> lsUsuarios = new List<UsuarioModel>(); string[] linhas = File.ReadAllLines("usuarios.csv"); foreach (string linha in linhas) { if(string.IsNullOrEmpty(linha)){ continue; } string[] dadosDaLinha = linha.Split(';'); UsuarioModel usuario = new UsuarioModel ( id: int.Parse(dadosDaLinha[0]), nome: dadosDaLinha[1], email: dadosDaLinha[2], senha: dadosDaLinha[3] ); lsUsuarios.Add(usuario); } return lsUsuarios; } public UsuarioModel Cadastrar(UsuarioModel usuario) { if(File.Exists("usuarios.csv")){ usuario.Id = System.IO.File.ReadAllLines("usuarios.csv").Length+1; }else{ using(StreamWriter sw = new StreamWriter("usuarios.csv",true)){ usuario.Administrador = true; sw.WriteLine($"1;Administrador;admin@carfel.com;admin;1;"); } usuario.Id = 2; } using(StreamWriter sw = new StreamWriter("usuarios.csv",true)){ sw.WriteLine($"{usuario.Id};{usuario.Nome};{usuario.Email};{usuario.Senha};0"); } return usuario; } public UsuarioModel CadastrarAdmin(UsuarioModel usuario) { if(File.Exists("usuarios.csv")){ usuario.Id = System.IO.File.ReadAllLines("usuarios.csv").Length+1; }else{ using(StreamWriter sw = new StreamWriter("usuarios.csv",true)){ usuario.Administrador = true; sw.WriteLine($"1;Administrador;admin@carfel.com;admin;1;"); } usuario.Id = 2; } using(StreamWriter sw = new StreamWriter("usuarios.csv",true)){ if(usuario.Administrador == true){ sw.WriteLine($"{usuario.Id};{usuario.Nome};{usuario.Email};{usuario.Senha};1"); } } return usuario; } public UsuarioModel BuscarPorId(int id) { string[] linhas = System.IO.File.ReadAllLines ("usuarios.csv"); for (int i = 0; i < linhas.Length; i++) { if (string.IsNullOrEmpty (linhas[i])) { continue; } string[] dados = linhas[i].Split (';'); if (dados[0] == id.ToString ()) { UsuarioModel usuario = new UsuarioModel ( id: int.Parse (dados[0]), nome: dados[1], email: dados[2], senha: dados[3], administrador: (dados[4] == "0" ? false : true) ); return usuario; } } return null; } } }
543efa006b7ca4272bf1898061e3b360f2c5d632
C#
stkona/testrepo
/TDDProject/Program.cs
3.078125
3
using System; using System.Collections.Generic; namespace TDDProject { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!"); var newList = new List<string[]>() { new string[] { "Tom", "Python", "Junior"}, new string[] { "Tom", "Python", "Junior"}, new string[] { "Lily", "Python", "Senior" }, new string[] { "Nathan", "Java", "Senior" }, new string[] { "Josh", "Java", "Junior" }, new string[] { "Penka", "JavaScript", "Junior" }, new string[] { "Gosho", "JavaScript", "Senior" }, }; var result = Builder.CreateDevelopers(newList); var pairs = Builder.ArrangePairs(result); foreach (var item in pairs) { Console.WriteLine(item.Language); Console.WriteLine(item.FirstDeveloper.Name + " and " + item.SecondDeveloper.Name); } Console.WriteLine(string.Join("|", Builder.BuildNickname(pairs))); } } }
a22b07432d1d4e8582c2f185eff76debb21320c3
C#
prasanjeetd/CTM
/CTM/Conference.cs
3.1875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CTM { public class Conference { #region " CONSTRUCTORS " public Conference() { this.TalksToSchedule = new List<Talk>(); this.ScheduledTracks = new List<Track>(); } public Conference(DayFormat trackFormat) : this() { this.DayFormat = trackFormat; } #endregion #region " PROPERTIES " public List<Talk> TalksToSchedule { get; set; } public DayFormat DayFormat { get; set; } public List<Track> ScheduledTracks { get; set; } #endregion #region " PRIVATE METHODS " private Event HandleSession(Session session, Track track) { var scheduler = new SessionScheduler(this.TalksToSchedule, session, track); var @event = scheduler.Schedule(); return @event; } private Event HandleSingleEvent(SingleEvent singleEvent, Track track) { Event @event= EventFactory.GetInstance(singleEvent, track); @event.Schedule(); return @event; } #endregion #region " PUBLIC METHOD " public List<Track> Schedule() { TalksToSchedule = TalksToSchedule.OrderByDescending(x => x.Duration).ToList(); while (TalksToSchedule.Count != 0) { var track = new Track(); foreach (var @event in DayFormat.Events) { if (@event is Session) { if (TalksToSchedule.Count == 0) break; Event session = HandleSession(@event as Session, track); track.Events.Add(session); } else { Event singleEvent = HandleSingleEvent(@event as SingleEvent, track); track.Events.Add(singleEvent); } } this.ScheduledTracks.Add(track); } return this.ScheduledTracks; } #endregion } }
38281876e736fe32e0d8a57b4943c39dd10328ed
C#
yanyitec/yitec
/Yitec/Compiling/FileSource.cs
3.015625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Yitec.Compiling { public class FileSource : ISource { public FileSource(string filename) { this.Filename = filename; } public string Filename { get; private set; } public string GetContent() { return System.IO.File.ReadAllText(this.Filename); } public bool Equals(ISource other) { if (other == null) return false; if (other == this) return true; var ot = other as FileSource; if (ot != null) { return ot.Filename.ToLower() == this.Filename.ToLower(); } return false; } } }
9897af724e3d75fbb784aa79e1602a3e4197d0f7
C#
BrianArdila/Ejercicios-en-Visual-Studio
/appEvalUnitTest_Brian_Ardila/appEvalUnitTest_Brian_Ardila/Program.cs
2.75
3
using appEvalUnitTest_Brian_Ardila.SaludDelosPerros; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace appEvalUnitTest_Brian_Ardila { class Program { static void Main(string[] args) { ProgramPerros Call = new ProgramPerros(); do { Console.WriteLine("===================== Menu Principal ======================"); Console.WriteLine("Escoja una de las siguiente dos opciones"); Console.WriteLine("Presione 1 para Evaluar el estado de nutrición de su mascota"); Console.WriteLine("Presione 2 para Salir"); Console.WriteLine("============================================================"); int choose = int.Parse(Console.ReadLine()); Call.MenuPrincipal(choose); } while (!Call.continuar); Console.WriteLine("\nKey kiss"); Console.ReadLine(); } } }
cca92a6135735ca3662c7fa793cb056a2c9544e7
C#
shendongnian/download4
/latest_version_download2/66280-12161050-28519852-3.cs
2.671875
3
var result = A.Concat(B) .GroupBy(x => x.Id) .Select(g => new { id = g.Key, isShipCollected = g.Any(m => m.IsChipCollected == 1), isShirtCollected = g.Any(m => m.IsShirtCollected == 1), isPackCollected = g.Any(m => m.IsPackCollected == 1) });
c63607499962e5defa01c1199342867a3585c46f
C#
avifarah/MySync
/MySync/ProgramArgs.cs
3.046875
3
using System; using System.Linq; using System.IO; using System.Collections.Generic; namespace MySync { public class ProgramArgs : IProgramArgs { public ProgramArgs(string primary, string secondary, string skipTil) { if (primary != null && Directory.Exists(primary)) MySyncConfiguration.Inst.PrimaryDir = Path.GetFullPath(primary); if (secondary != null && Directory.Exists(secondary)) MySyncConfiguration.Inst.SecondaryDir = Path.GetFullPath(secondary); if (!string.IsNullOrWhiteSpace(skipTil) && Directory.Exists(skipTil)) MySyncConfiguration.Inst.SkippingTillDir = Path.GetFullPath(skipTil); _primaryParts = BreakDirParts(Primary); _skipParts = BreakDirParts(SkipTil); if (_skipParts.Count >= _primaryParts.Count) { bool allEqual = _primaryParts.Select((p, i) => string.Compare(p, _skipParts[i], StringComparison.InvariantCultureIgnoreCase) == 0).All(b => b); if (allEqual) { _stopSkippingFiles = false; _stopSkippingDirectories = false; } } } public string Primary => MySyncConfiguration.Inst.PrimaryDir; public string Secondary => MySyncConfiguration.Inst.SecondaryDir; public string SkipTil => MySyncConfiguration.Inst.SkippingTillDir; private bool _stopSkippingFiles = true; private bool _stopSkippingDirectories = true; private readonly List<string> _skipParts; private readonly List<string> _primaryParts; public bool IsPrimaryLegit() => Directory.Exists(Primary); public bool IsSecondaryLegit() => Directory.Exists(Secondary); /// <inheritdoc /> /// <summary> /// SkipTill may be: /// &gt; Empty /// &gt; Must exits as a directory /// &gt; It must be a superset of the primary directory /// </summary> /// <returns></returns> public bool IsSkipTilLegit() { if (string.IsNullOrWhiteSpace(SkipTil)) return true; if (!IsDirectoryExist(SkipTil)) return false; if (_skipParts.Count < _primaryParts.Count) return false; bool allEqual = _primaryParts.Select((p, i) => string.Compare(p, _skipParts[i], StringComparison.InvariantCultureIgnoreCase) == 0).All(b => b); return allEqual; } /// <summary> /// Needed for unit testing /// </summary> /// <param name="dir"></param> /// <returns></returns> protected virtual bool IsDirectoryExist(string dir) => Directory.Exists(dir); private List<string> BreakDirParts(string dir) { var parts = new List<string>(); if (string.IsNullOrWhiteSpace(dir)) return parts; if (dir.EndsWith("\\")) dir = dir.Substring(0, dir.Length - 1); for (;;) { string file = Path.GetFileName(dir); if (string.IsNullOrWhiteSpace(file)) { parts.Add(dir); break; } var dirNext = Path.GetDirectoryName(dir); if (string.IsNullOrEmpty(dirNext)) { parts.Add(dir); break; } parts.Add(file); dir = dirNext; } parts.Reverse(); return parts; } public bool IsSkipFileCopy(DirectoryInfo dir) => IsSkipFileCopy(dir.FullName); public bool IsSkipFileCopy(string dir) { if (_stopSkippingFiles) return false; var dirFullPath = Path.GetFullPath(dir); bool allEqual = string.Compare(SkipTil, dirFullPath, StringComparison.InvariantCultureIgnoreCase) == 0; if (allEqual) _stopSkippingFiles = true; return true; } public bool IsSkipDirCopy(DirectoryInfo dir) => IsSkipDirCopy(dir.FullName); public bool IsSkipDirCopy(string dir) { if (_stopSkippingDirectories) return false; var dirFullPath = Path.GetFullPath(dir); var dirParts = BreakDirParts(dirFullPath); for (int i = 0; i < Math.Min(dirParts.Count, _skipParts.Count); ++i) if (string.Compare(dirParts[i], _skipParts[i], StringComparison.OrdinalIgnoreCase) != 0) return true; if (dirParts.Count == _skipParts.Count) _stopSkippingDirectories = true; return false; } } }
fd610834e4aa3ab7d424c299d1410beac67252cb
C#
ssurucu/ProducerConsumerMultiProcesses
/MainProcess/Program.cs
2.890625
3
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Configuration; namespace MainProcess { class Program { static void Main(string[] args) { CancellationTokenSource cts = new CancellationTokenSource(); CancellationToken token = cts.Token; Task.Factory.StartNew(() => { Listener.StartServer(token); }, token); int bufferCapacity = int.Parse(ConfigurationManager.AppSettings["BufferCapacity"]); //Defining the semaphores to be used Semaphore b = new Semaphore(1, 1, "Busy"); //The semaphore will be used for Busy condition of the buffer Semaphore e = new Semaphore(bufferCapacity, bufferCapacity, "Empty"); //Empty semaphore will represent empty buffer Semaphore f = new Semaphore(0, bufferCapacity, "Full"); //Empty semaphore will represent full buffer Semaphore l = new Semaphore(1, 1, "LogAccess"); //The semaphore will be used for Busy condition of the logfile //Read from configuration file int producerCount = int.Parse(ConfigurationManager.AppSettings["ProducerNum"]); int consumerCount = int.Parse(ConfigurationManager.AppSettings["ConsumerNum"]); Task[] producers = new Task[producerCount]; Task[] consumers = new Task[consumerCount]; //To start procuder processes for (int i = 0; i < producerCount; i++) { producers[i] = Task.Factory.StartNew(() => { ProcessStartInfo psi = new ProcessStartInfo(@"..\..\..\..\P2-BPC\ProducerProcess\bin\debug\ProducerProcess.exe"); Process p = new Process(); p.StartInfo = psi; p.Start(); p.WaitForExit(); }, TaskCreationOptions.LongRunning); } //To start consumer processes for (int i = 0; i < consumerCount; i++) { consumers[i] = Task.Factory.StartNew(() => { ProcessStartInfo psi = new ProcessStartInfo(@"..\..\..\..\P2-BPC\ConsumerProcess\bin\debug\ConsumerProcess.exe"); Process p = new Process(); p.StartInfo = psi; p.Start(); p.WaitForExit(); }, TaskCreationOptions.LongRunning); } Console.WriteLine("///////////////////////////////////////////////////////"); Console.WriteLine("Processes are created"); Console.WriteLine("///////////////////////////////////////////////////////"); Task.WaitAll(producers.Concat(consumers).ToArray()); cts.Cancel(); int full = f.Release(); int empty = e.Release(); b.Dispose(); f.Dispose(); e.Dispose(); Console.WriteLine("\n"); Console.WriteLine("///////////////////////////////////////////////////////"); Console.WriteLine("Time is Up"); Console.WriteLine("///////////////////////////////////////////////////////"); Console.WriteLine("Processes are killed"); Console.WriteLine("///////////////////////////////////////////////////////"); Console.WriteLine("Result:\n"); Console.WriteLine("Empty Slot:" + empty + " Full Slot:" + full); Console.WriteLine("Consumed Transactions Done: " + Listener.getConsumerTransactionsCount() +"\n"); Console.WriteLine("Produced Transactions Done: " + Listener.getProducerTransactionsCount() + "\n"); Console.WriteLine("Total Transactions Done: " + full + "\n"); Console.WriteLine("///////////////////////////////////////////////////////"); Console.ReadLine(); } } }
cc027e9ef8296cadc12eef36e80b83088f4b4eb4
C#
koryakinp/cnn
/Cnn.Example/MnistReader.cs
3
3
using System.Collections.Generic; using System.IO; namespace Cnn.Example { public static class MnistReader { private const string TrainImages = "mnist/train-images.idx3-ubyte"; private const string TrainLabels = "mnist/train-labels.idx1-ubyte"; private const string TestImages = "mnist/t10k-images.idx3-ubyte"; private const string TestLabels = "mnist/t10k-labels.idx1-ubyte"; public static IEnumerable<Image> ReadTrainingData() { foreach (var item in Read(TrainImages, TrainLabels)) { yield return item; } } public static IEnumerable<Image> ReadTestData() { foreach (var item in Read(TestImages, TestLabels)) { yield return item; } } private static IEnumerable<Image> Read(string imagesPath, string labelsPath) { List<Image> imgs = new List<Image>(); BinaryReader labels = new BinaryReader(new FileStream(labelsPath, FileMode.Open)); BinaryReader images = new BinaryReader(new FileStream(imagesPath, FileMode.Open)); int magicImages = images.ReadBigInt32(); int numberOfImages = images.ReadBigInt32(); int width = images.ReadBigInt32(); int height = images.ReadBigInt32(); int magicLabel = labels.ReadBigInt32(); int numberOfLabels = labels.ReadBigInt32(); for (int i = 0; i < numberOfImages; i++) { var bytes = images.ReadBytes(width * height); var arr = new byte[height, width]; for (int j = 0; j < height; j++) { for (int k = 0; k < width; k++) { arr[j, k] = bytes[j * height + k]; } } yield return new Image() { Data = arr, Label = labels.ReadByte() }; } } } }
2049e8fdd0c37b5c58327b61c186f6c42003e380
C#
NickSegalle/crane
/src/Crane.Core/Commands/Resolvers/SolutionPathResolver.cs
2.671875
3
using System.IO; using System.Linq; using Crane.Core.Commands.Exceptions; namespace Crane.Core.Commands.Resolvers { public class SolutionPathResolver : ISolutionPathResolver { public string GetPathRelativeFromBuildFolder(string rootFolder, params string[] ignoreDirs) { var root = new DirectoryInfo(rootFolder); return GetPath(rootFolder).Replace(root.FullName, ".."); } public string GetPath(string rootFolder) { var root = new DirectoryInfo(rootFolder); var solutions = root.GetFiles("*.sln", SearchOption.AllDirectories); if (solutions.Length == 0) throw new NoSolutionsFoundCraneException(rootFolder); if (solutions.Length > 1) throw new MultipleSolutionsFoundCraneException(solutions.Select(s => s.Name).ToArray()); return solutions.First().FullName; } } }
a667885cd498692bec84500b878f1a958d545887
C#
DavidAllanDev/Custom-Manual-ORM
/Custom.Manual.ORM.Base/Data/SQL/SQLBase.cs
2.640625
3
using System.Collections.Generic; using Custom.Manual.ORM.Base.Data.Fields; using Custom.Manual.ORM.Base.Interfaces; namespace Custom.Manual.ORM.Base.Data.SQL { public abstract class SQLBase<T, TId> where T : IIdentifiable<TId> { private readonly string _sqlSelectFrom = "SELECT * FROM"; protected string TableName; protected Dictionary<string, string> ExplicitMappings; protected string MapPropertyNameToColumnName(string propertyName) { if (ExplicitMappings == null) return propertyName; return ExplicitMappings.ContainsKey(propertyName) ? ExplicitMappings[propertyName] : propertyName; } protected string GetSQLGetCount() { return string.Format("SELECT COUNT(*) FROM {0} ", TableName); } protected string GetSQLUpdateEntity(T entity, string colSetPlaceHolder) { return string.Format("UPDATE {0} SET {1} WHERE {2} = {3}", TableName, colSetPlaceHolder, MapPropertyNameToColumnName(KeyFields.Id), entity.Id); } protected string GetSQLGetById(TId id) { return string.Format("{0} {1} {2}", _sqlSelectFrom, TableName, GetSQLWhereId(id)); } protected string GetSQLDeleteById(TId id) { return string.Format("DELETE FROM {0} {1}", TableName, GetSQLWhereId(id)); } protected string GetSQLWhereId(TId id) { string columnName = MapPropertyNameToColumnName(KeyFields.Id); if (id is string) { return string.Format("WHERE {0}='{1}'", columnName, id); } else if (id.GetType() == typeof(char[])) { return string.Format("WHERE {0}='{1}'", columnName, id); } else if (id is char) { return string.Format("WHERE {0}='{1}'", columnName, id); } else if (id is int) { return string.Format("WHERE {0}={1}", columnName, id); } else if (id is byte) { return string.Format("WHERE {0}={1}", columnName, id); } else if (id is sbyte) { return string.Format("WHERE {0}={1}", columnName, id); } else if (id is decimal) { return string.Format("WHERE {0}={1}", columnName, id); } else if (id is double) { return string.Format("WHERE {0}={1}", columnName, id); } else if (id is float) { return string.Format("WHERE {0}={1}", columnName, id); } else if (id is uint) { return string.Format("WHERE {0}={1}", columnName, id); } else if (id is long) { return string.Format("WHERE {0}={1}", columnName, id); } else if (id is ulong) { return string.Format("WHERE {0}={1}", columnName, id); } else if (id is short) { return string.Format("WHERE {0}={1}", columnName, id); } else if (id is ushort) { return string.Format("WHERE {0}={1}", columnName, id); } else { return string.Format("WHERE {0}='{1}'", columnName, id); } } protected string GetSQLAddEntity(string colNamePlaceHolder, string colValuePlaceHolder) { return string.Format("INSERT INTO {0} ({1}) VALUES ({2}) SELECT SCOPE_IDENTITY()", TableName, colNamePlaceHolder, colValuePlaceHolder); } protected string GetSQLGetAll() { return string.Format("{0} {1}", _sqlSelectFrom, TableName); } } }
ac5a0b3c472fc1382e36aa01bdab0500315dca4e
C#
BenjaminHamon/Overmind
/Games/Mods/Overmind.Games.Chess/Player.cs
2.984375
3
using Overmind.Core; using Overmind.Games.Engine; using System; using System.Drawing; using System.Linq; namespace Overmind.Games.Chess { public class Player : Engine.Player { public Player(Game game, string name, Color color) : base(game, name, color) { } public void Move(Piece source, Vector destination, bool checkPath) { if (game.FindEntity<Piece>(destination) != null) throw new Exception("Destination is occupied"); if (checkPath && (IsPathEmpty(source.Position, destination) == false)) throw new Exception("Path to destination is not empty"); source.Position = destination; IsTurnOver = true; } public void Take(Piece source, Vector target, bool checkPath) { Piece targetPiece = game.FindEntity<Piece>(target); if (targetPiece == null) throw new Exception("Target piece not found"); if (EntityCollection.Contains(targetPiece)) throw new Exception("Target piece belongs to the active player"); if (checkPath && (IsPathEmpty(source.Position, target) == false)) throw new Exception("Path to target is not empty"); targetPiece.Destroy(); source.Position = target; IsTurnOver = true; } private bool IsPathEmpty(Vector source, Vector destination) { Vector move = destination - source; if (move == new Vector(0, 0)) return true; // Normalize on each coordinate instead of using Vector.Normalize to get integers. Vector unitVector = new Vector(move.Select(coord => coord == 0d ? 0d : (coord > 0d ? 1d : -1d))); for (Vector current = source + unitVector; current != destination; current += unitVector) if (game.FindEntity<Piece>(current) != null) return false; return true; } public override bool AutoEndTurn { get { return true; } } } }
80d7f063516ece862f18012371965d8617b766f0
C#
wasabii/GLibSharp
/GObject.Introspection/Library/Model/ReturnValueElement.cs
2.59375
3
using System.Collections.Generic; using System.Linq; using System.Xml.Linq; namespace GObject.Introspection.Library.Model { /// <summary> /// Return value of a callable. /// </summary> public class ReturnValueElement : Element, IHasDocumentation { public static IEnumerable<ReturnValueElement> LoadFrom(XContainer container) { return container.Elements().Select(i => Load(i)).OfType<ReturnValueElement>(); } public static ReturnValueElement Load(XElement element) { return element.Name == Xmlns.Core_1_0_NS + "return-value" ? Populate(new ReturnValueElement(), element) : null; } public static ReturnValueElement Populate(ReturnValueElement target, XElement element) { Element.Populate(target, element); target.Introspectable = (int?)element.Attribute("introspectable") != 0; target.Nullable = element.Attribute("nullable").ToBool(); target.Closure = (int?)element.Attribute("closure"); target.Scope = element.Attribute("scope").ToEnum<ValueScope>(); target.Destroy = (int?)element.Attribute("destroy"); target.Skip = element.Attribute("skip").ToBool(); target.AllowNone = element.Attribute("allow-none").ToBool(); target.TransferOwnership = element.Attribute("transfer-ownership").ToEnum<TransferOwnership>(); target.Documentation = Documentation.Load(element); target.Type = AnyTypeElement.LoadFrom(element).FirstOrDefault(); return target; } public bool? Introspectable { get; set; } public bool? Nullable { get; set; } public int? Closure { get; set; } public ValueScope? Scope { get; set; } public int? Destroy { get; set; } public bool? Skip { get; set; } public bool? AllowNone { get; set; } public TransferOwnership? TransferOwnership { get; set; } public Documentation Documentation { get; set; } public AnyTypeElement Type { get; set; } public override string ToString() { return Type?.ToString(); } } }
f0de5dfeb7c68eb6532b6fc2bf6b6e10028eabd4
C#
GrigoriyBykovskiy/SteganographyJPEG
/SteganographyJPEG/DKP.cs
3.046875
3
using System; namespace SteganographyJPEG { public static class DKP { public static double[,] Dkp(byte[,] one) { int n = one.GetLength(0); double[,] two = new double[n, n]; double U; double V; double temp; for (int v = 0; v < n; v++) { for (int u = 0; u < n; u++) { if (v == 0) V = 1.0 / Math.Sqrt(2); else V = 1; if (u == 0) U = 1.0 / Math.Sqrt(2); else U = 1; temp = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { temp += one[i, j] * Math.Cos(Math.PI * v * (2 * i + 1) / (2 * n)) * Math.Cos(Math.PI * u * (2 * j + 1) / (2 * n)); } } two[v, u] = U * V * temp / (Math.Sqrt(2 * n)); } } return two; } public static double[,] Odkp(double[,] one) { int n = one.GetLength(0); double[,] two = new double[n, n]; double U; double V; double temp; for (int v = 0; v < n; v++) { for (int u = 0; u < n; u++) { temp = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i == 0) V = 1.0 / Math.Sqrt(2); else V = 1; if (j == 0) U = 1.0 / Math.Sqrt(2); else U = 1; temp += U * V * one[i, j] * Math.Cos(Math.PI * i * (2 * v + 1) / (2 * n)) * Math.Cos(Math.PI * j * (2 * u + 1) / (2 * n)); } } two[v, u] = temp / (Math.Sqrt(2 * n)); } } return two; } public static double[,] CoefficientChange(double[,] temp, char/*int*/ i, int u1, int v1, int u2, int v2, int P) { /* double - матрица коэффициентов i - бит нашего сообщения (0 или 1) u,v - координаты коэффициентов */ //double[,] two = new double[one.GetLength(0), one.GetLength(1)]; //for (int k = 0; k < two.GetLength(0); k++) // for (int l = 0; l < two.GetLength(1); l++) // two[k, l] = one[k, l]; double Abs1, Abs2; double z1 = 0, z2 = 0; Abs1 = Math.Abs(temp[u1, v1]); Abs2 = Math.Abs(temp[u2, v2]); if (temp[u1, v1] >= 0) z1 = 1; else z1 = -1; if (temp[u2, v2] >= 0) z2 = 1; else z2 = -1; if (i == '0')//if (i == 0) { if (Abs1 - Abs2 <= P) Abs1 = P + Abs2 + 1; } if (i == '1')//if (i == 1) { if (Abs1 - Abs2 >= -P) Abs2 = P + Abs1 + 1; } temp[u1, v1] = z1 * Abs1; temp[u2, v2] = z2 * Abs2; return temp; } } }
30c703468a2d4d108faf3fd17b46fe21237fb00f
C#
maniero/SOpt
/CSharp/Linq/General.cs
3.15625
3
using static System.Console; using System.Collections.Generic; using System.Linq; public class Program { public static void Main() { var produtos = new List<Produto> { new Produto {ProdutoId = 1, Descricao = "P1", Preco = 10.00M, Estoque = 10 }, new Produto {ProdutoId = 2, Descricao = "P2", Preco = 20.00M, Estoque = 20 }}; var filtrado = Lista(produtos); foreach (var produto in filtrado) WriteLine(produto.ProdutoId); filtrado = FiltreNome(produtos, "P2"); WriteLine("Filtrado"); foreach (var produto in filtrado) WriteLine(produto.ProdutoId); } public static IEnumerable<Produto> Lista(IEnumerable<Produto> produtos) { return from p in produtos select new Produto { ProdutoId = p.ProdutoId, Descricao = p.Descricao, Preco = p.Preco, Estoque = p.Estoque }; } public static IEnumerable<Produto> FiltreNome(IEnumerable<Produto> produtos, string descricao) { var query = from p in produtos where p.Descricao.StartsWith(descricao) select p; return Lista(query); } } public class Produto { public int ProdutoId; public string Descricao; public decimal Preco; public int Estoque; } //https://pt.stackoverflow.com/q/108757/101
948f9d94de05ef4b698f6c41bf00f55ac0921362
C#
shendongnian/download4
/first_version_download2/230455-18097962-44953113-2.cs
3.125
3
void go() { int i = 5; int i1 = i; //note this ThreadPool.QueueUserWorkItem(delegate { for (int j = 1; j <= 1000; j++) Console.Write(i1); //and note this }); for (int k = 1; k <= 1000; k++) i = k; Console.ReadLine(); }
a95a49cadf2fbcaf6ba21f75b65394fe5f05ae37
C#
pvcbuild/pvc
/Pvc.Core/Pvc.cs
2.703125
3
using Minimatch; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Humanizer; using System.Text.RegularExpressions; using Edokan.KaiZen.Colors; namespace PvcCore { public class Pvc { public readonly List<PvcTask> LoadedTasks; public readonly List<string> CompletedTasks; private readonly ConcurrentDictionary<string, object> locks; public Pvc() { this.LoadedTasks = new List<PvcTask>(); this.CompletedTasks = new List<string>(); this.locks = new ConcurrentDictionary<string, object>(); } public PvcTask Task(string taskName, Action taskAction) { var task = new PvcTask(taskName, taskAction); this.LoadedTasks.Add(task); return task; } public PvcTask Task(string taskName, Action<Action> asyncTaskAction) { var task = new PvcTask(taskName, asyncTaskAction); this.LoadedTasks.Add(task); return task; } public PvcTask Task(string taskName) { return this.Task(taskName, () => { }); } public PvcPipe Source(params string[] inputs) { return new PvcPipe().Source(inputs); } public PvcPipe Source(string input) { return new PvcPipe().Source(new[] { input }); } public void Start(string taskName) { if (this.LoadedTasks.FirstOrDefault(x => x.taskName == taskName) == null) throw new PvcException("Task {0} not defined.", taskName); var dependencyGraph = new PvcDependencyGraph(); foreach (var task in this.LoadedTasks) { dependencyGraph.AddDependencies(task.taskName, task.dependentTaskNames); } var executionPaths = new List<IEnumerable<PvcTask>>(); var runPaths = dependencyGraph.GetPaths(taskName); foreach (var runPath in runPaths) { var runTasks = runPath.Select(x => this.LoadedTasks.First(y => y.taskName == x)); executionPaths.Add(runTasks); foreach (var runTask in runTasks) { // create locks locks.AddOrUpdate(runTask.taskName, new { }, (s, o) => o); } } try { foreach (var executionPath in executionPaths.AsParallel()) { this.RunTasks(executionPath.ToArray()); } } catch (AggregateException ex) { throw new PvcException(ex.InnerException); } } private void RunTasks(PvcTask[] tasks) { for (int i = 0; i < tasks.Length; i++) { var task = tasks[i]; // lock on task name to avoid multiple threads doing the work lock (locks[task.taskName]) { try { if (CompletedTasks.Contains(task.taskName)) continue; if (task.isAsync) { // Start callback chain for async methods, lock on task Monitor.Enter(locks[task.taskName]); var callbackCalled = false; var stopwatch = this.StartTaskStatus(task.taskName); task.ExecuteAsync(() => { this.FinishTaskStatus(task.taskName, stopwatch); CompletedTasks.Add(task.taskName); if (i != tasks.Length - 1) this.RunTasks(tasks.Skip(i + 1).ToArray()); callbackCalled = true; }); // Keep app running while async task completes while (callbackCalled == false) { } break; } else { var stopwatch = this.StartTaskStatus(task.taskName); task.Execute(); CompletedTasks.Add(task.taskName); this.FinishTaskStatus(task.taskName, stopwatch); } } catch (Exception ex) { throw new PvcException(ex); } } } } private Stopwatch StartTaskStatus(string taskName) { var stopwatch = new Stopwatch(); stopwatch.Start(); Console.WriteLine("Starting '{0}' ...", taskName.Magenta()); return stopwatch; } private void FinishTaskStatus(string taskName, Stopwatch stopwatch) { stopwatch.Stop(); Console.WriteLine("Finished '{0}' in {1}", taskName.Magenta(), stopwatch.Elapsed.Humanize().White()); } } }
b8229c8b33e44bff90b27f1f33e4371173425b2d
C#
fbuether/GoodNight2
/service/GoodNight.Service.Storage/Serialisation/ReferenceConverterFactory.cs
2.671875
3
using System; using System.Linq; using System.Text.Json; using System.Text.Json.Serialization; using GoodNight.Service.Storage.Interface; namespace GoodNight.Service.Storage.Serialisation { public class ReferenceConverterFactory : JsonConverterFactory { private Store store; public ReferenceConverterFactory(Store store) { this.store = store; } public override bool CanConvert(Type typeToConvert) { return typeToConvert.IsGenericType && typeToConvert.GetGenericTypeDefinition() == typeof(IReference<>); } public override JsonConverter? CreateConverter(Type typeToConvert, JsonSerializerOptions options) { var elementType = typeToConvert.GetGenericArguments().First(); var repos = Activator.CreateInstance( typeof(ReferenceConverter<>).MakeGenericType(elementType), new [] { store }) as JsonConverter; if (repos is null) throw new Exception( $"Could not create ReferenceConverter for {elementType.FullName}"); return repos; } } }
64e43bb8a586b56948e3bc3e32efb924cb763ea7
C#
slorion/multiagent-system-example
/DLC.Multiagent/Rxx/System/Reactive/Subjects/ReadOnlyListSubject.cs
2.71875
3
using System.Collections.Generic; #if !PORT_40 using System.Collections.Specialized; #endif using System.ComponentModel; using System.Diagnostics.Contracts; namespace System.Reactive.Subjects { /// <summary> /// Provides a read-only wrapper around an <see cref="IListSubject{T}"/>. /// </summary> /// <typeparam name="T">The type of the elements in the collection.</typeparam> /// <threadsafety instance="true" /> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "It's a list, not just a collection. It's also a subject.")] public sealed class ReadOnlyListSubject<T> : IListSubject<T>, INotifyPropertyChanged { #region Public Properties /// <summary> /// Gets the number of elements currently contained in the list. /// </summary> public int Count { get { return subject.Count; } } /// <summary> /// Gets a value indicating whether the list is read-only. /// </summary> /// <value>Always returns <see langword="true" />.</value> public bool IsReadOnly { get { return true; } } /// <summary> /// Gets the element at the specified index. Setting this property is not supported. /// </summary> /// <param name="index">The zero-based index of the element to get.</param> /// <returns>The element at the specified index.</returns> /// <exception cref="NotSupportedException">Attempted to set an item in a read-only list.</exception> [ContractVerification(false)] public T this[int index] { get { return subject[index]; } set { throw new NotSupportedException(); } } #endregion #region Private / Protected private readonly IListSubject<T> subject; #endregion #region Constructors /// <summary> /// Constructs a new instance of the <see cref="ReadOnlyListSubject{T}" /> class. /// </summary> /// <param name="subject">The subject to be decorated with a read-only wrapper.</param> public ReadOnlyListSubject(IListSubject<T> subject) { Contract.Requires(subject != null); this.subject = subject; } #endregion #region Methods [ContractInvariantMethod] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "Required for code contracts.")] private void ObjectInvariant() { Contract.Invariant(subject != null); } /// <summary> /// Returns an observable sequence of collection notifications that represent changes to the list. /// </summary> /// <returns>An observable sequence of collection notifications that represent changes to the list.</returns> public IObservable<CollectionNotification<T>> Changes() { return subject.Changes(); } /// <summary> /// Notifies the subject that an observer is to receive collection notifications, starting with a notification /// that contains a snapshot of the existing values in the list. /// </summary> /// <param name="observer">The object that is to receive collection notifications.</param> /// <returns>The observer's interface that enables resources to be disposed.</returns> public IDisposable Subscribe(IObserver<CollectionNotification<T>> observer) { return subject.Subscribe(observer); } /// <summary> /// Changes the list according to the specified collection modification. This method is not supported. /// </summary> /// <param name="value">A modification that indicates how the list must be changed.</param> /// <exception cref="NotSupportedException">Attempted to modify a read-only list.</exception> public void OnNext(CollectionModification<T> value) { throw new NotSupportedException(); } /// <summary> /// Terminates the subject with an error condition. This method is not supported. /// </summary> /// <param name="error">An object that provides additional information about the error.</param> /// <exception cref="NotSupportedException">Attempted to modify a read-only list.</exception> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", MessageId = "0#", Justification = "Windows Phone defines IObserver<T>.OnError with the name \"exception\" for the \"error\" parameter, but it's better to" + "leave it as \"error\" here so that callers can use the same named parameter across all platforms.")] public void OnError(Exception error) { throw new NotSupportedException(); } /// <summary> /// Notifies the subject to stop accepting collection modifications. This method is not supported. /// </summary> /// <exception cref="NotSupportedException">Attempted to modify a read-only list.</exception> public void OnCompleted() { throw new NotSupportedException(); } /// <summary> /// Determines whether the list contains a specific value. /// </summary> /// <param name="item">The object to locate in the list.</param> /// <returns><see langword="True"/> if <paramref name="item"/> is found in the list; otherwise, <see langword="false"/></returns> [ContractVerification(false)] public bool Contains(T item) { return subject.Contains(item); } /// <summary> /// Determines the index of a specific item in the list. /// </summary> /// <param name="item">The object to locate in the list.</param> /// <returns>The index of <paramref name="item"/> if found in the list; otherwise, -1.</returns> [ContractVerification(false)] public int IndexOf(T item) { return subject.IndexOf(item); } /// <summary> /// Adds an item to the list. This method is not supported. /// </summary> /// <param name="item">The object to add to the list.</param> /// <exception cref="NotSupportedException">Attempted to modify a read-only list.</exception> public void Add(T item) { throw new NotSupportedException(); } /// <summary> /// Inserts an item to the list at the specified index. This method is not supported. /// </summary> /// <param name="index">The zero-based index at which item should be inserted.</param> /// <param name="item">The object to insert into the list.</param> /// <exception cref="NotSupportedException">Attempted to modify a read-only list.</exception> public void Insert(int index, T item) { throw new NotSupportedException(); } /// <summary> /// Removes the first occurrence of a specific object from the list. This method is not supported. /// </summary> /// <param name="item">The object to remove from the list.</param> /// <returns><see langword="True" /> if <paramref name="item"/> was successfully removed from the list; otherwise, <see langword="false" />. /// This method also returns <see langword="false" /> if <paramref name="item"/> is not found in the list.</returns> /// <exception cref="NotSupportedException">Attempted to modify a read-only list.</exception> public bool Remove(T item) { throw new NotSupportedException(); } /// <summary> /// Removes the list item at the specified index. This method is not supported. /// </summary> /// <param name="index">The zero-based index of the item to remove.</param> /// <exception cref="NotSupportedException">Attempted to modify a read-only list.</exception> public void RemoveAt(int index) { throw new NotSupportedException(); } /// <summary> /// Removes all items from the list. This method is not supported. /// </summary> /// <exception cref="NotSupportedException">Attempted to modify a read-only list.</exception> public void Clear() { throw new NotSupportedException(); } /// <summary> /// Copies the elements of the list to an <see cref="Array"/>, starting at a particular <see cref="Array"/> index. /// </summary> /// <param name="array">The one-dimensional <see cref="Array"/> that is the destination of the elements copied from /// the list. The <see cref="Array"/> must have zero-based indexing.</param> /// <param name="arrayIndex">The zero-based index in array at which copying begins.</param> [ContractVerification(false)] public void CopyTo(T[] array, int arrayIndex) { subject.CopyTo(array, arrayIndex); } /// <summary> /// Returns an enumerator that iterates through the list. /// </summary> /// <remarks> /// The list is locked for the entire duration while enumerating. Any collection modifications that are received /// during the enumeration will be blocked. When the enumeration has completed, all previous modifications will be /// allowed to acquire the lock and mutate the list. For this reason it is best to enumerate quickly. For example, /// you could call the <see cref="System.Linq.Enumerable.ToList"/> extension method to take a snapshot of the list, /// then perform work by enumerating the snapshot while the subject is free to accept collection modifications. /// </remarks> /// <returns>An <see cref="IEnumerator{T}"/> that can be used to iterate through the collection.</returns> public IEnumerator<T> GetEnumerator() { return subject.GetEnumerator(); } Collections.IEnumerator Collections.IEnumerable.GetEnumerator() { return subject.GetEnumerator(); } /// <summary> /// Unsubscribes all observers and releases resources. /// </summary> public void Dispose() { subject.Dispose(); } #endregion #region Events #if !PORT_40 /// <summary> /// Occurs when an item is added, removed, changed, moved, or the entire list is refreshed. /// </summary> public event NotifyCollectionChangedEventHandler CollectionChanged { add { subject.CollectionChanged += value; } remove { subject.CollectionChanged -= value; } } #endif event PropertyChangedEventHandler INotifyPropertyChanged.PropertyChanged { add { ((INotifyPropertyChanged)subject).PropertyChanged += value; } remove { ((INotifyPropertyChanged)subject).PropertyChanged -= value; } } #endregion } }
906fef0f40ea862f1b6c36544ba76949b130af46
C#
jacob-carrier/ZanyZebras
/Zany Zebras/ScreenManager.cs
3.015625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; namespace Zany_Zebras { public class ScreenManager { private List<GameScreen> _screens; public ScreenManager() { _screens = new List<GameScreen>(); } public void pushScreen(GameScreen screen) { _screens.Add(screen); } public void popScreen() { _screens.RemoveAt(_screens.Count - 1); } public GameScreen currentScreen() { return _screens.Last(); } public void Render() { /*foreach (GameScreen screen in _screens) { if(!screen.Block) { screen.Render(); } } */ for (int i = 0; i < _screens.Count; i++) { if (!_screens[i].Block) { _screens[i].Render(); } } } public void Update(GameTime gameTime) { /*foreach (GameScreen screen in _screens) { if (!screen.Pause) { screen.Update(gameTime); } } */ for (int i = 0; i < _screens.Count; i++) { if (!_screens[i].Pause) { _screens[i].Update(gameTime); } } } } }
fc8c172fa30e91ab5c9ce535efed6aec60a45e9e
C#
Infarh/MathCore.EF7
/MathCore.EF7.Interfaces/Entities/INamedEntity.cs
2.546875
3
using System.ComponentModel.DataAnnotations; namespace MathCore.EF7.Interfaces.Entities { /// <summary>Именованная сущность</summary> /// <typeparam name="TKey">Тип первичного ключа</typeparam> public interface INamedEntity<out TKey> : IEntity<TKey> { /// <summary>Имя</summary> [Required] string Name { get; } } /// <summary>Именованная сущность</summary> public interface INamedEntity : INamedEntity<int>, IEntity { } }
c87605b0197aa6a6c900cd7d39461101c53c292e
C#
mhdr/SelectionMaker
/SelectionMaker/DialogeBoxModificationDetected.xaml.cs
2.5625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; 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 SelectionMaker { public enum AfterModifiactionDetected:uint { SEARCH=0, TURNOFF=1, CANCEL=2, } /// <summary> /// Interaction logic for DialogeBoxModificationDetected.xaml /// </summary> public partial class DialogeBoxModificationDetected : Window { private string SourcePath; public AfterModifiactionDetected doWhat = AfterModifiactionDetected.CANCEL; public static bool IsOpen = false; public DialogeBoxModificationDetected() { InitializeComponent(); } private void Window_Loaded(object sender, RoutedEventArgs e) { IsOpen = true; TextBlockSourcePath.Text = string.Format("Source path : {0}", SourcePath); TextBlockShowMSG.Text = "Modification detected in this folder,do you want to search this folder again?"; } public void GetSourcePath(string path) { SourcePath = path; } private void ButtonCancel_Click(object sender, RoutedEventArgs e) { doWhat = AfterModifiactionDetected.CANCEL; this.Close(); } private void ButtonSearchAgain_Click(object sender, RoutedEventArgs e) { doWhat = AfterModifiactionDetected.SEARCH; this.Close(); } private void ButtonTurnOffWatcher_Click(object sender, RoutedEventArgs e) { doWhat = AfterModifiactionDetected.TURNOFF; this.Close(); } private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e) { IsOpen = false; } } }
ca95c5d74d1040386f0d450f30feee1548ad177c
C#
Darituan/CSharpLabs
/Lab05/Tools/Sorting/PropertyGetterHelper.cs
3.109375
3
using System; using System.Collections.ObjectModel; using System.Text; namespace Lab05.Tools.Sorting { internal static class PropertyGetterHelper { internal static ObservableCollection<PropertyGetter> GetPropertyGetters(Type type) { var getters = new ObservableCollection<PropertyGetter>(); var properties = type.GetProperties(); foreach (var property in properties) { var getter = property.GetGetMethod(); var sb = new StringBuilder(); var propName = getter.Name.Replace("get_", ""); if (propName.Contains("Usage")) { propName = propName.Replace("Usage", " usage"); if (propName.Contains("Percentage")) propName = propName.Replace("Percentage", ", %"); else propName += ", MB"; getters.Add(new PropertyGetter(getter, propName)); } else { sb.Append(propName[0]); for (var i = 1; i < propName.Length; ++i) { if (char.IsUpper(propName, i)) sb.Append(' '); sb.Append(propName[i]); } getters.Add(new PropertyGetter(getter, sb.ToString())); } } return getters; } } }
a27787e8f519f15596e9f9c873f582f6a68cfe1f
C#
MikhailSasnavikSandbox/SampleUITestFramework.Net
/BBCTests/BBCTests/Insfrastructure/WebDriverManager.cs
2.75
3
using BBCTests.Helpers; using OpenQA.Selenium; using OpenQA.Selenium.Chrome; using OpenQA.Selenium.Firefox; using System; using System.Collections.Concurrent; namespace BBCTests.Insfrastructure { public static class WebDriverManager { private static ConcurrentDictionary<string, IWebDriver> driverDictionary = new ConcurrentDictionary<string, IWebDriver>(); public static IWebDriver Driver { get { if (driverDictionary.ContainsKey(DriverID)) { return driverDictionary[DriverID]; } throw new Exception("Driver is not initialized"); } } private static string DriverID => NUnitHelper.CurrentTestName; public static void CleanupDriver() { driverDictionary.TryRemove(DriverID, out IWebDriver tempDriver); tempDriver.Quit(); } public static void InitDriver(Browser browser) { var driver = ConfigreDriver(GetDriverInstance(browser)); driverDictionary.TryAdd(DriverID, driver); } private static IWebDriver GetDriverInstance(Browser browser) { switch (browser) { case Browser.Chrome: return GetChromeDriver(); case Browser.Firefox: return GetFirefoxDriver(); default: throw new Exception("Unsupported browser"); } } private static IWebDriver GetChromeDriver() { var driver = new ChromeDriver(); driver.Manage().Window.Maximize(); return driver; } private static IWebDriver GetFirefoxDriver() { var driver = new FirefoxDriver(); driver.Manage().Window.Maximize(); return driver; } private static IWebDriver ConfigreDriver(IWebDriver driver) { driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(40); driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(60); return driver; } } }
030bbda054bc68326b13f616066086ab9b01e1c2
C#
shendongnian/download4
/first_version_download2/120506-8460082-18980295-2.cs
2.640625
3
SocketError error; byte[] buffer = new byte[512]; // Custom protocol max/fixed message size int c = this.Receive(buffer, 0, buffer.Length, SocketFlags.None, out error); if (error != SocketError.Success) { if(error == SocketError.MessageSize) { // The message was to large to fit in our buffer } }
4597593eba132333d0e45dbbe40954fae0e8bbf8
C#
gueguet/BotnetVisuVR
/Assets/Scripts/BotnetScript/GraphManager.cs
2.515625
3
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using System; public class GraphManager : MonoBehaviour { // GameObject public GameObject map_arkansas; public GameObject substation_prefab; public GameObject substation_malicious_prefab; public GameObject source_linked; // UI public Text numberOfSubText; public Text timerText; // init the read csv script private CsvReader csvReader; public List<CsvReader.Flow> flowData = new List<CsvReader.Flow>(); void Start() { } void Update() { // WE HAVE TO CHANGE THIS INPUT --> WITH THE CONTROLLER if (Input.GetKeyDown("k")) { CreateGraph(); } } public void CreateGraph() { csvReader = GameObject.Find("CsvReaderController").GetComponent<CsvReader>(); // get the output of our readCsv script flowData = csvReader.flowData; // display the number of substation we receive from the csv we read numberOfSubText.text = "Number of substation to place on the map : " + flowData.Count; StartCoroutine("DrawLine"); } IEnumerator DrawLine() { // retrieve and use the positions information of each substation var subPosData = csvReader.subPositionDict; var ind_flow = 0; foreach (CsvReader.Flow row in flowData) { Debug.Log("Current flow charger " + row.sub_detect); var placedNode = new GameObject(); // instanciate a node for every substation we detect -- WE HAVE TO IMPLEMENT SOMETHING TO AVOID SUBSTATION DUPLICATION if (row.sub_detect == "normal") { placedNode = Instantiate(substation_prefab, Vector3.zero, Quaternion.identity); placedNode.transform.parent = map_arkansas.transform; placedNode.transform.name = "Destination node " + ind_flow; } else { placedNode = Instantiate(substation_malicious_prefab, Vector3.zero, Quaternion.identity); placedNode.transform.parent = map_arkansas.transform; placedNode.transform.name = "Destination node " + ind_flow; } int x_pos; int y_pos; try { x_pos = int.Parse(subPosData[row.substation][0]); y_pos = int.Parse(subPosData[row.substation][1]); placedNode.transform.localPosition = new Vector3(x_pos, y_pos, 0f); } catch { Debug.Log("error dictionnary" + subPosData[row.substation]); Debug.Log(row.substation); } // place the node according to the position info of the substation placedNode.GetComponent<DrawLine>().destination = source_linked; // NEED TO ADD DATA TO DRAW LINE DEPENDING ON NODE INFO // attached flow information to the GameObject placedNode.AddComponent<DstNodeData>(); var nodeData = placedNode.GetComponent<DstNodeData>(); nodeData.ip_dst = row.ip_dst; nodeData.port_dst = row.port_dst; nodeData.duration = row.duration; nodeData.size = row.size; nodeData.substation = row.substation; nodeData.date = row.date; nodeData.protocol = row.protocol; ind_flow++; // extract timer from the row var timerString = row.date.Substring(row.date.Length - 5); timerText.text = "Time : " + timerString; yield return new WaitForSeconds(2); } } }
80c23f595627957cd43231fe44b9b37e40fca350
C#
icedt89/Queryfy
/Source/Queryfy/Inspection/MetadataResolution/PropertyMetadataFactory.cs
2.71875
3
namespace JanHafner.Queryfy.Inspection.MetadataResolution { using System; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Reflection; using Attributes; using Toolkit.Common.ExtensionMethods; /// <summary> /// The <see cref="PropertyMetadataFactory"/> class. /// </summary> public class PropertyMetadataFactory : IPropertyMetadataFactory { /// <summary> /// Gets the <see cref="IPropertyMetadata"/> /// </summary> /// <param name="propertyInfo">The <see cref="PropertyInfo"/>.</param> /// <returns>The associated <see cref="IPropertyMetadata"/>.</returns> /// <exception cref="ArgumentNullException">The value of '<paramref name="propertyInfo"/>' cannot be null. </exception> /// <exception cref="MissingMemberException">The delaring <see cref="Type"/> of the supplied <see cref="PropertyInfo"/> is annotated with the <see cref="MetadataTypeAttribute"/> but the </exception> public virtual IPropertyMetadata GetPropertyMetadata(PropertyInfo propertyInfo) { if (propertyInfo == null) { throw new ArgumentNullException(nameof(propertyInfo)); } var queryParameterAttribute = propertyInfo.GetAttribute<QueryParameterAttribute>(); var metadataTypeAttribute = propertyInfo.DeclaringType.GetAttribute<MetadataTypeAttribute>(); if (metadataTypeAttribute != null) { var metadataPropertyType = metadataTypeAttribute.MetadataClassType.GetProperty(propertyInfo.Name, propertyInfo.PropertyType, propertyInfo.GetIndexParameters().Select(p => p.ParameterType).ToArray()); if (metadataPropertyType == null) { throw new MissingMemberException(metadataTypeAttribute.MetadataClassType.Name, propertyInfo.Name); } return new DataAnnotationsPropertyMetadata(queryParameterAttribute, metadataPropertyType, propertyInfo); } return new PropertyMetadata(queryParameterAttribute, propertyInfo); } } }
3456ff71a32b6744b497ebe702ec0e4d63cff284
C#
StephMoody/Moody.Snake
/Moody.Snake/Converter/FieldContentToFillConverter.cs
2.890625
3
using System; using System.ComponentModel; using System.Globalization; using System.Windows.Data; using System.Windows.Media; using Moody.Snake.Model; namespace Moody.Snake.Converter { public class FieldContentToFillConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (!(value is FieldContent fieldContent)) throw new InvalidOperationException(); switch (fieldContent) { case FieldContent.Empty: return new SolidColorBrush(Colors.Black); case FieldContent.Fruit: return new SolidColorBrush(Colors.Coral); case FieldContent.Snake: return new SolidColorBrush(Colors.Green); default: throw new InvalidEnumArgumentException(); } } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } }
ab30dd44b8e9222ffb748402b72d44551452835c
C#
AzureDay/2017-WebSite
/TeamSpark.AzureDay.WebSite.App/Service/CountryService.cs
2.6875
3
using System.Collections.Generic; using System.Linq; using TeamSpark.AzureDay.WebSite.App.Entity; namespace TeamSpark.AzureDay.WebSite.App.Service { public sealed class CountryService { private readonly List<Country> _countries = new List<Country> { new Country {Id = 1, ImageUrl = "https://azureday2017ua.blob.core.windows.net/images/flags/ua.png", Title = Localization.App.Service.Country.Ukraine}, new Country {Id = 2, ImageUrl = "https://azureday2017ua.blob.core.windows.net/images/flags/ru.png", Title = Localization.App.Service.Country.Russia}, new Country {Id = 3, ImageUrl = "https://azureday2017ua.blob.core.windows.net/images/flags/by.png", Title = Localization.App.Service.Country.Belarus}, new Country {Id = 4, ImageUrl = "https://azureday2017ua.blob.core.windows.net/images/flags/fr.png", Title = Localization.App.Service.Country.France}, new Country {Id = 5, ImageUrl = "https://azureday2017ua.blob.core.windows.net/images/flags/se.png", Title = Localization.App.Service.Country.Sweden}, new Country {Id = 6, ImageUrl = "https://azureday2017ua.blob.core.windows.net/images/flags/pl.png", Title = Localization.App.Service.Country.Poland}, new Country {Id = 7, ImageUrl = "https://azureday2017ua.blob.core.windows.net/images/flags/ro.png", Title = Localization.App.Service.Country.Romania}, new Country {Id = 8, ImageUrl = "https://azureday2017ua.blob.core.windows.net/images/flags/bg.png", Title = Localization.App.Service.Country.Bulgaria} }; public IEnumerable<Country> GetCountries() { return _countries.OrderBy(x => x.Title); } public Country Ukraine { get { return _countries.Single(x => x.Id == 1); } } public Country Russia { get { return _countries.Single(x => x.Id == 2); } } public Country Belarus { get { return _countries.Single(x => x.Id == 3); } } public Country France { get { return _countries.Single(x => x.Id == 4); } } public Country Sweden { get { return _countries.Single(x => x.Id == 5); } } public Country Poland { get { return _countries.Single(x => x.Id == 6); } } public Country Romania { get { return _countries.Single(x => x.Id == 7); } } public Country Bulgaria { get { return _countries.Single(x => x.Id == 8); } } } }
19449c2cf5768caf572025b99b14bf97c2bb4d17
C#
lethanus/HeroGame2
/HeroesGame.Core/FightingMechanism/Skills/AttackFrontLineSkill.cs
2.671875
3
using System.Collections.Generic; using System.Linq; using HeroesGame.Characters; namespace HeroesGame.FightMechanizm { public class AttackFrontLineSkill : Skill { public List<ICharacterInTeam> GetTargets(List<ICharacterInTeam> liveCharacters) { var targets = liveCharacters.Where(x => TeamPositionHelper.FrontLane.Contains(x.GetPosition())); if (targets.Count() == 0) { targets = liveCharacters.Where(x => TeamPositionHelper.MiddleLane.Contains(x.GetPosition())); if (targets.Count() == 0) { targets = liveCharacters.Where(x => TeamPositionHelper.RearLane.Contains(x.GetPosition())); } } return targets.ToList(); } } }
7404b68bf47c3c1a847fb7aef53de7f7da91eb67
C#
HelloNetWorld/DroneStore
/DroneStore.Services/Services/Discounts/DiscountService.cs
2.609375
3
using Ardalis.GuardClauses; using DroneStore.Core.Entities.Discounts; using DroneStore.Data; using System.Collections.Generic; namespace DroneStore.Services.Services.Discounts { public class DiscountService : IDiscountService { private readonly IRepository<Discount> _discountRep; public DiscountService(IRepository<Discount> discountRep) => _discountRep = discountRep; public void Delete(Discount discount) { Guard.Against.Null(discount, nameof(discount)); _discountRep.Delete(discount); } public IEnumerable<Discount> GetAll() => _discountRep.EntitiesReadOnly; public Discount GetById(int discountId) => _discountRep.GetById(discountId); public void Insert(Discount discount) { Guard.Against.Null(discount, nameof(discount)); _discountRep.Insert(discount); } public void Update(Discount discount) { Guard.Against.Null(discount, nameof(discount)); _discountRep.Update(discount); } } }
cfd0b381606e5f1372451d3603d8ad7871c2a93d
C#
ironman27/TestApp
/TestApp/Classes/String/CompareString.cs
3.6875
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TestApp.Classes.String { class CompareString { public static void Compare() { var s1 = string.Format("{0}{1}", "abc", "cba"); var s2 = "abc" + "cba"; var s3 = "abccba"; Console.WriteLine(s1 == s2); Console.WriteLine((object)s1 == (object)s2); Console.WriteLine(s2 == s3); Console.WriteLine((object)s2 == (object)s3); //если две строки имеют одинаковый набор символов и создаются во время компиляции, то они фактически указывают на один и тот же объект. //строка s1 создается в процессе выполнения, поэтому она будет указывать на другой объект, отличный от s2 и s3. //А так как при сравнении объектов сравниваются ссылки, то поэтому мы получим false, так как s1 и s2 разные объекты. } } }
537be173f42b555657e383e46b25671a5985aaa8
C#
tsjishan/XamarinMovies
/Movies/Utilities/PopulateMovie.cs
2.8125
3
using Android.Content; using Android.Views; using Android.Widget; using System.Json; using System.Threading.Tasks; using Android.Graphics; using FFImageLoading; using FFImageLoading.Views; using System; namespace Movies.Utilities { public static class PopulateMovie { //retrieve movies to movie list public async static Task<LinearLayout> populateMovieList(string uri, LinearLayout movieList, Context context) { string imageUri = "https://image.tmdb.org/t/p/original"; JsonValue jsonValue = await FetchMoviesAsync.FetchMoviesAsyncCall(uri); var results = jsonValue["results"]; //loop through results to add imageviews to LinearLayout - moviewList foreach (JsonObject movieObject in results) { string movieUri = imageUri + movieObject["poster_path"]; string movieId = movieObject["id"].ToString(); addMovieImageToMovielist(context, movieUri, movieId, movieList); } return movieList; } public async static Task populateFavoriteMoviesList(LinearLayout movieList, string pathToDatabase, Context context) { string imageUri = "https://image.tmdb.org/t/p/original"; var movies = await SQLiteDatabase.getData(pathToDatabase); movieList.RemoveAllViews(); foreach (Movie movie in movies) { string movieUri = imageUri + movie.movieImageLink; string movieId = movie.movieID; addMovieImageToMovielist(context, movieUri, movieId, movieList); } } public static void addMovieImageToMovielist(Context context, string movieUri, string movieId, LinearLayout movieList) { //layout parameters LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(350, 450); lp.RightMargin = 10; //define imageView ImageViewAsync imageView = DefineImageView.GetImageView(context, lp); imageView.SetPadding(2, 2, 2, 2); ImageService .LoadUrl(movieUri) .FadeAnimation(true) .DownSample(width: 150) .Into(imageView); //add click event to ImageView #region click event on ImageView imageView.Click += delegate { var detailActivity = new Intent(context, typeof(DetailActivity)); detailActivity.PutExtra("movieId", movieId); context.StartActivity(detailActivity); }; #endregion //add imageView to movieList movieList.AddView(imageView); } } }
d23762cfbf9007307bb9a29a8f7bca8ede3cd560
C#
l1honghui/Dotnet.SampleCode
/src/SampleCode/ThreadSynchronization/AutoResetEventDemo.cs
3.40625
3
using System; using System.Threading; namespace SampleCode.ThreadSynchronization { /// <summary> /// AutoRestEvent /// </summary> public class AutoResetEventDemo { /// <summary> /// /// </summary> private readonly AutoResetEvent _event1 = new AutoResetEvent(true); private readonly AutoResetEvent _event2 = new AutoResetEvent(false); public void StartTest() { Console.WriteLine("Press Enter to create three threads and start them.\r\n" + "The threads wait on AutoResetEvent #1, which was created\r\n" + "in the signaled state, so the first thread is released.\r\n" + "This puts AutoResetEvent #1 into the unsignaled state."); Console.ReadLine(); for (int i = 1; i < 4; i++) { Thread t = new Thread(ThreadProc); t.Name = "Thread_" + i; t.Start(); } Thread.Sleep(250); for (int i = 0; i < 2; i++) { Console.WriteLine("Press Enter to release another thread."); Console.ReadLine(); _event1.Set(); Thread.Sleep(250); } Console.WriteLine("\r\nAll threads are now waiting on AutoResetEvent #2."); for (int i = 0; i < 3; i++) { Console.WriteLine("Press Enter to release a thread."); Console.ReadLine(); _event2.Set(); Thread.Sleep(250); } } private void ThreadProc() { string name = Thread.CurrentThread.Name; Console.WriteLine("{0} waits on AutoResetEvent #1.", name); _event1.WaitOne(); Console.WriteLine("{0} is released from AutoResetEvent #1.", name); Console.WriteLine("{0} waits on AutoResetEvent #2.", name); _event2.WaitOne(); Console.WriteLine("{0} is released from AutoResetEvent #2.", name); Console.WriteLine("{0} ends.", name); } } /* This example produces output similar to the following: Press Enter to create three threads and start them. The threads wait on AutoResetEvent #1, which was created in the signaled state, so the first thread is released. This puts AutoResetEvent #1 into the unsignaled state. Thread_1 waits on AutoResetEvent #1. Thread_1 is released from AutoResetEvent #1. Thread_1 waits on AutoResetEvent #2. Thread_3 waits on AutoResetEvent #1. Thread_2 waits on AutoResetEvent #1. Press Enter to release another thread. Thread_3 is released from AutoResetEvent #1. Thread_3 waits on AutoResetEvent #2. Press Enter to release another thread. Thread_2 is released from AutoResetEvent #1. Thread_2 waits on AutoResetEvent #2. All threads are now waiting on AutoResetEvent #2. Press Enter to release a thread. Thread_2 is released from AutoResetEvent #2. Thread_2 ends. Press Enter to release a thread. Thread_1 is released from AutoResetEvent #2. Thread_1 ends. Press Enter to release a thread. Thread_3 is released from AutoResetEvent #2. Thread_3 ends. */ }
9f792b86c79db34854ddbce061472f435623df17
C#
efclappe/Movie-Finder
/MovieFinderApp/Classes/MovieFinder.cs
3.171875
3
using System; using System.Collections.Generic; using System.Threading.Tasks; using TMDbLib.Client; using TMDbLib.Objects.General; using TMDbLib.Objects.Movies; using TMDbLib.Objects.Search; //Class used for finding movies. Search term is entered by the user and data for all matched movies is returned. //Uses TMDbLib, a C# wrapper for The Movie Database's API public class MovieFinder { //My api key private static string APIKey = "c729b8fb4ce55457e5497c3630933df2"; //Client responsible for searching the database private TMDbClient client; //Current search results, used by front end private MovieSearchResult currentSearch = new MovieSearchResult(0, new List<Movie>(), ""); //A list of movie objects populated after returning search results private List<Movie> movieResults = new List<Movie>(); //Creates singleton instance if null, returns it if not public MovieFinder() { client = new TMDbClient(APIKey); } //Task resposnsible for searching the database using the term entered by the user //Returns SearchMovie objects which are then converted into Movie objects in the following method public async Task searchForMovieByTitle(string searchTerm, string filter) { SearchContainer<SearchMovie> dbSearchResults = this.client.SearchMovieAsync(searchTerm).Result; foreach (SearchMovie movie in dbSearchResults.Results) { Task t = GetMovieByID(movie.Id); await t; } System.Diagnostics.Debug.WriteLine(dbSearchResults.Results.Count); buildMovieList(dbSearchResults.Results.Count, movieResults, filter); } //Gets a particular movie's info based on its ID, populates a Movie object, and adds it to the search results public async Task GetMovieByID(int id) { Movie m = await client.GetMovieAsync(id); movieResults.Add(m); } //Builds the search results used by the front end using a MovieSearchResult object public void buildMovieList(int resultCount, List<Movie> searchResults, string filter) { currentSearch = new MovieSearchResult(resultCount, searchResults, filter); } //Getter for the current search results public MovieSearchResult getCurrentSearchResults() { return currentSearch; } public void setCurrentSearchResults (MovieSearchResult msr) { currentSearch = msr; } }
50ec71d3018ae31e9e47b6b99f4634e7b040d6c9
C#
GameDev-TAY/Ex_8
/Assets/Scripts/2-player/KeyboardMoverByTile.cs
2.71875
3
using System.Collections; using UnityEngine; using UnityEngine.Tilemaps; /** * This component allows the player to move by clicking the arrow keys, * but only if the new position is on an allowed tile. */ public class KeyboardMoverByTile: KeyboardMover { [SerializeField] Tilemap tilemap = null; [SerializeField] AllowedTiles allowedTiles = null; [SerializeField] TileBase mountain = null; [SerializeField] TileBase hill = null; [SerializeField] KeyCode toQuarry = KeyCode.X; private TileBase TileOnPosition(Vector3 worldPosition) { Vector3Int cellPosition = tilemap.WorldToCell(worldPosition); return tilemap.GetTile(cellPosition); } private bool beingHandled = false; private IEnumerator HandleIt() { beingHandled = true; // process pre-yield yield return new WaitForSeconds(2.0f); // process post-yield beingHandled = false; } void Update() { Vector3 newPosition = NewPosition(); TileBase tileOnNewPosition = TileOnPosition(newPosition); if (allowedTiles.Contains(tileOnNewPosition)) { transform.position = newPosition; } else if (Input.GetKey(toQuarry)&& tileOnNewPosition.Equals(mountain) && !beingHandled) { tilemap.SetTile(tilemap.WorldToCell(newPosition), hill); StartCoroutine(HandleIt()); transform.position = newPosition; } else { Debug.Log("You cannot walk on " + tileOnNewPosition + "!"); } } }
88724d8c3e49f6f671a1d0375c38b40f3a08892c
C#
balalaikaproject/AmbulatoryEEG
/Application/Electroencephalograph/gapService.cs
2.515625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.Devices.Bluetooth.GenericAttributeProfile; using Windows.Devices.Enumeration; using Windows.Devices.Enumeration.Pnp; using System.Collections.Generic; using System.Threading.Tasks; using Windows.Storage.Streams; using System.Text; using System.Diagnostics; namespace Electroencephalograph { class gapService { public bool IsInitialised { get; private set; } public GattDeviceService service { get; set; } public GattCharacteristic characteristic { get; set; } private static gapService instance = new gapService(); public gapService() { IsInitialised = true; } public GattDeviceService Service { get { return service; } } public async Task SetAcquisitionRateAsync(UInt16 rate) { var acqusitionCharacteristic = service.GetCharacteristics(new Guid("00002A04-0000-1000-8000-00805f9b34fb"))[0]; DataWriter writer = new DataWriter(); //Endianess of reciever data inverted writer.WriteInt16((Int16) SwapUInt16(rate)); var status = await acqusitionCharacteristic.WriteValueAsync(writer.DetachBuffer()); } /// <summary> /// Configuration to recieved notifications whenever the characteristic value changes /// </summary> private async Task ConfigureServiceForNotificationsAsync() { characteristic.ValueChanged += eegNotification; GattCommunicationStatus status = await characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify); if (status == GattCommunicationStatus.Unreachable) throw new Exception(status.ToString()); } private async void eegNotification(GattCharacteristic sender, GattValueChangedEventArgs args) { var data = new byte[args.CharacteristicValue.Length]; DataReader.FromBuffer(args.CharacteristicValue).ReadBytes(data); System.Diagnostics.Debug.WriteLine(data[1]); } public ushort SwapUInt16(ushort v) { return (ushort)(((v & 0xff) << 8) | ((v >> 8) & 0xff)); } } }
87a88d76f808b70b287571321f86dc37729688da
C#
vansickle/dbexplorer
/commons/Commons.Utils/ArrayUtils.cs
3.203125
3
using System; using System.Collections.Generic; using System.Net; using System.Text; using Commons.Utils.Delegates; namespace Commons.Utils { public static class ArrayUtils { public static bool ArraysEqual(byte[] a1, byte[] a2) { if (a1 == a2) return true; if (a1 == null || a2 == null) return false; if (a1.Length != a2.Length) return false; for (int i = 0; i < a1.Length; i++) { if (a1[i] != a2[i]) return false; } return true; } public static bool ArraysEqual<T>(T[] a1, T[] a2) { if (ReferenceEquals(a1, a2)) return true; if (a1 == null || a2 == null) return false; if (a1.Length != a2.Length) return false; EqualityComparer<T> comparer = EqualityComparer<T>.Default; for (int i = 0; i < a1.Length; i++) { if (!comparer.Equals(a1[i], a2[i])) return false; } return true; } public static string ForEachToString<T>(T[] addresses, FuncDelegate<string,T> func) { var builder = new StringBuilder(); foreach (T address in addresses) { builder.Append(func(address) + ";"); } return builder.ToString(); } } }
b4621647785c667912d98572f92503eecd69e6c8
C#
SyncFall/UndefinedProject
/solution/feltic/Main/TestMain.cs
2.578125
3
using feltic.Language; using feltic.Visual; using System; using System.Diagnostics; using System.Threading; namespace feltic { public class MainTest { public static int Main(string[] args) { SourceList sourceList = new SourceList(); //.Add(SourceText.FromFile("test1.bee-source")); sourceList.Add(SourceText.FromFile("test2.bee-source")); //sourceList.Add(SourceText.FromFile("test3.bee-source")); //sourceList.Add(SourceText.FromFile("test4.bee-source")); //sourceList.Add(SourceText.FromFile("test5.bee-source")); Thread.Sleep(2500); Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); Registry registry = new Registry(); registry.AddSourceList(sourceList); for (int i=0; i<10000; i++) { registry.UpdateSource(sourceList[0]); } stopWatch.Stop(); Console.WriteLine("\nDone in: " + Utils.Format(stopWatch.Elapsed)); Console.ReadLine(); return 1; } } }
f2ff61f45280d747217852f36ff9002f5b7e846b
C#
ttafa/Rock-Paper-Scissors
/RockPaperScissorsGame/Helper/ExtensionHelper.cs
3
3
using RockPaperScissorsGame.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using static RockPaperScissorsGame.Models.GameAction; namespace RockPaperScissorsGame.Helper { public class ExtensionHelper { private PlayerAction GenerateRandomAction() { var rnd = new Random(); return (PlayerAction)rnd.Next(Enum.GetNames(typeof(PlayerAction)).Length); } private Player PlayMatch(Player player1, Player player2) { if (player1.PlayerAction == player2.PlayerAction) return null; else if (player1.PlayerAction == PlayerAction.Rock && player2.PlayerAction == PlayerAction.Scissors) return player1; else if (player1.PlayerAction == PlayerAction.Paper && player2.PlayerAction == PlayerAction.Rock) return player1; else if (player1.PlayerAction == PlayerAction.Scissors && player2.PlayerAction == PlayerAction.Paper) return player1; else if (player1.PlayerAction == PlayerAction.Lizard && player2.PlayerAction == PlayerAction.Spock) return player1; else if (player1.PlayerAction == PlayerAction.Spock && player2.PlayerAction == PlayerAction.Scissors) return player1; else if (player1.PlayerAction == PlayerAction.Scissors && player2.PlayerAction == PlayerAction.Lizard) return player1; else if (player1.PlayerAction == PlayerAction.Lizard && player2.PlayerAction == PlayerAction.Paper) return player1; else if (player1.PlayerAction == PlayerAction.Paper && player2.PlayerAction == PlayerAction.Spock) return player1; else if (player1.PlayerAction == PlayerAction.Spock && player2.PlayerAction == PlayerAction.Rock) return player1; else return player2; } private GameResultBlock FormatResult(List<Game> trackedResults) { GameResultBlock result = new GameResultBlock(); result.NumberOfPlays = trackedResults.Count(); result.MostUsedMove = (from c in trackedResults.SelectMany(x => x.Players).Select(x => x.PlayerAction) group c by c into g orderby g.Count() descending select g.Key).FirstOrDefault(); result.Winner = trackedResults.Max(x => x.Winner); var players = trackedResults.Select(x => x.Players); result.GamesPlayed = trackedResults; return result; } public GameResultBlock RunGame(Player player1, Player player2) { List<Game> tracker = new List<Game>(); player1.PlayerAction = GenerateRandomAction(); Thread.Sleep(10); //pausing random generation player2.PlayerAction = GenerateRandomAction(); Player winner = PlayMatch(player1, player2); Game game = new Game() { GameId = Guid.NewGuid(), Winner = winner, Players = new List<Player>() { player1, player2 } }; tracker.Add(game); if (winner != null) return FormatResult(tracker); //continue playing if a draw while (winner == null) { player1.PlayerAction = GenerateRandomAction(); Thread.Sleep(10); //pausing random generation player2.PlayerAction = GenerateRandomAction(); winner = PlayMatch(player1, player2); tracker.Add(new Game() { GameId = Guid.NewGuid(), Winner = winner, Players = new List<Player>() { player1, player2 } }); } return FormatResult(tracker); } } }
4de170606731a121c2aab0607677dac627369812
C#
HeyGitHub/UtinyRipper
/uTinyRipperCore/Parser/Classes/Texture2D/StreamingInfo.cs
2.65625
3
namespace uTinyRipper.Classes.Textures { public struct StreamingInfo : IAssetReadable { public void Read(AssetReader reader) { Offset = reader.ReadUInt32(); Size = reader.ReadUInt32(); Path = reader.ReadString(); } public void Read(AssetReader reader, string path) { Size = reader.ReadUInt32(); Offset = reader.ReadUInt32(); Path = path; } public uint Offset { get; private set; } public uint Size { get; private set; } public string Path { get; private set; } } }
1990be39470b6cea3286ffba809979e2e0fc2a53
C#
WWWcool/dtf_hack
/Assets/Scripts/PauseSystem.cs
2.765625
3
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PauseSystem : MonoBehaviour { private static PauseSystem instance = null; private bool isPaused = false; private int pausedCount = 0; public static PauseSystem Instance { get { if (instance == null) Debug.LogError("PauseSystem is Null"); return instance; } } public bool IsPaused { get { return isPaused; } } public int PausedCount { get { return pausedCount; } } private void Start() { if (instance == null) instance = this; else if (instance == this) Destroy(gameObject); DontDestroyOnLoad(gameObject); } public void PauseOnOff(bool on) { if (on) { Time.timeScale = 0.0f; isPaused = true; pausedCount++; } else { pausedCount--; if (pausedCount == 0) { Time.timeScale = 1.0f; isPaused = false; } } } public void NeedPause(bool needPause) { if (needPause) { Time.timeScale = 0.0f; isPaused = true; pausedCount++; } else { Time.timeScale = 1.0f; isPaused = false; pausedCount = 0; } } }
11ba78acef830cb4110df6dc52f3bf87e02dbfb6
C#
bharath1097/Fast-Parser-Combinators
/ParserGeneratorLinq/Parsing/Internal/UnsafeParsers/BlittableBulkParser.cs
2.71875
3
using System; using System.Collections.Generic; namespace Strilanc.Parsing.Internal.UnsafeParsers { /// <summary> /// BlittableBulkParser is used to parse arrays of values when memcpy'ing them is valid. /// Using memcpy is possible when the in-memory representation exactly matches the serialized representation. /// BlittableBulkParser uses unsafe code, but is an order of magnitude (or two!) faster than other parsers. /// </summary> internal sealed class BlittableBulkParser<T> : IBulkParser<T> { private readonly UnsafeBlitUtil.UnsafeArrayBlitParser<T> _parser; private readonly int _itemLength; private BlittableBulkParser(IParserInternal<T> itemParser) { if (!itemParser.OptionalConstantSerializedLength.HasValue) throw new ArgumentException(); _itemLength = itemParser.OptionalConstantSerializedLength.Value; _parser = UnsafeBlitUtil.MakeUnsafeArrayBlitParser<T>(); } public static BlittableBulkParser<T> TryMake(IParser<T> itemParser) { if (itemParser == null) throw new ArgumentNullException("itemParser"); var r = itemParser as IParserInternal<T>; if (r == null) return null; if (!r.AreMemoryAndSerializedRepresentationsOfValueGuaranteedToMatch) return null; if (!r.OptionalConstantSerializedLength.HasValue) return null; return new BlittableBulkParser<T>(r); } public ParsedValue<IReadOnlyList<T>> Parse(ArraySegment<byte> data, int count) { var length = count*_itemLength; if (data.Count < length) throw new InvalidOperationException("Fragment"); var value = _parser(data.Array, count, data.Offset, length); return new ParsedValue<IReadOnlyList<T>>(value, length); } public int? OptionalConstantSerializedValueLength { get { return _itemLength; } } } }
9c1dad95f8cbe85bac7fd6564cb2b406d27449fe
C#
Elmah55/IT-Company-Simulation
/Assets/Scripts/Logic/Misc/Defines.cs
2.53125
3
using System.Collections.Generic; using UnityEngine; using ITCompanySimulation.Project; /// <summary> /// This file contains definitons of enum and types used /// in other classes as well as utlities classes for these /// definitions /// </summary> /*Enums*/ namespace ITCompanySimulation.Project { /// <summary> /// This enum defines technologies that can be used in a single /// project /// </summary> public enum ProjectTechnology { C, Cpp, CSharp, JavaScript, PHP, Python, Java } /// <summary> /// This enum defines different sprint stages. Stages change /// as sprint progresses. /// </summary> public enum SprintStage { Planning, Developing, Retrospective } } /// <summary> /// This enum defines index of scene (as defined in /// build settings) /// </summary> public enum SceneIndex { Base = 0, Menu = 1, Game = 2 } /// <summary> /// Codes of events used for PhotonNetwork.RaiseEvent /// </summary> public enum RaiseEventCode : byte { RoomLobbyPlayerStateChanged, //Invoked when client received all data needed before starting simulation. ClientDataTransferCompleted } /// <summary> /// Possible states for player in /// room lobby /// </summary> public enum RoomLobbyPlayerState { Ready, NotReady } public enum SimulationFinishReason { PlayerCompanyReachedTargetBalance, PlayerCompanyReachedMinimalBalance, OnePlayerInRoom, ForcedByMasterClient, Disconnected } public enum SimulationEventNotificationPriority { Normal, High } namespace ITCompanySimulation.Character { /// <summary> /// This class defines possible movement of character. Animation names /// should match names in this enum. /// </summary> public enum CharacterMovement { WalkS, WalkSW, WalkSE, WalkW, WalkE, WalkN, WalkNW, WalkNE, StandS, StandSW, StandSE, StandW, StandE, StandN, StandNE, StandNW } public enum WorkerAttribute { Salary, ExpierienceTime, ProjectTechnology } /// <summary> /// Reason of worker not being able to /// work /// </summary> public enum WorkerAbsenceReason { Sickness, Holiday } public enum Gender { Male, Female } } namespace ITCompanySimulation.Event { public enum DataTransferSource { WorkersMarket, SimulationManager, //Used for both normal and master client ProjectsMarket, GameTime } } namespace ITCompanySimulation.Multiplayer { /// <summary> /// This enum defines keys to access photon player custom properties /// </summary> public enum PlayerCustomPropertiesKey { RoomLobbyPlayerState } /// <summary> /// This enum defines keys to access room custom properties /// </summary> public enum RoomCustomPropertiesKey { SettingsOfSimulationMinimalBalance, SettingsOfSimulationInitialBalance, SettingsOfSimulationTargetBalance } } /*Classes*/ namespace ITCompanySimulation.Utilities { /// <summary> /// This class maps enums to strings. /// </summary> public static class EnumToString { /// <summary> /// Converts ProjectTechnology enum to string. /// </summary> /// <param name="enumInput">Enum to be converted to string.</param> public static string GetString(ProjectTechnology enumInput) { return ProjectTechnologiesStrings[enumInput]; } /// <summary> /// Converts FullScreenMode enum to string. /// </summary> /// <param name="enumInput">Enum to be converted to string.</param> public static string GetString(FullScreenMode enumInput) { return FullScreenModeStrings[enumInput]; } private static IReadOnlyDictionary<ProjectTechnology, string> ProjectTechnologiesStrings = new Dictionary<ProjectTechnology, string>() { { ProjectTechnology.C,"C" }, { ProjectTechnology.Cpp,"C++" }, { ProjectTechnology.CSharp,"C#" }, { ProjectTechnology.JavaScript,"JavaScript" }, { ProjectTechnology.PHP,"PHP" }, { ProjectTechnology.Python,"Python" }, { ProjectTechnology.Java,"Java" } }; private static IReadOnlyDictionary<FullScreenMode, string> FullScreenModeStrings = new Dictionary<FullScreenMode, string>() { { FullScreenMode.ExclusiveFullScreen,"Exclusive fullscreen" }, { FullScreenMode.FullScreenWindow,"Fullscreen window" }, { FullScreenMode.MaximizedWindow,"Maximized window" }, { FullScreenMode.Windowed,"Windowed" } }; } } namespace ITCompanySimulation.Multiplayer { public static class NetworkingData { /// <summary> /// Bytes codes used for sending custom type data between clients /// </summary> public const byte SHARED_WORKER_BYTE_CODE = 0; public const byte LOCAL_WORKER_BYTE_CODE = 1; public const byte PROJECT_BYTE_CODE = 2; public const byte SIMULATION_SETTINGS_BYTE_CODE = 3; public const byte PLAYER_DATA_BYTE_CODE = 4; public const byte SIMULATION_STATS_BYTE_CODE = 5; } public struct ChatMessage { public string Sender { get; private set; } public string Message { get; private set; } public ChatMessage(string sender, string message) { this.Sender = sender; this.Message = message; } public override string ToString() { return string.Format("{0}: {1}", Sender, Message); } } } /*Delegates*/ namespace ITCompanySimulation.Project { public delegate void SharedProjectAction(SharedProject proj); public delegate void LocalProjectAction(LocalProject proj); public delegate void ScrumAtion(Scrum scrumObj); } namespace ITCompanySimulation.UI { public delegate void ParentChangeAction(GameObject obj, GameObject newParent); } namespace ITCompanySimulation.Character { public delegate void LocalWorkerAction(LocalWorker worker); public delegate void SharedWorkerAction(SharedWorker worker); /// <summary> /// Delegate for worker ability update action. /// </summary> /// <param name="worker">Worker whose ability was updated.</param> /// <param name="workerAbility">Ability type that was updated.</param> /// <param name="abilityValueDelta">Amount by which ability was changed.</param> public delegate void WorkerAbilityAction(SharedWorker worker, ProjectTechnology workerAbility, float abilityValueDelta); public delegate void MultiplayerWorkerAction(SharedWorker worker, PhotonPlayer player); } namespace ITCompanySimulation.Multiplayer { /// <summary> /// Delagate for event fired when photon chat message from other client is received /// </summary> /// <param name="senderNickname">Nickname of player that sent message</param> /// <param name="message">Contains message data</param> public delegate void PhotonChatMessageAction(ChatMessage message); public delegate void PhotonPlayerAction(PhotonPlayer player); } namespace ITCompanySimulation.Core { public delegate void SimulationFinishAction(int winnerPhotonPlayerID, SimulationFinishReason finishReason); } namespace ITCompanySimulation.Company { /// <summary> /// Delegate used when company balance is changed /// </summary> /// <param name="newBalance">New comapny's balance</param> /// <param name="balanceDelta">Difference between current and previous balance</param> public delegate void BalanceChangeAction(int newBalance, int balanceDelta); }
4aa74453b28c2556b27812a8038d500143494320
C#
melma/MikuMikuWorld
/MikuMikuWorldLib/Physics/Bullet.cs
2.5625
3
using BulletSharp; using MikuMikuWorld.GameComponents; using OpenTK; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MikuMikuWorld.Physics { public static class Bullet { public static Vector3 Gravity { get { return world.Gravity; } set { world.Gravity = value; } } private static DiscreteDynamicsWorld world; private static CollisionDispatcher dispatcher; private static DbvtBroadphase broadphase; private static ConstraintSolver solver; private static CollisionConfiguration collisionConf; private static OverlapFilterCallback filterCB; private static List<CollisionShape> collisionShapes = new List<CollisionShape>(); private static List<CollisionObject> collisionObjects = new List<CollisionObject>(); private static List<RigidBody> rigidBodies = new List<RigidBody>(); private static bool initialized = false; internal static void Init() { collisionConf = new DefaultCollisionConfiguration(); dispatcher = new CollisionDispatcher(collisionConf); broadphase = new DbvtBroadphase(); solver = new SequentialImpulseConstraintSolver(); world = new DiscreteDynamicsWorld(dispatcher, broadphase, solver, collisionConf); //filterCB = new CollisionFilterCallback(); //world.PairCache.SetOverlapFilterCallback(filterCB); initialized = true; } #region Create Shape /// <summary> /// スフィア物理形状を作成 /// </summary> /// <param name="radius">半径</param> /// <returns></returns> internal static Shapes.SphereShape CreateSphereShape(float radius) { var shape = new Shapes.SphereShape(radius); collisionShapes.Add(shape); return shape; } /// <summary> /// ボックス物理形状を作成 /// </summary> /// <param name="halfExtents"></param> /// <returns></returns> internal static Shapes.BoxShape CreateBoxShape(OpenTK.Vector3 halfExtents) { var shape = new Shapes.BoxShape(halfExtents); collisionShapes.Add(shape); return shape; } /// <summary> /// カプセル物理形状を作成 /// </summary> /// <param name="radius">半径</param> /// <param name="height">高さ</param> /// <returns></returns> internal static Shapes.CapsuleShape CreateCapsuleShape(float radius, float height) { var shape = new Shapes.CapsuleShape(radius, height); collisionShapes.Add(shape); return shape; } /// <summary> /// 円柱物理形状を作成 /// </summary> /// <param name="halfExtents"></param> /// <returns></returns> internal static Shapes.CylinderShape CreateCylinderShape(OpenTK.Vector3 halfExtents) { var shape = new Shapes.CylinderShape(halfExtents); collisionShapes.Add(shape); return shape; } /// <summary> /// 三角錐物理形状を作成 /// </summary> /// <param name="radius">半径</param> /// <param name="height">高さ</param> /// <returns></returns> internal static Shapes.ConeShape CreateConeShape(float radius, float height) { var shape = new Shapes.ConeShape(radius, height); collisionShapes.Add(shape); return shape; } /// <summary> /// 無限平面物理形状を作成 /// </summary> /// <param name="normal">平面法線</param> /// <param name="constant"></param> /// <returns></returns> internal static Shapes.StaticPlaneShape CreateStaticPlaneShape(OpenTK.Vector3 normal, float constant = 0.0f) { var shape = new Shapes.StaticPlaneShape(normal, constant); collisionShapes.Add(shape); return shape; } /// <summary> /// メッシュ物理形状を作成 /// </summary> /// <param name="vertices">頂点配列</param> /// <param name="indices">インデックス配列</param> /// <returns></returns> internal static Shapes.MeshShape CreateMeshShape(OpenTK.Vector3[] vertices, int[] indices) { var shape = new Shapes.MeshShape(vertices, indices); collisionShapes.Add(shape); return shape; } /// <summary> /// 複合物理形状を作成 /// </summary> /// <param name="shapes">物理形状の配列</param> /// <param name="transforms">物理形状のローカル姿勢行列</param> /// <returns></returns> internal static Shapes.CompoundShape CreateCompoundShape(CollisionShape[] shapes, OpenTK.Matrix4[] transforms) { var shape = new Shapes.CompoundShape(shapes, transforms); collisionShapes.Add(shape); return shape; } #endregion internal static CollisionObject CreateCollisionObject( CollisionShape shape, CollisionFilterGroups group = CollisionFilterGroups.DefaultFilter, CollisionFilterGroups mask = CollisionFilterGroups.AllFilter) { if (shape == null) return null; var o = new CollisionObject(shape); collisionObjects.Add(o); world.AddCollisionObject(o.BulletCollisionObject, group, mask); return o; } internal static List<Collision> ContactTest(CollisionObject col) { var cb = new ContactResultCallback() { colObj = col, gameObject = ((GameComponent)col.tag).GameObject, CollisionFilterGroup = col.CollisionFilterGroup, CollisionFilterMask = col.CollisionFilterMask, }; world.ContactTest(col.BulletCollisionObject, cb); return cb.Collides; } internal static bool ContactPairTest(CollisionObject colA, CollisionObject colB) { var cb = new ContactResultCallback(); world.ContactPairTest(colA.BulletCollisionObject, colB.BulletCollisionObject, cb); return cb.Collides.Count > 0; } public static List<RayTestResult> RayTest(OpenTK.Vector3 from, OpenTK.Vector3 to, params GameObject[] ignoreObjects) { var cb = new RayResultCB(ignoreObjects); world.RayTest(from, to, cb); var res = cb.Results; foreach (var r in res) { r.Position = Vector3.Lerp(from, to, r.Rate); } res.Sort((r1, r2) => r1.Rate - r2.Rate < 0.0f ? -1 : 1); return res; } internal static RigidBody CreateRigidBody(float mass, OpenTK.Matrix4 transform, CollisionShape shape, CollisionFilterGroups group = CollisionFilterGroups.DefaultFilter, CollisionFilterGroups mask = CollisionFilterGroups.AllFilter) { if (shape == null) { shape = CreateBoxShape(Vector3.Zero); } RigidBody body = new RigidBody(shape, mass, transform); world.AddRigidBody(body.BulletRigidBody, group, mask); rigidBodies.Add(body); return body; } internal static void Update(float deltaTime) { world.StepSimulation(deltaTime, 100); world.PerformDiscreteCollisionDetection(); for (var i = 0; i < world.Dispatcher.NumManifolds; i++) { var mani = world.Dispatcher.GetManifoldByIndexInternal(i); mani.RefreshContactPoints(mani.Body0.WorldTransform, mani.Body1.WorldTransform); var colA = (mani.Body0.UserObject as CollisionObject).tag as PhysicalGameComponent; var colB = (mani.Body1.UserObject as CollisionObject).tag as PhysicalGameComponent; if (colA == colB) continue; var mps = new ManifoldPoint[mani.NumContacts]; for (int j = 0; j < mani.NumContacts; j++) { mps[j] = mani.GetContactPoint(j); } colA.OnCollision(colB.GameObject, mps); colB.OnCollision(colA.GameObject, mps); } } internal static void AddCollisionObject(CollisionObject col) { if (!col.IsInWorld) world.AddCollisionObject(col.BulletCollisionObject, col.CollisionFilterGroup, col.CollisionFilterMask); } internal static void RemoveCollisionObject(CollisionObject col) { if (col.IsInWorld) world.RemoveCollisionObject(col.BulletCollisionObject); } internal static void AddRigidBody(RigidBody rigid) { if (!rigid.BulletRigidBody.IsInWorld) world.AddRigidBody(rigid.BulletRigidBody); } internal static void RemoveRigidBody(RigidBody rigid) { if (rigid.BulletRigidBody.IsInWorld) world.RemoveRigidBody(rigid.BulletRigidBody); } internal static void DestroyShape(CollisionShape shape) { collisionShapes.Remove(shape); shape.Destroy(); } internal static void DestroyCollisionObject(CollisionObject col) { if (collisionObjects.Remove(col)) { world.RemoveCollisionObject(col.BulletCollisionObject); } col.Destroy(); } internal static void DestroyRigidBody(RigidBody rigid) { if (rigidBodies.Remove(rigid)) { world.RemoveRigidBody(rigid.BulletRigidBody); } rigid.Destroy(); } internal static void Destroy() { if (!initialized) return; foreach (CollisionShape shape in collisionShapes) shape.Destroy(); collisionShapes.Clear(); // 衝突オブジェクトの解放 foreach (CollisionObject obj in collisionObjects) { world.RemoveCollisionObject(obj.BulletCollisionObject); obj.Destroy(); } collisionObjects.Clear(); // 剛体オブジェクトの解放 foreach (RigidBody rigid in rigidBodies) { world.RemoveRigidBody(rigid.BulletRigidBody); rigid.Destroy(); } rigidBodies.Clear(); //filterCB.Dispose(); dispatcher.Dispose(); collisionConf.Dispose(); solver.Dispose(); broadphase.Dispose(); //world.Dispose(); initialized = false; } } }
85720d49cc8f2fbf13364978f7ab02faabb98123
C#
zxyao145/LeetCode
/C#/Problems/Problem18.cs
3.28125
3
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Tracing; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LeetCode.Problems { /// <summary> /// 最长公共前缀 /// </summary> class Problem18 { public static void MainFunc() { int target = 2; var nums = new int[] { 2,1,0,-1 }; var result = FourSum(nums, target); var resultStr = string.Join("\r\n", result.Select(e => string.Join(",", e))); Console.WriteLine(string.Join(",", resultStr)); } public static IList<IList<int>> FourSum(int[] nums, int target) { IList<IList<int>> resultList = new List<IList<int>>(); int length = nums.Length; if (length < 4) { return resultList; } var maxIndex = length - 1; Array.Sort(nums); var lastVal = nums[maxIndex]; for (int i = 0; i < length - 3; i++) { var valI = nums[i]; if (i > 0 && valI == nums[i-1]) { continue; } var startJ = i + 1; for (int j = startJ; j < length - 2;j++ ) { var valJ = nums[j]; if (startJ != j && valJ == nums[j - 1]) { continue; } var startK = j + 1; for (int k = startK; k < length - 1; k++) { var valK = nums[k]; if (startK != k && valK == nums[k - 1]) { continue; } var remainderVal = target - valI - valJ - valK; var l = maxIndex; if (lastVal < remainderVal) { continue; } while (l > k) { var valL = nums[l]; if (valL == remainderVal) { resultList.Add(new List<int>() { valI,valJ, valK,valL }); break; } l--; } } } } return resultList; } } }
f3469d6789612e453bc121dd6efcf3f3f8dd7826
C#
ykpgrr/Object_ORIENTED_CSHARP
/Lesson-Codes/9.hafta/Point, Line, Square/ConsoleApplication1/Line.cs
3.515625
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { class Line { public point Point1 { get; set; } public point Point2 { get; set; } public Line(point point1, point point2) { Point1 = point1; Point2 = point2; } public double CalculateLenght() { double x = Math.Abs(Point1.Latitude - Point2.Latitude); double y = Math.Abs(Point1.longtitude - Point2.longtitude); return Math.Sqrt(x * x + y * y); } public bool IsLine() { if (Point1.isequal(Point2)) return false; return true; } } }
eed745c1e59cdd0c34aa9b270f02ff0fafa7d63d
C#
RuairiOKeefe/Fredrick
/Fredrick/src/Drawing/DrawManager.cs
2.65625
3
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Fredrick.src { public class DrawManager { public struct DrawInfo { SpriteSortMode SortMode; BlendState BlendState; SamplerState SamplerState; DepthStencilState stencilState; RasterizerState RasterizerState; } private Dictionary<string, Effect> m_shaders; private Dictionary<string, List<Component>> m_drawComponents;//Key is shaderId private Dictionary<string, List<Component>> m_batchComponents;//Key is Component Id, Components are grouped by this and the render info for the first is used public DrawManager() { m_shaders = new Dictionary<string, Effect>(); m_drawComponents = new Dictionary<string, List<Component>>(); m_batchComponents = new Dictionary<string, List<Component>>(); m_shaders.Add("", null); } public void SetLights(Effect shader, Lighting lighting) { Light[] fixedLights = new Light[16]; lighting.GetFixedLights(out fixedLights); if (shader != null) { shader.Parameters["position"].SetValue(LightingUtils.GetPositions(fixedLights)); shader.Parameters["colour"].SetValue(LightingUtils.GetColours(fixedLights)); } } public void SetWorldUniforms(Effect shader, Matrix wvp) { if (shader != null) { //This can be identity because this is a 2d space shader.Parameters["world"].SetValue(Matrix.Identity); shader.Parameters["wvp"].SetValue(wvp); } } public void Load(ContentManager content) { foreach (KeyValuePair<string, List<Component>> shaderComponentPair in m_drawComponents) { string shaderId = shaderComponentPair.Key; if (!m_shaders.ContainsKey(shaderId)) { Effect shader = content.Load<Effect>(shaderId); m_shaders.Add(shaderId, shader); } } } public void AddComponents(Entity entity) { foreach (Component component in entity.Components) { if (component.IsDrawn) { AddComponent(component); } } } /// <summary> /// Adds a compoment to the m_drawComponents dictionary. /// If the shaderId already exists in the dictionary, the component is added to the existing list, otherewise a new key is created. /// NOTE: This method should never be called after a Load() /// </summary> /// <param name="component"></param> public void AddComponent(Component component) { if (component.DrawBatched) { string id = component.GetType().ToString() + component.Id; if (m_batchComponents.ContainsKey(id)) { m_batchComponents[id].Add(component); } else { m_batchComponents.Add(id, new List<Component> { component }); } } else { string shaderId = component.ShaderId; if (m_drawComponents.ContainsKey(shaderId)) { m_drawComponents[shaderId].Add(component); } else { m_drawComponents.Add(shaderId, new List<Component> { component }); } } } public void RemoveComponent(Component component) { } public void DrawComponents(SpriteBatch spriteBatch, Matrix transformationMatrix, Matrix wvp, Lighting lighting) { foreach (KeyValuePair<string, List<Component>> shaderComponentPair in m_drawComponents) { List<Component> components = shaderComponentPair.Value; Effect shader = m_shaders[shaderComponentPair.Key]; // shader should be replaced with a class that can hold global uniforms ect SetWorldUniforms(shader, wvp); SetLights(shader, lighting); foreach (Component component in components) { component.Draw(spriteBatch, shader, transformationMatrix); } } } public void DrawBatch(SpriteBatch spriteBatch, Matrix transformationMatrix, Lighting lighting) { } public void DrawParticles(SpriteBatch spriteBatch, Matrix transformationMatrix, Matrix wvp, Lighting lighting) { foreach (Effect shader in m_shaders.Values) { SetWorldUniforms(shader, wvp); SetLights(shader, lighting); spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend, SamplerState.PointClamp, null, null, shader, transformationMatrix); ParticleBuffer.Instance.Draw(spriteBatch, shader); spriteBatch.End(); } } public void DrawProjectiles(SpriteBatch spriteBatch, Matrix transformationMatrix, Matrix wvp, Lighting lighting) { foreach (Effect shader in m_shaders.Values) { SetWorldUniforms(shader, wvp); SetLights(shader, lighting); ProjectileBuffer.Instance.Draw(spriteBatch, shader, transformationMatrix); } } public void Draw(SpriteBatch spriteBatch, Matrix transformationMatrix, Matrix wvp, Lighting lighting) { DrawComponents(spriteBatch, transformationMatrix, wvp, lighting); DrawBatch(spriteBatch, transformationMatrix, lighting); DrawParticles(spriteBatch, transformationMatrix, wvp, lighting); DrawProjectiles(spriteBatch, transformationMatrix, wvp, lighting); } } }
55ace58990e8d22c82396541b27b00b9ab6bb4e3
C#
KHCmaster/PPD
/Win/PPDEditor/PPDEditor/PPDSheet.cs
2.53125
3
using System; using System.Drawing; using System.Collections.Generic; using System.Text; using SlimDX; using SlimDX.Direct3D9; using PPDFramework; using PPDEditor.Forms; namespace PPDEditor { public class PPDSheet { public enum Direction { Up = 0, Left = 1, Down = 2, Right = 3 } public event EventHandler DisplayDataChanged; string name; CustomPoint recstart = new CustomPoint(-1, -1); CustomPoint recend = new CustomPoint(-1, -1); private float bpm = 100; private float bpmstart = 0; private int defaultinterval = 240; private int deatmodeindex = 0; int[] focusedmark = new int[] { -1, -1 }; SortedList<float, Mark>[] data; RingBuffer<SortedList<float, Mark>[]> storeddata; const int buttonnum = 10; public PPDSheet() { storeddata = new RingBuffer<SortedList<float, Mark>[]>(200); data = new SortedList<float, Mark>[buttonnum]; for (int i = 0; i < buttonnum; i++) { data[i] = new SortedList<float, Mark>(); } PreserveData(); } public float BPM { get { return bpm; } set { bpm = value; if (DisplayDataChanged != null) { DisplayDataChanged.Invoke(this, EventArgs.Empty); } } } public float BPMStart { get { return bpmstart; } set { bpmstart = value; if (DisplayDataChanged != null) { DisplayDataChanged.Invoke(this, EventArgs.Empty); } } } public string DisplayName { get { return name; } set { name = value; } } public int DisplayWidth { get { return defaultinterval; } set { defaultinterval = value; if (DisplayDataChanged != null) { DisplayDataChanged.Invoke(this, EventArgs.Empty); } } } public int BeatModeIndex { get { return deatmodeindex; } set { deatmodeindex = value; if (DisplayDataChanged != null) { DisplayDataChanged.Invoke(this, EventArgs.Empty); } } } public CustomPoint RecStart { get { return recstart; } set { recstart = value; } } public CustomPoint RecEnd { get { return recend; } set { recend = value; } } public bool AreaSelectionEnabled { get { return recstart.X != recend.X; } } public int[] FocusedMark { get { return focusedmark; } set { focusedmark = value; } } public SortedList<float, Mark>[] Data { get { return data; } set { data = value; } } public void PreserveData() { SortedList<float, Mark>[] temp = new SortedList<float, Mark>[10]; for (int i = 0; i < 10; i++) { temp[i] = new SortedList<float, Mark>(); for (int j = 0; j < data[i].Count; j++) { ExMark exmk = data[i].Values[j] as ExMark; if (exmk == null) { temp[i].Add(data[i].Values[j].Time, data[i].Values[j].Clone()); } else { temp[i].Add(data[i].Values[j].Time, exmk.ExClone()); } } } storeddata.add(temp); } public bool Undo() { if (storeddata.canundo()) { data = copydata(storeddata.getprevious()); focusedmark[0] = -1; focusedmark[1] = -1; return true; } return false; } public bool Redo() { if (storeddata.canredo()) { data = copydata(storeddata.getnext()); focusedmark[0] = -1; focusedmark[1] = -1; return true; } return false; } private SortedList<float, Mark>[] copydata(SortedList<float, Mark>[] dat) { SortedList<float, Mark>[] temp = new SortedList<float, Mark>[10]; for (int i = 0; i < 10; i++) { temp[i] = new SortedList<float, Mark>(); for (int j = 0; j < dat[i].Count; j++) { ExMark exmk = dat[i].Values[j] as ExMark; if (exmk == null) { temp[i].Add(dat[i].Values[j].Time, dat[i].Values[j].Clone()); } else { temp[i].Add(dat[i].Values[j].Time, exmk.ExClone()); } } } return temp; } public Mark[] GetAreaData() { if (recstart.X == -1 || recstart.Y == -1) { return new Mark[0]; } float width = Math.Abs(recstart.X - recend.X); int starty = (recstart.Y <= recend.Y ? recstart.Y : recend.Y); int height = Math.Abs(recstart.Y - recend.Y) + 1; float starttime = (recstart.X <= recend.X ? recstart.X : recend.X); float endtime = starttime + width; int num = 0; int[] startnum = new int[height]; for (int i = 0; i < height; i++) { startnum[i] = -1; } for (int i = starty; i < starty + height; i++) { bool first = true; for (int j = 0; j < data[i].Count; j++) { if (data[i].Keys[j] < starttime) continue; if (data[i].Keys[j] > endtime) break; if (first) { first = false; startnum[i - starty] = j; } num++; } } Mark[] mks = new Mark[num]; int iter = 0; while (true) { float minimumtime = float.MaxValue; int minimumnum = -1; for (int i = starty; i < starty + height; i++) { if (startnum[i - starty] == -1 || startnum[i - starty] >= data[i].Count) { continue; } if (data[i].Keys[startnum[i - starty]] > endtime) { startnum[i - starty] = -1; continue; } if (minimumtime > data[i].Keys[startnum[i - starty]]) { minimumnum = i; minimumtime = data[i].Keys[startnum[i - starty]]; continue; } } if (minimumnum == -1) { break; } else { mks[iter] = data[minimumnum].Values[startnum[minimumnum - starty]]; iter++; startnum[minimumnum - starty]++; } } return mks; } public void ShiftSelectedMarkTime(float dt) { Mark mk = null; if (data[focusedmark[0]].TryGetValue(data[focusedmark[0]].Keys[focusedmark[1]], out mk)) { data[focusedmark[0]].RemoveAt(focusedmark[1]); ExMark exmk = mk as ExMark; if (exmk != null) { exmk.EndTime += dt - mk.Time; } mk.Time = dt; while (data[focusedmark[0]].ContainsKey(mk.Time)) { mk.Time -= 0.01f; } data[focusedmark[0]].Add(mk.Time, mk); focusedmark[1] = data[focusedmark[0]].IndexOfKey(mk.Time); } } public void AddMark(float time, int num) { if (!data[num].ContainsKey(time) && !checklongmark(num, time)) { data[num].Add(time, CreateMark(400, 225, num, time, 0)); focusedmark[0] = num; focusedmark[1] = data[num].IndexOfKey(time); } } public void AddMark(float time, float x, float y, float rotation, int num) { if (num >= 0 && num < 10) { if (!data[num].ContainsKey(time) && !checklongmark(num, time)) { data[num].Add(time, CreateMark(x, y, num, time, rotation)); focusedmark[0] = num; focusedmark[1] = data[num].IndexOfKey(time); } } } public void AddExMark(float time, float endtime, int num) { if (!data[num].ContainsKey(time) && !checklongmark(num, time)) { data[num].Add(time, CreateExMark(400, 225, num, time, endtime, 0)); focusedmark[0] = num; focusedmark[1] = data[num].IndexOfKey(time); } } public void AddExMark(float time, float endtime, float x, float y, float rotation, int num) { if (!data[num].ContainsKey(time) && !checklongmark(num, time)) { data[num].Add(time, CreateExMark(x, y, num, time, endtime, rotation)); focusedmark[0] = num; focusedmark[1] = data[num].IndexOfKey(time); } } public void Swap(int first, int second) { if (first == second) return; SortedList<float, Mark> swap = new SortedList<float, Mark>(data[first].Count); foreach (Mark mk in this.data[first].Values) { mk.Type = (byte)second; swap.Add(mk.Time, mk); } this.data[first].Clear(); foreach (Mark mk in this.data[second].Values) { mk.Type = (byte)first; this.data[first].Add(mk.Time, mk); } this.data[second].Clear(); foreach (Mark mk in swap.Values) { this.data[second].Add(mk.Time, mk); } } public bool[] UpdateMark(float time, float speedscale, EventManager em) { bool[] ret = new bool[buttonnum]; if (data != null) { for (int i = 0; i < 10; i++) { foreach (Mark mk in data[i].Values) { ExMark exmk = mk as ExMark; EventData.DisplayState DState; bool AC; em.GetCorrectInfo(mk.Time, out DState, out AC); if (exmk != null) { ret[i] |= (exmk.ExUpdate(em.GetCorrectTime(time, mk.Time), speedscale * bpm, DState, AC, em.ReleaseSound(mk.Type)) == 1); } else { ret[i] |= (mk.Update(em.GetCorrectTime(time, mk.Time), speedscale * bpm, DState, AC) == 1); } } } } return ret; } public void DrawMark() { if (data != null) { int miny = -1, maxy = -1; float minx = -1, maxx = -1; if (AreaSelectionEnabled && recstart.Y != -1 && recend.Y != -1) { miny = Math.Min(recstart.Y, recend.Y); maxy = Math.Max(recstart.Y, recend.Y); minx = Math.Min(recstart.X, recend.X); maxx = Math.Max(recstart.X, recend.X); } for (int i = 0; i < 10; i++) { bool isin = miny <= i && i <= maxy; foreach (Mark mk in data[i].Values) { if (mk.Hidden) { if (isin && minx <= mk.Time && mk.Time <= maxx) { mk.DrawOnlyMark(); } } else { ExMark exmk = mk as ExMark; if (exmk != null) { exmk.ExDraw(); } else { mk.Draw(); } } } } } } public Mark SelectedMark { get { Mark ret = null; if (focusedmark[0] >= 0 && focusedmark[0] < buttonnum) { if (focusedmark[1] >= data[focusedmark[0]].Count) { return ret; } if (data[focusedmark[0]].TryGetValue(data[focusedmark[0]].Keys[focusedmark[1]], out ret)) { return ret; } } return ret; } } public int MoveMark(Point pos, int mode, bool shiftKey) { //0...pos //1...angle if (focusedmark[0] >= 0 && focusedmark[0] < 10) { Mark mk = null; if (data[focusedmark[0]].TryGetValue(data[focusedmark[0]].Keys[focusedmark[1]], out mk)) { if (mode == 0) { if (pos.X <= 0) pos.X = 0; if (pos.X >= 800) pos.X = 800; if (pos.Y <= 0) pos.Y = 0; if (pos.Y >= 450) pos.Y = 450; mk.Position = new Vector2(pos.X, pos.Y); //mk.Update((float)currenttime, bpm); return 0; } else if (mode == 1) { if (PPDStaticSetting.RestrictAngle == 0 || !shiftKey) { float length = (float)Math.Sqrt(Math.Pow(Math.Abs(pos.X - mk.Position.X), 2) + Math.Pow(Math.Abs(pos.Y - mk.Position.Y), 2)); float d = (float)Math.Acos((pos.X - mk.Position.X) / length); if (pos.Y > mk.Position.Y) { d = (float)(Math.PI * 2 - d); } mk.Rotation = d; } else { Vector2 vec = new Vector2(pos.X - mk.Position.X, pos.Y - mk.Position.Y); float length = vec.Length(); int anglebase = 0; if (vec.X >= 0) { if (vec.Y >= 0) { anglebase = 0; } else { anglebase = 270; } } else { if (vec.Y >= 0) { anglebase = 90; } else { anglebase = 180; } } List<Vector2> poses = new List<Vector2>(); int angleSplit = 90 / PPDStaticSetting.RestrictAngle; for (int i = 0; i <= angleSplit; i++) { double angle = Math.PI * ((anglebase + 90 * ((double)i / angleSplit))) / 180; poses.Add(new Vector2((float)(length * Math.Cos(angle)), (float)(length * Math.Sin(angle)))); } int nearestindex = -1; float nearestlength = float.MaxValue; int index = 0; foreach (Vector2 vector in poses) { Vector2 p = new Vector2(vector.X - pos.X, vector.Y - pos.Y) + mk.Position; length = p.Length(); if (length < nearestlength) { nearestlength = length; nearestindex = index; } index++; } Console.WriteLine(nearestindex); if (nearestindex >= 0) { float d = (float)(Math.PI * ((anglebase + 90 * ((float)nearestindex / angleSplit))) / 180); mk.Rotation = (float)(Math.PI * 2 - d); } } //mk.Update((float)currenttime, bpm); return 1; } } } return -1; } public Mark[] GetSortedData() { int num = 0; for (int i = 0; i < 10; i++) { num += data[i].Count; } Mark[] ret = new Mark[num]; int retiter = 0; int[] iters = new int[10]; while (true) { int minimum = -1; float minimumtime = float.MaxValue; for (int i = 0; i < 10; i++) { if (iters[i] < data[i].Count) { if (minimumtime >= data[i].Keys[iters[i]]) { minimum = i; minimumtime = data[i].Keys[iters[i]]; } } } if (minimum == -1) { break; } else { Mark mk = data[minimum].Values[iters[minimum]]; ret[retiter] = mk; retiter++; iters[minimum]++; } } return ret; } public void MoveLine(int num, float dt) { if (num >= 0 && num < 10) { SortedList<float, Mark> tempdat = new SortedList<float, Mark>(data[num].Count); foreach (Mark mk in data[num].Values) { ExMark exmk = mk as ExMark; if (exmk != null) { exmk.EndTime += dt; } mk.Time += dt; tempdat.Add(mk.Time, mk); } data[num] = tempdat; } else if (num == int.MaxValue) { for (int i = 0; i < 10; i++) { SortedList<float, Mark> tempdat = new SortedList<float, Mark>(data[i].Count); foreach (Mark mk in data[i].Values) { ExMark exmk = mk as ExMark; if (exmk != null) { exmk.EndTime += dt; } mk.Time += dt; tempdat.Add(mk.Time, mk); } data[i] = tempdat; } } } public bool SetData(float[] xs, float[] ys, float[] angles, bool reverse, int mode, bool withangle) { if (mode == 0) { if (focusedmark[0] == -1) return false; int iter = focusedmark[1]; if (!reverse) { for (int i = 0; i < xs.Length; i++) { Mark mk = data[focusedmark[0]].Values[iter]; mk.Position = new Vector2(xs[i], ys[i]); if (withangle) { mk.Rotation = angles[i]; } iter++; if (iter >= data[focusedmark[0]].Count) break; } } else { for (int i = 0; i < xs.Length; i++) { Mark mk = data[focusedmark[0]].Values[iter]; mk.Position = new Vector2(xs[i], ys[i]); if (withangle) { mk.Rotation = angles[i]; } iter--; if (iter < 0) break; } } return true; } else if (mode == 1) { Mark[] mks = GetAreaData(); int iter; if (!reverse) { iter = 0; for (int i = 0; i < xs.Length; i++) { mks[iter].Position = new Vector2(xs[i], ys[i]); if (withangle) { mks[iter].Rotation = angles[i]; } iter++; if (iter >= mks.Length) break; } } else { iter = mks.Length - 1; for (int i = 0; i < xs.Length; i++) { mks[iter].Position = new Vector2(xs[i], ys[i]); if (withangle) { mks[iter].Rotation = angles[i]; } iter--; if (iter < 0) break; } } return true; } return false; } public bool GetSortedData(bool reverse, int mode, out Mark[] mks) { mks = null; //mode 0 is line 1 is area if (mode == 0) { if (focusedmark[0] == -1) { return false; } else { if (!reverse) { int num = data[focusedmark[0]].Count - focusedmark[1]; mks = new Mark[num]; for (int i = 0; i < mks.Length; i++) { mks[i] = data[focusedmark[0]].Values[focusedmark[1] + i]; } return true; } else { int num = focusedmark[1] + 1; mks = new Mark[num]; for (int i = 0; i < mks.Length; i++) { mks[i] = data[focusedmark[0]].Values[focusedmark[1] - i]; } return true; } } } else { if (recstart.X == -1 || recstart.Y == -1) { return false; } mks = GetAreaData(); if (reverse) { Array.Reverse(mks); } return true; } } public bool MoveMarkInSame(float time) { Mark mk = SelectedMark; if (mk != null) { data[focusedmark[0]].RemoveAt(focusedmark[1]); ExMark exmk = mk as ExMark; if (exmk != null) { exmk.EndTime += time - mk.Time; } mk.Time = time; while (data[focusedmark[0]].ContainsKey(mk.Time)) { mk.Time -= 0.01f; } data[focusedmark[0]].Add(mk.Time, mk); focusedmark[1] = data[focusedmark[0]].IndexOfKey(mk.Time); return true; } return false; } public bool CopyMarkInSame(float time) { Mark mk = SelectedMark; if (mk != null && !data[focusedmark[0]].ContainsKey(time)) { ExMark exmk = mk as ExMark; if (exmk != null) { if (!checklongmark(focusedmark[0], time)) { ExMark newexmk = CreateExMark(exmk.Position.X, exmk.Position.Y, focusedmark[0], time, time + exmk.EndTime - exmk.Time, exmk.Rotation); data[focusedmark[0]].Add(time, newexmk); focusedmark[1] = data[focusedmark[0]].IndexOfKey(time); } } else { Mark newmk = CreateMark(mk.Position.X, mk.Position.Y, focusedmark[0], time, mk.Rotation); data[focusedmark[0]].Add(time, newmk); focusedmark[1] = data[focusedmark[0]].IndexOfKey(time); } return true; } return false; } private bool checklongmark(int num, float time) { foreach (Mark mk in data[num].Values) { ExMark exmk = mk as ExMark; if (exmk != null && time == exmk.EndTime) { return true; } } return false; } public bool SelectMark(float time, int num, float dt) { bool ret = false; foreach (float f in data[num].Keys) { Mark mk; data[num].TryGetValue(f, out mk); ExMark exmk = mk as ExMark; if (exmk != null) { if (f <= time && time <= f + exmk.EndTime - exmk.Time) { focusedmark[0] = num; focusedmark[1] = data[num].IndexOfKey(f); recstart.X = -1; recstart.Y = -1; ret = true; break; } } else { if (f - dt <= time && time <= f + dt) { focusedmark[0] = num; focusedmark[1] = data[num].IndexOfKey(f); recstart.X = -1; recstart.Y = -1; ret = true; break; } } } return ret; } public bool ChangeMarkType(int num) { Mark mk = SelectedMark; if (SelectedMark != null) { if (!data[num].ContainsKey(mk.Time)) { data[focusedmark[0]].Remove(mk.Time); mk.Type = (byte)num; data[num].Add(mk.Time, mk); focusedmark[0] = num; focusedmark[1] = data[num].IndexOfKey(mk.Time); return true; } } return false; } public bool CopyMark(int num) { Mark mk = SelectedMark; if (SelectedMark != null) { if (!data[num].ContainsKey(mk.Time)) { ExMark exmk = mk as ExMark; if (exmk != null) { ExMark newexmk = CreateExMark(exmk.Position.X, exmk.Position.Y, num, exmk.Time, exmk.EndTime, exmk.Rotation); data[num].Add(newexmk.Time, newexmk); focusedmark[0] = num; focusedmark[1] = data[num].IndexOfKey(newexmk.Time); } else { Mark newmk = CreateMark(mk.Position.X, mk.Position.Y, num, mk.Time, mk.Rotation); data[num].Add(newmk.Time, newmk); focusedmark[0] = num; focusedmark[1] = data[num].IndexOfKey(newmk.Time); } return true; } } return false; } public bool DeleteSelectedMark() { if (focusedmark[0] >= 0 && focusedmark[0] < 10) { data[focusedmark[0]].RemoveAt(focusedmark[1]); focusedmark[0] = -1; focusedmark[1] = -1; return true; } return false; } public bool DeleteSelectedMarks() { if (recstart.X != -1 && recstart.Y != -1) { float width = Math.Abs(recstart.X - recend.X); int starty = (recstart.Y <= recend.Y ? recstart.Y : recend.Y); int height = Math.Abs(recstart.Y - recend.Y) + 1; float starttime = (recstart.X <= recend.X ? recstart.X : recend.X); float endtime = starttime + width; for (int i = starty; i < starty + height; i++) { int iter = 0; if (data[i].Count == 0) continue; do { if (data[i].Keys[iter] >= starttime && data[i].Keys[iter] <= endtime) { data[i].RemoveAt(iter); } else { iter++; } } while (iter < data[i].Count); } return true; } return false; } public bool ShiftSelectedMark(int dn) { if (focusedmark[0] >= 0 && focusedmark[0] < 10) { if (dn > 0) { if (focusedmark[1] < data[focusedmark[0]].Count - dn) { focusedmark[1] += dn; return true; } } else if (dn < 0) { if (focusedmark[1] > -dn - 1) { focusedmark[1] += dn; return true; } } } return false; } public bool ShiftSelectedMarkInAll(int dn) { if (focusedmark[0] >= 0 && focusedmark[0] < 10) { if (dn > 0) { int minimum = -1; int point = 0; float time = data[focusedmark[0]].Keys[focusedmark[1]]; float timediff = float.MaxValue; for (int i = 0; i < 10; i++) { for (int j = 0; j < data[i].Count; j++) { if (i == focusedmark[0] && j == focusedmark[1]) continue; if (time < data[i].Keys[j]) { if (timediff > data[i].Keys[j] - time) { minimum = i; point = j; timediff = data[i].Keys[j] - time; } break; } if (time == data[i].Keys[j] && focusedmark[0] < i) { if (timediff > data[i].Keys[j] - time) { minimum = i; point = j; timediff = data[i].Keys[j] - time; } break; } } } if (minimum != -1) { focusedmark[0] = minimum; focusedmark[1] = point; return true; } } else if (dn < 0) { int minimum = -1; int point = 0; float time = data[focusedmark[0]].Keys[focusedmark[1]]; float timediff = float.MaxValue; for (int i = 9; i >= 0; i--) { for (int j = data[i].Count - 1; j >= 0; j--) { if (i == focusedmark[0] && j == focusedmark[1]) continue; if (time > data[i].Keys[j]) { if (timediff > time - data[i].Keys[j]) { minimum = i; point = j; timediff = time - data[i].Keys[j]; } break; } if (time == data[i].Keys[j] && focusedmark[0] > i) { if (timediff > data[i].Keys[j] - time) { minimum = i; point = j; timediff = data[i].Keys[j] - time; } break; } } } if (minimum != -1) { focusedmark[0] = minimum; focusedmark[1] = point; return true; } } } return false; } public bool CopyPreviousMarkAngle() { if (focusedmark[0] >= 0 && focusedmark[0] < 10 && focusedmark[1] > 0) { Mark beforemk = data[focusedmark[0]].Values[focusedmark[1] - 1]; Mark mk = data[focusedmark[0]].Values[focusedmark[1]]; mk.Rotation = beforemk.Rotation; return true; } return false; } public bool CopyPreviousMarkPosition() { if (focusedmark[0] >= 0 && focusedmark[0] < 10 && focusedmark[1] > 0) { Mark beforemk = data[focusedmark[0]].Values[focusedmark[1] - 1]; Mark mk = data[focusedmark[0]].Values[focusedmark[1]]; mk.Position = beforemk.Position; return true; } return false; } public bool FusionMarks() { if (recstart.X != -1 && recstart.Y != -1) { Mark[] mks = GetAreaData(); if (mks.Length == 2 && mks[0].Type == mks[1].Type) { //cast check ExMark exmk = mks[0] as ExMark; if (exmk == null) { exmk = mks[1] as ExMark; if (exmk == null) { exmk = CreateExMark(mks[0].Position.X, mks[0].Position.Y, mks[0].Type, mks[0].Time, mks[1].Time, mks[0].Rotation); data[mks[0].Type].Remove(mks[0].Time); data[mks[0].Type].Remove(mks[1].Time); data[mks[0].Type].Add(mks[0].Time, exmk); return true; } } } } return false; } public bool DeFusionExMark() { if (focusedmark[0] >= 0 && focusedmark[0] < 10) { Mark mk = data[focusedmark[0]].Values[focusedmark[1]]; ExMark exmk = mk as ExMark; if (exmk != null) { data[focusedmark[0]].Remove(exmk.Time); Mark mk1 = CreateMark(exmk.Position.X, exmk.Position.Y, exmk.Type, exmk.Time, exmk.Rotation); Mark mk2 = CreateMark(exmk.Position.X, exmk.Position.Y, exmk.Type, exmk.EndTime, exmk.Rotation); data[focusedmark[0]].Add(mk1.Time, mk1); data[focusedmark[0]].Add(mk2.Time, mk2); return true; } } return false; } public bool MoveMark(int dx, Direction dir) { if (focusedmark[0] >= 0 && focusedmark[0] < 10) { if (dir == Direction.Up) { Mark mk = data[focusedmark[0]].Values[focusedmark[1]]; mk.Position = new Vector2(mk.Position.X, (mk.Position.Y >= dx ? mk.Position.Y - dx : 0)); return true; } else if (dir == Direction.Left) { Mark mk = data[focusedmark[0]].Values[focusedmark[1]]; mk.Position = new Vector2((mk.Position.X >= dx ? mk.Position.X - dx : 0), mk.Position.Y); return true; } else if (dir == Direction.Down) { Mark mk = data[focusedmark[0]].Values[focusedmark[1]]; mk.Position = new Vector2(mk.Position.X, (mk.Position.Y <= 450 - dx ? mk.Position.Y + dx : 0)); return true; } else if (dir == Direction.Right) { Mark mk = data[focusedmark[0]].Values[focusedmark[1]]; mk.Position = new Vector2((mk.Position.X <= 800 - dx ? mk.Position.X + dx : 0), mk.Position.Y); return true; } } return false; } public bool MoveMarks(int dx, Direction dir) { if (recstart.X != -1 && recstart.Y != -1) { Mark[] mks = GetAreaData(); for (int i = 0; i < mks.Length; i++) { if (dir == Direction.Up) { mks[i].Position = new Vector2(mks[i].Position.X, (mks[i].Position.Y >= dx ? mks[i].Position.Y - dx : 0)); } else if (dir == Direction.Left) { mks[i].Position = new Vector2((mks[i].Position.X >= dx ? mks[i].Position.X - dx : 0), mks[i].Position.Y); } else if (dir == Direction.Down) { mks[i].Position = new Vector2(mks[i].Position.X, (mks[i].Position.Y <= 450 - dx ? mks[i].Position.Y + dx : 0)); } else if (dir == Direction.Right) { mks[i].Position = new Vector2((mks[i].Position.X <= 800 - dx ? mks[i].Position.X + dx : 0), mks[i].Position.Y); } } return true; } return false; } private static Mark CreateMark(float x, float y, int type, float time, float angle) { return new Mark(Utility.device, Utility.resourceManager, Utility.skin, type, x, y, time, angle); } private static ExMark CreateExMark(float x, float y, int type, float time, float endtime, float angle) { return new ExMark(Utility.device, Utility.resourceManager, Utility.skin, type, x, y, time, endtime, angle, Utility.circlepoints); } } }
d3ba391166065d31308644e68b6e473a6a3c9f58
C#
thuyhk/ThuanThienVN
/Source/HGT.Admin/Extensions/ModExtensions.cs
2.8125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace HGT.Admin.Extensions { public static class ModExtensions { #region EqualsIgCase /// <summary> /// Equals Ignore Case /// </summary> public static bool EqualsIgCase(this string value, string target) { if (value == null) return target == null; else return value.Equals(target, StringComparison.OrdinalIgnoreCase); } #endregion #region CombineWPath public static string CombineWPath(this string value, string path) { if (string.IsNullOrEmpty(value)) return path; if (value.EndsWith("/")) return value + path; else return value + '/' + path; } #endregion } }
a41e1938c66701168eac9943806adb0abe6a7d74
C#
MagusSolutions/KS.Foundation
/Collections/ThreadsafeEnumerator.cs
2.75
3
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.Serialization; using System.Threading; namespace KS.Foundation { public struct ThreadsafeEnumerator<T> : IEnumerator<T> { public T Current { get { return _current; } } /*** with a count property, it still gets errors.. public int Count { get{ return _size; } } ***/ public ThreadsafeEnumerator(T[] buffer, int size = 0) { if (size <= 0) _size = buffer.Length; else _size = size; _counter = 0; _buffer = buffer; _current = default(T); } object IEnumerator.Current { get { return _current; } } T IEnumerator<T>.Current { get { return _current; } } public void Dispose() { _buffer = null; GC.SuppressFinalize (this); } public bool MoveNext() { if (_counter < _size) { _current = _buffer[_counter++]; return true; } _current = default(T); return false; } public void Reset() { _counter = 0; } bool IEnumerator.MoveNext() { return MoveNext(); } void IEnumerator.Reset() { Reset(); } T[] _buffer; int _counter; int _size; T _current; } }