text:
LOG_FILE="digicert_express_install.log"

function dc_log {
    echo $1 | tee -a ${LOG_FILE}
}

function cent_is_package_installed {
  if yum list installed "$@" >/dev/null 2>&1; then
    return 0
  else
    return 1
  fi
}

dc_log
dc_log "DigiCert Express Install Bootstrapper"
dc_log

CHECK_INSTALL_PACKAGES=""
DIGICERT_PYTHON_PACKAGES="digicert-client digicert-express"
CHECK_PYTHON_PACKAGES="python-augeas"
touch ${LOG_FILE}
start_date=`date`
dc_log "${start_date}"

read -p "I agree to the terms & conditions at: https://www.digicert.com/docs/agreements/DigiCert_SA.pdf [y/N] " REPLY
if ! [[ "$REPLY" = "y" || "$REPLY" = "Y" || "$REPLY" = "Yes" || "$REPLY" = "yes" || "$REPLY" = "YES" ]]; then
    dc_log "You must accept the terms & conditions to use this program"
    exit
fi

# check for distribution, debian, centos, ubuntu
if [ -f /etc/lsb-release ]
then
        os=$(lsb_release -s -d)
elif [ -f /etc/debian_version ]; then
        os="Debian $(cat /etc/debian_version)"
elif [ -f /etc/centos-release ]; then
        os=`cat /etc/centos-release`
elif [ -f /etc/redhat-release ]; then
        os=`cat /etc/redhat-release`
else
        os="$(uname -s) $(uname -r)"
fi
echo "Found OS: ${os}"

# check for wget because CentOS needs it to install pip
if [[ $os == *"CentOS"* ]]
then
    wget --version >> /dev/null 2>&1
    if [ $? -eq 0 ]
    then
        dc_log "Prerequisite package wget is installed, continuing installation."
    else
        pip -V >> /dev/null 2>&1
        if [ $? -eq 127 ]
        then
            dc_log "wget is not installed.  Please install wget by typing: 'sudo yum install wget'"
            exit
        fi
    fi
fi

# check for architecture 32 bit or 64 bit
MACHINE_TYPE=`uname -m`
if [ ${MACHINE_TYPE} = "x86_64" ]; then
    # 64-bit stuff here
    CHECK_INSTALL_PACKAGES="augeas-lenses augeas-tools libaugeas0 openssl"
else
  # 32-bit stuff here
    CHECK_INSTALL_PACKAGES="augeas-lenses augeas-tools:i386 libaugeas0:i386 openssl"
fi

# add argparse to the install list if python < 2.7
PY_VERSION=`python -c 'import sys; print sys.version_info < (2, 7)'`
if [ $PY_VERSION = True ]; then
    CHECK_PYTHON_PACKAGES="$CHECK_PYTHON_PACKAGES argparse"
fi

VERSION=`python -c 'import sys; print sys.version_info < (2, 6)'`

# check for apache version
if [[ $os == *"CentOS"* ]]
then
    APACHE_VERSION=`apachectl -v | grep 'Server version' | cut -d '/' -f 2 | cut -d ' ' -f 1`
    if [[ ! $os =~ "6.5" ]] || [[ $VERSION = True ]] || [[ ! $APACHE_VERSION =~ "2.2" ]]; then
        echo ""
        echo "The requirements to run DigiCert Express Install are Cent OS 6.5 with Python 2.6.x and Apache 2.2.x"
        echo ""
        exit
    fi
else
    APACHE_VERSION=`apachectl -v | grep 'Server version' | cut -d '/' -f 2 | cut -d ' ' -f 1`
    if [[ ! $os =~ "14.04" ]] || [[ $PY_VERSION = True ]] || [[ ! $APACHE_VERSION =~ "2.4" ]]; then
        echo ""
        echo "The requirements to run DigiCert Express Install are Ubuntu 14.04 with Python 2.7.x and Apache 2.4.x"
        echo ""
        exit
    fi
fi

# check for dependencies installed
INSTALL_PACKAGES=""
PACKAGES="augeas openssl augeas-libs mod_ssl"
if [[ $os == *"CentOS"* ]]
then
    for package in $PACKAGES; do
        if cent_is_package_installed $package; then
            dc_log "Prerequisite package $package is already installed."
        else
            INSTALL_PACKAGES="$INSTALL_PACKAGES $package"
            install_cmd="yum"
        fi
    done
else
    for package in $CHECK_INSTALL_PACKAGES; do
        if dpkg --get-selections | grep -q "^$package[[:space:]]*install$" >> ${LOG_FILE}; then
            dc_log "Prerequisite package $package is already installed."
        else
            INSTALL_PACKAGES="$INSTALL_PACKAGES $package"
            install_cmd="apt-get"
        fi
    done
fi

# check for python-pip dependency
if [[ $os == *"CentOS"* ]]; then
    pip -V >> /dev/null 2>&1
    if [ $? -eq 127 ]
    then
        dc_log "Python PIP package needs to be installed."
        dc_log "Downloading PIP install script to /tmp"
        wget --no-check-certificate --directory-prefix=/tmp https://bootstrap.pypa.io/get-pip.py >> ${LOG_FILE} 2>&1

        dc_log "Installing PIP package from install script."
        sudo python /tmp/get-pip.py >> ${LOG_FILE} 2>&1
    else
        dc_log "Prerequisite python-pip package is already installed."
    fi
else
    if [ "dpkg-query -W python-pip | awk {'print $1'} = """ ]; then
        dc_log "Updating repository."
        sudo apt-get update >> ${LOG_FILE} 2>&1

        dc_log "Python PIP package needs to be installed.  Installing PIP now from repository."
        sudo apt-get install -q -y python-pip >> ${LOG_FILE} 2>&1
    fi
fi

# check for python dependency modules
PYTHON_PACKAGES=""
for package in $CHECK_PYTHON_PACKAGES; do
    installed_package=`pip list | grep $package | cut -c -${#package}`
    if [ "$installed_package" = "$package" ]; then
        dc_log "Prerequisite Python package $package is already installed."
    else
        PYTHON_PACKAGES="$PYTHON_PACKAGES $package"
    fi
done

MISSING_DIGICERT_PYTHON_PACKAGES=""
for package in $DIGICERT_PYTHON_PACKAGES; do
    installed_package=`pip list | grep $package | cut -c -${#package}`
    if [ "$installed_package" = "$package" ]; then
        dc_log "Prerequisite Python package $package is already installed."
    else
        MISSING_DIGICERT_PYTHON_PACKAGES="$MISSING_DIGICERT_PYTHON_PACKAGES $package"
    fi
done

# show what needs to be installed
if ! [ "$INSTALL_PACKAGES" = "" ]; then
    dc_log "The following system packages need to be installed: $INSTALL_PACKAGES"
fi
if ! [ "$PYTHON_PACKAGES" = "" ]; then
    dc_log "The following Python packages need to be installed: $PYTHON_PACKAGES"
fi
if ! [ "$MISSING_DIGICERT_PYTHON_PACKAGES" = "" ]; then
    dc_log "The following DigiCert packages need to be installed: $MISSING_DIGICERT_PYTHON_PACKAGES"
fi

# install the dependencies
if ! [[ "$INSTALL_PACKAGES" = "" && "$PYTHON_PACKAGES" = "" && $MISSING_DIGICERT_PYTHON_PACKAGES = "" ]]; then
    read -p "Do you wish to install these packages? [Y/n] " REPLY
    if ! [ "$REPLY" = "n" ]; then
        if ! [ "$INSTALL_PACKAGES" = "" ]; then
            dc_log "Installing packages...$INSTALL_PACKAGES. Please wait."
            sudo $install_cmd -q -y install $INSTALL_PACKAGES >> ${LOG_FILE} 2>&1
            if [ $? -ne 0 ]; then
                dc_log "Installation of package $package failed - aborting."
                exit
            fi
        fi
        if ! [ "$PYTHON_PACKAGES" = "" ]; then
            dc_log "Installing modules...$PYTHON_PACKAGES. Please wait."
            sudo pip install $PYTHON_PACKAGES >> ${LOG_FILE} 2>&1
            if [ $? -ne 0 ]; then
                dc_log "Installation of package $package failed - aborting."
                exit
            fi
        fi
        if ! [ "$MISSING_DIGICERT_PYTHON_PACKAGES" = "" ]; then
            dc_log "Installing modules...$MISSING_DIGICERT_PYTHON_PACKAGES. Please wait."
            sudo pip install --pre <?php echo $pypiSource ?> $MISSING_DIGICERT_PYTHON_PACKAGES >> ${LOG_FILE} 2>&1
            if [ $? -ne 0 ]; then
                dc_log "Installation of package $package failed - aborting."
                exit
            fi
        fi
        dc_log "All prerequisite packages have been installed."
    else
        dc_log "Aborting installation."
        exit
    fi
fi

# create a link so we can be run from the CLI
LINK_PATH="`pip show digicert-express | grep Location | cut -d ':' -f 2 | tr -d '[[:space:]]'`/digicert_express/express_install.py"
if [ -e "$LINK_PATH" ]; then
    if [[ $os == *"CentOS"* ]]
    then
        LINK_DIR="/usr/sbin/express_install"
    else
        LINK_DIR="/usr/local/bin/express_install"
    fi

    dc_log "Adding links to run DigiCert Express Install in ${LINK_DIR}"
    sudo ln -s "$LINK_PATH" "$LINK_DIR"
    sudo chmod 755 "$LINK_PATH"
	dc_log ""
	dc_log "DigiCert Express Install has been installed on your system."
	dc_log "As root, run 'express_install all' to install your certificate,"
	dc_log "or 'express_install --help' for more information."
	dc_log ""
fi

# DYNAMIC STUFF
# order details
DOMAIN=""
DOMAIN_PATH=`echo "$DOMAIN" | sed -e "s/\./_/g"`
FILEPATH="/etc/digicert/$DOMAIN_PATH"
ORDER=""
CERTIFICATE=""
CERTIFICATE_CHAIN=""
SUB=""

if ! [[ "$DOMAIN" = "" || "$ORDER" = "" ]]; then
    if ! [[ "$CERTIFICATE" = "" || "$CERTIFICATE_CHAIN" = "" ]]; then
        sudo mkdir -p "$FILEPATH"
        CERT_NAME=`echo "$DOMAIN" | sed -e "s/\./_/g"`

        # write the certificate to file
        dc_log "Copying certificate file to $FILEPATH/$CERT_NAME.crt"
        echo "$CERTIFICATE" | sudo tee "$FILEPATH/$CERT_NAME.crt" > /dev/null

        dc_log "Copying certificate chain file to $FILEPATH/DigiCertCA.crt"
        echo "$CERTIFICATE_CHAIN" | sudo tee "$FILEPATH/DigiCertCA.crt" > /dev/null
    fi

    # run express install
    dc_log "running: sudo express_install all --domain \"$DOMAIN\" --order_id \"$ORDER\""
    sudo express_install all --domain "$DOMAIN" --order_id "$ORDER" --sub_id "$SUB"

else
    dc_log "ERROR: You are missing your domain name or order id, please contact digicert support"
fi

dc_log
dc_log
dc_log "DigiCert Express Install Finished"
end_date=`date`
dc_log "${end_date}"


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:orientation="vertical">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="5dp">

        <TextView
            android:id="@+id/tv_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="嘟嘟嘟"
            android:textColor="@color/black"
            android:textSize="13sp"/>

        <TextView
            android:id="@+id/tv_time"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:textSize="13sp"
            android:textColor="@color/gary"
            android:text="2017年5月18日 11:10:12"/>
    </RelativeLayout>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="5dp"
        android:paddingRight="5dp">

        <TextView
            android:id="@+id/tv_style"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="充值"
            android:textColor="@color/black"
            android:textSize="15sp"/>

        <TextView
            android:id="@+id/tv_money"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:textSize="14sp"
            android:textColor="@color/tff7800"
            android:text="+200"/>
    </RelativeLayout>
