text:
'use strict';
var Cmd = require('../src/commands').cmd,
Room = require('../src/rooms').room,
Character = require('../src/character').character,
World = require('../src/world').world;

module.exports = {
	name: 'Midgaard',
	id: 'midgaard',
	type: 'city',
	levels: 'All',
	description: 'The first city.',
	reloads: 0,
	created: '',
	saved: '',
	author: 'Rocky',
	messages: [
		{msg: 'A cool breeze blows through the streets of Midgaard.'},
		{msg: 'The bustle of the city can be distracting. Keep an eye out for thieves.'}
	],
	respawnOn: 8,
	rooms: [
		{
			id: '1',
			title: 'Midgaard Town Square',
			light: true,
			area: 'midgaard',
			content: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent congue sagittis efficitur. Vivamus dapibus sem ac mauris pharetra dapibus. Nunc id ex orci. Quisque fringilla dictum orci molestie condimentum. Duis volutpat porttitor ipsum. Sed ac aliquet leo. Nulla at facilisis orci, eu suscipit nibh. ',
			outdoors: true,
			exits: [
				{
					cmd: 'north',
					id: '2'
				}, {
					cmd: 'east',
					id: '3'
				}, {
					cmd: 'south',
					id: '4'
				}, {
					cmd: 'west',
					id: '5'
				}, {
					cmd: 'up',
					id: '1'//,
//					area: 'midgaard_academy'
				}, {
					cmd: 'down',
					id: '6',
					door: {
						isOpen: false,
						locked: true,
						key: '101',
						openMsg: 'A foul smell flows in from below.',
						name: 'gate'
					}
				}
			],
			playersInRoom: [],
			monsters: [
				{
					name: 'Rufus',
					level: 15,
					short: 'Mayor Rufus',
					long: 'Rufus, current mayor of Midgaard, is here pacing around the room',
					description: '',
					inName: 'Mayor Rufus',
					race: 'human',
					id: 9,
					area: 'midgaard',
					weight: 245,
					diceNum: 2,
					diceSides: 8,
					diceMod: 5,
					str: 16,
					position: 'standing',
					attackType: 'punch',
					damRoll: 10,
					hitRoll: 10,
					ac: 20,
					wanderCheck: 38,
					itemType: 'mob',
					runOnAliveWhenEmpty: false,
					items: [{
						name: 'Midgaard city key',
						short: 'a thin gold key',
						long: 'A thin gold key with a ruby embbeded to the end lies here' ,
						area: 'midgaard',
						id: '10',
						level: 1,
						itemType: 'key',
						material: 'gold',
						weight: 0,
						slot: '',
						value: 1000,
						equipped: false,
						isKey: true
					}],
					behaviors: [{
						module: 'mayor'
					}, {
						module: 'wander'
					}]
				}, {
					name: 'Hound Dog',
					displayName: 'Hunting hound',
					level: 1,
					short: 'a healthy looking brown and white hound',
					long: 'A large spotted brown and white hound sniffs about the area',
					inName: 'A canine',
					race: 'animal',
					id: '6',
					area: 'midgaard',
					weight: 120,
					position: 'standing',
					attackType: 'bite',
					ac: 4,
					hp: 15,
					chp: 15,
					gold: 1,
					size: {value: 2, display: 'very small'},
					itemType: 'mob',
					behaviors: [{
						module: 'wander'
					}]
				}
			],
			items: [{
				name: 'Fountain',
				short: 'a large stone fountain',
				long: 'A large stone fountain full of sparkling water',
				area: 'midgaard',
				id: '112',
				waterSource: true,
				weight: 10000,
				itemType: 'ornament'
			}, {
				name: 'Leather Armor',
				short: 'a leather chestplate',
				long: 'Some leather armor was left here',
				area: 'midgaard',
				id: '111',
				level: 1,
				itemType: 'armor',
				material: 'leather',
				ac: 3,
				weight: 1,
				slot: 'body',
				equipped: false,
				value: 5
			}, {
				name: 'Torch',
				short: 'a wooden torch',
				long: 'A wooden torch rests on the ground' ,
				area: 'midgaard',
				id: '104',
				level: 1,
				itemType: 'weapon',
				material: 'wood',
				weaponType: 'club',
				diceNum: 1,
				diceSides: 2,
				diceMod: -5,
				attackType: 'smash',
				ac: -1,
				weight: 2,
				slot: 'hands',
				equipped: false,
				light: true,
				lightDecay: 10,
				flickerMsg: '',
				extinguishMsg: '',
				spell: {
					id: 'spark',
					display: 'Spark',
					mod: 0,
					train: 85,
					type: 'spell',
					wait: 2
				},
				beforeDrop: function(item, roomObj) {
					return true;
				}
			}, {
				name: 'Small Buckler',
				short: 'a small round buckler',
				long: 'A small basic looking round buckler lies here' ,
				area: 'midgaard',
				id: '103',
				level: 1,
				itemType: 'shield',
				material: 'wood',
				ac: 2,
				weight: 1,
				slot: 'hands',
				equipped: false,
				affects: [{
					id: 'hidden',
					affect: 'hidden',
					decay: -1
				}]
			}, {
				name: 'Loaf of Bread',
				short: 'a brown loaf of bread',
				long: 'A rather stale looking loaf of bread is lying on the ground' ,
				area: 'midgaard',
				id: '7',
				level: 1,
				itemType: 'food',
				weight: 0.5,
				diceNum: 1,
				diceSides: 6,
				diceMod: 1,
				decay: 3
			}, {
				name: 'Short Sword',
				displayName: 'Short Sword',
				short: 'a common looking short sword',
				long: 'A short sword with a hilt wrapped in leather straps was left on the ground' ,
				area: 'midgaard',
				id: '8',
				level: 1,
				itemType: 'weapon',
				weaponType: 'sword',
				material: 'iron',
				diceNum: 1,
				diceSides: 6,
				diceMod: 0,
				attackType: 'slash',
				attackElement: '',
				weight: 4,
				slot: 'hands',
				equipped: false,
				modifiers: {
					damRoll: 1
				}
			}, {
				name: 'Burlap sack',
				short: 'a worn, tan, burlap sack',
				long: 'A tan burlap sack with frizzed edges and various stains lies here',
				area: 'midgaard',
				id: '27',
				level: 1,
				itemType: 'container',
				weight: 1,
				items: [{
					name: 'Sewer key',
					short: 'small rusty key',
					long: 'A small rusty key made iron was left here',
					area: 'midgaard',
					id: '101',
					level: 1,
					itemType: 'key',
					material: 'iron',
					weight: 0,
					slot: '',
					value: 1,
					equipped: false,
					isKey: true
				}],
				isOpen: true,
				carryLimit: 50
			}],
			beforeEnter: function(roomObj, fromRoom, target) {
				return true;
			},
			onEnter: function(roomObj, target) {

			}
		},
		{
			id: '2',
			title: 'North of Town Square',
			area: 'midgaard',
			content: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent congue sagittis efficitur. Vivamus dapibus sem ac mauris pharetra dapibus. Nunc id ex orci. Quisque fringilla dictum orci molestie condimentum. Duis volutpat porttitor ipsum. Sed ac aliquet leo. Nulla at facilisis orci, eu suscipit nibh. ',
			outdoors: true,
			exits: [
				{
					cmd: 'south',
					id: '1'
				}, {
					cmd: 'north',
					id: '1',
					area: 'the_great_valley'
				}
			],
			playersInRoom: [],
			monsters: [],
			items: [{
				name: 'Tattered Buckler',
				short: 'a tattered buckler',
				long: 'A round buckler that looks like its seen heavy use is lying here' ,
				area: 'midgaard',
				id: '2',
				level: 1,
				itemType: 'shield',
				material: 'wood',
				ac: 2,
				weight: 6,
				slot: 'hands',
				equipped: false
			}]
		},
		{
			id: '3',
			title: 'East of Town Square',
			area: 'midgaard',
			content: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent congue sagittis efficitur. Vivamus dapibus sem ac mauris pharetra dapibus. Nunc id ex orci. Quisque fringilla dictum orci molestie condimentum. Duis volutpat porttitor ipsum. Sed ac aliquet leo. Nulla at facilisis orci, eu suscipit nibh. ',
			terrain: 'stone-road',
			terrainMod: 1,
			outdoors: true,
			exits: [
				{
					cmd: 'west',
					id: '1'
				}
			],
			playersInRoom: [],
			monsters: [],
			items: [{
				name: 'Brown waterskin',
				short: 'a light brown waterskin',
				long: 'A brown waterskin, the hide seems worn and used, was left here.' ,
				area: 'midgaard',
				id: '102',
				level: 1,
				drinks: 6,
				maxDrinks: 6,
				itemType: 'bottle',
				material: 'leather',
				weight: 0,
				value: 1,
				equipped: false
			}]
		},
		{
			id: '4',
			title: 'South of Town Square',
			area: 'midgaard',
			content: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent congue sagittis efficitur. Vivamus dapibus sem ac mauris pharetra dapibus. Nunc id ex orci. Quisque fringilla dictum orci molestie condimentum. Duis volutpat porttitor ipsum. Sed ac aliquet leo. Nulla at facilisis orci, eu suscipit nibh. ',
			outdoors: true,
			exits: [
				{
					cmd: 'north',
					id: '1'
				}
			],
			playersInRoom: [],
			monsters: [],
			items: []
		},
		{
			id: '5',
			title: 'West of Town Square',
			area: 'midgaard',
			content: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent congue sagittis efficitur. Vivamus dapibus sem ac mauris pharetra dapibus. Nunc id ex orci. Quisque fringilla dictum orci molestie condimentum. Duis volutpat porttitor ipsum. Sed ac aliquet leo. Nulla at facilisis orci, eu suscipit nibh. ',
			exits: [
				{
					cmd: 'west',
					id: '8'
				}, {
					cmd: 'east',
					id: '1'
				}
			],
			playersInRoom: [],
			monsters: [],
			items: [{
				name: 'Leather Helmet',
				short: 'a leather helmet',
				long: 'A simple leather helmet was left here' ,
				area: 'midgaard',
				id: '3',
				level: 1,
				itemType: 'armor',
				material: 'wood',
				ac: 1,
				weight: 1,
				slot: 'head',
				equipped: false
			}]
		},
		{
			id: '6',
			title: 'Beneath Town Square',
			area: 'midgaard',
			content: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent congue sagittis efficitur. Vivamus dapibus sem ac mauris pharetra dapibus. Nunc id ex orci. Quisque fringilla dictum orci molestie condimentum. Duis volutpat porttitor ipsum. Sed ac aliquet leo. Nulla at facilisis orci, eu suscipit nibh. ',
			size: {value: 3, display: 'medium'},
			outdoors: false,
			exits: [
				{
					cmd: 'up',
					id: '1',
					door: {
						name: 'gate',
						isOpen: false,
						locked: true,
						key: '101'
					}
				}
			],
			playersInRoom: [],
			monsters: [{
				name: 'Large Alligator',
				level: 3,
				race: 'animal',
				short: 'a mean looking Alligator',
				long: 'A large mean looking Alligator',
				diceNum: 2,
				diceSides: 2,
				diceMod: 2,
				hp: 30,
				chp: 30,
				kingdom: 'reptile',
				gold: 3,
				size: {value: 3, display: 'medium'},
				attackOnVisit: true,
				behaviors: [{
					module: 'aggie'
				}]
			}],
			items: []
		},
		{
			id: '8',
			title: 'The General Store',
			area: 'midgaard',
			content: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent congue sagittis efficitur. Vivamus dapibus sem ac mauris pharetra dapibus. Nunc id ex orci. Quisque fringilla dictum orci molestie condimentum. Duis volutpat porttitor ipsum. Sed ac aliquet leo. Nulla at facilisis orci, eu suscipit nibh. ',
			outdoors: false,
			exits: [
				{
					cmd: 'east',
					id: '5'
				}
			],
			playersInRoom: [],
			monsters: [
				{
					name: 'Thomas',
					level: 15,
					short: 'Thomas, the dwarven shopkeep',
					long: 'Thomas the dwarven shopkeeper is here',
					description: '',
					race: 'dwarf',
					id: '9',
					area: 'midgaard',
					weight: 200,
					diceNum: 2,
					diceSides: 8,
					diceMod: 5,
					str: 18,
					gold: 1000,
					position: 'standing',
					attackType: 'punch',
					damRoll: 10,
					hitRoll: 10,
					ac: 20,
					merchant: true,
					itemType: 'mob',
					preventItemDecay: true,
					items: [{
						name: 'Pemmican',
						short: 'a piece of Pemmican',
						long: 'A bit of Pemmican was left here' ,
						area: 'midgaard',
						id: '110',
						level: 1,
						itemType: 'food',
						material: 'flesh',
						weight: 0,
						slot: '',
						value: 10,
						equipped: false,
						spawn: 3
					}],
					behaviors: [],
					beforeSell: function(merchant, roomObj, buyer) {
						if (buyer.race === 'ogre') {
							Cmd.say(merchant, {
								msg: 'Sell to an Ogre? Are you insane?',
								roomObj: roomObj
							});

							return false;
						} else {
							return true;
						}
					}
				}
			],
			items: []
		}
	]
};


