text
stringlengths
13
6.01M
using Com.Colin.Forms.Properties; using System; using System.Collections; using System.Drawing; using System.Drawing.Drawing2D; using System.IO; using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Text; using System.Windows.Forms; namespace Com.Colin.Forms.Common { public class CommonFuc { // [DllImport("gdi32.dll")] // public static extern int CreateRoundRectRgn(int x1, int y1, int x2, int y2, int x3, int y3); // [DllImport("user32.dll")] // public static extern int SetWindowRgn(IntPtr hwnd, int hRgn, Boolean bRedraw); [DllImport("gdi32.dll", EntryPoint = "DeleteObject", CharSet = CharSet.Ansi)] public static extern int DeleteObject(int hObject); [DllImport("user32.dll", EntryPoint = "GetWindowLong")] public static extern long GetWindowLong(IntPtr hwnd, int nIndex); [DllImport("user32.dll", EntryPoint = "SetWindowLong")] public static extern long SetWindowLong(IntPtr hwnd, int nIndex, long dwNewLong); [DllImport("user32.dll", CharSet = CharSet.Auto)] private static extern int SetWindowPos(IntPtr hWnd, int hWndInsertAfter, int x, int y, int Width, int Height, int flags); [DllImportAttribute("gdi32.dll")] public static extern IntPtr CreateRoundRectRgn(int nLeftRect, int nTopRect, int nRightRect, int nBottomRect, int nWidthEllipse, int nHeightEllipse); [DllImportAttribute("user32.dll")] public static extern int SetWindowRgn(IntPtr hWnd, IntPtr hRgn, bool bRedraw); public const int GWL_EXSTYLE = -20; public const int WS_EX_TRANSPARENT = 0x20; public const int WS_EX_LAYERED = 0x80000; public const int LWA_ALPHA = 2; public const int GWL_STYLE = (-16); public const int WS_CAPTION = 0xC00000; public static int hRgn = 0; public static int rgnRadius = 6; public static bool IsDrawAll = true; [DllImport("user32.dll")] public static extern bool ReleaseCapture(); [DllImport("user32.dll")] public static extern bool SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam); public const int WM_SYSCOMMAND = 0x0112; public const int SC_MOVE = 0xF010; public const int HTCAPTION = 0x0002; public static void MouseDown(Form form) { ReleaseCapture(); SendMessage(form.Handle, WM_SYSCOMMAND, SC_MOVE + HTCAPTION, 0); } /// <summary> /// 以07:00:00-1的格式显示日期 /// </summary> /// <param name="standardTime">用以帮助判断第一天还是第二天的基准时间</param> /// <param name="showTime"></param> /// <returns></returns> public static string ShowTime(DateTime standardTime, DateTime showTime) { int days = (showTime.Date - standardTime.Date).Days; if (days > 0) { return showTime.ToString("HH:mm:ss") + "-" + (days + 1).ToString() + "日"; } else { return showTime.ToString("HH:mm:ss"); } } /// <summary> /// 以07:00-1的格式显示日期,只显示到分钟 /// </summary> /// <param name="standardTime">用以帮助判断第一天还是第二天的基准时间</param> /// <param name="showTime"></param> /// <returns></returns> public static string ShowShortTime(DateTime standardTime, DateTime showTime) { int days = (showTime.Date - standardTime.Date).Days; if (days > 0) { return showTime.ToString("HH:mm") + "-" + (days + 1).ToString() + "日"; } else { return showTime.ToString("HH:mm"); } } //获取文件创建时间 public static string GetFileCreateTime(string fileName) { //string result = ""; //FileInfo fi = new FileInfo(fileName); //result = fi.LastWriteTime.ToString("yyyy-MM-dd HH:mm"); string result = ""; FileInfo fi = new FileInfo(fileName); result = fi.Name; DateTime time = new DateTime( int.Parse(result.Substring(0, 4)), int.Parse(result.Substring(4, 2)), int.Parse(result.Substring(6, 2)), int.Parse(result.Substring(8, 2)), int.Parse(result.Substring(10, 2)), int.Parse(result.Substring(12, 2))); result = time.ToString(); return result; } #region MD5函数 /// <summary> /// MD5函数 /// </summary> /// <param name="str">原始字符串</param> /// <returns>MD5结果</returns> public static string MD5(string str) { byte[] b = Encoding.Default.GetBytes(str); b = new MD5CryptoServiceProvider().ComputeHash(b); string ret = ""; for (int i = 0; i < b.Length; i++) ret += b[i].ToString("x").PadLeft(2, '0'); return ret; } #endregion public static void FillRoundRectangle(Graphics g, Rectangle rectangle, Color backColor, int r) { rectangle = new Rectangle(rectangle.X, rectangle.Y, rectangle.Width - 1, rectangle.Height - 1); Brush b = new SolidBrush(backColor); g.FillPath(b, CommonFuc.GetRoundRectangle(rectangle, r)); } /// <summary> /// 根据普通矩形得到圆角矩形的路径 /// </summary> /// <param name="rectangle">原始矩形</param> /// <param name="r">半径</param> /// <returns>图形路径</returns> public static GraphicsPath GetRoundRectangle(Rectangle rectangle, int r) { int l = 2 * r; // 把圆角矩形分成八段直线、弧的组合,依次加到路径中 GraphicsPath gp = new GraphicsPath(); //右上角 gp.AddLine(new Point(rectangle.X + r, rectangle.Y), new Point(rectangle.Right - r, rectangle.Y)); gp.AddArc(new Rectangle(rectangle.Right - l, rectangle.Y, l, l), 270F, 90F); //右下角 gp.AddLine(new Point(rectangle.Right, rectangle.Y + r), new Point(rectangle.Right, rectangle.Bottom)); //左下角 gp.AddLine(new Point(rectangle.Right, rectangle.Bottom), new Point(rectangle.X, rectangle.Bottom)); //左上角 gp.AddLine(new Point(rectangle.X, rectangle.Bottom - r), new Point(rectangle.X, rectangle.Y + r)); gp.AddArc(new Rectangle(rectangle.X, rectangle.Y, l, l), 180F, 90F); return gp; } public static void FillRoundAllRectangle(Graphics g, Rectangle rectangle, Color backColor, int r) { rectangle = new Rectangle(rectangle.X, rectangle.Y, rectangle.Width - 1, rectangle.Height - 1); Brush b = new SolidBrush(backColor); g.FillPath(b, CommonFuc.GetRoundRectangle(rectangle, r)); } public static GraphicsPath GetRoundAllRectangle(Rectangle rectangle, int r) { int l = 2 * r; // 把圆角矩形分成八段直线、弧的组合,依次加到路径中 GraphicsPath gp = new GraphicsPath(); gp.AddLine(new Point(rectangle.X + r, rectangle.Y), new Point(rectangle.Right - r, rectangle.Y)); gp.AddArc(new Rectangle(rectangle.Right - l, rectangle.Y, l, l), 270F, 90F); gp.AddLine(new Point(rectangle.Right, rectangle.Y + r), new Point(rectangle.Right, rectangle.Bottom - r)); gp.AddArc(new Rectangle(rectangle.Right - l, rectangle.Bottom - l, l, l), 0F, 90F); gp.AddLine(new Point(rectangle.Right - r, rectangle.Bottom), new Point(rectangle.X + r, rectangle.Bottom)); gp.AddArc(new Rectangle(rectangle.X, rectangle.Bottom - l, l, l), 90F, 90F); gp.AddLine(new Point(rectangle.X, rectangle.Bottom - r), new Point(rectangle.X, rectangle.Y + r)); gp.AddArc(new Rectangle(rectangle.X, rectangle.Y, l, l), 180F, 90F); return gp; } public static void DrawFromTitle(Graphics g, string title, int width, int height) { //画表头 Brush b = new SolidBrush(Color.FromArgb(228, 238, 248)); int tHeight = 47; int left = 20; int top = 0; int r = 1; int buttom = 88; //画左右上角的圆角矩形 //g.SmoothingMode = SmoothingMode.AntiAlias; Rectangle rt = new Rectangle(0, top, width, tHeight); g.FillRectangle(new SolidBrush(Color.FromArgb(0, 102, 187)), rt); //CommonFuc.FillRoundRectangle(g, rt, Color.FromArgb(0, 102, 187), r); rt = new Rectangle(1, top, width - 2, tHeight); //CommonFuc.FillRoundRectangle(g, rt, Color.FromArgb(45, 145, 226), r); g.FillRectangle(new SolidBrush(Color.FromArgb(45, 145, 226)), rt); //画线 g.SmoothingMode = SmoothingMode.Default; Pen pen = new Pen(new SolidBrush(Color.FromArgb(119, 204, 255))); g.DrawLine(pen, r, top, width - r, top); //画背景颜色 rt = new Rectangle(0, tHeight, width, height - tHeight); g.FillRectangle(b, rt); if (IsDrawAll) { //画矩形 pen = new Pen(new SolidBrush(Color.FromArgb(165, 203, 248))); rt = new Rectangle(left, left + tHeight, width - 2 * left, height - tHeight - left - buttom); g.DrawRectangle(pen, rt); b = new SolidBrush(Color.FromArgb(246, 249, 254)); rt = new Rectangle(left + 1, left + tHeight + 1, width - 2 * left - 1, height - tHeight - left - buttom - 1); g.FillRectangle(b, rt); } Font font = new Font("微软雅黑", 14); g.DrawString(title, font, Brushes.White, left, (tHeight - font.Height) / 2); } /// <summary> /// 设置窗体的圆角矩形 /// </summary> /// <param name="form">需要设置的窗体</param> /// <param name="rgnRadius">圆角矩形的半径</param> public static void SetFormRoundRectRgn(Form form, int rgnRadius) { //int hRgn = 0; //hRgn = CreateRoundRectRgn(0, 0, form.Width, form.Height, rgnRadius, rgnRadius); //SetWindowRgn(form.Handle, hRgn, true); //DeleteObject(hRgn); } public static void SetFormRoundRectRgn(Form form) { //SetWindowLong(form.Handle, GWL_STYLE, GetWindowLong(form.Handle, GWL_STYLE) & ~WS_CAPTION).ToString(); //SetWindowPos(form.Handle, 0, 0, 0, 0, 0, 1 | 2); //IntPtr regionHandle = CreateRoundRectRgn(0, 0, form.Width, form.Height, 20, 20); //Region roundRegion = null; //roundRegion = Region.FromHrgn(regionHandle); //SetWindowRgn(form.Handle, regionHandle, true); } /// <summary> /// /// </summary> /// <param name="container"></param> /// <param name="g"></param> public static void drawHRV(Control container, Graphics g) { // 画图 int baseHeight = container.Height; int baseWidth = container.Width; int top = (int)(baseHeight * 0.1); int left = (int)(baseWidth * 0.1); int bmpHeight = (int)(baseHeight * 0.8); int bmpWidth = (int)(baseWidth * 0.8); Pen grayPen = new Pen(Color.LightGray, 1); g.DrawRectangle(grayPen, left, top, bmpWidth, bmpHeight); Font font = new Font("微软雅黑", 10); // 画Y轴 for (int j = 0; j < 6; j++) { g.DrawLine(grayPen, left - 5, top + (float)((1 - j * 0.19) * bmpHeight), left + bmpWidth, top + (float)((1 - j * 0.19) * bmpHeight)); g.DrawString(40 + 10 * j + "", font, Brushes.Black, left - 25, top + (float)((1 - j * 0.19) * bmpHeight) - 9); } string[] xAxis = new string[] { "00:30", "01:00", "01:30", "02:00" }; // 画X轴 for (int i = 0; i < 4; i++) { g.DrawLine(grayPen, left + (float)((i + 1) * 0.25 * bmpWidth), top, left + (float)((i + 1) * 0.25 * bmpWidth), top + bmpHeight); g.DrawString(xAxis[i], font, Brushes.Black, left + (float)((i + 1) * 0.25 * bmpWidth) - 15, top + bmpHeight + 2); } } /// <summary> /// 根据点击的按钮改变显示界面,模拟页签效果 /// </summary> /// <param name="map">页签模块集合</param> /// <param name="tabMap">页签是否显示集合</param> /// <param name="unCheckState">不选时样式</param> /// <param name="checkState">选中时样式</param> public static void displayTabByButton(Hashtable map, Hashtable tabMap = null, Hashtable unCheckState = null, Hashtable checkState = null) { // 遍历页签模块集合 foreach (Control button in map.Keys) { // 获取该页签是否显示 int state = (int)map[button]; if (state == 1) //显示 { if (tabMap != null) { ((Control)(tabMap[button])).Dock = DockStyle.Fill; ((Control)(tabMap[button])).Visible = true; } // 样式设置 if (checkState == null) { button.BackgroundImage = Resources._0130切片_63; button.ForeColor = Color.White; } else { button.BackgroundImage = (Image)checkState["BackgroundImage"]; button.ForeColor = (Color)checkState["ForeColor"]; } } else //不显示 { if (tabMap != null) { ((Control)(tabMap[button])).Visible = false; } // 样式设置 if (unCheckState == null) { button.BackgroundImage = Resources._0130切片_38; button.ForeColor = Color.Gray; } else { button.BackgroundImage = (Image)unCheckState["BackgroundImage"]; button.ForeColor = (Color)unCheckState["ForeColor"]; } } } } /// <summary> /// “页签”按钮点击处理 /// </summary> /// <param name="button"></param> public static void ButtonClickHandler(Button button, Hashtable map, Hashtable tabMap, int group = 0) { if ((int)map[button] == 1) return; ArrayList controls = new ArrayList(map.Keys); for (int i = 0; i < controls.Count; i++) { Control key = (Control)controls[i]; if (key.Equals(button)) { map[key] = 1; } else { map[key] = 0; } } switch (group) { case 0: displayTabByButton(map, tabMap); break; case 1: displayTabByButton(map, tabMap, new Hashtable() { { "BackgroundImage",null}, { "ForeColor",Color.Black} }); break; case 2: displayTabByButton(map, tabMap, null, new Hashtable() { { "BackgroundImage",Resources._0130切片_36}, { "ForeColor",Color.White} }); break; } } /// <summary> /// 递归算法获取界面 /// </summary> /// <param name="control"></param> /// <returns></returns> public static Control getUIForm(Control control) { if (control is Form) return control; if (control.Parent != null) return getUIForm(control.Parent); return control; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using SETrastornoBipolar.Models; using SETrastornoBipolar.Controllers.Objs; namespace SETrastornoBipolar.Controllers { public class HechosController : Controller { TrastornoBipolarDBEntities db = new TrastornoBipolarDBEntities(); // GET: Hechos public ActionResult Individuo() { var list = (db.TB_Hechos.Where(x => x.Activo == true)).ToList(); return View(); } public ActionResult TestBipolar() { var list = (from rp in db.TB_RespuestasxPreguntas join p in db.TB_Premisas on new { IdPremisa_pk = rp.IdPregunta_fk } equals new { IdPremisa_pk = p.IdPremisa_pk } join por in db.TB_Ponderados on new { IdPonderado_fk = rp.IdPonderado_fk } equals new { IdPonderado_fk = por.IdPonderado_pk } where rp.Premisa == true select new { IdRespuestaxPregunta_pk = rp.IdRespuestaxPregunta_pk, IdPregunta_fk = rp.IdPregunta_fk, IdOpcionRespuesta_fk = rp.IdOpcionRespuesta_fk, IdPonderado_fk = rp.IdPonderado_fk, Descripcion = rp.Descripcion, FechaRegistra = rp.FechaRegistra, Premisa = rp.Premisa, Pregunta = p.Descripcion, PonderadoPregunta = p.TB_Ponderados.Valor, Respuestas = rp.TB_OpcionesRespuestas.Nombre, PonderadoRespuesta = por.Valor }).ToList(); return View(); } public ActionResult _ParcialPremisa() { List<ModelList> VarResult = new List<ModelList>(); var resul1 = (from rp in db.TB_RespuestasxPreguntas join p in db.TB_Premisas on new { IdPremisa_pk = rp.IdPregunta_fk } equals new { IdPremisa_pk = p.IdPremisa_pk } join por in db.TB_Ponderados on new { IdPonderado_fk = rp.IdPonderado_fk } equals new { IdPonderado_fk = por.IdPonderado_pk } where rp.Premisa == true select new { IdRespuestaxPregunta_pk = rp.IdRespuestaxPregunta_pk, IdPregunta_fk = rp.IdPregunta_fk, IdOpcionRespuesta_fk = rp.IdOpcionRespuesta_fk, IdPonderado_fk = rp.IdPonderado_fk, Descripcion = rp.Descripcion, FechaRegistra = rp.FechaRegistra, Premisa = rp.Premisa, Pregunta = p.Descripcion, PonderadoPregunta = p.TB_Ponderados.Valor, Respuestas = rp.TB_OpcionesRespuestas.Nombre, PonderadoRespuesta = por.Valor }).ToList(); foreach (var item in resul1) { VarResult.Add(new ModelList { IdRespuestaxPregunta = item.IdRespuestaxPregunta_pk, IdPregunta = item.IdPregunta_fk, IdOpcionRespuesta = item.IdOpcionRespuesta_fk, IdPonderado = item.IdPonderado_fk, DescripcionFT = item.Descripcion, FechaRegistraFe = item.FechaRegistra, Premisa1 = item.Premisa, Pregunta1 = item.Pregunta, PonderadoPregunta1 = item.PonderadoPregunta, Respuestas1 = item.Respuestas, PonderadoRespuesta1 = item.PonderadoRespuesta }); } ViewBag.Data = VarResult; return PartialView("_ParcialPremisa", VarResult); //View(VarResult); } } }
using Microsoft.Data.SqlClient; using MySqlConnector; using Npgsql; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using static EasyWebApp.Data.Consts.AppConst; namespace EasyWebApp.Data.Entities.ServiceWebEntities { public class UserDbInfo : BaseEntity, IBaseEntity { public string Guid { get; set; } public string UserId { get; set; } public DbSqlTypes DbType { get; set; } public string Server { get; set; } public string Username { get; set; } public string Password { get; set; } public string InitialCatalog { get; set; } public string FrontEndId { get; set; } public string BackEndId { get; set; } public string DownloadLinkApi { get; set; } public string DownloadLinkClientApp { get; set; } public string Status { get; set; } public string BussinessName { get; set; } public int ServerPort { get; set; } public string BuildConnStr() { if(DbType != null) { switch (DbType) { case DbSqlTypes.PostgreSQL: NpgsqlConnectionStringBuilder postgresBuilder = new NpgsqlConnectionStringBuilder(); postgresBuilder.Host = Server; postgresBuilder.Port = ServerPort; postgresBuilder.Database = InitialCatalog; postgresBuilder.Username = Username; postgresBuilder.Password = Password; return postgresBuilder.ConnectionString; case DbSqlTypes.MySQL: MySqlConnectionStringBuilder mySqlBuilder = new MySqlConnectionStringBuilder(); mySqlBuilder.Server = Server; mySqlBuilder.Port = (uint)ServerPort; mySqlBuilder.UserID = Username; mySqlBuilder.Password = Password; mySqlBuilder.Database = InitialCatalog; return mySqlBuilder.ConnectionString; default: SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(); builder.DataSource = string.Format("{0},{1}", this.Server, ServerPort); builder.UserID = this.Username; builder.Password = this.Password; builder.InitialCatalog = this.InitialCatalog; builder.ConnectTimeout = 10; return builder.ConnectionString; } } return ""; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Euler_Logic.Problems { public class Problem284 : ProblemBase { public override string ProblemName { get { return "284: Steady Squares"; } } public override string GetAnswer() { LookForSteadyS(8); return ""; } private List<int> _steady = new List<int>(); private void LookForSteadyS(int digitCount) { int min = (int)Math.Pow(14, digitCount - 1); int max = (int)Math.Pow(14, digitCount) - 1; for (int num = min; num <= max; num++) { var x = GetBase14(num, digitCount); var y = GetBase14(num * num, digitCount); bool isGood = true; for (int digit = 0; digit < digitCount; digit++) { if (x[digit] != y[digit]) { isGood = false; break; } } if (isGood) { _steady.Add(num); } } } private int[] GetBase14(int num, int digitCount) { var maxDigits = (int)Math.Log(num, 14); var digits = new int[Math.Max(maxDigits + 1, digitCount)]; var powerOf14 = (int)Math.Pow(14, maxDigits); for (int power = maxDigits; power >= 0; power--) { var divide = num / powerOf14; if (divide > 0) { num -= divide * powerOf14; digits[power] = divide; } powerOf14 /= 14; } return digits; } } }
using System; using System.Collections.Generic; using System.Text; namespace Aquamonix.Mobile.Lib.ViewModels { public class MapViewModel { public double longitude { get; set; } public double lattitude { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Task_1 { public static class SumArray { public static int Sum(this int[] arr, int n, int sum) { sum = 0; arr = new int[n]; for (int i = 0; i < arr.Length; i++) sum += arr[i]; return sum; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EBS.Query.DTO { public class OutInOrderItemDto { public int StoreId { get; set; } public int ProductId { get; set; } public string BarCode { get; set; } public string ProductCode { get; set; } public string ProductName { get; set; } /// <summary> /// 规格 /// </summary> public string Specification { get; set; } /// <summary> /// 单位 /// </summary> public string Unit { get; set; } public decimal LastCostPrice { get; set; } public decimal CostPrice { get; set; } /// <summary> /// 数量 /// </summary> public int Quantity { get; set; } public decimal Amount { get { return CostPrice * Quantity; } } /// <summary> /// 库存数量,出库单用 /// </summary> public int InventoryQuantity { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace State { abstract class RamboState { public abstract void Correr(); } }
using Discord; using Discord.Commands; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Discord.Audio; using NAudio.Wave; namespace Dontebot { class MinunBotti { DiscordClient discord; CommandService commands; Random rand; Random rand2; string[] uusinMeme; string[] randomTexts; string[] randomJanneRamble; public MinunBotti() { uusinMeme = new string[] { "memes/dirl.jpg", "memes/dsp.jpg", "memes/konkistadori.jpg", "memes/laff.jpg", "memes/normot.jpg", "memes/nothing.jpg", "memes/pepe.png", "memes/pitsu.jpg", "memes/ricky.jpg", "memes/rune.jpg", "memes/orkesteri.png", "memes/emepepe.jpg", "memes/taurain.jpg", "memes/pear.jpg,", "memes/warb.jpg", "memes/samys.jpg", "memes/fagg.jpg,", "memes/anime.jpg", "memes/ananas.jpg", "memes/ow.png", "memes/lolherald.jpg", "memes/rickysthougts.jpg", "memes/gay.jpg", "memes/uther.png", "memes/paskabingo.png", "memes/valveplaytesters.png", "memes/CSBull.jpg" }; rand = new Random(); randomTexts = new string[] { "Eipä ollu", "Kyllä oli", "En muista", "Jaa.com", "makkarakeitto on hyvää", "Jannenradiossa kuulee tämän hetken kuumimmat hitit", }; discord = new DiscordClient(x => { x.LogLevel = LogSeverity.Info; x.LogHandler = Log; }); discord.UsingCommands(x => { x.PrefixChar = '!'; x.AllowMentionPrefix = true; }); discord.UsingAudio(x => { x.Mode = AudioMode.Outgoing; }); commands = discord.GetService<CommandService>(); RegisterTextCommand(); RegisterPurgeCommand(); RegisterMemeCommand(); RegisterRollCommand(); RegisterEmtCommand(); commands.CreateCommand("moro") .Do(async (e) => { await e.Channel.SendMessage("Päivää" + e.User.Mention); }); commands.CreateCommand("keios") .Do(async (e) => { await e.Channel.SendMessage("Ville se ei vaan pärjää"); await e.Channel.SendMessage("Ville se pärjää"); }); commands.CreateCommand("hepu") .Do(async (e) => { await e.Channel.SendMessage("Minä pidän Dota 2 -videopelistä :''>"); }); commands.CreateCommand("haistvittu") .Do(async (e) => { await e.Channel.SendFile("donte/donte.jpg"); }); commands.CreateCommand("janne") .Do(async (e) => { rand2 = new Random(); randomJanneRamble = new string[1]; await e.Channel.SendMessage("Dota kakkosta pitäisi pelata ainoastaan kolmen promillen humalassa, tai ei ollenkaan."); await e.Channel.SendMessage("tippu just illidanilta epic glaivet"); }); discord.ExecuteAndWait(async () => { await discord.Connect("MzM0Njg0Nzg3MjQ5OTA1NjY2.DEkRig.U30TEMYSeU5EIkYuEy4HCaSLZoU", TokenType.Bot); }); } private void RegisterTextCommand() { commands.CreateCommand("teksti") .Do(async (e) => { int randomTextsIndex = rand.Next(randomTexts.Length); string textToPost = randomTexts[randomTextsIndex]; await e.Channel.SendMessage(textToPost); }); } private void RegisterMemeCommand() { commands.CreateCommand("meme") .Do(async (e) => { int randomMeme = rand.Next(uusinMeme.Length); string meemiPost = uusinMeme[randomMeme]; await e.Channel.SendFile(meemiPost); }); } private void RegisterPurgeCommand() { commands.CreateCommand("purge") .Parameter("purgeAmount") .Do(async (e) => { Message[] messagesToDelete; messagesToDelete = await e.Channel.DownloadMessages(Convert.ToInt32(e.GetArg("purgeAmount")) + 1); await e.Channel.DeleteMessages(messagesToDelete); await e.Channel.SendMessage(e.GetArg("purgeAmount") + "Viestit poistettu"); }); } private void RegisterRollCommand() { commands.CreateCommand("Noppa") .Do(async (e) => { Random random = new Random(); int randomNumero = random.Next(1, 7); await e.Channel.SendMessage(string.Format("Sinä pyöräytit lukeman {0} ;')",randomNumero)); }); } private void RegisterEmtCommand() { commands.CreateCommand("emt") .Do(async (e) => await e.Channel.SendFile("emt/en muista.png")); } private void Log(object sender, LogMessageEventArgs e) { Console.WriteLine(e.Message); } } }
using BenefitDeduction.Employees; using BenefitDeduction.Employees.FamilyMembers; using System; using System.Collections.Generic; using System.Text; namespace BenefitDeduction.EmployeeBenefitDeduction.Employees.Calculators { public abstract class DiscountCalculatorRepository: IDiscountCalculatorRepository { public virtual int CalculateDiscount(IEmployee employee) { if (employee.FirstName.StartsWith("A", StringComparison.CurrentCultureIgnoreCase)) { return 10; } return 0; } public virtual int CalculateDiscount(IFamilyMember familyMember) { if (familyMember.FirstName.StartsWith("A", StringComparison.CurrentCultureIgnoreCase)) { return 10; } return 0; } } }
using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CapaDatos { public class DSolicitudBienUso { private SqlConnection cn; public void InsertSolicitudBienDeUso(int cod_sc, int cod_pro_buso, int cantidad, int cod_mar) { using (cn = Conexion.ConexionDB()) { SqlCommand cmd = new SqlCommand("InsertSolicitudBienDeUso", cn) { CommandType = CommandType.StoredProcedure }; cmd.Parameters.AddWithValue("@cod_sc", cod_sc); cmd.Parameters.AddWithValue("@cod_pro_buso", cod_pro_buso); cmd.Parameters.AddWithValue("@cantidad", cantidad); cmd.Parameters.AddWithValue("@cod_mar", cod_mar); cmd.ExecuteNonQuery() ; cn.Close(); } } public void DeleteBienesPorSolcitudCompra(int cod_sc) { using (cn = Conexion.ConexionDB()) { SqlCommand cmd = new SqlCommand("DeleteBienesPorSolcitudCompra", cn) { CommandType = CommandType.StoredProcedure }; cmd.Parameters.AddWithValue("@cod_sc", cod_sc); cmd.ExecuteNonQuery(); cn.Close(); } } public DataTable GetBienesUsoEnSolicitudCompra(int cod_sc) { DataTable miTabla = new DataTable("1_buso_sc"); SqlDataAdapter adapter; using (cn = Conexion.ConexionDB()) { SqlCommand cmd = new SqlCommand("GetBienesUsoEnSolicitudCompra", cn) { CommandType = CommandType.StoredProcedure }; cmd.Parameters.AddWithValue("@cod_sc", cod_sc); adapter = new SqlDataAdapter(cmd); adapter.Fill(miTabla); } cn.Close(); return miTabla; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class OrbitCamera : MonoBehaviour { public Transform target; private Transform _myTransform; public float ms = 2.0f; public float offsetZ = 3.0f; public float offsetY = 0.0f; public float smooth = 2.0f; public Vector2 AngleLimit=new Vector2(-40,60); private float xRot; private float yRot; void Awake(){ _myTransform = transform; } // Use this for initialization void Start () { _myTransform.position = target.position - _myTransform.forward * offsetZ+_myTransform.up*offsetY; } void Update () { yRot += Input.GetAxis ("Mouse X") * ms; xRot -= Input.GetAxis ("Mouse Y") * ms; xRot = Mathf.Clamp (xRot, AngleLimit.x, AngleLimit.y); } // Update is called once per frame void LateUpdate(){ CameraMove (); } private void CameraMove(){ _myTransform.rotation = Quaternion.Euler (xRot, yRot, 0.0f); _myTransform.position = target.position - _myTransform.forward * offsetZ+_myTransform.up*offsetY; } }
/*********************************************************************** * Module: TypeOfUsage.cs * Author: Dragana Carapic * Purpose: Definition of the Class TypeOfUsage ***********************************************************************/ using System; namespace Model.Manager { public enum TypeOfUsage { Soba_za_pregled = 0, Soba_za_lezanje = 1, Operaciona_sala = 2 } }
using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.ModelConfiguration; namespace HospitalSystem.Models.Mapping { public class medicine_detailMap : EntityTypeConfiguration<medicine_detail> { public medicine_detailMap() { // Primary Key this.HasKey(t => t.MedicineDetailID); // Properties // Table & Column Mappings this.ToTable("medicine_detail", "teamwork"); this.Property(t => t.MedicineDetailID).HasColumnName("MedicineDetailID"); this.Property(t => t.MedicineID).HasColumnName("MedicineID"); this.Property(t => t.PrescriptionID).HasColumnName("PrescriptionID"); this.Property(t => t.MedicineNumber).HasColumnName("MedicineNumber"); // Relationships this.HasOptional(t => t.medicine) .WithMany(t => t.medicine_detail) .HasForeignKey(d => d.MedicineID); this.HasOptional(t => t.prescription) .WithMany(t => t.medicine_detail) .HasForeignKey(d => d.PrescriptionID); } } }
using System; using System.Collections.Generic; using System.Text; namespace TheClickerGame.Services.Services.ViewService { public class ViewService : IViewService { public bool WideView { get; set; } = true; } }
using Newtonsoft.Json; using System; namespace oAuth2JwtProfile { public class AuthResult { [JsonProperty(PropertyName = "access_token")] public String AccessToken { get; set; } [JsonProperty(PropertyName = "token_type")] public String TokenType { get; set; } [JsonProperty(PropertyName = "expires_in")] public String ExpiresIn { get; set; } } }
using System; using System.Collections.Generic; using System.Text; namespace CalculatorService.Domain.Models { public abstract class ResultOperationBase { } }
using System.ComponentModel; using System.Runtime.CompilerServices; namespace CortanaTimeTrack.ViewModels { public abstract class BaseViewModel : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; protected bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null) { if (Equals(storage, value)) { return false; } storage = value; OnPropertyChanged(propertyName); return true; } protected void OnPropertyChanged([CallerMemberName] string propertyName = null) { var eventHandler = PropertyChanged; if (eventHandler != null) { eventHandler(this, new PropertyChangedEventArgs(propertyName)); } } /* * Usage: * private bool _enabled; public bool Enabled { get { return _enabled; } set { SetProperty(ref _enabled, value); } } */ } }
namespace SubC.Attachments { using UnityEngine; [CreateAssetMenuAttribute(fileName = "New Parenting Many-to-One Attach Strategy", menuName = "Clingy/Attach Strategies/Parenting Many-to-One Strategy")] public class ParentingManyToOneStrategy : ManyToOneAttachStrategy { public new enum Categories { Parent, Children } protected override void Reset() { base.Reset(); // reattachWhenParamsUpdated = true; } public override string GetLabelForRoot() { return "Parent"; } public override string GetLabelForLeaves() { return "Children"; } public override string GetLabelForLeaf() { return "Child"; } protected override void ConnectLeaf(AttachObject root, AttachObject leaf) { leaf.seedObject.transform.SetParent(root.seedObject.transform); } protected override void DisconnectLeaf(AttachObject root, AttachObject leaf) { leaf.seedObject.transform.SetParent(null); } } }
using System; using System.Collections; using System.Collections.Generic; using Microsoft.Build.Utilities; using Microsoft.TeamFoundation.Client; using Microsoft.TeamFoundation.VersionControl.Client; namespace DotNetNuke.MSBuild.Tasks { public class TfsComments : Task { public string Server { get; set; } public string Root { get; set; } public string Committer { get; set; } public override bool Execute() { Server = ""; //TODO: Fill the TFS Server Root = @"$/DotNetNuke/src/DotNetNuke_CS/"; Committer = ""; //TODO: Fill the committer username. #pragma warning disable 612,618 TeamFoundationServer tfs = TeamFoundationServerFactory.GetServer(Server); #pragma warning restore 612,618 var vcs = (VersionControlServer)tfs.GetService(typeof(VersionControlServer)); string path = Root; VersionSpec version = VersionSpec.Latest; const int deletionId = 0; const RecursionType recursion = RecursionType.Full; string user = null; VersionSpec versionFrom = null; VersionSpec versionTo = null; const int maxCount = 100; const bool includeChanges = true; const bool slotMode = true; const bool includeDownloadInfo = true; IEnumerable enumerable = vcs.QueryHistory(path, version, deletionId, recursion, user, versionFrom, versionTo, maxCount, includeChanges, slotMode, includeDownloadInfo); var c = new List<Changeset>(); foreach (var i in enumerable) { var cs = (i as Changeset); if (cs != null && cs.Committer != Committer) { foreach(var change in cs.Changes) { if(!change.Item.ServerItem.Contains("Professional")) { c.Add(cs); } } } } return true; } } }
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 SOFT152_Assignment { public partial class frmEditMonth : Form { public static frmEditMonth frmkeepEditMonth = null; public frmEditMonth() { InitializeComponent(); frmkeepEditMonth = this; } private void frmEditMonth_Load(object sender, EventArgs e) { int numlocations = Data.locations.Length; for (int i = 0; i < numlocations; i++) { combLocation.Items.Add(Data.locations[i].getLocationName()); } } private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { int locationpos = combLocation.SelectedIndex; int numyears = Data.locations[locationpos].getnumyears(); for (int i = 0; i < numyears; i++) { combYear.Items.Add(Data.locations[locationpos].getyearinfo()[i].getYear()); } } private void combYear_SelectedIndexChanged(object sender, EventArgs e) { int locationpos = combLocation.SelectedIndex; int yearpos = combYear.SelectedIndex; for (int i = 0; i < 12; i++) { combMonth.Items.Add(Data.locations[locationpos].getyearinfo()[yearpos].getmonthinfo()[i].getMonthID()); } } private void combMonth_SelectedIndexChanged(object sender, EventArgs e) { int locationpos = combLocation.SelectedIndex; int yearpos = combYear.SelectedIndex; int monthpos = combMonth.SelectedIndex; lstCurrentmonth.Items.Clear(); lstCurrentmonth.Items.Add("Month: " + Data.locations[locationpos].getyearinfo()[yearpos].getmonthinfo()[monthpos].getMonthID()); lstCurrentmonth.Items.Add("Max Temperature: " + Data.locations[locationpos].getyearinfo()[yearpos].getmonthinfo()[monthpos].getMaxTemp()); lstCurrentmonth.Items.Add("Min temp: " + Data.locations[locationpos].getyearinfo()[yearpos].getmonthinfo()[monthpos].getMinTemp()); lstCurrentmonth.Items.Add("Number of days with air frost: " + Data.locations[locationpos].getyearinfo()[yearpos].getmonthinfo()[monthpos].getAirFrostNum()); lstCurrentmonth.Items.Add("mm of rain: " + Data.locations[locationpos].getyearinfo()[yearpos].getmonthinfo()[monthpos].getMmOfRain()); lstCurrentmonth.Items.Add("Hours of sun: " + Data.locations[locationpos].getyearinfo()[yearpos].getmonthinfo()[monthpos].getHoursOfSun()); } private void btnCancel_Click(object sender, EventArgs e) { DisplayInfo.frmkeepDisplayInfo.Show(); frmkeepEditMonth.Close(); } private void btnEditAll_Click(object sender, EventArgs e) { EditMonthValues(); } private void EditMonthValues() { string newmaxtemp; string newmintemp; string newnumfrostdays; string newmmofrain; string newhoursofsun; newmaxtemp = txtnewMaxTemp.Text; newmintemp = txtNewMinTemp.Text; newnumfrostdays = txtNumFrostDays.Text; newmmofrain = txtNewMmOfRain.Text; newhoursofsun = txtNewHoursOfSun.Text; int locationpos = combLocation.SelectedIndex; int yearpos = combYear.SelectedIndex; int monthpos = combMonth.SelectedIndex; if ((locationpos == -1) || (yearpos == -1) || (monthpos == -1)) { MessageBox.Show("please make sure you have chosen a location, year and month using the comboboxes."); } else { try { if (newmaxtemp != "") { Convert.ToInt32(newmaxtemp); Data.locations[locationpos].getyearinfo()[yearpos].getmonthinfo()[monthpos].setMaxTemp(newmaxtemp); } if (newmintemp != "") { Convert.ToInt32(newmintemp); Data.locations[locationpos].getyearinfo()[yearpos].getmonthinfo()[monthpos].setMinTemp(newmintemp); } if (newnumfrostdays != "") { Convert.ToInt32(newnumfrostdays); Data.locations[locationpos].getyearinfo()[yearpos].getmonthinfo()[monthpos].setAirFrostNum(newnumfrostdays); } if (newmmofrain != "") { Convert.ToInt32(newmmofrain); Data.locations[locationpos].getyearinfo()[yearpos].getmonthinfo()[monthpos].setMmOfRain(newmmofrain); } if (newhoursofsun != "") { Convert.ToInt32(newhoursofsun); Data.locations[locationpos].getyearinfo()[yearpos].getmonthinfo()[monthpos].setHoursOfSun(newhoursofsun); } MessageBox.Show("new values have been set"); } catch (Exception ex) { MessageBox.Show("please make sure all of your inputs are numbers (no text or symbols)"); } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Otiport.API.Contract.Models; namespace Otiport.API.Contract.Response.Treatments { public class GetTreatmentsResponse : ResponseBase { public IEnumerable<TreatmentModel> Treatments { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AlgorithmProblems.Arrays { /// <summary> /// Given an array of sorted integers and a sum value. /// We need to calculate the count of all pairs of elements which will sum up to a particular value. /// for eg [0,2,3,5] and sum = 5 should return the count as 2 /// [1,1,3,5,5,5,5] and sum = 6 should return the count as 8 /// </summary> class CountOfPairsWhichSumUpToGivenSum { /// <summary> /// We can use the 2 pointers left and right. /// if we have arr[left] + arr[right] == sum we do left++ and right-- /// If we have the pair sum greater we do right-- /// If we have the pair sum less than sum we do left++ /// /// Special cases when we have duplicates which sum to a particular value, like [1,1,3,5,5,5,5]. /// We need to get the leftCount * rightCount = 2*4 = 8 /// /// Another edge case is when all the values are same. [1,1,1,1,1] sum = 2 /// We need to calculate nC2 where n=5 5C2 = 10 /// /// The running time is O(n) /// The space is O(1) /// </summary> /// <param name="arr"></param> /// <param name="sum"></param> /// <returns></returns> public static int GetCount(int[] arr, int sum) { int count = 0; int left = 0; int right = arr.Length - 1; while(left<right) { int pairSum = arr[left] + arr[right]; if(pairSum == sum) { if(arr[left] == arr[right]) { //case: all the elements are same from left to right int n = right - left + 1; count += (n * (n - 1)) / 2; // nC2 break; } // case: where we have duplicates in left or right int rightCount = 1; int leftCount = 1; while(left+1 < right && arr[left] == arr[left+1]) { leftCount++; left++; } while (left < right-1 && arr[right] == arr[right-1]) { rightCount++; right--; } left++; right--; count += rightCount * leftCount; } else if(pairSum > sum) { right--; } else { left++; } } return count; } public static void TestCountOfPairsWhichSumUpToGivenSum() { int[] arr = new int[] { 0,1, 2, 3, 5 }; int sum = 5; Console.WriteLine("The count of paris is {0}. Expected : 2", GetCount(arr, sum)); arr = new int[] { 1, 1, 2,2,3,4,4, 5, 5, 5, 5 }; sum = 6; Console.WriteLine("The count of paris is {0}. Expected : 12", GetCount(arr, sum)); arr = new int[] { 1, 1, 1,1,1,5 }; sum = 2; Console.WriteLine("The count of paris is {0}. Expected : 10", GetCount(arr, sum)); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class SingingResultsSceneKeyboardController : MonoBehaviour { private const string ContinueToNextSceneShortcut = "return"; void Update() { if (Input.GetKeyUp(ContinueToNextSceneShortcut)) { SceneNavigator.Instance.LoadScene(EScene.SongSelectScene); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LemonadeStand2 { class Day { readonly Weather weather; readonly Customer customer; public Day(int currentDay, Player player) { player.moneyDayBegin = player.money; player.moneyDayEnd = 0; player.ice = 0; weather = new Weather(); ShowCurrentDay(currentDay); DailyWeatherReport(); string userInput; do { userInput = UserInterface.AskToBuyProduct(player); } while (userInput == "yes"); UserInterface.AskForRecipe(player); customer = new Customer(weather, player, UserInterface.GetRecipe(player)); } internal Game Game { get => default(Game); set { } } public void ShowCurrentDay(int currentDay) { Console.WriteLine("Beginning of Day {0}", currentDay); } public void DailyWeatherReport() { Console.WriteLine("\r\nCurrent Weather Forecast:\r\nTemperature - {0}\r\nSky Condition - {1}", weather.temperature, weather.skyCondition); } public void EndOfDayTotal(Day day, Player player, Recipe recipe) { player.moneyDayEnd = player.money; double moneyDay = player.moneyDayBegin - player.moneyDayEnd; double moneyDay1 = player.moneyDayEnd - player.moneyDayBegin; UserInterface.ShowCustomerPurchase(customer, player, recipe); Console.WriteLine("\r\nToday You Sold: ${0} Of Lemonade", recipe.cupsMade * recipe.pricePerCup); if (player.moneyDayBegin > player.moneyDayEnd) { Console.WriteLine("\r\nToday You Lost: ${0}", moneyDay); } else { Console.WriteLine("\r\nToday You Made: ${0}", moneyDay1); } } } }
using System; using System.Collections.Generic; using System.Text; namespace ModelTransformationComponent { /// <summary> /// Класс исключений, генерируемых компонентом трансформации моделей <see cref="TransformationComponent"/> /// <para/> /// Наследует <see cref="Exception"/> /// </summary> [Serializable] public class TransformComponentException : Exception { /// <summary> /// Конструктор <see cref="TransformComponentException"/> /// </summary> public TransformComponentException() { } /// <summary> /// Конструктор <see cref="TransformComponentException"/> /// </summary> /// <param name="message">Сообщение</param> public TransformComponentException(string message) : base(message) { } /// <summary> /// Конструктор <see cref="TransformComponentException"/> /// </summary> /// <param name="message">Сообщение</param> /// <param name="inner">Внутренняя ошибка</param> public TransformComponentException(string message, Exception inner) : base(message, inner) { } /// <summary> /// Конструктор <see cref="TransformComponentException"/> /// </summary> /// <param name="info"></param> /// <param name="context"></param> protected TransformComponentException( System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } } }
using System.Collections.Generic; using BL; using Shared.DTO; using System.Web.Http; using System.Net.Http; using System.Net; using System.Linq; using Shared.Enum; namespace Nagarro_Exit_Test_Assignment.Controllers { public class MemberController : ApiController { [HttpGet] public HttpResponseMessage Get(string email) { MemberBL memberBL = new MemberBL(); ResponseFormat<bool> response = new ResponseFormat<bool>(); response.Data = memberBL.EmailExists(email); if (response.Data) { response.Message = "Member Created"; response.Success = true; return Request.CreateResponse(HttpStatusCode.OK, response); } else { response.Message = "There Was Some Error"; response.Success = false; return Request.CreateResponse(HttpStatusCode.OK, response); } } [HttpGet] [Route("api/member/{aadharNumber}")] public HttpResponseMessage GetByAadhar(string aadharNumber) { MemberBL memberBL = new MemberBL(); ResponseFormat<bool> response = new ResponseFormat<bool>(); response.Data = memberBL.AadharExists(aadharNumber); if (response.Data) { response.Message = "Member Created"; response.Success = true; return Request.CreateResponse(HttpStatusCode.OK, response); } else { response.Message = "There Was Some Error"; response.Success = false; return Request.CreateResponse(HttpStatusCode.OK, response); } } public HttpResponseMessage Post(MemberDTO member) { MemberBL memberBL = new MemberBL(); ResponseFormat<bool> response = new ResponseFormat<bool>(); response.Data = memberBL.Create(member); if (response.Data) { response.Message = "Member Created"; response.Success = true; return Request.CreateResponse(HttpStatusCode.OK, response); } else { response.Message = "There Was Some Error"; response.Success = false; return Request.CreateResponse(HttpStatusCode.BadRequest, response); } } //DELETE: api/Delete //public HttpResponseMessage Delete(int id) // { // MemberBL memberBL = new MemberBL(); // ResponseFormat<bool> response = new ResponseFormat<bool>(); // response.Data = memberBL.DeleteById(id); // if (response.Data) // { // response.Message = "Member Deleted"; // response.Success = true; // return Request.CreateResponse(HttpStatusCode.OK, response); // } // else // { // response.Message = "Cannot Delete"; // response.Success = false; // return Request.CreateResponse(HttpStatusCode.BadRequest, response); // } // } } }
using System; using System.Collections.Generic; namespace NStandard { public static class EnumerableEx { public static IEnumerable<T> Concat<T>(IEnumerable<IEnumerable<T>> enumerables) { foreach (var enumerable in enumerables) foreach (var item in enumerable) yield return item; } public static IEnumerable<T> Concat<T>(params IEnumerable<T>[] enumerables) { foreach (var enumerable in enumerables) foreach (var item in enumerable) yield return item; } public static IEnumerable<T> Create<T>(int count, Func<int, T> generate) { for (int i = 0; i < count; i++) yield return generate(i); } public static IEnumerable<T> Create<T>(T start, Func<T, T> generate, Func<T, int, bool> condition) { int i = 0; for (T item = start; condition(item, i); item = generate(item)) { yield return item; i++; } } public static IEnumerable<TSelf> CreateFromLinked<TSelf>(TSelf @this, Func<TSelf, TSelf> selector) { var select = @this; while (select is not null) { yield return select; select = selector(select); } } } }
using UnityEngine; using System.Collections; public class PropsController : MonoBehaviour { public string myType; [SerializeField] private GameController gameController; [SerializeField] private Sprite[] sprites; [SerializeField] private Sprite[] spritesNight; [SerializeField] private GameObject[] balloon; [SerializeField] public int nBallons; public float decreaseValue; private bool actived; [SerializeField] private FadeManager fadeManager; [SerializeField] private GameObject protest; void Start() { actived = false; } public void ChangeSprite () { switch (myType) { case "Hospital": if (gameController.props.x >= 8) { if (this.GetComponent<SpriteRenderer>().sprite != sprites[0]) this.GetComponent<SpriteRenderer>().sprite = sprites[0]; if (this.GetComponent<Animator>().enabled) this.GetComponent<Animator>().enabled = false; if (protest.activeSelf) protest.SetActive(false); } else if (gameController.props.x < 8 && gameController.props.x >= 6) { if (this.GetComponent<SpriteRenderer>().sprite != sprites[1]) this.GetComponent<SpriteRenderer>().sprite = sprites[1]; if (this.GetComponent<Animator>().enabled) this.GetComponent<Animator>().enabled = false; if (protest.activeSelf) protest.SetActive(false); } else if (gameController.props.x < 6) { this.GetComponent<SpriteRenderer>().sprite = sprites[2]; if (this.GetComponent<Animator>().enabled) this.GetComponent<Animator>().enabled = false; if (!protest.activeSelf) protest.SetActive(true); } break; case "School": if (gameController.props.y >= 8) { if (this.GetComponent<SpriteRenderer>().sprite != sprites[3]) this.GetComponent<SpriteRenderer>().sprite = sprites[3]; if (this.GetComponent<Animator>().enabled) this.GetComponent<Animator>().enabled = false; if (protest.activeSelf) protest.SetActive(false); } else if (gameController.props.y < 8 && gameController.props.y >= 6) { if (this.GetComponent<SpriteRenderer>().sprite != sprites[4]) this.GetComponent<SpriteRenderer>().sprite = sprites[4]; if (this.GetComponent<Animator>().enabled) this.GetComponent<Animator>().enabled = false; if (protest.activeSelf) protest.SetActive(false); } else if (gameController.props.y < 6) { this.GetComponent<SpriteRenderer>().sprite = sprites[5]; if (this.GetComponent<Animator>().enabled) this.GetComponent<Animator>().enabled = false; if (!protest.activeSelf) protest.SetActive(true); } break; case "Police": if (gameController.props.z >= 8) { if (this.GetComponent<SpriteRenderer>().sprite != sprites[6]) this.GetComponent<SpriteRenderer>().sprite = sprites[6]; if (this.GetComponent<Animator>().enabled) this.GetComponent<Animator>().enabled = false; if (protest.activeSelf) protest.SetActive(false); } else if (gameController.props.z <= 8 && gameController.props.z >= 6) { if (this.GetComponent<SpriteRenderer>().sprite != sprites[7]) this.GetComponent<SpriteRenderer>().sprite = sprites[7]; if (protest.activeSelf) protest.SetActive(false); } else if (gameController.props.z < 6) { this.GetComponent<SpriteRenderer>().sprite = sprites[8]; if (this.GetComponent<Animator>().enabled) this.GetComponent<Animator>().enabled = false; if (!protest.activeSelf) protest.SetActive(true); } break; } } }
using UnityEngine; using System.Collections; using DG.Tweening; public class DoublePromptEffect : MonoBehaviour { private static DoublePromptEffect _instance; public static DoublePromptEffect Instance { get { if (_instance == null) { _instance = FindObjectOfType<DoublePromptEffect>(); } return _instance; } } private RectTransform _rectTransform; public void ComeIn() { _rectTransform = transform.GetComponent<RectTransform>(); _rectTransform.DOMoveX(86.25f, 0.5f); _rectTransform.DOPlay(); } public void Back() { _rectTransform.DOMoveX(-86.75f, 0.5f); _rectTransform.DOPlay(); } }
namespace NetworkFramework { public abstract class Singleton<T> : UnityEngine.MonoBehaviour where T : UnityEngine.Object { private static bool _isCalled; private static T _instance; public static T Instance() { if (_instance == null && _isCalled) { _instance = FindObjectOfType<T>(); _isCalled = false; // todo: maybe error } return _instance; } protected virtual void Awake() { _instance = FindObjectOfType<T>(); } } }
using System; namespace MethodOverride { class Point { public double X; public double Y; public override string ToString() { return String.Format("({0}, {1})", X, Y); } } class Program { static void Main() { var myPoint = new Point() { X = 1, Y = 2 }; Console.WriteLine(myPoint); Console.ReadKey(); } } }
using CYJ.DingDing.Application.IAppService; namespace CYJ.DingDing.Application.AppService { public class MessageAppService : IMessageAppService { } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Problem_5_FallDown { class FallDown { static void Main() { // Read the input numbers int num0 = int.Parse(Console.ReadLine()); int num1 = int.Parse(Console.ReadLine()); int num2 = int.Parse(Console.ReadLine()); int num3 = int.Parse(Console.ReadLine()); int num4 = int.Parse(Console.ReadLine()); int num5 = int.Parse(Console.ReadLine()); int num6 = int.Parse(Console.ReadLine()); int num7 = int.Parse(Console.ReadLine()); for (int count = 1; count <= 7; count++) { for (int bit = 0; bit <= 7; bit++) { if ((num7 >> bit & 1) == 0 && (num6 >> bit & 1) == 1) { num7 |= (1 << bit); num6 &= ~(1 << bit); } } for (int bit = 0; bit <= 7; bit++) { if ((num6 >> bit & 1) == 0 && (num5 >> bit & 1) == 1) { num6 |= (1 << bit); num5 &= ~(1 << bit); } } for (int bit = 0; bit <= 7; bit++) { if ((num5 >> bit & 1) == 0 && (num4 >> bit & 1) == 1) { num5 |= (1 << bit); num4 &= ~(1 << bit); } } for (int bit = 0; bit <= 7; bit++) { if ((num4 >> bit & 1) == 0 && (num3 >> bit & 1) == 1) { num4 |= (1 << bit); num3 &= ~(1 << bit); } } for (int bit = 0; bit <= 7; bit++) { if ((num3 >> bit & 1) == 0 && (num2 >> bit & 1) == 1) { num3 |= (1 << bit); num2 &= ~(1 << bit); } } for (int bit = 0; bit <= 7; bit++) { if ((num2 >> bit & 1) == 0 && (num1 >> bit & 1) == 1) { num2 |= (1 << bit); num1 &= ~(1 << bit); } } for (int bit = 0; bit <= 7; bit++) { if ((num1 >> bit & 1) == 0 && (num0 >> bit & 1) == 1) { num1 |= (1 << bit); num0 &= ~(1 << bit); } } } Console.WriteLine(num0); Console.WriteLine(num1); Console.WriteLine(num2); Console.WriteLine(num3); Console.WriteLine(num4); Console.WriteLine(num5); Console.WriteLine(num6); Console.WriteLine(num7); /* byte[,] squareGrid = new byte[8, 8]; for (int row = 0; row < squareGrid.GetLength(0); row++) { for (int col = 0; col < squareGrid.GetLength(1); col++) { Console.Write(" " + squareGrid[row, col]); } Console.WriteLine(); } */ } } }
using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; namespace GradConnect.Models { public class Education { public int Id { get; set; } public string Institution { get; set; } public string CourseName { get; set; } public string YearStart { get; set; } public string YearEnd { get; set; } public Education() { Modules = new List<Module>(); } //Navigational props [InverseProperty("CV")] public int? CvId { get; set; } public virtual CV Cv { get; set; } public IEnumerable<Module> Modules { get; set; } [InverseProperty("User")] public string UserId { get; set; } public virtual User User { get; set; } } }
using UnityEngine; using System.Collections; public class RockCollector : MonoBehaviour { private GameObject[] rockHolders; private float distance = 3f; private float lastRocksX; private float rockMin = -2.3f; private float rockMax = 2.3f; void Awake() { rockHolders = GameObject.FindGameObjectsWithTag("RockHolder"); for (int i = 0; i < rockHolders.Length; i++) { Vector3 temp = rockHolders[i].transform.position; temp.y = Random.Range(rockMin, rockMax); rockHolders[i].transform.position = temp; } lastRocksX = rockHolders[0].transform.position.x; for (int i = 1; i < rockHolders.Length; i++) { if (lastRocksX < rockHolders[i].transform.position.x) { lastRocksX = rockHolders[i].transform.position.x; } } } void OnTriggerEnter2D(Collider2D target) { Debug.Log("collided with " + target); if (target.tag == "RockHolder") { Vector3 temp = target.transform.position; temp.x = lastRocksX + distance; temp.y = Random.Range(rockMin, rockMax); target.transform.position = temp; lastRocksX = temp.x; } } // Use this for initialization void Start () { } // Update is called once per frame void Update () { } }
using UnityEngine; using System.Collections.Generic; public class GameMaster :MonoBehaviour{ private static GameMaster instance; public static GameMaster Instance{ get{ return instance; } } private Card.Owner turnOwner; public Card.Owner TurnOwner { get{ return turnOwner; } set{ turnOwner =value; this.GetComponent<UserInterfaceController>().ActivateTurnIndicator(); } } public enum State {InitBoard, NewTurn , ChooseCard, MoveCardToHolder, ChooseZone, MoveCardToZone, RotateCard, CheckForDeadCards, EndTurn}; private State state =State.InitBoard; public State CurrentState{ get{ return state; } set{ state =value; Debug.Log(TurnOwner +": " +state); } } public bool isFirstTurn =true; #region SceneObjects public Transform Holder{ get{ if(TurnOwner ==Card.Owner.Human) return hCardHolder; else return cCardHolder; } } [HideInInspector] private Transform hCardHolder; [HideInInspector] private Transform cCardHolder; public Transform Hand{ get{ if(TurnOwner ==Card.Owner.Human) return hHand; else return cHand; } } [HideInInspector] public Transform hHand; [HideInInspector] public Transform cHand; [HideInInspector] public Transform boardObject; [HideInInspector] public Transform arrows; #endregion [HideInInspector] public Board board; public DeckStats GetDeckStats(Card.Owner owner){ if(owner ==Card.Owner.Human) return hDeckStats; else return cDeckStats; } public DeckStats DeckStats{ get{ if(TurnOwner ==Card.Owner.Human) return hDeckStats; else return cDeckStats; } } public DeckStats hDeckStats; public DeckStats cDeckStats; private Transform GetGraveYard(Card card){ if(card.owner ==Card.Owner.Comp) return cGraveYard; else return hGraveYard; } private Transform hGraveYard; private Transform cGraveYard; #region card private CardController activeCard; public CardController ActiveCard{ get{ return activeCard; } set{ activeCard =value; } } private DropZoneController activeZone; public DropZoneController ActiveZone{ get{ return activeZone; } set{ activeZone =value; //Set card "free" activeCard.transform.SetParent(GameObject.FindObjectOfType<Canvas>().transform); activeCard.transform.SetAsLastSibling(); } } public CardController GetCardController(Card card){ if(card.owner ==Card.Owner.Comp) { if (cDeckStats.activeCards.ContainsValue(card)) return LookForKey(cDeckStats.activeCards, card); } else{ if (hDeckStats.activeCards.ContainsValue(card)) return LookForKey(hDeckStats.activeCards, card); } return null; } private CardController LookForKey(Dictionary<CardController, Card> dictionary, Card value){ foreach (CardController cc in dictionary.Keys){ if(dictionary[cc] ==value) return cc; } return null; } public Card GetCardFromHand(CardController cardController){ return DeckStats.activeCards[cardController]; } public Card GetActiveCard(){ if(DeckStats.hand.ContainsKey(ActiveCard)) return GetActiveCardFromHand(); else return GetActiveCardFromActive(); } public Card GetActiveCardFromHand(){ return DeckStats.hand[activeCard]; } public Card GetActiveCardFromActive(){ return DeckStats.activeCards[activeCard]; } private void AddCardToActive(CardController cc){ Card tmpCard = GetActiveCardFromHand(); tmpCard.active =true; DeckStats.hand.Remove(cc); DeckStats.activeCards.Add(cc, tmpCard); //TODO remove // cc.UpdateElements(tmpCard); } public void PutCardOnBoard(CardController cc){ board.cardsOnBoard[(int)activeZone.fieldID.x, (int)activeZone.fieldID.y] =GetActiveCard(); AddCardToActive(activeCard); } public void PutCardInGraveyard(Card card, Vector2 cords){ if(card.owner ==Card.Owner.Comp) { cDeckStats.graveYard.Add(card); cDeckStats.activeCards.Remove(GetCardController(card)); board.cardsOnBoard[(int)cords.x, (int)cords.y] =null; } else{ hDeckStats.graveYard.Add(card); hDeckStats.activeCards.Remove(GetCardController(card)); board.cardsOnBoard[(int)cords.x, (int)cords.y] =null; } } //FixMe Random card from deck public void DrawCards(int max =5){ List<Card> tmpCards =new List<Card>(); max =max -DeckStats.hand.Count; for(int i =0; i <max; i++) { if(DeckStats.deck.Count ==0) break; int index = Random.Range(0, DeckStats.deck.Count); Card tmpCard =DeckStats.deck[index]; DeckStats.deck.Remove(tmpCard); tmpCards.Add(tmpCard); } foreach (Card c in tmpCards) SpawnCard(c); } public void AddCardToHand() { Card tmpCard = null; if (DeckStats.deck.Count != 0) { tmpCard = DeckStats.deck[0]; DeckStats.deck.Remove(tmpCard); } SpawnCard(tmpCard); } public void AddCardToHand(Card.Owner owner){ Card tmpCard =null; if(DeckStats.deck.Count !=0){ tmpCard =DeckStats.deck[0]; DeckStats.deck.Remove(tmpCard); } SpawnCard(tmpCard); } private void SpawnCard(Card c){ GameObject tmpGO =Instantiate(Resources.Load<GameObject>("Prefabs/Card")); tmpGO.GetComponent<CardController>().Init(c); tmpGO.name =TurnOwner +"Card"; tmpGO.transform.SetParent(Hand); tmpGO.transform.localScale =Vector3.one; tmpGO.transform.SetAsLastSibling(); DeckStats.hand.Add(tmpGO.GetComponent<CardController>(), c); } private void SpawnCard(Card.Owner owner, Card c){ GameObject tmpGO =Instantiate(Resources.Load<GameObject>("Prefabs/Card")); tmpGO.GetComponent<CardController>().Init(c); tmpGO.name =owner +"Card"; tmpGO.transform.SetParent(Hand); tmpGO.transform.localScale =Vector3.one; tmpGO.transform.SetAsLastSibling(); DeckStats.hand.Add(tmpGO.GetComponent<CardController>(), c); } #endregion #region turnChange public void EndTurnButton(){ if(this.state ==State.ChooseCard) EndTurn(); } private void EndTurn(){ if(TurnOwner ==Card.Owner.Human) TurnOwner =Card.Owner.Comp; else TurnOwner =Card.Owner.Human; this.state =State.NewTurn; } private void AddActionPoints(){ DeckStats.actionPoints +=2; } #endregion public List<CardController> compCards; private void RefreshListOfCompCard(){ compCards.Clear(); int tmpCount =Hand.childCount; for(int i =0; i <tmpCount; i++) compCards.Add(Hand.GetChild(i).GetComponent<CardController>()); Debug.Log("Comp Cards: " +compCards.Count); } #region MonoBehaviour private void Awake(){ instance =this; hCardHolder =GameObject.Find("hCard Holder").transform; cCardHolder =GameObject.Find("cCard Holder").transform; hHand =GameObject.Find("Human Hand").transform; cHand =GameObject.Find("Comp Hand").transform; cGraveYard =GameObject.Find("cGrave").transform; hGraveYard =GameObject.Find("hGrave").transform; boardObject =GameObject.Find("Board").transform; arrows =GameObject.Find("Arrows").transform; board =new Board(); hDeckStats =new DeckStats(); cDeckStats =new DeckStats(); compCards =new List<CardController>(); } private void Start(){ arrows.gameObject.SetActive(false); } private void Update(){ if(this.CurrentState ==State.InitBoard) InitBoard(); else if(this.CurrentState ==State.NewTurn) NewTurn(); else if(this.CurrentState ==State.ChooseCard && TurnOwner ==Card.Owner.Comp) CompChooseCard(); else if(this.CurrentState ==State.MoveCardToHolder) MoveCardToHolder(); else if(this.CurrentState ==State.ChooseZone && TurnOwner ==Card.Owner.Comp) CompChooseZone(); else if(this.CurrentState ==State.MoveCardToZone) MoveCardToZone(); else if(this.CurrentState ==State.RotateCard && TurnOwner ==Card.Owner.Comp) CompRotateCard(); else if(this.CurrentState ==State.CheckForDeadCards) CheckBoardForDeadCards(); else if(this.CurrentState ==State.EndTurn) EndTurn(); } #endregion #region States private void InitBoard(){ //ToDO Load Deck hDeckStats.deck =CardMaster.LoadDeck(Card.Owner.Human, "red"); DrawCards(); turnOwner =Card.Owner.Comp; for(int i =0; i <30; i++) cDeckStats.deck.Add(CardMaster.GetCardPlaceHolder()); DrawCards(); turnOwner =Card.Owner.Human; this.GetComponent<UserInterfaceController>().ActivateTurnIndicator(); CurrentState =State.NewTurn; } private void NewTurn(){ if(TurnOwner ==Card.Owner.Comp) RefreshListOfCompCard(); AddActionPoints(); if(!isFirstTurn) DrawCards(); else isFirstTurn =false; CurrentState =State.ChooseCard; } private void MoveCardToHolder(){ Transform tmpTarget =hCardHolder; if(GameMaster.Instance.TurnOwner ==Card.Owner.Comp) tmpTarget =cCardHolder; if(activeCard.MoveTo(tmpTarget)) CurrentState =GameMaster.State.ChooseZone; } private void MoveCardToZone(){ if(activeCard.MoveTo(activeZone.transform)) { //Put card visualization on board activeCard.transform.SetParent(activeZone.transform); activeCard.transform.localScale = new Vector3(0.9f, 0.9f, 1f); //Put card data on data board PutCardOnBoard(activeCard); //enable card rotation if (TurnOwner == Card.Owner.Human) { arrows.transform.position = activeCard.transform.position; arrows.gameObject.SetActive(true); } // clean activeZone =null; GameMaster.Instance.CurrentState =GameMaster.State.RotateCard; } } private void CheckBoardForDeadCards(){ List<Card> tmpDeadCards =new List<Card>(); List<Vector2> tmpDeadCardsCords =new List<Vector2>(); for(int x =0; x <3; x++){ for(int y =0; y <3; y++){ Card tmpCard =board.cardsOnBoard[x, y]; if(tmpCard !=null &&tmpCard.hp <=0) { tmpDeadCards.Add(tmpCard); tmpDeadCardsCords.Add(new Vector2(x, y)); } } } foreach (Card c in tmpDeadCards){ CardController tmpCC =GetCardController(c); if(tmpCC ==null){ Debug.Log("null"); continue; } if(tmpCC.MoveTo(GetGraveYard(c).transform)) { c.active =false; PutCardInGraveyard(c, tmpDeadCardsCords[tmpDeadCards.IndexOf(c)]); } } if(tmpDeadCards.Count ==0) this.CurrentState =GameMaster.State.ChooseCard; } private void CompChooseCard(){ if(board.cardsOnBoard[1, 1] !=null){ if(this.GetComponent<UserInterfaceController>().turnIndicator.gameObject.activeSelf) return; else { this.CurrentState = State.EndTurn; return ; } } ActiveCard =compCards[0]; GameMaster.Instance.CurrentState =GameMaster.State.MoveCardToHolder; } private void CompChooseZone(){ ActiveZone = boardObject.GetChild(4).GetComponent<DropZoneController>(); CurrentState =GameMaster.State.MoveCardToZone; } private void CompRotateCard(){ GetActiveCardFromActive().rotation =3; CurrentState =State.EndTurn; } #endregion public static ZoneMaster.FieldType[,] RotateRightMatrix(ZoneMaster.FieldType[,] matrix, int n) { ZoneMaster.FieldType[,] tmpMatrix = new ZoneMaster.FieldType[n, n]; for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { tmpMatrix[i, j] = matrix[n - j - 1, i]; } } return tmpMatrix; } public static Vector2 FindCardPosition(Card card){ Vector2 tmpCords =new Vector2(-1, -1); for(int x =0; x <3; x++){ for(int y =0; y <3; y++){ if(GameMaster.Instance.board.cardsOnBoard[x, y] ==card) { tmpCords = new Vector2(x, y); break; } } } return tmpCords; } public static CardsInZone CheckForCardsInZone(Card card, ZoneMaster.FieldType[,] zone){ ZoneMaster.FieldType[,] tmpRotatedZone =zone; for(int i =0; i <card.rotation; i++) tmpRotatedZone = GameMaster.RotateRightMatrix(tmpRotatedZone, 3); List<Card> tmpCards =new List<Card>(); Dictionary<Card, ZoneMaster.FieldType> tmpCardsFieldType =new Dictionary<Card, ZoneMaster.FieldType>(); Vector2 tmpPosition =GameMaster.FindCardPosition(card); // Check for Zone int tmpNewX =0; int tmpNewY =0; for(int y=-1; y <2; y++){ tmpNewX =(int)tmpPosition.y +y; for(int x =-1; x <2; x++){ tmpNewY =(int)tmpPosition.x +x; // check if tile is positioned on board if(tmpNewX <0 ||tmpNewX >2 ||tmpNewY <0 ||tmpNewY >2 ||(tmpNewX*3 +tmpNewY) >8) continue; // check if tile contains card else if(GameMaster.Instance.board.cardsOnBoard[tmpNewX, tmpNewY] ==null) continue; // check if card is friendly else if(GameMaster.Instance.board.cardsOnBoard[tmpNewX, tmpNewY].owner ==card.owner) continue; // add Card to List else { tmpCards.Add(GameMaster.Instance.board.cardsOnBoard[tmpNewX, tmpNewY]); tmpCardsFieldType.Add(GameMaster.Instance.board.cardsOnBoard[tmpNewX, tmpNewY], tmpRotatedZone[x+1, y+1]); } } } return new CardsInZone(tmpCards, tmpCardsFieldType); } public static int GetDefendersMod(Card aggressor, Card defender){ CardsInZone tmpCardsInZone =CheckForCardsInZone(defender, defender.defZone); foreach (Card c in tmpCardsInZone.cards){ if(c ==aggressor){ if(tmpCardsInZone.cardsFieldType[c] ==ZoneMaster.FieldType.Blind) return 2; else if(tmpCardsInZone.cardsFieldType[c] ==ZoneMaster.FieldType.Active) return -1; } } return 0; } } public struct CardsInZone{ public List<Card> cards; public Dictionary<Card, ZoneMaster.FieldType> cardsFieldType; public CardsInZone(List<Card> _cards, Dictionary<Card, ZoneMaster.FieldType> _cardsFieldType){ cards =_cards; cardsFieldType =_cardsFieldType; } }
using ServiceQuotes.Domain.Entities.Abstractions; using ServiceQuotes.Domain.Entities.Enums; using System; using System.Collections.Generic; namespace ServiceQuotes.Domain.Entities { public class Quote : Entity { public Quote() { Payments = new HashSet<Payment>(); } public int ReferenceNumber { get; set; } public decimal Total { get; set; } public Status Status { get; set; } public Guid ServiceRequestId { get; set; } public DateTime Created { get; set; } public virtual ICollection<Payment> Payments { get; set; } public virtual ServiceRequest ServiceRequest { get; set; } } }
using Payment.Domain.Enumerations; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Payment.Domain.Models { public class PaymentRequestState : ModelBase<long> { public long RequestId { get; set; } public PaymentRequest Request { get; set; } public PaymentState State { get; set; } public DateTimeOffset At { get; set; } } }
using DesignPatterns.Strategy.LoanExample; using DesignPatterns.TemplateMethod.Example1; using System; using System.Collections.Generic; using System.Text; using Xunit; using Worse = DesignPatterns.TemplateMethod.CapitalStrategy.Worse; namespace DesignPatternsTest { public class TemplateMethodTest { [Fact] public void TemplateMethod_Example1() { GeradorArquivo geradorArquivo = new GeradorXMLCompactado(); geradorArquivo.GerarArquivo("teste", new Dictionary<string, object> { {"body", "examples" }, {"div", "conteudo da div" }, {"p", 1 } }); } [Fact] public void TemplateMethod_CapitalStrategy_Worse() { Worse.CapitalStrategy strategy = new Worse.CapitalStrategyAdviseLine(); var loan = new Loan(2, null, null, null, 3, null); var result = strategy.Capital(loan); Assert.Equal(945, result); } [Fact] public void TemplateMethod_CapitalStrategy_Good() { Worse.CapitalStrategy strategy = new Worse.CapitalStrategyAdviseLine(); var loan = new Loan(2, null, null, null, 3, null); var result = strategy.Capital(loan); Assert.Equal(945, result); } } }
using System; using System.Collections.Generic; using System.Linq; namespace Euler_Logic.Problems { public class Problem11 : ProblemBase { public override string ProblemName { get { return "11: Largest product in a grid"; } } public override string GetAnswer() { return Solve().ToString(); } private ulong Solve() { ulong best = 0; var grid = GetGrid(); for (int x = 0; x < grid.Length; x++) { for (int y = 0; y < grid.Length; y++) { ulong prod; if (y < grid.Length - 4) { prod = grid[x][y] * grid[x][y + 1] * grid[x][y + 2] * grid[x][y + 3]; if (prod > best) best = prod; } if (x < grid.Length - 4) { prod = grid[x][y] * grid[x + 1][y] * grid[x + 2][y] * grid[x + 3][y]; if (prod > best) best = prod; } if (x < grid.Length - 4 && y < grid.Length - 4) { prod = grid[x][y] * grid[x + 1][y + 1] * grid[x + 2][y + 2] * grid[x + 3][y + 3]; if (prod > best) best = prod; } if (x > 3 && y < grid.Length - 4) { prod = grid[x][y] * grid[x - 1][y + 1] * grid[x - 2][y + 2] * grid[x - 3][y + 3]; if (prod > best) best = prod; } } } return best; } private ulong[][] GetGrid() { var text = new List<ulong[]>(); text.Add("08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08".Split(' ').Select(x => Convert.ToUInt64(x)).ToArray()); text.Add("49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00".Split(' ').Select(x => Convert.ToUInt64(x)).ToArray()); text.Add("81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65".Split(' ').Select(x => Convert.ToUInt64(x)).ToArray()); text.Add("52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91".Split(' ').Select(x => Convert.ToUInt64(x)).ToArray()); text.Add("22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80".Split(' ').Select(x => Convert.ToUInt64(x)).ToArray()); text.Add("24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50".Split(' ').Select(x => Convert.ToUInt64(x)).ToArray()); text.Add("32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70".Split(' ').Select(x => Convert.ToUInt64(x)).ToArray()); text.Add("67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21".Split(' ').Select(x => Convert.ToUInt64(x)).ToArray()); text.Add("24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72".Split(' ').Select(x => Convert.ToUInt64(x)).ToArray()); text.Add("21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95".Split(' ').Select(x => Convert.ToUInt64(x)).ToArray()); text.Add("78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92".Split(' ').Select(x => Convert.ToUInt64(x)).ToArray()); text.Add("16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57".Split(' ').Select(x => Convert.ToUInt64(x)).ToArray()); text.Add("86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58".Split(' ').Select(x => Convert.ToUInt64(x)).ToArray()); text.Add("19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40".Split(' ').Select(x => Convert.ToUInt64(x)).ToArray()); text.Add("04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66".Split(' ').Select(x => Convert.ToUInt64(x)).ToArray()); text.Add("88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69".Split(' ').Select(x => Convert.ToUInt64(x)).ToArray()); text.Add("04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36".Split(' ').Select(x => Convert.ToUInt64(x)).ToArray()); text.Add("20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16".Split(' ').Select(x => Convert.ToUInt64(x)).ToArray()); text.Add("20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54".Split(' ').Select(x => Convert.ToUInt64(x)).ToArray()); text.Add("01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48".Split(' ').Select(x => Convert.ToUInt64(x)).ToArray()); return text.ToArray(); } } }
namespace QStore.Strings.Interfaces { using System.Collections.Generic; public interface IStringMap<TValue> : IIndexedStringSet { TValue[] Values { get; } TValue this[IEnumerable<char> key] { get; set; } IEnumerable<KeyValuePair<string, TValue>> EnumerateByPrefixWithValue(IEnumerable<char> prefix); IEnumerable<KeyValuePair<string, TValue>> EnumerateWithValue(); KeyValuePair<string, TValue> GetByIndexWithValue(int index); string GetKeyByIndex(int index); bool TryGetValue(IEnumerable<char> key, out TValue value); } }
using UnityEngine; namespace UnityAtoms.BaseAtoms { /// <summary> /// Condition of type `GameObject`. Inherits from `AtomCondition&lt;GameObject&gt;`. /// </summary> [EditorIcon("atom-icon-teal")] public abstract class GameObjectCondition : AtomCondition<GameObject> { } }
using AutoMapper; using ReactMusicStore.Core.Domain.Entities; namespace ReactMusicStore.WebApi.ViewModels { public class GenreMenuViewModel { public string Name { get; set; } public static GenreMenuViewModel ToViewModel(Genre genre) { return Mapper.Map<GenreMenuViewModel>(genre); } } }
using System; using MQTTnet.Diagnostics.Logger; namespace MQTTnet.Tests.Mockups { public sealed class TestLogger : IMqttNetLogger { public event EventHandler<MqttNetLogMessagePublishedEventArgs> LogMessagePublished; public void Publish(MqttNetLogLevel logLevel, string source, string message, object[] parameters, Exception exception) { LogMessagePublished?.Invoke(this, new MqttNetLogMessagePublishedEventArgs(new MqttNetLogMessage { Level = logLevel, Message = string.Format(message, parameters), Exception = exception })); } } }
using System.Windows.Controls; namespace ThanksCardClient.Views { /// <summary> /// Interaction logic for UserEdit /// </summary> public partial class UserEdit : UserControl { public UserEdit() { InitializeComponent(); } private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { } } }
using System; using Microsoft.Extensions.DependencyInjection; using Eda.Extensions.DependencyInjection; namespace Eda.Integrations.Delivery.DependencyInjection { /// <inheritdoc /> /// <summary> /// Base class for delivery service block. /// </summary> public abstract class DeliveryServiceApplicationBlock : IApplicationBlock { public void AddTo(IServiceCollection services) => services .AddSingleton(CreateFactory) .AddSingleton(CreateGeoService) .AddSingleton(CreateDeliveryService); protected abstract void AddFactory(IServiceCollection services) => services.Add() protected abstract void AddGeoService(IServiceCollection services); protected abstract void AddDeliveryService(IServiceCollection services); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AlgorithmProblems.Stack_and_Queue.Queue_Helper { class QueueViaArray<T> { private T[] storage; private int first; private int last; public QueueViaArray(int capacity) { if (capacity > 0) { storage = new T[capacity]; first = 0; last = 1; } else { throw new Exception("Capacity is very low/invalid"); } } public void Enqueue(T data) { if(last < storage.Length) { storage[last-1] = data; last++; } else { throw new Exception("Array full"); } } public T Dequeue() { if(first < last) { T retVal = storage[first++]; return retVal; } else { // Note here the max number of dequeues can be equal to the storage capacity throw new Exception("Storage full"); } } } }
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity.UI.Services; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Authorization; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using OnlineGallery.Areas.Identity.Data; using OnlineGallery.Data; using OnlineGallery.Entities; using OnlineGallery.Models; using System; [assembly: HostingStartup(typeof(OnlineGallery.Areas.Identity.IdentityHostingStartup))] namespace OnlineGallery.Areas.Identity { public class IdentityHostingStartup : IHostingStartup { public void Configure(IWebHostBuilder builder) { builder.ConfigureServices((context, services) => { services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer( context.Configuration.GetConnectionString("DefaultConnection") ) ); services.AddIdentity<ApplicationUser, IdentityRole>(options => { options.Password.RequireNonAlphanumeric = false; options.User.RequireUniqueEmail = true; options.SignIn.RequireConfirmedEmail = true; options.SignIn.RequireConfirmedPhoneNumber = false; options.Lockout.AllowedForNewUsers = true; options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(2); options.Lockout.MaxFailedAccessAttempts = 3; }) .AddRoles<IdentityRole>() .AddEntityFrameworkStores<ApplicationDbContext>() .AddDefaultTokenProviders(); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Latest) .AddRazorPagesOptions(options => { options.Conventions.AuthorizeAreaFolder("Identity", "/Account/Manage"); options.Conventions.AuthorizeAreaPage("Identity", "/Account/Logout"); }); services.ConfigureApplicationCookie(options => { options.LoginPath = $"/Identity/Account/Login"; options.LogoutPath = $"/Identity/Account/Logout"; options.AccessDeniedPath = $"/Identity/Account/AccessDenied"; }); }); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Matrix { class Tree<T> { public delegate int CompType(T a, T b); private Node<T> Noeud; private CompType C; public delegate void MapFunction(ref T elt); private MapFunction MF; private delegate bool BinFunc(ref Node<T> node, T val); public Tree(CompType comp, T value) { Node<T> Noeud = new Node<T>(value); C = comp; } public void depth_first_traversal(MapFunction function) { MF = function; if (Noeud.fg != null) Noeud.fg.depth_first_traversal(MF); function(ref Noeud.val); if (Noeud.fd != null) Noeud.fd.depth_first_traversal(MF); } public void breadth_first_traversal(MapFunction function) { Queue<Node<T>> file = new Queue<Node<T>>(); file.Enqueue(Noeud); while (file.Count != 0) { Node<T> n = file.Dequeue(); function(ref n.val); if (n.fg != null) file.Enqueue(n.fg.Noeud); if (n.fd != null) file.Enqueue(n.fd.Noeud); } } private bool binary_traversal(ref Node<T> node, T val, BinFunc null_case, BinFunc equal_case) { if (C(node.val, val) == 0) return equal_case(ref Noeud, Noeud.val); if (node.fg != null || node.fd != null) { if (C(node.val, val) < 0) { if (node.fg != null) return binary_traversal(ref node.fg.Noeud, val, null_case, equal_case); } else if (node.fd != null) return binary_traversal(ref node.fd.Noeud, val, null_case, equal_case); } return null_case(ref Noeud, val); } public bool find(T val) { BinFunc NC = delegate(ref Node<T> n, T v) { return false; }; BinFunc EC = (ref Node<T> n, T v) => { return true; }; return binary_traversal(ref Noeud, val, NC, EC); } public bool insert(T val) { BinFunc NC = delegate(ref Node<T> n, T v) { n = new Node<T>(v); return true; }; BinFunc EC = (ref Node<T> n, T v) => { return false; }; return binary_traversal(ref Noeud, val, NC, EC); } public bool delete(T val) { BinFunc NC = delegate(ref Node<T> n, T v) { return false; }; BinFunc EC = (ref Node<T> n, T v) => { if (n.fg == null) { n = n.fd.Noeud; return true; } else if (n.fd == null) { n = n.fg.Noeud; return true; } else { Node<T> max = n.fg.Noeud; Node<T> papa = n; while (max.fd.Noeud != null) { papa = max; max = max.fd.Noeud; } papa.fd = max.fg; n.val = max.val; return true; } }; return binary_traversal(ref Noeud, val, NC, EC); } public Tree(CompType comp, T[] value) { Node<T> Noeud = new Node<T>(value[0]); C = comp; for (int i = 1; i < value.Length; i++) { insert(value[i]); } } } }
using System; using System.Collections.Generic; using System.Data.Entity.ModelConfiguration; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Anywhere2Go.DataAccess.Entity { public class NotifyType { public int notifyId { get; set; } public string notifyName { get; set; } public int sort { get; set; } public bool isActive { get; set; } public DateTime? createDate { get; set; } public DateTime? updateDate { get; set; } public string createBy { get; set; } public string updateBy { get; set; } } public class NotifyTypeConfig : EntityTypeConfiguration<NotifyType> { public NotifyTypeConfig() { ToTable("NotifyType"); Property(t => t.notifyId).HasColumnName("notify_id"); Property(t => t.notifyName).HasColumnName("notify_name").HasMaxLength(50); Property(t => t.sort).HasColumnName("sort"); Property(t => t.isActive).HasColumnName("isActive"); Property(t => t.createDate).HasColumnName("create_date"); Property(t => t.updateDate).HasColumnName("update_date"); Property(t => t.createBy).HasColumnName("create_by"); Property(t => t.updateBy).HasColumnName("update_by"); HasKey(t => t.notifyId); } } public class NotifyAlert { public string carRegis { get; set; } public int notifyStatus { get; set; } public bool isNotify { get; set; } public DateTime? createDate { get; set; } public DateTime? updateDate { get; set; } public string createBy { get; set; } public string updateBy { get; set; } } public class NotifyAlertConfig : EntityTypeConfiguration<NotifyAlert> { public NotifyAlertConfig() { MapToStoredProcedures(); Property(t => t.carRegis).HasColumnName("carRegis"); Property(t => t.notifyStatus).HasColumnName("notifyStatus"); Property(t => t.isNotify).HasColumnName("isNotify"); Property(t => t.createDate).HasColumnName("create_date"); Property(t => t.updateDate).HasColumnName("update_date"); Property(t => t.createBy).HasColumnName("create_by"); Property(t => t.updateBy).HasColumnName("update_by"); HasKey(t => t.carRegis); } } }
using UnityEngine; using UnityEngine.UI; using System.Collections; //<author>Georgina Perera</author> public class Overlay : MonoBehaviour { public GameObject window; public Text messageField; //Changes attribute of window gameobject to either display or hide public void Show() { window.SetActive(true); } public void Hide() { window.SetActive (false); } }
using System.Collections; using System.Collections.Generic; using UnityEditor; using UnityEngine; public class ObjectSorter : EditorWindow { Transform logicsStuff; //Transform shatterableStuff; Transform decorativeStuff; //Transform otherStuff; //Transform utilityStuff; Transform lightStuff; [MenuItem("Tools/Sorter")] private static void Init() { ObjectSorter window = (ObjectSorter)EditorWindow.GetWindow(typeof(ObjectSorter)); window.Show(); } private void OnGUI() { logicsStuff = (Transform)EditorGUILayout.ObjectField("Logic",logicsStuff, typeof(Transform),true); //shatterableStuff = (Transform)EditorGUILayout.ObjectField("Logic",shatterableStuff, typeof(Transform),false); decorativeStuff = (Transform)EditorGUILayout.ObjectField("Decorative",decorativeStuff, typeof(Transform), true); //otherStuff = (Transform)EditorGUILayout.ObjectField("Logic",otherStuff, typeof(Transform),false); //utilityStuff = (Transform)EditorGUILayout.ObjectField("Logic",utilityStuff, typeof(Transform),false); lightStuff = (Transform)EditorGUILayout.ObjectField("Lights",lightStuff, typeof(Transform), true); if (GUILayout.Button("Create Categories")) { if (logicsStuff == null) logicsStuff = FindOrCreateObject("Level Logic"); /* if (shatterableStuff == null) shatterableStuff = FindOrCreateObject("Shatterable");*/ if (decorativeStuff == null) decorativeStuff = FindOrCreateObject("Decorative"); /*if (otherStuff == null) otherStuff = FindOrCreateObject("Other");*/ /*if (utilityStuff == null) utilityStuff = FindOrCreateObject("Utility");*/ if (lightStuff == null) lightStuff = FindOrCreateObject("Lighting"); } if (GUILayout.Button("Sort Objects")) { GameObject[] interactables = GameObject.FindGameObjectsWithTag("Interactable"); foreach(GameObject g in interactables) { if (g.transform.parent == null) g.transform.SetParent(logicsStuff); } interactables = GameObject.FindGameObjectsWithTag("Sliceable"); foreach (GameObject g in interactables) { if (g.transform.parent == null) g.transform.SetParent(logicsStuff); } GameObject[] decorations = GameObject.FindGameObjectsWithTag("Small Detail"); foreach (GameObject g in decorations) { if (g.transform.parent == null) g.transform.SetParent(decorativeStuff); } GameObject[] lighting = GameObject.FindGameObjectsWithTag("LightSource"); foreach (GameObject g in lighting) { if (g.transform.parent == null) g.transform.SetParent(lightStuff); } ReflectionProbe[] probes = GameObject.FindObjectsOfType<ReflectionProbe>(); foreach (ReflectionProbe g in probes) { if (g.transform.parent == null) g.transform.SetParent(lightStuff); } } } private Transform FindOrCreateObject(string objname) { GameObject g = GameObject.Find(objname); if (g == null) g = new GameObject(objname); return g.transform; } }
using BradescoPGP.Repositorio; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace BradescoPGP.Web.Models { public class AgendaViewModel { public List<Vencimento> Vencimentos { get; set; } public List<Pipeline> Pipelines { get; set; } public List<TED> TEDs { get; set; } public List<AniversarianteViewModel> Aniversariantes { get; set; } public List<Evento> Eventos { get; set; } public static AgendaViewModel Mapear(List<Vencimento> vencimentos, List<Pipeline> pipelines, List<TED> teds, List<AniversarianteViewModel> aniversariantes, List<Evento> eventos) { return new AgendaViewModel { Aniversariantes = aniversariantes, Vencimentos = vencimentos, TEDs = teds, Pipelines = pipelines, Eventos = eventos }; } } }
using System.Linq; using ApartmentApps.Api.Auth; using ApartmentApps.Api.Modules; using ApartmentApps.Data; using ApartmentApps.Data.Repository; using Entrata.Client; using Ninject; namespace ApartmentApps.Api { public class EntrataModule : PropertyIntegrationModule<EntrataConfig> { private readonly IRepository<ApplicationUser> _userRepo; public EntrataModule(ApplicationDbContext dbContext, PropertyContext context, DefaultUserManager manager, IRepository<ApplicationUser> userRepo, IRepository<EntrataConfig> configRepo, IUserContext userContext, IKernel kernel) : base(dbContext, context, manager, configRepo, userContext, kernel) { _userRepo = userRepo; } public override void Execute(ILogger logger) { foreach (var item in _context.PropertyEntrataInfos.ToArray()) { var entrataClient = new EntrataClient() { Username = item.Username, Password = item.Password, EndPoint = item.Endpoint }; var result = entrataClient.GetMitsUnits(item.EntrataPropertyId).Result; if (result?.response?.error?.code == 301) { logger.Warning(result.response.error.message); continue; } if (result?.response != null) if (result?.response?.result?.PhysicalProperty != null) foreach (var property in result?.response?.result?.PhysicalProperty?.Property) { foreach (var ilsUnit in property.ILS_Unit.Select(p => p.Units.Unit)) { if (string.IsNullOrEmpty(ilsUnit.BuildingName)) continue; ImportUnit(logger, ilsUnit.BuildingName, ilsUnit.MarketingName); } } var customers = entrataClient.GetCustomers(item.EntrataPropertyId).Result.Response.Result.Customers.Customer; var customersOld = entrataClient.GetCustomers(item.EntrataPropertyId, "6")?.Result?.Response?.Result?.Customers?.Customer; // Archive all the old customers if (customersOld != null) foreach (var oldCustomer in customersOld) { if (!string.IsNullOrEmpty(oldCustomer.Email?.Trim())) { var entrataId = oldCustomer.Attributes?.Id; var customerEmail = oldCustomer.Email; var propertyId = (int?)UserContext.PropertyId; var user = DbContext.Users.FirstOrDefault(p => p.PropertyId == propertyId && (p.Email.ToLower() == customerEmail.ToLower() || p.SyncId == entrataId)); if (user != null) { if (user.Roles.Any(p => p.RoleId == "Resident")) { user.Archived = true; DbContext.SaveChanges(); logger.Info($"Email {oldCustomer.Email} Archived"); } } } } //var mitsLeasesResult = entrataClient.GetMitsLeases(item.EntrataPropertyId).Result; //var leases = mitsLeasesResult.response.result.LeaseApplication.LA_Lease; foreach (var customer in customers) { if (string.IsNullOrEmpty(customer.BuildingName)) { customer.BuildingName = " "; } //if (string.IsNullOrEmpty(customer.BuildingName)) continue; Building building; Unit unit; ImportUnit(logger, customer.BuildingName, customer.UnitNumber, out unit, out building); var entrataId = customer.Attributes?.Id; var user = ImportCustomer(this, entrataId, unit.Id, customer.PhoneNumber.NumbersOnly(), customer.City, customer.Email, customer.FirstName, customer.LastName, customer.MiddleName, customer.Gender, customer.PostalCode, customer.State, customer.Address); if (user == null) continue; user.Archived = false; user.SyncId = entrataId; _context.SaveChanges(); } } } } }
namespace BookStore.Interfaces { public interface IRenderer { void WriteLine(string message); } }
using System.Collections.Generic; namespace Codility.PerfectChannel { public class Path { readonly int _xpos ; readonly int _ypos ; private readonly int[][] _board; private readonly int _move; private readonly Path _previousNode; public int Move { get { return _move; } } public int X { get { return _xpos; } } public int Y { get { return _ypos; } } public Path PreviousNode { get { return _previousNode; } } public void GenerateCallStack(Stack<Path> callStack) { callStack.Push(this); if (PreviousNode != null) { PreviousNode.GenerateCallStack(callStack); } } public Path(int xpos, int ypos, int[][] board, int move, Path previousNode) { _xpos = xpos; _ypos = ypos; _board = board; _move = move; _previousNode = previousNode; } public List<Path> Next() { return FindPossiblePaths(_xpos, _ypos, _board, _move); } private List<Path> FindPossiblePaths(int xpos, int ypos, int[][] board, int move) { List<Path> paths = new List<Path>(); var positions = new List<Position> { new Position {X = xpos + 2, Y = ypos + 1}, new Position {X = xpos + 2, Y = ypos - 1}, new Position {X = xpos + 1, Y = ypos + 2}, new Position {X = xpos + 1, Y = ypos - 2}, new Position {X = xpos - 1, Y = ypos + 2}, new Position {X = xpos - 1, Y = ypos - 2}, new Position {X = xpos - 2, Y = ypos + 1}, new Position {X = xpos - 2, Y = ypos - 2}, }; foreach (var position in positions) { if (IsMovePossible(position.X, position.Y, board) ) { if (_previousNode == null || ((_previousNode != null) && (position.X != _previousNode.X || position.Y != _previousNode.Y))) { paths.Add(new Path(position.X, position.Y, board, move + 1, this)); } } } return paths; } private static bool IsMovePossible(int x, int y, int[][] board) { if (x < 0) return false; if (x >= board.Length) return false; if (y < 0) return false; if (y >= board[0].Length) return false; if (board[x][y] == 1) return false; return true; } public bool IsAtBottomRight() { if (_xpos == _board.Length-1 && _ypos == _board[0].Length-1) return true; return false; } } }
using System; using System.Collections.Generic; using System.Reflection; using Dapper; using System.Data; using System.Data.SqlClient; using Microsoft.Extensions.Configuration; using Embraer_Backend.Models; namespace Embraer_Backend.Models { public class ArComprimido { public long IdApontArComprimido { get; set; } public long IdLocalMedicao { get; set; } public long IdUsuario{get;set;} public string DescLocalMedicao { get; set; } public string CodUsuario{get;set;} public DateTime? DtMedicao{get;set;} public string Valor{get;set;} public DateTime? DtOcorrencia{get;set;} public string FatoOcorrencia{get;set;} public string AcoesObservacoes{get;set;} } public class ArComprimidoModel { private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(ArComprimidoModel)); public IEnumerable<ArComprimido> SelectArComprimido(IConfiguration _configuration,long? IdApontArComprimido,long? IdLocalMedicao,string dtIni,string dtFim,string Valor,bool? Ocorrencia) { try { string sSql = string.Empty; sSql = "SELECT IdApontArComprimido,A.IdLocalMedicao,DescLocalMedicao,A.IdUsuario,CodUsuario,DtMedicao,Valor,FatoOcorrencia,AcoesObservacoes"; sSql = sSql + " FROM TB_APONT_AR_COMPRIMIDO A"; sSql = sSql + " INNER JOIN TB_LOCAL_MEDICAO L ON A.IdLocalMedicao = L.IdLocalMedicao"; sSql = sSql + " INNER JOIN TB_USUARIO U ON A.IdUsuario = U.IdUsuario"; sSql = sSql + " WHERE 1=1"; if(IdApontArComprimido!=0 && IdApontArComprimido!=null) sSql = sSql + " AND IdApontArComprimido=" + IdApontArComprimido; if(IdLocalMedicao!=0 && IdLocalMedicao!=null) sSql = sSql + " AND A.IdLocalMedicao=" + IdLocalMedicao; if(Valor!="" && Valor!=null) sSql = sSql + " AND Valor='" + Valor + "'"; if(dtIni !=null && dtIni!="" && dtFim!=null && dtFim!="") sSql = sSql + " AND DtMedicao BETWEEN '" + dtIni + "' AND '" + dtFim + "'"; if (Ocorrencia.Value) sSql=sSql + " AND DtOcorrencia IS NULL"; IEnumerable <ArComprimido> _arcomp; using (IDbConnection db = new SqlConnection(_configuration.GetConnectionString("DB_Embraer_Sala_Limpa"))) { _arcomp = db.Query<ArComprimido>(sSql,commandTimeout:0); } return _arcomp; } catch (Exception ex) { log.Error("Erro ArComprimidoModel-SelectArComprimido:" + ex.Message.ToString()); return null; } } public IEnumerable<ArComprimido> SelectArComprimido(IConfiguration _configuration,long IdLocalMedicao) { try { string sSql = string.Empty; sSql = "SELECT TOP 1 IdApontArComprimido,IdLocalMedicao,IdUsuario,DtMedicao,Valor"; sSql = sSql + " FROM TB_APONT_AR_COMPRIMIDO"; sSql = sSql + " WHERE IdLocalMedicao=" + IdLocalMedicao; sSql = sSql + " ORDER BY DtMedicao DESC"; log.Debug(sSql); IEnumerable <ArComprimido> _arcomp; using (IDbConnection db = new SqlConnection(_configuration.GetConnectionString("DB_Embraer_Sala_Limpa"))) { _arcomp = db.Query<ArComprimido>(sSql,commandTimeout:0); } return _arcomp; } catch (Exception ex) { log.Error("Erro ArComprimidoModel-SelectArComprimido:" + ex.Message.ToString()); return null; } } public bool UpdateArComprimido(IConfiguration _configuration,ArComprimido _ar) { try{ string sSql = string.Empty; string dataOcorrencia = (_ar.DtOcorrencia==null) ? "NULL" : _ar.DtOcorrencia.Value.ToString("yyyy-MM-ddTHH:mm:ss"); sSql = "UPDATE TB_APONT_AR_COMPRIMIDO SET"; sSql=sSql+ ((dataOcorrencia=="NULL")? "[DtOcorrencia]="+ dataOcorrencia + "" : "[DtOcorrencia]='"+ dataOcorrencia + "'"); sSql=sSql+ ",[FatoOcorrencia]='"+ _ar.FatoOcorrencia + "'"; sSql=sSql+ ",[AcoesObservacoes]='"+ _ar.AcoesObservacoes + "'"; sSql =sSql+ " WHERE IdApontArComprimido=" + _ar.IdApontArComprimido; long update = 0; using (IDbConnection db = new SqlConnection(_configuration.GetConnectionString("DB_Embraer_Sala_Limpa"))) { update = db.Execute(sSql,commandTimeout:0); } if(update>0) { return true; } return false; } catch(Exception ex) { log.Error("Erro ArComprimidoModel-UpdateArComprimido:" + ex.Message.ToString()); return false; } } public bool InsertArComprimido(IConfiguration _configuration,ArComprimido _arcomp) { string sSql = string.Empty; try { sSql= "INSERT INTO TB_APONT_AR_COMPRIMIDO (IdLocalMedicao,IdUsuario,DtMedicao,Valor)"; sSql = sSql + " VALUES "; sSql = sSql + "(" + _arcomp.IdLocalMedicao; sSql = sSql + "," + _arcomp.IdUsuario; sSql = sSql + ", GETDATE(),'" + _arcomp.Valor + "')"; sSql = sSql + " SELECT @@IDENTITY"; long insertId=0; using (IDbConnection db = new SqlConnection(_configuration.GetConnectionString("DB_Embraer_Sala_Limpa"))) { insertId =db.QueryFirstOrDefault<long>(sSql,commandTimeout:0); } if(insertId>0) { _arcomp.IdApontArComprimido=insertId; return true; } return false; } catch(Exception ex) { log.Error("Erro ArComprimidoModel-InsertArComprimido:" + ex.Message.ToString()); return false; } } } }
using System; using Microsoft.QualityTools.Testing.Fakes; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Calculator.Test { [TestClass] public class CalcTests { [TestMethod] public void Calc_Sum_3_and_4_results_7() { //Arrange Calc calc = new Calc(); //Act var result = calc.Sum(3, 4); //Assert Assert.AreEqual(7, result); } [TestMethod] public void Calc_Sum_0_and_0_results_0() { //Arrange Calc calc = new Calc(); //Act var result = calc.Sum(0, 0); //Assert Assert.AreEqual(0, result); } [TestMethod] public void Calc_Sum_MAX_and_1_throws() { Calc calc = new Calc(); // //c̵̨̡̳̳͚̣̼̠̦̺͍̮̺̻̗̥̗̤͖̹̋ͧ̓̄̒̓̆ͪ̍ͬ̾̓ͣ̄͋ͤ̐̀#̳̼̦͇͓͋̀͋̃ͭ͂̅̕ ͥͧ̑͋̇̀̄̿̐͌ͬ̽̈́̆ͪ͒̄͐̾͘͏̶̧̹̝͕͙͓̙̣͙̳̰̻̺̼̭̦̺ͅp̧̱͖̖̤̱̜̳͈̖̼̞͍͋̂̂ͧ̈̈ͣ̊̈ͤ͊̄ͣͫ̈ͬ͜͜r̡̬͇̞͕̗̠̞ͯͦͫ͒̽̈̇ͪ̾́͑̊̇̾̎̐ͫ̉̿͝o̷̧̮͉͈͇̱̖͙ͨ͂̇̒ͮ͊̀ Assert.ThrowsException<OverflowException>(() => calc.Sum(int.MaxValue, 1)); } [TestMethod] [DataRow(0, 0, 0)] [DataRow(3, 4, 7)] [DataRow(100, 20, 120)] [DataRow(-109, 6, -103)] [DataRow(20, -30, -10)] public void Calc_Sum(int a, int b, int soll) { Calc calc = new Calc(); Assert.AreEqual(soll, calc.Sum(a, b)); } [TestMethod] public void MyTestMethod() { Calc calc = new Calc(); using (ShimsContext.Create()) { System.Fakes.ShimDateTime.NowGet = () => new DateTime(2019, 10, 28); Assert.IsFalse(calc.IsWeekend()); System.Fakes.ShimDateTime.NowGet = () => new DateTime(2019, 10, 29); Assert.IsFalse(calc.IsWeekend()); System.Fakes.ShimDateTime.NowGet = () => new DateTime(2019, 10, 30); Assert.IsFalse(calc.IsWeekend()); System.Fakes.ShimDateTime.NowGet = () => new DateTime(2019, 10, 31); Assert.IsFalse(calc.IsWeekend()); System.Fakes.ShimDateTime.NowGet = () => new DateTime(2019, 11, 1); Assert.IsFalse(calc.IsWeekend()); System.Fakes.ShimDateTime.NowGet = () => new DateTime(2019, 11, 2); Assert.IsTrue(calc.IsWeekend()); System.Fakes.ShimDateTime.NowGet = () => new DateTime(2019, 11, 3); Assert.IsTrue(calc.IsWeekend()); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Agencia_Datos_Repositorio; using entidades = Agencia_Datos_Entidades; namespace Agencia_Dominio { public class D_Control_Electrodomesticos { private readonly Repositorio<entidades.Control_Electrodomesticos> control_electrodomesticos; public D_Control_Electrodomesticos (Repositorio<entidades.Control_Electrodomesticos> control_electrodomesticos) { this.control_electrodomesticos = control_electrodomesticos; } public void AgregarNuevo(entidades.Control_Electrodomesticos modelo) { control_electrodomesticos.Agregar(modelo); control_electrodomesticos.Guardar(); control_electrodomesticos.Commit(); } public void Modificar(entidades.Control_Electrodomesticos modelo) { control_electrodomesticos.Modificar(modelo); control_electrodomesticos.Guardar(); control_electrodomesticos.Commit(); } public void Eliminar(entidades.Control_Electrodomesticos modelo) { control_electrodomesticos.Eliminar(modelo); control_electrodomesticos.Guardar(); control_electrodomesticos.Commit(); } public object TraerTodo() { return control_electrodomesticos.TraerTodo(); } public object TraerUnoPorId(int id) { return control_electrodomesticos.TraerUnoPorId(id); } public void Rollback() { control_electrodomesticos.RollBack(); } } }
using System.Collections.Generic; using System.Windows.Forms; using System.Drawing; namespace RectangleGame.Gamestate { public class GameStateManager { /******** Variables ********/ /// <summary> /// Enumerator encapsulating the different gamestates. /// </summary> public enum State { Menu, Highscore, Info, Options, Quit, Time, Rush } private State lastState; private State currentState; private List<GameState> gameStates; /******** Constructor ********/ public GameStateManager() { // Initializing variables. currentState = State.Menu; lastState = State.Menu; gameStates = new List<GameState>(); // Adding gamestates. gameStates.Add(new MenuState(this)); gameStates.Add(new HighscoreState(this)); gameStates.Add(new InfoState(this)); gameStates.Add(new OptionState(this)); gameStates.Add(new QuitState(this)); gameStates.Add(new TimeState(this)); gameStates.Add(new RushState(this)); SetState(currentState); } /******** Functions ********/ // Passing update and draw on to the currently active gamestate. public void Update() { gameStates[(int)currentState].Update(); } public void Draw(Graphics g) { gameStates[(int)currentState].Draw(g); } /******** Getter & Setter ********/ public State GetState() { return (currentState); } public void SetState(State state) { lastState = currentState; currentState = state; gameStates[(int)currentState].Init(); } /******** Keyboard ********/ // User input is passed to the currelty active gamestate. public void KeyPressed(KeyEventArgs e) { gameStates[(int)currentState].KeyPressed(e); } public void KeyReleased(KeyEventArgs e) { gameStates[(int)currentState].KeyReleased(e); } public void CharPressed(KeyPressEventArgs e) { gameStates[(int)currentState].CharPressed(e); } public void MousePressed(MouseEventArgs e) { gameStates[(int)currentState].MousePressed(e); } public void MouseReleased(MouseEventArgs e) { gameStates[(int)currentState].MouseReleased(e); } public void MouseMoved(MouseEventArgs e) { gameStates[(int)currentState].MouseMoved(e); } } }
using System; using com.Sconit.PrintModel; using System.Runtime.Serialization; using System.Collections.Generic; namespace com.Sconit.PrintModel.ORD { [Serializable] [DataContract] public partial class PrintMiscOrderMaster : PrintBase { #region O/R Mapping Properties [DataMember] public string Title { get; set; } [DataMember] public string MiscOrderNo { get; set; } [DataMember] public Int16 Type { get; set; } [DataMember] public Int16 Status { get; set; } [DataMember] public Boolean IsScanHu { get; set; } [DataMember] public Int16 QualityType { get; set; } [DataMember] public string QualityTypeDescription { get; set; } [DataMember] public string MoveType { get; set; } [DataMember] public string CancelMoveType { get; set; } [DataMember] public string Region { get; set; } [DataMember] public string Location { get; set; } [DataMember] public string ReceiveLocation { get; set; } [DataMember] public string Note { get; set; } [DataMember] public string CostCenter { get; set; } [DataMember] public string Asn { get; set; } [DataMember] public string ReferenceNo { get; set; } [DataMember] public string DeliverRegion { get; set; } [DataMember] public string WBS { get; set; } [DataMember] public DateTime EffectiveDate { get; set; } [DataMember] public Int32 CreateUserId { get; set; } [DataMember] public string CreateUserName { get; set; } [DataMember] public DateTime CreateDate { get; set; } [DataMember] public Int32 LastModifyUserId { get; set; } [DataMember] public string LastModifyUserName { get; set; } [DataMember] public DateTime LastModifyDate { get; set; } [DataMember] public string Flow { get; set; } #endregion public IList<PrintMiscOrderDetail> MiscOrderDetails { get; set; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Xml; namespace Svg2VectorDrawable { public class SvgTree { public float Width { get; set; } public float Height { get; set; } public float[] Matrix { get; set; } public float[] ViewBox { get; set; } public float ScaleFactor { get; set; } = 1; public string Filename { get; private set; } List<string> errorLines = new List<string>(); public enum SvgLogLevel { Error, Warning } public XmlDocument Parse(string filename) { Filename = filename; var doc = new XmlDocument(); doc.Load(filename); return doc; } public void Normalize() { if (Matrix != null) Transform(Matrix[0], Matrix[1], Matrix[2], Matrix[3], Matrix[4], Matrix[5]); if (ViewBox != null && (ViewBox[0] != 0 || ViewBox[1] != 0)) Transform(1, 0, 0, 1, -ViewBox[0], -ViewBox[1]); } private void Transform(float a, float b, float c, float d, float e, float f) { Root.Transform(a, b, c, d, e, f); } public void Dump(SvgGroupNode root) { // logger.log(Level.FINE, "current file is :" + mFileName); root.DumpNode(""); } public SvgGroupNode Root { get; set; } public void LogErrorLine(string s, XmlNode node, SvgLogLevel level) { if (!string.IsNullOrEmpty(s)) { if (node != null) { var position = getPosition(node); if (position != null && position.HasLineInfo()) errorLines.Add(level.ToString() + "@ line " + (position.LineNumber + 1) + " " + s + "\n"); else errorLines.Add(s); } else { errorLines.Add(s); } } } /** * @return Error log. Empty string if there are no errors. */ public string GetErrorLog() { var errorBuilder = new StringBuilder(); if (errorLines.Any()) { errorBuilder.Append("In " + Filename + ":\n"); } foreach (var log in errorLines) { errorBuilder.Append(log); } return errorBuilder.ToString(); } /** * @return true when there is no error found when parsing the SVG file. */ public bool CanConvertToVectorDrawable() => !errorLines.Any(); IXmlLineInfo getPosition(XmlNode node) { return null; // TODO: Get position } } }
using System; using log4net; namespace Sind.BLL.Infrastructure.Log { public class Logger : ILogger { private const string LogInFile = "LogInfoInFile"; private ILog _log; private ILog log { get { if (_log == null) _log = Configure(); return _log; } } private ILog Configure() { log4net.Config.XmlConfigurator.Configure(); return log4net.LogManager.GetLogger(LogInFile); } public void Informativo(string mensagem) { log.Info(mensagem); } public void Erro(string mensagem) { log.Error(mensagem); } public void Erro(Exception exception) { log.Error(exception.Message, exception); } public void Erro(string mensagem, Exception exception) { log.Error(mensagem, exception); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class Cookie1Destination : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { lblName.Text = "name is" + Request.Cookies["Name"].Value; lblAge.Text = "Age is " + Request.Cookies["Age"].Value; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; [RequireComponent(typeof(Collider))] public class SoundCollisionTrigger : MonoBehaviour { [Tooltip("The name/ID of the sound that should be played upon collision with this gameobject.")] public string soundName = "Blank"; [Tooltip("Should the colliders of this gameobject and its children be triggers or not?")] public bool triggerCollider = true; //Array for all colliders on object private Collider[] col; private void Awake() { col = transform.GetComponentsInChildren<Collider>(); foreach (Collider item in col) { item.isTrigger = triggerCollider; } //Debug.Log("Colliders: " + col.Length); } private void OnTriggerEnter(Collider other) { if (triggerCollider) SoundManager.PlaySound(soundName); } private void OnCollisionEnter(Collision collision) { if (!triggerCollider) SoundManager.PlaySound(soundName); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Timer : MonoBehaviour { [SerializeField] private float maxTimeSeconds; private float counter; private void Awake() { counter = maxTimeSeconds; } private void Update() { counter -= Time.deltaTime; } public float GetTimeLeftInPercent() { return (counter/maxTimeSeconds); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using DelftTools.Utils; using GeoAPI.Extensions.Feature; using NUnit.Framework; using SharpMap.Layers; using SharpMap.Styles; using SharpMap.UI.Editors; namespace SharpMap.UI.Tests.Editors { [TestFixture] public class FeatureEditorTest { private class TestFeatureEditor : FeatureEditor { public TestFeatureEditor(ICoordinateConverter coordinateConverter, ILayer layer, IFeature feature, VectorStyle vectorStyle, IEditableObject editableObject) : base(coordinateConverter, layer, feature, vectorStyle, editableObject) { } public bool IsEditable { get; set; } protected override bool AllowDeletionCore() { return IsEditable; } protected override bool AllowMoveCore() { return IsEditable; } } [Test] public void CanDeleteAndMoveDependsOnGroupLayerReadOnly() { var map = new Map(); var groupLayer1 = new GroupLayer(); var groupLayer2 = new GroupLayer(); var layer = new VectorLayer(); groupLayer1.Layers.Add(groupLayer2); groupLayer2.Layers.Add(layer); map.Layers.Add(groupLayer1); var editor = new TestFeatureEditor(null, layer, null, null, null) {IsEditable = true}; Assert.IsTrue(editor.AllowDeletion()); Assert.IsTrue(editor.AllowMove()); groupLayer1.ReadOnly = true; Assert.IsFalse(editor.AllowDeletion()); Assert.IsFalse(editor.AllowMove()); } [Test] public void CanDeleteAndMoveDependsOnGroupLayerReadOnlyAndFeatureItself() { var map = new Map(); var groupLayer1 = new GroupLayer(); var groupLayer2 = new GroupLayer(); var layer = new VectorLayer(); groupLayer1.Layers.Add(groupLayer2); groupLayer2.Layers.Add(layer); map.Layers.Add(groupLayer1); var editor = new TestFeatureEditor(null, layer, null, null, null) { IsEditable = false }; Assert.IsFalse(editor.AllowDeletion()); Assert.IsFalse(editor.AllowMove()); groupLayer1.ReadOnly = true; Assert.IsFalse(editor.AllowDeletion()); Assert.IsFalse(editor.AllowMove()); } [Test] public void CanDeleteAndMoveDoesNotCrashWithEmptyLayer() { var editor = new FeatureEditor(null, null, null, null, null) {}; Assert.IsFalse(editor.AllowDeletion()); Assert.IsFalse(editor.AllowMove()); } [Test] public void CanDeleteAndMoveDoesNotCrashWithEmptyMap() { var layer = new VectorLayer(); var editor = new FeatureEditor(null, layer, null, null, null); Assert.IsFalse(editor.AllowDeletion()); Assert.IsFalse(editor.AllowMove()); } } }
using UnityEngine; public class AttackRangeTriggerForSpannerMonster : MonoBehaviour { public SpannerEnemyAI spannerEnemyAI; public EnemyController2D enemyController2D; public void Awake() { spannerEnemyAI = GetComponentInParent<SpannerEnemyAI>(); enemyController2D = GetComponentInParent<EnemyController2D>(); } public void OnTriggerEnter2D(Collider2D col) { if (col.CompareTag("Player") && (col.GetComponent<Player>().IsDead == false)) { spannerEnemyAI.Attack(); LevelManager.Instance.KillPlayer(); enemyController2D.SetHorizontalForce(0); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; using System.Diagnostics; using System.Runtime.InteropServices; using System.Reflection; using System.Configuration; using IRAP.Global; using IRAP.AutoUpgrade; namespace IRAPPrinterServer { static class Program { //API 常数定义 private const int SW_HIDE = 0; private const int SW_NORMAL = 1; private const int SW_MAXIMIZE = 3; private const int SW_SHOWNOACTIVATE = 4; private const int SW_SHOW = 5; private const int SW_MINIMIZE = 6; private const int SW_RESTORE = 9; private const int SW_SHOWDEFAULT = 10; [DllImport("user32.dll")] private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow); [DllImport("user32.dll")] private static extern bool SetForegroundWindow(IntPtr hWnd); /// <summary> /// 应用程序的主入口点。 /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); #region 判断是否已经运行本程序的另一个实例 Process instance = GetRunningInstance(); if (instance != null) { HandleRunningInstance(instance); return; } #endregion if (WriteLog.Instance.IsWriteLog != SystemParams.Instance.WriteLog) WriteLog.Instance.IsWriteLog = SystemParams.Instance.WriteLog; string strProcedureName = string.Format( "{0}.{1}", MethodBase.GetCurrentMethod().DeclaringType.FullName, MethodBase.GetCurrentMethod().Name); WriteLog.Instance.WriteBeginSplitter(strProcedureName); WriteLog.Instance.Write( string.Format("运行 IRAP Printer Server (V {0})", "6.1"), strProcedureName); try { #if !DEBUG #region 系统自动更新 if (SystemParams.Instance.UpgradeURL != "") { WriteLog.Instance.Write("系统自动更新", strProcedureName); Upgrade.Instance.URLCFGFileName = SystemParams.Instance.UpgradeURL; if (Upgrade.Instance.CanUpgrade) { WriteLog.Instance.Write("系统开始更新...", strProcedureName); if (Upgrade.Instance.Do() == -1) { Process.Start(Application.ExecutablePath); WriteLog.Instance.Write("重新启动系统", strProcedureName); return; } WriteLog.Instance.Write("系统更新完成...", strProcedureName); } else { WriteLog.Instance.Write("系统无法自动更新", strProcedureName); } } #endregion #endif Application.Run(new frmPrinterServerMain()); } catch (Exception error) { WriteLog.Instance.Write(error.Message, strProcedureName); } finally { WriteLog.Instance.Write("退出 IRAP Printer Server", strProcedureName); WriteLog.Instance.WriteEndSplitter(strProcedureName); WriteLog.Instance.Write(""); } } /// <summary> /// 获取当前系统是否有相同的进程 /// </summary> /// <returns></returns> public static Process GetRunningInstance() { Process current = Process.GetCurrentProcess(); Process[] processes = Process.GetProcessesByName(current.ProcessName); // 遍历具有相同名字的正在运行的进程 foreach (Process process in processes) { // 忽略现有的进程 if (process.Id != current.Id) { // 确保例程是从EXE文件运行 if (Assembly.GetExecutingAssembly().Location.Replace("/", "\\") == current.MainModule.FileName) { return process; } } } return null; } /// <summary> /// 激活原有进程 /// </summary> public static void HandleRunningInstance(Process instance) { ShowWindowAsync(instance.MainWindowHandle, SW_SHOW); SetForegroundWindow(instance.MainWindowHandle); } } }
using Pelican.Config; using Pelican.Menus; using Pelican.Items; using StardewModdingAPI; using StardewModdingAPI.Events; namespace Pelican { public class ModEntry : Mod { private IModHelper helper; public override void Entry(IModHelper helper) { this.helper = helper; ControlEvents.KeyPressed += ControlEvents_KeyPressed; } private void ControlEvents_KeyPressed(object sender, EventArgsKeyPressed e) { if (Context.IsWorldReady) { Meta.Config = helper.ReadConfig<ModConfig>(); if (e.KeyPressed.ToString().Equals(Meta.Config.MenuAccessKey)) { Meta.Console = Monitor; Meta.Lang = helper.Translation; ItemHandler itemHandler = new ItemHandler(); PostalService menu = new PostalService(itemHandler); menu.Open(); } } } } }
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 Автошкола { public partial class CarriersRepairsForm : Form { public CarriersRepairsForm() { InitializeComponent(); } BusinessLogic BusinessLogic = new BusinessLogic(); AutoschoolDataSet dataSet; string LastSearchingText = ""; int LastFoundRow = -1; int LastSelectionIndex; bool FirstLoad = true; void ReloadCarriersRepairs() { dataSet = BusinessLogic.ReadCarriersRepairs(); CarriersRepairs_dataGridView.DataSource = dataSet; CarriersRepairs_dataGridView.DataMember = "CarriersRepairs"; CarriersRepairs_dataGridView.Columns["ID"].Visible = false; CarriersRepairs_dataGridView.Columns["Carrier"].Visible = false; CarriersRepairs_dataGridView.Columns["Master"].Visible = false; CarriersRepairs_dataGridView.Columns["Work"].Visible = false; CarriersRepairs_dataGridView.Columns["BeginDate"].Visible = false; CarriersRepairs_dataGridView.Columns["EndDate"].Visible = false; IDColumn.DataPropertyName = "ID"; CarrierColumn.DataSource = dataSet.Carriers; CarrierColumn.DisplayMember = "FinalName"; CarrierColumn.ValueMember = "ID"; CarrierColumn.DataPropertyName = "Carrier"; MasterColumn.DataSource = dataSet.ServiceMasters; MasterColumn.DisplayMember = "FIO"; MasterColumn.ValueMember = "ID"; MasterColumn.DataPropertyName = "Master"; WorkColumn.DataPropertyName = "Work"; BeginDateColumn.DataPropertyName = "BeginDate"; EndDateColumn.DataPropertyName = "EndDate"; if (LastSelectionIndex != -1) CarriersRepairs_dataGridView.CurrentCell = CarriersRepairs_dataGridView[1, LastSelectionIndex]; } private void CarriersRepairsForm_Load(object sender, EventArgs e) { LastSelectionIndex = -1; ReloadCarriersRepairs(); Edit_button.Enabled = false; Delete_button.Enabled = false; CarriersRepairs_dataGridView_SelectionChanged(sender, e); } private void CarriersRepairs_dataGridView_SelectionChanged(object sender, EventArgs e) { if (CarriersRepairs_dataGridView.SelectedRows.Count == 1) { Edit_button.Enabled = true; Delete_button.Enabled = true; } else { Edit_button.Enabled = false; Delete_button.Enabled = false; } } private void Search_button_Click(object sender, EventArgs e) { SearchingInDataGridViewClass.Search(Search_textBox, ref CarriersRepairs_dataGridView, Direction_checkBox, ref LastSearchingText, ref LastFoundRow, "MasterColumn", "CarrierColumn", "WorkColumn"); } private void Search_textBox_KeyPress(object sender, KeyPressEventArgs e) { if ((char)e.KeyChar == (Char)Keys.Enter) { Search_button_Click(sender, e); } if ((char)e.KeyChar == (Char)Keys.Back) { LastSearchingText = ""; } } private void ReloadCarriersRepairs_button_Click(object sender, EventArgs e) { LastSelectionIndex = -1; ReloadCarriersRepairs(); } private void CarriersRepairsForm_FormClosing(object sender, FormClosingEventArgs e) { MainForm.Perem(MainForm.FormsNames[10], false); } private void Close_button_Click(object sender, EventArgs e) { Close(); } private void Add_button_Click(object sender, EventArgs e) { ReloadCarriersRepairs(); AddEditCarrierRepairForm AddCarrierRepair = new AddEditCarrierRepairForm(dataSet.CarriersRepairs, dataSet.ServiceMasters, dataSet.Carriers, null); AddCarrierRepair.Text = "Добавление ремонта ТС"; this.Enabled = false; AddCarrierRepair.ShowDialog(); if (AddCarrierRepair.DialogResult == DialogResult.OK) { dataSet = BusinessLogic.WriteCarriersRepairs(dataSet); ReloadCarriersRepairs(); } this.Enabled = true; } private void Edit_button_Click(object sender, EventArgs e) { LastSelectionIndex = CarriersRepairs_dataGridView.SelectedRows[0].Index; ReloadCarriersRepairs(); AddEditCarrierRepairForm EditCarrierRepair = new AddEditCarrierRepairForm(dataSet.CarriersRepairs, dataSet.ServiceMasters, dataSet.Carriers, dataSet.CarriersRepairs.Rows.Find(CarriersRepairs_dataGridView.SelectedRows[0].Cells["ID"].Value)); EditCarrierRepair.Text = "Редактирование ремонта ТС"; this.Enabled = false; EditCarrierRepair.ShowDialog(); if (EditCarrierRepair.DialogResult == DialogResult.OK) { dataSet = BusinessLogic.WriteCarriersRepairs(dataSet); ReloadCarriersRepairs(); } this.Enabled = true; } private void Delete_button_Click(object sender, EventArgs e) { LastSelectionIndex = -1; if (CarriersRepairs_dataGridView.SelectedRows.Count != 1) { MessageBox.Show("Не выбрана строка для удаления", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } DialogResult result = MessageBox.Show("Вы действительно хотите удалить выбранную запись?", "Подтверждение удаления", MessageBoxButtons.YesNo, MessageBoxIcon.Warning); if (result == DialogResult.Yes) { try { dataSet.CarriersRepairs.Rows.Find(CarriersRepairs_dataGridView.SelectedRows[0].Cells["ID"].Value).Delete(); dataSet = BusinessLogic.WriteCarriersRepairs(dataSet); ReloadCarriersRepairs(); } catch { MessageBox.Show("Не удалось удалить выбранную строку.\nСкорее всего, на данную строку имеются ссылки из других таблиц", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); ReloadCarriersRepairs(); } } } private void CarriersRepairsForm_VisibleChanged(object sender, EventArgs e) { if (Visible) { if (!FirstLoad) ReloadCarriersRepairs_button_Click(sender, e); else FirstLoad = false; } } } }
using MongoDB.Bson; using MongoDB.Bson.Serialization.Attributes; using Nailhang.IndexBase.Storage; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Nailhang.Mongodb.ZonesStorage.Processing { class ZoneEntity { [BsonId] public string Id { get; set; } public string Description { get; set; } public string[] ComponentIds { get; set; } public ZoneType Type { get; set; } } }
using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using Discord; using Discord.Commands; using FifthBot.Core.Data; namespace FifthBot.Core.Commands { public class Attacks : ModuleBase<SocketCommandContext> { [RequireOwner(Group = "Permission")] [Command("shoot"), Alias("shootwithagun"), Summary("Shoot someone with a gun!")] public async Task shoot(IUser User = null) { if (User == null) { await Context.Channel.SendMessageAsync($"Who were you trying to shoot, {Context.User.Mention}?"); return; } await Context.Channel.SendMessageAsync($"*{Context.User.Mention} shoots {User.Mention} with a gun! BLAM!* :gun:"); await DataMethods.SaveAttack(Context.User.Id, User.Id, "shoot"); return; } [RequireOwner(Group = "Permission")] [Command("spank"), Summary("Spank a butt!")] public async Task Spank(IUser User = null) { if (User == null) { await Context.Channel.SendMessageAsync($"Who were you trying to spank, {Context.User.Mention}?"); return; } await Context.Channel.SendMessageAsync($"*{Context.User.Mention} spanks {User.Mention} right on the butt! YOWCH!* :clap:"); await DataMethods.SaveAttack(Context.User.Id, User.Id, "spank"); return; } [RequireOwner(Group = "Permission")] [Command("whip"), Summary("Crack a whip!")] public async Task Whip(IUser User = null) { if (User == null) { await Context.Channel.SendMessageAsync($"Who were you trying to whip, {Context.User.Mention}?"); return; } await Context.Channel.SendMessageAsync($"*{Context.User.Mention} lashes {User.Mention} with a whip! CRACK!*"); await DataMethods.SaveAttack(Context.User.Id, User.Id, "whip"); return; } [RequireOwner(Group = "Permission")] [Command("dodge"), Alias("dodges"), Summary("Dodge an attack!")] public async Task Dodge() { await DataMethods.RemoveOldAttacks(); (ulong AttackerId, string Name) = DataMethods.getAttacker(Context.User.Id); if(AttackerId == 0) { await Context.Channel.SendMessageAsync("what are you dodging?"); return; } else { Random rng = new Random(); int DodgeAttempt = rng.Next(1, 100); IUser Attacker = Context.Guild.GetUser(AttackerId); if (Name.Equals("shoot")) { if (DodgeAttempt > 50) { await Context.Channel.SendMessageAsync($"*{Context.User.Mention} dodges a bullet from {Attacker.Mention}! Wow, that was quick!*"); } else { await Context.Channel.SendMessageAsync($"*{Context.User.Mention} fails to dodge, and takes a bullet right in the face from {Attacker.Mention}!* :boom:"); } } else if (Name.Equals("spank")) { if (DodgeAttempt > 70) { await Context.Channel.SendMessageAsync($"*{Context.User.Mention} gets their butt out of the way! Better luck next time {Attacker.Mention}!*"); } else { await Context.Channel.SendMessageAsync($"*{Context.User.Mention} fails to dodge, and takes a spank right on the butt from {Attacker.Mention}!* :boom:"); } } else if (Name.Equals("whip")) { if (DodgeAttempt > 60) { await Context.Channel.SendMessageAsync($"*{Attacker.Mention} cracks their whip at thin air as {Context.User.Mention} evades!*"); } else { await Context.Channel.SendMessageAsync($"*{Context.User.Mention} fails to dodge, and takes a vicious lashing from {Attacker.Mention}!* :boom:"); } } await DataMethods.RemoveAttack(Context.User.Id); } } } }
//----------------------------------------------------------------------- // <copyright file="Aggregate.cs" company="4Deep Technologies LLC"> // Copyright (c) 4Deep Technologies LLC. All rights reserved. // <author>Darren Ford</author> // <date>Thursday, April 30, 2015 3:00:44 PM</date> // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections; using System.Reflection; namespace Dizzle.Cqrs.Core { /// <summary> /// Aggregate base class, which factors out some common infrastructure that /// all aggregates have (ID and event application). /// </summary> public class Aggregate : IAggregate { /// <summary> /// The number of events loaded into this aggregate. /// </summary> public long EventsLoaded { get; private set; } public static Dictionary<Type, MethodInfo> Cache = new Dictionary<Type, MethodInfo>(); public AbstractIdentity<Guid> Id { get; set; } /// <summary> /// Enumerates the supplied events and applies them in order to the aggregate. /// </summary> /// <param name="events"></param> public void ApplyEvents(IEnumerable<IEvent> events) { //this is a slow way to go about this //the method should be cached by type so you don't have to muck with reflection over and over foreach (var e in events) { Type typ = e.GetType(); if (Cache.ContainsKey(typ)) { //fire the action! Cache[typ].Invoke(this, new object[] { e }); } else { var method = GetType().GetRuntimeMethods().Single(t => t.Name.Equals("ApplyOneEvent")) .MakeGenericMethod(typ); method.Invoke(this, new object[] { e }); //invoke first because if the invoke fails then caching it does no good because it doesn't work! Cache[typ] = method; } } } //public void ApplyEvents(IEnumerable events) //{ // //this is a slow way to go about this // //the method should be cached by type so you don't have to muck with reflection over and over // foreach (var e in events) // GetType().GetRuntimeMethods().Single(t => t.Name.Equals("ApplyOneEvent")) // .MakeGenericMethod(e.GetType()) // .Invoke(this, new object[] { e }); //} /// <summary> /// Applies a single event to the aggregate. /// </summary> /// <typeparam name="TEvent"></typeparam> /// <param name="ev"></param> public void ApplyOneEvent<TEvent>(TEvent ev) { var applier = this as IApplyEvent<TEvent>; if (applier == null) throw new InvalidOperationException(string.Format( "Aggregate {0} does not know how to apply event {1}", GetType().Name, ev.GetType().Name)); applier.Apply(ev); EventsLoaded++; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IG_WPF_Library.Data { public class ScatterDataBase : ObservableModel { private double _x; private double _y; public double X { get { return _x; } set { if(_x != value) { _x = value; OnPropertyChanged(); } } } public double Y { get { return _y; } set { if (_y != value) { _y = value; OnPropertyChanged(); } } } } public class ScatterBubbleData : ScatterDataBase { private double _radius; public double Radius { get { return _radius; } set { if (_radius != value) { _radius = value; OnPropertyChanged(); } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace St.Eg.Day3.M2.Ex2.PLINQ { class Program { static void Main(string[] args) { var data = Enumerable.Range(0, 100); var count = 0; var query = data.AsParallel().WithDegreeOfParallelism(5) .Select(i => { Interlocked.Increment(ref count); Console.WriteLine("Starting task: {0}", count); Task.Delay(500).Wait(); Console.WriteLine("Exiting task: {0}", count); return i * i; }); var results = query.ToList(); results.ForEach(r => Console.WriteLine(r)); } } }
using System; namespace Profiling2.Web.Mvc.Areas.Profiling.Controllers.ViewModels { public class DateViewModel { public string StartDate { get; set; } public string EndDate { get; set; } public DateViewModel() { } public DateViewModel(DateTime startDate, DateTime endDate) { this.StartDate = string.Format("{0:yyyy-MM-dd}", startDate); this.EndDate = string.Format("{0:yyyy-MM-dd}", endDate); } public DateTime StartDateAsDate { get { return DateTime.Parse(this.StartDate); } } public DateTime EndDateAsDate { get { return DateTime.Parse(this.EndDate); } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Drawing; using System.IO; using System.Linq; using System.Net.Http; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; namespace Winforms { public partial class ParallelismForm1 : Form { private string apiURL; private HttpClient httpClient; private CancellationTokenSource cts; public ParallelismForm1() { InitializeComponent(); apiURL = "https://localhost:44342/api"; httpClient = new HttpClient(); } private async void btnStart_Click(object sender, EventArgs e) { LoadingGif.Visible = true; var currentDirectory = AppDomain.CurrentDomain.BaseDirectory; var destinationSequential = Path.Combine(currentDirectory, @"images\result-sequential"); var destinationSimultaneous = Path.Combine(currentDirectory, @"images\result-simultaneous"); PrepareExecution(destinationSimultaneous, destinationSequential); Console.WriteLine("begin"); var images = GetImages(); var stopwatch = new Stopwatch(); stopwatch.Start(); // Sequential Part foreach (var image in images) { await ProcessImage(destinationSequential, image); } var timeSequential = stopwatch.ElapsedMilliseconds / 1000; Console.WriteLine("Sequential - duration: {0} seconds", timeSequential); // Simultaneous Part stopwatch.Restart(); var tasks = images.Select(async image => await ProcessImage(destinationSimultaneous, image)); await Task.WhenAll(tasks); var timeSimultaneous = stopwatch.ElapsedMilliseconds / 1000; Console.WriteLine("Simultaneous - duration: {0} seconds", timeSimultaneous); WriteComparison(timeSequential, timeSimultaneous); LoadingGif.Visible = false; } private static List<ImageDTO> GetImages() { var images = new List<ImageDTO>(); for (int i = 0; i < 5; i++) { { images.Add( new ImageDTO() { Name = $"Spider-Man Spider-Verse {i}.jpg", URL = "https://m.media-amazon.com/images/M/MV5BMjMwNDkxMTgzOF5BMl5BanBnXkFtZTgwNTkwNTQ3NjM@._V1_UY863_.jpg" }); images.Add( new ImageDTO() { Name = $"Spider-Man Far From Home {i}.jpg", URL = "https://m.media-amazon.com/images/M/MV5BMGZlNTY1ZWUtYTMzNC00ZjUyLWE0MjQtMTMxN2E3ODYxMWVmXkEyXkFqcGdeQXVyMDM2NDM2MQ@@._V1_UY863_.jpg" }); images.Add( new ImageDTO() { Name = $"Moana {i}.jpg", URL = "https://lumiere-a.akamaihd.net/v1/images/r_moana_header_poststreet_mobile_bd574a31.jpeg?region=0,0,640,480" }); images.Add( new ImageDTO() { Name = $"Avengers Infinity War {i}.jpg", URL = "https://img.redbull.com/images/c_crop,x_143,y_0,h_1080,w_1620/c_fill,w_1500,h_1000/q_auto,f_auto/redbullcom/2018/04/23/e4a3d8a5-2c44-480a-b300-1b2b03e205a5/avengers-infinity-war-poster" }); //images.Add( //new ImageDTO() //{ // Name = $"Avengers Endgame {i}.jpg", // URL = "https://hipertextual.com/files/2019/04/hipertextual-nuevo-trailer-avengers-endgame-agradece-fans-universo-marvel-2019351167.jpg" //}); } } return images; } public static void WriteComparison(double time1, double time2) { var difference = time2 - time1; difference = Math.Round(difference, 2); var porcentualIncrement = ((time2 - time1) / time1) * 100; porcentualIncrement = Math.Round(porcentualIncrement, 2); Console.WriteLine($"Difference {difference} ({porcentualIncrement}%)"); } private async Task ProcessImage(string directorio, ImageDTO imagen) { var response = await httpClient.GetAsync(imagen.URL); var content = await response.Content.ReadAsByteArrayAsync(); Bitmap bitmap; using (var ms = new MemoryStream(content)) { bitmap = new Bitmap(ms); } bitmap.RotateFlip(RotateFlipType.Rotate90FlipNone); var destination = Path.Combine(directorio, imagen.Name); bitmap.Save(destination); } public static void PrepareExecution(string destinationParallel, string destinationSequential) { if (!Directory.Exists(destinationParallel)) { Directory.CreateDirectory(destinationParallel); } if (!Directory.Exists(destinationSequential)) { Directory.CreateDirectory(destinationSequential); } DeleteFiles(destinationSequential); DeleteFiles(destinationParallel); } public static void DeleteFiles(string directory) { var files = Directory.EnumerateFiles(directory); foreach (var file in files) { File.Delete(file); } } } }
using GalaSoft.MvvmLight.Messaging; namespace JeopardySimulator.Ui.Messages { public class RoundEndedMessage : MessageBase { public RoundEndedMessage(bool isGameEnded = false) { IsGameEnded = isGameEnded; } public bool IsGameEnded { get; private set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using Olive.Data; using System.ComponentModel.DataAnnotations; using System.Web.Mvc; namespace Olive.Web.MVC.Areas.Administration.ViewModels { public class AdminRecipeViewModel { public Recipe Recipe { get; set; } public int RecipeID { get; set; } [Required] public string Title { get; set; } public HttpPostedFileBase Image { get; set; } public string ImageURL { get; set; } public string ImageVersion { get; set; } public IEnumerable<Category> ParentCategories { get; set; } [Required] public int SelectedParentCategory { get; set; } public IEnumerable<Category> ChildrenCategories { get; set; } public int? SelectedChildrenCategory { get; set; } public IEnumerable<int> PrepTimeHours { get; set; } public int SelectedPrepTimeHours { get; set; } public IEnumerable<int> PrepTimeMinutes { get; set; } public int SelectedPrepTimeMinutes { get; set; } public IEnumerable<int> CookTimeHours { get; set; } public int SelectedCookTimeHours { get; set; } public IEnumerable<int> CookTimeMinutes { get; set; } public int SelectedCookTimeMinutes { get; set; } public IEnumerable<int> Serves { get; set; } public int SelectedServes { get; set; } public IEnumerable<int> Rating { get; set; } public int SelectedRating { get; set; } public IEnumerable<Source> Sources { get; set; } public int SelectedSource { get; set; } public IEnumerable<string> Recommendation { get; set; } public string SelectedRecommendation { get; set; } public DateTime PublishedDate { get; set; } [DataType(DataType.MultilineText)] [AllowHtml] public string Description { get; set; } public int NumberOfHits { get; set; } public int NumberOfLikes { get; set; } //public List<AdminStepViewModel> Steps { get; set; } public List<RecipeItem> RecipeItems { get; set; } public AdminRecipeViewModel() { Recipe = new Recipe(); RecipeItems = new List<RecipeItem>(); } } }
namespace Silo { public class SiloRunResult { public SiloRunStatus status; } public enum SiloRunStatus { Ready, Error } }
namespace Unit_Test_Demo.Commands { public class CreateContainerCommand { public int MaxCapacity { get; set; } } }
namespace Application.Utilities { using System.Linq; using Data.Interfaces; using Models; using SimpleHttpServer.Models; using SimpleHttpServer.Utilities; public static class AuthenticationManager { public static bool IsUserAuthenticated(this HttpSession session, IDataProvidable data) { return data.Logins.GetAll().Any(login => login.SessionId == session.Id && login.IsActive); } public static User GetAuthenticatedUser(this HttpSession session, IDataProvidable data) { var login = data.Logins.Find(l => l.SessionId == session.Id && l.IsActive); return login?.User; } public static void Logout(this HttpSession session, IDataProvidable data, HttpResponse response) { var login = data.Logins.Find(l => l.SessionId == session.Id && l.IsActive); login.IsActive = false; data.SaveChanges(); var newSession = SessionCreator.Create(); var sessionCookie = new Cookie("sessionId", $"{newSession.Id}; HttpOnly; path=/"); response.Header.AddCookie(sessionCookie); } } }
using CarManageSystem.helper; using CarManageSystem.Model; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Web; using System.Web.SessionState; namespace CarManageSystem.handler.UserManage.Driver { /// <summary> /// AccessDriver 的摘要说明 /// </summary> public class AccessDriver : IHttpHandler,IRequiresSessionState { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; //是否有部门管理员权限 var currentUser = CheckHelper.RoleCheck(context, 1); if (currentUser == null) return; dynamic json = new JObject(); json.state = "success"; var ids = new List<string>(); Model.Users driverArry=new Users() { Ids= ids }; //先看是在首页通过的,还是在人员管理处进行通过的。 if (context.Request.Params.AllKeys.Contains("drivers")) //人员管理 { var driver = context.Request["drivers"]; driverArry=JsonConvert.DeserializeObject<Users>(driver); } else if(context.Request.Params.AllKeys.Contains("uniqueCode")) //首页 { var uniqueCode = context.Request["uniqueCode"]; using (cmsdbEntities cms = new cmsdbEntities()) { var _msg = cms.msg_userapply.FirstOrDefault(s => s.Id == uniqueCode&&s.IsAudit==null); if(_msg==null) { json.state = "错误:用户已被审核,请刷新重试"; context.Response.Write(json.ToString()); return; } var tempRole = Convert.ToInt32(_msg.AccessRole); var tempUser = cms.user.FirstOrDefault(s => s.Account == _msg.AccessUser && s.ApplyRole == tempRole&&s.ApplyState==0); if(tempUser==null) { json.state = "错误:用户已被审核,请刷新重试"; context.Response.Write(json.ToString()); return; } driverArry.Ids.Add(tempUser.Account); cms.Dispose(); } } var access = context.Request["access"]; var now = DateTime.Now; using (cmsdbEntities cms = new cmsdbEntities()) { var dri = cms.user.Where(u => driverArry.Ids.Contains(u.Account)).ToList(); if(Convert.ToInt16(access)==1) { foreach (var d in dri) { var temprole = d.ApplyRole; var _msg = cms.msg_userapply .FirstOrDefault(s => s.AccessUser == d.Account && ((s.IsAudit == 0 || s.IsAudit == null) && s.AccessRole == temprole)); _msg.IsAudit = 1; _msg.AuditTime = now; _msg.AuditUser = currentUser.Account; var tempRole = d.ApplyRole; d.UserType = tempRole; d.ApplyState = 1;//通过 //推送 //Task.Factory.StartNew(() => //{ try { var msg = "您申请的"; if (d.UserType == 0) { msg += "司机"; } else if (d.UserType == 1) { msg += "部门管理员"; } else if (d.UserType == 2) { msg += "院级管理员"; } msg += "已通过审核"; PushHelper.PushToUser(d, "人员审核", msg); } catch(Exception ex) { } //}); } } else { foreach (var d in dri) { var temprole = d.ApplyRole; var _msg = cms.msg_userapply .FirstOrDefault(s => s.AccessUser == d.Account && ((s.IsAudit == 0 || s.IsAudit == null) && s.AccessRole == temprole)); _msg.IsAudit = 2; _msg.AuditTime = now; _msg.AuditUser = currentUser.Account; d.ApplyState = 2;//拒绝 } } cms.SaveChanges(); cms.Dispose(); context.Response.Write(json.ToString()); } } public bool IsReusable { get { return false; } } } }
namespace Welic.Dominio.Core.Web { public static class TempDataKeys { public readonly static string UserMessage = "UserMessage"; public readonly static string UserMessageAlertState = "UserMessageAlertState"; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _08.GreatestCommonDivisor { class GCD { static void Main() { Console.WriteLine("Enter an integer:"); int firstNum = int.Parse(Console.ReadLine()); Console.WriteLine("Enter second integer:"); int secondNum = int.Parse(Console.ReadLine()); Console.WriteLine("The Greatest Common Divisor is:"); while (firstNum != 0 && secondNum != 0) { if (firstNum > secondNum) { firstNum %= secondNum; } else { secondNum %= firstNum; } } if (firstNum == 0) { Console.WriteLine(secondNum); } else { Console.WriteLine(firstNum); } } } }
namespace LoowooTech.Stock.Models { public class VillageMessage { public string Value { get; set; } public string CheckValue { get; set; } public string Description { get; set; } public string WhereClause { get; set; } } }
using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace InvoiceNet.Data { public class SqlConnection : IDbConnection { #region Variables private IDbConnection m_connection; #endregion #region Properties public string ConnectionString { get { return m_connection.ConnectionString; } set { m_connection.ConnectionString = value; } } public int ConnectionTimeout { get { return m_connection.ConnectionTimeout; } } public string Database { get { return m_connection.Database; } } public ConnectionState State { get { return m_connection.State; } } #endregion #region Methods public IDbTransaction BeginTransaction() { return m_connection.BeginTransaction(); } public IDbTransaction BeginTransaction(IsolationLevel il) { return m_connection.BeginTransaction(il); } public void ChangeDatabase(string databaseName) { m_connection.ChangeDatabase(databaseName); } public void Close() { m_connection.Close(); } IDbCommand IDbConnection.CreateCommand() { return new SqlCommand(m_connection.CreateCommand()); } public SqlCommand CreateCommand() { return new SqlCommand(m_connection.CreateCommand()); } public void Dispose() { if (m_connection != null) { if (m_connection.State != ConnectionState.Closed) { m_connection.Close(); } m_connection.Dispose(); m_connection = null; } } public void Open() { m_connection.Open(); } #endregion #region Constructors public SqlConnection(IDbConnection connection) { m_connection = connection; } #endregion } }
using System; using JetBrains.Annotations; namespace SpeedSlidingTrainer.Core.Model.State.Validation { public sealed class BoardValidationError { public BoardValidationError(BoardValidationErrorType errorType, string message) : this(errorType, message, null) { } public BoardValidationError(BoardValidationErrorType errorType, [NotNull] string message, [CanBeNull] BoardPosition position) { if (message == null) { throw new ArgumentNullException("message"); } this.ErrorType = errorType; this.Message = message; this.Position = position; } public BoardValidationErrorType ErrorType { get; private set; } [NotNull] public string Message { get; private set; } [CanBeNull] public BoardPosition Position { get; private set; } public override string ToString() { return string.Format("ErrorType: {0}, Message: {1}, Position: {2}", this.ErrorType, this.Message, this.Position); } } }
using MessageClicker.Core.Entities; namespace MessageClicker.Core.Auth { public interface IUserProvider { User User { get; set; } } }
using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.IO; namespace Appnotics.Library.UI.UserControls { public class FolderViewModel : INotifyPropertyChanged { #region Data bool? _isChecked = false; bool _hasScanned = false; FolderViewModel _parent; #endregion // Data #region CreateFoos public static List<FolderViewModel> CreateFoos() { FolderViewModel root = new FolderViewModel("C:\\", "C:\\", true) { IsInitiallySelected = false }; root.Initialize(); return new List<FolderViewModel> { root }; } FolderViewModel(string name, string path, bool doChildren, bool isDummy = false) { this.Name = name; this.Path = path; this.IsDummy = isDummy; this.Children = new List<FolderViewModel>(); if (doChildren) FindChildren(); else if (!isDummy) // don't add dummies to dummies AddDummyChild(); // this ensures we have an expander } void AddDummyChild() { FolderViewModel child = new FolderViewModel("", "*", false, true); Children.Add(child); } void FindChildren() { Children.Clear(); DirectoryInfo di = new DirectoryInfo(Path); try { DirectoryInfo[] subdirectories = di.GetDirectories(); foreach (DirectoryInfo subdirectory in subdirectories) { if (subdirectory.Name.StartsWith("$Recycle")) Debug.WriteLine("recycle"); if (subdirectory.Name.StartsWith("$WIN")) continue; FolderViewModel child = new FolderViewModel(subdirectory.Name, subdirectory.FullName, false); Children.Add(child); } } catch { } _hasScanned = true; Initialize(); } void Initialize() { foreach (FolderViewModel child in this.Children) { child._parent = this; child.Initialize(); } } #endregion // CreateFoos #region Properties public List<FolderViewModel> Children { get; private set; } public bool IsInitiallySelected { get; private set; } private bool isNodeExpanded; public bool IsNodeExpanded { get { return isNodeExpanded; } set { isNodeExpanded = value; if (isNodeExpanded) { if (!_hasScanned) { // scan now FindChildren(); } } } } public string Name { get; private set; } public string Path { get; private set; } private bool IsDummy { get; set; } #region IsChecked /// <summary> /// Gets/sets the state of the associated UI toggle (ex. CheckBox). /// The return value is calculated based on the check state of all /// child FooViewModels. Setting this property to true or false /// will set all children to the same check state, and setting it /// to any value will cause the parent to verify its check state. /// </summary> public bool? IsChecked { get { return _isChecked; } set { this.SetIsChecked(value, true, true); } } void SetIsChecked(bool? value, bool updateChildren, bool updateParent) { if (value == _isChecked) return; _isChecked = value; if (updateChildren && _isChecked.HasValue) this.Children.ForEach(c => c.SetIsChecked(_isChecked, true, false)); if (updateParent && _parent != null) _parent.VerifyCheckState(); this.OnPropertyChanged("IsChecked"); } void VerifyCheckState() { bool? state = null; for (int i = 0; i < this.Children.Count; ++i) { bool? current = this.Children[i].IsChecked; if (i == 0) { state = current; } else if (state != current) { state = null; break; } } this.SetIsChecked(state, false, true); } #endregion // IsChecked #endregion // Properties #region INotifyPropertyChanged Members void OnPropertyChanged(string prop) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(prop)); } public event PropertyChangedEventHandler PropertyChanged; #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using CAPCO.Infrastructure.Domain; using CAPCO.Infrastructure.Data; namespace CAPCO.Areas.Admin.Controllers { public class StoreLocationsController : Controller { private readonly IRepository<StoreLocation> storelocationRepository; public StoreLocationsController(IRepository<StoreLocation> storelocationRepository) { this.storelocationRepository = storelocationRepository; } public ViewResult Index() { return View(storelocationRepository.All); } public ViewResult Show(int id) { return View(storelocationRepository.Find(id)); } public ActionResult New() { return View(); } [HttpPost, ValidateAntiForgeryToken, ValidateInput(false)] public ActionResult Create(StoreLocation storelocation) { if (ModelState.IsValid) { storelocationRepository.InsertOrUpdate(storelocation); storelocationRepository.Save(); this.FlashInfo("The was successfully deleted."); return RedirectToAction("Index"); } else { this.FlashError("There was a problem creating the ."); return View("New", storelocation); } } public ActionResult Edit(int id) { return View(storelocationRepository.Find(id)); } [HttpPut, ValidateAntiForgeryToken, ValidateInput(false)] public ActionResult Update(StoreLocation storelocation) { if (ModelState.IsValid) { storelocationRepository.InsertOrUpdate(storelocation); storelocationRepository.Save(); this.FlashInfo("The was successfully saved."); return RedirectToAction("Index"); } else { this.FlashError("There was a problem saving the ."); return View("Edit", storelocation); } } public ActionResult Delete(int id) { storelocationRepository.Delete(id); storelocationRepository.Save(); this.FlashInfo("The was successfully deleted."); return RedirectToAction("Index"); } } }
namespace Models.Enemies { public class LargeEnemyModel : IEnemy { public EnemyType Type { get { return EnemyType.Large; } } public int Health { get { return 20; } } public int Damage { get { return 1; } } public float Speed { get { return 1; } } public decimal Price { get { return 5; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace RobotiLibrary { public class Unealta : Obiecte { public Unealta() { } public Unealta(string tip, string denumire) { this.denumire = denumire; this.tip = tip; } } }
using Common.Enums; using Common.Model; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Common.Contracts { public interface IDbGenerator { void Create(Generator generator); void ResetRemoteGenerators(); List<Generator> ReadAll(); List<Measurement> GetMeasurementsForGenerator(int generatorId); Generator GetGenerator(int id); List<Generator> ReadAllRemote(); List<Generator> ReadAllLocal(); List<Generator> ReadAllForLC(string code); List<int> ReadAllIds(string code); void UpdatePower(List<Generator> generators); void ChangeType(int generatorId, int newActivePower, EControl control); } }
using System.Collections.Generic; using System.IO; using LogFile.Generator.Core.LogModel; namespace LogFile.Generator.Core { public class FileCreator { private readonly ConfigMaker _config = new ConfigMaker(); private readonly ToStringConverter _myConverter = new ToStringConverter(); private readonly List<string> _myLogs = new List<string>(); private readonly LogsGenerator _myLogsGen = new LogsGenerator(); private UserConfig _userConf = new UserConfig(); public void CreateFile(int logsCount, string fileName, string configPath) { _userConf = _config.MakeConfig(configPath); _myLogsGen.SetConfig(_userConf); foreach (var obj in _myLogsGen.LogStringsGenerator(logsCount)) _myLogs.Add(_myConverter.Convert(obj)); File.WriteAllLines(fileName, _myLogs); } } }
namespace SimpleHttpServer { using System; using System.Collections.Generic; using System.Linq; using System.Net.Sockets; using System.Text; using System.Text.RegularExpressions; using Enums; using Helpers; using Models; public class HttpProcessor { public HttpProcessor(IEnumerable<Route> routes) { this.Routes = new List<Route>(routes); } public HttpRequest Request { get; set; } public HttpResponse Response { get; set; } public IList<Route> Routes { get; set; } public void HandleClient(TcpClient tcpClient) { using (var stream = tcpClient.GetStream()) { this.Request = this.GetRequest(stream); this.Response = this.RouteRequest(); StreamUtils.WriteResponse(stream, this.Response); } } private HttpResponse RouteRequest() { var routes = this.Routes .Where(x => Regex.Match(Request.Url, x.UrlRegex).Success) .ToList(); if (!routes.Any()) { return HttpResponseBuilder.NotFound(); } var route = routes.SingleOrDefault(x => x.Method == Request.Method); if (route == null) { return new HttpResponse() { StatusCode = ResponseStatusCode.MethodNotAllowed }; } try { return route.Callable(Request); } catch (Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); return HttpResponseBuilder.InternalServerError(); } } private HttpRequest GetRequest(NetworkStream stream) { var requestArgs = StreamUtils .ReadLine(stream) .Split(' '); string requestMethod = requestArgs[0]; string requestUrl = requestArgs[1]; string requestProtocolVersion = requestArgs[2]; if (requestMethod == null || requestUrl == null || requestProtocolVersion == null) { throw new NullReferenceException("Some of request elements is missing!"); } Header header = new Header(HeadeType.HttpRequest); string line; while ((line = StreamUtils.ReadLine(stream)) != null) { if (line == "") { break; } var headerParams = line.Split(new[] { ':' }, 2).Select(s => s.Trim()).ToArray(); string name = headerParams[0]; string value = headerParams[1]; if (name.ToLower() == "cookie") { string[] cookies = value.Split(';'); foreach (var cookie in cookies) { string[] cookieArgs = cookie.Split('='); var cookieName = cookieArgs[0]; var cookieValue = cookieArgs[1]; Cookie cookieObject = new Cookie { Name = cookieName, Value = cookieValue }; header.Cookies.AddCookie(cookieObject); } } else if (name.ToLower() == "content-length") { header.ContentLength = value; } else { header.OtherParameters.Add(name, value); } } string content = null; if (header.ContentLength != null) { int totalBytes = Convert.ToInt32(header.ContentLength); int bytesLeft = totalBytes; byte[] bytes = new byte[totalBytes]; while (bytesLeft > 0) { byte[] buffer = new byte[bytesLeft > 1024 ? 1024 : bytesLeft]; int n = stream.Read(buffer, 0, buffer.Length); buffer.CopyTo(bytes, totalBytes - bytesLeft); bytesLeft -= n; } content = Encoding.ASCII.GetString(bytes); } var request = new HttpRequest { Method = (RequestMethod)Enum.Parse(typeof(RequestMethod), requestMethod), Url = requestUrl, Header = header, Content = content }; Console.WriteLine("-REQUEST-----------------------------"); Console.WriteLine(request); Console.WriteLine("------------------------------"); return request; } } }
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 ZM.TiledScreenDesigner.WinApp { public partial class frmGetHorizontalAlign : Form { public frmGetHorizontalAlign() { InitializeComponent(); lstOptions.Items.Add(System.Windows.Forms.VisualStyles.HorizontalAlign.Left); lstOptions.Items.Add(System.Windows.Forms.VisualStyles.HorizontalAlign.Center); lstOptions.Items.Add(System.Windows.Forms.VisualStyles.HorizontalAlign.Right); } private void btnOk_Click(object sender, EventArgs e) { DialogResult = DialogResult.OK; this.Hide(); } private void btnCancel_Click(object sender, EventArgs e) { DialogResult = DialogResult.Cancel; this.Hide(); } public static System.Windows.Forms.VisualStyles.HorizontalAlign? GetHorizontalAlign(System.Windows.Forms.VisualStyles.HorizontalAlign source) { System.Windows.Forms.VisualStyles.HorizontalAlign? result = null; var f = new frmGetHorizontalAlign(); f.lstOptions.SelectedItem = source; f.ShowDialog(); if (f.DialogResult == DialogResult.OK) result = (System.Windows.Forms.VisualStyles.HorizontalAlign)f.lstOptions.SelectedItem; f.Close(); return result; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PathLine : MonoBehaviour { public int EnemiesCount => enemiesInRange.Count; public List<Enemy> enemiesInRange = new List<Enemy>(); [SerializeField] LineRenderer lr; [SerializeField] BoxCollider bx; public void SetWidth(float w) { bx.size = new Vector3(bx.size.x, w, bx.size.z); lr.startWidth = lr.endWidth = w; } private void OnTriggerEnter(Collider other) { Enemy enemy = other.GetComponent<Enemy>(); if (enemy != null && !enemiesInRange.Contains(enemy)) { enemiesInRange.Add(enemy); } } private void OnTriggerExit(Collider other) { Enemy enemy = other.GetComponent<Enemy>(); if(enemy != null && enemiesInRange.Contains(enemy)) { enemiesInRange.Remove(enemy); } } }