System.Collections.Generic.Stack.Peek()

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

1579 Examples 7

19 Source : BssmapAnalysisStack.cs
with MIT License
from 1996v

[MethodImpl(MethodImplOptions.AggressiveInlining)]
        public BssMapRouteToken PeekToken()
        {
            return _tokens.Peek();
        }

19 Source : JsonWriter.cs
with MIT License
from 404Lcc

public void WriteObjectEnd ()
        {
            DoValidation (Condition.InObject);
            PutNewline (false);

            ctx_stack.Pop ();
            if (ctx_stack.Count == 1)
                has_reached_end = true;
            else {
                context = ctx_stack.Peek ();
                context.ExpectingValue = false;
            }

            Unindent ();
            Put ("}");
        }

19 Source : JsonReader.cs
with MIT License
from 404Lcc

public bool Read ()
        {
            if (end_of_input)
                return false;

            if (end_of_json) {
                end_of_json = false;
                automaton_stack.Clear ();
                automaton_stack.Push ((int) ParserToken.End);
                automaton_stack.Push ((int) ParserToken.Text);
            }

            parser_in_string = false;
            parser_return    = false;

            token       = JsonToken.None;
            token_value = null;

            if (! read_started) {
                read_started = true;

                if (! ReadToken ())
                    return false;
            }


            int[] entry_symbols;

            while (true) {
                if (parser_return) {
                    if (automaton_stack.Peek () == (int) ParserToken.End)
                        end_of_json = true;

                    return true;
                }

                current_symbol = automaton_stack.Pop ();

                ProcessSymbol ();

                if (current_symbol == current_input) {
                    if (! ReadToken ()) {
                        if (automaton_stack.Peek () != (int) ParserToken.End)
                            throw new JsonException (
                                "Input doesn't evaluate to proper JSON text");

                        if (parser_return)
                            return true;

                        return false;
                    }

                    continue;
                }

                try {

                    entry_symbols =
                        parse_table[current_symbol][current_input];

                } catch (KeyNotFoundException e) {
                    throw new JsonException ((ParserToken) current_input, e);
                }

                if (entry_symbols[0] == (int) ParserToken.Epsilon)
                    continue;

                for (int i = entry_symbols.Length - 1; i >= 0; i--)
                    automaton_stack.Push (entry_symbols[i]);
            }
        }

19 Source : JsonWriter.cs
with MIT License
from 404Lcc

public void WriteArrayEnd ()
        {
            DoValidation (Condition.InArray);
            PutNewline (false);

            ctx_stack.Pop ();
            if (ctx_stack.Count == 1)
                has_reached_end = true;
            else {
                context = ctx_stack.Peek ();
                context.ExpectingValue = false;
            }

            Unindent ();
            Put ("]");
        }

19 Source : SimpleJSON.cs
with MIT License
from 71

public static JSONNode Parse(string aJSON)
        {
            Stack<JSONNode> stack = new Stack<JSONNode>();
            JSONNode ctx = null;
            int i = 0;
            StringBuilder Token = new StringBuilder();
            string TokenName = "";
            bool QuoteMode = false;
            bool TokenIsQuoted = false;
            while (i < aJSON.Length)
            {
                switch (aJSON[i])
                {
                    case '{':
                        if (QuoteMode)
                        {
                            Token.Append(aJSON[i]);
                            break;
                        }
                        stack.Push(new JSONObject());
                        if (ctx != null)
                        {
                            ctx.Add(TokenName, stack.Peek());
                        }
                        TokenName = "";
                        Token.Length = 0;
                        ctx = stack.Peek();
                        break;

                    case '[':
                        if (QuoteMode)
                        {
                            Token.Append(aJSON[i]);
                            break;
                        }

                        stack.Push(new JSONArray());
                        if (ctx != null)
                        {
                            ctx.Add(TokenName, stack.Peek());
                        }
                        TokenName = "";
                        Token.Length = 0;
                        ctx = stack.Peek();
                        break;

                    case '}':
                    case ']':
                        if (QuoteMode)
                        {

                            Token.Append(aJSON[i]);
                            break;
                        }
                        if (stack.Count == 0)
                            throw new Exception("JSON Parse: Too many closing brackets");

                        stack.Pop();
                        if (Token.Length > 0 || TokenIsQuoted)
                            ctx.Add(TokenName, ParseElement(Token.ToString(), TokenIsQuoted));
                        TokenIsQuoted = false;
                        TokenName = "";
                        Token.Length = 0;
                        if (stack.Count > 0)
                            ctx = stack.Peek();
                        break;

                    case ':':
                        if (QuoteMode)
                        {
                            Token.Append(aJSON[i]);
                            break;
                        }
                        TokenName = Token.ToString();
                        Token.Length = 0;
                        TokenIsQuoted = false;
                        break;

                    case '"':
                        QuoteMode ^= true;
                        TokenIsQuoted |= QuoteMode;
                        break;

                    case ',':
                        if (QuoteMode)
                        {
                            Token.Append(aJSON[i]);
                            break;
                        }
                        if (Token.Length > 0 || TokenIsQuoted)
                            ctx.Add(TokenName, ParseElement(Token.ToString(), TokenIsQuoted));
                        TokenIsQuoted = false;
                        TokenName = "";
                        Token.Length = 0;
                        TokenIsQuoted = false;
                        break;

                    case '\r':
                    case '\n':
                        break;

                    case ' ':
                    case '\t':
                        if (QuoteMode)
                            Token.Append(aJSON[i]);
                        break;

                    case '\\':
                        ++i;
                        if (QuoteMode)
                        {
                            char C = aJSON[i];
                            switch (C)
                            {
                                case 't':
                                    Token.Append('\t');
                                    break;
                                case 'r':
                                    Token.Append('\r');
                                    break;
                                case 'n':
                                    Token.Append('\n');
                                    break;
                                case 'b':
                                    Token.Append('\b');
                                    break;
                                case 'f':
                                    Token.Append('\f');
                                    break;
                                case 'u':
                                    {
                                        string s = aJSON.Substring(i + 1, 4);
                                        Token.Append((char)int.Parse(
                                            s,
                                            System.Globalization.NumberStyles.AllowHexSpecifier));
                                        i += 4;
                                        break;
                                    }
                                default:
                                    Token.Append(C);
                                    break;
                            }
                        }
                        break;

                    default:
                        Token.Append(aJSON[i]);
                        break;
                }
                ++i;
            }
            if (QuoteMode)
            {
                throw new Exception("JSON Parse: Quotation marks seems to be messed up.");
            }
            if (ctx == null)
                return ParseElement(Token.ToString(), TokenIsQuoted);
            return ctx;
        }

19 Source : SimpleJSON.cs
with MIT License
from 734843327

public static JSONNode Parse(string aJSON)
        {
            Stack<JSONNode> stack = new Stack<JSONNode>();
            JSONNode ctx = null;
            int i = 0;
            string Token = "";
            string TokenName = "";
            bool QuoteMode = false;
            while (i < aJSON.Length)
            {
                switch (aJSON[i])
                {
                    case '{':
                        if (QuoteMode)
                        {
                            Token += aJSON[i];
                            break;
                        }
                        stack.Push(new JSONClreplaced());
                        if (ctx != null)
                        {
                            TokenName = TokenName.Trim();
                            if (ctx is JSONArray)
                                ctx.Add(stack.Peek());
                            else if (TokenName != "")
                                ctx.Add(TokenName,stack.Peek());
                        }
                        TokenName = "";
                        Token = "";
                        ctx = stack.Peek();
                    break;

                    case '[':
                        if (QuoteMode)
                        {
                            Token += aJSON[i];
                            break;
                        }

                        stack.Push(new JSONArray());
                        if (ctx != null)
                        {
                            TokenName = TokenName.Trim();
                            if (ctx is JSONArray)
                                ctx.Add(stack.Peek());
                            else if (TokenName != "")
                                ctx.Add(TokenName,stack.Peek());
                        }
                        TokenName = "";
                        Token = "";
                        ctx = stack.Peek();
                    break;

                    case '}':
                    case ']':
                        if (QuoteMode)
                        {
                            Token += aJSON[i];
                            break;
                        }
                        if (stack.Count == 0)
                            throw new Exception("JSON Parse: Too many closing brackets");

                        stack.Pop();
                        if (Token != "")
                        {
                            TokenName = TokenName.Trim();
                            if (ctx is JSONArray)
                                ctx.Add(Token);
                            else if (TokenName != "")
                                ctx.Add(TokenName,Token);
                        }
                        TokenName = "";
                        Token = "";
                        if (stack.Count>0)
                            ctx = stack.Peek();
                    break;

                    case ':':
                        if (QuoteMode)
                        {
                            Token += aJSON[i];
                            break;
                        }
                        TokenName = Token;
                        Token = "";
                    break;

                    case '"':
                        QuoteMode ^= true;
                    break;

                    case ',':
                        if (QuoteMode)
                        {
                            Token += aJSON[i];
                            break;
                        }
                        if (Token != "")
                        {
                            if (ctx is JSONArray)
                                ctx.Add(Token);
                            else if (TokenName != "")
                                ctx.Add(TokenName, Token);
                        }
                        TokenName = "";
                        Token = "";
                    break;

                    case '\r':
                    case '\n':
                    break;

                    case ' ':
                    case '\t':
                        if (QuoteMode)
                            Token += aJSON[i];
                    break;

                    case '\\':
                        ++i;
                        if (QuoteMode)
                        {
                            char C = aJSON[i];
                            switch (C)
                            {
                                case 't' : Token += '\t'; break;
                                case 'r' : Token += '\r'; break;
                                case 'n' : Token += '\n'; break;
                                case 'b' : Token += '\b'; break;
                                case 'f' : Token += '\f'; break;
                                case 'u':
                                {
                                    string s = aJSON.Substring(i+1,4);
                                    Token += (char)int.Parse(s, System.Globalization.NumberStyles.AllowHexSpecifier);
                                    i += 4;
                                    break;
                                }
                                default  : Token += C; break;
                            }
                        }
                    break;

                    default:
                        Token += aJSON[i];
                    break;
                }
                ++i;
            }
            if (QuoteMode)
            {
                throw new Exception("JSON Parse: Quotation marks seems to be messed up.");
            }
            return ctx;
        }

