text:
<?php
namespace GuzzleHttp\Tests;

use GuzzleHttp\Psr7;
use GuzzleHttp\Psr7\MultipartStream;

class MultipartStreamTest extends \PHPUnit_Framework_TestCase
{
    public function testCreatesDefaultBoundary()
    {
        $b = new MultipartStream();
        $this->assertNotEmpty($b->getBoundary());
    }

    public function testCanProvideBoundary()
    {
        $b = new MultipartStream([], 'foo');
        $this->assertEquals('foo', $b->getBoundary());
    }

    public function testIsNotWritable()
    {
        $b = new MultipartStream();
        $this->assertFalse($b->isWritable());
    }

    public function testCanCreateEmptyStream()
    {
        $b = new MultipartStream();
        $boundary = $b->getBoundary();
        $this->assertSame("--{$boundary}--\r\n", $b->getContents());
        $this->assertSame(strlen($boundary) + 6, $b->getSize());
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testValidatesFilesArrayElement()
    {
        new MultipartStream([['foo' => 'bar']]);
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testEnsuresFileHasName()
    {
        new MultipartStream([['contents' => 'bar']]);
    }

    public function testSerializesFields()
    {
        $b = new MultipartStream([
            [
                'name' => 'foo',
                'contents' => 'bar'
            ],
            [
                'name' => 'baz',
                'contents' => 'bam'
            ]
        ], 'boundary');
        $this->assertEquals(
            "--boundary\r\nContent-Disposition: form-data; name=\"foo\"\r\nContent-Length: 3\r\n\r\n"
            . "bar\r\n--boundary\r\nContent-Disposition: form-data; name=\"baz\"\r\nContent-Length: 3"
            . "\r\n\r\nbam\r\n--boundary--\r\n", (string)$b);
    }

    public function testSerializesFiles()
    {
        $f1 = Psr7\FnStream::decorate(Psr7\stream_for('foo'), [
            'getMetadata' => function () {
                return '/foo/bar.txt';
            }
        ]);

        $f2 = Psr7\FnStream::decorate(Psr7\stream_for('baz'), [
            'getMetadata' => function () {
                return '/foo/baz.jpg';
            }
        ]);

        $f3 = Psr7\FnStream::decorate(Psr7\stream_for('bar'), [
            'getMetadata' => function () {
                return '/foo/bar.gif';
            }
        ]);

        $b = new MultipartStream([
            [
                'name' => 'foo',
                'contents' => $f1
            ],
            [
                'name' => 'qux',
                'contents' => $f2
            ],
            [
                'name' => 'qux',
                'contents' => $f3
            ],
        ], 'boundary');

        $expected = <<<EOT
--boundary
Content-Disposition: form-data; name="foo"; filename="bar.txt"
Content-Length: 3
Content-Type: text/plain

foo
--boundary
Content-Disposition: form-data; name="qux"; filename="baz.jpg"
Content-Length: 3
Content-Type: image/jpeg

baz
--boundary
Content-Disposition: form-data; name="qux"; filename="bar.gif"
Content-Length: 3
Content-Type: image/gif

bar
--boundary--

EOT;

        $this->assertEquals($expected, str_replace("\r", '', $b));
    }

    public function testSerializesFilesWithCustomHeaders()
    {
        $f1 = Psr7\FnStream::decorate(Psr7\stream_for('foo'), [
            'getMetadata' => function () {
                return '/foo/bar.txt';
            }
        ]);

        $b = new MultipartStream([
            [
                'name' => 'foo',
                'contents' => $f1,
                'headers' => [
                    'x-foo' => 'bar',
                    'content-disposition' => 'custom'
                ]
            ]
        ], 'boundary');

        $expected = <<<EOT
--boundary
x-foo: bar
content-disposition: custom
Content-Length: 3
Content-Type: text/plain

foo
--boundary--

EOT;

        $this->assertEquals($expected, str_replace("\r", '', $b));
    }

    public function testSerializesFilesWithCustomHeadersAndMultipleValues()
    {
        $f1 = Psr7\FnStream::decorate(Psr7\stream_for('foo'), [
            'getMetadata' => function () {
                return '/foo/bar.txt';
            }
        ]);

        $f2 = Psr7\FnStream::decorate(Psr7\stream_for('baz'), [
            'getMetadata' => function () {
                return '/foo/baz.jpg';
            }
        ]);

        $b = new MultipartStream([
            [
                'name' => 'foo',
                'contents' => $f1,
                'headers' => [
                    'x-foo' => 'bar',
                    'content-disposition' => 'custom'
                ]
            ],
            [
                'name' => 'foo',
                'contents' => $f2,
                'headers' => ['cOntenT-Type' => 'custom'],
            ]
        ], 'boundary');

        $expected = <<<EOT
--boundary
x-foo: bar
content-disposition: custom
Content-Length: 3
Content-Type: text/plain

foo
--boundary
cOntenT-Type: custom
Content-Disposition: form-data; name="foo"; filename="baz.jpg"
Content-Length: 3

baz
--boundary--

EOT;

        $this->assertEquals($expected, str_replace("\r", '', $b));
    }
}

redpajama_set_name: RedPajamaGithub


text:
/*jslint node: true */
/* global it, before, after, describe, xit, xdescribe */
'use strict';

var logger = require('../lib/Logger'),
    http = require('http'),
    config = require('config'),
    sinon = require('sinon'),
    should = require('should'),
    httpMocks = require('node-mocks-http'),
    ServerError = require('../lib/Error').ServerError,
    errorMiddleware = require('../middleware/HttpError.js').httpError;

if (!logger.configured) {
    logger.configure(config.logging.winston);
}

describe("HttpError Middleware Tests", function() {
    it("Should create an valid 404 http error", function(done) {
        var next = sinon.spy();

        errorMiddleware(new ServerError(404, "Log not found"), httpMocks.createRequest(), httpMocks.createResponse(), next);

        should.equal(next.called, true)

        done();
    });

    it("Should create an valid 500 http error", function(done) {
        var next = sinon.spy();

        errorMiddleware(new ServerError(500, "Internal Server Error"), httpMocks.createRequest(), httpMocks.createResponse(), next);

        should.equal(next.called, true)

        done();
    });
});


text:
void Circuit_BrisRead_SHA_Test_Impl();
void Circuit_BrisRead_AES_Test_Impl();
void Circuit_Gen_Adder32_Test_Impl();
void Circuit_BrisRead_Adder32_Test_Impl();
//void DagCircuit_BrisRead_Adder32_Test_Impl();
//void DagCircuit_RandomReduce_Test_Impl();


text:
/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 */
'use strict';

var React = require('react-native');

var SearchBar = require('react-native-search-bar');

var SearchBarExample = React.createClass({
  render: function() {
    return (
      <SearchBar
        placeholder='Search'
        textFieldBackgroundColor='blue'
        />
    );
  }
});

React.AppRegistry.registerComponent('SearchBarExample', () => SearchBarExample);


text:
[![Version](http://cocoapod-badges.herokuapp.com/v/FSHeadsUpDisplay/badge.png)](http://cocoadocs.org/docsets/FSHeadsUpDisplay)
[![Platform](http://cocoapod-badges.herokuapp.com/p/FSHeadsUpDisplay/badge.png)](http://cocoadocs.org/docsets/FSHeadsUpDisplay)

## Usage

To run the example project; clone the repo, and run `pod install` from the Project directory first.

## Requirements

## Installation

FSHeadsUpDisplay is available through [CocoaPods](http://cocoapods.org), to install
it simply add the following line to your Podfile:

    pod "FSHeadsUpDisplay"

## Author

Bennett Smith, bennett@focalshift.com

## License

FSHeadsUpDisplay is available under the MIT license. See the LICENSE file for more info.


text:
[![Build Status](https://travis-ci.org/jmwri/pubg-php.svg?branch=master)](https://travis-ci.org/jmwri/pubg-php)
[![Total Downloads](https://poser.pugx.org/jmwri/pubg-php/d/total.svg)](https://packagist.org/packages/jmwri/pubg-php)
[![Latest Stable Version](https://poser.pugx.org/jmwri/pubg-php/v/stable.svg)](https://packagist.org/packages/jmwri/pubg-php)
[![Latest Unstable Version](https://poser.pugx.org/jmwri/pubg-php/v/unstable.svg)](https://packagist.org/packages/jmwri/pubg-php)
[![License](https://poser.pugx.org/jmwri/pubg-php/license.svg)](https://packagist.org/packages/jmwri/pubg-php)
[![Code Climate](https://codeclimate.com/github/jmwri/pubg-php/badges/gpa.svg)](https://codeclimate.com/github/jmwri/pubg-php)
[![Test Coverage](https://codeclimate.com/github/jmwri/pubg-php/badges/coverage.svg)](https://codeclimate.com/github/jmwri/pubg-php/coverage)
[![Issue Count](https://codeclimate.com/github/jmwri/pubg-php/badges/issue_count.svg)](https://codeclimate.com/github/jmwri/pubg-php)

**https://github.com/jmwri/pubg-php**

This package is a wrapper around [PUBG Tracker's API](https://pubgtracker.com/site-api).

Please obide by the rate limits specified by PUBG Tracker.

# Getting started
## Installation
    composer require jmwri/pubg-php

## API key
You will need to get an API key from [PUBG Tracker](https://pubgtracker.com/site-api).

# Usage
## Get account
```php
$pubg = new \JmWri\Pubg\Pubg('my-api-key');
$pubg->getAccount(1234567890); // \JmWri\Pubg\Output\Account
```

## Get player stats
```php
$pubg = new \JmWri\Pubg\Pubg('my-api-key');
$report = $pubg->getPlayerStats('test_nickname'); // \JmWri\Pubg\Output\Stats\Report
$report->getStats('eu', 'solo'); // \JmWri\Pubg\Output\Stats\Stat[]
$report->getStats('eu', ['solo', 'duo']); // \JmWri\Pubg\Output\Stats\Stat[]
$report->getStats(['eu', 'na'], 'duo'); // \JmWri\Pubg\Output\Stats\Stat[]
$report->getMatchHistory(); // \JmWri\Pubg\Output\Stats\MatchHistory[]
```

# Support
https://github.com/jmwri/pubg-php/issues


text:
fvu.js
======

Multivariable data visualisation with d3.js and mongodb.

:sweat: trying to work myself into MEAN :sweat:

Basic graph, server and database set-up is currently working.

Also a first introduction to github.


text:
<?php

// Error 404
$lang['error_404_title'] 			= 'Página no encontrada';
$lang['error_404_message'] 		= 'No pudimos encontrar la página que estabas buscando. Ir a la página principal.';

// Database
$lang['error_invalid_db_group'] 	= 'El grupo de configuración de la base de datos es incorrecto "%s".';

?>


text:
use std::path::PathBuf;

use util::{self, CargoResult, internal, ChainError, ProcessBuilder};

pub struct Rustc {
    pub path: PathBuf,
    pub verbose_version: String,
    pub host: String,
    /// Backwards compatibility: does this compiler support `--cap-lints` flag?
    pub cap_lints: bool,
}

impl Rustc {
    /// Run the compiler at `path` to learn various pieces of information about
    /// it.
    ///
    /// If successful this function returns a description of the compiler along
    /// with a list of its capabilities.
    pub fn new(path: PathBuf) -> CargoResult<Rustc> {
        let mut cmd = util::process(&path);
        cmd.arg("-vV");

        let mut first = cmd.clone();
        first.arg("--cap-lints").arg("allow");

        let (cap_lints, output) = match first.exec_with_output() {
            Ok(output) => (true, output),
            Err(..) => (false, cmd.exec_with_output()?),
        };

        let verbose_version = String::from_utf8(output.stdout).map_err(|_| {
            internal("rustc -v didn't return utf8 output")
        })?;

        let host = {
            let triple = verbose_version.lines().find(|l| {
                l.starts_with("host: ")
            }).map(|l| &l[6..]);
            let triple = triple.chain_error(|| {
                internal("rustc -v didn't have a line for `host:`")
            })?;
            triple.to_string()
        };

        Ok(Rustc {
            path: path,
            verbose_version: verbose_version,
            host: host,
            cap_lints: cap_lints,
        })
    }

    pub fn process(&self) -> ProcessBuilder {
        util::process(&self.path)
    }
}


text:
from app.settings import settings
from common.test_base import TestBase

class TestSettings(TestBase):

    def test_initial_settings_value(self):
        """ Settings - initial version value is not None """
        self.assertIsNotNone(settings['version'])

    def test_store_settings_value(self):
        """ Settings - stored version value to settings is returned back """
        settings['version'] = '1'
        self.assertEqual('1', settings['version'])

    def test_read_not_existing_settings_value(self):
        """ Settings - reading not existing value fails """
        def read_not_existing_value():
            return settings['not_existing_key']
        self.assertRaises(KeyError, read_not_existing_value)

    def test_separate_namespace_values(self):
        """ Settings - values in different namespaces are not affecting each other """

        from google.appengine.api import namespace_manager

        namespace_manager.set_namespace('namespace_1')
        settings['version'] = '1'

        namespace_manager.set_namespace('namespace_2')
        settings['version'] = '2'

        namespace_manager.set_namespace('namespace_1')
        self.assertEqual('1', settings['version'])


text:
<?php

namespace Neoxygen\Neogen\Parser;

interface ParserInterface
{
    public function parse($definition);

    public function getName();
}


text:
Prerequisites:
 - go1.8+ toolchain (can be downloaded from [here](https://golang.org/dl/))
 - Android NDK (tested with r12b) (can be downloaded from [here](https://developer.android.com/ndk/downloads/index.html))
 - Android Serial Cable or [Suzy-Q](https://chromium.googlesource.com/chromiumos/platform/ec/+/master/docs/case_closed_debugging.md) device to capture console output is preferable but optional. syzkaller can work with normal USB cable as well, but that can be somewhat unreliable and turn lots of crashes into "lost connection to test machine" crashes with no additional info.

From `syzkaller` checkout:
 - Build `syz-manager` for host:
```
go build -o bin/syz-manager ./syz-manager
```

 - Build `syz-fuzzer` and `syz-execprog` for arm64:
```
GOARCH=arm64 go build -o bin/syz-fuzzer ./syz-fuzzer
GOARCH=arm64 go build -o bin/syz-execprog ./tools/syz-execprog
```

 - Build `syz-executor` for arm64:
```
/android-ndk-r12b/toolchains/aarch64-linux-android-4.9/prebuilt/linux-x86_64/bin/aarch64-linux-android-g++ \
  -I/android-ndk-r12b/sources/cxx-stl/llvm-libc++/libcxx/include \
  --sysroot=/android-ndk-r12b/platforms/android-22/arch-arm64 \
  executor/executor.cc -O1 -g -Wall -static -o bin/syz-executor
```

 - Create config with `"type": "adb"` and specify adb devices to use. For example:
```
{
	"http": "localhost:50000",
	"workdir": "/gopath/src/github.com/google/syzkaller/workdir",
	"syzkaller": "/gopath/src/github.com/google/syzkaller",
	"vmlinux": "-",
	"sandbox": "none",
	"procs": 8,
	"type": "adb",
	"vm": {
		"devices": ["ABCD000010"]
	}
}
```

 - Start `syz-manager -config adb.cfg` as usual.


text:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.Analytics;
using System.Collections.Generic;
using UnityEngine.Advertisements;

public class SendScript : MonoBehaviour
{

    public Canvas inputCanvas;
    public Text textName;
    public Text textScore;
	private bool sendScoreEnabled = true;
    // Use this for initialization
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {

    }

    public void PostScore()
    {
		if (sendScoreEnabled) {
			sendScoreEnabled = false;
			Advertisement.Initialize ("1029906", false);

			//Example how to use Analytics
			//Analytics.Transaction("12345abcde", 0.99m, "USD", null, null);
			//Gender gender = Gender.Female;
			//Analytics.SetUserGender(gender);
			//int birthYear = 2014;
			//Analytics.SetUserBirthYear(birthYear);

			StartCoroutine (ShowAdWhenReady ());

			int totalPoints = int.Parse (textScore.text);
			string name = textName.text;
			Analytics.CustomEvent ("gameOver", new Dictionary<string, object> {
				{ "totalPoints", totalPoints },
				{ "name", name }
			});
			inputCanvas.gameObject.GetComponent<HSController> ().callPostScores (textName.text, int.Parse (textScore.text));
		}
    }
    IEnumerator ShowAdWhenReady()
    {
		while (!Advertisement.IsReady())
            yield return null;

		Advertisement.Show();
    }
}


text:
require "spec_helper"

describe Capistrano::Systemd::MultiService::UserService do
  let(:systemd_dir) { "/home/user/.config/systemd/user" }
  let(:systemctl_command) { [:systemctl, "--user"] }

  include_context "setup"

  before { env.set :user, "user" }

  context do
    include_context "with config/systemd/example1.service.erb"

    describe "#setup" do
      it "should upload and install unit file" do
        buf = stub
        File.expects(:read).with("config/systemd/example1.service.erb").returns("dummy")
        StringIO.expects(:new).with("dummy").returns(buf)

        backend.expects(:upload!).with(buf, "/home/user/.config/systemd/user/foo_example1.service")

        subject.setup
      end
    end

    describe "#remove" do
      it "should uninstall unit file" do
        backend.expects(:execute).with(:rm, '-f', '--', ["/home/user/.config/systemd/user/foo_example1.service"])

        subject.remove
      end
    end
  end

  context do
    include_context "with config/systemd/example2.service.erb, example2@.service.erb"

    describe "#setup" do
      it "should upload and install unit file" do
        buf1 = stub
        File.expects(:read).with("config/systemd/example2.service.erb").returns("dummy1")
        StringIO.expects(:new).with("dummy1").returns(buf1)

        backend.expects(:upload!).with(buf1, "/home/user/.config/systemd/user/foo_example2.service")

        buf2 = stub
        File.expects(:read).with("config/systemd/example2@.service.erb").returns("dummy2")
        StringIO.expects(:new).with("dummy2").returns(buf2)

        backend.expects(:upload!).with(buf2, "/home/user/.config/systemd/user/foo_example2@.service")

        subject.setup
      end
    end

    describe "#remove" do
      it "should uninstall unit file" do
        backend.expects(:execute).with(:rm, '-f', '--', ["/home/user/.config/systemd/user/foo_example2.service", "/home/user/.config/systemd/user/foo_example2@.service"])

        subject.remove
      end
    end
  end

  context do
    include_context "with config/systemd/example3@.service.erb"

    describe "#setup" do
      it "should upload and install unit file" do
        buf2 = stub
        File.expects(:read).with("config/systemd/example3@.service.erb").returns("dummy2")
        StringIO.expects(:new).with("dummy2").returns(buf2)

        backend.expects(:upload!).with(buf2, "#{systemd_dir}/foo_example3@.service")

        subject.setup
      end
    end

    describe "#remove" do
      it "should uninstall unit file" do
        backend.expects(:execute).with(:rm, '-f', '--', ["#{systemd_dir}/foo_example3@.service"])

        subject.remove
      end
    end
  end

  include_examples "without config file" do
    let(:systemctl_command) { [:systemctl, "--user"] }
  end
end


text:
* Added useful info in CHANGELOG.md

## 0.2.2
* Bug fix for issue where state was lost, and the error "this.sunTimes is not a function" was being thrown

## 0.2.1
* Revert previous change, incorrect implementation caused errors

## 0.2.0
* Attempted bug fix for issue where state was lost, and the error "this.sunTimes is not a function" was being thrown

## 0.1.1
* Added settings to allow checking interval to be set in settings

## 0.1.0 - First Release
* Added feature to change theme automatically based on time
* Added preferences and settings


text:
package mil.nga.giat.geowave.adapter.vector.query;

import java.io.Closeable;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import mil.nga.giat.geowave.adapter.vector.FeatureDataAdapter;
import mil.nga.giat.geowave.adapter.vector.query.cql.FilterToCQLTool;
import mil.nga.giat.geowave.adapter.vector.wms.DistributableRenderer;
import mil.nga.giat.geowave.core.index.ByteArrayId;
import mil.nga.giat.geowave.core.index.ByteArrayUtils;
import mil.nga.giat.geowave.core.index.HierarchicalNumericIndexStrategy;
import mil.nga.giat.geowave.core.index.NumericIndexStrategy;
import mil.nga.giat.geowave.core.index.PersistenceUtils;
import mil.nga.giat.geowave.core.index.StringUtils;
import mil.nga.giat.geowave.core.index.HierarchicalNumericIndexStrategy.SubStrategy;
import mil.nga.giat.geowave.core.index.sfc.data.MultiDimensionalNumericData;
import mil.nga.giat.geowave.core.store.CloseableIterator;
import mil.nga.giat.geowave.core.store.adapter.AdapterStore;
import mil.nga.giat.geowave.core.store.filter.DistributableFilterList;
import mil.nga.giat.geowave.core.store.filter.DistributableQueryFilter;
import mil.nga.giat.geowave.core.store.filter.QueryFilter;
import mil.nga.giat.geowave.core.store.index.Index;
import mil.nga.giat.geowave.datastore.accumulo.AccumuloOperations;
import mil.nga.giat.geowave.datastore.accumulo.query.AccumuloConstraintsQuery;
import mil.nga.giat.geowave.datastore.accumulo.util.CloseableIteratorWrapper;

import org.apache.accumulo.core.client.BatchScanner;
import org.apache.accumulo.core.client.IteratorSetting;
import org.apache.accumulo.core.client.ScannerBase;
import org.apache.accumulo.core.client.TableNotFoundException;
import org.apache.accumulo.core.data.Range;
import org.apache.hadoop.io.Text;
import org.apache.log4j.Logger;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.filter.Filter;

/**
 * This class extends the capabilities of a simple constraints query to perform
 * distributed rendering within tablet servers. It is able to serialize a
 * distributed renderer and return a set of features that contain the rendered
 * images ready for composition. It also supports CQL filters.
 *
 */
public class DistributedRenderQuery extends
		AccumuloConstraintsQuery
{
	private final static Logger LOGGER = Logger.getLogger(DistributedRenderQuery.class);
	private final DistributableRenderer renderer;
	private final Filter cqlFilter;
	private final FeatureDataAdapter dataAdapter;

	public DistributedRenderQuery(
			final Index index,
			final Filter cqlFilter,
			final FeatureDataAdapter dataAdapter,
			final DistributableRenderer renderer,
			final String... authorizations ) {
		super(
				(List<ByteArrayId>) null, // adaptor ids
				index,
				(MultiDimensionalNumericData) null,
				(List<QueryFilter>) null,
				authorizations);
		this.renderer = renderer;
		this.cqlFilter = cqlFilter;
		this.dataAdapter = dataAdapter;
	}

	public DistributedRenderQuery(
			final List<ByteArrayId> adapterIds,
			final Index index,
			final Filter cqlFilter,
			final FeatureDataAdapter dataAdapter,
			final DistributableRenderer renderer,
			final String... authorizations ) {
		super(
				adapterIds,
				index,
				(MultiDimensionalNumericData) null,
				(List<QueryFilter>) null,
				authorizations);
		this.renderer = renderer;
		this.cqlFilter = cqlFilter;
		this.dataAdapter = dataAdapter;
	}

	public DistributedRenderQuery(
			final Index index,
			final MultiDimensionalNumericData constraints,
			final List<QueryFilter> queryFilters,
			final Filter cqlFilter,
			final FeatureDataAdapter dataAdapter,
			final DistributableRenderer renderer,
			final String... authorizations ) {
		super(
				(List<ByteArrayId>) null, // adaptor ids
				index,
				constraints,
				queryFilters,
				authorizations);
		this.renderer = renderer;
		this.cqlFilter = cqlFilter;
		this.dataAdapter = dataAdapter;
	}

	public DistributedRenderQuery(
			final List<ByteArrayId> adapterIds,
			final Index index,
			final MultiDimensionalNumericData constraints,
			final List<QueryFilter> queryFilters,
			final Filter cqlFilter,
			final FeatureDataAdapter dataAdapter,
			final DistributableRenderer renderer,
			final String... authorizations ) {
		super(
				adapterIds,
				index,
				constraints,
				queryFilters,
				authorizations);
		this.renderer = renderer;
		this.cqlFilter = cqlFilter;
		this.dataAdapter = dataAdapter;
	}

	public List<CloseableIterator<SimpleFeature>> queryDistributedRender(
			final AccumuloOperations accumuloOperations,
			final AdapterStore adapterStore,
			final boolean separateSubStrategies ) {
		final Map<NumericIndexStrategy, ScannerBase> scanners = getScanners(
				accumuloOperations,
				separateSubStrategies);
		final List<CloseableIterator<SimpleFeature>> iterators = new ArrayList<CloseableIterator<SimpleFeature>>();
		for (final Entry<NumericIndexStrategy, ScannerBase> entry : scanners.entrySet()) {
			final ScannerBase scanner = entry.getValue();
			addScanIteratorSettings(
					scanner,
					entry.getKey());
			iterators.add(new CloseableIteratorWrapper<SimpleFeature>(
					new Closeable() {

						@Override
						public void close()
								throws IOException {
							scanner.close();
						}
					},
					new RenderIteratorWrapper(
							scanner.iterator())));
		}
		return iterators;
	}

	protected Map<NumericIndexStrategy, ScannerBase> getScanners(
			final AccumuloOperations accumuloOperations,
			final boolean separateSubStrategies ) {
		final String tableName = StringUtils.stringFromBinary(index.getId().getBytes());
		final Map<NumericIndexStrategy, ScannerBase> resultScanners = new HashMap<NumericIndexStrategy, ScannerBase>();
		final NumericIndexStrategy indexStrategy = index.getIndexStrategy();
		if ((indexStrategy instanceof HierarchicalNumericIndexStrategy) && separateSubStrategies) {
			final SubStrategy[] subStrategies = ((HierarchicalNumericIndexStrategy) indexStrategy).getSubStrategies();
			for (final SubStrategy subStrategy : subStrategies) {
				resultScanners.put(
						subStrategy.getIndexStrategy(),
						getScanner(
								accumuloOperations,
								subStrategy.getPrefix(),
								tableName));
			}
		}
		else {
			resultScanners.put(
					indexStrategy,
					getScanner(
							accumuloOperations,
							null,
							tableName));
		}
		return resultScanners;
	}

	protected ScannerBase getScanner(
			final AccumuloOperations accumuloOperations,
			final byte[] prefix,
			final String tableName ) {
		BatchScanner scanner;
		try {
			scanner = accumuloOperations.createBatchScanner(
					tableName,
					this.getAdditionalAuthorizations());
			if ((prefix != null) && (prefix.length > 0)) {
				final Range r = Range.prefix(new Text(
						prefix));
				final List<Range> ranges = new ArrayList<Range>();
				ranges.add(r);
				scanner.setRanges(ranges);
			}
			else {
				final List<Range> ranges = new ArrayList<Range>();
				ranges.add(new Range());
				scanner.setRanges(ranges);
			}
		}
		catch (final TableNotFoundException e) {
			LOGGER.warn(
					"Unable to query table '" + tableName + "'.  Table does not exist.",
					e);
			return null;
		}
		if ((adapterIds != null) && !adapterIds.isEmpty()) {
			for (final ByteArrayId adapterId : adapterIds) {
				scanner.fetchColumnFamily(new Text(
						adapterId.getBytes()));
			}
		}
		return scanner;
	}

	protected void addScanIteratorSettings(
			final ScannerBase scanner,
			final NumericIndexStrategy indexStrategy ) {
		if ((cqlFilter != null) && (dataAdapter != null)) {
			final IteratorSetting iteratorSettings = new IteratorSetting(
					CqlQueryFilterIterator.CQL_QUERY_ITERATOR_PRIORITY,
					CqlQueryFilterIterator.CQL_QUERY_ITERATOR_NAME,
					CqlQueryRenderIterator.class);
			iteratorSettings.addOption(
					CqlQueryFilterIterator.CQL_FILTER,
					FilterToCQLTool.toCQL(cqlFilter));
			iteratorSettings.addOption(
					CqlQueryFilterIterator.DATA_ADAPTER,
					ByteArrayUtils.byteArrayToString(PersistenceUtils.toBinary(dataAdapter)));
			iteratorSettings.addOption(
					CqlQueryFilterIterator.MODEL,
					ByteArrayUtils.byteArrayToString(PersistenceUtils.toBinary(index.getIndexModel())));
			iteratorSettings.addOption(
					CqlQueryRenderIterator.INDEX_STRATEGY,
					ByteArrayUtils.byteArrayToString(PersistenceUtils.toBinary(indexStrategy)));

			final DistributableQueryFilter filterList = new DistributableFilterList(
					distributableFilters);
			iteratorSettings.addOption(
					CqlQueryFilterIterator.GEOWAVE_FILTER,
					ByteArrayUtils.byteArrayToString(PersistenceUtils.toBinary(filterList)));
			iteratorSettings.addOption(
					CqlQueryRenderIterator.RENDERER,
					ByteArrayUtils.byteArrayToString(PersistenceUtils.toBinary(renderer)));
			scanner.addScanIterator(iteratorSettings);
		}
		else {
			super.addScanIteratorSettings(scanner);
		}
	}

}


text:
package org.codelikethewind.dataoperation;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

import org.apache.commons.io.IOUtils;
import org.jbpm.kie.services.impl.KModuleDeploymentUnit;
import org.jbpm.services.api.DeploymentService;
import org.kie.api.KieServices;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.builder.ReleaseId;
import org.kie.scanner.MavenRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;

@Configuration
@ComponentScan
@EnableAutoConfiguration(exclude=HibernateJpaAutoConfiguration.class)
@ImportResource(value= {
		"classpath:config/jee-tx-context.xml",
		"classpath:config/jpa-context.xml",
		"classpath:config/jbpm-context.xml"})
public class Application {

	private static final Logger LOG = LoggerFactory.getLogger(Application.class);

	private static final int THREAD_POOL_SIZE = Integer.parseInt(System.getProperty("thread.pool.size", "10"));
	public static final String KJAR = "org.kie.example:project1:1.0.1-SNAPSHOT";

	public static void main(String[] args) {

		System.setProperty("org.kie.txm.factory.class", "org.kie.spring.persistence.KieSpringTransactionManagerFactory");

		ConfigurableApplicationContext ctx = SpringApplication.run(Application.class, args);
        DeploymentService deploymentService = (DeploymentService) ctx.getBean("deploymentService");

        try {
    		deployKjar(deploymentService, KJAR);

    		List<DataOperationSpec> specList = DataRetriever.findAllActiveProcesses();

    		performDataOperation(specList);
    	} catch (Throwable e) {
    		LOG.error("Error while executing the data operation ...", e);
    	} finally {
    		ctx.close();
    	}
    }

	private static void performDataOperation(List<DataOperationSpec> specList) {
		ExecutorService executor = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
		LOG.info("\n\t>>>> Starting the data operation ... THREAD Pool Size: {}", THREAD_POOL_SIZE);

		Long start = System.currentTimeMillis();
		try {
			for(DataOperationSpec spec: specList) {
				executor.execute(new DataOperationTask(spec));
			}
			executor.shutdown();
			boolean executorShutdownTimedOut = executor.awaitTermination(12, TimeUnit.HOURS);
			LOG.info(">>> Executor shutdowm timed out : {}", !executorShutdownTimedOut);
		} catch (InterruptedException e) {
		    LOG.error("Data Operation Tasks interrupted.", e);
		} finally {
		    if (!executor.isTerminated()) {
		        LOG.error("Cancelling non-finished tasks ...");
		    }
		    executor.shutdownNow();
		    LOG.info(">>> Executor shutdown finished");

		    Long end = System.currentTimeMillis();
			LOG.info(">>> Performed Data Operation on {} process instances in {} (ms)", specList.size(), (end - start));
		}
	}

	private static final Pattern GAV_PATTERN = Pattern.compile(".+:.+:.+");

	/**
	 * Deploy the KJAR
	 *
	 * @param deploymentService
	 * @param gav
	 * @throws IOException
	 */
	private static void deployKjar(DeploymentService deploymentService, String gav) throws IOException {

		if(gav == null || !GAV_PATTERN.matcher(gav).matches()) {
			throw new IllegalStateException("Cannont deploy KJAR. Invalid GAV '"+gav+"'");
		}

		LOG.info("\n\t>>>> Deploying {} ....", gav);
		String [] tmp = gav.split(":");
		loadKjarFromClasspath(tmp[0], tmp[1], tmp[2]);
		KModuleDeploymentUnit unit = new KModuleDeploymentUnit(tmp[0], tmp[1], tmp[2]);
		deploymentService.deploy(unit);
		LOG.info("\n\t>>>> Succesfully deployed {} ", gav);
	}

	private static ReleaseId loadKjarFromClasspath(String G, String A, String V) throws IOException {
        KieFileSystem kfs = KieServices.Factory.get().newKieFileSystem();
        ReleaseId id = KieServices.Factory.get().newReleaseId(G, A, V);
        kfs.generateAndWritePomXML(id);
        byte[] pom = kfs.read("pom.xml");
        InputStream kjarIs = Application.class.getClassLoader()
                        .getResourceAsStream(String.format("META-INF/%s-%s.jar", A, V));
        byte[] kjar = IOUtils.toByteArray(kjarIs);
        MavenRepository.getMavenRepository().installArtifact(id, kjar, pom);
        return id;
	}
}


text:
{% extends "base.html" %}
{% block title %}{% block head_title %}{% endblock head_title %}{% endblock title %}

{% block content %}

    {% block inner %}
      {% csrf_token %}

      <input type="text" id="speed_value" disabled value="100">
      <input type="range" id="speed" min="0" max="255" value="100">
      <button type="button" value="left">Left</button>
      <button type="button" value="right">Right</button>
      <button type="button" value="up">Up</button>
      <button type="button" value="down">Down</button>
    {% endblock %}

{% endblock %}


text:
// jslitmus.js
//
// Copyright (c) 2010, Robert Kieffer, http://broofa.com
// Available under MIT license (http://en.wikipedia.org/wiki/MIT_License)

(function() {
  var root = this;

  //
  // Platform detect
  //

  var platform = (function() {
    // Platform info object
    var p = {
      name: null,
      version: null,
      os: null,
      description: 'unknown platform',
      toString: function() {return this.description;}
    };

    if (root.navigator) {
      var ua = navigator.userAgent;

      // Detect OS
      var oses = 'Windows|iPhone OS|(?:Intel |PPC )?Mac OS X|Linux';
      p.os = new RegExp('((' + oses + ') +[^ \);]*)').test(ua) ? RegExp.$1.replace(/_/g, '.') : null;

      // Detect expected names
      p.name = /(Chrome|MSIE|Safari|Opera|Firefox|Minefield)/.test(ua) ? RegExp.$1 : null;

      // Detect version
      if (p.name == 'Opera') {
        p.version = opera.name;
      } else if (p.name) {
        var vre = new RegExp('(Version|' + p.name + ')[ \/]([^ ;]*)');
        p.version = vre.test(ua) ? RegExp.$2 : null;
      }
    } else if (root.process && process.platform) {
      // Support node.js (see http://nodejs.org)
      p.name = 'node';
      p.version = process.version;
      p.os = process.platform;
    }

    // Set the description
    var d = [];
    if (p.name) d.push(p.name);
    if (p.version) d.push(' ' + p.version);
    if (p.os) d.push(' on ' + p.os);
    if (d.length) p.description = d.join('');

    return p;
  })();

  //
  // Context-specific initialization
  //

  var sys = null, querystring = null;
  if (platform.name == 'node') {
    sys = require('sys');
    querystring = require('querystring');
  }

  //
  // Misc convenience methods
  //

  function log(msg) {
    if (typeof(console) != 'undefined') {
      console.log(msg);
    } else if (sys) {
      sys.log(msg);
    }
  }

  // nil function
  function nilf(x) {
    return x;
  }

  // Copy properties
  function extend(dst, src) {
    for (var k in src) {
      dst[k] = src[k];
    }
    return dst;
  }

  // Array: apply f to each item in a
  function forEach(a, f) {
    for (var i = 0, il = (a && a.length); i < il; i++) {
      var o = a[i];
      f(o, i);
    }
  }

  // Array: return array of all results of f(item)
  function map(a, f) {
    var o, res = [];
    for (var i = 0, il = (a && a.length); i < il; i++) {
      var o = a[i];
      res.push(f(o, i));
    }
    return res;
  }

  // Array: filter out items for which f(item) is falsy
  function filter(a, f) {
    var o, res = [];
    for (var i = 0, il = (a && a.length); i < il; i++) {
      var o = a[i];
      if (f(o, i)) res.push(o);
    }
    return res;
  }

  // Array: IE doesn't have indexOf in some cases
  function indexOf(a, o) {
    if (a.indexOf) return a.indexOf(o);
    for (var i = 0, l = a.length; i < l; i++) if (a[i] === o) return i;
    return -1;
  }

  // Enhanced escape()
  function escape2(s) {
    s = s.replace(/,/g, '\\,');
    s = querystring ? querystring.escape(s) : escape(s);
    s = s.replace(/\+/g, '%2b');
    s = s.replace(/ /g, '+');
    return s;
  }

  // join(), for objects. Creates url query param-style strings by default
  function join(o, delimit1, delimit2) {
    var asQuery = !delimit1 && !delimit2;
    if (asQuery) {
      delimit1 = '&';
      delimit2 = '=';
    }

    var pairs = [];
    for (var key in o) {
      var value = o[key];
      if (asQuery) value = escape2(value);
      pairs.push(key + delimit2 + o[key]);
    }
    return pairs.join(delimit1);
  }

  // split(), for object strings. Parses url query param strings by default
  function split(s, delimit1, delimit2) {
    var asQuery = !delimit1 && !delimit2;
    if (asQuery) {
      s = s.replace(/.*[?#]/, '');
      delimit1 = '&';
      delimit2 = '=';
    }

    if (match) {
      var o = query.split(delimit1);
      for (var i = 0; i < o.length; i++) {
        var pair = o[i].split(new RegExp(delimit2 + '+'));
        var key = pair.shift();
        var value = (asQuery && pair.length > 1) ? pair.join(delimit2) : pair[0];
        o[key] = value;
      }
    }

    return o;
  }

  // Round x to d significant digits
  function sig(x, d) {
    var exp = Math.ceil(Math.log(Math.abs(x))/Math.log(10)),
        f = Math.pow(10, exp-d);
    return Math.round(x/f)*f;
  }

  // Convert x to a readable string version
  function humanize(x, sd) {
    var ax = Math.abs(x), res;
    sd = sd | 4;  // significant digits
    if (ax == Infinity) {
      res = ax > 0 ? 'Infinity' : '-Infinity';
    } else if (ax > 1e9) {
      res = sig(x/1e9, sd) + 'G';
    } else if (ax > 1e6) {
      res = sig(x/1e6, sd) + 'M';
    } else if (ax > 1e3) {
      res = sig(x/1e3, sd) + 'k';
    } else if (ax > .01) {
      res = sig(x, sd);
    } else if (ax > 1e-3) {
      res = sig(x/1e-3, sd) + 'm';
    } else if (ax > 1e-6) {
      res = sig(x/1e-6, sd) + '\u00b5'; // Greek mu
    } else if (ax > 1e-9) {
      res = sig(x/1e-9, sd) + 'n';
    } else {
      res = x ? sig(x, sd) : 0;
    }
    // Turn values like "1.1000000000005" -> "1.1"
    res = (res + '').replace(/0{5,}\d*/, '');

    return res;
  }

  // Node.js-inspired event emitter API, with some enhancements.
  function EventEmitter() {
    var ee = this;
    var listeners = {};
    extend(ee, {
      on: function(e, f) {
        if (!listeners[e]) listeners[e] = [];
        listeners[e].push(f);
      },
      removeListener: function(e, f) {
        listeners[e] = filter(listeners[e], function(l) {
          return l != f;
        });
      },
      removeAllListeners: function(e) {
        listeners[e] = [];
      },
      emit: function(e) {
        var args = Array.prototype.slice.call(arguments, 1);
        forEach([].concat(listeners[e], listeners['*']), function(l) {
          ee._emitting = e;
          if (l) l.apply(ee, args);
        });
        delete ee._emitting;
      }
    });
  }

  //
  // Test class
  //

  /**
   * Test manages a single test (created with JSLitmus.test())
   */
  function Test(name, f) {
    var test = this;

    // Test instances get EventEmitter API
    EventEmitter.call(test);

    if (!f) throw new Error('Undefined test function');
    if (!/function[^\(]*\(([^,\)]*)/.test(f)) {
      throw new Error('"' + name + '" test: Invalid test function');
    }

    // If the test function takes an argument, we assume it does the iteration
    // for us
    var isLoop = !!RegExp.$1;

    /**
     * Reset test state
     */
    function reset() {
      delete test.count;
      delete test.time;
      delete test.running;
      test.emit('reset', test);
      return test;
    }

    function clone() {
      var test = extend(new Test(name, f), test);
      return test.reset();
    }

    /**
     * Run the test n times, and use the best results
     */
    function bestOf(n) {
      var best = null;
      while (n--) {
        var t = clone();
        t.run(null, true);
        if (!best || t.period < best.period) {
          best = t;
        }
      }
      extend(test, best);
    }

    /**
     * Start running a test.  Default is to run the test asynchronously (via
     * setTimeout).  Can be made synchronous by passing true for 2nd param
     */
    function run(count, synchronous) {
      count = count || test.INIT_COUNT;
      test.running = true;

      if (synchronous) {
        _run(count, synchronous);
      } else {
        setTimeout(function() {
          _run(count);
        }, 1);
      }
      return test;
    }

    /**
     * Run, for real
     */
    function _run(count, noTimeout) {

      try {
        var start, f = test.f, now, i = count;

        // Start the timer
        start = new Date();

        // Run the test code
        test.count = count;
        test.time = 0;
        test.period = 0;

        test.emit('start', test);

        if (isLoop) {
          // Test code does it's own iteration
          f(count);
        } else {
          // Do the iteration ourselves
          while (i--) f();
        }

        // Get time test took (in secs)
        test.time = Math.max(1,new Date() - start)/1000;

        // Store iteration count and per-operation time taken
        test.count = count;
        test.period = test.time/count;

        // Do we need to keep running?
        test.running = test.time < test.MIN_TIME;

        // Publish results
        test.emit('results', test);

        // Set up for another run, if needed
        if (test.running) {
          // Use an iteration count that will (we hope) get us close to the
          // MAX_COUNT time.
          var x = test.MIN_TIME/test.time;
          var pow = Math.pow(2, Math.max(1, Math.ceil(Math.log(x)/Math.log(2))));
          count *= pow;
          if (count > test.MAX_COUNT) {
            throw new Error('Max count exceeded.  If this test uses a looping function, make sure the iteration loop is working properly.');
          }

          if (noTimeout) {
            _run(count, noTimeout);
          } else {
            run(count);
          }
        } else {
          test.emit('complete', test);
        }
      } catch (err) {
        log(err);
        // Exceptions are caught and displayed in the test UI
        test.emit('error', err);
      }

      return test;
    }

    /**
    * Get the number of operations per second for this test.
    *
    * @param normalize if true, iteration loop overhead taken into account.
    *                  Note that normalized tests may return Infinity if the
    *                  test time is of the same order as the calibration time.
    */
    function getHz(normalize) {
      var p = test.period;

      // Adjust period based on the calibration test time
      if (normalize) {
        var cal = test.isLoop ? Test.LOOP_CAL : Test.NOLOOP_CAL;
        if (!cal.period) {
          // Run calibration if needed
          cal.MIN_TIME = .3;
          cal.bestOf(3);
        }

        // Subtract off calibration time.  In theory this should never be
        // negative, but in practice the calibration times are affected by a
        // variety of factors so just clip to zero and let users test for
        // getHz() == Infinity
        p = Math.max(0, p - cal.period);
      }

      return sig(1/p, 4);
    }

    // Set properties that are specific to this instance
    extend(test, {
      // Test name
      name: name,

      // Test function
      f: f,

      // True if the test function does it's own looping (i.e. takes an arg)
      isLoop: isLoop,

      clone: clone,
      run: run,
      bestOf: bestOf,
      getHz: getHz,
      reset: reset
    });

    // IE7 doesn't do 'toString' or 'toValue' in object enumerations, so set
    // it explicitely here.
    test.toString = function() {
      if (this.time) {
        return this.name + ', f = '  +
        humanize(this.getHz()) + 'hz (' +
        humanize(this.count) + '/' + humanize(this.time) + 'secs)';
      } else {
        return this.name + ', count = '  + humanize(this.count);
      }
    };
  };

  // Set static properties
  extend(Test, {
    LOOP_CAL: new Test('loop cal', function(count) {while (count--) {}}),
    NOLOOP_CAL: new Test('noloop cal', nilf)
  });

  // Set default property values
  extend(Test.prototype, {
    // Initial number of iterations
    INIT_COUNT: 10,

    // Max iterations allowed (used to detect bad looping functions)
    MAX_COUNT: 1e9,

    // Minimum time test should take to get valid results (secs)
    MIN_TIME: 1.0
  });

  //
  // jslitmus
  //

  // Set up jslitmus context
  var jslitmus;
  if (platform.name == 'node') {
    jslitmus = exports;
  } else {
    jslitmus = root.jslitmus = {};
  }

  var tests = [], // test store (all tests added w/ jslitmus.test())
      queue = [], // test queue (to be run)
      currentTest; // currently runnning test

  // jslitmus gets EventEmitter API
  EventEmitter.call(jslitmus);

  /**
    * Create a new test
    */
  function test(name, f) {
    // Create the Test object
    var test = new Test(name, f);
    tests.push(test);

    // Run the next test if this one finished
    test.on('*', function() {
      // Forward test events to jslitmus listeners
      var args = Array.prototype.slice.call(arguments);
      args.unshift(test._emitting);
      jslitmus.emit.apply(jslitmus, args);

      // Auto-run the next test
      if (test._emitting == 'complete') {
        currentTest = null;
        _nextTest();
      }
    });

    jslitmus.emit('added', test);

    return test;
  }

  /**
    * Add all tests to the run queue
    */
  function runAll(e) {
    forEach(tests, _queueTest);
  }

  /**
    * Remove all tests from the run queue.  The current test has to finish on
    * it's own though
    */
  function stop() {
    while (queue.length) {
      var test = queue.shift();
    }
  }

  /**
    * Run the next test in the run queue
    */
  function _nextTest() {
    if (!currentTest) {
      var test = queue.shift();
      if (test) {
        currentTest = test;
        test.run();
      } else {
        jslitmus.emit('all_complete');
      }
    }
  }

  /**
    * Add a test to the run queue
    */
  function _queueTest(test) {
    if (indexOf(queue, test) >= 0) return;
    queue.push(test);
    _nextTest();
  }

  /**
    * Generate a Google Chart URL that shows the data for all tests
    */
  function getGoogleChart(normalize) {
    var chart_title = [
      'Operations/second on ' + platform.name,
      '(' + platform.version + ' / ' + platform.os + ')'
    ];

    var n = tests.length, markers = [], data = [];
    var d, min = 0, max = -1e10;

    // Gather test data

    var markers = map(tests, function(test, i) {
      if (test.count) {
        var hz = test.getHz();
        var v = hz != Infinity ? hz : 0;
        data.push(v);
        var label = test.name + '(' + humanize(hz)+ ')';
        var marker = 't' + escape2(label) + ',000000,0,' + i + ',10';
        max = Math.max(v, max);

        return marker;
      }
    });

    if (markers.length <= 0) return null;

    // Build labels
    var labels = [humanize(min), humanize(max)];

    var w = 250, bw = 15;
    var bs = 5;
    var h = markers.length*(bw + bs) + 30 + chart_title.length*20;

    var params = {
      chtt: escape(chart_title.join('|')),
      chts: '000000,10',
      cht: 'bhg',                     // chart type
      chd: 't:' + data.join(','),     // data set
      chds: min + ',' + max,          // max/min of data
      chxt: 'x',                      // label axes
      chxl: '0:|' + labels.join('|'), // labels
      chsp: '0,1',
      chm: markers.join('|'),         // test names
      chbh: [bw, 0, bs].join(','),    // bar widths
      // chf: 'bg,lg,0,eeeeee,0,eeeeee,.5,ffffff,1', // gradient
      chs: w + 'x' + h
    };

    var url = 'http://chart.apis.google.com/chart?' + join(params);

    return url;
  }

  // Public API
  extend(jslitmus, {
    Test: Test,
    platform: platform,
    test: test,
    runAll: runAll,
    getGoogleChart: getGoogleChart
  });

  // Expose code goodness we've got here, since it's useful, but do so in a way
  // that doesn't commit us to supporting it in future versions.
  jslitmus.unsupported = {
    nilf: nilf,
    log: log,
    extend: extend,
    forEach: forEach,
    filter: filter,
    map: map,
    indexOf: indexOf,
    escape2: escape2,
    join: join,
    split: split,
    sig: sig,
    humanize: humanize
  };
})();


text:
try:
    import Tkinter
    import tkMessageBox
    import Time
    from Tkinter import Entry,Label
except ImportError:
    print "Error : your system dosn't support Tkinter GUI, either it is a command line interface or you do not have \
the Tkinter library installed."
    exit()

class parent():
    def __init__(self,name):
        top = Tkinter.Tk()

        def helloCallBack():
            tkMessageBox.showinfo("time", Time.getTime(False))

        self.B = Tkinter.Button(top, text="show time", bg="gray", command=helloCallBack)
        self.L = Tkinter.Label(top, text="hi %s" % name , fg = "orange")
        Label(top,text="enter anything :").grid(row=1 ,column=0)
        E = Entry(top)
        self.L.grid(row=0 ,column=1)
        E.grid(row=1 ,column=1)
        self.B.grid(row=3 , column=1)
        Text = E.get();
        Label(top,text=Text).grid(row=4 ,column=1)
        top.mainloop()

    def object(self):
        pass


text:
/**
 * @file      move_to_pose.cpp
 * @brief     Arm motion node. Uses end-effector goal specification.
 * @author    Alexandre Silva <s1464657@sms.ed.ac.uk>
 * @date      2015-08-20
 */

#include "motion/move_to_pose.hpp"

MoveToPoseAction::MoveToPoseAction(ros::NodeHandle nh, std::string name) :
  nh_(nh),
  as_(nh_, name, false),
  action_name_(name) {
  //register the goal and feeback callbacks
  as_.registerGoalCallback(boost::bind(&MoveToPoseAction::goalCB, this));
  as_.registerPreemptCallback(boost::bind(&MoveToPoseAction::preemptCB, this));

  this->init();
  ROS_INFO("Starting MoveToPose server");
  as_.start();
}

MoveToPoseAction::~MoveToPoseAction(void) {
}

void MoveToPoseAction::init() {
}

void MoveToPoseAction::goalCB() {
  boost::shared_ptr< const motion_msgs::MoveToPoseGoal > goal = as_.acceptNewGoal();
  target_pose_ = goal->pose;
  distance_tol_ = goal->distance_tol;
  planning_time_ = goal->planning_time;
  orientation_tol_ = goal->orientation_tol;
  grasping_move_ = goal->grasping_move;
  this->executeCB();
}

void MoveToPoseAction::preemptCB() {
  ROS_INFO("Preempt");
  as_.setPreempted();
}

void MoveToPoseAction::executeCB() {
  bool going = true;
  bool success = false;
  bool plan_grasp_action = grasping_move_;
  bool moving = false;

  timed_out_ = false;
  // states:
  // 0 plan
  // 1 execute
  // 2 execute grasp action
  // 3 end
  int state = 0;
  int endstate = 3;

  ros::Rate r(10);
  ROS_INFO("Executing goal for %s", action_name_.c_str());
  feedback_.curr_state = 0;
  as_.publishFeedback(feedback_);
  // get move it to execute motion
  moveit::planning_interface::MoveGroup group("arm_1");
  // moveit motion plan
  move_group_interface::MoveGroup::Plan plan;
  move_group_interface::MoveGroup::Plan grasp_plan;
  // approach target pose
  double approach_dist = 0.05;
  geometry_msgs::PoseStamped target_pose = target_pose_;
  geometry_msgs::PoseStamped approach_pose = target_pose_;
  approach_pose.pose.position.z += approach_dist;

  while (going) {
    if (as_.isPreemptRequested() || !ros::ok()) {
      ROS_INFO("%s: Preempted", action_name_.c_str());
      as_.setPreempted();
      going = false;
    }

    // plan approach of a grasp action
    if (plan_grasp_action) {
      group.setPoseTarget(approach_pose, group.getEndEffectorLink());
      group.setGoalTolerance(distance_tol_);
      group.setGoalOrientationTolerance(orientation_tol_);
      group.setPlanningTime(planning_time_);
      // setup first target
      if (group.plan(plan)) {
        std::vector<double> init_state_ = plan.trajectory_.joint_trajectory.points.back().positions;
        robot_state::RobotState start_state(*group.getCurrentState());
        start_state.setVariablePosition(0, init_state_[0]);
        start_state.setVariablePosition(1, init_state_[1]);
        start_state.setVariablePosition(2, init_state_[2]);
        start_state.setVariablePosition(3, init_state_[3]);
        start_state.setVariablePosition(4, init_state_[4]);
        group.setStartState(start_state);
        group.setPoseTarget(target_pose_, group.getEndEffectorLink());
        group.setGoalTolerance(distance_tol_);
        group.setGoalOrientationTolerance(orientation_tol_);
        group.setPlanningTime(planning_time_);
        if (group.plan(grasp_plan)) {
          double base_joint_1 = init_state_[0];
          double base_joint_2 = grasp_plan.trajectory_.joint_trajectory.points.back().positions[0];

          if (fabs(base_joint_1 - base_joint_2) < 1.0) {
            plan_grasp_action = false;
            // have to set target pose as we will approach first
            target_pose = approach_pose;
            // go to execute plan
            state = 1;
          }
        }
      }

      // terminate if no plan
      if (state == 0)
        going = false;

      // terminate if no plan
      if (state == 0) {
        going = false;
        ROS_WARN("Failed planning smooth grasp trajectory");
      } else
        ROS_WARN("Valid grasp plan");

    } if (moving) {
      curr_pose_ = group.getCurrentPose();
      // ROS_INFO("CURRENT POSE: x:%f y:%f z:%f", curr_pose_.pose.position.x, curr_pose_.pose.position.y, curr_pose_.pose.position.z);
      distance_ = sqrt(pow(curr_pose_.pose.position.x - target_pose.pose.position.x, 2) +
                       pow(curr_pose_.pose.position.y - target_pose.pose.position.y, 2) +
                       pow(curr_pose_.pose.position.z - target_pose.pose.position.z, 2) );
      // ROS_INFO("Current distance to desired pose: %f", distance_);

      if (distance_ < distance_tol_) {
        if (grasping_move_)
          state++;
        else
          state = endstate;
        moving = false;
      }
    } else if (state == 0) {
      group.setPoseTarget(target_pose_, group.getEndEffectorLink());
      group.setGoalTolerance(distance_tol_);
      group.setGoalOrientationTolerance(orientation_tol_);
      group.setPlanningTime(planning_time_);
      if (!group.plan(plan)) {
        ROS_FATAL("Unable to create motion plan.  Aborting.");
        going = false;
      } else {
        ROS_INFO("Planning was successful");
        state = 1;
      }
    } else if (state == 1) {
      // do blocking move request
      // ATTENTION: moveit may abort but continue the motion
      if (group.execute(plan)) {
        if (grasping_move_) {
          state++;
        } else {
          state = endstate;
        }
      } else {
        // set timer
        // setting an action timer
        timed_out_ = false;
        timer_ = nh_.createTimer(ros::Duration(10), &MoveToPoseAction::timerCB, this, true);
        moving = true;
        ROS_INFO("Waiting to reach desired position...");
      }
    } else if (state == 2) {
      // execute second part of grasp action
      // do blocking move request
      // ATTENTION: moveit may abort but continue the motion
      target_pose = target_pose_;
      timer_.stop();
      if (group.execute(grasp_plan)) {
        state++;
      } else {
        // set timer
        // setting an action timer
        timed_out_ = false;
        timer_ = nh_.createTimer(ros::Duration(10), &MoveToPoseAction::timerCB, this, true);
        moving = true;
        ROS_INFO("Waiting to reach desired position...");
      }
    } else if (state == endstate) {
      going = false;
      success = true;
    }

    if (timed_out_) {
      ROS_INFO("%s: Timed out", action_name_.c_str());
      going = false;
    }

    ros::spinOnce();
    r.sleep();
  }

  curr_pose_ = group.getCurrentPose();
  ROS_INFO("TARGET POSE: x:%f y:%f z:%f", target_pose_.pose.position.x, target_pose_.pose.position.y, target_pose_.pose.position.z);
  ROS_INFO("CURRENT POSE: x:%f y:%f z:%f", curr_pose_.pose.position.x, curr_pose_.pose.position.y, curr_pose_.pose.position.z);
  distance_ = sqrt(pow(curr_pose_.pose.position.x - target_pose_.pose.position.x, 2) +
                   pow(curr_pose_.pose.position.y - target_pose_.pose.position.y, 2) +
                   pow(curr_pose_.pose.position.z - target_pose_.pose.position.z, 2) );
  ROS_INFO("Current distance to desired pose: %f", distance_);
  feedback_.curr_state = 3;
  as_.publishFeedback(feedback_);

  if (success) {
    result_.success = true;
    ROS_INFO("%s: Succeeded!", action_name_.c_str());
    as_.setSucceeded(result_);
  } else {
    result_.success = false;
    ROS_INFO("%s: Failed!", action_name_.c_str());
    as_.setAborted(result_);
  }
  timer_.stop();
}

void MoveToPoseAction::timerCB(const ros::TimerEvent& event) {
  timed_out_ = true;
}


text:
'''
Created on Jan 10, 2017

@author: tamsyn
'''

ByPassed = "By passed"
Triggered = "Triggered"
NotTriggered = "Not Triggered"
Nothing = "Nothing"

class BaseFilter():
    '''
    Basic interface that all the plug-in need to implement
    '''
    def __init__(self, filtertype):
        '''
        Constructor
        '''
        self.type = filtertype
        self.obj = "";
        self.param = {}
        self.result = Nothing

    def get_type(self):
        return self.type

    def set_object(self, msg):
        self.obj = msg

    def set_param(self, paramters):
        self.param = paramters

    def Execute(self):
        pass

    def Log(self):
        pass

    def get_result(self):
        return self.result


text:
struct IsUIMF : public pwiz::util::TestPathPredicate
{
    bool operator() (const string& rawpath) const
    {
        return bfs::is_regular_file(rawpath) && bal::iequals(bfs::extension(rawpath), ".UIMF");
    }
};

int main(int argc, char* argv[])
{
    TEST_PROLOG(argc, argv)

    #ifdef PWIZ_READER_UIMF
    const bool testAcceptOnly = false;
    #else
    const bool testAcceptOnly = true;
    #endif

    try
    {
        bool requireUnicodeSupport = true;
        pwiz::util::testReader(pwiz::msdata::Reader_UIMF(), testArgs, testAcceptOnly, requireUnicodeSupport, IsUIMF());
    }
    catch (exception& e)
    {
        TEST_FAILED(e.what())
    }
    catch (...)
    {
        TEST_FAILED("Caught unknown exception.")
    }

    TEST_EPILOG
}


text:
class MojoWebUIBrowserTest : public BaseWebUIBrowserTest {
 public:
  MojoWebUIBrowserTest();
  ~MojoWebUIBrowserTest() override;

  void set_use_mojo_lite_bindings() { use_mojo_lite_bindings_ = true; }

  // WebUIBrowserTest:
  void BrowsePreload(const GURL& browse_to) override;
  void SetUpOnMainThread() override;
  void SetupHandlers() override;

 private:
  class WebUITestContentBrowserClient;
  std::unique_ptr<WebUITestContentBrowserClient> test_content_browser_client_;

  bool use_mojo_lite_bindings_ = false;
};

#endif  // CHROME_TEST_BASE_MOJO_WEB_UI_BROWSER_TEST_H_


text:
package me.iwf.photopicker.widget;

import android.animation.ValueAnimator;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.Checkable;

import me.iwf.photopicker.R;

/**
 * Author : andy
 * Date   : 16/1/21 11:28
 * Email  : andyxialm@gmail.com
 * Github : github.com/andyxialm
 * Description : A custom CheckBox with animation for Android
 */

public class SmoothCheckBox extends View implements Checkable {
    private static final String KEY_INSTANCE_STATE = "InstanceState";

    private static final int COLOR_TICK      = Color.WHITE;
    private static final int COLOR_UNCHECKED = Color.WHITE;
    private static final int COLOR_CHECKED   = Color.parseColor("#FB4846");
    private static final int COLOR_FLOOR_UNCHECKED = Color.parseColor("#DFDFDF");

    private static final int DEF_DRAW_SIZE     = 25;
    private static final int DEF_ANIM_DURATION = 300;

    private Paint mPaint, mTickPaint, mFloorPaint;
    private Point[] mTickPoints;
    private Point mCenterPoint;
    private Path mTickPath;

    private float mLeftLineDistance, mRightLineDistance, mDrewDistance;
    private float mScaleVal = 1.0f, mFloorScale = 1.0f;
    private int mWidth, mAnimDuration, mStrokeWidth;
    private int mCheckedColor, mUnCheckedColor, mFloorColor, mFloorUnCheckedColor;

    private boolean mChecked;
    private boolean mTickDrawing;
    private OnCheckedChangeListener mListener;

    public SmoothCheckBox(Context context) {
        this(context, null);
    }

    public SmoothCheckBox(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public SmoothCheckBox(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(attrs);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public SmoothCheckBox(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init(attrs);
    }

    private void init(AttributeSet attrs) {

        TypedArray ta = getContext().obtainStyledAttributes(attrs, R.styleable.__picker_SmoothCheckBox);
        int tickColor = ta.getColor(R.styleable.__picker_SmoothCheckBox___picker_color_tick, COLOR_TICK);
        mAnimDuration = ta.getInt(R.styleable.__picker_SmoothCheckBox___picker_duration, DEF_ANIM_DURATION);
        mFloorColor = ta.getColor(R.styleable.__picker_SmoothCheckBox___picker_color_unchecked_stroke, COLOR_FLOOR_UNCHECKED);
        mCheckedColor = ta.getColor(R.styleable.__picker_SmoothCheckBox___picker_color_checked, COLOR_CHECKED);
        mUnCheckedColor = ta.getColor(R.styleable.__picker_SmoothCheckBox___picker_color_unchecked, COLOR_UNCHECKED);
        mStrokeWidth = ta.getDimensionPixelSize(R.styleable.__picker_SmoothCheckBox___picker_stroke_width, CompatUtils.dp2px(getContext(), 0));
        ta.recycle();

        mFloorUnCheckedColor = mFloorColor;
        mTickPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mTickPaint.setStyle(Paint.Style.STROKE);
        mTickPaint.setStrokeCap(Paint.Cap.ROUND);
        mTickPaint.setColor(tickColor);

        mFloorPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mFloorPaint.setStyle(Paint.Style.FILL);
        mFloorPaint.setColor(mFloorColor);

        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setColor(mCheckedColor);

        mTickPath = new Path();
        mCenterPoint = new Point();
        mTickPoints = new Point[3];
        mTickPoints[0] = new Point();
        mTickPoints[1] = new Point();
        mTickPoints[2] = new Point();

        setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                toggle();
                mTickDrawing = false;
                mDrewDistance = 0;
                if (isChecked()) {
                    startCheckedAnimation();
                } else {
                    startUnCheckedAnimation();
                }
            }
        });
    }

    @Override
    protected Parcelable onSaveInstanceState() {
        Bundle bundle = new Bundle();
        bundle.putParcelable(KEY_INSTANCE_STATE, super.onSaveInstanceState());
        bundle.putBoolean(KEY_INSTANCE_STATE, isChecked());
        return bundle;
    }

    @Override
    protected void onRestoreInstanceState(Parcelable state) {
        if (state instanceof Bundle) {
            Bundle bundle = (Bundle) state;
            boolean isChecked = bundle.getBoolean(KEY_INSTANCE_STATE);
            setChecked(isChecked);
            super.onRestoreInstanceState(bundle.getParcelable(KEY_INSTANCE_STATE));
            return;
        }
        super.onRestoreInstanceState(state);
    }

    @Override
    public boolean isChecked() {
        return mChecked;
    }

    @Override
    public void toggle() {
        this.setChecked(!isChecked());
    }

    @Override
    public void setChecked(boolean checked) {
        mChecked = checked;
        reset();
        invalidate();
        if (mListener != null) {
            mListener.onCheckedChanged(SmoothCheckBox.this, mChecked);
        }
    }

    /**
     * checked with animation
     * @param checked checked
     * @param animate change with animation
     */
    public void setChecked(boolean checked, boolean animate) {
        if (animate) {
            mTickDrawing = false;
            mChecked = checked;
            mDrewDistance = 0f;
            cancelAnimation();
            if (checked) {
                startCheckedAnimation();
            } else {
                startUnCheckedAnimation();
            }
            if (mListener != null) {
                mListener.onCheckedChanged(SmoothCheckBox.this, mChecked);
            }

        } else {
            this.setChecked(checked);
        }
    }

    private void reset() {
        mTickDrawing = true;
        mFloorScale = 1.0f;
        mScaleVal = isChecked() ? 0f : 1.0f;
        mFloorColor = isChecked() ? mCheckedColor : mFloorUnCheckedColor;
        mDrewDistance = isChecked() ? (mLeftLineDistance + mRightLineDistance) : 0;
    }

    private int measureSize(int measureSpec) {
        int defSize = CompatUtils.dp2px(getContext(), DEF_DRAW_SIZE);
        int specSize = MeasureSpec.getSize(measureSpec);
        int specMode = MeasureSpec.getMode(measureSpec);

        int result = 0;
        switch (specMode) {
            case MeasureSpec.UNSPECIFIED:
            case MeasureSpec.AT_MOST:
                result = Math.min(defSize, specSize);
                break;
            case MeasureSpec.EXACTLY:
                result = specSize;
                break;
        }
        return result;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        setMeasuredDimension(measureSize(widthMeasureSpec), measureSize(heightMeasureSpec));
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        mWidth = getMeasuredWidth();
        mStrokeWidth = (mStrokeWidth == 0 ? getMeasuredWidth() / 10 : mStrokeWidth);
        mStrokeWidth = mStrokeWidth > getMeasuredWidth() / 5 ? getMeasuredWidth() / 5 : mStrokeWidth;
        mStrokeWidth = (mStrokeWidth < 3) ? 3 : mStrokeWidth;
        mCenterPoint.x = mWidth / 2;
        mCenterPoint.y = getMeasuredHeight() / 2;

        mTickPoints[0].x = Math.round((float) getMeasuredWidth() / 30 * 7);
        mTickPoints[0].y = Math.round((float) getMeasuredHeight() / 30 * 14);
        mTickPoints[1].x = Math.round((float) getMeasuredWidth() / 30 * 13);
        mTickPoints[1].y = Math.round((float) getMeasuredHeight() / 30 * 20);
        mTickPoints[2].x = Math.round((float) getMeasuredWidth() / 30 * 22);
        mTickPoints[2].y = Math.round((float) getMeasuredHeight() / 30 * 10);

        mLeftLineDistance = (float) Math.sqrt(Math.pow(mTickPoints[1].x - mTickPoints[0].x, 2) +
                Math.pow(mTickPoints[1].y - mTickPoints[0].y, 2));
        mRightLineDistance = (float) Math.sqrt(Math.pow(mTickPoints[2].x - mTickPoints[1].x, 2) +
                Math.pow(mTickPoints[2].y - mTickPoints[1].y, 2));
        mTickPaint.setStrokeWidth(mStrokeWidth);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        drawBorder(canvas);
        drawCenter(canvas);
        drawTick(canvas);
    }

    private void drawCenter(Canvas canvas) {
        mPaint.setColor(mUnCheckedColor);
        float radius = (mCenterPoint.x - mStrokeWidth) * mScaleVal;
        canvas.drawCircle(mCenterPoint.x, mCenterPoint.y, radius, mPaint);
    }

    private void drawBorder(Canvas canvas) {
        mFloorPaint.setColor(mFloorColor);
        int radius = mCenterPoint.x;
        canvas.drawCircle(mCenterPoint.x, mCenterPoint.y, radius * mFloorScale, mFloorPaint);
    }

    private void drawTick(Canvas canvas) {
        if (mTickDrawing && isChecked()) {
            drawTickPath(canvas);
        }
    }

    private void drawTickPath(Canvas canvas) {
        mTickPath.reset();
        // draw left of the tick
        if (mDrewDistance < mLeftLineDistance) {
            float step = (mWidth / 20.0f) < 3 ? 3 : (mWidth / 20.0f);
            mDrewDistance += step;
            float stopX = mTickPoints[0].x + (mTickPoints[1].x - mTickPoints[0].x) * mDrewDistance / mLeftLineDistance;
            float stopY = mTickPoints[0].y + (mTickPoints[1].y - mTickPoints[0].y) * mDrewDistance / mLeftLineDistance;

            mTickPath.moveTo(mTickPoints[0].x, mTickPoints[0].y);
            mTickPath.lineTo(stopX, stopY);
            canvas.drawPath(mTickPath, mTickPaint);

            if (mDrewDistance > mLeftLineDistance) {
                mDrewDistance = mLeftLineDistance;
            }
        } else {

            mTickPath.moveTo(mTickPoints[0].x, mTickPoints[0].y);
            mTickPath.lineTo(mTickPoints[1].x, mTickPoints[1].y);
            canvas.drawPath(mTickPath, mTickPaint);

            // draw right of the tick
            if (mDrewDistance < mLeftLineDistance + mRightLineDistance) {
                float stopX = mTickPoints[1].x + (mTickPoints[2].x - mTickPoints[1].x) * (mDrewDistance - mLeftLineDistance) / mRightLineDistance;
                float stopY = mTickPoints[1].y - (mTickPoints[1].y - mTickPoints[2].y) * (mDrewDistance - mLeftLineDistance) / mRightLineDistance;

                mTickPath.reset();
                mTickPath.moveTo(mTickPoints[1].x, mTickPoints[1].y);
                mTickPath.lineTo(stopX, stopY);
                canvas.drawPath(mTickPath, mTickPaint);

                float step = (mWidth / 20) < 3 ? 3 : (mWidth / 20);
                mDrewDistance += step;
            } else {
                mTickPath.reset();
                mTickPath.moveTo(mTickPoints[1].x, mTickPoints[1].y);
                mTickPath.lineTo(mTickPoints[2].x, mTickPoints[2].y);
                canvas.drawPath(mTickPath, mTickPaint);
            }
        }

        // invalidate
        if (mDrewDistance < mLeftLineDistance + mRightLineDistance) {
            postDelayed(new Runnable() {
                @Override
                public void run() {
                    postInvalidate();
                }
            }, 10);
        }
    }

    private ValueAnimator mAnimator;
    private ValueAnimator mFloorAnimator;

    private void cancelAnimation(){
        if (mAnimator != null) {
            mAnimator.cancel();
        }
        if (mFloorAnimator != null) {
            mFloorAnimator.cancel();
        }
    }

    private void startCheckedAnimation() {

        mAnimator = ValueAnimator.ofFloat(1.0f, 0f);
        mAnimator.setDuration(mAnimDuration / 3 * 2);
        mAnimator.setInterpolator(new LinearInterpolator());
        mAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                mScaleVal = (float) animation.getAnimatedValue();
                mFloorColor = getGradientColor(mUnCheckedColor, mCheckedColor, 1 - mScaleVal);
                postInvalidate();
            }
        });
        mAnimator.start();

        mFloorAnimator = ValueAnimator.ofFloat(1.0f, 0.8f, 1.0f);
        mFloorAnimator.setDuration(mAnimDuration);
        mFloorAnimator.setInterpolator(new LinearInterpolator());
        mFloorAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                mFloorScale = (float) animation.getAnimatedValue();
                postInvalidate();
            }
        });
        mFloorAnimator.start();

        drawTickDelayed();
    }

    private void startUnCheckedAnimation() {
        mAnimator = ValueAnimator.ofFloat(0f, 1.0f);
        mAnimator.setDuration(mAnimDuration);
        mAnimator.setInterpolator(new LinearInterpolator());
        mAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                mScaleVal = (float) animation.getAnimatedValue();
                mFloorColor = getGradientColor(mCheckedColor, mFloorUnCheckedColor, mScaleVal);
                postInvalidate();
            }
        });
        mAnimator.start();

        mFloorAnimator = ValueAnimator.ofFloat(1.0f, 0.8f, 1.0f);
        mFloorAnimator.setDuration(mAnimDuration);
        mFloorAnimator.setInterpolator(new LinearInterpolator());
        mFloorAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                mFloorScale = (float) animation.getAnimatedValue();
                postInvalidate();
            }
        });
        mFloorAnimator.start();
    }

    private void drawTickDelayed() {
        postDelayed(new Runnable() {
            @Override
            public void run() {
                mTickDrawing = true;
                postInvalidate();
            }
        }, mAnimDuration);
    }

    private static int getGradientColor(int startColor, int endColor, float percent) {
        int sr = (startColor & 0xff0000) >> 0x10;
        int sg = (startColor & 0xff00) >> 0x8;
        int sb = (startColor & 0xff);

        int er = (endColor & 0xff0000) >> 0x10;
        int eg = (endColor & 0xff00) >> 0x8;
        int eb = (endColor & 0xff);

        int cr = (int) (sr * (1 - percent) + er * percent);
        int cg = (int) (sg * (1 - percent) + eg * percent);
        int cb = (int) (sb * (1 - percent) + eb * percent);
        return Color.argb(0xff, cr, cg, cb);
    }

    public void setOnCheckedChangeListener(OnCheckedChangeListener l) {
        this.mListener = l;
    }

    public interface OnCheckedChangeListener {
        void onCheckedChanged(SmoothCheckBox checkBox, boolean isChecked);
    }
}


text:
namespace base {
struct Feature;
}

namespace autofill_assistant {
namespace features {
// All features in alphabetical order.
extern const base::Feature kAutofillAssistant;
extern const base::Feature kAutofillAssistantChromeEntry;
extern const base::Feature kAutofillAssistantDirectActions;

}  // namespace features
}  // namespace autofill_assistant

#endif  // COMPONENTS_AUTOFILL_ASSISTANT_BROWSER_FEATURES_H_


text:
import inspect
import traceback
from weppy.handler import *
from weppy.http import *

class WSGIApplication(object):
    """
    WSGI application interface.
    """

    def __init__(self, debug, controllers=None):
        """
        Inspect controller modules to find Handler instances.
        """
        self._debug = debug
        self._routes = {}
        for controller in controllers or []:
            for name, obj in inspect.getmembers(controller):
                if isinstance(obj, Handler):
                    self.add_handler(obj)

    def add_handler(self, handler):
        """
        Add a Handler instance to this application.
        """
        self._routes[handler._url_regex] = handler

    def handle_request(self, req):
        """
        Return an HTTPResponse processed by the appropriate Handler instance or by catching an
        exception, or redirect the request by appending a slash to its path.
        """
        try:
            for (url_regex, handler) in self._routes.items():
                match = url_regex.match(req.path)
                if match is not None:
                    return handler(req, *match.groups())
            for (url_regex, handler) in self._routes.items():
                match = url_regex.match(req.path + '/')
                if match is not None:
                    return HTTPRedirect(req.path + '/')
            raise HTTPNotFound()
        except Exception as error:
            if not isinstance(error, HTTPError):
                if self._debug:
                    traceback.print_exc()
                error = HTTPInternalServerError()
            return HTTPResponse(str(error), status=error.status)

    def __call__(self, environ, start_response):
        """
        WSGI interface.
        """
        return self.handle_request(HTTPRequest(environ))(environ, start_response)


text:
<?php

namespace Beanie\Exception;

class DrainingException extends AbstractServerException
{
    const DEFAULT_CODE = 409;
    const DEFAULT_MESSAGE = 'Server \'%s\' is draining';
}


text:
require 'chef/log'
require 'mixlib/config'

class Chef
  class Config

    extend Mixlib::Config

    # Manages the chef secret session key
    # === Returns
    # <newkey>:: A new or retrieved session key
    #
    def self.manage_secret_key
      newkey = nil
      if Chef::FileCache.has_key?("chef_server_cookie_id")
        newkey = Chef::FileCache.load("chef_server_cookie_id")
      else
        chars = ("a".."z").to_a + ("A".."Z").to_a + ("0".."9").to_a
        newkey = ""
        40.times { |i| newkey << chars[rand(chars.size-1)] }
        Chef::FileCache.store("chef_server_cookie_id", newkey)
      end
      newkey
    end

    # Override the config dispatch to set the value of multiple server options simultaneously
    #
    # === Parameters
    # url<String>:: String to be set for all of the chef-server-api URL's
    #
    config_attr_writer :chef_server_url do |url|
      configure do |c|
        [ :registration_url,
          :openid_url,
          :template_url,
          :remotefile_url,
          :search_url,
          :chef_server_url,
          :role_url ].each do |u|
            c[u] = url
        end
      end
      url
    end

    # When you are using ActiveSupport, they monkey-patch 'daemonize' into Kernel.
    # So while this is basically identical to what method_missing would do, we pull
    # it up here and get a real method written so that things get dispatched
    # properly.
    config_attr_writer :daemonize do |v|
      configure do |c|
        c[:daemonize] = v
      end
    end

    # Override the config dispatch to set the value of log_location configuration option
    #
    # === Parameters
    # location<IO||String>:: Logging location as either an IO stream or string representing log file path
    #
    config_attr_writer :log_location do |location|
      if location.respond_to? :sync=
        location
      elsif location.respond_to? :to_str
        f = File.new(location.to_str, "a")
        f.sync = true
        f
      end
    end

    # Override the config dispatch to set the value of authorized_openid_providers when openid_providers (deprecated) is used
    #
    # === Parameters
    # providers<Array>:: An array of openid providers that are authorized to login to the chef server
    #
    config_attr_writer :openid_providers do |providers|
      configure { |c| c[:authorized_openid_providers] = providers }
      providers
    end

    authorized_openid_identifiers nil
    authorized_openid_providers nil
    client_registration_retries 5
    cookbook_path [ "/var/chef/cookbooks", "/var/chef/site-cookbooks" ]
    cookbook_tarball_path "/var/chef/cookbook-tarballs"
    couchdb_database "chef"
    couchdb_url "http://localhost:5984"
    couchdb_version nil
    delay 0
    executable_path ENV['PATH'] ? ENV['PATH'].split(File::PATH_SEPARATOR) : []
    file_cache_path "/var/chef/cache"
    file_backup_path nil
    group nil
    http_retry_count 5
    http_retry_delay 5
    interval nil
    json_attribs nil
    log_level :info
    log_location STDOUT
    verbose_logging nil
    node_name nil
    node_path "/var/chef/node"
    openid_cstore_couchdb false
    openid_cstore_path "/var/chef/openid/cstore"
    openid_providers nil
    openid_store_couchdb false
    openid_store_path "/var/chef/openid/db"
    openid_url "http://localhost:4001"
    pid_file nil
    queue_host "localhost"
    queue_password ""
    queue_port 61613
    queue_retry_count 5
    queue_retry_delay 5
    queue_user ""
    chef_server_url "http://localhost:4000"
    registration_url "http://localhost:4000"
    client_url "http://localhost:4042"
    remotefile_url "http://localhost:4000"
    rest_timeout 300
    run_command_stderr_timeout 120
    run_command_stdout_timeout 120
    search_url "http://localhost:4000"
    solo  false
    splay nil
    ssl_client_cert ""
    ssl_client_key ""
    ssl_verify_mode :verify_none
    ssl_ca_path nil
    ssl_ca_file nil
    template_url "http://localhost:4000"
    umask 0022
    user nil
    validation_token nil
    role_path "/var/chef/roles"
    role_url "http://localhost:4000"
    recipe_url nil
    solr_url "http://localhost:8983"
    solr_jetty_path "/var/chef/solr-jetty"
    solr_data_path "/var/chef/solr/data"
    solr_home_path "/var/chef/solr"
    solr_heap_size "256M"
    solr_java_opts nil
    amqp_host '0.0.0.0'
    amqp_port '5672'
    amqp_user 'chef'
    amqp_pass 'testing'
    amqp_vhost '/chef'
    # Setting this to a UUID string also makes the queue durable
    # (persist across rabbitmq restarts)
    amqp_consumer_id "default"

    client_key "/etc/chef/client.pem"
    validation_key "/etc/chef/validation.pem"
    validation_client_name "chef-validator"
    web_ui_client_name "chef-webui"
    web_ui_key "/etc/chef/webui.pem"
    web_ui_admin_user_name  "admin"
    web_ui_admin_default_password "p@ssw0rd1"

    # Server Signing CA
    #
    # In truth, these don't even have to change
    signing_ca_cert "/var/chef/ca/cert.pem"
    signing_ca_key "/var/chef/ca/key.pem"
    signing_ca_user nil
    signing_ca_group nil
    signing_ca_country "US"
    signing_ca_state "Washington"
    signing_ca_location "Seattle"
    signing_ca_org "Chef User"
    signing_ca_domain "opensource.opscode.com"
    signing_ca_email "opensource-cert@opscode.com"

    # Checksum Cache
    # Uses Moneta on the back-end
    cache_type "BasicFile"
    cache_options({ :path => "/var/chef/cache/checksums", :skip_expires => true })

  end
end


text:
<?xml version="1.0" encoding="utf-8"?>

<merge
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:cf="http://schemas.android.com/apk/res-auto">

    <discovery.contentful.ui.PagerSlidingTabStrip
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="@dimen/tabs_height"
        android:background="@color/cf_gray_background"
        cf:pstsDividerColor="#abb5c0"
        cf:pstsIndicatorColor="@color/cf_blue_secondary"
        cf:pstsShouldExpand="true"
        cf:pstsUnderlineColor="#abb5c0"
        cf:pstsUnderlineHeight="1dp"/>

    <android.support.v4.view.ViewPager
        android:id="@+id/view_pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="@dimen/tabs_height"/>

</merge>


text:
using ChaosCMS.Json.Models;
using ChaosCMS.LiteDB.Models;

namespace SampleSite.Model
{
    public class User : LiteDBUser //JsonUser
    {
    }
}


text:
package fi.csc.antero.controller;

import fi.csc.antero.exception.NotFoundException;
import fi.csc.antero.repository.ApiDataService;
import fi.csc.antero.repository.ApiProperty;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import java.util.Set;

@RestController
public class ApiController {

    private final ApiDataService service;

    @Autowired
    public ApiController(ApiDataService service) {
        this.service = service;
    }

    @RequestMapping(value = "/resources/{resource}/data", method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "Get resource data",
            notes = "You can query resource data with filters and use paging. " +
                    "Filtering uses [FIQL](https://tools.ietf.org/html/draft-nottingham-atompub-fiql-00) query syntax. " +
                    "HOX! All dates are in GMT time.",
            responseContainer = "List",
            response = Object.class)
    public StreamingResponseBody getResourceData(@ApiParam(value = "Name of the resource", required = true)
                                                 @PathVariable("resource") String resource,
                                                 ApiQuery query,
                                                 HttpServletResponse response) throws SQLException {
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        checkResource(resource);
        return outputStream -> {
            try {
                service.streamToJsonArray(resource, outputStream, query);
            } catch (SQLException e) {
                throw new IOException(e);
            }
        };
    }

    @RequestMapping(value = "/resources/{resource}/data/count", method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "Get count of resource data",
            notes = "Counts total amount of results that query will return. " +
                    "Can be used as pre-check if paging is need when actual data is loaded.")
    public Long getDataCount(@ApiParam(value = "Name of the resource", required = true)
                             @PathVariable("resource") String resource,
                             @ApiParam(value = "FIQL query filter")
                             @RequestParam(value = "filter", required = false) String filter)
            throws SQLException {
        return service.getCount(resource, filter);
    }

    @RequestMapping(value = "/resources/{resource}", method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "Describes structure of specified resource")
    public List<ApiProperty> getResource(@ApiParam(value = "Name of the resource", required = true)
                                         @PathVariable("resource") String resource) throws SQLException, IOException {
        checkResource(resource);
        return service.listResourceProperties(resource);
    }

    @RequestMapping(value = "/resources", method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "Lists available resource names")
    public Set<String> getResources() throws SQLException, IOException {
        return service.listResources();
    }

    private void checkResource(String resource) throws SQLException {
        if (!service.listResources().contains(resource.toLowerCase())) {
            throw new NotFoundException(String.format("Resource '%s' not found", resource));
        }
    }
}


text:
import logging

from bumps.names import *
from sasmodels import core, bumps_model, sesans
from sasdata.dataloader.loader import Loader

def get_bumps_model(model_name):
    kernel = core.load_model(model_name)
    model = bumps_model.Model(kernel)
    return model

def sesans_fit(file, model, initial_vals={}, custom_params={}, param_range=[],
               acceptance_angle=None):
    """

    @param file: SESANS file location
    @param model: Bumps model object or model name - can be model, model_1 * model_2, and/or model_1 + model_2
    @param initial_vals: dictionary of {param_name : initial_value}
    @param custom_params: dictionary of {custom_parameter_name : Parameter() object}
    @param param_range: dictionary of {parameter_name : [minimum, maximum]}
    @param constraints: dictionary of {parameter_name : constraint}
    @return: FitProblem for Bumps usage
    """
    logging.basicConfig()

    initial_vals['background'] = 0.0
    try:
        loader = Loader()
        data = loader.load(file)[0]
        if data is None:
            raise IOError("Could not load file %r"%(file))

    except Exception:
        raise
        # If no loadable data file, generate random data
        SElength = np.linspace(0, 2400, 61) # [A]
        data = np.ones_like(SElength)
        err_data = np.ones_like(SElength)*0.03

        class Sample:
            zacceptance = 0.1 # [A^-1]
            thickness = 0.2 # [cm]

        class SESANSData1D:
            #q_zmax = 0.23 # [A^-1]
            lam = 0.2 # [nm]
            x = SElength
            y = data
            dy = err_data
            sample = Sample()
            has_no_finite_acceptance = acceptance_angle is not None
        data = SESANSData1D()
        data.acceptance_angle = acceptance_angle

    data.has_no_finite_acceptance = acceptance_angle is not None
    radius = initial_vals.get("radius", 1000)
    data.Rmax = 30*radius # [A]

    if isinstance(model, str):
        model = get_bumps_model(model)

    # Load custom parameters, initial values and parameter ranges
    pars = model.parameters().copy()
    pars.update(custom_params)
    for k, v in custom_params.items():
        if k not in pars:
            par_error("Can't set parameter %r in model"%k, pars)
        setattr(model, k, v)
        model._parameter_names.append(k)
    for k, v in initial_vals.items():
        if k not in pars:
            par_error("Can't get parameter %r from model"%k, pars)
        param = pars[k]
        param.value = v
    for k, v in param_range.items():
        if k not in pars:
            par_error("Can't set range on parameter %r in model"%k, pars)
        param = pars[k]
        param.range(*v)

    if False: # for future implementation
        M_sesans = bumps_model.Experiment(data=data, model=model)
        M_sans = bumps_model.Experiment(data=sans_data, model=model)
        problem = FitProblem([M_sesans, M_sans])
    else:
        M_sesans = bumps_model.Experiment(data=data, model=model)
        problem = FitProblem(M_sesans)
    return problem

def par_error(msg, pars):
    raise ValueError(msg+"\nAvailable parameters: %s"%", ".join(sorted(pars.keys())))


text:
package main

import (
	"fmt"
	"log"
	"math/rand"
	"os"
	"strings"
	"time"

	"github.com/bcho/bearychat.go"
)

type Config struct {
	rtmToken string
	victims  []string
}

func (c Config) isVictimUID(uid string) bool {
	for _, victimUID := range c.victims {
		if victimUID == uid {
			return true
		}
	}
	return false
}

func (c Config) randomVictim() string {
	return c.victims[rand.Intn(len(c.victims))]
}

func (c Config) insultMessage(user *bearychat.User) bearychat.RTMMessage {
	messages := []string{
		fmt.Sprintf("hi %s", user.Name),
		fmt.Sprintf("hey %s, are you chill?", user.Name),
		fmt.Sprintf("苟利国家生死以,岂因祸福避趋之,%s 识得唔识得啊?", user.Name),
	}

	return bearychat.RTMMessage{
		"type":        bearychat.RTMMessageTypeP2PMessage,
		"vchannel_id": user.VChannelId,
		"to_uid":      user.Id,
		"text":        messages[rand.Intn(len(messages))],
		"call_id":     rand.Int(), // FIXME `call_id` sequence generator
		"refer_key":   nil,
	}
}

func main() {
	config := mustLoadConfigFromEnv()

	rtmClient, err := bearychat.NewRTMClient(config.rtmToken)
	checkErr(err)

	user, wsHost, err := rtmClient.Start()
	checkErr(err)

	rtmLoop, err := bearychat.NewRTMLoop(wsHost)
	checkErr(err)

	checkErr(rtmLoop.Start())
	defer rtmLoop.Stop()

	go rtmLoop.Keepalive(time.NewTicker(2 * time.Second))

	errC := rtmLoop.ErrC()
	messageC, err := rtmLoop.ReadC()
	checkErr(err)

	tickTock := time.NewTicker(15 * time.Second)
	defer tickTock.Stop()

	for {
		select {
		case err := <-errC:
			checkErr(err)
			return
		case message := <-messageC:
			if !message.IsChatMessage() {
				continue
			}
			if !message.IsP2P() {
				continue
			}
			if message.IsFromMe(*user) {
				continue
			}
			uid := message["uid"].(string)
			if !config.isVictimUID(uid) {
				continue
			}

			log.Printf("user %s said: %s", uid, message["text"])

			checkErr(rtmLoop.Send(message.Refer("🙊")))
		case <-tickTock.C:
			user, err := rtmClient.User.Info(config.randomVictim())
			checkErr(err)

			log.Printf("insulting user %s", user.Name)
			checkErr(rtmLoop.Send(config.insultMessage(user)))
		}
	}
}

func mustLoadConfigFromEnv() (config Config) {
	config.rtmToken = os.Getenv("CM_RTM_TOKEN")
	if config.rtmToken == "" {
		log.Fatalf("`CM_RTM_TOKEN` is required!")
		return
	}

	svictims := os.Getenv("CM_VICTIMS")
	if svictims == "" {
		log.Fatalf("`CM_VICTIMS` is required!")
		return
	}

	config.victims = strings.Split(svictims, ",")
	if len(config.victims) == 0 {
		log.Fatalf("`CM_VICTIMS` is required!")
		return
	}

	return
}

func checkErr(err error) {
	if err != nil {
		log.Fatal(err)
	}
}


text:
def extractGrabbytalesCom(item):
	'''
	Parser for 'grabbytales.com'
	'''

	vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
	if not (chp or vol) or "preview" in item['title'].lower():
		return None

	tagmap = [
		('The Rise of Phoenixes',       'The Rise of Phoenixes',                      'translated'),
		('PRC',       'PRC',                      'translated'),
		('Loiterous', 'Loiterous',                'oel'),
	]

	for tagname, name, tl_type in tagmap:
		if tagname in item['tags']:
			return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)

	return False


text:
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using System.Collections;

namespace UIWidgets {
	/// <summary>
	/// OnDragListener.
	/// </summary>
	public class OnDragListener : MonoBehaviour, IDragHandler {

		/// <summary>
		/// OnDragEvent.
		/// </summary>
		[SerializeField]
		public PointerUnityEvent OnDragEvent = new PointerUnityEvent();

		/// <summary>
		/// Raises the OnDragEvent.
		/// </summary>
		/// <param name="eventData">Event data.</param>
		public virtual void OnDrag(PointerEventData eventData)
		{
			OnDragEvent.Invoke(eventData);
		}
	}
}