text:
"""Argsort operator"""
import tvm
from tvm import api
from .util import get_const_tuple

@tvm.target.generic_func
def argsort(data, valid_count=None, axis=-1, is_ascend=1, dtype="float32"):
    """Performs sorting along the given axis and returns an array
    of indices having the same shape as an input array that index
    data in sorted order.

    Parameters
    ----------
    data : tvm.Tensor
        The input tensor.

    valid_count : tvm.Tensor, optional
        1-D tensor for valid number of boxes only for ssd.

    axis : int, optional
	    Axis along which to sort the input tensor.
        By default the flattened array is used.

    is_ascend : boolean, optional
        Whether to sort in ascending or descending order.

    dtype : string, optional
        DType of the output indices.

    Returns
    -------
    out : tvm.Tensor
        Sorted index tensor.

    Example
    --------
    .. code-block:: python

        # An example to use argsort
        dshape = (1, 5, 6)
        data = tvm.placeholder(dshape, name="data")
        axis = 0
        is_ascend = False
        out = argsort(data, axis=axis, is_ascend=is_ascend)
        np_data = np.random.uniform(dshape)
        s = topi.generic.schedule_argsort(out)
        f = tvm.build(s, [data, out], "llvm")
        ctx = tvm.cpu()
        tvm_data = tvm.nd.array(np_data, ctx)
        tvm_out = tvm.nd.array(np.zeros(dshape, dtype=data.dtype), ctx)
        f(tvm_data, tvm_out)
    """
    data_buf = api.decl_buffer(data.shape, data.dtype, "data_buf", data_alignment=8)
    if valid_count is not None:
        valid_count_buf = api.decl_buffer(valid_count.shape, valid_count.dtype,
                                          "valid_count_buf", data_alignment=4)
        out_buf = api.decl_buffer(data.shape, "int32", "out_buf", data_alignment=8)
        out = \
            tvm.extern(data.shape,
                       [data, valid_count],
                       lambda ins, outs: tvm.call_packed(
                           "tvm.contrib.sort.argsort_nms", ins[0], ins[1],
                           outs[0], axis, is_ascend),
                       dtype="int32",
                       in_buffers=[data_buf, valid_count_buf],
                       out_buffers=out_buf,
                       name="argsort_nms_cpu",
                       tag="argsort_nms_cpu")
    else:
        out_buf = api.decl_buffer(data.shape, dtype, "out_buf", data_alignment=8)
        out = \
            tvm.extern(data.shape,
                       [data],
                       lambda ins, outs: tvm.call_packed(
                           "tvm.contrib.sort.argsort", ins[0],
                           outs[0], axis, is_ascend),
                       dtype=dtype,
                       in_buffers=[data_buf],
                       out_buffers=out_buf,
                       name="argsort_cpu",
                       tag="argsort_cpu")
    return out

@tvm.target.generic_func
def topk(data, k=1, axis=-1, ret_type="both", is_ascend=False, dtype="int64"):
    """Get the top k elements in an input tensor along the given axis.

    Parameters
    ----------
    data : tvm.Tensor
        The input tensor.

    k : int, optional
        Number of top elements to select. Return all elements if k < 1.

    axis : int, optional
        Axis long which to sort the input tensor.

    ret_type: str, optional
        The return type [both, values, indices].
        "both": return both top k data and indices.
        "values": return top k data only.
        "indices": return top k indices only.

    is_ascend : boolean, optional
        Whether to sort in ascending or descending order.

    dtype : string, optional
        The data type of the indices output.

    Returns
    -------
    out : tvm.Tensor or List[tvm.Tensor]
        The computed result.
    """
    assert ret_type in ["both", "values", "indices"]
    data_buf = api.decl_buffer(data.shape, data.dtype, "data_buf", data_alignment=8)
    out_shape = list(get_const_tuple(data.shape))
    if k >= 1:
        out_shape[axis] = k
    out_bufs = []
    if ret_type in ["both", "values"]:
        out_bufs.append(api.decl_buffer(out_shape, data.dtype, "value_buf", data_alignment=8))
    if ret_type in ["both", "indices"]:
        out_bufs.append(api.decl_buffer(out_shape, dtype, "indices_buf", data_alignment=8))
    out_shapes = [out_shape] * len(out_bufs)

    out = tvm.extern(out_shapes,
                     [data],
                     lambda ins, outs: tvm.call_packed(
                         "tvm.contrib.sort.topk", ins[0], *outs, k, axis, ret_type, is_ascend),
                     in_buffers=[data_buf],
                     out_buffers=out_bufs,
                     name="topk_cpu",
                     tag="topk_cpu")
    return out


text:
set -e

# Wrapper script to run bats tests for various drivers.
# Usage: DRIVER=[driver] ./run-bats.sh [subtest]

function quiet_run () {
    if [[ "$VERBOSE" == "1" ]]; then
        "$@"
    else
        "$@" &>/dev/null
    fi
}

function cleanup_machines() {
    for MACHINE_NAME in $(machine ls -q); do
        if [[ "$MACHINE_NAME" != "$SHARED_NAME" ]] || [[ "$1" == "ALL" ]]; then
            quiet_run machine rm -f $MACHINE_NAME
        fi
    done
}

function cleanup_store() {
    if [[ -d "$MACHINE_STORAGE_PATH" ]]; then
        rm -r "$MACHINE_STORAGE_PATH"
    fi
}

function machine() {
    "$MACHINE_ROOT"/bin/"$MACHINE_BIN_NAME" "$@"
}

function run_bats() {
    for bats_file in $(find "$1" -name \*.bats); do
        echo "=> $bats_file"

        # BATS returns non-zero to indicate the tests have failed, we shouldn't
        # necessarily bail in this case, so that's the reason for the e toggle.
        set +e
        bats "$bats_file"
        if [[ $? -ne 0 ]]; then
            EXIT_STATUS=1
        fi
        set -e

        echo

        if [[ "$NO_SHARE_MACHINES" == "1" ]]; then
            cleanup_machines "ALL"
        else
            cleanup_machines "NON-SHARED"
        fi
    done
}

# Set this ourselves in case bats call fails
EXIT_STATUS=0
export BATS_FILE="$1"

# Check we're not running bash 3.x
if [ "${BASH_VERSINFO[0]}" -lt 4 ]; then
    echo "Bash 4.1 or later is required to run these tests"
    exit 1
fi

# If bash 4.x, check the minor version is 1 or later
if [ "${BASH_VERSINFO[0]}" -eq 4 ] && [ "${BASH_VERSINFO[1]}" -lt 1 ]; then
    echo "Bash 4.1 or later is required to run these tests"
    exit 1
fi

if [[ -z "$DRIVER" ]]; then
    echo "You must specify the DRIVER environment variable."
    exit 1
fi

if [[ -z "$BATS_FILE" ]]; then
    echo "You must specify a bats test to run."
    exit 1
fi

if [[ ! -e "$BATS_FILE" ]]; then
    echo "Requested bats file or directory not found: $BATS_FILE"
    exit 1
fi

# TODO: Should the script bail out if these are set already?
export BASE_TEST_DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )
export MACHINE_ROOT="$BASE_TEST_DIR/../.."
export MACHINE_STORAGE_PATH="/tmp/machine-bats-test-$DRIVER"
export MACHINE_BIN_NAME=docker-machine
export BATS_LOG="$MACHINE_ROOT/bats.log"
export B2D_LOCATION=~/.docker/machine/cache/boot2docker.iso
export SHARED_NAME="bats-$DRIVER-test-shared-$(date +%s)"
export MACHINE_BUGSNAG_API_TOKEN=no-report

# This function gets used in the integration tests, so export it.
export -f machine

> "$BATS_LOG"

cleanup_machines "ALL"
cleanup_store

if [[ -f "$B2D_LOCATION" ]]; then
    if [[ "$B2D_CACHE" == "1" ]]; then
        mkdir -p "${MACHINE_STORAGE_PATH}/cache"
        cp $B2D_LOCATION "${MACHINE_STORAGE_PATH}/cache/boot2docker.iso"
    else
        echo "INFO: Run the tests with B2D_CACHE=1 to avoid downloading the boot2docker iso each time."
    fi
fi

run_bats "$BATS_FILE"

cleanup_machines "ALL"
cleanup_store

exit ${EXIT_STATUS}

redpajama_set_name: RedPajamaGithub


text:
package edu.ucsb.cs56.w14.drawings.kjih.advanced;
import java.awt.geom.GeneralPath;
import java.awt.geom.AffineTransform;
import java.awt.Shape;

import java.awt.geom.Point2D;
import java.awt.geom.Line2D;
import java.awt.geom.Rectangle2D;
import java.awt.geom.Ellipse2D;
import java.awt.Rectangle;
import java.awt.geom.PathIterator;
import java.awt.geom.AffineTransform;

import edu.ucsb.cs56.w14.drawings.utilities.ShapeTransforms;
import edu.ucsb.cs56.w14.drawings.utilities.GeneralPathWrapper;

/**
   A vector drawing of a radio that implements
   the Shape interface, and so can be drawn, as well as
   rotated, scaled, etc.

   @author Kevin Jih
   @version for CS56, Winter 14, UCSB

*/
public class Radio extends GeneralPathWrapper implements Shape
{
     /**
	Constructor

	@param x x coord of upper left corner of Radio
	@param y y coord of upper left corner of Radio
	@param width width of Radio
	@param height height of Radio
     */
    public Radio(double x, double y, double width, double height)
    {
	double rightCircleCenterX = x + (width * 0.75);
	double leftCircleCenterX = x + (width * 0.25);
	double circleCenterY = y + (height * 0.5);
	double radiusX = width * 0.125;
	double radiusY = height * 0.25;

	Rectangle2D.Double frame =
	    new Rectangle2D.Double(x, y, width, height);

	Ellipse2D.Double rightSpeaker =
	    new Ellipse2D.Double(rightCircleCenterX - (radiusX/2),
				 circleCenterY - (radiusY/2),
				 radiusX,
				 radiusY);

	Ellipse2D.Double leftSpeaker =
	    new Ellipse2D.Double(leftCircleCenterX - (radiusX/2),
				 circleCenterY - (radiusY/2),
				 radiusX,
				 radiusY);

	Line2D.Double antenna =
	    new Line2D.Double(rightCircleCenterX, y,
			      rightCircleCenterX, y - (height*0.75));

	GeneralPath wholeRadio = this.get();
	wholeRadio.append(frame, false);
	wholeRadio.append(rightSpeaker, false);
	wholeRadio.append(leftSpeaker, false);
	wholeRadio.append(antenna, false);
    }
}


text:
<?php
namespace Icecave\Manifold\Connection;

use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerInterface;

/**
 * The interface implemented by concrete connections.
 *
 * This interface extends the PDO connection interface to add information
 * necessary to serialize the connection for later use.
 */
interface ConnectionInterface extends
    PdoConnectionInterface,
    Container\ConnectionContainerInterface,
    LoggerAwareInterface
{
    /**
     * Get the connection name.
     *
     * @return string The connection name.
     */
    public function name();

    /**
     * Get the data source name.
     *
     * @return string The data source name.
     */
    public function dsn();

    /**
     * Get the connection attributes.
     *
     * @return array<integer,mixed> The connection attributes.
     */
    public function attributes();

    /**
     * Get the logger.
     *
     * @return LoggerInterface|null The logger, or null if no logger is in use.
     */
    public function logger();
}


text:
<?php
require_once realpath(dirname(__FILE__)) . '/../TestHelper.php';

class Braintree_TextNodeTest extends PHPUnit_Framework_TestCase
{
  function testIs()
  {
      $node = new Braintree_TextNode('field');
      $node->is('value');
      $this->assertEquals(array('is' => 'value'), $node->toParam());
  }

  function testIsNot()
  {
      $node = new Braintree_TextNode('field');
      $node->isNot('value');
      $this->assertEquals(array('is_not' => 'value'), $node->toParam());
  }

  function testStartsWith()
  {
      $node = new Braintree_TextNode('field');
      $node->startsWith('beginning');
      $this->assertEquals(array('starts_with' => 'beginning'), $node->toParam());
  }

  function testEndsWith()
  {
      $node = new Braintree_TextNode('field');
      $node->endsWith('end');
      $this->assertEquals(array('ends_with' => 'end'), $node->toParam());
  }

  function testContains()
  {
      $node = new Braintree_TextNode('field');
      $node->contains('middle');
      $this->assertEquals(array('contains' => 'middle'), $node->toParam());
  }
}


text:
page_title: "config.vm - Vagrantfile"
sidebar_current: "vagrantfile-machine"
---

# Machine Settings

**Config namespace: `config.vm`**

The settings within `config.vm` modify the configuration of the
machine that Vagrant manages.

## Available Settings

`config.vm.boot_timeout` - The time in seconds that Vagrant will wait
for the machine to boot and be accessible. By default this is 300 seconds.

`config.vm.box` - This configures what [box](/v2/boxes/index.html) the
machine will be brought up against. The value here should match one of
the installed boxes on the system.

`config.vm.box_url` - The URL that the configured box can be found at.
If the box is not installed on the system, it will be retrieved from this
URL when `vagrant up` is run.