text:
'use strict';

var assert         = require('../../helpers/assert');
var stub           = require('../../helpers/stub').stub;
var commandOptions = require('../../factories/command-options');
var InstallCommand = require('../../../lib/commands/install');
var Task           = require('../../../lib/models/task');
var Promise        = require('../../../lib/ext/promise');

describe('install command', function() {
  var command, options, tasks, bowerInstance, npmInstance;

  beforeEach(function() {
    tasks = {
      BowerInstall: Task.extend({
        init: function() {
          bowerInstance = this;
        }
      }),

      NpmInstall: Task.extend({
        init: function() {
          npmInstance = this;
        }
      })
    };

    options = commandOptions({
      settings: {},

      project: {
        name: function() {
          return 'some-random-name';
        },

        isEmberCLIProject: function() {
          return true;
        }
      },

      tasks: tasks
    });

    stub(tasks.BowerInstall.prototype, 'run', Promise.resolve());
    stub(tasks.NpmInstall.prototype, 'run', Promise.resolve());

    command = new InstallCommand(options);
  });

  afterEach(function() {
    tasks.BowerInstall.prototype.run.restore();
    tasks.NpmInstall.prototype.run.restore();
  });

  it('runs the bower install task and npm install task', function() {
    return command.validateAndRun([]).then(function() {
      var bowerRun = tasks.BowerInstall.prototype.run;
      assert.equal(bowerRun.called, 1, 'expected bower install run was called once');
      assert.deepEqual(bowerRun.calledWith[0][0], {}, 'expected bower install called with empty options');

      var npmRun = tasks.NpmInstall.prototype.run;
      assert.equal(npmRun.called, 1, 'expected npm install run was called once');
      assert.deepEqual(npmRun.calledWith[0][0], {}, 'expected npm install called with empty options');
    });
  });

  it('initializes npm task with ui, project and analytics', function() {
    return command.validateAndRun([]).then(function() {
      assert.ok(npmInstance.ui, 'ui was set');
      assert.ok(npmInstance.project, 'project was set');
      assert.ok(npmInstance.analytics, 'analytics was set');
    });
  });

  it('initializes bower task with ui, project and analytics', function() {
    return command.validateAndRun([]).then(function() {
      assert.ok(bowerInstance.ui, 'ui was set');
      assert.ok(bowerInstance.project, 'project was set');
      assert.ok(bowerInstance.analytics, 'analytics was set');
    });
  });

  it('warns when passing args', function() {
    return command.validateAndRun(['moment']).then(function() {
      assert.ok(false, 'should have rejected with a warning');
    })
    .catch(function(error) {
      assert.equal(error.message, 'The `install` command does not take any arguments. You must use `install:npm` or `install:bower` to install a specific package.');
    });
  });
});

redpajama_set_name: RedPajamaGithub


text:
<?php

/**
 * Class FunctionStrrevTest
 * @link http://php.net/manual/en/function.strrev.php
 */
class FunctionStrrevTest extends PHPUnit_Framework_TestCase
{
    public function testFunctionStrrev()
    {
        $this->assertEquals('!dlrow olleH', strrev("Hello world!"));
    }
}


text:
local manif_core = {}
package.loaded["luarocks.manif_core"] = manif_core

local persist = require("luarocks.persist")
local type_check = require("luarocks.type_check")
local cfg = require("luarocks.cfg")
local dir = require("luarocks.dir")
local util = require("luarocks.util")
local path = require("luarocks.path")

-- Table with repository identifiers as keys and tables mapping
-- Lua versions to cached loaded manifests as values.
local manifest_cache = {}

--- Cache a loaded manifest.
-- @param repo_url string: The repository identifier.
-- @param lua_version string: Lua version in "5.x" format, defaults to installed version.
-- @param manifest table: the manifest to be cached.
function manif_core.cache_manifest(repo_url, lua_version, manifest)
   lua_version = lua_version or cfg.lua_version
   manifest_cache[repo_url] = manifest_cache[repo_url] or {}
   manifest_cache[repo_url][lua_version] = manifest
end

--- Attempt to get cached loaded manifest.
-- @param repo_url string: The repository identifier.
-- @param lua_version string: Lua version in "5.x" format, defaults to installed version.
-- @return table or nil: loaded manifest or nil if cache is empty.
function manif_core.get_cached_manifest(repo_url, lua_version)
   lua_version = lua_version or cfg.lua_version
   return manifest_cache[repo_url] and manifest_cache[repo_url][lua_version]
end

--- Back-end function that actually loads the manifest
-- and stores it in the manifest cache.
-- @param file string: The local filename of the manifest file.
-- @param repo_url string: The repository identifier.
-- @param lua_version string: Lua version in "5.x" format, defaults to installed version.
-- @param quick boolean: If given, skips type checking.
-- @return table or (nil, string, string): the manifest or nil,
-- error message and error code ("open", "load", "run" or "type").
function manif_core.manifest_loader(file, repo_url, lua_version, quick)
   local manifest, err, errcode = persist.load_into_table(file)
   if not manifest then
      return nil, "Failed loading manifest for "..repo_url..": "..err, errcode
   end
   local globals = err
   if not quick then
      local ok, err = type_check.type_check_manifest(manifest, globals)
      if not ok then
         return nil, "Error checking manifest: "..err, "type"
      end
   end

   manif_core.cache_manifest(repo_url, lua_version, manifest)
   return manifest
end

--- Load a local manifest describing a repository.
-- All functions that use manifest tables assume they were obtained
-- through either this function or load_manifest.
-- @param repo_url string: URL or pathname for the repository.
-- @return table or (nil, string, string): A table representing the manifest,
-- or nil followed by an error message and an error code, see manifest_loader.
function manif_core.load_local_manifest(repo_url)
   assert(type(repo_url) == "string")

   local cached_manifest = manif_core.get_cached_manifest(repo_url)
   if cached_manifest then
      return cached_manifest
   end

   local pathname = dir.path(repo_url, "manifest")
   return manif_core.manifest_loader(pathname, repo_url, nil, true)
end

--- Get all versions of a package listed in a manifest file.
-- @param name string: a package name.
-- @param deps_mode string: "one", to use only the currently
-- configured tree; "order" to select trees based on order
-- (use the current tree and all trees below it on the list)
-- or "all", to use all trees.
-- @return table: An array of strings listing installed
-- versions of a package.
function manif_core.get_versions(name, deps_mode)
   assert(type(name) == "string")
   assert(type(deps_mode) == "string")

   local version_set = {}
   path.map_trees(deps_mode, function(tree)
      local manifest = manif_core.load_local_manifest(path.rocks_dir(tree))

      if manifest and manifest.repository[name] then
         for version in pairs(manifest.repository[name]) do
            version_set[version] = true
         end
      end
   end)

   return util.keys(version_set)
end

return manif_core


