System.Collections.Generic.List.Add(ulong)

Here are the examples of the csharp api System.Collections.Generic.List.Add(ulong) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

209 Examples 7

19 View Source File : StringDedupeContext.cs
License : MIT License
Project Creator : 0x0ade

public void Cleanup() {
            foreach (KeyValuePair<int, int> entry in Counting) {
                int score = entry.Value - DemotionScore;
                if (score <= 0) {
                    CountingUpdates.Add(ToCountingUpdate(entry.Key, 0));
                } else if (score >= PromotionTreshold) {
                    CountingUpdates.Add(ToCountingUpdate(entry.Key, 0));
                    Map[entry.Key] = new();
                } else {
                    CountingUpdates.Add(ToCountingUpdate(entry.Key, score));
                }
            }
            foreach (ulong update in CountingUpdates) {
                FromCountingUpdate(update, out int key, out int value);
                if (value == 0)
                    Counting.Remove(key);
                else
                    Counting[key] = value;
            }
            CountingUpdates.Clear();
        }

19 View Source File : LayerSelectorInfo.cs
License : MIT License
Project Creator : 0xC0000054

private static List<ulong> GetLayerSizes(AV1LayeredImageIndexingBox layeredImageIndexingBox, ulong totalItemSize)
        {
            List<ulong> layerSizes = new List<ulong>(4);

            ulong remainingBytes = totalItemSize;

            foreach (uint size in layeredImageIndexingBox.LayerSize)
            {
                if (size > 0)
                {
                    if (size >= remainingBytes)
                    {
                        ExceptionUtil.ThrowFormatException($"The a1lx layer index does not fit in the remaining bytes.");
                    }

                    layerSizes.Add(size);
                    remainingBytes -= size;
                }
                else
                {
                    layerSizes.Add(remainingBytes);
                    remainingBytes = 0;
                    break;
                }
            }

            if (remainingBytes > 0)
            {
                layerSizes.Add(remainingBytes);
            }

            return layerSizes;
        }

19 View Source File : Formatter.Array1.List.cs
License : MIT License
Project Creator : 1996v

public List<UInt64> Deserialize(ref BssomReader reader, ref BssomDeserializeContext context)
        {
            if (reader.TryReadNullWithEnsureArray1BuildInType(BssomType.UInt64Code))
            {
                return default;
            }

            context.Option.Security.DepthStep(ref context);
            reader.SkipVariableNumber();
            int len = reader.ReadVariableNumber();
            List<ulong> val = new List<UInt64>(len);
            for (int i = 0; i < len; i++)
            {
                val.Add(reader.ReadUInt64WithOutTypeHead());
            }
            context.Depth--;
            return val;
        }

19 View Source File : DiscordManager.cs
License : Apache License 2.0
Project Creator : AantCoder

internal string SrvInfoCommand(SocketCommandContext context, string param)
        {
            var sb = new StringBuilder();
            var author = context.Message.Author.Id;

            switch (param)
            {
                // "srvinfo all: информация по всем серверам, отсортированные 1.По количеству пользователей от максимального к минимальному, по дате поcледнего онлайна"
                case "all":
                    {
                        //foreach (var sessionClient in _app.DiscrordToOCServer.Values)
                        //{
                        //    //sessionClient.
                        //}

                        return "";
                    }
                //все где я зарегестрирован\n"
                case "my":
                    {
                        var servers = new List<ulong>();
                        foreach (var kv in _app.UserOnServers)
                        {
                            if (kv.Value.Values.Any(x => x.UserId == author))
                            {
                                servers.Add(kv.Key);
                            }
                        }

                        return getServersInfo(servers, ServerInfoType.Full);
                    }
            }

            var sessionClient = _app.TryGetSessionClientByIP(param);
            if (sessionClient == null)
            {
                return Translator.ErrInvalidIP;
            }

            return sessionClient.GetDescription(ServerInfoType.FullWithDescription);
        }

19 View Source File : SocialPlatformManager.cs
License : MIT License
Project Creator : absurd-joy

public static void ForgetRemoteUsersNotInRoom()
    {
        List<ulong> toPurge = new List<ulong>();

        foreach (KeyValuePair<ulong, RemotePlayer> kvp in s_instance.remoteUsers)
        {
            if (kvp.Value.stillInRoom == false)
            {
                toPurge.Add(kvp.Key);
            }
        }

        foreach (ulong key in toPurge)
        {
            RemoveRemoteUser(key);
        }
    }

19 View Source File : XpTable.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public override void Unpack(BinaryReader reader)
        {
            Id = reader.ReadUInt32();

            // The counts for each "Table" are at the top of the file.
            int attributeCount          = reader.ReadInt32();
            int vitalCount              = reader.ReadInt32();
            int trainedSkillCount       = reader.ReadInt32();
            int specializedSkillCount   = reader.ReadInt32();

            uint levelCount             = reader.ReadUInt32();

            for (int i = 0; i <= attributeCount; i++)
                AttributeXpList.Add(reader.ReadUInt32());

            for (int i = 0; i <= vitalCount; i++)
                VitalXpList.Add(reader.ReadUInt32());

            for (int i = 0; i <= trainedSkillCount; i++)
                TrainedSkillXpList.Add(reader.ReadUInt32());

            for (int i = 0; i <= specializedSkillCount; i++)
                SpecializedSkillXpList.Add(reader.ReadUInt32());

            for (int i = 0; i <= levelCount; i++)
                CharacterLevelXPList.Add(reader.ReadUInt64());

            for (int i = 0; i <= levelCount; i++)
                CharacterLevelSkillCreditList.Add(reader.ReadUInt32());
        }

19 View Source File : ArchetypePool.cs
License : MIT License
Project Creator : Alan-FGR

public int Add(ulong UID, Flags* flags)
    {
        indicesToUIDs_.Add(UID);

        Count++;
        return Count - 1;
    }

19 View Source File : ArchetypePool.cs
License : MIT License
Project Creator : Alan-FGR

public int Add<T0>(ulong UID, Flags* flags, T0 t0) // genvariadic function
        where T0 : unmanaged // genvariadic duplicate
    {
        var p0 = componentBuffers_[flags[0]]; // genvariadic duplicate

        var one = 1;
        p0.replacedureRoomForMore(Count, one); // genvariadic duplicate
        p0.Set(ref t0, Count); // genvariadic duplicate

        indicesToUIDs_.Add(UID);

        Count++;
        return Count - 1;
    }

19 View Source File : ArchetypePool.cs
License : MIT License
Project Creator : Alan-FGR

public (int newIndex, ulong replacerUID) ChangePoolAndCompleteArchetype<T>(int index, ArchetypePool newPool, Flags newCompFlag, ref T newComp)
        where T : unmanaged
    {
        newPool.replacedureRoomForMore(1);

        var count = newPool.Count;
        CopyComponentsTo(index, newPool, count);

        var newCompBuffer = newPool.componentBuffers_[newCompFlag];
        newCompBuffer.Set(ref newComp, count);
        
        newPool.indicesToUIDs_.Add(indicesToUIDs_[index]);
        newPool.Count = count+1;

        var replacerUID = Remove(index);
        return (count, replacerUID);
    }

19 View Source File : Program.cs
License : MIT License
Project Creator : Alan-FGR

static void Benchmark(int enreplacedyCount, bool randomComponents)
    {
        Console.WriteLine($"Benchmarking {enreplacedyCount} enreplacedies, ARCHETYPES, random insertion order: {randomComponents}");

        Registry registry = new Registry();

        registry.RegisterComponent<Int1>();
        registry.RegisterComponent<Int2>();
        registry.RegisterComponent<Int3>();
        registry.RegisterComponent<Int4>();
        registry.RegisterComponent<Int5>();
        registry.RegisterComponent<Int6>();

        List<ulong> ids = new List<ulong>();
        for (int i = 0; i < enreplacedyCount; i++) ids.Add(registry.CreateEnreplacedy());

        List<int> indices1 = new List<int>();
        List<int> indices2 = new List<int>();
        List<int> indices3 = new List<int>();
        List<int> indices4 = new List<int>();
        List<int> indices5 = new List<int>();
        List<int> indices6 = new List<int>();

        for (int i = 0; i < enreplacedyCount; i += (xorshift(1) + 1)) indices1.Add(i);
        for (int i = 0; i < enreplacedyCount; i += (xorshift(2) + 1)) indices2.Add(i);
        for (int i = 0; i < enreplacedyCount; i += (xorshift(3) + 1)) indices3.Add(i);
        for (int i = 0; i < enreplacedyCount; i += (xorshift(4) + 1)) indices4.Add(i);
        for (int i = 0; i < enreplacedyCount; i += (xorshift(5) + 1)) indices5.Add(i);
        for (int i = 0; i < enreplacedyCount; i += (xorshift(6) + 1)) indices6.Add(i);

        if (randomComponents)
        {
            xorshuffle(indices1);
            xorshuffle(indices2);
            xorshuffle(indices3);
            xorshuffle(indices4);
            xorshuffle(indices5);
            xorshuffle(indices6);
        }


        //lr($"added enreplacedies", registry);

        foreach (int i in indices1)
        {
            registry.AddComponent(ids[i], new Int1(xorshift()));
            //lr($"added comp Int1 to {ids[i]}", registry);
        }

        foreach (int i in indices2)
        {
            registry.AddComponent(ids[i], new Int2(i, xorshift()));
            //lr($"added comp Int2 to {ids[i]}", registry);
        }

        foreach (int i in indices3)
        {
            registry.AddComponent(ids[i], new Int3(i, i, xorshift()));
            //lr($"added comp Int3 to {ids[i]}", registry);
        }

        foreach (int i in indices4)
        {
            registry.AddComponent(ids[i], new Int4(i, i, i, xorshift()));
            //lr($"added comp Int4 to {ids[i]}", registry);
        }

        foreach (int i in indices5)
        {
            registry.AddComponent(ids[i], new Int5(i, i, i, i, xorshift()));
            //lr($"added comp Int5 to {ids[i]}", registry);
        }

        foreach (int i in indices6) registry.AddComponent(ids[i], new Int6(i, i, i, i, i, xorshift()));

        Measure();
        registry.Loop((EnreplacedyData index, ref Int1 int1, ref Int2 int2) => { int2.x = int1.x; });
        Measure("Propagated x to Int2");
        registry.Loop((EnreplacedyData index, ref Int2 int2, ref Int3 int3) => { int3.x = int2.x; });
        Measure("Propagated x to Int3");
        registry.Loop((EnreplacedyData index, ref Int3 int3, ref Int4 int4) => { int4.x = int3.x; });
        Measure("Propagated x to Int4");
        registry.Loop((EnreplacedyData index, ref Int4 int4, ref Int5 int5) => { int5.x = int4.x; });
        Measure("Propagated x to Int5");
        registry.Loop((EnreplacedyData index, ref Int5 int5, ref Int6 int6) => { int6.x = int5.x; });
        Measure("Propagated x to Int6");

        registry.Loop((EnreplacedyData index, ref Int2 int2, ref Int3 int3, ref Int4 int4) => { int3.y = int2.y; int4.y = int3.y; });
        Measure("Propagated y to Int3 and Int4");
        registry.Loop((EnreplacedyData index, ref Int3 int3, ref Int4 int4, ref Int5 int5) => { int4.y = int3.y; int5.y = int4.y; });
        Measure("Propagated y to Int4 and Int5");
        registry.Loop((EnreplacedyData index, ref Int4 int4, ref Int5 int5, ref Int6 int6) => { int5.y = int4.y; int6.y = int5.y; });
        Measure("Propagated y to Int5 and Int6");

        ulong checkSum = 0;
        registry.Loop((EnreplacedyData index, ref Int6 int6) =>
        {
            checkSum ^= (ulong)(int6.x + int6.y);
        });

        Console.WriteLine($"checksum: {checkSum}");
    }

