text
stringlengths
13
6.01M
using gView.Framework.Data; using gView.Framework.Data.Cursors; using gView.Framework.Data.Filters; using gView.Framework.Geometry; using gView.Framework.system; using System; using System.Threading.Tasks; namespace gView.DataSources.GeoJson { class GeoJsonServiceFeatureClass : IFeatureClass { private readonly GeoJsonServiceDataset _dataset; private GeoJsonServiceFeatureClass(GeoJsonServiceDataset dataset) { _dataset = dataset; } async public static Task<GeoJsonServiceFeatureClass> CreateInstance(GeoJsonServiceDataset dataset, GeometryType geometryType) { var instance = new GeoJsonServiceFeatureClass(dataset); instance.SpatialReference = await dataset.GetSpatialReference(); instance.GeometryType = geometryType; instance.Name = $"{dataset.DatasetName}-{geometryType.ToString().ToLower()}"; #region Loop all features for Fields var fields = new FieldCollection(); if (dataset.Source != null) { bool idIsInterger = false; var features = await dataset.Source.GetFeatures(geometryType); // mayby later... //if (features != null && features.Count() > 0) //{ // idIsInterger = features.Where(f => f != null && int.TryParse(f["id"]?.ToString(), out int intId)) // .Count() == features.Count(); //} foreach (var feature in features) { foreach (var fieldValue in feature.Fields) { if (fields.FindField(fieldValue.Name) == null) { var val = fieldValue.Value; if (fieldValue.Name == "id" && idIsInterger) { fields.Add(new Field(fieldValue.Name, FieldType.ID)); } else if (val?.GetType() == typeof(int)) { fields.Add(new Field(fieldValue.Name, FieldType.integer)); } else if (val?.GetType() == typeof(double)) { fields.Add(new Field(fieldValue.Name, FieldType.Double)); } else { // ToDo: Check for Date? fields.Add(new Field(fieldValue.Name, FieldType.String)); } } } } } instance.Fields = fields; #endregion return instance; } #region IFeatureClass public string ShapeFieldName => "geometry"; public IEnvelope Envelope => _dataset.Source?.Envelope ?? new Envelope(); public IFieldCollection Fields { get; private set; } public string IDFieldName => "id"; public string Name { get; private set; } public string Aliasname => this.Name; public IDataset Dataset => _dataset; public bool HasZ => false; public bool HasM => false; public ISpatialReference SpatialReference { get; internal set; } public GeometryType GeometryType { get; private set; } public Task<int> CountFeatures() { throw new NotImplementedException(); } public IField FindField(string name) { return Fields.FindField(name); } async public Task<IFeatureCursor> GetFeatures(IQueryFilter filter) { if (filter is ISpatialFilter) { if (this.SpatialReference != null && ((ISpatialFilter)filter).FilterSpatialReference != null && !((ISpatialFilter)filter).FilterSpatialReference.Equals(this.SpatialReference)) { filter = (ISpatialFilter)filter.Clone(); ((ISpatialFilter)filter).Geometry = GeometricTransformerFactory.Transform2D(((ISpatialFilter)filter).Geometry, ((ISpatialFilter)filter).FilterSpatialReference, this.SpatialReference); ((ISpatialFilter)filter).FilterSpatialReference = null; } } if (_dataset.Source != null) { if (_dataset.Source.IsValid) { if (filter is DistinctFilter) { return new GeoJsonDistinctFeatureCursor(await _dataset.Source?.GetFeatures(this.GeometryType), (DistinctFilter)filter); } return new GeoJsonFeatureCursor(this, await _dataset.Source?.GetFeatures(this.GeometryType), filter); } else if (_dataset.Source.LastException != null) { throw new Exception(_dataset.Source.LastException.AllMessages()); } } // Dataset is not intializalized return new GeoJsonFeatureCursor(this, new IFeature[0], filter); } async public Task<ICursor> Search(IQueryFilter filter) { return (ICursor)await GetFeatures(filter); } public Task<ISelectionSet> Select(IQueryFilter filter) { return Task.FromResult<ISelectionSet>(null); } #endregion } }
namespace LogoPrinter { using System; class Program { static void Main() { Console.Write("Please enter and odd number between 2 and 10 000: "); var figureSize = int.Parse(Console.ReadLine()); var mid = figureSize * 2; var leftRightDasheshCount = figureSize; var middleRowIndex = figureSize / 2; var starsCount = figureSize; var dashesCount = figureSize; var logoPrinter = new LogoPrinter(figureSize, middleRowIndex, leftRightDasheshCount, starsCount, dashesCount, mid); logoPrinter.PrintUpperPartOfLogo(); logoPrinter.PrintBottomPartOfLogo(logoPrinter.MidDashesCount); } } }
/** * Definition for a binary tree node. * public class TreeNode { * public int val; * public TreeNode left; * public TreeNode right; * public TreeNode(int x) { val = x; } * } */ public class Solution { public Dictionary<int, int> dict; public TreeNode BuildTree(int[] preorder, int[] inorder) { if (preorder == null || preorder.Length == 0) { return null; } dict = new Dictionary<int, int>(); for (int i = 0; i < inorder.Length; i++) { dict[inorder[i]] = i; } return Helper(0, 0, preorder.Length-1, preorder, inorder); } public TreeNode Helper(int rootIndex, int startIndex, int endIndex, int[] preorder, int[] inorder) { if (rootIndex > preorder.Length - 1 || startIndex > endIndex) { return null; } TreeNode root = new TreeNode(preorder[rootIndex]); int inIndex = dict[preorder[rootIndex]]; root.left = Helper(rootIndex+1, startIndex, inIndex-1, preorder, inorder); root.right = Helper(rootIndex+inIndex-startIndex+1, inIndex+1, endIndex, preorder, inorder); return root; } }
namespace ParrisConnection.DataLayer.Dtos { public interface IPhoneType { int Id { get; set; } string Type { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.Caching.Memory; using System.Diagnostics; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Http; using AweShur.Core.Security; namespace AweShur.Web.Demo.Controllers { [ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)] public class HomeController : Controller { private IMemoryCache cache; public HomeController(IMemoryCache cache) { this.cache = cache; } public IActionResult Index() { return View(); } public IActionResult Error() { return View(); } public IActionResult Exit() { Request.HttpContext.Session.Clear(); return Redirect("/"); } } }
using System; using System.Collections.Generic; namespace Zadanie_3 { class Program { class Zajęcia { public string nazwa; public double start; public double koniec; public Zajęcia(string nazwa, double start, double koniec) { this.nazwa = nazwa; this.start = start; this.koniec = koniec; } public string zwroc() { return start + " - " + koniec + " " + nazwa; } public static Zajęcia[] Sortuj(Zajęcia[] zajęcia) { for (int i = 0; i < zajęcia.Length - 1; i++) { for (int k = i + 1; k < zajęcia.Length; k++) { if (zajęcia[i].start > zajęcia[k].start || (zajęcia[i].start == zajęcia[k].start && zajęcia[i].koniec > zajęcia[k].koniec)) { Zajęcia p = zajęcia[i]; zajęcia[i] = zajęcia[k]; zajęcia[k] = p; } } } return zajęcia; } } static List<Zajęcia> Wybór_podzbiór_zajęć(Zajęcia[] zajęcia) { List<Zajęcia> zgodne = new List<Zajęcia>(); zajęcia = Zajęcia.Sortuj(zajęcia); zgodne.Add(zajęcia[0]); for (int i = 1; i < zajęcia.Length; i++) { if (zajęcia[i].start >= zgodne[zgodne.Count - 1].koniec) zgodne.Add(zajęcia[i]); } return zgodne; } static void Main(string[] args) { Zajęcia z1 = new Zajęcia("Basen",7.40,9.10); Zajęcia z2 = new Zajęcia("Angielski", 8.30, 9); Zajęcia z3 = new Zajęcia("Siłownia", 19.15, 20); Zajęcia z4 = new Zajęcia("Szachy", 18.20, 19.20); Zajęcia z5 = new Zajęcia("Poker", 14.30, 16); Zajęcia z6 = new Zajęcia("Japoński", 17, 18.35); Zajęcia z7 = new Zajęcia("Badminton", 7, 9); Zajęcia[] zajęcia = { z1, z2, z3, z4, z5, z6, z7 }; List<Zajęcia> zgodne = Wybór_podzbiór_zajęć(zajęcia); foreach (var item in zgodne) { Console.WriteLine(item.zwroc()); } Console.ReadKey(); } } }
namespace CheckIt.Syntax { using System.Collections.Generic; public interface IProjects : IEnumerable<IProject>, IPatternContains<IProjectMatcher, ICheckProjectContains> { } }
using UnityEngine; using System.Collections; public class perro : MonoBehaviour { public string img; public static bool ready = false; void Start() { this.GetComponent<SpriteRenderer>().enabled = true; StartCoroutine(Mostrar()); } void FixedUpdate() { if(ready==false) { StartCoroutine(Mostrar()); } } IEnumerator Mostrar() { yield return new WaitForSeconds(3); this.GetComponent<SpriteRenderer>().enabled = false; this.GetComponent<Canvas>().enabled = false; ready = true; } }
using System; using MonoMac.AppKit; using System.Drawing; namespace OxyPlot.XamMac { /// <summary> /// Export extensions for Images and PDF Documents /// </summary> public static class ExportExtensions { /// <summary> /// Generates the image. /// </summary> /// <returns>The image.</returns> /// <param name="view">View.</param> public static NSImage GenerateImage(this NSView view) { RectangleF bounds = view.Bounds; NSBitmapImageRep bir = view.BitmapImageRepForCachingDisplayInRect (bounds); bir.Size = bounds.Size; view.CacheDisplay (bounds, bir); NSImage targetImage = new NSImage(bounds.Size); targetImage.LockFocus(); bir.DrawInRect(bounds); targetImage.UnlockFocus(); return targetImage; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using SharpSenses; namespace Aprendizado1 { public partial class Form1 : Form { static System.Windows.Forms.Timer Tempo = new System.Windows.Forms.Timer(); [System.Runtime.InteropServices.DllImport("user32.dll")] static extern bool SetCursorPos(int x, int y); [System.Runtime.InteropServices.DllImport("user32.dll")] public static extern void mouse_event(int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo); public const int MOUSEEVENTF_LEFTDOWN = 0x02; public const int MOUSEEVENTF_LEFTUP = 0x04; public string Orientacao; ICamera cam = Camera.Create(); public static void ClickDoMouse(int xpos, int ypos) { SetCursorPos(xpos, ypos); mouse_event(MOUSEEVENTF_LEFTDOWN, xpos, ypos, 0, 0); mouse_event(MOUSEEVENTF_LEFTUP, xpos, ypos, 0, 0); } public static void MoveMouse(int x, int y) { SetCursorPos(x, y); } public Form1() { InitializeComponent(); } private void Form1_KeyPress(object sender, KeyPressEventArgs e) { Tempo.Start(); if (e.KeyChar.ToString() == "k") { Orientacao = "PraBaixo"; } else if (e.KeyChar.ToString() == "i") { Orientacao = "PraCima"; } else if (e.KeyChar.ToString() == "l") { Orientacao = "PraDireita"; } else if (e.KeyChar.ToString() == "j") { Orientacao = "PraEsquerda"; } else if (e.KeyChar.ToString() == "p") { Tempo.Stop(); } else if (e.KeyChar.ToString() == "c") { Tempo.Stop(); ClickDoMouse(Cursor.Position.X, Cursor.Position.Y); } } private void button5_MouseClick(object sender, MouseEventArgs e) { MessageBox.Show("Clic"); } private void Form1_Load(object sender, EventArgs e) { Orientacao = "Pausa"; Tempo.Tick += new EventHandler(Evento); Tempo.Interval = 50; Tempo.Start(); //SupportedLanguage.PtBR; cam.Start(); cam.Face.WinkedRight += (self, eventArgs) => { if (Orientacao == "Pausa") { ClickDoMouse(Cursor.Position.X, Cursor.Position.Y); } else { Orientacao = "Pausa"; } }; cam.Face.LeftEye.DoubleBlink += (self, eventArgs) => { if (Orientacao == "Pausa") { Orientacao = "PraDireita"; Tempo.Interval = 50; } else if (Orientacao == "PraDireita") { Orientacao = "PraEsquerda"; } else if (Orientacao == "PraEsquerda") { Orientacao = "PraCima"; } else if (Orientacao == "PraCima") { Orientacao = "PraBaixo"; } else if (Orientacao == "PraBaixo") { Orientacao = "PraDireita"; } else Orientacao = "PraDireita"; }; } private void Evento(Object myObject, EventArgs myEventArgs) { if (Orientacao == "PraBaixo") { MoveMouse(Cursor.Position.X, Cursor.Position.Y + 3); } else if (Orientacao == "PraCima") { MoveMouse(Cursor.Position.X, Cursor.Position.Y - 3); } else if(Orientacao == "PraDireita") { MoveMouse(Cursor.Position.X + 3, Cursor.Position.Y); } else if(Orientacao == "PraEsquerda") { MoveMouse(Cursor.Position.X - 3, Cursor.Position.Y); } } private void Form1_KeyUp(object sender, KeyEventArgs e) { } private void button1_Click(object sender, EventArgs e) { MessageBox.Show("Clicou"); } private void button11_Click(object sender, EventArgs e) { cam.Speech.Say("BOM DIA", SupportedLanguage.PtBR); } private void button8_Click(object sender, EventArgs e) { cam.Speech.Say("BOA TARDE", SupportedLanguage.PtBR); } private void button4_Click(object sender, EventArgs e) { cam.Speech.Say("BOM NOITE", SupportedLanguage.PtBR); } private void button16_Click(object sender, EventArgs e) { cam.Speech.Say("COMO VAI", SupportedLanguage.PtBR); } private void button17_Click(object sender, EventArgs e) { cam.Speech.Say("CERTO", SupportedLanguage.PtBR); } private void button12_Click(object sender, EventArgs e) { cam.Speech.Say("OLA TDC", SupportedLanguage.PtBR); } private void button9_Click(object sender, EventArgs e) { cam.Speech.Say("SIM", SupportedLanguage.PtBR); } private void button5_Click(object sender, EventArgs e) { cam.Speech.Say("NAO", SupportedLanguage.PtBR); } private void button15_Click(object sender, EventArgs e) { cam.Speech.Say("ERRADO", SupportedLanguage.PtBR); } private void button18_Click(object sender, EventArgs e) { cam.Speech.Say("CARAMBA", SupportedLanguage.PtBR); } private void button13_Click(object sender, EventArgs e) { cam.Speech.Say("TURMA BOA", SupportedLanguage.PtBR); } private void button10_Click(object sender, EventArgs e) { cam.Speech.Say("VAI", SupportedLanguage.PtBR); } private void button19_Click(object sender, EventArgs e) { cam.Speech.Say("TCHAU", SupportedLanguage.PtBR); } private void button2_Click(object sender, EventArgs e) { cam.Speech.Say("A", SupportedLanguage.PtBR); } private void button14_Click(object sender, EventArgs e) { cam.Speech.Say("B", SupportedLanguage.PtBR); } private void button7_Click(object sender, EventArgs e) { cam.Speech.Say("C", SupportedLanguage.PtBR); } private void button3_Click(object sender, EventArgs e) { cam.Speech.Say("D", SupportedLanguage.PtBR); } private void button20_Click(object sender, EventArgs e) { cam.Speech.Say("E", SupportedLanguage.PtBR); } private void button6_Click(object sender, EventArgs e) { cam.Speech.Say("VEM", SupportedLanguage.PtBR); } } }
using MediatR; using SFA.DAS.CommitmentsV2.Shared.Interfaces; using SFA.DAS.ProviderCommitments.Infrastructure.OuterApi.Requests; using SFA.DAS.ProviderCommitments.Interfaces; using SFA.DAS.ProviderCommitments.Web.Models.Cohort; using System.Threading; using System.Threading.Tasks; namespace SFA.DAS.ProviderCommitments.Queries.BulkUploadValidate { public class FileUploadValidateDataHandler : IRequestHandler<FileUploadValidateDataRequest> { private IOuterApiService _client; private IModelMapper _modelMapper; private IBulkUploadFileParser _bulkUploadFileParser; public FileUploadValidateDataHandler(IOuterApiService client, IModelMapper modelMapper, IBulkUploadFileParser bulkUploadFileParser) { _client = client; _modelMapper = modelMapper; _bulkUploadFileParser = bulkUploadFileParser; } public async Task<Unit> Handle(FileUploadValidateDataRequest request, CancellationToken cancellationToken) { request.CsvRecords = _bulkUploadFileParser.GetCsvRecords(request.ProviderId, request.Attachment); var apiRequest = await _modelMapper.Map<BulkUploadValidateApimRequest>(request); await _client.ValidateBulkUploadRequest(apiRequest); return Unit.Value; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; namespace UnityStandardAssets.CrossPlatformInput { public class DeleteName : MonoBehaviour,IPointerEnterHandler { // Use this for initialization void Start() { } // Update is called once per frame void Update() { } public void OnPointerEnter(PointerEventData eventData) { PlayerPrefs.DeleteKey("playername"); } } }
using UnityEngine; namespace UnityAtoms.MonoHooks { /// <summary> /// Mono Hook for [`Update`](https://docs.unity3d.com/ScriptReference/MonoBehaviour.Update.html) /// </summary> [EditorIcon("atom-icon-delicate")] [AddComponentMenu("Unity Atoms/Hooks/On Update Hook")] public sealed class OnUpdateHook : VoidHook { private void Update() { OnHook(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using FprnM1C; using System.Threading; using KartObjects; using KartObjects.Entities.Documents; namespace AxisEq { public class AtolFR:AbstractPrinter { private FprnM45 ptr; public override int Open(string portName, string Baud, string OpName, string Psw, params object[] arg) { base.Open(portName, Baud, OpName, Psw, arg); lock (this) { try { RibbonWidth = 32; ptr = new FprnM45(); ptr.PortNumber = Convert.ToInt32(portName.ToUpper().Replace("COM", "")); switch (Baud) { case "2400": ptr.BaudRate = 4; break; case "4800": ptr.BaudRate = 5; break; case "9600": ptr.BaudRate = 7; break; case "19200": ptr.BaudRate = 10; break; case "38400": ptr.BaudRate = 12; break; case "57600": ptr.BaudRate = 14; break; case "115200": ptr.BaudRate = 18; break; default: break; } ptr.DeviceEnabled = true; if (ptr.ResultCode != 0) throw new Exception(ptr.ResultDescription); ptr.Password = "30"; } catch (Exception) { return -1; } return GetError(ptr.ResultCode); } } public override int Close() { ptr = null; return 0; } public override int ZReport(ZReport z) { lock (this) { try { //Заполняем счетчики foreach (ZReportPayment p in z.ZReportPayments) { ptr.RegisterNumber = 3; ptr.CheckType = 1; //продажа ptr.TypeClose = p.PayType.CounterNum - 1; ptr.GetRegister(); p.FiscalTotalSale = Convert.ToDecimal(ptr.Summ); WriteToLog("Счетчик " + p.PayType.CounterNum + " продажа " + p.FiscalTotalSale); ptr.RegisterNumber = 3; ptr.CheckType = 2; //возврат продажа ptr.TypeClose = p.PayType.CounterNum - 1; ptr.GetRegister(); p.FiscalTotalReturn = Convert.ToDecimal(ptr.Summ); WriteToLog("Счетчик " + p.PayType.CounterNum + " возврат " + p.FiscalTotalReturn); } ptr.Password = "30"; ptr.Mode = 3; int res = ptr.SetMode(); ptr.ReportType = 1; int enq = ptr.ENQTimeout; int ack = ptr.ACKTimeout; ptr.ACKTimeout = ptr.ENQTimeout = 99999; //5 мин таймаут на ответ res = ptr.Report(); ptr.ENQTimeout = enq; ptr.ACKTimeout = ack; //если приходит ответ -1 - нет связи, то выжидаем одну минуту, проверям статус, если смена закрыта то возвращаем 0 if (res == -1) { Thread.Sleep(5000); PrinterState st = GetState(); if (st == PrinterState.STATE_NOTCONNECTED) { res = -1; } else { var s = GetStatus(); if (s == (int)PrinterStatus.STATUS_SHIFTCLOSED) { res = 0; } } } if (ptr.ResultCode != 0) return GetError(ptr.ResultCode); while (GetStatus() == 8) Thread.Sleep(10); } catch (Exception) { } return GetError(ptr.ResultCode); } } public override int GetData(int ParamID, out long pData, out string pString) { throw new NotImplementedException(); } int DocumentType; public override int PrintFreeDoc(Receipt receipt) { lock (this) { int discount = 0; //эмуляция ПФД //открываем обычный документ if (receipt.DirectOperation == 1) DocumentType = 0; else DocumentType = 2; BeginReceipt(); //добавляем одну позицию на сумму ПФД ItemReceipt(0, "", "", (int)(receipt.TotalSum * 100), 1000); try { //закрываем обычный документ //TenderReceipt(_payType, _sum, 0); int[] summs = { 0, 0, 0, 0, 0, 0 }; foreach (Payment payment in receipt.Payment) { if (payment.PayType.IsDiscount) discount = discount + (int)(payment.PaymentSum * 100); else summs[payment.PayType.CounterNum - 1] = (int)(payment.PaymentSum * 100); } MixTenderReceipt(summs[0], summs[1], summs[2], summs[3], summs[4], summs[5], discount); } catch (Exception) { } return GetError(ptr.ResultCode); } } public int MixTenderReceipt(int Summ0, int Summ1, int Summ2, int Summ3, int Summ4, int Summ5, int Discount) { lock (this) { try { // ptr.CurrentDeviceIndex = deviceidx; ptr.Password = "30"; if (Discount != 0) { ptr.Summ = (double)Discount / 100.0; ptr.Destination = 0; ptr.SummDiscount(); } if (Summ0 > 0) { ptr.Summ = (double)Summ0 / 100.0; ptr.TypeClose = 0; ptr.Payment(); } if (Summ1 > 0) { ptr.Summ = (double)Summ1 / 100.0; ptr.TypeClose = 1; ptr.Payment(); } if (Summ2 > 0) { ptr.Summ = (double)Summ2 / 100.0; ptr.TypeClose = 2; ptr.Payment(); } if (Summ3 > 0) { ptr.Summ = (double)Summ3 / 100.0; ptr.TypeClose = 3; ptr.Payment(); } ptr.CloseCheck(); } catch (Exception) { } return GetError(ptr.ResultCode); } } private int ItemReceipt(int SecID, string GoodName, string Measure, int Price, int Count) { lock (this) { int res = 0; try { //ptr.CurrentDeviceIndex = deviceidx; ptr.Name = GoodName; ptr.Quantity = (double)Count / 1000.0; ptr.Price = (double)Price / 100.0; ptr.Department = SecID; //продажа if (DocumentType == 0) { res = ptr.Registration(); } //возврат if (DocumentType == 2) { ptr.Return(); res = ptr.ResultCode; } } catch (Exception) { } return GetError(res); } } private int BeginReceipt() { lock (this) { try { //ptr.CurrentDeviceIndex = deviceidx; //ptr.Password = "1"; ptr.Password = "30"; ptr.Mode = 1; //режим регистрации int res = ptr.SetMode(); if (res != 0) return GetError(ptr.ResultCode); ptr.TestMode = false; ptr.CheckType = 1; switch (DocumentType) { case 0: ptr.CheckType = 1; break; case 2: ptr.CheckType = 2; break; case 1: ptr.CheckType = 3; break; } ptr.OpenCheck(); } catch (Exception) { } return GetError(ptr.ResultCode); } } public override PrinterState GetState() { lock (this) { PrinterState result; try { //ptr.CurrentDeviceIndex = deviceidx; int res = ptr.GetStatus(); ptr.GetCurrentMode(); result = PrinterState.STATE_NORMAL; if (ptr.OutOfPaper) result = PrinterState.STATE_PAPEREND; if (ptr.CoverOpened == true) result = PrinterState.STATE_COVEROPEN; if (ptr.PrinterConnectionFailed == true) result = PrinterState.STATE_DAMAGED; if (res == -1) result = PrinterState.STATE_NOTCONNECTED; } catch (Exception ) { return PrinterState.STATE_NOTCONNECTED; } return result; } } public override int OpenCashDrawer() { lock (this) { try { //ptr.CurrentDeviceIndex = deviceidx; //ptr.Password = "1"; ptr.Password = "30"; //MP: ptr.DrawerOnTimeout = 400; ptr.DrawerOffTimeout = 400; ptr.DrawerOnQuantity = 2; for (int i = 0; i < 5; i++) { //Log.WriteToLog("OD+ " + Thread.CurrentThread.ManagedThreadId); //if (FptrFOCfg.AdvancedDrawerOpen) // ptr.AdvancedOpenDrawer(); //else ptr.OpenDrawer(); Thread.Sleep(200); if (isDrawerOpen() == 1) break; } } catch (Exception) { } return GetError(ptr.ResultCode); } } public override int XReport() { lock (this) { try { ptr.Password = "30"; ptr.Mode = 2; ptr.SetMode(); ptr.ReportType = 2; ptr.Report(); } catch (Exception) { } return GetError(ptr.ResultCode); } } public override int CashOut(long Sum) { lock (this) { try { ptr.Mode = 1; ptr.SetMode(); ptr.Summ = (double)Sum / 100.0; ptr.CashOutcome(); } catch (Exception) { } return GetError(ptr.ResultCode); } } public override int CashIn(long Sum) { lock (this) { try { ptr.Password = "30"; ptr.Mode = 1; ptr.SetMode(); ptr.Summ = (double)Sum / 100.0; ptr.CashIncome(); } catch (Exception) { } return GetError(ptr.ResultCode); } } public override int SetDateTime() { throw new NotImplementedException(); } public override int GetStatus() { lock (this) { try { ptr.Password = "30"; int res = ptr.NewDocument(); int result = (int)PrinterStatus.STATUS_IDLE; /* long a = int.MaxValue; string s = ""; GetData((int)FptrParam.FPTR_FM_RECORDS, out a, out s); FMEnding = a <= 90; //выполнение низкоуровневой команды "Выполнение команды ЭКЛЗ" для получения статуса "ЭКЛЗ близка к завершению" int m = ptr.Mode; ptr.Mode = 6; res = ptr.SetMode(); try { ptr.StreamFormat = 5; ptr.OutboundStream = "AF 07 01"; int r = ptr.RunCommand(); string[] bytes = ptr.InboundStream.Split(' '); int b = Convert.ToInt32(bytes[2], 16); EKLZEnding = false; if (b >= 128) { EKLZEnding = true; } } catch { } finally { ptr.Mode = m; ptr.SetMode(); } */ res = ptr.GetStatus(); if (ptr.SessionOpened == false) { return (int)PrinterStatus.STATUS_SHIFTCLOSED; } if (ptr.CheckState != 0) { return (int)PrinterStatus.STATUS_RECOPEN; } if (ptr.PrinterConnectionFailed == true) { return (int)PrinterStatus.STATUS_HARDWAREERROR; } if (res == -1) { return (int)PrinterStatus.STATUS_OFF; } return result; } catch (Exception) { return -10; } } } public override int isDrawerOpen() { lock (this) { try { ptr.Password = "30"; ptr.Mode = 1; ptr.SetMode(); ptr.GetStatus(); if (ptr.DrawerOpened == true) return 1; else return 0; //FptrFOCfg.InvertPosDrawer ? 0 : 1; else return FptrFOCfg.InvertPosDrawer ? 1 : 0; } catch (Exception) { return -1; } } } public override int ShiftReport(int ShiftNum) { lock (this) { try { //ptr.CurrentDeviceIndex = deviceidx; ptr.Mode = 6; ptr.Password = "30"; ptr.SetMode(); ptr.Session = ShiftNum; ptr.ReportType = 24; ptr.Report(); } catch (Exception) { } return GetError(ptr.ResultCode); } } public override int GetError(int err) { int result = (int)PrinterError.ERR_ERROR; this.RealError = err; if ((err >= -3928) && (err <= -3910)) result = (int)PrinterError.ERR_EKLZ; if (err == -3825) result = (int)PrinterError.ERR_PSW; if (err == 0) result = (int)PrinterError.ERR_SUCCESS; if (err == -16) result = (int)PrinterError.ERR_SHIFTCLOSE; if (err == -3837) result = (int)PrinterError.ERR_SHIFTCLOSE; if (err == -3822) result = (int)PrinterError.ERR_SHIFTCLOSE; if (err == 300) result = (int)PrinterError.ERR_TIMECORRECTION; if (err == 200) result = (int)PrinterError.ERR_NOTFOUND; if (err == -3811) result = (int)PrinterError.ERR_NOTREADY; if (err == -3810) result = (int)PrinterError.ERR_NOTENOUGHCASH; return result; } public override int GetLastKPK(out int kpk) { lock (this) { kpk = -1; try { //ptr.CurrentDeviceIndex = deviceidx; ptr.EKLZGetStatus(); kpk = ptr.EKLZKPKNumber; } catch (Exception) { } return GetError(ptr.ResultCode); } } public override int LastReceiptNumber { get { ptr.RegisterNumber = 19; ptr.GetRegister(); return ptr.CheckNumber - 1; } } public override int LastShiftNumber { get { ptr.RegisterNumber = 21; ptr.GetRegister(); return ptr.Session+1; } } public override decimal CashSum { get { ptr.RegisterNumber = 10; ptr.GetRegister(); return Convert.ToDecimal(ptr.Summ * 100); } } public override int PrintString(string Text) { lock (this) { try { //ptr.CurrentDeviceIndex = deviceidx; WriteToLog(Text); ptr.TextWrap = 1; ptr.Caption = Text.Replace("\r", ""); ptr.PrintString(); } catch (Exception) { } return GetError(ptr.ResultCode); } } public override int CancelReceipt() { return 0;//base.CancelReceipt(); } } }
namespace Serilog.Tests.Support; class LogEventPropertyValueComparer : IEqualityComparer<LogEventPropertyValue> { readonly IEqualityComparer<object> _objectEqualityComparer; public LogEventPropertyValueComparer(IEqualityComparer<object>? objectEqualityComparer = null) { _objectEqualityComparer = objectEqualityComparer ?? EqualityComparer<object>.Default; } public bool Equals(LogEventPropertyValue? x, LogEventPropertyValue? y) { if (x is ScalarValue scalarX && y is ScalarValue scalarY) { if (scalarX.Value is null && scalarY.Value is null) { return true; } if (scalarX.Value is null || scalarY.Value is null) { return false; } return _objectEqualityComparer.Equals(scalarX.Value, scalarY.Value); } if (x is SequenceValue sequenceX && y is SequenceValue sequenceY) { return sequenceX.Elements .SequenceEqual(sequenceY.Elements, this); } if (x is StructureValue || y is StructureValue) { throw new NotImplementedException(); } if (x is DictionaryValue || y is DictionaryValue) { throw new NotImplementedException(); } return false; } public int GetHashCode(LogEventPropertyValue obj) => 0; }
using DiscordSharp; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using TournamentBot.BL.Data; using DiscordSharp.Objects; using TournamentBot.BL.Common; namespace DiscordSharp_Starter { class Program { // First of all, a DiscordClient will be created, public static DiscordClient client = new DiscordClient(); static void Main(string[] args) { // the email and password will be defined. client.ClientPrivateInformation = getClientPrivateInformation(); // Then, we are going to set up our events before connecting to discord, to make sure nothing goes wrong. client.Connected += Client_Connected; client.PrivateMessageReceived += Client_PrivateMessageReceived; client.MessageReceived += Client_MessageReceived; // Now, try to connect to Discord. try { // The SendLoginRequest should be called after the events are defined, to prevent issues. client.SendLoginRequest(); client.Connect(); } catch (Exception e) { Console.WriteLine("Something went wrong!\n" + e.Message + "\nPress any key to close this window."); } // Now to make sure the console doesnt close: Console.ReadKey(); // If the user presses a key, the bot will shut down. } // This event fires everytime someone sends a public message over a channel. private static void Client_MessageReceived(object sender, DiscordSharp.Events.DiscordMessageEventArgs e) { //string[] input = e.message_text.Split(' '); //string command = input[0]; //string argument = input[1]; //string argument2 = input[2]; //string response = TournamentBot.BL.Common.Commands.parseCommand(command, argument, argument2); // Because this is a public message, // the bot should send a message to the channel the message was received. //e.Channel.SendMessage(response); } // Private Message Recieved Event. private static void Client_PrivateMessageReceived(object sender, DiscordPrivateMessageEventArgs e) { // Broken, fix later! //try //{ // string response = Commands.parseCommand(e); // // Because this is a private message, the bot should send a private message back // // A private message does NOT have a channel // e.author.SendMessage(response); //} //catch (Exception ex) //{ // e.author.SendMessage("Error: " + ex.Message); //} } // If the bot is connected, this message will show. // Changes to client, like playing game should be called when the client is connected, // just to make sure nothing goes wrong. private static void Client_Connected(object sender, DiscordConnectEventArgs e) { Console.WriteLine("Connected! User: " + e.user.Username); client.UpdateCurrentGame("No tournament running"); // This will display at "Playing: " } // Putting in a temporary fix for storing passwords. This may become the norm, if it does this will need be cleaned up and a proper menu for multiple configs. // this is actually a cool idea because we could use this to host multiple bots off of one instance across an array of discord servers potentially. // the main reason for this is that I did not want our own email / passwords to be stored in the github repo! private static DiscordUserInformation getClientPrivateInformation() { // yes I know storing raw passwords in plaintext is a terrible idea. That being said // this is a hobby project and discordsharp takes this information as plaintext. // no credit cards are coming through here. DiscordUserInformation privateInformation = new DiscordUserInformation(); try { using (var db = new TournamentBotModel()) { int clientConfigCount = db.DiscordClientConfigs.Count(); if (clientConfigCount == 0) { // no configuration, get first config from user! var config = new DiscordClientConfig(); // should write in validation rules, but this is a quick temporary fix to get the bot up and running for first time running. Console.WriteLine("Please Enter Email"); config.Email = Console.ReadLine(); Console.WriteLine("Please Enter Password"); config.Password = Console.ReadLine(); db.DiscordClientConfigs.Add(config); db.SaveChanges(); privateInformation.Email = config.Email; privateInformation.Password = config.Password; return privateInformation; } else { // get the first configuration we have stored in db. var config = db.DiscordClientConfigs.FirstOrDefault(); privateInformation.Email = config.Email; privateInformation.Password = config.Password; } } } catch (Exception ex) { throw ex; } return privateInformation; } } }
namespace SciVacancies.SearchSubscriptionsService { public class ElasticSettings { public string ConnectionUrl { get; set; } public string DefaultIndex { get; set; } } }
using System.Data; using Microsoft.Data.SqlClient; using Microsoft.Extensions.Configuration; using RESTfulAPI.Repository.Interfaces; namespace RESTfulAPI.Repository.Repositories { public class DbMsSql : IDbInterface { public DbMsSql(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } public IDbConnection GetDb() { return new SqlConnection(Configuration.GetConnectionString("MsSql")); } } }
using System; using System.Collections.Generic; using System.Linq; /* * tags: dfs * Time(n), Space(1) * first round, postoder from bottom up to get child count of each node, and distantce of root * second round, preorder from top down to update distantce of each node */ namespace leetcode { public class Lc834_Sum_of_Distances_in_Tree { public int[] SumOfDistancesInTree(int N, int[][] edges) { var graph = new List<int>[N]; for (int i = 0; i < N; i++) graph[i] = new List<int>(); foreach (var e in edges) { graph[e[0]].Add(e[1]); graph[e[1]].Add(e[0]); } var counts = new int[N]; var dist = new int[N]; Array.Fill(counts, 1); Dfs(graph, -1, 0, counts, dist, true); Dfs(graph, -1, 0, counts, dist, false); return dist; } void Dfs(List<int>[] graph, int parent, int node, int[] counts, int[] dist, bool firstRound) { foreach (var e in graph[node]) { if (e == parent) continue; if (!firstRound) dist[e] = dist[node] + graph.Length - counts[e] * 2; Dfs(graph, node, e, counts, dist, firstRound); if (firstRound) { counts[node] += counts[e]; dist[node] += counts[e] + dist[e]; } } } public void Test() { var edges = new int[][] { new int[] { 0, 1 }, new int[] { 0, 2 }, new int[] { 2, 3 }, new int[] { 2, 4 }, new int[] { 2, 5 } }; var exp = new int[] { 8, 12, 6, 10, 10, 10 }; Console.WriteLine(exp.SequenceEqual(SumOfDistancesInTree(6, edges))); } } }
using System.Collections.Generic; using buildingEnergyLoss.Model; namespace buildingEnergyLoss.Repository { public interface ITypeOfBuildingRepository { List<TypeOfBuilding> GetTypeOfBuildings(); } }
using Backend.Model; using System.Collections.Generic; namespace IntegrationAdaptersActionBenefitService.Service { public interface IActionBenefitService { List<ActionBenefit> GetAllActionsBenefits(); ActionBenefit GetActionBenefitById(int id); void CreateActionBenefit(ActionBenefit ab); void CreateActionBenefit(string exchangeName, ActionBenefitMessage message); void UpdateActionBenefit(ActionBenefit ab); void MakePublic(int id, bool isPublic); } }
using System.Windows.Forms; namespace Zombie_Apocalypse_Tomaszek_Piotr { public class ButtonWith2Tags : Button { private int _tag1; private int _tag2; private string _toolTipString; public string ToolTipString { get { return _toolTipString; } set { _toolTipString = value; } } public int Tag1 { get { return _tag1; } set { _tag1 = value; } } public int Tag2 { get { return _tag2; } set { _tag2 = value; } } } }
using System.Collections.Generic; using System.Data; using System.Linq; using Dapper; using RESTfulAPI.Model.Models; using RESTfulAPI.Repository.Interfaces; namespace RESTfulAPI.Repository.Repositories { public class UserMySqlRepository : IUserInterface { public UserMySqlRepository(IDbInterface db) { Connection = db.GetDb(); } public IDbConnection Connection { get; } public int Add<T>(T user) { const string strSql = "INSERT INTO `Users` (UserName, Birthday, Email, Phone) VALUES (@UserName, @Birthday, @Email, @Phone)"; return Connection.ExecuteScalar<int>(strSql, user); } public void Delete<T>(T id) { const string strSql = "DELETE FROM `Users` WHERE (Id = @Id)"; Connection.ExecuteScalar<User>(strSql, new { Id = id }); } public void Update<T>(T user) { const string strSql = "UPDATE `Users` SET UserName = @UserName, Birthday = @Birthday, Email = @Email, Phone = @Phone WHERE (Id = @Id)"; Connection.ExecuteScalar<User>(strSql, user); } public T View<T>(int id) { const string strSql = "SELECT * FROM `Users` WHERE (Users.Id = @Id)"; return Connection.QueryFirstOrDefault<T>(strSql, new { Id = id }); } public List<T> View<T>() { const string strSql = "SELECT * FROM `Users`"; return Connection.Query<T>(strSql).ToList(); } } }
using System; using System.Linq; using System.Net; using System.Threading.Tasks; using Newtonsoft.Json; using Pobs.Domain; using Pobs.Domain.Entities; using Pobs.Tests.Integration.Helpers; using Pobs.Web.Models.Tags; using Xunit; namespace Pobs.Tests.Integration.Tags { public class GetListTests : IDisposable { private string _generateUrl(bool? isApproved = null) => "/api/tags" + (isApproved.HasValue ? "?isApproved=" + isApproved : ""); private readonly int _userId; private readonly Tag[] _approvedTags; private readonly Tag[] _unapprovedTags; public GetListTests() { var user = DataHelpers.CreateUser(); _userId = user.Id; _approvedTags = new[] { DataHelpers.CreateTag(user, isApproved: true), DataHelpers.CreateTag(user, isApproved: true) }; _unapprovedTags = new[] { DataHelpers.CreateTag(user, isApproved: false), DataHelpers.CreateTag(user, isApproved: false) }; } [Fact] public async Task ShouldGetTags() { using (var server = new IntegrationTestingServer()) using (var client = server.CreateClient()) { var response = await client.GetAsync(_generateUrl()); response.EnsureSuccessStatusCode(); var responseContent = await response.Content.ReadAsStringAsync(); var responseModel = JsonConvert.DeserializeObject<TagsListModel>(responseContent); // Check that all of our Tags are in the response. (There may be more too.) foreach (var tag in _approvedTags) { var responseTag = responseModel.Tags.Single(x => x.Slug == tag.Slug); Assert.Equal(tag.Name, responseTag.Name); Assert.Equal(tag.Slug, responseTag.Slug); } foreach (var tag in _unapprovedTags) { Assert.DoesNotContain(tag.Name, responseModel.Tags.Select(x => x.Name)); } } } [Fact] public async Task WatchingTag_WatchingShouldBeTrue() { var watchingTag = _approvedTags[0]; var notWatchingTag = _approvedTags[1]; DataHelpers.CreateWatch(_userId, watchingTag); using (var server = new IntegrationTestingServer()) using (var client = server.CreateClient()) { client.AuthenticateAs(_userId); var response = await client.GetAsync(_generateUrl()); response.EnsureSuccessStatusCode(); var responseContent = await response.Content.ReadAsStringAsync(); var responseModel = JsonConvert.DeserializeObject<TagsListModel>(responseContent); var responseWatchingTag = responseModel.Tags.Single(x => x.Slug == watchingTag.Slug); Assert.True(responseWatchingTag.Watching); var responseNotWatchingTag = responseModel.Tags.Single(x => x.Slug == notWatchingTag.Slug); Assert.False(responseNotWatchingTag.Watching); } } [Fact] public async Task AuthenticatedAsAdmin_ApprovedFalse_ShouldGetUnapprovedTags() { using (var server = new IntegrationTestingServer()) using (var client = server.CreateClient()) { client.AuthenticateAs(_userId, Role.Admin); var response = await client.GetAsync(_generateUrl(false)); response.EnsureSuccessStatusCode(); var responseContent = await response.Content.ReadAsStringAsync(); var responseModel = JsonConvert.DeserializeObject<TagsListModel>(responseContent); // Check that all of our unapproved Tags are in the response. (There may be more too.) foreach (var tag in _unapprovedTags) { var responseTag = responseModel.Tags.Single(x => x.Slug == tag.Slug); Assert.Equal(tag.Name, responseTag.Name); Assert.Equal(tag.Slug, responseTag.Slug); } foreach (var tag in _approvedTags) { Assert.DoesNotContain(tag.Name, responseModel.Tags.Select(x => x.Name)); } } } [Fact] public async Task AuthenticatedAsNonAdmin_ApprovedFalse_ShouldGetForbidden() { using (var server = new IntegrationTestingServer()) using (var client = server.CreateClient()) { client.AuthenticateAs(_userId); var response = await client.GetAsync(_generateUrl(false)); Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); } } public void Dispose() { // This cascades to the Tags too DataHelpers.DeleteUser(_userId); } } }
using System; using System.Drawing; using System.Windows.Forms; using System.Diagnostics; namespace TorreHanoi { public partial class frm_play : Form { private bool jugar = false;// se crea uan variable que se rellena con el valor si se esta jugando private int finalA, finalB, finalC; //se declaran las variables que "sellan" la torre private int intentos, numAnillos, intentosMin; //se crean las variables que cuentan los intentos, los anillos que deben usarse y el numero minimo de intentos que debe realizar private int[] torreA, torreB, torreC; // se utilizan vectores para las torres que estas cargan los anillos private int anillosA, anillosB, anillosC;//de crean las variables anillos para validar si se cumplen las reglas del juego private bool intA, intB, intC; // boleanos para las columnas private int numeroDiscos;//Numero de discos private int posx; // posicion del eje X private int comp = 0;//variable para control del tiempo private int comp2 = 0;//Variable para la pausa private Color color;//para colores del dibujo private Graphics crear;//crear el dibujo private Stopwatch cronos = new Stopwatch(); //stopwatch para la pausa /// <summary> /// Contructor del formulario /// </summary> /// <param name="n"></param> public frm_play(int numeroDiscos) { InitializeComponent(); //crea el grafico del juego crear = juego.CreateGraphics(); this.numeroDiscos = numeroDiscos; // inicializar Comenzar(numeroDiscos); } /// <summary> /// inicializa todos los componentes /// </summary> /// <param name="n"></param> los discos elegidos private void Comenzar(int n) { juego.Enabled = (true); btn_pause.Enabled = (true); btn_reset.Enabled = (true); this.btn_pause.Text = "Pausa"; comp2 = 0; comp++; this.lblIntentos3.Text = "0"; timer1.Start(); numAnillos = System.Convert.ToInt32(n); torreA = new int[numAnillos]; torreB = new int[numAnillos]; torreC = new int[numAnillos]; anillosA = numAnillos; anillosB = 0; anillosC = 0; finalA = 1; finalB = 0; finalC = 0; for (int a = numAnillos, b = 0; a > 0; a--, b++) { torreA[b] = a; } intentos = 0; this.btn_return.Enabled = true; if (comp != 0) { cronos.Reset(); } lblIntentos2.Text = intentos.ToString(); jugar = true; this.Refresh(); } /// <summary> /// Timer para el tomar el tiempo /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void timer1_Tick(object sender, EventArgs e) { cronos.Start();//inicia el contador if (cronos.IsRunning) { TimeSpan ts = cronos.Elapsed; this.lblIntentos3.Text = String.Format("{0:00}:{1:00}:{2:00}:{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10); } } /// <summary> /// Evento para resetear el juego /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btn_reset_Click(object sender, EventArgs e) { // inicializar Comenzar(numeroDiscos); } /// <summary> /// Evento de movimiento de los discos de una torre a otra /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void juego_MouseMove(object sender, MouseEventArgs e) { if (intA | intB | intC) { this.Refresh(); } //Torre A --> B C if (intA) { crear.FillRectangle(new SolidBrush(Color.IndianRed), 90 - (torreA[anillosA - 1] * 10), 210 - ((anillosA - 1) * 20), 20 * torreA[anillosA - 1], 20); int x = e.X - (10 * torreA[anillosA - 1]); int y = e.Y - 10; crear.FillRectangle(new SolidBrush(Color.DarkRed), x, y, 20 * torreA[anillosA - 1], 20); crear.FillRectangle(new SolidBrush(color), x + 2, y + 2, (20 * torreA[anillosA - 1]) - 4, 16); } //Torre B --> A C if (intB) { crear.FillRectangle(new SolidBrush(Color.IndianRed), 250 - (torreB[anillosB - 1] * 10), 210 - ((anillosB - 1) * 20), 20 * torreB[anillosB - 1], 20); int x = e.X - (10 * torreB[anillosB - 1]); int y = e.Y - 10; crear.FillRectangle(new SolidBrush(Color.DarkRed), x, y, 20 * torreB[anillosB - 1], 20); crear.FillRectangle(new SolidBrush(color), x + 2, y + 2, (20 * torreB[anillosB - 1]) - 4, 16); } //Torre C --> A B if (intC) { crear.FillRectangle(new SolidBrush(Color.IndianRed), 410 - (torreC[anillosC - 1] * 10), 210 - ((anillosC - 1) * 20), 20 * torreC[anillosC - 1], 20); int x = e.X - (10 * torreC[anillosC - 1]); int y = e.Y - 10; crear.FillRectangle(new SolidBrush(Color.DarkRed), x, y, 20 * torreC[anillosC - 1], 20); crear.FillRectangle(new SolidBrush(color), x + 2, y + 2, (20 * torreC[anillosC - 1]) - 4, 16); } } /// <summary> /// Evento validacion de disco /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void juego_MouseDown(object sender, MouseEventArgs e) { if ((e.X >= 0 & e.X <= 170) & (finalA != 0)) { intA = true; intB = false; intC = false; } if ((e.X > 170 & e.X <= 330) & (finalB != 0)) { intB = true; intA = false; intC = false; } if ((e.X > 330 & e.X <= 500) & (finalC != 0)) { intC = true; intA = false; intB = false; } } /// <summary> /// evento cuando suelta el anillo /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void juego_MouseUp(object sender, MouseEventArgs e) { if ((e.X >= 0 & e.X <= 170) & intB & ((finalB < finalA) | finalA == 0)) { finalA = finalB; torreA[anillosA] = finalB; if (anillosB > 1) { finalB = torreB[anillosB - 2]; } else { finalB = torreB[anillosB]; } torreB[anillosB - 1] = 0; anillosA++; anillosB--; intentos++; } if ((e.X >= 0 & e.X <= 170) & intC & ((finalC < finalA) | finalA == 0)) { finalA = finalC; torreA[anillosA] = finalC; if (anillosC > 1) { finalC = torreC[anillosC - 2]; } else { finalC = torreC[anillosC]; } torreC[anillosC - 1] = 0; anillosA++; anillosC--; intentos++; } if ((e.X > 170 & e.X <= 330) & intA & ((finalA < finalB) | finalB == 0)) { finalB = finalA; torreB[anillosB] = finalA; if (anillosA > 1) { finalA = torreA[anillosA - 2]; } else { finalA = torreA[anillosA]; } torreA[anillosA - 1] = 0; anillosB++; anillosA--; intentos++; } if ((e.X > 170 & e.X <= 330) & intC & ((finalC < finalB) | finalB == 0)) { finalB = finalC; torreB[anillosB] = finalC; if (anillosC > 1) { finalC = torreC[anillosC - 2]; } else { finalC = torreC[anillosC]; } torreC[anillosC - 1] = 0; anillosB++; anillosC--; intentos++; } if ((e.X > 330 & e.X <= 500) & intA & ((finalA < finalC) | finalC == 0)) { finalC = finalA; torreC[anillosC] = finalA; if (anillosA > 1) { finalA = torreA[anillosA - 2]; } else { finalA = torreA[anillosA]; } torreA[anillosA - 1] = 0; anillosC++; anillosA--; intentos++; } if ((e.X > 330 & e.X <= 5000) & intB & ((finalB < finalC) | finalC == 0)) { finalC = finalB; torreC[anillosC] = finalB; if (anillosB > 1) { finalB = torreB[anillosB - 2]; } else { finalB = torreB[anillosB]; } torreB[anillosB - 1] = 0; anillosC++; anillosB--; intentos++; } intA = false; intB = false; intC = false; this.Refresh(); lblIntentos2.Text = intentos.ToString(); if ((torreC[numAnillos - 1] == 1) & jugar) { timer1.Stop(); intentosMin = 0; for (int n = 1; n <= numAnillos; n++) { intentosMin = (intentosMin * 2) + 1; } if (intentos > intentosMin) {//muestra un mensaje diciendo que ha ganado pero en un numero mayor de intentos a lo esperado string mejor = "Felicidades Ganador"; MessageBoxButtons buttons = MessageBoxButtons.OK; DialogResult result; string mensaje = "Lo finalizaste, pero haslo en " + intentosMin + " movimientos! Su tiempo " + this.lblIntentos3.Text + ", movimientos " + this.lblIntentos2.Text; // Muestra el mensaje de ganador result = MessageBox.Show(mensaje, mejor, buttons); } else { MessageBox.Show("Lo finalizaste en la cantidad minima de movimientos posibles: " + this.lblIntentos2.Text, "Felicidades Ganador", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); } this.Refresh(); jugar = false; } } /// <summary> /// Si el juego es true dibuja el hanoi /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void juego_Paint(object sender, PaintEventArgs e) { if (jugar)// if para dibujar la torre dibuja(); } /// <summary> /// Evento cierra el formulario y muestra el formulario de niveles /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btn_return_Click(object sender, EventArgs e) { Close(); frm_nivel nivel = new frm_nivel(1); nivel.Show(); } /// <summary> /// Evento muestra las reglas del juego /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btn_rules_Click(object sender, EventArgs e) { frm_rules rules = new frm_rules(); rules.Show(); } /// <summary> /// Metodo dibuja el hanoi /// </summary> public void dibuja() { //se encarga de dibujar las torres y los anillos crear.FillRectangle(new SolidBrush(Color.White), 0, 0, 500, 250); //Piso crear.FillRectangle(new SolidBrush(Color.Gray), 20, 230, 460, 20); //Torre A crear.FillRectangle(new SolidBrush(Color.SaddleBrown), 85, 20, 10, 210); //Torre B crear.FillRectangle(new SolidBrush(Color.SaddleBrown), 245, 20, 10, 210); //TorreC crear.FillRectangle(new SolidBrush(Color.SaddleBrown), 405, 20, 10, 210); //Anillos for (int a = 0; a < numAnillos; a++) {//borde crear.FillRectangle(new SolidBrush(Color.Black), 90 - (torreA[a] * 10), 210 - (a * 20), 20 * torreA[a], 20); crear.FillRectangle(new SolidBrush(Color.Black), 250 - (torreB[a] * 10), 210 - (a * 20), 20 * torreB[a], 20); crear.FillRectangle(new SolidBrush(Color.Black), 410 - (torreC[a] * 10), 210 - (a * 20), 20 * torreC[a], 20); //Anillo 1 if (torreA[a] == 1 | torreB[a] == 1 | torreC[a] == 1) { if (torreA[a] == 1) { posx = 92 - (torreA[a] * 10); } if (torreB[a] == 1) { posx = 252 - (torreB[a] * 10); } if (torreC[a] == 1) { posx = 412 - (torreC[a] * 10); } crear.FillRectangle(new SolidBrush(Color.DarkRed), posx, 212 - (a * 20), 16, 16); } //Anillo 2 if (torreA[a] == 2 | torreB[a] == 2 | torreC[a] == 2) { if (torreA[a] == 2) { posx = 92 - (torreA[a] * 10); } if (torreB[a] == 2) { posx = 252 - (torreB[a] * 10); } if (torreC[a] == 2) { posx = 412 - (torreC[a] * 10); } crear.FillRectangle(new SolidBrush(Color.DarkRed), posx, 212 - (a * 20), 36, 16); } //Anillo 3 if (torreA[a] == 3 | torreB[a] == 3 | torreC[a] == 3) { if (torreA[a] == 3) { posx = 92 - (torreA[a] * 10); } if (torreB[a] == 3) { posx = 252 - (torreB[a] * 10); } if (torreC[a] == 3) { posx = 412 - (torreC[a] * 10); } crear.FillRectangle(new SolidBrush(Color.DarkRed), posx, 212 - (a * 20), 56, 16); } //Anillo 4 if (torreA[a] == 4 | torreB[a] == 4 | torreC[a] == 4) { if (torreA[a] == 4) { posx = 92 - (torreA[a] * 10); } if (torreB[a] == 4) { posx = 252 - (torreB[a] * 10); } if (torreC[a] == 4) { posx = 412 - (torreC[a] * 10); } crear.FillRectangle(new SolidBrush(Color.DarkRed), posx, 212 - (a * 20), 76, 16); } //Anillo 5 if (torreA[a] == 5 | torreB[a] == 5 | torreC[a] == 5) { if (torreA[a] == 5) { posx = 92 - (torreA[a] * 10); } if (torreB[a] == 5) { posx = 252 - (torreB[a] * 10); } if (torreC[a] == 5) { posx = 412 - (torreC[a] * 10); } crear.FillRectangle(new SolidBrush(Color.DarkRed), posx, 212 - (a * 20), 96, 16); } //Anillo 6 if (torreA[a] == 6 | torreB[a] == 6 | torreC[a] == 6) { if (torreA[a] == 6) { posx = 92 - (torreA[a] * 10); } if (torreB[a] == 6) { posx = 252 - (torreB[a] * 10); } if (torreC[a] == 6) { posx = 412 - (torreC[a] * 10); } crear.FillRectangle(new SolidBrush(Color.DarkRed), posx, 212 - (a * 20), 116, 16); } //Anillo 7 if (torreA[a] == 7 | torreB[a] == 7 | torreC[a] == 7) { if (torreA[a] == 7) { posx = 92 - (torreA[a] * 10); } if (torreB[a] == 7) { posx = 252 - (torreB[a] * 10); } if (torreC[a] == 7) { posx = 412 - (torreC[a] * 10); } crear.FillRectangle(new SolidBrush(Color.DarkRed), posx, 212 - (a * 20), 136, 16); } //Anillo 8 if (torreA[a] == 8 | torreB[a] == 8 | torreC[a] == 8) { if (torreA[a] == 8) { posx = 92 - (torreA[a] * 10); } if (torreB[a] == 8) { posx = 252 - (torreB[a] * 10); } if (torreC[a] == 8) { posx = 412 - (torreC[a] * 10); } crear.FillRectangle(new SolidBrush(Color.DarkRed), posx, 212 - (a * 20), 156, 16); } } } /// <summary> /// Evento de pausar el juego /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btn_pause_Click(object sender, EventArgs e) { if (comp2 == 0)//Si comp2 es 0 pausa { //detiene el tiempo cronos.Stop(); timer1.Stop(); juego.Enabled = (false);//no puede mover los discos this.btn_pause.Text = "Continuar";//cambia el texto del boton comp2++; } else if (comp2 == 1)//si camp2 es un 1 quita pausa { juego.Enabled = (true);//puede mover los discos //continua el tiempo cronos.Start(); timer1.Start(); this.btn_pause.Text = "Pausa";//cambia el texto del boton comp2--; } } } }
using System; namespace Phenix.StandardRule.Information { /// <summary> /// 资料审核状态 /// </summary> [Serializable] [Phenix.Core.Operate.KeyCaptionAttribute(FriendlyName = "资料审核状态")] public enum InformationVerifyStatus { /// <summary> /// 初始的 /// </summary> [Phenix.Core.Rule.EnumCaptionAttribute("初始的")] Init, /// <summary> /// 已提交 /// </summary> [Phenix.Core.Rule.EnumCaptionAttribute("已提交")] Submitted, /// <summary> ///不通过 /// </summary> [Phenix.Core.Rule.EnumCaptionAttribute("不通过")] NotPass, /// <summary> /// 通过 /// </summary> [Phenix.Core.Rule.EnumCaptionAttribute("通过")] Pass, } }
namespace OPyke.ZopaTest.LoanProcessor.Interfaces { public interface ILoanValidator { bool IsValidLoanValue(string loanValueParameter); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Alps.Domain.Common; using Alps.Domain.SaleMgr; namespace Alps.Domain.DistributionMgr { public class DistributionVoucherItem : EntityBase { public Commodity Commodity { get; set; } public Guid CommodityID { get; set; } public Quantity Quantity { get; set; } } }
// Object pool: allows creation of an object pool for memory management when creating/disposing large numbers of objects. // Needed in C# as otherwise the garbage collector can slow the game down esp when handling large numbers of objects. // Use this when we expect many of the same object, e.g. used for many powerups in Pong game (although not strictly needed // as still few objects). // When we release an object into the pool, if the pool is not large enough, instead of Freeing the object we add it to the pool and hide it. // When we get an object from the pool, if the pool contains an object we just show the object and take it out of the pool. Otherwise, // we create a new object (hence the ObjectScn member variable) and add it to the parent node (specified as arg1). // Example usage (e.g. from a World class): // // Create the powerUpPool object pool: // private ObjectPool powerUpPool = new ObjectPool(powerUpScn, typeof(PowerUp), 20); // // Get a powerUp object from the pool: // PowerUp powerUp = (PowerUp)powerUpPool.Get(this); // // Release a powerUp object into the pool: // powerUpPool.Release(powerUp); // References: // https://www.infoworld.com/article/3221392/c-sharp/how-to-use-the-object-pool-design-pattern-in-c.html using System; using System.Collections.Concurrent; using Godot; public class ObjectPool { private ConcurrentBag<IPoolable> items = new ConcurrentBag<IPoolable>(); private PackedScene ObjectScn; private int Max; public ObjectPool(PackedScene objectScn, Type type, int max = 10) { if (! (typeof(IPoolable).IsAssignableFrom(type))) { // GD.Print(string.Format("Cannot use {0} in ObjectPool", type)); throw new Exception(); } this.ObjectScn = objectScn; this.Max = max; } public IPoolable Get(Node parent) { // GD.Print("Items in pool: ", items.Count); IPoolable item; if (items.TryTake(out item)) { item.Show(); // GD.Print("Getting from pool"); } else { // GD.Print("Making new object"); item = (IPoolable)ObjectScn.Instance(); parent.AddChild((Node)item); } item.Init(); return item; } public void Release(IPoolable item) { item.Term(); if (items.Count >= Max) { // GD.Print(string.Format("Object pool saturated, deleting {0}", item)); item.QueueFree(); return; } // GD.Print("Releasing to pool"); items.Add(item); item.Hide(); } }
using System; using System.Collections.Generic; using System.Text; using WinAppUpdater.Core.Models.Updates; namespace WinAppUpdater.Core.Services { /// <summary> /// Contract interface for retrieving updates information. /// </summary> public interface IUpdatesService { #region Public methods /// <summary> /// Retrieve all updates of a specific app. /// </summary> /// <param name="appName">Name of the app.</param> /// <returns>Collection of update.</returns> IEnumerable<UpdateVersion> GetUpdates(string appName); #endregion } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using Microsoft.Extensions.Logging; namespace Cogito.HostedWebCore { /// <summary> /// Provides hosting of the IIS pipeline. /// </summary> public class AppHost : IDisposable { readonly static object sync = new object(); readonly XDocument rootWebConfig; readonly XDocument appHostConfig; readonly IList<Action<AppHost>> onStartedHooks; readonly IList<Action<AppHost>> onStoppedHooks; readonly ILogger logger; /// <summary> /// Initializes a new instance. /// </summary> /// <param name="rootWebConfig"></param> /// <param name="appHostConfig"></param> /// <param name="onStartedHooks"></param> /// <param name="onStoppedHooks"></param> /// <param name="logger"></param> internal AppHost( XDocument rootWebConfig, XDocument appHostConfig, IList<Action<AppHost>> onStartedHooks = null, IList<Action<AppHost>> onStoppedHooks = null, ILogger logger = null) { this.rootWebConfig = rootWebConfig; this.appHostConfig = appHostConfig; this.onStartedHooks = onStartedHooks; this.onStoppedHooks = onStoppedHooks; this.logger = logger; } /// <summary> /// Desired path of the temporary Web.config file. /// </summary> public string TemporaryRootWebConfigPath { get; set; } = Path.Combine(Path.GetTempPath(), Process.GetCurrentProcess().Id + ".Web.config"); /// <summary> /// Desired path of the temporary ApplicationHost.config file. /// </summary> public string TemporaryApplicationHostConfigPath { get; set; } = Path.Combine(Path.GetTempPath(), Process.GetCurrentProcess().Id + ".ApplicationHost.config"); /// <summary> /// Starts the web host. /// </summary> public void Start() { lock (sync) { try { try { if (rootWebConfig != null) { if (TemporaryRootWebConfigPath != null) AppServer.RootWebConfigPath = TemporaryRootWebConfigPath; rootWebConfig.Save(AppServer.RootWebConfigPath); } } catch (IOException e) { throw new AppHostException("Unable to save web host configuration.", e); } try { if (appHostConfig != null) { if (TemporaryApplicationHostConfigPath != null) AppServer.ApplicationHostConfigPath = TemporaryApplicationHostConfigPath; appHostConfig.Save(AppServer.ApplicationHostConfigPath); } } catch (IOException e) { throw new AppHostException("Unable to save app host configuration.", e); } if (AppServer.IsActivated) throw new AppHostException("AppHost is already activated within this process."); LogStart(); AppServer.Start(); // invoke the on-started hooks foreach (var h in onStartedHooks ?? Enumerable.Empty<Action<AppHost>>()) h?.Invoke(this); } catch { // any sort of failures and we should attempt to clean up our config files TryRemoveConfigFiles(); throw; } } } /// <summary> /// Prints out a summary of the application. /// </summary> void LogStart() { if (logger != null) foreach (var site in appHostConfig.Root .Elements("system.applicationHost") .Elements("sites") .Elements("site")) LogStartSite(site); } /// <summary> /// Logs information related to a specific site. /// </summary> /// <param name="xml"></param> void LogStartSite(XElement xml) { var site = new { Id = (int)xml.Attribute("id"), Name = (string)xml.Attribute("name"), Applications = xml.Elements("application").Select(application => new { Path = (string)application.Attribute("path"), VirtualDirectories = application.Elements("virtualDirectory").Select(virtualDirectory => new { Path = (string)virtualDirectory.Attribute("path"), PhysicalPath = (string)virtualDirectory.Attribute("physicalPath"), }).ToArray(), }).ToArray(), Bindings = xml.Elements("bindings").Elements("binding").Select(binding => new { Protocol = binding.Attribute("protocol"), BindingInformation = binding.Attribute("bindingInformation") }).ToArray(), }; // build nice user log message var m = new StringBuilder(); m.AppendLine($"Starting site {site.Name} ({site.Id}):"); foreach (var binding in site.Bindings) m.AppendLine($" Binding: {binding.Protocol} {binding.BindingInformation}"); foreach (var application in site.Applications) { m.AppendLine($" Application: {application.Path}"); foreach (var virtualDirectory in application.VirtualDirectories) m.AppendLine($" Virtual Directory: {virtualDirectory.Path} -> {virtualDirectory.PhysicalPath}"); } // output log with object as data logger.LogInformation(m.ToString()); } /// <summary> /// Stops the app host. /// </summary> public void Stop() { lock (sync) { if (AppServer.IsActivated == false) return; logger?.LogInformation("Stopping AppHost..."); try { AppServer.Stop(); // invoke the on-stopped hooks foreach (var h in onStoppedHooks ?? Enumerable.Empty<Action<AppHost>>()) h?.Invoke(this); } finally { TryRemoveConfigFiles(); } } } /// <summary> /// Attempts to remove any temporary configuration files. /// </summary> void TryRemoveConfigFiles() { try { if (AppServer.RootWebConfigPath != null && File.Exists(AppServer.RootWebConfigPath)) File.Delete(AppServer.RootWebConfigPath); } catch (Exception e) { logger?.LogWarning(e, "Unable to delete temporary web config file."); } try { if (AppServer.ApplicationHostConfigPath != null && File.Exists(AppServer.ApplicationHostConfigPath)) File.Delete(AppServer.ApplicationHostConfigPath); } catch (Exception e) { logger?.LogWarning(e, "Unable to delete temporary application host file."); } } /// <summary> /// Runs the web host. /// </summary> /// <param name="logger"></param> /// <param name="cancellationToken"></param> public async Task RunAsync(CancellationToken cancellationToken = default) { try { Start(); while (cancellationToken.IsCancellationRequested == false) { await Task.Delay(TimeSpan.FromSeconds(5)); if (AppServer.IsActivated == false) throw new AppHostException("Application host has unexpectedly stopped."); } } catch (OperationCanceledException) { // ignore } finally { Stop(); } } /// <summary> /// Runs the web host. /// </summary> /// <param name="logger"></param> /// <param name="cancellationToken"></param> public void Run(CancellationToken cancellationToken = default) { Task.Run(() => RunAsync(cancellationToken)).Wait(); } /// <summary> /// Disposes of the instance. /// </summary> public void Dispose() { Stop(); GC.SuppressFinalize(this); } /// <summary> /// Finalizes the instance. /// </summary> ~AppHost() { Dispose(); } } }
using System.Collections; using System.Collections.Generic; using System.IO; using UnityEditor; using UnityEngine; using UnityEngine.UI; /// <summary> /// How To Use: /// SlideController sController = new SlideController(this.slideLocation, screen); /// loop /// sController.Update(); /// s.incrementSlide(); /// end /// </summary> public class SlideController { private string location; // the general location of the slides private int slideCount = -1; //the number of slides in the folder private int slideState = 0; //the current slide private List<string> slides; //the location and names of the slides private bool needToUpdateImage = true; private string materialsLocation; private bool enabled; public GameObject screen; public SlideController(string location, GameObject screen) { this.location = location; this.screen = screen; this.enabled = true; findSlides(); //get all files in the location directory scrubSlides(); //only hold on to png or jpg this.slideCount = this.slides.Count; } // Update is called once per frame public void Update () { //only update if the image has recently been changed if (enabled && needToUpdateImage) { //find where this image is string loc = this.slides[this.slideState]; //create a new shell for Spirte Sprite s = new Sprite(); Texture2D st = LoadTexture(loc); //ensure that the file actually existed if (st == null) return; //create a basic sprite s = Sprite.Create(st, new Rect(0,0, st.width, st.height), new Vector2(0,0), 100f ); Image sc = screen.GetComponentInChildren<Image>(); //resize the image object to the picture size if necessary sc.GetComponent<RectTransform>().sizeDelta = new Vector2(st.width, st.height); sc.sprite = s; needToUpdateImage = false; } } //returns a Texture2D if the file exists, null if it doesn't private Texture2D LoadTexture(string filePath) { Texture2D tex; byte[] fileData; //does the file exist if (File.Exists(filePath)) { //get the raw data fileData = File.ReadAllBytes(filePath); //the initial size doesnt matter because it will get resized tex = new Texture2D(2, 2); //returns true if the file is valid if (tex.LoadImage(fileData)) { return tex; } } //return null if it doesnt exist return null; } private bool findSlides() { this.slides = new List<string>(Directory.GetFiles(this.location)); return slides.Count > 0; } private bool scrubSlides() { for(int i = 0; i < slides.Count; i++) { if( !(Path.GetExtension(slides[i]).Equals(".png") || Path.GetExtension(slides[i]).Equals(".jpg") || Path.GetExtension(slides[i]).Equals(".PNG"))) { Debug.Log("remove" + Path.GetExtension(slides[i])); slides.RemoveAt(i); continue; } Debug.Log("keep" + Path.GetExtension(slides[i])); } return this.slides.Count > 0; } public void incrementSlide() { if (this.enabled) { if (slideState + 1 < slideCount) { needToUpdateImage = true; slideState++; } } } public void decrementSlide() { if (this.enabled) { if (slideState - 1 >= 0) { needToUpdateImage = true; slideState--; } } } public void resetSlide() { if (this.enabled) { needToUpdateImage = true; this.slideState = 0; } } public void setEnabled(bool enabled) { this.enabled = enabled; } public void toggleEnabled() { this.enabled = !this.enabled; } }
namespace PersonInfo.Model { public class PersonInfoModel { public string Name { get; set; } public decimal Number { get; set; } public string NumberString { get; set; } public string Message { get; set; } } }
using System; namespace Ricky.Infrastructure.Core { public static class Calendar { public static DateTime ThisYear(this DateTime dateTime, bool end = false) { if (end) return new DateTime(dateTime.Year, 12, 31, 23, 59, 59); return new DateTime(dateTime.Year, 1, 1, 0, 0, 0); } public static DateTime PreviousYear(this DateTime dateTime, bool end = false) { if (end) return (new DateTime(dateTime.Year, 12, 31, 23, 59, 59)).AddYears(-1); return (new DateTime(dateTime.Year, 1, 1, 0, 0, 0)).AddYears(-1); } public static DateTime PreviousTwoYear(this DateTime dateTime, bool end = false) { if (end) return (new DateTime(dateTime.Year, 12, 31, 23, 59, 59)).AddYears(-2); return (new DateTime(dateTime.Year, 1, 1, 0, 0, 0)).AddYears(-2); } public static DateTime CurrentQuarter(this DateTime dateTime, bool end = false) { var quarter = (dateTime.Month - 1) / 3 + 1; if (end) { var monthInNextQuater = (quarter * 3) + 1; var year = dateTime.Year; if (monthInNextQuater > 12) { monthInNextQuater = 1; year++; } var firstNextQuarter = new DateTime(year, monthInNextQuater, 1, 0, 0, 0); return firstNextQuarter.AddMinutes(-1); } return new DateTime(dateTime.Year, ((quarter - 1) * 3) + 1, 1, 0, 0, 0); } public static DateTime PreviousQuarter(this DateTime dateTime, bool end = false) { var currentQuarter = dateTime.CurrentQuarter(); var previousQuarter = currentQuarter.AddMonths(-3); if (end == false) return previousQuarter; return currentQuarter.AddMinutes(-1); } public static DateTime ThisMonth(this DateTime dateTime, bool end = false) { var thisMonth = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1, 0, 0, 0); ; if (end) return thisMonth.AddMonths(1).AddMinutes(-1); return thisMonth; } public static DateTime PreviousMonth(this DateTime dateTime, bool end = false) { var thisMonth = dateTime.ThisMonth(); var previousMonth = thisMonth.AddMonths(-1); if (end == false) return previousMonth; return previousMonth.AddMonths(1).AddMinutes(-1); } public static DateTime ThisDay(this DateTime dateTime, bool end = false) { if (end == false) return dateTime.Date; else return dateTime.AddDays(1).AddMinutes(-1); } public static DateTime Yesterday(this DateTime dateTime, bool end = false) { var yesterday = dateTime.Date.AddDays(-1); if (end == false) return yesterday; return yesterday.AddDays(1).AddMinutes(-1); } public static DateTime ThisWeek(this DateTime dateTime, bool end = false) { var day = dateTime.Date; var subTract = 0; switch (day.DayOfWeek) { case DayOfWeek.Friday: subTract = -4; break; case DayOfWeek.Monday: subTract = 0; break; case DayOfWeek.Saturday: subTract = -5; break; case DayOfWeek.Sunday: subTract = -6; break; case DayOfWeek.Thursday: subTract = -3; break; case DayOfWeek.Tuesday: subTract = -1; break; case DayOfWeek.Wednesday: subTract = -2; break; default: break; } if (end == false) return day.AddDays(subTract); return day.AddDays(8 + subTract).AddMinutes(-1); } public static DateTime LastWeek(this DateTime dateTime, bool end = false) { var thisWeek = dateTime.ThisWeek(); if (end == false) return thisWeek.AddDays(-7); return thisWeek.AddMinutes(-1); } } }
namespace ResolveUR.Library { using System; using System.Collections.Generic; using System.IO; public class MsBuildResolveUR { public static string FindMsBuildPath(string platform = "") { var path = string.Empty; if (string.IsNullOrWhiteSpace(platform)) { path = GetX64Path(); if (string.IsNullOrWhiteSpace(path)) path = GetX86Path(); } else { // if user specified platform look by it switch (platform) { case Constants.X64: path = GetX64Path(); break; case Constants.X86: path = GetX86Path(); break; } } if (string.IsNullOrWhiteSpace(path)) throw new FileNotFoundException("MsBuild not found on system!"); return path; } static string GetX86Path() { return GetPath( new List<string> { Constants.Msbuildx86VSCmd, Constants.Msbuildx86VS, Constants.Msbuildx86V14, Constants.Msbuildx86V12, Constants.Msbuildx8640, Constants.Msbuildx8635, Constants.Msbuildx8620 }); } static string GetX64Path() { return GetPath( new List<string> { Constants.Msbuildx64VSCmd, Constants.Msbuildx64VS, Constants.Msbuildx64V14, Constants.Msbuildx64V12, Constants.Msbuildx6440, Constants.Msbuildx6435, Constants.Msbuildx6420 }); } static string GetPath(List<string> searchPaths) { foreach (var path in searchPaths) { var msbuildPath = Environment.ExpandEnvironmentVariables(path); if (File.Exists(msbuildPath)) return msbuildPath; } return null; } } }
namespace RosPurcell.Web.ViewModels.Pages.Interfaces { public interface IAnalytics { string GoogleAnalyticsId { get; } bool ShowGoogleAnalyticsScript { get; } } }
using System.Collections.Generic; using UnityEngine; public class Thermal : MonoBehaviour { public Material matobject; int x = 66; public Color orange = new Color(0.2F, 0.3F, 0.4F); // Start is called before the first frame update void Start() { x = Random.Range(30, 200); if (x >= 30 && x <= 60) { matobject.color = Color.yellow; } if (x > 60 && x <= 120) { matobject.color = new Color(1.0f, 0.64f, 0.0f); } if (x > 120 && x <= 200) { matobject.color = Color.red; } } }
using System; using System.Threading; using System.IO; using System.Collections.Generic; namespace De.Thekid.INotify { // List of possible changes public enum Change { CREATE, MODIFY, DELETE, MOVED_FROM, MOVED_TO } /// Main class public class Runner { // Mappings protected static Dictionary<WatcherChangeTypes, Change> Changes = new Dictionary<WatcherChangeTypes, Change>(); private List<Thread> _threads = new List<Thread>(); private bool _eventOccured = false; private Semaphore _semaphore = new Semaphore(0, 1); private Mutex _mutex = new Mutex(); private Arguments _args = null; static Runner() { Changes[WatcherChangeTypes.Created]= Change.CREATE; Changes[WatcherChangeTypes.Changed]= Change.MODIFY; Changes[WatcherChangeTypes.Deleted]= Change.DELETE; } public Runner(Arguments args) { _args = args; } /// Callback for errors in watcher protected void OnWatcherError(object source, ErrorEventArgs e) { Console.Error.WriteLine("*** {0}", e.GetException()); } /// Output method protected void Output(TextWriter writer, string[] tokens, FileSystemWatcher source, Change type, string name) { foreach (var token in tokens) { var path = Path.Combine(source.Path, name); switch (token[0]) { case 'e': writer.Write(type); if (Directory.Exists(path)) { writer.Write(",ISDIR"); } break; case 'f': writer.Write(Path.GetFileName(path)); break; case 'w': writer.Write(Path.Combine(source.Path, Path.GetDirectoryName(path))); break; case 'T': writer.Write(DateTime.Now); break; default: writer.Write(token); break; } } writer.WriteLine(); } public void Processor(object data) { string path = (string)data; using (var w = new FileSystemWatcher { Path = path, IncludeSubdirectories = _args.Recursive, Filter = "*.*" }) { w.Error += new ErrorEventHandler(OnWatcherError); // Parse "events" argument WatcherChangeTypes changes = 0; if (_args.Events.Contains("create")) { changes |= WatcherChangeTypes.Created; } if (_args.Events.Contains("modify")) { changes |= WatcherChangeTypes.Changed; } if (_args.Events.Contains("delete")) { changes |= WatcherChangeTypes.Deleted; } if (_args.Events.Contains("move")) { changes |= WatcherChangeTypes.Renamed; } // Main loop if (!_args.Quiet) { Console.Error.WriteLine( "===> {0} for {1} in {2}{3} for {4}", _args.Monitor ? "Monitoring" : "Watching", changes, path, _args.Recursive ? " -r" : "", String.Join(", ", _args.Events.ToArray()) ); } w.EnableRaisingEvents = true; while (true) { var e = w.WaitForChanged(changes); _mutex.WaitOne(); if (_eventOccured) { _mutex.ReleaseMutex(); break; } if (null != _args.Exclude && _args.Exclude.IsMatch(System.IO.Path.GetFullPath(e.Name))) { _mutex.ReleaseMutex(); continue; } if (WatcherChangeTypes.Renamed.Equals(e.ChangeType)) { Output(Console.Out, _args.Format, w, Change.MOVED_FROM, e.OldName); Output(Console.Out, _args.Format, w, Change.MOVED_TO, e.Name); } else { Output(Console.Out, _args.Format, w, Changes[e.ChangeType], e.Name); } if (!_args.Monitor) { _eventOccured = true; _semaphore.Release(); } _mutex.ReleaseMutex(); } } } /// Entry point public int Run() { foreach (var path in _args.Paths) { Thread t = new Thread(new ParameterizedThreadStart(Processor)); t.Start(path); _threads.Add(t); } _semaphore.WaitOne(); foreach (var thread in _threads) { if (thread.IsAlive) thread.Abort(); thread.Join(); } return 0; } /// Entry point method public static int Main(string[] args) { var p = new ArgumentParser(); // Show usage if no args or standard "help" args are given if (0 == args.Length || args[0].Equals("-?") || args[0].Equals("--help")) { p.PrintUsage("inotifywait", Console.Error); return 1; } // Run! return new Runner(p.Parse(args)).Run(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Terraria; using Terraria.ModLoader; using Microsoft.Xna.Framework; namespace StarlightRiver.NPCs { class MovingPlatform : ModNPC { public override bool Autoload(ref string name) { return GetType().IsSubclassOf(typeof(MovingPlatform)); } public virtual void SafeSetDefaults() { } public sealed override void SetDefaults() { SafeSetDefaults(); npc.lifeMax = 1; npc.immortal = true; npc.noGravity = true; npc.aiStyle = -1; } public override bool CheckActive() { return false; } public virtual void SafeAI() { } public sealed override void AI() { SafeAI(); foreach (Player player in Main.player) { if (new Rectangle((int)player.position.X, (int)player.position.Y + (player.height - 2), player.width, 4).Intersects (new Rectangle((int)npc.position.X, (int)npc.position.Y, npc.width, 4)) && player.position.Y <= npc.position.Y) { player.position += npc.velocity; } } } } }
using Alabo.Web.Mvc.Attributes; using System.ComponentModel.DataAnnotations; namespace Alabo.Framework.Tasks.Schedules.Domain.Enums { /// <summary> /// 分润所依赖的关系图 /// </summary> [ClassProperty(Name = "分润依赖关系图")] public enum RelationshipType { /// <summary> /// 未依赖 /// </summary> [LabelCssClass(BadgeColorCalss.Success)] [Display(Name = "未依赖")] NoRelationship = 1, /// <summary> /// 会员推荐关系(组织架构图) /// </summary> [LabelCssClass(BadgeColorCalss.Success)] [Display(Name = "会员推荐关系(组织架构图)")] UserRecommendedRelationship = 2, /// <summary> /// 用户类型推荐关系(用户类型组织架构图) /// </summary> [LabelCssClass(BadgeColorCalss.Success)] [Display(Name = "用户类型推荐关系(用户类型组织架构图)")] UserTypeRelationship = 3, /// <summary> /// 客户责任关系(CRM客户图) /// </summary> [LabelCssClass(BadgeColorCalss.Success)] [Display(Name = "客户责任关系(CRM客户图)")] CRMRelationship = 4, /// <summary> /// 会员安置关系(安置关系图) /// 会员注册时候,手动安置会员之间的关系,常见的双轨,多轨之间的关系 /// </summary> [LabelCssClass(BadgeColorCalss.Success)] [Display(Name = "会员安置关系(安置关系图)")] PlacementRelationship = 5, /// <summary> /// 商品推荐关系(商品推荐图) /// </summary> [LabelCssClass(BadgeColorCalss.Success)] [Display(Name = "商品推荐关系(商品推荐图)")] GoodsRelationship = 6, /// <summary> /// 订单推荐关系(订单推荐图) /// </summary> [LabelCssClass(BadgeColorCalss.Success)] [Display(Name = "订单推荐关系(订单推荐图)")] OrderRelationship = 7, /// <summary> /// 区域推荐关系(省市区/县关系) /// </summary> [LabelCssClass(BadgeColorCalss.Success)] [Display(Name = "区域推荐关系(省市区/县关系)")] RegionalRelationship = 8, /// <summary> /// 城市商圈关系 /// </summary> [LabelCssClass(BadgeColorCalss.Success)] [Display(Name = "城市商圈关系")] BusinessCircle = 9, /// <summary> /// 公司组织架构(部门、员工关系) /// </summary> [LabelCssClass(BadgeColorCalss.Success)] [Display(Name = " 公司组织架构(部门、员工关系)")] Department = 10, /// <summary> /// 门店图(组织架构图上的服务网点) /// </summary> [LabelCssClass(BadgeColorCalss.Success)] [Display(Name = " 门店图(组织架构图上的服务网点)")] ServiceCenterRelationship = 101, /// <summary> /// 工单责任图(工单责任图) /// 根据工单表里头的对用的用户ID字段 /// </summary> [LabelCssClass(BadgeColorCalss.Success)] [Display(Name = " 工单责任图(工单责任图)")] WorkOrderRelationship = 102 } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.UI; public class BestiaryListButtonMouseEvents : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler, IPointerClickHandler { //For handling bestiary menu mouse cursor events - is attached to all instantiated bestiary entries /// <summary> /// Sets GUI objects in bestiary menu to hovered enemy /// </summary> public void OnPointerEnter(PointerEventData eventData) { if (!GameObject.Find("GameManager/Menus").GetComponent<GameMenu>().BestiaryEntryClicked) { int ID = int.Parse(gameObject.name.Replace("BestiaryEnemyEntryButton - ID ", "")); BaseEnemyDBEntry entry = GetEnemyDBEntry(ID); BaseEnemy enemy = entry.enemy; GameObject.Find("GameManager/Menus/BestiaryMenuCanvas/BestiaryMenuPanel/EnemyNamePanel/EnemyNameText").GetComponent<Text>().text = enemy.name; GameObject.Find("GameManager/Menus/BestiaryMenuCanvas/BestiaryMenuPanel/EnemyLevelPanel/EnemyLevelText").GetComponent<Text>().text = enemy.level.ToString(); GameObject.Find("GameManager/Menus/BestiaryMenuCanvas/BestiaryMenuPanel/EnemyGraphicPanel/EnemyGraphicImage").GetComponent<Image>().color = new Color( GameObject.Find("GameManager/Menus/BestiaryMenuCanvas/BestiaryMenuPanel/EnemyGraphicPanel/EnemyGraphicImage").GetComponent<Image>().color.r, GameObject.Find("GameManager/Menus/BestiaryMenuCanvas/BestiaryMenuPanel/EnemyGraphicPanel/EnemyGraphicImage").GetComponent<Image>().color.g, GameObject.Find("GameManager/Menus/BestiaryMenuCanvas/BestiaryMenuPanel/EnemyGraphicPanel/EnemyGraphicImage").GetComponent<Image>().color.b, 1); GameObject.Find("GameManager/Menus/BestiaryMenuCanvas/BestiaryMenuPanel/EnemyGraphicPanel/EnemyGraphicImage").GetComponent<Image>().sprite = entry.prefab.GetComponent<SpriteRenderer>().sprite; GameObject.Find("GameManager/Menus/BestiaryMenuCanvas/BestiaryMenuPanel/EnemyDescriptionPanel/EnemyDescriptionText").GetComponent<Text>().text = entry.description; } } public void ShowBestiaryEntryDetails() { if (!GameObject.Find("GameManager/Menus").GetComponent<GameMenu>().BestiaryEntryClicked) { int ID = int.Parse(gameObject.name.Replace("BestiaryEnemyEntryButton - ID ", "")); BaseEnemyDBEntry entry = GetEnemyDBEntry(ID); BaseEnemy enemy = entry.enemy; GameObject.Find("GameManager/Menus/BestiaryMenuCanvas/BestiaryMenuPanel/EnemyNamePanel/EnemyNameText").GetComponent<Text>().text = enemy.name; GameObject.Find("GameManager/Menus/BestiaryMenuCanvas/BestiaryMenuPanel/EnemyLevelPanel/EnemyLevelText").GetComponent<Text>().text = enemy.level.ToString(); GameObject.Find("GameManager/Menus/BestiaryMenuCanvas/BestiaryMenuPanel/EnemyGraphicPanel/EnemyGraphicImage").GetComponent<Image>().color = new Color( GameObject.Find("GameManager/Menus/BestiaryMenuCanvas/BestiaryMenuPanel/EnemyGraphicPanel/EnemyGraphicImage").GetComponent<Image>().color.r, GameObject.Find("GameManager/Menus/BestiaryMenuCanvas/BestiaryMenuPanel/EnemyGraphicPanel/EnemyGraphicImage").GetComponent<Image>().color.g, GameObject.Find("GameManager/Menus/BestiaryMenuCanvas/BestiaryMenuPanel/EnemyGraphicPanel/EnemyGraphicImage").GetComponent<Image>().color.b, 1); GameObject.Find("GameManager/Menus/BestiaryMenuCanvas/BestiaryMenuPanel/EnemyGraphicPanel/EnemyGraphicImage").GetComponent<Image>().sprite = entry.prefab.GetComponent<SpriteRenderer>().sprite; GameObject.Find("GameManager/Menus/BestiaryMenuCanvas/BestiaryMenuPanel/EnemyDescriptionPanel/EnemyDescriptionText").GetComponent<Text>().text = entry.description; } } /// <summary> /// Resets all GUI objects to empty fields /// </summary> public void OnPointerExit(PointerEventData eventData) { if (!GameObject.Find("GameManager/Menus").GetComponent<GameMenu>().BestiaryEntryClicked) { ClearFields(); } } /// <summary> /// Sets Menu to lock clicked bestiary entry so other entries won't be affected when hovered /// </summary> public void OnPointerClick(PointerEventData eventData) { if (!GameObject.Find("GameManager/Menus").GetComponent<GameMenu>().BestiaryEntryClicked) { GameObject.Find("GameManager/Menus").GetComponent<GameMenu>().BestiaryEntryClicked = true; gameObject.transform.Find("EnemyNameText").GetComponent<Text>().fontStyle = FontStyle.Bold; } } public void SetBestEntry() { if (!GameObject.Find("GameManager/Menus").GetComponent<GameMenu>().BestiaryEntryClicked) { GameObject.Find("GameManager/Menus").GetComponent<GameMenu>().BestiaryEntryClicked = true; gameObject.transform.Find("EnemyNameText").GetComponent<Text>().fontStyle = FontStyle.Bold; } } /// <summary> /// Clears all GUI fields /// </summary> void ClearFields() { GameObject.Find("GameManager/Menus/BestiaryMenuCanvas/BestiaryMenuPanel/EnemyNamePanel/EnemyNameText").GetComponent<Text>().text = ""; GameObject.Find("GameManager/Menus/BestiaryMenuCanvas/BestiaryMenuPanel/EnemyLevelPanel/EnemyLevelText").GetComponent<Text>().text = ""; GameObject.Find("GameManager/Menus/BestiaryMenuCanvas/BestiaryMenuPanel/EnemyGraphicPanel/EnemyGraphicImage").GetComponent<Image>().color = new Color( GameObject.Find("GameManager/Menus/BestiaryMenuCanvas/BestiaryMenuPanel/EnemyGraphicPanel/EnemyGraphicImage").GetComponent<Image>().color.r, GameObject.Find("GameManager/Menus/BestiaryMenuCanvas/BestiaryMenuPanel/EnemyGraphicPanel/EnemyGraphicImage").GetComponent<Image>().color.g, GameObject.Find("GameManager/Menus/BestiaryMenuCanvas/BestiaryMenuPanel/EnemyGraphicPanel/EnemyGraphicImage").GetComponent<Image>().color.b, 0); GameObject.Find("GameManager/Menus/BestiaryMenuCanvas/BestiaryMenuPanel/EnemyGraphicPanel/EnemyGraphicImage").GetComponent<Image>().sprite = null; GameObject.Find("GameManager/Menus/BestiaryMenuCanvas/BestiaryMenuPanel/EnemyDescriptionPanel/EnemyDescriptionText").GetComponent<Text>().text = ""; } /// <summary> /// Returns Enemy DB entry by given ID /// </summary> /// <param name="ID">ID of enemy entry to be returned</param> BaseEnemyDBEntry GetEnemyDBEntry(int ID) { foreach (BaseEnemyDBEntry entry in GameObject.Find("GameManager/DBs/EnemyDB").GetComponent<EnemyDB>().enemies) { if (entry.enemy.ID == ID) { return entry; } } return null; } }
using System; using System.IO; using System.Windows.Forms; using System.Xml.Serialization; using DevExpress.XtraBars; using DevExpress.XtraGrid.Views.Grid; using KartObjects; namespace KartLib.Views { /// <summary> /// Делегат для функции отображения состояния /// </summary> /// <param name="statusText">Текст статуса</param> public delegate void StatusProcType(string statusText); /// <summary> /// userControl реализующий базовую функциональность /// </summary> public partial class KartUserControl : UserControl,IAxiTradeView,ISettingsSaveable { public virtual string SectionName { get { return ""; } } /// <summary> /// Презентер для представления /// </summary> protected BasePresenter Preseneter; /// <summary> /// Показать статус-сообщение процесса /// </summary> public static StatusProcType ShowStatus; /// <summary> /// Текущий пользователь (со всеми правами доступа) /// </summary> public static User CurrentUser { get; set; } public virtual BarManager BarManager { get; set; } public KartUserControl() { InitializeComponent(); //_preseneter = new BasePresenter(); } private const ControlStyles Styles = ControlStyles.AllPaintingInWmPaint | ControlStyles.DoubleBuffer | ControlStyles.UserPaint; /// <summary> /// Признак выбора текущей записи в гриде /// </summary> public virtual bool RecordSelected { get { return false; } } public void BeginUpdate() { SetStyle(Styles, true); DoubleBuffered = true; } public void EndUpdate() { SetStyle(Styles, false); DoubleBuffered = false; } /// <summary> /// Действие печати /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void PrintAction(object sender, ItemClickEventArgs e) { //if (IsActionBanned(AxiTradeAction.Print)) return; PrintItems(sender, e); } public virtual void PrintItems(object sender, EventArgs e) { } /// <summary> /// Путь к файлу настроек грида /// </summary> public string gvSettingsFileName() { if (DesignMode) return "gvSettings.xml"; else return Settings.GetExecPath() + @"\settings\" + "gv" + this.GetType().Name + "Settings" + KartDataDictionary.user.Id + ".xml"; } public string gvSettingsFileName(string gvName) { if (DesignMode) return "gvSettings.xml"; else return Settings.GetExecPath() + @"\settings\" + gvName + "Settings" + KartDataDictionary.user.Id + ".xml"; } protected virtual Entity LoadSettings<T>() { Entity e=null; string FileName = Settings.GetExecPath() + @"\settings\" + typeof(T).Name + KartDataDictionary.user.Id.ToString() + ".xml"; if (File.Exists(FileName)) using (StreamReader reader = new StreamReader(FileName)) { var settingsSerializer = new XmlSerializer(typeof(T)); e = settingsSerializer.Deserialize(reader) as Entity; } return e; } protected virtual void SaveSettings<T>(Entity ViewSettings) where T : Entity, new() { if (!Directory.Exists(Settings.GetExecPath() + @"\settings")) Directory.CreateDirectory(Settings.GetExecPath() + @"\settings"); TextWriter writer = new StreamWriter(Settings.GetExecPath() + @"\settings\" + typeof(T).Name + KartDataDictionary.user.Id.ToString() + ".xml"); var serializer = new XmlSerializer(ViewSettings.GetType()); serializer.Serialize(writer, ViewSettings); writer.Close(); } /// <summary> /// Добавление записи /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void InsertAction(object sender, ItemClickEventArgs e) { if (IsActionBanned(AxiTradeAction.AddNew)) return; EditorAction(true); } public virtual void InsertItem(object sender, ItemClickEventArgs e) { } /// <summary> /// Редактирование записи /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void EditAction(object sender, ItemClickEventArgs e) { if (IsActionBanned(AxiTradeAction.Edit)) return; if (!RecordSelected) { return; } EditorAction(false); } /// <summary> /// Удаление записи /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void DeleteAction(object sender, ItemClickEventArgs e) { if ((!RecordSelected)||IsActionBanned(AxiTradeAction.Delete)) return; DeleteItem(sender, e); } public virtual void DeleteItem(object sender, ItemClickEventArgs e) { } protected bool TryDeleteDbEntity<T>(T deletedEntity, string warring) where T: Entity { if (deletedEntity == null) return false; if (MessageBox.Show(this, warring, "Внимание", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.Yes) { return Saver.DeleteFromDb<T>(deletedEntity); } else return false; } public virtual void EditorAction(bool addMode) { } private void KartUserControl_Load(object sender, EventArgs e) { //Для корректного отображения в дизайнере if (!DesignMode) { //_preseneter.ViewLoad(); InitView(); } } /// <summary> /// Обновление /// </summary> public virtual void RefreshView() { if (Preseneter != null) { //_preseneter.LoadDefaultData(); Preseneter.ViewLoad(); if (MainGridView != null) MainGridView.RefreshData(); } } public virtual ObjectType ViewObjectType { get; set; } /// <summary> /// true если действие action запрещено текущему пользователю иначе false /// </summary> public bool IsActionBanned(AxiTradeAction action) { return !KartDataDictionary.HasUserRightForActionWithObject(ViewObjectType, action); } /// <summary> /// Инициализация /// </summary> public virtual void InitView() { if (Preseneter == null) Preseneter = new BasePresenter(); //_preseneter.LoadDefaultData(); LoadSettings(); if (IsActionBanned(AxiTradeAction.View)) { Hide(); } else RefreshView(); } public virtual void LoadSettings() { } protected virtual GridView MainGridView { get; set; } public virtual Entity ActiveEntity { get { return MainGridView != null ? MainGridView.GetFocusedRow() as Entity : null; } set { if (MainGridView == null) return; for (var i = 0; i < MainGridView.RowCount; i++) { var simpleDbEntity = MainGridView.GetRow(i) as SimpleDbEntity; if (simpleDbEntity != null && (((!(MainGridView.GetRow(i) is SimpleDbEntity)) || (!(value is SimpleDbEntity))) || (simpleDbEntity.Id != (value as SimpleDbEntity).Id))) continue; MainGridView.FocusedRowHandle = i; break; } } } public virtual bool IsEditable { get { return false; } } public virtual bool IsInsertable { get { return false; } } public virtual bool UseSubmenu { get { return false; } set { ; } } public virtual bool IsDeletable { get { return false; } } public virtual bool IsPrintable { get { return false; } } /// <summary> /// Сохранение настроек /// </summary> public virtual void SaveSettings() { } /// <summary> /// Окончание работы /// </summary> public virtual void DoneView() { SaveSettings(); } /// <summary> /// Обновление состояния BarButton /// </summary> public virtual event EventHandler<EventArgs> SetBarButtonEvent; } }
using Sentry.Protocol.Envelopes; namespace Sentry.Internal.Extensions; internal static class ClientReportExtensions { public static void RecordDiscardedEvents(this IClientReportRecorder recorder, DiscardReason reason, Envelope envelope) { foreach (var item in envelope.Items) { recorder.RecordDiscardedEvent(reason, item.DataCategory); } } }
namespace InitModule.DefaultModule { internal class AutoFacManager { private Worker worker; private IPerson person; public AutoFacManager(Worker worker) { this.worker = worker; } public AutoFacManager(IPerson person) { this.person = person; } public AutoFacManager( ) { } } }
using System; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; namespace EnsureThat.Internals { public sealed class DefaultExceptionFactory : IExceptionFactory { [return: NotNull] [Pure] public Exception ArgumentException(string defaultMessage, string paramName) => new ArgumentException(defaultMessage, paramName); [return: NotNull] [Pure] public Exception ArgumentNullException(string defaultMessage, string paramName) => new ArgumentNullException(paramName, defaultMessage); [return: NotNull] [Pure] public Exception ArgumentOutOfRangeException<TValue>(string defaultMessage, string paramName, TValue value) => new ArgumentOutOfRangeException(paramName, value, defaultMessage); } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace API.Dtos { public class UserForRegisterDto { [Required] public string Username { get; set; } [Required] [StringLength(32, MinimumLength = 4, ErrorMessage = "You must specify a password between 4 and 32 characters")] public string Password { get; set; } [Required] public string KnownAs { get; set; } public string Email { get; set; } public DateTime Created { get; set; } public DateTime LastActive { get; set; } [Required] public string Role { get; set; } public UserForRegisterDto() { Created = DateTime.Now; LastActive = DateTime.Now; } public Nullable<int> OrganizationId { get; set; } public Nullable<int> FacilityId { get; set; } public Nullable<int> DepartmentId { get; set; } public Nullable<int> StoreId { get; set; } } }
using System.Collections.Generic; using Profiling2.Domain.Scr.Person; namespace Profiling2.Domain.Contracts.Queries { public interface IRequestPersonsQuery { IList<RequestPerson> GetNominatedRequestPersons(); IList<RequestPerson> GetNominationWithdrawnRequestPersons(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using WebApplication4.Repositories; using WebApplication4.ViewModels; namespace WebApplication4.Controllers { [Authorize] public class UserController : ApiController { public UserRepository UserRepository { get; set; } public UserController() { UserRepository = new UserRepository(); } public IEnumerable<UserDisplay> Get() { return UserRepository.GetTopUsers(); } } }
namespace MySurveys.Web.Areas.Surveys.Controllers { using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Attributes; using Base; using Models; using Services.Contracts; using ViewModels; using ViewModels.Filling; [Authorize] public class SurveysController : BaseScrollController { private static ICollection<AnswerViewModel> currentAnswers = new List<AnswerViewModel>(); private IQuestionService questionService; private IResponseService responseService; public SurveysController( ISurveyService surveyService, IUserService userService, IQuestionService questionService, IResponseService responseService) : base(userService, surveyService) { this.questionService = questionService; this.responseService = responseService; } //// GET: Surveys/Surveys/FillingUp [HttpGet] [AllowAnonymous] public ActionResult FillingUp(string id) { Survey survey; try { survey = this.SurveyService.GetById(id); } catch (Exception) { throw new HttpException(404, "Survey not found."); } if (!survey.IsPublic && this.CurrentUser == null) { return this.RedirectToAction("Login", "Account", new { area = string.Empty }); } var viewModel = this.Mapper.Map<SurveyViewModel>(survey); var firstQuestion = viewModel.Questions.ToList()[0]; return this.View(firstQuestion); } //// POST: Surveys/Surveys/FillingUp [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] [NoCache] public ActionResult FillingUp(FormCollection form) { if (form != null && ModelState.IsValid) { var questionId = Convert.ToInt32(form["Id"].ToString()); var possibleAnswerContent = form["Content"].ToString(); var dbQuestion = this.ValidateFormAndAddAnswer(questionId, possibleAnswerContent); var nextQuestion = this.questionService.GetNext(dbQuestion, possibleAnswerContent); if (nextQuestion != null) { if (!nextQuestion.PossibleAnswers.Any()) { this.SaveToDb(dbQuestion.SurveyId); currentAnswers.Clear(); this.TempData["fin"] = nextQuestion.Content; return this.RedirectToActionPermanent("Index", "Home", new { area = string.Empty }); } var viewModel = this.Mapper.Map<QuestionViewModel>(nextQuestion); return this.View(viewModel); } else { this.SaveToDb(dbQuestion.SurveyId); currentAnswers.Clear(); this.TempData["fin"] = "Thank you!"; } currentAnswers.Clear(); return this.RedirectToActionPermanent("Index", "Home", new { area = string.Empty }); } throw new HttpException(404, "Question not found"); } [NonAction] protected override IQueryable<Survey> GetData() { return this.SurveyService .GetAll(); } [NonAction] private Question ValidateFormAndAddAnswer(int questionId, string possibleAnswerContent) { Question dbQuestion; try { dbQuestion = this.questionService.GetById(questionId); } catch (Exception) { throw new HttpException(404, "Question not found"); } if (!dbQuestion.PossibleAnswers.Any(x => x.Content == possibleAnswerContent)) { throw new HttpException(404, "Answer not found"); } var possibleAnswer = dbQuestion.PossibleAnswers.FirstOrDefault(a => a.Content == possibleAnswerContent); var newAnswer = new AnswerViewModel() { QuestionId = dbQuestion.Id, PossibleAnswerId = possibleAnswer.Id }; currentAnswers.Add(newAnswer); return dbQuestion; } [NonAction] private void SaveToDb(int surveyId) { var currentSurvey = this.SurveyService.GetById(surveyId); var newResponse = new ResponseViewModel() { AuthorId = this.CurrentUser == null ? this.AnonimousUser.Id : this.CurrentUser.Id, Answers = currentAnswers }; var viewModel = this.Mapper.Map<Response>(newResponse); var saved = this.responseService.Add(viewModel); currentSurvey.Responses.Add(saved); this.SurveyService.Update(currentSurvey); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Web.Helpers; using System.Web.Mvc; using Timeclock.Services; using TimeClock.Data.Models; using TimeClock.Web.Models; using TimeClock.Web.Services; namespace TimeClock.Web.Controllers { //TODO: Add role based security here, to make sure only admins can edit employees; public class EmployeesController : Controller { private readonly IEmployeeService _employeeService; private readonly ITimeService _timeService; //ApplicationDbContext db = new ApplicationDbContext(); public EmployeesController(IEmployeeService employeeService, ITimeService timeService) { _employeeService = employeeService; _timeService = timeService; } // GET: Employees public ActionResult Index() { return View(); } [ChildActionOnly] public ActionResult List() { return PartialView(_employeeService.GetEmployeeList().Select(e => new EmployeeViewModel() { FirstName = e.FirstName, LastName = e.LastName, EmployeeId = e.EmployeeId, LastPunchTime = e.LastPunchTime, CurrentStatus = e.CurrentStatus })); } //GET: Employees/Details/5 public ActionResult Details(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Employee employee = _employeeService.FindById(id); if (employee == null) { return HttpNotFound(); } IEnumerable<TimePunchRequest> TimePunches = _timeService.GetPunchList(employee.EmployeeId, new TimeClockSpan( DateTime.Now.AddDays(-7), DateTime.Now)); View().ViewBag.TimePunches = TimePunches; return View(employee); } // GET: Employees/Create public ActionResult Create() { return View(); } // POST: Employees/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create([Bind(Include = "FirstName,LastName")] EmployeeCreateViewModel employeeViewModel) { if (ModelState.IsValid) { var employee = new Employee() { FirstName = employeeViewModel.FirstName, LastName = employeeViewModel.LastName, LastPunchTime = DateTime.Now }; _employeeService.CreateEmployee(employee); return RedirectToAction("Index"); } return View(employeeViewModel); } //// GET: Employees/Edit/5 public ActionResult Edit(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Employee employee = _employeeService.FindById(id); if (employee == null) { return HttpNotFound(); } return View(employee); } //// POST: Employees/Edit/5 //// To protect from overposting attacks, please enable the specific properties you want to bind to, for //// more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit([Bind(Include = "EmployeeId,FirstName,LastName")] Employee employee) { if (ModelState.IsValid) { _employeeService.UpdateEmployee(employee); return RedirectToAction("Index"); } return View(employee); } public ActionResult Clock(int? id, TimePunchStatus status) { if (id != null) { Employee employee = _employeeService.FindById(id); _employeeService.ChangeClockStatus(employee, status); _timeService.AddTimePunch(employee, new TimePunchRequest((int)id, status, DateTime.Now)); } return new RedirectResult(Request.UrlReferrer.AbsoluteUri); } [ChildActionOnly] public ActionResult StatusBlock(TimePunchStatus status) { var employeesWithStatus = _employeeService.FindByStatus(status); string statusString = status == TimePunchStatus.PunchedIn ? "in" : "out"; ViewBag.CountWithStatus = employeesWithStatus.Count; ViewBag.StatusString = statusString; return PartialView(); } public ActionResult EmployeeManager() { var emloyees = _employeeService.GetEmployeeList() .Select(e => new EmployeeManagerViewModel() { EmployeeId = e.EmployeeId, FullName = e.FullName }); return View(emloyees); } // GET: Employees/Delete/5 public ActionResult Delete(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Employee employee = _employeeService.FindById(id); if (employee == null) { return HttpNotFound(); } return View(employee); } // POST: Employees/Delete/5 [HttpPost, ActionName("Delete")] // [ValidateAntiForgeryToken] public ActionResult DeleteConfirmed(int id) { Employee employee = _employeeService.FindById(id); _employeeService.DeleteEmployee(employee); return Json(new { success = true }); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace JDWinService.Model { public class JD_SeorderBG_Log { public int ItemID { get; set; } /// <summary> /// /// </summary> public int FInterID { get; set; } /// <summary> /// /// </summary> public int FEntryID { get; set; } /// <summary> /// /// </summary> public string FBillNo { get; set; } /// <summary> /// /// </summary> public string FCustID { get; set; } /// <summary> /// /// </summary> public DateTime FDate { get; set; } /// <summary> /// /// </summary> public string Operater { get; set; } /// <summary> /// /// </summary> public string OperaterID { get; set; } /// <summary> /// /// </summary> public DateTime OperateDate { get; set; } /// <summary> /// /// </summary> public string IsUpdate { get; set; } public DateTime? FEntrySelfS0155 { get; set; } public DateTime? FEntrySelfS0154 { get; set; } public DateTime? FQTDate { get; set; } public string FQueLiao { get; set; } //备注 public string FNote { get; set; } //齐套日期 public string FEntrySelfS0183 { get; set; } //缺料 public string FEntrySelfS0184 { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class AIScript : MonoBehaviour { public GameObject TheAICar; public GameObject TheMarker; public GameObject Mark01; public GameObject Mark02; public GameObject Mark03; public GameObject Mark04; public GameObject Mark05; public GameObject Mark06; public GameObject Mark07; public GameObject Mark08; public GameObject Mark09; public GameObject Mark10; public GameObject Mark11; public GameObject Mark12; public GameObject Mark13; public GameObject Mark14; public GameObject Mark15; public GameObject Mark16; public GameObject Mark17; public GameObject Mark18; public GameObject Mark19; public GameObject Mark20; public GameObject Mark21; public GameObject Mark22; public GameObject Mark23; public GameObject Mark24; public GameObject Mark25; public GameObject Mark26; public GameObject Mark27; public GameObject Mark28; public GameObject Mark29; public GameObject Mark30; public GameObject Mark31; public GameObject Mark32; public GameObject Mark33; public GameObject Mark34; public GameObject Mark35; public GameObject Mark36; public GameObject Mark37; public GameObject Mark38; public GameObject Mark39; public GameObject Mark40; public GameObject Mark41; public GameObject Mark42; public int MarkTracker; void Update() { if(MarkTracker==0) { // Debug.Log("MarkTracker is 0"); //MarkTracker++; TheMarker.transform.position = Mark01.transform.position; } if (MarkTracker == 1) { // Debug.Log("MarkTracker is 1"); TheMarker.transform.position = Mark02.transform.position; TheMarker.transform.localScale = new Vector3(30, 30, 30); //MarkTracker++; } if (MarkTracker == 2) { // Debug.Log("MarkTracker is 2"); TheMarker.transform.position = Mark03.transform.position; } if (MarkTracker == 3) { TheMarker.transform.position = Mark04.transform.position; } if (MarkTracker == 4) { TheMarker.transform.position = Mark05.transform.position; } if (MarkTracker == 5) { TheMarker.transform.position = Mark06.transform.position; } if (MarkTracker == 6) { // Debug.Log("MarkTracker is 1"); TheMarker.transform.position = Mark07.transform.position; //MarkTracker++; } if (MarkTracker == 7) { // Debug.Log("MarkTracker is 2"); TheMarker.transform.position = Mark08.transform.position; } if (MarkTracker == 8) { TheMarker.transform.position = Mark09.transform.position; } if (MarkTracker == 9) { TheMarker.transform.position = Mark10.transform.position; } if (MarkTracker == 10) { TheMarker.transform.position = Mark11.transform.position; } if (MarkTracker == 11) { // Debug.Log("MarkTracker is 1"); TheMarker.transform.position = Mark12.transform.position; //MarkTracker++; } if (MarkTracker == 12) { // Debug.Log("MarkTracker is 2"); TheMarker.transform.position = Mark13.transform.position; } if (MarkTracker == 13) { TheMarker.transform.position = Mark14.transform.position; } if (MarkTracker == 14) { TheMarker.transform.position = Mark15.transform.position; } if (MarkTracker == 15) { TheMarker.transform.position = Mark16.transform.position; } if (MarkTracker == 16) { // Debug.Log("MarkTracker is 1"); TheMarker.transform.position = Mark17.transform.position; TheAICar.GetComponent<Rigidbody>().drag = 0.05f; TheAICar.GetComponent<Rigidbody>().angularDrag = 0.05f; Debug.Log("Changed drag and stuff!"); //MarkTracker++; } if (MarkTracker == 17) { // Debug.Log("MarkTracker is 2"); TheMarker.transform.position = Mark18.transform.position; } if (MarkTracker == 18) { TheMarker.transform.position = Mark19.transform.position; TheAICar.GetComponent<Rigidbody>().drag = 0.2f; TheAICar.GetComponent<Rigidbody>().angularDrag = 0.2f; Debug.Log("Changed drag and stuff, again!"); } if (MarkTracker == 19) { TheMarker.transform.position = Mark20.transform.position; } if (MarkTracker == 20) { TheMarker.transform.position = Mark21.transform.position; //TheMarker.transform.localScale = new Vector3(15, 15, 15); } if (MarkTracker == 21) { TheMarker.transform.position = Mark22.transform.position; } if (MarkTracker == 22) { TheMarker.transform.position = Mark23.transform.position; } if (MarkTracker == 23) { // Debug.Log("MarkTracker is 1"); TheMarker.transform.position = Mark24.transform.position; //MarkTracker++; } if (MarkTracker == 24) { // Debug.Log("MarkTracker is 2"); TheMarker.transform.position = Mark25.transform.position; } if (MarkTracker == 25) { TheMarker.transform.position = Mark26.transform.position; } if (MarkTracker == 26) { TheMarker.transform.position = Mark27.transform.position; //TheMarker.transform.localScale = new Vector3(10, 10, 10); } if (MarkTracker == 27) { TheMarker.transform.position = Mark28.transform.position; } if(MarkTracker == 28) { TheMarker.transform.position = Mark29.transform.position; } if (MarkTracker == 29) { // Debug.Log("MarkTracker is 1"); TheMarker.transform.position = Mark30.transform.position; //MarkTracker++; } if (MarkTracker == 30) { // Debug.Log("MarkTracker is 2"); TheMarker.transform.position = Mark31.transform.position; } if (MarkTracker == 31) { // Debug.Log("MarkTracker is 1"); TheMarker.transform.position = Mark32.transform.position; //MarkTracker++; } if (MarkTracker == 32) { // Debug.Log("MarkTracker is 2"); TheMarker.transform.position = Mark33.transform.position; } if (MarkTracker == 33) { TheMarker.transform.position = Mark34.transform.position; } if (MarkTracker == 34) { TheMarker.transform.position = Mark35.transform.position; } if (MarkTracker == 35) { TheMarker.transform.position = Mark36.transform.position; } if (MarkTracker == 36) { // Debug.Log("MarkTracker is 1"); TheMarker.transform.position = Mark37.transform.position; //MarkTracker++; } if (MarkTracker == 37) { // Debug.Log("MarkTracker is 2"); TheMarker.transform.position = Mark38.transform.position; } if (MarkTracker == 38) { TheMarker.transform.position = Mark39.transform.position; } if (MarkTracker == 39) { TheMarker.transform.position = Mark40.transform.position; } if (MarkTracker == 40) { TheMarker.transform.position = Mark41.transform.position; } if (MarkTracker == 41) { TheMarker.transform.position = Mark42.transform.position; } if (MarkTracker == 42) { TheMarker.transform.position = Mark01.transform.position; } } IEnumerator OnTriggerEnter(Collider collision) { Debug.Log("OnTriggerEnter"); if(collision.gameObject.tag == "AI") { Debug.Log("MarkTracker is incremented"+MarkTracker); this.GetComponent<BoxCollider>().enabled = false; MarkTracker++; if (MarkTracker == 42) MarkTracker = 0; } yield return new WaitForSeconds(1f); this.GetComponent<BoxCollider>().enabled = true; } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; namespace Challenge25 { public class Canidate { private string _name; private int _age; private string _party; private string _sex; private int _voteCount; public int VoteCount { get { return _voteCount; } set { _voteCount = value; } } public string Name { get { return _name; } set { _name = value; } } public string Party { get { return _party; } set { _party = value; } } public string Sex { get { return _sex; } set { _sex = value; } } public int Age { get { return _age; } set { _age = value; } } public object Current { get { throw new NotImplementedException(); } } } }
using System; using System.IO; namespace Tomelt { public class Program { const int ConsoleInputBufferSize = 8192; public static int Main(string[] args) { Console.SetIn(new StreamReader(Console.OpenStandardInput(ConsoleInputBufferSize))); return (int)new TomeltHost(Console.In, Console.Out, args).Run(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using System.ComponentModel; using TraceWizard.Entities; using TraceWizard.Notification; namespace TraceWizard.TwApp { public partial class StyledEventsViewer : UserControl { public Events Events { get; set; } public double ViewportSeconds { get; set; } public double ViewportVolume { get; set; } public StyledEventsViewer() { InitializeComponent(); } public void Initialize() { EventsViewer.Events = Events; EventsViewer.ViewportSeconds = ViewportSeconds; EventsViewer.ViewportVolume = ViewportVolume; EventsViewer.HorizontalRuler = HorizontalRuler; EventsViewer.VerticalRuler = VerticalRuler; EventsViewer.SelectionRuler = SelectionRuler; EventsViewer.ApprovalRuler = ApprovalRuler; EventsViewer.ClassificationRuler = ClassificationRuler; EventsViewer.FixturesRuler = FixturesRuler; EventsViewer.Initialize(); TimeFramePanel.Events = Events; TimeFramePanel.Initialize(); SelectionRuler.Events = Events; SelectionRuler.Initialize(); ApprovalRuler.Events = Events; ApprovalRuler.Initialize(); ClassificationRuler.Events = Events; ClassificationRuler.Initialize(); FixturesRuler.Events = Events; FixturesRuler.ViewportSeconds = ViewportSeconds; FixturesRuler.Initialize(); BindTimeFrameView(); ScrollViewersSetBindings(); Events.PropertyChanged += new PropertyChangedEventHandler(Events_PropertyChanged); } void ScrollViewersSetBindings() { BindHorizontalScrollViewers(EventsViewer.ScrollViewer, EventsViewer.HorizontalRuler.ScrollViewer); BindVerticalScrollViewers(EventsViewer.ScrollViewer, EventsViewer.VerticalRuler.ScrollViewer); BindHorizontalScrollViewers(EventsViewer.ScrollViewer, SelectionRuler.ScrollViewer); BindHorizontalScrollViewers(EventsViewer.ScrollViewer, ApprovalRuler.ScrollViewer); BindHorizontalScrollViewers(EventsViewer.ScrollViewer, ClassificationRuler.ScrollViewer); BindHorizontalScrollViewers(EventsViewer.ScrollViewer, FixturesRuler.ScrollViewer); } public void Events_PropertyChanged(object sender, PropertyChangedEventArgs e) { switch (e.PropertyName) { case TwNotificationProperty.OnChangeStartTime: WorkaroundForBindingProblem(); break; case TwNotificationProperty.OnEndApplyConversionFactor: RedrawVolumesChanged(); break; } } void RedrawVolumesChanged() { EventsViewer.ScrollChanged(true); EventsViewer.RestoreHorizontalScrollPosition(EventsViewer.UndoPosition); } void WorkaroundForBindingProblem() { TimeFramePanel.ClearBindings(); TimeFramePanel.SetBindings(); BindTimeFrameView(); this.EventsViewer.RenderRowsColumnsRulers(ViewportSeconds, ViewportVolume); } void BindHorizontalScrollViewers(ScrollViewer source, ScrollViewer target) { target.IsEnabled = false; target.IsTabStop = false; target.Focusable = false; TranslateTransform translateTransform = new TranslateTransform(); Binding bindingHorizontal = new Binding("HorizontalOffset"); bindingHorizontal.Source = source; bindingHorizontal.Converter = new ScrollViewerHorizontalConverter(); BindingOperations.SetBinding(translateTransform, TranslateTransform.XProperty, bindingHorizontal); Canvas canvas = (Canvas)target.Content; canvas.RenderTransform = translateTransform; } void BindVerticalScrollViewers(ScrollViewer source, ScrollViewer target) { target.IsEnabled = false; target.IsTabStop = false; target.Focusable = false; TranslateTransform translateTransform = new TranslateTransform(); Binding bindingVertical = new Binding("VerticalOffset"); bindingVertical.Source = source; bindingVertical.Converter = new ScrollViewerHorizontalConverter(); BindingOperations.SetBinding(translateTransform, TranslateTransform.YProperty, bindingVertical); Canvas canvas = (Canvas)target.Content; canvas.RenderTransform = translateTransform; } void BindTimeFrameView() { Binding bindingHorizontalOffset = new Binding("HorizontalOffset"); bindingHorizontalOffset.Source = EventsViewer.ScrollViewer; Binding bindingViewportWidth = new Binding("ViewportWidth"); bindingViewportWidth.Source = EventsViewer.ScrollViewer; Binding bindingWidth = new Binding("Width"); bindingWidth.Source = EventsViewer.LinedEventsCanvas; MultiBinding multiBinding; multiBinding = new MultiBinding(); multiBinding.Bindings.Add(bindingHorizontalOffset); multiBinding.Bindings.Add(bindingViewportWidth); multiBinding.Bindings.Add(bindingWidth); multiBinding.Converter = new TwHelper.ViewportStartTimeConverter(); multiBinding.ConverterParameter = Events.TimeFrame; BindingOperations.SetBinding(TimeFramePanel.textViewStartTime, TextBlock.TextProperty, multiBinding); multiBinding = new MultiBinding(); multiBinding.Bindings.Add(bindingHorizontalOffset); multiBinding.Bindings.Add(bindingViewportWidth); multiBinding.Bindings.Add(bindingWidth); multiBinding.Converter = new TwHelper.ViewportStartDateConverter(); multiBinding.ConverterParameter = Events.TimeFrame; BindingOperations.SetBinding(TimeFramePanel.textViewStartDate, TextBlock.TextProperty, multiBinding); multiBinding = new MultiBinding(); multiBinding.Bindings.Add(bindingHorizontalOffset); multiBinding.Bindings.Add(bindingViewportWidth); multiBinding.Bindings.Add(bindingWidth); multiBinding.Converter = new TwHelper.ViewportEndTimeConverter(); multiBinding.ConverterParameter = Events.TimeFrame; BindingOperations.SetBinding(TimeFramePanel.textViewEndTime, TextBlock.TextProperty, multiBinding); multiBinding = new MultiBinding(); multiBinding.Bindings.Add(bindingHorizontalOffset); multiBinding.Bindings.Add(bindingViewportWidth); multiBinding.Bindings.Add(bindingWidth); multiBinding.Converter = new TwHelper.ViewportEndDateConverter(); multiBinding.ConverterParameter = Events.TimeFrame; BindingOperations.SetBinding(TimeFramePanel.textViewEndDate, TextBlock.TextProperty, multiBinding); multiBinding = new MultiBinding(); multiBinding.Bindings.Add(bindingHorizontalOffset); multiBinding.Bindings.Add(bindingViewportWidth); multiBinding.Bindings.Add(bindingWidth); multiBinding.Converter = new TwHelper.ViewportDurationConverter(); multiBinding.ConverterParameter = Events.TimeFrame; BindingOperations.SetBinding(TimeFramePanel.textViewDuration, TextBlock.TextProperty, multiBinding); } } }
namespace EmailStatistics { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; public class StartUp { public static void Main() { var n = int.Parse(Console.ReadLine()); var pattern = @"(^|(?<=\s))([A-Za-z]{5,})@([a-z]{3,})(.com|.bg|.org)($|(?=\s))"; var emailRegister = new Dictionary<string, List<string>>(); for (int i = 0; i < n; i++) { var email = Console.ReadLine(); var match = Regex.Match(email, pattern); if (match.Success == false) { continue; } var user = match.Groups[2].Value; var domain = match.Groups[3].Value + match.Groups[4].Value; if (emailRegister.ContainsKey(domain) == false) { emailRegister.Add(domain, new List<string>()); } if (emailRegister[domain].Contains(user) == false) { emailRegister[domain].Add(user); } } foreach (var domain in emailRegister.OrderByDescending(x => x.Value.Count)) { Console.WriteLine($"{domain.Key}:"); Console.WriteLine($"{string.Join(Environment.NewLine, domain.Value.Select(x => $"### {x}"))}"); } } } }
using UnityEngine; using System.Collections; public class MenuObjectRotator : MonoBehaviour { void Update () { if (Camera.main.transform.position.x == 0 && Camera.main.transform.position.y >= -7.25 && Camera.main.transform.position.y <= 0) { if (gameObject.name == "ground") { transform.rotation = Quaternion.Euler(new Vector3(Camera.main.transform.position.y * -70f / 7.25f + 290f, transform.rotation.eulerAngles.y, transform.rotation.eulerAngles.z)); } else { transform.rotation = Quaternion.Euler(new Vector3(Camera.main.transform.position.y * 20f / 7.25f + 290f, 180f, 22.5f)); if (transform.position.y <= -9.5) { transform.rotation = Quaternion.Euler(new Vector3(transform.position.y * -5f + 225f, 180f, 22.5f)); } } } } }
using System; using System.Collections.Generic; using System.Text; namespace ClassMetotDemo { class MusteriManager { public void Ekle(Musteri musteri) { Console.WriteLine("---Müşteri Eklendi---"); Console.WriteLine("Müşteri ID:" + musteri.MusteriId); Console.WriteLine("Adı : " + musteri.MusteriAd); Console.WriteLine("Soyadı : " + musteri.MusteriSoyad); } public void Listele(Musteri musteri) { Console.WriteLine("---Müşteriler Listelendi---"); Console.WriteLine("Müşteri ID: " + musteri.MusteriId); Console.WriteLine("Adı : " + musteri.MusteriAd); Console.WriteLine("Soyadı : " + musteri.MusteriSoyad); } public void Sil(Musteri musteri) { Console.WriteLine("---Tebrikler Müşteri Başarılı ile silindi---"); Console.WriteLine("Müşteri ID: " + musteri.MusteriId); Console.WriteLine("Adı : " + musteri.MusteriAd); Console.WriteLine("Soyadı : " + musteri.MusteriSoyad); } } }
using System; using System.Windows; using System.Windows.Controls; namespace CODE.Framework.Wpf.Controls { /// <summary> /// Slider class used to set zoom levels /// </summary> /// <remarks> /// In zoom scenarios, the value 1 is usually the middle of the slider, while all the way /// to the left is something like .5 and all the way to the right is something like 500 /// </remarks> public class ZoomSlider : Slider { /// <summary> /// Initializes a new instance of the <see cref="ZoomSlider"/> class. /// </summary> public ZoomSlider() { //MouseDoubleClick += (o, e) => { Value = 1; }; ValueChanged += (o, e) => { UpdateChangeIncrement(); UpdateZoomFromValue(); }; MouseDoubleClick += (o, e) => { Value = 1d; }; SmallChange = .1d; Value = 1; Minimum = 0; Maximum = 2; UpdateChangeIncrement(); } /// <summary> /// Maximum zoom factor (example: 500% is 5) /// </summary> public double MaximumZoom { get { return (double)GetValue(MaximumZoomProperty); } set { SetValue(MaximumZoomProperty, value); } } /// <summary> /// Maximum zoom factor (example: 500% is 5) /// </summary> public static readonly DependencyProperty MaximumZoomProperty = DependencyProperty.Register("MaximumZoom", typeof(double), typeof(ZoomSlider), new PropertyMetadata(5d)); /// <summary> /// Minimum zoom factor (example: 50% is 0.5) /// </summary> public double MinimumZoom { get { return (double)GetValue(MinimumZoomProperty); } set { SetValue(MinimumZoomProperty, value); } } /// <summary> /// Minimum zoom factor (example: 50% is 0.5) /// </summary> public static readonly DependencyProperty MinimumZoomProperty = DependencyProperty.Register("MinimumZoom", typeof(double), typeof(ZoomSlider), new PropertyMetadata(.2d)); /// <summary> /// Text representation of the current zoom level /// </summary> public string ZoomText { get { return (string)GetValue(ZoomTextProperty); } set { SetValue(ZoomTextProperty, value); } } /// <summary> /// Text representation of the current zoom level /// </summary> public static readonly DependencyProperty ZoomTextProperty = DependencyProperty.Register("ZoomText", typeof(string), typeof(ZoomSlider), new PropertyMetadata("100%")); /// <summary> /// Actual zoom factor based on the slider value /// </summary> public double Zoom { get { return (double)GetValue(ZoomProperty); } set { SetValue(ZoomProperty, value); } } /// <summary> /// Actual zoom factor based on the slider value /// </summary> public static readonly DependencyProperty ZoomProperty = DependencyProperty.Register("Zoom", typeof(double), typeof(ZoomSlider), new PropertyMetadata(1d, OnZoomChanged)); private static void OnZoomChanged(DependencyObject d, DependencyPropertyChangedEventArgs args) { var zoom = d as ZoomSlider; if (zoom == null) return; zoom.OnZoomFactorChanged(); } /// <summary> /// Called when the zoom factor changes (can be overridden in subclasses) /// </summary> protected virtual void OnZoomFactorChanged() { } private IncrementMode _incrementMode = IncrementMode.Unset; /// <summary> /// Calculates the change increment of the slider when the user clicks +/- based /// on the current value as well as min/max increments /// </summary> private void UpdateChangeIncrement() { if (Value <= 1d && _incrementMode != IncrementMode.Negative) { // Each small click represents a 10% increase downwards var negativeRange = 1d - MinimumZoom; var negativeMultiplier = negativeRange * 10; SmallChange = 1/negativeMultiplier; _incrementMode = IncrementMode.Negative; } else if (Value > 1d && _incrementMode != IncrementMode.Positive) { // Each small click represents a 10% increase upwards (which is on a different scale compared to shrinking) _incrementMode = IncrementMode.Positive; var positiveRange = MaximumZoom - 1d; var positiveMultiplier = positiveRange*10; SmallChange = 1/positiveMultiplier; } } private enum IncrementMode { Unset, Negative, Positive } /// <summary> /// Calculates the zoom factor from the current value and min/max settings /// </summary> private void UpdateZoomFromValue() { if (Value < 1d) { var negativeRange = 1d - MinimumZoom; var currentPercentageOfNegativeRange = Value; var currentShrinkFactor = MinimumZoom + (currentPercentageOfNegativeRange*negativeRange); Zoom = currentShrinkFactor; if (Zoom > 0.97d && Zoom < 1.03d) Zoom = 1d; var percentage = Math.Round(Zoom*100); ZoomText = percentage + "%"; } else if (Value > 1d) { // Note: The positive side of the slider is on a different scale than the negative side var positiveRange = MaximumZoom - 1d; var currentPercentageOfPositiveRange = Value - 1; var currentGrowFactor = (currentPercentageOfPositiveRange*positiveRange) + 1; Zoom = currentGrowFactor; if (Zoom > 0.97d && Zoom < 1.03d) Zoom = 1d; var percentage = Math.Round(Zoom * 100); ZoomText = percentage + "%"; } else { Zoom = 1d; ZoomText = "100%"; } } } }
using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.Audio; using UnityEngine.UI; using System.Collections.Generic; public class MainMenu : MonoBehaviour { const float DEFAULT_VOL = 0f; const float MIN_VOL = -80f; const float MAX_VOL = 20f; public AudioMixer effectsMixer; public AudioMixer musicMixer; public AudioSource onClickSound; public Dropdown qualityDd, resolutionDd; public Toggle fullscreen; public GameObject videoOptions; public GameObject title; public GUISkin guiSkin; public Image controls; public float fXVolume; public float musicVolume; int indexResolution; int screenWidth, screenHeight; int btnWidth, btnHeight; float posX, posY; Resolution[] resolutions; enum Menu { main, play, options, controls, audio, video } [SerializeField] Menu currentMenu = Menu.main; // Use this for initialization void Start () { fXVolume = DEFAULT_VOL; musicVolume = DEFAULT_VOL; resolutions = Screen.resolutions; resolutionDd.ClearOptions(); List<string> choices = new List<string>(); // Source : Tutorial at https://www.youtube.com/watch?v=YOaYQrN1oYQ for (int i = 0; i < resolutions.Length; i++) { string widthByHeight = resolutions[i].width + " x " + resolutions[i].height; choices.Add(widthByHeight); if (resolutions[i].width == Screen.currentResolution.width && resolutions[i].height == Screen.currentResolution.height) indexResolution = i; } CalculateButtonMetrics(); resolutionDd.AddOptions(choices); resolutionDd.value = indexResolution; resolutionDd.RefreshShownValue(); } private void Test() { Debug.Log("Esketit"); } // Calculating the sizes at infinitum in case of resizes private void Update() { CalculateButtonMetrics(); } // Starts a new game, the game scene must be the next one in the build settings public void StartGame() { SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1); } // Quits the game, need to actually build the game though, it does not work on the editor public void QuitGame() { Application.Quit(); } private void ClickSound() { onClickSound.Play(); } // Every single button generated dynamicly on the main menu private void OnGUI() { GUI.skin = guiSkin; if (currentMenu == Menu.main) title.SetActive(true); else title.SetActive(false); if (currentMenu == Menu.main) { if (GUI.Button(new Rect(posX, posY + btnHeight * 2, btnWidth, btnHeight), "JOUER")) { StartGame(); currentMenu = Menu.play; ClickSound(); } if (GUI.Button(new Rect(posX, posY + btnHeight * 3, btnWidth, btnHeight), "OPTIONS")) { currentMenu = Menu.options; ClickSound(); } if (GUI.Button(new Rect(posX, posY + btnHeight * 4, btnWidth, btnHeight), "QUITTER")) { QuitGame(); ClickSound(); } } else if (currentMenu == Menu.options) { if (GUI.Button(new Rect(posX, posY + btnHeight * 1, btnWidth, btnHeight), "CONTROLES")) { currentMenu = Menu.controls; ClickSound(); } if (GUI.Button(new Rect(posX, posY + btnHeight * 2, btnWidth, btnHeight), "AUDIO")) { currentMenu = Menu.audio; ClickSound(); } if (GUI.Button(new Rect(posX, posY + btnHeight * 3, btnWidth, btnHeight), "VIDEO")) { currentMenu = Menu.video; ClickSound(); } if (GUI.Button(new Rect(posX, posY + btnHeight * 5, btnWidth, btnHeight), "RETOUR")) { currentMenu = Menu.main; ClickSound(); } } else if (currentMenu == Menu.controls) { controls.gameObject.SetActive(true); if (GUI.Button(new Rect(posX, posY + btnHeight * 6, btnWidth, btnHeight), "RETOUR")) { currentMenu = Menu.options; ClickSound(); } } else if (currentMenu == Menu.audio) { if (GUI.Button(new Rect(posX, posY + btnHeight * 1, btnWidth, btnHeight), "VOLUME EFFETS")) { fXVolume = DEFAULT_VOL; ClickSound(); } EffectsVolumeSlider(); if (GUI.Button(new Rect(posX, posY + btnHeight * 3, btnWidth, btnHeight), "VOLUME MUSIQUE")) { musicVolume = DEFAULT_VOL; ClickSound(); } EffectsMusicSlider(); if (GUI.Button(new Rect(posX, posY + btnHeight * 5, btnWidth, btnHeight), "RETOUR")) { currentMenu = Menu.options; ClickSound(); } } else if (currentMenu == Menu.video) { SetVideoOptions(); if (GUI.Button(new Rect(posX, posY + btnHeight * 5, btnWidth, btnHeight), "RETOUR")) { currentMenu = Menu.options; ClickSound(); } } if (currentMenu != Menu.video) videoOptions.gameObject.SetActive(false); if (currentMenu != Menu.controls) controls.gameObject.SetActive(false); } // The lower the index, the worst the quality is, e.g. no shadows rendered public void SetQuality(int qualityIndex) { QualitySettings.SetQualityLevel(qualityIndex); } // Toggles fullscreen and windowed mode, not feeling like adding windowed fullscreen public void SetFullscreen(bool isFullscreen) { if (isFullscreen) Screen.fullScreen = true; else Screen.fullScreen = false; } // Sets the resolution depending on the index [0, 5], 0 being the worst public void SetResolution(int index) { Resolution resolution = resolutions[index]; Screen.SetResolution(resolution.width, resolution.height, Screen.fullScreen); } // Retrieving actual value to print the right slider, reading the new value at each frame to update the slider void EffectsVolumeSlider() { effectsMixer.GetFloat("Volume", out fXVolume); fXVolume = GUI.HorizontalSlider(new Rect(posX, posY + btnHeight * 2, btnWidth, btnHeight), fXVolume, MIN_VOL, MAX_VOL); effectsMixer.SetFloat("Volume", fXVolume); } // Retrieving actual value to print the right slider, reading the new value at each frame to update the slider void EffectsMusicSlider() { musicMixer.GetFloat("Volume", out musicVolume); musicVolume = GUI.HorizontalSlider(new Rect(posX, posY + btnHeight * 4, btnWidth, btnHeight), musicVolume, MIN_VOL, MAX_VOL); musicMixer.SetFloat("Volume", musicVolume); } // How big should the things be ( ͡° ͜ʖ ͡°) void CalculateButtonMetrics() { screenWidth = Screen.width; screenHeight = Screen.height; btnWidth = screenWidth / 3; btnHeight = screenHeight / 10; posX = screenWidth / 2 - btnWidth / 2; posY = (3f / 10f) * screenHeight; } // All of the video options void SetVideoOptions() { videoOptions.gameObject.SetActive(true); qualityDd.value = QualitySettings.GetQualityLevel(); fullscreen.isOn = (Screen.fullScreen) ? true : false; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CameraFollows : MonoBehaviour { public Orbit object1; public Orbit2 object2; public Transform transformObject1; public Transform transformObject2; private Vector3 posicion; public Vector3 offset; public float CamMoveSpeed = 5f; void Start() { offset.Set(0, 0, -10); transform.position =(transformObject1.transform.position + offset); } void Update() { if (object1.orbiting == false) { transform.position = Vector3.Lerp(transform.position, transformObject1.transform.position + offset, CamMoveSpeed * Time.deltaTime); } if(object2.orbiting == false){ transform.position = Vector3.Lerp(transform.position, transformObject2.transform.position + offset, CamMoveSpeed * Time.deltaTime); } } }
using System; using Photon.Pun; using UnityEngine; public class PlayerHealth : MonoBehaviourPun { public const float MAX_HEALTH = 20.0f; public Action<float> OnHealthChanged; public Action OnHealthZero; private float value = MAX_HEALTH; public float Value { get => value; private set { this.value = Mathf.Clamp(value, 0, MAX_HEALTH); if(value < MAX_HEALTH) { audioSource.clip = audioClip; audioSource.Play(0); } OnHealthChanged?.Invoke(this.value); if (this.value == 0) { OnHealthZero?.Invoke(); gameObject.SetActive(false); } } } private AudioSource audioSource; public AudioClip audioClip; private void Awake() { audioSource = GetComponent<AudioSource>(); } public void Damage(float value) { photonView.RPC(nameof(DamageRPC), RpcTarget.All, value); } [PunRPC] public void DamageRPC(float damage) { Value -= damage; } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace com.Sconit.Web.Models.SearchModels.BIL { public class PlanBillSearchModel : SearchModelBase { public string Item { get; set; } public string ReceiptNo { get; set; } public string Party { get; set; } public string Flow { get; set; } public string Currency { get; set; } public string OrderNo { get; set; } public DateTime? CreateDate_start { get; set; } public DateTime? CreateDate_End { get; set; } public DateTime? EndTime { get; set; } public DateTime? StartTime { get; set; } public int? Type { get; set; } } }
using System.Collections.Generic; using Alabo.Data.People.Stores.Domain.Services; using Alabo.Datas.UnitOfWorks; using Alabo.Domains.Entities; using Alabo.Domains.Repositories; using Alabo.Domains.Services; using Alabo.Extensions; using Alabo.Industry.Shop.Deliveries.Domain.Entities; using MongoDB.Bson; namespace Alabo.Industry.Shop.Deliveries.Domain.Services { public class DeliveryTemplateService : ServiceBase<DeliveryTemplate, ObjectId>, IDeliveryTemplateService { public DeliveryTemplateService(IUnitOfWork unitOfWork, IRepository<DeliveryTemplate, ObjectId> repository) : base(unitOfWork, repository) { } /// <summary> /// 获取运费模板 /// </summary> /// <param name="storeId"></param> /// <returns></returns> public List<KeyValue> GetStoreDeliveryTemplateByCache(ObjectId storeId) { var store = Resolve<IStoreService>().GetSingleFromCache(storeId); if (store == null) { return null; } var result = new List<KeyValue>(); var list = GetList(r => r.StoreId == storeId); list.Foreach(r => { result.Add(new KeyValue(r.Id, r.TemplateName)); }); return result; } } }
using UnityEngine; namespace Assets.Scripts.UI { public class AdditionalStatsConstroller : MonoBehaviour { public UIGrid GridItems; public GameObject BreathObject; public UISprite BreathProgress; private GameManager _gameManager; private bool _initialized; public void Init(GameManager gameManager) { _gameManager = gameManager; BreathObject.SetActive(false); _initialized = true; } public void SetBreath(bool active) { BreathObject.SetActive(active); GridItems.Reposition(); } public void UpdateStats() { if (!_initialized) return; if (BreathObject.activeSelf) BreathProgress.fillAmount = 1 - _gameManager.PlayerModel.Breath/100f; } } }
using System.Data.Entity; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; using System.ComponentModel.DataAnnotations.Schema; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace BitClassroom.DAL.Models { // You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more. public class ApplicationUser : IdentityUser { public string Name { get; set; } [Display(Name="Last Name")] public string Lastname { get; set; } [NotMapped] [Display(Name="Full Name")] public string FullName { get { return Name + " " + Lastname; } } public string ProfilePicUrl { get; set; } [ForeignKey("MentorId")] public virtual ApplicationUser Mentor { get; set; } public virtual List<MentorReport> MentorReports { get; set; } public string MentorId { get; set; } [Display(Name="Skype Name")] public string SkypeName { get; set; } public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager) { // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); // Add custom user claims here return userIdentity; } } public class ApplicationDbContext : IdentityDbContext<ApplicationUser> { public ApplicationDbContext() : base("DefaultConnection", throwIfV1Schema: false) { } public static ApplicationDbContext Create() { return new ApplicationDbContext(); } public System.Data.Entity.DbSet<BitClassroom.DAL.Models.Course> Courses { get; set; } public System.Data.Entity.DbSet<BitClassroom.DAL.Models.CoursesTeach> CoursesTeaches { get; set; } public System.Data.Entity.DbSet<BitClassroom.DAL.Models.CoursesTaken> CoursesTakens { get; set; } public System.Data.Entity.DbSet<BitClassroom.DAL.Models.Announcement> Announcements { get; set; } public System.Data.Entity.DbSet<BitClassroom.DAL.Models.Assignment> Assignments { get; set; } public System.Data.Entity.DbSet<BitClassroom.DAL.Models.StudentsAssignment> StudentsAssignments { get; set; } public System.Data.Entity.DbSet<BitClassroom.DAL.Models.QuestionResponse> QuestionResponses { get; set; } public System.Data.Entity.DbSet<BitClassroom.DAL.Models.Question> Questions { get; set; } public System.Data.Entity.DbSet<BitClassroom.DAL.Models.Survey> Surveys { get; set; } public System.Data.Entity.DbSet<BitClassroom.DAL.Models.SurveyQuestion> SurveyQuestions { get; set; } public System.Data.Entity.DbSet<BitClassroom.DAL.Models.IndividualAssignment> IndividualAssignments { get; set; } public System.Data.Entity.DbSet<BitClassroom.DAL.Models.Notification> Notifications { get; set; } public System.Data.Entity.DbSet<BitClassroom.DAL.Models.MentorReport> MentorReports { get; set; } public System.Data.Entity.DbSet<BitClassroom.DAL.Models.Comment> Comments { get; set; } public System.Data.Entity.DbSet<BitClassroom.DAL.Models.CourseRequest> CourseRequests { get; set; } public System.Data.Entity.DbSet<BitClassroom.DAL.Models.WatchListItem> WatchListItems { get; set; } public System.Data.Entity.DbSet<BitClassroom.DAL.Models.TeacherUpload> TeacherUploads { get; set; } public System.Data.Entity.DbSet<BitClassroom.DAL.Models.StudentUpload> StudentUploads { get; set; } public System.Data.Entity.DbSet<BitClassroom.DAL.Models.DailyQuestion> DailyQuestions { get; set; } public System.Data.Entity.DbSet<BitClassroom.DAL.Models.DailyReport> DailyReports { get; set; } public System.Data.Entity.DbSet<BitClassroom.DAL.Models.DailyQuestionResponse> DailyQuestionResponses { get; set; } public System.Data.Entity.DbSet<BitClassroom.DAL.Models.MentorUpload> MentorUploads { get; set; } public System.Data.Entity.DbSet<BitClassroom.DAL.Models.IndividualAssignmentStudentUpload> IndividualAssignmentStudentUploads { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Model.Trade { public class E_Trade:E_BaseModel { /// <summary> /// 记录ID /// </summary> public int id { get; set; } /// <summary> /// 序号 /// </summary> public int rid { get; set; } /// <summary> /// 菜槽编号 /// </summary> public string devno { get; set; } /// <summary> /// 菜品编号 /// </summary> public string dishid { get; set; } /// <summary> /// 员工唯一码 /// </summary> public string emplid { get; set; } /// <summary> /// rfid 芯片 uid 号 /// </summary> public string rfid_uid { get; set; } /// <summary> /// 本次建议取用量(单位:g) /// </summary> public int suggest_takeqty { get; set; } /// <summary> /// 本次实际取用量(单位:g) /// </summary> public int takeqty { get; set; } /// <summary> /// 取菜时间,精确到秒 /// </summary> public DateTime taketime { get; set; } /// <summary> /// 取餐记录唯一标识 /// </summary> public string token { get; set; } /// <summary> /// 菜品名称 /// </summary> public string dishname { get; set; } /// <summary> /// 班组ID /// </summary> public int classid { get; set; } /// <summary> /// 班组名称 /// </summary> public string classname { get; set; } /// <summary> /// 员工姓名 /// </summary> public string uname { get; set; } /// <summary> /// 作业区ID /// </summary> public int operationid { get; set; } /// <summary> /// 热量 /// </summary> public double rl { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; using UnityEngine.UI; using TMPro; using DG.Tweening; using Roguelord; namespace Roguelord { public class CardController: MonoBehaviour { private UnityAction<EventParam> cardEventHandler; private List<GameObject> dealerCards; public List<CardStoreVO> inHand = new List<CardStoreVO>(); public List<CardStoreVO> drawPile = new List<CardStoreVO>(); public List<CardStoreVO> discardPile = new List<CardStoreVO>(); public List<CardStoreVO> exhaustPile = new List<CardStoreVO>(); public List<CardStoreVO> deck = new List<CardStoreVO>(); private GameObject drawPileA; private GameObject discardPileA; private GameObject drawPileD; private GameObject discardPileD; // List<CardStoreVO> drawPileD = new List<CardStoreVO>(); // List<CardStoreVO> discardPileD = new List<CardStoreVO>(); // List<CardStoreVO> exhaustPileD = new List<CardStoreVO>(); private List<GameObject> pool = new List<GameObject>(); private int poolTotal = 10; public GameObject defendStack; public GameObject attackStack; private Vector3 originalPosition, originalScale; private Quaternion originalRotation; public AnimationCurve moveCurve = AnimationCurve.Linear(0.0f, 0.0f, 1.0f, 1.0f); void Awake() { } void Start() { GameManager.instance.cardController = this;//cardController defendStack = GameObject.FindWithTag("DefendStack"); attackStack = GameObject.FindWithTag("AttackStack"); drawPileA = GameObject.FindWithTag("DrawPileA"); discardPileA = GameObject.FindWithTag("DiscardPileA"); drawPileD = GameObject.FindWithTag("DrawPileD"); discardPileD = GameObject.FindWithTag("DiscardPileD"); cardEventHandler = new UnityAction<EventParam>(cardEventHandlerFunction); EventManager.StartListening("cardEvent", cardEventHandler); InitPool(); GetStarterDeck(); // Deal Cards // EventParam eventParam = new EventParam(); // eventParam.name = "dealCards"; // EventManager.TriggerEvent("cardEvent", eventParam); } public void InitPool() { GameObject card; for (int i = 0; i < poolTotal; i++) { card = Instantiate(GameManager.instance.assetBundleCards.LoadAsset<GameObject>("CardPanel Variant")) as GameObject; if (i == 0) { originalPosition = card.transform.position; originalRotation = card.transform.rotation; originalScale = card.transform.localScale; } card.SetActive(false); pool.Add(card); } } public GameObject GetNewCard() { foreach (GameObject card in pool) { if (card.activeInHierarchy == false) { card.SetActive(true); card.transform.position = originalPosition; card.transform.rotation = originalRotation; card.transform.localScale = originalScale; return card; } } return null; } void cardEventHandlerFunction(EventParam eventParam) { Debug.Log("<color=red>== CardController.cardEventHandlerFunction ==</color>"); Debug.Log("== " + eventParam.name); // if (stackType != eventParam.owner) return; switch (eventParam.name) { // case "mouseEnter": // if (eventParam.card.model.state == CardVO.CardState.InHand) // FanStack(eventParam.card.cardIndex); // break; // case "mouseExit": // if (eventParam.card.model.state == CardVO.CardState.InHand) // ResetStack(); // break; case "updatePileCounts": UpdatePileCounts(); break; case "dealerSelected": CardView cardView; CardStackController stack = null; CardVO.CardOwner owner = CardVO.CardOwner.Attacker; foreach (GameObject card in dealerCards) { cardView = card.GetComponent<CardView>(); if (cardView.model.state != CardVO.CardState.InHand) card.transform.SetParent(null);//SetParent(attackStack.transform); else { if (cardView.model.owner == CardVO.CardOwner.Attacker) { stack = attackStack.GetComponent<CardStackController>(); } else { owner = CardVO.CardOwner.Defender; stack = defendStack.GetComponent<CardStackController>(); } cardView.isLatest = true; stack.NewCardAdded(cardView); } // else card.transform.SetParent(defendStack.transform); } // add card store to hand inHand.Insert(0, new CardStoreVO(eventParam.card.model.uid, eventParam.card.model.level, true)); // deal hand // DrawPileToHand(stack, owner); break; case "stowedCardActivated": discardPile.Insert(0, new CardStoreVO(eventParam.card.model.uid, eventParam.card.model.level, false)); // UpdatePileCounts(); break; } } private void InHandToDiscardPile() { Debug.Log("<color=blue>### " + drawPile.Count + " / " + inHand.Count + " / " + discardPile.Count + "</color>"); CardStackController stack = attackStack.GetComponent<CardStackController>(); int inHandTotal = stack.GetCardsInHand().Count; // add inHand to dicard pile foreach(CardView card in stack.GetCardsInHand()) { discardPile.Insert(0, new CardStoreVO(card.model.uid, card.model.level)); StartCoroutine(card.Discard()); } // remove from inHand inHand.RemoveRange(0, inHandTotal); Debug.Log("<color=blue>### " + drawPile.Count + " / " + inHand.Count + " / " + discardPile.Count + "</color>"); } private void DrawPileToHand(CardStackController toStack, CardVO.CardOwner owner) { Debug.Log("<color=orange>== CardController.DrawPileToHand ==</color>"); Debug.Log("* " + toStack + " / " + owner); // if not enough cards in draw pile... if (drawPile.Count < 5) { // cull *all* cards from discard foreach(CardStoreVO discard in discardPile) { drawPile.Add(discard); } // remove all from discard discardPile.Clear(); } UpdatePileCounts(); // take top-most 4 (or more) cards (not including dealer card which is already added) List<CardStoreVO> draw = drawPile.GetRange(0, 4); inHand.AddRange(draw); drawPile.RemoveRange(0, 4); List<CardVO> displayCards = new List<CardVO>(); CardVO card = null; foreach(CardStoreVO store in inHand) { Debug.Log(store.uid + " / " + store.level.ToString()); // don't include dealer cards (already in stack) if (store.isDealer == false) { card = CardLibraryVO.GetCardByStore(store); card.owner = owner; displayCards.Add(card); } } Debug.Log("done!"); List<CardView> cardViews = new List<CardView>(); // CardView cardView2; foreach(CardVO vo in displayCards) { // CardView cardView2 = CardVOToView(vo, owner); cardViews.Add(CardVOToView(vo, owner)); } // toStack.NewCardAdded(cardView); Vector3 drawPilePos;// = drawPileA.transform.position; // GameObject prefab; // Vector3 container; // Vector3 screenPos = new Vector3(); foreach (CardView view in cardViews) { Debug.Log("# dealer card " + view.transform.position.x); // cardView = go.GetComponent<CardView>(); view.model.state = CardVO.CardState.InHand; if (view.model.owner == CardVO.CardOwner.Attacker) { view.gameObject.transform.SetParent(attackStack.transform); drawPilePos = drawPileA.transform.GetChild(0).transform.position; // drawPilePos.x -= (view.rt.rect.width / 2); drawPilePos.y += 25;//(view.rt.rect.height / 2); view.gameObject.transform.localScale = new Vector3(0.35f, 0.35f, 0.35f); // Vector3 temp = view.gameObject.transform.rotation.eulerAngles; // temp.x = -45.0f; // view.gameObject.transform.rotation = Quaternion.Euler(temp); } else { view.gameObject.transform.SetParent(defendStack.transform); drawPilePos = drawPileD.transform.position; } view.gameObject.transform.position = drawPilePos; view.gameObject.SetActive(true); view.model.state = CardVO.CardState.DrawPile; toStack.MoveCardToStack(view); // toStack.NewCardAdded(view); } UpdatePileCounts(); } private CardView CardVOToView(CardVO vo, CardVO.CardOwner owner) { GameObject go = GetNewCard(); vo.owner = owner; CardView view = go.GetComponent<CardView>(); view.model = vo; return view; } public void GetStarterDeck() { CardVO card; CardStoreVO store; for(var i = 0; i < 9; i++) { store = null; if (i < 4) { card = CardLibraryVO.getChargedUpCard(); store = new CardStoreVO(card.uid, 1); } else if (i < 8) { card = CardLibraryVO.getEvasiveManeuversCard(); store = new CardStoreVO(card.uid, 1); } else { // random card = CardLibraryVO.getExposedCard(); store = new CardStoreVO(card.uid, 1); } if (store != null) { deck.Add(store); drawPile.Add(store); } } Debug.Log("deck len " + deck.Count); UpdatePileCounts(); ShufflePile(drawPile); DrawPileToHand(attackStack.GetComponent<CardStackController>(), CardVO.CardOwner.Attacker); } private void ShufflePile(List<CardStoreVO> pile) { pile = ListHelper.ShuffleCardStoreList(pile); Debug.Log("* shuffled"); } private void UpdatePileCounts() { drawPileA.transform.GetChild(0).GetComponent<TextMeshProUGUI>().text = drawPile.Count.ToString(); discardPileA.transform.GetChild(0).GetComponent<TextMeshProUGUI>().text = discardPile.Count.ToString(); } public IEnumerator DealCards(bool firstRun = false) { Debug.Log("<color=yellow>== CardController.dealCards ==</color>"); // if (turnCounter == null) // turnCounter = GameObject.FindWithTag("TurnCounter"); // if (firstRun == true) // { // yield return new WaitForSeconds(2f); // DrawPileToHand(attackStack.GetComponent<CardStackController>(), CardVO.CardOwner.Attacker); // yield return new WaitForSeconds(3f); // } // yield return new WaitForSeconds(1.5f); // hide turn counter UI // turnCounter.SetActive(false); // activate dealerCards // cardsUI.SetActive(true); dealerCards = new List<GameObject>(); GameObject card1 = GetNewCard(); GameObject card2 = GetNewCard(); GameObject card3 = GetNewCard(); // Instantiate(GameManager.instance.assetBundleCards.LoadAsset<GameObject>("CardPanel Variant")) as GameObject; // GameObject card2 = Instantiate(GameManager.instance.assetBundleCards.LoadAsset<GameObject>("CardPanel Variant")) as GameObject; // GameObject card3 = Instantiate(GameManager.instance.assetBundleCards.LoadAsset<GameObject>("CardPanel Variant")) as GameObject; dealerCards.Add(card1); dealerCards.Add(card2); dealerCards.Add(card3); // card data and owner CardVO card1data = CardLibraryVO.getChargedUpCard(); card1data.owner = CardVO.CardOwner.Attacker; CardVO card2data = CardLibraryVO.getEvasiveManeuversCard(); card2data.owner = CardVO.CardOwner.Attacker; CardVO card3data = CardLibraryVO.getExposedCard(); card3data.owner = CardVO.CardOwner.Attacker; // card states CardView c = card1.GetComponent<CardView>(); Debug.Log("* c " + c); card1.GetComponent<CardView>().model = card1data; card2.GetComponent<CardView>().model = card2data; card3.GetComponent<CardView>().model = card3data; // card1.GetComponent<CardView>().model.owner = CardVO.CardOwner.Attacker; // card2.GetComponent<CardView>().model.owner = CardVO.CardOwner.Attacker; // card3.GetComponent<CardView>().model.owner = CardVO.CardOwner.Attacker; // test defender stack /*GameObject card4 = GetNewCard();// Instantiate(GameManager.instance.assetBundleCards.LoadAsset<GameObject>("CardPanel Variant")) as GameObject; CardVO card4data = CardLibraryVO.getChargedUpCard(); card4data.owner = CardVO.CardOwner.Defender; // card4.GetComponent<CardView>().model.state = CardVO.CardState.Dealer; card4.GetComponent<CardView>().model = card4data; dealerCards.Add(card4);*/ // CardSODisplay cod = card1.GetComponent<CardSODisplay>(); // cod.card = GameManager.instance.assetBundleCards.LoadAsset<GameObject>("test1").GetComponent<CardSO>(); // CardSO zcard = Object.Instantiate(GameManager.instance.assetBundleCards.LoadAsset<GameObject>("test1")); // ScriptableObject card2 = ScriptableObject.CreateInstance<CardSO>(); // ScriptableObject card3 = ScriptableObject.CreateInstance<CardSO>(); // Transform stackTransform; CardView cardView; foreach (GameObject card in dealerCards) { Debug.Log("* dealer card " + attackStack); cardView = card.GetComponent<CardView>(); if (cardView.model.owner == CardVO.CardOwner.Attacker) card.transform.SetParent(attackStack.transform); else card.transform.SetParent(defendStack.transform); } // if (card1.GetComponent<CardView>().model.owner == CardVO.CardOwner.Defender) // stackTransform = defendStack.transform; // else stackTransform = attackStack.transform; // card1.transform.SetParent(stackTransform); // card2.transform.SetParent(stackTransform); // card3.transform.SetParent(stackTransform); //* // AddCards(card1, card2, card3); // card size RectTransform rt = (RectTransform)card1.transform; float attackCenter = ((Screen.width / 2) / 2) - (rt.rect.width / 2); float defendCenter = Screen.width - ((Screen.width / 3) / 2) - (rt.rect.width / 2); Vector3 screenCenter = new Vector3(Screen.width / 2, Screen.height / 2, 0); Vector3 pointA = card1.transform.position; // float baseZ = transform.forward + 1; pointA.x += 1.5f; // Vector3 pointB = new Vector3(2 + 0.75f, 3f, 0f); Vector3 x = defendStack.transform.position; Vector3 cam = Camera.main.transform.position; Vector3 middle = screenCenter;// Vector3(Screen.width / 2, Screen.height / 2, 0);//cam.z); middle.y += (rt.rect.height / 2) + (card1.GetComponent<CardView>().rt.rect.height / 3); Vector3 left = screenCenter; left.x -= rt.rect.width + 10; left.y += (rt.rect.height / 2) + (card1.GetComponent<CardView>().rt.rect.height / 3); Vector3 right = screenCenter; right.x += rt.rect.width + 10; right.y += (rt.rect.height / 2) + (card1.GetComponent<CardView>().rt.rect.height / 3); // time float seconds = 0.15f; yield return StartCoroutine(MoveObject(card1.transform, pointA, middle, seconds)); // yield return new WaitForSeconds(0.15f); pointA = card2.transform.position; pointA.x += 1.5f; Vector3 pointC = new Vector3(0, 3f, -5f);//pointA.z); yield return StartCoroutine(MoveObject(card2.transform, pointA, left, seconds)); // yield return new WaitForSeconds(0.15f); pointA = card3.transform.position; pointA.x += 1.5f; Vector3 pointD = new Vector3(0 - 0.75f, 3f, -5);//pointA.z); yield return StartCoroutine(MoveObject(card3.transform, pointA, right, seconds)); //*/ // deal new hands to stacks // attackStack.GetComponent<CardStackController>().DealHand(inHand); // if (firstRun == false) // RoundComplete(); // DrawPileToHand(attackStack.GetComponent<CardStackController>(), CardVO.CardOwner.Attacker); // DrawPileToHand(defendStack.GetComponent<CardStackController>(), CardVO.CardOwner.Defender); yield return null; } public IEnumerator RoundComplete() { Debug.Log("<color=lightblue>CardController.RoundComplete</color>"); // move inhand to discard pile InHandToDiscardPile(); yield return new WaitForSeconds(2.0f); // if draw pile empty, replenish // move 5 (+ additional) from draw pile to inhand DrawPileToHand(attackStack.GetComponent<CardStackController>(), CardVO.CardOwner.Attacker); yield return null; } public IEnumerator CardActionOnPlayer(CardView card, CharacterView character) { Debug.Log("<color=lightblue>CardController.CardActionOnPlayer</color>"); // TODO fix this! state update logic handled by action card.model.state = CardVO.CardState.DiscardPile; // get positions/sizes Vector3 characterPos = Camera.main.WorldToScreenPoint(character.prefab.transform.position); Vector3 characterSize = Camera.main.WorldToScreenPoint(character.prefab.GetComponent<BoxCollider>().bounds.size); RectTransform cardRect = (RectTransform)card.transform; // move card over character Vector3 toPos = characterPos; toPos.y += (cardRect.rect.height / 2) + (characterSize.y / 2); card.MoveObject(toPos, 0f, 0.35f); yield return new WaitForSeconds(0.75f); StartCoroutine(CardAction2(card, character)); yield return new WaitForSeconds(0.75f); // update character (apply card action by level) character.model.AssignedCard(card.model, card.model.levelData[card.model.level - 1]); // discard (or exhaust?) StartCoroutine(card.Discard()); } private IEnumerator CardAction2(CardView card, CharacterView character = null) { Debug.Log("<color=yellow>== CardController.CardAction2 ==</color>"); // get level data CardLevelDataVO leveldata = card.model.levelData[card.model.level - 1]; // get action type 2 switch (leveldata.actionType2) { /* ADD RANDOM */ case CardLevelDataVO.CardActionType.AddRandom: CardStackController stack = attackStack.GetComponent<CardStackController>(); if (card.model.owner == CardVO.CardOwner.Defender) stack = defendStack.GetComponent<CardStackController>(); // get number of draw cards int toDraw = leveldata.value2; Debug.Log("* drawing " + toDraw + " cards..."); // slide card(s) out from behind card // GameObject newcard; // CardView newcardview; // CardVO carddata; List<CardView> holding = new List<CardView>(); for (var i = 0; i < toDraw; i++) { // get (random?) card CardVO carddata = CardLibraryVO.getExposedCard(); // set owner carddata.owner = CardVO.CardOwner.Attacker; // get new card from pool GameObject newcard = GetNewCard(); // add to stack newcard.transform.SetParent(stack.transform); CardView newcardview = newcard.GetComponent<CardView>(); holding.Add(newcardview); // assign data to card newcardview.model = carddata;//CardLibraryVO.getExposedCard(); // move it Vector3 tran = new Vector3(card.transform.position.x, card.transform.position.y, card.transform.position.x); newcardview.transform.position = tran;//new Vector3(tran.x + card.rt.rect.width + 10, tran.y, tran.z); newcardview.MoveObject(new Vector3(tran.x + (card.rt.rect.width * (i + 1) + 10), tran.y, tran.z), 0, 0.25f); // yield return new WaitForSeconds(1f); } yield return new WaitForSeconds((float)toDraw); foreach(CardView cview in holding) { // add to inHand cview.model.state = CardVO.CardState.InHand; stack.NewCardAdded(cview); // pause yield return new WaitForSeconds(1f); } break; } yield return null; } IEnumerator MoveObject(Transform thisTransform, Vector3 startPos, Vector3 endPos, float time) { Debug.Log("== MoveObject =="); // AnimationCurve curve = AnimationCurve.Linear(0.0f, 0.0f, 1.0f, 1.0f); thisTransform.DOMove(endPos, time) .ChangeStartValue(startPos) .SetEase(moveCurve); yield return null; } } }
using UnityEngine; using static CellBehaviorTable; public class EntityPlate : EntityBase { [SerializeField] private SpriteRenderer plateSpriteRenderer = null; [SerializeField] private Sprite spriteFullPlate = null; [SerializeField] private Sprite spriteDirtyPlate = null; public void updateSprite(EnumPlateState state) { Sprite s = null; switch(state) { case EnumPlateState.NONE: s = null; break; case EnumPlateState.DIRTY: s = this.spriteDirtyPlate; break; case EnumPlateState.FULL: s = this.spriteFullPlate; break; } this.plateSpriteRenderer.sprite = s; } }
using PayByPhoneTwitter.Models; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Web; using System.Web.Script.Serialization; namespace PayByPhoneTwitter { public class TwitterJSonParser { public const string DateTimeFormat = "ddd MMM dd H:mm:ss zzz yyyy"; public virtual List<Tweet> ParseTweetsFromJSon(string json) { var serializer = new JavaScriptSerializer(); serializer.RegisterConverters(new[] { new DynamicJsonConverter() }); dynamic tweetJson = serializer.Deserialize(json, typeof(object)); List<Tweet> tweets = new List<Tweet>(); foreach (dynamic obj in tweetJson) { Tweet t = new Tweet() { Id = Convert.ToInt64(obj.id), Account = obj.user.screen_name, Posted = ParseJsonDate(obj.created_at), Text = obj.text, UserMentions = obj.entities.user_mentions.Count }; tweets.Add(t); } return tweets; } public DateTime ParseJsonDate(string s) { return DateTime.ParseExact(s, DateTimeFormat, CultureInfo.InvariantCulture).ToLocalTime(); } } }
namespace DesignPatterns.Decorator.Example1 { /// <summary> /// Concrete Components provide default implementations of the operations. /// There might be several variations of these classes. /// </summary> public class ConcreteComponent : Component { public override string Operation() { return "ConcreteComponent"; } } }
using System; namespace Bachelor_Party { class Program { static void Main(string[] args) { double sumForPerformer = double.Parse(Console.ReadLine()); string command = Console.ReadLine(); double sumOfMoney = 0; int numberOfGuests = 0; while (command != "The restaurant is full") { int groupOfPeople = int.Parse(command); numberOfGuests = numberOfGuests + groupOfPeople; if (groupOfPeople >= 5) { sumOfMoney = sumOfMoney + groupOfPeople * 70; } else { sumOfMoney = sumOfMoney + groupOfPeople * 100; } command = Console.ReadLine(); } if (sumOfMoney >= sumForPerformer) { Console.WriteLine($"You have {numberOfGuests} guests and {(sumOfMoney - sumForPerformer)} leva left."); } else { Console.WriteLine($"You have {numberOfGuests} guests and {sumOfMoney} leva income, but no singer."); } } } }
using UnityEngine; using UnityEngine.Events; public class Lever : Interactable { public bool toggle; public UnityEvent onEnable; public UnityEvent onDisable; public bool isOn = false; private TimeEntity te; private void Start() { te = GetComponent<TimeEntity>(); } private void Update() { if (TimeController.instance.playbackMode) { if (te != null) { isOn = bool.Parse(te.metadata); } } else { if (te != null) { te.metadata = isOn.ToString(); } } GetComponent<Animator>().SetBool("Flipped", isOn); } public override void E() { Debug.Log("E"); if (toggle) { isOn = !isOn; GetComponent<AudioSource>().Play(); if (isOn) { onEnable.Invoke(); } if (!isOn) { onDisable.Invoke(); } } else { if (!isOn) { isOn = true; GetComponent<AudioSource>().Play(); onEnable.Invoke(); } } } public void Switch(bool state) { isOn = state; if (isOn) { onEnable.Invoke(); } if (!isOn) { onDisable.Invoke(); } } }
using System; using System.Collections.Generic; using System.IO; using System.IO.Ports; using System.Text; using System.Windows.Forms; namespace ZebraTestPrint { public partial class Form1 : Form { private int refreshing = 0; public Form1() { InitializeComponent(); this.RefreshData(); } private void RefreshData() { if (this.refreshing <= 0) { this.refreshing += 1; try { // initialize the combobox cboPrinterName.Items.Clear(); foreach (string printer in System.Drawing.Printing.PrinterSettings.InstalledPrinters) { cboPrinterName.Items.Add(printer); } // initialize the combobox cboPorts.Items.Clear(); foreach (string port in SerialPort.GetPortNames()) { cboPorts.Items.Add(port); } } finally { this.refreshing -= 1; } } } private void btnTestPrint_Click(object sender, EventArgs e) { if (this.refreshing <= 0) { this.refreshing += 1; try { if (!(cboPrinterName.SelectedItem is string)) { MessageBox.Show("Please select a printer", "Invalid Option"); return; } string printerName = (string)cboPrinterName.SelectedItem; if (string.IsNullOrEmpty(printerName)) { MessageBox.Show("Please select a printer", "Invalid Option"); return; } string data = GetTestPrintFormat(); //PrintHelper.SendStringToPrinter(printerName, data); //PlainTextPrinter p = new PlainTextPrinter(); //p.Print(data, printerName); byte[] b = Encoding.ASCII.GetBytes(data); RawPrinter.Print(b, printerName); } catch (Exception ex) { MessageBox.Show(ex.Message, "Test Print Error"); } finally { this.refreshing -= 1; } } } private string GetTestPrintFormat() { string s = @"! 15 203 203 1500 1 LABEL TONE 0 CENTER T 5 1 0 245 TICKET INFORMATION IL 0 235 550 235 55 LEFT T 5 2 0 295 Ticket #: 17X00001 T 7 0 0 345 Date: 01/30/2017 T 7 0 300 345 Time: 17:55 T 7 0 0 370 Location:[ N DWIGHT PARK DRIVE T 7 0 0 395 Block: 100 T 7 0 300 395 Meter: M12345 CENTER T 5 1 0 430 VEHICLE INFORMATION IL 0 420 550 420 55 LEFT T 7 0 0 480 Plate: ABC1234 NY T 7 0 0 505 Reg Exp: 12/20 T 7 0 300 505 VIN4: 1234 T 7 0 0 530 Permit: P123456 T 7 0 0 555 Vehicle: 2017 FORD TAURUS T 7 0 0 580 Color: WHITE T 7 0 300 580 Body: 4DRSD T 7 0 0 605 Plate Type: PAS CENTER T 5 1 0 640 VIOLATION INFORMATION IL 0 630 550 630 55 LEFT T 7 0 0 690 Chalk Time: 01/30/2017 15:33 T 7 0 0 715 Elapsed Time: 15m T 7 0 0 740 Stem 1 Pos.: 12 T 7 0 300 740 Stem 2 Pos.: 6 T 7 0 0 765 Violation: 001 Amount: $25.00 T 7 0 0 790 METER VIOLATION T 7 0 0 815 Violation #2: 002 Amount: $10.00 T 7 0 0 840 OVERTIME PARKING T 7 0 0 865 Violation #3: 003 Amount: $20.00 T 7 0 0 890 FAILURE TO DISPLAY CENTER T 5 1 0 925 PAYMENT INFORMATION IL 0 915 550 915 55 LEFT T 5 2 0 975 Total Amount: $55.00 LINE 0 1075 430 1075 3 T 7 0 0 1100 NEXT VIOLATION WILL BE TOW CENTER B 39 1 2 50 0 1175 17X00001 LEFT T 7 0 20 1380 Officer: 100 FORM PRINT"; return s; } private string[] GetTestPrintArry() { List<string> lines = new List<string>(); lines.Add("!15 203 203 1500 1"); lines.Add("LABEL"); lines.Add("TONE 0"); lines.Add("CENTER"); lines.Add("T 5 1 0 245 TICKET INFORMATION"); lines.Add("IL 0 235 550 235 55"); lines.Add("LEFT"); lines.Add("T 5 2 0 295 Ticket #: 17X00001"); lines.Add("T 7 0 0 345 Date: 01/30/2017"); lines.Add("T 7 0 300 345 Time: 17:55"); lines.Add("T 7 0 0 370 Location:[ N DWIGHT PARK DRIVE"); lines.Add("T 7 0 0 395 Block: 100"); lines.Add("T 7 0 300 395 Meter: M12345"); lines.Add("CENTER"); lines.Add("T 5 1 0 430 VEHICLE INFORMATION"); lines.Add("IL 0 420 550 420 55"); lines.Add("LEFT"); lines.Add("T 7 0 0 480 Plate: ABC1234 NY"); lines.Add("T 7 0 0 505 Reg Exp: 12/20"); lines.Add("T 7 0 300 505 VIN4: 1234"); lines.Add("T 7 0 0 530 Permit: P123456"); lines.Add("T 7 0 0 555 Vehicle: 2017 FORD TAURUS"); lines.Add("T 7 0 0 580 Color: WHITE"); lines.Add("T 7 0 300 580 Body: 4DRSD"); lines.Add("T 7 0 0 605 Plate Type: PAS"); lines.Add("CENTER"); lines.Add("T 5 1 0 640 VIOLATION INFORMATION"); lines.Add("IL 0 630 550 630 55"); lines.Add("LEFT"); lines.Add("T 7 0 0 690 Chalk Time: 01/30/2017 15:33"); lines.Add("T 7 0 0 715 Elapsed Time: 15m"); lines.Add("T 7 0 0 740 Stem 1 Pos.: 12"); lines.Add("T 7 0 300 740 Stem 2 Pos.: 6"); lines.Add("T 7 0 0 765 Violation: 001 Amount: $25.00"); lines.Add("T 7 0 0 790 METER VIOLATION"); lines.Add("T 7 0 0 815 Violation #2: 002 Amount: $10.00"); lines.Add("T 7 0 0 840 OVERTIME PARKING"); lines.Add("T 7 0 0 865 Violation #3: 003 Amount: $20.00"); lines.Add("T 7 0 0 890 FAILURE TO DISPLAY"); lines.Add("CENTER"); lines.Add("T 5 1 0 925 PAYMENT INFORMATION"); lines.Add("IL 0 915 550 915 55"); lines.Add("LEFT"); lines.Add("T 5 2 0 975 Total Amount: $55.00"); lines.Add("LINE 0 1075 430 1075 3"); lines.Add("T 7 0 0 1100 NEXT VIOLATION WILL BE TOW"); lines.Add("CENTER"); lines.Add("B 39 1 2 50 0 1175 17X00001"); lines.Add("LEFT"); lines.Add("T 7 0 20 1380 Officer: 100"); lines.Add("FORM"); lines.Add("PRINT"); return lines.ToArray(); } private string[] GetTestZPL() { List<string> lines = new List<string>(); lines.Add("^XA^FWN^MD30"); lines.Add("^FO0100,0040^A0,N,100,30^FD TEMPORARY ^FS"); lines.Add("^FO0020,0140^A0,N,100,30^FD PARKING PERMIT ^FS"); lines.Add("^XZ"); return lines.ToArray(); } private void btnCOMTest_Click(object sender, EventArgs e) { if (this.refreshing <= 0) { this.refreshing += 1; try { if (!(cboPorts.SelectedItem is string)) { MessageBox.Show("Please select a port", "Invalid COM Option"); return; } string portName = (string)cboPorts.SelectedItem; if (string.IsNullOrEmpty(portName)) { MessageBox.Show("Please select a port", "Invalid COM Option"); return; } string[] lines; if (rbCPCL.Checked) { lines = GetTestPrintArry(); } else { lines = GetTestZPL(); } Console.Write("Opening COM Port... " + portName); COMPrintHelper com = new COMPrintHelper(portName, 9600); Console.WriteLine("... Open!"); try { com.Open(); if (com.IsOpen) { foreach (string line in lines) { Console.Write("Sending data... " + line); com.Print(line); Console.WriteLine("... Sent!"); } } else { throw new ApplicationException("Cannot write to a closed COM port"); } } catch (Exception printEx) { Console.WriteLine("Error: " + printEx.Message); MessageBox.Show(printEx.Message, "COM Print Error"); } finally { com.Close(); } } catch (Exception ex) { MessageBox.Show(ex.Message, "Test Print Error"); } finally { this.refreshing -= 1; } } } } }
using DataStructure.Abstractions; using System.Collections.Generic; using System.Text; namespace DataStructure.Models { public class Favourite : BaseModel { public List<Style> Styles { get; set; } public List<Performer> Performers { get; set; } public User User { get; set; } } }
 using Unity.Entities; using Unity.Mathematics; using static Unity.Mathematics.math; using Unity.Collections; namespace IzBone.PhysCloth.Core { using Common.Entities8; /** BodyAuthのデータをもとに、Entityを生成するモジュール */ public sealed class EntityRegisterer : EntityRegistererBase<Authoring.BaseAuthoring> { // ------------------------------------- public メンバ ---------------------------------------- public EntityRegisterer() : base(128) {} // --------------------------------- private / protected メンバ ------------------------------- /** Auth1つ分の変換処理 */ override protected void convertOne( Authoring.BaseAuthoring auth, RegLink regLink, EntityManager em ) { // ParticleのEntity一覧をまず作成 var ptclEntities = new NativeArray<Entity>( auth._particles.Length, Allocator.Temp ); for (int i=0; i<auth._particles.Length; ++i) { var entity = em.CreateEntity(); ptclEntities[i] = entity; } // ParticleのEntityの中身を作成 for (int i=0; i<auth._particles.Length; ++i) { var mp = auth._particles[i]; var entity = ptclEntities[i]; // コンポーネントを割り当て em.AddComponentData(entity, new Ptcl()); var nextEnt = i==ptclEntities.Length-1 ? Entity.Null : ptclEntities[i+1]; em.AddComponentData(entity, new Ptcl_Next{value = nextEnt}); var parentEnt = mp.parent==null ? Entity.Null : ptclEntities[mp.parent.idx]; em.AddComponentData(entity, new Ptcl_Parent{value = parentEnt}); em.AddComponentData(entity, new Ptcl_Root{value = ptclEntities[0]}); em.AddComponentData(entity, new Ptcl_DefaultHeadL2W()); em.AddComponentData(entity, new Ptcl_DefaultHeadL2P(mp.transHead)); em.AddComponentData(entity, new Ptcl_DefaultTailLPos{value = mp.defaultTailLPos}); em.AddComponentData(entity, new Ptcl_DefaultTailWPos()); em.AddComponentData(entity, new Ptcl_ToChildWDist()); em.AddComponentData(entity, new Ptcl_CurHeadTrans()); em.AddComponentData(entity, new Ptcl_WPos{value = mp.getTailWPos()}); em.AddComponentData(entity, new Ptcl_InvM(mp.m)); em.AddComponentData(entity, new Ptcl_R{value = mp.radius}); em.AddComponentData(entity, new Ptcl_Velo()); em.AddComponentData(entity, new Ptcl_DWRot()); em.AddComponentData(entity, new Ptcl_MaxAngle{value = radians(mp.maxAngle)}); em.AddComponentData(entity, new Ptcl_AngleCompliance{value = mp.angleCompliance}); em.AddComponentData(entity, new Ptcl_RestoreHL{value = mp.restoreHL}); em.AddComponentData(entity, new Ptcl_MaxMovableRange{value = mp.maxMovableRange}); em.AddComponentData(entity, new Ptcl_CldCstLmd()); em.AddComponentData(entity, new Ptcl_AglLmtLmd()); em.AddComponentData(entity, new Ptcl_MvblRngLmd()); em.AddComponentData(entity, new Ptcl_M2D{auth = mp}); // Entity・Transformを登録 addEntityCore(entity, regLink); var transHead = mp.transHead == null ? mp.transTail[0].parent : mp.transHead; addETPCore(entity, transHead, regLink); } // ConstraintのEntityを作成 for (int i=0; i<auth._constraints.Length; ++i) { var mc = auth._constraints[i]; // ここで生成しておかないと、パラメータの再設定ができなくなるので、 // Editor中は常に生成しておく #if !UNITY_EDITOR // 強度があまりにも弱い場合は拘束条件を追加しない if (Authoring.ComplianceAttribute.LEFT_VAL*0.98f < mc.compliance) continue; #endif Entity entity = Entity.Null; switch (mc.mode) { case Authoring.ConstraintMng.Mode.Distance: {// 距離拘束 // 対象パーティクルがどちらも固定されている場合は無効 var srcMP = auth._particles[mc.srcPtclIdx]; var dstMP = auth._particles[mc.dstPtclIdx]; if (srcMP.m < Ptcl_InvM.MinimumM && dstMP.m < Ptcl_InvM.MinimumM) break; // DefaultLenをHeadToTailの割合で計算する var defLen = mc.param.x / srcMP.headToTailWDist; // コンポーネントを割り当て entity = em.CreateEntity(); em.AddComponentData(entity, new DistCstr()); var srcEnt = ptclEntities[mc.srcPtclIdx]; var dstEnt = ptclEntities[mc.dstPtclIdx]; em.AddComponentData(entity, new Cstr_Target{src=srcEnt, dst=dstEnt}); em.AddComponentData(entity, new Cstr_Compliance{value = mc.compliance}); em.AddComponentData(entity, new Cstr_DefaultLen{value = defLen}); em.AddComponentData(entity, new Cstr_Lmd()); } break; case Authoring.ConstraintMng.Mode.MaxDistance: {// 最大距離拘束 // 未対応 // var b = new MaxDistance{ // compliance = i.compliance, // src = i.param.xyz, // tgt = pntsPtr + i.srcPtclIdx, // maxLen = i.param.w, // }; // if ( b.isValid() ) md.Add( b ); } break; case Authoring.ConstraintMng.Mode.Axis: {// 稼働軸拘束 // 未対応 // var b = new Axis{ // compliance = i.compliance, // src = pntsPtr + i.srcPtclIdx, // dst = pntsPtr + i.dstPtclIdx, // axis = i.param.xyz, // }; // if ( b.isValid() ) a.Add( b ); } break; default:throw new System.InvalidProgramException(); } if (entity == Entity.Null) continue; em.AddComponentData(entity, new Cstr_M2D{auth = mc}); // Entity・Transformを登録 addEntityCore(entity, regLink); } {// OneClothをECSへ変換 var rootEntity = ptclEntities[0]; em.AddComponentData(rootEntity, new Root()); em.AddComponentData(rootEntity, new Root_UseSimulation{value = auth.useSimulation}); em.AddComponentData(rootEntity, new Root_G{src = auth.g}); em.AddComponentData(rootEntity, new Root_Air()); em.AddComponentData(rootEntity, new Root_MaxSpd{value = auth.maxSpeed}); em.AddComponentData(rootEntity, new Root_WithAnimation{value = auth.withAnimation}); em.AddComponentData(rootEntity, new Root_ColliderPack()); em.AddComponentData(rootEntity, new Root_M2D{auth = auth}); auth._rootEntity = rootEntity; // ColliderPackを設定する処理。これは遅延して実行される可能性もある if (auth.Collider != null) { auth.Collider.getRootEntity( em, (em, cpEnt)=> em.SetComponentData( rootEntity, new Root_ColliderPack{value=cpEnt} ) ); } } ptclEntities.Dispose(); } /** 指定Entityの再変換処理 */ override protected void reconvertOne(Entity entity, EntityManager em) { if (em.HasComponent<Ptcl_M2D>(entity)) { var mp = em.GetComponentData<Ptcl_M2D>(entity).auth; em.SetComponentData(entity, new Ptcl_InvM(mp.m)); em.SetComponentData(entity, new Ptcl_R{value = mp.radius}); em.SetComponentData(entity, new Ptcl_MaxAngle{value = radians(mp.maxAngle)}); em.SetComponentData(entity, new Ptcl_AngleCompliance{value = mp.angleCompliance}); em.SetComponentData(entity, new Ptcl_RestoreHL{value = mp.restoreHL}); em.SetComponentData(entity, new Ptcl_MaxMovableRange{value = mp.maxMovableRange}); if (em.HasComponent<Root_M2D>(entity)) { var mr = em.GetComponentData<Root_M2D>(entity).auth; em.SetComponentData(entity, new Root_UseSimulation{value = mr.useSimulation}); em.AddComponentData(entity, new Root_G{src = mr.g}); // em.SetComponentData(entity, new Root_Air()); em.SetComponentData(entity, new Root_MaxSpd{value = mr.maxSpeed}); em.SetComponentData(entity, new Root_WithAnimation{value = mr.withAnimation}); } } else if (em.HasComponent<Cstr_M2D>(entity)) { var mc = em.GetComponentData<Cstr_M2D>(entity).auth; // とりあえず今は全部DistanceConstraintとして処理 em.SetComponentData(entity, new Cstr_Compliance{value = mc.compliance}); } } // -------------------------------------------------------------------------------------------- } }
/* Copyright (c) 2011-2012, HL7, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.Text.RegularExpressions; using Hl7.Fhir.Model; using System.Reflection; using Hl7.Fhir.Client; namespace Hl7.Fhir.Support { public class ResourceLocation { public const string BINARY_COLLECTION_NAME = "binary"; public static string GetCollectionNameForResource(Resource r) { if (r == null) return null; return GetCollectionNameForResource(r.GetType()); } public static string GetCollectionNameForResource(Type t) { #if NETFX_CORE if(typeof(Resource).GetTypeInfo().IsAssignableFrom(t.GetTypeInfo())) #else if (typeof(Resource).IsAssignableFrom(t)) #endif return ModelInfo.GetResourceNameForType(t).ToLower(); else throw new ArgumentException(String.Format("Cannot determine collection name, type {0} is " + "not a resource type", t.Name)); } //No, this is not Path.Combine. It's for Uri's public static string Combine(string path1, string path2) { if (String.IsNullOrEmpty(path1)) return path2; if (String.IsNullOrEmpty(path2)) return path1; return path1.TrimEnd('/') + "/" + path2.TrimStart('/'); } /// <summary> /// Determine whether the url in location is absolute (specifies protocol, hostname and path) /// </summary> /// <param name="location"></param> /// <returns></returns> public static bool IsAbsolute(string location) { return new Uri(location, UriKind.RelativeOrAbsolute).IsAbsoluteUri; } /// <summary> /// Determine whether location is absolute (specifies protocol, hostname and path) /// </summary> /// <param name="location"></param> /// <returns></returns> public static bool IsAbsolute(Uri location) { return location.IsAbsoluteUri; } private UriBuilder _location; /// <summary> /// Construct a ResourceLocation with all of its parts empty /// </summary> public ResourceLocation() { _location = new UriBuilder(); } /// <summary> /// Construct a new ResourceLocation with parts filled according to the specified location /// </summary> /// <param name="location">A string containing an absolute or relative url</param> /// <remarks> /// * This constructor will parse the location to not only find it usual Uri parts /// (host, path, query, etc), but also its Fhir-specific parts, like collection, service path, /// identifier, version and REST operation. /// * If the location is relative, http://localhost is assumed to be the protocol and host. /// </remarks> public ResourceLocation(string location) : this(new Uri(location, UriKind.RelativeOrAbsolute)) { } /// <summary> /// Construct a new ResourceLocation with parts filled according to the specified location /// </summary> /// <param name="location"></param> /// <seealso cref="ResourceLocation.#ctor(System.String)"/> public ResourceLocation(Uri location) { if (!location.IsAbsoluteUri) construct(new Uri(LOCALHOST, location)); else construct(location); } /// <summary> /// Construct a new ResourceLocation based on an absolute base path and a relative location. /// </summary> /// <param name="basePath"></param> /// <param name="location"></param> public ResourceLocation(string basePath, string location) : this(new Uri(basePath, UriKind.RelativeOrAbsolute), location) { } public ResourceLocation(Uri baseUri, string location) : this(baseUri, new Uri(location, UriKind.RelativeOrAbsolute)) { } /// <summary> /// Construct a ResourceLocation based on a baseUri and a relative path /// </summary> /// <param name="baseUri"></param> /// <param name="location"></param> /// <remarks> /// The relative path is appended after the baseUri, resolving any backtracks and path separators, /// so if the relative path starts with a '/', it will be appended right after the host part of /// the baseUri, even if the baseUri would have contained paths parts itself. /// /// If the relative path contains backtracks (..), these will all be resolved, by following the /// backtrack. The resulting ResourceLocation will not contain backtracks. /// </remarks> public ResourceLocation(Uri baseUri, Uri location) { if (!baseUri.IsAbsoluteUri) throw new ArgumentException("basePath must be an absolute Uri", "baseUri"); if (location.IsAbsoluteUri) throw new ArgumentException("location must be a relative Uri", "location"); // if location starts with "/", use the default Uri functionality // to concatenate the two, any path parts in basePath will be ignored, and // location will replace the path part, and start right after the hostname if (location.ToString().StartsWith("/")) construct(new Uri(baseUri, location)); // Otherwise, use the constructor to normalize the combined version. The // constructor will resolve ..-type path navigation and result in an // absolute path. construct(new Uri(Combine(baseUri.ToString(), location.ToString()), UriKind.Absolute)); } private static readonly Uri LOCALHOST = new Uri("http://localhost"); /// <summary> /// Build a ResourceLocation based on the name of a collection. /// </summary> /// <param name="collectionName"></param> /// <returns></returns> /// <remarks>ResourceLocations are always absolute, its host will be http://localhost</remarks> public static ResourceLocation Build(string collectionName) { return Build(LOCALHOST, collectionName); } /// <summary> /// Build a ResourceLocation based on an absolute endpoint and the name of a collection. /// </summary> /// <param name="baseUri"></param> /// <param name="collectionName"></param> /// <returns></returns> public static ResourceLocation Build(Uri baseUri, string collectionName) { if (!baseUri.IsAbsoluteUri) throw new ArgumentException("baseUri must be absolute", "baseUri"); if (String.IsNullOrEmpty(collectionName)) throw new ArgumentException("collection must not be empty", "collectionName"); return new ResourceLocation(baseUri, collectionName); } /// <summary> /// Build a ResourceLocation based on the name of a collection and a resource id /// </summary> /// <param name="baseUri"></param> /// <param name="collectionName"></param> /// <param name="id">The id, without '@'</param> /// <returns></returns> public static ResourceLocation Build(string collectionName, string id) { return Build(LOCALHOST, collectionName, id); } /// <summary> /// Build a ResourceLocation based on the endpoint, the name of a collection and a resource id /// </summary> /// <param name="baseUri"></param> /// <param name="collectionName"></param> /// <param name="id">The id, without '@'</param> /// <returns></returns> public static ResourceLocation Build(Uri baseUri, string collectionName, string id) { if (String.IsNullOrEmpty(id)) throw new ArgumentException("id must not be empty", "id"); var result = ResourceLocation.Build(baseUri, collectionName); result.Id = id; return result; } /// <summary> /// Build a new ResourceLocation based on the name of the collection, the id and version. /// </summary> /// <param name="collectionName"></param> /// <param name="id"></param> /// <param name="versionId"></param> /// <returns></returns> public static ResourceLocation Build(string collectionName, string id, string versionId) { return Build(LOCALHOST, collectionName, id, versionId); } /// <summary> /// Build a new ResourceLocation based on the endpoint, name of the collection, the id and version. /// </summary> /// <param name="collectionName"></param> /// <param name="id"></param> /// <param name="versionId"></param> /// <returns></returns> public static ResourceLocation Build(Uri baseUri, string collectionName, string id, string versionId) { if (String.IsNullOrEmpty(versionId)) throw new ArgumentException("versionId must not be empty", "versionId"); var result = ResourceLocation.Build(baseUri, collectionName, id); result.Operation = Util.RESTOPER_HISTORY; result.VersionId = versionId; var x = result.ToString(); return result; } private void construct(Uri absolutePath) { _location = new UriBuilder(absolutePath); parseLocationParts(); } /// <summary> /// The schema used in the ResourceLocation (http, mail, etc) /// </summary> public string Scheme { get { return _location.Scheme; } set { _location.Scheme = value; } } /// <summary> /// The hostname used in the ResourceLocation (e.g. www.hl7.org) /// </summary> public string Host { get { return _location.Host; } set { _location.Host = value; } } public int Port { get { return _location.Port; } set { _location.Port = value; } } /// <summary> /// The path of the ResourceLocation (e.g. /svc/patient/@1) /// </summary> public string Path { get { return _location.Path; } set { _location.Path = value; parseLocationParts(); } } //public string Fragment //{ // get { return _location.Fragment; } // set { _location.Fragment = value; } //} /// <summary> /// The query part of the ResourceLocation, including the '?' (e.g. ?name=Kramer&gender=M) /// </summary> public string Query { get { return _location.Query; } set { _location.Query = value.TrimStart('?'); } } /// <summary> /// The service path of a Fhir REST uri (e.g. /svc/fhir) /// </summary> private string _service; public string Service { get { return _service; } set { _service = value; _location.Path = buildPath(); } } /// <summary> /// The specified Fhir REST operation (e.g. history, validate) /// </summary> private string _operation; public string Operation { get { return _operation; } set { _operation = value; _location.Path = buildPath(); } } /// <summary> /// The collection part of a Fhir REST Url, corresponding to a Resource (patient, observation) /// </summary> private string _collection; public string Collection { get { return _collection; } set { _collection = value; _location.Path = buildPath(); } } /// <summary> /// The id part of a Fhir REST url, without the '@' /// </summary> private string _id; public string Id { get { return _id; } set { _id = value; _location.Path = buildPath(); } } private string buildPath() { var path = new StringBuilder("/"); if (!String.IsNullOrEmpty(Service)) path.Append(Service + "/"); path.Append(buildOperationPath()); return path.ToString().TrimEnd('/'); } private string buildOperationPath() { var path = new StringBuilder(); if (!String.IsNullOrEmpty(Collection)) { path.Append(Collection + "/"); if (!String.IsNullOrEmpty(Id)) { path.Append("@" + Id + "/"); if (!String.IsNullOrEmpty(Operation)) { path.Append(Operation + "/"); if (!String.IsNullOrEmpty(VersionId)) path.Append("@" + VersionId + "/"); } } else { if (!String.IsNullOrEmpty(Operation)) { path.Append(Operation + "/"); } } } else { if (!String.IsNullOrEmpty(Operation)) { path.Append(Operation + "/"); } } return path.ToString().TrimEnd('/'); } /// <summary> /// The version part of a Fhir REST url, without the '@' /// </summary> private string _versionId; public string VersionId { get { return _versionId; } set { _versionId = value; _location.Path = buildPath(); } } private static readonly string[] resourceCollections = ModelInfo.SupportedResources.Select(res => res.ToLower()).ToArray(); private bool isResourceOrBinaryCollection(string part) { return part == ResourceLocation.BINARY_COLLECTION_NAME || resourceCollections.Contains(part); } private void parseLocationParts() { _service = null; _operation = null; _collection = null; _id = null; _versionId = null; if (!String.IsNullOrEmpty(_location.Path)) { var path = _location.Path.Trim('/'); // The empty path, /, used for batch and conformance if (path == String.Empty) return; // Parse <service>/<resourcetype>/@<id>/history/@<version> var instancePattern = @"^(?:(.*)/)?(\w+)/@([^/]+)(?:/(\w+)(?:/@([^/]+))?)?$"; Regex instanceRegEx = new Regex(instancePattern, RegexOptions.RightToLeft); var match = instanceRegEx.Match(path); if (match.Success) { // Match groups from back to front: versionId, history?, id, collection, service path if (match.Groups[5].Success) _versionId = match.Groups[5].Value; if (match.Groups[4].Success) _operation = match.Groups[4].Value; _id = match.Groups[3].Value; _collection = match.Groups[2].Value; if (match.Groups[1].Success) _service = match.Groups[1].Value; return; } // Not a resource id or version-specific location, try other options... var parts = path.Split('/'); var lastPart = parts[parts.Length - 1]; var serviceParts = parts.Length; // Check for <service>/<resourcetype>/<operation> if( parts.Length >= 2 && isResourceOrBinaryCollection(parts[parts.Length - 2]) ) { _operation = parts[parts.Length - 1]; _collection = parts[parts.Length - 2]; serviceParts = parts.Length - 2; } // Check for <service>/<history|metadata> else if (lastPart == Util.RESTOPER_METADATA || lastPart == Util.RESTOPER_HISTORY) { _operation = lastPart; serviceParts = parts.Length - 1; } // Check for <service>/<resourcetype> else if (isResourceOrBinaryCollection(lastPart)) { _collection = lastPart; serviceParts = parts.Length - 1; } // Assume any remaining parts are part of the Service path _service = serviceParts > 0 ? String.Join("/", parts, 0, serviceParts) : null; } } /// <summary> /// Make a new ResourceLocation that represents a location after navigating to the specified path /// </summary> /// <param name="path"></param> /// <returns></returns> /// <example>If the current path is "http://hl7.org/svc/patient", NavigatingTo("../observation") will /// result in a ResourceLocation of "http://hl7.org/svc/observation"</example> public ResourceLocation NavigateTo(string path) { return NavigateTo(new Uri(path, UriKind.RelativeOrAbsolute)); } public ResourceLocation NavigateTo(Uri path) { if (path.IsAbsoluteUri) throw new ArgumentException("Can only navigate to relative paths", "path"); return new ResourceLocation(_location.Uri, path.ToString()); } /// <summary> /// Return the absolute Uri that represents this full ResourceLocation /// </summary> /// <returns></returns> public Uri ToUri() { return _location.Uri; } /// <summary> /// Return the absolute Uri that represents this full ResourceLocation as a string /// </summary> /// <returns></returns> public override string ToString() { return ToUri().ToString(); } /// <summary> /// Return the absolute Uri representing the ResourceLocation's base endpoint (e.g. http://hl7.org/fhir/svc) /// </summary> /// <returns>An absolute uri to reach the Fhir service endpoint</returns> public Uri ServiceUri { get { var path = Combine(_location.Uri.GetComponents(UriComponents.SchemeAndServer,UriFormat.Unescaped), Service); return new Uri(path, UriKind.Absolute); } } /// <summary> /// Return the path of the ResourceLocation relative to the ServicePath (e.g. patient/@1/history) /// </summary> /// <returns>A relative uri</returns> public Uri OperationPath { get { var path = new StringBuilder(buildOperationPath()); // if (!String.IsNullOrEmpty(Fragment)) // path.Append("#" + Fragment); if (!String.IsNullOrEmpty(Query)) path.Append(Query); return new Uri(path.ToString(), UriKind.Relative); } } private static readonly Uri DUMMY_BASE = new Uri("http://hl7.org"); [Obsolete] public static Uri BuildResourceIdPath(string collection, string id) { return ResourceLocation.Build(DUMMY_BASE, collection, id).OperationPath; } [Obsolete] public static Uri BuildResourceIdPath(string collection, string id, string version) { return ResourceLocation.Build(DUMMY_BASE, collection, id, version).OperationPath; } [Obsolete] public static string GetCollectionFromResourceId(Uri versionedUrl) { if (versionedUrl.IsAbsoluteUri) return new ResourceLocation(versionedUrl).Collection; else return new ResourceLocation(DUMMY_BASE, versionedUrl).Collection; } [Obsolete] public static string GetIdFromResourceId(Uri versionedUrl) { if (versionedUrl.IsAbsoluteUri) return new ResourceLocation(versionedUrl).Id; else return new ResourceLocation(DUMMY_BASE, versionedUrl).Id; } [Obsolete] public static string GetVersionFromResourceId(Uri versionedUrl) { if (versionedUrl.IsAbsoluteUri) return new ResourceLocation(versionedUrl).VersionId; else return new ResourceLocation(DUMMY_BASE, versionedUrl).VersionId; } } }
using System; using System.Data; using System.IO; using System.Linq; using System.Linq.Dynamic; using System.Linq.Expressions; using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Abp.Linq; using Abp.Linq.Extensions; using Abp.Extensions; using Abp.UI; using Abp.Domain.Repositories; using Abp.Domain.Services; using Dg.KMS; using Dg.KMS.People; namespace Dg.KMS.People.DomainService { /// <summary> /// Person领域层的业务管理 ///</summary> public class PersonManager :KMSDomainServiceBase, IPersonManager { private readonly IRepository<Person,long> _repository; /// <summary> /// Person的构造方法 ///</summary> public PersonManager( IRepository<Person, long> repository ) { _repository = repository; } /// <summary> /// 初始化 ///</summary> public void InitPerson() { //throw new NotImplementedException(); } // TODO:编写领域业务代码 public long Create() { var entity = new Person { Name = "c" + DateTime.Now.ToUnixTimestamp() + Guid.NewGuid() }; return _repository.InsertOrUpdateAndGetId(entity); } } }
using System; using System.Collections.Generic; using System.Text; namespace PatronBridge { public class ExpendedoraCafe : Expendedora { private int Cantidad; public ExpendedoraCafe(IBebida bebida, int cantidad): base(bebida) { this.Cantidad = cantidad; } public override string mostrarDatosExp() { return "Expendedora de Cafe. Capacidad Maxima: "+Cantidad; } } }
using System; namespace GenericAlgorithmPath { static class Helpers { private static Random _random = new Random((int) DateTime.Now.Ticks); public static void Shuffle<T>(T[] array) { int n = array.Length; while (n > 1) { int k = _random.Next(n--); T temp = array[n]; array[n] = array[k]; array[k] = temp; } } public static int GetRandomInt(int minValue = int.MinValue, int maxValue = int.MaxValue) { return _random.Next(minValue, maxValue); } public static bool GetBoolByChance(int chance, int outOf = 100) { return _random.Next(outOf) < chance; } /*public static BitArray GetFitnessValue() { BitArray fitnessValue = new BitArray(20); return fitnessValue; }*/ public static int GetCost(int city1, int city2) { int[][] costs = { new[] {0, 55, 34, 32, 54, 40, 36, 40, 37, 53}, new[] {64, 0, 54, 55, 73, 45, 71, 50, 53, 52}, new[] {51, 48, 0, 41, 40, 58, 55, 33, 35, 37}, new[] {47, 46, 55, 0, 49, 45, 56, 52, 57, 55}, new[] {50, 39, 43, 52, 0, 26, 40, 39, 38, 33}, new[] {60, 49, 48, 57, 58, 0, 48, 47, 48, 48}, new[] {51, 37, 44, 43, 38, 40, 0, 64, 48, 47}, new[] {58, 41, 53, 45, 47, 43, 74, 0, 43, 42}, new[] {53, 38, 40, 33, 36, 58, 35, 30, 0, 31}, new[] {60, 39, 40, 56, 41, 41, 45, 59, 19, 0} }; return costs[city1][city2]; } public static int[] OrderedGenes() { int[] orderedGenes = new int[GeneticAlgorithm.GENES_PER_CHROMOSOMES]; for (int i = 0; i < GeneticAlgorithm.GENES_PER_CHROMOSOMES; i++) { orderedGenes[i] = i + 1; } return orderedGenes; } public static void RemoveFromArray<T>(ref T[] array, T item) { int n = array.Length; while (n-- > 0) { if (Equals(array[n], item)) { array[n] = default(T); n = 0; } } } public static void CopyArray<T>(ref T[] source, ref T[] destination) { uint sourceLength = (uint) source.Length; uint destinationLength = (uint) destination.Length; if (!Equals(sourceLength, destinationLength)) { throw new IndexOutOfRangeException("Source and destination array's sizes mismatch."); } while (sourceLength-- > 0) { destination[sourceLength] = source[sourceLength]; } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class MouseOverRoom: MonoBehaviour { Environment env; Interface canvasInterface; GameObject monster; void Start() { env = GameObject.Find ("Environment").GetComponent<Environment> (); canvasInterface = GameObject.Find ("CanvasNight").GetComponent<Interface> (); } // OnMouseEnter et OnMouseExit permettent de gérer la transparence des cases quand on passe dessus public void OnMouseEnter() { GetComponent<SpriteRenderer>().color = new Color (0f, 1f, 0f, .5f); } public void OnMouseExit () { GetComponent<SpriteRenderer>().color = new Color (0f, 1f, 0f, .2f); } // Si on clique sur une salle, on instancie le monstre dans cette salle avec les valeurs d'attaque et hp du canvas public void OnMouseDown() { //Si on est en train de placer le coeur // Cette condition est placée au dessus de la condition settingAdventurersRoom pour éviter de passer directement dedans une fois que l'on passe en.settingHeart = true (en attendant de trouver mieux ...) if (env.settingHeart == true) { //On enregistre la salle du coeur env.heartH = GetComponent<InfoRoom> ().H; env.heartW = GetComponent<InfoRoom> ().W; env.settingHeart = false; //On réactive le Canvas et on enlève le texte de Choix de salle de départ GameObject.Find ("CanvasNight").GetComponent<Canvas> ().enabled = true; GameObject.Find ("TextOverlay").GetComponent<Canvas> ().enabled = false; //On ne pourra plus sélectionner cette case donc on la détruit Destroy (gameObject); //On créé le coeur monster = Instantiate(GameObject.Find("Dungeon(Clone)").GetComponent<Dungeon> ().monsterList[0]) as GameObject; //monster = Instantiate (monsters [0]) as GameObject; Actor actor = monster.GetComponent <Actor> (); actor.isHeart = true; actor.roomH = GetComponent<InfoRoom> ().H; actor.roomW = GetComponent<InfoRoom> ().W; monster.transform.SetParent (Dungeon.monsters); GetComponentInParent<InfoRoom>().containsMonster = true; //On désactive l'overlay OverlayOff(); } //Si on est en train de choisir la salle de départ if (env.settingAdventurersRoom == true) { //On enregistre la salle de départ des aventuriers env.startingH = GetComponent<InfoRoom> ().H; env.startingW = GetComponent<InfoRoom> ().W; //On n'est plus en train de choisir la salle de départ env.settingAdventurersRoom = false; //On ne pourra plus sélectionner cette case donc on la détruit Destroy (gameObject); //On change la couleur de la salle de départ pour la repérer GameObject[] groundTiles = GameObject.FindGameObjectsWithTag("Ground"); foreach (GameObject Tile in groundTiles) { if ((Tile.GetComponent<InfoRoom>().H == GetComponent<InfoRoom>().H) && (Tile.GetComponent<InfoRoom>().W == GetComponent<InfoRoom>().W)) { Tile.GetComponent<SpriteRenderer>().color = new Color(0.8f, 0.8f,0.8f,1f); } } //On affiche toutes les salles pour choisir la salle du coeur GameObject[] gameObjectOverlay = GameObject.FindGameObjectsWithTag ("Overlay"); foreach (GameObject Overlay in gameObjectOverlay) { if (Overlay.GetComponentInParent<InfoRoom>().containsMonster == false) { Overlay.GetComponent<Renderer> ().enabled = true; Overlay.GetComponent<PolygonCollider2D> ().enabled = true; Overlay.GetComponent<SpriteRenderer> ().color = new Color (0f, 1f, 0f, .2f); } } //On va choisir la salle du coeur env.settingHeart = true; GameObject.Find ("TextOverlay").GetComponent<TextOverlay> ().SetTextOverlay (); } //Si on est en train de placer un monstre if (env.addingMonster == true) { //MonsterPool monsterPool = GameObject.Find ("GenerateMonster").GetComponent<MonsterPool> (); int monsterNum = env.monsterNum; SetMonster selectedMonster = GameObject.Find("Monster" + (monsterNum).ToString()).GetComponent<SetMonster>(); GameObject monster = Instantiate (GameObject.Find("Dungeon(Clone)").GetComponent<Dungeon> ().monsterList[selectedMonster.monsterID]) as GameObject; Actor actor = monster.GetComponent <Actor> (); //On retire le prix au trésor canvasInterface.BuyMonster (selectedMonster.monsterPrice); actor.roomH = GetComponent<InfoRoom> ().H; actor.roomW = GetComponent<InfoRoom> ().W; actor.hpmax = selectedMonster.monsterHP; actor.attack = selectedMonster.monsterAttack; actor.value = selectedMonster.monsterPrice; actor.roomPos = 5; monster.transform.SetParent (Dungeon.monsters); env.addingMonster = false; GetComponentInParent<InfoRoom>().containsMonster = true; //On désactive l'overlay OverlayOff(); } } private void OverlayOff() { // Désactiver l'overlay GameObject[] gameObjectOverlay = GameObject.FindGameObjectsWithTag ("Overlay"); foreach (GameObject Overlay in gameObjectOverlay) { Overlay.GetComponent<Renderer> ().enabled = false; Overlay.GetComponent<PolygonCollider2D> ().enabled = false; } } }
using System; using Infrostructure.Enums; namespace DomainModel.Entity.ProductParts { public abstract class Device { /// <summary> /// کلاس مادر قطعات /// </summary> public Guid Id{ get; private set; } /// <summary> /// نام /// </summary> public string Name{ get; private set; } /// <summary> /// برند /// </summary> public string Brand{ get; private set; } /// <summary> /// نوع قطعه /// </summary> public abstract DeviceType DeviceType { get; } public Device(string name, string brand) { Name = name; Brand = brand; } } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class EnemyTouchHandler : MonoBehaviour { private EnemyUtilities enemyUtilities; private void Start() { enemyUtilities = GetComponent<EnemyUtilities>(); } internal void HandleCollisionEvent(string tag) { if (tag == Utilities.EnemyConstants.TagEnemyBody) { enemyUtilities.SendEnemyFsmEvent(Utilities.EnemyConstants.EventSelectBody); } else if (tag == Utilities.EnemyConstants.TagEnemyHead) { enemyUtilities.SendEnemyFsmEvent(Utilities.EnemyConstants.EventSelectHead); } else if (tag == Utilities.EnemyConstants.TagEnemyLeftArm) { enemyUtilities.SendEnemyFsmEvent(Utilities.EnemyConstants.EventSelectLeftArm); } else if (tag == Utilities.EnemyConstants.TagEnemyRightArm) { enemyUtilities.SendEnemyFsmEvent(Utilities.EnemyConstants.EventSelectRightArm); } } }
using System; using System.Collections.Generic; using System.Linq; namespace EasyConsoleNG.Selects { public class Select<T> { private EasyConsole Console { get; set; } private string Prompt { get; set; } private List<SelectOption<T>> Options { get; set; } public bool Required { get; set; } public T DefaultValue { get; set; } public Select(EasyConsole console = null, string prompt = null, IEnumerable<SelectOption<T>> options = null, bool required = false, T defaultValue = default) { Console = console ?? EasyConsole.Instance; Prompt = prompt ?? "Choose an option"; if (options != null) { Options = options.ToList(); } else { Options = new List<SelectOption<T>>(); } Required = required; DefaultValue = defaultValue; } public T Display() { while (true) { for (var i = 0; i < Options.Count; i++) { Console.Output.WriteLine("{0}. {1}", i + 1, Options[i].Name); } int idx; if (Required) { var choice = Console.Input.ReadInt(Prompt, min: 1, max: Options.Count, defaultValue: 1, required: true); idx = choice - 1; } else { var choice = Console.Input.ReadNullableInt(Prompt, min: 1, max: Options.Count, defaultValue: null, required: false); if (choice == null) return DefaultValue; idx = choice.Value - 1; } if (idx < 0 || idx > Options.Count) { Console.Output.WriteLine($"Invalid option."); continue; } return Options[idx].Value; } } public Select<T> Add(string option, T value) { return Add(new SelectOption<T>(option, value)); } public Select<T> Add(SelectOption<T> option) { Options.Add(option); return this; } public bool Contains(string option) { return Options.FirstOrDefault((op) => op.Name.Equals(option)) != null; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Business.Constants { public static class Messages { public static string ProductAdded = "Ürün eklendi"; public static string ProductNameInvalid = "Ürün ismi geçersiz."; public static string ProductsListed = "Ürün eklendi"; public static string MaintenanceTime = "sistem bakımda"; public static string OrderAdded="sipariş eklendi" ; public static string OrderDeleted = "sipariş silindi"; public static string OrdersListed="siparişler listelendi"; public static string OrderUpdated="sipariş güncellendi"; public static string CategoryAdded="yeni kategori eklendi"; public static string CategoryDeleted="kategori silindi"; public static string CategoryUpdated="kategori güncellendi"; public static string CustomerListed; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.PostProcessing; public class PPShifter_Interior : MonoBehaviour { public PostProcessingProfile PPPremiere_Phase; public PostProcessingProfile PPPhase2; public PostProcessingProfile PPPhase3; public Player player; private bool Interior = false; private float TimeToShift = 0.0f; public float TimePPPhase2 = 60.0f; public float TimePPPhase3 = 120.0f; // Use this for initialization void Start() { } // Update is called once per frame void Update() { TimeToShift += Time.deltaTime; if (TimeToShift > TimePPPhase2 && TimeToShift < TimePPPhase3) player.GetComponentInChildren<PostProcessingBehaviour>().profile = PPPhase2; else if (TimeToShift > TimePPPhase3) player.GetComponentInChildren<PostProcessingBehaviour>().profile = PPPhase3; else player.GetComponentInChildren<PostProcessingBehaviour>().profile = PPPremiere_Phase; } }
using System; using Enyim.Caching.Memcached.Results; namespace Enyim.Caching.Memcached.Protocol.Binary { public class StoreOperation : BinarySingleItemOperation, IStoreOperation { readonly StoreMode _mode; readonly uint _expires; CacheItem _value; public StoreOperation(StoreMode mode, string key, CacheItem value, uint expires) : base(key) { this._mode = mode; this._value = value; this._expires = expires; } protected override BinaryRequest Build() { OpCode op; switch (this._mode) { case StoreMode.Set: op = OpCode.Set; break; case StoreMode.Add: op = OpCode.Add; break; case StoreMode.Replace: op = OpCode.Replace; break; default: throw new ArgumentOutOfRangeException("mode", $"{this._mode} is not supported"); } var extra = new byte[8]; BinaryConverter.EncodeUInt32((uint)this._value.Flags, extra, 0); BinaryConverter.EncodeUInt32(this._expires, extra, 4); var request = new BinaryRequest(op) { Key = this.Key, Cas = this.Cas, Extra = new ArraySegment<byte>(extra), Data = this._value.Data }; return request; } protected override IOperationResult ProcessResponse(BinaryResponse response) { this.StatusCode = response.StatusCode; var result = new BinaryOperationResult(); return response.StatusCode == 0 ? result.Pass() : result.Fail(OperationResultHelper.ProcessResponseData(response.Data)); } StoreMode IStoreOperation.Mode => this._mode; protected internal override bool ReadResponseAsync(PooledSocket socket, Action<bool> next) => throw new NotSupportedException(); } } #region [ License information ] /* ************************************************************ * * © 2010 Attila Kiskó (aka Enyim), © 2016 CNBlogs, © 2022 VIEApps.net * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * ************************************************************/ #endregion
using UnityAtoms.Mobile; namespace UnityAtoms.Mobile { /// <summary> /// Condition of type `TouchUserInput`. Inherits from `AtomCondition&lt;TouchUserInput&gt;`. /// </summary> [EditorIcon("atom-icon-teal")] public abstract class TouchUserInputCondition : AtomCondition<TouchUserInput> { } }
using System; namespace Vanhackaton { class DigitalWallet { private long walletId; private string username; private string userAccessToken; private int walletBalance; public DigitalWallet(long walletId, string userName, string userAccessToken) { this.walletId = walletId; this.username = userName; this.userAccessToken = userAccessToken; // Generate a random balance for the wallet Random random = new Random(); this.walletBalance = random.Next(100000); } public long getWalletId() { return walletId; } public string getUsername() { return username; } public string getUserAccessToken() { return userAccessToken; } public int getWalletBalance() { return walletBalance; } public void setBalance(int walletBalance) { this.walletBalance = walletBalance; } } }
using Microsoft.SharePoint; using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace YFVIC.DMS.Model.Models.HR { public class OrgRoleEntity { public OrgRoleEntity(SPListItem item) { if (item != null) { ID = item["ID"] + ""; Title = item["Title"] + ""; Name = item["Filed_OrgRole_Name"] + ""; Role = item["Filed_OrgRole_Role"] + ""; UserAD = item["Filed_OrgRole_User"] + ""; Remark = item["Filed_OrgRole_Remark"] + ""; } } public OrgRoleEntity() { // TODO: Complete member initialization } /// <summary> /// 编号 /// </summary> public string ID; /// <summary> /// 标题 /// </summary> [DataMember] public string Title; /// <summary> ///组织名称 /// </summary> [DataMember] public string Name; /// <summary> ///角色名称 /// </summary> [DataMember] public string Role; /// <summary> ///用户 /// </summary> [DataMember] public string UserAD; /// <summary> ///备注 /// </summary> [DataMember] public string Remark; /// <summary> ///网站地址 /// </summary> [DataMember] public string WebUrl; /// <summary> ///组织名称 /// </summary> [DataMember] public string OrgName; /// <summary> ///用户名称 /// </summary> [DataMember] public List<SysUserEntity> UserName; } }
using DataAccessLayer.Infrastructure; using Entity; using Wakool.DataAnnotations; using MetadataDiscover; using System; using System.Collections.Generic; using ExceptionControl; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; using DataAccessLayer.Infrastructure.Extensions; namespace DataAccessLayer.Impl { public class EntityDAL<T> where T : EntityBase { public void Insert(T item) { if (item != null) new DbExecuter().Execute(SqlGenerator<T>.BuildInsertCommand(item)); } public int Update(T item) { if (item != null) return new DbExecuter().Execute(SqlGenerator<T>.BuildUpdateCommand(item)); return 0; } public int Delete(T item) { if (item != null) return new DbExecuter().Execute(SqlGenerator<T>.BuildDeleteCommand(item)); return 0; } public EntityBase GetByID(T nome, int id, Type type) { try { SqlCommand command = new SqlCommand(); command.CommandText = string.Format("SELECT * FROM {0} WHERE ID = @ID", (AssemblyUtils.GetPropertyTableNameAttribute(type))); command.Parameters.AddWithValue("@ID", id); DataTable table = new DbExecuter().GetData(command); if (table.Rows.Count == 0) return null; return (EntityBase)table.Rows[0].ToObject(type); } catch (Exception ex) { new ExceptionControl.LogConfing.ExceptionText(ex); } return new EntityBase(); } public object GetAll(Type type) { try { SqlCommand command = new SqlCommand(); command.CommandText = string.Format("SELECT * FROM {0}", AssemblyUtils.GetPropertyTableNameAttribute(type).ToUpper()); DataTable table = new DbExecuter().GetData(command); if (table.Rows.Count == 0) return null; return table.ToObjectCollection<T>(type); } catch (Exception ex) { new ExceptionControl.LogConfing.ExceptionText(ex); } return new EntityBase(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Task2.Game; namespace Task2.Game { abstract class Unit { public abstract Field Location { get; set; } } }
using NeuralNetwork.Core; using NeuralNetwork.LayersFactory; using NeuralNetwork.NeuralEventArgs; using System; using System.Collections.Generic; using NLog; using System.IO; namespace NeuralNetwork { // TODO: SAVE and LOAD // TODO: индесатор для NeuralLayers (возможность удалять слой) ??? // TODO: обработку исключений, кидать все ошибки в текстовый файл и завершать программу // TODO: LearningCounter -> MaxValue свойство, чтобы предотвратить OverflowException при преобразовании в Int32 значение // TODO: проверку параметров в классе Settings -> CreateNeuralNet // TODO: методы обработки различных форматов данных для загружаемого датасета public enum InitializerWeights { Random, Zeros, Ones, XavierUniform } public enum InitializerBias { Zeros, Ones, Random } public enum ActivationFunc { Sigmoid, TanH, Identity, ReLU, Gaussian } public enum LossFunc { MSE, RootMSE, Arctan } public enum LearningOptimizing { SGDM } [Serializable] public class NeuralNet : INeuralNet { //private static readonly string _saveDirPath = $@"{Directory.GetCurrentDirectory()}\save"; //private static readonly string _saveFileName = "SavedNeuralNet_"; //private static readonly string _dateTimeFormat = "dd-MM-yyyy_HH-mm-ss"; //private static readonly string _saveFileExt = ".dat"; private static readonly float _defaultLearningRate = 0.1F; private static readonly float _defaultMomentumRate = 0.9F; //private static readonly Logger _Logger = LogManager.GetCurrentClassLogger(); private LinkedList<ILayer> _NeuralLayers { get; set; } public ActivationFunc ActivationFunc { get; set; } public LearningOptimizing? LearningOptimizing { get; set; } public float LearningRate { get; set; } public float MomentumRate { get; set; } public LossFunc LossFunc { get; set; } public uint LearningCounter { get; private set; } #region ----- Constructor (Fluent Builder) ----- private NeuralNet(Builder settings) { ActivationFunc = settings.ActivationFunc; LearningOptimizing = settings.LearningOptimizing ?? default(LearningOptimizing); LearningRate = settings.LearningRate ?? _defaultLearningRate; MomentumRate = settings.MomentumRate ?? _defaultMomentumRate; LossFunc = settings.LossFunc; var layersFactory = new NeuralLayerFactory( settings.InputNeurons, settings.NeuronLayers.ToArray(), settings.IsBiasNeurons, settings.WeightsInitializer, settings.BiasInitializer); _NeuralLayers = layersFactory.CreateLayers(); } public class Builder { public uint InputNeurons { get; set; } public List<uint> NeuronLayers { get; set; } public bool IsBiasNeurons { get; set; } public float? LearningRate { get; private set; } public float? MomentumRate { get; private set; } public InitializerWeights WeightsInitializer { get; set; } public InitializerBias BiasInitializer { get; set; } public ActivationFunc ActivationFunc { get; private set; } public LossFunc LossFunc { get; private set; } public LearningOptimizing? LearningOptimizing { get; private set; } = null; public Builder() { NeuronLayers = new List<uint>(); } public Builder SetNeuronsInputLayer(uint inputNeurons) { InputNeurons = inputNeurons; return this; } public Builder SetNeuronsForLayers(params uint[] neuronLayers) { NeuronLayers.AddRange(neuronLayers); return this; } public Builder SetBiasNeurons(bool isBiasNeurons, InitializerBias biasInitializer = default(InitializerBias)) { IsBiasNeurons = isBiasNeurons; BiasInitializer = biasInitializer; return this; } public Builder SetLearningRate(float learningRate) { LearningRate = learningRate; return this; } public Builder SetMomentumRate(float momentumRate) { MomentumRate = momentumRate; return this; } public Builder SetWeightsInitializer(InitializerWeights weightsInitializer) { WeightsInitializer = weightsInitializer; return this; } public Builder SetActivationFunc(ActivationFunc activationFunc) { ActivationFunc = activationFunc; return this; } public Builder SetLossFunc(LossFunc lossFunc) { LossFunc = lossFunc; return this; } public Builder SetLearningOptimizing(LearningOptimizing learningOptimizing) { LearningOptimizing = learningOptimizing; return this; } public NeuralNet Build() { return new NeuralNet(this); } } #endregion public float[][] Activate(float[][] inputSignals) { return OnActivationNeuralNet(inputSignals).OutputsSignalsPrevLayer; } public float Learn(float[][] inputSignals, float[][] expectedSignals, uint epochsCount) { OnActivationNeuralNet(inputSignals); for (int epoch = 1; epoch <= epochsCount; epoch++) { LearningProcess(inputSignals, expectedSignals); } return CalculateError(inputSignals, expectedSignals); } public void Learn(float[][] inputSignals, float[][] expectedSignals, double acceptLoss) { float _currentLoss; OnActivationNeuralNet(inputSignals); do { LearningProcess(inputSignals, expectedSignals); _currentLoss = CalculateError(inputSignals, expectedSignals); } while (_currentLoss > acceptLoss); } public IEnumerable<float> Learn(float[][] inputSignals, float[][] expectedSignals, uint epochsCount, uint returnLossPeriod = 100) { OnActivationNeuralNet(inputSignals); for (int epoch = 1; epoch <= epochsCount; epoch++) { LearningProcess(inputSignals, expectedSignals); if (LearningCounter % returnLossPeriod == 0) yield return CalculateError(inputSignals, expectedSignals); } } public IEnumerable<float> Learn(float[][] inputSignals, float[][] expectedSignals, double acceptLoss = 0.01, uint returnLossPeriod = 100) { float _currentLoss; OnActivationNeuralNet(inputSignals); do { LearningProcess(inputSignals, expectedSignals); _currentLoss = CalculateError(inputSignals, expectedSignals); if (LearningCounter % returnLossPeriod == 0) yield return _currentLoss; } while (_currentLoss > acceptLoss); } public float CalculateError(float[][] inputSignals, float[][] expectedSignals) { var _outputSignals = OnActivationNeuralNet(inputSignals).OutputsSignalsPrevLayer; return NeuralMath.GetTotalLoss(_outputSignals, expectedSignals, LossFunc); } //public string SaveNeuralNetToFile() //{ // if (!Directory.Exists(_saveDirPath)) Directory.CreateDirectory(_saveDirPath); // string dateTimeNow = DateTime.Now.ToString(_dateTimeFormat); // string filePath = $@"{_saveDirPath}\{_saveFileName}{dateTimeNow}{_saveFileExt}"; // using (FileStream stream = new FileStream(filePath, FileMode.CreateNew)) // { // new BinaryFormatter().Serialize(stream, _NeuralNet); // _LastSavedNeuralNetName = filePath; // return filePath; // } //} //public bool LoadNeuralNetFromFile(string filePath = null) //{ // filePath = filePath ?? _LastSavedNeuralNetName; // if (File.Exists(filePath)) // { // using (FileStream stream = File.Open(filePath, FileMode.Open)) // { // _NeuralNet = (NeuralNet)new BinaryFormatter().Deserialize(stream); // return true; // } // } // else // { // return false; // } //} private void LearningProcess(float[][] inputSignals, float[][] expectedSignals) { for (int numberOfActiveDataset = 0; numberOfActiveDataset < inputSignals.Length; numberOfActiveDataset++) { OnActivationNeuralNet(inputSignals, numberOfActiveDataset); OnLearningNeuralNet(expectedSignals, numberOfActiveDataset); } LearningCounter++; } private LayerEventArgs OnActivationNeuralNet(float[][] inputsSignals, int? numberOfActiveDataset = null) { try { LayerEventArgs activationEventArgs = new LayerEventArgs(); activationEventArgs.ActivationFunc = ActivationFunc; activationEventArgs.OutputsSignalsPrevLayer = inputsSignals; activationEventArgs.NumberOfActiveDataset = numberOfActiveDataset; (_NeuralLayers.First.Value as NeuralLayer).Activate(this, activationEventArgs); return activationEventArgs; } catch (Exception ex) { Console.ForegroundColor = ConsoleColor.DarkRed; Console.WriteLine("\nInnerException: " + ex.InnerException); Console.WriteLine("\nMessage: " + ex.Message); Console.WriteLine("\nSource: " + ex.Source); Console.WriteLine("\nTargetSite: " + ex.TargetSite); Console.WriteLine("\nStackTrace: "); Console.WriteLine("\n" + ex.StackTrace); Console.ReadKey(); //Logger.Fatal(exception.Message); //LogManager.Flush(); //LogManager.Shutdown(); //Environment.Exit(0); } return null; } private void OnLearningNeuralNet(float[][] expectedSignals, int numberOfActiveDataset) { try { LayerEventArgs learningEventArgs = new LayerEventArgs(); learningEventArgs.ActivationFunc = ActivationFunc; learningEventArgs.LearningOptimizing = LearningOptimizing; learningEventArgs.LearningRate = LearningRate; learningEventArgs.MomentumRate = MomentumRate; learningEventArgs.ExpectedSignalsOutLayer = expectedSignals; learningEventArgs.NumberOfActiveDataset = numberOfActiveDataset; (_NeuralLayers.Last.Value as NeuralLayer).Learning(this, learningEventArgs); } catch (Exception ex) { Console.ForegroundColor = ConsoleColor.DarkRed; Console.WriteLine("\nInnerException: " + ex.InnerException); Console.WriteLine("\nMessage: " + ex.Message); Console.WriteLine("\nSource: " + ex.Source); Console.WriteLine("\nTargetSite: " + ex.TargetSite); Console.WriteLine("\nStackTrace: "); Console.WriteLine("\n" + ex.StackTrace); Console.ReadKey(); //Logger.Fatal(exception.Message); //LogManager.Flush(); //LogManager.Shutdown(); //Environment.Exit(0); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Animal.DgContext { public interface IServiceClass { String ServiceInfo(); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CoinCreator : MonoBehaviour { // Get a reference to our object. public GlobalPooler pooler; // This is the distance between all coins. public float distanceBetweenCoins; public void GenerateCoins(Vector3 positionStart) { // get a coin object and place it at the vector 3 location given an set it as active. GameObject coin1 = pooler.getPooledObject("Coin"); coin1.transform.position = positionStart; coin1.SetActive(true); // create another coin and place to to the left on the center coin by the value distanceBetweenCoins. GameObject coin2 = pooler.getPooledObject("Coin"); coin2.transform.position = new Vector3(positionStart.x - distanceBetweenCoins, positionStart.y, positionStart.z); coin2.SetActive(true); // create another coin and place to to the right on the center coin by the value distanceBetweenCoins. GameObject coin3 = pooler.getPooledObject("Coin"); coin3.transform.position = new Vector3(positionStart.x + distanceBetweenCoins, positionStart.y, positionStart.z); coin3.SetActive(true); } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.Text; using System.ServiceModel.Activation; namespace RestService { [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] public class Account : IAccount { private static IList<Model.Account> accounts = new List<Model.Account>() { new Model.Account() { Id = "1", Name = "Hello world" }, new Model.Account() { Id = "2", Name = "Henry" }, new Model.Account() { Id = "3", Name = "Test" } }; public IEnumerable<Model.Account> Datas() { return accounts; } public Model.Account Get(string id) { return accounts.Where(x => x.Id == id).FirstOrDefault(); } public Model.ResponseMessage Create(Model.Account account) { accounts.Add(new Model.Account() { Id = null == accounts.LastOrDefault() ? "1" : (int.Parse(accounts.LastOrDefault().Id) + 1).ToString(), Name = account.Name }); return new Model.ResponseMessage() { Success = true, Message = "Created" }; } public Model.ResponseMessage Modify(string id, Model.Account account) { var data = Get(id); if (null != data) { data.Name = account.Name; } return new Model.ResponseMessage() { Success = true, Message = "Modify success" }; } public Model.ResponseMessage Delete(string id) { var data = Get(id); if (null != data) { accounts.Remove(data); } return new Model.ResponseMessage() { Success = true, Message = "Deleted" }; } } }
using System; using System.Collections.Generic; namespace Fbtc.Domain.Entities { public class Anuidade { public int AnuidadeId { get; set; } public int Exercicio { get; set; } public DateTime DtVencimento { get; set; } public DateTime DtInicioVigencia { get; set; } public DateTime DtTerminoVigencia { get; set; } public bool CobrancaLiberada { get; set; } public DateTime? DtCobrancaLiberada { get; set; } public DateTime DtCadastro { get; set; } public bool Ativo { get; set; } } public class AnuidadeDao : Anuidade { public IEnumerable<AnuidadeTipoPublicoDao> AnuidadesTiposPublicosDao { get; set; } } }
using System; using System.Collections.Generic; using System.Net; using FluentAssertions; using Moq; using NUnit.Framework; using Properties.Controllers; using Properties.Core.Interfaces; using Properties.Core.Objects; using Properties.Tests.Helper; namespace Properties.Tests.UnitTests.Controllers { [TestFixture] // ReSharper disable once InconsistentNaming public class ChecksController_TestFixture { private readonly Mock<IPropertyCheckService> _mockChecksService = new Mock<IPropertyCheckService>(); private PropertyChecksController _checksController; [SetUp] public void Setup() { _checksController = ControllerHelper.GetInitialisedChecksController(_mockChecksService.Object); AutoMapperConfig.Bootstrap(); } [Test] public void ChecksController_NullCheckService_ThrowsException() { //act Assert.Throws<ArgumentNullException>(() => new PropertyChecksController(null)); } [Test] public void GetChecksForProperty_EmptyPropertyReference_ThrowsException() { //act Assert.Throws<ArgumentNullException>(() => _checksController.GetPropertyChecks(string.Empty)); } [Test] public void GetChecksForProperty_CallsChecksServices() { //arrange const string reference = "ABCD1234"; _mockChecksService.ResetCalls(); _mockChecksService.Setup(x => x.GetChecksForProperty(reference)).Returns(new List<PropertyCheck>()); //act var result = _checksController.GetPropertyChecks(reference); //assert _mockChecksService.Verify(x => x.GetChecksForProperty(reference), Times.Once); } [Test] public void GetCheckForProperty_EmptyPropertyReference_ThrowsException() { //arrange const string reference = "ABCD1234"; //act Assert.Throws<ArgumentNullException>(() => _checksController.GetPropertyCheck(string.Empty, reference)); } [Test] public void GetCheckForProperty_EmptyCheckReference_ThrowsException() { //arrange const string reference = "ABCD1234"; //act Assert.Throws<ArgumentNullException>(() => _checksController.GetPropertyCheck(reference, string.Empty)); } [Test] public void GetCheckForProperty_CallsChecksService() { //arrange const string reference = "ABCD1234"; //act var result = _checksController.GetPropertyCheck(reference, reference); //assert _mockChecksService.Verify(x => x.GetCheckForProperty(reference, reference), Times.Once); } [Test] public void Post_EmptyPropertyReference_ThrowsException() { //act Assert.Throws<ArgumentNullException>( () => _checksController.PostCheck(string.Empty, new Models.PropertyCheck())); } [Test] public void Post_NullCheck_ThrowsException() { //arrange const string reference = "ABCD1234"; //act Assert.Throws<ArgumentNullException>(() => _checksController.PostCheck(reference, null)); } [Test] public void Post_Check_CheckServiceSucceeds_Returns201CreatedAndLocationHeader() { //arrange const string reference = "ABCD1234"; _mockChecksService.ResetCalls(); _mockChecksService.Setup(x => x.CreateCheck(reference, It.IsAny<PropertyCheck>())).Returns(reference); //act var result = _checksController.PostCheck(reference, new Models.PropertyCheck()); //assert result.StatusCode.Should().Be(HttpStatusCode.Created); result.Headers.Location.Should().NotBeNull(); _mockChecksService.Verify(x => x.CreateCheck(reference, It.IsAny<PropertyCheck>()), Times.Once); } [Test] public void Post_Check_CheckServiceFails_Returns501InternalServerError() { //arrange const string reference = "ABCD1234"; _mockChecksService.ResetCalls(); _mockChecksService.Setup(x => x.CreateCheck(reference, It.IsAny<PropertyCheck>())).Returns((string)null); //act var result = _checksController.PostCheck(reference, new Models.PropertyCheck()); //assert result.StatusCode.Should().Be(HttpStatusCode.InternalServerError); result.Headers.Location.Should().BeNull(); _mockChecksService.Verify(x => x.CreateCheck(reference, It.IsAny<PropertyCheck>()), Times.Once); } [Test] public void Put_EmptyPropertyReference_ThrowsException() { //arrange const string reference = "ABCD1234"; //act Assert.Throws<ArgumentNullException>( () => _checksController.PutCheck(string.Empty, reference, new Models.PropertyCheck())); } [Test] public void Put_EmptyCheckReference_ThrowsException() { //arrange const string reference = "ABCD1234"; //act Assert.Throws<ArgumentNullException>( () => _checksController.PutCheck(reference, string.Empty, new Models.PropertyCheck())); } [Test] public void Put_NullCheck_ThrowsException() { //arrange const string reference = "ABCD1234"; //act Assert.Throws<ArgumentNullException>(() => _checksController.PutCheck(reference, reference, null)); } [Test] public void Put_Check_CheckServiceSucceeds_Returns200Ok() { //arrange const string reference = "ABCD1234"; _mockChecksService.ResetCalls(); _mockChecksService.Setup(x => x.UpdateCheck(reference, reference, It.IsAny<PropertyCheck>())).Returns(true); //act var result = _checksController.PutCheck(reference, reference, new Models.PropertyCheck()); //assert result.StatusCode.Should().Be(HttpStatusCode.OK); _mockChecksService.Verify(x => x.UpdateCheck(reference, reference, It.IsAny<PropertyCheck>()), Times.Once); } [Test] public void Put_Check_CheckServiceFails_Returns501InternalServerError() { //arrange const string reference = "ABCD1234"; _mockChecksService.ResetCalls(); _mockChecksService.Setup(x => x.UpdateCheck(reference, reference, It.IsAny<PropertyCheck>())).Returns(false); //act var result = _checksController.PutCheck(reference, reference, new Models.PropertyCheck()); //assert result.StatusCode.Should().Be(HttpStatusCode.InternalServerError); _mockChecksService.Verify(x => x.UpdateCheck(reference, reference, It.IsAny<PropertyCheck>()), Times.Once); } [Test] public void Delete_EmptyPropertyReference_ThrowsException() { //arrange const string reference = "ABCD1234"; //act Assert.Throws<ArgumentNullException>(() => _checksController.DeleteCheck(string.Empty, reference)); } [Test] public void Delete_EmptyCheckReference_ThrowsException() { //arrange const string reference = "ABCD1234"; //act Assert.Throws<ArgumentNullException>(() => _checksController.DeleteCheck(reference, string.Empty)); } [Test] public void Delete_Check_CheckServiceSucceeds_Returns204NoContent() { //arrange const string reference = "ABCD1234"; _mockChecksService.ResetCalls(); _mockChecksService.Setup(x => x.DeleteCheck(reference, reference)).Returns(true); //act var result = _checksController.DeleteCheck(reference, reference); //assert result.StatusCode.Should().Be(HttpStatusCode.NoContent); _mockChecksService.Verify(x => x.DeleteCheck(reference, reference), Times.Once); } [Test] public void Delete_Check_CheckServiceFails_Returns501InternalServerError() { //arrange const string reference = "ABCD1234"; _mockChecksService.ResetCalls(); _mockChecksService.Setup(x => x.DeleteCheck(reference, reference)).Returns(false); //act var result = _checksController.DeleteCheck(reference, reference); //assert result.StatusCode.Should().Be(HttpStatusCode.InternalServerError); _mockChecksService.Verify(x => x.DeleteCheck(reference, reference), Times.Once); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ClotheOurKids.Model { public interface IWhoWeServeRepository : IDisposable { IList<Office> GetAllOffices(); } }
// <copyright file="Notification.cs" company="Caspian Pacific Tech"> // Copyright (c) Caspian Pacific Tech. All rights reserved. // </copyright> namespace SmartLibrary.Models { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using Infrastructure; using Infrastructure.DataAnnotations; /// <summary> /// This class is used to Define Entity for Table - Notifications /// </summary> /// <CreatedBy>Bhoomi</CreatedBy> /// <CreatedDate>30-Aug-2018</CreatedDate> /// <ModifiedBy></ModifiedBy> /// <ModifiedDate></ModifiedDate> /// <ReviewBy></ReviewBy> /// <ReviewDate></ReviewDate> [Table("Notifications")] public sealed class Notification : BaseModel { #region Properties /// <summary> /// Gets or sets the ID value. /// </summary> [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int ID { get; set; } /// <summary> /// Gets or sets a value indicating whether the IsAdmin UserId belong to Admin or Customer. /// </summary> public bool IsAdmin { get; set; } /// <summary> /// Gets or sets the UserId value. /// </summary> public int? UserId { get; set; } /// <summary> /// Gets or sets the BorrowedBookId value. /// </summary> public int? BorrowedBookId { get; set; } /// <summary> /// Gets or sets the BookId value. /// </summary> public int? BookId { get; set; } /// <summary> /// Gets or sets the SpaceBookingId value. /// </summary> public int? SpaceBookingId { get; set; } /// <summary> /// Gets or sets a value indicating whether the IsRead is enabled. /// </summary> public bool? IsRead { get; set; } /// <summary> /// Gets or sets the NotificationTypeId value. /// </summary> public int? NotificationTypeId { get; set; } /// <summary> /// Gets or sets the NotificationStartDate value. /// </summary> public DateTime? NotificationStartDate { get; set; } /// <summary> /// Gets or sets the NotificationEndDate value. /// </summary> public DateTime? NotificationEndDate { get; set; } /// <summary> /// Gets or sets the CreatedDate value. /// </summary> public DateTime? CreatedDate { get; set; } /// <summary> /// Gets or sets the Title value. /// </summary> [NotMapped] [MappingAttribute(MapName = "Title")] public string Title { get; set; } /// <summary> /// Gets or sets the Description value. /// </summary> [NotMapped] [MappingAttribute(MapName = "Description")] public string Description { get; set; } #endregion } }