text:
Error view for ViewController
---
![](https://github.com/mikeooye/BPErrorView/blob/master/BPError%20demo%20gif.gif)


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model backend\models\ArmadaSearch */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin([
        'action' => ['index'],
        'method' => 'get',
    ]); ?>

    <?= $form->field($model, 'armada_id') ?>

    <?= $form->field($model, 'armada_nama') ?>

    <?= $form->field($model, 'armada_keterangan') ?>

    <?= $form->field($model, 'status') ?>

        <?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?>
        <?= Html::resetButton('Reset', ['class' => 'btn btn-default']) ?>

    <?php ActiveForm::end(); ?>


text:
package com.twitter.finagle.http

import com.twitter.conversions.DurationOps._
import com.twitter.util.Stopwatch
import java.net.URLEncoder
import java.nio.charset.StandardCharsets
import org.scalacheck.Gen
import org.scalatest.FunSuite
import org.scalatest.concurrent.{Eventually, IntegrationPatience}
import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks
import scala.collection.JavaConverters._

class QueryParamCodecTest
    extends FunSuite
    with ScalaCheckDrivenPropertyChecks
    with Eventually
    with IntegrationPatience {

  private def encode(s: String): String = URLEncoder.encode(s, StandardCharsets.UTF_8.name)

  private def genNonEmptyToken: Gen[String] =
    Gen.nonEmptyListOf(Gen.choose('a', 'z')).map(s => new String(s.toArray))

  private def genToken: Gen[String] =
    Gen.listOf(Gen.choose('a', 'z')).map(s => new String(s.toArray))

  private def genKeyValuePair: Gen[(String, String)] =
    for {
      k <- genNonEmptyToken
      v <- genToken
    } yield k -> v

  private def genParams: Gen[Seq[(String, String)]] = Gen.listOf(genKeyValuePair).map(_.sorted)

  private def roundTrip(params: Seq[(String, String)]): Unit = {
    val queryString = QueryParamEncoder.encode(params)
    val result = QueryParamDecoder.decode(queryString)
    val flattened = result.asScala.toSeq.flatMap {
      case (key, values) =>
        values.asScala.map(key -> _)
    }.sorted

    assert(flattened == params)
  }

  private val samples = Seq(
    "a" -> "b",
    "a" -> "b", // nobody says you can't repeat a value
    "empty value" -> "", // empty value
    "empty value" -> "", // nobody says you can't repeat an empty value
    "$$&&%;" -> "LOL!!&&;Z",
    encode("$$&&%;") -> encode("LOL!!&&;Z") // should be able to encode encoded samples
  ).sorted

  test("Will round trip explicit samples") {
    roundTrip(samples)
  }

  test("arbitrary keys and values") {
    forAll(genParams) { params =>
      roundTrip(params)
    }
  }

  test("Decode a uri without a query string") {
    assert(QueryParamDecoder.decode("foo.com").isEmpty)
    assert(QueryParamDecoder.decode("foo.com/bar").isEmpty)
    assert(QueryParamDecoder.decode("foo.com/bar?").isEmpty)
  }

  test("Encode an empty query string") {
    assert(QueryParamEncoder.encode(Map.empty) == "")
  }

  test("Decodes both '%20' and '+' as `space`") {
    Seq(
      "?foo%20=bar",
      "?foo+=bar"
    ).foreach { s =>
      val result = QueryParamDecoder.decode(s)
      assert(result.size == 1)
      val params = result.get("foo ")
      assert(params.size == 1)
      assert(params.get(0) == "bar")
    }
  }

  test("Illegal query params") {
    Seq(
      "?f%tf=bar", // Illegal hex char
      "?foo%=bar", // missing hex chars
      "?foo%d=bar" // missing hex char
    ).foreach { uri =>
      intercept[IllegalArgumentException] {
        QueryParamDecoder.decode(uri)
      }
    }
  }

  private def collisions(num: Int, length: Int): Iterator[String] = {
    val equiv = Array("Aa", "BB")

    // returns a length 2n string, indexed by x
    // 0 <= x < 2^n
    // for a fixed n, all strings have the same hashCode
    def f(x: Int, n: Int): String = n match {
      case 0 => ""
      case _ => equiv(x % 2) + f(x / 2, n - 1)
    }

    (0 until num).toIterator.map(f(_, length))
  }

  test("massive number of collisions isn't super slow") {
    // Using a quad core laptop i7 (single threaded) this many params took 399771 ms
    // for scala HashMap and 277 ms using the Java LinkedHashMap on Java 8.
    val num = 100 * 1000

    val cs = collisions(num, 22)
    val queryString = cs.map(_ + "=a").mkString("?", "&", "")

    eventually {
      val stopwatch = Stopwatch.start()
      val result = QueryParamDecoder.decode(queryString)
      assert(result.size == num)
      // we give a generous 2 seconds to complete, 10x what was observed in local
      // testing because CI can be slow at times. We'd expect quadratic behavior
      // to take two orders of magnitude longer, so just making sure it's below
      // 2 seconds should be enough to confirm we're not vulnerable to DoS attack.
      assert(stopwatch() < 2.seconds)
    }
  }
}


text:
from pprint import pformat
from six import iteritems
import re

class PollQuestionSampleSubpopulations(object):
    """
    NOTE: This class is auto generated by the swagger code generator program.
    Do not edit the class manually.
    """
    def __init__(self, observations=None, name=None, margin_of_error=None, responses=None):
        """
        PollQuestionSampleSubpopulations - a model defined in Swagger

        :param dict swaggerTypes: The key is attribute name
                                  and the value is attribute type.
        :param dict attributeMap: The key is attribute name
                                  and the value is json key in definition.
        """
        self.swagger_types = {
            'observations': 'int',
            'name': 'str',
            'margin_of_error': 'float',
            'responses': 'list[PollQuestionResponses]'
        }

        self.attribute_map = {
            'observations': 'observations',
            'name': 'name',
            'margin_of_error': 'margin_of_error',
            'responses': 'responses'
        }

        self._observations = observations
        self._name = name
        self._margin_of_error = margin_of_error
        self._responses = responses

    @property
    def observations(self):
        """
        Gets the observations of this PollQuestionSampleSubpopulations.
        Number of people in this subpopulation who responded to this question, or `null` if the survey house did not report a number.

        :return: The observations of this PollQuestionSampleSubpopulations.
        :rtype: int
        """
        return self._observations

    @property
    def name(self):
        """
        Gets the name of this PollQuestionSampleSubpopulations.
        One of: Adults, Adults - Democrat, Adults - Republican, Adults - independent, Registered Voters, Registered Voters - Democrat, Registered Voters - Republican, Registered Voters - independent, Likely Voters, Likely Voters - Democrat, Likely Voters - Republican, Likely Voters - independent. `Likely Voters` is editorially important during election seasons; sometimes Pollster editors will skip all other subpopulations.

        :return: The name of this PollQuestionSampleSubpopulations.
        :rtype: str
        """
        return self._name

    @property
    def margin_of_error(self):
        """
        Gets the margin_of_error of this PollQuestionSampleSubpopulations.
        Margin of error for this subpopulation, or `null` if the survey house did not report a number.

        :return: The margin_of_error of this PollQuestionSampleSubpopulations.
        :rtype: float
        """
        return self._margin_of_error

    @property
    def responses(self):
        """
        Gets the responses of this PollQuestionSampleSubpopulations.
        Options the survey house provided to respondents, and respondents' answers. These are ordered randomly.

        :return: The responses of this PollQuestionSampleSubpopulations.
        :rtype: list[PollQuestionResponses]
        """
        return self._responses

    def to_dict(self):
        """
        Returns the model properties as a dict
        """
        result = {}

        for attr, _ in iteritems(self.swagger_types):
            value = getattr(self, attr)
            if isinstance(value, list):
                result[attr] = list(map(
                    lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
                    value
                ))
            elif hasattr(value, "to_dict"):
                result[attr] = value.to_dict()
            elif isinstance(value, dict):
                result[attr] = dict(map(
                    lambda item: (item[0], item[1].to_dict())
                    if hasattr(item[1], "to_dict") else item,
                    value.items()
                ))
            else:
                result[attr] = value

        return result

    def to_str(self):
        """
        Returns the string representation of the model
        """
        return pformat(self.to_dict())

    def __repr__(self):
        """
        For `print` and `pprint`
        """
        return self.to_str()

    def __eq__(self, other):
        """
        Returns true if both objects are equal
        """
        return self.__dict__ == other.__dict__

    def __ne__(self, other):
        """
        Returns true if both objects are not equal
        """
        return not self == other


text:
from setuptools import setup, find_packages
from codecs import open
from os import path

here = path.abspath(path.dirname(__file__))

with open(path.join(here, 'README.rst'), encoding='utf-8') as f:
    long_description = f.read()

setup(
    name='yarntf',
    version='0.0.1.dev22',
    description='Easy distributed TensorFlow on Hadoop',
    long_description=long_description,
    url='https://github.com/tobiajo/yarntf',
    author='Tobias Johansson',
    author_email='tobias@johansson.xyz',
    license='Apache License 2.0',
    classifiers=[
        'Development Status :: 2 - Pre-Alpha',
        'Intended Audience :: Developers',
        'Topic :: Software Development :: Libraries',
        'License :: OSI Approved :: Apache Software License',
        'Programming Language :: Python :: 2.7',
    ],
    keywords='yarn tf hadoop tensorflow',
    packages=find_packages(exclude=['examples']),
    install_requires=['grpcio', 'tensorflow'],
)


text:
#include "encoderutils.hpp"
#include "simpletest.hpp"
#include "memoryutil.hpp"
#include "built_safe_safemessageone.hpp"
#include "built_unsafe_safemessageone.hpp"
#include <fudge-cpp/exception.hpp>
#include <cstdio>

using namespace fudgeproto;
using namespace built;

static fudge::message buildMessage ( bool safe )
{
    fudge::message innermessage, outermessage;
    innermessage.addField ( 2.048f, fudge::string ( "floating" ) );

    if ( safe )
        innermessage.addField ( fudge::string ( "built.safe.SafeMessageTwo" ),
                                fudge::message::noname, 0 );

    outermessage.addField ( 1024, fudge::string ( "integer" ) );
    outermessage.addField ( innermessage, fudge::string ( "nested" ) );

    if ( safe )
        outermessage.addField ( fudge::string ( "built.safe.SafeMessageOne" ),
                                fudge::message::noname, 0 );

    return outermessage;
}

DEFINE_TEST( SafeWorking )
    fudge::message encoded ( buildMessage ( true ) );

    safe::SafeMessageOne decoded;
    TEST_THROWS_NOTHING( decoded.fromFudgeMessage ( encoded ) );

    TEST_EQUALS_INT( decoded.integer ( ), 1024 );
    TEST_EQUALS_TRUE( decoded.nested ( ) != 0 );
    TEST_EQUALS_FLOAT( decoded.nested ( )->floating ( ), 2.048f, 0.0001f );
END_TEST

DEFINE_TEST( SafeFailed )
    fudge::message encoded ( buildMessage ( false ) );

    safe::SafeMessageOne decoded;
    TEST_THROWS_EXCEPTION( decoded.fromFudgeMessage ( encoded ), fudge::exception );
END_TEST

DEFINE_TEST( UnsafeWorking )
    fudge::message encoded ( buildMessage ( false ) );

    unsafe::SafeMessageOne decoded;
    TEST_THROWS_NOTHING( decoded.fromFudgeMessage ( encoded ) );

    TEST_EQUALS_INT( decoded.integer ( ), 1024 );
    TEST_EQUALS_TRUE( decoded.nested ( ) != 0 );
    TEST_EQUALS_FLOAT( decoded.nested ( )->floating ( ), 2.048f, 0.0001f );
END_TEST

DEFINE_TEST_SUITE( SafeMessage )
    REGISTER_TEST( SafeWorking )
    REGISTER_TEST( SafeFailed )
    REGISTER_TEST( UnsafeWorking )
END_TEST_SUITE


text:
=============
Testing shell
=============

``shell`` maintains 100% passing tests at all times. That said, there are
undoubtedly bugs or odd configurations it doesn't cover.

Setup
=====

Getting setup to run tests (Python 2) looks like::

    $ git clone https://github.com/toastdriven/shell
    $ cd shell
    $ virtualenv env
    $ . env/bin/activate
    $ pip install mock==1.0.1
    $ pip install nose==1.3.0

Once that's setup, setting up for Python 3 looks like::

    $ virtualenv -p python3 env3
    $ . env3/bin/activate
    $ pip install mock==1.0.1
    $ pip install nose==1.3.0

Running the tests
=================

To run the tests, run the following::

    $ nosetests -s tests.py


text:
#ifndef __SYSDEP_MIXER_H
#define __SYSDEP_MIXER_H

#include "rc.h"
#include "begin_code.h"

/* channel defines */
#define SYSDEP_MIXER_VOLUME	0
#define SYSDEP_MIXER_PCM1	1
#define SYSDEP_MIXER_PCM2	2
#define SYSDEP_MIXER_SYNTH	3
#define SYSDEP_MIXER_CD		4
#define SYSDEP_MIXER_LINE1	5
#define SYSDEP_MIXER_LINE2	6
#define SYSDEP_MIXER_LINE3	7
#define SYSDEP_MIXER_BASS	8
#define SYSDEP_MIXER_TREBLE	9
#define SYSDEP_MIXER_CHANNELS	10
#define SYSDEP_MIXER_NAMES { "Volume", "PCM 1", "PCM 2", "Synth", \
   "CD", "Line 1", "Line 2", "Line 3", "Bass", "Treble" }

/* flags for sysdep_mixer_create */
#define SYSDEP_MIXER_RESTORE_SETTINS_ON_EXIT 0x01

struct sysdep_mixer_struct;

int sysdep_mixer_init(struct rc_struct *rc, const char *plugin_path);
void sysdep_mixer_exit(void);

struct sysdep_mixer_struct *sysdep_mixer_create(const char *plugin,
   const char *device, int flags);
void sysdep_mixer_destroy(struct sysdep_mixer_struct *dsp);

int sysdep_mixer_channel_available(struct sysdep_mixer_struct *mixer,
   int channel);

int sysdep_mixer_set(struct sysdep_mixer_struct *mixer, int channel,
   int left, int right);
int sysdep_mixer_get(struct sysdep_mixer_struct *mixer, int channel,
   int *left, int *right);

#include "end_code.h"
#endif /* ifndef __SYSDEP_MIXER_H */