19 View Source File : actionChecker.cs
License : MIT License
Project Creator : AlbertMN

[STAThread]
        public void ProcessFile(string file, bool tryingAgain = false) {
            //Custom 'file read delay'
            float fileReadDelay = Properties.Settings.Default.FileReadDelay;
            if (fileReadDelay > 0) {
                MainProgram.DoDebug("User has set file delay to " + fileReadDelay.ToString() + "s, waiting before processing...");
                Thread.Sleep((int)fileReadDelay * 1000);
            }

            if (!File.Exists(file)) {
                MainProgram.DoDebug("File doesn't exist (anymore).");
                return;
            }

            //Make sure the file isn't in use before trying to access it
            int tries = 0;
            while (FileInUse(file) || tries >= 20) {
                tries++;
            }
            if (tries >= 20 && FileInUse(file)) {
                MainProgram.DoDebug("File in use in use and can't be read. Try again.");
                return;
            }

            //Check unique file ID (dublicate check)
            ulong theFileUid = 0;
            bool gotFileUid = false;
            tries = 0;
            while (!gotFileUid || tries >= 30) {
                try {
                    theFileUid = getFileUID(file);
                    gotFileUid = true;
                } catch {
                    Thread.Sleep(50);
                }
            }
            if (tries >= 30 && !gotFileUid) {
                MainProgram.DoDebug("File in use in use and can't be read. Try again.");
                return;
            }


            //Validate UID
            if (lastFileUid == 0) {
                lastFileUid = Properties.Settings.Default.LastActionFileUid;
            }
            if (lastFileUid == theFileUid && !tryingAgain) {
                //Often times this function is called three times per file - check if it has already been (or is being) processed
                return;
            }
            if (executedFiles.Contains(theFileUid) && !tryingAgain) {
                MainProgram.DoDebug("Tried to execute an already-executed file (UID " + theFileUid.ToString() + ")");
                return;
            }
            lastFileUid = theFileUid;
            executedFiles.Add(theFileUid);
            Properties.Settings.Default.LastActionFileUid = lastFileUid;
            Properties.Settings.Default.Save();

            MainProgram.DoDebug("Processing file...");
            string originalFileName = file, fullContent = "";

            if (!File.Exists(file)) {
                MainProgram.DoDebug("File no longer exists when trying to read file.");
                return;
            }

            //READ FILE
            if (new FileInfo(file).Length != 0) {
                try {
                    string fileContent;
                    fileContent = File.ReadAllText(file);
                    fullContent = Regex.Replace(fileContent, @"\t|\r", "");
                } catch (Exception e) {
                    if (unsuccessfulReads < 20) {
                        MainProgram.DoDebug("Failed to read file - trying again in 200ms... (trying max 20 times)");
                        unsuccessfulReads++;
                        Thread.Sleep(200);
                        ProcessFile(file, true);

                        return;
                    } else {
                        MainProgram.DoDebug("Could not read file on final try; " + e);
                        unsuccessfulReads = 0;
                        return;
                    }
                }
                MainProgram.DoDebug(" - Read complete, content: " + fullContent);
            } else {
                MainProgram.DoDebug(" - File is empty");
                ErrorMessageBox("No action was set in the action file.");
            }
            //END READ

            //DateTime lastModified = File.GetCreationTime(file);
            DateTime lastModified = File.GetLastWriteTime(file);
 
            if (lastModified.AddSeconds(Properties.Settings.Default.FileEditedMargin) < DateTime.Now) {
                //if (File.GetLastWriteTime(file).AddSeconds(Properties.Settings.Default.FileEditedMargin) < DateTime.Now) {
                //Extra security - sometimes the "creation" time is a bit behind, but the "modify" timestamp is usually right.

                MainProgram.DoDebug("File creation time: " + lastModified.ToString());
                MainProgram.DoDebug("Local time: " + DateTime.Now.ToString());

                if (GettingStarted.isConfiguringActions) {
                    //Possibly configure an offset - if this always happens

                    Console.WriteLine("File is actually too old, but configuring the software to maybe set an offset");

                    isConfiguringOffset = true;
                    if (lastModifiedOffsets == null) {
                        lastModifiedOffsets = new List<double>();
                    }

                    lastModifiedOffsets.Add((DateTime.Now - lastModified).TotalSeconds);
                    if (lastModifiedOffsets.Count >= 3) {
                        int average = (int)(lastModifiedOffsets.Average());
                        Console.WriteLine("File Margin fixed offset set to; " + average.ToString());
                        Properties.Settings.Default.AutoFileMarginFixer = average;
                        Properties.Settings.Default.Save();
                    }
                } else {
                    bool isGood = false;

                    if (Properties.Settings.Default.AutoFileMarginFixer != 0) {
                        //if (lastModified.AddSeconds(-Properties.Settings.Default.AutoFileMarginFixer) < DateTime.Now) {

                        var d1 = lastModified.AddSeconds(-Properties.Settings.Default.FileEditedMargin);
                        var d2 = DateTime.Now.AddSeconds(-Properties.Settings.Default.AutoFileMarginFixer);

                        if (d1 < d2) {
                            isGood = true;
                            MainProgram.DoDebug("File timestamp is actually more than " + Properties.Settings.Default.FileEditedMargin.ToString() + "s old, but the software is configured to have an auto-file-margin fix for " + Properties.Settings.Default.AutoFileMarginFixer.ToString() + "s");
                        } else {
                            //MainProgram.DoDebug(d1.ToString());
                            //MainProgram.DoDebug(d2.ToString());
                            MainProgram.DoDebug("The " + Properties.Settings.Default.AutoFileMarginFixer.ToString() + "s didn't fix it");
                        }
                    }

                    if (!isGood) {
                        MainProgram.DoDebug("The file is more than " + Properties.Settings.Default.FileEditedMargin.ToString() + "s old, meaning it won't be executed.");
                        new CleanupService().Start();
                        return;
                    }
                }
                //}
            }
            
            MainProgram.DoDebug("\n[ -- DOING ACTION(S) -- ]");
            MainProgram.DoDebug(" - " + file + " UID; " + theFileUid);
            MainProgram.DoDebug(" - File exists, checking the content...");

            //Process the file
            using (StringReader reader = new StringReader(fullContent)) {
                string theLine = string.Empty;
                do {
                    theLine = reader.ReadLine();
                    if (theLine != null) {
                        MainProgram.DoDebug("\n[EXECUTING ACTION]");
                        CheckAction(theLine, file);
                    }

                } while (theLine != null);
            }

            MainProgram.DoDebug("[ -- DONE -- ]");
        }

19 View Source File : VectorLayerVisualizer.cs
License : MIT License
Project Creator : alen-smajic

private void AddFeatureToTileObjectPool(VectorFeatureUnity feature, UnityTile tile)
		{
			_activeIds.Add(feature.Data.Id);
			if (!_idPool.ContainsKey(tile))
			{
				_idPool.Add(tile, new List<ulong>() { feature.Data.Id });
			}
			else
			{
				_idPool[tile].Add(feature.Data.Id);
			}
		}

19 View Source File : OsmRelation.cs
License : MIT License
Project Creator : alen-smajic

void RelationMembers(XmlNode node)
    {
        XmlNodeList members = node.SelectNodes("member");
        foreach (XmlNode n in members)
        {
            string type = GetAttribute<string>("type", n.Attributes);
            if (type == "node")
            {
                string role = GetAttribute<string>("role", n.Attributes);
                if (role == "stop")
                {
                    ulong refNo = GetAttribute<ulong>("ref", n.Attributes);
                    StoppingNodeIDs.Add(refNo);
                }
            }
            else if (type == "way")
            {
                string role = GetAttribute<string>("role", n.Attributes);
                if (role != "platform")
                {
                    ulong refNo = GetAttribute<ulong>("ref", n.Attributes);
                    WayIDs.Add(refNo);
                }
            }
        }
    }

19 View Source File : OsmWay.cs
License : MIT License
Project Creator : alen-smajic

void NodeIDsCreator(XmlNode node)
    {
        XmlNodeList nds = node.SelectNodes("nd");
        foreach (XmlNode n in nds)
        {
            ulong refNo = GetAttribute<ulong>("ref", n.Attributes);
            NodeIDs.Add(refNo);
        }
    }

19 View Source File : MemAnalyzerBase.cs
License : GNU Lesser General Public License v3.0
Project Creator : Alois-xx

protected static IEnumerable<ulong> GetObjectAddresses(ClrHeap heap, bool bLiveOnly)
        {
            if (bLiveOnly)
            {
                ObjectSet liveObjects = GetLiveObjects(heap);
                List<ulong> live = new List<ulong>();
                foreach (ClrSegment seg in heap.Segments)
                {
                    for (ulong obj = seg.FirstObject; obj != 0; obj = seg.NextObject(obj))
                    {
                        if (liveObjects.Contains(obj))
                        {
                            live.Add(obj);
                        }
                    }
                }
                return live;
            }
            else
            {
                return heap.EnumerateObjectAddresses();
            }
        }

19 View Source File : DiscordBotController.cs
License : MIT License
Project Creator : anoyetta

private Task Bot_MessageReceived(
            SocketMessage arg)
        {
            lock (this.LogIDHistory)
            {
                if (this.LogIDHistory.Contains(arg.Id))
                {
                    return Task.CompletedTask;
                }

                this.LogIDHistory.Add(arg.Id);
            }

            var activeChannels = this.GetActiveChannels();
            if (activeChannels == null)
            {
                return Task.CompletedTask;
            }

            var ch = activeChannels
                .FirstOrDefault(x =>
                    x.DiscordChannelID == arg.Channel.Id.ToString());
            if (ch == null)
            {
                return Task.CompletedTask;
            }

            var model = ChatLogModel.FromDiscordLog(arg);
            model.ChatCode = ch.ChatCode;
            model.IsMe = string.Equals(
                model.OriginalSpeaker,
                SharlayanController.Instance.CurrentPlayer?.Name,
                StringComparison.OrdinalIgnoreCase);

            if (!model.IsMe ||
                model.DiscordLog.Attachments.Any())
            {
                WPFHelper.Dispatcher.Invoke(() =>
                {
                    ChatLogsModel.AddToBuffers(model);
                });

                var chName = !string.IsNullOrEmpty(ch.ChannelShortName) ?
                    ch.ChannelShortName :
                    ch.ChannelName;

                ChatLogger.Write(
                    chName,
                    model.Speaker,
                    model.SpeakerAlias,
                    model.Message);
            }

            return Task.CompletedTask;
        }

19 View Source File : RaidProtectionModule.cs
License : GNU Affero General Public License v3.0
Project Creator : asmejkal

