text:
package suggestions
package gui

import scala.language.postfixOps
import scala.collection.mutable.ListBuffer
import scala.collection.JavaConverters._
import scala.concurrent._
import scala.concurrent.duration._
import scala.concurrent.ExecutionContext.Implicits.global
import scala.util.{ Try, Success, Failure }
import rx.subscriptions.CompositeSubscription
import rx.lang.scala.Observable
import observablex._
import search._
import scala.util.Failure

trait WikipediaApi {

  /** Returns a `Future` with a list of possible completions for a search `term`.
   */
  def wikipediaSuggestion(term: String): Future[List[String]]

  /** Returns a `Future` with the contents of the Wikipedia page for the given search `term`.
   */
  def wikipediaPage(term: String): Future[String]

  /** Returns an `Observable` with a list of possible completions for a search `term`.
   */
  def wikiSuggestResponseStream(term: String): Observable[List[String]] = ObservableEx(wikipediaSuggestion(term))

  /** Returns an `Observable` with the contents of the Wikipedia page for the given search `term`.
   */
  def wikiPageResponseStream(term: String): Observable[String] = ObservableEx(wikipediaPage(term))

  implicit class StringObservableOps(obs: Observable[String]) {

    /** Given a stream of search terms, returns a stream of search terms with spaces replaced by underscores.
     *
     * E.g. `"erik", "erik meijer", "martin` should become `"erik", "erik_meijer", "martin"`
     */
    def sanitized: Observable[String] = obs map {
      str => str.replace(' ', '_')
    }

  }

  implicit class ObservableOps[T](obs: Observable[T]) {

    /** Given an observable that can possibly be completed with an error, returns a new observable
     * with the same values wrapped into `Success` and the potential error wrapped into `Failure`.
     *
     * E.g. `1, 2, 3, !Exception!` should become `Success(1), Success(2), Success(3), Failure(Exception), !TerminateStream!`
     */
    def recovered: Observable[Try[T]] = Observable {
      observer =>
        val onNext = { t:T => observer.onNext(Success(t))}
        val onError = { t:Throwable => {observer.onNext(Failure(t)); observer.onCompleted}}
        val onComplete = { () => observer.onCompleted}
        obs.subscribe(onNext,onError,onComplete)

    }

    /** Emits the events from the `obs` observable, until `totalSec` seconds have elapsed.
     *
     * After `totalSec` seconds, if `obs` is not yet completed, the result observable becomes completed.
     *
     * Note: uses the existing combinators on observables.
     */
    def timedOut(totalSec: Long): Observable[T] = {
      obs.takeUntil(Observable.interval(totalSec second))
    }

    /** Given a stream of events `obs` and a method `requestMethod` to map a request `T` into
     * a stream of responses `S`, returns a stream of all the responses wrapped into a `Try`.
     * The elements of the response stream should reflect the order of their corresponding events in `obs`.
     *
     * E.g. given a request stream:
     *
     * 1, 2, 3, 4, 5
     *
     * And a request method:
     *
     * num => if (num != 4) Observable.just(num) else Observable.error(new Exception)
     *
     * We should, for example, get:
     *
     * Success(1), Success(2), Success(3), Failure(new Exception), Success(5)
     *
     *
     * Similarly:
     *
     * Observable(1, 2, 3).concatRecovered(num => Observable(num, num, num))
     *
     * should return:
     *
     * Observable(Success(1), Succeess(1), Succeess(1), Succeess(2), Succeess(2), Succeess(2), Succeess(3), Succeess(3), Succeess(3))
     */
    def concatRecovered[S](requestMethod: T => Observable[S]): Observable[Try[S]] = {
    	obs.map(requestMethod).map(_.recovered).concat
    }

  }

}


text:
<?php

/**
 * @file
 * Contains \Drupal\migrate_drupal\Tests\d6\MigrateCommentTypeTest.
 */

namespace Drupal\migrate_drupal\Tests\d6;

use Drupal\comment\Entity\CommentType;

/**
 * Upgrade comment type.
 *
 * @group migrate_drupal
 */
class MigrateCommentTypeTest extends MigrateDrupal6TestBase {

  static $modules = array('node', 'comment', 'text', 'filter');

  /**
   * {@inheritdoc}
   */
  protected function setUp() {
    parent::setUp();

    $this->installEntitySchema('node');
    $this->installEntitySchema('comment');
    $this->installConfig(['node', 'comment']);

    $this->loadDumps(['Variable.php', 'NodeType.php']);
    $this->executeMigration('d6_comment_type');
  }

  /**
   * Tests the Drupal 6 to Drupal 8 comment type migration.
   */
  public function testCommentType() {
    $comment_type = CommentType::load('comment');
    $this->assertIdentical('node', $comment_type->getTargetEntityTypeId());
    $comment_type = CommentType::load('comment_no_subject');
    $this->assertIdentical('node', $comment_type->getTargetEntityTypeId());
  }

}

redpajama_set_name: RedPajamaGithub


text:
package safehttp_test

import (
	"context"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"

	"github.com/google/go-cmp/cmp"
	"github.com/google/go-safeweb/safehttp"
	"github.com/google/go-safeweb/safehttp/safehttptest"
)

func TestIncomingRequestCookie(t *testing.T) {
	var tests = []struct {
		name      string
		req       *http.Request
		wantName  string
		wantValue string
	}{
		{
			name: "Basic",
			req: func() *http.Request {
				r := httptest.NewRequest(http.MethodGet, "/", nil)
				r.Header.Set("Cookie", "foo=bar")
				return r
			}(),
			wantName:  "foo",
			wantValue: "bar",
		},
		{
			name: "Multiple cookies with the same name",
			req: func() *http.Request {
				r := httptest.NewRequest(http.MethodGet, "/", nil)
				r.Header.Add("Cookie", "foo=bar; foo=xyz")
				r.Header.Add("Cookie", "foo=pizza")
				return r
			}(),
			wantName:  "foo",
			wantValue: "bar",
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			ir := safehttp.NewIncomingRequest(tt.req)
			c, err := ir.Cookie(tt.wantName)
			if err != nil {
				t.Errorf(`ir.Cookie(tt.wantName) got: %v want: nil`, err)
			}

			if got := c.Name(); got != tt.wantName {
				t.Errorf("c.Name() got: %v want: %v", got, tt.wantName)
			}

			if got := c.Value(); got != tt.wantValue {
				t.Errorf(`c.Value() got: %v want: %v`, got, tt.wantValue)
			}
		})
	}
}

func TestIncomingRequestCookieNotFound(t *testing.T) {
	r := httptest.NewRequest(http.MethodGet, "/", nil)
	ir := safehttp.NewIncomingRequest(r)
	if _, err := ir.Cookie("foo"); err == nil {
		t.Error(`ir.Cookie("foo") got: nil want: error`)
	}
}

func TestIncomingRequestCookies(t *testing.T) {
	var tests = []struct {
		name       string
		req        *http.Request
		wantNames  []string
		wantValues []string
	}{
		{
			name: "One",
			req: func() *http.Request {
				r := httptest.NewRequest(http.MethodGet, "/", nil)
				r.Header.Set("Cookie", "foo=bar")
				return r
			}(),
			wantNames:  []string{"foo"},
			wantValues: []string{"bar"},
		},
		{
			name: "Multiple",
			req: func() *http.Request {
				r := httptest.NewRequest(http.MethodGet, "/", nil)
				r.Header.Add("Cookie", "foo=bar; a=b")
				r.Header.Add("Cookie", "pizza=hawaii")
				return r
			}(),
			wantNames:  []string{"foo", "a", "pizza"},
			wantValues: []string{"bar", "b", "hawaii"},
		},
		{
			name:       "None",
			req:        httptest.NewRequest(http.MethodGet, "/", nil),
			wantNames:  []string{},
			wantValues: []string{},
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			ir := safehttp.NewIncomingRequest(tt.req)
			cl := ir.Cookies()

			if got, want := len(cl), len(tt.wantNames); got != want {
				t.Errorf("len(cl) got: %v want: %v", got, want)
			}

			for i, c := range cl {
				if got := c.Name(); got != tt.wantNames[i] {
					t.Errorf("c.Name() got: %v want: %v", got, tt.wantNames[i])
				}

				if got := c.Value(); got != tt.wantValues[i] {
					t.Errorf(`c.Value() got: %v want: %v`, got, tt.wantValues[i])
				}
			}
		})

	}
}

type pizza struct {
	val string
}

type pizzaKey string

func TestRequestWithContext(t *testing.T) {
	tests := []struct {
		name    string
		key     pizzaKey
		wantVal *pizza
		wantOk  bool
	}{
		{
			name:    "Value set for key",
			key:     pizzaKey("1234"),
			wantOk:  true,
			wantVal: &pizza{val: "margeritta"},
		},
		{
			name:    "Value not set for key",
			key:     pizzaKey("5678"),
			wantOk:  false,
			wantVal: nil,
		},
	}
	for _, test := range tests {
		req := httptest.NewRequest(safehttp.MethodGet, "/", nil)
		ir := safehttp.NewIncomingRequest(req)
		ir = ir.WithContext(context.WithValue(ir.Context(), pizzaKey("1234"), &pizza{val: "margeritta"}))

		got, ok := ir.Context().Value(test.key).(*pizza)
		if ok != test.wantOk {
			t.Errorf("type match: got %v, want %v", ok, test.wantOk)
		}
		if diff := cmp.Diff(test.wantVal, got, cmp.AllowUnexported(pizza{})); diff != "" {
			t.Errorf("ir.Context().Value(test.key): mismatch (-want +got): \n%s", diff)
		}
	}
}

func TestRequestSetNilContext(t *testing.T) {
	req := httptest.NewRequest(safehttp.MethodGet, "/", nil)
	ir := safehttp.NewIncomingRequest(req)

	defer func() {
		if r := recover(); r != nil {
			return
		}
		t.Errorf(`ir.SetContext(nil): expected panic`)
	}()

	// Avoids a linter complaint about a nil context being passed as argument.
	// In this case, we explicitly want to test that a nil context results in an error.
	var nilContext context.Context
	ir.WithContext(nilContext)
}

func TestIncomingRequestPostForm(t *testing.T) {
	methods := []string{
		safehttp.MethodPost,
		safehttp.MethodPut,
		safehttp.MethodPatch,
	}

	for _, m := range methods {
		t.Run(m, func(t *testing.T) {
			r := safehttptest.NewRequest(m, "/", strings.NewReader("a=b"))
			r.Header.Set("Content-Type", "application/x-www-form-urlencoded")

			f, err := r.PostForm()
			if err != nil {
				t.Errorf("r.PostForm() got: %v want: nil", err)
			}

			if got, want := f.String("a", ""), "b"; got != want {
				t.Errorf(`f.String("a", "") got: %q want: %q`, got, want)
			}

			if err := f.Err(); err != nil {
				t.Errorf("f.Err() got: %v want: nil", err)
			}
		})
	}
}