text:
using System;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Cobalt.Core.Network
{
	#region SocksException class
	[Serializable]
	public class SocksException : Exception
	{
		public SocksException(string message)
			: base(message)
		{
		}
	}
	#endregion

	public class SocksTcpClient
	{
		private const int SocksTimeout = 30000;

		private class AsyncResult : IAsyncResult
		{
			public object AsyncState { get; private set; }
			public WaitHandle AsyncWaitHandle { get { return this.Event; } }
			public bool CompletedSynchronously { get { return false; } }
			public bool IsCompleted { get { return this.AsyncWaitHandle.WaitOne(0); } }
			public EventWaitHandle Event { get; private set; }
			public AsyncCallback Callback { get; private set; }
			public string Hostname { get; set; }
			public int Port { get; set; }
			public Exception Exception { get; set; }
			public TcpClient Client { get; set; }

			public AsyncResult(AsyncCallback callback, object state)
			{
				this.Event = new ManualResetEvent(false);
				this.AsyncState = state;
			}
		}

		private readonly ProxyInfo _info;

		public SocksTcpClient(ProxyInfo proxy)
		{
			_info = proxy;
		}

		public IAsyncResult BeginConnect(string hostName, int port, AsyncCallback callback = null, object state = null)
		{
			var ar = new AsyncResult(callback, state) { Hostname = hostName, Port = port };
			ar.Client = new TcpClient();
			ar.Client.BeginConnect(_info.ProxyHostname, _info.ProxyPort, OnConnected, ar);
			return ar;
		}

		public TcpClient EndConnect(IAsyncResult ar)
		{
			var result = ar as AsyncResult;
			if (result == null)
			{
				throw new InvalidOperationException("IAsyncResult is not from this operation.");
			}
			ar.AsyncWaitHandle.WaitOne();
			if (result.Exception != null)
			{
				throw result.Exception;
			}
			return result.Client;
		}

	    public async Task<TcpClient> ConnectAsync(string hostname, int port)
	    {
	        TcpClient client = new TcpClient();
	        await client.ConnectAsync(hostname, port);
	        DoHandshake(client, hostname, port);
	        return client;
	    }

		private void OnConnected(IAsyncResult ar)
		{
			var result = ar.AsyncState as AsyncResult;

			try
			{
				result.Client.EndConnect(ar);
				this.DoHandshake(result);
			}
			catch (Exception ex)
			{
				result.Client.Close();
				result.Exception = ex;
			}
			finally
			{
				result.Event.Set();
			    result.Callback?.Invoke(result);
			}
		}

	    private async Task DoHandshakeAsync(TcpClient client, string hostname, int port)
	    {
            bool useAuth = _info.ProxyUsername != null && _info.ProxyPassword != null;

            var stream = client.GetStream();
            await stream.WriteByteAsync(0x05); // SOCKS v5
            await stream.WriteByteAsync(useAuth ? (byte)0x2 : (byte)0x1); // auth protocols supported
            await stream.WriteByteAsync(0x00); // no auth
            if (useAuth)
            {
                await stream.WriteByteAsync(0x02); // user/pass
            }

            var buffer = new byte[256];
            this.Read(stream, buffer, 2);

            byte method = buffer[1];
            if (method == 0x2)
            {
                stream.WriteByte(0x1);
                this.WriteString(stream, _info.ProxyUsername);
                this.WriteString(stream, _info.ProxyPassword);
                this.Read(stream, buffer, 2);
                if (buffer[1] != 0x0)
                {
                    throw new SocksException($"Proxy authentication failed with code {buffer[1].ToString()}.");
                }
            }

            stream.WriteByte(0x5); // SOCKS v5
            stream.WriteByte(0x1); // TCP stream
            stream.WriteByte(0x0); // reserved
            stream.WriteByte(0x3); // domain name
            this.WriteString(stream, hostname); // hostname
            stream.WriteByte((byte)((port >> 8) & 0xFF)); // port high byte
            stream.WriteByte((byte)(port & 0xff)); // port low byte

            this.Read(stream, buffer, 4);
            switch (buffer[1])
            {
                case 0x1:
                    throw new SocksException("General failure.");
                case 0x2:
                    throw new SocksException("Connection not allowed by ruleset.");
                case 0x3:
                    throw new SocksException("Network unreachable.");
                case 0x4:
                    throw new SocksException("Host unreachable.");
                case 0x5:
                    throw new SocksException("Connection refused by destination host.");
                case 0x6:
                    throw new SocksException("TTL expired.");
                case 0x7:
                    throw new SocksException("Command not supported / protocol error.");
                case 0x8:
                    throw new SocksException("Address type not supported.");
            }
            switch (buffer[3])
            {
                case 0x1:
                    this.Read(stream, buffer, 4);
                    break;
                case 0x3:
                    this.ReadString(stream, buffer);
                    break;
                case 0x4:
                    this.Read(stream, buffer, 16);
                    break;
            }
            this.Read(stream, buffer, 2);
        }

	    private void DoHandshake(TcpClient client, string hostname, int port)
	    {
            bool useAuth = _info.ProxyUsername != null && _info.ProxyPassword != null;

	        var stream = client.GetStream();
            stream.WriteByte(0x05); // SOCKS v5
            stream.WriteByte(useAuth ? (byte)0x2 : (byte)0x1); // auth protocols supported
            stream.WriteByte(0x00); // no auth
            if (useAuth)
            {
                stream.WriteByte(0x02); // user/pass
            }

            var buffer = new byte[256];
            this.Read(stream, buffer, 2);

            byte method = buffer[1];
            if (method == 0x2)
            {
                stream.WriteByte(0x1);
                this.WriteString(stream, _info.ProxyUsername);
                this.WriteString(stream, _info.ProxyPassword);
                this.Read(stream, buffer, 2);
                if (buffer[1] != 0x0)
                {
                    throw new SocksException($"Proxy authentication failed with code {buffer[1].ToString()}.");
                }
            }

            stream.WriteByte(0x5); // SOCKS v5
            stream.WriteByte(0x1); // TCP stream
            stream.WriteByte(0x0); // reserved
            stream.WriteByte(0x3); // domain name
            this.WriteString(stream, hostname); // hostname
            stream.WriteByte((byte)((port >> 8) & 0xFF)); // port high byte
            stream.WriteByte((byte)(port & 0xff)); // port low byte

            this.Read(stream, buffer, 4);
            switch (buffer[1])
            {
                case 0x1:
                    throw new SocksException("General failure.");
                case 0x2:
                    throw new SocksException("Connection not allowed by ruleset.");
                case 0x3:
                    throw new SocksException("Network unreachable.");
                case 0x4:
                    throw new SocksException("Host unreachable.");
                case 0x5:
                    throw new SocksException("Connection refused by destination host.");
                case 0x6:
                    throw new SocksException("TTL expired.");
                case 0x7:
                    throw new SocksException("Command not supported / protocol error.");
                case 0x8:
                    throw new SocksException("Address type not supported.");
            }
            switch (buffer[3])
            {
                case 0x1:
                    this.Read(stream, buffer, 4);
                    break;
                case 0x3:
                    this.ReadString(stream, buffer);
                    break;
                case 0x4:
                    this.Read(stream, buffer, 16);
                    break;
            }
            this.Read(stream, buffer, 2);
        }

		private void DoHandshake(AsyncResult result)
		{
		    DoHandshake(result.Client, result.Hostname, result.Port);
		}

		private void WriteString(NetworkStream stream, string str)
		{
			if (str.Length > 255)
			{
				str = str.Substring(0, 255);
			}
			stream.WriteByte((byte)str.Length);
			var buffer = Encoding.ASCII.GetBytes(str);
			stream.Write(buffer, 0, buffer.Length);
		}

	    private async Task WriteStringAsync(NetworkStream stream, string str)
	    {
	        if (str.Length > 255)
	        {
	            str = str.Substring(0, 255);
	        }
	        await stream.WriteByteAsync((byte) str.Length);
	        var buffer = Encoding.ASCII.GetBytes(str);
	        await stream.WriteAsync(buffer, 0, buffer.Length);
	    }

		private string ReadString(NetworkStream stream, byte[] buffer)
		{
			this.Read(stream, buffer, 1);
			int length = buffer[0];
			this.Read(stream, buffer, length);
			return Encoding.ASCII.GetString(buffer, 0, length);
		}

	    private async Task<string> ReadStringAsync(NetworkStream stream, byte[] buffer)
	    {
	        await ReadAsync(stream, buffer, 1);
	        int length = buffer[0];
	        await ReadAsync(stream, buffer, length);
	        return Encoding.ASCII.GetString(buffer, 0, length);
	    }

	    private async Task<int> ReadAsync(NetworkStream stream, byte[] buffer, int count)
	    {
	        var timeout = Task.Delay(SocksTimeout);
	        var readTask = stream.ReadAsync(buffer, 0, count);
	        var completed = await Task.WhenAny(timeout, readTask).ConfigureAwait(false);
	        if (completed == readTask)
	        {
	            int read = await readTask; // so we can throw exceptions
	            if (read < 2)
	            {
	                throw new SocksException("Unable to negotiate with the proxy.");
	            }
	            else
	            {
	                return read;
	            }
	        }
	        else
	        {
	            throw new SocksException("The proxy did not respond in a timely manner.");
	        }
	    }

		private int Read(NetworkStream stream, byte[] buffer, int count)
		{
			var ar = stream.BeginRead(buffer, 0, count, null, null);
			if (!ar.AsyncWaitHandle.WaitOne(SocksTimeout))
			{
				throw new SocksException("The proxy did not respond in a timely manner.");
			}
			count = stream.EndRead(ar);
			if (count < 2)
			{
				throw new SocksException("Unable to negotiate with the proxy.");
			}
			return count;
		}
	}
}


text:
set system parameters 'create_table_reuseoid=no';

call login ('dba','') on CLASS db_user;
create USER user1;

CREATE TABLE StateCity(State CHAR(20), City CHAR(20));
CREATE TABLE Company  (Name CHAR(20), Location StateCity not null primary KEY, Budget FLOAT);

insert into company values('name1',insert into statecity values('state1','city1'),1);
call login ('user1','') on CLASS db_user;

select * from dba.company;

call login ('dba','') on CLASS db_user;
drop CLASS Company;
drop CLASS StateCity;

DROP USER user1;

set system parameters 'create_table_reuseoid=yes';
--+ holdcas off;


text:
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "content/browser/preloading/prefetcher.h"

#include <vector>

#include "base/test/scoped_feature_list.h"
#include "content/browser/preloading/prefetch/prefetch_document_manager.h"
#include "content/browser/preloading/prefetch/prefetch_features.h"
#include "content/browser/preloading/prefetch/prefetch_service.h"
#include "content/public/browser/speculation_host_delegate.h"
#include "content/public/common/content_client.h"
#include "content/public/test/test_browser_context.h"
#include "content/public/test/test_renderer_host.h"
#include "content/test/test_content_browser_client.h"
#include "content/test/test_web_contents.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace content {
namespace {

class MockSpeculationHostDelegate : public SpeculationHostDelegate {
 public:
  explicit MockSpeculationHostDelegate(
      content::RenderFrameHost& render_frame_host) {}
  ~MockSpeculationHostDelegate() override = default;

  void ProcessCandidates(
      std::vector<blink::mojom::SpeculationCandidatePtr>& candidates,
      base::WeakPtr<SpeculationHostDevToolsObserver> devtools_observer)
      override {
    for (auto&& candidate : candidates) {
      candidates_.push_back(std::move(candidate));
    }
  }
  std::vector<blink::mojom::SpeculationCandidatePtr>& Candidates() {
    return candidates_;
  }

 private:
  std::vector<blink::mojom::SpeculationCandidatePtr> candidates_;
};

class TestPrefetchService : public PrefetchService {
 public:
  explicit TestPrefetchService(BrowserContext* browser_context)
      : PrefetchService(browser_context) {}

  void PrefetchUrl(
      base::WeakPtr<PrefetchContainer> prefetch_container) override {
    prefetches_.push_back(prefetch_container);

    const auto& devtools_observer = prefetch_container->GetDevToolsObserver();
    std::unique_ptr<network::ResourceRequest> request =
        std::make_unique<network::ResourceRequest>();
    network::ResourceRequest::TrustedParams trusted_params;
    request->trusted_params = trusted_params;
    request->trusted_params->devtools_observer =
        devtools_observer->MakeSelfOwnedNetworkServiceDevToolsObserver();
    devtools_observer->OnStartSinglePrefetch(prefetch_container->RequestId(),
                                             *request);

    network::mojom::URLResponseHead response_head;
    devtools_observer->OnPrefetchResponseReceived(
        prefetch_container->GetURL(), prefetch_container->RequestId(),
        response_head);

    devtools_observer->OnPrefetchRequestComplete(
        prefetch_container->RequestId(),
        network::URLLoaderCompletionStatus{net::ERR_NOT_IMPLEMENTED});

    devtools_observer->OnPrefetchBodyDataReceived(
        prefetch_container->RequestId(), /*body*/ std::string{},
        /*is_base64_encoded=*/false);
  }

  std::vector<base::WeakPtr<PrefetchContainer>> prefetches_;
};

class MockContentBrowserClient : public TestContentBrowserClient {
 public:
  MockContentBrowserClient() {
    old_browser_client_ = SetBrowserClientForTesting(this);
  }
  ~MockContentBrowserClient() override {
    EXPECT_EQ(this, SetBrowserClientForTesting(old_browser_client_));
  }

  std::unique_ptr<SpeculationHostDelegate> CreateSpeculationHostDelegate(
      RenderFrameHost& render_frame_host) override {
    auto delegate =
        std::make_unique<MockSpeculationHostDelegate>(render_frame_host);
    delegate_ = delegate.get();
    return delegate;
  }

  MockSpeculationHostDelegate* GetDelegate() { return delegate_; }

 private:
  raw_ptr<ContentBrowserClient> old_browser_client_;
  raw_ptr<MockSpeculationHostDelegate> delegate_;
};

class PrefetcherTest : public RenderViewHostTestHarness {
 public:
  PrefetcherTest() = default;
  void SetUp() override {
    RenderViewHostTestHarness::SetUp();

    browser_context_ = std::make_unique<TestBrowserContext>();
    web_contents_ = TestWebContents::Create(
        browser_context_.get(),
        SiteInstanceImpl::Create(browser_context_.get()));
    web_contents_->NavigateAndCommit(GetSameOriginUrl("/"));
    prefetch_service_ =
        std::make_unique<TestPrefetchService>(GetBrowserContext());
    PrefetchDocumentManager::SetPrefetchServiceForTesting(
        prefetch_service_.get());
  }
  void TearDown() override {
    web_contents_.reset();
    browser_context_.reset();
    PrefetchDocumentManager::SetPrefetchServiceForTesting(nullptr);
    RenderViewHostTestHarness::TearDown();
  }

  RenderFrameHostImpl& GetPrimaryMainFrame() {
    return web_contents_->GetPrimaryPage().GetMainDocument();
  }

  GURL GetSameOriginUrl(const std::string& path) {
    return GURL("https://example.com" + path);
  }

  GURL GetCrossOriginUrl(const std::string& path) {
    return GURL("https://other.example.com" + path);
  }

  TestPrefetchService* GetPrefetchService() { return prefetch_service_.get(); }

