text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Diagnostics;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax
{
    internal partial class Lexer
    {
        private void ScanStringLiteral(ref TokenInfo info, bool inDirective)
        {
            var quoteCharacter = TextWindow.PeekChar();
            Debug.Assert(quoteCharacter is '\'' or '"');

            TextWindow.AdvanceChar();
            _builder.Length = 0;

            while (true)
            {
                char ch = TextWindow.PeekChar();

                // Normal string & char constants can have escapes. Strings in directives cannot.
                if (ch == '\\' && !inDirective)
                {
                    ch = this.ScanEscapeSequence(out var c2);
                    _builder.Append(ch);
                    if (c2 != SlidingTextWindow.InvalidCharacter)
                    {
                        _builder.Append(c2);
                    }
                }
                else if (ch == quoteCharacter)
                {
                    TextWindow.AdvanceChar();
                    break;
                }
                else if (SyntaxFacts.IsNewLine(ch) ||
                        (ch == SlidingTextWindow.InvalidCharacter && TextWindow.IsReallyAtEnd()))
                {
                    //String and character literals can contain any Unicode character. They are not limited
                    //to valid UTF-16 characters. So if we get the SlidingTextWindow's sentinel value,
                    //double check that it was not real user-code contents. This will be rare.
                    Debug.Assert(TextWindow.Width > 0);
                    this.AddError(ErrorCode.ERR_NewlineInConst);
                    break;
                }
                else
                {
                    TextWindow.AdvanceChar();
                    _builder.Append(ch);
                }
            }

            info.Text = TextWindow.GetText(intern: true);
            if (quoteCharacter == '\'')
            {
                info.Kind = SyntaxKind.CharacterLiteralToken;
                if (_builder.Length != 1)
                {
                    this.AddError((_builder.Length != 0) ? ErrorCode.ERR_TooManyCharsInConst : ErrorCode.ERR_EmptyCharConst);
                }

                if (_builder.Length > 0)
                {
                    info.StringValue = TextWindow.Intern(_builder);
                    info.CharValue = info.StringValue[0];
                }
                else
                {
                    info.StringValue = string.Empty;
                    info.CharValue = SlidingTextWindow.InvalidCharacter;
                }
            }
            else
            {
                info.Kind = SyntaxKind.StringLiteralToken;
                if (_builder.Length > 0)
                {
                    info.StringValue = TextWindow.Intern(_builder);
                }
                else
                {
                    info.StringValue = string.Empty;
                }
            }
        }

        private char ScanEscapeSequence(out char surrogateCharacter)
        {
            var start = TextWindow.Position;
            surrogateCharacter = SlidingTextWindow.InvalidCharacter;
            char ch = TextWindow.NextChar();
            Debug.Assert(ch == '\\');

            ch = TextWindow.NextChar();
            switch (ch)
            {
                // escaped characters that translate to themselves
                case '\'':
                case '"':
                case '\\':
                    break;
                // translate escapes as per C# spec 2.4.4.4
                case '0':
                    ch = '\u0000';
                    break;
                case 'a':
                    ch = '\u0007';
                    break;
                case 'b':
                    ch = '\u0008';
                    break;
                case 'f':
                    ch = '\u000c';
                    break;
                case 'n':
                    ch = '\u000a';
                    break;
                case 'r':
                    ch = '\u000d';
                    break;
                case 't':
                    ch = '\u0009';
                    break;
                case 'v':
                    ch = '\u000b';
                    break;
                case 'x':
                case 'u':
                case 'U':
                    TextWindow.Reset(start);
                    SyntaxDiagnosticInfo error;
                    ch = TextWindow.NextUnicodeEscape(surrogateCharacter: out surrogateCharacter, info: out error);
                    AddError(error);
                    break;
                default:
                    this.AddError(start, TextWindow.Position - start, ErrorCode.ERR_IllegalEscape);
                    break;
            }

            return ch;
        }

        private void ScanVerbatimStringLiteral(ref TokenInfo info)
        {
            _builder.Length = 0;

            Debug.Assert(TextWindow.PeekChar() == '@' && TextWindow.PeekChar(1) == '"');
            TextWindow.AdvanceChar(2);

            while (true)
            {
                var ch = TextWindow.PeekChar();
                if (ch == '"')
                {
                    TextWindow.AdvanceChar();
                    if (TextWindow.PeekChar() == '"')
                    {
                        // Doubled quote -- skip & put the single quote in the string and keep going.
                        TextWindow.AdvanceChar();
                        _builder.Append(ch);
                        continue;
                    }

                    // otherwise, the string is finished.
                    break;
                }

                if (ch == SlidingTextWindow.InvalidCharacter && TextWindow.IsReallyAtEnd())
                {
                    // Reached the end of the source without finding the end-quote.  Give an error back at the
                    // starting point. And finish lexing this string.
                    this.AddError(ErrorCode.ERR_UnterminatedStringLit);
                    break;
                }

                TextWindow.AdvanceChar();
                _builder.Append(ch);
            }

            info.Kind = SyntaxKind.StringLiteralToken;
            info.Text = TextWindow.GetText(intern: false);
            info.StringValue = _builder.ToString();
        }

        private void ScanInterpolatedStringLiteral(ref TokenInfo info)
        {
            // We have a string of one of the forms
            //                $" ... "
            //                $@" ... "
            //                @$" ... "
            // Where the contents contains zero or more sequences
            //                { STUFF }
            // where these curly braces delimit STUFF in expression "holes".
            // In order to properly find the closing quote of the whole string,
            // we need to locate the closing brace of each hole, as strings
            // may appear in expressions in the holes. So we
            // need to match up any braces that appear between them.
            // But in order to do that, we also need to match up any
            // /**/ comments, ' characters quotes, () parens
            // [] brackets, and "" strings, including interpolated holes in the latter.

            ScanInterpolatedStringLiteralTop(
                ref info,
                out var error,
                kind: out _,
                openQuoteRange: out _,
                interpolations: null,
                closeQuoteRange: out _);

            this.AddError(error);
        }

        internal void ScanInterpolatedStringLiteralTop(
            ref TokenInfo info,
            out SyntaxDiagnosticInfo? error,
            out InterpolatedStringKind kind,
            out Range openQuoteRange,
            ArrayBuilder<Interpolation>? interpolations,
            out Range closeQuoteRange)
        {
            var subScanner = new InterpolatedStringScanner(this);
            subScanner.ScanInterpolatedStringLiteralTop(out kind, out openQuoteRange, interpolations, out closeQuoteRange);
            error = subScanner.Error;
            info.Kind = SyntaxKind.InterpolatedStringToken;
            info.Text = TextWindow.GetText(intern: false);
        }

        /// <summary>
        /// Turn a (parsed) interpolated string nonterminal into an interpolated string token.
        /// </summary>
        /// <param name="interpolatedString"></param>
        internal static SyntaxToken RescanInterpolatedString(InterpolatedStringExpressionSyntax interpolatedString)
        {
            var text = interpolatedString.ToString();
            var kind = SyntaxKind.InterpolatedStringToken;
            // TODO: scan the contents (perhaps using ScanInterpolatedStringLiteralContents) to reconstruct any lexical
            // errors such as // inside an expression hole
            return SyntaxFactory.Literal(
                interpolatedString.GetFirstToken().GetLeadingTrivia(),
                text,
                kind,
                text,
                interpolatedString.GetLastToken().GetTrailingTrivia());
        }

        internal enum InterpolatedStringKind
        {
            /// <summary>
            /// Normal interpolated string that just starts with $"
            /// </summary>
            Normal,
            /// <summary>
            /// Verbatim interpolated string that starts with $@" or @$"
            /// </summary>
            Verbatim,
        }

        /// <summary>
        /// Non-copyable ref-struct so that this will only live on the stack for the lifetime of the lexer/parser
        /// recursing to process interpolated strings.
        /// </summary>
        [NonCopyable]
        private ref struct InterpolatedStringScanner
        {
            private readonly Lexer _lexer;

            private readonly InterpolatedStringKind _kind;

            /// <summary>
            /// Error encountered while scanning.  If we run into an error, then we'll attempt to stop parsing at the
            /// next potential ending location to prevent compounding the issue.
            /// </summary>
            public SyntaxDiagnosticInfo? Error = null;

            public InterpolatedStringScanner(Lexer lexer)
            {
                _lexer = lexer;

                _kind =
                    (_lexer.TextWindow.PeekChar(0), _lexer.TextWindow.PeekChar(1)) is ('$', '@') or ('@', '$')
                        ? InterpolatedStringKind.Verbatim
                        : InterpolatedStringKind.Normal;
            }

            private bool IsAtEnd()
            {
                return IsAtEnd(_kind is InterpolatedStringKind.Verbatim);
            }

            private bool IsAtEnd(bool allowNewline)
            {
                char ch = _lexer.TextWindow.PeekChar();
                return
                    (!allowNewline && SyntaxFacts.IsNewLine(ch)) ||
                    (ch == SlidingTextWindow.InvalidCharacter && _lexer.TextWindow.IsReallyAtEnd());
            }

            private void TrySetUnrecoverableError(SyntaxDiagnosticInfo error)
            {
                // only need to record the first error we hit
                Error ??= error;
            }

            internal void ScanInterpolatedStringLiteralTop(
                out InterpolatedStringKind kind,
                out Range openQuoteRange,
                ArrayBuilder<Interpolation>? interpolations,
                out Range closeQuoteRange)
            {
                kind = _kind;
                ScanInterpolatedStringLiteralStart(out openQuoteRange);
                ScanInterpolatedStringLiteralContents(interpolations);
                ScanInterpolatedStringLiteralEnd(out closeQuoteRange);
            }

            private void ScanInterpolatedStringLiteralStart(out Range openQuoteRange)
            {
                // Handles reading the start of the interpolated string literal (up to where the content begins)
                var start = _lexer.TextWindow.Position;
                if (_kind is InterpolatedStringKind.Verbatim)
                {
                    // skip past @$ or $@
                    _lexer.TextWindow.AdvanceChar(2);
                }
                else
                {
                    Debug.Assert(_lexer.TextWindow.PeekChar() == '$');
                    _lexer.TextWindow.AdvanceChar();
                }

                Debug.Assert(_lexer.TextWindow.PeekChar() == '"');
                _lexer.TextWindow.AdvanceChar();

                openQuoteRange = new Range(start, _lexer.TextWindow.Position);
            }

            private void ScanInterpolatedStringLiteralEnd(out Range closeQuoteRange)
            {
                // Handles reading the end of the interpolated string literal (after where the content ends)

                var closeQuotePosition = _lexer.TextWindow.Position;
                if (_lexer.TextWindow.PeekChar() != '"')
                {
                    Debug.Assert(IsAtEnd());
                    int position = IsAtEnd(allowNewline: true) ? _lexer.TextWindow.Position - 1 : _lexer.TextWindow.Position;
                    TrySetUnrecoverableError(_lexer.MakeError(position, 1, _kind is InterpolatedStringKind.Verbatim ? ErrorCode.ERR_UnterminatedStringLit : ErrorCode.ERR_NewlineInConst));
                }
                else
                {
                    // found the closing quote
                    _lexer.TextWindow.AdvanceChar(); // "
                }

                closeQuoteRange = new Range(closeQuotePosition, _lexer.TextWindow.Position);
            }

            private void ScanInterpolatedStringLiteralContents(ArrayBuilder<Interpolation>? interpolations)
            {
                while (true)
                {
                    if (IsAtEnd())
                    {
                        // error: end of line before end of string
                        return;
                    }

                    switch (_lexer.TextWindow.PeekChar())
                    {
                        case '"':
                            if (RecoveringFromRunawayLexing())
                            {
                                // When recovering from mismatched delimiters, we consume the next
                                // quote character as the close quote for the interpolated string. In
                                // practice this gets us out of trouble in scenarios we've encountered.
                                // See, for example, https://github.com/dotnet/roslyn/issues/44789
                                return;
                            }

                            if (_kind is InterpolatedStringKind.Verbatim && _lexer.TextWindow.PeekChar(1) == '"')
                            {
                                _lexer.TextWindow.AdvanceChar(2); // ""
                                continue;
                            }
                            // found the end of the string
                            return;
                        case '}':
                            var pos = _lexer.TextWindow.Position;
                            _lexer.TextWindow.AdvanceChar(); // }
                            // ensure any } characters are doubled up
                            if (_lexer.TextWindow.PeekChar() == '}')
                            {
                                _lexer.TextWindow.AdvanceChar(); // }
                            }
                            else
                            {
                                TrySetUnrecoverableError(_lexer.MakeError(pos, 1, ErrorCode.ERR_UnescapedCurly, "}"));
                            }
                            continue;
                        case '{':
                            if (_lexer.TextWindow.PeekChar(1) == '{')
                            {
                                _lexer.TextWindow.AdvanceChar(2); // {{
                            }
                            else
                            {
                                int openBracePosition = _lexer.TextWindow.Position;
                                _lexer.TextWindow.AdvanceChar();
                                ScanInterpolatedStringLiteralHoleBalancedText('}', isHole: true, out var colonRange);
                                int closeBracePosition = _lexer.TextWindow.Position;
                                if (_lexer.TextWindow.PeekChar() == '}')
                                {
                                    _lexer.TextWindow.AdvanceChar();
                                }
                                else
                                {
                                    TrySetUnrecoverableError(_lexer.MakeError(openBracePosition - 1, 2, ErrorCode.ERR_UnclosedExpressionHole));
                                }

                                interpolations?.Add(new Interpolation(
                                    new Range(openBracePosition, openBracePosition + 1),
                                    colonRange,
                                    new Range(closeBracePosition, _lexer.TextWindow.Position)));
                            }
                            continue;
                        case '\\':
                            if (_kind is InterpolatedStringKind.Verbatim)
                            {
                                goto default;
                            }

                            var escapeStart = _lexer.TextWindow.Position;
                            char ch = _lexer.ScanEscapeSequence(surrogateCharacter: out _);
                            if (ch is '{' or '}')
                            {
                                TrySetUnrecoverableError(_lexer.MakeError(escapeStart, _lexer.TextWindow.Position - escapeStart, ErrorCode.ERR_EscapedCurly, ch));
                            }

                            continue;
                        default:
                            // found some other character in the string portion
                            _lexer.TextWindow.AdvanceChar();
                            continue;
                    }
                }
            }

            private void ScanFormatSpecifier()
            {
                /*
                ## Grammar from spec:

                interpolation_format
                    : ':' interpolation_format_character+
                ;
                interpolation_format_character
                    : '<Any character except \" (U+0022), : (U+003A), { (U+007B) and } (U+007D)>'
                ;
                 */

                Debug.Assert(_lexer.TextWindow.PeekChar() == ':');
                _lexer.TextWindow.AdvanceChar();
                while (true)
                {
                    char ch = _lexer.TextWindow.PeekChar();
                    if (ch == '\\' && _kind is InterpolatedStringKind.Normal)
                    {
                        // normal string & char constants can have escapes
                        var pos = _lexer.TextWindow.Position;
                        ch = _lexer.ScanEscapeSequence(surrogateCharacter: out _);
                        if (ch is '{' or '}')
                        {
                            TrySetUnrecoverableError(_lexer.MakeError(pos, 1, ErrorCode.ERR_EscapedCurly, ch));
                        }
                    }
                    else if (ch == '"')
                    {
                        if (_kind is InterpolatedStringKind.Verbatim && _lexer.TextWindow.PeekChar(1) == '"')
                        {
                            _lexer.TextWindow.AdvanceChar(2); // ""
                        }
                        else
                        {
                            return; // premature end of string! let caller complain about unclosed interpolation
                        }
                    }
                    else if (ch == '{')
                    {
                        TrySetUnrecoverableError(_lexer.MakeError(_lexer.TextWindow.Position, 1, ErrorCode.ERR_UnexpectedCharacter, ch));
                        _lexer.TextWindow.AdvanceChar();
                    }
                    else if (ch == '}')
                    {
                        return; // end of interpolation
                    }
                    else if (IsAtEnd())
                    {
                        return; // premature end; let caller complain
                    }
                    else
                    {
                        _lexer.TextWindow.AdvanceChar();
                    }
                }
            }

            /// <summary>
            /// Scan past the hole inside an interpolated string literal, leaving the current character on the '}' (if any)
            /// </summary>
            private void ScanInterpolatedStringLiteralHoleBalancedText(char endingChar, bool isHole, out Range colonRange)
            {
                colonRange = default;
                while (true)
                {
                    char ch = _lexer.TextWindow.PeekChar();

                    // Note: within a hole newlines are always allowed.  The restriction on if newlines are allowed or not
                    // is only within a text-portion of the interpolated string.
                    if (IsAtEnd(allowNewline: true))
                    {
                        // the caller will complain
                        return;
                    }

                    switch (ch)
                    {
                        case '#':
                            // preprocessor directives not allowed.
                            TrySetUnrecoverableError(_lexer.MakeError(_lexer.TextWindow.Position, 1, ErrorCode.ERR_SyntaxError, endingChar.ToString()));
                            _lexer.TextWindow.AdvanceChar();
                            continue;
                        case '$':
                            {
                                var discarded = default(TokenInfo);
                                if (_lexer.TryScanInterpolatedString(ref discarded))
                                {
                                    continue;
                                }

                                goto default;
                            }
                        case ':':
                            // the first colon not nested within matching delimiters is the start of the format string
                            if (isHole)
                            {
                                Debug.Assert(colonRange.Equals(default(Range)));
                                colonRange = new Range(_lexer.TextWindow.Position, _lexer.TextWindow.Position + 1);
                                ScanFormatSpecifier();
                                return;
                            }

                            goto default;
                        case '}':
                        case ')':
                        case ']':
                            if (ch == endingChar)
                            {
                                return;
                            }

                            TrySetUnrecoverableError(_lexer.MakeError(_lexer.TextWindow.Position, 1, ErrorCode.ERR_SyntaxError, endingChar.ToString()));
                            goto default;
                        case '"':
                            if (RecoveringFromRunawayLexing())
                            {
                                // When recovering from mismatched delimiters, we consume the next
                                // quote character as the close quote for the interpolated string. In
                                // practice this gets us out of trouble in scenarios we've encountered.
                                // See, for example, https://github.com/dotnet/roslyn/issues/44789
                                return;
                            }

                            // handle string literal inside an expression hole.
                            ScanInterpolatedStringLiteralNestedString();
                            continue;

                        case '\'':
                            // handle character literal inside an expression hole.
                            ScanInterpolatedStringLiteralNestedString();
                            continue;
                        case '@':
                            {
                                var discarded = default(TokenInfo);
                                if (_lexer.TryScanAtStringToken(ref discarded))
                                    continue;

                                // Wasn't an @"" or @$"" string.  Just consume this as normal code.
                                goto default;
                            }
                        case '/':
                            switch (_lexer.TextWindow.PeekChar(1))
                            {
                                case '/':
                                    _lexer.ScanToEndOfLine();
                                    continue;
                                case '*':
                                    _lexer.ScanMultiLineComment(out _);
                                    continue;
                                default:
                                    _lexer.TextWindow.AdvanceChar();
                                    continue;
                            }
                        case '{':
                            // TODO: after the colon this has no special meaning.
                            ScanInterpolatedStringLiteralHoleBracketed('{', '}');
                            continue;
                        case '(':
                            // TODO: after the colon this has no special meaning.
                            ScanInterpolatedStringLiteralHoleBracketed('(', ')');
                            continue;
                        case '[':
                            // TODO: after the colon this has no special meaning.
                            ScanInterpolatedStringLiteralHoleBracketed('[', ']');
                            continue;
                        default:
                            // part of code in the expression hole
                            _lexer.TextWindow.AdvanceChar();
                            continue;
                    }
                }
            }

            /// <summary>
            /// The lexer can run away consuming the rest of the input when delimiters are mismatched. This is a test
            /// for when we are attempting to recover from that situation.  Note that just running into new lines will
            /// not make us think we're in runaway lexing.
            /// </summary>
            private bool RecoveringFromRunawayLexing() => Error != null;

            private void ScanInterpolatedStringLiteralNestedString()
            {
                var discarded = default(TokenInfo);
                _lexer.ScanStringLiteral(ref discarded, inDirective: false);
            }

            private void ScanInterpolatedStringLiteralHoleBracketed(char start, char end)
            {
                Debug.Assert(start == _lexer.TextWindow.PeekChar());
                _lexer.TextWindow.AdvanceChar();
                ScanInterpolatedStringLiteralHoleBalancedText(end, isHole: false, colonRange: out _);
                if (_lexer.TextWindow.PeekChar() == end)
                {
                    _lexer.TextWindow.AdvanceChar();
                }
                else
                {
                    // an error was given by the caller
                }
            }
        }
    }
}


