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
9fb30af008f2a1900ae5d5ea59c344cd0e9becb4
C#
opap-jp/OpapPsdSplitter
/OpapPsdSplitter/LayerTreeParser.cs
2.796875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using PhotoshopFile; namespace OpapPsdSplitter { public static class LayerTreeParser { public static LayerNode ParseLayerTree(PsdFile psd) { LayerNode root = new LayerNode(); ParseLayerTree(psd.Layers.GetEnumerator(), root); return root; } private static void ParseLayerTree(IEnumerator<Layer> layers, LayerNode parentNode) { while (layers.MoveNext()) { Layer currentLayer = layers.Current; //ノード作成&追加 LayerNode newNode = new LayerNode(currentLayer); parentNode.AddChildNode(newNode); //レイヤ種類を取得 LayerSectionInfo sec = currentLayer.AdditionalInfo .OfType<LayerSectionInfo>().FirstOrDefault(); LayerSectionType secType = LayerSectionType.Layer; if (sec != null) { secType = sec.SectionType; } //レイヤ種類別処理 switch (secType) { case LayerSectionType.SectionDivider: //フォルダ終了(逆順に並んでいるため、こちらが先に来る) //ひとつ下の階層として以降のレイヤーを処理 newNode.Layer = null; newNode.AddChildNode(new LayerNode(currentLayer)); ParseLayerTree(layers, newNode); break; case LayerSectionType.OpenFolder: case LayerSectionType.ClosedFolder: //フォルダ開始(逆順に並んでいるため、こちらが後に来る) parentNode.Name = currentLayer.Name; //処理終了(再帰脱出条件) return; case LayerSectionType.Layer: default: //通常レイヤ break; } } } } }
f56aeae76bf4d16abdf71e29369055ef149d53e7
C#
drewkeller/SkippyLab
/Skippy/Extensions/StringExtensions.cs
3.203125
3
namespace Skippy.Extensions { public static class StringExtensions { /// <summary> /// Gets whether the string is not null and not empty. /// </summary> /// <param name="this"></param> /// <returns></returns> public static bool HasData(this string @this) { return !string.IsNullOrEmpty(@this); } } }
1c7a9a4b3b938e03f21d9ed18276414414fc6681
C#
FrancisChung/fixie
/src/Fixie.Cli/Dotnet.cs
2.765625
3
namespace Fixie.Cli { using System; using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; static class Dotnet { public static readonly string Path = FindDotnet(); static string FindDotnet() { var fileName = OsPlatformIsWindows() ? "dotnet.exe" : "dotnet"; //If `dotnet` is the currently running process, return the full path to that executable. using (var currentProcess = Process.GetCurrentProcess()) { var mainModule = currentProcess.MainModule; var currentProcessIsDotNet = !string.IsNullOrEmpty(mainModule?.FileName) && System.IO.Path.GetFileName(mainModule.FileName) .Equals(fileName, StringComparison.OrdinalIgnoreCase); if (currentProcessIsDotNet) return mainModule.FileName; return "dotnet"; } } static bool OsPlatformIsWindows() { #if NET452 return true; #else return RuntimeInformation.IsOSPlatform(OSPlatform.Windows); #endif } } }
40e092fce295bf9459f52c790b17d581ea1a861e
C#
Abc-Arbitrage/ZeroLog
/src/ZeroLog.Tests/BufferSegmentProviderTests.cs
2.59375
3
using System; using System.Collections.Generic; using NUnit.Framework; using ZeroLog.Tests.Support; namespace ZeroLog.Tests; [TestFixture] public unsafe class BufferSegmentProviderTests { private BufferSegmentProvider _bufferSegmentProvider; private const int _segmentCount = 4; private const int _segmentSize = 8; [SetUp] public void SetUp() { _bufferSegmentProvider = new BufferSegmentProvider(_segmentCount, _segmentSize); } [Test] public void should_get_buffer_segment_when_there_are_segments_available() { var bufferSegment = _bufferSegmentProvider.GetSegment(); bufferSegment.Length.ShouldEqual(_segmentSize); new IntPtr(bufferSegment.Data).ShouldNotEqual(IntPtr.Zero); bufferSegment.UnderlyingBuffer.ShouldNotBeNull(); } [Test] public void should_get_all_segments_from_a_large_buffer() { var segments = new List<BufferSegment>(); for (var i = 0; i < _segmentCount; ++i) segments.Add(_bufferSegmentProvider.GetSegment()); var lastAddress = (nuint)segments[0].Data; for (var i = 1; i < segments.Count; i++) { var bufferSegment = segments[i]; ((nuint)bufferSegment.Data).ShouldEqual(lastAddress + _segmentSize); bufferSegment.Length.ShouldEqual(_segmentSize); lastAddress = (nuint)bufferSegment.Data; } } [Test] public void should_allocate_a_new_large_buffer_when_needed() { var segments = new List<BufferSegment>(); for (var i = 0; i < 2 * _segmentCount; i++) segments.Add(_bufferSegmentProvider.GetSegment()); segments[_segmentCount - 1].UnderlyingBuffer.ShouldBeTheSameAs(segments[0].UnderlyingBuffer); segments[_segmentCount].UnderlyingBuffer.ShouldNotBeTheSameAs(segments[_segmentCount - 1].UnderlyingBuffer); segments[_segmentCount + 1].UnderlyingBuffer.ShouldBeTheSameAs(segments[_segmentCount].UnderlyingBuffer); ((nuint)segments[_segmentCount + 1].Data).ShouldEqual((nuint)segments[_segmentCount].Data + _segmentSize); } [Test] public void should_validate_arguments() { Assert.Throws<ArgumentOutOfRangeException>(() => _ = new BufferSegmentProvider(0, 1)); Assert.Throws<ArgumentOutOfRangeException>(() => _ = new BufferSegmentProvider(-1, 1)); Assert.Throws<ArgumentOutOfRangeException>(() => _ = new BufferSegmentProvider(1, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => _ = new BufferSegmentProvider(1, -1)); } [Test] public void should_limit_buffer_size() { var provider = new BufferSegmentProvider(4 * 1024, 1024 * 1024); provider.BufferSize.ShouldEqual(1024 * 1024 * 1024); } }
4b63b970730283b0af817487aa328a31b84c49df
C#
Alex236/TestTask
/PriceChecker/ProductUpdater/CatalogReader.cs
3.046875
3
using System.Collections; using System.Collections.Generic; using System.Linq; using System.IO; using System.Net; using PriceChecker.Models; using System; using HtmlAgilityPack; namespace PriceChecker.ProductUpdater { public class CatalogReader { public List<Product> ReadCatalog(string catalogUrl) { List<Product> products = new List<Product>(); int number = GetNumberOfPages(catalogUrl); for (int i = 1; i <= number; i++) { string pageUrl = catalogUrl + "?p=" + i.ToString(); products.AddRange(ReadPage(pageUrl)); } return products; } private List<Product> ReadPage(string url) { var products = new List<Product>(); string page = GetPage(url); var nodes = GetProductContainers(page); foreach (var node in nodes) { var product = ParseNodeToProduct(node); if (product != null) { products.Add(product); } } return products; } private Product ParseNodeToProduct(HtmlNode node) { string url = GetProductUrl(node); string imageUrl = GetImageUrl(node); string name = GetProductName(node); string price = GetProductPrice(node); if (price != string.Empty) { return new Product() { Url = url, ImageUrl = imageUrl, Name = name, Price = Double.Parse(price) }; } else { return null; } } private string GetImageUrl(HtmlNode node) { return ""; } private string GetProductUrl(HtmlNode node) { Console.Write(node.InnerHtml); var nodes = node.ChildNodes; HtmlNode infoNode = null; foreach (var currentNode in nodes) { if (currentNode.GetAttributeValue("class", "") == "product-name is-truncated") { infoNode = currentNode; break; } } var aNode = infoNode.ChildNodes; string url = String.Empty; foreach (var currentNode in aNode) { url = currentNode.GetAttributeValue("href", ""); } return url; } private string GetProductName(HtmlNode node) { var nodes = node.ChildNodes; HtmlNode infoNode = null; foreach (var currentNode in nodes) { if (currentNode.GetAttributeValue("class", "") == "product-name is-truncated") { infoNode = currentNode; break; } } var aNode = infoNode.ChildNodes; string name = String.Empty; foreach (var currentNode in aNode) { name = currentNode.GetAttributeValue("title", ""); } return name; } private string GetProductPrice(HtmlNode node) { var nodes = node.ChildNodes; HtmlNode infoNode = null; foreach (var currentNode in nodes) { if (currentNode.GetAttributeValue("class", "") == "price") { infoNode = currentNode; return infoNode.InnerText; } } return string.Empty; } private List<HtmlNode> GetProductContainers(string page) { var nodes = new List<HtmlNode>(); var htmlDoc = new HtmlDocument(); htmlDoc.LoadHtml(page); HtmlNode list = null; foreach (var node in htmlDoc.DocumentNode.SelectNodes("//ul[@class='" + "products-grid category-products-grid product-items-list" + "']")) { list = node; } HtmlNodeCollection childNodes = list.ChildNodes; return childNodes.ToList(); } private int GetNumberOfPages(string url) { string page = GetPage(url); var htmlDoc = new HtmlDocument(); htmlDoc.LoadHtml(page); string value = ""; foreach (HtmlNode node in htmlDoc.DocumentNode.SelectNodes("//a[@class='" + "last" + "']")) { value = node.InnerText; } return int.Parse(value); } private string GetPage(string url) { WebRequest request = WebRequest.Create(url); WebResponse response = request.GetResponse(); string responseFromServer = ""; using (Stream dataStream = response.GetResponseStream()) { StreamReader reader = new StreamReader(dataStream); responseFromServer = reader.ReadToEnd(); } return responseFromServer; } } }
b7eaa264f13c6c767fa1544baab24d46ed843ee8
C#
eqinox/SoftwareUniversity
/Course-Level-0/4.ConsoleInputOutput/09.SumOfNNumbers/SumOfNNumbers.cs
3.765625
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _09.SumOfNNumbers { class SumOfNNumbers { static void Main(string[] args) { Console.Write("Write num: "); int num = int.Parse(Console.ReadLine()); double sum = 0; Console.WriteLine("Now write {0} numbers", num); for (int i = 0; i < num; i++) { double currentNum = double.Parse(Console.ReadLine()); sum += currentNum; } Console.WriteLine(sum); } } }
6e226992d314cd3538485b81d5ec2a2787d88da7
C#
IbrahimFahdah/MLDemo
/MLModelBuilder/DataBuilder/Helper.cs
3.125
3
using System; using System.Collections.Generic; using System.Linq; namespace MLBuild.DataBuilder { public class Helper { public static double CalcXc(List<Square> seqList, int squareSize) { var A = seqList.Where(x => x.IsFull).Sum(x => x.A); var sum = 0.0; foreach (var x in seqList.Where(x => x.IsFull)) { sum += x.A * (x.Col * squareSize + squareSize / 2.0); } if (A == 0) return 0; return Math.Round(sum / A, 3); } } }
c73cb5b436c48cba9979d5cf5f7279eb6fcc0a25
C#
thilinanjana/io-reboot
/Assets/Scripts/Managers/MusicManager.cs
2.640625
3
using UnityEngine; public class MusicManager : MonoBehaviour { private AudioSource audioSource; public AudioClip[] audioTracks; private int index; private float elapsed; private float checkInterval = 15.0f; void Awake() { audioSource = GetComponent<AudioSource>(); index = Random.Range(0, audioTracks.Length); elapsed = checkInterval; } void Update() { elapsed += Time.deltaTime; if (elapsed >= checkInterval) { if (PlayNext()) { audioSource.clip = (audioTracks[index]); audioSource.Play(); } elapsed -= checkInterval; } } private bool PlayNext() { if (!audioSource.isPlaying) { index = (index + 1) % audioTracks.Length; return true; } return false; } public void Mute(bool pause) { audioSource.mute = pause; } }
b6c3f0e898909e20bd16c03a44f695ba9f3f219e
C#
ericakimdev/sprintapp
/SprintApp/Models/Project.cs
2.59375
3
using System; using MongoDB.Bson; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SprintApp.Models { // Project class for use with MongoDB public class Project { /************************* * PROPERTIES * * ***********************/ public ObjectId _id { get; set; } public long ProjectId { get; set; } public string ProjectName { get; set; } public string Manager { get; set; } public string Client { get; set; } public List<string> Members { get; set; } public DateTime StartDate { get; set; } public DateTime DueDate { get; set; } /************************* * CONSTRUCTORS * * ***********************/ public Project() { Members = new List<string>(); } public Project(int _projectid, string _projectname, string _manager, string _client, List<string> _members, DateTime _startDate, DateTime _dueDate) { ProjectId = _projectid; ProjectName = _projectname; Manager = _manager; Client = _client; Members = _members; StartDate = _startDate; DueDate = _dueDate; } } // END Project class } // END namespace
9219fe7876eae08e83164fdc34775a31fcbec726
C#
TheNumerus/Duckify
/Duckify/Classes/Models.cs
2.75
3
using SpotifyAPI.Web.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Duckify { public class SpotifySearchResult { public string Id { get; set; } public string Name { get; set; } public string ImageUrl { get; set; } public string Length { get; set; } public string Artists { get; set; } public SpotifySearchResult() { } public SpotifySearchResult(FullTrack track) { Id = track.Id; Name = track.Name; if (track.Album.Images.Count > 0) { ImageUrl = track.Album.Images[0].Url; } Length = Helper.ConvertMsToReadable(track.DurationMs); Artists = track.Artists.Select(x => x.Name).ConvertToString(); } } }
a25bd86b4912943b71877c7fbedb1a508ef3145a
C#
Drumev00/CSharp-Advanced
/Sets and Dictionaries/Lab/Cities by Continent and Country/Program.cs
3.671875
4
using System; using System.Collections.Generic; namespace Cities_by_Continent_and_Country { class Program { static void Main(string[] args) { int commands = int.Parse(Console.ReadLine()); var destinations = new Dictionary<string, Dictionary<string, List<string>>>(); for (int i = 0; i < commands; i++) { string[] input = Console.ReadLine().Split(); string continent = input[0]; string country = input[1]; string city = input[2]; if (!destinations.ContainsKey(continent)) { destinations[continent] = new Dictionary<string, List<string>>(); } if (!destinations[continent].ContainsKey(country)) { destinations[continent].Add(country, new List<string>()); } destinations[continent][country].Add(city); } foreach (var kvp in destinations) { Console.WriteLine($"{kvp.Key}:"); foreach (var item in kvp.Value) { Console.WriteLine($" {item.Key} -> {string.Join(", ", item.Value)}"); } } } } }
e2d285052ca70d2847d15cd7f7f3f5b67dfdef14
C#
annasirach/ISMConditionalStatements-2
/WhileConsole2/WhileConsole2/Program.cs
3.375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WhileConsole2 { class Program { static void Main(string[] args) { Console.OutputEncoding = Encoding.Unicode; Console.InputEncoding = Encoding.Unicode; Console.Write("P="); double p = Convert.ToInt32(Console.ReadLine()); double s = 10, d = 10, k = 1; ; while (s < 200) { d = d + d * (p / 100); s = s + d; k++; } Console.WriteLine("Кількість днів = {0:F0}", k); Console.WriteLine("Пробіг = {0:F2}", s); } } }
534c823f44221eda521ec65325c69d272104d270
C#
itovkach95/TulsiAp
/TulsiAp-master/Tulsi/Tulsi/Controls/CustomFrame.cs
2.671875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; namespace Tulsi.Controls { public class CustomFrame : ContentView { public readonly static BindableProperty BorderRadiusProperty = BindableProperty.Create("BorderRadius", typeof(int), typeof(CustomFrame), 5, BindingMode.OneWay, null, null, null, null, null); public readonly static BindableProperty OutlineColorProperty = BindableProperty.Create("OutlineColor", typeof(Color), typeof(CustomFrame), Color.Default, BindingMode.OneWay, null, null, null, null, null); public readonly static BindableProperty BorderWidthProperty = BindableProperty.Create("BorderWidth", typeof(int), typeof(CustomFrame), 2, BindingMode.OneWay, null, null, null, null, null); public int BorderWidth { get { return (int)base.GetValue(CustomFrame.BorderWidthProperty); } set { base.SetValue(CustomFrame.BorderWidthProperty, value); } } public Color OutlineColor { get { return (Color)base.GetValue(CustomFrame.OutlineColorProperty); } set { base.SetValue(CustomFrame.OutlineColorProperty, value); } } public int BorderRadius { get { return (int)base.GetValue(CustomFrame.BorderRadiusProperty); } set { base.SetValue(CustomFrame.BorderRadiusProperty, value); } } public CustomFrame() { base.Padding = new Size(10, 10); } } }
b3d71e6e5ccf3333b010508882df541d2d35d33a
C#
faheywf/FPToolbox
/FPToolbox.Test/Utility.Test.cs
3
3
using Microsoft.VisualStudio.TestTools.UnitTesting; using static FPToolbox.Utility; namespace FPToolbox.Test { [TestClass] public class Utility { [TestMethod] public void OptionReturnsSome() { Option option = Option(5); int value = option.Match(0); Assert.AreEqual(5, value); } [TestMethod] public void OptionReturnsNone() { // can't pass null directly because it invalidates type inference // default of classes is null which is why we need this whole thing anyways. Option option = Option(default(Some<int>)); int value = option.Match(0); Assert.AreEqual(0, value); } [TestMethod] public void SomeWorksForValueTypes() { Option option = Some(5); int value = option.Match(0); Assert.AreEqual(5, value); } class Square { public int Length; } [TestMethod] public void SomeWorksForReferenceTypes() { Square square = new Square() { Length = 3 }; Option option = Some(square); Square value = option.Match(new Square()); Assert.AreEqual(square, value); Assert.AreEqual(square.Length, value.Length); } [TestMethod] public void NoneWorks() { Option option = None(); int value = option.Match(5); Assert.AreEqual(5, value); } } }
aa4d7f29e2747f608a6fad72cff604ba7040c0d6
C#
mitkokazakov/C---Fundamentals---SoftUni
/Final Exam - April 2020/1. Activation Keys/Program.cs
3.765625
4
using System; namespace _1._Activation_Keys { class Program { static void Main(string[] args) { string input = Console.ReadLine(); string command = Console.ReadLine(); while (command != "Generate") { string[] commandsArgs = command.Split(">>>"); string mainCommand = commandsArgs[0]; if (mainCommand == "Contains") { string substr = commandsArgs[1]; if (input.Contains(substr)) { Console.WriteLine($"{input} contains {substr}"); } else { Console.WriteLine("Substring not found!"); } } else if (mainCommand == "Flip") { string option = commandsArgs[1]; int startIndex = int.Parse(commandsArgs[2]); int endIndex = int.Parse(commandsArgs[3]); string substr = input.Substring(startIndex, endIndex - startIndex); if (option == "Upper") { string changedSubstr = substr.ToUpper(); input = input.Replace(substr,changedSubstr); } else if (option == "Lower") { string changedSubstr = substr.ToLower(); input = input.Replace(substr, changedSubstr); } Console.WriteLine(input); } else if (mainCommand == "Slice") { int startIndex = int.Parse(commandsArgs[1]); int endIndex = int.Parse(commandsArgs[2]); input = input.Remove(startIndex,endIndex - startIndex); Console.WriteLine(input); } command = Console.ReadLine(); } Console.WriteLine($"Your activation key is: {input}"); } } }
f6522d33b5cf872d8d3c7f02f0c3df31153c1cc4
C#
Becc-s/super-barnacle
/Library/Library/Models/LibraryDbInit.cs
2.609375
3
//Rebecka Åkhagen Holm //V. 1.0 using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Library.Models { /// <summary> /// Derived database strategy /// </summary> class LibraryDbInit : DropCreateDatabaseAlways<LibraryContext> { protected override void Seed(LibraryContext context) { base.Seed(context); //Add to database Author Rebecka = new Author() { Name = "Rebecka" }; Book monteCristo = new Book() { Title = "The Count of Monte Cristo", Author = Rebecka, Description = "Greven av monte christo" }; BookCopy kopia = new BookCopy() { Book = monteCristo }; Member member1 = new Member() { Name = "Rebecka", PersonalId = "1992" }; Loan loan1 = new Loan() { Member = member1, BookCopy = kopia }; context.Books.Add(monteCristo); context.BookCopies.Add(kopia); context.Authors.Add(Rebecka); monteCristo.BookCopies.Add(kopia); context.SaveChanges(); context.Members.Add(member1); //context.Loans.Add(loan1); // Add the book to the DbSet of books. // Persist changes to the database context.SaveChanges(); } } }
ffb000d8eef7be044cf0c13512c98242288f8ec6
C#
matragorn/PV138_RSS_reader
/PV138_RSS_Reader/PV138_RSS_Reader/RenameBox.cs
2.71875
3
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace PV138_RSS_Reader { public partial class RenameBox : Form { public string NewName { get; set; } public RenameBox(string title= "") { InitializeComponent(); if (title != "") { label_title.Text = title; } } private void button1_Click(object sender, EventArgs e) { if (string.IsNullOrWhiteSpace(textBox_newText.Text)) { MessageBox.Show("Jméno nemůže být prázdné!", "Fatální chyba", MessageBoxButtons.OK, MessageBoxIcon.Error); textBox_newText.Focus(); return; } NewName = textBox_newText.Text; DialogResult = DialogResult.OK; this.Close(); } private void button2_Click(object sender, EventArgs e) { DialogResult = DialogResult.Cancel; this.Close(); } } }
b2438e8dd49f66eecaaebf698fdd984bd0d7d27a
C#
alexeygavrilov/PocketMoney
/PocketMoney.Model/Internal/Roles.cs
2.6875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using PocketMoney.Data; namespace PocketMoney.Model.Internal { public static class Roles { public static Role Empty = new Role(); public static Role Children = new Role(0x1, "Children"); public static Role Parent = new Role(0x2, "Parent"); public static Role FamilyAdmin = new Role(0x4, "FamilyAdmin"); public static Role Admin = new Role(0x8, "Admin"); public static Role Define(int roleId) { switch (roleId) { case 1: return Children; case 2: return Parent; case 4: return FamilyAdmin; case 8: return Admin; default: return Empty; } } public static Role Define(string roleName) { switch (roleName) { case "Children": return Children; case "Parent": return Parent; case "FamilyAdmin": return FamilyAdmin; case "Admin": return Admin; default: return Empty; } } } }
7ab3d78d650c3731a5efd0ef1b77e1c7d165d029
C#
o2co2/AffinityUI
/AffinityUI/Control.cs
2.75
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; namespace AffinityUI { /// <summary> /// The absolute base class for all controls, provides little functionality /// and mostly serves as a handle for referencing all other types of controls. /// </summary> public abstract class Control { UI context; string id; Rect position; public virtual UI Context { get { return context; } set { context = value; if (id != null && context != null) { context.RegisterID(this, id); } } } /// <summary> /// Gets or sets (protected internal) the owning parent of this control. /// </summary> /// <value>The parent control.</value> public Control Parent { get; protected internal set; } public TControl ParentAs<TControl>() where TControl : Control { return Parent as TControl; } /// <summary> /// Sets the position of the control. /// </summary> /// <param name="position">The position.</param> /// <returns>this instance</returns> public Control Position(Rect position) { this.position = position; return this; } public Rect Position() { return position; } /// <summary> /// Performs the necessary calls to UnityGUI to perform layout or updates. /// Should be called in the OnGUI methods. /// </summary> /// <remarks> /// Only override this method if you need complete control over GUI layout. /// This method automatically calls <see cref="Layout_GUI"/> or /// <see cref="Layout_GUILayout"/> depending on the GUI target. /// </remarks> public virtual void Layout() { GUI.skin = SkinValue; switch (Context.Layout) { case LayoutTarget.GUI: Layout_GUI(); break; case LayoutTarget.GUILayout: Layout_GUILayout(); position = GUILayoutUtility.GetLastRect(); break; default: throw new InvalidOperationException("Layout must be either GUI or GUILayout"); } } /// <summary> /// Called when layout is done using GUI. /// </summary> protected virtual void Layout_GUI() { throw new NotSupportedException("Layout_GUI not implemented in " + GetType().Name); } /// <summary> /// Called when layout is done using GUILayout. /// </summary> protected virtual void Layout_GUILayout() { throw new NotSupportedException("Layout_GUILayout not implemented in " + GetType().Name); } /// <summary> /// Globally registers this control with the specified ID. /// </summary> /// <param name="id">an ID used to refer to this control.</param> public Control ID(string id) { // At this point in time, Context may be null. If so, the ID // will be picked up and set when Context is first set. if (Context != null) { Context.RegisterID(this, id); } this.id = id; return this; } public string ID() { return id; } /// <summary> /// Gets or sets the skin to use when rendering. /// </summary> /// <value>The skin value.</value> protected internal virtual GUISkin SkinValue { get; set; } /// <summary> /// Gets or sets a value indicating whether this <see cref="AffinityUI.Control"/> has /// a skin independant of its parent. Setting the skin of a control that owns this one /// will have no effect if this value is true. For example, if this skin is inside a /// Window or a panel, setting the skin on the Window or panel will have no effect on /// this control when IndependantSkin is set to true. /// </summary> /// <value><c>true</c> if the control has an independant skin; otherwise, <c>false</c>.</value> protected internal virtual bool IndependantSkin { get; set; } } }
68a2a6e212f817108c3daab316a2267777664e31
C#
TheEliForbes/CS321-Projects
/BSTtree/BSTtree/Program.cs
3.484375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using static System.Math; //allows direct calling of Log function using static System.Console; //allows direct calling of Write, WriteLine, etc. class Node { private int data; //node value public Node left; //left node public Node right; //right node //Node constructor public Node(int val=0) { this.data = val; left = null; right = null; } //data getter public int Data { get { return data; } } public static int Comparison(Node n1, Node n2) { if (n1.data < n2.data) return -1; else if (n1.data == n2.data) return 0; else if (n1.data > n2.data) return 1; return 0; } public static bool operator <(Node n1, Node n2) { return Comparison(n1, n2) < 0; } public static bool operator >(Node n1, Node n2) { return Comparison(n1, n2) > 0; } public override bool Equals(object obj) { if (obj == null) return false; if (Object.ReferenceEquals(this, obj)) return true; if (this.GetType() != obj.GetType()) return false; Node temp = (Node)obj; if (this.data == temp.data) return true; else return false; } } //====================================================================== //====================================================================== class BinaryTree { private Node root; //tree root private int count; //used in count function //constructor public BinaryTree() { root = null; count = 0; } //fancy C# getter for empty check public bool isEmpty { get { return root == null; } } public int counter() { count = 0; //clear, in case previously set countHelper(root); return count; } private void countHelper(Node n) { if(n != null) { countHelper(n.left); count++; countHelper(n.right); } } //insertion interface public void insert(int data) { Node temp = new Node(data); if (isEmpty) this.root = temp; else { insertHelp(root, temp); } } //insertion, using overriden operators private bool insertHelp(Node rt, Node data) { if (data.Equals(rt)) return false; else if (data < rt) { if (rt.left == null) { rt.left = data; return true; } else insertHelp(rt.left, data); } else {// if (data > rt) if (rt.right == null) { rt.right = data; return true; } else insertHelp(rt.right, data); } return false;//error if here } //traversal interface public void inOrderTraversal() { inOrderHelper(root); } //in-order traversal public void inOrderHelper(Node n) { if(n != null) //ensure that we have data { inOrderHelper(n.left); //recurse left Console.Write("{0} ", n.Data);//print inOrderHelper(n.right);//recurse right } } //depth-finder interface public int maxDepth() { return maxDepthHelper(root); } //depth-finder private int maxDepthHelper(Node n) { if (n == null)//base case return 0; else { int ldepth = maxDepthHelper(n.left); //get max height in left tree int rdepth = maxDepthHelper(n.right);//get max height in right tree return ((ldepth < rdepth) ? ++rdepth : ++ldepth); //return max++, ternary operator fun! } } public int idealHeight() { return idealHeightHelper(root); } private int idealHeightHelper(Node n) { //log base2 (n+1) -1 == most accurate calculation for ideal tree height //instead of log base2 (n) , as given in cs223 int nodeCount = counter(); //need count for ideal height calculation return (int)Log((double)nodeCount + 1, 2.0); //log2(n+1)-1 } //interface function for printing the tree, passes all necessary variables public void printTree() { String dent = ""; int i = 0; bool last = false; int count = counter(); //init variables then call function with root prettyTree(root, dent, i, count, last); } //function for printing out the tree structure in a visually pleasing way private void prettyTree(Node rt, String dent, int i, int count, bool last) { //credit for +-| structure goes to Joshua Stachowski //https://stackoverflow.com/questions/1649027/how-do-i-print-out-a-tree-structure //adapted to this BST implementation by me, Eli Forbes WriteLine(dent + "+--" + rt.Data); dent += last ? " " : " |"; if(rt.left != null) { last = (i == count - 1); prettyTree(rt.left, dent, ++i, count, last); } if(rt.right != null) { last = (i == count - 1); prettyTree(rt.right, dent, i, count, last); } } } //====================================================================== //====================================================================== class BSTtree { static void Main(string[] args) { BinaryTree t = new BinaryTree(); WriteLine("Enter a collection of numbers in the range [0, 100], separated by spaces:"); string input = ReadLine(); string[] sList = input.Split(' '); int[] nList = new int[sList.Length]; //new array of length of string list foreach (string s in sList) //for all strings { int num; bool res = Int32.TryParse(s, out num); if (res) t.insert(num); //parse & insert else WriteLine("Parsing error.."); } Write("Tree contents: "); t.inOrderTraversal(); WriteLine(); WriteLine("Tree statistics:"); int numNodes = t.counter(); //assign to variable, used 2x WriteLine(" Number of nodes: {0}", numNodes); WriteLine(" Number of levels: {0}", t.maxDepth()); //direct calculation, since used 1x WriteLine(" Ideal Height for Tree of {0} Nodes = {1}", numNodes, t.idealHeight()); WriteLine("\nBonus! Print Tree!"); t.printTree(); WriteLine("\nDone"); } }
bac7cb73330a5ba1bcf85f63988dc3288dd8b8a8
C#
gleroi/k-rabbit
/Rabbit.Tests/Client/SocketFake.cs
2.765625
3
using System.Collections.Generic; using System.Text; using Rabbit.Client; namespace Rabbit.Tests.Client { class SocketFake : ISocket { public List<byte[]> SendedData = new List<byte[]>(); public List<string> ReceiveData = new List<string>(); int currentReceivedData = 0; public void Connect(string host, int port) { } public int Send(byte[] data) { this.SendedData.Add(data); return data.Length; } public int Receive(byte[] data) { if (this.currentReceivedData < this.ReceiveData.Count) { byte[] recvData = Encoding.ASCII.GetBytes(this.ReceiveData[this.currentReceivedData] + "\n"); this.currentReceivedData += 1; recvData.CopyTo(data, 0); return recvData.Length; } return 0; } } }
4b44982d26c33f69c4e514ecffbb9f3b4f14fd6f
C#
ndomitio/InheritanceAndPolymorphismPractice
/Vehicle.cs
3.625
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace InheritanceAndPolymorphismPractice { public class Vehicle { //fields private string color; private int wheels; //properties public string Color { get { return this.color; } set { this.color = value; } } public int Wheels { get { return this.wheels; } set { this.wheels = value; } } //constructors public Vehicle() { } public Vehicle(int wheels, string color) { { this.wheels = wheels; } { this.color = color; } } //methods public void Honk() { Console.WriteLine("Honk!"); } } }
7212a571bfd35ada62fdee3e036aa7b28e4ad273
C#
smokingpc/CSharpTest
/src/MSAccessTest/FRMmAIN.cs
2.5625
3
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Data.OleDb; namespace MSAccessTest { public partial class frmMain : Form { private string ExePath = System.IO.Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory); private string DsnFormat = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};"; private string DSN = ""; private OleDbConnection Connection; private OleDbCommand Command; private List<CTestUser> UserList = new List<CTestUser>(); public frmMain() { InitializeComponent(); } private void InitDatabase() { string filename = ExePath + "\\testdb.accdb"; DSN = string.Format(DsnFormat, filename); string SQL = ""; int ret = 0; //SQL = "INSERT INTO USER([USERNAME], [ADDRESS], [PHONE]) VALUES('海綿寶寶', '蟹堡王', '0800-092000'); SELECT SCOPE_IDENTITY();"; var SQL1 = "INSERT INTO [USER] (USERNAME, ADDRESS, PHONE) VALUES ('海綿寶寶', '蟹堡王', '0800-092000')"; var SQL2 = "SELECT @@Identity"; using (OleDbCommand cmd = new OleDbCommand(SQL1, new OleDbConnection(DSN))) { //cmd不像adapter,不會自己開啟connection.... cmd.Connection.Open(); cmd.ExecuteNonQuery(); //MSAccess一條statement不能執行兩個命令 //所以要拆開做,另外 SELECT @@Identity 只能取得 CurrentConnection 內的 identity //如果 connection closed 這值就會重算..... cmd.CommandText = SQL2; ret = Convert.ToInt32(cmd.ExecuteScalar()); cmd.Connection.Close(); } SQL = "SELECT * FROM [USER]"; using (DataTable table = new DataTable()) { using (OleDbDataAdapter adapter = new OleDbDataAdapter(SQL, DSN)) { adapter.Fill(table); } foreach (DataRow row in table.Rows) { //CJamCmd item = new CJamCmd(row); CTestUser item = new CTestUser(); item.Id = Convert.ToInt32(row["ID"].ToString()); item.Name = row["UserName"].ToString(); item.Address = row["Address"].ToString(); item.Phone = row["Phone"].ToString(); UserList.Add(item); } } gridControl1.DataSource = UserList; } private void frmMain_Load(object sender, EventArgs e) { InitDatabase(); gridControl1.RefreshDataSource(); } } public class CTestUser { public int Id { get; set; } public string Name { get; set; } public string Address { get; set; } public string Phone { get; set; } } }
aa6e8786db42614c4562c82cbbfb7847593fbc31
C#
frankhaugen/Frank.Libraries
/src/Frank.Libraries.Time/Frank.Libraries.Time/Types/YearMonth.cs
2.984375
3
namespace Frank.Libraries.Time.Types; public readonly partial struct YearMonth { public YearMonth(int year, int month) { // Guard if (year < DateOnly.MinValue.Year) { throw new ArgumentOutOfRangeException(nameof(year)); } if (year > DateOnly.MaxValue.Year) { throw new ArgumentOutOfRangeException(nameof(year)); } if (month < 1) { throw new ArgumentOutOfRangeException(nameof(month)); } if (month > 12) { throw new ArgumentOutOfRangeException(nameof(month)); } Year = year; Month = month; } public Year Year { get; } public int Month { get; } public override string ToString() => $"{Year:0000}-{Month:00}"; public bool Equals(YearMonth other) => Year == other.Year && Month == other.Month; public override bool Equals(object? obj) => obj is YearMonth other && Equals(other); public override int GetHashCode() => HashCode.Combine(Year, Month); private int CompareTo(YearMonth right) => Year.CompareTo(right.Year) * 12 + Month.CompareTo(right.Month); }
b620827d3d852938e6be81453acef4bb7ba58b1e
C#
090820-dotnet-uta/WongAlex
/Demos/RPS_Game_NoDB/Program.cs
3.421875
3
using System; using System.Collections.Generic; using System.Linq; namespace RPS_Game_NoDB { public enum Choice { Rock,//can be accessed with a 0 Paper,//can be accessed with a 1 Scissors//can be accessed with a 2 } class Program { static void Main(string[] args) { List<Player> players = new List<Player>(); List<Game> games = new List<Game>(); List<Round> rounds = new List<Round>(); Player computer = new Player() { Name = "Computer" };//instantiate a Player and give a value to the Name all at once. players.Add(computer); int choice; int gameCounter = 1; do//game loop { //get a choice from the user (play or quit) choice = PlayOrQuit(gameCounter); if (choice == 2)//if the user chose 2, break out of the game. { break; } Player p1 = Player.CheckPlayer(players); Game game = new Game();// create a game game.Player1 = p1;// game.Computer = computer;// Random rand = new Random(); int roundCounter = 1; //play rounds till one player has 2 wins //assign the winner to the game and check that property to break out of the loop. while (game.winner.Name == "null") { Round round = new Round();//declare a round for this iteration System.Console.WriteLine($"\n\t\tThis is round #{roundCounter++}\n"); round.game = game;// add the game to this round round.player1 = p1;// add user (p1) to this round round.Computer = computer;// add computer to this round //play a single round and set the round outcome round.Outcome = Round.PlayRound(round, roundCounter, game); game.rounds.Add(round);//add this round to the games List of rounds //see if anyone has won the game game.CheckWinner(); }//end of rounds loop games.Add(game); //play rounds till one player has 2 wins //record each round into the game //record the game //increment wins/losses for each player //print out the game results - rounds data } while (choice != 2);//end of game loop PrintAllCurrentData(games, players, rounds); //on quitting.... //print out the win.loss record for all players }//end of main public static void PrintAllCurrentData(List<Game> games, List<Player> players, List<Round> rounds) { int gameNum = 1; foreach (var game in games) { Console.WriteLine($"\tGame #{gameNum++}\n"); System.Console.WriteLine($"Player1 Name => {game.Player1.Name}\ncomputer Name => {game.Computer.Name}\n winner is => {game.winner.Name}"); System.Console.WriteLine($"\n\t--- Here are the games rounds ---\n "); foreach (Round round in game.rounds) { System.Console.WriteLine($"\tplayer1 => {round.player1.Name}\n\tp1 choice => {round.p1Choice}"); System.Console.WriteLine($"\tplayer2 => {round.Computer.Name}\n\tcomputer choice => {round.ComputerChoice}"); System.Console.WriteLine($"\tthe Outcome of this round is => {round.Outcome}\n"); } } System.Console.WriteLine("Here is the list of players."); foreach (var player in players) { System.Console.WriteLine($"Player Name: {player.Name}\n\twins: {player.record["wins"]} losses: {player.record["losses"]}"); } } public static int PlayOrQuit(int gameCounter) { bool inputInt; int choice; do//prompt loop { System.Console.WriteLine("Please choose 1 for Play or 2 for Quit"); string input = Console.ReadLine(); inputInt = int.TryParse(input, out choice); } while (!inputInt || choice <= 0 || choice >= 3);//end of promt loop System.Console.WriteLine($"\n\t\tThis is game #{gameCounter++}\n\n"); return choice; //System.Console.WriteLine("made it out of the loop"); } }//end of program }//end of namaespace
f10e00d0f835123aa7cd6d2e8b1df5b90807c968
C#
Objia/Altman2.2.1
/Altman/Logic/ShellExtra.cs
2.90625
3
using System.Net; using System.Xml; namespace Altman.Logic { /// <summary> /// 保存和提取shell扩展字符串(包括指定http头部字段和数据库连接字符串格式)的相关信息(调用了ShellExtraHandle类的方法) /// </summary> internal class ShellExtra { private string _shellExtraString; public ShellExtra(string shellExtraString) { this._shellExtraString = shellExtraString; } /// <summary> /// 提取shell扩展字符串中的http头部字段信息,并生成xml节点 /// </summary> public XmlNode HttpHeaderXml { get { return ShellExtraHandle.GetHttpHeaderXml(_shellExtraString);} } /// <summary> /// 提取shell扩展字符串中的数据库连接信息,并生成xml节点 /// </summary> public XmlNode SqlConnectionXml { get { return ShellExtraHandle.GetSqlConnectionXml(_shellExtraString); } } /// <summary> /// shell扩展字符串中http头部字段信息 /// </summary> public WebHeaderCollection HttpHeader { get { WebHeaderCollection header = new WebHeaderCollection(); foreach (var i in ShellExtraHandle.GetHttpHeaderList(_shellExtraString)) { header.Add(i.Key, i.Value); } return header; } } } }
2835290f3f33429d50e9aabdbf4689a7a93738f8
C#
aserowy/hackathonblazor_prosr_adminui
/BlazorHub/Client/Business/MessageResolver.cs
2.5625
3
using prosr.Parser.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text.Json; namespace BlazorHub.Client.Business { public interface IMessageResolver { Message GetByName(string ident); Type GetType(string ident); object GetObject(string ident, string json); } internal class MessageResolver : IMessageResolver { private readonly ITypeResolver _typeResolver; private readonly Ast _ast; public MessageResolver(ITypeResolver typeResolver, Ast ast) { _typeResolver = typeResolver; _ast = ast; _typeResolver.Initialize(_ast); } public Message GetByName(string ident) { return _ast .Nodes .SelectMany(nd => nd is Package package ? package.Nodes : new List<INode>() { nd }) .OfType<Message>() .SingleOrDefault(msg => msg.Ident == ident); } public Type GetType(string ident) { return _typeResolver.Get(ident, false); } public object GetObject(string ident, string json) { return JsonSerializer.Deserialize(json, GetType(ident)); } } }
70af4b206fd9a10dfdddd04c320e7b83774b7da4
C#
mohaanwrites/play-csharp
/Class/SampleInherited.cs
3.171875
3
using System; namespace MasteringCSharp.Class { public class SampleInherit : SampleBase { private protected SampleHelper GetHelperInstance() { return new SampleHelper(); } public SampleInherit(int id) : base(id) { ChildMessage = nameof(SampleInherit); } public sealed override void DisplayId() { GetHelperInstance().DoSomething(); Console.WriteLine($"From {nameof(SampleInherit)}:\n Id = {Id} | Identifier = {Identifier} | Message: {ChildMessage} | Key: {Key}"); } public sealed override string Key => "Changed Key"; public override void SayGreetings() => Console.WriteLine($"Hello! from {nameof(SampleInherit)}"); } }
1f615bf625359bb9461ae58d758b6e7951357f87
C#
tuncayalt/vscode-cs-exercises
/Actions.cs
3.640625
4
using System; using System.Reflection; public class Actions { public static void useActions() { Console.WriteLine("using Action"); Calculate(1,2,add); Calculate(1,2,subtract); Calculate(1,2, (a,b) => { Console.WriteLine(a * b); }); } private static void add (int a, int b) { Console.WriteLine(a + b); } private static void subtract (int a, int b) { Console.WriteLine(a - b); } private static void Calculate(int a, int b, Action<int,int> MyAction) { MyAction.Invoke(a, b); } }
37aedfb85c9637c1683b1479e7e4030626ca101b
C#
ChrisMissal/Bender
/src/Bender/DeserializeExceptions.cs
2.859375
3
using System; using System.Reflection; using System.Xml; using System.Xml.Linq; namespace Bender { public class DeserializeException : Exception { public DeserializeException(PropertyInfo property, XObject node, Format format, string message, params object[] args) : base(propertyMessage(property, node, message, args, format)) { } public DeserializeException(PropertyInfo property, XObject node, Format format, Exception exception, string message, params object[] args) : base(propertyMessage(property, node, message, args, format), exception) { } public DeserializeException(Type type, string message) : base("Unable to deserialize type {0}: {1}".ToFormat(type, message)) { } private static readonly Func<PropertyInfo, XObject, string, object[], Format, string> propertyMessage = (p, n, m, a, f) => "Unable to set {0}.{1} to the value in the '{2}' {3}: {4}".ToFormat( p.DeclaringType.FullName, p.Name, n.GetPath(f), n.ObjectType(), m.ToFormat(a)); } public abstract class SourceException : Exception { protected SourceException(string debugMessage, string friendlyMessage, Exception innerException) : base(debugMessage, innerException) { FriendlyMessage = friendlyMessage; } protected SourceException(string debugMessage, string friendlyMessage) : base(debugMessage) { FriendlyMessage = friendlyMessage; } public string FriendlyMessage { get; private set; } } public class UnmatchedNodeException : SourceException { public UnmatchedNodeException(ValueNode node) : base("The '{0}' {1} does not correspond to a type or property.".ToFormat( node.Object.GetPath(node.Format), node.NodeType.ToFriendlyNodeType()), "Unable to read {0}: The '{1}' {2} is not recognized.".ToFormat(node.Format.ToString().ToLower(), node.Object.GetPath(node.Format), node.NodeType.ToFriendlyNodeType())) { } } public class SourceParseException : SourceException { public SourceParseException(XmlException exception, Format format) : base(exception.Message, "Unable to parse {0}: {1}".ToFormat(format.ToString().ToLower(), exception.Message), exception) { } public XmlException ParseException { get { return (XmlException) InnerException; } } } public class ValueParseException : SourceException { public ValueParseException(ReaderContext context, ParseException exception) : this(context.Property, context.Node, exception) { } public ValueParseException(ReaderContext context, string friendlyMessage, Exception exception) : this(context.Property, context.Node, friendlyMessage, exception) { } public ValueParseException(PropertyInfo property, ValueNode node, ParseException exception) : this(property, node, exception.FriendlyMessage, exception) { } public ValueParseException(PropertyInfo property, ValueNode node, string friendlyMessage, Exception exception) : base("Unable to parse the value {0} in the '{1}' {2} as a {3} into {4}.{5}: {6}".ToFormat( GetFriendlyValue(node), node.Object.GetPath(node.Format), node.NodeType.ToFriendlyNodeType(), property.PropertyType.Name, property.DeclaringType.FullName, property.Name, exception.Message), "Unable to parse the value {0} in the '{1}' {2} as a {3}: {4}".ToFormat( GetFriendlyValue(node), node.Object.GetPath(node.Format), node.NodeType.ToFriendlyNodeType(), property.PropertyType.ToFriendlyType(), friendlyMessage), exception) { Value = node.Value; XPath = node.Object.GetPath(node.Format); Node = node; ParseErrorMessage = friendlyMessage; ClrType = property.PropertyType; FriendlyType = property.PropertyType.ToFriendlyType(); } public string Value { get; private set; } public string XPath { get; private set; } public ValueNode Node { get; private set; } public string ParseErrorMessage { get; private set; } public Type ClrType { get; private set; } public string FriendlyType { get; private set; } private static string GetFriendlyValue(ValueNode node) { return node.Value == null ? "<null>" : "'" + node.Value.TruncateAt(50) + "'"; } } public static class NodeTypeExtensions { public static string ToFriendlyNodeType(this NodeType nodeType) { switch (nodeType) { case NodeType.JsonField: return "field"; case NodeType.XmlAttribute: return "attribute"; default: return "element"; } } } }
66fcd8312ab2527cb16089ac0d0087fa027ddd03
C#
IvanPopik05/PrototypeMultiplayer2D
/Assets/Scripts/Bullet.cs
2.640625
3
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Bullet : MonoBehaviour { [SerializeField] private float speed; Rigidbody2D _rb; private void Start() { _rb = GetComponent<Rigidbody2D>(); StartCoroutine(Shoot()); } private IEnumerator Shoot() { _rb.velocity = transform.right * speed * Time.deltaTime; yield return new WaitForSeconds(1); Destroy(gameObject); } private void OnCollisionEnter2D(Collision2D collision) { if (collision.collider.name == "Player1") { PlayerHealth.TakingLives(6); Destroy(gameObject); } else if (collision.collider.name == "Player2") { PlayerHealth2.TakingLives(6); //Destroy(gameObject); } } }
0aebf88445d9031f0a9dbeaaaa17c7a470883121
C#
SimonDarksideJ/XNAGameStudio
/Samples/TouchThumbsticksSample_4_0/TouchThumbSticks/TouchThumbSticks/Ship.cs
2.890625
3
//----------------------------------------------------------------------------- // Ship.cs // // Microsoft Advanced Technology Group // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace TouchThumbsticks { /// <summary> /// A base class for all ships in our game. /// </summary> public abstract class Ship { /// <summary> /// The texture used to draw the ship. /// </summary> private Texture2D texture; /// <summary> /// The position of the ship in the game world. /// </summary> public Vector2 Position; /// <summary> /// The ship's velocity. /// </summary> public Vector2 Velocity; /// <summary> /// The ship's rotation. /// </summary> public float Rotation; public Ship(Texture2D texture) { this.texture = texture; } /// <summary> /// Does the ship contain the current point? Used for collision detection /// with the bullets. /// </summary> /// <param name="point">The point to test.</param> /// <returns>True if the ship contains the point, false otherwise.</returns> public virtual bool ContainsPoint(Vector2 point) { return false; } /// <summary> /// Allows the ship to update. /// </summary> /// <param name="gameTime">The current game timestamp.</param> public virtual void Update(GameTime gameTime) { } /// <summary> /// Allows the ship to draw. /// </summary> /// <param name="spriteBatch">The SpriteBatch to draw with.</param> public virtual void Draw(SpriteBatch spriteBatch) { spriteBatch.Draw( texture, Position, null, Color.White, Rotation, new Vector2(texture.Width / 2f, texture.Height / 2f), 1f, SpriteEffects.None, 0f); } } }
bb1a8fac4d682e4e9b7c43c035cb749b8eae79e5
C#
zduan001/BusAroundMe
/Console/3sum/004_ClimbStairs.cs
4.15625
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace console { public class _004_ClimbStairs { /// <summary> /// You are climbing a stair case. It takes n steps to reach to the top. /// each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? /// </summary> /// <param name="n">number of steps</param> public int ClimbStairs(int n) { int[] array = new int[n]; array[0] = 1; array[1] = 2; for (int i = 2; i < n; i++) { array[i] = array[i - 2] + array[i - 1]; } return array[n - 1]; } /// <summary> /// Same as last method, only use O(1) space. /// </summary> /// <param name="n"></param> /// <returns></returns> public int ClimbStarisWithO1(int n) { int[] array = new int[3] { 1, 2, 3 }; for (int i = 3; i < n; i++) { array[(i)%3] = array[(i-1)%3] + array[(i-2)%3]; } return array[(n-1) % 3]; } } }
ee02175c6aca9da67c18057ac20d9c843fe75e4c
C#
danielavillamar/LAB8
/Flashlight.cs
2.5625
3
using System.Collections; using UnityEngine; using System.Collections.Generic; public class Flashlight : MonoBehaviour { public KeyCode flashlightkey = KeyCode.Mouse0; public float batterylifesec = 60f; //(60 segundos dura bateria de la camara) public float maxIntensity = 1f; private readonly float intensity = 1f; private float batteryLife; private bool isActive; public AudioSource myAudioSource; private Light myLight; private void Start() { myAudioSource = myAudioSource.GetComponent<AudioSource>(); myLight = GetComponent<Light>(); batteryLife = myLight.intensity; } void Update() { if (Input.GetKeyDown(flashlightkey)) { isActive = !isActive; myAudioSource.Play(); } if (isActive) { myLight.enabled = true; myLight.intensity -= batteryLife / batterylifesec * Time.deltaTime; } else { myLight.enabled = false; } } public void AddBatteryLife(float _batterypower) { myLight.intensity += _batterypower; if (myLight.intensity > maxIntensity) myLight.intensity = maxIntensity; } }
db068b2a306a3df16ebefb923583afc03fd1085d
C#
KavinduT/CodeTest
/CodeTestAPI/CodeTestAPI/Services/MoviesService.cs
2.734375
3
using System; using System.Collections.Generic; using System.Net.Http; using System.Net.Http.Headers; using CodeTest.Models.DataRepo; using Newtonsoft.Json; namespace CodeTest.API.Services { public class MoviesService : IMoviesService { public IEnumerable<FilmDTO> GetMovies() { //TODO: Maintain the result to the external web service in a cash. //TODO: Check the Movies data collection is available in the cash. //TODO: If movie collection is available in the cash, return the cashed Movies data as the results. try { using (var client = new HttpClient()) { client.BaseAddress = new Uri("http://alintacodingtest.azurewebsites.net"); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage response = client.GetAsync("api/Movies").Result; if (!response.IsSuccessStatusCode) return new List<FilmDTO>(); var data = response.Content.ReadAsStringAsync().Result; return JsonConvert.DeserializeObject<List<FilmDTO>>(data); } } catch (Exception ex) { //TODO: Log exceptions errors. return new List<FilmDTO>(); } } } }
1330b78c2c1055e39f639f913944c14c40bd4006
C#
Still34/RaffleBlazor
/RaffleBlazor/Utility/EnumerableUtility.cs
3.28125
3
using System; using System.Collections.Generic; namespace RaffleBlazor.Utility { public class EnumerableUtility { private readonly Random _random; public EnumerableUtility(Random random) => _random = random; /// <seealso href="https://stackoverflow.com/a/1262619" /> public List<T> Shuffle<T>(List<T> list) { var n = list.Count; while (n > 1) { n--; var k = _random.Next(n + 1); var value = list[k]; list[k] = list[n]; list[n] = value; } return list; } } }
e3628763cc641408062b0e99e82cebf89f0693b7
C#
pgillett/AdventOfCode2020
/Advent/AdventTest/Day25Test.cs
2.578125
3
using Advent; using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace AdventTest { [TestClass] public class Day25Test { private Day25 _day25; [TestInitialize] public void Setup() { _day25 = new Day25(); } [TestMethod] public void SampleEncryptionKeyIs14897079() { var expected = 14897079; var actual = _day25.EncryptionKey(_input); actual.Should().Be(expected); } private string _input = @"5764801 17807724"; } }
d249b0b1ba8330f58b4580110691caa3d174c5ed
C#
icameisawibeatboxed/DownWithTheMonarchJulia
/Assets/CubeManager.cs
2.828125
3
using UnityEngine; using System.Collections; public class CubeManager : MonoBehaviour { public GameObject[] cubes;//= new GameObject[4]; int theCubeNumberYoureLookingFor=0; // Use this for initialization void Start () { for(int i = 0; i < cubes.Length; i++)//look up for loops { cubes[i].renderer.enabled = false; cubes[i].GetComponent<Cube>().cubeNumber=i;//this line is setting the cube number for each cube cubes[i].GetComponent<Cube>().manager = this;//this line sets the cubes manager variable to not null } } // Update is called once per frame void Update () { } public void cubeWasHit(int cubeNumber) { if (cubeNumber == theCubeNumberYoureLookingFor) { cubes[cubeNumber].renderer.enabled = true; print ("found " + cubeNumber); theCubeNumberYoureLookingFor = theCubeNumberYoureLookingFor + 1; } } }
c4abed399f064ef5da08a264f6a6c662a7220667
C#
ramanmiddha90/PeerIsland-SqlParser
/PeerIsland.SqlQueryGenrator/QueryGenerators/IQueryGenerator.cs
2.546875
3
using PeerIsland.SqlQueryGenerator.Configuration.SqlClauses; using System; using System.Collections.Generic; namespace PeerIsland.SqlQueryGenrator.QueryGenerators { /// <summary> /// Implement this interface for generated query for other provider /// </summary> public interface IQueryGenerator { /// <summary> /// Implement this function to parse string with given provider /// </summary> /// <param name="Input">Source</param> /// <param name="clauses">All Source elements in form of Abstract Clause /// Create own configuration provider and generate clauses</param> /// <returns></returns> public string Generate(string Input, Func<IList<AbstractClause>, string> clauses); } }
3092c8181adefe92a9f8da2deaa1614c4e219671
C#
ctrlcommunity/Ctrl.Framework
/src/CtrlCloud.Framework.Domain.Shared/OperateStatus.cs
2.625
3
using System.Collections.Generic; using CtrlCloud.Framework.Core.Properties; namespace Ctrl.Core.Entities { /// <summary> /// 调用服务或业务逻辑返回标识枚举,使用DataContract特性,表示可序列化 /// </summary> public enum ResultSign { /// <summary> /// 操作成功 /// </summary> Successful, /// <summary> /// 警告 /// </summary> Warning, /// <summary> /// 操作引发错误 /// </summary> Error } /// <summary> /// 调用调用服务或业务逻辑的操作状态,使用DataContract特性,表示可序列化 /// </summary> public class OperateStatus { #region 构造函数 /// <summary> /// 构造函数:默认为失败 /// </summary> public OperateStatus() { ResultSign = ResultSign.Error; Message = Chs.Error; } public OperateStatus(OperateStatus status) { ResultSign = status.ResultSign; Message = status.Message; FormatParams = status.FormatParams; } #endregion #region 属性 /// <summary> /// 返回标记 /// </summary> public ResultSign ResultSign { get; set; } /// <summary> /// 消息字符串(有多语言后将删除该属性) /// </summary> public string Message { get; set; } /// <summary> /// 消息的参数 /// </summary> public List<string> FormatParams { get; set; } #endregion } /// <summary> /// 返回结果带实体信息 /// </summary> /// <typeparam name="T">实体信息</typeparam> public class OperateStatus<T> : OperateStatus { public T Data { get; set; } } }
ee06a1aefacb823e9e1f86a7756edfe0ee7c5a09
C#
pafik13/SOPtemp
/SalesOfPharmacy/fListDrugs.cs
2.671875
3
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using MySql.Data.MySqlClient; namespace SalesOfPharmacy { public partial class fListDrugs : Form { Dictionary<string, string> context; private MySqlConnection conn = null; DataSet dataset = null; private int currentRow = -1; public fListDrugs() { InitializeComponent(); context = new Dictionary<string, string>(); dataset = new DataSet(); } internal void AddContext(string key, string value) { context.Add(key, value); } internal void AddContext(MySqlConnection connection) { conn = connection; } private void fListChains_Shown(object sender, EventArgs e) { gvDrugs.DataSource = new BindingSource(); if (conn.State == ConnectionState.Open) { if (dataset.Tables.Count > 0) { ((BindingSource)gvDrugs.DataSource).DataSource = dataset.Tables[0]; } } else { MessageBox.Show("Нет соединения с базой данных. Проверьте работоспособность БД.", "Отсутствует соединение", MessageBoxButtons.OK, MessageBoxIcon.Warning); gvMenu.Enabled = false; } } public void LoadDrugs() { if (conn.State == ConnectionState.Open) { string command = "SELECT d.id, d.name FROM tbl_drugs d ORDER BY d.name"; MySqlCommand cmd = new MySqlCommand(command, conn); MySqlDataAdapter adapter = new MySqlDataAdapter(cmd); adapter.Fill(dataset); } } private void gvDrugs_CellContextMenuStripNeeded(object sender, DataGridViewCellContextMenuStripNeededEventArgs e) { if (e.RowIndex > -1) { currentRow = e.RowIndex; } } private void gvDrugs_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e) { if ((e.Button == MouseButtons.Right) && (e.RowIndex > -1)) { // Add this gvDrugs.CurrentCell = gvDrugs.Rows[e.RowIndex].Cells[e.ColumnIndex]; } } private void mi_DelDrug_Click(object sender, EventArgs e) { if (currentRow != -1) { string command = "DELETE FROM tbl_drugs WHERE id = @id"; MySqlCommand cmd = new MySqlCommand(command, conn); cmd.Parameters.AddWithValue("@id", gvDrugs.Rows[currentRow].Cells[0].Value); if (cmd.ExecuteNonQuery() == 1) { MessageBox.Show("Deleted!"); LoadDrugs(); } else { MessageBox.Show("Not deleted! Try again!"); } } } private void gvDrugs_MouseDown(object sender, MouseEventArgs e) { if (gvDrugs.RowCount == 0) { mi_EditDrug.Enabled = false; mi_DelDrug.Enabled = false; } else { mi_EditDrug.Enabled = true; mi_DelDrug.Enabled = true; } } private void mi_AddChain_Click(object sender, EventArgs e) { fEditDrug edt = new fEditDrug(); edt.Text = "Добавление препарата"; edt.AddContext(conn); if (edt.ShowDialog() == DialogResult.OK) { LoadDrugs(); gvDrugs.CurrentCell = gvDrugs.Rows[gvDrugs.RowCount - 1].Cells[1]; } } private void mi_EditChain_Click(object sender, EventArgs e) { fEditDrug edt = new fEditDrug(); edt.Text = "Редактирование препарата"; edt.AddContext(conn); if (currentRow != -1) { edt.AddContext("ID", gvDrugs.Rows[currentRow].Cells[0].Value.ToString()); } if (edt.ShowDialog() == DialogResult.OK) { LoadDrugs(); gvDrugs.CurrentCell = gvDrugs.Rows[currentRow].Cells[1]; } } } }
8133baa135ac5e339d32e68f21354103dd8fc810
C#
mkubasz/other
/DumbSearchEngine/DumbSearchEngine/Stemmer.cs
3.1875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DumbSearchEngine { public class Stemmer { public static IEnumerable<Stem> Stem(string word) { int len = word.Length; for (var i = 1; i <= len; i++) yield return new Stem { Word = word.Substring(0, i), Score = (double)i / len }; for (var i = 1; i < len; i++) yield return new Stem { Word = word.Substring(i, len - i), Score = (double)(len - i) / len }; } } }
1e850e7c9555cc4781c926818dfad3d9dd0040df
C#
philanderson888/c-sharp
/ASP_MVC_Core_ContosoUniversity_03/Pages/About.cshtml.cs
2.578125
3
using ContosoUniversity.Models.SchoolViewModels; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.EntityFrameworkCore; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using ContosoUniversity.Models; namespace ContosoUniversity.Pages { public class AboutModel : PageModel { private readonly SchoolContext _context; public AboutModel(SchoolContext context) { _context = context; } public IList<EnrollmentDateGroup> Student { get; set; } public async Task OnGetAsync() { IQueryable<EnrollmentDateGroup> data = from student in _context.Student group student by student.EnrollmentDate into dateGroup select new EnrollmentDateGroup() { EnrollmentDate = dateGroup.Key, StudentCount = dateGroup.Count() }; Student = await data.AsNoTracking().ToListAsync(); } } }
c4f2ffa62602fca083ba876147f44343239e3959
C#
agaddampalli/Algorithms
/Chapter 7 - Tree/IsValidBST.linq
2.9375
3
<Query Kind="Program" /> void Main() { var root = new TreeNode(2147483647); root.left = new TreeNode(1); // root.right = new TreeNode(30); // root.right.left = new TreeNode(1); // root.right.left.right = new TreeNode(15); // root.right.left.right.right = new TreeNode(45); IsValidBST(root).Dump(); } public class TreeNode { public int val; public TreeNode left; public TreeNode right; public TreeNode(int x) { val = x; } } public bool IsValidBST(TreeNode root) { if (root == null) { return true; } var queue = new Queue<Tuple<long, TreeNode, long>>(); queue.Enqueue(Tuple.Create(Int64.MinValue, root, Int64.MaxValue)); while (queue.Count > 0) { var tuple = queue.Dequeue(); var left = tuple.Item1; var node = tuple.Item2; var right = tuple.Item3; if(node.val <= left || node.val >= right) { return false; } if (node.left != null) { queue.Enqueue(Tuple.Create(left, node.left, (long)node.val)); } if (node.right != null) { queue.Enqueue(Tuple.Create((long)node.val, node.right, right)); } } return true; }
90813350ca2dc59a4b9e0a7704720cf05f7f5918
C#
thailyn/LootGainAnalysis
/LootGainLib/DecisionTreeNode.cs
2.8125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LootGainLib { public class DecisionTreeNode { private DataSourcesCollection _sources; public DataSourcesCollection Sources { get { return _sources; } set { _sources = value; RefreshSourcesInformation(); } } private int _itemId; public int ItemId { get { return _itemId; } set { _itemId = value; RefreshSourcesInformation(); } } public double Entropy { get; set; } public double Probability { get; set; } public DataSourcesCollection Positive { get; set; } public DataSourcesCollection Negative { get; set; } public Attribute ParentSplitAttribute { get; set; } public object ParentSplitAttributeValue { get; set; } public Attribute SplitAttribute { get; set; } public object SplitAttributeValue { get; set; } public double SplitAttributeInformationGain { get; set; } public Dictionary<object, DecisionTreeNode> Children { get; set; } public DecisionTreeNode() { Children = new Dictionary<object, DecisionTreeNode>(); } protected void RefreshSourcesInformation() { if (Sources != null && Sources.Count > 0) { Entropy = Sources.EntropyOnItemId(ItemId); DataSourcesCollection positive, negative; Sources.DivideOnHavingItem(ItemId, out positive, out negative); Probability = (double) positive.Count / Sources.Count; Positive = positive; Negative = negative; } else { Entropy = double.NaN; Probability = double.NaN; Positive = null; Negative = null; } } public void CreateChildrenOnItemId(int itemId, AttributeValues attributeValues) { if (double.IsNaN(Entropy) || Entropy < 0.0001) { //System.Console.WriteLine("Will not create children. Entropy of {0} is below threshold.", Entropy); return; } Attribute bestAttribute; object bestAttributeValue; SplitAttributeInformationGain = Sources.FindGreatestInformationGain(itemId, attributeValues, out bestAttribute, out bestAttributeValue); SplitAttribute = bestAttribute; SplitAttributeValue = bestAttributeValue; //if (SplitAttributeInformationGain < Entropy / 100) if (SplitAttributeInformationGain < Entropy / 10000000) { //System.Console.WriteLine("Will not create children. Information gain of {0} is below threshold.", // SplitAttributeInformationGain); return; } Dictionary<object, DataSourcesCollection> splits; Sources.DivideOnAttribute(bestAttribute, bestAttributeValue, attributeValues.ValuesMap[bestAttribute], out splits); Parallel.ForEach(splits, split => { split.Value.UseAttributesWithValues = Sources.UseAttributesWithValues; DecisionTreeNode child = new DecisionTreeNode { Sources = split.Value, ItemId = itemId, ParentSplitAttribute = SplitAttribute, ParentSplitAttributeValue = split.Key, }; lock(Children) { Children.Add(split.Key, child); } child.CreateChildrenOnItemId(itemId, attributeValues); }); } public override string ToString() { var builder = new StringBuilder(); if (ParentSplitAttributeValue != null) { builder.Append(string.Format("{0}: {1}", ParentSplitAttribute.ToString(), ParentSplitAttributeValue.ToString())); } else { builder.Append("N/A"); } builder.Append(string.Format(", {0}% ({1}/{2}) / {3}", Probability * 100.0, Positive.Count, Sources.Count, Entropy)); builder.Append(" -> "); if (SplitAttributeInformationGain > 0) { builder.Append(SplitAttribute.ToString()); } else { builder.Append("N/A"); } return builder.ToString(); } public void ConsolePrint(string indent) { System.Console.WriteLine(indent + ToString()); foreach (var child in Children) { if (child.Value.Probability > 0) { child.Value.ConsolePrint(indent + "\t"); } } } } }
bd182b04cf7a2c7b77f023761f49eedeab2887b9
C#
melari/DATreconstruct
/DATreconstruct/Program.cs
3.375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace DATreconstruct { class Program { static void Main(string[] args) { if (args.Length < 2 || args.Length > 3) { Console.WriteLine("Syntax: DATreconstruct infile.bin outfile.txt <options>"); Console.WriteLine("Options: -l : Use little endian instead of big."); return; } if (!System.IO.File.Exists(args[0])) { Console.WriteLine("Error: File '" + args[0] + "' does not exist."); return; } byte[] bytes = System.IO.File.ReadAllBytes(args[0]); bool firstHalf = true; bool firstByte = true; byte first = 0x0; StringBuilder sb = new StringBuilder(bytes.Length/2*6+4); sb.Append("DAT "); foreach (byte b in bytes) { if (args.Length > 2 && args[2] == "-l") { if (firstHalf) { first = b; } else { if (!firstByte) { sb.Append(", "); } else { firstByte = false; } sb.Append("0x"); sb.AppendFormat("{0:x2}", b); sb.AppendFormat("{0:x2}", first); } firstHalf = !firstHalf; } else { if (firstHalf) { if (!firstByte) { sb.Append(", "); } else { firstByte = false; } sb.Append("0x"); sb.AppendFormat("{0:x2}", b); } else { sb.AppendFormat("{0:x2}", b); } firstHalf = !firstHalf; } } System.IO.File.WriteAllText(args[1], sb.ToString()); } } }
32e7e6e31494c043baf3befb09e724307e798391
C#
war-man/Cfood
/V308CMS.Data/LinkRepository.cs
2.703125
3
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Security.Cryptography; using System.Text; namespace V308CMS.Data { public interface LinkInterfaceRepository { string Insert(string url, int uid, string source, string taget, string name, string summary); } public class LinkRepository : LinkInterfaceRepository { private V308CMSEntities entities; public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { if (this.entities != null) { this.entities.Dispose(); this.entities = null; } } } public LinkRepository(V308CMSEntities mEntities) { this.entities = mEntities; } public string Insert(string url, int uid , string source = "", string taget = "", string name = "", string summary = "") { try { var link = new AffiliateLink { url = url, code = HashCode(), source = source, taget = taget, name = name, summary = summary, created = DateTime.Now, created_by = uid }; entities.AffiliateLink.Add(link); entities.SaveChanges(); return link.ID.ToString(); } catch (Exception ex) { return ex.ToString(); } } private string HashCode(string code = "") { if (code.Length < 1) { code = Guid.NewGuid().ToString().GetHashCode().ToString("x").ToUpper(); } var check_exit = from l in entities.AffiliateLink where l.code.ToUpper().Equals(code) select l; return check_exit.Count() < 1 ? code : HashCode(); } public int PageSize = 20; public List<AffiliateLink> GetItems(int pcurrent = 1) { List<AffiliateLink> mList = null; try { var links = from l in entities.AffiliateLink orderby l.ID descending select l; mList = links.Skip((pcurrent - 1) * PageSize) .Take(PageSize).ToList(); return mList; } catch (Exception ex) { Console.Write(ex); throw; } } public int GetItemsTotal() { try { var products = from p in entities.AffiliateLink orderby p.ID descending select p; return products.Count(); } catch (Exception ex) { Console.Write(ex); throw; } } } }
2bec4c8e04f648174541658b266e516744db567b
C#
BardenSAE/tankymctankface
/Assets/Chris/GAM112v4 - Chris Scripts - Git/Assets/Scripts/MouseSelector.cs
2.671875
3
using UnityEngine; using System.Collections; public class MouseSelector : MonoBehaviour { private GameObject target; // Update is called once per frame void Update () { // define a ray from the camera to the mouse cursor // beginning at the screen and extending to infinity Ray ray = GetComponent<Camera>().ScreenPointToRay(Input.mousePosition); // use hitInfo to store ray collision infomation RaycastHit hitInfo; // cast a ray and check what it collides with if (Physics.Raycast (ray, out hitInfo)) { hitInfo.transform.SendMessage("HitByRay"); } } }
2f13df3a2d38179d2d243bad83d91d9d2e76c614
C#
Lakthinda/CSVFileReader
/ReadCSV.Test/ServiceManagerTest.cs
2.671875
3
using Moq; using ReadCSV.Contracts.Models; using ReadCSV.Requests; using ReadCSV.Responses; using ReadCSV.Services; using System; using System.Collections.Generic; using System.Linq; using Xunit; namespace ReadCSV.Test { public class ServiceManagerTest { private readonly ServiceManager sut; private readonly Mock<ICSVFileService> cSVFileService; public ServiceManagerTest() { cSVFileService = new Mock<ICSVFileService>(); sut = new ServiceManager(cSVFileService.Object); } private readonly ReadCSVFilesRequest request = new ReadCSVFilesRequest { FolderPath = "AnyPath", Percentage = 0 }; [Fact] public void DisplayRecords_Throws_Exception_When_Reading_File() { // Arrange cSVFileService.Setup(s => s.ReadCSVFiles(It.IsAny<string>(), It.IsAny<int>())) .Throws(new Exception("Error reading the file")); // Act // Assert Assert.Throws<Exception>(() => sut.DisplayRecords(request)); } [Fact] public void DisplayRecords_Returns_Correct_Results() { // Arrange var displayRecordsList = GetDisplayRecords(); cSVFileService.Setup(s => s.ReadCSVFiles(It.IsAny<string>(), It.IsAny<int>())) .Returns(displayRecordsList); // Act var result = sut.DisplayRecords(request); // Assert Assert.IsType<ReadCSVFilesReponse>(result); Assert.True(result != null); Assert.True(displayRecordsList.ToList().Count() == result.Records.ToList().Count()); Assert.Equal(displayRecordsList.Select(s => s.ToString()).FirstOrDefault(), result.Records.Select(s => s.ToString()).FirstOrDefault()); } private IEnumerable<DisplayRecord> GetDisplayRecords() { var record = new Contracts.Models.Record { Value = "10.50", DateTime = "2019-04-21" }; var recordList = new List<Contracts.Models.Record>(); recordList.Add(record); var displayRecords = new DisplayRecord { Records = recordList, FileName = "Test File Name.csv", Median = 9.5 }; var displayRecordsList = new List<DisplayRecord>(); displayRecordsList.Add(displayRecords); return displayRecordsList; } } }
73ec5d023ccb375b30a29db18a82c6d7b41dfd91
C#
LightBDD/LightBDD
/src/LightBDD.Framework/Formatting/DefaultNameFormatter.cs
3.34375
3
using LightBDD.Core.Formatting; namespace LightBDD.Framework.Formatting { /// <summary> /// Default implementation of <see cref="INameFormatter"/> interface. /// </summary> public class DefaultNameFormatter : INameFormatter { private DefaultNameFormatter() { } /// <summary> /// Returns instance of the <see cref="DefaultNameFormatter"/>. /// </summary> public static DefaultNameFormatter Instance { get; } = new(); /// <summary> /// Formats name into readable text. /// This method applies following replacements:<br/> /// "__" -> ": "<br/> /// "_s_" -> "'s "<br/> /// "_" -> " "<br/> /// </summary> /// <param name="name">Name to format.</param> /// <returns>Formatted text.</returns> public string FormatName(string name) { return name .Replace("__", ": ") .Replace("_s_", "'s ") .Replace("_", " "); } } }
a606e215f6765847f457e0368849ae822991056d
C#
ivanginov7/WebForms3
/WebForms3/Contact.aspx.cs
2.53125
3
using System; using System.Collections.Generic; using System.Linq; using System.Net.Mail; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace WebForms3 { public partial class Contact : Page { protected void Page_Load(object sender, EventArgs e) { } protected void SendMessageButton_Click(object sender, EventArgs e) { if (IsValid) { ContactButton.Enabled = false; var body = "<p>Contact received from {0}</p><p>Message:</p><p>{1}</p>"; var message = new MailMessage(); //message.From = new MailAddress("ivanginovdev@gmail.com"); message.To.Add(new MailAddress(EmailControl.Text)); message.Subject = "Contact form"; message.Body = string.Format(body, EmailControl.Text, MessageControl.Text); message.IsBodyHtml = true; using (var smtp = new SmtpClient()) { //var credentials = new NetworkCredential //{ // UserName = "ivanginovdev@gmail.com", // Password = "Raynor1!" //}; //smtp.UseDefaultCredentials = false; //smtp.Credentials = credentials; //smtp.Host = "smtp.gmail.com"; //smtp.Port = 587; //smtp.EnableSsl = true; try { smtp.Send(message); EmailControl.Text = null; MessageControl.Text = null; SuccessMessage.Visible = true; SucessText.Text = "Email successfully sent"; } catch (Exception ex) { ErrorMessage.Visible = true; FailureText.Text = ex.Message; } finally { ContactButton.Enabled = true; } } } } } }
efc001dce57c4edfb72a81e6782951478cc23c6b
C#
LucasDotEXE/RHIndividueel
/RHIndividueel/ErgoClient/BluetoothLowEnergy/BLESimulator/BLESimulator.cs
2.890625
3
using Client; using System.Collections.Generic; using System.IO; namespace ErgoConnect { /// <summary> /// The WriteOption enumeration defines two options to help identify actions. These are Ergo and Heartrate. /// </summary> public enum WriteOption { Ergo, Heartrate } /// <summary> /// BLESimulator replicates data output by using a 1 : 1 copy of a team member cycling on the ergometer. /// </summary> public class BLESimulator { private readonly List<byte[]> _bytesErgo = new List<byte[]>(); private readonly List<byte[]> _bytesHeartRate = new List<byte[]>(); private readonly string _ergoID; private readonly string _patientName; private readonly string _patientNumber; private readonly IClient _iClient; public BLEDataHandler bLEDataHandler; /// <summary> /// The ergoID is needed to define the save location of the Ergometer data. /// </summary> /// <param name="ergoID"></param> public BLESimulator(string ergoID, IClient iClient, string patientName, string patientNumber) { this._ergoID = ergoID; this._iClient = iClient; this._patientName = patientName; this._patientNumber = patientNumber; } /// <summary> /// Use only for BLEConnect /// </summary> /// <param name="ergoID"></param> public BLESimulator(string ergoID) { this._ergoID = ergoID; } /// <summary> /// Run the simulator with a data transfer time of 4Hz, just like the real protocol. /// </summary> public void RunSimulator() { this.bLEDataHandler = new BLEDataHandler(this._ergoID, this._patientName, this._patientNumber); int i = 0; List<byte[]> data = new List<byte[]>(); while (true) { data = this.ReadData(ApplicationSettings.GetReadWritePath(this._ergoID), WriteOption.Ergo); BLEDecoderErgo.Decrypt(data[i], this.bLEDataHandler); string toSend = this.bLEDataHandler.ReadLastData(); // Data that should be send to the client. this._iClient.Write(toSend); if (i >= data.Count - 1) { i = 0; } i++; System.Threading.Thread.Sleep(250); } } /// <summary> /// Save bytes for record purposes of Ergometer. /// </summary> /// <param name="data"></param> public void SaveBytesErgo(byte[] data) { this._bytesErgo.Add(data); } /// <summary> /// Save bytes for record purposes of heart rate monitor. /// </summary> /// <param name="data"></param> public void SaveBytesHeartRate(byte[] data) { this._bytesHeartRate.Add(data); } /// <summary> /// Read data for simulating purposes. Returns a list of byte[] of data. /// </summary> /// <param name="filePath"></param> /// <param name="ergoOrHeartRate"></param> /// <returns></returns> public List<byte[]> ReadData(string filePath, WriteOption ergoOrHeartRate) { filePath = GetErgoHeartRatePath(filePath, ergoOrHeartRate); List<byte[]> deSerializedObject = ReadToFileBinary<List<byte[]>>(filePath); return deSerializedObject; } /// <summary> /// Read in a file and receive a binary desiralization. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="pathToFile"></param> /// <returns></returns> private static T ReadToFileBinary<T>(string pathToFile) { try { using (Stream stream = File.Open(pathToFile, FileMode.Open)) { System.Runtime.Serialization.Formatters.Binary.BinaryFormatter binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); return (T)binaryFormatter.Deserialize(stream); } } catch (FileNotFoundException) { using (File.Create(pathToFile)) { return ReadToFileBinary<T>(pathToFile); } } } /// <summary> /// Write to file, writeOption is needed to define the path. /// </summary> /// <param name="writeOption"></param> public void WriteData(WriteOption writeOption) { string pathToFile = GetErgoHeartRatePath(ApplicationSettings.GetReadWritePath(this._ergoID), writeOption); List<byte[]> dataToWrite = new List<byte[]>(); switch (writeOption) { case WriteOption.Ergo: dataToWrite = this._bytesErgo; break; case WriteOption.Heartrate: dataToWrite = this._bytesHeartRate; break; } WriteToFileBinary(pathToFile, dataToWrite); } /// <summary> /// Receive the Ergometer or Heart rate data path. /// </summary> /// <param name="pathToFile"></param> /// <param name="ergoOrHeartRate"></param> /// <returns></returns> private static string GetErgoHeartRatePath(string pathToFile, WriteOption ergoOrHeartRate) { string newPath = pathToFile; switch (ergoOrHeartRate) { case WriteOption.Ergo: newPath += "_Ergometer"; break; case WriteOption.Heartrate: newPath += "_HRMonitor"; break; } return newPath; } /// <summary> /// Write binary data to a file (serialize). /// </summary> /// <typeparam name="T"></typeparam> /// <param name="pathToFile"></param> /// <param name="objectToWrite"></param> /// <param name="newFile"></param> private static void WriteToFileBinary<T>(string pathToFile, T objectToWrite, bool newFile = false) { using (System.IO.Stream stream = System.IO.File.Open(pathToFile, newFile ? System.IO.FileMode.Create : System.IO.File.Exists(pathToFile) ? System.IO.FileMode.Truncate : System.IO.FileMode.Create)) { System.Runtime.Serialization.Formatters.Binary.BinaryFormatter binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); binaryFormatter.Serialize(stream, objectToWrite); } } } }
7790e803f37d9ab5ae69b8ff5f3311051172f067
C#
bradmdesign/OoT2DUnity
/Assets/Scripts/Carriable.cs
2.546875
3
using UnityEngine; [RequireComponent(typeof(Collider2D))] [RequireComponent(typeof(Rigidbody2D))] [RequireComponent(typeof(SpriteRenderer))] public class Carriable : MonoBehaviour { public Vector2 carryOffset; public Collider2D Collider2D { get { return m_Collider2D; } } public SpriteRenderer SpriteRenderer { get { return m_SpriteRenderer; } } protected Collider2D m_Collider2D; protected Rigidbody2D m_Rigidbody2D; protected SpriteRenderer m_SpriteRenderer; private float airTime = 0f; private bool hasBeenThrown; private float throwOffset = 0; void Awake() { m_Collider2D = GetComponent<Collider2D>(); m_Rigidbody2D = GetComponent<Rigidbody2D>(); m_SpriteRenderer = GetComponent<SpriteRenderer>(); } void FixedUpdate() { if (hasBeenThrown) { // Have the object "drop" towards the ground while it's in mid-air. m_Rigidbody2D.position = m_Rigidbody2D.position - new Vector2(0, Mathf.Lerp(0, 1, throwOffset)); // @TODO Fix magic numbers. if (transform.forward.normalized.y == -1) { throwOffset += 0.25f * Time.deltaTime; } else { throwOffset += 1f * Time.deltaTime; } airTime += 3.5f * Time.deltaTime; if (airTime >= 1.0f) { Destroy(this.gameObject); } } } /// <summary> /// Toggles the hasBeenThrown flag without any movement being added. /// </summary> public void Drop() { hasBeenThrown = true; } /// <summary> /// Sends the object in the given direction at the given speed. /// </summary> /// <param name="direction">Direction the object is thrown in.</param> /// <param name="speed">Speed the object will travel at.</param> public void Throw(int direction, float speed) { m_Rigidbody2D.bodyType = RigidbodyType2D.Dynamic; m_Rigidbody2D.constraints = RigidbodyConstraints2D.FreezeRotation; switch (direction) { case Constants.Direction.Right: SetVelocity(new Vector2(1, 0), speed); break; case Constants.Direction.Up: SetVelocity(new Vector2(0, 1), speed); break; case Constants.Direction.Left: SetVelocity(new Vector2(-1, 0), speed); break; default: SetVelocity(new Vector2(0, -1), speed); break; } hasBeenThrown = true; } /// <summary> /// Sets the velocity of the object. /// </summary> /// <param name="velocityVector">Vector2 direction to move the object in.</param> /// <param name="speed">Speed the object will travel at.</param> private void SetVelocity(Vector2 velocityVector, float speed) { m_Rigidbody2D.velocity = velocityVector * speed; } /// <summary> /// Destroys the object when it collides after being thrown. /// </summary> /// <param name="collision">Collision2D data about the collision that just occurred.</param> void OnCollisionEnter2D(Collision2D collision) { if (hasBeenThrown) { Destroy(this.gameObject); } } }
4a9ee2d619a2c28044d1f3138fce7962524aa2e7
C#
TimeToPlay/Orbitality
/Assets/Scripts/Controllers/LocalSaveController.cs
2.640625
3
using System; using System.IO; using Models; using UniRx; using UnityEngine; namespace Controllers { /// <summary> /// Serialize/deserialize json into game model /// </summary> public class LocalSaveController { private string gameDataFileName = "saves.json"; private string saveFileName = "saves"; private LocalStorageHelper _localStorageHelper; public LocalSaveController(LocalStorageHelper localStorageHelper) { _localStorageHelper = localStorageHelper; } public void LoadSaveFile(Action<GameModel> onSuccess, Action<string> onFailure) { MainThreadDispatcher.StartUpdateMicroCoroutine( _localStorageHelper.ReaderStringFileAsync(GetCurrentSavePath(), delegate(string s) { if (s == "") { onFailure("empty save file"); return; } var saveStoryModel = JsonUtility.FromJson<GameModel>(s); onSuccess(saveStoryModel); }, onFailure)); } public void SaveProgress(string jsonToSave) { var path = GetCurrentSavePath(); MainThreadDispatcher.StartUpdateMicroCoroutine(_localStorageHelper.WriteString(path, jsonToSave)); } private string GetCurrentSavePath() { return Path.Combine(Application.persistentDataPath, saveFileName); } public bool IsSaveFileExists() { return File.Exists(GetCurrentSavePath()); } } }
a5e53fc00a876602919fa4f15a2d3f9ddbc46451
C#
denisb1/mono-studentska-praksa
/Day4/Day4.Repository/EnrollmentRepository.cs
2.8125
3
using System; using System.Collections.Generic; using System.Data; using System.Linq; using Day4.DAL; using Day4.Models; using Day4.Models.Common; using Day4.Repository.Common; namespace Day4.Repository { public sealed class EnrollmentRepository : IGenericRepository<EnrollmentDto> { public void Add(EnrollmentDto enrollmentDto) { var idNotFound = false; var id = Guid.NewGuid(); do { if (idNotFound) id = Guid.NewGuid(); try { idNotFound = Get(id) != null; } catch (Exception) { idNotFound = false; } } while (idNotFound); new EnrollmentDatabase().Add(new Enrollment(id, enrollmentDto)); } public void Delete(Guid? id) { new EnrollmentDatabase().Delete(id); } public void Update(Guid? id, EnrollmentDto enrollmentDto) { new EnrollmentDatabase().Update(new Enrollment(id, enrollmentDto)); } public EnrollmentDto Get(Guid? id) { var dt = new EnrollmentDatabase().Get(id).Tables["Enrollment"]; return new EnrollmentDto( Guid.Parse(dt.Rows[0]["StudentId"].ToString()), Guid.Parse(dt.Rows[0]["CourseId"].ToString()) ); } public IEnumerable<EnrollmentDto> GetAll() { var dt = new EnrollmentDatabase().GetAll().Tables["Enrollment"]; return (from DataRow dr in dt.Rows select new EnrollmentDto( Guid.Parse(dr["StudentId"].ToString()), Guid.Parse(dr["CourseId"].ToString()) )).ToList(); } public StudentCourse GetJoin(Guid id) { var dt = new EnrollmentDatabase().GetJoin(id).Tables["Enrollment"]; return new StudentCourse( dt.Rows[0]["FirstName"].ToString(), dt.Rows[0]["LastName"].ToString(), dt.Rows[0]["College"].ToString(), int.Parse(dt.Rows[0]["CollegeYear"].ToString()), dt.Rows[0]["CourseName"].ToString(), double.Parse(dt.Rows[0]["Ects"].ToString()) ); } public IEnumerable<StudentCourse> GetJoinAll() { var dt = new EnrollmentDatabase().GetJoinAll().Tables["Enrollment"]; return (from DataRow dr in dt.Rows select new StudentCourse( dr["FirstName"].ToString(), dr["LastName"].ToString(), dr["College"].ToString(), int.Parse(dr["CollegeYear"].ToString()), dr["CourseName"].ToString(), double.Parse(dr["Ects"].ToString()) )).ToList(); } } }
e4c532e9b83714b353f96e583502da3d2b25be99
C#
Benova11/Gotcha
/Gotcha/Assets/Bank/Bank.cs
2.703125
3
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class Bank : MonoBehaviour { [SerializeField] int startingBalance = 150; [SerializeField] int currentBalance; GameManager gameManager; public int CurrentBalance { get { return currentBalance; } } public delegate void BalanceChanged(); public event BalanceChanged OnBalanceChanged; void Awake() { currentBalance = startingBalance; gameManager = FindObjectOfType<GameManager>(); } public void Deposite(int amountToDeposit) { currentBalance += Mathf.Abs(amountToDeposit); OnBalanceChanged(); } public void Withdraw(int amountToWithdraw) { currentBalance -= Mathf.Abs(amountToWithdraw); if (currentBalance < 0) { gameManager.LostGame(); } else { OnBalanceChanged(); } } }
efadbe13249de86c423ae5887eec1957b33c3800
C#
sanfengliao/uwp
/todolist/Model/ListItem.cs
2.5625
3
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; using Windows.Data.Json; using Windows.Storage; using Windows.Storage.AccessCache; using Windows.Storage.Streams; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Media.Imaging; namespace App6.Model { //json序列化是需要的注解 [DataContract] public class ListItem : INotifyPropertyChanged { private String id; // id 唯一标识符 private StorageFile file; // 图片的StorageFile private string img_path; //图片在LocalFolder的存储路径 private ImageSource pic; //图片的ImageSource private string title; // 标题 private string desc; // 详情 private bool? isComplete; //是否完成 private DateTimeOffset date;//时间 public event PropertyChangedEventHandler PropertyChanged; [DataMember(Order =0)] public string Id { get { return id; } set { id = value; } } [DataMember(Order = 1)] public string Title { get { return title; } set { title = value; PropertyChangedHanlder("Title"); } } [DataMember(Order =1)] public string ImgPath { get { return img_path; } set { img_path = value; PropertyChangedHanlder("ImgPath"); } } public ImageSource Pic { get { if (pic == null) { setImage(); } return pic; } set {pic = value; PropertyChangedHanlder("Pic"); } } [DataMember(Order = 3)] public string Desc { get { return desc; } set { desc = value; PropertyChangedHanlder("Desc"); } } [DataMember(Order = 4)] public bool? IsComplete { get { return isComplete; } set { isComplete = value; PropertyChangedHanlder("IsComplete"); } } [DataMember(Order = 5)] public DateTimeOffset Date { set { date = value; PropertyChangedHanlder("Date"); } get { return date; } } public StorageFile File{ set { file = value; PropertyChangedHanlder("File"); } get { if (file == null) { setStorageFileAsync(); } return file; } } public ListItem() { } public ListItem(ImageSource pic, string title, string desc, DateTimeOffset date, string token,StorageFile file ) { this.id = Guid.NewGuid().ToString(); this.pic = pic; this.title = title; this.desc = desc; this.date = date; this.isComplete = false; //this.img_path = id + file.Name.Substring(file.Name.LastIndexOf(".")); this.file = file; } protected void PropertyChangedHanlder(string str) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(str)); } } public string getId() { return this.id; } //设置ImageSource public async void setImage() { StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync(img_path); BitmapImage imgSrc = new BitmapImage(); if (file != null) { using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.Read)) { imgSrc.SetSource(stream); this.Pic = imgSrc; } } } //设置StorageFile public async void setStorageFileAsync() { this.file = await ApplicationData.Current.LocalFolder.GetFileAsync(img_path); } } }
61b869a9ae0521ef89166facf59e074f247555ee
C#
ipritt/CodeFights
/Arcade/SortByHeight/SortByHeight/Program.cs
3.46875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SortByHeight { class Program { static void Main(string[] args) { int[] a = { -1, 150, 190, -1, -1, 160, 180 }; Console.WriteLine(SortByHeight(a)); Console.ReadLine(); } static int[] SortByHeight(int[] a) { int[] newArray = new int[a.Length]; List<int> list = new List<int>(); List<int> treeList = new List<int>(); for(int i = 0; i < a.Length; i++) { if (a[i] == -1) treeList.Add(i); } foreach(int value in a) { if (value != -1) list.Add(value); } list.Sort(); foreach(int value in treeList) list.Insert(value, -1); newArray = list.ToArray(); return newArray; } } }
9793318a2359ab6f7b5b91430cf91621799e6299
C#
computerline1z/sstore-vn
/Source code/sourcecode 19.5/BusinessObjects/PaymentMethodsInfo.cs
2.8125
3
using System; namespace BusinessObjects { public class PaymentMethodsInfo { #region ***** Fields & Properties ***** private int _MethodID; public int MethodID { get { return _MethodID; } set { _MethodID = value; } } private string _MethodName; public string MethodName { get { return _MethodName; } set { _MethodName = value; } } private string _Guide; public string Guide { get { return _Guide; } set { _Guide = value; } } private Int64 _Fee; public Int64 Fee { get { return _Fee; } set { _Fee = value; } } #endregion #region ***** Init Methods ***** public PaymentMethodsInfo() { } public PaymentMethodsInfo(int methodid) { this.MethodID = methodid; } public PaymentMethodsInfo(int methodid, string methodname, string guide, Int64 fee) { this.MethodID = methodid; this.MethodName = methodname; this.Guide = guide; this.Fee = fee; } #endregion } }
2821e815cef19ce49e4807e30e16b18e723309ad
C#
Pranay-bit/ActivityClass-DiagnosticSource
/ActivityClass-DiagnosticSource/ActivityClass.cs
2.953125
3
using System; using System.Collections.Generic; using System.Diagnostics; using System.Net.Http; using System.Text; using System.Threading.Tasks; namespace ActivityClass_DiagnosticSource { public class ActivityClass { private static readonly DiagnosticSource diagnosticSource = new DiagnosticListener(typeof(ActivityClass).FullName); public int GetRandomNumber() { if (diagnosticSource.IsEnabled(typeof(ActivityClass).FullName)) { diagnosticSource.Write($"{typeof(ActivityClass).FullName}.StartGenerateRandom", null); } var number = new Random().Next(); if (diagnosticSource.IsEnabled(typeof(ActivityClass).FullName)) { diagnosticSource.Write($"{typeof(ActivityClass).FullName}.EndGenerateRandom", new {RandomNumber = number }); } return number; } // Activity // var activity = new Activity("MyActivity"); // _diagnostics.StartActivity(activity, new { Property1 = prop1, Property2 = prop2}); // Do work - normal application/Library code // activity.AddBaggage("MyBaggageId", value); // activity.AddTag("MyTagId", value) // _logger.Log(activity.Id); // _logger.Log(activity.ParentId) // _diagnostics.StopActivity(activity, id); public static async Task DoThingAsync(int id) { var activity = new Activity(nameof(DoThingAsync)); if(diagnosticSource.IsEnabled(typeof(ActivityClass).FullName)) { diagnosticSource.StartActivity(activity, new { IdArg = id }); } activity.AddTag("MyTagId", "valueTags"); activity.AddBaggage("MyBaggageId", "valueInBaggage"); var httpClient = new HttpClient(); await httpClient.GetAsync("http://localhost:5000/values"); if (diagnosticSource.IsEnabled(typeof(ActivityClass).FullName)) { diagnosticSource.StopActivity(activity, new { IdArg = id }); } } } }
bb2bcd067d27eba3a4089907aae30fc7aeff5a2c
C#
nescafe2002/AoC-2020
/10 Adapter Array.linq
3.015625
3
<Query Kind="Statements"> <Reference Relative="10 input.txt">C:\Drive\Challenges\AoC 2020\10 input.txt</Reference> <NuGetReference>morelinq</NuGetReference> <Namespace>MoreLinq</Namespace> </Query> var input = @"28 33 18 42 31 14 46 20 48 47 24 23 49 45 19 38 39 11 1 32 25 35 8 17 7 9 4 2 34 10 3".Split("\r\n").Select(int.Parse); input = File.ReadAllLines("10 input.txt").Select(int.Parse); var diffs = new[] { 0 } // Outlet joltage .Concat(input) // Adapter array .OrderBy(x => x) // Adapter order .Window(2) // Take pairs .Select(x => x.Last() - x.First()) // Calc diff .Concat(new[] { 3 }) // Device joltage is 3 higher .GroupBy(x => x) .ToDictionary(x => x.Key, x => x.Count()); (diffs[1] * diffs[3]).Dump("Answer 1"); var sections = new[] { 0 } // Outlet joltage is 0 .Concat(input) // Adapter array .OrderBy(x => x) // Adapter order .Window(2) // Take pairs .Select(x => x.Last() - x.First()) // Calc diff (actually, just 1 or 3) .Split(3) // Split into sections of diff 1, e.g. 32, 35, 36, 37, 38, 39, 42 => 4 .Select(x => x.Count()); // Section length var permutations = new Dictionary<int, long>() { { 0, 1 }, { 1, 1 }, { 2, 2 }, { 3, 4 }, { 4, 7 } }; sections.Aggregate(1L, (acc, x) => acc * permutations[x]).Dump("Answer 2"); // Permutations based on section length: // 1 // 0, 3, 4, 7 // 2 // 0, 3, 4, 5, 8 // 0, 3, 5, 8 // 3 // 0, 3, 4, 5, 6, 9 // 0, 3, 4, 6, 9 // 0, 3, 5, 6, 9 // 0, 3, 6, 9 // 4 // 0, 3, 4, 5, 6, 7, 10 // 0, 3, 4, 5, 7, 10 // 0, 3, 4, 6, 7, 10 // 0, 3, 4, 7, 10 // 0, 3, 5, 6, 7, 10 // 0, 3, 5, 7, 10 // 0, 3, 6, 7, 10
18829bb508456436be1da89d2e41267279639966
C#
ParallaxOW/BookAPIForGraphDemo
/BookGraphAPI/BookData.cs
2.6875
3
using System; using System.IO; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Azure.WebJobs; using Microsoft.Azure.WebJobs.Extensions.Http; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using Newtonsoft.Json; using Microsoft.Azure.Documents.Client; using System.Linq; using BookGraphAPI.Domain; using Microsoft.Azure.Documents.Linq; using System.Collections.Generic; namespace BookGraphAPI { public class BookData { private readonly DocumentClient _client; private string dbName = Environment.GetEnvironmentVariable("dbName"); private string dbCollection = Environment.GetEnvironmentVariable("dbBooksCollection"); public BookData(DocumentClient client) { _client = client; } [FunctionName("GetBooksAsync")] public async Task<IActionResult> GetAsync( [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "books")] HttpRequest req, ILogger log) { log.LogInformation("C# HTTP trigger function processed a request."); FeedOptions queryOptions = new FeedOptions { EnableCrossPartitionQuery = true }; var bookQuery = _client.CreateDocumentQuery<Book>( UriFactory.CreateDocumentCollectionUri(dbName, dbCollection), queryOptions) .AsDocumentQuery(); List<Book> retVal = new List<Book>(); while (bookQuery.HasMoreResults) { var results = await bookQuery.ExecuteNextAsync<Book>(); retVal.AddRange(results); } return new JsonResult(retVal); } [FunctionName("GetBooksByTitleAsync")] public async Task<IActionResult> GetBooksByTitleAsyncGetAsync( [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "books/{title}")] HttpRequest req, string title, ILogger log) { log.LogInformation("C# HTTP trigger function processed a request."); FeedOptions queryOptions = new FeedOptions { EnableCrossPartitionQuery = true }; var bookQuery = _client.CreateDocumentQuery<Book>( UriFactory.CreateDocumentCollectionUri(dbName, dbCollection), queryOptions) .Where(b => b.Title == title).AsDocumentQuery(); List<Book> retVal = new List<Book>(); while (bookQuery.HasMoreResults) { var results = await bookQuery.ExecuteNextAsync<Book>(); retVal.AddRange(results); } return new JsonResult(retVal); } [FunctionName("GetBooksByAuthorIdAsync")] public async Task<IActionResult> GetBooksByAuthorAsyncGetAsync( [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "bookbyauthor/{authorId}")] HttpRequest req, string authorId, ILogger log) { log.LogInformation("C# HTTP trigger function processed a request."); FeedOptions queryOptions = new FeedOptions { EnableCrossPartitionQuery = true }; var bookQuery = _client.CreateDocumentQuery<Book>( UriFactory.CreateDocumentCollectionUri(dbName, dbCollection), queryOptions) .Where(b => b.AuthorId == Guid.Parse(authorId)).AsDocumentQuery(); List<Book> retVal = new List<Book>(); while (bookQuery.HasMoreResults) { var results = await bookQuery.ExecuteNextAsync<Book>(); retVal.AddRange(results); } return new JsonResult(retVal); } [FunctionName("PostBook")] public async Task<IActionResult> PostBookAsync( [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "book")] HttpRequest req, ILogger log) { string requestBody = await new StreamReader(req.Body).ReadToEndAsync(); Book data = JsonConvert.DeserializeObject<Book>(requestBody); string dbName = Environment.GetEnvironmentVariable("dbName"); string dbCollection = Environment.GetEnvironmentVariable("dbBooksCollection"); var doc = await _client.UpsertDocumentAsync(UriFactory.CreateDocumentCollectionUri(dbName, dbCollection), data); var createdBook = JsonConvert.DeserializeObject<Book>(doc.Resource.ToString()); log.LogInformation(JsonConvert.SerializeObject(createdBook)); return new JsonResult(createdBook); } } }
f1cbee81e7d768f6bd9825bd2d538de17582d328
C#
hueblerw/CavemanWorld
/DynamicCavemanWorld/Assets/Classes/Editor/GeneratorTester.cs
2.671875
3
using UnityEngine; using UnityEditor; using NUnit.Framework; public class GeneratorTester { [Test] public void ElevationGeneratorTester() { // Set the world size DataGenerator generator = new DataGenerator(20, 15); // Generate the tested world float[,] array = generator.CreateElevationLayer(); // Generate random coordinates System.Random randy = new System.Random(); int i = randy.Next(0, generator.WORLDX); int j = randy.Next(0, generator.WORLDZ); string map =""; Assert.AreEqual(20, generator.WORLDX); Assert.AreEqual(15, generator.WORLDZ); Assert.GreaterOrEqual(array[0, 0], -3f); Assert.LessOrEqual(array[0, 0], 3f); Assert.AreNotEqual(0f, array[i, j]); for(int x = 0; x < generator.WORLDX; x++) { for (int z = 0; z < generator.WORLDZ; z++) { map += array[x, z] + ", "; } map += "\n"; } Debug.Log(map); } [Test] public void TempGeneratorTester() { // Set the world size DataGenerator generator = new DataGenerator(40, 60); // Generate the tested world float[][,] array = generator.CreateTemperatureLayers(4); // Generate random coordinates System.Random randy = new System.Random(); int i = randy.Next(0, generator.WORLDX); int j = randy.Next(0, generator.WORLDZ); string mapA = ""; string mapB = ""; for (int x = 0; x < generator.WORLDX; x++) { for (int z = 0; z < generator.WORLDZ; z++) { mapA += array[0][x, z] + ", "; mapB += array[1][x, z] + ", "; } mapA += "\n"; mapB += "\n"; } Debug.Log(mapA); Debug.Log(mapB); Assert.AreEqual(40, generator.WORLDX); Assert.AreEqual(60, generator.WORLDZ); Assert.GreaterOrEqual(array[0][0, 0], 30); Assert.LessOrEqual(array[0][0, 0], 110); Assert.GreaterOrEqual(array[0][i, j], 30); Assert.LessOrEqual(array[0][i, j], 110); Assert.GreaterOrEqual(array[1][0, 0], -20); Assert.LessOrEqual(array[1][0, 0], array[0][0, 0] - 15); Assert.GreaterOrEqual(array[1][i, j], -20); Assert.LessOrEqual(array[1][i, j], array[0][i, j] - 15); } [Test] public void StandardLayerTest() { // Set the world size DataGenerator generator = new DataGenerator(40, 50); // Generate the tested world float[,] array = generator.CreateStandardFloatLayer(0.0, 10.0, 1.0); // Generate random coordinates System.Random randy = new System.Random(); int i = randy.Next(0, generator.WORLDX); int j = randy.Next(0, generator.WORLDZ); string map = ""; Assert.AreEqual(40, generator.WORLDX); Assert.AreEqual(50, generator.WORLDZ); Assert.GreaterOrEqual(array[0, 0], 0f); Assert.LessOrEqual(array[0, 0], 10f); Assert.GreaterOrEqual(array[i, j], 0f); Assert.LessOrEqual(array[i, j], 10f); for (int x = 0; x < generator.WORLDX; x++) { for (int z = 0; z < generator.WORLDZ; z++) { map += array[x, z] + ", "; } map += "\n"; } Debug.Log(map); } }
2cbdf4bb0735b0b3da8391917c722cd6a8a2d02d
C#
snownz/Virtual-Intelligence
/VI/VI.Neural/Factory/LayerBuilder.cs
2.546875
3
using System; using VI.Neural.ActivationFunction; using VI.Neural.ANNOperations; using VI.Neural.Node; using VI.Neural.OptimizerFunction; namespace VI.Neural.Factory { public class LayerBuilder { private int size, connections; private float lr, mo, std; private ANNOperationsEnum operation; private ActivationFunctionEnum activation; private EnumOptimizerFunction optmizator; private NodeEnum nodeType; public LayerBuilder(int size, int connections, float lr, float mo, ANNOperationsEnum operation, ActivationFunctionEnum activation, EnumOptimizerFunction optmizator) { this.size = size; this.connections = connections; this.lr = lr; this.mo = mo; this.operation = operation; this.activation = activation; this.optmizator = optmizator; } public LayerBuilder FullSynapse(float std) { this.std = std; return this; } public INeuron Build() { switch (nodeType) { case NodeEnum.Supervised: return BuildSupervised(); case NodeEnum.Unsupervised: return BuildUnsupervised(); default: throw new InvalidOperationException(); } } private INeuron BuildSupervised() { ISupervisedOperations opr = null; IActivationFunction act = null; IOptimizerFunction opt = null; switch (activation) { case ActivationFunctionEnum.ArcTANH: act = new ArcTANHFunction(); break; case ActivationFunctionEnum.TANH: act = new TANHFunction(); break; case ActivationFunctionEnum.Binary: act = new BinaryStepFunction(); break; case ActivationFunctionEnum.LeakRelu: act = new LeakReluFunction(); break; case ActivationFunctionEnum.Relu: act = new ReluFunction(); break; case ActivationFunctionEnum.Sigmoid: act = new SigmoidFunction(); break; case ActivationFunctionEnum.Sinusoid: act = new SinusoidFunction(); break; case ActivationFunctionEnum.Nothing: act = null; break; default: throw new InvalidOperationException(); } switch (optmizator) { case EnumOptimizerFunction.Adagrad: opt = new AdagradOptimizerFunction(); break; case EnumOptimizerFunction.Adadelta: opt = new AdadeltaOptimizerFunction(); break; case EnumOptimizerFunction.Adam: opt = new AdamOptimizerFunction(); break; case EnumOptimizerFunction.Nadam: opt = new NadamOptimizerFunction(); break; case EnumOptimizerFunction.RmsProp: opt = new RMSOptimizerFunction(); break; case EnumOptimizerFunction.SGD: opt = new SGDOptimizerFunction(); break; case EnumOptimizerFunction.Momentum: opt = new MomentumOptmizerFunction(); break; default: throw new InvalidOperationException(); } switch (operation) { case ANNOperationsEnum.Activator: opr = new ANNActivatorOperations(); break; case ANNOperationsEnum.SoftMax: opr = new ANNSoftmaxOperations(); break; default: throw new InvalidOperationException(); } opr.SetActivation(act); opr.SetOptimizer(opt); var neuron = new SupervisedNeuron(size, connections, lr, mo, opr); neuron.FullSynapsis(size, connections, std); return neuron; } private INeuron BuildUnsupervised() { throw new NotImplementedException(); } } }
273f933b90ac99fb5a5f0c7cdafa6eeaaf580a1f
C#
grzabrodskiy/BoxingGame
/First/FighterRanking/EloFighterRanking.cs
2.796875
3
using System; using System.Collections.Concurrent; using log4net; using Main; using Newtonsoft.Json; namespace Boxing.FighterRating { [Serializable] [NewGame] public class EloFighterRating : IFighterRating { [JsonProperty] private ConcurrentDictionary<string, double> Ratings { get; set; } [JsonProperty] public int K { get; } [JsonProperty] double InitElo { get; } static readonly ILog LOGGER = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); public EloFighterRating(int k = 50, double initElo = 1500) { K = k; InitElo = initElo; } /** * Calculate the expected score for the player with rating1 * * @param rating1 The player's rating * @param rating2 The other player's rating * @return The expected score (0-1), where loss=0, draw=0.5, win=1 */ public double CalculateExpectedScore(double Rating1, double Rating2) { return 1 / (1.0 + Math.Pow(10.0, (Rating2 - Rating1) / 400.0)); } /** * Calculate the rating change for the player with rating1 and the given score * * @param rating1 The player's rating * @param rating2 The other player's rating * @param score The player's obtained score, where loss=0, draw=0.5, win=1 * @return The change in rating */ public double CalculateRatingChange(double f1Rating, double f2Rating, double score) { return Math.Round(K * (score - CalculateExpectedScore(f1Rating, f2Rating))); } public bool AddFighter(Fighter fighter) { return Ratings.TryAdd(fighter.Name, InitElo); } public double Rating(Fighter fighter) { return Ratings[fighter.Name]; } public double CalculateRatingChange(Fighter f1, Fighter f2, double score) { double delta = CalculateRatingChange(Rating(f1), Rating(f2), score); Ratings[f1.Name] += delta; Ratings[f2.Name] -= delta; f1.Performance["Elo"] = Ratings[f1.Name]; f2.Performance["Elo"] = Ratings[f2.Name]; return delta; } //public virtual void InitNewGame() DO WE NEED THESE //{ // LOGGER.Debug("Finit Elo New Game"); //} //public virtual void NewGame() //{ // LOGGER.Debug("FiElo New Game"); //} } }
43ba4cb7bcf8e24326619e328171810e57f45b74
C#
davidwmartines/MushMud-Archive
/src/Core/Factories/ImageFileInfoFactory.cs
2.890625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Drawing; using System.IO; using MusicCompany.Core.Services; namespace MusicCompany.Core.Factories { #region Interface public interface IImageFileInfoFactory { /// <summary> /// Returns a new ImageFileInfo instance. /// </summary> ImageFileInfo CreateImage(string originalFileName, FileFormat inputFormat, Stream inputStream); } #endregion #region Implementation public class ImageFileInfoFactory : IImageFileInfoFactory { #region Properties public IImageProcessingService ImageConversionService { get; set; } #endregion public ImageFileInfo CreateImage(string originalFileName, FileFormat inputFormat, Stream inputStream) { if (!inputFormat.IsImageType()) { throw new InvalidOperationException(string.Format("{0} is not a supported image format.", inputFormat)); } Size size = this.ImageConversionService.GetSize(inputStream); string colorMode = string.Empty; //TODO byte[] fileBytes = inputStream.GetBytes(); BinaryFileData binaryFileData = new BinaryFileData(fileBytes); ImageFileInfo imageFile = new ImageFileInfo(Path.GetFileName(originalFileName), inputFormat, fileBytes.Length, binaryFileData, size.Width, size.Height, colorMode); return imageFile; } } #endregion }
a62ac9d4ed3e977c882cc8fba15a5b87e2a3041c
C#
johncobley/stock_deprecator
/StockDeprecator/CurrentStock.Tests/StockLineServiceTests.cs
2.765625
3
using System; using System.Collections.Generic; using System.Threading.Tasks; using CurrentStock.DataAccess; using CurrentStock.Models; using CurrentStock.Service; using Moq; using Xunit; namespace CurrentStock.Tests { public class StockLineServiceTests { private IStockTypeRepository DefaultStockTypeRepository() { var mockStockTypeRepo = new Mock<IStockTypeRepository>(); mockStockTypeRepo .Setup(repo => repo.Get(It.IsAny<string>())) .Returns((string typeName) => Task.FromResult(new StockItemType { TypeName = typeName })); return mockStockTypeRepo.Object; } [Fact] public async void ParsesCorrectlyFormedStockLineWithSingleWordType() { var testLine = "Food 2 1"; var stockLineService = new StockLineService(DefaultStockTypeRepository()); var result = await stockLineService.ParseLine(testLine); Assert.Equal("Food", result.StockTypeId); Assert.Equal(2, result.SellIn); Assert.Equal(1, result.Quality); } [Fact] public async void ParsesCorrectlyFormedStockLineWithMultiWordType() { var testLine = "Toy Food 2 1"; var stockLineService = new StockLineService(DefaultStockTypeRepository()); var result = await stockLineService.ParseLine(testLine); Assert.Equal("Toy Food", result.StockTypeId); Assert.Equal(2, result.SellIn); Assert.Equal(1, result.Quality); } [Fact] public async void ParsesStockLineWithMissingQuality() { var testLine = "Vegan Food 2"; var stockLineService = new StockLineService(DefaultStockTypeRepository()); var result = await stockLineService.ParseLine(testLine); Assert.Equal("Vegan Food 2", result.StockTypeId); Assert.Equal(0, result.SellIn); Assert.Equal(0, result.Quality); } [Fact] public async void ParsesStockLineWithMissingQualityAndSellIn() { var testLine = "Cat Food"; var stockLineService = new StockLineService(DefaultStockTypeRepository()); var result = await stockLineService.ParseLine(testLine); Assert.Equal("Cat Food", result.StockTypeId); Assert.Equal(0, result.SellIn); Assert.Equal(0, result.Quality); } [Fact] public async void ParsesCorrectlyFormedStockLineAndAllocatesStockType() { var testLine = "Test Food 2 1"; var mockStockTypeRepo = new Mock<IStockTypeRepository>(); mockStockTypeRepo .Setup(repo => repo.Get(It.Is<string>(param => param == "Test Food"))) .Returns((string typeName) => Task.FromResult(new StockItemType { TypeName = "Test Food" })); var stockLineService = new StockLineService(mockStockTypeRepo.Object); var result = await stockLineService.ParseLine(testLine); Assert.Equal("Test Food", result.StockType.TypeName); } } }
c91ee250fc4769e01f62f32bc3895d5095c9f7ee
C#
Clouddevelopmentstudios/SlimCanvas
/Shared/SharedDroid/View/DrawInBitmap.cs
2.546875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Android.Graphics; namespace SlimCanvas.Droid { internal class DrawInBitmap { Bitmap myBitmap; Android.Graphics.Canvas canvas; public DrawInBitmap(int width, int height) { myBitmap = Bitmap.CreateBitmap(width, height, Bitmap.Config.Argb8888); canvas = new Android.Graphics.Canvas(myBitmap); } public Bitmap GetAsBitmap() { canvas.Dispose(); return myBitmap; } public void DrawBitmap(Bitmap bitmap, Matrix trans, BitmapInterpolationMode mode) { var paint = new Paint() { Alpha = 255 }; canvas.DrawBitmap(bitmap, trans, paint); } } }
45d18e50bdb27074b1a5726eee271d8f4c0ba4b2
C#
ikamusume7/CSharpStudy
/CSharpStudy/EssentialCSharp/Interface.cs
3
3
using System; using Xunit; using Xunit.Abstractions; namespace EssentialCSharp.Interface { public class Interface { private readonly ITestOutputHelper _testOutputHelper; public Interface(ITestOutputHelper testOutputHelper) { _testOutputHelper = testOutputHelper; } [Fact] public void Demo() { Contact[] contacts = new Contact[1]; contacts[0] = new Contact( "Dick", "Traci", "123 Main St., Spokane, WA 99037", "123-123-1234"); contacts.List(Contact.Headers); _testOutputHelper.WriteLine(""); Publication[] publications = new Publication[1] { new Publication("Celebration of Discipline", "Richard Foster", 1978) }; publications.List(Publication.Headers); } } interface IDistributedSettingsProvider : ISettingsProvider { string GetSetting(string machineName, string name, string defaultValue); void Setting(string machineName, string name, string value); } interface IPerson { string FirstName { get; set; } string LastName { get; set; } } public class Person : IPerson { public string FirstName { get; set; } public string LastName { get; set; } } interface IReadableSettingsProvider { string GetSetting(string name, string defaultValue); } interface IWriteableSettingsProvider { void SetSetting(string name, string value); } interface ISettingsProvider : IReadableSettingsProvider, IWriteableSettingsProvider { } class FileSettingsProvider : ISettingsProvider, IReadableSettingsProvider { #region ISettingsProvider Members public void SetSetting(string name, string value) { } #endregion #region IReadableSettingsProvider Members public string GetSetting(string name, string defaultValue) { return null; } #endregion } static class ConsoleListControl { public static void List(this IListable[] itmes, string[] headers) { int[] columnWidths = DisplayHeaders(headers); for (int count = 0; count < itmes.Length; count++) { string[] values = itmes[count].ColumnValues; DisplayItemRow(columnWidths, values); } } private static int[] DisplayHeaders(string[] headers) { return new int[1]; } private static void DisplayItemRow(int[] ColumnWidths, string[] values) { } } interface IFileCompression { void Compress(string targetFileName, string[] fileList); void UnCompress(string compressFileName, string expandDirectoryName); } interface IListable { string[] ColumnValues { get; } } public abstract class PdaItem { public virtual string Name { get; set; } public PdaItem(string name) { Name = name; } } class Contact : PdaItem, IListable, IComparable, IPerson { private Person _Person; private Person Person { get => _Person; set => _Person = value; } public string FirstName { get => _Person.FirstName; set => _Person.FirstName = value; } public string LastName { get => _Person.LastName; set => _Person.LastName = value; } public string Address { get; set; } public string Phone { get; set; } public Contact(string firstName, string lastName, string address, string phone) : base(null) { FirstName = firstName; LastName = lastName; Address = address; Phone = phone; } #region IComparable Members public int CompareTo(object? obj) { int result; Contact contact = obj as Contact; if (contact == null) { result = 1; } else if (obj != typeof(Contact)) { throw new ArgumentException("obj is not a Contact"); } else if (ReferenceEquals(this, obj)) { result = 0; } else { result = String.Compare(LastName, contact.LastName, StringComparison.Ordinal); if (result == 0) { result = String.Compare(FirstName, contact.FirstName, StringComparison.Ordinal); } } return result; } #endregion #region IListable Members string[] IListable.ColumnValues { get { return new string[] { FirstName, LastName, Phone, Address }; } } #endregion public string[] ColumnValues { get { return new string[] { FirstName, LastName, Phone, Address }; } } public static string[] Headers { get { return new string[] { "First Name", "Last Name ", "Phone ", "Address " }; } } } class Publication : IListable { public string Title { get; set; } public string Author { get; set; } public int Year { get; set; } public Publication(string title, string author, int year) { Title = title; Author = author; Year = year; } public string[] ColumnValues { get { return new string[] { Title, Author, Year.ToString() }; } } public static string[] Headers { get { return new string[] { "Title ", "Author ", "Year" }; } } } }
87eda41667b070d9d346f6e45e722f5c12f57619
C#
javierfil/SocketServer
/SocketServer/LENELBadgeAccessLevels.cs
3.0625
3
using System; using System.Collections.Generic; using System.Text; namespace ServerComunicacionesALUTEL { public class LENELBadgeAccessLevels { Dictionary<string, string> badgesAccessLevels; // Asociacion de badge a accessLevels (1,2,3,4) int orgID; public LENELBadgeAccessLevels(int v_orgID) { badgesAccessLevels = new Dictionary<string, string>(); orgID = v_orgID; } /// <summary> /// Se encarga de desasociar la tarjeta con los viejos access levels y de asociarlo a los access levels nuevos /// </summary> /// <param name="v_badge"></param> /// <param name="v_accessLevels"></param> /// <returns>True si cambiaron los access levels asociados a esta tarjeta</returns> public bool asociarAccessLevel(string v_badge, string v_accessLevels) { bool res = false; if (badgesAccessLevels.ContainsKey(v_badge)) // Si ya está en el diccionario me fijo si los access levels cambiaron { if (!badgesAccessLevels[v_badge].Equals(v_accessLevels)) // Si los access levels cambiaron los actualizo { badgesAccessLevels.Remove(v_badge); badgesAccessLevels.Add(v_badge, v_accessLevels); // Aqui se guardan los accesslevels actuales de la Badge. res = true; // Informa del cambio } } else { badgesAccessLevels.Add(v_badge, v_accessLevels); // Aqui se guardan los accesslevels actuales de la Badge. res = true; // Informa del cambio } return res; } public string getAccessLevels(string v_badge) { string res = ""; if (badgesAccessLevels.ContainsKey(v_badge)) { res = badgesAccessLevels[v_badge]; } return res; } } }
96e4453743ef4b87b2d9ff7f9ae11391a3e5b237
C#
fpapouin/tntpro
/oneTap2/oneTap2/Form1.cs
2.640625
3
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Timers; using System.Diagnostics; using System.IO; namespace oneTap2 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } bool checkCross = true; double timerInterval = 10; long minElapsedMs = 100; float minDiff = 20.0f; int recSize = 5; int mouseKey = 0x04; private void Form1_Shown(object sender, EventArgs e) { this.Visible = false; LoadConfig(); System.Timers.Timer timer = new System.Timers.Timer(timerInterval); timer.Elapsed += OnTimedEvent; timer.Start(); } private void LoadConfig() { if (File.Exists("oneTap2.cfg")) { string cfgFile = File.ReadAllText("oneTap2.cfg"); cfgFile = cfgFile.Replace("\r", ""); foreach (string line in cfgFile.Split('\n')) { if (line.Contains("checkCross")) checkCross = Convert.ToBoolean(line.Split('=').Last()); if (line.Contains("timerInterval")) timerInterval = Convert.ToDouble(line.Split('=').Last()); if (line.Contains("minElapsedMs")) minElapsedMs = Convert.ToInt64(line.Split('=').Last()); if (line.Contains("minDiff")) minDiff = Convert.ToSingle(line.Split('=').Last()); if (line.Contains("recSize")) recSize = Convert.ToInt32(line.Split('=').Last()); if (line.Contains("mouseKey")) mouseKey = Convert.ToInt32(line.Split('=').Last(), 16); } } } private void OnTimedEvent(Object source, ElapsedEventArgs e) { (source as System.Timers.Timer).Stop(); DoLoop(); (source as System.Timers.Timer).Start(); } private void ExitToolStripMenuItem_Click(object sender, EventArgs e) { this.Close(); } } }
21cbd53823403297abef30483b4f5bb8e9eafc65
C#
kvarik/yaat
/libYaAT/Window.cs
2.65625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.InteropServices; namespace libYaAT { public class Window { private static IntPtr hWnd; private static string title; public string Title { get { return title; } set { hWnd = FindWindow(null, value); title = value; } } public static IntPtr Handler { get { return hWnd; } } // user32.dll imports [DllImport("user32.dll")] static extern IntPtr FindWindow(string lpClassName, string lpWindowName); [DllImport("user32.dll")] static extern bool SetWindowText(IntPtr hWnd, string text); [DllImport("user32.dll", SetLastError = true)] public static extern IntPtr FindWindowEx(IntPtr parentHandle, IntPtr childAfter, string className, string windowTitle); public Window() { } public Window(string title) { this.Title = title; } public bool Rename(string text) { title = text; return SetWindowText(hWnd, text); } } }
2b4af9bd6a943c86e1b5e8c339bd70ae6d3c433d
C#
JoaLampela/Giants-Kettle
/Assets/Script/MapGeneration/Rooms/Classes/BossRoom.cs
2.65625
3
using System.Collections; using System.Collections.Generic; using UnityEngine; public class BossRoom : Room { public BossRoom(Coord centre, int[,] map) { CentreTile = centre; roomType = 10; width = 30; height = 20; for (int x = -width / 2 + centre.tileX; x < width / 2 + centre.tileX; x++) { for (int y = -height / 2 + centre.tileY; y < height / 2 + centre.tileY; y++) { map[x, y] = 0; } } SetRoomBorders(centre, map); height = 40; for (int x = -2 + centre.tileX; x < 3 + centre.tileX; x++) { for (int y = -height + centre.tileY + 15; y < height + centre.tileY - 15; y++) { map[x, y] = 0; } } DrawCircle(new Coord(centre.tileX, centre.tileY + height - 20), 7, map); DrawCircle(new Coord(centre.tileX, centre.tileY - height + 20), 7, map); } void DrawCircle(Coord c, int r, int[,] map) { for (int x = -r; x <= r; x++) for (int y = -r; y <= r; y++) { if (x * x + y * y <= r * r) { int drawX = c.tileX + x; int drawY = c.tileY + y; map[drawX, drawY] = 0; } } } }
713327d067dc72a99c2e15c0ff62045ea17e9f49
C#
PSNS-IMF/security-clientcerthandling
/src/ClientCertificateHandling/DodUser.cs
2.765625
3
using Psns.Common.Functional; using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using static Psns.Common.Functional.Prelude; using static Psns.Common.Security.ClientCertificateHandling.Constants; namespace Psns.Common.Security.ClientCertificateHandling { /// <summary> /// Basic properties of every DodUser /// </summary> public struct DodUser { /// <summary> /// The DodId/EDIPI /// </summary> public readonly string DodId; /// <summary> /// First Name /// </summary> public readonly Maybe<string> FirstName; /// <summary> /// Middle Name /// </summary> public readonly Maybe<string> MiddleName; /// <summary> /// Last Name /// </summary> public readonly Maybe<string> LastName; /// <summary> /// Email /// </summary> public readonly Maybe<string> EmailAddress; /// <summary> /// Constructor /// </summary> /// <param name="dodId"></param> /// <param name="firstName"></param> /// <param name="middleName"></param> /// <param name="lastName"></param> /// <param name="email"></param> /// <exception cref="ArgumentNullException">When <paramref name="dodId"/> is null or empty</exception> public DodUser(string dodId, Maybe<string> firstName, Maybe<string> middleName, Maybe<string> lastName, Maybe<string> email) { if (string.IsNullOrEmpty(dodId)) throw new ArgumentNullException(nameof(dodId), $"{nameof(dodId)} must have a value"); DodId = dodId.AssertValue(); FirstName = firstName; MiddleName = middleName; LastName = lastName; EmailAddress = email; } /// <summary> /// A formatted string for this. /// </summary> /// <returns></returns> public override string ToString() => $@"{{{nameof(DodId)}: {DodId}, {nameof(FirstName)}: {FirstName}, {nameof(LastName)}: { LastName}, {nameof(MiddleName)}: {MiddleName}, {nameof(EmailAddress)}: {EmailAddress}}}"; } /// <summary> /// Some <see cref="DodUser"/> extensions. /// </summary> public static class DodUserExtentions { /// <summary> /// Create a <see cref="DodUser" /> with just a <paramref name="dodId"/>. /// </summary> /// <param name="dodId"></param> /// <returns></returns> /// <exception cref="ArgumentNullException">When <paramref name="dodId"/> is null or empty</exception> public static DodUser FromDodId(string dodId) => new DodUser(dodId, None, None, None, None); /// <summary> /// Assign <paramref name="dodId"/> to <paramref name="self"/>. /// </summary> /// <param name="self"></param> /// <param name="dodId"></param> /// <returns></returns> public static DodUser WithDodId(this DodUser self, string dodId) => new DodUser(dodId, self.FirstName, self.LastName, self.MiddleName, self.EmailAddress); /// <summary> /// Assign <paramref name="firstName"/> to <paramref name="self"/>. /// </summary> /// <param name="self"></param> /// <param name="firstName"></param> /// <returns></returns> public static DodUser WithFirstName(this DodUser self, string firstName) => new DodUser(self.DodId, firstName, self.MiddleName, self.LastName, self.EmailAddress); /// <summary> /// Assign <paramref name="lastName"/> to <paramref name="self"/>. /// </summary> /// <param name="self"></param> /// <param name="lastName"></param> /// <returns></returns> public static DodUser WithLastName(this DodUser self, string lastName) => new DodUser(self.DodId, self.FirstName, self.MiddleName, lastName, self.EmailAddress); /// <summary> /// Assign <paramref name="middleName"/> to <paramref name="self"/>. /// </summary> /// <param name="self"></param> /// <param name="middleName"></param> /// <returns></returns> public static DodUser WithMiddleName(this DodUser self, string middleName) => new DodUser(self.DodId, self.FirstName, middleName, self.LastName, self.EmailAddress); /// <summary> /// Assign <paramref name="email"/> to <paramref name="self"/>. /// </summary> /// <param name="self"></param> /// <param name="email"></param> /// <returns></returns> public static DodUser WithEmail(this DodUser self, string email) => new DodUser(self.DodId, self.FirstName, self.MiddleName, self.LastName, email); /// <summary> /// Generates <see cref="Claim"/>s from a <see cref="DodUser"/>. /// </summary> /// <param name="self"></param> /// <returns></returns> public static IEnumerable<Claim> AsClaims(this DodUser self) => Cons( (FirstNameClaimTypeName, self.FirstName), (LastNameClaimTypeName, self.LastName), (MiddleNameClaimTypeName, self.MiddleName), (EmailClaimTypeName, self.EmailAddress), (DodIdClaimTypeName, self.DodId)) .Aggregate( Empty<Claim>(), (claims, next) => next.Item2.Match( some: typeVal => claims.Append(tail: new Claim(next.Item1, typeVal)), none: () => claims)); } }
c9eb929a981411160e9dd8388cb2723f2a402597
C#
shendongnian/download4
/first_version_download2/527326-49041984-167940533-4.cs
3.609375
4
public class Cache : ICache { private readonly ConcurrentDictionary<string, object> _cache = new ConcurrentDictionary<string, object>(); public T Get<T>(string key) { object cached; if(_cache.TryGetValue(key, out cached) && cached is T) { return(T) cached; } return default(T); } public void Set(string key, object value) { _cache.AddOrUpdate(key, value, (s, o) => value); } }
67cef0b0649407ce39ad701f2ab74b58a1b4b286
C#
TESSkyblivion/Skyblivion.ESReader
/src/Skyblivion.ESReader/Struct/Trie.cs
3
3
using Skyblivion.ESReader.PHP; using Skyblivion.ESReader.TES4; using System; using System.Collections.Generic; namespace Skyblivion.ESReader.Struct { /* * Class Trie * Based off implementation of https://github.com/fran6co/phptrie/ */ public class Trie { private Dictionary<string, Trie> trie = new Dictionary<string, Trie>(); private TES4LoadedRecord value = null; /* * Trie constructor * * This is for internal use */ public Trie(TES4LoadedRecord value = null) { this.value = value; } /* * Add value to the trie * * string The key * mixed The value * Overwrite existing value */ public void Add(string str, TES4LoadedRecord value, bool overWrite = true) { if (str == "") { if (this.value == null || overWrite) { this.value = value; } return; } foreach (var kvp in this.trie) { var prefix = kvp.Key; var trie = kvp.Value; int prefixLength = prefix.Length; string head = PHPFunction.Substr(str, prefixLength); int headLength = head.Length; bool equals = true; string equalPrefix = ""; for (int i = 0; i < prefixLength; ++i) { //Split if (i >= headLength) { Trie equalTrie = new Trie(value); this.trie.Add(equalPrefix, equalTrie); equalTrie.trie.Add(prefix.Substring(i), trie); this.trie.Remove(prefix); return; } else if (prefix[i] != head[i]) { if (i > 0) { Trie equalTrie = new Trie(); this.trie.Add(equalPrefix, equalTrie); equalTrie.trie.Add(prefix.Substring(i), trie); equalTrie.trie.Add(str.Substring(i), new Trie(value)); this.trie.Remove(prefix); return; } equals = false; break; } equalPrefix += head[i]; } if (equals) { trie.Add(str.Substring(prefixLength), value, overWrite); return; } } this.trie.Add(str, new Trie(value)); } /* * Search the Trie with a string */ public TES4LoadedRecord Search(string str) { if (str == "")//WTM: Change: In PHP, this was empty(str), which returns true when str = "0" { return this.value; } foreach (var kvp in this.trie) { var prefix = kvp.Key; if (str.StartsWith(prefix)) { var trie = kvp.Value; return trie.Search(str.Substring(prefix.Length)); } } return null; } public TrieIterator SearchPrefix(string str) { if (str == "") { return new TrieIterator(this); } int stringLength = str.Length; foreach (var kvp in this.trie) { var prefix = kvp.Key; var trie = kvp.Value; int prefixLength = prefix.Length; string headPrefix, stringPrefix; if (prefixLength > stringLength) { headPrefix = prefix.Substring(0, stringLength); stringPrefix = str; } else if (prefixLength < stringLength) { headPrefix = prefix; stringPrefix = str.Substring(0, prefixLength); } else { headPrefix = prefix; stringPrefix = str; } if (headPrefix == stringPrefix) { return trie.SearchPrefix(str.Substring(prefixLength)); } } return new TrieIterator(null); } public TES4LoadedRecord _value() { return this.value; } public Dictionary<string, Trie> Subnodes() { return this.trie; } } }
b937eb189229eceac2c04a7f7a3d60f064fa9fe9
C#
coder-of-night/GameFramework
/MidnightCoder/Script/GameObjectPool/GOPoolMgr.cs
2.609375
3
using System; using System.Collections.Generic; using UnityEngine; namespace MidnightCoder.Game { public class GOPoolMgr { // // Fields // public Dictionary<string, GOPool> pools = new Dictionary<string, GOPool> (); // // Constructors // public GOPoolMgr () { this.pools.Clear (); } // // Methods // public void AddPool (GameObject prefab, GameObject parent = null) { if (prefab == null) { return; } string key = this.SanitizeName (prefab.name); if (this.pools.ContainsKey (key)) { return; } this.pools.Add (this.SanitizeName (prefab.name), new GOPool (prefab,parent)); } public bool Destroy (GameObject go) { if (go == null) { return false; } string key = this.SanitizeName (go.name); if (this.pools.ContainsKey (key) && this.pools[key] != null && this.pools[key].Destroy (go)) { return true; } Destroy (go); return false; } public void DestroyAllPools () { foreach (GOPool current in this.pools.Values) { current.DestroyPool (); } this.pools.Clear (); } public void DestroyPool(GameObject prefab) { if (prefab == null) { return; } string key = this.SanitizeName(prefab.name); if (this.pools.ContainsKey(key)) { this.pools.Remove(key); } } public GameObject Instantiate (GameObject prefab, bool addToPoolIfMissing = true) { if (prefab == null) { return null; } string key = this.SanitizeName (prefab.name); if (!this.pools.ContainsKey (key)) { if (!addToPoolIfMissing) { return UnityEngine.Object.Instantiate<GameObject> (prefab); } this.AddPool (prefab); return UnityEngine.Object.Instantiate<GameObject> (prefab); } if (this.pools[key] == null) { this.pools[key] = new GOPool (prefab); } return this.pools[key].Instantiate (); } public GameObject Instantiate (string key, bool addToPoolIfMissing = true) { if (key == "" || !this.pools.ContainsKey (key) || this.pools[key] == null) { return null; } return this.pools[key].Instantiate (); } protected string SanitizeName (string name) { return name.Replace ("(Clone)", string.Empty).TrimEnd (); } } }
7b3d8b7bfd80bbc4ab1bff9782ebcdf529027117
C#
Karlmikaelb/SOLID_LSP
/SOLID_LSP/Calculator.cs
2.640625
3
namespace SOLID_LSP { public abstract class Calculator { protected readonly int[] Numbers; public Calculator(int[] numbers) { Numbers = numbers; } public abstract int Calculate(); } }
d2420f9818545a5a7683f2e282be76d54e62f65b
C#
RusyaOne/NetCore_09.12.2020
/Infestation/Infestation/Services/ImageProcessingChannel.cs
2.75
3
using Microsoft.AspNetCore.Http; using System; using System.Collections.Generic; using System.IO; using System.Threading.Channels; using System.Threading.Tasks; namespace Infestation.Services { public class ImageProcessingChannel { private Channel<(string, byte[])> _channel; public ImageProcessingChannel() { _channel = Channel.CreateUnbounded<(string, byte[])>(); } public async Task Write(IFormFile image) { using (var stream = new MemoryStream()) { image.CopyTo(stream); await _channel.Writer.WriteAsync((image.FileName, stream.ToArray())); } } public (string, byte[]) Read() { (string, byte[]) image; _channel.Reader.TryRead(out image); return image; } public IAsyncEnumerable<(string, byte[])> ReadAll() { return _channel.Reader.ReadAllAsync(); } } }
a01214ae1aec9a82c1af593cbab1f410a07276cd
C#
lhmarcondes2511/ProjetoTeste
/ProjetoTeste/Models/Cliente.cs
2.9375
3
using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace ProjetoTeste.Models { public class Cliente { [Key] public int Id { get; set; } [DisplayName("Nome do Cliente")] [Required(ErrorMessage = "Nome obrigatório")] [StringLength(60, MinimumLength = 3, ErrorMessage = "O nome precisa ter mais de 3 caracteres")] public string Nome { get; set; } [DisplayName("E-mail")] [Required(ErrorMessage = "E-mail obrigatório")] [RegularExpression(".+\\@.+\\..+", ErrorMessage = "E-mail inválido")] public string Email { get; set; } [DisplayName("CPF")] [Required(ErrorMessage = "CPF obrigatório")] [MinLength(11, ErrorMessage = "O CPF deve conter 11 números")] public string Cpf { get; set; } [DisplayName("Nome do Produto")] public Produto Produto { get; set; } public int ProdutoId { get; set; } public Cliente() { } public Cliente(int id, string nome, string email, string cpf, Produto produto) { Id = id; Nome = nome; Email = email; Cpf = cpf; Produto = produto; } } }
01b9ce7351895c8c5d6a0ecbaf7ff278d23e67bf
C#
anna4615/Lektion7
/200917 Lektion7 Visual/NameArray/Program.cs
3.796875
4
using System; namespace NameArray { class Program { static void Main(string[] args) { Console.WriteLine("Hur många namn vill du registrera? "); string[] names = new string[int.Parse(Console.ReadLine())]; for (int i = 0; i < names.Length; i++) { Console.Write($"Ange namn {i + 1} "); names[i] = Console.ReadLine(); } Console.WriteLine(); //for (int i = names.Length -1; i >= 0; i--) //{ // Console.WriteLine($"Namn {i +1}: {names[i]}"); //} //Console.WriteLine(); for (int i = 0; i < names.Length; i++) { Console.WriteLine($"Namn {i + 1}: {names[i]}"); } Console.WriteLine(); Console.Write("Vilken person vill du byta ut? "); string oldName = Console.ReadLine(); while (!CheckName(names, oldName)) { Console.Write($"Hittar inte {oldName}, skriv ett namn som finns i listan "); oldName = Console.ReadLine(); CheckName(names, oldName); } Console.Write("Vem vill du skriva in istället? "); string newname = Console.ReadLine(); Console.WriteLine(); ReplacePerson(names, newname, FindPosition(names, oldName)); for (int i = 0; i < names.Length; i++) { Console.WriteLine($"Namn {i +1}: {names[i]}"); } Console.WriteLine(); Console.WriteLine("Vems position vill du hitta? "); string input = Console.ReadLine(); while (!CheckName(names, input)) { Console.Write($"Hittar inte {input}, skriv ett namn som finns i listan "); input = Console.ReadLine(); CheckName(names, input); } int position = FindPosition(names, input); Console.WriteLine($"{input} finns på position {position +1}."); } private static bool CheckName(string[] names, string name) { bool nameExists = false; for (int i = 0; i < names.Length; i++) { if (names[i] == name) { nameExists = true; break; } } return nameExists; } private static void ReplacePerson(string[] names, string newname, int replacePosition) { names[replacePosition] = newname; } private static int FindPosition(string[] names, string oldName) { int position = 0; for (int i = 0; i < names.Length; i++) { if (names[i] == oldName) { position = i; break; } } return position; } } }
caee5a180c4d9da24b4cdb19a7a9ebfc432d1868
C#
ChristopherRamos/monotouch-samples
/NSZombieApocalypse/NSZombieApocalypse/ZombieMeter.cs
2.609375
3
using System; using System.Drawing; using MonoTouch.UIKit; using MonoTouch.Foundation; using MonoTouch.CoreGraphics; namespace NSZombieApocalypse { public class ZombieMeter : UIView { float zombieLevel; public float ZombieLevel { get { return zombieLevel; } set { zombieLevel = Math.Max (0, value); this.SetNeedsDisplay (); } } UILabel label; public ZombieMeter (RectangleF frame) : base (frame) { BackgroundColor = UIColor.Clear; Layer.CornerRadius = 8; ZombieLevel = 0; label = new UILabel (new RectangleF (0, 0, frame.Size.Width, 0)); label.TextAlignment = UITextAlignment.Center; label.Text = "Zombie Meter"; label.Font = UIFont.FromName ("Helvetica", 24); label.BackgroundColor = UIColor.Clear; AddSubview (label); label.SizeToFit (); var labelFrame = label.Frame; label.Frame = new RectangleF (labelFrame.X, labelFrame.Y, frame.Size.Width, labelFrame.Size.Height); } public override bool IsAccessibilityElement { get { return true; } } public override string AccessibilityLabel { get { return label.AccessibilityLabel; } } public override string AccessibilityValue { get { return String.Format ("{0} %", ZombieLevel * 100); } } public override void Draw (RectangleF rect) { float pad = 20; float numberOfMeters = 10; float meterSpacing = 5; float yOrigin = label.Frame.GetMaxY () + 10; UIBezierPath background = UIBezierPath.FromRoundedRect (rect, 8); UIColor.White.SetFill (); background.Fill (); UIColor.Black.SetStroke (); RectangleF meter = new RectangleF ( pad, yOrigin, rect.Size.Width - pad * 2, (rect.Size.Height - yOrigin - (numberOfMeters * meterSpacing)) / numberOfMeters ); for (int k =0; k < numberOfMeters; k++) { meter.Y = yOrigin + (meter.Height + meterSpacing) * (numberOfMeters - 1 - k); var path = UIBezierPath.FromRoundedRect (meter, 2); path.LineWidth = 1; float level = ZombieLevel * 10; if (level > k) { if (k < 3) { UIColor.Green.SetFill (); } else if (k < 6) { UIColor.Blue.SetFill (); } else { UIColor.Red.SetFill (); } float diff = (level - k); if (diff > 0 && diff < 1) { RectangleF smallerRect = meter; smallerRect = new RectangleF ( smallerRect.X, smallerRect.Y + smallerRect.Size.Height - ((smallerRect.Size.Height) * diff), smallerRect.Size.Width, (smallerRect.Size.Height) * diff ); var smallerPath = UIBezierPath.FromRoundedRect (smallerRect, UIRectCorner.BottomLeft | UIRectCorner.BottomRight, new SizeF (2, 2)); smallerPath.Fill (); } else { path.Fill (); } } path.Stroke (); } } } }
c23c6c5e9675ef8e19f676102fd2cd4e7c3455df
C#
modland/proto-event-delegates-real
/Assets/Scripts/Delegate.cs
3.234375
3
using System.Collections; using System.Collections.Generic; using UnityEngine; // example code public class Delegate : MonoBehaviour { // a delegate is just a variable that holds a method. // here is how to declare one. // note the Method Signature ie. input and returning parameter types // in this example we return void and pass in a Color variable. public delegate void ChangeColor(Color newColor); public ChangeColor onColorChange; // this delegate method signature returns void and accepts no parameters. public delegate void OnComplete(); public OnComplete onComplete; private void Start() { // So long as the signatures match, our delegate can have a method "registered" to it. onColorChange = UpdateColor; // now when we invoke our delegate we are calling to the registered method. onColorChange(Color.green); // Delegates are capable of Multicasting. Use += to register more methods to the stack. onComplete += Task; onComplete += Task1; onComplete += Task2; // know that you can (+=) register and also deregister (-=) methods to the delegate // this can be done out of order // onComplete -= Task2; // onComplete -= Task; // Etc. // it's a good move to test that some method has been registered to the delegate before invoking onComplete?.Invoke(); } public void UpdateColor(Color newColor) { Debug.Log("Changing color to: " + newColor.ToString()); } public void Task() { Debug.Log("Task 1 Finished"); } public void Task1() { Debug.Log("Task 2 Finished"); } public void Task2() { Debug.Log("Task 3 Finished"); } }
ce7bda9a275430fb8ba376139c56f50349c084b8
C#
jmontes495/YouHadOneJob
/YouHadOneJob/Assets/Scripts/Content/Snake.cs
2.828125
3
using System; using System.Collections.Generic; using UnityEngine; namespace YouHadOneJob { public class Snake { public event Action<Tile> OnCreateFood; public event Action<Tile, Tile> OnCreateSnake; public event Action<Tile, Tile, SnakeDirection> OnMoveHead; public event Action<Tile, Tile, Tile> OnMoveTail; public event Action<Tile> OnLose; public event Action OnRestart; private int xSize; private int ySize; private SnakeDirection direction; private SnakeDirection nextDirection; private Dictionary<Tile, TileState> tiles; private LinkedList<Tile> snake; private SnakeState state; public SnakeState State { get { return state; } } public int XSize { get { return xSize; } } public Snake (int xSize, int ySize, int obstaclesCount) { this.xSize = xSize; this.ySize = ySize; direction = SnakeDirection.Right; nextDirection = direction; CreateTiles (xSize, ySize); state = SnakeState.Lost; } public void Initialize () { CreateSnake (headX: xSize / 2, headY: ySize / 2); CreateFood (); state = SnakeState.Playing; } private void CreateTiles (int xSize, int ySize) { tiles = new Dictionary<Tile, TileState> (xSize * ySize); for (int x = 0; x < xSize; x++) { for (int y = 0; y < ySize; y++) { Tile tile = new Tile (x, y); tiles.Add (tile, TileState.Empty); } } } private void CreateSnake (int headX, int headY) { snake = new LinkedList<Tile> (); InitSnake (headX, headY); } private void InitSnake (int headX, int headY) { Tile head = new Tile (headX, headY); Tile tail = GetNextTile (head, direction.GetOpposite ()).Value; snake.AddFirst (head); snake.AddLast (tail); tiles[head] = TileState.Snake; tiles[tail] = TileState.Snake; if (OnCreateSnake != null) OnCreateSnake (head, tail); } private void CreateFood () { Tile emptyTile = GetRandomEmptyTile (); tiles[emptyTile] = TileState.Food; if (OnCreateFood != null) OnCreateFood (emptyTile); } private Tile? GetNextTile (Tile tile, SnakeDirection direction) { switch (direction) { case SnakeDirection.Right: if (tile.x >= xSize - 1) return null; return new Tile (tile.x + 1, tile.y); case SnakeDirection.Left: if (tile.x <= 0) return null; return new Tile (tile.x - 1, tile.y); case SnakeDirection.Up: if (tile.y >= ySize - 1) return null; return new Tile (tile.x, tile.y + 1); case SnakeDirection.Down: if (tile.y <= 0) return null; return new Tile (tile.x, tile.y - 1); } throw new UnityException (); } private TileState GetTileState (Tile? tile) { if (tile == null) return TileState.OutOfGrid; return tiles[tile.Value]; } private Tile GetRandomEmptyTile () { while (true) { int randomX = UnityEngine.Random.Range (0, xSize); int randomY = UnityEngine.Random.Range (0, ySize); Tile tile = new Tile (randomX, randomY); TileState tileState = GetTileState (tile); if (tileState == TileState.Empty) return tile; } } public void ChangeDirection (SnakeDirection direction) { if (direction == this.direction.GetOpposite ()) return; nextDirection = direction; } public void Tick () { if (state == SnakeState.Lost) return; SnakeDirection lastDirection = direction; direction = nextDirection; Tile? newHead = GetNextTile (snake.First.Value, direction); TileState tileState = GetTileState (newHead); switch (tileState) { case TileState.Empty: if (OnMoveHead != null) OnMoveHead (snake.First.Value, newHead.Value, lastDirection); snake.AddFirst (newHead.Value); tiles[newHead.Value] = TileState.Snake; if (OnMoveTail != null) OnMoveTail (snake.Last.Value, snake.Last.Previous.Value, snake.Last.Previous.Previous.Value); tiles[snake.Last.Value] = TileState.Empty; snake.RemoveLast (); break; case TileState.Food: if (OnMoveHead != null) OnMoveHead (snake.First.Value, newHead.Value, direction); snake.AddFirst (newHead.Value); tiles[newHead.Value] = TileState.Snake; CreateFood (); break; case TileState.Snake: case TileState.Obstacle: case TileState.OutOfGrid: state = SnakeState.Lost; if (OnLose != null) OnLose (snake.First.Value); break; } } public void Restart () { direction = SnakeDirection.Right; nextDirection = direction; ResetTiles (); snake.Clear (); if (OnRestart != null) OnRestart (); InitSnake (headX: xSize / 2, headY: ySize / 2); CreateFood (); state = SnakeState.Playing; } private void ResetTiles () { for (int x = 0; x < xSize; x++) { for (int y = 0; y < ySize; y++) { Tile tile = new Tile (x, y); tiles[tile] = TileState.Empty; } } } } }
33b312c48bfe5a14e1f433a00a2f5a3d12e5d054
C#
GuMiner/CommonNet
/CommonNet/Tree/RedBlackCore/RedBlackTreeNode.cs
3.0625
3
namespace CommonNet.Tree.RedBlackCore { /// <summary> /// Defines a node in a Red-Black Tree /// </summary> public class RedBlackTreeNode<T> { public const bool Red = false; public const bool Black = true; public RedBlackTreeNode(T data, bool isBlack) { this.Data = data; this.IsBlack = isBlack; } public T Data { get; } public bool IsBlack { get; set; } } }
86da313035a2e08a9d67fe031f8083d45e5f65b8
C#
AnejL/Persons.NET
/Persons.NET.Tests/FileServiceTests.cs
2.875
3
using NUnit.Framework; using Persons.NET.Model; using Persons.NET.Services; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; namespace Persons.NET.Tests { public class FileServiceTests { private FileService fileService; [SetUp] public void Setup() { this.fileService = new FileService(); } private string GenerateRandomFileName() { return $"{Guid.NewGuid()}.json"; } [Test] public async Task ReadPersonsFromNonExistantFile() { var result = await this.fileService.ReadFromFile<List<Person>>("DoesntExist.json"); Assert.True(result == default(List<Person>)); } [Test] public async Task WriteToNonExistantFile() { var filename = this.GenerateRandomFileName(); var personsService = new PersonsService(filename, this.fileService); var person1 = await personsService.AddPerson("a", "b", 11112222, "ad"); var result = await this.fileService.ReadFromFile<List<Person>>(filename); Assert.True(result.First().Id == person1.Id); } [Test] public async Task ReadMultiplePersonsFromFile() { var filename = this.GenerateRandomFileName(); var personsService = new PersonsService(filename, this.fileService); var person1 = await personsService.AddPerson("a", "b", 11112222, "ad"); var person2 = await personsService.AddPerson("aa", "ba", 11112223, "ada"); var result = await this.fileService.ReadFromFile<List<Person>>(filename); Assert.True(result.Count == 2); Assert.True(result.Last().FirstName == person2.FirstName); File.Delete(filename); } } }
1cb7ab145393d5b95380c40d9351c1543a5fa3fe
C#
JediChou/jedichou-study-backend
/csharp-study/cs4-power/ch15/other-apply/nonfunc.cs
3.40625
3
// File name: nonfunc.cs // Description: How to use anonymous method with delegate class Program { delegate void TestDelegate(string name); static void Main() { TestDelegate d2 = delegate(string name) { System.Console.WriteLine("Hello, {0}", name); }; d2("Jedi"); } }
8d3040abc12a6399fd8df52296a32cde680800fa
C#
Sequenta/MailChat
/MailChat/Messages/Message.cs
3.265625
3
using System; using System.Collections.Generic; using System.Text; namespace MailChat.Messages { public class Message { private readonly string sender; public string Sender { get { return sender; } } private readonly string messageText; public string MessageText { get { return messageText; } } public Message(string sender, string message) { this.sender = sender; messageText = message; } public Message(byte[] data) { var nameLen = BitConverter.ToInt32(data, 0); sender = nameLen > 0 ? Encoding.UTF8.GetString(data, 4, nameLen) : null; messageText = Encoding.UTF8.GetString(data, nameLen + 4, data.Length - nameLen - 4); } public byte[] ToByte() { var result = new List<byte>(); //Длина имени. result.AddRange(Sender != null ? BitConverter.GetBytes(Sender.Length) : BitConverter.GetBytes(0)); //Имя. if (Sender != null) result.AddRange(Encoding.UTF8.GetBytes(Sender)); //Сообщение. if (MessageText != null) result.AddRange(Encoding.UTF8.GetBytes(MessageText)); return result.ToArray(); } } }
9d6e3de5e621b054624309de8b42ce8128c2d979
C#
dabbertorres/Minesweeper
/Minesweeper/ChangedCell.cs
2.703125
3
namespace Minesweeper { /// <summary> /// Represents a Cell that had its status changed /// </summary> /// <remarks>Where <see cref="Cell.Flagged"/> or <see cref="Cell.Cleared"/> changed</remarks> public struct ChangedCell { public ChangedCell(Coordinate coord, int mines) { coordinate = coord; neighboringMines = mines; } public Coordinate coordinate; public int neighboringMines; } }
caeb3bbee3dc2dab1f0dabf14b9c625a11ee155f
C#
ShawkyZ/Social-Me
/Post.cs
2.703125
3
/* * Social Me Project * Developed By : Abdelrhman Shawky * fb.com/shawkyz1 */ using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using Facebook; namespace SocialMe { public partial class Post : Form { FacebookClient fb = new FacebookClient(); List<Group> Groups = new List<Group>(); List<Page> Pages = new List<Page>(); string access_token=""; public class Group { public string Groupname { get; set; } public string GroupID { get; set; } } public class Page { public string Pagename { get; set; } public string PageID { get; set; } public string Pageaccess { get; set; } } public Post(string access) { access_token = access; InitializeComponent(); } private async void Form2_Load(object sender, EventArgs e) { cbPrivacy.SelectedIndex = 0; fb.AccessToken = access_token; toolStripStatusLabel1.Text = "Getting Groups"; dynamic groups = await fb.GetTaskAsync("/me/groups"); //Get the user groups for (int i = 0; i < (int)groups.data.Count; i++) { //Add the user groups the Groups List Groups.Add(new Group { GroupID = groups.data[i].id, Groupname = groups.data[i].name }); //Add the user groups the CheckBox List GroupCb.Items.Add(groups.data[i].name); } toolStripStatusLabel1.Text = "Getting Your Pages"; dynamic pages = await fb.GetTaskAsync("/me/accounts"); //Get the user Pages for (int i = 0; i < (int)pages.data.Count; i++) { //Add the user pages to the Pages List Pages.Add(new Page { PageID = pages.data[i].id, Pagename = pages.data[i].name, Pageaccess = pages.data[i].access_token }); //Add the user pages to the CheckBox List PageCb.Items.Add(pages.data[i].name); } toolStripStatusLabel1.Text = "Ready"; } private void cbWall_CheckedChanged(object sender, EventArgs e) { if (cbWall.Checked) { label5.Show(); cbPrivacy.Show(); } else { label5.Hide(); cbPrivacy.Hide(); } } private async void button1_Click_1(object sender, EventArgs e) { //Set the post arguments for more info check the facebook graph documentation https://developers.facebook.com/docs/ Dictionary<string, object> args = new Dictionary<string, object>(); args["message"] = tbMessage.Text; args["link"] = tbLink.Text; //If the user chosed to post on his wall so we'll set the privacy value to the value chosen from the Privacy ComboBox switch (cbPrivacy.SelectedIndex) { case 0: args["privacy"] = new { value = "EVERYONE" }; break; case 1: args["privacy"] = new { value = "ALL_FRIENDS" }; break; case 2: args["privacy"] = new { value = "SELF" }; break; } //Post to user's wall if he chosed that if (cbWall.Checked) { toolStripStatusLabel1.Text = "Posting To Your Wall"; var id = await fb.PostTaskAsync("/me/feed", args); } //Remove the privacy Key becasue posting to Groups and Pages doesn't require this Key args.Remove("privacy"); //Posting to the user selected Groups for (int i = 0; i < GroupCb.Items.Count; i++) { if (GroupCb.GetItemChecked(i)) { toolStripStatusLabel1.Text = "Posting To Group " + Groups[i].Groupname; await fb.PostTaskAsync("/" + Groups[i].GroupID + "/feed", args); } } //Posting to the user selected Pages for (int i = 0; i < PageCb.Items.Count; i++) { if (PageCb.GetItemChecked(i)) { args["access_token"] = Pages[i].Pageaccess; toolStripStatusLabel1.Text = "Posting To Page " + Pages[i].Pagename; await fb.PostTaskAsync("/" + Pages[i].PageID + "/feed", args); } } toolStripStatusLabel1.Text = "Ready"; } } }
2a4a5b76a2bb5c90d05c43df76084478f310291c
C#
Treebotx/DataStructures
/DataStructures.Tests/ArrQueueTests.cs
3.21875
3
using DataStructures.Library; using System; using Xunit; namespace DataStructures.Tests { public class ArrQueueTests { [Fact] public void QueueStartsEmptyWithALengthOfZero() { var q = new ArrQueue<int>(); Assert.Equal(0, q.Length); Assert.True(q.IsEmpty); } [Fact] public void Offer_SetsLengthOfEmptyStackToOneAndMakesNonEmpty() { var q = new ArrQueue<int>(); q.Offer(555); Assert.Equal(1, q.Length); Assert.False(q.IsEmpty); } [Theory] [InlineData(new int[] { 1, 2 }, 2)] [InlineData(new int[] { 1 }, 1)] [InlineData(new int[] { 1, 2, 3, 4, 5, 6 }, 6)] public void Offer_AddsItemToTheEndOfTheQueue(int[] array, int expected) { var q = new ArrQueue<int>(); foreach (var item in array) q.Offer(item); int lastItem = 0; for (int i = 0; i < array.Length; i++) { lastItem = q.Poll(); } Assert.Equal(expected, lastItem); } //[Theory] //[InlineData(new int[] { 1, 2 }, 2)] //[InlineData(new int[] { 1 }, 1)] //[InlineData(new int[] { 1, 2, 3, 4, 5, 6 }, 6)] //public void Offer_ThrowsInvalidOperationExceptionIfExceedsLengthOfQueue(int[] array, int lengthOfQueue) //{ // var q = new ArrQueue<int>(lengthOfQueue); // foreach (var item in array) q.Offer(item); // Assert.Throws<InvalidOperationException>(() => q.Offer(555)); //} [Theory] [InlineData(new int[] { 1, 2 })] [InlineData(new int[] { 1 })] [InlineData(new int[] { 1, 2, 3, 4, 5, 6 })] public void Offer_StillAddsNewItemIfItGoesPastTheEndOfTheQueue(int[] array) { var q = new ArrQueue<int>(array.Length); q.Offer(555); q.Offer(555); q.Poll(); q.Poll(); foreach (var item in array) q.Offer(item); q.Offer(555); for (var i = 0; i < array.Length; i++) q.Poll(); Assert.Equal(555, q.Poll()); } [Theory] [InlineData(new int[] { 1, 2 }, 2)] [InlineData(new int[] { 1 }, 1)] [InlineData(new int[] { 1, 2, 3, 4, 5, 6 }, 6)] public void Offer_SuccessfullyCyclesIfNotAtEndOfArray(int[] array, int lengthOfQueue) { var q = new ArrQueue<int>(lengthOfQueue); foreach (var item in array) q.Offer(item); q.Poll(); q.Offer(555); for (var i = 0; i < array.Length - 1; i++) q.Poll(); Assert.Equal(555, q.Poll()); } [Fact] public void Peek_ReturnsFirstElementInQueue() { var q = new ArrQueue<int>(); q.Offer(555); Assert.Equal(555, q.Peek()); } [Theory] [InlineData(new int[] { 1, 2 }, 1, 2)] [InlineData(new int[] { 1, 2, 3, 4, 5, 6 }, 3, 4)] [InlineData(new int[] { 1, 2, 3, 4, 5, 6 }, 5, 6)] public void Peek_ReturnsAppropriateElementAfterMultiplePolls(int[] array, int timesToPoll, int expected) { var q = new ArrQueue<int>(); foreach (var item in array) q.Offer(item); for (int i = 0; i < timesToPoll; i++) q.Poll(); Assert.Equal(expected, q.Peek()); } [Fact] public void Peek_ThrowsInvalidOperationExceptionWhenEmpty() { var q = new ArrQueue<int>(); Assert.Throws<InvalidOperationException>(() => q.Peek()); } [Fact] public void Poll_ReturnsFirstElementInQueue() { var q = new ArrQueue<int>(); q.Offer(555); Assert.Equal(555, q.Poll()); } [Theory] [InlineData(new int[] { 1, 2 }, 2, 2)] [InlineData(new int[] { 1 }, 1, 1)] [InlineData(new int[] { 1, 2, 3, 4, 5, 6 }, 3, 3)] [InlineData(new int[] { 1, 2, 3, 4, 5, 6 }, 6, 6)] public void Poll_MultiplePollsReturnsAppropriateElement(int[] array, int timesToPoll, int expected) { var q = new ArrQueue<int>(); foreach (var item in array) q.Offer(item); var result = 0; for (int i = 0; i < timesToPoll; i++) result = q.Poll(); Assert.Equal(expected, result); } [Theory] [InlineData(new int[] { 1, 2 }, 6, new int[] { 6, 5, 4, 3, 2, 1 })] [InlineData(new int[] { 1 }, 4, new int[] { 4, 3, 2, 1 })] [InlineData(new int[] { 1, 2, 3, 4, 5, 6 }, 6, new int[] { 6, 5, 4, 3, 2, 1 })] [InlineData(new int[] { 1, 2, 3, 4, 5, 6 }, 11, new int[] { 6, 5, 4, 3, 2, 1 })] public void Poll_CyclesPastEndOfArrayIfRequired(int[] initialArray, int size, int[] expectedArray) { var q = new ArrQueue<int>(size); foreach (var item in initialArray) q.Offer(item); for (var i = 0; i < initialArray.Length; i++) q.Poll(); foreach (var item in expectedArray) q.Offer(item); var j = 0; for (j = 0; j < expectedArray.Length; j++) Assert.Equal(expectedArray[j], q.Poll()); Assert.Equal(expectedArray.Length, j); } [Fact] public void Poll_ThrowsInvalidOperationExceptionWhenEmpty() { var q = new ArrQueue<int>(); Assert.Throws<InvalidOperationException>(() => q.Poll()); } [Theory] [InlineData(new int[] { })] [InlineData(new int[] { 1 })] [InlineData(new int[] { 1, 2, 3, 4, 5 })] public void CanUseIterator(int[] array) { var q = new ArrQueue<int>(2); foreach (var item in array) q.Offer(item); var i = 0; foreach (var item in q) { Assert.Equal(array[i], item); i++; } Assert.Equal(array.Length, i); } } }
bbe79524e19d33314edb7bd6e433ebcee63830c2
C#
sandalkuilang/wb
/Container/Common.Document/Workbook.cs
2.6875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Runtime.Serialization.Formatters.Binary; using System.Net; namespace Common.Document { public abstract class Workbook { public abstract Stream FileStream { get; protected set; } public abstract bool IsReadOnly { get; } public Workbook(string path, SourceContent source) { if (source == SourceContent.Local) { File.SetAttributes(path, FileAttributes.Normal); this.FileStream = File.Open(path, FileMode.Open); } else { WebRequest req = WebRequest.Create(path); req.UseDefaultCredentials = true; req.PreAuthenticate = true; req.Credentials = CredentialCache.DefaultCredentials; WebResponse result = req.GetResponse(); this.FileStream = result.GetResponseStream(); } } public Workbook(Stream stream) { this.FileStream = stream; } public Workbook(StreamReader stream) { this.FileStream = stream.BaseStream; } protected byte[] ObjectToByteArray(Object obj) { if (obj == null) return null; BinaryFormatter bf = new BinaryFormatter(); MemoryStream ms = new MemoryStream(); bf.Serialize(ms, obj); return ms.ToArray(); } public abstract byte[] Write(); public abstract ExcelTabular this[int index] { get; } public abstract string[] GetSheetNames(); public abstract ExcelTabular GetSheet(string name); public abstract ExcelTabular GetSheet(int index); public abstract string GetSheetName(int index); public abstract void RemoveSheet(int index); public abstract void RemoveSheet(string name); public abstract void SetActiveSheet(string name); public abstract void SetActiveSheet(int index); } public enum SourceContent { Local = 1, Url } }
050a79e92e80535e1050a0bfb99951eed7e39c5d
C#
programming-653501/maksim_medunetski
/lab4_2.cs
3.5625
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; namespace lab4_2 { class Program { static bool Check(string s) { string symbols = "ABCEKMHOPTX"; foreach (char c in s) { if (symbols.IndexOf(c) == -1) return false; } return true; } static void Main(string[] args) { using (StreamReader reader = new StreamReader("input.txt")) { string str = reader.ReadToEnd(); string[] words = str.Split(new char[] { ' ', '.', ',','\r','\n' }, StringSplitOptions.RemoveEmptyEntries); foreach (string word in words) { //Console.WriteLine(word); if (Check(word)) Console.Write(word + " "); } } Console.ReadKey(); } } }
bb4fafc3997bec0abf0f471f22e6c9d47eb4867f
C#
NikitaPW/Ray-Tracing
/WindowsFormsApp9/Matrix4d.cs
2.8125
3
using System; using System.Collections.Generic; using System.Drawing.Drawing2D; using System.Linq; using System.Net.NetworkInformation; using System.Text; using System.Threading.Tasks; namespace WindowsFormsApp9 { public class Matrix4d { public float[,] mat; int size = 4; public float this[int r, int c] { get { return mat[r, c]; } set { mat[r, c] = value; } } public Matrix4d(float m00 = 1.0f, float m01 = 0.0f, float m02 = 0.0f, float m03 = 0.0f, float m10 = 0.0f, float m11 = 1.0f, float m12 = 0.0f, float m13 = 0.0f, float m20 = 0.0f, float m21 = 0.0f, float m22 = 1.0f, float m23 = 0.0f, float m30 = 0.0f, float m31 = 0.0f, float m32 = 0.0f, float m33 = 1.0f) { mat = new float[4, 4]; mat[0, 0] = m00; mat[0, 1] = m01; mat[0, 2] = m02; mat[0, 3] = m03; mat[1, 0] = m10; mat[1, 1] = m11; mat[1, 2] = m12; mat[1, 3] = m13; mat[2, 0] = m20; mat[2, 1] = m21; mat[2, 2] = m22; mat[2, 3] = m23; mat[3, 0] = m30; mat[3, 1] = m31; mat[3, 2] = m32; mat[3, 3] = m33; } public Matrix4d(Matrix4d a) { mat = new float[4, 4]; mat[0, 0] = a[0, 0]; mat[0, 1] = a[0, 1]; mat[0, 2] = a[0, 2]; mat[0, 3] = a[0, 3]; mat[1, 0] = a[1, 0]; mat[1, 1] = a[1, 1]; mat[1, 2] = a[1, 2]; mat[1, 3] = a[1, 3]; mat[2, 0] = a[2, 0]; mat[2, 1] = a[2, 1]; mat[2, 2] = a[2, 2]; mat[2, 3] = a[2, 3]; mat[3, 0] = a[3, 0]; mat[3, 1] = a[3, 1]; mat[3, 2] = a[3, 2]; mat[3, 3] = a[3, 3]; } public static Matrix4d TranslateMatrix(float x, float y, float z) { Matrix4d temp = new Matrix4d(); temp[0, 3] = x; temp[1, 3] = y; temp[2, 3] = z; return temp; } public static Matrix4d ScaleMatrix(float x, float y, float z) { Matrix4d temp = new Matrix4d(); temp[0, 0] = x; temp[1, 1] = y; temp[2, 2] = z; return temp; } public static Matrix4d RotateMatrix(float x, float y, float z) { Matrix4d tempX = Matrix4d.RotateXMatrix(x); Matrix4d tempY = Matrix4d.RotateYMatrix(y); Matrix4d tempZ = Matrix4d.RotateZMatrix(z); return tempX * tempY * tempZ; } public static Matrix4d RotateXMatrix(float x) { Matrix4d temp = new Matrix4d(); temp[1, 1] = (float)Math.Cos(x); temp[1, 2] = (float)Math.Sin(x) * -1.0f; temp[2, 1] = (float)Math.Sin(x); temp[2, 2] = (float)Math.Cos(x); return temp; } public static Matrix4d RotateYMatrix(float y) { Matrix4d temp = new Matrix4d(); temp[0, 0] = (float)Math.Cos(y); temp[0, 2] = (float)Math.Sin(y) ; temp[2, 0] = (float)Math.Sin(y) * -1.0f; temp[2, 2] = (float)Math.Cos(y); return temp; } public static Matrix4d RotateZMatrix(float z) { Matrix4d temp = new Matrix4d(); temp[0, 0] = (float)Math.Cos(z); temp[0, 1] = (float)Math.Sin(z) * -1.0f; temp[1, 0] = (float)Math.Sin(z) ; temp[1, 1] = (float)Math.Cos(z); return temp; } public static Matrix4d operator *(Matrix4d a, Matrix4d b) { Matrix4d temp = new Matrix4d(); for (int r = 0; r < a.size; r++) { for (int c = 0; c < a.size; c++) { temp[r, c] = a[r, 0] * b[0, c] + a[r, 1] * b[1, c] + a[r, 2] * b[2, c] + a[r, 3] * b[3, c]; } } return temp; } public static Matrix4d operator *(Matrix4d a, float b) { Matrix4d temp = new Matrix4d(a); for (int r = 0; r < a.size; r++) { for (int c = 0; c < a.size; c++) { temp[r, c] = temp[r, c] * b; } } return temp; } public Matrix4d Transpose() { Matrix4d temp = new Matrix4d(this); for (int r = 0; r < temp.size; r++) { for (int c = 0; c < temp.size; c++) { this[r, c] = temp[c, r]; } } return this; } public Matrix3d Sub(int x, int y) { Matrix3d sub = new Matrix3d(); int i = 0; for (int r = 0; r < this.size; r++) { int j = 0; if (r == x) continue; for (int c = 0; c < this.size; c++) { if (c == y) { continue; } sub[i, j] = this.mat[r, c]; j++; } i++; } return sub; } public float Det() { return mat[0, 3] * mat[1, 2] * mat[2, 1] * mat[3, 0] - mat[0, 2] * mat[1, 3] * mat[2, 1] * mat[3, 0] - mat[0, 3] * mat[1, 1] * mat[2, 2] * mat[3, 0] + mat[0, 1] * mat[1, 3] * mat[2, 2] * mat[3, 0] + mat[0, 2] * mat[1, 1] * mat[2, 3] * mat[3, 0] - mat[0, 1] * mat[1, 2] * mat[2, 3] * mat[3, 0] - mat[0, 3] * mat[1, 2] * mat[2, 0] * mat[3, 1] + mat[0, 2] * mat[1, 3] * mat[2, 0] * mat[3, 1] + mat[0, 3] * mat[1, 0] * mat[2, 2] * mat[3, 1] - mat[0, 0] * mat[1, 3] * mat[2, 2] * mat[3, 1] - mat[0, 2] * mat[1, 0] * mat[2, 3] * mat[3, 1] + mat[0, 0] * mat[1, 2] * mat[2, 3] * mat[3, 1] + mat[0, 3] * mat[1, 1] * mat[2, 0] * mat[3, 2] - mat[0, 1] * mat[1, 3] * mat[2, 0] * mat[3, 2] - mat[0, 3] * mat[1, 0] * mat[2, 1] * mat[3, 2] + mat[0, 0] * mat[1, 3] * mat[2, 1] * mat[3, 2] + mat[0, 1] * mat[1, 0] * mat[2, 3] * mat[3, 2] - mat[0, 0] * mat[1, 1] * mat[2, 3] * mat[3, 2] - mat[0, 2] * mat[1, 1] * mat[2, 0] * mat[3, 3] + mat[0, 1] * mat[1, 2] * mat[2, 0] * mat[3, 3] + mat[0, 2] * mat[1, 0] * mat[2, 1] * mat[3, 3] - mat[0, 0] * mat[1, 2] * mat[2, 1] * mat[3, 3] - mat[0, 1] * mat[1, 0] * mat[2, 2] * mat[3, 3] + mat[0, 0] * mat[1, 1] * mat[2, 2] * mat[3, 3]; } public Matrix4d Adjugate() { Matrix4d adj = new Matrix4d(); for (int r =0; r < size; r++) { for (int c =0; c < size; c++) { adj[r, c] = this.Sub(r, c).Det(); if (((r + c) % 2) != 0) { adj[r, c] *= -1.0f; } } } return adj; } public Matrix4d Inverse() { Matrix4d inverse = new Matrix4d(); float det = Det(); //Console.WriteLine(det); if (!Help.FloatEquality(det, 0.0f)) { inverse = this.Adjugate().Transpose() * (1.0f / det); } return inverse; } } }
2daaa58e4d7b57841101b70aa8adcddc30f9acef
C#
AGGP-NHTI/GinyuForce
/Assets/Nicole/falling debri/falling_objects.cs
2.65625
3
using System.Collections; using System.Collections.Generic; using UnityEngine; public class falling_objects : Actor { //length to right [SerializeField] private float limit = 0; //amount of spawners and their x-locations [SerializeField] private float[] positions = null; //enemy prefab holders [SerializeField] private GameObject[] enemyPrefabs = null; //amount of falling [SerializeField] private Wave[] wave = null; private float currentTime; List<float> remainingPosition = new List<float>(); private int waveIndex; float xPositions = 0; int rand; void Start() { currentTime = 0; remainingPosition.AddRange(positions); } void Update() { //if statement == true, set currentTime -= Time.deltaTime if (currentTime <= 0) { SelectWave(); } } void SpawnObject(float xPosition) { int r = Random.Range(0, 3); //3 types of falling entities GameObject enemyObject = Instantiate(enemyPrefabs[r], new Vector3(xPosition, transform.position.y, 0), Quaternion.identity); } void SelectWave() { remainingPosition = new List<float>(); remainingPosition.AddRange(positions); waveIndex = Random.Range(0, wave.Length); currentTime = wave[waveIndex].delayTime; if (wave[waveIndex].spawnAmount ==1) { xPositions = Random.Range(-limit, limit); } else if (wave[waveIndex].spawnAmount > 1) { rand = Random.Range(0, remainingPosition.Count); xPositions = remainingPosition[rand]; remainingPosition.RemoveAt(rand); } for (int i = 0; i < wave[waveIndex].spawnAmount; i++) { SpawnObject(xPositions); rand = Random.Range(0, remainingPosition.Count); xPositions = remainingPosition[rand]; remainingPosition.RemoveAt(rand); } } } //timer between spawns //amount spawned [System.Serializable] public class Wave { public float delayTime; public float spawnAmount; }
70b225df59fc14b85394585a502a63e88c084f77
C#
Geronius/BizTalk-Software-Factory
/BizTalkSoftwareFactory for BizTalk Server 2010/BizTalkSoftwareFactory/References/SolutionFolderRecipeReference.cs
2.640625
3
using System; using EnvDTE; using EnvDTE80; using VSLangProj; using System.Runtime.Serialization; using Microsoft.Practices.RecipeFramework; namespace BizTalkSoftwareFactory.References { /// <summary> /// UnBoundRecipe that allows to be executed only on Solution Folders /// </summary> [Serializable] public class SolutionFolderRecipeReference : UnboundRecipeReference { /// <summary> /// Constructor of the SolutionFolderRecipeReference that must specify the /// recipe name that will be used by the reference /// </summary> /// <param name="recipe"></param> public SolutionFolderRecipeReference(string recipe) : base(recipe) { } /// <summary> /// Returns a friendly name as Any Solution folder /// </summary> public override string AppliesTo { get { return "Any Solution Folder or the Solution Root"; } } /// <summary> /// Performs the validation of the item passed as target /// Returns true if the reference is allowed to be executed in the target /// that is if the target is a solution folder /// </summary> /// <param name="target"></param> /// <returns></returns> public override bool IsEnabledFor(object target) { if (target is SolutionFolder || target is Solution) { return true; } if (!(target is Project)) { return false; } return (((Project)target).Object is SolutionFolder); } #region ISerializable Members /// <summary> /// Required constructor for deserialization. /// </summary> protected SolutionFolderRecipeReference(SerializationInfo info, StreamingContext context) : base(info, context) { } #endregion ISerializable Members } }
bd72eda8034f61974c30155b6f9124e1e09528d1
C#
EdgeKing810/SphereShooter
/Assets/Scripts/playerMovement.cs
2.5625
3
using System.Collections; using System.Collections.Generic; using UnityEngine; using SimpleInputNamespace; public class playerMovement : MonoBehaviour { public Transform rotator; private Rigidbody cubeRb; public float speed = 5.0f; private Vector2 input; void Start() { cubeRb = GetComponent<Rigidbody>(); } void FixedUpdate() { if (GetInput("Horizontal", "Vertical")) { MovePlayer(); } if (GetInput("MouseX", "MouseY")) { RotateTurret(); } } bool GetInput(string horizontal, string vertical) { input.x = SimpleInput.GetAxisRaw(horizontal) * speed; input.y = SimpleInput.GetAxisRaw(vertical) * speed; return (Mathf.Abs(input.x) > 0.01f) || (Mathf.Abs(input.y) > 0.01f); } void MovePlayer() { cubeRb.velocity = Vector3.Normalize(new Vector3(input.x, 0, input.y)) * speed; } void RotateTurret() { rotator.eulerAngles = new Vector3(0, Mathf.Atan2(input.x, input.y) * 180 / Mathf.PI, 0); } }
e1d7750f70cb3100b69a2fb014b6b9bcdfb881fc
C#
atman/CSharp-DotNet
/OOPS Assignment/PolymorphismChallenge/PolymorphismChallenge/Program.cs
3.15625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PolymorphismChallenge { class Program { static void Main(string[] args) { Employee perEmp = new PermanentEmployee(); Employee conEmp = new ContractedEmployee(); //Initilizing values for the employees perEmp.EmployeeId = 1; perEmp.EmployeeName = "Atman"; perEmp.DaysofAttendance = 21; perEmp.DeductionAmount = 0; perEmp.CompensationRatePerHour = 25; perEmp.TotalHoursOfWork = 100; conEmp.EmployeeId = 2; conEmp.EmployeeName = "Batman"; conEmp.DeductionAmount = 1200; conEmp.DaysofAttendance = 17; conEmp.CompensationRatePerHour = 28; conEmp.TotalHoursOfWork = 145; //Create and Add to list List<Employee> payRollList = new List<Employee>(); payRollList.Add(perEmp); payRollList.Add(conEmp); EmployeeSalaryCalculator empSalCalc = new EmployeeSalaryCalculator(); empSalCalc.calculateSalaryOfEmployee(payRollList); Console.ReadKey(); } } }
3f7989a516b68d0f8ae838c85deee55d32707709
C#
AndrewColbeck/CSharp_ObjectOrientedGame
/Tests/TestInventory.cs
3.171875
3
// Title: 5-1C - TestInventory.cs // Author: Andrew Colbeck © 2018, all rights reserved. // Version: 1.0 // Description: Unit Tests for Inventory Class in Swinadventure // Last modified: 6/04/2018 // To Fix: Complete! using NUnit.Framework; namespace SwinAdventure { [TestFixture()] public class TestInventory { [Test] // PUT: The inventory has items that are put in it public void TestFindItem() { Inventory testInventoryObject = new Inventory(); Item testItem = new Item(new string[] { "a TestFirstId", "TestSecondId" }, "TestName", "TestDesc"); testInventoryObject.Put(testItem); bool actual = testInventoryObject.HasItem("a testfirstid"); bool expected = true; Assert.AreEqual(expected, actual, "Item not retrieved from Inventory correctly."); } [Test] // HASITEM: does not have items it does not contain public void TestDontFindNonexistingItem() { Inventory testInventoryObject = new Inventory(); Item testItem = new Item(new string[] { "a TestFirstId", "TestSecondId" }, "TestName", "TestDesc"); testInventoryObject.Put(testItem); bool actual = testInventoryObject.HasItem("Non-existent Item"); bool expected = false; Assert.AreEqual(expected, actual, "Item retrieved from Inventory incorrectly."); } [Test] // FETCH: Returns items it has, and the item remains in the inventory public void TestFetchItem() { Inventory testInventoryObject = new Inventory(); Item testItem = new Item(new string[] { "a TestFirstId", "TestSecondId" }, "TestName", "TestDesc"); testInventoryObject.Put(testItem); Item fetchedItem = testInventoryObject.Fetch("a testfirstid"); bool actual = testInventoryObject.HasItem("a testfirstid"); bool expected = true; Assert.AreEqual(expected, actual, "Item has been fetched and no longer exists in inventory."); } [Test] // TAKE: Returns items it has, and the item remains in the inventory public void TestTakeItem() { Inventory testInventoryObject = new Inventory(); Item testItem = new Item(new string[] { "a TestFirstId", "TestSecondId" }, "TestName", "TestDesc"); testInventoryObject.Put(testItem); testInventoryObject.Take("a testfirstid"); Item actual = testInventoryObject.Take("a testfirstid"); Item expected = null; Assert.AreEqual(expected, actual, "Item has been taken but still remains in the inventory."); } [Test] // ITEMLIST: returnsstring with one row per item and indented short descriptions public void TestItemList() { Inventory testInventoryObject = new Inventory(); Item testItem1 = new Item(new string[] { "shovel", "spade" }, "a shovel", "a mighty fine shovel"); Item testItem2 = new Item(new string[] { "sword", "medieval battle sword" }, "a bronze sword", "a mighty sharp sword"); Item testItem3 = new Item(new string[] { "pc", "a small terminal" }, "a small computer", "a small but fast computer"); testInventoryObject.Put(testItem1); testInventoryObject.Put(testItem2); testInventoryObject.Put(testItem3); string actual = testInventoryObject.ItemList; string expected = "\ta shovel (shovel)\n\ta bronze sword (sword)\n\ta small computer (pc)\n"; Assert.AreEqual(expected, actual, "Item List not returning short descriptions correctly"); } } }
f630e04bc3bdf348978736a9df4c97df46a419b9
C#
krolu/TowerDefenseColab
/TowerDefenseColab/GamePhases/StartScreen.cs
2.671875
3
using System; using System.Drawing; using System.Windows.Forms; namespace TowerDefenseColab.GamePhases { public class StartScreen : GamePhase { private readonly GamePhaseManager _gamePhaseManager; private readonly Image _background; public StartScreen(InputManager inputManager, GamePhaseManager gamePhaseManager) { _gamePhaseManager = gamePhaseManager; inputManager.OnClick += InputManagerOnOnClick; _background = Image.FromFile(@"Assets\menu.png"); } private void InputManagerOnOnClick(MouseEventArgs mouseEventArgs) { // Only respond to input when visible. if (IsVisible) { _gamePhaseManager.ChangeActiveGamePhase(GamePhaseEnum.Level001); } } public override void Init() { } public override void Update(TimeSpan timeDelta) { } public override void Render(BufferedGraphics g) { g.Graphics.DrawImage(_background, 0, 0); } } }