func TestIncomingRequestInvalidPostForm(t *testing.T) {
	tests := []struct {
		name string
		req  *safehttp.IncomingRequest
	}{
		{
			name: "GET method",
			req:  safehttptest.NewRequest(safehttp.MethodGet, "/", nil),
		},
		{
			name: "Wrong content type",
			req: func() *safehttp.IncomingRequest {
				r := safehttptest.NewRequest(safehttp.MethodPost, "/", nil)
				r.Header.Set("Content-Type", "blah/blah")
				return r
			}(),
		},
		{
			// Note that net/http.Request.ParseForm also parses url parameters and
			// the errors that occur are returned.
			name: "Invalid url parameter",
			req: func() *safehttp.IncomingRequest {
				r := safehttptest.NewRequest(safehttp.MethodPost, "http://foo.com/asdf?%xx=yy", nil)
				r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
				return r
			}(),
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			if _, err := tt.req.PostForm(); err == nil {
				t.Error("tt.req.PostForm() got: nil want: error")
			}
		})
	}
}

func TestIncomingRequestMultipartForm(t *testing.T) {
	methods := []string{
		safehttp.MethodPost,
		safehttp.MethodPut,
		safehttp.MethodPatch,
	}

	for _, m := range methods {
		t.Run(m, func(t *testing.T) {
			body := "--123\r\n" +
				"Content-Disposition: form-data; name=\"a\"\r\n" +
				"\r\n" +
				"b\r\n" +
				"--123--\r\n"
			r := safehttptest.NewRequest(m, "/", strings.NewReader(body))
			r.Header.Set("Content-Type", `multipart/form-data; boundary="123"`)

			f, err := r.MultipartForm(1000)
			if err != nil {
				t.Errorf("r.MultipartForm(1000) got: %v want: nil", err)
			}

			if got, want := f.String("a", ""), "b"; got != want {
				t.Errorf(`f.String("a", "") got: %q want: %q`, got, want)
			}

			if err := f.Err(); err != nil {
				t.Errorf("f.Err() got: %v want: nil", err)
			}
		})
	}
}

func TestIncomingRequestMultipartFormNegativeMemory(t *testing.T) {
	body := "--123\r\n" +
		"Content-Disposition: form-data; name=\"a\"\r\n" +
		"\r\n" +
		"b\r\n" +
		"--123--\r\n"
	r := safehttptest.NewRequest(safehttp.MethodPost, "/", strings.NewReader(body))
	r.Header.Set("Content-Type", `multipart/form-data; boundary="123"`)

	f, err := r.MultipartForm(-1)
	if err != nil {
		t.Errorf("r.MultipartForm(-1) got: %v want: nil", err)
	}

	if got, want := f.String("a", ""), "b"; got != want {
		t.Errorf(`f.String("a", "") got: %q want: %q`, got, want)
	}

	if err := f.Err(); err != nil {
		t.Errorf("f.Err() got: %v want: nil", err)
	}
}

func TestIncomingRequestInvalidMultipartForm(t *testing.T) {
	tests := []struct {
		name string
		req  *safehttp.IncomingRequest
	}{
		{
			name: "GET method",
			req:  safehttptest.NewRequest(safehttp.MethodGet, "/", nil),
		},
		{
			name: "Wrong content type",
			req: func() *safehttp.IncomingRequest {
				r := safehttptest.NewRequest(safehttp.MethodPost, "/", nil)
				r.Header.Set("Content-Type", "blah/blah")
				return r
			}(),
		},
		{
			// Note that net/http.Request.ParseMultipartForm also parses url parameters
			// and the errors that occur are returned.
			name: "Invalid url parameter",
			req: func() *safehttp.IncomingRequest {
				r := safehttptest.NewRequest(safehttp.MethodPost, "http://foo.com/asdf?%xx=yy", nil)
				r.Header.Set("Content-Type", "multipart/form-data")
				return r
			}(),
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			_, err := tt.req.MultipartForm(1000)
			if err == nil {
				t.Error("tt.req.ir.MultipartForm(1000) got: nil want: error")
			}
		})
	}
}

func TestIncomingRequestMultipartFileUpload(t *testing.T) {
	body := "--123\r\n" +
		"Content-Disposition: form-data; name=\"file\"; filename=\"myfile\"\r\n" +
		"\r\n" +
		"file content\r\n" +
		"--123--\r\n"
	r := safehttptest.NewRequest(safehttp.MethodPost, "/", strings.NewReader(body))
	r.Header.Set("Content-Type", `multipart/form-data; boundary="123"`)

	f, err := r.MultipartForm(1024)
	if err != nil {
		t.Errorf("r.MultipartForm(1024): got err %v", err)
	}

	fhs := f.File("file")
	if fhs == nil {
		t.Error(`f.File("file"): got nil, want file header`)
	}
	defer f.RemoveFiles()

	file, err := fhs[0].Open()
	if err != nil {
		t.Fatalf("fhs[0].Open(): got err %v, want nil", err)
	}

	content := make([]byte, 12)
	file.Read(content)
	if want, got := "file content", string(content); want != got {
		t.Errorf("file.Read(content): got %s, want %s", got, want)
	}
}

func TestIncomingRequestMultipartFormAndFileUpload(t *testing.T) {
	body := "--123\r\n" +
		"Content-Disposition: form-data; name=\"key\"\r\n" +
		"\r\n" +
		"12\r\n" +
		"--123\r\n" +
		"Content-Disposition: form-data; name=\"file\"; filename=\"myfile\"\r\n" +
		"\r\n" +
		"file content\r\n" +
		"--123--\r\n"
	r := safehttptest.NewRequest(safehttp.MethodPost, "/", strings.NewReader(body))
	r.Header.Set("Content-Type", `multipart/form-data; boundary="123"`)

	f, err := r.MultipartForm(1024)
	if err != nil {
		t.Errorf("r.MultipartForm(1024): got err %v", err)
	}

	if want, got := int64(12), f.Int64("key", 0); want != got {
		t.Errorf(`f.Int64("key", 0): got %d, want %d`, got, want)
	}
	if err := f.Err(); err != nil {
		t.Errorf("f.Err(): got err %v", err)
	}

	fhs := f.File("file")
	if fhs == nil {
		t.Error(`f.File("file"): got nil, want file header`)
	}
	defer f.RemoveFiles()

	file, err := fhs[0].Open()
	if err != nil {
		t.Fatalf("fhs[0].Open(): got err %v, want nil", err)
	}

	content := make([]byte, 12)
	file.Read(content)
	if want, got := "file content", string(content); want != got {
		t.Errorf("file.Read(content): got %s, want %s", got, want)
	}
}

func TestIncomingRequestFileUploadMissingContent(t *testing.T) {
	body := "--123\r\n" +
		"Content-Disposition: form-data; name=\"file\"; filename=\"myfile\"\r\n" +
		"\r\n" +
		"--123--\r\n"
	r := safehttptest.NewRequest(safehttp.MethodPost, "/", strings.NewReader(body))
	r.Header.Set("Content-Type", `multipart/form-data; boundary="123"`)

	f, err := r.MultipartForm(1024)
	if err != nil {
		t.Errorf("r.MultipartForm(1024): got err %v", err)
	}

	fhs := f.File("file")
	if fhs == nil {
		t.Error(`f.File("file"): got nil, want file header`)
	}
	defer f.RemoveFiles()

	file, err := fhs[0].Open()
	if err != nil {
		t.Fatalf("fhs[0].Open(): got err %v, want nil", err)
	}

	content := make([]byte, 0)
	file.Read(content)
	if want, got := "", string(content); want != got {
		t.Errorf("file.Read(content): got %s, want %s", got, want)
	}
}


text:
<?php

namespace RAPIBundle\DataMapper\Annotation;

/**
 * Class Int
 * @package RAPIBundle\DataMapper\Annotation
 * @Annotation
 */
final class Int extends Annotation
{
    /**
     * @param $value
     * @return int|null
     */
    public function convert($value)
    {
        if ($value === null) {
            return null;
        }

        return (int)$value;
    }
}


text:
{% extends "base.html" %}
{% block meta %}
    <meta name="description" content="{{category_description}}"/>
    {% if category_url_name == 'projects' %}
    <link rel="canonical" href="{{web_protocol}}{{domain}}projects/">
    {% else %}
    <link rel="canonical" href="{{web_protocol}}{{domain}}blog/category/{{category_url_name}}/">
    {% endif %}
    <title>{{title}}</title>
{% endblock %}
{% block css %}
    table, td, th {
        text-align: left;
    }

    table {
        border-collapse: collapse;
        width: 100%;
    }

    th {
        padding: 15px;
    }
    th, td {
        border-bottom: 1px solid #ddd;

    }

    tr:hover {
        background-color: #ddd;
    }

    #post-table a {
        display: block;
        color: black;
        text-decoration: none;
        padding: 15px;
     }

{% endblock %}
{% block content %}

{{category_name}}

    {% if is_admin %}
    <button type="submit">Add Post</button>
    <button type="submit">Edit Category</button>
    {% endif %}

                Title

        {% for post in posts %}

                {{post.title}}

        {% endfor %}

{% endblock %}


text:
require 'psych'

# Read YAML files and remember where each value came from.
#
# Objects behave like normal in most respects. Objects that implement
# Traceable can be asked for their position by calling file(), line(),
# column() and byte().
#
# If the class attribute TraceableString.debug is set, +inspect+ and
# +to_yaml+ output position information for each atom, in the case of
# +to_yaml+ separated from its value by the string " =^.^= ".
#
# Example:
#
#   yaml = "---
#   foo:
#     bar: 1
#     baz:
#       - gazonk
#       - foobar"
#   handler = PositionHandler.new("<STDIN>")
#   parser = Psych::Parser.new(handler)
#   handler.parser = parser
#   parser.parse(yaml)
#   visitor = PositionVisitor.new
#   tree = visitor.accept(handler.root)
#
#   tree[0]['foo']['bar']
#   => "1"
#   tree[0]['foo']['bar'].file
#   => "<STDIN>"
#   tree[0]['foo']['bar'].line
#   => 3
#   tree[0]['foo']['bar'].column
#   => 2
#
#   puts tree[0].to_yaml
#   ---
#   foo:
#     bar: 1
#     baz:
#     - gazonk
#     - foobar
#
#   TraceableString.debug = true
#   puts tree[0].to_yaml.gsub(' =^.^= ', '  # ')
#   ---
#   foo  # <STDIN> (line 1, column 4):
#     bar  # <STDIN> (line 2, column 6): 1  # <STDIN> (line 3, column 2)
#     baz  # <STDIN> (line 3, column 6):
#     - gazonk  # <STDIN> (line 5, column 4)
#     - foobar  # <STDIN> (line 6, column 0)

# Attributes required to trace the origin of a value.
module Traceable
  attr_accessor :file
  attr_accessor :byte
  attr_accessor :line
  attr_accessor :column
end

# A string that remembers the source of its value, and can output it
# again when serialised to YAML.
class TraceableString < String
  include Traceable

  def encode_with(coder)
    coder.tag = nil
    coder.scalar = self.to_str
    if debug?
      # LibYAML, the C YAML library which underlies Ruby's Psych
      # library, does not handle comments at all. The parser ignores
      # them and the emitter cannot write them. Thus, to output the
      # sourcing information in a manner that is at least semi-sane,
      # we need to put it in the actual value, behind some sort of
      # separator.
      #
      # The separator needs to be representable in Latin-1, otherwise
      # LibYAML quotes it. It needs to be non-breaking, otherwise
      # LibYAML will break here to wrap at 80 characters. It cannot
      # have any special meaning in YAML (including the quote
      # character), otherwise LibYAML quotes it. It shouldn't appear
      # in real data, sine we'll need to substitute all instances of
      # it.
      #
      # Also, I like cats, even ASCII ones.
      coder.scalar += " =^.^= #{@file} (line #{@line}, column #{@column})"
    end
  end

  def inspect
    if debug?
      '"%s" (%s, line: %i, col: %i, byte: %i)' %
        [self.to_str, @file, @line, @column, @byte]
    else
      super
    end
  end

  def self.debug=(maybe)
    @@debug = maybe
  end

  def self.debug
    @@debug ||= false
  end

  private

  def debug?
    self.class.debug
  end
