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
ade30d4cf4bba1ef3d8fb5cebc0a5939bd29ef9e
C#
t7160304/Smartkernel
/Framework/CSharp/Framework/Framework/Xml/SmartXml.cs
2.546875
3
/* * 项目:Smartkernel.Framework * 作者:曹艳白 * 邮箱:caoyanbai@139.com */ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Xml; using System.Xml.Linq; using System.Xml.Serialization; using System.Xml.Xsl; namespace Smartkernel.Framework.Xml { /// <summary> /// Xml /// </summary> public static class SmartXml { /// <summary> /// 通过XML文件获得实体,实体必须提供了公有构造函数 /// </summary> /// <typeparam name="T">实体类型</typeparam> /// <param name="xmlPath">XML文件地址,XML文件必须遵守特定格式</param> /// <param name="xmlMappingType">映射的类型</param> /// <returns>已经初始化并赋值的实体</returns> public static T ToObjectFromFile<T>(string xmlPath, SmartXmlMappingType xmlMappingType = SmartXmlMappingType.Property) { var entity = Activator.CreateInstance<T>(); ToObject(XElement.Load(xmlPath), xmlMappingType, ref entity); return entity; } /// <summary> /// 通过XML字符串获得实体,实体必须提供了公有构造函数 /// </summary> /// <typeparam name="T">实体类型</typeparam> /// <param name="xml">XML字符串</param> /// <param name="xmlMappingType">映射的类型</param> /// <returns>已经初始化并赋值的实体</returns> public static T ToObject<T>(string xml, SmartXmlMappingType xmlMappingType = SmartXmlMappingType.Property) { var entity = Activator.CreateInstance<T>(); ToObject(XElement.Parse(xml), xmlMappingType, ref entity); return entity; } /// <summary> /// 通过XML元素获得实体,实体必须提供了公有构造函数 /// </summary> /// <param name="xml">XML元素</param> /// <param name="xmkMappingType">映射的类型</param> /// <param name="entity">实体对象</param> private static void ToObject<T>(XElement xml, SmartXmlMappingType xmkMappingType, ref T entity) { var type = entity.GetType(); var xelements = xml.Descendants(); switch (xmkMappingType) { case SmartXmlMappingType.Auto: { try { #region 根据字段映射 foreach (var fieldInfo in SmartType.GetFields(type)) { string source = null; if (QueryNode(xelements, fieldInfo.Name, out source)) { var value = SmartConvert.To(source, fieldInfo.FieldType); fieldInfo.SetValue(entity, value); } } #endregion } catch { } try { #region 根据属性映射 foreach (var propertyInfo in SmartType.GetProperties(type)) { string source = null; if (QueryNode(xelements, propertyInfo.Name, out source)) { var value = SmartConvert.To(source, propertyInfo.PropertyType); propertyInfo.SetValue(entity, value, null); } } #endregion } catch { } try { #region 根据特性标识映射 foreach (var propertyInfo in SmartType.GetPropertiesWithAttribute<SmartNodeMappingAttribute>(type)) { var attribute = (SmartNodeMappingAttribute)Attribute.GetCustomAttribute(propertyInfo, typeof(SmartNodeMappingAttribute), false); string source = null; if (QueryNode(xelements, attribute.NodeName, out source)) { var value = SmartConvert.To(source, propertyInfo.PropertyType); propertyInfo.SetValue(entity, value, null); } else { if (attribute.DefaultValue != null) { propertyInfo.SetValue(entity, attribute.DefaultValue, null); } } } foreach (var fieldInfo in SmartType.GetFieldsWithAttribute<SmartNodeMappingAttribute>(type)) { var attribute = (SmartNodeMappingAttribute)Attribute.GetCustomAttribute(fieldInfo, typeof(SmartNodeMappingAttribute), false); string source = null; if (QueryNode(xelements, attribute.NodeName, out source)) { var value = SmartConvert.To(source, fieldInfo.FieldType); fieldInfo.SetValue(entity, value); } else { if (attribute.DefaultValue != null) { fieldInfo.SetValue(entity, attribute.DefaultValue); } } } #endregion } catch { } } break; case SmartXmlMappingType.Attribute: { #region 根据特性标识映射 foreach (var propertyInfo in SmartType.GetPropertiesWithAttribute<SmartNodeMappingAttribute>(type)) { var attribute = (SmartNodeMappingAttribute)Attribute.GetCustomAttribute(propertyInfo, typeof(SmartNodeMappingAttribute), false); string source = null; if (QueryNode(xelements, attribute.NodeName, out source)) { var value = SmartConvert.To(source, propertyInfo.PropertyType); propertyInfo.SetValue(entity, value, null); } else { if (attribute.DefaultValue != null) { propertyInfo.SetValue(entity, attribute.DefaultValue, null); } } } foreach (var fieldInfo in SmartType.GetFieldsWithAttribute<SmartNodeMappingAttribute>(type)) { var attribute = (SmartNodeMappingAttribute)Attribute.GetCustomAttribute(fieldInfo, typeof(SmartNodeMappingAttribute), false); string source; if (QueryNode(xelements, attribute.NodeName, out source)) { var value = SmartConvert.To(source, fieldInfo.FieldType); fieldInfo.SetValue(entity, value); } else { if (attribute.DefaultValue != null) { fieldInfo.SetValue(entity, attribute.DefaultValue); } } } #endregion } break; case SmartXmlMappingType.Property: { #region 根据属性映射 foreach (var propertyInfo in SmartType.GetProperties(type)) { string source; if (QueryNode(xelements, propertyInfo.Name, out source)) { var value = SmartConvert.To(source, propertyInfo.PropertyType); propertyInfo.SetValue(entity, value, null); } } #endregion } break; case SmartXmlMappingType.Field: { #region 根据字段映射 foreach (var fieldInfo in SmartType.GetFields(type)) { string source = null; if (QueryNode(xelements, fieldInfo.Name, out source)) { var value = SmartConvert.To(source, fieldInfo.FieldType); fieldInfo.SetValue(entity, value); } } #endregion } break; } } /// <summary> /// 通过XML文件获得实体,实体必须提供了公有构造函数 /// </summary> /// <typeparam name="T">实体类型</typeparam> /// <param name="xmlPath">XML文件地址,XML文件必须遵守特定格式</param> /// <param name="xmlMappingType">映射的类型</param> /// <returns>已经初始化并赋值的实体列表</returns> public static List<T> ToObjectsFromFile<T>(string xmlPath, SmartXmlMappingType xmlMappingType = SmartXmlMappingType.Property) { String xml = File.ReadAllText(xmlPath); return ToObjects<T>(xml, xmlMappingType); } /// <summary> /// 通过XML字符串获得实体,实体必须提供了公有构造函数 /// </summary> /// <typeparam name="T">实体类型</typeparam> /// <param name="xml">XML字符串</param> /// <param name="xmlMappingType">映射的类型</param> /// <returns>已经初始化并赋值的实体列表</returns> public static List<T> ToObjects<T>(string xml, SmartXmlMappingType xmlMappingType = SmartXmlMappingType.Property) { var xmls = XElement.Parse(xml); var xelements = xmls.Descendants(); var entityList = new List<T>(xelements.Count()); var xelementList = xelements.ToList(); xelementList.ForEach(delegate(XElement xe) { var entity = Activator.CreateInstance<T>(); ToObject(xe, xmlMappingType, ref entity); entityList.Add(entity); }); return entityList; } /// <summary> /// 判断指定的节点在文件中是否存在,节点没有值的也认为是不存在 /// </summary> /// <param name="xelements">文件的LINQ查询集合</param> /// <param name="node">节点名称</param> /// <param name="value">如果存在,则返回节点的值</param> /// <returns>是否存在,true表示存在,false表示不存在</returns> private static bool QueryNode(IEnumerable<XElement> xelements, string node, out string value) { var values = from v in xelements where v.Name.ToString().ToLower() == node.ToLower() && v.Value.Trim().Length > 0 select v; if (values.Count() > 1) { throw new Exception(); } if (values.Count() == 1) { value = values.First().Value.Trim(); return true; } value = string.Empty; return false; } /// <summary> /// 对象列表映射为Xml /// </summary> /// <typeparam name="T">对象类型</typeparam> /// <param name="list">列表</param> /// <param name="rootName">根元素的名称</param> /// <param name="xmlMappingType">映射类型</param> /// <returns>xml文档</returns> public static string ToXmls<T>(List<T> list, string rootName, SmartXmlMappingType xmlMappingType = SmartXmlMappingType.Property) { var xml = new StringBuilder(); list.ForEach(item => xml.AppendLine(ToXml(item, rootName, xmlMappingType))); return xml.ToString(); } private static XElement[] CreateXElements<T>(T item, SmartXmlMappingType xmlMappingType = SmartXmlMappingType.Property) { var list = new List<XElement>(); var datas = new Dictionary<string, object>(); switch (xmlMappingType) { case SmartXmlMappingType.Auto: { try { datas = SmartType.GetFieldsDictionary(item); } catch { } try { datas = SmartType.GetPropertiesDictionary(item); } catch { } try { var fields = SmartType.GetFieldsWithAttribute<SmartNodeMappingAttribute>(typeof(T)); foreach (var field in fields) { var key = field.Name; var temp = SmartType.GetFieldValue(item, key); var value = temp == null ? string.Empty : temp.ToString(); if (!datas.ContainsKey(key)) { datas.Add(key, value); } } var properties = SmartType.GetPropertiesWithAttribute<SmartNodeMappingAttribute>(typeof(T)); foreach (var property in properties) { var key = property.Name; var temp = SmartType.GetPropertyValue(item, key); var value = temp == null ? string.Empty : temp.ToString(); if (!datas.ContainsKey(key)) { datas.Add(key, value); } } } catch { } } break; case SmartXmlMappingType.Attribute: { var fields = SmartType.GetFieldsWithAttribute<SmartNodeMappingAttribute>(typeof(T)); foreach (var field in fields) { var key = field.Name; var temp = SmartType.GetFieldValue(item, key); var value = temp == null ? string.Empty : temp.ToString(); if (!datas.ContainsKey(key)) { datas.Add(key, value); } } var properties = SmartType.GetPropertiesWithAttribute<SmartNodeMappingAttribute>(typeof(T)); foreach (var property in properties) { var key = property.Name; var temp = SmartType.GetPropertyValue(item, key); var value = temp == null ? string.Empty : temp.ToString(); if (!datas.ContainsKey(key)) { datas.Add(key, value); } } } break; case SmartXmlMappingType.Property: { datas = SmartType.GetPropertiesDictionary(item); } break; case SmartXmlMappingType.Field: { datas = SmartType.GetFieldsDictionary(item); } break; } var enumerator = datas.GetEnumerator(); while (enumerator.MoveNext()) { list.Add(new XElement(enumerator.Current.Key, enumerator.Current.Value)); } return list.ToArray(); } /// <summary> /// 对象映射为Xml /// </summary> /// <typeparam name="T">对象类型</typeparam> /// <param name="item">对象</param> /// <param name="rootName">根元素的名称</param> /// <param name="xmlMappingType">映射类型</param> /// <returns>xml文档</returns> public static string ToXml<T>(T item, string rootName, SmartXmlMappingType xmlMappingType = SmartXmlMappingType.Property) { var xml = new XDocument(new XElement(rootName, CreateXElements(item, xmlMappingType))); return xml.ToString(); } /// <summary> /// 根据xsl转换xml文档 /// </summary> /// <param name="xml">xml文档的内容</param> /// <param name="xslFilePath">xsl文件的位置</param> /// <returns>转换的结果</returns> public static string Transform(string xml, string xslFilePath) { if (xml == null || xml.Length == 0 || !File.Exists(xslFilePath)) { return ""; } string result = ""; try { using (TextReader styleSheetTextReader = new StreamReader(new FileStream(xslFilePath, FileMode.Open, FileAccess.Read, FileShare.Read))) { TextReader xmlTextReader = new StringReader(xml); TextWriter xmlTextWriter = new StringWriter(); Transform(xmlTextReader, styleSheetTextReader, xmlTextWriter); result = xmlTextWriter.ToString(); } } catch { result = ""; } return result; } private static TextWriter Transform(TextReader xmlTextReader, TextReader styleSheetTextReader, TextWriter xmlTextWriter) { if (null == xmlTextReader || null == styleSheetTextReader) { return xmlTextWriter; } XslCompiledTransform xslt = new XslCompiledTransform(); XsltSettings settings = new XsltSettings(false, false); using (XmlReader sheetReader = XmlReader.Create(styleSheetTextReader)) { xslt.Load(sheetReader, settings, null); } using (XmlReader inReader = XmlReader.Create(xmlTextReader)) { xslt.Transform(inReader, null, xmlTextWriter); } return xmlTextWriter; } /// <summary> /// 序列化对象为xml文档 /// </summary> /// <typeparam name="T">对象类型</typeparam> /// <param name="item">对象</param> /// <returns>序列化的结果</returns> public static string Serialize<T>(T item) { XmlSerializer xmlSerializer = new XmlSerializer(typeof(T)); StringBuilder stringBuilder = new StringBuilder(); using (StringWriter stringWriter = new StringWriter(stringBuilder)) { xmlSerializer.Serialize(stringWriter, item); } return stringBuilder.ToString(); } /// <summary> /// 序列化对象为xml文档 /// </summary> /// <param name="item">对象</param> /// <returns>序列化的结果</returns> public static string Serialize(object item) { XmlSerializer xmlSerializer = new XmlSerializer(item.GetType()); StringBuilder stringBuilder = new StringBuilder(); using (StringWriter stringWriter = new StringWriter(stringBuilder)) { xmlSerializer.Serialize(stringWriter, item); } return stringBuilder.ToString(); } /// <summary> /// xml文档串行化为对象 /// </summary> /// <typeparam name="T">对象类型</typeparam> /// <param name="xml">xml文档</param> /// <returns>串行化的结果</returns> public static T Deserialize<T>(string xml) { XmlSerializer xmlSerializer = new XmlSerializer(typeof(T)); using (TextReader textReader = new StringReader(xml)) { return (T)xmlSerializer.Deserialize(textReader); } } /// <summary> /// xml文档串行化为对象 /// </summary> /// <param name="xml">xml文档</param> /// <param name="type">类型</param> /// <returns>串行化的结果</returns> public static object Deserialize(string xml, Type type) { XmlSerializer xmlSerializer = new XmlSerializer(type); using (TextReader textReader = new StringReader(xml)) { return xmlSerializer.Deserialize(textReader); } } } }
d3e3ed3656bdc9b36b08fb36b04d5dd17236c348
C#
dotnet-architecture/eShopOnWeb
/src/BlazorAdmin/Services/HttpService.cs
2.625
3
using System.Net.Http; using System.Text; using System.Text.Json; using System.Threading.Tasks; using BlazorShared; using BlazorShared.Models; using Microsoft.Extensions.Options; namespace BlazorAdmin.Services; public class HttpService { private readonly HttpClient _httpClient; private readonly ToastService _toastService; private readonly string _apiUrl; public HttpService(HttpClient httpClient, IOptions<BaseUrlConfiguration> baseUrlConfiguration, ToastService toastService) { _httpClient = httpClient; _toastService = toastService; _apiUrl = baseUrlConfiguration.Value.ApiBase; } public async Task<T> HttpGet<T>(string uri) where T : class { var result = await _httpClient.GetAsync($"{_apiUrl}{uri}"); if (!result.IsSuccessStatusCode) { return null; } return await FromHttpResponseMessage<T>(result); } public async Task<T> HttpDelete<T>(string uri, int id) where T : class { var result = await _httpClient.DeleteAsync($"{_apiUrl}{uri}/{id}"); if (!result.IsSuccessStatusCode) { return null; } return await FromHttpResponseMessage<T>(result); } public async Task<T> HttpPost<T>(string uri, object dataToSend) where T : class { var content = ToJson(dataToSend); var result = await _httpClient.PostAsync($"{_apiUrl}{uri}", content); if (!result.IsSuccessStatusCode) { var exception = JsonSerializer.Deserialize<ErrorDetails>(await result.Content.ReadAsStringAsync(), new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); _toastService.ShowToast($"Error : {exception.Message}", ToastLevel.Error); return null; } return await FromHttpResponseMessage<T>(result); } public async Task<T> HttpPut<T>(string uri, object dataToSend) where T : class { var content = ToJson(dataToSend); var result = await _httpClient.PutAsync($"{_apiUrl}{uri}", content); if (!result.IsSuccessStatusCode) { _toastService.ShowToast("Error", ToastLevel.Error); return null; } return await FromHttpResponseMessage<T>(result); } private StringContent ToJson(object obj) { return new StringContent(JsonSerializer.Serialize(obj), Encoding.UTF8, "application/json"); } private async Task<T> FromHttpResponseMessage<T>(HttpResponseMessage result) { return JsonSerializer.Deserialize<T>(await result.Content.ReadAsStringAsync(), new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); } }
ac787351df76b59d56e3b7460a18703d6cf6773f
C#
TheGostKasper/RDNEXAMS
/StatesExam/Assigner.cs
2.671875
3
using StatesExam.Helper; 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 StatesExam { public partial class Assigner : Form { SqlCommands cmd = new SqlCommands(DBCatalog.DB_Core.ToString()); public static int durations = 30; public static bool IsRandomized = true; string currExmsIds = ""; public Assigner() { InitializeComponent(); GetExms(); Init(); } public void Init() { cmd.Catalog = DBCatalog.DB_Exam_Engine.ToString(); int idx = (currExmsIds[currExmsIds.Length - 1] == ',') ? currExmsIds.LastIndexOf(",") : -1; currExmsIds = (idx >= 0) ? currExmsIds.Remove(idx, 1) : currExmsIds; var query = String.Format(@"select SUM(Exm_Duration_In_Mins) from t_exams where Exm_ID in ({0})", currExmsIds); cmd.GetCMDConnection(query, _cmd => { var res=_cmd.ExecuteScalar(); numericUpDown1.Value= durations = int.Parse(res.ToString()); }); } public void GetExms() { cmd.Catalog = DBCatalog.DB_Core.ToString(); cmd.ReaderCMD(String.Format(@"select * from t_assigned_exams"), _reader => { var curr_exm_id = ""; while (_reader.Read()) { curr_exm_id += String.Concat(_reader.GetValue(0).ToString(), ","); } currExmsIds = curr_exm_id; }); } private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { IsRandomized = (comboBox1.Text == "عشوائي") ? true : false; } private void btnSave_Click(object sender, EventArgs e) { try { durations = int.Parse(numericUpDown1.Value.ToString()); IsRandomized = (comboBox1.Text == "عشوائي") ? true : false; MessageBox.Show("تم الحفظ"); } catch (Exception ex) { MessageBox.Show(ex.Message); } } } }
f7ac475482b23c972e9a2795002bfadd724e1ac3
C#
xardison/Shaman
/src/Shaman.Common/Exc/ShamanObservableExceptionHandler.cs
2.515625
3
using System; using System.Diagnostics; using System.Net.Mail; using Shaman.Common.Extension; using Shaman.Common.Mail; using Shaman.Common.Messages; namespace Shaman.Common.Exc { public interface IObservableExceptionHandler : IObserver<Exception> { void SetDefaultMethodToShowError(Action<Exception> action); } internal class ShamanObservableExceptionHandler : IObservableExceptionHandler { private readonly IExceptionHandlersManager _exceptionHandlersManager; private readonly IScreenCapture _screenCapture; private readonly IMessenger _messenger; private readonly IMailer _mailer; private Action<Exception> _defaultMethodToShowError; public ShamanObservableExceptionHandler( IExceptionHandlersManager exceptionHandlersManager, IScreenCapture screenCapture, IMessenger messenger, IMailer mailer) { _exceptionHandlersManager = exceptionHandlersManager; _screenCapture = screenCapture; _messenger = messenger; _mailer = mailer; } public void OnNext(Exception value) { if (Debugger.IsAttached) Debugger.Break(); OnException(value); //RxApp.MainThreadScheduler.Schedule(() => { throw value; }); } public void OnError(Exception error) { if (Debugger.IsAttached) Debugger.Break(); OnException(error); //RxApp.MainThreadScheduler.Schedule(() => { throw error; }); } public void OnCompleted() { if (Debugger.IsAttached) Debugger.Break(); //RxApp.MainThreadScheduler.Schedule(() => { throw new NotImplementedException(); }); } public void SetDefaultMethodToShowError(Action<Exception> action) { _defaultMethodToShowError = action; } private void OnException(Exception exception) { try { if (!_exceptionHandlersManager.Handle(exception)) { ShowException(exception); } } catch (Exception innerExc) { if (Debugger.IsAttached) Debugger.Break(); var agrExc = new AggregateException( "Возникла ошибка при обработке уже имеющегося исключентя. Детали обоих исключений прилогаются", innerExc, exception); if (_defaultMethodToShowError != null) { _defaultMethodToShowError(agrExc); return; } if (Debugger.IsAttached) { Debug.Print("\n=====================================\n" + agrExc.GetMessage() + "=====================================\n"); } } } private void ShowException(Exception exception) { Log.Error(exception, "Упс!"); _mailer.SendMail(GetErrorMail(exception)); _messenger.Error(exception.GetMessage()); } private Letter GetErrorMail(Exception exception) { var letter = new ExceptionLetter(exception); letter.Attachments.Add(new Attachment(_screenCapture.CaptureScreenToStream(), "screen.jpg", "image/jpeg")); return letter; } } }
5e295e337b0b158b16efc9a65ff11cf7889d5c98
C#
ivar-blessing/ConstructionLine.CodingChallenge
/ConstructionLine.CodingChallenge.Tests/SearchEngineTests.cs
2.8125
3
using System; using System.Collections.Generic; using NUnit.Framework; namespace ConstructionLine.CodingChallenge.Tests { [TestFixture] public class SearchEngineTests : SearchEngineTestsBase { [Test] public void Test() { var shirts = new List<Shirt> { new Shirt(Guid.NewGuid(), "Red - Small", Size.Small, Color.Red), new Shirt(Guid.NewGuid(), "Black - Medium", Size.Medium, Color.Black), new Shirt(Guid.NewGuid(), "Blue - Large", Size.Large, Color.Blue), }; var searchEngine = new SearchEngine(shirts); var searchOptions = new SearchOptions { Colors = new List<Color> {Color.Red}, Sizes = new List<Size> {Size.Large} }; var results = searchEngine.Search(searchOptions); AssertResults(results.Shirts, searchOptions); AssertSizeCounts(shirts, searchOptions, results.SizeCounts); AssertColorCounts(shirts, searchOptions, results.ColorCounts); } } }
832a54e2a755d588330e649dc6eb9af92f26f760
C#
PabloGarciaGrossi/Moviles-P2
/Assets/Scripts/BoardManager.cs
2.671875
3
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace MazesAndMore { public class BoardManager : MonoBehaviour { public Tile tile; private LevelManager _lm; public Camera cam; bool[,,] walls; //Inicialización del map y cada uno de sus parámetros public void setMap(Map m) { map = m; //Contiene true o false para cada una de las direcciones de cada tile para indicar si hay pared o no walls = new bool[m.getWidth() + 1, m.getHeight() + 1, 4]; //Tiles del juego _tiles = new Tile[m.getWidth()+1, m.getHeight()+1]; //Creación de cada uno de los tiles y su posición, sin asignar ninguna de sus propiedades for (int i = 0; i < m.getWidth() + 1; i++) { for (int j = 0; j < m.getHeight() + 1; j++) { _tiles[i, j] = GameObject.Instantiate(tile); _tiles[i, j].transform.parent = this.transform; _tiles[i, j].gameObject.transform.position = new Vector2(i - m.getWidth() / 2, j - m.getHeight() / 2); } } //Ponemos el tile de inicio activau startX = m.getStart().x; startY = m.getStart().y; _tiles[startX, startY].enableStart(); //Ponemos el tile de fin activau endX = m.getEnd().x; endY = m.getEnd().y; _tiles[endX, endY].enableEnd(); _endTile = _tiles[endX, endY]; //Instanciación de los tiles según la info del map for (int i = 0; i < m.getWalls().Length; i++) { //direccion inicial del muro int posxO = m.getWalls()[i].o.x; int posyO = m.getWalls()[i].o.y; //direccion final del muro int posxD = m.getWalls()[i].d.x; int posyD = m.getWalls()[i].d.y; //Se comprueba si el muro es horizontal o vertical bool dirHorizontal = false; if (Mathf.Abs(posxO - posxD) != 0) dirHorizontal = true; //Coordenadas del tile, tomamos las coordenadas de abajo a la izquierda int x = Mathf.Min(posxO, posxD); int y = Mathf.Min(posyO, posyD); //Si es vertical if (!dirHorizontal) { _tiles[x, y].enableVerticalWall(); walls[x, y, (int)wallDir.LEFT] = true; //Activamos en la lógica el muro adyacente correspondiente if(x-1 >= 0) walls[x-1, y, (int)wallDir.RIGHT] = true; } //Si es horizontal else { _tiles[x, y].enableHorizontalWall(); walls[x, y, (int)wallDir.DOWN] = true; //Activamos en la lógica el muro adyacente correspondiente if (y-1 >= 0) walls[x, y-1, (int)wallDir.UP] = true; } } //Activación de los tiles de hielo for(int i = 0; i < m.getIce().Length; i++) { int posx = m.getIce()[i].x; int posy = m.getIce()[i].y; _tiles[posx, posy].enableIce(); } //Escalado según la cámara scale(); } public void init(LevelManager levelmanager) { _lm = levelmanager; } //Reiniciamos los valores del boardmanager public void resetBoard() { hintCount = 0; _tiles[startX, startY].disableStart(); _tiles[endX, endY].disableEnd(); ResetWalls(); ResetHints(); ResetIce(); ResetPaths(); } //Coloca el color del path para cada una de las casillas según el color del jugador public void setPathColor(Color col) { for (int i = 0; i < map.getWidth() + 1; i++) { for (int j = 0; j < map.getHeight() + 1; j++) { _tiles[i, j].setColor(col); } } } //Desactiva los paths de los tiles public void ResetPaths() { for (int i = 0; i < map.getWidth() + 1; i++) { for (int j = 0; j < map.getHeight() + 1; j++) { _tiles[i, j].disablePaths(); } } } //Reinicia las pistas del nivel public void ResetHints() { for (int i = 0; i < map.getHints().Length; i++) { int posx = map.getHints()[i].x; int posy = map.getHints()[i].y; _tiles[posx, posy].disableHint(); } } //Reinicia los tiles de hielo public void ResetIce() { for (int i = 0; i < map.getIce().Length; i++) { int posx = map.getIce()[i].x; int posy = map.getIce()[i].y; _tiles[posx, posy].disableIce(); } } //Reinicia los muros siguiendo el proceso inverso a crearlos public void ResetWalls() { for (int i = 0; i < map.getWalls().Length; i++) { int posxO = map.getWalls()[i].o.x; int posyO = map.getWalls()[i].o.y; int posxD = map.getWalls()[i].d.x; int posyD = map.getWalls()[i].d.y; bool dirHorizontal = false; if (Mathf.Abs(posxO - posxD) != 0) dirHorizontal = true; int x = Mathf.Min(posxO, posxD); int y = Mathf.Min(posyO, posyD); if (!dirHorizontal) { _tiles[x, y].disableVerticalWall(); walls[x, y, (int)wallDir.LEFT] = false; if (x - 1 >= 0) walls[x - 1, y, (int)wallDir.RIGHT] = false; } else { _tiles[x, y].disableHorizontalWall(); walls[x, y, (int)wallDir.DOWN] = false; if (y - 1 >= 0) walls[x, y - 1, (int)wallDir.UP] = false; } } } //Activación de las pistas public void activateHints() { int start = 0; int end = 0; //Comprobamos que el jugador tenga pistas y que no lleve 3 usos de pistas en el nivel if (hintCount < 3 && GameManager._instance.getHints() > 0) { //Dependiendo del número de usos, activaremos una parte de los hints u otras switch (hintCount) { case 0: start = 0; end = map.getHints().Length / 3; break; case 1: start = map.getHints().Length / 3; end = 2 * map.getHints().Length / 3; break; case 2: start = 2 * map.getHints().Length / 3; end = map.getHints().Length - 1; break; } for (int i = start; i < end; i++) { //Pillamos la posición en el mapa int posx = map.getHints()[i].x; int posy = map.getHints()[i].y; Vector2Int pos1 = new Vector2Int(posx, posy); //cogemos la próxima posición de las pistas para activarlas en los tiles int posx2 = map.getHints()[i + 1].x; int posy2 = map.getHints()[i + 1].y; Vector2Int pos2 = new Vector2Int(posx2, posy2); //Usamos el directionController para calcular la direccióon de la pista wallDir dir = directionController.getDirection(pos1, pos2); //Activación del sprite de la pista según la dirección calculada en el tile y el siguiente correspondiente a las pistas. switch (dir) { case wallDir.UP: _tiles[pos1.x, pos1.y].enableUpHint(); _tiles[pos2.x, pos2.y].enableDownHint(); break; case wallDir.DOWN: _tiles[pos1.x, pos1.y].enableDownHint(); _tiles[pos2.x, pos2.y].enableUpHint(); break; case wallDir.LEFT: _tiles[pos1.x, pos1.y].enableLeftHint(); _tiles[pos2.x, pos2.y].enableRightHint(); break; case wallDir.RIGHT: _tiles[pos1.x, pos1.y].enableRightHint(); _tiles[pos2.x, pos2.y].enableLeftHint(); break; } //Colocamos el color de hint _tiles[pos1.x, pos1.y].setPathColor(colHint); _tiles[pos2.x, pos2.y].setPathColor(colHint); } //sumamos el número de usos de pistas y lo restamos al gamemanager hintCount++; GameManager._instance.addHints(-1); } } //Escalado del boardmanager a la resolución de la cámara public void scale() { float r, scale; //Según el ancho en píxeles, calculamos la escala a multiplicar r = cam.pixelWidth / (float)cam.pixelHeight; scale = ((cam.orthographicSize - 0.01f) * 2 * r) / map.getWidth(); //cálculos para que no sobrepase los límites de la pantalla if (r > 3 / 5.0f) scale = ((cam.orthographicSize - 1.01f) * 2) / map.getHeight(); //Reescalado de mapa y transformación de la posición según si el mapa es par o impar para centrarlo correctamente en la pantalla. //Para ello uso el tamaño real, no el tamaño local, de cada tile. gameObject.transform.localScale = new Vector3(scale, scale, 1); if (map.getWidth() % 2 == 0) gameObject.transform.position = new Vector3(gameObject.transform.position.x + _tiles[0, 0].transform.lossyScale.x / 2, gameObject.transform.position.y, gameObject.transform.position.z); else gameObject.transform.position = Vector3.zero; } public Tile getEnd() { return _endTile; } public float getScale() { return totalScale; } public Tile[,] getTiles() { return _tiles; } public Color getColorHint() { return colHint; } public void setColorHint(Color col) { colHint = col; } public void RewardAdHints(){ GameManager._instance.addHints(3); Debug.Log("Ad watched"); } public void SkippedAdHints() { GameManager._instance.addHints(1); Debug.Log("Ad Skipped"); } public void FailedAd() { Debug.Log("Ad Failed"); } private Tile[,] _tiles; private Tile _endTile; int startX, startY; int endX, endY; float totalScale = 1f; int hintCount = 0; Map map; Color colHint; public bool[,,] getWalls() { return walls; } } }
53160bbfeb189fd7a422b4797e2ab4dc7475c582
C#
johnsonhaovip/DapperExt
/XNY.DataAccess/DapperExtensions/Lambda/LambdaSql/Where/IWhere.cs
2.796875
3
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; namespace DapperExtensions.Lambda { public interface IWhere<T> : IWhere where T : class { void And(Expression<Func<T, bool>> lambdaWhere); void And<T2>(Expression<Func<T, T2, bool>> lambdaWhere); void And<T2, T3>(Expression<Func<T, T2, T3, bool>> lambdaWhere); void And<T2, T3, T4>(Expression<Func<T, T2, T3, T4, bool>> lambdaWhere); void And<T2, T3, T4, T5>(Expression<Func<T, T2, T3, T4, T5, bool>> lambdaWhere); void And<T2, T3, T4, T5, T6>(Expression<Func<T, T2, T3, T4, T5, T6, bool>> lambdaWhere); void Or(Expression<Func<T, bool>> lambdaWhere); void Or<T2>(Expression<Func<T, T2, bool>> lambdaWhere); void Or<T2, T3>(Expression<Func<T, T2, T3, bool>> lambdaWhere); void Or<T2, T3, T4>(Expression<Func<T, T2, T3, T4, bool>> lambdaWhere); void Or<T2, T3, T4, T5>(Expression<Func<T, T2, T3, T4, T5, bool>> lambdaWhere); void Or<T2, T3, T4, T5, T6>(Expression<Func<T, T2, T3, T4, T5, T6, bool>> lambdaWhere); } public interface IWhere { void And(WhereClip where); /// <summary> /// Or /// </summary> /// <param name="where"></param> void Or(WhereClip where); /// <summary> /// 转换成WhereClip /// </summary> /// <returns></returns> WhereClip ToWhereClip(); } }
f9c2d61c9a295fd02c41a1196ee47cfa3d5fb1a7
C#
ghorsey/SHHH.Infrastructure.Web.AntiXss
/src/SHHH.Infrastructure.Web.AntiXss.Tests/AntiXssProcessorTestFixture.cs
2.609375
3
namespace SHHH.Infrastructure.Web.AntiXss.Tests { using System; using NUnit.Framework; /// <summary> /// The test fixture for the <see cref="IAntiXssProcessor"/> object /// </summary> [TestFixture] public class AntiXssProcessorTestFixture { /// <summary> /// Tests the process object method. /// </summary> [Test] public void TestProcessObjectMethod() { IAntiXssProcessor processor = new AntiXssProcessor(); var testObject = new SampleTestObject { IntProperty = 23, ObjectField = Guid.NewGuid(), StringField = "string <script>alert('boo!');</script> with <b>some potentially</b> dangerous code", StringProperty = "<a href='#' onclick='alert(\"ooo\")'>A link with some potentially dangerous code</a>", AllowUnsafe = "string <script>alert('boo!');</script> with <b>some potentially</b> dangerous code" }; processor.ProcessObject(testObject); Assert.AreEqual(23, testObject.IntProperty); Assert.IsNotNull(testObject.ObjectField); Assert.AreEqual( "string with <b>some potentially</b> dangerous code", testObject.StringField); Assert.AreEqual("<a href=\"\">A link with some potentially dangerous code</a>", testObject.StringProperty); Assert.AreEqual("This is unsafe", testObject.PrivateSetProperty); Assert.AreEqual( "string <script>alert('boo!');</script> with <b>some potentially</b> dangerous code", testObject.AllowUnsafe); } } }
1ba413e81f1658e6798d0b5515fd949fae531787
C#
fabriceleal/ImageProcessing
/Framework/Core/Filters/Spatial/Kernel2DBatch.cs
3.421875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Framework.Core.Filters.Spatial { /// <summary> /// Provides functionality for applying several kernels to calculate an image. /// </summary> /// <remarks> /// It follows a pattern resembling the Map-Reduce pattern: each kernel to apply will be evaluated /// and all the outputs will be "merged", resulting in the pixel to calculate. /// </remarks> public class Kernel2DBatch { #region Methods /// <summary> /// The function signature for applying a kernel to a image. /// </summary> /// <param name="kernel">The kernel to use.</param> /// <param name="operand">The image to parse.</param> /// <param name="x">The x coordinate of the pixel to generate.</param> /// <param name="y">The y coordinate of the pixel to generate.</param> /// <returns>The output of the evaluation of the kernel to the image.</returns> public delegate double EvaluateKernelDelegate(Kernel2D kernel, byte[,] operand, int x, int y); /// <summary> /// The function signature for merging the outputs of the evaluations of the several kernels. /// </summary> /// <param name="values">List of the outputs generated.</param> /// <returns>The final value of the pixel being generated.</returns> public delegate byte ReduceDelegate(List<double> values); /// <summary> /// Evaluates a list of kernels against a byte[,] image. /// </summary> /// <param name="operand">The image to parse.</param> /// <param name="kernels">The kernels to apply.</param> /// <param name="evaluateKernel">The "map" function to use. For further explaination, /// refer to the documentation of Kernel2DBatch.</param> /// <param name="reduce">The "reduce" function to use. For further explaination, /// refer to the documentation of Kernel2DBatch.</param> /// <returns>The transformed byte[,].</returns> public static byte[,] Evaluate( byte[,] operand, Kernel2D[] kernels, EvaluateKernelDelegate evaluateKernel, ReduceDelegate reduce) { int width = operand.GetLength(0); int height = operand.GetLength(1); byte[,] ret = new byte[width, height]; List<double> evaluations = new List<double>(); for (int x = 0; x < width; ++x) { for (int y = 0; y < height; ++y) { evaluations.Clear(); // -> Map for (int i = 0; i < kernels.Length; ++i) { // Evaluate evaluations.Add(evaluateKernel(kernels[i], operand, x, y)); } // -> Reduce ret[x, y] = reduce(evaluations); } } return ret; } #endregion } }
db093dc69bf4e55d36a185747f536d944dbb2273
C#
markovood/SoftUni---Tech-Module-4.0
/Objects and Classes - Lab/05. Students/Students.cs
3.765625
4
using System; using System.Collections.Generic; using System.Linq; namespace _05._Students { public class Students { public static void Main() { List<Student> students = new List<Student>(); while (true) { string[] tokens = Console.ReadLine().Split(' ', StringSplitOptions.RemoveEmptyEntries); if (tokens[0] == "end") { break; } string firstName = tokens[0]; string lastName = tokens[1]; int age = int.Parse(tokens[2]); string homeTown = tokens[3]; var student = new Student(firstName, lastName, age, homeTown); students.Add(student); } string city = Console.ReadLine(); var filtered = students.Where(s => s.HomeTown == city); foreach (var student in filtered) { Console.WriteLine(student); } } } }
8a05b70fdfba560954e401a223091bc92dd792f0
C#
Janluke0/opendiagram
/Previous_Versions/Version_4.1/Examples/C#/Tutorial/CustomRender.cs
2.6875
3
using System; using System.Drawing; using System.Drawing.Text; using Crainiate.ERM4; namespace WindowsApplication1 { public class CustomRender: Render { private string mWatermark; //Constructor public CustomRender(): base() { Watermark = string.Empty; base.DrawSelections = true; base.DrawGrid = true; } //Properties public virtual string Watermark { get { return mWatermark; } set { mWatermark = value; } } //Overrides protected override void OnPreRender(System.Drawing.Graphics graphics) { if (Watermark != string.Empty) { SolidBrush brush = new SolidBrush(Color.FromArgb(128,Color.LightGray)); Font font = new Font("Arial",72,FontStyle.Bold); graphics.TextRenderingHint = TextRenderingHint.AntiAlias; graphics.DrawString(Watermark, font, brush, new PointF(30,30)); graphics.TextRenderingHint = TextRenderingHint.SystemDefault; } base.OnPreRender (graphics); } } }
862092058598c89582738aba4923df2ec4057714
C#
shendongnian/download4
/first_version_download2/306682-41503774-135365514-2.cs
2.546875
3
public class MyTableSource : UITableViewSource { string SectionIndentifer = "mySection"; string CellIndentifer = "myCell"; public List<MyItem> vList { get; set; } List<bool> expandStatusList; // Maintain a list which keeps track if a section is expanded or not public MeasurementsDetailsTableSource (List<MyItem> vList) { this.vList = vList; expandStatusList = new List<bool> (); for (int i = 0; i < vList.Count; i++) { expandStatusList.Add (false); // Initially, no section are expanded } } public override nint NumberOfSections (UITableView tableView) { return vList.Count; } public override nint RowsInSection (UITableView tableview, nint section) { if (!expandStatusList [(int)section]) return 0; // Returning 0 to hide all the rows of the section, there by collapsing the section. return vList [(int)section].subItems.Count; } public override UIView GetViewForHeader (UITableView tableView, nint section) { UITableViewCell cell = tableView.DequeueReusableCell (SectionIndentifer); if (cell == null) { cell = new UITableViewCell (UITableViewCellStyle.Default, SectionIndentifer); } ... // Settings up a click event to section to expand the section.. var gesture = new UITapGestureRecognizer (); gesture.AddTarget (() => ParentClick (gesture)); cell.AddGestureRecognizer (gesture); cell.Tag = section; // This is needed to indentify the section clicked.. return cell; } public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) { UITableViewCell cell = tableView.DequeueReusableCell (CellIndentifer); if (cell == null) { cell = new UITableViewCell (UITableViewCellStyle.Default, CellIndentifer); } ... return cell; } public void ParentClick (UITapGestureRecognizer gesture) { NSIndexPath indexPath = NSIndexPath.FromRowSection (0, gesture.View.Tag); if (indexPath.Row == 0) { if (vList [indexPath.Section].mValues.Count != 0) { bool expandStatus = expandStatusList [indexPath.Section]; for (int i = 0; i < vList.Count; i++) { if (indexPath.Section == i) { expandStatusList [i] = !expandStatus; } } tableView.ReloadSections (NSIndexSet.FromIndex (gesture.View.Tag), UITableViewRowAnimation.Automatic); tableView.ReloadData (); return; } } } }
edbe74b4dd19bedd3a83fd612d2ad9f70d3fb6b1
C#
tedKarabeliov/Telerik-Academy
/Data Structures and Algorithms/Trees and Traversals/3. File Tree/Folder.cs
3.484375
3
using System; using System.Collections.Generic; using System.IO; namespace FileTree { public class Folder { public string Name { get; set; } public File[] Files { get; set; } public Folder[] ChildFolders { get; set; } public Folder(string name) { //Assign name this.Name = name; //Assign files try { var files = Directory.GetFiles(this.Name); this.Files = new File[files.Length]; for (int i = 0; i < files.Length; i++) { this.Files[i] = new File(files[i]); } //Assign folders var folders = Directory.GetDirectories(this.Name); this.ChildFolders = new Folder[folders.Length]; for (int i = 0; i < folders.Length; i++) { this.ChildFolders[i] = new Folder(folders[i]); } } catch (UnauthorizedAccessException ex) { Console.WriteLine("Restricted file or folder"); } } } }
887bd117ecc4efa05677dc4b567dcfba1f55ff32
C#
IvanChepik/TAT_2019.1
/DEV-5/DEV-5/EntryPoint.cs
3.53125
4
using System; using System.Collections.Generic; using Points; using Flying; namespace DEV_5 { /// <summary> /// Class EntryPoint /// gets fly time for 3 object of this classes. /// </summary> public class EntryPoint { /// <summary> /// Method Main /// entry point. /// </summary> /// <param name="args"></param> public static void Main(string[] args) { try { var startPoint = new Point(0, 0, 0); var newPoint = new Point(100,200,800); var flyables = new List<IFlyable> { new Bird(startPoint), new Plane(startPoint), new SpaceShip(startPoint) }; foreach (var flyable in flyables) { flyable.Flied += DisplayFlyMessage; flyable.FlyTo(newPoint); Console.WriteLine(flyable.GetFlyTime()); } } catch (ObjectIDontFlyException e) { Console.WriteLine("Error : " + e.Message); } catch (Exception e) { Console.WriteLine("Something going wrong : " + e.Message ); } } /// <summary> /// Method DisplayFlyMessage /// handler for Flied event, calls when object in flight. /// </summary> /// <param name="sender">object calls event</param> /// <param name="eventArgs">arguments for events</param> private static void DisplayFlyMessage(object sender, FlyingEventArgs eventArgs) { Console.WriteLine(eventArgs.Message); } } }
38b80900bc72db1135366fa578004b527631921a
C#
itplamen/Telerik-Academy
/Programming with C#/5. C# Data Structures and Algorithms/01.LinearDataStructures/11.ImplementDataStructureLinkedList.Tests/LinkedListTests.cs
3.09375
3
namespace _11.ImplementDataStructureLinkedList.Tests { using System; using Microsoft.VisualStudio.TestTools.UnitTesting; [TestClass] public class LinkedListTests { private LinkedList<string> linkedList; [TestInitialize] public void TestInitialize() { this.linkedList = new LinkedList<string>(); } [TestMethod] [ExpectedException(typeof(ArgumentOutOfRangeException))] public void Indexer_ReturnInvalidValue() { this.linkedList.Add("Asus"); var element = this.linkedList[3]; } [TestMethod] public void Indexer_ReturnValidElement() { this.linkedList.Add("debug"); this.linkedList.Add("build"); var expected = "build"; Assert.AreEqual(expected, this.linkedList[1]); } [TestMethod] [ExpectedException(typeof(ArgumentOutOfRangeException))] public void Indexer_SetInvalidElement() { this.linkedList.Add("project"); this.linkedList[-1] = "test"; } [TestMethod] public void Indexer_SetValidElement() { this.linkedList.Add("project"); this.linkedList.Add("project"); this.linkedList.Add("project"); this.linkedList[2] = "hp"; var expected = "hp"; Assert.AreEqual(expected, this.linkedList[2]); } [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void Add_NullableElement() { this.linkedList.Add(null); } [TestMethod] public void Add_AddElements() { string[] array = { "C#", "Java", "C++" }; for (int i = 0; i < array.Length; i++) { this.linkedList.Add(array[i]); } bool expectedResult = true; for (int i = 0; i < this.linkedList.Count; i++) { if (this.linkedList[i] != array[i]) { expectedResult = false; break; } } Assert.IsTrue(expectedResult); } [TestMethod] [ExpectedException(typeof(ArgumentOutOfRangeException))] public void Insert_InvalidIndex() { this.linkedList.Add("linux"); this.linkedList.Add("unix"); this.linkedList.Add("array"); this.linkedList.Insert(4, "IL"); } [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void Insert_InvalidElement() { this.linkedList.Add("linux"); this.linkedList.Add("unix"); this.linkedList.Add("array"); this.linkedList.Insert(1, null); } [TestMethod] public void Insert_InsertElementAtTheHead() { this.linkedList.Add("linux"); this.linkedList.Add("unix"); this.linkedList.Add("array"); this.linkedList.Insert(0, "mac"); var expected = "mac"; Assert.AreEqual(expected, this.linkedList[0]); } [TestMethod] public void Insert_InsertElementAtTheEnd() { this.linkedList.Add("linux"); this.linkedList.Add("unix"); this.linkedList.Add("array"); this.linkedList.Insert(2, "mac"); var expected = "mac"; Assert.AreEqual(expected, this.linkedList[3]); } [TestMethod] public void Insert_InsertElementAtTheSpecifiedPosition() { this.linkedList.Add("linux"); this.linkedList.Add("unix"); this.linkedList.Add("array"); this.linkedList.Add("class"); this.linkedList.Add("enum"); this.linkedList.Insert(2, "mac"); var expected = "mac"; Assert.AreEqual(expected, this.linkedList[2]); } [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void Remove_NullableElement() { this.linkedList.Add("xp"); this.linkedList.Remove(null); } [TestMethod] public void Remove_NotExistElement() { this.linkedList.Add("xp"); bool isElementRemoved = this.linkedList.Remove("asp"); Assert.IsFalse(isElementRemoved); } [TestMethod] public void Remove_RemoveElementFromTheHead() { this.linkedList.Add("xp"); this.linkedList.Add(".net"); this.linkedList.Add("framework"); this.linkedList.Remove("xp"); var expected = ".net"; var headElement = this.linkedList[0]; Assert.AreEqual(expected, headElement); } [TestMethod] public void Remove_RemoveElementFromTheEnd() { this.linkedList.Add("xp"); this.linkedList.Add(".net"); this.linkedList.Add("framework"); this.linkedList.Remove("framework"); var expected = ".net"; var lastElement = this.linkedList[1]; Assert.AreEqual(expected, lastElement); } [TestMethod] public void Remove_RemoveElementFromTheSpecifiedPosition() { this.linkedList.Add("xp"); this.linkedList.Add(".net"); this.linkedList.Add("framework"); this.linkedList.Remove(".net"); Assert.IsFalse(this.linkedList.Contains(".net")); } [TestMethod] [ExpectedException(typeof(ArgumentOutOfRangeException))] public void RemoveAt_InvalidIndex() { this.linkedList.Add("xp"); this.linkedList.Add(".net"); this.linkedList.RemoveAt(-1); } [TestMethod] public void RemoveAt_RemoveElementAtTheSpecifiedIndex() { this.linkedList.Add("xp"); this.linkedList.Add(".net"); this.linkedList.Add("IL"); this.linkedList.RemoveAt(1); } [TestMethod] public void Clear_ClearAllElement() { this.linkedList.Add("xp"); this.linkedList.Clear(); bool isListEmpty = true; if (this.linkedList.Count != 0 || this.linkedList.Contains("xp") == true) { isListEmpty = false; } Assert.IsTrue(isListEmpty); } [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void Contains_NullableElemen() { this.linkedList.Add("xp"); this.linkedList.Add(".net"); this.linkedList.Add("IL"); this.linkedList.Contains(null); } [TestMethod] public void Contains_True() { this.linkedList.Add("xp"); this.linkedList.Add(".net"); this.linkedList.Add("IL"); Assert.IsTrue(this.linkedList.Contains("IL")); } [TestMethod] public void Contains_False() { this.linkedList.Add("xp"); this.linkedList.Add(".net"); this.linkedList.Add("IL"); Assert.IsFalse(this.linkedList.Contains("mono")); } [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void IndexOf_NullableElement() { this.linkedList.Add("xp"); this.linkedList.Add(".net"); this.linkedList.Add("IL"); this.linkedList.IndexOf(null); } [TestMethod] public void IndexOf_ReturnIndexOfTheElement() { this.linkedList.Add("xp"); this.linkedList.Add(".net"); this.linkedList.Add("IL"); var expectedIndex = 2; Assert.AreEqual(expectedIndex, this.linkedList.IndexOf("IL")); } [TestMethod] public void IndexOf_IfListDoesntContainsTheElement() { this.linkedList.Add("xp"); this.linkedList.Add(".net"); this.linkedList.Add("IL"); var expectedIndex = -1; Assert.AreEqual(expectedIndex, this.linkedList.IndexOf("basic")); } [TestMethod] public void ToArray_ConvertListToArray() { this.linkedList.Add("xp"); this.linkedList.Add(".net"); this.linkedList.Add("IL"); string[] array = this.linkedList.ToArray(); bool expected = true; for (int i = 0; i < this.linkedList.Count; i++) { if (this.linkedList[i] != array[i]) { expected = false; break; } } Assert.IsTrue(expected); } [TestMethod] public void Reverse_ReverseElementsOrder() { this.linkedList.Add("xp"); this.linkedList.Add(".net"); this.linkedList.Add("IL"); this.linkedList.Reverse(); string[] array = { "IL", ".net", "xp" }; bool areElementsReversed = true; for (int i = 0; i < this.linkedList.Count; i++) { if (this.linkedList[i] != array[i]) { areElementsReversed = false; break; } } Assert.IsTrue(areElementsReversed); } [TestMethod] public void Sort_SortElementsInAscendingOrder() { this.linkedList.Add("xp"); this.linkedList.Add("app"); this.linkedList.Add("IL"); this.linkedList.Sort(); string[] sortedElements = { "app", "IL", "xp" }; bool areElementsSorted = true; for (int i = 0; i < this.linkedList.Count; i++) { if (this.linkedList[i] != sortedElements[i]) { areElementsSorted = false; break; } } Assert.IsTrue(areElementsSorted); } [TestMethod] public void ToString_PrintElements() { this.linkedList.Add("xp"); this.linkedList.Add("app"); this.linkedList.Add("IL"); var expected = "xp app IL"; var result = this.linkedList.ToString(); Assert.AreEqual(expected, result); } [TestMethod] public void GetEnumerator_TestForeachLoop() { this.linkedList.Add("xp"); this.linkedList.Add("app"); this.linkedList.Add("IL"); string[] array = { "xp", "app", "IL" }; int index = 0; bool expected = true; foreach (var item in this.linkedList) { if (item != array[index]) { expected = false; } index++; } Assert.IsTrue(expected); } } }
6be0c48bb3e6f39b7d1322b1162b4b7edd575d40
C#
arey1124/ConsoleApplication-Examples
/EmployeeNew.cs
3.46875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Linq; namespace ConsoleApp1 { class EmployeeNew { public int id { get; set; } public string ename { get; set; } public string job { get; set; } public int salary { get; set; } private List<EmployeeNew> employees; public void AddEmployee(EmployeeNew e) { this.employees.Add(e); } public void displayNames() { var query = from data in employees select data.ename; foreach(string name in query) { Console.WriteLine("{0}",name); } } public void DeleteEmployee(int id) { for (var i = 0; i < employees.Count(); i++) { if (employees[i].id == id) { employees.Remove(employees[i]); } } } public void SearchEmployee(int id) { foreach (EmployeeNew e1 in employees) { if (e1.id == id) { Console.WriteLine("{0} , {1} , {2} , {3}", e1.id, e1.ename, e1.job, e1.salary); } } } public void UpdateEmployee(int id,EmployeeNew e) { for(int i = 0; i < employees.Count(); i++) { if (employees[i].id == id) { employees[i] = e; } } } public List<EmployeeNew> GetEmployees() { employees = new List<EmployeeNew>() { new EmployeeNew { id = 1, ename = "Ariha", job = "SE", salary = 55000 }, new EmployeeNew { id = 2, ename = "Chaya", job = "P", salary = 54000 }, new EmployeeNew { id = 3, ename = "Prash", job = "SE", salary = 53000 }, new EmployeeNew { id = 4, ename = "Kir", job = "P", salary = 52000 }, new EmployeeNew { id = 5, ename = "A", job = "SE", salary = 51000 }, new EmployeeNew { id = 6, ename = "B", job = "P", salary = 50000 }, new EmployeeNew { id = 7, ename = "C", job = "SE", salary = 51000 }, new EmployeeNew { id = 8, ename = "D", job = "P", salary = 58000 }, new EmployeeNew { id = 9, ename = "E", job = "SE", salary = 59000 }, new EmployeeNew { id = 10, ename = "F", job = "P", salary = 42000 }, new EmployeeNew { id = 11, ename = "G", job = "SE", salary = 32000 }, new EmployeeNew { id = 12, ename = "H", job = "P", salary = 2000 }, new EmployeeNew { id = 13, ename = "I", job = "SE", salary = 12000 }, new EmployeeNew { id = 14, ename = "J", job = "SE", salary = 22000 }, new EmployeeNew { id = 15, ename = "K", job = "P", salary = 32000 } }; return employees; } } }
7a57678642bf961b600e433808aea3f37c092225
C#
allwinvinoth/RS-ECL-Server-master
/LIS.Data/Repositories/DepartmentRepository.cs
2.875
3
using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using LIS.DataContracts.Entities; using LIS.DataContracts.Repositories; using Microsoft.EntityFrameworkCore; using System.Linq; namespace LIS.Data.Repositories { public sealed class DepartmentRepository : IDepartmentRepository { private readonly LISDbContext _dbContext; public DepartmentRepository(LISDbContext dbContext) { _dbContext = dbContext; } public async Task<DepartmentEntity> GetDepartmentById(int id, CancellationToken token) { return await _dbContext.Departments .SingleAsync(department => department.Id == id && department.IsActive, token); } public async Task<DepartmentEntity> CreateDepartmentAsync(DepartmentEntity departmentEntity, CancellationToken token) { await _dbContext.Departments.AddAsync(departmentEntity, token); await _dbContext.SaveChangesAsync(token); return departmentEntity; } public async Task<IEnumerable<DepartmentEntity>> GetDepartmentsByBranchIdAsync(int branchId, CancellationToken token) { return await _dbContext.Departments.Where(department => department.BranchId == branchId && department.IsActive).ToListAsync(token); } public async Task<IEnumerable<DepartmentEntity>> GetAll(CancellationToken token) { return await _dbContext.Departments.Where(department => department.IsActive).ToListAsync(token); } public async Task<DepartmentEntity> UpdateDepartmentAsync(DepartmentEntity departmentEntity, CancellationToken token) { _dbContext.Departments.Update(departmentEntity); await _dbContext.SaveChangesAsync(token); return departmentEntity; } public async Task DeleteDepartmentByIdAsync(int departmentId, CancellationToken token) { var departmentEntity =await _dbContext.Departments.SingleAsync(department => department.Id == departmentId && department.IsActive,token); departmentEntity.IsActive = false; await _dbContext.SaveChangesAsync(); } } }
c0e6f98e5aa484f39d480c882e8a774ae26863e4
C#
manasachervirala/Assignmentpractice
/anonymous methods/lamdaexpresions.cs
3.8125
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lamda_expresions { //DEfine the delegates with respected methods with the code public delegate double AddnumsDelegate(int x,float y,double z); public delegate void Addnums2Delegate(int x, float y, double z);// public delegate bool CheckDelegate(string str); class Program { //method with returning value public static double Addnums(int x, float y, double z) { return (x + y + z); } //method with non returning value public static void Addnum2(int x, float y, double z) { Console.WriteLine(x + y + z); } public static bool Check(string name) { //check the string whose lenght is greater than the four if (name.Length>4) return true; return false; } // public static double Add(string name) // { // return "hello" + " " + name + "GOOD Afternoon"; // } static void Main(string[] args) { //AddnumsDelegate obj1 = new AddnumsDelegate(Addnums);//new variables to store the values ---return value //double result = obj1.Invoke(10, 3.14f, 123.12324); //Console.WriteLine(result); /* AddnumsDelegate obj1 = delegate(int x,float y,double z)*///new variables to store the values ---return value //AddnumsDelegate obj1 = (x,y,z) => //using the lamda operator Func<int,float,double,double> obj1 = (x, y, z) => { return(x + y + z); }; //double result = obj1.Invoke(10, 3.14f, 123.12324); Console.WriteLine(obj1); Action<int, float, double> obj2 = (x, y, z) => { Console.WriteLine(x + y + z); }; obj2.Invoke(10, 3.14f, 12345.123434); //Addnums2Delegate obj2 = new Addnums2Delegate(Addnum2);//non return type //obj2.Invoke(10, 3.14f, 12345.123434); Predicate<string> obj3 = (name) => { if (name.Length > 4) return true; return false; }; //CheckDelegate obj3 = new CheckDelegate(Check);//New Variable to store the value --return value //bool check = obj3.Invoke("MANASA"); //Console.WriteLine(check); //Console.ReadLine(); // GreetingsDelegate obj = new GreetingsDelegate(Greetings); //GreetingsDelegate obj = delegate (string name)//initializing delegate using anonoyous //{ // return "hello " + " " + name +" " + " GOOD Afternoon"; //}; //GreetingsDelegate obj = name=> // lamda operator //{ // return "hello" + " " + name + "GOOD Afternoon"; //}; //string str = obj.Invoke("Manasa"); //Console.WriteLine(str); //Console.ReadLine(); // } } }
242b9d24597f08bceeb600eb07c4b0eba5fc635d
C#
delimaxdev/DX.CQRS
/src/DX.Contracts/ContractAttribute.cs
2.609375
3
using System; namespace DX.Contracts { [AttributeUsage( AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Enum, AllowMultiple = false, Inherited = false)] public sealed class ContractAttribute : Attribute { public string? Name { get; set; } public string? PartialName { get; set; } public Type[] GenericArguments { get; set; } = new Type[0]; public bool IsPolymorphic { get; set; } = false; public ContractAttribute() { } public ContractAttribute(string name) { Name = Check.NotNull(name, nameof(name)); } } }
58427bfb71d19b478d70cdec602986b930356be1
C#
aj-r/Utils
/Sharp.Utils/Linq/UtilsEnumerable.cs
3.421875
3
using System; using System.Collections.Generic; using System.Linq; using Sharp.Utils.Transactions; namespace Sharp.Utils.Linq { /// <summary> /// Contains methods for querying objects that implements IEnumerable. /// </summary> public static class UtilsEnumerable { /// <summary> /// Determines whether the number of elements in a sequence is equal to a certain value. /// </summary> /// <typeparam name="T">The type of the elements of <paramref name="source"/>.</typeparam> /// <param name="source">A sequence that contains elements to be counted.</param> /// <param name="count">The expected number of elements.</param> /// <returns><value>true</value> if <paramref name="source"/> contains the specified number of elements exactly; otherwise <value>false</value>.</returns> /// <remarks> /// This method is more efficient than Enumerable.Count() because it will stop enumerating items after it passes the count. /// Thus, if the actual number of elements is much more than count, this method will perform faster. /// However, it will be the same speed if <paramref name="source"/> is an ICollection&lt;T&gt;. /// </remarks> public static bool HasCount<T>(this IEnumerable<T> source, int count) { var collection = source as ICollection<T>; if (collection != null) return collection.Count == count; return source.Take(count + 1).Count() == count; } /// <summary> /// Determines whether the number of elements in a sequence is equal to a certain value. /// </summary> /// <typeparam name="T">The type of the elements of <paramref name="source"/>.</typeparam> /// <param name="source">A sequence that contains elements to be counted.</param> /// <param name="count">The expected number of elements.</param> /// <returns><value>true</value> if <paramref name="source"/> contains the specified number of elements exactly; otherwise <value>false</value>.</returns> public static bool HasCount<T>(this ICollection<T> source, int count) { return source.Count == count; } /// <summary> /// Determines whether the sequence contains at least a certain number of elements. /// </summary> /// <typeparam name="T">The type of the elements of <paramref name="source"/>.</typeparam> /// <param name="source">A sequence that contains elements to be counted.</param> /// <param name="count">The minimum number of elements.</param> /// <returns><value>true</value> if <paramref name="source"/> contains at least the specified number of elements; otherwise <value>false</value>.</returns> /// <remarks> /// This method is more efficient than Enumerable.Count() because it will stop enumerating items after it passes the count. /// Thus, if the actual number of elements is much more than count, this method will perform faster. /// However, it will be the same speed if <paramref name="source"/> is an ICollection&lt;T&gt;. /// </remarks> public static bool HasAtLeast<T>(this IEnumerable<T> source, int count) { var collection = source as ICollection<T>; if (collection != null) return collection.Count >= count; return source.Take(count).Count() == count; } /// <summary> /// Determines whether the sequence contains at least a certain number of elements. /// </summary> /// <typeparam name="T">The type of the elements of source.</typeparam> /// <param name="source">A sequence that contains elements to be counted.</param> /// <param name="count">The minimum number of elements.</param> /// <returns><value>true</value> if <paramref name="source"/> contains at least the specified number of elements; otherwise <value>false</value>.</returns> public static bool HasAtLeast<T>(this ICollection<T> source, int count) { return source.Count >= count; } /// <summary> /// Determines whether the sequence contains at most a certain number of elements. /// </summary> /// <typeparam name="T">The type of the elements of source.</typeparam> /// <param name="source">A sequence that contains elements to be counted.</param> /// <param name="count">The minimum number of elements.</param> /// <returns><value>true</value> if <paramref name="source"/> contains at most the specified number of elements; otherwise <value>false</value>.</returns> /// <remarks> /// This method is more efficient than Enumerable.Count() because it will stop enumerating items after it passes the count. /// This, if the actual number of elements is much more than count, this method will perform faster. /// However, it will be the same speed if source is an ICollection&lt;T&gt;. /// </remarks> public static bool HasAtMost<T>(this IEnumerable<T> source, int count) { var collection = source as ICollection<T>; if (collection != null) return collection.Count <= count; return source.Take(count + 1).Count() <= count; } /// <summary> /// Determines whether the sequence contains at most a certain number of elements. /// </summary> /// <typeparam name="T">The type of the elements of source.</typeparam> /// <param name="source">A sequence that contains elements to be counted.</param> /// <param name="count">The minimum number of elements.</param> /// <returns><value>true</value> if <paramref name="source"/> contains at most the specified number of elements; otherwise <value>false</value>.</returns> public static bool HasAtMost<T>(this ICollection<T> source, int count) { return source.Count <= count; } /// <summary> /// Gets a range of items in an IEnumerable. /// </summary> /// <typeparam name="T">The type of the elements of source.</typeparam> /// <param name="source">A sequence that contains elements.</param> /// <param name="startIndex">The index at which to start taking elements.</param> /// <param name="endIndex">The index to stop taking elements. The element at this index is not included.</param> /// <returns>A subset of source.</returns> public static IEnumerable<T> Range<T>(this IEnumerable<T> source, int startIndex, int endIndex) { return source.Skip(startIndex).Take(endIndex - startIndex); } /// <summary> /// Returns the first element in a sequence, or a default value if the sequence is empty. /// </summary> /// <typeparam name="T">The type of the elements of source.</typeparam> /// <param name="source">A sequence that contains elements.</param> /// <param name="defaultValue">The value to return if the sequence is empty.</param> /// <returns>The first item in source.</returns> public static T FirstOr<T>(this IEnumerable<T> source, T defaultValue) { foreach (var item in source) return item; return defaultValue; } /// <summary> /// Returns the first element of the sequence that satisfies a condition, or a default value if no value matches the condition. /// </summary> /// <typeparam name="T">The type of the elements of source.</typeparam> /// <param name="source">A sequence that contains elements.</param> /// <param name="defaultValue">The value to return if the sequence is empty.</param> /// <param name="predicate">A function to test each element for a condition.</param> /// <returns>The first item in source.</returns> public static T FirstOr<T>(this IEnumerable<T> source, T defaultValue, Func<T, bool> predicate) { foreach (var item in source) if (predicate(item)) return item; return defaultValue; } /// <summary> /// Gets the first index of the item in source that equals the specified value. /// </summary> /// <typeparam name="T">The type of the elements of source.</typeparam> /// <param name="source">A sequence that contains elements.</param> /// <param name="value">The value to look for.</param> /// <returns>An enumerable contaning the indices of all items in source that match the given criteria.</returns> public static int IndexOf<T>(this IEnumerable<T> source, T value) { return IndexOf(source, value, 0); } /// <summary> /// Gets the first index of the item in source that matches the given criteria. /// </summary> /// <typeparam name="T">The type of the elements of source.</typeparam> /// <param name="source">A sequence that contains elements.</param> /// <param name="predicate">A function to test each element for a condition.</param> /// <returns>The index of the first item in source that match the given criteria.</returns> public static int IndexOf<T>(this IEnumerable<T> source, Func<T, bool> predicate) { return IndexOf(source, predicate, 0); } /// <summary> /// Gets the first index of the item in source that equals the specified value. /// </summary> /// <typeparam name="T">The type of the elements of source.</typeparam> /// <param name="source">A sequence that contains elements.</param> /// <param name="value">The value to look for.</param> /// <param name="startIndex">The index at which to start the search.</param> /// <returns>An enumerable contaning the indices of all items in source that match the given criteria.</returns> public static int IndexOf<T>(this IEnumerable<T> source, T value, int startIndex) { return IndexOf(source, value, startIndex, -1); } /// <summary> /// Gets the first index of the item in source that matches the given criteria. /// </summary> /// <typeparam name="T">The type of the elements of source.</typeparam> /// <param name="source">A sequence that contains elements.</param> /// <param name="predicate">A function to test each element for a condition.</param> /// <param name="startIndex">The index at which to start the search.</param> /// <returns>The index of the first item in source that match the given criteria.</returns> public static int IndexOf<T>(this IEnumerable<T> source, Func<T, bool> predicate, int startIndex) { return IndexOf(source, predicate, startIndex, -1); } /// <summary> /// Gets the first index of the item in source that equals the specified value. /// </summary> /// <typeparam name="T">The type of the elements of source.</typeparam> /// <param name="source">A sequence that contains elements.</param> /// <param name="value">The value to look for.</param> /// <param name="startIndex">The index at which to start the search.</param> /// <param name="count">The number of items to search.</param> /// <returns>An enumerable contaning the indices of all items in source that match the given criteria.</returns> public static int IndexOf<T>(this IEnumerable<T> source, T value, int startIndex, int count) { return IndexOf(source, t => EqualityComparer<T>.Default.Equals(t, value), startIndex, count); } /// <summary> /// Gets the first index of the item in source that matches the given criteria. /// </summary> /// <typeparam name="T">The type of the elements of source.</typeparam> /// <param name="source">A sequence that contains elements.</param> /// <param name="predicate">A function to test each element for a condition.</param> /// <param name="startIndex">The index at which to start the search.</param> /// <param name="count">The number of items to search.</param> /// <returns>The index of the first item in source that match the given criteria.</returns> public static int IndexOf<T>(this IEnumerable<T> source, Func<T, bool> predicate, int startIndex, int count) { return IndicesOf(source, predicate, startIndex, count).FirstOr(-1); } /// <summary> /// Gets the indices of all items in source that are equal to the specified value. /// </summary> /// <typeparam name="T">The type of the elements of source.</typeparam> /// <param name="source">A sequence that contains elements.</param> /// <param name="value">The value to look for.</param> /// <returns>An enumerable contaning the indices of all items in source that match the given criteria.</returns> public static IEnumerable<int> IndicesOf<T>(this IEnumerable<T> source, T value) { return IndicesOf(source, value, 0); } /// <summary> /// Gets the indices of all items in source that match the given criteria. /// </summary> /// <typeparam name="T">The type of the elements of source.</typeparam> /// <param name="source">A sequence that contains elements.</param> /// <param name="predicate">A function to test each element for a condition.</param> /// <returns>An enumerable contaning the indices of all items in source that match the given criteria.</returns> public static IEnumerable<int> IndicesOf<T>(this IEnumerable<T> source, Func<T, bool> predicate) { return IndicesOf(source, predicate, 0); } /// <summary> /// Gets the indices of all items in source that are equal to the specified value. /// </summary> /// <typeparam name="T">The type of the elements of source.</typeparam> /// <param name="source">A sequence that contains elements.</param> /// <param name="value">The value to look for.</param> /// <param name="startIndex">The index at which to start the search.</param> /// <returns>An enumerable contaning the indices of all items in source that match the given criteria.</returns> public static IEnumerable<int> IndicesOf<T>(this IEnumerable<T> source, T value, int startIndex) { return IndicesOf(source, value, startIndex, -1); } /// <summary> /// Gets the indices of all items in source that match the given criteria. /// </summary> /// <typeparam name="T">The type of the elements of source.</typeparam> /// <param name="source">A sequence that contains elements.</param> /// <param name="predicate">A function to test each element for a condition.</param> /// <param name="startIndex">The index at which to start the search.</param> /// <returns>An enumerable contaning the indices of all items in source that match the given criteria.</returns> public static IEnumerable<int> IndicesOf<T>(this IEnumerable<T> source, Func<T, bool> predicate, int startIndex) { return IndicesOf(source, predicate, startIndex, -1); } /// <summary> /// Gets the indices of all items in source that are equal to the specified value. /// </summary> /// <typeparam name="T">The type of the elements of source.</typeparam> /// <param name="source">A sequence that contains elements.</param> /// <param name="value">The value to look for.</param> /// <param name="startIndex">The index at which to start the search.</param> /// <param name="count">The number of items to search.</param> /// <returns>An enumerable contaning the indices of all items in source that match the given criteria.</returns> public static IEnumerable<int> IndicesOf<T>(this IEnumerable<T> source, T value, int startIndex, int count) { return IndicesOf(source, t => EqualityComparer<T>.Default.Equals(t, value), startIndex, count); } /// <summary> /// Gets the indices of all items in source that match the given criteria. /// </summary> /// <typeparam name="T">The type of the elements of source.</typeparam> /// <param name="source">A sequence that contains elements.</param> /// <param name="predicate">A function to test each element for a condition.</param> /// <param name="startIndex">The index at which to start the search.</param> /// <param name="count">The number of items to search.</param> /// <returns>An enumerable contaning the indices of all items in source that match the given criteria.</returns> public static IEnumerable<int> IndicesOf<T>(this IEnumerable<T> source, Func<T, bool> predicate, int startIndex, int count) { var itemsToSearch = source; if (startIndex > 0) itemsToSearch = itemsToSearch.Skip(startIndex); if (count >= 0) itemsToSearch = itemsToSearch.Take(count); int index = startIndex; foreach (var item in itemsToSearch) { if (predicate(item)) yield return index; ++index; } } /// <summary> /// Adds multiple items to the end of a collection. /// </summary> /// <typeparam name="T">The type of the elements of <paramref name="source"/>.</typeparam> /// <param name="source">A sequence that contains elements.</param> /// <param name="items">The items to add.</param> public static void AddRange<T>(this ICollection<T> source, IEnumerable<T> items) { if (source == null) throw new ArgumentNullException("source"); if (source is List<T>) ((List<T>)source).AddRange(items); else if (source is TransactableCollection<T>) ((TransactableCollection<T>)source).AddRange(items); else foreach (var item in items) source.Add(item); } } }
f5585f8ecffc8b8586bad48c683d1dc37b7367d7
C#
veenabkatte/functionsAndException
/FunctionsAndExceptions/FunctionsAndExceptions/CustomExcepDemo.cs
2.90625
3
using System; using System.Collections.Generic; using System.Text; namespace FunctionsAndExceptions { class CustomExcepDemo { static void Main() { try { Employee employee = new Employee(); employee.ValidateEmployeeCode(0, "Scott"); } catch (InvalidEmployeeCode ex) { Console.WriteLine(ex.Message); } Console.ReadLine(); } } }
dea340de1edc643a7cd037e0f8177dfd0fbd0298
C#
jkoefoed21/PhysicsStats
/PhysicsStats/Player.cs
3.671875
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PhysicsStats { class Player { public string First { get; } public string Last { get; } public Player(string LastName, string FirstName) { if (FirstName==null||LastName==null) { throw new ArgumentNullException("Players must have non-null names"); } if (LastName.Equals("")) { throw new ArgumentException("Players must have non-empty Last Name"); } First = FirstName; Last = LastName; } public override string ToString() { if (First.Equals("")) { return Last; } return First + " " + Last; } public override bool Equals(object obj) { if (obj is Player) { Player p2 = (Player)obj; if (p2.First.ToLower().Equals(this.First.ToLower())&&p2.Last.ToLower().Equals(this.Last.ToLower())) { return true; } } return false; } } }
34ad6add951945cf9ce6370da175fbb382fcec52
C#
JohnnyKapps/fubumvc
/src/FubuMVC.Spark/SparkModel/SparkFileReader.cs
2.625
3
using System; using System.IO; using System.Xml; using FubuMVC.Core.View.Model; namespace FubuMVC.Spark.SparkModel { public class SparkFileReader { private readonly string _file; public SparkFileReader(string file) { _file = file; } // <viewdata model="FubuMVC.Diagnostics.DashboardModel" /> public Parsing Read() { var parsing = new Parsing(); using (var reader = new StreamReader(_file)) { string line; // Read and display lines from the file until the end of // the file is reached. while ((line = reader.ReadLine()) != null) { if (line.Contains("<viewdata")) { var document = new XmlDocument(); document.LoadXml(line.Trim()); parsing.ViewModelType = document.DocumentElement.GetAttribute("model"); } } } return parsing; } } }
ebea935146fee37ef7e4ee501c9d0f81eac36865
C#
1993Max/MxFrameWork
/MFrameWork/Assets/Scripts/GameLibs/CodeExtend/TypeEx.cs
2.859375
3
using System.Collections; using System.Collections.Generic; using UnityEngine; using System; namespace MFrameWork { public static class TypeEx { /// <summary> /// 获取默认值 /// </summary> /// <param name="targetType"></param> /// <returns></returns> public static object DefaultForType(this Type targetType) { return targetType.IsValueType ? Activator.CreateInstance(targetType) : null; } public static string DefaultValueStringForType(this Type targetType) { if (targetType.IsClass) { return "null"; } else { return $"default({targetType.FullName})"; } } /// <summary> /// 获取类型的简化名称 /// </summary> /// <param name="typeName"></param> /// <returns></returns> public static string GetSimpleTypeName(string typeName) { var result = typeName; if (typeName.Contains(".")) { result = typeName.Substring(typeName.LastIndexOf(".") + 1); } return result; } /// <summary> /// 获取类型名,可使用在代码中 /// </summary> /// <param name="type"></param> /// <returns></returns> public static string GetTypeName(this Type type) { var replace = type.FullName?.Replace('+', '.'); return replace; } } }
6ccd19958b24de97fff0d3a02d4285824bb641ce
C#
azhurba/stockcalculation
/StockProductivityCalculation/StockCalculator.cs
3.09375
3
using StockProductivityCalculation.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace StockProductivityCalculation { public static class StockCalculator { public static IList<decimal> Calculate(IStockData data) { var totalRecords = data.Years + 1; var result = new List<decimal>(totalRecords); result.Add(data.Price * data.Quantity); for (int i = 1; i < totalRecords; i++) { result.Add(result[i - 1]); result[i] += result[i] * (decimal)data.Percentage / 100; } return result; } } public interface IStockData { decimal Price { get; set; } int Quantity { get; set; } double Percentage { get; set; } int Years { get; set; } } public class StockData : IStockData { public decimal Price { get; set; } public int Quantity { get; set; } public double Percentage { get; set; } public int Years { get; set; } public StockData(StockDetails details) { if (!details.Years.HasValue || !details.Quantity.HasValue || !details.Price.HasValue || !details.Percentage.HasValue) { throw new ArgumentException("details"); } this.Percentage = details.Percentage.Value; this.Price = details.Price.Value; this.Quantity = details.Quantity.Value; this.Years = details.Years.Value; } public StockData() { } } }
29f37777129946821a748db6ec4174bbc9d30725
C#
mithila451/bank_2
/bank_2/Checking account.cs
2.546875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace bank_2 { class Checking_account:account { public override void ShowAccountInformation() { base.ShowAccountInformation(); } public override void Withdraw(double amount) { if (amount > 0 && amount <= Balance) { Balance -= amount; TransactionIncrement(); } } } }
ee713081064c27854ca87c34ed009a2620202d25
C#
Bshowg/QuarantineJam
/Assets/Scripts/TextManager.cs
2.640625
3
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class TextManager : MonoBehaviour{ public GameObject text; public List<string> possibleLines; public void requireTexts(List<GameObject> subjects) { foreach (GameObject g in subjects) { GameObject newText = GameObject.Instantiate(text) as GameObject; newText.transform.SetParent(transform); newText.transform.SetAsFirstSibling(); newText.GetComponent<WigglyWaggly>().subject = g; if (possibleLines != null) { if (possibleLines.Count > 0) { int l = Random.Range(0, possibleLines.Count); string s = possibleLines[l]; newText.GetComponent<Text>().text = s; } } } } }
f498c4122ba854b255042ce91b9ff97e1bc31c73
C#
janalvares/Tugas-Delegete-dan-Event
/CalculatorDelegate/Perhitungan.cs
2.65625
3
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace CalculatorDelegate { public partial class Perhitungan : Form { public Perhitungan() { InitializeComponent(); } public delegate void CreateEventHandler(int a, string operasi, int b, int hasil); public event CreateEventHandler Add; public event CreateEventHandler Remove; private bool isNewData = true; Calculator cal; private void BtnProses_Click_1(object sender, EventArgs e) { if (isNewData) cal = new Calculator(); { Add(cal.NilaiA, cal.Operasi, cal.NilaiB, cal.Hasil); string op; int hasil, nilai1, nilai2; nilai1 = int.Parse(textNilaiA.Text); nilai2 = int.Parse(textNilaiB.Text); cal.NilaiA = nilai1; cal.NilaiB = nilai2; if (Operasi.SelectedIndex == -1) { MessageBox.Show("Pilih Operasi !"); } else if (Operasi.SelectedIndex == 0) { op = "+"; hasil = nilai1 + nilai2; hasil = cal.Hasil; op = cal.Operasi; } else if (Operasi.SelectedIndex == 1) { op = "-"; hasil = nilai1 - nilai2; hasil = cal.Hasil; op = cal.Operasi; } else if (Operasi.SelectedIndex == 2) { op = "*"; hasil = nilai1 * nilai2; hasil = cal.Hasil; op = cal.Operasi; } else if(Operasi.SelectedIndex == 3) { op = "/"; hasil = nilai1 / nilai2; hasil = cal.Hasil; op = cal.Operasi; } } else if() { Remove(Cal); } } } }
72f83eeca206fac2600d418e15d26b3d0aa5ccb8
C#
MindfireTechnology/Bonobo-Git-Server
/Bonobo.Git.Server/Owin/WindowsAuthenticationHandshakeCache.cs
2.8125
3
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Runtime.Caching; using System.Web; namespace Bonobo.Git.Server.Owin.Windows { internal class WindowsAuthenticationHandshakeCache { private static readonly int expirationTimeInMinutes = 1; private MemoryCache handshakeCache; public bool TryGet(string key, out WindowsAuthenticationHandshake handshake) { bool result = false; handshake = null; if (handshakeCache.Contains(key)) { object cachedHandshake = handshakeCache[key]; if (cachedHandshake != null) { handshake = cachedHandshake as WindowsAuthenticationHandshake; result = true; } } return result; } public void Add(string key, WindowsAuthenticationHandshake handshake) { handshakeCache.Set(key, handshake, GetCacheItemPolicy()); } public bool TryRemove(string key) { return handshakeCache.Remove(key) != null; } private static CacheItemPolicy GetCacheItemPolicy() { var policy = new CacheItemPolicy() { Priority = CacheItemPriority.Default, AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(expirationTimeInMinutes), RemovedCallback = (handshake) => { IDisposable expiredHandshake = handshake.CacheItem as IDisposable; if (expiredHandshake != null) { expiredHandshake.Dispose(); } } }; return policy; } public WindowsAuthenticationHandshakeCache(string name) { handshakeCache = new MemoryCache(name); } } }
6f6ab9d58f716badd6c75dd30ddc06efca2d52fd
C#
Elian173/tp_laboratorio_2
/Elian_Rojas_TP2_2C/TP-02/Entidades/Leche.cs
3.0625
3
using System; using System.Text; namespace Entidades_2018 { public class Leche: Producto { #region Atributos public enum ETipo { Entera, Descremada } private ETipo tipo; #endregion Atributos #region Constructores /// <summary> /// Constructor publico Leche , con un tipo especifico (Por defecto, TIPO será ENTERA) /// </summary> /// <param name="marca">Nombre de la marca</param> /// <param name="codigoDeBarras">Codigo de barras</param> /// <param name="colorEmpaque">Color del empaque</param> /// <param name="tipoDeLeche">(Entera o Descremada)</param> public Leche( EMarca marca, string codigoDeBarras, ConsoleColor colorEmpaque, ETipo tipoDeLeche ) : base(marca, codigoDeBarras, colorEmpaque) { this.tipo = tipoDeLeche; } /// <summary> /// Constructor publico Leche , (Por defecto, TIPO será ENTERA) /// </summary> /// <param name="marca">Nombre de la marca</param> /// <param name="codigoDeBarras">Codigo de barras</param> /// <param name="colorEmpaque">Color del empaque</param> public Leche( EMarca marca, string codigoDeBarras, ConsoleColor color ) : this(marca, codigoDeBarras, color, ETipo.Entera) { } #endregion Constructores #region Propiedades /// <summary> /// Las leches tienen 20 calorías /// </summary> protected override short CantidadCalorias { get { return 20; } } #endregion Propiedades #region Metodos /// <summary> /// Expone los datos del elemento , incluyendo los de su clase base ( Producto ). /// </summary> /// <returns></returns> public override sealed string Mostrar() { StringBuilder descripcion = new StringBuilder(); descripcion.AppendLine("LECHE"); descripcion.AppendLine(base.Mostrar()); descripcion.AppendFormat("CALORIAS : {0}", this.CantidadCalorias); descripcion.AppendLine(""); descripcion.AppendLine("TIPO : " + this.tipo); descripcion.AppendLine("---------------------"); return descripcion.ToString(); } #endregion Metodos } }
45946457e91e10c9375ef9438359c7f2701ac10e
C#
ArkadyPL/Multiagent-Action-Language
/MultiAgentLanguageModels/Reasoning/Structure.cs
2.515625
3
using System.Collections.Generic; namespace MultiAgentLanguageModels.Reasoning { public class Structure { public HashSet<State> InitialStates { get; } public HashSet<State> PossibleStates { get; } public Dictionary<Triple, HashSet<State>> Res { get; } public Structure(HashSet<State> initialStates, HashSet<State> possibleStates, Dictionary<Triple, HashSet<State>> res) { InitialStates = initialStates; PossibleStates = possibleStates; Res = res; } } }
860b21004381f75d78a862f322b731d98f21416b
C#
g-stoyanov/BattleField2
/CurrentVersion/BattleField.Common.Tests/GameFieldTest.cs
2.703125
3
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace BattleField.Common.Tests { [TestClass] public class GameFieldTest { [TestMethod] public void TestGameFieldConstructor() { FieldCell fieldCell = new FieldCell(); byte fieldSize = 3; GameField gameField = new GameField(fieldSize); Assert.AreEqual(gameField.FieldSize, fieldSize); } [TestMethod] public void TestCountRemainingMines() { IUserInterface userInterface = new KeyboardInterface(); IRenderer renderer = new ConsoleRenderer(); GameField gameField = new GameField(3); GameEngine gameEngine = new GameEngine(userInterface, renderer, gameField); gameEngine.InitializeField(); Assert.IsTrue(gameField.CountRemainingMines() == 0); } [TestMethod] public void TestFieldCellIndexator() { IUserInterface userInterface = new KeyboardInterface(); IRenderer renderer = new ConsoleRenderer(); GameField gameField = new GameField(3); GameEngine gameEngine = new GameEngine(userInterface, renderer, gameField); gameEngine.InitializeField(); FieldCell fieldCell = new FieldCell(); Assert.AreEqual(gameField[0, 0].ToString(), fieldCell.ToString()); } } }
8b9c711f1b482bf5e3e3945648e2506d0f1e9434
C#
IPA3211/JumpMonkey
/simple android/Assets/Script/SwipeManager.cs
3.015625
3
using UnityEngine; using System; public class SwipeManager : MonoBehaviour { [Flags] public enum SwipeDirection { None = 0, Left = 1, Right = 2, Up = 4, Down = 8 } private static SwipeManager m_instance; public static SwipeManager Instance { get { if (!m_instance) { m_instance = new GameObject("SwipeManager").AddComponent<SwipeManager>(); } return m_instance; } } public SwipeDirection Direction { get; private set; } private Vector3 m_touchPosition; private float m_swipeResistanceX = Screen.width / 20; private float m_swipeResistanceY = Screen.height / 40; private void Start() { if (m_instance != this) { Debug.LogError("Don't instantiate SwipeManager manually"); DestroyImmediate(this); } Debug.Log(m_swipeResistanceX); Debug.Log(m_swipeResistanceY); } private void Update() { Direction = SwipeDirection.None; if (Input.GetMouseButtonDown(0)) { m_touchPosition = Input.mousePosition; Debug.Log(m_touchPosition); } if (Input.GetMouseButtonUp(0)) { Vector2 deltaSwipe = m_touchPosition - Input.mousePosition; Debug.Log(deltaSwipe); if (Mathf.Abs(deltaSwipe.x) > Mathf.Abs(deltaSwipe.y)) deltaSwipe.y = 0; else deltaSwipe.x = 0; if (Mathf.Abs(deltaSwipe.x) > m_swipeResistanceX) { // Swipe on the X axis Direction |= (deltaSwipe.x < 0) ? SwipeDirection.Right : SwipeDirection.Left; } if (Mathf.Abs(deltaSwipe.y) > m_swipeResistanceY) { // Swipe on the Y axis Direction |= (deltaSwipe.y < 0) ? SwipeDirection.Up : SwipeDirection.Down; } } } public bool IsSwiping(SwipeDirection dir) { return (Direction & dir) == dir; } }
06c5135c20f963d529656e138867767e379c5421
C#
shendongnian/download4
/first_version_download2/192694-14713525-35527848-2.cs
3.140625
3
static void Main(string[] args) { List<String> datestrings = new List<string>() { "12/23/2012 09:51", "9/27/2012 11:36", "10/2/2012 12:28", "10/3/2012 10:51" }; List<DateTime> dates = datestrings.Select(a => DateTime.Parse(a)).OrderBy(a => a).ToList(); foreach (var d in dates) { Console.WriteLine(d); } Console.ReadLine(); }
5aecf2ab84706abde9ee6d45b29e549686450e18
C#
Stevie-O/SharpLua
/SharpLua/NewParser/XmlDocumentation/ExtractDocumentationComments.cs
2.6875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using SharpLua.Ast; using SharpLua.Ast.Statement; using SharpLua.Ast.Expression; namespace SharpLua.XmlDocumentation { public class ExtractDocumentationComments { public static List<DocumentationComment> Extract(Chunk c) { if (c.ScannedTokens != null && c.ScannedTokens.Count > 0) { List<DocumentationComment> cmnts = new List<DocumentationComment>(); for (int p = 0; p < c.ScannedTokens.Count; p++) { Token t_ = c.ScannedTokens[p]; Token t = t_.Leading.Count > 0 ? t_.Leading[0] : null; if (t != null) { int i = 0; DocumentationComment cmt = new DocumentationComment(); do { if (t_.Leading.Count <= i) break; t = t_.Leading[i++]; if (t.Type == TokenType.DocumentationComment) cmt.Lines.Add(t.Data); } while (t.Type == TokenType.WhitespaceN || t.Type == TokenType.WhitespaceR || t.Type == TokenType.WhitespaceSpace || t.Type == TokenType.WhitespaceTab || t.Type == TokenType.DocumentationComment); // find the ident it's for if (c.ScannedTokens.Count > p) { t = c.ScannedTokens[p]; if (t.Type == TokenType.Keyword && t.Data == "local") if (c.ScannedTokens[p + 1].Type == TokenType.Keyword && c.ScannedTokens[p + 1].Data == "function") { int i2 = 2; while ( (c.ScannedTokens[p + i2].Type == TokenType.Symbol && c.ScannedTokens[p + i2].Data == ".") || (c.ScannedTokens[p + i2].Type == TokenType.Ident)) i2++; cmt.Ident = c.ScannedTokens[p + i2 - 1].Data; p += i2; } else { int i2 = 2; while ( (c.ScannedTokens[p + i2].Type == TokenType.Symbol && c.ScannedTokens[p + i2].Data == ".") || (c.ScannedTokens[p + i2].Type == TokenType.Ident)) i2++; cmt.Ident = c.ScannedTokens[p + i2 - 1].Data; p += i2; } else if (t.Type == TokenType.Keyword && t.Data == "function") { int i2 = 1; while ( (c.ScannedTokens[p + i2].Type == TokenType.Symbol && c.ScannedTokens[p + i2].Data == ".") || (c.ScannedTokens[p + i2].Type == TokenType.Ident)) i2++; cmt.Ident = c.ScannedTokens[p + i2 - 1].Data; p += i2; } else if (t.Type == TokenType.Ident) { int i2 = 1; while ( (c.ScannedTokens[p + i2].Type == TokenType.Symbol && c.ScannedTokens[p + i2].Data == ".") || (c.ScannedTokens[p + i2].Type == TokenType.Ident)) i2++; cmt.Ident = c.ScannedTokens[p + i2 - 1].Data; p += i2; } } if (cmt.Ident != null && string.IsNullOrEmpty(cmt.Ident) == false && cmt.Lines.Count > 0) { //Console.WriteLine("YEP: " + cmt.Ident); cmnts.Add(cmt); } else { /* Console.Write("NOPE: (" + (cmt.Ident == null ? "" : cmt.Ident) + ")"); Console.WriteLine( cmt.Ident == null ? "Ident is null" : (string.IsNullOrEmpty(cmt.Ident) ? "Ident is empty" : (cmt.Lines.Count == 0 ? "No doc lines" : "wut?")) ); */ } } } return cmnts; } return new List<DocumentationComment>(); } } }
620c605bc11fd0ea7c200561dcc0f68a81a2b65d
C#
tripathi-error/LibraryManagement
/LibraryManagmentDataAccessLayer/Repositories/UserActionDbRepository.cs
2.734375
3
using LibraryManagmentDataAccessLayer.Interfaces; using LibraryManagmentDomainLayer.Entities; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LibraryManagmentDataAccessLayer.Repositories { public class UserActionDbRepository : IUserActionRepository { private readonly LibraryDbContext _libraryDbContext; public UserActionDbRepository(LibraryDbContext libraryDbContext) { _libraryDbContext = libraryDbContext; } public void AddBookToUserRecord(UserBooksRecord userBooksRecord) { _libraryDbContext.Add(userBooksRecord); } public void EditUserBookRecord(UserBooksRecord userBooksRecord) { var bookDetail = _libraryDbContext.UserBooksRecords.Find(userBooksRecord.ApplicationUser.Id); if (bookDetail != null) { bookDetail.IsFavorite = userBooksRecord.IsFavorite; bookDetail.IsRead = userBooksRecord.IsRead; _libraryDbContext.Update(bookDetail); } } public void PostReview(BookReview bookReview) { _libraryDbContext.Add(bookReview); } public async Task<UserBooksRecord> GetUserRecordByBookId(int bookId, string userId) { return await _libraryDbContext.UserBooksRecords.Where(s => s.BookId == bookId && s.ApplicationUser.Id == userId).FirstOrDefaultAsync(); } public async Task<bool> SaveAsync() { return await _libraryDbContext.SaveChangesAsync() > 0; } } }
c59b2a6b5ff6e53ed758ebe33be02a8c42916d47
C#
modelse/DojoQuotes
/UserFactory.cs
3
3
using System.Collections.Generic; using System.Linq; using Dapper; using System.Data; using MySql.Data.MySqlClient; using quotes.Models; namespace quotes.Factory { public class UserFactory { private string connectionString; public UserFactory() { connectionString = "server=localhost;userid=root;password=root;port=3306;database=mydb;SslMode=None"; } internal IDbConnection Connection { get { return new MySqlConnection(connectionString); } } public void Add(Quotes item) { using (IDbConnection dbConnection = Connection) { string query = "INSERT INTO quotes (name, content, created_at, updated_at) VALUES (@name, @content, NOW(), NOW())"; dbConnection.Open(); dbConnection.Execute(query, item); } } public IEnumerable<Quotes> FindAll() { using (IDbConnection dbConnection = Connection) { dbConnection.Open(); return dbConnection.Query<Quotes>("SELECT * FROM quotes"); } } public Quotes FindByID(int id) { using (IDbConnection dbConnection = Connection) { dbConnection.Open(); return dbConnection.Query<Quotes>("SELECT * FROM quotes WHERE id = @Id", new { Id = id }).FirstOrDefault(); } } } }
84547d94fb20cc1f9aef57d08b5030640700aa9f
C#
dhtweb/dht
/DhtCrawler/Encode/Exception/DecodeException.cs
2.890625
3
using System; using System.Text; namespace DhtCrawler.Encode.Exception { public class DecodeException : System.Exception { public byte[] ErrorBytes { get; } public int ErrorIndex { get; } public DecodeException(byte[] errorBytes, int errorIndex, string msg, System.Exception innerException) : base(msg, innerException) { ErrorBytes = errorBytes; ErrorIndex = errorIndex; } public DecodeException(byte[] errorBytes, int errorIndex, string msg) : this(errorBytes, errorIndex, msg, null) { } public override string ToString() { var sb = new StringBuilder(); sb.Append($"Decode Error Data:{BitConverter.ToString(ErrorBytes)}").Append(Environment.NewLine); sb.Append($"Decode Error Index:{ErrorIndex}").Append(Environment.NewLine); sb.Append(base.ToString()); return sb.ToString(); } } }
e9293c3685e195c55a4a8de59b944d7b13127c66
C#
coniturbo/miniSqlParser
/MiniSqlParser/Exprs/AggregateFuncExpr.cs
2.625
3
 namespace MiniSqlParser { public class AggregateFuncExpr : Expr { public AggregateFuncExpr(string name , QuantifierType quantifier , bool wildcard , Expr argument1 , Expr argument2) { this.Name = name; this.Quantifier = quantifier; this.Wildcard = wildcard; this.Argument1 = argument1; this.Argument2 = argument2; var c = CountTrue(this.Quantifier != QuantifierType.None , this.Wildcard , this.Argument2 != null // Commaの有無 ); this.Comments = new Comments(c + 3); } internal AggregateFuncExpr(string name , QuantifierType quantifier , bool wildcard , Expr argument1 , Expr argument2 , Comments comments) { this.Comments = comments; this.Name = name; this.Quantifier = quantifier; this.Wildcard = wildcard; this.Argument1 = argument1; this.Argument2 = argument2; } public string Name { get; private set; } public QuantifierType Quantifier { get; private set; } public bool Wildcard { get; private set; } private Expr _argument1; public Expr Argument1 { get { return _argument1; } set { _argument1 = value; this.SetParent(value); } } private Expr _argument2; public Expr Argument2 { get { return _argument2; } set { _argument2 = value; this.SetParent(value); } } protected override void AcceptImp(IVisitor visitor) { visitor.VisitBefore(this); int offset = this.Quantifier != QuantifierType.None ? 3 : 2; if(this.Wildcard) { visitor.VisitOnWildCard(this, offset); offset += 1; } else { if(this.Argument1 != null) { this.Argument1.Accept(visitor); } if(this.Argument2 != null) { visitor.VisitOnSeparator(this, offset, 0); offset += 1; this.Argument2.Accept(visitor); } } visitor.VisitAfter(this); } } }
386d70272829a1ae045d2bb6bf17cee4eaa9f768
C#
shendongnian/download4
/code1/100781-1706472-3408924-2.cs
2.78125
3
int WS_CHILD = 0x40000000; int WS_VISIBLE = 0x10000000; // paint wpf on int hParentWnd myWindow = new MyWpfWindow(); // First it creates an HwndSource, whose parameters are similar to CreateWindow: HwndSource otxHwndSource = new HwndSource( 0, // class style WS_VISIBLE | WS_CHILD, // style 0, // exstyle 10, 10, 200, 400, "MyWpfWindow", // NAME (IntPtr)hParentWnd // parent window ); otxHwndSource.RootVisual = ...; // following must be set to prcess key events myHwndSource.AddHook(new HwndSourceHook(ChildHwndSourceHook));
cec73e5b9206e0b4313dafe0a2080a36cbe2faec
C#
ASHWINI-GUPTA/LeadX.NET
/example/Program.cs
2.734375
3
using System; using System.Threading.Tasks; using LeadX.NET.Entities; namespace Example { class Program { static async Task Main(string[] args) { Console.WriteLine("Application Started...!!!"); var cred = new LeadXCredential("YOUR ACCESS TOKEN"); var leadX = LeadX.NET.LeadX.Client(cred); leadX.Version = "1.0"; leadX.OrganizationId = 1; leadX.VendorId = "ORGANIZATION VENDOR ID/KEY"; // Get the current user info var currentUser = await leadX.Users.MeAsync(); Console.WriteLine($"Hello, {currentUser.FirstName}!"); } } }
39114bf410be6c0d4476cdc85305aed74b549ed5
C#
jtlai0921/AEL013700
/範例程式 (1)/C#範例程式/PageRedirect/SessionState.aspx.cs
2.84375
3
using System; using System.Web.UI; public partial class SessionState : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } //儲存Session狀態資料 protected void btnSave_Click(object sender, EventArgs e) { if (!string.IsNullOrEmpty(txtName.Text) && !string.IsNullOrEmpty(txtTel.Text)) { Session["Name"] = txtName.Text; Session["Tel"] = txtTel.Text; txtMsg.Text = "Session狀態儲存成功!"; } else { txtMsg.Text = "不得為空白或null!"; } } //讀取Session狀態資料 protected void btnRead_Click(object sender, EventArgs e) { txtMsg.Text = ""; if (Session["Name"] != null && Session["Tel"] != null) { txtMsg.Text = "Session狀態資料如下:<br/>"; txtMsg.Text += "姓名:" + Session["Name"] + "<br/>"; txtMsg.Text += "Tel:" + Session["Tel"]; } else { txtMsg.Text = "Session狀態值為null"; } } }
4fb40b7c514d13f9d5220d74fc2b88af573bf29c
C#
dhunt3/FizzBuzz
/Program.cs
3.46875
3
namespace FizzBuzzDoro { class Program { static void Main(string[] args) { int fizz = 3; int buzz = 5; int fizzBuzz = fizz * buzz; int num = 15; for (int counter = 1; counter <= num; counter++) { if (counter % fizzBuzz == 0) { //System.Console.Write('\n'); System.Console.Write("FB "); } else if (counter % fizz == 0) { // System.Console.Write('\n'); System.Console.Write("F "); } else if (counter % buzz == 0) { //System.Console.Write('\n'); System.Console.Write("B "); } else { //System.Console.Write('\n'); System.Console.Write(counter + " "); } } System.Console.ReadLine(); } } }
079c09a6f823f7ef9ec22326d0e97f7cf5a14781
C#
chertpong/PhaSom-Ecommerce
/Model/Concrete/EFPostRepository.cs
3.0625
3
using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Linq.Expressions; using Model.Entity; using Model.Repository; namespace Model.Concrete { public class EFPostRepository : IPostRepository, IDisposable { private readonly EFDbContext _context; private bool _disposed; public EFPostRepository(EFDbContext context) { this._context = context; this._disposed = false; } public List<Post> GetAll() { return _context.Posts.ToList(); } public Post GetById(int id) { return _context.Posts.First(p => p.Id.Equals(id)); } public void Create(Post post) { _context.Posts.Add(post); _context.SaveChanges(); } public void Update(Post post) { _context.Entry(post).State = EntityState.Modified; _context.SaveChanges(); } public void Delete(int id) { var post = _context.Posts.Find(id); _context.Posts.Remove(post); _context.SaveChanges(); } public List<Post> Find(Expression<Func<Post, bool>> predicate) { return _context.Posts.Where(predicate.Compile()).ToList(); } protected virtual void Dispose(bool disposing) { if (!this._disposed) { if (disposing) { _context.Dispose(); } } this._disposed = true; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } } }
66681cd9f42c964852b61f1ef7944f855f0b5431
C#
dcarles/PurchaseOrderRuleEngine
/PurchaseOrderRuleEngine/Models/PurchaseOrder.cs
2.578125
3
using System; using System.Collections.Generic; namespace PurchaseOrderRuleEngine.Models { public class PurchaseOrder { public int PONumber { get; set; } public decimal TotalAmount { get; set; } public Customer Customer { get; set; } public List<PurchaseOrderItem> Items { get; } public PurchaseOrder() { Items = new List<PurchaseOrderItem>(); } public void AddItem(PurchaseOrderItem item) { Items.Add(item); } } }
10ec8ba50719aabf13d0f527ec55ff3aef234db0
C#
maxappdevelopement/Labb3_VatCalculator
/VATCalculator/VATCalculator/MainPage.xaml.cs
2.9375
3
using System; using System.ComponentModel; using Xamarin.Forms; namespace VATCalculator { // Learn more about making custom code visible in the Xamarin.Forms previewer // by visiting https://aka.ms/xamarinforms-previewer [DesignTimeVisible(false)] public partial class MainPage : ContentPage { public MainPage() { InitializeComponent(); eightPercent.Clicked += (s,e) => CalculateVat(8); twelvePercent.Clicked += (s, e) => CalculateVat(12); twentyFivePercent.Clicked += (s, e) => CalculateVat(25); } void CalculateVat(double vat) { double amount; if (!(Double.TryParse(input.Text, out amount) && amount > 0)) { inputError.Text = "Fyll i ett belopp"; return; } inputAmount.Text = input.Text + " SEK"; vatRate.Text = vat + "%"; calculatedAmount.Text = CalculateExcludeVat(amount, vat); calculatedVat.Text = CalculateVat(amount, vat); inputError.Text = string.Empty; } private string CalculateExcludeVat(double amount, double vat) { double amountExcludedVat = 100 / (100 + vat) * amount; return amountExcludedVat.ToString("0.00") + " SEK"; } private string CalculateVat(double amount, double vat) { double vatAmount = (1 - 100 / (100 + vat)) * amount; return vatAmount.ToString("0.00") + " SEK"; } } }
e8c442a738be756ebfa6e031fd2f969fec44effc
C#
ArchitectNow/TypeScripter
/TypeScripter.Tests/TypeScriptCompiler.cs
3.046875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Diagnostics; namespace TypeScripter.Tests { public static class TypeScriptCompiler { #region Internal Constructs /// <summary> /// A class representing the compiler result /// </summary> public class Result { /// <summary> /// The compiler return code /// </summary> public int ReturnCode { get; private set; } /// <summary> /// The compiler output /// </summary> public string Output { get; private set; } /// <summary> /// The compiler output /// </summary> public string ErrorOutput { get; private set; } /// <summary> /// Constructor /// </summary> /// <param name="returnCode"></param> /// <param name="output"></param> /// <param name="errorOutput"></param> public Result(int returnCode, string output, string errorOutput) { this.ReturnCode = returnCode; this.Output = output; this.ErrorOutput = errorOutput; } } #endregion #region Static Methods /// <summary> /// Compiles a TypeScript file /// </summary> /// <param name="file">The typescript file name</param> /// <returns>The tsc return code</returns> public static Result CompileFiles(params string[] files) { var options = ""; var process = new Process(); process.StartInfo.FileName = "tsc.cmd"; process.StartInfo.Arguments = string.Format("{0} {1}", options, string.Join(" ", files)); process.StartInfo.WorkingDirectory = System.IO.Directory.GetCurrentDirectory() + "\\..\\.."; process.StartInfo.CreateNoWindow = true; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; process.Start(); process.WaitForExit(10 * 1000); var output = process.StandardOutput.ReadToEnd(); var errorOutput = process.StandardError.ReadToEnd(); return new Result(process.ExitCode, output, errorOutput); } /// <summary> /// Compiles a specific string of TypeScript /// </summary> /// <param name="typeScript">The TypeScript to compile</param> /// <returns>The tsc return code</returns> public static Result Compile(string typeScript) { var tempFile = System.IO.Path.GetTempFileName(); System.IO.File.WriteAllText(tempFile, typeScript); try { var newTempFile = tempFile.Replace(".tmp", ".ts"); System.IO.File.Move(tempFile, newTempFile); tempFile = newTempFile; return CompileFiles(tempFile); } finally { System.IO.File.Delete(tempFile); } } #endregion } }
1358d258ba945f4e1cac394a7ab252ded5b58168
C#
twistedstream/FluentSiteMap
/src/FluentSiteMap.Core/Builders/TargetNodeBuilder.cs
3.078125
3
using System; namespace TS.FluentSiteMap.Builders { /// <summary> /// A <see cref="DecoratingNodeBuilder"/> class /// that sets the node target. /// </summary> public class TargetNodeBuilder : DecoratingNodeBuilder { private readonly Func<Node, BuilderContext, string> _targetGenerator; /// <summary> /// Initializes a new instance of the <see cref="TargetNodeBuilder"/> class. /// </summary> /// <param name="inner"> /// The inner <see cref="INodeBuilder"/> instance being decorated. /// </param> /// <param name="targetGenerator"> /// An expression that generates the node target. /// </param> public TargetNodeBuilder(INodeBuilder inner, Func<Node, BuilderContext, string> targetGenerator) : base(inner) { if (targetGenerator == null) throw new ArgumentNullException("targetGenerator"); _targetGenerator = targetGenerator; } /// <summary> /// Overrides the <see cref="DecoratingNodeBuilder.OnBuild"/> method, /// setting the node title. /// </summary> protected override void OnBuild(Node node, BuilderContext context) { node.Target = _targetGenerator(node, context); } } }
d92ba0bf7c0f80b66dfa5373e16d1c0ccaa9ea2a
C#
gvishu2003/BRENew
/BRE/BusinessEngineService.cs
2.71875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using BRE.Interfaces; using BRE.Repository; namespace BRE { public class BusinessEngineService : IBusinessRule { private List<IRules> rules = new List<IRules>(); private List<string> actions = new List<string>(); public static BusinessEngineService LoadFromString(string ruleInString) { var lines = ruleInString.Split('\n'); var brs = new BusinessEngineService(); var ruleSelection = ExtractRules(lines); brs.rules.AddRange(ruleSelection); var selection = ExtractActions(lines); brs.actions.AddRange(selection); return brs; } private static IEnumerable<string> ExtractActions(IEnumerable<string> lines) { var selection = lines.SkipWhile(x => !x.Contains("actions:")); selection = selection.Skip(1); selection = selection.Select(x => x.Trim().Replace("- ", "")); return selection; } private static IEnumerable<IRules> ExtractRules(IEnumerable<string> lines) { var extracted = ExtractLines(lines); var selection = extracted.Select<string, IRules>(x => { if (x.StartsWith("membership upgrade")) { return new MembershipUpgradeRepository(); } else if (x.StartsWith("membership request")) { var extractedType = x.Replace("membership request", "").Trim(); extractedType = extractedType.Substring(0, 1).ToUpper() + extractedType.Substring(1, extractedType.Length - 1); var membershipType = (MembershipType)Enum.Parse(typeof(MembershipType), extractedType); return new MembershipRepository(membershipType); } else if (x.StartsWith("commission")) { return new CommissionRepository(); } else if (x.StartsWith("video")) { var title = x.Replace("video", "").Trim(); return new ProductRepository("video", title); } else if (x.StartsWith("physical product")) { return new PhysicalProductRepository(); } else { throw new Exception(); } }); return selection; } private static IEnumerable<string> ExtractLines(IEnumerable<string> lines) { var selection = lines.SkipWhile(x => !x.Contains("rules:")); selection = selection.Skip(1); selection = selection.TakeWhile(x => !x.Contains("actions:")); selection = selection.Select(x => x.Trim().Replace("- ", "")); return selection; } public bool ShouldApply(IGetOrder purchaseOrder) { return rules.All(x => x.ShouldApply(purchaseOrder)); } public void Apply(IOrderFunctionalities purchaseOrder) { actions.ForEach(x => { if (x.Contains("membership activate books")) { purchaseOrder.AddMembership(MembershipType.Books); } else if (x.Contains("add video")) { purchaseOrder.AddVideo(x.Replace("add video", "").Trim()); } else if (x.Contains("membership activate upgrade")) { purchaseOrder.UpgradeMembership(); } else if (x.Contains("create shipping slip")) { purchaseOrder.CreateShippingSlip(); } else if (x.Contains("generate comission")) { purchaseOrder.GenerateCommission(); } }); } } }
a4129a41061e9229b543f14169f14835f5a5de42
C#
zarusz/LightDataInterface
/LightDataInterface.Core/DataSessionAwareExtensions.cs
2.71875
3
namespace LightDataInterface.Core { public static class DataSessionAwareExtensions { /// <summary> /// Retrieve the <see cref="IDataSession"/> from the <see cref="IDataSessionAware"/>. /// </summary> /// <param name="dataSessionAware"></param> /// <returns></returns> public static IDataSession GetDataSession(this IDataSessionAware dataSessionAware) { var dataSession = DataSession.Current(dataSessionAware.DataName); return dataSession; } } }
6444452b724d681e9572481242dab32a887f9296
C#
lakhtak/WalrusEnglish
/WalrusEnglish/NewGameDialog.cs
2.65625
3
using System; using System.Linq; using System.Windows.Forms; using WalrusEngishLogic; namespace WalrusEnglishGui { public partial class NewGameDialog : Form { private int _playerOneAvatarNumber = 1; private int _playerTwoAvatarNumber = 1; public NewGameDialog() { InitializeComponent(); Shown += InitializeControls; } private void InitializeControls(object sender, EventArgs e) { FillFailsToLose(); FillPointsToWin(); FillPlayerNames(); FillPlayerAvatars(); FillDictionaries(); } private void FillPlayerAvatars() { _playerOneAvatarNumber = Game.PlayerOne == null ? 1 : Game.PlayerOne.Avatar; pictureBoxPlayer1.Image = AvatarManager.GetAvatarByNumber(_playerOneAvatarNumber); _playerTwoAvatarNumber = Game.PlayerTwo == null ? 1 : Game.PlayerTwo.Avatar; pictureBoxPlayer2.Image = AvatarManager.GetAvatarByNumber(_playerTwoAvatarNumber, flip: true); } private void FillDictionaries() { comboBoxDictionary.DataSource = TheDictionary.GetAvailableDictionaries(); if (Game.WordDictionary == null) return; comboBoxDictionary.Text = Game.WordDictionary.DictionaryFileName; if (Game.WordDictionary.EnglishRussian) radioEnglishRussian.Checked = true; else radioRussianEnglish.Checked = true; } private void FillPlayerNames() { if (Game.PlayerOne == null) return; textBoxPlayer1Name.Text = Game.PlayerOne.Name; if (Game.PlayerTwo != null) { radioTwoPlayers.Checked = true; textBoxPlayer2Name.Text = Game.PlayerTwo.Name; } else { radioTwoPlayers.Checked = false; } } private void FillPointsToWin() { radioPoints1.Text = Constants.PointsToWin[0] + " point(s)"; radioPoints2.Text = Constants.PointsToWin[1] + " point(s)"; radioPoints3.Text = Constants.PointsToWin[2] + " point(s)"; if (Game.PointsToWin == 0) return; for (var i = 0; i < Constants.PointsToWin.Count(); i++) { if (Constants.PointsToWin[i] != Game.PointsToWin) continue; panelPointsToWin.Controls.OfType<RadioButton>().First(radio => radio.TabIndex == i).Checked = true; } } private void FillFailsToLose() { radioFails1.Text = Constants.FailsCount[0] + " fail(s)"; radioFails2.Text = Constants.FailsCount[1] + " fail(s)"; radioFails3.Text = Constants.FailsCount[2] + " fail(s)"; if (Game.FailsToLose == 0) return; for (var i = 0; i < Constants.FailsCount.Count(); i++) { if (Constants.FailsCount[i] != Game.FailsToLose) continue; panelFailsToLose.Controls.OfType<RadioButton>().First(radio => radio.TabIndex == i).Checked = true; } } private void buttonCance_Click(object sender, EventArgs e) { Close(); } private void buttonOk_Click(object sender, EventArgs e) { if (!ValidateControls()) return; var playerOne = new Player(textBoxPlayer1Name.Text, _playerOneAvatarNumber); var playerTwo = radioTwoPlayers.Checked ? new Player(textBoxPlayer2Name.Text, _playerTwoAvatarNumber, lastChance: true) : null; Game.StartNew(playerOne, playerTwo, radioEnglishRussian.Checked, comboBoxDictionary.Text, ReadFailsToLose(), ReadPointsToWin()); Close(); Program.TheGameForm.SetStartMessage(); Program.TheGameForm.Redraw(); } private int ReadPointsToWin() { var pointsToWin = 0; foreach (var radioPointsToWin in panelPointsToWin.Controls.OfType<RadioButton>().Where(radioPointsToWin => radioPointsToWin.Checked)) { pointsToWin = Constants.PointsToWin[radioPointsToWin.TabIndex]; } if (pointsToWin == 0) throw new InvalidOperationException("pointsToWin = 0!"); return pointsToWin; } private int ReadFailsToLose() { var failsToLose = 0; foreach (var radioFailsToLose in panelFailsToLose.Controls.OfType<RadioButton>().Where(radioFailsToLose => radioFailsToLose.Checked)) { failsToLose = Constants.FailsCount[radioFailsToLose.TabIndex]; } if (failsToLose == 0) throw new InvalidOperationException("failsToLose = 0!"); return failsToLose; } private bool ValidateControls() { if (!string.IsNullOrWhiteSpace(textBoxPlayer1Name.Text)) return true; MessageBox.Show("Please enter the name of player one. Пожалуйста введите имя первого игрока.", "Error. Ошибка.", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return false; } private void radioOnePlayer_CheckedChanged(object sender, EventArgs e) { labelPlayerTwo.Visible = !radioOnePlayer.Checked; textBoxPlayer2Name.Visible = !radioOnePlayer.Checked; pictureBoxPlayer2.Visible = !radioOnePlayer.Checked; } private void pictureBoxPlayer1_Click(object sender, EventArgs e) { pictureBoxPlayer1.Image = AvatarManager.GetNextAvatar(ref _playerOneAvatarNumber); } private void pictureBoxPlayer2_Click(object sender, EventArgs e) { pictureBoxPlayer2.Image = AvatarManager.GetNextAvatar(ref _playerTwoAvatarNumber, flip: true); } } }
da64f3afb9a9026cae2077a19fff40393e2b1689
C#
csetep/damil84
/week-04/day-1/Exercise_Farm/Program.cs
2.984375
3
using System; using System.Collections.Generic; using System.Text; using System.Linq; using System.Threading.Tasks; namespace Exercise_Farm { class Program { static void Main(string[] args) { var Animals = new Animals(); var dog = new Animals(); var cow = new Animals(); var chicken = new Animals(); var pig = new Animals(); var cat = new Animals(); var farm = new Farm(new List<Animals>() { dog, cow, chicken, pig, cat }, 5); Console.WriteLine("Dog hunger value is: " + dog.HungerValue + " shit"); dog.Eat(); cow.Eat(); Console.WriteLine("Dog hunger value is: " + dog.HungerValue + " shit"); Console.ReadLine(); //farm = new Farm(new List<Farm>() } } }
066263c2cb7f2d71d4e6a07c6ee43300a69df2b4
C#
kuangwei8/ExercsimPractice
/csharp/scrabble-score/ScrabbleScore.cs
3.40625
3
using System; using System.Collections.Generic; using System.Linq; public static class ScrabbleScore { enum Alphabets { AEIOULNRST = 1, DG = 2, BCMP = 3, FHVWY =4, K =5, JX =8, QZ=10 } public static int Score(string input) { string inputUpper = input.ToUpper(); int sum = 0; foreach(char c in inputUpper) { foreach (string item in Enum.GetNames(typeof(Alphabets))) { if (item.Contains(c)) { Enum.TryParse(item, out Alphabets myValue); sum += (int)myValue; } } } return sum; //List<int> sumIndex = new List<int>(); //string[] alphabets = new string[] //{ // "0", // "AEIOULNRST", // "DG", // "BCMP", // "FHVWY", // "K", // "0", // "0", // "JX", // "0", // "QZ" //}; //string inputUpper = input.ToUpper(); //foreach(char c in inputUpper ) //{ // for (int i = 0; i < alphabets.Length; i++) // { // if(alphabets[i].Contains(c)) // { // sumIndex.Add(i); // } // } //} //return sumIndex.Sum(); } }
ba885e789e3925a2590e7a5f71a8cee89cc51fbb
C#
edsaedi/Self-Balancing-Trees
/Self-Balancing Trees/AVL_With_Parents/AVLTree.cs
3.421875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AVL_With_Parents { public class AVLNode<T> { public T Value; public AVLNode<T> Parent; public AVLNode<T> Right; public AVLNode<T> Left; public int Height; public int Balance { get { int right = Right == null ? 0 : Right.Height; int left = Left == null ? 0 : Left.Height; return right - left; } } public bool IsLeftChild { get { if (Parent != null && Parent.Left == this) { return true; } return false; } } public bool IsRightChild { get { if (Parent != null && Parent.Right == this) { return true; } return false; } } public int ChildCount { get { int count = 0; if (Left != null) { count++; } if (Right != null) { count++; } return count; } } public AVLNode<T> First { get { if (Left != null) return Left; if (Right != null) return Right; return null; } } public AVLNode(T value) { Value = value; Height = 1; } public AVLNode(T value, AVLNode<T> parent) { Value = value; Parent = parent; Height = 1; } } public class AVLTree<T> where T : IComparable<T> { public int Count { get; private set; } public AVLNode<T> root; public AVLTree() { Count = 0; root = null; } public bool IsEmpty() { if (root != null) { return true; } return false; } public AVLNode<T> Find(T value) { AVLNode<T> curr = root; while (curr != null) { if (curr.Value.CompareTo(value) == 0) { return curr; } else if (value.CompareTo(curr.Value) < 0) { curr = curr.Left; } else if (value.CompareTo(curr.Value) > 0) { curr = curr.Right; } } return null; } public bool Contains(T value) { if (Find(value) != null) { return true; } return false; } public void Clear() { Count = 0; root = null; } public AVLNode<T> Minimum(AVLNode<T> curr) { while (curr.Left != null) { curr = curr.Left; } return curr; } public AVLNode<T> Maximum(AVLNode<T> curr) { while (curr.Right != null) { curr = curr.Right; } return curr; } public void RotateLeft(AVLNode<T> node) { var parent = node.Parent; var pivot = node.Right; var child = pivot.Left; if (node.IsLeftChild) { parent.Left = pivot; } else if (node.IsRightChild) { parent.Right = pivot; } else { root = pivot; } pivot.Left = node; pivot.Parent = parent; node.Parent = pivot; node.Right = child; if (child != null) { child.Parent = node; } UpdateHeight(node); UpdateHeight(pivot); } public void RotateRight(AVLNode<T> node) { var parent = node.Parent; var pivot = node.Left; var child = pivot.Right; //Fix Parent if (node.IsLeftChild) { parent.Left = pivot; } else if (node.IsRightChild) { parent.Right = pivot; } else { root = pivot; } //Rotate pivot.Right = node; pivot.Parent = parent; node.Parent = pivot; //Pass Child node.Left = child; if (child != null) { child.Parent = node; } UpdateHeight(node); UpdateHeight(pivot); } public void Add(T value) { Count++; if (root == null) { root = new AVLNode<T>(value); return; } var curr = root; while (curr != null) { if (value.CompareTo(curr.Value) < 0) { if (curr.Left == null) { //add the new child curr.Left = new AVLNode<T>(value, curr); break; } curr = curr.Left; } else if (value.CompareTo(curr.Value) > 0) { if (curr.Right == null) { curr.Right = new AVLNode<T>(value, curr); break; } curr = curr.Right; } else { throw new ArgumentException("No duplicate values allowed"); } } Fixup(curr); } public bool Remove(T value) { var toRemove = Find(value); if (toRemove == null) { return false; } Remove(toRemove); Count--; return true; } private void Remove(AVLNode<T> del) { if (del.ChildCount == 0) { if (del.IsLeftChild) { del.Parent.Left = null; } else if (del.IsRightChild) { del.Parent.Right = null; } else { root = null; } Fixup(del.Parent); } else if (del.ChildCount == 1) { if (del.IsLeftChild) { del.Parent.Left = del.First; del.First.Parent = del.Parent; } else if (del.IsRightChild) { del.Parent.Right = del.First; del.First.Parent = del.Parent; } else { root = del.First; root.Parent = null; } Fixup(del.Parent); } else if (del.ChildCount == 2) { AVLNode<T> curr = Maximum(del.Left); del.Value = curr.Value; Remove(curr); } } private void Fixup(AVLNode<T> node) { if (node == null) { return; } UpdateHeight(node); if (node.Balance > 1) //right heavy { if (node.Right.Balance < 0) //weight on right { RotateRight(node.Right); } RotateLeft(node); } else if (node.Balance < -1) //left heavy { if (node.Left.Balance > 0) //weight on left { RotateLeft(node.Left); } RotateRight(node); } Fixup(node.Parent); } private void UpdateHeight(AVLNode<T> node) { //Update Height int left = node.Left == null ? 0 : node.Left.Height; int right = node.Right == null ? 0 : node.Right.Height; node.Height = Math.Max(left, right) + 1; } } }
38e78ceda5e3dfb53bb3c33007cc7aa5a98f4b40
C#
vag1830/clean-code-paella
/UnitTests/ProductTests/GetAllUseCaseTests.cs
2.65625
3
using System.Collections.Generic; using FluentAssertions; using Moq; using Paella.Application.Persistence; using Paella.Application.ProductUseCases.GetAll; using Paella.Domain.Entities; using Xunit; namespace UnitTests.ProductTests { public class GetAllUseCaseTests { [Fact] public void NoProductsAvailable_ShouldReturnEmptyList() { // Arrange var repository = GetEmptyProductRepository(); var sut = new GetAllUseCase(repository); // Act var actual = sut.Execute(); // Assert actual .Should() .BeEmpty(); } [Fact] public void ProductsAvailable_ShouldReturnAListOfProducts() { // Arrange var repository = GetProductRepository(); var sut = new GetAllUseCase(repository); // Act var actual = sut.Execute(); // Assert actual .Should() .NotBeEmpty(); actual.Count .Should() .Be(1); } private IProductRepository GetEmptyProductRepository() { var repository = new Mock<IProductRepository>(); repository .Setup(r => r.GetAll()) .Returns(new List<Product>()); return repository.Object; } private IProductRepository GetProductRepository() { var repository = new Mock<IProductRepository>(); var products = new List<Product> { new Product("Name", "Description") }; repository .Setup(r => r.GetAll()) .Returns(products); return repository.Object; } } }
3726b4bbbad27213f6f589bb195d084017d9bfb7
C#
Knist-Larsen/Trekantsruten
/Rejsen_Pa_Trekantsruten/Assets/Scripts/ShipPlayer.cs
2.8125
3
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ShipPlayer : MonoBehaviour { //string som fra start at srger for at der ikke er et baneskift igang private string baneSkift = "n"; public GameObject obj; Vector3 startPos; public float height; // Start is called before the first frame update void Start() { // Start posistionen p det objekt som scribtet ligger p bliveer brugt som position startPos = transform.position; // Kompunentet rigidbody bruges til at fortlle hvor hurtigt spilleren bevger sig GetComponent<Rigidbody>().velocity = new Vector3(0,0, 2); } // Her styres venste knap public void Left() { // tjekker et baneskift allerede er igang og positionen af spilleren for at se om spilleren kan bevge sig til venstre if ((baneSkift == "n") && (transform.position.x > -.9)) { // Rykker spilleren en til venstre p banen GetComponent<Rigidbody>().velocity = new Vector3(-1, 0, 2); // ndre stringen baneskift til at vre igang s man ikke kan lave et banskift samtidig med at man er igang med det baneSkift = "y"; StartCoroutine(StopLaneCh()); } } // Her styres hjre knap public void Right() { // tjekker et baneskift allerede er igang og positionen af spilleren for at se om spilleren kan bevge sig til hjre if ((baneSkift == "n") && (transform.position.x < .9)) { // Rykker spilleren en til hjre p banen GetComponent<Rigidbody>().velocity = new Vector3(1, 0, 2); // ndre stringen baneskift til at vre igang s man ikke kan lave et banskift samtidig med at man er igang med det baneSkift = "y"; StartCoroutine(StopLaneCh()); } } // Update is called once per frame void Update() { transform.position = new Vector3(transform.position.x, height, transform.position.z); } // IEnumerator srger for at der skal vre en pause p 1 sekund mellem baneskiftene, men ikke mere hvis der bliver trykket mange gange i trk p en knap IEnumerator StopLaneCh() { yield return new WaitForSeconds(1); GetComponent<Rigidbody>().velocity = new Vector3(0, 0, 2); baneSkift = "n"; } // Funktionen tjekker om spilleren rammer en af forhindringerne. Hvis man gr aktivere den funktionen EndGame i GameManagerShip scriptet private void OnTriggerEnter(Collider other) { if (other.tag == "Obstacle") { FindObjectOfType<GameManagerShip>().EndGame(); } } }
200d81b60ab4d61014605d491101c220f637a982
C#
rodrigosousa1/rest-aspnetcore-lab
/RestAspNetCoreLab/RestAspNetCoreLab/Repository/Generic/GenericRepository.cs
2.90625
3
using Microsoft.EntityFrameworkCore; using RestAspNetCoreLab.Model.Base; using RestAspNetCoreLab.Model.Context; using System; using System.Collections.Generic; using System.Linq; namespace RestAspNetCoreLab.Repository.Generic { public class GenericRepository<T> : IRepository<T> where T : BaseEntity { private readonly PgSQLContext _context; private DbSet<T> dbSet; public GenericRepository(PgSQLContext context) { _context = context; dbSet = context.Set<T>(); } public T Create(T entity) { try { dbSet.Add(entity); _context.SaveChanges(); } catch (Exception ex) { throw ex; } return entity; } public void Delete(int id) { var entity = dbSet.AsNoTracking().SingleOrDefault(e => e.Id == id); try { if (entity != null) dbSet.Remove(entity); _context.SaveChanges(); } catch (Exception) { throw; } } public List<T> FindAll() { return dbSet.AsNoTracking().ToList(); } public T FindById(int id) { return dbSet.AsNoTracking().SingleOrDefault(e => e.Id == id); } public T Update(T entity) { var entityDb = dbSet.AsNoTracking().SingleOrDefault(e => e.Id == entity.Id); if (entityDb == null) return null; try { _context.Entry(entityDb).CurrentValues.SetValues(entity); _context.SaveChanges(); } catch (Exception ex) { throw; } return entity; } } }
37985b6e704d386b5d4beeeead567026b38a2af5
C#
MishoMihaylov/SoftUni-Projects
/Homemade/Homemade.Services/Models/ShoppingCartService.cs
2.59375
3
namespace Homemade.Services.Models { using System.Linq; using Homemade.Models.EntityModels; using Homemade.Services.Contracts; public class ShoppingCartService : BaseService, IShoppingCartService { public void AddOrUpdate(ShoppingCart shoppingCart) { this.UnitOfWork.ShoppingCarts.AddOrUpdate(shoppingCart); this.UnitOfWork.Commit(); } public ShoppingCart GetByUser(string username) { return this.UnitOfWork.ShoppingCarts.FindBy(sc => sc.Owner.UserName == username).Single(); } public void AddProduct(ShoppingCart shoppingCart, CartProduct product) { if(product.Product == null) { product.Product = this.UnitOfWork.Products.FindById(product.ProductId); } this.UnitOfWork.ShoppingCarts.FindBy(cart => cart.Id == shoppingCart.Id).Single().Items.Add(product); this.UnitOfWork.ShoppingCarts.AddOrUpdate(shoppingCart); this.UnitOfWork.Commit(); } public void DeleteProduct(ShoppingCart shoppingCart, int productId) { var item = shoppingCart.Items.Where(i => i.Id == productId).Single(); shoppingCart.Items.Remove(item); this.UnitOfWork.ShoppingCarts.AddOrUpdate(shoppingCart); this.UnitOfWork.Commit(); } public void Clear(ShoppingCart shoppingCart) { shoppingCart.Items.Clear(); this.UnitOfWork.ShoppingCarts.AddOrUpdate(shoppingCart); this.UnitOfWork.Commit(); } } }
9a08f741853eeb8ea1a4dcc5a409920798149621
C#
TeodorKostadinov/TelerikCSharp6
/CalculateVariations/CalculateVariations.cs
3.4375
3
using System; class CalculateVariations { static void Main(string[] args) { Console.Write("Enter N= "); int n = int.Parse(Console.ReadLine()); Console.Write("Enter K= "); int k = int.Parse(Console.ReadLine()); int nFactor = 1; for (int i = k+1; i <= n; i++) { nFactor = nFactor * i; } Console.WriteLine("N!/K! is {0}",nFactor); } }
d2444c304fb57a52112ef4f7fd5f9713f2f94d05
C#
caok168/Cit_Library
/AdvancedCalculation/WaveFormProcess.cs
2.515625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using MathWorks.MATLAB.NET.Arrays; using DataProcessAdvance; using System.IO; namespace AdvancedCalculation { public class WaveFormProcess { //DataProcessAdvanceClass ppmc; public WaveFormProcess() { //ppmc = new DataProcessAdvanceClass(); } /// <summary> /// 波形变化识别 /// </summary> /// <param name="channelName">通道名称</param> /// <param name="mileData1">第一组里程</param> /// <param name="channelData1">第一组几何不平顺</param> /// <param name="speedData1">第一组速度</param> /// <param name="gaugeData1">第一组轨距</param> /// <param name="mileData2">第二组里程</param> /// <param name="channelData2">第二组几何不平顺</param> /// <param name="speedData2">第二组速度</param> /// <param name="gaugeData2">第二组轨距</param> public List<Result> WaveformChangeRecognition(string channelName, double[] mileData1, double[] channelData1, double[] speedData1, double[] gaugeData1, double[] mileData2, double[] channelData2, double[] speedData2, double[] gaugeData2) { List<Result> dataList = new List<Result>(); try { int oneTimeLength = 600000; //一次处理的点数,150公里 int len1 = Math.Min(mileData1.Length, channelData1.Length); int len2 = Math.Min(mileData2.Length, channelData2.Length); int len = Math.Min(len1, len2); for (int i = 0; i < len; i += oneTimeLength) { int remain = 0; int index = (i / oneTimeLength) * oneTimeLength; remain = len - oneTimeLength * (i / oneTimeLength + 1); int ThisTimeLength = remain > 0 ? oneTimeLength : (remain += oneTimeLength); double[] tmp_tt_1 = new double[ThisTimeLength]; double[] tmp_wx_1 = new double[ThisTimeLength]; double[] tmp_wvelo_1 = new double[ThisTimeLength]; double[] tmp_wx_gauge_1 = new double[ThisTimeLength]; double[] tmp_tt_2 = new double[ThisTimeLength]; double[] tmp_wx_2 = new double[ThisTimeLength]; double[] tmp_wvelo_2 = new double[ThisTimeLength]; double[] tmp_wx_gauge_2 = new double[ThisTimeLength]; for (int j = 0; j < ThisTimeLength; j++) { tmp_tt_1[j] = mileData1[index + j]; tmp_wx_1[j] = channelData1[index + j]; tmp_wvelo_1[j] = speedData1[index + j]; tmp_wx_gauge_1[j] = gaugeData1[index + j]; tmp_tt_2[j] = mileData2[index + j]; tmp_wx_2[j] = channelData2[index + j]; tmp_wvelo_2[j] = speedData2[index + j]; tmp_wx_gauge_2[j] = gaugeData2[index + j]; } MWNumericArray d_tt_1 = new MWNumericArray(tmp_tt_1); MWNumericArray d_wx_1 = new MWNumericArray(tmp_wx_1); MWNumericArray d_wvelo_1 = new MWNumericArray(tmp_wvelo_1); MWNumericArray d_wv_gauge_1 = new MWNumericArray(tmp_wx_gauge_1); MWNumericArray d_tt_2 = new MWNumericArray(tmp_tt_2); MWNumericArray d_wx_2 = new MWNumericArray(tmp_wx_2); MWNumericArray d_wvelo_2 = new MWNumericArray(tmp_wvelo_2); MWNumericArray d_wv_gauge_2 = new MWNumericArray(tmp_wx_gauge_2); DataProcessAdvanceClass ppmc = new DataProcessAdvanceClass(); //调用算法 MWNumericArray resultArrayAB = (MWNumericArray)ppmc.sub_abrupt_change_detection(d_tt_1, d_wx_1, d_wvelo_1, d_wv_gauge_1, d_tt_2, d_wx_2, d_wvelo_2, d_wv_gauge_2); double[,] tmpArray = (double[,])resultArrayAB.ToArray(); for (int j = 0; j < tmpArray.GetLength(0); j++) { tmpArray[j, 0] = tmp_tt_2[(long)(tmpArray[j, 0])]; tmpArray[j, 1] = tmp_tt_2[(long)(tmpArray[j, 1])]; //dataStr = String.Format("{0},{1},{2},{3}", channelName, tmpArray[j, 0], tmpArray[j, 1], tmpArray[j, 2]); Result result = new Result(); result.channelname = channelName; result.startpos = tmpArray[j, 0]; result.endpos = tmpArray[j, 1]; result.absvalue = tmpArray[j, 2]; dataList.Add(result); } } } catch (System.Exception ex) { throw new Exception(ex.Message); } return dataList; } /// <summary> /// 峰峰值偏差 /// </summary> /// <param name="channelName">通道名称</param> /// <param name="milesData">里程</param> /// <param name="channelData">具体通道的数据</param> /// <param name="speedData">速度</param> /// <param name="gaugeData">轨距</param> /// <param name="thresh_gauge">峰峰值的阈值,取8.0</param> public List<Result> WaveformPeakDeviation(string channelName, double[] milesData, double[] channelData, double[] speedData, double[] gaugeData, double thresh_gauge=8.0) { List<Result> dataList = new List<Result>(); try { int oneTimeLength = 1000000; //一次处理的点数 for (int i = 0; i < milesData.Length; i += oneTimeLength) { int remain = 0; int index = (i / oneTimeLength) * oneTimeLength; remain = milesData.Length - oneTimeLength * (i / oneTimeLength + 1); int ThisTimeLength = remain > 0 ? oneTimeLength : (remain += oneTimeLength); double[] tmp_tt = new double[ThisTimeLength]; double[] tmp_wx = new double[ThisTimeLength]; double[] tmp_wvelo = new double[ThisTimeLength]; double[] tmp_wx_gauge = new double[ThisTimeLength]; for (int j = 0; j < ThisTimeLength; j++) { tmp_tt[j] = milesData[index + j]; tmp_wx[j] = channelData[index + j]; tmp_wvelo[j] = speedData[index + j]; tmp_wx_gauge[j] = gaugeData[index + j]; } MWNumericArray d_tt = new MWNumericArray(tmp_tt); MWNumericArray d_wx = new MWNumericArray(tmp_wx); MWNumericArray d_wvelo = new MWNumericArray(tmp_wvelo); MWNumericArray d_wx_gauge = new MWNumericArray(tmp_wx_gauge); MWNumericArray d_thresh_gauge = new MWNumericArray(thresh_gauge); DataProcessAdvanceClass ppmc = new DataProcessAdvanceClass(); //调用算法 MWNumericArray resultArrayAB = (MWNumericArray)ppmc.sub_preprocessing_deviation_by_p2p(d_tt, d_wx, d_wvelo, d_wx_gauge, d_thresh_gauge); double[,] tmpArray = (double[,])resultArrayAB.ToArray(); for (int j = 0; j < tmpArray.GetLength(0); j++) { tmpArray[j, 0] = tmp_tt[(long)(tmpArray[j, 0])]; tmpArray[j, 1] = tmp_tt[(long)(tmpArray[j, 1])]; //dataStr = String.Format("{0},{1},{2},{3}", channelName, tmpArray[j, 0], tmpArray[j, 1], tmpArray[j, 2]); Result result = new Result(); result.channelname = channelName; result.startpos = tmpArray[j, 0]; result.endpos = tmpArray[j, 1]; result.absvalue = tmpArray[j, 2]; dataList.Add(result); } } } catch (Exception ex) { throw new Exception(ex.Message); } return dataList; } /// <summary> /// 保存到txt文件 /// </summary> /// <param name="filePathTxt"></param> /// <param name="list"></param> public void SaveToTxt(string filePathTxt,List<Result> list) { try { StreamWriter sw = new StreamWriter(filePathTxt); for (int i = 0; i < list.Count; i++) { string strText = "通道名称:" + list[i].channelname + "," + "起点位置:" + list[i].startpos + ",终点位置:" + list[i].endpos + ",绝对值差:" + list[i].absvalue; sw.WriteLine(strText); } sw.Close(); } catch (Exception ex) { throw new Exception(ex.Message); } } } }
1c2254a81948a21265e044630dbf69a6d6cd4895
C#
chmitkov/SoftUni
/C#/TrainingLab/Program.cs
3
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TrainingLab { class Program { static void Main(string[] args) { var w = double.Parse(Console.ReadLine()); var h = double.Parse(Console.ReadLine()); w = (int)((w * 100) / 120); h = (h * 100) - 100; h = (int)h / 70; var all = (w * h) - 3; Console.WriteLine(all); } } }
4c1f98e388d4b99cbf9f951825f9c438a71211eb
C#
hasankhan/DraggerGame
/MapInverter/Player.cs
3.265625
3
using System; using System.Collections.Generic; using System.Text; using System.Drawing; namespace Dragger { enum Direction { UP, Down, Left, Right, Unknown } class Player { Point location; Map map; readonly Point defaultLocation; public Player(Map map, Point location) { this.map = map; this.defaultLocation = this.location = location; } public Point Location { get { return location; } private set { location = value; } } public void Reset() { this.location = defaultLocation; } public bool Move(Direction towards) { if (towards == Direction.Unknown) return false; Point disp = GetDisplacement(towards); Point dest = Location, dest2 = Location; dest.Offset(disp); disp.X *= 2; disp.Y *= 2; dest2.Offset(disp); if (map[dest] == MapCell.Wall || map[dest] == MapCell.Illegal) return false; if (map.IsFree(dest)) { Location = dest; return true; } if (map.IsFree(dest2) && map.IsMovable(dest)) { map.MoveObject(dest, dest2); Location = dest; return true; } return false; } private Point GetDisplacement(Direction towards) { Point displacement; switch (towards) { case Direction.UP: displacement = new Point(0, -1); break; case Direction.Down: displacement = new Point(0, 1); break; case Direction.Left: displacement = new Point(-1, 0); break; default:// Direction.Right: displacement = new Point(1, 0); break; } return displacement; } } }
1e78cfb3166a2366c4d9a66d3fe46996e9ab33a2
C#
jamunabalamurugan/CTSDN016
/C#_Day5/PropertyEg/PropertyEg/Employee.cs
3.515625
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PropertyEg { class Employee { private int eno;//Private member variable public Employee() { eno = 100; } public int GetEmpNo() { return eno; } public int EmployeeNo //property definition { get { return eno; } //accessor // set { eno = value; } //Mutator set { if (value > 100 ) { eno = 0; Console.WriteLine("Employee No should be in the range 0-100 only"); } else { eno = value; } }//Mutator } } }
ecdf6ee9549e2b652bc8f07e78862963ddc2e587
C#
nagyist/HealthTracker-1
/HealthTracker.Infrastructure/UndoRedoManager.cs
2.9375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using HealthTracker.Infrastructure.Interfaces; namespace HealthTracker.Infrastructure { public class UndoRedoManager { #region Constructors public UndoRedoManager() { _undoItems = new Stack<IUndoRedo>(); _redoItems = new Stack<IUndoRedo>(); IsPerformingUndoOrRedo = false; } #endregion #region Public Interface public void Add<T>( T propertyUndoValue ) where T : IUndoRedo { _undoItems.Push( propertyUndoValue ); } public Boolean IsPerformingUndoOrRedo { get; private set; } public void Undo() { IUndoRedo undoItem; IsPerformingUndoOrRedo = true; if (CanUndo) { undoItem = _undoItems.Pop(); undoItem.Undo(); _redoItems.Push( undoItem ); } IsPerformingUndoOrRedo = false; } public Boolean CanUndo { get { return (_undoItems.Count > 0); } } public void Redo() { IUndoRedo redoItem; IsPerformingUndoOrRedo = true; if (CanRedo) { redoItem = _redoItems.Pop(); redoItem.Redo(); _undoItems.Push( redoItem ); } IsPerformingUndoOrRedo = false; } public Boolean CanRedo { get { return (_redoItems.Count > 0); } } #endregion #region Private Data private Stack<IUndoRedo> _undoItems; private Stack<IUndoRedo> _redoItems; #endregion } }
3d56a772e91dd7da843cd9711c9488c7ab6b25a4
C#
Deven-D07/CS_Chapter2
/CS_Chapter2/Room/Program.cs
3.203125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Room { class Program { static void Main(string[] args) { int length = 15; int width = 25; Console.WriteLine("The floor space is:"); Console.WriteLine(length * width); } } }
01d83291441350a79957d5d893e3cb6f3ec35dab
C#
Karlashenko/dark-bestiary
/Values/Damage.cs
2.734375
3
using DarkBestiary.Skills; using UnityEngine; namespace DarkBestiary.Values { public struct Damage { public float Amount { get; set; } public float Absorbed { get; set; } public DamageType Type { get; set; } public DamageFlags Flags { get; set; } public DamageInfoFlags InfoFlags { get; set; } public WeaponSound WeaponSound { get; set; } public Skill Skill { get; set; } public Damage(float amount, DamageType type, WeaponSound weaponSound, DamageFlags flags, DamageInfoFlags infoFlags, Skill skill) { Amount = amount; Type = type; WeaponSound = weaponSound; Flags = flags; InfoFlags = infoFlags; Absorbed = 0; Skill = skill; } public bool IsWeapon() { return Flags.HasFlag(DamageFlags.Melee) || Flags.HasFlag(DamageFlags.Ranged); } public bool IsMagic() { return Flags.HasFlag(DamageFlags.Magic); } public bool IsTrue() { return Flags.HasFlag(DamageFlags.True); } public bool IsPhysicalType() { return Type == DamageType.Crushing || Type == DamageType.Slashing || Type == DamageType.Piercing; } public bool IsMagicalType() { return Type == DamageType.Fire || Type == DamageType.Cold || Type == DamageType.Holy || Type == DamageType.Shadow || Type == DamageType.Arcane || Type == DamageType.Lightning || Type == DamageType.Poison; } public bool IsDOT() { return Flags.HasFlag(DamageFlags.DOT); } public bool IsReflected() { return InfoFlags.HasFlag(DamageInfoFlags.Reflected); } public bool IsThorns() { return InfoFlags.HasFlag(DamageInfoFlags.Thorns); } public bool IsCleave() { return InfoFlags.HasFlag(DamageInfoFlags.Cleave); } public bool IsCritical() { return InfoFlags.HasFlag(DamageInfoFlags.Critical); } public bool IsSpiritLink() { return InfoFlags.HasFlag(DamageInfoFlags.SpiritLink); } public bool IsInvulnerable() { return InfoFlags.HasFlag(DamageInfoFlags.Invulnerable); } public bool IsDodged() { return InfoFlags.HasFlag(DamageInfoFlags.Dodged); } public bool IsBlocked() { return InfoFlags.HasFlag(DamageInfoFlags.Blocked); } public bool IsBlockedOrDodged() { return IsBlocked() || IsDodged(); } public static Damage operator +(Damage damage, float amount) { return new Damage(damage.Amount + amount, damage.Type, damage.WeaponSound, damage.Flags, damage.InfoFlags, damage.Skill); } public static Damage operator -(Damage damage, float amount) { return new Damage( Mathf.Max(0, damage.Amount - amount), damage.Type, damage.WeaponSound, damage.Flags, damage.InfoFlags, damage.Skill); } public static Damage operator *(Damage damage, float amount) { return new Damage(damage.Amount * amount, damage.Type, damage.WeaponSound, damage.Flags, damage.InfoFlags, damage.Skill); } public static Damage operator /(Damage damage, float amount) { return new Damage(damage.Amount / amount, damage.Type, damage.WeaponSound, damage.Flags, damage.InfoFlags, damage.Skill); } public static implicit operator float(Damage damage) { return damage.Amount; } } }
9b1e7f97ab6f234a3440728c109d57fae601f3fe
C#
hteinlinaung1423/Security
/AddCredits.aspx.cs
2.59375
3
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class AddCredits : System.Web.UI.Page { string USER_TEMP = "nyan"; protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { string credits; using (GreatBooksDBEntities context = new GreatBooksDBEntities()) { credits = context.Customers.Where(x => x.CustomerUserName == USER_TEMP).First().CreditAmount.ToString(); } Label_Credits.Text = "$" + credits; } } protected void Button_AddCredits_Click(object sender, EventArgs e) { int creditsToAdd = Convert.ToInt32(TextBox_CreditsToAdd.Text); string newCredits = ""; using (GreatBooksDBEntities context = new GreatBooksDBEntities()) { Customer cust = context.Customers.Where(x => x.CustomerUserName == USER_TEMP).First(); cust.CreditAmount = cust.CreditAmount + creditsToAdd; newCredits = cust.CreditAmount.ToString(); context.SaveChanges(); } Label_Credits.Text = "$" + newCredits; TextBox_CreditsToAdd.Text = ""; } }
e77b83af1e95238d6db34da4e74a9b911149494b
C#
VermassenJonas/SBU_Backend
/SBU_API/Models/Monster.cs
2.59375
3
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace SBU_API.Models { public class Monster { public int Id { get; set; } public String Name { get; set; } public String Size { get; set; } public String MonsterType { get; set; } public List<String> Languages { get; set; } public List<String> Tags { get; set; } public String Alignment { get; set; } public int ArmourClass { get; set; } public String ArmourType { get; set; } public int Hitpoints { get; set; } public String HpFormula { get; set; } public Dictionary<String, int> Speed { get; set; } public Statline Stats { get; set; } public List<String> Resistances { get; set; } public List<String> Immunities { get; set; } public List<String> ConditionImmunities { get; set; } public List<String> Vulnerabilities { get; set; } public Dictionary<String, int> Skills { get; set; } public String ChallengeRating { get; set; } public List<Trait> Traits { get; set; } public List<Action> Actions { get; set; } public String Fluff { get; set; } public User Author { get; set; } public DateTime Created { get; set; } public DateTime LastUpdated { get; set; } // override object.Equals public override bool Equals(object obj) { // // See the full list of guidelines at // http://go.microsoft.com/fwlink/?LinkID=85237 // and also the guidance for operator== at // http://go.microsoft.com/fwlink/?LinkId=85238 // if (obj == null || GetType() != obj.GetType()) { return false; } return this.Id == ((Monster)obj).Id; } // override object.GetHashCode public override int GetHashCode() { // TODO: write your implementation of GetHashCode() here return Id; } } }
d690acd83378bd4b53eb041e44ae2e0c37ce9911
C#
vygantas-meskauskis/DesignPatternExamples
/Bridge/Program.cs
3.09375
3
using System; using System.Collections.Generic; using System.Runtime.Serialization; namespace Bridge { class Program { static void Main(string[] args) { var standartFormatter = new StandartFormatter(); var backwardsFormatter = new BackWardsFormatter(); var documents = new List<MenuScript>(); var book = new Book(standartFormatter); var paper = new Paper(backwardsFormatter); documents.Add(book); documents.Add(paper); foreach (var menuScript in documents) { menuScript.Print(); } } } public abstract class MenuScript { protected readonly IMenuFormatter Formatter; public MenuScript(IMenuFormatter formatter) { Formatter = formatter; } public abstract void Print(); } public class Paper : MenuScript { public string Title { get; set; } public Paper(IMenuFormatter backwardsFormatter) : base(backwardsFormatter) { Console.WriteLine(Title); } public override void Print() { Console.WriteLine(); } } public class Book : MenuScript { public string BookTitle { get; set; } public Book(IMenuFormatter standartFormatter) : base(standartFormatter) { } public override void Print() { Console.WriteLine(BookTitle); } } public class BackWardsFormatter : IMenuFormatter { } public class StandartFormatter : IMenuFormatter { } public interface IMenuFormatter { } }
416e3d63690d2c097344002727f223d4c6e3485d
C#
BogdanPinchuk/C_sharp_Essential-PBY_HW_AT11
/LesApp1/Class1.cs
2.859375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LesApp1 { class Class1 : IInt { /// <summary> /// Відобразити тип класу /// </summary> public void ShowClassType() { Console.WriteLine($"\n\tТип класу: {this.GetType().Name}"); } } }
81dc657c6756e09c8ed574b512fe264be815f6c2
C#
IstanbulBoy/gis-dij-proj
/gis1/gis/Projects/GiS/Backup/2/App_Code/TspAlgorithm.cs
3
3
using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Summary description for TspAlgorithms /// </summary> public class TspAlgorithm { const int INF = 2147483647; int bestResult = INF; int[] bestPath; int[] result; /// <summary> /// Zwraca wyniki dla wyliczenia wszystkich permutacji dla TSP grafu /// </summary> /// <param name="matrix">macierz sasiedztwa grafu</param> /// <param name="startNode">wierzcholek poczatkowy</param> /// <returns>Lista zawierajaca wyniki</returns> public List<object> GetPermutationAlg(int[,] matrix, int startNode) { result = new int[matrix.GetLength(1)]; bestPath = new int[matrix.GetLength(1)]; DateTime ExecutionStartTime; DateTime ExecutionStopTime; TimeSpan ExecutionTime; ExecutionStartTime = DateTime.Now; GetPermutation(matrix, startNode, 1); ExecutionStopTime = DateTime.Now; ExecutionTime = ExecutionStopTime.Subtract(ExecutionStartTime); List<object> results = new List<object>(); results.Add(bestResult); string bestPathString = ""; for (int i = 0; i < bestPath.Length; i++) { bestPathString += (bestPath[i]+1).ToString(); bestPathString += ","; } bestPathString += (bestPath[0]+1).ToString(); results.Add(bestPathString); results.Add(ExecutionTime.TotalSeconds.ToString() + " sec."); //nie znaleziono rozwiazania results.Add("noresult"); return results; } private void GetPermutation(int[,] matrix, int startNode, int level) { int nodesConut = matrix.GetLength(1); //startowy wierzcholek trafia od razu do wyniku if (level == 1) { result[0] = startNode; } if (level != nodesConut) { for (int i = 0; i < nodesConut; i++) { //sprawdza czy wierzcholek jest juz w permutacji bool isDuplicate = false; for (int j = 0; j < nodesConut - 1; j++) { if (result[j] == i) { isDuplicate = true; } } if (isDuplicate == false) { result[level] = i; //obliczylismy pierwsza pozycje permutacji //i nie mozemy jeszcze okreslic wagi krawedzi if (level == 0) { GetPermutation(matrix, 0, level + 1); } //mozemy juz okreslic wage krawedzi else if (matrix[result[level - 1], result[level]] != INF) { //nie okreslilismy jeszcze ostatniego wierzcholka if (level != nodesConut - 1) { GetPermutation(matrix, 0, level + 1); } //ostatni wierzcholek ma droge do startowego wierzcholka else if (level == nodesConut - 1 && matrix[result[level], result[0]] != INF) { GetPermutation(matrix, 0, level + 1); } } result[level] = -1; } } } //oblicz wartość permutacji else { int wynik = 0; for (int j = 0; j < nodesConut; j++) { if (j != 0) { wynik += matrix[result[j - 1], result[j]]; } } wynik += matrix[result[nodesConut - 1], result[0]]; if (wynik < bestResult) { bestResult = wynik; for (int r = 0; r < result.Length; r++) { bestPath[r] = result[r]; } } } } /// <summary> /// Zwraca wynik dla wyliczenia algorytmu zachlannego dla TSP grafu /// </summary> /// <param name="matrix">macierz sasiedztwa grafu</param> /// <param name="startNode">wierzcholek poczatkowy</param> /// <returns>Lista zawierajaca wyniki</returns> public List<object> GreedyAlg(int[,] matrix, int startNode) { bestPath = new int[matrix.GetLength(1)]; DateTime ExecutionStartTime; DateTime ExecutionStopTime; TimeSpan ExecutionTime; ExecutionStartTime = DateTime.Now; GreedyAlgorithm(matrix, startNode); ExecutionStopTime = DateTime.Now; ExecutionTime = ExecutionStopTime.Subtract(ExecutionStartTime); List<object> results = new List<object>(); results.Add(bestResult); string bestPathString = ""; for (int i = 0; i < bestPath.Length; i++) { bestPathString += (bestPath[i] + 1).ToString(); bestPathString += ","; } bestPathString += (bestPath[0] + 1).ToString(); results.Add(bestPathString); results.Add(ExecutionTime.TotalSeconds.ToString() + " sec."); return results; } private void GreedyAlgorithm(int[,] matrix, int startNode) { int nodesConut = matrix.GetLength(1); int currentNode = startNode; int shortestPath = INF; int closestNode = -1; List<int[]> wrongPath = new List<int[]>(); bool isWrongPath = true; int[] result; do { result = new int[nodesConut]; for (int i = 0; i < nodesConut; i++) { result[i] = -1; } result[0] = startNode; currentNode = startNode; bestResult = 0; for (int i = 0; i < nodesConut; i++) { //z ostatniego wierzcholka trzeba wrocic do pierwszego if (i == nodesConut - 1) { if (matrix[currentNode, startNode] != INF) { bestResult += matrix[currentNode, startNode]; isWrongPath = false; } else { wrongPath.Add(result); isWrongPath = true; } } else { shortestPath = INF; for (int j = 0; j < nodesConut; j++) { if (matrix[currentNode, j] < shortestPath) { bool isFree = true; //sprawdza czy wierzcholek nie byl juz odwiedzony for (int k = 0; k < nodesConut; k++) { if (result[k] == j) { isFree = false; } } //jesli nie byl to mozna go odwiedzic if (isFree == true) { result[i + 1] = j; //sprawdz czy proponowana sciezka nie jest na liscie zakazanej if (IsArrayInList(wrongPath, result) == false) { shortestPath = matrix[currentNode, j]; closestNode = j; } result[i + 1] = -1; } } } //nie dalo sie wygenerowac sciezki, proponowana droga trafia na liste zakazana if (closestNode == -1) { wrongPath.Add(result); //mozna przerwac i = nodesConut; } else { bestResult += matrix[currentNode, closestNode]; currentNode = closestNode; result[i + 1] = currentNode; closestNode = -1; Console.Write(currentNode); } } } } while (isWrongPath == true); for (int i = 0; i < nodesConut; i++) { bestPath[i] = result[i]; } } /// <summary> /// sprawdza czy w liscie zakazanej istnieje juz badana sciezka /// </summary> /// <param name="listOfArrays">lista drog zakazanych</param> /// <param name="array">badania droga</param> /// <returns>true jesli podana droga istnieje juz na liscie</returns> private bool IsArrayInList(List<int[]> listOfArrays, int[] array) { if (listOfArrays.Count == 0) { return false; } else { bool isCopy = false; for (int i = 0; i < listOfArrays.Count; i++) { isCopy = false; int[] tempArray = listOfArrays[i]; for (int j = 0; j < array.Count(); j++) { if (tempArray[j] != array[j]) { isCopy = false; //przerwij to sprawdzanie bo ciagi sa rozne j = array.Count(); } else { isCopy = true; } } if (isCopy == true) { return isCopy; } } return isCopy; } } }
5e35f1b3c18e68b4eeac748fae52cd053031351b
C#
GameDevProject-S20/Pre-Production
/4900Project/Assets/Scripts/Tooltip/Tooltip.cs
2.5625
3
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using TMPro; public class Tooltip : MonoBehaviour { private Component[] texts; public int rightClickStage = 0; void Awake() { gameObject.GetComponent<Image>().enabled = false; texts = GetComponentsInChildren<Text>(); foreach (Text tex in texts) { tex.gameObject.SetActive(false); } } public void GenerateTooltip(string title, string desc) { gameObject.GetComponent<Image>().enabled = true; gameObject.SetActive(true); texts = GetComponentsInChildren<Text>(true); foreach (Text tex in texts) { tex.gameObject.SetActive(true); } gameObject.transform.GetChild(0).GetComponent<Text>().text = title; gameObject.transform.GetChild(1).GetComponent<TextMeshProUGUI>().text = desc; } public void GenerateTooltip (Item item) { gameObject.GetComponent<Image>().enabled = true; gameObject.SetActive(true); texts = GetComponentsInChildren<Text>(true); foreach (Text tex in texts) { tex.gameObject.SetActive(true); } gameObject.transform.GetChild(0).GetComponent<Text>().text = item.DisplayName; gameObject.transform.GetChild(1).GetComponent<TextMeshProUGUI>().text = item.Tooltip + "\n \n Right Click for Details"; } public void GenerateDetailedTooltip(Item item) { gameObject.GetComponent<Image>().enabled = true; gameObject.SetActive(true); texts = GetComponentsInChildren<Text>(true); foreach (Text tex in texts) { tex.gameObject.SetActive(true); } gameObject.transform.GetChild(0).GetComponent<Text>().text = item.DisplayName; string descriptor = item.Description; // Only if in Inventory if (InventoryWindow.Instance){ if (this == InventoryWindow.Instance.tooltip && item.IsConsumable) { int health = item.GetHealthCured(); int maxhealth = item.GetMaxHealthGiven(); if(maxhealth!=0) { descriptor += $"\n\nGrants {maxhealth} additional max health"; } else if(health!=0) { descriptor += $"\n\nRestores {health} health"; } descriptor += "\n\n<color=#CB0A00>Right click to consume</color>"; } } descriptor += "\n\nWeight per Unit:" + item.Weight.ToString() + "\n \n"; string tagList = ""; string iconList = ""; foreach (ItemTag tag in item.tags) { tagList += tag.ToString() + ", "; switch (tag) { case ItemTag.None: break; case ItemTag.General: iconList += makeIcon(3); break; case ItemTag.Fuel: iconList += makeIcon(2); break; case ItemTag.Useable: iconList += makeIcon(10); break; case ItemTag.Food: iconList += makeIcon(1); break; case ItemTag.Luxury: iconList += makeIcon(4); break; case ItemTag.Medical: iconList += makeIcon(5); break; case ItemTag.Building_Materials: iconList += makeIcon(13); break; case ItemTag.Tools_And_Parts: iconList += makeIcon(8); break; case ItemTag.Combat: iconList += makeIcon(14); break; case ItemTag.Scientific: iconList += makeIcon(7); break; case ItemTag.Mineral: iconList += makeIcon(6); break; case ItemTag.Antique: iconList += makeIcon(12); break; case ItemTag.Advanced: iconList += makeIcon(11); break; } iconList += " "; } tagList = tagList.Substring(0, tagList.Length - 2); tagList = tagList.Replace("_"," "); iconList = iconList.Substring(0, iconList.Length - 2); gameObject.transform.GetChild(1).GetComponent<TextMeshProUGUI>().text = descriptor + tagList + "\n" + iconList; } public string makeIcon(int a) { string temp = "<sprite=" + a + ">"; return temp; } }
292bd87cac117605e003b5cfb132d2083834ae9e
C#
jimmygogo/jimmygogo.github.io
/fruitmail/fruitmail/App_Code/FruitServ.cs
2.71875
3
using System; using System.Collections.Generic; using System.Linq; using System.Web; public class FruitServ { List<Fruit> fruitList; List<Category> categories; int pageNum = 1; public FruitServ() { fruitList = GetAllFruits(); categories = GetAllCategories(); } private List<Category> GetAllCategories() { Category[] res = { new Category(0, "全部"), new Category(1, "瓜果类"), new Category(2, "柑桔类"), new Category(3, "热带水果类"), new Category(4, "核果类"), new Category(5, "浆果类"), new Category(6, "干货类") }; return res.ToList(); } public List<Tag> GetAlltags() { Tag[] res = { new Tag("多汁"), new Tag("时令"), new Tag("新鲜"), new Tag("进口"), new Tag("干货"), new Tag("香甜") }; return res.ToList(); } public Category[] GetCategories() { return categories.ToArray(); } public Fruit[] GetFruitsByTypeAndPage(int type = 0, int page = 1) { page--; List<Fruit> res = new List<Fruit>(); Fruit[] fruits = GetFruitsByType(type); for (int i = page * 9 + 0; i < Math.Min(page * 9 + 9, fruits.Length); i++) { res.Add(fruits[i]); } return res.ToArray(); } public int getPageNum() { return pageNum; } private Fruit[] GetFruitsByType(int type) { if (type == 0) { pageNum = (fruitList.Count + 8) / 9; return fruitList.ToArray(); } List<Fruit> res = new List<Fruit>(); foreach (Fruit fruit in fruitList) { if (fruit.CategoryId == type) { res.Add(fruit); } } pageNum = (res.Count + 8) / 9; return res.ToArray(); } //Bycolor public Fruit[] GetFruitsByColor(string color) { List<Fruit> res1 = new List<Fruit>(); if (color != null) { foreach (Fruit fruit in fruitList) { if (fruit.Color == color) { res1.Add(fruit); } } pageNum = (res1.Count + 8) / 9; } return res1.ToArray(); } //Bytag public Fruit[] GetFruitsByTag(string tag) { List<Fruit> res2 = new List<Fruit>(); if (tag != null) { foreach (Fruit fruit in fruitList) { if (fruit.Tag1 == tag || fruit.Tag2 == tag) { res2.Add(fruit); } } pageNum = (res2.Count + 8) / 9; } return res2.ToArray(); } //Bytsearch public Fruit[] GetFruitsBySearch(string search) { List<Fruit> res3 = new List<Fruit>(); if (search != null) { foreach (Fruit fruit in fruitList) { if (fruit.Tag1 == search || fruit.Tag2 == search) { res3.Add(fruit); } if (fruit.Color == search) { res3.Add(fruit); } if (fruit.Family == search) { res3.Add(fruit); } if (fruit.Place == search) { res3.Add(fruit); } if (fruit.Title == search) { res3.Add(fruit); } } pageNum = (res3.Count + 8) / 9; } return res3.ToArray(); } public Fruit GetFruitById(int id) { Fruit result = new Fruit(); //foreach (Fruit fruit in fruitList) //{ // if (fruit.Id == id) // { // result = fruit; // break; // } //} //Linq result = fruitList.FirstOrDefault(p => p.Id == id); return result; } public List<Fruit> GetAllFruits() { return DBHelper.GetFruitsList(); #region 原来的水果初始化代码 // Fruit fruit; // List<Fruit> fruitList = new List<Fruit>(); // fruit = new Fruit(); // fruit.Price = 10.00m; // fruit.IsOff = false; // fruit.Score = 0; // fruit.Photo = "apple1.jpg"; // fruit.OnTime = DateTime.Now; // fruit.Description = "苹果营养价值很高,富含矿物质和维生素,含钙量丰富,有助于代谢掉体内多余盐分,苹果酸可代谢热量,防止下半身肥胖。苹果是人们经常食用的水果之一。"; // fruit.Tag = "多汁,新鲜"; // fruit.CategoryId = 4; // fruit.Stock = 100; // fruit.Color = "red"; // fruit.Title = "苹果"; // fruit.Place = "烟台"; // fruit.Family = "核果类"; // fruit.Id = 1; // fruitList.Add(fruit); // //fruit = new Fruit(); // fruit.Price = 10.00m; // fruit.IsOff = false; // fruit.Score = 0; // fruit.Photo = "apple2.jpg"; // fruit.OnTime = DateTime.Now; // fruit.Description = "原名叫 Red delicious apple(可口的红苹果)香港人翻译为红地厘蛇果,简约为地厘蛇果。原产于美国的加利福尼亚州,又名红元帅,为红香蕉(元帅)的浓条红型芽变,是世界主要栽培品种之一。由于高品质的蛇果对气候条件的苛刻,发展到现在中国蛇果仅在甘肃天水高海拔山区魏店及周边种植。"; // fruit.Tag = "多汁,进口"; // fruit.CategoryId = 4; // fruit.Stock = 100; // fruit.Color = "red"; // fruit.Title = "蛇果"; // fruit.Place = "美国华盛顿"; // fruit.Family = "核果类"; // fruit.Id = 2; // fruitList.Add(fruit); // fruit = new Fruit(); // fruit.Price = 10.00m; // fruit.IsOff = false; // fruit.Score = 0; // fruit.Photo = "xg.jpg"; // fruit.OnTime = DateTime.Now; // fruit.Description = "西瓜为夏季之水果,果肉味甜,能降温去暑;种子含油,可作消遣食品;果皮药用,有清热、利尿、降血压之效。"; // fruit.Tag = "多汁,时令"; // fruit.CategoryId = 1; // fruit.Stock = 100; // fruit.Color = "red"; // fruit.Title = "西瓜"; // fruit.Place = "浙江"; // fruit.Family = "瓜果类"; // fruit.Id = 3; // fruitList.Add(fruit); // fruit = new Fruit(); // fruit.Price = 10.00m; // fruit.IsOff = false; // fruit.Score = 0; // fruit.Photo = "hmg.jpg"; // fruit.OnTime = DateTime.Now; // fruit.Description = "哈密瓜主产于吐哈盆地,它形态各异,风味独特,瓜肉肥厚,清脆爽口。哈密瓜营养丰富,含糖量最高达21%。哈密的甜瓜在东汉永平年间就成为进贡的异瓜种了。至清代,被哈密王作为贡品,受康熙赏赐而得名哈密瓜。"; // fruit.Tag = "新鲜,香甜"; // fruit.CategoryId = 1; // fruit.Stock = 100; // fruit.Color = "yellow"; // fruit.Title = "哈密瓜"; // fruit.Place = "吐鲁番"; // fruit.Family = "瓜果类"; // fruit.Id = 4; // fruitList.Add(fruit); // fruit = new Fruit(); // fruit.Price = 10.00m; // fruit.IsOff = false; // fruit.Score = 0; // fruit.Photo = "xg2.jpg"; // fruit.OnTime = DateTime.Now; // fruit.Description = "各种香瓜均含有苹果酸、葡萄糖、氨基酸、甜菜茄、维生素C等丰富营养。全国各地广泛栽培,世界温带至热带地区也广泛栽培。"; // fruit.Tag = "新鲜,香甜"; // fruit.CategoryId = 1; // fruit.Stock = 100; // fruit.Color = "yellow"; // fruit.Title = "香瓜"; // fruit.Place = "浙江"; // fruit.Family = "瓜果类"; // fruit.Id = 5; // fruitList.Add(fruit); // fruit = new Fruit(); // fruit.Price = 10.00m; // fruit.IsOff = false; // fruit.Score = 0; // fruit.Photo = "jz.jpg"; // fruit.OnTime = DateTime.Now; // fruit.Description = "柑和橘都属于芸香科柑橘属的宽皮柑橘类,果实外皮肥厚,内藏瓤瓣,由汁泡和种子构成。"; // fruit.Tag = "多汁,香甜"; // fruit.CategoryId = 2; // fruit.Stock = 100; // fruit.Color = "yellow"; // fruit.Title = "橘子"; // fruit.Place = "四川"; // fruit.Family = "柑桔类"; // fruit.Id = 6; // fruitList.Add(fruit); // fruit = new Fruit(); // fruit.Price = 10.00m; // fruit.IsOff = false; // fruit.Score = 0; // fruit.Photo = "cz.jpg"; // fruit.OnTime = DateTime.Now; // fruit.Description = "橙子起源于东南亚。橙树属小乔木。果实可以剥皮鲜食其果肉,果肉可以用作其他食物的调料或附加物。"; // fruit.Tag = "多汁,香甜"; // fruit.CategoryId = 2; // fruit.Stock = 100; // fruit.Color = "yellow"; // fruit.Title = "橙子"; // fruit.Place = "浙江"; // fruit.Family = "柑桔类"; // fruit.Id = 7; // fruitList.Add(fruit); // fruit = new Fruit(); // fruit.Price = 10.00m; // fruit.IsOff = false; // fruit.Score = 0; // fruit.Photo = "nm.jpg"; // fruit.OnTime = DateTime.Now; // fruit.Description = "柠檬因其味极酸,因为孕妇最喜食,故称益母果或益母子。柠檬中含有丰富的柠檬酸,因此被誉为“柠檬酸仓库”。它的果实汁多肉脆,有浓郁的芳香气。"; // fruit.Tag = "新鲜,多汁"; // fruit.CategoryId = 2; // fruit.Stock = 100; // fruit.Color = "yellow"; // fruit.Title = "柠檬"; // fruit.Place = "浙江"; // fruit.Family = "柑桔类"; // fruit.Id = 8; // fruitList.Add(fruit); // fruit = new Fruit(); // fruit.Price = 10.00m; // fruit.IsOff = false; // fruit.Score = 0; // fruit.Photo = "pty.jpg"; // fruit.OnTime = DateTime.Now; // fruit.Description = "葡萄柚又叫西柚、朱栾。因挂果时果实密集,呈簇生状,似葡萄成串垂吊,故称葡萄柚。系芸香科柑橘亚科柑橘属常绿乔木果树。"; // fruit.Tag = "新鲜,进口"; // fruit.CategoryId = 2; // fruit.Stock = 100; // fruit.Color = "red"; // fruit.Title = "葡萄柚"; // fruit.Place = "南非"; // fruit.Family = "柑桔类"; // fruit.Id = 9; // fruitList.Add(fruit); // fruit = new Fruit(); // fruit.Price = 10.00m; // fruit.IsOff = false; // fruit.Score = 0; // fruit.Photo = "jsmy.jpg"; // fruit.OnTime = DateTime.Now; // fruit.Description = "蜜柚(Honey pomelo),又名香抛,系柚子优质品的一种。多见生长于南方,果实小的如柑或者橘,大的如瓜,黄色的外皮很厚,食用时需去皮吃其瓤,大多在10-11月果实成熟时采摘。其皮厚耐藏,一般可存放三个月而不失香味,故被称为“天然水果罐头”。"; // fruit.Tag = "新鲜,进口"; // fruit.CategoryId = 2; // fruit.Stock = 100; // fruit.Color = "red"; // fruit.Title = "金丝蜜柚"; // fruit.Place = "泰国"; // fruit.Family = "柑桔类"; // fruit.Id = 10; // fruitList.Add(fruit); // fruit = new Fruit(); // fruit.Price = 10.00m; // fruit.IsOff = false; // fruit.Score = 0; // fruit.Photo = "banana.jpg"; // fruit.OnTime = DateTime.Now; // fruit.Description = "香蕉含有多种微量元素和维生素,能帮助肌肉松弛,使人身心愉悦 ,并具有一定的减肥功效。"; // fruit.Tag = "新鲜,进口"; // fruit.CategoryId = 3; // fruit.Stock = 100; // fruit.Color = "yellow"; // fruit.Title = "香蕉"; // fruit.Place = "泰国"; // fruit.Family = "热带水果类"; // fruit.Id = 11; // fruitList.Add(fruit); ////后来加了一个 //fruit = new Fruit(); //fruit.Price = 14.00m; //fruit.IsOff = false; //fruit.Score = 0; //fruit.Photo = "mht.jpg"; //fruit.OnTime = DateTime.Now; //fruit.Description = "猕猴桃(学名:Actinidia chinensis Planch),也称奇异果(奇异果是猕猴桃的一个人工选育品种,因使用广泛而成为了猕猴桃的代称)。中国是猕猴桃的原产地,20世纪早期被引入新西兰。"; //fruit.Tag = "多汁,进口"; //fruit.CategoryId = 3; //fruit.Stock = 100; //fruit.Color = "green"; //fruit.Title = "猕猴桃"; //fruit.Place = "新西兰"; //fruit.Family = "热带水果类"; //fruit.Id = 31; //fruitList.Add(fruit); //fruit = new Fruit(); //fruit.Price = 10.00m; //fruit.IsOff = false; //fruit.Score = 0; //fruit.Photo = "bl.jpg"; //fruit.OnTime = DateTime.Now; //fruit.Description = "菠萝原产于南美洲巴西、巴拉圭的亚马逊河流域一带,16世纪从巴西传入中国。 现在已经流传到整个热带地区。"; //fruit.Tag = "香甜,进口"; //fruit.CategoryId = 3; //fruit.Stock = 100; //fruit.Color = "yellow"; //fruit.Title = "菠萝"; //fruit.Place = "泰国"; //fruit.Family = "热带水果类"; //fruit.Id = 12; //fruitList.Add(fruit); //fruit = new Fruit(); //fruit.Price = 10.00m; //fruit.IsOff = false; //fruit.Score = 0; //fruit.Photo = "mg.jpg"; //fruit.OnTime = DateTime.Now; //fruit.Description = "芒果为著名热带水果之一,芒果果实含有糖、蛋白质、粗纤维,芒果所含有的维生素A的前体胡萝卜素成分特别高,是所有水果中少见的。其次维生素C含量也不低。"; //fruit.Tag = "时令,进口"; //fruit.CategoryId = 3; //fruit.Stock = 100; //fruit.Color = "yellow"; //fruit.Title = "芒果"; //fruit.Place = "泰国"; //fruit.Family = "热带水果类"; //fruit.Id = 13; //fruitList.Add(fruit); //fruit = new Fruit(); //fruit.Price = 10.00m; //fruit.IsOff = false; //fruit.Score = 0; //fruit.Photo = "yt.jpg"; //fruit.OnTime = DateTime.Now; //fruit.Description = "樱桃果实可以作为水果食用,外表色泽鲜艳、晶莹美丽、红如玛瑙,黄如凝脂,果实富含糖、蛋白质、维生素及钙、铁、磷、钾等多种元素。"; //fruit.Tag = "新鲜,时令"; //fruit.CategoryId = 4; //fruit.Stock = 100; //fruit.Color = "red"; //fruit.Title = "樱桃"; //fruit.Place = "浙江"; //fruit.Family = "核果类"; //fruit.Id = 14; //fruitList.Add(fruit); //fruit = new Fruit(); //fruit.Price = 10.00m; //fruit.IsOff = false; //fruit.Score = 0; //fruit.Photo = "tz.jpg"; //fruit.OnTime = DateTime.Now; //fruit.Description = "桃是一种果实作为水果的落叶小乔木,花可以观赏,果实多汁,可以生食或制桃脯、罐头等。"; //fruit.Tag = "多汁,香甜"; //fruit.CategoryId = 4; //fruit.Stock = 100; //fruit.Color = "red"; //fruit.Title = "桃子"; //fruit.Place = "浙江"; //fruit.Family = "核果类"; //fruit.Id = 15; //fruitList.Add(fruit); //fruit = new Fruit(); //fruit.Price = 10.00m; //fruit.IsOff = false; //fruit.Score = 0; //fruit.Photo = "lz.jpg"; //fruit.OnTime = DateTime.Now; //fruit.Description = "李子味酸,能促进胃酸和胃消化酶的分泌,并能促进胃肠蠕动,因而有改善食欲,促进消化的作用,尤其对胃酸缺乏、食后饱胀、大便秘结者有效。"; //fruit.Tag = "多汁,时令"; //fruit.CategoryId = 4; //fruit.Stock = 100; //fruit.Color = "red"; //fruit.Title = "李子"; //fruit.Place = "浙江"; //fruit.Family = "核果类"; //fruit.Id = 16; //fruitList.Add(fruit); //fruit = new Fruit(); //fruit.Price = 10.00m; //fruit.IsOff = false; //fruit.Score = 0; //fruit.Photo = "blm.jpg"; //fruit.OnTime = DateTime.Now; //fruit.Description = "波罗蜜以果实、种仁入药,果实用于酒精中毒,种仁用于产后脾虚气弱,乳少或乳汁不行"; //fruit.Tag = "新鲜,进口"; //fruit.CategoryId = 3; //fruit.Stock = 100; //fruit.Color = "yellow"; //fruit.Title = "波罗蜜"; //fruit.Place = "浙江"; //fruit.Family = "热带水果类"; //fruit.Id = 17; //fruitList.Add(fruit); //fruit = new Fruit(); //fruit.Price = 10.00m; //fruit.IsOff = false; //fruit.Score = 0; //fruit.Photo = "qm.jpg"; //fruit.OnTime = DateTime.Now; //fruit.Description = "青梅(学名:Vatica mangachapoi Blanco)是龙脑香科,青梅属乔木,树高约20米。小枝被星状绒毛。分布于中国海南。生于丘陵、坡地林中,海拔700米以下。"; //fruit.Tag = "多汁,香甜"; //fruit.CategoryId = 4; //fruit.Stock = 100; //fruit.Color = "green"; //fruit.Title = "青梅"; //fruit.Place = "海南"; //fruit.Family = "核果类"; //fruit.Id = 18; //fruitList.Add(fruit); //fruit = new Fruit(); //fruit.Price = 10.00m; //fruit.IsOff = false; //fruit.Score = 0; //fruit.Photo = "lz2.jpg"; //fruit.OnTime = DateTime.Now; //fruit.Description = "荔枝味甘、酸、性温,入心、脾、肝经;可止呃逆,止腹泻,是顽固性呃逆及五更泻者的食疗佳品,同时有补脑健身,开胃益脾,有促进食欲之功效。"; //fruit.Tag = "多汁,香甜"; //fruit.CategoryId = 4; //fruit.Stock = 100; //fruit.Color = "green"; //fruit.Title = "荔枝"; //fruit.Place = "广东"; //fruit.Family = "核果类"; //fruit.Id = 19; //fruitList.Add(fruit); //fruit = new Fruit(); //fruit.Price = 10.00m; //fruit.IsOff = false; //fruit.Score = 0; //fruit.Photo = "pear.jpg"; //fruit.OnTime = DateTime.Now; //fruit.Description = "梨的果实通常用来食用,不仅味美汁多,甜中带酸,而且营养丰富,含有多种维生素和纤维素,不同种类的梨味道和质感都完全不同。梨既可生食,也可蒸煮后食用。"; //fruit.Tag = "多汁,香甜"; //fruit.CategoryId = 4; //fruit.Stock = 100; //fruit.Color = "green"; //fruit.Title = "梨"; //fruit.Place = "广东"; //fruit.Family = "核果类"; //fruit.Id = 20; //fruitList.Add(fruit); //fruit = new Fruit(); //fruit.Price = 10.00m; //fruit.IsOff = false; //fruit.Score = 0; //fruit.Photo = "ym.jpg"; //fruit.OnTime = DateTime.Now; //fruit.Description = "杨梅果味酸甜适中,既可直接食用,又可加工成杨梅干、酱、蜜饯等,还可酿酒,有止渴、生津、助消化等功能。"; //fruit.Tag = "多汁,新鲜"; //fruit.CategoryId = 4; //fruit.Stock = 100; //fruit.Color = "red"; //fruit.Title = "杨梅"; //fruit.Place = "浙江"; //fruit.Family = "核果类"; //fruit.Id = 21; //fruitList.Add(fruit); //fruit = new Fruit(); //fruit.Price = 10.00m; //fruit.IsOff = false; //fruit.Score = 0; //fruit.Photo = "cm2.jpg"; //fruit.OnTime = DateTime.Now; //fruit.Description = "原产南美,中国各地及欧洲等地广为栽培。草莓营养价值高,含有多种营养物质 ,且有保健功效。"; //fruit.Tag = "香甜,新鲜"; //fruit.CategoryId = 5; //fruit.Stock = 100; //fruit.Color = "red"; //fruit.Title = "草莓"; //fruit.Place = "浙江"; //fruit.Family = "浆果类"; //fruit.Id = 22; //fruitList.Add(fruit); //fruit = new Fruit(); //fruit.Price = 10.00m; //fruit.IsOff = false; //fruit.Score = 0; //fruit.Photo = "lm.jpg"; //fruit.OnTime = DateTime.Now; //fruit.Description = "蓝莓果实中含有丰富的营养成分,具有防止脑神经老化、保护视力、强心、抗癌、软化血管、增强人机体免疫等功能,营养成分高。"; //fruit.Tag = "多汁,新鲜"; //fruit.CategoryId = 5; //fruit.Stock = 100; //fruit.Color = "blue"; //fruit.Title = "蓝莓"; //fruit.Place = "浙江"; //fruit.Family = "浆果类"; //fruit.Id = 23; //fruitList.Add(fruit); //fruit = new Fruit(); //fruit.Price = 10.00m; //fruit.IsOff = false; //fruit.Score = 0; //fruit.Photo = "pt2.jpg"; //fruit.OnTime = DateTime.Now; //fruit.Description = "葡萄为著名水果,生食或制葡萄干,并酿酒,酿酒后的酒脚可提酒石酸,根和藤药用能止呕、安胎。"; //fruit.Tag = "多汁,新鲜"; //fruit.CategoryId = 5; //fruit.Stock = 100; //fruit.Color = "blue"; //fruit.Title = "葡萄"; //fruit.Place = "浙江"; //fruit.Family = "浆果类"; //fruit.Id = 24; //fruitList.Add(fruit); //fruit = new Fruit(); //fruit.Price = 10.00m; //fruit.IsOff = false; //fruit.Score = 0; //fruit.Photo = "ptg.jpg"; //fruit.OnTime = DateTime.Now; //fruit.Description = "葡萄干(英文名称:raisin)是在日光下晒干或在阴影下晾干的葡萄的果实。葡萄又名草龙珠。主产新疆、甘肃,陕西、河北、山东等地。夏末秋初采收,鲜用或干燥备用。"; //fruit.Tag = "香甜,干货"; //fruit.CategoryId = 6; //fruit.Stock = 100; //fruit.Color = "blue"; //fruit.Title = "葡萄干"; //fruit.Place = "浙江"; //fruit.Family = "干货类"; //fruit.Id = 25; //fruitList.Add(fruit); //fruit = new Fruit(); //fruit.Price = 10.00m; //fruit.IsOff = false; //fruit.Score = 0; //fruit.Photo = "mg2.jpg"; //fruit.OnTime = DateTime.Now; //fruit.Description = "梅干,是日本传统的咸菜食品,对日本人来说,咸黄梅是最普遍的食品之一。到了黄梅雨季节,在各个家庭与食品工厂就开始生产梅干,一时间,整个日本都弥漫着一股梅子香味。"; //fruit.Tag = "香甜,干货"; //fruit.CategoryId = 6; //fruit.Stock = 100; //fruit.Color = "red"; //fruit.Title = "梅干"; //fruit.Place = "浙江"; //fruit.Family = "干货类"; //fruit.Id = 26; //fruitList.Add(fruit); //fruit = new Fruit(); //fruit.Price = 10.00m; //fruit.IsOff = false; //fruit.Score = 0; //fruit.Photo = "xjg.jpg"; //fruit.OnTime = DateTime.Now; //fruit.Description = "香蕉干是将香蕉去皮,切成片后的干货,易于储藏和食用。香蕉干就是我们常说的香蕉片,是一种很受欢迎的小零食。香蕉干主要以广西栽培主要香蕉品种——那龙蕉为原料,采取热风干燥加工法制成。"; //fruit.Tag = "香甜,干货"; //fruit.CategoryId = 6; //fruit.Stock = 100; //fruit.Color = "yellow"; //fruit.Title = "香蕉干"; //fruit.Place = "浙江"; //fruit.Family = "干货类"; //fruit.Id = 27; //fruitList.Add(fruit); //fruit = new Fruit(); //fruit.Price = 10.00m; //fruit.IsOff = false; //fruit.Score = 0; //fruit.Photo = "mgg.jpg"; //fruit.OnTime = DateTime.Now; //fruit.Description = "芒果干是用芒果制作的一道小吃。芒果干有益胃、止呕、止晕的功效。因此,芒果对于眩晕症、梅尼埃综合症、高血压晕眩、恶心呕吐等均有疗效。"; //fruit.Tag = "干货,进口"; //fruit.CategoryId = 6; //fruit.Stock = 100; //fruit.Color = "yellow"; //fruit.Title = "芒果干"; //fruit.Place = "泰国"; //fruit.Family = "干货类"; //fruit.Id = 28; //fruitList.Add(fruit); //fruit = new Fruit(); //fruit.Price = 10.00m; //fruit.IsOff = false; //fruit.Score = 0; //fruit.Photo = "cmg.jpg"; //fruit.OnTime = DateTime.Now; //fruit.Description = "草莓干中所含的胡萝卜素是合成维生素A的重要物质,具有明目养肝作用。"; //fruit.Tag = "干货,香甜"; //fruit.CategoryId = 6; //fruit.Stock = 100; //fruit.Color = "red"; //fruit.Title = "草莓干"; //fruit.Place = "浙江"; //fruit.Family = "干货类"; //fruit.Id = 29; //fruitList.Add(fruit); //fruit = new Fruit(); //fruit.Price = 10.00m; //fruit.IsOff = false; //fruit.Score = 0; //fruit.Photo = "htg.jpg"; //fruit.OnTime = DateTime.Now; //fruit.Description = "桃干有益肾固涩,活血化瘀,止汗止血,截疟。治盗汗,遗精,吐血,疟疾,心腹痛;妊娠下血。还可用于治疗幼儿缺铁性贫血。"; //fruit.Tag = "干货,香甜"; //fruit.CategoryId = 6; //fruit.Stock = 100; //fruit.Color = "yellow"; //fruit.Title = "黄桃干"; //fruit.Place = "浙江"; //fruit.Family = "干货类"; //fruit.Id = 30; //fruitList.Add(fruit); // //return fruitList; #endregion } }
edad924f94e5a4a71f4345a968f5bf663af9d563
C#
BenGab/ParrallelProgramming
/WikiediaArticleAnalyzer/Program.cs
3.046875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; namespace WikiediaArticleAnalyzer { class Program { static void Main(string[] args) { TestWrite(); Console.ReadLine(); } static void TestWrite() { string cont = string.Empty; const string keyword = "John von Neumann"; do { XDocument xd = XDocument.Load( $"https://en.wikipedia.org/w/api.php?action=query&titles={keyword}&prop=links&&pllimit=max&format=xml" + cont); Console.WriteLine(xd.Descendants("pl").Count()); if(xd.Descendants("continue").Count() > 0) { cont = $"&plcontinue={xd.Descendants("continue").Single().Attribute("plcontinue").Value}"; } else { cont = string.Empty; } foreach (var xelem in xd.Descendants("pl").Select(x => x.Attribute("title").Value)) { Console.WriteLine(xelem); } } while (!string.IsNullOrEmpty(cont)); } } }
ff502d5d5fc7d4e6cc5f23a0e39dd3b2e582863b
C#
shendongnian/download4
/code10/1725221-49910646-171602834-2.cs
2.984375
3
var gems = new HashSet<string>(); gems.Add('ruby'); gems.Add('diamond'); if (gems.Contain(want)) { Console.WriteLine($"Your wedding ring will feature your selection: {want}"); } else { Console.WriteLine(""Im sorry that was not a valid selection."); }
db026bb4c4d9fd4b5b49da254feafde2bfe9f6d1
C#
FearfulFlamingos/fear_valley_client
/fear_client/Assets/Scripts/CharacterClass/ICharacterFeatures.cs
2.8125
3
namespace Scripts.CharacterClass { /// <summary> /// This script is largely used to keep track of information on each of the game objects /// vital to making the game work. /// </summary> public interface ICharacterFeatures { /// <summary>Armor bonus of the character.</summary> int ArmorBonus { get; set; } /// <summary>Attack bonus of the character.</summary> int AttackBonus { get; set; } /// <summary>Attack range of the character.</summary> int AttackRange { get; set; } /// <summary>Class of the character.</summary> string Charclass { get; set; } /// <summary>Damage bonus of the character.</summary> int DamageBonus { get; set; } /// <summary>Health of the character.</summary> int Health { get; set; } /// <summary>Attacking state of the character.</summary> bool IsAttacking { get; set; } /// <summary>Focused state of the character.</summary> bool IsFocused { get; set; } /// <summary>Leadership quality of the character.</summary> int IsLeader { get; set; } /// <summary>Maximum damage value of the character.</summary> int MaxAttackVal { get; set; } /// <summary>Maximum movement distance of the character.</summary> int Movement { get; set; } /// <summary>Perception bonus of the character.</summary> /// <remarks>Unused by the game.</remarks> int Perception { get; set; } /// <summary>Stealth bonus of the character.</summary> /// <remarks>Unused by the game.</remarks> int Stealth { get; set; } /// <summary>Team number of the character.</summary> int Team { get; set; } /// <summary>ID number of the character.</summary> int TroopId { get; set; } /// <summary>RNG calculator of the character. See <see cref="IRandomNumberGenerator"/>.</summary> IRandomNumberGenerator Rng { get; set; } /// <summary> /// Damages the character. /// </summary> /// <param name="amount">Amount of damage the character should take.</param> void DamageCharacter(int amount); /// <summary> /// Get the attack roll of the character to be compared against an enemy's armor. /// See <see cref="Actions.PlayerAttack.Attack"/> for more details. /// </summary> /// <returns>Integer value of the attack roll.</returns> int GetAttackRoll(); /// <summary> /// Get the damage roll of the character. /// See <see cref="Actions.PlayerAttack.Attack"/> for more details. /// </summary> /// <returns>Integer value of the damage roll.</returns> int GetDamageRoll(); /// <summary> /// Get the magical attack roll of the character. /// See <see cref="Actions.PlayerMagic.MagicAttack(UnityEngine.GameObject)"/>. /// </summary> /// <returns>Integer value of the magical attack roll.</returns> int GetMagicAttackRoll(); /// <summary> /// Get the magical damage roll of the character. /// See <see cref="Actions.PlayerMagic.MagicAttack(UnityEngine.GameObject)"/>. /// </summary> /// <returns>Integer value of the magical damage roll.</returns> int GetMagicDamageRoll(); } }
fbcc2542899da815db6092fd84c3c91d3bf2d42d
C#
GearsAD/zasteroids
/SharedContent/ContentSections/MusicContent.cs
2.578125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Content; using Shared_Content; using Microsoft.Xna.Framework.Media; namespace ZitaAsteria.ContentSections { /// <summary> /// A static class containing references to all the music content. Not necessarily a good idea, can be done better (like with a sorted list), but this is /// both simple and effective. /// </summary> public class MusicContent { public Song mainMenuSong = null; public Song selectionMenuSong = null; public Song endCreditsSong = null; public Song planetBackgroundIce = null; public Song planetVolcano = null; public Song planetDust = null; public Song zaBlueDanubeIntro = null; public Song zaBlueDanubeLoop = null; /// <summary> /// Nothing happens in the constructor. /// </summary> public MusicContent() { } /// <summary> /// Load and set all the content. /// </summary> /// <param name="contentManager">The Content property (ContentManager) from GameClass</param> public void InitializeFromContent(ContentManager gameContentManager) { mainMenuSong = gameContentManager.Load<Song>("Music\\Game Theme & Menu"); selectionMenuSong = gameContentManager.Load<Song>("Music\\Selection Menu"); endCreditsSong = gameContentManager.Load<Song>("Music\\End Credits"); zaBlueDanubeIntro = gameContentManager.Load<Song>("Music\\ZAsteroids\\Blue Danube Intro"); zaBlueDanubeLoop = gameContentManager.Load<Song>("Music\\ZAsteroids\\Blue Danube Loop"); } } }
e2f2510e37ddfbad914450e1a10e9232612d8191
C#
programmerNacho/LanityKalkigi-CursoValladolid
/Assets/Scripts/Drawing/DrawingDifficultySelector.cs
2.609375
3
using System.Collections; using System.Collections.Generic; using UnityEngine; public class DrawingDifficultySelector : MonoBehaviour { [SerializeField] private DrawingBlock drawingBlock; private int roundsCompleted; public Texture2D SelectDrawing() { if(roundsCompleted < 3) { return drawingBlock.GiveMeADrawing(PlayerPaint.TextureSizes.Small); } else if(roundsCompleted < 6) { return drawingBlock.GiveMeADrawing(PlayerPaint.TextureSizes.Medium); } else { return drawingBlock.GiveMeADrawing(PlayerPaint.TextureSizes.Large); } } public void NextRound() { roundsCompleted++; } }
b4b8b0f1a61163efd203c83bc7899adb4545c8a2
C#
CWEB2010/nfl-coaches-draft-program-project-1-joebrenny
/project1/Program.cs
2.8125
3
using System; using System.Collections.Generic; using System.Linq; namespace project1 { class Program { //need to create a class so i can make the objects of players //use a bool value once the a player is selected so they user can use it twice static void Main(string[] args) { //deculartions string primer,sential="EXIT"; double Budget = 95000000; double costSelected; double moneyLeft; string playerNameSelection; double deal = 65000000; string[,] playersName = { { "Joe Burrow ", "Tua Tagoviloa","Justin Herbert","Jordan Love","Jake Fromm"}, { "D'Andre Swift", "Jonathan Taylor","J.K Dobbins","Zack Moss","Cam Akers"}, { "CeeDee Lamb ", "Jerry Jeudy","Tee Higgins","Henry Ruggs III","Yeter Gross-Matos"}, { "Chase Young ", "Derrick Brown","A.J Epenesa","Javon Kinlaw","Yeter Gross-Matos"}, { "Jeff Okudah", "Grant Delpit","Kristian Fulton","Xavier McKinny","CJ Jenderson"}, { "Cole Kmet", "Brycen Hopkins","Hunter Bryant","Jared Pinkney","Jacob Breeland"}, { "Isaiah Simmons", "Kenneth Murray","Zach Baun","Akeem Davis-Gaither","Troy Dye"}, { "Jedrick Wills Jr.", "Andrew Thomas","Tristan Wirfs","Tyler Biadasz","Mekhi Becton"} }; string[,] playersCollege = { { "(LSU) ", "(Alabama)","(Oregon)","(Utah St.)","(Georgia)"}, { "(Gerogia)", "(Wisconsin)","(Ohio St.)","(Utah)","(Florida St.)"}, { "(Oklahoma)", "(Alabama)","(Clemson)","(Alabama)","(Minnesota)"}, { "(Ohio St.)", "(Auburn)","(Iowa)","(So. Carolina)","(Penn St.)"}, { "(Ohio St.)", "(LSU)","(LSU)","(Alabama)","(Florida)"}, { "(Norte Dame)", "(Purdue)","(Washington)","(Vanderbilt)","(Oregon)"}, { "(Clemson)", "(Oklahoma)","(Wisconsin)","(App. St.)","(Oregon)"}, { "(Alabama)", "(Geogia)","(Iowa)","(Wisconsin)","(Louisville)"} }; double [,] playersCost = { {26400100,20300100,17420300,13100145,10300000}, {24500100,19890200,18700800,15000000,11600400}, {23400000,21900300,19300230,13400230,10000000}, {26200300,22000000,16000000,18000000,13000000}, { 24000000,22500249,20000100,16000200,11899999}, { 27800900,21000800,17499233,27900200,14900333}, { 22900300,19000590,18000222,12999999,10000100}, { 23000000, 20000000,19400000,16200700,15900000} }; int[,] rank= { {1,2,3,4,5 }, {1,2,3,4,5 }, {1,2,3,4,5 }, {1,2,3,4,5 }, {1,2,3,4,5 }, {1,2,3,4,5 }, {1,2,3,4,5 }, {1,2,3,4,5 }, }; string [,] Position= { {"Quarterback","Quarterback","Quarterback","Quarterback","Quarterback" }, {"Running Back","Running Back","Running Back","Running Back","Running Back" }, {"Wide-Receiver","Wide-Receiver","Wide-Receiver","Wide-Receiver","Wide-Receiver" }, {"Defensive Lineman","Defensive Lineman","Defensive Lineman","Defensive Lineman","Defensive Lineman" }, {"Defensive-Back","Defensive-Back","Defensive-Back","Defensive-Back","Defensive-Back" }, {"Tight End","Tight End","Tight End","Tight End","Tight End" }, {"Line-Backer","Line-Backer","Line-Backer","Line-Backer","Line-Backer" }, {"Offensive Tackle","Offensive Tackle","Offensive Tackle","Offensive Tackle","Offensive Tackle" }, }; Console.WriteLine("Welcome to the NFL Draft Program"); Console.WriteLine("Please type Enter to get started"); Console.WriteLine($"Please select up to 5 players and you have a budget of {Budget.ToString("c")} "); primer=Console.ReadLine(); while (primer != sential) { Player[] player = new Player[40]; List<Player> PlayerList = new List<Player>(); List<Player> selectionList = new List<Player>(5); //int y = 0; //creating the object for Joe Burrow for (var x = 0; x < playersName.GetLength(0); x++) { for (var y = 0; y < playersName.GetLength(1); y++) { player[x] = new Player(playersName[x, y], playersCollege[x, y], playersCost[x, y], rank[x, y], Position[x, y]); //Console.WriteLine(player[x]); PlayerList.Add(player[x]); //Console.WriteLine("output player list"); //Console.WriteLine(PlayerList); } //inner for loop y }// end of the for loop X //out put the list Console.WriteLine("checking to see if the list is outputing"); PlayerList.ForEach(x => Console.WriteLine(x.ToString())); for (var s=0 /*selectionList.Count*/; s <=4 ; s++) { Console.WriteLine($"you have picked {s} Players"); Console.WriteLine($"please enter the player name for pick {s+1}"); Console.WriteLine("Press 'enter' if you are done selecting players"); playerNameSelection = Console.ReadLine(); if (playerNameSelection == "") { break; } for (var i = PlayerList.Count - 1; i >= 0; i--) //(var i =0; PlayerList.Count > i; i++) { if (PlayerList[i].Name.Contains(playerNameSelection)) { selectionList.Add(PlayerList[i]); PlayerList.RemoveAt(i); } } PlayerList.ForEach(x => Console.WriteLine(x.ToString())); Console.WriteLine("SELECTED PLAYERS_BELOW_______REMAINING_CHOICES_ABOVE____________________________"); selectionList.ForEach(x => Console.WriteLine(x.ToString())); //get the total of players selected and the remaining budget left costSelected =selectionList.Sum(item => item.Salary); moneyLeft = costSelected - Budget; if (costSelected > Budget) { Console.WriteLine("You have exceeded the budget and must start over"); break; } Console.WriteLine($"You have spent {costSelected.ToString("c")}"); Console.WriteLine($"You have {moneyLeft.ToString("c")} remaining"); //cost effective check if top three players and not working for this //if (selectionList.Exists(x => x.Rank == 1) || selectionList.Exists(x => x.Rank == 2) || selectionList.Exists(x => x.Rank == 3) // && /*costSelected =*/ selectionList.Sum(item => item.Salary) < deal) //{ // Console.WriteLine("1111111111COngrats you are cost effective"); //} } costSelected = selectionList.Sum(item => item.Salary); if ((selectionList.Exists(x => x.Rank == 1) || selectionList.Exists(x => x.Rank == 2) || selectionList.Exists(x => x.Rank == 3)) && costSelected /*= selectionList.Sum(item => item.Salary)*/ < deal) { Console.WriteLine("Congrats you are cost effective !!!!!!!!!"); } Console.WriteLine("please press enter to run program again or type'EXIT' to end program "); primer= Console.ReadLine().ToUpper(); }//end of while loop primer }//end of the main }// end of the class program }
9bb2bbafac8f24a8abc104cfea240df978ee446b
C#
andrei-ga/spotyplace
/Server/Spotyplace.Entities/DTOs/CustomerSubscriptionDto.cs
2.578125
3
using ChargeBee.Models; using System; using System.Collections.Generic; using System.Text; namespace Spotyplace.Entities.DTOs { public class CustomerSubscriptionDto { /// <summary> /// Identifier of the plan for this subscription. /// </summary> public string PlanId { get; set; } /// <summary> /// Current state of the subscription. /// </summary> public Subscription.StatusEnum Status { get; set; } public CustomerSubscriptionDto() { } public CustomerSubscriptionDto(Subscription subscription) { if (subscription != null) { this.PlanId = subscription.PlanId; this.Status = subscription.Status; } } } }
3ad75dcb897a9369d752acd95be75553749a04c1
C#
mdobson2/Lab-02-Repo
/Tools/Assets/Editor/CreateAnimations.cs
2.609375
3
using UnityEngine; using System.Collections; using UnityEditor; /* A tool for creating sprite sheet animations quickly and easily * @author Mike Dobson */ public class CreateAnimations : EditorWindow { public static Object selectedObject; int numAnimations; string controllerName; string[] animationNames = new string[100]; float[] clipFrameRate = new float[100]; float[] clipTimeBetween = new float[100]; int[] startFrames = new int[100]; int[] endFrames = new int[100]; bool[] pingPong = new bool[100]; bool[] loop = new bool[100]; [MenuItem("Project Tools/2D Animations")] public static void Init() { selectedObject = Selection.activeObject; if (selectedObject == null) return; CreateAnimations window = (CreateAnimations)EditorWindow.GetWindow(typeof(CreateAnimations)); window.Show(); } void OnGUI() { if (selectedObject != null) { //Displays the object name that the animations are being created from EditorGUILayout.LabelField("Animations for " + selectedObject.name); //Seperator EditorGUILayout.Separator(); //Get the name of the controller for the animations controllerName = EditorGUILayout.TextField("Controller Name", controllerName); //Get the number of animations numAnimations = EditorGUILayout.IntField("How Many Animations?", numAnimations); //Loop through each animation for (int i = 0; i < numAnimations; i++) { //Determine the name of the animation animationNames[i] = EditorGUILayout.TextField("Animation Name", animationNames[i]); //Start a section where the following items will be displayed horozontally instead of vertically EditorGUILayout.BeginHorizontal(); //Determine the start frame of the animation startFrames[i] = EditorGUILayout.IntField("Start Frame", startFrames[i]); //Determine the end frame of the animation endFrames[i] = EditorGUILayout.IntField("End Frame", endFrames[i]); //End the section where the previous items are displayed horozontally instead of vertically EditorGUILayout.EndHorizontal(); //Start a section where the items will be displayed horozontally instead of vertically EditorGUILayout.BeginHorizontal(); //Determine the frame rate of the animation clipFrameRate[i] = EditorGUILayout.FloatField("Frame Rate", clipFrameRate[i]); //Determine the space between each keyframe clipTimeBetween[i] = EditorGUILayout.FloatField("Frame Spacing", clipTimeBetween[i]); //End the section where the previous items are displayed horozontally instead of vertically EditorGUILayout.EndHorizontal(); //Start a section where the items will be displayed horozontally instead of vertically EditorGUILayout.BeginHorizontal(); //Create a checkbox to determine if this animation should loop loop[i] = EditorGUILayout.Toggle("Loop", loop[i]); //Create a checkbox to determine if this animation should pingpong pingPong[i] = EditorGUILayout.Toggle("Ping Pong", pingPong[i]); //End the section where items are displayed horozontally instead of vertically EditorGUILayout.EndHorizontal(); //Seperator EditorGUILayout.Separator(); } //Create a button with the label Create if (GUILayout.Button("Create")) { //if the button has been pressed UnityEditor.Animations.AnimatorController controller = UnityEditor.Animations.AnimatorController.CreateAnimatorControllerAtPath(("Assets/" + controllerName + ".controller")); for (int i = 0; i < numAnimations; i++) { //Create animation clip AnimationClip tempClip = CreateClip(selectedObject, animationNames[i], startFrames[i], endFrames[i], clipFrameRate[i], clipTimeBetween[i], pingPong[i]); if (loop[i]) { //set the loop on the clip to true AnimationClipSettings settings = AnimationUtility.GetAnimationClipSettings(tempClip); settings.loopTime = true; settings.loopBlend = true; AnimationUtility.SetAnimationClipSettings(tempClip, settings); } controller.AddMotion(tempClip); } } } } public AnimationClip CreateClip(Object obj, string clipName, int startFrame, int endFrame, float frameRate, float timeBetween, bool pingPong) { //Get the path to the object string path = AssetDatabase.GetAssetPath(obj); //Extract the sprites at the path Object[] sprites = AssetDatabase.LoadAllAssetsAtPath(path); //Determine how many frames and the length of each frame int frameCount = endFrame - startFrame + 1; float frameLength = 1f / timeBetween; //create the new empty animation clip AnimationClip clip = new AnimationClip(); //set the framerate of the clip clip.frameRate = frameRate; //create the new empty curve binding EditorCurveBinding curveBinding = new EditorCurveBinding(); //assign it to change the sprite renderer curveBinding.type = typeof(SpriteRenderer); //assign it to alter the sprite of the sprite renderer curveBinding.propertyName = "m_Sprite"; //Create a container for all the keyframes ObjectReferenceKeyframe[] keyFrames; //Determine how many frames there will be if we are or are not pingponging if(!pingPong) { keyFrames = new ObjectReferenceKeyframe[frameCount + 1]; } else { keyFrames = new ObjectReferenceKeyframe[frameCount * 2 + 1]; } //track what frame number we are on int frameNumber = 0; //loop from start to end, incrementing frameNumber as we go for (int i = startFrame; i < endFrame + 1; i++, frameNumber++) { //create an empty keyframe ObjectReferenceKeyframe tempKeyFrame = new ObjectReferenceKeyframe(); //Assign i a time to appear in the animation tempKeyFrame.time = frameNumber * frameLength; //assign it a sprite tempKeyFrame.value = sprites[i]; //Place it into the container fro all the keyframes keyFrames[frameNumber] = tempKeyFrame; } if(pingPong) { //create the keyframes starting at the end and going backwards //continue to keep track of the frame number for(int i = endFrame; i>= startFrame; i--, frameNumber++) { ObjectReferenceKeyframe tempkeyframe = new ObjectReferenceKeyframe(); tempkeyframe.time = frameNumber * frameLength; tempkeyframe.value = sprites[i]; keyFrames[frameNumber] = tempkeyframe; } } //Create the last sprite to stop it from switching to the first frame from the last immediately ObjectReferenceKeyframe lastSprite = new ObjectReferenceKeyframe(); lastSprite.time = frameNumber * frameLength; lastSprite.value = sprites[startFrame]; keyFrames[frameNumber] = lastSprite; //assign the name to the clip clip.name = clipName; //apply the curve AnimationUtility.SetObjectReferenceCurve(clip, curveBinding, keyFrames); //create the clip AssetDatabase.CreateAsset(clip, ("Assets/" + clipName + ".anim")); //return the clip return clip; } }
52d89e260505e3b13c79782157b0d245314469dd
C#
mfmmac/GC-Exercises
/Exercise26/Exercise26/Program.cs
3.703125
4
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; namespace Exercise26 { class Program { static void Main(string[] args) { Console.WriteLine("Please enter some text"); var userInput = Console.ReadLine(); bool userContinue = true; var vowels = new List<char>() { 'a', 'e', 'i', 'o', 'u'}; int count = 0; do { foreach (char charInString in userInput) { if (vowels.Contains(charInString)) { count++; } Console.WriteLine($"Number of vowels: {count}"); } var contInput = Console.ReadLine().ToLower(); Console.WriteLine("Do you want to continue? (Y/N)"); if ((contInput == "y") || (contInput == "yes")) { userContinue = true; } else if ((contInput == "n") || (contInput == "no")) { userContinue = false; Console.WriteLine("Thank you. Goodbye"); return; } else { Console.WriteLine("Invalid Entry. Please use y or n."); var contInput2 = Console.ReadLine(); userContinue = true; } } while (userContinue); } } }
31379deaca77cde07bf72bc5a29554940053c722
C#
BenBBO/GestionClient
/GestionClient/GestionClient.Manager/Manager/CrudManager.cs
2.84375
3
using GestionClient.Manager.Interface; using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Linq.Expressions; namespace GestionClient.Manager { public abstract class CrudManager<C, T> : ICrudManager<T> where T : class where C : DbContext, new() { #region Properties private C _entities = new C(); public C Context { get { return _entities; } set { _entities = value; } } #endregion public virtual void CreateItem(T item) { var entities = _entities.Set<T>(); entities.Add(item); _entities.SaveChanges(); } public virtual void DeleteItem(T item) { _entities.Set<T>().Remove(item); _entities.SaveChanges(); } public virtual IEnumerable<T> GetAll() { IQueryable<T> query = _entities.Set<T>(); return query; } public virtual IEnumerable<T> GetWhere(Expression<Func<T, bool>> predicate) { IQueryable<T> toReturn = _entities.Set<T>().Where(predicate); return toReturn; } public virtual void UpdateItem(T item) { _entities.Entry(item).State = EntityState.Modified; _entities.SaveChanges(); } public abstract T GetById(int Id); } }
9fced6c3de7b29786baa89f4ec8b85f5dd9090ae
C#
BenjaminRSergent/Warlord
/Warlord/Warlord/GameTools/Graph/Vector3i.cs
3.265625
3
using System; using Microsoft.Xna.Framework; namespace GameTools.Graph { struct Vector3i { int x; int y; int z; public Vector3i(int X, int Y, int Z) { x = X; y = Y; z = Z; } public Vector3i(Vector3i source) { x = source.X; y = source.Y; z = source.Z; } public Vector3i(Vector3 source) { x = (int)source.X; y = (int)source.Y; z = (int)source.Z; } public static implicit operator Vector3i(Vector3 source) { Vector3i vector = new Vector3i(); vector.X = (int)source.X; vector.Y = (int)source.Y; vector.Z = (int)source.Z; return vector; } public float AngleBetween(Vector3i otherVector) { Vector3 thisNorm = GetNormalized(); Vector3 otherNorm = otherVector.GetNormalized(); float dot = GraphMath.Dot(thisNorm, otherNorm); return (float)Math.Acos(dot); } public float DotProduct(Vector3i otherVector) { return this.X * otherVector.X + this.Y * otherVector.Y + this.Z * otherVector.Z; } public Vector3 GetNormalized() { Vector3 normVec = new Vector3(X, Y, Z); normVec.Normalize(); return normVec; } static public Vector3i operator +(Vector3i leftVector, Vector3i rightVector) { Vector3i sumVector = new Vector3i(leftVector); sumVector.X += rightVector.X; sumVector.Y += rightVector.Y; sumVector.Z += rightVector.Z; return sumVector; } static public Vector3i operator -(Vector3i leftVector, Vector3i rightVector) { Vector3i differenceVector = new Vector3i(leftVector); differenceVector.X -= rightVector.X; differenceVector.Y -= rightVector.Y; differenceVector.Z -= rightVector.Z; return differenceVector; } static public Vector3i operator *(int number, Vector3i vector) { Vector3i scaledVector = new Vector3i(vector); scaledVector.X *= number; scaledVector.Y *= number; scaledVector.Z *= number; return scaledVector; } static public float operator *(Vector3i leftVector, Vector3i rightVector) { return leftVector.DotProduct(rightVector); } static public bool operator ==(Vector3i leftVector, Vector3i rightVector) { return leftVector.X == rightVector.X && leftVector.Y == rightVector.Y && leftVector.Z == rightVector.Z; } static public bool operator !=(Vector3i leftVector, Vector3i rightVector) { return leftVector.X != rightVector.X || leftVector.Y != rightVector.Y || leftVector.Z != rightVector.Z; } public override bool Equals(object obj) { if(obj is Vector3i) { return this == (Vector3i)obj; } else return false; } public override int GetHashCode() { // xor the components with large prime numbers return x ^ 73856093 ^ y ^ 19349663 ^ z ^ 83492791; } public override string ToString() { return "(" + X + "," + Y + "," + Z + ")"; } public float Length { get { return (float)Math.Sqrt(LengthSquared); } } public int LengthSquared { get { return X * X + Y * Y + Z * Z; } } public Vector3 ToVector3 { get { return new Vector3(X, Y, Z); } } static public Vector3i Zero { get { return new Vector3i(0, 0, 0); } } static public Vector3i One { get { return new Vector3i(1, 1, 1); } } static public Vector3i XIncreasing { get { return new Vector3i(1, 0, 0); } } static public Vector3i YIncreasing { get { return new Vector3i(0, 1, 0); } } static public Vector3i ZIncreasing { get { return new Vector3i(0, 0, 1); } } static public Vector3i XDecreasing { get { return new Vector3i(-1, 0, 0); } } static public Vector3i YDecreasing { get { return new Vector3i(0, -1, 0); } } static public Vector3i ZDecreasing { get { return new Vector3i(0, 0, -1); } } public int X { get { return x; } set { x = value; } } public int Y { get { return y; } set { y = value; } } public int Z { get { return z; } set { z = value; } } } }
73562a3fb0068efd850039754817d27c5a5eecdd
C#
Yiomo/acafe
/αcafe/Functions/GetTips.cs
2.921875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace αcafe.Functions { class GetTips { public static string GetRdTips() { List<string> AllTips = new List<string>(); AllTips.Add("最佳的变焦镜便是你自己的脚"); AllTips.Add("多留意光线"); AllTips.Add("靠近,然后再靠近一点"); AllTips.Add("不要想太多,拍摄吧!"); AllTips.Add("不要停止练习"); AllTips.Add("减少你的负重,增加你的创意"); AllTips.Add("多拍摄,不要光看理论"); AllTips.Add("放慢一点"); AllTips.Add("街拍宜低调,高感黑白片,旁轴大光圈"); AllTips.Add("广角重主题,长焦压缩景"); AllTips.Add("小光圈景深,全开糊背景"); AllTips.Add("拍花侧逆光,慢门显动感"); AllTips.Add("见山寻侧光,见水拍倒影"); AllTips.Add("对焦对主题,水平要抓平"); AllTips.Add("长曝避车灯,岩石要湿润"); AllTips.Add("有云天要多,无云地为主"); AllTips.Add("前景位关键,三分九宫格"); AllTips.Add("偏光去反光,渐变平反差"); AllTips.Add("拍小孩全靠手急,拍女孩全靠磨皮。"); AllTips.Add("变焦基本靠走,对焦基本靠扭。"); Random rd = new Random(); int a=rd.Next(1,AllTips.Count()+1); return AllTips[a]; } } }
8c8a7abc1bdbae7a376afe91458806b92b711cc7
C#
joebir/csharplibrary
/0.20_Interfaces/ListClass.cs
3.09375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _0._20_Interfaces { class ListClass : IEnum, IList, ICollect { public void IterateOverCollection() { Console.WriteLine("Iterating over the collection."); } public void AddStuff() { Console.WriteLine("Adding stuff to the list."); } public void RemoveStuff() { Console.WriteLine("Removing stuff from the list."); } public void CheckCount() { Console.WriteLine("Checking the count of the list."); } public void CheckCapacity() { Console.WriteLine("Checking the capacity of the list."); } } }
a35aa5dcb26e228e2b796d9bdc419ad68956deb8
C#
Ctor1994/AspApp
/tHISiStHEsHOP/Data/Repository/CarRepository.cs
2.578125
3
using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using tHISiStHEsHOP.Data.Interfaces; using tHISiStHEsHOP.Models; namespace tHISiStHEsHOP.Data.Repository { public class CarRepository : ICars { private readonly ApplicationContext dbContext; public CarRepository(ApplicationContext dbContext) { this.dbContext = dbContext; } public IEnumerable<Car> GetAllCars => dbContext.Cars.Include(c => c.Category); public IEnumerable<Car> GetFavCars => dbContext.Cars.Where(x => x.IsFavorite).Include(c => c.Category); public Car GetObjCar(int carId) => dbContext.Cars.FirstOrDefault(i => i.Id == carId); } }
51dc4509c6888381931791bb669592cf17170a04
C#
woger/teste2
/Settings/Configuracoes/Helper.cs
2.84375
3
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; namespace Settings.Configuracoes { public static class Helper { public static Image Resize(Image img, int iWidth, int iHeight) { Bitmap bmp = new Bitmap(iWidth, iHeight); Graphics graphic = Graphics.FromImage((Image)bmp); graphic.DrawImage(img, 0, 0, iWidth, iHeight); return (Image)bmp; } } }
bff84cf9babfde51175d6e9dab160bdb0cfedbe9
C#
RodolfoZamora999/Gauss_Seidel
/Gauss_Seidel/Form1.cs
3
3
using System; using System.Drawing; using System.Windows.Forms; namespace Gauss_Seidel { public partial class frmMetodos : Form { //Esta matriz almacena los valores de "x" calculados. private double[] valoresX; private ArrayDynamic arrayDynamic; public frmMetodos() { InitializeComponent(); this.btnIteracion.Enabled = false; } //Evento para el botón de "Aceptar" //Sirve para preparar la interfaz y todo lo necesario private void Click_Crear_Matriz(object sender, EventArgs e) { try { Limpiar(); //Inicializa el vector para guardar todos los valores de las x this.valoresX = new double[int.Parse(this.txDimension.Text)]; //Todos los valores se igualan a 0 for (int i = 0; i < this.valoresX.Length; i++) this.valoresX[i] = 0; //Creación de la matriz de TextBoxs this.arrayDynamic = new ArrayDynamic(this.panelMatriz); this.arrayDynamic.Crear_Matriz(int.Parse(this.txDimension.Text)); Crear_Columnas(int.Parse(this.txDimension.Text)); this.btnIteracion.Enabled = true; } catch(Exception ex) { MessageBox.Show("Houston, tenemos un problema..."); Console.WriteLine(ex.ToString()); } } //Método que se encarga de crear la lista donde se desplegaran los resultados private void Crear_Columnas(int variables) { ColumnHeader[] columnas = new ColumnHeader[(variables * 2)]; this.listaResultado.Columns.Add(new ColumnHeader() {Text = "#Iteración", Width = 90 }); for(int i = 0; i < variables; i++) { columnas[i] = new ColumnHeader() { Text = "X" + (i+1), Width = 90 }; } byte n = 1; for (int i = variables; i < (variables*2); i++) { columnas[i] = new ColumnHeader() { Text = "Ex" + (n), Width = 90 }; n++; } this.listaResultado.Columns.AddRange(columnas); } //Método para empezar con la iteración del programa private void Clic_Iniciar_Iteracion(object sender, EventArgs e) { this.listaResultado.Items.Clear(); //Limite int limite = int.Parse(this.txtIteracion.Text); //Toleranciad error double tolerancia = double.Parse(this.txtTolerancia.Text); if (ComprobarDiagonal(this.arrayDynamic.LeerIncognitas())) { if(cbMetodo.SelectedIndex==0) AlgoritmoGauss_Seidel(this.arrayDynamic.LeerIncognitas(), this.arrayDynamic.LeerIgualaciones(), limite, tolerancia); else if(cbMetodo.SelectedIndex==1) AlgoritmoGauss_Simple(this.arrayDynamic.LeerIncognitas(), this.arrayDynamic.LeerIgualaciones(), limite, tolerancia); } else MessageBox.Show("Comprobar diagonal, ¿Quieres?"); } //Método para calcular las iteraciones public void AlgoritmoGauss_Seidel(double[,] valores, double[] igualaciones, int limite, double tolerancia) { //Variables que guardan los xn anteriores double[] valoresXanteriores; valoresXanteriores = (double[])valoresX.Clone(); //Esta parte del código sirve para imprimir los valores string[] valoresImprimir = new string[ (this.valoresX.Length * 2) + 1]; //Ciclo para hacer el numero de iteraciones for (int iterador = 1; iterador <= limite || limite == 0; iterador++) { valoresImprimir[0] = iterador.ToString(); //Almacenar los valores for (int i = 0; i < this.valoresX.Length; i++) valoresImprimir[i+1] = Math.Round(this.valoresX[i], 4).ToString(); //Almacenar los errores for (int i = this.valoresX.Length; i < valoresX.Length * 2; i++) valoresImprimir[i + 1] = Math.Round(Calcular_EX(this.valoresX[i - this.valoresX.Length], valoresXanteriores[i - this.valoresX.Length]), 4).ToString(); this.listaResultado.Items.Add(new ListViewItem(valoresImprimir)); //Comprobar la tolerancia for (int i = 0; i < this.valoresX.Length; i++) { if (Math.Round(Calcular_EX(this.valoresX[i], valoresXanteriores[i]), 4) <= tolerancia) { //Por si el error es menor o igual al establecido MessageBox.Show("La iteración ha sido exitosa"); return; } } //Se almacenan los valores en anteriores valoresXanteriores = (double[])valoresX.Clone(); //Ciclo para recorrer los vectores for (int i = 0; i < igualaciones.Length; i++) { //Esta variable es temporal double valorTemp = 0; //Recorre un valor por cada iteración for (int j = 0; j < igualaciones.Length; j++) { if (i != j) valorTemp = valorTemp - (valores[i, j] * this.valoresX[j]); } valorTemp += igualaciones[i]; //Almacena el resultado de los valores para X this.valoresX[i] = (valorTemp / valores[i, i]); } } //Por si alcanza el limite de iteraciones MessageBox.Show("La iteración ha sido exitosa por iteraciones"); } public void AlgoritmoGauss_Simple(double[,] valores, double[]igualaciones, int limite, double tolerancia) { //resolver for (int iterador = 1; iterador <= limite || limite == 0; iterador++) { for (int k = 0; k < valoresX.Length - 1; k++) { for (int i = k + 1; i < valoresX.Length - 1; i++) { double factor = valores[i, k] / valores[k, k]; for (int j = k; j <= valoresX.Length - 1; j++) { valores[i, j] = valores[i, j] - valores[k, j] * factor; } } } } } public bool ComprobarDiagonal(double[,] matriz) { for (int i = 0; i < matriz.GetLength(0); i++) { for (int j = 0; j < matriz.GetLength(0); j++) { if (matriz[i, i] < matriz[i, j]) { return false; } } } return true; } //Método encargado para el cálculo del error aproximado. private double Calcular_EX(double xnActual, double xnAnterior) { return Math.Abs(((xnActual - xnAnterior) / xnActual) * 100); ; } //Método que se encarga de limpiar toda la interfaz grafica private void Limpiar() { this.listaResultado.Columns.Clear(); this.listaResultado.Items.Clear(); this.panelMatriz.Controls.Clear(); } //Cambiar de color a componentes // // No personalizable porque escogen colores feos // private void TsmiVerde_Click(object sender, EventArgs e) { msMenu.BackColor = Color.FromArgb(162, 215, 41); btnAceptar.BackColor = Color.FromArgb(162, 215, 41); btnIteracion.BackColor = Color.FromArgb(162, 215, 41); lblX.BackColor = Color.FromArgb(162, 215, 41); } private void TsmiRojo_Click(object sender, EventArgs e) { msMenu.BackColor = Color.FromArgb(250, 130, 76); btnAceptar.BackColor = Color.FromArgb(250, 130, 76); btnIteracion.BackColor = Color.FromArgb(250, 130, 76); lblX.BackColor = Color.FromArgb(250, 130, 76); } private void TsmiNegro_Click(object sender, EventArgs e) { msMenu.BackColor = Color.FromArgb(52, 46, 55); btnAceptar.BackColor = Color.FromArgb(52, 46, 55); btnIteracion.BackColor = Color.FromArgb(52, 46, 55); lblX.BackColor = Color.FromArgb(52, 46, 55); } private void TsmiAzul_Click(object sender, EventArgs e) { msMenu.BackColor = Color.FromArgb(60, 145, 230); btnAceptar.BackColor = Color.FromArgb(60, 145, 230); btnIteracion.BackColor = Color.FromArgb(60, 145, 230); lblX.BackColor = Color.FromArgb(60, 145, 230); } private void LblX_Click(object sender, EventArgs e) { Close(); } } }
1e9c7ca0bd2862ccaf05e25f79431814c10d0ab8
C#
shendongnian/download4
/code6/1119637-29401381-87196730-2.cs
3.109375
3
string fetchContentString(object o) { if (o == null) { return null; } if(o is string) { return o.ToString(); } if(o is ContentControl) { var cc = o as ContentControl; if (cc.HasContent) { return fetchContentString(cc.Content); } else { return null; } } if(o is Panel) { var p = o as Panel; if (p.Children != null) { if (p.Children.Count > 0) { if(p.Children[0] is ContentControl) { return fetchContentString((p.Children[0] as ContentControl).Content); } } } } return null; }
7922a1fa7d668dd063a4a5e45c7da349f87cced0
C#
mwlk/dicsys-academy-.net
/solution-academy/Services/IngredienteService.cs
2.828125
3
using Microsoft.EntityFrameworkCore; using Persistencia.Database.Models; using System; using System.Collections.Generic; using System.Linq; namespace Services { public class IngredienteService { public void Add(Ingrediente ingrediente) { using ApplicationDbContext db = new ApplicationDbContext(); try { if (ingrediente.Id != 0) { db.Entry(ingrediente).State = EntityState.Modified; } else { db.Ingredientes.Add(ingrediente); } db.SaveChanges(); } catch (Exception e) { throw new ApplicationException("Error al guardar " + e.Message); } } public bool Delete(int id) { using ApplicationDbContext db = new ApplicationDbContext(); var busqueda = db.Ingredientes.Find(id); if(busqueda != null) { db.Ingredientes.Remove(busqueda); db.SaveChanges(); return true; } else { return false; } } public List<Ingrediente> GetAll() { using ApplicationDbContext db = new ApplicationDbContext(); var list = db.Ingredientes.ToList(); return list; } public void GetByPizza(int id) { } public void Update(Ingrediente ingrediente) { using ApplicationDbContext db = new ApplicationDbContext(); Ingrediente oIngrediente = db.Ingredientes.Find(ingrediente.Id); oIngrediente.Nombre = ingrediente.Nombre; db.Entry(oIngrediente).State = EntityState.Modified; db.SaveChanges(); } public bool ValIngrediente(Ingrediente ingrediente) { using ApplicationDbContext db = new ApplicationDbContext(); var ing = db.Ingredientes.Where(i => i.Nombre == ingrediente.Nombre).FirstOrDefault(); if (ing == null) { return true; } else { return false; } } } }
555be99f1234a0a0dd67206d2afbf46270f7f49b
C#
shendongnian/download4
/first_version_download2/403135-35105261-109683084-2.cs
3.21875
3
public static List<string> GetBetweenAll(this string main, string start, string finish, bool preserve = false, int index = 0) { List<string> matches = new List<string>(); Match gbMatch = new Regex(Regex.Escape(start) + "(.+?)" + Regex.Escape(finish)).Match(main, index); while (gbMatch.Success) { matches.Add((preserve ? start : string.Empty) + gbMatch.Groups[1].Value + (preserve ? finish : string.Empty)); gbMatch = gbMatch.NextMatch(); } return matches; } public static string[] getBetweenAllBackwards(this string main, string strstart, string strend, bool preserve = false) { List<string> all = Reverse(main).GetBetweenAll(Reverse(strend), Reverse(strstart), preserve); for (int i = 0; i < all.Count; i++) { all[i] = Reverse(all[i]); } return all.ToArray(); } public static string Reverse(string s) { char[] charArray = s.ToCharArray(); Array.Reverse(charArray); return new string(charArray); }
4f0b7a7d7a169f6d6c634407173b370c6e646290
C#
yusuflateef/dotnetRecap
/CustomerAppDAL/UOW/UnitOfWorkMem.cs
2.71875
3
using System; using CustomerAppDAL.Context; using CustomerAppDAL.Repositories; namespace CustomerAppDAL.UOW { public class UnitOfWorkMem : IUnitOfWork { public ICustomerRepository CustomerRepository { get; internal set; } private InMemoryContext context; public UnitOfWorkMem() { context = new InMemoryContext(); CustomerRepository = new CustomerRepositoryEFMemory(context); } public int Complete() { //The number of objects written to the underlying database. return context.SaveChanges(); } public void Dispose() { context.Dispose(); } } }
3980fde287157df5cf313577d38a6c906433702b
C#
rkvtsn/sch-dev
/Mvc_Schedule.Models/DataModels/Repositories/RepositorySubjects.cs
2.625
3
using System.Collections.Generic; using System.Data.Entity.Migrations; using System.Linq; using System.Text; using System.Web; using Mvc_Schedule.Models.DataModels.Entities; namespace Mvc_Schedule.Models.DataModels.Repositories { public class RepositorySubjects : RepositoryBase<ConnectionContext, Subject> { public RepositorySubjects(ConnectionContext ctx) : base(ctx) { QueryPager = from x in _ctx.Subjects orderby x.Title select x; } public TxtUploaderResultModel AddListFromTxt(HttpPostedFileBase data) { return TxtUploader.AddListFromTxt(data, Encoding.GetEncoding(1251), subjectName => { var subject = new Subject { Title = subjectName }; this.Add(subject); return true; }); } public IList<Subject> List() { return _ctx.Subjects.ToList(); } public bool IsDublicate(Subject subject) { var first = (from x in _ctx.Subjects where x.Title == subject.Title select x).FirstOrDefault(); if (first == null) { return false; } return first.SubjectId != subject.SubjectId; } public void Add(Subject subject) { subject.Title = subject.Title.Trim(); _ctx.Subjects.AddOrUpdate(x => x.Title, subject); } public Subject Get(int id) { return _ctx.Subjects.Find(id); } public void Remove(int id) { var old = Get(id); if (old != null) { _ctx.Subjects.Remove(old); } } public void Edit(Subject subject) { var old = Get(subject.SubjectId); if (old != null) { old.Title = subject.Title; } } public void Add(string subjectName) { var subject = new Subject { Title = subjectName }; this.Add(subject); } } }
b9ca4fce9c9710c4d16dfe50bca7f02bbdc6478e
C#
Devjoeri/Memory
/App/Memory/Memory/MemoryGrid.cs
2.640625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; namespace Memory { /// <summary> /// Hier maken we en setten we alle images voor het memory spel /// plaatsen we de kaarten gerandomized en omgedraait. /// De sidebar is apart gezet in een class /// </summary> class MemoryGrid { private Grid grid; private Sidebar sidebar; private int rows, columns; public object RowDefinitions { get; internal set; } private int cardsTurned = 0; private Card turnedCard; private object pic; private Image oldcard; private List<Card> images; private int countedCards = 0; Highscore _highscore; private INavigator _navigator; public MemoryGrid(Grid sidebar, Grid grid, int colums, int rows, string[] setup, INavigator navigator) { this.grid = grid; this.rows = rows; this.columns = colums; this._navigator = navigator; this.sidebar = new Sidebar(sidebar, setup, images, _navigator, this); AddImages(); initGrid(colums, rows); } /// <summary> /// Hier maken we de rows en columns aan voor de game grid /// </summary> /// <param name="colums"></param> /// <param name="rows"></param> private void initGrid(int colums, int rows) { for(int i = 0; i < rows; i++) { grid.RowDefinitions.Add(new RowDefinition()); } for (int i = 0; i < colums; i++) { grid.ColumnDefinitions.Add(new ColumnDefinition()); } } /// <summary> /// Hier plaatsen we alle background images to op de plek voor de kaarten, en geven we ze een tag mee /// </summary> private void AddImages() { images = GetImagesList(); for (int row = 0; row < rows; row++) { for(int column = 0; column < columns; column++) { Image backgroundImage = new Image(); backgroundImage.Source = new BitmapImage(new Uri("Images/front.png", UriKind.Relative)); //backgroundImage.Source = images.First().getImage(); backgroundImage.Tag = images.First(); images.RemoveAt(0); backgroundImage.MouseDown += new MouseButtonEventHandler(CardClick); Grid.SetColumn(backgroundImage, column); Grid.SetRow(backgroundImage, row); grid.Children.Add(backgroundImage); } } } /// <summary> /// Hier randomize we de plaatjes voor de kaarten als je ze omdraait /// </summary> /// <returns></returns> private List<Card> GetImagesList() { List<Card> images = new List<Card>(); for(int i = 0; i < rows*columns; i++) { int imageNr = i % (rows * columns / 2) + 1; //now variable ImageSource source = new BitmapImage(new Uri("Images/"+imageNr+".png", UriKind.Relative)); images.Add(new Card(source, imageNr)); } Random random = new Random(); int n = images.Count; for (int i = 0; i < images.Count; i++) { int rnd = random.Next(i + 1); Card value = images[rnd]; images[rnd] = images[i]; images[i] = value; } return images; } /// <summary> /// Een event handler die af gaat als iemand op een kaart klikt, daar na slaan we de eerste op, /// en gaan we kijken of de tweede keuze overeen komt met de eerste. /// Zowel, worden er punten toegevoegt aan de speler die aan de beurd is. /// Zo niet, dan draaien we de kaarten weer om en is de volgende aan de beurt. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void CardClick(object sender, MouseButtonEventArgs e) { //need to refactor this CardClick part! Image card = (Image)sender; Card front = (Card)card.Tag; if (!front.isSelected()) { front.select(); card.Source = front.flipCard(); cardsTurned++; } if (cardsTurned == 1) { oldcard = card; turnedCard = front; } if (cardsTurned == 2) { string player = sidebar.getTurn(); if (front.getNumber() == turnedCard.getNumber() && front.isSelected() && turnedCard.isSelected()) { sidebar.AddPoint(player); countedCards += 2; if (countedCards == (rows*columns)) { _highscore = new Highscore(); _highscore.addScore(new PlayerScore(player, sidebar.getPlayerScore(player))); winner winnerWindow = new winner(_navigator, player); winnerWindow.ShowDialog(); } } else { await Task.Run(() => { Thread.Sleep(500); }); turnedCard.deselect(); front.deselect(); oldcard.Source = turnedCard.flipCard(); card.Source = front.flipCard(); } sidebar.setTurn(player); cardsTurned = 0; } } } }
035da99969dd19d65b5df775060edf524c2e47ba
C#
jharnack79/EECS393Project
/GetThiqqq/GetThiqqq/Repository/ForumTopicRepository.cs
2.796875
3
using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Text; using GetThiqqq.Constants; using GetThiqqq.Models; using GetThiqqq.Services; namespace GetThiqqq.Repository { public interface IForumTopicRepository { List<ForumTopic> GetAllForumTopics(); ForumTopic GetForumTopicById(int id); ForumTopic CreateNewForumTopic(CreateTopicViewModel createTopicViewModel); } public class ForumTopicRepository : IForumTopicRepository { private readonly ForumPostRepository _forumPostRepository; public ForumTopicRepository(ForumPostRepository forumPostRepository) { _forumPostRepository = forumPostRepository; } public List<ForumTopic> GetAllForumTopics() { var sqlConnection = new SqlConnection(DatabaseConstants.ConnectionString); var cmd = new SqlCommand(); sqlConnection.Open(); cmd.CommandText = "Select * from ForumTopic"; cmd.Connection = sqlConnection; var reader = cmd.ExecuteReader(); var listOfTopics = new List<ForumTopic>(); while (reader.Read()) { listOfTopics.Add(new ForumTopic { TopicId = (int)reader["Id"], UserId = (int)reader["UserId"], TopicText = (string)reader["TopicText"], TopicTitle = (string)reader["TopicTitle"], TopicPosts = _forumPostRepository.GetForumPostByTopicId((int)reader["Id"]) }); } return listOfTopics; } public ForumTopic CreateNewForumTopic(CreateTopicViewModel createTopicViewModel) { var sqlConnection = new SqlConnection(DatabaseConstants.ConnectionString); var cmd = new SqlCommand(); sqlConnection.Open(); cmd.CommandText = "Select Count(*) from ForumTopic"; cmd.Connection = sqlConnection; var newId = (int) cmd.ExecuteScalar() + 1; cmd.CommandText = "SET IDENTITY_INSERT [GetThiqq].[dbo].[ForumTopic] ON INSERT INTO [GetThiqq].[dbo].[ForumTopic] (ID, TopicTitle, TopicText, UserId) " + "Values(" + newId + ", '" + createTopicViewModel.TopicTitle + "', '" + createTopicViewModel.TopicText + "', '" + createTopicViewModel.UserId + "'); " + "SET IDENTITY_INSERT[GetThiqq].[dbo].[ForumTopic] OFF"; if (cmd.ExecuteNonQuery() != 1) return null; var forumTopic = new ForumTopic { TopicId = newId, UserId = createTopicViewModel.UserId, TopicTitle = createTopicViewModel.TopicTitle, TopicText = createTopicViewModel.TopicText, Tags = null, TopicPosts = new List<ForumPost>() }; sqlConnection.Close(); return forumTopic; } public ForumTopic GetForumTopicById(int id) { var sqlConnection = new SqlConnection(DatabaseConstants.ConnectionString); var cmd = new SqlCommand(); sqlConnection.Open(); cmd.CommandText = "Select * from ForumTopic Where Id = " + id; cmd.Connection = sqlConnection; var reader = cmd.ExecuteReader(); if (!reader.Read()) return null; var forumTopic = new ForumTopic { TopicId = id, TopicTitle = (string)reader["TopicTitle"], TopicText = (string)reader["TopicText"], TopicPosts = _forumPostRepository.GetForumPostByTopicId(id), Tags = null, }; sqlConnection.Close(); return forumTopic; } } }
108914098f0f5b7201c96a9b7ba2b08ec7ed5215
C#
j-a-rave/monogame-demo
/MGLib/ParallaxManager.cs
2.75
3
/*a class for parallax-scrolling environment elements and backgrounds, as well as a manager for them, using Camera2D. Jacob Rave Dec 2015*/ using System; using System.Collections.Generic; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace MGLib { public static class ParallaxManager { //list of backgrounds, arbitrary # public static List<ParallaxBackground> Backgrounds = new List<ParallaxBackground>(); public static Vector2 prevPos = Vector2.Zero; //storing camera positions. public static Rectangle viewportRect = new Rectangle(-2560, -2560, 5120, 5120); //TODO figure out infinite scrolling... public static Vector2 viewportLoc = new Vector2(viewportRect.X, viewportRect.Y); public static void UpdateParallaxScrolling(GraphicsDevice gDevice) { foreach (ParallaxBackground pb in Backgrounds) { pb.loc += (Camera2D.position - prevPos) * pb.distanceScale; } prevPos = Camera2D.position; } #region AddBackground overloads public static void AddBackground(Game game, string textureName, float distanceScale) { AddBackground(game, textureName, distanceScale, Vector2.Zero, true); } public static void AddBackground(Game game, string textureName, float distanceScale, Vector2 loc, bool isTiled) { AddBackground(new ParallaxBackground(game, textureName, distanceScale, loc, isTiled)); } public static void AddBackground(ParallaxBackground pb) { Backgrounds.Add(pb); } #endregion } public class ParallaxBackground : DrawableGameComponent { public Vector2 loc; //the initial position it's drawn at. public float distanceScale; //usually between 0.0 & 1.0: 0.0 is at player distance, 1.0 is a static background. > 1.0 runs ahead of the player, < 0.0 would pass backwards i.e. foreground. SpriteBatch spriteBatch; Texture2D texture; string textureName; //saved to be referenced later on in LoadContent. SamplerState tileMode; //we'll set to LinearWrap if it's tiled, and null if it isn't. public ParallaxBackground(Game game, string textureName, float distanceScale, Vector2 loc, bool isTiled) : base(game) { this.distanceScale = distanceScale; this.loc = loc; this.textureName = textureName; if (isTiled) { tileMode = SamplerState.LinearWrap; } else { tileMode = null; } //finally, adds itself to the components game.Components.Add(this); } protected override void LoadContent() { this.spriteBatch = new SpriteBatch(Game.GraphicsDevice); this.texture = Game.Content.Load<Texture2D>(this.textureName); base.LoadContent(); } public override void Draw(GameTime gameTime) { spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, this.tileMode, DepthStencilState.Default, null, null, MGLib.Camera2D.GetTransformation(Game.GraphicsDevice)); spriteBatch.Draw(this.texture, ParallaxManager.viewportLoc + this.loc, ParallaxManager.viewportRect, Color.DarkSlateGray); spriteBatch.End(); base.Draw(gameTime); } } }
cd760bd41067e8c34dd1571e804985bc3fdc93b2
C#
vladkinoman/information-security
/src/Lab_2(CaesarCipher)/MainForm.cs
3.078125
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 InfoProtection { public partial class MainForm : Form { public MainForm() { InitializeComponent(); } class CaesarCipher { // count of unicode chars private int n = 65536; public int Shift { get; set; } public string Encode(string sInput) { string sOutput = ""; for (int i = 0; i < sInput.Length; i++) { sOutput += (Convert.ToChar(((sInput[i]) + Shift) % n)); } return sOutput; } public string Encode(string sInput, ProgressBar progressCoding) { string sOutput = ""; for (int i = 0; i < sInput.Length; i++) { sOutput += (Convert.ToChar(((sInput[i]) + Shift) % n)); progressCoding.Value++; } return sOutput; } public string Decode(string sInput) { string sOutput = ""; for (int i = 0; i < sInput.Length; i++) sOutput += (Convert.ToChar(((sInput[i]) - Shift + n) % n)); return sOutput; } public string Decode(string sInput, ProgressBar progressCoding) { string sOutput = ""; for (int i = 0; i < sInput.Length; i++) { sOutput += (Convert.ToChar(((sInput[i]) - Shift + n) % n)); progressCoding.Value++; } return sOutput; } } CaesarCipher newCipher; delegate string Func(string s); void DoFunction(Func f, CaesarCipher newCipher, TextBox textBoxInput, TextBox textBoxOutput) { string sInput = ""; string sOutput = ""; sInput = textBoxInput.Text; newCipher.Shift = int.Parse(textBoxShift.Text); progressCoding.Value = 0; progressCoding.Maximum = sInput.Length; sOutput = f(sInput); textBoxOutput.Text = sOutput; } private void buttonEncrypt_Click(object sender, EventArgs e) { if (textBoxForInput.TextLength != 0) { newCipher = new CaesarCipher(); DoFunction(newCipher.Encode, newCipher,textBoxForInput,textBoxCipher); } else MessageBox.Show("Введите данные для зашифровывания!"); } private void buttonDecrypt_Click(object sender, EventArgs e) { if (textBoxCipher.TextLength != 0) { newCipher = new CaesarCipher(); DoFunction(newCipher.Decode, newCipher, textBoxCipher, textBoxResult); } else MessageBox.Show("Введите данные для расшифровывания!"); } private void buttonClear_Click(object sender, EventArgs e) { textBoxForInput.Text = ""; textBoxCipher.Text = ""; textBoxResult.Text = ""; } } }
d73aaf0fb2901ef97314169a928565e611b9c22e
C#
r-Larch/MouseTrap
/MouseTrap/src/Logger.cs
2.828125
3
using System.ComponentModel; using System.Diagnostics; using System.Text; using MouseTrap.Models; namespace MouseTrap; internal class Logger : SettingsFile { private readonly string _datetimeFormat = "yyyy-MM-dd HH:mm:ss.fff"; private readonly object _fileLock = new(); public readonly string LogFilename; public static readonly Logger Log = new(); public Logger() { LogFilename = Path.ChangeExtension(SavePath($"{App.Name}"), ".log"); var logHeader = LogFilename + " is created."; if (!File.Exists(LogFilename)) { WriteLine(DateTime.Now.ToString(_datetimeFormat) + " " + logHeader, false); } } /// <summary> /// Log a DEBUG message /// </summary> /// <param name="text">Message</param> public void Debug(string text) { WriteFormattedLog(LogLevel.Debug, text); } /// <summary> /// Log an ERROR message /// </summary> /// <param name="text">Message</param> public void Error(string text) { WriteFormattedLog(LogLevel.Error, text); } public static void Error(string message, Exception? e) { var msg = new StringBuilder(); if (e is null) msg.Append(message); while (e != null) { var hResult = (e is Win32Exception win32) ? win32.NativeErrorCode : e.HResult; msg.AppendLine($"[0x{0x80070000 + hResult:X}] {e.GetType().FullName}: {e.Message}\r\n{e.StackTrace}"); e = e.InnerException; } Log.Error(msg.ToString()); if (OperatingSystem.IsWindows()) { EventLog.WriteEntry(App.Name, msg.ToString(), EventLogEntryType.Error); } } /// <summary> /// Log a FATAL ERROR message /// </summary> /// <param name="text">Message</param> public void Fatal(string text) { WriteFormattedLog(LogLevel.Fatal, text); } /// <summary> /// Log an INFO message /// </summary> /// <param name="text">Message</param> public void Info(string text) { WriteFormattedLog(LogLevel.Info, text); } /// <summary> /// Log a TRACE message /// </summary> /// <param name="text">Message</param> public void Trace(string text) { WriteFormattedLog(LogLevel.Trace, text); } /// <summary> /// Log a WARNING message /// </summary> /// <param name="text">Message</param> public void Warning(string text) { WriteFormattedLog(LogLevel.Warning, text); } private void WriteLine(string text, bool append = true) { if (!string.IsNullOrEmpty(text)) { lock (_fileLock) { try { var file = new FileInfo(LogFilename); if (file.Exists && file.Length > (1024 * 1024 * 3)) { file.Delete(); } using var fs = new FileStream(LogFilename, append ? FileMode.Append : FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite | FileShare.Delete); using var writer = new StreamWriter(fs, Encoding.UTF8); writer.WriteLine(text); } catch (Exception e) { System.Diagnostics.Debug.WriteLine(e); } } } } private void WriteFormattedLog(LogLevel level, string text) { var pretext = level switch { LogLevel.Trace => System.DateTime.Now.ToString(_datetimeFormat) + " [TRACE] ", LogLevel.Info => System.DateTime.Now.ToString(_datetimeFormat) + " [INFO] ", LogLevel.Debug => System.DateTime.Now.ToString(_datetimeFormat) + " [DEBUG] ", LogLevel.Warning => System.DateTime.Now.ToString(_datetimeFormat) + " [WARNING] ", LogLevel.Error => System.DateTime.Now.ToString(_datetimeFormat) + " [ERROR] ", LogLevel.Fatal => System.DateTime.Now.ToString(_datetimeFormat) + " [FATAL] ", _ => "" }; WriteLine(pretext + text); } private enum LogLevel { Trace, Info, Debug, Warning, Error, Fatal } }
b4f167a5ff97a26bce0db92156ae5ddb549e5ba7
C#
shendongnian/download4
/code4/696981-30118206-116030877-2.cs
3.296875
3
bool IsTheSameCellValue(int column, int row) { DataGridViewCell cell1 = dataGridView1[column, row]; DataGridViewCell cell2 = dataGridView1[column, row - 1]; if (cell1.Value == null || cell2.Value == null) { return false; } return cell1.Value.ToString() == cell2.Value.ToString(); }