19 Source : MyObjectPool.cs
with Apache License 2.0
from A7ocin

public void Release(T element)
        {
            if (this.m_Stack.Count > 0 && object.ReferenceEquals(this.m_Stack.Peek(), element))
            {
                Debug.LogError("Internal error. Trying to destroy object that is already released to pool.");
            }
            if (this.m_ActionOnRelease != null)
            {
                this.m_ActionOnRelease(element);
            }
            this.m_Stack.Push(element);
        }

19 Source : HighlightedLine.cs
with MIT License
from Abdesol

void Insert(ref int pos, ref int newSectionStart, int insertionEndPos, HighlightingColor color, Stack<int> insertionStack)
		{
			if (newSectionStart >= insertionEndPos) {
				// nothing to insert here
				return;
			}

			while (insertionStack.Peek() <= newSectionStart) {
				insertionStack.Pop();
			}
			while (insertionStack.Peek() < insertionEndPos) {
				int end = insertionStack.Pop();
				// insert the portion from newSectionStart to end
				if (end > newSectionStart) {
					this.Sections.Insert(pos++, new HighlightedSection {
						Offset = newSectionStart,
						Length = end - newSectionStart,
						Color = color
					});
					newSectionStart = end;
				}
			}
			if (insertionEndPos > newSectionStart) {
				this.Sections.Insert(pos++, new HighlightedSection {
					Offset = newSectionStart,
					Length = insertionEndPos - newSectionStart,
					Color = color
				});
				newSectionStart = insertionEndPos;
			}
		}

19 Source : HighlightedLine.cs
with MIT License
from Abdesol

public void MergeWith(HighlightedLine additionalLine)
		{
			if (additionalLine == null)
				return;
#if DEBUG
			ValidateInvariants();
			additionalLine.ValidateInvariants();
#endif

			int pos = 0;
			Stack<int> activeSectionEndOffsets = new Stack<int>();
			int lineEndOffset = this.DoreplacedentLine.EndOffset;
			activeSectionEndOffsets.Push(lineEndOffset);
			foreach (HighlightedSection newSection in additionalLine.Sections) {
				int newSectionStart = newSection.Offset;
				// Track the existing sections using the stack, up to the point where
				// we need to insert the first part of the newSection
				while (pos < this.Sections.Count) {
					HighlightedSection s = this.Sections[pos];
					if (newSection.Offset < s.Offset)
						break;
					while (s.Offset > activeSectionEndOffsets.Peek()) {
						activeSectionEndOffsets.Pop();
					}
					activeSectionEndOffsets.Push(s.Offset + s.Length);
					pos++;
				}
				// Now insert the new section
				// Create a copy of the stack so that we can track the sections we traverse
				// during the insertion process:
				Stack<int> insertionStack = new Stack<int>(activeSectionEndOffsets.Reverse());
				// The stack enumerator reverses the order of the elements, so we call Reverse() to restore
				// the original order.
				int i;
				for (i = pos; i < this.Sections.Count; i++) {
					HighlightedSection s = this.Sections[i];
					if (newSection.Offset + newSection.Length <= s.Offset)
						break;
					// Insert a segment in front of s:
					Insert(ref i, ref newSectionStart, s.Offset, newSection.Color, insertionStack);

					while (s.Offset > insertionStack.Peek()) {
						insertionStack.Pop();
					}
					insertionStack.Push(s.Offset + s.Length);
				}
				Insert(ref i, ref newSectionStart, newSection.Offset + newSection.Length, newSection.Color, insertionStack);
			}

#if DEBUG
			ValidateInvariants();
#endif
		}

19 Source : AwaiterExtensions.cs
with Apache License 2.0
from abist-co-ltd

public IEnumerator Run()
            {
                while (true)
                {
                    var topWorker = processStack.Peek();

                    bool isDone;

                    try
                    {
                        isDone = !topWorker.MoveNext();
                    }
                    catch (Exception e)
                    {
                        // The IEnumerators we have in the process stack do not tell us the
                        // actual names of the coroutine methods but it does tell us the objects
                        // that the IEnumerators are replacedociated with, so we can at least try
                        // adding that to the exception output
                        var objectTrace = GenerateObjectTrace(processStack);
                        awaiter.Complete(default(T), objectTrace.Any() ? new Exception(GenerateObjectTraceMessage(objectTrace), e) : e);

                        yield break;
                    }

                    if (isDone)
                    {
                        processStack.Pop();

                        if (processStack.Count == 0)
                        {
                            awaiter.Complete((T)topWorker.Current, null);
                            yield break;
                        }
                    }

                    // We could just yield return nested IEnumerator's here but we choose to do
                    // our own handling here so that we can catch exceptions in nested coroutines
                    // instead of just top level coroutine
                    var item = topWorker.Current as IEnumerator;
                    if (item != null)
                    {
                        processStack.Push(item);
                    }
                    else
                    {
                        // Return the current value to the unity engine so it can handle things like
                        // WaitForSeconds, WaitToEndOfFrame, etc.
                        yield return topWorker.Current;
                    }
                }
            }

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

public ChessMove GetLastMove()
        {
            return History.Peek();
        }

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

public void UndoMove(uint count)
        {
            while (History.Count > 0 && count > 0)
            {
                var move = History.Peek();

                // undo 'global' information
                Turn = Chess.InverseColor(move.Color);
                Castling = move.Castling;
                EnPreplacedantCoord = move.EnPreplacedantCoord;
                HalfMove = move.HalfMove;
                Move = move.Move;

                MovePiece(move.To, move.From);

                var flags = move.Flags;
                if (flags.HasFlag(ChessMoveFlag.Promotion))
                {
                    var piece = AddPiece(Turn, ChessPieceType.Pawn, move.To);
                    piece.Guid = move.Guid;
                }

                if (flags.HasFlag(ChessMoveFlag.Capture))
                {
                    var piece = AddPiece(Turn, move.Captured, move.To);
                    piece.Guid = move.CapturedGuid;
                }

                if (flags.HasFlag(ChessMoveFlag.EnPreplacedantCapture))
                {
                    var enPreplacedantFrom = new ChessPieceCoord(move.To);
                    enPreplacedantFrom.MoveOffset(0, move.Color == ChessColor.Black ? 1 : -1);

                    var piece = AddPiece(Turn, ChessPieceType.Pawn, enPreplacedantFrom);
                    piece.Guid = move.CapturedGuid;
                }

                if ((flags & (ChessMoveFlag.KingSideCastle | ChessMoveFlag.QueenSideCastle)) != 0)
                {
                    var castlingTo = new ChessPieceCoord(move.To);
                    var castlingFrom = new ChessPieceCoord(castlingTo);

                    if (flags.HasFlag(ChessMoveFlag.KingSideCastle))
                    {
                        castlingTo.MoveOffset(1, 0);
                        castlingFrom.MoveOffset(-1, 0);
                    }
                    if (flags.HasFlag(ChessMoveFlag.QueenSideCastle))
                    {
                        castlingTo.MoveOffset(-2, 0);
                        castlingFrom.MoveOffset(1, 0);
                    }

                    MovePiece(castlingTo, castlingFrom);
                }

                History.Pop();
                count--;
            }
        }

19 Source : ToJson.cs
with MIT License
from actions

private String PrefixValue(
            String value,
            Stack<ICollectionEnumerator> ancestors,
            Boolean isMappingKey = false)
        {
            var level = ancestors.Count;
            var parent = level > 0 ? ancestors.Peek() : null;

            if (!isMappingKey && parent is ObjectEnumerator)
            {
                return $": {value}";
            }
            else if (level > 0)
            {
                return $"{(parent.IsFirst ? String.Empty : ",")}\n{new String(' ', level * 2)}{value}";
            }
            else
            {
                return value;
            }
        }

19 Source : ExpressionParser.cs
with MIT License
from actions

private static void PushOperator(ParseContext context)
        {
            // Flush higher or equal precedence
            if (context.Token.replacedociativity == replacedociativity.LeftToRight)
            {
                var precedence = context.Token.Precedence;
                while (context.Operators.Count > 0)
                {
                    var topOperator = context.Operators.Peek();
                    if (precedence <= topOperator.Precedence &&
                        topOperator.Kind != TokenKind.StartGroup &&     // Unless top is "(" logical grouping
                        topOperator.Kind != TokenKind.StartIndex &&     // or unless top is "["
                        topOperator.Kind != TokenKind.StartParameters &&// or unless top is "(" function call
                        topOperator.Kind != TokenKind.Separator)        // or unless top is ","
                    {
                        FlushTopOperator(context);
                        continue;
                    }

                    break;
                }
            }

            // Push the operator
            context.Operators.Push(context.Token);

            // Process closing operators now, since context.LastToken is required
            // to accurately process TokenKind.EndParameters
            switch (context.Token.Kind)
            {
                case TokenKind.EndGroup:        // ")" logical grouping
                case TokenKind.EndIndex:        // "]"
                case TokenKind.EndParameters:   // ")" function call
                    FlushTopOperator(context);
                    break;
            }
        }

19 Source : ExpressionParser.cs
with MIT License
from actions