end

# Make the nodes in Psych's YAML parse tree track their positions.
class Psych::Nodes::Node
  include Traceable
end

# Extend the parser to remember the position of each object.
class PositionHandler < Psych::TreeBuilder
  # The handler needs access to the parser in order to call mark
  attr_accessor :parser

  # +filename+ is the name of the source file the YAML structure will
  # be parsed from. It is only copied into parsed objects, not
  # interpreted.
  def initialize(filename)
    super()
    @file = filename
  end

  # Copy a parser position from a +Psych::Parser::Mark+ to a parse
  # tree node.
  def record_position(node, mark)
    node.extend Traceable
    node.file = @file
    node.byte = mark.index
    node.line = mark.line
    node.column = mark.column
    node
  end

  def start_mapping(anchor, tag, implicit, style)
    record_position(super, parser.mark)
  end

  def start_sequence(anchor, tag, implicit, style)
    record_position(super, parser.mark)
  end

  def scalar(value, anchor, tag, plain, quoted, style)
    record_position(super, parser.mark)
  end
end

# Extend the Ruby structure builder to remeber each object's position.
class PositionVisitor < Psych::Visitors::ToRuby
  # Copy a parser position from a parse tree node to a primitive
  # object.
  def record_position(s, o)
    s.extend Traceable
    s.file = o.file
    s.byte = o.byte
    s.line = o.line
    s.column = o.column
    s
  end

  # rubocop:disable Style/MethodName
  def visit_Psych_Nodes_Scalar o
    # Primitive YAML values can be either strings or integers. Ruby
    # integers cannot be extended, so convert everything to strings
    # before inserting position information.
    record_position(TraceableString.new(String(super)), o)
  end

  def visit_Psych_Nodes_Sequence o
    record_position(super, o)
  end

  def visit_Psych_Nodes_Mapping o
    record_position(super, o)
  end
  # rubocop:enable Style/MethodName
end

module TraceableYAML
  # Parse a YAML document from the string +doc+, tagging each value
  # with the source +tag+, and return a Ruby object tree representing
  # the result.
  def self.parse(doc, tag)
    handler = PositionHandler.new(tag)
    parser = Psych::Parser.new(handler)
    handler.parser = parser
    parser.parse doc
    if PositionVisitor.respond_to?(:create)
      # Ruby 2.1 and above
      visitor = PositionVisitor.create
    else
      # Ruby 2.0
      visitor = PositionVisitor.new
    end
    tree = visitor.accept(handler.root)
    tree[0]
  end

  # Load a YAML document from the file +path+, tagging each value with
  # the source +tag+, and return a Ruby object tree representing the
  # result.
  def self.load_file(path, tag)
    File.open(path) do |f|
      parse(f.read, tag)
    end
  end
end


text:
import React, {Component} from 'react'
import { Icon, Card, Progress } from 'antd'
import CountUp from 'react-countup'
import styles from './numberCard.less'

class NumberCard extends Component {

  state = {
    percent: 0
  }

  increase(count) {
    let percent = this.state.percent
    if(percent < count) {
      percent++
      if (percent > 100) {
        percent = 100
      }
      this.setState({ percent })
    } else {
      clearInterval(this.countdown)
    }

  }

  componentDidMount() {
    const { percent } = this.props
    this.countdown = setInterval(() => this.increase(percent), 25)
  }

  componentWillUnmount() {
    clearInterval(this.countdown)
  }

  render() {
    const { icon, color, title, number, countUp } = this.props
    const { percent } = this.state
    return (
      <Card className={styles.numberCard} bordered={false} bodyStyle={{padding: 0}}>

          <Icon className={styles.iconWarp} style={{ backgroundColor : color }} type={icon} />

{title || 'No Title'}

            <Progress percent={percent} strokeWidth={3} />

              <CountUp
                start={0}
                end={number}
                duration={2.75}
                useEasing
                useGrouping
                separator=','
                {...countUp || {}}
              />

      </Card>
    )
  }
}

export default NumberCard


text:
var guide = false;
var active = false;
var scrollBool = true;
var viewPortWidth = -1;

		$(function(){

			$.fn.fadeInWithDelay = function(){
                    var delay = 0;
                    return this.each(function(){
                        $(this).delay(delay).animate({opacity:1}, 2000);
                        delay += 100;
                    });
                };

	$('.main').scrollPagination({
		'contentPage': 'data.html', // the url you are fetching the results
		'contentData': 'abin=Abin', // these are the variables you can pass to the request, for example: children().size() to know which page you are
		'scrollTarget': $(window), // who gonna scroll? in this example, the full window
		'heightOffset': 1, // it gonna request when scroll is 10 pixels before the page ends
		'beforeLoad': function(){ // before load function, you can display a preloader div
			//$('#loading').fadeIn();
			NProgress.start();
		},
		'afterLoad': function(elementsLoaded){ // after loading content, you can use this function to animate your new elements
			 $('#loading').fadeOut();
			 var i = 0;
			 $(elementsLoaded).fadeInWithDelay();
			 if ($('.main').children().size() > 2){ // if more than 10 results already loaded, then stop pagination (only for testing)
			 	$('#nomoreresults').fadeIn();
				$('.main').stopScrollPagination();
			 }
			 NProgress.done();
			 LoadGvidocThumbnails('div.ajaxtitle');

			 if(!guide)
			 {
			 	$('div.videoAssembly').css('margin-left', '1%');
			 }
			 else
			 {
			 	$('div.videoAssembly').css('margin-left', '1%');
			 }
		}
	});
});

/*
jQuery(window).resize(function () {
        if (jQuery(window).height < 500) {
            console.log('Changed ++');
        }
        else {
        	console.log('Changed --');
            //jQuery(".top-menu").css("display", "block");
        }
    });
*/

		$( document ).ready(function() {

			viewPortWidth = $( window ).width();

			$('div.side').css('display', 'none');
			var temp = $('#searchInput > input[type="text"]').css('width');
			var defaultSide = $('div.side').css('width');

			//console.log(defaultSide);
			//$('div.videoAssembly').css('margin-left', '30px');

			LoadGvidocThumbnails();

		// Side Bar Animation  Script
		$('#start').on('click', function(e) {
			console.log("Guide Engine :"+guide);
			if(guide)
			{
			$('nav.dr-menu').removeClass('dr-menu-open');
			$('a.dr-label').hide();
			$('div.side').animate({ width: "-1px", opacity: "0.0"}, 240);

			setTimeout( function()
			{
			//$('div.videoAssembly').css('margin-left', '30px');
			//$('div.videoAssembly').css('margin-right', '2%');
			$('#start').css('color', '');
			$('div.side').css('display', 'none');
			}, 250);

			guide = false;
			console.log("Hide");
			}
			else
			{

			$('div.side').animate({ width: ""+defaultSide, opacity: "1.0"}, 240);

			//$('div.videoAssembly').css('margin-left', '23%');
			//$('div.videoAssembly').css('margin-right', '1%');

			$('#start').css('color', 'red');
			$('div.side').css('width', '0px');

			$('div.side').css('display', '');
			$('a.dr-label').show();

			setTimeout( function() {
				$('nav.dr-menu').addClass('dr-menu-open');
			}, 60);

			guide = true;
			console.log("Shown");
			}
		});

		$('span.dr-icon-menu').on('click', function(e) {
			if(guide)
			{
			$('nav.dr-menu').removeClass('dr-menu-open');
			$('a.dr-label').hide();
			$('div.side').animate({ width: "-1px", opacity: "0.0"}, 240);
			setTimeout( function()
			{
			//$('div.videoAssembly').css('margin-left', '30px');
			//$('div.videoAssembly').css('margin-right', '2%');
			$('#start').css('color', '');
			$('div.side').css('display', 'none');
			}, 250);
			guide = false;
			}
		});

		//Search Bar Animation JQuery
		$('#searchInput > input[type="text"]').on('focus', function(e) {
			if(viewPortWidth > 700)
				$(this).animate({ width: "350px"}, 500);
		});

		$('#searchInput > input[type="text"]').on('blur', function(e) {
			if(viewPortWidth > 700)
				$(this).animate({ width: ""+temp}, 500);
		});

		$( window ).scroll(function() {
  			var scrollBool = $('div.branding').visible( true );
  			if(scrollBool)
  			{
  				$('div.side').css({ "margin-top": "-64px", "min-height": "95%" });
  			}
  			else
  			{
  				$('div.side').css({ "margin-top": "-140px", "min-height": "100%" });
  			}
		});

		$(window).on('resize', function(e) {
  			// do your stuff
  			viewPortWidth = $( window ).width();

	});

});


text:
describe 'adapter_daybreak', adapter: :Daybreak do
  moneta_build do
    Moneta::Adapters::Daybreak.new(file: File.join(tempdir, "adapter_daybreak"))
  end

  moneta_specs ADAPTER_SPECS.without_multiprocess.returnsame.with_each_key
end


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Ztop.Todo.Model
{
    [Table("ipad_invoices")]
    public class iPadInvoice
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int ID { get; set; }
        public DateTime Time { get; set; }
        public string Number { get; set; }
        public double Money { get; set; }
        public string File { get; set; }
        [NotMapped]
        public int Count
        {
            get
            {
                if (iPads == null)
                {
                    return 0;
                }
                else
                {
                    return iPads.Count;
                }
            }
        }
        public string Buyer { get; set; }
        public string Enter { get; set; }
        [NotMapped]
        public List<Register_iPad> Relations { get; set; }
        [NotMapped]
        public List<iPad> iPads
        {
            get
            {
                if (Relations == null)
                {
                    return null;
                }
                return Relations.Select(e => e.iPad).ToList();
            }
        }
    }
}


text:
"""
Copyright 2018 Dean Hall.  See LICENSE for details.

dpp.py - the Dining Philosopher's Problem
         implementation translated from Chaper 9.2 of PSiCC
         [https://newcontinuum.dl.sourceforge.net/project/qpc/doc/PSiCC2.pdf]
"""

import asyncio
import random

import pq

N_PHILO = 10

pq.Signal.register("EAT")
pq.Signal.register("DONE")
pq.Signal.register("TERMINATE")
pq.Signal.register("HUNGRY")

def PHILO_ID(act):
    global philo
    return philo.index(act)

def RIGHT(n):
    return (n + N_PHILO - 1) % N_PHILO

def LEFT(n):
    return (n + 1) % N_PHILO

def THINK_TIME():
    return random.randrange(1, 9)

def EAT_TIME():
    return random.randrange(1, 9)

