text
stringlengths
13
6.01M
// // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. // #region Usings using System; using DotNetNuke.Collections.Internal; #endregion namespace DotNetNuke.ComponentModel { internal class ComponentTypeCollection : SharedDictionary<Type, ComponentType> { } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace e_Ticaret.viewModel { public class urunBilgisiModel { public string urun_Id { get; set; } public string urun_Marka_Id { get; set; } public string urun_Kategori_Id { get; set; } public string urun_Adi { get; set; } public int urun_Gelis_Fiyat { get; set; } public int urun_Satis_Fiyat { get; set; } public int urun_Stok { get; set; } public System.DateTime urun_Eklenme_Tarih { get; set; } public int urun_KDV { get; set; } public Nullable<int> urun_Satılan { get; set; } public string urun_Admin_Bilgi { get; set; } public string urun_Aciklama { get; set; } public string urun_Tanitim { get; set; } public string urun_Foto_Bilgisi { get; set; } public string urun_Foto1 { get; set; } public string urun_Foto_2 { get; set; } public string urun_foto_3 { get; set; } public markaBilgisiModel markabilgi{ get; set; } public kategoriBilgisiModel kategoribilgi { get; set; } public kategoriBilgisiModel sepetbilgi { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace _21st_Sep2018_1 { public class PersonData { internal string FName; internal string LName; internal int Age; internal int Num; internal string Gender; internal string Country; //internal string details; } }
using Newtonsoft.Json; namespace Points.Shared.Dtos { public class Geometry { [JsonProperty(PropertyName = "location")] public Location Location { get; set; } } }
using UnityEngine; using System.Collections; public class EnterOwnerRoom : MonoBehaviour { public GameObject brokenLightObject = null; BrokenLight lightScript; // Use this for initialization void Start () { lightScript = brokenLightObject.GetComponent<BrokenLight>(); } // Update is called once per frame void Update () { } void OnTriggerEnter(Collider other) { lightScript.flicker(true); } void OnTriggerExit(Collider other) { lightScript.flicker(false); } }
using System.Threading; using System.Threading.Tasks; using ChesterDevs.Core.Aspnet.App.Jobs; using ChesterDevs.Core.Aspnet.App.PageHelpers; using ChesterDevs.Core.Aspnet.Models.ViewModels; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; namespace ChesterDevs.Core.Aspnet.Controllers { public class JobsController: Controller { private readonly ILogger<JobsController> _logger; private readonly IJobListHelper _jobListHelper; private readonly IJobDetailHelper _jobDetailHelper; private readonly IJobSubscriptionHelper _jobSubscriptionHelper; private readonly IAskARecruiterHelper _askARecruiterHelper; public JobsController(ILogger<JobsController> logger, IJobListHelper jobListHelper, IJobDetailHelper jobDetailHelper, IJobSubscriptionHelper jobSubscriptionHelper, IAskARecruiterHelper askARecruiterHelper) { _logger = logger; _jobListHelper = jobListHelper; _jobDetailHelper = jobDetailHelper; _jobSubscriptionHelper = jobSubscriptionHelper; _askARecruiterHelper = askARecruiterHelper; } public async Task<IActionResult> Index(int? pageNumber, CancellationToken cancellationToken) { return View(await _jobListHelper.LoadViewModelAsync(pageNumber ?? 1, cancellationToken)); } public async Task<IActionResult> Details(int id, CancellationToken cancellationToken) { return View(await _jobDetailHelper.LoadViewModelAsync(id, cancellationToken)); } public IActionResult Subscribe() { return View(new SubscribeViewModel()); } [HttpPost] public async Task<IActionResult> Subscribe(SubscribeViewModel model, CancellationToken cancellationToken) { return View(await _jobSubscriptionHelper.Subscribe(model, cancellationToken)); } public IActionResult Advertise() { return View(); } [HttpGet] public IActionResult RecruiterPanel() { return View(new AskARecruiterViewModel(){ AskARecruiter = new AskARecruiter() }); } [HttpPost] public async Task<IActionResult> RecruiterPanel(AskARecruiterViewModel model, CancellationToken cancellationToken) { return View(await _askARecruiterHelper.SendAskARecruiter(model, cancellationToken)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using ExpVMsape.Models; namespace ExpVMsape.ViewModels { public class InformeTirajeVM { public InformeTiraje InformeTiraje { get; set; } public List<LineaTiraje> LineasTiraje { get; set; } } }
namespace Triton.Game.Data { using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using Triton.Game.Abstraction; using Triton.Game.Mapping; public class MulliganData { [CompilerGenerated] private List<Triton.Game.Abstraction.Card> list_0; [CompilerGenerated] private List<bool> list_1; [CompilerGenerated] private TAG_CLASS tag_CLASS_0; [CompilerGenerated] private TAG_CLASS tag_CLASS_1; internal MulliganData() { this.UserClass = GameState.Get().GetFriendlySidePlayer().GetHero().GetClass(); this.OpponentClass = GameState.Get().GetOpposingSidePlayer().GetHero().GetClass(); this.Cards = new List<Triton.Game.Abstraction.Card>(); this.Mulligans = new List<bool>(); foreach (Triton.Game.Mapping.Card card in MulliganManager.Get().m_startingCards) { this.Cards.Add(new Triton.Game.Abstraction.Card(card)); this.Mulligans.Add(false); } } public List<Triton.Game.Abstraction.Card> Cards { [CompilerGenerated] get { return this.list_0; } [CompilerGenerated] private set { this.list_0 = value; } } public List<bool> Mulligans { [CompilerGenerated] get { return this.list_1; } [CompilerGenerated] private set { this.list_1 = value; } } public TAG_CLASS OpponentClass { [CompilerGenerated] get { return this.tag_CLASS_1; } [CompilerGenerated] private set { this.tag_CLASS_1 = value; } } public TAG_CLASS UserClass { [CompilerGenerated] get { return this.tag_CLASS_0; } [CompilerGenerated] private set { this.tag_CLASS_0 = value; } } } }
using FacultyV3.Core.Interfaces; using FacultyV3.Core.Interfaces.IServices; using FacultyV3.Core.Models.Entities; using PagedList; using System; using System.Collections.Generic; using System.Linq; namespace FacultyV3.Core.Services { public class VideoService : IVideoService { private IDataContext context; public VideoService(IDataContext context) { this.context = context; } public IEnumerable<Video> PageList(string name, int page, int pageSize) { if (!string.IsNullOrEmpty(name)) { return context.Videos.Where(x => x.Title.Contains(name)).OrderByDescending(x => new { x.Serial, x.Update_At }).ToPagedList(page, pageSize); } return context.Videos.OrderByDescending(x => new { x.Serial, x.Update_At }).ToPagedList(page, pageSize); } public Video GetVideoByID(string id) { try { Guid ID = new Guid(id); return context.Videos.Find(ID); } catch (Exception) { } return null; } public List<Video> GetVideosOrderBySerial(int amount) { try { return context.Videos.OrderByDescending(x => x.Serial).Take(amount).Select(x => x).ToList(); } catch (Exception) { } return null; } } }
using UnityEngine; using System.Collections; public abstract class Command { abstract public void Execute(CharacterController character); abstract public void Undo(CharacterController character); }
using System; using System.Collections.Generic; namespace YZOpenSDK { public interface YZClient { string Invoke(string apiName, string version, string method, IDictionary<string, object> apiParams, List<KeyValuePair<string, string>> files); } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace Viking.AssemblyVersioning { public class TypeSignature : IEquatable<TypeSignature> { /// <summary> /// All attributes of a type that are not changeable when doing signature comparing. /// </summary> private static TypeAttributes NonChangeableAttributesMask { get; } = TypeAttributes.LayoutMask | TypeAttributes.CustomFormatMask | TypeAttributes.BeforeFieldInit | TypeAttributes.Class | TypeAttributes.HasSecurity | TypeAttributes.RTSpecialName | TypeAttributes.Import | TypeAttributes.Interface | TypeAttributes.NestedPublic | TypeAttributes.Public | TypeAttributes.Serializable | TypeAttributes.SpecialName; /// <summary> /// All attributes of a type that are relaxable (meaning we can remove the properties but not add them) when doing signature comparing. /// </summary> private static TypeAttributes RelaxableAttributesMask { get; } = TypeAttributes.Abstract | TypeAttributes.Sealed | TypeAttributes.NotPublic | TypeAttributes.NestedAssembly | TypeAttributes.NestedFamily; public TypeSignature(Type t) { Type = t; if (t.IsGenericTypeDefinition) GenericSignature = new GenericSignature(t.GetGenericArguments()); } private Type Type { get; } private GenericSignature GenericSignature { get; } public bool IsGeneric => GenericSignature != null; public TypeAttributes Attributes => Type.Attributes; public string GivenName => Type.Name; public string FullName => Type.FullName; public bool IsInterface => Type.IsInterface; public bool IsSealed => Type.IsSealed; public bool IsAbstract => Type.IsAbstract; public bool Equals(TypeSignature signature) { return FullName.Equals(signature.FullName, StringComparison.Ordinal) && Attributes.Equals(signature.Attributes) && GenericSignature == signature.GenericSignature; } public bool CanBeRelaxedTo(TypeSignature signature) { return FullName.Equals(signature.FullName, StringComparison.Ordinal) && TypeAttributesAllowRelaxationTo(signature.Attributes) && GenericSignature == signature.GenericSignature; } public bool TypeAttributesAllowRelaxationTo(TypeAttributes attr) => (Attributes & NonChangeableAttributesMask) == (attr & NonChangeableAttributesMask) && (Attributes & RelaxableAttributesMask).HasFlag(attr & RelaxableAttributesMask); public static bool TypesHaveSameSignatures(Type a, Type b) => new TypeSignature(a).Equals(new TypeSignature(b)); public static bool FirstSignatureCanBeRelaxedToSecondSignature(Type a, Type b) => new TypeSignature(a).CanBeRelaxedTo(new TypeSignature(b)); } }
namespace MonoGame.Extended.Content.Pipeline { public class ContentImporterResult<T> { public ContentImporterResult(string filePath, T data) { FilePath = filePath; Data = data; } public string FilePath { get; private set; } public T Data { get; private set; } } }
using BPiaoBao.DomesticTicket.Domain.Models.Orders.States; using BPiaoBao.DomesticTicket.Platform.Plugin; using System; using BPiaoBao.DomesticTicket.Domain.Services; using System.Collections.Generic; using System.Linq; using System.Text; using BPiaoBao.Common.Enums; using StructureMap; using BPiaoBao.SystemSetting.Domain.Models.Businessmen; using BPiaoBao.DomesticTicket.Domain.Models.Deduction; using JoveZhao.Framework.Expand; using System.Diagnostics; using BPiaoBao.AppServices.DataContracts.DomesticTicket; using JoveZhao.Framework; using BPiaoBao.Common; using PnrAnalysis; using BPiaoBao.DomesticTicket.Domain.Models.Policies; using System.Threading; using BPiaoBao.DomesticTicket.Domain.Models.PlatformPoint; namespace BPiaoBao.DomesticTicket.Domain.Models.Orders.Behaviors { /// <summary> /// 选择政策操作 /// </summary> [Behavior("NewSelectPolicy")] public class NewSelectPolicyBehavior : BaseOrderBehavior { string OldOutOrderId = string.Empty; public override object Execute() { //记录时间 StringBuilder sbLog = new StringBuilder(); Stopwatch watch = new Stopwatch(); try { watch.Start(); string platformCode = getParame("platformCode").ToString(); string policyId = getParame("policyId").ToString(); string operatorName = getParame("operatorName").ToString(); string source = getParame("source").ToString(); PolicyDto policyUI = source != "back" ? (getParame("policy") as PolicyDto) : null; decimal TotlePaidPirce = 0m; OldOutOrderId = order.OutOrderId; string innerPlatformCode = "系统"; DataBill databill = new DataBill(); DomesticService domesticService = ObjectFactory.GetInstance<DomesticService>(); UserRelation userRealtion = domesticService.GetUserRealtion(order.BusinessmanCode); bool IspolicyIsNull = false; if (policyUI != null) { //赋值 order.Policy = PolicyDtoPolicy(policyUI, order.Policy, source); } else { #region 原获取政策 PolicyParam policyParam = new PolicyParam(); policyParam.code = order.BusinessmanCode; policyParam.PnrContent = order.PnrContent; policyParam.OrderId = order.OrderId; policyParam.OrderType = order.OrderType; policyParam.OrderSource = order.OrderSource; policyParam.IsChangePnrTicket = order.IsChangePnrTicket; policyParam.IsDestine = order.OrderSource == EnumOrderSource.WhiteScreenDestine ? true : false; Passenger pasData = order.Passengers.Where(p => p.PassengerType != EnumPassengerType.Baby).FirstOrDefault(); if (pasData != null) { policyParam.defFare = pasData.SeatPrice.ToString(); policyParam.defTAX = pasData.ABFee.ToString(); policyParam.defRQFare = pasData.RQFee.ToString(); } if (order.Policy == null) { IspolicyIsNull = true; order.Policy = new Policy(); } Policy localPolicy = null; PlatformPolicy policy = null; PlatformOrder platformOrder = null; PolicyService policyService = ObjectFactory.GetInstance<PolicyService>(); watch.Stop(); sbLog.AppendFormat("初始话变量时间:{0}\r\n", watch.Elapsed.ToString()); watch.Restart(); if (platformCode != innerPlatformCode) { PnrData pnrData = PnrHelper.GetPnrData(order.PnrContent); policy = PlatformFactory.GetPlatformByCode(platformCode).GetPoliciesByPnrContent(order.PnrContent, order.IsLowPrice, pnrData).Find((p) => p.Id == policyId); watch.Stop(); sbLog.AppendFormat("0.调用方法【GetPlatformByCode】用时:{0}\r\n", watch.Elapsed.ToString()); watch.Restart(); if (policy == null) { localPolicy = GetLocalPolicy(policyParam, policyId, innerPlatformCode, userRealtion, IspolicyIsNull, policyService, localPolicy); watch.Stop(); sbLog.AppendFormat("1.调用方法【GetLocalPolicy】用时:{0}\r\n", watch.Elapsed.ToString()); watch.Restart(); if (localPolicy != null) { order.Policy = localPolicy; } else { throw new OrderCommException("政策发生变动,请重新获取政策!!!"); } } else { SetInterface(platformCode, operatorName, source, ref TotlePaidPirce, policy, userRealtion, ref platformOrder, pnrData); watch.Stop(); sbLog.AppendFormat("2.调用方法【SetInterface】用时:{0}\r\n", watch.Elapsed.ToString()); watch.Restart(); } } else { localPolicy = GetLocalPolicy(policyParam, policyId, innerPlatformCode, userRealtion, IspolicyIsNull, policyService, localPolicy); watch.Stop(); sbLog.AppendFormat("3.调用方法【GetLocalPolicy】用时:{0}\r\n", watch.Elapsed.ToString()); watch.Restart(); if (localPolicy == null) { PnrData pnrData = PnrHelper.GetPnrData(order.PnrContent); localPolicy = policyService.GetInterfacePolicy(policyParam, "", userRealtion, pnrData).Find((p) => p.PolicyId == policyId); watch.Stop(); sbLog.AppendFormat("4.调用方法【GetInterfacePolicy】用时:{0}\r\n", watch.Elapsed.ToString()); watch.Restart(); if (localPolicy != null) { policy.AreaCity = localPolicy.AreaCity; policy.Id = localPolicy.PolicyId; policy.PolicyPoint = localPolicy.PolicyPoint; if (source != "back") { policy.PolicyPoint = localPolicy.PaidPoint; } policy.ReturnMoney = localPolicy.ReturnMoney; policy.IsLow = localPolicy.IsLow; policy.SeatPrice = localPolicy.SeatPrice; policy.ABFee = localPolicy.ABFee; policy.RQFee = localPolicy.RQFee; policy.Remark = localPolicy.Remark; policy.IsChangePNRCP = localPolicy.IsChangePNRCP; policy.IsSp = localPolicy.IsSp; policy.PolicyType = localPolicy.PolicyType; policy.WorkTime = localPolicy.WorkTime; policy.ReturnTicketTime = localPolicy.ReturnTicketTime; policy.AnnulTicketTime = localPolicy.AnnulTicketTime; policy.CPOffice = localPolicy.CPOffice; policy.IssueSpeed = localPolicy.IssueSpeed; TotlePaidPirce = platformOrder.TotlePaidPirce; SetInterface(platformCode, operatorName, source, ref TotlePaidPirce, policy, userRealtion, ref platformOrder, pnrData); watch.Stop(); sbLog.AppendFormat("5.调用方法【GetInterfacePolicy】用时:{0}\r\n", watch.Elapsed.ToString()); watch.Restart(); } else { if (localPolicy == null) throw new OrderCommException("政策发生变动,请重新获取政策!"); } } else { //赋值 order.Policy = localPolicy; } } #endregion } decimal _OrderMoney = 0m; if (source != "back") { //扣点组类型 DeductionType deductionType = order.Policy.PolicySourceType == EnumPolicySourceType.Local ? DeductionType.Local : (order.Policy.PolicySourceType == EnumPolicySourceType.Share ? DeductionType.Share : DeductionType.Interface); if (policyUI != null) { order.Policy.PolicyPoint = order.Policy.PaidPoint; } PlatformDeductionParam pfDp = new PlatformDeductionParam(); foreach (SkyWay leg in order.SkyWays) { pfDp.FlyLineList.Add(new FlyLine() { CarrayCode = leg.CarrayCode, FromCityCode = leg.FromCityCode, ToCityCode = leg.ToCityCode }); } //匹配扣点规则 domesticService.MatchDeductionRole(order.Policy, pfDp, order.SkyWays[0].CarrayCode, userRealtion.deductionGroup, userRealtion, deductionType); watch.Stop(); sbLog.AppendFormat("6.调用方法【MatchDeductionRole】用时:{0}\r\n", watch.Elapsed.ToString()); watch.Restart(); //佣金 order.Policy.Commission = databill.GetCommission(order.Policy.PolicyPoint, order.Policy.SeatPrice, order.Policy.ReturnMoney); //单人支付金额 根据选择的政策 设置价格 for (int i = 0; i < order.Passengers.Count; i++) { Passenger p = order.Passengers[i]; if (p.PassengerType != EnumPassengerType.Baby) { p.SeatPrice = order.Policy.SeatPrice; p.ABFee = order.Policy.ABFee; p.RQFee = order.Policy.RQFee; p.PayMoney = databill.GetPayPrice(order.Policy.SeatPrice, order.Policy.ABFee, order.Policy.RQFee, order.Policy.PolicyPoint, order.Policy.ReturnMoney); } else { p.PayMoney = databill.GetPayPrice(p.SeatPrice, p.ABFee, p.RQFee, 0, 0); } } _OrderMoney = order.Passengers.Sum(p => p.PayMoney); order.OrderCommissionTotalMoney = order.Passengers.Sum(p => p.PassengerType != EnumPassengerType.Baby ? databill.GetCommission(order.Policy.PolicyPoint, order.Policy.SeatPrice, order.Policy.ReturnMoney) : 0); } #region 支付信息 if (order.OrderPay == null) order.OrderPay = new OrderPay(); order.OrderPay.OrderId = order.OrderId; order.OrderPay.PaidMoney = TotlePaidPirce; if (source != "back") { order.OrderPay.PayMoney = _OrderMoney; order.OrderMoney = _OrderMoney; order.OrderPay.PayStatus = EnumPayStatus.NoPay; } order.OrderPay.PaidStatus = EnumPaidStatus.NoPaid; order.OrderPay.TradePoundage = 0m; order.OrderPay.SystemFee = 0m; order.CpOffice = order.Policy.CPOffice; #endregion #region 根据政策扣点明细计算支付分润 if (source != "back") { domesticService.CreateBillDetails(order, userRealtion); watch.Stop(); sbLog.AppendFormat("7.调用方法【CreateBillDetails】用时:{0}\r\n", watch.Elapsed.ToString()); } #endregion order.WriteLog(new OrderLog() { OperationContent = string.Format("{0}选择政策,政策:{1},编号:{2},订单号:{3},出票速度:{4}", source, order.Policy.PolicyPoint, order.Policy.PolicyId, order.OrderId, order.Policy.IssueSpeed), OperationDatetime = DateTime.Now, OperationPerson = operatorName, IsShowLog = false }); order.WriteLog(new OrderLog() { OperationContent = string.Format("选择政策,订单号:{0},出票速度:{1}", order.OrderId, order.Policy.IssueSpeed), OperationDatetime = DateTime.Now, OperationPerson = operatorName, IsShowLog = true }); if (source == "back") { //order.ChangeStatus(EnumOrderStatus.WaitAndPaid); order.ChangeStatus(EnumOrderStatus.PayWaitCreatePlatformOrder); } else { order.ChangeStatus(EnumOrderStatus.NewOrder); } } finally { if (sbLog.ToString() != "") { new CommLog().WriteLog("NewSelectPolicyBehavior", sbLog.ToString()); } } if (order.Policy.PolicySourceType == EnumPolicySourceType.Interface) { order.Policy.Code = string.Empty; order.Policy.Name = string.Empty; order.Policy.CashbagCode = string.Empty; } return null; } private void SetInterface(string platformCode, string operatorName, string source, ref decimal TotlePaidPirce, PlatformPolicy policy, UserRelation userRealtion, ref PlatformOrder platformOrder, PnrData pnrData) { #region 接口政策信息 order.Policy.AreaCity = policy.AreaCity; order.Policy.PolicyId = policy.Id; order.Policy.PlatformCode = platformCode; order.Policy.OriginalPolicyPoint = policy.PolicyPoint; order.Policy.DownPoint = 0m; order.Policy.PaidPoint = policy.PolicyPoint; if (source != "back") { order.Policy.PolicyPoint = order.Policy.PaidPoint; } order.Policy.ReturnMoney = policy.ReturnMoney; order.Policy.IsLow = policy.IsLow; order.Policy.SeatPrice = policy.SeatPrice; order.Policy.ABFee = policy.ABFee; order.Policy.RQFee = policy.RQFee; order.Policy.Remark = policy.Remark; order.Policy.IsChangePNRCP = policy.IsChangePNRCP; order.Policy.IsSp = policy.IsSp; order.Policy.PolicyType = policy.PolicyType; order.Policy.WorkTime = policy.WorkTime; order.Policy.ReturnTicketTime = policy.ReturnTicketTime; order.Policy.AnnulTicketTime = policy.AnnulTicketTime; order.Policy.CPOffice = policy.CPOffice; order.Policy.OrderId = order.OrderId; order.Policy.PolicySourceType = EnumPolicySourceType.Interface; order.Policy.CarryCode = order.SkyWays[0].CarrayCode; order.Policy.IssueSpeed = policy.IssueSpeed; order.Policy.TodayGYCode = policy.TodayGYCode; #endregion } private Policy GetLocalPolicy(PolicyParam policyParam, string policyId, string innerPlatformCode, UserRelation userRealtion, bool IspolicyIsNull, PolicyService policyService, Policy localPolicy) { PnrData pnrData = PnrHelper.GetPnrData(order.PnrContent); if (IspolicyIsNull) { //全部查询匹配一下 localPolicy = policyService.GetLocalPolicy(userRealtion, innerPlatformCode, policyParam, pnrData).Find((p) => p.PolicyId == policyId); if (localPolicy == null) { localPolicy = policyService.GetSharePolicy(userRealtion, innerPlatformCode, policyParam, pnrData).Find((p) => p.PolicyId == policyId); } if (localPolicy == null && policyId.StartsWith(userRealtion.carrier.Code + "_")) { //本地 默认 localPolicy = policyService.GetDefaultPolicy(userRealtion, innerPlatformCode, policyParam, pnrData, policyId).FirstOrDefault(); } } else { //非接口重新获取政策 //本地 localPolicy = policyService.GetLocalPolicy(userRealtion, innerPlatformCode, policyParam, pnrData).Find((p) => p.PolicyId == policyId); if (localPolicy == null) { //共享 异地 localPolicy = policyService.GetSharePolicy(userRealtion, innerPlatformCode, policyParam, pnrData).Find((p) => p.PolicyId == policyId); } if (localPolicy == null) { if (policyId.StartsWith(userRealtion.carrier.Code + "_")) { //本地 默认 localPolicy = policyService.GetDefaultPolicy(userRealtion, innerPlatformCode, policyParam, pnrData, policyId).FirstOrDefault(); } } } return localPolicy; } private Policy PolicyDtoPolicy(PolicyDto policyDto, Policy policy, string source) { Policy rePolicy = null; if (policy == null) { rePolicy = new Policy(); rePolicy.PaidPoint = policyDto.PaidPoint; rePolicy.OriginalPolicyPoint = policyDto.OriginalPolicyPoint; } else { rePolicy = policy; if (source != "back") { rePolicy.PaidPoint = policyDto.PaidPoint; rePolicy.OriginalPolicyPoint = policyDto.OriginalPolicyPoint; } } rePolicy.PolicyId = policyDto.Id; rePolicy.Commission = policyDto.Commission; rePolicy.AreaCity = policyDto.AreaCity; rePolicy.PlatformCode = policyDto.PlatformCode; rePolicy.PolicyPoint = policyDto.Point; rePolicy.DownPoint = policyDto.DownPoint; rePolicy.IsChangePNRCP = policyDto.IsChangePNRCP; rePolicy.EnumIssueTicketWay = (EnumIssueTicketWay)Enum.Parse(typeof(EnumIssueTicketWay), policyDto.IssueTicketWay); rePolicy.IsSp = policyDto.IsSp; rePolicy.PolicyType = policyDto.PolicyType; string[] strTime = policyDto.WorkTime.Split('-'); if (strTime != null && strTime.Length == 2) { rePolicy.WorkTime = new StartAndEndTime() { StartTime = strTime[0], EndTime = strTime[1] }; } strTime = policyDto.AnnulTicketTime.Split('-'); if (strTime != null && strTime.Length == 2) { rePolicy.AnnulTicketTime = new StartAndEndTime() { StartTime = strTime[0], EndTime = strTime[1] }; } strTime = policyDto.ReturnTicketTime.Split('-'); if (strTime != null && strTime.Length == 2) { rePolicy.ReturnTicketTime = new StartAndEndTime() { StartTime = strTime[0], EndTime = strTime[1] }; } rePolicy.CPOffice = policyDto.CPOffice; rePolicy.IssueSpeed = policyDto.IssueSpeed; rePolicy.Remark = policyDto.Remark; rePolicy.PolicySourceType = policyDto.PolicySourceType == "本地" ? EnumPolicySourceType.Local : policyDto.PolicySourceType == "接口" ? EnumPolicySourceType.Interface : EnumPolicySourceType.Share; //(EnumPolicySourceType)Enum.Parse(typeof(EnumPolicySourceType), policyDto.PolicySourceType); rePolicy.CarryCode = policyDto.CarryCode; rePolicy.CarrierCode = policyDto.CarrierCode; rePolicy.PolicyOwnUserRole = (EnumPolicyOwnUserRole)Enum.Parse(typeof(EnumPolicyOwnUserRole), policyDto.PolicyOwnUserRole); rePolicy.Code = policyDto.Code; rePolicy.Name = policyDto.Name; rePolicy.CashbagCode = policyDto.CashbagCode; rePolicy.Rate = policyDto.Rate; rePolicy.IsLow = policyDto.IsLow; rePolicy.SeatPrice = policyDto.SeatPrice; rePolicy.ABFee = policyDto.ABFee; rePolicy.RQFee = policyDto.RQFee; rePolicy.PolicySpecialType = policyDto.PolicySpecialType; rePolicy.SpecialPriceOrDiscount = policyDto.SpecialPriceOrDiscount; rePolicy.TodayGYCode = policyDto.TodayGYCode; return rePolicy; } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.Linq; using Microsoft.AspNetCore.Mvc; namespace BigViews { public class HomeController : Controller { private static Dictionary<string, User> _users = new Dictionary<string, User>(); static HomeController() { // Create a few unique users. var jobIndex = 0; var pastJobCount = 0; for (var i = 0; i < 10; i++) { var user = new User { CurrentJob = BigViews.User.AvailableJobs[jobIndex], FirstName = $"Joey { i }", LastName = "Brown", HomePhone = $"425-555-{ i }{ i }{ i }{ i }", Mobile = $"206-555-{ i }{ i }{ i }{ i }", MailId = $"Joey{ i }@contoso.com", }; jobIndex = (jobIndex + 1) % BigViews.User.AvailableJobs.Count; for (var j = 0; j < pastJobCount; j++) { user.PastJobs.Add(BigViews.User.AvailableJobs[jobIndex]); jobIndex = (jobIndex + 1) % BigViews.User.AvailableJobs.Count; } pastJobCount = (pastJobCount + 1) % 3; _users.Add(user.MailId, user); } } public IActionResult Index() { // In a more realistic scenario, may have many more users. But would likely display details of only 10 or // so at once. return View(_users.Values.ToArray()); } public IActionResult IndexWithStaticOptions() { // In a more realistic scenario, may have many more users. But would likely display details of only 10 or // so at once. return View(_users.Values.ToArray()); } public IActionResult IndexWithTagHelpers() { // In a more realistic scenario, may have many more users. But would likely display details of only 10 or // so at once. return View(_users.Values.ToArray()); } public IActionResult Edit(string id) { User user; _users.TryGetValue(id, out user); return new ContentResult { Content = user?.FirstName, }; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Jieshai { [Serializable] public class DateTimeRange { public DateTimeRange() { } public DateTimeRange(DateTime? start, DateTime? end) { this.Start = start; this.End = end; } public DateTime? Start { set; get; } public DateTime? End { set; get; } public bool InRange(DateTime? date) { if (!date.HasValue) { return false; } if (this.End.HasValue && this.Start.HasValue) { if (date.Value < Start.Value || date.Value > this.End.Value) { return false; } } else if (this.End.HasValue) { if (date.Value > this.End.Value) { return false; } } else if (this.Start.HasValue) { if (date.Value < Start.Value) { return false; } } return true; } public bool InRange(DateTimeRange range) { if (this.InRange(range.Start)) { return true; } if (this.InRange(range.End)) { return true; } return false; } public override string ToString() { if (this.Start.HasValue && this.End.HasValue) { return string.Format("{0}到{1}", this.Start.Value.ToString("yyyy-MM-dd HH:mm"), this.End.Value.ToString("yyyy-MM-dd HH:mm")); } else if (this.Start.HasValue) { return string.Format("{0}以后", this.Start.Value.ToString("yyyy-MM-dd HH:mm")); } else if (this.End.HasValue) { return string.Format("{0}以前", this.End.Value.ToString("yyyy-MM-dd HH:mm")); } return ""; } } }
using System; using System.Linq; using System.Threading.Tasks; using System.Collections.Generic; using System.Collections.Concurrent; using System.Net.Http; using Grpc.Core; using Newtonsoft.Json.Linq; using Google.Protobuf.WellKnownTypes; using System.IO; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using System.Data; namespace Etg.Data.Entry { public class EntryDataServiceImpl : EntryDataService.EntryDataServiceBase { private HttpClient httpClient; private string servicePath; private string zipPath; private string DbConn; private readonly ILogger<EntryDataServiceImpl> logger; public EntryDataServiceImpl(IOptions<EntryDataServiceOptions> optionsAccessor, ILoggerFactory loggerFactory) { //var serviceUrl = new Uri(optionsAccessor.Value.PopServiceUrl); //httpClient = new HttpClient() { BaseAddress = new Uri(serviceUrl.GetComponents(UriComponents.SchemeAndServer, UriFormat.UriEscaped)) }; //servicePath = serviceUrl.LocalPath; DbConn = optionsAccessor.Value.DbConn; zipPath = optionsAccessor.Value.DataFilePath; this.logger = loggerFactory.CreateLogger<EntryDataServiceImpl>(); } public class QueryReply { public string StatusText; public Timestamp DeclareDate; } public override async Task GetYDTEntryDataFrom(GetYDTEntryDataRequest request, IServerStreamWriter<GetYDTEntryDataResponse> responseStream, ServerCallContext context) { //获取请求 logger.LogDebug($"Peer:{context.Peer},DataFrom:{request.DateFrom}"); var time = request.DateFrom.ToDateTime().ToLocalTime(); string beginFile = time.ToString("yyyyMMddHH") + ".zip"; foreach (string file in Directory.GetFiles(zipPath)) { if (file.CompareTo(zipPath + beginFile) >= 0) { //读取文件 var fileBytes = File.ReadAllBytes(file); //返回结果 GetYDTEntryDataResponse ret = new GetYDTEntryDataResponse() { FileName = new FileInfo(file).Name }; logger.LogDebug($"GeneralFile:{ret.FileName}"); if (fileBytes != null) { ret.Data = Google.Protobuf.ByteString.CopyFrom(fileBytes); } await responseStream.WriteAsync(ret); } } logger.LogDebug($"responseStream:{responseStream}"); } public override async Task<GetYDTEntryDataResponse> GetYDTEntryDataAt(GetYDTEntryDataRequest request, ServerCallContext context) { logger.LogDebug($"Peer:{context.Peer},DataFrom:{request.DateFrom}"); var time = request.DateFrom.ToDateTime().ToLocalTime(); string filePath = Directory.GetFiles(zipPath) .Where(file => string.Compare(new FileInfo(file).Name, time.ToString("yyyyMMddHH")) < 0) .OrderBy(file => new FileInfo(file).Name).Last(); Task<byte[]> t = new Task<byte[]>(() => { return File.ReadAllBytes(filePath); }); t.Start(); byte[] fileBytes = await t; GetYDTEntryDataResponse response = new GetYDTEntryDataResponse(); if (fileBytes != null) { response.FileName = new FileInfo(filePath).Name; response.Data = Google.Protobuf.ByteString.CopyFrom(fileBytes); } logger.LogDebug($"GeneralFile:{response.FileName}"); return response; } public override async Task GetEntryStatus(IAsyncStreamReader<GetEntryStatusRequest> requestStream, IServerStreamWriter<GetEntryStatusResponse> responseStream, ServerCallContext context) { while (await requestStream.MoveNext()) { var request = requestStream.Current; var status = await QueryEntryStatus(request.EntryId); GetEntryStatusResponse ret = new GetEntryStatusResponse() { EntryId = request.EntryId }; if (status != null) { ret.StatusText = status.StatusText; ret.DeclareDate = status.DeclareDate; } await responseStream.WriteAsync(ret); } } private async Task<QueryReply> QueryEntryStatus(string entryId) { try { //var res = await httpClient.GetStringAsync($"{servicePath}/{entryId}"); //var resObj = JObject.Parse(res); //if (resObj.Value<int>("code") == 200) //{ // if (resObj["data"][entryId] != null) // { // return new QueryReply() // { // StatusText = resObj["data"][entryId].Value<string>("status"), // DeclareDate = Timestamp.FromDateTime(resObj["data"][entryId].Value<DateTime>("declare_date")) // }; // } //} string strStatus = ""; string strdDate = ""; await Task.Run(() => { GetStatusFromDb(entryId, out strStatus, out strdDate); }); var a= new QueryReply() { StatusText = strStatus, DeclareDate = Timestamp.FromDateTime(DateTime.Parse(strdDate).ToUniversalTime()) }; return a; } catch (AggregateException ex) { System.Console.WriteLine(ex.Message); } return null; } #region 访问数据库 /// <summary> /// 从数据库中获报关单状态 /// </summary> /// <param name="entryId">报关单ID</param> /// <returns></returns> private void GetStatusFromDb(string entryId, out string status, out string dDate) { status = ""; dDate = ""; if (entryId.Length != 18) { return; } string SQL = string.Format("SELECt top 1 CHANNEL,D_DATE FROM [ENT_RET_2012].[dbo].[ENTRY_RETURN] where ENTRY_ID='{0}' order by f_name desc", entryId); SQLHelper.strConnect = DbConn; DataTable dt = SQLHelper.FillDataTable(SQL); if (dt != null && dt.Rows.Count > 0) { status = dt.Rows[0]["CHANNEL"].ToString(); dDate = dt.Rows[0]["D_DATE"].ToString(); } } #endregion } }
using irc_client.connection.handlers; namespace irc_client.connection { /// <summary> /// Singleton. /// Contains input and output queue of requests. /// </summary> public class RequestRepository { #region fields private static RequestRepository instance; private RequestQueue inputRequests; private RequestQueue outputRequests; #endregion #region constructors /// <summary> /// Creates new repository with empty queues. /// </summary> private RequestRepository() { inputRequests = new RequestQueue(); outputRequests = new RequestQueue(); } #endregion #region properies public RequestQueue InputRequests => inputRequests; public RequestQueue OutputRequests => outputRequests; public IQueueHandler InputHandler { get; set; } public IQueueHandler OutputHandler { get; set; } public static RequestRepository Instance { get { if (instance == null) { instance = new RequestRepository(); } return instance; } } #endregion } }
using AutoMapper; using AutoMapper.Extensions.ExpressionMapping; using Contoso.AutoMapperProfiles; using Contoso.BSL.AutoMapperProfiles; using Contoso.Common.Utils; using Contoso.Contexts; using Contoso.Data.Entities; using Contoso.Domain.Entities; using Contoso.Parameters.Expressions; using Contoso.Repositories; using Contoso.Stores; using LogicBuilder.Expressions.Utils.Strutures; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using Xunit; namespace Contoso.Bsl.Flow.Integration.Tests { public class QueryOperationsTest { public QueryOperationsTest() { Initialize(); } #region Fields private IServiceProvider serviceProvider; private static readonly string parameterName = "$it"; #endregion Fields #region Tests [Fact] public void SelectNewCourseAssignment() { var bodyParameter = new SelectOperatorParameters ( new OrderByOperatorParameters ( new ParameterOperatorParameters("q"), new MemberSelectorOperatorParameters ( "Title", new ParameterOperatorParameters("s") ), ListSortDirection.Ascending, "s" ), new MemberInitOperatorParameters ( new List<MemberBindingItem> { new MemberBindingItem("CourseID", new MemberSelectorOperatorParameters("CourseID", new ParameterOperatorParameters("a"))), new MemberBindingItem("CourseTitle", new MemberSelectorOperatorParameters("Title", new ParameterOperatorParameters("a"))), new MemberBindingItem ( "CourseNumberAndTitle", new ConcatOperatorParameters ( new ConcatOperatorParameters ( new ConvertToStringOperatorParameters ( new MemberSelectorOperatorParameters("CourseID", new ParameterOperatorParameters("a")) ), new ConstantOperatorParameters(" ", typeof(string)) ), new MemberSelectorOperatorParameters("Title", new ParameterOperatorParameters("a")) ) ) }, typeof(CourseAssignmentModel) ), "a" ); //act DoTest<CourseModel, Course, IQueryable<CourseAssignmentModel>, IQueryable<CourseAssignment>> ( bodyParameter, "q", returnValue => { Assert.Equal("Calculus", returnValue.First().CourseTitle); }, "q => q.OrderBy(s => s.Title).Select(a => new CourseAssignmentModel() {CourseID = a.CourseID, CourseTitle = a.Title, CourseNumberAndTitle = a.CourseID.ToString().Concat(\" \").Concat(a.Title)})" ); } [Fact] public void SelectInstructorFullNames() { var bodyParameter = new SelectOperatorParameters ( new OrderByOperatorParameters ( new ParameterOperatorParameters("q"), new MemberSelectorOperatorParameters ( "FullName", new ParameterOperatorParameters("s") ), ListSortDirection.Ascending, "s" ), new MemberSelectorOperatorParameters("FullName", new ParameterOperatorParameters("a")), "a" ); //act DoTest<InstructorModel, Instructor, IQueryable<string>, IQueryable<string>> ( bodyParameter, "q", returnValue => Assert.Equal("Candace Kapoor", returnValue.First()), "q => q.OrderBy(s => s.FullName).Select(a => a.FullName)" ); } [Fact] public void SelectNewInstructor() { var bodyParameter = new SelectOperatorParameters ( new OrderByOperatorParameters ( new ParameterOperatorParameters("q"), new MemberSelectorOperatorParameters ( "FullName", new ParameterOperatorParameters("s") ), ListSortDirection.Ascending, "s" ), new MemberInitOperatorParameters ( new List<MemberBindingItem> { new MemberBindingItem("ID", new MemberSelectorOperatorParameters("ID", new ParameterOperatorParameters("a"))), new MemberBindingItem("FirstName", new MemberSelectorOperatorParameters("FirstName", new ParameterOperatorParameters("a"))), new MemberBindingItem("LastName", new MemberSelectorOperatorParameters("LastName", new ParameterOperatorParameters("a"))), new MemberBindingItem("FullName", new MemberSelectorOperatorParameters("FullName", new ParameterOperatorParameters("a"))) }, typeof(InstructorModel) ), "a" ); //act DoTest<InstructorModel, Instructor, IQueryable<InstructorModel>, IQueryable<Instructor>> ( bodyParameter, "q", returnValue => Assert.Equal("Candace Kapoor", returnValue.First().FullName), "q => q.OrderBy(s => s.FullName).Select(a => new InstructorModel() {ID = a.ID, FirstName = a.FirstName, LastName = a.LastName, FullName = a.FullName})" ); } [Fact] public void SelectNewInstructor_FullNameOnly() { var bodyParameter = new SelectOperatorParameters ( new OrderByOperatorParameters ( new ParameterOperatorParameters("q"), new MemberSelectorOperatorParameters ( "FullName", new ParameterOperatorParameters("s") ), ListSortDirection.Ascending, "s" ), new MemberInitOperatorParameters ( new List<MemberBindingItem> { new MemberBindingItem("FullName", new MemberSelectorOperatorParameters("FullName", new ParameterOperatorParameters("a"))) }, typeof(InstructorModel) ), "a" ); //act DoTest<InstructorModel, Instructor, IQueryable<InstructorModel>, IQueryable<Instructor>> ( bodyParameter, "q", returnValue => Assert.Equal(" ", returnValue.First().FullName), //No way to create FirstName and LastName in the translated expressions //See the test "SelectNewInstructor()" "q => q.OrderBy(s => s.FullName).Select(a => new InstructorModel() {FullName = a.FullName})" ); } [Fact] public void SelectNewInstructor_FirstNameOnly() { var bodyParameter = new SelectOperatorParameters ( new OrderByOperatorParameters ( new ParameterOperatorParameters("q"), new MemberSelectorOperatorParameters ( "FullName", new ParameterOperatorParameters("s") ), ListSortDirection.Ascending, "s" ), new MemberInitOperatorParameters ( new List<MemberBindingItem> { new MemberBindingItem("FirstName", new MemberSelectorOperatorParameters("FirstName", new ParameterOperatorParameters("a"))) }, typeof(InstructorModel) ), "a" ); //act DoTest<InstructorModel, Instructor, IQueryable<InstructorModel>, IQueryable<Instructor>> ( bodyParameter, "q", returnValue => Assert.Equal("Candace", returnValue.First().FirstName), "q => q.OrderBy(s => s.FullName).Select(a => new InstructorModel() {FirstName = a.FirstName})" ); } [Fact] public void SelectNewAnonymousType_FullNameOnly() { var bodyParameter = new SelectOperatorParameters ( new OrderByOperatorParameters ( new ParameterOperatorParameters("q"), new MemberSelectorOperatorParameters ( "FullName", new ParameterOperatorParameters("s") ), ListSortDirection.Ascending, "s" ), new MemberInitOperatorParameters ( new List<MemberBindingItem> { new MemberBindingItem("FullName", new MemberSelectorOperatorParameters("FullName", new ParameterOperatorParameters("a"))) } ), "a" ); //act DoTest<InstructorModel, Instructor, IQueryable<dynamic>, IQueryable<dynamic>> ( bodyParameter, "q", returnValue => Assert.Equal("Candace Kapoor", returnValue.First().FullName), "q => Convert(q.OrderBy(s => s.FullName).Select(a => new AnonymousType() {FullName = a.FullName}))" ); } [Fact] public void BuildWhere_OrderBy_ThenBy_Skip_Take_Average() { //arrange var bodyParameter = new AverageOperatorParameters ( new TakeOperatorParameters ( new SkipOperatorParameters ( new ThenByOperatorParameters ( new OrderByOperatorParameters ( new WhereOperatorParameters (//q.Where(s => ((s.ID > 1) AndAlso (Compare(s.FirstName, s.LastName) > 0))) new ParameterOperatorParameters("q"),//q. the source operand new AndBinaryOperatorParameters//((s.ID > 1) AndAlso (Compare(s.FirstName, s.LastName) > 0) ( new GreaterThanBinaryOperatorParameters ( new MemberSelectorOperatorParameters("Id", new ParameterOperatorParameters("s")), new ConstantOperatorParameters(1, typeof(int)) ), new GreaterThanBinaryOperatorParameters ( new MemberSelectorOperatorParameters("FirstName", new ParameterOperatorParameters("s")), new MemberSelectorOperatorParameters("LastName", new ParameterOperatorParameters("s")) ) ), "s"//s => (created in Where operator. The parameter type is based on the source operand underlying type in this case Student.) ), new MemberSelectorOperatorParameters("LastName", new ParameterOperatorParameters("v")), ListSortDirection.Ascending, "v" ), new MemberSelectorOperatorParameters("FirstName", new ParameterOperatorParameters("v")), ListSortDirection.Descending, "v" ), 2 ), 3 ), new MemberSelectorOperatorParameters("Id", new ParameterOperatorParameters("j")), "j" ); //act DoTest<StudentModel, Student, double, double> ( bodyParameter, "q", returnValue => Assert.True(returnValue > 1), "q => q.Where(s => ((s.ID > 1) AndAlso (s.FirstName.Compare(s.LastName) > 0))).OrderBy(v => v.LastName).ThenByDescending(v => v.FirstName).Skip(2).Take(3).Average(j => j.ID)" ); } [Fact] public void BuildGroupBy_OrderBy_ThenBy_Skip_Take_Average() { //arrange var bodyParameter = new SelectOperatorParameters ( new OrderByOperatorParameters ( new GroupByOperatorParameters ( new ParameterOperatorParameters("q"), new ConstantOperatorParameters(1, typeof(int)), "a" ), new MemberSelectorOperatorParameters("Key", new ParameterOperatorParameters("b")), ListSortDirection.Ascending, "b" ), new MemberInitOperatorParameters ( new List<MemberBindingItem> { new MemberBindingItem ( "Sum_budget", new SumOperatorParameters ( new WhereOperatorParameters ( new ParameterOperatorParameters("q"), new AndBinaryOperatorParameters ( new NotEqualsBinaryOperatorParameters ( new MemberSelectorOperatorParameters("DepartmentID", new ParameterOperatorParameters("d")), new CountOperatorParameters(new ParameterOperatorParameters("q")) ), new EqualsBinaryOperatorParameters ( new MemberSelectorOperatorParameters("DepartmentID", new ParameterOperatorParameters("d")), new MemberSelectorOperatorParameters("Key", new ParameterOperatorParameters("c")) ) ), "d" ), new MemberSelectorOperatorParameters("Budget", new ParameterOperatorParameters("item")), "item" ) ) } ), "c" ); //act DoTest<DepartmentModel, Department, IQueryable<dynamic>, IQueryable<object>> ( bodyParameter, "q", returnValue => Assert.True(returnValue.First().Sum_budget == 350000), "q => Convert(q.GroupBy(a => 1).OrderBy(b => b.Key).Select(c => new AnonymousType() {Sum_budget = q.Where(d => ((d.DepartmentID != q.Count()) AndAlso (d.DepartmentID == c.Key))).Sum(item => item.Budget)}))" ); } [Fact] public void BuildGroupBy_AsQueryable_OrderBy_Select_FirstOrDefault() { //arrange var bodyParameter = new FirstOrDefaultOperatorParameters ( new SelectOperatorParameters ( new OrderByOperatorParameters ( new AsQueryableOperatorParameters ( new GroupByOperatorParameters ( new ParameterOperatorParameters("q"), new ConstantOperatorParameters(1, typeof(int)), "item" ) ), new MemberSelectorOperatorParameters("Key", new ParameterOperatorParameters("group")), ListSortDirection.Ascending, "group" ), new MemberInitOperatorParameters ( new List<MemberBindingItem> { new MemberBindingItem ( "Min_administratorName", new MinOperatorParameters ( new WhereOperatorParameters ( new ParameterOperatorParameters("q"), new EqualsBinaryOperatorParameters ( new ConstantOperatorParameters(1, typeof(int)), new MemberSelectorOperatorParameters("Key", new ParameterOperatorParameters("sel")) ), "d" ), new MemberSelectorOperatorParameters("AdministratorName", new ParameterOperatorParameters("item")), "item" ) ), new MemberBindingItem ( "Count", new CountOperatorParameters ( new WhereOperatorParameters ( new ParameterOperatorParameters("q"), new EqualsBinaryOperatorParameters ( new ConstantOperatorParameters(1, typeof(int)), new MemberSelectorOperatorParameters("Key", new ParameterOperatorParameters("sel")) ), "d" ) ) ), new MemberBindingItem ( "Sum_budget", new SumOperatorParameters ( new WhereOperatorParameters ( new ParameterOperatorParameters("q"), new EqualsBinaryOperatorParameters ( new ConstantOperatorParameters(1, typeof(int)), new MemberSelectorOperatorParameters("Key", new ParameterOperatorParameters("sel")) ), "d" ), new MemberSelectorOperatorParameters("Budget", new ParameterOperatorParameters("item")), "item" ) ), new MemberBindingItem ( "Min_budget", new MinOperatorParameters ( new WhereOperatorParameters ( new ParameterOperatorParameters("q"), new EqualsBinaryOperatorParameters ( new ConstantOperatorParameters(1, typeof(int)), new MemberSelectorOperatorParameters("Key", new ParameterOperatorParameters("sel")) ), "d" ), new MemberSelectorOperatorParameters("Budget", new ParameterOperatorParameters("item")), "item" ) ), new MemberBindingItem ( "Min_startDate", new MinOperatorParameters ( new WhereOperatorParameters ( new ParameterOperatorParameters("q"), new EqualsBinaryOperatorParameters ( new ConstantOperatorParameters(1, typeof(int)), new MemberSelectorOperatorParameters("Key", new ParameterOperatorParameters("sel")) ), "d" ), new MemberSelectorOperatorParameters("StartDate", new ParameterOperatorParameters("item")), "item" ) ) } ), "sel" ) ); //act DoTest<DepartmentModel, Department, dynamic, object> ( bodyParameter, "q", returnValue => { Assert.True(returnValue.Min_administratorName == "Candace Kapoor"); Assert.True(returnValue.Count == 4); Assert.True(returnValue.Sum_budget == 900000); Assert.True(returnValue.Min_budget == 100000); Assert.True(returnValue.Min_startDate == DateTime.Parse("2007-09-01")); }, "q => Convert(q.GroupBy(item => 1).AsQueryable().OrderBy(group => group.Key).Select(sel => new AnonymousType() {Min_administratorName = q.Where(d => (1 == sel.Key)).Min(item => item.AdministratorName), Count = q.Where(d => (1 == sel.Key)).Count(), Sum_budget = q.Where(d => (1 == sel.Key)).Sum(item => item.Budget), Min_budget = q.Where(d => (1 == sel.Key)).Min(item => item.Budget), Min_startDate = q.Where(d => (1 == sel.Key)).Min(item => item.StartDate)}).FirstOrDefault())" ); } [Fact] public void All_Filter() { //arrange var bodyParameter = new AllOperatorParameters ( new ParameterOperatorParameters(parameterName), new OrBinaryOperatorParameters ( new EqualsBinaryOperatorParameters ( new MemberSelectorOperatorParameters("AdministratorName", new ParameterOperatorParameters("a")), new ConstantOperatorParameters("Kim Abercrombie") ), new EqualsBinaryOperatorParameters ( new MemberSelectorOperatorParameters("AdministratorName", new ParameterOperatorParameters("a")), new ConstantOperatorParameters("Fadi Fakhouri") ) ), "a" ); //act DoTest<DepartmentModel, Department, bool, bool> ( bodyParameter, parameterName, returnValue => Assert.False(returnValue), "$it => $it.All(a => ((a.AdministratorName == \"Kim Abercrombie\") OrElse (a.AdministratorName == \"Fadi Fakhouri\")))" ); } [Fact] public void Any_Filter() { //arrange var bodyParameter = new AnyOperatorParameters ( new ParameterOperatorParameters(parameterName), new EqualsBinaryOperatorParameters ( new MemberSelectorOperatorParameters("AdministratorName", new ParameterOperatorParameters("a")), new ConstantOperatorParameters("Kim Abercrombie") ), "a" ); //act DoTest<DepartmentModel, Department, bool, bool> ( bodyParameter, parameterName, returnValue => Assert.True(returnValue), "$it => $it.Any(a => (a.AdministratorName == \"Kim Abercrombie\"))" ); } [Fact] public void Any() { //arrange var bodyParameter = new AnyOperatorParameters ( new ParameterOperatorParameters(parameterName) ); //act DoTest<DepartmentModel, Department, bool, bool> ( bodyParameter, parameterName, returnValue => Assert.True(returnValue), "$it => $it.Any()" ); } [Fact] public void AsQueryable() { //arrange var bodyParameter = new AsQueryableOperatorParameters ( new ParameterOperatorParameters(parameterName) ); //act DoTest<DepartmentModel, Department, IQueryable<DepartmentModel>, IQueryable<Department>> ( bodyParameter, parameterName, returnValue => { Assert.True(returnValue.Count() == 4); }, "$it => $it.AsQueryable()" ); } [Fact] public void Average_Selector() { //arrange var bodyParameter = new AverageOperatorParameters ( new ParameterOperatorParameters(parameterName), new MemberSelectorOperatorParameters("DepartmentID", new ParameterOperatorParameters("a")), "a" ); //act DoTest<DepartmentModel, Department, double, double> ( bodyParameter, parameterName, returnValue => Assert.Equal(2.5, returnValue), "$it => $it.Average(a => a.DepartmentID)" ); } [Fact] public void Average() { //arrange var bodyParameter = new AverageOperatorParameters ( new SelectOperatorParameters ( new ParameterOperatorParameters(parameterName), new MemberSelectorOperatorParameters("DepartmentID", new ParameterOperatorParameters("a")), "a" ) ); //act DoTest<DepartmentModel, Department, double, double> ( bodyParameter, parameterName, returnValue => Assert.Equal(2.5, returnValue), "$it => $it.Select(a => a.DepartmentID).Average()" ); } [Fact] public void Count_Filter() { //arrange var bodyParameter = new CountOperatorParameters ( new ParameterOperatorParameters(parameterName), new EqualsBinaryOperatorParameters ( new MemberSelectorOperatorParameters("DepartmentID", new ParameterOperatorParameters("a")), new ConstantOperatorParameters(1) ), "a" ); //act DoTest<DepartmentModel, Department, int, int> ( bodyParameter, parameterName, returnValue => Assert.Equal(1, returnValue), "$it => $it.Count(a => (a.DepartmentID == 1))" ); } [Fact] public void Count() { //arrange var bodyParameter = new CountOperatorParameters ( new ParameterOperatorParameters(parameterName) ); //act DoTest<DepartmentModel, Department, int, int> ( bodyParameter, parameterName, returnValue => Assert.Equal(4, returnValue), "$it => $it.Count()" ); } [Fact] public void Distinct() { //arrange var bodyParameter = new ToListOperatorParameters ( new DistinctOperatorParameters ( new ParameterOperatorParameters(parameterName) ) ); //act DoTest<DepartmentModel, Department, List<DepartmentModel>, List<Department>> ( bodyParameter, parameterName, returnValue => Assert.Equal(4, returnValue.Count()), "$it => $it.Distinct().ToList()" ); } [Fact()] public void First_Filter_Throws_Exception() { //arrange var bodyParameter = new FirstOperatorParameters ( new ParameterOperatorParameters(parameterName), new EqualsBinaryOperatorParameters ( new MemberSelectorOperatorParameters("DepartmentID", new ParameterOperatorParameters("a")), new ConstantOperatorParameters(-1) ), "a" ); //act Assert.Throws<AggregateException> ( () => DoTest<DepartmentModel, Department, DepartmentModel, Department> ( bodyParameter, parameterName, returnValue => { }, "$it => $it.First(a => (a.DepartmentID == -1))" ) ); } [Fact] public void First_Filter_Returns_match() { //arrange var bodyParameter = new FirstOperatorParameters ( new ParameterOperatorParameters(parameterName), new EqualsBinaryOperatorParameters ( new MemberSelectorOperatorParameters("DepartmentID", new ParameterOperatorParameters("a")), new ConstantOperatorParameters(1) ), "a" ); //act DoTest<DepartmentModel, Department, DepartmentModel, Department> ( bodyParameter, parameterName, returnValue => Assert.Equal(1, returnValue.DepartmentID), "$it => $it.First(a => (a.DepartmentID == 1))" ); } [Fact] public void First() { //arrange var bodyParameter = new FirstOperatorParameters ( new ParameterOperatorParameters(parameterName) ); //act DoTest<DepartmentModel, Department, DepartmentModel, Department> ( bodyParameter, parameterName, returnValue => Assert.NotNull(returnValue), "$it => $it.First()" ); } [Fact] public void FirstOrDefault_Filter_Returns_null() { //arrange var bodyParameter = new FirstOrDefaultOperatorParameters ( new ParameterOperatorParameters(parameterName), new EqualsBinaryOperatorParameters ( new MemberSelectorOperatorParameters("DepartmentID", new ParameterOperatorParameters("a")), new ConstantOperatorParameters(-1) ), "a" ); //act DoTest<DepartmentModel, Department, DepartmentModel, Department> ( bodyParameter, parameterName, returnValue => Assert.Null(returnValue), "$it => $it.FirstOrDefault(a => (a.DepartmentID == -1))" ); } [Fact] public void FirstOrDefault_Filter_Returns_match() { //arrange var bodyParameter = new FirstOrDefaultOperatorParameters ( new ParameterOperatorParameters(parameterName), new EqualsBinaryOperatorParameters ( new MemberSelectorOperatorParameters("DepartmentID", new ParameterOperatorParameters("a")), new ConstantOperatorParameters(1) ), "a" ); //act DoTest<DepartmentModel, Department, DepartmentModel, Department> ( bodyParameter, parameterName, returnValue => Assert.Equal(1, returnValue.DepartmentID), "$it => $it.FirstOrDefault(a => (a.DepartmentID == 1))" ); } [Fact] public void FirstOrDefault() { //arrange var bodyParameter = new FirstOrDefaultOperatorParameters ( new ParameterOperatorParameters(parameterName) ); //act DoTest<DepartmentModel, Department, DepartmentModel, Department> ( bodyParameter, parameterName, returnValue => Assert.NotNull(returnValue), "$it => $it.FirstOrDefault()" ); } [Fact(Skip = "Can't map/project IGrouping<,>")] public void GroupBy() { //arrange var bodyParameter = new GroupByOperatorParameters ( new ParameterOperatorParameters(parameterName), new MemberSelectorOperatorParameters("DepartmentID", new ParameterOperatorParameters("a")), "a" ); //act DoTest<CourseModel, Course, IQueryable<IGrouping<int, CourseModel>>, IQueryable<IGrouping<int, Course>>> ( bodyParameter, parameterName, returnValue => { Assert.True(returnValue.Count() > 2); }, "$it => $it.GroupBy(a => a.DepartmentID)" ); } [Fact] public void GroupBy_Select() { //arrange var bodyParameter = new SelectOperatorParameters ( new GroupByOperatorParameters ( new ParameterOperatorParameters(parameterName), new MemberSelectorOperatorParameters("DepartmentID", new ParameterOperatorParameters("a")), "a" ), new MemberSelectorOperatorParameters("Key", new ParameterOperatorParameters("b")), "b" ); //act DoTest<CourseModel, Course, IQueryable<int>, IQueryable<int>> ( bodyParameter, parameterName, returnValue => { Assert.NotNull(returnValue); }, "$it => $it.GroupBy(a => a.DepartmentID).Select(b => b.Key)" ); } [Fact] public void GroupBy_SelectCount() { //arrange var bodyParameter = new CountOperatorParameters ( new SelectOperatorParameters ( new GroupByOperatorParameters ( new ParameterOperatorParameters(parameterName), new MemberSelectorOperatorParameters("DepartmentID", new ParameterOperatorParameters("a")), "a" ), new MemberSelectorOperatorParameters("Key", new ParameterOperatorParameters("b")), "b" ) ); //act DoTest<CourseModel, Course, int, int> ( bodyParameter, parameterName, returnValue => { Assert.Equal(4, returnValue); }, "$it => $it.GroupBy(a => a.DepartmentID).Select(b => b.Key).Count()" ); } [Fact] public void Last_Filter_Throws_Exception() { //arrange var bodyParameter = new LastOperatorParameters ( new ParameterOperatorParameters(parameterName), new EqualsBinaryOperatorParameters ( new MemberSelectorOperatorParameters("DepartmentID", new ParameterOperatorParameters("a")), new ConstantOperatorParameters(-1) ), "a" ); //act Assert.Throws<AggregateException> ( () => DoTest<DepartmentModel, Department, DepartmentModel, Department> ( bodyParameter, parameterName, returnValue => { }, "$it => $it.Last(a => (a.DepartmentID == -1))" ) ); } [Fact] public void Last_Filter_Returns_match() { //arrange var bodyParameter = new LastOperatorParameters ( new ToListOperatorParameters ( new ParameterOperatorParameters(parameterName) ), new EqualsBinaryOperatorParameters ( new MemberSelectorOperatorParameters("DepartmentID", new ParameterOperatorParameters("a")), new ConstantOperatorParameters(2) ), "a" ); //act DoTest<DepartmentModel, Department, DepartmentModel, Department> ( bodyParameter, parameterName, returnValue => Assert.Equal(2, returnValue.DepartmentID), "$it => $it.ToList().Last(a => (a.DepartmentID == 2))" ); } [Fact] public void Last() { //arrange var bodyParameter = new LastOperatorParameters ( new ToListOperatorParameters ( new ParameterOperatorParameters(parameterName) ) ); //act DoTest<DepartmentModel, Department, DepartmentModel, Department> ( bodyParameter, parameterName, returnValue => Assert.NotNull(returnValue), "$it => $it.ToList().Last()" ); } [Fact] public void LastOrDefault_Filter_Returns_null() { //arrange var bodyParameter = new LastOrDefaultOperatorParameters ( new ToListOperatorParameters ( new ParameterOperatorParameters(parameterName) ), new EqualsBinaryOperatorParameters ( new MemberSelectorOperatorParameters("DepartmentID", new ParameterOperatorParameters("a")), new ConstantOperatorParameters(-1) ), "a" ); //act DoTest<DepartmentModel, Department, DepartmentModel, Department> ( bodyParameter, parameterName, returnValue => Assert.Null(returnValue), "$it => $it.ToList().LastOrDefault(a => (a.DepartmentID == -1))" ); } [Fact] public void LastOrDefault_Filter_Returns_match() { //arrange var bodyParameter = new LastOrDefaultOperatorParameters ( new ToListOperatorParameters ( new ParameterOperatorParameters(parameterName) ), new EqualsBinaryOperatorParameters ( new MemberSelectorOperatorParameters("DepartmentID", new ParameterOperatorParameters("a")), new ConstantOperatorParameters(2) ), "a" ); //act DoTest<DepartmentModel, Department, DepartmentModel, Department> ( bodyParameter, parameterName, returnValue => Assert.Equal(2, returnValue.DepartmentID), "$it => $it.ToList().LastOrDefault(a => (a.DepartmentID == 2))" ); } [Fact] public void LastOrDefault() { //arrange var bodyParameter = new LastOrDefaultOperatorParameters ( new ToListOperatorParameters ( new ParameterOperatorParameters(parameterName) ) ); //act DoTest<DepartmentModel, Department, DepartmentModel, Department> ( bodyParameter, parameterName, returnValue => Assert.NotNull(returnValue), "$it => $it.ToList().LastOrDefault()" ); } [Fact] public void Max_Selector() { //arrange var bodyParameter = new MaxOperatorParameters ( new ParameterOperatorParameters(parameterName), new MemberSelectorOperatorParameters("DepartmentID", new ParameterOperatorParameters("a")), "a" ); //act DoTest<DepartmentModel, Department, int, int> ( bodyParameter, parameterName, returnValue => Assert.Equal(4, returnValue), "$it => $it.Max(a => a.DepartmentID)" ); } [Fact] public void Max() { var bodyParameter = new MaxOperatorParameters ( new SelectOperatorParameters ( new ParameterOperatorParameters(parameterName), new MemberSelectorOperatorParameters("DepartmentID", new ParameterOperatorParameters("a")), "a" ) ); //act DoTest<DepartmentModel, Department, int, int> ( bodyParameter, parameterName, returnValue => Assert.Equal(4, returnValue), "$it => $it.Select(a => a.DepartmentID).Max()" ); } [Fact] public void Min_Selector() { //arrange var bodyParameter = new MinOperatorParameters ( new ParameterOperatorParameters(parameterName), new MemberSelectorOperatorParameters("DepartmentID", new ParameterOperatorParameters("a")), "a" ); //act DoTest<DepartmentModel, Department, int, int> ( bodyParameter, parameterName, returnValue => Assert.Equal(1, returnValue), "$it => $it.Min(a => a.DepartmentID)" ); } [Fact] public void Min() { //arrange var bodyParameter = new MinOperatorParameters ( new SelectOperatorParameters ( new ParameterOperatorParameters(parameterName), new MemberSelectorOperatorParameters("DepartmentID", new ParameterOperatorParameters("a")), "a" ) ); //act DoTest<DepartmentModel, Department, int, int> ( bodyParameter, parameterName, returnValue => Assert.Equal(1, returnValue), "$it => $it.Select(a => a.DepartmentID).Min()" ); } [Fact] public void OrderBy() { //arrange var bodyParameter = new OrderByOperatorParameters ( new ParameterOperatorParameters(parameterName), new MemberSelectorOperatorParameters("DepartmentID", new ParameterOperatorParameters("a")), ListSortDirection.Ascending, "a" ); //act DoTest<DepartmentModel, Department, IOrderedQueryable<DepartmentModel>, IOrderedQueryable<Department>> ( bodyParameter, parameterName, returnValue => Assert.Equal(1, returnValue.First().DepartmentID), "$it => $it.OrderBy(a => a.DepartmentID)" ); } [Fact] public void OrderByDescending() { //arrange var bodyParameter = new OrderByOperatorParameters ( new ParameterOperatorParameters(parameterName), new MemberSelectorOperatorParameters("DepartmentID", new ParameterOperatorParameters("a")), ListSortDirection.Descending, "a" ); //act DoTest<DepartmentModel, Department, IOrderedQueryable<DepartmentModel>, IOrderedQueryable<Department>> ( bodyParameter, parameterName, returnValue => Assert.Equal(4, returnValue.First().DepartmentID), "$it => $it.OrderByDescending(a => a.DepartmentID)" ); } [Fact] public void OrderByThenBy() { //arrange var bodyParameter = new ThenByOperatorParameters ( new OrderByOperatorParameters ( new ParameterOperatorParameters(parameterName), new MemberSelectorOperatorParameters("Credits", new ParameterOperatorParameters("a")), ListSortDirection.Ascending, "a" ), new MemberSelectorOperatorParameters("CourseID", new ParameterOperatorParameters("a")), ListSortDirection.Ascending, "a" ); //act DoTest<CourseModel, Course, IOrderedQueryable<CourseModel>, IOrderedQueryable<Course>> ( bodyParameter, parameterName, returnValue => Assert.Equal(1050, returnValue.First().CourseID), "$it => $it.OrderBy(a => a.Credits).ThenBy(a => a.CourseID)" ); } [Fact] public void OrderByThenByDescending() { //arrange var bodyParameter = new ThenByOperatorParameters ( new OrderByOperatorParameters ( new ParameterOperatorParameters(parameterName), new MemberSelectorOperatorParameters("Credits", new ParameterOperatorParameters("a")), ListSortDirection.Ascending, "a" ), new MemberSelectorOperatorParameters("CourseID", new ParameterOperatorParameters("a")), ListSortDirection.Descending, "a" ); //act DoTest<CourseModel, Course, IOrderedQueryable<CourseModel>, IOrderedQueryable<Course>> ( bodyParameter, parameterName, returnValue => Assert.Equal(4041, returnValue.First().CourseID), "$it => $it.OrderBy(a => a.Credits).ThenByDescending(a => a.CourseID)" ); } [Fact] public void Paging() { //arrange var bodyParameter = new TakeOperatorParameters ( new SkipOperatorParameters ( new ThenByOperatorParameters ( new OrderByOperatorParameters ( new SelectManyOperatorParameters ( new ParameterOperatorParameters(parameterName), new MemberSelectorOperatorParameters("Assignments", new ParameterOperatorParameters("a")), "a" ), new MemberSelectorOperatorParameters("CourseTitle", new ParameterOperatorParameters("a")), ListSortDirection.Ascending, "a" ), new MemberSelectorOperatorParameters("InstructorID", new ParameterOperatorParameters("a")), ListSortDirection.Ascending, "a" ), 1 ), 2 ); //act DoTest<CourseModel, Course, IQueryable<CourseAssignmentModel>, IQueryable<CourseAssignment>> ( bodyParameter, parameterName, returnValue => { Assert.Equal(2, returnValue.Count()); Assert.Equal("Chemistry", returnValue.Last().CourseTitle); }, "$it => $it.SelectMany(a => a.Assignments).OrderBy(a => a.CourseTitle).ThenBy(a => a.InstructorID).Skip(1).Take(2)" ); } [Fact] public void Select_New() { //arrange var bodyParameter = new SelectOperatorParameters ( new OrderByOperatorParameters ( new ParameterOperatorParameters(parameterName), new MemberSelectorOperatorParameters("DepartmentID", new ParameterOperatorParameters("a")), ListSortDirection.Descending, "a" ), new MemberInitOperatorParameters ( new List<MemberBindingItem> { new MemberBindingItem("ID", new MemberSelectorOperatorParameters("DepartmentID", new ParameterOperatorParameters("a"))), new MemberBindingItem("DepartmentName", new MemberSelectorOperatorParameters("Name", new ParameterOperatorParameters("a"))), new MemberBindingItem("Courses", new MemberSelectorOperatorParameters("Courses", new ParameterOperatorParameters("a"))) } ), "a" ); //act DoTest<DepartmentModel, Department, IQueryable<dynamic>, IQueryable<dynamic>> ( bodyParameter, parameterName, returnValue => Assert.Equal(4, returnValue.First().ID), "$it => Convert($it.OrderByDescending(a => a.DepartmentID).Select(a => new AnonymousType() {ID = a.DepartmentID, DepartmentName = a.Name, Courses = a.Courses}))" ); } [Fact] public void SelectMany() { //arrange var bodyParameter = new SelectManyOperatorParameters ( new ParameterOperatorParameters(parameterName), new MemberSelectorOperatorParameters("Assignments", new ParameterOperatorParameters("a")), "a" ); //act DoTest<CourseModel, Course, IQueryable<CourseAssignmentModel>, IQueryable<CourseAssignment>> ( bodyParameter, parameterName, returnValue => { Assert.Equal(8, returnValue.Count()); }, "$it => $it.SelectMany(a => a.Assignments)" ); } [Fact] public void Single_Filter_Throws_Exception() { //arrange var bodyParameter = new SingleOperatorParameters ( new ParameterOperatorParameters(parameterName), new EqualsBinaryOperatorParameters ( new MemberSelectorOperatorParameters("DepartmentID", new ParameterOperatorParameters("a")), new ConstantOperatorParameters(-1) ), "a" ); //act Assert.Throws<AggregateException> ( () => DoTest<DepartmentModel, Department, DepartmentModel, Department> ( bodyParameter, parameterName, returnValue => { }, "$it => $it.Single(a => (a.DepartmentID == -1))" ) ); } [Fact] public void Single_Filter_Returns_match() { //arrange var bodyParameter = new SingleOperatorParameters ( new ParameterOperatorParameters(parameterName), new EqualsBinaryOperatorParameters ( new MemberSelectorOperatorParameters("DepartmentID", new ParameterOperatorParameters("a")), new ConstantOperatorParameters(1) ), "a" ); //act DoTest<DepartmentModel, Department, DepartmentModel, Department> ( bodyParameter, parameterName, returnValue => Assert.Equal(1, returnValue.DepartmentID), "$it => $it.Single(a => (a.DepartmentID == 1))" ); } [Fact] public void Single_with_multiple_matches_Throws_Exception() { //arrange var bodyParameter = new SingleOperatorParameters ( new ParameterOperatorParameters(parameterName) ); //act Assert.Throws<AggregateException> ( () => DoTest<DepartmentModel, Department, DepartmentModel, Department> ( bodyParameter, parameterName, returnValue => { }, "$it => $it.Single()" ) ); } [Fact] public void Sum_Selector() { //arrange var bodyParameter = new SumOperatorParameters ( new ParameterOperatorParameters(parameterName), new MemberSelectorOperatorParameters("DepartmentID", new ParameterOperatorParameters("a")), "a" ); //act DoTest<DepartmentModel, Department, int, int> ( bodyParameter, parameterName, returnValue => Assert.Equal(10, returnValue), "$it => $it.Sum(a => a.DepartmentID)" ); } [Fact] public void Sum() { //arrange var bodyParameter = new SumOperatorParameters ( new SelectOperatorParameters ( new ParameterOperatorParameters(parameterName), new MemberSelectorOperatorParameters("DepartmentID", new ParameterOperatorParameters("a")), "a" ) ); //act DoTest<DepartmentModel, Department, int, int> ( bodyParameter, parameterName, returnValue => Assert.Equal(10, returnValue), "$it => $it.Select(a => a.DepartmentID).Sum()" ); } [Fact] public void ToList() { //arrange var bodyParameter = new ToListOperatorParameters ( new ParameterOperatorParameters(parameterName) ); //act DoTest<DepartmentModel, Department, List<DepartmentModel>, List<Department>> ( bodyParameter, parameterName, returnValue => Assert.Equal(4, returnValue.Count), "$it => $it.ToList()" ); } [Fact] public void Where_with_matches() { //arrange var bodyParameter = new WhereOperatorParameters ( new OrderByOperatorParameters ( new ParameterOperatorParameters(parameterName), new MemberSelectorOperatorParameters("DepartmentID", new ParameterOperatorParameters("a")), ListSortDirection.Descending, "a" ), new NotEqualsBinaryOperatorParameters ( new MemberSelectorOperatorParameters("DepartmentID", new ParameterOperatorParameters("a")), new ConstantOperatorParameters(1) ), "a" ); //act DoTest<DepartmentModel, Department, IQueryable<DepartmentModel>, IQueryable<Department>> ( bodyParameter, parameterName, returnValue => Assert.Equal(2, returnValue.Last().DepartmentID), "$it => $it.OrderByDescending(a => a.DepartmentID).Where(a => (a.DepartmentID != 1))" ); } [Fact] public void Where_without_matches() { //arrange var bodyParameter = new WhereOperatorParameters ( new ParameterOperatorParameters(parameterName), new EqualsBinaryOperatorParameters ( new MemberSelectorOperatorParameters("DepartmentID", new ParameterOperatorParameters("a")), new ConstantOperatorParameters(-1) ), "a" ); //act DoTest<DepartmentModel, Department, IQueryable<DepartmentModel>, IQueryable<Department>> ( bodyParameter, parameterName, returnValue => Assert.Empty(returnValue), "$it => $it.Where(a => (a.DepartmentID == -1))" ); } void DoTest<TModel, TData, TModelReturn, TDataReturn>(IExpressionParameter bodyParameter, string parameterName, Action<TModelReturn> assert, string expectedExpressionString, Parameters.Expansions.SelectExpandDefinitionParameters selectExpandDefinition = null) where TModel : LogicBuilder.Domain.BaseModel where TData : LogicBuilder.Data.BaseData { //arrange IMapper mapper = serviceProvider.GetRequiredService<IMapper>(); ISchoolRepository repository = serviceProvider.GetRequiredService<ISchoolRepository>(); IExpressionParameter expressionParameter = GetExpressionParameter<IQueryable<TModel>, TModelReturn>(bodyParameter, parameterName); TestExpressionString(); TestReturnValue(); void TestReturnValue() { //act TModelReturn returnValue = QueryOperations<TModel, TData, TModelReturn, TDataReturn>.Query ( repository, mapper, expressionParameter, selectExpandDefinition ); //assert assert(returnValue); } void TestExpressionString() { //act Expression<Func<IQueryable<TModel>, TModelReturn>> expression = QueryOperations<TModel, TData, TModelReturn, TDataReturn>.GetQueryFunc ( mapper.MapToOperator(expressionParameter) ); //assert if (!string.IsNullOrEmpty(expectedExpressionString)) { AssertFilterStringIsCorrect(expression, expectedExpressionString); } } } #endregion Tests #region Helpers private IExpressionParameter GetExpressionParameter<T, TResult>(IExpressionParameter selectorBody, string parameterName = "$it") => new SelectorLambdaOperatorParameters ( selectorBody, typeof(T), parameterName, typeof(TResult) ); private void AssertFilterStringIsCorrect(Expression expression, string expected) { AssertStringIsCorrect(ExpressionStringBuilder.ToString(expression)); void AssertStringIsCorrect(string resultExpression) => Assert.True ( expected == resultExpression, $"Expected expression '{expected}' but the deserializer produced '{resultExpression}'" ); } static MapperConfiguration MapperConfiguration; private void Initialize() { if (MapperConfiguration == null) { MapperConfiguration = new MapperConfiguration(cfg => { cfg.AddExpressionMapping(); cfg.AddProfile<ParameterToDescriptorMappingProfile>(); cfg.AddProfile<DescriptorToOperatorMappingProfile>(); cfg.AddProfile<SchoolProfile>(); cfg.AddProfile<ExpansionParameterToDescriptorMappingProfile>(); cfg.AddProfile<ExpansionDescriptorToOperatorMappingProfile>(); }); } MapperConfiguration.AssertConfigurationIsValid(); serviceProvider = new ServiceCollection() .AddDbContext<SchoolContext> ( options => options.UseSqlServer ( @"Server=(localdb)\mssqllocaldb;Database=SchoolContext2;ConnectRetryCount=0" ), ServiceLifetime.Transient ) .AddTransient<ISchoolStore, SchoolStore>() .AddTransient<ISchoolRepository, SchoolRepository>() .AddSingleton<AutoMapper.IConfigurationProvider> ( MapperConfiguration ) .AddTransient<IMapper>(sp => new Mapper(sp.GetRequiredService<AutoMapper.IConfigurationProvider>(), sp.GetService)) .BuildServiceProvider(); SchoolContext context = serviceProvider.GetRequiredService<SchoolContext>(); //context.Database.EnsureDeleted(); context.Database.EnsureCreated(); DatabaseSeeder.Seed_Database(serviceProvider.GetRequiredService<ISchoolRepository>()).Wait(); } #endregion Helper } }
namespace SGDE.Domain.Repositories { #region Using using SGDE.Domain.Entities; using System.Collections.Generic; #endregion public interface IDetailInvoiceRepository { List<DetailInvoice> GetAll(int invoiceId = 0, bool previousInvoice = false); DetailInvoice GetById(int id); DetailInvoice Add(DetailInvoice newDetailInvoice); bool Update(DetailInvoice detailInvoice); bool Delete(int id); List<DetailInvoice> UpdateFromPreviousInvoice(int invoiceId); List<DetailInvoice> UpdateFromWork(int invoiceId, List<DetailInvoice> detailsInvoice); List<DetailInvoice> UpdateToEmptyDetails(int invoiceId); List<DetailInvoice> GetAllWithIncludes(); } }
using Amazon.DynamoDBv2; using Amazon.DynamoDBv2.DocumentModel; using calculatorRestAPI.Models.DTOs; using System.Collections.Generic; using System.Linq; namespace calculatorRestAPI.Services { public class Service { private static Service thisService; private static readonly string tableName = "CalculatorData"; AmazonDynamoDBConfig clientConfig = new AmazonDynamoDBConfig(); AmazonDynamoDBClient client = new AmazonDynamoDBClient( new AmazonDynamoDBConfig()); public static Service getService() { if ( thisService == null ) { thisService = new Service(); } return thisService; } public CalculatorDTO getCalculatorData( string userName ) { Table table = Table.LoadTable(client, tableName); QueryFilter filter = new QueryFilter("UserID", QueryOperator.Equal, userName ); CalculatorDTO answer = new CalculatorDTO(); Search search = table.Query(filter); List<Document> queryResult = search.GetNextSet(); if(queryResult.Count > 0 && queryResult.FirstOrDefault() != null ) { Document output = queryResult.FirstOrDefault(); answer.ParamA = output["paramA"]; answer.ParamB = output["paramB"]; answer.Operator = output["operator"]; answer.Result = output["result"]; } return answer; } public void saveCalculatorData(CalculatorDTO data) { Table table = Table.LoadTable(client, tableName); Document book = new Document(); book["UserID"] = data.UserName; book["paramA"] = data.ParamA; book["paramB"] = data.ParamB; book["operator"] = data.Operator; book["result"] = data.Result; table.PutItem(book); } } }
namespace Airport.Models { public class Departure: FlightEvent { } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using UniversityAdministration.Models.Entities; namespace UniversityAdministration.Models { internal class DbInitializer { internal static void Initialize(UniversityAdministrationContext context) { if (context.Student.Any()) { return; } var students = new Student[] { new Student { FirstName = "Carson", LastName = "Alexander", EnrollMentDate = DateTime.Parse("2010-09-01") }, new Student { FirstName = "Meredith", LastName = "Alonso", EnrollMentDate = DateTime.Parse("2012-09-01") }, new Student { FirstName = "Arturo", LastName = "Anand", EnrollMentDate = DateTime.Parse("2013-09-01") }, new Student { FirstName = "Gytis", LastName = "Barzdukas", EnrollMentDate = DateTime.Parse("2012-09-01") }, new Student { FirstName = "Yan", LastName = "Li", EnrollMentDate = DateTime.Parse("2012-09-01") }, new Student { FirstName = "Peggy", LastName = "Justice", EnrollMentDate = DateTime.Parse("2011-09-01") }, new Student { FirstName = "Laura", LastName = "Norman", EnrollMentDate = DateTime.Parse("2013-09-01") }, new Student { FirstName = "Nino", LastName = "Olivetto", EnrollMentDate = DateTime.Parse("2005-09-01") } }; foreach (Student s in students) { context.Student.Add(s); } context.SaveChanges(); var courses = new Course[] { new Course {CourseId = 1050, Title = "Chemistry", Etcs = 5}, new Course {CourseId = 4022, Title = "Microeconomics", Etcs = 5 }, new Course {CourseId = 4041, Title = "Computer Sciece", Etcs = 5 }, new Course {CourseId = 1045, Title = "Calculus", Etcs = 5 }, }; foreach (Course c in courses) { context.Course.Add(c); } context.SaveChanges(); var enrollments = new EnrollMent[] { new EnrollMent { StudentId = students.Single(s => s.LastName == "Alexander").StudentId, CourseId = courses.Single(c => c.Title == "Chemistry" ).CourseId, Grade = 1 }, new EnrollMent { StudentId = students.Single(s => s.LastName == "Alexander").StudentId, CourseId = courses.Single(c => c.Title == "Microeconomics" ).CourseId, Grade = 1 }, new EnrollMent { StudentId = students.Single(s => s.LastName == "Alexander").StudentId, CourseId = courses.Single(c => c.Title == "Macroeconomics" ).CourseId, Grade = 1 }, new EnrollMent { StudentId = students.Single(s => s.LastName == "Alonso").StudentId, CourseId = courses.Single(c => c.Title == "Calculus" ).CourseId, Grade = 1 }, new EnrollMent { StudentId = students.Single(s => s.LastName == "Alonso").StudentId, CourseId = courses.Single(c => c.Title == "Trigonometry" ).CourseId, Grade = 5 }, new EnrollMent { StudentId = students.Single(s => s.LastName == "Alonso").StudentId, CourseId = courses.Single(c => c.Title == "Composition" ).CourseId, Grade = 4 }, new EnrollMent { StudentId = students.Single(s => s.LastName == "Anand").StudentId, CourseId = courses.Single(c => c.Title == "Chemistry" ).CourseId }, new EnrollMent { StudentId = students.Single(s => s.LastName == "Anand").StudentId, CourseId = courses.Single(c => c.Title == "Microeconomics").CourseId, Grade = 3 }, new EnrollMent { StudentId = students.Single(s => s.LastName == "Barzdukas").StudentId, CourseId = courses.Single(c => c.Title == "Chemistry").CourseId, Grade = 2 }, new EnrollMent { StudentId = students.Single(s => s.LastName == "Li").StudentId, CourseId = courses.Single(c => c.Title == "Composition").CourseId, Grade = 7 }, new EnrollMent { StudentId = students.Single(s => s.LastName == "Justice").StudentId, CourseId = courses.Single(c => c.Title == "Literature").CourseId, Grade = 8 } }; foreach (EnrollMent e in enrollments) { var enrollmentInDataBase = context.EnrollMent.Where( s => s.StudentId == e.StudentId && s.Course.CourseId == e.CourseId).SingleOrDefault(); if (enrollmentInDataBase == null) { context.EnrollMent.Add(e); } } context.SaveChanges(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WindowsFormsApp3 { public abstract class ListADT { public Node Head; public int Size = 0; public abstract void InsertFirst(Staj stj, Egitim egt); public abstract void InsertLast(Staj stj, Egitim egt); public abstract void InsertPos(int position,Staj stj, Egitim egt); public abstract void DeleteFirst(); public abstract void DeleteLast(); public abstract void DeletePos(int position); public abstract Node GetElement(int position); public abstract string DisplayElements(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using TriodorArgeProject.Entities.EntityClasses; using TriodorArgeProject.Service.Abstract; namespace TriodorArgeProject.Service.Managers { public class MaterialCostManager:ManagerBase<MaterialCosts> { } }
using Microsoft.Spark.Sql; using System; using System.Collections.Generic; namespace GettingData { public class Program { static void Main(string[] args) { var sparkSession = SparkSession.Builder().GetOrCreate(); var options = new Dictionary<string, string> { {"delimiter", "|"}, {"samplingRation", "1.0" }//, //{"inferSchema", "true" } }; var schemaString = "invDate INT, invItemId INT, invWareHouseId INT, invQuantityOnHand String"; var csvFileSource = sparkSession.Read() .Format("csv") .Options(options) .Schema(schemaString) .Load(args[0]); //.Load(@"C:\Users\maxde\source\repos\POC-Spark-Docker-NetCore\GettingData\FileSpark\inventory.dat"); var csvFileTarget = sparkSession.Read() .Format("csv") .Options(options) .Schema(schemaString) .Load(args[1]); csvFileSource.PrintSchema(); csvFileTarget.PrintSchema(); csvFileSource.Show(5); csvFileTarget.Show(5); csvFileSource.Select("invItemId").Where("invItemId > 2124").Show(); csvFileSource.GroupBy("invItemId").Count() .WithColumnRenamed("count", "total") .Filter("invItemId >= 2124") .Show(); //Spark with SQL Queries csvFileSource.CreateOrReplaceTempView("csvFileSourceTemp"); sparkSession.Sql("select invItemId from csvFileSourceTemp").Show(); //csvFileSource.Join(csvFileTarget, "key").Show(); } } }
using System.Collections; using UnityEngine; public class DarkController : MonoBehaviour { private void OnTriggerEnter2D(Collider2D collision) { if (collision.gameObject.name == "Player") { StartCoroutine(Fade()); } } private void OnTriggerExit2D(Collider2D collision) { if (collision.gameObject.name == "Player") { StartCoroutine(Appear()); } } IEnumerator Fade() { for (float ft = 0.7f; ft >= 0; ft -= 0.015f) { Color c = GetComponent<SpriteRenderer>().color; c.a = ft; GetComponent<SpriteRenderer>().color = c; yield return null; } } IEnumerator Appear() { for (float ft = 0; ft <= 0.7f; ft += 0.015f) { Color c = GetComponent<SpriteRenderer>().color; c.a = ft; GetComponent<SpriteRenderer>().color = c; yield return null; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _04POO { class Program { static void Main(string[] args) { Instructor unaPersona = new Instructor(); unaPersona.SetApellido("Villa"); unaPersona.Nombre = "Andres"; unaPersona.Denominacion = "Instructor"; unaPersona.NumeroCuenta = "lkasjdkla123"; Console.WriteLine(unaPersona.ObtenerNombreCompleto()); Alumno unAlumno = new Alumno(); unAlumno.SetApellido("Gomez"); unAlumno.Nombre = "Ariel"; unAlumno.Denominacion = "Alumno"; unAlumno.PagoAlDia = false; Console.WriteLine(unAlumno.ObtenerNombreCompleto()); Alumno otroAlumno = new Alumno() { Nombre = "Pedro", Denominacion = "Alumno", PagoAlDia = true }; otroAlumno.SetApellido("Gonzalez"); Console.WriteLine(otroAlumno.ObtenerNombreCompleto()); Console.WriteLine(otroAlumno.ObtenerNombreCompleto("Señor")); IDescriptible descriptible = new Persona(); descriptible = unAlumno; Persona[] participantes = new Persona[10]; Persona unaPersonaCualquiera = new Instructor(); unaPersonaCualquiera.ObtenerNombreCompleto(); participantes[0] = new Instructor(); participantes[1] = new Administrativo(); participantes[2] = new Alumno(); participantes[3] = new Alumno(); participantes[4] = new Alumno(); participantes[5] = new Alumno(); Console.ReadKey(); } } }
/** * Author: Kenneth Vassbakk */ using System.Collections; using System.Collections.Generic; using UnityEngine; public class EndlessProperties : MonoBehaviour { public int tileSize; public int tileLength; public int preGen; public GameObject[] leftSide; public GameObject[] rightSide; public GameObject[] ground; public GameObject[] collidersLeft; public GameObject[] collidersRight; public GameObject[] collidersCenter; }
using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading; namespace Micro.Net.Core.Extensions { public static class FileExtensions { public static FileStream WaitForFile(string fullPath, FileMode mode, FileAccess access, FileShare share, int retries = 10, int interval = 50) { for (int numTries = 0; numTries < retries; numTries++) { FileStream fs = null; try { fs = new FileStream(fullPath, mode, access, share); return fs; } catch (IOException) { if (fs != null) { fs.Dispose(); } Thread.Sleep(interval); } } return null; } } }
using System; using System.Collections; namespace Aut.Lab.lab09 { public class Line { private Point point1 = null; private Point point2 = null; public Line(Point p1, Point p2) { point1 = p1; point2 = p2; } public double Length() { double powSquare = Math.Pow(point1.X - point2.X, 2) + Math.Pow(point1.Y - point2.Y, 2); double sumlength = Math.Sqrt(powSquare); return (sumlength); } public double Slope() { double sum = (point1.Y-point2.Y)/(point1.X-point2.X); return(sum); } public void ShowC(double slope) { double sumc = -(slope)*point1.X + point2.Y; Console.WriteLine("Sumc = {0}",sumc); } } }
namespace Average_Character_Delimiter { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; public class AverageCharacterDelimiter { public static void Main(string[] args) { //read the input,split and covert to list; var input = Console.ReadLine().Split(' ').ToList(); //list for all chars; var chars = new List<char>(); //fill the chars list; foreach (var str in input) { foreach (char ch in str) { chars.Add(ch); } } //var for average char; string averageChar = Char.ToUpper(AverageChar(chars)).ToString(); Console.WriteLine(string.Join(averageChar , input)); } //method for calculate average char from list char; public static char AverageChar(List<char> list) { //char for the result; char resultChar; //var average sum; of char list; var average = 0.0; //var for sum of value of all char in list; var sum = 0; for (int i = 0; i < list.Count; i++) { //var for current char int value; int currentCharValue = (int)list[i]; sum += currentCharValue; } average = (int)sum / (list.Count); resultChar = (char)average; return resultChar; } } }
using System.Linq; namespace Restaurant365.Core { public class CalculationResult { public CalculationResult(int total, string formula) { Total = total; Formula = formula; } public int Total { get; } public string Formula { get; } } }
using Publicon.Core.Entities.Abstract; using System; namespace Publicon.Core.Entities.Concrete { public class Notification : Entity { public string Title { get; protected set; } public string Message { get; protected set; } public DateTime SendTime { get; protected set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class GridLayoutController : MonoBehaviour { public bool isVertical, isHorizontal; void Start() { } void Update() { if (isVertical == true) { gameObject.GetComponent<RectTransform>().sizeDelta = new Vector2(gameObject.GetComponent<RectTransform>().sizeDelta.x, (gameObject.GetComponent<GridLayoutGroup>().cellSize.y * gameObject.transform.childCount) + gameObject.GetComponent<GridLayoutGroup>().padding.bottom + gameObject.GetComponent<GridLayoutGroup>().padding.top); } if (isHorizontal == true) { gameObject.GetComponent<RectTransform>().sizeDelta = new Vector2((gameObject.GetComponent<RectTransform>().sizeDelta.x * gameObject.transform.childCount) + gameObject.GetComponent<GridLayoutGroup>().padding.left + gameObject.GetComponent<GridLayoutGroup>().padding.right, gameObject.GetComponent<GridLayoutGroup>().cellSize.y); } if (isVertical == false && isHorizontal == false) { print("Script is not setting up"); } } }
using Mosa.Kernel; using Mosa.Kernel.x86; using Mosa.Runtime; namespace Mosa.External.x86.Driver { public class VMWareSVGAII { public enum Register : ushort { ID = 0, Enable = 1, Width = 2, Height = 3, BitsPerPixel = 7, FrameBufferStart = 13, VRamSize = 15, MemStart = 18, MemSize = 19, ConfigDone = 20, Sync = 21, Busy = 22, FifoNumRegisters = 293 } private enum ID : uint { Magic = 0x900000, V2 = (Magic << 8) | 2, } public enum FIFO : uint { Min = 0, Max = 4, NextCmd = 8, Stop = 12 } private enum FIFOCommand { Update = 1 } private enum IOPortOffset : byte { Index = 0, Value = 1, } private ushort IndexPort; private ushort ValuePort; public MemoryBlock Video_Memory; private MemoryBlock FIFO_Memory; private PCIDevice device; public uint height; public uint width; public uint depth; public VMWareSVGAII() { device = (PCI.GetDevice(VendorID.VMWare, DeviceID.SVGAIIAdapter)); device.EnableMemory(true); uint basePort = device.BaseAddressBar[0].BaseAddress; IndexPort = (ushort)(basePort + (uint)IOPortOffset.Index); ValuePort = (ushort)(basePort + (uint)IOPortOffset.Value); WriteRegister(Register.ID, (uint)ID.V2); if (ReadRegister(Register.ID) != (uint)ID.V2) return; Video_Memory = Memory.GetPhysicalMemory(new Pointer(ReadRegister(Register.FrameBufferStart)), ReadRegister(Register.VRamSize)); InitializeFIFO(); } protected void InitializeFIFO() { FIFO_Memory = Memory.GetPhysicalMemory(new Pointer(ReadRegister(Register.MemStart)), ReadRegister(Register.MemSize)); FIFO_Memory.Write32((uint)FIFO.Min, (uint)Register.FifoNumRegisters * 4); FIFO_Memory.Write32((uint)FIFO.Max, FIFO_Memory.Size); FIFO_Memory.Write32((uint)FIFO.NextCmd, (uint)FIFO.Min); FIFO_Memory.Write32((uint)FIFO.Stop, FIFO_Memory.Read32((uint)FIFO.Min)); WriteRegister(Register.ConfigDone, 1); } public void SetMode(uint width, uint height, uint depth = 32) { Disable(); this.depth = (depth / 8); this.width = width; this.height = height; WriteRegister(Register.Width, width); WriteRegister(Register.Height, height); WriteRegister(Register.BitsPerPixel, depth); Enable(); InitializeFIFO(); } protected void WriteRegister(Register register, uint value) { IOPort.Out32(IndexPort, (uint)register); IOPort.Out32(ValuePort, value); } protected uint ReadRegister(Register register) { IOPort.Out32(IndexPort, (uint)register); return IOPort.In32(ValuePort); } protected void SetFIFO(FIFO cmd, uint value) { FIFO_Memory.Write32((uint)cmd, value); return; } uint nextcmd = 1172; public void Update() { if (nextcmd == 1212) { nextcmd = 1172; } SetFIFO((FIFO)(nextcmd), (uint)FIFOCommand.Update); SetFIFO(FIFO.NextCmd, nextcmd + 4); nextcmd += 4; SetFIFO((FIFO)(nextcmd), 0); SetFIFO(FIFO.NextCmd, nextcmd + 4); nextcmd += 4; SetFIFO((FIFO)(nextcmd), 0); SetFIFO(FIFO.NextCmd, nextcmd + 4); nextcmd += 4; SetFIFO((FIFO)(nextcmd), width); SetFIFO(FIFO.NextCmd, nextcmd + 4); nextcmd += 4; SetFIFO((FIFO)(nextcmd), height); SetFIFO(FIFO.NextCmd, nextcmd + 4); nextcmd += 4; } public void Enable() { WriteRegister(Register.Enable, 1); } public void Disable() { WriteRegister(Register.Enable, 0); } } }
using System; using System.Collections.Generic; using System.Text; namespace TaskForce.Network { /// <summary> /// List of all possible network packages /// </summary> [Serializable] public enum Command { /// <summary> /// Forces the client to refresh his ProtectedFilterList with the given filter list /// </summary> RefreshProtectedFilterList, /// <summary> /// Forces the client to refresh his Forbbiden FilterList with the given filter list /// </summary> RefreshForbiddenFilterList, /// <summary> /// Sends an Protocol object to the server /// </summary> SaveProtocol } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using Athena.Data.Books; using Athena.Data.Categories; using Athena.Data.PublishingHouses; using Athena.Data.Series; using Athena.Data.SpreadsheetData; using Athena.Data.StoragePlaces; using Athena.Import.Extractors; using OfficeOpenXml; using Serilog; using Serilog.Core; using Author = Athena.Data.Author; namespace Athena.Import { public class SpreadsheetDataImport : IDisposable { private string _fullFilePath; private Logger _log; private List<SpreadsheetCatalogData> _spreadsheetCatalogDataList = null; private List<SpreadsheetCategoryData> _spreadsheetCategoryDataList = null; private List<SpreadsheetStoragePlaceData> _spreadsheetStoragePlaceDataList = null; public IReadOnlyList<SpreadsheetCatalogData> CatalogData { get { if (_spreadsheetCatalogDataList == null) { LoadData(); } return _spreadsheetCatalogDataList.AsReadOnly(); } } public IReadOnlyList<SpreadsheetCategoryData> CategoryData { get { if (_spreadsheetCategoryDataList == null) { LoadData(); } return _spreadsheetCategoryDataList.AsReadOnly(); } } public IReadOnlyList<SpreadsheetStoragePlaceData> StoragePlaceData { get { if (_spreadsheetStoragePlaceDataList == null) { LoadData(); } return _spreadsheetStoragePlaceDataList.AsReadOnly(); } } public SpreadsheetDataImport(string fullFilePath) { _fullFilePath = fullFilePath; ExcelPackage.LicenseContext = LicenseContext.NonCommercial; _log = new LoggerConfiguration().WriteTo.File("./logs/ImportLog_.txt", rollingInterval: RollingInterval.Day) .CreateLogger(); } public void LoadData() { using var package = new ExcelPackage(new FileInfo(_fullFilePath)); var catalog = package.Workbook.Worksheets[0]; var categories = package.Workbook.Worksheets[1]; var storagePlaces = package.Workbook.Worksheets[2]; _spreadsheetCatalogDataList = new List<SpreadsheetCatalogData>(); _spreadsheetCategoryDataList = new List<SpreadsheetCategoryData>(); _spreadsheetStoragePlaceDataList = new List<SpreadsheetStoragePlaceData>(); var catalogRowNumber = 2; while (catalog.Cells[catalogRowNumber, 1].Value != null) { var catalogData = new SpreadsheetCatalogData { Title = catalog.Cells[catalogRowNumber, 1].Value.ToString(), Author = catalog.Cells[catalogRowNumber, 2].Value?.ToString(), Series = catalog.Cells[catalogRowNumber, 3].Value?.ToString(), PublishingHouse = catalog.Cells[catalogRowNumber, 4].Value?.ToString(), Year = catalog.Cells[catalogRowNumber, 5].Value?.ToString(), Town = catalog.Cells[catalogRowNumber, 6].Value?.ToString(), ISBN = catalog.Cells[catalogRowNumber, 7].Value?.ToString(), Language = catalog.Cells[catalogRowNumber, 8].Value.ToString(), StoragePlace = catalog.Cells[catalogRowNumber, 9].Value?.ToString(), Comment = catalog.Cells[catalogRowNumber, 10].Value?.ToString(), Category = catalog.Cells[catalogRowNumber, 2].Style.Fill.BackgroundColor.Rgb }; _spreadsheetCatalogDataList.Add(catalogData); catalogRowNumber++; } var categoryRowNumber = 2; while (categories.Cells[categoryRowNumber, 1].Value != null) { var categoryData = new SpreadsheetCategoryData { Colour = categories.Cells[categoryRowNumber, 1].Style.Fill.BackgroundColor.Rgb, Name = categories.Cells[categoryRowNumber, 2].Value.ToString() }; _spreadsheetCategoryDataList.Add(categoryData); categoryRowNumber++; } var storagePlaceRowNumber = 2; while (storagePlaces.Cells[storagePlaceRowNumber, 1].Value != null) { var storagePlaceData = new SpreadsheetStoragePlaceData { Name = storagePlaces.Cells[storagePlaceRowNumber, 1].Value.ToString(), Comment = storagePlaces.Cells[storagePlaceRowNumber, 2].Value.ToString() }; _spreadsheetStoragePlaceDataList.Add(storagePlaceData); storagePlaceRowNumber++; } } public List<Book> ImportBooksList() { var authors = ImportAuthorsList(); var seriesInfos = ImportSeriesListInfo(); var publishingHouses = ImportPublishingHousesList(); var storagePlaces = ImportStoragePlacesList(); var categories = ImportCategoriesList(); var seriesList = seriesInfos .GroupBy(a => a.SeriesName) .Select(a => a.First()) .Where(a => !string.IsNullOrEmpty(a.SeriesName)) .Select(a => a.ToSeries()) .ToList(); List<Book> books = new List<Book>(); foreach (var spreadsheetCatalogData in CatalogData) { var bookCategories = new List<Category>() { CategoryExtractor.Extract(spreadsheetCatalogData.Category) }; bookCategories = bookCategories.Where(a => a != null).ToList(); var bookSeriesInfo = SeriesInfoExtractor.Extract(spreadsheetCatalogData.Series); var book = new Book { Id = Guid.NewGuid(), Title = TitleExtractor.Extract(spreadsheetCatalogData.Title), Authors = AuthorExtractor.Extract(spreadsheetCatalogData.Author), Series = bookSeriesInfo?.ToSeries(), PublishingHouse = PublishingHouseExtractor.Extract(spreadsheetCatalogData.PublishingHouse), PublishmentYear = YearExtractor.Extract(spreadsheetCatalogData.Year), ISBN = IsbnExtractor.Extract(spreadsheetCatalogData.ISBN), Language = LanguageExtractor.Extract(spreadsheetCatalogData.Language), StoragePlace = StoragePlaceExtractor.Extract(spreadsheetCatalogData.StoragePlace), Comment = CommentExtractor.Extract(spreadsheetCatalogData.Comment), Categories = bookCategories, VolumeNumber = bookSeriesInfo?.VolumeNumber }; ImportBookValidator.CheckAuthors(authors, book.Authors); ImportBookValidator.CheckSeries(seriesList, book.Series); ImportBookValidator.CheckPublishingHouse(publishingHouses, book.PublishingHouse); ImportBookValidator.CheckStoragePlace(storagePlaces, book.StoragePlace); ImportBookValidator.CheckCategory(categories, book.Categories); books.Add(book); } return books; } public List<Author> ImportAuthorsList() { List<Author> authors = new List<Author>(); foreach (var spreadsheetData in CatalogData) { List<Author> authorsOfOneBook; try { authorsOfOneBook = AuthorExtractor.Extract(spreadsheetData.Author); } catch (ExtractorException e) { _log.Error($"Author Extract Error: [{e.Text}]"); continue; } authors.AddRange(authorsOfOneBook); } var authorWithoutDoubles = authors .GroupBy(a => new {a.FirstName, a.LastName}) .Select(a => a.First()) .ToList(); return authorWithoutDoubles; } public List<SeriesInfo> ImportSeriesListInfo() { List<SeriesInfo> seriesInfoList = new List<SeriesInfo>(); foreach (var spreadsheetData in CatalogData) { SeriesInfo seriesInfo; try { seriesInfo = SeriesInfoExtractor.Extract(spreadsheetData.Series); } catch (ExtractorException e) { _log.Error($"Series Extract Error: [{e.Text}]"); continue; } if (seriesInfo != null) { seriesInfoList.Add(seriesInfo); } } var seriesInfoWithoutDoubles = seriesInfoList .GroupBy(a => new {a.SeriesName, a.VolumeNumber}) .Select(a => a.First()) .ToList(); return seriesInfoWithoutDoubles; } public List<PublishingHouse> ImportPublishingHousesList() { List<PublishingHouse> publishingHousesList = new List<PublishingHouse>(); foreach (var spreadsheetData in CatalogData) { var publishingHouse = PublishingHouseExtractor.Extract(spreadsheetData.PublishingHouse); if (publishingHouse != null) { publishingHousesList.Add(publishingHouse); } } var publisherWithoutDoubles = publishingHousesList .GroupBy(a => a.PublisherName) .Select(a => a.First()) .ToList(); return publisherWithoutDoubles; } public List<StoragePlace> ImportStoragePlacesList() { List<StoragePlace> storagePlaces = new List<StoragePlace>(); foreach (var spreadsheetStoragePlaceData in StoragePlaceData) { var storagePlace = StoragePlaceExtractor.Extract(spreadsheetStoragePlaceData.Name, spreadsheetStoragePlaceData.Comment); if (storagePlace != null) { storagePlaces.Add(storagePlace); } } foreach (var spreadsheetCatalogData in CatalogData) { var storagePlace = StoragePlaceExtractor.Extract(spreadsheetCatalogData.StoragePlace); if (storagePlace != null) { storagePlaces.Add(storagePlace); } } var storagePlacesWithoutDoubles = storagePlaces .GroupBy(a => a.StoragePlaceName) .Select(a => a.FirstOrDefault(b => !string.IsNullOrEmpty(b.Comment)) ?? a.First()) .ToList(); return storagePlacesWithoutDoubles; } public List<Category> ImportCategoriesList() { List<Category> categories = new List<Category>(); foreach (var spreadsheetCategoryData in CategoryData) { var category = CategoryExtractor.Extract(spreadsheetCategoryData.Colour); if (category != null) { categories.Add(category); } } return categories; } public void Dispose() { _log.Dispose(); } } }
namespace Components.DataAccess.Sql.Persistence { using System.Collections.Generic; internal interface IPersistent { internal void PersistMultipleCommandsInSingleTransaction( string connectionString, Queue<SqlCommandDetail> orderOfExecutions); } }
/******************************************************************** * FulcrumWeb RAD Framework - Fulcrum of your business * * Copyright (c) 2002-2009 FulcrumWeb, ALL RIGHTS RESERVED * * * * THE SOURCE CODE CONTAINED WITHIN THIS FILE AND ALL RELATED * * FILES OR ANY PORTION OF ITS CONTENTS SHALL AT NO TIME BE * * COPIED, TRANSFERRED, SOLD, DISTRIBUTED, OR OTHERWISE MADE * * AVAILABLE TO OTHER INDIVIDUALS WITHOUT EXPRESS WRITTEN CONSENT * * AND PERMISSION FROM FULCRUMWEB. CONSULT THE END USER LICENSE * * AGREEMENT FOR INFORMATION ON ADDITIONAL RESTRICTIONS. * ********************************************************************/ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Framework.Db; using Framework.Entity; using Framework.Remote.Mobile; namespace Framework.Remote { public partial class CxAppServer { /// <summary> /// Removes bookmark. /// </summary> ///<param name="uniqueId">Id of removed bookmark.</param> /// <returns>Initialized CxModel</returns> public CxModel RemoveBookmark(string uniqueId) { try { CxAppServerContext context = new CxAppServerContext(); CxEntityMark toRemove = context.EntityMarks.BookmarkItems.FirstOrDefault(mark => mark.UniqueId == uniqueId); if (toRemove != null) { context.EntityMarks.DeleteMark(toRemove); using (CxDbConnection conn = CxDbConnections.CreateEntityConnection()) { context.EntityMarks.SaveAndReload(conn, m_Holder); } } CxModel model = new CxModel { EntityMarks = new CxClientEntityMarks() }; model.EntityMarks.RemovedBookmarkItems.Add(new CxClientEntityMark(toRemove)); return model; } catch (Exception ex) { CxExceptionDetails exceptionDetails = new CxExceptionDetails(ex); CxModel model = new CxModel { Error = exceptionDetails }; return model; } } } }
using System; using System.Collections.Generic; using System.Reflection; using UnityEditor; using UnityEngine; namespace UnityWebGLSpeechDetection { public class Example07PanelCommands : EditorWindow { /// <summary> /// Holds the languages and dialects /// </summary> private LanguageResult _mLanguageResult = null; /// <summary> /// The selected language index /// </summary> private int _mLanguage = 0; private string[] _mLanguages = new string[] { "Languages" }; /// <summary> /// The selected dialog index /// </summary> private int _mDialect = 0; private string[] _mDialects = new string[] { "Dialects" }; /// <summary> /// Is the detection event initialized /// </summary> private bool _mInitialized = false; private Dictionary<string, MethodInfo> _mEditorCommands = new Dictionary<string, MethodInfo>(); /// <summary> /// Dictionary of commands /// </summary> private Dictionary<string, DateTime> _mTimers = new Dictionary<string, DateTime>(); /// <summary> /// Run UI actions on the main thread /// </summary> private List<Action> _mPendingActions = new List<Action>(); /// <summary> /// Display status text /// </summary> private static string _sTextStatus = string.Empty; /// <summary> /// Set the status text and repaint /// </summary> /// <param name="text">Text.</param> private void SetTextStatus(string text) { //Debug.Log(text); _sTextStatus = text; //Repaint in the update event Action action = () => { Repaint(); }; _mPendingActions.Add(action); } /// <summary> /// Initially not initialized /// </summary> private void OnEnable() { SetTextStatus("OnEnable"); _mEditorCommands.Clear(); Assembly assembly = Assembly.GetExecutingAssembly(); if (null != assembly) { foreach (var type in assembly.GetTypes()) { foreach (var methodInfo in type.GetMethods(BindingFlags.Static | BindingFlags.Public)) { foreach (var attribute in methodInfo.GetCustomAttributes(false)) { if (attribute is SpeechDetectionAttribute) { SpeechDetectionAttribute attr = attribute as SpeechDetectionAttribute; //Debug.Log(attr.GetSpokenPhrase()); _mEditorCommands[attr.GetSpokenPhrase()] = methodInfo; break; } } } } } _mInitialized = false; _mTimers.Clear(); foreach (KeyValuePair<string, MethodInfo> kvp in _mEditorCommands) { _mTimers[kvp.Key] = DateTime.MinValue; } } bool RunEditorCommands(string word) { foreach (KeyValuePair<string, MethodInfo> kvp in _mEditorCommands) { if (word.Contains(kvp.Key)) { if (!_mTimers.ContainsKey(kvp.Key) || _mTimers[kvp.Key] < DateTime.Now) { kvp.Value.Invoke(null, null); _mTimers[kvp.Key] = DateTime.Now + TimeSpan.FromSeconds(1); SetTextStatus(kvp.Key); return true; } } } return false; } /// <summary> /// Handler for speech detection events /// </summary> /// <param name="args"></param> bool HandleDetectionResult(DetectionResult detectionResult) { bool enabled = EditorProxySpeechDetectionPlugin.IsEnabled(); if (!enabled) { return false; } //Debug.Log("Example06PanelDictation: HandleDetectionResult:"); if (null == detectionResult) { return false; } SpeechRecognitionResult[] results = detectionResult.results; if (null == results) { return false; } bool doAbort = false; foreach (SpeechRecognitionResult result in results) { if (doAbort) { break; } SpeechRecognitionAlternative[] alternatives = result.alternatives; if (null == alternatives) { continue; } foreach (SpeechRecognitionAlternative alternative in alternatives) { if (string.IsNullOrEmpty(alternative.transcript)) { continue; } string lower = alternative.transcript.ToLower(); SetTextStatus(lower); if (RunEditorCommands(lower)) { doAbort = true; break; } } } if (doAbort) { EditorProxySpeechDetectionPlugin plugin = EditorProxySpeechDetectionPlugin.GetInstance(); if (null != plugin) { plugin.Abort(); } return true; } return false; } /// <summary> /// Handle multiple panels open and changing languages /// </summary> /// <param name="languageChangedResult"></param> void HandleOnLanguageChanged(LanguageChangedResult languageChangedResult) { ISpeechDetectionPlugin plugin = EditorProxySpeechDetectionPlugin.GetInstance(); int languageIndex = _mLanguage; if (SpeechDetectionUtils.HandleOnLanguageChanged( ref _mLanguage, _mLanguages, ref _mDialect, _mDialects, _mLanguageResult, plugin, languageChangedResult)) { if (languageIndex != _mLanguage) { SpeechDetectionUtils.HandleLanguageChanged(_mLanguages, _mLanguage, out _mDialects, ref _mDialect, _mLanguageResult, plugin); } Repaint(); } } /// <summary> /// Reinitialize the editor proxy when enabled and not compiling /// </summary> private void Update() { bool enabled = EditorProxySpeechDetectionPlugin.IsEnabled(); if (!enabled || EditorApplication.isCompiling) { _mInitialized = false; return; } // handle init EditorProxySpeechDetectionPlugin plugin = EditorProxySpeechDetectionPlugin.GetInstance(); if (null != plugin) { if (!_mInitialized) { if (!plugin.IsAvailable()) { return; } //Debug.LogFormat("Update: Plugin is available"); plugin.GetLanguages((languageResult) => { _mLanguageResult = languageResult; // populate the language options SpeechDetectionUtils.PopulateLanguages(out _mLanguages, out _mLanguage, languageResult); // Restore the default language SpeechDetectionUtils.RestoreLanguage(_mLanguages, out _mLanguage); // Handle setting the default language SpeechDetectionUtils.PausePlayerPrefs(true); SpeechDetectionUtils.HandleLanguageChanged(_mLanguages, _mLanguage, out _mDialects, ref _mDialect, _mLanguageResult, plugin); SpeechDetectionUtils.PausePlayerPrefs(false); // Restore the default dialect SpeechDetectionUtils.RestoreDialect(_mDialects, out _mDialect); // Update UI Repaint(); }); // subscribe to events plugin.AddListenerOnDetectionResult(HandleDetectionResult); // get on language changed events plugin.AddListenerOnLanguageChanged(HandleOnLanguageChanged); //Debug.Log("Update: HandleDetectionResult subscribed"); _mInitialized = true; Repaint(); } } // Check timers to deactivate button after delay bool doRepaint = false; foreach (KeyValuePair<string, MethodInfo> kvp in _mEditorCommands) { DateTime timer = _mTimers[kvp.Key]; if (timer != DateTime.MinValue && timer < DateTime.Now) { _mTimers[kvp.Key] = DateTime.MinValue; doRepaint = true; } } if (doRepaint) { Repaint(); } // run pending UI actions while (_mPendingActions.Count > 0) { Action action = _mPendingActions[0]; _mPendingActions.RemoveAt(0); action.Invoke(); } } /// <summary> /// Display GUI in the editor panel /// </summary> private void OnGUI() { EditorProxySpeechDetectionPlugin plugin = EditorProxySpeechDetectionPlugin.GetInstance(); bool enabled = EditorProxySpeechDetectionPlugin.IsEnabled(); if (!enabled) { if (null != plugin) { // unsubscribe to events plugin.RemoveListenerOnDetectionResult(HandleDetectionResult); } } bool isCompiling = EditorApplication.isCompiling; if (isCompiling) { GUI.enabled = false; } bool newEnabled = GUILayout.Toggle(enabled, "Enabled"); if (newEnabled != enabled) { EditorProxySpeechDetectionPlugin.SetEnabled(newEnabled); } if (isCompiling) { GUI.enabled = true; } if (null != plugin && plugin.IsAvailable()) { GUILayout.Label("IsAvailable: true"); } else { GUILayout.Label("IsAvailable: false"); } if (isCompiling || !newEnabled) { GUI.enabled = false; } if (GUILayout.Button("Open Browser Tab")) { if (null != plugin) { SetTextStatus("Open Browser Tab"); plugin.ManagementOpenBrowserTab(); } } if (GUILayout.Button("Close Browser Tab")) { if (null != plugin) { SetTextStatus("Close Browser Tab"); plugin.ManagementCloseBrowserTab(); } } GUILayout.BeginHorizontal(GUILayout.Width(position.width)); int port = 5000; if (null != plugin) { port = plugin._mPort; } string strPort = GUILayout.TextField(string.Format("{0}", port)); if (int.TryParse(strPort, out port)) { if (null != plugin) { plugin._mPort = port; } } if (GUILayout.Button("Set Proxy Port")) { if (null != plugin) { SetTextStatus(string.Format("Set Proxy Tab: port={0}", plugin._mPort)); plugin.ManagementSetProxyPort(plugin._mPort); } } GUILayout.EndHorizontal(); if (GUILayout.Button("Launch Proxy")) { if (null != plugin) { SetTextStatus("Launch Proxy"); plugin.ManagementLaunchProxy(); } } if (GUILayout.Button("Close Proxy")) { if (null != plugin) { SetTextStatus("Close Proxy"); plugin.ManagementCloseProxy(); } } int newLanguage = EditorGUILayout.Popup(_mLanguage, _mLanguages); if (_mLanguage != newLanguage) { _mLanguage = newLanguage; if (null != plugin) { SpeechDetectionUtils.HandleLanguageChanged(_mLanguages, _mLanguage, out _mDialects, ref _mDialect, _mLanguageResult, plugin); } } if (!isCompiling && newEnabled) { GUI.enabled = _mLanguage != 0; } int newDialect = EditorGUILayout.Popup(_mDialect, _mDialects); if (_mDialect != newDialect) { _mDialect = newDialect; if (null != plugin) { SpeechDetectionUtils.HandleDialectChanged(_mDialects, _mDialect, _mLanguageResult, plugin); } } if (!isCompiling && newEnabled) { GUI.enabled = true; } GUI.skin.label.wordWrap = true; GUILayout.Label("Say any of the following words which will highlight when detected.", GUILayout.Width(position.width), GUILayout.Height(40)); GUI.skin.label.wordWrap = false; Color oldColor = GUI.backgroundColor; foreach (KeyValuePair<string, MethodInfo> kvp in _mEditorCommands) { DateTime timer = _mTimers[kvp.Key]; if (timer > DateTime.Now) { GUI.backgroundColor = Color.red; } else { GUI.backgroundColor = oldColor; } GUILayout.Button(kvp.Key); } GUI.backgroundColor = oldColor; GUILayout.Label(_sTextStatus, GUILayout.Width(position.width), GUILayout.Height(40)); if (isCompiling || !newEnabled) { GUI.enabled = true; } } } }
using System; using UnityEngine; /// <summary> /// Thje Script is attached to a Controller /// Script to grab Objects with a Rigidbody /// </summary> public class ControllerGrabObject : ControllerFunctionality { JointBreakSensor jointBreakSensor; //TODO private ThrowObject Cube; protected override void Awake() { info = new GrabObjectInformation(); base.Awake(); } private void TriggerEnter(Collider other, VRSensor sensor) { ControllerInformation info = controllerManager.GetControllerInfo(sensor.GetComponent<SteamVR_TrackedObject>()); SetCollidingObject(other, info); } private void TriggerStay(Collider other, VRSensor sensor) { ControllerInformation info = controllerManager.GetControllerInfo(sensor.GetComponent<SteamVR_TrackedObject>()); SetCollidingObject(other, info); } private void TriggerExit(Collider other, VRSensor sensor) { ControllerInformation info = controllerManager.GetControllerInfo(sensor.GetComponent<SteamVR_TrackedObject>()); GrabObjectInformation grabObjInfo = (GrabObjectInformation)info.GetFunctionalityInfoByType(typeof(GrabObjectInformation)); if (!grabObjInfo.collidingObject) { return; } grabObjInfo.collidingObject = null; } /// <summary> /// In here we check if the collision that jsut occured is relevant /// </summary> private void SetCollidingObject(Collider col, ControllerInformation info) { GrabObjectInformation grabObjInfo = (GrabObjectInformation)info.GetFunctionalityInfoByType(typeof(GrabObjectInformation)); if (grabObjInfo.collidingObject || !col.GetComponent<Rigidbody>() || col.GetComponent<SteamVR_TrackedObject>()) { return; } grabObjInfo.collidingObject = col.gameObject; //Debug.Log("Collided with -> " +info.trackedObj + " - " + grabObjInfo.collidingObject.name); } private void GrabObject(ControllerInformation info) { GrabObjectInformation grabObjInfo = (GrabObjectInformation)info.GetFunctionalityInfoByType(typeof(GrabObjectInformation)); grabObjInfo.objectInHand = grabObjInfo.collidingObject; grabObjInfo.collidingObject = null; //objectInHand.transform.position = Vector3.Lerp(transform.position,objectInHand.transform.position, 0.8f); if (!info.trackedObj.GetComponent<FixedJoint>()) { var joint = AddFixedJoint(info); joint.connectedBody = grabObjInfo.objectInHand.GetComponent<Rigidbody>(); } if(grabObjInfo.objectInHand.gameObject.name == "Cube") { Cube = grabObjInfo.objectInHand.GetComponent<ThrowObject>(); if (Cube) { if (Cube.taskCompleted[0] != null) { { Cube.taskCompleted[0].Invoke(); } } } } } private FixedJoint AddFixedJoint(ControllerInformation info) { FixedJoint fx = info.trackedObj.gameObject.AddComponent<FixedJoint>(); fx.breakForce = 20000; fx.breakTorque = 20000; return fx; } private void ReleaseObject(ControllerInformation info) { GrabObjectInformation grabObjInfo = (GrabObjectInformation)info.GetFunctionalityInfoByType(typeof(GrabObjectInformation)); FixedJoint[] joints = info.trackedObj.gameObject.GetComponents<FixedJoint>(); if (joints != null && joints.Length > 0) { foreach (var item in joints) { item.connectedBody = null; Destroy(item); } } if (grabObjInfo.objectInHand == null) return; grabObjInfo.objectInHand.GetComponent<Rigidbody>().velocity = Quaternion.Euler(0, 180, 0) * controllerManager.GetController(info.trackedObj).velocity; grabObjInfo.objectInHand.GetComponent<Rigidbody>().angularVelocity = Quaternion.Euler(0, 180, 0) * controllerManager.GetController(info.trackedObj).angularVelocity; if (grabObjInfo.ObjectReleased != null) { grabObjInfo.ObjectReleased.Invoke(grabObjInfo.objectInHand); } grabObjInfo.objectInHand = null; } public void ForceGrab(GameObject go, ControllerInformation info) { GrabObjectInformation grabObjInfo = (GrabObjectInformation)info.GetFunctionalityInfoByType(typeof(GrabObjectInformation)); ReleaseObject(info); grabObjInfo.collidingObject = go; GrabObject(info); } protected override void ActiveControllerUpdate(ControllerInformation controller) { } protected override void NonActiveControllerUpdate(ControllerInformation controller) { } protected override void AnyControllerUpdate(ControllerInformation controller) { GrabObjectInformation grabObjInfo = (GrabObjectInformation)controller.GetFunctionalityInfoByType(typeof(GrabObjectInformation)); if (controllerManager.GetController(controller.trackedObj).GetHairTriggerDown()) { if (grabObjInfo.collidingObject) { GrabObject(controller); } } if (controllerManager.GetController(controller.trackedObj).GetHairTriggerUp()) { ReleaseObject(controller); } if (controllerManager.GetController(controller.trackedObj).GetPressDown(SteamVR_Controller.ButtonMask.Grip)) { if (grabObjInfo.objectInHand != null) { if (grabObjInfo.objectInHand.GetComponent<Lighter>()) { grabObjInfo.objectInHand.GetComponent<Lighter>().StartFire(); } } } if (controllerManager.GetController(controller.trackedObj).GetPressUp(SteamVR_Controller.ButtonMask.Grip)) { if (grabObjInfo.objectInHand != null) { if (grabObjInfo.objectInHand.GetComponent<Lighter>()) { grabObjInfo.objectInHand.GetComponent<Lighter>().StopFire(); } } } } protected override void OnControllerInitialized() { base.OnControllerInitialized(); foreach (var item in controllerManager.controllerInfos) { item.sensor.triggerEnter += TriggerEnter; item.sensor.triggerLeave += TriggerExit; item.sensor.triggerStay += TriggerStay; } } private void OnJointBroke(JointBreakSensor sensor) { ReleaseObject(controllerManager.GetControllerInfo(sensor.GetComponent<SteamVR_TrackedObject>())); } protected override void AfterControllerIntialized(){} }
using UnityEngine; using System.Collections; public class MainMenuBehavior : IWorldBehavior { #region Class Variables //Class Variables public enum GameState{ MainState, NewGameState, SettingsState, QuitState, QuitConfirmState, CreditsState }//GameState private GameState _currentState = GameState.MainState; private Vector3 _notVisible = new Vector3(1000.0f, 0.0f, 0.0f); private Vector3 _visible = Vector3.zero; //References to game objects private GameObject _mainState; private GameObject _newGameState; private GameObject _settingsState; private GameObject _quitState; private GameObject _creditsState; private GameObject _names; #endregion public void Initialize(){} public MainMenuBehavior(){ findGameObjects(); } public void findGameObjects(){ //find game state objects _mainState = GameObject.Find("MainState"); _newGameState = GameObject.Find("NewGameState"); //_settingsState = GameObject.Find("SettingsState"); _quitState = GameObject.Find("QuitConfirmState"); _creditsState = GameObject.Find ("CreditsState"); _names = GameObject.Find("Names"); //set visibility _names.SetActive(false); _newGameState.transform.position = _notVisible; _creditsState.transform.position = _notVisible; //_settingsState.transform.position = _notVisible; _quitState.transform.position = _notVisible; } public void React(ThrowableType[] types){ var type = types[0]; switch(type){ case ThrowableType.A: switch(_currentState){ case GameState.MainState: // New Game Label in Main State _mainState.transform.position = _notVisible; _newGameState.transform.position = _visible; _currentState = GameState.NewGameState; break; case GameState.NewGameState: //Back Label in New Game State _newGameState.transform.position = _notVisible; _mainState.transform.position = _visible; _currentState = GameState.MainState; break; case GameState.SettingsState: break; case GameState.QuitConfirmState: Application.Quit(); break; case GameState.CreditsState: _creditsState.transform.position = _notVisible; _mainState.transform.position = _visible; _names.SetActive(false); _currentState = GameState.MainState; break; } break; case ThrowableType.B: switch(_currentState){ case GameState.QuitConfirmState: _mainState.transform.position = _visible; _quitState.transform.position = _notVisible; _currentState = GameState.MainState; break; case GameState.NewGameState: Application.LoadLevel("02_recycle_game"); break; } break; case ThrowableType.C: switch(_currentState){ case GameState.MainState: _mainState.transform.position = _notVisible; _quitState.transform.position = _visible; _currentState = GameState.QuitConfirmState; break; } break; case ThrowableType.D: switch(_currentState){ case GameState.MainState: _mainState.transform.position = _notVisible; _creditsState.transform.position = _visible; _names.SetActive(true); _currentState = GameState.CreditsState; break; } break; }//switch }//React }
using System; using System.Collections.Generic; using System.Text; using ServiceDesk.Core.Interfaces.Common; namespace ServiceDesk.Core.Entities.RequestSystem { public class RequestAttachment : IEntity { public int Id { get; set; } public string RealName { get; set; } public string UnicalName { get; set; } public string SizeMb { get; set; } public string FilePath { get; set; } public string Reference { get; set; } public Guid RequestId { get; set; } public virtual Request Request { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace FirstWebApp.ViewModels { public class PagingViewModel { public int PageNumber { get; set; } public bool HasPreviousPage => this.PageNumber > 1; public bool HasNextPage => this.PageNumber < this.PagesCount; public int PreviousPageNumber => this.PageNumber - 1; public int NextPageNumber => this.PageNumber + 1; public int PagesCount => (int)Math.Ceiling((double)this.CountSmartphones / this.ItemsPerPage); public int CountSmartphones { get; set; } public int ItemsPerPage { get; set; } public bool WitchSearch { get; set; } public string StringSearch { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public static class MiscUtil { // Send FSM event to all FSMs that is in the same game object with the input fsm / monobehavior public static void MySendEventToAll(this Behaviour mb, string name) { if (!mb) return; var go = mb.gameObject; MySendEventToAll(go, name); } // Send FSM event to all FSMs that is in the game object public static void MySendEventToAll(this GameObject go, string name) { if (!go) return; foreach (var i in go.GetComponents<PlayMakerFSM>()) { i.SendEvent(name); } } }
namespace Game.ConsoleUI.Interfaces.Services { using Game.Models; public interface IGameStateService { GameState GetOrCreateGameState(); } }
// Copyright (c) 2014 Rotorz Limited. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. using UnityEngine; using UnityEditor; using Rotorz.Tile; using Rotorz.Tile.Editor; namespace Custom { /// <summary> /// Custom tool which paints previously composed tile compositions onto the active /// tile system. This tool also includes erase functionality. /// </summary> [InitializeOnLoad] public class CompositeTileTool : PaintTool { static CompositeTileTool() { ToolManager.Instance.RegisterTool<CompositeTileTool>(); } /// <summary> /// Gets or sets the active tile composition. A value of <c>null</c> indicates /// that erase function should be used. /// </summary> public static TileComposition ActiveComposition { get; set; } #region Tool Information public override string Name { get { return "custom.composite.paint"; } } public override string Label { get { return ">C<"; } } public override Texture2D IconNormal { get { return null; } } public override Texture2D IconActive { get { return null; } } #endregion #region Tool Interaction public override void OnTool(ToolEvent e, IToolContext context) { if (e.type == EventType.MouseDown) { context.TileSystem.BeginBulkEdit(); OnPaint(e, context); context.TileSystem.EndBulkEdit(); } } protected override void OnPaint(ToolEvent e, IToolContext context) { var system = context.TileSystem; TileIndex paintIndex = new TileIndex(e.row, e.column); if (e.leftButton) { // Paint with brush! system.PaintComposition(paintIndex, ActiveComposition); } else { // Erase! var compositionMap = system.GetComponent<CompositeTileMap>(); if (compositionMap == null) system.EraseTile(paintIndex); else system.EraseGroup(paintIndex, ActiveComposition); } } #endregion #region Tool Options Interface public override void OnToolOptionsGUI() { DrawActiveCompositionPopup("Composition"); } /// <summary> /// Draw popup control allowing selection of active tile composition. /// </summary> /// <param name="label">Prefix label for popup control.</param> private void DrawActiveCompositionPopup(string label) { GUIStyle style = EditorStyles.popup; Rect position = GUILayoutUtility.GetRect(GUIContent.none, style); position = EditorGUI.PrefixLabel(position, new GUIContent(label)); string activeContent = ActiveComposition != null ? ActiveComposition.Name : "(Erase)"; position.width -= 31; if (GUI.Button(position, activeContent, style)) ShowActiveCompositionPopup(position); position.x = position.xMax + 3; position.width = 28; if (GUI.Button(position, "...")) Selection.objects = new Object[] { TileCompositionEditorUtility.Manager }; } /// <summary> /// Show popup menu allowing selection from defined tile compositions. /// </summary> /// <param name="position">Position of popup button in in tool palette.</param> private void ShowActiveCompositionPopup(Rect position) { var popup = new GenericMenu(); popup.AddItem(new GUIContent("(Erase)"), ActiveComposition == null, SetActiveComposition, -1); popup.AddSeparator(""); var compositions = TileCompositionEditorUtility.Manager.Compositions; for (int i = 0; i < compositions.Count; ++i) { var composition = compositions[i]; popup.AddItem(new GUIContent(composition.Name), composition == ActiveComposition, SetActiveComposition, i); } popup.DropDown(position); } /// <summary> /// Set active tile composition from the given index. This method handles user selection /// from popup menu (<see cref="ShowActiveCompositionPopup(Rect)"/>). /// </summary> /// <param name="index">Zero-based index of tile composition of a value of -1 for "(Erase)".</param> private void SetActiveComposition(object index) { int i = (int)index; if (i == -1) ActiveComposition = null; else ActiveComposition = TileCompositionEditorUtility.Manager.Compositions[i]; } #endregion #region Scene View private static Vector3[] s_SquareNozzleVerts = new Vector3[4]; protected override void DrawNozzleIndicator(TileSystem system, int row, int column, Vector3 position, BrushNozzle nozzle, int radius) { if (ActiveComposition != null) { // // Draw custom indicator to highlight area which will be filled by template. // Matrix4x4 restoreMatrix = Handles.matrix; Handles.matrix = system.transform.localToWorldMatrix; Handles.color = Color.white; s_SquareNozzleVerts[0] = new Vector3(column, -row, 0); s_SquareNozzleVerts[1] = new Vector3(column + ActiveComposition.Columns, -row, 0); s_SquareNozzleVerts[2] = new Vector3(column + ActiveComposition.Columns, -row - ActiveComposition.Rows, 0); s_SquareNozzleVerts[3] = new Vector3(column, -row - ActiveComposition.Rows, 0); Handles.DrawSolidRectangleWithOutline(s_SquareNozzleVerts, new Color(1f, 0f, 0f, 0.07f), new Color(1f, 0f, 0f, 0.55f)); Handles.matrix = restoreMatrix; } else { base.DrawNozzleIndicator(system, row, column, position, nozzle, 0); } } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using System.IO; using System.Collections; using System.Windows.Media.Effects; namespace Images { /// <summary> /// MainWindow.xaml 的交互逻辑 /// </summary> public partial class MainWindow : Window { public int i = 0; public string str = ""; bool state = false; public Point currentPosition; ArrayList newArrayList = new ArrayList(); Image canvasImage = new Image(); public MainWindow() { InitializeComponent(); DirectoryInfo Dir = new DirectoryInfo(Environment.CurrentDirectory + "//Image"); foreach (FileInfo file in Dir.GetFiles("*.jpg", SearchOption.AllDirectories)) { str = file.ToString(); newArrayList.Add(str); } for (; i < newArrayList.Count; i++) { Image listImage = new Image(); Border br = new Border(); Border bs = new Border(); BitmapImage bitmapImage = new BitmapImage(); ListBoxItem newListBox = new ListBoxItem(); bitmapImage.BeginInit(); bitmapImage.UriSource = new Uri(Environment.CurrentDirectory + "//Image//" + newArrayList[i].ToString()); bitmapImage.EndInit(); listImage.Source = bitmapImage; listImage.Width = 280; listImage.Height = 280; //Image添加到Border中 br.Child = listImage; br.Padding = new System.Windows.Thickness((float)1.1f); br.Background = Brushes.White; br.BorderThickness = new System.Windows.Thickness((int)3); br.Margin = new System.Windows.Thickness((int)1); // br.BorderBrush = Brushes.Green; //阴影效果 DropShadowEffect myDropShadowEffect = new DropShadowEffect(); // Set the color of the shadow to Black. Color myShadowColor = new Color(); myShadowColor.A = 255; // Note that the alpha value is ignored by Color property. // The Opacity property is used to control the alpha. myShadowColor.B = 50; myShadowColor.G = 50; myShadowColor.R = 50; myDropShadowEffect.Color = myShadowColor; // Set the direction of where the shadow is cast to 320 degrees. myDropShadowEffect.Direction = 310; // Set the depth of the shadow being cast. myDropShadowEffect.ShadowDepth = 20; // Set the shadow softness to the maximum (range of 0-1). myDropShadowEffect.BlurRadius = 10; // Set the shadow opacity to half opaque or in other words - half transparent. // The range is 0-1. myDropShadowEffect.Opacity = 0.4; // Apply the effect to the Button. // listImage.Effect = myDropShadowEffect; newListBox.Effect = myDropShadowEffect; listImage.TouchUp += list1_TouchUp; //TouchUp时才能被选中 newListBox.Content = br; newListBox.Margin = new System.Windows.Thickness((int)10); list1.Items.Add(newListBox); } } private void canvas_ManipulationDelta(object sender, ManipulationDeltaEventArgs e) { FrameworkElement element = (FrameworkElement)e.Source; Matrix matrix = ((MatrixTransform)element.RenderTransform).Matrix; ManipulationDelta deltaManipulation = e.DeltaManipulation; Point center = new Point(element.ActualWidth / 2, element.ActualHeight / 2); center = matrix.Transform(center); matrix.ScaleAt(deltaManipulation.Scale.X, deltaManipulation.Scale.Y, center.X, center.Y); matrix.RotateAt(e.DeltaManipulation.Rotation, center.X, center.Y); matrix.Translate(e.DeltaManipulation.Translation.X, e.DeltaManipulation.Translation.Y); ((MatrixTransform)element.RenderTransform).Matrix = matrix; } private void list1_TouchUp(object sender, TouchEventArgs e) { if (list1.SelectedIndex >= 0) { BitmapImage bitmapImage = new BitmapImage(); bitmapImage.BeginInit(); bitmapImage.UriSource = new Uri(Environment.CurrentDirectory + "//Image//" + newArrayList[list1.SelectedIndex].ToString()); bitmapImage.EndInit(); canvasImage.Source = bitmapImage; canvasImage.Width = 300; canvasImage.Height = 300; canvasImage.IsManipulationEnabled = true; canvasImage.RenderTransform = new MatrixTransform(); Canvas.SetTop(canvasImage, 200); Canvas.SetLeft(canvasImage, 700); if (!state) { canvas.Children.Add(canvasImage); state = true; } } } private void canvas_ManipulationStarting(object sender, ManipulationStartingEventArgs e) { e.ManipulationContainer = canvas; e.Mode = ManipulationModes.All; } private void canvas_MouseDown(object sender, MouseButtonEventArgs e) { if (e.ClickCount == 2) { canvas.Children.Remove(canvasImage); state = false; } } private void list1_TouchMove(object sender, TouchEventArgs e) { this.scrolls.PanningMode = PanningMode.HorizontalOnly; this.scrolls.CanContentScroll = false; } private void list1_TouchEnter(object sender, TouchEventArgs e) { if (list1.SelectedIndex >= 0) { BitmapImage bitmapImage = new BitmapImage(); bitmapImage.BeginInit(); bitmapImage.UriSource = new Uri(Environment.CurrentDirectory + "//Image//" + newArrayList[list1.SelectedIndex].ToString()); bitmapImage.EndInit(); canvasImage.Source = bitmapImage; canvasImage.Width = 300; canvasImage.Height = 300; canvasImage.IsManipulationEnabled = true; canvasImage.RenderTransform = new MatrixTransform(); Canvas.SetTop(canvasImage, 200); Canvas.SetLeft(canvasImage, 700); if (!state) { canvas.Children.Add(canvasImage); state = true; } } } private void list1_MouseDoubleClick(object sender, MouseButtonEventArgs e) { if (list1.SelectedIndex >= 0) { BitmapImage bitmapImage = new BitmapImage(); bitmapImage.BeginInit(); bitmapImage.UriSource = new Uri(Environment.CurrentDirectory + "//Image//" + newArrayList[list1.SelectedIndex].ToString()); bitmapImage.EndInit(); canvasImage.Source = bitmapImage; canvasImage.Width = 300; canvasImage.Height = 300; //阴影效果 DropShadowEffect myDropShadowEffect = new DropShadowEffect(); // Set the color of the shadow to Black. Color myShadowColor = new Color(); myShadowColor.A = 255; // Note that the alpha value is ignored by Color property. // The Opacity property is used to control the alpha. myShadowColor.B = 50; myShadowColor.G = 50; myShadowColor.R = 50; myDropShadowEffect.Color = myShadowColor; // Set the direction of where the shadow is cast to 320 degrees. myDropShadowEffect.Direction = 310; // Set the depth of the shadow being cast. myDropShadowEffect.ShadowDepth = 25; // Set the shadow softness to the maximum (range of 0-1). myDropShadowEffect.BlurRadius = 13; // Set the shadow opacity to half opaque or in other words - half transparent. // The range is 0-1. myDropShadowEffect.Opacity = 0.4; // Apply the effect to the Button. // listImage.Effect = myDropShadowEffect; canvasImage.Effect = myDropShadowEffect; canvasImage.IsManipulationEnabled = true; canvasImage.RenderTransform = new MatrixTransform(); Canvas.SetTop(canvasImage, 200); Canvas.SetLeft(canvasImage, 700); if (!state) { canvas.Children.Add(canvasImage); state = true; } } } //private void list1_TouchLeave(object sender, TouchEventArgs e) //{ // if (list1.SelectedIndex >= 0) // { // BitmapImage bitmapImage = new BitmapImage(); // bitmapImage.BeginInit(); // bitmapImage.UriSource = new Uri(Environment.CurrentDirectory + "//Image//" + newArrayList[list1.SelectedIndex].ToString()); // bitmapImage.EndInit(); // canvasImage.Source = bitmapImage; // canvasImage.Width = 300; // canvasImage.Height = 300; // canvasImage.IsManipulationEnabled = true; // canvasImage.RenderTransform = new MatrixTransform(); // Canvas.SetTop(canvasImage, 200); // Canvas.SetLeft(canvasImage, 700); // if (!state) // { // canvas.Children.Add(canvasImage); // state = true; // } // } //} } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace TestCrawler_2 { class Program { static void Main(string[] args) { //**Os Arquivos estão em ~bin/Debug**// string fullText = File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "FullText.txt")); var indexes = new Regex(@"\D+").Split(fullText).Where(x => x != String.Empty); string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ResourceIT.txt"); TextWriter textWriter = new StreamWriter(path, true); string extractedText = ""; foreach (string index in indexes) { if (int.Parse(index) % 2 == 0) { extractedText = Regex.Match(fullText, $@"(?i){int.Parse(index) - 1} RESOURCE IT SOLUTIONS\s+(.+?)\s+{index} RESOURCE IT SOLUTIONS").Groups[1].Value; textWriter.WriteLine(extractedText); } } textWriter.Close(); } } }
 using UnityEngine; public class bullet : MonoBehaviour { public float speed = 20f; public Rigidbody rb; public Transform body; void Start() { rb.velocity = transform.right * speed; } void OnTriggerEnter(Collider hitInfo) { Debug.Log(hitInfo); Destroy(gameObject); } }
using System.Runtime.Serialization; using System.ServiceModel; using System.ServiceModel.Web; namespace JKMWCFService { /// <summary> /// Interface Name : IMove /// Author : Ranjana Singh /// Creation Date : 27 Nov 2017 /// Purpose : Contains all information of Move. /// Revision : /// </summary> /// <returns></returns> [ServiceContract] public interface IMove { [OperationContract] [WebInvoke(Method = "GET", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "/{moveID}")] string GetMoveData(string moveID); [OperationContract] [WebInvoke(Method = "GET", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "/{customerID}/move")] string GetMoveID(string customerID); [OperationContract] [WebInvoke(Method = "GET", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "/{moveID}/contact")] string GetContactForMove(string moveID); [OperationContract] [WebInvoke(Method = "GET", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "/list/{statusReason}")] string GetMoveList(string statusReason); [OperationContract] [WebInvoke(Method = "PUT", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "/{moveID}")] string PutMoveData(string moveID, MoveDetail moveDetail); } [DataContract] public class MoveDetail { [DataMember] public string StatusReason { get; set; } } }
using Contoso.Bsl.Business.Requests; using Contoso.Bsl.Business.Responses; using Contoso.Bsl.Flow; using Contoso.Domain.Entities; using Contoso.Repositories; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using System.Collections.Generic; using System.Linq; namespace Contoso.Bsl.Controllers { [Produces("application/json")] [Route("api/Student")] public class StudentController : Controller { private readonly IFlowManager flowManager; private readonly ISchoolRepository schoolRepository; private readonly ILogger<StudentController> logger; public StudentController(IFlowManager flowManager, ISchoolRepository schoolRepository, ILogger<StudentController> logger) { this.flowManager = flowManager; this.schoolRepository = schoolRepository; this.logger = logger; } [HttpPost("Delete")] public IActionResult Delete([FromBody] DeleteEntityRequest deleteStudentRequest) { this.flowManager.FlowDataCache.Request = deleteStudentRequest; this.flowManager.Start("deletestudent"); return Ok(this.flowManager.FlowDataCache.Response); } [HttpPost("Save")] public IActionResult Save([FromBody] SaveEntityRequest saveStudentRequest) { this.flowManager.FlowDataCache.Request = saveStudentRequest; this.flowManager.Start("savestudent"); return Ok(this.flowManager.FlowDataCache.Response); } [HttpPost("SaveWithoutRules")] public IActionResult SaveWithoutRules([FromBody] SaveEntityRequest saveStudentRequest) { System.Diagnostics.Stopwatch stopWatch = System.Diagnostics.Stopwatch.StartNew(); var response = SaveStudentWithoutRules(saveStudentRequest); stopWatch.Stop(); logger.LogWarning("this.SaveStudentWithoutRules: {0}", stopWatch.Elapsed.TotalMilliseconds); return Ok(response); } private SaveEntityResponse SaveStudentWithoutRules(SaveEntityRequest saveStudentRequest) { Domain.Entities.StudentModel studentModel = (StudentModel)saveStudentRequest.Entity; SaveEntityResponse saveStudentResponse = new SaveEntityResponse() { ErrorMessages = new List<string>() }; #region Validation if (string.IsNullOrWhiteSpace(studentModel.FirstName)) saveStudentResponse.ErrorMessages.Add("First Name is required."); if (string.IsNullOrWhiteSpace(studentModel.LastName)) saveStudentResponse.ErrorMessages.Add("Last Name is required."); if (studentModel.EnrollmentDate == default) saveStudentResponse.ErrorMessages.Add("Enrollment Date is required."); if (saveStudentResponse.ErrorMessages.Any()) { flowManager.CustomActions.WriteToLog("An error occurred saving the request."); saveStudentResponse.Success = false; return saveStudentResponse; } #endregion Validation #region Save and retrieve saveStudentResponse.Success = schoolRepository.SaveGraphAsync<Domain.Entities.StudentModel, Data.Entities.Student>(studentModel).Result; if (!saveStudentResponse.Success) return saveStudentResponse; studentModel = schoolRepository.GetAsync<Domain.Entities.StudentModel, Data.Entities.Student> ( f => f.ID == studentModel.ID, null, new LogicBuilder.Expressions.Utils.Expansions.SelectExpandDefinition { ExpandedItems = new List<LogicBuilder.Expressions.Utils.Expansions.SelectExpandItem> { new LogicBuilder.Expressions.Utils.Expansions.SelectExpandItem { MemberName = "enrollments" } } } ).Result.SingleOrDefault(); saveStudentResponse.Entity = studentModel; #endregion Save and retrieve #region Log Enrollments int Iteration_Index = 0; flowManager.CustomActions.WriteToLog ( string.Format ( "EnrollmentCount: {0}. Index: {1}", new object[] { studentModel.Enrollments.Count, Iteration_Index } ) ); Domain.Entities.EnrollmentModel enrollmentModel = null; while (Iteration_Index < studentModel.Enrollments.Count) { enrollmentModel = studentModel.Enrollments.ElementAt(Iteration_Index); Iteration_Index = Iteration_Index + 1; flowManager.CustomActions.WriteToLog ( string.Format ( "Student Id:{0} is enrolled in {1}.", new object[] { studentModel.ID, enrollmentModel.CourseTitle } ) ); } #endregion Log Enrollments return saveStudentResponse; } [HttpGet] public IEnumerable<string> Get() { return new string[] { "a", "b"}; } } }
using System; using System.Configuration; using System.Net; using System.Net.Mail; using System.Threading.Tasks; using Web.Interfaces; using Web.Models; namespace Web.Services { public class BasicMailService : IEmailService { private static readonly string BasicMailServer = ConfigurationManager.AppSettings["BasicMailServer"]; private static readonly string BasicMailUsername = ConfigurationManager.AppSettings["BasicMailUsername"]; private static readonly string BasicMailPassword = ConfigurationManager.AppSettings["BasicMailPassword"]; private static readonly bool BasicMailSsl = Convert.ToBoolean(ConfigurationManager.AppSettings["BasicMailSsl"]); private static readonly int BasicMailPort = Convert.ToInt32(ConfigurationManager.AppSettings["BasicMailPort"]); private static readonly string MailFrom = ConfigurationManager.AppSettings["MailFrom"]; private static readonly string BasicMailDisplayName = ConfigurationManager.AppSettings["BasicMailDisplayName"]; public Task SendAsync(MailMessage mailMessage) { // Configure mail client mailMessage.IsBodyHtml = true; if(mailMessage.From==null) mailMessage.From = new MailAddress(MailFrom, BasicMailDisplayName); //Log4NetHelper.Log("Will Send Mail to: " + mailMessage.To.First().Address, LogLevel.INFO, "BasicMailServices", 34, "tester", null); var mailClient = GetMailClient(); // Send mail try { mailClient.Send(mailMessage); } catch (Exception ex) { Log4NetHelper.Log("Send Mail Failed", LogLevel.ERROR, "MailMessages", 41, "tester", ex); } return Task.FromResult(0); } public Task SendAsync(string subject, string body, string to) { var mailMessage = new MailMessage { Body = body, Subject = subject, From = new MailAddress(ConfigurationManager.AppSettings["SiteMailAddress"]), IsBodyHtml = true }; var mailAddress = new MailAddress(to); mailMessage.To.Add(mailAddress); var mailClient = GetMailClient(); try { mailClient.Send(mailMessage); } catch (Exception ex) { Console.WriteLine(ex); } return Task.FromResult(0); } public Task SendAsync(string subject, string body, string to, bool copyPartners) { var mailMessage = new MailMessage { Body = body , Subject = subject, From = new MailAddress(ConfigurationManager.AppSettings["SiteMailAddress"]), IsBodyHtml=true }; var mailAddress = new MailAddress(to); mailMessage.To.Add(mailAddress); if (copyPartners) { mailMessage.To.Add("rogerswetnam@gmail.com"); } var mailClient = GetMailClient(); try { mailClient.Send(mailMessage); } catch (Exception ex) { Console.WriteLine(ex); } return Task.FromResult(0); } private static SmtpClient GetMailClient() { var mailClient = new SmtpClient(BasicMailServer) { UseDefaultCredentials = false, Credentials = new NetworkCredential(BasicMailUsername, BasicMailPassword), EnableSsl = BasicMailSsl, Port = BasicMailPort }; return mailClient; } public Task NotifyPartners(string subject, string body) { throw new NotImplementedException(); } public Task ProcessMail(int amountToSent) { throw new NotImplementedException(); } } }
/* * Copyright 2014 Technische Universität Darmstadt * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using EnvDTE; using JetBrains.Application; using JetBrains.Application.Threading; using KaVE.Commons.Model.Events.VisualStudio; using KaVE.Commons.Utils; using KaVE.Commons.Utils.Collections; using KaVE.RS.Commons.Utils; using KaVE.VS.Commons; using KaVE.VS.Commons.Generators; using KaVE.VS.Commons.Naming; namespace KaVE.VS.FeedbackGenerator.Generators.VisualStudio { [ShellComponent] public class WindowEventGenerator : EventGeneratorBase { private const int SignificantMoveDistanceLowerBound = 25; private const int WindowMoveTimeout = 200; private class WindowDescriptor { public int Top; public int Left; public int Width; public int Height; } private readonly ICallbackManager _callbackManager; private readonly IDateUtils _dateUtils; private readonly IDictionary<Window, WindowDescriptor> _knownWindows; private readonly IDictionary<Window, WindowEvent> _delayedMoveEvents; private readonly IDictionary<Window, ScheduledAction> _delayedMoveEventFireActions; // ReSharper disable once PrivateFieldCanBeConvertedToLocalVariable private readonly WindowEvents _windowEvents; public WindowEventGenerator(IRSEnv env, IMessageBus messageBus, ICallbackManager callbackManager, IDateUtils dateUtils, IThreading threading) : base(env, messageBus, dateUtils, threading) { _callbackManager = callbackManager; _knownWindows = new Dictionary<Window, WindowDescriptor>(); _delayedMoveEvents = new Dictionary<Window, WindowEvent>(); _delayedMoveEventFireActions = new ThreadSafeDictionary<Window, ScheduledAction>(name => ScheduledAction.NoOp); _dateUtils = dateUtils; _windowEvents = DTE.Events.WindowEvents; _windowEvents.WindowCreated += OnWindowCreated; _windowEvents.WindowActivated += OnWindowActivated; _windowEvents.WindowMoved += OnWindowMoved; _windowEvents.WindowClosing += OnWindowClosed; } private void OnWindowCreated(Window window) { RememberWindow(window); Fire(window, WindowAction.Create); } private void OnWindowActivated(Window window, Window lostFocus) { RememberWindow(window); Fire(window, WindowAction.Activate); // We don't fire lostFocus events, since we track the active window in every event and know that the // previously active window looses the focus whenever some other window gains it. } private void OnWindowMoved(Window window, int top, int left, int width, int height) { if (IsUnknownWindow(window)) { // If the window is unknown, we don't know how much its position or size changed. Therefore, we // ignore the current event, but remember the window for subsequent move events. RememberWindow(window); } else if (IsMovedSignificantly(window)) { // Insignificant moves are frequently caused by rerendering. To avoid bloating the event stream, we // only handle significant moves here. Most real moves start with a number of insignificant events, // followed by a number of significant ones. UpdateAndScheduleEvent(window); RememberWindow(window); } } private bool IsUnknownWindow(Window window) { return !_knownWindows.ContainsKey(window); } private void RememberWindow(Window window) { _knownWindows[window] = CreateDescriptor(window); } private static WindowDescriptor CreateDescriptor(Window window) { return new WindowDescriptor { Top = window.Top, Left = window.Left, Width = window.Width, Height = window.Height }; } private bool IsMovedSignificantly(Window window) { var knownWindow = _knownWindows[window]; var diffHeight = Math.Abs(knownWindow.Height - window.Height); var diffWidth = Math.Abs(knownWindow.Width - window.Width); var downwards = Math.Abs(knownWindow.Top - window.Top); var leftwards = Math.Abs(knownWindow.Left - window.Left); return downwards > SignificantMoveDistanceLowerBound || leftwards > SignificantMoveDistanceLowerBound || diffHeight > SignificantMoveDistanceLowerBound || diffWidth > SignificantMoveDistanceLowerBound; } private void UpdateAndScheduleEvent(Window window) { _delayedMoveEventFireActions[window].Cancel(); lock (_delayedMoveEvents) { if (!_delayedMoveEvents.ContainsKey(window)) { _delayedMoveEvents[window] = CreateWindowEvent(window, WindowAction.Move); } _delayedMoveEvents[window].TerminatedAt = _dateUtils.Now; _delayedMoveEventFireActions[window] = _callbackManager.RegisterCallback( () => FireDelayedMoveEvent(window), WindowMoveTimeout); } } private void FireDelayedMoveEvent(Window window) { lock (_delayedMoveEvents) { Fire(_delayedMoveEvents[window]); _delayedMoveEvents.Remove(window); } } private void OnWindowClosed(Window window) { Fire(window, WindowAction.Close); } private void Fire(Window window, WindowAction action) { var windowEvent = CreateWindowEvent(window, action); FireNow(windowEvent); } private WindowEvent CreateWindowEvent(Window window, WindowAction action) { var windowEvent = Create<WindowEvent>(); windowEvent.Window = window.GetName(); windowEvent.Action = action; return windowEvent; } } }
using Terraria.ModLoader; namespace TutorialMod { public class TutorialMod : Mod { public TutorialMod() { } } }
using System; using System.Collections.Generic; using System.Windows.Forms; namespace DiffusionWindowsFormsApp { public partial class DiffusionForm : Form { List<RedMolecule> redBalls = new List<RedMolecule>(); List<BlackMolecule> blackBalls = new List<BlackMolecule>(); private int redBallsCount = 10; private int blackBallsCount = 10; private int redBallsOnLeft; private int redBallsOnRight; private int blackBallsOnLeft; private int blackBallsOnRight; public DiffusionForm() { InitializeComponent(); } private void DiffusionForm_Load(object sender, EventArgs e) { for (int i = 0; i < redBallsCount; i++) { var redMolecule = new RedMolecule(this); redBalls.Add(redMolecule); redMolecule.Start(); } for (int i = 0; i < blackBallsCount; i++) { var blackMolecule = new BlackMolecule(this); blackBalls.Add(blackMolecule); blackMolecule.Start(); } diffusionTimer.Start(); } private void DiffusionForm_MouseClick(object sender, MouseEventArgs e) { for (int i = 0; i < redBalls.Count; i++) { if (redBalls[i].IsMoving()) { redBalls[i].Stop(); } else { redBalls[i].Start(); } } for (int i = 0; i < blackBalls.Count; i++) { if (blackBalls[i].IsMoving()) { blackBalls[i].Stop(); } else { blackBalls[i].Start(); } } } private void diffusionTimer_Tick(object sender, EventArgs e) { CheckForEqualNumber(); } private void CheckForEqualNumber() { redBallsOnLeft = 0; redBallsOnRight = 0; blackBallsOnLeft = 0; blackBallsOnRight = 0; for (int i = 0; i < redBalls.Count; i++) { if (redBalls[i].OnLeftHalfForm()) { redBallsOnLeft++; } if (blackBalls[i].OnLeftHalfForm()) { blackBallsOnLeft++; } if (redBalls[i].OnRightHalfForm()) { redBallsOnRight++; } if (blackBalls[i].OnRightHalfForm()) { blackBallsOnRight++; } } if (EqualAmount()) { for (int i = 0; i < redBalls.Count; i++) { redBalls[i].Stop(); } for (int i = 0; i < blackBalls.Count; i++) { blackBalls[i].Stop(); } } } public bool EqualAmount() { return blackBallsOnLeft == blackBalls.Count / 2 && blackBallsOnRight == blackBalls.Count / 2 && redBallsOnLeft == redBalls.Count / 2 && redBallsOnRight == redBalls.Count / 2; } } }
using System; using Xunit; using BinaryTreeBalanced.Classes; namespace BinaryTreeBalancedTDD { public class UnitTest1 { [Fact] public void BalancedTrueTest1() { BinaryTree tree = new BinaryTree(); tree.Root = new Node(1); Assert.True(tree.IsBinaryTreeBalanced(tree.Root)); } [Fact] public void BalancedTrueTest2() { BinaryTree tree = new BinaryTree(); tree.Root = new Node(1); tree.Root.LeftChild = new Node(2); tree.Root.RightChild = new Node(3); Assert.True(tree.IsBinaryTreeBalanced(tree.Root)); } [Fact] public void BalancedTrueTest3() { BinaryTree tree = new BinaryTree(); tree.Root = new Node(1); tree.Root.LeftChild = new Node(2); tree.Root.RightChild = new Node(3); tree.Root.LeftChild.RightChild = new Node(4); tree.Root.LeftChild.LeftChild = new Node(5); tree.Root.RightChild.RightChild = new Node(6); tree.Root.RightChild.LeftChild = new Node(7); tree.Root.LeftChild.LeftChild.LeftChild = new Node(8); tree.Root.RightChild.LeftChild.LeftChild = new Node(9); Assert.True(tree.IsBinaryTreeBalanced(tree.Root)); } [Fact] public void BalancedFalseTest1() { BinaryTree tree = new BinaryTree(); tree.Root = new Node(1); tree.Root.RightChild = new Node(2); tree.Root.RightChild.RightChild = new Node(3); Assert.False(tree.IsBinaryTreeBalanced(tree.Root)); } [Fact] public void BalancedFalseTest2() { BinaryTree tree = new BinaryTree(); tree.Root = new Node(1); tree.Root.LeftChild = new Node(2); tree.Root.RightChild = new Node(3); tree.Root.LeftChild.LeftChild = new Node(4); tree.Root.LeftChild.LeftChild.RightChild = new Node(5); Assert.False(tree.IsBinaryTreeBalanced(tree.Root)); } [Fact] public void BalancedFalseTest3() { BinaryTree tree = new BinaryTree(); tree.Root = new Node(1); tree.Root.LeftChild = new Node(2); tree.Root.RightChild = new Node(3); tree.Root.LeftChild.RightChild = new Node(4); tree.Root.LeftChild.LeftChild = new Node(5); tree.Root.RightChild.RightChild = new Node(6); tree.Root.RightChild.LeftChild = new Node(7); tree.Root.LeftChild.LeftChild.LeftChild = new Node(8); tree.Root.LeftChild.LeftChild.LeftChild.LeftChild = new Node(9); Assert.False(tree.IsBinaryTreeBalanced(tree.Root)); } } }
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Security.Cryptography.X509Certificates; using System.Threading.Tasks; namespace MockTwitterAPI.Models { public class AuthModel { public AuthModel() { } public static int validToken(User user, string idToken) { if(idToken == null || user == null) { return StatusCodes.Status400BadRequest; } if(idToken != user.IdToken) { return StatusCodes.Status401Unauthorized; } TimeSpan exp = new TimeSpan(0, user.TokenExpiresIn, 0); // expired. if (user.LastAuthed.Add(exp) < DateTime.Now) { return StatusCodes.Status401Unauthorized; } return StatusCodes.Status200OK; } } }
namespace doob.Scripter.Shared { public interface IScripterModule { } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics; using UnityEngine; namespace FPSAdjuster { public class FPSAdjuster { public int Fps { get; set; } // 直前の時間 private double _lastTick; private Stopwatch _watch; public void Start() { _watch = new Stopwatch(); _lastTick = 0; _watch.Start(); } public void Adjust() { // 重みを求める(1000 / fpsを求める) double weight = 1000.0 / Fps; double timeNow = _watch.Elapsed.TotalMilliseconds; while (timeNow < _lastTick + weight) { // 気休め程度に待つ、ここは適した処理を書く System.Threading.Thread.Sleep(0); timeNow = _watch.Elapsed.TotalMilliseconds; } _lastTick = timeNow; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Lab2N8 { public partial class Search : Form { string[] text; char[] separators = { ' ', ',', '.', ':', ';', '-', '—', '–', '!', '?', '\n', '\r'}; public Search() { InitializeComponent(); } public Search(string txt) { InitializeComponent(); text = txt.Split(separators, StringSplitOptions.RemoveEmptyEntries); } private void buttonFind_Click(object sender, EventArgs e) { string[] line = textBoxWord.Text.Split(separators, StringSplitOptions.RemoveEmptyEntries); if (line.Length == 0) { MessageBox.Show("Некорректное слово!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } else if (line.Length > 1) { MessageBox.Show("Несколько слов!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } string word = line[0]; List<KeyValuePair<string, int>> words = new List<KeyValuePair<string, int>>(); foreach(string w in text) words.Add(new KeyValuePair<string, int>(w, CombinatorialAlgorithms.LevenshteinDistance(word, w))); words.Distinct(); words.Sort((a, b) => a.Value.CompareTo(b.Value)); textBoxResults.Clear(); foreach (var w in words) textBoxResults.Text += string.Format("{0} ({1}){2}", w.Key, w.Value, Environment.NewLine); } } }
using LogicBuilder.Attributes; namespace CheckMySymptoms.Flow { public interface ICustomActions { [AlsoKnownAs("AddSymptom")] void AddSymptom([ParameterEditorControl(ParameterControlType.MultipleLineTextBox)]string symptom); [AlsoKnownAs("AddDiagnosis")] void AddDiagnosis([ParameterEditorControl(ParameterControlType.MultipleLineTextBox)]string diagnosis); [AlsoKnownAs("AddTreatment")] void AddTreatment([ParameterEditorControl(ParameterControlType.MultipleLineTextBox)]string treatment); [AlsoKnownAs("SavePatientData")] void SavePatientData(); [AlsoKnownAs("GetPatientData")] void GetPatientData(); [AlsoKnownAs("ConvertToString")] string ConvertToString(object obj); } }
using System; using System.Data; using System.Configuration; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; /// <summary> /// Summary description for IUseable /// </summary> public interface IUseable { void Use(PlayerCharacter PC); }
using Microsoft.Owin; using ODataPOC; using ODataPOC.Security; using Owin; [assembly: OwinStartup(typeof (Startup))] namespace ODataPOC { public class Startup { public void Configuration(IAppBuilder app) { app.Use(typeof (AuthenticationMiddleware)); } } }
using Logic.Resource; using Logic.TechnologyClasses; using Moq; using NUnit.Framework; using System; namespace UnitTest4X { [TestFixture] public class ResearchQueueTest { [TestCase] public void Add_ResearchIsNull_ExceptionThrown() { Assert.Throws<ArgumentNullException>(() => new ResearchQueue().Add(null)); } [TestCase] public void Add_ResearchAddedMoreThanOnce_OnlyAddedOnce() { var queue = new ResearchQueue(); var research = new TechnologyResearcher(new EmptyTechnology(), new Resources(), 1); Assert.AreEqual(0, queue.BeingResearched); Assert.AreEqual(0, queue.WaitingInQueue); queue.Add(research); Assert.AreEqual(1, queue.BeingResearched); Assert.AreEqual(0, queue.WaitingInQueue); } [TestCase] public void Add_FourResearchesAdded_CorrectDisrtibution() { var queue = new ResearchQueue(); var researchOne = new TechnologyResearcher(new EmptyTechnology(), new Resources(), 1); var researchTwo = new TechnologyResearcher(new EmptyTechnology(), new Resources(), 1); var researchThree = new TechnologyResearcher(new EmptyTechnology(), new Resources(), 1); var researchFour = new TechnologyResearcher(new EmptyTechnology(), new Resources(), 1); Assert.AreEqual(0, queue.BeingResearched); Assert.AreEqual(0, queue.WaitingInQueue); queue.Add(researchOne); Assert.AreEqual(1, queue.BeingResearched); Assert.AreEqual(0, queue.WaitingInQueue); queue.Add(researchTwo); Assert.AreEqual(2, queue.BeingResearched); Assert.AreEqual(0, queue.WaitingInQueue); queue.Add(researchThree); Assert.AreEqual(3, queue.BeingResearched); Assert.AreEqual(0, queue.WaitingInQueue); queue.Add(researchFour); Assert.AreEqual(3, queue.BeingResearched); Assert.AreEqual(1, queue.WaitingInQueue); } } }
using System; using Microsoft.EntityFrameworkCore.Migrations; namespace Payroll.Data.Migrations { public partial class ManagerNullableDateBirthNullable : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey( name: "FK_Employee_Employee_ManagerId", table: "Employee"); migrationBuilder.AlterColumn<string>( name: "PhoneNumber", table: "Employee", nullable: false, oldClrType: typeof(string), oldNullable: true); migrationBuilder.AlterColumn<string>( name: "PersonalDocument", table: "Employee", nullable: false, oldClrType: typeof(string), oldNullable: true); migrationBuilder.AlterColumn<string>( name: "Nationality", table: "Employee", nullable: false, oldClrType: typeof(string), oldNullable: true); migrationBuilder.AlterColumn<Guid>( name: "ManagerId", table: "Employee", nullable: true, oldClrType: typeof(Guid)); migrationBuilder.AlterColumn<string>( name: "IDName", table: "Employee", nullable: false, oldClrType: typeof(string), oldNullable: true); migrationBuilder.AlterColumn<string>( name: "EmployeeNumber", table: "Employee", nullable: false, oldClrType: typeof(string), oldNullable: true); migrationBuilder.AddForeignKey( name: "FK_Employee_Employee_ManagerId", table: "Employee", column: "ManagerId", principalTable: "Employee", principalColumn: "Id", onDelete: ReferentialAction.Restrict); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey( name: "FK_Employee_Employee_ManagerId", table: "Employee"); migrationBuilder.AlterColumn<string>( name: "PhoneNumber", table: "Employee", nullable: true, oldClrType: typeof(string)); migrationBuilder.AlterColumn<string>( name: "PersonalDocument", table: "Employee", nullable: true, oldClrType: typeof(string)); migrationBuilder.AlterColumn<string>( name: "Nationality", table: "Employee", nullable: true, oldClrType: typeof(string)); migrationBuilder.AlterColumn<Guid>( name: "ManagerId", table: "Employee", nullable: false, oldClrType: typeof(Guid), oldNullable: true); migrationBuilder.AlterColumn<string>( name: "IDName", table: "Employee", nullable: true, oldClrType: typeof(string)); migrationBuilder.AlterColumn<string>( name: "EmployeeNumber", table: "Employee", nullable: true, oldClrType: typeof(string)); migrationBuilder.AddForeignKey( name: "FK_Employee_Employee_ManagerId", table: "Employee", column: "ManagerId", principalTable: "Employee", principalColumn: "Id", onDelete: ReferentialAction.Cascade); } } }
using Microsoft.Xna.Framework.Content; using ArmadaEngine.Scenes.Sagey.Managers; namespace ArmadaEngine.Scenes.Sagey.GameObjects.NPCs { public class Banker : NPC { public Banker(NPCManager nm) : base(nm) { AddMessages("OpenBank"); _Interactable = true; } public override void Interact() { base.Interact(); _NPCManager.PlayDialogue("OpenBank"); } } }
using UnityEngine; using System.Collections; namespace UMA { [System.Serializable] public class OverlayData : ScriptableObject { public string overlayName; [System.NonSerialized] public int listID; public Color color = new Color(1, 1, 1, 1); public Rect rect; public Texture2D[] textureList; public Color32[] channelMask; public Color32[] channelAdditiveMask; [System.NonSerialized] public UMAData umaData; /// <summary> /// Use this to identify what kind of overlay this is and what it fits /// Eg. BaseMeshSkin, BaseMeshOverlays, GenericPlateArmor01 /// </summary> public string[] tags; public OverlayData Duplicate() { OverlayData tempOverlay = CreateInstance<OverlayData>(); tempOverlay.overlayName = overlayName; tempOverlay.listID = listID; tempOverlay.color = color; tempOverlay.rect = rect; tempOverlay.textureList = new Texture2D[textureList.Length]; for (int i = 0; i < textureList.Length; i++) { tempOverlay.textureList[i] = textureList[i]; } return tempOverlay; } public OverlayData() { } public bool useAdvancedMasks { get { return channelMask != null && channelMask.Length > 0; } } public void SetColor(int channel, Color32 color) { if (useAdvancedMasks) { EnsureChannels(channel+1); channelMask[channel] = color; } else if (channel == 0) { this.color = color; } else { AllocateAdvancedMasks(); EnsureChannels(channel+1); channelMask[channel] = color; } if (umaData != null) { umaData.Dirty(false, true, false); } } public Color32 GetColor(int channel) { if (useAdvancedMasks) { EnsureChannels(channel + 1); return channelMask[channel]; } else if (channel == 0) { return this.color; } else { return new Color32(255, 255, 255, 255); } } public Color32 GetAdditive(int channel) { if (useAdvancedMasks) { EnsureChannels(channel + 1); return channelAdditiveMask[channel]; } else { return new Color32(0, 0, 0, 0); } } public void SetAdditive(int overlay, Color32 color) { if (!useAdvancedMasks) { AllocateAdvancedMasks(); } EnsureChannels(overlay+1); channelAdditiveMask[overlay] = color; if (umaData != null) { umaData.Dirty(false, true, false); } } private void AllocateAdvancedMasks() { int channels = umaData != null ? umaData.umaGenerator.textureNameList.Length : 2; EnsureChannels(channels); channelMask[0] = color; } public void CopyColors(OverlayData overlay) { if (overlay.useAdvancedMasks) { EnsureChannels(overlay.channelAdditiveMask.Length); for (int i = 0; i < overlay.channelAdditiveMask.Length; i++) { SetColor(i, overlay.GetColor(i)); SetAdditive(i, overlay.GetAdditive(i)); } } else { SetColor(0, overlay.color); } } public void EnsureChannels(int channels) { if (channelMask == null) { channelMask = new Color32[channels]; channelAdditiveMask = new Color32[channels]; for (int i = 0; i < channels; i++) { channelMask[i] = new Color32(255, 255, 255, 255); channelAdditiveMask[i] = new Color32(0, 0, 0, 0); } } else { if( channelMask.Length > channels ) return; var oldMask = channelMask; var oldAdditive = channelAdditiveMask; channelMask = new Color32[channels]; channelAdditiveMask = new Color32[channels]; for (int i = 0; i < channels; i++) { if (oldMask.Length > i) { channelMask[i] = oldMask[i]; channelAdditiveMask[i] = oldAdditive[i]; } else { channelMask[i] = new Color32(255, 255, 255, 255); channelAdditiveMask[i] = new Color32(0, 0, 0, 0); } } } } } }
namespace LSP._6_before { public class Square : Rectangle { public Square(int height, int width) : base(height, width) { } public override int Height { get => base.Height; set => base.Height = base.Width= value; } public override int Width { get => base.Width; set => base.Width = base.Height= value; } } }
using Microsoft.EntityFrameworkCore; using SampleDatabaseApp.Model; using SampleDatabaseApp.Model.Objects; using SampleDatabaseApp.Services.Interfaces; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SampleDatabaseApp.Services { public class OrderService : IOrderService { private readonly SampleDatabaseContext _context; public OrderService() { _context = SampleDatabaseContext.GetSampleDatabaseContext(); } public async Task<Order> Get(int id) { return await _context.Orders.SingleOrDefaultAsync(o => o.Id == id); } public async Task<Order> Add(Customer customer, Product product, int quantity) { Order order = new Order() { Id = default(int), CustomerId = customer.Id, ProductId = product.Id, Quantity = quantity, OrderDate = DateTime.UtcNow }; await _context.Orders.AddAsync(order); await _context.SaveChangesAsync(); return order; } public async Task<Order> Update(int id, Product product, int quantity) { Order order = await Get(id); if (order is null) { return null; } order.ProductId = product.Id; order.Quantity = quantity; _context.Orders.Update(order); await _context.SaveChangesAsync(); return order; } public async Task Delete(int id) { Order order = await Get(id); if (order is null) { return; } _context.Orders.Remove(order); await _context.SaveChangesAsync(); } public async Task<ICollection<Order>> GetAll() { return await _context.Orders.ToListAsync(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using MvcApplication2.Models; namespace MvcApplication2.Controllers { public class BaseController : Controller { // // GET: /Base/ public Database1Entities1 cx =new Database1Entities1(); public BaseController() { } } }
using System; namespace Casino { public class RandomSlots { public int oneTime = 0; private const int slotNumber = 3; private const int slotTypeNumber = 7; public Random random = new Random(); public int[] quantity = new int[3]; public int[] slots = new int[3]; public RandomSlots() { for(int i = 0; i < slotNumber; i++) { slots[i] = Randomize(slotTypeNumber); } } public int Randomize(int num) { return random.Next(0, num); } public int Bigger(int num) { int biggest; for(int i = 0; i < 3; i++) { quantity[i] = Randomize(num); } biggest = quantity[0]; for(int i = 1; i <= 2; i++) { if(biggest < quantity[i]) { biggest = quantity[i]; } } return biggest; } public void RollSlots() { oneTime++; for (int i = 0; i < slotNumber; i++) { if (quantity[i] >= oneTime) { slots[i]++; } } } } }
using System; using UnityEngine; namespace UnityUIPlayables { [Serializable] public class SliderAnimationValue { [SerializeField] private float _value; public float Value => _value; } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace MyCar.Models { public class Car { public int CarID { get; set; } public string CarName { get; set; } public DateTime AvailableDate { get; set; } public decimal Price { get; set; } } }
namespace Triton.Game.Mapping { using ns26; using System; [Attribute38("RotateOverTimePingPong")] public class RotateOverTimePingPong : MonoBehaviour { public RotateOverTimePingPong(IntPtr address) : this(address, "RotateOverTimePingPong") { } public RotateOverTimePingPong(IntPtr address, string className) : base(address, className) { } public void Start() { base.method_8("Start", Array.Empty<object>()); } public void Update() { base.method_8("Update", Array.Empty<object>()); } public bool RandomStartX { get { return base.method_2<bool>("RandomStartX"); } } public bool RandomStartY { get { return base.method_2<bool>("RandomStartY"); } } public bool RandomStartZ { get { return base.method_2<bool>("RandomStartZ"); } } public float RotateRangeXmax { get { return base.method_2<float>("RotateRangeXmax"); } } public float RotateRangeXmin { get { return base.method_2<float>("RotateRangeXmin"); } } public float RotateRangeYmax { get { return base.method_2<float>("RotateRangeYmax"); } } public float RotateRangeYmin { get { return base.method_2<float>("RotateRangeYmin"); } } public float RotateRangeZmax { get { return base.method_2<float>("RotateRangeZmax"); } } public float RotateRangeZmin { get { return base.method_2<float>("RotateRangeZmin"); } } public float RotateSpeedX { get { return base.method_2<float>("RotateSpeedX"); } } public float RotateSpeedY { get { return base.method_2<float>("RotateSpeedY"); } } public float RotateSpeedZ { get { return base.method_2<float>("RotateSpeedZ"); } } } }
#region Copyright Syncfusion Inc. 2001-2015. // Copyright Syncfusion Inc. 2001-2015. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // licensing@syncfusion.com. Any infringement will be prosecuted under // applicable laws. #endregion using System; #if __UNIFIED__ using UIKit; using Foundation; using CoreGraphics; using ObjCRuntime; #else using MonoTouch.UIKit; using MonoTouch.Foundation; using MonoTouch.CoreGraphics; using MonoTouch.ObjCRuntime; using CGRect = System.Drawing.RectangleF; using nint = System.Int32; using nuint = System.Int32; using nfloat = System.Single; #endif namespace SampleBrowser { public class SampleViewController: UIViewController { bool menuVisible; UIView fadeOutView; CGRect sampleFrame; UIBarButtonItem menuButton; UIBarButtonItem optionButton; public SampleViewController () { } public SampleView sample { get; set; } public NSString selectedControl { get; set; } public NSString selectedSample { get; set; } public UIView menuView { get; set; } public UIView optionView { get; set; } public UITableView menuTable { get; set; } public NSArray sampleArray { get; set; } public NSArray sampleDictionaryArray { get; set; } public override void ViewDidLoad () { this.View.BackgroundColor = UIColor.White; menuVisible = false; nfloat height = this.View.Bounds.Height - 64 - 49; nfloat left = this.View.Bounds.Width - 260; menuView = new UIView(new CGRect( left, 64, 260, height)); menuTable = new UITableView (new CGRect (0, 0, 260, height)); menuTable.Layer.BorderWidth = 0.5f; menuTable.Layer.BorderColor = (UIColor.FromRGBA (0.537f, 0.537f, 0.537f, 0.5f)).CGColor; menuTable.BackgroundColor = UIColor.White; menuTable.Source = new sampleDataSource (this) ; NSIndexPath indexPath = NSIndexPath.FromRowSection (0, 0); menuTable.SelectRow (indexPath, false, UITableViewScrollPosition.Top); menuView.AddSubview (menuTable); fadeOutView = new UIView(this.View.Bounds); fadeOutView.BackgroundColor = UIColor.FromRGBA( 0.537f ,0.537f,0.537f,0.3f); menuButton = new UIBarButtonItem(); menuButton.Image = UIImage.FromBundle ("Images/menu"); menuButton.Style = UIBarButtonItemStyle.Plain; menuButton.Target = this; menuButton.Clicked += OpenMenu; optionButton = new UIBarButtonItem (); optionButton.Image = UIImage.FromBundle ("Images/Option"); optionButton.Style = UIBarButtonItemStyle.Plain; optionButton.Target = this; optionButton.Clicked += OpenOptionView; UITapGestureRecognizer singleFingerTap = new UITapGestureRecognizer (); singleFingerTap.AddTarget(() => HandleSingleTap(singleFingerTap)); fadeOutView.AddGestureRecognizer (singleFingerTap); selectedSample = sampleArray.GetItem<NSString> (0); this.LoadSample (selectedSample); this.NavigationController.InteractivePopGestureRecognizer.Enabled = false; } public override void ViewWillDisappear (bool animated) { sample.dispose (); base.ViewWillDisappear (animated); } void HandleSingleTap (UITapGestureRecognizer gesture){ if(menuVisible){ menuVisible = false; HideMenu (); } } void OpenOptionView (object sender, EventArgs ea) { menuVisible = false; HideMenu (); OptionViewController optionController = new OptionViewController (); optionController.sampleView = sample; optionController.optionView = optionView; this.NavigationController.PushViewController (optionController, true); } void OpenMenu (object sender, EventArgs ea) { if (menuVisible) { menuVisible = false; HideMenu (); } else { menuVisible = true; this.View.AddSubview (fadeOutView); this.View.AddSubview (menuView); ShowMenu (); } } void ShowMenu() { menuView.Transform = CGAffineTransform.MakeScale (0, 1); menuView.Alpha = 0; UIView.Animate (0.25, () => { menuView.Alpha = 1; menuView.Transform = CGAffineTransform.MakeScale (1, 1); }); } void HideMenu() { menuView.Transform = CGAffineTransform.MakeScale(1,1); fadeOutView.RemoveFromSuperview (); UIView.AnimateNotify (0.25, () => { menuView.Alpha = 0; menuView.Transform = CGAffineTransform.MakeScale(0.001f,1); },(bool finished)=>{ if(finished) menuView.RemoveFromSuperview(); } ); } void LoadSample (NSString sampleName){ if(sample != null && sample.control.IsDescendantOfView(this.View)){ sample.control.RemoveFromSuperview (); sample.dispose (); } this.Title = sampleName; string classname = "SampleBrowser." + sampleName; if(sampleName == "100% Stacked Area") { classname = "SampleBrowser.StackingArea100"; } else if(sampleName == "100% Stacked Column") { classname = "SampleBrowser.StackingColumn100"; } else if(sampleName == "100% Stacked Bar") { classname = "SampleBrowser.StackingBar100"; } classname = classname.Replace (" ", ""); sampleFrame = new CGRect(this.View.Bounds.X, this.View.Bounds.Y + 66, this.View.Bounds.Width, this.View.Bounds.Height - 66 - 56); if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad && !(this.selectedControl.ToString()== "DataGrid") && !(this.selectedControl.ToString()== "NavigationDrawer") && !(this.selectedControl.ToString()== "Calendar")) { sampleFrame = new CGRect(this.View.Bounds.X + 100, this.View.Bounds.Y + 66 + 100, this.View.Bounds.Width - 200, this.View.Bounds.Height - 66 - 56 -200); } Type sampleClass = Type.GetType (classname); if (sampleClass != null) { sample = Activator.CreateInstance (sampleClass) as SampleView; sample.control.Frame = sampleFrame; optionView = sample.optionView (); this.NavigationItem.RightBarButtonItems = null; if (optionView != null) { optionView.Frame = sampleFrame; if (sampleArray.Count > 1) { this.NavigationItem.SetRightBarButtonItems (new UIBarButtonItem []{ menuButton, optionButton }, true); optionButton.ImageInsets= new UIEdgeInsets (0, 0, 0, -25); } else { this.NavigationItem.SetRightBarButtonItem (optionButton, true); } } else if (sampleArray.Count > 1){ this.NavigationItem.SetRightBarButtonItem (menuButton, true); } this.View.AddSubview (sample.control); } else if (sampleArray.Count > 1) { this.NavigationItem.SetRightBarButtonItem (menuButton, true); } } class sampleDataSource:UITableViewSource { readonly SampleViewController controller; NSArray sampleArray; NSDictionary sampleDict; NSArray sampleDictArray; public sampleDataSource (SampleViewController sampleControl) { this.controller = sampleControl; sampleArray = this.controller.sampleArray; sampleDictArray = this.controller.sampleDictionaryArray; } public override nint NumberOfSections (UITableView tableView) { return 1; } public override nint RowsInSection (UITableView tableview, nint section) { return (nint) this.controller.sampleArray.Count;; } public override string TitleForHeader (UITableView tableView, nint section) { return this.controller.selectedControl; } public override void RowSelected (UITableView tableView, NSIndexPath indexPath) { nuint row = (nuint)indexPath.Row; NSString selectedSample = sampleArray.GetItem<NSString> (row); // Load selected sample this.controller.LoadSample(selectedSample); this.controller.menuVisible = false; this.controller.HideMenu (); } public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) { var cell = tableView.DequeueReusableCell (SampleTableViewCell.Key) as SampleTableViewCell; if (cell == null) cell = new SampleTableViewCell (); // Configure the cell... nuint row = (nuint)indexPath.Row; NSString sampleName = sampleArray.GetItem<NSString> (row); cell.TextLabel.Text = sampleName; sampleDict = sampleDictArray.GetItem<NSDictionary>(row); if (sampleDict.ValueForKey (new NSString ("SampleName")).ToString () == sampleName) { if (sampleDict.ValueForKey (new NSString ("IsNew")).ToString () == "YES") { cell.DetailTextLabel.Text = "NEW"; cell.DetailTextLabel.TextColor = UIColor.FromRGB (148, 75, 157); } else if (sampleDict.ValueForKey (new NSString ("IsUpdated")).ToString () == "YES") { cell.DetailTextLabel.Text = "UPDATED"; cell.DetailTextLabel.TextColor = UIColor.FromRGB (148, 75, 157); } else { cell.DetailTextLabel.Text = null; } } cell.Accessory = UITableViewCellAccessory.None; return cell; } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.XR.ARFoundation; //using UnityEngine.Experimental.XR; using UnityEngine.XR.ARSubsystems; using System; public class ARTracking : MonoBehaviour { public GameObject skeleton; private Vector3 cameraPos; void start() { cameraPos = transform.position; } void update() { skeleton.transform.LookAt(cameraPos); } }
//namespace LearningSignalR.BackEnd.ViewModels.Account //{ // public class ExternalLoginListViewModel // { // public string ReturnUrl { get; set; } // } //}
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Media; namespace Test { public class MapManager { private TileMap myMap; private readonly Texture2D texture; private int squaresAcross; private int squaresDown; private int CellWidth = Tile.TileWidth ; private int CellHeight = Tile.TileHeight ; public MapManager(Texture2D texture, int squaresAcross, int squaresDown) { this.texture = texture; Tile.TileSetTexture = texture; this.squaresAcross = squaresAcross; this.squaresDown = squaresDown; myMap = new TileMap(texture); } internal void Update(GameTime gameTime) { updateMapTileType(); } public int SquaresAcross { get { return squaresAcross; } set { this.squaresAcross = value; } } public int SquaresDown { get { return squaresDown; } set { this.squaresDown = value; } } public TileMap MyMap { get { return myMap; } } private int TileSetRow(int TileIndex) { return TileIndex / (texture.Width / Tile.TileWidth); } private int TileSetColumn(int TileIndex) { return TileIndex % (texture.Width / Tile.TileWidth); } private int TileSetIndex(int TileRow, int TileColumn) { return TileRow * (texture.Width / Tile.TileWidth) + TileColumn; } private void updateMapTileType() { for (int y = 0; y < squaresDown; y++) { for (int x = 0; x < squaresAcross; x++) { foreach (int tileID in myMap.Rows[y].Columns[x].BaseTiles) { int row = TileSetRow(tileID); if (row == 0) { myMap.Rows[y].Columns[x].tileType = TileType.block; } else if (row == 1) { myMap.Rows[y].Columns[x].tileType = TileType.floorBotUp45; } else if (row == 2) { myMap.Rows[y].Columns[x].tileType = TileType.floorTopDown45; } else if (row == 3) { myMap.Rows[y].Columns[x].tileType = TileType.floorBotMid30; } else if (row == 4) { myMap.Rows[y].Columns[x].tileType = TileType.floorMidUp30; } else if (row == 5) { myMap.Rows[y].Columns[x].tileType = TileType.floorMidDown30; } else if (row == 6) { myMap.Rows[y].Columns[x].tileType = TileType.floorTopMid30; } else if (row == 7) { myMap.Rows[y].Columns[x].tileType = TileType.roofTopDown45; } else if (row == 8) { myMap.Rows[y].Columns[x].tileType = TileType.roofBotUp45; } else if (row == 9) { myMap.Rows[y].Columns[x].tileType = TileType.roofTopMid30; } else if (row == 10) { myMap.Rows[y].Columns[x].tileType = TileType.roofMidDown30; } else if (row == 11) { myMap.Rows[y].Columns[x].tileType = TileType.roofMidUp30; } else if (row == 12) { myMap.Rows[y].Columns[x].tileType = TileType.roofBotMid30; } else if (row == 13) { myMap.Rows[y].Columns[x].tileType = TileType.halfBlock; } else if (row == 14) { myMap.Rows[y].Columns[x].tileType = TileType.ladderVerti; } else if (row == 15) { myMap.Rows[y].Columns[x].tileType = TileType.ladderHori; } else if (row == 16) { myMap.Rows[y].Columns[x].tileType = TileType.decorationBack; } else if (row == 17) { myMap.Rows[y].Columns[x].tileType = TileType.decorationFront; } else if (row == 18) { myMap.Rows[y].Columns[x].tileType = TileType.mortal; } } } } } public void Draw(SpriteBatch spriteBatch) { for (int y = 0; y < squaresDown; y++) { for (int x = 0; x < squaresAcross; x++) { foreach (int tileID in myMap.Rows[y].Columns[x].BaseTiles) { if (myMap.Rows[y].Columns[x].Drawable) { spriteBatch.Draw(Tile.TileSetTexture, new Rectangle((x * CellWidth), (y * CellHeight), CellWidth, CellHeight), Tile.GetSourceRectangle(tileID), Color.White); } } } } } } }
using System; using System.IO; using UnityEngine; namespace UnityExtensions.DB { public class DatabaseManager { #region Attributes private static DatabaseManager m_instance; private static readonly object m_lock = new object(); #endregion Attributes #region Methods #region Accessors and Mutators //_____________________________________________________________________ ACCESSORS AND MUTATORS _____________________________________________________________________ public static DatabaseManager instance { get { lock (m_lock) { if (m_instance == null) { m_instance = new DatabaseManager(Application.dataPath + "/Databases/localization.db", Application.dataPath + "/Databases/user.db"); } return m_instance; } } } public SQLiteDatabase localizationDatabase { get; private set; } public SQLiteDatabase userDatabase { get; private set; } #endregion Accessors and Mutators #region Inherited Methods //_______________________________________________________________________ INHERITED METHODS _______________________________________________________________________ public DatabaseManager(string localizationDatabaseFilePath, string userDatabaseFilePath) { if (!File.Exists(localizationDatabaseFilePath) || !File.Exists(userDatabaseFilePath)) throw new Exception("One (or all) of the databases files are missing."); localizationDatabase = new SQLiteDatabase(localizationDatabaseFilePath); userDatabase = new SQLiteDatabase(userDatabaseFilePath); } #endregion Inherited Methods #region Events //_____________________________________________________________________________ EVENTS _____________________________________________________________________________ #endregion Events #region Other Methods //__________________________________________________________________________ OTHER METHODS _________________________________________________________________________ #endregion Other Methods #endregion Methods } }
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace TrackingServiceAlejo.Model { public class Location { public string Type { get; set; } public Geometry Geometry { get; set; } public Properties Properties { get; set; } } }
using System; using System.Threading.Tasks; using Acme.Core.Models; using Acme.Core.Repositories; using Acme.Core.Settings; using Acme.Infrastructure.Cache; namespace Acme.Data.Repositories.Cache { public class MerchantCacheRepository : IMerchantRepository { private readonly IMerchantRepository _merchantRepository; private readonly ICacheService _cacheService; private readonly MerchantCacheSettings _merchantCacheSettings; public MerchantCacheRepository(IMerchantRepository merchantRepository, ICacheService cacheService, MerchantCacheSettings merchantCacheSettings) { this._merchantRepository = merchantRepository; this._cacheService = cacheService; this._merchantCacheSettings = merchantCacheSettings; } public async Task<Merchant> GetByIdAsync(string id) { if (this._merchantCacheSettings.IsEnabled == false) { return await this._merchantRepository.GetByIdAsync(id); } string cacheKey = $"merchant_{id}"; var merchant = await this._cacheService.GetAsync<Merchant>(cacheKey); if (merchant != null) { return merchant; } merchant = await this._merchantRepository.GetByIdAsync(id); if (merchant == null) return null; var cacheExpiration = DateTimeOffset.UtcNow.AddMinutes(this._merchantCacheSettings.CacheExpirationInMinutes); await this._cacheService.SetAsync(cacheKey, merchant, cacheExpiration); return merchant; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using SkiaSharp; namespace GameLib { public static class Helper { public static Texture2D GetTexture2DFromPath(string path, GraphicsDevice graphicsDevice) { return ToTexture2D(GetBitmapFromPath(path), graphicsDevice); } public static SKBitmap GetBitmapFromPath(string path) { if (GameContext.Instance.Platform == Platform.Android) { using (var stream = GameContext.Instance.Assets.Open(path)) using (SKStream managed = new SKMemoryStream(GetBytesFromStream(stream))) { return SKBitmap.Decode(managed); } } using (var stream = new FileStream(path, FileMode.Open)) { return GetBitmapFromStream(stream); } } private static SKBitmap GetBitmapFromStream(Stream stream) { using (var managedStream = new SKManagedStream(stream)) { return SKBitmap.Decode(managedStream); } } /// <summary> /// Convertes the created TextureMap as a <see cref="Texture2D"/> /// </summary> /// <param name="bitmap"></param> /// <param name="graphicsDevice">The <see cref="GraphicsDevice"/> </param> /// <returns></returns> public static Texture2D ToTexture2D(this SKBitmap bitmap, GraphicsDevice graphicsDevice) { using (var image = SKImage.FromBitmap(bitmap)) { using (var data = image.Encode(SKEncodedImageFormat.Png, 100)) { using (var stream = new MemoryStream()) { data.SaveTo(stream); stream.Seek(0, SeekOrigin.Begin); return Texture2D.FromStream(graphicsDevice, stream); } } } } public static byte[] GetBytesFromStream(Stream baseStream) { var buffer = new byte[16 * 1024]; using (var ms = new MemoryStream()) { int read; while ((read = baseStream.Read(buffer, 0, buffer.Length)) > 0) { ms.Write(buffer, 0, read); } return ms.ToArray(); } } public static byte[] GetBytesFromFile(string path) { if (GameContext.Instance.Platform == Platform.Android) { using (var stream = GameContext.Instance.Assets.Open(path)) return GetBytesFromStream(stream); } using (var stream = new FileStream(path, FileMode.Open)) { return GetBytesFromStream(stream); } } public static TimeSpan Multiply(this TimeSpan first, float second) { return new TimeSpan((long)(first.Ticks * second)); } public static int ArrayMin(IEnumerable<int> data) { return data.Concat(new[] { int.MaxValue }).Min(); } public static int ArrayMax(IEnumerable<int> data) { return data.Concat(new[] { int.MinValue }).Max(); } public static float DistanceSquared(this Index2 first, Index2 second) { return (float)(Math.Pow(first.X - second.X, 2) + Math.Pow(first.Y - second.Y, 2)); } public static float DistanceSquared(this Vector2 first, Vector2 second) { return (float)(Math.Pow(first.X - second.X, 2) + Math.Pow(first.Y - second.Y, 2)); } public static bool NearlyEqual(this float first, float second, float tolerance = 0.001f) { return Math.Abs(first - second) < tolerance; } public static float DistanceSquared(this Vector3 first, Vector3 second) { return DistanceSquared(new Vector2(first.X, first.Y), new Vector2(second.X, second.Y)) + (float)Math.Pow(first.Z - second.Z, 2); } public static Vector3 Abs(this Vector3 first) { return new Vector3(Math.Abs(first.X), Math.Abs(first.Y), Math.Abs(first.Z)); } public static Vector2 Abs(this Vector2 first) { return new Vector2(Math.Abs(first.X), Math.Abs(first.Y)); } } }
using HtmlAgilityPack; using System; using System.Linq; namespace AgilityPackTest { class Program { static void Main(string[] args) { var oldHtml = @"https://www.centracare.com/providers/profile/sarah-abdul-jabbar"; HtmlWeb oldWeb = new HtmlWeb(); var oldHtmlDoc = oldWeb.Load(oldHtml); //var newHtml = @"http://centracare.scorpionwebsite.com/doctors/sarah-abdul-jabbar-mbbs/"; var newHtml = @"http://centracare.scorpionwebsite.com/doctors/oluyemi-a-ajayi-mbbs/"; HtmlWeb newWeb = new HtmlWeb(); var newHtmlDoc = newWeb.Load(newHtml); int score = 0; //var node = oldHtmlDoc.DocumentNode.SelectSingleNode("//body/main"); var oldNode = oldHtmlDoc.DocumentNode.SelectSingleNode("//h1").InnerText; var newNode = newHtmlDoc.DocumentNode.SelectSingleNode("//h1").InnerText; var oldText = getText(oldNode); var newText = getText(newNode); Console.WriteLine(oldText== newText); if (oldText == newText) score++; else score--; Console.WriteLine($"score: {score}"); Console.WriteLine("Hello World!"); } static string getText(string node) { return System.Text.RegularExpressions.Regex.Replace((node.Trim()), @"\s+", " "); } } }
using AspNetCore.Identity.MongoDB; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Sample.Models { public class ApplicationUser : MongoIdentityUser { } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TQVaultAE.GUI.Components { // Inspired from https://stackoverflow.com/questions/33776387/dont-raise-textchanged-while-continuous-typing public class TypeAssistant : Component { System.Threading.Timer waitingTimer; public event EventHandler Idled = delegate { }; [DefaultValue(1000)] public int WaitingMilliSeconds { get; set; } = 1000; public TypeAssistant() { waitingTimer = new System.Threading.Timer(p => { Idled(this, EventArgs.Empty); }); } public void TextChanged() => waitingTimer.Change(WaitingMilliSeconds, System.Threading.Timeout.Infinite); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DungeonGame { class Collision { /// <summary> /// Checks whether or not the hero is touching a border or wall. /// </summary> /// <param name="heroX"></param> /// <param name="heroY"></param> /// <param name="walls"></param> /// <returns></returns> public bool checkHeroWall(Attributes hero, IList<IList<Obstacles>> walls, int borderX, int borderY) { // Checks if Hero is touching a wall (not border) for (int i = 0; i < walls.Count; i++) { for(int j = 0; j < walls[i].Count; j++) if (hero.X.Equals(walls[i][j].X) && hero.Y.Equals(walls[i][j].Y) || hero.X.Equals(walls[i][j].X2) && hero.Y.Equals(walls[i][j].Y)) return true; } // Checks Top border for(int i = 0; i < (borderX + 5); i++) { if (hero.X.Equals(i) && hero.Y.Equals(5)) // I don't like hardcoding 5 return true; } // Checks Bottom border for (int i = 0; i < (borderX + 5); i++) { if (hero.X.Equals(i) && hero.Y.Equals(borderY + 4)) // I don't like hardcoding 4. return true; } // Checks Left border for (int i = 0; i < (borderY + 5); i++) { if (hero.X.Equals(5) && hero.Y.Equals(i)) // I don't like hardcoding 5. return true; } // Checks Right border for (int i = 0; i < (borderY + 5); i++) { if (hero.X.Equals(borderX + 5) && hero.Y.Equals(i)) // I don't like hardcoding 5. return true; } return false; } /// <summary> /// Checks if a monster and hero are on the same X Y position. /// If so it returns true. This will start a battle. /// At the moment it just returns true which takes 1 life away from the hero. /// </summary> /// <param name="monster"></param> /// <param name="heroX"></param> /// <param name="heroY"></param> /// <returns></returns> public bool CheckHeroMon(IList<Attributes> monster, Attributes hero) { for (int i = 0; i < monster.Count; i++) { if (hero.X.Equals(monster[i].X) && hero.Y.Equals(monster[i].Y)) return true; } return false; } /// <summary> /// Checks to see if the monster is at the same position a the wall. /// If the monster is at the same position as a wall, the monster can't pass. /// </summary> /// <param name="monster"></param> /// <param name="heroX"></param> /// <param name="heroY"></param> /// <param name="walls"></param> /// <param name="borderX"></param> /// <param name="borderY"></param> /// <returns></returns> public bool checkMonsterWall(IList<Attributes> monster, IList<IList<Obstacles>> walls, int borderX, int borderY) { // Checks Top Border for (int i = 0; i < (borderX + 5); i++) { for(int j = 0; j < monster.Count; j++) if (monster[j].X.Equals(i) && monster[j].Equals(5)) // I don't like hardcoding 5 return true; } // Checks Bottom Border for (int i = 0; i < (borderX + 5); i++) { for (int j = 0; j < monster.Count; j++) if (monster[j].X.Equals(i) && monster[j].Equals(borderY + 4)) return true; } // Checks Left border for (int i = 0; i < (borderY + 5); i++) { for (int j = 0; j < monster.Count; j++) if (monster[j].X.Equals(5) && monster[j].Equals(i)) return true; } // Checks Right border for (int i = 0; i < (borderY + 5); i++) { for (int j = 0; j < monster.Count; j++) if (monster[j].X.Equals(borderX + 5) && monster[j].Equals(i)) return true; } // Checks if a monster is touching another monster for (int i = 0; i < monster.Count; i++) { for(int j = 0; j < monster.Count - 1; j++) { if(i!=j) { if (monster[i].X.Equals(monster[j].X) && monster[i].Y.Equals(monster[j].Y)) return true; } } } // Checks if monster is touching a wall (not border) for (int i = 0; i < walls.Count; i++) { for (int j = 0; j < walls[i].Count; j++) { for (int k = 0; k < monster.Count; k++) { // Changed this TODO if (monster[k].X.Equals(walls[i][j].X) && monster[k].Y.Equals(walls[i][j].Y) || monster[k].X.Equals(walls[i][j].X2) && monster[k].Y.Equals(walls[i][j].Y)) return true; } } } return false; } /// <summary> /// Checks if the walls are touching other walls before it actually /// saves or prints the wall. This also checks to make sure that each /// wall has an opening to allow monsters or players to get through. /// </summary> /// <param name="walls"></param> /// <param name="wallX"></param> /// <param name="wallY"></param> /// <returns></returns> public bool checkWall(IList<IList<Obstacles>> walls, int wallX, int wallY) { for (int i = 0; i < walls.Count; i++) { for (int j = 0; j < walls[i].Count; j++) { if (walls[i][j].X.Equals(wallX) && walls[i][j].Y.Equals(wallY)) return true; if (walls[i][j].X2.Equals(wallX) && walls[i][j].Y.Equals(wallY)) return true; if ((walls[i][j].X.Equals(wallX + 1) && walls[i][j].Y.Equals(wallY + 1)) || (walls[i][j].X.Equals(wallX + 1) && walls[i][j].Y.Equals(wallY - 1))) return true; if ((walls[i][j].X.Equals(wallX - 1) && walls[i][j].Y.Equals(wallY + 1)) || (walls[i][j].X.Equals(wallX - 1) && walls[i][j].Y.Equals(wallY - 1))) return true; if ((walls[i][j].X.Equals(wallX - 1) && walls[i][j].Y.Equals(wallY + 1)) || (walls[i][j].X.Equals(wallX + 1) && walls[i][j].Y.Equals(wallY + 1))) return true; if ((walls[i][j].X.Equals(wallX + 1) && walls[i][j].Y.Equals(wallY - 1)) || (walls[i][j].X.Equals(wallX - 1) && walls[i][j].Y.Equals(wallY - 1))) return true; if ((walls[i][j].X2.Equals(wallX + 1) && walls[i][j].Y.Equals(wallY - 1)) || (walls[i][j].X2.Equals(wallX + 1) && walls[i][j].Y.Equals(wallY + 1))) return true; if ((walls[i][j].X2.Equals(wallX - 1) && walls[i][j].Y.Equals(wallY + 1)) || (walls[i][j].X2.Equals(wallX - 1) && walls[i][j].Y.Equals(wallY - 1))) return true; if ((walls[i][j].X2.Equals(wallX - 1) && walls[i][j].Y.Equals(wallY + 1)) || (walls[i][j].X2.Equals(wallX + 1) && walls[i][j].Y.Equals(wallY + 1))) return true; if ((walls[i][j].X2.Equals(wallX - 1) && walls[i][j].Y.Equals(wallY - 1)) || (walls[i][j].X2.Equals(wallX + 1) && walls[i][j].Y.Equals(wallY - 1))) return true; } } return false; } } }
namespace OmniGui.Xaml { using OmniXaml; public class BindDefinition { private readonly LinkMode linkMode; public object TargetInstance { get; } public Member TargetMember { get; } public string SourceProperty { get; } public BindDefinition(object targetInstance, Member targetMember, string sourceProperty, LinkMode linkMode) { this.linkMode = linkMode; TargetInstance = targetInstance; TargetMember = targetMember; SourceProperty = sourceProperty; } public LinkMode LinkMode { get; set; } public bool SourceFollowsTarget => linkMode == LinkMode.FullLink || linkMode == LinkMode.SourceFollowsTarget; public bool TargetFollowsSource => linkMode == LinkMode.FullLink || linkMode == LinkMode.TargetFollowsSource; public BindingSource Source { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; public static class StringExtensions { public static bool IsNullOrEmpty(this string s) => s == null || s.Trim().Length == 0; public static void ThrowIfNullOrEmpty(this string s,string message=null) { if (s.IsNullOrEmpty()) throw new ArgumentException(message??"String cannot be null or empty"); } public static string FormatWith(this string s,params object[] args) { return string.Format(s, args); } public static string Add(this string s,string arg) { return s + arg; } public static string Left(this string s,int len) { if (s.IsNullOrEmpty()) return string.Empty; if (s.Trim().Length <= len) return s; return s.Substring(0, len); } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace hw06 { public partial class Form1 : Form { private static double your=0,com=0; private static String msg=""; private static PictureBox[] pic = new PictureBox[10]; private static int cont=0,locat=0; private static int money=1000,stake; private static int[] poker = new int[52]; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { pic[0] = pictureBox1; pic[1] = pictureBox2; pic[2] = pictureBox3; pic[3] = pictureBox4; pic[4] = pictureBox5; pic[5] = pictureBox6; pic[6] = pictureBox7; pic[7] = pictureBox8; pic[8] = pictureBox9; pic[9] = pictureBox10; newgame(); unavailable(); reset(); shuffle(); } //重玩 private void button6_Click(object sender, EventArgs e) { newgame(); //遊戲的介面與數值回歸初始 unavailable(); //讓主要控制鍵無法互動 reset(); //重設遊戲回合 shuffle(); //洗牌 show(); //顯示訊息 } //繼續 private void button3_Click(object sender, EventArgs e) { reset(); //重設遊戲回合 shuffle(); //洗牌 show(); //顯示訊息 } //確定 private void button2_Click(object sender, EventArgs e) { competitor(); //對手動作 decide(); //決定輸贏 show(); //顯示結果 judge(); //判斷手頭上的錢 unavailable(); //讓確定鍵無法在被按 } //抽牌 private void pictureBox1_Click(object sender, EventArgs e) { draw(); //按下進行翻牌 showdown(); //按完後不讓使用者在與剛按下的圖片互動 show(); //顯示訊息 } private void pictureBox2_Click(object sender, EventArgs e) { draw(); showdown(); show(); } private void pictureBox3_Click(object sender, EventArgs e) { draw(); showdown(); show(); } private void pictureBox4_Click(object sender, EventArgs e) { draw(); showdown(); show(); } private void pictureBox5_Click(object sender, EventArgs e) { draw(); showdown(); show(); } //下注賭金 private void button1_Click(object sender, EventArgs e) { if (money > 0) //如果現金大於0則每次下注可為100 stake = 100; else stake = 500; //反之 bet(); //下注 } private void button4_Click(object sender, EventArgs e) { if (money > 0) stake = 150; else stake = 1000; bet(); } private void button5_Click(object sender, EventArgs e) { if (money > 0) stake = 200; else stake = 1500; bet(); } //遊戲的介面與數值初始化 public void newgame() { money = 1000; label3.Text = "賭金:" + money; label4.Text = "一般模式"; button1.Text = "100"; button4.Text = "150"; button5.Text = "200"; } //確定鍵關閉並開啟繼續鍵和重玩鍵 //所有牌都會變得不可互動 public void unavailable() { button2.Enabled = false; button3.Enabled = true; button6.Enabled = true; for (int i = 0; i < 5; i++) { pic[i].Enabled = false; } } //重設遊戲回合 public void reset() { msg = "遊戲開始"; com = 0; your = 0; cont = 0; locat = 0; //全部蓋牌 for (int i = 0; i < 10; i++) { if (i <= 5) { pic[i].Image = Image.FromFile("poker\\52.jpg"); pic[i].Enabled = false; } else { pic[i].Image = null; } } //賭金按鈕開啟 button1.Enabled = true; button4.Enabled = true; button5.Enabled = true; //繼續重玩鍵關閉 button3.Enabled = false; button6.Enabled = false; } //洗牌 public void shuffle() { int p, q; Random rand = new Random(); for (int i = 0; i < 52; i++) { poker[i] = i; } for (int i = 0; i <= 1000; i++) // Randomly select two numbers for exchange { p = rand.Next(0, 52); q = rand.Next(0, 52); int tmp = poker[p]; poker[p] = poker[q]; poker[q] = tmp; } } //秀出提示訊息 public void show() { label2.Text = msg; } //抽牌並判斷加點數 public void draw() { string st; //將牌顯示在圖框裡 st = "poker\\" + poker[cont].ToString() + ".jpg"; pic[locat].Image = Image.FromFile(st); if (poker[cont] % 13 == 10 || poker[cont] % 13 == 11 || poker[cont] % 13 == 12) //當牌等於JQK加半點 your += 0.50; else your += poker[cont] % 13 + 1; msg = "目前你的點數為" + your + "\n"; cont++; //第幾張牌 locat++; //第幾個位置 } //攤開覆蓋的牌 public void showdown() { //將原本按下的牌設為不互動,未攤開的下張牌設為互動 pic[locat - 1].Enabled = false; pic[locat].Enabled = true; //確定鍵打開 button2.Enabled = true; } //決定輸贏 public void decide() { //當使用者>電腦且<=10.5 //電腦爆掉且使用者<=10.5 if ((your > com && your <= 10.5) || (com > 10.5 && your <= 10.5)) { msg = "電腦點數:" + com + " 你的點數:" + your + "\n恭喜!你贏了"; money += stake * 2; //賭金會加上下注的賭金*2倍 label3.Text = "賭金:" + money; } //使用者爆掉,電腦沒爆 //使用者<電腦且電腦沒爆 else if ((your < com && com <= 10.5) || (your > 10.5 && com <= 10.5)) { msg = "電腦點數:" + com + " 你的點數:" + your + "\n你輸了"; //因賭金已付出故不需再扣 } //使用者=電腦或兩者一起爆 else if (your == com || (your > 10.5 && com > 10.5)) { msg = "電腦點數:" + com + " 你的點數:" + your + "\n和局"; money += stake; //賭金加回下注金額 label3.Text = "賭金:" + money; } } //判斷賭金 public void judge() { if (money <= 0) { label4.Text = "借錢模式"; button1.Text = "500"; button4.Text = "1000"; button5.Text = "1500"; } else { button1.Text = "100"; button4.Text = "150"; button5.Text = "200"; } if (money >= 2000) //當賭金大於2000則勝利 { //玩家可繼續在玩 label2.Text = "勝利!!!"; label4.Text = "勝利!!!"; label1.Text = "勝利!!!"; label3.Text = "勝利!!!"; } } //下注 public void bet() { money -= stake; //先收錢 label3.Text = "賭金:" + money; pictureBox1.Enabled = true; //讓玩家可進行攤牌動作 button1.Enabled = false; //屏蔽所有下注按鈕 button4.Enabled = false; button5.Enabled = false; } //對手行為 public void competitor() { Random r = new Random(); int p = r.Next(10); //對手做任何行動的機率 //locat一定要等於5,因為對手的圖片位置從5開始 locat = 5; action(); //對手行動(抽牌) cont++; //第幾張牌 locat++; //第幾個位置 //當玩家賭金>=800和<=100且大於-200時,玩家完勝的機率為30% if (money >= 800 || (money <= 100 && money>=-200)) { if (p < 3) { win(); label4.Text = "完勝模式"; } else { general(); label4.Text = "一般模式"; } } else if (money >= 1700) //當玩家賭金大於1700時對手絕對會完勝 { win(); label4.Text = "完勝模式"; } else //其餘時候有80%對手都是完勝 { if (p < 8) { win(); label4.Text = "完勝模式"; } else { general(); label4.Text = "一般模式"; } } } //對手抽牌行動 public void action() { string st; //將牌顯示在圖框裡 st = "poker\\" + poker[cont].ToString() + ".jpg"; pic[locat].Image = Image.FromFile(st); if (poker[cont] % 13 == 10 || poker[cont] % 13 == 11 || poker[cont] % 13 == 12) //當牌等於JQK加半點 com += 0.50; else com += poker[cont] % 13 + 1; } //對手一般動作 public void general() { //如果<6.5時一定抽牌 while (com < 6.5) { action(); cont++; //這張抽完換下一張 locat++; //換下一個位置 } } //完勝模式:對手一定贏或平手的動作 public void win() { double temp = 0; //暫存變數 while ((com<=your && com<10.5) && your<=10.5) //當對手贏或者平手的情形則跳出迴圈 { if (cont == 52 || locat == 10) //當牌數和位置超過範圍則跳出迴圈 { //避免無窮迴圈 label4.Text = cont+"/"+locat; break; } //先看看牌的點數 if (poker[cont] % 13 == 10 || poker[cont] % 13 == 11 || poker[cont] % 13 == 12) //當牌等於JQK加半點 temp = 0.50; else temp = poker[cont] % 13 + 1; //如果原先點數加上目前牌的點數未超過10.5則進入判斷 if ((com + temp) <= 10.5) { if ((locat == 8) && (your==10.5)) //這是當使用者絕對贏的情形做判斷 { if (((com + temp) % 1 == 0.5)) //如果再倒數第二張牌的位置此時點數加起來沒有"半點"了話 { //那麼這個位置一定要有個"半點" action(); //如果確定加起來有半點則將牌分配給對手 locat++; //進到下個位置 } else cont++; //沒了話換下一張 } else if (locat == 9) //這是在倒數最後一個位置的情形 { if ((com + temp) >= your && (com + temp) <= 10.5) //最後一張抽到的牌一定要等於或大於使用者 { //而且要小於等於10.5 action(); //若是的話則將牌指定給對手 locat++; } } else //不是已上情形了話直接將牌指定給對手 { //因為在最前面的判斷已經過濾了讓對手牌爆掉的情形故可以直接指定 action(); locat++; //進入下個位置 } } cont++; //下張牌 } //為了不讓對手看起來很威而顯的太假所以偶爾也會有平手的情形 //當然是在確定使用者一定輸的情況 if (your > 10.5) { general(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using KelpNet.Common.Optimizers; using KelpNet.Common.Tools; namespace KelpNet.Common.Functions { //Base class of Function stacked in FunctionStack [Serializable] public abstract class Function { public string Name; private bool _gpuEnable; public bool GpuEnable { get => _gpuEnable; protected set { if (_gpuEnable != value) { _gpuEnable = value; OnGpuEnableChanged(); } } } public NdArray[] Parameters = { }; public Optimizer[] Optimizers = { }; [NonSerialized] public List<NdArray[]> PrevInputs = new List<NdArray[]>(); public abstract NdArray[] Forward(params NdArray[] xs); public virtual void Backward(params NdArray[] ys){} public string[] InputNames; public string[] OutputNames; //constructor protected Function(string name, string[] inputNames = null, string[] outputNames = null) { this.Name = name; if (inputNames != null) { this.InputNames = inputNames.ToArray(); } if (outputNames != null) { this.OutputNames = outputNames.ToArray(); } } [OnDeserialized] private void OnDeserialized(StreamingContext context) { this.PrevInputs = new List<NdArray[]>(); } public virtual void SetOptimizer(params Optimizer[] optimizers) { this.Optimizers = optimizers; foreach (Optimizer optimizer in optimizers) { optimizer.AddFunctionParameters(this.Parameters); } } protected virtual void OnGpuEnableChanged() { } //Function to call when updating parameters protected void BackwardCountUp() { foreach (NdArray parameter in Parameters) { parameter.CountUp(); } } //Evaluation function public virtual NdArray[] Predict(params NdArray[] input) { return this.Forward(input); } public virtual void Update() { foreach (Optimizer optimizer in this.Optimizers) { optimizer.Update(); } } //ある処理実行後に特定のデータを初期値に戻す処理 public virtual void ResetState() { PrevInputs.Clear(); } //Return name public override string ToString() { return this.Name; } //Method to create copy public Function Clone() { return DeepCopyHelper.DeepCopy(this); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Mercury.Shared { public class DataReturnArgs { public string Message { get; set; } public string SessionID { get; set; } public string CorelationID { get; set; } public ReceivedMessage ReceivedMessage { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using System.Data; using MaterialDesignColors.WpfExample.Domain; using Chpoi.SuitUp.Service; using Chpoi.SuitUp.Util; using Chpoi.SuitUp.SSL; using Chpoi.SuitUp.Entity; using Chpoi.SuitUp.Source; namespace chpoi.suitup.ui { /// <summary> /// Interaction logic for UserOrderInterface.xaml /// </summary> /// public partial class UserOrderInterface : Window { int page = 0; public UserOrderInterface() { try { //显示用户订单 InitializeComponent(); if (SourceManager.clientOrderEnd == false) { try { if (SourceManager.clientorder[0] == null) { } List<ClientOrder> orderLst = new List<ClientOrder>(); for (int i = page * 10; i < page * 10 + 10; i++) { orderLst.Add(SourceManager.clientorder[i]); } Lst.ItemsSource = orderLst; } catch { OrderService os = ServiceFactory.GetOrderService(); int t = os.ClientGetOrderInfor(SourceManager.client._id, 0, 10); if (t < 10) { SourceManager.clientOrderEnd = true; SourceManager.clientOrderPageMax = page; SourceManager.clientOrderLastPageCount = t; } List<ClientOrder> orderLst = new List<ClientOrder>(); for (int i = 0; i < t; i++) { orderLst.Add(SourceManager.clientorder[i]); } Lst.ItemsSource = orderLst; } } else { if (SourceManager.clientOrderPageMax == 0) { List<ClientOrder> orderLst = new List<ClientOrder>(); for (int i = 0; i < SourceManager.clientOrderLastPageCount; i++) { orderLst.Add(SourceManager.clientorder[i]); } Lst.ItemsSource = orderLst; } else { List<ClientOrder> orderLst = new List<ClientOrder>(); for (int i = 0; i < 10; i++) { orderLst.Add(SourceManager.clientorder[i]); } Lst.ItemsSource = orderLst; } } } catch { MessageBox.Show("载入商品失败,请稍后再试。"); } } private void BuyerInformationButtonClick(object sender, RoutedEventArgs e) { BuyerWindow bW = new BuyerWindow(); bW.Show(); this.Close(); } private void BuyerOrderButtonClick(object sender, RoutedEventArgs e) { UserOrderInterface uOI = new UserOrderInterface(); uOI.Show(); this.Close(); } private void ShoppingCartButtonClick(object sender, RoutedEventArgs e) { ShoppingcartInterface sI = new ShoppingcartInterface(); sI.Show(); this.Close(); } private void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { this.DragMove(); } private void CloseButtonClick(object sender, RoutedEventArgs e) { this.Close(); } private void MinimizeButtonClick(object sender, RoutedEventArgs e) { this.WindowState = WindowState.Minimized; } private void MainPageButtonClick(object sender, RoutedEventArgs e) { GoodsWindow bW = new GoodsWindow(); bW.Show(); this.Close(); } private void SearchButtonOnClick(object sender, RoutedEventArgs e) { } private void Button1_Click(object sender, RoutedEventArgs e) { } private void LogOutButtonClick(object sender, RoutedEventArgs e) { //注销 LoginWindow lW = new LoginWindow(); lW.Show(); this.Close(); } private void OrderManageButtonClick(object sender, RoutedEventArgs e) { } private void GoodsManageButtonClick(object sender, RoutedEventArgs e) { } private void DetailButtonClick(object sender, RoutedEventArgs e) { ClientOrder curItem = (ClientOrder)((ListBoxItem)Lst.ContainerFromElement((Button)sender)).Content; SourceManager.curOrder = curItem; UserDetailOrderInterface uDOI = new UserDetailOrderInterface(); uDOI.Show(); this.Close(); } private void OrderButtonClick(object sender, RoutedEventArgs e) { } private void NextPageButtonClick(object sender, RoutedEventArgs e) { try { if (page == SourceManager.clientOrderPageMax) { MessageBox.Show("已是最后一页。"); return; } //翻页 page++; try { if (SourceManager.clientorder[page * 10] == null) { } List<ClientOrder> orderLst = new List<ClientOrder>(); if (page == SourceManager.clientOrderPageMax) { for (int i = page * 10; i < page * 10 + SourceManager.clientOrderLastPageCount; i++) { orderLst.Add(SourceManager.clientorder[i]); } Lst.ItemsSource = orderLst; } for (int i = page * 10; i < page * 10 + 10; i++) { orderLst.Add(SourceManager.clientorder[i]); } Lst.ItemsSource = orderLst; } catch { OrderService os = ServiceFactory.GetOrderService(); int t = os.ClientGetOrderInfor(SourceManager.client._id, 0, 10); if (t == 0) { MessageBox.Show("已经是最后一页"); return; } if (t != 10) { SourceManager.clientOrderEnd = true; SourceManager.clientOrderPageMax = page; SourceManager.clientOrderLastPageCount = t; } List<ClientOrder> orderLst = new List<ClientOrder>(); for (int i = page * 10; i < page * 10 + t; i++) { orderLst.Add(SourceManager.clientorder[i]); } Lst.ItemsSource = orderLst; } } catch { MessageBox.Show("系统错误,请稍后再试!"); } } private void PrePageButtonClick(object sender, RoutedEventArgs e) { //前一页 try { page--; if (page < 0) { MessageBox.Show("已经是第一页"); return; } List<ClientOrder> orderLst = new List<ClientOrder>(); for (int i = page * 10; i < page * 10 + 10; i++) { orderLst.Add(SourceManager.clientorder[i]); } Lst.ItemsSource = orderLst; } catch { MessageBox.Show("系统错误,请稍后再试!"); } } } }
using System; namespace ExplicacionInterface { public class Class1 { } }
using System.Diagnostics; using MediatR; using Newtonsoft.Json; using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.JsonRpc.Generation; using OmniSharp.Extensions.LanguageServer.Protocol.Client; using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; using OmniSharp.Extensions.LanguageServer.Protocol.Generation; using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; using OmniSharp.Extensions.LanguageServer.Protocol.Serialization.Converters; using OmniSharp.Extensions.LanguageServer.Protocol.Server.Capabilities; // ReSharper disable once CheckNamespace namespace OmniSharp.Extensions.LanguageServer.Protocol { namespace Models { [Parallel] [Method(TextDocumentNames.SignatureHelp, Direction.ClientToServer)] [GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Document")] [GenerateHandlerMethods] [GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] [RegistrationOptions(typeof(SignatureHelpRegistrationOptions))] [Capability(typeof(SignatureHelpCapability))] public partial record SignatureHelpParams : TextDocumentPositionParams, IWorkDoneProgressParams, IRequest<SignatureHelp?> { /// <summary> /// The signature help context. This is only available if the client specifies /// to send this using the client capability `textDocument.signatureHelp.contextSupport === true` /// /// @since 3.15.0 /// </summary> public SignatureHelpContext Context { get; init; } = null!; } /// <summary> /// Additional information about the context in which a signature help request was triggered. /// /// @since 3.15.0 /// </summary> public record SignatureHelpContext { /// <summary> /// Action that caused signature help to be triggered. /// </summary> public SignatureHelpTriggerKind TriggerKind { get; init; } /// <summary> /// Character that caused signature help to be triggered. /// /// This is undefined when `triggerKind !== SignatureHelpTriggerKind.TriggerCharacter` /// </summary> [Optional] public string? TriggerCharacter { get; init; } /// <summary> /// `true` if signature help was already showing when it was triggered. /// /// Retriggers occur when the signature help is already active and can be caused by actions such as /// typing a trigger character, a cursor move, or document content changes. /// </summary> public bool IsRetrigger { get; init; } /// <summary> /// The currently active `SignatureHelp`. /// /// The `activeSignatureHelp` has its `SignatureHelp.activeSignature` field updated based on /// the user navigating through available signatures. /// </summary> [Optional] public SignatureHelp? ActiveSignatureHelp { get; init; } } /// <summary> /// How a signature help was triggered. /// /// @since 3.15.0 /// </summary> [JsonConverter(typeof(NumberEnumConverter))] public enum SignatureHelpTriggerKind { /// <summary> /// Signature help was invoked manually by the user or by a command. /// </summary> Invoked = 1, /// <summary> /// Signature help was triggered by a trigger character. /// </summary> TriggerCharacter = 2, /// <summary> /// Signature help was triggered by the cursor moving or by the document content changing. /// </summary> ContentChange = 3, } /// <summary> /// Signature help represents the signature of something /// callable. There can be multiple signature but only one /// active and only one active parameter. /// </summary> public partial record SignatureHelp { /// <summary> /// One or more signatures. /// </summary> public Container<SignatureInformation> Signatures { get; init; } = new(); /// <summary> /// The active signature. /// </summary> [Optional] public int? ActiveSignature { get; init; } /// <summary> /// The active parameter of the active signature. /// </summary> [Optional] public int? ActiveParameter { get; init; } } /// <summary> /// Represents the signature of something callable. A signature /// can have a label, like a function-name, a doc-comment, and /// a set of parameters. /// </summary> [DebuggerDisplay("{" + nameof(DebuggerDisplay) + ",nq}")] public record SignatureInformation { /// <summary> /// The label of this signature. Will be shown in /// the UI. /// </summary> public string Label { get; init; } = null!; /// <summary> /// The human-readable doc-comment of this signature. Will be shown /// in the UI but can be omitted. /// </summary> [Optional] public StringOrMarkupContent? Documentation { get; init; } /// <summary> /// The parameters of this signature. /// </summary> [Optional] public Container<ParameterInformation>? Parameters { get; init; } /// <summary> /// The index of the active parameter. /// /// If provided, this is used in place of `SignatureHelp.activeParameter`. /// /// @since 3.16.0 /// </summary> [Optional] public int? ActiveParameter { get; init; } private string DebuggerDisplay => $"{Label}{Documentation?.ToString() ?? ""}"; /// <inheritdoc /> public override string ToString() { return DebuggerDisplay; } } /// <summary> /// Represents a parameter of a callable-signature. A parameter can /// have a label and a doc-comment. /// </summary> [DebuggerDisplay("{" + nameof(DebuggerDisplay) + ",nq}")] public record ParameterInformation { /// <summary> /// The label of this parameter. Will be shown in /// the UI. /// </summary> public ParameterInformationLabel Label { get; init; } = null!; /// <summary> /// The human-readable doc-comment of this parameter. Will be shown /// in the UI but can be omitted. /// </summary> [Optional] public StringOrMarkupContent? Documentation { get; init; } private string DebuggerDisplay => $"{Label}{( Documentation != null ? $" {Documentation}" : string.Empty )}"; /// <inheritdoc /> public override string ToString() { return DebuggerDisplay; } } [JsonConverter(typeof(ParameterInformationLabelConverter))] [DebuggerDisplay("{" + nameof(DebuggerDisplay) + ",nq}")] public record ParameterInformationLabel { public ParameterInformationLabel((int start, int end) range) { Range = range; } public ParameterInformationLabel(string label) { Label = label; } public (int start, int end) Range { get; } public bool IsRange => Label == null; public string? Label { get; } public bool IsLabel => Label != null; public static implicit operator ParameterInformationLabel(string label) { return new ParameterInformationLabel(label); } public static implicit operator ParameterInformationLabel((int start, int end) range) { return new ParameterInformationLabel(range); } private string DebuggerDisplay => IsRange ? $"(start: {Range.start}, end: {Range.end})" : IsLabel ? Label! : string.Empty; /// <inheritdoc /> public override string ToString() { return DebuggerDisplay; } } [GenerateRegistrationOptions(nameof(ServerCapabilities.SignatureHelpProvider))] [RegistrationName(TextDocumentNames.SignatureHelp)] public partial class SignatureHelpRegistrationOptions : ITextDocumentRegistrationOptions, IWorkDoneProgressOptions { /// <summary> /// The characters that trigger signature help /// automatically. /// </summary> [Optional] public Container<string>? TriggerCharacters { get; set; } /// <summary> /// List of characters that re-trigger signature help. /// /// These trigger characters are only active when signature help is already showing. All trigger characters /// are also counted as re-trigger characters. /// /// @since 3.15.0 /// </summary> [Optional] public Container<string>? RetriggerCharacters { get; set; } } } namespace Client.Capabilities { public partial class SignatureHelpCapability : DynamicCapability { /// <summary> /// The client supports the following `SignatureInformation` /// specific properties. /// </summary> [Optional] public SignatureInformationCapabilityOptions? SignatureInformation { get; set; } /// <summary> /// The client supports to send additional context information for a /// `textDocument/signatureHelp` request. A client that opts into /// contextSupport will also support the `retriggerCharacters` on /// `StaticOptions`. /// /// @since 3.15.0 /// </summary> [Optional] public bool ContextSupport { get; set; } } public class SignatureInformationCapabilityOptions { /// <summary> /// Client supports the follow content formats for the content property. The order describes the preferred format of the client. /// </summary> [Optional] public Container<MarkupKind>? DocumentationFormat { get; set; } [Optional] public SignatureParameterInformationCapabilityOptions? ParameterInformation { get; set; } /// <summary> /// The client support the `activeParameter` property on `SignatureInformation` /// literal. /// /// @since 3.16.0 /// </summary> [Optional] public bool ActiveParameterSupport { get; set; } } public class SignatureParameterInformationCapabilityOptions { /// <summary> /// The client supports processing label offsets instead of a /// simple label string. /// </summary> [Optional] public bool LabelOffsetSupport { get; set; } } } namespace Document { } }
using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Threading.Tasks; using System.Net; using System.Web; using System.Web.Mvc; using Aroma_Violet.Models; namespace Aroma_Violet.Controllers { public class finAccountsController : Controller { private AromaContext db = new AromaContext(); // GET: finAccounts public async Task<ActionResult> Index() { return View(await db.Accounts.OrderBy(m=>m.AccountName).ToListAsync()); } // GET: finAccounts/Details/5 public async Task<ActionResult> Details(Guid? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } finAccount finAccount = await db.Accounts.FindAsync(id); if (finAccount == null) { return HttpNotFound(); } return View(finAccount); } // GET: finAccounts/Create public ActionResult Create() { return View(); } // POST: finAccounts/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> Create([Bind(Include = "AccountId,AccountName,IsSystemAccount,Active")] finAccount finAccount, string debitAmount,string creditAmount) { if (ModelState.IsValid) { finAccount.AccountId = Guid.NewGuid(); db.Accounts.Add(finAccount); await db.SaveChangesAsync(); InforceDebitCreditRule(finAccount.AccountId, debitAmount,creditAmount); return RedirectToAction("Index"); } return View(finAccount); } private void InforceDebitCreditRule(Guid accountId, string debitAmount, string creditAmount) { decimal debit = 0; decimal credit = 0; var validDebit = (debitAmount != null && debitAmount.Length > 0 && decimal.TryParse(debitAmount, out debit)); var validCredit = (creditAmount != null && creditAmount.Length > 0 && decimal.TryParse(creditAmount, out credit)); var rule = db.DebitCreditRules.Find(accountId); if (validDebit || validCredit) { if (rule == null) { rule = new DebitCreditRule() { AccountId = accountId }; db.DebitCreditRules.Add(rule); } } if (rule != null) { rule.DebitAmount = debit; rule.CreditAmount = credit; rule.ActiveCredit = validCredit; rule.ActiveDebit = validDebit; db.SaveChanges(); } } // GET: finAccounts/Edit/5 public async Task<ActionResult> Edit(Guid? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } finAccount finAccount = await db.Accounts.FindAsync(id); if (finAccount == null) { return HttpNotFound(); } var rule = db.DebitCreditRules.Find(id); ViewBag.DebiCreditRule = rule; return View(finAccount); } // POST: finAccounts/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> Edit([Bind(Include = "AccountId,AccountName,IsSystemAccount,Active")] finAccount finAccount, string debitAmount, string creditAmount) { if (ModelState.IsValid) { db.Entry(finAccount).State = EntityState.Modified; await db.SaveChangesAsync(); InforceDebitCreditRule(finAccount.AccountId, debitAmount, creditAmount); return RedirectToAction("Index"); } return View(finAccount); } // GET: finAccounts/Delete/5 public async Task<ActionResult> Delete(Guid? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } finAccount finAccount = await db.Accounts.FindAsync(id); if (finAccount == null) { return HttpNotFound(); } return View(finAccount); } // POST: finAccounts/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public async Task<ActionResult> DeleteConfirmed(Guid id) { finAccount finAccount = await db.Accounts.FindAsync(id); db.Accounts.Remove(finAccount); await db.SaveChangesAsync(); return RedirectToAction("Index"); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } internal static string Name(AromaContext db, Guid accountId) { var account = db.Accounts.Where(m => m.AccountId.Equals(accountId)).FirstOrDefault(); if (account == null) { var clientAccount = db.ClientAccounts.Where(m => m.ClientAccountId.Equals(accountId)).FirstOrDefault(); if (clientAccount != null) return clientAccount.Account.AccountName; } else { return account.AccountName; } return "Unknown"; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using System.Web; using System.Web.Http.Filters; namespace Shop.Atrributes { public class ZeroHendlerAttribute: Attribute, IExceptionFilter { public bool AllowMultiple { get { return false; } } public Task ExecuteExceptionFilterAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken) { if (actionExecutedContext.Exception != null && actionExecutedContext.Exception is DivideByZeroException) { actionExecutedContext.Response = actionExecutedContext.Request.CreateErrorResponse (HttpStatusCode.BadRequest,"Check you prametr"); } return Task.FromResult<object>(null); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Threading.Tasks; namespace WebApi.Controllers.Cotizacion { public class PesosController : ApiController, IDinero { public async Task<IEnumerable<string>> GetCotizacion() { using (var client = new HttpClient()) { client.BaseAddress = new Uri("http://www.bancoprovincia.com.ar/"); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var response = await client.GetAsync("Principal/Dolar"); if (response.IsSuccessStatusCode) { return await response.Content.ReadAsAsync<IEnumerable<string>>(); } return await Task.FromResult<IEnumerable<string>>(null); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Visibilidad.Models; namespace Visibilidad.Controllers { public class EventoController : Controller { public EventoModels _evento_model = new EventoModels(); public ActionResult Index() { ViewData["Mensaje"] = _evento_model.Mensaje(); return View(); } public ActionResult Insertar() { return View(); } } }