 private:
  std::unique_ptr<TestBrowserContext> browser_context_;
  std::unique_ptr<TestWebContents> web_contents_;
  std::unique_ptr<TestPrefetchService> prefetch_service_;
};

TEST_F(PrefetcherTest, PrefetcherWithDelegate) {
  MockContentBrowserClient browser_client;
  auto prefetcher = Prefetcher(GetPrimaryMainFrame());
  auto* delegate = browser_client.GetDelegate();
  EXPECT_TRUE(delegate != nullptr);

  // Create list of SpeculationCandidatePtrs.
  std::vector<blink::mojom::SpeculationCandidatePtr> candidates;

  auto candidate1 = blink::mojom::SpeculationCandidate::New();
  candidate1->action = blink::mojom::SpeculationAction::kPrefetch;
  candidate1->requires_anonymous_client_ip_when_cross_origin = true;
  candidate1->url = GetCrossOriginUrl("/candidate1.html");
  candidate1->referrer = blink::mojom::Referrer::New();
  candidates.push_back(std::move(candidate1));

  prefetcher.ProcessCandidatesForPrefetch(candidates);
  EXPECT_EQ(1u, delegate->Candidates().size());

  EXPECT_TRUE(prefetcher.IsPrefetchAttemptFailedOrDiscarded(
      GetCrossOriginUrl("/candidate1.html")));
}

TEST_F(PrefetcherTest, PrefetcherWithoutDelegate) {
  base::test::ScopedFeatureList scoped_feature_list;
  scoped_feature_list.InitAndEnableFeatureWithParameters(
      content::features::kPrefetchUseContentRefactor,
      {{"proxy_host", "https://testproxyhost.com"}});

  MockContentBrowserClient browser_client;
  auto prefetcher = Prefetcher(GetPrimaryMainFrame());
  auto* delegate = browser_client.GetDelegate();
  EXPECT_TRUE(delegate != nullptr);

  // Create list of SpeculationCandidatePtrs.
  std::vector<blink::mojom::SpeculationCandidatePtr> candidates;

  auto candidate1 = blink::mojom::SpeculationCandidate::New();
  candidate1->action = blink::mojom::SpeculationAction::kPrefetch;
  candidate1->requires_anonymous_client_ip_when_cross_origin = true;
  candidate1->url = GetCrossOriginUrl("/candidate1.html");
  candidate1->referrer = blink::mojom::Referrer::New();
  candidates.push_back(std::move(candidate1));

  prefetcher.ProcessCandidatesForPrefetch(candidates);
  EXPECT_TRUE(delegate->Candidates().empty());
  EXPECT_EQ(1u, GetPrefetchService()->prefetches_.size());

  EXPECT_FALSE(prefetcher.IsPrefetchAttemptFailedOrDiscarded(
      GetCrossOriginUrl("/candidate1.html")));
  GetPrefetchService()->prefetches_[0]->SetPrefetchStatus(
      PrefetchStatus::kPrefetchFailedNetError);
  EXPECT_TRUE(prefetcher.IsPrefetchAttemptFailedOrDiscarded(
      GetCrossOriginUrl("/candidate1.html")));
}

class MockPrefetcher : public Prefetcher {
 public:
  explicit MockPrefetcher(content::RenderFrameHost& render_frame_host)
      : Prefetcher(render_frame_host) {}

  void OnStartSinglePrefetch(const std::string& request_id,
                             const network::ResourceRequest& request) override {
    on_start_signle_prefetch_was_called_ = true;
    dev_tools_observer_is_valid_ =
        request.trusted_params->devtools_observer.is_valid();
  }
  void OnPrefetchResponseReceived(
      const GURL& url,
      const std::string& request_id,
      const network::mojom::URLResponseHead& response) override {
    on_prefetch_response_received_was_called_ = true;
  }
  void OnPrefetchRequestComplete(
      const std::string& request_id,
      const network::URLLoaderCompletionStatus& status) override {
    on_prefetch_request_complete_was_called_ = true;
  }
  void OnPrefetchBodyDataReceived(const std::string& request_id,
                                  const std::string& body,
                                  bool is_base64_encoded) override {
    on_prefetch_body_data_received_was_called_ = true;
  }

  bool on_start_signle_prefetch_was_called_ = false;
  bool on_prefetch_response_received_was_called_ = false;
  bool on_prefetch_request_complete_was_called_ = false;
  bool on_prefetch_body_data_received_was_called_ = false;
  bool dev_tools_observer_is_valid_ = false;
};

TEST_F(PrefetcherTest, MockPrefetcher) {
  base::test::ScopedFeatureList scoped_feature_list;
  scoped_feature_list.InitAndEnableFeatureWithParameters(
      content::features::kPrefetchUseContentRefactor,
      {{"proxy_host", "https://testproxyhost.com"}});

  MockContentBrowserClient browser_client;
  auto prefetcher = MockPrefetcher(GetPrimaryMainFrame());
  auto* delegate = browser_client.GetDelegate();
  EXPECT_TRUE(delegate != nullptr);

  // Create list of SpeculationCandidatePtrs.
  std::vector<blink::mojom::SpeculationCandidatePtr> candidates;

  auto candidate1 = blink::mojom::SpeculationCandidate::New();
  candidate1->action = blink::mojom::SpeculationAction::kPrefetch;
  candidate1->requires_anonymous_client_ip_when_cross_origin = true;
  candidate1->url = GetCrossOriginUrl("/candidate1.html");
  candidate1->referrer = blink::mojom::Referrer::New();
  candidates.push_back(std::move(candidate1));

  prefetcher.ProcessCandidatesForPrefetch(candidates);
  EXPECT_TRUE(delegate->Candidates().empty());
  EXPECT_EQ(1u, GetPrefetchService()->prefetches_.size());

  EXPECT_TRUE(prefetcher.on_start_signle_prefetch_was_called_);
  EXPECT_TRUE(prefetcher.on_prefetch_response_received_was_called_);
  EXPECT_TRUE(prefetcher.on_prefetch_request_complete_was_called_);
  EXPECT_TRUE(prefetcher.on_prefetch_body_data_received_was_called_);
  EXPECT_TRUE(prefetcher.dev_tools_observer_is_valid_);
}

}  // namespace
}  // namespace content


text:
export default /* glsl */`
uniform vec3 fog_color;
uniform float fog_start;
uniform float fog_end;
float dBlendModeFogFactor = 1.0;

vec3 addFog(vec3 color) {
    float depth = gl_FragCoord.z / gl_FragCoord.w;
    float fogFactor = (fog_end - depth) / (fog_end - fog_start);
    fogFactor = clamp(fogFactor, 0.0, 1.0);
    return mix(fog_color * dBlendModeFogFactor, color, fogFactor);
}
`;


text:
(function( global, undefined ) {

var slice = [].slice,
	subscriptions = {};

var amplify = global.amplify = {
	publish: function( topic ) {
		if ( typeof topic !== "string" ) {
			throw new Error( "You must provide a valid topic to publish." );
		}

		var args = slice.call( arguments, 1 ),
			topicSubscriptions,
			subscription,
			length,
			i = 0,
			ret;

		if ( !subscriptions[ topic ] ) {
			return true;
		}

		topicSubscriptions = subscriptions[ topic ].slice();
		for ( length = topicSubscriptions.length; i < length; i++ ) {
			subscription = topicSubscriptions[ i ];
			ret = subscription.callback.apply( subscription.context, args );
			if ( ret === false ) {
				break;
			}
		}
		return ret !== false;
	},

	subscribe: function( topic, context, callback, priority ) {
		if ( typeof topic !== "string" ) {
			throw new Error( "You must provide a valid topic to create a subscription." );
		}

		if ( arguments.length === 3 && typeof callback === "number" ) {
			priority = callback;
			callback = context;
			context = null;
		}
		if ( arguments.length === 2 ) {
			callback = context;
			context = null;
		}
		priority = priority || 10;

		var topicIndex = 0,
			topics = topic.split( /\s/ ),
			topicLength = topics.length,
			added;
		for ( ; topicIndex < topicLength; topicIndex++ ) {
			topic = topics[ topicIndex ];
			added = false;
			if ( !subscriptions[ topic ] ) {
				subscriptions[ topic ] = [];
			}

			var i = subscriptions[ topic ].length - 1,
				subscriptionInfo = {
					callback: callback,
					context: context,
					priority: priority
				};

			for ( ; i >= 0; i-- ) {
				if ( subscriptions[ topic ][ i ].priority <= priority ) {
					subscriptions[ topic ].splice( i + 1, 0, subscriptionInfo );
					added = true;
					break;
				}
			}

			if ( !added ) {
				subscriptions[ topic ].unshift( subscriptionInfo );
			}
		}

		return callback;
	},

	unsubscribe: function( topic, context, callback ) {
		if ( typeof topic !== "string" ) {
			throw new Error( "You must provide a valid topic to remove a subscription." );
		}

		if ( arguments.length === 2 ) {
			callback = context;
			context = null;
		}

		if ( !subscriptions[ topic ] ) {
			return;
		}

		var length = subscriptions[ topic ].length,
			i = 0;

		for ( ; i < length; i++ ) {
			if ( subscriptions[ topic ][ i ].callback === callback ) {
				if ( !context || subscriptions[ topic ][ i ].context === context ) {
					subscriptions[ topic ].splice( i, 1 );

					// Adjust counter and length for removed item
					i--;
					length--;
				}
			}
		}
	}
};

}( this ) );