class Table(pq.Ahsm):
    def __init__(self, initialState):
        super(Table, self).__init__(initialState)
        self.fork = ["FREE",] * N_PHILO
        self.isHungry = [False,] * N_PHILO

    def initial(self, event):
        pq.Framework.subscribe("DONE", self)
        pq.Framework.subscribe("TERMINATE", self)
        return self.tran(self, Table.serving)

    def serving(self, event):
        sig = event.signal
        if sig == pq.Signal.HUNGRY:
            # BSP.busyDelay()
            n = event.value
            assert n < N_PHILO and not self.isHungry[n]
            print(n, "hungry")
            m = LEFT(n)
            if self.fork[m] == "FREE" and self.fork[n] == "FREE":
                self.fork[m] = "USED"
                self.fork[n] = "USED"
                e = pq.Event(pq.Signal.EAT, n)
                pq.Framework.publish(e)
                print(n, "eating")
            else:
                self.isHungry[n] = True
            return self.handled(self, event)

        elif sig == pq.Signal.DONE:
            # BSP.busyDelay()
            n = event.value
            assert n < N_PHILO and not self.isHungry[n]
            print(n, "thinking")
            m = LEFT(n)
            assert self.fork[n] == "USED" and self.fork[m] == "USED"
            self.fork[m] = "FREE"
            self.fork[n] = "FREE"
            m = RIGHT(n)
            if self.isHungry[m] and self.fork[m] == "FREE":
                self.fork[n] = "USED"
                self.fork[m] = "USED"
                self.isHungry[m] = False
                e = pq.Event(pq.Signal.EAT, m)
                pq.Framework.publish(e)
                print(m, "eating")
            m = LEFT(n)
            n = LEFT(m)
            if self.isHungry[m] and self.fork[n] == "FREE":
                self.fork[m] = "USED"
                self.fork[n] = "USED"
                self.isHungry[m] = False
                e = pq.Event(pq.Signal.EAT, m)
                pq.Framework.publish(e)
                print(m, "eating")
            return self.handled(self, event)

        elif sig == pq.Signal.TERMINATE:
            pq.Framework.stop()

        return self.super(self, self.top)

class Philo(pq.Ahsm):
    def initial(self, event):
        self.timeEvt = pq.TimeEvent("TIMEOUT")
        pq.Framework.subscribe("EAT", self)
        return self.tran(self, Philo.thinking)

    def thinking(self, event):
        sig = event.signal
        if sig == pq.Signal.ENTRY:
            self.timeEvt.postIn(self, THINK_TIME())
            status = self.handled(self, event)

        elif sig == pq.Signal.TIMEOUT:
            status = self.tran(self, Philo.hungry)

        elif sig == pq.Signal.EAT or sig == pq.Signal.DONE:
            assert event.value != PHILO_ID(self)
            status = self.handled(self, event)

        else:
            status = self.super(self, self.top)
        return status

    def hungry(self, event):
        sig = event.signal
        if sig == pq.Signal.ENTRY:
            e = pq.Event(pq.Signal.HUNGRY, PHILO_ID(self))
            pq.Framework.post(e, "Table")
            status = self.handled(self, event)

        elif sig == pq.Signal.EAT:
            if event.value == PHILO_ID(self):
                status = self.tran(self,Philo.eating)
            else:
                status = self.super(self, self.top) # UNHANDLED

        elif sig == pq.Signal.DONE:
            assert event.value != PHILO_ID(self)
            status = self.handled(self, event)

        else:
            status = self.super(self, self.top)
        return status

    def eating(self, event):
        sig = event.signal
        if sig == pq.Signal.ENTRY:
            self.timeEvt.postIn(self, EAT_TIME())
            status = self.handled(self, event)

        elif sig == pq.Signal.EXIT:
            e = pq.Event(pq.Signal.DONE, PHILO_ID(self))
            pq.Framework.publish(e)
            status = self.handled(self, event)

        elif sig == pq.Signal.TIMEOUT:
            status = self.tran(self,Philo.thinking)

        elif sig == pq.Signal.EAT or sig == pq.Signal.DONE:
            assert event.value != PHILO_ID(self)
            status = self.handled(self, event)

        else:
            status = self.super(self, self.top)
        return status

def main():
    global philo

    table = Table(Table.initial)
    table.start(0)

    philo = []
    for n in range(N_PHILO):
        p = Philo(Philo.initial)
        p.start(n+1)
        philo.append(p)

    loop = asyncio.get_event_loop()
    loop.run_forever()
    loop.close()

if __name__ == "__main__":
    main()


text:
<?php

namespace App\Http\Logics;

class StoryLogic extends Logic
{

}


text:
/* Sticky footer styles
-------------------------------------------------- */
html {
  position: relative;
  min-height: 100%;
}

body {
  /* Margin bottom by footer height */
  margin-bottom: 60px;
}

.footer {
  position: absolute;
  bottom: 0;
  width: 100%;
  /* Set the fixed height of the footer here */
  height: 60px;
  background-color: #f5f5f5;
}

.container .text-muted {
  margin: 20px 0;
}

.list-group-item {
  border-radius: 0 !important;
}

.list-group-item:last-child {
  border-width: 1px 0 !important;
}


text:
    #pragma interface "textctrl.h"
#endif

class WXDLLEXPORT wxTextCtrl : public wxTextCtrlBase
{
public:
    // creation
    // --------

    wxTextCtrl() { Init(); }
    wxTextCtrl(wxWindow *parent, wxWindowID id,
               const wxString& value = wxEmptyString,
               const wxPoint& pos = wxDefaultPosition,
               const wxSize& size = wxDefaultSize,
               long style = 0,
               const wxValidator& validator = wxDefaultValidator,
               const wxString& name = wxTextCtrlNameStr)
    {
        Init();

        Create(parent, id, value, pos, size, style, validator, name);
    }
    ~wxTextCtrl();

    bool Create(wxWindow *parent, wxWindowID id,
                const wxString& value = wxEmptyString,
                const wxPoint& pos = wxDefaultPosition,
                const wxSize& size = wxDefaultSize,
                long style = 0,
                const wxValidator& validator = wxDefaultValidator,
                const wxString& name = wxTextCtrlNameStr);

    // implement base class pure virtuals
    // ----------------------------------

    virtual wxString GetValue() const;
    virtual void SetValue(const wxString& value);

    virtual wxString GetRange(long from, long to) const;

    virtual int GetLineLength(long lineNo) const;
    virtual wxString GetLineText(long lineNo) const;
    virtual int GetNumberOfLines() const;

    virtual bool IsModified() const;
    virtual bool IsEditable() const;

    virtual void GetSelection(long* from, long* to) const;

    // operations
    // ----------

    // editing
    virtual void Clear();
    virtual void Replace(long from, long to, const wxString& value);
    virtual void Remove(long from, long to);

    // load the controls contents from the file
    virtual bool LoadFile(const wxString& file);

    // clears the dirty flag
    virtual void MarkDirty();
    virtual void DiscardEdits();

    virtual void SetMaxLength(unsigned long len);

    // writing text inserts it at the current position, appending always
    // inserts it at the end
    virtual void WriteText(const wxString& text);
    virtual void AppendText(const wxString& text);

#ifdef __WIN32__
    virtual bool EmulateKeyPress(const wxKeyEvent& event);
#endif // __WIN32__

#if wxUSE_RICHEDIT
    // apply text attribute to the range of text (only works with richedit
    // controls)
    virtual bool SetStyle(long start, long end, const wxTextAttr& style);
    virtual bool SetDefaultStyle(const wxTextAttr& style);
    virtual bool GetStyle(long position, wxTextAttr& style);
#endif // wxUSE_RICHEDIT

    // translate between the position (which is just an index in the text ctrl
    // considering all its contents as a single strings) and (x, y) coordinates
    // which represent column and line.
    virtual long XYToPosition(long x, long y) const;
    virtual bool PositionToXY(long pos, long *x, long *y) const;

    virtual void ShowPosition(long pos);
    virtual wxTextCtrlHitTestResult HitTest(const wxPoint& pt, long *pos) const;
    virtual wxTextCtrlHitTestResult HitTest(const wxPoint& pt,
                                            wxTextCoord *col,
                                            wxTextCoord *row) const
    {
        return wxTextCtrlBase::HitTest(pt, col, row);
    }

    // Clipboard operations
    virtual void Copy();
    virtual void Cut();
    virtual void Paste();

    virtual bool CanCopy() const;
    virtual bool CanCut() const;
    virtual bool CanPaste() const;

    // Undo/redo
    virtual void Undo();
    virtual void Redo();

    virtual bool CanUndo() const;
    virtual bool CanRedo() const;

    // Insertion point
    virtual void SetInsertionPoint(long pos);
    virtual void SetInsertionPointEnd();
    virtual long GetInsertionPoint() const;
    virtual wxTextPos GetLastPosition() const;

    virtual void SetSelection(long from, long to);
    virtual void SetEditable(bool editable);

    // Caret handling (Windows only)

    bool ShowNativeCaret(bool show = true);
    bool HideNativeCaret() { return ShowNativeCaret(false); }

    // Implementation from now on
    // --------------------------

    virtual void SetWindowStyleFlag(long style);

    virtual void Command(wxCommandEvent& event);
    virtual bool MSWCommand(WXUINT param, WXWORD id);
    virtual WXHBRUSH MSWControlColor(WXHDC hDC, WXHWND hWnd);

#if wxUSE_RICHEDIT
    virtual bool MSWOnNotify(int idCtrl, WXLPARAM lParam, WXLPARAM *result);

    int GetRichVersion() const { return m_verRichEdit; }
    bool IsRich() const { return m_verRichEdit != 0; }

    // rich edit controls are not compatible with normal ones and wem ust set
    // the colours for them otherwise
    virtual bool SetBackgroundColour(const wxColour& colour);
    virtual bool SetForegroundColour(const wxColour& colour);
#endif // wxUSE_RICHEDIT

    virtual void AdoptAttributesFromHWND();

    virtual bool AcceptsFocus() const;

    // callbacks
    void OnDropFiles(wxDropFilesEvent& event);
    void OnChar(wxKeyEvent& event); // Process 'enter' if required

    void OnCut(wxCommandEvent& event);
    void OnCopy(wxCommandEvent& event);
    void OnPaste(wxCommandEvent& event);
    void OnUndo(wxCommandEvent& event);
    void OnRedo(wxCommandEvent& event);
    void OnDelete(wxCommandEvent& event);
    void OnSelectAll(wxCommandEvent& event);

    void OnUpdateCut(wxUpdateUIEvent& event);
    void OnUpdateCopy(wxUpdateUIEvent& event);
    void OnUpdatePaste(wxUpdateUIEvent& event);
    void OnUpdateUndo(wxUpdateUIEvent& event);
    void OnUpdateRedo(wxUpdateUIEvent& event);
    void OnUpdateDelete(wxUpdateUIEvent& event);
    void OnUpdateSelectAll(wxUpdateUIEvent& event);

    // Show a context menu for Rich Edit controls (the standard
    // EDIT control has one already)
    void OnContextMenu(wxContextMenuEvent& event);

    // be sure the caret remains invisible if the user
    // called HideNativeCaret() before
    void OnSetFocus(wxFocusEvent& event);

protected:
    // common part of all ctors
    void Init();

    // intercept WM_GETDLGCODE
    virtual WXLRESULT MSWWindowProc(WXUINT nMsg, WXWPARAM wParam, WXLPARAM lParam);

    // return true if this control has a user-set limit on amount of text (i.e.
    // the limit is due to a previous call to SetMaxLength() and not built in)
    bool HasSpaceLimit(unsigned int *len) const;