`config.vm.graceful_halt_timeout` - The time in seconds that Vagrant will
wait for the machine to gracefully halt when `vagrant halt` is called.
Defaults to 300 seconds.

`config.vm.guest` - The guest OS that will be running within this
machine. This defaults to `:linux`, and Vagrant will auto-detect the
proper distro. Vagrant needs to know this information to perform some
guest OS-specific things such as mounting folders and configuring
networks.

`config.vm.hostname` - The hostname the machine should have. Defaults
to nil. If nil, Vagrant won't manage the hostname. If set to a string,
the hostname will be set on boot.

`config.vm.network` - Configures [networks](/v2/networking/index.html) on
the machine. Please see the networking page for more information.

`config.vm.provider` - Configures [provider-specific configuration](/v2/providers/configuration.html),
which is used to modify settings which are specific to a certain
[provider](/v2/providers/index.html). If the provider you're configuring
doesn't exist or is not setup on the system of the person who runs
`vagrant up`, Vagrant will ignore this configuration block. This allows
a Vagrantfile that is configured for many providers to be shared among
a group of people who may not have all the same providers installed.

`config.vm.provision` - Configures [provisioners](/v2/provisioning/index.html)
on the machine, so that software can be automatically installed and configured
when the machine is created. Please see the page on provisioners for more
information on how this setting works.

`config.vm.synced_folder` - Configures [synced folders](/v2/synced-folders/index.html)
on the machine, so that folders on your host machine can be synced to
and from the guest machine. Please see the page on synced folders for
more information on how this setting works.

`config.vm.usable_port_range` - A range of ports Vagrant can use for
handling port collisions and such. Defaults to `2200..2250`.


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.leo.nanodegree.ui.SpotifyPlayerActivity"
    android:orientation="vertical"
    >

        <include
            layout="@layout/toolbar_widget"/>

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/spotify_player_fragment"
        android:layout_gravity="center_horizontal"
       />
</LinearLayout>


text:
class Pet(object):

    @staticmethod
    def from_list(args_list):
        kwargs = dict()
        type_str = args_list[0]
        if type_str == "Dog":
            pet_clss = Dog
        elif type_str == "Cat":
            pet_clss = Cat
        else:
            raise ValueError("Unknown Pet type '%s'" % type_str)
        return pet_clss(**dict([[args_list[x], args_list[x+1]] for x in range(1, len(args_list)-1, 2)]))

    def __init__(self, **kwargs):
        self.name = kwargs['name']
        self.breed = kwargs['breed']
        self.owner = kwargs.get('owner', None)
        self.color = kwargs['color']

    def was_sold(self):
        if self.owner is not None:
            return True
        else:
            return False

class Cat(Pet):

    def __init__(self, **kwargs):
        Pet.__init__(self, **kwargs)
        self.meows = kwargs.get("meows", True)

class Dog(Pet):

    def __init__(self, **kwargs):
        Pet.__init__(self, **kwargs)
        self.barks = kwargs.get("barks", True)

class FilterablePetStore(object):

    def __iter__(self):
        raise NotImplementedError()

    def filter(self, filter_func):
        return PetStoreView(self, filter_func)

    def was_sold(self):
        return self.filter(lambda pet: pet.was_sold())

    def is_type(self, test_type):
        return self.filter(lambda pet: isinstance(pet, test_type))

    def is_color(self, color):
        return self.filter(lambda pet: pet.color.upper() == color.upper())

    def is_tabby(self):
        return self.filter(lambda pet: pet.color.upper().endswith("TABBY"))

    def as_list(self):
        return [pet for pet in self]

class PetStore(FilterablePetStore):

    def __init__(self, list_of_pets):
        self.pets = list_of_pets

    def __getitem__(self, index):
        assert isinstance(index, int), "Index must be an integer"
        return self.pets[index]

    def __iter__(self):
        return PetStoreView(self, lambda pet: True)

class PetStoreView(FilterablePetStore):

    def __init__(self, pets, filter_func):
        self._pets = pets
        self._location = 0
        self._filter_function = filter_func

    def __iter__(self):
        return self

    def next(self):
        try:
            try:
                next_item = self._pets.next()
            except AttributeError:
                next_item = self._pets[self._location]
                self._location += 1
        except IndexError:
            raise StopIteration()
        if self._filter_function(next_item):
            return next_item
        else:
            return self.next()

class PetStore2(FilterablePetStore):

    def __init__(self, list_of_pets):
        self.pets = list_of_pets

    def __iter__(self):
        return iter(self.pets)

    def filter(self, filter_func):
        return PetStore2(filter(filter_func, self.pets))

    def as_list(self):
        return self.pets

if __name__ == "__main__":
    import cProfile
    import csv

    list_of_pets = []
    with open("pets.csv", "rb") as csv_file:
        reader = csv.reader(csv_file, delimiter="\t", quotechar="|")
        for row in reader:
            list_of_pets.append(Pet.from_list(row))
        del reader

    print "### Profiling iterators for filtering ###"
    print ""
    pets1 = PetStore(list_of_pets)
    cProfile.run('for pet in pets1.is_type(Cat).is_tabby().was_sold(): print pet.name')

    print "### Profiling filter() for filtering ###"
    print ""
    pets2 = PetStore2(list_of_pets)
    cProfile.run('for pet in pets2.is_type(Cat).is_tabby().was_sold(): print pet.name')


text:
const markdown = require('./markdown.md');

const data = {
  id: 'unca',
  school: 'University of North Carolina, Asheville',
  link: 'https://www.unca.edu/',
  city: 'Asheville',
  state: 'NC',
  latitude: -82.565303,
  longitude: 35.616909,
  degree_type: 'BS',
  degree: 'Environmental Studies',
  concentration: 'Earth Science',
  graduation_month: 'May',
  graduation_year: 2010,
  coursework: [
    'Hydrogeology',
    'Mineralogy & Petrology',
    'Environmental Geology',
    'Soils',
    'Ecology and Field Biology',
    'Environmental Ethics',
    'Environmental Management',
    'Environmental Economics',
    'International Relations',
    'Economic Development',
    'Humanities',
    'Introduction to GIS',
  ],
  body: markdown.body,
};

export default data;


text:
@interface PodsDummy_Pods_whisky : NSObject
@end
@implementation PodsDummy_Pods_whisky
@end


text:
#define LOG_TAG "CameraClient"
//#define LOG_NDEBUG 0

#include <cutils/properties.h>
#include <gui/Surface.h>

#include "api1/CameraClient.h"
#include "device1/CameraHardwareInterface.h"
#include "CameraService.h"