</LinearLayout>

redpajama_set_name: RedPajamaGithub


text:
layout: api
title: "v2.1.6 JavaScript Library: L.mapbox.legendControl(options)"
categories: api
version: v2.1.6
permalink: /api/v2.1.6/l-mapbox-legendcontrol
---

L.mapbox.legendControl(options)

Extends: L.Control

A map control that shows legends added to maps in Mapbox. Legends are auto-detected from active layers.

Options
Value
Description

options optional
object
An options object. Beyond the default options for map controls, this object has one special parameter: sanitizer: A function that accepts a string, and returns a sanitized result for HTML display. The default will remove dangerous script content, and is recommended.

Example:

var map = L.mapbox.map('map').setView([38, -77], 5);
map.addControl(L.mapbox.legendControl());

Returns: a L.mapbox.legendControl object.

Class: L.mapbox.LegendControl

legendControl.addLegend(legend)

Adds a legend to the legendControl.

Options
Value
Description

legend required
string
A string which may contain HTML. It will be sanitized by the legendControl's sanitizer option.

legendControl.removeLegend(legend)

Removes a legend from the legendControl.

Options
Value
Description

legend required
string
legend data to remove.


text:
The project demonstrates how you can easily build single page applications (SPA) using [node.js](http://nodejs.org/download/) with Express, Jade templates and geared with ServiceStack as a backend API engine. The application works for Windows and Linuxes. To simplify development node.js used a proxy to route all "/api" requests to SericeStack but for heavy loaded sites you can use [nginx](http://wiki.nginx.org/Main).

## Instructions

Make sure that [node.js and npm](http://nodejs.org/download/) is installed and path variables are set correctly (`Windows`: install it with `.msi`, `Linux/Mac`: use [install](https://github.com/ServiceStack/ServiceStack.UseCases/blob/master/NodeStackProxy/install) script or read [how-to-install-nodejs](http://howtonode.org/how-to-install-nodejs) )

Both commands should return version:

```
node --version
v0.10.2

npm --version
1.2.15
```

[Site](https://github.com/ServiceStack/ServiceStack.UseCases/tree/master/NodeStackProxy/Service) has a dependency on [Redis](http://redis.io/download). Make sure that it's installed locally and listening port 6379. If you have Redis on another server then just change it in [app.config](https://github.com/ServiceStack/ServiceStack.UseCases/blob/master/NodeStackProxy/Service/app.config#L5).

### Windows

[run.cmd](https://github.com/ServiceStack/ServiceStack.UseCases/blob/master/NodeStackProxy/run.cmd) builds Service.csproj and executes `Service/bin/Debug/Service.exe` you have to see the following console:

```
Listening: http://*:8090/api/
Press any key to stop program
```

Then script download `node-modules` for node.js and runs the server for port: `8080`.

That's it, you can see Backbone.JS Todo SPA geared with [ServiceStack](www.servicestack.net): [http://localhost:8080](http://localhost:8080)

NOTE: Service is actually a Windows Service. So you can also install it with:

```
installutil <Path of the Service.exe>
```

### Linux & mono

[run](https://github.com/ServiceStack/ServiceStack.UseCases/blob/master/NodeStackProxy/run) script automatically compiles Service.sln file using `xbuild`. Then it tries to shutdown the previous Service process and run it again. When service is up and running, it downloads all required `node-modules` and runs `node.js` app server using port: `8080`.

```
chmod +x ./run
./run
```

That's it, you can see Backbone.JS Todo SPA geared with [ServiceStack](www.servicestack.net): `http://[linux-host]:8080`


text:
#ifndef B2_WORLD_CALLBACKS_H
#define B2_WORLD_CALLBACKS_H

#include <Box2D/Common/b2Settings.h>

struct b2Vec2;
struct b2Transform;
class b2Fixture;
class b2Body;
class b2Joint;
class b2Contact;
class b2ParticleSystem;
struct b2ContactResult;
struct b2Manifold;
class b2ParticleGroup;
struct b2ParticleBodyContact;
struct b2ParticleContact;

/// Joints and fixtures are destroyed when their associated
/// body is destroyed. Implement this listener so that you
/// may nullify references to these joints and shapes.
class b2DestructionListener
{
public:
	virtual ~b2DestructionListener() {}

	/// Called when any joint is about to be destroyed due
	/// to the destruction of one of its attached bodies.
	virtual void SayGoodbye(b2Joint* joint) = 0;

	/// Called when any fixture is about to be destroyed due
	/// to the destruction of its parent body.
	virtual void SayGoodbye(b2Fixture* fixture) = 0;

	/// Called when any particle group is about to be destroyed.
	virtual void SayGoodbye(b2ParticleGroup* group)
	{
		B2_NOT_USED(group);
	}

	/// Called when a particle is about to be destroyed.
	/// The index can be used in conjunction with
	/// b2ParticleSystem::GetUserDataBuffer() or
	/// b2ParticleSystem::GetParticleHandleFromIndex() to determine which
	/// particle has been destroyed.
	virtual void SayGoodbye(b2ParticleSystem* particleSystem, int32 index)
	{
		B2_NOT_USED(particleSystem);
		B2_NOT_USED(index);
	}
};

/// Implement this class to provide collision filtering. In other words, you can implement
/// this class if you want finer control over contact creation.
class b2ContactFilter
{
public:
	virtual ~b2ContactFilter() {}

	/// Return true if contact calculations should be performed between these two shapes.
	/// @warning for performance reasons this is only called when the AABBs begin to overlap.
	virtual bool ShouldCollide(b2Fixture* fixtureA, b2Fixture* fixtureB);

	/// Return true if contact calculations should be performed between a
	/// fixture and particle.  This is only called if the
	/// b2_fixtureContactListenerParticle flag is set on the particle.
	virtual bool ShouldCollide(b2Fixture* fixture,
							   b2ParticleSystem* particleSystem,
							   int32 particleIndex)
	{
		B2_NOT_USED(fixture);
		B2_NOT_USED(particleIndex);
		B2_NOT_USED(particleSystem);
		return true;
	}

	/// Return true if contact calculations should be performed between two
	/// particles.  This is only called if the
	/// b2_particleContactListenerParticle flag is set on the particle.
	virtual bool ShouldCollide(b2ParticleSystem* particleSystem,
							   int32 particleIndexA, int32 particleIndexB)
	{
		B2_NOT_USED(particleSystem);
		B2_NOT_USED(particleIndexA);
		B2_NOT_USED(particleIndexB);
		return true;
	}
};

/// Contact impulses for reporting. Impulses are used instead of forces because
/// sub-step forces may approach infinity for rigid body collisions. These
/// match up one-to-one with the contact points in b2Manifold.
struct b2ContactImpulse
{
	float32 normalImpulses[b2_maxManifoldPoints];
	float32 tangentImpulses[b2_maxManifoldPoints];
	int32 count;
};

/// Implement this class to get contact information. You can use these results for
/// things like sounds and game logic. You can also get contact results by
/// traversing the contact lists after the time step. However, you might miss
/// some contacts because continuous physics leads to sub-stepping.
/// Additionally you may receive multiple callbacks for the same contact in a
/// single time step.
/// You should strive to make your callbacks efficient because there may be
/// many callbacks per time step.
/// @warning You cannot create/destroy Box2D entities inside these callbacks.
class b2ContactListener
{
public:
	virtual ~b2ContactListener() {}

	/// Called when two fixtures begin to touch.
	virtual void BeginContact(b2Contact* contact) { B2_NOT_USED(contact); }

	/// Called when two fixtures cease to touch.
	virtual void EndContact(b2Contact* contact) { B2_NOT_USED(contact); }

	/// Called when a fixture and particle start touching if the
	/// b2_fixtureContactFilterParticle flag is set on the particle.
	virtual void BeginContact(b2ParticleSystem* particleSystem,
							  b2ParticleBodyContact* particleBodyContact)
	{
		B2_NOT_USED(particleSystem);
		B2_NOT_USED(particleBodyContact);
	}

	/// Called when a fixture and particle stop touching if the
	/// b2_fixtureContactFilterParticle flag is set on the particle.
	virtual void EndContact(b2Fixture* fixture,
							b2ParticleSystem* particleSystem, int32 index)
	{
		B2_NOT_USED(fixture);
		B2_NOT_USED(particleSystem);
		B2_NOT_USED(index);
	}

	/// Called when two particles start touching if
	/// b2_particleContactFilterParticle flag is set on either particle.
	virtual void BeginContact(b2ParticleSystem* particleSystem,
							  b2ParticleContact* particleContact)
	{
		B2_NOT_USED(particleSystem);
		B2_NOT_USED(particleContact);
	}

	/// Called when two particles start touching if
	/// b2_particleContactFilterParticle flag is set on either particle.
	virtual void EndContact(b2ParticleSystem* particleSystem,
							int32 indexA, int32 indexB)
	{
		B2_NOT_USED(particleSystem);
		B2_NOT_USED(indexA);
		B2_NOT_USED(indexB);
	}

	/// This is called after a contact is updated. This allows you to inspect a
	/// contact before it goes to the solver. If you are careful, you can modify the
	/// contact manifold (e.g. disable contact).
	/// A copy of the old manifold is provided so that you can detect changes.
	/// Note: this is called only for awake bodies.
	/// Note: this is called even when the number of contact points is zero.
	/// Note: this is not called for sensors.
	/// Note: if you set the number of contact points to zero, you will not
	/// get an EndContact callback. However, you may get a BeginContact callback
	/// the next step.
	virtual void PreSolve(b2Contact* contact, const b2Manifold* oldManifold)
	{
		B2_NOT_USED(contact);
		B2_NOT_USED(oldManifold);
	}

	/// This lets you inspect a contact after the solver is finished. This is useful
	/// for inspecting impulses.
	/// Note: the contact manifold does not include time of impact impulses, which can be
	/// arbitrarily large if the sub-step is small. Hence the impulse is provided explicitly
	/// in a separate data structure.
	/// Note: this is only called for contacts that are touching, solid, and awake.
	virtual void PostSolve(b2Contact* contact, const b2ContactImpulse* impulse)
	{
		B2_NOT_USED(contact);
		B2_NOT_USED(impulse);
	}
};

/// Callback class for AABB queries.
/// See b2World::Query
class b2QueryCallback
{
public:
	virtual ~b2QueryCallback() {}

	/// Called for each fixture found in the query AABB.
	/// @return false to terminate the query.
	virtual bool ReportFixture(b2Fixture* fixture) = 0;

	/// Called for each particle found in the query AABB.
	/// @return false to terminate the query.
	virtual bool ReportParticle(const b2ParticleSystem* particleSystem,
								int32 index)
	{
		B2_NOT_USED(particleSystem);
		B2_NOT_USED(index);
		return false;
	}

	/// Cull an entire particle system from b2World::QueryAABB. Ignored for
	/// b2ParticleSystem::QueryAABB.
	/// @return true if you want to include particleSystem in the AABB query,
	/// or false to cull particleSystem from the AABB query.
	virtual bool ShouldQueryParticleSystem(
		const b2ParticleSystem* particleSystem)
	{
		B2_NOT_USED(particleSystem);
		return true;
	}
};

/// Callback class for ray casts.
/// See b2World::RayCast
class b2RayCastCallback
{
public:
	virtual ~b2RayCastCallback() {}

	/// Called for each fixture found in the query. You control how the ray cast
	/// proceeds by returning a float:
	/// return -1: ignore this fixture and continue
	/// return 0: terminate the ray cast
	/// return fraction: clip the ray to this point
	/// return 1: don't clip the ray and continue
	/// @param fixture the fixture hit by the ray
	/// @param point the point of initial intersection
	/// @param normal the normal vector at the point of intersection
	/// @return -1 to filter, 0 to terminate, fraction to clip the ray for
	/// closest hit, 1 to continue
	virtual float32 ReportFixture(	b2Fixture* fixture, const b2Vec2& point,
									const b2Vec2& normal, float32 fraction) = 0;

	/// Called for each particle found in the query. You control how the ray
	/// cast proceeds by returning a float:
	/// return <=0: ignore the remaining particles in this particle system
	/// return fraction: ignore particles that are 'fraction' percent farther
	///   along the line from 'point1' to 'point2'. Note that 'point1' and
	///   'point2' are parameters to b2World::RayCast.
	/// @param particleSystem the particle system containing the particle
	/// @param index the index of the particle in particleSystem
	/// @param point the point of intersection bt the ray and the particle
	/// @param normal the normal vector at the point of intersection
	/// @param fraction percent (0.0~1.0) from 'point0' to 'point1' along the
	///   ray. Note that 'point1' and 'point2' are parameters to
	///   b2World::RayCast.
	/// @return <=0 to ignore rest of particle system, fraction to ignore
	/// particles that are farther away.
	virtual float32 ReportParticle(const b2ParticleSystem* particleSystem,
								   int32 index, const b2Vec2& point,
								   const b2Vec2& normal, float32 fraction)
	{
		B2_NOT_USED(particleSystem);
		B2_NOT_USED(index);
		B2_NOT_USED(&point);
		B2_NOT_USED(&normal);
		B2_NOT_USED(fraction);
		return 0;
	}

	/// Cull an entire particle system from b2World::RayCast. Ignored in
	/// b2ParticleSystem::RayCast.
	/// @return true if you want to include particleSystem in the RayCast, or
	/// false to cull particleSystem from the RayCast.
	virtual bool ShouldQueryParticleSystem(
		const b2ParticleSystem* particleSystem)
	{
		B2_NOT_USED(particleSystem);
		return true;
	}
};

#endif


text:
require 'formula'

class Libffi < Formula
  homepage 'http://sourceware.org/libffi/'
  url 'http://mirrors.kernel.org/sources.redhat.com/libffi/libffi-3.0.13.tar.gz'
  mirror 'ftp://sourceware.org/pub/libffi/libffi-3.0.13.tar.gz'
  sha1 'f5230890dc0be42fb5c58fbf793da253155de106'

  bottle do
    cellar :any
    sha1 "b6a9696c2a58f34f37cf2bca5a652ee6982c3c14" => :mavericks
    sha1 "421a0108078e79a1e32ccebea8eeadce0d0533db" => :mountain_lion
    sha1 "c2ad5c7f63e06566494d92baa1e31c0c2190ea05" => :lion
  end

  keg_only :provided_by_osx, "Some formulae require a newer version of libffi."

  def install
    ENV.deparallelize # https://github.com/Homebrew/homebrew/pull/19267
    ENV.universal_binary
    system "./configure", "--disable-debug", "--disable-dependency-tracking",
                          "--prefix=#{prefix}"
    system "make install"
  end

  test do
    (testpath/'closure.c').write <<-TEST_SCRIPT.undent
     #include <stdio.h>
     #include <ffi.h>

     /* Acts like puts with the file given at time of enclosure. */
     void puts_binding(ffi_cif *cif, unsigned int *ret, void* args[],
                       FILE *stream)
     {
       *ret = fputs(*(char **)args[0], stream);
     }

     int main()
     {
       ffi_cif cif;
       ffi_type *args[1];
       ffi_closure *closure;

       int (*bound_puts)(char *);
       int rc;

       /* Allocate closure and bound_puts */
       closure = ffi_closure_alloc(sizeof(ffi_closure), &bound_puts);

       if (closure)
         {
           /* Initialize the argument info vectors */
           args[0] = &ffi_type_pointer;

           /* Initialize the cif */
           if (ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1,
                            &ffi_type_uint, args) == FFI_OK)
             {
               /* Initialize the closure, setting stream to stdout */
               if (ffi_prep_closure_loc(closure, &cif, puts_binding,
                                        stdout, bound_puts) == FFI_OK)
                 {
                   rc = bound_puts("Hello World!");
                   /* rc now holds the result of the call to fputs */
                 }
             }
         }

       /* Deallocate both closure, and bound_puts */
       ffi_closure_free(closure);

       return 0;
     }
    TEST_SCRIPT

    flags = ["-L#{lib}", "-lffi", "-I#{lib}/libffi-#{version}/include"]
    system ENV.cc, "-o", "closure", "closure.c", *(flags + ENV.cflags.split)
    system "./closure"
  end
end


text:
"""Database backed models for the asset store."""

import json
import re
import six

from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import Column, Integer, JSON, String
from sqlalchemy.exc import IntegrityError
from sqlalchemy_utils import ChoiceType

from asset_store.utils import get_choice_list, ResourceConflictError, ValidationError, validate_choice

db = SQLAlchemy()

class Asset(db.Model):
    """A model for tracking satellite and antenna assets."""

    # TODO: consider using enums
    # types
    ANTENNA = 'antenna'
    SATELLITE = 'satellite'

    ASSET_TYPES = [(SATELLITE, 'satellite'),
                   (ANTENNA, 'antenna')]

    # type specific classes
    DISH = 'dish'
    YAGI = 'yagi'

    ANTENNA_CLASSES = [(DISH, 'dish'),
                       (YAGI, 'yagi')]

    DOVE = 'dove'
    RAPIDEYE = 'rapideye'
    SATELLITE_CLASSES = [(DOVE, 'dove'),
                         (RAPIDEYE, 'rapideye')]

    # all classes
    ASSET_CLASSES = ANTENNA_CLASSES + SATELLITE_CLASSES

    # supported keys in the asset_details json blob for dish assets
    DIAMETER = 'diameter'
    RADOME = 'radome'
    DISH_DETAILS = [DIAMETER, RADOME]

    # supported keys in the asset_details json blob for yagi assets
    GAIN = 'gain'
    YAGI_DETAILS = [GAIN]

    # model fields
    id = Column(Integer, primary_key=True)
    asset_name = Column(String(64), nullable=False, unique=True)
    asset_type = Column(ChoiceType(ASSET_TYPES), nullable=False)
    asset_class = Column(ChoiceType(ASSET_CLASSES), nullable=False)
    # store details as a string for now -- consider using a JSON column (requires a sqlite extension)
    asset_details_json = Column(String)

    @property
    def asset_details(self):
        """Dict of asset details."""
        if self.asset_details_json:
            return json.loads(self.asset_details_json)
        else:
            return {}

    def update_details(self, new_details):
        """Validate and update asset_details for an asset."""
        if not isinstance(new_details, dict):
            raise ValidationError('Asset details should be a dict.')
        self._validate_asset_details_for_asset_class(new_details, self.asset_class.value)
        self.asset_details_json = json.dumps(new_details)
        db.session.add(self)
        db.session.commit()

    @classmethod
    def create_asset(cls, asset_name, asset_type, asset_class, asset_details=None):
        """Create a new instance of an Asset.

        Args:
            asset_name (string): name of the new asset. Must meet the following constraints:
                                    1. must start with an alphanumeric character
                                    2. can only contain alphanumeric characters, dashses, and underscores
                                    3. can be no longer than 64 characters
                                    4. can be no shorter than 4 characters
                                    5. can not already be used as an existing asset's asset_name
            asset_type (string): the type of asset. Valid types are 'satellite' and 'antenna'
            asset_class (string): the class of the asset. Valid classes depend on the asset_type.
                                      - Valid classes for 'satellite' asset_type are 'dove' and 'rapideye'
                                      - Valid classes for 'antenna' asset_type are 'dish' and 'yagi'
        Returns:
            asset: a newly created Asset instance
        Raises:
            ValidationError: the provided arguments do not meet validation constraints
            IntegrityError
        """
        from run import app
        cls._validate_asset_name(asset_name)
        cls._validate_asset_type(asset_type)
        cls._validate_asset_class(asset_class)
        cls._validate_asset_class_with_asset_type(asset_class, asset_type)

        if not asset_details:
            asset_details = {}
        else:
            cls._validate_asset_details_for_asset_class(asset_details, asset_class)

        with app.app_context():
            try:
                asset = Asset(asset_name=asset_name,
                              asset_type=asset_type,
                              asset_class=asset_class,
                              asset_details_json=json.dumps(asset_details))
                db.session.add(asset)
                db.session.commit()
                return asset
            except IntegrityError as err:
                if 'UNIQUE constraint failed: asset.asset_name' in '{}'.format(err):
                    raise ResourceConflictError('There is already an asset with asset_name {}'.format(asset_name))

    # The following methods are for validating asset fields.
    # To better enforce some of the business rules, additional database constraints could be added in the future.

    @classmethod
    def _validate_asset_type(cls, asset_type):
        """Check if an asset_type value is valid.

        Args:
            asset_type (str): value representing an asset_type to be validated
        Returns:
            valid (bool): True if validation passed
        Raises:
            ValidationError: if provided asset_type value is not a valid choice
        """
        return validate_choice('asset_type', asset_type, cls.ASSET_TYPES)

    @classmethod
    def _validate_asset_class(cls, asset_class):
        """Check if an asset_type value is valid.

        Args:
            asset_class (str): value representing an asset_class to be validated
        Returns:
            valid (bool): True if validation passed
        Raises:
            ValidationError: if provided asset_class value is not a valid choice
        """
        return validate_choice('asset_class', asset_class, cls.ASSET_CLASSES)

    @classmethod
    def _validate_asset_class_with_asset_type(cls, asset_class, asset_type):
        """Check if an asset_class value is valid for a given asset_type.

        Args:
            asset_type (str): value representing an asset_type to be validated
            asset_class (str): value representing an asset_class to be validated
        Returns:
            valid (bool): True if validation passed
        Raises:
            ValidationError: if provided asset_class value is not a valid choice given the provided asset_type
        """
        error_msg = 'Invalid asset_class. For the {} asset_type, valid asset_class values are: {}'
        if asset_type == cls.ANTENNA:
            choices = get_choice_list(cls.ANTENNA_CLASSES)
            error_msg = error_msg.format(cls.ANTENNA, choices)
            return validate_choice('asset_class', asset_class, cls.ANTENNA_CLASSES,
                                   custom_error_msg=error_msg)
        elif asset_type == cls.SATELLITE:
            choices = get_choice_list(cls.SATELLITE_CLASSES)
            error_msg = error_msg.format(cls.SATELLITE, choices)
            return validate_choice('asset_class', asset_class, cls.SATELLITE_CLASSES,
                                   custom_error_msg=error_msg)
        else:
            raise ValidationError('Unrecognized asset_type {}'.format(asset_type))

    @classmethod
    def _validate_asset_name(cls, asset_name):
        """Check if an asset_name value is valid.

        Args:
            asset_name (str): value representing an asset_name to be validated
        Returns:
            valid (bool): True if validation passed
        Raises:
            ValidationError: if provided asset_name has one of the following issues:
                - is shorter than 4 characters
                - is longer than 64 characters
                - has already used by another asset
                - starts with a '-' or '_'
        """
        if not isinstance(asset_name, six.string_types):
            raise ValidationError('asset_name must be a string.')

        length = len(asset_name)
        if length < 4:
            raise ValidationError('asset_name must be at least 4 characters in length.')
        if length > 64:
            raise ValidationError('asset_name must be at most 64 characters in length.')

        first_char = asset_name[0]
        if first_char in ['-', '_']:
            raise ValidationError('asset_name cannot begin with an underscore or dash.')

        # should start with an alphanum and all subsequent characters should be alphanum or dashes
        if re.match('^[0-9a-zA-Z]+[0-9a-zA-Z_-]*$', asset_name) is None:
            raise ValidationError('asset_name may only contain alphanumeric ascii characters, underscores, and dashes.')

        return True

    @classmethod
    def _get_asset_details_dict(cls, asset_details):
        try:
            details = json.loads(asset_details)
            if not isinstance(details, dict):
                raise ValidationError('asset_details should be a json object.')
            return True
        except:
            raise ValidationError('asset_details should be a json object.')

    @classmethod
    def _check_for_unknown_asset_details_keys(cls, asset_details, asset_class):
        """Make sure details keys are supported."""
        allowed_keys = []
        if asset_class == cls.DISH:
            allowed_keys = cls.DISH_DETAILS
        if asset_class == cls.YAGI:
            allowed_keys = cls.YAGI_DETAILS

        keys = asset_details.keys()
        for key in keys:
            if key not in allowed_keys:
                key_error_msg = 'key {} in asset_details is not supported for asset_class {}. allowed keys are: {}'
                raise ValidationError(key_error_msg.format(key, asset_class, allowed_keys))

    @classmethod
    def _validate_float_key(cls, name, value):
        try:
            float(value)
        except ValueError:
            raise ValidationError('{} in asset_details should have a float value'.format(name))

    @classmethod
    def _validate_asset_details_for_asset_class(cls, asset_details, asset_class):
        """Make sure that the asset_details follow business roles for the provided asset_class.

        - asset_class dish can have diameter and radome details
        - asset_class yagi can have gain details
        """
        cls._check_for_unknown_asset_details_keys(asset_details, asset_class)
        for key, value in asset_details.items():
            if key == cls.DIAMETER:
                cls._validate_float_key(key, value)
            elif key == cls.RADOME:
                try:
                    bool(value)
                except ValueError:
                    raise ValidationError('{} in asset_details should have a boolean value'.format(cls.RADOME))
            elif key == cls.GAIN:
                cls._validate_float_key(key, value)


text:
<?php echo $this->lang->line('common_fields_required_message'); ?>

	<fieldset id="receiving_basic_info">
	<?php echo form_open("receivings/save/".$receiving_info['receiving_id'],array('id'=>'recvs_edit_form')); ?>
	<legend><?php echo $this->lang->line("recvs_basic_information"); ?></legend>

	<?php echo form_label($this->lang->line('recvs_receipt_number').':', 'supplier'); ?>

			<?php echo anchor('receivings/receipt/'.$receiving_info['receiving_id'], $this->lang->line('recvs_receipt_number') .$receiving_info['receiving_id'], array('target' => '_blank'));?>

	<?php echo form_label($this->lang->line('recvs_date').':', 'date', array('class'=>'required')); ?>

			<?php echo form_input(array('name'=>'date','value'=>date('m/d/Y', strtotime($receiving_info['receiving_time'])), 'id'=>'date'));?>

	<?php echo form_label($this->lang->line('recvs_supplier').':', 'supplier'); ?>

			<?php echo form_input(array('name' => 'supplier_id', 'value' => $selected_supplier, 'id' => 'supplier_id'));?>

	<?php echo form_label($this->lang->line('recvs_invoice_number').':', 'invoice_number'); ?>

			<?php echo form_input(array('name' => 'invoice_number', 'value' => $receiving_info['invoice_number'], 'id' => 'invoice_number'));?>

	<?php echo form_label($this->lang->line('recvs_employee').':', 'employee'); ?>

			<?php echo form_dropdown('employee_id', $employees, $receiving_info['employee_id'], 'id="employee_id"');?>

	<?php echo form_label($this->lang->line('recvs_comments').':', 'comment'); ?>

			<?php echo form_textarea(array('name'=>'comment','value'=>$receiving_info['comment'],'rows'=>'4','cols'=>'23', 'id'=>'comment'));?>

	<?php
	echo form_submit(array(
		'name'=>'submit',
		'value'=>$this->lang->line('common_submit'),
		'class'=> 'submit_button float_right')
	);
	?>
	</form>

	<?php echo form_open("receivings/delete/".$receiving_info['receiving_id'],array('id'=>'recvs_delete_form')); ?>
		<?php echo form_hidden('receiving_id', $receiving_info['receiving_id']);?>
		<?php
		echo form_submit(array(
			'name'=>'submit',
			'value'=>$this->lang->line('recvs_delete_entire_sale'),
			'class'=>'delete_button float_right')
		);
		?>
	</form>
	</fieldset>


text:
$(document).ready(function () {
            // On récupère la balise
 en question qui contient l'attribut « data-prototype » qui nous intéresse.
            var $container = $('div#qcm_backbundle_question_addedit_questionAnswers');
            // On ajoute un lien pour ajouter une nouvelle catégorie
            var $addLink = $('Ajouter une réponse');
            $container.before($addLink);

            // On ajoute un nouveau champ à chaque clic sur le lien d'ajout.
            $addLink.click(function (e) {
                addAnswer($container);
                $('textarea').ckeditor();
                e.preventDefault(); // évite qu'un # apparaisse dans l'URL
                return false;
            });

            // On définit un compteur unique pour nommer les champs qu'on va ajouter dynamiquement
            var index = $container.find(':input').length;

            // On ajoute un premier champ automatiquement s'il n'en existe pas déjà un (cas d'une nouvelle annonce par exemple).
            if (index === 0) {
                addAnswer($container);
            } else {
                // Pour chaque catégorie déjà existante, on ajoute un lien de suppression
                $container.children('div').each(function () {
                    addDeleteLink($(this));
                });
            }

            // La fonction qui ajoute un formulaire Reponse
            function addAnswer($container) {
                // Dans le contenu de l'attribut « data-prototype », on remplace :
                // - le texte "__name__label__" qu'il contient par le label du champ
                // - le texte "__name__" qu'il contient par le numéro du champ
                var $prototype = $($container.attr('data-prototype').replace(/__name__label__/g, 'Réponse n°' + (index + 1))
                        .replace(/__name__/g, index));
                // On ajoute au prototype un lien pour pouvoir supprimer la catégorie
                addDeleteLink($prototype);

                // On ajoute le prototype modifié à la fin de la balise

                $container.append($prototype);

                // Enfin, on incrémente le compteur pour que le prochain ajout se fasse avec un autre numéro
                index++;
            }

            // La fonction qui ajoute un lien de suppression d'une catégorie
            function addDeleteLink($prototype) {
                // Création du lien
                $deleteLink = $('Supprimer');

                // Ajout du lien
                $prototype.append($deleteLink);

                // Ajout du listener sur le clic du lien
                $deleteLink.click(function (e) {
                    $prototype.remove();
                    e.preventDefault(); // évite qu'un # apparaisse dans l'URL
                    return false;
                });
            }

            $('textarea').ckeditor();
        });


text:
.class final Lcom/htc/net/usbnet/UsbnetInfo$1;
.super Ljava/lang/Object;
.source "UsbnetInfo.java"

# interfaces
.implements Landroid/os/Parcelable$Creator;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/htc/net/usbnet/UsbnetInfo;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x8
    name = null
.end annotation

.annotation system Ldalvik/annotation/Signature;
    value = {
        "Ljava/lang/Object;",
        "Landroid/os/Parcelable$Creator",
        "<",
        "Lcom/htc/net/usbnet/UsbnetInfo;",
        ">;"
    }
.end annotation

# direct methods
.method constructor <init>()V
    .locals 0

    .prologue
    .line 90
    invoke-direct/range {p0 .. p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public createFromParcel(Landroid/os/Parcel;)Lcom/htc/net/usbnet/UsbnetInfo;
    .locals 3
    .parameter "in"

    .prologue
    .line 92
    new-instance v0, Lcom/htc/net/usbnet/UsbnetInfo;

    invoke-direct {v0}, Lcom/htc/net/usbnet/UsbnetInfo;-><init>()V

    .line 93
    .local v0, info:Lcom/htc/net/usbnet/UsbnetInfo;
    invoke-virtual {p1}, Landroid/os/Parcel;->readDouble()D

    move-result-wide v1

    #setter for: Lcom/htc/net/usbnet/UsbnetInfo;->mLinkSpeed:D
    invoke-static {v0, v1, v2}, Lcom/htc/net/usbnet/UsbnetInfo;->access$002(Lcom/htc/net/usbnet/UsbnetInfo;D)D

    .line 94
    invoke-virtual {p1}, Landroid/os/Parcel;->readInt()I

    move-result v1

    #setter for: Lcom/htc/net/usbnet/UsbnetInfo;->mIpAddress:I
    invoke-static {v0, v1}, Lcom/htc/net/usbnet/UsbnetInfo;->access$102(Lcom/htc/net/usbnet/UsbnetInfo;I)I

    .line 95
    invoke-virtual {p1}, Landroid/os/Parcel;->readLong()J

    move-result-wide v1

    #setter for: Lcom/htc/net/usbnet/UsbnetInfo;->mBsMacAddress:J
    invoke-static {v0, v1, v2}, Lcom/htc/net/usbnet/UsbnetInfo;->access$202(Lcom/htc/net/usbnet/UsbnetInfo;J)J

    .line 96
    invoke-virtual {p1}, Landroid/os/Parcel;->readInt()I

    move-result v1

    #setter for: Lcom/htc/net/usbnet/UsbnetInfo;->mNetworkId:I
    invoke-static {v0, v1}, Lcom/htc/net/usbnet/UsbnetInfo;->access$302(Lcom/htc/net/usbnet/UsbnetInfo;I)I

    .line 97
    return-object v0
.end method

.method public bridge synthetic createFromParcel(Landroid/os/Parcel;)Ljava/lang/Object;
    .locals 1
    .parameter "x0"

    .prologue
    .line 90
    invoke-virtual {p0, p1}, Lcom/htc/net/usbnet/UsbnetInfo$1;->createFromParcel(Landroid/os/Parcel;)Lcom/htc/net/usbnet/UsbnetInfo;

    move-result-object v0

    return-object v0
.end method

.method public newArray(I)[Lcom/htc/net/usbnet/UsbnetInfo;
    .locals 1
    .parameter "size"

    .prologue
    .line 101
    new-array v0, p1, [Lcom/htc/net/usbnet/UsbnetInfo;

    return-object v0
.end method

.method public bridge synthetic newArray(I)[Ljava/lang/Object;
    .locals 1
    .parameter "x0"

    .prologue
    .line 90
    invoke-virtual {p0, p1}, Lcom/htc/net/usbnet/UsbnetInfo$1;->newArray(I)[Lcom/htc/net/usbnet/UsbnetInfo;

    move-result-object v0

    return-object v0
.end method


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.fteams.sstrain.android"
    android:versionCode="30"
    android:versionName="1.2.7" >

    <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="23" />

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/GdxTheme" >
        <activity
            android:name="com.fteams.sstrain.android.AndroidLauncher"
            android:label="@string/app_name"
            android:screenOrientation="sensorLandscape"
            android:configChanges="keyboard|keyboardHidden|orientation|screenSize">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


text:
.gitbook-link {
  display: none !important;
}

iframe {
  width: 100%;
  height: 500px;
  border: none;
}

/*maybe add image to sidebar in future*/
/*.book-summary:before {
  position: absolute;
  bottom:200px;
  left:0;
  content: " ";
  background: url(/images/logo.png);
  background-size: 100% 100%;
  width: 100%;
  margin: 2px;
  float: left;
  background-size: cover;
}*/

/*.book .book-summary .expanded > a .exc-trigger:before, .book .book-summary .expanded > span .exc-trigger:before {
  content: "\f0d7" !important;
}
.book .book-summary .exc-trigger:before {
  content: '\f0da' !important;
}*/

.page-inner {
  max-width: 1600px;
}

.navigation-next,
.navigation-prev {
  display: none;
}

img {
  /* text-align: center; */
  display: block;
  margin-left: auto;
  margin-right: auto;
}

tr th {
  background: rgb(61, 84, 103);
  color: white;
}


text:
//
//   Copyright 2016  Cityzen Data
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.
//

package io.warp10.script.functions;

import io.warp10.script.NamedWarpScriptFunction;
import io.warp10.script.WarpScriptException;
import io.warp10.script.WarpScriptStack;
import io.warp10.script.WarpScriptStackFunction;

import java.io.IOException;

import net.razorvine.pyro.serializer.PickleSerializer;

/**
 * Encode an object as Pickle
 */
public class TOPICKLE extends NamedWarpScriptFunction implements WarpScriptStackFunction {

  public TOPICKLE(String name) {
    super(name);
  }

  @Override
  public Object apply(WarpScriptStack stack) throws WarpScriptException {
    Object o = stack.pop();

    try {
      PickleSerializer serializer = new PickleSerializer();
      byte[] data = serializer.serializeData(o);
      stack.push(data);
    } catch (IOException ioe) {
      throw new WarpScriptException(ioe);
    }

    return stack;
  }
}


text:
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "chainparams.h"
#include "consensus/merkle.h"

#include "tinyformat.h"
#include "util.h"
#include "utilstrencodings.h"

#include <assert.h>

#include <boost/assign/list_of.hpp>

#include "chainparamsseeds.h"

static CBlock CreateGenesisBlock(const char* pszTimestamp, const CScript& genesisOutputScript, uint32_t nTime, uint32_t nNonce, uint32_t nBits, int32_t nVersion, const CAmount& genesisReward)
{
    CMutableTransaction txNew;
    txNew.nVersion = 1;
    txNew.vin.resize(1);
    txNew.vout.resize(1);
    txNew.vin[0].scriptSig = CScript() << 486604799 << CScriptNum(4) << std::vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
    txNew.vout[0].nValue = genesisReward;
    txNew.vout[0].scriptPubKey = genesisOutputScript;

    CBlock genesis;
    genesis.nTime    = nTime;
    genesis.nBits    = nBits;
    genesis.nNonce   = nNonce;
    genesis.nVersion = nVersion;
    genesis.vtx.push_back(txNew);
    genesis.hashPrevBlock.SetNull();
    genesis.hashMerkleRoot = BlockMerkleRoot(genesis);
    return genesis;
}

/**
 * Build the genesis block. Note that the output of its generation
 * transaction cannot be spent since it did not originally exist in the
 * database.
 *
 * CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1)
 *   CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0)
 *     CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73)
 *     CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B)
 *   vMerkleTree: 4a5e1e
 */
static CBlock CreateGenesisBlock(uint32_t nTime, uint32_t nNonce, uint32_t nBits, int32_t nVersion, const CAmount& genesisReward)
{
    const char* pszTimestamp = "Pakistan, Afghanistan in angry tangle over chicken-wire border fence to keep out terrorists";
    const CScript genesisOutputScript = CScript() << ParseHex("044acf76c7baca12fa3c8ae1a6d7c7982f283af5ed3918030574b011bfaae6b12fea21703fdcce5ec48b24558d67af0db26b493122d61ee5c7feb5409acb0a17d2") << OP_CHECKSIG;
    return CreateGenesisBlock(pszTimestamp, genesisOutputScript, nTime, nNonce, nBits, nVersion, genesisReward);
}

/**
 * Main network
 */
/**
 * What makes a good checkpoint block?
 * + Is surrounded by blocks with reasonable timestamps
 *   (no blocks before with a timestamp after, none after with
 *    timestamp before)
 * + Contains no strange transactions
 */

class CMainParams : public CChainParams {
public:
    CMainParams() {
        strNetworkID = "main";
        consensus.nSubsidyHalvingInterval = 840000;
        consensus.nMajorityEnforceBlockUpgrade = 750;
        consensus.nMajorityRejectBlockOutdated = 950;
        consensus.nMajorityWindow = 1000;
        consensus.BIP34Height = 0;
        consensus.BIP34Hash = uint256S("0x");
        consensus.powLimit = uint256S("00000fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
        consensus.nPowTargetTimespan = 3.5 * 24 * 60 * 60; // 3.5 days
        consensus.nPowTargetSpacing = 2.5 * 60;
        consensus.fPowAllowMinDifficultyBlocks = false;
        consensus.fPowNoRetargeting = false;
        consensus.nRuleChangeActivationThreshold = 6048; // 75% of 8064
        consensus.nMinerConfirmationWindow = 8064; // nPowTargetTimespan / nPowTargetSpacing * 4
        consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].bit = 28;
        consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nStartTime = 0; // 10/19/2017 @ 7:10am (UTC)
        consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nTimeout = 999999999999ULL; // 10/10/2018

        // Deployment of BIP68, BIP112, and BIP113.
        consensus.vDeployments[Consensus::DEPLOYMENT_CSV].bit = 0;
        consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nStartTime = 0; // January 28, 2017
        consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nTimeout = 999999999999ULL; // January 31st, 2018

        // Deployment of SegWit (BIP141, BIP143, and BIP147)
        consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].bit = 1;
        consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nStartTime = 0; // January 28, 2017
        consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nTimeout = 999999999999ULL; // January 31st, 2018

        // The best chain should have at least this much work.
        consensus.nMinimumChainWork = uint256S("0x000000000000000000000000000000000000000000000005c13f99f6d0b1a908");

        /**
         * The message start string is designed to be unlikely to occur in normal data.
         * The characters are rarely used upper ASCII, not valid as UTF-8, and produce
         * a large 32-bit integer with any alignment.
         */
        pchMessageStart[0] = 0xfc;
        pchMessageStart[1] = 0xdc;
        pchMessageStart[2] = 0xc2;
        pchMessageStart[3] = 0xd5;
        nDefaultPort = 9944;
        nPruneAfterHeight = 100000;

        genesis = CreateGenesisBlock(1508485972, 599942, 0x1e0fff00, 1, 50 * COIN);
        consensus.hashGenesisBlock = genesis.GetHash();

        printf("TEST genesis merkle root: %s\n", genesis.hashMerkleRoot.ToString().c_str());
        printf("TEST genesis nonce: %d\n", genesis.nNonce);
        printf("TEST genesis hash: %s\n", genesis.GetHash().ToString().c_str());

        assert(consensus.hashGenesisBlock == uint256S("0x64770bab6a22948dc589626d6ae2a09fc7eea4b57763f47276dcd719f4606b48"));
        assert(genesis.hashMerkleRoot == uint256S("0x941459ea478e4567eb64f38cc6f0f7d892ef5740d15e82fdaadfea0d5730cc4f"));

        vFixedSeeds.clear();
        vSeeds.clear();
        // Note that of those with the service bits flag, most only support a subset of possible options
        //vSeeds.push_back(CDNSSeedData("bilalpc", "119.157.29.83", true));
        //vSeeds.push_back(CDNSSeedData("bilalserver", "173.212.194.240", true));

        base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,50);
        base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,6);
        base58Prefixes[SECRET_KEY] =     std::vector<unsigned char>(1,216);
        base58Prefixes[EXT_PUBLIC_KEY] = boost::assign::list_of(0x05)(0x86)(0xC2)(0x2E).convert_to_container<std::vector<unsigned char> >();
        base58Prefixes[EXT_SECRET_KEY] = boost::assign::list_of(0x05)(0x86)(0xDC)(0xF1).convert_to_container<std::vector<unsigned char> >();

        vFixedSeeds = std::vector<SeedSpec6>(pnSeed6_main, pnSeed6_main + ARRAYLEN(pnSeed6_main));

        fMiningRequiresPeers = true;
        fDefaultConsistencyChecks = false;
        fRequireStandard = true;
        fMineBlocksOnDemand = false;
        fTestnetToBeDeprecatedFieldRPC = false;

	checkpointData = (CCheckpointData) {
		boost::assign::map_list_of
			(0, uint256S("0x64770bab6a22948dc589626d6ae2a09fc7eea4b57763f47276dcd719f4606b48")),
			0, // * UNIX timestamp of last checkpoint block
			0,   // * total number of transactions between genesis and last checkpoint
			//   (the tx=... number in the SetBestChain debug.log lines)
			5500.0     // * estimated number of transactions per day after checkpoint
	};

    }
};
static CMainParams mainParams;

/**
 * Testnet (v3)
 */
class CTestNetParams : public CChainParams {
public:
    CTestNetParams() {
        strNetworkID = "test";
        consensus.nSubsidyHalvingInterval = 840000;
        consensus.nMajorityEnforceBlockUpgrade = 51;
        consensus.nMajorityRejectBlockOutdated = 75;
        consensus.nMajorityWindow = 100;
        consensus.BIP34Height = 0;
        consensus.BIP34Hash = uint256S("0x");
        consensus.powLimit = uint256S("00000fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
        consensus.nPowTargetTimespan = 3.5 * 24 * 60 * 60; // 3.5 days
        consensus.nPowTargetSpacing = 2.5 * 60;
        consensus.fPowAllowMinDifficultyBlocks = true;
        consensus.fPowNoRetargeting = false;
        consensus.nRuleChangeActivationThreshold = 1512; // 75% for testchains
        consensus.nMinerConfirmationWindow = 2016; // nPowTargetTimespan / nPowTargetSpacing
        consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].bit = 28;
        consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nStartTime = 0; // January 1, 2008
        consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nTimeout = 999999999999ULL; // December 31, 2008

        // Deployment of BIP68, BIP112, and BIP113.
        consensus.vDeployments[Consensus::DEPLOYMENT_CSV].bit = 0;
        consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nStartTime = 0; // January 1, 2017
        consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nTimeout = 999999999999ULL; // January 31st, 2018

        // Deployment of SegWit (BIP141, BIP143, and BIP147)
        consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].bit = 1;
        consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nStartTime = 0; // January 1, 2017
        consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nTimeout = 999999999999ULL; // January 31st, 2018

        // The best chain should have at least this much work.
        consensus.nMinimumChainWork = uint256S("0x00000000000000000000000000000000000000000000000000006fce5d67766e");

        pchMessageStart[0] = 0xac;
        pchMessageStart[1] = 0xb2;
        pchMessageStart[2] = 0xd5;
        pchMessageStart[3] = 0x2c;
        nDefaultPort = 19944;
        nPruneAfterHeight = 1000;

        genesis = CreateGenesisBlock(1508486273, 25658, 0x1e0fff5d, 1, 50 * COIN);
        consensus.hashGenesisBlock = genesis.GetHash();

        printf("TEST genesis merkle root: %s\n", genesis.hashMerkleRoot.ToString().c_str());
        printf("TEST genesis nonce: %d\n", genesis.nNonce);
        printf("TEST genesis hash: %s\n", genesis.GetHash().ToString().c_str());

        assert(consensus.hashGenesisBlock == uint256S("0xb24865829f7d40637a4660e24222e7952244f5d632dc6525ea8457867491a864"));
        assert(genesis.hashMerkleRoot == uint256S("0x941459ea478e4567eb64f38cc6f0f7d892ef5740d15e82fdaadfea0d5730cc4f"));

        vFixedSeeds.clear();
        vSeeds.clear();
        // nodes with support for servicebits filtering should be at the top
        //vSeeds.push_back(CDNSSeedData("pearlcointools.com", "testnet-seed.pearlcointools.com"));
        //vSeeds.push_back(CDNSSeedData("loshan.co.uk", "seed-b.pearlcoin.loshan.co.uk", true));

        base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,11);
        base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,106);
        base58Prefixes[SECRET_KEY] =     std::vector<unsigned char>(1,229);
        base58Prefixes[EXT_PUBLIC_KEY] = boost::assign::list_of(0x05)(0x37)(0x82)(0xBF).convert_to_container<std::vector<unsigned char> >();
        base58Prefixes[EXT_SECRET_KEY] = boost::assign::list_of(0x05)(0x37)(0x84)(0xA4).convert_to_container<std::vector<unsigned char> >();

        vFixedSeeds = std::vector<SeedSpec6>(pnSeed6_test, pnSeed6_test + ARRAYLEN(pnSeed6_test));

        fMiningRequiresPeers = true;
        fDefaultConsistencyChecks = false;
        fRequireStandard = false;
        fMineBlocksOnDemand = false;
        fTestnetToBeDeprecatedFieldRPC = true;

        checkpointData = (CCheckpointData) {
            boost::assign::map_list_of
            ( 0, uint256S("0xb24865829f7d40637a4660e24222e7952244f5d632dc6525ea8457867491a864")),
            0,
            0,
            576
        };

    }
};
static CTestNetParams testNetParams;

/**
 * Regression test
 */
class CRegTestParams : public CChainParams {
public:
    CRegTestParams() {
        strNetworkID = "regtest";
        consensus.nSubsidyHalvingInterval = 150;
        consensus.nMajorityEnforceBlockUpgrade = 750;
        consensus.nMajorityRejectBlockOutdated = 950;
        consensus.nMajorityWindow = 1000;
        consensus.BIP34Height = -1; // BIP34 has not necessarily activated on regtest
        consensus.BIP34Hash = uint256();
        consensus.powLimit = uint256S("7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
        consensus.nPowTargetTimespan = 3.5 * 24 * 60 * 60; // two weeks
        consensus.nPowTargetSpacing = 2.5 * 60;
        consensus.fPowAllowMinDifficultyBlocks = true;
        consensus.fPowNoRetargeting = true;
        consensus.nRuleChangeActivationThreshold = 108; // 75% for testchains
        consensus.nMinerConfirmationWindow = 144; // Faster than normal for regtest (144 instead of 2016)
        consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].bit = 28;
        consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nStartTime = 0;
        consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nTimeout = 999999999999ULL;
        consensus.vDeployments[Consensus::DEPLOYMENT_CSV].bit = 0;
        consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nStartTime = 0;
        consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nTimeout = 999999999999ULL;
        consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].bit = 1;
        consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nStartTime = 0;
        consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nTimeout = 999999999999ULL;

        // The best chain should have at least this much work.
        consensus.nMinimumChainWork = uint256S("0x00");

        pchMessageStart[0] = 0xaa;
        pchMessageStart[1] = 0xbd;
        pchMessageStart[2] = 0xaf;
        pchMessageStart[3] = 0xd1;
        nDefaultPort = 19444;
        nPruneAfterHeight = 1000;

        genesis = CreateGenesisBlock(1508486245, 191760, 0x1e0fff11, 1, 50 * COIN);
        consensus.hashGenesisBlock = genesis.GetHash();

        printf("REG genesis merkle root: %s\n", genesis.hashMerkleRoot.ToString().c_str());
        printf("REG genesis nonce: %d\n", genesis.nNonce);
        printf("REG genesis hash: %s\n", genesis.GetHash().ToString().c_str());

        assert(consensus.hashGenesisBlock == uint256S("0xeddb963d6a2e50ada3bd719b41960e4c96ff0088d316825f7da5ebc3f08edb02"));
        assert(genesis.hashMerkleRoot == uint256S("0x941459ea478e4567eb64f38cc6f0f7d892ef5740d15e82fdaadfea0d5730cc4f"));

        vFixedSeeds.clear(); //!< Regtest mode doesn't have any fixed seeds.
        vSeeds.clear();      //!< Regtest mode doesn't have any DNS seeds.

        fMiningRequiresPeers = false;
        fDefaultConsistencyChecks = true;
        fRequireStandard = false;
        fMineBlocksOnDemand = true;
        fTestnetToBeDeprecatedFieldRPC = false;

	checkpointData = (CCheckpointData){
		boost::assign::map_list_of
			( 0, uint256S("0xeddb963d6a2e50ada3bd719b41960e4c96ff0088d316825f7da5ebc3f08edb02")),
			0,
			0,
			0
	};

        base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,113);
        base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,123);
        base58Prefixes[SECRET_KEY] =     std::vector<unsigned char>(1,202);
        base58Prefixes[EXT_PUBLIC_KEY] = boost::assign::list_of(0x05)(0x39)(0x81)(0xAB).convert_to_container<std::vector<unsigned char> >();
        base58Prefixes[EXT_SECRET_KEY] = boost::assign::list_of(0x05)(0x39)(0x85)(0x2C).convert_to_container<std::vector<unsigned char> >();
    }

    void UpdateBIP9Parameters(Consensus::DeploymentPos d, int64_t nStartTime, int64_t nTimeout)
    {
        consensus.vDeployments[d].nStartTime = nStartTime;
        consensus.vDeployments[d].nTimeout = nTimeout;
    }
};
static CRegTestParams regTestParams;