    // call this to increase the size limit (will do nothing if the current
    // limit is big enough)
    //
    // returns true if we increased the limit to allow entering more text,
    // false if we hit the limit set by SetMaxLength() and so didn't change it
    bool AdjustSpaceLimit();

#if wxUSE_RICHEDIT && (!wxUSE_UNICODE || wxUSE_UNICODE_MSLU)
    // replace the selection or the entire control contents with the given text
    // in the specified encoding
    bool StreamIn(const wxString& value, wxFontEncoding encoding, bool selOnly);

    // get the contents of the control out as text in the given encoding
    wxString StreamOut(wxFontEncoding encoding, bool selOnly = false) const;
#endif // wxUSE_RICHEDIT

    // replace the contents of the selection or of the entire control with the
    // given text
    void DoWriteText(const wxString& text, bool selectionOnly = true);

    // set the selection possibly without scrolling the caret into view
    void DoSetSelection(long from, long to, bool scrollCaret = true);

    // return true if there is a non empty selection in the control
    bool HasSelection() const;

    // get the length of the line containing the character at the given
    // position
    long GetLengthOfLineContainingPos(long pos) const;

    // send TEXT_UPDATED event, return true if it was handled, false otherwise
    bool SendUpdateEvent();

    // override some base class virtuals
    virtual bool MSWShouldPreProcessMessage(WXMSG* pMsg);
    virtual wxSize DoGetBestSize() const;

    virtual WXDWORD MSWGetStyle(long style, WXDWORD *exstyle) const;

#if wxUSE_RICHEDIT
    // we're using RICHEDIT (and not simple EDIT) control if this field is not
    // 0, it also gives the version of the RICHEDIT control being used (1, 2 or
    // 3 so far)
    int m_verRichEdit;
#endif // wxUSE_RICHEDIT

    // number of EN_UPDATE events sent by Windows when we change the controls
    // text ourselves: we want this to be exactly 1
    int m_updatesCount;

    virtual wxVisualAttributes GetDefaultAttributes() const;

private:
    DECLARE_EVENT_TABLE()
    DECLARE_DYNAMIC_CLASS_NO_COPY(wxTextCtrl)

    wxMenu* m_privateContextMenu;

    bool m_isNativeCaretShown;
};

#endif
    // _WX_TEXTCTRL_H_


text:
"""Testing inconsistent returns"""
import math
import sys

# These ones are consistent
def explicit_returns(var):
    if var >= 0:
        return math.sqrt(var)
    else:
        return None

def explicit_returns2(var):
    if var < 0:
        return None
    return math.sqrt(var)

def empty_implicit_returns(var):
    if var < 0:
        return

def returns_in_exceptions():
    try:
        raise ValueError('test')
    except ValueError:
        return 1
    except (OSError, TypeError):
        return 2

def returns_and_exceptions(var):
    if var < 10:
        return var**2
    else:
        raise ValueError("Incorrect value")

def returns_and_exceptions_issue1770(var):
    try:
        if var == 1:
            return 'a'
        elif var == 2:
            return 'b'
        else:
            raise ValueError
    except AssertionError:
        return None

def explicit_returns3(arg):
    if arg:
        return False
    else:
        if arg < 3:
            print('arg < 3')
        return True

def explicit_returns4(arg):
    if arg:
        if arg > 2:
            print('arg > 2')
        return False
    else:
        if arg < 3:
            print('arg < 3')
        return True

def explicit_returns5(arg):
    if arg:
        if arg > 2:
            print('arg > 2')
        return False
    else:
        return True

def nested_function():
    def dummy_return():
        return
    return dummy_return

def explicit_returns6(x, y, z):
    if x:  # pylint: disable=no-else-return
        a = 1
        if y:  # pylint: disable=no-else-return
            b = 2
            return y
        else:
            c = 3
            return x
    else:
        d = 4
        return z

def explicit_returns7(arg):
    if arg < 0:
        arg = 2 * arg
        return 'below 0'
    elif arg == 0:
        print("Null arg")
        return '0'
    else:
        arg = 3 * arg
        return 'above 0'

def bug_1772():
    """Don't check inconsistent return statements inside while loop"""
    counter = 1
    while True:
        counter += 1
        if counter == 100:
            return 7

def bug_1771(var):
    if var == 1:
        sys.exit(1)
    else:
        return var * 2

def bug_1771_with_user_config(var):
    # sys.getdefaultencoding is considered as a never
    # returning function in the inconsistent_returns.rc file.
    if var == 1:
        sys.getdefaultencoding()
    else:
        return var * 2

# Next ones are not consistent
def explicit_implicit_returns(var): # [inconsistent-return-statements]
    if var >= 0:
        return math.sqrt(var)

def empty_explicit_returns(var): # [inconsistent-return-statements]
    if var < 0:
        return
    return math.sqrt(var)

def explicit_implicit_returns2(arg): # [inconsistent-return-statements]
    if arg:
        if arg > 2:
            print('arg > 2')
            return False
    else:
        return True

def explicit_implicit_returns3(arg): # [inconsistent-return-statements]
    if arg:
        if arg > 2:
            print('arg > 2')
            return False
        else:
            return True

def returns_missing_in_catched_exceptions(arg): # [inconsistent-return-statements]
    try:
        arg = arg**2
        raise ValueError('test')
    except ValueError:
        print('ValueError')
        arg = 0
    except (OSError, TypeError):
        return 2

def complex_func(arg): # [inconsistent-return-statements]
    for i in range(arg):
        if i > arg / 2:
            break
        else:
            return arg

def inconsistent_returns_in_nested_function():
    def not_consistent_returns_inner(arg): # [inconsistent-return-statements]
        for i in range(arg):
            if i > arg / 2:
                break
            else:
                return arg
    return not_consistent_returns_inner

class BlargException(Exception):
    pass

def blarg(someval):
    try:
        if someval:
            raise BlargException()
        return 5
    except BlargException:
        raise

def bug_1772_counter_example(): # [inconsistent-return-statements]
    counter = 1
    if counter == 1:
        while True:
            counter += 1
            if counter == 100:
                return 7

def bug_1771_counter_example(var): # [inconsistent-return-statements]
    if var == 1:
        inconsistent_returns_in_nested_function()
    else:
        return var * 2


text:
Current Design:
=================

MOPs - Message Oriented Pipelines - If you do not like this (or find
    it confusing) then just read about:
Alan Kay's Real OOP, Erlang Process/Message/OTP, and biological systems.
MOPs is focused on experiments, recovering from those failed experiments,
     and flexibility. I should be able to create a Ruby Rack, Elixir Plug,
     or GUI-interaction system with just a few concepts.

![Message Oriented Pipelines](./docs/MOPs.png?raw=true)

