private List <PokemonData> GetPokemonByPossibleEvolve(IGrouping <PokemonId, PokemonData> pokemon, int limit) { PokemonSettings setting = null; if (!PokeSettings.TryGetValue(pokemon.Key, out setting)) { LogCaller(new LoggerEventArgs(String.Format("Failed to find settings for pokemon {0}", pokemon.Key), LoggerTypes.Info)); return(new List <PokemonData>()); } Candy pokemonCandy = PokemonCandy.FirstOrDefault(x => x.FamilyId == setting.FamilyId); int candyToEvolve = setting.CandyToEvolve; int totalPokemon = pokemon.Count(); int totalCandy = pokemonCandy.Candy_; if (candyToEvolve == 0) { return(new List <PokemonData>()); } int maxPokemon = totalCandy / candyToEvolve; if (maxPokemon > limit) { maxPokemon = limit; } return(pokemon.OrderByDescending(x => x.Cp).Skip(maxPokemon).ToList()); }
private IEnumerable <PlanejamentoDiarioInfantilDto> ObterDadosAulasComponente(IGrouping <string, AulaDiarioBordoDto> aulasComponenteCurricular, bool exibirDetalhamento) { foreach (var aula in aulasComponenteCurricular.OrderByDescending(o => o.DataAula)) { var aulaPlanejamento = new PlanejamentoDiarioInfantilDto(); aulaPlanejamento.AulaId = aula.AulaId; aulaPlanejamento.AulaCJ = aula.AulaCJ; aulaPlanejamento.DataAula = aula.DataAula.ToString("dd/MM/yyyy"); aulaPlanejamento.PlanejamentoRealizado = aula.DataPlanejamento.HasValue; if (aula.DataPlanejamento.HasValue) { aulaPlanejamento.DateRegistro = aula.DataPlanejamento.Value.ToString("dd/MM/yyyy HH:mm"); aulaPlanejamento.Usuario = $"{aula.Usuario} ({aula.UsuarioRf})"; aulaPlanejamento.SecoesPreenchidas = ObterSecoesPreenchidas(aula); if (exibirDetalhamento) { aulaPlanejamento.Planejamento = string.IsNullOrEmpty(aula.Planejamento) ? "" : aula.Planejamento; } } yield return(aulaPlanejamento); } }
public static void Main() { int n = int.Parse(Console.ReadLine()); Company company = new Company(); for (int i = 0; i < n; i++) { string[] line = Console.ReadLine().Split(' '); string name = line[0]; decimal salary = decimal.Parse(line[1]); string position = line[2]; string department = line[3]; string email = "n/a"; int age = -1; if (line.Length == 6) { email = line[4]; age = int.Parse(line.Last()); } else if (line.Length == 5) { int currAge = 0; bool isAge = int.TryParse(line[4], out currAge); if (isAge) { age = currAge; } else { email = line[4]; } } Employee newEmployee = new Employee { Age = age, Department = department, Email = email, Name = name, Position = position, Salary = salary }; company.AddEmployee(newEmployee); } IGrouping <string, Employee> result = company.GetDepartmentWithHighestSalary(); Console.WriteLine($"Highest Average Salary: {result.Key}"); foreach (var each in result.OrderByDescending(x => x.Salary)) { Console.WriteLine($"{each.Name} {each.Salary:f2} {each.Email} {each.Age}"); } }
public static TransactionCategorySummary CreateCategorySummary(this IGrouping <string, Transaction> group) { return(new TransactionCategorySummary { CategoryTitle = group.Key ?? "Uncategorised", TotalAmount = Math.Round(group.Sum(y => y.Amount), 2), AverageAmount = Math.Round(group.Average(y => y.Amount), 2), LargestPurchase = group.OrderByDescending(transaction => Math.Abs(transaction.Amount)).First() }); }
private static void PrintResult(IGrouping <string, Employee> department) { var departmentName = department.Key; Console.WriteLine($"Highest Average Salary: {departmentName}"); department.OrderByDescending(e => e.Salary) .ToList() .ForEach(e => Console.WriteLine(e.ToString())); }
public static ConversationDTO Create(IGrouping <int, Models.Message> conversation, Dictionary <int, Models.User> users, int currentUserId) { return(new ConversationDTO { UserId = conversation.Key, LastMessage = new MessageDTO(conversation.OrderByDescending(m => m.DateOfSending).First(), currentUserId), FirstName = users[conversation.Key].FirstName, LastName = users[conversation.Key].LastName, NumberOfUnreadMessages = conversation.Where(x => !x.IsRead && x.OwnerId == conversation.Key).Count() }); }
private ContactViewModel MapToViewModel(IGrouping <int?, MessageRecipient> grouping, int userId) { MessageRecipient latestMessage = grouping.OrderByDescending(mr => mr.Message.CreatedAt).First(); int unreadMessagesCount = grouping.Count(mr => mr.RecipientUserId == userId && !mr.IsRead); return(_mapper.Map <MessageRecipient, ContactViewModel>(latestMessage, options => { options.Items["UnreadMessagesCount"] = unreadMessagesCount; })); }
private List <PokemonData> GetPokemonByIV(IGrouping <PokemonId, PokemonData> pokemon, int amount) { if (!pokemon.Any()) { return(new List <PokemonData>()); } //Test out first one to make sure things are correct double perfectResult = CalculateIVPerfection(pokemon.First()); return(pokemon.OrderByDescending(x => CalculateIVPerfection(x)).ThenByDescending(x => x.Cp).Skip(amount).ToList()); }
private void InvaderReturnFire() { if (invaderShots.Count() < wave + 1 && random.Next(10) > 10 - wave) //if (true) { var groups = invaders.GroupBy(i => i.Location.X).OrderBy(k => k.Key); IGrouping <int, Invader> group = groups.ToArray()[random.Next(groups.Count())]; Invader invader = group.OrderByDescending(i => i.Location.Y).First(); invaderShots.Add(new Shot(new Point(invader.Area.X + invader.Area.Width / 2, invader.Area.Y), Direction.Down, boundaries)); } }
/// <summary> /// Determines whether a provided sequence of <see cref="Card"/> objects contain a subset of 5 cards who are of the same suit. /// </summary> /// <param name="cards">An <see cref="IEnumerable"/> of <see cref="Card"/> objects.</param> /// <returns>If no appropriate subset is found null, otherwise the value of the highest card in the subset.</returns> public static Value?ContainsFlush(IEnumerable <Card> cards) { IEnumerable <IGrouping <GameValues.Suit, Card> > suitGroups = cards.GroupBy(x => x.Suit); IGrouping <GameValues.Suit, Card> flushGroup = suitGroups.SingleOrDefault(x => x.Count() >= 5); if (flushGroup == null) { return(null); } return(flushGroup.OrderByDescending(x => (int)x.Value).First().Value); }
public static void Main(string[] args) { List <Employee> employees = new List <Employee>(); int count = int.Parse(Console.ReadLine()); for (int i = 0; i < count; i++) { string[] inputArgs = Console.ReadLine().Split(); //Pesho 120.00 Dev Development [email protected] 28 //Toncho 333.33 Manager Marketing 33 string name = inputArgs[0]; decimal salary = decimal.Parse(inputArgs[1]); string position = inputArgs[2]; string department = inputArgs[3]; Employee employee = new Employee(name, salary, position, department); if (inputArgs.Length == 5) { if (int.TryParse(inputArgs[4], out int result)) { employee.Age = result; } else { employee.Email = inputArgs[4]; } } else if (inputArgs.Length == 6) { employee.Email = inputArgs[4]; employee.Age = int.Parse(inputArgs[5]); } employees.Add(employee); } IGrouping <string, Employee> topDepartment = employees .GroupBy(e => e.Department) .OrderByDescending(s => s.Average(e => e.Salary)) .FirstOrDefault(); Console.WriteLine($"Highest Average Salary: {topDepartment.Key}"); foreach (Employee employee in topDepartment.OrderByDescending(e => e.Salary)) { Console.WriteLine($"{employee.Name} {employee.Salary:F2} {employee.Email} {employee.Age}"); } }
private static void CreateTimeline(StringBuilder sb, IGrouping <DateTime, RaidModel> raidDate, bool reverse) { var ordered = reverse ? raidDate.OrderByDescending(i => i.OccurenceEnd) : raidDate.OrderBy(i => i.OccurenceEnd); foreach (var model in ordered) { sb.Append(model.Killed ? HtmlCreator.CreateEncounterHtmlPass(model) : HtmlCreator.CreateEncounterHtmlFail(model)); } }
private List <PokemonData> GetPokemonByPossibleEvolve(IGrouping <PokemonId, PokemonData> pokemon, int limit) { PokemonSettings setting = null; if (!PokeSettings.TryGetValue(pokemon.Key, out setting)) { LogCaller(new LoggerEventArgs(String.Format("Failed to find settings for pokemon {0}", pokemon.Key), LoggerTypes.Info)); return(new List <PokemonData>()); } int pokemonCandy = 0; if (PokemonCandy.Any(x => x.FamilyId == setting.FamilyId)) { pokemonCandy = PokemonCandy.Where(x => x.FamilyId == setting.FamilyId).FirstOrDefault().Candy_; //int pokemonCandy = PokemonCandy.SingleOrDefault(x => x.FamilyId == setting.FamilyId).Candy_; } int candyToEvolve = setting.EvolutionBranch.Select(x => x.CandyCost).FirstOrDefault(); int totalPokemon = pokemon.Count(); if (candyToEvolve == 0) { //Not thinks good return(pokemon.OrderByDescending(x => x.Cp).ToList()); //return new List<PokemonData>(); } int maxPokemon = pokemonCandy / candyToEvolve; if (maxPokemon > limit) { maxPokemon = limit; } return(pokemon.OrderByDescending(x => x.Cp).Skip(maxPokemon).ToList()); }
private IEnumerable <FileBlob> ApplySort(IGrouping <string, FileBlob> hashGroup, KeepOption keepOption) { if (keepOption == KeepOption.Oldest) { return(hashGroup.OrderBy(b => b.OldestTime)); } if (keepOption == KeepOption.Newest) { return(hashGroup.OrderByDescending(b => b.OldestTime)); } throw new ArgumentException("Invalid keep option"); }
public static IOrderedEnumerable <Participant> JudgeGroup(this IGrouping <Rank, Participant> group) { switch (group.Key) { case Rank.HighCard: default: return (group.OrderByDescending(c => c.Hand.H1) .ThenByDescending(c => c.Hand.H2) .ThenByDescending(c => c.Hand.H3) .ThenByDescending(c => c.Hand.H4) .ThenByDescending(c => c.Hand.H5)); case Rank.OnePair: return (group.OrderByDescending(c => c.Hand.PairValue1) .ThenByDescending(c => c.Hand.H3) .ThenByDescending(c => c.Hand.H4) .ThenByDescending(c => c.Hand.H5)); case Rank.TwoPair: return (group.OrderByDescending(c => c.Hand.PairValue1) .ThenByDescending(c => c.Hand.PairValue2) .ThenByDescending(c => c.Hand.H5)); case Rank.ThreeOfAKind: return (group.OrderByDescending(c => c.Hand.PairValue1) .ThenByDescending(c => c.Hand.H4) .ThenByDescending(c => c.Hand.H5)); case Rank.FullHouse: return (group.OrderByDescending(c => c.Hand.PairValue1) .ThenByDescending(c => c.Hand.PairValue2)); case Rank.FourOfAKind: return (group.OrderByDescending(c => c.Hand.PairValue1) .ThenByDescending(c => c.Hand.H5)); case Rank.Straight: case Rank.StraightFlush: case Rank.RoyalFlush: return (group.OrderByDescending(c => c.Hand.H1)); } }
private static void PrintEmployeesWithHighestSalary(Stack <Employee> employees) { if (employees.Count == 0) { return; } IGrouping <string, Employee> highestAverageSalaryDepartment = employees .GroupBy(e => e.Department) .OrderByDescending(g => g.Select(e => e.Salary).Sum()) .First(); Console.WriteLine($"Highest Average Salary: {highestAverageSalaryDepartment.Key}"); Console.WriteLine(string.Join(Environment.NewLine, highestAverageSalaryDepartment .OrderByDescending(e => e.Salary) .Select(e => $"{e.Name} {e.Salary:F2} {e.Email} {e.Age}"))); }
private List <PokemonData> GetPokemonByIV(IGrouping <PokemonId, PokemonData> pokemon, int amount) { if (pokemon.Count() == 0) { return(new List <PokemonData>()); } //Test out first one to make sure things are correct MethodResult <double> perfectResult = CalculateIVPerfection(pokemon.First()); if (!perfectResult.Success) { //Failed return(new List <PokemonData>()); } return(pokemon.OrderByDescending(x => CalculateIVPerfection(x).Data).ThenByDescending(x => x.Cp).Skip(amount).ToList()); }
private static IEnumerable<SecurityAttributeDescriptor> Reduce(IGrouping<string, SecurityAttributeDescriptor> g) { var overrides = g.Where(d => d.Override != SecurityAttributeOverride.None).ToList(); switch (overrides.Count) { case 0: yield return g.OrderByDescending(d => d.AttributeType).First(); break; case 1: var @override = overrides[0]; if (@override.Override == SecurityAttributeOverride.Add) yield return new SecurityAttributeDescriptor(@override.AttributeType, @override.Target, @override.Signature); break; default: throw new ArgumentException(string.Format("Conflicting overrides: {0}", overrides)); } }
private IEnumerable <PlanejamentoDiarioDto> ObterDadosAulasComponente(IGrouping <string, AulaPlanoAulaDto> aulasComponenteCurricular, bool exibirDetalhamento) { foreach (var aula in aulasComponenteCurricular.OrderByDescending(o => o.DataAula)) { var aulaPlanejamento = new PlanejamentoDiarioDto(); aulaPlanejamento.AulaId = aula.AulaId; aulaPlanejamento.AulaCJ = aula.AulaCJ; aulaPlanejamento.DataAula = aula.DataAula.ToString("dd/MM/yyyy"); aulaPlanejamento.QuantidadeAulas = aula.QuantidadeAula; aulaPlanejamento.PlanejamentoRealizado = aula.DataPlanejamento.HasValue; if (aula.DataPlanejamento.HasValue) { aulaPlanejamento.DateRegistro = aula.DataPlanejamento.Value.ToString("dd/MM/yyyy HH:mm"); aulaPlanejamento.Usuario = $"{aula.Usuario} ({aula.UsuarioRf})"; aulaPlanejamento.SecoesPreenchidas = ObterSecoesPreenchidas(aula); aulaPlanejamento.QtdObjetivosEspecificos = aula.QtdObjetivosSelecionados; aulaPlanejamento.QtdSecoesPreenchidas = aula.QtdSecoesPreenchidas; if (exibirDetalhamento) { string ObjetivosSalecionados = ""; if (!string.IsNullOrEmpty(aula.ObjetivosSalecionados)) { var ObjSplit = aula.ObjetivosSalecionados.Split("<br/>"); foreach (var obj in ObjSplit.OrderBy(c => c)) { ObjetivosSalecionados += $"{obj} <br/>"; } } aulaPlanejamento.ObjetivosSelecionados = ObjetivosSalecionados; aulaPlanejamento.MeusObjetivosEspecificos = string.IsNullOrEmpty(aula.ObjetivosEspecificos) ? "" : aula.ObjetivosEspecificos; aulaPlanejamento.DesenvolvimentoAula = string.IsNullOrEmpty(aula.DesenvolvimentoAula) ? "" : aula.DesenvolvimentoAula; } } yield return(aulaPlanejamento); } }
private static IEnumerable <SecurityAttributeDescriptor> Reduce(IGrouping <string, SecurityAttributeDescriptor> g) { var overrides = g.Where(d => d.Override != SecurityAttributeOverride.None).ToList(); switch (overrides.Count) { case 0: yield return(g.OrderByDescending(d => d.AttributeType).First()); break; case 1: var @override = overrides[0]; if (@override.Override == SecurityAttributeOverride.Add) { yield return(new SecurityAttributeDescriptor(@override.AttributeType, @override.Target, @override.Signature)); } break; default: throw new ArgumentException(string.Format("Conflicting overrides: {0}", overrides)); } }
private static IEnumerable <string> OrderSeasonCupTable(IGrouping <string, CupGame> seasonsCupGames) { var finalIds = new[] { "final", "Final", "f" }; Finals = seasonsCupGames .OrderByDescending(x => x.Date) .Where(x => finalIds.Contains(x.Type)); var final = Finals.Last(); if (final == null) { var c = seasonsCupGames.Select(x => x.Type).Distinct(); throw new Exception("cant find cup final"); } // dirty hac to not deal with replays, 2leg games and other shenanigans var winners = new[] { final.Winner, final.Loser }; var others = seasonsCupGames .SelectMany(x => x.Teams) .Distinct() .Except(winners); return(winners.Concat(others).ToList()); }
public static EventStore.Core.Data.ResolvedEvent ResolveState(IGrouping <string, EventStore.Core.Data.ResolvedEvent> events) { var eventToReturn = events.OrderByDescending(x => x.Event.TimeStamp).First(); return(eventToReturn.Event.EventType == "$ProjectionCreated" ? eventToReturn : EventStore.Core.Data.ResolvedEvent.EmptyEvent); }
public ChampionshipResultsViewModel(IGrouping <ChampionshipCategoryDTO, ChampionshipResultItemDTO> @group) { this.category = @group.Key; var list = category.Category == ChampionshipWinningCategories.Druzynowa ? @group.OrderByDescending(x => x.Value).ThenBy(x => x.Position) : @group.OrderBy(x => x.Value).ThenBy(x => x.Position); foreach (var championshipResultItemDto in list) { items.Add(new ChampionshipResultItemViewModel(championshipResultItemDto, Item)); } }
private static MethodInfo GetMostGeneralOverload(IGrouping <string, MethodInfo> kvp) { return(kvp.OrderByDescending(mi => mi.GetParameters().First().ParameterType == typeof(object)).First()); }
public static void DrawHediffRow(Rect rowRect, Pawn pawn, IEnumerable <Hediff> diffs, ref float curY) { rowRect = rowRect.Rounded(); int currentY = (int)curY; var settings = CompactHediffsMod.settings; int column_bodypartWidth = (int)(rowRect.width * 0.375f); //int column_hediffLabelWidth = (int)(rowRect.width - column_bodypartWidth - field_lastMaxIconsTotalWidth.Value); BodyPartRecord part = diffs.First <Hediff>().Part; Hediff replacingPart = null; if (part != null && settings.replacingPartInBodypart) { replacingPart = GetReplacingPart(diffs, part); } string bodyPartText = MakeBodyPartText(pawn, part, replacingPart); int bodypartLabelWidth = (int)(column_bodypartWidth - IconHeight / 2f); int bodyPartLabelHeight = (int)(Text.CalcHeight(bodyPartText, bodypartLabelWidth)); int hediffTotalHeight = 0; List <IGrouping <HediffDef, Hediff> > groupings; if (replacingPart == null) { if (settings.tendPrioritySort) { groupings = diffs.OrderByDescending(i => i.TendableNow(true) ? i.TendPriority : -1).GroupBy(x => x.def).ToList(); } else { groupings = diffs.GroupBy(x => x.def).ToList(); } } else { if (settings.tendPrioritySort) { groupings = diffs.Where(x => x != replacingPart).OrderByDescending(i => i.TendableNow(true) ? i.TendPriority : -1).GroupBy(x => x.def).ToList(); } else { groupings = diffs.Where(x => x != replacingPart).GroupBy(x => x.def).ToList(); } } for (int i = 0; i < groupings.Count; i++) { IGrouping <HediffDef, Hediff> grouping = groupings[i]; string hediffLabel = GenLabelForHediffGroup(grouping); Hediff representativeHediff = grouping.First(); //string hediffLabel = representativeHediff.LabelCap; if (grouping.Count() > 1) { hediffLabel = hediffLabel + " x" + grouping.Count().ToString(); } if (settings.italicizeMissing && representativeHediff.def == HediffDefOf.MissingBodyPart) { hediffLabel = hediffLabel.ApplyTag("i"); } int iconsWidth = CalcIconsWidthForGrouping(grouping, out int iconCount); float iconOverlap = 0; if (iconsWidth > (rowRect.width - column_bodypartWidth) / 2f) { iconOverlap = (((iconsWidth - (rowRect.width - column_bodypartWidth) / 2f)) / (float)iconCount); iconsWidth = (int)((rowRect.width - column_bodypartWidth) / 2f); } int hediffLabelWidth = (int)(rowRect.width - (column_bodypartWidth + iconsWidth)); hediffTotalHeight += (int)(Text.CalcHeight(hediffLabel, hediffLabelWidth)); if (settings.internalSeparator && i < groupings.Count - 1) { hediffTotalHeight += settings.internalSeparatorHeight; } if (settings.severityBarMode != CompactHediffs_Settings.SeverityBarMode.Off) { var hediff = grouping.First(); float maxSeverity = GetMaxSeverityForHediff(hediff); float severityFraction = (hediff.Severity / maxSeverity); if (severityFraction < 0) { severityFraction = 0; } var tendDurationComp = hediff.TryGetComp <HediffComp_TendDuration>(); var immunizableComp = hediff.TryGetComp <HediffComp_Immunizable>(); bool hasImmunity = immunizableComp != null; bool hasSeverity = severityFraction > 0.001f; bool showsSeverity = hediff.SeverityLabel != null; if (settings.showHiddenProgressConditions || showsSeverity) { if (hasImmunity || hasSeverity) { hediffTotalHeight += settings.internalBarHeight; } } } } int totalHeight = Math.Max(bodyPartLabelHeight, hediffTotalHeight); if (settings.horizontalSeparator) { totalHeight += settings.horizontalSeparatorHeight; } Rect wholeEntryRect = new Rect(0f, currentY, rowRect.width, totalHeight).Rounded(); if (settings.evenOddHighlights) { DoWholeRowHighlight(wholeEntryRect); } var separatorColor = settings.separatorNightMode ? Color.black : Color.grey; if (settings.verticalSeparator) { GUI.color = separatorColor; Rect verticalSeparatorRect = new Rect(column_bodypartWidth, currentY, settings.verticalSeparatorWidth, totalHeight).Rounded(); GUI.DrawTexture(verticalSeparatorRect, TexUI.FastFillTex); } if (settings.horizontalSeparator) { GUI.color = separatorColor; Rect horizontalSeparatorRect = new Rect(0, currentY, rowRect.width, settings.horizontalSeparatorHeight).Rounded(); GUI.DrawTexture(horizontalSeparatorRect, TexUI.FastFillTex); currentY += settings.horizontalSeparatorHeight; } if (settings.bodypartHealthbars) { Rect fullHealthPercentageRect = new Rect(0, currentY, column_bodypartWidth, settings.healthBarHeight).Rounded(); if (part != null) { Color healthColor = GetHealthColorForBodypart(pawn, part); float partMaxHealth = getPartMaxHealth(pawn, part); float partHealthFraction = pawn.health.hediffSet.GetPartHealth(part) / partMaxHealth; if (partHealthFraction < 1f) { GUI.color = Color.gray; GUI.DrawTexture(fullHealthPercentageRect, Textures.translucentWhite); if (partHealthFraction == 0) { GUI.color = MissingBodyPart; //GUI.color = Color.black; GUI.DrawTexture(fullHealthPercentageRect, TexUI.FastFillTex); } else { GUI.color = healthColor; Rect healthPercentageRect = new Rect(0, currentY, column_bodypartWidth * partHealthFraction, settings.healthBarHeight); GUI.DrawTexture(healthPercentageRect, Textures.translucentWhite); } } } } if (settings.verticalSeparator) { column_bodypartWidth += settings.verticalSeparatorWidth; } if (part == null) { Widgets.Label(new Rect(0f, currentY, bodypartLabelWidth, 100f), bodyPartText); } else { Widgets.Label(new Rect(0f, currentY, bodypartLabelWidth, 100f), bodyPartText); if (replacingPart != null) { GUI.color = Color.white; int iconOffset = (int)Math.Max((bodyPartLabelHeight - IconHeight) / 2f, 0); Rect iconRect = new Rect(bodypartLabelWidth, currentY + iconOffset, IconHeight / 2f, IconHeight).Rounded(); CustomInfoCardButtonWidget.CustomInfoCardButton(iconRect, replacingPart); } } int innerY = 0; GUI.color = Color.white; for (int i = 0; i < groupings.Count; i++) { IGrouping <HediffDef, Hediff> grouping = groupings[i]; string hediffLabel = GenLabelForHediffGroup(grouping); var hediffsByPriority = grouping.OrderByDescending(x => x.TendableNow(true) ? x.TendPriority : -1); //TextureAndColor stateIcon = null; //float stateSeverity = 0f; //float totalBleedRate = 0f; /*foreach (Hediff heddif in hediffsByPriority) * { * stateIcon = heddif.StateIcon; * if (heddif.def.lethalSeverity > 0f) * stateSeverity = heddif.Severity / heddif.def.lethalSeverity; * else * stateSeverity = -1f; * * totalBleedRate += heddif.BleedRate; * }*/ Hediff representativeHediff = grouping.First(); //string hediffLabel = representativeHediff.LabelCap; if (grouping.Count() > 1) { hediffLabel = hediffLabel + " x" + grouping.Count().ToString(); } if (settings.italicizeMissing && representativeHediff.def == HediffDefOf.MissingBodyPart) { hediffLabel = hediffLabel.ApplyTag("i"); } int iconsWidth = CalcIconsWidthForGrouping(grouping, out int iconCount); float iconOverlap = 1f; if (iconsWidth > (rowRect.width - column_bodypartWidth) / 2f) { iconOverlap = ((rowRect.width - column_bodypartWidth) / 2f) / (float)iconsWidth; iconsWidth = (int)((rowRect.width - column_bodypartWidth) / 2f); } int hediffLabelWidth = (int)((rowRect.width - column_bodypartWidth) - iconsWidth); int hediffTextHeight = (int)Text.CalcHeight(hediffLabel, hediffLabelWidth); int hediffColumnWidth = (int)(rowRect.width - column_bodypartWidth); if (settings.severityBarMode != CompactHediffs_Settings.SeverityBarMode.Off && settings.severityBarsPosition == CompactHediffs_Settings.BarPosition.Above) { foreach (Hediff hediff in grouping) { Rect barRect = new Rect(column_bodypartWidth, currentY + innerY, hediffColumnWidth, settings.internalBarHeight).Rounded(); innerY += DrawSeverityBar(settings, barRect, hediff); } } Rect fullHediffRect = new Rect(column_bodypartWidth, currentY + innerY, rowRect.width - column_bodypartWidth, hediffTextHeight).Rounded(); Rect hediffLabelrect = new Rect(column_bodypartWidth, currentY + innerY, hediffLabelWidth, hediffTextHeight).Rounded(); GUI.color = representativeHediff.LabelColor; Widgets.Label(hediffLabelrect, hediffLabel); GUI.color = Color.white; float widthAccumulator = 0; int iconOffset = (int)Math.Max((fullHediffRect.height - IconHeight) / 2f, 0); //draw info button { Rect iconRect = new Rect(rowRect.width - (IconHeight / 2f), fullHediffRect.y + iconOffset, IconHeight / 2f, IconHeight).Rounded(); CustomInfoCardButtonWidget.CustomInfoCardButton(iconRect, representativeHediff); widthAccumulator += iconRect.width; } var hediffsWithStateIcon = hediffsByPriority.Where(x => x.StateIcon.HasValue); //draw non-injury icons first foreach (Hediff localHediff in hediffsWithStateIcon.Where(x => x.StateIcon.Texture != Textures.Vanilla_TendedIcon_Well_Injury)) { var hediffStateIcon = localHediff.StateIcon; GUI.color = hediffStateIcon.Color; Rect iconRect = new Rect(rowRect.width - (widthAccumulator + IconHeight), fullHediffRect.y + iconOffset, IconHeight, IconHeight).Rounded(); GUI.DrawTexture(iconRect, hediffStateIcon.Texture); widthAccumulator += iconRect.width * iconOverlap; } //draw tended injuries foreach (Hediff localHediff in hediffsWithStateIcon.Where(x => x.StateIcon.Texture == Textures.Vanilla_TendedIcon_Well_Injury).OrderByDescending(x => x.TryGetComp <HediffComp_TendDuration>().tendQuality)) { var hediffStateIcon = localHediff.StateIcon; GUI.color = hediffStateIcon.Color; Rect iconRect; if (settings.tendingIcons) { iconRect = new Rect(rowRect.width - (widthAccumulator + TendIconWidth), fullHediffRect.y + iconOffset, TendIconWidth, IconHeight).Rounded(); DrawCustomTendingIcon(iconRect, localHediff); } else { iconRect = new Rect(rowRect.width - (widthAccumulator + IconHeight), fullHediffRect.y + iconOffset, IconHeight, IconHeight).Rounded(); GUI.DrawTexture(iconRect, hediffStateIcon.Texture); } widthAccumulator += iconRect.width * iconOverlap; } //draw bleeding injuries GUI.color = Color.white; foreach (Hediff localHediff in hediffsByPriority.Where(x => x.Bleeding).OrderByDescending(x => x.BleedRate)) { if (localHediff.Bleeding) { Rect iconRect; if (settings.bleedingIcons) { iconRect = new Rect(rowRect.width - (widthAccumulator + BleedIconWidth), fullHediffRect.y + iconOffset, BleedIconWidth, IconHeight).Rounded(); DrawCustomBleedIcon(iconRect, localHediff); } else { iconRect = new Rect(rowRect.width - (widthAccumulator + IconHeight), fullHediffRect.y + iconOffset, IconHeight, IconHeight).Rounded(); GUI.DrawTexture(iconRect.ContractedBy(GenMath.LerpDouble(0f, 0.6f, 5f, 0f, Mathf.Min(localHediff.BleedRate, 1f))), Textures.Vanilla_BleedingIcon); } widthAccumulator += iconRect.width * iconOverlap; } else { break; } } /*if (totalBleedRate > 0f) * { * Rect iconRect = new Rect(rowRect.width - (widthAccumulator + IconSize), fullHediffRect.y + iconOffset, IconSize, IconSize); * * DrawBleedIcon(iconRect, ); * * widthAccumulator += iconRect.width; * }*/ //field_lastMaxIconsTotalWidth.Value = Math.Max(widthAccumulator, field_lastMaxIconsTotalWidth.Value); innerY += hediffTextHeight; if (settings.severityBarMode != CompactHediffs_Settings.SeverityBarMode.Off && settings.severityBarsPosition == CompactHediffs_Settings.BarPosition.Below) { foreach (Hediff hediff in grouping) { Rect barRect = new Rect(column_bodypartWidth, currentY + innerY, hediffColumnWidth, settings.internalBarHeight).Rounded(); int extraHeight = DrawSeverityBar(settings, barRect, hediff); innerY += extraHeight; fullHediffRect.height += extraHeight; } } if (settings.internalSeparator && i < groupings.Count - 1) { Rect internalSeparatorRect = new Rect(column_bodypartWidth, currentY + innerY, (rowRect.width - column_bodypartWidth), settings.internalSeparatorHeight).Rounded(); GUI.color = separatorColor; GUI.DrawTexture(internalSeparatorRect, TexUI.FastFillTex); innerY += settings.internalSeparatorHeight; fullHediffRect.height += settings.internalSeparatorHeight; } } GUI.color = Color.white; currentY += Math.Max(bodyPartLabelHeight, hediffTotalHeight); if (pawn != null) { if (Widgets.ButtonInvisible(wholeEntryRect, method_CanEntryBeClicked.GetValue <bool>(diffs, pawn))) { method_EntryClicked.GetValue(diffs, pawn); } if (Mouse.IsOver(wholeEntryRect)) { TooltipHandler.TipRegion(wholeEntryRect, new TipSignal(() => method_GetTooltip.GetValue <string>(diffs, pawn, part), (int)currentY + 7857)); if (CompactHediffsMod.pawnmorpherLoaded) { //copied from Pawnmorph.PatchHealthCardUtilityDrawHediffRow string tooltip = method_pawnmorpher_Tooltip.GetValue <string>(diffs); if (tooltip != "") { TooltipHandler.TipRegion(wholeEntryRect, new TipSignal(() => tooltip, (int)currentY + 117857)); } } } } curY = (float)currentY; }
private static ITypeElement TypeFromRuntimeProfilePlatformIfExist(IGrouping <PlatformID, ITypeElement> @group) { return(@group.OrderByDescending(typeElement => typeElement.GetPlatformId(), DefaultPlatformUtil.DefaultPlatformIDComparer).First()); }
private DataAroundEvent[] ComputeOffsetBetweenEvents(IGrouping<string, DataAroundEvent>[] orderEventGroups, IGrouping<string, DataAroundEvent> midGroup) { // compute offset between each event to center group DataAroundEvent[] repivotEvents; repivotEvents = orderEventGroups.SelectMany(@group => @group.Select(d => { var eventPicked = @group.OrderByDescending(e => e.EventDate).FirstOrDefault(g => g.EventDate > DateTime.Today.AddDays(-numberOfPointsAroundEvent)); int busDayDiff = 0; if (eventPicked != null) { busDayDiff = BusDayDiff(midGroup.OrderByDescending(e => e.EventDate).First(x => x.EventDate > DateTime.Today.AddDays(-numberOfPointsAroundEvent)).EventDate, eventPicked.EventDate); } var ar = new DataAroundEvent(d.EventDate, d.Instrument, d.RawData, d.NumPointsAroundEvent, d.EventCode, busDayDiff) { PivotIndex = pivotIndex, }; return ar; })).ToArray(); return repivotEvents; }
public IEnumerable <ExpandoObject> Transform(IEnumerable <dynamic> documents) { int resultsCount = documents.Count(); ExpandoObject[] resultsBatch = _expandoObjectsPool.Rent(resultsCount); for (int resultCount = 0; resultCount < resultsCount; resultCount++) { IGrouping <string, PublishedProviderVersion> publishedProviderVersionGroup = documents .ElementAt(resultCount); if (!publishedProviderVersionGroup.Any(v => v.Status == PublishedProviderStatus.Updated)) { continue; } PublishedProviderVersion updatedPublishedProviderVersion = null; PublishedProviderVersion releasedPublishedProviderVersion = null; foreach (PublishedProviderVersion item in publishedProviderVersionGroup.OrderByDescending(x => x.Version)) { switch (item.Status) { case PublishedProviderStatus.Released: releasedPublishedProviderVersion = item; break; case PublishedProviderStatus.Updated: updatedPublishedProviderVersion = item; break; default: continue; } if (updatedPublishedProviderVersion == null || releasedPublishedProviderVersion == null) { continue; } IDictionary <string, object> row = resultsBatch[resultCount] ?? (resultsBatch[resultCount] = new ExpandoObject()); row["UKPRN"] = updatedPublishedProviderVersion.Provider.UKPRN; row["Provider Has Successor"] = (!string.IsNullOrEmpty(updatedPublishedProviderVersion.Provider.Successor) && string.IsNullOrEmpty(releasedPublishedProviderVersion.Provider.Successor)).ToString(); row["Provider Data Changed"] = updatedPublishedProviderVersion.VariationReasons != null?updatedPublishedProviderVersion.VariationReasons.Any().ToString() : false.ToString(); row["Provider Has Closed"] = (updatedPublishedProviderVersion.Provider.DateClosed != null && releasedPublishedProviderVersion.Provider.DateClosed == null).ToString(); row["Provider Has Opened"] = (updatedPublishedProviderVersion.Provider.DateOpened != null && releasedPublishedProviderVersion.Provider.DateOpened == null).ToString(); row["Variation Reason"] = updatedPublishedProviderVersion.VariationReasons != null?string.Join('|', updatedPublishedProviderVersion.VariationReasons) : string.Empty; row["Current URN"] = updatedPublishedProviderVersion.Provider.URN; row["Current Provider Name"] = updatedPublishedProviderVersion.Provider.Name; row["Current Provider Type"] = updatedPublishedProviderVersion.Provider.ProviderType; row["Current Provider Subtype"] = updatedPublishedProviderVersion.Provider.ProviderSubType; row["Current LA Code"] = updatedPublishedProviderVersion.Provider.LACode; row["Current LA Name"] = updatedPublishedProviderVersion.Provider.Authority; row["Current Open Date"] = updatedPublishedProviderVersion.Provider.DateOpened?.ToString("s"); row["Current Open Reason"] = updatedPublishedProviderVersion.Provider.ReasonEstablishmentOpened; row["Current Close Date"] = updatedPublishedProviderVersion.Provider.DateClosed?.ToString("s"); row["Current Close Reason"] = updatedPublishedProviderVersion.Provider.ReasonEstablishmentClosed; row["Current Successor Provider ID"] = updatedPublishedProviderVersion.Provider.Successor; row["Current Trust Code"] = updatedPublishedProviderVersion.Provider.TrustCode; row["Current Trust Name"] = updatedPublishedProviderVersion.Provider.TrustName; row["Previous URN"] = releasedPublishedProviderVersion.Provider.URN; row["Previous Provider Name"] = releasedPublishedProviderVersion.Provider.Name; row["Previous Provider Type"] = releasedPublishedProviderVersion.Provider.ProviderType; row["Previous Provider Subtype"] = releasedPublishedProviderVersion.Provider.ProviderSubType; row["Previous LA Code"] = releasedPublishedProviderVersion.Provider.LACode; row["Previous LA Name"] = releasedPublishedProviderVersion.Provider.Authority; row["Previous Close Date"] = releasedPublishedProviderVersion.Provider.DateClosed?.ToString("s"); row["Previous Close Reason"] = releasedPublishedProviderVersion.Provider.ReasonEstablishmentClosed; row["Previous Trust Code"] = releasedPublishedProviderVersion.Provider.TrustCode; row["Previous Trust Name"] = releasedPublishedProviderVersion.Provider.TrustName; updatedPublishedProviderVersion = releasedPublishedProviderVersion = null; yield return((ExpandoObject)row); } } _expandoObjectsPool.Return(resultsBatch); }
/// <summary> /// Assigns the release status. /// </summary> /// <param name="processItem">The process item.</param> private static void AssignReleaseStatus(IGrouping<byte?, ProcessComplianceListItem> processItem) { var currentDate = DateTimeHelper.RetrieveCurrentDate(); var currentDateTime = DateTimeHelper.RetrieveCurrentDateTime(); ////For past releases. var processComplianceListItem = processItem.OrderByDescending(u => u.StartDate).FirstOrDefault(u => u.StartDate <= currentDateTime); int missedArtifactsCount; ////When Artifacts are missed. if (processComplianceListItem != null) { missedArtifactsCount = (from listItem in processComplianceListItem.Items where listItem.DueDate < currentDate && listItem.Status != (byte)ArtifactStatus.Completed select listItem).Count(); if (missedArtifactsCount > 0) { processComplianceListItem.ReleaseArtifactsMissedCount = missedArtifactsCount; } } ////When release has not been completed on EndDate. if (processComplianceListItem != null && processComplianceListItem.ReleaseStatus.HasValue && processComplianceListItem.EndDate.HasValue && processComplianceListItem.EndDate < currentDateTime && !processComplianceListItem.ReleaseStatus.Equals((byte)ReleaseStatus.Completed)) { processComplianceListItem.IsReleaseNotCompleted = true; } ////For future releases. processComplianceListItem = processItem.OrderBy(u => u.StartDate).FirstOrDefault(u => u.StartDate >= currentDateTime); ////When Artifacts are missed. if (processComplianceListItem != null) { missedArtifactsCount = (from listItem in processComplianceListItem.Items where listItem.DueDate < currentDate && listItem.Status != (byte)ArtifactStatus.Completed select listItem).Count(); if (missedArtifactsCount > 0) { processComplianceListItem.ReleaseArtifactsMissedCount = missedArtifactsCount; } } ////When risk at release level for future releases. if (processComplianceListItem != null && processComplianceListItem.Items.Any(u => u.ReleaseAtRiskFlag.HasValue && u.ReleaseAtRiskFlag.Value)) { processComplianceListItem.IsReleaseAtRisk = true; } }
public IEnumerable<Article> GetPartArticlesSite(IGrouping<int,Article> site,int partSize) { return site.OrderByDescending(s => s.Id).Take(partSize); }
private List <PokemonData> GetPokemonByStrongest(IGrouping <PokemonId, PokemonData> pokemon, int amount) { return(pokemon.OrderByDescending(x => x.Cp).Skip(amount).ToList()); }