private static string GetHierarchy(CommandContext ctx, DiscordRole role) { string roleString = string.Empty; bool hasAboveRole = false; DiscordRole?rle = null; IOrderedEnumerable <DiscordRole> roles = ctx.Guild.Roles.Values.OrderBy(r => r.Position); if (roles.Any(r => r.Position > role.Position)) { hasAboveRole = true; rle = roles.First(r => r.Position > role.Position); roleString += $"{rle.Mention}\n"; } roleString += $"{(hasAboveRole ? "⠀⠀↑" : "")}\n{role.Mention}\n"; if (roles.Any(r => r.Position < role.Position)) { rle = roles.Last(r => r.Position < role.Position); roleString += $"⠀⠀↑\n{rle.Mention}"; } return(roleString); }
public Task <Tuple <bool, LogRptDto> > GetCheckInforInUseOuts(LogRptDto logRptDto, IEnumerable <LogFile> logFiles) { IOrderedEnumerable <LogFile> logFilesToCheck = from l in logFiles where l.EndEvent.TimeStamp >= logRptDto.OutTime orderby l.StartEvent.TimeStamp select l; if (logFilesToCheck.Any()) { var firstLogFileWithShutdown = (from l in logFiles where l.Shutdowns.Any(x => x.TimeStamp >= logRptDto.OutTime) orderby l.StartEvent.TimeStamp select l).FirstOrDefault(); if (firstLogFileWithShutdown != null) { logFilesToCheck = from l in logFilesToCheck where l.StartEvent.TimeStamp <= firstLogFileWithShutdown.StartEvent.TimeStamp orderby l.StartEvent.TimeStamp select l; if (logFilesToCheck.Any()) { foreach (var logFile in logFilesToCheck) { var InTime = CheckInTimeProcessingService.GetCheckInTime(logRptDto, logFile); if (SetCheckInTime(InTime, logRptDto)) { return(Task.Run(() => Tuple.Create(true, logRptDto))); } } var firstShutdown = firstLogFileWithShutdown.Shutdowns.OrderBy(x => x.TimeStamp) .FirstOrDefault(x => x.TimeStamp > logRptDto.OutTime); if (SetCheckInTime(firstShutdown.TimeStamp, logRptDto)) { return(Task.Run(() => Tuple.Create(true, logRptDto))); } } } else { foreach (var logFile in logFilesToCheck) { var InTime = CheckInTimeProcessingService.GetCheckInTime(logRptDto, logFile); if (SetCheckInTime(InTime, logRptDto)) { return(Task.Run(() => Tuple.Create(true, logRptDto))); } } } } return(Task.Run(() => Tuple.Create(false, logRptDto))); }
public async Task <Embed> GetMarketBoardItem(ulong itemId) { Item item = await ItemAPI.Get(itemId); EmbedBuilder embed = item.ToMbEmbed(); if (item.IsUntradable != 1) { IOrderedEnumerable <MarketAPI.History> prices = await MarketAPI.GetBestPriceFromAllWorlds("Elemental", itemId); if (prices.Any()) { StringBuilder hqBuilder = new StringBuilder(); StringBuilder nqBuilder = new StringBuilder(); if (prices.Any(x => x.Hq == true)) { hqBuilder.AppendLine("High Quality"); } if (prices.Any(x => x.Hq == false)) { nqBuilder.AppendLine("Normal Quality"); } foreach (MarketAPI.History price in prices) { if (price.Hq == true) { hqBuilder.AppendLine(Utils.Characters.Tab + price.ToStringEx()); } if (price.Hq == false) { nqBuilder.AppendLine(Utils.Characters.Tab + price.ToStringEx()); } } if (hqBuilder.Length > 0 && nqBuilder.Length > 0) { hqBuilder.AppendLine(); } embed.AddField("Best Market Board Prices", hqBuilder.ToString() + nqBuilder.ToString()); } } return(embed.Build()); }
Expression WrapExceptions(Expression body) { if (!_exceptionTypeMap.Any()) { return(body); } var catchExps = from map in _exceptionTypeMap let ex = Expression.Parameter(map.Value) select Expression.Catch( ex, Expression.Block( Expression.Throw( Expression.New( typeof(Exception <>) .MakeGenericType(map.Key) .GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance) .Single(), Expression.Convert( Expression.Call( Ref.ImplementationToAbstractionAdapter_ForceAdapt, ex, Expression.Constant(map.Value), Expression.Constant(map.Key), Expression.Constant(this)), map.Key))))); return(Expression.TryCatch(Expression.Block(typeof(void), body), catchExps.ToArray())); }
/// <summary> /// Calculates the various time related properties of a Track /// </summary> private void CalculateTrackDateProperties(IOrderedEnumerable <Location> locations, out DateTime?start, out DateTime?end, out TimeSpan?duration) { var locationsWithDates = locations.Where(x => x.Date != null); s_log.DebugFormat("Calculating time properties of track with {0} locations {1} of those have Date data", locations.Count(), locationsWithDates.Count()); if (locations != null && locations.Any() && locationsWithDates.Any()) { start = locationsWithDates.Min(x => x.Date); end = locationsWithDates.Max(x => x.Date); if (start.HasValue && end.HasValue) { duration = end.Value.Subtract(start.Value); } else { s_log.Debug("Either the Start End Time of track was not found, the duration will be null"); duration = null; } } else { s_log.Debug("No locations were found. StartTime, EndTime and Duration will be null"); start = null; end = null; duration = null; } }
public static List <GroupedItems <T> > CalcPossibilities(List <T> ils) { List <GroupedItems <T> > possibilities = new List <GroupedItems <T> >(); foreach (var groupedByRow in ils.GroupBy(il => il.Row)) { int row = groupedByRow.Key; IOrderedEnumerable <T> ilsInRow = groupedByRow.OrderBy(il => il.Col); if (ilsInRow.Count() > 1) { List <T> linesToNextAdd = new List <T> { ilsInRow.First() }; for (int i = 1; i < ilsInRow.Count(); i++) { if (ilsInRow.ElementAt(i).Col - ilsInRow.ElementAt(i - 1).Col != 1) { AddPossibility(possibilities, linesToNextAdd); linesToNextAdd = new List <T>(); } linesToNextAdd.Add(ilsInRow.ElementAt(i)); } AddPossibility(possibilities, linesToNextAdd); } else if (ilsInRow.Any()) { AddPossibility(possibilities, new List <T> { ilsInRow.First() }); } } return(possibilities); }
public void WriteTableDataBodyForSingleState(AclExpansionEntry aclExpansionEntry) { if (aclExpansionEntry.AccessControlList is StatelessAccessControlList) { HtmlTagWriter.Value(StatelessAclStateHtmlText); } else { IOrderedEnumerable <StateDefinition> stateDefinitions = GetAllStatesForAclExpansionEntry(aclExpansionEntry); if (!stateDefinitions.Any()) { HtmlTagWriter.Value(AclWithNoAssociatedStatesHtmlText); } else { bool firstElement = true; foreach (StateDefinition stateDefiniton in stateDefinitions) { if (!firstElement) { HtmlTagWriter.Value(", "); } string stateName = _settings.ShortenNames ? stateDefiniton.ShortName() : stateDefiniton.DisplayName; HtmlTagWriter.Value(stateName); firstElement = false; } } } }
private EmbedBuilder AddGuildUserInfo(EmbedBuilder embed, SocketGuildUser user) { // add nickname if present if (user.Nickname != null) { embed.AddField("Guild nickname", user.Nickname, true) .WithAuthor($"Intel on {user.Nickname}", _client.CurrentUser.GetSafeAvatarUrl()); } // get roles, respecting hierarchy IOrderedEnumerable <SocketRole> roles = user.Roles.Where(r => r.Id != user.Guild.EveryoneRole.Id).OrderByDescending(r => r.Position); if (roles.Any()) { embed.AddField("Roles", string.Join(", ", roles.Select(r => MentionUtils.MentionRole(r.Id))), true); } else { embed.AddField("Roles", "-"); } embed.Color = roles.FirstOrDefault(r => r.Color != Color.Default)?.Color; // add joined time if (user.JoinedAt != null) { embed.AddField("Time in this guild", (DateTimeOffset.UtcNow - user.JoinedAt.Value).ToLongFriendlyString(), true); } return(embed); }
private static string CreateMethode(string name, IEnumerable <Card> values, bool?collect, CardSet set, CardType type, CardClass cardClass) { IOrderedEnumerable <Card> valuesOrdered = values .Where(p => p.Set == set && (collect == null || p.Collectible == collect) && (type == CardType.INVALID && p.Type != CardType.HERO && p.Type != CardType.HERO_POWER || p.Type == type) && (cardClass == CardClass.INVALID || p.Class == cardClass)) .OrderBy(p => p.Type.ToString()); if (!valuesOrdered.Any()) { return(null); } var str = new StringBuilder(); str.AppendLine($"\t\tprivate static void {name}(IDictionary<string, List<Enchantment>> cards)"); str.AppendLine("\t\t{"); foreach (Card card in valuesOrdered) { str.Append(AddCardString(card)); str.Append(AddCardCode(card)); } str.AppendLine("\t\t}"); return(str.ToString()); }
private static IEnumerable <MilestoneObject> OrderMilestones(IList <MilestoneObject> transformedCollection) { MilestoneObject unknownVersionEntry = transformedCollection.FirstOrDefault(entry => entry.Milestone == null); IEnumerable <MilestoneObject> entriesWithVersion = transformedCollection.Where(entry => entry.Milestone != null); IOrderedEnumerable <MilestoneObject> entriesWithOpenVersion = entriesWithVersion .Where(entry => entry.Milestone?.ClosedAt == null) .OrderByDescending(entry => entry.Milestone.Title); IOrderedEnumerable <MilestoneObject> entriesWithClosedVersion = entriesWithVersion .Where(entry => entry.Milestone?.ClosedAt != null) .OrderByDescending(entry => entry.Milestone?.ClosedAt); List <MilestoneObject> result = new List <MilestoneObject>(); if (unknownVersionEntry != null) { result.Add(unknownVersionEntry); } if (entriesWithOpenVersion.Any()) { result.AddRange(entriesWithOpenVersion); } if (entriesWithClosedVersion.Any()) { result.AddRange(entriesWithClosedVersion); } return(result); }
private static string CreateMethode(string name, IEnumerable <Card> values, bool?collect, CardSet set, CardType type, CardClass cardClass) { string idString = MapCardSetAdventureString(set); IOrderedEnumerable <Card> valuesOrdered = values .Where(p => p.Set == set && (collect == null || p.Collectible == collect) && (type == CardType.INVALID && p.Type != CardType.HERO && p.Type != CardType.HERO_POWER || p.Type == type) && (cardClass == CardClass.INVALID || p.Class == cardClass) && (idString == String.Empty || Adventure && p.Id.StartsWith(idString) || !Adventure && !p.Id.StartsWith(idString))) .OrderBy(p => p.Type.ToString()); if (!valuesOrdered.Any()) { return(null); } var str = new StringBuilder(); str.AppendLine($"\t\tprivate static void {name}(IDictionary<string, Power> cards)"); str.AppendLine("\t\t{"); foreach (Card card in valuesOrdered) { str.Append(AddCardString(card)); str.Append(AddCardCode(card)); } str.AppendLine("\t\t}"); return(str.ToString()); }
public async Task ListMembersAsync(string roleName) { IRole role = await GetRoleInGuildAsync(roleName).ConfigureAwait(false); if (role == null) { return; } IReadOnlyCollection <IGuildUser> guildUsers = await Context.Guild.GetUsersAsync().ConfigureAwait(false); IOrderedEnumerable <string> roleUsers = guildUsers?.Where(x => x.RoleIds.Contains(role.Id)) .Select(x => x.Username) .OrderBy(x => x); if (roleUsers == null || !roleUsers.Any()) { return; } var builder = new EmbedBuilder { Color = new Color(114, 137, 218), Description = $"These are the users assigned to the {role.Name} role:" }; _ = builder.AddField(x => { x.Name = role.Name; x.Value = string.Join(", ", roleUsers); x.IsInline = false; }); _ = await Context.User.SendMessageAsync("", false, builder.Build()).ConfigureAwait(false); await ReplyAndDeleteAsync("I have sent you a private message").ConfigureAwait(false); }
public DisplayPackageViewModel(Package package, User currentUser, IOrderedEnumerable <Package> packageHistory) : this(package, currentUser, (string)null) { HasSemVer2Version = NuGetVersion.IsSemVer2; HasSemVer2Dependency = package.Dependencies.ToList() .Where(pd => !string.IsNullOrEmpty(pd.VersionSpec)) .Select(pd => VersionRange.Parse(pd.VersionSpec)) .Any(p => (p.HasUpperBound && p.MaxVersion.IsSemVer2) || (p.HasLowerBound && p.MinVersion.IsSemVer2)); Dependencies = new DependencySetsViewModel(package.Dependencies); PackageVersions = packageHistory.Select(p => new DisplayPackageViewModel(p, currentUser, GetPushedBy(p, currentUser))); PushedBy = GetPushedBy(package, currentUser); PackageFileSize = package.PackageFileSize; LatestSymbolsPackage = package.LatestSymbolPackage(); if (packageHistory.Any()) { // calculate the number of days since the package registration was created // round to the nearest integer, with a min value of 1 // divide the total download count by this number TotalDaysSinceCreated = Convert.ToInt32(Math.Max(1, Math.Round((DateTime.UtcNow - packageHistory.Min(p => p.Created)).TotalDays))); DownloadsPerDay = TotalDownloadCount / TotalDaysSinceCreated; // for the package DownloadsPerDayLabel = DownloadsPerDay < 1 ? "<1" : DownloadsPerDay.ToNuGetNumberString(); IsDotnetToolPackageType = package.PackageTypes.Any(e => e.Name.Equals("DotnetTool", StringComparison.OrdinalIgnoreCase)); } }
private async Task CmdListModsAsync(SocketCommandContext context, CancellationToken cancellationToken = default) { using IDisposable logScope = _log.BeginCommandScope(context, this); IOrderedEnumerable <StellarisMod> mods = (await _stellarisModsStore.GetAllAsync(cancellationToken).ConfigureAwait(false)).OrderBy(m => m.Name); if (!mods.Any()) { await context.ReplyAsync($"{_einherjiOptions.FailureSymbol} You did not have any mod on the list.", cancellationToken).ConfigureAwait(false); return; } List <string> listStrings = new List <string>(mods.Count()); foreach (StellarisMod mod in mods) { listStrings.Add(ModToListString(mod, listStrings.Count + 1)); } EmbedBuilder embed = new EmbedBuilder() .WithDescription(string.Join('\n', listStrings)) .WithFooter($"Currently you guys are using {listStrings.Count} mods.", context.Client.CurrentUser.GetAvatarUrl()) .WithTimestamp(DateTimeOffset.Now) .WithAuthor("Your Stellaris mods", context.Client.CurrentUser.GetAvatarUrl()); await context.ReplyAsync(null, false, embed.Build(), cancellationToken).ConfigureAwait(false); }
public DisplayPackageViewModel(Package package, IOrderedEnumerable <Package> packageHistory, bool isVersionHistory) : base(package) { Copyright = package.Copyright; if (!isVersionHistory) { Dependencies = new DependencySetsViewModel(package.Dependencies); PackageVersions = packageHistory.Select(p => new DisplayPackageViewModel(p, packageHistory, isVersionHistory: true)); } DownloadCount = package.DownloadCount; LastEdited = package.LastEdited; if (!isVersionHistory && packageHistory.Any()) { // calculate the number of days since the package registration was created // round to the nearest integer, with a min value of 1 // divide the total download count by this number TotalDaysSinceCreated = Convert.ToInt32(Math.Max(1, Math.Round((DateTime.UtcNow - packageHistory.Last().Created).TotalDays))); DownloadsPerDay = TotalDownloadCount / TotalDaysSinceCreated; // for the package } else { TotalDaysSinceCreated = 0; DownloadsPerDay = 0; } DownloadsPerDayLabel = DownloadsPerDay < 1 ? "<1" : DownloadsPerDay.ToNuGetNumberString(); }
private static string CreateMethodeTest(string name, IEnumerable <Card> values, bool?collect, CardSet set, CardType type, CardClass cardClass) { string idString = MapCardSetAdventureString(set); IOrderedEnumerable <Card> valuesOrdered = values.Where(p => p.Set == set && (collect == null || p.Collectible == collect) && (type == CardType.INVALID && p.Type != CardType.HERO && p.Type != CardType.HERO_POWER || p.Type == type) && (cardClass == CardClass.INVALID || p.Class == cardClass) && (idString == String.Empty || Adventure && p.Id.StartsWith(idString) || !Adventure && !p.Id.StartsWith(idString))) .OrderBy(p => p.Type.ToString()); if (!valuesOrdered.Any()) { return(null); } var str = new StringBuilder(); //str.AppendLine("\t[TestClass]"); str.AppendLine($"\tpublic class {name}{UpperCaseFirst(set.ToString())}Test"); str.AppendLine("\t{"); foreach (Card card in valuesOrdered) { var cardNameRx = Rgx.Replace(card.Name, "").Split(' ', '-').ToList(); string cardName = String.Join("", cardNameRx.Select(p => UpperCaseFirst(p)).ToList()); CardClass heroClass1 = card.Class == CardClass.INVALID || card.Class == CardClass.NEUTRAL ? CardClass.MAGE : card.Class; CardClass heroClass2 = card.Class == CardClass.INVALID || card.Class == CardClass.NEUTRAL ? CardClass.MAGE : card.Class; str.Append(AddCardString(card, 1)); str.AppendLine("\t\t[Fact(Skip = \"ignore\")]"); str.AppendLine($"\t\tpublic void {cardName}_{card.Id}()"); str.AppendLine("\t\t{"); str.AppendLine($"\t\t\t// TODO {cardName}_{card.Id} test"); str.AppendLine("\t\t\tvar game = new Game(new GameConfig"); str.AppendLine("\t\t\t{"); str.AppendLine("\t\t\t\tStartPlayer = 1,"); str.AppendLine($"\t\t\t\tPlayer1HeroClass = CardClass.{heroClass1},"); str.AppendLine($"\t\t\t\tPlayer1Deck = new List<Card>()"); str.AppendLine("\t\t\t\t{"); str.AppendLine($"\t\t\t\t\tCards.FromName(\"{card.Name}\"),"); str.AppendLine("\t\t\t\t},"); str.AppendLine($"\t\t\t\tPlayer2HeroClass = CardClass.{heroClass2},"); str.AppendLine("\t\t\t\tShuffle = false,"); str.AppendLine("\t\t\t\tFillDecks = true,"); str.AppendLine("\t\t\t\tFillDecksPredictably = true"); str.AppendLine("\t\t\t});"); str.AppendLine("\t\t\tgame.StartGame();"); str.AppendLine("\t\t\tgame.Player1.BaseMana = 10;"); str.AppendLine("\t\t\tgame.Player2.BaseMana = 10;"); str.AppendLine($"\t\t\t//var testCard = Generic.DrawCard(game.CurrentPlayer, Cards.FromName(\"{card.Name}\"));"); str.AppendLine($"\t\t\t//game.Process(PlayCardTask.Any(game.CurrentPlayer, \"{card.Name}\"));"); str.AppendLine("\t\t}"); str.AppendLine(); } str.AppendLine("\t}"); return(str.ToString()); }
public async Task ListMembersAsync(CommandContext ctx, [RemainingText, Description("The role to display members for")] DiscordRole role) { if (role == null) { IEnumerable <DiscordRole> assignableRoles = await _roleManagementService.GetAssignableRolesAsync(ctx.Guild); role = await GetUserRoleSelectionAsync(assignableRoles, ctx.Channel, ctx.Member, "Role to list members for"); } if (role == null) { await ctx.ErrorAsync("Invalid role"); return; } IReadOnlyCollection <DiscordMember> guildMembers = await ctx.Guild.GetAllMembersAsync(); IOrderedEnumerable <string> roleUsers = guildMembers?.Where(x => x.Roles.Contains(role)) .Select(x => x.DisplayName) .OrderBy(x => x); if (roleUsers == null || !roleUsers.Any()) { await ctx.ErrorAsync("This role does not have any members!"); return; } var builder = new DiscordEmbedBuilder() .WithColor(new DiscordColor(114, 137, 218)) .WithTitle($"These are the users assigned to the {role.Name} role:") .WithDescription(string.Join(", ", roleUsers)); await ctx.RespondDeletableAsync(builder.Build()); }
protected override void OnDraw(Android.Graphics.Canvas canvas) { if (_context == null || compassViewDrawer == null) { return; } var heading = (_context.HeadingX ?? 0) + _context.HeadingCorrector; compassViewDrawer.OnDrawBackground(canvas); //PaintCompass(canvas, heading); if (ShowElevationProfile) { PaintElevationProfileLines(canvas, heading); } if (ShowPointsOfInterest) { if (_poisToBeDisplayed == null) { ShowInfoText(canvas, GetTextNoGPS()); } else if (!_poisToBeDisplayed.Any()) { ShowInfoText(canvas, GetTextNoPOIs()); } else { PaintVisiblePois(canvas, heading); } } }
public async Task ListMembersAsync(CommandContext ctx) { var builder = new DiscordEmbedBuilder() .WithColor(new DiscordColor(114, 137, 218)) .WithDescription("These are the are all the assignable roles and the users assigned to them:"); IEnumerable <DiscordRole> assignableRoles = await _roleManagementService.GetAssignableRolesAsync(ctx.Guild); IReadOnlyCollection <DiscordMember> guildMembers = await ctx.Guild.GetAllMembersAsync(); foreach (DiscordRole role in assignableRoles) { IOrderedEnumerable <string> roleUsers = guildMembers?.Where(m => m.Roles.Contains(role)) .Select(x => x.DisplayName) .OrderBy(x => x); if (roleUsers != null && roleUsers.Any()) { builder.AddField(role.Name, string.Join(", ", roleUsers), false); } else { builder.AddField(role.Name, "-", false); } } await ctx.RespondDeletableAsync(builder.Build()); }
public async Task ListMembersAsync() { var builder = new EmbedBuilder { Color = new Color(114, 137, 218), Description = "These are the are all the assignable roles and the users assigned to them:" }; // Get the role of the bot with permission manage roles IRole botRole = await GetManageRolesRoleAsync().ConfigureAwait(false); // Get all roles that are lower than the bot's role (roles the bot can assign) IReadOnlyCollection <IGuildUser> guildUsers = await Context.Guild.GetUsersAsync().ConfigureAwait(false); foreach (IRole role in Context.Guild.Roles) { if (role.IsMentionable && role.Name != "everyone" && botRole?.Position > role.Position) { IOrderedEnumerable <string> roleUsers = guildUsers?.Where(x => x.RoleIds.Contains(role.Id)) .Select(x => x.Username) .OrderBy(x => x); if (roleUsers != null && roleUsers.Any()) { _ = builder.AddField(x => { x.Name = role.Name; x.Value = string.Join(", ", roleUsers); x.IsInline = false; }); } } } _ = await Context.User.SendMessageAsync("", false, builder.Build()).ConfigureAwait(false); await ReplyAndDeleteAsync("I have sent you a private message").ConfigureAwait(false); }
private Task CmdCommandsAsync(SocketCommandContext context, Match match, CancellationToken cancellationToken = default) { IOrderedEnumerable <IGrouping <string, CommandDescriptor> > commands = this.GetCommandDescriptors(context); if (commands.Any()) { EmbedBuilder embed = this.StartEmbed(context); string prefix = this.GetPrefix(context); StringBuilder commandsList = new StringBuilder(); foreach (IGrouping <string, CommandDescriptor> group in commands) { commandsList.Clear(); foreach (CommandDescriptor cmd in group) { commandsList.Append($"***{prefix}{cmd.DisplayName}***: {cmd.Summary}\n"); } embed.AddField(group.Key, commandsList.ToString(), inline: false); } return(context.ReplyAsync(null, false, embed.Build(), cancellationToken)); } else { return(context.InlineReplyAsync($"{_einherjiOptions.FailureSymbol} Ooops, I detected no commands... this obviously isn't right. Please let {GetAuthorText(context)} know!", cancellationToken)); } }
/// <summary> /// Handles KeyDown event. Returns true if a component accepted and handled the event. /// </summary> public virtual bool KeyDown(KeyEventArgs e) { if (e.Code == _config.GetConsoleKey()) { _console.ToggleVisible(); return(true); } if (_console.IsVisible()) { if (_console.KeyDown(e)) { return(true); } } IOrderedEnumerable <IGuiComponent> inputList = from IGuiComponent comp in _components where comp.RecieveInput orderby comp.ZDepth ascending orderby comp.IsVisible() descending // Invisible controls still recieve input but after everyone else. This is mostly for the inventory and other toggleable components. orderby comp.Focus descending select comp; return(inputList.Any(current => current.KeyDown(e))); }
private bool IsCardEffectPlayedForTeam( IOrderedEnumerable <Tuple <PlayCardEvent, Card> > cardsPlayedOnTeam, EffectCardType effect) { return(cardsPlayedOnTeam .Any(x => x.Item2.EffectType.HasFlag(effect))); }
public DisplayPackageViewModel(Package package, IOrderedEnumerable<Package> packageHistory, bool isVersionHistory) : base(package) { Copyright = package.Copyright; if (!isVersionHistory) { Dependencies = new DependencySetsViewModel(package.Dependencies); PackageVersions = packageHistory.Select(p => new DisplayPackageViewModel(p, packageHistory, isVersionHistory: true)); } DownloadCount = package.DownloadCount; LastEdited = package.LastEdited; if (!isVersionHistory && packageHistory.Any()) { // calculate the number of days since the package registration was created // round to the nearest integer, with a min value of 1 // divide the total download count by this number TotalDaysSinceCreated = Convert.ToInt32(Math.Max(1, Math.Round((DateTime.UtcNow - packageHistory.Last().Created).TotalDays))); DownloadsPerDay = TotalDownloadCount / TotalDaysSinceCreated; // for the package } else { TotalDaysSinceCreated = 0; DownloadsPerDay = 0; } }
private void AddGroupsRecursive(MesMenuDefinitionBase menu, MesStandardMenuItem menuModel) { List <MesMenuItemGroupDefinition> groups = _menuItemGroups .Where(x => x.Parent == menu) .Where(x => !_excludeMenuItemGroups.Contains(x)) .OrderBy(x => x.SortOrder) .ToList(); for (Int32 i = 0; i < groups.Count; i++) { MesMenuItemGroupDefinition group = groups[i]; IOrderedEnumerable <MesMenuItemDefinition> menuItems = _menuItems .Where(x => x.Group == group) .Where(x => !_excludeMenuItems.Contains(x)) .OrderBy(x => x.SortOrder); foreach (MesMenuItemDefinition menuItem in menuItems) { MesStandardMenuItem menuItemModel = (menuItem.CommandDefinition != null) ? new MesCommandMenuItem(_commandService.GetCommand(menuItem.CommandDefinition), menuModel) : (MesStandardMenuItem) new MesTextMenuItem(menuItem); AddGroupsRecursive(menuItem, menuItemModel); menuModel.Add(menuItemModel); } if (i < groups.Count - 1 && menuItems.Any()) { menuModel.Add(new MesMenuItemSeparator()); } } }
// Output duplicate users to console public static void OutputDuplicatedUsersToConsole(IEnumerable <ZdUser> zdUsers, IOrderedEnumerable <IGrouping <string, ZdUser> > duplicatedUsersGrouped) { if (duplicatedUsersGrouped.Any()) { Console.WriteLine($"Total # user records: {zdUsers.Count()}, # duplicated users: {duplicatedUsersGrouped.Count()}"); Console.WriteLine(""); Console.WriteLine("User name\tEmail\tRole\tUpdated"); bool firstLine; foreach (var userGroup in duplicatedUsersGrouped) { firstLine = true; foreach (var user in userGroup) { if (firstLine) { Console.WriteLine($"{user.Name}\t{user.Email}\t{user.Role}\t{user.UpdatedAt}"); firstLine = false; } else { Console.WriteLine($"\t{user.Email}\t{user.Role}\t{user.UpdatedAt}"); } } } } }
public Port GetNextDestination() { Port nextDestination = null; if (CurrentLocation == null) { return(_ports.First().Value); } int currentRegionNumber = _ports.First(x => x.Value == CurrentLocation).Key; bool portsInThisRegion = _ports.Any(x => x.Key == currentRegionNumber && x.Value != CurrentLocation); if (portsInThisRegion) { nextDestination = getNextDestinationFromCurrentRegion(currentRegionNumber); } if (nextDestination == null) { //go to next region int nextRegionNumber = currentRegionNumber + 1; nextDestination = _ports.First(x => x.Key == nextRegionNumber).Value; } return(nextDestination); }
private string ForTableFlightRecords(PrintOptions printOptions = null) { AirportStatUtils.AirportStatsLogger(Log.FromPool("").WithCodepoint()); string str = string.Empty; IOrderedEnumerable <FlightRecord> flightRecords = string.IsNullOrWhiteSpace(printOptions.AirlineName) ? flights[printOptions.Day].OrderBy(x => x.arrivalTime).ThenBy(x => x.airline) : flights[printOptions.Day].Where(x => x.airline == printOptions.AirlineName).OrderBy(x => x.arrivalTime).ThenBy(x => x.airline); if (!flightRecords.Any()) { return(str); } str += "<tbody>"; bool oddRow = false; foreach (FlightRecord fr in flightRecords) { str += $"<tr{(oddRow ? " class=\"oddRow\"" : string.Empty)}>\n"; if (string.IsNullOrWhiteSpace(printOptions.AirlineName)) { str += $"<td><a href=\"/{fr.airline}?Day={printOptions.Day}\">{fr.airline}</a></td>\n"; } str += $"<td class=\"None\"><a class=\"ajax-dialog\" href=\"/aircraftstats?aircraft={fr.aircraft}\" rel=\"#dialog\">{fr.aircraft}</a></td>\n"; str += $"<td class=\"None\">{fr.originalGate}</td>\n"; str += $"<td class=\"None\">{DateTime.MinValue.AddSeconds(fr.arrivalTime * 60):t}</td>\n"; str += $"<td class=\"{(fr.actual_arrivalTime <= 0 ? AirportStatUtils.InfoLevels.None : fr.actual_arrivalTime > fr.arrivalTime ? AirportStatUtils.InfoLevels.Info : AirportStatUtils.InfoLevels.None)}\">{(fr.actual_arrivalTime > 0 ? DateTime.MinValue.AddSeconds(fr.actual_arrivalTime * 60).ToString("t") : string.Empty)}</td>\n"; str += $"<td class=\"None\">{DateTime.MinValue.AddSeconds(fr.departureTime * 60):t}</td>\n"; str += $"<td class=\"{(fr.actual_departureTime <= 0 ? AirportStatUtils.InfoLevels.None : fr.actual_departureTime - fr.departureTime > 15 ? AirportStatUtils.InfoLevels.Warning : fr.actual_departureTime - fr.departureTime > 0 ? AirportStatUtils.InfoLevels.Info : AirportStatUtils.InfoLevels.None)}\">{(fr.actual_departureTime > 0 ? DateTime.MinValue.AddSeconds(fr.actual_departureTime * 60).ToString("t") : string.Empty)}</td>\n"; str += $"<td class=\"None\">{fr.nArriving:#}</td>\n"; str += $"<td class=\"None\">{(fr.actual_arrivalTime > 0 ? new TimeSpan(0, 0, (int)fr.time_deplaning * 60).ToString("g") : string.Empty)}</td>\n"; str += $"<td class=\"None\">{fr.nDeparting:#}</td>\n"; str += $"<td class=\"None\">{fr.nCheckedIn:#}</td>\n"; str += $"<td class=\"{(fr.actual_departureTime <=0 ? AirportStatUtils.InfoLevels.None : fr.nBoarded < fr.nDeparting ? AirportStatUtils.InfoLevels.Warning : AirportStatUtils.InfoLevels.None)}\">{fr.nBoarded:#}</td>\n"; str += $"<td class=\"None\">{(fr.nBoarded > 0 ? new TimeSpan(0, 0, (int)fr.time_boarding * 60).ToString("g") : string.Empty)}</td>\n"; str += $"<td class=\"None\">{fr.nArrivalBags:#}</td>\n"; str += $"<td class=\"None\">{fr.nBagsUnloaded:#}</td>\n"; str += $"<td class=\"None\">{(fr.nBagsUnloaded > 0 ? DateTime.MinValue.AddSeconds(fr.time_bag_unload * 60).ToString("t") : string.Empty)}</td>\n"; str += $"<td class=\"None\">{fr.nDepartingBags:#}</td>\n"; str += $"<td class=\"{(fr.actual_departureTime <= 0 ? AirportStatUtils.InfoLevels.None : fr.nBagsLoaded < fr.nDepartingBags ? AirportStatUtils.InfoLevels.Info : AirportStatUtils.InfoLevels.None)}\">{fr.nBagsLoaded:#}</td>\n"; str += $"<td class=\"None\">{(fr.nBagsLoaded > 0 ? new TimeSpan(0, 0, (int)fr.time_bag_load * 60).ToString("g") : string.Empty)}</td>\n"; str += $"<td class=\"None\">{fr.nFuelRequested / 1000:#,#}</td>\n"; str += $"<td class=\"{(fr.actual_departureTime <=0 ? AirportStatUtils.InfoLevels.None : fr.nFuelRefueled < fr.nFuelRequested ? AirportStatUtils.InfoLevels.Info : AirportStatUtils.InfoLevels.None)}\">{fr.nFuelRefueled / 1000:#,#}</td>\n"; string st = string.Empty; foreach (Flight.Status stat in Enum.GetValues(typeof(Flight.Status))) { if (AirportStatUtils.HasStatus(fr.status, stat)) { st += i18n.Get("TBFlash.AirportStats.flightstatus." + Enum.GetName(typeof(Flight.Status), stat)) + "<br/>"; } } str += $"<td class=\"None\">{st}</td>\n"; str += $"<td class=\"{(fr.reason.ToString().Length > 5 ? AirportStatUtils.InfoLevels.Warning : AirportStatUtils.InfoLevels.None)}\">{i18n.Get("UI.strings.flightstatusreason.") + fr.reason.ToString()}</td>\n"; str += "</tr>\n"; oddRow = !oddRow; } str += "</tbody>"; return(str); }
private bool IsInvincibleCardEffectPlayedForTeam( IOrderedEnumerable <Tuple <PlayCardEvent, Card> > cardsPlayedOnTeam, EffectCardType effect) { return(cardsPlayedOnTeam .Any(x => x.Item2.EffectType.HasFlag(effect) && x.Item2.CardType == CardType.EFFECT_INVINCIBLE )); }
public IEnumerable <PotentialTarget> FilterTargets(IEnumerable <PotentialTarget> potentialTargets) { if (_targeters == null || !_targeters.Any()) { Debug.Log(name + " has no target pickers! (might just not be initialised yet, attempting reinitialisation...)"); Start(); if (_targeters == null || !_targeters.Any()) { Debug.LogError(name + " still has no target pickers!"); } } foreach (var targeter in _targeters) { potentialTargets = targeter.FilterTargets(potentialTargets); } return(potentialTargets); }
public string MeansOfTransportAsString(IOrderedEnumerable<TransportMethod> meansOfTransport) { if (meansOfTransport == null || !meansOfTransport.Any()) { return string.Empty; } return string.Join("-", meansOfTransport.Select(m => EnumHelper.GetShortName(m))); }
static void Main(string[] args) { // Get input variables Console.Write("Enter Zendesk Support API base (e.g. https://xyz.zendesk.com): "); string userApiBase = Console.ReadLine(); Console.Write("Enter email address of a Zendesk admin or agent: "); string emailAddress = Console.ReadLine(); Console.Write("Enter Zendesk API token: "); string apiToken = Console.ReadLine(); Console.Write("Enter output Excel file name: "); string excelFileName = Console.ReadLine(); Console.Write("Enter output Excel file sheet name: "); string sheetName = Console.ReadLine(); var apiCredentials = Convert.ToBase64String(Encoding.Default.GetBytes($"{emailAddress}/token:{apiToken}")); IOrderedEnumerable <IGrouping <string, ZdUser> > duplicatedUsersGrouped = null; IEnumerable <ZdUser> zdUsers = null; var stopwatch = Stopwatch.StartNew(); try { // Get all users zdUsers = ZdFunctions.Users.GetAllUsers(userApiBase, apiCredentials); // Get duplicate users, grouped by name duplicatedUsersGrouped = zdUsers.GroupBy(x => x.Name) .Where(g => g.Count() > 1) .OrderBy(g => g.Key); // Create output Excel file and write duplicated users if any if (duplicatedUsersGrouped.Any()) { Console.WriteLine("Creating Excel file"); ExcelHelperFunctions.CreateExcelFile(excelFileName, sheetName); Console.WriteLine("Writing duplicate users to Excel file"); ExcelHelperFunctions.OutputDuplicatedUsersToExcel(excelFileName, sheetName, duplicatedUsersGrouped, zdUsers); } } catch (Exception ex) { Console.WriteLine($"Exception occurred, message: {ex.Message}, stackTrace: {ex.StackTrace}"); } stopwatch.Stop(); TimeSpan ts = stopwatch.Elapsed; Console.WriteLine(""); Console.WriteLine($"Total # user records: {zdUsers.Count()}, # duplicated users: {duplicatedUsersGrouped.Count()}"); Console.WriteLine($"Program duration time: {ts.Hours} hours, {ts.Minutes} minutes, {ts.Seconds} seconds, {ts.Milliseconds} milliseconds"); Console.ReadLine(); }
private static bool AbsentEventCreation(TimeBox sender, Term absent, IOrderedEnumerable<Term> orderedTerms) { if (orderedTerms.Any(t => t.CanNotOverlapWithAbsent && t.OverlapNotEnclosed(absent))) return false; var exists = orderedTerms.Where(absent.NeedRelyOn) .Any(t => { if (t.EnclosedWithTypeVerification(absent)) { absent.Bottom = t.GetLowestTerm() as Term; //if (absent.IsNeedSeat != t.IsNeedSeat && t is AssignmentBase) // ((AssignmentBase)t).CancelSeatArrangement(absent); return true; } return false; }); return exists; }
private static bool IndependenceTermCreation(TimeBox sender, Term other, IOrderedEnumerable<Term> orderedTerms) { //bugs might be here var result = !orderedTerms.Any(t => { var found = false; if (t.Level > other.Level) { found = other.OverlapNotEnclosed(t); other.Exception = new TermException(t, "OverlapNotEnclosed"); }//upper term if (t.Level == other.Level && !(t is IOffWork || other is IOffWork) && t.HrDateEq(other)) // 只有非IOffWork不可相交 { found = t.IsCoverd(other); other.Exception = new TermException(t, "IsCoverd"); }// same level term return found; }); return result; }
public HighChart ParseToHighChart(IOrderedEnumerable<ScoreList> source) { var hiChart = new HighChart(); if(source.Any()) { hiChart.Name = source.First().Title; hiChart.Data = source.Select(s => ParseDateAndNumber(s.Date, s.Popular)).ToList(); } return hiChart; }
private static void MostrarResultado(IOrderedEnumerable<Coche> resultado) { //Se puede comprobar si la lista que devuelve la búsqueda de linq //tiene elementos, o no, con el metodo .Any if (!resultado.Any()) { foreach (var coche in resultado) { Console.WriteLine(coche); } } else { Console.WriteLine("\n\nNo se han encontrado resultados.\n\n"); } }
private static OrderLine OrderProduct(int productId, IOrderedEnumerable<int> variants, int itemCount, OrderInfo order) { var currentLocalization = StoreHelper.CurrentLocalization; var productService = IO.Container.Resolve<IProductService>(); var productInfo = productService.CreateProductInfoByProductId(productId, order, currentLocalization, itemCount); if (variants != null && variants.Any()) { var productVariantService = IO.Container.Resolve<IProductVariantService>(); var variantClasses = variants.Select(variant => productVariantService.GetById(variant, currentLocalization)).Where(variant => variant != null).GroupBy(a => a.Group).Select(g => g.FirstOrDefault()).Where(variant => variant != null); productInfo.ProductVariants = variantClasses.Select(variant => new ProductVariantInfo(variant, productInfo, itemCount)).ToList(); } return new OrderLine(productInfo, order); }
private bool IsCardEffectPlayedForTeam( IOrderedEnumerable<Tuple<PlayCardEvent, Card>> cardsPlayedOnTeam, EffectCardType effect) { return cardsPlayedOnTeam .Any(x => x.Item2.EffectType.HasFlag(effect)); }
private bool IsInvincibleCardEffectPlayedForTeam( IOrderedEnumerable<Tuple<PlayCardEvent, Card>> cardsPlayedOnTeam, EffectCardType effect) { return cardsPlayedOnTeam .Any(x => x.Item2.EffectType.HasFlag(effect) && x.Item2.CardType == CardType.EFFECT_INVINCIBLE ); }
private decimal GetCardsForTrade(decimal actualValue, IOrderedEnumerable<MagicCard> purchaseCards, decimal runningValue) { var cardsSelected = new Dictionary<int, MagicCard>(); var remainingCount = TheirCollection.ToList.Count(p => p.CopiesOfCard > 0); while (cardsSelected.Values.Sum(p => p.CopiesOfCard * p.BuyPrice) < actualValue && remainingCount > 0) { var card = GetCard(purchaseCards.ToList(), cardsSelected); _logger.Trace("Selecting Card: " + card); runningValue -= card.BuyPrice; purchaseCards = TheirCollection.ToList.Where(p => p.BuyPrice < runningValue && p.CopiesOfCard > 0).OrderByDescending(p => p.BuyPrice); remainingCount = TheirCollection.ToList.Count(p => p.CopiesOfCard > 0); while (!purchaseCards.Any() && remainingCount > 0 && purchaseCards.Sum(p => p.BuyPrice*p.CopiesOfCard) < runningValue) { runningValue += (decimal) .10; purchaseCards = TheirCollection.ToList.Where(p => p.BuyPrice < runningValue && p.CopiesOfCard > 0).OrderByDescending(p => p.BuyPrice); } } MagicOnlineInterface.WriteWishListFile(cardsSelected); MagicOnlineInterface.LoadWishList(); AutoItX.Sleep(5000); MagicOnlineInterface.DetermineYouGetAmount(); if (MagicOnlineInterface.YouGetAmount != CardsYouGet.CountOfCards()) { PopulateCardsYouGet(); } return CardsYouGiveAmount - Credit - CardsYouGet.BuySum(); }