text:
"""Unit tests for vtdb.tablet"""

import unittest

import mock

from net import gorpc
import utils
from vtdb import tablet

class TestRPCCallAndExtract(unittest.TestCase):
  """Tests rpc_call_and_extract_error is tolerant to various responses."""

  tablet_conn = tablet.TabletConnection('addr', 'type', 'keyspace', 'shard', 30, caller_id='dev')

  def test_reply_is_none(self):
    with mock.patch.object(self.tablet_conn, 'client', autospec=True) as mock_client:
      mock_client.call.return_value = gorpc.GoRpcResponse()
      self.tablet_conn.rpc_call_and_extract_error('method', 'req')

  def test_reply_is_empty_string(self):
    with mock.patch.object(self.tablet_conn, 'client', autospec=True) as mock_client:
      response = gorpc.GoRpcResponse()
      response.reply = ''
      mock_client.call.return_value = response
      self.tablet_conn.rpc_call_and_extract_error('method', 'req')

  def test_reply_is_string(self):
    with mock.patch.object(self.tablet_conn, 'client', autospec=True) as mock_client:
      response = gorpc.GoRpcResponse()
      response.reply = 'foo'
      mock_client.call.return_value = response
      self.tablet_conn.rpc_call_and_extract_error('method', 'req')

  def test_reply_is_dict(self):
    with mock.patch.object(self.tablet_conn, 'client', autospec=True) as mock_client:
      response = gorpc.GoRpcResponse()
      response.reply = {'foo': 'bar'}
      mock_client.call.return_value = response
      self.tablet_conn.rpc_call_and_extract_error('method', 'req')

  def test_reply_has_non_dict_err(self):
    with mock.patch.object(self.tablet_conn, 'client', autospec=True) as mock_client:
      response = gorpc.GoRpcResponse()
      response.reply = {'Err': 'foo'}
      mock_client.call.return_value = response
      with self.assertRaisesRegexp(gorpc.AppError, 'Missing error message'):
        self.tablet_conn.rpc_call_and_extract_error('method', 'req')

  def test_reply_has_missing_err_message(self):
    with mock.patch.object(self.tablet_conn, 'client', autospec=True) as mock_client:
      response = gorpc.GoRpcResponse()
      response.reply = {'Err': {'foo': 'bar'}}
      mock_client.call.return_value = response
      with self.assertRaisesRegexp(gorpc.AppError, 'Missing error message'):
        self.tablet_conn.rpc_call_and_extract_error('method', 'req')

  def test_reply_has_err_message(self):
    with mock.patch.object(self.tablet_conn, 'client', autospec=True) as mock_client:
      response = gorpc.GoRpcResponse()
      response.reply = {'Err': {'Message': 'bar'}}
      mock_client.call.return_value = response
      with self.assertRaisesRegexp(gorpc.AppError, "'bar', 'method'"):
        self.tablet_conn.rpc_call_and_extract_error('method', 'req')

