public void CanAssignToHugeArrayElements() { ulong arraySize = 2L * Int32.MaxValue; HugeArray <int> array = new HugeArray <int>(arraySize); ulong[] indices = new ulong[10000]; int scale = 0, value = 0; ulong v = 0; for (int i = 0; i < indices.Length; i++) { v = indices[0]; while (indices.Contains(v)) { scale = rng.Next(1, 2); value = rng.Next(0, Int32.MaxValue - 1); v = (ulong)scale * (ulong)value; } array[v] = i; indices[i] = v; } for (int i = 0; i < indices.Length; i++) { Assert.Equal(i, array[indices[i]]); } array.Close(); }
public ulong IntelID(ItemCollection Items) { if (Items.Count == 0) { return(1); } else { ulong LastID = 0; ulong[] IDs = new ulong[Items.Count]; for (int i = 0; i < Items.Count; i++) { DataRowView data = (DataRowView)Items[i]; ulong.TryParse(data.Row.ItemArray[0].ToString(), out IDs[i]); } for (int i = 1; i <= IDs.Length; i++) { if (!IDs.Contains((ulong)i)) { return((ulong)(i)); } else { LastID = (ulong)(i + 1); } } return(LastID); } }
/// <summary> /// Load up the roles /// </summary> private void LoadRoles() { SocketGuild guild = client.GetGuild(guildId); // A hardcoded array of valid color rules that the bot will work with ulong[] roleIds = new ulong[] { 500194642458050561, // Light Blue 500172092214607875, // Blue 500194724154703873, // Light Purple 500173202987679765, // Purple 500188030594973696, // Orange 500194776373657601, // Light Orange 500171852568723456, // Red 500201785399705602, // Pink 500270967109582855, // Green 515875271946141711, // Black }; // Grab all of these roles from the guild validRoles = guild.Roles.Where(r => roleIds.Contains(r.Id)); foreach (IRole role in validRoles) { Console.WriteLine($"Loaded role {role.Name}"); } }
public static bool IsPublicChannel(this IChannel channel) { IEnumerable <ulong> publicChannels = new ulong[] { 435094509953744907, // #announcements 453209462438887435, // #welcome 633724305871470593, // #goodbyes 633725420285591571, // #deletions 435152590209286145, // #reviews 470513916393291777, // #feedback 435913619662831616, // #syndication 455012497775132673, // #community 435097044433240065, // #git 368117881000427540, // #general 479405352207777795, // #gaming 437311972917248022, // #act-i 437312012603752458, // #act-ii 439742315016486922, // #dev-screenshots 454937488000024577, // #bugs, 457813004889751553, // #ideas 535160312320753664, // #bots 549182701630914561, // #aaaaaaaaaaaaaaaaaaaa 435131444931723264, // #friends }; return(publicChannels.Contains(channel.Id)); }
static void ExtractMBinFile(FileInfo inputFile, string outputFileName) { using var mbinFile = new MBINFile(inputFile.FullName); using var outputFile = File.Create(outputFileName); using var sw = new StreamWriter(outputFile); if (!(mbinFile.Load() && mbinFile.Header.IsValid)) { throw new InvalidDataException("Invalid File"); } var type = NMSTemplate.GetTemplateType(mbinFile.Header.GetXMLTemplateName()); if (type == null) { throw new NullReferenceException(); } var nms = (NMSAttribute)(type.GetCustomAttributes(typeof(NMSAttribute), false)?[0] ?? null); var broken = nms.Broken; // GUID's for the old files ulong[] UnsupportedGUIDs = new ulong[] { }; var mismatch = (mbinFile.Header.TemplateGUID != nms.GUID); bool unsupported = (UnsupportedGUIDs.Contains(mbinFile.Header.TemplateGUID)); if (broken) { var previousColour = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("File is broken"); Console.ForegroundColor = previousColour; } else if (unsupported) { var previousColour = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.DarkRed; Console.WriteLine("File is Unsupported"); Console.ForegroundColor = previousColour; } else if (mismatch) { var previousColour = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("File is Mismatched"); Console.ForegroundColor = previousColour; } var data = mbinFile.GetData(); sw.Write(EXmlFile.WriteTemplate(data)); sw.Flush(); }
public override void Initialize() { // Orion's shit list var invalidIDs = new ulong[] { 76561198362152774 }; if (SteamManager.Initialized && invalidIDs.Contains(SteamUser.GetSteamID().m_SteamID)) { var mod = ModLister.GetActiveModWithIdentifier("Orion.Hospitality"); if (mod != null) { mod.Active = false; Application.Quit(); } } Hospitality_SpecialInjector.Inject(); }
public async Task <IEnumerable <IGameRole> > GenerateCivilianRoles(int count) { var everyone = GaiaMembers.Concat(GuardianMembers).Concat(OCMembers).Concat(Civilians); var all_ids = new ulong[] { Occult_Club.Id, Guardian.Id, Gaia.Id }; if (count < 4) { var random_players = (await ServerHost.GetUsersAsync()) .Where((x) => !x.IsBot && !everyone.Contains(x) && !x.RoleIds.Any((y) => all_ids.Contains(y)) ); var random_numbers = new int[4 - count]; var total_non_playing = random_players.Count(); var resultMsg = String.Empty; for (int i = 0; i < 4 - count; i++) { do { random_numbers[i] = Randomizer.Next(total_non_playing); } while (random_numbers.Take(i).Contains(random_numbers[i])); var memToAdd = random_players.ElementAt(random_numbers[i]); Civilians.Add(memToAdd); await memToAdd.AddRoleAsync(GvG_Player); resultMsg += $"Because there are too few players, {memToAdd.Mention} is forced to join the game as a Civilian" + ((i == count - 1) ? "" : Environment.NewLine); } Public_GvG.SendMessageAsync(resultMsg); } IEnumerable <IGameRole> result = new IGameRole[] { new Kagari(), new NormalCivilian(), new NormalCivilian(), new NormalCivilian() }; if (count > 4) { for (int i = 0; i < count - 4; i++) { result = result.Append(new NormalCivilian()); } } return(result.OrderBy((x) => Randomizer.Next())); }
/// <summary> /// Generates the attendance poll, periodically /// </summary> /// <param name="ctx"></param> /// <param name="pollFrequency"></param> /// <param name="presentStudents"></param> /// <returns></returns> static async Task CreatePoll(CommandContext ctx, TimeSpan pollFrequency, List <ulong> presentStudents) { var attendanceEmoji = DiscordEmoji.FromName(ctx.Client, ":raised_hand:"); var pollEmbed = new DiscordEmbedBuilder { Title = "Attendance Poll", Description = $"React with '{attendanceEmoji}' to confirm your attendance.", ThumbnailUrl = ctx.Client.CurrentUser.AvatarUrl, Color = DiscordColor.Green }; var interactivity = ctx.Client.GetInteractivity(); if (pollFrequency == default) { pollFrequency = TimeSpan.FromMinutes(20); //Sets default poll frequency if it was omitted at command call } // Generates poll var pollMessage = await ctx.Channel.SendMessageAsync(embed : pollEmbed).ConfigureAwait(false); await pollMessage.CreateReactionAsync(DiscordEmoji.FromName(ctx.Client, ":raised_hand:")).ConfigureAwait(false); // Defines the emojis to be used in the poll // Extracts the info of Discord users who reacted to the poll var pollResults = await interactivity.CollectReactionsAsync(pollMessage, pollFrequency).ConfigureAwait(false); // Collect poll reactions var results = pollResults.Select(x => $"{x.Users.ToArray()[0]}"); string[] attendanceInfo = string.Join("\n", results).Split("\n"); // Makes a list of the info of the students who answered the poll // Deletes poll + Sends attendance confirmation message await ctx.Channel.SendMessageAsync($"Attendance successfully taken on {DateTime.Now.ToString("dddd, dd MMMM yyyy HH:mm")}."); await pollMessage.DeleteAsync(); // Extracts the Discord ID of users who reacted to the poll ulong[] usersWhoReacted = new ulong[attendanceInfo.Length]; for (int i = 0; i < attendanceInfo.Length; i++) { ulong userID = Convert.ToUInt64(attendanceInfo[i].Substring(7, 18)); usersWhoReacted[i] = userID; // Stores ID of people who reacted } // Extracts the usernames of people in the VC (if the teacher is in VC) // Filters out students who reacted to the poll but were not actually in class (i.e. in teacher's VC) var teacherVC = ctx.Member?.VoiceState?.Channel; //VC channel if (teacherVC != null) { var resultsVC = teacherVC.Users.ToArray()[0]; string[] userInfo = string.Join("\n", resultsVC).Split("\n"); ulong[] usersInVC = new ulong[attendanceInfo.Length]; for (int i = 0; i < userInfo.Length; i++) { ulong userID = Convert.ToUInt64(userInfo[i].Substring(7, 18)); usersInVC[i] = userID; // Stores ID of people in the VC } // Filters out reactions made by people not in VC foreach (ulong userID in usersWhoReacted) { if (usersInVC.Contains(userID)) { presentStudents.Add(userID); } } } // Uses no filtering if the teacher is not in a VC else { foreach (ulong userID in usersWhoReacted) { presentStudents.Add(userID); } } }
void OnPlayerDeath(PlayerSession player, EntityEffectSourceData source) { var tmpName = GetNameOfObject(source.EntitySource); if (tmpName.Length < 3) { return; } var murdererName = tmpName.Remove(tmpName.Length - 3); var isPlayer = (getSession(murdererName) != null) ? true : false; if (source.EntitySource.name == null || !isPlayer) { return; } var murderer = getSession(murdererName); var deceased = player; var deceasedId = player.SteamId; var myInClause = new ulong[] { (ulong)murderer.SteamId, (ulong)deceasedId }; DuelData thisDuel = (from x in Duels where myInClause.Contains(x.Accepter) && myInClause.Contains(x.Requester) && x.Winner == 0 select x).FirstOrDefault(); if (thisDuel == null || thisDuel.Accepted != 1 || thisDuel.Winner != 0) { return; } if (isPlayer) { thisDuel.Winner = (ulong)murderer.SteamId; thisDuel.WinnerName = murdererName; PrintWarning(murdererName + " got " + thisDuel.Wager); AddCash(murderer, thisDuel.Wager); //announce the winner. hurt.BroadcastChat(GetMsg("broadcast_DuelWinner", player).Replace("{playerName}", murdererName)); PrintToChat(murderer, GetMsg("msg_DuelWon", player) .Replace("{moneySymbol}", MoneySym) .Replace("{money}", (thisDuel.Wager / 2).ToString())); //Make loser infamouse. //announce that the loser is now infamouse, due to duel laws. //Duels.Remove(thisDuel); Vector3 transportBack = default(Vector3); if (thisDuel.Accepter == (ulong)murderer.SteamId) { transportBack = parseVector3(thisDuel.AccepterPos); } else if (thisDuel.Requester == (ulong)murderer.SteamId) { transportBack = parseVector3(thisDuel.RequesterPos); } float lootTime = float.Parse(GetConf("lootTime", "30").ToString()); PrintToChat(murderer, GetMsg("msg_TransportBackIn", player).Replace("{time}", lootTime.ToString())); timer.Once(lootTime, () => { murderer.WorldPlayerEntity.transform.position = transportBack; }); } SaveData(); }
public static bool Contains(this ulong l, Cell cell) { return(l.Contains(cell.ToULong())); }
async Task FinishGiveawayAsync(RiftActiveGiveaway expiredGiveaway) { var dbGiveaway = await DB.Giveaways.GetAsync(expiredGiveaway.GiveawayName); var giveawayData = $"ID {expiredGiveaway.Id.ToString()} \"{expiredGiveaway.GiveawayName}\""; if (dbGiveaway is null) { RiftBot.Log.Error($"Could not finish giveaway {giveawayData}: {nameof(RiftGiveaway)} is null!"); return; } if (!IonicHelper.GetTextChannel(Settings.App.MainGuildId, Settings.ChannelId.Chat, out var channel)) { RiftBot.Log.Error($"Could not finish giveaway {giveawayData}: Giveaway channel is null!"); return; } var message = (IUserMessage)await channel.GetMessageAsync(expiredGiveaway.ChannelMessageId); if (message is null) { RiftBot.Log.Error($"Could not finish giveaway {giveawayData}: Giveaway message is null! Deleted?"); return; } if (!IonicHelper.GetEmote(403616665603932162, "giveaway", out var emote)) { RiftBot.Log.Error($"Could not finish giveaway {giveawayData}: Emote is null! Deleted?"); return; } // Reaction amount is limited by discord itself. // See https://discordapp.com/developers/docs/resources/channel#get-reactions var reactions = await message.GetReactionUsersAsync(emote, 100).FlattenAsync(); if (reactions is null) { RiftBot.Log.Error($"Could not finish giveaway {giveawayData}: Unable to get reactions."); return; } var dbReward = await DB.Rewards.GetAsync(dbGiveaway.RewardId); if (dbReward is null) { RiftBot.Log.Error($"Could not finish giveaway {giveawayData}: " + $"Unable to get reward ID {dbGiveaway.RewardId.ToString()}."); return; } var reward = dbReward.ToRewardBase(); var participants = reactions .Where(x => !x.IsBot && x.Id != IonicHelper.Client.CurrentUser.Id) .Select(x => x.Id) .ToArray(); if (participants.Length == 0) { await LogGiveawayAsync(dbGiveaway.Name, null, null, "No reward provided", expiredGiveaway.StartedBy, expiredGiveaway.StartedAt, dbGiveaway.Duration); await DB.ActiveGiveaways.RemoveAsync(expiredGiveaway.Id); RiftBot.Log.Error($"Could not finish giveaway {giveawayData}: No participants."); return; } var winners = new ulong[dbGiveaway.WinnersAmount]; if (participants.Length < dbGiveaway.WinnersAmount) { RiftBot.Log.Error($"Could not finish giveaway {giveawayData}: " + $"Not enough participants: only {participants.Length.ToString()} of minimum {dbGiveaway.WinnersAmount.ToString()}"); return; } if (participants.Length == dbGiveaway.WinnersAmount) { Array.Copy(participants, winners, dbGiveaway.WinnersAmount); } else { ulong winnerId; for (var i = 0; i < dbGiveaway.WinnersAmount; i++) { do { winnerId = participants.Random(); } while (winners.Contains(winnerId)); winners[i] = winnerId; } } foreach (var winner in winners) { await rewardService.DeliverToAsync(winner, reward); } await DB.ActiveGiveaways.RemoveAsync(expiredGiveaway.Id); foreach (var participant in participants) { GiveawaysParticipated?.Invoke(null, new GiveawaysParticipatedEventArgs(participant)); } var log = new RiftGiveawayLog { Name = dbGiveaway.Name, Winners = winners, Participants = participants, Reward = "No reward provided", StartedBy = expiredGiveaway.StartedBy, StartedAt = expiredGiveaway.StartedAt, Duration = dbGiveaway.Duration, FinishedAt = DateTime.UtcNow, }; await messageService.SendMessageAsync("giveaway-finished", Settings.ChannelId.Chat, new FormatData(expiredGiveaway.StartedBy) { Giveaway = new GiveawayData { Log = log, Stored = dbGiveaway, }, Reward = reward }); await LogGiveawayAsync(log).ConfigureAwait(false); }
public void TestRegionsByCreatingNewUser() { // Id-шники регионов var browseRegions = new ulong[] { 1, 8, 16, 256 }; var orderRegions = new ulong[] { 1, 8, 256 }; client.MaskRegion = 0; foreach (var region in browseRegions) { client.MaskRegion |= region; } session.SaveOrUpdate(client); foreach (var region in browseRegions) { settings.WorkRegionMask |= region; } foreach (var region in orderRegions) { settings.OrderRegionMask |= region; } session.SaveOrUpdate(settings); FlushAndCommit(); ClickLink("Новый пользователь"); Thread.Sleep(2000); AssertText("Новый пользователь"); // Указанные регионы для обзора и для заказа должны быть выделены foreach (var region in browseRegions) { Assert.IsTrue(browser.CheckBox(Find.ById("browseRegion" + region)).Checked); } foreach (var region in orderRegions) { Assert.IsTrue(browser.CheckBox(Find.ById("orderRegion" + region)).Checked); } // Если регион помечен только для обзора, то галка "Для заказа" должна быть снята var diff = browseRegions.Where(region => !orderRegions.Contains(region)); foreach (var region in diff) { Assert.IsFalse(browser.CheckBox(Find.ById("orderRegion" + region)).Checked); } // Снимаем галку "В обзоре" (должна также сняться галка "Доступен для заказа") // и регистрируем нового пользователя browser.CheckBox(Find.ById("browseRegion" + browseRegions[0])).Checked = false; browser.TextField(Find.ByName("user.Name")).TypeText("User for test regions"); ClickButton("Создать"); AssertText("Регистрационная карта "); var login = Helper.GetLoginFromRegistrationCard(browser); browser.GoTo(BuildTestUrl(String.Format("client/{0}", client.Id))); Refresh(); ClickLink(login.ToString()); Click("Настройка"); // Проверяем, чтобы были доступны нужные регионы. Берем с первого региона, т.к. галку с нулевого сняли for (var i = 1; i < browseRegions.Length; i++) { Assert.IsTrue(browser.CheckBox(Find.ById(String.Format("WorkRegions[{0}]", i))).Checked); } for (var i = 1; i < orderRegions.Length; i++) { Assert.IsTrue(browser.CheckBox(Find.ById(String.Format("OrderRegions[{0}]", i))).Checked); } }
public void Go() { Console.WriteLine("{0}: ", max); var primes = MyMath.ConvertSieveToPrimes(MyMath.CreatePrimesSieve(max)); // Because there are no combinations for them: var forbiddenPrimes = new[] { 11, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79 }; var numbers = Enumerable .Range(2, max - 1) .Where(i => forbiddenPrimes.All(p => i % p != 0)) // for max = 80, there is only one combination for 13: 13, 39, 52 => remove all other 13x .Where(i => i % 13 != 0 || i == 13 || i == 39 || i == 52) // there are no 25, and 49 in the 5,7 combinations .Where(i => i != 25 && i != 49) // there is no 27 in the 3 combinations .Where(i => i != 27) .Select(i => (ulong)i) .ToArray(); var map = numbers.Select((n, i) => new { n, i }).ToDictionary(a => a.n, a => 1ul << a.i); Console.WriteLine(numbers.Length); ShowPrimeCombinations(primes, numbers); // Console.WriteLine(CompareToTarget(Sum(numbers.Where(n => n >= 3)))); // -1 => 1/2 must be in the sum var powersOf2 = new ulong[] { 2, 4, 8, 16, 32, 64 }; var primesCombinations = powersOf2 .Where(n => n <= max) .ToArray() .Subsets(1) .Where(comb => comb.Contains(2)) .Select(comb => new Candidate { Bits = ConvertToBitArray(map, comb), Summa = Sum(comb) }) .ToList(); var threes = numbers.Where(n => n % 3 == 0).ToArray(); // for max = 80, threes.Length = 26 var threesMask = ConvertToBitArray(map, threes); { var timer = Stopwatch.StartNew(); var squares = threes.Select(t => new BigInteger(t * t / 9)).ToArray(); var result = new List <int[]>(); for (var i = 0; i < squares.Length; i++) { FindAllowedThrees(result, new Stack <int>(), 0, 1, i, squares); } var copy = primesCombinations.ToList(); foreach (var combIndices in result) { var combBits = ConvertToBitArray(map, combIndices.Select(i => threes[i])); foreach (var prevComb in primesCombinations) { var newCombBits = combBits | prevComb.Bits; copy.Add(new Candidate { Bits = newCombBits, Summa = Sum(numbers, newCombBits) }); } } primesCombinations = copy; Console.WriteLine("Threes total: {0}; calc: {1}", result.Count, timer.ElapsedMilliseconds); } { var allBits = ConvertToBitArray(map, numbers); var allBut23mask = ConvertToBitArray(map, numbers.Where(n => n % 3 != 0 && !powersOf2.Contains(n))); var copy = new List <Candidate>(); foreach (var comb in primesCombinations) { var sum = Sum(numbers, comb.Bits); if (CompareToTarget(sum) > 0) { continue; } var remainingBits = (allBits - comb.Bits) & allBut23mask; if (CompareToTarget(Sum(numbers, remainingBits) + sum) >= 0) { copy.Add(comb); } } primesCombinations = copy; } var solutions = new HashSet <string>(); // Принимаем на веру, что нет решений только из 2 и 3 foreach (var prime in primes) { if (prime >= 5) { var divisiblesByPrime = numbers.Where(n => n % prime == 0).ToArray(); var combinations = divisiblesByPrime.Subsets(2) .Where(s => Sum(s).Denumerator % prime != 0) .ToArray(); // Console.WriteLine(new { prime, combs = combinations.Length }); if (combinations.Length == 0) { continue; } var copy = primesCombinations.ToList(); foreach (var comb in combinations) { var combBits = ConvertToBitArray(map, comb); var addedThrees = threesMask & combBits; foreach (var prevComb in primesCombinations) { if (!BitArrayContains(prevComb.Bits, addedThrees)) { continue; } if (!BitArrayContains(prevComb.Bits, combBits)) { var newCombBits = combBits | prevComb.Bits; var addition = newCombBits ^ prevComb.Bits; var sum = prevComb.Summa + Sum(numbers, addition); var compare = CompareToTarget(sum); if (compare > 0) { continue; } if (prime < 13) { copy.Add(new Candidate { Bits = newCombBits, Summa = sum }); } if (compare == 0) { var sol = BitArrayToString(numbers, newCombBits); solutions.Add(sol); Console.WriteLine(sol); } } } } primesCombinations = copy; } } Console.WriteLine("All combinations: " + primesCombinations.Count); Console.WriteLine("Total distinct solutions: " + solutions.Count); }
/// <summary>Convert MBIN to EXML</summary> /// <param name="fIn">Source file</param> /// <param name="msOut">Output stream</param> /// <param name="fileOut">Output file path. Passed through as the return value. Not actually used.</param> /// <returns>fileOut</returns> private static string ConvertMBIN(string inputPath, FileStream fIn, MemoryStream msOut, string fileOut) { var mbin = new MBINFile(fIn); if (!(mbin.Load() && mbin.Header.IsValid)) { throw new InvalidDataException("Not a valid MBIN file!"); } var type = NMSTemplate.GetTemplateType(mbin.Header.GetXMLTemplateName()); var nms = (NMSAttribute)(type.GetCustomAttributes(typeof(NMSAttribute), false)?[0] ?? null); var broken = nms.Broken; // GUID's for the old files ulong[] UnsupportedGUIDs = new ulong[] { }; var mismatch = (mbin.Header.TemplateGUID != nms.GUID); bool unsupported = (UnsupportedGUIDs.Contains(mbin.Header.TemplateGUID)); //if ( broken && mismatch ) { // FileIsUnsupported( fIn.Name, mbin ); //} else if (broken) { FileIsBroken(inputPath, mbin); } else if (unsupported) { FileIsUnused(inputPath, mbin); } else if (mismatch) { FileIsUnrecognized(inputPath, mbin, nms.GUID); } var sw = new StreamWriter(msOut); NMSTemplate data = null; string msg = ""; try { msg = $"Failed to read {mbin.Header.GetXMLTemplateName()} from MBIN."; data = mbin.GetData(); if (data is null) { throw new InvalidDataException("Invalid MBIN data."); } msg = $"Failed serializing {mbin.Header.GetXMLTemplateName()} to EXML."; string exml = EXmlFile.WriteTemplate(data, HideVersionInfo); if (StreamToConsole) { EmitInfo($""); EmitInfo($"[INPUT]: {inputPath}"); EmitInfo($"{exml}"); } else { sw.Write(exml); sw.Flush(); if (msOut.Length == 0) { throw new InvalidDataException("Invalid EXML data."); } } } catch (Exception e) { throw new MbinException(msg, e, fIn.Name, mbin); } return(fileOut); }