text
stringlengths
13
6.01M
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; namespace JeuDuMoulin { /// <summary> /// Interaction logic for Options.xaml /// </summary> public partial class Options : Page { MainWindow mainW; Jeu j; public Options(MainWindow mW, Jeu j) { InitializeComponent(); mainW = mW; this.j = j; } private void bRetourOptions_Click(object sender, RoutedEventArgs e) { mainW.Content = j; } private void bAplliquer_Click(object sender, RoutedEventArgs e) { if (rb1.IsChecked == true) j.setBg(c1.Fill); else if (rb2.IsChecked == true) j.setBg(c2.Fill); else if (rb3.IsChecked == true) j.setBg(c3.Fill); if (rbJ.IsChecked == true) j.setFirst(false); else j.setFirst(true); } } }
using gView.Framework.IO; using gView.Framework.system; namespace gView.Framework.Symbology { public sealed class SymbolCollectionItem : ISymbolCollectionItem, IPersistable { private bool _visible; private ISymbol _symbol; public SymbolCollectionItem(ISymbol symbol, bool visible) { Symbol = symbol; Visible = visible; } public SymbolCollectionItem Clone(CloneOptions options) { if (Symbol != null) { return new SymbolCollectionItem((ISymbol)Symbol.Clone(options), Visible); } else { return new SymbolCollectionItem(null, Visible); } } #region IPersistable Member public string PersistID { get { return null; } } public void Load(IPersistStream stream) { Visible = (bool)stream.Load("visible", false); Symbol = (ISymbol)stream.Load("ISymbol"); } public void Save(IPersistStream stream) { stream.Save("visible", Visible); stream.Save("ISymbol", Symbol); } #endregion #region ISymbolCollectionItem Member public bool Visible { get { return _visible; } set { _visible = value; } } public ISymbol Symbol { get { return _symbol; } set { _symbol = value; } } #endregion } }
using System.Collections; using System.Collections.Generic; using UnityEngine; /// <summary> /// Field of View of the enemies /// </summary> public class FieldOfView : MonoBehaviour { public float viewRadius; [Range(0,360)] public float viewAngle; public LayerMask targetMask; public LayerMask ObstacleMask; [HideInInspector] public List<Transform> visibleTargets = new List<Transform>(); public float meshResolution; public int edgeResolveIterations; public float edgeDistanceThreshold; public MeshFilter viewMeshFilter; Mesh viewMesh; public float fovAngle; private void Start() { viewMesh = new Mesh(); viewMesh.name = "View Mesh"; viewMeshFilter.mesh = viewMesh; StartCoroutine("FindTargetWithDelay", 0.2f); fovAngle = gameObject.transform.localEulerAngles.y; } IEnumerator FindTargetWithDelay (float delay) { while (true) { yield return new WaitForSeconds(delay); FindVisibleTargets(); } } private void LateUpdate() { DrawFieldOfView(); gameObject.transform.localEulerAngles = new Vector3(0, fovAngle, 0); } void FindVisibleTargets() { visibleTargets.Clear(); Collider2D[] targetsInViewRadius = Physics2D.OverlapCircleAll(transform.position, viewRadius, targetMask); for (int i = 0; i < targetsInViewRadius.Length; i++) { Transform target = targetsInViewRadius[i].transform; Vector2 dirToTarget = (target.position - transform.position).normalized; Vector2 vector = new Vector2( Mathf.Sin(transform.eulerAngles.y * Mathf.Deg2Rad) , Mathf.Cos(transform.eulerAngles.y * Mathf.Deg2Rad) ); if (Vector2.Angle( vector , dirToTarget ) < (viewAngle/2)) { float distToTarget = Vector2.Distance(transform.position, target.position); if (!Physics2D.Raycast(transform.position, dirToTarget, distToTarget, ObstacleMask)) { visibleTargets.Add(target); } } } } void DrawFieldOfView() { int stepCount = Mathf.RoundToInt( viewAngle * meshResolution ); float stepAngleSize = viewAngle / stepCount; List<Vector2> viewPoints = new List<Vector2>(); ViewCastInfo oldViewCast = new ViewCastInfo(); for (int i = 0; i <= stepCount; i++) { float angle = transform.eulerAngles.y - viewAngle / 2 + stepAngleSize * i; //Debug.DrawLine(transform.position, transform.position + DirFromAngle(angle, true) * viewRadius, Color.red); ViewCastInfo newViewCast = ViewCast(angle); if (i > 0) { bool edgeDistanceThresholdExceeded = Mathf.Abs(oldViewCast.dist - newViewCast.dist) > edgeDistanceThreshold; if (oldViewCast.hit != newViewCast.hit || (oldViewCast.hit && newViewCast.hit && edgeDistanceThresholdExceeded)) { EdgeInfo edge = FindEdge(oldViewCast, newViewCast); if (edge.pointA != Vector2.zero) { viewPoints.Add(edge.pointA); } if(edge.pointB != Vector2.zero) { viewPoints.Add(edge.pointB); } } } viewPoints.Add(newViewCast.point); oldViewCast = newViewCast; } int vertexCount = viewPoints.Count + 1; Vector3[] vertices = new Vector3[vertexCount]; int[] triangles = new int[(vertexCount - 2) * 3]; vertices[0] = Vector3.zero; for(int i = 0; i < vertexCount - 1; i++) { vertices[i + 1] = transform.InverseTransformPoint(viewPoints[i]); if (i < vertexCount - 2) { triangles[i * 3] = 0; triangles[i * 3 + 1] = i + 1; triangles[i * 3 + 2] = i + 2; } } viewMesh.Clear(); viewMesh.vertices = vertices; viewMesh.triangles = triangles; viewMesh.RecalculateNormals(); } EdgeInfo FindEdge(ViewCastInfo minViewCast, ViewCastInfo maxViewCast) { float minAngle = minViewCast.angle; float maxAngle = maxViewCast.angle; Vector2 minPoint = Vector2.zero; Vector2 maxPoint = Vector2.zero; for (int i = 0; i < edgeResolveIterations; i++) { float angle = (minAngle + maxAngle) / 2; ViewCastInfo newViewCast = ViewCast(angle); bool edgeDistanceThresholdExceeded = Mathf.Abs(minViewCast.dist - newViewCast.dist) > edgeDistanceThreshold; if (newViewCast.hit == minViewCast.hit && !edgeDistanceThresholdExceeded) { minAngle = angle; minPoint = newViewCast.point; } else { maxAngle = angle; maxPoint = newViewCast.point; } } return new EdgeInfo(minPoint, maxPoint); } ViewCastInfo ViewCast(float globalAngle) { Vector3 dir = DirFromAngle(globalAngle, true); RaycastHit hit; if (Physics.Raycast(transform.position, dir, out hit, viewRadius, ObstacleMask)) { return new ViewCastInfo(true, hit.point, hit.distance, globalAngle); } else { return new ViewCastInfo(false, transform.position + dir * viewRadius, viewRadius, globalAngle); } } public Vector3 DirFromAngle(float angleInDegrees, bool angleIsGlobal) { if (!angleIsGlobal) { angleInDegrees += transform.eulerAngles.y; } float sin = Mathf.Sin(angleInDegrees * Mathf.Deg2Rad); float cos = Mathf.Cos(angleInDegrees * Mathf.Deg2Rad); return new Vector3(sin, cos , 0); } public struct ViewCastInfo { public bool hit; public Vector2 point; public float dist; public float angle; public ViewCastInfo(bool hit, Vector2 point, float dist, float angle) { this.hit = hit; this.point = point; this.dist = dist; this.angle = angle; } } public struct EdgeInfo { public Vector2 pointA; public Vector2 pointB; public EdgeInfo(Vector2 pointA, Vector2 pointB) { this.pointA = pointA; this.pointB = pointB; } } }
namespace Ach.Fulfillment.Data.Specifications { using System; using System.Linq.Expressions; using Ach.Fulfillment.Data.Common; public class AchFileRejected : SpecificationBase<AchFileEntity> { public override Expression<Func<AchFileEntity, bool>> IsSatisfiedBy() { return m => m.FileStatus == AchFileStatus.Rejected; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using FoodSupplementsSystem.Data.Repositories; using FoodSupplementsSystem.Data.Contracts; namespace FoodSupplementsSystem.Data { public class UnitOfWork : IUnitOfWork, IDisposable { private readonly FoodSupplementsSystemDbContext context; private SupplementRepository supplementRepository; private bool disposed = false; public UnitOfWork(FoodSupplementsSystemDbContext context) { if (context == null) { throw new ArgumentNullException("An instance of DbContext is required to use this UnitOfWork.", "context"); } this.context = context; } public SupplementRepository SupplementRepository { get { if (this.supplementRepository == null) { this.supplementRepository = new SupplementRepository(this.context); } return this.supplementRepository; } } public void Save() { this.context.SaveChanges(); } protected virtual void Dispose(bool disposing) { bool isDisposed = this.disposed; if (!isDisposed) { if (disposing) { this.context.Dispose(); } } this.disposed = true; } public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } } }
using Compent.LinkPreview.HttpClient; using System; using System.Configuration; namespace Uintra.Features.LinkPreview.Configurations { public class LinkPreviewConfiguration : ILinkPreviewConfiguration { private const string SectionName = "linkPreviewServiceUri"; public Uri ServiceUri => new Uri(ConfigurationManager.AppSettings[SectionName]); } }
using System; namespace ReactData.Models { public class User { public int ID { get; set; } public DateTime DateRegistration { get; set; } public DateTime DateLastActivity { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Anywhere2Go.Business.Master; using Anywhere2Go.DataAccess.Entity; using Claimdi.Web.TH.Filters; using Anywhere2Go.DataAccess.Object; using System.IO; using System.Drawing; using Claimdi.Web.TH.Helper; using Anywhere2Go.DataAccess; namespace Claimdi.Web.TH.Controllers { public class InsurerController : Controller { int systemAdmin = Constant.Permission.SystemAdmin; Guid ClaimdiApp = new Guid(Constant.CompanyId.ClaimDi); // GET: MasterData [AuthorizeUser(AccessLevel = "View", PageAction = "Insurer")] public ActionResult index() { InsurerLogic insurer = new InsurerLogic(); var result = insurer.getInsurer(); return View(result); } [AuthorizeUser(AccessLevel = "Add", PageAction = "Insurer")] public ActionResult Create() { var auth = ClaimdiSessionFacade.ClaimdiSession; CompanyController compCon = new CompanyController(); //default bike company var companys = compCon.GetDropDownCompanyIns(auth.com_id); if (companys != null && companys.Count > 1) { companys[1].Selected = true; } ViewBag.Companys = companys; ViewBag.InsurerGroupList = GetInsurerRateGroup(); DashboardController dash = new DashboardController(); ViewBag.Departments = dash.GetDropDownDashboardDepartment(auth.com_id); return View("CreateEdit", new Insurer() { isActive = true, sort = 99, isContact = true }); } [AuthorizeUser(AccessLevel = "Edit", PageAction = "Insurer")] public ActionResult Edit(string id) { InsurerLogic insurer = new InsurerLogic(); var data = insurer.getInsurer(id).SingleOrDefault(); var auth = ClaimdiSessionFacade.ClaimdiSession; CompanyController compCon = new CompanyController(); //default bike company List<SelectListItem> companys = null; if (auth.Role.roleId==Constant.Permission.SystemAdmin) { companys = compCon.GetDropDownCompany(); } else { companys = compCon.GetDropDownCompanyIns(auth.com_id); } if (companys != null && companys.Count > 1) { var selected = companys.Where(x => x.Value == auth.com_id.ToString()).First(); selected.Selected = true; } ViewBag.Companys = companys; ViewBag.InsurerGroupList = GetInsurerRateGroup(); ViewBag.InsurerGroupList = GetInsurerRateGroup(); DashboardController dash = new DashboardController(); ViewBag.Departments = dash.GetDropDownDashboardDepartment(auth.com_id); return View("CreateEdit", data); } [HttpPost] [AuthorizeUser(AccessLevel = "Edit", PageAction = "Insurer")] public ActionResult CreateEdit(Insurer model) { if (ModelState.IsValid) { var auth = ClaimdiSessionFacade.ClaimdiSession; InsurerLogic ins = new InsurerLogic(); #region Outsource Dept Sorting var comId = Request.Form.GetValues("item.comId"); var depId = Request.Form.GetValues("item.depId"); var sort = Request.Form.GetValues("item.sort"); //var description = Request.Form.GetValues("item.description"); if (comId != null && comId.Length > 0) { model.InsurerDepConfig = new List<InsurerDepConfig>(); for (int i = 0; i < comId.Length; i++) { model.InsurerDepConfig.Add(new InsurerDepConfig { comId = (!string.IsNullOrEmpty(comId[i]) ? Guid.Parse(comId[i]) : new Guid()), depId = depId[i], sort = (!string.IsNullOrEmpty(sort[i]) ? Convert.ToInt32(sort[i]) : 0), insId = model.InsID }); } } #endregion #region InsuranceDept var insDeptId = Request.Form.GetValues("item.InsurerDepartmentId"); var insDeptName = Request.Form.GetValues("item.InsurerDepartmentName"); var insDeptDesc = Request.Form.GetValues("item.InsurerDepartmentDesc"); var insDeptSort = Request.Form.GetValues("item.InsDeptSort"); var insDeptIsActive = Request.Form.GetValues("item.insDeptIsActive"); //var description = Request.Form.GetValues("item.description"); if (insDeptName != null && insDeptName.Length > 0) { model.InsurerDepartments = new List<InsurerDepartment>(); for (int i = 0; i < insDeptName.Length; i++) { model.InsurerDepartments.Add(new InsurerDepartment { InsurerDepartmentId = int.Parse(insDeptId[i]), InsurerDepartmentName = (!string.IsNullOrEmpty(insDeptName[i]) ? (insDeptName[i]).ToString() : ""), InsurerDepartmentDesc = (!string.IsNullOrEmpty(insDeptDesc[i]) ? (insDeptDesc[i]).ToString() : ""), IsActive = (!string.IsNullOrEmpty(insDeptIsActive[i]) ?(insDeptIsActive[i].ToString()=="1"?true:false) : false), InsId = model.InsID, Sort = (!string.IsNullOrEmpty(insDeptSort[i]) ? Convert.ToInt32(insDeptSort[i]) : 99), }); } } #endregion #region AccountProfile string directoryPath = Server.MapPath("~/Logos/insurer"); if (!Directory.Exists(directoryPath)) { Directory.CreateDirectory(directoryPath); } var res = ins.saveInsurer(model, auth); if (!string.IsNullOrEmpty(model.logo) && model.logo.IndexOf("TempUpload") >= 0) { string oldPath = Server.MapPath(model.logo); var file = Image.FromFile(oldPath); string fileName = res.Result + Path.GetExtension(oldPath); string newPath = Path.Combine(directoryPath, fileName); file.Save(newPath); string logo = "Logos/insurer" + "/" + fileName; model.logo = logo; ins.saveInsurer(model, (Authentication)Session[Configurator.SessionUserAuthen]); } if (res.StatusCode == "200") { //return RedirectToAction("Index"); ViewBag.Message = "success"; } else { ViewBag.Message = res.Message; } #endregion #region InsurerRate #endregion #region GetDataView CompanyController compCon = new CompanyController(); //default bike company List<SelectListItem> companys = null; if (auth.Role.roleId == Constant.Permission.SystemAdmin) { companys = compCon.GetDropDownCompany(); } else { companys = compCon.GetDropDownCompanyIns(auth.com_id); } if (companys != null && companys.Count > 1) { var selected = companys.Where(x => x.Value == auth.com_id.ToString()).First(); selected.Selected = true; } ViewBag.Companys = companys; ViewBag.InsurerGroupList = GetInsurerRateGroup(); DashboardController dash = new DashboardController(); ViewBag.Departments = dash.GetDropDownDashboardDepartment(auth.com_id); #endregion } return View(model); } public List<SelectListItem> GetInsurerRateGroup() { InsurerRateLogic insurerRate = new InsurerRateLogic(); List<SelectListItem> ls = new List<SelectListItem>(); var insRateGroup = insurerRate.GetInsurerRateGroup(); ls.Add(new SelectListItem() { Text = "กลุ่มราคา", Value = "" }); foreach (var temp in insRateGroup) { ls.Add(new SelectListItem() { Text = temp.InsurerRateGroupName, Value = temp.InsurerRateGroupId.ToString() }); } return ls; } } }
namespace WinAppDriver { using System.Collections.Generic; using System.IO; using System.Text; using WinAppDriver.UAC; internal abstract class AppInstaller<T> : IPackageInstaller where T : IApplication { private static ILogger logger = Logger.GetLogger("WinAppDriver"); private T app; private IDriverContext context; private IUtils utils; private bool prepared = false; public AppInstaller(IDriverContext context, T app, IUtils utils) { this.context = context; this.app = app; this.utils = utils; } private string CurrentFile { get { return Path.Combine(this.context.GetAppWorkingDir(this.app), "Current.txt"); } } private string PackageDir { get { return Path.Combine(this.context.GetAppWorkingDir(this.app), "InstallationPackage"); } } private string PackageInfoFile { get { return Path.Combine(this.PackageDir, "Info.txt"); } } public bool IsBuildChanged() { string currentChecksum; if (!this.TryReadCurrent(out currentChecksum)) { logger.Info( "Build changed, because current build (checksum) is unknown; app = [{0}]", this.app.DriverAppID); return true; } string cachedChecksum; string package = this.PrepareInstallationPackage(out cachedChecksum); bool changed = currentChecksum != cachedChecksum; logger.Info( "Build changed? {0}; app = [{1}], current checksum = [{2}], cached checksum = [{3}]", changed, this.app.DriverAppID, currentChecksum, cachedChecksum); return changed; } public void Install() { string checksum; string package = this.PrepareInstallationPackage(out checksum); this.InstallImpl(package, checksum); this.UpdateCurrent(checksum); System.Threading.Thread.Sleep(5000); // TODO avoid timing issue, esp. for store apps } protected internal abstract void InstallImpl(string package, string checksum); protected internal void UpdateCurrent(string checksum) { string path = this.CurrentFile; checksum = checksum.ToLower(); logger.Debug("Update current build (checksum); app = [{0}], checksum = [{1}]", this.app.DriverAppID, checksum); File.WriteAllText(path, checksum); } private bool TryReadCurrent(out string checksum) { string path = this.CurrentFile; logger.Debug("Current file: [{0}]; app = [{1}]", path, this.app.DriverAppID); if (!File.Exists(path)) { logger.Debug("Current file does not exist."); checksum = null; return false; } checksum = File.ReadAllText(path); logger.Debug("Current build (checksum): [{0}]", checksum); return true; } private string PrepareInstallationPackage(out string checksum) { string baseDir = this.PackageDir; var caps = this.app.Capabilities; logger.Debug( "Prepare installation package; app = [{0}], base dir = [{1}], caps.App = [{2}], caps.AppChecksum = [{3}]", this.app.DriverAppID, baseDir, caps.App, caps.AppChecksum); string filename; string fullpath; bool cached = this.TryReadCachedPackageInfo(out filename, out checksum); if (this.prepared && cached) { fullpath = Path.Combine(baseDir, filename); logger.Debug( "Alread prepared; path = [{0}], checksum = [{1}]", fullpath, checksum); return fullpath; } // Quick comparison if (caps.AppChecksum != null && cached) { logger.Debug("Checksum matching (case-insensitive); caps.AppChecksum = [{0}], cached checksum = [{1}]", caps.AppChecksum, checksum); fullpath = Path.Combine(baseDir, filename); if (checksum == caps.AppChecksum.ToLower()) { logger.Info( "The cached installation package of app '{0}' ({1}) can be reused, because of matched checksums.", this.app.DriverAppID, fullpath); this.prepared = true; return fullpath; } else { logger.Info( "The cached installation package of app '{0}' ({1}) can not be reused, because of unmatched checksums.", this.app.DriverAppID, fullpath); } } // Download the installation package logger.Info( "Start downloading installation pacakge of app '{0}' from {1}.", this.app.DriverAppID, caps.App); string downloaded = this.utils.GetAppFileFromWeb(caps.App, caps.AppChecksum); filename = Path.GetFileName(downloaded); // TODO Preserve original filename, and replace invalid characters checksum = caps.AppChecksum != null ? caps.AppChecksum.ToLower() : this.utils.GetFileMD5(downloaded); logger.Info("Installation package downloaded: {0} ({1}).", downloaded, checksum); // Discard cached installation package if (Directory.Exists(baseDir)) { Directory.Delete(baseDir, true); } Directory.CreateDirectory(baseDir); // Update cached package information. fullpath = Path.Combine(baseDir, filename); logger.Info("Cache the installation package: {0}.", fullpath); File.Move(downloaded, fullpath); this.WriteCachedPackageInfo(filename, checksum); this.prepared = true; return fullpath; } private bool TryReadCachedPackageInfo(out string filename, out string checksum) { string path = this.PackageInfoFile; logger.Debug("Cached package info file: [{0}]; app = [{1}]", path, this.app.DriverAppID); if (!File.Exists(path)) { logger.Debug("Cached package info file does not exist."); filename = null; checksum = null; return false; } string[] lines = File.ReadAllLines(path, Encoding.UTF8); filename = lines[0]; checksum = lines[1]; logger.Debug("Cached package info: filename = [{0}], checksum = [{1}]", filename, checksum); return true; } private void WriteCachedPackageInfo(string filename, string checksum) { string path = this.PackageInfoFile; string[] lines = { filename, checksum }; logger.Debug( "Write cached package info; app = [{0}], path = [{1}], filename = [{2}], checksum = [{3}]", this.app.DriverAppID, path, filename, checksum); File.WriteAllLines(path, lines, Encoding.UTF8); } } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class Synchronizer { private static Synchronizer m_instance; public event Action OnAllEnemiesDiedEvent; public event Action OnPlayerDiedEvent; private bool m_started = false; public static Synchronizer Instance { get { if (m_instance == null) { m_instance = new Synchronizer(); } return m_instance; } } public static void Start() { Instance.m_started = true; Instance.init(); SynchronizedActor a = Instance.GetNextActorTurn(); if (a != null) { Debug.Log("Actor Found: " + a); a.GiveTurn(); } else { Debug.Log("Null Actor!"); } } private void init() { GameObject player = GameObject.FindGameObjectWithTag("Player"); m_player = player.GetComponent<SynchronizedActor>(); m_actorList.Add(m_player); GameObject[] enemas = GameObject.FindGameObjectsWithTag("Enemy"); foreach (GameObject go in enemas) { SynchronizedActor a = go.GetComponent<SynchronizedActor>(); if (a != null) m_actorList.Add(a); } Debug.Log("Actors loaded from scene: " + m_actorList.Count); } internal static void Reset() { Debug.LogError("Synchronizer Reset!"); Instance.m_player = null; m_instance = null; } public SynchronizedActor Player { get { return m_player; } } //First actor is the player public List<SynchronizedActor> GetActors() { return m_actorList; } private SynchronizedActor m_player; private List<SynchronizedActor> m_actorList = new List<SynchronizedActor>(); private ulong m_time = 0; public static bool IsPlayerTurn { get { return Instance.Player.ActionTime == 0; } } public Synchronizer() { Debug.LogError("Synchronizer Constructed"); } internal static void Continue(SynchronizedActor actor, int actionCost) { if (Instance.m_started) { actor.ActionTime += (ulong)actionCost; actor.EndTurn(); //Debug.Log(actor.name + " Action Complete, Next Action Time: "+actor.ActionTime); SynchronizedActor next = Instance.GetNextActorTurn(); int count = 100; while (next == null && count > 0) { count--; Instance.ForwardTime(); next = Instance.GetNextActorTurn(); } if (count == 0) Debug.LogError("Continue Loop Timeout!"); else { //Debug.Log("Giving Turn to " + next.name); next.GiveTurn(); } } } private void ForwardTime() { if (Instance.m_started) { foreach (SynchronizedActor actor in m_actorList) { //Debug.Log(actor.name + " Next Action ? " + actor.HasNextAction); if (actor.HasNextAction) { actor.ResolveAction(); } } m_time++; //Debug.Log("Time: " + m_time); } } private SynchronizedActor GetNextActorTurn() { if (Instance.m_started) { foreach (SynchronizedActor a in m_actorList) { //Debug.Log(a.name + " AT: " + a.ActionTime + " vs. " + m_time); if ((ulong)a.ActionTime <= m_time) { return a; } } } return null; } internal static void KillEntity(SynchronizedActor actor) { Instance.kill(actor); } private void kill(SynchronizedActor actor) { if (!m_started) return; for (int i = 0; i < m_actorList.Count; i++) { if (actor == m_actorList[i]) { m_actorList.RemoveAt(i); break; } } Entity e = actor.Entity; actor.Entity.GetCell().SetEntity(null); actor.gameObject.SetActive(false); if (e.GetType() == typeof(Player)) { m_player = null; if (OnPlayerDiedEvent != null) { OnPlayerDiedEvent(); } } else if (m_actorList.Count == 1) // only player remains { if (OnAllEnemiesDiedEvent != null) { OnAllEnemiesDiedEvent(); } } } }
namespace UnityAtoms.FSM { /// <summary> /// Action of type `FSMTransitionData`. Inherits from `AtomAction&lt;FSMTransitionData&gt;`. /// </summary> [EditorIcon("atom-icon-purple")] public abstract class FSMTransitionDataAction : AtomAction<FSMTransitionData> { } }
using System; using System.Collections.Generic; using System.Text; using Breeze.AssetTypes; using Breeze.Screens; using Microsoft.Xna.Framework; namespace Breeze.AssetTypes.StaticTemplates { public class CloseButton : StaticTemplate { public new ButtonVisualDescriptor Normal => new ButtonVisualDescriptor() { FontColor = Color.White, BackgroundColor = Color.Red, BorderColor = Color.Red, FontFamily = Solids.Instance.Fonts.MDL2, BorderBrushSize = 0, TextJustification = FontAsset.FontJustification.Left }; public new ButtonVisualDescriptor Hover => new ButtonVisualDescriptor() { FontColor = Color.White, BackgroundColor = Color.Red * 0.7f, BorderColor = Color.Red, FontFamily = Solids.Instance.Fonts.MDL2, BorderBrushSize = 0, TextJustification = FontAsset.FontJustification.Left }; public new ButtonVisualDescriptor Pressing => new ButtonVisualDescriptor() { FontColor = Color.White, BackgroundColor = Color.Green, BorderColor = Color.Red, FontFamily = Solids.Instance.Fonts.MDL2, BorderBrushSize = 0, TextJustification = FontAsset.FontJustification.Left }; public static StaticTemplate Template => new StaticTemplate() { Disabled = new CloseButton().Disabled, Hover = new CloseButton().Hover, Normal = new CloseButton().Normal, Pressing = new CloseButton().Pressing }; } }
using System; using System.Linq; namespace SpaceHosting.Index { public sealed class SparseVector : IVector { public SparseVector(int dimension, int[] columnIndices, double[] coordinates) { if (coordinates.Length != columnIndices.Length) throw new ArgumentException("Can't create sparse vector. Column indices count does not matches values count"); if (columnIndices.Any(i => i >= dimension)) throw new ArgumentException("Can't create sparse vector. Column index is more than vector dimension"); if (columnIndices.Distinct().Count() != columnIndices.Length) throw new ArgumentException("Can't create sparse vector. Column indices have duplicates"); Dimension = dimension; ColumnIndices = columnIndices; Coordinates = coordinates; } public int Dimension { get; } public int[] ColumnIndices { get; } public double[] Coordinates { get; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MIDIDotNet { public delegate void NoteOnDelegate(byte note, byte velocity); public delegate void NoteOffDelegate(byte note, byte velocity); public class GMInDevice : IInDevice, IDisposable { IInDevice inDevice; NoteOnDelegate noteOnDelegate = null; NoteOffDelegate noteOffDelegate = null; HandleDataDelegate otherHandleDataDelegate = null; public GMInDevice(IInDevice inDevice) { this.inDevice = inDevice; inDevice.HandleDataDelegate = new HandleDataDelegate(this.HandleData); } #region IDisposable public void Dispose() { } #endregion #region IInDevice public string DeviceName { get { return inDevice.DeviceName;} } public bool IsOpen { get { return inDevice.IsOpen; } } public bool IsStarted { get { return inDevice.IsStarted; } } public HandleDataDelegate HandleDataDelegate { set { otherHandleDataDelegate = value; } } public void Open() { inDevice.Open(); } public void Close() { inDevice.Close(); } public void Start() { inDevice.Start(); } public void Stop() { inDevice.Stop(); } #endregion public NoteOnDelegate NoteOnDelegate { set { noteOnDelegate = value; } } public NoteOffDelegate NoteOffDelegate { set { noteOffDelegate = value; } } public void HandleData(IntPtr dwParam1, IntPtr dwParam2) { uint param1 = (uint)dwParam1; uint param2 = (uint)dwParam2; byte status = (byte)(param1 & 0xff); byte data1 = (byte)((param1 >> 8) & 0xff); byte data2 = (byte)((param1 >> 16) & 0xff); if (status == 0x90 && noteOnDelegate != null) { noteOnDelegate(data1, data2); return; } if (status == 0x80 && noteOffDelegate != null) { noteOffDelegate(data1, data2); return; } if (otherHandleDataDelegate != null) { otherHandleDataDelegate(dwParam1, dwParam2); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web.Profile; using System.Web.Security; namespace ZC_IT_TimeTracking.Services { public class UserProfile : ProfileBase { [SettingsAllowAnonymous(false)] public string FirstName { get { return base["FirstName"] as string; } set { base["FirstName"] = value; } } [SettingsAllowAnonymous(false)] public string LastName { get { return base["LastName"] as string; } set { base["LastName"] = value; } } public static UserProfile GetUserProfile(string userName) { return Create(userName) as UserProfile; } public static UserProfile GetUserProfile() { return Create(Membership.GetUser().UserName) as UserProfile; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace QLBSX_DAL_WS.Memento { public class MemoryKTB { private MementoKTB _memento; public MementoKTB Memento { get { return _memento; } set { _memento = value; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CommandDesignPattern { public class Close : IExecuter { public void Execute() { Console.WriteLine("Close"); } } }
using System; using System.IO; using MyWebServer.Enums; using MyWebServer.Models; namespace MyWebServer { public static class HttpResponseBuilder { public static HttpResponse InternalServerError() { var page500 = File.ReadAllText("500.html"); var header = new Header(HeaderType.HttpResponse); var response = new HttpResponse() { StatusCode = ResponseStatusCode.InternalServerError, Header = header, ContentAsUTF8 = page500 }; return response; } public static HttpResponse NotFound() { var page401 = File.ReadAllText("401.html"); var header = new Header(HeaderType.HttpResponse); var response = new HttpResponse() { StatusCode = ResponseStatusCode.NotFound, Header = header, ContentAsUTF8 = page401 }; Console.WriteLine("-RESPONSE-----------------------------"); Console.WriteLine(response); Console.WriteLine("------------------------------"); return response; } } }
using UnityEngine; using System.Collections; public class DebugGuiManager : MonoBehaviour { public Font FontReplaceSmall = null; public Font FontReplaceLarge = null; private int StereoSpreadX = -40; // Spacing for scenes menu private int StartX = 240; private int StartY = 300; private int WidthX = 300; private int WidthY = 50; private bool isGuiOn = false; private string controllerName = "Name has not been initialized"; private PlayerManager playerManager; private PlayerController activeController; // Use this for initialization void Start () { playerManager = GameObject.Find("PlayerManager").GetComponent<PlayerManager>(); activeController = playerManager.GetActivePlayer().GetComponent<PlayerController>(); controllerName = activeController.GetControllerName(); } // Update is called once per frame void Update () { if(Input.GetKeyDown(KeyCode.Z)){ isGuiOn = !isGuiOn; } } void OnGUI(){ if(!isGuiOn){ return; } //GUI.Button (new Rect (10,10,150,100), "I am a button"); GUIStereoBox (StartX, StartY, WidthX, WidthY, ref controllerName, Color.yellow); } // GUIStereoBox - Values based on pixels in DK1 resolution of W: (1280 / 2) H: 800 void GUIStereoBox(int X, int Y, int wX, int wY, ref string text, Color color) { float ploLeft = 0, ploRight = 0; float sSX = (float)Screen.width / 1280.0f; float sSY = ((float)Screen.height / 800.0f); OVRDevice.GetPhysicalLensOffsets(ref ploLeft, ref ploRight); int xL = (int)((float)X * sSX); int sSpreadX = (int)((float)StereoSpreadX * sSX); int xR = (Screen.width / 2) + xL + sSpreadX - // required to adjust for physical lens shift (int)(ploLeft * (float)Screen.width / 2); int y = (int)((float)Y * sSY); GUI.contentColor = color; int sWX = (int)((float)wX * sSX); int sWY = (int)((float)wY * sSY); // Change font size based on screen scale if(Screen.height > 800) GUI.skin.font = FontReplaceLarge; else GUI.skin.font = FontReplaceSmall; GUI.Box(new Rect(xL, y, sWX, sWY), text); GUI.Box(new Rect(xR, y, sWX, sWY), text); } public void SetNewActivePlayer(GameObject activePlayerGO){ activeController = activePlayerGO.GetComponent<PlayerController>(); controllerName = activeController.GetControllerName(); print(controllerName); } }
using System; using System.Collections.Generic; namespace Sfa.Poc.ResultsAndCertification.CsvHelper.Domain.Models { public partial class TqRegistrationProfile : BaseEntity { public TqRegistrationProfile() { TqRegistrationPathways = new HashSet<TqRegistrationPathway>(); } public int UniqueLearnerNumber { get; set; } public string Firstname { get; set; } public string Lastname { get; set; } public DateTime DateofBirth { get; set; } public virtual ICollection<TqRegistrationPathway> TqRegistrationPathways { get; set; } } }
namespace GitHubExplorer.Entities { public class Settings { public string GitHubBaseUrl { get; set; } } }
using Microsoft.VisualStudio.TestTools.UnitTesting; namespace ReversingIntegers { [TestClass] public class TestReversingIntegers { [TestMethod] public void TestMethod1() { Assert.AreEqual(12345, ReverseTheInteger.Reverse(54321)); } [TestMethod] public void TestMethod2() { Assert.AreEqual(6862, ReverseTheInteger.Reverse(2686)); } [TestMethod] public void TestMethod3() { Assert.AreEqual(1, ReverseTheInteger.Reverse(1)); } [TestMethod] public void TestMethod4() { Assert.AreEqual(92, ReverseTheInteger.Reverse(29)); } } }
using NHibernate.Cfg; using NHibernate.DataAnnotations.Tests.Model; using NHibernate.Session; using NHibernate.Tool.hbm2ddl; using NUnit.Framework; namespace NHibernate.DataAnnotations.Tests { [TestFixture] public class When_using_session_auditor { private readonly Marshaler _currentScope; public When_using_session_auditor() { //configure NHibernate var config = new Configuration(); config.AddClass(typeof(Cat)); //create the database var tool = new SchemaExport(config); tool.Execute(false, true, false); //initialize context _currentScope = new Marshaler(config, typeof(ValidationInterceptor)); } [Test] public void Can_validate_a_simple_property() { var cat = new Cat {Name = "Beetlejuice", Gender = "F"}; try { var session = _currentScope.CurrentSession; session.SaveOrUpdate(cat); Assert.IsFalse(session.GetValidator().IsValid()); var results = session.GetValidator().GetValidationResults(); Assert.AreEqual(1, results.Count); Assert.AreEqual(1, results[cat].Count); Assert.AreEqual(Pet.NameLengthValidation, results[cat][0].ErrorMessage); session.GetValidator().Eval(session.Transaction, false); } finally { _currentScope.End(); } } [Test] public void IValidatableObject__is_invoked() { var cat = new Cat { Name = "Fluffy", Gender = "F" }; try { var session = _currentScope.CurrentSession; session.SaveOrUpdate(cat); for (var i = 0; i < 16; i++) { var kitten = new Cat { Name = string.Format("Baby{0}", i), Gender = "F" }; cat.Kittens.Add(kitten); } Assert.IsFalse(session.GetValidator().IsValid()); var results = session.GetValidator().GetValidationResults(); Assert.AreEqual(1, results.Count); Assert.AreEqual(1, results[cat].Count); Assert.AreEqual(Pet.TooManyKittens, results[cat][0].ErrorMessage); session.GetValidator().Eval(session.Transaction, false); } finally { _currentScope.End(); } } [Test] public void A_persistence_context_is_provided_to_IValidatableObject() { var cat = new Cat { Name = "Fluffy", Gender = "F" }; try { var session = _currentScope.CurrentSession; session.SaveOrUpdate(cat); session.Flush(); session.Delete(cat); Assert.IsFalse(session.GetValidator().IsValid()); var results = session.GetValidator().GetValidationResults(); Assert.AreEqual(1, results.Count); Assert.AreEqual(1, results[cat].Count); Assert.AreEqual(Cat.CatsHaveNineLives, results[cat][0].ErrorMessage); session.GetValidator().Eval(session.Transaction, false); } finally { _currentScope.End(); } } [Test] public void Validation_can_be_cascaded_to_entity_components() { var cat = new Cat { Name = "Fluffy", Gender = "F" }; try { var session = _currentScope.CurrentSession; session.SaveOrUpdate(cat); cat.Toy = new BallOfYarn { IsUsedForSewing = true }; Assert.IsFalse(session.GetValidator().IsValid()); var results = session.GetValidator().GetValidationResults(); Assert.AreEqual(1, results.Count); Assert.AreEqual(1, results[cat].Count); Assert.AreEqual(BallOfYarn.NotForPlayingValidation, results[cat][0].ErrorMessage); session.GetValidator().Eval(session.Transaction, false); } finally { _currentScope.End(); } } [Test] public void Can_persist_a_cat_hierarchy() { //arrange var grannyCat = new Cat { Name = "Granny", Gender = "F" }; var mommyCat = new Cat { Name = "Mommy", Gender = "F" }; var babyCat = new Cat { Name = "Baby", Gender = "F" }; try { var session = _currentScope.CurrentSession; session.SaveOrUpdate(grannyCat); grannyCat.Kittens.Add(mommyCat); mommyCat.Parent = grannyCat; mommyCat.Kittens.Add(babyCat); babyCat.Parent = mommyCat; _currentScope.Commit(); } finally { _currentScope.End(); } //act try { var session = _currentScope.CurrentSession; babyCat = session.Get<Cat>(babyCat.Id); babyCat.Parent.Parent.Name = "Gramma"; var siblingCat = new Cat { Name = "Sibling", Gender = "F" }; babyCat.Parent.Kittens.Add(siblingCat); siblingCat.Parent = babyCat.Parent; _currentScope.Commit(); } finally { _currentScope.End(); } //assert try { var session = _currentScope.CurrentSession; babyCat = session.Get<Cat>(babyCat.Id); //assert persistence Assert.AreEqual(2, babyCat.Parent.Kittens.Count); Assert.AreEqual("Gramma", babyCat.Parent.Parent.Name); } finally { _currentScope.End(); } } } }
using System.Collections.Generic; using System.Threading.Tasks; namespace WebApplication1.DataAccess { public interface IRepository<T> { T Add(T model); T Update(T model); Task<T> FindAsync<TInput>(TInput id); Task DeleteAsync<TInput>(TInput id); Task<IList<T>> AllAsync(); } }
using System; using System.Drawing; using System.Collections.Generic; using PopulationWars.Map; using PopulationWars.Utilities; using static PopulationWars.Utilities.Constants; namespace PopulationWars.Mechanics { public class Game { public List<Player> Players { get; set; } public World Map { get; set; } public Gameplay Gameplay { get; } public Settings Settings { get; } public Game(Settings settings, List<Player> players = null) { Players = players ?? new List<Player>(); Map = new World(settings); Settings = settings; Gameplay = new Gameplay(settings.GameDuration, settings.PopulationGrowthRate, Players, Map); } public void AddPlayer(Player player) { Players.Add(player); } public void RemovePlayer(Player player) { Players.Remove(player); } public void StartGame(Action<Tuple<int, int>, Color, int> tileUpdateAction, Action<Tuple<int, int>> environmentLoadAction, Action gameResultShowAction, Action<bool> humanPlayerMoveRequestAction, GameType gameType) { if (gameType == GameType.Normal) { Gameplay.SetActions(tileUpdateAction, environmentLoadAction, gameResultShowAction, humanPlayerMoveRequestAction); } else { Gameplay.SetActions((a, b, c) => { }, (a) => { }, gameResultShowAction, (a) => { }); } Gameplay.CreateInitialColonies(); Gameplay.Play(); } } }
namespace BoardGame.CardModelFromDatabase { public partial class PropertyCard { public override string ToString() { return "Lelet: " + PropertyName + ", Ár: " + PropertyValue + ", Jövedelem: " + PropertyFinishedValue; } } }
// // ProviderRepository.cs // // Author: // nofanto ibrahim <nofanto.ibrahim@gmail.com> // // Copyright (c) 2011 sejalan // // This library is free software; you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as // published by the Free Software Foundation; either version 2.1 of the // License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA using System; using System.Configuration; namespace Sejalan.Framework.Provider.AppConfig { public class ProviderRepository : ProviderRepositoryBase { public ProviderRepository () { } public override ProviderRepositoryInfo GetProviderRepositoryInfo (string providerFactoryKey) { if (String.IsNullOrEmpty(providerFactoryKey)) { throw new ArgumentNullException("providerFactoryKey"); } ProviderConfigurationSectionHandler _ProviderConfigurationSectionHandler = (ProviderConfigurationSectionHandler)ConfigurationManager.GetSection(providerFactoryKey); ProviderRepositoryInfo result = new ProviderRepositoryInfo(); result.DefaultProviderName = _ProviderConfigurationSectionHandler.DefaultProviderName; foreach (ProviderSettings item in _ProviderConfigurationSectionHandler.Providers.Values) { result.ProviderSettings.Add(item); } return result; } public override void SaveProviderRepositoryInfo (string providerFactoryKey, ProviderRepositoryInfo providerRepositoryInfo) { //TODO: implement save provider info to app config file. throw new System.NotImplementedException(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using Microsoft.Azure.Documents; using Microsoft.Azure.Documents.Client; using NinjaStore.Common.Models; namespace NinjaStore.Common.Repositories { public class ProductRepository { #region Data Members private readonly DocumentClient _documentClient; private readonly DocumentDbSettings _documentDbSettings; #endregion #region Constructors public ProductRepository(DocumentDbSettings settings) { // Save the document db settings into a private data member and // instantiate an instance of the client. _documentDbSettings = settings; _documentClient = new DocumentClient(new Uri(_documentDbSettings.Endpoint), _documentDbSettings.AuthKey); } public ProductRepository() : this(DocumentDbSettings.GetDbSettings()) { } #endregion #region Public Methods public async Task Initialize() { await CreateDatabaseIfNotExistsAsync(); await CreateCollectionIfNotExistsAsync(); var ninjaStar = new Product() { Id = "1", Count = 5, Name = "Ninja Stars", Price = 5.99}; CreateProductDocumentIfNotExists(ninjaStar).Wait(); var sword = new Product() { Id = "2", Count = 12, Name = "Sword", Price = 199.99 }; CreateProductDocumentIfNotExists(sword).Wait(); var nunchucks = new Product() { Id = "3", Count = 12, Name = "Nunchucks", Price = 24.79 }; CreateProductDocumentIfNotExists(nunchucks).Wait(); } public List<Product> GetAllProducts() { var results = _documentClient.CreateDocumentQuery<Product>(this.CollectionUri); return results.ToList(); } public Product GetProductById(string productId) { var queryOptions = new FeedOptions { MaxItemCount = -1 }; var query = _documentClient.CreateDocumentQuery<Product>(this.CollectionUri, queryOptions) .Where(p => p.Id.ToLower() == productId.ToLower()).ToList(); return query.FirstOrDefault(); } public async Task CreateProduct(Product product) { await _documentClient.CreateDocumentAsync(this.CollectionUri, product); } public async Task DeleteProduct(string id) { await _documentClient.DeleteDocumentAsync(UriFactory.CreateDocumentUri(_documentDbSettings.DatabaseId, _documentDbSettings.CollectionId, id)); } public async Task UpdateProduct(Product product) { // Check to see if the product exist var existingProduct = GetProductById(product.Id); if (existingProduct != null) { await _documentClient.UpsertDocumentAsync( UriFactory.CreateDocumentCollectionUri(_documentDbSettings.DatabaseId, _documentDbSettings.CollectionId), product); } } #endregion #region Properties private Uri CollectionUri => UriFactory.CreateDocumentCollectionUri(_documentDbSettings.DatabaseId, _documentDbSettings.CollectionId); #endregion #region Private Methods private async Task CreateDatabaseIfNotExistsAsync() { try { var databaseUri = UriFactory.CreateDatabaseUri(_documentDbSettings.DatabaseId); await _documentClient.ReadDatabaseAsync(databaseUri); } catch (DocumentClientException e) { if (e.StatusCode == System.Net.HttpStatusCode.NotFound) { var database = new Database { Id = _documentDbSettings.DatabaseId }; await _documentClient.CreateDatabaseAsync(database); } else { throw; } } } private async Task CreateCollectionIfNotExistsAsync() { try { var collectionUri = UriFactory.CreateDocumentCollectionUri(_documentDbSettings.DatabaseId, _documentDbSettings.CollectionId); await _documentClient.ReadDocumentCollectionAsync(collectionUri); } catch (DocumentClientException e) { if (e.StatusCode == System.Net.HttpStatusCode.NotFound) { var databaseUri = UriFactory.CreateDatabaseUri(_documentDbSettings.DatabaseId); await _documentClient.CreateDocumentCollectionAsync(databaseUri, new DocumentCollection { Id = _documentDbSettings.CollectionId }, new RequestOptions { OfferThroughput = 400 }); } else { throw; } } } private async Task CreateProductDocumentIfNotExists(Product product) { await _documentClient.UpsertDocumentAsync( UriFactory.CreateDocumentCollectionUri(_documentDbSettings.DatabaseId, _documentDbSettings.CollectionId), product); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using ExpressionSerialization; using Northwind; using System.Reflection; using System.Linq.Expressions; using System.Xml.Linq; using System.ServiceModel; namespace NorthwindClient { class Program { static Uri baseAddress = new Uri("http://localhost:8999/"); static void Main(string[] args) { Test1(); Test2(); } static void Test1() { //just create a IQueryable to get the Expression: IQueryable<Customer> queryable = from c in new Query<Customer>() where c.ID != null && c.ID > 5 && c.ID < 10 select c; //serialize: var serializer = CreateSerializer(); XElement xmlExpression = serializer.Serialize(queryable.Expression); //make direct call to WebHttp service and send the Expression as XML //(do not use RemoteProvider). var client = new WebHttpClient<IQueryService>(baseAddress); Customer[] result = client.SynchronousCall<Customer[]>((svc) => svc.ExecuteQuery(xmlExpression)); var count = Enumerable.Count(result); } /// <summary> /// make request with RemoteProvider /// </summary> static void Test2() { var client = new WebHttpClient<IQueryService>(baseAddress); IQueryProvider provider = new RemoteProvider(client); Query<Customer> query = new Query<Customer>(provider); IQueryable<Customer> queryable = from c in ((IQueryable<Customer>)query) where c.ID > 5 && c.ID < 10 select c; List<Customer> results = queryable.ToList(); } static ExpressionSerializer CreateSerializer() { var assemblies = new Assembly[] { typeof(Customer).Assembly, typeof(ExpressionType).Assembly, typeof(IQueryable).Assembly }; var resolver = new TypeResolver(assemblies, new Type[] { typeof(Customer), typeof(Order), typeof(Product), typeof(Supplier), typeof(Shipper) }); //var creator = new QueryCreator(); CustomExpressionXmlConverter queryconverter = new QueryExpressionXmlConverter(creator: null, resolver: resolver); CustomExpressionXmlConverter knowntypeconverter = new KnownTypeExpressionXmlConverter(resolver); ExpressionSerializer serializer = new ExpressionSerializer(resolver, new CustomExpressionXmlConverter[] { queryconverter, knowntypeconverter }); return serializer; //ExpressionSerializer serializer = new ExpressionSerializer() } } }
using BAL; using log4net; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace UILayer { public partial class DeleteEmployee : Form { private static readonly ILog _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); EmployeeManager em = new EmployeeManager(); public DeleteEmployee() { InitializeComponent(); } private void Navbtn_Click(object sender, EventArgs e) { NavigationForm ng = new NavigationForm(); ng.Show(); Hide(); } private void btnDelEmp_Click(object sender, EventArgs e) { int empId = Convert.ToInt32(txtEmpId.Text); em.DeleteEmployeeData(empId); _log.Info("Employee deleted successfully"); } private void btnSearch_Click(object sender, EventArgs e) { int empId = Convert.ToInt32(txtEmpId.Text); if(em.SearchEmployeeData(empId)!=null) { lblSearchData.Text = "Data Found...Do you want to delete this?"; _log.Info("Employee search done..."); } else { lblSearchData.Text = "Data Not Found..."; _log.Info("Employee not found..."); } } } }
namespace MinesweeperLibrary.FillInBoard { public interface IFillInAWholeBoard { void FillInABoard(int grid, char[,] board); } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SecurityPlusUI.Model { public sealed class FifoObservableCollection<T> : IEnumerable<T> { private readonly int capacity; public ObservableCollection<T> Collection { get; set; } public FifoObservableCollection(int capacity) { this.capacity = capacity; this.Collection = new ObservableCollection<T>(); } public IEnumerator<T> GetEnumerator() { return this.Collection.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return this.Collection.GetEnumerator(); } public void Add(T item) { if (this.capacity < this.Collection.Count + 1) { this.Collection.RemoveAt(0); } this.Collection.Add(item); } } }
using Infrostructure.Exeption; namespace DomainModel.Entity.ProductParts { /// <summary> /// ولتاژ /// </summary> public class Voltage { private const decimal MinValue = 0m; public decimal Value { get; private set; } public Voltage(decimal value) { ValidateVoltageValue(value); Value = value; } private void ValidateVoltageValue(decimal value) { if (value < MinValue) throw new InvalidVoltageMeasureValueException(value.ToString()); } } }
using RRExpress.Api.V1.Methods; using RRExpress.AppCommon; using RRExpress.AppCommon.Attributes; namespace RRExpress.ViewModels { [Regist(InstanceMode.Singleton)] public class MessageViewModel : BaseVM { public override string Title { get { return "消息"; } } public int ID { get; set; } public RRExpress.Service.Entity.Message Data { get; set; } protected override void OnActivate() { base.OnActivate(); this.LoadData(); } private async void LoadData() { this.IsBusy = true; var mth = new GetMessage() { ID = this.ID }; this.Data = await ApiClient.ApiClient.Instance.Value.Execute(mth); this.NotifyOfPropertyChange(() => this.Data); this.IsBusy = false; } } }
using System; using System.Diagnostics.CodeAnalysis; namespace EnsureThat { public static class EnsureThatTypeExtensions { public static TypeParam IsInt(this in TypeParam param) { Ensure.Type.IsInt(param.Type, param.Name); return param; } public static TypeParam IsShort(this in TypeParam param) { Ensure.Type.IsShort(param.Type, param.Name); return param; } public static TypeParam IsDecimal(this in TypeParam param) { Ensure.Type.IsDecimal(param.Type, param.Name); return param; } public static TypeParam IsDouble(this in TypeParam param) { Ensure.Type.IsDouble(param.Type, param.Name); return param; } public static TypeParam IsFloat(this in TypeParam param) { Ensure.Type.IsFloat(param.Type, param.Name); return param; } public static TypeParam IsBool(this in TypeParam param) { Ensure.Type.IsBool(param.Type, param.Name); return param; } public static TypeParam IsDateTime(this in TypeParam param) { Ensure.Type.IsDateTime(param.Type, param.Name); return param; } public static TypeParam IsString(this in TypeParam param) { Ensure.Type.IsString(param.Type, param.Name); return param; } public static TypeParam IsOfType(this in TypeParam param, [NotNull] Type expectedType) { Ensure.Type.IsOfType(param.Type, expectedType, param.Name); return param; } public static TypeParam IsNotOfType(this in TypeParam param, Type expectedType) { Ensure.Type.IsNotOfType(param.Type, expectedType, param.Name); return param; } public static TypeParam IsAssignableToType(this in TypeParam param, [NotNull] Type expectedType) { Ensure.Type.IsAssignableToType(param.Type, expectedType, param.Name); return param; } public static TypeParam IsNotAssignableToType(this in TypeParam param, Type expectedType) { Ensure.Type.IsNotAssignableToType(param.Type, expectedType, param.Name); return param; } public static Param<T> IsClass<T>(this in Param<T> param) { Ensure.Type.IsClass(param.Value, param.Name); return param; } public static TypeParam IsClass(this in TypeParam param) { Ensure.Type.IsClass(param.Type, param.Name); return param; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SingleTonDesignPattern { public sealed class SingletonDoubleCheck { private static SingletonDoubleCheck _instance = null; private static readonly object _lock = new object(); public static SingletonDoubleCheck GetInstance() { if (_instance == null) { lock (_lock) { if (_instance == null) { _instance = new SingletonDoubleCheck(); } } } return _instance; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Ecommerce.Data; using Ecommerce.Models; using Microsoft.AspNetCore.Mvc; namespace Ecommerce.Controllers { public class ProductsController : Controller { ApplicationDbContext db; public int PageSize = 6; public ProductsController(ApplicationDbContext db) { this.db = db; } //public IActionResult Index() //{ // return View(); //} //Adding Pagination public ViewResult Index(int category, int productPage = 1) => View(new ProductsListViewModel { Products = db.Products .Where(p => category == 0 || p.CategoryID == category) .OrderBy(p => p.ProductID) .Skip((productPage - 1) * PageSize) .Take(PageSize), PagingInfo = new PagingInfoViewModel { CurrentPage = productPage, ItemsPerPage = PageSize, TotalItems = category == 0 ? db.Products.Count() : db.Products.Where(e => e.CategoryID == category).Count() //TotalItems = db.Products.Count() }, CurrentCategory = category }); public IActionResult Details(int id) { return View(db.Products.Where(x => x.ProductID == id).FirstOrDefault()); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LeetCode { /// <summary> /// 面试金典练习 /// </summary> class OtherTrain { //static void Main(string[] args) //{ // //Console.Write(checkStr01("awqs f")); // //Console.Write(reverseStr("12345")); // //Console.Write(checkStr02("qwer", "rewq")); // //Console.Write(changeStr_ans01("aaabbbcc")); // ListNode h1 = new ListNode(4); // ListNode h2 = new ListNode(5); // ListNode h3 = new ListNode(2); // ListNode h4 = new ListNode(1); // h1.next = h2; // h2.next = h3; // h3.next = h4; // ////removeRepetion(h1); // //Console.Write(findLastIndexVal2(h1, 2)); // h1 = divisionListNode(h1, 3); //int[] nums = { 1, 2, 3 }; //ListNode node = ListNode.CreateFromArrays(nums); //node = reversalListnode(node); // Console.ReadLine(); //} // 判断一棵树是否平衡,任意一个节点,其两颗子树的高度差不超过1 public static bool checkedTreeBalanced(TreeNode root) { if (root == null) return true; int heightDiff = getHeight(root.left) - getHeight(root.right); if (Math.Abs(heightDiff) > 1) return false; else return checkedTreeBalanced(root.left) && checkedTreeBalanced(root.right); } public static int getHeight(TreeNode root) { if (root == null) return 0; return Math.Max(getHeight(root.left), getHeight(root.right)) + 1; } // 翻转链表 public static ListNode reversalListnode(ListNode node) { if (node == null) return node; ListNode res = null; ListNode p = node; while (p != null) { ListNode temp = p.next; p.next = res; res = p; p = temp; } return res; } //删除单链表中的某个节点,你只能访问这个节点 public static Boolean deleteNode(ListNode node) { if (node == null || node.next == null) return false; node.val = node.next.val; node.next = node.next.next; return true; } //以val为基准将链表分割成两部分,所有小于x的节点排在大于或等于x的节点之前 public static ListNode divisionListNode(ListNode head,int val) { ListNode beforeStart = null; ListNode beforeEnd = null; ListNode afterStart = null; ListNode afterEnd = null; while (head != null) { ListNode next = head.next; head.next = null; if (head.val < val) { if (beforeStart == null) { beforeStart = head; beforeEnd = head; } else { beforeEnd.next = head; beforeEnd = head; } } else { if (afterStart == null) { afterStart = head; afterEnd = afterStart; } else { afterEnd.next = head; afterEnd = head; } } head = next; } if (beforeStart != null) { beforeEnd.next = afterStart; return beforeStart; } return head; } // 检查一个字符串的所有字符是否全部都不同 public static bool checkStr01(string str) { while(str.Length > 1) { char c = str[0]; str = str.Remove(0, 1); if (str.Contains(c)) return false; } return true; } //使用散列表解题 public static bool checkStr01_an01(string str) { if (str.Length > 256) return false; bool[] cTab = new bool[256]; for (int i = 0; i < str.Length; i++) { int val = str[i];//直接转ascii码 if (cTab[val]) return false; cTab[val] = true; } return true; } // 翻转一个字符串 public static string reverseStr(string str) { char[] chs = str.ToCharArray(); int len = chs.Length; for (int i = 0; i < len / 2 ; i++) { char temp = chs[i]; chs[i] = chs[len -1 - i];// chs[len -1 - i] = temp; } return new string(chs); } //判断str1重新排列后能否组成str2 public static bool checkStr02(string str1,string str2) { if (str1.Length != str2.Length) return false; List<char> chs = new List<char>(str1); foreach (char c in str2) { if (chs.Contains(c)) chs.Remove(c); else return false; } return true; } //使用数组将一个字符串中的空格替换乘%20,字符串空间足够存放替换后的新字符串 public static string changeEmp(string str) { char[] chs = new char[str.Length]; int index = 0; foreach(char c in str) { if (c == ' ') { chs[index++] = '%'; chs[index++] = '2'; chs[index++] = '0'; } else { chs[index++] = c; } } return new string(chs); } //压缩重复的字符串,如aaabbb->a3b3 public static string changeStr(string str) { char[] chs = new char[str.Length]; int index = 0; for (int i = 0; i < str.Length; i++) { int len = 1; chs[index++] = str[i]; while (i < str.Length-1 && str[i] == str[i+1]) { len++; i++; } chs[index++] = len.ToString()[0]; } if (index == 0) return str; string res = new string(chs); return res.Trim(); } public static string changeStr_ans01(string str) { string mstr = ""; char last = str[0]; int count = 1; for (int i = 0; i < str.Length; i++) { if (str[i] == last) { count++; } else { mstr += last + "" + count; last = str[i]; count = 1; } } return mstr + last + count; } // 去除链表中的重复元素 public static void removeRepetion(ListNode head) { HashSet<int> set = new HashSet<int>(); ListNode t1 = head; ListNode t2 = head.next; set.Add(t1.val); while (t2 != null) { if (set.Contains(t2.val)) { t1.next = t2.next; t1 = t1.next; if (t1 != null) t2 = t1.next; else t2 = null; } else { set.Add(t2.val); t1 = t1.next; t2 = t2.next; } } } //更简单的方式 public static void removeRepetion2(ListNode head) { HashSet<int> set = new HashSet<int>(); ListNode temp = head; ListNode t = null; while (temp != null) { if (set.Contains(temp.val)) { t.next = temp.next; } else { set.Add(temp.val); t = temp; } temp = temp.next; } } //不使用缓冲区 public static void removeRepetion3(ListNode head) { ListNode t1 = head; while (t1 != null) { ListNode t2 = t1; while (t2.next != null) { if (t2.next.val == t1.val) { t2.next = t2.next.next; } else { t2 = t2.next; } } } } //找出链表倒数第k个节点 //递归方式 public static int findLastIndexVal(ListNode n,int k) { if (n == null) return 0; int sum = findLastIndexVal(n.next, k) + 1; if (sum == k) { Console.Write(n.val); } return sum; } //迭代 public static int findLastIndexVal2(ListNode n, int k) { ListNode t1 = n; ListNode t2 = n; int count = 0; while (t2 != null) { if (count >= k) { t1 = t1.next; } //让t2先走k步 t2 = t2.next; count++; } return t1.val; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _11.Checks_the_3rd_bit_of_a_number { class BitwiseCheck { static void Main() { int number = int.Parse(Console.ReadLine()); string result; result = (number & 0x8) != 0 ? "1" : "0"; Console.WriteLine(result); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TP.Entities.ValueObjects.JobViewModels { public class JobAdvRegisterViewModel { [DisplayName("Başlık:"), Required, StringLength(50)] public string adv_title { get; set; } [DisplayName("Açıklama:"), Required, StringLength(4000)] public string adv_desc { get; set; } [DisplayName("Ödül Skor:"), Required] public int AwardScoreValue { get; set; } [DisplayName("Ücret ( ₺ )")] [Required(ErrorMessage = "Price is required")] [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:0.00}")] public decimal price { get; set; } } }
using UnityEngine; using System.Collections; using UnityEngine.EventSystems; public class PointerClicker : MonoBehaviour { GameObject cam; Camera camera; AreaHudManager AHudM; //GameObject MainSpaceStationCenter; Transform MainSpaceSCTrans; Vector3 MSSCOrigPos; public Vector3 CursorToWorld, CursorToDistance; public float ExtensionDist; public float Z_Angle; public bool GENpos,ATTpos,PASpos; // Use this for initialization void Start () { //MainSpaceStationCenter = GameObject.FindGameObjectWithTag (""); AHudM = GameObject.Find ("Sub_AreaSwitch Canvas").GetComponent<AreaHudManager> (); cam = GameObject.FindGameObjectWithTag("MainCamera"); camera = cam.GetComponent<Camera>(); MainSpaceSCTrans = GameObject.FindGameObjectWithTag("MSSC_model").GetComponent<Transform>(); } // Update is called once per frame void Update () { AngleUpdater (); CursorPosUpdater (); CursorIsClose (); } void CursorPosUpdater(){ MSSCOrigPos = new Vector3 (MainSpaceSCTrans.position.x,MainSpaceSCTrans.position.y,0.0f); CursorToWorld = Camera.main.ScreenToWorldPoint (new Vector3(Input.mousePosition.x,Input.mousePosition.y,0.0f)); CursorToDistance = new Vector3(CursorToWorld.x,CursorToWorld.y,0.0f) - MSSCOrigPos; } void CursorIsClose(){ if (CursorToDistance.magnitude <= ExtensionDist && AHudM.LockedIn == false) { if (Z_Angle >= 30 && Z_Angle < 150) { //Debug.Log ("I_H8_My_Generation Faction"); GENpos = true; } else { GENpos = false; } if (Z_Angle >= 150 && Z_Angle < 270) { //Debug.Log("TRIGGERED Faction"); ATTpos = true; } else { ATTpos = false; } if (Z_Angle >= 270 || Z_Angle < 30) { //Debug.Log ("pASSive Faction"); PASpos = true; } else { PASpos = false; } } else if (CursorToDistance.magnitude >= ExtensionDist && AHudM.LockedIn == false) { GENpos = false; ATTpos = false; PASpos = false; } } void AngleUpdater(){ float angleRad = Mathf.Atan2 (CursorToDistance.y, CursorToDistance.x); //TheDrawRay //Debug.DrawRay (Vector3.zero, Quaternion.EulerAngles(0.0f,0.0f,angleRad)*Vector3.right*100.0f, Color.green); Z_Angle = angleRad * Mathf.Rad2Deg; if (Z_Angle < 0) { Z_Angle += 360; } //float angleDegrees } }
using System.Collections; using System.Collections.Generic; using UnityEngine; /// <summary> /// Author: Nathan Hales /// This is scritp gets placed on each credit object and acts as its brain. Adds self culling and movement fuctionality. /// when the objecte rises to the threshold(Y axis point) it destorys its self. /// </summary> public class Credit_AI : MonoBehaviour { [HideInInspector]public float maxHeight = 575f; [HideInInspector] public float speed; // Use this for initialization void Start () { } // Update is called once per frame void Update () { Rise(); } void Rise() { //Stored current position Vector3 newPosistion = transform.position; //Increase the y axis or the stored posistion newPosistion.y += speed*Time.deltaTime; //Assign to the object transform.position = newPosistion; HeightChecker(); } /// <summary> /// Check the height of the object and destroys it if it goes to high. /// </summary> void HeightChecker() { if(transform.position.y >= maxHeight) Destroy(gameObject); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlatformMove : MonoBehaviour { int iterationTime = 200; int currIterTime = 0; Vector3 v = new Vector3(-3, 0, 0); // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { if (currIterTime != iterationTime) { transform.position += Time.deltaTime * v; currIterTime++; } else { v.x *= -1; currIterTime = 0; } } }
using System; using System.Collections.Generic; using Microsoft.Xna.Framework; using Terraria; using Terraria.DataStructures; using Terraria.ID; using Terraria.ModLoader; using Caserraria.Items; namespace Caserraria.Items.Weapons { public class BoomSaw : ModItem { public override void SetStaticDefaults() { DisplayName.SetDefault("Boomsaw"); Tooltip.SetDefault("Lobs a grenade with each swing" + Environment.NewLine + "'Yo dawg we heard you like swords, saws and grenade launchers'"); } public override void SetDefaults() { item.damage = 240; item.melee = true; item.width = 72; item.height = 78; item.useTime = 12; item.useAnimation = 12; item.useStyle = 1; item.knockBack = 2; item.value = 35000000; item.rare = 4; item.UseSound = SoundID.Item1; item.autoReuse = true; item.shoot = 30; item.shootSpeed = 13f; item.expert = true; } public override void AddRecipes() { ModRecipe recipe = new ModRecipe(mod); recipe.AddIngredient(ItemID.LunarBar, 30); if(Caserraria.instance.thoriumLoaded) { recipe.AddIngredient(ModLoader.GetMod("ThoriumMod").ItemType("TerrariumCore"), 10); } if(Caserraria.instance.calamityLoaded) { recipe.AddIngredient(ModLoader.GetMod("CalamityMod").ItemType("MeldiateBar"), 10); } if(Caserraria.instance.cosmeticvarietyLoaded) { recipe.AddIngredient(ModLoader.GetMod("CosmeticVariety").ItemType("Pallasite"), 30); } recipe.AddIngredient(null, "Unknownparts", 1); recipe.AddTile(TileID.LunarCraftingStation); recipe.SetResult(this); recipe.AddRecipe(); } } }
using System.ComponentModel; namespace IconCreator.Core.Domain.Enums { public enum Opties { Niets = 0, Workicons = 1, [Description("Artikel Iconen")] ArtIcon = 2, [Description("Pagina Iconen")] PagIcon = 4, [Description("Directies")] Directies = 8, [Description("Modifiers")] Mdf = 16, [Description("Kleuren")] ColorValues = 32, [Description("PaginaDirekties")] PagDir = 64, } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Web; namespace FacebookClone.Models.Data { [Table("Messages")] public class MessageDto { [Key] public int Id { get; set; } public int From { get; set; } public int To { get; set; } public string Message { get; set; } public DateTime DateSent { get; set; } public bool Read { get; set; } [ForeignKey("From")] public virtual UserDTO FromUsers { get; set; } [ForeignKey("To")] public virtual UserDTO ToUsers { get; set; } } }
using System; using System.Threading.Tasks; namespace ChatServer.HAuthentication { // TODO: Rework authentication to be more universal class HAuthenticator { private AuthenticatorBackend _backend; public HAuthenticator(AuthenticatorBackend backend) { _backend = backend; } public async Task<AuthenticationResponse> TryPasswordAuthenticationTask(HChatClient client, string password) { return new AuthenticationResponse(true, Guid.NewGuid().ToString(), "", "0000"); // TODO: Fix to return actual id } public async Task<AuthenticationResponse> TryTokenAuthenticationTask(HChatClient client, string token) { return new AuthenticationResponse(true, Guid.NewGuid().ToString(), "", "0000"); // TODO: FIx to return actual id } public async Task<bool> DeauthenticateClientTask(HChatClient client) { return true; } } /// <summary> /// Available authentication backends. /// </summary> enum AuthenticatorBackend { SQLite, PostgreSQL, None, } struct AuthenticationResponse { public bool Success; public string Id; public string DisplayName; public string Token; public AuthenticationResponse(bool success, string id, string displayName, string token) { Success = success; Id = id; DisplayName = displayName; Token = token; } } }
using System.Collections.Generic; namespace ostranauts_modding { public class Homeworld { public IList<string> aCondsCitizen { get; set; } public IList<string> aCondsIllegal { get; set; } public IList<string> aCondsResident { get; set; } public int nFoundingYear { get; set; } public string strATCCode { get; set; } public string strColonyName { get; set; } public string strName { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Data { [Serializable()] public class Order { public DateTime Date { get; private set; } public int OrderNumber { get; private set; } public IList<ShoppingItem> Items { get; private set; } public double TotalCost { get; private set; } public Order(ShoppingCart cart, DateTime date, int orderNumber) : this(cart.GetItems(), date, orderNumber) { TotalCost = cart.Total; } public Order(IList<ShoppingItem> items, DateTime date, int orderNumber) { Date = date; OrderNumber = orderNumber; Items = items; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using BrickBreaker.Screens; //multiplayer lose screen by Daniel C namespace BrickBreaker { public partial class LoseScreenMulti : UserControl { Boolean leftArrowDown, downArrowDown, rightArrowDown, upArrowDown, spaceDown, vDown, bDown, nDown; int selected, lastSelected; public LoseScreenMulti() { InitializeComponent(); onStart(); } public void onStart() { if (GameScreenMulti.player1Won) { winnerLabel.Text = "Player 1 wins"; } if (GameScreenMulti.player2Won) { winnerLabel.Text = "Player 2 wins"; } } private void LoseScreenMulti_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e) { lastSelected = selected; switch (e.KeyCode) { case Keys.Left: leftArrowDown = true; break; case Keys.Down: downArrowDown = true; break; case Keys.Right: rightArrowDown = true; break; case Keys.Up: upArrowDown = true; break; case Keys.Space: spaceDown = true; break; case Keys.V: vDown = true; break; case Keys.B: bDown = true; break; case Keys.N: nDown = true; break; default: break; } if (rightArrowDown == true) { if (selected == 2) { selected = 1; } else { selected++; } } if (leftArrowDown == true) { if (selected == 1) { selected = 2; } else { selected--; } } switch (selected) { case 1: playAgainLabel.ForeColor = Color.White; returnToMenuLabel.ForeColor = Color.Red; if (spaceDown == true) { // Goes to the game screen Form form = this.FindForm(); GameScreenMulti gsm = new GameScreenMulti(); gsm.Location = new Point((form.Width - gsm.Width) / 2, (form.Height - gsm.Height) / 2); form.Controls.Add(gsm); form.Controls.Remove(this); } break; case 2: returnToMenuLabel.ForeColor = Color.White; playAgainLabel.ForeColor = Color.Red; if (spaceDown == true) { // Goes to the main menu screen Form form = this.FindForm(); MenuScreen ms = new MenuScreen(); ms.Location = new Point((form.Width - ms.Width) / 2, (form.Height - ms.Height) / 2); form.Controls.Add(ms); form.Controls.Remove(this); } break; } } private void LoseScreenMulti_KeyUp(object sender, KeyEventArgs e) { switch (e.KeyCode) { case Keys.Left: leftArrowDown = false; break; case Keys.Down: downArrowDown = false; break; case Keys.Right: rightArrowDown = false; break; case Keys.Up: upArrowDown = false; break; case Keys.Space: spaceDown = false; break; case Keys.V: vDown = false; break; case Keys.B: bDown = false; break; case Keys.N: nDown = false; break; default: break; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace signalcompiler { class SyntaxAnalyzer { private List<Lexem> CodedTokensList; private LexTable TokensTable; private List<Error> Errors; private Tree.Node CurrentNode; private List<int> AlreadyPassedIdentifier = new List<int>(); private int StackCount = 0; private List<Constant> Constants = new List<Constant>(); public SyntaxAnalyzer(List<Lexem> LexemList, LexTable Table, List<Error> ErrorList) { CodedTokensList = LexemList; TokensTable = Table; Errors = ErrorList; } public Tree Parser() { if (Errors.Count == 0) { return Program(CodedTokensList[0]); } return null; } private Tree Program(Lexem CurrentToken) { var ParsingTree = new Tree { Root = new Tree.Node { LexemType = "Signal program", Value = "", Childrens = new List<Tree.Node>() } }; if(TokensTable.GetToken(CurrentToken.LexemId) == "PROGRAM") { ParsingTree.Root.Childrens.Add(new Tree.Node { LexemType = "Keyword", Value = "Program", Childrens = null }); CurrentToken = CodedTokensList.ElementAt(CodedTokensList.IndexOf(CurrentToken) + 1); if(AddNode(Identifier(CurrentToken))) { ParsingTree.Root.Childrens.Add(CurrentNode); CurrentToken = CodedTokensList.ElementAt(CodedTokensList.IndexOf(CurrentToken) + 1); if (TokensTable.GetToken(CurrentToken.LexemId) == ";") { ParsingTree.Root.Childrens.Add(new Tree.Node { LexemType = "Delimiter", Value = ";", Childrens = null }); CurrentToken = CodedTokensList.ElementAt(CodedTokensList.IndexOf(CurrentToken) + 1); if (AddNode(Block(CurrentToken))) { ParsingTree.Root.Childrens.Add(CurrentNode); CurrentToken = GetStackLexem(CodedTokensList.IndexOf(CurrentToken)); if (TokensTable.GetToken(CurrentToken.LexemId) == ".") { ParsingTree.Root.Childrens.Add(new Tree.Node { LexemType = "Deleimiter", Value = ".", Childrens = null }); return ParsingTree; } Errors.Add(ErrorGenerate(CurrentToken, "'.' expected, but" + TokensTable.GetToken(CurrentToken.LexemId) + " found.")); return null; } Errors.Add(ErrorGenerate(CurrentToken, "Block expected.")); return null; } Errors.Add(ErrorGenerate(CurrentToken, "';' expected, but" + TokensTable.GetToken(CurrentToken.LexemId) + " found.")); return null; } return null; } Errors.Add(ErrorGenerate(CurrentToken, "'PROGRAM' expected.")); return null; } private Tree.Node Block(Lexem CurrentLexem) { var ResultNode = new Tree.Node { LexemType = "Block", Value = "", Childrens = null }; if (AddNode(Declarations(CurrentLexem))) { ResultNode.Childrens = new List<Tree.Node> { CurrentNode }; if (StackCount == 0 || CurrentNode.Childrens == null) { ResultNode.Childrens = new List<Tree.Node>(); } CurrentLexem = GetStackLexem(CodedTokensList.IndexOf(CurrentLexem)); if (TokensTable.GetToken(CurrentLexem.LexemId) == "BEGIN") { ResultNode.Childrens.Add(new Tree.Node { LexemType = "Keyword", Value = "BEGIN", Childrens = null }); CurrentLexem = CodedTokensList.ElementAt(CodedTokensList.IndexOf(CurrentLexem) + 1); if (TokensTable.GetToken(CurrentLexem.LexemId) == "END") { ResultNode.Childrens.Add(new Tree.Node { LexemType = "Keyword", Value = "END", Childrens = null }); StackCount += 2; return ResultNode; } Errors.Add(ErrorGenerate(CurrentLexem, "Unexpected symbol: '" + TokensTable.GetToken(CurrentLexem.LexemId) + "': 'END' expected.")); return null; } Errors.Add(ErrorGenerate(CurrentLexem, "Unexpected symbol: " + TokensTable.GetToken(CurrentLexem.LexemId))); return null; } Errors.Add(ErrorGenerate(CurrentLexem, "Unexpected symbol: " + TokensTable.GetToken(CurrentLexem.LexemId) + " 'BEGIN' expected.")); return null; } private Tree.Node Identifier(Lexem CurrentLexem) { if (TokensTable.isIdentifier(CurrentLexem.LexemId)) { return new Tree.Node { LexemType = "Identifier", Value = TokensTable.GetToken(CurrentLexem.LexemId), Childrens = null }; } Errors.Add(ErrorGenerate(CurrentLexem, "Identifier expected, but '" + TokensTable.GetToken(CurrentLexem.LexemId) + "' found.")); return null; } private Tree.Node Declarations(Lexem CurrentLexem) { var ResultNode = new Tree.Node { LexemType = "Declarations", Value = "", Childrens = null }; if (TokensTable.GetToken(CurrentLexem.LexemId) == "DEFFUNC") { CurrentLexem = CodedTokensList.ElementAt(CodedTokensList.IndexOf(CurrentLexem) + 1); ResultNode.Childrens = new List<Tree.Node>(); ResultNode.Childrens.Add(new Tree.Node { LexemType = "Keyword", Value = "DEFFUNC", Childrens = null }); var Functions = new Tree.Node { LexemType = "Function list", Value = "", Childrens = new List<Tree.Node>() }; if (AddNode(FunctionList(CurrentLexem, Functions))) { ResultNode.Childrens.Add(Functions); StackCount += 1; return ResultNode; } return null; } if(TokensTable.GetToken(CurrentLexem.LexemId) == "BEGIN") { return ResultNode; } return null; } private Tree.Node FunctionList(Lexem CurrentLexem, Tree.Node CurrentFunctions) { var ResultNode = new Tree.Node { LexemType = "Function list", Value = "", Childrens = null }; if(AddNode(Function(CurrentLexem))) { CurrentFunctions.Childrens.Add(CurrentNode); CurrentLexem = CodedTokensList.ElementAt(CodedTokensList.IndexOf(CurrentLexem) + 8); // Jump over function declaration to next token if (AddNode(FunctionList(CurrentLexem, CurrentFunctions))) { return CurrentFunctions; } } if (TokensTable.GetToken(CurrentLexem.LexemId) == "BEGIN") { return CurrentFunctions; } return null; } private Tree.Node FunctionCharacteristic(Lexem CurrentLexem) { if (AddNode(Constant(CurrentLexem))) { var ResultNode = new Tree.Node { LexemType = "Function characteristic", Value = "", Childrens = new List<Tree.Node> { CurrentNode } }; CurrentLexem = CodedTokensList.ElementAt(CodedTokensList.IndexOf(CurrentLexem) + 1); if (TokensTable.GetToken(CurrentLexem.LexemId) == ",") { ResultNode.Childrens.Add(new Tree.Node { LexemType = "Delimiter", Value = ",", Childrens = null }); CurrentLexem = CodedTokensList.ElementAt(CodedTokensList.IndexOf(CurrentLexem) + 1); if(AddNode(Constant(CurrentLexem))) { ResultNode.Childrens.Add(CurrentNode); return ResultNode; } return null; } Errors.Add(ErrorGenerate(CurrentLexem, "',' expected, but '" + TokensTable.GetToken(CurrentLexem.LexemId) + "' found.")); return null; } return null; } private Tree.Node Constant(Lexem CurrentLexem) { if (TokensTable.isConstant(CurrentLexem.LexemId)) { Constants.Add(new Constant { Value = Convert.ToInt32(TokensTable.GetToken(CurrentLexem.LexemId)), LexemPosition = new Constant.Position { Line = CurrentLexem.LexemPosition.Line, Column = CurrentLexem.LexemPosition.Column } }); return new Tree.Node { LexemType = "Constant", Value = TokensTable.GetToken(CurrentLexem.LexemId), Childrens = null }; } Errors.Add(ErrorGenerate(CurrentLexem, "Constant expected, but '" + TokensTable.GetToken(CurrentLexem.LexemId) + "' found.")); return null; } private Tree.Node Function(Lexem CurrentLexem) { if(TokensTable.GetToken(CurrentLexem.LexemId) == "BEGIN") { return null; } if(AddNode(Identifier(CurrentLexem))) { if(AlreadyPassedIdentifier.Contains(CurrentLexem.LexemId)) { Errors.Add(ErrorGenerate(CurrentLexem, "'" + TokensTable.GetToken(CurrentLexem.LexemId) + "' already defined")); return null; } AlreadyPassedIdentifier.Add(CurrentLexem.LexemId); var ResultNode = new Tree.Node { LexemType = "Function", Value = "", Childrens = new List<Tree.Node> { CurrentNode } }; CurrentLexem = CodedTokensList.ElementAt(CodedTokensList.IndexOf(CurrentLexem) + 1); if (TokensTable.GetToken(CurrentLexem.LexemId) == "=") { ResultNode.Childrens.Add(new Tree.Node { LexemType = "Delimiter", Value = "=", Childrens = null }); CurrentLexem = CodedTokensList.ElementAt(CodedTokensList.IndexOf(CurrentLexem) + 1); if(AddNode(Constant(CurrentLexem))) { ResultNode.Childrens.Add(CurrentNode); CurrentLexem = CodedTokensList.ElementAt(CodedTokensList.IndexOf(CurrentLexem) + 1); if (TokensTable.GetToken(CurrentLexem.LexemId) == "\\") { ResultNode.Childrens.Add(new Tree.Node { LexemType = "Delimiter", Value = "\\", Childrens = null }); CurrentLexem = CodedTokensList.ElementAt(CodedTokensList.IndexOf(CurrentLexem) + 1); if(!AddNode(FunctionCharacteristic(CurrentLexem))) { return null; } ResultNode.Childrens.Add(CurrentNode); CurrentLexem = CodedTokensList.ElementAt(CodedTokensList.IndexOf(CurrentLexem) + 3); //Jump over function characteristic to next token if(TokensTable.GetToken(CurrentLexem.LexemId) == ";") { ResultNode.Childrens.Add(new Tree.Node { LexemType = "Delimiter", Value = ";", Childrens = null }); StackCount += 8; return ResultNode; } Errors.Add(ErrorGenerate(CurrentLexem, "';' expected, but " + TokensTable.GetToken(CurrentLexem.LexemId) + " found.")); return null; } } return null; } Errors.Add(ErrorGenerate(CurrentLexem, "'=' expected, but " + TokensTable.GetToken(CurrentLexem.LexemId) + " found.")); return null; } return null; } public bool AddNode(Tree.Node CurrentNode) { if(CurrentNode != null) { this.CurrentNode = CurrentNode; return true; } return false; } public Error ErrorGenerate(Lexem CurrentLexem, string ErrorMessage) { return new Error { CodeLineNumber = CurrentLexem.LexemPosition.Line, CodeErrorType = ErrorMessage, CodeColumnNumber = CurrentLexem.LexemPosition.Column }; } public Lexem GetStackLexem(int Index) { if (Index + StackCount >= CodedTokensList.Count) return CodedTokensList[CodedTokensList.Count - 1]; return CodedTokensList[Index + StackCount]; } public List<Error> GetErrors() { return Errors; } public List<Constant> GetConstants() { return Constants; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; using UnityEngine.SceneManagement; /// <summary> /// 场景切换模块 /// 知识点 /// 1.场景异步加载 /// 2.协程 /// 3.委托 /// </summary> public class ScenesMgr : BaseManager<ScenesMgr> { /// <summary> /// 切换场景 同步 /// </summary> /// <param name="name"></param> public void LoadScene(string name, UnityAction fun) { //场景同步加载 SceneManager.LoadScene(name); //加载完成过后 才会去执行fun fun(); } /// <summary> /// 提供给外部的 异步加载的接口方法 /// </summary> /// <param name="name"></param> /// <param name="fun"></param> public void LoadSceneAsyn(string name, UnityAction fun) { MonoMgr.GetInstance().StartCoroutine(ReallyLoadSceneAsyn(name, fun)); } /// <summary> /// 协程异步加载场景 /// </summary> /// <param name="name"></param> /// <param name="fun"></param> /// <returns></returns> private IEnumerator ReallyLoadSceneAsyn(string name, UnityAction fun) { AsyncOperation ao = SceneManager.LoadSceneAsync(name); //可以得到场景加载的一个进度 while(!ao.isDone) { //事件中心 向外分发 进度情况 外面想用就用 EventCenter.GetInstance().EventTrigger("进度条更新", ao.progress); //这里面去更新进度条 yield return ao.progress; } //加载完成过后 才会去执行fun fun(); } }
using System.ComponentModel.DataAnnotations; namespace Discount.Core.Contracts.v1.Coupons { public class CreateCouponDto { [Required] [MaxLength(24), MinLength(24)] public string ProductId { get; set; } [Required] public string Description { get; set; } [Required] public int Amount { get; set; } } }
using AutoFixture; using Microsoft.AspNetCore.Mvc; using Moq; using NUnit.Framework; using SFA.DAS.CommitmentsV2.Api.Client; using SFA.DAS.CommitmentsV2.Shared.Interfaces; using SFA.DAS.ProviderCommitments.Web.Controllers; using SFA.DAS.ProviderCommitments.Web.Models.Apprentice; using SFA.DAS.ProviderCommitments.Web.Models.Apprentice.Edit; using System.Threading.Tasks; namespace SFA.DAS.ProviderCommitments.Web.UnitTests.Controllers.ApprenticesControllerTests { public class WhenGettingChangeOption { private GetChangeOptionFixture _fixture; [SetUp] public void Arrange() { _fixture = new GetChangeOptionFixture(); } [Test] public async Task ThenVerifyMapperWasCalled() { await _fixture.ChangeOption(); _fixture.VerifyMapperWasCalled(); } [Test] public async Task ThenReturnsViewModel() { var result = await _fixture.ChangeOption(); _fixture.VerifyViewModel(result as ViewResult); } } public class GetChangeOptionFixture { public ApprenticeController Controller { get; set; } private readonly Mock<IModelMapper> _modelMapperMock; private readonly ChangeOptionRequest _request; private readonly ChangeOptionViewModel _viewModel; public GetChangeOptionFixture() { var fixture = new Fixture(); _request = fixture.Create<ChangeOptionRequest>(); _viewModel = fixture.Create<ChangeOptionViewModel>(); _modelMapperMock = new Mock<IModelMapper>(); _modelMapperMock.Setup(m => m.Map<ChangeOptionViewModel>(_request)).ReturnsAsync(_viewModel); Controller = new ApprenticeController(_modelMapperMock.Object, Mock.Of<ICookieStorageService<IndexRequest>>(), Mock.Of<ICommitmentsApiClient>()); } public async Task<IActionResult> ChangeOption() { var result = await Controller.ChangeOption(_request); return result as ViewResult; } public void VerifyMapperWasCalled() { _modelMapperMock.Verify(m => m.Map<ChangeOptionViewModel>(_request)); } public void VerifyViewModel(ViewResult viewResult) { var viewModel = viewResult.Model as ChangeOptionViewModel; Assert.AreEqual(_viewModel, viewModel); } } }
using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace Coldairarrow.Entity.CB { /// <summary> /// Frame_Department /// </summary> [Table("Frame_Department")] public class Frame_Department { /// <summary> /// DepartmentID /// </summary> [Key] public Int32 DepartmentID { get; set; } /// <summary> /// RootID /// </summary> public Int32? RootID { get; set; } /// <summary> /// DepartmentName /// </summary> public String DepartmentName { get; set; } /// <summary> /// Telephone /// </summary> public String Telephone { get; set; } /// <summary> /// bm_id /// </summary> public String bm_id { get; set; } } }
using mec.Model.Enums; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Text; using System.Threading.Tasks; namespace mec.Model.Packs { public class PackNoticeViewModel { public decimal Id { get; set; } public string NoticeNo { get; set; } public Nullable<decimal> NoticeSeq { get; set; } public string States { get; set; } /// <summary> /// 產品型號 /// </summary> public string CustomerCode { get; set; } /// <summary> /// 物料編碼 /// </summary> public string MaterialCode { get; set; } /// <summary> /// 數量 /// </summary> public Nullable<decimal> Qty { get; set; } /// <summary> /// 內盒 /// </summary> public string BoxCode { get; set; } /// <summary> /// 起始箱號 /// </summary> public Nullable<decimal> StartNo { get; set; } /// <summary> /// 截止箱號 /// </summary> public Nullable<decimal> EndNo { get; set; } /// <summary> /// PCS*CN /// </summary> public Nullable<decimal> PCS { get; set; } /// <summary> /// G.W /// </summary> public Nullable<decimal> GW { get; set; } /// <summary> /// N.W /// </summary> public Nullable<decimal> NW { get; set; } /// <summary> /// MT /// </summary> public string Volume { get; set; } public string OrgCode { get; set; } public PackInfo PCInfo { get; set; } public Nullable<DateTime> CreateTime { get; set; } } public class PackInfo { public string C_CODE { get; set; } public string C_CUST_CODE { get; set; } public string PartNo { get; set; } public string BoxInfo { get; set; } public string DateCode { get; set; } public string ProductCode { get; set; } public string Description { get; set; } public string LINE_REMARK { get; set; } public string C_PRODUCT_MODEL { get; set; } public Nullable<decimal> I_SEQ { get; set; } } public class PackRecordViewModel { public decimal ID { get; set; } /// <summary> /// 包裝箱號 /// </summary> public string NoticeNo { get; set; } public string WorkNo { get; set; } /// <summary> /// /// </summary> public string MaterialCode { get; set; } /// <summary> /// /// </summary> public string SourceType { get; set; } /// <summary> /// 流轉卡編號 /// </summary> public string LotNo { get; set; } /// <summary> /// 料箱編號 /// </summary> public string BinNo { get; set; } /// <summary> /// 包裝箱編號 /// </summary> public string BoxNo { get; set; } /// <summary> /// 包裝箱ID /// </summary> public decimal BoxId { get; set; } public Nullable<decimal> Qty { get; set; } public Nullable<decimal> OutQty { get; set; } public string Process { get; set; } public bool IsSelected { get; set; } public ModifyFlagEnum ModifyFlag { get; set; } public string DateCode { get; set; } public string ProductCode { get; set; } public int Seq { get; set; } public Nullable<DateTime> CreateTime { get; set; } public string PartNumber { get; set; } public PackRecordViewModel Clone() { return (PackRecordViewModel)this.MemberwiseClone(); } public override string ToString() { return string.Format("LotNo {0}, MaterialCode {1}, Qty {2}", this.LotNo, this.MaterialCode, this.Qty); } } /* public class PackSourceViewModel { public decimal ID { get; set; } public string Barcode { get; set; } public string MaterialCode { get; set; } public string SourceType { get; set; } //public string FlowCardNo { get; set; } public Nullable<decimal> Qty { get; set; } public Nullable<decimal> OutQty { get; set; } public string Process { get; set; } public PackSourceViewModel Clone() { return (PackSourceViewModel)this.MemberwiseClone(); } }*/ public class PackNoticeParam : BaseParam { public string NoticeNo { get; set; } } }
using System; using System.Collections.Generic; using System.Text; namespace Entities.Models { /// <summary> /// 博客首页访问记录表 /// </summary> public class VisitLog { public int Id { get; set; } public string Ip { get; set; } public string Position { get; set; } public DateTime VistTime { get; set; } } }
using Alabo.App.Share.HuDong.Domain.Entities; using Alabo.Datas.UnitOfWorks; using Alabo.Domains.Repositories; using MongoDB.Bson; namespace Alabo.App.Share.HuDong.Domain.Repositories { public class HudongRepository : RepositoryMongo<Hudong, ObjectId>, IHudongRepository { public HudongRepository(IUnitOfWork unitOfWork) : base(unitOfWork) { } } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using AreaCalc; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AreaCalc.Tests { [TestClass()] public class AreaCalcTests { [TestMethod()] public void CalcArea_triangle_a10_b10_c10_43returned() { // arrange double a = 10.0; double b = 10.0; double c = 10.0; double expected = 43.301; Figure triangle = new Triangle(a, b, c); // act AreaCalc areaCalc = new AreaCalc(); double actual = areaCalc.Calculate(triangle); //assert Assert.AreEqual(expected, actual); } [TestMethod()] public void CalcArea_circle_radius1_Pireturned() { // arrange double radius = 1.0; double expected = 3.142; Figure circle = new Circle(radius); // act AreaCalc areaCalc = new AreaCalc(); double actual = areaCalc.Calculate(circle); //assert Assert.AreEqual(expected, actual); } [TestMethod()] public void isTriangleRight_a3_b4_c5_true() { // arrange double a = 3.0; double b = 4.0; double c = 5.0; Triangle triangle = new Triangle(a, b, c); //assert Assert.IsTrue(triangle.isRight()); } } }
using Allyn.Domain.Models.Front; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.ModelConfiguration; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Allyn.Infrastructure.EfRepositories.ModelConfigurations { internal class OrderTypeConfiguration : EntityTypeConfiguration<Order> { internal OrderTypeConfiguration() { ToTable("FOrder"); HasKey(k => k.Id) .Property(p => p.Id) .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); Property(p => p.Address) .IsRequired() .HasColumnType("varchar") .HasMaxLength(100); Property(p => p.Code) .IsRequired() .HasColumnType("varchar") .HasMaxLength(64); Property(p => p.WxCode) .HasColumnType("varchar") .HasMaxLength(64); Property(p => p.Contact) .HasColumnType("varchar") .HasMaxLength(20); Property(p => p.ExpressCode) .HasColumnType("varchar") .HasMaxLength(20); Property(p => p.OrderType) .HasColumnType("varchar") .HasMaxLength(20); Property(p => p.PayCode) .HasColumnType("varchar") .HasMaxLength(20); Property(p => p.Phone) .HasColumnType("varchar") .HasMaxLength(20); Property(p => p.UpdateDate) .IsOptional(); Property(p => p.Modifier) .IsOptional(); HasMany(m=>m.OrderLines) .WithOptional() .Map(m => m.MapKey("OrderKey")); Ignore(m => m.Amount); Property(p => p.MemberOpenKey) .HasColumnType("varchar") .HasMaxLength(64); Property(p => p.ExpressOrderNo) .HasColumnType("varchar") .HasMaxLength(64); Property(p => p.ConsignDate) .IsOptional(); Property(p => p.Consigner) .HasColumnType("varchar") .HasMaxLength(20); Property(p => p.ConfirmReceiveDate) .IsOptional(); Property(p => p.ConfirmReceiver) .HasColumnType("varchar") .HasMaxLength(20); } } }
using Autofac; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Http; using Autofac.Integration.WebApi; using System.Reflection; using System.Web.Mvc; using Autofac.Integration.Mvc; namespace WebApplication4 { public class WebApp { public static void Run() { var configuration = GlobalConfiguration.Configuration; var builder = new ContainerBuilder(); // Configure the container //builder.ConfigureWebApi(configuration); // Register API controllers using assembly scanning. builder.RegisterApiControllers(Assembly.GetExecutingAssembly()); //builder.RegisterType<DefaultCommandBus>().As<ICommandBus>() // .InstancePerApiRequest(); //builder.RegisterType<UnitOfWork>().As<IUnitOfWork>() // .InstancePerApiRequest(); //builder.RegisterType<DatabaseFactory>().As<IDatabaseFactory>() // .InstancePerApiRequest(); //builder.RegisterAssemblyTypes(typeof(CategoryRepository) // .Assembly).Where(t => t.Name.EndsWith("Repository")) // .AsImplementedInterfaces().InstancePerApiRequest(); //var services = Assembly.Load("EFMVC.Domain"); //builder.RegisterAssemblyTypes(services) // .AsClosedTypesOf(typeof(ICommandHandler<>)) // .InstancePerApiRequest(); //builder.RegisterAssemblyTypes(services) // .AsClosedTypesOf(typeof(IValidationHandler<>)) // .InstancePerApiRequest(); var container = builder.Build(); // Set the WebApi dependency resolver. //var resolver = new AutofacWebApiDependencyResolver(container); //configuration.DependencyResolver.(resolver); DependencyResolver.SetResolver(new AutofacWebApiDependencyResolver(container)); } } }
using gView.Framework.Carto; using gView.Framework.Data; using gView.Framework.Geometry; using gView.Framework.IO; using gView.Framework.Symbology; using gView.Framework.Sys.UI.Extensions; using gView.Framework.system; using System; using System.Drawing; using System.IO; using System.Linq; using System.Windows.Forms; namespace gView.Framework.UI.Dialogs { public partial class FormMapProperties : Form { private IMap _map; private IDisplay _display; private FormSpatialReference _sr = null, _sr2 = null; private IMapApplication _app; public FormMapProperties(IMapApplication app, IMap map, IDisplay display) { _app = app; _map = map; _display = display; InitializeComponent(); } private void FormMapProperties_Load(object sender, EventArgs e) { if (_map == null || _display == null) { return; } txtName.Text = _map.Name; numRefScale.Value = (int)_display.refScale; int index = 0; foreach (GeoUnits unit in Enum.GetValues(typeof(GeoUnits))) { // MapUnit darf nie diese Einheit sein... Immer double Wert! if (unit != GeoUnits.DegreesMinutesSeconds) { bool append = false; if (_display.SpatialReference != null) { if (_display.SpatialReference.SpatialParameters.IsGeographic && (int)unit < 0) { append = true; } else if (!_display.SpatialReference.SpatialParameters.IsGeographic && (int)unit > 0) { append = true; } else if (unit == 0) { append = true; } } else { append = true; } if (append) { cmbMapUnits.Items.Add(new GeoUnitsItem(unit)); if (_display.MapUnits == unit) { cmbMapUnits.SelectedIndex = cmbMapUnits.Items.Count - 1; } } } cmbDisplayUnits.Items.Add(new GeoUnitsItem(unit)); if (_display.DisplayUnits == unit) { cmbDisplayUnits.SelectedIndex = index; } index++; } //if (_display.SpatialReference != null && _display.SpatialReference.SpatialParameters.Unit != GeoUnits.Unknown) // cmbMapUnits.Enabled = false; _sr = new FormSpatialReference(_map.Display.SpatialReference); _sr.canModify = true; tabSR.Controls.Add(_sr.panelReferenceSystem); _sr2 = new FormSpatialReference(_map.LayerDefaultSpatialReference); _sr2.canModify = true; panelDefaultLayerSR.Controls.Add(_sr2.panelReferenceSystem); btnBackgroundColor.BackColor = _display.BackgroundColor.ToGdiColor(); txtTitle.Text = _map.Title; txtDescription.Text = _map.GetLayerDescription(Map.MapDescriptionId); txtCopyright.Text = _map.GetLayerCopyrightText(Map.MapCopyrightTextId); numFontScaleFactor.Value = (decimal)(SystemVariables.SystemFontsScaleFactor * 100f); #region Graphics Engine numEngineDpi.Value = (decimal)GraphicsEngine.Current.Engine.ScreenDpi; foreach (var engineName in Engines.RegisteredGraphicsEngineNames()) { cmbGraphicsEngine.Items.Add(engineName); } cmbGraphicsEngine.SelectedItem = GraphicsEngine.Current.Engine.EngineName; #endregion Graphics Engine #region Current Display Values txtCurrentBBox.Text = _display.Envelope.ToBBoxString(); int iWidth = (int)((float)_display.iWidth * 96f / (float)_display.dpi); int iHeight = (int)((float)_display.iHeight * 96f / (float)_display.dpi); txtCurrentSize.Text = $"{iWidth},{iHeight}"; #endregion BuildResourcesList(); } private void btnOK_Click(object sender, EventArgs e) { if (_map == null || _display == null) { return; } try { bool refresh = false; _map.Name = txtName.Text; _display.refScale = Convert.ToDouble(numRefScale.Value); if (cmbMapUnits.Enabled) { _display.MapUnits = ((GeoUnitsItem)cmbMapUnits.SelectedItem).Unit; } _display.DisplayUnits = ((GeoUnitsItem)cmbDisplayUnits.SelectedItem).Unit; _display.BackgroundColor = btnBackgroundColor.BackColor.ToArgbColor(); ISpatialReference oldSRef = _display.SpatialReference; _display.SpatialReference = _sr.SpatialReference; if (oldSRef != null && !oldSRef.Equals(_display.SpatialReference)) { IEnvelope limit = _display.Limit; IEnvelope env = _display.Envelope; _display.Limit = GeometricTransformerFactory.Transform2D( limit, oldSRef, _display.SpatialReference).Envelope; _display.ZoomTo( GeometricTransformerFactory.Transform2D( env, oldSRef, _display.SpatialReference).Envelope ); } _map.LayerDefaultSpatialReference = _sr2.SpatialReference; _map.Title = txtTitle.Text; _map.SetLayerDescription(Map.MapDescriptionId, txtDescription.Text); _map.SetLayerCopyrightText(Map.MapCopyrightTextId, txtCopyright.Text); if (SystemVariables.SystemFontsScaleFactor != (float)numFontScaleFactor.Value / 100f) { SystemVariables.SystemFontsScaleFactor = (float)numFontScaleFactor.Value / 100f; _display.Screen?.RefreshSettings(); refresh = true; } #region Graphics Engine if (cmbGraphicsEngine.SelectedItem.ToString() != GraphicsEngine.Current.Engine.EngineName) { var engine = Engines.RegisteredGraphcisEngines().Where(ge => ge.EngineName == cmbGraphicsEngine.SelectedItem.ToString()).FirstOrDefault(); if (engine != null) { GraphicsEngine.Current.Engine = engine; RefreshFeatureRendererSymbolsGraphcisEngine(); refresh = true; } } #endregion Graphics Engine if (refresh) { if (_app != null) { _app.RefreshTOC(); _app.RefreshActiveMap(DrawPhase.All); } } } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void btnBackgroundColor_Click(object sender, EventArgs e) { ColorDialog dlg = new ColorDialog(); dlg.Color = btnBackgroundColor.BackColor; if (dlg.ShowDialog() == DialogResult.OK) { btnBackgroundColor.BackColor = dlg.Color; } } private void btnTransparent_Click(object sender, EventArgs e) { btnBackgroundColor.BackColor = Color.FromArgb(0, 0, 0, 0); } private void btnAntialiasLabels_Click(object sender, EventArgs e) { SetLabelSmoothing(SymbolSmoothing.AntiAlias); } private void btnNoAntialiasLabels_Click(object sender, EventArgs e) { SetLabelSmoothing(SymbolSmoothing.None); } private void btnAntialiasFeatures_Click(object sender, EventArgs e) { SetFeatureSmooting(SymbolSmoothing.AntiAlias); } private void btnNoAntialiasFeatures_Click(object sender, EventArgs e) { SetFeatureSmooting(SymbolSmoothing.None); } private void SetLabelSmoothing(SymbolSmoothing smooting) { if (_map == null || _map.MapElements == null) { return; } foreach (IDatasetElement dsElement in _map.MapElements) { IFeatureLayer fLayer = dsElement as IFeatureLayer; if (fLayer == null || fLayer.LabelRenderer == null) { continue; } ILabelRenderer lRenderer = fLayer.LabelRenderer; foreach (ISymbol symbol in lRenderer.Symbols) { if (symbol == null) { continue; } symbol.SymbolSmothingMode = smooting; } } if (_app != null) { _app.RefreshActiveMap(DrawPhase.All); } } private void SetFeatureSmooting(SymbolSmoothing smooting) { if (_map == null || _map.MapElements == null) { return; } foreach (IDatasetElement dsElement in _map.MapElements) { IFeatureLayer fLayer = dsElement as IFeatureLayer; if (fLayer == null || fLayer.FeatureRenderer == null) { continue; } IFeatureRenderer fRenderer = fLayer.FeatureRenderer; foreach (ISymbol symbol in fRenderer.Symbols) { if (symbol == null) { continue; } symbol.SymbolSmothingMode = smooting; } } if (_app != null) { _app.RefreshActiveMap(DrawPhase.All); } } private void RefreshFeatureRendererSymbolsGraphcisEngine() { if (_map == null || _map.MapElements == null) { return; } foreach (IDatasetElement dsElement in _map.MapElements) { IFeatureLayer fLayer = dsElement as IFeatureLayer; if (fLayer == null || fLayer.FeatureRenderer == null) { continue; } IFeatureRenderer fRenderer = fLayer.FeatureRenderer; foreach (ISymbol symbol in fRenderer.Symbols) { if (symbol is ISymbolCurrentGraphicsEngineDependent) { ((ISymbolCurrentGraphicsEngineDependent)symbol).CurrentGraphicsEngineChanged(); } } } } #region MapResources private void btnAddResources_Click(object sender, EventArgs e) { OpenFileDialog dlg = new OpenFileDialog() { Multiselect = true }; if (dlg.ShowDialog() == DialogResult.OK) { foreach (var filename in dlg.FileNames) { FileInfo fi = new FileInfo(filename); _map.ResourceContainer[fi.Name] = File.ReadAllBytes(fi.FullName); } BuildResourcesList(); } } private void BuildResourcesList() { gridResources.Rows.Clear(); if (_map?.ResourceContainer?.Names != null) { foreach (string name in _map.ResourceContainer.Names) { var data = _map.ResourceContainer[name]; if (data == null || data.Length == 0) { continue; } var gridRow = new DataGridViewRow(); gridRow.Cells.Add(new DataGridViewTextBoxCell() { Value = name }); gridRow.Cells.Add(new DataGridViewTextBoxCell() { Value = $"{Math.Round(data.Length / 1024.0, 2).ToString()}kb" }); gridRow.Cells.Add(new DataGridViewButtonCell() { Value = "Remove" }); gridResources.Rows.Add(gridRow); } } } private void gridResources_CellClick(object sender, DataGridViewCellEventArgs e) { if (_map?.ResourceContainer != null) { if (e.ColumnIndex == 2) // remove { var row = gridResources.Rows[e.RowIndex]; string resourceName = row.Cells[0].Value.ToString(); if (MessageBox.Show($"Remove resouorce {resourceName} from map?", "Remove", MessageBoxButtons.YesNo) == DialogResult.Yes) { _map.ResourceContainer[resourceName] = null; gridResources.Rows.Remove(row); } } } } #endregion MapResources async private void btnMapServiceMetadata_Click(object sender, EventArgs e) { XmlStream xmlStream = new XmlStream(String.Empty); this._map.ReadMetadata(xmlStream); FormMetadata dlg = new FormMetadata(xmlStream, this._map); if (dlg.ShowDialog() == DialogResult.OK) { await (this._map).WriteMetadata(await dlg.GetStream()); } } private void btnDefaultLayerSRFromSpatialReference_Click(object sender, EventArgs e) { _sr2.SpatialReference = _sr.SpatialReference; _sr2.RefreshGUI(); } } internal class GeoUnitsItem { private GeoUnits _unit; public GeoUnitsItem(GeoUnits unit) { _unit = unit; } public GeoUnits Unit { get { return _unit; } } public override string ToString() { return Unit2String(_unit); } private string Unit2String(GeoUnits unit) { switch (unit) { case GeoUnits.Unknown: return unit.ToString(); case GeoUnits.Inches: return unit.ToString(); case GeoUnits.Feet: return unit.ToString(); case GeoUnits.Yards: return unit.ToString(); case GeoUnits.Miles: return unit.ToString(); case GeoUnits.NauticalMiles: return "Nautic Miles"; case GeoUnits.Millimeters: return unit.ToString(); case GeoUnits.Centimeters: return unit.ToString(); case GeoUnits.Decimeters: return unit.ToString(); case GeoUnits.Meters: return unit.ToString(); case GeoUnits.Kilometers: return unit.ToString(); case GeoUnits.DecimalDegrees: return "Decimal Degrees"; case GeoUnits.DegreesMinutesSeconds: return "Degrees Minutes Seconds"; } return "???"; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ZombieVomit : ZombieBase { [Header("Vomit Zombie Config")] [SerializeField] private Transform _fxParent; [SerializeField] private Transform _vomitSpawnPosition; [SerializeField] private GameObject _vomitFXPrefab; private int _enemyLayerMask; private int _playerLayerMask; GameObject _vomitFX; protected override void Awake() { base.Awake(); } public override IEnumerator Hurt(float pDamage = 0.0f) { if (IsAlive ) { if (pDamage > 0) { if (_currentHealth - pDamage > 0) _currentHealth -= pDamage; else _currentHealth = 0; if (_zombieHealthBar) _zombieHealthBar.fillAmount = _currentHealth / CharacterStats.Health; if (_hurtFx != null) Instantiate(_hurtFx, new Vector3(transform.position.x, 1, transform.position.z), Quaternion.identity); if (_currentHealth <= 0) { DieState(); _navMeshAgent.enabled = false; transform.position = new Vector3(transform.position.x, 0, transform.position.z); } } } yield return null; } public override IEnumerator Attack() { if (IsAlive && !IsAttacking) { finalLayerMask = humanLayerMask | playerLayerMask | zombieLayerMask; Being closestBeing = GetClosestBeingToAttack(finalLayerMask, CharacterStats.AttackRange); if(closestBeing) transform.LookAt(closestBeing.transform); if (IsBeingControlled) _animator.SetTrigger("attack"); IsAttacking = true; yield return new WaitForSeconds(0.8f); if (_vomitFXPrefab != null) { _vomitFX = Instantiate(_vomitFXPrefab, _fxParent); _vomitFX.transform.position = _vomitSpawnPosition.position; } yield return new WaitForSeconds(CharacterStats.AttackRate - 0.8f); IsAttacking = false; } yield return null; } }
using System.Diagnostics; namespace ApplicationCore.Interfaces { public interface IObjectMapFactory { TMap GetMapping<TMap, TSource>(TSource source); } }
using StardewValley; using System.IO; namespace StardewValleyMP.Packets { // Server <-> Client // Update the amount of lost books found. public class LostBooksPacket : Packet { public int bookCount; public LostBooksPacket() : base(ID.LostBooks) { bookCount = 0; if (Game1.player.archaeologyFound.ContainsKey(102)) bookCount = Game1.player.archaeologyFound[102][0]; } protected override void read(BinaryReader reader) { bookCount = reader.ReadInt32(); } protected override void write(BinaryWriter writer) { writer.Write(bookCount); } public override void process(Client client) { process(); } public override void process( Server server, Server.Client client ) { process(); server.broadcast(this, client.id); } private void process() { if ( !Game1.player.archaeologyFound.ContainsKey( 102 ) ) { Game1.player.archaeologyFound.Add(102, new int[] { 0, 0 }); } Game1.player.archaeologyFound[102][0] = bookCount; Game1.player.archaeologyFound[102][1] = bookCount; // No idea what the second is for, but LibraryMuseum.foundArtifact increments both. Multiplayer.prevBooks = bookCount; } public override string ToString() { return base.ToString() + " " + bookCount; } } }
using UnityEngine; using UnityEngine.UI; using SimpleJSON; using System.Collections; public class Summonmanual: MonoBehaviour { public Text Gold; //public Text SoulStone; public ParticleSystem p; public GameObject soundBG, model,mycamera,FirstTimerSummon; public firstimersummon firstTimerSummonScript; // public Text Common, Rare, Legendary; public Sprite CommonIcon, RareIcon, LegendaryIcon; public Image icon; public string[] SummonedGhost; public GameObject statusAktif; private string jenis; int tutorHitung; public Text header; public Text info; //sementara public int uang,batuc,batur,batul; void Start () { StartCoroutine (updateData ()); //PlayerPrefs.SetString ("PLAY_TUTORIAL", "TRUE"); if (PlayerPrefs.GetString ("PLAY_TUTORIAL") == "TRUE") { firstTimerSummonScript.gameObject.SetActive (true); } else { firstTimerSummonScript.gameObject.SetActive (false);} //StartCoroutine ( GetDataUser ()); uang=int.Parse(PlayerPrefs.GetString(Link.GOLD)); batuc=int.Parse(PlayerPrefs.GetString(Link.COMMON)); batur=int.Parse(PlayerPrefs.GetString(Link.RARE)); batul=int.Parse(PlayerPrefs.GetString(Link.LEGENDARY)); Gold.text = PlayerPrefs.GetString (Link.GOLD); Common.text = PlayerPrefs.GetString (Link.COMMON); Rare.text = PlayerPrefs.GetString (Link.RARE); Legendary.text = PlayerPrefs.GetString (Link.LEGENDARY); //SoulStone.text = PlayerPrefs.GetString (Link.SOUL_STONE); icon.sprite = CommonIcon; jenis = "COMMON"; header.text = "SUMMON " + jenis; Debug.Log (PlayerPrefs.GetString (Link.GOLD) + "/" + PlayerPrefs.GetString (Link.COMMON) ); if (int.Parse (PlayerPrefs.GetString (Link.GOLD)) >= 20 && int.Parse (PlayerPrefs.GetString (Link.COMMON)) >= 20) { statusAktif.SetActive (false); } else { statusAktif.SetActive (true); } } void Update(){ if (uang < 20) { if (jenis == "COMMON" && batuc < 20) { statusAktif.SetActive (true); } else if (jenis == "RARE" && batuc < 20) { statusAktif.SetActive (true); } else if (jenis == "LEGENDARY" && batul < 20) { statusAktif.SetActive (true); } else { statusAktif.SetActive (false); } } else { statusAktif.SetActive (false); } } public void OnClickCommon () { jenis = "COMMON"; header.text = "SUMMON " + jenis; icon.sprite = CommonIcon; // if (int.Parse (PlayerPrefs.GetString (Link.GOLD)) >= 20 && int.Parse (PlayerPrefs.GetString (Link.COMMON)) >= 20) { // // statusAktif.SetActive (false); // } else { // statusAktif.SetActive (true); // } } public void OnClickRare () { jenis = "RARE"; header.text = "SUMMON " + jenis; icon.sprite = RareIcon; // if (int.Parse (PlayerPrefs.GetString (Link.GOLD)) >= 20 && int.Parse (PlayerPrefs.GetString (Link.RARE)) >= 20) { // statusAktif.SetActive (false); // } else { // // statusAktif.SetActive (true); // } } public void OnClickLegendary () { jenis = "LEGENDARY"; header.text = "SUMMON " + jenis; icon.sprite = LegendaryIcon; // if (int.Parse (PlayerPrefs.GetString (Link.GOLD)) >= 20 && int.Parse (PlayerPrefs.GetString (Link.LEGENDARY)) >= 20) { // statusAktif.SetActive (false); // } else { // // statusAktif.SetActive (true); // } } public void OnClickSummon () { uang -= 20; if (jenis == "COMMON" && batuc > 20) { batuc -= 20; int choice = Random.Range (0, 6); Summoning (SummonedGhost [choice]); } else if (jenis == "RARE" && batur > 20) { batur -= 20; int choice = Random.Range (7, 12); Summoning (SummonedGhost [choice]); } else { if (batul > 20) { batul -= 20; int choice = Random.Range (13, 19); Summoning (SummonedGhost [choice]); } } } public void Summoning(string ghost){ p.Play (); if (mycamera.transform.Find ("SummonPos").transform.childCount > 0) { Destroy (mycamera.transform.Find ("SummonPos").transform.Find ("ghost").gameObject); } else { //nothing to see here } model = Instantiate (Resources.Load ("PrefabsChar/" + ghost) as GameObject, new Vector3(0f,0f,0f), Quaternion.identity); model.transform.SetParent (mycamera.transform); model.transform.localPosition =mycamera.transform.Find ("SummonPos").transform.localPosition; model.transform.localScale = mycamera.transform.Find ("SummonPos").transform.localScale; model.transform.localEulerAngles = mycamera.transform.Find ("SummonPos").transform.localEulerAngles; model.name = "ghost"; model.transform.SetParent (mycamera.transform.Find ("SummonPos")); //ss.Summon (ghost); // ini terusin ke mana??? StartCoroutine (sendSummon(ghost,jenis)); tutorHitung += 1; if (tutorHitung == 3) { if(PlayerPrefs.GetString ("PLAY_TUTORIAL")== "TRUE"){ //PlayerPrefs.SetString ("SummonTutor", "UDAH"); //next.SetActive(true); firstTimerSummonScript.position = 3; } } } private IEnumerator sendSummon(string file, string jenis) { string url = Link.url + "send_summon"; WWWForm form = new WWWForm (); form.AddField ("MY_ID", PlayerPrefs.GetString(Link.ID)); form.AddField ("FILE", file); form.AddField ("JENIS", jenis); WWW www = new WWW(url,form); yield return www; if (www.error == null) { info.text = file; StartCoroutine (updateData()); } } private IEnumerator updateData() { string url = Link.url + "login"; WWWForm form = new WWWForm (); form.AddField (Link.DEVICE_ID, PlayerPrefs.GetString(Link.DEVICE_ID)); form.AddField (Link.EMAIL, PlayerPrefs.GetString(Link.EMAIL)); form.AddField (Link.PASSWORD, PlayerPrefs.GetString(Link.PASSWORD)); Debug.Log (PlayerPrefs.GetString(Link.ID)); WWW www = new WWW(url,form); yield return www; if (www.error == null) { //StartCoroutine (getDataBatu()); Debug.Log ("UPDATE SUCCESS"); var jsonString = JSON.Parse (www.text); Debug.Log (www.text); PlayerPrefs.SetString (Link.GOLD, jsonString["data"]["coin"]); PlayerPrefs.SetString (Link.COMMON, jsonString["data"]["common"]); PlayerPrefs.SetString (Link.RARE, jsonString["data"]["rare"]); PlayerPrefs.SetString (Link.LEGENDARY, jsonString["data"]["legendary"]); Gold.text = PlayerPrefs.GetString (Link.GOLD); Common.text = PlayerPrefs.GetString (Link.COMMON); Rare.text = PlayerPrefs.GetString (Link.RARE); Legendary.text = PlayerPrefs.GetString (Link.LEGENDARY); if (jenis == "COMMON") { OnClickCommon (); } else if (jenis == "RARE") { OnClickRare (); } else { OnClickLegendary (); } } } public void OnBack () { SceneManagerHelper.LoadScene ("Home"); } }
using System; using System.Collections.Generic; using System.Linq; namespace Euler_Logic.Problems.AdventOfCode.Y2017 { public class Problem20 : AdventOfCodeBase { private List<Particle> _particles; public override string ProblemName { get { return "Advent of Code 2017: 20"; } } public override string GetAnswer() { return Answer1(Input()).ToString(); } public override string GetAnswer2() { return Answer2(Input()).ToString(); } private int Answer1(List<string> input) { GetParticles(input); return FindClosestToZero(); } private int Answer2(List<string> input) { GetParticles(input); return FindLastOne(); } private int FindLastOne() { int count = 0; do { for (int index = 0; index < _particles.Count; index++) { var particle = _particles[index]; if (!particle.IsRemoved) { particle.VelocityX += particle.AccelerationX; particle.VelocityY += particle.AccelerationY; particle.VelocityZ += particle.AccelerationZ; particle.X += particle.VelocityX; particle.Y += particle.VelocityY; particle.Z += particle.VelocityZ; for (int priorIndex = 0; priorIndex < index; priorIndex++) { var prior = _particles[priorIndex]; if (!prior.IsRemoved && prior.X == particle.X && prior.Y == particle.Y && prior.Z == particle.Z) { prior.WillBeRemoved = true; particle.WillBeRemoved = true; } } } } foreach (var particle in _particles) { if (particle.WillBeRemoved) { particle.IsRemoved = true; particle.WillBeRemoved = false; } } count++; } while (count <= 1000); return _particles.Where(x => !x.IsRemoved).Count(); } private int FindClosestToZero() { long distance = 0; long bestDistance = 0; int bestParticle = 0; int currentParticle = 0; int lastBestParticle = -1; int noChangeCount = 0; do { bestDistance = long.MaxValue; bestParticle = 0; currentParticle = 0; foreach (var particle in _particles) { particle.VelocityX += particle.AccelerationX; particle.VelocityY += particle.AccelerationY; particle.VelocityZ += particle.AccelerationZ; particle.X += particle.VelocityX; particle.Y += particle.VelocityY; particle.Z += particle.VelocityZ; distance = Math.Abs(particle.X) + Math.Abs(particle.Y) + Math.Abs(particle.Z); if (distance < bestDistance) { bestDistance = distance; bestParticle = currentParticle; } currentParticle++; } if (bestParticle == lastBestParticle) { noChangeCount++; } else { noChangeCount = 0; } lastBestParticle = bestParticle; } while (noChangeCount < 1000); return bestParticle; } private void GetParticles(List<string> input) { _particles = input.Select(line => { var split = line .Replace("p=<", "") .Replace(">, v=<", ",") .Replace(">, a=<", ",") .Replace(">", "") .Split(','); return new Particle() { X = Convert.ToInt32(split[0]), Y = Convert.ToInt32(split[1]), Z = Convert.ToInt32(split[2]), VelocityX = Convert.ToInt32(split[3]), VelocityY = Convert.ToInt32(split[4]), VelocityZ = Convert.ToInt32(split[5]), AccelerationX = Convert.ToInt32(split[6]), AccelerationY = Convert.ToInt32(split[7]), AccelerationZ = Convert.ToInt32(split[8]) }; }).ToList(); } private class Particle { public long X { get; set; } public long Y { get; set; } public long Z { get; set; } public long VelocityX { get; set; } public long VelocityY { get; set; } public long VelocityZ { get; set; } public long AccelerationX { get; set; } public long AccelerationY { get; set; } public long AccelerationZ { get; set; } public bool WillBeRemoved { get; set; } public bool IsRemoved { get; set; } } } }
using System.Collections.Generic; namespace Codility { public class Permutation { public static int Check(int[] A) { long expectedSum = 0; long actualSum = 0; var distinctMap = new HashSet<long>(); for (var i = 0; i < A.Length; i++) { expectedSum += (i + 1); if (distinctMap.Contains(A[i])) return 0; distinctMap.Add(A[i]); } for (var i = 0; i < A.Length; i++) { actualSum += A[i]; } return (expectedSum - actualSum == 0) ? 1 : 0; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace WebAPIHelloWorld.Models { public class HelloWorldPeople { //creating data model class as example -- this could come from entity framework model public int WorldId { get; set; } public string WorldGreeting { get; set; } public string WorldPerson { get; set; } } }
using System; using Machine.Specifications; using SimpleConfigSections; namespace Tests.SimpleConfigSections { public class when_declaring_configuration_section_that_has_complex_property { private Because b = () => value = Configuration.Get<ISectionWithComplexProperty>(); private It should_create_complex_property = () => value.ComplexProperty.ShouldNotBeNull(); private It should_read_complex_property_of_complex_property = () => value.ComplexProperty.Simple.ShouldNotBeNull(); private It should_read_simple_values_of_complex_property = () => value.ComplexProperty.UriProperty.AbsoluteUri.ShouldEqual("http://google.pl/"); private static ISectionWithComplexProperty value; } public class SectionWithComplexProperty : ConfigurationSection<ISectionWithComplexProperty> { } public interface ISectionWithComplexProperty { IComplexConfigSection ComplexProperty { get; set; } } public interface IComplexConfigSection { IDeclareAppConfiguration Simple { get; set; } Uri UriProperty { get; set; } } }
namespace CPlanner.Client.Models { public class LocationViewModel { public string Street { get; set; } public string City { get; set; } public string State { get; set; } public string Zipcode { get; set; } } }
using System; using System.Collections.Generic; using System.Text; using ImagoCore.Enums; using ImagoCore.Models.Strategies; namespace ImagoCore.Models { public class BeprobbareFertigkeit : BeprobbareFertigkeitBase, INwBerechenbar { public BeprobbareFertigkeit(ImagoEntitaet identifier, INatuerlicherWertBerechnenStrategy strategy) : base(identifier) { _natuerlicherWertBerechnenStrategy = strategy; } public BeprobbareFertigkeit() { } private INatuerlicherWertBerechnenStrategy _natuerlicherWertBerechnenStrategy { get; } public void BerechneNatuerlicherWert(Dictionary<ImagoAttribut, int> values) { if (_natuerlicherWertBerechnenStrategy != null) NatuerlicherWert = _natuerlicherWertBerechnenStrategy.berechneNatuerlicherWert(values); } } }
using System; using System.IO; public class GStream2 : Stream { protected GClass19 gclass19_0; protected GClass10 gclass10_0; protected Stream stream_0; private bool bool_0; private bool bool_1 = true; public override bool CanRead { get { return this.stream_0.CanRead; } } public override bool CanSeek { get { return false; } } public override bool CanWrite { get { return false; } } public override long Length { get { return (long)this.gclass10_0.method_0(); } } public override long Position { get { return this.stream_0.Position; } set { throw new NotSupportedException("InflaterInputStream Position not supported"); } } public GStream2(Stream stream_1, GClass19 gclass19_1, int int_0) { if (stream_1 == null) { throw new ArgumentNullException("baseInputStream"); } if (gclass19_1 == null) { throw new ArgumentNullException("inflater"); } if (int_0 <= 0) { throw new ArgumentOutOfRangeException("bufferSize"); } this.stream_0 = stream_1; this.gclass19_0 = gclass19_1; this.gclass10_0 = new GClass10(stream_1, int_0); } protected void method_0() { this.gclass10_0.method_2(); this.gclass10_0.method_1(this.gclass19_0); } public override void Flush() { this.stream_0.Flush(); } public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException("Seek not supported"); } public override void SetLength(long value) { throw new NotSupportedException("InflaterInputStream SetLength not supported"); } public override void Write(byte[] buffer, int offset, int count) { throw new NotSupportedException("InflaterInputStream Write not supported"); } public override void WriteByte(byte value) { throw new NotSupportedException("InflaterInputStream WriteByte not supported"); } public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { throw new NotSupportedException("InflaterInputStream BeginWrite not supported"); } public override void Close() { if (!this.bool_0) { this.bool_0 = true; if (this.bool_1) { this.stream_0.Close(); } } } public override int Read(byte[] buffer, int offset, int count) { if (this.gclass19_0.method_8()) { throw new GException0("Need a dictionary"); } int num = count; while (true) { int num2 = this.gclass19_0.method_6(buffer, offset, num); offset += num2; num -= num2; if (num == 0 || this.gclass19_0.method_9()) { goto IL_6F; } if (this.gclass19_0.method_7()) { this.method_0(); } else if (num2 == 0) { break; } } throw new GException1("Dont know what to do"); IL_6F: return count - num; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Student { private string SName; private string Scourse; private int Happines; private string ClassIwant; private string Gender; private string Hobbie; private string ClassIgot; public string SName1 { get => SName; set => SName = value; } public string Scourse1 { get => Scourse; set => Scourse = value; } public int Happines1 { get => Happines; set => Happines = value; } public string ClassIwant1 { get => ClassIwant; set => ClassIwant = value; } public string Gender1 { get => Gender; set => Gender = value; } public string ClassIgot1 { get => ClassIgot; set => ClassIgot = value; } public string Hobbie1 { get => Hobbie; set => Hobbie = value; } public Student(string sName, string classIwant, string gender, string hobbie) { SName1 = sName; Happines1 = 0; ClassIwant1 = classIwant; Scourse1 = "Not Registered"; Gender1 = gender; ClassIgot = "nada"; Hobbie1 = hobbie; } }
namespace NStandard { public interface IContravariance<in T> { } }
namespace InstrumentationSample { public sealed class AuthorizationService : IAuthorizationService { public void Authorise(AuthorizationRequest request) { //Do some auth. Potentially complex logic happens here } } }
using Cs_IssPrefeitura.Aplicacao.Interfaces; using Cs_IssPrefeitura.Dominio.Entities; using Cs_IssPrefeitura.Dominio.Interfaces.Servicos; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Cs_IssPrefeitura.Aplicacao.ServicosApp { public class AppServicoConfiguracoes: AppServicoBase<Config>, IAppServicoConfiguracoes { private readonly IServicoConfiguracoes _servicoConfiguracoes; public AppServicoConfiguracoes(IServicoConfiguracoes servicoConfiguracoes) : base(servicoConfiguracoes) { _servicoConfiguracoes = servicoConfiguracoes; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Data; using System.Globalization; using System.Windows; namespace Common.Converter { [ValueConversion(typeof(DateTimeOffset), typeof(String))] public class DateConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { DateTimeOffset date = (DateTimeOffset)value; return date.DateTime.ToShortDateString() + " " + date.DateTime.ToShortTimeString(); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { string strValue = value as string; DateTimeOffset resultDateTime; if (DateTimeOffset.TryParse(strValue, out resultDateTime)) { return resultDateTime; } return DependencyProperty.UnsetValue; } } }
/* low pass filter to smooth sensor data * Author:Xiufeng Xie */ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace xxf_Server { class lowPass { //linear Low Pass Filter public static void lowPassFilter(ref double[] last_Output, ref bool cursor_brake_X, ref bool cursor_brake_Y, ref double in_Yaw, ref double in_Pitch, ref double in_Roll, out double out_Yaw, out double out_Pitch, out double out_Roll, out bool cursor_brake_X_out, out bool cursor_brake_Y_out, out double[] last_Output_out) { cursor_brake_X_out = cursor_brake_X; cursor_brake_Y_out = cursor_brake_X; //coefficient of the first-order low pass filter const double alpha = 0.08; //first order low-pass filter out_Yaw = (1 - alpha) * last_Output[0] + alpha * in_Yaw; out_Pitch = (1 - alpha) * last_Output[1] + alpha * in_Pitch; out_Roll = (1 - alpha) * last_Output[2] + alpha * in_Roll; /*brake system * if the absolute roll or pitch value become smaller, maybe the user wanted to stop the cursor */ //X axis if (Math.Abs(out_Roll) < Math.Abs(last_Output[2])) { cursor_brake_X_out = true; } else { cursor_brake_X_out = false; } //Y axis if (Math.Abs(out_Pitch) < Math.Abs(last_Output[1])) { cursor_brake_Y_out = true; } else { cursor_brake_Y_out = false; } //store the output for the LPF formula last_Output_out = last_Output; last_Output_out[0] = out_Yaw; last_Output_out[1] = out_Pitch; last_Output_out[2] = out_Roll; } } }
//Copyright © 2013 Dagorn Julien (julien.dagorn@gmail.com) //This work is free. You can redistribute it and/or modify it under the //terms of the Do What The Fuck You Want To Public License, Version 2, //as published by Sam Hocevar. See the COPYING file for more details. using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; namespace ActionGroupManager { class WindowRecap : UIObject { Rect recapWindowSize; Vector2 recapWindowScrollposition; public override void Initialize(params object[] list) { recapWindowSize = SettingsManager.Settings.GetValue<Rect>(SettingsManager.RecapWindocRect, new Rect(200, 200, 400, 500)); } public override void Terminate() { SettingsManager.Settings.SetValue(SettingsManager.RecapWindocRect, recapWindowSize); SettingsManager.Settings.SetValue(SettingsManager.IsRecapWindowVisible, IsVisible()); } public override void DoUILogic() { GUI.skin = HighLogic.Skin; recapWindowSize = GUILayout.Window(this.GetHashCode(), recapWindowSize, new GUI.WindowFunction(DoMyRecapView), "AGM : Recap", HighLogic.Skin.window, GUILayout.Width(200)); } private void DoMyRecapView(int id) { if (GUI.Button(new Rect(recapWindowSize.width - 24, 4, 20, 20), new GUIContent("X", "Close the window."), Style.CloseButtonStyle)) ActionGroupManager.Manager.ShowRecapWindow = false; recapWindowScrollposition = GUILayout.BeginScrollView(recapWindowScrollposition, Style.ScrollViewStyle); GUILayout.BeginVertical(); foreach (KSPActionGroup ag in VesselManager.Instance.AllActionGroups) { if (ag == KSPActionGroup.None) continue; List<BaseAction> list = BaseActionFilter.FromParts(VesselManager.Instance.GetParts(), ag).ToList(); if (list.Count > 0) { GUILayout.Label(ag.ToString() + " :", HighLogic.Skin.label); Dictionary<string, int> dic = new Dictionary<string, int>(); list.ForEach( (e) => { string str = e.listParent.part.partInfo.title + "\n(" + e.guiName + ")"; if (!dic.ContainsKey(str)) dic.Add(str, 1); else dic[str]++; }); foreach (KeyValuePair<string, int> pair in dic) { GUILayout.BeginHorizontal(); GUILayout.Space(20); string str = pair.Key; if (pair.Value > 1) str += " * " + pair.Value; GUILayout.Label(str, HighLogic.Skin.label); GUILayout.EndHorizontal(); } } } GUILayout.EndVertical(); GUILayout.EndScrollView(); GUI.DragWindow(); } public override void Reset() { } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using UnityEngine.InputSystem; using UnityEngine.SceneManagement; public class InputUIController : MonoBehaviour { private PrologueController prologueController; public SceneData sceneData; private GameObject player; void Start() { prologueController = GetComponent<PrologueController>(); player = GameObject.Find("Player"); } public void Move(InputAction.CallbackContext context) { if (context.started) { var value = context.ReadValue<Vector2>(); player.GetComponent<SpriteRenderer>().flipX = value.x < 0; } } public void onClick(InputAction.CallbackContext context) { if (context.started) { if (prologueController.stage != PrologueStage.CharacterSelect) { prologueController.Submit(); } else { if (!GameObject.Find("Dialogue").GetComponent<DialogueScript>().writing) { sceneData.SetPlayer(player.GetComponent<SpriteRenderer>().flipX ? ElementType.Electric : ElementType.Fire); SceneManager.LoadScene("SampleScene"); } } } } }
using PhobiaX.Game.GameObjects; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace PhobiaX.Physics { public class PathFinder { public IGameObject FindClosestTarget(IGameObject objectSearchingPath, IList<IGameObject> targets) { var closestDistance = double.MaxValue; var closesestTarget = targets.First(); foreach (var target in targets) { var xDiff = target.X - objectSearchingPath.X; var yDiff = target.Y - objectSearchingPath.Y; var distance = Math.Sqrt(xDiff * xDiff + yDiff * yDiff); if (distance < closestDistance) { closestDistance = distance; closesestTarget = target; } } return closesestTarget; } } }
using PopulationFitness.Models; using PopulationFitness.Models.Genes; using PopulationFitness.Models.Genes.BitSet; using System; using System.Collections.Generic; using System.Diagnostics; using NUnit.Framework; namespace TestPopulationFitness.UnitTests { [TestFixture] public class GenesDistributionTest { private const int Population = 40000; private const int NumberOfGenes = 100; private const int SizeOfGenes = 10; [TestCase(Function.Schwefel220, 1.0)] [TestCase(Function.SchumerSteiglitz, 1.0)] [TestCase(Function.Qing, 1.0)] [TestCase(Function.Griewank, 1.0)] [TestCase(Function.Exponential, 1.0)] [TestCase(Function.DixonPrice, 1.0)] [TestCase(Function.ChungReynolds, 1.0)] [TestCase(Function.Brown, 1.0)] [TestCase(Function.Alpine, 1.0)] [TestCase(Function.Ackleys, 1.0)] [TestCase(Function.SumOfPowers, 0.05)] [TestCase(Function.Rastrigin, 1.0)] [TestCase(Function.StyblinksiTang, 1.0)] [TestCase(Function.Rosenbrock, 1.0)] [TestCase(Function.Schwefel226, 0.01)] [TestCase(Function.Sphere, 1.0)] [TestCase(Function.SumSquares, 1.0)] public void GenesAreDistributedWithoutExcessiveSpikes(Function function, double fitness_factor) { BitSetGenesFactory factory = new BitSetGenesFactory(); RepeatableRandom.ResetSeed(); factory.FitnessFunction = function; // Given a number of randomly generated genes Config config = new Config { NumberOfGenes = NumberOfGenes, SizeOfEachGene = SizeOfGenes }; var genes = new List<IGenes>(); for (int i = 0; i < Population; i++) { var next = factory.Build(config); next.BuildFromRandom(); genes.Add(next); } // When the fitnesses are counted into a distribution var fitnesses = new int[100]; for (int i = 0; i < fitnesses.Length; i++) { fitnesses[i] = 0; } foreach (IGenes g in genes) { double fitness = g.Fitness * fitness_factor; int i = Math.Abs(Math.Min(99, (int)(fitness * 100))); fitnesses[i]++; } // Then the gene fitness is distributed without excessive spikes Debug.WriteLine(function.ToString()); foreach (int f in fitnesses) { Debug.WriteLine(f); Assert.True(f < 20 * (genes.Count / fitnesses.Length)); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; public class DeathMenuController : MonoBehaviour { public Text scoreText; public Image background; private bool isShowActive; private float transition; // Use this for initialization void Start () { transition = 0.0f; this.gameObject.SetActive(false); } // Update is called once per frame void Update () { if (!isShowActive) { return; } transition += Time.deltaTime; background.color = Color.Lerp(new Color(0,0,0,0), Color.black, transition); } public void ShowEndMenu(float score) { this.gameObject.SetActive(true); scoreText.text = ((int)score).ToString(); isShowActive = true; } public void PlayButton() { SceneManager.LoadScene(SceneManager.GetActiveScene().name); } public void MenuButton() { SceneManager.LoadScene("MainMenu"); } }
using System; using Xunit; namespace Terminal.Gui.TypeTests { public class RectTests { [Fact] public void Rect_New () { var rect = new Rect (); Assert.True (rect.IsEmpty); rect = new Rect (new Point (), new Size ()); Assert.True (rect.IsEmpty); rect = new Rect (1, 2, 3, 4); Assert.False (rect.IsEmpty); rect = new Rect (-1, -2, 3, 4); Assert.False (rect.IsEmpty); Action action = () => new Rect (1, 2, -3, 4); var ex = Assert.Throws<ArgumentException> (action); Assert.Equal ("Width must be greater or equal to 0.", ex.Message); action = () => new Rect (1, 2, 3, -4); ex = Assert.Throws<ArgumentException> (action); Assert.Equal ("Height must be greater or equal to 0.", ex.Message); action = () => new Rect (1, 2, -3, -4); ex = Assert.Throws<ArgumentException> (action); Assert.Equal ("Width must be greater or equal to 0.", ex.Message); } [Fact] public void Rect_SetsValue () { var rect = new Rect () { X = 0, Y = 0 }; Assert.True (rect.IsEmpty); rect = new Rect () { X = -1, Y = -2 }; Assert.False (rect.IsEmpty); rect = new Rect () { Width = 3, Height = 4 }; Assert.False (rect.IsEmpty); rect = new Rect () { X = -1, Y = -2, Width = 3, Height = 4 }; Assert.False (rect.IsEmpty); Action action = () => { rect = new Rect () { X = -1, Y = -2, Width = -3, Height = 4 }; }; var ex = Assert.Throws<ArgumentException> (action); Assert.Equal ("Width must be greater or equal to 0.", ex.Message); action = () => { rect = new Rect () { X = -1, Y = -2, Width = 3, Height = -4 }; }; ex = Assert.Throws<ArgumentException> (action); Assert.Equal ("Height must be greater or equal to 0.", ex.Message); action = () => { rect = new Rect () { X = -1, Y = -2, Width = -3, Height = -4 }; }; ex = Assert.Throws<ArgumentException> (action); Assert.Equal ("Width must be greater or equal to 0.", ex.Message); } [Fact] public void Rect_Equals () { var rect1 = new Rect (); var rect2 = new Rect (); Assert.Equal (rect1, rect2); rect1 = new Rect (1, 2, 3, 4); rect2 = new Rect (1, 2, 3, 4); Assert.Equal (rect1, rect2); rect1 = new Rect (1, 2, 3, 4); rect2 = new Rect (-1, 2, 3, 4); Assert.NotEqual (rect1, rect2); } [Fact] public void Positive_X_Y_Positions () { var rect = new Rect (10, 5, 100, 50); int yCount = 0, xCount = 0, yxCount = 0; for (int line = rect.Y; line < rect.Y + rect.Height; line++) { yCount++; xCount = 0; for (int col = rect.X; col < rect.X + rect.Width; col++) { xCount++; yxCount++; } } Assert.Equal (yCount, rect.Height); Assert.Equal (xCount, rect.Width); Assert.Equal (yxCount, rect.Height * rect.Width); } [Fact] public void Negative_X_Y_Positions () { var rect = new Rect (-10, -5, 100, 50); int yCount = 0, xCount = 0, yxCount = 0; for (int line = rect.Y; line < rect.Y + rect.Height; line++) { yCount++; xCount = 0; for (int col = rect.X; col < rect.X + rect.Width; col++) { xCount++; yxCount++; } } Assert.Equal (yCount, rect.Height); Assert.Equal (xCount, rect.Width); Assert.Equal (yxCount, rect.Height * rect.Width); } } }
namespace BartlettGenesisLogFileParser { internal class BartlettReportLine { public string FiringName { get; set; } public string FiringDate { get; set; } public string FiringCost { get; set; } public string FirmwareVersion { get; set; } public string CircuitBoardStartTemp { get; set; } public string CircuitBoardEndTemp { get; set; } public int SegmentNumber { get; set; } public string SegmentStart { get; set; } public string SegmentEnd { get; set; } public string SegmentClimbRate { get; set; } public string SegmentTargetTemp { get; set; } public string SegmentStartTemp { get; set; } public string SegmentHoldTime { get; set; } public string SegmentEndTemp { get; set; } public string TempDate { get; set; } public string Setpoint { get; set; } public string Temp { get; set; } } }
using CG.MovieAppEntity.Entities; using System; using System.Collections.Generic; using System.Text; namespace CG.MovieApp.Business.Interfaces { public interface ICategoryService : IGenericService<Category> { } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Transition : MonoBehaviour { public static Transition Instance { get; private set; } [SerializeField] private Animation animation = null; private void Awake() { if (Instance == null) { Instance = this; } } public void FadeBlack() { animation.Play("FadeBlack"); } public void FadeNormal() { animation.Play("FadeNormal"); } }
namespace BettingSystem.Startup.Betting.Specs { using System.Linq; using Application.Betting.Bets.Queries.Search; using Domain.Betting.Models.Bets; using FluentAssertions; using MyTested.AspNetCore.Mvc; using Web.Betting.Features; using Xunit; public class BetsControllerSpecs { [Fact] public void ControllerShouldHaveCorrectAttributes() => MyController<BetsController> .ShouldHave() .Attributes(attr => attr .RestrictingForAuthorizedRequests()); [Fact] public void SearchShouldHaveCorrectAttributes() => MyController<BetsController> .Calling(controller => controller .Search(With.Default<SearchBetsQuery>())) .ShouldHave() .ActionAttributes(attr => attr .RestrictingForHttpMethod(HttpMethod.Get)); //[Theory] //[InlineData(10)] //public void SearchShouldReturnAllBetsWithoutAQuery(int totalBets) // => MyPipeline // .Configuration() // .ShouldMap("/Bets") // .To<BetsController>(controller => controller // .Search(With.Empty<SearchBetsQuery>())) // .Which(instance => instance // .WithData(BetFakes.Data.GetBets(count: totalBets))) // .ShouldReturn() // .ActionResult<SearchBetsResponseModel>(result => result // .Passing(model => model // .Bets.Count().Should().Be(totalBets))); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Register.Repository { public class DatabaseConnection { public string Name { get; set; } public string DatabaseServerAddr { get; set; } public string DatabaseName { get; set; } public string DatabaseUser { get; set; } public string DatabasePassword { get; set; } public string ConnectionString => $"Server={DatabaseServerAddr}; database={DatabaseName}; User Id={DatabaseUser}; Password={DatabasePassword}"; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using System.IO; using UnityEngine.UI; /* Grabs the JSON file from a specified twitch channel /* Converts the JSON to a string of raw code */ public class ParseJSON : MonoBehaviour { public string channelName; public Text jsonConsole; private string jsonString = ""; private WWW www; // Use this for initialization void Start () { StartCoroutine(ReadFromJSON()); } // Update is called once per frame void Update () { } IEnumerator ReadFromJSON() { string url = "tmi.twitch.tv/group/user/" + channelName + "/chatters"; www = new WWW(url); yield return new WaitForSeconds(3); jsonString = www.text; if (jsonConsole != null) { jsonConsole.text = jsonString; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; //-------------------------------- using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; //-------------------------------- namespace Ejercicio_15 { class GestionPersona { string _fichero; public GestionPersona(string fichero) { _fichero = fichero; } #region MyMethods public string GenerarHtml() { // Crea un fichero con formato HTML con tabla para mostrar el contenido de las personas // DEVUELVE: La ruta del fichero html o un string vacio si no se creó. int nLinea = 1; string ficheroCreado = Path.ChangeExtension(_fichero, "html"); Persona tmp = null; StringBuilder docHtml = new StringBuilder(); if (!File.Exists(_fichero)) return ""; // Añadiendo etiquetas ... docHtml.Append("<html>"); docHtml.Append("<head>"); docHtml.Append("<title>Listado de Personas</title>"); docHtml.Append("</head>"); docHtml.Append("<body>"); docHtml.Append("<h1>Listado de Personas</h1>"); docHtml.Append("<table border='1'>"); docHtml.Append("<tr bgcolor='red'> <th>Orden</th> <th>Apellido</th> <th>Nombre</th> <th>Sueldo</th> <th>Fecha de Nacimiento</th> </tr>"); // Cuerpo con los datos ... using (FileStream flujo = new FileStream(_fichero, FileMode.Open, FileAccess.Read)) { IFormatter formate = new BinaryFormatter(); while (true) { try { tmp = (Persona)formate.Deserialize(flujo); if (tmp.Borrado) continue; if (nLinea % 2 == 0) docHtml.Append("<tr bgcolor='white'>"); else docHtml.Append("<tr bgcolor='yellow'>"); docHtml.Append("<td>" + nLinea++.ToString("000") + "</td>"); docHtml.Append("<td>" + tmp.Apellido + "</td>"); docHtml.Append("<td>" + tmp.Nombre + "</td>"); docHtml.Append("<td>" + tmp.Sueldo.ToString("0000.0") + "</td>"); docHtml.Append("<td>" + tmp.FechaNac.ToShortDateString() + "</td>"); docHtml.Append("</tr>"); } catch (Exception) { break; } }// Fin del while }// Fin using docHtml.Append("</table></body></html>"); // Crear el fichero de salida ... using (FileStream flujoSalida = new FileStream(ficheroCreado, FileMode.Create, FileAccess.Write)) { using(StreamWriter salido = new StreamWriter(flujoSalida, Encoding.Default)) { salido.Write(docHtml.ToString()); } } return ficheroCreado; } public bool Anadir(Persona persona) { // Forma de instanciar utilizando el Poliformismo IFormatter formato = new BinaryFormatter(); /* La forma normal de instanciar un objeto BinaryFormatter formatoB = new BinaryFormatter(); */ using(FileStream flujo = new FileStream(_fichero, FileMode.Append, FileAccess.Write)) { // Este método añade en flujo, del tiron, todo los campos de persona. formato.Serialize(flujo, persona); } return true; } public void AnadirVariasPruebas(int nPersonas) { string[] nombres = { "Pepe", "Hector", "Juan", "Sandra", "Alejandro", "Manuel", "Maria" }; string[] apellidos = { "Gil", "Muñoz", "Rodriguez", "Sanchez", "Garcia", "Moreno", "Pendor" }; Random rnd = new Random(); Persona tmp = null; // Añade varias personas a la lista Personas for (int i = 0; i < nPersonas; i++) { tmp = new Persona(apellidos[rnd.Next(apellidos.Length)], nombres[rnd.Next(nombres.Length)], (float)rnd.NextDouble() * 1000, DateTime.Now - TimeSpan.FromDays(rnd.Next(1, 365 * 20))); Anadir(tmp); } } public void Listar() { if (!File.Exists(_fichero)) { Console.Write("No hay datos a listar. El fichero {0} no existe...",_fichero); Console.ReadLine(); return; } Persona tmp = null; using (FileStream flujo = new FileStream(_fichero, FileMode.Open, FileAccess.Read)) { IFormatter formato = new BinaryFormatter(); while (true) { try { tmp = (Persona)formato.Deserialize(flujo); if (tmp.Borrado) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(tmp.ToString()); Console.ResetColor(); } Console.WriteLine(tmp.ToString()); } catch { // Se terminó el fichero break; } } } } public long Buscar(string apellido) { long PosPersonaAnterior = 0; long PosPersonaActual = 0; if (!File.Exists(_fichero)) return -1; // Si no existe sale cantando bajito. Persona tmp = null; using (FileStream flujo = new FileStream(_fichero, FileMode.Open, FileAccess.Read)) { IFormatter formato = new BinaryFormatter(); while (true) { try { PosPersonaAnterior = flujo.Position; // Esto es lo devuelto tmp = (Persona)formato.Deserialize(flujo); if (tmp.Apellido == apellido && !tmp.Borrado) { PosPersonaActual = flujo.Position; return PosPersonaAnterior; } } catch { return -1; } } } } public bool Borrar(long PosBorrar) { if (PosBorrar == -1) return false; Persona tmp = null; using (FileStream flujo = new FileStream(_fichero, FileMode.Open, FileAccess.ReadWrite)) { IFormatter formato = new BinaryFormatter(); flujo.Position = PosBorrar; tmp = (Persona)formato.Deserialize(flujo); tmp.Borrado = true; flujo.Position = PosBorrar; formato.Serialize(flujo, tmp); } return true; } public string Ver(long PosVer) { if (PosVer == -1) return ""; Persona tmp = null; using (FileStream flujo = new FileStream(_fichero, FileMode.Open, FileAccess.Read)) { IFormatter formato = new BinaryFormatter(); flujo.Position = PosVer; tmp = (Persona)formato.Deserialize(flujo); return tmp.Borrado ? "No encontrado" : tmp.ToString(); } } #endregion } }
using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using System.Web.Http.Description; using CYT.Entities; using CYT.Web.DataContext; using System.Threading.Tasks; using CYT.Web.FileUpload; using System.IO; using CYT.Web.FileManagement; namespace CYT.Web.Controllers.WebApi { public class RecipesController : ApiController { private CytDb db = new CytDb(); private FileManager fileManager = new FileManager(); // GET: api/Recipes public IQueryable<Recipe> GetRecipes() { return db.Recipes.Include(u => u.RecipeImages).Include(u => u.Ingredients).Include(u => u.RecipeCategory).Include(u => u.RecipeVotes).Include(u => u.User).Where(r => r.RecipeStatus == RecipeStatus.Approved); } // GET: api/Recipes/5 [ResponseType(typeof(Recipe))] public IHttpActionResult GetRecipe(int id) { Recipe recipe = db.Recipes.Find(id); if (recipe == null || recipe.RecipeStatus == RecipeStatus.Pending) { return NotFound(); } return Ok(recipe); } // GET: api/Recipes/5 [HttpGet] [Route("api/all/recipes")] [ResponseType(typeof(IEnumerable<Recipe>))] public IHttpActionResult GetAllRecipes() { IEnumerable<Recipe> recipes = db.Recipes.Include(u => u.RecipeImages).Include(u => u.Ingredients).Include(u => u.RecipeCategory).Include(u => u.RecipeVotes).Include(u => u.User); if (recipes == null ) { return NotFound(); } return Ok(recipes); } [HttpGet] [Route("api/user/recipes/{id:int}")] [ResponseType(typeof(IEnumerable<Recipe>))] public IHttpActionResult GetUserRecipes(int id) { IEnumerable<Recipe> recipes = db.Recipes.Where(r => r.UserId == id && r.RecipeStatus == RecipeStatus.Approved).Include(u => u.RecipeImages).Include(u => u.User).Include(u => u.RecipeCategory).Include(u => u.Ingredients); if (recipes == null) { return NotFound(); } return Ok(recipes); } [HttpGet] [Route("api/user/recipes/admin/{id:int}")] [ResponseType(typeof(IEnumerable<Recipe>))] public IHttpActionResult GetUserAdminRecipes(int id) { IEnumerable<Recipe> recipes = db.Recipes.Where(r => r.UserId == id).Include(u => u.RecipeImages).Include(u => u.User).Include(u => u.RecipeCategory).Include(u => u.Ingredients); if (recipes == null) { return NotFound(); } return Ok(recipes); } [HttpGet] [Route("api/recipe/{recipeId:int}")] [ResponseType(typeof(IEnumerable<Recipe>))] public IHttpActionResult GetFullRecipe(int recipeId) { IEnumerable<Recipe> recipe = db.Recipes.Where(r => r.RecipeId == recipeId && r.RecipeStatus == RecipeStatus.Approved).Include(u => u.RecipeImages).Include(u => u.User).Include(u => u.RecipeCategory).Include(u => u.Ingredients); if (recipe == null) { return NotFound(); } return Ok(recipe); } [HttpPost] [Route("api/search/recipes/category")] //[ResponseType(typeof(IEnumerable<Recipe>))] public IHttpActionResult SearchRecipesCategory(int categoryId, string[] ingridients) { IEnumerable<Recipe> recipes = db.Recipes.Where(r => r.RecipeCategoryId == categoryId && r.RecipeStatus == RecipeStatus.Approved).Include(u => u.RecipeImages).Include(u => u.User).Include(u => u.RecipeCategory).Include(u => u.RecipeVotes).Include(i => i.Ingredients); if (recipes == null) { return NotFound(); } return Ok(recipes); } [HttpPost] [Route("api/search/recipes")] //[ResponseType(typeof(IEnumerable<Recipe>))] public IHttpActionResult SearchRecipes(string[] ingridients) { //IEnumerable<Recipe> recipes = db.Recipes.Where(r => r.RecipeId == recipeId && r.RecipeStatus == RecipeStatus.Approved).Include(u => u.RecipeImages).Include(u => u.User).Include(u => u.RecipeCategory).Include(u => u.Ingredients); //if (recipes == null) //{ // return NotFound(); //} return Ok(); } [HttpGet] [Route("api/similar/recipes/{recipeId:int}")] [ResponseType(typeof(IEnumerable<Recipe>))] public IHttpActionResult GetSimilarRecipes(int recipeId) { Recipe recipe = db.Recipes.Find(recipeId); if (recipe == null) { return NotFound(); } IEnumerable<Recipe> recipes = db.Recipes.Where(u => u.RecipeCategoryId == recipe.RecipeCategoryId && u.RecipeStatus == RecipeStatus.Approved).OrderByDescending(u => u.Rating).Take(3).Include(i => i.RecipeImages).ToList(); if (recipes == null) { return NotFound(); } return Ok(recipes); } // PUT: api/Recipes/5 [ResponseType(typeof(void))] public IHttpActionResult PutRecipe(int id, Recipe recipe) { if (!ModelState.IsValid) { return BadRequest(ModelState); } if (id != recipe.RecipeId) { return BadRequest(); } //foreach (Ingredient ingredient in recipe.Ingredients) //{ // if (ingredient.RecipeId == 0) // { // ingredient.RecipeId = recipe.RecipeId; // db.Entry(ingredient).State = EntityState.Added; // } //} db.Entry(recipe).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { if (!RecipeExists(id)) { return NotFound(); } else { throw; } } return StatusCode(HttpStatusCode.NoContent); } [HttpPost] [Route("api/upload/recipes/image/{recipeId:int}/{userId:int}")] public async Task<IHttpActionResult> UploadRecipeImage(int recipeId, int userId, HttpRequestMessage request) { RecipeImage image = new RecipeImage(); string directory = fileManager.GetRecipeDirectoryPath(userId, recipeId); MultipartFormDataStreamProvider provider = new GuidMultipartFormDataStreamProvider(directory); FileUploader fileUploader = new FileUploader(request, provider, null); FileUploadResult uploadResult = await fileUploader.Upload(); if (uploadResult.Status != FileUploadStatus.Success) return BadRequest(uploadResult.Messages); FileInfo fileInfo = fileUploader.GetFileInfo(); image.Description = ""; image.RecipeId = recipeId; image.TimeCreated = DateTime.Now; image.ImageUrl = fileManager.GetRecipeImageFileUrl(userId, recipeId, fileInfo.Name); db.RecipeImages.Add(image); db.SaveChanges(); return Ok(image); } [HttpPost] [Route("api/recipe/update/{recipeId:bool}")] [ResponseType(typeof(Recipe))] public IHttpActionResult RecipeUpdate(bool recipeId, Recipe recipe) { Recipe re = db.Recipes.Find(recipe.RecipeId); if (recipe == null) { return NotFound(); } if (recipeId) { re.RecipeStatus = RecipeStatus.Approved; } else re.RecipeStatus = RecipeStatus.Disabled; db.Entry(re).State = EntityState.Modified; db.SaveChanges(); return StatusCode(HttpStatusCode.NoContent); } // POST: api/Recipes [ResponseType(typeof(Recipe))] public IHttpActionResult PostRecipe(Recipe recipe) { User user = db.Users.Single(u => u.Username == User.Identity.Name); if(user == null){ return BadRequest(); } recipe.TimeCreated = DateTime.Now; recipe.RecipeImages = new List<RecipeImage>(); recipe.RecipeVotes = new List<RecipeVote>(); recipe.Rating = 0; recipe.UserId = user.UserId; recipe.RecipeStatus = RecipeStatus.Pending; if (!ModelState.IsValid) { return BadRequest(ModelState); } db.Recipes.Add(recipe); db.SaveChanges(); return CreatedAtRoute("DefaultApi", new { id = recipe.RecipeId }, recipe); } // DELETE: api/Recipes/5 [ResponseType(typeof(Recipe))] public IHttpActionResult DeleteRecipe(int id) { Recipe recipe = db.Recipes.Find(id); if (recipe == null) { return NotFound(); } db.Recipes.Remove(recipe); db.SaveChanges(); return Ok(recipe); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } private bool RecipeExists(int id) { return db.Recipes.Count(e => e.RecipeId == id) > 0; } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Threading.Tasks; namespace ERPApplication.Models.DomainModels { public class Company { public int Id { get; set; } public string CompanyName { get; set; } public int BaseCurrency { get; set; } public string CreatedBy { get; set; } [ForeignKey("CreatedBy")] public ApplicationUser User { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using System.Collections; using System.Reflection; using IRAP.Global; using IRAP.Server.Global; using IRAP.Entities.MES; using IRAP.Entities.MES.Tables; using IRAPORM; using IRAPShared; using IRAPShared.Json; using IRAP.BL.MDM; namespace IRAP.BL.MES { public class ManualInspecting : IRAPBLLBase { private static string className = MethodBase.GetCurrentMethod().DeclaringType.FullName; public ManualInspecting() { WriteLog.Instance.WriteLogFileName = MethodBase.GetCurrentMethod().DeclaringType.Namespace; } /// <summary> /// 申请序列号 /// ⒈ 申请预定义序列的一个或多个序列号; /// ⒉ 如果序列是交易号的,自动写交易日志。 /// </summary> /// <param name="communityID">社区标识</param> /// <param name="sequenceCode">序列代码</param> /// <param name="count">申请序列值个数</param> /// <param name="sysLogID">系统登录标识</param> /// <param name="opNode">业务操作节点列表</param> /// <param name="voucherNo">业务凭证号</param> /// <returns>申请到的第一个序列值[long]</returns> private void ssp_GetSequenceNo( int communityID, string sequenceCode, int count, long sysLogID, string opNode, string voucherNo, ref long sequenceNo, out int errCode, out string errText) { string strProcedureName = string.Format( "{0}.{1}", className, MethodBase.GetCurrentMethod().Name); WriteLog.Instance.WriteBeginSplitter(strProcedureName); try { sequenceNo = 0; Hashtable rlt = new Hashtable(); #region 创建数据库调用参数组,并赋值 IList<IDataParameter> paramList = new List<IDataParameter>(); paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID)); paramList.Add(new IRAPProcParameter("@SequenceCode", DbType.String, sequenceCode)); paramList.Add(new IRAPProcParameter("@Count", DbType.Int32, count)); paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID)); paramList.Add(new IRAPProcParameter("@OpNode", DbType.String, opNode)); paramList.Add(new IRAPProcParameter("@VoucherNo", DbType.String, voucherNo)); paramList.Add(new IRAPProcParameter("@SequenceNo", DbType.Int64, ParameterDirection.Output, 8)); paramList.Add(new IRAPProcParameter("@ErrCode", DbType.Int32, ParameterDirection.Output, 4)); paramList.Add(new IRAPProcParameter("@ErrText", DbType.String, ParameterDirection.Output, 400)); WriteLog.Instance.Write( string.Format( "调用 IRAP..ssp_GetSequenceNo,输入参数:" + "CommunityID={0}|SequenceCode={1}|Count={2}|SysLogID={3}" + "OpNode={4}|VoucherNo={5}", communityID, sequenceCode, count, sysLogID, opNode, voucherNo), strProcedureName); #endregion #region 执行数据库函数或存储过程 try { using (IRAPSQLConnection conn = new IRAPSQLConnection()) { IRAPError error = conn.CallProc("IRAP..ssp_GetSequenceNo", ref paramList); errCode = error.ErrCode; errText = error.ErrText; rlt = DBUtils.DBParamsToHashtable(paramList); if (rlt["SequenceNo"] != null) sequenceNo = (long)rlt["SequenceNo"]; } } catch (Exception error) { errCode = 99000; errText = string.Format("调用 IRAP..ssp_GetSequenceNo 函数发生异常:{0}", error.Message); WriteLog.Instance.Write(errText, strProcedureName); WriteLog.Instance.Write(error.StackTrace, strProcedureName); } #endregion } finally { WriteLog.Instance.WriteEndSplitter(strProcedureName); } } /// <summary> /// 计算 QCStatus 的值 /// </summary> /// <param name="communityID">社区标识</param> /// <param name="t102LeafID">产品叶标识</param> /// <param name="t107LeafID">工位叶标识</param> /// <param name="pwoNo">工单号</param> /// <param name="qcStatus">质量控制状态</param> private long CalculateQCStatus( int communityID, int t102LeafID, int t107LeafID, string pwoNo, long qcStatus) { string strProcedureName = string.Format( "{0}.{1}", className, MethodBase.GetCurrentMethod().Name); WriteLog.Instance.WriteBeginSplitter(strProcedureName); try { int errCode = 0; string errText = ""; QC qc = new QC(); try { IRAPJsonResult rlt = qc.ufn_GetQCCheckPointOrdinal( communityID, t102LeafID, t107LeafID, pwoNo, out errCode, out errText); int qcCheckPointOrdinal = (int)IRAPJsonSerializer.Deserializer( rlt.Json, typeof(int)); if (errCode == 0) { qcStatus = qcStatus | Int64.Parse(Math.Pow(2, (23 + qcCheckPointOrdinal)).ToString()); } } catch (Exception error) { WriteLog.Instance.Write(error.Message, strProcedureName); } return qcStatus; } finally { WriteLog.Instance.WriteEndSplitter(strProcedureName); } } /// <summary> /// 获取指定在制品经过指定工位的次数 /// </summary> /// <param name="t102LeafID">产品叶标识</param> /// <param name="t107LeafID">工位叶标识</param> /// <param name="wipCode">在制品主标识代码</param> private int ufn_GetWIPPassByTimes( int communityID, int t102LeafID, int t107LeafID, string wipCode) { string strProcedureName = string.Format( "{0}.{1}", className, MethodBase.GetCurrentMethod().Name); WriteLog.Instance.WriteBeginSplitter(strProcedureName); try { int errCode = 0; string errText = ""; WIP wip = new WIP(); try { IRAPJsonResult rlt = wip.ufn_GetWIPPassByTimes( communityID, t102LeafID, t107LeafID, wipCode, out errCode, out errText); return (int)IRAPJsonSerializer.Deserializer(rlt.Json, typeof(int)); } catch (Exception error) { WriteLog.Instance.Write(error.Message, strProcedureName); return 0; } } finally { WriteLog.Instance.WriteEndSplitter(strProcedureName); } } /// <summary> /// 获取工序标准周期时间 /// </summary> /// <param name="t102LeafID">产品叶标识</param> /// <param name="t107LeafID">工位叶标识</param> private long ufn_GetStdCycleTimeOfOperation( int communityID, int t102LeafID, int t107LeafID) { string strProcedureName = string.Format( "{0}.{1}", className, MethodBase.GetCurrentMethod().Name); WriteLog.Instance.WriteBeginSplitter(strProcedureName); try { int errCode = 0; string errText = ""; IRAPMDM mdm = new IRAPMDM(); try { IRAPJsonResult rlt = mdm.ufn_GetStdCycleTimeOfOperation( communityID, t102LeafID, t107LeafID, out errCode, out errText); return (long)IRAPJsonSerializer.Deserializer(rlt.Json, typeof(long)); } catch (Exception error) { WriteLog.Instance.Write(error.Message, strProcedureName); return 0; } } finally { WriteLog.Instance.WriteEndSplitter(strProcedureName); } } /// <summary> /// 人工检查实体对象中是否有子板需要送修 /// </summary> /// <param name="wipInspecting"></param> /// <returns></returns> private bool NeedRepair(Inspecting wipInspecting) { foreach (SubWIPIDCodeInfo_Inspecting subWIP in wipInspecting.SubWIPIDCodes) { if (subWIP.InspectingStatus == 3) return true; } return false; } /// <summary> /// 根据工位呼叫安灯记录计算工位停产时间(秒) /// </summary> /// <param name="t107LeafID">工位叶标识</param> /// <param name="periodBegin">期间开始时间</param> /// <param name="periodEnd">期间结束时间</param> /// <returns>long</returns> private long ufn_GetUnscheduledPDTofAWorkUnit( int communityID, int t107LeafID, DateTime periodBegin, DateTime periodEnd, long sysLogID) { string strProcedureName = string.Format( "{0}.{1}", className, MethodBase.GetCurrentMethod().Name); WriteLog.Instance.WriteBeginSplitter(strProcedureName); try { int errCode = 0; string errText = ""; WorkUnit workUnit = new WorkUnit(); try { IRAPJsonResult rlt = workUnit.ufn_GetUnscheduledPDTofAWorkUnit( communityID, t107LeafID, periodBegin, periodEnd, sysLogID, out errCode, out errText); return (long)IRAPJsonSerializer.Deserializer(rlt.Json, typeof(long)); } catch (Exception error) { WriteLog.Instance.Write(error.Message, strProcedureName); return 0; } } finally { WriteLog.Instance.WriteEndSplitter(strProcedureName); } } /// <summary> /// /// </summary> /// <param name="communityID">社区标识</param> /// <param name="transactNo">申请到的交易号</param> /// <param name="factID">申请到的事实编号</param> /// <param name="t102LeafID">产品叶标识</param> /// <param name="t107LeafID">工位叶标识</param> /// <param name="pwoNo">生产工单号</param> /// <param name="rsFactXML">检查结果 XML /// [RSFact] /// [RF17 Ordinal="" T118LeafID="" Metric01="" /] /// [/RSFact] /// </param> /// <param name="inspectedQty">检查总不良品数量</param> /// <param name="sysLogID">系统登录标识</param> public IRAPJsonResult usp_SaveFact_FailureInspecting( int communityID, long transactNo, long factID, int t102LeafID, int t107LeafID, string pwoNo, string rsFactXML, long inspectedQty, long sysLogID, out int errCode, out string errText) { string strProcedureName = string.Format( "{0}.{1}", className, MethodBase.GetCurrentMethod().Name); WriteLog.Instance.WriteBeginSplitter(strProcedureName); try { #region 创建数据库调用参数组,并赋值 IList<IDataParameter> paramList = new List<IDataParameter>(); paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID)); paramList.Add(new IRAPProcParameter("@TransactNo", DbType.Int64, transactNo)); paramList.Add(new IRAPProcParameter("@FactID", DbType.Int64, factID)); paramList.Add(new IRAPProcParameter("@T102LeafID", DbType.Int32, t102LeafID)); paramList.Add(new IRAPProcParameter("@T107LeafID", DbType.Int32, t107LeafID)); paramList.Add(new IRAPProcParameter("@PWONo", DbType.String, pwoNo)); paramList.Add(new IRAPProcParameter("@RSFactXML", DbType.String, rsFactXML)); paramList.Add(new IRAPProcParameter("@InspectedQty", DbType.Int64, inspectedQty)); paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID)); paramList.Add(new IRAPProcParameter("@ErrCode", DbType.Int32, ParameterDirection.Output, 4)); paramList.Add(new IRAPProcParameter("@ErrText", DbType.String, ParameterDirection.Output, 400)); WriteLog.Instance.Write( string.Format( "执行存储过程 IRAPMES..usp_SaveFact_FailureInspecting,参数:"+ "CommunityID={0}|TransactNo={1}|FactID={2}|"+ "T102LeafID={3}|T107LeafID={4}|PWONo={5}|"+ "RSFactXML={6}|InspectedQty={7}|SysLogID={8}", communityID, transactNo, factID, t102LeafID, t107LeafID, pwoNo, rsFactXML, inspectedQty, sysLogID), strProcedureName); #endregion #region 执行数据库函数或存储过程 using (IRAPSQLConnection conn = new IRAPSQLConnection()) { IRAPError error = conn.CallProc("IRAPMES..usp_SaveFact_FailureInspecting", ref paramList); errCode = error.ErrCode; errText = error.ErrText; return Json(error); } #endregion } catch (Exception error) { errCode = 99000; errText = string.Format( "调用 IRAPMES..usp_SaveFact_FailureInspecting 函数发生异常:{0}", error.Message); return Json( new IRAPError() { ErrCode = errCode, ErrText = errText, }); } finally { WriteLog.Instance.WriteEndSplitter(strProcedureName); } } /// <summary> /// 人工检查记录保存 /// </summary> /// <param name="userCode">系统登录用户号</param> /// <param name="agencyLeaf">登录用户的机构叶标识</param> /// <param name="productLeaf">产品叶标识</param> /// <param name="workUnitLeaf">工位叶标识</param> /// <param name="t107EntityID">工位实体标识</param> /// <param name="t132LeafID">产品族叶标识</param> /// <param name="containerNo">容器号</param> /// <param name="functionName">功能名称</param> /// <param name="wipInspecting">人工检查实体对象</param> /// <param name="confirmTime">检查确认时间</param> /// <returns></returns> public IRAPJsonResult msp_SaveFact_ManualInspecting( int communityID, string userCode, int agencyLeaf, int productLeaf, int workUnitLeaf, int t107EntityID, int t132LeafID, string containerNo, string functionName, Inspecting wipInspecting, DateTime confirmTime, long sysLogID, out int errCode, out string errText) { string strProcedureName = string.Format("{0}.{1}", className, MethodBase.GetCurrentMethod().Name); WriteLog.Instance.WriteBeginSplitter(strProcedureName); try { WriteLog.Instance.Write(string.Format("CommunityID={0}|UserCode={1}|AgencyLeaf={2}|" + "ProductLeaf={3}|WorkUnitLeaf={4}|T107EntityID={5}|T132LeafID={6}|" + "ContainerNo={7}|FunctionName={8}|ConfirmTime={9}|SysLogID={10}", communityID, userCode, agencyLeaf, productLeaf, workUnitLeaf, t107EntityID, t132LeafID, containerNo, functionName, confirmTime, sysLogID), strProcedureName); using (IRAPSQLConnection conn = new IRAPSQLConnection()) { long transactNo = 0; #region 申请交易号 WriteLog.Instance.Write("开始申请交易号", strProcedureName); try { ssp_GetSequenceNo( communityID, "NextTransactNo", 1, sysLogID, "-6", "", ref transactNo, out errCode, out errText); WriteLog.Instance.Write( string.Format("({0}){1}", errCode, errText), strProcedureName); if (errCode == 0) { WriteLog.Instance.Write(string.Format("申请到的交易号:{0}", transactNo), strProcedureName); } else { errCode = 99001; errText = string.Format("申请交易号出错:{0}", errText); WriteLog.Instance.Write(errText, strProcedureName); return Json(errCode); } } catch (Exception error) { errCode = 99001; errText = string.Format("申请交易号出错:{0}", error.Message); WriteLog.Instance.Write(errText, strProcedureName); WriteLog.Instance.Write(error.StackTrace, strProcedureName); return Json(errCode); } #endregion int passByTimes = ufn_GetWIPPassByTimes( communityID, productLeaf, workUnitLeaf, wipInspecting.MainWIPIDCode.WIPCode); long stdcycleTimeOfOperation = ufn_GetStdCycleTimeOfOperation( communityID, productLeaf, workUnitLeaf); long unscheduledPDTofAWorkUnit = ufn_GetUnscheduledPDTofAWorkUnit( communityID, workUnitLeaf, wipInspecting.MainWIPIDCode.MoveInTime, confirmTime, sysLogID); // 开始事务处理 conn.BeginTran(); foreach (SubWIPIDCodeInfo_Inspecting wip in wipInspecting.SubWIPIDCodes) { long factID = 0; long partitionPolicy = 0; long factPartitioningKey = 0; #region 申请事实编号 try { factID = IRAPDAL.UTS.Instance.msp_GetSequenceNo("NextFactNo", 1); } catch (Exception error) { errCode = 99001; errText = string.Format("申请事实编号出错:{0}", error.Message); WriteLog.Instance.Write(errText, strProcedureName); WriteLog.Instance.Write(error.StackTrace, strProcedureName); conn.RollBack(); return Json(errCode); } if (factID <= 0) { errCode = 99001; errText = "未申请到事实编号!"; WriteLog.Instance.Write(errText, strProcedureName); conn.RollBack(); return Json(errCode); } else { WriteLog.Instance.Write(string.Format("申请到的事实编号:{0}", factID), strProcedureName); } #endregion #region 在行集事实表(RSFact_Inspecting)中添加纪录 WriteLog.Instance.Write("保存行集事实", strProcedureName); partitionPolicy = Int64.Parse(DateTime.Now.Year.ToString() + (100000000L + communityID).ToString().Substring(1, 8) + "0006"); wip.GetListFromDataTable(); for (int i = 0; i < wip.FailureItems.Count; i++) { RSFact_Inspecting rsFactInspecting = new RSFact_Inspecting() { FactID = factID, PartitionPolicy = partitionPolicy, WFInstanceID = wipInspecting.MainWIPIDCode.PWONo, Ordinal = i + 1, T101LeafID = wip.FailureItems[i].T101LeafID, T110LeafID = wip.FailureItems[i].T110LeafID, T118LeafID = wip.FailureItems[i].T118LeafID, T216LeafID = wip.FailureItems[i].T216LeafID, T183LeafID = wip.FailureItems[i].T183LeafID, T184LeafID = wip.FailureItems[i].T184LeafID, CntDefect = wip.FailureItems[i].CntDefect, }; try { conn.Insert(rsFactInspecting); } catch (Exception error) { errCode = 99002; errText = string.Format("保存行集事实失败:{0}", error.Message); WriteLog.Instance.Write(errText, strProcedureName); WriteLog.Instance.Write(error.StackTrace, strProcedureName); conn.RollBack(); return Json(errCode); } } WriteLog.Instance.Write("行集事实保存完成", strProcedureName); #endregion #region 在辅助事实表(AuxFact_PDC)中添加纪录 WriteLog.Instance.Write("保存辅助事实", strProcedureName); partitionPolicy = Int64.Parse(communityID.ToString() + (100000000L + t132LeafID).ToString().Substring(1, 8) + DateTime.Now.Year.ToString()); factPartitioningKey = Int64.Parse(DateTime.Now.Year.ToString() + (100000000L + communityID).ToString().Substring(1, 8) + "0006"); AuxFact_PDC auxFactPDC = new AuxFact_PDC() { FactID = factID, PartitioningKey = partitionPolicy, FactPartitioningKey = factPartitioningKey, WFInstanceID = wipInspecting.MainWIPIDCode.PWONo, WIPCode = wip.SubWIPIDCode, AltWIPCode = wipInspecting.MainWIPIDCode.AltWIPCode, SerialNumber = wipInspecting.MainWIPIDCode.SerialNumber, LotNumber = wipInspecting.MainWIPIDCode.LotNumber, ContainerNo = containerNo, FakePreventingCode = "", CustomerAssignedID = "", ElectronicProductCode = "", }; #region 计算 QCStatus 值 if (wip.InspectingStatus == 3) wip.QCStatus = CalculateQCStatus(communityID, productLeaf, workUnitLeaf, wipInspecting.MainWIPIDCode.PWONo, wip.QCStatus); auxFactPDC.QCStatus = wip.QCStatus; #endregion try { conn.Insert(auxFactPDC); } catch (Exception error) { errCode = 99002; errText = string.Format("保存辅助事实表失败:{0}", error.Message); WriteLog.Instance.Write(errText, strProcedureName); WriteLog.Instance.Write(error.StackTrace, strProcedureName); conn.RollBack(); return Json(errCode); } WriteLog.Instance.Write("辅助事实保存完成", strProcedureName); #endregion #region 在主事实表(FixedFact_MES)中添加记录 WriteLog.Instance.Write("保存主事实", strProcedureName); partitionPolicy = Int64.Parse(DateTime.Now.Year.ToString() + (100000000L + communityID).ToString().Substring(1, 8) + "0006"); #region 准备需要保存的数据 FixedFact_MES fixedFactMES = new FixedFact_MES() { FactID = factID, PartitioningKey = partitionPolicy, TransactNo = transactNo, IsFixed = 1, OpID = 6, OpType = wip.InspectingStatus, BusinessDate = confirmTime, Code01 = wipInspecting.MainWIPIDCode.T102Code, Code02 = wipInspecting.MainWIPIDCode.T120Code, Code03 = wipInspecting.MainWIPIDCode.T107Code, Code04 = wipInspecting.MainWIPIDCode.T126Code, Code05 = wipInspecting.MainWIPIDCode.T1Code, Code06 = wipInspecting.MainWIPIDCode.T134Code, Code07 = wipInspecting.MainWIPIDCode.T181Code, Code08 = wipInspecting.MainWIPIDCode.T1002Code, Leaf01 = wipInspecting.MainWIPIDCode.T102Leaf, Leaf02 = wipInspecting.MainWIPIDCode.T120Leaf, Leaf03 = wipInspecting.MainWIPIDCode.T107Leaf, Leaf04 = wipInspecting.MainWIPIDCode.T126Leaf, Leaf05 = wipInspecting.MainWIPIDCode.T1Leaf, Leaf06 = wipInspecting.MainWIPIDCode.T134Leaf, Leaf07 = wipInspecting.MainWIPIDCode.T181Leaf, Leaf08 = wipInspecting.MainWIPIDCode.T1002Leaf, }; fixedFactMES.AChecksum = 0; fixedFactMES.CorrelationID = 0; fixedFactMES.Metric01 = 1; // 此处应该由前台传入 fixedFactMES.Metric02 = passByTimes; fixedFactMES.Metric03 = 1; fixedFactMES.Metric04 = Int64.Parse((confirmTime - wipInspecting.MainWIPIDCode.MoveInTime).TotalMilliseconds.ToString()) / wipInspecting.MainWIPIDCode.NumOfSubWIPs; fixedFactMES.Metric05 = fixedFactMES.Metric04 + fixedFactMES.Metric02; fixedFactMES.Metric06 = fixedFactMES.Metric04 + fixedFactMES.Metric03; fixedFactMES.Metric07 = stdcycleTimeOfOperation; fixedFactMES.Metric08 = TimeParser.LocalTimeToUnix(confirmTime); fixedFactMES.Metric09 = (long)(wipInspecting.ScanTime - wipInspecting.MainWIPIDCode.MoveInTime).TotalMilliseconds; fixedFactMES.Metric10 = unscheduledPDTofAWorkUnit; fixedFactMES.BChecksum = 0; fixedFactMES.MeasurementID = 0; fixedFactMES.WFInstanceID = wipInspecting.MainWIPIDCode.PWONo; fixedFactMES.Remark = functionName; fixedFactMES.LinkedFactID = 0; #endregion #region 添加记录 try { conn.Insert(fixedFactMES); } catch (Exception error) { errCode = 99002; errText = string.Format("保存主事实表失败:{0}", error.Message); WriteLog.Instance.Write(errText, strProcedureName); WriteLog.Instance.Write(error.StackTrace, strProcedureName); conn.RollBack(); return Json(errCode); } #endregion WriteLog.Instance.Write("主事实保存完成", strProcedureName); #endregion } if (NeedRepair(wipInspecting)) { #region 调整路由送修(IRAPMES..usp_MarkNGWIP) { WriteLog.Instance.Write("调整路由送修", strProcedureName); WIP wip = new WIP(); try { IRAPJsonResult rlt = wip.usp_MarkNGWIP( communityID, productLeaf, wipInspecting.MainWIPIDCode.WIPCode, wipInspecting.MainWIPIDCode.LotNumber, containerNo, wipInspecting.MainWIPIDCode.PWONo, wipInspecting.MainWIPIDCode.QCStatus, workUnitLeaf, 0, sysLogID, out errCode, out errText); WriteLog.Instance.Write(string.Format("({0}){1}", errCode, errText), strProcedureName); if (errCode != 0) { conn.RollBack(); return Json(errCode); } } catch (Exception error) { errCode = 99003; errText = string.Format("调用 usp_MarkNGWIP 失败:{0}", error.Message); WriteLog.Instance.Write(errText, strProcedureName); WriteLog.Instance.Write(error.StackTrace, strProcedureName); conn.RollBack(); return Json(errCode); } WriteLog.Instance.Write("路由送修调整完毕", strProcedureName); } #endregion } else { #region 调整路由(IRAPMES..usp_WIPForward) { WriteLog.Instance.Write("调整路由", strProcedureName); WIP wip = new WIP(); try { IRAPJsonResult rlt = wip.usp_WIPForward( communityID, productLeaf, wipInspecting.MainWIPIDCode.WIPPattern, wipInspecting.MainWIPIDCode.LotNumber, containerNo, wipInspecting.MainWIPIDCode.PWONo, wipInspecting.MainWIPIDCode.QCStatus, workUnitLeaf, 0, sysLogID, out errCode, out errText); WriteLog.Instance.Write(string.Format("({0}){1}", errCode, errText), strProcedureName); if (errCode != 0) { conn.RollBack(); return Json(errCode); } } catch (Exception error) { errCode = 99003; errText = string.Format("调用 usp_WIPForward 失败:{0}", error.Message); WriteLog.Instance.Write(errText, strProcedureName); WriteLog.Instance.Write(error.StackTrace, strProcedureName); conn.RollBack(); return Json(errCode); } WriteLog.Instance.Write("路由调整完成", strProcedureName); } #endregion } #region 更新工位的第二个瞬态属性(IRAPMDM..stb060) { WriteLog.Instance.Write("更新工位第二个瞬态属性", strProcedureName); int partitioningKey = Int32.Parse(communityID.ToString() + "0107"); List<IDataParameter> paramList = new List<IDataParameter>(); paramList.Add(new IRAPProcParameter("@Statistic02", DbType.Int64, TimeParser.LocalTimeToUnix(confirmTime))); paramList.Add(new IRAPProcParameter("@PartitioningKey", DbType.Int64, partitioningKey)); paramList.Add(new IRAPProcParameter("@T107EntityID", DbType.Int32, t107EntityID)); try { conn.Update("UPDATE IRAPMDM..stb060 SET Statistic02 = @Statistic02 " + "WHERE PartitioningKey = @PartitioningKey AND EntityID = @T107EntityID", paramList); } catch (Exception error) { errCode = 99004; errText = string.Format("更新工位(IRAPMDM..stb060)的第二个瞬态属性失败:{0}", error.Message); WriteLog.Instance.Write(errText, strProcedureName); WriteLog.Instance.Write(error.StackTrace, strProcedureName); conn.RollBack(); return Json(errCode); } WriteLog.Instance.Write("工位第二个瞬态属性更新完成", strProcedureName); } #endregion #region 交易复核(IRAPMES..stb010) { WriteLog.Instance.Write("交易复核", strProcedureName); long partitionPolicy = Int64.Parse(confirmTime.Year.ToString() + (100000000L + communityID).ToString().Substring(1, 8)); List<IDataParameter> paramList = new List<IDataParameter>(); paramList.Add(new IRAPProcParameter("@OkayTime", DbType.DateTime2, confirmTime)); paramList.Add(new IRAPProcParameter("@AgencyLeaf2", DbType.Int32, agencyLeaf)); paramList.Add(new IRAPProcParameter("@Checked", DbType.String, userCode)); paramList.Add(new IRAPProcParameter("@TransactNo", DbType.Int64, transactNo)); paramList.Add(new IRAPProcParameter("@PartitioningKey", DbType.Int64, partitionPolicy)); try { conn.Update("UPDATE IRAPMES..stb010 SET OkayTime = @OkayTime, " + "AgencyLeaf2 = @AgencyLeaf2, Checked = @Checked, " + "Status = 5 WHERE TransactNo = @TransactNo AND " + "PartitioningKey = @PartitioningKey", paramList); } catch (Exception error) { errCode = 99004; errText = string.Format("交易复核(IRAPMES..stb010)失败:{0}", error.Message); WriteLog.Instance.Write(errText, strProcedureName); WriteLog.Instance.Write(error.StackTrace, strProcedureName); conn.RollBack(); return Json(errCode); } WriteLog.Instance.Write("交易复核完成", strProcedureName); } #endregion conn.Commit(); errCode = 0; errText = "保存成功"; return Json(errCode); } } finally { WriteLog.Instance.WriteEndSplitter(strProcedureName); } } } }
 namespace Data.Common.QueryBuilder { public class Sorting { public string FieldName { get; set; } public SortDirection SortDirection { get; set; } } }
using UnityEngine; using System.Collections; /* * Test showing the Pimp system in action * */ [ExecuteInEditMode()] public class PimpedTest : PimpedMonoBehaviour { [SerializeField] [Tooltip("Expose a private secret about the hero")] private string privateSecret = "The gold is in the basement under the rug"; [System.Serializable] public class Ability { [Group("Physical properties")] public int agility; [Group("Physical properties")] public int strength; [Group("Physical properties")] public int speed; [Group("Mental properties")] public int iq; [Group("Mental properties")] public int persuasion; [Group("Mental properties")] public int focus; public float mentalAverage { get { return (iq + persuasion + focus) / 3.0f; }} public float physicalAverage { get { return (agility + strength + speed) / 3.0f; }} [GetSetVisible] public int level { get { return Mathf.FloorToInt((mentalAverage + physicalAverage) / 2.0f); } set { int toLevel = value < 0 ? 0 : value; int increase = toLevel - level; iq += increase; persuasion += increase; focus += increase; agility += increase; strength += increase; speed += increase; }} } [Tooltip("The villains abilities. They are vicious creatures capable of no remorse. Also this text is bloated to show wrapping.")] public Ability[] villains; [Tooltip("This is the hero!")] public Ability hero; [Tooltip("Another")] public Ability subhero; [Tooltip("Another")] public string something; [Tooltip("Another")] public int someint; [Tooltip("Another")] public float somefloat; [Tooltip("Another")] public Vector3 somevector; [System.Serializable] public class Nestor { [System.Serializable] public class Nested { [System.Serializable] public class InnerNest { public string hey; public Vector3 you; public Quaternion quat; } public InnerNest nestor; public Nested subnest; } public Nested nested; public Nested other; } [Tooltip("Another")] public Nestor nestor1; [Tooltip("Another")] public Nestor nestor2; public Nestor nestor3; [System.Serializable] public class Link { public string url; public Texture2D texture; } [HideInInspector] public Link[] link; void Update() { hero.agility++; } void OnGUI() { // This is just an ad running if you open the Pimp My Editor Example Scene if (link == null || link.Length < 4) return; GUILayout.BeginArea(new Rect(Screen.width/2-300,Screen.height/2-300, 600, 600)); { GUILayout.BeginVertical(); { GUILayout.FlexibleSpace(); GUILayout.BeginHorizontal(); { GUILayout.FlexibleSpace(); GuiLink(link[0]); GUILayout.Space(5); GuiLink(link[1]); GUILayout.FlexibleSpace(); } GUILayout.EndHorizontal(); GUILayout.Space(5); GUILayout.BeginHorizontal(); { GUILayout.FlexibleSpace(); GuiLink(link[2]); GUILayout.Space(5); GuiLink(link[3]); GUILayout.FlexibleSpace(); } GUILayout.EndHorizontal(); GUILayout.FlexibleSpace(); } GUILayout.EndVertical(); } GUILayout.EndArea(); } void GuiLink(Link link) { GUILayout.BeginVertical(GUI.skin.button); { GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); GUILayout.Label(link.texture); GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); GUILayout.Label(link.url); } GUILayout.EndVertical(); if(Event.current.type == EventType.MouseDown) { Rect r = GUILayoutUtility.GetLastRect(); if(r.Contains(Event.current.mousePosition)) { Application.OpenURL(link.url); } } } void ThisIsHereJustToRemoveAWarning() { if (privateSecret == null) privateSecret = "How did that happen?"; } }
using UnityEngine; using System.Collections; public class isoShakeCamera : MonoBehaviour { public float updownDecaytime_0 = 1.0f; public float leftrightDecaytime_0 = 1.0f; public float updownDecaytime = 0.0f; public float leftrightDecaytime = 0.0f; public Vector3 offset = new Vector3(0, 0, 0); public Vector3 position; public float startTime; public float amp = 0.15f; // 진폭 . 상하로 이동하는 정도. 값이 클수록 더 크게 진동 . //public float amp = 0.3f; // 진폭 . 상하로 이동하는 정도. 값이 클수록 더 크게 진동 . public float freq = 7f; // 진동수. 초당 상하 운동 횟수. 값이 클수록 더 빨 진동 . public float phase = 0f; // 위상 . 함수의 시작 포지ㅅㄴ.. 모르겠다 꾀꼬리 복붙은 위대해 public bool updown; public bool leftright; // Use this for initialization void Start () { //StartUpDownShake(10.0f); } //void OnGUI() //{ // if (GUI.Button(new Rect(100, 100, 100, 100), "")) // { // StartUpDownShake(updownDecaytime_0); // } // if (GUI.Button(new Rect(200, 100, 100, 100), "")) // { // StartLeftRightShake(leftrightDecaytime_0); // } // if (GUI.Button(new Rect(300, 100, 100, 100), "")) // { // StartUpDownShake(updownDecaytime_0); // StartLeftRightShake(leftrightDecaytime_0); // } //} public void StartUpDownShake( float decay ) { startTime = Time.time; updownDecaytime = decay + Time.fixedTime - startTime; position = this.gameObject.transform.localPosition; updown = true; } public void StartLeftRightShake( float decay ) { startTime = Time.time; leftrightDecaytime = decay + Time.fixedTime - startTime; position = this.gameObject.transform.localPosition; leftright = true; } // Update is called once per frame public void Update () { } public void FixedUpdate () { if(updown) UpDownShake(); if(leftright) LeftRightShake(); } public void SetOption(float _amp, float _freq) // 진폭, 진동수 { amp = _amp; freq = _freq; } public void UpDownShake() { float totaltime = Time.fixedTime - startTime; if( totaltime < updownDecaytime ) { Vector3 pos = this.gameObject.transform.localPosition; pos -= offset; offset.y = Mathf.Sin( 2 * 3.14159f * (totaltime * freq) + phase ) * amp * (updownDecaytime - totaltime) / updownDecaytime ; pos += offset; this.gameObject.transform.localPosition = pos; } else { updown = false; this.gameObject.transform.localPosition = position; offset = new Vector3(0,0,0); } } public void LeftRightShake() { float totaltime = Time.fixedTime - startTime; if( totaltime < leftrightDecaytime ) { Vector3 pos = this.gameObject.transform.localPosition; pos -= offset; offset.x = Mathf.Sin( 2 * 3.14159f * (totaltime * freq) + phase ) * amp * (leftrightDecaytime - totaltime) / leftrightDecaytime ; pos += offset; this.gameObject.transform.localPosition = pos; } else { offset = new Vector3(0,0,0); this.gameObject.transform.localPosition = position; leftright = false; } } }
using System; using Microsoft.Silverlight.Testing; using Microsoft.VisualStudio.TestTools.UnitTesting; using ExpressionSerialization; using System.Linq.Expressions; using System.Xml.Linq; using System.Diagnostics; using System.Collections.Generic; using Northwind; using System.Linq; using System.Reflection; using System.Dynamic; using System.Runtime.Serialization; using System.IO; namespace UnitTests { [TestClass] public class QueryableTests : BaseTests { public QueryableTests() :base() { } /// <summary> /// We want to be able to call the standard LINQ IQueryProvider /// on any arbitrary Expression. /// /// Create the IQueryProvider by calling Queryable.AsQueryable on /// a string collection to create a Linq.EnumerableQuery`1, /// then get its .Provider property. /// /// The call to IQueryProvider.Execute will fail if the input Expression /// does not match the return type. e.g. calling Execute without /// specifying IEnumerable`1 return type (generic arg) will fail. /// </summary> [TestMethod] [Tag("System.Linq.EnumerableQuery`1")] [Tag("IQueryable")] [Tag("IQueryProvider")] public void QueryProvider_Execute1() { IEnumerable<string> data = GetStrings(); IQueryable<string> query1 = data.AsQueryable<string>(); IQueryable<string> query2; IQueryProvider provider; provider = query1.Provider; query2 = provider.CreateQuery<string>(query1.Expression);//create IQueryable<string> query2.ToList();//force call to Execute try { provider.Execute(query1.Expression);//this will throw error } catch { provider.Execute<IEnumerable<string>>(query1.Expression);//the generic type arg is necessary. } } [TestMethod] [Tag("System.Linq.EnumerableQuery`1")] [Tag("IQueryable")] [Tag("IQueryProvider")] public void QueryProvider_Execute2() { object result; IQueryable<Customer> query1 = GetCustomers().AsQueryable(); IQueryable<Customer> query2 = query1.Where(c => c.ID > 0); IQueryProvider provider; provider = query1.Provider; //provider.Execute(query1.Expression); //does not work query2 = provider.CreateQuery<Customer>(query1.Expression); query2.ToList(); provider.Execute<IEnumerable<Customer>>(query1.Expression); //client has remote WCF IQueryProvider //server has actual data (e.g. RequestProcessor) IQueryProvider. //Query<Customer> query1 = new Query<Customer>(provider, query1.Expression); IQueryable<Customer> queryable = query1.Where(c => c.ID > 0); query1.Provider.Execute<IQueryable<Customer>>(query1.Expression); result = query1.Provider.Execute(query1.Expression);//fails because customers.Expression as a ConstantExpression yields IEnumerable<Customer> not EnumerableQuery<Customer> result = query1.Provider.Execute(query2.Expression); result = queryable.Provider.Execute(Expression.Constant((IEnumerable<Customer>)query1.AsEnumerable())); var list = query1.ToList(); } /// <summary> /// demonstrate how to use Query and how IQueryProvider.CreateQuery /// is called. /// </summary> [TestMethod] [Tag("Query")] [Tag("IQueryable")] [Tag("IQueryProvider")] public void IQueryProvider_CreateQuery1() { IQueryProvider clientprovider = null; //Expression is ConstantExpression: Query<Customer> clientquery = new Query<Customer>(clientprovider); Assert.IsTrue(clientquery is IQueryable); Assert.IsTrue(((IQueryable)clientquery).Expression is ConstantExpression); //This will NOT force call to IQueryProvider.CreateQuery clientquery.AsQueryable(); //This next statement WILL call IQueryProvider.CreateQuery. //Expression is MethodCallExpression: IQueryable<Customer> clientqueryable = from c in clientquery where c.ID > 0 select c; Assert.IsTrue(clientqueryable.Expression is MethodCallExpression); } /// <summary> /// Create a Query (of string) with another IQueryable's IQueryProvider. /// Then call IQueryProvider.Execute /// </summary> [TestMethod] [Tag("Query")] [Tag("IQueryProvider")] public void Query_Execute1() { IEnumerable<string> data = GetStrings(); IQueryable<string> queryable = data.AsQueryable<string>(); IQueryProvider provider = queryable.Provider;//IQueryProvider: Linq.EnumerableQuery`1 //create the Query IQueryable<string> query = new Query<string>(provider, queryable.Expression); //Execute the Query with (borrowed) queryable.Provider //IQueryProvider: Linq.EnumerableQuery`1 //Expression is a ConstantExpression IEnumerable<string> executedresults = query.Provider.Execute<IEnumerable<string>>(queryable.Expression); //Expression is MethodCallExpression. //Return type is IEnumerable`1 query = from s in query where s.StartsWith("H") || s.StartsWith("J") select s; executedresults = query.Provider.Execute<IEnumerable<string>>(query.Expression); //Create a MethodCallExpression for Queryable.Count //Return type is int IEnumerable<MethodInfo> methods = from m in typeof(Queryable).GetMethods() where m.Name == "Count" && m.IsGenericMethod select m; MethodInfo method = methods.First(); MethodInfo generic = method.MakeGenericMethod(typeof(string)); MethodCallExpression countCall = Expression.Call(null,//static generic, new Expression[] { Expression.Constant(query)}); //check that the MethodCallExprssion is valid. LambdaExpression lambda = Expression.Lambda(countCall, Expression.Parameter(typeof(IQueryable)));//I'm not even sure this is the correct parameter Type! int count = (int)lambda.Compile().DynamicInvoke(new object[] { query }); //call IQueryProvider.Execute: count = (int)query.Provider.Execute<int>(countCall); Assert.AreEqual(query.Count(), count); } /// <summary> /// Create a Query (of Customer) with another IQueryable's IQueryProvider. /// Then call IQueryProvider.Execute /// </summary> [TestMethod] [Tag("Query")] [Tag("IQueryProvider")] public void Query_Execute2() { IEnumerable<Customer> data = GetCustomers(); IQueryable<Customer> queryable = data.AsQueryable<Customer>(); IQueryProvider provider = queryable.Provider;//IQueryProvider: Linq.EnumerableQuery`1 IEnumerable<Customer> executedresults; //create the Query IQueryable<Customer> query = new Query<Customer>(provider, queryable.Expression); //Execute the Query with (borrowed) queryable.Provider //IQueryProvider: Linq.EnumerableQuery`1 //Expression is a ConstantExpression query.Provider.Execute<IEnumerable<Customer>>(queryable.Expression); //Execute on ConstantExpression of IEnumerable`1 //instead of Linq.EnumerableQuery`1. Works. provider.Execute<IEnumerable<Customer>>(Expression.Constant(GetCustomers())); //Expression is MethodCallExpression. //Return type is IEnumerable`1 query = from c in query where c.Name.StartsWith("H") || c.Name.StartsWith("J") select c; executedresults = query.Provider.Execute<IEnumerable<Customer>>(query.Expression); //re-create the Query, but this time with no Expression in constructor: query = new Query<Customer>(provider);//ConstantExpression has no data. //Expression is MethodCallExpression. //Arguments[0]: query: [System.Linq.Expressions.ConstantExpression]: {ExpressionSerialization.Query`1 //Arguments[1]: Unary (Quote) or LambdaExpression query = from c in query // call IQueryProvider.CreateQuery where c.Name != null //but query (ConstantExpression) has no data. select c; //Even though we'd think the IQueryProvider (Linq.EnumerableQuery`1) has data, //the MethodCallExpression will execute with ConstantExpression (query) //as Argument 0. But Argument 0 (the no-data Query) we just created will //be evaluated as a ConstantExpression with Value != IEnumerable`1. executedresults = query.Provider.Execute<IEnumerable<Customer>>(query.Expression); //So this will throw exception: //var list = executedresults.ToList(); //To make the Execute call work, we'd need to either //1: instantiate Query with a ConstantExpression equal to actual IEnumerable`1 //2: ExpressionVisitor.Visit the MethodCallExpression, and swap //Argument 0 with an actual data source (IEnumerable`1). query = new Query<Customer>(provider, Expression.Constant(GetCustomers())); provider.Execute<IEnumerable<Customer>>(query.Expression); } /// <summary> /// demonstrate how to use Query and how IQueryProvider.CreateQuery /// is called. /// </summary> [TestMethod] [Tag("Query")] [Tag("IQueryable")] [Tag("IQueryProvider")] public void IQueryProvider_CreateQuery2() { IEnumerable<Customer> data = GetCustomers(); IQueryable<Customer> queryable = data.AsQueryable<Customer>(); IQueryProvider EnumerableQueryProvider = queryable.Provider;//IQueryProvider: Linq.EnumerableQuery`1 IEnumerable<Customer> execute; IEnumerable<Customer> executeList; //This next statement WILL call IQueryProvider.CreateQuery. //Expression is MethodCallExpression: IQueryable<Customer> query = new Query<Customer>(default(IQueryProvider)); query = from c in query where c.ID != null select c; execute = EnumerableQueryProvider.Execute<IEnumerable<Customer>>(query.Expression); try { executeList = execute.ToList(); } catch { } //TryDeserialize: query = new Query<Customer>(EnumerableQueryProvider, Expression.Constant(queryable)); query = from c in query where c.ID != null select c; execute = EnumerableQueryProvider.Execute<IEnumerable<Customer>>(query.Expression); executeList = execute.ToList(); } [TestMethod()] [Tag("Query")] [Tag("QueryCreator")] [Tag("IQueryable")] [Tag("IQueryProvider")] public void CreateNewQuery_Execute() { QueryCreator creator = new QueryCreator(); Type elementType = typeof(Customer); Query<Customer> query = creator.CreateQuery(elementType); IQueryable<Customer> queryable; queryable = from c in query where c.ID == null //initialized with properties == null select c; IQueryProvider provider = ((IQueryable)query).Provider; //execute: var ienumerable = provider.Execute<IEnumerable<Customer>>(queryable.Expression); var list = ienumerable.ToList(); //new QueryCreator: creator = new QueryCreator(this.FnGetObjects); query = creator.CreateQuery(elementType); queryable = from c in query where c.ID == null //initialized with properties == null select c; provider.Execute<IEnumerable<Customer>>(queryable.Expression).ToList(); } [TestMethod] [Tag("System.Linq.EnumerableQuery`1")] [Tag("IQueryable")] [Tag("CustomExpressionXmlConverter")] [Tag("QueryCreator")] public void QueryExpressionXmlConverterTest() { Type elementType = typeof(Customer); var creator = new QueryCreator(this.FnGetObjects); var converter = new QueryExpressionXmlConverter(creator, this.resolver); bool success; XElement x; Expression e; MethodCallExpression m; ConstantExpression cx; IQueryProvider provider; //the client Query. IQueryProvider has not real data. Query<Customer> query = new Query<Customer>(default(IQueryProvider)); provider = ((IQueryable)query).Provider; IQueryable<Customer> queryable; queryable = from c in query where c.ID == null //initialized with properties == null select c; //serialize to XML e = Expression.Constant(queryable); success = converter.TrySerialize(e, out x); //deserialize to ConstantExpression(Query) success = converter.TryDeserialize(x, out e); cx = (ConstantExpression)e; Query<Customer> serverquery = (Query<Customer>)cx.Value; //upon deserialization, should have a new IQueryProvider Assert.AreNotEqual(provider, ((IQueryable)serverquery).Provider); provider = ((IQueryable)serverquery).Provider; //Execute Query on server side. int count = serverquery.Count(); } /// <summary> /// now, actually attempt to serialize IQueryable Expression /// /// </summary> [TestMethod] [Tag("System.Linq.EnumerableQuery`1")] [Tag("IQueryable")] [Tag("ExpressionSerializer")] public void EnumerableQueryExpressionSerialize() { XElement xml; Expression e; IEnumerable<Customer> customers = GetCustomers(); Query<Customer> query = new Query<Customer>(default(IQueryProvider)); IQueryable<Customer> queryable = from c in query where c.ID >= 0 select c; //serialize the Expression to WCF remote service: xml = serializer.Serialize(queryable.Expression); //deserialize the XML to Expression on WCF server side: e = serializer.Deserialize(xml); MethodCallExpression m = (MethodCallExpression)e; //now simply invoke the MethodCallExpression LambdaExpression lambda = Expression.Lambda(m); Delegate fn = lambda.Compile(); dynamic result = fn.DynamicInvoke(new object[0]); Assert.AreEqual("EnumerableQuery`1", result.GetType().Name); dynamic array = Enumerable.ToArray(result); Assert.IsTrue(array is Customer[]); } #region Resolved /// <summary> /// Initial test during run-in with issue with System.Linq.EnumerableQuery`1, /// typical during "Where" LINQ method calls. /// The original code (even in .NET 3.5) could not handle this scenario. /// /// This shows that the solution WAS to serialize the System.Linq.EnumerableQuery /// to IEnumerable`1. /// /// Now we use QueryExpressionXmlConverter to send Query Type of IQueryable /// across the wire. For plain System.Linq.EnumerableQuery`1 the user should /// just take responsiblity for using IEnumerable`1 instead. /// </summary> //[TestMethod] //[Tag("Type")] //[Tag("System.Linq.EnumerableQuery`1")] //[Tag("IQueryable")] //public void EnumerableQuery_Queryable_Test() //{ // //The following Type(s) not System.Linq.EnumerableQuery`1: // //Type iqueryableType = typeof(IQueryable<Customer>); // //Type existing = typeof(Customer); // //Type queryableGeneric = typeof(IQueryable<>).MakeGenericType(existing); // IEnumerable<Customer> customers = GetCustomers(); // IQueryable<Customer> queryable = customers.AsQueryable<Customer>(); // IQueryable<Customer> query = from c in queryable // where c.ID >= 0 // select c; // //Is the System.Linq.EnumerableQuery<Customer> a KnownType, or mapped to one in TypeResolver? // Type knownType; // bool canSerialize, hasKnownType; // Type enumerableQueryType = queryable.Expression.Type; // hasKnownType = this.resolver.HasMappedKnownType(enumerableQueryType, out knownType); // Assert.IsTrue(hasKnownType); // //Attempt to DataContractSerializer-serialize IQueryable... // canSerialize = this.CanSerialize(queryable, new Type[] { enumerableQueryType, knownType }); // Assert.AreEqual(false, canSerialize, "did not expect to serialize " + queryable.Expression.Type); // //Cast to what can serialize... // Assert.IsTrue(typeof(IQueryable).IsAssignableFrom(enumerableQueryType)); // if (typeof(IQueryable).IsAssignableFrom(enumerableQueryType)) // { // System.Collections.IEnumerable enumerable // = LinqHelper.CastToGenericEnumerable(queryable, knownType); // Assert.IsTrue(enumerable is IEnumerable<Customer>); // canSerialize = CanSerialize(enumerable);//IEnumerable<T> cannot serialize. // var list = ((IEnumerable<Customer>)enumerable).ToList(); // canSerialize = CanSerialize(list); // Assert.IsTrue(canSerialize); // dynamic array = enumerable; //I like Arrays better here. // array = Enumerable.ToArray(array); // Assert.IsTrue(CanSerialize(array)); // } // else // Assert.Fail("!typeof(IQueryable).IsAssignableFrom"); //} #endregion } }
using System.Threading.Tasks; using DFC.ServiceTaxonomy.Banners.Models; using DFC.ServiceTaxonomy.Banners.ViewModels; using Microsoft.Extensions.Localization; using OrchardCore.ContentManagement.Display.ContentDisplay; using OrchardCore.ContentManagement.Display.Models; using OrchardCore.ContentManagement.Metadata.Models; using OrchardCore.DisplayManagement.ModelBinding; using OrchardCore.DisplayManagement.Views; using OrchardCore.Mvc.ModelBinding; using YesSql; namespace DFC.ServiceTaxonomy.Banners.Drivers { public class BannerPartDisplayDriver : ContentPartDisplayDriver<BannerPart> { private readonly IStringLocalizer S; private readonly ISession _session; public BannerPartDisplayDriver(IStringLocalizer<BannerPartDisplayDriver> localizer, ISession session) { S = localizer; _session = session; } public override IDisplayResult Display(BannerPart part, BuildPartDisplayContext context) { return Initialize<BannerPartViewModel>(GetDisplayShapeType(context), model => BuildViewModel(model, part, context.TypePartDefinition)) .Location("Detail", "Content") .Location("Summary", "Content"); } public override IDisplayResult Edit(BannerPart part, BuildPartEditorContext context) { return Initialize<BannerPartViewModel>(GetEditorShapeType(context), model => BuildViewModel(model, part, context.TypePartDefinition)); } private void BuildViewModel(BannerPartViewModel model, BannerPart part, ContentTypePartDefinition typePartDefinition) { model.WebPageName = part.WebPageName; model.WebPageURL = part.WebPageURL; model.BannerPart = part; model.PartDefinition = typePartDefinition; } public override async Task<IDisplayResult> UpdateAsync(BannerPart part, IUpdateModel updater, UpdatePartEditorContext context) { var updated = await updater.TryUpdateModelAsync(part, Prefix, b => b.WebPageName, b => b.WebPageURL); if (updated) { await foreach (var item in part.ValidateAsync(S, _session)) { updater.ModelState.BindValidationResult(Prefix, item); } } return await EditAsync(part, context); } } }