(function( amplify, undefined ) {

var store = amplify.store = function( key, value, options ) {
	var type = store.type;
	if ( options && options.type && options.type in store.types ) {
		type = options.type;
	}
	return store.types[ type ]( key, value, options || {} );
};

store.types = {};
store.type = null;
store.addType = function( type, storage ) {
	if ( !store.type ) {
		store.type = type;
	}

	store.types[ type ] = storage;
	store[ type ] = function( key, value, options ) {
		options = options || {};
		options.type = type;
		return store( key, value, options );
	};
};
store.error = function() {
	return "amplify.store quota exceeded";
};

var rprefix = /^__amplify__/;
function createFromStorageInterface( storageType, storage ) {
	store.addType( storageType, function( key, value, options ) {
		var storedValue, parsed, i, remove,
			ret = value,
			now = (new Date()).getTime();

		if ( !key ) {
			ret = {};
			remove = [];
			i = 0;
			try {
				// accessing the length property works around a localStorage bug
				// in Firefox 4.0 where the keys don't update cross-page
				// we assign to key just to avoid Closure Compiler from removing
				// the access as "useless code"
				// https://bugzilla.mozilla.org/show_bug.cgi?id=662511
				key = storage.length;

				while ( key = storage.key( i++ ) ) {
					if ( rprefix.test( key ) ) {
						parsed = JSON.parse( storage.getItem( key ) );
						if ( parsed.expires && parsed.expires <= now ) {
							remove.push( key );
						} else {
							ret[ key.replace( rprefix, "" ) ] = parsed.data;
						}
					}
				}
				while ( key = remove.pop() ) {
					storage.removeItem( key );
				}
			} catch ( error ) {}
			return ret;
		}

		// protect against name collisions with direct storage
		key = "__amplify__" + key;

		if ( value === undefined ) {
			storedValue = storage.getItem( key );
			parsed = storedValue ? JSON.parse( storedValue ) : { expires: -1 };
			if ( parsed.expires && parsed.expires <= now ) {
				storage.removeItem( key );
			} else {
				return parsed.data;
			}
		} else {
			if ( value === null ) {
				storage.removeItem( key );
			} else {
				parsed = JSON.stringify({
					data: value,
					expires: options.expires ? now + options.expires : null
				});
				try {
					storage.setItem( key, parsed );
				// quota exceeded
				} catch( error ) {
					// expire old data and try again
					store[ storageType ]();
					try {
						storage.setItem( key, parsed );
					} catch( error ) {
						throw store.error();
					}
				}
			}
		}

		return ret;
	});
}

// localStorage + sessionStorage
// IE 8+, Firefox 3.5+, Safari 4+, Chrome 4+, Opera 10.5+, iPhone 2+, Android 2+
for ( var webStorageType in { localStorage: 1, sessionStorage: 1 } ) {
	// try/catch for file protocol in Firefox and Private Browsing in Safari 5
	try {
		// Safari 5 in Private Browsing mode exposes localStorage
		// but doesn't allow storing data, so we attempt to store and remove an item.
		// This will unfortunately give us a false negative if we're at the limit.
		window[ webStorageType ].setItem( "__amplify__", "x" );
		window[ webStorageType ].removeItem( "__amplify__" );
		createFromStorageInterface( webStorageType, window[ webStorageType ] );
	} catch( e ) {}
}

// globalStorage
// non-standard: Firefox 2+
// https://developer.mozilla.org/en/dom/storage#globalStorage
if ( !store.types.localStorage && window.globalStorage ) {
	// try/catch for file protocol in Firefox
	try {
		createFromStorageInterface( "globalStorage",
			window.globalStorage[ window.location.hostname ] );
		// Firefox 2.0 and 3.0 have sessionStorage and globalStorage
		// make sure we default to globalStorage
		// but don't default to globalStorage in 3.5+ which also has localStorage
		if ( store.type === "sessionStorage" ) {
			store.type = "globalStorage";
		}
	} catch( e ) {}
}

// userData
// non-standard: IE 5+
// http://msdn.microsoft.com/en-us/library/ms531424(v=vs.85).aspx
(function() {
	// IE 9 has quirks in userData that are a huge pain
	// rather than finding a way to detect these quirks
	// we just don't register userData if we have localStorage
	if ( store.types.localStorage ) {
		return;
	}

	// append to html instead of body so we can do this from the head
	var div = document.createElement( "div" ),
		attrKey = "amplify";
	div.style.display = "none";
	document.getElementsByTagName( "head" )[ 0 ].appendChild( div );

	// we can't feature detect userData support
	// so just try and see if it fails
	// surprisingly, even just adding the behavior isn't enough for a failure
	// so we need to load the data as well
	try {
		div.addBehavior( "#default#userdata" );
		div.load( attrKey );
	} catch( e ) {
		div.parentNode.removeChild( div );
		return;
	}

	store.addType( "userData", function( key, value, options ) {
		div.load( attrKey );
		var attr, parsed, prevValue, i, remove,
			ret = value,
			now = (new Date()).getTime();

		if ( !key ) {
			ret = {};
			remove = [];
			i = 0;
			while ( attr = div.XMLDocument.documentElement.attributes[ i++ ] ) {
				parsed = JSON.parse( attr.value );
				if ( parsed.expires && parsed.expires <= now ) {
					remove.push( attr.name );
				} else {
					ret[ attr.name ] = parsed.data;
				}
			}
			while ( key = remove.pop() ) {
				div.removeAttribute( key );
			}
			div.save( attrKey );
			return ret;
		}

		// convert invalid characters to dashes
		// http://www.w3.org/TR/REC-xml/#NT-Name
		// simplified to assume the starting character is valid
		// also removed colon as it is invalid in HTML attribute names
		key = key.replace( /[^\-._0-9A-Za-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c-\u200d\u203f\u2040\u2070-\u218f]/g, "-" );
		// adjust invalid starting character to deal with our simplified sanitization
		key = key.replace( /^-/, "_-" );

		if ( value === undefined ) {
			attr = div.getAttribute( key );
			parsed = attr ? JSON.parse( attr ) : { expires: -1 };
			if ( parsed.expires && parsed.expires <= now ) {
				div.removeAttribute( key );
			} else {
				return parsed.data;
			}
		} else {
			if ( value === null ) {
				div.removeAttribute( key );
			} else {
				// we need to get the previous value in case we need to rollback
				prevValue = div.getAttribute( key );
				parsed = JSON.stringify({
					data: value,
					expires: (options.expires ? (now + options.expires) : null)
				});
				div.setAttribute( key, parsed );
			}
		}

		try {
			div.save( attrKey );
		// quota exceeded
		} catch ( error ) {
			// roll the value back to the previous value
			if ( prevValue === null ) {
				div.removeAttribute( key );
			} else {
				div.setAttribute( key, prevValue );
			}

			// expire old data and try again
			store.userData();
			try {
				div.setAttribute( key, parsed );
				div.save( attrKey );
			} catch ( error ) {
				// roll the value back to the previous value
				if ( prevValue === null ) {
					div.removeAttribute( key );
				} else {
					div.setAttribute( key, prevValue );
				}
				throw store.error();
			}
		}
		return ret;
	});
}() );

// in-memory storage
// fallback for all browsers to enable the API even if we can't persist data
(function() {
	var memory = {},
		timeout = {};

	function copy( obj ) {
		return obj === undefined ? undefined : JSON.parse( JSON.stringify( obj ) );
	}

	store.addType( "memory", function( key, value, options ) {
		if ( !key ) {
			return copy( memory );
		}

		if ( value === undefined ) {
			return copy( memory[ key ] );
		}

		if ( timeout[ key ] ) {
			clearTimeout( timeout[ key ] );
			delete timeout[ key ];
		}

		if ( value === null ) {
			delete memory[ key ];
			return null;
		}

		memory[ key ] = value;
		if ( options.expires ) {
			timeout[ key ] = setTimeout(function() {
				delete memory[ key ];
				delete timeout[ key ];
			}, options.expires );
		}

		return value;
	});
}() );

}( this.amplify = this.amplify || {} ) );

(function( amplify, undefined ) {

function noop() {}
function isFunction( obj ) {
	return ({}).toString.call( obj ) === "[object Function]";
}

function async( fn ) {
	var isAsync = false;
	setTimeout(function() {
		isAsync = true;
	}, 1 );
	return function() {
		var that = this,
			args = arguments;
		if ( isAsync ) {
			fn.apply( that, args );
		} else {
			setTimeout(function() {
				fn.apply( that, args );
			}, 1 );
		}
	};
}

amplify.request = function( resourceId, data, callback ) {
	// default to an empty hash just so we can handle a missing resourceId
	// in one place
	var settings = resourceId || {};

	if ( typeof settings === "string" ) {
		if ( isFunction( data ) ) {
			callback = data;
			data = {};
		}
		settings = {
			resourceId: resourceId,
			data: data || {},
			success: callback
		};
	}

	var request = { abort: noop },
		resource = amplify.request.resources[ settings.resourceId ],
		success = settings.success || noop,
		error = settings.error || noop;
	settings.success = async( function( data, status ) {
		status = status || "success";
		amplify.publish( "request.success", settings, data, status );
		amplify.publish( "request.complete", settings, data, status );
		success( data, status );
	});
	settings.error = async( function( data, status ) {
		status = status || "error";
		amplify.publish( "request.error", settings, data, status );
		amplify.publish( "request.complete", settings, data, status );
		error( data, status );
	});

	if ( !resource ) {
		if ( !settings.resourceId ) {
			throw "amplify.request: no resourceId provided";
		}
		throw "amplify.request: unknown resourceId: " + settings.resourceId;
	}

	if ( !amplify.publish( "request.before", settings ) ) {
		settings.error( null, "abort" );
		return;
	}

	amplify.request.resources[ settings.resourceId ]( settings, request );
	return request;
};

amplify.request.types = {};
amplify.request.resources = {};
amplify.request.define = function( resourceId, type, settings ) {
	if ( typeof type === "string" ) {
		if ( !( type in amplify.request.types ) ) {
			throw "amplify.request.define: unknown type: " + type;
		}

		settings.resourceId = resourceId;
		amplify.request.resources[ resourceId ] =
			amplify.request.types[ type ]( settings );
	} else {
		// no pre-processor or settings for one-off types (don't invoke)
		amplify.request.resources[ resourceId ] = type;
	}
};

}( amplify ) );

(function( amplify, $, undefined ) {

var xhrProps = [ "status", "statusText", "responseText", "responseXML", "readyState" ],
    rurlData = /\{([^\}]+)\}/g;

amplify.request.types.ajax = function( defnSettings ) {
	defnSettings = $.extend({
		type: "GET"
	}, defnSettings );

	return function( settings, request ) {
		var xhr, handleResponse,
			url = defnSettings.url,
			abort = request.abort,
			ajaxSettings = $.extend( true, {}, defnSettings, { data: settings.data } ),
			aborted = false,
			ampXHR = {
				readyState: 0,
				setRequestHeader: function( name, value ) {
					return xhr.setRequestHeader( name, value );
				},
				getAllResponseHeaders: function() {
					return xhr.getAllResponseHeaders();
				},
				getResponseHeader: function( key ) {
					return xhr.getResponseHeader( key );
				},
				overrideMimeType: function( type ) {
					return xhr.overrideMimeType( type );
				},
				abort: function() {
					aborted = true;
					try {
						xhr.abort();
					// IE 7 throws an error when trying to abort
					} catch( e ) {}
					handleResponse( null, "abort" );
				},
				success: function( data, status ) {
					settings.success( data, status );
				},
				error: function( data, status ) {
					settings.error( data, status );
				}
			};

		handleResponse = function( data, status ) {
			$.each( xhrProps, function( i, key ) {
				try {
					ampXHR[ key ] = xhr[ key ];
				} catch( e ) {}
			});
			// Playbook returns "HTTP/1.1 200 OK"
			// TODO: something also returns "OK", what?
			if ( /OK$/.test( ampXHR.statusText ) ) {
				ampXHR.statusText = "success";
			}
			if ( data === undefined ) {
				// TODO: add support for ajax errors with data
				data = null;
			}
			if ( aborted ) {
				status = "abort";
			}
			if ( /timeout|error|abort/.test( status ) ) {
				ampXHR.error( data, status );
			} else {
				ampXHR.success( data, status );
			}
			// avoid handling a response multiple times
			// this can happen if a request is aborted
			// TODO: figure out if this breaks polling or multi-part responses
			handleResponse = $.noop;
		};

		amplify.publish( "request.ajax.preprocess",
			defnSettings, settings, ajaxSettings, ampXHR );

		$.extend( ajaxSettings, {
			success: function( data, status ) {
				handleResponse( data, status );
			},
			error: function( _xhr, status ) {
				handleResponse( null, status );
			},
			beforeSend: function( _xhr, _ajaxSettings ) {
				xhr = _xhr;
				ajaxSettings = _ajaxSettings;
				var ret = defnSettings.beforeSend ?
					defnSettings.beforeSend.call( this, ampXHR, ajaxSettings ) : true;
				return ret && amplify.publish( "request.before.ajax",
					defnSettings, settings, ajaxSettings, ampXHR );
			}
		});
		$.ajax( ajaxSettings );

		request.abort = function() {
			ampXHR.abort();
			abort.call( this );
		};
	};
};

amplify.subscribe( "request.ajax.preprocess", function( defnSettings, settings, ajaxSettings ) {
	var mappedKeys = [],
		data = ajaxSettings.data;

	if ( typeof data === "string" ) {
		return;
	}

	data = $.extend( true, {}, defnSettings.data, data );

	ajaxSettings.url = ajaxSettings.url.replace( rurlData, function ( m, key ) {
		if ( key in data ) {
			mappedKeys.push( key );
			return data[ key ];
		}
	});

	// We delete the keys later so duplicates are still replaced
	$.each( mappedKeys, function ( i, key ) {
		delete data[ key ];
	});

	ajaxSettings.data = data;
});

amplify.subscribe( "request.ajax.preprocess", function( defnSettings, settings, ajaxSettings ) {
	var data = ajaxSettings.data,
		dataMap = defnSettings.dataMap;

	if ( !dataMap || typeof data === "string" ) {
		return;
	}

	if ( $.isFunction( dataMap ) ) {
		ajaxSettings.data = dataMap( data );
	} else {
		$.each( defnSettings.dataMap, function( orig, replace ) {
			if ( orig in data ) {
				data[ replace ] = data[ orig ];
				delete data[ orig ];
			}
		});
		ajaxSettings.data = data;
	}
});

var cache = amplify.request.cache = {
	_key: function( resourceId, url, data ) {
		function chunk() {
			return data.charCodeAt( i++ ) << 24 |
				data.charCodeAt( i++ ) << 16 |
				data.charCodeAt( i++ ) << 8 |
				data.charCodeAt( i++ ) << 0;
		}

		data = url + data;
		var length = data.length,
			i = 0,
			checksum = chunk();

		while ( i < length ) {
			checksum ^= chunk();
		}

		return "request-" + resourceId + "-" + checksum;
	},

	_default: (function() {
		var memoryStore = {};
		return function( resource, settings, ajaxSettings, ampXHR ) {
			// data is already converted to a string by the time we get here
			var cacheKey = cache._key( settings.resourceId,
					ajaxSettings.url, ajaxSettings.data ),
				duration = resource.cache;

			if ( cacheKey in memoryStore ) {
				ampXHR.success( memoryStore[ cacheKey ] );
				return false;
			}
			var success = ampXHR.success;
			ampXHR.success = function( data ) {
				memoryStore[ cacheKey ] = data;
				if ( typeof duration === "number" ) {
					setTimeout(function() {
						delete memoryStore[ cacheKey ];
					}, duration );
				}
				success.apply( this, arguments );
			};
		};
	}())
};

if ( amplify.store ) {
	$.each( amplify.store.types, function( type ) {
		cache[ type ] = function( resource, settings, ajaxSettings, ampXHR ) {
			var cacheKey = cache._key( settings.resourceId,
					ajaxSettings.url, ajaxSettings.data ),
				cached = amplify.store[ type ]( cacheKey );

			if ( cached ) {
				ajaxSettings.success( cached );
				return false;
			}
			var success = ampXHR.success;
			ampXHR.success = function( data ) {
				amplify.store[ type ]( cacheKey, data, { expires: resource.cache.expires } );
				success.apply( this, arguments );
			};
		};
	});
	cache.persist = cache[ amplify.store.type ];
}

amplify.subscribe( "request.before.ajax", function( resource ) {
	var cacheType = resource.cache;
	if ( cacheType ) {
		// normalize between objects and strings/booleans/numbers
		cacheType = cacheType.type || cacheType;
		return cache[ cacheType in cache ? cacheType : "_default" ]
			.apply( this, arguments );
	}
});

amplify.request.decoders = {
	// http://labs.omniti.com/labs/jsend
	jsend: function( data, status, ampXHR, success, error ) {
		if ( data.status === "success" ) {
			success( data.data );
		} else if ( data.status === "fail" ) {
			error( data.data, "fail" );
		} else if ( data.status === "error" ) {
			delete data.status;
			error( data, "error" );
		} else {
			error( null, "error" );
		}
	}
};

amplify.subscribe( "request.before.ajax", function( resource, settings, ajaxSettings, ampXHR ) {
	var _success = ampXHR.success,
		_error = ampXHR.error,
		decoder = $.isFunction( resource.decoder ) ?
			resource.decoder :
			resource.decoder in amplify.request.decoders ?
				amplify.request.decoders[ resource.decoder ] :
				amplify.request.decoders._default;

	if ( !decoder ) {
		return;
	}

	function success( data, status ) {
		_success( data, status );
	}
	function error( data, status ) {
		_error( data, status );
	}
	ampXHR.success = function( data, status ) {
		decoder( data, status, ampXHR, success, error );
	};
	ampXHR.error = function( data, status ) {
		decoder( data, status, ampXHR, success, error );
	};
});

}( amplify, jQuery ) );