if __name__ == '__main__':
  utils.main()

redpajama_set_name: RedPajamaGithub


text:
package guru.ashley.testyourself.lib;

/**
 * @author: Ashley Menhennett <ashleymenhennett@gmail.com>
 * @package: Test Yourself
 * @license: MIT
 */

import java.util.ArrayList;

/**
 * POJO class, used as a DTO
 */
public class Question {

    private String question;
    private ArrayList<String> answers;
    private String correctAnswer;

    public Question(String question, ArrayList<String> answers, String correctAnswer) {
        this.question = question;
        this.answers = answers;
        this.correctAnswer = correctAnswer;
    }

    public String getQuestion() {
        return question;
    }

    public void setQuestion(String question) {
        this.question = question;
    }

    public ArrayList<String> getAnswers() {
        return answers;
    }

    public void setAnswers(ArrayList<String> answers) {
        this.answers = answers;
    }

    public String getCorrectAnswer() {
        return correctAnswer;
    }

    public void setCorrectAnswer(String correctAnswer) {
        this.correctAnswer = correctAnswer;
    }

    @Override
    public String toString() {
        return "Question{" +
                "question='" + question + '\'' +
                ", answers=" + answers +
                ", correctAnswer='" + correctAnswer + '\'' +
                '}';
    }
}