private static void FlushTopOperator(ParseContext context)
        {
            // Special handling for closing operators
            switch (context.Operators.Peek().Kind)
            {
                case TokenKind.EndIndex:        // "]"
                    FlushTopEndIndex(context);
                    return;

                case TokenKind.EndGroup:        // ")" logical grouping
                    FlushTopEndGroup(context);
                    return;

                case TokenKind.EndParameters:   // ")" function call
                    FlushTopEndParameters(context);
                    return;
            }

            // Pop the operator
            var @operator = context.Operators.Pop();

            // Create the node
            var node = (Container)@operator.ToNode();

            // Pop the operands, add to the node
            var operands = PopOperands(context, @operator.OperandCount);
            foreach (var operand in operands)
            {
                // Flatten nested And
                if (node is And)
                {
                    if (operand is And nestedAnd)
                    {
                        foreach (var nestedParameter in nestedAnd.Parameters)
                        {
                            node.AddParameter(nestedParameter);
                        }

                        continue;
                    }
                }
                // Flatten nested Or
                else if (node is Or)
                {
                    if (operand is Or nestedOr)
                    {
                        foreach (var nestedParameter in nestedOr.Parameters)
                        {
                            node.AddParameter(nestedParameter);
                        }

                        continue;
                    }
                }

                node.AddParameter(operand);
            }

            // Push the node to the operand stack
            context.Operands.Push(node);
        }

19 Source : ExpressionParser.cs
with MIT License
from actions

private static void FlushTopEndParameters(ParseContext context)
        {
            // Pop the operator
            var @operator = PopOperator(context, TokenKind.EndParameters);   // ")" function call

            // Sanity check top operator is the current token
            if (!Object.ReferenceEquals(@operator, context.Token))
            {
                throw new InvalidOperationException("Expected the operator to be the current token");
            }

            var function = default(Function);

            // No parameters
            if (context.LastToken.Kind == TokenKind.StartParameters)
            {
                // Node already exists on the operand stack
                function = (Function)context.Operands.Peek();
            }
            // Has parameters
            else
            {
                // Pop the operands
                var parameterCount = 1;
                while (context.Operators.Peek().Kind == TokenKind.Separator)
                {
                    parameterCount++;
                    context.Operators.Pop();
                }
                var functionOperands = PopOperands(context, parameterCount);
                
                // Node already exists on the operand stack
                function = (Function)context.Operands.Peek();

                // Add the operands to the node
                foreach (var operand in functionOperands)
                {
                    function.AddParameter(operand);
                }
            }

            // Pop the "(" operator too
            @operator = PopOperator(context, TokenKind.StartParameters);

            // Check min/max parameter count
            TryGetFunctionInfo(context, function.Name, out var functionInfo);
            if (functionInfo == null && context.AllowUnknownKeywords)
            {
                // Don't check min/max
            }
            else if (function.Parameters.Count < functionInfo.MinParameters)
            {
                throw new ParseException(ParseExceptionKind.TooFewParameters, token: @operator, expression: context.Expression);
            }
            else if (function.Parameters.Count > functionInfo.MaxParameters)
            {
                throw new ParseException(ParseExceptionKind.TooManyParameters, token: @operator, expression: context.Expression);
            }
        }

19 Source : IExpressionNodeExtensions.cs
with MIT License
from actions

private static void Match(
            IExpressionNode node,
            Stack<IExpressionNode>[] patterns,
            Boolean[] result)
        {
            var nodeSegments = GetMatchSegments(node);

            if (nodeSegments.Count == 0)
            {
                return;
            }

            var nodeNamedValue = nodeSegments.Peek() as NamedValue;
            var originalNodeSegments = nodeSegments;

            for (var i = 0; i < patterns.Length; i++)
            {
                var patternSegments = patterns[i];
                var patternNamedValue = patternSegments.Peek() as NamedValue;

                // Compare the named-value
                if (String.Equals(nodeNamedValue.Name, patternNamedValue.Name, StringComparison.OrdinalIgnoreCase))
                {
                    // Clone the stacks before mutating
                    nodeSegments = new Stack<IExpressionNode>(originalNodeSegments.Reverse());
                    nodeSegments.Pop();
                    patternSegments = new Stack<IExpressionNode>(patternSegments.Reverse());
                    patternSegments.Pop();

                    // Walk the stacks
                    while (true)
                    {
                        // Every pattern segment was matched
                        if (patternSegments.Count == 0)
                        {
                            result[i] = true;
                            break;
                        }
                        // Every node segment was matched. Treat the pattern as matched. There is not
                        // enough information to determine whether the property is required; replacedume it is.
                        // For example, consider the pattern "github.event" and the expression "toJson(github)".
                        // In this example the function requires the full structure of the named-value.
                        else if (nodeSegments.Count == 0)
                        {
                            result[i] = true;
                            break;
                        }

                        var nodeSegment = nodeSegments.Pop();
                        var patternSegment = patternSegments.Pop();

                        // The behavior of a wildcard varies depending on whether the left operand
                        // is an array or an object. For simplicity, treat the pattern as matched.
                        if (nodeSegment is Wildcard)
                        {
                            result[i] = true;
                            break;
                        }
                        // Treat a wildcard pattern segment as matching any literal segment
                        else if (patternSegment is Wildcard)
                        {
                            continue;
                        }

                        // Convert literals to string and compare
                        var nodeLiteral = nodeSegment as Literal;
                        var nodeEvaluationResult = EvaluationResult.CreateIntermediateResult(null, nodeLiteral.Value);
                        var nodeString = nodeEvaluationResult.ConvertToString();
                        var patternLiteral = patternSegment as Literal;
                        var patternEvaluationResult = EvaluationResult.CreateIntermediateResult(null, patternLiteral.Value);
                        var patternString = patternEvaluationResult.ConvertToString();
                        if (String.Equals(nodeString, patternString, StringComparison.OrdinalIgnoreCase))
                        {
                            continue;
                        }

                        // Convert to number and compare
                        var nodeNumber = nodeEvaluationResult.ConvertToNumber();
                        if (!Double.IsNaN(nodeNumber) && nodeNumber >= 0d && nodeNumber <= (Double)Int32.MaxValue)
                        {
                            var patternNumber = patternEvaluationResult.ConvertToNumber();
                            if (!Double.IsNaN(patternNumber) && patternNumber >= 0 && patternNumber <= (Double)Int32.MaxValue)
                            {
                                nodeNumber = Math.Floor(nodeNumber);
                                patternNumber = Math.Floor(patternNumber);
                                if (nodeNumber == patternNumber)
                                {
                                    continue;
                                }
                            }
                        }

                        // Not matched
                        break;
                    }
                }
            }
        }

19 Source : ToJson.cs
with MIT License
from actions

protected sealed override Object EvaluateCore(
            EvaluationContext context,
            out ResultMemory resultMemory)
        {
            resultMemory = null;
            var result = new StringBuilder();
            var memory = new MemoryCounter(this, context.Options.MaxMemory);
            var current = Parameters[0].Evaluate(context);
            var ancestors = new Stack<ICollectionEnumerator>();

            do
            {
                // Descend as much as possible
                while (true)
                {
                    // Collection
                    if (current.TryGetCollectionInterface(out Object collection))
                    {
                        // Array
                        if (collection is IReadOnlyArray array)
                        {
                            if (array.Count > 0)
                            {
                                // Write array start
                                WriteArrayStart(result, memory, ancestors);

                                // Move to first item
                                var enumerator = new ArrayEnumerator(context, current, array);
                                enumerator.MoveNext();
                                ancestors.Push(enumerator);
                                current = enumerator.Current;
                            }
                            else
                            {
                                // Write empty array
                                WriteEmptyArray(result, memory, ancestors);
                                break;
                            }
                        }
                        // Mapping
                        else if (collection is IReadOnlyObject obj)
                        {
                            if (obj.Count > 0)
                            {
                                // Write mapping start
                                WriteMappingStart(result, memory, ancestors);

                                // Move to first pair
                                var enumerator = new ObjectEnumerator(context, current, obj);
                                enumerator.MoveNext();
                                ancestors.Push(enumerator);

                                // Write mapping key
                                WriteMappingKey(context, result, memory, enumerator.Current.Key, ancestors);

                                // Move to mapping value
                                current = enumerator.Current.Value;
                            }
                            else
                            {
                                // Write empty mapping
                                WriteEmptyMapping(result, memory, ancestors);
                                break;
                            }
                        }
                        else
                        {
                            throw new NotSupportedException($"Unexpected type '{collection?.GetType().FullName}'");
                        }
                    }
                    // Not a collection
                    else
                    {
                        // Write value
                        WriteValue(context, result, memory, current, ancestors);
                        break;
                    }
                }

                // Next sibling or ancestor sibling
                do
                {
                    if (ancestors.Count > 0)
                    {
                        var parent = ancestors.Peek();

                        // Parent array
                        if (parent is ArrayEnumerator arrayEnumerator)
                        {
                            // Move to next item
                            if (arrayEnumerator.MoveNext())
                            {
                                current = arrayEnumerator.Current;

                                break;
                            }
                            // Move to parent
                            else
                            {
                                ancestors.Pop();
                                current = arrayEnumerator.Array;

                                // Write array end
                                WriteArrayEnd(result, memory, ancestors);
                            }
                        }
                        // Parent mapping
                        else if (parent is ObjectEnumerator objectEnumerator)
                        {
                            // Move to next pair
                            if (objectEnumerator.MoveNext())
                            {
                                // Write mapping key
                                WriteMappingKey(context, result, memory, objectEnumerator.Current.Key, ancestors);

                                // Move to mapping value
                                current = objectEnumerator.Current.Value;

                                break;
                            }
                            // Move to parent
                            else
                            {
                                ancestors.Pop();
                                current = objectEnumerator.Object;

                                // Write mapping end
                                WriteMappingEnd(result, memory, ancestors);
                            }
                        }
                        else
                        {
                            throw new NotSupportedException($"Unexpected type '{parent?.GetType().FullName}'");
                        }
                    }
                    else
                    {
                        current = null;
                    }

                } while (current != null);

            } while (current != null);

            return result.ToString();
        }

19 Source : ReCon.cs
with GNU Affero General Public License v3.0
from active-logic

public void Add(Resettable r){
        if(Count > 0) Peek().Traverse(r);
    }