text:
"""A demonstration of jobTree. Sorts the lines of a file into ascending order by doing a parallel merge sort.
"""
from optparse import OptionParser
import os
import random
import shutil
from sonLib.bioio import getTempFile
from jobTree.scriptTree.target import Target
from jobTree.scriptTree.stack import Stack
from jobTree.test.sort.lib import merge, sort, copySubRangeOfFile, getMidPoint

def setup(target, inputFile, N):
    """Sets up the sort.
    """
    tempOutputFile = getTempFile(rootDir=target.getGlobalTempDir())
    target.addChildTargetFn(down, (inputFile, 0, os.path.getsize(inputFile), N, tempOutputFile))
    target.setFollowOnFn(cleanup, (tempOutputFile, inputFile))

def down(target, inputFile, fileStart, fileEnd, N, outputFile):
    """Input is a file and a range into that file to sort and an output location in which
    to write the sorted file.
    If the range is larger than a threshold N the range is divided recursively and
    a follow on job is then created which merges back the results else
    the file is sorted and placed in the output.
    """
    if random.random() > 0.5:
        raise RuntimeError() #This error is a test error, it does not mean the tests have failed.
    length = fileEnd - fileStart
    target.logToMaster("Am running a down target with length: %i from input file: %s" % (length, inputFile))
    assert length >= 0
    if length > N:
        midPoint = getMidPoint(inputFile, fileStart, fileEnd)
        assert midPoint >= fileStart
        assert midPoint+1 < fileEnd
        #We will subdivide the file
        tempFile1 = getTempFile(rootDir=target.getGlobalTempDir())
        tempFile2 = getTempFile(rootDir=target.getGlobalTempDir())
        target.addChildTargetFn(down, (inputFile, fileStart, midPoint+1, N, tempFile1))
        target.addChildTargetFn(down, (inputFile, midPoint+1, fileEnd, N, tempFile2)) #Add one to avoid the newline
        target.setFollowOnTargetFn(up, (tempFile1, tempFile2, outputFile))
    else:
        #We can sort this bit of the file
        copySubRangeOfFile(inputFile, fileStart, fileEnd, outputFile)
        sort(outputFile)

def up(target, inputFile1, inputFile2, outputFile):
    """Merges the two files and places them in the output.
    """
    if random.random() > 0.5:
        raise RuntimeError() #This error is a test error, it does not mean the tests have failed.
    merge(inputFile1, inputFile2, outputFile)
    target.logToMaster("Am running an up target with input files: %s and %s" % (inputFile1, inputFile2))

def cleanup(tempOutputFile, outputFile):
    """Copies back the temporary file to input once we've successfully sorted the temporary file.
    """
    if random.random() > 0.5:
        raise RuntimeError() #This is a test error and not a failure of the tests
    shutil.copyfile(tempOutputFile, outputFile)

def main():
    parser = OptionParser()
    Stack.addJobTreeOptions(parser)

    parser.add_option("--fileToSort", dest="fileToSort",
                      help="The file you wish to sort")

    parser.add_option("--N", dest="N",
                      help="The threshold below which a serial sort function is used to sort file. All lines must of length less than or equal to N or program will fail",
                      default=10000)

    options, args = parser.parse_args()

    if options.fileToSort == None:
        raise RuntimeError("No file to sort given")

    if not os.path.exists(options.fileToSort):
        raise RuntimeError("File to sort does not exist: %s" % options.fileToSort)

    if int(options.N) <= 0:
        raise RuntimeError("Invalid value of N: %s" % options.N)

    if len(args) != 0:
        raise RuntimeError("Unrecognised input arguments: %s" % " ".join(args))

    #Now we are ready to run
    i = Stack(Target.makeTargetFn(setup, (options.fileToSort, int(options.N)))).startJobTree(options)

    #if i:
    #    raise RuntimeError("The jobtree contained %i failed jobs" % i)

if __name__ == '__main__':
    from jobTree.test.sort.scriptTreeTest_Sort import *
    main()


text:
A Floating TextField Menu For List of Input