text:
import { browser, element, by } from 'protractor';

export class Ng2TeslaRangeCalculatorPage {
  navigateTo() {
    return browser.get('/');
  }

  getParagraphText() {
    return element(by.css('app-root h1')).getText();
  }
}


text:
import logging
from twisted.internet import defer
from twisted.protocols.basic import FileSender
from twisted.python.failure import Failure
from zope.interface import implements
from lbrynet.interfaces import IQueryHandlerFactory, IQueryHandler, IBlobSender

log = logging.getLogger(__name__)

class BlobRequestHandlerFactory(object):
    implements(IQueryHandlerFactory)

    def __init__(self, blob_manager, wallet, payment_rate_manager):
        self.blob_manager = blob_manager
        self.wallet = wallet
        self.payment_rate_manager = payment_rate_manager

    ######### IQueryHandlerFactory #########

    def build_query_handler(self):
        q_h = BlobRequestHandler(self.blob_manager, self.wallet, self.payment_rate_manager)
        return q_h

    def get_primary_query_identifier(self):
        return 'requested_blob'

    def get_description(self):
        return "Blob Uploader - uploads blobs"

class BlobRequestHandler(object):
    implements(IQueryHandler, IBlobSender)
    PAYMENT_RATE_QUERY = 'blob_data_payment_rate'
    BLOB_QUERY = 'requested_blob'

    def __init__(self, blob_manager, wallet, payment_rate_manager):
        self.blob_manager = blob_manager
        self.payment_rate_manager = payment_rate_manager
        self.wallet = wallet
        self.query_identifiers = [self.PAYMENT_RATE_QUERY, self.BLOB_QUERY]
        self.peer = None
        self.blob_data_payment_rate = None
        self.read_handle = None
        self.currently_uploading = None
        self.file_sender = None
        self.blob_bytes_uploaded = 0

    ######### IQueryHandler #########

    def register_with_request_handler(self, request_handler, peer):
        self.peer = peer
        request_handler.register_query_handler(self, self.query_identifiers)
        request_handler.register_blob_sender(self)

    def handle_queries(self, queries):
        response = {}
        if self.PAYMENT_RATE_QUERY in queries:
            self._handle_payment_rate_query(response, queries[self.PAYMENT_RATE_QUERY])
        if self.BLOB_QUERY in queries:
            return self._handle_blob_query(response, queries[self.BLOB_QUERY])
        else:
            return defer.succeed(response)

    def _handle_payment_rate_query(self, response, query):
        if not self.handle_blob_data_payment_rate(query):
            response['blob_data_payment_rate'] = "RATE_TOO_LOW"
        else:
            response['blob_data_payment_rate'] = 'RATE_ACCEPTED'

    def _handle_blob_query(self, response, query):
        log.debug("Received the client's request to send a blob")
        response['incoming_blob'] = {}

        if self.blob_data_payment_rate is None:
            response['incoming_blob']['error'] = "RATE_UNSET"
            return defer.succeed(response)
        else:
            return self._send_blob(response, query)

    def _send_blob(self, response, query):
        d = self.blob_manager.get_blob(query, True)
        d.addCallback(self.open_blob_for_reading, response)
        return d

    def open_blob_for_reading(self, blob, response):
        def failure(msg):
            log.warning("We can not send %s: %s", blob, msg)
            response['incoming_blob']['error'] = "BLOB_UNAVAILABLE"
            return response
        if not blob.is_validated():
            return failure("blob can't be validated")
        read_handle = blob.open_for_reading()
        if read_handle is None:
            return failure("blob can't be opened")

        self.currently_uploading = blob
        self.read_handle = read_handle
        log.info("Sending %s to client", blob)
        response['incoming_blob']['blob_hash'] = blob.blob_hash
        response['incoming_blob']['length'] = blob.length
        return response

    ######### IBlobSender #########

    def send_blob_if_requested(self, consumer):
        if self.currently_uploading is not None:
            return self.send_file(consumer)
        return defer.succeed(True)

    def cancel_send(self, err):
        if self.currently_uploading is not None:
            self.currently_uploading.close_read_handle(self.read_handle)
        self.read_handle = None
        self.currently_uploading = None
        return err

    ######### internal #########

    def handle_blob_data_payment_rate(self, requested_payment_rate):
        if not self.payment_rate_manager.accept_rate_blob_data(self.peer, requested_payment_rate):
            return False
        else:
            self.blob_data_payment_rate = requested_payment_rate
            return True

    def send_file(self, consumer):

        def _send_file():
            inner_d = start_transfer()
            # TODO: if the transfer fails, check if it's because the connection was cut off.
            # TODO: if so, perhaps bill the client
            inner_d.addCallback(lambda _: set_expected_payment())
            inner_d.addBoth(set_not_uploading)
            return inner_d

        def count_bytes(data):
            self.blob_bytes_uploaded += len(data)
            self.peer.update_stats('blob_bytes_uploaded', len(data))
            return data

        def start_transfer():
            self.file_sender = FileSender()
            log.debug("Starting the file upload")
            assert self.read_handle is not None, "self.read_handle was None when trying to start the transfer"
            d = self.file_sender.beginFileTransfer(self.read_handle, consumer, count_bytes)
            return d

        def set_expected_payment():
            log.debug("Setting expected payment")
            if self.blob_bytes_uploaded != 0 and self.blob_data_payment_rate is not None:
                # TODO: explain why 2**20
                self.wallet.add_expected_payment(self.peer,
                                                 self.currently_uploading.length * 1.0 *
                                                 self.blob_data_payment_rate / 2**20)
                self.blob_bytes_uploaded = 0
            self.peer.update_stats('blobs_uploaded', 1)
            return None

        def set_not_uploading(reason=None):
            if self.currently_uploading is not None:
                self.currently_uploading.close_read_handle(self.read_handle)
                self.read_handle = None
                self.currently_uploading = None
            self.file_sender = None
            if reason is not None and isinstance(reason, Failure):
                log.info("Upload has failed. Reason: %s", reason.getErrorMessage())

        return _send_file()


