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
2c9a1c93202425697fe3ec38625023d069a3fb34
C#
seiya886s/kudryavkaDiscordBot
/src/discordClinet/Config/Configuration.cs
2.703125
3
using kudryavkaDiscordBot.discondClinet.Utility; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Text; namespace kudryavkaDiscordBot.discondClinet.Config { /// <summary> /// Class for stroing global setting values in memory /// </summary> public class Configuration { public string DISCORD_TOKEN; public string NAVER_CLIENT_ID; public string NAVER_CLINET_SECRET; public string DB_CONNECT; } /// <summary> /// Class that provides only Static function to manage data /// </summary> public class ConfigurationHelper { /// <summary> /// Read data from env if not read data to File /// </summary> /// <param name="path"></param> /// <returns></returns> static public Configuration Load() { Configuration configuration = Singleton<Configuration>.Instance; if (LoadEnvironment(configuration)) { return configuration; } else if (LoadFile(configuration, "config/bot.json")) { return configuration; } return null; } /// <summary> /// Read Data From Config File /// </summary> /// <param name="config">Configuration Class</param> /// <param name="filePath">FIle Path</param> /// <returns></returns> public static bool LoadFile(Configuration config, string filePath) { bool result = true; string jsonFileText = File.ReadAllText(filePath); config = JsonConvert.DeserializeObject<Configuration>(jsonFileText); if (config.DISCORD_TOKEN == null) { result = false; } return result; } /// <summary> /// Read Data From Environment Variable /// </summary> /// <param name="config">Configuration Class</param> /// <returns> </returns> static public bool LoadEnvironment(Configuration config) { bool result = true; try { IDictionary env = System.Environment.GetEnvironmentVariables(); config.DISCORD_TOKEN = env["DISCORD_TOKEN"].ToString(); config.NAVER_CLIENT_ID = env["NAVER_CLIENT_ID"].ToString(); config.NAVER_CLINET_SECRET = env["NAVER_CLINET_SECRET"].ToString(); config.DB_CONNECT = env["MYSQL_CONNECT"].ToString(); } catch (Exception ) { result = false; #if DEBUG_EXCEPT throw new SystemException(e); #endif } return result; } } }
61bffb18b989ed5dc675c41faf637a0e89b85c8b
C#
Karrazyne/Past
/Past.Protocol/Types/game/character/CharacterMinimalInformations.cs
2.921875
3
using Past.Protocol.IO; using System; namespace Past.Protocol.Types { public class CharacterMinimalInformations { public int id; public string name; public byte level; public const short Id = 110; public virtual short TypeId { get { return Id; } } public CharacterMinimalInformations() { } public CharacterMinimalInformations(int id, string name, byte level) { this.id = id; this.name = name; this.level = level; } public virtual void Serialize(IDataWriter writer) { writer.WriteInt(id); writer.WriteUTF(name); writer.WriteByte(level); } public virtual void Deserialize(IDataReader reader) { id = reader.ReadInt(); if (id < 0) throw new Exception("Forbidden value on id = " + id + ", it doesn't respect the following condition : id < 0"); name = reader.ReadUTF(); level = reader.ReadByte(); if (level < 1 || level > 200) throw new Exception("Forbidden value on level = " + level + ", it doesn't respect the following condition : level < 1 || level > 200"); } } }
8a072e198bf3919ea4543a638949288c4fd0ba10
C#
rsakshay/HangryDrago
/Assets/Code/InputMan.cs
2.515625
3
using UnityEngine; public static class InputMan { private const string LHorizontal = "LHorizontal"; private static bool allowControls = true; public static bool GetButtonDown(string key) { if (!allowControls) return false; return Input.GetButtonDown(key); } public static bool GetButtonUp(string key) { if (!allowControls) return false; return Input.GetButtonUp(key); } public static float GetLHorizontal() { if (!allowControls) return 0; return Input.GetAxis(LHorizontal); } public static void DisableControls() { allowControls = false; } public static void EnableControls() { allowControls = true; } }
1a8b5321670d93fadb1b04e8d030d181650779cd
C#
avinash0161/OrleansExperiments
/Program.cs
2.6875
3
using Microsoft.Extensions.Logging; using Orleans; using Orleans.Configuration; using Orleans.Hosting; using System; using System.Net; using System.Threading.Tasks; namespace Orleans2StatelessWorkers { class Program { private const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; private static Random random; static string GenerateRandomString() // ref: https://stackoverflow.com/a/1344258/983064 { var stringChars = new char[8]; for (int i = 0; i < stringChars.Length; i++) { var randomCharIndex = random.Next(chars.Length); stringChars[i] = chars[randomCharIndex]; } return new string(stringChars); } static async Task Main(string[] args) { random = new Random(); // 1. set up silo var siloBuilder = new SiloHostBuilder() .UseLocalhostClustering() //.UseDashboard(options => { }) .Configure<ClusterOptions>(options => { options.ClusterId = "dev"; options.ServiceId = "Orleans2StatelessWorkers"; }) .Configure<EndpointOptions>(options => options.AdvertisedIPAddress = IPAddress.Loopback) .ConfigureLogging(logging => logging.SetMinimumLevel(LogLevel.Critical).AddConsole()) // options.ResendOnTimeout = true; options.MaxResendCount = 60; .Configure<SiloMessagingOptions>(options => {options.ResponseTimeout = new TimeSpan(0,0,32); }); var host = siloBuilder.Build(); await host.StartAsync(); // 2. set up client var clientBuilder = new ClientBuilder() .UseLocalhostClustering() .Configure<ClusterOptions>(options => { options.ClusterId = "dev"; options.ServiceId = "Orleans2StatelessWorkers"; }) .ConfigureLogging(logging => logging.SetMinimumLevel(LogLevel.Critical).AddConsole()) .Configure<ClientMessagingOptions>(options => {options.ResponseTimeout = new TimeSpan(0,0,130);}); var client = clientBuilder.Build(); await client.Connect(); // 3. generate load // var hashGenerator = client.GetGrain<IHashGeneratorGrain>(0); var grainA=client.GetGrain<IOperatorA>(1); //while (true) //{ // var randomString = GenerateRandomString(); // var hash = await hashGenerator.GenerateHashAsync(randomString); // Console.WriteLine(hash); try{ Console.WriteLine("Client making a call"); for(int i=0;i<10;++i) await grainA.ReceiveTuple(i+1); // hashGenerator.CallToFellowGrain(); // await hashGenerator.TempCall(); // hashGenerator.Call_A_ToTemp(); // await Task.Delay(1000); // hashGenerator.Call_B_ToTemp(); // hashGenerator.TempCall().ContinueWith((t)=> // { // if(t.IsFaulted) // { // Console.WriteLine("Got faulted"); // hashGenerator.TempCall(); // } // // else if(t.I) // } // ); } catch (Exception ex) { Console.WriteLine("EXCEPTION: " + ex.Message); } //} // 4. cleanup - never reached in this case Console.ReadKey(); await client.Close(); await host.StopAsync(); } } }
76252cbd867975845635db6e350d0c378072842a
C#
nightmare40000/DMInS
/Lab1-DMInS/MainForm.cs
2.578125
3
using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Linq; using System.Windows.Forms; using Shared; namespace Lab1_DMInS { public partial class MainForm : Form { private readonly IDisplayer _displayer; private readonly IClusterizer _clusterizer; private string _filePath; public MainForm() { InitializeComponent(); WindowState = FormWindowState.Maximized; var settings = new DisplayerFields { BalckAndWhitePictureBox = BlackAndWhitePictureBox, CorrectedBrightnessPictureBox = CorrectedBrightnessPictureBox, ResultPictureBox = ResultPictureBox, OriginalPictureBox = OriginalImagePictureBox }; _clusterizer = new Clusterizer(); _displayer = new Displayer(settings); } /// <summary> /// Selecting file /// </summary> private void SelectFileButton_Click(object sender, EventArgs e) { var fileDialog = new OpenFileDialog { Title = @"Select Image", Filter = @"JPEG|*.jpg", InitialDirectory = Path.GetDirectoryName(Application.ExecutablePath) }; if (fileDialog.ShowDialog() != DialogResult.OK) { MessageBox.Show(@"Error when open file"); } _filePath = fileDialog.FileName; FilePathLabel.Text = _filePath; } private void GoButton_Click(object sender, EventArgs e) { if (!FormIsValid()) { return; } var image = new Bitmap(_filePath); var correctedImage = image; if (FilterCheckBox.Checked) { correctedImage = ImageCorrector.CorrectBrightness(image); } var labels = new int[image.Width, image.Height]; Bitmap blackAndWhiteImage = ImageCorrector.ConvertToBlackAndWhite(correctedImage, int.Parse(BinarizationLevelTextBox.Text)); ImageCorrector.Labeling(blackAndWhiteImage, labels); _displayer.ShowOriginalImage(image); _displayer.ShowCorrectedImage(correctedImage); _displayer.ShowBlackAndWhiteImage(blackAndWhiteImage); var dictionary = FindLabelGroups(labels, image.Width, image.Height); var parameters = _clusterizer.CalculateParameters(dictionary.Values, ref labels); var classes = _clusterizer.Clusterize(parameters, int.Parse(ClassesCountComboBox.Text)); var resultImage = blackAndWhiteImage; foreach (var cluster in classes) { var random = new Random(); var color = Color.FromArgb(255, random.Next(255), random.Next(255), random.Next(255)); resultImage = ImageCorrector.SetColorToClusters(resultImage, cluster, color); } _displayer.ShowResultImage(resultImage); } private bool FormIsValid() { int result; return !string.IsNullOrEmpty(_filePath) && int.TryParse(ClassesCountComboBox.Text, out result); } private static Dictionary<int, LabelGroup> FindLabelGroups(int[,] labels, int width, int height) { var dictionary = new Dictionary<int, LabelGroup>(); for (var i = 0; i < width; i++) { for (var j = 0; j < height; j++) { if (labels[i, j] == 0) { continue; } LabelGroup labelGroup; var item = labels[i, j]; if (!dictionary.TryGetValue(item, out labelGroup)) { labelGroup = new LabelGroup { Label = item, Pixels = new List<Coords>() }; dictionary.Add(item, labelGroup); } if (labelGroup != null) { labelGroup.Pixels.Add(new Coords(i, j)); } } } if (Configuration.IsDiscard) { var result = dictionary.Where(item => item.Value.Pixels.Count > Configuration.DiscardPixelsCount) .ToDictionary(item => item.Key, item => item.Value); return result; } return dictionary; } } }
edbd9074dd9cd5a826fb1d1cd0bcc5a7bb896dcf
C#
Jrdiazs/Prueba.Servicios
/Prueba.Servicios/ExecuteJobs.cs
2.5625
3
using Prueba.Servicios.StringTools; using Quartz; using Quartz.Impl; using System; using System.Collections.Specialized; namespace Prueba.Servicios { public class ExecuteJobs : IExecuteJobs, IDisposable { /// <summary> /// Sheduler Time /// </summary> private static IScheduler _scheduler; /// <summary> /// StdSchedulerFactory /// </summary> private static StdSchedulerFactory _schedulerFactory; private bool disposedValue; /// <summary> /// Nombre del proceso /// </summary> private const string nameProcess = "ExecuteTaskTest"; private readonly int minutesInterval; private readonly NameValueCollection collection = new NameValueCollection() { {"quartz.threadPool.threadCount","5"}, {"quartz.scheduler.instanceName",string.Format("Scheduler{0}",nameProcess)}, {"quartz.threadPool.type","Quartz.Simpl.SimpleThreadPool, Quartz"}, {"quartz.threadPool.threadPriority","Normal"} }; public ExecuteJobs() { var minutesKey = "minutesInterval".ReadAppConfig("5"); minutesInterval = int.Parse(minutesKey); _schedulerFactory = new StdSchedulerFactory(collection); } public void Start() { try { IScheduler sheduler = _schedulerFactory.GetScheduler(nameProcess); _scheduler = sheduler ?? _schedulerFactory.GetScheduler(); if (!_scheduler.IsStarted) _scheduler.Start(); JobDetailImpl job = new JobDetailImpl(nameProcess, typeof(MyJob)); ITrigger trigger = trigger = TriggerBuilder.Create(). WithIdentity(string.Format("Trigger{0}", "TriggerExecuteTask"), string.Format("Group{0}", "groupExecuteTask")) .WithSimpleSchedule (s => s.WithIntervalInMinutes(minutesInterval).RepeatForever()).Build(); DateTimeOffset date = _scheduler.ScheduleJob(job, trigger); } catch (Exception) { throw; } } public void Stop() { try { if (_scheduler != null) _scheduler.Shutdown(true); } catch (Exception) { throw; } } #region [Dispose] protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { // TODO: eliminar el estado administrado (objetos administrados) } // TODO: liberar los recursos no administrados (objetos no administrados) y reemplazar el finalizador // TODO: establecer los campos grandes como NULL disposedValue = true; } } // // TODO: reemplazar el finalizador solo si "Dispose(bool disposing)" tiene código para liberar los recursos no administrados // ~ExecuteJobs() // { // // No cambie este código. Coloque el código de limpieza en el método "Dispose(bool disposing)". // Dispose(disposing: false); // } public void Dispose() { // No cambie este código. Coloque el código de limpieza en el método "Dispose(bool disposing)". Dispose(disposing: true); GC.SuppressFinalize(this); } #endregion [Dispose] } public interface IExecuteJobs : IDisposable { void Start(); void Stop(); } }
656d3ac085023edd904538c1c5cf714993cec276
C#
tmatuszewski97/university-projects
/ai-programming/KnnWindowsForms/KnnWindowsForms/OknoZParametrem.cs
2.765625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Windows.Forms.VisualStyles; using static KnnWindowsForms.Testy; namespace KnnWindowsForms { public static class OknoZParametrem { public static double WyswietlOkno(string text, string caption) { Form okno = new Form() { Width = 500, Height = 150, FormBorderStyle = FormBorderStyle.FixedDialog, Text = caption, StartPosition = FormStartPosition.CenterScreen }; Label textLabel = new Label() { Left = 50, Top = 20, Text = text, Width = 400}; TextBox textBox = new TextBox() { Left = 150, Top = 40, Width = 100, TextAlign = HorizontalAlignment.Center}; Button confirmation = new Button() { Text = "Zatwierdź", Left = 150, Width = 100, Top = 60, DialogResult = DialogResult.OK }; confirmation.Click += (sender, e) => { okno.Close(); }; okno.Controls.Add(textBox); okno.Controls.Add(confirmation); okno.Controls.Add(textLabel); okno.AcceptButton = confirmation; if (okno.ShowDialog() == DialogResult.OK) { var tmp = textBox.Text; tmp = CzyPrzecinek() ? tmp.Replace(".", ",") : tmp.Replace(",", "."); if (CzyDouble(tmp)) { //BladAtrybuty.Visible = false; return (Convert.ToDouble(tmp)); } } return 0; } } }
81e6ac7e10c0443e443b974ea9926ddccc9f9e0d
C#
leandrotquinelato/SOP
/CORE.Auth/TratamentoLog.cs
3.171875
3
using System; using System.Collections.Generic; using System.Text; using System.IO; namespace MRS.Automacao.Uteis { public class TratamentoLog { public enum NivelLog { Info, Erro, Acao }; private static String pathPastaLog = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "log"); private static String NiveisLogAtual = "Info|Erro|Acao"; /// <summary> /// Altera o path da pasta de logs atualmente sendo utilizada. /// </summary> /// <param name="Pasta">Novo caminho para a pasta de logs.</param> public static void AlterarPastaLog(String PathPasta) { pathPastaLog = PathPasta; } /// <summary> /// Obtém a pasta de logs atualmente sendo utilizada. /// </summary> /// <returns>Path para a pasta de logs</returns> public static String ObterPastaLog() { return pathPastaLog; } /// <summary> /// Altera o nível dos logs gravados. Os níveis devem ser separados por vírgula ou por pipe ("|"). /// Ex: "Erro|Acao" ou "Erro, Acao" /// </summary> /// <param name="Niveis">Níveis a serem gravados, separados por vírgula ou por pipe ("|").</param> public static void AlterarNiveisGravacaoLogs(String Niveis) { NiveisLogAtual = ""; char charSeparacao = (Niveis.IndexOf(",") >= 0) ? ',' : '|'; String[] arrNiveis = Niveis.Split(charSeparacao); foreach (String Nivel in arrNiveis) NiveisLogAtual += (NiveisLogAtual == "" ? "" : "|") + Nivel.Trim(); } /// <summary> /// Verifica se um nível específico de log está sendo gravado. /// </summary> /// <param name="Nivel">Nível que se deseja verificar se está sendo gravado.</param> /// <returns>Verdadeiro quando estiver sendo gravado o nível especificado, Falso caso contrário.</returns> public static Boolean EstaGravandoNivel(NivelLog Nivel) { return new List<String>(NiveisLogAtual.Split('|')).Contains(Enum.GetName(typeof(NivelLog), Nivel)); } /// <summary> /// Grava a mensagem de log desejada. O nível do log gravado será de Erro. /// </summary> /// <param name="Mensagem">Mensagem de erro a ser gravada.</param> public static void GravarLog(String Mensagem) { GravarLog(Mensagem, NivelLog.Erro, "", ""); } /// <summary> /// Grava a mensagem de log desejada, no nível desejado. /// Caso o nível desejado não esteja ativo no momento, nada será gravado. /// </summary> /// <param name="Mensagem">Mensagem de log a ser gravada.</param> /// <param name="Nivel">Nível de log da mensagem sendo gravada.</param> public static void GravarLog(String Mensagem, NivelLog Nivel) { GravarLog(Mensagem, Nivel, "", ""); } /// <summary> /// Grava a mensagem de log desejada, no nível desejado. /// Caso o nível desejado não esteja ativo no momento, nada será gravado. /// </summary> /// <param name="Mensagem">Mensagem de log a ser gravada.</param> /// <param name="Nivel">Nível de log da mensagem sendo gravada.</param> /// <param name="SubPasta">Subpasta (opcional) na qual se deseja gravar o log.</param> /// <param name="NomeArquivo">Nome do arquivo (opcional) para o qual o log será gravado. Por padrão, o nome é a data, no formato yyyyddmm. A extensão sempre é .txt.</param> public static void GravarLog(String Mensagem, NivelLog Nivel, String SubPasta, String NomeArquivo) { try { if (EstaGravandoNivel(Nivel)) { String path = pathPastaLog; String nome = DateTime.Now.ToString("yyyyMMdd"); if (SubPasta != "") path = Path.Combine(pathPastaLog, SubPasta); if (NomeArquivo != "") nome = NomeArquivo; if (!Directory.Exists(path)) Directory.CreateDirectory(path); File.AppendAllText(Path.Combine(path, nome + ".txt"), DateTime.Now.ToString("HH:mm:ss") + " - " + Enum.GetName(typeof(NivelLog), Nivel) + " - " + Mensagem + "\r\n"); } } catch { } } } }
ef5e7d3e5e3f906cc8251cb5394338afbd92e074
C#
TeodorPenev/SoftUni
/Level 0/C#_Basics/PreparationForExam/Exercises/4.Console-Input-Output-HW/15. NewHouse/NewHouse.cs
3.5625
4
//Problem 15. * – New House //This problem is from Variant 4 of C# Basics exam from 11-04-2014 Evening. using System; class NewHouse { static void Main() { int n = int.Parse(Console.ReadLine()); int starIncrease = 0; int linesDecrease =0; for (int i = 0; i < n/2+1; i++) { string lines = new string('-',Math.Abs(n/2 -linesDecrease++ )); string star = new string('*',1+ 2*starIncrease++); Console.WriteLine("{0}{1}{0}",lines,star); if (lines == "") for (int i1 = 0; i1 < n; i1++) { string stick = new string('|', 1); string starEnd = new string('*', n - 2); Console.WriteLine("{0}{1}{0}", stick, starEnd); } } } }
526cec87770f8ba55ed070556d28cb38f3a32906
C#
SobekCM/SobekCM-Web-Application
/SobekCM_Library/ItemViewer/HtmlHeadWriters/iItemHtmlHeadWriter.cs
2.59375
3
using System.IO; using SobekCM.Core.BriefItem; using SobekCM.Library.ItemViewer.Viewers; namespace SobekCM.Library.ItemViewer.HtmlHeadWriters { /// <summary> Defines the interface for the objects that can write into the HTML head during item display </summary> /// <remarks> This object should be thread safe and not contain any state information </remarks> public interface iItemHtmlHeadWriter { /// <summary> Write anything within the HTML head while displaying an item </summary> /// <param name="Output"> Stream to which to write within the HTML head tag </param> /// <param name="CurrentViewer"> Current item viewer which will be used to fill the primary part of the page </param> /// <param name="CurrentItem"> Current item which is being displayed </param> /// <param name="RequestSpecificValues"> Other, request specific values, such as the current mode, user, etc.. </param> void Write_Within_HTML_Head(TextWriter Output, iItemViewer CurrentViewer, BriefItemInfo CurrentItem, RequestCache RequestSpecificValues); } }
359a83444d7a1befb782bfec2b34064756effa12
C#
CCurl/StockAnalyzer
/trader1/MainWindowViewModel.cs
2.75
3
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; namespace trader1 { public class MainWindowViewModel : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; public List<Stock> Stocks { get { return this.stocks; } } private List<Stock> stocks; public List<Stock> Stocks_BAD { get { return this.stocks_bad; } } private List<Stock> stocks_bad; public List<Stock> Stocks_NEW { get { return this.stocks_new; } } private List<Stock> stocks_new; public Stock Current { get { return currentStock; } set { currentStock = value; NotifyPropertyChanged(); } } private Stock currentStock; public string Status { get { return status; } set { status = value; NotifyPropertyChanged(); } } private string status; public bool Stop { get; set; } public bool Validating { get { return validating; } set { validating = value; NotifyPropertyChanged(); } } private bool validating; public MainWindowViewModel() { stocks = new List<Stock>(); stocks_bad = new List<Stock>(); stocks_new = new List<Stock>(); Status = "init"; validating = true; } public void NotifyPropertyChanged([CallerMemberName] String propertyName = "") { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } internal void LoadStocks() { this.stocks.Clear(); this.stocks_bad.Clear(); this.stocks_new.Clear(); StockDB.LoadStocks(ref this.stocks, "G"); StockDB.LoadStocks(ref this.stocks_bad, "B"); StockDB.LoadStocks(ref this.stocks_new, "U"); } internal void SaveStocks() { foreach (var s in this.Stocks) { if (s.IsChanged) { s.Save(); } } foreach (var s in this.Stocks_BAD) { if (s.IsChanged) { if (string.IsNullOrEmpty(s.Company)) { s.Company = ""; } s.Status = "B"; s.Save(); } } foreach (var s in this.Stocks_NEW) { if (s.IsChanged) { if (string.IsNullOrEmpty(s.Company)) { s.Company = ""; } s.Status = "U"; s.Save(); } } } } }
46639a54a868348fa1e02147a8c33f08fec13e18
C#
abubakarirfan/ShapeDrawer
/Shape.cs
3.140625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using SplashKitSDK; using System.IO; namespace ShapeDrawer { public abstract class Shape { private static Dictionary<string, Type> _ShapeClassRegistry = new Dictionary<string, Type>(); public static void RegisterShape(string name, Type t) { _ShapeClassRegistry[name] = t; } public static string GetKey(Type y) { foreach(string x in _ShapeClassRegistry.Keys) { if (_ShapeClassRegistry[x] == y) { return x; } } return null; } public static Shape CreateShape(string name) { return (Shape)Activator.CreateInstance(_ShapeClassRegistry[name]); } private Color _color; private float _x, _y; private bool _selected; public Shape() : this (Color.Yellow) { } public Shape(Color color) { _color = color; } public virtual void SaveTo(StreamWriter writer) { writer.WriteLine(GetKey(GetType())); writer.WriteColor(Color); writer.WriteLine(X); writer.WriteLine(Y); } public Color Color { get { return _color; } set { _color = value; } } public float X { get { return _x; } set { _x = value; } } public float Y { get { return _y; } set { _y = value; } } public virtual void LoadFrom(StreamReader reader) { Color = reader.ReadColor(); X = reader.ReadSingle(); Y = reader.ReadSingle(); } public bool Selected { get { return _selected; } set { _selected = value; } } public abstract void DrawOutline(); public abstract void Draw(); public abstract bool IsAt(Point2D pt); } }
a6cb992f31d40107b107c162cf64a5bb592059ce
C#
Bhaskers-Blu-Org2/CromwellOnAzure
/src/deploy-cromwell-on-azure/Program.cs
2.59375
3
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Threading.Tasks; namespace CromwellOnAzureDeployer { internal class Program { public static async Task Main(string[] args) { await InitializeAndDeployAsync(args); } private static async Task InitializeAndDeployAsync(string[] args) { Configuration configuration = null; try { configuration = Configuration.BuildConfiguration(args); } catch(ArgumentException ex) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(ex.Message); Console.ResetColor(); Environment.Exit(1); } if (!configuration.Silent) { PrintWelcomeScreen(); } var isSuccessful = await new Deployer(configuration).DeployAsync(); if (isSuccessful) { Environment.Exit(0); } else { Environment.Exit(1); } } private static void PrintWelcomeScreen() { Console.WriteLine("Copyright (c) Microsoft Corporation."); Console.WriteLine("Licensed under the MIT License."); Console.WriteLine("Privacy & Cookies: https://go.microsoft.com/fwlink/?LinkId=521839"); Console.WriteLine(); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Cromwell on Azure"); Console.ResetColor(); Console.WriteLine("https://github.com/microsoft/CromwellOnAzure"); Console.WriteLine(); } } }
97e3341df285a44a6292953a410defb1ba0658c2
C#
shendongnian/download4
/first_version_download2/548322-51750900-179354552-2.cs
3.078125
3
public static void FindElement(this IWebDriver driver, By by, int timeout) { if(timeout >0) { return new WebDriverWait(driver, TimeSpan.FromSeconds(timeout)).Until(ExpectedConditions.ElementToBeClickable(by)); } return driver.FindElement(by); } public static IReadOnlyCollection<IWebElement> FindElements(this IWebDriver driver, By by, int timeout) { if(timeout >0) { return new WebDriverWait(driver, TimeSpan.FromSeconds(timeout)).Until(ExpectedConditions.PresenceOfAllElementsLocatedBy(by)); } return driver.FindElements(by); }
6a815e4a4026ee356c047bfcc4004c9949077af4
C#
Skeletonware/Fog-Eater
/Assets/_Scripts/BulletUI.cs
2.65625
3
using System.Collections; using System.Collections.Generic; using UnityEngine; public class BulletUI : MonoBehaviour { public List<GameObject> uiBullets = new List<GameObject>(); public GameObject bulletPrefab; public static BulletUI instance; void Awake() { instance = this; } public static void AddBullets(int amt) { for (int i = 0; i < amt; i++) { GameObject bullet = Instantiate(instance.bulletPrefab, instance.transform); //bullet.transform.parent = instance.transform; instance.uiBullets.Add(bullet); } } public static void SetBullets(int amt) { foreach (GameObject bullet in new List<GameObject>(instance.uiBullets)) { Destroy(instance.uiBullets[0]); instance.uiBullets.RemoveAt(0); } AddBullets(amt); } public static void RemoveBullet() { Destroy(instance.uiBullets[0]); instance.uiBullets.RemoveAt(0); } }
e3d69e9e4e5ab45503f672025883cc14cbd21ae6
C#
WeiWei-Haung/asp.net-class
/asp.net-class-2018-4-19/WebApplication1/Models/Service/OrderService.cs
2.671875
3
using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Web; using WebApplication1.Models.Daos; namespace WebApplication1.Models.Service { public class OrderService { /// <summary> /// 進行Order的查詢 /// </summary> /// <param name="orderID">訂單編號</param> /// <returns></returns> public Orders GetOrder(int orderID) { OrderDao dao = new OrderDao(); return dao.GetOrderById(orderID); } /// <summary> /// 取得 Orders by 條件 /// </summary> /// <returns></returns> public IList<Orders> GetOrders(OrderQueryArg arg) { CustomerService customerService = new CustomerService(); OrderDao orderDao = new OrderDao(); // 取得所有訂單後進行篩選 (注意: 此處應將查詢條件串入SQL中為較好之寫法) IEnumerable<Orders> currentOrders = orderDao.GetAllOrders(); // 訂單編號 if (arg.OrderID.HasValue) { currentOrders = currentOrders.Where(m => m.OrderID == arg.OrderID.Value); } // 客戶名稱 (like 查詢) if (!string.IsNullOrWhiteSpace(arg.CompanyName)) { currentOrders = currentOrders.Where( m => customerService.GetCompanyName(m.CustomerID).Contains(arg.CompanyName) ); } // 員工編號 if (arg.EmployeeID.HasValue) { currentOrders = currentOrders.Where(m => m.EmployeeID == arg.EmployeeID.Value); } // 出貨公司 if (arg.ShipperID.HasValue) { currentOrders = currentOrders.Where(m => m.ShipperID == arg.ShipperID.Value); } // 訂購日期 if (arg.OrderDate.HasValue) { currentOrders = currentOrders.Where(m => m.OrderDate == arg.OrderDate.Value); } // 需要日期 if (arg.RequiredDate.HasValue) { currentOrders = currentOrders.Where(m => m.RequiredDate == arg.RequiredDate.Value); } // 出貨日期 if (arg.ShipedDate.HasValue) { currentOrders = currentOrders.Where(m => m.ShippedDate == arg.ShipedDate.Value); } return currentOrders.OrderBy(m => m.OrderID).ToList(); } /// <summary> /// 新增 Order /// </summary> /// <param name="order">欲新增的訂單資料</param> public void InsOrder(Orders order) { OrderDao orderDao = new OrderDao(); orderDao.AddNewOrderReturnNewOrderId(order); } /// <summary> /// 更新 Order /// </summary> /// <param name="order">欲更新的訂單資料</param> public void UpdOrder(Orders order) { OrderDao orderDao = new OrderDao(); orderDao.UpdateOrder(order); } /// <summary> /// 刪除 Order /// </summary> /// <param name="orderID">訂單編號</param> public void DelOrder(int orderID) { OrderDao orderDao = new OrderDao(); orderDao.DeleteOrder(orderID); } */ } }
53fbff297ffc5eb28aa2725ff4a662166e2f94f6
C#
local-minimum/emotihunt
/Assets/scripts/ImageAnalysis/Filters/Gaussian5x5S1.cs
3.25
3
namespace ImageAnalysis.Filters { public class Gaussian5x5S1 : Gaussian { double[,] kernel = new double[5,5]; public Gaussian5x5S1() { for (int y=0;y<5;y++) { for (int x=0; x<5;x++) { kernel[y, x] = GetValue(x, y, 1.0f); } } SetScale(); } public override double[,] Kernel { get { return kernel; } } public override string Name { get { return "Gaussian 5x5 Kernel, Sigma 1.0"; } } } }
710cd8a70cb5365923d958aca01ddd5edc419c5a
C#
bulentmericli/abc-bank-c-sharp
/AbcBank.Test/CustomerTest.cs
2.875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NUnit.Framework; namespace AbcBank.Test { [TestFixture, Description("Tests for Customer class")] public class CustomerTest { [Test] public void Should_Set_Customer_Name() { var customer = new Customer("John"); Assert.AreEqual("John", customer.Name); } [Test] public void Should_Add_Customer_Account() { var customer = new Customer("Oscar"); customer.AddAccount(new Account(AccountType.Checking)); Assert.AreEqual(1, customer.Accounts.Count()); } [Test] public void Should_Earn_No_Interest1() { var customer = new Customer("Oscar"); Assert.AreEqual(0d, customer.GetEarnedInterest()); } [Test] public void Should_Earn_No_Interest2() { var customer = new Customer("Oscar"); customer.AddAccount(new Account(AccountType.Checking)); Assert.AreEqual(0d, customer.GetEarnedInterest()); } [Test] public void Should_Earn_No_Interest3() { var customer = new Customer("Oscar"); var account = new Account(AccountType.Checking); account.Deposit(10000); customer.AddAccount(account); Assert.AreEqual(0d, customer.GetEarnedInterest()); } [Test] public void Should_Earn_No_Interest4() { var customer = new Customer("Oscar"); customer.AddAccount(new Account(AccountType.Checking)); customer.AddAccount(new Account(AccountType.Checking)); customer.AddAccount(new Account(AccountType.MaxiSavings)); customer.AddAccount(new Account(AccountType.Savings)); Assert.AreEqual(0d, customer.GetEarnedInterest()); } [Test] public void Should_Earn_Interest1() { var account = new Account ( AccountType.Checking, new Transaction[] { new Transaction(DateTime.Today.AddDays(-100), 100000), new Transaction(DateTime.Today.AddDays(-90), 10000) } ); var customer = new Customer("Oscar"); customer.AddAccount(account); var earned = customer.GetEarnedInterest(); var expected = 29.867d; Console.WriteLine("Expected: {0} Earned: {1}", expected, earned); Assert.AreEqual(expected, earned, Helper.TOLERANCE); } [Test] public void Should_Format_Statement() { var checking = new Account ( AccountType.Checking, new Transaction[] { new Transaction(DateTime.Today.AddDays(-200), 100000), new Transaction(DateTime.Today.AddDays(-190), 10000), new Transaction(DateTime.Today.AddDays(-150), -5000), new Transaction(DateTime.Today.AddDays(-100), 1000) } ); checking.Withdraw(6000); checking.Deposit(14001.99); var customer = new Customer("Oscar"); customer.AddAccount(checking); var calculated = customer.GetStatement(); var expected = "Statement for Oscar\nChecking Account\r\n deposit $100,000.00\r\n deposit $10,000.00\r\n withdrawal $5,000.00\r\n deposit $1,000.00\r\n withdrawal $6,000.00\r\n deposit $14,001.99\r\nTotal $114,001.99\n\nTotal In All Accounts $114,001.99"; Console.WriteLine("Expected: {0} calculated: {1}", expected, calculated); Assert.AreEqual(expected, calculated); } [Test] public void Should_Get_Summary_No_Accounts() { var customer = new Customer("George"); var calculated = customer.GetSummary(); var expected = "- George (no accounts)"; Console.WriteLine("Expected: {0} calculated: {1}", expected, calculated); Assert.AreEqual(expected, calculated); } [Test] public void Should_Get_Summary_One_Account() { var customer = new Customer("George"); customer.AddAccount(new Account(AccountType.Checking)); var calculated = customer.GetSummary(); var expected = "- George (1 account)"; Console.WriteLine("Expected: {0} calculated: {1}", expected, calculated); Assert.AreEqual(expected, calculated); } [Test] public void Should_Get_Summary_Three_Accounts() { var customer = new Customer("George"); customer.AddAccount(new Account(AccountType.Checking)); customer.AddAccount(new Account(AccountType.MaxiSavings)); customer.AddAccount(new Account(AccountType.Savings)); var calculated = customer.GetSummary(); var expected = "- George (3 accounts)"; Console.WriteLine("Expected: {0} calculated: {1}", expected, calculated); Assert.AreEqual(expected, calculated); } [Test] [ExpectedException(ExpectedMessage = Customer.INVALID_SOURCE_ACCOUNT)] public void Should_Fail_Transfer_From_Invalid_Account() { var fromAccount = new Account ( AccountType.Checking, new Transaction[] { new Transaction(DateTime.Today.AddDays(-100), 100000), new Transaction(DateTime.Today.AddDays(-90), 10000) } ); var toAccount = new Account ( AccountType.Checking, new Transaction[] { new Transaction(DateTime.Today.AddDays(-100), 100000), new Transaction(DateTime.Today.AddDays(-90), 10000) } ); var customer = new Customer("Tom"); customer.AddAccount(toAccount); customer.Transfer(fromAccount, toAccount, 1000); } [Test] [ExpectedException(ExpectedMessage = Customer.INVALID_TARGET_ACCOUNT)] public void Should_Fail_Transfer_To_Invalid_Account() { var fromAccount = new Account ( AccountType.Checking, new Transaction[] { new Transaction(DateTime.Today.AddDays(-100), 100000), new Transaction(DateTime.Today.AddDays(-90), 10000) } ); var toAccount = new Account ( AccountType.Checking, new Transaction[] { new Transaction(DateTime.Today.AddDays(-100), 100000), new Transaction(DateTime.Today.AddDays(-90), 10000) } ); var customer = new Customer("Tom"); customer.AddAccount(fromAccount); customer.Transfer(fromAccount, toAccount, 1000); } [Test] [ExpectedException(ExpectedMessage = Customer.INVALID_TRANSFER_AMOUNT)] public void Should_Fail_To_Transfer_Invalid_Amount([Values(-10, 0)] double amount) { var fromAccount = new Account ( AccountType.Checking, new Transaction[] { new Transaction(DateTime.Today.AddDays(-100), 100000), new Transaction(DateTime.Today.AddDays(-90), 10000) } ); var toAccount = new Account ( AccountType.Checking, new Transaction[] { new Transaction(DateTime.Today.AddDays(-100), 100000), new Transaction(DateTime.Today.AddDays(-90), 10000) } ); var customer = new Customer("Tom"); customer.AddAccount(fromAccount); customer.AddAccount(toAccount); customer.Transfer(fromAccount, toAccount, amount); } [Test] public void Should_Transfer_Amount([Values(1000, 5000, 110000)] double amount) { var fromAccount = new Account ( AccountType.Checking, new Transaction[] { new Transaction(DateTime.Today.AddDays(-100), 100000), new Transaction(DateTime.Today.AddDays(-90), 10000) } ); var toAccount = new Account(AccountType.Checking); var customer = new Customer("Tom"); customer.AddAccount(fromAccount); customer.AddAccount(toAccount); var fromBefore = fromAccount.GetCurrentBalance(); var toBefore = toAccount.GetCurrentBalance(); customer.Transfer(fromAccount, toAccount, amount); var fromAfter = fromAccount.GetCurrentBalance(); var toAfter= toAccount.GetCurrentBalance(); Assert.AreEqual(amount, fromBefore - fromAfter, Helper.DOUBLE_DELTA); Assert.AreEqual(amount, toAfter - toBefore, Helper.DOUBLE_DELTA); } } }
651121677500c0e7f04f8b745745f6e60348daff
C#
JDosX/Functal
/Source/FunctionScript/FunctionScript/FnFunctionPointer.cs
3.015625
3
using System; using System.Collections.Generic; namespace Functal { /// <summary> /// The generic interface for a function pointer. /// </summary> internal interface FnFunctionPointer { /// <summary> /// Gets the return type of the contained function reference /// </summary> /// <returns></returns> Type GetTypeOfObject(); /// <summary> /// Creates an FnObject using the contained function reference /// </summary> /// <param name="functionParameters">The parameters to use in the function call.</param> /// <param name="ghostParameters">The ghost parameters that can be accessed from the function implementation without declaring them.</param> /// <param name="isImmutableExecute"> /// The <see cref="FnVariable"/> used to determine if the function wil be immutably executed. /// </param> FnObject CreateObjectWithPointer(List<FnObject> functionParameters, Dictionary<String, FnObject> parameters, FnVariable<Boolean> isPreExecute); Type[] GetFunctionTypeArray(); } /// <summary> /// Stores a reference to a function with a list of FnObjects as the specified arguments, and can be used to create an /// FnObject containing the function reference. /// </summary> /// <typeparam name="T"></typeparam> internal class FnFunctionPointer<T> : FnFunctionPointer { /// <summary> /// The function reference this <see cref="FnFunctionPointer"/> wraps. /// </summary> public readonly FnFunction<T> Target; /// <summary> /// Constructor. /// </summary> /// <param name="target">The function reference to wrap.</param> public FnFunctionPointer(FnFunction<T> target) { // I shouldn't need to worry about creating a blank verion of the FnFunction, unless // I want to ensure the function provided isn't lugging unneccessary data around (potential security flaw). Target = target; } /// <summary> /// Gets the return type of the contained function reference. /// </summary> public Type GetTypeOfObject() { return typeof(T); } /// <summary> /// Creates an FnObject using the contained function reference /// </summary> /// <param name="functionParameters">The parameters to use in the function call.</param> /// <param name="ghostParameters">The ghost parameters that can be accessed from the function implementation without declaring them.</param> /// <param name="isImmutableExecute"> /// The <see cref="FnVariable"/> used to determine if the function wil be immutably executed. /// </param> public FnObject CreateObjectWithPointer(List<FnObject> functionParameters, Dictionary<String, FnObject> parameters, FnVariable<Boolean> isImmutableExecute) { return Target.CreateNewFunction(functionParameters, parameters, isImmutableExecute); } public Type[] GetFunctionTypeArray() { return Target.ArgumentTypes; } } }
e95495643a7def57e118853f1dab50d594792c9a
C#
profjordanov/CSharp-Web-Development-Basics
/Store/SoftStore/Views/Home/Index.cs
2.515625
3
using System.Collections.Generic; using System.IO; using System.Text; using SimpleMVC.Interfaces.Generic; using SoftStore.ViewModels; namespace SoftStore.Views.Home { public class Index : IRenderable<IEnumerable<HomeGameVm>> { public string Render() { string header = File.ReadAllText(Constants.ContentPath + Constants.HeaderHtml); string navigation = File.ReadAllText(Constants.ContentPath + Constants.NavigationLoggedHtml); string home = File.ReadAllText(Constants.ContentPath + Constants.HomeHtml); StringBuilder builder = new StringBuilder(); int counter = 0; foreach (HomeGameVm homeGameVm in Model) { if (counter != 0 && counter % 3 == 0) { builder.Append("</div>"); } if (counter % 3 == 0) { builder.Append("<div class=\"card-group\">"); } builder.Append(homeGameVm); counter++; } home = string.Format(home, builder); string footer = File.ReadAllText(Constants.ContentPath + Constants.FooterHtml); StringBuilder finalHtml = new StringBuilder(); finalHtml.Append(header); finalHtml.Append(navigation); finalHtml.Append(home); finalHtml.Append(footer); return finalHtml.ToString(); } public IEnumerable<HomeGameVm> Model { get; set; } } }
b1c3ad5571e5abee2c7835a7fb1c80a73d3fb065
C#
kudsu/CnBlogSubscribeTool
/src/CnBlogSubscribeTool/MailUtil.cs
2.734375
3
using System.Collections.Generic; using CnBlogSubscribeTool.Config; using MailKit.Net.Smtp; using MimeKit; namespace CnBlogSubscribeTool { /// <summary> /// send email /// </summary> public class MailUtil { private static bool SendMail(MimeMessage mailMessage,MailConfig config) { try { var smtpClient = new SmtpClient(); smtpClient.Timeout = 10 * 1000; //设置超时时间 smtpClient.Connect(config.Host, config.Port, MailKit.Security.SecureSocketOptions.None);//连接到远程smtp服务器 smtpClient.Authenticate(config.Address, config.Password); smtpClient.Send(mailMessage);//发送邮件 smtpClient.Disconnect(true); return true; } catch { throw; } } /// <summary> ///发送邮件 /// </summary> /// <param name="config">配置</param> /// <param name="receives">接收人</param> /// <param name="sender">发送人</param> /// <param name="subject">标题</param> /// <param name="body">内容</param> /// <param name="attachments">附件</param> /// <param name="fileName">附件名</param> /// <returns></returns> public static bool SendMail(MailConfig config,List<string> receives, string sender, string subject, string body, byte[] attachments = null,string fileName="") { var fromMailAddress = new MailboxAddress(config.Name, config.Address); var mailMessage = new MimeMessage(); mailMessage.From.Add(fromMailAddress); foreach (var add in receives) { var toMailAddress = new MailboxAddress(add); mailMessage.To.Add(toMailAddress); } if (!string.IsNullOrEmpty(sender)) { var replyTo = new MailboxAddress(config.Name, sender); mailMessage.ReplyTo.Add(replyTo); } var bodyBuilder = new BodyBuilder() { HtmlBody = body }; //附件 if (attachments != null) { if (string.IsNullOrEmpty(fileName)) { fileName = "未命名文件.txt"; } var attachment = bodyBuilder.Attachments.Add(fileName, attachments); //解决中文文件名乱码 var charset = "GB18030"; attachment.ContentType.Parameters.Clear(); attachment.ContentDisposition.Parameters.Clear(); attachment.ContentType.Parameters.Add(charset, "name", fileName); attachment.ContentDisposition.Parameters.Add(charset, "filename", fileName); //解决文件名不能超过41字符 foreach (var param in attachment.ContentDisposition.Parameters) param.EncodingMethod = ParameterEncodingMethod.Rfc2047; foreach (var param in attachment.ContentType.Parameters) param.EncodingMethod = ParameterEncodingMethod.Rfc2047; } mailMessage.Body = bodyBuilder.ToMessageBody(); mailMessage.Subject = subject; return SendMail(mailMessage, config); } } }
7619fb8b218c0dc18f36a3f87bf3cfd6eafdf60b
C#
15831944/autodesk-inventor-powertools
/StevenVolckaert.Libraries/StevenVolckaert.Web.Mvc/Extensions/HtmlHelperExtensions.cs
2.734375
3
using System; using System.Collections.Generic; using System.Web.Mvc; using System.Web.Mvc.Html; using System.Web.Routing; using StevenVolckaert.Globalization; namespace StevenVolckaert.Web.Mvc { /// <summary> /// Provides extension methods for System.Web.Mvc.HtmlHelper objects. /// </summary> public static class HtmlHelperExtensions { /// <summary> /// Returns a combo box that's used to set the language, /// using the specified HTML helper and the name of the form field. /// </summary> /// <param name="htmlHelper">The HTML helper instance that this method extends.</param> /// <param name="name">The name of the form field to return.</param> /// <param name="cultureRouteKey"></param> /// <param name="routeName"></param> /// <exception cref="ArgumentNullException"><paramref name="htmlHelper"/> is <c>null</c>.</exception> /// <exception cref="ArgumentException"><paramref name="name"/>, <paramref name="cultureRouteKey"/>, or /// <paramref name="routeName"/> is <c>null</c>, empty, or white space.</exception> public static MvcHtmlString LanguageComboBox(this HtmlHelper htmlHelper, string name, string cultureRouteKey, string routeName) { if (htmlHelper == null) throw new ArgumentNullException("htmlHelper"); if (String.IsNullOrWhiteSpace(name)) throw new ArgumentException(StevenVolckaert.Properties.Resources.ValueNullEmptyOrWhiteSpace, "name"); if (String.IsNullOrWhiteSpace(cultureRouteKey)) throw new ArgumentException(StevenVolckaert.Properties.Resources.ValueNullEmptyOrWhiteSpace, "cultureRouteKey"); if (String.IsNullOrWhiteSpace(routeName)) throw new ArgumentException(StevenVolckaert.Properties.Resources.ValueNullEmptyOrWhiteSpace, "routeName"); var itemList = new List<SelectListItem>(); var cultureManager = Container.Current.GetExportedValue<CultureManager>(); foreach (var cultureInfo in cultureManager.SupportedCultures.Values) itemList.Add( new SelectListItem { Selected = cultureManager.IsCultureSelected(cultureInfo.Name), Text = cultureInfo.NativeName, Value = GetGlobalizedUrl(htmlHelper, cultureInfo.Name, cultureRouteKey, routeName) } ); return htmlHelper.DropDownList(name, itemList, new { onchange = "window.location.replace(this.value)" }); } //public static MvcHtmlString LanguageHyperLink(this HtmlHelper htmlHelper, string cultureName, string selectedText, string unselectedText, string routeName, IDictionary<string, object> htmlAttributes, string languageRouteName = "language", bool strictSelected = false) //{ // /* TODO Implement this extension method. See <http://geekswithblogs.net/shaunxu/archive/2010/05/06/localization-in-asp.net-mvc-ndash-3-days-investigation-1-day.aspx>. // * Steven Volckaert. January 8, 2012. // */ // throw new NotImplementedException(); // /* // var routeValueDictionary = GetRouteValueDictionary(htmlHelper); // // Add the culture name to the route values. // routeValueDictionary["language"] = cultureName; // return htmlHelper.RouteLink(selectedText, routeName, routeValueDictionary, htmlAttributes); // */ //} /// <summary> /// Returns a date in the language of the application's current culture. /// </summary> /// <param name="htmlHelper">The HTML helper instance that this method extends.</param> /// <param name="year">The year (1 through 9999).</param> /// <param name="month">The month (1 through 12).</param> /// <param name="day">The day (1 through the number of days in month).</param> /// <exception cref="ArgumentNullException"><paramref name="htmlHelper"/> is <c>null</c>.</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="year"/> is less than 1 or greater than 9999, or is less than 1 or greater /// than 12, or <paramref name="day"/> is less than 1 or greater than the number of days in <paramref name="month"/>.</exception> /// <example>Friday, February 27, 2009</example> public static MvcHtmlString LocalizedDate(this HtmlHelper htmlHelper, int year, int month, int day) { if (htmlHelper == null) throw new ArgumentNullException("htmlHelper"); return new MvcHtmlString(new DateTime(year, month, day).ToString("D", Container.Current.GetExportedValue<CultureManager>().CurrentCulture)); } private static string GetGlobalizedUrl(HtmlHelper htmlHelper, string cultureName, string cultureRouteKey, string routeName) { var routeValueDictionary = GetRouteValueDictionary(htmlHelper); // Add the culture name to the route values. routeValueDictionary[cultureRouteKey] = cultureName; // Return the globalized URL. var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext, htmlHelper.RouteCollection); return urlHelper.RouteUrl(routeName, routeValueDictionary); } private static RouteValueDictionary GetRouteValueDictionary(HtmlHelper htmlHelper) { // Get the route values from the HTML helper's view context. var routeValueDictionary = new RouteValueDictionary(htmlHelper.ViewContext.RouteData.Values); // Copy the query strings into the route values. var queryString = htmlHelper.ViewContext.HttpContext.Request.QueryString; foreach (string key in queryString) if (queryString[key] != null && !String.IsNullOrWhiteSpace(key)) if (routeValueDictionary.ContainsKey(key)) routeValueDictionary[key] = queryString[key]; else routeValueDictionary.Add(key, queryString[key]); return routeValueDictionary; } } }
37a3d52d074e59ca26e0a25b9b2c5e2776fc22c4
C#
sand-foam/MiniGame
/Assets/Scripts/MonoSingleton.cs
2.625
3
using System.Collections; using System.Collections.Generic; using UnityEngine; public abstract class MonoSingleton<T> : MonoBehaviour where T : MonoSingleton<T> { #region 单例 protected static T s_Instance; public static T Instance { get { if (s_Instance != null) return s_Instance; s_Instance = FindObjectOfType<T>(); if (s_Instance != null) return s_Instance; return s_Instance; } } #endregion // //可以重写的Awake虚方法,用于实例化对象 // protected virtual void Awake() //{ // s_Instance = this as T; //} }
f15e6ea60d56e09fbbe3838120b7d5aa5ca080cd
C#
proniphy/abstraction
/Abstract-Classes/Biplane.cs
3
3
using System; using System.Collections.Generic; using System.Text; namespace Abstract_Classes { public class Biplane : Plane { public override string Type { get { return "Bilane"; } } public override int Speed { get { return 400; } } public void LandWithEngineOff() { Console.WriteLine("Biplane has landed with engine off!"); } } }
b078291ddb1013bb1069d5c932cea97b40fe8365
C#
sama-network/Sama.Api
/src/Sama.Services/Ngos/ChildService.cs
2.734375
3
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Sama.Core.Domain.Ngos; using Sama.Core.Domain.Ngos.Repositories; using Sama.Services.Ngos.Dtos; namespace Sama.Services.Ngos { public class ChildService : IChildService { private readonly INgoRepository _ngoRepository; public ChildService(INgoRepository ngoRepository) { _ngoRepository = ngoRepository; } public async Task AddAsync(Guid ngoId, params ChildInfoDto[] children) => await ExecuteAsync(ngoId, children, (n,c) => n.AddChildren(c)); public async Task EditAsync(Guid ngoId, params ChildInfoDto[] children) => await ExecuteAsync(ngoId, children, (n,c) => n.EditChildren(c)); private async Task ExecuteAsync(Guid ngoId, IList<ChildInfoDto> children, Action<Ngo,IEnumerable<Child>> action) { if (children == null || !children.Any()) { throw new ServiceException("children_not_provided", $"Children were not provided for NGO with id: '{ngoId}'."); } var ngo = await _ngoRepository.GetAsync(ngoId); if (ngo == null) { throw new ServiceException("ngo_not_found", $"NGO with id: '{ngoId}' was not found."); } var ngoChildren = children.Select(x => new Child(x.Id, x.FullName, x.Gender, x.Birthdate, x.Notes, x.NeededFunds > 0 ? x.NeededFunds : ngo.FundsPerChild)); action(ngo, ngoChildren); await _ngoRepository.UpdateAsync(ngo); } } }
541c3028dec7815ab69ada6e8701a65038ef7e5b
C#
ZhiyueZhao/NetZhiyueZhao
/DataTier/Data.cs
3.28125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.OleDb; using System.Data; namespace DataTier { public abstract class Data { #region Attributes private OleDbConnection _connection; private OleDbDataAdapter _adapter; private OleDbCommandBuilder _commandBuilder; private DataSet _dataSet; private string _connectionString; private string _tableName; private string _selectQuery; #endregion #region Constructors /// <summary> /// Constructs an new Data object. /// </summary> /// <param name="connectionString">The connection string to the data source.</param> /// <param name="tableName">The name of the table added to the dataset.</param> /// <param name="selectQuery">The Select query for the SelectCommand.</param> public Data(string connectionString, string tableName, string selectQuery) { _connectionString = connectionString; _tableName = tableName; _selectQuery = selectQuery; // 1. Establishes a connection to the database _connection = new OleDbConnection(_connectionString); //open the connection _connection.Open(); // 2.Generates INSERT, UPDATE and DELETE commands _adapter = new OleDbDataAdapter(_selectQuery, _connection); _commandBuilder = new OleDbCommandBuilder(_adapter); // 3 Populates the DataSet _dataSet = new DataSet(); _adapter.Fill(_dataSet, _tableName); _adapter.RowUpdated += new OleDbRowUpdatedEventHandler(DataAdapter_RowUpdated); } #endregion #region Event Handlers /// <summary> /// the event handler that to automatic assign the current ID+1 to the new added row /// </summary> void DataAdapter_RowUpdated(object sender, OleDbRowUpdatedEventArgs e) { // When the update is an Insert (new record) if (e.StatementType == StatementType.Insert) { // Creates a new command // @@IDENTITY - a database function that returns the last-inserted identity (autonumber) value OleDbCommand cmd = new OleDbCommand("SELECT @@IDENTITY", _connection); // Assigns the ID value of the new row in the database to the DataColumn "ID" of the new // DataRow in the DataTable // *** // ExecuteScalar - Executes the command and returns the value of first column of the first row // e.Row - reference to the DataRow added to the DataTable // e.Row["ID"] - reference to the "ID" DataColumn in the DataRow e.Row["ID"] = (int)cmd.ExecuteScalar(); } } #endregion #region Methods /// <summary> /// Return the DataTable from the dataset. /// </summary> /// <returns>The DataTable from the dataset.</returns> public DataTable GetAllRows() { return _dataSet.Tables[this._tableName]; } /// <summary> /// Updates the changes made to the dataset to the data source. /// </summary> public void Update() { _adapter.Update(_dataSet.Tables[_tableName]); } /// <summary> /// Closes the connection to the database. /// </summary> public void Close() { _connection.Close(); } #endregion } }
7f89d00fb669b5f2abc712c26b57a74807d829d2
C#
PlumpMath/DesignPatterns-234
/Adapter/TextView.cs
2.8125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DesignPatterns { public class TextView { public TextView() { } public void GetOrigin(Coord x, Coord y) { } public void GetExtent(Coord width, Coord height) { } public virtual Boolean IsEmpty() { return true; } } }
006ad2223e0c3c981e42f172fd3b7a5b4bbdabd0
C#
maxBlaze101/csharp-exercises
/CountingCharacters/Program.cs
3.859375
4
using System; using System.Collections.Generic; namespace CountingCharacters { class Program { static void Main(string[] args) { Dictionary<char, int> Counts = new Dictionary<char, int>(); Console.WriteLine("Please enter a phrase:"); string babel = Console.ReadLine(); char[] characters = babel.ToCharArray(); foreach (char character in characters) { if (Counts.ContainsKey(character)) { Counts[character] = Counts[character] + 1; } else { Counts.Add(character, 1); } } foreach (KeyValuePair<char, int> Count in Counts) { Console.WriteLine("There are " + Count.Value + " of " + Count.Key); } Console.ReadLine(); } } }
ac51c1b74d7b2e0af9425f0746aa8cf45aa9c29f
C#
mamun-131/COMP123-S2016-AbstractPlanet
/AbstractPlanets/Program.cs
3.328125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; /* *Author: Md Mamunur Rahman * Student ID: 300872772 * * Date: July 07, 2016 * Description: This program demonstrates a game named 'Abstract Planet', * * Version: 0.0.4 - added all comments and colose the project */ namespace AbstractPlanets { /** * This class is the "driver" class for our Program * * @class Program */ class Program { /** * the main method for our driver class Program * * @method Main * @param {sting[]} args */ static void Main(string[] args) { //Call Display Logo method DisplayLogo(); Console.WriteLine(" GIANT PLANET"); Console.WriteLine(" ------------"); //create instance of the PlanetType Enum string planetType = Enum.GetName(typeof(PlanetType), PlanetType.Ice); //create instance of the GiantPlanet class GiantPlanet giantPlanet = new GiantPlanet(planetType, "Jupiter", 142984, 317.83); Console.WriteLine(giantPlanet.ToString()); Console.WriteLine(); Console.WriteLine(" TERRESTRIAL PLANET"); Console.WriteLine(" ------------------"); //create instance of the TerrestrialPlanet class TerrestrialPlanet terrestrialPlanet = new TerrestrialPlanet(false, "Mars", 1000, .11); Console.WriteLine(terrestrialPlanet.ToString()); Console.ReadKey(); } //PUBLIC METHOD+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ /** * <summary> * This is the static void method to make decoration logo. * </summary> * * @method DisplayLogo * @return {void} * */ public static void DisplayLogo() { Console.ForegroundColor = ConsoleColor.Red; Thread.Sleep(400); Console.WriteLine(" ************"); Thread.Sleep(400); Console.WriteLine(" ********************"); Thread.Sleep(400); Console.WriteLine(" ************************"); Thread.Sleep(400); Console.WriteLine(" ***************************"); Thread.Sleep(400); Console.WriteLine("*****************************"); Thread.Sleep(400); Console.Write("******"); Console.ForegroundColor = ConsoleColor.Green; Console.Write("ABSTRACT PLANET"); Console.ForegroundColor = ConsoleColor.Red; Console.Write("********\n"); Thread.Sleep(400); Console.WriteLine("*****************************"); Thread.Sleep(400); Console.WriteLine(" ***************************"); Thread.Sleep(400); Console.WriteLine(" ************************"); Thread.Sleep(400); Console.WriteLine(" ********************"); Thread.Sleep(400); Console.WriteLine(" ************"); Thread.Sleep(400); Console.ForegroundColor = ConsoleColor.Cyan; Console.WriteLine(); } } }
ca4b787baa0d1b0431e6d62e4932a7d9be96cbc1
C#
indra-ipd/Element-Placement-on-PCB-using-Genetic-Algorithms
/Assets/Scripts/GA/Generation.cs
3.09375
3
using System; namespace GeneticAlgorithm { public class Generation { public Person[] p; public static double SumFitness = 0; public Generation(int n) { p = new Person[n]; for (int i = 0; i < n; i++) { p[i] = new Person(); //особи } } public void decode() { for (int i = 0; i < p.Length; i++) { Decode(p[i]); } } public void decodeTest() { for (int i = 0; i < p.Length; i++) { DecodeTest(p[i]); } if (DataStorage.F1Min < DataStorage.F2Min) { DataStorage.p2 = DataStorage.F1Min / DataStorage.F2Min; DataStorage.p1 = 1 - DataStorage.p2; } else { DataStorage.p1 = DataStorage.F2Min / DataStorage.F1Min; DataStorage.p2 = 1 - DataStorage.p1; } DataStorage.p2_start = DataStorage.p2; DataStorage.p1_start = DataStorage.p1; } static int IndexOfMaxKM(Person p1) { int max = 0; int S = 0; int index = -1; for (int z = 0; z < DataStorage.N; z++) { if (DataStorage.cm[z].used == 0) { S = DataStorage.cm[z].Width * DataStorage.cm[z].Height; if (S > max) { index = z; max = S; } } } return index; } static int IndexOfMinKM(Person p1) { int min = int.MaxValue; int S = 0; int index = 0; for (int z = 0; z < DataStorage.N; z++) { if (DataStorage.cm[z].used == 0) { S = DataStorage.cm[z].Width * DataStorage.cm[z].Height; if (S < min) { index = z; min = S; } } } return index; } static void Rotate(int index) { int temp = DataStorage.cm[index].Height; DataStorage.cm[index].Height = DataStorage.cm[index].Width; DataStorage.cm[index].Width = temp; } static void FindPlace(int index) //i - текущая особь, index - размещаемый элемент { bool ok = false; //флаг продолжения работы for (int h = 0; h < (PP.Height - DataStorage.cm[index].Height); h++) //ДРП по вертикали { if (ok) //если элемент размещен break; //выход из цикла for (int w = 0; w < (PP.Width - DataStorage.cm[index].Width); w++) //по горизонтали { if (PP.Plate[w, h] == -1) //если не занято { if (PP.Plate[w, h + DataStorage.cm[index].Height - 1] == -1) for (int ht = h; ht < (h + DataStorage.cm[index].Height); ht++) //по вертикали { if (PP.Plate[w, ht] == -1) //если не занято ok = true; else //если занято { ok = false; //дальше не смотреть break; //выход из цикла } } else { ok = false; } if (ok) //если по вертикали было свободно { if (PP.Plate[w + DataStorage.cm[index].Width - 1, h] == -1) for (int wt = w; wt < (w + DataStorage.cm[index].Width); wt++) //по горизонтали { if (PP.Plate[wt, h] == -1) ok = true; else { ok = false; break; } } else { ok = false; } } if (ok) //если и по горизонтали и по вертикали свободно { SetElem(w, h, index); break; //выход из цикла } } } } } static void SetElem(int x, int y, int index) { DataStorage.cm[index].x = x; DataStorage.cm[index].y = y; //задаются координаты элемента int max1 = (y + DataStorage.cm[index].Height); //пределы для цикла int max2 = (x + DataStorage.cm[index].Width); for (int wt = x; wt < max2; wt++) { for (int ht = y; ht < max1; ht++) { PP.Plate[wt, ht] = index; //на ДРП занимается место } } DataStorage.cm[index].used = index + 1; //метка о том, что элемент размещен if (DataStorage.cm[index].Height < DataStorage.cm[index].Width) //горизонтально { DataStorage.cm[index].isVertical = false; } else { DataStorage.cm[index].isVertical = true; } } public static void Decode(Person p1) { int plateHeight = 0; PP.Refresh(); for (int j = 0; j < DataStorage.N; j++) { DataStorage.cm[j].Refresh(); } int index = -1; for (int j = 0; j < DataStorage.N; j++) { switch (p1.Chromosome.Genes[j]) //декодирование гена и размещение по эвристикам { case 1: { index = IndexOfMaxKM(p1); //Самый большой из неразмещенных элементов if (DataStorage.cm[index].Height > DataStorage.cm[index].Width) //горизонтально { Rotate(index); } FindPlace(index); //разместить элемент break; } case 2: { index = IndexOfMaxKM(p1); if (DataStorage.cm[index].Height < DataStorage.cm[index].Width) { Rotate(index); } FindPlace(index); break; } case 3: { index = IndexOfMinKM(p1); if (DataStorage.cm[index].Height > DataStorage.cm[index].Width) { Rotate(index); } FindPlace(index); break; } case 4: { index = IndexOfMinKM(p1); if (DataStorage.cm[index].Height < DataStorage.cm[index].Width) { Rotate(index); } FindPlace(index); break; } } if (DataStorage.cm[index].isVertical) { if (plateHeight < DataStorage.cm[index].y + DataStorage.cm[index].Height) plateHeight = DataStorage.cm[index].y + DataStorage.cm[index].Height; } else { if (plateHeight < DataStorage.cm[index].y + DataStorage.cm[index].Width) plateHeight = DataStorage.cm[index].y + DataStorage.cm[index].Width; } } PP.Height = plateHeight; p1.F = F(); SumFitness += 1 / p1.F; if (p1.F < DataStorage.Best) { DataStorage.Best = p1.F; DataStorage.BestPerson = p1; } } static void DecodeTest(Person p1) { PP.Refresh(); for (int j = 0; j < DataStorage.N; j++) { DataStorage.cm[j].Refresh(); } for (int j = 0; j < DataStorage.N; j++) { switch (p1.Chromosome.Genes[j]) //декодирование гена и размещение по эвристикам { case 1: { int index = IndexOfMaxKM(p1); //Самый большой из неразмещенных элементов if (DataStorage.cm[index].Height > DataStorage.cm[index].Width) //горизонтально { Rotate(index); } FindPlace(index); //разместить элемент break; } case 2: { int index = IndexOfMaxKM(p1); if (DataStorage.cm[index].Height < DataStorage.cm[index].Width) { Rotate(index); } FindPlace(index); break; } case 3: { int index = IndexOfMinKM(p1); if (DataStorage.cm[index].Height > DataStorage.cm[index].Width) { Rotate(index); } FindPlace(index); break; } case 4: { int index = IndexOfMinKM(p1); if (DataStorage.cm[index].Height < DataStorage.cm[index].Width) { Rotate(index); } FindPlace(index); break; } } } FMin(); } static double F() { double F1 = 0, F2 = 0, fx, fy, d; //целевая функция, расстояние по x, расстояние по y for (int i = 0; i < DataStorage.N; i++) for (int j = i + 1; j < DataStorage.N; j++) { fx = Math.Pow(DataStorage.cm[i].x + (double)DataStorage.cm[i].Width / 2 - DataStorage.cm[j].x + (double)DataStorage.cm[j].Width / 2, 2); fy = Math.Pow(DataStorage.cm[i].y + (double)DataStorage.cm[i].Height / 2 - DataStorage.cm[j].y + (double)DataStorage.cm[j].Height / 2, 2); d = Math.Sqrt(fx + fy); if (DataStorage.C[i, j] != 0) { F1 += d * DataStorage.C[i, j]; } F2 += d * Math.Abs((DataStorage.cm[i].pwDissipation - DataStorage.cm[j].pwDissipation)); } double F = (DataStorage.p1 * F1 + DataStorage.p2 * F2); // получить аддитивную функцию от двух частных критериев return F; } static void FMin() { double F1 = 0, F2 = 0, fx, fy, d; //целевая функция, расстояние по x, расстояние по y for (int i = 0; i < DataStorage.N; i++) for (int j = i + 1; j < DataStorage.N; j++) { fx = Math.Pow(DataStorage.cm[i].x + (double)DataStorage.cm[i].Width / 2 - DataStorage.cm[j].x + (double)DataStorage.cm[j].Width / 2, 2); fy = Math.Pow(DataStorage.cm[i].y + (double)DataStorage.cm[i].Height / 2 - DataStorage.cm[j].y + (double)DataStorage.cm[j].Height / 2, 2); d = Math.Sqrt(fx + fy); if (DataStorage.C[i, j] != 0) { F1 += d * DataStorage.C[i, j]; } F2 += d * Math.Abs((DataStorage.cm[i].pwDissipation - DataStorage.cm[j].pwDissipation)); } if (F1 < DataStorage.F1Min) DataStorage.F1Min = F1; if (F2 < DataStorage.F2Min) DataStorage.F2Min = F2; } public void Mutation() { Random rnd = new Random(); //выбор случайных особей для мутации int t; for (int z = 0; z < DataStorage.NMut; z++) { t = rnd.Next(0, p.Length); p[t].Chromosome.Mutation(); } } } }
63b4664a6737d51224ce82442a5eccab3e7ca484
C#
fintyara/Animals
/Foods/Scripts/TreeHaveFood.cs
2.671875
3
using System.Collections.Generic; using UnityEngine; namespace CollectCreatures { public class TreeHaveFood : HaveFood { #region VAR [SerializeField] private List<AppleFood> _appleFoods = new List<AppleFood>(); private List<int> _selected = new List<int>(); #endregion #region FUNC public override bool CheckHaveFood() { for (int i = 0; i < _appleFoods.Count; i++) { if (_appleFoods[i].HaveFood && !_appleFoods[i].Busy) return true; } return false; } public override Food GetFood() { for (int i = 0; i < _appleFoods.Count; i++) { if (_appleFoods[i].HaveFood && !_appleFoods[i].Busy) return _appleFoods[i].GetFood(); } return null; } public override void AddFood() { Food emptyFood = GetEmptyFood(); if (emptyFood == null) return; emptyFood.AddFood(); } public override void DeleteOneFood(int count) { for (int i = 0; i < _appleFoods.Count; i++) { if (_appleFoods[i].HaveFood) { _appleFoods[i].DeleteFood(); return; } } } public override void DeleteAllFood() { for (int i = 0; i < _appleFoods.Count; i++) { if (_appleFoods[i].HaveFood) { _appleFoods[i].DeleteFood(); } } } private Food GetEmptyFood() { _selected.Clear(); for (int i = 0; i < _appleFoods.Count; i++) if (!_appleFoods[i].HaveFood) _selected.Add(i); if (_selected.Count == 0) return null; var randomIndex = _selected[Random.Range(0, _selected.Count)]; return _appleFoods[randomIndex]; } #endregion } }
3a58211b9b8977ccd239f21e0a507dbb4f17c0f5
C#
Jaco-van-Stryp/BIDataHack
/BiDataHack 2020/VotingFormMainUI.cs
2.625
3
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace BiDataHack_2020 { public partial class VotingFormMainUI : Form { mainBackend mb = new mainBackend(); public VotingFormMainUI() { InitializeComponent(); String localLocation = Directory.GetCurrentDirectory(); string readText = File.ReadAllText(localLocation + "\\settingsFile.db"); string readCode = File.ReadAllText(localLocation + "\\VotingSettings\\" + readText + "\\vote.db"); String[] values = mb.Decrypt(readCode).Split('♥'); label1.Text = values[0]; label2.Text = values[1]; label3.Text = values[2]; label5.Text = values[3]; } private void button2_Click(object sender, EventArgs e) { Form1 mm = new Form1(); mm.Show(); this.Hide(); } private void label5_Click(object sender, EventArgs e) { } private void button1_Click(object sender, EventArgs e) { mainBackend mb = new mainBackend(); String localLocation = Directory.GetCurrentDirectory() + "//Registrations"; if (String.IsNullOrEmpty(nameVal.Text)); { bool found = false; String userName = nameVal.Text + " " + surnameVal.Text; String locatedFile = ""; string[] files = new DirectoryInfo(localLocation).GetFiles().Select(o => o.Name).ToArray(); for (int i = 0; i < files.Length; i++) { String nameTest = files[i].Substring(0, files[i].Length-3); if(userName.ToLower().Equals(nameTest.ToLower())) { found = true; localLocation = localLocation + "//" + nameTest + ".db"; break; } } if(found == true) { string text = System.IO.File.ReadAllText(localLocation); string[] datafile = mb.Decrypt(text).Split('♥'); if(datafile[4].Equals("Vote") || datafile[4].Equals("Both")) { if(datafile[3].Equals(idVal.Text.ToString().Trim())) { using (StreamWriter writetext = new StreamWriter("temp.db")) { writetext.WriteLine(text); } MainVotingSection mvs = new MainVotingSection(); mvs.Show(); this.Hide(); } else { MessageBox.Show("You are not authenticated to vote, Sorry!", "Error"); this.Hide(); this.Show(); } } else { MessageBox.Show("You are not allowed to vote, Sorry!" + datafile[0] + datafile[1] + datafile[2] + datafile[3] + datafile[4], "Error"); this.Hide(); this.Show(); } } else { MessageBox.Show("We didnt find you in the system, sorry about that!", "Error"); this.Hide(); this.Show(); } } } } }
19bc15e9ec968464160208a4c407a4957b4c1e53
C#
Ziagl/DevBlogProjects-CSharp
/RaspberryPiGPIO/Program.cs
2.625
3
using System; namespace RaspberryPiGPIO { class Program { static void Main(string[] args) { int pinId = 14; GPIOControl control = new GPIOControl(); while(true) { Console.WriteLine("Pin Status: " + control.GetPinStatus(pinId)); } } } }
5252a5ac489c933d0171fb425cf2642f9c5e8e2a
C#
davyraes/CSharpPF
/TussentijdseOefening/boek.cs
2.90625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TussentijdseOefening { public abstract class boek:IVoorwerpen,IAankoop { public boek(string titel,string auteur,decimal aankoopprijs,Genre genre) { this.Titel = titel; this.Auteur = auteur; this.aankoopPrijs = aankoopprijs; this.Genre = genre; } static boek() { Eigenaar = "VDAB"; } private string titelValue; public string Titel { get { return titelValue; } set { if (value != null) titelValue = value; } } private string auteurValue; public string Auteur { get { return auteurValue; } set { if (value != null) auteurValue = value; } } private static string eigenaarValue; private static string Eigenaar { get { return eigenaarValue; } set { if (value != null) eigenaarValue = value; } } public Genre Genre { get; set; } public abstract decimal winst { get; } private decimal aankoopPrijsValue; public decimal aankoopPrijs { get { return aankoopPrijsValue; } set { if (value > 0) aankoopPrijsValue = value; } } public virtual void GegevensTonen() { Console.WriteLine("Titel : {0}", Titel); Console.WriteLine("Auteur : {0}", Auteur); Console.WriteLine("Eigenaar : {0}", Eigenaar); Console.WriteLine("Aankoopprijs : {0} euro", aankoopPrijs); Console.WriteLine("genre : {0}",Genre.Naam); Console.WriteLine("doelgroep leeftijd : {0}",Genre.DoelGroep.Leeftijd); Console.WriteLine("doelgroep categorie : {0}",Genre.DoelGroep.Categorie); } } }
25bbd8d0cfa9b7c0ef3fdb880afb3e891987bda3
C#
awekisa/ProgrammingBasics
/03. Console Input Output/03. Circle Perimeter and Area/CirclePerimeterAndArea.cs
3.8125
4
using System; class CirclePerimeterAndArea { static void Main() { double radius = double.Parse(Console.ReadLine()); double pi = 3.1415926; double perimeter = pi * 2 * radius; double area = pi * (radius * radius); Console.WriteLine("Perimeter is {0:F2}, area is {1:F2}", perimeter, area); } }
56bed18d434b923091f0968c10d3fe0e46e7c257
C#
gradusina/FA2
/FA2/Ftp/FtpClient.cs
2.515625
3
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Text.RegularExpressions; namespace FA2.Ftp { internal class FtpClient : WebClient { //protected override WebRequest GetWebRequest(Uri address) //{ // var request = (FtpWebRequest) base.GetWebRequest(address); // if (request == null) return base.GetWebRequest(address); // request.UsePassive = false; // return request; //} //private FtpWebRequest _ftpWebRequest; private string _path; private const int BufferSize = 2048; public bool Passive { get; set; } public bool Binary { get; set; } public bool EnableSsl { get; set; } public string CurrentPath { get { return _path; } set { _path = value; } } public string ParentUri { get { //var index = _path.LastIndexOf("/", StringComparison.Ordinal); //return _path.Remove(index); return GetParrentDictionary(_path); } } public FtpClient(string path, string userName, string password) { _path = path; Passive = true; Binary = true; EnableSsl = false; Credentials = new NetworkCredential(userName, password); } public string DeleteFile(string filePath) { var ftpWebRequest = CreateRequest(filePath, WebRequestMethods.Ftp.DeleteFile); try { return GetStatusDescription(ftpWebRequest); } catch (Exception) { return null; } } public string FtpDownloadFile(string fileName, string dest) { var ftpWebRequest = CreateRequest(Combine(_path, fileName), WebRequestMethods.Ftp.DownloadFile); var buffer = new byte[BufferSize]; try { var response = (FtpWebResponse) ftpWebRequest.GetResponse(); var stream = response.GetResponseStream(); using (var fs = new FileStream(dest, FileMode.OpenOrCreate)) { if (stream == null) return response.StatusDescription; var readCount = stream.Read(buffer, 0, BufferSize); while (readCount > 0) { fs.Write(buffer, 0, readCount); readCount = stream.Read(buffer, 0, BufferSize); } } var status = response.StatusDescription; ftpWebRequest.Abort(); if (response != null) response.Close(); return status; } catch (Exception) { return null; } } public DateTime GetDateTimestamp(string filePath) { var ftpWebRequest = CreateRequest(filePath, WebRequestMethods.Ftp.GetDateTimestamp); try { var response = (FtpWebResponse) ftpWebRequest.GetResponse(); DateTime lastMod = response.LastModified; ftpWebRequest.Abort(); if (response != null) response.Close(); return lastMod; } catch (Exception) { return new DateTime(); } } public long GetFileSize(string filePath) { var ftpWebRequest = CreateRequest(filePath, WebRequestMethods.Ftp.GetFileSize); try { var response = (FtpWebResponse) ftpWebRequest.GetResponse(); var length = response.ContentLength; ftpWebRequest.Abort(); if (response != null) response.Close(); return length; } catch (Exception) { return 0; } } public IEnumerable<string> ListDirectory() { var list = new List<string>(); var ftpWebRequest = CreateRequest(WebRequestMethods.Ftp.ListDirectory); try { var response = (FtpWebResponse) ftpWebRequest.GetResponse(); var stream = response.GetResponseStream(); if (stream == null) return list.ToArray(); using (var reader = new StreamReader(stream)) { while (!reader.EndOfStream) { list.Add(reader.ReadLine()); } } ftpWebRequest.Abort(); if (response != null) response.Close(); } catch (WebException) { } return list.ToArray(); } public IEnumerable<FtpFileDirectoryInfo> ListDirectoryDetails() { var stringsList = new List<string>(); var list = new List<FtpFileDirectoryInfo>(); var ftpWebRequest = CreateRequest(WebRequestMethods.Ftp.ListDirectoryDetails); var regex = new Regex( @"^([d-])([rwxt-]{3}){3}\s+\d{1,}\s+.*?(\d{1,})\s+(\w+\s+\d{1,2}\s+(?:\d{4})?)(\d{1,2}:\d{2})?\s+(.+?)\s?$", RegexOptions.Compiled | RegexOptions.Multiline | RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace); try { var response = (FtpWebResponse) ftpWebRequest.GetResponse(); var stream = response.GetResponseStream(); if (stream != null) //using (var reader = new StreamReader(stream, Encoding.GetEncoding(1251), true)) using (var reader = new StreamReader(stream)) { while (!reader.EndOfStream) { stringsList.Add(reader.ReadLine()); } } ftpWebRequest.Abort(); if (response != null) response.Close(); if (stringsList.Count == 0) return list; list = stringsList.AsEnumerable().Select(s => { var match = regex.Match(s); if (match.Length > 5) { var dirInfo = match.Groups[1].Value; var fileSize = string.Empty; if (dirInfo != "d") fileSize = match.Groups[3].Value.Trim(); var permissions = match.Groups[2].Value; var date = match.Groups[4].Value; var convertedDate = DateTime.Parse(date, new CultureInfo("en-US")); date = convertedDate.ToString("dd.MM.yyyy"); var time = string.IsNullOrEmpty(match.Groups[5].Value) ? "00:00" : match.Groups[5].Value; var fileName = match.Groups[6].Value; return new FtpFileDirectoryInfo(dirInfo, permissions, fileSize, date, time, fileName, Combine(_path, fileName)); } return new FtpFileDirectoryInfo(); }).ToList(); } catch (WebException) { } return list; } public string MakeDirectory(string directoryPath) { var parrentPath = directoryPath; string description; // Find first, exist parrent directory while (!DirectoryExist(parrentPath)) { parrentPath = GetParrentDictionary(parrentPath); } do { var childDirectory = directoryPath; // Get child directory while (parrentPath != GetParrentDictionary(childDirectory)) { childDirectory = GetParrentDictionary(childDirectory); } parrentPath = childDirectory; // Creating directory var ftpWebRequest = CreateRequest(parrentPath, WebRequestMethods.Ftp.MakeDirectory); try { description = GetStatusDescription(ftpWebRequest); } catch (WebException) { return null; } } while (parrentPath != directoryPath); return description; } public string PrintWorkingDirectory() { var ftpWebRequest = CreateRequest(WebRequestMethods.Ftp.PrintWorkingDirectory); try { return GetStatusDescription(ftpWebRequest); } catch (Exception) { return null; } } public string RemoveDirectory(string directoryPath) { var ftpWebRequest = CreateRequest(directoryPath, WebRequestMethods.Ftp.RemoveDirectory); try { return GetStatusDescription(ftpWebRequest); } catch (Exception) { return null; } } public string Rename(string currentPath, string newName) { var ftpWebRequest = CreateRequest(currentPath, WebRequestMethods.Ftp.Rename); ftpWebRequest.RenameTo = newName; try { return GetStatusDescription(ftpWebRequest); } catch (Exception) { return null; } } public string FtpUploadFile(string source, string destination) { var ftpWebRequest = CreateRequest(Combine(_path, destination), WebRequestMethods.Ftp.UploadFile); try { using (var stream = ftpWebRequest.GetRequestStream()) { using (var fileStream = File.Open(source, FileMode.Open)) { int num; var buffer = new byte[BufferSize]; while ((num = fileStream.Read(buffer, 0, buffer.Length)) > 0) { stream.Write(buffer, 0, num); } } } return GetStatusDescription(ftpWebRequest); } catch (Exception) { return null; } } public string UploadFileWithUniqueName(string source) { var ftpWebRequest = CreateRequest(WebRequestMethods.Ftp.UploadFileWithUniqueName); try { using (var stream = ftpWebRequest.GetRequestStream()) { using (var fileStream = File.Open(source, FileMode.Open)) { int num; var buffer = new byte[BufferSize]; while ((num = fileStream.Read(buffer, 0, buffer.Length)) > 0) { stream.Write(buffer, 0, num); } } } var response = (FtpWebResponse) ftpWebRequest.GetResponse(); var fileName = Path.GetFileName(response.ResponseUri.ToString()); ftpWebRequest.Abort(); if (response != null) response.Close(); return fileName; } catch (Exception) { return null; } } private FtpWebRequest CreateRequest(string method) { return CreateRequest(_path, method); } private FtpWebRequest CreateRequest(string path, string method) { var r = (FtpWebRequest) WebRequest.Create(path); r.Credentials = Credentials; r.Method = method; r.UseBinary = Binary; r.EnableSsl = EnableSsl; r.UsePassive = Passive; r.KeepAlive = false; r.Proxy = null; return r; } private static string GetStatusDescription(WebRequest request) { var response = (FtpWebResponse) request.GetResponse(); var description = response.StatusDescription; request.Abort(); if (response != null) response.Close(); return description; } private static string Combine(string path1, string path2) { return Path.Combine(path1, path2).Replace("\\", "/"); } public bool DirectoryExist(string directoryPath) { var exist = false; var ftpWebRequest = CreateRequest(directoryPath, WebRequestMethods.Ftp.ListDirectory); try { var response = ftpWebRequest.GetResponse(); exist = true; ftpWebRequest.Abort(); if (response != null) response.Close(); } catch (WebException ex) { if (ex.Response == null) return exist; var response = (FtpWebResponse) ex.Response; if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable) { exist = false; } } return exist; } public bool FileExist(string filePath) { var exist = false; var ftpWebRequest = CreateRequest(filePath, WebRequestMethods.Ftp.GetFileSize); try { var response = ftpWebRequest.GetResponse(); exist = true; ftpWebRequest.Abort(); if (response != null) response.Close(); } catch (WebException ex) { if (ex.Response != null) { var response = (FtpWebResponse) ex.Response; if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable) { exist = false; } } } return exist; } private static string GetParrentDictionary(string directoryPath) { var uri = new Uri(Path.Combine(directoryPath, @"..\")); return uri.ToString(); } } }
bf647db57153b8ad8da3f05ea10933df1a0461a0
C#
shendongnian/download4
/first_version_download2/22454-1155121-2257226-2.cs
2.90625
3
[DataContract] public class Person { [DataMember] private int id; public int Id {get {return id;}} // immutable public Person(int id) { this.id = id; } [DataMember] public string Name {get;set;} // mutable }
f86358b4620a178f9e4cd6d115117ffff2bc22d1
C#
a-severin/ttut
/Commons/Configuration.cs
2.9375
3
 using System; namespace Commons { public class Configuration { public const string DefaultHost = "127.0.0.1"; public const int DefaultPort = 50001; public Configuration(string[] args) { for (int i = 0; i < args.Length; i++) { var param = args[i]; if (param.Equals("-h", StringComparison.InvariantCultureIgnoreCase) && i + 1 < args.Length) { Hostname = args[i + 1]; } if (param.Equals("-p", StringComparison.CurrentCultureIgnoreCase) && i + 1 < args.Length) { var portInput = args[i + 1]; if (int.TryParse(portInput, out var portValue)) { Port = portValue; } } } } public string Hostname { get; } = DefaultHost; public int Port { get; } = DefaultPort; } }
87f40b1fd3fde6b8947db98bff81462ee349744e
C#
reilley/LeetCode
/219-Contains-Duplicate-II/solution.cs
3.28125
3
public class Solution { public bool ContainsNearbyDuplicate(int[] nums, int k) { if(nums==null || nums.Length ==0) return false; var dict = new Dictionary<int, int>(); for(int i=0; i<nums.Length; i++){ if(!dict.ContainsKey(nums[i])){ dict[nums[i]] = i; } else { if(i-dict[nums[i]] <=k) return true; else dict[nums[i]] = i; } } return false; } }
fdd52a9c5983bce92f71474e3bbe02b79e367ba8
C#
RoziPetkova/SoftUni-Homework
/1.4 High-Quality Code/Exams/BuhtigIssueTracker/BuhtigIssueTracker/Execution/IssueTrackerEngine.cs
2.8125
3
namespace BuhtigIssueTracker.Execution { using System; using System.Text; using Interfaces; using UserInterface; public class IssueTrackerEngine : IEngine { private readonly CommandExecutor commandExecutor; private readonly IUserInterface userInterface; public IssueTrackerEngine(CommandExecutor commandExecutor, IUserInterface userInterface) { this.commandExecutor = commandExecutor; this.userInterface = userInterface; } public IssueTrackerEngine() : this(new CommandExecutor(), new ConsoleUserInterface()) { } public void Run() { //var result = new StringBuilder(); while (true) { string urlLine = this.userInterface.ReadLine(); //if (urlLine == "zz") //{ // break; //} if (urlLine == null) { break; } urlLine = urlLine.Trim(); if (string.IsNullOrEmpty(urlLine)) { continue; } try { var endpoint = new Endpoint(urlLine); string viewResult = this.commandExecutor.DispatchAction(endpoint); this.userInterface.WriteLine(viewResult); // result.AppendLine(viewResult); } catch (Exception ex) { this.userInterface.WriteLine(ex.Message); //result.AppendLine(ex.Message); } } //this.userInterface.WriteLine(result); } } }
fcd69944e05a92818c4aa1477c63f52b2591c8a5
C#
Dreami/PIDS_Actividad5
/Actividad5/Actividad5/Program.cs
3.125
3
using FileOutputs; using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace Actividad5 { class Program { static void Main(string[] args) { DirectoryInfo d = new DirectoryInfo(Outputs.getAllFiles()); FileInfo[] Files = d.GetFiles("*.txt"); string output_path5 = @"C:\Users\maple\Documents\9° Semester\CS13309_Archivos_HTML\a5_matricula.txt"; string output; var watch = System.Diagnostics.Stopwatch.StartNew(); foreach (FileInfo file in Files) { output = ""; var watchEach = System.Diagnostics.Stopwatch.StartNew(); string htmlContent = File.ReadAllText(file.FullName); htmlContent.Trim(); List<string> sortedWords = new List<string>(); Dictionary<string, int> repetitions = new Dictionary<string, int>(); string[] eachWord = htmlContent.Split(' '); string lowercase; try { foreach (string word in eachWord) { if (!string.IsNullOrEmpty(word)) { lowercase = word.ToLower(); if (repetitions.ContainsKey(lowercase)) { repetitions[lowercase]++; } else { repetitions.Add(lowercase, 1); } } } } catch (ArgumentNullException argExc) { Console.WriteLine(argExc.StackTrace); } catch (KeyNotFoundException keyNotFoundExc) { Console.WriteLine(keyNotFoundExc.StackTrace); } var list = repetitions.Keys.ToList(); list.Sort(); foreach (var key in list) { output += key + " \t" + repetitions[key] + "\n"; } output += "\n" + file.Name + " sorted in\t" + watchEach.Elapsed.TotalMilliseconds.ToString() + " ms"; Console.WriteLine(output); watchEach.Stop(); Outputs.output_print(output_path5, output); } output = "\nAll files sorted in\t" + watch.Elapsed.TotalMilliseconds.ToString() + " ms"; Console.WriteLine(output); watch.Stop(); Outputs.output_print(output_path5, output); Console.Read(); } } }
96c7dd84dde3da14c942adf7991dc13bb0d3f63e
C#
zdougherty18/Aspose_Email_NET
/Examples/ProgrammersGuide/ProgrammingEmail/ManagingEmailMessagesPOP3/ReceivingAndSavingToDisk/RecipientInformation/CSharp/Program.cs
2.734375
3
////////////////////////////////////////////////////////////////////////// // Copyright 2001-2013 Aspose Pty Ltd. All Rights Reserved. // // This file is part of Aspose.Email. The source code in this file // is only intended as a supplement to the documentation, and is provided // "as is", without warranty of any kind, either expressed or implied. ////////////////////////////////////////////////////////////////////////// using System.IO; using Aspose.Email; using Aspose.Email.Outlook; using System; namespace RecipientInformation { public class Program { public static void Main(string[] args) { // The path to the documents directory. string dataDir = Path.GetFullPath("../../../Data/"); //Load message file MapiMessage msg = MapiMessage.FromFile(dataDir + "Message.msg"); //Enumerate the recipients foreach (MapiRecipient recip in msg.Recipients) { switch (recip.RecipientType) // What's the type? { case MapiRecipientType.MAPI_TO: Console.WriteLine("RecipientType:TO"); break; case MapiRecipientType.MAPI_CC: Console.WriteLine("RecipientType:CC"); break; case MapiRecipientType.MAPI_BCC: Console.WriteLine("RecipientType:BCC"); break; } //Get email address Console.WriteLine("Email Address: " + recip.EmailAddress); //Get display name Console.WriteLine("DisplayName: " + recip.DisplayName); //Get address type Console.WriteLine("AddressType: " + recip.AddressType); } } } }
314dba769d3fe9050f784ef16888408b1a2b45de
C#
dimass2580/organizer
/orgainizer/Data/ContactsRequests.cs
2.703125
3
using orgainizer.Data.Add; using orgainizer.Data.Deleate; using orgainizer.Data.Get; using orgainizer.DataModels; using System.Collections.Generic; using System.Data.OleDb; namespace orgainizer.Data { class ContactsRequests : Reqester { public ContactsRequests() { addRequest = new AddContact(); deleateRequest = new DeleateContact(); getRequest = new GetAllContacts(); } public List<ContactModel> Find(string key, string field) { List<ContactModel> contacts = new List<ContactModel>(); string getReq = $"SELECT * FROM Contacts WHERE {field} like '%{key}%'"; connection.Open(); OleDbCommand getCommand = new OleDbCommand(getReq, connection); OleDbDataReader reader = getCommand.ExecuteReader(); while (reader.Read()) { ContactModel row = new ContactModel((int)reader[0], (string)reader[1], (string)reader[2], (string)reader[3], (string)reader[4]); contacts.Add(row); } connection.Close(); return contacts; } } }
e33743456198ab701a637a594fc9318f957cf9fd
C#
beerseeker0/TesteEsquinaLab
/TesteEsquinaLab/Controllers/ComprasController.cs
2.625
3
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using EsquinaLabApi.Data; using EsquinaLabApi.Models; namespace EsquinaLabApi.Controllers { [Route("api/[controller]/{action}")] [ApiController] public class ComprasController : ControllerBase { private readonly Db _context; public ComprasController(Db context) { _context = context; } [HttpGet("{id}")] public async Task<ActionResult<Compra>> BuscarCompra(int id) { var compra = await _context.Compra.AsNoTracking().FirstOrDefaultAsync(x => x.CodigoCompra == id); if (compra == null) { return NotFound(new { message = $"Não foi possível encontrar a Compra." }); } return compra; } [HttpPost] public async Task<ActionResult<Compra>> InserirCompra(Compra compra) { if (!ModelState.IsValid) return BadRequest(ModelState); if (!VerificarCliente(compra.CodigoCliente)) return NotFound(new { message = $"Não foi possível encontrar o Cliente." }); try { _context.Compra.Add(compra); List<Parcela> parcelas = CriarParcelas(compra); _context.Parcela.AddRange(parcelas); await _context.SaveChangesAsync(); return CreatedAtAction("BuscarCompra", new { id = compra.CodigoCompra }, compra); } catch (Exception) { return BadRequest(new { message = "Não foi possível realizar a Compra." }); } } public List<Parcela> CriarParcelas(Compra compra) { List<Parcela> parcelas = new List<Parcela>(); for(int i = 1; i <= compra.QuantidadeParcelas; i++) { Parcela parc = new Parcela(); parc.CodigoCompra = compra.CodigoCompra; parc.DataVencimento = compra.DataCompra.AddMonths(i-1); parc.ValorParcela = compra.ValorCompra / i; } return parcelas; } public bool VerificarCliente(int codigoCliente) { var cliente = _context.Cliente.Where(x=> x.CodigoCliente == codigoCliente).FirstOrDefault(); if (cliente != null) return true; else return false; } } }
09f5a38b808057cfbebe782d62b08648191a986d
C#
PavithraSSE/Shopping_Service
/Projects/ShoppingProcessor/ShoppingModel.cs
2.609375
3
using ShoppingProcessor.Interface; using System; using System.Collections.Generic; using System.Data; using System.Threading.Tasks; using ShoppingDAL; using System.Data.SqlClient; namespace ShoppingProcessor { public class ShoppingModel: IShoppingModel { public async Task<dynamic> GetItemsDetailsByName(CategoryRQ categoryRQ) { List<CategoryRS> lstCategoryRS = new List<CategoryRS>(); if (!string.IsNullOrEmpty(categoryRQ.CategoryName)) lstCategoryRS = Get_CategoryDetails(categoryRQ.CategoryName); return lstCategoryRS; } public async Task<bool> DeleteCategorByName(string Name) { bool IsDeleted = false; if (!string.IsNullOrEmpty(Name)) IsDeleted = DeleteCategoryDetails(Name); return IsDeleted; } public List<CategoryRS> Get_CategoryDetails(string Name) { List<CategoryRS> lstcategoryRS = new List<CategoryRS>(); try { DataTable dt = new DataTable(); List<SqlParameter> sqlParameters = new List<SqlParameter>(); sqlParameters.Add(new SqlParameter("@CategoryName", Name)); dt = DBconnection.FillDataTable(SPNames.GetItemsByName, sqlParameters.ToArray()); for (int i = 0; i < dt.Rows.Count; i++) { CategoryRS categoryRS = new CategoryRS(); categoryRS.CategoryName = dt.Rows[i]["CategoryName"].ToString(); categoryRS.SubCategoryName = dt.Rows[i]["SubCategoryName"].ToString(); categoryRS.ItemName = dt.Rows[i]["ItemName"].ToString(); categoryRS.ItemDescription = dt.Rows[i]["Description"].ToString(); lstcategoryRS.Add(categoryRS); } } catch(Exception ex) { throw ex; } return lstcategoryRS; } public bool DeleteCategoryDetails(string Name) { bool IsDeleted = false; List<SqlParameter> sqlParameters = new List<SqlParameter>(); sqlParameters.Add(new SqlParameter("@CategoryName", Name)); IsDeleted = DBconnection.ExecuteNonQuery(SPNames.DeleteItemByName, sqlParameters.ToArray()); return IsDeleted; } } }
04c7826ff7d23ad4b85038b8c8e2052c2f6e7183
C#
TAHK518/tdd
/cs/TagsCloudVisualization/PointExtension.cs
2.890625
3
using System; using System.Collections.Generic; using System.Drawing; using System.Text; namespace TagsCloudVisualization { public static class PointExtension { public static double GetDistance(this Point currentPoint, Point otherPoint) { return Math.Sqrt(Math.Pow(currentPoint.X - otherPoint.X, 2) + Math.Pow(currentPoint.Y - otherPoint.Y, 2)); } } }
fbc478da3d88ce1f5484976039448d734f44ea21
C#
KasperSK/TripleA
/Software/TripleA/CashRegister.WebApi/Controllers/OrderLinesController.cs
2.609375
3
using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Linq; using System.Net; using System.Net.Http; using System.Threading.Tasks; using System.Web.Http; using System.Web.Http.Description; using CashRegister.WebApi.Models; namespace CashRegister.WebApi.Controllers { /// <summary> /// Controller to handle transfer of OrderLines between web and database /// </summary> public class OrderLinesController : ApiController { private CashRegisterContext db = new CashRegisterContext(); // GET: api/OrderLines /// <summary> /// Get a list of all order lines /// </summary> /// <returns>List of all order lines</returns> public IQueryable<OrderlineDto> GetOrderLines() { var OrderLines = from o in db.OrderLines select new OrderlineDto() { Id = o.Id, Quantity = o.Quantity, ProductName = o.Product.Name, UnitPrice = o.UnitPrice, Discount = o.Discount.Percent, }; return OrderLines; } // GET: api/OrderLines/5 /// <summary> /// Get a detailed order line /// </summary> /// <param name="id">Id of order line you want details from</param> /// <returns>Detailed Order line or an error code</returns> [ResponseType(typeof(OrderLine))] public async Task<IHttpActionResult> GetOrderLine(long id) { OrderLine orderLine = await db.OrderLines.FindAsync(id); if (orderLine == null) { return NotFound(); } return Ok(orderLine); } // PUT: api/OrderLines/5 /// <summary> /// Input Changes to orderline /// </summary> /// <param name="id">Id of orderline to change</param> /// <param name="orderLine">Object with the changes</param> /// <returns>Status code</returns> [ResponseType(typeof(void))] public async Task<IHttpActionResult> PutOrderLine(long id, OrderLine orderLine) { if (!ModelState.IsValid) { return BadRequest(ModelState); } if (id != orderLine.Id) { return BadRequest(); } db.Entry(orderLine).State = EntityState.Modified; try { await db.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!OrderLineExists(id)) { return NotFound(); } else { throw; } } return StatusCode(HttpStatusCode.NoContent); } // POST: api/OrderLines /// <summary> /// Input a new orderline to the db /// </summary> /// <param name="orderLine">An object containing the detailde product</param> /// <returns>The insertet object or an error code</returns> [ResponseType(typeof(OrderLine))] public async Task<IHttpActionResult> PostOrderLine(OrderLine orderLine) { if (!ModelState.IsValid) { return BadRequest(ModelState); } db.OrderLines.Add(orderLine); await db.SaveChangesAsync(); return CreatedAtRoute("DefaultApi", new { id = orderLine.Id }, orderLine); } // DELETE: api/OrderLines/5 /// <summary> /// Delete a orderline /// </summary> /// <param name="id">ID of order line to delete</param> /// <returns>the deleted tab</returns> [ResponseType(typeof(OrderLine))] public async Task<IHttpActionResult> DeleteOrderLine(long id) { OrderLine orderLine = await db.OrderLines.FindAsync(id); if (orderLine == null) { return NotFound(); } db.OrderLines.Remove(orderLine); await db.SaveChangesAsync(); return Ok(orderLine); } /// <summary> /// To dispose of db context /// </summary> /// <param name="disposing">True if disposing</param> protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } /// <summary> /// internal helper method to check if orderline exists /// </summary> /// <param name="id">id of orderline to check</param> /// <returns>True if it exists</returns> private bool OrderLineExists(long id) { return db.OrderLines.Count(e => e.Id == id) > 0; } } }
92b38256d697e2da438048627f0dcf1623583232
C#
Jivitesh13/CardGameScoreCalculator
/CardGameScoreCalculator.Web/Controllers/CardGameController.cs
2.625
3
using CardGameScoreCalculator.Web.Models; using CardGameScoreCalculator.Web.Models.Builders; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; namespace CardGameScoreCalculator.Web.Controllers { public class CardGameController : Controller { private readonly ILogger<CardGameController> _logger; private readonly IScoreResultBuilder _scoreResultBuilder; public CardGameController(ILogger<CardGameController> logger, IScoreResultBuilder scoreResultBuilder) { _logger = logger; _scoreResultBuilder = scoreResultBuilder; } [HttpGet] public IActionResult Index() { return View(); } [HttpPost] public IActionResult Score(CardGameModel cardGameModel) { if (!ModelState.IsValid) { return View(nameof(this.Index)); } // we are here means validations has been passed var model = _scoreResultBuilder .ForHand(cardGameModel.Hand) .Parse() .Build(); return View(model); ; } } }
c839caec80f3a7b6990b8abc56327349e2883495
C#
NathanHoln/Cyberarms
/Cyberarms.IntrusionDetection.Shared/Db/DbUpgrader.cs
2.515625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Cyberarms.IntrusionDetection.Shared.Db { public class DbUpgrader { public void RunUpgradeScripts(System.Data.IDbConnection connection) { System.Data.IDbCommand cmd = connection.CreateCommand(); cmd.Connection = connection; cmd.CommandText = "SELECT VersionNumber from DbConfig order by VersionNumber desc LIMIT 1"; int latestVersion = 0; object result = null; try { result = cmd.ExecuteScalar(); } catch (System.Data.Common.DbException) { result = null; latestVersion = 0; } catch(Exception ex) { throw (ex); } if (result != null && !String.IsNullOrEmpty(result.ToString())) { if(!int.TryParse(result.ToString(), out latestVersion)) { latestVersion = 0; } } InitScripts(); UpgradeAll(connection, latestVersion); } public void UpgradeAll(System.Data.IDbConnection connection, int latestVersionNumber) { foreach (int key in upgradeScripts.Keys) { if (key > latestVersionNumber) { upgradeScripts[key].UpgradeDatabase(connection); } } } SortedList<int, DbUpgradeScript> upgradeScripts; private void InitScripts() { upgradeScripts = new SortedList<int, DbUpgradeScript>(); upgradeScripts.Add(1, new Version_2_1()); } public DbUpgrader() { } } }
09b1bea9517ff8e8a449bfa37b02ba52a465ff0d
C#
abbasbordbar/Shop
/Shop/Models/Services/UserService.cs
2.59375
3
using Shop.Data; using Shop.Models.Interfaces; using Shop.ViewModels; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Shop.Models.Services { public class UserService : IUserService { DBShop dB; public UserService(DBShop dBShop) { dB = dBShop; } public int AddUser(User user) { try { dB.Add(user); dB.SaveChanges(); return user.UserId; } catch { return 0; } } public User GetUserById(int id) { return dB.users.Find(id); } public bool EditUser(User user) { try { dB.Update(user); dB.SaveChanges(); return true; } catch { return false; } } public bool CheckExistEmail(string email) { return dB.users.Any(e => e.Email == email);//اگر وجود داشت یا ایا وجود دارد این ایمیل در جدول یا نه } public ActiveEmailViewModel GetUserForForgotPassword(string email) { return dB.users.Where(u => u.Email == email).Select(u => new ActiveEmailViewModel { UserId=u.UserId, ActiveCode=u.EmailActiveCode }).SingleOrDefault(); } public User LoginUser(string email) { return dB.users.Where(u => u.Email == email ).SingleOrDefault(); } } }
be5bc4ebd095b1d2adf4526e6398c3446c851376
C#
KleinclausFlorent/ContactsAPI-For-OpenWt
/MyContacts.API/Validation/SaveUserResourceValidation.cs
2.625
3
using FluentValidation; using MyContacts.API.Resources; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace MyContacts.API.Validation { /// <summary> /// Class used to make some data validation before sending data to the database /// Fluent Validation makes it easier /// User model /// </summary> public class SaveUserResourceValidation : AbstractValidator<SaveUserResource> { // --- Methods --- public SaveUserResourceValidation() { RuleFor(u => u.Username) .NotEmpty() .MaximumLength(50); RuleFor(u => u.Password) .NotEmpty() .MaximumLength(50); RuleFor(u => u.ContactId) .NotEmpty() .WithMessage(" 'Contact Id' must not be 0."); } } }
430b46c53597116d7c7b24522407e29dff9e83a3
C#
isdaniel/Asp.net-MVC-Debuger
/src/aspnetwebstack/OData/src/System.Web.Http.OData/OData/Routing/CastPathSegment.cs
2.5625
3
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. using System.Web.Http.OData.Formatter; using System.Web.Http.OData.Properties; using Microsoft.Data.Edm; namespace System.Web.Http.OData.Routing { /// <summary> /// An <see cref="ODataPathSegment"/> implementation representing a cast. /// </summary> public class CastPathSegment : ODataPathSegment { /// <summary> /// Initializes a new instance of the <see cref="CastPathSegment" /> class. /// </summary> /// <param name="castType">The type of the cast.</param> public CastPathSegment(IEdmEntityType castType) { if (castType == null) { throw Error.ArgumentNull("castType"); } CastType = castType; CastTypeName = castType.FullName(); } /// <summary> /// Initializes a new instance of the <see cref="CastPathSegment" /> class. /// </summary> /// <param name="castTypeName">Name of the cast type.</param> public CastPathSegment(string castTypeName) { if (castTypeName == null) { throw Error.ArgumentNull("castTypeName"); } CastTypeName = castTypeName; } /// <summary> /// Gets the segment kind for the current segment. /// </summary> public override string SegmentKind { get { return ODataSegmentKinds.Cast; } } /// <summary> /// Gets the type of the cast. /// </summary> public IEdmEntityType CastType { get; private set; } /// <summary> /// Gets the name of the cast type. /// </summary> public string CastTypeName { get; private set; } /// <summary> /// Gets the EDM type for this segment. /// </summary> /// <param name="previousEdmType">The EDM type of the previous path segment.</param> /// <returns> /// The EDM type for this segment. /// </returns> public override IEdmType GetEdmType(IEdmType previousEdmType) { if (CastType != null && previousEdmType != null) { if (previousEdmType.TypeKind == EdmTypeKind.Collection) { return CastType.GetCollection(); } else { return CastType; } } return null; } /// <summary> /// Gets the entity set for this segment. /// </summary> /// <param name="previousEntitySet">The entity set of the previous path segment.</param> /// <returns> /// The entity set for this segment. /// </returns> public override IEdmEntitySet GetEntitySet(IEdmEntitySet previousEntitySet) { return previousEntitySet; } /// <summary> /// Returns a <see cref="System.String" /> that represents this instance. /// </summary> /// <returns> /// A <see cref="System.String" /> that represents this instance. /// </returns> public override string ToString() { return CastTypeName; } } }
b29d369533579508bd5558d8d7e20837fb5286e7
C#
celery94/EntPhysicalTableTree
/EntPhysicalTableTree/GetTable.cs
2.734375
3
using System; using System.Net; using System.Text; using System.Collections.Generic; using SnmpSharpNet; namespace EntPhysicalTableTree { class MainClass { public static void GetTable() { Dictionary<String, Dictionary<uint, AsnType>> result = new Dictionary<String, Dictionary<uint, AsnType>>(); // Not every row has a value for every column so keep track of all columns available in the table List<uint> tableColumns = new List<uint>(); // Prepare agent information AgentParameters param = new AgentParameters(SnmpVersion.Ver2, new OctetString("public")); IpAddress peer = new IpAddress("192.168.15.42"); if (!peer.Valid) { Console.WriteLine("Unable to resolve name or error in address for peer: {0}", ""); return; } UdpTarget target = new UdpTarget((IPAddress)peer); // This is the table OID supplied on the command line Oid startOid = new Oid("1.3.6.1.2.1.47.1.1.1"); // Each table OID is followed by .1 for the entry OID. Add it to the table OID startOid.Add(1); // Add Entry OID to the end of the table OID // Prepare the request PDU Pdu bulkPdu = Pdu.GetBulkPdu(); bulkPdu.VbList.Add(startOid); // We don't need any NonRepeaters bulkPdu.NonRepeaters = 0; // Tune MaxRepetitions to the number best suited to retrive the data bulkPdu.MaxRepetitions = 100; // Current OID will keep track of the last retrieved OID and be used as // indication that we have reached end of table Oid curOid = (Oid)startOid.Clone(); // Keep looping through results until end of table while (startOid.IsRootOf(curOid)) { SnmpPacket res = null; try { res = target.Request(bulkPdu, param); } catch (Exception ex) { Console.WriteLine("Request failed: {0}", ex.Message); target.Close(); return; } // For GetBulk request response has to be version 2 if (res.Version != SnmpVersion.Ver2) { Console.WriteLine("Received wrong SNMP version response packet."); target.Close(); return; } // Check if there is an agent error returned in the reply if (res.Pdu.ErrorStatus != 0) { Console.WriteLine("SNMP agent returned error {0} for request Vb index {1}", res.Pdu.ErrorStatus, res.Pdu.ErrorIndex); target.Close(); return; } // Go through the VbList and check all replies foreach (Vb v in res.Pdu.VbList) { curOid = (Oid)v.Oid.Clone(); // VbList could contain items that are past the end of the requested table. // Make sure we are dealing with an OID that is part of the table if (startOid.IsRootOf(v.Oid)) { // Get child Id's from the OID (past the table.entry sequence) uint[] childOids = Oid.GetChildIdentifiers(startOid, v.Oid); // Get the value instance and converted it to a dotted decimal // string to use as key in result dictionary uint[] instance = new uint[childOids.Length - 1]; Array.Copy(childOids, 1, instance, 0, childOids.Length - 1); String strInst = InstanceToString(instance); // Column id is the first value past <table oid>.entry in the response OID uint column = childOids[0]; if (!tableColumns.Contains(column)) tableColumns.Add(column); if (result.ContainsKey(strInst)) { result[strInst][column] = (AsnType)v.Value.Clone(); } else { result[strInst] = new Dictionary<uint, AsnType>(); result[strInst][column] = (AsnType)v.Value.Clone(); } } else { // We've reached the end of the table. No point continuing the loop break; } } // If last received OID is within the table, build next request if (startOid.IsRootOf(curOid)) { bulkPdu.VbList.Clear(); bulkPdu.VbList.Add(curOid); bulkPdu.NonRepeaters = 0; bulkPdu.MaxRepetitions = 100; } } target.Close(); if (result.Count <= 0) { Console.WriteLine("No results returned.\n"); } else { Console.Write("Instance"); foreach (uint column in tableColumns) { Console.Write("\tColumn id {0}", column); } Console.WriteLine(""); foreach (KeyValuePair<string, Dictionary<uint, AsnType>> kvp in result) { Console.Write("{0}", kvp.Key); foreach (uint column in tableColumns) { if (kvp.Value.ContainsKey(column)) { Console.Write("\t{0} ({1})", kvp.Value[column].ToString(), SnmpConstants.GetTypeName(kvp.Value[column].Type)); } else { Console.Write("\t-"); } } Console.WriteLine(""); } } } public static string InstanceToString(uint[] instance) { StringBuilder str = new StringBuilder(); foreach (uint v in instance) { if (str.Length == 0) str.Append(v); else str.AppendFormat(".{0}", v); } return str.ToString(); } } }
7f3330beaae1110e57bb600ab777da1991644e4f
C#
jelacicedin/AVMS-sensor
/LIDAR-app/packages/0.9.0.9 OpenGL Sources/OpenTKLib/Triangulation/Cell2D.cs
2.84375
3
/************************************************************************* * This file & class is part of the MIConvexHull Library Project. * Copyright 2010 Matthew Ira Campbell, PhD. * * MIConvexHull is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MIConvexHull is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MIConvexHull. If not, see <http://www.gnu.org/licenses/>. * * Please find further details and contact information on GraphSynth * at http://miconvexhull.codeplex.com *************************************************************************/ using System; using System.Linq; using System.Windows; using MIConvexHull; namespace OpenTKLib { /// <summary> /// A vertex is a simple class that stores the postion of a point, node or vertex. /// </summary> public class Cell2D : TriangulationCell<Vertex2D, Cell2D> { static Random rnd = new Random(); OpenTK.Vector2d circumCenter; OpenTK.Vector2d centroid; double Det(double[,] m) { return m[0, 0] * ((m[1, 1] * m[2, 2]) - (m[2, 1] * m[1, 2])) - m[0, 1] * (m[1, 0] * m[2, 2] - m[2, 0] * m[1, 2]) + m[0, 2] * (m[1, 0] * m[2, 1] - m[2, 0] * m[1, 1]); } double LengthSquared(double[] v) { double norm = 0; for (int i = 0; i < v.Length; i++) { var t = v[i]; norm += t * t; } return norm; } OpenTK.Vector2d GetCircumcenter() { // From MathWorld: http://mathworld.wolfram.com/Circumcircle.html var points = Vertices; double[,] m = new double[3, 3]; // x, y, 1 for (int i = 0; i < 3; i++) { m[i, 0] = points[i][0]; m[i, 1] = points[i][1]; m[i, 2] = 1; } var a = Det(m); // size, y, 1 for (int i = 0; i < 3; i++) { m[i, 0] = LengthSquared(points[i].PositionArray); } var dx = -Det(m); // size, x, 1 for (int i = 0; i < 3; i++) { m[i, 1] = points[i][0]; } var dy = Det(m); // size, x, y for (int i = 0; i < 3; i++) { m[i, 2] = points[i][1]; } var c = -Det(m); var s = -1/ (2* a); var r = System.Math.Abs(s) * System.Math.Sqrt(dx * dx + dy * dy - 4 * a * c); return new OpenTK.Vector2d(s * dx, s * dy); } OpenTK.Vector2d GetCentroid() { return new OpenTK.Vector2d(Vertices.Select(v => v[0]).Average(), Vertices.Select(v => v[1]).Average()); } public OpenTK.Vector2d Circumcenter { get { if (circumCenter == default(OpenTK.Vector2d)) circumCenter = GetCircumcenter(); return circumCenter; } } public OpenTK.Vector2d Centroid { get { if (centroid == default(OpenTK.Vector2d)) centroid = GetCentroid(); return centroid; } } } }
acacaa8fff723f1279c829b1737190eaf6a7e4bb
C#
Kamleeonau/Intel-Unite-Video-Plugin
/UniteVideoBrowserExtensionHelper/Program.cs
2.734375
3
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Threading; using System.Web.Script.Serialization; using System.IO; using System.Text; using System.Net; using System.Net.Sockets; namespace UniteVideoBrowserExtensionHelper { class Program { static void Main(string[] args) { const int MAX_LENGTH = 10240; Stream stdin = Console.OpenStandardInput(); Stream stdout = Console.OpenStandardOutput(); // socket to send for debugging var s = new System.Net.Sockets.UdpClient(); // buffer byte[] messageLengthRaw = new byte[4]; String messageString = ""; while (true) { try { int readBytes = stdin.Read(messageLengthRaw, 0, 4); //unpack bytes to a 32-bit unsigned integer int length = BitConverter.ToInt32(messageLengthRaw, 0); if (readBytes == 0) { // we read zero bytes. this means we should be ending return; } Console.Error.WriteLine("Read {0} bytes from stream. Message length is {1}.", readBytes, length); // need an appropriate sized buffer for the incoming message if (length > MAX_LENGTH) { length = MAX_LENGTH; } byte[] message = new byte[length]; stdin.Read(message, 0, length); messageString = Encoding.UTF8.GetString(message); Console.Error.WriteLine("Length: {0}, Message: {1}", messageString.Length, messageString); if (messageString.Length == 0) { //abort because we have a null string continue; } String HubAddress = Util.FindUniteHub(); String Response = ""; if (HubAddress.Length > 0) { // We appear to be connected to a hub, try to send the URL through for playback Response = "OK"; TcpClient client = new TcpClient(); try { client.Connect(HubAddress, 5050); Stream stream = client.GetStream(); stream.Write(message,0,length); } catch (Exception) { Console.Error.WriteLine("Exception happened trying to connect :("); Response = "ERR:CONNECTERROR"; } } else { Response = "ERR:NOTCONNECT"; } byte[] m = Util.EncodeNative(Response); stdout.Write(m, 0, m.Length); stdout.Flush(); // send the data to localhost for debugging //s.Send(m, m.Length, "10.30.0.1", 5050); } catch (Exception e) { Console.Error.WriteLine("Exception happened. {0}", e.Message); continue; } } } } }
9205e47b9da9d82aa7285738d4208703cca5def5
C#
ajurkic/Songs-and-playlists
/SandP/Migrations/201707160926442_InsertDataIntoSongsAndPlaylistsTables.cs
2.609375
3
namespace SandP.Migrations { using System; using System.Data.Entity.Migrations; public partial class InsertDataIntoSongsAndPlaylistsTables : DbMigration { public override void Up() { Sql("INSERT INTO Songs(Name, Author, Length) VALUES ('Something like this', 'Coldplay', 250)"); Sql("INSERT INTO Songs(Name, Author, Length) VALUES ('Little talks', 'Of Monsters And Men', 212)"); Sql("INSERT INTO Songs(Name, Author, Length) VALUES ('Four seasons', 'Antonio Vivaldi', 500)"); Sql("INSERT INTO Songs(Name, Author, Length) VALUES ('With everything', 'Hillsong United', 302)"); Sql("INSERT INTO Songs(Name, Author, Length) VALUES ('Fur Elise', 'Ludwig van Beethoven', 174)"); } public override void Down() { Sql("DELETE FROM Songs WHERE SongID IN (1,2,3,4,5)"); } } }
e3a1d35cce4c85332cfec08f528904ad01da8780
C#
jackyyang09/Simple-Unity-Audio-Manager
/Runtime/Scripts/JSAMSettings.cs
2.703125
3
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEditor; using UnityEngine.Audio; namespace JSAM { public class JSAMSettings : ScriptableObject { [Tooltip("If true, enables 3D spatialized audio for all sound effects, does not effect music")] [SerializeField] bool spatialSound = true; public bool Spatialize => spatialSound; /// <summary> /// Number of Sound Channels to be created on start /// </summary> [Tooltip("Number of Sound Channels to be created on start")] [SerializeField] int startingSoundChannels = 16; public int StartingSoundChannels => startingSoundChannels; [Tooltip("Number of Music Channels to be created on start")] [SerializeField] int startingMusicChannels = 3; public int StartingMusicChannels => startingMusicChannels; [Tooltip("If the maxDistance property of an Audio File Object is left at 0, then this value will be used as a substitute.")] [SerializeField] float defaultSoundMaxDistance = 7; public float DefaultSoundMaxDistance => defaultSoundMaxDistance; /// <summary> /// If true, AudioManager no longer prints info to the console. Does not affect AudioManager errors/warnings /// </summary> [Tooltip("If true, AudioManager no longer prints info to the console. Does not affect AudioManager errors/warnings")] [SerializeField] bool disableConsoleLogs = false; public bool DisableConsoleLogs => disableConsoleLogs; /// <summary> /// If true, keeps AudioManager alive through scene loads. You're recommended to disable this if your AudioManager is instanced /// </summary> [Tooltip("If true, keeps AudioManager alive through scene loads. You're recommended to disable this if your AudioManager is instanced")] [SerializeField] bool dontDestroyOnLoad = true; public new bool DontDestroyOnLoad => dontDestroyOnLoad; /// <summary> /// If true, adds more Audio Sources automatically if you exceed the starting count, you are recommended to keep this enabled /// </summary> [Tooltip("If true, adds more Audio Sources automatically if you exceed the starting count, you are recommended to keep this enabled")] [SerializeField] bool dynamicSourceAllocation = true; public bool DynamicSourceAllocation => dynamicSourceAllocation; [Tooltip("The AudioManager will instantiate this prefab during runtime to play sounds from. If null, will use default AudioSource settings.")] [SerializeField] GameObject soundChannelPrefabOverride; public GameObject SoundChannelPrefab => soundChannelPrefabOverride; [Tooltip("The AudioManager will instantiate this prefab during runtime to play music from. If null, will use default AudioSource settings.")] [SerializeField] GameObject musicChannelPrefabOverride; public GameObject MusicChannelPrefab => musicChannelPrefabOverride; /// <summary> /// If true, stops all sounds when you load a scene /// </summary> [Tooltip("If true, stops all sounds when you load a scene")] [SerializeField] bool stopSoundsOnSceneLoad = false; public bool StopSoundsOnSceneLoad => stopSoundsOnSceneLoad; [Tooltip("Use if spatialized sounds are spatializing late when playing in-editor, known to happen with the Oculus SDK")] [SerializeField] bool spatializeLateUpdate = false; public bool SpatializeOnLateUpdate => spatializeLateUpdate; /// <summary> /// Specifies how your audio channels will follow their targets in 3D space during runtime. /// Only applies if you have Spatial Sound enabled /// </summary> public enum SpatializeUpdateMode { /// <summary> /// Audio channels track their targets in world space every Update. /// </summary> Default, /// <summary> /// Audio channels track their targets in FixedUpdate. /// Good for targets that move during FixedUpdate /// </summary> FixedUpdate, /// <summary> /// Audio channels track their targets in LateUpdate. /// Good for targets that move during LateUpdate /// </summary> LateUpdate, /// <summary> /// Audio channels are parented in the hierarchy to their targets. /// Less performance overhead, but will clutter your object hierarchies during runtime /// </summary> Parented } [Tooltip("Default - Audio Channels track their targets in World Space every update.\n\n" + "FixedUpdate - Audio channels track their targets in FixedUpdate. Good for targets that move during FixedUpdate.\n\n" + "LateUpdate - Same as FixedUpdate but in LateUpdate instead.\n\n" + "Parented - Audio channels are parented in the hierarchy to their targets. " + "Slightly less performance overhead, but will clutter your object hierarchies during runtime.")] [SerializeField] SpatializeUpdateMode spatializationMode; public SpatializeUpdateMode SpatializationMode => spatializationMode; [Tooltip("Changes the pitch of sounds according to Time.timeScale. When Time.timeScale is set to 0, pauses all sounds instead")] [SerializeField] bool timeScaledSounds = true; public bool TimeScaledSounds => timeScaledSounds; [SerializeField] AudioMixer mixer; public AudioMixer Mixer => mixer; [SerializeField] AudioMixerGroup masterGroup; public AudioMixerGroup MasterGroup => masterGroup; [SerializeField] AudioMixerGroup musicGroup; public AudioMixerGroup MusicGroup => musicGroup; [SerializeField] AudioMixerGroup soundGroup; public AudioMixerGroup SoundGroup => soundGroup; [SerializeField] AudioMixerGroup voiceGroup; public AudioMixerGroup VoiceGroup => voiceGroup; [Tooltip("If true, will save volume settings into PlayerPrefs and automatically loads previous volume settings on play. ")] [SerializeField] bool saveVolumeToPlayerPrefs = true; public bool SaveVolumeToPlayerPrefs => saveVolumeToPlayerPrefs; [SerializeField] string masterVolumeKey = "JSAM_MASTER_VOL"; [SerializeField] string masterMutedKey = "JSAM_MASTER_MUTE"; public string MasterVolumeKey => masterVolumeKey; public string MasterMutedKey => masterMutedKey; [SerializeField] string musicVolumeKey = "JSAM_MUSIC_VOL"; [SerializeField] string musicMutedKey = "JSAM_MUSIC_MUTE"; public string MusicVolumeKey => musicVolumeKey; public string MusicMutedKey => musicMutedKey; [SerializeField] string soundVolumeKey = "JSAM_SOUND_VOL"; [SerializeField] string soundMutedKey = "JSAM_SOUND_MUTE"; public string SoundVolumeKey => soundVolumeKey; public string SoundMutedKey => soundMutedKey; [SerializeField] string voiceVolumeKey = "JSAM_VOICE_VOL"; [SerializeField] string voiceMutedKey = "JSAM_VOICE_MUTE"; public string VoiceVolumeKey => voiceVolumeKey; public string VoiceMutedKey => voiceMutedKey; [Tooltip("The font size used when rendering \"quick reference guides\" in JSAM editor windows")] [SerializeField] int quickReferenceFontSize = 10; public int QuickReferenceFontSize { get { return quickReferenceFontSize; } } static JSAMSettings settings; public static JSAMSettings Settings { get { if (settings == null) { var asset = Resources.Load(nameof(JSAMSettings)); settings = asset as JSAMSettings; #if UNITY_EDITOR if (settings == null) TryCreateNewSettingsAsset(); #endif } return settings; } } #if UNITY_EDITOR static readonly string SETTINGS_PATH = "Assets/Settings/Resources/" + nameof(JSAMSettings) + ".asset"; public static void TryCreateNewSettingsAsset() { if (EditorApplication.isCompiling) return; if (!EditorUtility.DisplayDialog( "JSAM First Time Setup", "In order to function, JSAM needs a place to store settings. By default, a " + "Settings asset will be created at " + SETTINGS_PATH + ", but you may move it " + "elsewhere, so long as it's in a Resources folder.\n" + "Moving it out of the Resources folder will prompt this message to appear again erroneously!", "Ok Create It.", "Not Yet!")) return; var asset = CreateInstance<JSAMSettings>(); if (!AssetDatabase.IsValidFolder("Assets/Settings")) AssetDatabase.CreateFolder("Assets", "Settings"); if (!AssetDatabase.IsValidFolder("Assets/Settings/Resources")) AssetDatabase.CreateFolder("Assets/Settings", "Resources"); AssetDatabase.CreateAsset(asset, SETTINGS_PATH); asset.Reset(); settings = asset; EditorUtility.DisplayDialog("JSAM Settings", "Settings asset created successfully!", "Cool."); } static SerializedObject serializedObject; public static SerializedObject SerializedObject { get { if (serializedObject == null) { serializedObject = new SerializedObject(Settings); return serializedObject; } return serializedObject; } } public void ResetEditor() { SerializedObject.FindProperty(nameof(disableConsoleLogs)).boolValue = false; SerializedObject.FindProperty(nameof(quickReferenceFontSize)).intValue = 10; SerializedObject.ApplyModifiedProperties(); } public void Reset() { } #endif } }
ee75c0e29b4398d829e2fff5c5c02bc7ad030970
C#
Gokinha/RPG
/Aula09.Servico/Equipamento_Servico.cs
2.671875
3
using System; using System.Collections.Generic; using Aula09.Comum.NotificationPattern; using Aula09.Dados; using Aula09.Dominio; namespace Aula09.Servico { public class Equipamento_Servico { private readonly Equipamento_Repositorio _equipamento_Repositorio; public Equipamento_Servico() { _equipamento_Repositorio = new Equipamento_Repositorio(); } public NotificationResult Salvar(Equipamento entidade) { var notificationResult = new NotificationResult(); try { if (entidade.CodEquipamento == 0) notificationResult.Add(new NotificationError("Cod Equipamento não pode ser zero.", NotificationErrorType.USER)); if (notificationResult.IsValid) { _equipamento_Repositorio.Adicionar(entidade); notificationResult.Add("Equipamento cadastrado com sucesso."); } notificationResult.Result = entidade; return notificationResult; } catch (Exception ex) { return notificationResult.Add(new NotificationError(ex.Message)); } } public string Excluir(Equipamento entidade) { return ""; } public IEnumerable<Equipamento> ListarTodosComEstoqueZerado() { return _equipamento_Repositorio.ListarTodosComEstoqueZerado(); } } }
2c42bd14e3740e5139cb38c5a445ad414f497b35
C#
akav/pbrt
/pbrt/core/GeometricPrimitive.cs
2.671875
3
using pbrt.core.geometry; using pbrt.lights; namespace pbrt.core { public class GeometricPrimitive : Primitive { public readonly Shape Shape; public readonly Material Material; public readonly AreaLight AreaLight; public override Bounds3<float> WorldBounds => Shape.WorldBound(); //private MediumInterface medium; public GeometricPrimitive(Shape shape, Material material, AreaLight areaLight = null) { Shape = shape; Material = material; AreaLight = areaLight; } public override AreaLight GetAreaLight() { return AreaLight; } public override bool Intersect(Ray ray, out SurfaceInteraction isect) { if (!Shape.Intersect(ray, out float tHit, out isect, true)) return false; ray.tMax = tHit; isect.Primitive = this; return true; } public override bool IntersectP(Ray ray) { return Shape.IntersectP(ray, true); } public override void ComputeScatteringFunctions(SurfaceInteraction inter, bool allowMultipleLobes) { if (Material != null) Material.ComputeScatteringFunctions(inter, allowMultipleLobes); } /*public override AreaLight GetAreaLight() { return areaLight; }*/ } }
69c7c30357e9c8c486a7f9fb9d639283d07a70b4
C#
Juliana090694/Aluninho
/ProjetinhoAluninho/View/Projeto.cs
2.546875
3
using ProjetinhoAluninho.DAO; using ProjetinhoAluninho.Model; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace ProjetinhoAluninho.View { public partial class Tela4 : Form { private Aluno aluno; private Professor professor; private Projeto projeto; private bool modoEdicao; public Tela4() { InitializeComponent(); } public void Init(Projeto p, bool modoEdicao) { if (modoEdicao) { projeto = p; dateTimePicker1.Value = projeto.data; textBox2.Text = projeto.descricaodoprojeto; textBox1.Text = projeto.nomepro; professor = projeto.professor; aluno = projeto.aluno; textBox3.Text = aluno.cpf + " - " + aluno.nome; textBox4.Text = professor.cpf + " - " + professor.nome; } else { projeto = new Projeto(); } //this refencia ao próprio objeto Professor que está em execução, tipo pegar ele mesmo //Ou um médico fazendo cirurgia em si mesmo this.modoEdicao = modoEdicao; } private void button2_Click(object sender, EventArgs e) { if (aluno != null && professor != null && dateTimePicker1.Value != null && textBox1.Text != "" && textBox2.Text != "") { projeto.data = dateTimePicker1.Value; projeto.descricaodoprojeto = textBox2.Text; projeto.nomepro = textBox1.Text; projeto.professor = professor; projeto.aluno = aluno; projeto.Aluno = aluno.Id; projeto.Professor = professor.Id; if (modoEdicao) { if (ProjetoDAO.Alterar(projeto)) { MessageBox.Show("Projeto editado com sucesso.", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { MessageBox.Show("Erro ao tentar editar o projeto.", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error); } } else { if (ProjetoDAO.Incluir(projeto)) { MessageBox.Show("Projeto cadastrado com sucesso.", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { MessageBox.Show("Erro ao tentar incluir o projeto.", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error); } } Program.atualizarListas(); } } private void button3_Click(object sender, EventArgs e) { if (textBox3.Text != "") { Aluno a = new Aluno(); a.cpf = textBox3.Text; a = AlunoDAO.ObterAlunoPorcpf(a); if (a != null) { textBox3.Text = a.cpf + " - " + a.nome; aluno = a; textBox3.ReadOnly = true; button3.Enabled = false; } else { MessageBox.Show("Aluno não encontrado!", "Aviso", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } else { MessageBox.Show("Nenhum campo pode estar vazio!", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void button4_Click(object sender, EventArgs e) { if (textBox4.Text != "") { Professor p = new Professor(); p.cpf = textBox4.Text; p = ProfessorDAO.ObterProfessorPorcpf(p); if (p != null) { textBox4.Text = p.cpf + " - " + p.nome; professor = p; textBox4.ReadOnly = true; button4.Enabled = false; } else { MessageBox.Show("Professor não encontrado!", "Aviso", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } else { MessageBox.Show("Nenhum campo pode estar vazio!", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error); } } public void Limparcampos() { foreach (Control c in Controls) { if (c.GetType() == typeof(TextBox)) { ((TextBox)(c)).Text = string.Empty; } } //reativa as caixas ou seja limpa textBox3.ReadOnly = false; textBox4.ReadOnly = false; button3.Enabled = true; button4.Enabled = true; //seta a data para hoje dateTimePicker1.Value = DateTime.Today; } private void Tela4_Load(object sender, EventArgs e) { } } }
ad46866c09519e9e16afcc18648ecad958f4f9dc
C#
riceman0000/loadoftheoilmagnate
/loadoftheoilmagnate/Assets/Scripts/Systems/General/SavableBase.cs
2.625
3
using UnityEngine; using System; using System.IO; using System.Security.Cryptography; using UniRx; using UniRx.Async; namespace OilMagnate { public class SavableBase<T> : ISavable where T : SavableBase<T>, new() { /// <summary> /// json text. /// </summary> static string _jsonText; /// <summary> /// whether after loading. /// </summary> bool _isLoaded; /// <summary> /// Whether during save. /// </summary> bool _isEditing; public async void SaveAsync() { await UniTask.WaitUntil(() => _isEditing); if (_isLoaded && !_isEditing) { _isEditing = true; var path = GetSavePath(); _jsonText = JsonUtility.ToJson(this); File.WriteAllText(path, _jsonText); #if UNITY_IOS // iOSでデータをiCloudにバックアップさせない設定 UnityEngine.iOS.Device.SetNoBackupFlag(path); #endif _isEditing = false; Debug.Log($"saved data"); } } public static T Load() // ref T target { var json = File.Exists(GetSavePath()) ? File.ReadAllText(GetSavePath()) : ""; var instance = new T(); if (string.IsNullOrEmpty(json)) { instance._isLoaded = true; } else { instance = LoadFromJson(json); } if (instance != null) { instance.OnLoad(); } return instance; } /// <summary> /// Load instance from json data. /// </summary> /// <param name="json">json file.</param> /// <returns>An instance of the specified type.</returns> static T LoadFromJson(string json) { var instance = new T(); try { instance = JsonUtility.FromJson<T>(json); instance._isLoaded = true; } catch (Exception e) { Debug.Log(e.ToString()); } Debug.Log($"loaded data"); return instance; } /// <summary> /// Delete any saved data if it exists. /// </summary> public void Clear() { var savePath = GetSavePath(); if (File.Exists(savePath)) { File.Delete(savePath); Debug.Log($"cleared data"); } } /// <summary> /// Reset save data. /// </summary> public void Reset() { _jsonText = JsonUtility.ToJson(new T()); JsonUtility.FromJsonOverwrite(_jsonText, this); Debug.Log($"reset data"); } /// <summary> /// Get the save path. /// </summary> /// <returns>save path.</returns> static string GetSavePath() { string filePath; #if UNITY_EDITOR filePath = $"{GetSaveKey()}.json"; #else filePath = $"{Application.persistentDataPath}/{GetSaveKey()}.json"; #endif return filePath; } /// <summary> /// セーブする名前をクラス名から取得する。 /// </summary> /// <returns></returns> /// <remarks> /// !現状だと1種類のクラスに対して一意のセーブしか作れない設計になっている。 /// </remarks> static string GetSaveKey() { var provider = new SHA1CryptoServiceProvider(); var hash = provider.ComputeHash(System.Text.Encoding.ASCII.GetBytes(typeof(T).FullName)); return BitConverter.ToString(hash); } /// <summary> /// Called back when loaded save data. /// </summary> protected virtual void OnLoad() { } } }
de9c21c0fbd98e8000bee18317866b5909b73a0c
C#
MJKruszewski/Mod-Bannerlord-SettlersForVillages
/SettlersForVillages/Logger.cs
2.84375
3
using System; using System.IO; using TaleWorlds.Core; namespace SettlersForVillages { public static class Logger { private static string LOGGING_PATH = "./../../Modules/SettlersForVillages/Logs/"; private static string FILE_ERROR_PATH = "./../../Modules/SettlersForVillages/Logs/Errors.log"; private static string FILE_PATH = "./../../Modules/SettlersForVillages/Logs/Debug.log"; static Logger() { if (!Directory.Exists(LOGGING_PATH)) Directory.CreateDirectory(LOGGING_PATH); if (!File.Exists(FILE_ERROR_PATH)) File.Create(FILE_ERROR_PATH); if (!File.Exists(FILE_PATH)) File.Create(FILE_PATH); } public static void logDebug(string log) { if (!Main.Settings.DebugMode) return; using (StreamWriter streamWriter = new StreamWriter(FILE_PATH, true)) streamWriter.WriteLine(log); DisplayInfoMsg("DEBUG | " + log); } public static void logError(string log) { using (StreamWriter streamWriter = new StreamWriter(FILE_ERROR_PATH, true)) streamWriter.WriteLine(log); } public static void logError(Exception exception) { logError("Message " + exception.Message); logError("Error at " + exception.Source.ToString() + " in function " + exception.Message); logError("With stacktrace :\n" + exception.StackTrace); logError("----------------------------------------------------"); if (!Main.Settings.DebugMode) return; DisplayInfoMsg(exception.Message); DisplayInfoMsg(exception.Source); DisplayInfoMsg(exception.StackTrace); } public static void DisplayInfoMsg(string message) { InformationManager.DisplayMessage(new InformationMessage(message)); } } }
0492d76a230f3c156a0d22d3a2bc5c29b5dd8353
C#
Moiraines/Blackcurrant-team
/MonopolyGame/MonopolyGame/Model/Classes/Tiles/StartTile.cs
2.53125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MonopolyGame.Model.Classes { public class StartTile : Tile { private const string START_TILE_NAME = "Start"; public StartTile() : base(START_TILE_NAME) { } public override void Action(Player player) { player.AddMoney(200); } } }
d5dca79d2bafac4695f7a2a9d864aabba9101164
C#
ryanlewis94/ContactsApi
/Contacts.API/Services/ContactRepo.cs
2.671875
3
using Contacts.API.DB; using Contacts.API.Entities; using Contacts.API.Helpers; using Contacts.API.Models; using Contacts.API.ResourceParameters; using System; using System.Collections.Generic; using System.Linq; namespace Contacts.API.Services { public class ContactRepo : IContactRepo { private readonly ContactDb _context; private readonly IPropertyMappingService _propertyMappingService; public ContactRepo(ContactDb context, IPropertyMappingService propertyMappingService) { _context = context ?? throw new ArgumentNullException(nameof(context)); _propertyMappingService = propertyMappingService ?? throw new ArgumentNullException(nameof(propertyMappingService)); } public Contact GetContact(int id) { return _context.Contacts.FirstOrDefault(c => c.Id == id); } public PagedList<Contact> GetContacts(ContactsResourceParameters contactsResourceParameters) { if (contactsResourceParameters == null) { throw new ArgumentNullException(nameof(contactsResourceParameters)); } var collection = _context.Contacts as IQueryable<Contact>; if (contactsResourceParameters.id != 0) { collection = _context.Contacts.Where(c => c.Id == contactsResourceParameters.id); } if (!string.IsNullOrWhiteSpace(contactsResourceParameters.firstname)) { var firstName = contactsResourceParameters.firstname.Trim(); collection = _context.Contacts.Where(c => c.FirstName == firstName); } if (!string.IsNullOrWhiteSpace(contactsResourceParameters.search)) { var searchQuery = contactsResourceParameters.search.Trim(); collection = collection.Where(c => c.FirstName.Contains(searchQuery) || c.LastName.Contains(searchQuery) || c.Phone.Contains(searchQuery) || c.Email.Contains(searchQuery)); } if (!string.IsNullOrWhiteSpace(contactsResourceParameters.OrderBy)) { //get property mapping dictionary var contactPropertyMappingDictionary = _propertyMappingService.GetPropertyMapping<ContactDto, Contact>(); collection = collection.ApplySort(contactsResourceParameters.OrderBy, contactPropertyMappingDictionary); } else { collection = collection.OrderBy(c => c.Id); } return PagedList<Contact>.Create(collection, contactsResourceParameters.PageNumber, contactsResourceParameters.PageSize); } public Contact AddContact(Contact contact) { _context.Contacts.Add(contact); _context.SaveChanges(); return contact; } public Contact UpdateContact(Contact contact) { var result = _context.Contacts.First(c => c.Id == contact.Id); if (result != null) { result.FirstName = contact.FirstName; result.LastName = contact.LastName; result.Phone = contact.Phone; result.Email = contact.Email; _context.SaveChanges(); } return contact; } public Contact DeleteContact(Contact contact) { var contactToDelete = _context.Contacts.First(c => c.Id == contact.Id); if (contactToDelete != null) { _context.Contacts.Remove(contactToDelete); } _context.SaveChanges(); return contact; } } }
35c162f032dfa75b63767a5818bceb7ba5c9bdf9
C#
teshiba/DockingManager
/DockingManager/MultiDockContent.cs
2.859375
3
using WeifenLuo.WinFormsUI.Docking; namespace DockingManager { /// <summary> /// Manages multiple instance which is created from one class derived <see cref="DockContent"/>. /// </summary> public class MultiDockContent : DockContent { /// <summary> /// Initializes a new instance of the <see cref="MultiDockContent"/> class. /// </summary> /// <param name = "formId">Instance identifier of one class derived <see cref="DockContent"/>.</param> public MultiDockContent(string formId) { FormId = formId; Text = formId; } /// <summary> /// Initializes a new instance of the <see cref="MultiDockContent"/> class. /// This constructor is only used in form designer. /// </summary> private MultiDockContent() { } /// <summary> /// Gets delimiter string. /// </summary> public static string PersistStringDelimiter => "::"; /// <summary> /// Gets or sets Instance identifier. /// </summary> public string FormId { get; set; } /// <summary> /// Get PersisitString of this instance. /// </summary> /// <returns>PersistString identified by file name.</returns> protected override string GetPersistString() { return base.GetPersistString() + PersistStringDelimiter + FormId; } } }
3bcc7718f0dd5b9be7fc807272343d175b069c7e
C#
PressmanMatthew/Console-Based-Roguelike-Game
/PressmanM-HW1/MovementHandler.cs
2.796875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading; namespace PressmanM_HW1 { class MovementHandler { OutsideLevel outsidelvl = new OutsideLevel(); static GrassTile grass = new GrassTile(); static PondTile pond = new PondTile(); static int tileLength = grass.GetTileLength(); static int tileHeight = grass.GetTileHeight(); static TileHandler tileHandler = new TileHandler(); static ColorHandler colHandler = new ColorHandler(); static int windowPositionLeft = 0; static int windowPositionUp = 0; static int bufferAdd = Program.bufferAdd; static int windowHeight = Program.windowHeight; //70 static int windowLength = Program.windowLength; static int windowTileNumWidth = windowLength / 10; public int WindowTileNumWidth { get { return windowTileNumWidth; } } static int windowTileNumHeight = windowHeight / 10; public int WindowTileNumHeight { get { return windowTileNumHeight; } } static int innerTileBorder = tileHeight / 5; public int InnerTileBorder //Accessor for innerTileBorder { get { return innerTileBorder; } } static int charTilePositionLeft = windowTileNumWidth / 2; public int CharTilePositionLeft //Accessor for charTilePositionLeft { get { return charTilePositionLeft; } } static int charTilePositionUp = windowTileNumHeight / 2; public int CharTilePositionUp //Accessor for charTilePositionUp { get { return charTilePositionUp; } } static int charPixelPositionLeft = charTilePositionLeft * 10; public int CharPixelPositionLeft //Accessor for charPixelPositionLeft { get { return charPixelPositionLeft; } } static int charPixelPositionUp = charTilePositionUp * 10; public int CharPixelPositionUp //Accessor for charPixelPositionUp { get { return charPixelPositionUp; } } static int horMoveSpeed = tileLength; static int vertMoveSpeed = tileHeight; static int highBound = bufferAdd + tileLength; static int lowBound = 0; static int cursorLeftPos; static int cursorUpPos; static int colorNum; public MovementHandler() { } public void CheckForMovement(ConsoleKeyInfo inputKey) { //Change cursor position to the top left pixel of the characters position cursorLeftPos = Console.WindowLeft + charPixelPositionLeft; cursorUpPos = Console.WindowTop + charPixelPositionUp; Console.SetCursorPosition(cursorLeftPos, cursorUpPos); //Detect if movement is being attempted if (inputKey.Key == ConsoleKey.A | inputKey.Key == ConsoleKey.D | inputKey.Key == ConsoleKey.W | inputKey.Key == ConsoleKey.S) { switch (inputKey.Key) { case ConsoleKey.A: if ((windowPositionLeft - (horMoveSpeed)) < lowBound) { } else { tileHandler.ReplaceTile(windowPositionLeft, windowPositionUp, horMoveSpeed, charPixelPositionLeft, charPixelPositionUp); cursorLeftPos = Console.WindowLeft + charPixelPositionLeft - tileLength; cursorUpPos = Console.WindowTop + charPixelPositionUp; Console.SetCursorPosition(cursorLeftPos, cursorUpPos); for (int i = 0; i < tileHeight; i++) { for (int j = 0; j < tileLength; j++) { colHandler.ColorCodeReturn(cursorLeftPos + j, cursorUpPos + i, 1); } } Thread.Sleep(100); windowPositionLeft -= horMoveSpeed; Console.SetWindowPosition(windowPositionLeft, windowPositionUp); } break; case ConsoleKey.D: if ((windowPositionLeft + (horMoveSpeed)) > highBound - 45) { } else { tileHandler.ReplaceTile(windowPositionLeft, windowPositionUp, horMoveSpeed, charPixelPositionLeft, charPixelPositionUp); Console.SetWindowPosition(windowPositionLeft, windowPositionUp); cursorLeftPos = Console.WindowLeft + charPixelPositionLeft + horMoveSpeed; cursorUpPos = Console.WindowTop + charPixelPositionUp; Console.SetCursorPosition(cursorLeftPos, cursorUpPos); for (int i = 0; i < tileHeight; i++) { for (int j = 0; j < tileLength; j++) { colHandler.ColorCodeReturn(cursorLeftPos + j, cursorUpPos + i, 1); } } Thread.Sleep(100); windowPositionLeft += horMoveSpeed; Console.SetWindowPosition(windowPositionLeft, windowPositionUp); } break; case ConsoleKey.W: if ((windowPositionUp - (vertMoveSpeed * 2)) < lowBound) { } else { tileHandler.ReplaceTile(windowPositionLeft, windowPositionUp, vertMoveSpeed, charPixelPositionLeft, charPixelPositionUp); cursorLeftPos = Console.WindowLeft + charPixelPositionLeft; cursorUpPos = Console.WindowTop + charPixelPositionUp - tileHeight; Console.SetCursorPosition(cursorLeftPos, cursorUpPos); for (int i = 0; i < tileHeight; i++) { for (int j = 0; j < tileLength; j++) { colHandler.ColorCodeReturn(cursorLeftPos + j, cursorUpPos + i, 1); } } Thread.Sleep(100); windowPositionUp -= vertMoveSpeed; Console.SetWindowPosition(windowPositionLeft, windowPositionUp); } break; case ConsoleKey.S: if ((windowPositionUp + (vertMoveSpeed * 2)) > highBound) { } else { tileHandler.ReplaceTile(windowPositionLeft, windowPositionUp, vertMoveSpeed, charPixelPositionLeft, charPixelPositionUp); cursorLeftPos = Console.WindowLeft + charPixelPositionLeft; cursorUpPos = Console.WindowTop + charPixelPositionLeft + tileHeight; Console.SetCursorPosition(cursorLeftPos, cursorUpPos); for (int i = 0; i < tileHeight; i++) { for (int j = 0; j < tileLength; j++) { colHandler.ColorCodeReturn(cursorLeftPos + j, cursorUpPos + i, 1); } } Thread.Sleep(100); windowPositionUp += vertMoveSpeed; Console.SetWindowPosition(windowPositionLeft, windowPositionUp); } break; } } else { windowPositionLeft = 100; Console.SetWindowPosition(windowPositionLeft, windowPositionUp); } } } }
afd9d2ec9cc729c73aaa7723dc951e0ab47a4bb5
C#
flpsno/kasolution-20487
/Mod. 10/backend/FN.Store/FN.Store.Data/EF/Maps/ProdutoMap.cs
2.640625
3
using FN.Store.Domain.Entities; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; namespace FN.Store.Data.EF.Maps { public class ProdutoMap : IEntityTypeConfiguration<Produto> { public void Configure(EntityTypeBuilder<Produto> builder) { //Table builder.ToTable(nameof(Produto)); //PK builder.HasKey(pk => pk.Id); // builder.HasKey(pk => new { pk.Id, pk.Nome }); --> PK composta //Colunas builder.Property(c => c.Nome) .IsRequired() .HasColumnType("varchar(80)"); builder.Property(c => c.NomeArquivo) .IsRequired() .HasColumnType("varchar(255)"); builder.Property(c => c.Preco) .HasColumnType("money"); //Relacionamentos builder .HasOne(c => c.TipoProduto) .WithMany(c => c.Produtos).HasForeignKey(fk => fk.TipoProdutoId); } } }
30b6bda86abbe3cebc4f4cbb113d790b69cb3cf5
C#
ShaifulSolehan/C-project
/Form4.cs
2.984375
3
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.IO; namespace SE_project { public partial class Form4 : Form { public Form4() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { bool notfound=true; int count=0; string output; string findingname; findingname = textBox2.Text.ToLower(); string Path = "db.txt"; List<string> line = new List<string>(); List<string> samename = new List<string>(); //list to printing the list line = File.ReadAllLines(Path).ToList(); foreach (string finding in line) { string[] column = finding.Split(','); if (findingname.ToLower() == column[1].ToLower() && count != line.Count()) //check the name search same in the text file { samename.Add("Name " + column[1] + " with Matric No. " + column[2]); notfound = false; } } if (notfound == false) { output = string.Join("\n", samename); //printing the list MessageBox.Show("Found " + "\n" + "\n" + output); textBox2.Focus(); } else { MessageBox.Show("Name " + findingname + " not found"); } } private void Form4_Load(object sender, EventArgs e) { textBox2.Focus(); } private void textBox1_TextChanged(object sender, EventArgs e) { } } }
036d89d8839d0d8e6cc62696b9e68d66652b015b
C#
louwangzhiyuY/Presentation.ETW
/Counter/ThreadSyncTester.cs
3.28125
3
using System.IO; using System.Runtime.CompilerServices; using System.Threading; namespace Counter { internal class ThreadSyncTester { private readonly CancellationToken _token; private volatile int _aCounter; private volatile int _bCounter; public ThreadSyncTester(CancellationToken token) { _token = token; _aCounter = 0; _bCounter = 0; } [MethodImpl(MethodImplOptions.NoInlining)] public void ThreadA() { while (!_token.IsCancellationRequested) { if (_bCounter == _aCounter) { _aCounter = _aCounter + 1; } } } [MethodImpl(MethodImplOptions.NoInlining)] public void ThreadB() { while (!_token.IsCancellationRequested) { if (_aCounter == _bCounter + 1) { _bCounter = _bCounter + 1; } } } public void PrintResult(TextWriter output) { output.WriteLine("A counter: " + _aCounter); output.WriteLine("B counter: " + _bCounter); } } }
3a2f5eedd8cfbf0e717f43e3b25055bcb7bbfb09
C#
sagerioz/MyTripTracker
/MyTripTracker.UI/Services/IApiClient.cs
3.21875
3
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading.Tasks; using MyTripTracker.BackService.Models; namespace MyTripTracker.UI.Services { public interface IApiClient { // These extension methods here are used // for encapsulating utility methods on top of http // client. We are creating specific extensions which // make it easier to do stuff. For example: go get // json and deserialize it as a trip. Task<List<BackService.Models.Trip>> GetTripsAsync(); Task<BackService.Models.Trip> GetTripAsync(int id); Task PutTripAsync(Trip tripToUpdate); Task AddTripAsync(Trip tripToAdd); } public class ApiClient : IApiClient { private readonly HttpClient _HttpClient; public ApiClient(HttpClient httpClient) { _HttpClient = httpClient; } public async Task<Trip> GetTripAsync(int id) { var response = await _HttpClient.GetAsync($"/api/Trips{id}"); response.EnsureSuccessStatusCode(); return await response.Content.ReadAsJsonAsync<Trip>(); } public async Task<List<Trip>> GetTripsAsync() { var response = await _HttpClient.GetAsync("/api/Trips"); response.EnsureSuccessStatusCode(); return await response.Content.ReadAsJsonAsync<List<Trip>>(); } public async Task PutTripAsync(Trip tripToUpdate) { var response = await _HttpClient.PutJsonAsync($"api/Trips/{tripToUpdate.Id}", tripToUpdate); response.EnsureSuccessStatusCode(); } public async Task AddTripAsync(Trip tripToAdd) { var response = await _HttpClient.PostJsonAsync("/api/Trips", tripToAdd); response.EnsureSuccessStatusCode(); } } }
987f771d9a7284cf37ab90cc2776b99ee63ebc93
C#
Hengle/SboxDiscordBot
/SboxDiscordBot/Commands/HelpCommand.cs
2.6875
3
using System; using System.Reflection; using Disco; namespace SboxDiscordBot.Commands { public class Help : Command { public override string[] Aliases => new[] {"help", "h"}; public override string[] Syntax => new string[] { }; public override string Description => "Get a list of bot commands"; public override string Icon => "💁"; public override int MinArgs => 0; public override int MaxArgs => 0; public override void Run(CommandArgs args) { var eb = Utils.BuildDefaultEmbed(); eb.WithTitle("Help"); foreach (var t in Assembly.GetExecutingAssembly().GetTypes()) { if (t.Namespace == null) continue; if (t.Namespace.Equals("SboxDiscordBot.Commands", StringComparison.CurrentCultureIgnoreCase)) if (!t.IsAbstract && t.BaseType == typeof(Command)) { var cmd = (Command) Activator.CreateInstance(t); var cmdSyntaxStr = ""; foreach (var s in cmd.Syntax) cmdSyntaxStr += $" [{s}]"; var cmdAliasesStr = ""; for (var i = 0; i < cmd.Aliases.Length; ++i) { if (i > 0 && i < cmd.Aliases.Length) cmdAliasesStr += " / "; cmdAliasesStr += cmd.Aliases[i]; } eb.AddField("`" + ConfigBucket.prefix + cmdAliasesStr + cmdSyntaxStr + "`", cmd.Description); } } args.Message.Channel.SendMessageAsync("", false, eb.Build()); } } }
24b10b03ea69efba90946f06225ed6c193b44c9d
C#
Ian-Meadows/ResourceCollection
/Resource Collection/Assets/Scripts/ItemStuff/Item.cs
2.671875
3
using UnityEngine; using System.Collections; using System; [Serializable] public class Item { public int worth; public string name; public int ItemType; public int ImageLocation; public enum ItemBase {Coal, Ore, Plate, Wire, Processor, Computer}; public ItemBase itemBase = new ItemBase(); public Item(int ItemType, ItemImageHolder itemHolder) { Item baseItem = itemHolder.getItem(ItemType); this.ItemType = ItemType; worth = baseItem.worth; name = baseItem.name; ImageLocation = baseItem.ImageLocation; itemBase = baseItem.itemBase; } public Item(int ItemType, int worth, string name, int ImageLocation, ItemBase itemBase) { this.ItemType = ItemType; this.worth = worth; this.name = name; this.ImageLocation = ImageLocation; this.itemBase = itemBase; } }
f019be9b7904b2442cf179e353cd4d130378d8ac
C#
RaqG/SearchExtensions
/ExtensionsSearch/ExtensionsSearch/FolderSearch.cs
3.546875
4
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SearchExtensions { public class FolderSearch { /* Lista todos os arquivos de um tipo de extensão informada, dentro de um caminho especificado */ public string ListOfFiles(string sourceFolder, string extensionFiles) { // Coloca em um array, os diretorios e subdiretorios do caminho informado string[] dirs = null; try { dirs = Directory.GetDirectories(sourceFolder); } catch { } /* Se o array dir estiver vazio, significa que não há mais diretórios ou subdiretório Caso contrário, procura-se mais subdiretorios pelo método recursivo ListOfFiles*/ /* Cria-se um array de files e coloca todos os arquivos daquele diretorio especifico dentro do array files */ if (dirs == null || dirs.Length == 0) { try { string[] files = Directory.GetFiles(sourceFolder, extensionFiles); string file = ""; for (int i = 0; i < files.Length; i++) { file += files[i] + "\n"; } return file; } catch { return ""; } } else { string filesFound = ""; foreach (string dir in dirs) filesFound += ListOfFiles(dir, extensionFiles); return filesFound; } } } }
8fb12c5448162034bb3c5cc06fe529f057c3960e
C#
epicwebgame/dragdrop
/DotNet/Building a Simple LINQ Provider/CSVToSQL/CSVToSQL/BooleanExtensions.cs
3.109375
3
using System; namespace CSVToSQL.Extensions { public static class BooleanExtensions { public static void ThrowIfTrue(this bool b) { if (b) throw new Exception(); } public static void ThrowIfTrue(this bool b, Exception exception) { if (b) throw exception; } public static void ThrowIfTrue(this bool b, string message) { if (b) throw new Exception(message); } public static void ThrowIfTrue(this bool b, string message, params object[] args) { if (b) throw new Exception(string.Format(message, args)); } public static void ThrowIfTrue(this bool b, Exception innerException, string message, params object[] args) { if (b) throw new Exception(string.Format(message, args), innerException); } public static void ThrowIfFalse(this bool b) { if (!b) throw new Exception(); } public static void ThrowIfFalse(this bool b, Exception exception) { if (!b) throw exception; } public static void ThrowIfFalse(this bool b, string message) { if (!b) throw new Exception(message); } public static void ThrowIfFalse(this bool b, string message, params object[] args) { if (!b) throw new Exception(string.Format(message, args)); } public static void ThrowIfFalse(this bool b, Exception innerException, string message, params object[] args) { if (!b) throw new Exception(string.Format(message, args), innerException); } } }
ffe187f7899c2bf48a800b843a793984517e0bcf
C#
beejones/ZonePlayer
/ZonePlayer/PlayerChangedEventArgs.cs
2.796875
3
//--------------------------------------------------------------- // The MIT License. Beejones //--------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; /// <summary> /// Implementation of <see cref="PlayerChangedEventArgs"/> for creating player changed events /// </summary> namespace ZonePlayer { public sealed class PlayerChangedEventArgs : EventArgs { /// <summary> /// Initializes a new instance of the <see cref="PlayerChangedEventArgs"/> class. /// </summary> /// <param name="zoneIndex">the zone name</param> /// <param name="newPlayerType">the new player type</param> public PlayerChangedEventArgs(string zoneName, PlayerType newPlayerType) { this.ZoneName = zoneName; this.NewPlayerType = newPlayerType; } /// <summary> /// gets or sets the zone name /// </summary> public string ZoneName { get; set; } /// <summary> /// Gets or sets the new player type /// </summary> public PlayerType NewPlayerType { get; set; } } }
544a02b0c23e031d64948e3652bd8709544b216d
C#
RafalH4/Clinic.API
/Repositories/ReferralRepository.cs
2.671875
3
using Clinic.API.Data; using Clinic.API.IRepositories; using Clinic.API.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Clinic.API.Repositories { public class ReferralRepository : IReferralRepository { private readonly DataContext _context; public ReferralRepository(DataContext context) { _context = context; } public async Task<IEnumerable<Referral>> Get() => await Task.FromResult(_context.Referrals.ToList()); public async Task<IEnumerable<Referral>> GetByAppointment(Appointment appointment) => await Task.FromResult(_context.Referrals .Where(referral => referral.Appointment.Equals(appointment)).ToList()); public async Task<IEnumerable<Referral>> GetByDate(DateTime date) => await Task.FromResult(_context.Referrals .Where(referral => referral.CreatedAt.Equals(date)).ToList()); public async Task<Referral> GetById(Guid id) => await Task.FromResult(_context.Referrals .SingleOrDefault(referral => referral.Id.Equals(id))); public async Task AddReferral(Referral referral) { await _context.Referrals.AddAsync(referral); await _context.SaveChangesAsync(); await Task.CompletedTask; } public async Task DeleteReferral(Referral referral) { _context.Referrals.Remove(referral); await _context.SaveChangesAsync(); await Task.CompletedTask; } public async Task UpdateReferral(Referral referral) { _context.Referrals.Update(referral); await _context.SaveChangesAsync(); await Task.CompletedTask; } } }
5bc99b79e7222e4fcc9f136ea594f6e0b72f1a0b
C#
xianyu8866/Restaurant-Management-System--C-sharp-project
/HungerGames.V2.0/Presentation Layer/Order_Dashboard.cs
2.53125
3
using HungerGames.V2._0.Business_Logic_Layer; using HungerGames.V2._0.DataAccessLayer; using HungerGames.V2._0.DataAccessLayer.Entities; using System; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace HungerGames.V2._0.Presentation_Layer { public partial class Order_Dashboard : Form { MenuService ms; DataAccess da; OrderService os; int x; public Order_Dashboard() { InitializeComponent(); ms = new MenuService(); da = new DataAccess(); os = new OrderService(); itemComboBox.DataSource = ms.GetMenuName(); } private void Order_Dashboard_FormClosing(object sender, FormClosingEventArgs e) { Application.Exit(); } int a; string text, text2; private void removeButton_Click(object sender, EventArgs e) { if (orderListBox.SelectedIndex == -1) { MessageBox.Show("Please select item from Menu!"); } else { orderListBox.Items.RemoveAt(orderListBox.SelectedIndex); } } private void clearButton_Click(object sender, EventArgs e) { Varriables.a = 0; orderListBox.Items.Clear(); } private void backButton_Click(object sender, EventArgs e) { this.Hide(); Employee_Dashboard employee_Dashboard = new Employee_Dashboard(); employee_Dashboard.Show(); } private void totalButton_Click(object sender, EventArgs e) { int a = 0; string text = "_ _ _ _ _ _ _ _ _ _ _ _ _ "; string text2 = " Total = " + Varriables.total(a) + "TAKA"; orderListBox.Items.Add(text); orderListBox.Items.Add(text2); SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["HungerGamesDb"].ConnectionString); connection.Open(); string sql = "INSERT INTO Orders (EmployeeName, EmployeeId, Month, Price) VALUES ('" + nametextBox.Text + "','" + idtextBox.Text + "','" + dateTimePicker1.Text + "','" + Varriables.total(a) + "');"; SqlCommand cmd = new SqlCommand(sql, connection); cmd.ExecuteNonQuery(); MessageBox.Show("Your order has been placed"); } private void addButton_Click(object sender, EventArgs e) { if (itemComboBox.SelectedItem != null) { if (!string.IsNullOrEmpty(QuatityTextBox.Text)) { da = new DataAccess(); string sql = "SELECT Price FROM Menu WHERE MenuName='" + itemComboBox.SelectedItem.ToString() + "' "; SqlDataReader reader = da.GetData(sql); Menus m = new Menus(); while (reader.Read()) { m.Price = (int)reader["Price"]; } x = Convert.ToInt32(m.Price) * Convert.ToInt32(QuatityTextBox.Text); string text = itemComboBox.SelectedItem.ToString() + " " + QuatityTextBox.Text + " " + x + "taka"; orderListBox.Items.Add(text); itemComboBox.SelectedItem = null; QuatityTextBox.Clear(); Varriables.total(x); } else { MessageBox.Show("Please Select Quantity!"); } } else { MessageBox.Show("Please select an item!"); } } } }
a67ecda8348139f5d4e0fa72789033acdd62c042
C#
cnc-kvsr/Algorithms
/VARS1/VARS05.cs
3.15625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace VARS1 { public static class VARS05 { public static void AnaKod() { string[] meyveler = { "elma", "armut", "muz", "üzüm", "şeftali" }; var meyve = from m in meyveler where m[0] == 'a' select m; // Direk Console.WriteLine(meyve) diyerek çıktı alındığında istenilen sonuç çıktıya yansımıyor!!! // Console.WriteLine(meyve); // WriteLine deyince alt alta yazar. Write dersek yan yana yazar! // {} kümeli parantez içine tek satırlık bir komut yazacaksak paranteze gerek yok. foreach (string m in meyve) Console.Write(m); } } }
30d5e85e06e6c1827c88e8adefaa274a7460416f
C#
AnthonyRyck/SuiviFormation
/src/FormationApp/Composants/RechercheFormation.razor.cs
2.65625
3
using AccessData; using AccessData.Models; using Microsoft.AspNetCore.Components; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace FormationApp.Composants { public partial class RechercheFormation : ComponentBase { #region Properties [Inject] public SqlContext SqlService { get; set; } /// <summary> /// Pour pouvoir récupérer la formation qui est sélectionné /// </summary> [Parameter] public EventCallback<CatalogueFormations> OnSelectFormationClick { get; set; } /// <summary> /// Résultat de la recherche sur le nom de la formation. /// </summary> public IEnumerable<CatalogueFormations> AllFormations { get; set; } /// <summary> /// Nom de la personne recherché. /// </summary> public string NomFormation { get { return _nomFormation; } set { _nomFormation = value; GetFormationByName(value); } } private string _nomFormation; #endregion #region Constructeur #endregion #region Internal methods #endregion #region Private methods /// <summary> /// Récupère la liste des formations par rapport à un nom de formation. /// </summary> /// <param name="nomFormation"></param> private async void GetFormationByName(string nomFormation) { AllFormations = await SqlService.GetFormationAsync(nomFormation); StateHasChanged(); } #endregion } }
761a376a83309c33b1d6166d325519aa7990184f
C#
bmaulana/lone-worker-poc
/LoneWorkerPoC/LoneWorkerPoC/BandManager.cs
2.578125
3
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Windows.Storage; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Media.Imaging; using Microsoft.Band; using Microsoft.Band.Notifications; using Microsoft.Band.Tiles; namespace LoneWorkerPoC { public class BandManager { private const int BandDelay = 100; //delay in communicating with the band for sensor retreival in milliseconds private const string RunningMessage = "Refreshing"; private IBandClient _bandClient; private bool _started; public async Task<bool> ConnectTask() { var pairedBands = await BandClientManager.Instance.GetBandsAsync(); if (pairedBands.Length < 1) return false; _bandClient = await BandClientManager.Instance.ConnectAsync(pairedBands[0]); //TODO add consent stuff _started = true; return true; } public bool IsConnected() { return _started; } public async Task<decimal> DisplaySkinTemperature(TextBlock output) { if (!_started) return -1; output.Text = RunningMessage; try { bool tempConsentGranted; // Check whether the user has granted access to the SkinTemperature sensor. if (_bandClient.SensorManager.SkinTemperature.GetCurrentUserConsent() == UserConsent.Granted) { tempConsentGranted = true; } else { tempConsentGranted = await _bandClient.SensorManager.SkinTemperature.RequestUserConsentAsync(); } if (!tempConsentGranted) { output.Text = "Access to the skin temperature sensor is denied."; } else { var readings = new List<double>(); // Subscribe to SkinTemperature data. _bandClient.SensorManager.SkinTemperature.ReadingChanged += (s, args) => { readings.Add(args.SensorReading.Temperature); }; await _bandClient.SensorManager.SkinTemperature.StartReadingsAsync(); // Receive SkinTemperature data for a while, then stop the subscription. while (readings.Count == 0) { await Task.Delay(TimeSpan.FromMilliseconds(BandDelay)); } await _bandClient.SensorManager.SkinTemperature.StopReadingsAsync(); var average = (decimal)readings.Sum() / readings.Count; var message = average + " C"; output.Text = message; return average; } } catch (Exception ex) { output.Text = ex.ToString(); } return -1; } public async Task<decimal> DisplayHeartRate(TextBlock output) { if (!_started) return -1; output.Text = RunningMessage; try { bool heartRateConsentGranted; // Check whether the user has granted access to the HeartRate sensor. if (_bandClient.SensorManager.HeartRate.GetCurrentUserConsent() == UserConsent.Granted) { heartRateConsentGranted = true; } else { heartRateConsentGranted = await _bandClient.SensorManager.HeartRate.RequestUserConsentAsync(); } if (!heartRateConsentGranted) { output.Text = "Access to the heart rate sensor is denied."; } else { var readings = new List<int>(); // Subscribe to HeartRate data. _bandClient.SensorManager.HeartRate.ReadingChanged += (s, args) => { readings.Add(args.SensorReading.HeartRate); }; await _bandClient.SensorManager.HeartRate.StartReadingsAsync(); // Receive HeartRate data for a while, then stop the subscription. while (readings.Count == 0) { await Task.Delay(TimeSpan.FromMilliseconds(BandDelay)); } await _bandClient.SensorManager.HeartRate.StopReadingsAsync(); var average = (decimal)readings.Sum() / readings.Count; var message = average + " BPM"; output.Text = message; return average; } } catch (Exception ex) { output.Text = ex.ToString(); } return -1; } public async Task<long> GetPedometer(TextBlock output) { if (!_started) return -1; output.Text = RunningMessage; try { bool consentGranted; // Check whether the user has granted access to the Pedometer sensor. if (_bandClient.SensorManager.Pedometer.GetCurrentUserConsent() == UserConsent.Granted) { consentGranted = true; } else { consentGranted = await _bandClient.SensorManager.Pedometer.RequestUserConsentAsync(); } if (!consentGranted) { output.Text = "Access to the pedometer is denied."; } else { var readings = new List<long>(); _bandClient.SensorManager.Pedometer.ReadingChanged += (s, args) => { readings.Add(args.SensorReading.TotalSteps); }; await _bandClient.SensorManager.Pedometer.StartReadingsAsync(); while (readings.Count == 0) { await Task.Delay(TimeSpan.FromMilliseconds(BandDelay)); } await _bandClient.SensorManager.Distance.StopReadingsAsync(); return readings[readings.Count - 1]; } } catch (Exception ex) { output.Text = ex.ToString(); } return -1; } public async Task<long> GetDistance(TextBlock output) { if (!_started) return -1; output.Text = RunningMessage; try { bool consentGranted; // Check whether the user has granted access to the Distance sensor. if (_bandClient.SensorManager.Distance.GetCurrentUserConsent() == UserConsent.Granted) { consentGranted = true; } else { consentGranted = await _bandClient.SensorManager.Distance.RequestUserConsentAsync(); } if (!consentGranted) { output.Text = "Access to the distance sensor is denied."; } else { var readings = new List<long>(); _bandClient.SensorManager.Distance.ReadingChanged += (s, args) => { readings.Add(args.SensorReading.TotalDistance); }; await _bandClient.SensorManager.Distance.StartReadingsAsync(); while (readings.Count == 0) { await Task.Delay(TimeSpan.FromMilliseconds(BandDelay)); } await _bandClient.SensorManager.Distance.StopReadingsAsync(); return readings[readings.Count - 1]; } } catch (Exception ex) { output.Text = ex.ToString(); } return -1; } public async Task SendNotification(TextBlock output, string title, string message) { if (!_started) return; // output.Text = "Sending..."; try { // Create a Tile. var myTileId = new Guid("D0BAB7A8-FFDC-43C3-B995-87AFB2A43387"); var myTile = new BandTile(myTileId) { Name = "Notifications Tile", TileIcon = await LoadIcon("ms-appx:///Assets/SampleTileIconLarge.png"), SmallIcon = await LoadIcon("ms-appx:///Assets/SampleTileIconSmall.png") }; // // Remove the Tile from the Band, if present. An application won't need to do this everytime it runs. // But in case you modify this sample code and run it again, let's make sure to start fresh. // TODO add version check - if version is same skip this step, if changed remove old tile first // await bandClient.TileManager.RemoveTileAsync(myTileId); // Check if tile exists in the band var installedApps = await _bandClient.TileManager.GetTilesAsync(); bool[] exists = { false }; foreach (var tile in installedApps.Where(tile => !exists[0] && tile.TileId == myTileId)) { exists[0] = true; } // Create new tile if not if (!exists[0]) { await _bandClient.TileManager.AddTileAsync(myTile); } // Send a notification. await _bandClient.NotificationManager.SendMessageAsync(myTileId, title, message, DateTimeOffset.Now, MessageFlags.ShowDialog); //output.Text = "Message sent."; } catch (Exception ex) { output.Text = ex.ToString(); } } private static async Task<BandIcon> LoadIcon(string uri) { var imageFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri(uri)); using (var fileStream = await imageFile.OpenAsync(FileAccessMode.Read)) { var bitmap = new WriteableBitmap(1, 1); await bitmap.SetSourceAsync(fileStream); return bitmap.ToBandIcon(); } } } }
f359a557e0d7e6571795876777f03dee68f1eb08
C#
trpakov/ComputerPartsApp
/ComputerParts/Parts/RAM.cs
3.078125
3
using System; namespace ComputerPartsLibrary { [Serializable()] public class RAM : Part { public int CapacityGB { get; set; } public string Type { get; set; } public int SpeedMHz { get; set; } public RAM( string manufacturer, string name, string model, decimal price, string pictureURL, string url, int capacityGB, string type, int speedMHz) : base(manufacturer, name, model, price, pictureURL, url) { CapacityGB = capacityGB; Type = type; SpeedMHz = speedMHz; } public override string GetPartInfo() => "Паметта с произволен достъп (RAM) е вид компютърна памет,\nкоято позволява неограничен достъп до произволна част от\nзапаметените данни. Има относително голяма скорост.\nНамира широко приложение в изчислителната техника."; public override string ToStringInCSV() => $"\"RAM\",\"{Manufacturer}\",\"{Name}\",\"{Model}\",\"{Price}\",\"{PictureURL}\",\"{URL}\",\"{CapacityGB}\",\"{Type}\",\"{SpeedMHz}\""; } }
a264a53f16a3716559fb861b7695aacd00d44ab5
C#
ReznichenkoSergey/ThePackage
/ThePackage/Services/StaffToPointService.cs
2.6875
3
using System.Collections.Generic; using System.Linq; using ThePackage.Models.Abstract; using ThePackage.Models.Database; using ThePackage.Models.Entities; using ThePackage.Services.Interfaces; namespace ThePackage.Services { public class StaffToPointService : IService<StaffToPoint> { public BaseRepository<StaffToPoint> Repository { get; set; } public StaffToPointService(PackageDbContext dbContext) { Repository = new BaseRepository<StaffToPoint>(dbContext); } public void Create(StaffToPoint item) { Repository.Create(item); } public void Delete(int id) { Repository.Remove(id); } public List<StaffToPoint> GetAll() { return Repository.GetAll().ToList(); } public StaffToPoint Update(int id, StaffToPoint updatedItem) { Repository.Update(updatedItem); return updatedItem; } public StaffToPoint FindById(int id) { return Repository.FindById(id); } public IQueryable<StaffToPoint> GetQuery() { return Repository.GetAll(); } } }
07e7ad3557fa1eeb44baff80e6b6e16f12029a2e
C#
homer-zhang/hydra-BAPI
/src/Lonsid.MES.Core/MesManager/MesManager.cs
2.828125
3
using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; namespace Lonsid.MES.MesManager { public class MesManager : IMesManager { public MesManager() { } public string CallBapi(string parm) { string output = ""; //输出字符串 if (!string.IsNullOrWhiteSpace(parm)) { Process process = new Process();//创建进程对象 ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.WorkingDirectory = "D:\\HYDRA"; startInfo.FileName = "D:\\HYDRA\\hysys.bat"; startInfo.Arguments = string.Format("1 \"{0}\"", parm);//“/C”表示执行完命令后马上退出 startInfo.UseShellExecute = false;//不使用系统外壳程序启动 startInfo.RedirectStandardInput = false;//不重定向输入 startInfo.RedirectStandardOutput = true; //重定向输出 startInfo.CreateNoWindow = false;//不创建窗口 process.StartInfo = startInfo; try { if (process.Start())//开始进程 { //process.WaitForExit(300000);//这里无限等待进程结束 output += process.StandardOutput.ReadToEnd();//读取进程的输出 } else throw new Exception("启动进程失败!"); } catch (Exception ex) { output += "进程执行过程中发生错误\r\n"; output = ex.Message;//捕获异常,输出异常信息 } finally { if (process != null) process.Close(); } } return output; } } }
3f438a7997d804d7d7e59f2077d4e6905b5d5e0f
C#
AmrElshenawy/Automated-Maintenance-Reminder
/Automated Maintenance Reminder/FixturesChecker.cs
2.875
3
using System; using System.Linq; using Excel = Microsoft.Office.Interop.Excel; namespace Automated_Maintenance_Reminder { class FixturesChecker : Program { private bool yellowFlag = false; private bool redFlag = false; //Flags getter public string getFlag() { if (redFlag == true) return "redFlag"; else if (yellowFlag == true) return "yellowFlag"; return "greenFlag"; } //Header information in the email public string HeaderInfo() { string headerText = ""; headerText = "This is an automated email reminder and tracker for test fixtures maintenance.<br/>" + "Please follow WI-718 for the 16-week checks.<br/>For any questions, please contact Amr Elshenawy or Peter Abercrombie.<br/>" + "<br/>Please do NOT reply to this email as it is not monitored.<br/><br/>"; return headerText; } //Email body if Excel object can't open/read Excel Log file public string FileMissing() { string errorText = ""; errorText = "This is an automated email reminder and tracker for test fixtures maintenance.<br/>" + "<br/><br/><b><font color=red>ERROR - can't find/access Excel file for Maintenance Log. " + @"Please ensure the file is G:\Test Eng\Documents\Test Fixture Maintenance\Test Fixture Maintenance Log.xls</b></font><br/><br/>"; return errorText; } public string FixtureChecker(string type) { int rowLimit = 0; string emailBody = ""; Excel.Worksheet worksheet = null; Excel.Range range = null; if (type == "Breakdown Fixtures") { emailBody += "**************************************************************" + //Formatting "<br/><div style = margin-left:150px'><b> BREAKDOWN FIXTURES </b></div>"; rowLimit = rowCount_Sheet1; worksheet = xlWorksheet1; range = xlRange1; } else if (type == "HST Fixtures") { emailBody += "**************************************************************" + //Formatting "<br/><div style = margin-left:180px'><b> HST FIXTURES </b></div>"; rowLimit = rowCount_Sheet2; worksheet = xlWorksheet2; range = xlRange2; } /* Scan through the entire worksheet and dump all unique serial numbers in list */ for (int j = 4; j < rowLimit; j++) { if (worksheet.Cells[j, 1] != null && worksheet.Cells[j, 1].Value2 != null) { serialNumbersList.Add(range.Cells[j, 5].Value2); } } /* Take each unique serial number from the list and scan the worksheet for for all maintenance dates for that number. Add those dates to maintained_Dates list.*/ foreach (string part in serialNumbersList) { for (int i = 4; i < rowLimit; i++) { if (worksheet.Cells[i, 1] != null && worksheet.Cells[i, 1].Value2 != null) { serialNumber = range.Cells[i, 5].Value2; double d = double.Parse(range.Cells[i, 1].Value2.ToString()); DateTime converted = DateTime.FromOADate(d); if (serialNumber == part) { partNumber = range.Cells[i, 4].Value2; maintained_Dates.Add(converted); } } } latestDate = maintained_Dates.Max(); //Find the latest date amongst list of dates for that fixture daysElapsed = (DateTime.Now - latestDate).Days; nextMaintenance = latestDate.AddDays(112); daysLeft = (nextMaintenance - DateTime.Now).Days; maintained_Dates.Clear(); //Clear the list for new dates for the next serial number if (daysLeft > 30) { emailBody += "**************************************************************" + "<br/><b>Part Number: </b>" + partNumber + "<br/><b>Serial Number: </b>" + part + "<br/><b>Last time maintained: </b>" + latestDate.ToShortDateString() + "<br/><b>Time elapsed since last maintenance: </b>" + daysElapsed + " days OR " + daysElapsed / 7 + " weeks." + "<br/><b>Next Maintenance: </b>" + nextMaintenance.ToShortDateString() + " (" + daysLeft + ")" + " days left.<br/>"; } else if (daysLeft > 14 && daysLeft <= 30) { emailBody += "**************************************************************" + "<font color=#d17117><b>" + "<br/><color='yellow'><b>Part Number: </b>" + partNumber + "<br/><b>Serial Number: </b>" + part + "<br/><b>Last time maintained: </b>" + latestDate.ToShortDateString() + "<br/><b>Time elapsed since last maintenance: </b>" + daysElapsed + " days OR " + daysElapsed / 7 + " weeks." + "<br/><b>Next Maintenance: </b>" + nextMaintenance.ToShortDateString() + " (" + daysLeft + ")" + " days left.<br/>" + "</b></font>"; yellowFlag = true; //Indicate email frequency } else if (daysLeft <= 14) { emailBody += "**************************************************************" + "<font color=red><b>" + "<br/><b>Part Number: </b>" + partNumber + "<br /><b>Serial Number: </b>" + part + "<br/><b>Last time maintained: </b>" + latestDate.ToShortDateString() + "<br/><b>Time elapsed since last maintenance: </b>" + daysElapsed + " days OR " + daysElapsed / 7 + " weeks." + "<br/><b>Next Maintenance: </b>" + nextMaintenance.ToShortDateString() + " (" + daysLeft + ")" + " days left.<br/>" + "</b></font>"; redFlag = true; //Indicate email frequency } } emailBody += "<br/><b><font color=green>===>>> TOTAL: " + serialNumbersList.Count + " " + type + "</font></b><br/>"; //"<p style='color: green; font-size:50px; margin-left:100px'>different font and color</p>";#bd7e13#bd7e13 serialNumbersList.Clear(); //Clear the list for new serial numbers for HST/Breakdown maintained_Dates.Clear(); return emailBody; } } }
6ee14efc0a8067601ec7923311dfd1cd00164c3a
C#
Ilo-ILD/CSharpBasic
/OperatorsExpressionsStatements/FourDigitNumber/FourDigitNumber.cs
3.90625
4
using System; namespace FourDigitNumber { class FourDigitNumber { static void Main() { int number = 0; Console.Write("Enter a integer between 1000 and 9999: "); if (int.TryParse(Console.ReadLine(), out number) && number >= 1000 && number <= 9999) { Console.Clear(); int firstDigit = number / 1000; int secondDigit = ((number / 100) % 10); int thirdDigit = ((number / 10) % 10); int fourDigit = number % 10; int digitsSum = firstDigit + secondDigit + thirdDigit + fourDigit; string reversed = fourDigit.ToString() + thirdDigit.ToString() + secondDigit.ToString() + firstDigit.ToString(); string lastInFront = fourDigit.ToString() + firstDigit.ToString() + secondDigit.ToString() + thirdDigit.ToString(); string exchangedDigids = firstDigit.ToString() + thirdDigit.ToString() + secondDigit.ToString() + fourDigit.ToString(); Console.WriteLine("n\tsum\treversed\tlast in front\texchanged digits"); Console.WriteLine("{0}\t{1}\t{2}\t\t{3}\t\t{4}", number, digitsSum, reversed, lastInFront, exchangedDigids); } else { Console.WriteLine("You have entered invalid data!"); } } } }
29b69d404b0f97468e1f996c5fdd745a34e122b9
C#
wanlitao/FCP.FluentData
/FluentData/Core/PropertyExpressionParser.cs
3.03125
3
using System; using System.Linq.Expressions; using System.Reflection; namespace FluentData { public class PropertyExpressionParser<T> { private readonly object _item; private readonly PropertyInfo _property; public PropertyExpressionParser(object item, Expression<Func<T, object>> propertyExpression) { _item = item; _property = GetProperty(propertyExpression); } private static PropertyInfo GetProperty(Expression<Func<T, object>> exp) { PropertyInfo result; if (exp.Body.NodeType == ExpressionType.Convert) result = ((MemberExpression) ((UnaryExpression) exp.Body).Operand).Member as PropertyInfo; else result = ((MemberExpression) exp.Body).Member as PropertyInfo; if (result != null) return typeof(T).GetProperty(result.Name); throw new ArgumentException(string.Format("Expression '{0}' does not refer to a property.", exp.ToString())); } public object Value { get { return ReflectionHelper.GetPropertyValue(_item, _property); } } public string Name { get { return _property.Name; } } public Type Type { get { return ReflectionHelper.GetPropertyType(_property); } } } }
dd3a6a9e312ab714ec6e56223f0205b21a58bcf5
C#
oluwasege/Lab5WorkingWithAbstractClasses
/BankC.cs
3.65625
4
using System; using System.Collections.Generic; using System.Text; namespace Lab5WorkingWithAbstractClasses { class BankC : Bank { int balance = 200; public override void getBalance() { int input; Console.WriteLine("Welcome to Bank C\nWe are glad to have you with us\nPlease Press Enter"); Console.ReadKey(); Console.WriteLine("1 : Check your balance\n2 : cancel"); string inputs = Console.ReadLine(); while(!int.TryParse(inputs,out input)) { Console.Clear(); Console.WriteLine("Welcome to Bank C\nWe are glad to have you with us\n"); Console.WriteLine("You entered a wrong input"); Console.WriteLine("1 : Check your balance\n2 : cancel"); inputs = Console.ReadLine(); } if (input == 1) { Console.Clear(); Console.WriteLine($"Your balance is : {balance}\n Thank you!"); } else if (input == 2) { Environment.Exit(0); } } } }
b1a34b43e5505e6657b90b2da4f78f823d45c4e2
C#
ChpNick/3dPerson
/Assets/Script/CollectibleItem.cs
2.640625
3
using UnityEngine; using System.Collections; public class CollectibleItem : MonoBehaviour { // Введите имя этого элемента на панели Inspector. [SerializeField] private string itemName; void OnTriggerEnter(Collider other) { Debug.Log("Item collected: " + itemName); Managers.Inventory.AddItem(itemName); Destroy(this.gameObject); } }
de0242ea3d11506a19e0e794491d94442a8ba7c9
C#
trcruse/dino-diner
/Menu/Drinks/Sodasaurus.cs
3.21875
3
using System; using System.Collections.Generic; using System.Text; /// <summary> /// Inherits from base class Drink /// </summary> namespace DinoDiner.Menu { /// <summary> /// Inherits from base class Drink /// </summary> public class Sodasaurus : Drink { /// <summary> /// protected backing variable for flavor /// </summary> protected SodasaurusFlavor flavor; /// <summary> /// Inheritance from SodasaurusFlavor enum allowing for correct drink flavor /// </summary> public SodasaurusFlavor Flavor { get { return flavor; } set { flavor = value; NotifyOfPropertyChanged("Description"); } } /// <summary> /// constructor for Sodasaurus that implements Price, Calories, and Ingredients at default /// </summary> public Sodasaurus() { Price = 1.50; Calories = 112; ingredients.Add("Water"); ingredients.Add("Natural Flavors"); ingredients.Add("Cane Sugar"); } /// <summary> /// override method leads into enum Size class to make changes in Price and Calories for called enum Sizes /// Notifys property change in Price and Calories per each Size implementation in /// each class requirements /// </summary> public override Size Size { set { size = value; NotifyOfPropertyChanged("Price"); NotifyOfPropertyChanged("Calories"); switch (size) { case Size.Small: Price = 1.50; Calories = 112; break; case Size.Medium: Price = 2.00; Calories = 156; break; case Size.Large: Price = 2.50; Calories = 208; break; } } get { return size; } } /// <summary> /// ToString Implementation to refactor all Menu items /// </summary> public override string ToString() { return $"{size} {flavor} Sodasaurus"; } /// <summary> /// Gets a description of the order item /// Size is integrated /// </summary> public override string Description { get { return this.ToString(); } } /// <summary> /// contains any special instructions for the food preparation /// All drinks require Hold Ice except Jurassic Java /// </summary> public override string[] Special { get { List<string> special = new List<string>(); //If Ice is false if (!Ice) special.Add("Hold Ice"); return special.ToArray(); } } } // End of Sodasaurus class }
b97fbfb38786ca7f589c9a7aa45e37684d60fa78
C#
csnemes/shapeshifter
/Shapeshifter.Tests.Unit/RoundtripTests/ComplexStructure/Product.cs
2.609375
3
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; namespace Shapeshifter.Tests.Unit.RoundtripTests.ComplexStructure { [DataContract] public class Product { public Product(string name, string description, double price) { Name = name; Description = description; Price = price; } [DataMember] public string Name { get; set; } [DataMember] public string Description { get; set; } [DataMember] public double Price { get; set; } } }
0658b8d0f46e8c296203fb68bcf47f3661d5ebf0
C#
kxnaylorCLE216/LibraryAPISolution
/LibraryAPI/Controllers/DemoController.cs
2.8125
3
using LibraryAPI.Models.Employees; using LibraryAPI.Models.Status; using LibraryAPI.Services; using Microsoft.AspNetCore.Mvc; using System; namespace LibraryAPI.Controllers { public class DemoController : ControllerBase { private readonly IProvideServerStatusInformation _statusService; public DemoController(IProvideServerStatusInformation statusService) { _statusService = statusService; } // GET /status [HttpGet("/status")] public ActionResult GetTheStatus() { GetStatusResponse response = null; //return Ok(new { Message = "All is Good", CreatedAt = DateTime.Now }); try { response = _statusService.GetCurrentStatus(); } catch (Exception) { response = new GetStatusResponse { Message = "Status is unavailable", CreatedAt = new DateTime() }; } return Ok(response); } // GET /employees/99 [HttpGet("/employees/{employeeId:int}", Name = "demo-getemployee")] public ActionResult GetEmployee(int employeeId) { return Ok(new { EmployeId = employeeId, Name = "Bob Smith" }); } [HttpGet("/blogs/{year:int}/{month:int}/{day:int}")] public ActionResult GetBlogPosts(int year, int month, int day) { return Ok($"Getting the blog posts for {month}/{day}/{year}"); } // GET /agents // GET /agents?state=CO [HttpGet("/agents")] public ActionResult GetAgents([FromQuery] string state = "All", [FromQuery] string city = "All") { return Ok($"Getting Agents from State {state} and city {city}"); } [HttpGet("/whoami")] // User-Agent public ActionResult GetUserAgent([FromHeader(Name = "User-Agent")] string userAgent) { return Ok($"I see you are running {userAgent}"); } [HttpPost("/employees")] public ActionResult Hire([FromBody] PostEmployeeRequest employeeToHire) { // POSTing To a Collection // 1. Validate it. If Not, return a 400. (we'll do this tomorrow) // 2. Change the world, man. Add it to the database, whever hiring someone means to you. var response = new GetEmployeeDetailsResponse { Id = new Random().Next(40, 2000), Name = employeeToHire.Name, Department = employeeToHire.Department, Manager = "Sue Jones", Salary = employeeToHire.StartingSalary * 1.3M }; // Return: // - At least a 200, but 201 is "More" Correct (201 means 'created') // - a birth announcement - Location: http://localhost:1337/employees/500 // - Also send them a copy of the newly created entity. return CreatedAtRoute("demo-getemployee", new { employeeId = response.Id }, response); } } }
034f0f40b95af862a25376cd635fdfa23e66182a
C#
sluski/DumbKnightAdventure
/Assets/Scripts/CoinBehavior.cs
2.625
3
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class CoinBehavior : MonoBehaviour { private static int score = 0; public Text countText; void Start() { updateScoreText(score); } void Update() { } void OnTriggerEnter2D(Collider2D collision) { score += 1; updateScoreText(score); Destroy(gameObject); } private void updateScoreText(int score) { countText.text = "Coins: " + score.ToString(); } }
9e9a08e2955dc9c09bd3d15b1b95ccee7afda691
C#
sweko/SEDC-Euler
/EulerSolutions/SWeko/Problem005.cs
2.828125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using EulerEngine; namespace EulerSolutions.SWeko { class Problem005 : IProblemSolution { public int ProblemID { get { return 5; } } public long Execute() { PrimeManager.GeneratePrimes(100); return Enumerable.Range(1, 20) .Aggregate(new FactorCollection(), (collection, i) => collection.Combine(i.Factorize())) .GetNumber(); } } }
c5328cdfd54ab6b2738fd561a67370f649c935ca
C#
braianb92/Progr_Labo_2
/Integrador/Repaso/Repaso/Estante.cs
3.453125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Repaso { class Estante { private Producto[] productos; private int ubicacionEstante; public Estante(int capacidad,int ubicacion):this(capacidad) { this.ubicacionEstante = ubicacion; } private Estante(int capacidad) { this.productos = new Producto[capacidad]; } public Producto[] GetProductos() { return this.productos; } public static string MostrarEstante(Estante estante) { string cadena = ""; foreach (var producto in estante.productos) { cadena += Producto.MostrarProducto(producto)+"\n\n"; } return cadena; } //retornará true, si es que el producto ya se encuentra en el estante, false, caso contrario. public static bool operator ==(Estante e, Producto p) { foreach (var producto in e.productos) { if ((producto == p)) return true; } return false; } //retornará true, si es que el producto no se encuentra en el estante, false, caso contrario. public static bool operator !=(Estante e, Producto p) { return !(e == p); } //Adición, retornará true y agregará el producto si el estante posee capacidad de almacenar //al menos un producto más y dicho producto no se encuentra en él; false, caso contrario. public static bool operator +(Estante e, Producto p) { int i = 0; if (e != p) { foreach (Producto producto in e.productos) { if (Object.ReferenceEquals(producto,null)) { e.productos[i] = p; return true; } i++; } } return false; } //Sustracción(Estante, Producto), retornará un estante sin el producto, //siempre y cuando el producto se encuentre en el listado public static Estante operator -(Estante e, Producto p) { int i = 0; if (e == p) { foreach (Producto producto in e.productos) { if (Object.ReferenceEquals(producto, p)) { e.productos[i] = null; return e; } i++; } } return e; } } }
1f70ecfadd3b49acc93c6b639e52308577be73fd
C#
jaranvil/C-Sharp
/Assign4/WindowsFormsApplication11/Biz/Test.cs
3.171875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Biz { public class Test { public delegate void FireHandler(String txt); public FireHandler handler; //method deep down //metods already doesn't return a value //want to fire many actions, methods, at same time //solve the issue of circular reference //async method calls public void Read(bool value) { if(!value) //ask the delegate to publish; alert subscribers handler("Error"); } public void Level3(bool value) { Read(value); } public void Level1(bool value) { Level2(value); } public void Level2(bool value) { Level3(value); } } }
4381c5e2e922e953118aa1be005a64a241ca0642
C#
CityChainFoundation/city-chain
/src/Stratis.SmartContracts.CLR/AddressGenerator.cs
2.953125
3
using System.Linq; using NBitcoin; using Stratis.SmartContracts.Core.Hashing; namespace Stratis.SmartContracts.CLR { public class AddressGenerator : IAddressGenerator { /// <summary> /// Deterministically generates a new contract address using the given seed and nonce. /// </summary> /// <param name="seed">A seed value from which to generate the address. Typically, the hash of a <see cref="Transaction"/> is used.</param> /// <param name="nonce">A value which, when combined with the seed, allows for generation of different addresses from the same seed.</param> public uint160 GenerateAddress(uint256 seed, ulong nonce) { byte[] toHash = seed.ToBytes().Concat(new uint256(nonce).ToBytes()).ToArray(); return new uint160(HashHelper.Keccak256(toHash).Take(20).ToArray()); } } }
bb8370511a0f065f6c740524b8369b39d0ce694e
C#
wunmao/LinqFasterer
/LinqFasterer/Aggregate.cs
3.140625
3
using LinqFasterer.Utils; using System; using System.Collections.Generic; using System.Runtime.CompilerServices; namespace LinqFasterer { public static partial class EnumerableF { /// <summary> /// Applies an accumulator function over a sequence. /// </summary> /// <param name="source">An <see cref="IList{T}"/> to aggregate over.</param> /// <param name="func">An accumulator function to be invoked on each element.</param> /// <typeparam name="TSource">The type of the elements of <paramref name="source"/>.</typeparam> /// <returns>The final accumulator value.</returns> public static TSource AggregateF<TSource>(this IList<TSource> source, Func<TSource, TSource, TSource> func) { var sourceArray = source.ToArrayF(); var sourceLength = sourceArray.Length; if (sourceLength == 0) throw Error.NoElements(); var result = sourceArray[0]; for (var i = 1; i < sourceLength; i++) result = func(result, sourceArray[i]); return result; } /// <summary> /// Applies an accumulator function over a sequence. The specified seed value is used as the initial accumulator value. /// </summary> /// <param name="source">An <see cref="IList{T}"/> to aggregate over.</param> /// <param name="seed">An initial accumulator value.</param> /// <param name="func">An accumulator function to be invoked on each element.</param> /// <typeparam name="TSource">The type of the elements of <paramref name="source"/>.</typeparam> /// <typeparam name="TAccumulate">The type of the accumulator value.</typeparam> /// <returns>The final accumulator value.</returns> public static TAccumulate AggregateF<TSource, TAccumulate>(this IList<TSource> source, TAccumulate seed, Func<TAccumulate, TSource, TAccumulate> func) { var sourceArray = source.ToArrayF(); var sourceLength = sourceArray.Length; var result = seed; for (var i = 0; i < sourceLength; i++) result = func(result, sourceArray[i]); return result; } /// <summary> /// Applies an accumulator function over a sequence. The specified seed value is used as the initial accumulator value, and the specified function is used to select the result value. /// </summary> /// <param name="source">An <see cref="IList{T}"/> to aggregate over.</param> /// <param name="seed">An initial accumulator value.</param> /// <param name="func">An accumulator function to be invoked on each element.</param> /// <param name="resultSelector">A selector function to transform the final accumulator value into the result value.</param> /// <typeparam name="TSource">The type of the elements of <paramref name="source"/>.</typeparam> /// <typeparam name="TAccumulate">The type of the accumulator value.</typeparam> /// <typeparam name="TResult">The type of the resulting value.</typeparam> /// <returns>The transformed final accumulator value.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static TResult AggregateF<TSource, TAccumulate, TResult>(this IList<TSource> source, TAccumulate seed, Func<TAccumulate, TSource, TAccumulate> func, Func<TAccumulate, TResult> resultSelector) { return resultSelector(AggregateF(source, seed, func)); } } }
5a4b6f553405b80f856eb594a19f887da281fb9a
C#
EpsteinRoss-FS/ADF_2012_EpsteinRoss
/App.cs
3.140625
3
/** * Ross Epstein * 12/10/2020 * ADF119-O - APPLICATION DEVELOPMENT FUNDAMENTALS * 3.6 - Data Integration 2 * **/ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace ADF_2011_EpsteinRoss { class App { private static Menu _appMenu { get; set; } private static User _activeUser { get; set; } private static bool _loggedIn { get; set; } private static readonly string filePath = "../../../Users.txt"; public App() { //create initial menu Console.Clear(); Menu appMenu = new Menu(); string[] menuItems = { "Main Menu", "Create User", "Show Profile", "Login", "About","Display Users", "Exit" }; _appMenu = appMenu; //initialize menu appMenu.Init(menuItems); appMenu.Display(_loggedIn, _activeUser); Selection(); } public static void Selection() { //get the length of the menu - 1 to account for "Main Menu" int menuLength = Menu.menuLength - 1; Console.Write("Please make a selection > "); string _userChoice = Console.ReadLine(); //validate the choice is an integer bool isInt = Validation.CheckInt(_userChoice); int _userChoiceInt = isInt ? Int32.Parse(_userChoice) : 000; //validate the choice is in range of the menu bool isInRange = Validation.CheckRange(_userChoiceInt, menuLength); //ask again if the validation returns false while (!isInt || !isInRange) { Console.Clear(); _appMenu.Display(_loggedIn, _activeUser); Console.Write($"Invalid entry! Please enter a number between 1 and {menuLength} > "); _userChoice = Console.ReadLine(); isInt = Validation.CheckInt(_userChoice); _userChoiceInt = isInt ? Int32.Parse(_userChoice) : 000; ; isInRange = Validation.CheckRange(_userChoiceInt, (menuLength)); } //get the text value from the menu index based on user choice string chosenItem = _appMenu.MenuList[_userChoiceInt]; //switch statement to handle the chosen menu item switch (chosenItem.ToLower()) { case "create user": Create(); break; case "about": About(); break; case "login": Login(); break; case "exit": Exit(); break; case "show profile": ShowProfile(); break; case "display users": DisplayUsers(); break; default: break; } } //call for the user login method public static bool Login() { //if a user is logged in, log user out if (_loggedIn) { _loggedIn = false; return _loggedIn; } //if user is not logged in, log in the user if (!_loggedIn) { if (_activeUser == null) { _activeUser = new User(); } _loggedIn = User.Login(_activeUser); return _loggedIn; } return _loggedIn; } //function for centering headers public static void Header(string headerName) { Console.WriteLine("========================================"); string SpacedHeader; string paddingSpaces = ""; int HeaderLength = headerName.Length; headerName = headerName.ToUpper(); //40 is the length of "=" in header lines int totalSpaces = 40; //calculate 40 - lenstring / 2 for each sides padding int paddingEachSide = (totalSpaces - HeaderLength) / 2; //add padding to each side of the string for (int i = 0; i < paddingEachSide;) { paddingSpaces += " "; i++; } SpacedHeader = paddingSpaces + headerName + paddingSpaces; Console.WriteLine(SpacedHeader); Console.WriteLine("========================================"); } //display the about section public static void About() { Console.ForegroundColor = ConsoleColor.Blue; Console.Clear(); Header("WELCOME TO MY CONSOLE APPLICATION!"); Console.WriteLine("This console application is a demonstration of my skillset in C#.\nIt is being done for my \"PROJECT AND PORTFOLIO I: APPLICATION DEVELOPMENT FUNDAMENTALS\"\n" + "class at Full Sail University!\n\nThis application demonstrates my ability to write C# code that utilizes:" + "\n - File I/O Functionality" + "\n - User Authentication" + "\n - User Creation" + "\n - Validation" + "\n - Automation (headers are auto spaced)" + "\n - Git Principles" + "\n - Agile Development Principles" + "\n\nI hope you enjoy it! - Ross Epstein"); Continue(); } //gracefully exit public static void Exit() { Console.WriteLine("Exiting..."); Program.hasExited = true; return; } public static void DisplayUsers() { Console.Clear(); App.Header("Display Users"); Console.WriteLine("\nThe following users were found:"); List<string> usersToDisplay = User.DisplayUsers(); int i = 1; foreach (var userName in usersToDisplay) { Console.WriteLine($"{i}: {userName.ToUpper()}"); i++; } Console.WriteLine("\n"); Continue(); } //display continue statement and wait for key press public static void Continue() { Console.WriteLine("Press any key to continue..."); Console.ReadKey(); } public static void Create() { Console.Clear(); Console.Write($"Please enter your desired username: > "); string _chooseUserName = Console.ReadLine(); bool validUsername = Validation.CheckString(_chooseUserName); //insure username is valid string while (!validUsername) { Console.Clear(); Console.Write($"Invalid Entry! "); Console.Write($"Please enter your desired username: > "); _chooseUserName = Console.ReadLine(); validUsername = Validation.CheckString(_chooseUserName); } Console.Write("Please enter your desired password: > "); string _choosePassword = Console.ReadLine(); bool validPassword = Validation.CheckString(_choosePassword); //insure password is valid string while (!validPassword) { Console.Clear(); Console.Write($"Invalid Entry! "); Console.Write($"Please enter your desired password: > "); _choosePassword = Console.ReadLine(); validPassword = Validation.CheckString(_choosePassword); } Console.Write("Please enter your desired city: > "); string _chooseCity = Console.ReadLine(); bool validCity = Validation.CheckString(_choosePassword); //insure city is a valid string while (!validCity) { Console.Clear(); Console.Write($"Invalid Entry! "); Console.Write($"Please enter your desired password: > "); _chooseCity = Console.ReadLine(); validCity = Validation.CheckString(_chooseCity); } Console.Write("Please enter your desired state: > "); string _chooseState = Console.ReadLine(); bool validState = Validation.CheckString(_choosePassword); //insure state is valid string while (!validState) { Console.Clear(); Console.Write($"Invalid Entry! "); Console.Write($"Please enter your desired password: > "); _chooseState = Console.ReadLine(); validState = Validation.CheckString(_chooseState); } //display choices and confirm they are correct Console.Clear(); Console.WriteLine("You have chosen the following options:"); Console.WriteLine($"Username: {_chooseUserName}"); Console.WriteLine($"Password: {_choosePassword}"); Console.WriteLine($"City: {_chooseCity}"); Console.WriteLine($"State: {_chooseState}"); Console.WriteLine("Is this correct? Yes/No"); //validate choice confirmation string confirmUser = Console.ReadLine(); bool confirmChoiceValid = Validation.CheckString(confirmUser); while (!confirmChoiceValid || (confirmUser.ToLower() != "yes" && confirmUser.ToLower() != "no")) { Console.Clear(); Console.WriteLine("Invalid entry!"); Console.WriteLine("You have chosen the following options:"); Console.WriteLine($"Username: {_chooseUserName}"); Console.WriteLine($"Password: {_choosePassword}"); Console.WriteLine($"City: {_chooseCity}"); Console.WriteLine($"Password: {_chooseState}"); Console.WriteLine("Is this correct? Yes/No"); confirmUser = Console.ReadLine(); confirmChoiceValid = Validation.CheckString(confirmUser); } if (confirmUser.ToLower() == "yes") { //generate a random user ID var rand = new Random(); int userId = rand.Next(1, 2147483647); //all newly created users are active int userActive = 1; //setup streamwriter using (StreamWriter sw = File.AppendText(filePath)) { //write file sw.WriteLine(_chooseUserName + "|" + userId + "|" + _choosePassword + "|" + _chooseCity + "|" + _chooseState + "|" + userActive + ""); } } if (confirmUser.ToLower() == "no") { Console.WriteLine("Cancelling user creation! Press any key to continue..."); Console.ReadKey(); } } public static void ShowProfile() { Console.Clear(); //display profile header Header($"USER { _activeUser._name.ToUpper()} PROFILE"); //display user name Console.WriteLine($"NAME: {_activeUser._name}"); //display city and state Console.WriteLine($"STATE AND CITY: {_activeUser._city}, {_activeUser._state} "); //display if they are active or not string userActive = _activeUser._status == 1 ? "Active" : "Inactive"; Console.WriteLine($"ACCOUNT STATUS: {userActive}"); App.Continue(); } } }
1e7b400126c8068393a80f63f216b03d47fb301b
C#
BooLeet/Mansion-Warrior
/Mansion Warrior Mobile/Assets/Player/HUD/Scripts/HUD_Healthbar.cs
2.5625
3
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class HUD_Healthbar : MonoBehaviour { public Image healthFill; public Image damageEffectFill; public Text[] healthCounters; public RawImage lowHealthIndicator; public float lowHealthIndicatorSpeed = 3; private float lowHealthIndicatorParameter = 0; private void Update() { DamageEffectUpdate(); Color targetColor = lowHealthIndicator.color; if (healthFill.fillAmount <= 1 / 3f) { targetColor.a = Mathf.Abs(Mathf.Sin(lowHealthIndicatorParameter)); lowHealthIndicatorParameter += Time.deltaTime * lowHealthIndicatorSpeed; lowHealthIndicatorParameter %= Mathf.PI; } else { targetColor.a = 0; lowHealthIndicatorParameter = 0; } lowHealthIndicator.color = targetColor; } public void SetHealth(float currentHealth, float maxHealth) { healthFill.fillAmount = currentHealth / maxHealth; foreach(Text healthCounter in healthCounters) healthCounter.text = ((int)currentHealth).ToString(); } private void DamageEffectUpdate() { damageEffectFill.fillAmount = Mathf.Lerp(damageEffectFill.fillAmount, healthFill.fillAmount, Time.deltaTime * 5); } }
329247062aeab7964756c00959c0585204fd9eab
C#
DoctorSoft/fbkBot
/facebookQuery/DataBase/QueriesAndCommands/Commands/Friends/RemoveAnalyzedFriendCommand/RemoveAnalyzedFriendCommandHandler.cs
2.640625
3
using System.Linq; using Constants.FriendTypesEnum; using DataBase.Context; using DataBase.Models; namespace DataBase.QueriesAndCommands.Commands.Friends.RemoveAnalyzedFriendCommand { public class RemoveAnalyzedFriendCommandHandler : ICommandHandler<RemoveAnalyzedFriendCommand, VoidCommandResponse> { private readonly DataBaseContext _context; public RemoveAnalyzedFriendCommandHandler(DataBaseContext context) { this._context = context; } public VoidCommandResponse Handle(RemoveAnalyzedFriendCommand command) { var friendModel = _context.AnalisysFriends.FirstOrDefault( model => model.AccountId == command.AccountId && model.Id == command.FriendId); if (friendModel == null) { return new VoidCommandResponse(); } _context.AnalisysFriends.Remove(friendModel); _context.SaveChanges(); return new VoidCommandResponse(); } } }