private async Task CleanupContext(RaidProtectionSettings settings)
        {
            try
            {
                // Guild contexts
                await _context.Mutex.WaitAsync();

                DateTime now = DateTime.UtcNow;
                if (_context.LastCleanup > now - CleanupTimer)
                    return;

                _context.LastCleanup = now;

                var toRemove = new List<ulong>();
                foreach (var guildContext in _context.GuildContexts)
                {
                    try
                    {
                        // User contexts
                        await guildContext.Value.Mutex.WaitAsync();
                        foreach (var userContext in guildContext.Value.UserContexts.ToList())
                        {
                            try
                            {
                                await userContext.Value.Mutex.WaitAsync();
                                foreach (var offenses in userContext.Value.Offenses.ToList())
                                {
                                    offenses.Value.SlideWindow(settings.GetRule<ReadOnlyRaidProtectionRule>(offenses.Key).OffenseWindow, now - MaxMessageProcessingDelay);
                                    if (offenses.Value.Count <= 0)
                                        userContext.Value.Offenses.Remove(offenses.Key);
                                }

                                userContext.Value.TextPosts.SlideWindow(settings.TextSpamRule.Window, now - MaxMessageProcessingDelay);
                                userContext.Value.ImagePosts.SlideWindow(settings.ImageSpamRule.Window, now - MaxMessageProcessingDelay);

                                if (userContext.Value.Empty)
                                    guildContext.Value.UserContexts.Remove(userContext.Key);
                            }
                            finally
                            {
                                userContext.Value.Mutex.Release();
                            }
                        }

                        if (guildContext.Value.UserContexts.Count <= 0)
                            toRemove.Add(guildContext.Key);
                    }
                    finally
                    {
                        guildContext.Value.Mutex.Release();
                    }
                }

                foreach (var removable in toRemove)
                    _context.GuildContexts.Remove(removable);

                if (_context.LastReport < now - ReportTimer)
                {
                    _context.LastReport = now;
                    _logger.LogInformation("Raid protection status: {RaidProtectionGuildContextCount} guild contexts, {RaidProtectionUserContextCount} user contexts", 
                        _context.GuildContexts.Count, 
                        _context.GuildContexts.Aggregate(0, (x, y) => x + y.Value.UserContexts.Count));
                }
            }
            finally
            {
                _context.Mutex.Release();
            }
        }

19 View Source File : RolesModule.cs
License : GNU Affero General Public License v3.0
Project Creator : asmejkal

private Task HandleMessageReceived(SocketMessage message)
        {
            TaskHelper.FireForget(async () =>
            {
                try
                {
                    var channel = message.Channel as SocketTextChannel;
                    if (channel == null)
                        return;

                    var user = message.Author as IGuildUser;
                    if (user == null)
                        return;

                    if (user.IsBot)
                        return;

                    var settings = await _settings.Read<RolesSettings>(channel.Guild.Id, false);
                    if (settings == null || settings.RoleChannel != channel.Id)
                        return;

                    var logger = _logger.WithScope(message);
                    if (!channel.Guild.CurrentUser.GetPermissions(channel).SendMessages)
                    {
                        logger.LogInformation("Can't replacedign role because of missing SendMessage permissions");
                        return;
                    }

                    using (await _rolereplacedignmentUserMutex.ClaimAsync(user.Id)) // To prevent race-conditions when spamming roles
                    {
                        try
                        {
                            logger.LogInformation("Received role channel message {MessageContent}");

                            string msgContent = message.Content.Trim();
                            bool remove = false;
                            if (msgContent.StartsWith("-"))
                            {
                                msgContent = msgContent.Substring(1);
                                remove = true;
                            }

                            msgContent = msgContent.TrimStart('-', '+');
                            msgContent = msgContent.Trim();

                            // First try to match an alias case sensitive
                            var roleAar = settings.replacedignableRoles.FirstOrDefault(x => x.Names.Any(y => string.Compare(y, msgContent) == 0) && channel.Guild.GetRole(x.RoleId) != null);

                            // Then try current role names case sensitive
                            if (roleAar == null)
                            {
                                roleAar = settings.replacedignableRoles
                                    .Select(x => (Aar: x, Role: channel.Guild.GetRole(x.RoleId)))
                                    .FirstOrDefault(x => x.Role != null && string.Compare(x.Role.Name, msgContent) == 0)
                                    .Aar;
                            }

                            // Then alias case insensitive
                            if (roleAar == null)
                                roleAar = settings.replacedignableRoles.FirstOrDefault(x => x.Names.Any(y => string.Compare(y, msgContent, true, GlobalDefinitions.Culture) == 0) && channel.Guild.GetRole(x.RoleId) != null);

                            // And current role names case insensitive
                            if (roleAar == null)
                            {
                                roleAar = settings.replacedignableRoles
                                    .Select(x => (Aar: x, Role: channel.Guild.GetRole(x.RoleId)))
                                    .FirstOrDefault(x => x.Role != null && string.Compare(x.Role.Name, msgContent, true, GlobalDefinitions.Culture) == 0)
                                    .Aar;
                            }

                            if (roleAar == null)
                            {
                                var response = await _communicator.CommandReplyError(message.Channel, "This is not a self-replacedignable role.");
                                if (settings.ClearRoleChannel)
                                    response.First().DeleteAfter(3);

                                return;
                            }

                            // Check group settings
                            if (!remove && roleAar.Groups.Any())
                            {
                                var existingreplacedignableRoles = settings.replacedignableRoles
                                    .Where(x => user.RoleIds.Contains(x.RoleId) || user.RoleIds.Contains(x.SecondaryId))
                                    .ToList();

                                foreach (var existingreplacedignableRole in existingreplacedignableRoles)
                                {
                                    foreach (var commonGroup in existingreplacedignableRole.Groups.Intersect(roleAar.Groups))
                                    {
                                        if (!settings.GroupSettings.TryGetValue(commonGroup, out var groupSetting))
                                            continue;

                                        if (groupSetting.Limit > 0)
                                        {
                                            var groupRoleCount = existingreplacedignableRoles.Count(x => x.Groups.Contains(commonGroup));
                                            if (groupRoleCount >= groupSetting.Limit)
                                            {
                                                var response = await _communicator.CommandReplyError(message.Channel, $"You can't add any more roles from group `{commonGroup}`.");
                                                if (settings.ClearRoleChannel)
                                                    response.First().DeleteAfter(3);

                                                return;
                                            }
                                        }
                                    }
                                }
                            }

                            var addRoles = new List<ulong>();
                            var removeRoles = new List<ulong>();
                            if (roleAar.SecondaryId != 0)
                            {
                                // Bias role (more complex logic)
                                if (remove)
                                {
                                    // Remove also secondary
                                    removeRoles.Add(roleAar.RoleId);
                                    removeRoles.Add(roleAar.SecondaryId);
                                }
                                else
                                {
                                    var primaryRoles = settings.replacedignableRoles.Where(x => x.SecondaryId != 0);

                                    // If the user doesn't have the primary already
                                    if (!user.RoleIds.Any(x => x == roleAar.RoleId))
                                    {
                                        // Check if user has any primary role
                                        if (user.RoleIds.Any(x => primaryRoles.Any(y => y.RoleId == x)))
                                        {
                                            // replacedign secondary
                                            addRoles.Add(roleAar.SecondaryId);
                                        }
                                        else
                                        {
                                            // replacedign primary and delete secondary
                                            addRoles.Add(roleAar.RoleId);
                                            removeRoles.Add(roleAar.SecondaryId);
                                        }
                                    }
                                    else
                                    {
                                        removeRoles.Add(roleAar.SecondaryId); // Try to remove secondary just in case (cleanup)
                                    }
                                }
                            }
                            else
                            {
                                // Regular role
                                if (remove)
                                    removeRoles.Add(roleAar.RoleId);
                                else
                                    addRoles.Add(roleAar.RoleId);
                            }

                            try
                            {
                                if (addRoles.Count > 0)
                                    await user.AddRolesAsync(addRoles.Select(x => channel.Guild.GetRole(x)).Where(x => x != null));

                                if (removeRoles.Count > 0)
                                    await user.RemoveRolesAsync(removeRoles.Select(x => channel.Guild.GetRole(x)).Where(x => x != null));

                                var guildRole = channel.Guild.GetRole(roleAar.RoleId);
                                if (guildRole != null)
                                {
                                    var response = await _communicator.SendMessage(message.Channel, string.Format(remove ? "You no longer have the **{0}** role." : "You now have the **{0}** role.", guildRole.Name));
                                    if (settings.ClearRoleChannel)
                                        response.First().DeleteAfter(3);
                                }
                            }
                            catch (Discord.Net.HttpException ex) when (ex.HttpCode == HttpStatusCode.Unauthorized || ex.HttpCode == HttpStatusCode.Forbidden)
                            {
                                await _communicator.CommandReplyError(message.Channel, "The bot doesn't have the necessary permissions. If you're the admin, please make sure the bot can Manage Roles and all the replacedignable roles are placed below the bot's highest role.");
                            }
                        }
                        catch (Exception ex)
                        {
                            logger.LogError(ex, "Failed to replacedign roles");
                            await _communicator.CommandReplyGenericFailure(message.Channel);
                        }
                        finally
                        {
                            if (settings.ClearRoleChannel)
                                message.DeleteAfter(3);
                        }
                    }
                }
                catch (Exception ex)
                {
                    _logger.WithScope(message).LogError(ex, "Failed to process potential role replacedignment message");
                }
            });

            return Task.CompletedTask;
        }

19 View Source File : GdidGenerationTests.cs
License : MIT License
Project Creator : azist

private void _parallelGenerationSame()
            {
              const int Preplaced_CNT = 5000;

              int TOTAL = 0;

              var gen = new GdidGenerator(NOPApplication.Instance);
              gen.AuthorityHosts.Register(new GdidGenerator.AuthorityHost(NOPApplication.Instance, "sync://127.0.0.1:9999"));

              var lst = new List<ulong>();
              var rnd = new Random();

              var sw = Stopwatch.StartNew();
              Parallel.For(0, Preplaced_CNT,
                        (_)=>
                        {
                          var BATCH = 32 + rnd.Next(255); //introduces randomness in threads
                          ulong[] arr = new ulong[BATCH];

                          for(int i=0; i<BATCH; i++)
                          {
                           arr[i] = gen.GenerateOneGdid("a", "aseq", 1024).ID;
                          }

                          lock(lst)
                            foreach(var id in arr)
                              lst.Add(id);

                          System.Threading.Interlocked.Add(ref TOTAL, BATCH);
                        });

              var elapsed = sw.ElapsedMilliseconds;


              Aver.AreEqual(lst.Count, lst.Distinct().Count());//all values are distinct

              Console.WriteLine("Processed {0} in {1} ms. at {2}/sec.".Args(TOTAL, elapsed, TOTAL / (elapsed / 1000d)));

            }

19 View Source File : GdidGenerationTests.cs
License : MIT License
Project Creator : azist