text:
static ESCssParser *__currentParser = nil;

typedef NS_ENUM(NSUInteger, RuleType) {
    RuleTypeStyle,
    RuleTypeCharset,
    RuleTypeKeyframes,
    RuleTypeKeyframe
};

typedef NS_ENUM(NSUInteger, Flags) {
    InsideStyleSheet,
    InsideKeyframes,
    InsideRuleSet,
    InsideProperty,
    InsideValue
};

@interface ESCssParser () {
    NSMutableDictionary*    _styleSheet;
    NSMutableDictionary *   _activeKeyframes;
    NSMutableDictionary *   _activeRuleSet;
    NSMutableString *       _activeSelector;
    NSMutableString *       _activeKeyframesName;
    NSString *              _activePropertyName;

    struct {
        RuleType type;
        Flags flag;
        int lastToken;
    } _state;
}

- (void)cssScan:(const char *)text token:(int)token;

@end

void css_scan(const char *text, int token) {
    [__currentParser cssScan:text token:token];
}

@implementation ESCssParser

- (instancetype)init {
    self = [super init];
    if (self) {
        _activeSelector = [[NSMutableString alloc] init];
        _styleSheet = [[NSMutableDictionary alloc] init];
    }
    return self;
}

- (void)cssScan:(const char *)text token:(int)token {
    switch (token) {
        case S:
            return;
        case CHARSET_SYM: {
            _state.type = RuleTypeCharset;
            break;
        }
        case HASH:
        case IDENT: {
            if (_state.type == RuleTypeKeyframes) {
                if (_state.flag == InsideStyleSheet) {
                    if (_activeKeyframesName.length) {
                        [_activeKeyframesName appendString:@" "];
                    }
                    [_activeKeyframesName appendString:@(text)];
                } else if (_state.flag == InsideKeyframes) {
                    [_activeSelector appendString:@(text)];
                } else if (_state.flag == InsideRuleSet) {
                    _state.flag = InsideProperty;
                    _activePropertyName = @(text);
                } else if (_state.flag == InsideValue) {
                    NSMutableString *value = _activeRuleSet[_activePropertyName];
                    [value appendString:@(text)];
                }

            }
            else if (_state.type == RuleTypeStyle) {
                if (_state.flag == InsideStyleSheet) {
                    [_activeSelector appendString:@(text)];

                } else if (_state.flag == InsideRuleSet) {
                    _state.flag = InsideProperty;
                    _activePropertyName = @(text);
                } else if (_state.flag == InsideValue) {
                    NSMutableString *value = _activeRuleSet[_activePropertyName];
                    [value appendString:@(text)];
                }
            }
            break;
        }
        case FUNCTION: {
            NSMutableString *value = _activeRuleSet[_activePropertyName];
            [value appendString:@(text)];
            break;
        }
        case STRING:
        case PERCENTAGE:
        case EMS:
        case EXS:
        case LENGTH:
        case FREQ:
        case ANGLE:
        case NUMBER:
        case TIME:
        case URI: {
            if (_state.type == RuleTypeCharset) {
                printf("@charset: %s; \n", text);
            } else if (_state.flag == InsideValue) {
                NSMutableString *value = _activeRuleSet[_activePropertyName];
                if (value.length && _state.lastToken != FUNCTION) {
                    [value appendString:@" "];
                }
                [value appendString:@(text)];
            }
            break;
        }
        case UNKNOWN: {
            switch (text[0]) {
                case '{':
                    if (_state.type == RuleTypeStyle) {
                        _state.flag = InsideRuleSet;
                        _activeRuleSet = [[NSMutableDictionary alloc] init];
                        _activePropertyName = [[NSMutableString alloc] init];
                    } else if (_state.type == RuleTypeKeyframes) {
                        if (_state.flag == InsideStyleSheet) {
                            _state.flag = InsideKeyframes;
                            _activeKeyframes = [[NSMutableDictionary alloc] init];
                        } else if (_state.flag == InsideKeyframes) {
                            _state.flag = InsideRuleSet;
                            _activeRuleSet = [[NSMutableDictionary alloc] init];
                        }
                    }
                    break;
                case '}':
                    if (_state.type == RuleTypeStyle) {
                        _state.flag = InsideStyleSheet;
                        [self mergeStyleSheetFields:_activeRuleSet forProperty:_activeSelector];
                        _activeSelector = [[NSMutableString alloc] init];
                    } else if (_state.type == RuleTypeKeyframes) {
                        if (_state.flag == InsideKeyframes) {
                            _state.type = RuleTypeStyle;
                            _state.flag = InsideStyleSheet;
                            [self mergeStyleSheetFields:_activeKeyframes forProperty:_activeKeyframesName];
                        } else if (_state.flag == InsideRuleSet) {
                            _state.flag = InsideKeyframes;
                            _activeKeyframes[_activeSelector] = _activeRuleSet;
                            _activeSelector = [[NSMutableString alloc] init];
                        }
                    }
                    break;
                case '*':
                    [_activeSelector appendString:@(text)];
                    break;
                case ':':
                    if (_state.flag == InsideProperty) {
                        _state.flag = InsideValue;
                        NSMutableString *value = [[NSMutableString alloc] init];
                        _activeRuleSet[_activePropertyName] = value;
                    }
                    break;
                case '@': {
                    _state.type = RuleTypeKeyframes;
                    _activeKeyframesName = [[NSMutableString alloc] init];
                    break;
                }
                case ';': {
                    if (_state.type == RuleTypeCharset) {
                        _state.type = RuleTypeStyle;
                    } else if (_state.type == RuleTypeStyle) {
                        if (_state.flag == InsideValue) {
                            _state.flag = InsideRuleSet;
                            _activePropertyName = [[NSMutableString alloc] init];
                        }
                    } else if (_state.type == RuleTypeKeyframes) {
                        if (_state.flag == InsideValue) {
                            _state.flag = InsideRuleSet;
                            _activePropertyName = [[NSMutableString alloc] init];
                        }
                    }
                    break;
                }
                case ',': {
                    if (_state.flag == InsideValue) {
                        NSMutableString *value = _activeRuleSet[_activePropertyName];
                        [value appendString:@(text)];
                    }
                    break;
                }
                case '.': {
                    if (_state.flag == InsideStyleSheet) {
                        [_activeSelector appendString:@(text)];
                    }
                    break;
                }
                case ')': {
                    if (_state.flag == InsideValue) {
                        NSMutableString *value = _activeRuleSet[_activePropertyName];
                        [value appendString:@(text)];
                    }
                    break;
                }
                default:
                    printf("[%s] (%s)", text, cssTokenName[token]);
                    break;
            }
            break;
        }
        default:
            printf("[%s] (%s)", text, cssTokenName[token]);
            break;
    }
    _state.lastToken = token;

}