static CChainParams *pCurrentParams = 0;

const CChainParams &Params() {
    assert(pCurrentParams);
    return *pCurrentParams;
}

CChainParams& Params(const std::string& chain)
{
    if (chain == CBaseChainParams::MAIN)
            return mainParams;
    else if (chain == CBaseChainParams::TESTNET)
            return testNetParams;
    else if (chain == CBaseChainParams::REGTEST)
            return regTestParams;
    else
        throw std::runtime_error(strprintf("%s: Unknown chain %s.", __func__, chain));
}

void SelectParams(const std::string& network)
{
    SelectBaseParams(network);
    pCurrentParams = &Params(network);
}

void UpdateRegtestBIP9Parameters(Consensus::DeploymentPos d, int64_t nStartTime, int64_t nTimeout)
{
    regTestParams.UpdateBIP9Parameters(d, nStartTime, nTimeout);
}


text:
<?php

namespace frdl\aSQL\Engines\Terminal;

class ACConsole extends CLI
{

  protected function boot(){}
  protected function _exec($args){}
  protected function force_state($state){}
  public function parseQuery(){}
  public function validateQuery(){}
 /**
  * Build CLI
  */
  public function add_command($command, callable $callable){}
  public function add_option(mixed $settings){}
  public function add_flag(mixed $settings){}
  public function add_argument(mixed $settings){}

public function test()
{
		header("Content-Type: text/plain");
		 $cmd = 'frdl test -c --test=console --foo=bar; install
 ';

 $batch = $this->parse($cmd);
 echo 'Test command line:'."\n\n".$cmd."\n\n".'Parsed:'."\n"
     .print_r($batch,true);
 echo "\n";
 echo 'Unparsed:'."\n\n";
 $u =  $this->unparse($batch);
 echo $u;
 echo "\n";
 $batch = $this->parse($u);
 echo 'Test-Re-Parsing:'."\n"
     .print_r($batch,true);
}

}