private void _parallelGenerationDifferent()
            {
              const int Preplaced_CNT = 5000;

              int TOTAL = 0;

              var gen = new GdidGenerator(NOPApplication.Instance);
              gen.AuthorityHosts.Register(new GdidGenerator.AuthorityHost(NOPApplication.Instance, "sync://127.0.0.1:9999"));

              var dict = new Dictionary<string, List<ulong>>();
              dict.Add("aseq", new List<ulong>());
              dict.Add("bseq", new List<ulong>());
              dict.Add("cseq", new List<ulong>());
              dict.Add("dseq", new List<ulong>());
              dict.Add("eseq", new List<ulong>());
              dict.Add("fseq", new List<ulong>());
              dict.Add("gseq", new List<ulong>());


              var rnd = new Random();

              var sw = Stopwatch.StartNew();
              Parallel.For(0, Preplaced_CNT,
                        (n)=>
                        {
                          var seq = dict.Keys.ToList()[n % dict.Keys.Count];

                          var BATCH = 32 + rnd.Next(255); //introduces randomness in threads
                          ulong[] arr = new ulong[BATCH];

                          for(int i=0; i<BATCH; i++)
                          {
                           arr[i] = gen.GenerateOneGdid("a", seq, 1024).ID;
                          }

                          lock(dict[seq])
                            foreach(var id in arr)
                              dict[seq].Add(id);

                          System.Threading.Interlocked.Add(ref TOTAL, BATCH);
                        });

              var elapsed = sw.ElapsedMilliseconds;

              foreach(var kvp in dict)
              {
                Aver.AreEqual(kvp.Value.Count, kvp.Value.Distinct().Count());//all values are distinct
                Console.WriteLine("{0} = {1} ids".Args(kvp.Key, kvp.Value.Count));
              }

              Console.WriteLine("Processed {0} in {1} ms. at {2}/sec.".Args(TOTAL, elapsed, TOTAL / (elapsed / 1000d)));

            }

19 View Source File : Bitmap.cs
License : MIT License
Project Creator : Azure

public uint Allocate() {
            for (var blockIdx = 0; blockIdx < Bits.Count; blockIdx++) {
                if (Bits[blockIdx] == ulong.MaxValue) {
                    continue; // Full - continue
                }
                // Grab from block
                var block = Bits[blockIdx];
                for (var bit = 0; bit < 64; bit++) {
                    if (0 == (block & (1ul << bit))) {
                        Bits[blockIdx] |= 1ul << bit;
                        return (uint)(((uint)blockIdx * 64) + bit);
                    }
                }
            }
            // Add new block
            Bits.Add(1);
            return (uint)(Bits.Count - 1) * 64;
        }

19 View Source File : MainForm.cs
License : MIT License
Project Creator : baaron4

private string DiscordBatch(out List<ulong> ids)
        {
            ids = new List<ulong>();
            AddTraceMessage("Sending batch to Discord");
            if (Properties.Settings.Default.WebhookURL == null)
            {
                return "Set a discord webhook url in settings first";
            }
            var fullDpsReportLogs = new List<FormOperationController>();
            foreach (FormOperationController operation in OperatorBindingSource)
            {
                if (operation.DPSReportLink != null && operation.DPSReportLink.Contains("https"))
                {
                    fullDpsReportLogs.Add(operation);
                }
            }
            if (!fullDpsReportLogs.Any())
            {
                return "Nothing to send";
            }
            // first sort by time
            fullDpsReportLogs.Sort((x, y) =>
            {
                return DateTime.Parse(x.BasicMetaData.LogStart).CompareTo(DateTime.Parse(y.BasicMetaData.LogStart));
            });
            var fullDpsReportsLogsByDate = fullDpsReportLogs.GroupBy(x => DateTime.Parse(x.BasicMetaData.LogStart).Date).ToDictionary(x => x.Key, x => x.ToList());
            // split the logs so that a single embed does not reach the discord embed limit and also keep a reasonable size by embed
            string message = "";
            bool start = true;
            foreach (KeyValuePair<DateTime, List<FormOperationController>> pair in fullDpsReportsLogsByDate)
            {
                if (!start)
                {
                    message += "\r\n";
                }
                start = false;
                var splitDpsReportLogs = new List<List<FormOperationController>>() { new List<FormOperationController>() };
                message += pair.Key.ToString("yyyy-MM-dd") + " - ";
                List<FormOperationController> curListToFill = splitDpsReportLogs.First();
                foreach (FormOperationController controller in pair.Value)
                {
                    if (curListToFill.Count < 40)
                    {
                        curListToFill.Add(controller);
                    }
                    else
                    {
                        curListToFill = new List<FormOperationController>()
                    {
                        controller
                    };
                        splitDpsReportLogs.Add(curListToFill);
                    }
                }
                foreach (List<FormOperationController> dpsReportLogs in splitDpsReportLogs)
                {
                    EmbedBuilder embedBuilder = ProgramHelper.GetEmbedBuilder();
                    embedBuilder.WithCurrentTimestamp();
                    embedBuilder.WithFooter(pair.Key.ToString("yyyy-MM-dd"));
                    dpsReportLogs.Sort((x, y) =>
                    {
                        var categoryCompare = x.BasicMetaData.FightCategory.CompareTo(y.BasicMetaData.FightCategory);
                        if (categoryCompare == 0)
                        {
                            return DateTime.Parse(x.BasicMetaData.LogStart).CompareTo(DateTime.Parse(y.BasicMetaData.LogStart));
                        }
                        return categoryCompare;
                    });
                    string currentSubCategory = "";
                    var embedFieldBuilder = new EmbedFieldBuilder();
                    var fieldValue = "I can not be empty";
                    foreach (FormOperationController controller in dpsReportLogs)
                    {
                        string subCategory = controller.BasicMetaData.FightCategory.GetSubCategoryName();
                        string toAdd = "[" + controller.BasicMetaData.FightName + "](" + controller.DPSReportLink + ") " + (controller.BasicMetaData.FightSuccess ? " :white_check_mark: " : " :x: ") + ": " + controller.BasicMetaData.FightDuration;
                        if (subCategory != currentSubCategory)
                        {
                            embedFieldBuilder.WithValue(fieldValue);
                            embedFieldBuilder = new EmbedFieldBuilder();
                            fieldValue = "";
                            embedBuilder.AddField(embedFieldBuilder);
                            embedFieldBuilder.WithName(subCategory);
                            currentSubCategory = subCategory;
                        }
                        else if (fieldValue.Length + toAdd.Length > 1024)
                        {
                            embedFieldBuilder.WithValue(fieldValue);
                            embedFieldBuilder = new EmbedFieldBuilder();
                            fieldValue = "";
                            embedBuilder.AddField(embedFieldBuilder);
                        }
                        else
                        {
                            fieldValue += "\r\n";
                        }
                        fieldValue += toAdd;
                    }
                    embedFieldBuilder.WithValue(fieldValue);
                    ids.Add(WebhookController.SendMessage(Properties.Settings.Default.WebhookURL, embedBuilder.Build(), out string curMessage));
                    message += curMessage + " - ";
                }
            }
            return message;
        }

19 View Source File : ObjectPlacement.cs
License : MIT License
Project Creator : Big-Endian-32

public override void Load(Stream stream)
        {
            BINAReader reader = new(stream);

            reader.JumpAhead(0x0C); // Always zero - maybe padding.
            Data.Name = new string(reader.ReadChars(0x20)).Replace("\0", ""); // Usually 'test', but not always.

            // Read data table information.
            uint objectCount       = reader.ReadUInt32();
            uint objectTableOffset = reader.ReadUInt32();
            uint groupCount        = reader.ReadUInt32();
            uint groupTableOffset  = reader.ReadUInt32();

            // Jump to objects.
            reader.JumpTo(objectTableOffset, true);

            // Read objects.
            for (int o = 0; o < objectCount; o++)
            {
                // Initialise new object.
                SetObject setObject = new()
                {
                    Index = o, // Set object ID to the current index.
                    DisplayIndex = DisplayIndex
                };

                uint objectNameOffset = reader.ReadUInt32(); // Offset to this object's name.
                uint objectTypeOffset = reader.ReadUInt32(); // Offset to this object's type.

                reader.JumpAhead(0x03); // Skip the 40 00 00 bytes at the start of the object, as these seem to NEVER change.
                setObject.StartInactive = reader.ReadBoolean();
                reader.JumpAhead(0x0C); // Skip the remaining bytes which I believe to all be padding, as they're always 00?

                setObject.Position     = reader.ReadVector3();
                setObject.DrawDistance = reader.ReadSingle();
                setObject.Rotation     = reader.ReadQuaternion();
                
                uint parameterCount  = reader.ReadUInt32(); // Amount of parameters this object has.
                uint parameterOffset = reader.ReadUInt32(); // Offset to the data for this object's parameters.

                long position = reader.BaseStream.Position; // Save our current position in the stream so we can jump back after reading the name, type and parameters.

                // Read this object's name and type.
                if (objectNameOffset != 0)
                    setObject.Name = reader.ReadNullTerminatedString(false, objectNameOffset, true);

                if (objectTypeOffset != 0)
                    setObject.Type = reader.ReadNullTerminatedString(false, objectTypeOffset, true);

                // Parameters.
                if (parameterCount != 0)
                {
                    reader.JumpTo(parameterOffset, true);
                    for (int p = 0; p < parameterCount; p++)
                    {
                        // Read object data type.
                        ObjectDataType type = (ObjectDataType)reader.ReadUInt32();

                        // Initialise new parameter with the read type.
                        SetParameter setParameter = new()
                        {
                            Type = type
                        };

                        switch (type)
                        {
                            case ObjectDataType.Boolean:
                                setParameter.Data = reader.ReadBoolean(4);
                                reader.JumpAhead(0x0C);
                                break;

                            case ObjectDataType.Int32:
                                setParameter.Data = reader.ReadInt32();
                                reader.JumpAhead(0x0C);
                                break;

                            case ObjectDataType.Single:
                                setParameter.Data = reader.ReadSingle();
                                reader.JumpAhead(0x0C);
                                break;

                            case ObjectDataType.String:
                            {
                                uint stringOffset = reader.ReadUInt32();

                                // Store current position.
                                long stringParameterPosition = reader.BaseStream.Position;

                                // Read null-terminated string.
                                reader.JumpTo(stringOffset, true);
                                {
                                    setParameter.Data = reader.ReadNullTerminatedString();
                                }

                                // Jump back to previous position.
                                reader.JumpTo(stringParameterPosition);

                                // Always 1, 0 then the amount of characters minus one in the string?
                                reader.JumpAhead(0x0C);

                                break;
                            }

                            case ObjectDataType.Vector3:
                                setParameter.Data = reader.ReadVector3();
                                reader.JumpAhead(0x04);
                                break;

                            case ObjectDataType.UInt32:
                                setParameter.Data = reader.ReadUInt32();
                                reader.JumpAhead(0x0C);
                                break;

                            default:
                                throw new InvalidSetParameterType((uint)type, reader.BaseStream.Position - 4);
                        }

                        setObject.Parameters.Add(setParameter);
                    }
                }

                // Add this object to the list of objects then jump back to the previously saved position.
                Data.Objects.Add(setObject);
                reader.JumpTo(position);
            }

            // Groups.
            reader.JumpTo(groupTableOffset, true);
            for (int g = 0; g < groupCount; g++)
            {
                // Initialise new SetGroup.
                SetGroup setGroup = new();

                // Store offsets for this group and the amount of objects within it.
                uint groupNameOffset       = reader.ReadUInt32();
                uint groupFunctionOffset   = reader.ReadUInt32();
                uint groupObjectCount      = reader.ReadUInt32();
                uint groupObjectListOffset = reader.ReadUInt32();

                long position = reader.BaseStream.Position; // Save our current position in the stream so we can jump back after reading the name, type and list.

                // Read this group's name and type.
                if (groupNameOffset != 0)
                    setGroup.Name = reader.ReadNullTerminatedString(false, groupNameOffset, true);

                if (groupFunctionOffset != 0)
                    setGroup.Function = reader.ReadNullTerminatedString(false, groupFunctionOffset, true);

                // Read this group's object list
                reader.JumpTo(groupObjectListOffset, true);
                for (int o = 0; o < groupObjectCount; o++)
                    setGroup.Objects.Add(reader.ReadUInt64());

                // Add this group to the list of groups then jump back to the previously saved position.
                Data.Groups.Add(setGroup);
                reader.JumpTo(position);
            }
        }