![alt Could Not Load Image](https://github.com/vaghul/VKFoatingActionText/blob/master/FloatingTextMenu/Media/zcdfo.gif)

## Using this in your project

- Import the VKFloatingActionText to your project
- Use VKFloatingActionText.h

## Also Available in Pods
- pod 'VKFloatingActionText'

**Initialize the button and add it as a subview**
```
VKFloatingActionText *floatButton = [[VKFloatingActionButton alloc]initWithFrame:floatFrame normalImage:[UIImage imageNamed:@"plus"] andPressedImage:[UIImage imageNamed:@"cross"]];
```

**Add Images and TextField PlaceHolders for the Menu Action**
```
floatButton.menuButttonImages = @[@"fb-icon",@"twitter-icon",@"google-icon",@"linkedin-icon"];
floatButton.menuTextFieldDesc = @[@"Facebook",@"Twitter",@"Google Plus",@"Linked in"];
```
**Use Delegate to handle actions**
```
-(void)didClickOnMenuAtIndex:(NSInteger)index andValue:(NSString *)value
```
**Contributing**

I'd love to see your ideas for improving this Control! The best way to contribute is by submitting a pull request. I'll do my best to respond to your patch as soon as possible. You can also submit a [new Github issue](https://github.com/vaghul/VKFoatingActionText/issues/new) if you find bugs or have questions. :octocat:

##License
MIT License


text:
/**
 * @private
 */
Ext.define('Ext.fx.layout.card.Slide', {
    extend: 'Ext.fx.layout.card.Style',

    alias: 'fx.layout.card.slide',

    config: {
        inAnimation: {
            type: 'slide',
            easing: 'ease-out'
        },
        outAnimation: {
            type: 'slide',
            easing: 'ease-out',
            out: true
        }
    },

    updateReverse: function(reverse) {
        this.getInAnimation().setReverse(reverse);
        this.getOutAnimation().setReverse(reverse);
    }
});


text:
/**
 * Log4j 1.x compatibility layer.
 */
package org.apache.log4j.config;


text:
class Markup {
  forceReply (value = true) {
    this.force_reply = value
    return this
  }

  removeKeyboard (value = true) {
    this.remove_keyboard = value
    return this
  }

  selective (value = true) {
    this.selective = value
    return this
  }

  extra (options) {
    return {
      reply_markup: { ...this },
      ...options
    }
  }

  keyboard (buttons, options) {
    const keyboard = buildKeyboard(buttons, { columns: 1, ...options })
    if (keyboard && keyboard.length > 0) {
      this.keyboard = keyboard
    }
    return this
  }

  resize (value = true) {
    this.resize_keyboard = value
    return this
  }

  oneTime (value = true) {
    this.one_time_keyboard = value
    return this
  }

  inlineKeyboard (buttons, options) {
    const keyboard = buildKeyboard(buttons, { columns: buttons.length, ...options })
    if (keyboard && keyboard.length > 0) {
      this.inline_keyboard = keyboard
    }
    return this
  }

  button (text, hide) {
    return Markup.button(text, hide)
  }

  contactRequestButton (text, hide) {
    return Markup.contactRequestButton(text, hide)
  }

  locationRequestButton (text, hide) {
    return Markup.locationRequestButton(text, hide)
  }

  urlButton (text, url, hide) {
    return Markup.urlButton(text, url, hide)
  }

  callbackButton (text, data, hide) {
    return Markup.callbackButton(text, data, hide)
  }

  switchToChatButton (text, value, hide) {
    return Markup.switchToChatButton(text, value, hide)
  }

  switchToCurrentChatButton (text, value, hide) {
    return Markup.switchToCurrentChatButton(text, value, hide)
  }

  gameButton (text, hide) {
    return Markup.gameButton(text, hide)
  }

  payButton (text, hide) {
    return Markup.payButton(text, hide)
  }

  loginButton (text, url, opts, hide) {
    return Markup.loginButton(text, url, opts, hide)
  }

  static removeKeyboard (value) {
    return new Markup().removeKeyboard(value)
  }

  static forceReply (value) {
    return new Markup().forceReply(value)
  }

  static keyboard (buttons, options) {
    return new Markup().keyboard(buttons, options)
  }

  static inlineKeyboard (buttons, options) {
    return new Markup().inlineKeyboard(buttons, options)
  }

  static resize (value = true) {
    return new Markup().resize(value)
  }

  static selective (value = true) {
    return new Markup().selective(value)
  }

  static oneTime (value = true) {
    return new Markup().oneTime(value)
  }

  static button (text, hide = false) {
    return { text: text, hide: hide }
  }

  static contactRequestButton (text, hide = false) {
    return { text: text, request_contact: true, hide: hide }
  }

  static locationRequestButton (text, hide = false) {
    return { text: text, request_location: true, hide: hide }
  }

  static pollRequestButton (text, type, hide = false) {
    return { text: text, request_poll: { type }, hide: hide }
  }

  static urlButton (text, url, hide = false) {
    return { text: text, url: url, hide: hide }
  }

  static callbackButton (text, data, hide = false) {
    return { text: text, callback_data: data, hide: hide }
  }

  static switchToChatButton (text, value, hide = false) {
    return { text: text, switch_inline_query: value, hide: hide }
  }

  static switchToCurrentChatButton (text, value, hide = false) {
    return { text: text, switch_inline_query_current_chat: value, hide: hide }
  }

  static gameButton (text, hide = false) {
    return { text: text, callback_game: {}, hide: hide }
  }

  static payButton (text, hide = false) {
    return { text: text, pay: true, hide: hide }
  }

  static loginButton (text, url, opts = {}, hide = false) {
    return {
      text: text,
      login_url: { ...opts, url: url },
      hide: hide
    }
  }

  static formatHTML (text = '', entities = []) {
    const chars = [...text]
    const available = [...entities]
    const opened = []
    const result = []
    for (let offset = 0; offset < chars.length; offset++) {
      while (true) {
        const index = available.findIndex((entity) => entity.offset === offset)
        if (index === -1) {
          break
        }
        const entity = available[index]
        switch (entity.type) {
          case 'bold':
            result.push('')
            break
          case 'italic':
            result.push('')
            break
          case 'code':
            result.push('')
            break
          case 'pre':
            if (entity.language) {
              result.push(`<pre><code class="language-${entity.language}">`)
            } else {
              result.push('
')
            }
            break
          case 'strikethrough':
            result.push('<s>')
            break
          case 'underline':
            result.push('')
            break
          case 'text_mention':
            result.push(`<a href="tg://user?id=${entity.user.id}">`)
            break
          case 'text_link':
            result.push(`<a href="${entity.url}">`)
            break
        }
        opened.unshift(entity)
        available.splice(index, 1)
      }

      result.push(chars[offset])

      while (true) {
        const index = opened.findIndex((entity) => entity.offset + entity.length - 1 === offset)
        if (index === -1) {
          break
        }
        const entity = opened[index]
        switch (entity.type) {
          case 'bold':
            result.push('')
            break
          case 'italic':
            result.push('')
            break
          case 'code':
            result.push('')
            break
          case 'pre':
            if (entity.language) {
              result.push('
')
            } else {
              result.push('
')
            }
            break
          case 'strikethrough':
            result.push('</s>')
            break
          case 'underline':
            result.push('')
            break
          case 'text_mention':
          case 'text_link':
            result.push('')
            break
        }
        opened.splice(index, 1)
      }
    }
    return result.join('')
  }
}

function buildKeyboard (buttons, options) {
  const result = []
  if (!Array.isArray(buttons)) {
    return result
  }
  if (buttons.find(Array.isArray)) {
    return buttons.map(row => row.filter((button) => !button.hide))
  }
  const wrapFn = options.wrap
    ? options.wrap
    : (btn, index, currentRow) => currentRow.length >= options.columns
  let currentRow = []
  let index = 0
  for (const btn of buttons.filter((button) => !button.hide)) {
    if (wrapFn(btn, index, currentRow) && currentRow.length > 0) {
      result.push(currentRow)
      currentRow = []
    }
    currentRow.push(btn)
    index++
  }
  if (currentRow.length > 0) {
    result.push(currentRow)
  }
  return result
}

module.exports = Markup


text:
using System.Collections.Generic;
using System;
namespace DiskIO.AvailableMetrics
{
    [Serializable]
    public class AvailableMetrics
    {
        /// <summary>
        /// The availablemetrics.
        /// </summary>
        public List<Metric> availablemetrics;
    }
}


text:
My configuration file for the [mplayer](http://www.mplayerhq.hu) movie player.

**Note**: I no longer use mplayer. Instead, I use
[mpv](https://github.com/s3rvac/dotfiles/tree/master/mpv).

## Installation

* Copy `config` to `$HOME/.mplayer/`.


text:
/** @module uid */

/** @protected */
var uidCounter = 1;

/** @protected */
var uidObjects = {
    /** Root object. */
    root: {}
};

/** Obtain a unique ID. */
exports.getUid = function getUid() {
    return uidCounter++;
};

/** Associate an object with a unique ID. */
exports.setObjectForUid = function setObjectForUid(obj, uid) {
    uidObjects[uid] = obj;
};


text:
#!/usr/bin/env node

/**
 * qabot
 *
 * Command Line launcher
 *
 * (c) Troven Software 2009-2015. Apache Licensed.
 *
 */

var _ = require("underscore");

var pkg = require("../package.json");

var qabot = require("meta4qa"), cli = qabot.cli, Runtime = qabot.Runtime, files = qabot.helpers.files, vars = qabot.helpers.vars, assert = qabot.assert;
var debug = require("debug")("qabot");

assert(pkg && pkg.name && pkg.version, "Missing package name/version");

// customize the CLI options

cli.version("qabot v"+pkg.version);
cli.option("--reporter <reporter>", "Mocha reporter [spec|simple|tap|xunit|nyan|progress]");

// commands to run .feature files
cli.command('*').description("[.feature file]").action(function (featureFile) {
    cli.features = featureFile;
    if (arguments.length>2) {
        console.log("Only one .feature file allowed on the command line");
        process.exit(1);
    }
});

// initialize the configuration
debug("version %s (meta4qa v%s)", pkg.version, qabot.pkg.version);

var config = false;
try {
    config = qabot.configure(cli);
    if (!config) {
        cli.help();
        return;
    }
} catch(e) {
    console.log("ERROR: %s", e);
    process.exit(1);
}
config.configFile = "qa.json";
config.name = "qashield";

var qa = new Runtime(config);

// more intuitive configs
qa.config.paths = _.extend({}, pkg.directories, qa.config.paths);
qa.config.reporter = qa.config.reporter || "spec";

// built-in dialects
qa.dialect.learn( require("meta4qa-common"), "common" );
qa.dialect.learn( require("meta4qa-webapi"), "webapi" );
//qa.dialect.learn( require("meta4qa-blueprint"), "blueprint" );

// auto-install dialects
_.each(pkg.dependencies, function(ver, dep) {
    if (dep.indexOf("-dialect")>=0) {
        debug("%s install: %s @ %s",pkg.name, dep, ver);
        qa.dialect.learn( require(dep), dep);
    }
});
_.each(config.dialects, function(dep, name) {
    qa.dialect.learn( require(dep), _.isString(name)?name:dep );
});

vars.env(cli.envPrefix || "QA_", process.env, config);

// if no built-in commands gobbled us, run ./features
if (!qa.commands(cli)) {
    qa.execute();
}


text:
**Property Types** are the types of [Property](https://docs.unity3d.com/Manual/SL-Properties.html) than can be defined on the [Blackboard](Blackboard.md) for use in the **Graph**. These [Properties](https://docs.unity3d.com/Manual/SL-Properties.html) will be exposed to the [Inspector](https://docs.unity3d.com/Manual/UsingTheInspector.html) for [Materials](https://docs.unity3d.com/Manual/class-Material.html) that use the shader.

Each property has an associated **Data Type**. See [Data Types](Data-Types.md) for more information.

## Common Parameters

In addition to values specific to their [Data Types](Data-Types.md), all properties have the following parameters.

| Name        | Type  | Description |
|:------------ |:---|:---|
| Display Name | String | The display name of the property |
| Exposed | Boolean | If true this property will be exposed on the material inspector |
| Reference Name | String | The internal name used for the property inside the shader |

NOTE: If you overwrite the **Reference Name** parameter be aware of the following conditions:
- If your **Reference Name** does not begin with an underscore, one will be automatically appended.
- If your **Reference Name** contains any characters which are unsupported in HLSL they will be removed.
- You can revert to the default **Reference Name** by right clicking on it and selecting **Reset Reference**.

## Vector 1

Defines a **Vector 1** value.

| Data Type    | Modes |
|:-------------|:------|
| Vector 1 | Default, Slider, Integer |

#### Default

Displays a scalar input field in the material inspector.

| Field        | Type  | Description |
|:-------------|:------|:------------|
| Default | Vector 1 | The default value of the [Property](https://docs.unity3d.com/Manual/SL-Properties.html). |

#### Slider

Displays a slider field in the material inspector.

| Field        | Type  | Description |
|:-------------|:------|:------------|
| Default | Vector 1 |  The default value of the [Property](https://docs.unity3d.com/Manual/SL-Properties.html). |
| Min | Vector 1 | The minimum value of the slider. |
| Max | Vector 1 | The maximum value of the slider. |

#### Integer

Displays an integer input field in the material inspector.

| Field        | Type  | Description |
|:-------------|:------|:------------|
| Default | Integer | The default value of the [Property](https://docs.unity3d.com/Manual/SL-Properties.html). |

## Vector 2

Defines a **Vector 2** value. Displays a **Vector 4** input field in the material inspector, where the z and w components are not used.

| Data Type    | Modes |
|:-------------|:------|
| Vector 2 |  |

| Field        | Type  | Description |
|:-------------|:------|:------------|
| Default | Vector 2 | The default value of the [Property](https://docs.unity3d.com/Manual/SL-Properties.html). |

## Vector 3

Defines a **Vector 3** value. Displays a **Vector 4** input field in the material inspector, where the w component is not used.

| Data Type    | Modes |
|:-------------|:------|
| Vector 3 |  |

| Field        | Type  | Description |
|:-------------|:------|:------------|
| Default | Vector 3 | The default value of the [Property](https://docs.unity3d.com/Manual/SL-Properties.html). |

## Vector 4

Defines a **Vector 4** value. Displays a **Vector 4** input field in the material inspector.

| Data Type    | Modes |
|:-------------|:------|
| Vector 4 |  |

| Field        | Type  | Description |
|:-------------|:------|:------------|
| Default | Vector 4 | The default value of the [Property](https://docs.unity3d.com/Manual/SL-Properties.html). |

## Color

Defines a **Color** value.

| Data Type    | Modes |
|:-------------|:------|
| Color | Default, HDR |

#### Default

Displays an sRGB color field in the material inspector.

| Field        | Type  | Description |
|:-------------|:------|:------------|
| Default | Vector 4 | The default value of the [Property](https://docs.unity3d.com/Manual/SL-Properties.html). |

#### HDR

Displays an HDR color field in the material inspector.

| Field        | Type  | Description |
|:-------------|:------|:------------|
| Default | Vector 4 | The default value of the [Property](https://docs.unity3d.com/Manual/SL-Properties.html). |

## Texture 2D

Defines a [Texture 2D](https://docs.unity3d.com/Manual/class-TextureImporter.html) value. Displays an object field of type [Texture](https://docs.unity3d.com/Manual/class-TextureImporter.html) in the material inspector.

| Data Type    | Modes |
|:-------------|:------|
| Texture | White, Black, Grey, Bump |

| Field        | Type  | Description |
|:-------------|:------|:------------|
| Default | Texture | The default value of the [Property](https://docs.unity3d.com/Manual/SL-Properties.html). |

## Texture 3D

Defines a [Texture 3D](https://docs.unity3d.com/Manual/class-TextureImporter.html) value. Displays an object field of type [Texture 3D](https://docs.unity3d.com/Manual/class-TextureImporter.html) in the material inspector.

| Data Type    | Modes |
|:-------------|:------|
| Texture |  |

| Field        | Type  | Description |
|:-------------|:------|:------------|
| Default | Texture | The default value of the [Property](https://docs.unity3d.com/Manual/SL-Properties.html). |

## Texture 2D Array

Defines a [Texture 2D Array](https://docs.unity3d.com/Manual/class-TextureImporter.html) value. Displays an object field of type [Texture 2D Array](https://docs.unity3d.com/Manual/class-TextureImporter.html) in the material inspector.

| Data Type    | Modes |
|:-------------|:------|
| Texture |  |

| Field        | Type  | Description |
|:-------------|:------|:------------|
| Default | Texture | The default value of the [Property](https://docs.unity3d.com/Manual/SL-Properties.html). |

## Cubemap

Defines a [Cubemap](https://docs.unity3d.com/Manual/class-Cubemap.html) value. Displays an object field of type [Texture](https://docs.unity3d.com/Manual/class-TextureImporter.html) in the material inspector.

| Data Type    | Modes |
|:-------------|:------|
| Cubemap |  |

| Field        | Type  | Description |
|:-------------|:------|:------------|
| Default | Cubemap | The default value of the [Property](https://docs.unity3d.com/Manual/SL-Properties.html). |

## Boolean

Defines a **Boolean** value. Displays a **ToggleUI** field in the material inspector. Note that internally to the shader this value is a **Vector 1**. The **Boolean** type in [Shader Graph](Shader-Graph.md) is merely for usability.

| Data Type    | Modes |
|:-------------|:------|
| Boolean |  |

| Field        | Type  | Description |
|:-------------|:------|:------------|
| Default | Boolean | The default value of the [Property](https://docs.unity3d.com/Manual/SL-Properties.html). |


text:
package pr04_shoppingSpree;

public class Product {

    private String name;
    private int cost;

    public Product(String name, int cost) {
        this.setName(name);
        this.setCost(cost);
    }

    public String getName() {
        return name;
    }

    public int getCost() {
        return cost;
    }

    @Override
    public String toString() {
        return this.getName();
    }

    private void setName(String name) {
        if (name.length() < 1 || name.charAt(0) == ' ') {
            throw new IllegalArgumentException("Name cannot be empty");
        }
        this.name = name;
    }

    private void setCost(int cost) {
        if (cost < 0) {
            throw new IllegalArgumentException("Money cannot be negative");
        }
        this.cost = cost;
    }
}


text:
import java.util.ArrayList;
import java.util.List;

public class Main {
  public void test(Integer[] arr) {
    List<Integer> result = new ArrayList<>();
    result.add(1);
    for(Integer i : arr)
      result.<caret>add(i);
  }
}