text:
<!DOCTYPE html>

	<title>Leaflet debug page</title>

	<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.0.3/leaflet.css" />

	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<link rel="stylesheet" href="screen.css" />

	<link rel="stylesheet" href="../dist/MarkerCluster.css" />
	<link rel="stylesheet" href="../dist/MarkerCluster.Default.css" />

	<button id="moveone">Move a random marker</button>


text:
package cmd

import (
	"github.com/stretchr/testify/require"
	"os"
	"runtime"
	"testing"

	"path/filepath"

	"github.com/drud/ddev/pkg/ddevapp"
	"github.com/drud/ddev/pkg/exec"
	"github.com/drud/ddev/pkg/testcommon"
	"github.com/drud/ddev/pkg/util"
	asrt "github.com/stretchr/testify/assert"
)

// TestCmdPauseContainers runs `ddev pause` on the test apps
func TestCmdPauseContainers(t *testing.T) {
	assert := asrt.New(t)

	// Make sure we have running sites.
	err := addSites()
	require.NoError(t, err)

	site := TestSites[0]
	cleanup := site.Chdir()

	out, err := exec.RunCommand(DdevBin, []string{"pause"})
	assert.NoError(err, "ddev pause should succeed but failed, err: %v, output: %s", err, out)
	assert.Contains(out, "has been paused")

	apps := ddevapp.GetActiveProjects()

	for _, app := range apps {
		if app.GetName() != site.Name {
			continue
		}

		status, _ := app.SiteStatus()
		assert.True(status == ddevapp.SitePaused)
	}

	cleanup()

	// Re-create running sites.
	err = addSites()
	require.NoError(t, err)
	out, err = exec.RunCommand(DdevBin, []string{"pause", "--all"})
	assert.NoError(err, "ddev pause --all should succeed but failed, err: %v, output: %s", err, out)

	// Confirm all sites are stopped.
	apps = ddevapp.GetActiveProjects()
	for _, app := range apps {
		status, statusDesc := app.SiteStatus()
		assert.Equal(ddevapp.SitePaused, status, "All sites should be stopped, but project=%s status=%s, statusDesc=%s", app.GetName(), status, statusDesc)
		assert.Equal(ddevapp.SitePaused, statusDesc, "Status description should be \"stopped\", but %s status description is: %s", app.GetName(), statusDesc)
	}

	// Now put the sites back together so other tests can use them.
	err = addSites()
	require.NoError(t, err)
}