19 View Source File : MongoDbProducerService.cs
License : GNU Affero General Public License v3.0
Project Creator : blockbasenetwork

public async Task<IEnumerable<ulong>> GetMissingBlockNumbers(string databaseName, ulong endSequenceNumber)
        {
            databaseName = ClearSpecialCharacters(databaseName);
            using (IClientSession session = await MongoClient.StartSessionAsync())
            {
                ulong lowerEndToGet = 1;
                ulong upperEndToGet;
                var sidechainDatabase = MongoClient.GetDatabase(_dbPrefix + databaseName);
                var blockHeaderCollection = sidechainDatabase.GetCollection<BlockheaderDB>(MongoDbConstants.BLOCKHEADERS_COLLECTION_NAME);
                var missingSequenceNumbers = new List<ulong>();

                //TODO rpinto - why is this done in a while true loop
                while (true)
                {
                    upperEndToGet = lowerEndToGet + 99 > endSequenceNumber ? endSequenceNumber : lowerEndToGet + 99;

                    var blockHeadersResponse = await blockHeaderCollection.FindAsync(b => b.SequenceNumber >= lowerEndToGet && b.SequenceNumber <= upperEndToGet);
                    var blockHeaders = await blockHeadersResponse.ToListAsync();
                    var sequenceNumbers = blockHeaders.Select(b => b.SequenceNumber).OrderBy(s => s);
                    for (ulong i = lowerEndToGet; i <= upperEndToGet; i++)
                    {
                        if (!sequenceNumbers.Contains(i)) missingSequenceNumbers.Add(i);
                    }

                    if (upperEndToGet == endSequenceNumber) break;

                    lowerEndToGet = upperEndToGet + 1;
                }

                return missingSequenceNumbers.OrderByDescending(s => s);
            }
        }

19 View Source File : MessageForwarder.cs
License : GNU Affero General Public License v3.0
Project Creator : blockbasenetwork

private TransactionConfirmationReceivedEventArgs ParseTransactionConfirmationMessage(NetworkMessage message)
        {
            var sequenceNumbers = new List<ulong>();
            for (int i = 0; i < message.Payload.Length; i += 8)
            {
                byte[] sequenceNumberBytes = new byte[8];
                Array.Copy(message.Payload, i, sequenceNumberBytes, 0, 8);
                sequenceNumbers.Add(BitConverter.ToUInt64(sequenceNumberBytes));
            }
            return new TransactionConfirmationReceivedEventArgs { SenderAccountName = message.EosAccount, TransactionSequenceNumbers = sequenceNumbers };
        }

19 View Source File : MessageForwarder.cs
License : GNU Affero General Public License v3.0
Project Creator : blockbasenetwork

private BlocksRequestReceivedEventArgs ParseRequestBlocksMessage(byte[] payload, IPEndPoint sender)
        {
            var numberBlocksBytes = new byte[4];
            Array.Copy(payload, 0, numberBlocksBytes, 0, 4);
            var numberOfBlocks = BitConverter.ToInt32(numberBlocksBytes);
            _logger.LogDebug("Payload size " + payload.Length + " bytes.");
            _logger.LogDebug("Number of blocks to send: " + numberOfBlocks);
            var sequenceNumbers = new List<ulong>();

            int i;

            for (i = 4; i < numberOfBlocks * 8 + 4; i += 8)
            {
                // _logger.LogDebug("Index: " + i);
                var sequenceNumberBytes = new byte[8];
                Array.Copy(payload, i, sequenceNumberBytes, 0, 8);
                var sequenceNumber = BitConverter.ToUInt64(sequenceNumberBytes);
                sequenceNumbers.Add(sequenceNumber);
            }


            int sidechainBytesLength = payload.Length - i;
            byte[] stringBytes = new byte[sidechainBytesLength];
            Array.Copy(payload, i, stringBytes, 0, sidechainBytesLength);

            return new BlocksRequestReceivedEventArgs { ClientAccountName = Encoding.UTF8.GetString(stringBytes), BlocksSequenceNumber = sequenceNumbers, Sender = sender };
        }

private async void MessageForwarder_TransactionsReceived(MessageForwarder.TransactionsReceivedEventArgs args, IPEndPoint sender)
        {
            try
            {
                _logger.LogDebug($"Receiving transaction for sidechain: {args.ClientAccountName}");
                var transactionsProto = SerializationHelper.DeserializeTransactions(args.TransactionsBytes, _logger);

                if (!_sidechainKeeper.TryGet(args.ClientAccountName, out var sidechainContext))
                {
                    _logger.LogDebug($"Transaction received but sidechain {args.ClientAccountName} is unknown.");
                    return;
                }

                if (transactionsProto == null) return;

                var receivedValidTransactions = new List<ulong>();
                var containsUnsavedTransactions = false;
                _logger.LogInformation($"Received transaction #{transactionsProto.FirstOrDefault()?.SequenceNumber} to #{transactionsProto.LastOrDefault()?.SequenceNumber} for sidechain {args.ClientAccountName}");

                foreach (var transactionProto in transactionsProto)
                {
                    if (receivedValidTransactions.Contains(transactionProto.SequenceNumber))
                        continue;

                    var transaction = new Transaction().SetValuesFromProto(transactionProto);
                    if (await ValidateTransaction(transaction, args.ClientAccountName, sidechainContext))
                    {
                        var isTransactionAlreadySaved = await CheckIfAlreadySavedTransactionAndSave(args.ClientAccountName, transaction);
                        if (!isTransactionAlreadySaved && !containsUnsavedTransactions) containsUnsavedTransactions = true;
                        receivedValidTransactions.Add(transaction.SequenceNumber);
                    }
                }

                if (!receivedValidTransactions.Any()) return;

                var lastTransaction = new Transaction().SetValuesFromProto(transactionsProto.Last());
                var alreadyReceivedTrxAfterLast = await GetConfirmedTransactionsSequeceNumber(lastTransaction, args.ClientAccountName);
                if (alreadyReceivedTrxAfterLast.Count > 0)
                    receivedValidTransactions.AddRange(alreadyReceivedTrxAfterLast);

                var data = new List<byte>();
                foreach (var transactionSequenceNumber in receivedValidTransactions)
                    data.AddRange(BitConverter.GetBytes(transactionSequenceNumber));

                var requesterPeer = _peerConnectionsHandler.CurrentPeerConnections.GetEnumerable().Where(p => p.ConnectionAccountName == args.ClientAccountName).FirstOrDefault();
                if (requesterPeer?.IPEndPoint?.Address.ToString() == sender.Address.ToString() && requesterPeer?.IPEndPoint?.Port == sender.Port)
                {
                    var message = new NetworkMessage(
                        NetworkMessageTypeEnum.ConfirmTransactionReception,
                        data.ToArray(),
                        TransportTypeEnum.Tcp, _nodeConfigurations.ActivePrivateKey,
                        _nodeConfigurations.ActivePublicKey,
                        _networkConfigurations.GetResolvedIp() + ":" + _networkConfigurations.TcpPort,
                        _nodeConfigurations.AccountName, sender);
                    _logger.LogDebug("Sending confirmation transaction.");
                    await _networkService.SendMessageAsync(message);
                }

                //TODO: Temporarily remove logic, to replace with asking for transactions
                // if (containsUnsavedTransactions)
                // {
                //     await SendTransactionsToConnectedProviders(transactionsProto, args.ClientAccountName, sender, sidechainContext);
                // }
            }
            catch (Exception e)
            {
                _logger.LogError("Error handling received transactions");
                _logger.LogDebug($"Exception: {e}");
            }
        }

private async Task<IList<ulong>> GetConfirmedTransactionsSequeceNumber(Transaction transaction, string clientAccountName)
        {

            var confirmedSequenceNumbers = new List<ulong>();

            if (_sidechainKeeper.TryGet(clientAccountName, out var sidechainContext))
            {
                try
                {
                    var databaseName = clientAccountName;
                    if (await _mongoDbProducerService.IsTransactionInDB(databaseName, transaction))
                    {
                        //_logger.LogDebug($"Already have transaction with same transaction hash or same sequence number.");
                        var afterTransactions = await _mongoDbProducerService.GetTransactionsSinceSequenceNumber(_nodeConfigurations.AccountName, transaction.SequenceNumber);
                        confirmedSequenceNumbers.Add(transaction.SequenceNumber);
                        confirmedSequenceNumbers.AddRange(afterTransactions.Select(t => t.SequenceNumber));
                        return confirmedSequenceNumbers;
                    }

                    confirmedSequenceNumbers.Add(transaction.SequenceNumber);
                }
                catch (Exception e)
                {
                    _logger.LogError($"Transaction validator crashed with exception {e.Message}");
                }
            }
            return confirmedSequenceNumbers;
        }

19 View Source File : RsaKeyUtils.cs
License : MIT License
Project Creator : bunq

private static AsnType CreateOid(string value)
        {
            if (IsEmpty(value))
                return null;

            var tokens = value.Split(' ', '.');

            if (IsEmpty(tokens))
                return null;

            ulong a = 0;

            var arcs = new List<ulong>();

            foreach (var t in tokens)
            {
                if (t.Length == 0)
                {
                    break;
                }

                try
                {
                    a = Convert.ToUInt64(t, CultureInfo.InvariantCulture);
                }
                catch (FormatException /*e*/)
                {
                    break;
                }
                catch (OverflowException /*e*/)
                {
                    break;
                }

                arcs.Add(a);
            }

            if (0 == arcs.Count)
                return null;

            var octets = new List<byte>();

            if (arcs.Count >= 1)
            {
                a = arcs[0] * 40;
            }

            if (arcs.Count >= 2)
            {
                a += arcs[1];
            }

            octets.Add((byte) (a));

            for (var i = 2; i < arcs.Count; i++)
            {
                var temp = new List<byte>();
                var arc = arcs[i];

                do
                {
                    temp.Add((byte) (0x80 | (arc & 0x7F)));
                    arc >>= 7;
                } while (0 != arc);

                var t = temp.ToArray();

                t[0] = (byte) (0x7F & t[0]);
                Array.Reverse(t);
                octets.AddRange(t);
            }

            return CreateOid(octets.ToArray());
        }