- (NSDictionary *)parseText:(NSString *)cssText {
    __currentParser = self;
    css_parse([cssText UTF8String]);
    return _styleSheet;
}

- (void)mergeStyleSheetFields:(id)fields forProperty:(id)property {
    NSMutableDictionary *existFields = _styleSheet[property];
    if ([existFields isKindOfClass:NSDictionary.class] && [fields isKindOfClass:NSDictionary.class]) {
        existFields = existFields.mutableCopy;
        [existFields addEntriesFromDictionary:(NSDictionary *)fields];
        fields = existFields;
    }

    _styleSheet[property] = fields;
}

@end


text:
This is where the Koding desktop app lives.

It is written in coffee-script and it's compiled when the app is built.

![app](http://i.imgur.com/V9g6eKs.jpg)
![dock](http://i.imgur.com/xDI1V7B.png)

## Development

```bash
$ cd koding/elektron
$ npm i
$ npm start
```

## Packaging Apps

We use `electron-packager` npm module to package apps. You can build and package apps for Mac, Windows and Linux.

```bash
$ cd koding/elektron
$ npm run app-<platform>
```
i.e.
```bash
$ npm run app-mac
$ npm run app-linux
$ npm run app-win
```

## App icons

App icons live in the `elektron/assets/icons` folder. Apps use different file formats per platform, for windows use `.ico` format, for mac use `.icns` format and linux needs a folder which includes different size `png` files (see elektron/assets/icons/square-logo-orange-linux folder).

There is a master `svg` file in the same folder to generate all the others. You can use external tools to automate that process e.g. [https://iconverticons.com](https://iconverticons.com)