// TestCmdPauseContainersMissingProjectDirectory ensures the `ddev pause` command returns the expected help text when
// a project's directory no longer exists.
func TestCmdPauseContainersMissingProjectDirectory(t *testing.T) {
	var err error
	var out string

	if runtime.GOOS == "windows" {
		t.Skip("Skipping because unreliable on Windows")
	}

	assert := asrt.New(t)

	projDir, _ := os.Getwd()

	projectName := util.RandString(6)

	tmpDir := testcommon.CreateTmpDir(t.Name())
	defer testcommon.CleanupDir(tmpDir)
	defer testcommon.Chdir(tmpDir)()

	_, err = exec.RunCommand(DdevBin, []string{"config", "--project-type", "php", "--project-name", projectName})
	assert.NoError(err)

	_, err = exec.RunCommand(DdevBin, []string{"start", "-y"})
	assert.NoError(err)

	//nolint: errcheck
	defer exec.RunCommand(DdevBin, []string{"stop", "-RO", projectName})

	_, err = exec.RunCommand(DdevBin, []string{"pause", projectName})
	assert.NoError(err)

	err = os.Chdir(projDir)
	assert.NoError(err)

	copyDir := filepath.Join(testcommon.CreateTmpDir(t.Name()), util.RandString(4))
	err = os.Rename(tmpDir, copyDir)
	assert.NoError(err)

	out, err = exec.RunCommand(DdevBin, []string{"pause", projectName})
	assert.Error(err, "Expected an error when pausing project with no project directory")
	assert.Contains(out, "ddev can no longer find your project files")
}