19 View Source File : UIDebug.cs
License : GNU Affero General Public License v3.0
Project Creator : Caraxi

private void DrawElementSelector() {
            ImGui.GetIO().WantCaptureKeyboard = true;
            ImGui.GetIO().WantCaptureMouse = true;
            ImGui.GetIO().WantTextInput = true;
            if (ImGui.IsKeyPressed((int)VirtualKey.ESCAPE)) {
                elementSelectorActive = false;
                FreeExclusiveDraw();
                return;
            }
            
            ImGui.SetNextWindowPos(Vector2.Zero);
            ImGui.SetNextWindowSize(ImGui.GetIO().DisplaySize);
            ImGui.SetNextWindowBgAlpha(0.3f);
            ImGui.Begin("ElementSelectorWindow", ImGuiWindowFlags.NoDecoration | ImGuiWindowFlags.NoScrollWithMouse | ImGuiWindowFlags.NoScrollbar);
            var drawList = ImGui.GetWindowDrawList();
            
            var y = 100f;
            foreach (var s in new[]{"Select an Element", "Press ESCAPE to cancel"}) {
                var size = ImGui.CalcTextSize(s);
                var x = ImGui.GetWindowContentRegionWidth() / 2f - size.X / 2;
                drawList.AddText(new Vector2(x, y), 0xFFFFFFFF, s);
                y += size.Y;
            }
            
            var mousePos = ImGui.GetMousePos();
            var windows = GetAtkUnitBaseAtPosition(mousePos);

            ImGui.SetCursorPosX(100);
            ImGui.SetCursorPosY(100);
            ImGui.BeginChild("noClick", new Vector2(800, 2000), false, ImGuiWindowFlags.NoInputs | ImGuiWindowFlags.NoBackground | ImGuiWindowFlags.NoScrollWithMouse);
            ImGui.BeginGroup();
            
            ImGui.Text($"Mouse Position: {mousePos.X}, {mousePos.Y}\n");
            var i = 0;
            
            foreach (var a in windows) {
                var name = Marshal.PtrToStringAnsi(new IntPtr(a.UnitBase->Name));
                ImGui.Text($"[Addon] {name}");
                ImGui.Indent(15);
                foreach (var n in a.Nodes) {
                    var nSelected = i++ == elementSelectorIndex;
                    if (nSelected) ImGui.PushStyleColor(ImGuiCol.Text, 0xFF00FFFF);
                    // ImGui.Text($"{((int)n.ResNode->Type >= 1000 ? ((ULDComponentInfo*)((AtkComponentNode*) n.ResNode)->Component->UldManager.Objects)->ComponentType.ToString() + "ComponentNode" : n.ResNode->Type.ToString() + "Node")}");
                    
                    PrintNode(n.ResNode, false, null, true);
                    
                    
                    if (nSelected) ImGui.PopStyleColor();

                    if (nSelected && ImGui.IsMouseClicked(ImGuiMouseButton.Left)) {
                        elementSelectorActive = false;
                        FreeExclusiveDraw();

                        selectedUnitBase = a.UnitBase;

                        var l = new List<ulong>();
                        
                        l.Add((ulong)n.ResNode);
                        var nextNode = n.ResNode->ParentNode;
                        while (nextNode != null) {
                            l.Add((ulong) nextNode);
                            nextNode = nextNode->ParentNode;
                        }

                        elementSelectorFind = l.ToArray();
                        elementSelectorCountdown = 100;
                        elementSelectorScrolled = false;
                    }
                    
                    
                    drawList.AddRectFilled(n.State.Position, n.State.SecondPosition, (uint) (nSelected ? 0x4400FFFF: 0x0000FF00));
                }
                ImGui.Indent(-15);
            }

            if (i != 0) {
                elementSelectorIndex -= (int) ImGui.GetIO().MouseWheel;
                while (elementSelectorIndex < 0) elementSelectorIndex += i;
                while (elementSelectorIndex >= i) elementSelectorIndex -= i;
            }

            ImGui.EndGroup();
            ImGui.EndChild();
            ImGui.End();
        }

19 View Source File : FixedMemoryBlock.cs
License : Apache License 2.0
Project Creator : cdy816

public List<ulong> ReadULongs(long offset, int count)
        {
            List<ulong> re = new List<ulong>(count);
            for (int i = 0; i < count; i++)
            {
                re.Add(ReadULong(offset + 8 * i));
            }
            return re;
        }

19 View Source File : MarketDepth.cs
License : MIT License
Project Creator : centaurus-project

private bool AddOrder(OrderInfo order)
        {
            if (order == null)
                throw new ArgumentNullException(nameof(order));

            var price = NormalizePrice(order.Price);
            var source = prices[order.Side];
            var currentPrice = source.FirstOrDefault(p => p.Price == price);
            if (currentPrice == null)
            {
                currentPrice = new MarketDepthPrice(price);
                var indexToInsert = source.FindIndex(p => p.Price < price);
                if (indexToInsert == -1 && source.Count == maxPricesCount)
                    return false;

                if (indexToInsert == -1)
                    source.Add(currentPrice);
                else
                    source.Insert(indexToInsert, currentPrice);
            }
            currentPrice.Amount += order.AmountDiff;
            currentPrice.Orders.Add(order.OrderId);

            return true;
        }

19 View Source File : PS4DBG.Proc.cs
License : MIT License
Project Creator : ChendoChap

public List<ulong> ScanProcess<T>(int pid, ScanCompareType compareType, T value, T extraValue = default)
        {
            CheckConnected();

            int typeLength = 0;
            ScanValueType valueType;
            byte[] valueBuffer, extraValueBuffer = null;

            // fill in variables
            switch (value)
            {
                case bool b:
                    valueType = ScanValueType.valTypeUInt8;
                    typeLength = 1;
                    valueBuffer = BitConverter.GetBytes(b);
                    if (extraValue != null)
                        extraValueBuffer = BitConverter.GetBytes((bool)(object)extraValue);
                    break;
                case sbyte sb:
                    valueType = ScanValueType.valTypeInt8;
                    valueBuffer = BitConverter.GetBytes(sb);
                    typeLength = 1;
                    if (extraValue != null)
                        extraValueBuffer = BitConverter.GetBytes((sbyte)(object)extraValue);
                    break;
                case byte b:
                    valueType = ScanValueType.valTypeUInt8;
                    valueBuffer = BitConverter.GetBytes(b);
                    typeLength = 1;
                    if (extraValue != null)
                        extraValueBuffer = BitConverter.GetBytes((byte)(object)extraValue);
                    break;
                case short s:
                    valueType = ScanValueType.valTypeInt16;
                    valueBuffer = BitConverter.GetBytes(s);
                    typeLength = 2;
                    if (extraValue != null)
                        extraValueBuffer = BitConverter.GetBytes((short)(object)extraValue);
                    break;
                case ushort us:
                    valueType = ScanValueType.valTypeUInt16;
                    valueBuffer = BitConverter.GetBytes(us);
                    typeLength = 2;
                    if (extraValue != null)
                        extraValueBuffer = BitConverter.GetBytes((ushort)(object)extraValue);
                    break;
                case int i:
                    valueType = ScanValueType.valTypeInt32;
                    valueBuffer = BitConverter.GetBytes(i);
                    typeLength = 4;
                    if (extraValue != null)
                        extraValueBuffer = BitConverter.GetBytes((int)(object)extraValue);
                    break;
                case uint ui:
                    valueType = ScanValueType.valTypeUInt32;
                    valueBuffer = BitConverter.GetBytes(ui);
                    typeLength = 4;
                    if (extraValue != null)
                        extraValueBuffer = BitConverter.GetBytes((uint)(object)extraValue);
                    break;
                case long l:
                    valueType = ScanValueType.valTypeInt64;
                    valueBuffer = BitConverter.GetBytes(l);
                    typeLength = 8;
                    if (extraValue != null)
                        extraValueBuffer = BitConverter.GetBytes((long)(object)extraValue);
                    break;
                case ulong ul:
                    valueType = ScanValueType.valTypeUInt64;
                    valueBuffer = BitConverter.GetBytes(ul);
                    typeLength = 8;
                    if (extraValue != null)
                        extraValueBuffer = BitConverter.GetBytes((ulong)(object)extraValue);
                    break;
                case float f:
                    valueType = ScanValueType.valTypeFloat;
                    valueBuffer = BitConverter.GetBytes(f);
                    typeLength = 4;
                    if (extraValue != null)
                        extraValueBuffer = BitConverter.GetBytes((float)(object)extraValue);
                    break;
                case double d:
                    valueType = ScanValueType.valTypeDouble;
                    valueBuffer = BitConverter.GetBytes(d);
                    typeLength = 8;
                    if (extraValue != null)
                        extraValueBuffer = BitConverter.GetBytes((double)(object)extraValue);
                    break;
                case string s:
                    valueType = ScanValueType.valTypeString;
                    valueBuffer = Encoding.ASCII.GetBytes(s);
                    typeLength = valueBuffer.Length;
                    break;
                case byte[] ba:
                    valueType = ScanValueType.valTypeArrBytes;
                    valueBuffer = ba;
                    typeLength = valueBuffer.Length;
                    break;
                default:
                    throw new NotSupportedException("Requested scan value type is not supported! (Feed in Byte[] instead.)");
                    
            }
            // send packet
            SendCMDPacket(CMDS.CMD_PROC_SCAN, CMD_PROC_SCAN_PACKET_SIZE, pid, (byte)valueType, (byte)compareType, (int)(extraValue == null ? typeLength : typeLength * 2));
            CheckStatus();

            SendData(valueBuffer, typeLength);
            if (extraValueBuffer != null)
            {
                SendData(extraValueBuffer, typeLength);
            }

            CheckStatus();

            // receive results
            int save = sock.ReceiveTimeout;
            sock.ReceiveTimeout = Int32.MaxValue;
            List<ulong> results = new List<ulong>();
            while(true)
            {
                ulong result = BitConverter.ToUInt64(ReceiveData(sizeof(ulong)), 0);
                if(result == 0xFFFFFFFFFFFFFFFF)
                {
                    break;
                }

                results.Add(result);
            }

            sock.ReceiveTimeout = save;

            return results;
        }

19 View Source File : DebuggingSession.cs
License : MIT License
Project Creator : chrisnas

public List<ulong> GetInstancesOf(string typeName)
        {
            var clrType = ManagedHeap.GetTypeByName(typeName);
            if (clrType == null)
                return null;
            if (clrType.IsValueClreplaced)
                return null;

            List<ulong> addresses = new List<ulong>(1024);
            foreach (var address in ManagedHeap.EnumerateObjectAddresses())
            {
                var type = ManagedHeap.GetObjectType(address);
                if (type != clrType)
                    continue;

                addresses.Add(address);
            }

            return addresses;
        }

19 View Source File : astarclasses.cs
License : GNU General Public License v3.0
Project Creator : coconauts

public virtual void WillUpdateNode (GraphNode node) {
			if (trackChangedNodes && node != null) {
				if (changedNodes == null) { changedNodes = ListPool<GraphNode>.Claim(); backupData = ListPool<ulong>.Claim(); backupPositionData = ListPool<Int3>.Claim(); }
				changedNodes.Add (node);
				backupPositionData.Add (node.position);
				backupData.Add ((ulong)node.Penalty<<32 | (ulong)node.Flags);
			}
		}

