System.Collections.Generic.Queue.Dequeue()

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

4232 Examples 7

19 Source : MainViewModel.cs
with MIT License
from ABTSoftware

public void RunNextTest()
        {
            if (_testQueue.Count == 0)
                return;

            var testCase = _testQueue.Dequeue();
            LayoutRoot.Children.Add(testCase.SpeedTestUi);

            testCase.Run((result) =>
                {
                    LayoutRoot.Children.Remove(testCase.SpeedTestUi);

                    // log the test run
                    _testRuns.Add(string.Format("({0:N2}) - {1} - {2}", result, testCase.TestCaseName, testCase.Version));

                    // add results to the table
                    var testResult = _testResults.SingleOrDefault(i => i.TestName == testCase.TestCaseName);
                    if (testResult == null)
                    {
                        testResult = new TestResult()
                        {
                            TestName = testCase.TestCaseName
                        };
                        _testResults.Add(testResult);
                    }
                    testResult[testCase.Version] = result;
                    string strPrefix = "LC";
                    if (_iTestResult % 2 == 0)
                    {
                        strPrefix = "SC";
                    }
                    else
                    {
                        strPrefix = "LC";
                    } 
                    //Write to log 
                    WriteLog(testCase.TestCaseName + ";" + result.ToString("0.0") + ";", System.AppDomain.CurrentDomain.BaseDirectory + "\\"+strPrefix+"_PerformanceComparisonDump.csv");
                    _iTestResult++; 
                    // start the next test
                    TestFinished(testCase, result);
                });
        }

19 Source : BuilderEntityMetadata.cs
with MIT License
from abvogel

public void RemoveAttributesWhereIdentical(Enreplacedy enreplacedy)
        {
            this.CommitIdentifier();

            var ReducedEnreplacedies = new Queue<Enreplacedy>();

            while (this.Enreplacedies.Count > 0)
            {
                var e = this.Enreplacedies.Dequeue();
                String EnreplacedyIdentifier = GetIdentifierFromEnreplacedy(e);
                String EnreplacedyToMatch = GetIdentifierFromEnreplacedy(enreplacedy);

                if (EnreplacedyIdentifier.Equals(EnreplacedyToMatch))
                {
                    var newAttributes = e.Attributes.Except(enreplacedy.Attributes, new AttributeComparer()).ToList();

                    if (newAttributes.Count == 0)
                        continue;

                    e.SetSealedPropertyValue("Attributes", new AttributeCollection());
                    foreach (var attribute in newAttributes)
                    {
                        e[attribute.Key] = attribute.Value;
                    }
                }

                ReducedEnreplacedies.Enqueue(e);
            }

            while (ReducedEnreplacedies.Count > 0)
                this.Enreplacedies.Enqueue(ReducedEnreplacedies.Dequeue());
        }

19 Source : BuilderEntityMetadata.cs
with MIT License
from abvogel

private void ReduceEnreplacediesBasedOnIdentifier()
        {
            Dictionary<String, Enreplacedy> DistinctEnreplacedies = new Dictionary<String, Enreplacedy>();

            while (Enreplacedies.Count > 0)
            {
                var enreplacedy = Enreplacedies.Dequeue();
                String EnreplacedyIdentifier = GetIdentifierFromEnreplacedy(enreplacedy);
                if (DistinctEnreplacedies.ContainsKey(EnreplacedyIdentifier))
                {
                    Enreplacedy priorEnreplacedy = DistinctEnreplacedies[EnreplacedyIdentifier];
                    foreach (var attribute in enreplacedy.Attributes)
                    {
                        priorEnreplacedy[attribute.Key] = attribute.Value;
                    }
                    DistinctEnreplacedies[EnreplacedyIdentifier] = priorEnreplacedy;
                }
                else
                {
                    DistinctEnreplacedies.Add(EnreplacedyIdentifier, enreplacedy);
                }
            }

            // Rebuild list of enreplacedies based on an enforced identifier
            DistinctEnreplacedies.Keys.ToList<String>().ForEach(key => Enreplacedies.Enqueue(DistinctEnreplacedies[key]));
        }

19 Source : CategoryTree.cs
with Apache License 2.0
from acblog

public IEnumerable<Category> AsCategoryList()
        {
            Queue<CategoryTreeNode> q = new Queue<CategoryTreeNode>();
            foreach (var item in Root.Children.Values)
            {
                q.Enqueue(item);
            }
            while (q.Count > 0)
            {
                var u = q.Dequeue();
                yield return u.Category;
                foreach (var v in u.Children.Values)
                {
                    q.Enqueue(v);
                }
            }
        }

19 Source : PostRepositoryBuilder.cs
with Apache License 2.0
from acblog

async Task BuildIndexCategory(IList<Post> data)
        {
            FSStaticBuilder.EnsureDirectoryEmpty(Paths.GetCategoryRoot(RootPath));

            var (tree, map) = await CategoryTreeBuilder.BuildFromPosts(data.ToAsyncEnumerable());

            Queue<CategoryTree.CategoryTreeNode> q = new Queue<CategoryTree.CategoryTreeNode>();
            foreach (var v in tree.Root.Children.Values)
                q.Enqueue(v);

            while (q.Count > 0)
            {
                var node = q.Dequeue();

                await BuildDataIdList(map[node].Select(x => x.Id).IgnoreNull().ToArray(),
                    Paths.GetCategoryRoot(RootPath, node.Category)).ConfigureAwait(false);

                foreach (var v in node.Children.Values)
                    q.Enqueue(v);
            }

            await using var st = FSStaticBuilder.GetFileRewriteStream(Paths.GetCategoryMetadata(RootPath));
            await JsonSerializer.SerializeAsync(st, tree).ConfigureAwait(false);
        }

19 Source : PropertyObserver.cs
with MIT License
from Accelerider

private void Initialize(INotifyPropertyChanged owner, Queue<string> expressions, Action onChanged)
        {
            var propObserverNodeRoot = new PropertyObserverNode(expressions.Dequeue(), onChanged);
            PropertyObserverNode previousNode = propObserverNodeRoot;
            foreach (var propName in expressions) // Create a node chain that corresponds to the property chain.
            {
                var currentNode = new PropertyObserverNode(propName, onChanged);
                previousNode.Next = currentNode;
                previousNode = currentNode;
            }

            _tailNode = previousNode;

            propObserverNodeRoot.SubscribeListenerFor(owner);
        }

19 Source : ChessMatch.cs
with GNU Affero General Public License v3.0
from ACEmulator

public void Update()
        {
            switch (State)
            {
                case ChessState.WaitingForPlayers:
                    {
                        if (StartAiTime != null && DateTime.UtcNow >= StartAiTime)
                        {
                            AddAi();
                        }
                        break;
                    }

                case ChessState.InProgress:
                    {
                        switch (AiState)
                        {
                            case ChessAiState.WaitingToStart:
                                StartAiMove();
                                break;
                            case ChessAiState.WaitingForFinish:
                                FinishAiMove();
                                break;
                        }
                        break;
                    }
            }

            // don't handle any delayed actions while ai is working to prevent races
            if (AiState != ChessAiState.None)
                return;

            // don't handle any delayed actions while weenie pieces are moving or attacking
            if (WaitingForMotion)
                return;

            while (Actions.Count > 0)
            {
                var action = Actions.Dequeue();

                switch (action.Action)
                {
                    case ChessDelayedActionType.Start:
                        Start();
                        break;
                    case ChessDelayedActionType.Move:
                        MoveDelayed(action);
                        break;
                    case ChessDelayedActionType.MovePreplaced:
                        MovePreplacedDelayed(action);
                        break;
                    case ChessDelayedActionType.Stalemate:
                        StalemateDelayed(action);
                        break;
                    case ChessDelayedActionType.Quit:
                        QuitDelayed(action.Color);
                        break;
                }
            }

            if (NextRangeCheck != null)
            {
                if (NextRangeCheck.Value <= DateTime.UtcNow)
                {
                    foreach (var side in Sides)
                    {
                        if (side == null)
                            continue;

                        if (side.IsAi())
                            continue;

                        var player = side.GetPlayer();
                        if (player == null)
                        {
                            QuitDelayed(side.Color);
                            return;
                        }

                        // arbitrary distance, should there be some warning before reaching leash range?
                        var distanceToGame = player.Location.DistanceTo(ChessBoard.Location);
                        if (distanceToGame > 40.0f)
                        {
                            QuitDelayed(side.Color);
                            return;
                        }
                    }
                    NextRangeCheck = DateTime.UtcNow.AddSeconds(5);
                }
            }
        }

