public static ISet<int> GetSchemaVersionsForSubscription(List<string> capabilities) { //The first two schema versions follow the old regex, and versions 3 on follow the new one. if (capabilities == null) { throw new ArgumentNullException("capabilities"); } var matchesOld = capabilities.Select(s => ClustersContractCapabilityRegexOld.Match(s)).Where(match => match.Success).ToList(); var schemaVersions = new HashSet<int>(matchesOld.Select(m => Int32.Parse(m.Groups[1].Value, CultureInfo.CurrentCulture)).ToList()); var matchesNew = capabilities.Select(s => ClustersContractCapabilityRegex.Match(s)).Where(match => match.Success).ToList(); if (matchesNew.Count != 0) { schemaVersions.UnionWith( matchesNew.Select(m => Int32.Parse(m.Groups[1].Value, CultureInfo.CurrentCulture))); } if (schemaVersions == null || !schemaVersions.Any()) { throw new NotSupportedException("This subscription is not enabled for the clusters contract."); } return schemaVersions; }
public RefactorCombineTableForm(Microsoft.VisualStudio.Modeling.Store store, nHydrateDiagram diagram, nHydrateModel model, Entity entity1, Entity entity2) : this() { _store = store; _model = model; _diagram = diagram; _entity1 = entity1; _entity2 = entity2; lblEntity1.Text = entity1.Name; lblEntity2.Text = entity2.Name; var fieldList = new List<Field>(); fieldList.AddRange(entity1.Fields); fieldList.AddRange(entity2.Fields); fieldList.Remove(x => entity2.PrimaryKeyFields.Contains(x)); if (fieldList.Select(x => x.Name.ToLower()).Count() != fieldList.Select(x => x.Name.ToLower()).Distinct().Count()) { cmdApply.Enabled = false; lblError.Text = "Duplicate field names are not allowed."; lblError.Visible = true; } fieldList.ForEach(x => lstField.Items.Add(x.Name)); }
public void Init(PluginInitContext context) { this.context = context; controlPanelItems = ControlPanelList.Create(48); iconFolder = Path.Combine(context.CurrentPluginMetadata.PluginDirectory, @"Images\ControlPanelIcons\"); fileType = ".bmp"; if (!Directory.Exists(iconFolder)) { Directory.CreateDirectory(iconFolder); } foreach (ControlPanelItem item in controlPanelItems) { if (!File.Exists(iconFolder + item.GUID + fileType) && item.Icon != null) { item.Icon.ToBitmap().Save(iconFolder + item.GUID + fileType); } } Task.Run(() => { var characters = controlPanelItems.Select(i => i.LocalizedString) .Concat(controlPanelItems.Select(i => i.InfoTip)); Parallel.ForEach(characters, c => { if (!string.IsNullOrWhiteSpace(c) && Alphabet.ContainsChinese(c)) { Alphabet.PinyinComination(c); } }); }); }
public ILogFormat Create(Stream stream) { var savedPresets = Settings.Default.LexPresets ?? new XElement("Presets"); var presets = new List<LexPreset>( from element in savedPresets.Elements("Preset") select new LexPreset { Name = (string) element.Attribute("Name"), CommonCode = (string) element.Attribute("CommonCode"), SegmentCode = (string) element.Attribute("SegmentCode"), RecordCode = (string) element.Attribute("RecordCode") }); var selectView = new LexPresetsView(); var viewModel = selectView.ViewModel; foreach (var preset in presets) viewModel.Presets.Add(preset); viewModel.SelectedPreset = viewModel.Presets.FirstOrDefault(); viewModel.EditPreset = preset => { InvalidateCache(preset); ShowEditPresetDialog(selectView, stream, preset, presets.Select(x => x.Name)); }; viewModel.CreateNewPreset = () => { var preset = new LexPreset { Name = "New Preset", SegmentCode = "%%", RecordCode = "%%" }; return ShowEditPresetDialog(selectView, stream, preset, presets.Select(x => x.Name)) ? preset : null; }; if (selectView.ShowDialog() != true) return null; Settings.Default.LexPresets = new XElement("Presets", from preset in viewModel.Presets select new XElement("Preset", new XAttribute("Name", preset.Name), new XAttribute("CommonCode", preset.CommonCode), new XAttribute("SegmentCode", preset.SegmentCode), new XAttribute("RecordCode", preset.RecordCode))); Settings.Default.Save(); var selectedPreset = selectView.ViewModel.SelectedPreset; if (selectedPreset == null) return null; if (selectedPreset.Format != null) return selectedPreset.Format; return Compile(selectedPreset) ?? CompileManually(selectView, stream, selectedPreset); }
protected override string GetSolution() { const double v = 3f / 7f; int maxD = 1000000; List<Tuple<int, int>> rpf = new List<Tuple<int, int>>(); for (int d = 2; d < maxD; d++) { for (int n = 1; n < d; n++) { if (Helper.GCD(d, n) == 1) { rpf.Add(new Tuple<int, int>(n, d)); if (rpf.Count > 1000000) { // Shrink list var data = rpf.Select(x => new { Value = (double)x.Item1 / (double)x.Item2, Data = x }).OrderBy(x => x.Value).ToList(); var dataBefore = data.Where(x => x.Value <= v).ToList(); if (dataBefore.Count > 5) { dataBefore = dataBefore.Skip(dataBefore.Count - 5).Take(5).ToList(); } var dataAfter = data.Where(x => x.Value >= v).ToList(); if (dataAfter.Count > 5) { dataAfter = dataAfter.Take(5).ToList(); } data = dataBefore.Concat(dataAfter).Distinct().ToList(); System.Diagnostics.Debug.Print("Shrunk! D = " + d.ToString()); rpf = data.Select(x => x.Data).ToList(); } } } } var sorted = rpf.Select(x => new { Value = (double)x.Item1 / (double)x.Item2, Data = x }).OrderBy(x => x.Value).ToList(); var solution = sorted.Where(x => x.Value < v).Last(); return solution.ToString(); }
/// <summary> /// The try save characteristics to database. /// </summary> /// <param name="characteristics"> /// The characteristics. /// </param> public void TrySaveCharacteristicsToDatabase(List<Characteristic> characteristics) { if (characteristics.Count > 0) { try { db.Characteristic.AddRange(characteristics); db.SaveChanges(); } catch (Exception exception) { // todo: refactor and optimize all this var characteristicsSequences = characteristics.Select(c => c.SequenceId).Distinct().ToArray(); var characteristicsTypes = characteristics.Select(c => c.CharacteristicTypeLinkId).Distinct().ToArray(); var characteristicsFilter = characteristics.Select(c => new { c.SequenceId, c.CharacteristicTypeLinkId }).ToArray(); var wasteCharacteristics = db.Characteristic.Where(c => characteristicsSequences.Contains(c.SequenceId) && characteristicsTypes.Contains(c.CharacteristicTypeLinkId)) .ToArray().Where(c => characteristicsFilter.Contains(new { c.SequenceId, c.CharacteristicTypeLinkId })).Select(c => new { c.SequenceId, c.CharacteristicTypeLinkId }); var wasteNewCharacteristics = characteristics.Where(c => wasteCharacteristics.Contains(new { c.SequenceId, c.CharacteristicTypeLinkId })); db.Characteristic.RemoveRange(wasteNewCharacteristics); try { db.SaveChanges(); } catch (Exception anotherException) { } } } }
public CollectionQuerySimplification(List<object> coll) { var x = coll.Select(element => element as object).Any(element => element != null); // Noncompliant use OfType x = coll.Select((element) => ((element as object))).Any(element => (element != null) && CheckCondition(element) && true); // Noncompliant use OfType var y = coll.Where(element => element is object).Select(element => element as object); // Noncompliant use OfType var y = coll.Where(element => element is object).Select(element => element as object[]); y = coll.Where(element => element is object).Select(element => (object)element); // Noncompliant use OfType x = coll.Where(element => element == null).Any(); // Noncompliant use Any([expression]) var z = coll.Where(element => element == null).Count(); // Noncompliant use Count([expression]) z = Enumerable.Count(coll.Where(element => element == null)); // Noncompliant z = Enumerable.Count(Enumerable.Where(coll, element => element == null)); // Noncompliant y = coll.Select(element => element as object); y = coll.ToList().Select(element => element as object); // Noncompliant y = coll .ToList() // Noncompliant .ToArray() // Noncompliant .Select(element => element as object); var z = coll .Select(element => element as object) .ToList(); var c = coll.Count(); //Noncompliant c = coll.OfType<object>().Count(); x = Enumerable.Select(coll, element => element as object).Any(element => element != null); //Noncompliant x = Enumerable.Any(Enumerable.Select(coll, element => element as object), element => element != null); //Noncompliant }
public WatchSpecificMovies(List<Movie> moviesToWatch) { Require.NotNull(moviesToWatch, "moviesToWatch"); Require.IsTrue(() => moviesToWatch.Count > 0, "At least one movie required"); MoviesToWatch = moviesToWatch.Select(m => new MovieToWatch(m)).ToList(); Description = "Watch all movies: " + string.Join(" ,", moviesToWatch.Select(m => m.Name)); }
public WbImageData( List<WbVmUtils.PlotPoint<Color>> plotPoints, List<WbVmUtils.PlotRectangle<Color>> filledRects, List<WbVmUtils.PlotRectangle<Color>> openRects, List<WbVmUtils.PlotLine<Color>> plotLines, double width, double height) { Height = height; Width = width; PlotPoints = plotPoints; FilledRectangles = filledRects; OpenRectangles = openRects; PlotLines = plotLines; BoundingRect = RectExt.NegInfRect .BoundingRect(plotLines.Select(pl => pl.X1)) .BoundingRect(plotLines.Select(pl => pl.X2)) .BoundingRect(plotLines.Select(pl => pl.Y1)) .BoundingRect(plotLines.Select(pl => pl.Y2)) .BoundingRect(filledRects.Select(pl => pl.X)) .BoundingRect(filledRects.Select(pl => pl.X + pl.Width)) .BoundingRect(filledRects.Select(pl => pl.Y)) .BoundingRect(filledRects.Select(pl => pl.Y + pl.Height)) .BoundingRect(openRects.Select(pl => pl.X)) .BoundingRect(openRects.Select(pl => pl.X + pl.Width)) .BoundingRect(openRects.Select(pl => pl.Y)) .BoundingRect(openRects.Select(pl => pl.Y + pl.Height)) .BoundingRect(plotPoints.Select(pl => pl.X)) .BoundingRect(plotPoints.Select(pl => pl.Y)); }
protected AssociativeNode CreateOutputAST( AssociativeNode codeInputNode, List<AssociativeNode> inputAstNodes, List<Tuple<string, AssociativeNode>> additionalBindings) { var names = additionalBindings.Select( x => AstFactory.BuildStringNode(x.Item1) as AssociativeNode).ToList(); names.Add(AstFactory.BuildStringNode("IN")); var vals = additionalBindings.Select(x => x.Item2).ToList(); vals.Add(AstFactory.BuildExprList(inputAstNodes)); Func<string, IList, IList, object> backendMethod = IronPythonEvaluator.EvaluateIronPythonScript; return AstFactory.BuildAssignment( GetAstIdentifierForOutputIndex(0), AstFactory.BuildFunctionCall( backendMethod, new List<AssociativeNode> { codeInputNode, AstFactory.BuildExprList(names), AstFactory.BuildExprList(vals) })); }
private static IEnumerable<string> GetUsedPaths(List<Customer> customers) { IEnumerable<string> usedPaths = customers.Select(cust => cust.PhotoPath); usedPaths = usedPaths.Concat(customers.Select(cust => cust.ProofOfIdPath)); usedPaths = usedPaths.Concat(customers.Select(cust => cust.Address.ProofOfAddressPath)); return usedPaths; }
private async Task<AffineTransformationParameters> CalibrateAsync(CalibrationStyle style) { await _LoadTask.Task; double margin = 50; List<Tuple<Point, Point>> measurements = new List<Tuple<Point, Point>>(); measurements.Add(new Tuple<Point, Point>(new Point(margin, margin), new Point())); //Top left if(style == CalibrationStyle.SevenPoint) measurements.Add(new Tuple<Point, Point>(new Point(this.ActualWidth * .5, margin), new Point())); //Top center measurements.Add(new Tuple<Point, Point>(new Point(this.ActualWidth - margin, margin), new Point())); //Top right measurements.Add(new Tuple<Point, Point>(new Point(this.ActualWidth - margin, this.ActualHeight - margin), new Point())); //Bottom right if (style == CalibrationStyle.SevenPoint) measurements.Add(new Tuple<Point, Point>(new Point(this.ActualWidth * .5, this.ActualHeight - margin), new Point())); //Bottom center measurements.Add(new Tuple<Point, Point>(new Point(margin, this.ActualHeight - margin), new Point())); //Bottom left if (style == CalibrationStyle.CornersAndCenter || style == CalibrationStyle.SevenPoint) measurements.Add(new Tuple<Point, Point>(new Point(this.ActualWidth * .5, this.ActualHeight * .5), new Point())); //Center for (int i = 0; i < measurements.Count; i++) { progress.Value = i * 100d / measurements.Count; var p = measurements[i].Item1; CalibrationMarker.RenderTransform = new TranslateTransform() { X = p.X, Y = p.Y }; var p1 = await GetRawTouchEventAsync(); measurements[i] = new Tuple<Point, Point>(p, p1); } var lsa = new LeastSquaresAdjustment(measurements.Select(t => t.Item1), measurements.Select(t => t.Item2)); return lsa.GetTransformation(); }
private List<DpsPerCharacter> FillEmptyDataPoints(List<DpsPerCharacter> list) { var allCharacters = list.Select(m => m.character).Distinct().OrderBy(m => m).ToList(); var allIntervals = list.Select(m => m.interval).Distinct().OrderBy(m => m).ToList(); // Fill in missing intervals var lastInterval = allIntervals.FirstOrDefault(); foreach (var interval in allIntervals.OrderBy(m => m)) { int diff = interval - lastInterval; if (diff > 1) { for (int i = 1; i < diff; i++) { foreach (var character in allCharacters) { list.Add(new DpsPerCharacter { character = character, damage = 0, interval = lastInterval + i }); } } } foreach (var character in allCharacters) { if (list.Any(m => m.character == character && m.interval == interval) == false) { list.Add(new DpsPerCharacter { character = character, interval = interval, damage = 0 }); } } lastInterval = interval; } return list; }
public List<PostWrapped> Wrap(List<Guid> postIds, User currentUser = null) { var posts = new List<PostWrapped>(); foreach (var postId in postIds) { var post = _postDao.GetPostById(postId); if (post != null) posts.Add(new PostWrapped(post)); } var authors = _membershipService.GetUsersByIds(posts.Select(x => x.Post.UserId).Distinct().ToList()).ToDictionary(x => x.Id, x => x); var subs = _subDao.GetSubsByIds(posts.Select(x => x.Post.SubId).Distinct().ToList()).ToDictionary(x => x.Id, x => x); var likes = currentUser != null ? _voteDao.GetVotesOnPostsByUser(currentUser.Id, postIds) : new Dictionary<Guid, VoteType>(); foreach (var item in posts) { item.Author = authors.ContainsKey(item.Post.UserId) ? authors[item.Post.UserId] : null; item.Sub = subs.ContainsKey(item.Post.SubId) ? subs[item.Post.SubId] : null; if (currentUser != null) item.CurrentUserVote = likes.ContainsKey(item.Post.Id) ? likes[item.Post.Id] : (VoteType?)null; } return posts; }
public static IEnumerable<RestrictionModel> Sanitize(this IEnumerable<RestrictionModel> input) { var patterns = new List<PatternRestrictionModel>(); foreach (var item in input) { var pattern = item as PatternRestrictionModel; if (pattern != null) patterns.Add(pattern); else yield return item; } if (patterns.Count == 1) { yield return patterns[0]; } else if (patterns.Count > 1) { var config = patterns.Select(x => x.Configuration).First(); var pattern = string.Join("|", patterns.Select(x => string.Format("({0})", x.Value))); yield return new PatternRestrictionModel(config) { Value = pattern, }; } }
public override void Frame(double dt) { var enemies = Manager.GetEntitiesWithComponent<Enemy>().ToList(); var bullets = Manager.GetEntitiesWithComponent<Bullet>().ToList(); var collisions = new List<Tuple<Entity, Entity>>(); foreach (var bullet in bullets) { foreach (var enemy in enemies) { if (Collision(bullet.GetComponent<Position>(), enemy.GetComponent<Position>())) { collisions.Add(Tuple.Create(bullet, enemy)); break; } } } var deadbullets = collisions.Select(x => x.Item1).Distinct(); var deadEnemies = collisions.Select(x => x.Item2).Distinct(); foreach (var deadBullet in deadbullets) { Manager.DestroyEntity(deadBullet); } foreach (var deadEnemy in deadEnemies) { Manager.DestroyEntity(deadEnemy); } }
[Fact] // CodePlex 583 public void RemoveDuplicateTphColumns_removes_multiple_batches_of_duplicate_columns_from_same_table() { var removed = new List<EdmMember>(); var mockTableType = CreateMockType("Lancre"); mockTableType.Setup(m => m.RemoveMember(It.IsAny<EdmMember>())).Callback<EdmMember>(removed.Add); var columns = CreateColumns( mockTableType, "Nanny", "Ogg", "Nanny", "Nanny", "Granny", "Magrat", "Weatherwax", "Weatherwax", "Magrat", "Garlik", "Tiffany", "Tiffany"); var mappings = CreateMappings( columns, "Nanny1", "Ogg", "Nanny2", "Nanny2", "Granny", "Magrat1", "Weatherwax", "Weatherwax", "Magrat2", "Garlik", "Tiffany", "Tiffany"); new TphColumnFixer(mappings).RemoveDuplicateTphColumns(); Assert.Equal(5, removed.Count); Assert.Equal(2, removed.Select(m => m.Name).Count(n => n == "Nanny")); Assert.Equal(1, removed.Select(m => m.Name).Count(n => n == "Weatherwax")); Assert.Equal(1, removed.Select(m => m.Name).Count(n => n == "Magrat")); Assert.Equal(1, removed.Select(m => m.Name).Count(n => n == "Tiffany")); AssertDuplicatesRemoved(mappings, "Nanny"); AssertDuplicatesRemoved(mappings, "Weatherwax"); AssertDuplicatesRemoved(mappings, "Magrat"); AssertDuplicatesRemoved(mappings, "Tiffany"); }
public static List<Manning> CreateHierarchicalTree(List<Manning> mannings) { Action<Manning> setChildren = null; setChildren = parent => { parent.Children = mannings .Where(childItem => childItem.ParentId == parent.Id) .ToList(); // Recursively call the SetChildren method for each child. if (setChildren != null) parent.Children.ForEach(setChildren); }; var ids = mannings.Select(x => x.Id).ToList(); var parentIds = mannings.Select(x => x.ParentId).ToList(); var roots = parentIds.Except(ids).ToList(); // Initialize the hierarchical list to root level items var hierarchicalItems = mannings .Where(x => roots.Contains(x.ParentId)) .ToList(); // Call the SetChildren method to set the children on each root level item. hierarchicalItems.ForEach(setChildren); return hierarchicalItems; }
public static void ExecuteUserCommand(string command, Dictionary<string, string> userInputsArgs) { ChassisManagerLauncher launcher = new ChassisManagerLauncher(); List<KeyValuePair<string, string>> methodParam = new List<KeyValuePair<string, string>>(); foreach (KeyValuePair<string, string> parm in userInputsArgs) { if (parm.Key != command && parm.Key != string.Empty) { methodParam.Add(new KeyValuePair<string, string>(CorrectParameterName(command,parm.Key) , parm.Value)); } } try { launcher.GetType().InvokeMember(command, BindingFlags.InvokeMethod, null, launcher, methodParam.Select(d => d.Value).ToArray(), null, null, methodParam.Select(d => d.Key).ToArray()); } catch (TargetInvocationException ex) { ex.InnerException.Data["OriginalStackTrace"] = ex.InnerException.StackTrace; throw ex.InnerException; } }
private void onReceiveMessage(ZWaveContext context, ZWaveMessage message) { var response = message.Message; var foundNodes = new List<byte>(); for (var i = 7; i < 35; i++) { for (var j = 0; j < 8; j++) { if ((response[i] & (0x01 << j)) != 0) { var nodeId = (byte)((i - 7) * 8 + (j + 1)); if (nodeId != context.ControllerId) { foundNodes.Add(nodeId); } } } } if (foundNodes.Any()) { context.DoParallelFor(foundNodes.Select(x => new LoadNodeProtocolInfo(x)).ToArray()); context.DoParallelFor(foundNodes.Select(x => new LoadNodeCapabilities(x)).ToArray()); } }
private Highcharts RenderChart() { Random rand = new Random(); var transactionCounts = new List<VolumeModel> { new VolumeModel(){ Month="January", Volume=rand.Next(1001)}, new VolumeModel(){ Month="February", Volume=rand.Next(1001)}, new VolumeModel(){ Month="March", Volume=rand.Next(1001)}, new VolumeModel(){ Month="April", Volume=rand.Next(1001)}, new VolumeModel(){ Month="May", Volume=rand.Next(1001)}, new VolumeModel(){ Month="June", Volume=rand.Next(1001)}, new VolumeModel(){ Month="July", Volume=rand.Next(1001)}, new VolumeModel(){ Month="August", Volume=rand.Next(1001)}, new VolumeModel(){ Month="September", Volume=rand.Next(1001)}, new VolumeModel(){ Month="October", Volume=rand.Next(1001)}, new VolumeModel(){ Month="November", Volume=rand.Next(1001)}, new VolumeModel(){ Month="December", Volume=rand.Next(1001)} }; var xDataMonths = transactionCounts.Select(i => i.Month).ToArray(); var yDataCounts = transactionCounts.Select(i => new object[] { i.Volume }).ToArray(); var chart = new Highcharts("chart") .InitChart(new Chart { DefaultSeriesType = ChartTypes.Line }) .SetTitle(new Title { Text = "Average Trading Volume per Day" }) .SetSubtitle(new Subtitle { Text = "Light-Sweet Crude Oil" }) .SetXAxis(new XAxis { Categories = xDataMonths }) .SetYAxis(new YAxis { Title = new YAxisTitle { Text = "Volume x 10,000" } }) .SetTooltip(new Tooltip { Enabled = true, Formatter = @"function() { return '<b>'+ this.series.name +'</b><br/>'+ this.x +': '+ this.y; }" }) .SetPlotOptions(new PlotOptions { Line = new PlotOptionsLine { DataLabels = new PlotOptionsLineDataLabels { Enabled = true }, EnableMouseTracking = false } }) .SetSeries(new[] { new Series {Name = "2015", Data = new Data(yDataCounts)} }); return chart; }
public void UpLoadJob() { List<int> successList = new List<int>(); try { using (IDataReader dr = DataAccess.ExecuteReader("select * from jobMain where isUploaded=0")) { int id = 0; while (dr.Read()) { String jobdate = dr["jobDate"].ToString(); Int32 userid = Int32.Parse(dr["UserID"].ToString()); string begintime = dr["BeginTime"] == DBNull.Value ? "" : dr["BeginTime"].ToString(); string endtime = dr["EndTime"] == DBNull.Value ? "" : dr["EndTime"].ToString(); string ipAddress = dr["ipAddress"] == DBNull.Value ? "" : dr["ipAddress"].ToString(); Int32 needcheckposition = dr["NeedCheckPosition"] == DBNull.Value ? 0 : Int32.Parse(dr["NeedCheckPosition"].ToString()); Int32 CheckPosition = dr["CheckPosition"] == DBNull.Value ? 0 : Int32.Parse(dr["CheckPosition"].ToString()); Int32 PassPosition = dr["PassPosition"] == DBNull.Value ? 0 : Int32.Parse(dr["PassPosition"].ToString()); id = Int32.Parse(dr["ID"].ToString()); String isfull = (dr["IsFull"] != DBNull.Value) ? dr["IsFull"].ToString() : "0"; string TrainCode = (dr["TrainCode"] == DBNull.Value) ? "" : dr["TrainCode"].ToString(); List<String> list = new List<string>(); using (IDataReader detaildr = DataAccess.ExecuteReader("select * from JobDetail where jobid=" + id.ToString())) { while (detaildr.Read()) { list.Add(string.Format("{0}|{1}|{2}|{3}", detaildr["SpecsID"].ToString(), detaildr["CheckTime"].ToString(), detaildr["CheckDetailList"].ToString(), detaildr["BarCode"].ToString())); if (detaildr["BarCode"] != DBNull.Value) TrainCode = detaildr["BarCode"].ToString().Trim(); } detaildr.Close(); } string childlist = string.Join("@", list.ToArray()); if (TrainCode.Length == AppHelper.BarCodeDim) TrainCode = TrainCode.Substring(4, 3); _Service.UploadJob(jobdate, userid, begintime, endtime, ipAddress, needcheckposition, CheckPosition, PassPosition, childlist, isfull == "1" ? true : false, TrainCode); successList.Add(id); } dr.Close(); } } catch (Exception ex) { throw ex; } finally { if (successList.Count > 0) { DataAccess.ExecuteNonQuery(String.Format("Delete from jobmain where id in ({0})", String.Join(",", successList.Select(jid => jid.ToString()).ToArray()))); DataAccess.ExecuteNonQuery(String.Format("Delete from jobDetail where jobid in ({0})", String.Join(",", successList.Select(jid => jid.ToString()).ToArray()))); } } }
private static List<Standing> GetStandings(List<Game> games) { var teams = games.Select(game => game.HomeTeam) .Concat(games.Select(game => game.AwayTeam)) .Distinct(); var standings = (from team in teams let teamGames = games.Where(game => (game.HomeTeam.Id == team.Id || game.AwayTeam.Id == team.Id) && game.IncludeInStandings ).ToList() let scores = teamGames.Select(Score.GetScore).ToList() select new Standing { Team = team, Wins = scores.Count(score => score.WinningTeamId == team.Id), Losses = scores.Count(score => score.LosingTeamId == team.Id), Ties = scores.Count(score => score.IsTie), Forfeits = teamGames.Count(game => game.WasForfeited && game.ForfeitingTeamId == team.Id), GamesPlayed = teamGames.Count, GoalsFor = teamGames.Sum(game => { var score = Score.GetScore(game); return game.HomeTeam.Id == team.Id ? score.HomeTeamScore : score.AwayTeamScore; }), GoalsAgainst = teamGames.Sum(game => { var score = Score.GetScore(game); return game.HomeTeam.Id == team.Id ? score.AwayTeamScore : score.HomeTeamScore; }) }).ToList(); return standings; }
public void SelectDisposableShouldWork() { var scheduler = new TestScheduler(); var disposables = new List<BooleanDisposable>(); var list = new CompositeDisposable(); scheduler.CreateColdObservable( new Recorded<Notification<long>>(100, Notification.CreateOnNext(0L)), new Recorded<Notification<long>>(200, Notification.CreateOnNext(1L)), new Recorded<Notification<long>>(300, Notification.CreateOnNext(2L)), new Recorded<Notification<long>>(400, Notification.CreateOnNext(3L)), new Recorded<Notification<long>>(400, Notification.CreateOnCompleted<long>()) ) .SelectDisposable(list, i => { var d = new BooleanDisposable(); disposables.Add(d); return d; }, (i, _) => i) .Subscribe() .DisposeWith(list); scheduler.AdvanceTo(300); disposables.Count.Should().Be(3); disposables.Select(d => d.IsDisposed).Should().NotContain(true); list.Dispose(); disposables.Select(d => d.IsDisposed).Should().NotContain(false); }
private Delegate CreateActionDelegate(MethodInfo method) { List<ParameterExpression> parameters = new List<ParameterExpression>(); foreach (ParameterInfo parameterInfo in method.GetParameters()) { parameters.Add(Expression.Parameter(parameterInfo.ParameterType, parameterInfo.Name)); } LambdaExpression lambda; if (method.IsStatic) { lambda = Expression.Lambda( GetActionType(parameters.Select(p => p.Type).ToArray()), Expression.Call(method, parameters.Cast<Expression>().ToArray()), parameters.ToArray()); } else { Type bindingType = method.DeclaringType; Expression<Func<object>> getInstanceExpression = () => ScenarioContext.Current.GetBindingInstance(bindingType); lambda = Expression.Lambda( GetActionType(parameters.Select(p => p.Type).ToArray()), Expression.Call( Expression.Convert(getInstanceExpression.Body, bindingType), method, parameters.Cast<Expression>().ToArray()), parameters.ToArray()); } return lambda.Compile(); }
static void Main(string[] args) { var images = new List<ImageInfo>(); var imageId = 0; foreach (var dir in new DirectoryInfo(@"..\..\Images").GetDirectories()) { var groupId = int.Parse(dir.Name.Replace("s", string.Empty)) - 1; foreach (var imageFile in dir.GetFiles("*.pgm")) { images.Add(new ImageInfo { Image = new Mat(imageFile.FullName, LoadMode.GrayScale), ImageId = imageId++, ImageGroupId = groupId }); } } var model = FaceRecognizer.CreateFisherFaceRecognizer(); model.Train(images.Select(x => x.Image), images.Select(x => x.ImageGroupId)); var rnd = new Random(); var randomImageId = rnd.Next(0, images.Count - 1); var testSample = images[randomImageId]; Console.WriteLine("Actual group: {0}", testSample.ImageGroupId); Cv2.ImShow("actual", testSample.Image); var predictedGroupId = model.Predict(testSample.Image); Console.WriteLine("Predicted group: {0}", predictedGroupId); Cv2.WaitKey(0); }
public ActionResult Agitator(int Id) { var politicalViews = new List<KeyValuePair<string, int>>(); var agitatorHouses = dataManager.AgitatorHouseRelations.GetAll().Where(ah => ah.AgitatorId == Id && ah.HouseId.HasValue).Select(wh => wh.HouseId.Value).ToList(); var houses = dataManager.Houses.GetAll().Where(h => agitatorHouses.Contains(h.Id) && h.Latitude.HasValue && h.Longitude.HasValue).ToList(); var persons = dataManager.Persons.GetAll().Where(p => houses.Select(x => x.Id).Contains(p.HouseId ?? 0)).ToList(); var voters = dataManager.Voters.GetAll().Where(v => persons.Select(x => x.Id).Contains(v.PersonId ?? 0)).ToList(); var voterPartyRelations = dataManager.VoterPartyRelations.GetAll().ToList(); var parties = voterPartyRelations.Where(vp => voters.Select(x => x.Id).Contains(vp.VoterId ?? 0)) .Select(x => dataManager.Parties.Get(x.PartyId ?? 0)).ToList(); foreach (var house in houses) { var hPersons = persons.Where(x => x.HouseId == house.Id).ToList(); var hVoters = voters.Where(x => hPersons.Select(x2 => x2.Id).Contains(x.PersonId ?? 0)).ToList(); var hVoterPartyRelations = voterPartyRelations.Where(x => hVoters.Select(x2 => x2.Id).Contains(x.VoterId ?? 0)).ToList(); var hParties = parties.Where(x => hVoterPartyRelations.Select(x2 => x2.PartyId).Contains(x.Id)).ToList(); foreach (var hParty in hParties.GroupBy(x => x.Id).Select(x => x.First())) { politicalViews.Add(new KeyValuePair<string, int>(hParty.Name, hVoterPartyRelations.Where(x => x.PartyId == hParty.Id).Count())); } } var chart = new Chart(width: 200, height: 200) .AddSeries( name: "Employee", xValue: politicalViews.Select(p => p.Key).ToArray(), yValues: politicalViews.Select(p => p.Value).ToArray(), chartType: "Pie"); return File(chart.GetBytes(), "image/jpeg"); }
private static void DumpPosts() { var path = Path.Combine(RawDataPath, "posts.xml"); var sw = Stopwatch.StartNew(); var buffer = new List<byte[]>(20000); int total = 0; foreach (var line in ReadLinesSequentially(path).Where(l => l.StartsWith(" <row "))) { total += 1; var post = PostParse(line); if (post == null) continue; buffer.Add(post.ToBinary()); if (buffer.Count == buffer.Capacity) { _reader.WriteEventsInLargeBatch("", buffer.Select(x => (x))); buffer.Clear(); var speed = total / sw.Elapsed.TotalSeconds; Console.WriteLine("Posts:\r\n\t{0} per second\r\n\tAdded {1} posts", speed, total); } } _reader.WriteEventsInLargeBatch("s3:post", buffer.Select(x => (x))); Console.WriteLine("Posts import complete"); }
public static bool Save(List<RoleFunctions> rolefunctions, OracleConnection conn) { try { bool saved = false; string query = "INSERT INTO SYSTEMROLEFUNCTIONS (ROLEID, FUNCTIONID) values(:roleid, :functionid)"; using (var command = conn.CreateCommand()) { command.CommandText = query; command.CommandType = CommandType.Text; command.BindByName = true; // In order to use ArrayBinding, the ArrayBindCount property // of OracleCommand object must be set to the number of records to be inserted command.ArrayBindCount = rolefunctions.Count; command.Parameters.Add(":roleid", OracleDbType.Int32, rolefunctions.Select(rf => rf.RoleId).ToArray(), ParameterDirection.Input); command.Parameters.Add(":functionid", OracleDbType.Int32, rolefunctions.Select(rf => rf.FunctionId).ToArray(), ParameterDirection.Input); int result = command.ExecuteNonQuery(); if (result == rolefunctions.Count) saved = true; return saved; } } catch(Exception ex) { throw ex; } }
private ElementCollection CreateElementGroup(string xPath, List<Element> list) { var names = new Dictionary<string, int>(); foreach (var name in list.Select(el => el.Name)) { if (names.ContainsKey(name)) names[name]++; else names.Add(name, 1); } string mostRepeatedName = names.Keys.OrderBy(name => names[name]).First(); int minX = list.Select(el => el.Location.X).Min(); int minY = list.Select(el => el.Location.Y).Min(); int maxX = list.Select(el => el.Location.X + el.Size.Width).Max(); int maxY = list.Select(el => el.Location.Y + el.Size.Height).Max(); var firstLocation = new Point(minX, minY); var combinedArea = new Size(maxX - minX, maxY - minY); return new ElementCollection() { Name = mostRepeatedName + "Group", LocatorType = "xpath", Locator = xPath, Location = firstLocation, Size = combinedArea }; }
/// <summary> /// / 매칭 시도를 실패하면 선점한 플레이어를 삭제, 다른 매칭에 검색 되도록 /// </summary> /// <param name="player_list"></param> /// <returns></returns> public static async Task CancelOccupiedMatchUser(List <long> player_list) { await Cache.Instance.GetDatabase().KeyDeleteAsync(player_list.Select(key => (RedisKey)$"match_user:{key}").ToArray()); }
protected override void ProcessRecordInternal() { switch (ParameterSetName) { case ListActionRulesParameterSet: case ListActionRulesByTargetResourceIdParameterSet: IPage <ActionRule> pageResult = new Page <ActionRule>(); List <ActionRule> resultList = new List <ActionRule>(); bool listByResourceGroup = false; if (string.IsNullOrWhiteSpace(ResourceGroupName)) { pageResult = this.AlertsManagementClient.ActionRules.ListBySubscriptionWithHttpMessagesAsync( targetResource: TargetResourceId, targetResourceType: TargetResourceType, targetResourceGroup: TargetResourceGroup, monitorService: MonitorService, severity: Severity, alertRuleId: AlertRuleId, impactedScope: ImpactedScope, actionGroup: ActionGroup, description: Description, name: Name ).Result.Body; listByResourceGroup = false; } else { pageResult = this.AlertsManagementClient.ActionRules.ListByResourceGroupWithHttpMessagesAsync( resourceGroupName: ResourceGroupName, targetResource: TargetResourceId, targetResourceType: TargetResourceType, targetResourceGroup: TargetResourceGroup, monitorService: MonitorService, severity: Severity, alertRuleId: AlertRuleId, impactedScope: ImpactedScope, actionGroup: ActionGroup, description: Description, name: Name ).Result.Body; listByResourceGroup = true; } // Deal with paging in response ulong first = MyInvocation.BoundParameters.ContainsKey("First") ? this.PagingParameters.First : ulong.MaxValue; ulong skip = MyInvocation.BoundParameters.ContainsKey("Skip") ? this.PagingParameters.Skip : 0; // Any items before this count should be return ulong lastCount = MyInvocation.BoundParameters.ContainsKey("First") ? skip + first : ulong.MaxValue; ulong currentCount = 0; var nextPageLink = pageResult.NextPageLink; do { List <ActionRule> tempList = pageResult.ToList(); if (currentCount + (ulong)tempList.Count - 1 < skip) { // skip the whole chunk if they are all in skip currentCount += (ulong)tempList.Count; } else { foreach (ActionRule currentActionRule in tempList) { // not return "skip" count of items in the begin, and only return "first" count of items after that. if (currentCount >= skip && currentCount < lastCount) { resultList.Add(currentActionRule); } currentCount++; if (currentCount >= lastCount) { break; } } } if (!string.IsNullOrEmpty(nextPageLink)) { if (listByResourceGroup) { pageResult = this.AlertsManagementClient.ActionRules.ListByResourceGroupNextWithHttpMessagesAsync(nextPageLink).Result.Body; } else { pageResult = this.AlertsManagementClient.ActionRules.ListBySubscriptionNextWithHttpMessagesAsync(nextPageLink).Result.Body; } nextPageLink = pageResult.NextPageLink; } } while (!string.IsNullOrEmpty(nextPageLink) && currentCount < lastCount); WriteObject(resultList.Select((r) => TransformOutput(r)), enumerateCollection: true); break; case ActionRuleByNameParameterSet: var rulebyName = this.AlertsManagementClient.ActionRules.GetByNameWithHttpMessagesAsync(ResourceGroupName, Name).Result.Body; WriteObject(sendToPipeline: TransformOutput(rulebyName)); break; case ResourceIdParameterSet: ExtractedInfo info = CommonUtils.ExtractFromActionRuleResourceId(ResourceId); var ruleById = this.AlertsManagementClient.ActionRules.GetByNameWithHttpMessagesAsync(info.ResourceGroupName, info.Resource).Result.Body; WriteObject(sendToPipeline: TransformOutput(ruleById)); break; } }
public List <ProductCardModel> Get(List <Product> products) { var galleryIds = products.Select(product => product.Gallery.Id).ToList(); var productIds = products.Select(product => product.Id).ToList(); List <MediaFile> mediaFiles = _session.QueryOver <MediaFile>() .Where(file => file.MediaCategory.Id.IsIn(galleryIds)) .OrderBy(file => file.DisplayOrder) .Asc.Cacheable() .List().ToList(); List <ProductVariant> variants = _session.QueryOver <ProductVariant>() .Where(productVariant => productVariant.Product.Id.IsIn(productIds)) .Cacheable() .List().ToList(); var productCardModels = new List <ProductCardModel>(); foreach (var product in products) { MediaFile image = mediaFiles.FirstOrDefault(file => file.IsImage() && file.MediaCategory.Id == product.Gallery.Id); var productVariants = variants.FindAll(productVariant => productVariant.Product.Id == product.Id); if (!productVariants.Any()) { continue; } var productCardModel = new ProductCardModel { Name = product.Name, Url = product.LiveUrlSegment, Abstract = product.ProductAbstract, Image = image == null ? null : image.FileUrl, PreviousPriceText = _ecommerceSettings.PreviousPriceText, ProductReviewsEnabled = _productReviewSettings.EnableProductReviews, IsMultiVariant = productVariants.Count > 1 }; if (productVariants.Count == 1) { var variant = productVariants.FirstOrDefault(); productCardModel.PreviousPrice = product.ShowPreviousPrice ? variant.PreviousPrice : null; productCardModel.Price = variant.Price; productCardModel.VariantId = variant.Id; CanBuyStatus canBuyStatus = _productVariantAvailabilityService.CanBuy(variant, 1); productCardModel.CanBuyStatus = canBuyStatus; productCardModel.StockMessage = canBuyStatus.OK ? (!string.IsNullOrEmpty(variant.CustomStockInStockMessage) ? variant.CustomStockInStockMessage : _stringResourceProvider.GetValue("In Stock")) : (!string.IsNullOrEmpty(variant.CustomStockOutOfStockMessage) ? variant.CustomStockOutOfStockMessage : _stringResourceProvider.GetValue("Out of Stock")); productCardModel.Rating = variant.Rating; productCardModel.NumberOfReviews = variant.NumberOfReviews; if (variant.ETag != null) { productCardModel.ETag = variant.ETag; } } else { ProductVariant variant = productVariants.OrderBy(x => x.Price).FirstOrDefault(); productCardModel.Price = variant != null ? variant.Price : (decimal?)null; productCardModel.Rating = variant.Rating; productCardModel.NumberOfReviews = variant.NumberOfReviews; if (variant.ETag != null) { productCardModel.ETag = variant.ETag; } } productCardModels.Add(productCardModel); } return(productCardModels); }
private static bool Judge(List <int> resources, List <List <int> > claimedResources, List <List <int> > allocatedResources) { var processCount = claimedResources.Count; var neededResources = claimedResources.Zip(allocatedResources, (a, b) => a.Zip(b, (i, j) => i - j)).ToList(); var currentResources = resources.Zip(allocatedResources.Aggregate( (a, b) => a.Zip(b, (int1, int2) => int1 + int2).ToList()), (int1, int2) => int1 - int2).ToList(); if (currentResources.Any(o => o < 0)) { Console.WriteLine( "Currently allocated resources exceeds the limitation", Color.Red); return(false); } var results = new List <int>(); var runed = Enumerable.Repeat(false, claimedResources.Count) .ToList(); for (var i = 0; i < processCount; i++) { if (neededResources[i].All(o => o.Equals(0))) { runed[i] = true; Console.WriteLine(i + 1 + " seems running, freed.", Color.Aqua); currentResources = currentResources.Zip( allocatedResources[i], (i1, i2) => i1 + i2).ToList(); results.Add(i); } } while (runed.Any(fg => !fg)) { var onceRun = false; for (var i = 0; i < processCount; i++) { if (!runed[i] && currentResources .Zip(neededResources[i], (i1, i2) => i1 - i2) .All(o => o >= 0)) { runed[i] = true; Console.WriteLine(i + 1 + " is running, freed.", Color.Aqua); currentResources = currentResources.Zip( allocatedResources[i], (i1, i2) => i1 + i2).ToList(); results.Add(i); onceRun = true; } } if (!onceRun) { return(false); } } Console.WriteLine(results.Select(o => (o + 1).ToString()).Aggregate((i1, i2) => $"{i1}->{i2}"), Color.Aqua); return(true); }
/// <summary> /// Every 30s queries mail server for new email. /// When there are new emails available it first download all mail headers and publishes them to the stream. /// Afterwards start downloading all mail content for just downloaded mail headers. /// </summary> /// <param name="cancel"></param> /// <returns></returns> private async Task RunCheckForNewMailAsyncLoop(CancellationToken cancel) { // Create mail client. IMailClient client = (new TrivialMailDllFactory()).Build(_serverType); try { // Publish Connecting state. _controllerStateStream.OnNext(ControllerState.Connecting); client.Connect(_serverEncryption, _host); // Publish LoggingIn state. _controllerStateStream.OnNext(ControllerState.LoggingIn); client.Login(_user, _password); // Publish Connected state. _controllerStateStream.OnNext(ControllerState.Connected); // Main loop while (!cancel.IsCancellationRequested) { // If disconnect or not encrypted (when should be) then reconnect. if (client.IsConnected && (_serverEncryption == MailServerEncryption.Unencrypted || client.IsEncrypted)) { // MailHeaderList contains new headers which will be published to subscribers. List <MailHeaderEntity> mailHeaderEntities = new List <MailHeaderEntity>(); using (IMailStorage <MailHeaderEntity> storage = _mailHeaderStorageFactory()) { // 1. Get from mail server all uids (emails). // ToDo: for Imap this could be improved. List <string> newUids = client.GetAllUids().ToList(); // 2. Distinct list of uids which are not yet stored in the database. // Let's reverse and start checking with the most recent email (the latest uid). newUids.Reverse(); List <string> uidList = new List <string>(); foreach (var uid in newUids) { if (!storage.Exists(x => x.Uid == uid)) { uidList.Add(uid); } else { break; } // Note: if any first exists, break the loop other emails are probably downloaded. } if (uidList.Count > 0) { // 3. Download mail headers. foreach (var uid in uidList) { // Download message header. var header = client.GetHeadersByUid(uid); // Note: MailDll documentation states that header can be null. if (header == null) { throw new ArgumentNullException(nameof(header), $"Downloaded an empty email header ({uid})."); } var email = new MailBuilder().CreateFromEml(header); var emailFrom = email?.From.FirstOrDefault(); var mailHeaderEntity = new MailHeaderEntity() { Uid = uid, Date = email?.Date ?? DateTime.MinValue, Subject = email?.Subject, MailFromEntity = new MailFromEntity() { Address = emailFrom?.Address, Name = emailFrom?.Name, LocalPart = emailFrom?.LocalPart, DomainPart = emailFrom?.DomainPart } }; mailHeaderEntities.Add(mailHeaderEntity); } // 4. Insert all new mail headers into the storage. storage.Insert(mailHeaderEntities); } } // For all new email headers publish them to the subscribers and download the content. // Note: This whole block is taken out from above using() to release storage handle asap. if (mailHeaderEntities.Count > 0) { // 5. Publish all new mail headers to the stream. mailHeaderEntities.ForEach(mailHeaderEntity => { _mailHeaderStream.OnNext(new MailHeader(mailHeaderEntity)); }); // 6. Start downloading content loop // It's not done in above foreach loop to not to keep storage open for too long // when running over slow internet connection. RunDownloadContentAsyncLoop(cancel, mailHeaderEntities.Select(x => x.Uid).ToList()); } } else { break; } // Check for new email again in 30s await Observable.Return(0).Delay(TimeSpan.FromSeconds(30), Scheduler.CurrentThread).ToTask(cancel); } } catch (Exception e) { Logger.Error(e, $"RunCheckForNewMailAsyncLoop"); } finally { client?.Close(); if (!cancel.IsCancellationRequested) { // Publish Disconnected state. _controllerStateStream.OnNext(ControllerState.Disconnected); } } }
private async Task GetTodoList(bool isAppStarting) { // // Get an access token to call the To Do service. // AuthenticationResult result = null; try { result = await authContext.AcquireTokenSilentAsync(todoListResourceId, clientId); SignInButton.Content = clearCacheString; this.SetUserName(result.UserInfo); } catch (AdalException ex) { // There is no access token in the cache, so prompt the user to sign-in. if (ex.ErrorCode == AdalError.UserInteractionRequired || ex.ErrorCode == AdalError.FailedToAcquireTokenSilently) { if (!isAppStarting) { MessageBox.Show("Please sign in to view your To-Do list"); SignInButton.Content = signInString; } } else { // An unexpected error occurred. string message = ex.Message; if (ex.InnerException != null) { message += "Error Code: " + ex.ErrorCode + "Inner Exception : " + ex.InnerException.Message; } MessageBox.Show(message); } UserName.Content = Properties.Resources.UserNotSignedIn; return; } // Once the token has been returned by ADAL, add it to the http authorization header, before making the call to access the To Do list service. httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken); // Call the To Do list service. HttpResponseMessage response = await httpClient.GetAsync(todoListBaseAddress + "/api/todolist"); if (response.IsSuccessStatusCode) { // Read the response and databind to the GridView to display To Do items. string s = await response.Content.ReadAsStringAsync(); JavaScriptSerializer serializer = new JavaScriptSerializer(); List <TodoItem> toDoArray = serializer.Deserialize <List <TodoItem> >(s); TodoList.ItemsSource = toDoArray.Select(t => new { t.Title }); } else { MessageBox.Show("An error occurred : " + response.ReasonPhrase); } return; }
/// <summary> /// Wrapp the given hl shopping cart to view. /// </summary> /// <param name="hlCarts">List of shopping cart.</param> /// <returns>Shopping cart views.</returns> public static List<MyHLShoppingCartView> WrappToShoppingCartViewList(List<MyHLShoppingCart> hlCarts, string Locale, string filterExpressions, string sortExpressions, bool savedCartsMode) { var config = HLConfigManager.Configurations.DOConfiguration; if (config.UseGregorianCalendar) { changeFormatCalendarToGregorian(); } // Initializing the MyHLShoppingCartView list result. var cartViewList = new List<MyHLShoppingCartView>(); if (hlCarts.Count > 1 && hlCarts[0].ShoppingCartID == hlCarts[1].ShoppingCartID && hlCarts[0].IsSavedCart) { // Leave the cart with the right date in list hlCarts.RemoveAt(0); } foreach (MyHLShoppingCart cart in hlCarts) { if (!cartViewList.Select(i => i.ID).Contains(cart.ShoppingCartID.ToString()) && cart.OrderCategory != ServiceProvider.CatalogSvc.OrderCategoryType.APF) { var cartView = new MyHLShoppingCartView(); // Direct properties. cartView.ID = cart.ShoppingCartID.ToString(); cartView.OrderNumber = cart.OrderNumber ?? string.Empty; cartView.DraftName = cart.CartName ?? string.Empty; if (savedCartsMode) { cartView.Date = cart.LastUpdated.ToString("d", CultureInfo.CurrentCulture); cartView.LastUpdatedDate = cart.LastUpdated; } else { cartView.Date = cart.OrderDate.ToString("d", CultureInfo.CurrentCulture); cartView.LastUpdatedDate = cart.OrderDate; } var deliveryOpt = cart.DeliveryOption; // Address formatting if (savedCartsMode) { cart.LoadShippingInfo(cart.DeliveryOptionID, cart.ShippingAddressID, cart.DeliveryOption, true); } else { if (cart.DeliveryInfo == null || cart.DeliveryInfo.Address == null) { cart.GetShippingInfoForCopyOrder(cart.DistributorID, cart.Locale, cart.ShoppingCartID, deliveryOpt, true); } } cartView.Recipient = cart.DeliveryInfo != null && cart.DeliveryInfo.Address != null ? cart.DeliveryInfo.Address.Recipient ?? string.Empty : string.Empty; if (cart.DeliveryInfo != null && cart.DeliveryInfo.Address != null) { cartView.Address = ShippingProvider.GetShippingProvider(Locale.Substring(3, 2)).FormatShippingAddress( new DeliveryOption(cart.DeliveryInfo.Address), cart.DeliveryInfo.Option, cart.DeliveryInfo.Description, false) ?? string.Empty; cartView.AddressValue = cart.DeliveryInfo.Address.Address; } if (!savedCartsMode && deliveryOpt == ServiceProvider.CatalogSvc.DeliveryOptionType.Pickup && cart.DeliveryInfo != null && cart.DeliveryInfo.Address != null) { cartView.Address = string.Concat(cart.DeliveryInfo.Address.Alias, "</br>", cartView.Address); cartView.AddressValue = cart.DeliveryInfo.Address.Address; } cartViewList.Add(cartView); // Getting car items var cartItems = new List<MyHLProductItemView>(); if (cart.CartItems != null) { cart.CartItems.ForEach( item => cartItems.Add(new MyHLProductItemView() { Quantity = item.Quantity, SKU = item.SKU })); // Getting descriptions if (savedCartsMode) { cart.GetShoppingCartForDisplay(false, true); } if (cart.ShoppingCartItems != null && cart.ShoppingCartItems.Count() > 0) { foreach (MyHLProductItemView t in cartItems) { if (t != null) { var item = cart.ShoppingCartItems.Where(x => x.SKU == t.SKU); if (item.Count() > 0) { t.Description = item.FirstOrDefault().Description; } } } } } cartView.CartItems = cartItems; } } // Search if (!string.IsNullOrEmpty(filterExpressions)) { cartViewList = Search(cartViewList, filterExpressions); } // Sort if (!string.IsNullOrEmpty(sortExpressions)) { cartViewList = SortBy(cartViewList, sortExpressions); } return cartViewList; }
public List <Order> GetOrders() { return(orders.Select(item => (Order)item).ToList()); }
public List <Rate> Get() { return(_rates. Select(item => (Rate)item.Clone()).ToList()); }
public async Task <IActionResult> Import(IFormFile file) { var stream = file.OpenReadStream(); var reader = new EmployeeReader(stream); var models = reader.Parse(); var list = new List <EmployeeBuffer>(); var data = await _service.GetDataForEmployeeAction(); if (!models.Any()) { return(BadRequest("File trống")); } foreach (var model in models) { var row = model.Row; var staff = model.Model; var buffer = new EmployeeBuffer { Employee = new Employee(), Errors = new List <string>() }; if (string.IsNullOrEmpty(staff.Code)) { buffer.Errors.Add("Mã nhân viên trống."); buffer.Index = row; } else { buffer.Employee.DefCode = staff.Code; } if (string.IsNullOrEmpty(staff.Name)) { buffer.Errors.Add("Tên nhân viên trống."); buffer.Index = row; } else { buffer.Employee.Name = staff.Name; } buffer.Employee.DateOfBirth = staff.DateOfBirth; buffer.Employee.Email = staff.Email; buffer.Employee.Phone = staff.Phone; buffer.Employee.CreatedDate = DateTime.Now; buffer.Employee.LastModified = DateTime.Now; buffer.Employee.IsPublished = true; if (string.IsNullOrEmpty(staff?.FacutlyCode.ToString())) { buffer.Errors.Add("Mã khoa trống"); buffer.Index = row; } else { var facutly = data.Facutlies.ToList()?.FirstOrDefault(x => x.DefCode == staff.FacutlyCode); if (facutly == null) { buffer.Errors.Add("Không tìm thấy khoa trên hệ thống"); buffer.Index = row; } else { buffer.Employee.FacutlyCode = facutly.Id.ToObjectId(); } } if (string.IsNullOrEmpty(staff.MajorCode.ToString())) { buffer.Errors.Add("Mã chuyên môn trống"); buffer.Index = row; } else { var major = data.Majors.ToList()?.FirstOrDefault(x => x.DefCode == staff.MajorCode); if (major == null) { buffer.Errors.Add("Không tìm thấy chuyên môn trên hệ thống"); buffer.Index = row; } else { buffer.Employee.MajorCode = major.Id.ToObjectId(); } } if (string.IsNullOrEmpty(staff.LevelCode.ToString())) { buffer.Errors.Add("Mã trình độ trống"); buffer.Index = row; } else { var level = data.Levels.ToList()?.FirstOrDefault(x => x.DefCode == staff.LevelCode); if (level == null) { buffer.Errors.Add("Không tìm thấy trình độ trên hệ thống"); buffer.Index = row; } else { buffer.Employee.LevelCode = level.Id.ToObjectId(); } } list.Add(buffer); } if (list.Any(x => x.Errors.Any())) { return(BadRequest(new { Errors = list.Where(x => x.Errors.Any()).ToList() })); } var listToInsert = list.Select(x => x.Employee).ToList(); await _service.Import(listToInsert); return(Ok()); }
protected override ShoppingCartRuleResult PerformRules(MyHLShoppingCart cart, ShoppingCartRuleReason reason, ShoppingCartRuleResult Result) { if (!GetPurchaseRestrictionManager(cart.DistributorID).CanPurchase) { cart.ItemsBeingAdded.Clear(); Result.AddMessage( string.Format( HttpContext.GetGlobalResourceObject( string.Format("{0}_ErrorMessage", HLConfigManager.Platform), "CantBuy").ToString())); Result.Result = RulesResult.Failure; return(Result); } var currentlimits = GetCurrentPurchasingLimits(cart.DistributorID, GetCurrentOrderMonth()); if (cart == null || currentlimits == null) { return(Result); } if (cart.ItemsBeingAdded == null || cart.ItemsBeingAdded.Count == 0) { return(Result); } string processingCountryCode = DistributorProfileModel.ProcessingCountryCode; //bool bCanPurchasePType = CanPurchasePType(cart.DistributorID); var errors = new List <string>(); decimal NewVolumePoints = decimal.Zero; decimal cartVolume = cart.VolumeInCart; bool bLimitExceeded = false; List <string> skuToAdd = new List <string>(); foreach (var item in cart.ItemsBeingAdded) { var currentItem = CatalogProvider.GetCatalogItem(item.SKU, Country); if (currentItem == null) { continue; } if (currentlimits.PurchaseLimitType == PurchaseLimitType.Volume || currentlimits.RestrictionPeriod == PurchasingLimitRestrictionPeriod.PerOrder) { if (currentlimits.maxVolumeLimit == -1) { skuToAdd.Add(item.SKU); continue; } NewVolumePoints += currentItem.VolumePoints * item.Quantity; if (currentlimits.RemainingVolume - (cartVolume + NewVolumePoints) < 0) { if (currentlimits.LimitsRestrictionType == LimitsRestrictionType.FOP || currentlimits.LimitsRestrictionType == LimitsRestrictionType.OrderThreshold) //MPE FOP { Result.Result = RulesResult.Failure; ///Order exceeds the allowable volume for First Order Program. The Volume on the order needs to be reduced by {0:F2} VPs. The following SKU(s) have not been added to the cart. if (!bLimitExceeded) // to add this message only once { errors.Add( string.Format( HttpContext.GetGlobalResourceObject( string.Format("{0}_Rules", HLConfigManager.Platform), "FOPVolumePointExceeds").ToString(), 1100, PurchaseRestrictionProvider.GetVolumeLimitsAfterFirstOrderFOP( processingCountryCode), PurchaseRestrictionProvider.GetThresholdPeriod(processingCountryCode), -999)); // -999 should be replaced with caluclated value. bLimitExceeded = true; } /// Item SKU:{0}. errors.Add( string.Format( HttpContext.GetGlobalResourceObject( string.Format("{0}_Rules", HLConfigManager.Platform), "VolumePointExceedsThreshold").ToString(), item.SKU)); } else { if (currentItem.ProductType != ServiceProvider.CatalogSvc.ProductType.Product) { skuToAdd.Add(item.SKU); } else { Result.Result = RulesResult.Failure; errors.Add( string.Format( HttpContext.GetGlobalResourceObject( string.Format("{0}_Rules", HLConfigManager.Platform), "PurchaseLimitTypeProductCategory").ToString(), item.SKU)); } } } else { skuToAdd.Add(item.SKU); } } else { skuToAdd.Add(item.SKU); } } if (Result.Result == RulesResult.Failure && errors.Count > 0) { if (cart.OnCheckout && (currentlimits.LimitsRestrictionType == LimitsRestrictionType.FOP || currentlimits.LimitsRestrictionType == LimitsRestrictionType.OrderThreshold)) { Result.AddMessage(string.Format(HttpContext.GetGlobalResourceObject( string.Format("{0}_Rules", HLConfigManager.Platform), "FOPVolumePointExceedsOnCheckout").ToString(), 1100, PurchaseRestrictionProvider.GetVolumeLimitsAfterFirstOrderFOP(processingCountryCode), PurchaseRestrictionProvider.GetThresholdPeriod(processingCountryCode), (cartVolume + NewVolumePoints) - currentlimits.RemainingVolume)); } else { errors = errors.Select(x => x.Replace("-999", ((cartVolume + NewVolumePoints) - currentlimits.RemainingVolume).ToString())).ToList <string>(); Array.ForEach(errors.ToArray(), a => Result.AddMessage(a)); } } cart.ItemsBeingAdded.RemoveAll(s => !skuToAdd.Contains(s.SKU)); return(Result); }
/// <summary> /// Loot any wrecks & cargo containers close by /// </summary> private void LootWrecks() { var cargo = Cache.Instance.DirectEve.GetShipsCargo(); if (cargo.Window == null) { // No, command it to open Cache.Instance.DirectEve.ExecuteCommand(DirectCmd.OpenCargoHoldOfActiveShip); return; } // Ship's cargo is not ready yet if (!cargo.IsReady) { return; } var shipsCargo = cargo.Items.Select(i => new ItemCache(i)).ToList(); var freeCargoCapacity = cargo.Capacity - cargo.UsedCapacity; var lootWindows = Cache.Instance.DirectEve.Windows.OfType <DirectContainerWindow>().Where(w => w.Type == "form.LootCargoView"); foreach (var window in lootWindows) { // The window is not ready, then continue if (!window.IsReady) { continue; } // Get the container var containerEntity = Cache.Instance.EntityById(window.ItemId); // Does it no longer exist or is it out of transfer range or its looted if (containerEntity == null || containerEntity.Distance > 2500 || Cache.Instance.LootedContainers.Contains(containerEntity.Id)) { Logging.Log("Salvage: Closing loot window [" + window.ItemId + "]"); window.Close(); continue; } // Get the container that is associated with the cargo container var container = Cache.Instance.DirectEve.GetContainer(window.ItemId); // List its items var items = container.Items.Select(i => new ItemCache(i)); // Build a list of items to loot var lootItems = new List <ItemCache>(); // Walk through the list of items ordered by highest value item first foreach (var item in items.OrderByDescending(i => i.IskPerM3)) { // We pick up loot depending on isk per m3 var isMissionItem = Cache.Instance.MissionItems.Contains((item.Name ?? string.Empty).ToLower()); // Never pick up contraband (unless its the mission item) if (!isMissionItem && item.IsContraband) { continue; } // Do we want to loot other items? if (!isMissionItem && !LootEverything) { continue; } // We are at our max, either make room or skip the item if ((freeCargoCapacity - item.TotalVolume) <= (isMissionItem ? 0 : ReserveCargoCapacity)) { // We can't drop items in this container anyway, well get it after its salvaged if (!isMissionItem && containerEntity.GroupId != (int)Group.CargoContainer) { continue; } // Make a list of items which are worth less List <ItemCache> worthLess; if (isMissionItem) { worthLess = shipsCargo; } else if (item.IskPerM3.HasValue) { worthLess = shipsCargo.Where(sc => sc.IskPerM3.HasValue && sc.IskPerM3 < item.IskPerM3).ToList(); } else { worthLess = shipsCargo.Where(sc => sc.IskPerM3.HasValue).ToList(); } // Remove mission item from this list worthLess.RemoveAll(wl => Cache.Instance.MissionItems.Contains((wl.Name ?? string.Empty).ToLower())); worthLess.RemoveAll(wl => (wl.Name ?? string.Empty).ToLower() == Cache.Instance.BringMissionItem); // Consider dropping ammo if it concerns the mission item! if (!isMissionItem) { worthLess.RemoveAll(wl => Ammo.Any(a => a.TypeId == wl.TypeId)); } // Nothing is worth less then the current item if (worthLess.Count() == 0) { continue; } // Not enough space even if we dumped the crap if ((freeCargoCapacity + worthLess.Sum(wl => wl.TotalVolume)) < item.TotalVolume) { if (isMissionItem) { Logging.Log("Salvage: Not enough space for mission item! Need [" + item.TotalVolume + "] maximum available [" + (freeCargoCapacity + worthLess.Sum(wl => wl.TotalVolume)) + "]"); } continue; } // Start clearing out items that are worth less var moveTheseItems = new List <DirectItem>(); foreach (var wl in worthLess.OrderBy(wl => wl.IskPerM3.HasValue ? wl.IskPerM3.Value : double.MaxValue).ThenByDescending(wl => wl.TotalVolume)) { // Mark this item as moved moveTheseItems.Add(wl.DirectItem); // Substract (now) free volume freeCargoCapacity += wl.TotalVolume; // We freed up enough space? if ((freeCargoCapacity - item.TotalVolume) >= ReserveCargoCapacity) { break; } } if (moveTheseItems.Count > 0) { // If this is not a cargo container, then jettison loot if (containerEntity.GroupId != (int)Group.CargoContainer || isMissionItem) { if (DateTime.Now.Subtract(_lastJettison).TotalSeconds < 185) { return; } Logging.Log("Salvage: Jettisoning [" + moveTheseItems.Count + "] items to make room for the more valuable loot"); // Note: This could (in theory) f**k up with the bot jettison an item and // then picking it up again :/ (granted it should never happen unless // mission item volume > reserved volume cargo.Jettison(moveTheseItems.Select(i => i.ItemId)); _lastJettison = DateTime.Now; return; } // Move items to the cargo container container.Add(moveTheseItems); // Remove it from the ships cargo list shipsCargo.RemoveAll(i => moveTheseItems.Any(wl => wl.ItemId == i.Id)); Logging.Log("Salvage: Moving [" + moveTheseItems.Count + "] items into the cargo container to make room for the more valuable loot"); } } // Update free space freeCargoCapacity -= item.TotalVolume; lootItems.Add(item); } // Mark container as looted Cache.Instance.LootedContainers.Add(containerEntity.Id); // Loot actual items if (lootItems.Count != 0) { Logging.Log("Salvage: Looting container [" + containerEntity.Name + "][" + containerEntity.Id + "], [" + lootItems.Count + "] valuable items"); cargo.Add(lootItems.Select(i => i.DirectItem)); } else { Logging.Log("Salvage: Container [" + containerEntity.Name + "][" + containerEntity.Id + "] contained no valuable items"); } } // Open a container in range foreach (var containerEntity in Cache.Instance.Containers.Where(e => e.Distance <= 2500)) { // Emptry wreck, ignore if (containerEntity.GroupId == (int)Group.Wreck && containerEntity.IsWreckEmpty) { continue; } // We looted this container if (Cache.Instance.LootedContainers.Contains(containerEntity.Id)) { continue; } // We already opened the loot window var window = lootWindows.FirstOrDefault(w => w.ItemId == containerEntity.Id); if (window != null) { continue; } // Ignore open request within 10 seconds if (_openedContainers.ContainsKey(containerEntity.Id) && DateTime.Now.Subtract(_openedContainers[containerEntity.Id]).TotalSeconds < 10) { continue; } // Open the container Logging.Log("Salvage: Opening container [" + containerEntity.Name + "][" + containerEntity.Id + "]"); containerEntity.OpenCargo(); _openedContainers[containerEntity.Id] = DateTime.Now; break; } }
// this is a GET /fubar/1,2,3,4 public Result CalcThis(string function, string args) { // function=fubar // args = 1,2,3,4 var allargs = args.Split(','); // store each argument with their type var typeList = new List <Tuple <Type, object> >(); // parsr to gind the best match foreach (var arg in allargs) { // convert each argument string // to a type that is supported int i; if (Int32.TryParse(arg, out i)) { typeList.Add(new Tuple <Type, object>(typeof(Int32), i)); continue; } double d; if (Double.TryParse(arg, NumberStyles.AllowDecimalPoint, new CultureInfo("en-us"), out d)) { typeList.Add(new Tuple <Type, object>(typeof(Double), d)); continue; } // if all fails assume string typeList.Add(new Tuple <Type, object>(typeof(string), arg)); } // find and call the correct method // notice that parameters and their type do matter // overloads of the same methodname with // different types is supported // Functions is the static type with methods to call var method = typeof(Functions).GetMethod( function, BindingFlags.Static | BindingFlags.Public | BindingFlags.InvokeMethod, null, typeList.Select(ty => ty.Item1).ToArray(), //all types null); var callresult = method.Invoke( null, typeList.Select(ty => ty.Item2).ToArray()); // all values // shape the output in the form you need var result = new Result(); if (callresult is double) { result.DoubleResult = (double)callresult; } if (callresult is int) { result.IntResult = (int)callresult; } if (callresult is string) { result.Message = (string)callresult; } return(result); }
public static List <string> getLexemesFromList(List <token> tkns) { return(tkns.Select(a => a.lexeme).ToList()); }
public ActionResult Create(string JsonLessonSessions, string FILTER_Keyword, string FILTER_InvoiceNo, int?FILTER_Cancelled, bool?FILTER_chkDateFrom, DateTime?FILTER_DateFrom, bool?FILTER_chkDateTo, DateTime?FILTER_DateTo) { List <LessonSessionsModel> LessonSessions = new List <LessonSessionsModel>(); if (string.IsNullOrEmpty(JsonLessonSessions)) { return(returnView(LessonSessions, "Please add at least one student")); } LessonSessions = JsonConvert.DeserializeObject <List <LessonSessionsModel> >(JsonLessonSessions); LessonSessionsModel model = LessonSessions[0]; model.Branches_Id = Helper.getActiveBranchId(Session); if (ModelState.IsValid) { Guid PayrollPaymentItems_Id = Guid.NewGuid(); //verify remaining hours is enough to cover the session hours. show error for the first error only string SaleInvoiceItems_IdList = string.Join(",", LessonSessions.Select(x => x.SaleInvoiceItems_Id.ToString()).ToArray()); List <SaleInvoiceItemsModel> SaleInvoiceItems = SaleInvoiceItemsController.get_by_IdList(SaleInvoiceItems_IdList); List <SaleInvoiceItemsModel> insufficientRemainingHours = SaleInvoiceItems.Where(x => x.SessionHours_Remaining < model.SessionHours).ToList(); if (insufficientRemainingHours.Count > 0) { return(returnView(LessonSessions, string.Format("Insufficient remaining hours for student {0}", insufficientRemainingHours[0].Customer_UserAccounts_Name))); } //set tutor pay rate List <HourlyRatesModel> hourlyRates = HourlyRatesController.get(null, null, model.Tutor_UserAccounts_Id); bool isFullTimeTutor = false; foreach (HourlyRatesModel hourlyRate in hourlyRates) { if (hourlyRate.FullTimeTutorPayrate > 0) { isFullTimeTutor = true; continue; } } foreach (LessonSessionsModel session in LessonSessions) { SaleInvoiceItemsModel saleInvoiceItem = SaleInvoiceItems.Where(x => x.Id == session.SaleInvoiceItems_Id).FirstOrDefault(); session.Id = Guid.NewGuid(); session.Branches_Id = model.Branches_Id; session.HourlyRates_Rate = 0; session.SessionHours = session.IsScheduleChange ? 0 : session.SessionHours; session.TravelCost = session.IsScheduleChange ? 0 : (int)Math.Ceiling((saleInvoiceItem.TravelCost / saleInvoiceItem.SessionHours) * session.SessionHours); session.TutorTravelCost = session.IsScheduleChange ? 0 : (int)Math.Ceiling((saleInvoiceItem.TutorTravelCost / saleInvoiceItem.SessionHours) * session.SessionHours); session.PayrollPaymentItems_Id = session.IsScheduleChange ? (Guid?)null : PayrollPaymentItems_Id; //Calculate tutor payrate if (!isFullTimeTutor && hourlyRates.Count > 0) { foreach (HourlyRatesModel hourlyRate in hourlyRates) { session.HourlyRates_Rate = Math.Ceiling(hourlyRate.Rate / LessonSessions.Count); if (hourlyRate.LessonPackages_Id == saleInvoiceItem.LessonPackages_Id) //rate for the exact lesson package { break; } } } model.TutorTravelCost = session.TutorTravelCost; add(session); //adjust remaining session hours saleInvoiceItem.SessionHours_Remaining -= session.SessionHours; SaleInvoiceItemsController.update_SessionHours_Remaining(db, Session, saleInvoiceItem.Id, saleInvoiceItem.SessionHours_Remaining, string.Format("Lesson Session on {0:dd/MM/yy HH:mm} for {1:N2} hours. Remaining hours: {2:N2} hours.", session.Timestamp, session.SessionHours, saleInvoiceItem.SessionHours_Remaining)); } db.SaveChanges(); //create payrollpaymentitem if (!model.IsScheduleChange) { //Calculate tutor payrate decimal HourlyRate = 0; if (!isFullTimeTutor && hourlyRates.Count > 0) { foreach (HourlyRatesModel hourlyRate in hourlyRates) { HourlyRate = hourlyRate.Rate; if (hourlyRate.Branches_Id == model.Branches_Id) //rate for the exact lesson package { break; } } } PayrollPaymentItemsController.add(new PayrollPaymentItemsModel() { Id = PayrollPaymentItems_Id, PayrollPayments_Id = null, Timestamp = model.Timestamp, Description = null, Hour = model.IsWaiveTutorFee ? 0 : model.SessionHours, HourlyRate = HourlyRate, TutorTravelCost = model.TutorTravelCost, Amount = PayrollPaymentItemsController.calculateAmount(model.IsWaiveTutorFee, model.SessionHours, HourlyRate, model.TutorTravelCost), UserAccounts_Id = model.Tutor_UserAccounts_Id, Branches_Id = model.Branches_Id, IsFullTime = false }); } return(RedirectToAction(nameof(Index), new { FILTER_Keyword = FILTER_Keyword, FILTER_InvoiceNo = FILTER_InvoiceNo, FILTER_Cancelled = FILTER_Cancelled, FILTER_chkDateFrom = FILTER_chkDateFrom, FILTER_DateFrom = FILTER_DateFrom, FILTER_chkDateTo = FILTER_chkDateTo, FILTER_DateTo = FILTER_DateTo })); } return(returnView(LessonSessions, null)); }
public int TranslateRomanNumeral(string input) { var inputList = input?.ToUpper().ToList(); if (inputList == null || inputList.Any(x => _validNumerals.Select(t => t.Item1).Contains(x) == false)) { throw new ArgumentException(); } char?valForSubtraction = null; int result = 0; bool noAdding = false; int equalSum = 0; for (int i = 0; i < inputList.Count; i++) { var currentNumeral = _validNumerals.FirstOrDefault(s => s.Item1 == inputList[i]); var nextNumeral = i < inputList.Count - 1 ? _validNumerals.FirstOrDefault(s => s.Item1 == inputList[i + 1]) : null; bool currentIsDecimalPower = currentNumeral?.Item3?.Any() ?? false; if (nextNumeral != null) { // Syntax and Semantics checks if ((currentNumeral.Item2 < nextNumeral.Item2) && (currentIsDecimalPower == false || currentNumeral.Item3.Any(s => s == nextNumeral.Item1) == false) || (currentNumeral.Item2 == nextNumeral.Item2) && (currentIsDecimalPower == false || nextNumeral.Item1 == valForSubtraction) || (currentIsDecimalPower && result > 0 && ((nextNumeral.Item2 - currentNumeral.Item2) > result)) || (currentNumeral.Item2 > nextNumeral.Item2) && (nextNumeral.Item1 == valForSubtraction) ) { throw new ArgumentException(); } if (currentNumeral.Item2 == nextNumeral.Item2) { equalSum += equalSum == 0 ? currentNumeral.Item2 + nextNumeral.Item2 : nextNumeral.Item2; int?smallest = null; var list = _validNumerals.Where(p => _validNumerals.FirstOrDefault(s => s.Item1 == currentNumeral.Item1).Item3.Any(s2 => s2 != null && s2 == p.Item1)).ToList(); if (list.Any()) { smallest = list.Select(s3 => s3.Item2).ToList().Min(); } // Another Semantics check if (currentNumeral.Item3 != null && equalSum >= (smallest - currentNumeral.Item2)) { throw new ArgumentException(); } result += noAdding ? 0 : currentNumeral.Item2 + nextNumeral.Item2; noAdding = !noAdding; valForSubtraction = null; } else if (currentNumeral.Item2 < nextNumeral.Item2) { equalSum = 0; result += nextNumeral.Item2 - currentNumeral.Item2; valForSubtraction = currentNumeral.Item1; noAdding = true; } else if (currentNumeral.Item2 > nextNumeral.Item2) { equalSum = 0; result += noAdding ? 0 : currentNumeral.Item2; noAdding = false; valForSubtraction = null; } } else { result += noAdding ? 0 : currentNumeral.Item2; } } return(result); }
protected override List <MenuItem> CreateMenuItems() { townCodesArray = RailTrackRegistry.AllTracks.Select(p => p.logicTrack.ID.FullID) .Where(s => !s.StartsWith(SelectTrackPage.GENERAL_TRACK_PREFIX)) .Select(s => s.GetUntilOrEmpty(SelectTrackPage.TRACK_PARTS_SEPARATOR)) .Distinct() .OrderBy(s => s) .ToArray(); if (townCodesArray.Length == 0) { Terminal.Log("No town found!"); } List <string> townNames = new List <string>(); foreach (var townCode in townCodesArray) { switch (townCode) { case "HB": townNames.Add("Harbor and town"); break; case "GF": townNames.Add("Goods factory and town"); break; case "FF": townNames.Add("Foods factory and town"); break; case "OWN": townNames.Add("Oil well north"); break; case "OWC": townNames.Add("Oil well central"); break; case "CM": townNames.Add("Coal mine"); break; case "SM": townNames.Add("Steel mill"); break; case "CSW": townNames.Add("City SW"); break; case "IME": townNames.Add("Iron ore mine east"); break; case "IMW": townNames.Add("Iron ore mine west"); break; case "FRC": townNames.Add("Forest central"); break; case "FRS": townNames.Add("Forest south"); break; case "FM": townNames.Add("Farm"); break; case "MF": townNames.Add("Machine factory and town"); break; case "MB": townNames.Add("Military base"); break; case "SW": townNames.Add("Sawmill"); break; case "HMB": townNames.Add("Harbor military base"); break; case "MFMB": townNames.Add("Machine factory military base"); break; default: townNames.Add(townCode); break; } } return(townNames.Select(s => new MenuItem(s, null)).ToList()); }
private void butConvertBrand_Click(object sender, EventArgs e) { if (gridMissing.SelectedIndices.Length == 0) { MsgBox.Show(this, "Please select an item from the list before attempting to convert."); return; } List <MedicationPat> listMedPats = (List <MedicationPat>)gridMissing.Rows[gridMissing.SelectedIndices[0]].Tag; List <Medication> listRxCuiMeds = null; Medication medBrand = null; if (listMedPats[0].RxCui != 0) { listRxCuiMeds = Medications.GetAllMedsByRxCui(listMedPats[0].RxCui); medBrand = listRxCuiMeds.FirstOrDefault(x => x.MedicationNum != x.GenericNum); if (medBrand == null && listRxCuiMeds.FirstOrDefault(x => x.MedicationNum == x.GenericNum) != null) //A Generic Medication exists with matching RxCui. { MsgBox.Show(this, "A generic medication matching the RxNorm of the selected medication already exists in the medication list. " + "You cannot create a brand for the selected medication. Use the Convert to Generic button instead."); return; } } if (listRxCuiMeds == null || listRxCuiMeds.Count == 0) //No medications found matching the RxCui { Medication medGeneric = null; if (gridAllMedications.SelectedIndices.Length > 0) { medGeneric = (Medication)gridAllMedications.Rows[gridAllMedications.SelectedIndices[0]].Tag; if (medGeneric.MedicationNum != medGeneric.GenericNum) { medGeneric = null; //The selected medication is a brand medication, not a generic medication. } } if (medGeneric == null) { MsgBox.Show(this, "Please select a generic medication from the All Medications tab before attempting to convert. " + "The selected medication will be used as the generic medication for the new brand medication."); return; } medBrand = new Medication(); medBrand.MedName = listMedPats[0].MedDescript; medBrand.RxCui = listMedPats[0].RxCui; medBrand.GenericNum = medGeneric.MedicationNum; Medications.Insert(medBrand); FormMedicationEdit FormME = new FormMedicationEdit(); FormME.MedicationCur = medBrand; FormME.IsNew = true; FormME.ShowDialog(); //This window refreshes the Medication cache if the user clicked OK. if (FormME.DialogResult != DialogResult.OK) { return; //User canceled. } } else if (medBrand != null && !MsgBox.Show(this, true, "A brand medication matching the RxNorm of the selected medication already exists in the medication list. " + "Click OK to use the existing medication as the brand for the selected medication, or click Cancel to abort.")) { return; } Cursor = Cursors.WaitCursor; MedicationPats.UpdateMedicationNumForMany(medBrand.MedicationNum, listMedPats.Select(x => x.MedicationPatNum).ToList()); FillTab(); Cursor = Cursors.Default; MsgBox.Show(this, "Done."); }
public static void Launch(string name, string path, List <string> args, string cwd = null) { try { if (args == null) { args = new(); } string argsString = ""; argsString = string.Join(" ", args.Select(a => $"\"{a}\"")); Logger.Info($"running {name}: \"{path}\" {argsString}"); List <string> stdOut = new(); List <string> stdErr = new(); using Process p = new(); p.StartInfo.UseShellExecute = false; p.StartInfo.FileName = path; p.StartInfo.UseShellExecute = false; p.StartInfo.CreateNoWindow = true; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.RedirectStandardError = true; args.ForEach(a => p.StartInfo.ArgumentList.Add(a)); if (cwd != null) { p.StartInfo.WorkingDirectory = cwd; } p.ErrorDataReceived += (sender, line) => { if (line.Data != null) { stdErr.Add(line.Data); } }; p.OutputDataReceived += (sender, line) => { if (line.Data != null) { stdOut.Add(line.Data); } }; p.Start(); p.BeginOutputReadLine(); p.BeginErrorReadLine(); bool timeout = !p.WaitForExit(10000); if (!timeout) { p.WaitForExit(); } if (stdErr.Count != 0) { Logger.Warn($"{name}'s output does not indicate success: {string.Join("\n", stdErr)}"); } if (stdOut.Count > 0) { Logger.Info($"{name}'s output: {string.Join("\n", stdOut)}"); } if (timeout) { p.Kill(); Logger.Warn($"{name}: {path} {args} took too long to complete and had to be stopped"); } if (p.ExitCode != 0) { Logger.Warn($"{name}'s exit code does not indicate success. exit code: { p.ExitCode }"); } } catch (Exception ex) { Logger.Warn(ex, $"error while running {name}:"); } }
private IEnumerable <String> GenerateLines(String BuildGradlePath, String BaseDirPath) { var conf = Project.Configurations.Merged(Project.TargetType, HostOperatingSystem, HostArchitecture, TargetOperatingSystem, TargetArchitecture, null, Toolchain, Compiler, CLibrary, CLibraryForm, CppLibrary, CppLibraryForm, ConfigurationType); var confDebug = Project.Configurations.Merged(Project.TargetType, HostOperatingSystem, HostArchitecture, TargetOperatingSystem, TargetArchitecture, null, Toolchain, Compiler, CLibrary, CLibraryForm, CppLibrary, CppLibraryForm, Cpp.ConfigurationType.Debug); var confRelease = Project.Configurations.Merged(Project.TargetType, HostOperatingSystem, HostArchitecture, TargetOperatingSystem, TargetArchitecture, null, Toolchain, Compiler, CLibrary, CLibraryForm, CppLibrary, CppLibraryForm, Cpp.ConfigurationType.Release); var Results = BuildGradleTemplateText.Replace("\r\n", "\n").Split('\n').AsEnumerable(); var SolutionOutputDir = SolutionOutputDirectory.RelativeTo(BaseDirPath).ToString(PathStringStyle.Unix); var ArchitectureType = TargetArchitecture.Value.ToString(); var ProjectTargetName = Project.TargetName ?? ProjectName; var ApplicationId = conf.Options.ContainsKey("gradle.applicationId") ? conf.Options["gradle.applicationId"] : (SolutionName + "." + ProjectTargetName).ToLower(); var ConsumerProguardFiles = conf.Options.ContainsKey("gradle.consumerProguardFiles") ? new List <String> { String.Join(", ", conf.Options["gradle.consumerProguardFiles"].Split(';').Select(d => "'" + d.AsPath().RelativeTo(BaseDirPath).ToString(PathStringStyle.Unix) + "'")) } : new List <String> { }; var ManifestSrcFile = conf.Options.ContainsKey("gradle.manifestSrcFile") ? conf.Options["gradle.manifestSrcFile"].AsPath().RelativeTo(BaseDirPath).ToString(PathStringStyle.Unix) : (InputDirectory / "AndroidManifest.xml").RelativeTo(BaseDirPath).ToString(PathStringStyle.Unix); var JavaSrcDirs = String.Join(", ", conf.Files.Where(f => System.IO.Directory.Exists(f.Path)).Select(f => "'" + f.Path.RelativeTo(BaseDirPath).ToString(PathStringStyle.Unix) + "'")); var ResSrcDirs = conf.Options.ContainsKey("gradle.resSrcDirs") ? String.Join(", ", conf.Options["gradle.resSrcDirs"].Split(';').Select(d => "'" + d.AsPath().RelativeTo(BaseDirPath).ToString(PathStringStyle.Unix) + "'")) : "'" + (InputDirectory / "res").RelativeTo(BaseDirPath).ToString(PathStringStyle.Unix) + "'"; var AssetsSrcDirs = conf.Options.ContainsKey("gradle.assetsSrcDirs") ? String.Join(", ", conf.Options["gradle.assetsSrcDirs"].Split(';').Select(d => "'" + d.AsPath().RelativeTo(BaseDirPath).ToString(PathStringStyle.Unix) + "'")) : "'" + (InputDirectory / "assets").RelativeTo(BaseDirPath).ToString(PathStringStyle.Unix) + "'"; var JarFiles = conf.Options.ContainsKey("gradle.jarFiles") ? conf.Options["gradle.jarFiles"].Split(';').Select(d => d.AsPath().RelativeTo(BaseDirPath).ToString(PathStringStyle.Unix)).ToList() : new List <String> { }; var ProjectDependencies = conf.Options.ContainsKey("gradle.projectDependencies") ? conf.Options["gradle.projectDependencies"].Split(';').ToList() : new List <String> { }; var AndroidAbi = GetArchitectureString(TargetArchitecture.Value); var TempJniLibsDirDebug = confDebug.Options.ContainsKey("gradle.tempJniLibsDirectory") ? confDebug.Options["gradle.tempJniLibsDirectory"].AsPath().RelativeTo(BaseDirPath).ToString(PathStringStyle.Unix) : $"{SolutionOutputDir}/Debug/gradle/{ProjectName}"; var TempJniLibsDirRelease = confRelease.Options.ContainsKey("gradle.tempJniLibsDirectory") ? confRelease.Options["gradle.tempJniLibsDirectory"].AsPath().RelativeTo(BaseDirPath).ToString(PathStringStyle.Unix) : $"{SolutionOutputDir}/Release/gradle/{ProjectName}"; var TargetDirectoryDebug = confDebug.Options.ContainsKey("gradle.targetDirectory") ? confDebug.Options["gradle.targetDirectory"].AsPath() : (SolutionOutputDirectory / $"Debug"); var TargetDirectoryRelease = confRelease.Options.ContainsKey("gradle.targetDirectory") ? confRelease.Options["gradle.targetDirectory"].AsPath() : (SolutionOutputDirectory / $"Release"); if (ConfigurationType == Cpp.ConfigurationType.Debug) { TempJniLibsDirRelease = TempJniLibsDirDebug; TargetDirectoryRelease = TargetDirectoryDebug; } else if (ConfigurationType == Cpp.ConfigurationType.Release) { TempJniLibsDirDebug = TempJniLibsDirRelease; TargetDirectoryDebug = TargetDirectoryRelease; } var SoLibraryPathsDebug = new List <PathString> { TargetDirectoryDebug / $"lib{ProjectTargetName}.so" }; var SoLibraryPathsRelease = new List <PathString> { TargetDirectoryRelease / $"lib{ProjectTargetName}.so" }; foreach (var Lib in confDebug.Libs) { if (Lib.Extension.ToLowerInvariant() != "so") { continue; } var Found = false; foreach (var LibDirectory in confDebug.LibDirectories) { if (System.IO.File.Exists(LibDirectory / Lib)) { SoLibraryPathsDebug.Add(LibDirectory / Lib); Found = true; break; } } if (!Found) { SoLibraryPathsDebug.Add(SolutionOutputDirectory / $"Debug" / Lib); } } foreach (var Lib in confRelease.Libs) { if (Lib.Extension.ToLowerInvariant() != "so") { continue; } var Found = false; foreach (var LibDirectory in confRelease.LibDirectories) { if (System.IO.File.Exists(LibDirectory / Lib)) { SoLibraryPathsRelease.Add(LibDirectory / Lib); Found = true; break; } } if (!Found) { SoLibraryPathsRelease.Add(SolutionOutputDirectory / $"Release" / Lib); } } if ((CppLibrary == CppLibraryType.libcxx) && (CppLibraryForm == CppLibraryForm.Dynamic)) { var LibcxxSo = AndroidNdk / $"toolchains/llvm/prebuilt/{GetHostArchitectureString(HostOperatingSystem, HostArchitecture)}/sysroot/usr/lib/{GetTargetTripletString(TargetArchitecture.Value)}/libc++_shared.so"; SoLibraryPathsDebug.Add(LibcxxSo); SoLibraryPathsRelease.Add(LibcxxSo); } var LibsDebug = String.Join(", ", SoLibraryPathsDebug.Select(p => "'" + p.RelativeTo(BaseDirPath).ToString(PathStringStyle.Unix) + "'")); var LibsRelease = String.Join(", ", SoLibraryPathsRelease.Select(p => "'" + p.RelativeTo(BaseDirPath).ToString(PathStringStyle.Unix) + "'")); Results = Results.Select(Line => Line.Replace("${ApplicationId}", ApplicationId)); Results = Results.SelectMany(Line => Line.Contains("${ConsumerProguardFiles}") ? ConsumerProguardFiles.Select(v => Line.Replace("${ConsumerProguardFiles}", v)) : new List <String> { Line }); Results = Results.Select(Line => Line.Replace("${ManifestSrcFile}", ManifestSrcFile)); Results = Results.Select(Line => Line.Replace("${JavaSrcDirs}", JavaSrcDirs)); Results = Results.Select(Line => Line.Replace("${ResSrcDirs}", ResSrcDirs)); Results = Results.Select(Line => Line.Replace("${AssetsSrcDirs}", AssetsSrcDirs)); Results = Results.Select(Line => Line.Replace("${AndroidAbi}", AndroidAbi)); Results = Results.Select(Line => Line.Replace("${TempJniLibsDirDebug}", TempJniLibsDirDebug)); Results = Results.Select(Line => Line.Replace("${TempJniLibsDirRelease}", TempJniLibsDirRelease)); Results = Results.Select(Line => Line.Replace("${LibsDebug}", LibsDebug)); Results = Results.Select(Line => Line.Replace("${LibsRelease}", LibsRelease)); Results = Results.SelectMany(Line => Line.Contains("${JarFiles}") ? JarFiles.Select(JarDir => Line.Replace("${JarFiles}", JarDir)) : new List <String> { Line }); Results = Results.SelectMany(Line => Line.Contains("${ProjectDependencies}") ? ProjectDependencies.Select(ProjectDependency => Line.Replace("${ProjectDependencies}", ProjectDependency)) : new List <String> { Line }); return(Results); }
public DbCommand CreateCommand(IQueryable query, IEntityType entity, List <Tuple <string, object> > values) { #if NETSTANDARD1_3 Assembly assembly = null; Assembly postgreSqlAssembly = null; try { assembly = Assembly.Load(new AssemblyName("Microsoft.EntityFrameworkCore.SqlServer")); } catch (Exception ex) { try { postgreSqlAssembly = Assembly.Load(new AssemblyName("Npgsql.EntityFrameworkCore.PostgreSQL")); } catch { throw new Exception(ExceptionMessage.BatchOperations_AssemblyNotFound); } } if (assembly != null || postgreSqlAssembly != null) { string tableName = ""; string primaryKeys = ""; if (assembly != null) { var type = assembly.GetType("Microsoft.EntityFrameworkCore.SqlServerMetadataExtensions"); var sqlServerEntityTypeMethod = type.GetMethod("SqlServer", new[] { typeof(IEntityType) }); var sqlServerPropertyMethod = type.GetMethod("SqlServer", new[] { typeof(IProperty) }); var sqlServer = (IRelationalEntityTypeAnnotations)sqlServerEntityTypeMethod.Invoke(null, new[] { entity }); // GET mapping tableName = string.IsNullOrEmpty(sqlServer.Schema) ? string.Concat("[", sqlServer.TableName, "]") : string.Concat("[", sqlServer.Schema, "].[", sqlServer.TableName, "]"); // GET keys mappings var columnKeys = new List <string>(); foreach (var propertyKey in entity.GetKeys().ToList()[0].Properties) { var mappingProperty = sqlServerPropertyMethod.Invoke(null, new[] { propertyKey }); var columnNameProperty = mappingProperty.GetType().GetProperty("ColumnName", BindingFlags.Public | BindingFlags.Instance); columnKeys.Add((string)columnNameProperty.GetValue(mappingProperty)); } // GET primary key join primaryKeys = string.Join(Environment.NewLine + "AND ", columnKeys.Select(x => string.Concat("A.[", x, "] = B.[", x, "]"))); } else if (postgreSqlAssembly != null) { var type = assembly.GetType("Microsoft.EntityFrameworkCore.NpgsqlMetadataExtensions"); var sqlServerEntityTypeMethod = type.GetMethod("Npgsql", new[] { typeof(IEntityType) }); var sqlServerPropertyMethod = type.GetMethod("Npgsql", new[] { typeof(IProperty) }); var sqlServer = (IRelationalEntityTypeAnnotations)sqlServerEntityTypeMethod.Invoke(null, new[] { entity }); // GET mapping tableName = string.IsNullOrEmpty(sqlServer.Schema) ? string.Concat("\"", sqlServer.TableName, "\"") : string.Concat("\"", sqlServer.Schema, "\".\"", sqlServer.TableName, "\""); // GET keys mappings var columnKeys = new List <string>(); foreach (var propertyKey in entity.GetKeys().ToList()[0].Properties) { var mappingProperty = sqlServerPropertyMethod.Invoke(null, new[] { propertyKey }); var columnNameProperty = mappingProperty.GetType().GetProperty("ColumnName", BindingFlags.Public | BindingFlags.Instance); columnKeys.Add((string)columnNameProperty.GetValue(mappingProperty)); } // GET primary key join primaryKeys = string.Join(Environment.NewLine + "AND ", columnKeys.Select(x => string.Concat(tableName + ".\"", x, "\" = B.\"", x, "\""))); } #else var assembly = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(x => x.FullName.StartsWith("Microsoft.EntityFrameworkCore.SqlServer", StringComparison.InvariantCulture)); var postgreSqlAssembly = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(x => x.FullName.StartsWith("Npgsql.EntityFrameworkCore.PostgreSQL", StringComparison.InvariantCulture)); if (assembly != null || postgreSqlAssembly != null) { string tableName = ""; string primaryKeys = ""; if (assembly != null) { var type = assembly.GetType("Microsoft.EntityFrameworkCore.SqlServerMetadataExtensions"); var sqlServerEntityTypeMethod = type.GetMethod("SqlServer", BindingFlags.Public | BindingFlags.Static, null, new[] { typeof(IEntityType) }, null); var sqlServerPropertyMethod = type.GetMethod("SqlServer", BindingFlags.Public | BindingFlags.Static, null, new[] { typeof(IProperty) }, null); var sqlServer = (IRelationalEntityTypeAnnotations)sqlServerEntityTypeMethod.Invoke(null, new[] { entity }); // GET mapping tableName = string.IsNullOrEmpty(sqlServer.Schema) ? string.Concat("[", sqlServer.TableName, "]") : string.Concat("[", sqlServer.Schema, "].[", sqlServer.TableName, "]"); // GET keys mappings var columnKeys = new List <string>(); foreach (var propertyKey in entity.GetKeys().ToList()[0].Properties) { var mappingProperty = sqlServerPropertyMethod.Invoke(null, new[] { propertyKey }); var columnNameProperty = mappingProperty.GetType().GetProperty("ColumnName", BindingFlags.Public | BindingFlags.Instance); columnKeys.Add((string)columnNameProperty.GetValue(mappingProperty)); } // GET primary key join primaryKeys = string.Join(Environment.NewLine + "AND ", columnKeys.Select(x => string.Concat("A.[", x, "] = B.[", x, "]"))); } else if (postgreSqlAssembly != null) { var type = postgreSqlAssembly.GetType("Microsoft.EntityFrameworkCore.NpgsqlMetadataExtensions"); var sqlServerEntityTypeMethod = type.GetMethod("Npgsql", BindingFlags.Public | BindingFlags.Static, null, new[] { typeof(IEntityType) }, null); var sqlServerPropertyMethod = type.GetMethod("Npgsql", BindingFlags.Public | BindingFlags.Static, null, new[] { typeof(IProperty) }, null); var sqlServer = (IRelationalEntityTypeAnnotations)sqlServerEntityTypeMethod.Invoke(null, new[] { entity }); // GET mapping tableName = string.IsNullOrEmpty(sqlServer.Schema) ? string.Concat("\"", sqlServer.TableName, "\"") : string.Concat("\"", sqlServer.Schema, "\".\"", sqlServer.TableName, "\""); // GET keys mappings var columnKeys = new List <string>(); foreach (var propertyKey in entity.GetKeys().ToList()[0].Properties) { var mappingProperty = sqlServerPropertyMethod.Invoke(null, new[] { propertyKey }); var columnNameProperty = mappingProperty.GetType().GetProperty("ColumnName", BindingFlags.Public | BindingFlags.Instance); columnKeys.Add((string)columnNameProperty.GetValue(mappingProperty)); } // GET primary key join primaryKeys = string.Join(Environment.NewLine + "AND ", columnKeys.Select(x => string.Concat(tableName + ".\"", x, "\" = B.\"", x, "\""))); } #endif // GET command text template var commandTextTemplate = #if TODO BatchSize > 0 ? BatchDelayInterval > 0 ? CommandTextWhileDelayTemplate : CommandTextWhileTemplate : #endif assembly == null && postgreSqlAssembly != null ? CommandTextTemplate_PostgreSQL : CommandTextTemplate; // GET inner query #if EFCORE RelationalQueryContext queryContext; var relationalCommand = query.CreateCommand(out queryContext); #else var relationalCommand = query.CreateCommand(); #endif var querySelect = relationalCommand.CommandText; // GET updateSetValues var setValues = ""; if (assembly != null) { setValues = string.Join("," + Environment.NewLine, values.Select((x, i) => x.Item2 is ConstantExpression ? string.Concat("A.[", x.Item1, "] = ", ((ConstantExpression)x.Item2).Value) : string.Concat("A.[", x.Item1, "] = @zzz_BatchUpdate_", i))); } else if (postgreSqlAssembly != null) { setValues = string.Join("," + Environment.NewLine, values.Select((x, i) => x.Item2 is ConstantExpression ? string.Concat("\"", x.Item1, "\" = ", ((ConstantExpression)x.Item2).Value) : string.Concat("\"", x.Item1, "\" = @zzz_BatchUpdate_", i))); } // REPLACE template commandTextTemplate = commandTextTemplate.Replace("{TableName}", tableName) .Replace("{Select}", querySelect) .Replace("{PrimaryKeys}", primaryKeys) .Replace("{SetValue}", setValues); // CREATE command var command = query.GetDbContext().CreateStoreCommand(); command.CommandText = commandTextTemplate; #if EFCORE // ADD Parameter foreach (var relationalParameter in relationalCommand.Parameters) { var parameter = queryContext.ParameterValues[relationalParameter.InvariantName]; var param = command.CreateParameter(); param.CopyFrom(relationalParameter, parameter); command.Parameters.Add(param); } #else // ADD Parameter var parameterCollection = relationalCommand.Parameters; foreach (var parameter in parameterCollection) { var param = command.CreateParameter(); param.CopyFrom(parameter); command.Parameters.Add(param); } #endif for (var i = 0; i < values.Count; i++) { var value = values[i]; if (value.Item2 is ConstantExpression) { continue; } var parameter = command.CreateParameter(); parameter.ParameterName = "@zzz_BatchUpdate_" + i; parameter.Value = values[i].Item2 ?? DBNull.Value; command.Parameters.Add(parameter); } return(command); } return(null); }
/***************************************************/ public static bool IsContaining(this Polyline curve, List <Point> points, bool acceptOnEdge = true, double tolerance = Tolerance.Distance) { // Todo: // check boundingBox/proximity at the beginning! // project to 2D & rewrite methods to 2D to improve performance // - to be replaced with a general method for a nurbs curve? // - could be done with a ray instead of an infinite line! if (curve.IsClosed(tolerance)) { Plane p = curve.FitPlane(tolerance); double sqTol = tolerance * tolerance; if (p == null) { if (acceptOnEdge) { foreach (Point pt in points) { if (curve.ClosestPoint(pt).SquareDistance(pt) > sqTol) { return(false); } } return(true); } else { return(false); } } else { List <Line> subParts = curve.SubParts(); List <Vector> edgeDirections = subParts.Select(c => c.Direction()).ToList(); foreach (Point pt in points) { Point pPt = pt.Project(p); if (pPt.SquareDistance(pt) <= sqTol) { Point end = p.Origin; Vector direction = (end - pPt).Normalise(); while (direction.SquareLength() <= 0.5 || edgeDirections.Any(e => 1 - Math.Abs(e.DotProduct(direction)) <= Tolerance.Angle)) { end = end.Translate(Create.RandomVectorInPlane(p, true)); direction = (end - pPt).Normalise(); } Line ray = new Line { Start = pPt, End = end }; ray.Infinite = true; List <Point> intersects = new List <Point>(); List <Point> extraIntersects = new List <Point>(); Func <double, double, double> ToFactor = (t, n) => (1 - t * t) / (1 - n * n); Line current = subParts[1]; double prevTolFactor = ToFactor(subParts[0].Direction().DotProduct(direction), current.Direction().DotProduct(direction)); for (int i = 1; i < subParts.Count + 1; i++) { Line next = subParts[(i + 1) % subParts.Count]; double nextTolFactor = ToFactor(next.Direction().DotProduct(direction), current.Direction().DotProduct(direction)); Point iPt = current.LineIntersection(ray, false, tolerance); if (iPt != null) { double signedAngle = direction.SignedAngle(current.Direction(), p.Normal); if ((current.Start.SquareDistance(iPt) <= sqTol * prevTolFactor)) // Will we get a point on the previous line { if (signedAngle > Tolerance.Angle) { intersects.Add(iPt); } else { extraIntersects.Add(iPt); } } else if ((current.End.SquareDistance(iPt) <= sqTol * nextTolFactor)) // Will we get a point on the next line { if (signedAngle < -Tolerance.Angle) { intersects.Add(iPt); } else { extraIntersects.Add(iPt); } } else { intersects.Add(iPt); } } prevTolFactor = 1 / nextTolFactor; current = next; } if (intersects.Count == 0) { return(false); } if ((pPt.ClosestPoint(intersects.Union(extraIntersects)).SquareDistance(pPt) <= sqTol)) { if (acceptOnEdge) { continue; } else { return(false); } } intersects.Add(pPt); intersects = intersects.SortCollinear(tolerance); for (int j = 0; j < intersects.Count; j++) { if (j % 2 == 0 && intersects[j] == pPt) { return(false); } } } else { return(false); } } return(true); } } return(false); }
/// <summary> /// Attempts to break cycles in the graph by removing the deepest remove edge, as defined /// by the supplied predicate function. /// </summary> /// <param name="graph">The bidirectional graph to be processed.</param> /// <param name="isRemovable">A function indicating whether or not a particular edge can be removed (i.e. is a "soft" dependency).</param> /// <typeparam name="TVertex">The <see cref="Type" /> of the vertices of the graph.</typeparam> /// <typeparam name="TEdge">The <see cref="Type" /> of the edges of the graph.</typeparam> /// <returns>The list of edges that were removed to break the cycle(s).</returns> /// <exception cref="NonAcyclicGraphException">Occurs if one or more of the cycles present in the graph cannot be broken by removing one of its edges.</exception> public static IReadOnlyList<TEdge> BreakCycles<TVertex, TEdge>(this BidirectionalGraph<TVertex, TEdge> graph, Func<TEdge, bool> isRemovable) where TEdge : IEdge<TVertex> { var removedEdges = new List<TEdge>(); // Get cyclical dependencies found in the graph var cycles = graph.GetCycles(); // Break circular dependencies foreach (var cycle in cycles) { // Last element of Path repeats first element (so ignore duplicate) var distinctPathVertices = cycle.Path.Take(cycle.Path.Count - 1).ToArray(); var sacrificialDependency = distinctPathVertices .Select( (e, i) => { // Get the next entity in the path (circling around to the first entity on the last item) var dependentVertex = distinctPathVertices[(i + 1) % distinctPathVertices.Length]; return new { DependentVertex = dependentVertex, CycleEdges = graph.InEdges(dependentVertex).Where(IsCycleEdge) }; }) .Reverse() .FirstOrDefault(x => x.CycleEdges.All(isRemovable)); if (sacrificialDependency == null) { graph.ValidateGraph(); // Should never get here in this situation, but throw an exception to satisfy code analysis warnings throw new NonAcyclicGraphException(); } // Remove the chosen graph edge(s) to break the cyclical dependency foreach (TEdge edge in sacrificialDependency.CycleEdges.ToArray()) { if (_logger.IsDebugEnabled) { _logger.Debug($"Edge '{edge.ToString()}' removed to prevent the following cycle: {string.Join(" --> ", cycle.Path.Select(x => x.ToString()))}"); } graph.RemoveEdge(edge); removedEdges.Add(edge); } bool IsCycleEdge(TEdge edge) => distinctPathVertices.Contains(edge.Source); } if (_logger.IsDebugEnabled) { _logger.Debug($@"The following edges were removed from the graph to prevent cycles: {string.Join(Environment.NewLine, removedEdges.Select(x => x.ToString()))}"); } return removedEdges; }
/// <summary>Creates a command to execute the batch operation.</summary> /// <param name="query">The query.</param> /// <param name="entity">The schema entity.</param> /// <returns>The new command to execute the batch operation.</returns> internal DbCommand CreateCommand <T>(ObjectQuery query, SchemaEntityType <T> entity, List <Tuple <string, object> > values) { var command = query.Context.CreateStoreCommand(); bool isMySql = command.GetType().FullName.Contains("MySql"); var isSqlCe = command.GetType().Name == "SqlCeCommand"; var isOracle = command.GetType().Namespace.Contains("Oracle"); var isPostgreSQL = command.GetType().Name == "NpgsqlCommand"; // Oracle BindByName if (isOracle) { var bindByNameProperty = command.GetType().GetProperty("BindByName") ?? command.GetType().GetProperty("PassParametersByName"); if (bindByNameProperty != null) { bindByNameProperty.SetValue(command, true, null); } } // GET mapping var mapping = entity.Info.EntityTypeMapping.MappingFragment; var store = mapping.StoreEntitySet; string tableName; if (isMySql) { tableName = string.Concat("`", store.Table, "`"); } else if (isSqlCe) { tableName = string.Concat("[", store.Table, "]"); } else if (isOracle) { tableName = string.IsNullOrEmpty(store.Schema) || store.Schema == "dbo" ? string.Concat("\"", store.Table, "\"") : string.Concat("\"", store.Schema, "\".\"", store.Table, "\""); } else if (isPostgreSQL) { tableName = string.IsNullOrEmpty(store.Schema) ? string.Concat("\"", store.Table, "\"") : string.Concat("\"", store.Schema, "\".\"", store.Table, "\""); } else { tableName = string.IsNullOrEmpty(store.Schema) ? string.Concat("[", store.Table, "]") : string.Concat("[", store.Schema, "].[", store.Table, "]"); } // GET keys mappings var columnKeys = new List <string>(); foreach (var propertyKey in entity.Info.Key.PropertyRefs) { var mappingProperty = mapping.ScalarProperties.Find(x => x.Name == propertyKey.Name); if (mappingProperty == null) { throw new Exception(string.Format(ExceptionMessage.BatchOperations_PropertyNotFound, propertyKey.Name)); } columnKeys.Add(mappingProperty.ColumnName); } // GET command text template var commandTextTemplate = #if TODO BatchSize > 0 ? BatchDelayInterval > 0 ? CommandTextWhileDelayTemplate : CommandTextWhileTemplate : #endif isPostgreSQL ? CommandTextTemplate_PostgreSQL : isOracle ? CommandTextOracleTemplate : isMySql ? CommandTextTemplate_MySQL : isSqlCe ? CommandTextTemplateSqlCe : CommandTextTemplate; // GET inner query var customQuery = query.GetCommandTextAndParameters(); var querySelect = customQuery.Item1; // GET primary key join string primaryKeys; string setValues; if (isSqlCe) { primaryKeys = string.Join(Environment.NewLine + "AND ", columnKeys.Select(x => string.Concat(tableName + ".", EscapeName(x, isMySql, isOracle, isPostgreSQL), " = B.", EscapeName(x, isMySql, isOracle, isPostgreSQL), ""))); setValues = string.Join("," + Environment.NewLine, values.Select((x, i) => x.Item2 is ConstantExpression ? string.Concat(EscapeName(x.Item1, isMySql, isOracle, isPostgreSQL), " = ", ((ConstantExpression)x.Item2).Value.ToString().Replace("B.[", "[")) : string.Concat(EscapeName(x.Item1, isMySql, isOracle, isPostgreSQL), " = @zzz_BatchUpdate_", i))); } else if (isOracle || isPostgreSQL) { primaryKeys = string.Join(Environment.NewLine + "AND ", columnKeys.Select(x => string.Concat(tableName + ".", EscapeName(x, isMySql, isOracle, isPostgreSQL), " = B.", EscapeName(x, isMySql, isOracle, isPostgreSQL), ""))); // GET updateSetValues setValues = string.Join("," + Environment.NewLine, values.Select((x, i) => x.Item2 is ConstantExpression ? string.Concat(EscapeName(x.Item1, isMySql, isOracle, isPostgreSQL), " = ", ((ConstantExpression)x.Item2).Value) : string.Concat(EscapeName(x.Item1, isMySql, isOracle, isPostgreSQL), " = :zzz_BatchUpdate_", i))); } else { primaryKeys = string.Join(Environment.NewLine + "AND ", columnKeys.Select(x => string.Concat("A.", EscapeName(x, isMySql, isOracle, isPostgreSQL), " = B.", EscapeName(x, isMySql, isOracle, isPostgreSQL), ""))); // GET updateSetValues setValues = string.Join("," + Environment.NewLine, values.Select((x, i) => x.Item2 is ConstantExpression ? string.Concat("A.", EscapeName(x.Item1, isMySql, isOracle, isPostgreSQL), " = ", ((ConstantExpression)x.Item2).Value) : string.Concat("A.", EscapeName(x.Item1, isMySql, isOracle, isPostgreSQL), " = @zzz_BatchUpdate_", i))); } // REPLACE template commandTextTemplate = commandTextTemplate.Replace("{TableName}", tableName) .Replace("{Select}", querySelect) .Replace("{PrimaryKeys}", primaryKeys) .Replace("{SetValue}", setValues); // CREATE command command.CommandText = commandTextTemplate; // ADD Parameter var parameterCollection = customQuery.Item2; #if EF5 foreach (ObjectParameter parameter in parameterCollection) { var param = command.CreateParameter(); param.CopyFrom(parameter); command.Parameters.Add(param); } #elif EF6 foreach (DbParameter parameter in parameterCollection) { var param = command.CreateParameter(); param.CopyFrom(parameter); command.Parameters.Add(param); } #endif for (var i = 0; i < values.Count; i++) { var value = values[i]; if (value.Item2 is ConstantExpression) { continue; } var parameterPrefix = isOracle ? ":" : "@"; var parameter = command.CreateParameter(); parameter.ParameterName = parameterPrefix + "zzz_BatchUpdate_" + i; parameter.Value = values[i].Item2 ?? DBNull.Value; command.Parameters.Add(parameter); } return(command); }
/// <summary> /// 开始计算 /// </summary> private void Statistics() { try { int allLogCount = 0; int errorEnterOutLogCount = 0; int validFullEnterOutLogCount = 0; //获取统计的最后一条数据的ID SeatManage.ClassModel.EnterOutLogStatistics lastStatisticsLog = seatManageService.GetLastLog(); DateTime sdt = lastStatisticsLog != null?lastStatisticsLog.SelectSeatTime.AddDays(1) : seatManageService.GetFristLogDate(); if (sdt <= DateTime.Parse("2000-1-1")) { return; } sdt = sdt.AddDays(1); while (true) { //获取进出记录 List <EnterOutLogInfo> enterOutLogList = seatManageService.GetEnterOutBakLogsByDate(sdt); if (enterOutLogList.Count <= 0) { if (sdt >= DateTime.Now.Date.AddDays(-1)) { break; } else { sdt = sdt.AddDays(1); continue; } } sdt = sdt.AddDays(1); allLogCount += enterOutLogList.Count; List <EnterOutLogInfo> eolSelectList = enterOutLogList.FindAll(u => u.EnterOutState == EnterOutLogType.BookingConfirmation || u.EnterOutState == EnterOutLogType.SelectSeat || u.EnterOutState == EnterOutLogType.ReselectSeat || u.EnterOutState == EnterOutLogType.WaitingSuccess).OrderBy(u => u.EnterOutLogID).ToList(); foreach (List <EnterOutLogInfo> eolNoList in eolSelectList.Select(eols => enterOutLogList.FindAll(u => u.EnterOutLogNo == eols.EnterOutLogNo).OrderBy(u => u.EnterOutLogID).ToList()).Where(eolNoList => eolNoList.Count >= 1)) { SeatManage.ClassModel.EnterOutLogStatistics newStatistics = new SeatManage.ClassModel.EnterOutLogStatistics(); newStatistics.CardNo = eolNoList[0].CardNo; newStatistics.SeatNo = eolNoList[0].SeatNo; newStatistics.ReadingRoomNo = eolNoList[0].ReadingRoomNo; newStatistics.EnterOutLogNo = eolNoList[0].EnterOutLogNo; foreach (EnterOutLogInfo eol in eolNoList) { //判断状态 switch (eol.EnterOutState) { case EnterOutLogType.BookingConfirmation: newStatistics.SelectSeat = EnterOutLogSelectSeatMode.BookAdmission; newStatistics.SelectSeatTime = eol.EnterOutTime; break; case EnterOutLogType.WaitingSuccess: newStatistics.SelectSeat = EnterOutLogSelectSeatMode.WaitAdmission; newStatistics.SelectSeatTime = eol.EnterOutTime; break; case EnterOutLogType.ReselectSeat: newStatistics.SelectSeat = EnterOutLogSelectSeatMode.ReSelect; newStatistics.SelectSeatTime = eol.EnterOutTime; break; case EnterOutLogType.SelectSeat: newStatistics.SelectSeat = eol.Flag == Operation.Admin ? EnterOutLogSelectSeatMode.AdminAllocation : EnterOutLogSelectSeatMode.ReadCardSelect; newStatistics.SelectSeatTime = eol.EnterOutTime; break; case EnterOutLogType.ContinuedTime: newStatistics.ContinueTimeCount++; break; case EnterOutLogType.ShortLeave: newStatistics.ShortLeaveCount++; break; case EnterOutLogType.Leave: switch (eol.Flag) { case Operation.Admin: newStatistics.LeaveSeat = EnterOutLogLeaveSeatMode.AdminReleased; break; case Operation.Reader: newStatistics.LeaveSeat = EnterOutLogLeaveSeatMode.ReaderReleased; break; case Operation.Service: newStatistics.LeaveSeat = EnterOutLogLeaveSeatMode.ServerReleased; break; } newStatistics.LastEnterOutLogID = int.Parse(eol.EnterOutLogID); newStatistics.LeaveSeatTime = eol.EnterOutTime; break; } } if (newStatistics.LeaveSeatTime.Date != newStatistics.SelectSeatTime.Date) { errorEnterOutLogCount++; continue; } newStatistics.SeatTime = (int)(newStatistics.LeaveSeatTime - newStatistics.SelectSeatTime).TotalMinutes; //操作次数 newStatistics.AllOperationCount = eolNoList.Count; newStatistics.AdminOperationCount = eolNoList.Count(u => u.Flag == Operation.Admin); newStatistics.OtherOperationCount = eolNoList.Count(u => u.Flag == Operation.OtherReader); newStatistics.ReaderOperationCount = eolNoList.Count(u => u.Flag == Operation.Reader); newStatistics.ServerOperationCount = eolNoList.Count(u => u.Flag == Operation.Service); if (seatManageService.AddEnterOutStatistics(newStatistics) == HandleResult.Successed) { validFullEnterOutLogCount++; } else { errorEnterOutLogCount++; } } } WriteLog.Write(string.Format("数据统计服务:统计进出记录数据{0}条,有效数据{1}条,无效数据{2}条", allLogCount, validFullEnterOutLogCount, errorEnterOutLogCount)); } catch (Exception ex) { WriteLog.Write(string.Format("数据统计服务:统计进出记录失败:{0}", ex.Message)); } }
/// <summary> /// When client pay its drink and wait for coin change. /// </summary> /// <param name="sender">Object sender</param> /// <param name="e">Event args</param> private void btnPayDrink_Click(object sender, System.EventArgs e) { string strInputAmount = tbxInputMoney.Text; double inputAmount = -1; var drinkSelected = cbxSelectDrink.SelectedItem as Drink; if (double.TryParse(strInputAmount, out inputAmount)) { if (inputAmount <= 5.00) { if (drinkSelected != null) { if (inputAmount >= drinkSelected.Price) { double diff = (inputAmount - drinkSelected.Price); // Exact amount. if (diff == 0.00) { MessageBox.Show("Payment OK. You got coin change : " + diff, "Payment OK", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } // Coin change. else { // The different available coin type in coin stock List <CoinStock> availableCoinStock = _clientController.LoadCoinStocks(); List <double> availableCoinTypeValues = availableCoinStock .Select(x => x.CoinType.Value).Distinct().ToList(); // Get all the coin changes solutions recursively. IEnumerable <List <double> > solutionsForChange = _clientController.GetChange(diff, availableCoinTypeValues.AsQueryable()).OrderBy(x => x.Count); // Take the best solution depending on the coin stock. bool canCoinChange = false; Dictionary <double, int> finalSolution = new Dictionary <double, int>(); foreach (var solution in solutionsForChange) { Dictionary <double, int> tempSolution = solution.GroupBy(c => c).ToDictionary(g => g.Key, g => g.Count()); // Confront the solution to the stock (quantities). bool isQuantityAvailable = true; foreach (var coinOfAType in tempSolution) { var correspCoinStock = availableCoinStock .FirstOrDefault ( cs => cs.CoinType.Value == coinOfAType.Key && cs.Quantity >= coinOfAType.Value); if (correspCoinStock == null) { isQuantityAvailable = false; break; } } // If solution quantity matches the coin stocks. if (isQuantityAvailable) { canCoinChange = true; finalSolution = tempSolution; break; } } // Update the stock / show message. if (canCoinChange) { _clientController.UpdateCoinStocksQuantities(finalSolution); string finalMsg = "Payment OK. Coin change transaction :" + Environment.NewLine; foreach (var coinType in finalSolution.OrderBy(x => x.Key)) { finalMsg += string.Format("- {0} x {1}{2}", coinType.Key, coinType.Value, Environment.NewLine); } MessageBox.Show(finalMsg, "Coin change OK", MessageBoxButtons.OK, MessageBoxIcon.Information); } // Show error when no coin availability. else { MessageBox.Show("Coin stock are not available to coin change", "No stocks", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } } else { MessageBox.Show("You can do better than that with a simple coin", "A bigger coin", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } else { MessageBox.Show("Bad drink selection. Maybe a bug...", "Bad drink", MessageBoxButtons.OK, MessageBoxIcon.Error); } } else if (inputAmount > 5.00 && inputAmount < 100.00) { MessageBox.Show("A coin superior to 5 CHF? :)", "Impossible", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } else if (inputAmount > 100.00) { MessageBox.Show("You can't pay by bill or card yet...", "Big amount", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } else { MessageBox.Show(string.Format("Amount tapped '{0}' is invalid", strInputAmount), "Bad input", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
private async void DropDownSelected(object sender, EventArgs e) { // Generate filtered unit list (ex vessel tags) List <StatusModel> list = (List <StatusModel>)statusview.ItemsSource; List <string> droplist = list.Select(c => c.droplist).ToList(); for (int i = droplist.Count - 1; i > -1; i--) { string temp = droplist[i]; if (temp == space) { droplist.RemoveAt(i); } } // Switch expansion variable for selected unit StatusModel selectedmodel = (StatusModel)statusview.SelectedItem; string selectedunit = (string)selectedmodel.droplist; int index = droplist.IndexOf(selectedunit); if (selectedunit.EndsWith("+")) { unitexpanded[index] = 1; SetViewList(); } if (selectedunit.EndsWith("-")) { unitexpanded[index] = 0; SetViewList(); } if (selectedunit.EndsWith(" ")) { string answer = await DisplayActionSheet("Vessel Selection Options", "Cancel", null, "Open CSE Manager", "Open Analytics"); if (answer == null) { } else { //Update global location selection prior to page navigation Globals.init = true; Globals.vessel = selectedmodel.namelist.Remove(0, space.Length); //grabs vessel name of selected row and trims indent spacers //Determine unitname of vessel (without database query) search text list List <string> namelist = list.Select(c => c.namelist).ToList(); index = namelist.IndexOf(selectedmodel.namelist); int track = 0; while (track == 0) //track upwards through list to find unitname { index--; if (namelist[index].First() != ' ') { Globals.unit = namelist[index]; track = 1; } } //Open requested page navigation if (answer == "Open CSE Manager") { await Navigation.PushModalAsync(new CSEntryPage(), false); } if (answer == "Open Analytics") { await Navigation.PushModalAsync(new AnalyticsPage(), false); } } } }
private void OnLocationSelect(decimal plantID) { PLANT plant = SQMModelMgr.LookupPlant(plantID); if (plant == null) { DisplayProfileMessage(lblProfileNotExist); } else { List <BusinessLocation> locationList = new List <BusinessLocation>(); locationList.Add(new BusinessLocation().Initialize(plantID)); List <PERSON> responsibleList = SQMModelMgr.SelectPlantPersonList(locationList, "311", AccessMode.Update); SQMBasePage.SetPersonList(ddlMetricResponsible, responsibleList, ""); SQMBasePage.SetPersonList(ddlFinalApprover, responsibleList.Where(l => l.ROLE < SessionManager.AccessModeRoleXREF(AccessMode.Update)).ToList(), ""); LoadPlantProfile(plant); if (LocalProfile() != null && (LocalProfile().Profile.EHS_PROFILE_MEASURE == null || LocalProfile().Profile.EHS_PROFILE_MEASURE.Count == 0)) { if (UserContext.RoleAccess() > AccessMode.Plant) { List <EHS_PROFILE> profileList = EHSModel.SelectPlantProfileList(SessionManager.UserContext.HRLocation.Company.COMPANY_ID); SQMBasePage.SetLocationList(ddlCopyProfile, SQMModelMgr.SelectBusinessLocationList(SessionManager.UserContext.HRLocation.Company.COMPANY_ID, 0, true).Where(l => profileList.Select(p => p.PLANT_ID).ToArray().Contains(l.Plant.PLANT_ID)).ToList(), 0); ddlCopyProfile.Items.Insert(0, new Telerik.Web.UI.RadComboBoxItem("", "")); responsibleList = SQMModelMgr.SelectPersonList((decimal)plant.COMPANY_ID, (decimal)plant.BUS_ORG_ID, true, false).Where(p => p.ROLE >= SessionManager.AccessModeRoleXREF(AccessMode.Admin) && p.ROLE < SessionManager.AccessModeRoleXREF(AccessMode.View)).OrderBy(l => l.LAST_NAME).ToList(); ddlDefaultResponsible.Items.Clear(); foreach (PERSON person in responsibleList) { if (SQMModelMgr.PersonPlantAccess(person, plant.PLANT_ID)) { ddlDefaultResponsible.Items.Add(new Telerik.Web.UI.RadComboBoxItem(SQMModelMgr.FormatPersonListItem(person), person.PERSON_ID.ToString())); } } ddlDefaultResponsible.Items.Insert(0, new Telerik.Web.UI.RadComboBoxItem("", "")); pnlCopyProfile.Visible = true; } } pnlProfileEdit.Style.Add("display", "none"); } }
public static IEnumerable<TipoDocumentoDTO> Traduzir(this List<TipoDocumento> lista, int idIdioma) { return lista.Select(x => x.Traduzir(idIdioma)); }
private object InvokeBestConstructor(List <ConstructorInfo> constructors, params object[] parameters) { if (constructors.Count == 1) { return(constructors[0].Invoke(parameters)); } var importDecorated = constructors.Where(c => Attribute.IsDefined(c, typeof(UseWithObjectConstructorAttribute))).ToArray(); if (importDecorated.Length == 1) { return(importDecorated[0].Invoke(parameters)); } throw new ObjectLacksCompatibleConstructorException("Could not pick the correct constructor between:" + Environment.NewLine + string.Join("" + Environment.NewLine, constructors.Select(c => c.Name + "(" + string.Join(",", c.GetParameters().Select(p => p.ParameterType))))); }