19 View Source File : ReusableCluster.cs
License : MIT License
Project Creator : Const-me

void readSilentTracks( Stream stream, ref List<ulong> list )
		{
			ElementReader reader = new ElementReader( stream );
			while( !reader.EOF )
			{
				eElement id = reader.readElementId();
				switch( id )
				{
					case eElement.SilentTrackNumber:
						if( null == list )
							list = new List<ulong>();
						list.Add( reader.readUlong() );
						break;
					default:
						reader.skipElement();
						break;
				}
			}
		}

19 View Source File : CalendarManager.cs
License : GNU General Public License v3.0
Project Creator : CypherCore

void FreeInviteId(ulong id)
        {
            if (id == _maxInviteId)
                --_maxInviteId;
            else
                _freeInviteIds.Add(id);
        }

19 View Source File : CalendarManager.cs
License : GNU General Public License v3.0
Project Creator : CypherCore

public void LoadFromDB()
        {
            uint oldMSTime = Time.GetMSTime();

            uint count = 0;
            _maxEventId = 0;
            _maxInviteId = 0;

            //                                              0        1      2      3            4          5          6     7      8
            SQLResult result = DB.Characters.Query("SELECT EventID, Owner, replacedle, Description, EventType, TextureID, Date, Flags, LockDate FROM calendar_events");
            if (!result.IsEmpty())
            {
                do
                {
                    ulong eventID = result.Read<ulong>(0);
                    ObjectGuid ownerGUID = ObjectGuid.Create(HighGuid.Player, result.Read<ulong>(1));
                    string replacedle = result.Read<string>(2);
                    string description = result.Read<string>(3);
                    CalendarEventType type = (CalendarEventType)result.Read<byte>(4);
                    int textureID = result.Read<int>(5);
                    long date = result.Read<long>(6);
                    CalendarFlags flags = (CalendarFlags)result.Read<uint>(7);
                    long lockDate = result.Read<long>(8);
                    ulong guildID = 0;

                    if (flags.HasAnyFlag(CalendarFlags.GuildEvent) || flags.HasAnyFlag(CalendarFlags.WithoutInvites))
                        guildID = Global.CharacterCacheStorage.GetCharacterGuildIdByGuid(ownerGUID);

                    CalendarEvent calendarEvent = new(eventID, ownerGUID, guildID, type, textureID, date, flags, replacedle, description, lockDate);
                    _events.Add(calendarEvent);

                    _maxEventId = Math.Max(_maxEventId, eventID);

                    ++count;
                }
                while (result.NextRow());
            }

            Log.outInfo(LogFilter.ServerLoading, $"Loaded {count} calendar events in {Time.GetMSTimeDiffToNow(oldMSTime)} ms");
            count = 0;
            oldMSTime = Time.GetMSTime();

            //                                    0         1        2        3       4       5             6               7
            result = DB.Characters.Query("SELECT InviteID, EventID, Invitee, Sender, Status, ResponseTime, ModerationRank, Note FROM calendar_invites");
            if (!result.IsEmpty())
            {
                do
                {
                    ulong inviteId = result.Read<ulong>(0);
                    ulong eventId = result.Read<ulong>(1);
                    ObjectGuid invitee = ObjectGuid.Create(HighGuid.Player, result.Read<ulong>(2));
                    ObjectGuid senderGUID = ObjectGuid.Create(HighGuid.Player, result.Read<ulong>(3));
                    CalendarInviteStatus status = (CalendarInviteStatus)result.Read<byte>(4);
                    long responseTime = result.Read<long>(5);
                    CalendarModerationRank rank = (CalendarModerationRank)result.Read<byte>(6);
                    string note = result.Read<string>(7);

                    CalendarInvite invite = new(inviteId, eventId, invitee, senderGUID, responseTime, status, rank, note);
                    _invites.Add(eventId, invite);

                    _maxInviteId = Math.Max(_maxInviteId, inviteId);

                    ++count;
                }
                while (result.NextRow());
            }

            Log.outInfo(LogFilter.ServerLoading, $"Loaded {count} calendar invites in {Time.GetMSTimeDiffToNow(oldMSTime)} ms");

            for (ulong i = 1; i < _maxEventId; ++i)
                if (GetEvent(i) == null)
                    _freeEventIds.Add(i);

            for (ulong i = 1; i < _maxInviteId; ++i)
                if (GetInvite(i) == null)
                    _freeInviteIds.Add(i);
        }

19 View Source File : CalendarManager.cs
License : GNU General Public License v3.0
Project Creator : CypherCore

void FreeEventId(ulong id)
        {
            if (id == _maxEventId)
                --_maxEventId;
            else
                _freeEventIds.Add(id);
        }

19 View Source File : CreatureGroups.cs
License : GNU General Public License v3.0
Project Creator : CypherCore

public static void LoadCreatureFormations()
        {
            uint oldMSTime = Time.GetMSTime();

            //Get group data
            SQLResult result = DB.World.Query("SELECT leaderGUID, memberGUID, dist, angle, groupAI, point_1, point_2 FROM creature_formations ORDER BY leaderGUID");
            if (result.IsEmpty())
            {
                Log.outInfo(LogFilter.ServerLoading, "Loaded 0 creatures in formations. DB table `creature_formations` is empty!");
                return;
            }

            uint count = 0;
            List<ulong> leaderSpawnIds = new();
            do
            {
                //Load group member data
                FormationInfo member = new();
                member.LeaderSpawnId = result.Read<ulong>(0);
                ulong memberSpawnId = result.Read<ulong>(1);
                member.FollowDist = 0f;
                member.FollowAngle = 0f;

                //If creature is group leader we may skip loading of dist/angle
                if (member.LeaderSpawnId != memberSpawnId)
                {
                    member.FollowDist = result.Read<float>(2);
                    member.FollowAngle = result.Read<float>(3) * MathFunctions.PI / 180;
                }

                member.GroupAI = result.Read<uint>(4);

                for (var i = 0; i < 2; ++i)
                    member.LeaderWaypointIDs[i] = result.Read<ushort>(5 + i);

                // check data correctness
                {
                    if (Global.ObjectMgr.GetCreatureData(member.LeaderSpawnId) == null)
                    {
                        Log.outError(LogFilter.Sql, $"creature_formations table leader guid {member.LeaderSpawnId} incorrect (not exist)");
                        continue;
                    }

                    if (Global.ObjectMgr.GetCreatureData(memberSpawnId) == null)
                    {
                        Log.outError(LogFilter.Sql, $"creature_formations table member guid {memberSpawnId} incorrect (not exist)");
                        continue;
                    }

                    leaderSpawnIds.Add(member.LeaderSpawnId);
                }

                _creatureGroupMap.Add(memberSpawnId, member);
                ++count;
            }
            while (result.NextRow());

            foreach (ulong leaderSpawnId in leaderSpawnIds)
            {
                if (!_creatureGroupMap.ContainsKey(leaderSpawnId))
                {
                    Log.outError(LogFilter.Sql, $"creature_formation contains leader spawn {leaderSpawnId} which is not included on its formation, removing");
                    foreach (var itr in _creatureGroupMap.ToList())
                    {
                        if (itr.Value.LeaderSpawnId == leaderSpawnId)
                            _creatureGroupMap.Remove(itr.Key);
                    }
                }
            }

            Log.outInfo(LogFilter.ServerLoading, "Loaded {0} creatures in formations in {1} ms", count, Time.GetMSTimeDiffToNow(oldMSTime));
        }

19 View Source File : PoolManager.cs
License : GNU General Public License v3.0
Project Creator : CypherCore

public void ActivateObject<T>(ulong db_guid, uint pool_id)
        {
            switch (typeof(T).Name)
            {
                case "Creature":
                    mSpawnedCreatures.Add(db_guid);
                    break;
                case "GameObject":
                    mSpawnedGameobjects.Add(db_guid);
                    break;
                case "Pool":
                    mSpawnedPools[db_guid] = 0;
                    break;
                case "Quest":
                    mActiveQuests.Add(db_guid);
                    break;
                default:
                    return;
            }
            if (!mSpawnedPools.ContainsKey(pool_id))
                mSpawnedPools[pool_id] = 0;

            ++mSpawnedPools[pool_id];
        }

19 View Source File : PoolManager.cs
License : GNU General Public License v3.0
Project Creator : CypherCore

void SpawnQuestObject(ActivePoolData spawns, uint limit, ulong triggerFrom)
        {
            Log.outDebug(LogFilter.Pool, "PoolGroup<Quest>: Spawning pool {0}", poolId);
            // load state from db
            if (triggerFrom == 0)
            {
                PreparedStatement stmt = DB.Characters.GetPreparedStatement(CharStatements.SEL_POOL_QUEST_SAVE);
                stmt.AddValue(0, poolId);
                SQLResult result = DB.Characters.Query(stmt);

                if (!result.IsEmpty())
                {
                    do
                    {
                        uint questId = result.Read<uint>(0);
                        spawns.ActivateObject<Quest>(questId, poolId);
                        PoolObject tempObj = new(questId, 0.0f);
                        Spawn1Object(tempObj);
                        --limit;
                    } while (result.NextRow() && limit != 0);
                    return;
                }
            }

            List<ulong> currentQuests = spawns.GetActiveQuests();
            List<ulong> newQuests = new();

            // always try to select different quests
            foreach (var poolObject in EqualChanced)
            {
                if (spawns.IsActiveObject<Quest>(poolObject.guid))
                    continue;
                newQuests.Add(poolObject.guid);
            }

            // clear the pool
            DespawnObject(spawns);

            // recycle minimal amount of quests if possible count is lower than limit
            while (limit > newQuests.Count && !currentQuests.Empty())
            {
                ulong questId = currentQuests.SelectRandom();
                newQuests.Add(questId);
                currentQuests.Remove(questId);
            }

            if (newQuests.Empty())
                return;

            // activate <limit> random quests
            do
            {
                ulong questId = newQuests.SelectRandom();
                spawns.ActivateObject<Quest>(questId, poolId);
                PoolObject tempObj = new(questId, 0.0f);
                Spawn1Object(tempObj);
                newQuests.Remove(questId);
                --limit;
            } while (limit != 0 && !newQuests.Empty());

            // if we are here it means the pool is initialized at startup and did not have previous saved state
            if (triggerFrom == 0)
                Global.PoolMgr.SaveQuestsToDB();
        }

19 View Source File : MailHandler.cs
License : GNU General Public License v3.0
Project Creator : CypherCore