text: Introduction Tutorial to TensorFlow


text:
namespace content {

// static
PepperPlatformAudioOutputImpl* PepperPlatformAudioOutputImpl::Create(
    int sample_rate,
    int frames_per_buffer,
    int source_render_view_id,
    webkit::ppapi::PluginDelegate::PlatformAudioOutputClient* client) {
  scoped_refptr<PepperPlatformAudioOutputImpl> audio_output(
      new PepperPlatformAudioOutputImpl());
  if (audio_output->Initialize(sample_rate, frames_per_buffer,
                               source_render_view_id, client)) {
    // Balanced by Release invoked in
    // PepperPlatformAudioOutputImpl::ShutDownOnIOThread().
    audio_output->AddRef();
    return audio_output.get();
  }
  return NULL;
}

bool PepperPlatformAudioOutputImpl::StartPlayback() {
  if (ipc_) {
    ChildProcess::current()->io_message_loop()->PostTask(
        FROM_HERE,
        base::Bind(&PepperPlatformAudioOutputImpl::StartPlaybackOnIOThread,
                   this));
    return true;
  }
  return false;
}

bool PepperPlatformAudioOutputImpl::StopPlayback() {
  if (ipc_) {
    ChildProcess::current()->io_message_loop()->PostTask(
        FROM_HERE,
        base::Bind(&PepperPlatformAudioOutputImpl::StopPlaybackOnIOThread,
                   this));
    return true;
  }
  return false;
}

void PepperPlatformAudioOutputImpl::ShutDown() {
  // Called on the main thread to stop all audio callbacks. We must only change
  // the client on the main thread, and the delegates from the I/O thread.
  client_ = NULL;
  ChildProcess::current()->io_message_loop()->PostTask(
      FROM_HERE,
      base::Bind(&PepperPlatformAudioOutputImpl::ShutDownOnIOThread, this));
}

void PepperPlatformAudioOutputImpl::OnStateChanged(
    media::AudioOutputIPCDelegate::State state) {
}

void PepperPlatformAudioOutputImpl::OnStreamCreated(
    base::SharedMemoryHandle handle,
    base::SyncSocket::Handle socket_handle,
    int length) {
#if defined(OS_WIN)
  DCHECK(handle);
  DCHECK(socket_handle);
#else
  DCHECK_NE(-1, handle.fd);
  DCHECK_NE(-1, socket_handle);
#endif
  DCHECK(length);

  if (base::MessageLoopProxy::current() == main_message_loop_proxy_) {
    // Must dereference the client only on the main thread. Shutdown may have
    // occurred while the request was in-flight, so we need to NULL check.
    if (client_)
      client_->StreamCreated(handle, length, socket_handle);
  } else {
    main_message_loop_proxy_->PostTask(FROM_HERE,
        base::Bind(&PepperPlatformAudioOutputImpl::OnStreamCreated, this,
                   handle, socket_handle, length));
  }
}

void PepperPlatformAudioOutputImpl::OnIPCClosed() {
  ipc_ = NULL;
}

PepperPlatformAudioOutputImpl::~PepperPlatformAudioOutputImpl() {
  // Make sure we have been shut down. Warning: this will usually happen on
  // the I/O thread!
  DCHECK_EQ(0, stream_id_);
  DCHECK(!client_);
}

PepperPlatformAudioOutputImpl::PepperPlatformAudioOutputImpl()
    : client_(NULL),
      stream_id_(0),
      main_message_loop_proxy_(base::MessageLoopProxy::current()) {
  ipc_ = RenderThreadImpl::current()->audio_message_filter();
}

bool PepperPlatformAudioOutputImpl::Initialize(
    int sample_rate,
    int frames_per_buffer,
    int source_render_view_id,
    webkit::ppapi::PluginDelegate::PlatformAudioOutputClient* client) {
  DCHECK(client);
  client_ = client;

  media::AudioParameters::Format format;
  const int kMaxFramesForLowLatency = 2047;

  media::AudioHardwareConfig* hardware_config =
      RenderThreadImpl::current()->GetAudioHardwareConfig();

  const CommandLine* cmd_line = CommandLine::ForCurrentProcess();
  if (!cmd_line->HasSwitch(switches::kDisableAudioOutputResampler)) {
    // Rely on AudioOutputResampler to handle any inconsistencies between the
    // hardware params required for low latency and the requested params.
    format = media::AudioParameters::AUDIO_PCM_LOW_LATENCY;
  } else if (sample_rate == hardware_config->GetOutputSampleRate() &&
             frames_per_buffer <= kMaxFramesForLowLatency &&
             frames_per_buffer % hardware_config->GetOutputBufferSize() == 0) {
    // Use the low latency back end if the client request is compatible, and
    // the sample count is low enough to justify using AUDIO_PCM_LOW_LATENCY.
    format = media::AudioParameters::AUDIO_PCM_LOW_LATENCY;
  } else {
    format = media::AudioParameters::AUDIO_PCM_LINEAR;
  }

  media::AudioParameters params(format, media::CHANNEL_LAYOUT_STEREO,
                                sample_rate, 16, frames_per_buffer);

  ChildProcess::current()->io_message_loop()->PostTask(
      FROM_HERE,
      base::Bind(&PepperPlatformAudioOutputImpl::InitializeOnIOThread,
                 this, params, source_render_view_id));
  return true;
}

void PepperPlatformAudioOutputImpl::InitializeOnIOThread(
    const media::AudioParameters& params, int source_render_view_id) {
  // Make sure we don't call init more than once.
  DCHECK_EQ(0, stream_id_);
  stream_id_ = ipc_->AddDelegate(this);
  DCHECK_NE(0, stream_id_);

  ipc_->CreateStream(stream_id_, params);
  ipc_->AssociateStreamWithProducer(stream_id_, source_render_view_id);
}

void PepperPlatformAudioOutputImpl::StartPlaybackOnIOThread() {
  if (stream_id_)
    ipc_->PlayStream(stream_id_);
}

void PepperPlatformAudioOutputImpl::StopPlaybackOnIOThread() {
  if (stream_id_)
    ipc_->PauseStream(stream_id_);
}

void PepperPlatformAudioOutputImpl::ShutDownOnIOThread() {
  // Make sure we don't call shutdown more than once.
  if (!stream_id_)
    return;

  ipc_->CloseStream(stream_id_);
  ipc_->RemoveDelegate(stream_id_);
  stream_id_ = 0;

  Release();  // Release for the delegate, balances out the reference taken in
              // PepperPluginDelegateImpl::CreateAudio.
}

}  // namespace content


