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
71de0660c11bfd2e0e6d6c09fdabd2bd07717f62
C#
Holmes-s/Deck-Package
/Assets/Scripts/Hand.cs
2.796875
3
using System.Collections.Generic; using UnityEngine; namespace Photon.Pun.CardPackage { public class Hand : Collection { /// <summary> /// Draw an amount of cards from the beginning of a targeted card collection /// </summary> /// <param name="collection">target card collection</param> /// <param name="amount">amount to draw</param> public int Draw(Collection collection, int amount = 1) { int Overflow = 0; if (amount >= collection.cards.Count) { Overflow = amount - collection.cards.Count; amount = collection.cards.Count; } Add(collection.cards.GetRange(0, amount)); for (int i = 0; i < amount; i++) { collection.Remove(0); } //pull extra while (Overflow > 0 && collection.discards.Count != 0) { //return discards to deck if deck is empty if (collection.cards.Count == 0) { collection.Add(collection.discards); collection.discards.Clear(); collection.Shuffle(); } Add(collection.cards.GetRange(0, Overflow)); int DeckCount = collection.cards.Count; for (int i = 0; i < DeckCount; i++) { Overflow -= 1; collection.Remove(0); } } if (collection.cards.Count == 0 && collection.discards.Count != 0) { //return discards to deck if deck is empty if (collection.cards.Count == 0) { collection.Add(collection.discards); collection.discards.Clear(); collection.Shuffle(); } } return Overflow; } // /////// public override void Discard(int index) { discards.Add(cards[index]); Remove(index); } public override void DiscardAll() { discards.AddRange(cards); Clear(); } public override void Shuffle() { List<PlayingCard> temp = new List<PlayingCard>(); int StartLength = cards.Count; for (int i = 0; i < StartLength; i++) { int tempRand = Random.Range(0, cards.Count); temp.Add(cards[tempRand]); cards.RemoveAt(tempRand); } cards.Clear(); cards = temp; } public override void Add(PlayingCard card) { cards.Add(card); } public override void Add(List<PlayingCard> card) { cards.AddRange(card); } public override void Add(PlayingCard card, int index = 0) { cards.Insert(index, card); } public override void Add(List<PlayingCard> card, int index = 0) { cards.InsertRange(index, card); } public override void Remove(int index) { cards.RemoveAt(index); } public override void Remove(PlayingCard card) { cards.Remove(card); } public override void Clear() { cards.Clear(); } } }
4bc949f99cd7d82e11872f429db1c4a8cd5958e4
C#
gormel/SuperLib
/SuperCore/SuperCore/Utils/Utils.cs
3
3
using System; using System.Collections.Generic; using System.Linq; namespace SuperCore.Utilses { internal static class Utils { private static readonly Dictionary<Tuple<Type, int>, Type> mTypesCashe = new Dictionary<Tuple<Type, int>, Type>(); public static Type GetActionWrapper<T>(Type[] argTypes) { var key = Tuple.Create(typeof (T), argTypes.Length); if (!mTypesCashe.ContainsKey(key)) { var genericTypes = AppDomain.CurrentDomain.GetAssemblies() .SelectMany(a => a.GetTypes()) .Where(t => t.BaseType == typeof (T) || t.GetInterface(typeof (T).Name) != null); var foundType = genericTypes.First(t => t.GetGenericArguments().Length == argTypes.Length); mTypesCashe.Add(key, foundType); } var interestingType = mTypesCashe[key]; if (argTypes.Length <= 0) return interestingType; return interestingType.MakeGenericType(argTypes); } public static Type GetFuncWrapper<T>(Type resultType, Type[] argTypes) { return GetActionWrapper<T>(argTypes.Concat(new[] {resultType}).ToArray()); } } }
1b4667e9ddaa2029ac94fa1e741cb41176390e60
C#
shira-zichel/CloudComputingProject1
/BE/Doctor.cs
2.515625
3
using System; using System.Collections.Generic; using System.Text; namespace BE { public class Doctor { public string Name { get; set; } public int age { get; set; } public string WorkPlace { get; set; } public int ID { get; set; } public override string ToString() { return $"id:{ID} name:{Name} WorkPlace:{WorkPlace}"; } } }
59da06a9227c97664c86cf061b9f2f83133e6020
C#
mco2hy/CoopSimulator
/CoopSimulator.Helper/DateHelper.cs
3.421875
3
using System; namespace CoopSimulator.Helper { public class DateHelper { public static int MonthDifferenceBetweenTwoDate(DateTime startDate, DateTime endDate) { return (endDate.Year - startDate.Year) * 12 + endDate.Month - startDate.Month; } public static int WeekDifferenceBetweenTwoDate(DateTime startDate, DateTime endDate) { return (int)Math.Floor((endDate - startDate).TotalDays / 7); } public static int YearDifferenceBetweenTwoDate(DateTime startDate, DateTime endDate) { int years = endDate.Year - startDate.Year; if (startDate.Month == endDate.Month && endDate.Day < startDate.Day || endDate.Month < startDate.Month) { years--; } return years; } } }
27ebdb5a1725fa689b3e6bd34c27970399324d04
C#
pupentamaster/GreenSuperGreen
/GreenSuperGreen.NetStandard/Exceptions/StackTraceExceptionUC/StackTraceExceptionUC.cs
2.765625
3
using System; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.Serialization; // ReSharper disable UnusedMember.Global // ReSharper disable InconsistentNaming // ReSharper disable CheckNamespace namespace GreenSuperGreen.Exceptions { /// <summary> /// Allows to create Exception with <see cref="StackTrace"/> /// skipping requested number of <see cref="StackFrame"/>'s /// </summary> public class StackTraceExceptionUC : Exception { public override string StackTrace { get; } public StackTraceExceptionUC() { } [MethodImpl(MethodImplOptions.NoInlining)] public StackTraceExceptionUC(string message, int skipStackFrames = 1) : base(message) { skipStackFrames = skipStackFrames < 0 ? 0 : skipStackFrames; StackTrace st = new StackTrace(skipStackFrames, true); StackTrace = st.ToString(); } [MethodImpl(MethodImplOptions.NoInlining)] public StackTraceExceptionUC(string message, int skipStackFrames = 1, Exception innerException = null) : base(message, innerException) { skipStackFrames = skipStackFrames < 0 ? 0 : skipStackFrames; StackTrace st = new StackTrace(skipStackFrames, true); StackTrace = st.ToString(); } protected StackTraceExceptionUC(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
5ca239fb392f7986d0b4e43b17aec44cc4e38577
C#
PStanos/Unity-Editor-Tuts
/Assets/Scripts/Grid/TileDirectory.cs
2.5625
3
using UnityEngine; using System.Collections; using System.Collections.Generic; [System.Serializable] public class TileDirectory : ScriptableObject { [SerializeField] private List<TileType> _tileTypes; public List<TileType> TileTypes { get { return _tileTypes; } set { _tileTypes = value; } } #if UNITY_EDITOR public void AddTileType() { TileType tileType = ScriptableObject.CreateInstance<TileType>(); _tileTypes.Add(tileType); UnityEditor.AssetDatabase.AddObjectToAsset(tileType, this); UnityEditor.AssetDatabase.SaveAssets(); UnityEditor.AssetDatabase.Refresh(); } public void DeleteTileType(TileType tileType) { _tileTypes.Remove(tileType); DestroyImmediate(tileType, true); UnityEditor.AssetDatabase.SaveAssets(); UnityEditor.AssetDatabase.Refresh(); } #endif }
3e3dbb24d444633d449ff21d2be558e93ccf6e90
C#
ufanatoly/practicePeton
/mdbWrite/Class1.cs
2.859375
3
using System; using System.Collections.Generic; using System.Data.OleDb; using System.Linq; using System.Text; using System.Threading.Tasks; namespace mdbWrite { public class MdbWrite { public void addAtributes(string connectionString, string[] strArrayName, string[] strArrayValue) { string strSQL = "select C.linkage_index " + "from label_values A, labels B, linkage C " + "where A.label_value_index = B.label_value_index and B.label_name_index = 3 and C.label_file_index = 5 and C.linkage_index = B.linkage_index and A.label_value NOT LIKE ('%End%')"; OleDbConnection connection = new OleDbConnection(connectionString); connection.Open(); OleDbCommand command = new OleDbCommand(strSQL, connection); OleDbDataReader dataReader = command.ExecuteReader(); List<int> eqiupmentNames = new List<int>(); while (dataReader.Read()) { eqiupmentNames.Add(dataReader.GetInt32(0)); } int n = strArrayName.Length; int[] names = new int[n]; int[] values = new int[n]; //добовляем в бд атрибуты for (int i = 0; i < n; i++) { strSQL = "select max(label_name_index) from label_names"; command = new OleDbCommand(strSQL, connection); int ind = (int)command.ExecuteScalar(); ind++; names[i] = ind; strSQL = "insert into label_names values (" + ind + ", '" + strArrayName[i] + "', 1, -1, -1)"; command = new OleDbCommand(strSQL, connection); command.ExecuteNonQuery(); strSQL = "select max(label_value_index) from label_values"; command = new OleDbCommand(strSQL, connection); ind = (int)command.ExecuteScalar(); ind++; values[i] = ind; strSQL = "insert into label_values values (" + ind + ", '" + strArrayValue[i] + "', 0)"; command = new OleDbCommand(strSQL, connection); command.ExecuteNonQuery(); } //добовляем атарибуты в модели for (int j = 0; j < eqiupmentNames.Count(); j++) { strSQL = "select max(label_line_number) from labels where linkage_index = " + eqiupmentNames[j]; command = new OleDbCommand(strSQL, connection); int ind = (int)((Int16)command.ExecuteScalar()); ind++; for (int i = 0; i < n; i++) { strSQL = "insert into labels values (" + eqiupmentNames[j] + ", '" + names[i] + "', '" + values[i] + "', " + ind + ", 0)"; command = new OleDbCommand(strSQL, connection); command.ExecuteNonQuery(); } } connection.Close(); } } }
5e3a20ce04ab718e3d4a6251e7fa1bb90df30ac9
C#
andreiboy84/EPAMPAB
/GoeuroTest/GoeuroTest/GoeuroTest.cs
2.5625
3
using NUnit.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace GoeuroTest { [TestFixture] public class GoeuroTest { [Test] public void Test1() { using (var page = new Page()) { page.TestCase1(); Thread.Sleep(5000); } } [Test] public void Test2() { using (var page = new Page()) { page.TestCase2(); Thread.Sleep(5000); } } [Test] public void Test3() { using (var page = new Page()) { page.TestCase3(); Thread.Sleep(5000); } } [Test] public void Test4() { using (var page = new Page()) { page.TestCase4(); Thread.Sleep(5000); } } [Test] public void Test5() { using (var page = new Page()) { page.TestCase5(); Thread.Sleep(5000); } } [Test] public void Test6() { using (var page = new Page()) { page.TestCase6(); Thread.Sleep(5000); } } [Test] public void Test7() { using (var page = new Page()) { page.TestCase7(); Thread.Sleep(5000); } } [Test] public void Test8() { using (var page = new Page()) { page.TestCase8(); Thread.Sleep(10000); } } [Test] public void Test9() { using (var page = new Page()) { page.TestCase9(); Thread.Sleep(5000); } } [Test] public void Test10() { using (var page = new Page()) { page.TestCase9(); Thread.Sleep(5000); } } } }
2b169d026fbe76406bf19c13ce0c0f41b921c17d
C#
ArturLehnytsky/LearningAutomation
/FirstTestFraemwork/UnitTest1.cs
2.546875
3
using System; using NUnit.Framework; using OpenQA.Selenium; using OpenQA.Selenium.Chrome; namespace FirstTestFraemwork { [TestFixture] public class UnitTest1 { public IWebDriver driver; [SetUp] public void init() { driver = new ChromeDriver(); } [Test] public void NavigatetoGoogle() { driver.Navigate().GoToUrl("https://www.google.com/"); driver.Manage().Window.Maximize(); System.Threading.Thread.Sleep(5000); } [TearDown] public void TearDown() { driver.Quit(); } } }
0541a040b9620efbaeb9bf28bad2fa784d298fb0
C#
sunneo/NesDev
/HalfNes/Com/GrapeShot/utils.cs
3.1875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace HalfNes.Com.GrapeShot { public class utils { private utils() { } public static int BIT0 = 1, BIT1 = 2, BIT2 = 4, BIT3 = 8, BIT4 = 16, BIT5 = 32, BIT6 = 64, BIT7 = 128, BIT8 = 256, BIT9 = 512, BIT10 = 1024, BIT11 = 2048, BIT12 = 4096, BIT13 = 8192, BIT14 = 16384, BIT15 = 32768; public static int setbit(int num, int bitnum, bool state) { return (state) ? (num | (1 << bitnum)) : (num & ~(1 << bitnum)); } public static String hex(int num) { String s = num.ToString("X").ToUpper(); if ((s.Length & 1) == 1) { s = "0" + s; } return s; } public static String hex(long num) { String s = num.ToString("X").ToUpper(); if ((s.Length & 1) == 1) { s = "0" + s; } return s; } public static uint ReverseBits(uint n) { n = (n >> 1) & 0x55555555 | (n << 1) & 0xaaaaaaaa; n = (n >> 2) & 0x33333333 | (n << 2) & 0xcccccccc; n = (n >> 4) & 0x0f0f0f0f | (n << 4) & 0xf0f0f0f0; n = (n >> 8) & 0x00ff00ff | (n << 8) & 0xff00ff00; n = (n >> 16) & 0x0000ffff | (n << 16) & 0xffff0000; return n; } public static int reverseByte(int nibble) { //reverses 8 bits packed into int. return (int)((ReverseBits(unchecked((uint)nibble)) >> 24) & 0xff); } public static void printarray<T>(T[] a) { StringBuilder s = new StringBuilder(); foreach (T i in a) { s.Append(i); s.Append(", "); } if (s.Length >= 1) { s.Remove(s.Length - 1, 1); } s.Append("\n"); Console.Error.WriteLine(s.ToString()); } public static int max(int[] array) { int m = array[0]; foreach (int i in array) { if (i > m) { m = i; } } return m; } } public class Arrays { public static void fill<T>(T[] arr, T val) { for (int i = 0; i < arr.Length; ++i) { arr[i] = val; } } } }
613da15691665aeea075eeb32794d85673f860c4
C#
OneEighteenNoTwo/LetterboxdCsv
/CommandLineManager/OptionAttribute.cs
2.9375
3
using System; namespace CommandLineManager { [AttributeUsage(AttributeTargets.All)] public class OptionAttribute : Attribute { public readonly string shortCmd; public readonly string longCmd; private bool required; public virtual bool Required { get { return required; } set { required = value; } } public OptionAttribute(string shortCmd, string longCmd) { this.shortCmd = shortCmd; this.longCmd = longCmd; this.required = false; } } }
73257cda40bd54d33c31179421623fdbc3c18f32
C#
AlexeyShpavda/CalculusPractice
/Inheritance/Inheritance/Models/SportsCar.cs
3.609375
4
namespace Inheritance.Models { class SportsCar : Car { private static string _color; public static string Color { get => _color; set => _color = value; } public SportsCar(string name, string number, string speed, string color) : base(name, number, speed) => Color = color; public override string displayInformationAboutTheCar(string name, string number, string speed) => base.displayInformationAboutTheCar(name, number, speed) + "\nCar color is " + Color; } }
96ed835206ecd0cb701f2ee7bd81309db0858647
C#
razuk-78/DotNetExamples
/ThreadTasks/MyTaskScheduler.cs
3.046875
3
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; class MyScheduler:IDisposable { List<Task> _tasks = new List<Task>(); CancellationTokenSource cs = new CancellationTokenSource(); Task _task; int _taskNumber =0; public MyScheduler(int taskNumber) { _taskNumber = taskNumber; } public void addToQueue(Action action) { _tasks.Add(new Task(action,cs.Token)); if (_tasks.Count < _taskNumber&& _tasks.Count>0) { _tasks[_tasks.Count - 1].Start(); } } void RunTask(Task tsk) { Console.WriteLine("form RunTask"); } void RemoveTaskWhenCompleted() { } public int GetTaskNumber() { return _tasks.Count; } public void Dispose() { cs.Cancel(); _task = null; } void RemoveTaskFromList() { _task = Task.Run(() => { while (true) { if (_tasks.Count > 0) { _tasks.Remove(Task.WhenAny(_task)); } cs.Token.ThrowIfCancellationRequested(); } },cs.Token); } }
41a7db4ba08afaacafee40a4e5a42cfcb9ef8706
C#
Digishui/Digishui.NET
/Digishui.NET/Extensions/System.Uri.cs
2.578125
3
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.IO; using System.Net; using System.Threading.Tasks; using System.Web; //=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+= namespace Digishui.Extensions { //=========================================================================================================================== /// <summary> /// System.Uri Extensions /// </summary> public static partial class Extensions { //------------------------------------------------------------------------------------------------------------------------- private static HttpWebRequest CreateRequest(Uri uri, CookieContainer cookieContainer, Uri refererUri = null, bool ignoreCertificateValidationErrors = false) { HttpWebRequest httpWebRequest = WebRequest.CreateHttp(uri); httpWebRequest.CookieContainer = cookieContainer; if (ignoreCertificateValidationErrors == true) { httpWebRequest.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => { return true; }; } httpWebRequest.AllowAutoRedirect = true; httpWebRequest.Referer = refererUri?.ToString() ?? ""; httpWebRequest.Headers.Add("DNT", "1"); httpWebRequest.UserAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 11_2_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36"; httpWebRequest.ReadWriteTimeout = 60000; httpWebRequest.Timeout = 60000; return httpWebRequest; } //------------------------------------------------------------------------------------------------------------------------- public static async Task<HttpWebResponse> WebRequestGetAsync(this Uri uri, CookieContainer cookieContainer, Uri refererUri = null) { HttpWebRequest httpWebRequest = CreateRequest(uri, cookieContainer, refererUri); HttpWebResponse httpWebResponse = await httpWebRequest.GetAsync(); return httpWebResponse; } //------------------------------------------------------------------------------------------------------------------------- public static async Task<HttpWebResponse> WebRequestPostAsync(this Uri uri, CookieContainer cookieContainer, NameValueCollection formData, Uri refererUri = null) { HttpWebRequest httpWebRequest = CreateRequest(uri, cookieContainer, refererUri); HttpWebResponse httpWebResponse = await httpWebRequest.PostAsync(formData); return httpWebResponse; } //------------------------------------------------------------------------------------------------------------------------- /// <remarks> /// https://stackoverflow.com/questions/566462/upload-files-with-httpwebrequest-multipart-form-data /// </remarks> public static async Task<HttpWebResponse> WebRequestPostAsync(this Uri uri, CookieContainer cookieContainer, NameValueCollection formData, List<FormFile> formFiles, Uri refererUri = null) { string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x"); HttpWebRequest httpWebRequest = CreateRequest(uri, cookieContainer, refererUri); httpWebRequest.ContentType = $"multipart/form-data; boundary={boundary}"; httpWebRequest.Method = "POST"; httpWebRequest.KeepAlive = true; Stream requestMemoryStream = await httpWebRequest.GetRequestStreamAsync(); if (formData != null) { foreach (string key in formData.Keys) { //If the key contains "[]//", we're dealing with the desire to submit an unindexed array based on the order //that fields bearing the same key preceding the "[]//" we added to the formData NameValueCollection. This is //handled just by submitting the same form field over and over again, and the server parses it based on order //of inclusion. So, the part following "[]//" is a descriptor to differentiate values in the collection, and //it's not sent in the POST payload. Technically, NameValueCollection halfway handles this scenario, in that //if you try to add entries with the same key multiple times it accepts tham and comma separates them, but this //becomes problematic if one of the values contains commas (it doesn't quote comma-containing values, so you //can't figure out if it's a new field with the same name or a value containing a comma). This is a hack around //the implementation of the NameValueCollection as it pertains to duplication submission of unindexed formField //arrays. string formFieldName = key; if (formFieldName.Contains("[]//") == true) { formFieldName = formFieldName.Substring(0, key.IndexOf("[]//") + 2); } string formItem = $"\r\n--{boundary}\r\nContent-Disposition: form-data; name=\"{formFieldName}\";\r\n\r\n{formData[key]}"; byte[] formItemBytes = System.Text.Encoding.UTF8.GetBytes(formItem); await requestMemoryStream.WriteAsync(formItemBytes, 0, formItemBytes.Length); } } foreach (FormFile formFile in formFiles) { string header = $"\r\n--{boundary}\r\nContent-Disposition: form-data; name=\"{formFile.FormFieldName}\"; filename=\"{formFile.FileName}\"\r\nContent-Type: {formFile.ContentType ?? "application/octet-stream"}\r\n\r\n"; byte[] headerBytes = System.Text.Encoding.UTF8.GetBytes(header); await requestMemoryStream.WriteAsync(headerBytes, 0, headerBytes.Length); await formFile.Stream.CopyToAsync(requestMemoryStream, true); } byte[] endBoundaryBytes = System.Text.Encoding.ASCII.GetBytes($"\r\n--{boundary}--"); await requestMemoryStream.WriteAsync(endBoundaryBytes, 0, endBoundaryBytes.Length); //await requestMemoryStream.CopyToAsync(await httpWebRequest.GetRequestStreamAsync(), true); //httpWebRequest.ContentLength = requestMemoryStream.Length; //using (Stream requestStream = httpWebRequest.GetRequestStream()) //{ // requestMemoryStream.Position = 0; // byte[] tempBuffer = new byte[requestMemoryStream.Length]; // requestMemoryStream.Read(tempBuffer, 0, tempBuffer.Length); // requestMemoryStream.Close(); // requestStream.Write(tempBuffer, 0, tempBuffer.Length); //} return (HttpWebResponse)(await httpWebRequest.GetResponseAsync()); } } }
eea792e82ecec06bd858029f37f57d04a58a5079
C#
dev2dev-community/d2dquest
/src/D2DQuest.BusinessLogic/Commands/RegisterWordCommand.cs
2.515625
3
using System; using System.Linq; using D2DQuest.Contracts.Commands.Exceptions; using D2DQuest.Contracts.DataAccessLayer; using D2DQuest.ObjectDomain; using D2DQuest.Contracts.Exceptions; using D2DQuest.Contracts.Commands; namespace D2DQuest.BusinessLogic.Commands { public class RegisterWordCommand : IRegisterWordCommand { private readonly IUnitOfWorkFactory _uowFactory; public RegisterWordCommand(IUnitOfWorkFactory uowFactory) { if (uowFactory == null) throw new ArgumentNullException("uowFactory"); _uowFactory = uowFactory; } public void Register(string visiterUid, string word) { try { using (var uow = _uowFactory.Create()) { var keyWord = uow.Items<KeyWord>().FirstOrDefault(w => w.Word.ToLower() == word.ToLower()); if (keyWord == null) throw new WordNotExistException(word); var visiter = uow.Items<Visiter>().FirstOrDefault(v => v.Uid.ToUpper() == visiterUid.ToUpper()); if (visiter == null) throw new VisiterNotExistException(visiterUid); if (uow.Items<WordRegistration>().Any(r => r.Visiter.Id == visiter.Id && r.Word.Id == keyWord.Id)) throw new WordRegistedAlreadyException(visiterUid, word); uow.Add(new WordRegistration { Time = DateTime.UtcNow, Word = keyWord, Visiter = visiter }); uow.Commit(); } } catch (LogicException) { throw; } catch (WrappedUnexpectedException) { throw; } catch(Exception ex) { throw new RegisterWordCommandException(ex, visiterUid, word); } } } }
83ed887e4efc8a87981c6ee6c0a0e20a747d0abe
C#
relaxar/ngenerics
/src/NGenerics.Tests/DataStructures/General/VertexTests/GetIncidentEdgeWith.cs
2.546875
3
/* Copyright 2007-2017 The NGenerics Team (https://github.com/ngenerics/ngenerics/wiki/Team) This program is licensed under the MIT License. You should have received a copy of the license along with the source code. If not, an online copy of the license can be found at https://opensource.org/licenses/MIT. */ using NGenerics.DataStructures.General; using NUnit.Framework; namespace NGenerics.Tests.DataStructures.General.VertexTests { [TestFixture] public class GetIncidentEdgeWith:VertexTest { [Test] public void Undirected() { var vertex1 = new Vertex<int>(3); var vertex2 = new Vertex<int>(5); var vertex3 = new Vertex<int>(8); var graph = new Graph<int>(false); graph.AddVertex(vertex1); graph.AddVertex(vertex2); graph.AddEdge(vertex1, vertex2); var edge = vertex1.GetIncidentEdgeWith(vertex2); Assert.AreEqual(edge.FromVertex, vertex1); Assert.AreEqual(edge.ToVertex, vertex2); edge = vertex2.GetIncidentEdgeWith(vertex1); Assert.AreEqual(edge.FromVertex, vertex1); Assert.AreEqual(edge.ToVertex, vertex2); Assert.IsNull(vertex1.GetIncidentEdgeWith(vertex3)); } [Test] public void Directed() { var vertex1 = new Vertex<int>(3); var vertex2 = new Vertex<int>(5); var vertex3 = new Vertex<int>(8); var graph = new Graph<int>(true); graph.AddVertex(vertex1); graph.AddVertex(vertex2); graph.AddEdge(vertex1, vertex2); var edge = vertex1.GetIncidentEdgeWith(vertex2); Assert.AreEqual(edge.FromVertex, vertex1); Assert.AreEqual(edge.ToVertex, vertex2); edge = vertex2.GetIncidentEdgeWith(vertex1); Assert.AreEqual(edge.FromVertex, vertex1); Assert.AreEqual(edge.ToVertex, vertex2); Assert.IsNull(vertex1.GetIncidentEdgeWith(vertex3)); } } }
50e6d801feab46ecd9d06568ea6ef1584c7a21fe
C#
sepehrhh/Coursera_Algorithm_Implementations
/A4/A4/Node.cs
2.734375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace A2 { public class Node { public Node Prev { get; set; } public long Distance { get; set; } public long Data { get; set; } public Nullable<long> QueueIndex { get; set; } public long[] Coordinates { get; } public double FScore { get; set; } //F is the total cost of the node. public double GScore { get; set; } //G is the distance between the current node and the start node. public double HScore { get; set; } //H is the heuristic — estimated distance from the current node to the end node. public Node(long data, long[] coordinates) { Data = data; Coordinates = coordinates; QueueIndex = null; } } }
8325741f2e758238341b4a616219e7bf5ef96138
C#
danielmoore/Extension-Method-Pack
/NorthHorizon.Common.Xmp/ObjectExtensions.cs
2.90625
3
using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Reflection; namespace NorthHorizon.Common.Xmp { /// <summary> /// Provides extension methods for all objects. /// </summary> public static class ObjectExtensions { /// <summary> /// Executes the specified action if <paramref name="obj"/> is of type <typeparamref name="T"/>. /// </summary> /// <typeparam name="T">The desired type.</typeparam> /// <param name="obj">The target object.</param> /// <param name="action">The action to perform.</param> /// <returns>Whether or not the action was able to be performed.</returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "obj")] public static bool As<T>(this object obj, Action<T> action) where T : class { if (obj == null) throw new ArgumentNullException("obj"); if (action == null) throw new ArgumentNullException("action"); var target = obj as T; if (target == null) return false; action(target); return true; } /// <summary> /// Executes the specified action if <paramref name="obj"/> is of type <typeparamref name="T"/>. /// </summary> /// <typeparam name="T">The desired type.</typeparam> /// <param name="obj">The target object.</param> /// <param name="action">The action to perform.</param> /// <returns>Whether or not the action was able to be performed.</returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "obj")] public static bool AsValueType<T>(this object obj, Action<T> action) where T : struct { if (obj == null) throw new ArgumentNullException("obj"); if (action == null) throw new ArgumentNullException("action"); if (obj is T) { action((T)obj); return true; } return false; } /// <summary> /// Gets a specified property in a chain of member accesses, checking for null at each node. /// </summary> /// <typeparam name="TRoot">The type of the root object.</typeparam> /// <typeparam name="TValue">The type of the final node.</typeparam> /// <param name="root">The target object</param> /// <param name="getExpression">The expression representing the member access chain.</param> /// <returns>The value of the target member or <code>default(TValue)</code></returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")] public static TValue ChainGet<TRoot, TValue>(this TRoot root, Expression<Func<TRoot, TValue>> getExpression) { bool success; return ChainGet(root, getExpression, out success); } /// <summary> /// Gets a specified property in a chain of member accesses, checking for null at each node. /// </summary> /// <typeparam name="TRoot">The type of the root object.</typeparam> /// <typeparam name="TValue">The type of the final node.</typeparam> /// <param name="root">The target object</param> /// <param name="getExpression">The expression representing the member access chain.</param> /// <param name="success">Whether or not the chain was completely evaluated.</param> /// <returns>The value of the target member or <code>default(TValue)</code></returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "2#")] public static TValue ChainGet<TRoot, TValue>(this TRoot root, Expression<Func<TRoot, TValue>> getExpression, out bool success) { // it's ok if root is null! if (getExpression == null) throw new ArgumentNullException("getExpression"); var members = new Stack<MemberAccessInfo>(); Expression expr = getExpression.Body; while (expr != null) { if (expr.NodeType == ExpressionType.Parameter) break; var memberExpr = expr as MemberExpression; if (memberExpr == null) throw new ArgumentException("Given expression is not a member access chain.", "getExpression"); members.Push(new MemberAccessInfo(memberExpr.Member)); expr = memberExpr.Expression; } object node = root; foreach (var member in members) { if (node == null) { success = false; return default(TValue); } node = member.GetValue(node); } success = true; return (TValue)node; } private class MemberAccessInfo { private PropertyInfo _propertyInfo; private FieldInfo _fieldInfo; public MemberAccessInfo(MemberInfo info) { _propertyInfo = info as PropertyInfo; _fieldInfo = info as FieldInfo; } public object GetValue(object target) { if (_propertyInfo != null) return _propertyInfo.GetValue(target, null); else if (_fieldInfo != null) return _fieldInfo.GetValue(target); else throw new InvalidOperationException(); } } } }
dc2b611bb9994233cd4b26fdb1c067a57ab7e916
C#
nigel-sampson/object-server
/UnitTests/Chelsea/Occasion.cs
2.6875
3
using System; using System.Xml.Serialization; using Nichevo.ObjectServer; namespace UnitTests.Chelsea { [Table("Occasions", "Id", PrimaryKeyType.Identity, DefaultOrder="name")] public abstract class Occasion : ServerObject, IComparable { public const int MaxNameLength = 50; [XmlType("Occasion")] public class ServiceProxy { private int id; private string name; public ServiceProxy() { id = -1; name = String.Empty; } public ServiceProxy(Occasion occasion) { id = occasion.Id; name = occasion.Name; } public int Id { get { return id; } set { id = value; } } public string Name { get { return name; } set { name = value; } } } public ServiceProxy ConstructProxy() { return new ServiceProxy(this); } [Column("id")] public abstract int Id { get; } [Column("name")] protected abstract string name { get; set; } public string Name { get { return name; } set { if(value == null) throw new ArgumentNullException("value", "Name cannot be null"); value = value.Trim(); if(value.Length == 0) throw new ArgumentException("Name cannot be an empty string"); if(value.Length > MaxNameLength) throw new ArgumentException(String.Format("Name cannot be more than {0} characters", MaxNameLength)); name = value; } } public int CompareTo(object obj) { if(!(obj is Occasion)) throw new ApplicationException("object is not an Occasion"); Occasion occasion = obj as Occasion; return Name.CompareTo(occasion.Name); } [Parent("featured", CanBeNull = true, DeleteAction = DeleteAction.Null)] public abstract Recipe Featured { get; set; } [Children(typeof(RecipeOccasionMap), "Occasion")] public abstract ServerObjectCollection RecipeMaps { get; } } }
b2bb1b443e2d69003400e18574f9f465b100556e
C#
OpenNefia/OpenNefia
/OpenNefia.Core/Areas/AreaId.cs
3.03125
3
namespace OpenNefia.Core.Areas { [Serializable] public readonly struct AreaId : IEquatable<AreaId> { public static readonly AreaId Nullspace = new(0); public static readonly AreaId FirstId = new(1); internal readonly int Value; public AreaId(int value) { Value = value; } /// <inheritdoc /> public bool Equals(AreaId other) { return Value == other.Value; } /// <inheritdoc /> public override bool Equals(object? obj) { if (ReferenceEquals(null, obj)) return false; return obj is AreaId id && Equals(id); } /// <inheritdoc /> public override int GetHashCode() { return Value; } public static bool operator ==(AreaId a, AreaId b) { return a.Value == b.Value; } public static bool operator !=(AreaId a, AreaId b) { return !(a == b); } public static explicit operator int(AreaId self) { return self.Value; } public override string ToString() { return Value.ToString(); } } }
5ad6a9720004386c140c7a6247126d5034c084fc
C#
mschwa/resolver
/Resolver.Case.Api/src/Services/StorageRepository.cs
2.703125
3
using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Queue; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.WindowsAzure.Storage.Table; using Resolver.Case.Api.Snapshot; namespace Resolver.Case.Api.Services { public class StorageRepository : IStorageRepository { public async Task<Models.Case> GetCaseFromStorageQueueAsync() { //Retrieve storage account from connection string CloudStorageAccount storageAccount = CaseBuilder.CreateStorageAccountFromConnectionString(); // Create the queue client CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient(); // Retrieve a reference to a queue CloudQueue queue = queueClient.GetQueueReference("case"); await queue.FetchAttributesAsync(); var cases = new List<Models.Case>(); foreach (var message in await queue.PeekMessagesAsync(queue.ApproximateMessageCount.Value)) { // Display message. Console.WriteLine(message.AsString); var myCase = JsonConvert.DeserializeObject<Models.Case>(message.AsString); cases.Add(myCase); } return new Models.Case(); } public async Task<CaseSnapshot> GetCaseSnapshotFromStorageTableAsync(string caseId) { //Retrieve storage account from connection string CloudStorageAccount storageAccount = CaseBuilder.CreateStorageAccountFromConnectionString(); // Create the queue client CloudTableClient tableClient = storageAccount.CreateCloudTableClient(); // Retrieve a reference to a queue CloudTable table = tableClient.GetTableReference("CaseSnapshot"); // Create a retrieve operation that takes a customer entity. TableOperation retrieveOperation = TableOperation.Retrieve<CaseSnapshot>("2019", caseId); // Execute the retrieve operation. TableResult retrievedResult = await table.ExecuteAsync(retrieveOperation); return ((CaseSnapshot)retrievedResult.Result); } public async Task<bool> SubmitCaseSnapshotToStorageTableAsync(CaseSnapshot caseSnapshot) { //Retrieve storage account from connection string CloudStorageAccount storageAccount = CaseBuilder.CreateStorageAccountFromConnectionString(); // Create the queue client CloudTableClient tableClient = storageAccount.CreateCloudTableClient(); // Retrieve a reference to a queue CloudTable table= tableClient.GetTableReference("CaseSnapshot"); // Create the TableOperation object that inserts the customer entity. TableOperation insertOperation = TableOperation.Insert(caseSnapshot); // Execute the insert operation. var result = await table.ExecuteAsync(insertOperation); var success = (result.HttpStatusCode == 200 || result.HttpStatusCode == 201); return Task.FromResult(success).GetAwaiter().GetResult(); } public async Task<bool> ReplaceCaseSnapshotToStorageTableAsync(CaseSnapshot caseSnapshot) { //Retrieve storage account from connection string CloudStorageAccount storageAccount = CaseBuilder.CreateStorageAccountFromConnectionString(); // Create the queue client CloudTableClient tableClient = storageAccount.CreateCloudTableClient(); // Retrieve a reference to a queue CloudTable table = tableClient.GetTableReference("CaseSnapshot"); // Create the TableOperation object that inserts the customer entity. TableOperation insertOperation = TableOperation.Replace(caseSnapshot); // Execute the insert operation. var result = await table.ExecuteAsync(insertOperation); var success = (result.HttpStatusCode == 200 || result.HttpStatusCode == 201); return Task.FromResult(success).GetAwaiter().GetResult(); } } }
87352f72ea3f5bf6dc7fca47b2536738dda6bd8e
C#
SaeedTaghavi/learning_csharp
/00_basics/03_bankAccount/03_csharp.cs
2.96875
3
using System; namespace myBank { class Program { static void Main(string[] args) { var account = new bankAccount("taghi",100); Console.WriteLine($"accont {account.Number} was created for {account.Owner} with {account.Balance}"); account.MakeWithdrawal(10, DateTime.Now, "hi"); Console.WriteLine(account.Balance); try { var invalidAccount = new bankAccount("invalid", -55); } catch (ArgumentOutOfRangeException e) { // Console.WriteLine("exception caught creating account with negative balance"); // Console.WriteLine(e.ToString()); } Console.WriteLine("\n \n \n"); account.MakeWithdrawal(20,DateTime.Now,"for xbox"); Console.WriteLine(account.Balance); Console.WriteLine(account.getAccountHistory()); } } }
b4be61684c06e1bda7df3ff9137be243749503b7
C#
NickHudgins/NickHudgins-c-sharp-material
/module-1/02_Variables_Data_Types/student-exercise/VariableNaming/Program.cs
3.515625
4
using System; namespace VariableNaming { class Program { static void Main(string[] args) { /* 1. 4 birds are sitting on a branch. 1 flies away. How many birds are left on the branch? */ int startingNumberOfBirds = 4; int numberOfBirdsThatLeave = 1; int leftOverBirds = startingNumberOfBirds - numberOfBirdsThatLeave; // ### EXAMPLE: int initialNumberOfBirds = 4; int birdsThatFlewAway = 1; int remainingNumberOfBirds = initialNumberOfBirds - birdsThatFlewAway; /* 2. There are 6 birds and 3 nests. How many more birds are there than nests? */ int birdsNeedingNests = 6; int nestsAvailable = 3; int birdsWithoutNests = birdsNeedingNests - nestsAvailable; // ### EXAMPLE: int numberOfBirds = 6; int numberOfNests = 3; int numberOfExtraBirds = numberOfBirds - numberOfNests; /* 3. 3 raccoons are playing in the woods. 2 go home to eat dinner. How many raccoons are left in the woods? */ int raccoonsPlaying = 3; int raccoonsLeavingForDinner = 2; int raccoonsLeftPlaying = raccoonsPlaying - raccoonsLeavingForDinner; /* 4. There are 5 flowers and 3 bees. How many less bees than flowers? */ int flowerInventory = 5; int numberOfBees = 3; int beesBetweenJobs = flowerInventory - numberOfBees; /* 5. 1 lonely pigeon was eating breadcrumbs. Another pigeon came to eat breadcrumbs, too. How many pigeons are eating breadcrumbs now? */ int lonelyPigeons = 1; int sypatheticPigeons = 1; int pigeonPals = lonelyPigeons + sypatheticPigeons; /* 6. 3 owls were sitting on the fence. 2 more owls joined them. How many owls are on the fence now? */ int fenceHooters = 3; int aspriringFenceHooters = 2; int totalFenceHooters = fenceHooters + aspriringFenceHooters; /* 7. 2 beavers were working on their home. 1 went for a swim. How many beavers are still working on their home? */ int homeImprovementBeavers = 2; int michaelPhelpsBeavers = 1; int beaversNeedingARaise = homeImprovementBeavers - michaelPhelpsBeavers; /* 8. 2 toucans are sitting on a tree limb. 1 more toucan joins them. How many toucans in all? */ int toucanSamsChillin = 2; int uninvitedToucanSam = 1; int threesACrowd = toucanSamsChillin + uninvitedToucanSam; /* 9. There are 4 squirrels in a tree with 2 nuts. How many more squirrels are there than nuts? */ int nutlessSquirrels = 4; int obtainableNuts = 2; int nutHungrySquirrels = nutlessSquirrels - obtainableNuts; /* 10. Mrs. Hilt found a quarter, 1 dime, and 2 nickels. How much money did she find? */ int quartersCollected = 1; int dimesDiscovered = 1; int nickelsNoticed = 2; int mrsHiltsGoodEyePayout = quartersCollected + dimesDiscovered + nickelsNoticed; /* 11. Mrs. Hilt's favorite first grade classes are baking muffins. Mrs. Brier's class bakes 18 muffins, Mrs. MacAdams's class bakes 20 muffins, and Mrs. Flannery's class bakes 17 muffins. How many muffins does first grade bake in all? */ int mrsBrierMuffinCount = 18; int mrsMacAdamsMuffinCount = 20; int mrsFlanneryMuffinCount = 17; int firstGradeMuffinTotal = mrsBrierMuffinCount + mrsFlanneryMuffinCount + mrsMacAdamsMuffinCount; /* 12. Mrs. Hilt bought a yoyo for 24 cents and a whistle for 14 cents. How much did she spend in all for the two toys? */ int yoyoPurchase = 24; int whistlePuchase = 12; int totalToyPurchase = yoyoPurchase + whistlePuchase; /* 13. Mrs. Hilt made 5 Rice Krispie Treats. She used 8 large marshmallows and 10 mini marshmallows.How many marshmallows did she use altogether? */ int largeMarshmallows = 8; int miniMarshmallows = 10; int numberOfMarshmellowsPerFiveTreats = largeMarshmallows + miniMarshmallows; /* 14. At Mrs. Hilt's house, there was 29 inches of snow, and Brecknock Elementary School received 17 inches of snow. How much more snow did Mrs. Hilt's house have? */ int homeSnowFall = 29; int schoolSnowFall = 17; int snowFallDifference = homeSnowFall - schoolSnowFall; /* 15. Mrs. Hilt has $10. She spends $3 on a toy truck and $2 on a pencil case. How much money does she have left? */ int totalFunds = 10; int toyTruckExpense = 3; int pencilExpense = 2; int leftOverFunds = totalFunds - toyTruckExpense - pencilExpense; /* 16. Josh had 16 marbles in his collection. He lost 7 marbles. How many marbles does he have now? */ int marbleCount = 16; int lostMarbles = 7; int remainingMarbles = marbleCount - lostMarbles; /* 17. Megan has 19 seashells. How many more seashells does she need to find to have 25 seashells in her collection? */ int currentShellCount = 19; int desiredShellCount = 25; int shellsNeeded = desiredShellCount - currentShellCount; /* 18. Brad has 17 balloons. 8 balloons are red and the rest are green. How many green balloons does Brad have? */ int bradsTotalBalloons = 19; int redBalloons = 8; int greenBalloons = bradsTotalBalloons - redBalloons; /* 19. There are 38 books on the shelf. Marta put 10 more books on the shelf. How many books are on the shelf now? */ int currentBooksOnShelf = 38; int booksAddedToShelf = 10; int newTotalBooksOnShelf = currentBooksOnShelf + booksAddedToShelf; /* 20. A bee has 6 legs. How many legs do 8 bees have? */ int legsPerBee = 6; int totalBees = 8; int numberOfLegs = legsPerBee * totalBees; /* 21. Mrs. Hilt bought an ice cream cone for 99 cents. How much would 2 ice cream cones cost? */ int costPerCone = 99; int desiredNumberOfCones = 2; int totalConeCost = costPerCone * desiredNumberOfCones; /* 22. Mrs. Hilt wants to make a border around her garden. She needs 125 rocks to complete the border. She has 64 rocks. How many more rocks does she need to complete the border? */ int totalRocksNeeded = 125; int rocksOnHand = 64; int numberOfRocksMissing = totalRocksNeeded - rocksOnHand; /* 23. Mrs. Hilt had 38 marbles. She lost 15 of them. How many marbles does she have left? */ int totalHiltMarbles = 38; int lostHiltMarbles = 15; int hiltMarblesRemaining = totalHiltMarbles - lostHiltMarbles; /* 24. Mrs. Hilt and her sister drove to a concert 78 miles away. They drove 32 miles and then stopped for gas. How many miles did they have left to drive? */ int milesToConcert = 78; int milesCuurentlyDriven = 32; int milesLeftTilConcert = milesToConcert - milesCuurentlyDriven; /* 25. Mrs. Hilt spent 1 hour and 30 minutes shoveling snow on Saturday morning and 45 minutes shoveling snow on Saturday afternoon. How much total time did she spend shoveling snow? */ int saturdayMorningSnowShoveled = 90; int saturdayAfternoonSnowShoveled = 45; int saturdayTotalSnowShoveled = saturdayMorningSnowShoveled + saturdayAfternoonSnowShoveled; /* 26. Mrs. Hilt bought 6 hot dogs. Each hot dog cost 50 cents. How much money did she pay for all of the hot dogs? */ int numberOfHotDogs = 6; double hotDogCost = 0.5; double totalSpent = numberOfHotDogs * hotDogCost; /* 27. Mrs. Hilt has 50 cents. A pencil costs 7 cents. How many pencils can she buy with the money she has? */ double centsOnHand = 0.5; double costPerPencil = 0.07; double numberOfPencilsPurchaseable = centsOnHand / costPerPencil; /* 28. Mrs. Hilt saw 33 butterflies. Some of the butterflies were red and others were orange. If 20 of the butterflies were orange, how many of them were red? */ int totalButterflies = 33; int orangeButterflies = 20; int redButterflies = totalButterflies - orangeButterflies; /* 29. Kate gave the clerk $1.00. Her candy cost 54 cents. How much change should Kate get back? */ double totalTender = 1.00; double candyCost = 0.54; double changeReceived = totalTender - candyCost; /* 30. Mark has 13 trees in his backyard. If he plants 12 more, how many trees will he have? */ int marksCurrentTrees = 13; int addedTrees = 12; int newTreeTotal = marksCurrentTrees + addedTrees; /* 31. Joy will see her grandma in two days. How many hours until she sees her? */ int daysTillVisit = 2; int hoursPerDay = 24; int hoursTillVisit = daysTillVisit * hoursPerDay; /* 32. Kim has 4 cousins. She wants to give each one 5 pieces of gum. How much gum will she need? */ int kimsCousinCount = 4; int gumPerCousin = 5; int gumTotalNeeded = kimsCousinCount * gumPerCousin; /* 33. Dan has $3.00. He bought a candy bar for $1.00. How much money is left? */ double dansFunds = 3.00; double candyBarCost = 1.00; double dansRemainingFunds = dansFunds - candyBarCost; /* 34. 5 boats are in the lake. Each boat has 3 people. How many people are on boats in the lake? */ int boatsAfloat = 5; int peoplePerBoat = 3; int totalPeoplePerBoat = boatsAfloat * peoplePerBoat; /* 35. Ellen had 380 legos, but she lost 57 of them. How many legos does she have now? */ int legoTotal = 380; int lostLegos = 57; int legosRemaining = legoTotal - lostLegos; /* 36. Arthur baked 35 muffins. How many more muffins does Arthur have to bake to have 83 muffins? */ int arthurMuffinsBaked = 35; int muffinsToBake = 83; int muffinsNeeded = muffinsToBake - arthurMuffinsBaked; /* 37. Willy has 1400 crayons. Lucy has 290 crayons. How many more crayons does Willy have then Lucy? */ int willyCrayons = 1400; int lucyCrayons = 290; int willyDiffernce = willyCrayons - lucyCrayons; /* 38. There are 10 stickers on a page. If you have 22 pages of stickers, how many stickers do you have? */ int stickerPerPage = 10; int totalStickerPages = 22; int totalStickers = stickerPerPage * totalStickerPages; /* 39. There are 96 cupcakes for 8 children to share. How much will each person get if they share the cupcakes equally? */ int cupcakeTotal = 96; int kidTotal = 8; int cupcakePerKidTotal = cupcakeTotal / kidTotal; /* 40. She made 47 gingerbread cookies which she will distribute equally in tiny glass jars. If each jar is to contain six cookies each, how many cookies will not be placed in a jar? */ int gingerBreadTotal = 47; int cookiesPerJar = 6; double leftoverCookies = gingerBreadTotal / cookiesPerJar; /* 41. She also prepared 59 croissants which she plans to give to her 8 neighbors. If each neighbor received and equal number of croissants, how many will be left with Marian? */ int croissantsBaked = 59; int neighborsNearby = 8; double croissantsLeftover = croissantsBaked / neighborsNearby; /* 42. Marian also baked oatmeal cookies for her classmates. If she can place 12 cookies on a tray at a time, how many trays will she need to prepare 276 oatmeal cookies at a time? */ int cookiesPerTray = 12; int totalClassmates = 276; int numberOfTraysToBake = totalClassmates / cookiesPerTray; /* 43. Marian’s friends were coming over that afternoon so she made 480 bite-sized pretzels. If one serving is equal to 12 pretzels, how many servings of bite-sized pretzels was Marian able to prepare? */ int pretzelTotal = 480; int pretzelPerServing = 12; int totalServings = pretzelTotal / pretzelPerServing; /* 44. Lastly, she baked 53 lemon cupcakes for the children living in the city orphanage. If two lemon cupcakes were left at home, how many boxes with 3 lemon cupcakes each were given away? */ int lemonCupCakeTotal = 53; int cupcakesLeftAtHome = 2; int lemonCupCakesPerBox = 3; int newCupCakeTotal = 51; int cupCakesDistributed = newCupCakeTotal / lemonCupCakesPerBox; /* 45. Susie's mom prepared 74 carrot sticks for breakfast. If the carrots were served equally to 12 people, how many carrot sticks were left uneaten? */ int carrotsMade = 74; int peopleDining = 12; double carrotsRemaining = carrotsMade / peopleDining; /* 46. Susie and her sister gathered all 98 of their teddy bears and placed them on the shelves in their bedroom. If every shelf can carry a maximum of 7 teddy bears, how many shelves will be filled? */ int teddyBearTotal = 98; int bearsPerShelf = 7; int filledShelves = teddyBearTotal / bearsPerShelf; /* 47. Susie’s mother collected all family pictures and wanted to place all of them in an album. If an album can contain 20 pictures, how many albums will she need if there are 480 pictures? */ int allFamilyPhotos = 480; int photosPerBook = 20; int pictureBooksNeeded = allFamilyPhotos / photosPerBook; /* 48. Joe, Susie’s brother, collected all 94 trading cards scattered in his room and placed them in boxes. If a full box can hold a maximum of 8 cards, how many boxes were filled and how many cards are there in the unfilled box? */ int cardsCollected = 94; int boxCapacity = 8; int boxesFilled = cardsCollected / boxCapacity; double remainingCards = 1; /* 49. Susie’s father repaired the bookshelves in the reading room. If he has 210 books to be distributed equally on the 10 shelves he repaired, how many books will each shelf contain? */ int booksNeedingShelved= 210; int shelvesAvailable = 10; int booksPerShelf = booksNeedingShelved / shelvesAvailable; /* 50. Cristina baked 17 croissants. If she planned to serve this equally to her seven guests, how many will each have? */ int christinasCroissants = 17; int christinasGuests = 7; double croissantPerGuest = christinasCroissants / christinasGuests; /* CHALLENGE PROBLEMS */ /* Bill and Jill are house painters. Bill can paint a 12 x 14 room in 2.15 hours, while Jill averages 1.90 hours. How long will it take the two painter working together to paint 5 12 x 14 rooms? Hint: Calculate the hourly rate for each painter, combine them, and then divide the total walls in feet by the combined hourly rate of the painters. Challenge: How many days will it take the pair to paint 623 rooms assuming they work 8 hours a day?. */ /* Create and assign variables to hold your first name, last name, and middle initial. Using concatenation, build an additional variable to hold your full name in the order of last name, first name, middle initial. The last and first names should be separated by a comma followed by a space, and the middle initial must end with a period. Example: "Hopper, Grace B." */ /* The distance between New York and Chicago is 800 miles, and the train has already travelled 537 miles. What percentage of the trip has been completed? Hint: The percent completed is the miles already travelled divided by the total miles. Challenge: Display as an integer value between 0 and 100 using casts. */ } } }
9706ba2b7d659aeffd91a24c6607ef7c710822c2
C#
TRiV07/OrchardCore.Commerce
/src/Modules/OrchardCore.Commerce/Settings/ProductAttributeFieldSettings.cs
2.90625
3
using OrchardCore.Commerce.Abstractions; using System.Collections.Generic; namespace OrchardCore.Commerce.Settings; /// <summary> /// A base class for product attribute settings. /// </summary> public abstract class ProductAttributeFieldSettings { /// <summary> /// Gets or sets the description text to display for this attribute in the product page. /// </summary> public string Hint { get; set; } } /// <summary> /// A typed base class for product attribute settings. /// </summary> public abstract class ProductAttributeFieldSettings<T> : ProductAttributeFieldSettings { /// <summary> /// Gets or sets the default value associated with this attribute. /// </summary> public T DefaultValue { get; set; } } /// <summary> /// Settings for the Boolean product attribute. /// </summary> public class BooleanProductAttributeFieldSettings : ProductAttributeFieldSettings<bool> { /// <summary> /// Gets or sets the text associated to the checkbox for this attribute in the product page. /// </summary> public string Label { get; set; } } /// <summary> /// Settings for the numeric product attribute. /// </summary> public class NumericProductAttributeFieldSettings : ProductAttributeFieldSettings<decimal?> { /// <summary> /// Gets or sets a value indicating whether a value is required. /// </summary> public bool Required { get; set; } /// <summary> /// Gets or sets the hint to display when the input is empty. /// </summary> public string Placeholder { get; set; } /// <summary> /// Gets or sets the number of digits after the decimal point. /// </summary> public int DecimalPlaces { get; set; } /// <summary> /// Gets or sets the minimum value allowed. /// </summary> public decimal? Minimum { get; set; } /// <summary> /// Gets or sets the maximum value allowed. /// </summary> public decimal? Maximum { get; set; } } /// <summary> /// Settings for the text product attribute. /// </summary> public class TextProductAttributeFieldSettings : ProductAttributeFieldSettings<string>, IPredefinedValuesProductAttributeFieldSettings { /// <summary> /// Gets or sets a value indicating whether a value is required. /// </summary> public bool Required { get; set; } /// <summary> /// Gets or sets the hint to display when the input is empty. /// </summary> public string Placeholder { get; set; } /// <summary> /// Gets or sets the set of suggested or allowed values. /// </summary> public IEnumerable<object> PredefinedValues { get; set; } /// <summary> /// Gets or sets a value indicating whether values should be restricted to the set of predefined values. /// </summary> public bool RestrictToPredefinedValues { get; set; } /// <summary> /// Gets or sets a value indicating whether multiple values can be selected. /// </summary> public bool MultipleValues { get; set; } }
12dcc105d18aee073fcc6251bc145966badf0d31
C#
e-hill/track-my-games
/src/Repositories/GoalsRepository.cs
2.84375
3
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using AutoMapper; using Microsoft.EntityFrameworkCore; using TrackMyGames.DbContexts; using TrackMyGames.Entities; using TrackMyGames.Models; namespace TrackMyGames.Repositories { public class GoalsRepository : IGoalsRepository { private readonly ApplicationDbContext _dbContext; private readonly IMapper _mapper; public GoalsRepository(ApplicationDbContext dbContext, IMapper mapper) { _dbContext = dbContext; _mapper = mapper; } public async Task<IEnumerable<Goal>> ReplaceGoalsAsync(IEnumerable<Goal> goals, int gameId) { var newGoals = _mapper.Map<IEnumerable<GoalEntity>>(goals); newGoals = await LinkGoalsAsync(newGoals, gameId); var oldGoals = _dbContext.Goals.Where(x => x.GameId == gameId); using (var transaction = await _dbContext.Database.BeginTransactionAsync()) { _dbContext.Goals.RemoveRange(oldGoals); await _dbContext.Goals.AddRangeAsync(newGoals); await _dbContext.SaveChangesAsync(); await transaction.CommitAsync(); } return _mapper.Map<IEnumerable<Goal>>(newGoals); } private async Task<IEnumerable<GoalEntity>> LinkGoalsAsync(IEnumerable<GoalEntity> goals, int gameId) { var game = await _dbContext.Games.SingleOrDefaultAsync(x => x.Id == gameId); return goals.Select(x => { x.Game = game; return x; }); } } }
bd4a7ad3670e44b048255b67af34fc5b06f9d7bf
C#
spica29/Centar-za-udomljavanje-pasa
/Centar/Centar/UgovorDAO.cs
2.640625
3
using MySql.Data.MySqlClient; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Centar { public class UgovorDAO:IDaoCrud<Ugovor> { private MySqlConnection con; public UgovorDAO(string host, string db, string user, string pass) { string connectionString = "server=localhost;user=" + user + ";pwd=" + pass + ";database=" + db; con = new MySqlConnection(connectionString); try { con.Open(); } catch (Exception e) { throw e; } } public long create(Ugovor entity) { throw new NotImplementedException(); } public Ugovor read(Ugovor entity) { throw new NotImplementedException(); } public Ugovor update(Ugovor entity) { throw new NotImplementedException(); } public void delete(Ugovor entity) { throw new NotImplementedException(); } public Ugovor getById(int id) { throw new NotImplementedException(); } public List<Ugovor> getAll() { throw new NotImplementedException(); } public List<Ugovor> getByExample(string name, string value) { throw new NotImplementedException(); } } }
a9834a575d72f4d497f631f96cab022c5e8f724e
C#
Garados007/MaxLib
/MaxLib.Sqlite/DB/Database.cs
2.796875
3
using System; using System.Data.SQLite; using System.Diagnostics; using System.Threading; namespace MaxLib.DB { public class Database : IDisposable { public class TransactionDisposer : IDisposable { readonly Database db; public TransactionDisposer(Database db) { this.db = db ?? throw new ArgumentNullException("db"); db.BeginTransaction(); } public void Dispose() { db.StopTransaction(); } } readonly SQLiteFactory factory; public SQLiteConnection Connection { get; private set; } readonly object lockObject = new object(); public Database(string file, string checkSql, string createSql) { if (file == null) throw new ArgumentNullException("file"); if (checkSql == null) throw new ArgumentNullException("checkSql"); if (createSql == null) throw new ArgumentNullException("createSql"); var dir = new System.IO.FileInfo(file).Directory; if (!dir.Exists) dir.Create(); factory = new SQLiteFactory(); Connection = (SQLiteConnection)factory.CreateConnection(); Connection.ConnectionString = "Data Source=" + file; Connection.Open(); if (!CheckValidity(checkSql)) CreateTables(createSql); } bool CheckValidity(string checkSql) { using (var query = Create(checkSql)) using (var reader = query.ExecuteReader()) { if (!reader.Read()) return false; return reader.GetInt32(0) == 0; } } void CreateTables(string createSql) { int result; using (var query = Create(createSql)) result = query.ExecuteNonQuery(); Debug.Print($"result: {result}"); } public Query Create(string sql) { if (disposedValue) throw new ObjectDisposedException(null); if (sql == null) throw new ArgumentNullException("sql"); return new Query(this, sql); } public void Execute(Action method, bool doCommit = true) { if (disposedValue) throw new ObjectDisposedException(null); if (method == null) throw new ArgumentNullException("method"); bool NeedWait = false; lock (lockObject) { if (BigTransaction != null && !TransactionThread.Equals(Thread.CurrentThread)) NeedWait = true; } if (NeedWait) { Mutex.WaitOne(); } lock (lockObject) { if (NeedWait) Mutex.ReleaseMutex(); if (BigTransaction == null) using (var transaction = Connection.BeginTransaction()) { method(); if (doCommit && BigTransaction != null) transaction.Commit(); } else method(); } } static readonly Mutex Mutex = new Mutex(false); static SQLiteTransaction BigTransaction = null; static Thread TransactionThread; static int lockDepth = 0; public void BeginTransaction() { if (disposedValue) throw new ObjectDisposedException(null); Mutex.WaitOne(); lock (lockObject) { if (BigTransaction != null && TransactionThread != Thread.CurrentThread) throw new InvalidOperationException("transaction is running"); if (lockDepth++ > 0) return; BigTransaction = Connection.BeginTransaction(); TransactionThread = Thread.CurrentThread; } } public void StopTransaction() { if (disposedValue) throw new ObjectDisposedException(null); lock (lockObject) { if (BigTransaction == null || TransactionThread != Thread.CurrentThread) return; if (--lockDepth > 0) return; BigTransaction.Commit(); BigTransaction = null; TransactionThread = null; } Mutex.ReleaseMutex(); } public TransactionDisposer Transaction() { return new TransactionDisposer(this); } #region IDisposable Support private bool disposedValue = false; // Dient zur Erkennung redundanter Aufrufe. protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { // TODO: verwalteten Zustand (verwaltete Objekte) entsorgen. } // TODO: nicht verwaltete Ressourcen (nicht verwaltete Objekte) freigeben und Finalizer weiter unten überschreiben. // TODO: große Felder auf Null setzen. factory.Dispose(); Connection.Dispose(); disposedValue = true; } } // TODO: Finalizer nur überschreiben, wenn Dispose(bool disposing) weiter oben Code für die Freigabe nicht verwalteter Ressourcen enthält. // ~Database() { // // Ändern Sie diesen Code nicht. Fügen Sie Bereinigungscode in Dispose(bool disposing) weiter oben ein. // Dispose(false); // } // Dieser Code wird hinzugefügt, um das Dispose-Muster richtig zu implementieren. public void Dispose() { // Ändern Sie diesen Code nicht. Fügen Sie Bereinigungscode in Dispose(bool disposing) weiter oben ein. Dispose(true); // TODO: Auskommentierung der folgenden Zeile aufheben, wenn der Finalizer weiter oben überschrieben wird. // GC.SuppressFinalize(this); } #endregion } }
8782acfb6cfb1ea0ef38909fcef17ca2d87ae991
C#
dochinhthtn/crazy-fitness-app
/Assets/Scripts/Components/ProfileForm.cs
2.65625
3
using Models; using UnityEngine; using UnityEngine.UI; using System; namespace Components { public class ProfileForm : BaseComponent<Models.Profile> { [SerializeField] private InputField nameInput; [SerializeField] private Toggle maleOption; [SerializeField] private Toggle femaleOption; [SerializeField] private InputField ageInput; [SerializeField] private InputField weightInput; [SerializeField] private InputField heightInput; void Start () { Profile profile = (App.instance.profile != null) ? App.instance.profile : new Profile (); SetData (profile); AttachInputsListener (); } public override void Render () { nameInput.text = data.name; if (data.sex == "male") { maleOption.isOn = true; } else if (data.sex == "female") { femaleOption.isOn = true; } ageInput.text = data.age.ToString (); weightInput.text = data.weight.ToString (); heightInput.text = data.height.ToString (); } void AttachInputsListener () { try { nameInput.onValueChanged.AddListener ((value) => { data.name = value; }); maleOption.onValueChanged.AddListener ((value) => { if (maleOption.isOn) data.sex = "male"; }); femaleOption.onValueChanged.AddListener ((value) => { if (femaleOption.isOn) data.sex = "female"; }); ageInput.onValueChanged.AddListener ((value) => { Int32.TryParse(value, out data.age); }); weightInput.onValueChanged.AddListener ((value) => { float.TryParse(value, out data.weight); }); heightInput.onValueChanged.AddListener ((value) => { float.TryParse(value, out data.height); }); } catch (System.Exception e) { Debug.Log (e.Message); } } public void SaveProfile() { Profile.Save(data); } } }
5fea2d167eb2765d21931c81e560bcd1012cb5b5
C#
zhuhuijun/20201228testcrud
/Asp.NetCore/SoEasyPlatform/src/LayuiCmdCore.Utils/StringExtensions.cs
3.234375
3
using System; using System.Collections.Generic; using System.Text; namespace LayuiCmsCore.Utils { /// <summary> /// String 操作扩展类 /// </summary> public static class StringExtensions { /// <summary> /// Null Empty 判断 /// </summary> /// <param name="str">源字符串</param> /// <returns>Null/Empty时返回真</returns> public static bool IsNullOrEmpty(this string str) => string.IsNullOrEmpty(str); /// <summary> /// SpanSplit 扩展方法 /// </summary> /// <param name="source">源数组</param> /// <param name="splitStr">分隔符数组 分割规则作为整体</param> /// <param name="stringSplitOptions">StringSplitOptions 选项</param> /// <returns>分割后的字符串数组</returns> public static List<string> SpanSplit(this string source, string splitStr = null, StringSplitOptions stringSplitOptions = StringSplitOptions.None) { var ret = new List<string>(); if (source.IsNullOrEmpty()) return ret; if (splitStr.IsNullOrEmpty()) splitStr = Environment.NewLine; var sourceSpan = source.AsSpan(); var splitSpan = splitStr.AsSpan(); do { var n = sourceSpan.IndexOf(splitSpan); if (n == -1) n = sourceSpan.Length; ret.Add(stringSplitOptions == StringSplitOptions.None ? sourceSpan.Slice(0, n).ToString() : sourceSpan.Slice(0, n).Trim().ToString()); sourceSpan = sourceSpan.Slice(Math.Min(sourceSpan.Length, n + splitSpan.Length)); } while (sourceSpan.Length > 0); return ret; } /// <summary> /// SpanSplit 扩展方法 /// </summary> /// <param name="source">源数组</param> /// <param name="splitStr">分隔符数组 分割规则是任意一个</param> /// <param name="stringSplitOptions">StringSplitOptions 选项</param> /// <returns>分割后的字符串数组</returns> public static List<string> SpanSplitAny(this string source, string splitStr, StringSplitOptions stringSplitOptions = StringSplitOptions.None) { var ret = new List<string>(); if (source.IsNullOrEmpty()) return ret; if (splitStr.IsNullOrEmpty()) { ret.Add(source); return ret; } var sourceSpan = source.AsSpan(); var splitSpan = splitStr.AsSpan(); do { var n = sourceSpan.IndexOfAny(splitSpan); if (n == -1) n = sourceSpan.Length; if (n > 0) ret.Add(stringSplitOptions == StringSplitOptions.None ? sourceSpan.Slice(0, n).ToString() : sourceSpan.Slice(0, n).Trim().ToString()); sourceSpan = sourceSpan.Slice(Math.Min(sourceSpan.Length, n + 1)); } while (sourceSpan.Length > 0); return ret; } } }
15ba5a305d02a3931c5cd6f3a63d87175468290b
C#
ErhanKurnaz/UrenTijd
/UrenTijd/MainWindow.xaml.cs
2.71875
3
using System.Windows; using System.Globalization; using UrenTijd.ui; using System.ComponentModel; using System.Threading; using System; using System.IO; namespace UrenTijd { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window, INotifyPropertyChanged { private int _workWeek; private int _workYear; private bool _loading = false; private bool _showingError = false; public event PropertyChangedEventHandler PropertyChanged; public struct TimeWindow { public System.DateTime? from; public System.DateTime? until; } public struct DayFieldsStruct { public TimeWindow arriving; public TimeWindow leaving; public TimeWindow working; public string workDescription; public string workType; public bool hadBreak; } public int WorkWeek { get { return _workWeek; } set { if (value != _workWeek) { _workWeek = value; UpdateWeek(); OnPropertyChanged("WorkWeek"); } } } public int WorkYear { get { return _workYear; } set { if (value != _workYear) { _workYear = value; UpdateWeek(); OnPropertyChanged("WorkYear"); } } } public bool Loading { get { return _loading; } set { if (value != _loading) { _loading = value; OnPropertyChanged("Loading"); } } } public bool ShowingError { get { return _showingError; } set { if (value != _showingError) { _showingError = value; OnPropertyChanged("ShowingError"); } } } public MainWindow() { InitializeComponent(); this.DataContext = this; System.DateTime now = System.DateTime.Now; var cal = CultureInfo.CurrentCulture.Calendar; WorkWeek = cal.GetWeekOfYear(now, CalendarWeekRule.FirstDay, System.DayOfWeek.Monday); WorkYear = cal.GetYear(now); } private void SendMail(DayFieldsStruct[] days) { try { Utils.CreateExcel(days, Utils.FirstDateOfWeekISO8601(_workYear, _workWeek)); } catch (InvalidOperationException) { ShowingError = true; } Utils.SendMail(); } private DayFieldsStruct ConvertToDayFields(DayFields dayFields) { DayFieldsStruct dayFieldsStruct = new DayFieldsStruct(); dayFieldsStruct.arriving.from = dayFields.GoFrom.SelectedTime; dayFieldsStruct.arriving.until = dayFields.GoUntil.SelectedTime; dayFieldsStruct.leaving.from = dayFields.BackFrom.SelectedTime; dayFieldsStruct.leaving.until = dayFields.BackUntil.SelectedTime; dayFieldsStruct.working.from = dayFields.WorkFrom.SelectedTime; dayFieldsStruct.working.until = dayFields.WorkUntil.SelectedTime; dayFieldsStruct.hadBreak = dayFields.hadBreak.IsChecked ?? false; dayFieldsStruct.workDescription = dayFields.WorkDescription.Text; dayFieldsStruct.workType = dayFields.WorkType.Text; return dayFieldsStruct; } private void UpdateWeek() { if (_workYear != 0 && _workWeek != 0) { System.DateTime beginOfWeek = Utils.FirstDateOfWeekISO8601(_workYear, _workWeek); System.DateTime endOfWeek = beginOfWeek.AddDays(6); string text = string.Format("Van {0} tot {1}", beginOfWeek.ToString("dd MMM"), endOfWeek.ToString("dd MMM")); workWeekBlock.Text = text; } } private void Send(object sender, RoutedEventArgs e) { DayFieldsStruct[] days = new DayFieldsStruct[7]; days[0] = ConvertToDayFields(Monday); days[1] = ConvertToDayFields(Tuesday); days[2] = ConvertToDayFields(Wednesday); days[3] = ConvertToDayFields(Thursday); days[4] = ConvertToDayFields(Friday); days[5] = ConvertToDayFields(Saturday); days[6] = ConvertToDayFields(Sunday); Thread thread = new Thread(() => { this.Loading = true; this.SendMail(days); this.Loading = false; }); thread.Start(); } private void CloseDialog(object sender, RoutedEventArgs e) { ShowingError = false; } private void WindowClosed(object sender, EventArgs e) { if (Directory.Exists(Environment.GetEnvironmentVariable("Temp") + @"\UrenTijd")) { Directory.Delete(Environment.GetEnvironmentVariable("Temp") + @"\UrenTijd", true); } } protected void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } }
2d01c0e4d04868a351f6872aa879f3d1e8efed05
C#
chris-nissen/authorization
/src/GraphQL.Authorization/Requirements/ClaimAuthorizationRequirement.cs
3
3
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace GraphQL.Authorization { /// <summary> /// Implements an <see cref="IAuthorizationRequirement"/> which requires an instance of the specified /// claim type, and, if allowed values are specified, the claim value must be any of the allowed values. /// </summary> public class ClaimAuthorizationRequirement : IAuthorizationRequirement { private readonly string _claimType; private readonly IEnumerable<string> _displayValues; private readonly IEnumerable<string> _allowedValues; /// <summary> /// Creates a new instance of <see cref="ClaimAuthorizationRequirement"/> with /// the specified claim type. /// </summary> public ClaimAuthorizationRequirement(string claimType) : this(claimType, (IEnumerable<string>)null, null) { } /// <summary> /// Creates a new instance of <see cref="ClaimAuthorizationRequirement"/> with /// the specified claim type and optional list of claim values, which, if present, /// the claim must match. /// </summary> public ClaimAuthorizationRequirement(string claimType, IEnumerable<string> allowedValues) : this(claimType, allowedValues, null) { } /// <summary> /// Creates a new instance of <see cref="ClaimAuthorizationRequirement"/> with /// the specified claim type and optional list of claim values, which, if present, /// the claim must match. /// </summary> public ClaimAuthorizationRequirement(string claimType, params string[] allowedValues) : this(claimType, allowedValues, null) { } /// <summary> /// Creates a new instance of <see cref="ClaimAuthorizationRequirement"/> with /// the specified claim type and optional list of claim values, which, if present, /// the claim must match. Additional <paramref name="displayValues"/> argument /// specifies the set of displayed claim values that will be used to generate an /// error message if the requirement is not met. /// </summary> public ClaimAuthorizationRequirement(string claimType, IEnumerable<string> allowedValues, IEnumerable<string> displayValues) { _claimType = claimType ?? throw new ArgumentNullException(nameof(claimType)); _allowedValues = allowedValues ?? Enumerable.Empty<string>(); _displayValues = displayValues; } /// <inheritdoc /> public Task Authorize(AuthorizationContext context) { bool found = false; if (context.User != null) { if (_allowedValues == null || !_allowedValues.Any()) { found = context.User.Claims.Any( claim => string.Equals(claim.Type, _claimType, StringComparison.OrdinalIgnoreCase)); } else { found = context.User.Claims.Any( claim => string.Equals(claim.Type, _claimType, StringComparison.OrdinalIgnoreCase) && _allowedValues.Contains(claim.Value, StringComparer.Ordinal)); } } if (!found) { if (_allowedValues != null && _allowedValues.Any()) { string values = string.Join(", ", _displayValues ?? _allowedValues); context.ReportError($"Required claim '{_claimType}' with any value of '{values}' is not present."); } else { context.ReportError($"Required claim '{_claimType}' is not present."); } } return Task.CompletedTask; } } }
b26f6a840adec05147c2b89c354dfb125c9dee4c
C#
LogicAndTrick/sledge
/Sledge.FileSystem/VirtualFile.cs
2.78125
3
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; namespace Sledge.FileSystem { public class VirtualFile : IFile { public FileSystemType Type { get { return FileSystemType.Virtual; } } public bool IsContainer { get; private set; } public IFile Parent { get; private set; } public string FullPathName { get; private set; } public string Name { get; private set; } public string NameWithoutExtension { get; private set; } public string Extension { get; private set; } public bool Exists { get; private set; } public long Size { get; private set; } public int NumChildren { get { return Children.Count(x => x.IsContainer); } } public int NumFiles { get { return Children.Count(x => !x.IsContainer); } } public List<IFile> Children { get; private set; } public VirtualFile(IFile parent, string name) { Parent = parent; Name = name; IsContainer = false; FullPathName = parent != null ? Path.Combine(parent.FullPathName, name) : name; NameWithoutExtension = Path.GetFileNameWithoutExtension(name); Extension = (Path.GetExtension(Name) ?? "").TrimStart('.'); Exists = true; Size = 0; Children = new List<IFile>(); } public VirtualFile(IFile parent, string name, IEnumerable<IFile> children) { Parent = parent; Name = name; IsContainer = true; FullPathName = parent == null ? name : Path.Combine(parent.FullPathName, name); NameWithoutExtension = name; Extension = ""; Exists = true; Size = 0; Children = children.ToList(); } public Stream Open() { throw new NotImplementedException(); } public byte[] ReadAll() { throw new NotImplementedException(); } public byte[] Read(long offset, long count) { throw new NotImplementedException(); } public IEnumerable<IFile> GetRelatedFiles() { return new List<IFile>(); } public IFile GetRelatedFile(string extension) { return null; } public IFile GetChild(string name) { return Children.FirstOrDefault(x => x.Name == name); } public IEnumerable<IFile> GetChildren() { return Children.Where(x => x.IsContainer); } public IEnumerable<IFile> GetChildren(string regex) { return GetChildren().Where(x => Regex.IsMatch(x.Name, regex, RegexOptions.IgnoreCase)); } public IFile GetFile(string name) { return GetFiles().FirstOrDefault(x => x.Name.ToLower() == name.ToLower()); } public IEnumerable<IFile> GetFiles() { return Children.Where(x => !x.IsContainer); } public IEnumerable<IFile> GetFiles(string regex) { return GetFiles().Where(x => Regex.IsMatch(x.Name, regex, RegexOptions.IgnoreCase)); } public IEnumerable<IFile> GetFilesWithExtension(string extension) { return GetFiles().Where(x => x.Name.EndsWith("." + extension)); } } }
99b48a6bc90728c731825abd36d5e578b6947323
C#
zmaimy22/Plugins
/TechTreeTool/BlueprintController.cs
2.671875
3
using UnityEngine; using System.Collections; using System.Collections.Generic; using System.Linq; using System; using TechTree.Model; namespace TechTree { /// <summary> /// The BlueprintController wraps the Blueprint class. This is so you can have multiple instances of /// a blueprint (eg multiple soldiers, turrets) and also share the one blueprint model among multiple /// players in a single game. This class is used to build units from blueprints. /// /// There is one controller per blueprint, and it contains information that is shared between all the /// units it builds. /// </summary> public class BlueprintController { #region API /// <summary> /// All units built by this controller. /// </summary> public List<TechTreeUnit> units = new List<TechTreeUnit>(); /// <summary> /// The blueprint being used by this class to create units. /// </summary> public Blueprint blueprint; /// <summary> /// How many units have been built from this bp. /// </summary> public int buildCount = 0; /// <summary> /// Gets a value indicating whether this blueprint has been built during the game session. The first time /// a unit is built with this controller, the value will become true. If enough Demolish calls are /// made, this flag can become false. /// </summary> /// <value><c>true</c> if this instance has been built; otherwise, <c>false</c>.</value> public bool HasBeenBuilt { get { return buildCount > 0; } } /// <summary> /// Indicates whether this controller is able to be built, by checking that all prerequistes are met. /// Does not check if enough resources are available. /// </summary> /// <value><c>true</c> if this instance can be built; otherwise, <c>false</c>.</value> public bool CanBeBuilt { get { if(Excluded) return false; if ((IsBuilding || HasBeenBuilt) && !blueprint.allowMultiple) return false; foreach (var b in blueprint.prerequisites) { if (!controller.blueprints [b.blueprint.ID].HasBeenBuilt) { return false; } } return true; } } /// <summary> /// Gets a value indicating whether this instance is building. /// </summary> /// <value><c>true</c> if this instance is building; otherwise, <c>false</c>.</value> public bool IsBuilding { get; set; } /// <summary> /// Gets a value indicating whether this <see cref="TechTree.BlueprintController"/> is excluded. A blueprint is excluded when it depends on a Mutex blueprint, and was not chosen to be built. /// </summary> /// <value><c>true</c> if excluded; otherwise, <c>false</c>.</value> public bool Excluded { get; private set; } /// <summary> /// If this blueprint is for a factory, returns all possible blueprint controllers that this factory can /// build. If this blueprint is not for a factory, an exception is raised. /// </summary> public IEnumerable<BlueprintController> GetFactoryBlueprints () { if (!blueprint.isFactory) throw new Exception ("This is not a Factory: " + this.blueprint.ID); foreach (var b in blueprint.factory.blueprints) { yield return controller.blueprints [b.ID]; } } /// <summary> /// Using a blueprint specified by ID, returns a build request. The build request will contain the /// gameobject and sprite specified in the model. /// </summary> /// <returns>The build request.</returns> public BlueprintBuildRequest CreateBuildRequest (TechTreeUnit factoryUnit, string ID) { if (!HasBeenBuilt) { return new BlueprintBuildRequest () { status = BuildStatus.FactoryNotBuilt }; } var bpc = GetValidBPC (ID); if(factoryUnit.Level < bpc.blueprint.requiredFactoryLevel) { return new BlueprintBuildRequest () { status=BuildStatus.FactoryNotHighEnoughLevel }; } foreach (var p in bpc.blueprint.prerequisites) { var pc = controller.blueprints [p.blueprint.ID]; if (!pc.HasBeenBuilt) { return new BlueprintBuildRequest () { status=BuildStatus.MissingPrerequisite, prerequisite=p }; } var requiredLevel = p.level; if(requiredLevel > 0) { var maxLevel = (from i in pc.units select i.Level).Max(); if(maxLevel < requiredLevel) { return new BlueprintBuildRequest () { status=BuildStatus.PrerequisiteNotHighEnoughLevel, prerequisite=p }; } } } var req = new BlueprintBuildRequest () { blueprint = bpc.blueprint, percentComplete=0 }; if(blueprint.constructTime <= 0) blueprint.constructTime = 0.01f; return req; } #endregion #region implementation BlueprintController GetValidBPC (string ID) { if (!blueprint.isFactory) throw new Exception ("This is not a Factory: " + this.blueprint.ID); BlueprintController bpc = null; foreach (var b in blueprint.factory.blueprints) { if (b.ID == ID) bpc = controller.blueprints [ID]; } if (bpc == null) { throw new Exception ("Blueprint not available in this Factory: " + ID); } return bpc; } public BlueprintController (BlueprintModelController controller, Blueprint blueprint) { this.controller = controller; this.blueprint = blueprint; } public void OnDependentHasBeenBuilt (BlueprintController bpc) { if(blueprint.mutex) { var children = (from i in controller.model.GetDependentBlueprints(blueprint) where i.ID != bpc.blueprint.ID select i); foreach(var c in children) { controller.blueprints[c.ID].Excluded = true; } } } BlueprintModelController controller; #endregion } }
4d8b88a70d6aa790e7f527ce2b11a8e19b683b69
C#
pieringro/MyTrelloClone-Server
/MyTrelloClone.DataAccess/Data/BoardData/Commands/CreateTaskLiskCommand.cs
2.5625
3
using MediatR; using MyTrelloClone.DataAccess.Data.Repository.IRepository; using MyTrelloClone.Models; using System; using System.Collections.Generic; using System.Text; using System.Threading; using System.Threading.Tasks; namespace MyTrelloClone.DataAccess.Data.BoardData.Commands { public class CreateTaskLiskCommand : IRequest<int> { public string Name { get; set; } public string Description { get; set; } public int BoardId { get; set; } public class CreateTaskLiskCommandHandler : IRequestHandler<CreateTaskLiskCommand, int> { private readonly IUnitOfWork _unitOfWork; public CreateTaskLiskCommandHandler(IUnitOfWork unitOfWork) { _unitOfWork = unitOfWork; } public async Task<int> Handle(CreateTaskLiskCommand command, CancellationToken cancellationToken) { var taskList = new TaskList() { Name = command.Name, Description = command.Description, BoardId = command.BoardId, }; _unitOfWork.TaskList.Add(taskList); await _unitOfWork.SaveAsync(); return taskList.Id; } } } }
1a8e6808a1e746febc7e9bb64b7a7224b7ba4ec5
C#
TanushaVeraksa/test
/xUnit/InequalityTriangles/Triangle.cs
3.140625
3
using System; namespace InequalityTriangles { public class Triangle { public static bool TheExistenceOfTriangle(double X, double Y, double Z) { return (X > 0 && Y > 0 && Z > 0 && X <= Y + Z && Y <= X + Z && Z <= X + Y); } } }
6ecacdae4f714f2840cf3fe999641584082ba741
C#
adehikmatfr/c-sharp-simple-desktop-project
/AppFirst/AppFirst/model/Koneksi.cs
2.609375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; //panggil modul driver mysql using MySql.Data; using MySql.Data.MySqlClient; namespace AppFirst.model { class Koneksi { //buat method open db untuk membuka database public MySqlConnection getKoneksi() { String host, user, password, db,con; host = "localhost"; user = "root"; password = ""; db = "sepatu"; con="server="+host+";user="+user+";password="+password+";database="+db+";"; Console.WriteLine(con); //syntax MySqlConnection conn = new MySqlConnection(con); return conn; } } }
f9a8f4084cc37b65ba50bcceb4f64472da2dffa3
C#
christophwille/viennarealtime
/Source/MundlTransit.WP8.Data/Reference/ReferenceDataContext.Import.cs
2.625
3
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using SQLite; namespace MundlTransit.WP8.Data.Reference { public partial class ReferenceDataContext { public async Task InitializeDatabaseAsync() { await _connection .CreateTablesAsync<Haltestelle,OgdLinie,OgdSteig,OgdHaltestelle>() .ConfigureAwait(false); } public async Task InsertAsync(IEnumerable objects) { await _connection.InsertAllAsync(objects).ConfigureAwait(false); } private static string LinienAtHaltestelleQuery = @"SELECT OgdLinien.Id, OgdLinien.Bezeichnung, OgdSteige.RblNummer FROM OgdLinien INNER JOIN OgdSteige ON OgdLinien.Id = OgdSteige.FK_LinienId WHERE OgdSteige.FK_HaltestellenId = {0} ORDER BY OgdLinien.Reihenfolge"; // GROUP BY OgdLinien.Id, OgdLinien.Bezeichnung public async Task<int> CreateLookupTableAsync() { var haltestellen = await _connection.Table<OgdHaltestelle>() .ToListAsync() .ConfigureAwait(false); var toInsert = new List<Haltestelle>(); foreach (var h in haltestellen) { var result = await _connection .QueryAsync<LinienAtHaltestelleModel>(String.Format(LinienAtHaltestelleQuery, h.Id)) .ConfigureAwait(false); var groupedLinien = (from model in result group model by new { model.Id, model.Bezeichnung } into g select new { g.Key.Id, g.Key.Bezeichnung }).ToList(); string linienDisplay = String.Join(", ", groupedLinien.Select(r => r.Bezeichnung)); string linienIds = String.Join(",", groupedLinien.Select(r => r.Id)); // Take only records where RblNummer exists string rblNummern = String.Join(",", result .Where(r => !String.IsNullOrWhiteSpace(r.RblNummer)) .Select(r => r.RblNummer)); // eg.Abdsdorf-Hippersdorf S Bahn has no Steige if (!String.IsNullOrWhiteSpace(rblNummern)) { var haltstelle = new Haltestelle() { Id = h.Id, Diva = h.Diva, Bezeichnung = h.Bezeichnung, Longitude = h.Longitude, Latitude = h.Latitude, Linien = linienDisplay, LinienIds = linienIds, RblNummern = rblNummern }; toInsert.Add(haltstelle); } else { Debug.WriteLine(h.Bezeichnung + " was omitted because of missing Steige"); } } return await _connection.InsertAllAsync(toInsert).ConfigureAwait(false); } } }
d903e2e2557140ad3c81f8493cccbf750d2f64bb
C#
ossentoo/xamarin-amccorma
/MaskValidation - BETA/MaskedEdit/Library/SelectionPoint.cs
2.578125
3
using System; namespace Masked.Library { public class SelectionPoint { public SelectionPoint(Int32 start, Int32 end) { this.Start = start; this.End = end; } public SelectionPoint(Int32 start) { this.Start = start; this.End = -1; } /// <summary> /// used by renderer /// </summary> /// <value>The start.</value> public Int32 Start { get; set; } /// <summary> /// used by renderer. /// </summary> /// <value>The end.</value> public Int32 End { get; set; } /// <summary> /// used by renderer. /// </summary> /// <value>The text.</value> public string Text { get; set; } } }
34df7c664369b97a2ca8c39983281008407ecba2
C#
patrickmartins/Bazaar
/src/PM.Bazaar.Services.WebApi/Extensions/ImageUtilExtension.cs
3.046875
3
using System; using System.Drawing; using System.Drawing.Imaging; using System.IO; namespace PM.Bazaar.Services.WebApi.Extensions { public static class ImageUtilExtensions { public static Image Resize(this Image image, int maxWidth, int maxHeight) { var ratioX = (double)maxWidth/image.Width; var ratioY = (double)maxHeight/image.Height; var ratio = Math.Min(ratioX, ratioY); var newWidth = (int)(image.Width * ratio); var newHeight = (int)(image.Height * ratio); var newImage = new Bitmap(newWidth, newHeight); using (var graphics = Graphics.FromImage(newImage)) { graphics.DrawImage(image, 0, 0, newWidth, newHeight); } return newImage; } public static Image Resize(this Image image, int maxHeight) { var ratioY = (double)maxHeight / image.Height; var newWidth = (int)(image.Width * ratioY); var newHeight = (int)(image.Height * ratioY); var newImage = new Bitmap(newWidth, newHeight); using (var graphics = Graphics.FromImage(newImage)) { graphics.DrawImage(image, 0, 0, newWidth, newHeight); } return newImage; } public static byte[] ToArray(this Image image) { var ms = new MemoryStream(); image.Save(ms, ImageFormat.Jpeg); return ms.ToArray(); } public static Image ToImage(this byte[] buffer) { return Image.FromStream(new MemoryStream(buffer)); } } }
17996bbe5c88c602f8165c13bd7a878c2c12369b
C#
peytonas/keepr-ta
/Services/VaultKeepsService.cs
2.796875
3
using System; using System.Collections.Generic; using Keepr.Models; using Keepr.Repositories; namespace Keepr.Services { public class VaultKeepsService { private readonly VaultKeepsRepository _repo; public VaultKeepsService(VaultKeepsRepository repo) { _repo = repo; } public VaultKeep Create(VaultKeep newVaultKeep, string userId) { newVaultKeep.UserId = userId; int id = _repo.Create(newVaultKeep); newVaultKeep.Id = id; return newVaultKeep; } public IEnumerable<Keep> Get(int vaultId, string userId) { return _repo.Get(vaultId, userId); } public string Delete(VaultKeep vaultKeep) { VaultKeep exists = _repo.GetId(vaultKeep.VaultId, vaultKeep.KeepId); if (exists == null) { throw new Exception("nothing here broh"); } _repo.Delete(exists.Id); return "it's gone broh"; } } }
3c6c578eccf577bbc5df98a6eff2552fe57d0f42
C#
mybirthname/VisitorSimple
/DesignPatterns/Program.cs
2.6875
3
using DesignPatterns.VisitorPattern; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DesignPatterns { class Program { public static void Main(string[] args) { TestSimpleVisitor(); } public static void TestSimpleVisitor() { var director = new Director("Gosho", 3500, 19); var increaseSallary = new IncreaseIncomeVisitor(); director.Accept(increaseSallary); } } }
72c376182777905a1ecb59bb7f6072c1768abaaf
C#
MaximillianMS/AllaxScript
/Loggers/UltraLogger.cs
2.984375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Allax.Logger { public class UltraLogger { static int MAX_NOTES = 100000; static bool TurnedOn = false; const string PredefinedPath = "C:\\Windows\\Temp\\"; System.Collections.Concurrent.ConcurrentBag<Note> Notes = new System.Collections.Concurrent.ConcurrentBag<Note>(); private static volatile UltraLogger instance; private UltraLogger() { } private static readonly object syncRoot = new object(); public static UltraLogger Instance { get { if (instance == null) { lock (syncRoot) { if (instance == null) { instance = new UltraLogger(); } } } return instance; } } public void AddToLog(String Msg, Logger.MsgType Type = MsgType.Action, int MsgLevel = 0) { if (!TurnedOn) return; var N = new Note(); N.Thread = System.Threading.Thread.CurrentThread.ManagedThreadId; N.Time = DateTime.Now; N.Type = Type; N.Msg = Msg; N.MsgLevel = 0; Notes.Add(N); if (Notes.Count > MAX_NOTES) { //AddToLog("Logger: MAX_NOTES Reached", MsgType.Warning); //lock(syncRoot) //{ ExportToFile(); //} return; //throw new Exception("Logger: Over 100000 notes in Logger"); } } public void ExportToFile(string Path = PredefinedPath) { AddToLog("Logger: Exporting Notes from UltraLogger started."); if (!System.IO.Directory.Exists(Path)) { AddToLog("Logger: No such directory exists: \"" + Path+"\""); return; } Path+= "Allax_"+DateTime.Now.ToShortDateString()+".log"; AddToLog("Logger: File: "+Path); if(Notes.Count!=0) using (var aFile = new System.IO.FileStream(Path, System.IO.FileMode.Append, System.IO.FileAccess.Write)) using (var sw = new System.IO.StreamWriter(aFile)) { lock (syncRoot) { var Notes = GetNotes(); string Buffer = ""; for (int i = 0; i < Notes.Count; i++) { if (i % (MAX_NOTES / 100) != 0) { Buffer += Notes[i] + "\n"; } else { sw.WriteLine(Buffer); Buffer = ""; } } if (Buffer != "") { sw.WriteLine(Buffer); Buffer = ""; } this.Notes = new System.Collections.Concurrent.ConcurrentBag<Note>(); } } // AddToLog("Logger: File creation failed through exporting UltraLogger notes."); } public List<Note> GetNotes(bool SortByTime = false) { AddToLog("Logger: Getting Notes from UltraLogger started."); List<Note> ret = new List<Note>(228); if (!SortByTime) { ret = new List<Note>(Notes.Count); lock (syncRoot) { foreach (var N in Notes) { ret.Add(N); } } } else { throw new NotImplementedException(); } return ret; } } }
57971acc98604ddda3fc9a00a05f70a8399ee0da
C#
stefanv877/CSharpOOP_SoftUni
/DefiningClasses/RawData/Car.cs
2.703125
3
using System; using System.Collections.Generic; using System.Text; class Car { string model; Engine engine; Cargo cargo; Tire tires; public string Model { get { return model; } } public Engine Engine { get { return engine; } } public Cargo Cargo { get { return cargo; } } public Tire Tires { get { return tires; } } public Car(string model, Engine engine, Cargo cargo, Tire tires) { this.model = model; this.engine = engine; this.cargo = cargo; this.tires = tires; } }
269047f95c2d8c310175bbd4fe2da1473a5cda80
C#
BagirovPavel/TestForWork
/ProjectLife/LoadWindow.xaml.cs
2.53125
3
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace ProjectLife { /// <summary> /// Interaction logic for LoadWindow.xaml /// </summary> public partial class LoadWindow : Window { DBConnect con; bool isLoaded = false; public LoadWindow(DBConnect con) { InitializeComponent(); this.con = con; } private DataTable GetSavedGames() { using (SqlDataReader reader = con.LoadGame()) { DataTable dt = new DataTable(); dt.Columns.Add("id"); dt.Columns.Add("guid"); dt.Columns.Add("generation"); dt.Columns.Add("sequence"); while (reader.Read()) { dt.Rows.Add((int)reader["id"], (Guid)reader["guid"], (int)reader["generation"], (string)reader["sequence"]); } return dt; } } private void cancel_button_Click(object sender, RoutedEventArgs e) { Globals.isChosen = false; Close(); } private void Window_Loaded(object sender, RoutedEventArgs e) { loading_data.ItemsSource = GetSavedGames().DefaultView; if (Globals.isConSuccess) isLoaded = true; } private void load_button_Click(object sender, RoutedEventArgs e) { if (!isLoaded || loading_data.SelectedIndex < 0) return; try { DataRowView drv = (DataRowView)loading_data.SelectedItem; Globals.guid = Guid.Parse((string)drv.Row["guid"]); Globals.sequence = (string)drv.Row["sequence"]; Globals.generation = Int32.Parse((string)drv.Row["generation"]); Globals.isChosen = true; MessageBox.Show("Загрузка произведена успешно"); Close(); } catch (Exception) { } } private void delete_button_Click(object sender, RoutedEventArgs e) { if (!isLoaded || loading_data.SelectedIndex < 0 || !Globals.isConSuccess) return; try { DataRowView drv = (DataRowView)loading_data.SelectedItem; if (con.DeleteGame(Guid.Parse((string)drv.Row["guid"]))) { loading_data.ItemsSource = GetSavedGames().DefaultView; MessageBox.Show("Запись удалена"); return; } MessageBox.Show("Что-то пошло не так"); } catch (Exception) { } } } }
95d56d7fac548ff254c3e46e512b456480f900b9
C#
K2177/TTOS0200
/Labra1+2/Tht05.cs
3.28125
3
using System; namespace Labra1_2 { class Tht05 { public static void Tehtava5() { // Tee ohjelma, joka näyttää annetun sekuntimäärän tunteina, minuutteina ja sekunteina. Aikamääre sekuntteina kysytään käyttäjältä. Console.Write("Sekunnit: "); int sek = int.Parse(Console.ReadLine()); int h = sek / 3600; int m = (sek % 3600) / 60; int s = (sek % 3600) % 60; Console.WriteLine("Tunnit: {0} Minuutit: {1} Sekunnit: {2}", h, m, s); } } }
57deaa2697a041c019bcc1b95ee09705f9243267
C#
liamxun-123/myMd
/01.计算机科学/算法/leetcode/513.找树左下角的值.cs
3.328125
3
/* * @lc app=leetcode.cn id=513 lang=csharp * * [513] 找树左下角的值 * * https://leetcode-cn.com/problems/find-bottom-left-tree-value/description/ * * algorithms * Medium (72.00%) * Likes: 140 * Dislikes: 0 * Total Accepted: 25.7K * Total Submissions: 35.8K * Testcase Example: '[2,1,3]' * * 给定一个二叉树,在树的最后一行找到最左边的值。 * * 示例 1: * * * 输入: * * ⁠ 2 * ⁠ / \ * ⁠ 1 3 * * 输出: * 1 * * * * * 示例 2: * * * 输入: * * ⁠ 1 * ⁠ / \ * ⁠ 2 3 * ⁠ / / \ * ⁠ 4 5 6 * ⁠ / * ⁠ 7 * * 输出: * 7 * * * * * 注意: 您可以假设树(即给定的根节点)不为 NULL。 * */ // @lc code=start /** * Definition for a binary tree node. * public class TreeNode { * public int val; * public TreeNode left; * public TreeNode right; * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) { * this.val = val; * this.left = left; * this.right = right; * } * } */ public class Solution { public int FindBottomLeftValue (TreeNode root) { int result = root.val; Queue<TreeNode> queue = new Queue<TreeNode> (); queue.Enqueue (root); while (queue.Count > 0) { int count = queue.Count; for (int i = 0; i < count; i++) { TreeNode tmp = queue.Dequeue (); if (i == 0) { result = tmp.val; } if (tmp.left != null) queue.Enqueue (tmp.left); if (tmp.right != null) queue.Enqueue (tmp.right); } } return result; } } // @lc code=end
241299f8062208a973c188a22804120e84ab82fe
C#
nirjhar18/EventsAndDelegates
/Number.cs
3.875
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EventsAndDelegates { //All the subscribers must provided a handler function, which is going to be called when a publisher raises an event. //In the above example, the Number class creates an instance of PrintHelper and subscribes to the beforePrintEvent //with the "+=" operator and gives the name of the function which will handle the event (it will be get called when publish fires an event). //printHelper_beforePrintEvent is the event handler that has the same signature as the BeforePrint delegate in the PrintHelper class. class Number { PrintHelper printHelper = new PrintHelper(); public int Value { get; set; } public Number(int val) { Value = val; //subscribe to beforePrintEvent event. To subscribe to an event, you will look at the events of the print helper class // and add your method which will be called when publisher fires an event. printHelper.beforePrintEvent += helperEventToBeRaised; } //beforePrintevent handler //This function will be called when publish fires an event void helperEventToBeRaised() { Console.WriteLine("BeforPrintEventHandler: PrintHelper is going to print a value"); } public void PrintMoney() { //You are calling a function of print helper which checks if anyone has subscribed to their event, if yes // then it calls a method which is handled by client class printHelper.PrintMoney(Value); } public void PrintNumber() { //You are calling a function of print helper which checks if anyone has subscribed to their event, if yes // then it calls a method which is handled by client class printHelper.PrintNumber(Value); } } }
373dde8656dee8abdb19caad51d4568237a8ae65
C#
huchanghui123/Read-PC-hardware-info
/OpenPCINFO/PC.cs
2.578125
3
using System; using System.Collections.Generic; using System.Text; using System.Management; using System.Collections; using System.Net; using System.Net.NetworkInformation; using System.Linq; namespace OpenPCINFO { class PC { public static string GetSystemType() { try { var st = string.Empty; var mos = new ManagementObjectSearcher("Select * from Win32_ComputerSystem"); foreach (var o in mos.Get()) { var mo = (ManagementObject)o; st = mo["SystemType"].ToString(); } mos.Dispose(); return st; } catch (Exception) { return "unknow"; } } public static string GetSystemVersion() { try { var os_version = string.Empty; var mos = new ManagementObjectSearcher("Select * from Win32_OperatingSystem"); foreach (var o in mos.Get()) { var mo = (ManagementObject)o; os_version += mo["Caption"].ToString() + " "; os_version += mo["Version"].ToString(); } mos.Dispose(); return os_version; } catch (Exception) { return "unknow"; } } public static string GetCpuName() { try { var st = string.Empty; var mos = new ManagementObjectSearcher("Select * from Win32_Processor"); foreach (var o in mos.Get()) { var mo = (ManagementObject)o; st = mo["Name"].ToString(); } mos.Dispose(); return st; } catch (Exception) { return "unknow"; } } public static string GetBoardType() { try { var st = string.Empty; var mos = new ManagementObjectSearcher("Select * from Win32_BaseBoard"); foreach (var o in mos.Get()) { var mo = (ManagementObject)o; st = mo["Product"].ToString(); } mos.Dispose(); return st; } catch (Exception) { return "unknow"; } } public static string GetBios() { try { ManagementClass mc = new ManagementClass("Win32_BIOS"); ManagementObjectCollection moc = mc.GetInstances(); string strID = null; foreach (ManagementObject mo in moc) { strID += mo.Properties["Manufacturer"].Value.ToString() + " "; //strID += mo.Properties["Version"].Value.ToString() + " "; strID += mo.Properties["Name"].Value.ToString() + " "; string data = mo.Properties["ReleaseDate"].Value.ToString().Substring(0, 8); strID += DateTime.ParseExact(data, "yyyyMMdd", null).ToString("yyyy/MM/dd") + " "; } mc = null; moc.Dispose(); return strID; } catch (Exception) { return "unknow"; } } public static ArrayList GetMemeryInfo() { try { ManagementClass mc = new ManagementClass("Win32_PhysicalMemory"); ManagementObjectCollection moc = mc.GetInstances(); ArrayList mem_list = new ArrayList(); foreach (ManagementObject m in moc) { mem_list.Add(new MemInfo(m.Properties["Manufacturer"].Value.ToString(), Convert.ToInt32(m.Properties["Speed"].Value), Convert.ToInt16(m.Properties["MemoryType"].Value), Convert.ToDouble(m.Properties["Capacity"].Value))); } mc = null; moc.Dispose(); return mem_list; } catch (Exception) { return null; } } public static ArrayList GetDiskInfo() { try { ManagementClass mc = new ManagementClass("Win32_DiskDrive"); ManagementObjectCollection moc = mc.GetInstances(); ArrayList disk_list = new ArrayList(); foreach (ManagementObject m in moc) { if (m.Properties["Size"].Value != null) { disk_list.Add(new DiskInfo(m.Properties["Caption"].Value.ToString(), m.Properties["InterfaceType"].Value.ToString(), Convert.ToDouble(m.Properties["Size"].Value))); } } mc = null; moc.Dispose(); return disk_list; } catch (Exception) { return null; } } public static ArrayList GetMyNetWorkInfo() { try { ManagementClass mc = new ManagementClass("Win32_NetworkAdapter"); ManagementObjectCollection moc = mc.GetInstances(); ArrayList net_list = new ArrayList(); String Name = ""; String MACAddress = ""; foreach (ManagementObject m in moc) { //物理适配器 if (Convert.ToBoolean(m.Properties["PhysicalAdapter"].Value.ToString())) { if (m.Properties["MACAddress"].Value != null) { Name = m.Properties["Name"].Value.ToString(); MACAddress = m.Properties["MACAddress"].Value.ToString(); //net_list.Add(new NetWorkInfo(Name, MACAddress)); Console.WriteLine("Name:"+ Name+ " MACAddress:"+ MACAddress); } } } mc = null; moc.Dispose(); return net_list; } catch (Exception) { return null; } } public static ArrayList GetIPv4Address() { ArrayList net_list = new ArrayList(); String Name = ""; String IPAddress = ""; String Mac = ""; String NetType = ""; long NetSpeed = 0; string ping = ""; NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface adapter in adapters) { //Name = adapter.Name; Name = adapter.Description; Mac = BitConverter.ToString(adapter.GetPhysicalAddress().GetAddressBytes()); NetSpeed = adapter.Speed; NetType = adapter.NetworkInterfaceType.ToString(); //Console.WriteLine("Name:"+ Name+" OperationalStatus:" + adapter.OperationalStatus); //String temp = string.Join(":", (from z in adapter.GetPhysicalAddress().GetAddressBytes() select z.ToString("X2")).ToArray()); if (Mac == string.Empty || Name.Contains("Microsoft"))//屏蔽系统创建的虚拟无线网卡 { continue; } UnicastIPAddressInformationCollection unicastIPAddressInformation = adapter.GetIPProperties().UnicastAddresses; if (unicastIPAddressInformation.Count > 0) { foreach (var item in unicastIPAddressInformation) { if (item.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { IPAddress = item.Address.ToString(); ping = Ping(IPAddress); NetWorkInfo netwotk = new NetWorkInfo(Name, IPAddress, Mac, NetSpeed, ping, NetType); net_list.Add(netwotk); } } } } return net_list; } public static string Ping(string ip) { System.Diagnostics.Process p = new System.Diagnostics.Process(); p.StartInfo.FileName = "cmd.exe"; //关闭Shell的使用 p.StartInfo.UseShellExecute = false; //重定向标准输入 p.StartInfo.RedirectStandardInput = true; //重定向标准输出 p.StartInfo.RedirectStandardOutput = true; //重定向错误输出 p.StartInfo.RedirectStandardError = true; //设置不显示窗口 p.StartInfo.CreateNoWindow = true; p.Start(); p.StandardInput.WriteLine(string.Format("ping -n 1 -S {0} www.baidu.com", ip)); p.StandardInput.WriteLine("exit"); string strRst = p.StandardOutput.ReadToEnd(); String[] strs =strRst.Split(new string[] { "\r\n" }, StringSplitOptions.None); //foreach (string str in strs) //{ // Console.WriteLine("ping>>>>>>"+str); //} //Console.WriteLine("ping>>>>>>" + strs[6]); //System.IO.StringReader sr = new System.IO.StringReader(strRst); //Console.WriteLine("ping>>>>>>>>>>>>>"+sr.ReadLine()); return strs[6]; } } }
61af434a9e47deb2d55b83d5b8e4ff6f97441c23
C#
BigETI/INIEngine
/INIEngine/INIFile.cs
3.046875
3
using System.IO; /// <summary> /// INI engine namespace /// </summary> namespace INIEngine { /// <summary> /// INI file class /// </summary> public static class INIFile { /// <summary> /// Open file /// </summary> /// <param name="path">Path</param> /// <returns>INI</returns> public static INI Open(string path) { INI ret = null; try { if (File.Exists(path)) { using (FileStream stream = File.Open(path, FileMode.Open)) { ret = Open(stream); } } } catch { // } return ret; } /// <summary> /// Open stream /// </summary> /// <param name="stream">Stream</param> /// <returns>INI</returns> public static INI Open(Stream stream) { INI ret = null; if (stream != null) { ret = new INI(stream); } return ret; } } }
958c427edea4f8ffd504da3fe7ea502a2b63b11c
C#
chuxuantinh/Software-Dev
/13.DS-Adv/exam21Nov2020/01. Dog Vet - Correctness_Skeleton/01.DogVet/DogVet.cs
3.265625
3
namespace _01.DogVet { using System; using System.Collections.Generic; using System.Linq; public class DogVet : IDogVet { List<Dog> dogs = new List<Dog>(); Dictionary<string, Dictionary<string, Dog>> byOwnerId = new Dictionary<string, Dictionary<string, Dog>>(); Dictionary<Breed, HashSet<Dog>> byBreed = new Dictionary<Breed, HashSet<Dog>>(); Dictionary<int, HashSet<Dog>> byAge = new Dictionary<int, HashSet<Dog>>(); //SortedDictionary<int, SortedDictionary<string, SortedDictionary<string, List<Dog>>>> ordered = new SortedDictionary<int, SortedDictionary<string, SortedDictionary<string, List<Dog>>>>(); public int Size { get => dogs.Count; } public void AddDog(Dog dog, Owner owner) { if (dogs.Any(d => d.Id == dog.Id)) { throw new ArgumentException(); } if (!byOwnerId.ContainsKey(owner.Id)) { byOwnerId[owner.Id] = new Dictionary<string, Dog>(); } if (byOwnerId[owner.Id].ContainsKey(dog.Name)) { throw new ArgumentException(); } dog.Owner = owner; //owner.Dogs.Add(dog.Name, dog); byOwnerId[owner.Id].Add(dog.Name, dog); if (!byBreed.ContainsKey(dog.Breed)) { byBreed[dog.Breed] = new HashSet<Dog>(); } byBreed[dog.Breed].Add(dog); if (!byAge.ContainsKey(dog.Age)) { byAge[dog.Age] = new HashSet<Dog>(); } byAge[dog.Age].Add(dog); dogs.Add(dog); } public bool Contains(Dog dog) { return dogs.Contains(dog); } public Dog GetDog(string name, string ownerId) { if (!byOwnerId.ContainsKey(ownerId))//? { throw new ArgumentException(); } if (!byOwnerId[ownerId].ContainsKey(name)) { throw new ArgumentException(); } return byOwnerId[ownerId][name]; } public Dog RemoveDog(string name, string ownerId) { var dogToRemove = GetDog(name, ownerId); dogs.Remove(dogToRemove); byOwnerId[ownerId].Remove(name); if (byOwnerId[ownerId].Count == 0) { byOwnerId.Remove(ownerId); } byBreed[dogToRemove.Breed].Remove(dogToRemove); if (byBreed[dogToRemove.Breed].Count == 0) { byBreed.Remove(dogToRemove.Breed); } byAge[dogToRemove.Age].Remove(dogToRemove); if (byAge[dogToRemove.Age].Count == 0) { byAge.Remove(dogToRemove.Age); } return dogToRemove; } public IEnumerable<Dog> GetDogsByOwner(string ownerId) { if (!byOwnerId.ContainsKey(ownerId)) { throw new ArgumentException(); } return byOwnerId[ownerId].Values; } public IEnumerable<Dog> GetDogsByBreed(Breed breed) { if (!byBreed.ContainsKey(breed) || byBreed[breed].Count == 0) { throw new ArgumentException(); } return byBreed[breed]; } public void Vaccinate(string name, string ownerId) { if (!byOwnerId.ContainsKey(ownerId) || !byOwnerId[ownerId].ContainsKey(name))//? { throw new ArgumentException(); } byOwnerId[ownerId][name].Vaccines++; } public void Rename(string oldName, string newName, string ownerId) { if (!byOwnerId.ContainsKey(ownerId) || !byOwnerId[ownerId].ContainsKey(oldName))//? { throw new ArgumentException(); } var dog = byOwnerId[ownerId][oldName]; dog.Name = newName; byOwnerId[ownerId].Remove(oldName); byOwnerId[ownerId].Add(newName, dog); } public IEnumerable<Dog> GetAllDogsByAge(int age) { if (!byAge.ContainsKey(age)) { throw new ArgumentException(); } return byAge[age]; } public IEnumerable<Dog> GetDogsInAgeRange(int lo, int hi) { return dogs.Where(d => lo <= d.Age && d.Age <= hi).ToList(); } public IEnumerable<Dog> GetAllOrderedByAgeThenByNameThenByOwnerNameAscending() { return dogs.OrderBy(d => d.Age).ThenBy(d => d.Name).ThenBy(d => d.Owner.Name).ToList(); //return ordered.Values.SelectMany(d => d.Values).SelectMany(dog => dog.Values).Select(dogs => dogs).ToList(); } } }
fef1d2b85a26b585af7bd0c7715aae34f25be959
C#
chenmj201601/UMP
/UMP/UMPS4601/UMPS4601/Converters/TableLvConverter.cs
2.78125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Data; using VoiceCyber.UMP.Common; namespace UMPS4601.Converters { public class TableLvConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (value == null || parameter == null) { return Visibility.Collapsed; } //double trendType; double doubleValue = double.Parse(value.ToString()); if (value.Equals(string.Empty)) { return Visibility.Collapsed; } string strParam = parameter.ToString(); //if (!double.TryParse(strValue, out trendType)) //{ // return Visibility.Collapsed; //} if (doubleValue==1&& strParam == "U")//1 上升 { return Visibility.Visible; } if (doubleValue==-1 && strParam == "D")//-1下降 { return Visibility.Visible; } if (doubleValue==0 && strParam == "F")//0持平 { return Visibility.Visible; } if (doubleValue >= 1 && strParam == "G")//达标 { return Visibility.Visible; } if (doubleValue < 1 && strParam == "B")//不达标 { return Visibility.Visible; } if (strParam == "Go") { return Visibility.Visible; } return Visibility.Collapsed; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } }
e965f1f16f9921f93b6176488ac512f1273bfa2c
C#
Albert-Bennett/EonEngine
/Eon Engine/Console/Mk 1/Eon/Eon/Common.cs
2.703125
3
/* Created 10/06/2013 * * Author: Albert Bennett. * Copyright @ Aeon Studios. */ using Eon.Helpers; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Media; using System; namespace Eon { /// <summary> /// An event to deal with the exiting of the game. /// </summary> public delegate void ExitingEvent(); /// <summary> /// A delegate used to define what happends /// when the screen resolution has changed. /// </summary> public delegate void ScreenResolutionChangedEvent(); /// <summary> /// Defines the common elements in Eon i.e GraphicsDevice. /// </summary> public sealed class Common { static Game game; static TimeSpan elapsedTimeDelta; static TimeSpan totalSecs = TimeSpan.Zero; static SpriteBatch batch; static GraphicsDeviceManager deviceManager; //static VideoPlayer videoPlayer; static ContentManager content; static Vector2 scrnRes = new Vector2(800, 480); static Vector2 prevScrnRes = Vector2.One; /// <summary> /// An event to be thrown when the game is being exited. /// </summary> public static event ExitingEvent OnExit; /// <summary> /// An event to be thrown when the screen /// resolution for the game has changed. /// </summary> public static ScreenResolutionChangedEvent OnScreenResChanged; /// <summary> /// The game. /// </summary> public static Game Game { get { return game; } } /// <summary> /// The common GraphicsDevice. /// </summary> public static GraphicsDevice Device { get { return Game.GraphicsDevice; } } /// <summary> /// The common GraphicsDeviceManager. /// </summary> public static GraphicsDeviceManager DeviceManager { get { return deviceManager; } } /// <summary> /// The screen resolution of the game. /// </summary> public static Vector2 ScreenResolution { get { return scrnRes; } } /// <summary> /// The previous resolution setting for the screen. /// </summary> public static Vector2 PreviousScreenResolution { get { return prevScrnRes; } } /// <summary> /// The common Viewport. /// </summary> internal static Viewport Viewport { get { return Device.Viewport; } } /// <summary> /// The common ContentManager. /// </summary> public static ContentManager ContentManager { get { return content; } } /// <summary> /// The common SpriteBatch. /// </summary> public static SpriteBatch Batch { get { return batch; } } /// <summary> /// The common ElapsedTimeDelta. /// </summary> public static TimeSpan ElapsedTimeDelta { get { return Common.elapsedTimeDelta; } } /// <summary> /// Returns the video player for the game. /// </summary> //public static VideoPlayer VideoPlayer { get { return videoPlayer; } } /// <summary> /// The total amount of seconds that the game has been running for. /// </summary> public static TimeSpan TotalPlayTimeSecs { get { return Common.totalSecs; } } /// <summary> /// Creates a new Common. /// </summary> /// <param name="game">Game.</param> public Common(Game game) { deviceManager = new GraphicsDeviceManager(game); Common.game = game; Common.content = game.Content; Common.content.RootDirectory = "Content\\"; } public void Initialize() { batch = new SpriteBatch(game.GraphicsDevice); //videoPlayer = new VideoPlayer(); } /// <summary> /// Changes the game to full screen. /// </summary> public static void FullScreen() { DeviceManager.IsFullScreen = true; DeviceManager.ApplyChanges(); } /// <summary> /// Changes the screen resolution of the game. /// </summary> /// <param name="width">New resolution width.</param> /// <param name="height">New resolution height.</param> public static void ChangeScreenResolution(float width, float height) { if (!EonMathHelper.EqualEnough(width, scrnRes.X) || !EonMathHelper.EqualEnough(height, scrnRes.Y)) { prevScrnRes = scrnRes; scrnRes = new Vector2(width, height); if (OnScreenResChanged != null) OnScreenResChanged(); } } /// <summary> /// Sets the elasped time delta. /// </summary> /// <param name="time">The time to set to.</param> public void SetElaspedTimeDelta(TimeSpan time) { elapsedTimeDelta = time; totalSecs += time; } /// <summary> /// Exits the game. /// </summary> public static void ExitGame() { if (OnExit != null) OnExit(); } #region Helper Methods /// <summary> /// Converts a 2D co-ordinate into 3D space. /// </summary> /// <param name="position">The co-ordinate to be converted.</param> /// <param name="near">Wheather or not the co-ordinate should be /// calculated as being near / far from the viewport</param> /// <param name="viewMatrix">The camera's view matrix.</param> /// <param name="projection">The camera's projection matrix.</param> /// <returns>The converted co-ordinate.</returns> public static Vector3 ConvertTo3DSpace(Vector2 position, bool near, Matrix viewMatrix, Matrix projection) { Vector3 pos; if (near) pos = new Vector3(position, 0); else pos = new Vector3(position, 1); return Device.Viewport.Unproject(pos, projection, viewMatrix, Matrix.Identity); } /// <summary> /// Used to re-calibrate the position of objects /// when the screen resolution has been changed. /// </summary> /// <param name="screenSpaceVector">Any Vector2 that has been used /// to define a position or scale of an object.</param> /// <returns>The newly calibrated vector.</returns> public static Vector2 ReCalibrateScreenSpaceVector(Vector2 screenSpaceVector) { return (screenSpaceVector / prevScrnRes) * scrnRes; } /// <summary> /// Used to re-calibrate teh scale of objects /// when the screen resolution has been /// </summary> /// <param name="scale">The scale of an object.</param> /// <returns>The newly re-calibrated scale.</returns> public static float ReCalibrateScale(float scale) { Vector2 vec = ReCalibrateScreenSpaceVector( new Vector2(scale, scale)); return (vec.X + vec.Y) / 2; } #endregion } }
6d3a434c3a2f5149f1504cc151903415b3b87fdc
C#
justJosh1004/AcademyPGH-VisualStudio
/2-23-17/Guessing Game/Guessing Game/Program.cs
3.875
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Guessing_Game { class Program { static void Main(string[] args) { int[] my_array = { 3, 12, 8, 33, 2 }; while (true) { Console.WriteLine("I'm thinking of a number between 1 and 50. Can you guess which one?"); string user_guess = Console.ReadLine(); int guess = Convert.ToInt32(user_guess); bool correct = false; bool check = false; while (correct == false) { for (int i = 0; i < my_array.Length; i++) { if (my_array[i] == guess) { check = true; i = 10; correct = true; } else { check = false; } } Console.WriteLine("HERE"); if (check == true) { Console.WriteLine("you got it"); } else if (check == false) { Console.WriteLine("wrong"); } Console.ReadLine(); //return; } Console.ReadLine(); return; } } } }
95518d2f5f724efdeee7b975cbb08ea7499574ed
C#
eiceblue/Spire.Presentation-for-.NET
/CS/03_Slides/ClonePPTAtEndOfAnother.cs
2.8125
3
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using Spire.Presentation; namespace ClonePPTAtEndOfAnother { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void btnRun_Click(object sender, EventArgs e) { //Load source document from disk Presentation sourcePPT = new Presentation(); sourcePPT.LoadFromFile(@"..\..\..\..\..\..\Data\ChangeSlidePosition.pptx"); //Load destination document from disk Presentation destPPT = new Presentation(); destPPT.LoadFromFile(@"..\..\..\..\..\..\Data\PPTSample_N.pptx"); //Loop through all slides of source document foreach (ISlide slide in sourcePPT.Slides) { //Append the slide at the end of destination document destPPT.Slides.Append(slide); } //Save the document string result = "ClonePPTAtEndOfAnother_result.pptx"; destPPT.SaveToFile(result, FileFormat.Pptx2013); //Launch the file OutputViewer(result); } private void OutputViewer(string filename) { try { System.Diagnostics.Process.Start(filename); } catch { } } } }
12f5b4e40186ea7a980ece6963d9c9386e880c65
C#
marcieleadivincula/entra21
/AppVinteUm/AppVinteUm/GeraOutrosDados.cs
3.03125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AppVinteUm { class GeraOutrosDados { private static Random ran = new Random(); //Gera int TipoCliente, sendo 1 para NORMAL e 2 para SÓCIO e 0 para indefinido public static string TipoClienteNormal() { int escolha = ran.Next(1, 2); string tipoCliente; switch (escolha) { case 1: tipoCliente = "Nomal"; break; default: tipoCliente = ""; break; } return tipoCliente; } public static string TipoClienteSocio() { int escolha = ran.Next(1, 2); string tipoCliente; switch (escolha) { case 1: tipoCliente = "Sócio"; break; default: tipoCliente = ""; break; } return tipoCliente; } //Gera string Cargo public static string Cargo() { int escolha = ran.Next(1, 21); string cargo; switch (escolha) { case 1: cargo = "Desenvolvedor Júnior"; break; case 2: cargo = "Estagiário"; break; case 3: cargo = "Desenvolvedor Pleno"; break; case 4: cargo = "Diretor"; break; case 5: cargo = "Gerente"; break; case 6: cargo = "Tech Líder"; break; case 7: cargo = "Scrum Master"; break; case 8: cargo = "BA"; break; case 9: cargo = "PO"; break; case 10: cargo = "CTO"; break; case 11: cargo = "CEO"; break; case 12: cargo = "Desenvolvedor Mobile"; break; case 13: cargo = "Desenvolvedor C#"; break; case 14: cargo = "Desenvolvedor Java"; break; case 15: cargo = "Desenvolvedor Android"; break; case 16: cargo = "Desenvolvedor Frontend"; break; case 17: cargo = "Desenvolvedor Backend"; break; case 18: cargo = "Desenvolvedor Full Stack"; break; case 19: cargo = "Desenvolvedor iOS"; break; case 20: cargo = "Desenvolvedor Sênior"; break; default: cargo = ""; break; } return cargo; } // Gera um Tipo de Produto de 1 a 6 //O tipoDeProduto gera um custo para loja, o custo é dado na tabela abaixo public static int TipoProduto() { int tipoProduto = ran.Next(1, 7); double valorProduto; switch (tipoProduto) { case 1: valorProduto = 5.45; break; case 2: valorProduto = 6.78; break; case 3: valorProduto = 1.43; break; case 4: valorProduto = 2.68; break; case 5: valorProduto = 3.78; break; case 6: valorProduto = 2.96; break; default: valorProduto = 0.0; break; } return (int)valorProduto; } // Gera um quantidade fornecida ao mês de 1 a 6 public static int QuantidadeFornecidaAoMes() { double qtdFornecidaAoMes = ran.Next(200, 2000) + ran.NextDouble(); return (int)qtdFornecidaAoMes; } // Gera um QtdAcoes de 1 a 10 (clientes) de até no máximo de 4.95% das ações public static float QtdAcoes() { double qtdAcoes = ran.Next(1, 10); return (int)qtdAcoes; } // Gera um cnpj no padrao 00.000.000/0000-00 //Exemplo: CNPJ: 42.318.949/0001-84 public static string Cnpj() { string cnpj = ""; for (int i = 0; i < 18; i++) { if (i % 4 == 0) { if (i == 15) { cnpj += "-"; } } else { cnpj += ran.Next(0, 10); } } return cnpj; } // Gera um saldo aleatório por hora public static double SalarioPorHora() { //double valorHora = ran.Next(0, 5); //double valorDiario = ran.Next(5, 35); //double valorMensal = ran.Next(151, 1046); double saldoPorHora = ran.Next(1, 6) + ran.NextDouble(); return saldoPorHora; } } }
cdf63fd7e923cff48ac3fc32ddf8279b205b5b99
C#
ElementaryDearWatson/TestBench
/SOLIDexperimentation/Program.cs
3.296875
3
using System; namespace SOLIDexperimentation { class Program { public static void Main() { Console.WriteLine("Name of the Student?"); var name = Console.ReadLine(); Console.WriteLine("Student ID"); var Id = Console.ReadLine(); Console.WriteLine("Marks in SubjectA"); var subjectA = float.Parse(Console.ReadLine()); Console.WriteLine("Marks in SubjectB"); var subjectB = float.Parse(Console.ReadLine()); Console.WriteLine("Marks in SubjectC"); var subjectC = float.Parse(Console.ReadLine()); Console.WriteLine("Marks in SubjectD"); var subjectD = float.Parse(Console.ReadLine()); Student newEntry = new Student(new StudentMarksCalculator(), new StudentFeeCalculator()); newEntry.Name = name; newEntry.ID = Id; var studentPercentage = newEntry.GetPercentage(subjectA, subjectB, subjectC, subjectD); Console.WriteLine("The percentage of Student: {0} is {1}", name, studentPercentage); Console.WriteLine("The fee for the student {0} is {1}", name, newEntry.GetTution(studentPercentage)); } } }
0a97ac392b418e1c2284d9d1e9a23994fc4167c1
C#
KinaUna/AvP_Song_Annotations
/AvP_Song_Annotations/Services/RunProcess.cs
2.890625
3
using System; using System.Linq; using System.Collections.Generic; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using AvP_Song_Annotations.Extensions; namespace AvP_Song_Annotations.Services { public class ProcessWrapper : Process { public enum PipeType { StdOut, StdErr } public class Output { public string Message { get; set; } public PipeType Pipe { get; set; } public override string ToString() { return $"{Pipe}: {Message}"; } } private readonly string _command; private readonly string _args; private bool _isDisposed; private readonly Queue<Output> _outputQueue = new Queue<Output>(); private readonly ManualResetEvent[] _waitHandles = new ManualResetEvent[2]; private readonly ManualResetEvent _outputSteamWaitHandle = new ManualResetEvent(false); public ProcessWrapper(string startCommand, string args) { _command = startCommand; _args = args; } public IEnumerable<string> GetMessages() { while (!_isDisposed) { _outputSteamWaitHandle.WaitOne(); if (_outputQueue.Any()) yield return _outputQueue.Dequeue().ToString(); } } public void SendCommand(string command) { StandardInput.Write(command); StandardInput.Flush(); } public new int Start() { ProcessStartInfo startInfo = new ProcessStartInfo { FileName = _command, Arguments = _args, UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true, RedirectStandardInput = true, CreateNoWindow = true }; StartInfo = startInfo; OutputDataReceived += delegate (object sender, DataReceivedEventArgs args) { if (args.Data == null) { _waitHandles[0].Set(); } else if (args.Data.Length > 0) { _outputQueue.Enqueue(new Output { Message = args.Data, Pipe = PipeType.StdOut }); _outputSteamWaitHandle.Set(); } }; ErrorDataReceived += delegate (object sender, DataReceivedEventArgs args) { if (args.Data == null) { _waitHandles[1].Set(); } else if (args.Data.Length > 0) { _outputSteamWaitHandle.Set(); _outputQueue.Enqueue(new Output { Message = args.Data, Pipe = PipeType.StdErr }); } }; EnableRaisingEvents = true; var tcs = new TaskCompletionSource<int>(); Exited += (s, ea) => tcs.SetResult(base.ExitCode); bool started = base.Start(); if (!started) { //you may allow for the process to be re-used (started = false) //but I'm not sure about the guarantees of the Exited event in such a case throw new InvalidOperationException("Could not start process: " + base.ProcessName); } _waitHandles[0] = new ManualResetEvent(false); BeginErrorReadLine(); _waitHandles[1] = new ManualResetEvent(false); BeginOutputReadLine(); return Id; } public new void Dispose() { StandardInput.Flush(); StandardInput.Close(); if (!WaitForExit(1000)) { Kill(); } if (WaitForExit(1000)) { WaitHandle.WaitAll(_waitHandles); } base.Dispose(); _isDisposed = true; } } }
cebc45c7f84f75435b90ade8ba304ccd8d0bee4a
C#
AArnott/MoneyMan
/src/Nerdbank.MoneyManagement/AccountSort.cs
2.625
3
// Copyright (c) Andrew Arnott. All rights reserved. // Licensed under the Ms-PL license. See LICENSE.txt file in the project root for full license information. using Nerdbank.MoneyManagement.ViewModels; namespace Nerdbank.MoneyManagement; /// <summary> /// Sorts <see cref="AccountViewModel"/> objects by <see cref="AccountViewModel.Name"/>. /// </summary> internal class AccountSort : IOptimizedComparer<AccountViewModel> { internal static readonly AccountSort Instance = new(); private AccountSort() { } public int Compare(AccountViewModel? x, AccountViewModel? y) { if (x is null) { return y is null ? 0 : -1; } else if (y is null) { return 1; } int order = x.Name.CompareTo(y.Name); if (order != 0) { return order; } order = x.Id == 0 ? (y.Id == 0 ? 0 : -1) : (y.Id == 0) ? 1 : 0; if (order != 0) { return order; } return 0; } public bool IsPropertySignificant(string propertyName) => propertyName is nameof(AccountViewModel.Name) or nameof(AccountViewModel.Id); }
7d75d98f0f6540739eb40d0a36f31b200e1e6c88
C#
vait/TimerInForm
/TimerInForm/Form1.cs
2.90625
3
using System; using System.Threading; using System.Windows.Forms; namespace TimerInForm { public partial class Form1 : Form { private readonly SafeTimerDecorator _timer; public Form1() { InitializeComponent(); _timer = new SafeTimerDecorator(ShowTime, null, Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan); } private void button1_Click(object sender, EventArgs e) { _timer.Change(TimeSpan.Zero, TimeSpan.FromMilliseconds(100)); } private void button2_Click(object sender, EventArgs e) { _timer.Stop(); } private void Form1_FormClosing(object sender, FormClosingEventArgs e) { _timer?.Dispose(); } private void ShowTime(object state) { Invoke((MethodInvoker)(() => { label1.Text = DateTime.Now.ToString("HH:mm:ss.fff tt"); })); } } }
59484b32b9e0bfed1a2c2d68b3d0534ebe26ea46
C#
didimitrov/Algo
/SortingAlgorithmsDemo/CSharp2/StringsAndTextProcessing/21.CharOccurs/Program.cs
3.96875
4
/* * 21. Write a program that reads a string from the console and prints * all different letters in the string along with information how many * times each letter is found. */ using System; using System.Collections.Generic; using System.Linq; namespace _21.CharOccurs { class Program { static void Main(string[] args) { var input = Console.ReadLine(); if (input != null) { char[] inputInCharArray = input.ToCharArray(); var result = new Dictionary<char, int>(); // var differentLetters = inputInCharArray.Distinct().ToArray(); foreach (char ch in inputInCharArray) { if (!result.ContainsKey(ch)) { result.Add(ch, 1); } result[ch]++; } // var sortedList = result.OrderBy(x => x.Key); Console.WriteLine("\nLetter occurence table:\n{0}\n", string.Join("\n", result.Select(x => string.Format(@"'{0}' -> {1} time(s)", x.Key, x.Value)).ToArray())); } } } }
6be846799b80e37f36d12b4a6ecfb200c6114c88
C#
cristirss/TlgrmGenerator
/TelegramGenerator/Program.cs
3.359375
3
using Json.Net; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace TelegramGenerator { class Program { static void Main(string[] args) { List<Telegram> Telegrams = new List<Telegram>(); Console.WriteLine("Input the number of telegrams you would like to write to file: "); int numOfTelegrams = Convert.ToInt16(Console.ReadLine()); Console.WriteLine("Input number of milliseconds between each write to file: "); int milliSec = Convert.ToInt16(Console.ReadLine()); Console.WriteLine("Write name of json file: "); string fileName = Console.ReadLine(); for (int i = 0; i < numOfTelegrams; i++) Telegrams.Add(Telegram.RandomTelegram()); foreach (var item in Telegrams) { Thread.Sleep(milliSec); File.AppendAllText($"C:\\Users\\cris\\Desktop\\{fileName}.json", $"{item} ," + Environment.NewLine); } Console.WriteLine("Telegrams successfully written to file."); } } }
46c43ca997bcaf0f08c896c511ffed59601c02de
C#
zhuxb711/Vanara
/PInvoke/Gdi32/WinGdi.Brush.cs
2.53125
3
using System; using System.Runtime.InteropServices; namespace Vanara.PInvoke { public static partial class Gdi32 { /// <summary> /// <para>The <c>CreateBrushIndirect</c> function creates a logical brush that has the specified style, color, and pattern.</para> /// </summary> /// <param name="plbrush"> /// <para>A pointer to a LOGBRUSH structure that contains information about the brush.</para> /// </param> /// <returns> /// <para>If the function succeeds, the return value identifies a logical brush.</para> /// <para>If the function fails, the return value is <c>NULL</c>.</para> /// </returns> /// <remarks> /// <para>A brush is a bitmap that the system uses to paint the interiors of filled shapes.</para> /// <para> /// After an application creates a brush by calling <c>CreateBrushIndirect</c>, it can select it into any device context by calling /// the SelectObject function. /// </para> /// <para> /// A brush created by using a monochrome bitmap (one color plane, one bit per pixel) is drawn using the current text and background /// colors. Pixels represented by a bit set to 0 are drawn with the current text color; pixels represented by a bit set to 1 are /// drawn with the current background color. /// </para> /// <para>When you no longer need the brush, call the DeleteObject function to delete it.</para> /// <para> /// <c>ICM:</c> No color is done at brush creation. However, color management is performed when the brush is selected into an /// ICM-enabled device context. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/wingdi/nf-wingdi-createbrushindirect HBRUSH CreateBrushIndirect( CONST // LOGBRUSH *plbrush ); [DllImport(Lib.Gdi32, SetLastError = false, ExactSpelling = true)] [PInvokeData("wingdi.h", MSDNShortId = "75f94ad1-ca25-4ad1-9e8c-ad1a4b8475a7")] public static extern SafeHBRUSH CreateBrushIndirect(in LOGBRUSH plbrush); /// <summary> /// <para> /// The <c>CreateDIBPatternBrush</c> function creates a logical brush that has the pattern specified by the specified /// device-independent bitmap (DIB). The brush can subsequently be selected into any device context that is associated with a device /// that supports raster operations. /// </para> /// <para> /// <c>Note</c> This function is provided only for compatibility with 16-bit versions of Windows. Applications should use the /// CreateDIBPatternBrushPt function. /// </para> /// </summary> /// <param name="h"> /// <para> /// A handle to a global memory object containing a packed DIB, which consists of a BITMAPINFO structure immediately followed by an /// array of bytes defining the pixels of the bitmap. /// </para> /// </param> /// <param name="iUsage"> /// <para> /// Specifies whether the <c>bmiColors</c> member of the BITMAPINFO structure is initialized and, if so, whether this member contains /// explicit red, green, blue (RGB) values or indexes into a logical palette. The fuColorSpec parameter must be one of the following values. /// </para> /// <list type="table"> /// <listheader> /// <term>Value</term> /// <term>Meaning</term> /// </listheader> /// <item> /// <term>DIB_PAL_COLORS</term> /// <term> /// A color table is provided and consists of an array of 16-bit indexes into the logical palette of the device context into which /// the brush is to be selected. /// </term> /// </item> /// <item> /// <term>DIB_RGB_COLORS</term> /// <term>A color table is provided and contains literal RGB values.</term> /// </item> /// </list> /// </param> /// <returns> /// <para>If the function succeeds, the return value identifies a logical brush.</para> /// <para>If the function fails, the return value is <c>NULL</c>.</para> /// </returns> /// <remarks> /// <para> /// When an application selects a two-color DIB pattern brush into a monochrome device context, the system does not acknowledge the /// colors specified in the DIB; instead, it displays the pattern brush using the current background and foreground colors of the /// device context. Pixels mapped to the first color of the DIB (offset 0 in the DIB color table) are displayed using the foreground /// color; pixels mapped to the second color (offset 1 in the color table) are displayed using the background color. /// </para> /// <para>When you no longer need the brush, call the DeleteObject function to delete it.</para> /// <para> /// <c>ICM:</c> No color is done at brush creation. However, color management is performed when the brush is selected into an /// ICM-enabled device context. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/wingdi/nf-wingdi-createdibpatternbrush HBRUSH CreateDIBPatternBrush( HGLOBAL // h, UINT iUsage ); [DllImport(Lib.Gdi32, SetLastError = false, ExactSpelling = true)] [PInvokeData("wingdi.h", MSDNShortId = "d123ef44-e047-4188-a2bc-20e479869dc3")] [Obsolete("This function is provided only for compatibility with 16-bit versions of Windows. Applications should use the CreateDIBPatternBrushPt function.")] public static extern SafeHBRUSH CreateDIBPatternBrush(IntPtr h, DIBColorMode iUsage); /// <summary> /// <para> /// The <c>CreateDIBPatternBrushPt</c> function creates a logical brush that has the pattern specified by the device-independent /// bitmap (DIB). /// </para> /// </summary> /// <param name="lpPackedDIB"> /// <para> /// A pointer to a packed DIB consisting of a BITMAPINFO structure immediately followed by an array of bytes defining the pixels of /// the bitmap. /// </para> /// </param> /// <param name="iUsage"> /// <para> /// Specifies whether the <c>bmiColors</c> member of the BITMAPINFO structure contains a valid color table and, if so, whether the /// entries in this color table contain explicit red, green, blue (RGB) values or palette indexes. The iUsage parameter must be one /// of the following values. /// </para> /// <list type="table"> /// <listheader> /// <term>Value</term> /// <term>Meaning</term> /// </listheader> /// <item> /// <term>DIB_PAL_COLORS</term> /// <term> /// A color table is provided and consists of an array of 16-bit indexes into the logical palette of the device context into which /// the brush is to be selected. /// </term> /// </item> /// <item> /// <term>DIB_RGB_COLORS</term> /// <term>A color table is provided and contains literal RGB values.</term> /// </item> /// </list> /// </param> /// <returns> /// <para>If the function succeeds, the return value identifies a logical brush.</para> /// <para>If the function fails, the return value is <c>NULL</c>.</para> /// </returns> /// <remarks> /// <para>A brush is a bitmap that the system uses to paint the interiors of filled shapes.</para> /// <para> /// After an application creates a brush by calling <c>CreateDIBPatternBrushPt</c>, it can select that brush into any device context /// by calling the SelectObject function. /// </para> /// <para>When you no longer need the brush, call the DeleteObject function to delete it.</para> /// <para> /// <c>ICM:</c> No color is done at brush creation. However, color management is performed when the brush is selected into an /// ICM-enabled device context. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/wingdi/nf-wingdi-createdibpatternbrushpt HBRUSH CreateDIBPatternBrushPt( // const VOID *lpPackedDIB, UINT iUsage ); [DllImport(Lib.Gdi32, SetLastError = false, ExactSpelling = true)] [PInvokeData("wingdi.h", MSDNShortId = "0e34d108-fd35-4512-9eb3-c7710af36e95")] public static extern SafeHBRUSH CreateDIBPatternBrushPt(IntPtr lpPackedDIB, DIBColorMode iUsage); /// <summary> /// <para>The <c>CreateHatchBrush</c> function creates a logical brush that has the specified hatch pattern and color.</para> /// </summary> /// <param name="iHatch"> /// <para>The hatch style of the brush. This parameter can be one of the following values.</para> /// <list type="table"> /// <listheader> /// <term>Value</term> /// <term>Meaning</term> /// </listheader> /// <item> /// <term>HS_BDIAGONAL</term> /// <term>45-degree upward left-to-right hatch</term> /// </item> /// <item> /// <term>HS_CROSS</term> /// <term>Horizontal and vertical crosshatch</term> /// </item> /// <item> /// <term>HS_DIAGCROSS</term> /// <term>45-degree crosshatch</term> /// </item> /// <item> /// <term>HS_FDIAGONAL</term> /// <term>45-degree downward left-to-right hatch</term> /// </item> /// <item> /// <term>HS_HORIZONTAL</term> /// <term>Horizontal hatch</term> /// </item> /// <item> /// <term>HS_VERTICAL</term> /// <term>Vertical hatch</term> /// </item> /// </list> /// </param> /// <param name="color"> /// <para>The foreground color of the brush that is used for the hatches. To create a COLORREF color value, use the RGB macro.</para> /// </param> /// <returns> /// <para>If the function succeeds, the return value identifies a logical brush.</para> /// <para>If the function fails, the return value is <c>NULL</c>.</para> /// </returns> /// <remarks> /// <para>A brush is a bitmap that the system uses to paint the interiors of filled shapes.</para> /// <para> /// After an application creates a brush by calling <c>CreateHatchBrush</c>, it can select that brush into any device context by /// calling the SelectObject function. It can also call SetBkMode to affect the rendering of the brush. /// </para> /// <para> /// If an application uses a hatch brush to fill the backgrounds of both a parent and a child window with matching color, you must /// set the brush origin before painting the background of the child window. You can do this by calling the SetBrushOrgEx function. /// Your application can retrieve the current brush origin by calling the GetBrushOrgEx function. /// </para> /// <para>When you no longer need the brush, call the DeleteObject function to delete it.</para> /// <para> /// <c>ICM:</c> No color is defined at brush creation. However, color management is performed when the brush is selected into an /// ICM-enabled device context. /// </para> /// <para>Examples</para> /// <para> /// The following example creates a logical brush that has the specified hatch pattern and color. You can also set a hatch brush /// background to transparent or to opaque. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/wingdi/nf-wingdi-createhatchbrush HBRUSH CreateHatchBrush( int iHatch, // COLORREF color ); [DllImport(Lib.Gdi32, SetLastError = false, ExactSpelling = true)] [PInvokeData("wingdi.h", MSDNShortId = "0b5849d6-1e22-4ac5-980c-2f2a73b16adb")] public static extern SafeHBRUSH CreateHatchBrush(HatchStyle iHatch, COLORREF color); /// <summary> /// <para> /// The <c>CreatePatternBrush</c> function creates a logical brush with the specified bitmap pattern. The bitmap can be a DIB section /// bitmap, which is created by the <c>CreateDIBSection</c> function, or it can be a device-dependent bitmap. /// </para> /// </summary> /// <param name="hbm"> /// <para>A handle to the bitmap to be used to create the logical brush.</para> /// </param> /// <returns> /// <para>If the function succeeds, the return value identifies a logical brush.</para> /// <para>If the function fails, the return value is <c>NULL</c>.</para> /// </returns> /// <remarks> /// <para>A pattern brush is a bitmap that the system uses to paint the interiors of filled shapes.</para> /// <para> /// After an application creates a brush by calling <c>CreatePatternBrush</c>, it can select that brush into any device context by /// calling the SelectObject function. /// </para> /// <para> /// You can delete a pattern brush without affecting the associated bitmap by using the DeleteObject function. Therefore, you can /// then use this bitmap to create any number of pattern brushes. /// </para> /// <para> /// A brush created by using a monochrome (1 bit per pixel) bitmap has the text and background colors of the device context to which /// it is drawn. Pixels represented by a 0 bit are drawn with the current text color; pixels represented by a 1 bit are drawn with /// the current background color. /// </para> /// <para> /// <c>ICM:</c> No color is done at brush creation. However, color management is performed when the brush is selected into an /// ICM-enabled device context. /// </para> /// <para>Examples</para> /// <para>For an example, see Using Brushes.</para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/wingdi/nf-wingdi-createpatternbrush HBRUSH CreatePatternBrush( HBITMAP hbm ); [DllImport(Lib.Gdi32, SetLastError = false, ExactSpelling = true)] [PInvokeData("wingdi.h", MSDNShortId = "a3cf347e-9803-4bb0-bdb3-98929ef859ab")] public static extern SafeHBRUSH CreatePatternBrush(HBITMAP hbm); /// <summary> /// <para>The <c>CreateSolidBrush</c> function creates a logical brush that has the specified solid color.</para> /// </summary> /// <param name="color"> /// <para>The color of the brush. To create a COLORREF color value, use the RGB macro.</para> /// </param> /// <returns> /// <para>If the function succeeds, the return value identifies a logical brush.</para> /// <para>If the function fails, the return value is <c>NULL</c>.</para> /// </returns> /// <remarks> /// <para>When you no longer need the <c>HBRUSH</c> object, call the DeleteObject function to delete it.</para> /// <para>A solid brush is a bitmap that the system uses to paint the interiors of filled shapes.</para> /// <para> /// After an application creates a brush by calling <c>CreateSolidBrush</c>, it can select that brush into any device context by /// calling the SelectObject function. /// </para> /// <para> /// To paint with a system color brush, an application should use instead of , because GetSysColorBrush returns a cached brush /// instead of allocating a new one. /// </para> /// <para> /// <c>ICM:</c> No color management is done at brush creation. However, color management is performed when the brush is selected into /// an ICM-enabled device context. /// </para> /// <para>Examples</para> /// <para>For an example, see Creating Colored Pens and Brushes.</para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/wingdi/nf-wingdi-createsolidbrush HBRUSH CreateSolidBrush( COLORREF color ); [DllImport(Lib.Gdi32, SetLastError = false, ExactSpelling = true)] [PInvokeData("wingdi.h", MSDNShortId = "e39b5f77-97d8-4ea6-8277-7da12b3367f3")] public static extern SafeHBRUSH CreateSolidBrush(COLORREF color); /// <summary> /// <para> /// The <c>GetBrushOrgEx</c> function retrieves the current brush origin for the specified device context. This function replaces the /// <c>GetBrushOrg</c> function. /// </para> /// </summary> /// <param name="hdc"> /// <para>A handle to the device context.</para> /// </param> /// <param name="lppt"> /// <para>A pointer to a POINT structure that receives the brush origin, in device coordinates.</para> /// </param> /// <returns> /// <para>If the function succeeds, the return value is nonzero.</para> /// <para>If the function fails, the return value is zero.</para> /// </returns> /// <remarks> /// <para>A brush is a bitmap that the system uses to paint the interiors of filled shapes.</para> /// <para> /// The brush origin is a set of coordinates with values between 0 and 7, specifying the location of one pixel in the bitmap. The /// default brush origin coordinates are (0,0). For horizontal coordinates, the value 0 corresponds to the leftmost column of pixels; /// the value 7 corresponds to the rightmost column. For vertical coordinates, the value 0 corresponds to the uppermost row of /// pixels; the value 7 corresponds to the lowermost row. When the system positions the brush at the start of any painting operation, /// it maps the origin of the brush to the location in the window's client area specified by the brush origin. For example, if the /// origin is set to (2,3), the system maps the origin of the brush (0,0) to the location (2,3) on the window's client area. /// </para> /// <para> /// If an application uses a brush to fill the backgrounds of both a parent and a child window with matching colors, it may be /// necessary to set the brush origin after painting the parent window but before painting the child window. /// </para> /// <para> /// The system automatically tracks the origin of all window-managed device contexts and adjusts their brushes as necessary to /// maintain an alignment of patterns on the surface. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/wingdi/nf-wingdi-getbrushorgex BOOL GetBrushOrgEx( HDC hdc, LPPOINT lppt ); [DllImport(Lib.Gdi32, SetLastError = false, ExactSpelling = true)] [PInvokeData("wingdi.h", MSDNShortId = "0b938237-cb06-4776-86f8-14478abcee00")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool GetBrushOrgEx(HDC hdc, out POINT lppt); /// <summary> /// <para> /// The <c>PatBlt</c> function paints the specified rectangle using the brush that is currently selected into the specified device /// context. The brush color and the surface color or colors are combined by using the specified raster operation. /// </para> /// </summary> /// <param name="hdc"> /// <para>A handle to the device context.</para> /// </param> /// <param name="x"> /// <para>The x-coordinate, in logical units, of the upper-left corner of the rectangle to be filled.</para> /// </param> /// <param name="y"> /// <para>The y-coordinate, in logical units, of the upper-left corner of the rectangle to be filled.</para> /// </param> /// <param name="w"> /// <para>The width, in logical units, of the rectangle.</para> /// </param> /// <param name="h"> /// <para>The height, in logical units, of the rectangle.</para> /// </param> /// <param name="rop"> /// <para>The raster operation code. This code can be one of the following values.</para> /// <list type="table"> /// <listheader> /// <term>Value</term> /// <term>Meaning</term> /// </listheader> /// <item> /// <term>PATCOPY</term> /// <term>Copies the specified pattern into the destination bitmap.</term> /// </item> /// <item> /// <term>PATINVERT</term> /// <term>Combines the colors of the specified pattern with the colors of the destination rectangle by using the Boolean XOR operator.</term> /// </item> /// <item> /// <term>DSTINVERT</term> /// <term>Inverts the destination rectangle.</term> /// </item> /// <item> /// <term>BLACKNESS</term> /// <term> /// Fills the destination rectangle using the color associated with index 0 in the physical palette. (This color is black for the /// default physical palette.) /// </term> /// </item> /// <item> /// <term>WHITENESS</term> /// <term> /// Fills the destination rectangle using the color associated with index 1 in the physical palette. (This color is white for the /// default physical palette.) /// </term> /// </item> /// </list> /// </param> /// <returns> /// <para>If the function succeeds, the return value is nonzero.</para> /// <para>If the function fails, the return value is zero.</para> /// </returns> /// <remarks> /// <para> /// The values of the dwRop parameter for this function are a limited subset of the full 256 ternary raster-operation codes; in /// particular, an operation code that refers to a source rectangle cannot be used. /// </para> /// <para> /// Not all devices support the <c>PatBlt</c> function. For more information, see the description of the RC_BITBLT capability in the /// GetDeviceCaps function. /// </para> /// <para>Examples</para> /// <para>For an example, see "Example of Menu-Item Bitmaps" in Using Menus.</para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/wingdi/nf-wingdi-patblt BOOL PatBlt( HDC hdc, int x, int y, int w, int h, // DWORD rop ); [DllImport(Lib.Gdi32, SetLastError = false, ExactSpelling = true)] [PInvokeData("wingdi.h", MSDNShortId = "6deea8ef-b55d-4086-a54e-3f89bb17c6cd")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool PatBlt(HDC hdc, int x, int y, int w, int h, RasterOperationMode rop); /// <summary> /// <para> /// The <c>SetBrushOrgEx</c> function sets the brush origin that GDI assigns to the next brush an application selects into the /// specified device context. /// </para> /// </summary> /// <param name="hdc"> /// <para>A handle to the device context.</para> /// </param> /// <param name="x"> /// <para> /// The x-coordinate, in device units, of the new brush origin. If this value is greater than the brush width, its value is reduced /// using the modulus operator (nXOrg <c>mod</c> brush width). /// </para> /// </param> /// <param name="y"> /// <para> /// The y-coordinate, in device units, of the new brush origin. If this value is greater than the brush height, its value is reduced /// using the modulus operator (nYOrg <c>mod</c> brush height). /// </para> /// </param> /// <param name="lppt"> /// <para>A pointer to a POINT structure that receives the previous brush origin.</para> /// <para>This parameter can be <c>NULL</c> if the previous brush origin is not required.</para> /// </param> /// <returns> /// <para>If the function succeeds, the return value is nonzero.</para> /// <para>If the function fails, the return value is zero.</para> /// </returns> /// <remarks> /// <para>A brush is a bitmap that the system uses to paint the interiors of filled shapes.</para> /// <para> /// The brush origin is a pair of coordinates specifying the location of one pixel in the bitmap. The default brush origin /// coordinates are (0,0). For horizontal coordinates, the value 0 corresponds to the leftmost column of pixels; the width /// corresponds to the rightmost column. For vertical coordinates, the value 0 corresponds to the uppermost row of pixels; the height /// corresponds to the lowermost row. /// </para> /// <para> /// The system automatically tracks the origin of all window-managed device contexts and adjusts their brushes as necessary to /// maintain an alignment of patterns on the surface. The brush origin that is set with this call is relative to the upper-left /// corner of the client area. /// </para> /// <para> /// An application should call <c>SetBrushOrgEx</c> after setting the bitmap stretching mode to HALFTONE by using SetStretchBltMode. /// This must be done to avoid brush misalignment. /// </para> /// <para> /// The system automatically tracks the origin of all window-managed device contexts and adjusts their brushes as necessary to /// maintain an alignment of patterns on the surface. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/wingdi/nf-wingdi-setbrushorgex BOOL SetBrushOrgEx( HDC hdc, int x, int y, // LPPOINT lppt ); [DllImport(Lib.Gdi32, SetLastError = false, ExactSpelling = true)] [PInvokeData("wingdi.h", MSDNShortId = "dcc7575a-49fd-4306-8baa-57e9e0d5ed1f")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool SetBrushOrgEx(HDC hdc, int x, int y, in POINT lppt); /// <summary> /// <c>SetDCBrushColor</c> function sets the current device context (DC) brush color to the specified color value. If the device /// cannot represent the specified color value, the color is set to the nearest physical color. /// </summary> /// <param name="hdc">A handle to the DC.</param> /// <param name="color">The new brush color.</param> /// <returns> /// <para>If the function succeeds, the return value specifies the previous DC brush color as a COLORREF value.</para> /// <para>If the function fails, the return value is CLR_INVALID.</para> /// </returns> /// <remarks> /// <para> /// When the stock DC_BRUSH is selected in a DC, all the subsequent drawings will be done using the DC brush color until the stock /// brush is deselected. The default DC_BRUSH color is WHITE. /// </para> /// <para> /// The function returns the previous DC_BRUSH color, even if the stock brush DC_BRUSH is not selected in the DC: however, this will /// not be used in drawing operations until the stock DC_BRUSH is selected in the DC. /// </para> /// <para> /// The GetStockObject function with an argument of DC_BRUSH or DC_PEN can be used interchangeably with the SetDCPenColor and /// <c>SetDCBrushColor</c> functions. /// </para> /// <para><c>ICM:</c> Color management is performed if ICM is enabled.</para> /// <para>Examples</para> /// <para>For an example of setting colors, see Setting the Pen or Brush Color.</para> /// </remarks> // https://docs.microsoft.com/en-us/windows/win32/api/wingdi/nf-wingdi-setdcbrushcolor // COLORREF SetDCBrushColor( HDC hdc, COLORREF color ); [DllImport(Lib.Gdi32, SetLastError = false, ExactSpelling = true)] [PInvokeData("wingdi.h", MSDNShortId = "4feed536-2f1d-4a25-8311-7cae303167ca")] public static extern COLORREF SetDCBrushColor(HDC hdc, COLORREF color); /// <summary> /// The <c>LOGBRUSH</c> structure defines the style, color, and pattern of a physical brush. It is used by the CreateBrushIndirect /// and ExtCreatePen functions. /// </summary> /// <remarks> /// Although <c>lbColor</c> controls the foreground color of a hatch brush, the SetBkMode and SetBkColor functions control the /// background color. /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/wingdi/ns-wingdi-taglogbrush typedef struct tagLOGBRUSH { UINT lbStyle; // COLORREF lbColor; ULONG_PTR lbHatch; } LOGBRUSH, *PLOGBRUSH, *NPLOGBRUSH, *LPLOGBRUSH; [PInvokeData("wingdi.h", MSDNShortId = "ded2c7a4-2248-4d01-95c6-ab4050719094")] [StructLayout(LayoutKind.Explicit)] public struct LOGBRUSH { /// <summary> /// <para>The brush style. The <c>lbStyle</c> member must be one of the following styles.</para> /// <list type="table"> /// <listheader> /// <term>Value</term> /// <term>Meaning</term> /// </listheader> /// <item> /// <term>BS_DIBPATTERN</term> /// <term> /// A pattern brush defined by a device-independent bitmap (DIB) specification. If lbStyle is BS_DIBPATTERN, the lbHatch member /// contains a handle to a packed DIB. For more information, see discussion in lbHatch. /// </term> /// </item> /// <item> /// <term>BS_DIBPATTERN8X8</term> /// <term>See BS_DIBPATTERN.</term> /// </item> /// <item> /// <term>BS_DIBPATTERNPT</term> /// <term> /// A pattern brush defined by a device-independent bitmap (DIB) specification. If lbStyle is BS_DIBPATTERNPT, the lbHatch member /// contains a pointer to a packed DIB. For more information, see discussion in lbHatch. /// </term> /// </item> /// <item> /// <term>BS_HATCHED</term> /// <term>Hatched brush.</term> /// </item> /// <item> /// <term>BS_HOLLOW</term> /// <term>Hollow brush.</term> /// </item> /// <item> /// <term>BS_NULL</term> /// <term>Same as BS_HOLLOW.</term> /// </item> /// <item> /// <term>BS_PATTERN</term> /// <term>Pattern brush defined by a memory bitmap.</term> /// </item> /// <item> /// <term>BS_PATTERN8X8</term> /// <term>See BS_PATTERN.</term> /// </item> /// <item> /// <term>BS_SOLID</term> /// <term>Solid brush.</term> /// </item> /// </list> /// </summary> [FieldOffset(0)] public BrushStyle lbStyle; /// <summary> /// <para> /// The color in which the brush is to be drawn. If <c>lbStyle</c> is the BS_HOLLOW or BS_PATTERN style, <c>lbColor</c> is ignored. /// </para> /// <para> /// If <c>lbStyle</c> is BS_DIBPATTERN or BS_DIBPATTERNPT, the low-order word of <c>lbColor</c> specifies whether the /// <c>bmiColors</c> members of the BITMAPINFO structure contain explicit red, green, blue (RGB) values or indexes into the /// currently realized logical palette. The <c>lbColor</c> member must be one of the following values. /// </para> /// <list type="table"> /// <listheader> /// <term>Value</term> /// <term>Meaning</term> /// </listheader> /// <item> /// <term>DIB_PAL_COLORS</term> /// <term>The color table consists of an array of 16-bit indexes into the currently realized logical palette.</term> /// </item> /// <item> /// <term>DIB_RGB_COLORS</term> /// <term>The color table contains literal RGB values.</term> /// </item> /// </list> /// <para> /// If <c>lbStyle</c> is BS_HATCHED or BS_SOLID, <c>lbColor</c> is a COLORREF color value. To create a <c>COLORREF</c> color /// value, use the RGB macro. /// </para> /// </summary> [FieldOffset(4)] public COLORREF lbColor; /// <summary> /// <para>A hatch style. The meaning depends on the brush style defined by <c>lbStyle</c>.</para> /// <para> /// If <c>lbStyle</c> is BS_DIBPATTERN, the <c>lbHatch</c> member contains a handle to a packed DIB. To obtain this handle, an /// application calls the GlobalAlloc function with GMEM_MOVEABLE (or LocalAlloc with LMEM_MOVEABLE) to allocate a block of /// memory and then fills the memory with the packed DIB. A packed DIB consists of a BITMAPINFO structure immediately followed by /// the array of bytes that define the pixels of the bitmap. /// </para> /// <para> /// If <c>lbStyle</c> is BS_DIBPATTERNPT, the <c>lbHatch</c> member contains a pointer to a packed DIB. The pointer derives from /// the memory block created by LocalAlloc with LMEM_FIXED set or by GlobalAlloc with GMEM_FIXED set, or it is the pointer /// returned by a call like LocalLock (handle_to_the_dib). A packed DIB consists of a BITMAPINFO structure immediately followed /// by the array of bytes that define the pixels of the bitmap. /// </para> /// <para> /// If <c>lbStyle</c> is BS_HATCHED, the <c>lbHatch</c> member specifies the orientation of the lines used to create the hatch. /// It can be one of the following values. /// </para> /// <list type="table"> /// <listheader> /// <term>Value</term> /// <term>Meaning</term> /// </listheader> /// <item> /// <term>HS_BDIAGONAL</term> /// <term>A 45-degree upward, left-to-right hatch</term> /// </item> /// <item> /// <term>HS_CROSS</term> /// <term>Horizontal and vertical cross-hatch</term> /// </item> /// <item> /// <term>HS_DIAGCROSS</term> /// <term>45-degree crosshatch</term> /// </item> /// <item> /// <term>HS_FDIAGONAL</term> /// <term>A 45-degree downward, left-to-right hatch</term> /// </item> /// <item> /// <term>HS_HORIZONTAL</term> /// <term>Horizontal hatch</term> /// </item> /// <item> /// <term>HS_VERTICAL</term> /// <term>Vertical hatch</term> /// </item> /// </list> /// <para> /// If <c>lbStyle</c> is BS_PATTERN, <c>lbHatch</c> is a handle to the bitmap that defines the pattern. The bitmap cannot be a /// DIB section bitmap, which is created by the CreateDIBSection function. /// </para> /// <para>If <c>lbStyle</c> is BS_SOLID or BS_HOLLOW, <c>lbHatch</c> is ignored.</para> /// </summary> [FieldOffset(8)] public HatchStyle lbHatchStyle; /// <summary> /// <para>A hatch style. The meaning depends on the brush style defined by <c>lbStyle</c>.</para> /// <para> /// If <c>lbStyle</c> is BS_DIBPATTERN, the <c>lbHatch</c> member contains a handle to a packed DIB. To obtain this handle, an /// application calls the GlobalAlloc function with GMEM_MOVEABLE (or LocalAlloc with LMEM_MOVEABLE) to allocate a block of /// memory and then fills the memory with the packed DIB. A packed DIB consists of a BITMAPINFO structure immediately followed by /// the array of bytes that define the pixels of the bitmap. /// </para> /// <para> /// If <c>lbStyle</c> is BS_DIBPATTERNPT, the <c>lbHatch</c> member contains a pointer to a packed DIB. The pointer derives from /// the memory block created by LocalAlloc with LMEM_FIXED set or by GlobalAlloc with GMEM_FIXED set, or it is the pointer /// returned by a call like LocalLock (handle_to_the_dib). A packed DIB consists of a BITMAPINFO structure immediately followed /// by the array of bytes that define the pixels of the bitmap. /// </para> /// <para> /// If <c>lbStyle</c> is BS_HATCHED, the <c>lbHatch</c> member specifies the orientation of the lines used to create the hatch. /// It can be one of the following values. /// </para> /// <list type="table"> /// <listheader> /// <term>Value</term> /// <term>Meaning</term> /// </listheader> /// <item> /// <term>HS_BDIAGONAL</term> /// <term>A 45-degree upward, left-to-right hatch</term> /// </item> /// <item> /// <term>HS_CROSS</term> /// <term>Horizontal and vertical cross-hatch</term> /// </item> /// <item> /// <term>HS_DIAGCROSS</term> /// <term>45-degree crosshatch</term> /// </item> /// <item> /// <term>HS_FDIAGONAL</term> /// <term>A 45-degree downward, left-to-right hatch</term> /// </item> /// <item> /// <term>HS_HORIZONTAL</term> /// <term>Horizontal hatch</term> /// </item> /// <item> /// <term>HS_VERTICAL</term> /// <term>Vertical hatch</term> /// </item> /// </list> /// <para> /// If <c>lbStyle</c> is BS_PATTERN, <c>lbHatch</c> is a handle to the bitmap that defines the pattern. The bitmap cannot be a /// DIB section bitmap, which is created by the CreateDIBSection function. /// </para> /// <para>If <c>lbStyle</c> is BS_SOLID or BS_HOLLOW, <c>lbHatch</c> is ignored.</para> /// </summary> [FieldOffset(8)] public IntPtr lbHatch; } } }
be51771009c0b1eaafdaafa7f46300a95645df9b
C#
rangermattos/remnants
/Remnants/Models/Effects/Line.cs
2.8125
3
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Content; using System; namespace Remnants { class Line { public Vector2 A; public Vector2 B; public float Thickness; public Line() { } public Line(Vector2 a, Vector2 b, float thickness = 1) { A = a; B = b; Thickness = thickness; } public void Draw(SpriteBatch spriteBatch, Color color, Texture2D halfCircle, Texture2D lightningSegment) { Vector2 tangent = B - A; float rotation = (float)Math.Atan2(tangent.Y, tangent.X); const float ImageThickness = 8; float thicknessScale = Thickness / ImageThickness; Vector2 capOrigin = new Vector2(halfCircle.Width, halfCircle.Height / 2f); Vector2 middleOrigin = new Vector2(0, lightningSegment.Height / 2f); Vector2 middleScale = new Vector2(tangent.Length() / 10, thicknessScale); spriteBatch.Draw(lightningSegment, A, null, color, rotation, middleOrigin, middleScale, SpriteEffects.None, 0f); spriteBatch.Draw(halfCircle, A, null, color, rotation, capOrigin, thicknessScale, SpriteEffects.None, 0f); spriteBatch.Draw(halfCircle, B, null, color, rotation + MathHelper.Pi, capOrigin, thicknessScale, SpriteEffects.None, 0f); } } }
9edc397de05a7d8682c6cf2a265428a65811a9ac
C#
Tgsngl/ClassMetotDemo
/ClassMetotDemo/Program.cs
3.234375
3
using System; namespace ClassMetotDemo { class Program { static void Main(string[] args) { Musteri customer1 = new Musteri(); customer1.Name = "Ali"; customer1.Surname = "Veli"; customer1.Id = 2132; Musteri customer2 = new Musteri(); customer2.Name = "Ahmet"; customer2.Surname = "Mehmet"; customer2.Id = 2132; Musteri customer3 = new Musteri(); customer3.Name = "Ayşe"; customer3.Surname = "Tuğba"; customer3.Id = 2132; Musteri[] musteriler = new Musteri[] {customer1, customer2, customer3}; MusteriManager islem = new MusteriManager(); Console.WriteLine(" ******Müşteri ekleme bölümü******\n"); islem.Ekle(customer2); Console.WriteLine("******Müşteri Silme bölümü******\n"); islem.Sil(customer3); Musteri[] liste = new Musteri[] { customer1, customer2, customer3 }; Console.WriteLine("******Listeleme Bölümü*****\n"); islem.Listele(liste); Console.WriteLine("*****Müşteri bilgileri ekleme bölümü******\n"); foreach (var x in musteriler) { Console.WriteLine(x.Name+" "+ x.Surname + "\n" +x.Id+ "\n"); } Console.ReadLine(); } } }
1a381df8c0b3a1798c922de02c614488cc458947
C#
TrevorMare/Interviews
/Ozow/src/StringSorter/ArrayLibrarySorter.cs
3.234375
3
using System; using System.Linq; namespace StringSorter { public class ArrayLibrarySorter : Interfaces.ISortingAlgorithm { public string SortingName => "Array Library"; public string ApplySort(string input) { if (string.IsNullOrEmpty(input)) { return string.Empty; } var inputArray = input.ToCharArray(); Array.Sort<char>(inputArray); return string.Concat(inputArray); } } }
f4ce3e7598d10c4c3ddb9530a2f523f360b0a6cb
C#
andreharak/MyImdb
/MyImdbLibrary/MovieCountry.cs
2.640625
3
using System; using SQLite; namespace MyImdbLibrary { [Table("MovieCountry")] public class MovieCountry { [PrimaryKey, AutoIncrement, Column("Id")] public int Id { get; set; } [MaxLength(8)] public int Movie { get; set; } public int Country { get; set; } public MovieCountry() { } public MovieCountry(int movie_id, int country_id) { Movie = movie_id; Country = country_id; } } }
2a9069253faa891ea8b6cbaa99530b5bf4e4a6e7
C#
roysbailey/Selenium.Helpers
/TestFramework/POM/HomePage.cs
2.734375
3
using OpenQA.Selenium; using OpenQA.Selenium.Support.PageObjects; using System; using System.Threading; namespace WebSitePOM.POM { public class HomePage { static string reltativePath = "sut\\home.html"; private static string PageTitle = "Home Page"; [FindsBy(How = How.LinkText, Using = "Sign Out")] private IWebElement signOutLink; public void Goto() { string convertedUri = Utils.FolderUtils.GetPathAsLocalFileUri(reltativePath); Browser.Goto(convertedUri); } public bool IsAt() { var timeout = 1; bool match = false; while (!match && timeout < 5) { match = Browser.Title == PageTitle; Thread.Sleep(200); timeout++; } return match; } public void SignOut() { signOutLink.Click(); } } }
e005ad4d7ad5e78eb18010495d6fdbda01e9471c
C#
m1771vw/MyCodeFights
/CodeFights/TestCode/MatrixElementsSumClass.cs
3.546875
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CodeFights { public class MatrixElementsSumClass { public int matrixElementsSum(int [][] matrix) { var totalCount = 0; for (int y = 0; y < matrix[0].Length; y++) { for (int x = 0; x < matrix.Length; x++) { if (matrix[x][y] == 0) break; else totalCount += matrix[x][y]; } } return totalCount; } public int matrixElementsSum2(int[][] matrix) { var totalCounter = 0; for (int x = 0; x < matrix.Length; x++) { for (int y = 0; y < matrix[x].Length; y++) { Console.WriteLine(@"Checking Matrix[" + x + "][" + y + "] : " + matrix[x][y]); if (matrix[x][y] == 0) { for (int i = x; i < matrix.Length; i++) { Console.WriteLine(@"Found Matrix[" + i + "][" + y + "]: " + matrix[i][y]); matrix[i][y] = 0; Console.WriteLine(@"Changed Matrix["+i+"]["+y+"]: " + matrix[i][y]); } } else { totalCounter += matrix[x][y]; } } } return totalCounter; } } }
222134f88141c1defa69188ea6c3c5747b19e39a
C#
idotnet/MvcDemo
/MvcViewApp/Controllers/HomeController.cs
2.53125
3
using MvcViewApp.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MvcViewApp.Controllers { public class HomeController : Controller { // GET: Home public ActionResult Index() { /* 弱类型:ViewData[""] 动态型:ViewBag //dynamic 强类型:Model 临时存储:TempData[""] 后台:return View(data); // 存入 ViewData.Model 前台:Model //其实就是 WebViewPage.Model */ ViewData["One"] = "天机老人孙老头"; ViewBag.Two = "子母龙凤环上官金虹"; var user = new User { Name = "下李飞刀李寻欢" }; TempData["Four"] = "嵩阳铁剑郭嵩阳"; return View(user); //ViewData.Model = user; } } }
4149c0ccf353cb9daa15f800f204eb1daece44c9
C#
samkim91/Algorithm
/Algorithm/DivisibleSumPairs.cs
3.421875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Algorithm { class DivisibleSumPairs { public int divisibleSumPairs(int n, int k, int [] ar) { int result = 0; for (int i = 0; i < n - 1; i++) { for (int j = 1; j < n - i; j++) { if( (ar[i] + ar[i+j]) % k == 0) { result++; } } } return result; } } }
aa0ba6ac3027165a91262d138a47930612c9b50c
C#
BartSiwek/GALibrary
/TestApp/MuPlusLambdaTester.cs
2.875
3
using System; using System.Collections.Generic; using System.Text; using GALibrary.Common; using GALibrary.Evolutionary; using GALibrary.Evolutionary.Chromsomes; using GALibrary.Evolutionary.Operations; using GALibrary.Evolutionary.MuPlusLambda; namespace TestApp { class MuPlusLambdaJudgeClass : IOneChromosomeJudge<DoubleRealNumberChromosome> { #region IOneChromosomeJudge<T> Members public void Judge(DoubleRealNumberChromosome chromosome) { double value = AckleyFunction.GetValue(chromosome.Values); if (double.IsNaN(value)) chromosome.SetValueAndFitness(24.9999, 0.0001); else chromosome.SetValueAndFitness(value, 25 - value); } public void Initialize() { } #endregion } class MuPlusLambdaTester { private DoubleRealNumberChromosome best = null; private void OnIterationComeplete(object sender, EventArgs e) { //Get the args MuPlusLambdaStrategy<DoubleRealNumberChromosome> ga = (MuPlusLambdaStrategy<DoubleRealNumberChromosome>)sender; IterationalGAStrategyEventArgs iterE = (IterationalGAStrategyEventArgs)e; //Find the max int max = 0; for (int i = 1; i < ga.Population.Length; i++) if (ga.Population[i].Fitness > ga.Population[max].Fitness) max = i; //Renember the max if (best == null) best = (DoubleRealNumberChromosome)ga.Population[max].Clone(); else { if (best.Fitness < ga.Population[max].Fitness) best = (DoubleRealNumberChromosome)ga.Population[max].Clone(); } //Display the info if (iterE.Iteration % 500 == 0) { Console.WriteLine("Best at {0}: {1} ({2})", iterE.Iteration, best.Value, best.Fitness); } } public void Run() { Console.WriteLine("MuPlusLambda #1 (LocalAverage)"); best = null; //Create the strategy MuPlusLambdaStrategy<DoubleRealNumberChromosome> ga1 = new MuPlusLambdaStrategy<DoubleRealNumberChromosome>(1000, 500); //Assign a generator ga1.ChromosomeGenerator = new DoubleRealNumberChromosomeGenerator(AckleyFunction.Dimentions, -30, 30, 60); //Assign a crossover ga1.CrossoverStrategy = new LocalAverageCrossover(); //Assign a judge ga1.JudgeStrategy = new AutonomousJudgeStrategy<DoubleRealNumberChromosome>( new MuPlusLambdaJudgeClass() ); //Assign a mutation ga1.MutationStrategy = new OneChromosomeMutationStrategy<DoubleRealNumberChromosome>( new EvolutionaryMutation() ); //Assign a selection ga1.SelectionStrategy = new ProportionalSelectionStrategy<DoubleRealNumberChromosome>(); //Assign a stop condition ga1.StopCondition = new IterationNumberStopCondition(2500); //Subscribe to a event ga1.ReportProgress += OnIterationComeplete; ga1.Run(); //Print result Console.WriteLine("MuPlusLambda Best: {0}", best.Value); Console.WriteLine("MuPlusLambda #2 (LocalDiscrete)"); best = null; //Create the strategy MuPlusLambdaStrategy<DoubleRealNumberChromosome> ga2 = new MuPlusLambdaStrategy<DoubleRealNumberChromosome>(1000, 500); //Assign a generator ga2.ChromosomeGenerator = new DoubleRealNumberChromosomeGenerator(AckleyFunction.Dimentions, -30, 30, 60); //Assign a crossover ga2.CrossoverStrategy = new LocalDiscreteCrossover(); //Assign a judge ga2.JudgeStrategy = new AutonomousJudgeStrategy<DoubleRealNumberChromosome>( new MuPlusLambdaJudgeClass() ); //Assign a mutation ga2.MutationStrategy = new OneChromosomeMutationStrategy<DoubleRealNumberChromosome>( new EvolutionaryMutation() ); //Assign a selection ga2.SelectionStrategy = new ProportionalSelectionStrategy<DoubleRealNumberChromosome>(); //Assign a stop condition ga2.StopCondition = new IterationNumberStopCondition(2500); //Subscribe to a event ga2.ReportProgress += OnIterationComeplete; ga2.Run(); //Print result Console.WriteLine("MuPlusLambda Best: {0}", best.Value); Console.WriteLine("MuPlusLambda #3 (GlobalAverage)"); best = null; //Create the strategy MuPlusLambdaStrategy<DoubleRealNumberChromosome> ga3 = new MuPlusLambdaStrategy<DoubleRealNumberChromosome>(1000, 500); //Assign a generator ga3.ChromosomeGenerator = new DoubleRealNumberChromosomeGenerator(AckleyFunction.Dimentions, -30, 30, 60); //Assign a crossover ga3.CrossoverStrategy = new GlobalAverageCrossover(AckleyFunction.Dimentions); //Assign a judge ga3.JudgeStrategy = new AutonomousJudgeStrategy<DoubleRealNumberChromosome>( new MuPlusLambdaJudgeClass() ); //Assign a mutation ga3.MutationStrategy = new OneChromosomeMutationStrategy<DoubleRealNumberChromosome>( new EvolutionaryMutation() ); //Assign a selection ga3.SelectionStrategy = new ProportionalSelectionStrategy<DoubleRealNumberChromosome>(); //Assign a stop condition ga3.StopCondition = new IterationNumberStopCondition(2500); //Subscribe to a event ga3.ReportProgress += OnIterationComeplete; ga3.Run(); //Print result Console.WriteLine("MuPlusLambda Best: {0}", best.Value); Console.WriteLine("MuPlusLambda #4 (GlobalDiscrete)"); best = null; //Create the strategy MuPlusLambdaStrategy<DoubleRealNumberChromosome> ga4 = new MuPlusLambdaStrategy<DoubleRealNumberChromosome>(1000, 500); //Assign a generator ga4.ChromosomeGenerator = new DoubleRealNumberChromosomeGenerator(AckleyFunction.Dimentions, -30, 30, 60); //Assign a crossover ga4.CrossoverStrategy = new GlobalDiscreteCrossover(AckleyFunction.Dimentions); //Assign a judge ga4.JudgeStrategy = new AutonomousJudgeStrategy<DoubleRealNumberChromosome>( new MuPlusLambdaJudgeClass() ); //Assign a mutation ga4.MutationStrategy = new OneChromosomeMutationStrategy<DoubleRealNumberChromosome>( new EvolutionaryMutation() ); //Assign a selection ga4.SelectionStrategy = new ProportionalSelectionStrategy<DoubleRealNumberChromosome>(); //Assign a stop condition ga4.StopCondition = new IterationNumberStopCondition(2500); //Subscribe to a event ga4.ReportProgress += OnIterationComeplete; ga4.Run(); //Print result Console.WriteLine("MuPlusLambda Best: {0}", best.Value); } } }
b6a38f5b494bfab47a31cb2481f66e2ddf94eb10
C#
Trevorton27/brendonBattleShipApp
/BattleShip/GameBoard.cs
3.234375
3
using System; using System.Collections.Generic; using System.Linq; namespace BattleShip { class GameBoard { private List<Coordinate> AllCoordinates { get; set; } = new List<Coordinate>(); public int ShipHealth { get; set; } public void DrawGameBoard (bool isPeek = false) { List<string> Rows = BuildRows(); Console.Clear(); Console.WriteLine(" Battle Ship "); Console.WriteLine(" "); Console.WriteLine(" A B C D E F G H I J "); Console.WriteLine(" |=======================|"); foreach (var row in Rows) Console.WriteLine(row); Console.WriteLine(" |=======================|"); Console.WriteLine(); UpdateHealth(isPeek); Console.WriteLine($" Ship Health: {ShipHealth}"); if (ShipHealth == 0) Console.WriteLine(" SHIP SUNK!!! YOU WIN!!!"); } private List<string> BuildRows () { List<string> Rows = new(); var line = ""; for (int i = 0; i < 10; i++) { line = ""; if ((i + 1).ToString().Length == 1) line += $" {i + 1}||"; else line += $"{i + 1}||"; for (int j = 0; j < 10; j++) { var matchingCoordinate = AllCoordinates.Where(c => c.Column == j && c.Row == i).Single(); var character = ChooseDisplayCharacter(matchingCoordinate.IsShip, matchingCoordinate.IsVisible); line += $" {character}"; } line += " ||"; Rows.Add(line); } return Rows; } public void InitializeShip() { Random rnd = new(); var randomColumn = rnd.Next(0, 9); var randomRow = rnd.Next(0, 9); int randomStart = rnd.Next(1, 4); bool isStop = false; while (!isStop) { switch (randomStart) { case 1: if (randomColumn + 4 < 10) { foreach (var coordinate in AllCoordinates) if (coordinate.Row == randomRow && (coordinate.Column >= randomColumn && coordinate.Column <= randomColumn + 4)) coordinate.IsShip = true; isStop = true; } break; case 2: if (randomColumn - 4 >= 0) { foreach (var coordinate in AllCoordinates) if (coordinate.Row == randomRow && (coordinate.Column >= randomColumn -4 && coordinate.Column <= randomColumn )) coordinate.IsShip = true; isStop = true; } break; case 3: if (randomRow + 4 < 10) { foreach (var coordinate in AllCoordinates) if (coordinate.Column == randomColumn && (coordinate.Row >= randomRow && coordinate.Row <= randomRow + 4)) coordinate.IsShip = true; isStop = true; } break; case 4: if (randomRow - 4 >= 0) { foreach (var coordinate in AllCoordinates) if (coordinate.Column == randomColumn && (coordinate.Row >= randomRow - 4 && coordinate.Row <= randomRow )) coordinate.IsShip = true; isStop = true; } break; default: break; } if (randomStart == 4) randomStart = 0; randomStart++; } } public void InitializeCoordinates() { for (int i = 0; i < 10; i++) for (int j = 0; j < 10; j++) AllCoordinates.Add(new Coordinate(i, j)); } private void UpdateHealth(bool isPeek) { if (!isPeek) { int count = 0; foreach (var coordinate in AllCoordinates) if (coordinate.IsShip && !coordinate.IsVisible) count++; ShipHealth = count; } } private static string ChooseDisplayCharacter (bool isShip, bool isVisible) { string result; if (!isVisible) result = "-"; else { if(isShip) result = "X"; else result = "O"; } return result; } public int ChangeLetterToNumber (string input) { List<string> Columns = new() { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J" }; try { return Columns.IndexOf(input); } catch (Exception) { return 20; } } public void ToggleIsVisible(int column, int row) { var matchingCoordinate = AllCoordinates.Where(c => c.Column == column && c.Row == row).Single(); matchingCoordinate.IsVisible = true; } public void ShowShipTimer(int time) { foreach (var coordinate in AllCoordinates) { if (coordinate.IsShip) coordinate.IsVisible = true; } DrawGameBoard(true); System.Threading.Thread.Sleep(time); foreach (var coordinate in AllCoordinates) { if (coordinate.IsShip && !coordinate.IsGuessed) coordinate.IsVisible = false; } DrawGameBoard(true); } public void ShowShipPermanent() { foreach (var coordinate in AllCoordinates) if (coordinate.IsShip == true) coordinate.IsVisible = true; DrawGameBoard(true); } public void ToggleIsGuessed (int column, int row) { var matchingCoordinate = AllCoordinates.Where(c => c.Column == column && c.Row == row).Single(); matchingCoordinate.IsGuessed = true; } public bool CheckIsGuessed (int column, int row) { bool result = false; foreach (var coordinate in AllCoordinates) if (coordinate.Column == column && coordinate.Row == row && coordinate.IsGuessed) result = true; return result; } } }
05eea4cdd05c0a942f8f45fc476dcc63a133807d
C#
vasudhapuri/OOPS
/SettingFieldsWhielCreatingObjects/Program.cs
3.453125
3
using System; namespace SettingFieldsWhielCreatingObjects { class Program { String model; int year; String color; static void Main(string[] args) { Program p = new Program(); p.model = "Merc"; p.year = 1988; p.color = "black"; Program p2 = new Program(); p2.model = "Volvo"; p2.year = 1994; p2.color = "Silver"; Console.WriteLine(p.model); Console.WriteLine(p2.model); Console.WriteLine(p.year); Console.WriteLine(p2.year); } } }
4c7e800d636b3397797d0fa7d23bba5c1d88e412
C#
outase/taws
/tawsLibrary/FileIo.cs
2.6875
3
using System; using System.Collections.Generic; using System.Configuration; using System.IO; using System.Linq; using System.Text; using System.Web; using tawsCommons.mvc; namespace tawsLibrary { public class FileIo { //エビデンス用のディレクトリ作成 public string CreateEvidencesDirectory(ITestPropertyModelBase prop) { var evidenceSaveDir = $@"{ConfigurationManager.AppSettings["SaveFileRootPath"]}{ prop.testBrowser }_{ prop.testDevice }_{ prop.testDateTime }"; var evidenceSavePath = evidenceSaveDir + @"\"; if (!Directory.Exists(evidenceSaveDir)) { Directory.CreateDirectory(evidenceSaveDir); } return evidenceSavePath; } //テストケース保存 public string SaveTestCaseFiles(HttpPostedFileWrapper testCaseFile, string testDateTime) { if (testCaseFile != null) { var uploadFileSaveDir = $@"{ConfigurationManager.AppSettings["UploadFileRootPath"]}\{ testDateTime }"; var uploadFileSavePath = uploadFileSaveDir + @"\"; //ディレクトリ作成 if (!Directory.Exists(uploadFileSaveDir)) { Directory.CreateDirectory(uploadFileSaveDir); } //ファイル保存 testCaseFile.SaveAs(uploadFileSavePath + Path.GetFileName(testCaseFile.FileName)); return uploadFileSavePath; } return null; } public const string ELEM_NO = "elem_no"; public const string ELEM_NAME = "elem_name"; public const string SEND_KEY = "send_key"; public const string SLEEP_TIME = "sleep_time"; public List<Dictionary<string, string>> TestCaseFromUploadFile(string uploadFileSavePath, HttpPostedFileWrapper testCaseFile) { var testElemList = new List<Dictionary<string, string>>(); var csvFilePath = uploadFileSavePath + testCaseFile.FileName; StreamReader reader = new StreamReader(csvFilePath, Encoding.GetEncoding("Shift_JIS")); reader.ReadLine(); //タイトルを読み飛ばす while (reader.Peek() >= 0) { string[] cols = reader.ReadLine().Split(','); // 項目分繰り返す for (int i = 0; i < cols.Length; ++i) { //先頭のスペースを除去して、(")ダブルクォーテーションが入っていないか判定する if (cols[i] != string.Empty && cols[i].TrimStart()[0] == '"') { cols[i] = cols[i].Replace("\"", "").Trim(); } //先頭のスペースを除去して、(')クォーテーションが入っていないか判定する else if (cols[i] != string.Empty && cols[i].TrimStart()[0] == '\'') { cols[i] = cols[i].Replace("'", "").Trim(); } } //テストケースを格納する testElemList.Add(new Dictionary<string, string>() { { ELEM_NO, $"{ cols[0] }" }, { ELEM_NAME, $"{ cols[1] }" }, { SEND_KEY, $"{ cols[2] }" }, { SLEEP_TIME, $"{ cols[3] }" } }); } reader.Close(); //uploadしたファイルをフォルダごと削除 Directory.Delete(uploadFileSavePath.Substring(0, uploadFileSavePath.Length - 1), true); return testElemList; } } }
46ffa4068bac3d8c5da0a1697f2dd7cf9f2bd666
C#
khats/Coffee
/Coffee.Shared/Extenders.cs
2.984375
3
namespace Coffee.Shared { using System; using System.IO; using System.Runtime.Serialization.Formatters.Binary; public static class Extenders { public static byte[] ToByteArray(this object a, bool failIfNull = true) { if (a == null) { if (failIfNull) { throw new ArgumentNullException("a"); } return null; } using (var ms = new MemoryStream()) { new BinaryFormatter().Serialize(ms, a); return ms.ToArray(); } } public static object AsObject(this byte[] a) { if (a == null) { throw new ArgumentNullException("a"); } using (var ms = new MemoryStream()) { ms.Write(a, 0, a.Length); ms.Position = 0; return new BinaryFormatter().Deserialize(ms); } } } }
98ab204cbd9679972c3d77b6153f9fb81b6fd41e
C#
legoli/Diancan
/GeneralCode/Base64Convertor.cs
2.953125
3
using System; using System.Collections.Generic; using System.IO; using System.Text; namespace GeneralCode { public class Base64Convertor { public static String convertToBase64(byte[] buffer) { String strRet = ""; if (null == buffer) return ""; try { strRet = Convert.ToBase64String(buffer); } catch (Exception exp) { Console.WriteLine(exp.Message); strRet = ""; } return strRet; } public static String convertToBase64(MemoryStream stream) { if (null == stream) return ""; //如果用buffer=stream.GetBuffer()提示错误 long bufferSize = stream.Length; byte[] buffer = new byte[bufferSize + 100]; //从stream中读出字节并写入到buffer中 stream.Read(buffer, 0, buffer.Length); return convertToBase64(buffer); } public static byte[] regainByteBuffer(String base64Cluster) { byte[] buffer = null; if (CSTR.isEmpty(base64Cluster)) return null; try { buffer = Convert.FromBase64String(base64Cluster); } catch (Exception exp) { Console.WriteLine(exp.Message); buffer = null; } return buffer; } } }
7a15904c1cf17164e30b896884f717c0a8aefce0
C#
JTOne123/Yozian.Extension
/src/Yozian.Extension.Test/ICollectionExtensionTest.cs
2.71875
3
using System.Collections.Generic; using NUnit.Framework; namespace Yozian.Extension.Test { public class ICollectionExtensionTest { [SetUp] public void Setup() { } [TestCase()] public void Test_AddWhen() { var collection = new List<int>() { 1, 2, 3 }; collection.AddWhen(false, 4); Assert.AreEqual(3, collection.Count); collection.AddWhen(true, 4); Assert.AreEqual(4, collection.Count); } [TestCase()] public void RemoveWhen() { var collection = new List<int>() { 1, 2, 3 }; collection.RemoveWhen(false, 1); Assert.AreEqual(3, collection.Count); collection.RemoveWhen(true, 1); Assert.AreEqual(2, collection.Count); } } }
8059ddfc8dc40fc6697b656f496c48a27e232ef7
C#
AntonFechin/zipper
/zipper/Program.cs
3.125
3
using System; namespace zipper { class Program { static void Main(string[] args) { try { StartProgram(args); } catch (Exception ex) { Console.WriteLine("There was an error \"{0}\"", ex.Message); Console.WriteLine("Do you want to try again? y/n"); if (Console.ReadKey().KeyChar == 'y' || Console.ReadKey().KeyChar == 'Y') { StartProgram(new string[0]); } } } private static void StartProgram(string[] args) { var consoleManager = args?.Length == 0 ? new ConsoleManager() : new ConsoleManager(args); var zipManager = ManagerFactry.CreateZipManager(consoleManager.CompressionMode, consoleManager.InputFileName, consoleManager.OutputFileName); zipManager.Run(); Console.WriteLine("File was seccessfully {0}ed, enter any button to exit", consoleManager.CompressionMode.ToString().ToLower()); Console.ReadLine(); } } }
d657ad3a94f19452a930bda070969959efae376b
C#
CreateLab/vk
/VkNet/Enums/SafetyEnums/ScheduleWorkInfoStatus.cs
2.53125
3
using System; using VkNet.Utils; namespace VkNet.Enums.SafetyEnums { /// <summary> /// Тип расписания. /// </summary> [Serializable] public class ScheduleWorkInfoStatus : SafetyEnum<ScheduleWorkInfoStatus> { /// <summary> /// Нет информации о расписании /// </summary> [DefaultValue] public static readonly ScheduleWorkInfoStatus NoInformation = RegisterPossibleValue("no_information"); /// <summary> /// Открыто круглосуточно /// </summary> public static readonly ScheduleWorkInfoStatus AlwaysOpened = RegisterPossibleValue("always_opened"); /// <summary> /// закрыто навсегда /// </summary> public static readonly ScheduleWorkInfoStatus ForeverClosed = RegisterPossibleValue("forever_closed"); /// <summary> /// Открыто в указанные часы работы. /// </summary> public static readonly ScheduleWorkInfoStatus Timetable = RegisterPossibleValue("timetable"); } }
d9bd69fcb94dd4535e4e11b907cc57b9dd164870
C#
CoserL/Remember
/RememberMyPass/Classes/PasswordDB.cs
3.140625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RememberMyPass.Classes { class PasswordDB { private static DataBase getDataBase() { DataBase db = new DataBase(); if (db.DatabaseExists() == false) { db.CreateDatabase(); } return db; } //Consulta public static List<Passwords> GetPass() { DataBase db = getDataBase(); var query = from p in db.Passwords orderby p.idPass select p; List<Passwords> pw = new List<Passwords>(query.AsEnumerable()); return pw; } //Salva public static void SalvarPW(Passwords pw) { DataBase db = getDataBase(); db.Passwords.InsertOnSubmit(pw); db.SubmitChanges(); } //Deletar public static void DeletarPW(Passwords pw) { DataBase db = getDataBase(); var query = from p in db.Passwords where p.idPass == pw.idPass select p; db.Passwords.DeleteOnSubmit(query.ToList()[0]); db.SubmitChanges(); } } }
8a2d0f76364f0c5325ee9116c845393ad1a02f64
C#
shendongnian/download4
/code5/810051-19888315-51149479-2.cs
2.625
3
protected void Button1_Click1(object sender, EventArgs e) { // Session["Fruitname"] = TbxName.Text; // my session i have made MyFruit = Session["Fruitname"] as List<string>; //Create new, if null if (MyFruit == null) MyFruit = new List<string>(); MyFruit.Add(TbxName.Text); Session["Fruitname"] = MyFruit; { public List<string> MyFruit { get; set; } }
7d594b0be8eeebae9e00181b53174ab37ac63518
C#
shiiifuuuu/bitm_dot_net
/Day10/Assignment8/Assignment6/Repository/ItemRepository.cs
3.140625
3
using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; using Assignment6.MODEL; namespace Assignment6.REPOSITORY { public class ItemRepository { private SqlConnection sqlConnection; public ItemRepository() { //Database Connection String connectionString = @"Server=PC-301-21\SQLEXPRESS; Database=CoffeeShopCRUD; Integrated Security=True"; sqlConnection = new SqlConnection(connectionString); } public bool AddItem(Item _item) { bool isAdded = false; try { String commandString = @"INSERT INTO Items (Name, Price) VALUES ('" + _item.Name + "', '" + _item.Price + "')"; SqlCommand sqlCommand = new SqlCommand(commandString, sqlConnection); sqlConnection.Open(); int queryCheck = sqlCommand.ExecuteNonQuery(); if (queryCheck > 0) { isAdded = true; } sqlConnection.Close(); } catch { } return isAdded; } public bool IsItemExist(Item _item) { bool isItemExist = false; try { String commandString = @"SELECT * FROM Items WHERE Name LIKE '" + _item.Name + "'"; SqlCommand sqlCommand = new SqlCommand(commandString, sqlConnection); sqlConnection.Open(); SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand); DataTable dataTable = new DataTable(); sqlDataAdapter.Fill(dataTable); if (dataTable.Rows.Count > 0) { isItemExist = true; } sqlConnection.Close(); } catch { } return isItemExist; } public DataTable SearchItem(Item _item) { DataTable dataTable = new DataTable(); bool searchSuccess = false; try { String commandString = @"SELECT * FROM Items WHERE Name LIKE '" + _item.Name + "%'"; SqlCommand sqlCommand = new SqlCommand(commandString, sqlConnection); sqlConnection.Open(); SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand); sqlDataAdapter.Fill(dataTable); searchSuccess = true; sqlConnection.Close(); } catch { } if (searchSuccess) { return dataTable; } else { dataTable = null; return dataTable; } } public bool DeleteItem(Item _item) { bool isDeleted = false; try { String commandString = @"DELETE FROM Items WHERE Id = '" + _item.ID + "'"; SqlCommand sqlCommand = new SqlCommand(commandString, sqlConnection); sqlConnection.Open(); int queryCheck = sqlCommand.ExecuteNonQuery(); if (queryCheck > 0) { isDeleted = true; } sqlConnection.Close(); } catch { } return isDeleted; } public DataTable ShowData() { DataTable dataTable = new DataTable(); bool trySuccess = false; try { String commandString = @"SELECT * FROM Items"; SqlCommand sqlCommand = new SqlCommand(commandString, sqlConnection); sqlConnection.Open(); SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand); sqlDataAdapter.Fill(dataTable); trySuccess = true; sqlConnection.Close(); } catch { } if (trySuccess) { return dataTable; } else { dataTable = null; return dataTable; } } public bool UpdateItem(Item _item) { bool isUpdated = false; try { String commandString = @"UPDATE ITEMS SET Name = '" + _item.Name + "', " + "Price = " + _item.Price + " " + "WHERE Id = '" + _item.ID + "' "; SqlCommand sqlCommand = new SqlCommand(commandString, sqlConnection); sqlConnection.Open(); if (sqlCommand.ExecuteNonQuery() > 0) { isUpdated = true; } sqlConnection.Close(); } catch { } return isUpdated; } } }
f86f1a1ca2d6940fd17a031eb81a05ccb56d3b25
C#
rcolzani/SmartSchoolWebAPI
/SmartSchool.API/Data/Repository.cs
2.875
3
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using SmartSchool.API.Helpers; using SmartSchool.API.Models; namespace SmartSchool.API.Data { public class Repository : IRepository { private readonly SmartContext _context; public Repository(SmartContext context) { _context = context; } public void Add<T>(T entity) where T : class { _context.Add(entity); } public void Remove<T>(T entity) where T : class { _context.Remove(entity); } public void Update<T>(T entity) where T : class { _context.Update(entity); } public bool SaveChanges() { return (_context.SaveChanges() > 0); } public async Task<User> GetUser(string userName, string userPassword) { IQueryable<User> query = _context.Users; query = query.Where(u => u.Username.ToLower() == userName.ToLower() && u.Password == userPassword); return await query.FirstOrDefaultAsync(); } public Aluno[] GetAllAlunos(bool includeProfessor = false) { IQueryable<Aluno> query = _context.Alunos; if (includeProfessor) { query = query.Include(a => a.AlunosDisciplinas) .ThenInclude(ad => ad.Disciplina) .ThenInclude(p => p.Professor); } query = query.AsNoTracking() .OrderBy(a => a.Id); return query.ToArray(); } public async Task<PageList<Aluno>> GetAllAlunosAsync( PageParams pageParams, bool includeProfessor = false) { IQueryable<Aluno> query = _context.Alunos; if (includeProfessor) { query = query.Include(a => a.AlunosDisciplinas) .ThenInclude(ad => ad.Disciplina) .ThenInclude(p => p.Professor); } query = query.AsNoTracking() .OrderBy(a => a.Id); if (!string.IsNullOrEmpty(pageParams.Nome)) { query = query.Where(aluno => aluno.Nome.ToUpper().Contains(pageParams.Nome.ToUpper()) || aluno.Sobrenome.ToUpper().Contains(pageParams.Nome.ToUpper())); } if (pageParams.Matricula > 0) { query = query.Where(aluno => aluno.Matricula == pageParams.Matricula); } if (pageParams != null) { query = query.Where(aluno => aluno.Ativo == (pageParams.Ativo != 0)); } return await PageList<Aluno>.CreateAsync(query, pageParams.PageNumber, pageParams.PageSize); } public Aluno[] GetAllAlunosByDisciplina(int discplinaId, bool includeProfessor = false) { IQueryable<Aluno> query = _context.Alunos; if (includeProfessor) { query = query.Include(a => a.AlunosDisciplinas) .ThenInclude(ad => ad.Disciplina) .ThenInclude(p => p.Professor); } query = query.AsNoTracking() .OrderBy(a => a.Id) .Where(aluno => aluno.AlunosDisciplinas.Any(ad => ad.DisciplinaId == discplinaId)); return query.ToArray(); } public Aluno GetAlunoById(int alunoId, bool includeProfessor = false) { IQueryable<Aluno> query = _context.Alunos; if (includeProfessor) { query = query.Include(a => a.AlunosDisciplinas) .ThenInclude(ad => ad.Disciplina) .ThenInclude(p => p.Professor); } query = query.AsNoTracking() .Where(al => al.Id == alunoId) .OrderBy(a => a.Id); return query.FirstOrDefault(); } public Aluno[] GetAlunoByName(string name, string lastname) { if (string.IsNullOrEmpty(name) == false) name = name.ToLower(); if (string.IsNullOrEmpty(lastname) == false) lastname = lastname.ToLower(); IQueryable<Aluno> query = _context.Alunos; if (string.IsNullOrEmpty(name) && string.IsNullOrEmpty(lastname)) { return new Aluno[0]; } else if (string.IsNullOrEmpty(name) == false && string.IsNullOrEmpty(lastname) == false) { query = query.Where(a => a.Nome.ToLower().Contains(name) && a.Sobrenome.ToLower().Contains(lastname)); } else if (string.IsNullOrEmpty(name) == false) { query = query.Where(a => a.Nome.ToLower().Contains(name)); } else if (string.IsNullOrEmpty(lastname) == false) { query = query.Where(a => a.Sobrenome.ToLower().Contains(lastname)); } query = query.Include(a => a.AlunosDisciplinas) .ThenInclude(ad => ad.Disciplina) .ThenInclude(p => p.Professor); query = query.AsNoTracking() .OrderBy(a => a.Id); return query.ToArray(); } public Professor[] GetAllProfessores(bool includeAlunos = false) { IQueryable<Professor> query = _context.Professores; if (includeAlunos) { query = query.Include(a => a.Disciplinas) .ThenInclude(ad => ad.AlunosDisciplinas) .ThenInclude(aluno => aluno.Aluno); } query = query.AsNoTracking() .OrderBy(a => a.Id); return query.ToArray(); } public Professor[] GetAllProfessoresByDisciplina(int discplinaId, bool includeAlunos = false) { IQueryable<Professor> query = _context.Professores; if (includeAlunos) { query = query.Include(a => a.Disciplinas) .ThenInclude(ad => ad.AlunosDisciplinas) .ThenInclude(aluno => aluno.Aluno); } query = query.AsNoTracking() .Where(prof => prof.Disciplinas.Any(ad => ad.Id == discplinaId)) .OrderBy(a => a.Id); return query.ToArray(); } public Professor GetProfessorById(int professorId) { IQueryable<Professor> query = _context.Professores; query = query.Include(a => a.Disciplinas) .ThenInclude(ad => ad.AlunosDisciplinas) .ThenInclude(aluno => aluno.Aluno); query = query.AsNoTracking() .Where(prof => prof.Id == professorId) .OrderBy(a => a.Id); return query.FirstOrDefault(); } } }
c87deae504583e0ffa7f4e7303ef5ff56236fdc9
C#
tedlasai/UserCreation
/UserCreation/Data/UserDatabase.cs
3.359375
3
/*File: UserDatabase.cs *Description: Methods to interact with user database */ using System.Collections.Generic; using System.Threading.Tasks; using SQLite; using UserCreation.Models; namespace UserCreation.Data { public class UserDatabase { //database connenction readonly SQLiteAsyncConnection _database; //constructor public UserDatabase(string dbPath) { //create database connection _database = new SQLiteAsyncConnection(dbPath); _database.CreateTableAsync<User>().Wait(); } //get users as list public Task<List<User>> GetUsersAsync() { return _database.Table<User>().ToListAsync(); } //get a single user by id public Task<User> GetUserAsync(int id) { return _database.Table<User>() .Where(i => i.Id == id) .FirstOrDefaultAsync(); } //save a user to database public Task<int> SaveUserAsync(User user) { if (user.Id != 0) { return _database.UpdateAsync(user); } else { return _database.InsertAsync(user); } } //delete user from database public Task<int> DeleteUserAsync(User user) { return _database.DeleteAsync(user); } } }
facbf418ef9fb23b816ef55c8b2ddb3412648781
C#
VincentH-Net/XamarinCommunityToolkit
/XamarinCommunityToolkit/Views/SnackBar/Options/SnackBarActionOptions.shared.cs
2.59375
3
using System; using System.Threading.Tasks; using Xamarin.Forms; namespace Xamarin.CommunityToolkit.UI.Views.Options { public class SnackBarActionOptions { /// <summary> /// Gets or sets the action for the SnackBar action button. /// </summary> public Func<Task> Action { get; set; } = DefaultAction; public static Func<Task> DefaultAction { get; set; } = null; /// <summary> /// Gets or sets the text for the SnackBar action button. /// </summary> public string Text { get; set; } = DefaultText; public static string DefaultText { get; set; } /// <summary> /// Gets or sets the font size for the SnackBar action button. /// </summary> public double FontSize { get; set; } = DefaultFontSize; public static double DefaultFontSize { get; set; } = 14; /// <summary> /// Gets or sets the font family for the SnackBar action button. /// </summary> public string FontFamily { get; set; } = DefaultFontFamily; public static string DefaultFontFamily { get; set; } = "Arial"; /// <summary> /// Gets or sets the background color for the SnackBar action button. /// </summary> public Color BackgroundColor { get; set; } = DefaultBackgroundColor; public static Color DefaultBackgroundColor { get; set; } = Color.White; /// <summary> /// Gets or sets the font color for the SnackBar action button. /// </summary> public Color ForegroundColor { get; set; } = DefaultForegroundColor; public static Color DefaultForegroundColor { get; set; } = Color.Black; } }
02ed20df3ab9f02990bd22592d300ae90908177e
C#
cryptobuks/E-CommerceSystem
/Controllers/ProductsController.cs
2.984375
3
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using BusinessLogic; using Common; namespace Assignment.Controllers { public class ProductsController : Controller { // GET: Products [HttpGet] public ActionResult ProductCatalog() { IQueryable<Product> listProducts = new ProductsBL().GetProducts(); //i am storing the list of books List<Product> listProduct = new List<Product>(); foreach (Product p in listProducts) { if (p.Available == true) { listProduct.Add(p); } } return View(listProduct); } [HttpPost] public ActionResult ProductCatalog(string input)//we have to call the method in the business logic layer { IQueryable<Product> foundProducts = new ProductsBL().GetProducts(input); List<Product> listProduct = new List<Product>(); foreach (Product p in foundProducts) { if (p.Available == true) { listProduct.Add(p); } } return View(foundProducts); //the returned list of users will he be displayed //in the same view tha was loaded in the first action } public ActionResult Details(int productId)//list details of the product { Product p= new ProductsBL().GetProduct(productId); return View(p);//you are passing the returned book which we are calling b as a parameter to the view } //so that when we click the register new book link this will be called [Authorize(Roles = "Administrator")] [HttpGet] public ActionResult Create() { return View(); } //so that the user will input the book details [Authorize(Roles = "Administrator")] [HttpPost] public ActionResult Create(Product p, HttpPostedFileBase productImage) { try { //to insert an image string absoluteFolderPath = Server.MapPath("\\ProductImages"); //in case of the assignment, productImages instead of images string extOfImage = System.IO.Path.GetExtension(productImage.FileName); //get extension string newFilename = Guid.NewGuid() + extOfImage; absoluteFolderPath += "\\" + newFilename; productImage.SaveAs(absoluteFolderPath); //in the database we store the relative path Images/filename.jpg string relativePath = "\\Images\\" + newFilename; p.Image = relativePath; new ProductsBL().AddProduct(p); //to add the book in the database ViewData["msg"] = "Success"; ModelState.Clear(); //to clear the boxes } catch { ViewData["msg"] = "Registration of product failed. Please check details."; } return View(); } [Authorize(Roles = "Administrator")] public ActionResult Delete(int productId) { new ProductsBL().DeleteProduct(productId); //to display the mose recent list of books in the dabatese return RedirectToAction("ProductCatalog"); } //getting the book with the isbn in order to edit its details [Authorize(Roles = "Administrator")] [HttpGet] public ActionResult Update(int productId) { //you must do a try catch in order to handle bad inserted data for example one must enter an integer and he enters a string Product productToEdit = new ProductsBL().GetProduct(productId); return View(productToEdit); } [Authorize(Roles = "Administrator")] [HttpPost] public ActionResult Update(Product modifiedDetails) { //you must do a try catch in order to handle bad inserted data for example one must enter an integer and he enters a string new ProductsBL().UpdateProduct(modifiedDetails); return RedirectToAction("ProductCatalog"); } } }
8bca34d3f94efcfe84dd3aa2490024f2b58478b2
C#
ViktorGorchev/C-Sharp-Fundamentals
/C# Advanced/Homework/01 Arrays, Lists, Stacks, Queues/05 LongestIncreasingSequence/LongestIncreasingSequenceMain.cs
4.03125
4
namespace _05_LongestIncreasingSequence { using System; using System.Linq; public class LongestIncreasingSequenceMain { public static void Main() { int numberLongest = 0; int bestCount = 0; int longestCount = 0; int[] inputNumbers = Console.ReadLine().Split(' ').Select(int.Parse).ToArray(); for (int i = 0; i < inputNumbers.Length - 1; i++) { var count = CountSequence(i, inputNumbers); if (count >= bestCount) { bestCount = count; int number = i; i += count - 1; PrintSequence(number, bestCount, inputNumbers); if (bestCount > longestCount) { longestCount = bestCount; numberLongest = number; } bestCount = 0; } } Console.Write("Longest: "); PrintSequence(numberLongest, longestCount, inputNumbers); } private static void PrintSequence(int number, int bestCount, int[] inputNumbers) { for (int l = number; l <= number + bestCount - 1; l++) { Console.Write("{0} ", inputNumbers[l]); } Console.WriteLine(); } private static int CountSequence(int i, int[] inputNumbers) { int count = 1; int j = i + 1; int k = i; while (inputNumbers[k] < inputNumbers[j]) { count++; j++; k++; if (j >= inputNumbers.Length) { break; } } return count; } } }
63e6e593783e3866321842afdafcb11d83f562e9
C#
NobuyukiInoue/LeetCode
/Problems/0500_0599/0551_Student_Attendance_Record1/Project_CS/Student_Attendance_Record1.cs
3.515625
4
using System; public class Solution { public bool CheckRecord(string s) { return !(s.IndexOf("A") != s.LastIndexOf("A") || s.Contains("LLL")); } public string output_str_array(string[] words) { if (words.Length <= 0) return ""; string results = words[0]; for (int i = 1; i < words.Length; ++i) { results += ", " + words[i]; } return results; } public void Main(string args) { string s = args.Replace("\"","").Replace(" ","").Replace("[","").Replace("]","").Trim(); Console.WriteLine("s = " + s); System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); sw.Start(); bool result = CheckRecord(s); Console.WriteLine("result = " + result.ToString()); sw.Stop(); Console.WriteLine("Execute time ... " + sw.ElapsedMilliseconds.ToString() + "ms\n"); } }
d5126a91357ab92bf104f688b6f31d02f136d827
C#
kosmakoff/AdventOfCode2016
/Day08/CommandParser.cs
3.453125
3
using System; namespace Day08 { public class CommandParser { public ScreenCommand Parse(string command) { if (command.StartsWith("rect")) return ParseRectCommand(command); if (command.StartsWith("rotate row")) return ParseRotateRowCommand(command); if (command.StartsWith("rotate column")) return ParseRotateColumnCommand(command); throw new NotSupportedException($"Command '{command}' not supported."); } private static ScreenCommand ParseRectCommand(string command) { var param = command.Substring(5).Split('x'); var width = int.Parse(param[0]); var height = int.Parse(param[1]); return new RectCommand(width, height); } private static ScreenCommand ParseRotateRowCommand(string command) { var param = command.Substring(11).Split(new[] {" by "}, StringSplitOptions.None); var rowNumber = int.Parse(param[0].Split('=')[1]); var count = int.Parse(param[1]); return new ShiftRowCommand(rowNumber, count); } private static ScreenCommand ParseRotateColumnCommand(string command) { var param = command.Substring(14).Split(new[] { " by " }, StringSplitOptions.None); var rowNumber = int.Parse(param[0].Split('=')[1]); var count = int.Parse(param[1]); return new ShiftColumnCommand(rowNumber, count); } } }
33db2c04ae3ef57e8331e3b8b756a3fcc2600921
C#
ideadreamDefy/Defy
/SiRenNiuNiu/Assets/Scripts/Model/Player.cs
2.578125
3
using UnityEngine; using System.Collections; using System; using System.Collections.Generic; //玩家类 public class Player { //玩家手牌 public List<Poker> poker = new List<Poker>(); public List<int> pokerValue = new List<int>(); public List<GameObject> pokerGameObject = new List<GameObject>(); public void AddPoker(Poker po){ poker.Add(po); } public void AddPokerGameObject(GameObject poGame){ pokerGameObject.Add(poGame); } public void AddPokerValue(int pokeValueNum){ pokerValue.Add(pokeValueNum); } public string getPoints(){ int []arrPokerValue = new int[global.roundMax]; string []arrPokerColor = new string[global.roundMax]; for(int i=0;i<poker.Count;i++){ arrPokerValue[i] = poker[i].pokerPoints; arrPokerColor[i] = poker[i].pokerColor; } Judge.pokerValue = arrPokerValue; Judge.pokerColor = arrPokerColor; return Judge.getPokerPoint(); } }
85a80ba4521bf7bb4ca9066f14ae2e8f5373e286
C#
josephvempala/GameServer
/Server/server/ServerHandle.cs
2.5625
3
using Shared; using System; namespace Server { internal static class ServerHandle { public static void WelcomeReceived(int client_id, Packet packet) { string username = packet.ReadString(); Console.WriteLine($"{client_id} says {username}"); Server.clients[client_id].SendIntoGame(username); } public static void MessageReceived(int client_id, Packet packet) { string message = packet.ReadString(); Console.WriteLine($"{message} from udp client {client_id}"); ServerSend.Message(client_id, message); } } }
24b5a3de692664f66d8b2b9528a858847fbe45b3
C#
THING-Lab/HapticVRWizard
/HapticVRWizard/Assets/Scripts/Tools/Tube/TubeDraw.cs
2.578125
3
using System.Collections; using System.Collections.Generic; using System.Linq; using UnityEngine; public class TubeDraw : StrokeDraw { private int _numSegments = 10; // Should match min move distance public float _meshTailLength = 0.03f; private Vector3 _prevNormal; // Connects the most recently added vertex ring to the one before it public static List<int> CreateTriRing(int segments, int vertCount) { List<int> ring = new List<int>(); for (int i = 0; i < segments; i++) { int i0 = vertCount - 1 - i; int i1 = vertCount - 1 - ((i + 1) % segments); int[] seg = { i0, i1 - segments, i0 - segments, i0, i1, i1 - segments }; ring.AddRange(seg); } return ring; } public void LoadMesh(Geometry geo) { List<Vector3> verts = new List<Vector3>(); List<int> tris = new List<int>(); List<Vector2> uvs = new List<Vector2>(); // Get relevant data List<float> positions = geo.data.attributes.position.array; List<float> oldUvs = geo.data.attributes.uvs.array; int numVerts = positions.Count / 3; for(int i = 0; i < numVerts; i++) { int offset = i * 3; Vector3 vertex = new Vector3(positions[offset], positions[offset + 1], positions[offset + 2]); Vector3 uv = new Vector2(oldUvs[i * 2], oldUvs[(i * 2) + 1]); int vectorIndex; if (verts.Contains(vertex)) { vectorIndex = verts.IndexOf(vertex); } else { verts.Add(vertex); uvs.Add(uv); vectorIndex = verts.Count - 1; } tris.Add(vectorIndex); } GenerateFrom(verts, tris, uvs); } public override void AddPoint(Vector3 point, Quaternion _, float scale) { _pointsList.Add(point); // Defaults for normal and direction Vector3 ringNormal = Vector3.zero; Vector3 direction = point; int pointIndex = _pointsList.Count - 1; // If there is only one point just create initial ring // Else do all mesh generation steps if(_pointsList.Count == 1) { AddVertexRing(pointIndex * _numSegments, point, direction, ringNormal, 0); } else { // Correct direction if more than 1 point so far direction = point - _pointsList[pointIndex - 1]; // This code is from Pinch draw and I need to comment it properly if(_pointsList.Count == 2) { float angleToUp = Vector3.Angle(direction, Vector3.up); if (angleToUp < 10 || angleToUp > 170) { ringNormal = Vector3.Cross(direction, Vector3.right); } else { ringNormal = Vector3.Cross(direction, Vector3.up); } ringNormal = ringNormal.normalized; } else { Vector3 prevPerp = Vector3.Cross(_pointsList[pointIndex - 1] - _pointsList[pointIndex - 2], _prevNormal); ringNormal = Vector3.Cross(prevPerp, point - _pointsList[pointIndex - 1]).normalized; } // End pinch draw copy paste // Clear out mesh end cap if (_pointsList.Count > 3) { _verts.RemoveRange(_verts.Count - (_numSegments), _numSegments); _uvs.RemoveRange(_uvs.Count - (_numSegments), _numSegments); _tris.RemoveRange(_tris.Count - (6 * _numSegments), 6 * _numSegments); } // Create vertex ring and Add tris AddVertexRing(pointIndex * _numSegments, point, direction, ringNormal, scale); _tris.AddRange(CreateTriRing(_numSegments, _verts.Count)); // Add mesh end cap if (_pointsList.Count > 2) { CloseMesh(); } UpdateMesh(); } _prevNormal = ringNormal; } private void AddVertexRing(int offset, Vector3 ringPosition, Vector3 direction, Vector3 normal, float radiusScale) { for (int i = 0; i < _numSegments; i++) { float angle = 360.0f * (i / (float)(_numSegments)); Quaternion rotator = Quaternion.AngleAxis(angle, direction.normalized); Vector3 ringSpoke = rotator * normal.normalized * radiusScale * 0.5f; // * _radius _verts.Add(ringPosition + ringSpoke); _uvs.Add(new Vector2(i / (_numSegments - 1.0f), 0)); // What is that stuff with Colors?!?! // _colors.Add(ColorManager.Instance.GetCurrentColor()); } } // Create closing cap for mesh // Might want to do this in a more nuanced way instead of just creating another ring public void CloseMesh() { if (_pointsList.Count > 1) { Vector3 ringNormal = Vector3.zero; Vector3 direction = _pointsList.Last() - _pointsList[_pointsList.Count - 2]; Vector3 scaledEndDelta = Vector3.Scale(direction.normalized, new Vector3(_meshTailLength, _meshTailLength, _meshTailLength)); Vector3 endPoint = _pointsList.Last() + scaledEndDelta; AddVertexRing(_pointsList.Count * _numSegments, endPoint, endPoint, ringNormal, 0); _tris.AddRange(CreateTriRing(_numSegments, _verts.Count)); UpdateMesh(); } } }
230d36def6532bb4f8e6ec9fcc76f86120bc3830
C#
simonejsing/Prerelease
/CraftingGame/ProceduralObjectManager.cs
2.703125
3
using System; using System.Collections.Generic; using System.Linq; using CraftingGame.Physics; using Terrain; using VectorMath; using Object = CraftingGame.Physics.Object; using Contracts; namespace CraftingGame { internal class ProceduralObjectGrid : ICollidableObjectGrid { private readonly Grid grid; private readonly ITerrainGenerator terrainGenerator; private readonly Plane plane; public ProceduralObjectGrid(ITerrainGenerator terrainGenerator, Grid grid, Plane plane) { this.terrainGenerator = terrainGenerator; this.grid = grid; this.plane = plane; } public ICollidableObject[] Neighbors(Object obj) { var neighbors = new ICollidableObject[9]; var centerCoord = grid.PointToGridCoordinate(obj.Center); int localIndex = 0; for (var v = centerCoord.V - 1; v <= centerCoord.V + 1; v++) { for (var u = centerCoord.U - 1; u <= centerCoord.U + 1; u++) { var coord = new Coordinate(u, v); var occupied = false; var type = terrainGenerator[coord, plane].Type; if (type == TerrainType.NotGenerated) { // Force generate terrainGenerator.Generate(coord, plane); type = terrainGenerator[coord, plane].Type; } switch (type) { case TerrainType.NotGenerated: // ??? break; case TerrainType.Free: case TerrainType.Sea: occupied = false; break; default: occupied = true; break; } neighbors[localIndex] = new Block() { Position = grid.GridCoordinateToPoint(coord), Occupied = occupied }; localIndex++; } } return neighbors; } } internal class ProceduralObjectManager : IObjectManager { public ProceduralObjectManager(ITerrainGenerator terrainGenerator, Grid grid, Plane plane) { this.Blocks = new ProceduralObjectGrid(terrainGenerator, grid, plane); } public ICollidableObjectGrid Blocks { get; } public IEnumerable<ICollidableObject> CollisionOrder => Enumerable.Empty<ICollidableObject>(); } }
19c54fb9c99f3ce778c808a9948a44078e7ed01b
C#
rougemeilland/palmtreemath
/Palmtree.Math/Implements/SubstractImplementOfUnsignedLongLongInteger.cs
2.859375
3
using System; using System.Diagnostics; namespace Palmtree.Math.Implements { internal class SubtractImplementOfUnsignedLongLongInteger : ImplementOfUnsignedLongLongIntegerBase { #region パブリックメソッド public ushort[] Subtract(ushort x, ushort y) { Debug.Assert(x > 0); Debug.Assert(y > 0); if (x < y) throw (new OverflowException("減算の結果がUnsignedLongLongIntegerで表現不可能な値になりました。")); else if (x == y) return (new ushort[0]); else return (new ushort[] { (ushort)(x - y) }); } public ushort[] Subtract(ushort[] x, ushort y) { Debug.Assert(x.Length > 0); Debug.Assert(y > 0); if (x.Length == 1) return (Subtract(x[0], y)); ushort[] z = new ushort[x.Length]; int index = 1; long carry = (uint)x[0]; carry -= (uint)y; z[0] = (ushort)carry; carry >>= 16; for (; index < x.Length; ++index) { carry += (uint)x[index]; z[index] = (ushort)carry; carry >>= 16; } Debug.Assert(carry == 0); return (Regularize(z)); } public ushort[] Subtract(ushort x, ushort[] y) { Debug.Assert(x > 0); Debug.Assert(y.Length > 0); if (y.Length == 1) return (Subtract(x, y[0])); else throw (new OverflowException("減算の結果がUnsignedLongLongIntegerで表現不可能な値になりました。")); } public ushort[] Subtract(ushort[] x, ushort[] y) { Debug.Assert(x.Length > 0); Debug.Assert(y.Length > 0); if (x.Length < y.Length) throw (new OverflowException("減算の結果がUnsignedLongLongIntegerで表現不可能な値になりました。")); if (x.Length == 1) return (Subtract(x[0], y[0])); if (y.Length == 1) return (Subtract(x, y[0])); ushort[] z = new ushort[x.Length]; int index = 1; long carry = (uint)x[0]; carry -= (uint)y[0]; z[0] = (ushort)carry; carry >>= 16; for (; index < y.Length; ++index) { carry += (uint)x[index]; carry -= (uint)y[index]; z[index] = (ushort)carry; carry >>= 16; } for (; index < x.Length; ++index) { carry += (uint)x[index]; z[index] = (ushort)carry; carry >>= 16; } if (carry != 0) throw (new OverflowException("減算の結果がUnsignedLongLongIntegerで表現不可能な値になりました。")); return (Regularize(z)); } #endregion } }
956c6881319f454519c33f867272510f3e78ae46
C#
SpinDOS/Algorithms
/AlgorithmTests/CpAlgorithmsTests/Algebra/ModularArithmetic/MontgomeryMultiplicationTests.cs
2.6875
3
using CpAlgorithms.Algebra.ModularArithmetic.MontgomeryMultiplication; using NUnit.Framework; namespace AlgorithmTests.CpAlgorithmsTests.Algebra.ModularArithmetic { public class MontgomeryMultiplicationTests { private const uint Modulo = 127; private MontgomerySpace _testSpace; [OneTimeSetUp] public void InitTestSpace() { _testSpace = new MontgomerySpace(Modulo); } [Test] [TestCase(0U)] [TestCase(1U)] [TestCase(2U)] [TestCase(4U)] [TestCase(15U)] [TestCase(17U)] [TestCase(32U)] [TestCase(135U)] [TestCase(Modulo)] public void TestTransformToFromSpace(uint x) { var naive = _testSpace.ToSpaceNaive(x); Assert.AreEqual(x % Modulo, (uint)_testSpace.FromSpace(naive)); var simple = _testSpace.ToSpace(x); Assert.AreEqual(x % Modulo, (uint)_testSpace.FromSpace(simple)); var fast = _testSpace.ToSpace(x); Assert.AreEqual(x % Modulo, (uint)_testSpace.FromSpace(fast)); } [Test] [TestCase(100U, 35U)] [TestCase(35U, 100U)] [TestCase(Modulo, 2U)] [TestCase(Modulo - 1, 3U)] [TestCase(Modulo + 1, 3U)] public void TestOperations(uint lhs, uint rhs) { var montgomeryLhs = _testSpace.ToSpaceFast(lhs); var montgomeryRhs = _testSpace.ToSpaceFast(rhs); var montgomerySum = _testSpace.Add(montgomeryLhs, montgomeryRhs); var sum = (uint) _testSpace.FromSpace(montgomerySum); Assert.AreEqual((lhs + rhs) % Modulo, sum); var montgomerySubtract = _testSpace.Subtract(montgomeryLhs, montgomeryRhs); var subtract = (uint) _testSpace.FromSpace(montgomerySubtract); Assert.AreEqual(ModuloSubtract(lhs, rhs), subtract); var montgomeryProduct = _testSpace.Multiply(montgomeryLhs, montgomeryRhs); var product = (uint) _testSpace.FromSpace(montgomeryProduct); Assert.AreEqual((lhs * rhs) % Modulo, product); } private static uint ModuloSubtract(uint lhs, uint rhs) => (lhs + Modulo - (rhs % Modulo)) % Modulo; } }
db3cbe83f00126108c51406f17801ae9929060b7
C#
491134648/Kugar.UI.Web
/Kugar.Core.Web.NetCore/MyRequest.NetCore.cs
2.65625
3
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web; using Kugar.Core.BaseStruct; using Kugar.Core.ExtMethod; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Newtonsoft.Json.Serialization; namespace Kugar.Core.Web { public static partial class MyRequest { public static string GetString(this HttpRequest request, string name, string defaultValue="", bool autoDecode=false) { try { string value; if (request.Method == "GET") { value = request.Query[name]; } else { if (request.Form.ContainsKey(name)) { value = request.Form[name]; } else { value = request.Query[name]; } } if (string.IsNullOrWhiteSpace(value)) { return defaultValue; } else { if (autoDecode) { return HttpUtility.UrlDecode(value); } else { return value; } } } catch (Exception) { return defaultValue; } } /// <summary> /// 判断文件是否存在 /// </summary> /// <param name="request"></param> /// <param name="key"></param> /// <returns></returns> public static bool IsFileExist(this HttpRequest request, string key) { try { if (request.Form.Files.Count > 0 && request.Form.Files.Any(x=>x.Name.CompareTo(key,true))) { return true; } else { return false; } } catch (Exception e) { return false; } } /// <summary> /// 生成一个随机文件名,带扩展名 /// </summary> /// <param name="file"></param> /// <returns></returns> public static string GetRandomName(this IFormFile file,bool containExtension=true) { return $"{DateTime.Now.ToString("yyyyMMddHHmmssffff")}{RandomEx.Next(100, 999)}{(containExtension? Path.GetExtension(file.FileName):"")}"; } public static IFormFile GetFile(this HttpRequest request) { if (request.Form.Files.Count>0) { return request.Form.Files[0]; } else { return null; } } /// <summary> /// 根据naem,获取对应的file对象 /// </summary> /// <param name="request"></param> /// <param name="name"></param> /// <returns></returns> public static IFormFile GetFile(this HttpRequest request, string name) { if (IsFileExist(request, name)) { return request.Form.Files.GetFile(name); } return null; } /// <summary> /// 获取相同name的多个file文件对象 /// </summary> /// <param name="request"></param> /// <param name="name"></param> /// <returns></returns> public static IFormFile[] GetFiles(this HttpRequest request, string name) { if (IsFileExist(request, name)) { return request.Form.Files.GetFiles(name).ToArrayEx(); } return null; } /// <summary> /// 获取本次上传的所有file文件对象 /// </summary> /// <param name="request"></param> /// <param name="name"></param> /// <returns></returns> public static IFormFile[] GetFiles(this HttpRequest request) { return request.Form.Files.ToArrayEx(); } /// <summary> /// 将文件保存入磁盘,注意:path必须为完全路径,如非完整路径,请使用GetWebsitePath进行拼接或启用静态Httpcontext /// </summary> /// <param name="file"></param> /// <param name="path">保存的磁盘路径,必须为完全路径,如非完整路径,请使用GetWebsitePath进行拼接或启用静态Httpcontext</param> /// <returns></returns> public static ResultReturn<string> SaveAsEx(this IFormFile file, string path) { if (file == null || file.Length <= 0) { return new FailResultReturn<string>(new ArgumentOutOfRangeException(nameof(file))); } if (string.IsNullOrWhiteSpace(path)) { return new FailResultReturn<string>(new ArgumentNullException(nameof(path))); } try { //string fullPath = ""; //if (!IsFileFullPath(path)) //{ // fullPath = Path.Combine(GetWebsitePath(request), path); //} var filePath = path; if (!Path.IsPathFullyQualified(filePath)) { if (HttpContext.Current != null && HttpContext.Current.Request!=null) { var rootpath = GetWebsitePath(HttpContext.Current.Request);// HttpContext.Current.Request.GetWebsitePath(); if (path[0] == '/') { filePath = rootpath + filePath; } else { filePath = $"{rootpath}/{filePath}"; } } else { var rootPath = Directory.GetCurrentDirectory(); if (path[0] == '/') { filePath = rootPath + filePath; } else { filePath = $"{rootPath}/{filePath}"; } } } var dirPath = Path.GetDirectoryName(filePath); if (!Directory.Exists(dirPath)) { Directory.CreateDirectory(dirPath); } if (File.Exists(filePath)) { File.Delete(filePath); } using (var diskFile = File.Open(filePath, FileMode.CreateNew, FileAccess.ReadWrite)) using(var srcStream=file.OpenReadStream()) { srcStream.CopyTo(diskFile, 4096); } return new SuccessResultReturn<string>(path); } catch (Exception ex) { return new FailResultReturn<string>(ex); } } /// <summary> /// 将文件保存入磁盘,注意:path必须为完全路径,如非完整路径,请使用GetWebsitePath进行拼接或启用静态Httpcontext /// </summary> /// <param name="file"></param> /// <param name="path">保存的磁盘路径,必须为完全路径,如非完整路径,请使用GetWebsitePath进行拼接或启用静态Httpcontext</param> /// <returns></returns> public static async Task<ResultReturn<string>> SaveAsExAsync(this IFormFile file, string path) { if (file == null || file.Length <= 0) { return new FailResultReturn<string>(new ArgumentOutOfRangeException(nameof(file))); } if (string.IsNullOrWhiteSpace(path)) { return new FailResultReturn<string>(new ArgumentNullException(nameof(path))); } try { //string fullPath = ""; //if (!IsFileFullPath(path)) //{ // fullPath = Path.Combine(GetWebsitePath(request), path); //} var filePath = path; if (!Path.IsPathFullyQualified(filePath)) { if (HttpContext.Current != null) { var rootpath = HttpContext.Current.Request.GetWebsitePath(); if (path[0] == '/') { filePath = rootpath + filePath; } else { filePath = $"{rootpath}/{filePath}"; } } else { throw new ArgumentException("路径必须是绝对路径", nameof(path)); } } var dirPath = Path.GetDirectoryName(filePath); if (!Directory.Exists(dirPath)) { Directory.CreateDirectory(dirPath); } if (File.Exists(filePath)) { File.Delete(filePath); } using (var diskFile = File.Open(filePath, FileMode.CreateNew, FileAccess.ReadWrite)) using (var srcStream = file.OpenReadStream()) { await srcStream.CopyToAsync(diskFile, 4096); } return new SuccessResultReturn<string>(path); } catch (Exception ex) { return new FailResultReturn<string>(ex); } } //public static string GetClientIPAddress(this HttpRequest request) //{ // string ip = null; // if (request.ServerVariables["HTTP_VIA"] != null) // using proxy // { // ip = request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToStringEx(); // Return real client IP. // } // else// not using proxy or can't get the Client IP // { // ip = request.ServerVariables["REMOTE_ADDR"].ToStringEx(); //While it can't get the Client IP, it will return proxy IP. // } // return ip; //} /// <summary> /// 获取当前站点的宿主程序信息 /// </summary> /// <param name="request"></param> /// <returns></returns> public static IHostingEnvironment GetHostingEnvironment(this HttpRequest request) { var env = (IHostingEnvironment)request.HttpContext.RequestServices.GetService(typeof(IHostingEnvironment)); return env; } /// <summary> /// 用于提供类似原先Asp.net 的Server.MapPath功能 /// </summary> /// <param name="request"></param> /// <param name="path">目录</param> /// <returns></returns> public static string MapPath(this HttpRequest request, string path) { if (path[0]=='/') { return Path.Combine(request.GetWebsitePath(), path.Substring(1)); } else { return Path.Combine(request.GetWebsitePath(), path); } } /// <summary> /// 获取当前站点的所在文件夹,站点的根目录 /// </summary> /// <param name="request"></param> /// <returns></returns> public static string GetWebsitePath(this HttpRequest request) { var env = GetHostingEnvironment(request); return env.ContentRootPath; } /// <summary> /// 获取当前站点的useragent /// </summary> /// <param name="request"></param> /// <returns></returns> public static string GetUserAgent(this HttpRequest request) { return request.Headers["User-Agent"].FirstOrDefault(); } /// <summary> /// 判断当前站点是否为移动端浏览器 /// </summary> /// <param name="request"></param> /// <returns></returns> public static bool IsMobileBrowser(this HttpRequest request) { string u = GetUserAgent(request); return (b.IsMatch(u) || v.IsMatch(u.Substring(0, 4))); } /// <summary> /// 获取客户端的IP,如果有反向代理,也可以获取正确的客户端IP /// </summary> /// <param name="request"></param> /// <returns></returns> public static string GetClienIP(this HttpRequest request) { var ip = request.Headers["X-Forwarded-For"].FirstOrDefault(); if (string.IsNullOrEmpty(ip)) { ip = request.HttpContext.Connection?.RemoteIpAddress?.ToStringEx(); } return ip; } public static string GetBodyString(this HttpRequest request,Encoding encoding=null) { if (!request.Body.CanSeek) { request.EnableBuffering(); } //var oldPositon = request.Body.Position; request.Body.Position = 0; if (encoding==null) { encoding=Encoding.UTF8; } var data = request.Body.ReadToEnd(encoding); request.Body.Position = 0; return data; } } }
0b43eea3a2bf8138fe2745faa71b8cdab477889f
C#
sahernoureen/TaskManagmentSystem-C-Asp.net-
/Models/Helper/AdminHelper.cs
2.609375
3
using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; using System.Collections.Generic; using System.Data.Entity; using System.Globalization; using System.Linq; using TaskManagementSystem.Models.Helper; namespace TaskManagementSystem.Models { public static class AdminHelper { public static ApplicationDbContext db = new ApplicationDbContext(); public static UserManager<ApplicationUser> userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db)); public static RoleManager<IdentityRole> roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(db)); //USER public static bool addUser(RegisterViewModel user) { if (userManager.FindByEmail(user.Email) == null) { ApplicationUser appUser = new ApplicationUser() { Email = user.Email, UserName = user.Email, Salary = user.Salary}; userManager.Create(appUser, user.Password); return true; } return false; } public static bool deleteUser(string userId) { if (userManager.FindById(userId) != null) { var user = db.Users.Find(userId); foreach (var n in user.NotificationDev) { user.NotificationDev.Remove(n); db.SaveChanges(); } foreach (var n in user.NotificationManager) { user.NotificationManager.Remove(n); db.SaveChanges(); } foreach (var t in user.Tasks) { user.Tasks.Remove(t); db.SaveChanges(); } foreach (var p in user.Projects) { user.Projects.Remove(p); db.SaveChanges(); } userManager.Delete(user); return true; } return false; } public static List<UserInfoHolder> getAllUsersInfo() { var users = db.Users.ToList(); var userInfo = new List<UserInfoHolder>(); foreach (var u in users) { var ui = new UserInfoHolder(); ui.Id = u.Id; ui.Name = u.UserName; ui.Salary = u.Salary; foreach(var r in u.Roles) { var role = db.Roles.Find(r.RoleId); ui.RolesInfo.Add(role); } userInfo.Add(ui); } return userInfo.Where(u=>u.RolesInfo.All(r=>r.Name!="Admin")).ToList(); } public static List<IdentityRole> getAllRoles() { return db.Roles.Where(r=>r.Name!="Admin").ToList(); } public static ApplicationUser getUserById(string userId) { return db.Users.FirstOrDefault(x => x.Id == userId); } public static List<ApplicationUser> getAllUserExceptById(string userId) { return db.Users.Where(x => x.Id != userId).ToList(); } //ADD ROLE TO USER public static bool addUserToRole(string userId, string role) { if (checkIfUserIsRole(userId, role)) { return false; } else { userManager.AddToRole(userId, role); return true; } } //REMOVE ROLE TO USER public static bool removeUserFromRole(string userId, string role) { if (!checkIfUserIsRole(userId, role)) { return false; } else { userManager.RemoveFromRole(userId, role); return true; } } //ADD ROLE public static bool addRole(string roleName) { if (!roleManager.RoleExists(roleName)) { roleManager.Create(new IdentityRole { Name = roleName }); return true; } return false; } //REMOVE ROLE public static void removeRole(string roleName) { if (roleManager.RoleExists(roleName)) { roleManager.Delete(new IdentityRole { Name = roleName }); } } //CHECKING public static bool checkIfUserIsRole(string userId, string role) { var result = userManager.IsInRole(userId, role); return result; } } }
b80e03c427c5894076c7f10d051d8311e91578a8
C#
lhaneda-tocho/Patmark-master
/iOS/Presenter/MyToast.cs
2.984375
3
using System; using GlobalToast; namespace TokyoChokoku.Patmark.iOS.Presenter { public static class MyToast { public const double Long = 3.5; public const double Short = 2.5; /// <summary> /// トーストを経由してユーザにメッセージを伝えます。 /// メッセージはローカライズされて表示されます。 /// </summary> /// <param name="text">表示するメッセージ。メッセージはローカライズされて表示されます。</param> /// <param name="duration">表示時間の設定です。</param> /// <param name="fargs">引数を指定すると、 <c>text</c> をローカライズした物を、string.Format でフォーマットされます。</param> public static void ShowMessage(string text, double duration = Short, params object[] fargs) { ShowMessageUnsafe(text, localize: true, duration: duration, fargs: fargs); } /// <summary> /// トーストを経由して文字列を表示します。 /// メッセージはローカライズされませんので、デバッグログの表示に利用できます。 /// UI の機能と1つとして利用する場合はこのメソッドではなく、 <c>ShowMessage</c> メソッドを使うべきです。 /// </summary> /// <param name="text">表示するメッセージ。メッセージはローカライズされて表示されます。</param> /// <param name="duration">表示時間の設定です。</param> /// <param name="fargs">引数を指定すると、 <c>text</c> の内容が string.Format でフォーマットされます。</param> [Obsolete("トーストメッセージはローカライズされるべきです。 (デバッグ用途で使う場合は無視して構いません)", error: false)] public static void ShowMessageNotLocalized(string text, double duration = Short, params object[] fargs) { ShowMessageUnsafe(text, localize: false, duration: duration, fargs: fargs); } private static void ShowMessageUnsafe(string text, bool localize, double duration, params object[] fargs) { if (localize) text = text.Localize(); if (fargs == null) fargs = new object[0]; if (fargs.Length > 0) text = string.Format(text, fargs); Toast.MakeToast(text) .SetDuration(duration*1000.0) .Show(); } } }
d0346c729b9e8853641274622d58f8bddd791029
C#
fabioGeorg/freebox-api
/FreeboxAPI/FSAPI/FSErrorsPlus.cs
2.765625
3
 namespace FreeboxAPI.FSAPI { /// <summary> /// FSErrorPlus /// </summary> public enum FSErrorsPlus { /// <summary> /// No error. /// </summary> none, /// <summary> /// Error reading archive. /// </summary> archive_read_failed, /// <summary> /// Error opening archive. /// </summary> archive_open_failed, /// <summary> /// Error writing archive. /// </summary> archive_write_failed, /// <summary> /// Error changing directory. /// </summary> chdir_failed, /// <summary> /// The destination is not a directory. /// </summary> dest_is_not_dir, /// <summary> /// File already exists. /// </summary> file_exists, /// <summary> /// File not found. /// </summary> file_not_found, /// <summary> /// Unable to create directory. /// </summary> mkdir_failed, /// <summary> /// Error opening input file. /// </summary> open_input_failed, /// <summary> /// Error opening output file. /// </summary> open_output_failed, /// <summary> /// Error opening directory. /// </summary> opendir_failed, /// <summary> /// Error overwriting file. /// </summary> openwrite_failed, /// <summary> /// Path is too long. /// </summary> path_too_big, /// <summary> /// Failed to repair corrupted files. /// </summary> repair_failed, /// <summary> /// Error removing directory. /// </summary> mdir_failed, /// <summary> /// Source and Destination are the same file. /// </summary> same_file, /// <summary> /// Error removing file. /// </summary> unlink_failed, /// <summary> /// This file type is not supported. /// </summary> unsupported_file_type, /// <summary> /// Error writing file. /// </summary> write_failed, /// <summary> /// Disk is full. /// </summary> disk_full, /// <summary> /// Internal error. /// </summary> @internal, /// <summary> /// Invalid file format (corrupted?). /// </summary> invalid_format, /// <summary> /// Invalid or missing password for extraction. /// </summary> incorrect_password, /// <summary> /// Permission denied. /// </summary> permission_denied, /// <summary> /// Failed to read the target of a symbolic link. /// </summary> readlink_failed, /// <summary> /// Failed to create a symbolic link. /// </summary> symlink_failed } }
d27c4dfa6e660006437417423c676806dcf7c41f
C#
EvdokiyaValova/Programming-Fundamentals-
/Fundamentals-Basic-Homeworks/Man O War4/Program.cs
3.3125
3
using System; using System.Collections.Generic; using System.Linq; namespace Man_O_War3 { class Program { static void Main(string[] args) { List<int> piratesShip = Console.ReadLine().Split(">").Select(int.Parse).ToList(); List<int> warship = Console.ReadLine().Split(">").Select(int.Parse).ToList(); int maxHealth = int.Parse(Console.ReadLine()); string comand = Console.ReadLine(); bool isDead = false; while (comand != "Retire") { List<string> currentComand = comand.Split().ToList(); if (currentComand[0] == "Fire") { int indexFire = int.Parse(currentComand[1]); int damageFire = int.Parse(currentComand[2]); if (indexFire >= 0 && indexFire < warship.Count) { int fireResult = warship[indexFire] - damageFire; if (fireResult <= 0) { isDead = true; Console.WriteLine("You won! The enemy ship has sunken."); break; } else { warship[indexFire] = fireResult; } } if (isDead) { break; } } else if (currentComand[0] == "Defend") { int startIndex = int.Parse(currentComand[1]); int endIndex = int.Parse(currentComand[2]); int damageDefend = int.Parse(currentComand[3]); if (startIndex >= 0 && endIndex < piratesShip.Count) { for (int i = startIndex; i <= endIndex; i++) { int defendedResul = piratesShip[i] - damageDefend; if (defendedResul <= 0) { isDead = true; Console.WriteLine("You lost! The pirate ship has sunken."); break; } else { piratesShip[i] = defendedResul; } } } if (isDead) { break; } } else if (currentComand[0] == "Repair") { int indexRepair = int.Parse(currentComand[1]); int health = int.Parse(currentComand[2]); if (indexRepair >= 0 && indexRepair < piratesShip.Count) { int resultRepair = piratesShip[indexRepair] + health; if (resultRepair >= maxHealth) { resultRepair = maxHealth; piratesShip[indexRepair] = resultRepair; } else { piratesShip[indexRepair] = resultRepair; } } } else if (currentComand[0] == "Status") { int countLower = 0; for (int i = 0; i < piratesShip.Count; i++) { if (piratesShip[i] < maxHealth * 0.2) { countLower++; } } Console.WriteLine($"{countLower} sections need repair."); } comand = Console.ReadLine(); } if (!isDead) { int sumPirates = 0; for (int i = 0; i < piratesShip.Count; i++) { sumPirates += piratesShip[i]; } int sumWarship = 0; for (int i = 0; i < warship.Count; i++) { sumWarship += warship[i]; } Console.WriteLine($"Pirate ship status: {sumPirates}"); Console.WriteLine($"Warship status: {sumWarship}"); } } } }