19 Source : GeneratorProfile.cs
with GNU Affero General Public License v3.0
from ACEmulator

public void Maintenance_HeartBeat()
        {
            while (RemoveQueue.TryPeek(out var result) && result.time <= DateTime.UtcNow)
            {
                RemoveQueue.Dequeue();
                FreeSlot(result.objectGuid);
            }
        }

19 Source : GuidManager.cs
with GNU Affero General Public License v3.0
from ACEmulator

public uint Alloc()
            {
                lock (this)
                {
                    // First, try to use a recycled Guid
                    if (recycledGuids.TryPeek(out var result) && DateTime.UtcNow - result.Item1 > recycleTime)
                    {
                        recycledGuids.Dequeue();
                        return result.Item2;
                    }

                    // Second, try to use a known available Guid
                    if (availableIDs.First != null)
                    {
                        var id = availableIDs.First.Value.start;

                        if (availableIDs.First.Value.start == availableIDs.First.Value.end)
                        {
                            availableIDs.RemoveFirst();

                            //if (availableIDs.First == null)
                            //    log.Warn($"Sequence gap GUIDs depleted on {name}");
                        }
                        else
                            availableIDs.First.Value = (availableIDs.First.Value.start + 1, availableIDs.First.Value.end);

                        return id;
                    }
                    else
                    {
                        if (!useSequenceGapExhaustedMessageDisplayed)
                        {
                            log.Debug($"{name} GUID Sequence gaps exhausted. Any new, non-recycled GUID will be current + 1. current is now {current:X8}");
                            useSequenceGapExhaustedMessageDisplayed = true;
                        }
                    }

                    // Lastly, use an id that increments our max
                    if (current == max)
                    {
                        log.Fatal($"Out of {name} GUIDs!");
                        return InvalidGuid;
                    }

                    if (current == max - LowIdLimit)
                        log.Warn($"Running dangerously low on {name} GUIDs, need to defrag");

                    uint ret = current;
                    current += 1;

                    return ret;
                }
            }

19 Source : NetworkBundle.cs
with GNU Affero General Public License v3.0
from ACEmulator

public GameMessage Dequeue()
        {
            return messages.Dequeue();
        }

19 Source : AttackQueue.cs
with GNU Affero General Public License v3.0
from ACEmulator

public float Fetch()
        {
            if (PowerAccuracy.Count > 1)
                PowerAccuracy.Dequeue();

            if (!PowerAccuracy.TryPeek(out var powerAccuracy))
            {
                //log.Error($"{Player.Name}.AttackQueue.Fetch() - empty queue");
                return 0.5f;
            }
            return powerAccuracy;
        }

19 Source : QueueExtensions.cs
with GNU Affero General Public License v3.0
from ACEmulator

public static T DequeueLast<T>(this Queue<T> q)
    {
        for (var i = 1; i < q.Count; i++)
            q.Enqueue(q.Dequeue());

        return q.Dequeue();
    }

19 Source : QueueExtensions.cs
with GNU Affero General Public License v3.0
from ACEmulator

public static IEnumerable<T> DequeueLast<T>(this Queue<T> q, int quanreplacedy)
    {
        for (var i = quanreplacedy; i < q.Count; i++)
            q.Enqueue(q.Dequeue());

        var poppedItems = new List<T>(quanreplacedy);
        for (int i = 0; i < quanreplacedy; i++)
            poppedItems.Add(q.Dequeue());

        return poppedItems;
    }

19 Source : QueueExtensions.cs
with GNU Affero General Public License v3.0
from ACEmulator

public static void EnqueueFirst<T>(this Queue<T> q, T item)
    {
        q.Enqueue(item);
        for (var i = 1; i < q.Count; i++)
            q.Enqueue(q.Dequeue());
    }

19 Source : QueueExtensions.cs
with GNU Affero General Public License v3.0
from ACEmulator

public static void EnqueueFirst<T>(this Queue<T> q, IEnumerable<T> items)
    {
        if (items == null || !items.Any()) return;

        foreach (var item in items)
            q.Enqueue(item);

        for (var i = items.Count(); i < q.Count; i++)
            q.Enqueue(q.Dequeue());
    }

19 Source : InterpolationManager.cs
with GNU General Public License v3.0
from ACEmulator

public void NodeCompleted(bool success)
        {
            if (PhysicsObj == null)
                return;

            FrameCounter = 0;
            ProgressQuantum = 0.0f;

            var head = PositionQueue.Count == 0 ? null : PositionQueue.First();
            var next = PositionQueue.Count <= 1 ? null : PositionQueue.ElementAt(1);

            if (PositionQueue.Count > 1)
            {
                if (next.Type == InterpolationNodeType.PositionType)
                    OriginalDistance = PhysicsObj.Position.Distance(next.Position);

                else if (!success)
                {
                    if (head == null) return;
                    BlipToPosition = head.Position;
                }
            }
            else
            {
                OriginalDistance = LargeDistance;
                if (!success)
                {
                    if (head == null) return;
                    BlipToPosition = head.Position;
                }
                else
                    StopInterpolating();
            }
            if (PositionQueue.Count > 0)
                PositionQueue.Dequeue();
        }

19 Source : InterpolationManager.cs
with GNU General Public License v3.0
from ACEmulator

public void InterpolateTo(Position position, bool keepHeading)
        {
            if (PhysicsObj == null)
                return;

            var dest = PositionQueue.Count > 0 && PositionQueue.Last().Type == InterpolationNodeType.PositionType ?
                PositionQueue.Last().Position : PhysicsObj.Position;

            var dist = dest.Distance(position);

            if (PhysicsObj.GetAutonomyBlipDistance() >= dist)
            {
                if (PhysicsObj.Position.Distance(position) > 0.05f)
                {
                    while (PositionQueue.Count > 0)
                    {
                        var lastNode = PositionQueue.Last();
                        if (lastNode.Type != InterpolationNodeType.PositionType || lastNode.Position.Distance(position) >= 0.05f)
                            break;

                        PositionQueue.DequeueLast();
                    }
                    while (PositionQueue.Count >= 20)
                        PositionQueue.Dequeue();

                    var interpolationNode = new InterpolationNode(InterpolationNodeType.PositionType, position);
                    if (keepHeading)
                        interpolationNode.Position.Frame.set_heading(PhysicsObj.get_heading());

                    PositionQueue.Enqueue(interpolationNode);
                }
                else
                {
                    if (!keepHeading)
                        PhysicsObj.set_heading(position.Frame.get_heading(), true);

                    StopInterpolating();
                }
            }
            else
            {
                var interpolationNode = new InterpolationNode(InterpolationNodeType.PositionType, position);
                if (keepHeading)
                    interpolationNode.Position.Frame.set_heading(PhysicsObj.get_heading());

                PositionQueue.Enqueue(interpolationNode);
                NodeFailCounter = 4;
            }
        }

19 Source : PromptManagerTestsL0.cs
with MIT License
from actions

[Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "PromptManager")]
        public void PromptsAgainWhenEmpty()
        {
            using (TestHostContext hc = new TestHostContext(this))
            {
                // Arrange.
                var readLineValues = new Queue<string>(new[] { string.Empty, "Some prompt value" });
                _terminal
                    .Setup(x => x.ReadLine())
                    .Returns(() => readLineValues.Dequeue());
                _terminal
                    .Setup(x => x.ReadSecret())
                    .Throws<InvalidOperationException>();
                hc.SetSingleton(_terminal.Object);
                _promptManager.Initialize(hc);

                // Act.
                string actual = ReadValue();

                // replacedert.
                replacedert.Equal("Some prompt value", actual);
                _terminal.Verify(x => x.ReadLine(), Times.Exactly(2));
            }
        }

19 Source : PromptManagerTestsL0.cs
with MIT License
from actions

[Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "PromptManager")]
        public void PromptsAgainWhenFailsValidation()
        {
            using (TestHostContext hc = new TestHostContext(this))
            {
                // Arrange.
                var readLineValues = new Queue<string>(new[] { "Some invalid prompt value", "Some valid prompt value" });
                _terminal
                    .Setup(x => x.ReadLine())
                    .Returns(() => readLineValues.Dequeue());
                _terminal
                    .Setup(x => x.ReadSecret())
                    .Throws<InvalidOperationException>();
                hc.SetSingleton(_terminal.Object);
                _promptManager.Initialize(hc);

                // Act.
                string actual = ReadValue(validator: x => x == "Some valid prompt value");

                // replacedert.
                replacedert.Equal("Some valid prompt value", actual);
                _terminal.Verify(x => x.ReadLine(), Times.Exactly(2));
            }
        }