[WorldPacketHandler(ClientOpcodes.QueryNextMailTime)]
        void HandleQueryNextMailTime(MailQueryNextMailTime packet)
        {
            MailQueryNextTimeResult result = new();

            if (!GetPlayer().m_mailsLoaded)
                GetPlayer()._LoadMail();

            if (GetPlayer().unReadMails > 0)
            {
                result.NextMailTime = 0.0f;

                long now = GameTime.GetGameTime();
                List<ulong> sentSenders = new();

                foreach (Mail mail in GetPlayer().GetMails())
                {
                    if (mail.checkMask.HasAnyFlag(MailCheckMask.Read))
                        continue;

                    // and already delivered
                    if (now < mail.deliver_time)
                        continue;

                    // only send each mail sender once
                    if (sentSenders.Any(p => p == mail.sender))
                        continue;

                    result.Next.Add(new MailQueryNextTimeResult.MailNextTimeEntry(mail));

                    sentSenders.Add(mail.sender);

                    // do not send more than 2 mails
                    if (sentSenders.Count > 2)
                        break;
                }
            }
            else
                result.NextMailTime = -Time.Day;

            SendPacket(result);
        }

19 View Source File : SevenZipExtractor.cs
License : MIT License
Project Creator : daPhie79

public IExtractor ExtractFiles(string[] fileNames, string outputDirectory)
        {
            var indices = new List<UInt64>();
            foreach (var fileName in fileNames)
            {
                long index = findFileIndex(fileName, true);
                if (index == -1)
                    throw new ArgumentOutOfRangeException($"Filename `{fileName}` doesn't exist in archive.");
                indices.Add((UInt64)index);
            }
            if (indices.Any())
                return ExtractFiles(indices.ToArray(), outputDirectory);

            return this;
        }

19 View Source File : SevenZipExtractor.cs
License : MIT License
Project Creator : daPhie79

public IExtractor ExtractFiles(string[] fileNames, Func<ArchiveFile, Stream> onStreamRequest, Action<ArchiveFile, Stream> onStreamClose = null)
        {
            var indices = new List<UInt64>();
            foreach (var fileName in fileNames)
            {
                long index = findFileIndex(fileName, true);
                if (index == -1)
                    throw new ArgumentOutOfRangeException($"Filename `{fileName}` doesn't exist in archive.");
                indices.Add((UInt64)index);
            }
            if (indices.Any())
                return ExtractFiles(indices.ToArray(), onStreamRequest, onStreamClose);

            return this;
        }

19 View Source File : SevenZipExtractor.cs
License : MIT License
Project Creator : daPhie79

public IExtractor ExtractFiles(UInt64[] indices, string outputDirectory)
        {
            if (indices.Any(index => index >= (ulong)_Files.LongLength))
                throw new ArgumentOutOfRangeException("An index given in `indices[]` array is out of range.");

            // preprocess files and keep track of streams to decompress
            var streamToFileIndex = new Dictionary<ulong, ulong>();
            var streamIndices = new List<ulong>();
            ulong streamIndex = 0;
            for (ulong i = 0; i < (ulong)_Files.LongLength; ++i)
            {
                if (!indices.Any() || Array.IndexOf(indices, i) != -1)
                {
                    if (!preProcessFile(outputDirectory, _Files[i]))
                        streamIndices.Add(streamIndex);
                }
                if (!_Files[i].IsEmpty)
                    streamToFileIndex[streamIndex++] = i;
            }

            // no file to decompress
            if (!streamIndices.Any())
            {
                Trace.TraceWarning("ExtractFiles: No decoding required.");
                return this;
            }

            // progress provider
            SevenZipProgressProvider szpp = null;
            if (ProgressDelegate != null)
                szpp = new SevenZipProgressProvider(_Files, indices, ProgressDelegate);

            // extraction
            Trace.TraceInformation("Extracting...");
            var sx = new SevenZipStreamsExtractor(stream, header.RawHeader.MainStreamsInfo, Preplacedword);
            sx.ExtractMultiple(
                streamIndices.ToArray(),
                (ulong index) => {
                    SevenZipArchiveFile file = _Files[streamToFileIndex[index]];
                    string fullPath = Path.Combine(outputDirectory, PreserveDirectoryStructure ? file.Name : Path.GetFileName(file.Name));

                    Trace.TraceInformation($"File index {index}, filename: {file.Name}, file size: {file.Size}");
                    return new FileStream(fullPath,
                        FileMode.Create,
                        FileAccess.Write,
                        FileShare.None,
                        bufferSize);
                },
                (ulong index, Stream stream) => {
                    stream.Close();
                    SevenZipArchiveFile file = _Files[streamToFileIndex[index]];
                    string fullPath = Path.Combine(outputDirectory, PreserveDirectoryStructure ? file.Name : Path.GetFileName(file.Name));
                    if (file.Time != null)
                        File.SetLastWriteTimeUtc(fullPath, (DateTime)file.Time);
                },
                szpp);

            return this;
        }

19 View Source File : SevenZipExtractor.cs
License : MIT License
Project Creator : daPhie79

public IExtractor ExtractFiles(UInt64[] indices, Func<ArchiveFile, Stream> onStreamRequest, Action<ArchiveFile, Stream> onStreamClose = null)
        {
            if (indices.Any(index => index >= (ulong)_Files.LongLength))
                throw new ArgumentOutOfRangeException("An index given in `indices[]` array is out of range.");

            // preprocess files and keep track of streams to decompress
            var streamToFileIndex = new Dictionary<ulong, ulong>();
            var streamIndices = new List<ulong>();
            ulong streamIndex = 0;
            for (ulong i = 0; i < (ulong)_Files.LongLength; ++i)
            {
                if (!indices.Any() || Array.IndexOf(indices, i) != -1)
                {
                    if (_Files[i].IsEmpty)
                    {
                        using (Stream s = onStreamRequest(_Files[i]))
                            if (s != null)
                                onStreamClose?.Invoke(_Files[i], s);
                    }
                    else if (indices.Any())
                        streamIndices.Add(streamIndex);
                }
                if (!_Files[i].IsEmpty)
                    streamToFileIndex[streamIndex++] = i;
            }

            // no file to decompress
            if (!streamToFileIndex.Any())
            {
                Trace.TraceWarning("ExtractFiles: No decoding required.");
                return this;
            }

            // progress provider
            SevenZipProgressProvider szpp = null;
            if (ProgressDelegate != null)
                szpp = new SevenZipProgressProvider(_Files, indices, ProgressDelegate);

            // extraction
            Trace.TraceInformation("Extracting...");
            var sx = new SevenZipStreamsExtractor(stream, header.RawHeader.MainStreamsInfo, Preplacedword);
            sx.ExtractMultiple(
                streamIndices.ToArray(),
                (ulong index) => onStreamRequest(_Files[streamToFileIndex[index]]),
                (ulong index, Stream stream) => onStreamClose?.Invoke(_Files[streamToFileIndex[index]], stream),
                szpp);

            return this;
        }

19 View Source File : SevenZipHeader.cs
License : MIT License
Project Creator : daPhie79

public void Parse(Stream hs)
            {
                PropertyID propertyID = GetPropertyID(this, hs);

                // Number of UnPack Streams per Folder

                if (propertyID == PropertyID.kNumUnPackStream)
                {
                    NumUnPackStreamsInFolders = new UInt64[unPackInfo.NumFolders];
                    NumUnPackStreamsTotal = 0;
                    for (ulong i = 0; i < unPackInfo.NumFolders; ++i)
                        NumUnPackStreamsTotal += NumUnPackStreamsInFolders[i] = hs.ReadDecodedUInt64();

                    propertyID = GetPropertyID(this, hs);
                }
                else // If no records, replacedume `1` output stream per folder
                {
                    NumUnPackStreamsInFolders = Enumerable.Repeat((UInt64)1, (int)unPackInfo.NumFolders).ToArray();
                    NumUnPackStreamsTotal = unPackInfo.NumFolders;
                }

                // UnPackSizes

                UnPackSizes = new List<UInt64>();
                if (propertyID == PropertyID.kSize)
                {
                    for (ulong i = 0; i < unPackInfo.NumFolders; ++i)
                    {
                        UInt64 num = NumUnPackStreamsInFolders[i];
                        if (num == 0)
                            continue;

                        UInt64 sum = 0;
                        for (ulong j = 1; j < num; ++j)
                        {
                            UInt64 size = hs.ReadDecodedUInt64();
                            sum += size;
                            UnPackSizes.Add(size);
                        }
                        UnPackSizes.Add(unPackInfo.Folders[i].GetUnPackSize() - sum);
                    }

                    propertyID = GetPropertyID(this, hs);
                }
                else // If no records, replacedume one unpack size per folder
                {
                    for (ulong i = 0; i < unPackInfo.NumFolders; ++i)
                    {
                        ulong num = NumUnPackStreamsInFolders[i];
                        if (num > 1)
                            throw new SevenZipException($"Invalid number of UnPackStreams `{num}` in Folder # `{i}`.");
                        if (num == 1)
                            UnPackSizes.Add(unPackInfo.Folders[i].GetUnPackSize());
                    }
                }

                // Digests [Number of Unknown CRCs]

                UInt64 numDigests = 0;
                for (UInt64 i = 0; i < unPackInfo.NumFolders; ++i)
                {
                    UInt64 numSubStreams = NumUnPackStreamsInFolders[i];
                    if (numSubStreams > 1 || unPackInfo.Folders[i].UnPackCRC == null)
                        numDigests += numSubStreams;
                }

                if (propertyID == PropertyID.kCRC)
                {
                    Digests = new Digests(numDigests);
                    Digests.Parse(hs);

                    propertyID = GetPropertyID(this, hs);
                }

                if (propertyID != PropertyID.kEnd)
                    throw new SevenZipException("Expected `kEnd` property ID.");
            }

19 View Source File : TsMapAreaItem.cs
License : MIT License
Project Creator : dariowouters

public void TsMapAreaItem825(int startOffset)
        {
            var fileOffset = startOffset + 0x34; // Set position at start of flags

            DrawOver = MemoryHelper.ReadUint8(Sector.Stream, fileOffset) != 0;
            var dlcGuardCount = (Sector.Mapper.IsEts2) ? Common.Ets2DlcGuardCount : Common.AtsDlcGuardCount;
            Hidden = MemoryHelper.ReadInt8(Sector.Stream, fileOffset + 0x01) > dlcGuardCount;

            NodeUids = new List<ulong>();

            var nodeCount = MemoryHelper.ReadInt32(Sector.Stream, fileOffset += 0x05); // 0x05(flags)
            fileOffset += 0x04; // 0x04(nodeCount)
            for (var i = 0; i < nodeCount; i++)
            {
                NodeUids.Add(MemoryHelper.ReadUInt64(Sector.Stream, fileOffset));
                fileOffset += 0x08;
            }

            ColorIndex = MemoryHelper.ReadUInt32(Sector.Stream, fileOffset);
            fileOffset += 0x04; // 0x04(colorIndex)
            BlockSize = fileOffset - startOffset;
        }

19 View Source File : ColumnWriterStatistics.cs
License : MIT License
Project Creator : ddrinka

public void AnnotatePosition(long storedBufferOffset, long? decompressedOffset = null, int? rleValuesToConsume = null, int? bitsToConsume = null)
        {
            var newTuple = new List<ulong> { (ulong)storedBufferOffset };
            if (decompressedOffset.HasValue)
                newTuple.Add((ulong)decompressedOffset.Value);
            if (rleValuesToConsume.HasValue)
                newTuple.Add((ulong)rleValuesToConsume.Value);
            if (bitsToConsume.HasValue)
                newTuple.Add((ulong)bitsToConsume.Value);
            PositionTuples.Add(newTuple);
        }

See More Examples