19 Source : ReCon.cs
with GNU Affero General Public License v3.0
from active-logic

public void Exit(bool reset = true){
            if(!forward && reset) foreach(var e in this) e.Reset();
            if(owner.Peek() != this){
                throw new InvOp(
                         "Exiting context not topmost in ReCon stack");
            }
            owner.Pop();
        }

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

public override void VisitPropertyDeclaration(PropertyDeclarationSyntax propertyDeclaration)
		{
			bool isInsideDacOrDacExt = _isInsideDacContextStack.Count > 0
				? _isInsideDacContextStack.Peek()
				: false;

			if (!isInsideDacOrDacExt || SystemDacFieldsNames.All.Contains(propertyDeclaration.Identifier.Text))
				return;

			replacedyzeTypeMemberDeclarationForMissingXmlComments(propertyDeclaration, propertyDeclaration.Modifiers, 
															 propertyDeclaration.Identifier, reportDiagnostic: true, out _);
		}

19 Source : Repository.cs
with Apache License 2.0
from adamralph

public Version GetVersion(string tagPrefix, VersionPart autoIncrement, string defaultPreReleasePhase, ILogger log)
        {
            var commit = this.head;

            if (commit == null)
            {
                var version = new Version(defaultPreReleasePhase);

                log.Info($"No commits found. Using default version {version}.");

                return version;
            }

            var tagsAndVersions = this.tags
                .Select(tag => (tag, Version.ParseOrDefault(tag.Name, tagPrefix)))
                .OrderBy(tagAndVersion => tagAndVersion.Item2)
                .ThenBy(tagsAndVersion => tagsAndVersion.tag.Name)
                .ToList();

            var commitsChecked = new HashSet<string>();
            var count = 0;
            var height = 0;
            var candidates = new List<Candidate>();
            var commitsToCheck = new Stack<(Commit, int, Commit)>();
            Commit previousCommit = null;

            if (log.IsTraceEnabled)
            {
                log.Trace($"Starting at commit {commit.ShortSha} (height {height})...");
            }

            while (true)
            {
                var parentCount = 0;

                if (commitsChecked.Add(commit.Sha))
                {
                    ++count;

                    var commitTagsAndVersions = tagsAndVersions.Where(tagAndVersion => tagAndVersion.tag.Sha == commit.Sha).ToList();
                    var foundVersion = false;

                    foreach (var (tag, commitVersion) in commitTagsAndVersions)
                    {
                        var candidate = new Candidate { Commit = commit, Height = height, Tag = tag.Name, Version = commitVersion, Index = candidates.Count };

                        foundVersion = foundVersion || candidate.Version != null;

                        if (log.IsTraceEnabled)
                        {
                            log.Trace($"Found {(candidate.Version == null ? "non-" : null)}version tag {candidate}.");
                        }

                        candidates.Add(candidate);
                    }

                    if (!foundVersion)
                    {
                        if (log.IsTraceEnabled)
                        {
                            var parentIndex = 0;
                            Commit firstParent = null;

                            foreach (var parent in commit.Parents)
                            {
                                switch (parentIndex)
                                {
                                    case 0:
                                        firstParent = parent;
                                        break;
                                    case 1:
                                        log.Trace($"History diverges from {commit.ShortSha} (height {height}) to:");
                                        log.Trace($"- {firstParent.ShortSha} (height {height + 1})");
                                        goto default;
                                    default:
                                        log.Trace($"- {parent.ShortSha} (height {height + 1})");
                                        break;
                                }

                                ++parentIndex;
                                parentCount = parentIndex;
                            }
                        }

                        foreach (var parent in ((IEnumerable<Commit>)commit.Parents).Reverse())
                        {
                            commitsToCheck.Push((parent, height + 1, commit));
                        }

                        if (commitsToCheck.Count == 0 || commitsToCheck.Peek().Item2 <= height)
                        {
                            var candidate = new Candidate { Commit = commit, Height = height, Tag = null, Version = new Version(defaultPreReleasePhase), Index = candidates.Count };

                            if (log.IsTraceEnabled)
                            {
                                log.Trace($"Found root commit {candidate}.");
                            }

                            candidates.Add(candidate);
                        }
                    }
                }
                else
                {
                    if (log.IsTraceEnabled)
                    {
                        log.Trace($"History converges from {previousCommit.ShortSha} (height {height - 1}) back to previously seen commit {commit.ShortSha} (height {height}). Abandoning path.");
                    }
                }

                if (commitsToCheck.Count == 0)
                {
                    break;
                }

                if (log.IsTraceEnabled)
                {
                    previousCommit = commit;
                }

                var oldHeight = height;
                Commit child;
                (commit, height, child) = commitsToCheck.Pop();

                if (log.IsTraceEnabled)
                {
                    if (parentCount > 1)
                    {
                        log.Trace($"Following path from {child.ShortSha} (height {height - 1}) through first parent {commit.ShortSha} (height {height})...");
                    }
                    else if (height <= oldHeight)
                    {
                        if (commitsToCheck.Any() && commitsToCheck.Peek().Item2 == height)
                        {
                            log.Trace($"Backtracking to {child.ShortSha} (height {height - 1}) and following path through next parent {commit.ShortSha} (height {height})...");
                        }
                        else
                        {
                            log.Trace($"Backtracking to {child.ShortSha} (height {height - 1}) and following path through last parent {commit.ShortSha} (height {height})...");
                        }
                    }
                }
            }

            log.Debug($"{count:N0} commits checked.");

            var orderedCandidates = candidates.OrderBy(candidate => candidate.Version).ThenByDescending(candidate => candidate.Index).ToList();

            var tagWidth = log.IsDebugEnabled ? orderedCandidates.Max(candidate => candidate.Tag?.Length ?? 2) : 0;
            var versionWidth = log.IsDebugEnabled ? orderedCandidates.Max(candidate => candidate.Version?.ToString().Length ?? 4) : 0;
            var heightWidth = log.IsDebugEnabled ? orderedCandidates.Max(candidate => candidate.Height).ToString(CultureInfo.CurrentCulture).Length : 0;

            if (log.IsDebugEnabled)
            {
                foreach (var candidate in orderedCandidates.Take(orderedCandidates.Count - 1))
                {
                    log.Debug($"Ignoring {candidate.ToString(tagWidth, versionWidth, heightWidth)}.");
                }
            }

            var selectedCandidate = orderedCandidates.Last();

            if (selectedCandidate.Tag == null)
            {
                log.Info($"No commit found with a valid SemVer 2.0 version{(tagPrefix == null ? null : $" prefixed with '{tagPrefix}'")}. Using default version {selectedCandidate.Version}.");
            }

            log.Info($"Using{(log.IsDebugEnabled && orderedCandidates.Count > 1 ? "    " : " ")}{selectedCandidate.ToString(tagWidth, versionWidth, heightWidth)}.");

            return selectedCandidate.Version.WithHeight(selectedCandidate.Height, autoIncrement, defaultPreReleasePhase);
        }

19 Source : FSM.cs
with MIT License
from adrenak

void HandleOnUpdate() {
            if (stateStack.Peek() != null)
                stateStack.Peek().Invoke(this, owner);
        }

19 Source : StatementVisitor.cs
with MIT License
from adrianoc

public override void VisitBreakStatement(BreakStatementSyntax node)
        {
            if (breakToInstructionVars.Count == 0)
            {
                throw new InvalidOperationException("Invalid break.");
            }

            AddCilInstruction(_ilVar, OpCodes.Br, breakToInstructionVars.Peek());
        }

19 Source : BlockParser.cs
with GNU General Public License v3.0
from Aekras1a

private static ScopeBlock replacedignScopes(CilBody body, List<BasicBlock<CILInstrList>> blocks)
        {
            var ehScopes = new Dictionary<ExceptionHandler, Tuple<ScopeBlock, ScopeBlock, ScopeBlock>>();
            foreach(var eh in body.ExceptionHandlers)
            {
                var tryBlock = new ScopeBlock(ScopeType.Try, eh);
                var handlerBlock = new ScopeBlock(ScopeType.Handler, eh);

                if(eh.FilterStart != null)
                {
                    var filterBlock = new ScopeBlock(ScopeType.Filter, eh);
                    ehScopes[eh] = Tuple.Create(tryBlock, handlerBlock, filterBlock);
                }
                else
                {
                    ehScopes[eh] = Tuple.Create(tryBlock, handlerBlock, (ScopeBlock) null);
                }
            }

            var root = new ScopeBlock();
            var scopeStack = new Stack<ScopeBlock>();
            scopeStack.Push(root);

            foreach(var block in blocks)
            {
                var header = block.Content[0];

                foreach(var eh in body.ExceptionHandlers)
                {
                    var ehScope = ehScopes[eh];

                    if(header == eh.TryEnd)
                    {
                        var pop = scopeStack.Pop();
                        Debug.replacedert(pop == ehScope.Item1);
                    }

                    if(header == eh.HandlerEnd)
                    {
                        var pop = scopeStack.Pop();
                        Debug.replacedert(pop == ehScope.Item2);
                    }

                    if(eh.FilterStart != null && header == eh.HandlerStart)
                    {
                        // Filter must precede handler immediately
                        Debug.replacedert(scopeStack.Peek().Type == ScopeType.Filter);
                        var pop = scopeStack.Pop();
                        Debug.replacedert(pop == ehScope.Item3);
                    }
                }
                foreach(var eh in body.ExceptionHandlers.Reverse())
                {
                    var ehScope = ehScopes[eh];
                    var parent = scopeStack.Count > 0 ? scopeStack.Peek() : null;

                    if(header == eh.TryStart)
                    {
                        if(parent != null)
                            AddScopeBlock(parent, ehScope.Item1);
                        scopeStack.Push(ehScope.Item1);
                    }

                    if(header == eh.HandlerStart)
                    {
                        if(parent != null)
                            AddScopeBlock(parent, ehScope.Item2);
                        scopeStack.Push(ehScope.Item2);
                    }

                    if(header == eh.FilterStart)
                    {
                        if(parent != null)
                            AddScopeBlock(parent, ehScope.Item3);
                        scopeStack.Push(ehScope.Item3);
                    }
                }

                var scope = scopeStack.Peek();
                AddBasicBlock(scope, block);
            }
            foreach(var eh in body.ExceptionHandlers)
            {
                if(eh.TryEnd == null)
                {
                    var pop = scopeStack.Pop();
                    Debug.replacedert(pop == ehScopes[eh].Item1);
                }
                if(eh.HandlerEnd == null)
                {
                    var pop = scopeStack.Pop();
                    Debug.replacedert(pop == ehScopes[eh].Item2);
                }
            }
            Debug.replacedert(scopeStack.Count == 1);
            Validate(root);

            return root;
        }