text:
[![travis build](https://img.shields.io/travis/panzerdp/voca.svg)](https://travis-ci.org/panzerdp/voca)
[![code coverage](https://img.shields.io/codecov/c/github/panzerdp/voca.svg)](https://codecov.io/github/panzerdp/voca)
[![npm package](https://img.shields.io/npm/v/voca.svg)](https://www.npmjs.com/package/voca)

Voca is a JavaScript library for manipulating strings. [https://vocajs.com][voca]

```javascript
v.camelCase('bird flight');              // => 'birdFlight'
v.sprintf('%s costs $%.2f', 'Tea', 1.5); // => 'Tea costs $1.50'
v.slugify('What a wonderful world');     // => 'what-a-wonderful-world'
```

The Voca library offers helpful functions to make string manipulations comfortable: *change case, trim, pad, slugify,
latinise, sprintf'y, truncate, escape* and much more.  The *modular design* allows to load the entire library, or
individual functions to minimize the application builds. The library is *fully tested*, *well documented* and *long-term supported*.

## Features

*  Provides the complete set of functions to manipulate, chop, format, escape and query strings
*  Includes detailed, easy to read and searchable [documentation][voca]
*  [Supports](https://saucelabs.com/u/panzerdp) a wide range of environments: Node.js 0.10+, Chrome, Firefox, Safari 7+, Edge 13+, IE 9+
*  100% code coverage
*  No dependencies

## Documentation

See the complete documentation at [https://vocajs.com][voca]

## Usage
Voca can be used in various environments.

### Node.js, Rollup, Webpack, Browserify

![Voca JavaScript library supports Node.js, Rollup, Webpack, Browserify][logo_commonjs]

Install the library with npm into your local modules directory:

```bash
npm install voca
```

### CommonJS modules

Then in your application require the entire library:

```javascript
const v = require('voca');
v.trim(' Hello World! ');            // => 'Hello World'
v.sprintf('%d red %s', 3, 'apples'); // => '3 red apples'
```

Or require individual functions:

```javascript
const words = require('voca/words');
const slugify = require('voca/slugify');
words('welcome to Earth'); // => ['welcome', 'to', 'Earth']
slugify('caffé latté');    // => 'caffe-latte'
```

### ES2015 modules

Voca is compatible with ES2015 modules to import the entire library:

```javascript
import voca from 'voca';
voca.kebabCase('goodbye blue sky'); // => 'goodbye-blue-sky'
```

Or import individual functions:

```javascript
import last from 'voca/last';
last('sun rises', 5); // => 'rises'
```

### Browser

![Voca JavaScript library supports Chrome, Firefox, Safari, Edge, Internet Explorer][logo_browsers]

Load the UMD builds directly into browser's web page:

* [`dist/voca.min.js`][voca_min_js] minified production-ready, with [source map][source_map]
* [`dist/voca.js`][voca_js] uncompressed with comments

```html
<script src="voca.js" type="text/javascript"></script>
```

Then a global variable `v` is exposed for the entire library:

```html
<script type="text/javascript">
  v.last('wonderful world', 5); // => 'world'
</script>
```

## Functions

| Manipulate                           | Query                          | Chop                                 | Case                           | Index                          |
| :----------------------------------- | :----------------------------- | :----------------------------------- | :----------------------------- | :------------------------------|
| [v.insert][insert]                   | [v.endsWith][endsWith]         | [v.charAt][charAt]                   | [v.camelCase][camelCase]       | [v.indexOf][indexOf]           |
| [v.latinise][latinise]               | [v.includes][includes]         | [v.codePointAt][codePointAt]         | [v.capitalize][capitalize]     | [v.lastIndexOf][lastIndexOf]   |
| [v.pad][pad]                         | [v.isAlpha][isAlpha]           | [v.first][first]                     | [v.decapitalize][decapitalize] | [v.search][search]             |
| [v.padLeft][padLeft]                 | [v.isAlphaDigit][isAlphaDigit] | [v.graphemeAt][graphemeAt]           | [v.kebabCase][kebabCase]       | **Escape**                     |
| [v.padRight][padRight]               | [v.isBlank][isBlank]           | [v.last][last]                       | [v.lowerCase][lowerCase]       | [v.escapeHtml][escapeHtml]     |
| [v.repeat][repeat]                   | [v.isDigit][isDigit]           | [v.prune][prune]                     | [v.snakeCase][snakeCase]       | [v.escapeRegExp][escapeRegExp] |
| [v.replace][replace]                 | [v.isEmpty][isEmpty]           | [v.slice][slice]                     | [v.swapCase][swapCase]         | [v.unescapeHtml][unescapeHtml] |
| [v.replaceAll][replaceAll]           | [v.isLowerCase][isLowerCase]   | [v.substr][substr]                   | [v.titleCase][titleCase]       | **Strip**                      |
| [v.reverse][reverse]                 | [v.isNumeric][isNumeric]       | [v.substring][substring]             | [v.upperCase][upperCase]       |  [v.stripBom][stripBom]        |
| [v.reverseGrapheme][reverseGrapheme] | [v.isString][isString]         | [v.truncate][truncate]               | **Split**                      |  [v.stripTags][stripTags]      |
| [v.slugify][slugify]                 | [v.isUpperCase][isUpperCase]   | **Count**                            | [v.chars][chars]               |                                |
| [v.splice][splice]                   | [v.matches][matches]           | [v.count][count]                     | [v.codePoints][codePoints]     |                                |
| [v.tr][tr]                           | [v.startsWith][startsWith]     | [v.countGraphemes][countGraphemes]   | [v.graphemes][graphemes]       |                                |
| [v.trim][trim]                       | **Format**                     | [v.countSubstrings][countSubstrings] | [v.split][split]               |                                |
| [v.trimLeft][trimLeft]               | [v.sprintf][sprintf]           | [v.countWhere][countWhere]           | [v.words][words]               |                                |
| [v.trimRight][trimRight]             | [v.vprintf][vprintf]           | [v.countWords][countWords]           |                                |                                |
| [v.wordWrap][wordWrap]               |                                |                                      |                                |                                |

## Bug reports

For bug reports, documentation typos or feature requests feel free to create an [issue](https://github.com/panzerdp/voca/issues).
Please make sure that the same problem wasn't reported already.

For general usage questions please ask on [StackOverflow](http://stackoverflow.com/questions/ask).

## Contributing

Contribution is welcome!

* Create a pull request containing bug fixes or new features. Include unit tests and keep the code coverage report near 100% 😎
* [Propose](https://github.com/panzerdp/voca/issues/new) new functions, improvements, better documentation

See more details in [Contributing guide][CONTRIBUTING].

Please note that this project is released with a Contributor [Code of Conduct][CODE_OF_CONDUCT]. By participating in this project you agree to abide by its terms.

## Author

| ![Dmitri Pavlutin](https://s.gravatar.com/avatar/0d57a57d8807ebc70e24b46f6d9e3a36?s=100) |
| :-: |
| Dmitri Pavlutin
| [Personal blog](https://dmitripavlutin.com)
| [Email](mailto:dmitripavlutin@gmail.com)

## License

Licensed under [MIT](https://github.com/panzerdp/voca/blob/master/LICENSE.md)

[CODE_OF_CONDUCT]: https://github.com/panzerdp/voca/blob/master/CODE_OF_CONDUCT.md
[CONTRIBUTING]: https://github.com/panzerdp/voca/blob/master/.github/CONTRIBUTING.md
[voca_min_js]: https://raw.githubusercontent.com/panzerdp/voca/v1.4.0/dist/voca.min.js
[source_map]: https://raw.githubusercontent.com/panzerdp/voca/v1.4.0/dist/voca.min.js.map
[voca_js]: https://raw.githubusercontent.com/panzerdp/voca/v1.4.0/dist/voca.js
[voca]: https://vocajs.com
[logo]: https://github.com/panzerdp/voca/raw/master/jsdoc/template/static/images/voca-logo@300px.png
[logo_commonjs]: https://github.com/panzerdp/voca/raw/master/jsdoc/template/static/images/commonjs@200px.png
[logo_browsers]: https://github.com/panzerdp/voca/raw/master/jsdoc/template/static/images/browsers@200px.png

[camelCase]: https://vocajs.com/#camelCase
[capitalize]: https://vocajs.com/#capitalize
[decapitalize]: https://vocajs.com/#decapitalize
[kebabCase]: https://vocajs.com/#kebabCase
[lowerCase]: https://vocajs.com/#lowerCase
[snakeCase]: https://vocajs.com/#snakeCase
[swapCase]: https://vocajs.com/#swapCase
[titleCase]: https://vocajs.com/#titleCase
[upperCase]: https://vocajs.com/#upperCase

[charAt]: https://vocajs.com/#charAt
[codePointAt]: https://vocajs.com/#codePointAt
[first]: https://vocajs.com/#first
[graphemeAt]: https://vocajs.com/#graphemeAt
[last]: https://vocajs.com/#last
[prune]: https://vocajs.com/#prune
[slice]: https://vocajs.com/#slice
[substr]: https://vocajs.com/#substr
[substring]: https://vocajs.com/#substring
[truncate]: https://vocajs.com/#truncate

[count]: https://vocajs.com/#count
[countGraphemes]: https://vocajs.com/#countGraphemes
[countSubstrings]: https://vocajs.com/#countSubstrings
[countWhere]: https://vocajs.com/#countWhere
[countWords]: https://vocajs.com/#countWords

[escapeHtml]: https://vocajs.com/#escapeHtml
[escapeRegExp]: https://vocajs.com/#escapeRegExp
[unescapeHtml]: https://vocajs.com/#unescapeHtml

[sprintf]: https://vocajs.com/#sprintf
[vprintf]: https://vocajs.com/#vprintf

[indexOf]: https://vocajs.com/#indexOf
[lastIndexOf]: https://vocajs.com/#lastIndexOf
[search]: https://vocajs.com/#search

[insert]: https://vocajs.com/#insert
[latinise]: https://vocajs.com/#latinise
[pad]: https://vocajs.com/#pad
[padLeft]: https://vocajs.com/#padLeft
[padRight]: https://vocajs.com/#padRight
[repeat]: https://vocajs.com/#repeat
[replace]: https://vocajs.com/#replace
[replaceAll]: https://vocajs.com/#replaceAll
[reverse]: https://vocajs.com/#reverse
[reverseGrapheme]: https://vocajs.com/#reverseGrapheme
[slugify]: https://vocajs.com/#slugify
[splice]: https://vocajs.com/#splice
[tr]: https://vocajs.com/#tr
[trim]: https://vocajs.com/#trim
[trimLeft]: https://vocajs.com/#trimLeft
[trimRight]: https://vocajs.com/#trimRight
[wordWrap]: https://vocajs.com/#wordWrap

[endsWith]: https://vocajs.com/#endsWith
[includes]: https://vocajs.com/#includes
[isAlpha]: https://vocajs.com/#isAlpha
[isAlphaDigit]: https://vocajs.com/#isAlphaDigit
[isBlank]: https://vocajs.com/#isBlank
[isDigit]: https://vocajs.com/#isDigit
[isEmpty]: https://vocajs.com/#isEmpty
[isLowerCase]: https://vocajs.com/#isLowerCase
[isNumeric]: https://vocajs.com/#isNumeric
[isString]: https://vocajs.com/#isString
[isUpperCase]: https://vocajs.com/#isUpperCase
[matches]: https://vocajs.com/#matches
[startsWith]: https://vocajs.com/#startsWith

[chars]: https://vocajs.com/#chars
[codePoints]: https://vocajs.com/#codePoints
[graphemes]: https://vocajs.com/#graphemes
[split]: https://vocajs.com/#split
[words]: https://vocajs.com/#words

[stripTags]: https://vocajs.com/#stripTags
[stripBom]: https://vocajs.com/#stripBom


text:
When you want to return to a past version of a file, you can reset to a past
commit. When you don't want to abandon a bunch of other changes, this isn't
going to cut it. Another option is to just checkout the particular file as
it was at the time of a past commit.

If the sha of that past commit is `72f2675` and the file's name is
`some_file.rb`, then just use checkout like so:

```bash
git checkout 72f2675 some_file.rb
```

Via [jbranchaud/til](https://github.com/jbranchaud/til).


text:
require 'spec_helper'

describe Rubex do
  test_case = "ruby_symbols"

  context "Case: #{test_case}" do
    before do
      @path = path_str test_case
    end

    context ".ast" do
      it "generates the AST" do
        t = Rubex::Compiler.ast(@path + '.rubex')
      end
    end

    context ".compile" do
      it "compiles to valid C file" do
        t,c,e = Rubex::Compiler.compile(@path + '.rubex', test: true)
      end
    end

    context "Black box testing" do
      it "compiles and checks for valid output" do
        setup_and_teardown_compiled_files(test_case) do |dir|
          require_relative "#{dir}/#{test_case}.#{os_extension}"
          answer = {
            first: "a",
            second: :f,
            third: [3,3]
          }
          expect(RubySymbols.new.symbol_support("a", :f)).to eq(answer)
        end
      end
    end
  end
end


text:
package net.nhs.esb.transfer.model;

import java.text.SimpleDateFormat;
import java.util.GregorianCalendar;
import java.util.TimeZone;

import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.PrePersist;
import javax.persistence.Table;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;

@Entity
@Table(name="sites")
public class Site {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @JsonProperty("id")
    private Long id;

    @Column(name="patient_id", unique=true, nullable=false)
    @JsonProperty("patientId")
    private Long patientId;

    @Column(name="site_to")
    @JsonProperty("siteTo")
    private String siteTo;

    @Column(name="site_from")
    @JsonProperty("siteFrom")
    private String siteFrom;

    @Column(name="time_stamp")
    @JsonProperty("timeStamp")
    private String timeStamp;

    @OneToOne
    @JoinColumn(name="transfer_detail_id")
    @JsonIgnore
    private TransferDetail transferDetail;

     @PrePersist
     public void setTimeStamp(){
         SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
         sdf.setTimeZone(TimeZone.getTimeZone("Europe/London"));
         this.timeStamp = sdf.format(GregorianCalendar.getInstance().getTime());
     }

	public String getSiteTo() {
		return siteTo;
	}

	public void setSiteTo(String siteTo) {
		this.siteTo = siteTo;
	}

	public String getSiteFrom() {
		return siteFrom;
	}

	public void setSiteFrom(String siteFrom) {
		this.siteFrom = siteFrom;
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public Long getPatientId() {
		return patientId;
	}

	public void setPatientId(Long patientId) {
		this.patientId = patientId;
	}

	public TransferDetail getTransferDetail() {
		return transferDetail;
	}

	public void setTransferDetail(TransferDetail transferDetail) {
		this.transferDetail = transferDetail;
	}

	public String getTimeStamp() {
		return timeStamp;
	}

	public void setTimeStamp(String timeStamp) {
		this.timeStamp = timeStamp;
	}
}


text:
using System;

namespace Echonest.Models
{
    public class LicenceType
    {
        public LicenceTypeEnum Type { get; set; }

        public override string ToString()
        {
            switch (this.Type)
            {
                case LicenceTypeEnum.EchoSource:
                    return "echo-source";
                case LicenceTypeEnum.AllRightsReserved:
                    return "all-rights-reserved";
                case LicenceTypeEnum.CcBySa:
                    return "cc-by-sa";
                case LicenceTypeEnum.CcByNc:
                    return "cc-by-nc";
                case LicenceTypeEnum.CcByNcNd:
                    return "cc-by-nc-nd";
                case LicenceTypeEnum.CcByNcSa:
                    return "cc-by-nc-sa";
                case LicenceTypeEnum.CcByNd:
                    return "cc-by-nd";
                case LicenceTypeEnum.CcBy:
                    return "cc-by";
                case LicenceTypeEnum.PublicDomain:
                    return "public-domain";
                case LicenceTypeEnum.Unknown:
                    return "unknown";
            }

            return null;
        }
    }

    public enum LicenceTypeEnum
    {
        EchoSource,
        AllRightsReserved,
        CcBySa,
        CcByNc,
        CcByNcNd,
        CcByNcSa,
        CcByNd,
        CcBy,
        PublicDomain,
        Unknown
    }
}