private static StringBuilder GenerateClass2(IGrouping<string, FileInfo> group, bool isLast) { StringBuilder sb = new StringBuilder(); sb.AppendLine($" public class {GetClassName(group.Key)}"); sb.AppendLine(" {"); for (int i = 0; i < group.Count(); i++) { var item = group.ElementAt(i); var renamedAction = GetFiledName(group.ElementAt(i)); sb.AppendLine($" public const string {renamedAction} = \"{GetRelativeName(item.FullName)}\";"); if (i != group.Count() - 1) { sb.AppendLine(); } } sb.AppendLine(" }"); if (!isLast) { sb.AppendLine(); } return sb; }
private static StringBuilder GenerateEnum(IGrouping <string, EnumInfo> group, bool isLast) { StringBuilder sb = new StringBuilder(); sb.AppendLine($" public enum {group.Key}Enum"); sb.AppendLine(" {"); for (int i = 0; i < group.Count(); i++) { var item = group.ElementAt(i); var name = GetFiledName(group.ElementAt(i)); sb.AppendLine($" {name} = {item.Id},"); if (i != group.Count() - 1) { sb.AppendLine(); } } sb.AppendLine(" }"); if (!isLast) { sb.AppendLine(); } return(sb); }
private string GetValue(PrinterTemplate template, IEnumerable <T> models) { var groupSwitchValue = template.GetSwitch(GetTargetTag() + " GROUP"); if (groupSwitchValue != null) { var result = ""; var groups = models.GroupBy(x => GetGroupSelector(x, groupSwitchValue)); foreach (var @group in groups.OrderBy(x => x.Key)) { IGrouping <GroupingKey, T> grp = @group; var gtn = string.Format("{0} GROUP{1}", GetTargetTag(), grp.Key.Name != null ? ":" + grp.Key.Name : ""); var groupTemplate = (template.GetPart(gtn) ?? ""); groupTemplate = Helper.FormatDataIf(grp.Key != null, groupTemplate, "{GROUP KEY}", () => (grp.Key.Name ?? "")); groupTemplate = Helper.FormatDataIf(grp.Key != null, groupTemplate, "{GROUP SUM}", () => grp.Sum(x => GetSumSelector(x)).ToString("#,#0.00")); result += ReplaceValues(groupTemplate, grp.ElementAt(0), template) + "\r\n"; group.ToList().ForEach(x => ProcessItem(x, groupSwitchValue)); result += string.Join("\r\n", grp.SelectMany(x => GetValue(template, x).Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries))); var ftr = string.Format("{0} FOOTER{1}", GetTargetTag(), grp.Key.Name != null ? ":" + grp.Key.Name : ""); var ftrTemplate = template.GetPart(ftr) ?? ""; ftrTemplate = Helper.FormatDataIf(grp.Key != null, ftrTemplate, "{GROUP KEY}", () => (grp.Key.Name ?? "")); ftrTemplate = Helper.FormatDataIf(grp.Key != null, ftrTemplate, "{GROUP SUM}", () => grp.Sum(x => GetSumSelector(x)).ToString("#,#0.00")); result += "\r\n" + ftrTemplate + "\r\n"; } return(result); } return(string.Join("\r\n", models.SelectMany(x => GetValue(template, x).Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries)))); }
private static StringBuilder GenerateClass(IGrouping <string, RouteInfo> group, bool isLast) { string classFullName = $"{group.First().Namespace}.{group.First().ControllerName}Controller"; string crefNamespace = GetCrefNamespace(classFullName, GetConvertedNamespace(group.First().Namespace)); StringBuilder sb = new StringBuilder(); sb.AppendLine($" /// <summary>"); sb.AppendLine($" /// <see cref=\"{crefNamespace}\"/>"); sb.AppendLine($" /// </summary>"); sb.AppendLine($" public class {group.Key}Route"); sb.AppendLine(" {"); for (int i = 0; i < group.Count(); i++) { var item = group.ElementAt(i); var renamedAction = RenameOverloadedAction(group, i); sb.AppendLine(" /// <summary>"); sb.AppendLine($" /// <see cref=\"{crefNamespace}.{item.ActionName}\"/>"); sb.AppendLine(" /// </summary>"); sb.AppendLine($" public const string {renamedAction} = \"{item.Path}\";"); if (i != group.Count() - 1) { sb.AppendLine(); } } sb.AppendLine(" }"); if (!isLast) { sb.AppendLine(); } return(sb); }
private BezekInfoEntity createSummaryBezekRow(IGrouping <int, BezekFileInfo> row) { SharedService validationsService = new SharedService(); var defaultValues = row.First(); var contractSummary = new BezekFileInfo(); long callTimeSum = 0, freeTimeSum = 0, freeSupplierTimeSum = 0; decimal callRateSum = 0, monthlyRateSum = 0; double discountPresent = 0; int amountOfContracts = row.Count(); for (int i = 0; i < amountOfContracts; i++) { var currentContract = row.ElementAt(i); contractSummary.BillingAmount += currentContract.BillingAmount; contractSummary.BillingAmountAfterTax += currentContract.BillingAmountAfterTax; callRateSum += currentContract.CallRate; contractSummary.CallsAmount += currentContract.CallsAmount; callTimeSum += validationsService.GetCurrectTimeSpanTicksByString(currentContract.CallTime); freeTimeSum += validationsService.GetCurrectTimeSpanTicksByString(currentContract.FreeTimeUsage); freeSupplierTimeSum += validationsService.GetCurrectTimeSpanTicksByString(currentContract.FreeTimeUsageSupplier); contractSummary.ConsumptionAmount += currentContract.ConsumptionAmount; discountPresent += currentContract.DiscountPrecent; monthlyRateSum += currentContract.MonthlyRate != null?currentContract.MonthlyRate.Value:0; contractSummary.PriceBeforeDiscount += currentContract.PriceBeforeDiscount; } return(new BezekInfoEntity { Amount = contractSummary.BillingAmount, AmountAfterTax = contractSummary.BillingAmountAfterTax, Description = "", Type = "", CallRate = callRateSum / amountOfContracts, CallsAmount = contractSummary.CallsAmount, CallTime = new TimeSpan(callTimeSum).ToString(), DepartmentNumber = defaultValues.DepartmentNumber, ClientNumber = defaultValues.ClientNumber, ConsumptionAmount = contractSummary.ConsumptionAmount, DiscountPrecent = discountPresent / amountOfContracts, EndDate = defaultValues.EndDateBilling, FreeTimeUsage = new TimeSpan(freeTimeSum).ToString(), FreeTimeUsageSupplier = new TimeSpan(freeSupplierTimeSum).ToString(), GeneralSummaryRowId = defaultValues.GeneralRowId, HebServiceType = "", IsMatched = row.Where(x => !x.IsMatched).Count() == 0, MonthlyRate = monthlyRateSum / amountOfContracts, OriginalClient = defaultValues.OriginalClient, OriginalPayer = defaultValues.OriginalPayer, PayerNumberBezek = defaultValues.PayerNumberBezek, Contract = row.Key, PriceBeforeDiscount = contractSummary.PriceBeforeDiscount, RowId = 0, SecondaryServiceType = "", ServiceType = "", StartDate = defaultValues.StartDateBilling, TimePeriodText = "", CustomerId = defaultValues.CustomerId }); }
/// <summary> /// Find the list of treatments in a group of arms consisting of permutations /// of the same list of treatments by locating a separator and verifying if that /// separator yields the same list of treatments for all grouped arms /// </summary> /// <param name="permutationGroup"></param> private void findTreatmentsInPermutationBySeparator(IGrouping <string, ArmMapping> permutationGroup) { var firstArm = permutationGroup.First().OldArm; char separator = ' '; int skip = 1; bool found = false; while (!found && skip < firstArm.Length) { // We do not expect letters or digits to be separator characters do { separator = firstArm[skip++]; } while ((char.IsLetterOrDigit(separator) || char.IsWhiteSpace(separator)) && skip < firstArm.Length); // if we did find a potential separator character if (skip < firstArm.Length) { // split the first two arms using the selected separator // and compare the resulting lists, if separator is correct // they will yield the same list of treatments var secondArm = permutationGroup.ElementAt(1).OldArm; var firstArmTrts = firstArm.Split(separator).Select(t => t.Trim()); var secondArmTrts = secondArm.Split(separator).Select(t => t.Trim()); if (firstArmTrts.OrderBy(t => t) .SequenceEqual(secondArmTrts.OrderBy(t => t))) { // Store the treatment lists found = true; permutationGroup.First().Treatments.AddRange(firstArmTrts .Select(t => cleanTreatmentSpecialChars(t))); permutationGroup.ElementAt(1).Treatments = secondArmTrts .Select(t => cleanTreatmentSpecialChars(t)).ToList(); if (permutationGroup.Count() > 2) { foreach (var arm in permutationGroup.Skip(2)) { arm.Treatments = arm.OldArm.Split(separator) .Select(t => cleanTreatmentSpecialChars(t.Trim())).ToList(); } } } } } }
static void Main(string[] args) { Customer cs1 = new Customer() { Name = "Ali Veli", SurName = "Korkmaz", Age = 21, BirthDate = new DateTime(1998, 1, 1), IsStudent = true, Nationality = "TC" }; Customer cs2 = new Customer() { Name = "Mehmet", SurName = "Salim", Age = 38, BirthDate = new DateTime(1981, 1, 1), IsStudent = false, Nationality = "TC" }; Customer cs3 = new Customer() { Name = "Mehmet", SurName = "Kemal", Age = 56, BirthDate = new DateTime(1965, 1, 1), IsStudent = false, Nationality = "TC" }; List <Customer> customers = new List <Customer>(); customers.Add(cs1); customers.Add(cs2); customers.Add(cs3); IEnumerable <IGrouping <string, Customer> > filteredList = from cust in customers group cust by cust.Name into custGroup select custGroup; for (int i = 0; i < filteredList.Count(); i++) { IGrouping <string, Customer> groupItem = filteredList.ElementAt(0); var cs = groupItem.ElementAt(0); cs2.Age = 89; } }
public PeerSubscription Select(IGrouping<string, PeerSubscription> potentials) { int current = -1; lock (_currentOrdinals) { _currentOrdinals.TryGetValue(potentials.Key, out current); current = (current + 1) % potentials.Count(); _currentOrdinals[potentials.Key] = current; } return potentials.ElementAt(current); }
private static StringBuilder GenerateClass(IGrouping <string, RouteInfo> group, bool isLast) { string classFullName = $"{group.First().Namespace}.{group.First().ControllerName}Controller"; string crefNamespace = GetCrefNamespace(classFullName, GetConvertedNamespace(group.First().Namespace)); StringBuilder sb = new StringBuilder(); sb.AppendLine($" /// <summary>"); sb.AppendLine($" /// <see cref=\"{crefNamespace}\"/>"); sb.AppendLine($" /// </summary>"); sb.AppendLine($" public class {group.Key}Route"); sb.AppendLine(" {"); for (int i = 0; i < group.Count(); i++) { var item = group.ElementAt(i); var renamedAction = RenameOverloadedAction(group, i); sb.AppendLine(" /// <summary>"); sb.AppendLine($" /// <see cref=\"{crefNamespace}.{item.ActionName}\"/>"); sb.AppendLine(" /// </summary>"); sb.AppendLine($" public const string {renamedAction} = \"{item.Path}\";"); if (config != null && config.GenerateMethod) { sb.AppendLine($" public static async Task<T> {item.ActionName}Async<T>({GeneraParameters(item.Parameters, true, false)})"); sb.AppendLine(" {"); sb.AppendLine($" var routeInfo = new {nameof(RouteInfo)}"); sb.AppendLine(" {"); sb.AppendLine($" {nameof(RouteInfo.HttpMethods)} = \"{item.HttpMethods}\","); sb.AppendLine($" {nameof(RouteInfo.Path)} = {renamedAction},"); sb.Append(GenerateParameters(item.Parameters)); sb.AppendLine(" };"); sb.AppendLine($" return await {nameof(HttpClientAsync)}.{nameof(HttpClientAsync.Async)}<T>(routeInfo{GeneraParameters(item.Parameters, false, true)});"); sb.AppendLine(" }"); } if (i != group.Count() - 1) { sb.AppendLine(); } } sb.AppendLine(" }"); if (!isLast) { sb.AppendLine(); } return(sb); }
private MtuRtoEvaluateResult EvaluateMtuPerformance(IGrouping <int, NetTransferPara> group) { int maxRto = 0; int successCount = 0, timeoutCount = 0; long tansferTotalLen = 0, totalRto = 0; long successTansferTotalLen = 0, successTotalRto = 0; foreach (var item in group) { tansferTotalLen += item.Mtu; totalRto += item.Rto; if (item.IsTimeout) { //统计超时 timeoutCount++; continue; } //统计成功 successCount++; successTansferTotalLen += item.Mtu; successTotalRto += item.Rto; if (maxRto < item.Rto) { maxRto = item.Rto; } } //统计传输性能指标 float unitTimeTrasnferSize = (float)successTansferTotalLen / totalRto; int avgRto, mtu = group.ElementAt(0).Mtu; if (successCount > 0) { //计算成功的平均rto值,成功的平均值再和最大值取平均值 avgRto = ((int)(successTotalRto / successCount) + maxRto) / 2; //Loger.Trace(NetTransferConstant.TRACE_EVENT_ID, null, $"mtu:{mtu},avgRto:{avgRto},总共:{group.Count() }次,成功:{successCount}次,超时:{timeoutCount}次"); avgRto = (int)(avgRto * this._config.RtoAmplitude);//rto多乘以一个振幅,如果没有此值则容易超时 return(new MtuRtoEvaluateResult(unitTimeTrasnferSize, mtu, avgRto, timeoutCount)); } else { //Loger.Warn(NetTransferConstant.WARN_EVENT_ID, null, $"mtu[{group.Key}]全部超时"); return(null); } }
static void PrintExtendedInfo(IGrouping <ushort, SceneEntity> duplicateGroup) { int duplicateCount = duplicateGroup.Count(); for (int i = 0; i < duplicateCount; i++) { SceneEntity entity = duplicateGroup.ElementAt(i); Console.WriteLine("Entity '{0}' is a {1}, at location X:{2}, Y:{3}", i, entity.Object.Name.Name, entity.Position.X.High, entity.Position.Y.High); foreach (var attribute in entity.attributesMap) { Console.WriteLine($"{attribute.Key} = {attribute.Value}"); } Console.WriteLine("**************"); } }
private static StringBuilder GenerateClass(IGrouping <string, RouteInfo> group, bool isLast) { string classFullName = $"{group.First().Namespace}.{group.First().ControllerName}Controller"; string crefNamespace = GetCrefNamespace(classFullName, GetConvertedNamespace(group.First().Namespace)); StringBuilder sb = new StringBuilder(); sb.AppendLine($" /// <summary>"); sb.AppendLine($" /// <see cref=\"{crefNamespace}\"/>"); sb.AppendLine($" /// </summary>"); sb.AppendLine($" public class {group.Key}Route"); sb.AppendLine(" {"); for (int i = 0; i < group.Count(); i++) { var item = group.ElementAt(i); sb.AppendLine(" /// <summary>"); sb.AppendLine($" /// <see cref=\"{crefNamespace}.{item.ActionName}\"/>"); sb.AppendLine(" /// </summary>"); sb.AppendLine($" public const string {item.ActionName} = \"{item.Path}\";"); // TODO if (item.Namespace.Contains("Core.Api")) { sb.AppendLine($" public static async Task<T> {item.ActionName}Async<T>({GeneraParameters(item.Parameters, true, false)})"); sb.AppendLine(" {"); sb.AppendLine($" return await {typeof(HttpClientAsync).FullName}.{nameof(HttpClientAsync.Async2)}<T>({item.ActionName}{GeneraParameters(item.Parameters, false, true)});"); sb.AppendLine(" }"); } if (i != group.Count() - 1) { sb.AppendLine(); } } sb.AppendLine(" }"); if (!isLast) { sb.AppendLine(); } return(sb); }
static void PerformKeep(IGrouping <ushort, SceneEntity> duplicateGroup) { Console.WriteLine("Enter number between 0 and {0}, to indicate which entity to keep. ", duplicateGroup.Count() - 1); ColorConsole.WriteLine("All others in this group will be deleted!", ConsoleColor.Yellow); bool gotValidNumber = false; byte chosenEntityIndex = 0; while (!gotValidNumber) { Console.Write("Choice: "); string input = Console.ReadLine(); if (Byte.TryParse(input, out chosenEntityIndex)) { if (chosenEntityIndex >= 0 && chosenEntityIndex < duplicateGroup.Count()) { gotValidNumber = true; } else { Console.WriteLine("That is not in the valid range."); } } else { Console.WriteLine("Invalid selection!"); } } for (byte b = 0; b < duplicateGroup.Count(); b++) { if (b == chosenEntityIndex) { continue; } var entity = duplicateGroup.ElementAt(b); _scene.Objects.Find(o => o == entity.Object).Entities.Remove(entity); } }
private void HandleDuplicateGroup(IGrouping <ushort, SceneEntity> duplicateGroup) { ushort id = duplicateGroup.Key; int duplicateCount = duplicateGroup.Count(); Console.Write("There are "); ColorConsole.Write(duplicateCount.ToString(), ConsoleColor.Cyan); Console.Write(" entities with the id: "); ColorConsole.Write(id.ToString(), ConsoleColor.Cyan); Console.WriteLine("."); for (int i = 0; i < duplicateCount; i++) { PrintEntitySummary(duplicateGroup.ElementAt(i), i); } bool handled = false; while (!handled) { DuplicateAction duplicateAction = GetAction(); switch (duplicateAction) { case DuplicateAction.Info: PrintExtendedInfo(duplicateGroup); break; case DuplicateAction.Keep: PerformKeep(duplicateGroup); handled = true; break; default: Console.WriteLine("All changes aborted!"); CloseConsole(-2); break; } } }
private static string RenameOverloadedAction(IGrouping <string, RouteInfo> group, int index) { var currentItem = group.ElementAt(index); var sameActionNameGroup = group.GroupBy(o => o.ActionName); foreach (var item in sameActionNameGroup) { if (item.Count() > 1) { for (int i = 1; i < item.Count(); i++) { var element = item.ElementAt(i); if (element == currentItem) { return(element.ActionName + i); } } } } return(currentItem.ActionName); }
private void SimulateMove() { if (!gameCards.Exists(c => c.Status == CardState.Covered)) { state = GameState.GameOver; } if (state == GameState.GameOver) { return; } Card cardA; Card cardB; var potentialCollection = gameCards.Where(c => c.Status == CardState.Covered).ToList(); IGrouping <string, Card> memoryMatch = CheckMemoryForMatch(); if (memoryMatch == null) { // //Pick random card (CARD A) // int posA = random.Next(0, potentialCollection.Count()); cardA = potentialCollection.ElementAt(posA); if (!cardMemory.Contains(cardA)) { cardMemory.Add(cardA); } memoryMatch = CheckMemoryForMatch(); if (memoryMatch == null) { // //Pick random card (CARD B) // potentialCollection.RemoveAt(posA); //Avoid picking cardA again int posB = random.Next(0, potentialCollection.Count()); cardB = potentialCollection.ElementAt(posB); } else { cardA = memoryMatch.ElementAt(0); cardB = memoryMatch.ElementAt(1); } } else { cardA = memoryMatch.ElementAt(0); cardB = memoryMatch.ElementAt(1); } var allRectangles = gameGrid.Children.OfType <Rectangle>().ToList(); var recA = allRectangles.Single(rec => rec.DataContext == cardA); var recB = allRectangles.Single(rec => rec.DataContext == cardB); Wait(6800); PickCard(recA); Wait(4800); PickCard(recB); }
public void KmeanPlusPlus(ref List <MyGrouping <int, Grade> > CentralPoint, System.Collections.Generic.List <IGrouping <int, Grade> > pointList) { Random ran = new Random(); // Khoi tao Student ID bat dau va ket thuc trong danh sach de random vi tri khoi tao int startingStudentID = pointList.First().Key; int endingStudentID = pointList.Last().Key; var temporaryVariable = new MyGrouping <int, Grade>(); // Khoi tao central point dau tien bang cach random CentralPoint.Add(temporaryVariable); int kmeanPlusPlusInitializePoint = ran.Next(startingStudentID, endingStudentID); var TheFisrtPoint = CentralPoint[0]; CopyPoint(ref TheFisrtPoint, pointList.Single(c => c.Key == kmeanPlusPlusInitializePoint)); int Count = 1; // Da ton tai san 1 central point while (true) // Bat dau tim cac central point con lai { if (Count == ClusterAmount) // Thoa so luong cluster yeu cau thi break { break; } List <MyGrouping <double?, Grade> > MinDistanceList = new List <MyGrouping <double?, Grade> >(); // Khoi tao List chua khoang cach be nhat den central point gan nhat cua tat cac cac point foreach (var point in pointList) { List <double?> Result = new List <double?>(); // List chua khoang cach den tung central point cua 1 diem for (int i = 0; i < Count; i++) { var temp = 0; Result.Add(temp); } for (int i = 0; i < this.SubjectAmount; i++) // Cong thuc tinh khoang cach, nhung khong tinh cang bac 2 { for (int j = 0; j < Count; j++) { Result[j] += (point.ElementAt(i).Mark - CentralPoint[j].ElementAt(i).Mark) * (point.ElementAt(i).Mark - CentralPoint[j].ElementAt(i).Mark); } } double?minResult = Result[0]; // Tim ra khoang cach be nhat for (int i = 0; i < Count; i++) { if (Result[i] < minResult) { minResult = Result[i]; } } MyGrouping <double?, Grade> temporaryCentralPoint = new MyGrouping <double?, Grade>(); // khoi tao 1 instance dai dien cho 1 point voi key la khoang cach ngan nhat toi central point gan nhat cua point do temporaryCentralPoint.Key = minResult; for (int j = 0; j < this.SubjectAmount; j++) { temporaryCentralPoint.Add(new Grade { }); } int elementCount = 0; foreach (var c in temporaryCentralPoint) { temporaryCentralPoint.ElementAt(elementCount).Mark = point.ElementAt(elementCount).Mark; elementCount++; } MinDistanceList.Add(temporaryCentralPoint); } IGrouping <double?, Grade> MaxPoint = MinDistanceList.First(); // Sau khi da co duoc ket qua khoang cach cua tung point den central point gan nhat cua no, ta se duyet het tat ca cac khoang cach nay va tim ra khoang cach lon nhat, point tuong ung se tro thanh point tiep theo foreach (var Point in MinDistanceList) // key o day chinh la khoang cach giua 1 point va central point gan nhat cua no { if (Point.Key > MaxPoint.Key) { MaxPoint = Point; } } var TemporaryPoint = new MyGrouping <int, Grade>(); // Copy point cac thanh phan trong 1 reference type variable sang 1 variable khac CentralPoint.Add(TemporaryPoint); for (int j = 0; j < this.SubjectAmount; j++) { CentralPoint[Count].Add(new Grade { }); } int gradeCount = 0; foreach (var c in CentralPoint[Count]) { CentralPoint[Count].ElementAt(gradeCount).Mark = MaxPoint.ElementAt(gradeCount).Mark; gradeCount++; } Count++; // Them thanh cong 1 central point } return; }
public StackElement? CreateStackElement(IGrouping<int, string> words, ref char[,] matrix, int wordIndex, int elementI, List<Restriction> restrictions) { int wCount = wordIndex; bool flag = true; if (restrictions.Count == 0) { var word = words.ElementAt(wCount++).ToCharArray(); WriteWord(matrix, elementI, word); } else { int i = -1; foreach (var word in words) { i++; if (i < wordIndex) continue; flag = true; var wordArray = word.ToCharArray(); foreach (var restriction in restrictions) { if (arr[elementI].orient == Orientation.Horizontal) { if (wordArray[restriction.YRestriction - arr[elementI].yorigin] != restriction.Value) { flag = false; break; } } else { if (wordArray[restriction.XRestriction - arr[elementI].xorigin] != restriction.Value) { flag = false; break; } } } if (flag) { WriteWord(matrix, elementI, wordArray); wCount++; break; } wCount++; } if (!flag) return null; } return new StackElement { Order = elementI, wordIndex = wCount, Restrictions = restrictions }; }
string GetRandomWordFromPool(IGrouping <string, string> anagramPool) { return(anagramPool.ElementAt(new Random().Next(0, anagramPool.Count()))); }