19 Source : ILASTBuilder.cs
with GNU General Public License v3.0
from Aekras1a

private ILASTTree BuildAST(CILInstrList instrs, ILASTVariable[] beginStack)
        {
            var tree = new ILASTTree();
            var evalStack = new Stack<ILASTVariable>(beginStack);
            Func<int, IILASTNode[]> popArgs = numArgs =>
            {
                var args = new IILASTNode[numArgs];
                for(var i = numArgs - 1; i >= 0; i--)
                    args[i] = evalStack.Pop();
                return args;
            };

            var prefixes = new List<Instruction>();
            foreach(var instr in instrs)
            {
                if(instr.OpCode.OpCodeType == OpCodeType.Prefix)
                {
                    prefixes.Add(instr);
                    continue;
                }

                int pushes, pops;
                ILASTExpression expr;
                if(instr.OpCode.Code == Code.Dup)
                {
                    pushes = pops = 1;

                    var arg = evalStack.Peek();
                    expr = new ILASTExpression
                    {
                        ILCode = Code.Dup,
                        Operand = null,
                        Arguments = new IILASTNode[] {arg}
                    };
                }
                else
                {
                    instr.CalculateStackUsage(method.ReturnType.ElementType != ElementType.Void, out pushes, out pops);
                    Debug.replacedert(pushes == 0 || pushes == 1);

                    if(pops == -1)
                    {
                        evalStack.Clear();
                        pops = 0;
                    }

                    expr = new ILASTExpression
                    {
                        ILCode = instr.OpCode.Code,
                        Operand = instr.Operand,
                        Arguments = popArgs(pops)
                    };
                    if(expr.Operand is Instruction || expr.Operand is Instruction[])
                        instrReferences.Add(expr);
                }
                expr.CILInstr = instr;
                if(prefixes.Count > 0)
                {
                    expr.Prefixes = prefixes.ToArray();
                    prefixes.Clear();
                }

                if(pushes == 1)
                {
                    var variable = new ILASTVariable
                    {
                        Name = string.Format("s_{0:x4}", instr.Offset),
                        VariableType = ILASTVariableType.StackVar
                    };
                    evalStack.Push(variable);

                    tree.Add(new ILASTreplacedignment
                    {
                        Variable = variable,
                        Value = expr
                    });
                }
                else
                {
                    tree.Add(expr);
                }
            }
            tree.StackRemains = evalStack.Reverse().ToArray();
            return tree;
        }

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

public static string ValidateUnityTags(string text)
        {
            StringBuilder builder = new StringBuilder(text);

            Stack<Tag> tags = new Stack<Tag>();
            var matches = Regex.Matches(text, @"<(\/?)(\w+)(?:=.+?)?>");
            foreach (Match match in matches)
            {
                var tag = new Tag(
                    match.Groups[2].Value,
                    string.IsNullOrEmpty(match.Groups[1].Value));

                if (tag.IsOpeningTag)
                {
                    tags.Push(tag);
                }
                else
                {
                    if (tags.Count > 0 && tags.Peek().TagName == tag.TagName)
                    {
                        tags.Pop();
                    }
                    else
                    {
                        builder.Remove(match.Index, match.Length);
                    }
                }
            }
            while (tags.Count > 0)
            {
                builder.Append(tags.Pop().ClosingTag);
            }

            return builder.ToString();
        }

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

public static JSONNode Parse(string aJSON)
        {
            Stack<JSONNode> stack = new Stack<JSONNode>();
            JSONNode ctx = null;
            int i = 0;
            StringBuilder Token = new StringBuilder();
            string TokenName = "";
            bool QuoteMode = false;
            bool TokenIsQuoted = false;
            bool HasNewlineChar = false;
            while (i < aJSON.Length)
            {
                switch (aJSON[i])
                {
                    case '{':
                        if (QuoteMode)
                        {
                            Token.Append(aJSON[i]);
                            break;
                        }
                        stack.Push(new JSONObject());
                        if (ctx != null)
                        {
                            ctx.Add(TokenName, stack.Peek());
                        }
                        TokenName = "";
                        Token.Length = 0;
                        ctx = stack.Peek();
                        HasNewlineChar = false;
                        break;

                    case '[':
                        if (QuoteMode)
                        {
                            Token.Append(aJSON[i]);
                            break;
                        }

                        stack.Push(new JSONArray());
                        if (ctx != null)
                        {
                            ctx.Add(TokenName, stack.Peek());
                        }
                        TokenName = "";
                        Token.Length = 0;
                        ctx = stack.Peek();
                        HasNewlineChar = false;
                        break;

                    case '}':
                    case ']':
                        if (QuoteMode)
                        {

                            Token.Append(aJSON[i]);
                            break;
                        }
                        if (stack.Count == 0)
                            throw new Exception("JSON Parse: Too many closing brackets");

                        stack.Pop();
                        if (Token.Length > 0 || TokenIsQuoted)
                            ctx.Add(TokenName, ParseElement(Token.ToString(), TokenIsQuoted));
                        if (ctx != null)
                            ctx.Inline = !HasNewlineChar;
                        TokenIsQuoted = false;
                        TokenName = "";
                        Token.Length = 0;
                        if (stack.Count > 0)
                            ctx = stack.Peek();
                        break;

                    case ':':
                        if (QuoteMode)
                        {
                            Token.Append(aJSON[i]);
                            break;
                        }
                        TokenName = Token.ToString();
                        Token.Length = 0;
                        TokenIsQuoted = false;
                        break;

                    case '"':
                        QuoteMode ^= true;
                        TokenIsQuoted |= QuoteMode;
                        break;

                    case ',':
                        if (QuoteMode)
                        {
                            Token.Append(aJSON[i]);
                            break;
                        }
                        if (Token.Length > 0 || TokenIsQuoted)
                            ctx.Add(TokenName, ParseElement(Token.ToString(), TokenIsQuoted));
                        TokenIsQuoted = false;
                        TokenName = "";
                        Token.Length = 0;
                        TokenIsQuoted = false;
                        break;

                    case '\r':
                    case '\n':
                        HasNewlineChar = true;
                        break;

                    case ' ':
                    case '\t':
                        if (QuoteMode)
                            Token.Append(aJSON[i]);
                        break;

                    case '\\':
                        ++i;
                        if (QuoteMode)
                        {
                            char C = aJSON[i];
                            switch (C)
                            {
                                case 't':
                                    Token.Append('\t');
                                    break;
                                case 'r':
                                    Token.Append('\r');
                                    break;
                                case 'n':
                                    Token.Append('\n');
                                    break;
                                case 'b':
                                    Token.Append('\b');
                                    break;
                                case 'f':
                                    Token.Append('\f');
                                    break;
                                case 'u':
                                    {
                                        string s = aJSON.Substring(i + 1, 4);
                                        Token.Append((char)int.Parse(
                                            s,
                                            System.Globalization.NumberStyles.AllowHexSpecifier));
                                        i += 4;
                                        break;
                                    }
                                default:
                                    Token.Append(C);
                                    break;
                            }
                        }
                        break;
                    case '/':
                        if (allowLineComments && !QuoteMode && i + 1 < aJSON.Length && aJSON[i + 1] == '/')
                        {
                            while (++i < aJSON.Length && aJSON[i] != '\n' && aJSON[i] != '\r') ;
                            break;
                        }
                        Token.Append(aJSON[i]);
                        break;
                    case '\uFEFF': // remove / ignore BOM (Byte Order Mark)
                        break;

                    default:
                        Token.Append(aJSON[i]);
                        break;
                }
                ++i;
            }
            if (QuoteMode)
            {
                throw new Exception("JSON Parse: Quotation marks seems to be messed up.");
            }
            if (ctx == null)
                return ParseElement(Token.ToString(), TokenIsQuoted);
            return ctx;
        }

19 Source : Tokenizer.cs
with MIT License
from AgathokakologicalBit

public Context PeekContext() => contextStack.Peek();

19 Source : StackUseAnalyzer.cs
with GNU General Public License v3.0
from ahmed605

