text
stringlengths
13
6.01M
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CameraInterface.Cameras { public class NoCamera : ICamera { public bool _isActive = false; public bool isActive { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public ActionResult Activate() { return new ActionResult("No camera available", _isActive); } public ActionResult ChargeCamera() { return new ActionResult("No camera available", _isActive); } public ActionResult DeActivate() { return new ActionResult("No camera available", _isActive); } public ActionResult SetCamera() { return new ActionResult("No camera available", _isActive); } public ImagePhoto TakeSnap() { return new ImagePhoto("noCamera", DateTime.Now, "noFoto", false); } } }
using StackExchange.Redis; using System.Threading.Tasks; using System.Collections.Generic; namespace Microsoft.UnifiedRedisPlatform.Core.Database { public partial class UnifiedRedisDatabase { public bool SortedSetAdd(RedisKey key, RedisValue member, double score, CommandFlags flags) => Execute(() => _baseDatabase.SortedSetAdd(CreateAppKey(key), member, score, flags)); public bool SortedSetAdd(RedisKey key, RedisValue member, double score, When when = When.Always, CommandFlags flags = CommandFlags.None) => Execute(() => _baseDatabase.SortedSetAdd(CreateAppKey(key), member, score, when, flags)); public long SortedSetAdd(RedisKey key, SortedSetEntry[] values, CommandFlags flags) => Execute(() => _baseDatabase.SortedSetAdd(CreateAppKey(key), values, flags)); public long SortedSetAdd(RedisKey key, SortedSetEntry[] values, When when = When.Always, CommandFlags flags = CommandFlags.None) => Execute(() => _baseDatabase.SortedSetAdd(CreateAppKey(key), values, when, flags)); public Task<bool> SortedSetAddAsync(RedisKey key, RedisValue member, double score, CommandFlags flags) => ExecuteAsync(() => _baseDatabase.SortedSetAddAsync(CreateAppKey(key), member, score, flags)); public Task<bool> SortedSetAddAsync(RedisKey key, RedisValue member, double score, When when = When.Always, CommandFlags flags = CommandFlags.None) => ExecuteAsync(() => _baseDatabase.SortedSetAddAsync(CreateAppKey(key), member, score, when, flags)); public Task<long> SortedSetAddAsync(RedisKey key, SortedSetEntry[] values, CommandFlags flags) => ExecuteAsync(() => _baseDatabase.SortedSetAddAsync(CreateAppKey(key), values, flags)); public Task<long> SortedSetAddAsync(RedisKey key, SortedSetEntry[] values, When when = When.Always, CommandFlags flags = CommandFlags.None) => ExecuteAsync(() => _baseDatabase.SortedSetAddAsync(CreateAppKey(key), values, when, flags)); public long SortedSetCombineAndStore(SetOperation operation, RedisKey destination, RedisKey first, RedisKey second, Aggregate aggregate = Aggregate.Sum, CommandFlags flags = CommandFlags.None) => Execute(() => _baseDatabase.SortedSetCombineAndStore(operation, CreateAppKey(destination), CreateAppKey(first), CreateAppKey(second), aggregate, flags)); public long SortedSetCombineAndStore(SetOperation operation, RedisKey destination, RedisKey[] keys, double[] weights = null, Aggregate aggregate = Aggregate.Sum, CommandFlags flags = CommandFlags.None) => Execute(() => _baseDatabase.SortedSetCombineAndStore(operation, CreateAppKey(destination), CreateAppKeys(keys), weights, aggregate, flags)); public Task<long> SortedSetCombineAndStoreAsync(SetOperation operation, RedisKey destination, RedisKey first, RedisKey second, Aggregate aggregate = Aggregate.Sum, CommandFlags flags = CommandFlags.None) => ExecuteAsync(() => _baseDatabase.SortedSetCombineAndStoreAsync(operation, CreateAppKey(destination), CreateAppKey(first), CreateAppKey(second), aggregate, flags)); public Task<long> SortedSetCombineAndStoreAsync(SetOperation operation, RedisKey destination, RedisKey[] keys, double[] weights = null, Aggregate aggregate = Aggregate.Sum, CommandFlags flags = CommandFlags.None) => ExecuteAsync(() => _baseDatabase.SortedSetCombineAndStoreAsync(operation, CreateAppKey(destination), CreateAppKeys(keys), weights, aggregate, flags)); public double SortedSetDecrement(RedisKey key, RedisValue member, double value, CommandFlags flags = CommandFlags.None) => Execute(() => _baseDatabase.SortedSetDecrement(CreateAppKey(key), member, value, flags)); public Task<double> SortedSetDecrementAsync(RedisKey key, RedisValue member, double value, CommandFlags flags = CommandFlags.None) => ExecuteAsync(() => _baseDatabase.SortedSetDecrementAsync(CreateAppKey(key), member, value, flags)); public double SortedSetIncrement(RedisKey key, RedisValue member, double value, CommandFlags flags = CommandFlags.None) => Execute(() => _baseDatabase.SortedSetIncrement(CreateAppKey(key), member, value, flags)); public Task<double> SortedSetIncrementAsync(RedisKey key, RedisValue member, double value, CommandFlags flags = CommandFlags.None) => ExecuteAsync(() => _baseDatabase.SortedSetIncrementAsync(CreateAppKey(key), member, value, flags)); public long SortedSetLength(RedisKey key, double min = double.NegativeInfinity, double max = double.PositiveInfinity, Exclude exclude = Exclude.None, CommandFlags flags = CommandFlags.None) => Execute(() => _baseDatabase.SortedSetLength(CreateAppKey(key), min, max, exclude, flags)); public Task<long> SortedSetLengthAsync(RedisKey key, double min = double.NegativeInfinity, double max = double.PositiveInfinity, Exclude exclude = Exclude.None, CommandFlags flags = CommandFlags.None) => ExecuteAsync(() => _baseDatabase.SortedSetLengthAsync(CreateAppKey(key), min, max, exclude, flags)); public long SortedSetLengthByValue(RedisKey key, RedisValue min, RedisValue max, Exclude exclude = Exclude.None, CommandFlags flags = CommandFlags.None) => Execute(() => _baseDatabase.SortedSetLengthByValue(CreateAppKey(key), min, max, exclude, flags)); public Task<long> SortedSetLengthByValueAsync(RedisKey key, RedisValue min, RedisValue max, Exclude exclude = Exclude.None, CommandFlags flags = CommandFlags.None) => ExecuteAsync(() => _baseDatabase.SortedSetLengthByValueAsync(CreateAppKey(key), min, max, exclude, flags)); public SortedSetEntry? SortedSetPop(RedisKey key, Order order = Order.Ascending, CommandFlags flags = CommandFlags.None) => Execute(() => _baseDatabase.SortedSetPop(CreateAppKey(key), order, flags)); public SortedSetEntry[] SortedSetPop(RedisKey key, long count, Order order = Order.Ascending, CommandFlags flags = CommandFlags.None) => Execute(() => _baseDatabase.SortedSetPop(CreateAppKey(key), count, order, flags)); public Task<SortedSetEntry?> SortedSetPopAsync(RedisKey key, Order order = Order.Ascending, CommandFlags flags = CommandFlags.None) => ExecuteAsync(() => _baseDatabase.SortedSetPopAsync(CreateAppKey(key), order, flags)); public Task<SortedSetEntry[]> SortedSetPopAsync(RedisKey key, long count, Order order = Order.Ascending, CommandFlags flags = CommandFlags.None) => ExecuteAsync(() => _baseDatabase.SortedSetPopAsync(CreateAppKey(key), count, order, flags)); public RedisValue[] SortedSetRangeByRank(RedisKey key, long start = 0, long stop = -1, Order order = Order.Ascending, CommandFlags flags = CommandFlags.None) => Execute(() => _baseDatabase.SortedSetRangeByRank(CreateAppKey(key), start, stop, order, flags)); public Task<RedisValue[]> SortedSetRangeByRankAsync(RedisKey key, long start = 0, long stop = -1, Order order = Order.Ascending, CommandFlags flags = CommandFlags.None) => ExecuteAsync(() => _baseDatabase.SortedSetRangeByRankAsync(CreateAppKey(key), start, stop, order, flags)); public SortedSetEntry[] SortedSetRangeByRankWithScores(RedisKey key, long start = 0, long stop = -1, Order order = Order.Ascending, CommandFlags flags = CommandFlags.None) => Execute(() => _baseDatabase.SortedSetRangeByRankWithScores(CreateAppKey(key), start, stop, order, flags)); public Task<SortedSetEntry[]> SortedSetRangeByRankWithScoresAsync(RedisKey key, long start = 0, long stop = -1, Order order = Order.Ascending, CommandFlags flags = CommandFlags.None) => ExecuteAsync(() => _baseDatabase.SortedSetRangeByRankWithScoresAsync(CreateAppKey(key), start, stop, order, flags)); public RedisValue[] SortedSetRangeByScore(RedisKey key, double start = double.NegativeInfinity, double stop = double.PositiveInfinity, Exclude exclude = Exclude.None, Order order = Order.Ascending, long skip = 0, long take = -1, CommandFlags flags = CommandFlags.None) => Execute(() => _baseDatabase.SortedSetRangeByScore(CreateAppKey(key), start, stop, exclude, order, skip, take, flags)); public Task<RedisValue[]> SortedSetRangeByScoreAsync(RedisKey key, double start = double.NegativeInfinity, double stop = double.PositiveInfinity, Exclude exclude = Exclude.None, Order order = Order.Ascending, long skip = 0, long take = -1, CommandFlags flags = CommandFlags.None) => ExecuteAsync(() => _baseDatabase.SortedSetRangeByScoreAsync(CreateAppKey(key), start, stop, exclude, order, skip, take, flags)); public SortedSetEntry[] SortedSetRangeByScoreWithScores(RedisKey key, double start = double.NegativeInfinity, double stop = double.PositiveInfinity, Exclude exclude = Exclude.None, Order order = Order.Ascending, long skip = 0, long take = -1, CommandFlags flags = CommandFlags.None) => Execute(() => _baseDatabase.SortedSetRangeByScoreWithScores(CreateAppKey(key), start, stop, exclude, order, skip, take, flags)); public Task<SortedSetEntry[]> SortedSetRangeByScoreWithScoresAsync(RedisKey key, double start = double.NegativeInfinity, double stop = double.PositiveInfinity, Exclude exclude = Exclude.None, Order order = Order.Ascending, long skip = 0, long take = -1, CommandFlags flags = CommandFlags.None) => ExecuteAsync(() => _baseDatabase.SortedSetRangeByScoreWithScoresAsync(CreateAppKey(key), start, stop, exclude, order, skip, take, flags)); public RedisValue[] SortedSetRangeByValue(RedisKey key, RedisValue min, RedisValue max, Exclude exclude, long skip, long take = -1, CommandFlags flags = CommandFlags.None) => Execute(() => _baseDatabase.SortedSetRangeByValue(CreateAppKey(key), min, max, exclude, skip, take, flags)); public RedisValue[] SortedSetRangeByValue(RedisKey key, RedisValue min = default, RedisValue max = default, Exclude exclude = Exclude.None, Order order = Order.Ascending, long skip = 0, long take = -1, CommandFlags flags = CommandFlags.None) => Execute(() => _baseDatabase.SortedSetRangeByValue(CreateAppKey(key), min, max, exclude, order, skip, take, flags)); public Task<RedisValue[]> SortedSetRangeByValueAsync(RedisKey key, RedisValue min, RedisValue max, Exclude exclude, long skip, long take = -1, CommandFlags flags = CommandFlags.None) => ExecuteAsync(() => _baseDatabase.SortedSetRangeByValueAsync(CreateAppKey(key), min, max, exclude, skip, take, flags)); public Task<RedisValue[]> SortedSetRangeByValueAsync(RedisKey key, RedisValue min = default, RedisValue max = default, Exclude exclude = Exclude.None, Order order = Order.Ascending, long skip = 0, long take = -1, CommandFlags flags = CommandFlags.None) => ExecuteAsync(() => _baseDatabase.SortedSetRangeByValueAsync(CreateAppKey(key), min, max, exclude, order, skip, take, flags)); public long? SortedSetRank(RedisKey key, RedisValue member, Order order = Order.Ascending, CommandFlags flags = CommandFlags.None) => Execute(() => _baseDatabase.SortedSetRank(CreateAppKey(key), member, order, flags)); public Task<long?> SortedSetRankAsync(RedisKey key, RedisValue member, Order order = Order.Ascending, CommandFlags flags = CommandFlags.None) => ExecuteAsync(() => _baseDatabase.SortedSetRankAsync(CreateAppKey(key), member, order, flags)); public bool SortedSetRemove(RedisKey key, RedisValue member, CommandFlags flags = CommandFlags.None) => Execute(() => _baseDatabase.SortedSetRemove(CreateAppKey(key), member, flags)); public long SortedSetRemove(RedisKey key, RedisValue[] members, CommandFlags flags = CommandFlags.None) => Execute(() => _baseDatabase.SortedSetRemove(CreateAppKey(key), members, flags)); public Task<bool> SortedSetRemoveAsync(RedisKey key, RedisValue member, CommandFlags flags = CommandFlags.None) => ExecuteAsync(() => _baseDatabase.SortedSetRemoveAsync(CreateAppKey(key), member, flags)); public Task<long> SortedSetRemoveAsync(RedisKey key, RedisValue[] members, CommandFlags flags = CommandFlags.None) => ExecuteAsync(() => _baseDatabase.SortedSetRemoveAsync(CreateAppKey(key), members, flags)); public long SortedSetRemoveRangeByRank(RedisKey key, long start, long stop, CommandFlags flags = CommandFlags.None) => Execute(() => _baseDatabase.SortedSetRemoveRangeByRank(CreateAppKey(key), start, stop, flags)); public Task<long> SortedSetRemoveRangeByRankAsync(RedisKey key, long start, long stop, CommandFlags flags = CommandFlags.None) => ExecuteAsync(() => _baseDatabase.SortedSetRemoveRangeByRankAsync(CreateAppKey(key), start, stop, flags)); public long SortedSetRemoveRangeByScore(RedisKey key, double start, double stop, Exclude exclude = Exclude.None, CommandFlags flags = CommandFlags.None) => Execute(() => _baseDatabase.SortedSetRemoveRangeByScore(CreateAppKey(key), start, stop, exclude, flags)); public Task<long> SortedSetRemoveRangeByScoreAsync(RedisKey key, double start, double stop, Exclude exclude = Exclude.None, CommandFlags flags = CommandFlags.None) => ExecuteAsync(() => _baseDatabase.SortedSetRemoveRangeByScoreAsync(CreateAppKey(key), start, stop, exclude, flags)); public long SortedSetRemoveRangeByValue(RedisKey key, RedisValue min, RedisValue max, Exclude exclude = Exclude.None, CommandFlags flags = CommandFlags.None) => Execute(() => _baseDatabase.SortedSetRemoveRangeByValue(CreateAppKey(key), min, max, exclude, flags)); public Task<long> SortedSetRemoveRangeByValueAsync(RedisKey key, RedisValue min, RedisValue max, Exclude exclude = Exclude.None, CommandFlags flags = CommandFlags.None) => ExecuteAsync(() => _baseDatabase.SortedSetRemoveRangeByValueAsync(CreateAppKey(key), min, max, exclude, flags)); public IEnumerable<SortedSetEntry> SortedSetScan(RedisKey key, RedisValue pattern, int pageSize, CommandFlags flags) => Execute(() => _baseDatabase.SortedSetScan(CreateAppKey(key), pattern, pageSize, flags)); public IEnumerable<SortedSetEntry> SortedSetScan(RedisKey key, RedisValue pattern = default, int pageSize = 10, long cursor = 0, int pageOffset = 0, CommandFlags flags = CommandFlags.None) => Execute(() => _baseDatabase.SortedSetScan(CreateAppKey(key), pattern, pageSize, cursor, pageOffset, flags)); public double? SortedSetScore(RedisKey key, RedisValue member, CommandFlags flags = CommandFlags.None) => Execute(() => _baseDatabase.SortedSetScore(CreateAppKey(key), member, flags)); public Task<double?> SortedSetScoreAsync(RedisKey key, RedisValue member, CommandFlags flags = CommandFlags.None) => ExecuteAsync(() => _baseDatabase.SortedSetScoreAsync(CreateAppKey(key), member, flags)); public RedisValue[] Sort(RedisKey key, long skip = 0, long take = -1, Order order = Order.Ascending, SortType sortType = SortType.Numeric, RedisValue by = default, RedisValue[] get = null, CommandFlags flags = CommandFlags.None) => Execute(() => _baseDatabase.Sort(CreateAppKey(key), skip, take, order, sortType, by, get, flags)); public Task<RedisValue[]> SortAsync(RedisKey key, long skip = 0, long take = -1, Order order = Order.Ascending, SortType sortType = SortType.Numeric, RedisValue by = default, RedisValue[] get = null, CommandFlags flags = CommandFlags.None) => ExecuteAsync(() => _baseDatabase.SortAsync(CreateAppKey(key), skip, take, order, sortType, by, get, flags)); public long SortAndStore(RedisKey destination, RedisKey key, long skip = 0, long take = -1, Order order = Order.Ascending, SortType sortType = SortType.Numeric, RedisValue by = default, RedisValue[] get = null, CommandFlags flags = CommandFlags.None) => Execute(() => _baseDatabase.SortAndStore(CreateAppKey(destination), CreateAppKey(key), skip, take, order, sortType, by, get, flags)); public Task<long> SortAndStoreAsync(RedisKey destination, RedisKey key, long skip = 0, long take = -1, Order order = Order.Ascending, SortType sortType = SortType.Numeric, RedisValue by = default, RedisValue[] get = null, CommandFlags flags = CommandFlags.None) => ExecuteAsync(() => _baseDatabase.SortAndStoreAsync(CreateAppKey(destination), CreateAppKey(key), skip, take, order, sortType, by, get, flags)); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace IRAP.Entity.FVS { public class AndonEventKanbanBMR { /// <summary> /// 序号 /// </summary> public int Ordinal { get; set; } /// <summary> /// 事件事实编号 /// </summary> public long FactID { get; set; } /// <summary> /// 呼叫时间 /// </summary> public string CallingTime { get; set; } /// <summary> /// 产线代码 /// </summary> public string LineCode { get; set; } /// <summary> /// 产线名称 /// </summary> public string LineName { get; set; } /// <summary> /// 设备代码 /// </summary> public string EquipmentCode { get; set; } /// <summary> /// 设备名称 /// </summary> public string EquipmentName { get; set; } /// <summary> /// 失效模式 /// </summary> public string FailureMode { get; set; } /// <summary> /// 是否已停产 /// </summary> public string ProductionStatus { get; set; } /// <summary> /// 责任团队 /// </summary> public string ResponsibleTeamName { get; set; } /// <summary> /// 是否已响应 /// </summary> public string RespondingStatus { get; set; } /// <summary> /// 已过时间(分钟) /// </summary> public int ElapsedTimeInMinutes { get; set; } public AndonEventKanbanBMR Clone() { AndonEventKanbanBMR rlt = MemberwiseClone() as AndonEventKanbanBMR; return rlt; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using AGCompressedAir.Domain.Domains; using AGCompressedAir.Domain.Services; using AGCompressedAir.Windows.Enums; using AGCompressedAir.Windows.Models; namespace AGCompressedAir.Windows.Services.ServiceService { public class ServiceService : IServiceService { public ServiceService(IDomainService domainService) { DomainService = domainService; } private IDomainService DomainService { get; } public async Task<Service> GetAsync(Guid id) { var service = await DomainService.GetFirstAsync<ServiceDomain>(x => x.Id == id && !x.IsDeleted, null, x => new ServiceDomain { Id = x.Id, SerialNumber = x.SerialNumber, Compressor = x.Compressor, AirFilter = x.AirFilter, OilFilter = x.OilFilter, Seperator = x.Seperator, Belt = x.Belt, Oil = x.Oil, Client = new ClientDomain { Id = x.ClientId, Name = x.Client.Name, AddressLine1 = x.Client.AddressLine1, AddressLine2 = x.Client.AddressLine2, City = x.Client.City, Postcode = x.Client.Postcode, Email = x.Client.Email, Telephone = x.Client.Telephone }, ServiceDate = x.ServiceDate, ServiceInterval = x.ServiceInterval }); return new Service { Id = service.Id, SerialNumber = service.SerialNumber, Compressor = service.Compressor, AirFilter = service.AirFilter, OilFilter = service.OilFilter, Seperator = service.Seperator, Belt = service.Belt, Oil = service.Oil, Client = new Client { Id = service.Client.Id, Name = service.Client.Name, AddressLine1 = service.Client.AddressLine1, AddressLine2 = service.Client.AddressLine2, City = service.Client.City, Postcode = service.Client.Postcode, Email = service.Client.Email, Telephone = service.Client.Telephone }, ServiceDate = service.ServiceDate, ServiceInterval = (ServiceInterval) Enum.ToObject(typeof (ServiceInterval), service.ServiceInterval) }; } public async Task<Service> GetRecentAsync() { var service = await DomainService.GetFirstAsync<ServiceDomain>(x => !x.IsDeleted, q => q.OrderBy(x => x.Created), x => new ServiceDomain { Id = x.Id, SerialNumber = x.SerialNumber, Compressor = x.Compressor, AirFilter = x.AirFilter, OilFilter = x.OilFilter, Seperator = x.Seperator, Belt = x.Belt, Oil = x.Oil, Client = new ClientDomain { Id = x.ClientId, Name = x.Client.Name, AddressLine1 = x.Client.AddressLine1, AddressLine2 = x.Client.AddressLine2, City = x.Client.City, Postcode = x.Client.Postcode, Email = x.Client.Email, Telephone = x.Client.Telephone }, ServiceDate = x.ServiceDate, ServiceInterval = x.ServiceInterval }); return new Service { Id = service.Id, SerialNumber = service.SerialNumber, Compressor = service.Compressor, AirFilter = service.AirFilter, OilFilter = service.OilFilter, Seperator = service.Seperator, Belt = service.Belt, Oil = service.Oil, Client = new Client { Id = service.Client.Id, Name = service.Client.Name, AddressLine1 = service.Client.AddressLine1, AddressLine2 = service.Client.AddressLine2, City = service.Client.City, Postcode = service.Client.Postcode, Email = service.Client.Email, Telephone = service.Client.Telephone }, ServiceDate = service.ServiceDate, ServiceInterval = (ServiceInterval) Enum.ToObject(typeof (ServiceInterval), service.ServiceInterval) }; } public async Task UpdateAsync(Service model) { var service = await DomainService.GetFirstAsync<ServiceDomain>(x => x.Id == model.Id && !x.IsDeleted); if (service == null) { throw new ArgumentNullException(nameof(service)); } var airFilterPart = model.AirFilter; var oilFilterPart = model.OilFilter; var seperaterPart = model.Seperator; var beltPart = model.Belt; var oilPart = model.Oil; service.Compressor = model.Compressor; service.SerialNumber = model.SerialNumber; service.AirFilter = airFilterPart; service.OilFilter = oilFilterPart; service.Seperator = seperaterPart; service.Belt = beltPart; service.Oil = oilFilterPart; service.ClientId = model.Client.Id; service.ServiceDate = model.ServiceDate; service.ServiceInterval = model.ServiceInterval; DomainService.Update(service); if (!string.IsNullOrEmpty(airFilterPart)) { var exists = await DomainService.GetExistsAsync<PartDomain>( x => x.Number == airFilterPart && x.Type == PartType.AirFilter); if (!exists) { var part = new PartDomain { Number = airFilterPart, Type = PartType.AirFilter }; DomainService.Create(part); } } if (!string.IsNullOrEmpty(oilFilterPart)) { var exists = await DomainService.GetExistsAsync<PartDomain>( x => x.Number == oilFilterPart && x.Type == PartType.OilFilter); if (!exists) { var part = new PartDomain { Number = oilFilterPart, Type = PartType.OilFilter }; DomainService.Create(part); } } if (!string.IsNullOrEmpty(seperaterPart)) { var exists = await DomainService.GetExistsAsync<PartDomain>( x => x.Number == seperaterPart && x.Type == PartType.Seperator); if (!exists) { var part = new PartDomain { Number = seperaterPart, Type = PartType.Seperator }; DomainService.Create(part); } } if (!string.IsNullOrEmpty(beltPart)) { var exists = await DomainService.GetExistsAsync<PartDomain>(x => x.Number == beltPart && x.Type == PartType.Belt); if (!exists) { var part = new PartDomain { Number = beltPart, Type = PartType.Belt }; DomainService.Create(part); } } if (!string.IsNullOrEmpty(oilPart)) { var exists = await DomainService.GetExistsAsync<PartDomain>(x => x.Number == oilPart && x.Type == PartType.Oil); if (!exists) { var part = new PartDomain { Number = oilPart, Type = PartType.Oil }; DomainService.Create(part); } } await DomainService.SaveAsync(); } public async Task AddAsync(Service model) { var airFilterPart = model.AirFilter; var oilFilterPart = model.OilFilter; var seperaterPart = model.Seperator; var beltPart = model.Belt; var oilPart = model.Oil; var service = new ServiceDomain { Compressor = model.Compressor, SerialNumber = model.SerialNumber, AirFilter = airFilterPart, OilFilter = oilFilterPart, Seperator = seperaterPart, Belt = beltPart, Oil = oilFilterPart, ClientId = model.Client.Id, ServiceDate = model.ServiceDate, ServiceInterval = model.ServiceInterval }; DomainService.Create(service); if (!string.IsNullOrEmpty(airFilterPart)) { var exists = await DomainService.GetExistsAsync<PartDomain>( x => x.Number == airFilterPart && x.Type == PartType.AirFilter); if (!exists) { var part = new PartDomain { Number = airFilterPart, Type = PartType.AirFilter }; DomainService.Create(part); } } if (!string.IsNullOrEmpty(oilFilterPart)) { var exists = await DomainService.GetExistsAsync<PartDomain>( x => x.Number == oilFilterPart && x.Type == PartType.OilFilter); if (!exists) { var part = new PartDomain { Number = oilFilterPart, Type = PartType.OilFilter }; DomainService.Create(part); } } if (!string.IsNullOrEmpty(seperaterPart)) { var exists = await DomainService.GetExistsAsync<PartDomain>( x => x.Number == seperaterPart && x.Type == PartType.Seperator); if (!exists) { var part = new PartDomain { Number = seperaterPart, Type = PartType.Seperator }; DomainService.Create(part); } } if (!string.IsNullOrEmpty(beltPart)) { var exists = await DomainService.GetExistsAsync<PartDomain>(x => x.Number == beltPart && x.Type == PartType.Belt); if (!exists) { var part = new PartDomain { Number = beltPart, Type = PartType.Belt }; DomainService.Create(part); } } if (!string.IsNullOrEmpty(oilPart)) { var exists = await DomainService.GetExistsAsync<PartDomain>(x => x.Number == oilPart && x.Type == PartType.Oil); if (!exists) { var part = new PartDomain { Number = oilPart, Type = PartType.Oil }; DomainService.Create(part); } } await DomainService.SaveAsync(); } public async Task DeleteAsync(Service model) { var service = await DomainService.GetFirstAsync<ServiceDomain>(x => x.Id == model.Id && !x.IsDeleted); if (service == null) { throw new ArgumentNullException(nameof(service)); } DomainService.Delete(service); await DomainService.SaveAsync(); } public async Task<List<Service>> ListAsync(string filter = "", CancellationToken cancellationToken = default(CancellationToken)) { IEnumerable<ServiceDomain> query; if (!string.IsNullOrEmpty(filter)) { query = await DomainService.GetAsync<ServiceDomain>(x => !x.IsDeleted && (!string.IsNullOrEmpty(x.Client.Name) && (x.Client.Name.ToLower().Contains(filter) || filter.Contains(x.Client.Name.ToLower()))) || (!string.IsNullOrEmpty(x.Compressor) && (x.Compressor.ToLower().Contains(filter) || filter.Contains(x.Compressor.ToLower()))) || (!string.IsNullOrEmpty(x.SerialNumber) && (x.SerialNumber.ToLower().Contains(filter) || filter.Contains(x.SerialNumber.ToLower()))) || (!string.IsNullOrEmpty(x.AirFilter) && (x.AirFilter.ToLower().Contains(filter) || filter.Contains(x.AirFilter.ToLower()))) || (!string.IsNullOrEmpty(x.OilFilter) && (x.OilFilter.ToLower().Contains(filter) || filter.Contains(x.OilFilter.ToLower()))) || (!string.IsNullOrEmpty(x.Seperator) && (x.Seperator.ToLower().Contains(filter) || filter.Contains(x.Seperator.ToLower()))) || (!string.IsNullOrEmpty(x.Belt) && (x.Belt.ToLower().Contains(filter) || filter.Contains(x.Belt.ToLower()))) || (!string.IsNullOrEmpty(x.Oil) && (x.Oil.ToLower().Contains(filter) || filter.Contains(x.Oil.ToLower()))) || (!string.IsNullOrEmpty(x.Belt) && (x.Belt.ToLower().Contains(filter) || filter.Contains(x.Belt.ToLower()))) || (!string.IsNullOrEmpty(x.Compressor) && (x.Compressor.ToLower().Contains(filter) || filter.Contains(x.Compressor.ToLower()))) || (!string.IsNullOrEmpty(x.Compressor) && (x.Compressor.ToLower().Contains(filter) || filter.Contains(x.Compressor.ToLower()))) || (!string.IsNullOrEmpty(x.Compressor) && (x.Compressor.ToLower().Contains(filter) || filter.Contains(x.Compressor.ToLower()))), null, x => new ServiceDomain { Id = x.Id, Compressor = x.Compressor, SerialNumber = x.SerialNumber, AirFilter = x.AirFilter, OilFilter = x.OilFilter, Seperator = x.Seperator, Belt = x.Belt, Oil = x.Oil, ClientId = x.ClientId, Client = new ClientDomain { Id = x.ClientId, Name = x.Client.Name, AddressLine1 = x.Client.AddressLine1, AddressLine2 = x.Client.AddressLine2, City = x.Client.City, Postcode = x.Client.Postcode, Email = x.Client.Email, Telephone = x.Client.Telephone }, ServiceDate = x.ServiceDate, ServiceInterval = x.ServiceInterval, Modified = x.Modified, Created = x.Created, IsDeleted = x.IsDeleted }); } else { query = await DomainService.GetAsync<ServiceDomain>(x => !x.IsDeleted, null, x => new ServiceDomain { Id = x.Id, Compressor = x.Compressor, SerialNumber = x.SerialNumber, AirFilter = x.AirFilter, OilFilter = x.OilFilter, Seperator = x.Seperator, Belt = x.Belt, Oil = x.Oil, ClientId = x.ClientId, Client = new ClientDomain { Id = x.ClientId, Name = x.Client.Name, AddressLine1 = x.Client.AddressLine1, AddressLine2 = x.Client.AddressLine2, City = x.Client.City, Postcode = x.Client.Postcode, Email = x.Client.Email, Telephone = x.Client.Telephone }, ServiceDate = x.ServiceDate, ServiceInterval = x.ServiceInterval, Modified = x.Modified, Created = x.Created, IsDeleted = x.IsDeleted }); } return query.Select(x => new Service { Id = x.Id, Compressor = x.Compressor, SerialNumber = x.SerialNumber, AirFilter = x.AirFilter, OilFilter = x.OilFilter, Seperator = x.Seperator, Belt = x.Belt, Oil = x.Oil, Hash = x.Modified, Client = new Client { Id = x.ClientId, Name = x.Client.Name, AddressLine1 = x.Client.AddressLine1, AddressLine2 = x.Client.AddressLine2, City = x.Client.City, Postcode = x.Client.Postcode, Email = x.Client.Email, Telephone = x.Client.Telephone }, ServiceDate = x.ServiceDate, ServiceInterval = x.ServiceInterval, ServiceDue = GetServiceDueDate(x.ServiceDate, x.ServiceInterval), ServiceStatus = GetServiceStatus(x.ServiceDate, x.ServiceInterval) }).OrderBy(q => q.ServiceDue).ToList(); } private DateTime GetServiceDueDate(DateTime serviceDate, ServiceInterval serviceInterval) { int months; switch (serviceInterval) { case ServiceInterval.EveryMonth: months = 1; break; case ServiceInterval.Every6Months: months = 6; break; case ServiceInterval.Every12Months: months = 12; break; default: throw new ArgumentOutOfRangeException(nameof(serviceInterval), serviceInterval, null); } return serviceDate.AddMonths(months); } private ServiceStatus GetServiceStatus(DateTime serviceDate, ServiceInterval serviceInterval) { var serviceDueDate = GetServiceDueDate(serviceDate, serviceInterval); if (DateTime.Today >= serviceDueDate) { return ServiceStatus.OverDue; } if (DateTime.Today >= serviceDueDate.AddDays(-7)) { return ServiceStatus.Due; } return ServiceStatus.Normal; } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Web; namespace chat.Models { public class User_Picture_Like { [Key,Column(Order=0)] public long Id { get; set; } [Key,ForeignKey("Profile"),Column(Order = 1)] public long Profile_Id { get; set; } public virtual User_Profile Profile { get; set; } [Key,ForeignKey("Picture"),Column(Order = 2)] public long Picture_Id { get; set; } public virtual User_Picture Picture { get; set; } } }
namespace DataAccess.Model { public class AgeLimit { public int Id { get; set; } public string Limit { get; set; } public override string ToString() { return Limit + "+"; } } }
namespace RRExpress.AppCommon.Services { public interface IDevice { string GetPhoneNumber(); string GetDeviceID(); } }
using jaytwo.Common.Http; using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Globalization; using System.IO; using System.Net; using System.Linq; using System.Text; using System.Xml; using System.Drawing; namespace jaytwo.Common.Extensions { public static partial class HttpWebResponseExtensions { public static string GetFileName(this HttpWebResponse httpWebResponse) { return HttpHelper.GetFileName(httpWebResponse); } public static string GetEtag(this HttpWebResponse httpWebResponse) { return HttpHelper.GetEtag(httpWebResponse); } public static bool IsDeflate(this HttpWebResponse httpWebResponse) { return HttpHelper.IsDeflate(httpWebResponse); } public static bool IsGzip(this HttpWebResponse httpWebResponse) { return HttpHelper.IsGzip(httpWebResponse); } public static T VerifyResponseStatusOK<T>(this T httpWebResponse) where T : HttpWebResponse { HttpHelper.VerifyResponseStatusOK(httpWebResponse); return httpWebResponse; } public static T VerifyResponseStatusSuccess<T>(this T httpWebResponse) where T : HttpWebResponse { HttpHelper.VerifyResponseStatusSuccess(httpWebResponse); return httpWebResponse; } public static T VerifyResponseStatus<T>(this T httpWebResponse, HttpStatusCode statusCode) where T : HttpWebResponse { HttpHelper.VerifyResponseStatus(httpWebResponse, statusCode); return httpWebResponse; } public static T VerifyResponseStatus<T>(this T httpWebResponse, params HttpStatusCode[] statusCodes) where T : HttpWebResponse { HttpHelper.VerifyResponseStatus(httpWebResponse, statusCodes); return httpWebResponse; } public static Stream GetContent(this HttpWebResponse httpWebResponse) { return HttpHelper.GetContent(httpWebResponse); } public static Encoding GetEncoding(this HttpWebResponse httpWebResponse) { return HttpHelper.GetEncoding(httpWebResponse); } public static TextReader GetContentAsReader(this HttpWebResponse httpWebResponse) { return HttpHelper.GetContentAsReader(httpWebResponse); } public static TextReader GetContentAsReader(this HttpWebResponse httpWebResponse, Encoding encoding) { return HttpHelper.GetContentAsReader(httpWebResponse, encoding); } public static byte[] GetContentBytes(this HttpWebResponse httpWebResponse) { return HttpHelper.GetContentBytes(httpWebResponse); } public static string GetContentAsString(this HttpWebResponse httpWebResponse) { return HttpHelper.GetContentAsString(httpWebResponse); } public static string GetContentAsString(this HttpWebResponse httpWebResponse, Encoding encoding) { return HttpHelper.GetContentAsString(httpWebResponse, encoding); } public static Image GetContentAsImage(this HttpWebResponse httpWebResponse) { return HttpHelper.GetContentAsImage(httpWebResponse); } } }
using System.Threading.Tasks; using Microsoft.AspNet.SignalR; namespace SignInCheckIn.Hubs { public class EventHub : Hub { public async Task Subscribe(string channel) { await Groups.Add(Context.ConnectionId, channel); } public async Task Unsubscribe(string channel) { await Groups.Remove(Context.ConnectionId, channel); } public Task Publish(ChannelEvent channelEvent) { Clients.Group(channelEvent.ChannelName).OnEvent(channelEvent.ChannelName, channelEvent); return Task.FromResult(0); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class GameControls : MonoBehaviour { public GameObject Bullet; public void shootBullet() { GameObject Hero = GameObject.Find("Hero"); GameObject a = Instantiate(Bullet) as GameObject; a.transform.position = new Vector2(Hero.transform.position.x, Hero.transform.position.y); } }
using System; using Microsoft.EntityFrameworkCore.Migrations; using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; namespace GraderBot.Database.Migrations { public partial class InitialCreate : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "Users", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), Username = table.Column<string>(maxLength: 64, nullable: false), Password = table.Column<string>(nullable: true), Role = table.Column<int>(nullable: false), State = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Users", x => x.Id); }); migrationBuilder.CreateTable( name: "Problems", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), Name = table.Column<string>(maxLength: 64, nullable: false), AuthorId = table.Column<int>(nullable: false), Type = table.Column<int>(nullable: false), Description = table.Column<string>(nullable: false), Config = table.Column<string>(nullable: false), Source = table.Column<byte[]>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Problems", x => x.Id); table.ForeignKey( name: "FK_Problems_Users_AuthorId", column: x => x.AuthorId, principalTable: "Users", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Solutions", columns: table => new { Id = table.Column<Guid>(nullable: false), UserId = table.Column<int>(nullable: false), ProblemId = table.Column<int>(nullable: false), Source = table.Column<byte[]>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Solutions", x => x.Id); table.ForeignKey( name: "FK_Solutions_Problems_ProblemId", column: x => x.ProblemId, principalTable: "Problems", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_Solutions_Users_UserId", column: x => x.UserId, principalTable: "Users", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Results", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), Output = table.Column<string>(nullable: true), SolutionId = table.Column<Guid>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Results", x => x.Id); table.ForeignKey( name: "FK_Results_Solutions_SolutionId", column: x => x.SolutionId, principalTable: "Solutions", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateIndex( name: "IX_Problems_AuthorId", table: "Problems", column: "AuthorId"); migrationBuilder.CreateIndex( name: "IX_Problems_Type_Name", table: "Problems", columns: new[] { "Type", "Name" }, unique: true); migrationBuilder.CreateIndex( name: "IX_Results_SolutionId", table: "Results", column: "SolutionId"); migrationBuilder.CreateIndex( name: "IX_Solutions_ProblemId", table: "Solutions", column: "ProblemId"); migrationBuilder.CreateIndex( name: "IX_Solutions_UserId", table: "Solutions", column: "UserId"); migrationBuilder.CreateIndex( name: "IX_Users_Username", table: "Users", column: "Username", unique: true); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "Results"); migrationBuilder.DropTable( name: "Solutions"); migrationBuilder.DropTable( name: "Problems"); migrationBuilder.DropTable( name: "Users"); } } }
using System; using SharpEngine; using org.ogre; using PacmanOgre.Utilities; using Entity.Component; namespace PacmanOgre.Components { public class PositionChangedEventArgs : EventArgs { public Vector3 Position { get; set; } } public class PositionComponent : IComponent { public event EventHandler<PositionChangedEventArgs> OnPositionChanged; private Vector3 _position; [Description("Position")] public Vector3 Position { get { return _position; } set { if(_position == null || _position.isNaN()) { _position = VectorUtils.Vector3.ZERO; } _position = value; OnPositionChangedEvent(_position); } } public PositionComponent(IContext context, IEntity entity) { } protected virtual void OnPositionChangedEvent(Vector3 vector3) { OnPositionChanged?.Invoke(this, new PositionChangedEventArgs { Position = vector3 }); } public void Setup() { } public void OnLoaded() { } } }
using System.Collections; using System.Collections.Generic; using DChild.Gameplay.Objects.Characters.Attributes; using DChild.Gameplay.Systems; using DChild.Gameplay.Systems.Subroutine; using UnityEngine; namespace DChild.Gameplay.Player { [System.Serializable] public class PlayerLevel { [SerializeField] private Experience m_experience; private int m_targetEXP; private Player m_player; public int level => m_experience.level; public int exp => m_experience.level; public int expProgress => m_experience.exp / m_targetEXP; public int targetEXP { set { m_targetEXP = value; } } public void InitializeReferences(Player player) => m_player = player; public void Initialize(int level, int exp) { SetLevel(level); m_experience.exp = exp; } public void SetLevel(int level) { if (m_experience.level > level) { m_experience.exp = 0; } m_experience.level = level; m_targetEXP = GetTargetEXP(level); } public void AddEXP(int exp) { var currentExp = m_experience.exp + exp; if (currentExp >= m_targetEXP) { var playerReward = GameplaySystem.GetRoutine<IPlayerRewardRoutine>(); do { currentExp -= m_targetEXP; playerReward.LevelUp(m_player, 1); } while (currentExp >= m_targetEXP); } m_experience.exp = currentExp; } private int GetTargetEXP(int level) { var exp = ((int)Mathf.Pow(level, 2) * 3) + (6 * level); if (level == 2) { return exp + 24; } else { return exp; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GeneralResources.CursoAlgoritmoEstruturaDeDados.Algoritmos { /// <summary> /// The Levenshtein Algorithm /// https://medium.com/@ethannam/understanding-the-levenshtein-distance-equation-for-beginners-c4285a5604f0 /// https://eximia.co/computing-the-levenshtein-edit-distance-of-two-strings-using-c/ /// /// </summary> public class Levenshtein { /// <summary> /// O(n²) /// </summary> public int Version1(string a, string b) { if (a.Length == 0) return b.Length; if (b.Length == 0) return a.Length; var matrix = new int[a.Length + 1, b.Length + 1]; for (int i = 0; i <= a.Length; i++) { matrix[i, 0] = i; } for (int j = 0; j <= b.Length; j++) { matrix[0, j] = j; } for (int i = 1; i <= a.Length; i++) { for (int j = 1; j <= b.Length; j++) { int cost = a[i - 1] == b[j - 1] ? 0 : 1; var match = matrix[i - 1, j - 1] + cost; var insert = matrix[i, j - 1] + 1; var delete = matrix[i - 1, j] + 1; matrix[i, j] = Min(delete, insert, match); } } return matrix[a.Length, b.Length]; } /// <summary> /// Otimizado. Economizando memória. /// Feito pelo Elemar, não consegui entender a lógica completa /// </summary> public int Version2(string a, string b) { if (a.Length == 0) return b.Length; if (b.Length == 0) return a.Length; var current = 1; var previous = 0; var matrix = new int[2, b.Length + 1]; for (int i = 0; i <= b.Length; i++) { matrix[previous, i] = i; } for (int i = 0; i < a.Length; i++) { matrix[current, 0] = i + 1; for (int j = 1; j <= b.Length; j++) { int cost = b[j - 1] == a[i] ? 0 : 1; matrix[current, j] = Min( matrix[previous, j] + 1, matrix[current, j - 1] + 1, matrix[previous, j - 1] + cost); } previous = (previous + 1) % 2; current = (current + 1) % 2; } return matrix[previous, b.Length]; } public int Min(int x, int y, int z) { return Math.Min(Math.Min(x, y), z); } [Theory] [InlineData("jonatan", "natan", 2)] [InlineData("ant", "aunt", 1)] [InlineData("a", "a", 0)] public void TestVersion1(string a, string b, int expected) { // Arrange var sut = new Levenshtein(); // Act var result = sut.Version1(a, b); // Assert Assert.Equal(expected, result); } [Theory] [InlineData("jonatan", "natan", 2)] [InlineData("ant", "aunt", 1)] [InlineData("a", "a", 0)] public void TestVersion2(string a, string b, int expected) { // Arrange var sut = new Levenshtein(); // Act var result = sut.Version2(a, b); // Assert Assert.Equal(expected, result); } } }
#region License //*****************************************************************************/ // Copyright (c) 2012 Luigi Grilli // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. //*****************************************************************************/ #endregion using System; using ByteArray = Grillisoft.ImmutableArray.ImmutableArray<byte>; namespace Grillisoft.FastCgi.Protocol { public class Message { public static readonly byte[] Padding = new byte[Consts.ChunkSize]; public Message(ByteArray array) { this.Header = new MessageHeader(array); this.Body = array.SubArray(MessageHeader.HeaderSize, this.Header.ContentLength); } public Message(byte[] data) : this(new ByteArray(data)) { } protected Message(MessageHeader header) : this(header, ByteArray.Empty) { } public Message(MessageType messageType, ushort requestId, byte[] body) : this(messageType, requestId, new ByteArray(body)) { } public Message(MessageType messageType, ushort requestId, ByteArray body) : this(new MessageHeader(messageType, requestId, (ushort)body.Count), body) { } public Message(MessageHeader header, ByteArray body) { if (header.ContentLength != body.Count) throw new InvalidOperationException("Header ContentLength must be equals to body length"); this.Header = header; this.Body = body; } public MessageHeader Header { get; protected set; } public ByteArray Body { get; protected set; } public int CopyTo(byte[] dest) { if (dest.Length < this.Header.MessageSize) throw new ArgumentException("dest"); this.Header.CopyTo(dest); this.Body.CopyTo(dest, MessageHeader.HeaderSize); Array.Copy(Padding, 0, dest, MessageHeader.HeaderSize + this.Body.Count, this.Header.PaddingLength); return this.Header.MessageSize; } public ByteArray ToByteArray() { return new ByteArray(this.Header.ToArray()) + this.Body + new ByteArray(Padding, this.Header.PaddingLength); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Lunchify.Data.Models; using Lunchify.Data.Services; using Microsoft.AspNetCore.Mvc; namespace Lunchify.Web.Controllers { public class LunchesController : Controller { IAppData db; public LunchesController(IAppData db) { this.db = db; } // GET: Lunches public ActionResult Index() { var model = db.GetAllLunches(); return View(model); } public ActionResult Details(int id) { var model = db.GetLunch(id); if (model == null) { return View("NotFound"); } return View(model); } [HttpGet] public ActionResult Create() { return View(); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create(Lunch lunch) { if (ModelState.IsValid) { db.CreateLunch(lunch); return RedirectToAction("Details", new { id = lunch.Id }); } return View(); } [HttpGet] public ActionResult Edit(int id) { var model = db.GetLunch(id); if (model == null) { return NotFound(); } return View(model); } [HttpPost] public ActionResult Edit(Lunch lunch) { if (ModelState.IsValid) { db.UpdateLunch(lunch); TempData["Message"] = "You have saved the lunch!"; return RedirectToAction("Details", new { id = lunch.Id }); } return View(); } [HttpGet] public ActionResult Delete(int id) { var model = db.GetLunch(id); if (model == null) { return NotFound(); } return View(model); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult Delete(Lunch lunch) { db.DeleteLunch(lunch.Id); return RedirectToAction("Index"); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; [RequireComponent(typeof(GenericTextFlashingScript))] public class TemperatureWarningTextScript : MonoBehaviour { public static TemperatureWarningTextScript MainInstance; private GenericTextFlashingScript flashingScript; private void Awake() { flashingScript = GetComponent<GenericTextFlashingScript>(); MainInstance = this; Hide(); } private void OnDestroy() { MainInstance = null; } public static void SetFlashRate(float flashRate) { if (!MainInstance) return; MainInstance.flashingScript.SetFlashRate(flashRate); } public static void Hide() { if (MainInstance) MainInstance.gameObject.SetActive(false); } public static void Show() { if (MainInstance) MainInstance.gameObject.SetActive(true); } }
 using Xamarin.Forms; namespace RRExpress.Express.Views.Shared { public partial class OrderItemSimpleView : ContentPage { public OrderItemSimpleView() { InitializeComponent(); } } }
namespace Alabo.Framework.Tasks.Queues.Models { public interface ITaskModule { //TODO 9月重构注释 //TaskContext Context { get; } //ExecuteResult<ITaskResult[]> Execute(TaskParameter parameter); } }
namespace Visitor { public interface INotification { void Execute(IOperation operation); } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; using API; using Newtonsoft.Json; namespace DataSoftAPI.Controllers { public class RecordController : Controller { WebClient client = new WebClient(); string adresse = @"https://public.opendatasoft.com/api/records/1.0/search/?dataset=crimes-et-delits-enregistres-par-les-forces-de-securite-en-2016-par-departement&facet=departement&facet=libelle_departement&refine.departement="; public ActionResult SelectDep() { return View(); } // GET: Record public ActionResult Index(string Departement) { var json = client.DownloadString(adresse+Departement); var obj = JsonConvert.DeserializeObject<RootObject>(json); //Record listRecord obj.records.ToList(); return View(obj.records); } // GET: Record/Details/5 public ActionResult Details(int id) { return View(); } // GET: Record/Create public ActionResult Create() { return View(); } // POST: Record/Create [HttpPost] public ActionResult Create(FormCollection collection) { try { // TODO: Add insert logic here return RedirectToAction("Index"); } catch { return View(); } } // GET: Record/Edit/5 public ActionResult Edit(int id) { return View(); } // POST: Record/Edit/5 [HttpPost] public ActionResult Edit(int id, FormCollection collection) { try { // TODO: Add update logic here return RedirectToAction("Index"); } catch { return View(); } } // GET: Record/Delete/5 public ActionResult Delete(int id) { return View(); } // POST: Record/Delete/5 [HttpPost] public ActionResult Delete(int id, FormCollection collection) { try { // TODO: Add delete logic here return RedirectToAction("Index"); } catch { return View(); } } } }
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 Kalkulator { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { textBox1.Clear(); textBox2.Clear(); lblHasil.Text = ""; } private void button1_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(textBox1.Text) || string.IsNullOrEmpty(textBox2.Text)) { MessageBox.Show("Masukkan Bilangan Terlebih Dahulu"); } else { int a, b, c; a = int.Parse(this.textBox1.Text); b = int.Parse(this.textBox2.Text); c = a + b; this.lblHasil.Text = c.ToString(); } } private void button2_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(textBox1.Text) || string.IsNullOrEmpty(textBox2.Text)) { MessageBox.Show("Masukkan Bilangan Terlebih Dahulu"); } else { int a, b, c; a = int.Parse(this.textBox1.Text); b = int.Parse(this.textBox2.Text); c = a - b; this.lblHasil.Text = c.ToString(); } } private void button3_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(textBox1.Text) || string.IsNullOrEmpty(textBox2.Text)) { MessageBox.Show("Masukkan Bilangan Terlebih Dahulu"); } else { int a, b, c; a = int.Parse(this.textBox1.Text); b = int.Parse(this.textBox2.Text); c = a * b; this.lblHasil.Text = c.ToString(); } } private void button4_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(textBox1.Text) || string.IsNullOrEmpty(textBox2.Text)) { MessageBox.Show("Masukkan Bilangan Terlebih Dahulu"); } else { int a, b, c; a = int.Parse(this.textBox1.Text); b = int.Parse(this.textBox2.Text); c = a / b; this.lblHasil.Text = c.ToString(); } } private void button5_Click(object sender, EventArgs e) { textBox1.Clear(); textBox2.Clear(); lblHasil.Text = ""; } } }
using System.Threading.Tasks; using SulsApp; using Work.MVC; namespace SlusApp { class Program { static async Task Main(string[] args) { await WebHost.StartAsync(new Startup()); } } }
using System; namespace AlgoReines { class MainClass { public static void Main (string[] args) { Console.Out.Write("Entrez la taille du plateau : "); int taille = Convert.ToInt32(Console.In.ReadLine()); JeuEchec jeu = new JeuEchec(taille); jeu.Resoudre(); Console.Out.Write ("Appuyez sur une touche pour terminer..."); Console.Read(); } } }
using Alabo.Cloud.Shop.Favorites.Domain.Entities; using Alabo.Datas.UnitOfWorks; using Alabo.Domains.Repositories; using MongoDB.Bson; namespace Alabo.Cloud.Shop.Favorites.Domain.Repositories { public class FavoriteRepository : RepositoryMongo<Favorite, ObjectId>, IFavoriteRepository { public FavoriteRepository(IUnitOfWork unitOfWork) : base(unitOfWork) { } } }
using System; using System.Diagnostics.Tracing; namespace Log.Api.Models { public class EventLog { public string InstanceName { get; set; } public Guid ProviderId { get; set; } public string ProviderName { get; set; } public int EventId { get; set; } public EventKeywords EventKeywords { get; set; } public EventLevel Level { get; set; } public EventOpcode Opcode { get; set; } public EventTask Task { get; set; } public DateTime Timestamp { get; set; } public byte Version { get; set; } public string FormattedMessage { get; set; } public string Payload { get; set; } public Guid ActivityId { get; set; } public Guid RelatedActivityId { get; set; } public int ProcessId { get; set; } public int ThreadId { get; set; } } }
using System.ComponentModel.DataAnnotations; using System.Text.Json.Serialization; using MediatR; using Microsoft.AspNetCore.Mvc; namespace Justa.Job.Backend.Api.Application.MediatR.Requests { public class ChangeUserPasswordRequest : IRequest<IActionResult> { [JsonIgnore] public string UserName { get; set; } [Required(AllowEmptyStrings = false, ErrorMessage = "CurrentUserPassword is required.")] [StringLength(100, ErrorMessage = "CurrentUserPassword Must be between 6 and 100 characters", MinimumLength = 6)] [DataType(DataType.Password)] public string CurrentUserPassword { get; set; } [Required(AllowEmptyStrings = false, ErrorMessage = "NewPassword is required.")] [StringLength(100, ErrorMessage = "NewPassword Must be between 6 and 100 characters", MinimumLength = 6)] [DataType(DataType.Password)] public string NewPassword { get; set; } } }
using System; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using CirAnime.Pages; using Microsoft.Extensions.FileProviders; using tusdotnet; using tusdotnet.Models; using tusdotnet.Stores; using tusdotnet.Interfaces; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.OAuth; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Authentication.Cookies; using System.Security.Claims; using System.Net.Http; using System.Net.Http.Headers; using System.Text.Json; using Microsoft.EntityFrameworkCore; using CirAnime.Data; using System.Linq; using System.IO; using CirAnime.Models; using CirAnime.Services; namespace CirAnime { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddHttpContextAccessor(); services.AddRazorPages(); services.AddRouting(); services.AddTransient<ICarService, CarService>(); services.AddAuthentication(options => { // If an authentication cookie is present, use it to get authentication information options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme; // If authentication is required, and no cookie is present, use Okta (configured below) to sign in options.DefaultChallengeScheme = "Discord"; }) .AddCookie() // cookie authentication middleware first .AddOAuth("Discord", options => { // Oauth authentication middleware is second //var oktaDomain = Configuration.GetValue<string>("Okta:OktaDomain"); // When a user needs to sign in, they will be redirected to the authorize endpoint //options.AuthorizationEndpoint = $"{oktaDomain}/oauth2/default/v1/authorize"; options.AuthorizationEndpoint = "https://discordapp.com/api/oauth2/authorize"; // Okta's OAuth server is OpenID compliant, so request the standard openid // scopes when redirecting to the authorization endpoint //options.Scope.Add("openid"); //options.Scope.Add("profile"); options.Scope.Add("identify"); // After the user signs in, an authorization code will be sent to a callback // in this app. The OAuth middleware will intercept it options.CallbackPath = new PathString("/discord-login"); // The OAuth middleware will send the ClientId, ClientSecret, and the // authorization code to the token endpoint, and get an access token in return options.ClientId = Configuration.GetValue<string>("Discord:AppId"); options.ClientSecret = Configuration.GetValue<string>("Discord:AppSecret"); options.TokenEndpoint = "https://discordapp.com/api/oauth2/token"; // Below we call the userinfo endpoint to get information about the user options.UserInformationEndpoint = "https://discordapp.com/api/users/@me"; // Describe how to map the user info we receive to user claims options.ClaimActions.MapJsonKey(ClaimTypes.NameIdentifier, "id"); options.ClaimActions.MapJsonKey(ClaimTypes.Name, "username"); //options.ClaimActions.MapJsonKey(ClaimTypes.Email, "email"); options.Events = new OAuthEvents { OnCreatingTicket = async context => { // Get user info from the userinfo endpoint and use it to populate user claims var request = new HttpRequestMessage(HttpMethod.Get, context.Options.UserInformationEndpoint); request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", context.AccessToken); var response = await context.Backchannel.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, context.HttpContext.RequestAborted); response.EnsureSuccessStatusCode(); var user = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); context.RunClaimActions(user.RootElement); } }; }); var physicalProvider = new PhysicalFileProvider(Configuration.GetValue<string>("FileUploadPath")); services.AddSingleton<IFileProvider>(physicalProvider); services.AddDbContext<CirAnimeContext>(options => options.UseSqlServer(Configuration.GetConnectionString("CirAnimeContext"))); services.AddScoped<MyCustomTusConfiguration>(); } private async Task ProcessFile(ITusFile file) { return; } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env, CirAnimeContext dbContext) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseAuthentication(); app.UseTus( cont => cont.RequestServices.GetService<MyCustomTusConfiguration>() ); // app.UseTus(CreateTusConfiguration); app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}"); endpoints.MapRazorPages(); }); } /* private DefaultTusConfiguration ConfigureTus(HttpContext httpContext) { return new DefaultTusConfiguration { Store = new TusDiskStore(Configuration.GetValue<string>("FileUploadPath")), UrlPath = "/uploadTus",// + httpContext.User.Identity, Events = new tusdotnet.Models.Configuration.Events { OnFileCompleteAsync = async eventContext => { ITusFile file = await eventContext.GetFileAsync(); Console.WriteLine("file finished"); await ProcessFile(file); }, OnAuthorizeAsync = async eventContext => { eventContext.FailRequest("not authorized"); } } }; } */ public DefaultTusConfiguration CreateTusConfiguration(HttpContext httpContext) { if (!httpContext.User.Identity.IsAuthenticated) { return null; } string baseDirectory = Configuration.GetValue<string>("FileUploadPath"); if (!baseDirectory.EndsWith("/")) baseDirectory.Append('/'); string usersubdirectory = httpContext.User.Identity.Name; usersubdirectory = usersubdirectory.Replace('/', '_').Replace("..", "_"); string uploadDirectory = baseDirectory + usersubdirectory + "/"; if (!Directory.Exists(uploadDirectory)) { Directory.CreateDirectory(uploadDirectory); } return new DefaultTusConfiguration { Store = new TusDiskStore(uploadDirectory), UrlPath = "/uploadTus",// + httpContext.User.Identity, Events = new tusdotnet.Models.Configuration.Events { OnFileCompleteAsync = async eventContext => { ITusFile file = await eventContext.GetFileAsync(); var metaData = await file.GetMetadataAsync(eventContext.CancellationToken); string filename = metaData["filename"].GetString(System.Text.Encoding.UTF8); UploadEntry entry = new UploadEntry { OriginalFileName = filename, Owner = httpContext.User.Identity.Name, Title = filename.Contains('.') ? filename.Remove(filename.LastIndexOf('.')) : filename, UploadDate = DateTime.Now }; // dbContext.UploadEntry.Add(entry); Console.WriteLine("file finished"); await ProcessFile(file); }, OnAuthorizeAsync = async eventContext => { //eventContext.FailRequest("not authorized"); }, OnBeforeCreateAsync = async eventContext => { string filename = eventContext.Metadata["filename"].GetString(System.Text.Encoding.UTF8); string filetype = eventContext.Metadata["filetype"].GetString(System.Text.Encoding.UTF8); Console.WriteLine(filename); } } }; } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace SimpleTaskListSPA.Data { //класс определяющий категорию задач public class Category : EntityBase { //имя категории [Required(ErrorMessage = "Введите название")] [StringLength(60, MinimumLength = 3, ErrorMessage = "Название должно быть от 3 до 60 символов")] public string Name { get; set; } = string.Empty; public IEnumerable<TaskItem> TaskItems { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using alg; /* * tags: greedy, stack * Time(n), Space(n) */ namespace leetcode { public class Lc316_Remove_Duplicate_Letters { public string RemoveDuplicateLetters(string s) { if (string.IsNullOrEmpty(s)) return ""; var counts = new int[26]; foreach (var c in s) counts[c - 'a']++; int smallestCharPos = 0; for (int i = 0; i < s.Length; i++) { if (s[smallestCharPos] > s[i]) smallestCharPos = i; if (--counts[s[i] - 'a'] == 0) break; // prefix is duplicate } var rs = s.Substring(smallestCharPos + 1).Replace(s[smallestCharPos].ToString(), ""); return s[smallestCharPos] + RemoveDuplicateLetters(rs); } public string RemoveDuplicateLettersStack(string s) { if (string.IsNullOrEmpty(s)) return ""; var counts = new int[26]; foreach (var c in s) counts[c - 'a']++; var visited = new bool[26]; var stack = new Stack<char>(); foreach (var c in s) { counts[c - 'a']--; if (visited[c - 'a']) continue; // there is another top char later while (stack.Count > 0 && c < stack.Peek() && counts[stack.Peek() - 'a'] > 0) { visited[stack.Pop() - 'a'] = false; // will visit later } stack.Push(c); visited[c - 'a'] = true; } var cs = new char[stack.Count]; for (int i = cs.Length - 1; i >= 0; i--) cs[i] = stack.Pop(); return new string(cs); } public void Test() { Console.WriteLine(RemoveDuplicateLetters("bcabc") == "abc"); Console.WriteLine(RemoveDuplicateLettersStack("bcabc") == "abc"); Console.WriteLine(RemoveDuplicateLetters("cbacdcbc") == "acdb"); Console.WriteLine(RemoveDuplicateLettersStack("cbacdcbc") == "acdb"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using System.Threading.Tasks; using SmartHome.Service; namespace SmartHome.Droid.Common { public static class Util { static bool isCheckController = false; public async static Task<bool> IsCheckController() { //bool result = false; System.Collections.ArrayList arr = new System.Collections.ArrayList(); System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient(); for (int i = 1; i <= 253; i++) { IAsyncResult iaResult = client.BeginConnect("192.168.0." + i.ToString(), 3000, null, null); iaResult.AsyncWaitHandle.WaitOne(200, false); if (client.Connected) { isCheckController = await APIManager.GetHello("192.168.0." + i); if (isCheckController) { arr.Add("192.168.0." + i); } break; } } return isCheckController; } } }
using UnityEngine; using System.Collections; public class DestroyObject : MonoBehaviour { void Start() { Destroy(this.gameObject,1.5f); } }
namespace JhinBot.Interface { public interface IMessageFormatter { string GetFormattedMessage(string msg); } }
using CC.Utilities.Services; namespace CC.Mobile.Services { public interface IDeviceService:IService { PhoneIdentification DeviceInfo{ get; } PlatformType PlatformType { get; } string PlatformVersionNumber{get; } bool IsOnline{get;} } public class PhoneIdentification { public virtual string SerialNumber { get; set; } public virtual PlatformType PlatformType { get; set; } public virtual string PlatformVersion { get; set; } public virtual string DeviceType { get; set; } } public enum PlatformType { Unknown = 0, WindowsMobile = 1, Android = 2, IOS = 3, Web = 4, Nunit = 5 } }
using System; using System.Diagnostics; using System.Runtime.CompilerServices; using Windows.UI.Popups; namespace curr.Models { public class Date { public int Day { get; set; } public int Month { get; set; } public int Year { get; set; } public override string ToString() { return Year + "-" + Day + "-" + Month; } } public class Helper { public static void TraceMessage(string message, [CallerMemberName] string memberName = "", [CallerFilePath] string sourceFilePath = "", [CallerLineNumber] int sourceLineNumber = 0) { Debug.WriteLine("message: " + message); Debug.WriteLine("member name: " + memberName); Debug.WriteLine("source file path: " + sourceFilePath); Debug.WriteLine("source line number: " + sourceLineNumber); } public static async void Message(string info) { var dialog = new MessageDialog(info); await dialog.ShowAsync(); } } }
namespace UnityAtoms { /// <summary> /// Interface for retrieving a Variable. /// </summary> public interface IVariable<T> { T Variable { get; } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using IsoTools; namespace Caapora.Pathfinding { [ExecuteInEditMode] public class Grid : MonoBehaviour { public IsoWorld world; public LayerMask unwalkableMask; public Vector3 gridWorldSize; public float nodeRadius; Node[,] grid; public List<Node> path; float nodeDiameter; int gridSizeX, gridSizeY; void Start() { world = GameObject.Find("Player/Camera").GetComponent<IsoWorld>(); nodeDiameter = nodeRadius*2; gridSizeX = Mathf.RoundToInt(gridWorldSize.x/nodeDiameter); gridSizeY = Mathf.RoundToInt(gridWorldSize.y/nodeDiameter); CreateGrid(); } void CreateGrid() { // Cria um grade vazia com o tamanho passador por parametros grid = new Node[gridSizeX,gridSizeY]; // Pega a posição Base Vector3 worldBottomLeft = GetComponent<IsoObject>().position; // Popula a grade com as posições de acordo com o código for (int x = 0; x < gridSizeX; x ++) { for (int y = 0; y < gridSizeY; y ++) { // Gera a grade baseado nas posições isometricas de 0,0 à n,n Vector3 worldPoint = worldBottomLeft + new Vector3(x, y, 0); // Converte posição para isometrico var newWorldPoint = world.IsoToScreen(worldPoint); // Caso haja um colisão com algum elemento do tipo unwalkableMask passado como parametro seta a variavel walkable para true bool walkable = (Physics2D.OverlapCircle(newWorldPoint, 0.2f, unwalkableMask) == false); // popula a grade com o nó grid[x,y] = new Node(walkable, newWorldPoint, x,y); } } } protected bool IsDiagonal(int x, int y) { if (x != 0 && y != 0) return true; return false; } // retorna um vizinho de cada vez respeitando as restrições de limites de mapa public List<Node> GetNeighbours(Node node) { List<Node> neighbours = new List<Node>(); // Verifica as posições vizinhas que são de -1 à 1 for (int x = -1; x <= 1; x++) { for (int y = -1; y <= 1; y++) { // exclui a própria posição ou diagonal if ((x == 0 && y == 0) || IsDiagonal(x,y)) continue; int checkX = node.gridX + x; int checkY = node.gridY + y; // respeita os limites do mapa e exclui posição do proprio elemento if (checkX >= 0 && checkX < gridSizeX && checkY >= 0 && checkY < gridSizeY) { neighbours.Add(grid[checkX,checkY]); } } } return neighbours; } // worldPosition: posição do objeto alvo no formato isometrico // gridWorldSize: valor dos parametros // Retorna: posição do objeto na grade public Node NodeFromWorldPoint(Vector3 worldPosition) { // Distancia entr float percentX = (worldPosition.x + gridWorldSize.x/2) / gridWorldSize.x; float percentY = (worldPosition.y + gridWorldSize.y/2) / gridWorldSize.y; //Debug.Log("Valor de percenty: " + percentY); percentX = Mathf.Clamp01(percentX); percentY = Mathf.Clamp01(percentY); int x = Mathf.RoundToInt((gridSizeX-1) * percentX); int y = Mathf.RoundToInt((gridSizeY-1) * percentY); // está utilizando coordenadas isometricas return grid[x,y]; } void OnDrawGizmos() { Gizmos.color = Color.cyan; if (grid != null) { foreach (Node n in grid) { Gizmos.color = (n.walkable) ? Color.white : Color.red; if (path != null) if (path.Contains(n)) { Gizmos.color = Color.black; } Gizmos.DrawCube(n.worldPosition, Vector3.one * (nodeDiameter - .1f)); } } } } // end Grid } // namesapace
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using TellStoryTogether.Models; namespace TellStoryTogether.Controllers { public class ScheduleController : Controller { readonly UsersContext _userContext = new UsersContext(); // // GET: /Schedule?identifier=1 public ActionResult Index(string identifier) { string result = ""; try { if (User.Identity.IsAuthenticated) { if (identifier == "1") { /*List<Language> all = _userContext.Languages.Where(p=>p.LanguageId>4).ToList(); _userContext.Languages.RemoveRange(all); _userContext.SaveChanges(); foreach (Comment comment in all) { comment.Time = DateTime.Now; } _userContext.SaveChanges(); result = "done";*/ } else { result = "incorrect identifier"; } } } catch (Exception) { result = "unhandled exception"; } ViewBag.result = result; return View(); } } }
using System; namespace EPI.PrimitiveTypes { /// <summary> /// Write a function that takes a non-negative number, x as input and /// returns y <> x such that y has the same weight as x and the difference /// between x and y is minimzed. Assume x is not 0 or all 1s /// </summary> /// <remarks> Two numbers have the same weight if they have the same number of 1s</remarks> public static class ClosestIntSameWeight { public static Int64 FindClosestNumberWithSameWeight(Int64 number) { for (int i = 1; i < 64; i++) { if (((number >> i-1) & 1) != ((number >> i) & 1)) { number ^= (1 << i - 1) | (1 << i); return number; } } throw new InvalidOperationException("all bits are equal"); } } }
using System; using System.Threading.Tasks; using Aloha.ShopSystem; using UnityEngine; public class CollectionPurchaseController { public event Action<Product> OnProductPurchased; public Action<int, int, int> FirebaseEvent; public Action<int> FirebaseAdEvent; private PurchaseController _purchaseController = new PurchaseController(); private bool _purchaseLock; public async Task<PurchaseController.Result> ProgressPurchase(Product product) { if (_purchaseLock) return PurchaseController.Result.PaymentFailed; _purchaseLock = true; var result = await _purchaseController.ProgressPurchase(product); OnProductPurchased?.Invoke(product); if (product.Id == 1) { FireBase.Instance.GetCoin(0, 0, 200); FireBase.Instance.Reward("coin200"); CoinManager.Instance.InitCoinText(); } _purchaseLock = false; return result; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProyectoArchivos { class HashDinamico_SubBloqueInformacion { // private long dirsub_bloque; // private int valor; // private long dirregistro; //CONSTRUCTOR public HashDinamico_SubBloqueInformacion() { } // public long DirSub_Bloque { get { return dirsub_bloque; } set { dirsub_bloque = value; } } // public int Valor { get { return valor; } set { valor = value; } } // public long DirRegistro { get { return dirregistro; } set { dirregistro = value; } } } }
using System.Linq; using System.Security.Cryptography; using System.Text; using ApartmentApps.Api; using ApartmentApps.Api.Modules; using ApartmentApps.Api.Services; using ApartmentApps.Api.ViewModels; using ApartmentApps.Data; namespace ApartmentApps.Portal.Controllers { public class UserMapper : BaseMapper<ApplicationUser, UserBindingModel> { private readonly IBlobStorageService _blobService; public UserMapper(IBlobStorageService blobService, IUserContext userContext, IModuleHelper moduleHelper) : base(userContext, moduleHelper) { _blobService = blobService; } public override void ToModel(UserBindingModel viewModel, ApplicationUser model) { model.Id = viewModel.Id.ToString(); model.FirstName = viewModel.FirstName; model.LastName = viewModel.LastName; } /// Hashes an email with MD5. Suitable for use with Gravatar profile /// image urls public static string HashEmailForGravatar(string email) { // Create a new instance of the MD5CryptoServiceProvider object. MD5 md5Hasher = MD5.Create(); // Convert the input string to a byte array and compute the hash. byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(email.ToLower().Trim())); // Create a new Stringbuilder to collect the bytes // and create a string. StringBuilder sBuilder = new StringBuilder(); // Loop through each byte of the hashed data // and format each one as a hexadecimal string. for (int i = 0; i < data.Length; i++) { sBuilder.Append(data[i].ToString("x2")); } return sBuilder.ToString(); // Return the hexadecimal string. } public override void ToViewModel(ApplicationUser user, UserBindingModel viewModel) { if (user == null) return; viewModel.Id = user.Id; viewModel.ImageUrl = _blobService.GetPhotoUrl(user.ImageUrl) ?? $"http://www.gravatar.com/avatar/{HashEmailForGravatar(user.Email.ToLower())}.jpg"; viewModel.ImageThumbnailUrl = _blobService.GetPhotoUrl(user.ImageThumbnailUrl) ?? $"http://www.gravatar.com/avatar/{HashEmailForGravatar(user.Email.ToLower())}.jpg"; viewModel.FirstName = user.FirstName; viewModel.LastName = user.LastName; viewModel.FullName = user.FirstName + " " + user.LastName; viewModel.UnitName = user.Unit?.Name; viewModel.BuildingName = user.Unit?.Building.Name; viewModel.Title = $"{viewModel.FullName}"; if (user.Unit != null) viewModel.Title+=$" [ {user.Unit?.Building.Name} {user.Unit?.Name} ]"; viewModel.IsTenant = user.Unit != null; viewModel.PhoneNumber = user.PhoneNumber; viewModel.Email = user.Email; viewModel.Address = user?.Address; viewModel.City = user?.City; viewModel.PostalCode = user?.PostalCode; viewModel.Roles = user.Roles.Select(p => p.RoleId).ToArray(); viewModel.Archived = user.Archived; } } }
namespace CyberSoldierServer.Dtos.EjectDtos { public class CampPoolDto { public int Id { get; set; } public int BaseId { get; set; } public uint Capacity { get; set; } public uint CurrentValue { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class StartGame : MonoBehaviour { private void Start() { if (PlayerPrefs.GetInt("Lvl1Won", 0) == 1) LevelManager.Instance.SetLevelWon(0); if (PlayerPrefs.GetInt("Lvl2Won", 0) == 1) LevelManager.Instance.SetLevelWon(1); if (PlayerPrefs.GetInt("Lvl3Won", 0) == 1) LevelManager.Instance.SetLevelWon(2); if (PlayerPrefs.GetInt("Lvl4Won", 0) == 1) LevelManager.Instance.SetLevelWon(3); if (PlayerPrefs.GetInt("Lvl5Won", 0) == 1) LevelManager.Instance.SetLevelWon(4); if (PlayerPrefs.GetInt("Lvl6Won", 0) == 1) LevelManager.Instance.SetLevelWon(5); if (PlayerPrefs.GetInt("Lvl7Won", 0) == 1) LevelManager.Instance.SetLevelWon(6); if (PlayerPrefs.GetInt("Lvl8Won", 0) == 1) LevelManager.Instance.SetLevelWon(7); if (PlayerPrefs.GetInt("Lvl9Won", 0) == 1) LevelManager.Instance.SetLevelWon(8); if (PlayerPrefs.GetInt("Star1.1", 0) == 1) LevelManager.Instance.SetStarTaken(0, 0); if (PlayerPrefs.GetInt("Star1.2", 0) == 1) LevelManager.Instance.SetStarTaken(0, 1); if (PlayerPrefs.GetInt("Star1.3", 0) == 1) LevelManager.Instance.SetStarTaken(0, 2); if (PlayerPrefs.GetInt("Star2.1", 0) == 1) LevelManager.Instance.SetStarTaken(1, 0); if (PlayerPrefs.GetInt("Star2.2", 0) == 1) LevelManager.Instance.SetStarTaken(1, 1); if (PlayerPrefs.GetInt("Star2.3", 0) == 1) LevelManager.Instance.SetStarTaken(1, 2); if (PlayerPrefs.GetInt("Star3.1", 0) == 1) LevelManager.Instance.SetStarTaken(2, 0); if (PlayerPrefs.GetInt("Star3.2", 0) == 1) LevelManager.Instance.SetStarTaken(2, 1); if (PlayerPrefs.GetInt("Star3.3", 0) == 1) LevelManager.Instance.SetStarTaken(2, 2); if (PlayerPrefs.GetInt("Star4.1", 0) == 1) LevelManager.Instance.SetStarTaken(3, 0); if (PlayerPrefs.GetInt("Star4.2", 0) == 1) LevelManager.Instance.SetStarTaken(3, 1); if (PlayerPrefs.GetInt("Star4.3", 0) == 1) LevelManager.Instance.SetStarTaken(3, 2); if (PlayerPrefs.GetInt("Star5.1") == 1) LevelManager.Instance.SetStarTaken(4, 0); if (PlayerPrefs.GetInt("Star5.2", 0) == 1) LevelManager.Instance.SetStarTaken(4, 1); if (PlayerPrefs.GetInt("Star5.3", 0) == 1) LevelManager.Instance.SetStarTaken(4, 2); if (PlayerPrefs.GetInt("Star6.1", 0) == 1) LevelManager.Instance.SetStarTaken(5, 0); if (PlayerPrefs.GetInt("Star6.2", 0) == 1) LevelManager.Instance.SetStarTaken(5, 1); if (PlayerPrefs.GetInt("Star6.3", 0) == 1) LevelManager.Instance.SetStarTaken(5, 2); if (PlayerPrefs.GetInt("Star7.1", 0) == 1) LevelManager.Instance.SetStarTaken(6, 0); if (PlayerPrefs.GetInt("Star7.2", 0) == 1) LevelManager.Instance.SetStarTaken(6, 1); if (PlayerPrefs.GetInt("Star7.3", 0) == 1) LevelManager.Instance.SetStarTaken(6, 2); if (PlayerPrefs.GetInt("Star8.1", 0) == 1) LevelManager.Instance.SetStarTaken(7, 0); if (PlayerPrefs.GetInt("Star8.2", 0) == 1) LevelManager.Instance.SetStarTaken(7, 1); if (PlayerPrefs.GetInt("Star8.3", 0) == 1) LevelManager.Instance.SetStarTaken(7, 2); if (PlayerPrefs.GetInt("Star9.1", 0) == 1) LevelManager.Instance.SetStarTaken(8, 0); if (PlayerPrefs.GetInt("Star9.2", 0) == 1) LevelManager.Instance.SetStarTaken(8, 1); if (PlayerPrefs.GetInt("Star9.3", 0) == 1) LevelManager.Instance.SetStarTaken(8, 2); } }
namespace SpeedRacing { using System; using System.Collections.Generic; using System.Linq; public class StartUp { static void Main(string[] args) { int numberOfCars = int.Parse(Console.ReadLine()); var cars = new List<Car>(); for (int i = 0; i < numberOfCars; i++) { var carInfo = Console.ReadLine().Split(); var currentCar = new Car(carInfo[0],double.Parse(carInfo[1]),double.Parse(carInfo[2])); cars.Add(currentCar); } var command = Console.ReadLine(); while (command != "End") { var tokens = command.Split(); var carModel = tokens[1]; var distance = double.Parse(tokens[2]); try { var car = cars.First(c => c.Model == carModel); car.Drive(distance); } catch (Exception e) { Console.WriteLine(e.Message); } command = Console.ReadLine(); } foreach (var car in cars) { Console.WriteLine($"{car.Model} {car.FuelAmount:F2} {car.TravelledDistance}"); } } } }
using Xamarin.Forms; namespace Soccer.Prism.Views { public partial class TournamentTabbedPage : TabbedPage { public TournamentTabbedPage() { InitializeComponent(); } } }
//using System; //using System.Collections.Generic; //using System.Linq; //using System.Threading.Tasks; //using DFC.ServiceTaxonomy.Neo4j.Configuration; //using Microsoft.Extensions.Options; //using Neo4j.Driver; //namespace DFC.ServiceTaxonomy.IntegrationTests.Helpers //{ // public class TestNeoGraphDatabase : IDisposable // { // private readonly IDriver _driver; // public TestNeoGraphDatabase(IOptionsMonitor<Neo4jOptions> neo4jOptionsMonitor) // { // // Each IDriver instance maintains a pool of connections inside, as a result, it is recommended to only use one driver per application. // // It is considerably cheap to create new sessions and transactions, as sessions and transactions do not create new connections as long as there are free connections available in the connection pool. // // driver is thread-safe, while the session or the transaction is not thread-safe. // //todo: add configuration/settings menu item/page so user can enter this // var neo4jOptions = neo4jOptionsMonitor.CurrentValue; // //todo: pass logger, see https://github.com/neo4j/neo4j-dotnet-driver // // o => o.WithLogger(logger) // var endpointToTest = neo4jOptions.Endpoints.FirstOrDefault(x => x.Enabled); // if(endpointToTest == null) // { // throw new InvalidOperationException("No enabled endpoint in Neo4j configuration."); // } // _driver = GraphDatabase.Driver(endpointToTest.Uri, AuthTokens.Basic(endpointToTest.Username, endpointToTest.Password)); // } // public async Task<IGraphDatabaseTestRun> StartTestRun() // { // GraphDatabaseTestRun testRun = new GraphDatabaseTestRun(); // await testRun.Initialise(_driver); // return testRun; // } // public void Dispose() // { // _driver?.Dispose(); // } // private class GraphDatabaseTestRun : IGraphDatabaseTestRun // { // private IAsyncSession? _session; // private IAsyncTransaction? _transaction; // public async Task Initialise(IDriver driver) // { // _session = driver.AsyncSession(); // _transaction = await _session.BeginTransactionAsync(); // } // public async Task<List<T>> RunReadQuery<T>(Query query, Func<IRecord, T> operation) // { // if (_transaction == null) // throw new InvalidOperationException($"{nameof(GraphDatabaseTestRun)} not initialised."); // IResultCursor result = await _transaction.RunAsync(query); // return await result.ToListAsync(operation); // } // #pragma warning disable S4144 // //todo: read/write? can't seems to specify with BeginTransactionAsync? could have 1 read & 1 write transaction? specify write at the session level? remove distinction and just have RunQuery? // public async Task<List<T>> RunWriteQuery<T>(Query query, Func<IRecord, T> operation) // { // if (_transaction == null) // throw new InvalidOperationException($"{nameof(GraphDatabaseTestRun)} not initialised."); // IResultCursor result = await _transaction.RunAsync(query); // return await result.ToListAsync(operation); // } // #pragma warning restore S4144 // public async Task RunWriteQueries(params Query[] queries) // { // if (_transaction == null) // throw new InvalidOperationException($"{nameof(GraphDatabaseTestRun)} not initialised."); // foreach (Query query in queries) // { // await _transaction.RunAsync(query); // } // } // public async Task RunWriteQueriesWithCommit(params Query[] queries) // { // if (_transaction == null) // throw new InvalidOperationException($"{nameof(GraphDatabaseTestRun)} not initialised."); // foreach (Query query in queries) // { // await _transaction.RunAsync(query); // } // await _transaction!.CommitAsync(); // _transaction = await _session!.BeginTransactionAsync(); // } // public void Dispose() // { // // if you want to see the results of a test in neo's browser... // //(_transaction!.CommitAsync()).GetAwaiter().GetResult(); // _session?.CloseAsync(); // } // } // } //}
using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace Microsoft.ServiceFabric.Data.Collections { internal interface ICommitable { Task CommitTransactionAsync(Transaction tx); } }
namespace BeverageLabels { using System; public class StartUp { public static void Main() { string typeCola = Console.ReadLine(); double volume = double.Parse(Console.ReadLine()); double energyBy100 = double.Parse(Console.ReadLine()); double sugerBy100 = double.Parse(Console.ReadLine()); double energy = energyBy100 * (volume / 100); double sugar = sugerBy100 * (volume / 100); Console.WriteLine($"{volume}ml {typeCola}:"); Console.WriteLine($"{energy}kcal, {sugar}g sugars"); } } }
using System; namespace ThoughtWorks.QRCode.ExceptionHandler { public class VersionInformationException:System.ArgumentException { } }
using System.Threading; using System.Threading.Tasks; using AutoFixture; using MediatR; using Moq; using NUnit.Framework; using SFA.DAS.CommitmentsV2.Api.Client; using SFA.DAS.CommitmentsV2.Api.Types.Responses; using SFA.DAS.CommitmentsV2.Types; using SFA.DAS.ProviderCommitments.Queries.GetTrainingCourses; using SFA.DAS.ProviderCommitments.Web.Mappers; namespace SFA.DAS.ProviderCommitments.Web.UnitTests.Mappers { [TestFixture] public class WhenIMapToSelectCourseViewModel { private SelectCourseViewModelMapperHelper _mapper; private Mock<IMediator> _mediatorMock; private Mock<ICommitmentsApiClient> _commitmentsClientMock; private AccountLegalEntityResponse _ale; private GetTrainingCoursesQueryResponse _trainingCourses; private int _accountLegalEntityId; private string _courseCode; private bool? _isOnFlexiPaymentsPilot; [SetUp] public void Arrange() { var fixture = new Fixture(); _accountLegalEntityId = fixture.Create<int>(); _courseCode = fixture.Create<string>(); _isOnFlexiPaymentsPilot = fixture.Create<bool?>(); _ale = fixture.Create<AccountLegalEntityResponse>(); _trainingCourses = fixture.Create<GetTrainingCoursesQueryResponse>(); var includeFrameworks = _ale.LevyStatus != ApprenticeshipEmployerType.NonLevy; _mediatorMock = new Mock<IMediator>(); _mediatorMock.Setup(x => x.Send(It.Is<GetTrainingCoursesQueryRequest>(p => p.IncludeFrameworks == includeFrameworks), It.IsAny<CancellationToken>())) .ReturnsAsync(_trainingCourses); _commitmentsClientMock = new Mock<ICommitmentsApiClient>(); _commitmentsClientMock.Setup(x => x.GetAccountLegalEntity(_accountLegalEntityId, It.IsAny<CancellationToken>())).ReturnsAsync(_ale); _mapper = new SelectCourseViewModelMapperHelper(_commitmentsClientMock.Object, _mediatorMock.Object); } [Test] public async Task ThenCourseCodeIsMappedCorrectly() { var result = await _mapper.Map(_courseCode, _accountLegalEntityId, _isOnFlexiPaymentsPilot); Assert.AreEqual(_courseCode, result.CourseCode); } [Test] public async Task ThenCoursesAreReturnedCorrectly() { var result = await _mapper.Map(_courseCode, _accountLegalEntityId, _isOnFlexiPaymentsPilot); Assert.AreEqual(_trainingCourses.TrainingCourses, result.Courses); } [Test] public async Task ThenIsOnFlexiPaymentsPilotIsMappedCorrectly() { var result = await _mapper.Map(_courseCode, _accountLegalEntityId, _isOnFlexiPaymentsPilot); Assert.AreEqual(_isOnFlexiPaymentsPilot, result.IsOnFlexiPaymentsPilot); } } }
using System; using System.Linq.Expressions; using System.Threading.Tasks; using MeeToo.DataAccess.Contracts; namespace MeeToo.DataAccess.DocumentDb { public interface IDocumentDbQquery<T> : IQuery<T> { Task<T> FindAsync(string id); IDocumentDbQquery<T> Where(Expression<Func<T, bool>> predicate); IDocumentDbQquery<TResult> Select<TResult>(Expression<Func<T, TResult>> selector); T FirstOrDefault(); T FirstOrDefault(Func<T, bool> predicate); } }
using LuckyMasale.Shared.DTO; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LuckyMasale.DAL.DataProviders { public interface IDeliveryAddressDataProvider : IBaseDataProvider { Task<List<DeliveryAddress>> GetAllDeliveryAddress(); Task<DeliveryAddress> GetDeliveryAddressByOrderID(int id); Task<List<DeliveryAddress>> GetDeliveryAddressByUserID(int id); Task<int> InsertDeliveryAddress(DeliveryAddress deliveryAddress); Task<int> UpdateDeliveryAddress(DeliveryAddress deliveryAddress); } public class DeliveryAddressDataProvider : BaseDataProvider, IDeliveryAddressDataProvider { #region Constructors public DeliveryAddressDataProvider(IDataSourceFactory dataSourceFactory) : base(dataSourceFactory) { } #endregion #region Methods public async Task<List<DeliveryAddress>> GetAllDeliveryAddress() { List<DeliveryAddress> deliveryAddresses = new List<DeliveryAddress>(); try { using (var ds = DataSourceFactory.CreateDataSource()) { deliveryAddresses = await ds.GetResults<DeliveryAddress>("usp_GetAllDeliveryAddress", null); } return deliveryAddresses; } catch (Exception) { return null; } } public async Task<DeliveryAddress> GetDeliveryAddressByOrderID(int id) { DeliveryAddress deliveryAddress = new DeliveryAddress(); try { using (var ds = DataSourceFactory.CreateDataSource()) { deliveryAddress = await ds.GetResult<DeliveryAddress>("usp_GetDeliveryAddressByOrderID", ds.CreateParameter("OrderID", id)); return deliveryAddress; } } catch (Exception) { return null; } } public async Task<List<DeliveryAddress>> GetDeliveryAddressByUserID(int id) { List<DeliveryAddress> deliveryAddresses = new List<DeliveryAddress>(); try { using (var ds = DataSourceFactory.CreateDataSource()) { deliveryAddresses = await ds.GetResults<DeliveryAddress>("usp_GetDeliveryAddressByUserID", ds.CreateParameter("UserID", id)); } return deliveryAddresses; } catch (Exception) { return null; } } public async Task<int> InsertDeliveryAddress(DeliveryAddress deliveryAddress) { int result = 0; try { using (var ds = DataSourceFactory.CreateDataSource()) { result = await ds.ExecuteNonQuery("usp_InsertDeliveryAddress", ds.CreateParameter("UserID", deliveryAddress.UserID), ds.CreateParameter("OrderID", deliveryAddress.OrderID), ds.CreateParameter("Name", deliveryAddress.Name), ds.CreateParameter("Pincode", deliveryAddress.Pincode), ds.CreateParameter("Address", deliveryAddress.Address), ds.CreateParameter("Landmark", deliveryAddress.Landmark), ds.CreateParameter("country", deliveryAddress.country), ds.CreateParameter("state", deliveryAddress.state), ds.CreateParameter("city", deliveryAddress.city), ds.CreateParameter("phone", deliveryAddress.phone)); } return result; } catch (Exception) { return 0; } } public async Task<int> UpdateDeliveryAddress(DeliveryAddress deliveryAddress) { int result = 0; try { using (var ds = DataSourceFactory.CreateDataSource()) { result = await ds.ExecuteNonQuery("usp_UpdateDeliveryAddress", ds.CreateParameter("DeliveryAddressID", deliveryAddress.DeliveryAddessID), ds.CreateParameter("UserID", deliveryAddress.UserID), ds.CreateParameter("OrderID", deliveryAddress.OrderID), ds.CreateParameter("Name", deliveryAddress.Name), ds.CreateParameter("Pincode", deliveryAddress.Pincode), ds.CreateParameter("Address", deliveryAddress.Address), ds.CreateParameter("Landmark", deliveryAddress.Landmark), ds.CreateParameter("country", deliveryAddress.country), ds.CreateParameter("state", deliveryAddress.state), ds.CreateParameter("city", deliveryAddress.city), ds.CreateParameter("phone", deliveryAddress.phone)); } return result; } catch (Exception) { return 0; } } #endregion } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class CardView : MonoBehaviour { internal Card reference; internal Image cardImage; void Start() { cardImage = GetComponent<Image>(); } }
using MAS.Models; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace MAS.Repositories.Interfaces { public interface IEmployeeRepository { Task<List<Employee>> GetAllEmployees(); Task<Employee> GetEmployeeById(int employeeId); } }
using System.CodeDom.Compiler; using System.Collections.Generic; using System.Collections; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.Serialization; using System.Text.RegularExpressions; using System.Text; using System; class Result { // Returns the max difference between two numbers in an array where max = arr[j] - arr[i] and j > i. public static int maxDifference(List<int> arr) { if (listIsDescending(arr)) { return -1; } return calculateMaxDifference(arr); } // Calculates the max difference by keeping track of both the maximum difference and the current minimum number. private static int calculateMaxDifference(List<int> arr) { var maxDiff = arr[1] - arr[0]; var minItem = arr[0]; for (int item = 1; item < arr.Count; item++) { if (arr[item] - minItem > maxDiff) { // Optimization: maxDiff = Math.Max(maxDiff, arr[item] - minItem) maxDiff = arr[item] - minItem; } if (arr[item] < minItem) { // Optimization: minItem = Math.Min(arr[item], minItem) minItem = arr[item]; } } return maxDiff; } // Performs a check to verify if the list is already descending private static bool listIsDescending(List<int> arr) { var descendingArr = arr.OrderByDescending(item => item).ToList(); return arr.SequenceEqual(descendingArr); } } class Solution { public static void Main(string[] args) { TextWriter textWriter = new StreamWriter(@System.Environment.GetEnvironmentVariable("OUTPUT_PATH"), true); int arrCount = Convert.ToInt32(Console.ReadLine().Trim()); List<int> arr = new List<int>(); for (int i = 0; i < arrCount; i++) { int arrItem = Convert.ToInt32(Console.ReadLine().Trim()); arr.Add(arrItem); } int result = Result.maxDifference(arr); textWriter.WriteLine(result); textWriter.Flush(); textWriter.Close(); } }
using System.Linq; namespace Numerology.Models { public class StringAdder : IStringAdder { public StringAdder(ILetterConverter letterConverter) { _letterConverter = letterConverter; } private readonly ILetterConverter _letterConverter; public string Add(string str) { if (str == "") return ""; return SumStringInt(str).ToString(); } private int SumStringInt(string str) { return str .ToLower() .Select(_letterConverter.GetLetterDigit) .Sum(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace BandR { public class ExportObject { public int fileId { get; set; } public string fileName { get; set; } public string fieldType { get; set; } public string fieldName { get; set; } public string fieldValue { get; set; } public bool fieldIsMultiVal { get; set; } } public class CustomRegistrySettings { public string siteUrl { get; set; } public string userName { get; set; } public string passWord { get; set; } public string domain { get; set; } public string isSPOnline { get; set; } public string sourceListName { get; set; } public string destListName { get; set; } public string numItemsToProcess { get;set; } } public class CustFileObj { public int fileId { get; set; } public string fileName { get; set; } public string folderPath { get; set; } public string fullPath { get; set; } public string relFolderPath { get; set; } public string relFullPath { get; set; } public string fileType { get; set; } public int GetLevel() { return relFullPath.ToCharArray().Count(x => x == '/'); } } }
using System; using System.Collections.Generic; using System.Text; namespace SocialWorld.Entities.Concrete { public class Job { public int Id { get; set; } public string Name { get; set; } public DateTime AddedTime { get; set; } = DateTime.Now; public DateTime LastEdit { get; set; } = DateTime.Now; public string Explanation { get; set; } public string PhotoString { get; set; } public bool isActive { get; set; } = true; public int JobTypeId { get; set; } public JobType JobType { get; set; } public int CompanyId { get; set; } public Company Company { get; set; } public List<Applicant> Applicants { get; set; } } }
using System; using System.Collections.Generic; using System.Text; using System.IO; using ICSharpCode.SharpZipLib.Zip; using ICSharpCode.SharpZipLib.Core; using System.Diagnostics; using NSTOX.DataPusher.BOService; namespace NSTOX.DataPusher.Helper { public static class BOFilesHelper { private static DateTime CurrentDateTime { get { return DateTime.Now; //return new DateTime(2012, 04, 24); } } public static string ItemsFile { get { return Path.Combine(ConfigurationHelper.ItemAndDeptFilesPath, string.Format("ITEM{0}", CurrentDateTime.ToString("MMdd.yy"))); } } public static string DepartmentsFile { get { return Path.Combine(ConfigurationHelper.ItemAndDeptFilesPath, string.Format("DEPT{0}", CurrentDateTime.ToString("MMdd.yy"))); } } public static List<string> TransactionFiles { get { List<string> result = new List<string>(); DirectoryInfo dirInfo = new DirectoryInfo(ConfigurationHelper.TransactionsPath); FileInfo[] files = dirInfo.GetFiles("*.XML"); foreach (FileInfo file in files) { result.Add(file.FullName); } return result; } } public static List<string> GetFilePathByType(BOFileType fileType, string filePath = null) { if (filePath != null) { return new List<string> { filePath }; } switch (fileType) { case BOFileType.Items: return new List<string>() { ItemsFile }; case BOFileType.Departments: return new List<string>() { DepartmentsFile }; case BOFileType.Transactions: return TransactionFiles; } return null; } public static byte[] Compress(List<string> files) { if (files == null || files.Count == 0) { return null; } bool atLeastOnFileExists = false; foreach (string file in files) { if (File.Exists(file)) { atLeastOnFileExists = true; break; } } if (!atLeastOnFileExists) return null; int uncompressedSize = 0; int noOfFilesCompressed = 0; using (MemoryStream outputStream = new MemoryStream()) { using (ZipOutputStream zip = new ZipOutputStream(outputStream)) { foreach (string file in files) { if (File.Exists(file)) { noOfFilesCompressed += 1; byte[] content = File.ReadAllBytes(file); uncompressedSize += content.Length; zip.SetLevel(ConfigurationHelper.ZipCompressionLevel); ZipEntry entry = new ZipEntry(file); entry.DateTime = CurrentDateTime; zip.PutNextEntry(entry); StreamUtils.Copy(new MemoryStream(content), zip, new byte[4096]); zip.CloseEntry(); zip.IsStreamOwner = false; } else { Logger.LogInfo(string.Format("Coudn't find file: {0}", file), EventLogEntryType.Warning); } } zip.Close(); outputStream.Position = 0; return outputStream.ToArray(); } } } public static List<byte[]> DeCompress(string filePath) { List<byte[]> result = new List<byte[]>(); if (!File.Exists(filePath)) return result; using (ZipInputStream zip = new ZipInputStream(new FileStream(filePath, FileMode.Open, FileAccess.Read))) { ZipEntry entry = zip.GetNextEntry(); while (entry != null) { using (MemoryStream outputStream = new MemoryStream()) { StreamUtils.Copy(zip, outputStream, new byte[4096]); result.Add(outputStream.ToArray()); } entry = zip.GetNextEntry(); } } return result; } } }
using System; namespace VacationCost { public class VacationCostCalculator { public double DistanceToDestination { get; set; } public decimal CostOfVacation(string transportMethod) { switch (transportMethod) { case "Car": return (decimal) (DistanceToDestination * 1); case "Plane": return (decimal) (DistanceToDestination * 2); default: throw new ArgumentOutOfRangeException(); } } } }
using Mojang.Minecraft.Protocol.Providers; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Mojang.Minecraft.Protocol { //去除参数类型: /[\[\w\]]*?(?<!,) / public partial class EssentialClient { [VarIntUnderlying] public enum LoginNextState { Ping = 1, Login, } /// <summary> /// 以握手开始Ping或登陆 /// </summary> /// <param name="protocolVersion">协议版本</param> /// <param name="serverAddress">服务器地址,可以是主机名(如"localhost")也可以是IP</param> /// <param name="serverPort">端口号,如25565</param> /// <param name="nextState">代表本次握手的目的</param> /// <returns></returns> [PackageSender(0x00, State.Handshaking)] protected async Task Handshake([Variable] int protocolVersion, [Variable] string serverAddress, ushort serverPort, LoginNextState nextState) { await _PackageSenderManager.Send(protocolVersion, serverAddress, serverPort, nextState); switch (nextState) { case LoginNextState.Ping: _ConnectState = State.Status; break; case LoginNextState.Login: _ConnectState = State.Login; break; } } [PackageSender(0x00, State.Status)] protected virtual async Task HandshakeRequest() => await _PackageSenderManager.Send(); [PackageSender(0x00, State.Login)] protected virtual async Task Login([Variable] string name) => await _PackageSenderManager.Send(name); /// <summary> /// 响应服务器的在线请求 /// </summary> /// <param name="keepAlive"></param> /// <returns></returns> [PackageSender(0x00)] protected virtual async Task KeepAlive([Variable] int keepAlive) => await _PackageSenderManager.Send(keepAlive); [PackageSender(0x01, State.Status)] protected virtual async Task Ping(long payload) => await _PackageSenderManager.Send(payload); [PackageSender(0x01, State.Login)] protected virtual async Task ResponseEncryption([VariableCount] byte[] sharedSecret, [VariableCount] byte[] verifyToken) => await _PackageSenderManager.Send(sharedSecret, verifyToken); /// <summary> /// 聊天 /// </summary> /// <param name="message">默认的服务器会检查消息是否以‘/’开头。若不是,则将发送者的名字添加到消息前并将它发送给所有客户端端(包括发送者自己)。如果是以‘/’开头,服务器将认为它是一个指令并尝试处理它。</param> /// <returns></returns> [PackageSender(0x01)] protected virtual async Task Chat([Variable] string message) => await _PackageSenderManager.Send(message); [VarIntUnderlying] public enum EntityUseWay { Interact, Attack, //InteractAt } //TODO: 1.8存在实体用法重载 // /// <summary> /// 攻击或右键实体(比如玩家,马,矿车...) /// <para>原版服务器只会在实体距离玩家不超过4单位长度,并且两者之间视线不受阻碍时,才会处理此数据包;在1.8中若两者之间没有视线,则距离不能超过3.若视线通畅,则距离不能超过6.</para> /// <para>注意在创造模式中,鼠标中间选取是在客户端进行,但它也会发送给服务器一个创造模式物品栏动作数据包.</para> /// </summary> /// <param name="targetEntityId"></param> /// <param name="entityUseWay"></param> /// <returns></returns> [PackageSender(0x02)] protected virtual async Task UseEntity([Variable] int targetEntityId, EntityUseWay entityUseWay) => await _PackageSenderManager.Send(targetEntityId, entityUseWay); /// <summary> /// 改变是飞行状态 /// <para>当从一定高度落下时,跌落伤害会在此项从False变为True时施加在玩家身上. 伤害程度是根据上次此项由True变False时,玩家站立的地点的高度来决定.</para> /// <para>注意:并非只有此数据包会引起跌落伤害计算,其他的几种跟移动相关的数据包也能引发跌落伤害.</para> /// </summary> /// <param name="isOnGround"></param> /// <returns>true为在地上或者在游泳,false为其他情况</returns> [PackageSender(0x03)] protected virtual async Task ChangeOnGroundState(bool isOnGround) => await _PackageSenderManager.Send(isOnGround); /// <summary> /// 更新位置. /// <para>如果头部Y减去脚底Y小于0.1或大于1.65,服务器会以“Illegal Stance”为理由踢出玩家. </para> /// <para> 如果新位置到旧位置(以服务器数据为准)的距离超过100个单位长度的话,玩家会被以"You moved too quickly :( (Hacking?)"为理由踢出.</para> /// <para>此外,如果X或Z的定点数(即浮点数的尾数部分)大于3.2E7D的话,服务器也会以"Illegal position"为理由踢出玩家.</para> /// </summary> /// <param name="x">绝对坐标(即相对世界原点位置)X</param> /// <param name="feetY">玩家脚底的绝对坐标Y.</param> /// <param name="headY">玩家头部的绝对坐标Y. 通常为头部Y坐标减1.62,用来修正玩家的碰撞盒</param> /// <param name="z">绝对坐标Z</param> /// <param name="isOnGround">true为在地上或者在游泳,false为其他情况</param> /// <returns></returns> [PackageSender(0x04)] protected virtual async Task SetPosition(double x, double feetY, double z, bool isOnGround) => await _PackageSenderManager.Send(x, feetY, z, isOnGround); /// <summary> /// 更新玩家正在观察的方向. /// </summary> /// <param name="yaw">围绕X轴的绝对旋转,角度制</param> /// <param name="pitch">围绕Y轴的绝对旋转,角度制</param> /// <param name="isOnGround">true为在地上或者在游泳,false为其他情况</param> /// <returns></returns> [PackageSender(0x05)] protected virtual async Task SetLook(float yaw, float pitch, bool isOnGround) => await _PackageSenderManager.Send(yaw, pitch, isOnGround); /// <summary> /// 同时结合了玩家位置和观察的数据包. /// </summary> /// <param name="x">绝对坐标(即相对世界原点位置)X</param> /// <param name="feetY">玩家脚底的绝对坐标Y. 通常为头部Y坐标减1.62,用来修正玩家的碰撞盒</param> /// <param name="z">绝对坐标Z</param> /// <param name="yaw">围绕X轴的绝对旋转,角度制</param> /// <param name="pitch">围绕Y轴的绝对旋转,角度制</param> /// <param name="isOnGround">true为在地上或者在游泳,false为其他情况</param> /// <returns></returns> [PackageSender(0x06)] protected virtual async Task SetPositionAndLook(double x, double feetY, double z, float yaw, float pitch, bool isOnGround) => await _PackageSenderManager.Send(x, feetY, z, yaw, pitch, isOnGround); public enum DiggingAction : byte { StartedDigging, CancelledDigging, FinishedDigging, DropItemStack, DropItem, ShootArrowOrFinishEating, } public enum BlockFace : byte { NegativeY, PositiveY, NegativeZ, PositiveZ, NegativeX, PositiveX, } /// <summary> /// 采集方块. 只接受距离玩家6个单位距离以内的挖掘 /// </summary> /// <param name="diggingAction">玩家当期挖掘的进度(见下表)</param> /// <param name="location">方块坐标</param> /// <param name="blockFace">挖掘的面</param> /// <returns></returns> [PackageSender(0x07)] protected virtual async Task DigBlock(DiggingAction diggingAction, Position location, BlockFace blockFace) => await _PackageSenderManager.Send(diggingAction, location, blockFace); /// <summary> /// 放置方块 /// </summary> /// <param name="location">方块坐标</param> /// <param name="blockFace">在放置前光标所指向方块的面</param> /// <param name="heldItem">手上拿的物品</param> /// <param name="cursorPositionX">放置前,光标指在砖块上的相对位置</param> /// <param name="cursorPositionY"></param> /// <param name="cursorPositionZ"></param> /// <returns></returns> [PackageSender(0x08)] protected virtual async Task PlaceBlock(Position location, BlockFace blockFace, Slot heldItem, byte cursorPositionX, byte cursorPositionY, byte cursorPositionZ) => await _PackageSenderManager.Send(location, blockFace, heldItem, cursorPositionX, cursorPositionY, cursorPositionZ); /// <summary> /// 改变手持物 /// </summary> /// <param name="slot">欲选择的栏位</param> /// <returns></returns> [PackageSender(0x09)] protected virtual async Task ChangeHeldItem(short slot) => await _PackageSenderManager.Send(slot); /// <summary> /// 产生挥手的动作 /// </summary> /// <returns></returns> [PackageSender(0x0a)] protected virtual async Task SwingArm() => await _PackageSenderManager.Send(); [VarIntUnderlying] public enum EntityAction { Crouch, Uncrouch, LeaveBed, StartSprinting, StopSprinting, JumpWithHorse, OpenInventory, } /// <summary> /// 在蹲着,离开床或奔跑 /// </summary> /// <param name="entityId">玩家ID</param> /// <param name="entityAction"></param> /// <param name="jumpBoost">马跳加速,范围从0到100</param> /// <returns></returns> [PackageSender(0x0b)] protected virtual async Task ActEntity([Variable] int entityId, EntityAction entityAction, [Variable] int jumpBoost) => await _PackageSenderManager.Send(entityId, entityAction, jumpBoost); [Flags] public enum SteerFlags : byte { Jump = 0x01, Unmount = 0x02, } /// <summary> /// 驾驶交通工具 /// </summary> /// <param name="sideways">向左为正</param> /// <param name="forward">向前为正</param> /// <param name="steerFlags"></param> /// <returns></returns> [PackageSender(0x0c)] protected virtual async Task SteerVehicle(float sideways, float forward, SteerFlags steerFlags) => await _PackageSenderManager.Send(sideways, forward, steerFlags); /// <summary> /// 关闭窗口 /// </summary> /// <param name="windowId">要关闭的窗口的ID,0表示背包</param> /// <returns></returns> [PackageSender(0x0d)] protected virtual async Task CloseWindow(byte windowId) => await _PackageSenderManager.Send(windowId); /* 模式 按键 栏位 触发方式 0 0 Normal 鼠标左键点击 1 Normal 鼠标右键点击 1 0 Normal Shift+鼠标左键点击 1 Normal Shift+鼠标右键点击 2 0 Normal 数字键1 1 Normal 数字键2 2 Normal 数字键3 ... ... ... 8 Normal 数字键9 3 2 Normal 鼠标中键 4 0 Normal 丢弃物品(Q) 1 Normal Ctrl+丢弃物品(Q) 0 -999 左键什么都不拿点击背包外(No-op) 1 -999 右键什么都不拿点击背包外(No-op) 5 0 -999 开始鼠标左键(或中键)拖拽 4 -999 开始鼠标右键拖拽 1 Normal 鼠标左键拖拽来增加栏位 5 Normal 鼠标右键拖拽来增加栏位 2 -999 结束鼠标左键拖拽 6 -999 结束鼠标右键拖拽 6 0 Normal 双击 */ /// <summary> /// 点击窗口中的栏位 /// </summary> /// <param name="windowId">所点击的窗口ID,0表示玩家背包</param> /// <param name="slot">点击的栏位</param> /// <param name="button">所用来点击的键</param> /// <param name="actionNumber">这个动作的唯一数字,用来控制事物</param> /// <param name="mode">背包操作模式</param> /// <param name="clickedItem"></param> /// <returns></returns> [PackageSender(0x0e)] protected virtual async Task ClickWindow(byte windowId, short slot, byte button, short actionNumber, byte mode, Slot clickedItem) => await _PackageSenderManager.Send(windowId, slot, button, actionNumber, mode, clickedItem); /// <summary> /// 确认窗口事务 /// </summary> /// <param name="windowId">发生操作的窗口ID</param> /// <param name="actionNumber">每一个操作都有一个唯一数字,这个字段与这个数字有关</param> /// <param name="accepted">操作是否被接受</param> /// <returns></returns> [PackageSender(0x0f)] protected virtual async Task ConfirmWindowTransaction(byte windowId, short actionNumber, bool accepted) => await _PackageSenderManager.Send(windowId, actionNumber, accepted); /// <summary> /// 创造模式获得物品 /// </summary> /// <param name="slot">背包栏位</param> /// <param name="item">所需获得的物品slot数据</param> /// <returns></returns> [PackageSender(0x10)] protected virtual async Task SetInventorySlot(short slot, Slot item) => await _PackageSenderManager.Send(slot, item); /// <summary> /// 附魔物品 /// </summary> /// <param name="windowId">附魔窗口的id</param> /// <param name="enchantment">附魔物品在附魔台窗口的位置,从0开始作为最高的一个</param> /// <returns></returns> [PackageSender(0x11)] protected virtual async Task EnchantItem(byte windowId, byte enchantment) => await _PackageSenderManager.Send(windowId, enchantment); /// <summary> /// 修改牌子 /// </summary> /// <param name="location">牌子坐标</param> /// <param name="line1">牌子的第一行</param> /// <param name="line2">牌子的第二行</param> /// <param name="line3">牌子的第三行</param> /// <param name="line4">牌子的第四行</param> /// <returns></returns> [PackageSender(0x12)] protected virtual async Task UpdateSign(Position location, Chat line1, Chat line2, Chat line3, Chat line4) => await _PackageSenderManager.Send(location, line1, line2, line3, line4); /* /// <summary> /// 设置玩家能力 /// </summary> /// <param name="playerAbilities">玩家能力标志</param> /// <param name="flyingSpeed">飞行速度</param> /// <param name="walkingSpeed">行走速度</param> /// <returns></returns> [PackageSender(0x13)] protected virtual async Task SetPlayerAbilities(PlayerAbilities playerAbilities, float flyingSpeed, float walkingSpeed) => await _PackageSenderManager.MakeField(playerAbilities, flyingSpeed, walkingSpeed); */ //TODO: 无法实现自动补全,协议问题? /// <summary> /// 输入文本进行补全请求 /// </summary> /// <param name="text"></param> /// <param name="hasPosition"></param> /// <param name="lookedAtBlock">只有在hasPosition==true时才能不为null</param> /// <returns></returns> [PackageSender(0x14)] protected virtual async Task TabCompleteRequest([Variable] string text, bool hasPosition, [Optional] Position? lookedAtBlock) => await _PackageSenderManager.Send(text, hasPosition, lookedAtBlock); public enum ChatMode : byte { Enabled, CommandsOnly, Hidden, } [Flags] public enum DisplayedSkinParts : byte { CapeEnabled = 0x01, JacketEnabled = 0x02, LeftSleeveEnabled = 0x04, RightSleeveEnabled = 0x08, LeftPantsLegEnabled = 0x10, RightPantsLegEnabled = 0x20, HatEnabled = 0x40, } /// <summary> /// 改变或设置客户端设置 /// </summary> /// <param name="locale">地区化,例如en_GB</param> /// <param name="viewDistance">客户端渲染距离(区块)</param> /// <param name="chatMode">聊天设置</param> /// <param name="chatColors">“颜色”设置</param> /// <param name="displayedSkinParts">皮肤部分</param> /// <returns></returns> [PackageSender(0x15)] protected virtual async Task SetClientSettings([Variable] string locale, byte viewDistance, ChatMode chatMode, bool chatColors, DisplayedSkinParts displayedSkinParts) => await _PackageSenderManager.Send(locale, viewDistance, chatMode, chatColors, displayedSkinParts); [VarIntUnderlying] public enum StateAction { PerformRespawn, RequestStats, TakingInventoryAchievement } /// <summary> /// 完成连接或复活 /// </summary> /// <param name="action">表示需改变的状态</param> /// <returns></returns> [PackageSender(0x16)] protected virtual async Task ChangeState(StateAction action) => await _PackageSenderManager.Send(action); [PackageSender(0x17)] internal protected virtual async Task PluginMessage(Channel channel) => await _PackageSenderManager.Send(channel); /// <summary> /// 观察某玩家 /// </summary> /// <param name="targetPlayer">目标玩家</param> /// <returns></returns> [PackageSender(0x18)] protected virtual async Task Spectate(Uuid targetPlayer) => await _PackageSenderManager.Send(targetPlayer); [VarIntUnderlying] public enum ResourcePackResult { SuccessfullyLoaded, Declined, FailedDownload, Accepted, } /// <summary> /// 设置资源包状态 /// </summary> /// <param name="hash">资源包hash值</param> /// <param name="reslut">欲设置的结果</param> /// <returns></returns> [PackageSender(0x19)] protected virtual async Task SetResourcePackStatus([Variable] string hash, ResourcePackResult reslut) => await _PackageSenderManager.Send(hash, reslut); } }
public class Solution { public int[] PlusOne(int[] digits) { int carry = 1; for (int i=digits.Length-1; i>=0; i--) { int curr = digits[i] + carry; digits[i] = curr % 10; carry = curr / 10; if (carry == 0) return digits; } int[] res = new int[digits.Length+1]; res[0] = 1; return res; } }
using System; using AppStudio.DataProviders; namespace GalwayTourismGuide.Sections { /// <summary> /// Implementation of the History1Schema class. /// </summary> public class History1Schema : SchemaBase { public string Title { get; set; } public string Subtitle { get; set; } public string ImageUrl { get; set; } public string Description { get; set; } public string Link { get; set; } } }
namespace NeuroLinker.Models { /// <summary> /// Urls that contain more information about /// </summary> public class InfoUrls { #region Properties /// <summary> /// URL that link to character and staff information page /// </summary> public string CharactersAndStaff { get; set; } /// <summary> /// URL that link to clubs related to the show /// </summary> public string Clubs { get; set; } /// <summary> /// URL that link to episode information for the show /// </summary> public string Episodes { get; set; } /// <summary> /// URL that link to featured shows /// </summary> public string Featured { get; set; } /// <summary> /// URL that links to the forums /// </summary> public string Forum { get; set; } /// <summary> /// URL that links to the news page /// </summary> public string News { get; set; } /// <summary> /// URL that links to the picture page for the show /// </summary> public string Pictures { get; set; } /// <summary> /// URL that links to the recommendation page for the show /// </summary> public string Recommendation { get; set; } /// <summary> /// URL that links to the reviews page for the show /// </summary> public string Reviews { get; set; } /// <summary> /// URL that links to the stats page for the show /// </summary> public string Stats { get; set; } #endregion } }
using UnityEngine; public class FireParticles : MonoBehaviour { Transform myTransform; public Transform[] subtractTransforms; Vector3[] subtractPosOriginal; Vector3[] subtractSclOriginal; void Start() { myTransform = transform; subtractPosOriginal = new Vector3[2]; subtractSclOriginal = new Vector3[2]; for (int i = 0; i < subtractTransforms.Length; i ++ ) { subtractPosOriginal[i] = subtractTransforms[i].localPosition; subtractSclOriginal[i] = subtractTransforms[i].localScale; } } void Update () { Vector3 p0 = myTransform.position; Vector3 p1 = Camera.main.transform.position; float dstToCam = Vector3.Distance(p0,p1); float dstMax = 4f; float dstConverted = BasicFunctions.ConvertRange(dstToCam,0f,dstMax,dstMax,0f); for ( int i = 0; i < subtractTransforms.Length; i ++ ) { float subtractDir = (i == 0) ? 1f : -1f; Vector3 subtractPosTarget = subtractPosOriginal[i]; subtractPosTarget.x += (dstConverted * subtractDir) * .0925f; subtractTransforms[i].localPosition = subtractPosTarget; subtractTransforms[i].localScale = Vector3.one * (1f + (dstConverted * .075f)); } } }
using Game.Facade; using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Data.SqlClient; using System.Linq; using System.Web; namespace WebApplication1 { /// <summary> /// EmailAdd 的摘要说明 /// </summary> public class EmailAdd : IHttpHandler { public void ProcessRequest(HttpContext context) { string DataString = CommonTools.GetRequest(context); JsonEMail newPhoneLoginInfo = LitJson.JsonMapper.ToObject<JsonEMail>(DataString); string MyConn = System.Configuration.ConfigurationManager.AppSettings["DBAccounts"]; // string MyConn = "server=103.105.58.140;uid=testdb;pwd=123abc;database=RYAccountsDB;Trusted_Connection=no"; SqlConnection MyConnection = new SqlConnection(MyConn); try { MyConnection.Open(); SqlCommand cmd = new SqlCommand(); cmd.Connection = MyConnection; cmd.CommandText = "GSP_MB_AccountsEmailAdd"; cmd.Parameters.Add(new SqlParameter("@dwUserID", newPhoneLoginInfo.dwUserID)); cmd.Parameters.Add(new SqlParameter("@szTitle", newPhoneLoginInfo.szTitle)); cmd.Parameters.Add(new SqlParameter("@nType", newPhoneLoginInfo.nType)); cmd.Parameters.Add(new SqlParameter("@nSatus", newPhoneLoginInfo.nStatus)); cmd.Parameters.Add(new SqlParameter("@szMessage", newPhoneLoginInfo.szMessage)); cmd.Parameters.Add(new SqlParameter("@szSender", newPhoneLoginInfo.szSender)); cmd.CommandType = CommandType.StoredProcedure; cmd.ExecuteNonQuery(); CommonTools.SendStringToClient(context, 0, "Suss"); } catch (Exception exp) { CommonTools.SendStringToClient(context, 1, "ErrorJson:" + exp.Message.ToString() + "-" + exp.StackTrace.ToString()); } finally { MyConnection.Close(); } } public static void AddEmail(JsonEMail newPhoneLoginInfo) { var prams = new List<DbParameter>(); prams.Add(FacadeManage.aideTreasureFacade.DataProvider.GetDbHelper().MakeInParam("dwUserID", newPhoneLoginInfo.dwUserID)); prams.Add(FacadeManage.aideTreasureFacade.DataProvider.GetDbHelper().MakeInParam("szTitle", newPhoneLoginInfo.szTitle)); prams.Add(FacadeManage.aideTreasureFacade.DataProvider.GetDbHelper().MakeInParam("nType", newPhoneLoginInfo.nType)); prams.Add(FacadeManage.aideTreasureFacade.DataProvider.GetDbHelper().MakeInParam("nSatus", newPhoneLoginInfo.nStatus)); prams.Add(FacadeManage.aideTreasureFacade.DataProvider.GetDbHelper().MakeInParam("szMessage", newPhoneLoginInfo.szMessage)); prams.Add(FacadeManage.aideTreasureFacade.DataProvider.GetDbHelper().MakeInParam("szDescribe", newPhoneLoginInfo.szTitle)); prams.Add(FacadeManage.aideTreasureFacade.DataProvider.GetDbHelper().MakeInParam("szSender", newPhoneLoginInfo.szSender)); FacadeManage.aideAccountsFacade.DataProvider.GetDbHelper().RunProc("GSP_MB_AccountsEmailAdd", prams); } public bool IsReusable { get { return false; } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class BlockPosition_2 : MonoBehaviour { // 空オブジェクトを格納する為の宣言 public GameObject[] MoveBranch = new GameObject[9]; // Block_Blueを2次元配列に格納 public GameObject[,] Block_Blue_Red = new GameObject[2, 4]; // 空オブジェクトの対応付け用の配列初期化 public bool[] Cnt = new bool[8]; // 空オブジェクト(MoveBranch)の添字用の配列初期化 public int[] mvb = new int[8]; // 自分自身がどの空オブジェクトにいるか判断する public bool MoveTop; public bool CntPos1; public bool CntPos2; public bool CntPos3; public bool CntPos4; public bool CntPos5; public bool CntPos6; public bool CntPos7; public bool Toppo_L_Pos; // rotationを扱う場合、Quaternionを使う。Quaternion(x,y,z,w) Quaternion Sync; // Blockが動く速さ。割り切れないと挙動がおかしくなる。20間隔 public int Speed = 1000; // ソードの当たり判定のオブジェクトの宣言※親 GameObject Sword_L; GameObject Sword_R; // 子オブジェクト用に変数を宣言 // ソードの当たり判定のオブジェクトの宣言※子 // 子のオブジェクトを取得する場合、GameObject型ではなく、Transform型を使う Transform Sword_L_Child; Transform Sword_R_Child; // Start is called before the first frame update void Start() { // ソードの当たり判定を取得 ※親じゃなく子にCollisionがついている。 this.Sword_L = GameObject.Find("Sword_L"); this.Sword_R = GameObject.Find("Sword_R"); this.Sword_L_Child = this.Sword_L.transform.Find("effect"); this.Sword_R_Child = this.Sword_L.transform.Find("effect2"); } // Update is called once per frame void Update() { // 指標オブジェクトを空オブジェクトとしてGameObject型配列で代入 GameObject[] MoveBranch = { GameObject.Find("Bench1"), GameObject.Find("Bench2"), GameObject.Find("Bench3"), GameObject.Find("Bench4"), GameObject.Find("Bench5"), GameObject.Find("Bench6"), GameObject.Find("Bench7"), GameObject.Find("Toppo_L"), GameObject.Find("Stage_Bottom") }; // Block_BlueとRedの空オブジェクトをGameObject型に代入 // 2次元配列で格納している。 GameObject[,] Block_Blue_Red = { { GameObject.Find("Blue_Up(Clone)"), GameObject.Find("Blue_Down(Clone)"), GameObject.Find("Blue_Left(Clone)"), GameObject.Find("Blue_Right(Clone)") }, { GameObject.Find("Red_Up(Clone)"), GameObject.Find("Red_Down(Clone)"), GameObject.Find("Red_Left(Clone)"), GameObject.Find("Red_Right(Clone)")} }; // 配列の初期化 // なぜかCntとmvbだけ要素を入れないとエラーになる。 // CntはBlockがどの空オブジェクトにいるかの判定 // mvbは空オブジェクト(MoveBranch)の添字を表す・ bool[] Cnt = { false, false, false, false, false, false, false, false, false}; int[] mvb = {0,0,0,0,0,0,0,0}; // Block_Blue_Red配列のBlockの属性と種類 int[] Seek_Blue_Red = new int[8]; int[] Seek_Arrow = new int[8]; int count = 0; int i; int j; // Blockの属性を表す。Blue、Red for (i = 0; i < Block_Blue_Red.GetLength(0); i++) { // Blockの種類を表す、Up,Down,L,R for (j = 0; j < Block_Blue_Red.GetLength(1); j++) { // 1番目にブロックがあれば処理しない。 if (Block_Blue_Red[i, j].transform.position.z == transform.position.z) { MoveTop = true; Cnt[count] = true; Seek_Blue_Red[count] = i; Seek_Arrow[count] = j; mvb[count] = 0; return; } else { MoveTop = false; // Seek_Blue_Redは、Blockの属性の添字 // Seek_Arrowは、Blockの種類の添字 // 空オブジェクトとBlockの対応付け。bool型に格納。 if (MoveBranch[1].transform.position.z == Block_Blue_Red[i, j].transform.position.z) { CntPos1 = true; Cnt[count] = true; Seek_Blue_Red[count] = i; Seek_Arrow[count] = j; mvb[count] = 0; } else if (MoveBranch[2].transform.position.z == Block_Blue_Red[i, j].transform.position.z) { CntPos2 = true; Cnt[count] = true; Seek_Blue_Red[count] = i; Seek_Arrow[count] = j; mvb[count] = 1; } else if (MoveBranch[3].transform.position.z == Block_Blue_Red[i, j].transform.position.z) { CntPos3 = true; Cnt[count] = true; Seek_Blue_Red[count] = i; Seek_Arrow[count] = j; mvb[count] = 2; } else if (MoveBranch[4].transform.position.z == Block_Blue_Red[i, j].transform.position.z) { CntPos4 = true; Cnt[count] = true; Seek_Blue_Red[count] = i; Seek_Arrow[count] = j; mvb[count] = 3; } else if (MoveBranch[5].transform.position.z == Block_Blue_Red[i, j].transform.position.z) { CntPos5 = true; Cnt[count] = true; Seek_Blue_Red[count] = i; Seek_Arrow[count] = j; mvb[count] = 4; } else if (MoveBranch[6].transform.position.z == Block_Blue_Red[i, j].transform.position.z) { CntPos6 = true; Cnt[count] = true; Seek_Blue_Red[count] = i; Seek_Arrow[count] = j; mvb[count] = 5; } else if (MoveBranch[7].transform.position.z == Block_Blue_Red[i, j].transform.position.z) { CntPos7 = true; Cnt[count] = true; Seek_Blue_Red[count] = i; Seek_Arrow[count] = j; mvb[count] = 6; } else if (MoveBranch[8].transform.position.z == Block_Blue_Red[i, j].transform.position.z) { Toppo_L_Pos = true; Cnt[count] = true; Seek_Blue_Red[count] = i; Seek_Arrow[count] = j; mvb[count] = 7; } } // countにより先頭からの順番を把握している。 count++; } // 全てのBlockと空オブジェクトの対応付けが完了した場合 if (i == Block_Blue_Red.GetLongLength(0) - 1) { count = 0; // 1番目がなければ処理 if (!MoveTop) { // 空オブジェクトに対応付けされた順番に呼び出される。 for (int x = 0; x < Seek_Blue_Red.Length; x++) { // Blockの移動を伴うメソッド Spawn_move(Block_Blue_Red, MoveBranch, Seek_Blue_Red[x], Seek_Arrow[x], mvb[x], Cnt); } } } } } // Blockの移動をするメソッド public void Spawn_move(GameObject[,] Block_Red_Blue, GameObject[] MoveBranch, int i, int j, int Movedec, bool[] MoveOn) { if (MoveOn[i]) { Block_Red_Blue[i, j].transform.position = Vector3.MoveTowards(Block_Red_Blue[i, j].transform.position, MoveBranch[Movedec].transform.position, Speed * Time.deltaTime); if (Block_Red_Blue[i, j].transform.position.z == MoveBranch[Movedec].transform.position.z) { MoveOn[i] = false; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using CourseRegistrationApplication.Business; using System.Data.SqlClient; using System.Windows.Forms; namespace CourseRegistrationApplication.DataAccess { public static class CourseAssignmentDB { public static void SaveCourseAssignment(CourseAssignment courseAssigned) { SqlConnection connDB = UtilityDB.ConnectDB(); SqlCommand sqlCmd = new SqlCommand(); sqlCmd.Connection = connDB; sqlCmd.CommandText = "INSERT INTO CourseAssignment (StudentID, CourseNumber, AssignedDate) " + "VALUES (@StudentID, @CourseNumber,@AssignedDate)"; sqlCmd.Parameters.AddWithValue("@StudentId", courseAssigned.StudentID); sqlCmd.Parameters.AddWithValue("@CourseNumber", courseAssigned.CourseNumber); sqlCmd.Parameters.AddWithValue("@AssignedDate", courseAssigned.AssignedDate); sqlCmd.ExecuteNonQuery(); connDB.Close(); } public static void ListCourseByStudent(int studentId, ListView listCourse) { SqlConnection connDB = UtilityDB.ConnectDB(); string sqlSelect = "SELECT C.CourseNumber, C.CourseTitle, C.Duration, C.Prerequisite" + "FROM Courses C, CourseAssignments CA " + "WHERE C.CourseNumber = CA.CourseNumber " + "AND CA.StudentID = " + studentId; SqlCommand cmd = new SqlCommand(sqlSelect, connDB); SqlDataReader reader = cmd.ExecuteReader(); if (reader.HasRows) { while (reader.Read()) { ListViewItem listItem = new ListViewItem(reader["CourseNumber"].ToString()); listItem.SubItems.Add(reader["CourseTitle"].ToString()); listItem.SubItems.Add(reader["Duration"].ToString()); listItem.SubItems.Add(reader["Prerequisite"].ToString()); listCourse.Items.Add(listItem); } } else { MessageBox.Show("No course assigned to this teacher.", "No Course Assigned"); } } public static bool IsDuplicateAssignment(CourseAssignment ca) { bool duplicate = false; SqlConnection connDB = UtilityDB.ConnectDB(); string sqlSelect = "SELECT * FROM CourseAssignment"; SqlCommand command = new SqlCommand(sqlSelect, connDB); SqlDataReader reader = command.ExecuteReader(); if (reader.HasRows) { while (reader.Read()) { if ((ca.StudentID == Convert.ToInt32(reader["StudentID"])) && (ca.CourseNumber == reader["CourseNumber"].ToString()) ) { duplicate = true; break; } } } connDB.Close(); return duplicate; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GISDesign_ZY { enum SymbolType { SimpleMarkerSymbol, SimpleLineSymbol, SimpleFillSymbol, HatchFillSymbol } enum MarkerStyleConstant { MCircle, MSolidCircle, MRectengle, MSolidRectengle, MTriangle, MSolidTriangle, MDotCircle, MDoubleCircle } enum LineStyleConstant { LSolid, LDash, LDot, LDashDot, LDashDotDash } enum FillStyleConstant { FColor, FTransparent } enum HatchStyleConstant { HLine, HDot, HCrossLine } enum RendererType { SimpleRenderer, UniqueValueRenderer, ClassBreaksRenderer } enum FeatureTypeConstant { PointD, Polyline, Polygon, MultiPolygon, MultiPolyline } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace IRAP.UFMPS.Library { public delegate void InvokeAddLogs(object sender, string logMessage); }
using Allyn.Application.Basic; using Allyn.Application.Dto.Manage.Basic; using Allyn.Infrastructure; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web.Mvc; namespace Allyn.MvcApp.Controllers.Manage { //后台菜单 public class MenuController : Controller { //GET: /Manage/Menu/ public ActionResult Index() { IMenuService service = ServiceLocator.Instance.GetService<IMenuService>(); List<MenuDto> menus = service.GetMenuDtoByUser(Guid.NewGuid()); ViewBag.Menus = JsonConvert.SerializeObject(menus); return View(); } public ActionResult Update(Guid id) { if (id == Guid.Empty) { throw new ArgumentException("参数无效","id"); } IMenuService service = ServiceLocator.Instance.GetService<IMenuService>(); MenuEditDto model = service.GetMenuEditDto(id); //model.Children.Clear(); ViewBag.Menu = JsonConvert.SerializeObject(model); List<MenuSelectTreeDto> menus = service.GetMenuSelectTreeDto(); ViewBag.MenuSelectTree = JsonConvert.SerializeObject(menus); return View("Edit"); } public ActionResult Add(Guid? id) { MenuAddDto model = new MenuAddDto { ParentKey = id ?? Guid.Empty }; ViewBag.Menu = JsonConvert.SerializeObject(model); IMenuService service = ServiceLocator.Instance.GetService<IMenuService>(); List<MenuSelectTreeDto> menus = service.GetMenuSelectTreeDto(); ViewBag.MenuSelectTree = JsonConvert.SerializeObject(menus); return View("Edit"); } [HttpPost,ValidateAntiForgeryToken] public JsonResult AddAjax(MenuAddDto model) { if (ModelState.IsValid) { IMenuService service = ServiceLocator.Instance.GetService<IMenuService>(); UserDto user = User.Identity.GetDetails<UserDto>(); model.Creater = user.Id; service.Add(model); return Json(new { status = true, urlReferrer = "/manage/menu" }, "json", Encoding.UTF8, JsonRequestBehavior.DenyGet); } else { string msg = string.Empty; ModelState.Keys.ToList().ForEach(m => { ModelState[m].Errors.ToList().ForEach(s => { msg = s.ErrorMessage; return; }); if (msg.Length > 0) { return; } }); throw new Exception(msg); } } [HttpPost, ValidateAntiForgeryToken] public JsonResult UpdateAjax(MenuEditDto model) { if (ModelState.IsValid) { IMenuService service = ServiceLocator.Instance.GetService<IMenuService>(); UserDto user = User.Identity.GetDetails<UserDto>(); model.Modifier = user.Id; service.Update(model); return Json(new { status = true, urlReferrer = "/manage/menu" }, "json", Encoding.UTF8, JsonRequestBehavior.DenyGet); } else { string msg = string.Empty; ModelState.Keys.ToList().ForEach(m => { ModelState[m].Errors.ToList().ForEach(s => { msg = s.ErrorMessage; return; }); if (msg.Length > 0) { return; } }); throw new Exception(msg); } } [HttpPost, ValidateAntiForgeryToken] public JsonResult DeleteAjax(List<Guid> keys) { if (keys!=null&&keys.Count>0) { IMenuService service = ServiceLocator.Instance.GetService<IMenuService>(); service.Delete(keys); return Json(new { status = true, urlReferrer = "/manage/menu" }, "json", Encoding.UTF8, JsonRequestBehavior.DenyGet); } else { throw new ArgumentException("要删除的菜单标识不能为空!","keys"); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class FlightPath : MonoBehaviour { public Transform firePointTransform; public float speed; //bullet velocity multiplier public Rigidbody2D rb; public int Damage; private Vector2 direction; private Vector2 normalizedDirection; public GameObject explosionPrefab; private Collider2D thisCollider; // Start is called before the first frame update void Start() { Vector2 direction = this.transform.up; thisCollider = gameObject.GetComponent<Collider2D>(); normalizedDirection = direction / Mathf.Sqrt(Mathf.Pow (direction.x, 2) + Mathf.Pow (direction.y , 2) ) ; } void FixedUpdate() { rb.velocity = normalizedDirection*speed; } /* void OnTriggerEnter2D (Collider2D hitInfo) { if (hitInfo.name == "Player" || hitInfo.tag == "Radius") Physics2D.IgnoreCollision( hitInfo , this.GetComponent<Collider2D>()); else { Debug.Log(hitInfo.name); //Destroy(gameObject); Instantiate(explosionPrefab, this.transform.position, this.transform.rotation); } } */ void OnCollisionEnter2D (Collision2D other) { if (other.collider.CompareTag("Player") || other.collider.CompareTag("Radius") || other.collider.CompareTag("Bullet")) { Physics2D.IgnoreCollision(thisCollider, other.collider); } else { Destroy(gameObject); Instantiate(explosionPrefab, this.transform.position, this.transform.rotation); other.collider.gameObject.SendMessage( "Damage", Damage ); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CaptionConverter { [System.Xml.Serialization.XmlRoot("tt", Namespace = "http://www.w3.org/ns/ttml")] public class Tt { [System.Xml.Serialization.XmlElement("body")] public Body Body { get; set; } } }
namespace Assets.Common.Extensions { public static class Settings { public const int LENGTH = 10; public const int HIGH_VISION_LIMIT = -60; public const int LOW_VISION_LIMIT = 60; } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace MVCandEntityFrameworkPractice.Models.Domain.CardStatuses { public class Lost : CardStatus { public Lost() { Initialize(); } public Lost(Card card) { Initialize(); this.Card = card; } public Lost(CardStatus status) { Initialize(); this.Card = status.Card; } private void Initialize() { DisplayName = "Lost"; } public override void Issue(CardHolder holder, DateTime startDate, DateTime endDate, int pin) { // Cannot issue a lost card } public override void Return() { // Return the lost card this.Card.Holder = null; this.Card.StartDate = null; this.Card.EndDate = null; this.Card.Pin = null; this.Card.AccessLevels = null; this.Card.Status = new InStock(this); this.Card.StatusDate = DateTime.Now; } public override void Destroy() { // Destroy the lost card this.Card.Status = new Destroyed(this); this.Card.StatusDate = DateTime.Now; } public override void Deactivate() { // Deactivate the lost card this.Card.Status = new Deactivated(this); this.Card.StatusDate = DateTime.Now; } public override void Lose() { // Cannot lose a lost card } public override void Extend(DateTime extensionDate) { // Cannot extend a lost card } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class Bau : MonoBehaviour { bool loja = false; public GameObject LojaPanel; public GameObject pressione; // Update is called once per frame void Update() { if (loja == true && Input.GetKey(KeyCode.E)) { LojaPanel.SetActive(true); pressione.SetActive(false); } } private void OnTriggerEnter(Collider collision) { if (collision.gameObject.CompareTag("Player")) { loja = true; } } private void OnTriggerStay(Collider collision) { if (collision.gameObject.CompareTag("Player")) { loja = true; pressione.SetActive(true); } } private void OnTriggerExit(Collider collision) { if (collision.gameObject.CompareTag("Player")) { loja = false; pressione.SetActive(false); LojaPanel.SetActive(false); } } }
namespace CheckIt { using System.Collections.Generic; using System.Linq; using CheckIt.Compilation; using CheckIt.Syntax; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; internal class CheckClassVisitor : CSharpSyntaxWalker { private readonly ICompilationDocument document; private readonly SemanticModel semanticModel; private readonly List<object> types = new List<object>(); private readonly ICompilationInfo compilationInfo; private IType currentType; public CheckClassVisitor(ICompilationDocument document, SemanticModel semanticModel, ICompilationInfo compilationInfo) { this.document = document; this.semanticModel = semanticModel; this.compilationInfo = compilationInfo; } public override void VisitClassDeclaration(ClassDeclarationSyntax node) { var position = GetPosition(node); var namedTypeSymbol = this.semanticModel.GetDeclaredSymbol(node).ContainingNamespace; this.currentType = new CheckClass(node.Identifier.ValueText, namedTypeSymbol.ToDisplayString(), this.compilationInfo, position); this.types.Add(this.currentType); base.VisitClassDeclaration(node); } private Position GetPosition(SyntaxNode node) { var p = node.SyntaxTree.GetLineSpan(node.Span).StartLinePosition; return new Position(p.Line, this.document.Name); } public override void VisitInterfaceDeclaration(InterfaceDeclarationSyntax node) { var position = GetPosition(node); var namedTypeSymbol = this.semanticModel.GetDeclaredSymbol(node).ContainingNamespace; this.currentType = new CheckInterface(node.Identifier.ValueText, namedTypeSymbol.ToDisplayString(), this.compilationInfo, position); this.types.Add(this.currentType); base.VisitInterfaceDeclaration(node); } public override void VisitMethodDeclaration(MethodDeclarationSyntax node) { var position = GetPosition(node); var namedTypeSymbol = this.semanticModel.GetDeclaredSymbol(node); var immutableArray = namedTypeSymbol.TypeArguments; this.types.Add(new CheckMethod(node.Identifier.ValueText, position, this.currentType, GetTypes(immutableArray, position).ToList())); base.VisitMethodDeclaration(node); } public override void VisitInvocationExpression(InvocationExpressionSyntax node) { var position = GetPosition(node); var name = string.Empty; SimpleNameSyntax identifier; IList<IType> typesList = null; if (node.Expression is MemberAccessExpressionSyntax) { var memberAccessExpressionSyntax = node.Expression as MemberAccessExpressionSyntax; if (memberAccessExpressionSyntax.Name is GenericNameSyntax) { var genericNameSyntax = memberAccessExpressionSyntax.Name as GenericNameSyntax; typesList = GetTypes(genericNameSyntax.TypeArgumentList).ToList(); identifier = genericNameSyntax; } else { identifier = memberAccessExpressionSyntax.Name; } name = identifier.Identifier.ValueText; } else if (node.Expression is SimpleNameSyntax) { identifier = node.Expression as SimpleNameSyntax; name = identifier.Identifier.ValueText; } if (!string.IsNullOrWhiteSpace(name)) { this.types.Add(new CheckMethod(name, position, this.currentType, typesList)); } base.VisitInvocationExpression(node); } private IEnumerable<IType> GetTypes(TypeArgumentListSyntax typeArgumentList) { foreach (TypeSyntax typeSyntax in typeArgumentList.Arguments) { if (typeSyntax is IdentifierNameSyntax) { var t = typeSyntax as IdentifierNameSyntax; yield return new IntenalType(t.Identifier.Text, t.Identifier.Text, GetPosition(typeArgumentList)); } else if (typeSyntax is PredefinedTypeSyntax) { var t = typeSyntax as PredefinedTypeSyntax; yield return new IntenalType(t.Keyword.Text, t.Keyword.Text, GetPosition(typeArgumentList)); } } } private static IEnumerable<IType> GetTypes(IEnumerable<ITypeSymbol> immutableArray, Position position) { return immutableArray.Select(t => new IntenalType(t.Name, t.ContainingNamespace.ToDisplayString(), position)); } public IEnumerable<T> Get<T>() { return this.types.OfType<T>(); } } internal class IntenalType : IType { public IntenalType(string name, string nameSpace, Position position) { this.Name = name; this.NameSpace = nameSpace; this.Position = position; } public string Name { get; private set; } public string NameSpace { get; private set; } public Position Position { get; private set; } public IEnumerable<IMethod> Method(string name) { throw new System.NotImplementedException(); } } public class Position { public Position(int line, string name) { this.Line = line; this.Name = name; } public int Line { get; private set; } public string Name { get; private set; } } }
// Copyright (c) Bruno Brant. All rights reserved. using System; using System.Drawing; using System.Windows.Forms; namespace RestLittle.UI.Presenters { /// <summary> /// The view's contract. /// </summary> public interface ITrayIconView { /// <summary> /// Raised whenever the user express the desire to show the configuration view. /// </summary> event EventHandler ShowConfigurationClicked; /// <summary> /// Raised whenever the user express the desire to show the About view. /// </summary> event EventHandler ShowAboutClicked; /// <summary> /// Raised whenever the user express the desire to pause or unpause the timer. /// </summary> event EventHandler PauseUnpauseClicked; /// <summary> /// Raised whenever the user express the desire to close the application. /// </summary> event EventHandler ExitClicked; /// <summary> /// Gets or sets the current icon that appears on the system tray. /// </summary> Icon Icon { get; set; } /// <summary> /// Gets or sets the text that's displayed when the user hovers the /// mouse over the icon. /// </summary> string Status { get; set; } /// <summary> /// Displays a balloon tip with the specified title, text, and icon in the taskbar /// for the specified time period. /// </summary> /// <param name="timeout"> /// The time period, in milliseconds, the balloon tip should display. This parameter /// is deprecated as of Windows Vista. Notification display times are now based on /// system accessibility settings. /// </param> /// <param name="tipTitle"> /// The title to display on the balloon tip. /// </param> /// <param name="tipText"> /// The text to display on the balloon tip. /// </param> /// <param name="tipIcon"> /// One of the System.Windows.Forms.ToolTipIcon values. /// </param> /// <exception cref="System.ArgumentOutOfRangeException"> /// Timeout is less than 0. /// </exception> /// <exception cref="System.ArgumentException"> /// tipText is null or an empty string. /// </exception> /// <exception cref="System.ComponentModel.InvalidEnumArgumentException"> /// tipIcon is not a member of System.Windows.Forms.ToolTipIcon. /// </exception> void ShowBalloonTip(int timeout, string tipTitle, string tipText, ToolTipIcon tipIcon); } }
// The MIT License (MIT) // // Copyright (c) 2014-2018, Institute for Software & Systems Engineering // Copyright (c) 2018, Pascal Pfeil // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using ISSE.SafetyChecking.ExecutableModel; using ISSE.SafetyChecking.Formula; using ISSE.SafetyChecking.Modeling; using ISSE.SafetyChecking.Utilities; using System; using System.IO; using System.Linq; using System.Linq.Expressions; namespace SafetyLustre { public unsafe class LustreExecutableModel : ExecutableModel<LustreExecutableModel> { internal LustreModelBase Model { get; private set; } public override int StateVectorSize => Model.StateVectorSize; private AtomarPropositionFormula[] _atomarPropositionFormulas; public override AtomarPropositionFormula[] AtomarPropositionFormulas => _atomarPropositionFormulas; public override CounterExampleSerialization<LustreExecutableModel> CounterExampleSerialization => new LustreExecutableModelCounterExampleSerialization(); public LustreExecutableModel(byte[] serializedModel) { SerializedModel = serializedModel; InitializeFromSerializedModel(); } private void InitializeFromSerializedModel() { var modelWithFormula = LustreModelSerializer.DeserializeFromByteArray(SerializedModel); Model = modelWithFormula.Item1; Faults = Model.Faults.Values.OrderBy(fault => fault.Identifier).ToArray(); Formulas = modelWithFormula.Item2; var atomarPropositionVisitor = new CollectAtomarPropositionFormulasVisitor(); _atomarPropositionFormulas = atomarPropositionVisitor.AtomarPropositionFormulas.ToArray(); foreach (var stateFormula in Formulas) { atomarPropositionVisitor.Visit(stateFormula); } StateConstraints = new Func<bool>[0]; UpdateFaultSets(); _deserialize = LustreModelSerializer.CreateFastInPlaceDeserializer(Model); _serialize = LustreModelSerializer.CreateFastInPlaceSerializer(Model); _restrictRanges = () => { }; InitializeConstructionState(); CheckConsistencyAfterInitialization(); } public override void ExecuteInitialStep() { foreach (var fault in NondeterministicFaults) fault.Reset(); Model.SetInitialState(); } public override void ExecuteStep() { foreach (var fault in NondeterministicFaults) fault.Reset(); Model.Update(); } public override void SetChoiceResolver(ChoiceResolver choiceResolver) { Model.Choice.Resolver = choiceResolver; foreach (var faultsValue in Model.Faults.Values) { faultsValue.Choice.Resolver = choiceResolver; } } public static CoupledExecutableModelCreator<LustreExecutableModel> CreateExecutedModelCreator(string ocFileName, string mainNode, Fault[] faults, params Formula[] formulasToCheckInBaseModel) { Requires.NotNull(ocFileName, nameof(ocFileName)); Requires.NotNull(mainNode, nameof(mainNode)); Requires.NotNull(formulasToCheckInBaseModel, nameof(formulasToCheckInBaseModel)); LustreExecutableModel creatorFunc(int reservedBytes) { // Each model checking thread gets its own SimpleExecutableModel. // Thus, we serialize the C# model and load this file again. // The serialization can also be used for saving counter examples var serializedModelWithFormulas = LustreModelSerializer.CreateByteArray(ocFileName, mainNode, faults, formulasToCheckInBaseModel); var simpleExecutableModel = new LustreExecutableModel(serializedModelWithFormulas); return simpleExecutableModel; } void writeOptimizedStateVectorLayout(TextWriter textWriter) { throw new NotImplementedException(); } var flatFaults = faults.OrderBy(fault => fault.Identifier).ToArray(); return new CoupledExecutableModelCreator<LustreExecutableModel>(creatorFunc, writeOptimizedStateVectorLayout, ocFileName, formulasToCheckInBaseModel, flatFaults); } public static ExecutableModelCreator<LustreExecutableModel> CreateExecutedModelFromFormulasCreator(string ocFileName, string mainNode, Fault[] faults) { Requires.NotNull(ocFileName, nameof(ocFileName)); Requires.NotNull(mainNode, nameof(mainNode)); CoupledExecutableModelCreator<LustreExecutableModel> creator(Formula[] formulasToCheckInBaseModel) { Requires.NotNull(formulasToCheckInBaseModel, nameof(formulasToCheckInBaseModel)); return CreateExecutedModelCreator(ocFileName, mainNode, faults, formulasToCheckInBaseModel); } return new ExecutableModelCreator<LustreExecutableModel>(creator, ocFileName); } public override Expression CreateExecutableExpressionFromAtomarPropositionFormula(AtomarPropositionFormula formula) { if (formula is LustreAtomarProposition atomarProposition) { Func<bool> formulaEvaluatesToTrue = () => atomarProposition.Evaluate(Model); return Expression.Invoke(Expression.Constant(formulaEvaluatesToTrue)); } throw new InvalidOperationException("AtomarPropositionFormula cannot be evaluated. Use SimpleAtomarProposition instead."); } public override void WriteOptimizedStateVectorLayout(TextWriter textWriter) { throw new NotImplementedException(); } } }
using System; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Web; using ICSharpCode.SharpZipLib.GZip; using ICSharpCode.SharpZipLib.Zip.Compression; using ICSharpCode.SharpZipLib.Zip.Compression.Streams; namespace Knapcode.HttpSandbox { public class HttpSandboxHandler : HttpTaskAsyncHandler { private const string Line = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Lorem ipsum dolor sit amet. Pellentesque tincidunt ligula sed magna semper."; public override async Task ProcessRequestAsync(HttpContext context) { // prepare the headers context.Response.Buffer = false; context.Response.AddHeader("Content-Type", "text/plain"); // parse the parameters HttpSandboxParameters parameters = HttpSandboxParameters.Parse(context.Request.QueryString.ToString()); // build the lines string[] parameterLines = parameters.GetLines().ToArray(); byte[][] lines = Enumerable.Empty<string>() .Concat(parameterLines) .Concat(Enumerable.Repeat(Line, Math.Max(0, parameters.Lines - parameterLines.Length))) .Take(parameters.Lines) .Select(l => Encoding.UTF8.GetBytes(l + "\r\n")) .ToArray(); // calculate the content length, if needed Stream responseStream; if (!parameters.Chunked) { var outputStream = new MemoryStream(); Stream encodingStream = AddContentEncodingAndGetStream(parameters, context.Response, outputStream); responseStream = context.Response.OutputStream; int offset = 0; using (encodingStream) { for (int i = 0; i < lines.Length; i++) { encodingStream.Write(lines[i], 0, lines[i].Length); encodingStream.Flush(); int newLength = (int)outputStream.Length - offset; var newLine = new byte[newLength]; Buffer.BlockCopy(outputStream.GetBuffer(), offset, newLine, 0, newLength); offset = (int)outputStream.Length; lines[i] = newLine; } } context.Response.AddHeader("Content-Length", offset.ToString(CultureInfo.InvariantCulture)); } else { responseStream = AddContentEncodingAndGetStream(parameters, context.Response, context.Response.OutputStream); } // write the lines foreach (var line in lines) { await responseStream.WriteAsync(line, 0, line.Length); await Task.Delay(parameters.Sleep); await responseStream.FlushAsync(); } } public override bool IsReusable { get { return false; } } private static Stream AddContentEncodingAndGetStream(HttpSandboxParameters httpSandboxParameters, HttpResponse headers, Stream sourceStream) { switch (httpSandboxParameters.Encoding) { case "gzip": headers.AddHeader("Content-Encoding", "gzip"); return new GZipOutputStream(sourceStream); case "deflate": headers.AddHeader("Content-Encoding", "deflate"); return new DeflaterOutputStream(sourceStream, new Deflater(httpSandboxParameters.DeflateLevel, true)); case "zlib": headers.AddHeader("Content-Encoding", "deflate"); return new DeflaterOutputStream(sourceStream, new Deflater(httpSandboxParameters.DeflateLevel, false)); default: return sourceStream; } } } }
using System;using Alabo.Domains.Repositories.EFCore;using Alabo.Domains.Repositories.Model; using System.Linq; using Alabo.Domains.Entities; using Microsoft.AspNetCore.Mvc; using Alabo.Framework.Core.WebApis.Filter; using MongoDB.Bson; using Alabo.Framework.Core.WebApis.Controller; using Alabo.RestfulApi;using ZKCloud.Open.ApiBase.Configuration; using Alabo.Domains.Services; using Alabo.Web.Mvc.Attributes; using Alabo.Web.Mvc.Controllers; using Alabo.Data.People.Regionals.Domain.Entities; using Alabo.Data.People.Regionals.Domain.Services; namespace Alabo.Data.People.Regionals.Controllers { [ApiExceptionFilter] [Route("Api/Regional/[action]")] public class ApiRegionalController : ApiBaseController<Regional,ObjectId> { public ApiRegionalController() : base() { BaseService = Resolve<IRegionalService>(); } } }
using ApartmentApps.Data; namespace ApartmentApps.Api { public interface IIncidentReportSubmissionEvent { void IncidentReportSubmited( IncidentReport incidentReport); } }
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.Graphics; using XRpgLibrary; using XRpgLibrary.Controls; namespace EyesOfTheDragon.GameScreens { public class TitleScreen : BaseGameState { #region Field region Texture2D backgroundImage; Texture2D titleImage; //金属框 PictureBox switchBoxImage; //背后的灰色 PictureBox switchBackImage; //选项框 PictureBox switchImage; //开始选项 LinkLabel startGame; //继续选项 LinkLabel loadGame; //设置选项 LinkLabel options; //推出选项 LinkLabel exitGame; //组件初始位置 float maxItemWidth = 0f; int x = 0; int timeSpan = 50; int time = 0; #endregion #region Constructor region public TitleScreen(Game game, GameStateManager manager) : base(game, manager) { } #endregion #region XNA Method region protected override void LoadContent() { base.LoadContent(); ContentManager Content = GameRef.Content; backgroundImage = Content.Load<Texture2D>(@"Backgrounds\titleX"); titleImage = Content.Load<Texture2D>(@"Backgrounds\Title"); Texture2D switchGUI = Content.Load<Texture2D>(@"GUI\Steel"); switchImage = new PictureBox( switchGUI, new Rectangle(160, 300, 130, 32), new Rectangle(64, 64, 32, 32)); ControlManager.Add(switchImage); switchBackImage = new PictureBox( switchGUI, new Rectangle(140, 300, 150, 130), new Rectangle(0, 0, 64, 64)); ControlManager.Add(switchBackImage); switchBoxImage = new PictureBox( switchGUI, new Rectangle(130, 290, 170, 150), new Rectangle(64, 0, 64, 64)); ControlManager.Add(switchBoxImage); startGame = new LinkLabel(); startGame.Text = "New Game"; startGame.Size = startGame.SpriteFont.MeasureString(startGame.Text); startGame.Selected += new EventHandler(menuItem_Selected); ControlManager.Add(startGame); loadGame = new LinkLabel(); loadGame.Text = "Continue"; loadGame.Size = loadGame.SpriteFont.MeasureString(loadGame.Text); loadGame.Selected += menuItem_Selected; ControlManager.Add(loadGame); options = new LinkLabel(); options.Text = "Options"; options.Size = options.SpriteFont.MeasureString(options.Text); options.Selected += menuItem_Selected; ControlManager.Add(options); exitGame = new LinkLabel(); exitGame.Text = "Exit Program"; exitGame.Size = exitGame.SpriteFont.MeasureString(exitGame.Text); exitGame.Selected += menuItem_Selected; ControlManager.Add(exitGame); ControlManager.NextControl(); ControlManager.FocusChanged += ControlManager_FocusChanged; Vector2 position = new Vector2(160, 310); foreach (Control c in ControlManager) { if (c is LinkLabel) { if (c.Size.X > maxItemWidth) maxItemWidth = c.Size.X; c.Position = position; position.Y += c.Size.Y - 3; } } ControlManager_FocusChanged(startGame, null); } void ControlManager_FocusChanged(object sender, EventArgs e) { Control control = sender as Control; Vector2 position = new Vector2(control.Position.X - 10f, control.Position.Y - 2); switchImage.SetPosition(position); } public override void Update(GameTime gameTime) { ControlManager.Update(gameTime, PlayerIndex.One); time ++; if (time == timeSpan) { time = 0; x++; if(x > 480) { x = 0; } } base.Update(gameTime); } public override void Draw(GameTime gameTime) { GameRef.SpriteBatch.Begin(); base.Draw(gameTime); GameRef.SpriteBatch.Draw( backgroundImage, GameRef.ScreenRectangle, new Rectangle(x, 0, 640, 480), Color.White); GameRef.SpriteBatch.Draw( titleImage, new Rectangle(0, 0, GameRef.ScreenRectangle.Width, GameRef.ScreenRectangle.Height), Color.White); ControlManager.Draw(GameRef.SpriteBatch); GameRef.SpriteBatch.End(); } #endregion #region Title Screen Methods private void menuItem_Selected(object sender, EventArgs e) { Transition(ChangeType.Push, GameRef.StartMenuScreen); } #endregion } }
using System; namespace BootLoader.Impl { public class TimerEventArg : EventArgs { public DateTime when = DateTime.Now; public TimerEventArg() { when = DateTime.Now; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using QuestSystem; public class QuestManager : MonoBehaviour { // Update is called once per frame void Update() { int i = 0; foreach(Quest it in QuestHolder.CurrentQuests ) { if(it.IsComplete() == true) { Reward(it.questIdentifier._questID); QuestHolder.AddQuestToDone(it); QuestHolder.RemoveQuestFromCurrent(i); i--; } i++; } } public void CollectionCheck(GameObject item) { foreach (Quest it in QuestHolder.CurrentQuests) { it.CheckCollection(item); } } void Reward(int ID) { switch(ID) { case 1: { // Put reward for quest here. break; } } } }
using Akka.Actor; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Exp003_Akka_Server { public class SweeperActor : ReceiveActor { public SweeperActor() { Receive<SweepFloor>(Sweeper => { Console.WriteLine($"Sweeper is sweeping."); Task.Delay(new Random().Next(100, 3000)); Console.WriteLine($"Sweeper is done."); Sender.Tell("Swept!"); }); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; namespace Genesys.WebServicesClient { // TODO Support cookies public class GenesysClient : IDisposable { internal readonly Setup setup; internal readonly string encodedCredentials; readonly HttpClient httpClient; readonly bool disposeOfHttpClient; readonly string serverUri; readonly TimeSpan requestTimeout; bool disposed = false; //TODO readonly CookieSession cookieSession; //TODO readonly Authentication authentication; // DESIGN: Use of TaskScheduler instead of SynchronizationContext // Preferred as a TaskScheduler is what is actually needed by HttpClient's async methods. // A TaskScheduler can be obtained from a SynchronizationContext by using TaskScheduler.FromCurrentSynchronizationContext(). readonly TaskScheduler asyncTaskScheduler; // DESIGN: Use of the Builder pattern // Builder pattern is being used here for the big number of parameters the constructor would need. // It also makes it easier to expand with more optional parameters, and keep backwards compatible. // Builder is used here under the name Setup, which has a clearer meaning. We could change it to Builder if it is more familiar to clients. protected GenesysClient(Setup setup) { this.setup = setup; this.httpClient = setup.httpClient; this.disposeOfHttpClient = setup.disposeOfHttpClient; this.serverUri = setup.serverUri; this.encodedCredentials = Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes(setup.UserName + ":" + setup.Password)); httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", encodedCredentials); this.requestTimeout = setup.RequestTimeout; //this.cookieSession = setup.cookieSession; //this.authentication = setup.authentication; this.asyncTaskScheduler = setup.AsyncTaskScheduler; } public void Dispose() { disposed = true; if (disposeOfHttpClient) httpClient.Dispose(); } public GenesysRequest CreateRequest(string httpMethod, string uri, object jsonContent) { string absoluteUri; if (uri.StartsWith("/")) absoluteUri = serverUri + uri; else if (uri.StartsWith("http")) absoluteUri = uri; else throw new ArgumentException( "URI must be either complete (starting with \"http\")," + " or an absolute path ((starting with \"/\"): " + uri); return new GenesysRequest(this, httpMethod, absoluteUri, jsonContent); } public GenesysRequest CreateRequest(string httpMethod, string uri) { return CreateRequest(httpMethod, uri, null); } public GenesysEventReceiver CreateEventReceiver(GenesysEventReceiver.Setup setup) { return new GenesysEventReceiver(this, setup); } public HttpClient HttpClient { get { return httpClient; } } public bool Disposed { get { return disposed; } } // DESIGN: Use of Properties instead of a Fluent Construction // For 2 reasons: // - C# Object Initializers make a good syntax already // - Fluent interfaces should be kept for very frequent use. Not the case here public class Setup { internal string serverUri; internal HttpClient httpClient; internal bool disposeOfHttpClient = true; //internal Authentication authentication; //internal CookieSession cookieSession = new CookieSessionImpl(); //public TimeSpan ConnectTimeout { get; set; } public TimeSpan RequestTimeout { get; set; } public string UserName { get; set; } public string Password { get; set; } public bool Anonymous { get; set; } public Setup() { RequestTimeout = TimeSpan.FromSeconds(5); } public GenesysClient Create() { if ((UserName == null || Password == null) & !Anonymous) throw new InvalidOperationException( "UserName and Password are mandatory. " + "If you want no credentials please set Anonymous explicitly."); if (httpClient == null) { if (serverUri == null) throw new InvalidOperationException("Either property ServerUri or HttpClient is mandatory"); httpClient = new HttpClient() { BaseAddress = new Uri(serverUri), Timeout = RequestTimeout, }; } if (AsyncTaskScheduler == null) { try { AsyncTaskScheduler = TaskScheduler.FromCurrentSynchronizationContext(); } catch (InvalidOperationException) { AsyncTaskScheduler = null; } } return new GenesysClient(this); } public string ServerUri { internal get { return serverUri; } set { if (value != null && value.EndsWith("/")) throw new ArgumentException("Server URI must not end with a slash '/'"); serverUri = value; } } public HttpClient HttpClient { set { this.disposeOfHttpClient = value == null; this.httpClient = value; } } //public bool CookiesEnabled //{ // set // { // if (!value) // this.cookieSession = NoCookieSession.Instance; // } //} public TaskScheduler AsyncTaskScheduler { set; internal get; } public GenesysClient SharedHttpClient { set { this.disposeOfHttpClient = false; HttpClient = value.httpClient; } } //public GenesysClient SharedCookies //{ // set // { // this.cookieSession = value.cookieSession; // } //} } } }
 using FrbaOfertas.Model; using FrbaOfertas.Model.DataModel; 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 FrbaOfertas.ConsumirOferta { public partial class ListadoCupones : Form { CompraData cData; private static DateTime fecha = FrbaOfertas.ConfigurationHelper.FechaActual; Exception exError = null; public ListadoCupones() { InitializeComponent(); } private void ListadoCupones_Load(object sender, EventArgs e) { cData = new CompraData(Conexion.getConexion()); cargarDataGrid(); } private void cargarDataGrid() { Dictionary<String, Object> dic = new Dictionary<String, Object>() { { "compra_fecha_vencimiento", fecha } }; List<Compra> compras = cData.FilterSelect(new Dictionary<String, String>(), dic, out exError); if (exError == null) { dataGridOfertas.DataSource = compras; //dataGridOfertas.Columns[0].Visible = false; } else MessageBox.Show("No se pudo obtener la lista de cupones, " + exError.Message); } private void cargarDataGrid(string busqueda) { Dictionary<String, String> like = new Dictionary<String, String>() { { "id_compra", busqueda } }; Dictionary<String, Object> dic = new Dictionary<String, Object>() { { "compra_fecha_vencimiento", fecha } }; List<Compra> compras = cData.FilterSelect(like, dic, out exError); if (exError == null) { dataGridOfertas.DataSource = compras; //dataGridOfertas.Columns[0].Visible = false; } else MessageBox.Show("No se pudo obtener la lista de cupones, " + exError.Message); } private void buscar_Click(object sender, EventArgs e) { if (cod_compra.Text.Count() > 0) cargarDataGrid(cod_compra.Text); else cargarDataGrid(); } private void limpiar_Click(object sender, EventArgs e) { cod_compra.Text = ""; cargarDataGrid(); } private void canjear_Click(object sender, EventArgs e) { Int32 id = (Int32)dataGridOfertas.Rows[dataGridOfertas.CurrentCell.RowIndex].Cells["id_compra"].Value; Compra compra = new Compra(); compra.id_compra = id; CanjearCupon canjeo = new CanjearCupon(); canjeo.MdiParent = this.ParentForm; canjeo.Show(); return; } } }
namespace Tutorial.Tests.LinqToSql { using System; using System.Diagnostics; using System.Transactions; using Tutorial.LinqToSql; using Microsoft.VisualStudio.TestTools.UnitTesting; [TestClass] public class ChangesTests { [TestMethod] public void TracingTest() { Tracking.EntitiesFromSameDataContext(); Tracking.ObjectsFromSameDataContext(); Tracking.EntitiesFromDataContexts(); Tracking.EntityChanges(); Tracking.Attach(); Tracking.RelationshipChanges(); try { Tracking.DisableObjectTracking(); Assert.Fail(); } catch (InvalidOperationException exception) { Trace.WriteLine(exception); } } [TestMethod] public void ChangesTest() { using (TransactionScope scope = new TransactionScope()) { int subcategoryId = Changes.Create(); Changes.Update(); Changes.UpdateWithNoChange(); Changes.Delete(); Changes.DeleteWithNoQuery(subcategoryId); Changes.DeleteWithRelationship(); try { Changes.UntrackedChanges(); Assert.Fail(); } catch (InvalidOperationException exception) { Trace.WriteLine(exception); } scope.Complete(); } } } }
// Copyright (c) 2018 FiiiLab Technology Ltd // Distributed under the MIT software license, see the accompanying // file LICENSE or http://www.opensource.org/licenses/mit-license.php. using FiiiChain.Framework; using System; namespace FiiiChain.Node { class Program { static void Main(string[] args) { AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; bool testnet = false; string minerName=null; bool isMining = false; try { if (args.Length > 0) { if (args[0].ToLower() == "-testnet") { testnet = true; if (args.Length == 3) { minerName = args[1]; isMining = args[2] == "mining" ? true : false; LogHelper.Info("FiiiChain Testnet Engine is Started."); } } else if (args.Length == 2) { minerName = args[0]; isMining = args[1] == "mining" ? true : false; LogHelper.Info("FiiiChain Engine is Started."); } else { LogHelper.Info("FiiiChain Engine is Started."); } } else { LogHelper.Info("FiiiChain Engine is Started."); } GlobalParameters.IsTestnet = testnet; BlockchainJob.Initialize(); if (isMining) { BlockchainJob.Current.MinerService = new MinerJob(minerName); BlockchainJob.Current.MinerService.Start(); } BlockchainJob.Current.Start(); } catch (Exception ex) { LogHelper.Error(ex.Message, ex); } } private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { if (e.ExceptionObject is Exception) { var ex = e.ExceptionObject as Exception; LogHelper.Error(ex.Message,ex); } } } }
using UnityEngine; using System.Collections; public class Button : MonoBehaviour { public Color defaultColour; public Color selectedColour; private Material mat; private Vector3 targetPos; // Use this for initialization void Start () { targetPos = this.transform.position; mat = renderer.material; } void Update() { this.transform.position = Vector3.Lerp(this.transform.position, targetPos, Time.deltaTime * 500); } void OnTouchDown() { mat.color = selectedColour; } void OnTouchUp() { mat.color = defaultColour; } void OnTouchStay(Vector3 point) { targetPos = new Vector3(point.x,point.y,targetPos.z); mat.color = selectedColour; } void OnTouchExit() { mat.color = defaultColour; } void SingleTouchClick() { print("ihaaaa"); } }
using EddiDataDefinitions; using System; using Utilities; namespace EddiEvents { [PublicAPI] public class SuitPurchasedEvent : Event { public const string NAME = "Suit purchased"; public const string DESCRIPTION = "Triggered when you buy a space suit"; public const string SAMPLE = "{ \"timestamp\":\"2021-04-30T21:37:58Z\", \"event\":\"BuySuit\", \"Name\":\"UtilitySuit_Class1\", \"Name_Localised\":\"Maverick Suit\", \"Price\":150000, \"SuitID\":1698502991022131 }"; [PublicAPI("The name of the space suit")] public string suit => Suit?.localizedName; [PublicAPI("The invariant name of the space suit")] public string suit_invariant => Suit?.invariantName; [PublicAPI("The price paid for the space suit")] public int? price { get; } // Not intended to be user facing public Suit Suit { get; } public SuitPurchasedEvent(DateTime timestamp, Suit suit, int? price) : base(timestamp, NAME) { this.Suit = suit; this.price = price; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using BusinessObjects; using DatabaseHelper; using System.IO; namespace LooksGood.Account { public partial class Upload : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (Session["User"] == null) { Response.Redirect("Login.aspx"); } } protected void btnPost_Click(object sender, EventArgs e) { User user = (User)Session["User"]; Post post = new Post(); if (txtTitle.Text != null && txtDesription.Text != null && this.fuUpload.HasFile) { string path = Server.MapPath("../UploadedImages"); path = Path.Combine(path, this.fuUpload.FileName); string relativePath = Path.Combine("UploadedImages", this.fuUpload.FileName); this.fuUpload.SaveAs(path); if (Session["User"] != null) { post.ImagePath = relativePath; post.Title = txtTitle.Text.ToString(); post.Description = txtDesription.Text.ToString(); post.UserId = user.Id; post.Save(); Response.Redirect("~/Default.aspx"); } //else //{ // //Show broken Rules // foreach (BrokenRule br in user.BrokenRules.List) // { // AddCustomError(br.Rule); // } //} } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FI.AtividadeEntrevista.BLL { public class BoBeneficiario { /// <summary> /// Lista os clientes /// </summary> public List<DML.Beneficiario> Listar(long idCliente) { DAL.DaoBeneficiario beneficiario = new DAL.DaoBeneficiario(); return beneficiario.Listar(idCliente); } /// <summary> /// Excluir beneficiario /// </summary> public void Excluir(long idBeneficiario) { DAL.DaoBeneficiario beneficiario = new DAL.DaoBeneficiario(); beneficiario.Excluir(idBeneficiario); } /// <summary> /// Consultar beneficiario /// </summary> public DML.Beneficiario Consultar(long idBeneficiario) { DAL.DaoBeneficiario beneficiario = new DAL.DaoBeneficiario(); return beneficiario.Consultar(idBeneficiario); } } }
namespace Serilog.Tests.Data; class LimitingRewriter : LogEventPropertyValueRewriter<int> { public LogEventPropertyValue LimitStringLength(LogEventPropertyValue value, int maximumLength) { return Visit(maximumLength, value); } protected override LogEventPropertyValue VisitScalarValue(int state, ScalarValue scalar) { if (scalar.Value is not string str || str.Length <= state) return scalar; return new ScalarValue(str.Substring(0, state)); } } public class LogEventPropertyValueRewriterTests { [Fact] public void StatePropagatesAndNestedStructuresAreRewritten() { var value = new SequenceValue(new[] { new StructureValue(new[] { new LogEventProperty("S", new ScalarValue("abcde")) }) }); var limiter = new LimitingRewriter(); var limited = limiter.LimitStringLength(value, 3); var seq = limited as SequenceValue; Assert.NotNull(seq); var str = seq.Elements.Single() as StructureValue; Assert.NotNull(str); var prop = str.Properties.Single(); Assert.Equal("S", prop.Name); var sca = prop.Value as ScalarValue; Assert.NotNull(sca); Assert.Equal("abc", sca.Value); } [Fact] public void WhenNoRewritingTakesPlaceAllElementsAreUnchanged() { var value = new SequenceValue(new[] { new StructureValue(new[] { new LogEventProperty("S", new ScalarValue("abcde")) }) }); var limiter = new LimitingRewriter(); var unchanged = limiter.LimitStringLength(value, 10); Assert.Same(value, unchanged); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Exercicio4 { class Somatorio { static void Main(string[] args) { { Console.Write("Quantos elementos tem o vector? "); int N = Convert.ToInt16(Console.ReadLine()); double[] A = new double[N]; for (int I = 0; I <= N - 1; I++) { Console.Write("Elemento {0}=", I + 1); A[I] = Convert.ToDouble(Console.ReadLine()); } double Total = 0; for (int I = 0; I <= N - 1; I++) Total += A[I]; Console.WriteLine("Somatório dos elementos={0,4:F2}", Total); } } } }
using System; using Grasshopper.Kernel; using Pterodactyl; using Xunit; namespace UnitTestsGH { public class TestUnderlineGhHelper { public static UnderlineGH TestObject { get { UnderlineGH testObject = new UnderlineGH(); return testObject; } } } public class TestUnderlineGh { [Theory] [InlineData("Underline", "Underline", "Format text -> underline", "Pterodactyl", "Format")] public void TestName(string name, string nickname, string description, string category, string subCategory) { Assert.Equal(name, TestUnderlineGhHelper.TestObject.Name); Assert.Equal(nickname, TestUnderlineGhHelper.TestObject.NickName); Assert.Equal(description, TestUnderlineGhHelper.TestObject.Description); Assert.Equal(category, TestUnderlineGhHelper.TestObject.Category); Assert.Equal(subCategory, TestUnderlineGhHelper.TestObject.SubCategory); } [Theory] [InlineData(0, "Text", "Text", "Text to format", GH_ParamAccess.item)] public void TestRegisterInputParams(int id, string name, string nickname, string description, GH_ParamAccess access) { Assert.Equal(name, TestUnderlineGhHelper.TestObject.Params.Input[id].Name); Assert.Equal(nickname, TestUnderlineGhHelper.TestObject.Params.Input[id].NickName); Assert.Equal(description, TestUnderlineGhHelper.TestObject.Params.Input[id].Description); Assert.Equal(access, TestUnderlineGhHelper.TestObject.Params.Input[id].Access); } [Theory] [InlineData(0, "Report Part", "Report Part", "Created part of the report", GH_ParamAccess.item)] public void TestRegisterOutputParams(int id, string name, string nickname, string description, GH_ParamAccess access) { Assert.Equal(name, TestUnderlineGhHelper.TestObject.Params.Output[id].Name); Assert.Equal(nickname, TestUnderlineGhHelper.TestObject.Params.Output[id].NickName); Assert.Equal(description, TestUnderlineGhHelper.TestObject.Params.Output[id].Description); Assert.Equal(access, TestUnderlineGhHelper.TestObject.Params.Output[id].Access); } [Fact] public void TestGuid() { Guid expected = new Guid("1386bcfa-a262-429d-ab64-55b36b18ca2a"); Guid actual = TestUnderlineGhHelper.TestObject.ComponentGuid; Assert.Equal(expected, actual); } } }
namespace Intelecom.SmsGateway.Client.Models { /// <summary> /// SMS message. /// </summary> public class Message : IMessage { /// <summary> /// The MSISDN of the recipient. The format should follow the ITUT E.164 standard with a + prefix. /// </summary> public string Recipient { get; set; } /// <summary> /// The message payload to send, typically the message text. /// </summary> public string Content { get; set; } /// <summary> /// The cost for the recipient to receive the message. In lowest monetary unit. /// </summary> public uint Price { get; set; } /// <summary> /// For advanced message settings. /// </summary> public Settings Settings { get; set; } /// <summary> /// Arbitrary client reference ID that will be returned in the message response. /// </summary> public string ClientReference { get; set; } /// <summary> /// Returns a string that represents the current object. /// </summary> /// <returns> /// A string that represents the current object. /// </returns> public override string ToString() => $"Recipient: {Recipient}, Content: {Content}, Price: {Price}, Settings: {Settings}, ClientReference: {ClientReference}"; } }
using SFA.DAS.CommitmentsV2.Shared.Interfaces; using SFA.DAS.ProviderCommitments.Application.Commands.CreateCohort; using SFA.DAS.ProviderCommitments.Infrastructure.OuterApi.Requests.OverlappingTrainingDateRequest; using System.Threading.Tasks; namespace SFA.DAS.ProviderCommitments.Web.Mappers.Cohort { public class CreateCohortResponseToCreateOverlappingTrainingDateRequestMapper : IMapper<CreateCohortResponse, CreateOverlappingTrainingDateApimRequest> { public Task<CreateOverlappingTrainingDateApimRequest> Map(CreateCohortResponse source) { return Task.FromResult(new CreateOverlappingTrainingDateApimRequest { DraftApprenticeshipId = source.DraftApprenticeshipId.Value }); } } }