namespace android {

#define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__);
#define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__);

static int getCallingPid() {
    return IPCThreadState::self()->getCallingPid();
}

CameraClient::CameraClient(const sp<CameraService>& cameraService,
        const sp<ICameraClient>& cameraClient,
        const String16& clientPackageName,
        int cameraId, int cameraFacing,
        int clientPid, int clientUid,
        int servicePid):
        Client(cameraService, cameraClient, clientPackageName,
                cameraId, cameraFacing, clientPid, clientUid, servicePid)
{
    int callingPid = getCallingPid();
    LOG1("CameraClient::CameraClient E (pid %d, id %d)", callingPid, cameraId);

    mHardware = NULL;
    mMsgEnabled = 0;
    mSurface = 0;
    mPreviewWindow = 0;
    mDestructionStarted = false;

    // Callback is disabled by default
    mPreviewCallbackFlag = CAMERA_FRAME_CALLBACK_FLAG_NOOP;
    mOrientation = getOrientation(0, mCameraFacing == CAMERA_FACING_FRONT);
    mPlayShutterSound = true;
    LOG1("CameraClient::CameraClient X (pid %d, id %d)", callingPid, cameraId);
}

status_t CameraClient::initialize(camera_module_t *module) {
    int callingPid = getCallingPid();
    status_t res;

    LOG1("CameraClient::initialize E (pid %d, id %d)", callingPid, mCameraId);

    // Verify ops permissions
    res = startCameraOps();
    if (res != OK) {
        return res;
    }

    char camera_device_name[10];
    snprintf(camera_device_name, sizeof(camera_device_name), "%d", mCameraId);

    mHardware = new CameraHardwareInterface(camera_device_name);
    res = mHardware->initialize(&module->common);
    if (res != OK) {
        ALOGE("%s: Camera %d: unable to initialize device: %s (%d)",
                __FUNCTION__, mCameraId, strerror(-res), res);
        mHardware.clear();
        return NO_INIT;
    }

    mHardware->setCallbacks(notifyCallback,
            dataCallback,
            dataCallbackTimestamp,
            (void *)mCameraId);

    // Enable zoom, error, focus, and metadata messages by default
    enableMsgType(CAMERA_MSG_ERROR | CAMERA_MSG_ZOOM | CAMERA_MSG_FOCUS |
                  CAMERA_MSG_PREVIEW_METADATA | CAMERA_MSG_FOCUS_MOVE);

    LOG1("CameraClient::initialize X (pid %d, id %d)", callingPid, mCameraId);
    return OK;
}

// tear down the client
CameraClient::~CameraClient() {
    // this lock should never be NULL
    Mutex* lock = mCameraService->getClientLockById(mCameraId);
    lock->lock();
    mDestructionStarted = true;
    // client will not be accessed from callback. should unlock to prevent dead-lock in disconnect
    lock->unlock();
    int callingPid = getCallingPid();
    LOG1("CameraClient::~CameraClient E (pid %d, this %p)", callingPid, this);

    disconnect();
    LOG1("CameraClient::~CameraClient X (pid %d, this %p)", callingPid, this);
}

status_t CameraClient::dump(int fd, const Vector<String16>& args) {
    const size_t SIZE = 256;
    char buffer[SIZE];

    size_t len = snprintf(buffer, SIZE, "Client[%d] (%p) PID: %d\n",
            mCameraId,
            getRemoteCallback()->asBinder().get(),
            mClientPid);
    len = (len > SIZE - 1) ? SIZE - 1 : len;
    write(fd, buffer, len);
    return mHardware->dump(fd, args);
}

// ----------------------------------------------------------------------------

status_t CameraClient::checkPid() const {
    int callingPid = getCallingPid();
    if (callingPid == mClientPid) return NO_ERROR;

    ALOGW("attempt to use a locked camera from a different process"
         " (old pid %d, new pid %d)", mClientPid, callingPid);
    return EBUSY;
}

status_t CameraClient::checkPidAndHardware() const {
    status_t result = checkPid();
    if (result != NO_ERROR) return result;
    if (mHardware == 0) {
        ALOGE("attempt to use a camera after disconnect() (pid %d)", getCallingPid());
        return INVALID_OPERATION;
    }
    return NO_ERROR;
}

status_t CameraClient::lock() {
    int callingPid = getCallingPid();
    LOG1("lock (pid %d)", callingPid);
    Mutex::Autolock lock(mLock);

    // lock camera to this client if the the camera is unlocked
    if (mClientPid == 0) {
        mClientPid = callingPid;
        return NO_ERROR;
    }

    // returns NO_ERROR if the client already owns the camera, EBUSY otherwise
    return checkPid();
}

status_t CameraClient::unlock() {
    int callingPid = getCallingPid();
    LOG1("unlock (pid %d)", callingPid);
    Mutex::Autolock lock(mLock);

    // allow anyone to use camera (after they lock the camera)
    status_t result = checkPid();
    if (result == NO_ERROR) {
        if (mHardware->recordingEnabled()) {
            ALOGE("Not allowed to unlock camera during recording.");
            return INVALID_OPERATION;
        }
        mClientPid = 0;
        LOG1("clear mRemoteCallback (pid %d)", callingPid);
        // we need to remove the reference to ICameraClient so that when the app
        // goes away, the reference count goes to 0.
        mRemoteCallback.clear();
    }
    return result;
}

// connect a new client to the camera
status_t CameraClient::connect(const sp<ICameraClient>& client) {
    int callingPid = getCallingPid();
    LOG1("connect E (pid %d)", callingPid);
    Mutex::Autolock lock(mLock);

    if (mClientPid != 0 && checkPid() != NO_ERROR) {
        ALOGW("Tried to connect to a locked camera (old pid %d, new pid %d)",
                mClientPid, callingPid);
        return EBUSY;
    }

    if (mRemoteCallback != 0 &&
        (client->asBinder() == mRemoteCallback->asBinder())) {
        LOG1("Connect to the same client");
        return NO_ERROR;
    }

    mPreviewCallbackFlag = CAMERA_FRAME_CALLBACK_FLAG_NOOP;
    mClientPid = callingPid;
    mRemoteCallback = client;

    LOG1("connect X (pid %d)", callingPid);
    return NO_ERROR;
}

static void disconnectWindow(const sp<ANativeWindow>& window) {
    if (window != 0) {
        status_t result = native_window_api_disconnect(window.get(),
                NATIVE_WINDOW_API_CAMERA);
        if (result != NO_ERROR) {
            ALOGW("native_window_api_disconnect failed: %s (%d)", strerror(-result),
                    result);
        }
    }
}

void CameraClient::disconnect() {
    int callingPid = getCallingPid();
    LOG1("disconnect E (pid %d)", callingPid);
    Mutex::Autolock lock(mLock);

    // Allow both client and the media server to disconnect at all times
    if (callingPid != mClientPid && callingPid != mServicePid) {
        ALOGW("different client - don't disconnect");
        return;
    }

    if (mClientPid <= 0) {
        LOG1("camera is unlocked (mClientPid = %d), don't tear down hardware", mClientPid);
        return;
    }

    // Make sure disconnect() is done once and once only, whether it is called
    // from the user directly, or called by the destructor.
    if (mHardware == 0) return;

    LOG1("hardware teardown");
    // Before destroying mHardware, we must make sure it's in the
    // idle state.
    // Turn off all messages.
    disableMsgType(CAMERA_MSG_ALL_MSGS);
    mHardware->stopPreview();
    mHardware->cancelPicture();
    // Release the hardware resources.
    mHardware->release();

    // Release the held ANativeWindow resources.
    if (mPreviewWindow != 0) {
        disconnectWindow(mPreviewWindow);
        mPreviewWindow = 0;
        mHardware->setPreviewWindow(mPreviewWindow);
    }
    mHardware.clear();

    CameraService::Client::disconnect();

    LOG1("disconnect X (pid %d)", callingPid);
}

// ----------------------------------------------------------------------------

status_t CameraClient::setPreviewWindow(const sp<IBinder>& binder,
        const sp<ANativeWindow>& window) {
    Mutex::Autolock lock(mLock);
    status_t result = checkPidAndHardware();
    if (result != NO_ERROR) return result;

    // return if no change in surface.
    if (binder == mSurface) {
        return NO_ERROR;
    }

    if (window != 0) {
        result = native_window_api_connect(window.get(), NATIVE_WINDOW_API_CAMERA);
        if (result != NO_ERROR) {
            ALOGE("native_window_api_connect failed: %s (%d)", strerror(-result),
                    result);
            return result;
        }
    }

    // If preview has been already started, register preview buffers now.
    if (mHardware->previewEnabled()) {
        if (window != 0) {
            native_window_set_scaling_mode(window.get(),
                    NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
            native_window_set_buffers_transform(window.get(), mOrientation);
            result = mHardware->setPreviewWindow(window);
        }
    }

    if (result == NO_ERROR) {
        // Everything has succeeded.  Disconnect the old window and remember the
        // new window.
        disconnectWindow(mPreviewWindow);
        mSurface = binder;
        mPreviewWindow = window;
    } else {
        // Something went wrong after we connected to the new window, so
        // disconnect here.
        disconnectWindow(window);
    }

    return result;
}

// set the buffer consumer that the preview will use
status_t CameraClient::setPreviewTarget(
        const sp<IGraphicBufferProducer>& bufferProducer) {
    LOG1("setPreviewTarget(%p) (pid %d)", bufferProducer.get(),
            getCallingPid());

    sp<IBinder> binder;
    sp<ANativeWindow> window;
    if (bufferProducer != 0) {
        binder = bufferProducer->asBinder();
        // Using controlledByApp flag to ensure that the buffer queue remains in
        // async mode for the old camera API, where many applications depend
        // on that behavior.
        window = new Surface(bufferProducer, /*controlledByApp*/ true);
    }
    return setPreviewWindow(binder, window);
}

// set the preview callback flag to affect how the received frames from
// preview are handled.
void CameraClient::setPreviewCallbackFlag(int callback_flag) {
    LOG1("setPreviewCallbackFlag(%d) (pid %d)", callback_flag, getCallingPid());
    Mutex::Autolock lock(mLock);
    if (checkPidAndHardware() != NO_ERROR) return;

    mPreviewCallbackFlag = callback_flag;
    if (mPreviewCallbackFlag & CAMERA_FRAME_CALLBACK_FLAG_ENABLE_MASK) {
        enableMsgType(CAMERA_MSG_PREVIEW_FRAME);
    } else {
        disableMsgType(CAMERA_MSG_PREVIEW_FRAME);
    }
}

status_t CameraClient::setPreviewCallbackTarget(
        const sp<IGraphicBufferProducer>& callbackProducer) {
    (void)callbackProducer;
    ALOGE("%s: Unimplemented!", __FUNCTION__);
    return INVALID_OPERATION;
}

// start preview mode
status_t CameraClient::startPreview() {
    LOG1("startPreview (pid %d)", getCallingPid());
    return startCameraMode(CAMERA_PREVIEW_MODE);
}

// start recording mode
status_t CameraClient::startRecording() {
    LOG1("startRecording (pid %d)", getCallingPid());
    return startCameraMode(CAMERA_RECORDING_MODE);
}

// start preview or recording
status_t CameraClient::startCameraMode(camera_mode mode) {
    LOG1("startCameraMode(%d)", mode);
    Mutex::Autolock lock(mLock);
    status_t result = checkPidAndHardware();
    if (result != NO_ERROR) return result;

    switch(mode) {
        case CAMERA_PREVIEW_MODE:
            if (mSurface == 0 && mPreviewWindow == 0) {
                LOG1("mSurface is not set yet.");
                // still able to start preview in this case.
            }
            return startPreviewMode();
        case CAMERA_RECORDING_MODE:
            if (mSurface == 0 && mPreviewWindow == 0) {
                ALOGE("mSurface or mPreviewWindow must be set before startRecordingMode.");
                return INVALID_OPERATION;
            }
            return startRecordingMode();
        default:
            return UNKNOWN_ERROR;
    }
}

status_t CameraClient::startPreviewMode() {
    LOG1("startPreviewMode");
    status_t result = NO_ERROR;

    // if preview has been enabled, nothing needs to be done
    if (mHardware->previewEnabled()) {
        return NO_ERROR;
    }

    if (mPreviewWindow != 0) {
        native_window_set_scaling_mode(mPreviewWindow.get(),
                NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
        native_window_set_buffers_transform(mPreviewWindow.get(),
                mOrientation);
    }
    mHardware->setPreviewWindow(mPreviewWindow);
    result = mHardware->startPreview();

    return result;
}

status_t CameraClient::startRecordingMode() {
    LOG1("startRecordingMode");
    status_t result = NO_ERROR;

    // if recording has been enabled, nothing needs to be done
    if (mHardware->recordingEnabled()) {
        return NO_ERROR;
    }

    // if preview has not been started, start preview first
    if (!mHardware->previewEnabled()) {
        result = startPreviewMode();
        if (result != NO_ERROR) {
            return result;
        }
    }

    // start recording mode
    enableMsgType(CAMERA_MSG_VIDEO_FRAME);
    mCameraService->playSound(CameraService::SOUND_RECORDING);
    result = mHardware->startRecording();
    if (result != NO_ERROR) {
        ALOGE("mHardware->startRecording() failed with status %d", result);
    }
    return result;
}

// stop preview mode
void CameraClient::stopPreview() {
    LOG1("stopPreview (pid %d)", getCallingPid());
    Mutex::Autolock lock(mLock);
    if (checkPidAndHardware() != NO_ERROR) return;

    disableMsgType(CAMERA_MSG_PREVIEW_FRAME);
    mHardware->stopPreview();

    mPreviewBuffer.clear();
}

// stop recording mode
void CameraClient::stopRecording() {
    LOG1("stopRecording (pid %d)", getCallingPid());
    Mutex::Autolock lock(mLock);
    if (checkPidAndHardware() != NO_ERROR) return;

    disableMsgType(CAMERA_MSG_VIDEO_FRAME);
    mHardware->stopRecording();
    mCameraService->playSound(CameraService::SOUND_RECORDING);

    mPreviewBuffer.clear();
}

// release a recording frame
void CameraClient::releaseRecordingFrame(const sp<IMemory>& mem) {
    Mutex::Autolock lock(mLock);
    if (checkPidAndHardware() != NO_ERROR) return;
    mHardware->releaseRecordingFrame(mem);
}

status_t CameraClient::storeMetaDataInBuffers(bool enabled)
{
    LOG1("storeMetaDataInBuffers: %s", enabled? "true": "false");
    Mutex::Autolock lock(mLock);
    if (checkPidAndHardware() != NO_ERROR) {
        return UNKNOWN_ERROR;
    }
    return mHardware->storeMetaDataInBuffers(enabled);
}

bool CameraClient::previewEnabled() {
    LOG1("previewEnabled (pid %d)", getCallingPid());

    Mutex::Autolock lock(mLock);
    if (checkPidAndHardware() != NO_ERROR) return false;
    return mHardware->previewEnabled();
}

bool CameraClient::recordingEnabled() {
    LOG1("recordingEnabled (pid %d)", getCallingPid());

    Mutex::Autolock lock(mLock);
    if (checkPidAndHardware() != NO_ERROR) return false;
    return mHardware->recordingEnabled();
}

status_t CameraClient::autoFocus() {
    LOG1("autoFocus (pid %d)", getCallingPid());

    Mutex::Autolock lock(mLock);
    status_t result = checkPidAndHardware();
    if (result != NO_ERROR) return result;

    return mHardware->autoFocus();
}

status_t CameraClient::cancelAutoFocus() {
    LOG1("cancelAutoFocus (pid %d)", getCallingPid());

    Mutex::Autolock lock(mLock);
    status_t result = checkPidAndHardware();
    if (result != NO_ERROR) return result;

    return mHardware->cancelAutoFocus();
}

// take a picture - image is returned in callback
status_t CameraClient::takePicture(int msgType) {
    LOG1("takePicture (pid %d): 0x%x", getCallingPid(), msgType);

    Mutex::Autolock lock(mLock);
    status_t result = checkPidAndHardware();
    if (result != NO_ERROR) return result;

    if ((msgType & CAMERA_MSG_RAW_IMAGE) &&
        (msgType & CAMERA_MSG_RAW_IMAGE_NOTIFY)) {
        ALOGE("CAMERA_MSG_RAW_IMAGE and CAMERA_MSG_RAW_IMAGE_NOTIFY"
                " cannot be both enabled");
        return BAD_VALUE;
    }

    // We only accept picture related message types
    // and ignore other types of messages for takePicture().
    int picMsgType = msgType
                        & (CAMERA_MSG_SHUTTER |
                           CAMERA_MSG_POSTVIEW_FRAME |
                           CAMERA_MSG_RAW_IMAGE |
                           CAMERA_MSG_RAW_IMAGE_NOTIFY |
                           CAMERA_MSG_COMPRESSED_IMAGE);

    enableMsgType(picMsgType);

    return mHardware->takePicture();
}

// set preview/capture parameters - key/value pairs
status_t CameraClient::setParameters(const String8& params) {
    LOG1("setParameters (pid %d) (%s)", getCallingPid(), params.string());

    Mutex::Autolock lock(mLock);
    status_t result = checkPidAndHardware();
    if (result != NO_ERROR) return result;

    CameraParameters p(params);
    return mHardware->setParameters(p);
}

// get preview/capture parameters - key/value pairs
String8 CameraClient::getParameters() const {
    Mutex::Autolock lock(mLock);
    if (checkPidAndHardware() != NO_ERROR) return String8();

    String8 params(mHardware->getParameters().flatten());
    LOG1("getParameters (pid %d) (%s)", getCallingPid(), params.string());
    return params;
}

// enable shutter sound
status_t CameraClient::enableShutterSound(bool enable) {
    LOG1("enableShutterSound (pid %d)", getCallingPid());

    status_t result = checkPidAndHardware();
    if (result != NO_ERROR) return result;

    if (enable) {
        mPlayShutterSound = true;
        return OK;
    }

    // Disabling shutter sound may not be allowed. In that case only
    // allow the mediaserver process to disable the sound.
    char value[PROPERTY_VALUE_MAX];
    property_get("ro.camera.sound.forced", value, "0");
    if (strcmp(value, "0") != 0) {
        // Disabling shutter sound is not allowed. Deny if the current
        // process is not mediaserver.
        if (getCallingPid() != getpid()) {
            ALOGE("Failed to disable shutter sound. Permission denied (pid %d)", getCallingPid());
            return PERMISSION_DENIED;
        }
    }

    mPlayShutterSound = false;
    return OK;
}

status_t CameraClient::sendCommand(int32_t cmd, int32_t arg1, int32_t arg2) {
    LOG1("sendCommand (pid %d)", getCallingPid());
    int orientation;
    Mutex::Autolock lock(mLock);
    status_t result = checkPidAndHardware();
    if (result != NO_ERROR) return result;

    if (cmd == CAMERA_CMD_SET_DISPLAY_ORIENTATION) {
        // Mirror the preview if the camera is front-facing.
        orientation = getOrientation(arg1, mCameraFacing == CAMERA_FACING_FRONT);
        if (orientation == -1) return BAD_VALUE;

        if (mOrientation != orientation) {
            mOrientation = orientation;
            if (mPreviewWindow != 0) {
                native_window_set_buffers_transform(mPreviewWindow.get(),
                        mOrientation);
            }
        }
        return OK;
    } else if (cmd == CAMERA_CMD_ENABLE_SHUTTER_SOUND) {
        switch (arg1) {
            case 0:
                return enableShutterSound(false);
            case 1:
                return enableShutterSound(true);
            default:
                return BAD_VALUE;
        }
        return OK;
    } else if (cmd == CAMERA_CMD_PLAY_RECORDING_SOUND) {
        mCameraService->playSound(CameraService::SOUND_RECORDING);
    } else if (cmd == CAMERA_CMD_SET_VIDEO_BUFFER_COUNT) {
        // Silently ignore this command
        return INVALID_OPERATION;
    } else if (cmd == CAMERA_CMD_PING) {
        // If mHardware is 0, checkPidAndHardware will return error.
        return OK;
    }

    return mHardware->sendCommand(cmd, arg1, arg2);
}

// ----------------------------------------------------------------------------

void CameraClient::enableMsgType(int32_t msgType) {
    android_atomic_or(msgType, &mMsgEnabled);
    mHardware->enableMsgType(msgType);
}

void CameraClient::disableMsgType(int32_t msgType) {
    android_atomic_and(~msgType, &mMsgEnabled);
    mHardware->disableMsgType(msgType);
}

#define CHECK_MESSAGE_INTERVAL 10 // 10ms
bool CameraClient::lockIfMessageWanted(int32_t msgType) {
    int sleepCount = 0;
    while (mMsgEnabled & msgType) {
        if (mLock.tryLock() == NO_ERROR) {
            if (sleepCount > 0) {
                LOG1("lockIfMessageWanted(%d): waited for %d ms",
                    msgType, sleepCount * CHECK_MESSAGE_INTERVAL);
            }
            return true;
        }
        if (sleepCount++ == 0) {
            LOG1("lockIfMessageWanted(%d): enter sleep", msgType);
        }
        usleep(CHECK_MESSAGE_INTERVAL * 1000);
    }
    ALOGW("lockIfMessageWanted(%d): dropped unwanted message", msgType);
    return false;
}

// Callback messages can be dispatched to internal handlers or pass to our
// client's callback functions, depending on the message type.
//
// notifyCallback:
//      CAMERA_MSG_SHUTTER              handleShutter
//      (others)                        c->notifyCallback
// dataCallback:
//      CAMERA_MSG_PREVIEW_FRAME        handlePreviewData
//      CAMERA_MSG_POSTVIEW_FRAME       handlePostview
//      CAMERA_MSG_RAW_IMAGE            handleRawPicture
//      CAMERA_MSG_COMPRESSED_IMAGE     handleCompressedPicture
//      (others)                        c->dataCallback
// dataCallbackTimestamp
//      (others)                        c->dataCallbackTimestamp
//
// NOTE: the *Callback functions grab mLock of the client before passing
// control to handle* functions. So the handle* functions must release the
// lock before calling the ICameraClient's callbacks, so those callbacks can
// invoke methods in the Client class again (For example, the preview frame
// callback may want to releaseRecordingFrame). The handle* functions must
// release the lock after all accesses to member variables, so it must be
// handled very carefully.

void CameraClient::notifyCallback(int32_t msgType, int32_t ext1,
        int32_t ext2, void* user) {
    LOG2("notifyCallback(%d)", msgType);

    Mutex* lock = getClientLockFromCookie(user);
    if (lock == NULL) return;
    Mutex::Autolock alock(*lock);

    CameraClient* client =
            static_cast<CameraClient*>(getClientFromCookie(user));
    if (client == NULL) return;

    if (!client->lockIfMessageWanted(msgType)) return;

    switch (msgType) {
        case CAMERA_MSG_SHUTTER:
            // ext1 is the dimension of the yuv picture.
            client->handleShutter();
            break;
        default:
            client->handleGenericNotify(msgType, ext1, ext2);
            break;
    }
}

void CameraClient::dataCallback(int32_t msgType,
        const sp<IMemory>& dataPtr, camera_frame_metadata_t *metadata, void* user) {
    LOG2("dataCallback(%d)", msgType);

    Mutex* lock = getClientLockFromCookie(user);
    if (lock == NULL) return;
    Mutex::Autolock alock(*lock);

    CameraClient* client =
            static_cast<CameraClient*>(getClientFromCookie(user));
    if (client == NULL) return;

    if (!client->lockIfMessageWanted(msgType)) return;
    if (dataPtr == 0 && metadata == NULL) {
        ALOGE("Null data returned in data callback");
        client->handleGenericNotify(CAMERA_MSG_ERROR, UNKNOWN_ERROR, 0);
        return;
    }

    switch (msgType & ~CAMERA_MSG_PREVIEW_METADATA) {
        case CAMERA_MSG_PREVIEW_FRAME:
            client->handlePreviewData(msgType, dataPtr, metadata);
            break;
        case CAMERA_MSG_POSTVIEW_FRAME:
            client->handlePostview(dataPtr);
            break;
        case CAMERA_MSG_RAW_IMAGE:
            client->handleRawPicture(dataPtr);
            break;
        case CAMERA_MSG_COMPRESSED_IMAGE:
            client->handleCompressedPicture(dataPtr);
            break;
        default:
            client->handleGenericData(msgType, dataPtr, metadata);
            break;
    }
}

void CameraClient::dataCallbackTimestamp(nsecs_t timestamp,
        int32_t msgType, const sp<IMemory>& dataPtr, void* user) {
    LOG2("dataCallbackTimestamp(%d)", msgType);

    Mutex* lock = getClientLockFromCookie(user);
    if (lock == NULL) return;
    Mutex::Autolock alock(*lock);

    CameraClient* client =
            static_cast<CameraClient*>(getClientFromCookie(user));
    if (client == NULL) return;

    if (!client->lockIfMessageWanted(msgType)) return;

    if (dataPtr == 0) {
        ALOGE("Null data returned in data with timestamp callback");
        client->handleGenericNotify(CAMERA_MSG_ERROR, UNKNOWN_ERROR, 0);
        return;
    }

    client->handleGenericDataTimestamp(timestamp, msgType, dataPtr);
}

// snapshot taken callback
void CameraClient::handleShutter(void) {
    if (mPlayShutterSound) {
        mCameraService->playSound(CameraService::SOUND_SHUTTER);
    }

    sp<ICameraClient> c = mRemoteCallback;
    if (c != 0) {
        mLock.unlock();
        c->notifyCallback(CAMERA_MSG_SHUTTER, 0, 0);
        if (!lockIfMessageWanted(CAMERA_MSG_SHUTTER)) return;
    }
    disableMsgType(CAMERA_MSG_SHUTTER);

    mLock.unlock();
}

// preview callback - frame buffer update
void CameraClient::handlePreviewData(int32_t msgType,
                                              const sp<IMemory>& mem,
                                              camera_frame_metadata_t *metadata) {
    ssize_t offset;
    size_t size;
    sp<IMemoryHeap> heap = mem->getMemory(&offset, &size);

    // local copy of the callback flags
    int flags = mPreviewCallbackFlag;

    // is callback enabled?
    if (!(flags & CAMERA_FRAME_CALLBACK_FLAG_ENABLE_MASK)) {
        // If the enable bit is off, the copy-out and one-shot bits are ignored
        LOG2("frame callback is disabled");
        mLock.unlock();
        return;
    }

    // hold a strong pointer to the client
    sp<ICameraClient> c = mRemoteCallback;

    // clear callback flags if no client or one-shot mode
    if (c == 0 || (mPreviewCallbackFlag & CAMERA_FRAME_CALLBACK_FLAG_ONE_SHOT_MASK)) {
        LOG2("Disable preview callback");
        mPreviewCallbackFlag &= ~(CAMERA_FRAME_CALLBACK_FLAG_ONE_SHOT_MASK |
                                  CAMERA_FRAME_CALLBACK_FLAG_COPY_OUT_MASK |
                                  CAMERA_FRAME_CALLBACK_FLAG_ENABLE_MASK);
        disableMsgType(CAMERA_MSG_PREVIEW_FRAME);
    }

    if (c != 0) {
        // Is the received frame copied out or not?
        if (flags & CAMERA_FRAME_CALLBACK_FLAG_COPY_OUT_MASK) {
            LOG2("frame is copied");
            copyFrameAndPostCopiedFrame(msgType, c, heap, offset, size, metadata);
        } else {
            LOG2("frame is forwarded");
            mLock.unlock();
            c->dataCallback(msgType, mem, metadata);
        }
    } else {
        mLock.unlock();
    }
}

// picture callback - postview image ready
void CameraClient::handlePostview(const sp<IMemory>& mem) {
    disableMsgType(CAMERA_MSG_POSTVIEW_FRAME);

    sp<ICameraClient> c = mRemoteCallback;
    mLock.unlock();
    if (c != 0) {
        c->dataCallback(CAMERA_MSG_POSTVIEW_FRAME, mem, NULL);
    }
}

// picture callback - raw image ready
void CameraClient::handleRawPicture(const sp<IMemory>& mem) {
    disableMsgType(CAMERA_MSG_RAW_IMAGE);

    ssize_t offset;
    size_t size;
    sp<IMemoryHeap> heap = mem->getMemory(&offset, &size);

    sp<ICameraClient> c = mRemoteCallback;
    mLock.unlock();
    if (c != 0) {
        c->dataCallback(CAMERA_MSG_RAW_IMAGE, mem, NULL);
    }
}

// picture callback - compressed picture ready
void CameraClient::handleCompressedPicture(const sp<IMemory>& mem) {
    disableMsgType(CAMERA_MSG_COMPRESSED_IMAGE);

    sp<ICameraClient> c = mRemoteCallback;
    mLock.unlock();
    if (c != 0) {
        c->dataCallback(CAMERA_MSG_COMPRESSED_IMAGE, mem, NULL);
    }
}

void CameraClient::handleGenericNotify(int32_t msgType,
    int32_t ext1, int32_t ext2) {
    sp<ICameraClient> c = mRemoteCallback;
    mLock.unlock();
    if (c != 0) {
        c->notifyCallback(msgType, ext1, ext2);
    }
}

void CameraClient::handleGenericData(int32_t msgType,
    const sp<IMemory>& dataPtr, camera_frame_metadata_t *metadata) {
    sp<ICameraClient> c = mRemoteCallback;
    mLock.unlock();
    if (c != 0) {
        c->dataCallback(msgType, dataPtr, metadata);
    }
}

void CameraClient::handleGenericDataTimestamp(nsecs_t timestamp,
    int32_t msgType, const sp<IMemory>& dataPtr) {
    sp<ICameraClient> c = mRemoteCallback;
    mLock.unlock();
    if (c != 0) {
        c->dataCallbackTimestamp(timestamp, msgType, dataPtr);
    }
}

void CameraClient::copyFrameAndPostCopiedFrame(
        int32_t msgType, const sp<ICameraClient>& client,
        const sp<IMemoryHeap>& heap, size_t offset, size_t size,
        camera_frame_metadata_t *metadata) {
    LOG2("copyFrameAndPostCopiedFrame");
    // It is necessary to copy out of pmem before sending this to
    // the callback. For efficiency, reuse the same MemoryHeapBase
    // provided it's big enough. Don't allocate the memory or
    // perform the copy if there's no callback.
    // hold the preview lock while we grab a reference to the preview buffer
    sp<MemoryHeapBase> previewBuffer;

    if (mPreviewBuffer == 0) {
        mPreviewBuffer = new MemoryHeapBase(size, 0, NULL);
    } else if (size > mPreviewBuffer->virtualSize()) {
        mPreviewBuffer.clear();
        mPreviewBuffer = new MemoryHeapBase(size, 0, NULL);
    }
    if (mPreviewBuffer == 0) {
        ALOGE("failed to allocate space for preview buffer");
        mLock.unlock();
        return;
    }
    previewBuffer = mPreviewBuffer;

    memcpy(previewBuffer->base(), (uint8_t *)heap->base() + offset, size);

    sp<MemoryBase> frame = new MemoryBase(previewBuffer, 0, size);
    if (frame == 0) {
        ALOGE("failed to allocate space for frame callback");
        mLock.unlock();
        return;
    }

    mLock.unlock();
    client->dataCallback(msgType, frame, metadata);
}

int CameraClient::getOrientation(int degrees, bool mirror) {
    if (!mirror) {
        if (degrees == 0) return 0;
        else if (degrees == 90) return HAL_TRANSFORM_ROT_90;
        else if (degrees == 180) return HAL_TRANSFORM_ROT_180;
        else if (degrees == 270) return HAL_TRANSFORM_ROT_270;
    } else {  // Do mirror (horizontal flip)
        if (degrees == 0) {           // FLIP_H and ROT_0
            return HAL_TRANSFORM_FLIP_H;
        } else if (degrees == 90) {   // FLIP_H and ROT_90
            return HAL_TRANSFORM_FLIP_H | HAL_TRANSFORM_ROT_90;
        } else if (degrees == 180) {  // FLIP_H and ROT_180
            return HAL_TRANSFORM_FLIP_V;
        } else if (degrees == 270) {  // FLIP_H and ROT_270
            return HAL_TRANSFORM_FLIP_V | HAL_TRANSFORM_ROT_90;
        }
    }
    ALOGE("Invalid setDisplayOrientation degrees=%d", degrees);
    return -1;
}

}; // namespace android


text:
@protocol NBCOptionBuildPanelDelegate
@optional
- (void)continueWorkflow:(NSDictionary *)preWorkflowTasks;
@end

@interface NBCOptionBuildPanel : NSWindowController {
    id _delegate;
}

@property (weak) id settingsViewController;
@property (strong) IBOutlet NSWindow *windowOptionWindow;

@property (weak) IBOutlet NSButton *checkboxClearSourceCache;
@property (weak) IBOutlet NSPopUpButton *popUpButtonClearSourceCache;
@property (weak) IBOutlet NSPopUpButton *pupUpButtonChangeLogLevel;

@property (weak) IBOutlet NSButton *buttonContinue;
- (IBAction)buttonContinue:(id)sender;
- (IBAction)buttonCancel:(id)sender;

- (id)initWithDelegate:(id<NBCOptionBuildPanelDelegate>)delegate;

@end


text:
(* ::Package:: *)

BeginPackage["sierpinskifractalnet3D`",{"sierpinskifractalnet2D`"}]
fractalNetModule3D::usage="fractalNetModule3D: Displays folding between 2D and 3D fractal net."
Begin["`Private`"]
(*******************************************************************)
(*Begin: 3D Unfolding Code*)(*******************************************************************)(*******************************************************************)
(*Documentation: applyRotationStack*)applyRotationStack::usage="applyRotationStack: Applies a rotation transform to a 3D triangle, using a stack of rotations.";
(*Function: applyRotationStack*)
applyRotationStack[point_,rotations_]:=Fold[(RotationTransform@@#2)[#1]&,point,rotations];
(*******************************************************************)
(*******************************************************************)
(*Documentation: drawFolded3D*)
drawFolded3D::usage="drawFolded3D: Unfolds and displays a tetrahedron with extra rotation information,using a stack of rotation information,i.e.multiple roatations. Each side of the tetrahedron has it's color.";
(*Function: drawFolded3D*)
drawFolded3D[{{pBLeft_,pBRight_,PBUp_,PTop_},{rotationsBase_,rotations1_,rotations2_,rotations3_}}]:=Graphics3D@{Opacity[1],EdgeForm[{Thickness[Medium],Directive[Black]}],{{Opacity[1],Darker[Green,.6],Specularity[White,50],Polygon[applyRotationStack[{pBLeft,pBRight,PBUp},rotationsBase]]},(*Yellow*){Opacity[1],Darker[Pink,.6],Specularity[White,50],Polygon[applyRotationStack[{pBLeft,pBRight,PTop},rotations1]]},(*Red*){Opacity[1],Darker[Blue,.6],Specularity[White,50],Polygon[applyRotationStack[{pBLeft,PBUp,PTop},rotations2]]},(*Blue*)(*{White,Specularity[GrayLevel[1],200]}*){Opacity[1],Darker[Yellow,.6],Specularity[White,50],Polygon[applyRotationStack[{pBRight,PBUp,PTop},rotations3]]}}}
(*******************************************************************)
(*******************************************************************)
(*Documentation: showFolded3D*)
showFolded3D::usage="showFolded3D: Unfolds and displays a list of tetrahedrons with extra rotation information.";
(*Function: showFolded3D*)
showFolded3D[plist_]:=Show[Map[drawFolded3D,plist]]
(*******************************************************************)
(*******************************************************************)
(*Documentation: midpoint*)
midpoint::usage="midpoint: Computes midpoints a midpoint between two points to be used in the IFS method for generating the fractal.";
(*Function: midpoint*)
midpoint[x_,y_]:=(x+y)/2
(*******************************************************************)
(*******************************************************************)
(*In the 2D code we use only unit Triangle, In 3D code the unit traingle is used as the Base points of the unit Tetrahedron.*)
(*Points on Tetrahedron S0*)
b=N[{-(1/(2 Sqrt[3])),-(1/2),-(1/(2 Sqrt[6]))}];
c=N[{1/Sqrt[3],0,-(1/(2 Sqrt[6]))}];
a=N[{-(1/(2 Sqrt[3])),1/2,-(1/(2 Sqrt[6]))}];
d=N[{0,0,Sqrt[2/3]-1/(2 Sqrt[6])}];
(*******************************************************************)
(*******************************************************************)
(*Midpoints on Tetrehderon,for Subscript[S,1]*)
ab=midpoint[a,b];
ac=midpoint[a,c];
ad=midpoint[a,d];
bc=midpoint[b,c];
bd=midpoint[b,d];
cd=midpoint[c,d];
(*******************************************************************)
(*******************************************************************)
(*Documentation: foldedAngle*)
foldedAngle::usage="foldedAngle: Computes an stores the angle variable to be used in the folds.";
(*Function: foldedAngle*)
foldedAngle=N[Pi-ArcSec[3]];
(*******************************************************************)
(*******************************************************************)
(*Documentation: foldedAngle*)
tetrahedronF0original::usage="tetrahedronF0original: Unit Tetrahdron that unfolds to the first net, takes a list of thetas to unfold at various iterations.";
(*Function: tetrahedronF0original*)
tetrahedronF0original[theta_]:=Module[{angleToChange=theta[[1]]},{{a,b,c,d},{{{0,b-a,a}},{{angleToChange,b-a,b}},{{angleToChange,a-c,c}},{{angleToChange,c-b,c}}}}];
(*******************************************************************)
(*******************************************************************)
(*Documentation: tetrahedronF0new*)
tetrahedronF0new::usage="tetrahedronF0original: Unit tetrahedron that unfolds to the second net.";
(*Function: tetrahedronF0new*)
tetrahedronF0new[theta_]:=Module[{angleToChange=theta[[1]]},{{a,b,c,d},{{{0,b-a,a}},{{angleToChange,b-a,b}},{{angleToChange,d-a,a},{angleToChange,b-a,b}},{{angleToChange,c-b,b}}}}];
(*******************************************************************)
(*******************************************************************)
(*Documentation: computeChildren3D*)
computeChildren3D::usage="computeChildren3D: Takes a tetrahedron and splits it using the IFS, modified by taking into account the roatation method,  where the rotation method is dependent upon the iteration.
\[IndentingNewLine]rotationsBase: the roatation stack for the bottom/base/Gray side of the the current tetrahedron.
\[IndentingNewLine]rotations1: the roatation stack of the yellow side of the current tetreahedron.
\[IndentingNewLine]rotations2: the roatation stack of the red side of the current tetrahedron.
\[IndentingNewLine]rotation3: the roatation stack of the blue side of the current tetreahedron.";
(*Function: computeChildren3D*)
computeChildren3D[{{pBLeft_,pBRight_,pBUp_,pTop_},{rotationsBase_,rotations1_,rotations2_,rotations3_}},theta_,iteration_]:=Module[{pLRMid=midpoint[pBLeft,pBRight],pLUMid=midpoint[pBLeft,pBUp],pRUMid=midpoint[pBRight,pBUp],pLTMid=midpoint[pBLeft,pTop],pRTMid=midpoint[pBRight,pTop],pUTMid=midpoint[pBUp,pTop],angleToChange=-theta[[iteration+2]]},{{{pLTMid,pRTMid,pUTMid,pTop},{Prepend[rotations2,{-angleToChange,pUTMid-pLTMid,pLTMid}],rotations1,rotations2,rotations3}},(*Top Tetrahedron*){{pBLeft,pLRMid,pLUMid,pLTMid},{rotationsBase,rotations1,rotations2,Prepend[rotations1,{angleToChange,pLTMid-pLRMid,pLTMid}]}},(*Left Tetrahedron*){{pLRMid,pBRight,pRUMid,pRTMid},{rotationsBase,rotations1,Prepend[rotationsBase,{-angleToChange,pLTMid-pUTMid,pRUMid}],rotations3}},(*"Middle" Tetrahedron*){{pLUMid,pRUMid,pBUp,pUTMid},{rotationsBase,Prepend[rotations3,{-angleToChange,pUTMid-pRUMid,pUTMid}],rotations2,rotations3}} (*Right Tetrahedron*)}]
(*******************************************************************)
(*******************************************************************)
(*Documentation: recursivelyCreateChildren3D*)
recursivelyCreateChildren3D::usage="computeChildren3D: Takes an argument,iteration,maxIterations,start,theta.iteration:determines the iteration.maxIterations:determines when to stop,calls function till interation greater the maxIterations.Where theta is a list of angles to use for subrotations dependent upon the iteration";
(*Function: recursivelyCreateChildren3D*)
recursivelyCreateChildren3D[iteration_,maxIterations_,start_,theta_]:=Which[maxIterations==0,start,iteration>=maxIterations,start,True,recursivelyCreateChildren3D[iteration+1,maxIterations,Flatten[Map[computeChildren3D[#,theta,iteration]&,start],1],theta]]
(*******************************************************************)
(*******************************************************************)
(*Documentation: foldedSierpinski*)
foldedSierpinski::usage="computeChildren3D: set intial conditions for recursivelyCreateChildren3D.";
(*Function: foldedSierpinski*)
foldedSierpinski[iteration_,theta_,net_]:=
If[net,
If[iteration==0,{tetrahedronF0new[theta]},
recursivelyCreateChildren3D[0,iteration,{tetrahedronF0new[theta]},theta]],
If[iteration==0,{tetrahedronF0original[theta]},
recursivelyCreateChildren3D[0,iteration,{tetrahedronF0original[theta]},theta]]]
(*******************************************************************)
(*******************************************************************)
(*Documentation: FoldingModule1*)
FoldingModule1::usage="FoldingModule1: Folding module with sub-folding capablites.";
(*Function: FoldingModule1*)
FoldingModule1=DynamicModule[{n=0,theta=Table[foldedAngle,{i,5}],net=False},Column[{Checkbox[Dynamic[net]],
SetterBar[Dynamic[n],{0,1,2,3}],Dynamic[Column[Table[With[{i=i},Slider[Dynamic[theta[[i]]],{foldedAngle,0}]],{i,n+1}]]],
Dynamic[Show[showFolded3D[foldedSierpinski[n,theta,net]],Axes->True,AxesOrigin->{0,0,-(1/(2 Sqrt[6]))},AxesStyle->Directive[Dotted,Italic,Black],Ticks->{{-1,1},{-1,1},{-1,1}},AxesLabel->{"x","y","z"},PlotRange->1.5,FaceGrids->{{0,-1,0},{-1,0,0},{0,0,-1}},FaceGridsStyle->Directive[Thickness[.001],LightGray,Dotted],Boxed->False,Axes->True,AxesStyle->Thickness[.001],Background->White,Lighting->"Neutral"]]}]];
(*******************************************************************)
(*******************************************************************)
(*Documentation: FoldingModule2*)
FoldingModule2::usage="FoldingModule2: Folding module that folds all iterations.";
(*Function: FoldingModule2*)
FoldingModule2=DynamicModule[{n=0,alphatheta=0,net=False},Column[{Checkbox[Dynamic[net]],SetterBar[Dynamic[n],{0,1,2,3}],Slider[Dynamic[alphatheta],{0,foldedAngle}],
Dynamic[Show[showFolded3D[foldedSierpinski[n,Table[foldedAngle-alphatheta,{i,5}],net]],Axes->True,AxesOrigin->{0,0,-(1/(2 Sqrt[6]))},AxesStyle->Directive[Dotted,Italic,Black],Ticks->{{-1,1},{-1,1},{-1,1}},AxesLabel->{"x","y","z"},PlotRange->1.5,FaceGrids->{{0,-1,0},{-1,0,0},{0,0,-1}},FaceGridsStyle->Directive[Thickness[.001],LightGray,Dotted],Boxed->False,Axes->True,AxesStyle->Thickness[.001],Background->Black,Lighting->"Neutral"]]}]];
(*******************************************************************)
(*******************************************************************)
(*End: 3D Unfolding Code*)(*******************************************************************)

(*Vertex Coordinates for Net 1*)
net1ptsS0={(*Perimeter Vertices Net1*)
(*Subscript[d, 1]*){-2/Sqrt[3],0,-1/(2Sqrt[6])},
(*Subscript[d, 2]*){1/Sqrt[3],-1,-1/(2Sqrt[6])},
(*Subscript[d, 3]*){1/Sqrt[3],1,-1/(2Sqrt[6])},
(*Midpoint Vertices Subscript[S, 0]*)
(*a=PBleft*){-1/(2Sqrt[3]),-1/2,-1/(2Sqrt[6])},
(*b=PBup*){-1/(2Sqrt[3]),1/2,-1/(2Sqrt[6])},
(*c=PBright*){1/Sqrt[3],0,-1/(2Sqrt[6])}};

net1ptsS1={(*Perimeter Vertices Net1*)
(*Subscript[d, 1]*){-2/Sqrt[3],0,-1/(2Sqrt[6])},
(*Subscript[d, 2]*){1/Sqrt[3],-1,-1/(2Sqrt[6])},
(*Subscript[d, 3]*){1/Sqrt[3],1,-1/(2Sqrt[6])},
(*Midpoint Vertices Subscript[S, 0]*)
(*a=PBleft*){-1/(2Sqrt[3]),-1/2,-1/(2Sqrt[6])},
(*b=PBup*){-1/(2Sqrt[3]),1/2,-1/(2Sqrt[6])},
(*c=PBright*){1/Sqrt[3],0,-1/(2Sqrt[6])}};

(*Vertex Coordinates for Net 2*)
net2pts={(*Perimeter Vertices Net2*)
(*1*){-2/Sqrt[3],0,-1/(2Sqrt[6])},
(*2*){1/Sqrt[3],-1,-1/(2Sqrt[6])},
(*3*){-2/Sqrt[3],1,-1/(2Sqrt[6])},
(*Midpoint Vertices Subscript[S, 0]*)
(*4*){-1/(2Sqrt[3]),-1/2,-1/(2Sqrt[6])},
(*5*){-1/(2Sqrt[3]),1/2,-1/(2Sqrt[6])},
(*6*){1/Sqrt[3],0,-1/(2Sqrt[6])}};
pts3D={{0,0,Sqrt[2/3]-1/(2Sqrt[6])},
(*4*){-1/(2Sqrt[3]),-1/2,-1/(2Sqrt[6])},
(*5*){-1/(2Sqrt[3]),1/2,-1/(2Sqrt[6])},
(*6*){1/Sqrt[3],0,-1/(2Sqrt[6])}};
(*Labels*)
labelsNetOneS0={"\!\(\*SubscriptBox[\(x\), \(00\)]\)","\!\(\*SubscriptBox[\(x\), \(01\)]\)","\!\(\*SubscriptBox[\(x\), \(02\)]\)","\!\(\*SubscriptBox[\(x\), \(03\)]\)","\!\(\*SubscriptBox[\(x\), \(04\)]\)","\!\(\*SubscriptBox[\(x\), \(05\)]\)"};
labelsNetTwoS0={"\!\(\*SubscriptBox[\(x\), \(0\)]\)","\!\(\*SubscriptBox[\(x\), \(0, 0\)]\)","\!\(\*SubscriptBox[\(x\), \(0, 3\)]\)","\!\(\*SubscriptBox[\(x\), \(0, 2\)]\)","\!\(\*SubscriptBox[\(x\), \(0, 1\)]\)","\!\(\*SubscriptBox[\(x\), \(0, 3\)]\)"};
(*Labels*)
labelsNetOneS1={Text[Style["\!\(\*SubscriptBox[\(u\), \(0\)]\)",Large,Bold]],Text[Style["\!\(\*SubscriptBox[\(u\), \(1\)]\)",Large,Bold]],Text[Style["\!\(\*SubscriptBox[\(u\), \(2\)]\)",Large,Bold]],"\!\(\*SubscriptBox[\(x\), \(01\)]\)","\!\(\*SubscriptBox[\(x\), \(02\)]\)","\!\(\*SubscriptBox[\(x\), \(12\)]\)","\!\(\*SubscriptBox[\(u\), \(0\)]\)","\!\(\*SubscriptBox[\(u\), \(0\)]\)","\!\(\*SubscriptBox[\(x\), \(0, 0\)]\)","\!\(\*SubscriptBox[\(x\), \(0, 2\)]\)","\!\(\*SubscriptBox[\(x\), \(0, 1\)]\)","\!\(\*SubscriptBox[\(x\), \(0, 3\)]\)","\!\(\*SubscriptBox[\(x\), \(0, 0\)]\)","\!\(\*SubscriptBox[\(x\), \(0, 0\)]\)","\!\(\*SubscriptBox[\(x\), \(0, 0\)]\)","\!\(\*SubscriptBox[\(x\), \(0, 2\)]\)"};
(*Labels*)
labels3D={"\!\(\*SubscriptBox[\(u\), \(3\)]\)","\!\(\*SubscriptBox[\(u\), \(1\)]\)","\!\(\*SubscriptBox[\(u\), \(2\)]\)","\!\(\*SubscriptBox[\(u\), \(0\)]\)"};
(*Labels*)
offsets2DNetOne=-{{-1,1},{-1,-1},{1,1},{-1,-1},{-1,1},{1,-1}};
offsets2DNetTwo=-{{-1,-1},{-1,-1},{1,1},{-1,-1},{1,1},{1,1}};
offsets2DNetOneS1=-{{-1,-1},{-1,-1},{1,1},{-1,-1},{1,1},{1,1},{-1,-1},{-1,-1},{1,1},{-1,-1},{1,1},{1,1},{-1,-1},{-1,-1},{1,1}};
offsets3D={{-1,-1},{1,1},{1,-1},{-1,-1}};
(*Labeled Vertex Coordinates for Net 1, Subscript[S, 0]*)
labeledNet1PtsS0=Graphics3D[{PointSize[Large],Point@net1ptsS0,
MapIndexed[Style[Text[First[labelsNetOneS0[[#2]]],#1,First[offsets2DNetOne[[#2]]]],Black,20]&,net1ptsS0]},Boxed->False,Axes->False];
(*Labeled Vertex Coordinates for Net 1, Subscript[S, 1]*)
labeledNet1PtsS1=Graphics3D[{PointSize[Large],Point@net1ptsS0,
MapIndexed[Style[Text[First[labelsNetOneS1[[#2]]],#1,First[offsets2DNetOneS1[[#2]]]],Black,20]&,net1ptsS1]},Boxed->False,Axes->False];
(*Labeled Vertex Coordinates for Net 2*)
labeledNet2pts=Graphics3D[{PointSize[Large],Point@net2pts,
MapIndexed[Style[Text[First[labelsNetTwoS0[[#2]]],#1,First[offsets2DNetTwo[[#2]]]],Black,20]&,net2pts]},Boxed->False,Axes->False];
labeled3DPts=Graphics3D[{PointSize[Large],Point@pts3D,
MapIndexed[Style[Text[First[labels3D[[#2]]],#1,First[offsets3D[[#2]]]],Black,20]&,pts3D]},Boxed->False,Axes->False];

fractalNetModule3D=DynamicModule[{alphatheta=0},Column[{Panel[Grid[{{"n",SetterBar[Dynamic[n],{0,1,2,3}]},{"net",Checkbox[Dynamic[net]]},{"Fold",Slider[Dynamic[alphatheta],{0,foldedAngle}]}},Alignment->Left,ItemSize->{{10,40}}],ImageSize-> {600,125},Background->White],
Dynamic[Show[If[alphatheta>foldedAngle-10^-6,labeled3DPts,If[net,labeledNet2pts,labeledNet1PtsS1]],
showFolded3D[foldedSierpinski[n,Table[foldedAngle-alphatheta,{i,5}],net]],generateSierpinskiNet[n+1,net],
Boxed->False,ImageSize->{600,600},ViewPoint->{0.18,-1,0.542},ViewAngle->0.69115,PlotRange->1.5,Background->White,Lighting->"Neutral",
Axes->True,AxesOrigin->{0,0,0},AxesStyle->Directive[Dotted,Italic,Black,Thin]]]}]];

End[ ]
EndPackage[ ]


text:
using std::string;
using namespace v8;
using namespace protagonist;

NAN_METHOD(protagonist::ParseSync) {
    Nan::HandleScope scope;

    // Check arguments
    if (info.Length() != 1 && info.Length() != 2) {
        Nan::ThrowTypeError("wrong number of arguments, `parseSync(string, options)` expected");
        return;
    }

    if (!info[0]->IsString()) {
        Nan::ThrowTypeError("wrong argument - string expected, `parseSync(string, options)`");
        return;
    }

    if (info.Length() == 2 && !info[1]->IsObject()) {
        Nan::ThrowTypeError("wrong argument - object expected, `parseSync(string, options)`");
        return;
    }

    // Get source data
    String::Utf8Value sourceData(info[0]->ToString());

    // Prepare options
    snowcrash::BlueprintParserOptions options = 0;
    drafter::ASTType astType = drafter::RefractASTType;

    if (info.Length() == 2) {
        OptionsResult *optionsResult = ParseOptionsObject(Handle<Object>::Cast(info[1]));

        if (optionsResult->error != NULL) {
            Nan::ThrowTypeError(optionsResult->error);
            return;
        }

        options = optionsResult->options;
        astType = optionsResult->astType;
        free(optionsResult);
    }

    // Parse the source data
    snowcrash::ParseResult<snowcrash::Blueprint> parseResult;
    drafter::ParseBlueprint(*sourceData, options, parseResult);

    Local<Object> result = Result::WrapResult(parseResult, options, astType);

    if (parseResult.report.error.code != snowcrash::Error::OK) {
        Nan::ThrowError((Local<Value>) SourceAnnotation::WrapSourceAnnotation(parseResult.report.error));
        return;
    }

    info.GetReturnValue().Set(result);
}


text:
import numpy as np
import matplotlib as mpl
from distutils.version import LooseVersion
import nose
import matplotlib.pyplot as plt
import nose.tools as nt
import numpy.testing as npt

from .. import rcmod

class RCParamTester(object):

    def flatten_list(self, orig_list):

        iter_list = map(np.atleast_1d, orig_list)
        flat_list = [item for sublist in iter_list for item in sublist]
        return flat_list

    def assert_rc_params(self, params):

        for k, v in params.items():
            if k == "svg.embed_char_paths":
                # This param causes test issues and is deprecated anyway
                continue
            elif isinstance(v, np.ndarray):
                npt.assert_array_equal(mpl.rcParams[k], v)
            else:
                nt.assert_equal((k, mpl.rcParams[k]), (k, v))

class TestAxesStyle(RCParamTester):

    styles = ["white", "dark", "whitegrid", "darkgrid", "ticks"]

    def test_default_return(self):

        current = rcmod.axes_style()
        self.assert_rc_params(current)

    def test_key_usage(self):

        _style_keys = set(rcmod._style_keys)
        for style in self.styles:
            nt.assert_true(not set(rcmod.axes_style(style)) ^ _style_keys)

    def test_bad_style(self):

        with nt.assert_raises(ValueError):
            rcmod.axes_style("i_am_not_a_style")

    def test_rc_override(self):

        rc = {"axes.facecolor": "blue", "foo.notaparam": "bar"}
        out = rcmod.axes_style("darkgrid", rc)
        nt.assert_equal(out["axes.facecolor"], "blue")
        nt.assert_not_in("foo.notaparam", out)

    def test_set_style(self):

        for style in self.styles:

            style_dict = rcmod.axes_style(style)
            rcmod.set_style(style)
            self.assert_rc_params(style_dict)

    def test_style_context_manager(self):

        rcmod.set_style("darkgrid")
        orig_params = rcmod.axes_style()
        with rcmod.axes_style("whitegrid"):
            context_params = rcmod.axes_style("whitegrid")
            self.assert_rc_params(context_params)
        self.assert_rc_params(orig_params)

    def test_style_context_independence(self):

        nt.assert_true(set(rcmod._style_keys) ^ set(rcmod._context_keys))

    def test_set_rc(self):

        rcmod.set(rc={"lines.linewidth": 4})
        nt.assert_equal(mpl.rcParams["lines.linewidth"], 4)
        rcmod.set()

    def test_reset_defaults(self):

        # Changes to the rc parameters make this test hard to manage
        # on older versions of matplotlib, so we'll skip it
        if LooseVersion(mpl.__version__) < LooseVersion("1.3"):
            raise nose.SkipTest

        rcmod.reset_defaults()
        self.assert_rc_params(mpl.rcParamsDefault)
        rcmod.set()

    def test_reset_orig(self):

        # Changes to the rc parameters make this test hard to manage
        # on older versions of matplotlib, so we'll skip it
        if LooseVersion(mpl.__version__) < LooseVersion("1.3"):
            raise nose.SkipTest

        rcmod.reset_orig()
        self.assert_rc_params(mpl.rcParamsOrig)
        rcmod.set()

class TestPlottingContext(RCParamTester):

    contexts = ["paper", "notebook", "talk", "poster"]

    def test_default_return(self):

        current = rcmod.plotting_context()
        self.assert_rc_params(current)

    def test_key_usage(self):

        _context_keys = set(rcmod._context_keys)
        for context in self.contexts:
            missing = set(rcmod.plotting_context(context)) ^ _context_keys
            nt.assert_true(not missing)

    def test_bad_context(self):

        with nt.assert_raises(ValueError):
            rcmod.plotting_context("i_am_not_a_context")

    def test_font_scale(self):

        notebook_ref = rcmod.plotting_context("notebook")
        notebook_big = rcmod.plotting_context("notebook", 2)

        font_keys = ["axes.labelsize", "axes.titlesize", "legend.fontsize",
                     "xtick.labelsize", "ytick.labelsize"]

        for k in font_keys:
            nt.assert_equal(notebook_ref[k] * 2, notebook_big[k])

    def test_rc_override(self):

        key, val = "grid.linewidth", 5
        rc = {key: val, "foo": "bar"}
        out = rcmod.plotting_context("talk", rc=rc)
        nt.assert_equal(out[key], val)
        nt.assert_not_in("foo", out)

    def test_set_context(self):

        for context in self.contexts:

            context_dict = rcmod.plotting_context(context)
            rcmod.set_context(context)
            self.assert_rc_params(context_dict)

    def test_context_context_manager(self):

        rcmod.set_context("notebook")
        orig_params = rcmod.plotting_context()
        with rcmod.plotting_context("paper"):
            context_params = rcmod.plotting_context("paper")
            self.assert_rc_params(context_params)
        self.assert_rc_params(orig_params)

class TestFonts(object):

    def test_set_font(self):

        rcmod.set(font="Verdana")

        _, ax = plt.subplots()
        ax.set_xlabel("foo")

        try:
            nt.assert_equal(ax.xaxis.label.get_fontname(),
                            "Verdana")
        except AssertionError:
            if has_verdana():
                raise
            else:
                raise nose.SkipTest("Verdana font is not present")
        finally:
            rcmod.set()
            plt.close("all")

    def test_set_serif_font(self):

        rcmod.set(font="serif")

        _, ax = plt.subplots()
        ax.set_xlabel("foo")

        nt.assert_in(ax.xaxis.label.get_fontname(),
                     mpl.rcParams["font.serif"])

        rcmod.set()
        plt.close("all")

    def test_different_sans_serif(self):

        if LooseVersion(mpl.__version__) < LooseVersion("1.4"):
            raise nose.SkipTest

        rcmod.set()
        rcmod.set_style(rc={"font.sans-serif":
                            ["Verdana"]})

        _, ax = plt.subplots()
        ax.set_xlabel("foo")

        try:
            nt.assert_equal(ax.xaxis.label.get_fontname(),
                            "Verdana")
        except AssertionError:
            if has_verdana():
                raise
            else:
                raise nose.SkipTest("Verdana font is not present")
        finally:
            rcmod.set()
            plt.close("all")

def has_verdana():
    """Helper to verify if Verdana font is present"""
    # This import is relatively lengthy, so to prevent its import for
    # testing other tests in this module not requiring this knowledge,
    # import font_manager here
    import matplotlib.font_manager as mplfm
    try:
        verdana_font = mplfm.findfont('Verdana', fallback_to_default=False)
    except:
        # if https://github.com/matplotlib/matplotlib/pull/3435
        # gets accepted
        return False
    # otherwise check if not matching the logic for a 'default' one
    try:
        unlikely_font = mplfm.findfont("very_unlikely_to_exist1234",
                                       fallback_to_default=False)
    except:
        # if matched verdana but not unlikely, Verdana must exist
        return True
    # otherwise -- if they match, must be the same default
    return verdana_font != unlikely_font


text:
<?php
$this->breadcrumbs = array('首页管理','首页顶部动态图');
$doteySer = new DoteyService();
?>

		<?php if(!isset($isAjax) || !$isAjax){?>

首页顶部动态图

		<?php }?>

			<?php if(isset($notices) && count($notices)>0){?>

				<button type="button" class="close" data-dismiss="alert">×</button>
			<?php foreach($notices as $notice){?>

<?php echo isset($notice[0])?$notice[0]:$notice;?>

			<?php }?>

			<?php }?>
			<form class="form-horizontal" method="post" action="<?php echo $this->createUrl('index/homecarousel',array('op'=>'addHomeCarousel'));?>" enctype="multipart/form-data">
				<fieldset>

					主播用户/ID

					  <input class="input-small focused" id="indexForm_dotey_name" name="dotey_info" type="text" value="">
					  <input class="btn" type="button" value="验证" name="valid_dotey_info" id="valid_dotey_info">

						  +添加到本站明星

				  	本站明星列表

明星用户

UID

标题

链接地址

明星图片 (尺寸230*230)

					<?php if(isset($sideData)){?>
					<?php foreach($sideData as $k=>$data){?>
					<?php $uid = $data['target_id'];?>
					<dl class="effect" id="<?php echo $data['target_id'];?>">
						<input name="indexForm[operate_id][<?php echo $k?>]" type="hidden" id="indexForm[operate_id][<?php echo $data['operate_id']?>]" value="<?php echo $data['operate_id'];?>">

							≥
							<input name="indexForm[target_id][<?php echo $k?>]" type="hidden" id="indexForm[target_id][<?php echo $data['target_id']?>]" class="input-small focused" size="10" value="<?php echo $data['target_id'];?>">
							<input name="indexForm[content][nickname][<?php echo $k?>]" type="text" readonly="true" id="indexForm[content][nickname][<?php echo $data['target_id']?>]" class="input-small focused" size="10" value="<?php echo isset($data['content']['nickname'])?$data['content']['nickname']:'';?>">
							<input name="indexForm[content][username][<?php echo $k?>]" type="hidden" readonly="true" id="indexForm[content][username][<?php echo $data['target_id']?>]" class="input-small focused" size="10" value="<?php echo isset($data['content']['username'])?$data['content']['username']:'';?>">

							<?php echo $uid;?>

							<input name="indexForm[subject][<?php echo $k?>]" type="text" id="indexForm[subject][<?php echo $data['subject']?>]" class="input-small focused" size="10" value="<?php echo $data['subject'];?>">

							<input name="indexForm[textlink][<?php echo $k?>]" type="text" id="indexForm[textlink][<?php echo $data['textlink']?>]" class="input-small focused" size="10" value="<?php echo $data['textlink'];?>">

							<input name="doteyinfo[display_big][<?php echo $uid?>]" id="doteyinfo[display_big][<?php echo $uid;?>]" type="file" class="focused" size="10" value="">
							<?php if (!empty($data['dynamic_big'])){?>
							<span title="查看大图" class="icon icon-color icon-link" imgSrc="<?php echo $data['dynamic_big'];?>">
							<span title="查看中图" class="icon icon-color icon-link" imgSrc="<?php echo $data['dynamic_middle'];?>">
							<span title="查看小图" class="icon icon-color icon-link" imgSrc="<?php echo $data['dynamic_small'];?>">
							<?php }?>

							<i class="icon-remove" operateId=<?php echo $data['operate_id'];?>>

					<?php }?>
					<?php }?>

					<button type="submit" class="btn btn-primary">提交</button>

				</fieldset>
			</form>


text:
package org.locationtech.geomesa.utils.zk

import java.nio.charset.StandardCharsets

import org.apache.curator.framework.CuratorFrameworkFactory
import org.apache.curator.retry.ExponentialBackoffRetry
import org.locationtech.geomesa.index.metadata.{KeyValueStoreMetadata, MetadataSerializer}
import org.locationtech.geomesa.utils.collection.CloseableIterator

class ZookeeperMetadata[T](val namespace: String, val zookeepers: String, val serializer: MetadataSerializer[T])
    extends KeyValueStoreMetadata[T] {

  import org.locationtech.geomesa.utils.zk.ZookeeperMetadata.Root

  private val client = CuratorFrameworkFactory.builder()
      .namespace(namespace)
      .connectString(zookeepers)
      .retryPolicy(new ExponentialBackoffRetry(1000, 3))
      .build()
  client.start()

  override protected def checkIfTableExists: Boolean = true

  override protected def createTable(): Unit = {}

  override protected def createEmptyBackup(timestamp: String): ZookeeperMetadata[T] =
    new ZookeeperMetadata(s"${namespace}_${timestamp}_bak", zookeepers, serializer)

  override protected def write(rows: Seq[(Array[Byte], Array[Byte])]): Unit = {
    rows.foreach { case (row, value) =>
      val path = toPath(row)
      if (client.checkExists().forPath(path) == null) {
        client.create().creatingParentsIfNeeded().forPath(path)
      }
      client.setData().forPath(path, value)
    }
  }

  override protected def delete(rows: Seq[Array[Byte]]): Unit = {
    rows.foreach { row =>
      val path = toPath(row)
      if (client.checkExists().forPath(path) != null) {
        client.delete().deletingChildrenIfNeeded().forPath(path)
      }
    }
  }

  override protected def scanValue(row: Array[Byte]): Option[Array[Byte]] = {
    val path = toPath(row)
    if (client.checkExists().forPath(path) == null) { None } else {
      Option(client.getData.forPath(path))
    }
  }

  override protected def scanRows(prefix: Option[Array[Byte]]): CloseableIterator[(Array[Byte], Array[Byte])] = {
    import scala.collection.JavaConversions._
    val path = prefix.map(toPath(_, withSlash = false))
    if (client.checkExists().forPath(Root) == null) { CloseableIterator.empty } else {
      val all = CloseableIterator(client.getChildren.forPath(Root).iterator)
      val filtered = path match {
        case None => all
        case Some(p) => all.filter(_.startsWith(p))
      }
      filtered.map { f =>
        val bytes = f.getBytes(StandardCharsets.UTF_8)
        (bytes, client.getData.forPath(toPath(bytes)))
      }
    }
  }

  override def close(): Unit = client.close()

  private def toPath(row: Array[Byte], withSlash: Boolean = true): String = {
    val string = new String(row, StandardCharsets.UTF_8) // TODO escape?
    if (withSlash) { "/" + string } else { string }
  }
}

object ZookeeperMetadata {
  private val Root = "/"
}


text:
@interface LPDCollectionCellViewModel : LPDCollectionItemViewModel
+ (instancetype) new NS_UNAVAILABLE;
- (instancetype)init NS_UNAVAILABLE;
@end


text:
package com.senla.bolkunets.autoservice.controllers.managers;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

import com.senla.bolkunets.autoservice.api.beans.IMaster;
import com.senla.bolkunets.autoservice.api.beans.IOrder;
import com.senla.bolkunets.autoservice.api.managers.IMastersManager;
import com.senla.bolkunets.autoservice.api.repositoties.IMasterRepository;
import com.senla.bolkunets.autoservice.api.repositoties.IOrderRepository;
import com.senla.bolkunets.autoservice.model.repositories.MasterRepository;
import com.senla.bolkunets.autoservice.model.repositories.OrderRepository;
import com.senla.bolkunets.autoservice.utils.arrayworkers.CollectionWorker;

public class MastersManager implements IMastersManager {

	private final IMasterRepository masterRepository;
	private final IOrderRepository orderRepo;

	public MastersManager() {
		super();
		this.masterRepository = MasterRepository.getInstance();
		this.orderRepo = OrderRepository.getInstance();
	}

	@Override
	public void addMaster(IMaster master) {
		masterRepository.addMaster(master);
	}

	@Override
	public boolean removeMaster(long id) {
		IMaster master = masterRepository.deleteMaster(id);
		if (master != null) {
			List<IOrder> listOrders = orderRepo.getOrders();
			for (IOrder order : listOrders) {
				if (order != null) {
					CollectionWorker.removeById(order.getMasters(), master.getId());
				}
			}
			return true;
		}
		return false;

	}

	@Override
	public List<IMaster> getSortedListMaster(Comparator<IMaster> masterComparator) {
		List<IMaster> mastersList = masterRepository.getMasters();
		mastersList.sort(masterComparator);
		return mastersList;
	}

	@Override
	public List<IMaster> getMastersByOrder(long idOrder) {
		List<IMaster> resultListMasters = new ArrayList<>();
		IOrder order = orderRepo.getOrder(idOrder);
		if (order != null) {
			List<IMaster> masters = masterRepository.getMasters();
			for (IMaster master : masters) {
				if (master.getOrder()!=null && master.getOrder().equals(order)) {
					resultListMasters.add(master);
				}
			}
		}
		return resultListMasters;
	}

	@Override
	public List<IMaster> getMasters() {
		return masterRepository.getMasters();
	}

}


text:
/**
 * web server/service to wrap interactions w/ FB open graph
 */

var _debug = false;

var fs = require('fs'),
    http = require('http'),
    url = require('url'),
    express = require('express'),
    connect = require('connect'),
    sys = require('sys'),
    app = express.createServer(
                    connect.bodyParser(),
                    connect.cookieParser(),
                    connect.session({secret : "locker"})),
    locker = require('../../Common/node/locker.js'),
    lfs = require('../../Common/node/lfs.js');

var wwwdude = require('wwwdude'),
    wwwdude_client = wwwdude.createClient({ encoding: 'binary' });

var me, auth, latests, userInfo;
var facebookClient = require('facebook-js')();

app.set('views', __dirname);
app.get('/',
function(req, res) {
    res.writeHead(200, {
        'Content-Type': 'text/html'
    });
    if(!auth.appID) {
        res.end("Enter your personal FaceBook app info that will be used to sync your data" +
                " (create a new one at " +
                "http://www.facebook.com/developers/createapp.php using the callback url of " +
                "http://"+url.parse(me.uri).host+"/) " +
                "<form method='get' action='save'>" +
                    "App ID: <input name='appID'>
" +
                    "App Secret: <input name='appSecret'>
" +
                    "<input type='submit' value='Save'>" +
                "</form>");
        return;
    }
    if(!auth.token)
        res.end("you need to auth w/ fb yet");
    else
        res.end("found a token, load friends");
});

app.get('/save',
function(req, res) {
    res.writeHead(200, {
        'Content-Type': 'text/html'
    });
    if(!req.param('appID') || !req.param('appSecret')) {
        res.end("missing field(s)?");
        return;
    }
    auth.appID = req.param('appID');
    auth.appSecret = req.param('appSecret');
    lfs.writeObjectToFile('auth.json', auth);
    res.end("k thanks, now we need to auth that app to your account.");
});

app.get('/gofb',
function(req, res) {
    res.redirect(facebookClient.getAuthorizeUrl({
        client_id: auth.appID,
        redirect_uri: me.uri+"auth",
        scope: 'email,offline_access,read_stream,user_photos,friends_photos,publish_stream'
    }));
    res.end();
});

app.get('/auth',
function(req, res) {
    console.log("incoming auth " + req.param('code'));
    res.writeHead(200, {
        'Content-Type': 'text/html'
    });
    var OAuth = require("oauth").OAuth2;
    var oa = new OAuth(auth.appID, auth.appSecret, 'https://graph.facebook.com');

    oa.getOAuthAccessToken(
    req.param('code'),
    {redirect_uri: me.uri+"auth"},
    function(error, access_token, refresh_token) {
        if (error) {
            sys.debug(error);
            res.end("uhoh " + error);
        } else {
            res.end("too legit to quit: " + access_token + " so now load friends");
            auth.token = access_token;
            lfs.writeObjectToFile('auth.json', auth);
        }
    });
});

var photoQueue = [];
var photoIndex = 0;
function downloadPhotos(userID) {
    fs.mkdir('photos/', 0755);
    downloadNextPhoto();
}
function downloadNextPhoto() {
    if (photoIndex >= photoQueue.length) return;

//    var userID = photoQueue[photoIndex].userID;
    var friendID = photoQueue[photoIndex].friendID;
    photoIndex++;
    lfs.curlFile('https://graph.facebook.com/' + friendID + '/picture', 'photos/' + friendID + '.jpg', downloadNextPhoto);
}

function doFQLQuery(access_token, query, callback) {
    var fb = http.createClient(443, 'api.facebook.com', true);
    var request = fb.request('GET', '/method/fql.query?format=json&access_token=' + access_token +
                            '&query=' + escape(query),
                            {'host': 'api.facebook.com'});
    request.end();
    var data = '';
    request.on('response',
    function(response) {
        response.setEncoding('utf8');
        response.on('data',
        function(chunk) {
            data += chunk;
        });
        response.on('end',
        function() {
            callback(data);
        });
    });
}

app.get('/allContacts',
function(req, res) {
    res.writeHead(200, {
        'Content-Type': 'text/plain'
    });
    lfs.readObjectsFromFile('contacts.json', function(contacts) {
        res.write(JSON.stringify(contacts));
        res.end();
    });
});

app.get('/allPhotos',
function(req, res) {
    res.writeHead(200, {
        'Content-Type': 'text/plain'
    });
    fs.readdir('photos/Me', function(err, files) {
        var photoAlbums = [];
        function readNext(callback) {
            var file = files.pop();
            sys.debug('reading file ' + file)
            lfs.readObjectFromFile('photos/Me/' + file + "/meta.json", function(albumInfo) {
                photoAlbums.push(albumInfo);
                if(files.length > 0)
                    readNext(callback);
                else {
                    callback();
                    return;
                }
            });
        }
        readNext(function() {
            res.end(JSON.stringify(photoAlbums));
        });
    });
});

app.get('/friends',
function(req, res) {
    if (!auth.token) {
        res.writeHead(401);
        res.end();
//        res.end("you need to auth w/ fb yet");
        return;
    } else {
        res.writeHead(200, {
            'Content-Type': 'text/html'
        });
        facebookClient.apiCall('GET', '/me', {access_token: auth.token},
        function(error, result) {
            var userID = result.id;
            facebookClient.apiCall(
            'GET',
            '/me/friends',
            {access_token: auth.token},
            function(error, result) {
                console.log(error);
                var stream = fs.createWriteStream('contacts.json');
                for (var i = 0; i < result.data.length; i++) {
                    if (result.data[i]) {
                        stream.write(JSON.stringify(result.data[i]) + "\n");
                        if (result.data[i].id) {
                            photoQueue.push({
                                'userID': userID,
                                'friendID': result.data[i].id
                            });
                        }
                    }
                }
                stream.end();
                downloadPhotos(userID);
                locker.at('/friends', 3600);
                res.end();
            });

            facebookClient.apiCall(
            'GET',
            '/me/checkins',
            {access_token: auth.token},
            function(error, result) {
                console.log(error);
                var stream = fs.createWriteStream('places.json');
                for (var i = 0; i < result.data.length; i++) {
                    if (result.data[i]) {
                        stream.write(JSON.stringify(result.data[i]) + "\n");
                    }
                }
                stream.end();
            });
        });
    }
});

app.get('/feed',
function(req, res) {
    res.writeHead(200, {
        'Content-Type': 'text/html'
    });
    pullNewsFeed(function() {
        locker.at('/feed', 10);
        res.end();
    });
});

function getProfileInfo(userID, callback) {
    if(!callback) {
        callback = userID;
        userID = 'Me';
    }
    facebookClient.apiCall('GET', '/' + userID, {access_token: auth.token}, callback);
}

app.get('/photos',
function(req, res) {
    getPhotoAlbums(function(error, albums) {
        getNextPhotoAlbum(albums.data, function(albumError, album) { //get lists of photos in albums
            var albumFolder = 'photos/Me/' + album.id;
            try {
                fs.mkdirSync('photos/Me', 0755);
            } catch(err) {
                if(_debug) sys.debug(err);
            }
            try {
                fs.mkdirSync(albumFolder, 0755);
            } catch(err) {
                if(_debug) sys.debug(err);
            }
            lfs.writeObjectToFile(albumFolder + '/meta.json', album);
            getPhotos(albumFolder, album.photosList.data, function(photosError) {
                if(error) sys.debug(photosError);
            });
        }, function() {
            //all done
            res.end();
        });
    });
});

function getPhotoAlbums(userID, callback) {
    if(!callback) {
        callback = userID;
        userID = 'Me';
    }
    facebookClient.apiCall('GET', '/' + userID + '/albums', {access_token: auth.token}, callback);
}

function getNextPhotoAlbum(albums, albumCallback, finalCallback) {
    if(!albums || albums.length < 1) {
        finalCallback();
        return;
    }
    var album = albums.pop();
    getPhotoAlbum(album.id, function(error, photosList) {
        if(_debug) sys.debug('get album: ' + album.id);
        if(error) sys.debug(sys.inspect(error));
        album.photosList = photosList;
        albumCallback(error, album);
        getNextPhotoAlbum(albums, albumCallback, finalCallback);
    });
}

function getPhotoAlbum(albumID, callback) {
    if(_debug) sys.debug('getting album: ' + albumID);
    facebookClient.apiCall('GET', '/' + albumID + '/photos', {access_token: auth.token}, callback);
}

function getPhotos(albumFolder, photos, callback) {
    if(_debug) sys.debug('for ' + albumFolder + ', ' + photos.length + ' remaining.');
    if(!photos || photos.length < 1) {
        callback();
        return;
    }
    var photo = photos.pop();
    var largestURL = photo.images[0].source;
    lfs.curlFile(largestURL, albumFolder + '/' + photo.id + '.jpg');
    getPhotos(albumFolder, photos, callback);
}

app.get('/getfeed',
function(req, res) {
    res.writeHead(200, {
        'Content-Type': 'text/html'
    });
    lfs.readObjectsFromFile('feed.json', function(data) {
        var obj = {};
        obj.data = data;
        res.write(JSON.stringify(obj));
        res.end();
    });
});

function pullNewsFeed(callback) {
    if(!latests.feed)
        latests.feed = {};
    var items = [];
    pullNewsFeedPage(null, latests.feed.latest, items, function() {
        items.reverse();
        lfs.appendObjectsToFile('feed.json', items);
        callback();
    });
}

function pullNewsFeedPage(until, since, items, callback) {
    var params = {access_token: auth.token, limit: 1000};
    if(until)
        params.until = until;
    if(since)
        params.since = since;
    facebookClient.apiCall('GET', '/me/home', params,
        function(error, result) {
            if(error) {
                console.log(JSON.stringify(error));
                return;
            }
            if(result.data.length > 0) {
                var t = result.data[0].updated_time;
                if(!latests.feed.latest || t > latests.feed.latest)
                    latests.feed.latest = t;
                console.log(JSON.stringify(latests));
                for(var i = 0; i < result.data.length; i++)
                    items.push(result.data[i]);
                var next = result.paging.next;
                var until = unescape(next.substring(next.lastIndexOf("&until=") + 7));
                pullNewsFeedPage(until, since, items, callback);
            } else if(callback) {
                lfs.writeObjectToFile('latests.json', latests);
                callback();
            }
        });
}

var stdin = process.openStdin();
stdin.setEncoding('utf8');
stdin.on('data', function (chunk) {
    var processInfo = JSON.parse(chunk);
    locker.initClient(processInfo);
    process.chdir(processInfo.workingDirectory);
    lfs.readObjectFromFile('auth.json', function(newAuth) {
        auth = newAuth;
        lfs.readObjectFromFile('latests.json', function(newLatests) {
            latests = newLatests;
            lfs.readObjectFromFile('userInfo.json', function(newUserInfo) {
                userInfo = newUserInfo;
                me = lfs.loadMeData();
                app.listen(processInfo.port);
                var returnedInfo = {port: processInfo.port};
                console.log(JSON.stringify(returnedInfo));
            });
        });
    });
});


text:
using System;
using NUnit.Framework;
using NUnit.Framework.Api;

namespace NUnitLite.Tests
{
    public class RecordingTestListener : ITestListener
    {
        public string Events = string.Empty;

        public void TestStarted(ITest test)
        {
            Events += string.Format("<{0}:", test.Name);
        }

        public void TestFinished(ITestResult result)
        {
            Events += string.Format(":{0}>", result.ResultState);
        }

        public void TestOutput(TestOutput output) { }
    }
}


text:
package com.tribbloids.spookystuff.utils.io

import com.tribbloids.spookystuff.session.WebProxySetting
import com.tribbloids.spookystuff.utils.http._
import com.tribbloids.spookystuff.utils.serialization.NOTSerializable
import org.apache.hadoop.conf.Configuration
import org.apache.http.client.methods.HttpRequestBase

import java.net.URI

trait CompoundResolver extends URIResolver {

  def getImpl(pathStr: String): URIResolver

  case class _Execution(pathStr: String) extends Execution {

    lazy val impl: URIExecution = getImpl(pathStr).execute(pathStr)

    override def absolutePathStr: String = impl.absolutePathStr

    override def _delete(mustExist: Boolean): Unit = impl.delete(mustExist)

    override def moveTo(target: String, force: Boolean = false): Unit = impl.moveTo(target, force)

    //    override def mkDirs(): Unit = impl.mkDirs()
    override type _Resource = impl._Resource

    override def _Resource: WriteMode => impl._Resource = { v =>
      impl._Resource(v)
    }
  }

  //  override def lockAccessDuring[T](pathStr: String)(f: String => T) =
  //    getImpl(pathStr).lockAccessDuring(pathStr)(f)
}

object CompoundResolver {

  // TODO: should be "FileService"
  class FSResolver(
      hadoopConfFactory: () => Configuration,
      timeoutMillis: Int
  ) extends CompoundResolver {

    lazy val hdfs: HDFSResolver = HDFSResolver(hadoopConfFactory)

    lazy val ftp: URLConnectionResolver = URLConnectionResolver(timeoutMillis)

    override def getImpl(uri: String): URIResolver = {

      val _uri = HttpUtils.uri(uri)
      val scheme = _uri.getScheme
      scheme match {
        case "ftp" | "ftps" =>
          ftp
        case "local" =>
          LocalResolver // TODO: useless? identical to "file://"
        case _ =>
          hdfs
      }
    }
  }

  // TODO: should be "Omni"
  class OmniResolver(
      hadoopConfFactory: () => Configuration,
      timeoutMillis: Int,
      webProxy: WebProxySetting,
      input2Http: URI => HttpRequestBase
  ) extends FSResolver(hadoopConfFactory, timeoutMillis)
      with NOTSerializable {

    override def getImpl(uri: String): URIResolver = {

      val _uri = HttpUtils.uri(uri)
      val scheme = _uri.getScheme
      scheme match {
        case "http" | "https" =>
          http
        case _ =>
          super.getImpl(uri)
      }
    }

    lazy val http: HTTPResolver = HTTPResolver(timeoutMillis, webProxy, input2Http)
  }
}


text:
using System;

namespace NServiceKit.Logging.Support.Logging
{
    ///
    /// Creates a test Logger, that stores all log messages in a member list
    ///
	public class TestLogFactory : ILogFactory
    {
        /// Gets the logger.
        ///
        /// <param name="type">The type.</param>
        ///
        /// <returns>The logger.</returns>
        public ILog GetLogger(Type type)
        {
            return new TestLogger(type);
        }

        /// Gets the logger.
        ///
        /// <param name="typeName">Name of the type.</param>
        ///
        /// <returns>The logger.</returns>
        public ILog GetLogger(string typeName)
        {
            return new TestLogger(typeName);
        }
    }
}