private void replacedyzeCodePath(Stack<StackValue> stack, CodePath path, ref int tempVarIndex)
        {
            HLInstruction instruction = path.GetFirstInstruction();
            while (instruction != null)
            {
                try
                {
                    if (instruction.BranchFunction != null)
                    {
                        if (!instruction.Instruction.HreplacedtackUsageInfo)
                        {
                            instruction.Instruction.StackIn = instruction.BranchFunction.ParameterCount;
                            instruction.Instruction.StackOut = instruction.BranchFunction.ReturnCount;
                            instruction.Instruction.StackLeftOver = 0;
                            instruction.Instruction.HreplacedtackUsageInfo = true;
                        }
                    }

                    if (instruction.UnconditionalBranch)
                    {
                        // One should not even occur
                        //Debug.replacedert(false);
                    }
                    else if (instruction.ExitFunction)
                    {
                        var value = new StackValueOperation(StackValueOperationType.Return);

                        if (path.ParentFunction.ReturnCount > 0)
                        {
                            for (int i = 0; i < path.ParentFunction.ReturnCount; i++)
                            {
                                value.Operands.Add(stack.Pop());
                            }
                        }

                        instruction.ProcessedStackValue = value;
                    }
                    else if (instruction.IsConditionalBranch || instruction.IsSwitchBranch)
                    {
                        instruction.ProcessedStackValue = stack.Pop();
                    }
                    else
                    {
                        bool processDefault = false;

                        StackValueOperation operationValue = null;
                        StackValue tempAnyValue;
                        StackValueOperation tempOpValue;
                        StackValueLiteral tempLiteralValue;
                        StackValuePointerBase tempPointerValue;

                        OpCode opCode = instruction.Instruction.OpCode;
                        switch (opCode)
                        {
                            case OpCode.AddVec:
                                VectorOperation(StackValueOperationType.Add, stack);
                                break;
                            case OpCode.SubVec:
                                VectorOperation(StackValueOperationType.Sub, stack);
                                break;
                            case OpCode.MulVec:
                                VectorOperation(StackValueOperationType.Mul, stack);
                                break;
                            case OpCode.DivVec:
                                VectorOperation(StackValueOperationType.Div, stack);
                                break;
                            case OpCode.NegVec:
                                VectorOperation(StackValueOperationType.Neg, stack);
                                break;
                            case OpCode.VecFromF:
                                VectorOperation(StackValueOperationType.FromF, stack);
                                break;
                            case OpCode.PushS:
                                stack.Push(new StackValueLiteral((short) instruction.Instruction.Operands[0]));
                                break;
                            case OpCode.Push:
                                stack.Push(new StackValueLiteral((int) (uint) instruction.Instruction.Operands[0]));
                                break;
                            case OpCode.PushF:
                                stack.Push(new StackValueLiteral((float) instruction.Instruction.Operands[0]));
                                break;
                            case OpCode.PushString:
                                stack.Push(new StackValueLiteral((string) instruction.Instruction.Operands[0]));
                                break;
                            case OpCode.Dup:
                                stack.Push(stack.Peek());
                                break;
                            case OpCode.Pop:
                                tempOpValue = stack.Peek() as StackValueOperation;
                                if (tempOpValue != null && tempOpValue.OperationType == StackValueOperationType.Call)
                                {
                                    operationValue = new StackValueOperation(StackValueOperationType.Pop);
                                    processDefault = true;
                                }
                                break;
                            case OpCode.CallNative:
                                operationValue = new StackValueOperation(instruction.Instruction.Operands[2].ToString());
                                processDefault = true;
                                break;
                            case OpCode.Call:
                                operationValue = new StackValueOperation(instruction.BranchFunction.Name);
                                processDefault = true;
                                break;
                            case OpCode.RefGet:
                                stack.Push(new StackValueDeref(stack.Pop()));
                                break;
                            case OpCode.RefSet:
                                instruction.ProcessedStackValue = new StackValuereplacedign(PopPointer(stack), stack.Pop());
                                break;
                            case OpCode.RefPeekSet:
                                tempAnyValue = stack.Pop(); // value!
                                instruction.ProcessedStackValue = new StackValuereplacedign(PeekPointer(stack), tempAnyValue);
                                break;
                            case OpCode.ArrayExplode:
                                // This is used to either preplaced a structure to a native/function call
                                // or to explode the variables onto the stack to do a "shallow-copy"

                                tempPointerValue = PopPointer(stack);
                                tempLiteralValue = stack.Pop() as StackValueLiteral;
                                Debug.replacedert(tempLiteralValue != null &&
                                             tempLiteralValue.ValueType == StackValueType.Integer);

                                var explodeCount = (int) tempLiteralValue.Value;
                                for (int i = 0; i < explodeCount; i++)
                                {
                                    stack.Push(new StackValueDeref(new StackValuePointerIndex(tempPointerValue, i)));
                                }

                                break;
                            case OpCode.ArrayImplode:
                                // The only case this is ever used is for a shallow copy!

                                tempPointerValue = PopPointer(stack);
                                tempLiteralValue = stack.Pop() as StackValueLiteral;
                                Debug.replacedert(tempLiteralValue != null &&
                                             tempLiteralValue.ValueType == StackValueType.Integer);

                                var tempStack = new Stack<StackValue>();
                                var implodeCount = (int) tempLiteralValue.Value;
                                for (int i = implodeCount - 1; i >= 0; i--)
                                {
                                    tempStack.Push(
                                        new StackValuereplacedign(new StackValuePointerIndex(tempPointerValue, i),
                                                             stack.Pop()));
                                }

                                var stackValueGroup = new ProcessedStackValueGroup();

                                stackValueGroup.Values.AddRange(tempStack.ToArray());
                                instruction.ProcessedStackValue = stackValueGroup;

                                break;
                            case OpCode.Var0:
                            case OpCode.Var1:
                            case OpCode.Var2:
                            case OpCode.Var3:
                            case OpCode.Var4:
                            case OpCode.Var5:
                            case OpCode.Var6:
                            case OpCode.Var7:
                                stack.Push(new StackValuePointerVar(StackValuePointerType.Stack,
                                                                    (opCode - OpCode.Var0)));
                                break;
                            case OpCode.Var:
                                tempLiteralValue = stack.Pop() as StackValueLiteral;
                                Debug.replacedert(tempLiteralValue != null &&
                                             tempLiteralValue.ValueType == StackValueType.Integer);

                                stack.Push(new StackValuePointerVar(StackValuePointerType.Stack,
                                                                    (int) tempLiteralValue.Value));
                                break;
                            case OpCode.LocalVar:
                                tempLiteralValue = stack.Pop() as StackValueLiteral;
                                Debug.replacedert(tempLiteralValue != null &&
                                             tempLiteralValue.ValueType == StackValueType.Integer);

                                stack.Push(new StackValuePointerVar(StackValuePointerType.Local,
                                                                    (int) tempLiteralValue.Value));
                                break;
                            case OpCode.GlobalVar:
                                tempLiteralValue = stack.Pop() as StackValueLiteral;
                                Debug.replacedert(tempLiteralValue != null &&
                                             tempLiteralValue.ValueType == StackValueType.Integer);

                                stack.Push(new StackValuePointerVar(StackValuePointerType.Global,
                                                                    (int) tempLiteralValue.Value));
                                break;
                            case OpCode.ArrayRef:
                                tempPointerValue = PopPointer(stack);
                                tempLiteralValue = stack.Pop() as StackValueLiteral;
                                tempAnyValue = stack.Pop();
                                Debug.replacedert(tempPointerValue != null);
                                Debug.replacedert(tempLiteralValue != null &&
                                             tempLiteralValue.ValueType == StackValueType.Integer);

                                stack.Push(new StackValuePointerArray(tempPointerValue, tempAnyValue,
                                                                      (int) tempLiteralValue.Value));
                                break;
                            case OpCode.NullObj:
                                stack.Push(new StackValuePointerVar(StackValuePointerType.Null));
                                break;
                            case OpCode.Add:
                                // Special case for pointer add
                                tempAnyValue = stack.Pop();
                                tempPointerValue = stack.Peek() as StackValuePointerBase;

                                if (tempPointerValue != null)
                                {
                                    stack.Pop(); // tempPointerValue

                                    tempLiteralValue = tempAnyValue as StackValueLiteral;
                                    Debug.replacedert(tempLiteralValue != null && (int) tempLiteralValue.Value%4 == 0);

                                    stack.Push(new StackValuePointerIndex(tempPointerValue,
                                                                          (int) tempLiteralValue.Value/4));
                                }
                                else
                                {
                                    stack.Push(tempAnyValue);
                                    operationValue = new StackValueOperation(opCode);
                                    processDefault = true;
                                }
                                break;
                            case OpCode.StrCat:
                            case OpCode.StrCatI:
                            case OpCode.StrCpy:
                            case OpCode.IntToStr:
                                operationValue = new StackValueStringOperation(opCode, (byte)instruction.Instruction.Operands[0]);
                                processDefault = true;
                                break;
                            case OpCode.StrVarCpy:
                                tempPointerValue = PopPointer(stack);

                                tempLiteralValue = stack.Pop() as StackValueLiteral;
                                
                                Debug.replacedert(tempLiteralValue != null &&
                                             tempLiteralValue.ValueType == StackValueType.Integer);

                                var targetSize = (uint)(int)tempLiteralValue.Value;

                                tempLiteralValue = stack.Pop() as StackValueLiteral;

                                Debug.replacedert(tempLiteralValue != null &&
                                             tempLiteralValue.ValueType == StackValueType.Integer);

                                var sourceSize = (uint)(int)tempLiteralValue.Value;

                                var popSize = sourceSize;

                                tempAnyValue = PopPointer(stack);

                                // Pop till the last one
                                for (var i = 1; i < popSize; i++)
                                {
                                    tempAnyValue = PopPointer(stack);
                                }

                                operationValue = new StackValueStringOperation(opCode, targetSize, sourceSize);
                                operationValue.Operands.Add(new StackValueRef(tempAnyValue)); // 0 = source
                                operationValue.Operands.Add(tempPointerValue); // 1 = target
                                
                                instruction.ProcessedStackValue = operationValue;

                                break;
                            case OpCode.RefProtect:
                                tempLiteralValue = stack.Pop() as StackValueLiteral;

                                Debug.replacedert(tempLiteralValue != null &&
                                     tempLiteralValue.ValueType == StackValueType.Integer);

                                var protectMode = (int)tempLiteralValue.Value;

                                Debug.replacedert(protectMode == 1 || protectMode == 2 || protectMode == 5 || protectMode == 6);

                                tempLiteralValue = stack.Pop() as StackValueLiteral;

                                Debug.replacedert(tempLiteralValue != null &&
                                     tempLiteralValue.ValueType == StackValueType.Integer);

                                var protectCount = (int)tempLiteralValue.Value;

                                //Debug.replacedert(protectCount == 1);

                                tempPointerValue = PopPointer(stack);

                                operationValue = new StackValueOperation(StackValueOperationType.RefProtect);
                                operationValue.Operands.Add(tempPointerValue);
                                operationValue.Operands.Add(tempLiteralValue);

                                if ((protectMode & 1) != 0)
                                {
                                    stack.Push(operationValue);
                                }
                                
                                break;
                            default:
                                if (instruction.Instruction is InstructionPush)
                                {
                                    // PushD special case
                                    stack.Push(new StackValueLiteral((int) instruction.Instruction.Operands[0]));
                                }
                                else
                                {
                                    operationValue = new StackValueOperation(opCode);
                                    processDefault = true;
                                }
                                break;
                        }

                        if (processDefault)
                        {
                            Debug.replacedert(instruction.Instruction.HreplacedtackUsageInfo);

                            var stackValues = new Stack<StackValue>();
                            for (int i = 0; i < instruction.Instruction.StackIn; i++)
                            {
                                StackValue stackItem = stack.Pop();
                                stackValues.Push(stackItem);
                            }

                            operationValue.Operands.AddRange(stackValues);

                            if (instruction.Instruction.StackLeftOver > 0)
                            {
                                for (int i = 0; i < instruction.Instruction.StackLeftOver; i++)
                                {
                                    stackValues.Push(stackValues.Pop());
                                }
                            }

                            if (instruction.Instruction.StackOut > 0)
                            {
                                if (instruction.Instruction.StackOut > 1)
                                {
                                    var multireplacedign = new StackValuereplacedignMulti(operationValue);
                                    for (int i = 0; i < instruction.Instruction.StackOut; i++)
                                    {
                                        tempPointerValue = new StackValuePointerVar(StackValuePointerType.Temporary,
                                                                                    tempVarIndex + i);
                                        multireplacedign.replacedignPointers.Add(tempPointerValue);
                                        stack.Push(new StackValueDeref(tempPointerValue));
                                    }
                                    tempVarIndex += instruction.Instruction.StackOut;
                                    instruction.ProcessedStackValue = multireplacedign;
                                }
                                else
                                {
                                    stack.Push(operationValue);
                                }
                            }
                            else
                            {
                                instruction.ProcessedStackValue = operationValue;
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    throw new Exception(
                        "Error while decompiling instruction : " + instruction.Instruction + "\n", e);
                }

                instruction = instruction.GetNextInstruction();
            }
        }

19 Source : StackUseAnalyzer.cs
with GNU General Public License v3.0
from ahmed605

private StackValuePointerBase PeekPointer(Stack<StackValue> stack)
        {
            StackValue value = stack.Peek();
            if (value is StackValuePointerBase)
            {
                return value as StackValuePointerBase;
            }
            else
            {
                return new StackValuePointerFake(value);
            }
        }

19 Source : BehaviorTreeBuilder.cs
with MIT License
from aillieo

public BehaviorTreeBuilder AddAction(NodeAction nodeAction)
        {
            this.stack.Peek().AddChild(nodeAction);
            return this;
        }

19 Source : BehaviorTreeBuilder.cs
with MIT License
from aillieo

public BehaviorTreeBuilder AddCondition(NodeCondition nodeCondition)
        {
            this.stack.Peek().AddChild(nodeCondition);
            return this;
        }

19 Source : BehaviorTreeBuilder.cs
with MIT License
from aillieo

public BehaviorTreeBuilder AddComposite(NodeComposite nodeComposite)
        {
            if (this.stack.Count > 0)
            {
                this.stack.Peek().AddChild(nodeComposite);
            }
            this.stack.Push(nodeComposite);
            return this;
        }

19 Source : BehaviorTreeBuilder.cs
with MIT License
from aillieo

public BehaviorTreeBuilder AddDecorator(NodeDecorator nodeDecorator)
        {
            if (this.stack.Count > 0)
            {
                this.stack.Peek().AddChild(nodeDecorator);
            }
            this.stack.Push(nodeDecorator);
            return this;
        }

19 Source : JsonSerializerInternalReader.cs
with MIT License
from akaskela

private object PopulateMultidimensionalArray(IList list, JsonReader reader, JsonArrayContract contract, JsonProperty containerProperty, string id)
        {
            int rank = contract.UnderlyingType.GetArrayRank();

            if (id != null)
            {
                AddReference(reader, id, list);
            }

            OnDeserializing(reader, contract, list);

            JsonContract collectionItemContract = GetContractSafe(contract.CollectionItemType);
            JsonConverter collectionItemConverter = GetConverter(collectionItemContract, null, contract, containerProperty);

            int? previousErrorIndex = null;
            Stack<IList> listStack = new Stack<IList>();
            listStack.Push(list);
            IList currentList = list;

            bool finished = false;
            do
            {
                int initialDepth = reader.Depth;

                if (listStack.Count == rank)
                {
                    try
                    {
                        if (ReadForType(reader, collectionItemContract, collectionItemConverter != null))
                        {
                            switch (reader.TokenType)
                            {
                                case JsonToken.EndArray:
                                    listStack.Pop();
                                    currentList = listStack.Peek();
                                    previousErrorIndex = null;
                                    break;
                                default:
                                    object value;

                                    if (collectionItemConverter != null && collectionItemConverter.CanRead)
                                    {
                                        value = DeserializeConvertable(collectionItemConverter, reader, contract.CollectionItemType, null);
                                    }
                                    else
                                    {
                                        value = CreateValueInternal(reader, contract.CollectionItemType, collectionItemContract, null, contract, containerProperty, null);
                                    }

                                    currentList.Add(value);
                                    break;
                            }
                        }
                        else
                        {
                            break;
                        }
                    }
                    catch (Exception ex)
                    {
                        JsonPosition errorPosition = reader.GetPosition(initialDepth);

                        if (IsErrorHandled(list, contract, errorPosition.Position, reader as IJsonLineInfo, reader.Path, ex))
                        {
                            HandleError(reader, true, initialDepth);

                            if (previousErrorIndex != null && previousErrorIndex == errorPosition.Position)
                            {
                                // reader index has not moved since previous error handling
                                // break out of reading array to prevent infinite loop
                                throw JsonSerializationException.Create(reader, "Infinite loop detected from error handling.", ex);
                            }
                            else
                            {
                                previousErrorIndex = errorPosition.Position;
                            }
                        }
                        else
                        {
                            throw;
                        }
                    }
                }
                else
                {
                    if (reader.Read())
                    {
                        switch (reader.TokenType)
                        {
                            case JsonToken.StartArray:
                                IList newList = new List<object>();
                                currentList.Add(newList);
                                listStack.Push(newList);
                                currentList = newList;
                                break;
                            case JsonToken.EndArray:
                                listStack.Pop();

                                if (listStack.Count > 0)
                                {
                                    currentList = listStack.Peek();
                                }
                                else
                                {
                                    finished = true;
                                }
                                break;
                            case JsonToken.Comment:
                                break;
                            default:
                                throw JsonSerializationException.Create(reader, "Unexpected token when deserializing multidimensional array: " + reader.TokenType);
                        }
                    }
                    else
                    {
                        break;
                    }
                }
            } while (!finished);

            if (!finished)
            {
                ThrowUnexpectedEndException(reader, contract, list, "Unexpected end when deserializing array.");
            }

            OnDeserialized(reader, contract, list);
            return list;
        }

19 Source : JsonValidatingReader.cs
with MIT License
from akaskela

private SchemaScope Pop()
        {
            SchemaScope poppedScope = _stack.Pop();
            _currentScope = (_stack.Count != 0)
                ? _stack.Peek()
                : null;

            return poppedScope;
        }

19 Source : HtmlParser.cs
with GNU Affero General Public License v3.0
from akshinmustafayev

private void AddEmptyElement(XmlElement htmlEmptyElement)
        {
            Invariantreplacedert(_openedElements.Count > 0, "AddEmptyElement: Stack of opened elements cannot be empty, as we have at least one artificial root element");
            XmlElement htmlParent = _openedElements.Peek();
            htmlParent.AppendChild(htmlEmptyElement);
        }

19 Source : HtmlParser.cs
with GNU Affero General Public License v3.0
from akshinmustafayev

private void OpenStructuringElement(XmlElement htmlElement)
        {
            // Close all pending inline elements
            // All block elements are considered as delimiters for inline elements
            // which forces all inline elements to be closed and re-opened in the following
            // structural element (if any).
            // By doing that we guarantee that all inline elements appear only within most nested blocks
            if (HtmlSchema.IsBlockElement(htmlElement.LocalName))
            {
                while (_openedElements.Count > 0 && HtmlSchema.IsInlineElement(_openedElements.Peek().LocalName))
                {
                    XmlElement htmlInlineElement = _openedElements.Pop();
                    Invariantreplacedert(_openedElements.Count > 0, "OpenStructuringElement: stack of opened elements cannot become empty here");

                    _pendingInlineElements.Push(CreateElementCopy(htmlInlineElement));
                }
            }

            // Add this block element to its parent
            if (_openedElements.Count > 0)
            {
                XmlElement htmlParent = _openedElements.Peek();

                // Check some known block elements for auto-closing (LI and P)
                if (HtmlSchema.ClosesOnNextElementStart(htmlParent.LocalName, htmlElement.LocalName))
                {
                    _openedElements.Pop();
                    htmlParent = _openedElements.Count > 0 ? _openedElements.Peek() : null;
                }

                if (htmlParent != null)
                {
                    // NOTE:
                    // Actually we never expect null - it would mean two top-level P or LI (without a parent).
                    // In such weird case we will loose all paragraphs except the first one...
                    htmlParent.AppendChild(htmlElement);
                }
            }

            // Push it onto a stack
            _openedElements.Push(htmlElement);
        }

19 Source : HtmlParser.cs
with GNU Affero General Public License v3.0
from akshinmustafayev

private void AddTextContent(string textContent)
        {
            OpenPendingInlineElements();

            Invariantreplacedert(_openedElements.Count > 0, "AddTextContent: Stack of opened elements cannot be empty, as we have at least one artificial root element");

            XmlElement htmlParent = _openedElements.Peek();
            XmlText textNode = _doreplacedent.CreateTextNode(textContent);
            htmlParent.AppendChild(textNode);
        }

19 Source : HtmlParser.cs
with GNU Affero General Public License v3.0
from akshinmustafayev

private void CloseElement(string htmlElementName)
        {
            // Check if the element is opened and already added to the parent
            Invariantreplacedert(_openedElements.Count > 0, "CloseElement: Stack of opened elements cannot be empty, as we have at least one artificial root element");

            // Check if the element is opened and still waiting to be added to the parent
            if (_pendingInlineElements.Count > 0 && _pendingInlineElements.Peek().LocalName == htmlElementName)
            {
                // Closing an empty inline element.
                // Note that HtmlConverter will skip empty inlines, but for completeness we keep them here on parser level.
                XmlElement htmlInlineElement = _pendingInlineElements.Pop();
                Invariantreplacedert(_openedElements.Count > 0, "CloseElement: Stack of opened elements cannot be empty, as we have at least one artificial root element");
                XmlElement htmlParent = _openedElements.Peek();
                htmlParent.AppendChild(htmlInlineElement);
                return;
            }
            else if (IsElementOpened(htmlElementName))
            {
                while (_openedElements.Count > 1) // we never pop the last element - the artificial root
                {
                    // Close all unbalanced elements.
                    XmlElement htmlOpenedElement = _openedElements.Pop();

                    if (htmlOpenedElement.LocalName == htmlElementName)
                    {
                        return;
                    }

                    if (HtmlSchema.IsInlineElement(htmlOpenedElement.LocalName))
                    {
                        // Unbalances Inlines will be transfered to the next element content
                        _pendingInlineElements.Push(CreateElementCopy(htmlOpenedElement));
                    }
                }
            }

            // If element was not opened, we simply ignore the unbalanced closing tag
            return;
        }

19 Source : HtmlParser.cs
with GNU Affero General Public License v3.0
from akshinmustafayev

private void AddComment(string comment)
        {
            OpenPendingInlineElements();

            Invariantreplacedert(_openedElements.Count > 0, "AddComment: Stack of opened elements cannot be empty, as we have at least one artificial root element");

            XmlElement htmlParent = _openedElements.Peek();
            XmlComment xmlComment = _doreplacedent.CreateComment(comment);
            htmlParent.AppendChild(xmlComment);
        }

19 Source : HtmlParser.cs
with GNU Affero General Public License v3.0
from akshinmustafayev

private void OpenPendingInlineElements()
        {
            if (_pendingInlineElements.Count > 0)
            {
                XmlElement htmlInlineElement = _pendingInlineElements.Pop();

                OpenPendingInlineElements();

                Invariantreplacedert(_openedElements.Count > 0, "OpenPendingInlineElements: Stack of opened elements cannot be empty, as we have at least one artificial root element");

                XmlElement htmlParent = _openedElements.Peek();
                htmlParent.AppendChild(htmlInlineElement);
                _openedElements.Push(htmlInlineElement);
            }
        }

19 Source : MagicLaboratory.cs
with MIT License
from alaabenfatma

public static string DeleteAllDirectoriesForce(string head, bool async = true)
        {
            if (DeletedFolders.Peek() == "End.")
                foreach (var file in Directory.GetFiles(head))
                    File.Delete(file);

            foreach (var h in Directory.GetDirectories(head))
                DeleteAllDirectoriesForce(h);

            Directory.Delete(head);
            return null;
        }

19 Source : UI.cs
with MIT License
from Alan-FGR

private void AddScissorRectangle(Rectangle parentRectangle)
        {
            ScissorArea();
            // add a rectangle that's the intersection of the current destination and the one on the top of the stack (if any)
            Rectangle rToIntersect = ScissorRects.Count > 0 ? ScissorRects.Peek() : new Rectangle(0, 0, Int32.MaxValue, Int32.MaxValue);
            ScissorRects.Push(Rectangle.Intersect(GetDestinationRectangle(parentRectangle).InflateClone(-1, -1), rToIntersect)); //scissor margin
        }

19 Source : UI.cs
with MIT License
from Alan-FGR

private void ScissorArea()
        {
            if (ScissorRects.Count > 0)
            {
                device_.ScissorRectangle = ScissorRects.Peek();
                device_.RasterizerState.ScissorTestEnable = true;
            }
            batch.End();
            batch.Begin();
        }

19 Source : Layout.cs
with MIT License
from alelievr

public void AutoSizePanel(LayoutSetting defaultSetting, LayoutPanel panel)
		{
			var sep = new StaticPanelSeparator(currentOrientation.Peek());
			sep.UpdateLayoutSetting(defaultSetting);
			AddPanel(sep, panel);
		}

19 Source : MixtureGraphProcessor.cs
with MIT License
from alelievr

void ProcessNodeList(CommandBuffer cmd, HashSet<BaseNode> nodes)
		{
			HashSet<ILoopStart> starts = new HashSet<ILoopStart>();
			HashSet<ILoopEnd> ends = new HashSet<ILoopEnd>();
			HashSet<INeedLoopReset> iNeedLoopReset = new HashSet<INeedLoopReset>();

			// Note that this jump pattern doesn't handle correctly the multiple dependencies a for loop
			// can have and it may cause some nodes to be processed multiple times unnecessarily, depending on the compute order.
			Stack<(ILoopStart node, int index)> jumps = new Stack<(ILoopStart, int)>();

			// TODO: cache?
			var sortedNodes = nodes.Where(n => n.computeOrder >= 0).OrderBy(n => n.computeOrder).ToList();

			int maxLoopCount = 0;
			jumps.Clear();
			starts.Clear();
			ends.Clear();
			iNeedLoopReset.Clear();

			for (int executionIndex = 0; executionIndex < sortedNodes.Count; executionIndex++)
			{
				maxLoopCount++;
				if (maxLoopCount > 10000)
					return;

				var node = sortedNodes[executionIndex];

				if (node is ILoopStart loopStart)
				{
					if (!starts.Contains(loopStart))
					{
						loopStart.PrepareLoopStart();
						jumps.Push((loopStart, executionIndex));
						starts.Add(loopStart);
					}
				}

				bool finalIteration = false;
				if (node is ILoopEnd loopEnd)
				{
					if (jumps.Count == 0)
					{
						Debug.Log("Aborted execution, for end without start");
						return ;
					}

					var startLoop = jumps.Peek();
					if (!ends.Contains(loopEnd))
					{
						loopEnd.PrepareLoopEnd(startLoop.node);
						ends.Add(loopEnd);
					}

					// Jump back to the foreach start
					if (!startLoop.node.IsLasreplacederation())
					{
						executionIndex = startLoop.index - 1;
					}
					else
					{
						var fs2 = jumps.Pop();
						starts.Remove(fs2.node);
						ends.Remove(loopEnd);
						finalIteration = true;
					}
				}

				if (node is INeedLoopReset i)
				{
					if (!iNeedLoopReset.Contains(i))
					{
						i.PrepareNewIteration();
						iNeedLoopReset.Add(i);
					}

					// TODO: remove this node form iNeedLoopReset when we go over a foreach start again
				}
			
				if (finalIteration && node is ILoopEnd le)
				{
					le.FinalIteration();
				}

				ProcessNode(cmd, node);
			}
		}

19 Source : Layout.cs
with MIT License
from alelievr

public void ResizablePanel(LayoutSetting defaultSetting, LayoutPanel panel)
		{
			var sep = new ResizablePanelSeparator(currentOrientation.Peek());
			sep.UpdateLayoutSetting(defaultSetting);
			AddPanel(sep, panel);

			savedDefaultSettings.Add(defaultSetting.Clone(null));
		}

19 Source : TgParser.cs
with MIT License
from ali4heydari

private List<Message> GetMessages()
        {
            var doreplacedent = new HtmlDoreplacedent();
            doreplacedent.Load(InputHtmlPath, encoding: Encoding.UTF8);

            var messageNodes = doreplacedent.QuerySelectorAll(MESSAGES_QUERY_SELECTOR);

            Stack<Message> messagesStack = new Stack<Message>();


            try
            {
                foreach (var messageNode in messageNodes)
                {
                    int messageId = int.Parse(
                        messageNode
                            .Attributes["id"]
                            .Value.Substring(7));

                    // text can be null
                    string text = messageNode
                        .QuerySelector(MESSAGE_TEXT_QUERY_SELECTOR)
                        ?.InnerText.Trim();

                    string date = messageNode
                        .QuerySelector(MESSAGE_DATE_QUERY_SELECTOR)
                        .Attributes["replacedle"].Value;

                    string author = messageNode
                        .QuerySelector(MESSAGE_FROM_NAME_QUERY_SELECTOR)
                        ?.InnerText.Trim();

                    int? replyMessageId = null;
                    if (messageNode.QuerySelector(MESSAGE_REPLY_QUERY_SELECTOR) != null)
                    {
                        replyMessageId = int.Parse(messageNode
                                                       .QuerySelector(MESSAGE_REPLY_QUERY_SELECTOR)
                                                       ?.Attributes["href"].Value.Substring(14) ??
                                                   throw new Exception());
                    }

                    messagesStack.Push(author != null
                        ? new Message(text, author, date, replyMessageId, messageId)
                        : new Message(text, messagesStack.Peek().Author, date, replyMessageId, messageId));
                }
            }
            catch (Exception e)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine($"Exception thrown: \nMessage -> {e.Message}\nStackTrace -> {e.StackTrace}");
                Console.ForegroundColor = ConsoleColor.White;
            }

            return messagesStack.ToList();
        }

See More Examples