19 Source : RunnerL0.cs
with MIT License
from actions

[Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Runner")]
        //process 2 new job messages, and one cancel message
        public async void TestRunAsync()
        {
            using (var hc = new TestHostContext(this))
            {
                //Arrange
                var runner = new Runner.Listener.Runner();
                hc.SetSingleton<IConfigurationManager>(_configurationManager.Object);
                hc.SetSingleton<IJobNotification>(_jobNotification.Object);
                hc.SetSingleton<IMessageListener>(_messageListener.Object);
                hc.SetSingleton<IPromptManager>(_promptManager.Object);
                hc.SetSingleton<IRunnerServer>(_runnerServer.Object);
                hc.SetSingleton<IConfigurationStore>(_configStore.Object);
                runner.Initialize(hc);
                var settings = new RunnerSettings
                {
                    PoolId = 43242
                };

                var message = new TaskAgentMessage()
                {
                    Body = JsonUtility.ToString(CreateJobRequestMessage("job1")),
                    MessageId = 4234,
                    MessageType = JobRequestMessageTypes.PipelineAgentJobRequest
                };

                var messages = new Queue<TaskAgentMessage>();
                messages.Enqueue(message);
                var signalWorkerComplete = new SemapreplacedSlim(0, 1);
                _configurationManager.Setup(x => x.LoadSettings())
                    .Returns(settings);
                _configurationManager.Setup(x => x.IsConfigured())
                    .Returns(true);
                _messageListener.Setup(x => x.CreateSessionAsync(It.IsAny<CancellationToken>()))
                    .Returns(Task.FromResult<bool>(true));
                _messageListener.Setup(x => x.GetNextMessageAsync(It.IsAny<CancellationToken>()))
                    .Returns(async () =>
                        {
                            if (0 == messages.Count)
                            {
                                signalWorkerComplete.Release();
                                await Task.Delay(2000, hc.RunnerShutdownToken);
                            }

                            return messages.Dequeue();
                        });
                _messageListener.Setup(x => x.DeleteSessionAsync())
                    .Returns(Task.CompletedTask);
                _messageListener.Setup(x => x.DeleteMessageAsync(It.IsAny<TaskAgentMessage>()))
                    .Returns(Task.CompletedTask);
                _jobDispatcher.Setup(x => x.Run(It.IsAny<Pipelines.AgentJobRequestMessage>(), It.IsAny<bool>()))
                    .Callback(() =>
                    {

                    });
                _jobNotification.Setup(x => x.StartClient(It.IsAny<String>()))
                    .Callback(() =>
                    {

                    });

                hc.EnqueueInstance<IJobDispatcher>(_jobDispatcher.Object);

                _configStore.Setup(x => x.IsServiceConfigured()).Returns(false);
                //Act
                var command = new CommandSettings(hc, new string[] { "run" });
                Task runnerTask = runner.ExecuteCommand(command);

                //replacedert
                //wait for the runner to run one job
                if (!await signalWorkerComplete.WaitAsync(2000))
                {
                    replacedert.True(false, $"{nameof(_messageListener.Object.GetNextMessageAsync)} was not invoked.");
                }
                else
                {
                    //Act
                    hc.ShutdownRunner(ShutdownReason.UserCancelled); //stop Runner

                    //replacedert
                    Task[] taskToWait2 = { runnerTask, Task.Delay(2000) };
                    //wait for the runner to exit
                    await Task.WhenAny(taskToWait2);

                    replacedert.True(runnerTask.IsCompleted, $"{nameof(runner.ExecuteCommand)} timed out.");
                    replacedert.True(!runnerTask.IsFaulted, runnerTask.Exception?.ToString());
                    replacedert.True(runnerTask.IsCanceled);

                    _jobDispatcher.Verify(x => x.Run(It.IsAny<Pipelines.AgentJobRequestMessage>(), It.IsAny<bool>()), Times.Once(),
                         $"{nameof(_jobDispatcher.Object.Run)} was not invoked.");
                    _messageListener.Verify(x => x.GetNextMessageAsync(It.IsAny<CancellationToken>()), Times.AtLeastOnce());
                    _messageListener.Verify(x => x.CreateSessionAsync(It.IsAny<CancellationToken>()), Times.Once());
                    _messageListener.Verify(x => x.DeleteSessionAsync(), Times.Once());
                    _messageListener.Verify(x => x.DeleteMessageAsync(It.IsAny<TaskAgentMessage>()), Times.AtLeastOnce());

                    // verify that we didn't try to delete local settings file (since we're not ephemeral)
                    _configurationManager.Verify(x => x.DeleteLocalRunnerConfig(), Times.Never());
                }
            }
        }

19 Source : RunnerL0.cs
with MIT License
from actions

[Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Runner")]
        public async void TestRunOnceOnlyTakeOneJobMessage()
        {
            using (var hc = new TestHostContext(this))
            {
                //Arrange
                var runner = new Runner.Listener.Runner();
                hc.SetSingleton<IConfigurationManager>(_configurationManager.Object);
                hc.SetSingleton<IJobNotification>(_jobNotification.Object);
                hc.SetSingleton<IMessageListener>(_messageListener.Object);
                hc.SetSingleton<IPromptManager>(_promptManager.Object);
                hc.SetSingleton<IRunnerServer>(_runnerServer.Object);
                hc.SetSingleton<IConfigurationStore>(_configStore.Object);
                runner.Initialize(hc);
                var settings = new RunnerSettings
                {
                    PoolId = 43242,
                    Ephemeral = true
                };

                var message1 = new TaskAgentMessage()
                {
                    Body = JsonUtility.ToString(CreateJobRequestMessage("job1")),
                    MessageId = 4234,
                    MessageType = JobRequestMessageTypes.PipelineAgentJobRequest
                };
                var message2 = new TaskAgentMessage()
                {
                    Body = JsonUtility.ToString(CreateJobRequestMessage("job1")),
                    MessageId = 4235,
                    MessageType = JobRequestMessageTypes.PipelineAgentJobRequest
                };

                var messages = new Queue<TaskAgentMessage>();
                messages.Enqueue(message1);
                messages.Enqueue(message2);
                _configurationManager.Setup(x => x.LoadSettings())
                    .Returns(settings);
                _configurationManager.Setup(x => x.IsConfigured())
                    .Returns(true);
                _messageListener.Setup(x => x.CreateSessionAsync(It.IsAny<CancellationToken>()))
                    .Returns(Task.FromResult<bool>(true));
                _messageListener.Setup(x => x.GetNextMessageAsync(It.IsAny<CancellationToken>()))
                    .Returns(async () =>
                        {
                            if (0 == messages.Count)
                            {
                                await Task.Delay(2000);
                            }

                            return messages.Dequeue();
                        });
                _messageListener.Setup(x => x.DeleteSessionAsync())
                    .Returns(Task.CompletedTask);
                _messageListener.Setup(x => x.DeleteMessageAsync(It.IsAny<TaskAgentMessage>()))
                    .Returns(Task.CompletedTask);

                var runOnceJobCompleted = new TaskCompletionSource<bool>();
                _jobDispatcher.Setup(x => x.RunOnceJobCompleted)
                    .Returns(runOnceJobCompleted);
                _jobDispatcher.Setup(x => x.Run(It.IsAny<Pipelines.AgentJobRequestMessage>(), It.IsAny<bool>()))
                    .Callback(() =>
                    {
                        runOnceJobCompleted.TrySetResult(true);
                    });
                _jobNotification.Setup(x => x.StartClient(It.IsAny<String>()))
                    .Callback(() =>
                    {

                    });

                hc.EnqueueInstance<IJobDispatcher>(_jobDispatcher.Object);

                _configStore.Setup(x => x.IsServiceConfigured()).Returns(false);
                //Act
                var command = new CommandSettings(hc, new string[] { "run" });
                Task<int> runnerTask = runner.ExecuteCommand(command);

                //replacedert
                //wait for the runner to run one job and exit
                await Task.WhenAny(runnerTask, Task.Delay(30000));

                replacedert.True(runnerTask.IsCompleted, $"{nameof(runner.ExecuteCommand)} timed out.");
                replacedert.True(!runnerTask.IsFaulted, runnerTask.Exception?.ToString());
                replacedert.True(runnerTask.Result == Constants.Runner.ReturnCode.Success);

                _jobDispatcher.Verify(x => x.Run(It.IsAny<Pipelines.AgentJobRequestMessage>(), true), Times.Once(),
                     $"{nameof(_jobDispatcher.Object.Run)} was not invoked.");
                _messageListener.Verify(x => x.GetNextMessageAsync(It.IsAny<CancellationToken>()), Times.AtLeastOnce());
                _messageListener.Verify(x => x.CreateSessionAsync(It.IsAny<CancellationToken>()), Times.Once());
                _messageListener.Verify(x => x.DeleteSessionAsync(), Times.Once());
                _messageListener.Verify(x => x.DeleteMessageAsync(It.IsAny<TaskAgentMessage>()), Times.Once());
            }
        }

19 Source : RunnerL0.cs
with MIT License
from actions

[Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Runner")]
        public async void TestRunOnceHandleUpdateMessage()
        {
            using (var hc = new TestHostContext(this))
            {
                //Arrange
                var runner = new Runner.Listener.Runner();
                hc.SetSingleton<IConfigurationManager>(_configurationManager.Object);
                hc.SetSingleton<IJobNotification>(_jobNotification.Object);
                hc.SetSingleton<IMessageListener>(_messageListener.Object);
                hc.SetSingleton<IPromptManager>(_promptManager.Object);
                hc.SetSingleton<IRunnerServer>(_runnerServer.Object);
                hc.SetSingleton<IConfigurationStore>(_configStore.Object);
                hc.SetSingleton<ISelfUpdater>(_updater.Object);

                runner.Initialize(hc);
                var settings = new RunnerSettings
                {
                    PoolId = 43242,
                    AgentId = 5678,
                    Ephemeral = true
                };

                var message1 = new TaskAgentMessage()
                {
                    Body = JsonUtility.ToString(new AgentRefreshMessage(settings.AgentId, "2.123.0")),
                    MessageId = 4234,
                    MessageType = AgentRefreshMessage.MessageType
                };

                var messages = new Queue<TaskAgentMessage>();
                messages.Enqueue(message1);
                _updater.Setup(x => x.SelfUpdate(It.IsAny<AgentRefreshMessage>(), It.IsAny<IJobDispatcher>(), It.IsAny<bool>(), It.IsAny<CancellationToken>()))
                        .Returns(Task.FromResult(true));
                _configurationManager.Setup(x => x.LoadSettings())
                    .Returns(settings);
                _configurationManager.Setup(x => x.IsConfigured())
                    .Returns(true);
                _messageListener.Setup(x => x.CreateSessionAsync(It.IsAny<CancellationToken>()))
                    .Returns(Task.FromResult<bool>(true));
                _messageListener.Setup(x => x.GetNextMessageAsync(It.IsAny<CancellationToken>()))
                    .Returns(async () =>
                        {
                            if (0 == messages.Count)
                            {
                                await Task.Delay(2000);
                            }

                            return messages.Dequeue();
                        });
                _messageListener.Setup(x => x.DeleteSessionAsync())
                    .Returns(Task.CompletedTask);
                _messageListener.Setup(x => x.DeleteMessageAsync(It.IsAny<TaskAgentMessage>()))
                    .Returns(Task.CompletedTask);
                _jobNotification.Setup(x => x.StartClient(It.IsAny<String>()))
                    .Callback(() =>
                    {

                    });

                hc.EnqueueInstance<IJobDispatcher>(_jobDispatcher.Object);

                _configStore.Setup(x => x.IsServiceConfigured()).Returns(false);
                //Act
                var command = new CommandSettings(hc, new string[] { "run" });
                Task<int> runnerTask = runner.ExecuteCommand(command);

                //replacedert
                //wait for the runner to exit with right return code
                await Task.WhenAny(runnerTask, Task.Delay(30000));

                replacedert.True(runnerTask.IsCompleted, $"{nameof(runner.ExecuteCommand)} timed out.");
                replacedert.True(!runnerTask.IsFaulted, runnerTask.Exception?.ToString());
                replacedert.True(runnerTask.Result == Constants.Runner.ReturnCode.RunOnceRunnerUpdating);

                _updater.Verify(x => x.SelfUpdate(It.IsAny<AgentRefreshMessage>(), It.IsAny<IJobDispatcher>(), false, It.IsAny<CancellationToken>()), Times.Once);
                _jobDispatcher.Verify(x => x.Run(It.IsAny<Pipelines.AgentJobRequestMessage>(), true), Times.Never());
                _messageListener.Verify(x => x.GetNextMessageAsync(It.IsAny<CancellationToken>()), Times.AtLeastOnce());
                _messageListener.Verify(x => x.CreateSessionAsync(It.IsAny<CancellationToken>()), Times.Once());
                _messageListener.Verify(x => x.DeleteSessionAsync(), Times.Once());
                _messageListener.Verify(x => x.DeleteMessageAsync(It.IsAny<TaskAgentMessage>()), Times.Once());
            }
        }

19 Source : MessageListenerL0.cs
with MIT License
from actions

[Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Runner")]
        public async void GetNextMessage()
        {
            using (TestHostContext tc = CreateTestContext())
            using (var tokenSource = new CancellationTokenSource())
            {
                Tracing trace = tc.GetTrace();

                // Arrange.
                var expectedSession = new TaskAgentSession();
                PropertyInfo sessionIdProperty = expectedSession.GetType().GetProperty("SessionId", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
                replacedert.NotNull(sessionIdProperty);
                sessionIdProperty.SetValue(expectedSession, Guid.NewGuid());

                _runnerServer
                    .Setup(x => x.CreateAgentSessionAsync(
                        _settings.PoolId,
                        It.Is<TaskAgentSession>(y => y != null),
                        tokenSource.Token))
                    .Returns(Task.FromResult(expectedSession));

                _credMgr.Setup(x => x.LoadCredentials()).Returns(new VssCredentials());
                _store.Setup(x => x.GetCredentials()).Returns(new CredentialData() { Scheme = Constants.Configuration.OAuthAccessToken });
                _store.Setup(x => x.GetMigratedCredentials()).Returns(default(CredentialData));

                // Act.
                MessageListener listener = new MessageListener();
                listener.Initialize(tc);

                bool result = await listener.CreateSessionAsync(tokenSource.Token);
                replacedert.True(result);

                var arMessages = new TaskAgentMessage[]
                {
                        new TaskAgentMessage
                        {
                            Body = "somebody1",
                            MessageId = 4234,
                            MessageType = JobRequestMessageTypes.PipelineAgentJobRequest
                        },
                        new TaskAgentMessage
                        {
                            Body = "somebody2",
                            MessageId = 4235,
                            MessageType = JobCancelMessage.MessageType
                        },
                        null,  //should be skipped by GetNextMessageAsync implementation
                        null,
                        new TaskAgentMessage
                        {
                            Body = "somebody3",
                            MessageId = 4236,
                            MessageType = JobRequestMessageTypes.PipelineAgentJobRequest
                        }
                };
                var messages = new Queue<TaskAgentMessage>(arMessages);

                _runnerServer
                    .Setup(x => x.GetAgentMessageAsync(
                        _settings.PoolId, expectedSession.SessionId, It.IsAny<long?>(), tokenSource.Token))
                    .Returns(async (Int32 poolId, Guid sessionId, Int64? lastMessageId, CancellationToken cancellationToken) =>
                    {
                        await Task.Yield();
                        return messages.Dequeue();
                    });
                TaskAgentMessage message1 = await listener.GetNextMessageAsync(tokenSource.Token);
                TaskAgentMessage message2 = await listener.GetNextMessageAsync(tokenSource.Token);
                TaskAgentMessage message3 = await listener.GetNextMessageAsync(tokenSource.Token);
                replacedert.Equal(arMessages[0], message1);
                replacedert.Equal(arMessages[1], message2);
                replacedert.Equal(arMessages[4], message3);

                //replacedert
                _runnerServer
                    .Verify(x => x.GetAgentMessageAsync(
                        _settings.PoolId, expectedSession.SessionId, It.IsAny<long?>(), tokenSource.Token), Times.Exactly(arMessages.Length));
            }
        }

19 Source : RunnerL0.cs
with MIT License
from actions

[Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Runner")]
        public async void TestRunOnce()
        {
            using (var hc = new TestHostContext(this))
            {
                //Arrange
                var runner = new Runner.Listener.Runner();
                hc.SetSingleton<IConfigurationManager>(_configurationManager.Object);
                hc.SetSingleton<IJobNotification>(_jobNotification.Object);
                hc.SetSingleton<IMessageListener>(_messageListener.Object);
                hc.SetSingleton<IPromptManager>(_promptManager.Object);
                hc.SetSingleton<IRunnerServer>(_runnerServer.Object);
                hc.SetSingleton<IConfigurationStore>(_configStore.Object);
                runner.Initialize(hc);
                var settings = new RunnerSettings
                {
                    PoolId = 43242,
                    Ephemeral = true
                };

                var message = new TaskAgentMessage()
                {
                    Body = JsonUtility.ToString(CreateJobRequestMessage("job1")),
                    MessageId = 4234,
                    MessageType = JobRequestMessageTypes.PipelineAgentJobRequest
                };

                var messages = new Queue<TaskAgentMessage>();
                messages.Enqueue(message);
                _configurationManager.Setup(x => x.LoadSettings())
                    .Returns(settings);
                _configurationManager.Setup(x => x.IsConfigured())
                    .Returns(true);
                _messageListener.Setup(x => x.CreateSessionAsync(It.IsAny<CancellationToken>()))
                    .Returns(Task.FromResult<bool>(true));
                _messageListener.Setup(x => x.GetNextMessageAsync(It.IsAny<CancellationToken>()))
                    .Returns(async () =>
                        {
                            if (0 == messages.Count)
                            {
                                await Task.Delay(2000);
                            }

                            return messages.Dequeue();
                        });
                _messageListener.Setup(x => x.DeleteSessionAsync())
                    .Returns(Task.CompletedTask);
                _messageListener.Setup(x => x.DeleteMessageAsync(It.IsAny<TaskAgentMessage>()))
                    .Returns(Task.CompletedTask);

                var runOnceJobCompleted = new TaskCompletionSource<bool>();
                _jobDispatcher.Setup(x => x.RunOnceJobCompleted)
                    .Returns(runOnceJobCompleted);
                _jobDispatcher.Setup(x => x.Run(It.IsAny<Pipelines.AgentJobRequestMessage>(), It.IsAny<bool>()))
                    .Callback(() =>
                    {
                        runOnceJobCompleted.TrySetResult(true);
                    });
                _jobNotification.Setup(x => x.StartClient(It.IsAny<String>()))
                    .Callback(() =>
                    {

                    });

                hc.EnqueueInstance<IJobDispatcher>(_jobDispatcher.Object);

                _configStore.Setup(x => x.IsServiceConfigured()).Returns(false);
                //Act
                var command = new CommandSettings(hc, new string[] { "run" });
                Task<int> runnerTask = runner.ExecuteCommand(command);

                //replacedert
                //wait for the runner to run one job and exit
                await Task.WhenAny(runnerTask, Task.Delay(30000));

                replacedert.True(runnerTask.IsCompleted, $"{nameof(runner.ExecuteCommand)} timed out.");
                replacedert.True(!runnerTask.IsFaulted, runnerTask.Exception?.ToString());
                replacedert.True(runnerTask.Result == Constants.Runner.ReturnCode.Success);

                _jobDispatcher.Verify(x => x.Run(It.IsAny<Pipelines.AgentJobRequestMessage>(), true), Times.Once(),
                     $"{nameof(_jobDispatcher.Object.Run)} was not invoked.");
                _messageListener.Verify(x => x.GetNextMessageAsync(It.IsAny<CancellationToken>()), Times.AtLeastOnce());
                _messageListener.Verify(x => x.CreateSessionAsync(It.IsAny<CancellationToken>()), Times.Once());
                _messageListener.Verify(x => x.DeleteSessionAsync(), Times.Once());
                _messageListener.Verify(x => x.DeleteMessageAsync(It.IsAny<TaskAgentMessage>()), Times.AtLeastOnce());

                // verify that we did try to delete local settings file (since we're ephemeral)
                _configurationManager.Verify(x => x.DeleteLocalRunnerConfig(), Times.Once());
            }
        }

19 Source : WorkerL0.cs
with MIT License
from actions

[Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Worker")]
        public async void DispatchRunNewJob()
        {
            //Arrange
            using (var hc = new TestHostContext(this))
            using (var tokenSource = new CancellationTokenSource())
            {
                var worker = new GitHub.Runner.Worker.Worker();
                hc.EnqueueInstance<IProcessChannel>(_processChannel.Object);
                hc.EnqueueInstance<IJobRunner>(_jobRunner.Object);
                worker.Initialize(hc);
                var jobMessage = CreateJobRequestMessage("job1");
                var arWorkerMessages = new WorkerMessage[]
                    {
                        new WorkerMessage
                        {
                            Body = JsonUtility.ToString(jobMessage),
                            MessageType = MessageType.NewJobRequest
                        }
                    };
                var workerMessages = new Queue<WorkerMessage>(arWorkerMessages);

                _processChannel
                    .Setup(x => x.ReceiveAsync(It.IsAny<CancellationToken>()))
                    .Returns(async () =>
                    {
                        // Return the job message.
                        if (workerMessages.Count > 0)
                        {
                            return workerMessages.Dequeue();
                        }

                        // Wait for the text to run
                        await Task.Delay(-1, tokenSource.Token);
                        return default(WorkerMessage);
                    });
                _jobRunner.Setup(x => x.RunAsync(It.IsAny<Pipelines.AgentJobRequestMessage>(), It.IsAny<CancellationToken>()))
                    .Returns(Task.FromResult<TaskResult>(TaskResult.Succeeded));

                //Act
                await worker.RunAsync(pipeIn: "1", pipeOut: "2");

                //replacedert
                _processChannel.Verify(x => x.StartClient("1", "2"), Times.Once());
                _jobRunner.Verify(x => x.RunAsync(
                    It.Is<Pipelines.AgentJobRequestMessage>(y => IsMessageIdentical(y, jobMessage)), It.IsAny<CancellationToken>()));
                tokenSource.Cancel();
            }
        }

19 Source : WorkerL0.cs
with MIT License
from actions

[Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Worker")]
        public async void DispatchCancellation()
        {
            //Arrange
            using (var hc = new TestHostContext(this))
            {
                var worker = new GitHub.Runner.Worker.Worker();
                hc.EnqueueInstance<IProcessChannel>(_processChannel.Object);
                hc.EnqueueInstance<IJobRunner>(_jobRunner.Object);
                worker.Initialize(hc);
                var jobMessage = CreateJobRequestMessage("job1");
                var cancelMessage = CreateJobCancelMessage(jobMessage.JobId);
                var arWorkerMessages = new WorkerMessage[]
                    {
                        new WorkerMessage
                        {
                            Body = JsonUtility.ToString(jobMessage),
                            MessageType = MessageType.NewJobRequest
                        },
                        new WorkerMessage
                        {
                            Body = JsonUtility.ToString(cancelMessage),
                            MessageType = MessageType.CancelRequest
                        }

                    };
                var workerMessages = new Queue<WorkerMessage>(arWorkerMessages);

                _processChannel.Setup(x => x.ReceiveAsync(It.IsAny<CancellationToken>()))
                    .Returns(() => Task.FromResult(workerMessages.Dequeue()));
                _jobRunner.Setup(x => x.RunAsync(It.IsAny<Pipelines.AgentJobRequestMessage>(), It.IsAny<CancellationToken>()))
                    .Returns(
                    async (Pipelines.AgentJobRequestMessage jm, CancellationToken ct) =>
                    {
                        await Task.Delay(-1, ct);
                        return TaskResult.Canceled;
                    });

                //Act
                await replacedert.ThrowsAsync<TaskCanceledException>(
                    async () => await worker.RunAsync("1", "2"));

                //replacedert
                _processChannel.Verify(x => x.StartClient("1", "2"), Times.Once());
                _jobRunner.Verify(x => x.RunAsync(
                    It.Is<Pipelines.AgentJobRequestMessage>(y => IsMessageIdentical(y, jobMessage)), It.IsAny<CancellationToken>()));
            }
        }

19 Source : ITypeSymbolExtensions.cs
with GNU General Public License v3.0
from Acumatica

private static IEnumerable<INamedTypeSymbol> GetFlattenedNestedTypesImplementation(this ITypeSymbol type, 
																						   Func<ITypeSymbol, bool> shouldWalkThroughNestedTypesPredicate,
																						   CancellationToken cancellationToken)
		{
			var nestedTypes = type.GetTypeMembers();

			if (nestedTypes.IsDefaultOrEmpty)
				yield break;

			var typesQueue = new Queue<INamedTypeSymbol>(nestedTypes);

			while (typesQueue.Count > 0)
			{
				cancellationToken.ThrowIfCancellationRequested();
				var currentType = typesQueue.Dequeue();
				bool shouldWalkThroughChildNestedTypes = shouldWalkThroughNestedTypesPredicate?.Invoke(currentType) ?? true;

				if (shouldWalkThroughChildNestedTypes)
				{
					var declaredNestedTypes = currentType.GetTypeMembers();

					if (!declaredNestedTypes.IsDefaultOrEmpty)
					{
						foreach (var nestedType in declaredNestedTypes)
						{
							typesQueue.Enqueue(nestedType);
						}
					}
				}

				yield return currentType;
			}
		}

19 Source : EditorExtensions.cs
with GNU General Public License v3.0
from Acumatica

public static IEnumerable<ITextBuffer> GetSourceBuffersRecursive(this IProjectionBuffer projectionBuffer)
        {
            var toVisit = new Queue<IProjectionBuffer>();
            toVisit.Enqueue(projectionBuffer);

            var found = new HashSet<ITextBuffer>();

            while (toVisit.Count > 0)
            {
                IProjectionBuffer current = toVisit.Dequeue();

                if (found.Contains(current))
                {
                    continue;
                }

                found.Add(current);

                foreach (ITextBuffer sourceBuffer in current.SourceBuffers)
                {
                    var sourceProjection = sourceBuffer as IProjectionBuffer;

                    if (sourceProjection != null)
                    {
                        toVisit.Enqueue(sourceProjection);
                    }
                    else
                    {
                        found.Add(sourceBuffer);
                    }
                }
            }

            return found.Where(x => !(x is IProjectionBuffer));
        }

19 Source : NavigationProxy.cs
with MIT License
from adamped

private void _page_Popped(object sender, NavigationEventArgs e)
        {
            if (OnPopped != null)
            {
                var poppedPage = e.Page as IView;
				var currentPage = _page.CurrentPage as IView;
                var parameter = _argQueue.Count > 0 ? _argQueue.Dequeue() : null;
                OnPopped(this, new ViewNavigationArgs() { Parameter = parameter, CurrentView = currentPage, PoppedView = poppedPage });
            }
        }

19 Source : AdColony.cs
with Apache License 2.0
from AdColony

void Update()
        {
            if (_updateOnMainThreadActions.Count > 0)
            {
                System.Action action;
                do
                {
                    action = null;
                    lock (_updateOnMainThreadActionsLock)
                    {
                        if (_updateOnMainThreadActions.Count > 0)
                        {
                            action = _updateOnMainThreadActions.Dequeue();
                        }
                    }
                    if (action != null)
                    {
                        action.Invoke();
                    }
                } while (action != null);
            }
        }

19 Source : MethodHelpers.cs
with MIT License
from ADeltaX

public static IEnumerable<T> SkipLast<T>(this IEnumerable<T> source, int count)
        {
            var e = source.GetEnumerator();
            var cache = new Queue<T>(count + 1);

            using (e = source.GetEnumerator())
            {
                bool hasRemainingItems;
                do
                {
                    if (hasRemainingItems = e.MoveNext())
                    {
                        cache.Enqueue(e.Current);
                        if (cache.Count > count)
                            yield return cache.Dequeue();
                    }
                } while (hasRemainingItems);
            }
        }

19 Source : CmsIndexHelper.cs
with MIT License
from Adoxio

private static IEnumerable<Guid> SelectAllDescendantWebpagesWithPredicates(Guid enreplacedyId, ContentMap contentMap, IEnumerable<Predicate<WebPageNode>> predicates)
		{
			EnreplacedyNode enreplacedy;
			if (!contentMap.TryGetValue(new EnreplacedyReference("adx_webpage", enreplacedyId), out enreplacedy))
			{
				return Enumerable.Empty<Guid>();
			}

			var rootWebpage = enreplacedy as WebPageNode;
			if (rootWebpage == null)
			{
				return Enumerable.Empty<Guid>();
			}

			// if it's a content page, we want to start at it's root page so we can navigate down the web page hierarchy
			if (rootWebpage.IsRoot == false)
			{
				if (rootWebpage.RootWebPage == null)
				{
					// just return this web page, can't reach any others
					return new List<Guid>() { rootWebpage.Id };
				}

				rootWebpage = rootWebpage.RootWebPage;
			}

			var unprocessedNodes = new Queue<WebPageNode>();
			var webPageGuids = new List<Guid>();
			
			unprocessedNodes.Enqueue(rootWebpage);
			while (unprocessedNodes.Count > 0)
			{
				WebPageNode currWebPage = unprocessedNodes.Dequeue();

				foreach (var childWebPage in currWebPage.WebPages)
				{
					unprocessedNodes.Enqueue(childWebPage);
				}

				if (currWebPage.LanguageContentPages != null)
				{
					foreach (var contentPage in currWebPage.LanguageContentPages)
					{
						unprocessedNodes.Enqueue(contentPage);
					}
				}

				if (predicates.All(predicate => predicate(currWebPage)))
				{
					webPageGuids.Add(currWebPage.Id);
				}
			}

			return webPageGuids;
		}

19 Source : BrowserWebRtcNetwork.cs
with MIT License
from adrenak

public bool Dequeue(out NetworkEvent evt)
        {
            evt = new NetworkEvent();
            if (mEvents.Count == 0)
                return false;

            evt = mEvents.Dequeue();
            return true;
        }

19 Source : Agent.cs
with MIT License
from adrenak

void CreatePerformState() {
            mPerformState = (pFSM, pGameObject) => {
                Action _action = mPlan.Peek();

                if (_action.IsDone()) {
                    mActor.OnActionFinished(_action);
                    mPlan.Dequeue();

                    if (!HasActionPlan()) {
                        mStateMachine.PopAndPush(mIdleState);
                        mActor.OnActionsFinished();
                        return;
                    }
                }

                _action = mPlan.Peek();
                bool inRange = _action.IsRanged() ? _action.IsInRange() : true;

                if (inRange) {
                    bool success = _action.Perform(gameObject);

                    if (!success) {
                        mStateMachine.PopAndPush(mIdleState);
                        mActor.OnActionFailed(_action);
                    }
                }
                else 
                    mStateMachine.PushState(mMovingState);
            };
        }

19 Source : Dispatcher.cs
with MIT License
from adrenak

void Update() {
			lock (m_Queue) {
				while (m_Queue.Count > 0)
					m_Queue.Dequeue()();
			}
		}

19 Source : ObjectPool.cs
with Apache License 2.0
from advancer68

public virtual T Get()
        {
            var it = getQue.Dequeue();
            if (it == null)
            {
                if (m_createNew == null)
                {
                    it = new T();
                }
                else
                {
                    it = m_createNew();
                }
            }
            return it;
        }

19 Source : QueueSync.cs
with Apache License 2.0
from advancer68

private T DequeueUnsafe()
    {
        return outQue.Dequeue();
    }

19 Source : QueueSync.cs
with Apache License 2.0
from advancer68

public void DequeueAll(Action<T> func)
    {
        if (func == null)
        {
            return;
        }
        Switch();
        while (outQue.Count > 0)
        {
            T it = outQue.Dequeue();
            func(it);
        }
    }

19 Source : ModEntry.cs
with GNU General Public License v3.0
from aedenthorn

private static bool recursiveTryToCreateLadderDown(MineShaft location, Vector2 centerTile, string sound, int maxIterations)
        {

            int iterations = 0;
            Queue<Vector2> positionsToCheck = new Queue<Vector2>();
            positionsToCheck.Enqueue(centerTile);
            List<Vector2> closedList = new List<Vector2>();
            while (iterations < maxIterations && positionsToCheck.Count > 0)
            {
                Vector2 currentPoint = positionsToCheck.Dequeue();
                closedList.Add(currentPoint);
                if (!location.isTileOccupied(currentPoint, "ignoreMe", false) && location.isTileOnClearAndSolidGround(currentPoint) && location.isTileOccupiedByFarmer(currentPoint) == null && location.doesTileHaveProperty((int)currentPoint.X, (int)currentPoint.Y, "Type", "Back") != null && location.doesTileHaveProperty((int)currentPoint.X, (int)currentPoint.Y, "Type", "Back").Equals("Stone"))
                {
                    location.playSound("hoeHit", NetAudio.SoundContext.Default);
                    location.createLadderDown((int)currentPoint.X, (int)currentPoint.Y, true);
                    return true;
                }
                foreach (Vector2 v in Utility.DirectionsTileVectors)
                {
                    if (!closedList.Contains(currentPoint + v))
                    {
                        positionsToCheck.Enqueue(currentPoint + v);
                    }
                }
                iterations++;
            }

            return false;
        }

19 Source : SyncList.cs
with GNU General Public License v3.0
from aelariane

public void Unlock()
        {
            lock (syncer)
            {
                Locked = false;
                lock (actionQueue)
                {
                    while (actionQueue.Count > 0)
                    {
                        actionQueue.Dequeue().Invoke();
                    }
                }
            }
        }

19 Source : EventOSR.cs
with GNU General Public License v3.0
from aelariane

public bool Handle()
        {
            int count = hashData.Count;
            for (int i = 0; i < count; i++)
            {
                PhotonView view = PhotonView.Find(hashViews.Dequeue());
                if (view == null)
                {
                    //Message what view ID not exists
                    //Maybe put spam for invalid viewIDs, like 100 per second, idk
                    return true;
                }
                else if (view.prefix > 0 && correctPrefix != view.prefix)
                {
                    Debug.LogError(string.Concat(new object[] { "Received OnSerialization for view ID ", view.viewID, " with prefix ", correctPrefix, ". Our prefix is ", view.prefix }));
                }
                if (view.observed == null)
                {
                    myReason = $"OSR: Null observed for ViewID[{view.viewID.ToString()}]";
                    return false;
                }
                if (view.observed is MonoBehaviour)
                {
                    PhotonStream pStream = new PhotonStream(false, hashData.Dequeue());
                    PhotonMessageInfo info = new PhotonMessageInfo(sender, sentTime, view);
                    view.ExecuteOnSerialize(pStream, info);
                }
                else if (view.observed is Transform)
                {
                    Transform tf = (Transform)view.observed;
                    object[] arr = hashData.Dequeue();
                    switch (arr.Length)
                    {
                        case 1:
                            {
                                if (arr[0] == null || !(arr[0] is Vector3 vec))
                                {
                                    myReason = "OSR: Null or Invalid value inside data";
                                    return false;
                                }
                                tf.localPosition = vec;
                            }
                            break;

                        case 2:
                            {
                                if (arr[0] == null || !(arr[0] is Vector3 vec))
                                {
                                    myReason = "OSR: Null or Invalid value inside data";
                                    return false;
                                }
                                if (arr[1] == null || !(arr[1] is Quaternion quat))
                                {
                                    myReason = "OSR: Null or Invalid value inside data";
                                    return false;
                                }
                                tf.localPosition = vec;
                                tf.localRotation = quat;
                                break;
                            }

                        case 3:
                        case 4:
                            {
                                if (arr[0] == null || !(arr[0] is Vector3 vec))
                                {
                                    myReason = "OSR: Null or Invalid value inside data";
                                    return false;
                                }
                                if (arr[1] == null || !(arr[1] is Quaternion quat))
                                {
                                    myReason = "OSR: Null or Invalid value inside data";
                                    return false;
                                }
                                if (arr[2] == null || !(arr[2] is Vector3 vec1))
                                {
                                    myReason = "OSR: Null or Invalid value inside data";
                                    return false;
                                }
                                tf.localPosition = vec;
                                tf.localRotation = quat;
                                tf.localScale = vec1;
                                break;
                            }

                        default:
                            myReason = $"OSR:Invalid data length(Tf)" + arr.Length.ToString();
                            return false;
                    }
                }
                else if (view.observed is Rigidbody)
                {
                    Rigidbody rb = (Rigidbody)view.observed;
                    object[] arr = hashData.Dequeue();
                    switch (arr.Length)
                    {
                        case 1:
                            {
                                if (arr[0] == null || !(arr[0] is Vector3 vec))
                                {
                                    myReason = "OSR: Null or Invalid value inside data";
                                    return false;
                                }
                                rb.velocity = vec;
                                break;
                            }

                        case 2:
                            {
                                if (arr[0] == null || !(arr[0] is Vector3 vec))
                                {
                                    myReason = "OSR: Null or Invalid value inside data";
                                    return false;
                                }
                                if (arr[1] == null || !(arr[1] is Vector3 loc))
                                {
                                    myReason = "OSR: Null or Invalid value inside data";
                                    return false;
                                }
                                rb.velocity = vec;
                                rb.angularVelocity = loc;
                                break;
                            }

                        default:
                            myReason = "OSR:Invalid data length(Rb) " + arr.Length.ToString();
                            return false;
                    }
                }
                else
                {
                    //Log.Spam($"Recieved unknown observed type by [{sender.ID.ToString()}]", "UnkOSR", sender.ID);
                    hashData.Dequeue();
                }
            }
            return true;
        }

19 Source : SyncDictionary.cs
with GNU General Public License v3.0
from aelariane

public void Unlock()
        {
            lock (syncer)
            {
                Locked = false;
                lock (actionsQueue)
                {
                    while (actionsQueue.Count > 0)
                    {
                        actionsQueue.Dequeue().Invoke();
                    }
                }
            }
        }

19 Source : FengGameManagerMKII.cs
with GNU General Public License v3.0
from aelariane

public void KillInfoUpdate()
    {
        if (killInfoList.Count > 0 && killInfoList.Peek() == null)
        {
            killInfoList.Dequeue();
        }
    }

19 Source : Client.cs
with Apache License 2.0
from aequabit

private void HandleSendQueue()
    {
        try
        {
            if (SendIndex >= SendBuffer.Length)
            {
                SendIndex = 0;
                SendBuffer = Header(SendQueue.Dequeue());
            }

            int Write = Math.Min(SendBuffer.Length - SendIndex, _BufferSize);
            Items[1].SetBuffer(SendBuffer, SendIndex, Write);

            if (!Handle.SendAsync(Items[1]))
            {
                Process(null, Items[1]);
            }
        }
        catch (Exception ex)
        {
            O.Post(x => OnExceptionThrown((Exception)x), ex);
            Disconnect();
        }
    }

19 Source : Server.cs
with Apache License 2.0
from aequabit

private void HandleSendQueue()
    {
        try
        {
            if (SendIndex >= SendBuffer.Length)
            {
                SendIndex = 0;
                SendBuffer = Header(SendQueue.Dequeue());
            }

            int Write = Math.Min(SendBuffer.Length - SendIndex, _BufferSize);
            Items[1].SetBuffer(SendBuffer, SendIndex, Write);

            if (!Handle.SendAsync(Items[1]))
            {
                Process(null, Items[1]);
            }
        }
        catch (Exception ex)
        {
            OnExceptionThrown(ex);
            Disconnect();
        }
    }

19 Source : ActiveSet.cs
with The Unlicense
from aeroson

void DistributeMreplaced(List<Control> controls)
        {
            //We replacedume that all stressed paths have already been marked with nonzero StressCounts.
            //Perform a multi-origin breadth-first search starting at every control. Look for any bones
            //which still have a StressCount of zero.

            //These zero-StressCount bones are the beginnings of isolated 'limbs' in the graph; there is only
            //one bone-to-bone connection (potentially made of multiple constraints, of course, but that does not affect graph connectivity)
            //between the stressed component of the graph and the isolated limb.
            //That means any traversal starting at that first bone and moving out away from the stressed graph will never return to the stressed graph
            //(no bone can be revisited).

            //Because these unstressed limbs are not critical weight-carrying paths, they do not need to be as heavy as the stressed paths.
            //In addition, to make the IK more responsive, unstressed bones further from the stressed component of the graph can be made less mreplacedive.

            //Care must be taken in determining the mreplacedes, though; if the root is light and its children, while individually lighter, are replacedulatively much heavier,
            //there could be mreplaced-ratio related instability.

            //To address this, cycles are found and given equal mreplaced and each noncycle branch splits the current object's mreplaced between all noncycle children.


            //Perform a breadth-first search through the graph starting at the bones targeted by each control.
            foreach (var control in controls)
            {
                bonesToVisit.Enqueue(control.TargetBone);
                //Note that a bone is added to the visited bone set before it is actually processed.
                //This prevents a bone from being put in the queue redundantly.
                control.TargetBone.IsActive = true;
                //A second traversal flag is required for the mreplaced distribution phase on each unstressed part to work efficiently.
                control.TargetBone.traversed = true;
                bones.Add(control.TargetBone);
            }

            //Note that it's technically possible for multiple controls to affect the same bone.
            //The containment tests will stop it from adding in any redundant constraints as a result.
            while (bonesToVisit.Count > 0)
            {
                var bone = bonesToVisit.Dequeue();
                if (bone.stressCount == 0)
                {
                    bone.Mreplaced = automreplacedUnstressedFalloff;
                    //This is an unstressed bone. We should start a DFS to identify any cycles in the unstressed graph.
                    FindCycles(bone);
                    //Once the cycles are marked, we can proceed through the unstressed graph component and give child bones mreplaced.
                    DistributeMreplaced(bone);
                    //Do not continue the breadth-first search into the unstressed part of the graph.
                    continue;
                }
                else
                {
                    //The mreplaced of stressed bones is a multiplier on the number of stressed paths overlapping the bone.
                    bone.Mreplaced = bone.stressCount;
                }
                //This bone is not an unstressed branch root. Continue the breadth first search!
                foreach (var joint in bone.joints)
                {
                    Bone boneToAdd = joint.ConnectionA == bone ? joint.ConnectionB : joint.ConnectionA;
                    if (!boneToAdd.Pinned && //Pinned bones act as dead ends! Don't try to traverse them.
                        !boneToAdd.IsActive) //Don't try to add a bone if it's already active.
                    {
                        boneToAdd.IsActive = true;
                        //A second traversal flag is required for the mreplaced distribution phase on each unstressed part to work efficiently.
                        boneToAdd.traversed = true;
                        boneToAdd.predecessors.Add(bone);
                        //The bone was not already present in the active set. We should visit it!
                        //Note that a bone is added to the visited bone set before it is actually processed.
                        //This prevents a bone from being put in the queue redundantly.
                        bonesToVisit.Enqueue(boneToAdd);
                        bones.Add(boneToAdd);
                    }
                }
            }

            //Normalize the mreplacedes of objects so that the heaviest bones have AutomreplacedTarget mreplaced.
            float lowestInverseMreplaced = float.MaxValue;
            foreach (var bone in bones)
            {
                if (bone.inverseMreplaced < lowestInverseMreplaced)
                    lowestInverseMreplaced = bone.inverseMreplaced;
            }

            float inverseMreplacedScale = 1 / (AutomreplacedTarget * lowestInverseMreplaced);

            foreach (var bone in bones)
            {
                //Normalize the mreplaced to the AutomreplacedTarget.
                bone.inverseMreplaced *= inverseMreplacedScale;

                //Also clear the traversal flags while we're at it.
                bone.IsActive = false;
                bone.traversed = false;
                bone.stressCount = 0;
                bone.unstressedCycle = false;
                bone.predecessors.Clear();
            }

            bones.Clear();
        }

19 Source : DetectorVolume.cs
with The Unlicense
from aeroson

void IDeferredEventCreator.DispatchEvents()
        {
            while (containmentChanges.Count > 0)
            {
                var change = containmentChanges.Dequeue();
                switch (change.Change)
                {
                    case ContainmentChangeType.BeganTouching:
                        if (EnreplacedyBeganTouching != null)
                            EnreplacedyBeganTouching(this, change.Enreplacedy);
                        break;
                    case ContainmentChangeType.StoppedTouching:
                        if (EnreplacedyStoppedTouching != null)
                            EnreplacedyStoppedTouching(this, change.Enreplacedy);
                        break;
                    case ContainmentChangeType.BeganContaining:
                        if (VolumeBeganContainingEnreplacedy != null)
                            VolumeBeganContainingEnreplacedy(this, change.Enreplacedy);
                        break;
                    case ContainmentChangeType.StoppedContaining:
                        if (VolumeStoppedContainingEnreplacedy != null)
                            VolumeStoppedContainingEnreplacedy(this, change.Enreplacedy);
                        break;
                }
            }
        }

19 Source : ActiveSet.cs
with The Unlicense
from aeroson

internal void UpdateActiveSet(List<Control> controls)
        {
            //Clear out the previous active set to make way for the new active set.
            //Note that the below flag clearing and usage creates a requirement.
            //Two IKSolvers cannot operate on the same graph; the active set flags could be corrupted.
            Clear();

            if (UseAutomreplaced)
            {
                //Identify the stressed bones.
                FindStressedPaths(controls);

                //Compute the dependency graph for all the unstressed bones and replacedign mreplacedes.
                DistributeMreplaced(controls);
            }

            //While we have traversed the whole active set in the previous stressed/unstressed searches, we do not yet have a proper breadth-first constraint ordering available.

            //Perform a breadth-first search through the graph starting at the bones targeted by each control.
            foreach (var control in controls)
            {
                bonesToVisit.Enqueue(control.TargetBone);
                //Note that a bone is added to the visited bone set before it is actually processed.
                //This prevents a bone from being put in the queue redundantly.
                control.TargetBone.IsActive = true;
                bones.Add(control.TargetBone);
            }

            //Note that it's technically possible for multiple controls to affect the same bone.
            //The containment tests will stop it from adding in any redundant constraints as a result.
            while (bonesToVisit.Count > 0)
            {
                var bone = bonesToVisit.Dequeue();
                foreach (var joint in bone.joints)
                {
                    if (!joint.IsActive)
                    {
                        joint.IsActive = true;
                        //This is the first time the joint has been visited, so plop it into the list.
                        joints.Add(joint);
                    }
                    Bone boneToAdd = joint.ConnectionA == bone ? joint.ConnectionB : joint.ConnectionA;
                    if (!boneToAdd.Pinned && //Pinned bones act as dead ends! Don't try to traverse them.
                        !boneToAdd.IsActive) //Don't try to add a bone if it's already active.
                    {
                        boneToAdd.IsActive = true;
                        //The bone was not already present in the active set. We should visit it!
                        //Note that a bone is added to the visited bone set before it is actually processed.
                        //This prevents a bone from being put in the queue redundantly.
                        bonesToVisit.Enqueue(boneToAdd);
                        bones.Add(boneToAdd);
                    }
                }
            }

        }

19 Source : SimpleLooper.cs
with The Unlicense
from aeroson

private void ShutDownThread()
            {
                //Let the manager know that it is done with its 'task'!
                if (Interlocked.Decrement(ref manager.tasksRemaining) == 0)
                {
                    if (!manager.disposed) //Don't mess with the handle if it's already disposed.
                        manager.allThreadsIdleNotifier.Set();
                }
                //Dump out any remaining tasks in the queue.
                for (int i = 0; i < taskQueue.Count; i++) //This is still safe since shutDownThread is called from within a lock(taskQueue) block.
                {
                    taskQueue.Dequeue();
                    if (Interlocked.Decrement(ref manager.tasksRemaining) == 0)
                    {
                        if (!manager.disposed) //Don't mess with the handle if it's already disposed.
                            manager.allThreadsIdleNotifier.Set();
                    }
                }

                lock (manager.workers)
                    manager.workers.Remove(this);
            }

19 Source : SimpleLooper.cs
with The Unlicense
from aeroson

private void ThreadExecutionLoop()
            {
                //Perform any initialization requested.
                if (threadStart != null)
                    threadStart(initializationInformation);
                object information = null;

                while (true)
                {
                    Action<object> task = null;
                    lock (taskQueue)
                    {
                        if (taskQueue.Count > 0)
                        {
                            task = taskQueue.Dequeue();
                            if (task == null)
                            {
                                Dispose();
                                return;
                            }

                            information = taskInformationQueue.Dequeue();
                        }
                    }
                    if (task != null)
                    {
                        //Perform the task!
                        try
                        {
                            task(information);
                        }
                        catch (ArithmeticException arithmeticException)
                        {
                            throw new ArithmeticException(
                                "Some internal mulreplacedhreaded arithmetic has encountered an invalid state.  Check for invalid enreplacedy momentums, velocities, and positions; propagating NaN's will generally trigger this exception in the getExtremePoint function.",
                                arithmeticException);
                        }
                        if (Interlocked.Decrement(ref manager.tasksRemaining) == 0)
                        {
                            manager.allThreadsIdleNotifier.Set();
                            resetEvent.WaitOne();
                        }
                    }
                    else
                        resetEvent.WaitOne();
                }
            }

See More Examples