For the specs...
=================
Someone beat me to this: [https://twitter.com/d0rc/status/685544307533545472](https://twitter.com/d0rc/status/685544307533545472)
    ![Example in erlang](./docs/CYJSUDfWcAU9dVQ.png?raw=true)

Extremes:
=========

* Pipelines: server-side (data processing) + client-side (GUIs)
* Visualize GUI + prepare GUI elements
  * Associate functions to elements, run those functions
* State between functions
* Foms - before/after/on submit
* Mouse & keyboard events
* HTML -> JS (function)
* Toggles: bool -> function
* Logic as a value
  * Markup -> Logic Preview -> Templates
* Standardization of messages:
  * AJAX request/response -> message -> processed data structure
  * message -> processed data structure (inspiration Mustache)
  * processed data structure -> markup/view

1 - Previous designs:
==================
```javascript
    computer('push', 'dom-change', my_func);
    computer('push', '!dom-change', my_func);
    computer('push', 'dom-change?', my_func);
    computer('run', {dom_change: true});

    data-do="is_factor   my_func"
    data-do="is_factor?  my_func"
    data-do="my_func!    arg1 arg2"
    data-if="is_factor   my_func"
    data-key="is_factor  my_func"
```

The previous designs were prone to creating matching DSLs on messages.
Anytime you have to introduce mini-languages/DSLs and clever tricks, you are limiting
flexibility and creating future dead-ends. It adds more things to learn and more complexity
to the implementation of `dum_dum_boom_boom`.

2 - Previous design:
==============
Basically an array of functions. Each function
handles it's own message matching and allows for simplicity while adding flexibity.

```javascript
    data-do="my_func  arg1  arg2 ..."
    function my_func(msg) {
      if (!msg_match(pattern, msg))
        return;

      computer('push', function my_func_with_closure(msg) {
          if (!msg_match(my_other_pattern, msg))
            return;
      });
    }
    computer('run', {my_key: true});
```

There is no "name of message"/"type of message". This allows the functions
flexibility to handle messages and avoid creating a limiting/inflexible
DSL to associate messages w/functions.


text:
using UnityStandardAssets.CrossPlatformInput;
public class MyCrossPlatformInputManager : IplayerInputController
{
    public float GetAxisRaw(string axisName)
    {
        return CrossPlatformInputManager.GetAxisRaw(axisName);
    }
}


text:
/* tslint:disable:no-unused-variable */

import { TestBed, async } from '@angular/core/testing';
import { ArtistComponent } from './artist.component';

describe('Component: Artist', () => {
  it('should create an instance', () => {
    let component = new ArtistComponent();
    expect(component).toBeTruthy();
  });
});


text:
class BuildService {

  constructor(config) {

    var
      BES = "BuildEventService",
      BCS = "BuildCommandService",
      addresses = {};

    /* params */

    var
      // (serviceType: String, state: String, error: ErrorEvent) => void
      onServiceEvent = config.onServiceEvent,

      // (project: String, data: String) => void
      onBuildEvent = config.onBuildEvent,

      // (reply: (m: js) => void, data: js) => reply(data)
      onBuildCommand = config.onBuildCommand;

    // ws://localhost:8083/buildService/events
    addresses[BES] = config.eventService;

    // ws://localhost:8083/buildService/commands
    addresses[BCS] = config.commandService;

    /* public */

    this.start = () => {
      stopped = false;
      for (var id in addresses) startConnecting(id);
    };

    this.stop = () => {
      stopped = true;
      for (var id in addresses) {
        stopConnecting(id);
        if (connections[id] !== undefined) connections[id].close();
      }
    };

    /* private */

    var
      stopped = false,
      handlers = {},
      tryConnectHandles = {},
      connections = {},
      debugServiceEvent = (serviceType, state, error) => console.debug("onServiceEvent", serviceType, state, error),
      debugMessage = m => console.debug("onMessage", m),
      startConnecting = id => {
        var start = () => {
          if (!stopped && tryConnectHandles[id] === undefined);
          tryStart(id);
        }
        start();
        tryConnectHandles[id] = setInterval(start,2000);
      },
      stopConnecting = id => {
        if (tryConnectHandles[id] !== undefined) {
          clearInterval(tryConnectHandles[id]);
          delete tryConnectHandles[id];
        }
      },
      tryStart = id => {
        if (connections[id] !== undefined) return;
        var ws = new WebSocket(addresses[id]);
        ws.onopen = e => {
          stopConnecting(id);
          var handler = onServiceEvent || debugServiceEvent;
          handler(id, "Started", undefined);
        };
        ws.onerror = e => {
          if (e.target.readyState == 3) return;
          var handler = onServiceEvent || debugServiceEvent;
          handler(id, "Error", e);
        };
        ws.onclose = e => {
          if (connections[id] !== undefined) delete connections[id];
          if (tryConnectHandles[id] !== undefined) return;
          var handler = onServiceEvent || debugServiceEvent;
          handler(id, "Closed", undefined);
          startConnecting(id);
        };
        ws.onmessage = e => {
          var
            m = JSON.parse(e.data),
            handler = handlers[id] || debugMessage;
          handler(m);
        };
        connections[id] = ws;
      };

    var debugBuildEvent = (project, event) => console.debug("onBuildEvent", project, event);
    handlers[BES] = e => {
      var
        [project, event] = e,
        handler = onBuildEvent || debugBuildEvent;
      if (project === undefined || event === undefined) return;
      handler(project,event);
    };

    var debugBuildCommand = (reply, data) => console.debug("onBuildCommand", data);
    handlers[BCS] = e => {
      var
        [id, data] = e,
        reply = m => commandService.send(JSON.stringify([id, m])),
        handler = onBuildCommand || debugBuildCommand;
      handler(reply, data);
    };

  }

}


text:
//-----------------------------------------------------------------------------
// <copyright file="MobileBehavior.cs" company="WheelMUD Development Team">
//   Copyright (c) WheelMUD Development Team.  See LICENSE.txt.  This file is
//   subject to the Microsoft Public License.  All other rights reserved.
// </copyright>
//
//   Created: May 2010 by Karak.
//
//-----------------------------------------------------------------------------

namespace WheelMUD.Core
{
    using System.Collections.Generic;
    using WheelMUD.Core.Events;

    /// @@@ Might be better renamed to AIBrainBehavior or something...?
    public class MobileBehavior : Behavior
    {
        /// Initializes a new instance of the MobileBehavior class.
        public MobileBehavior()
            : base(null)
        {
        }

        /// Initializes a new instance of the MobileBehavior class.
        /// <param name="instanceID">ID of the behavior instance.</param>
        /// <param name="instanceProperties">The dictionary of propertyNames-propertyValues for this behavior instance.</param>
        public MobileBehavior(long instanceID, Dictionary<string, object> instanceProperties)
            : base(instanceProperties)
        {
            this.ID = instanceID;
        }

        /// Receives an event.
        /// <param name="root">The root.</param>
        /// <param name="theEvent">The event to be received.</param>
        public void Receive(Thing root, GameEvent theEvent)
        {
            ////this.brain.ProcessStimulus(theEvent);
        }

        /// Sets the default properties of this behavior instance.
        protected override void SetDefaultProperties()
        {
            // @@@ For now, rigging MobileBehavior back up to all events like Mobile used to; I don't
            //     want to mess with AI too much right now especially since Fasta is working on it.
            // Prepare to handle receiving all relevant sensory events (not requests) which have
            // happened within the player's perception, and relay the sensory message to the player.
            if (this.Parent != null)
            {
                this.Parent.Eventing.CombatEvent += this.Receive;
                this.Parent.Eventing.MovementEvent += this.Receive;
                this.Parent.Eventing.CommunicationEvent += this.Receive;
                this.Parent.Eventing.MiscellaneousEvent += this.Receive;
            }
        }

        // @@@ TODO: After moving, do this.ProcessSurroundings();

        /* @@@ TODO: Ensure mobile entities are loaded just like any other entity...
        /// Loads the mobile.
        public void Load()
        {
            // @@@ TODO: Stuff should be loaded from the Data Layer instead of using temp values.
            this.Stats.Add("health", new StatHP(Controller, 100, 100));
            this.Stats.Add("power", new Stat(Controller, "Power", 100, 0, 100, true));
            this.Stats.Add("strength", new Stat(Controller, "Srength", 40, 0, 100, true));
            this.Stats.Add("balance", new Stat(Controller, "Balance", 1, 0, 1, false));
            this.Stats.Add("mobility", new Stat(Controller, "Mobility", 2, -10, 2, false));
            this.Stats.Add("agility", new Stat(Controller, "Agility", 2, -10, 2, true));
            this.Stats.Add("perception", new Stat(Controller, "Perception", 2, -10, 2, false));

            this.Commands.Add("punch", new Command("punch", SecurityRole.mobile));

            this.LoadInventory();
        }

        /// Saves the mobile.
        public override void Save()
        {
            var repository = new MobRepository();

            if (this.Id == 0)
            {
                repository.Add(this.DataRecord);
                this.Id = this.DataRecord.ID;
            }
            else
            {
                repository.Update(this.DataRecord);
            }
        }*/
    }
}


text:
package org.apache.sysml.api.mlcontext;

import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.sql.DataFrame;
import org.apache.sysml.conf.ConfigurationManager;
import org.apache.sysml.runtime.DMLRuntimeException;
import org.apache.sysml.runtime.controlprogram.context.SparkExecutionContext;
import org.apache.sysml.runtime.matrix.MatrixCharacteristics;
import org.apache.sysml.runtime.matrix.data.MatrixBlock;
import org.apache.sysml.runtime.matrix.data.MatrixIndexes;

/**
 * BinaryBlockMatrix stores data as a SystemML binary-block matrix representation.
 *
 */
public class BinaryBlockMatrix {

	JavaPairRDD<MatrixIndexes, MatrixBlock> binaryBlocks;
	MatrixMetadata matrixMetadata;

	/**
	 * Convert a Spark DataFrame to a SystemML binary-block representation.
	 *
	 * @param dataFrame
	 *            the Spark DataFrame
	 * @param matrixMetadata
	 *            matrix metadata, such as number of rows and columns
	 */
	public BinaryBlockMatrix(DataFrame dataFrame, MatrixMetadata matrixMetadata) {
		this.matrixMetadata = matrixMetadata;
		binaryBlocks = MLContextConversionUtil.dataFrameToMatrixBinaryBlocks(dataFrame, matrixMetadata);
	}

	/**
	 * Convert a Spark DataFrame to a SystemML binary-block representation,
	 * specifying the number of rows and columns.
	 *
	 * @param dataFrame
	 *            the Spark DataFrame
	 * @param numRows
	 *            the number of rows
	 * @param numCols
	 *            the number of columns
	 */
	public BinaryBlockMatrix(DataFrame dataFrame, long numRows, long numCols) {
		this(dataFrame, new MatrixMetadata(numRows, numCols,
				ConfigurationManager.getBlocksize(), ConfigurationManager.getBlocksize()));
	}

	/**
	 * Convert a Spark DataFrame to a SystemML binary-block representation.
	 *
	 * @param dataFrame
	 *            the Spark DataFrame
	 */
	public BinaryBlockMatrix(DataFrame dataFrame) {
		this(dataFrame, new MatrixMetadata());
	}

	/**
	 * Create a BinaryBlockMatrix, specifying the SystemML binary-block matrix
	 * and its metadata.
	 *
	 * @param binaryBlocks
	 *            the {@code JavaPairRDD<MatrixIndexes, MatrixBlock>} matrix
	 * @param matrixCharacteristics
	 *            the matrix metadata as {@code MatrixCharacteristics}
	 */
	public BinaryBlockMatrix(JavaPairRDD<MatrixIndexes, MatrixBlock> binaryBlocks,
			MatrixCharacteristics matrixCharacteristics) {
		this.binaryBlocks = binaryBlocks;
		this.matrixMetadata = new MatrixMetadata(matrixCharacteristics);
	}

	/**
	 * Obtain a SystemML binary-block matrix as a
	 * {@code JavaPairRDD<MatrixIndexes, MatrixBlock>}
	 *
	 * @return the SystemML binary-block matrix
	 */
	public JavaPairRDD<MatrixIndexes, MatrixBlock> getBinaryBlocks() {
		return binaryBlocks;
	}

	/**
	 * Obtain a SystemML binary-block matrix as a {@code MatrixBlock}
	 *
	 * @return the SystemML binary-block matrix as a {@code MatrixBlock}
	 */
	public MatrixBlock getMatrixBlock() {
		try {
			MatrixCharacteristics mc = getMatrixCharacteristics();
			return SparkExecutionContext.toMatrixBlock(binaryBlocks, (int) mc.getRows(), (int) mc.getCols(),
					mc.getRowsPerBlock(), mc.getColsPerBlock(), mc.getNonZeros());
		} catch (DMLRuntimeException e) {
			throw new MLContextException("Exception while getting MatrixBlock from binary-block matrix", e);
		}
	}

	/**
	 * Obtain the SystemML binary-block matrix characteristics
	 *
	 * @return the matrix metadata as {@code MatrixCharacteristics}
	 */
	public MatrixCharacteristics getMatrixCharacteristics() {
		return matrixMetadata.asMatrixCharacteristics();
	}

	/**
	 * Obtain the SystemML binary-block matrix metadata
	 *
	 * @return the matrix metadata as {@code MatrixMetadata}
	 */
	public MatrixMetadata getMatrixMetadata() {
		return matrixMetadata;
	}

	/**
	 * Set the SystemML binary-block matrix metadata
	 *
	 * @param matrixMetadata
	 *            the matrix metadata
	 */
	public void setMatrixMetadata(MatrixMetadata matrixMetadata) {
		this.matrixMetadata = matrixMetadata;
	}

	/**
	 * Set the SystemML binary-block matrix as a
	 * {@code JavaPairRDD<MatrixIndexes, MatrixBlock>}
	 *
	 * @param binaryBlocks
	 *            the SystemML binary-block matrix
	 */
	public void setBinaryBlocks(JavaPairRDD<MatrixIndexes, MatrixBlock> binaryBlocks) {
		this.binaryBlocks = binaryBlocks;
	}

	@Override
	public String toString() {
		if (matrixMetadata != null) {
			return matrixMetadata.toString();
		} else {
			return super.toString();
		}
	}
}


text:
<?php

class Forms {

    //fast way to retrieve a form element by its submit value
  public static function getFormBySubmit(Element $element, $submit){
    $path = "//form[descendant::input[@type='submit'][@value='$submit']]";
    return current($element->xpath($path));
  }
  public static function getSubmit(Element $element, $submit){
    return $element->getElement("input[type=submit][value='$submit']");
  }

  public static function getSelected(Element $element){
    return $element->getElements("option[selected=selected]:not([disabled=disabled])");
  }

  public static function set(Element $form, $selector, $value){
    $element = $form->getElement($selector);
    $element['value'] = $value;
  }

    //mix over ./Element/Element.js, Patchs/Element/Element.js,
  public static function toQueryString(Element $element){
    $queryString  = array();
    foreach($element->getElements("input, select, textarea") as $el){ //[type!=file], input[type!=submit], input[type!=image]
        $tag = $el->get("tag");
        if(!$el['name'] || $el->match("[disabled=disabled]") ) continue;
        if($tag == 'select') {
            $values = $el->getSelected();
            foreach($values as &$v) $v=(string)$v['value'];
            $value = $el->match("[multiple=multiple]") ?  $values : $v;
        } elseif($tag == 'textarea') {
            $value = $el->get("innerHTML");
        } elseif($tag == "input") {
            $type = strtolower($el['type']);
            if(in_array($type, array('file', 'submit', 'image', 'button')))
                continue;
            if(in_array($type, array('radio', 'checkbox')) ) {
                if(!$el['checked']) continue;
                $value =  (string) ($el['value']?$el['value']:"on");
            } else $value = (string) $el['value'];
        } else continue;

        $queryString [(string) $el['name']]  = $value;
    } return $queryString;
  }

}


text:
/**
* Phaser.TilemapParser parses data objects from Phaser.Loader that need more preparation before they can be inserted into a Tilemap.
*
* @class Phaser.TilemapParser
* @static
*/
Phaser.TilemapParser = {

    /**
     * When scanning the Tiled map data the TilemapParser can either insert a null value (true) or
     * a Phaser.Tile instance with an index of -1 (false, the default). Depending on your game type
     * depends how this should be configured. If you've a large sparsely populated map and the tile
     * data doesn't need to change then setting this value to `true` will help with memory consumption.
     * However if your map is small, or you need to update the tiles (perhaps the map dynamically changes
     * during the game) then leave the default value set.
     *
     * @constant
     * @type {boolean}
     */
    INSERT_NULL: false,

    /**
     * A tiled flag that resides within the 32 bit of the object gid and
     * indicates whether the tiled/object is flipped horizontally.
     *
     * @constant
     * @type {number}
     */
    FLIPPED_HORIZONTALLY_FLAG: 0x80000000,

    /**
     * A tiled flag that resides within the 31 bit of the object gid and
     * indicates whether the tiled/object is flipped vertically.
     *
     * @constant
     * @type {number}
     */
    FLIPPED_VERTICALLY_FLAG: 0x40000000,

    /**
     * A tiled flag that resides within the 30 bit of the object gid and
     * indicates whether the tiled/object is flipped diagonally.
     *
     * @constant
     * @type {number}
     */
    FLIPPED_DIAGONALLY_FLAG: 0x20000000,

    /**
    * Parse tilemap data from the cache and creates a Tilemap object.
    *
    * @method Phaser.TilemapParser.parse
    * @param {Phaser.Game} game - Game reference to the currently running game.
    * @param {string} key - The key of the tilemap in the Cache.
    * @param {number} [tileWidth=32] - The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data.
    * @param {number} [tileHeight=32] - The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data.
    * @param {number} [width=10] - The width of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this.
    * @param {number} [height=10] - The height of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this.
    * @return {object} The parsed map object.
    */
    parse: function (game, key, tileWidth, tileHeight, width, height) {

        if (tileWidth === undefined) { tileWidth = 32; }
        if (tileHeight === undefined) { tileHeight = 32; }
        if (width === undefined) { width = 10; }
        if (height === undefined) { height = 10; }

        if (key === undefined)
        {
            return this.getEmptyData();
        }

        if (key === null)
        {
            return this.getEmptyData(tileWidth, tileHeight, width, height);
        }

        var map = game.cache.getTilemapData(key);

        if (map)
        {
            if (map.format === Phaser.Tilemap.CSV)
            {
                return this.parseCSV(key, map.data, tileWidth, tileHeight);
            }
            else if (!map.format || map.format === Phaser.Tilemap.TILED_JSON)
            {
                return this.parseTiledJSON(map.data);
            }
        }
        else
        {
            console.warn('Phaser.TilemapParser.parse - No map data found for key ' + key);
        }

    },

    /**
    * Parses a CSV file into valid map data.
    *
    * @method Phaser.TilemapParser.parseCSV
    * @param {string} key - The name you want to give the map data.
    * @param {string} data - The CSV file data.
    * @param {number} [tileWidth=32] - The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data.
    * @param {number} [tileHeight=32] - The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data.
    * @return {object} Generated map data.
    */
    parseCSV: function (key, data, tileWidth, tileHeight) {

        var map = this.getEmptyData();

        //  Trim any rogue whitespace from the data
        data = data.trim();

        var output = [];
        var rows = data.split("\n");
        var height = rows.length;
        var width = 0;

        for (var y = 0; y < rows.length; y++)
        {
            output[y] = [];

            var column = rows[y].split(",");

            for (var x = 0; x < column.length; x++)
            {
                output[y][x] = new Phaser.Tile(map.layers[0], parseInt(column[x], 10), x, y, tileWidth, tileHeight);
            }

            if (width === 0)
            {
                width = column.length;
            }
        }

        map.format = Phaser.Tilemap.CSV;
        map.name = key;
        map.width = width;
        map.height = height;
        map.tileWidth = tileWidth;
        map.tileHeight = tileHeight;
        map.widthInPixels = width * tileWidth;
        map.heightInPixels = height * tileHeight;

        map.layers[0].width = width;
        map.layers[0].height = height;
        map.layers[0].widthInPixels = map.widthInPixels;
        map.layers[0].heightInPixels = map.heightInPixels;
        map.layers[0].data = output;

        return map;

    },

    /**
    * Returns an empty map data object.
    *
    * @method Phaser.TilemapParser.getEmptyData
    * @return {object} Generated map data.
    */
    getEmptyData: function (tileWidth, tileHeight, width, height) {

        var map = {};

        map.width = 0;
        map.height = 0;
        map.tileWidth = 0;
        map.tileHeight = 0;

        if (typeof tileWidth !== 'undefined' && tileWidth !== null) { map.tileWidth = tileWidth; }
        if (typeof tileHeight !== 'undefined' && tileHeight !== null) { map.tileHeight = tileHeight; }
        if (typeof width !== 'undefined' && width !== null) { map.width = width; }
        if (typeof height !== 'undefined' && height !== null) { map.height = height; }

        map.orientation = 'orthogonal';
        map.version = '1';
        map.properties = {};
        map.widthInPixels = 0;
        map.heightInPixels = 0;

        var layers = [];

        var layer = {

            name: 'layer',
            x: 0,
            y: 0,
            width: 0,
            height: 0,
            widthInPixels: 0,
            heightInPixels: 0,
            alpha: 1,
            visible: true,
            properties: {},
            indexes: [],
            callbacks: [],
            bodies: [],
            data: []

        };

        //  fill with nulls?

        layers.push(layer);

        map.layers = layers;
        map.images = [];
        map.objects = {};
        map.collision = {};
        map.tilesets = [];
        map.tiles = [];

        return map;

    },

    /**
    * Parses a Tiled JSON file into valid map data.
    * @method Phaser.TilemapParser.parseJSON
    * @param {object} json - The JSON map data.
    * @return {object} Generated and parsed map data.
    */
    parseTiledJSON: function (json) {

        if (json.orientation !== 'orthogonal')
        {
            console.warn('TilemapParser.parseTiledJSON - Only orthogonal map types are supported in this version of Phaser');
            return null;
        }

        //  Map data will consist of: layers, objects, images, tilesets, sizes
        var map = {};

        map.width = json.width;
        map.height = json.height;
        map.tileWidth = json.tilewidth;
        map.tileHeight = json.tileheight;
        map.orientation = json.orientation;
        map.format = Phaser.Tilemap.TILED_JSON;
        map.version = json.version;
        map.properties = json.properties;
        map.widthInPixels = map.width * map.tileWidth;
        map.heightInPixels = map.height * map.tileHeight;

        //  Tile Layers
        var layers = [];

        for (var i = 0; i < json.layers.length; i++)
        {
            if (json.layers[i].type !== 'tilelayer')
            {
                continue;
            }

            var curl = json.layers[i];

            // Base64 decode data if necessary
            // NOTE: uncompressed base64 only.
            if (!curl.compression && curl.encoding && curl.encoding === "base64") {
                var binaryString =  window.atob(curl.data);
                var len = binaryString.length;
                var bytes = new Array( len );
                // Interpret binaryString as an array of bytes representing
                // little-endian encoded uint32 values.
                for (var j = 0; j < len; j+=4) {
                    bytes[j/4] = (binaryString.charCodeAt(j) |
                                 binaryString.charCodeAt(j+1) << 8 |
                                 binaryString.charCodeAt(j+2) << 16 |
                                 binaryString.charCodeAt(j+3) << 24) >>> 0;
                }
                curl.data = bytes;
                delete curl.encoding;
            }
            else if(curl.compression){
                console.warn('TilemapParser.parseTiledJSON - Layer compression is unsupported, skipping layer \'' + curl.name + '\'');
                continue;
            }

            var layer = {

                name: curl.name,
                x: curl.x,
                y: curl.y,
                width: curl.width,
                height: curl.height,
                widthInPixels: curl.width * json.tilewidth,
                heightInPixels: curl.height * json.tileheight,
                alpha: curl.opacity,
                visible: curl.visible,
                properties: {},
                indexes: [],
                callbacks: [],
                bodies: []

            };

            if (curl.properties)
            {
                layer.properties = curl.properties;
            }

            var x = 0;
            var row = [];
            var output = [];
            var rotation, flipped, flippedVal, gid;

            //  Loop through the data field in the JSON.

            //  This is an array containing the tile indexes, one after the other. -1 = no tile, everything else = the tile index (starting at 1 for Tiled, 0 for CSV)
            //  If the map contains multiple tilesets then the indexes are relative to that which the set starts from.
            //  Need to set which tileset in the cache = which tileset in the JSON, if you do this manually it means you can use the same map data but a new tileset.

            for (var t = 0, len = curl.data.length; t < len; t++)
            {
                rotation = 0;
                flipped = false;
                gid = curl.data[t];

                //  If true the current tile is flipped or rotated (Tiled TMX format)
                if (gid > 0x20000000)
                {
                    flippedVal = 0;

                    // FlippedX
                    if (gid > 0x80000000)
                    {
                        gid -= 0x80000000;
                        flippedVal += 4;
                    }

                    // FlippedY
                    if (gid > 0x40000000)
                    {
                        gid -= 0x40000000;
                        flippedVal += 2;
                    }

                    // FlippedAD
                    if (gid > 0x20000000)
                    {
                        gid -= 0x20000000;
                        flippedVal += 1;
                    }

                    switch (flippedVal)
                    {
                        case 5:
                            rotation = Math.PI/2;
                            break;
                        case 6:
                            rotation = Math.PI;
                            break;
                        case 3:
                            rotation = 3*Math.PI/2;
                            break;
                        case 4:
                            rotation = 0;
                            flipped = true;
                            break;
                        case 7:
                            rotation = Math.PI/2;
                            flipped = true;
                            break;
                        case 2:
                            rotation = Math.PI;
                            flipped = true;
                            break;
                        case 1:
                            rotation = 3*Math.PI/2;
                            flipped = true;
                            break;
                    }
                }

                //  index, x, y, width, height
                if (gid > 0)
                {
                    row.push(new Phaser.Tile(layer, gid, x, output.length, json.tilewidth, json.tileheight));
                    row[row.length - 1].rotation = rotation;
                    row[row.length - 1].flipped = flipped;
                }
                else
                {
                    if (Phaser.TilemapParser.INSERT_NULL)
                    {
                        row.push(null);
                    }
                    else
                    {
                        row.push(new Phaser.Tile(layer, -1, x, output.length, json.tilewidth, json.tileheight));
                    }
                }

                x++;

                if (x === curl.width)
                {
                    output.push(row);
                    x = 0;
                    row = [];
                }
            }

            layer.data = output;

            layers.push(layer);

        }

        map.layers = layers;

        //  Images
        var images = [];

        for (var i = 0; i < json.layers.length; i++)
        {
            if (json.layers[i].type !== 'imagelayer')
            {
                continue;
            }

            var curi = json.layers[i];

            var image = {

                name: curi.name,
                image: curi.image,
                x: curi.x,
                y: curi.y,
                alpha: curi.opacity,
                visible: curi.visible,
                properties: {}

            };

            if (curi.properties)
            {
                image.properties = curi.properties;
            }

            images.push(image);

        }

        map.images = images;

        //  Tilesets & Image Collections
        var tilesets = [];
        var imagecollections = [];

        for (var i = 0; i < json.tilesets.length; i++)
        {
            //  name, firstgid, width, height, margin, spacing, properties
            var set = json.tilesets[i];

            if (set.image)
            {
                var newSet = new Phaser.Tileset(set.name, set.firstgid, set.tilewidth, set.tileheight, set.margin, set.spacing, set.properties);

                if (set.tileproperties)
                {
                    newSet.tileProperties = set.tileproperties;
                }

                // For a normal sliced tileset the row/count/size information is computed when updated.
                // This is done (again) after the image is set.
                newSet.updateTileData(set.imagewidth, set.imageheight);
                tilesets.push(newSet);
            }
            else
            {
                var newCollection = new Phaser.ImageCollection(set.name, set.firstgid, set.tilewidth, set.tileheight, set.margin, set.spacing, set.properties);

                for (var ti in set.tiles)
                {
                    var image = set.tiles[ti].image;
                    var gid = set.firstgid + parseInt(ti, 10);
                    newCollection.addImage(gid, image);
                }

                imagecollections.push(newCollection);
            }

        }

        map.tilesets = tilesets;
        map.imagecollections = imagecollections;

        //  Objects & Collision Data (polylines, etc)
        var objects = {};
        var collision = {};

        function slice (obj, fields) {

            var sliced = {};

            for (var k in fields)
            {
                var key = fields[k];

                if (typeof obj[key] !== 'undefined')
                {
                    sliced[key] = obj[key];
                }
            }

            return sliced;
        }

        for (var i = 0; i < json.layers.length; i++)
        {
            if (json.layers[i].type !== 'objectgroup')
            {
                continue;
            }

            var curo = json.layers[i];

            objects[curo.name] = [];
            collision[curo.name] = [];

            for (var v = 0, len = curo.objects.length; v < len; v++)
            {
                //  Object Tiles
                if (curo.objects[v].gid)
                {
                    var self = this;

                    var object = {

                        gid: curo.objects[v].gid,
                        name: curo.objects[v].name,
                        type: curo.objects[v].hasOwnProperty("type") ? curo.objects[v].type : "",
                        x: curo.objects[v].x,
                        y: curo.objects[v].y,
                        width: curo.objects[v].width,
                        height: curo.objects[v].height,
                        visible: curo.objects[v].visible,
                        properties: curo.objects[v].properties,
                        horizontallyFlipped: curo.objects[v].gid & self.FLIPPED_HORIZONTALLY_FLAG,
                        verticallyFlipped: curo.objects[v].gid & self.FLIPPED_VERTICALLY_FLAG,
                        diagonallyFlipped: curo.objects[v].gid & self.FLIPPED_DIAGONALLY_FLAG
                    };

                    if (curo.objects[v].rotation)
                    {
                        object.rotation = curo.objects[v].rotation;
                    }

                    objects[curo.name].push(object);
                }
                else if (curo.objects[v].polyline)
                {
                    var object = {

                        name: curo.objects[v].name,
                        type: curo.objects[v].type,
                        x: curo.objects[v].x,
                        y: curo.objects[v].y,
                        width: curo.objects[v].width,
                        height: curo.objects[v].height,
                        visible: curo.objects[v].visible,
                        properties: curo.objects[v].properties

                    };

                    if (curo.objects[v].rotation)
                    {
                        object.rotation = curo.objects[v].rotation;
                    }

                    object.polyline = [];

                    //  Parse the polyline into an array
                    for (var p = 0; p < curo.objects[v].polyline.length; p++)
                    {
                        object.polyline.push([ curo.objects[v].polyline[p].x, curo.objects[v].polyline[p].y ]);
                    }

                    collision[curo.name].push(object);
                    objects[curo.name].push(object);
                }
                // polygon
                else if (curo.objects[v].polygon)
                {
                    var object = slice(curo.objects[v],
                                       ["name", "type", "x", "y", "visible", "rotation", "properties" ]);

                    //  Parse the polygon into an array
                    object.polygon = [];

                    for (var p = 0; p < curo.objects[v].polygon.length; p++)
                    {
                        object.polygon.push([ curo.objects[v].polygon[p].x, curo.objects[v].polygon[p].y ]);
                    }

                    objects[curo.name].push(object);

                }
                // ellipse
                else if (curo.objects[v].ellipse)
                {
                    var object = slice(curo.objects[v],
                                       ["name", "type", "ellipse", "x", "y", "width", "height", "visible", "rotation", "properties" ]);
                    objects[curo.name].push(object);
                }
                // otherwise it's a rectangle
                else
                {
                    var object = slice(curo.objects[v],
                                       ["name", "type", "x", "y", "width", "height", "visible", "rotation", "properties" ]);
                    object.rectangle = true;
                    objects[curo.name].push(object);
                }
            }
        }

        map.objects = objects;
        map.collision = collision;

        map.tiles = [];

        //  Finally lets build our super tileset index
        for (var i = 0; i < map.tilesets.length; i++)
        {
            var set = map.tilesets[i];

            var x = set.tileMargin;
            var y = set.tileMargin;

            var count = 0;
            var countX = 0;
            var countY = 0;

            for (var t = set.firstgid; t < set.firstgid + set.total; t++)
            {
                //  Can add extra properties here as needed
                map.tiles[t] = [x, y, i];

                x += set.tileWidth + set.tileSpacing;

                count++;

                if (count === set.total)
                {
                    break;
                }

                countX++;

                if (countX === set.columns)
                {
                    x = set.tileMargin;
                    y += set.tileHeight + set.tileSpacing;

                    countX = 0;
                    countY++;

                    if (countY === set.rows)
                    {
                        break;
                    }
                }
            }

        }

        // assign tile properties

        var layer;
        var tile;
        var sid;
        var set;

        // go through each of the map layers
        for (var i = 0; i < map.layers.length; i++)
        {
            layer = map.layers[i];

            // rows of tiles
            for (var j = 0; j < layer.data.length; j++)
            {
                row = layer.data[j];

                // individual tiles
                for (var k = 0; k < row.length; k++)
                {
                    tile = row[k];

                    if (tile === null || tile.index < 0)
                    {
                        continue;
                    }

                    // find the relevant tileset

                    sid = map.tiles[tile.index][2];
                    set = map.tilesets[sid];

                    // if that tile type has any properties, add them to the tile object

                    if (set.tileProperties && set.tileProperties[tile.index - set.firstgid])
                    {
                        tile.properties = Phaser.Utils.mixin(set.tileProperties[tile.index - set.firstgid], tile.properties);
                    }
                }
            }
        }

        return map;

    }

};


text:
An anagram is a rearrangement of letters to form a new word.
Given a word and a list of candidates, select the sublist of anagrams of the given word.

Given `"listen"` and a list of candidates like `"enlists" "google"
"inlets" "banana"` the program should return a list containing
`"inlets"`.

The Scala exercises assume an SBT project scheme. The exercise solution source
should be placed within the exercise directory/src/main/scala. The exercise
unit tests can be found within the exercise directory/src/test/scala.

To run the tests simply run the command `sbt test` in the exercise directory.

Please see the [learning](https://exercism.io/tracks/scala/learning) and
[installation](https://exercism.io/tracks/scala/installation) pages if you need any help.

## Source

Inspired by the Extreme Startup game [https://github.com/rchatley/extreme_startup](https://github.com/rchatley/extreme_startup)

## Submitting Incomplete Solutions
It's possible to submit an incomplete solution so you can see how others have completed the exercise.


text:
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var cors = require("cors");
var fs = require("fs");
var Promise = require("promise");

var fullBookList;

//Promisification
var readFile = Promise.denodeify(fs.readFile);
readFile("full_book_list.json", "utf8")
  .then(function (str) {
	fullBookList = JSON.parse(str);
});

//Static content rendering
app.use(express.static("./build"));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

//SERVER SETUP
//CORS resolution
app.use(cors());
app.use(function(req, res, next) {
	res.header("Access-Control-Allow-Origin", "*");
	res.header("Access-Control-Allow-Headers", "accept, content-type, xrs-tenant-id");
	next();
});

//GetBooks calls
app.get("/api/books",function(req, res){
  try{
    res.status(200);
    res.json({
      "response": { "status": 200, "message": "success" },
      "books" : fullBookList.books.filter(function(book){
        return book.shelf !== "none";
      })
    });
  }catch(e){
    res.status(500);
    res.json({"response": { "status": 500, "message": "fail" },
              "error" : e});
  }
});

//Request handling
app.put("/api/books/:booksId",function(req, res){
  var i = 0;
  try{
    for(i=0; i<fullBookList.books.length; i++)
      if(fullBookList.books[i].id == req.params.booksId){
        fullBookList.books[i].shelf = req.body.shelf;
        res.json({
            "book" : fullBookList.books[i],
            "response": { "status": 200, "message": "success" }
        });
        break;
      }
    res.status(200);
  }catch(e){
    res.json({"response": { "status": 500, "message": "fail" },
              "error" : e});
    res.status(500);
  }
});

//Search calls
app.post("/api/search",function(req, res){

  if(!req.body.query){
    res.status(200);
    res.json({"books" : []});
    return;
  }

  try{
    res.status(200);
    res.json({
      "response": { "status": 200, "message": "success" },
      "books" : fullBookList.books.filter(function(book){
        var title = book.title.toLocaleLowerCase(),
          query = req.body.query.toLocaleLowerCase();
        return title.indexOf(query) > 1;
      })
    });
  }catch(e){
    res.status(500);
    res.json({"response": { "status": 500, "message": "fail" },
              "error" : e});
  }
});

var port = process.env.PORT || 3000
app.listen(port, function() {
    console.log("To view your app, open this link in your browser: http://localhost:" + port);
});


text:
class CreateInvites < ActiveRecord::Migration
  def self.up
    create_table :invites, :force => true do |t|
      t.string :slug
      t.datetime :expires_at
      t.timestamps
    end
  end

  def self.down
    drop_table :invites
  end
end


text:
package scalydomain.core

import scala.util.Random

class MarkovChainBuilder(val db: ModelDbWriter, val n: Int) {
	val Prefix = "^" * n
	val Suffix = "$" * n

	//Update the model to reflect the contents of the given word
	def learn(text: String) {
		(Prefix + text + Suffix).sliding(n+1).foreach { seg =>
			val ngram = seg take n
			val nextSym = seg drop n

			db.addNgramNextSymbol(ngram, nextSym)

			//For the purposes of our stats, the synthetic ngrams which include the prefix or suffix characters
			//should not be counted, as that will skew the actual frequency numbers for ngrams in the training corpus
			val isSyntheticNgram = ngram.contains("$") || ngram.contains("^")
			if (!isSyntheticNgram) {
				db.incrementNgramOccurrenceCount(ngram)
			}
		}
	}
}


text:
require 'twilio-ruby'

# Initialize the client
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Twilio::REST::Client.new(account_sid, auth_token)

# Retrieve the Service Instance
service = client.sync.v1.services('ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')

# Traverse the Sync Lists
service.sync_lists.each do |list|
  puts list.unique_name
end

# List the Sync Lists
response = service.sync_lists.list

puts response