text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>../src/components/cameraFX.js</title>
    <link rel="stylesheet" href="http://yui.yahooapis.com/3.9.1/build/cssgrids/cssgrids-min.css">
    <link rel="stylesheet" href="../assets/vendor/prettify/prettify-min.css">
    <link rel="stylesheet" href="../assets/css/main.css" id="site_styles">
    <link rel="icon" href="../assets/favicon.ico">

            API Docs for:

APIs

Classes

Modules

                            <input type="search" id="api-filter" placeholder="Type to filter APIs">

LS.Animation

LS.Animation.Take

LS.Animation.Track

LS.BaseComponent

LS.Collision

LS.ComponentContainer

LS.Components.Camera

LS.Components.CameraController

LS.Components.CameraDirector

LS.Components.CameraFX

LS.Components.Canvas3D

LS.Components.CustomData

LS.Components.FollowNode

LS.Components.FrameFX

LS.Components.FXGraphComponent

LS.Components.FXStack

LS.Components.GeometricPrimitive

LS.Components.GraphComponent

LS.Components.Light

LS.Components.LightFX

LS.Components.LinesRenderer

LS.Components.MeshRenderer

LS.Components.MorphDeformer

LS.Components.NodeManipulator

LS.Components.ParticlesEmissor

LS.Components.PlayAnimation

LS.Components.Poser

LS.Components.RealtimeReflector

LS.Components.Rotator

LS.Components.SceneInclude

LS.Components.Script

LS.Components.SkinDeformer

LS.Components.Skybox

LS.Components.Spline

LS.Components.SVGRenderer

LS.Components.Target

LS.Components.Transform

LS.Components.VRCameraController

LS.CompositePattern

LS.DebugRender

LS.Draw

LS.Formats

LS.GLSLCode

LS.GraphCode

LS.GUI

LS.Input

LS.InteractiveController

LS.Knob

LS.LS

LS.LScript

LS.Material

LS.oldStandardMaterial

LS.Pack

LS.Particle

LS.Physics

LS.PhysicsInstance

LS.Picking

LS.Player

LS.Prefab

LS.Project

LS.Ray

LS.Renderer

LS.RenderFrameContext

LS.RenderInstance

LS.RenderSettings

LS.RenderState

LS.Resource

LS.ResourcesManager

LS.Scene

LS.SceneNode

LS.ShaderBlock

LS.ShaderCode

LS.ShaderMaterial

LS.Shaders

LS.SpatialContainer

LS.StandardMaterial

LS.Tween

LS.UnityMaterial

LS.WBin

LSQ

LS

                    Show:

                        <input type="checkbox" id="api-show-inherited" checked>
                        Inherited

                        <input type="checkbox" id="api-show-protected">
                        Protected

                        <input type="checkbox" id="api-show-private">
                        Private

                        <input type="checkbox" id="api-show-deprecated">
                        Deprecated

File: ../src/components/cameraFX.js

///@INFO: UNCOMMON
/**
* This component allow to create basic FX
* @class CameraFX
* @param {Object} o object with the serialized info
*/
function CameraFX( o )
{
	this.enabled = true;

	/**
	* The FX Stack
	* @property fx {LS.FXStack}
	*/
	this.fx = new LS.FXStack( o ? o.fx : null );

	/**
	* The position of the camera (in local space, node space)
	* @property eye {vec3}
	* @default [0,100,100]
	*/
	this.frame = new LS.RenderFrameContext();
	this.frame.use_depth_texture = true;
	this.use_antialiasing = false;

	this.shader_material = null;

	if(o)
		this.configure(o);
}

CameraFX.icon = "mini-icon-fx.png";
CameraFX["@camera_uid"] = { type: "String" };

/**
* Apply antialiasing post-processing shader
* @property use_antialiasing {Boolean}
*/
Object.defineProperty( CameraFX.prototype, "use_antialiasing", {
	set: function(v) { this.fx.apply_fxaa = v; },
	get: function() { return this.fx.apply_fxaa; },
	enumerable: true
});

CameraFX.prototype.configure = function(o)
{
	this.enabled = !!o.enabled;
	this.use_antialiasing = !!o.use_antialiasing;
	this.camera_uid = o.camera_uid;
	if(o.frame)
		this.frame.configure( o.frame );
	if(o.fx)
		this.fx.configure(o.fx);
}

CameraFX.prototype.serialize = function()
{
	return {
		object_class: "CameraFX",
		enabled: this.enabled,
		use_antialiasing: this.use_antialiasing,
		frame: this.frame.serialize(),
		camera_uid: this.camera_uid,
		fx: this.fx.serialize()
	};
}

CameraFX.prototype.getResources = function( res )
{
	this.fx.getResources(res);
	if(this.shader_material)
		res[ this.shader_material ] = true;
	return res;
}

CameraFX.prototype.onResourceRenamed = function( old_name, new_name, resource )
{
	if( this.shader_material == old_name )
		this.shader_material = new_name;
	else
		this.fx.onResourceRenamed( old_name, new_name, resource );
}

CameraFX.prototype.addFX = function( name )
{
	this.fx.addFX(name);
}

CameraFX.prototype.getFX = function(index)
{
	return this.fx.getFX( index );
}

CameraFX.prototype.moveFX = function( fx, offset )
{
	return this.fx.moveFX(fx,offset);
}

CameraFX.prototype.removeFX = function( fx )
{
	return this.fx.removeFX( fx );
}

CameraFX.prototype.onAddedToScene = function( scene )
{
	LEvent.bind( scene, "enableFrameContext", this.onBeforeRender, this );
	LEvent.bind( scene, "showFrameContext", this.onAfterRender, this );
}

CameraFX.prototype.onRemovedFromScene = function( scene )
{
	LEvent.unbind( scene, "enableFrameContext", this.onBeforeRender, this );
	LEvent.unbind( scene, "showFrameContext", this.onAfterRender, this );

	if( this._binded_camera )
	{
		LEvent.unbindAll( this._binded_camera, this );
		this._binded_camera = null;
	}
}

//hook the RFC
CameraFX.prototype.onBeforeRender = function(e, render_settings)
{
	if(!this.enabled)
	{
		if( this._binded_camera )
		{
			LEvent.unbindAll( this._binded_camera, this );
			this._binded_camera = null;
		}
		return;
	}

	//FBO for one camera
	var camera = this._root.camera;
	if(this.camera_uid)
	{
		if( !this._binded_camera || this._binded_camera.uid != this.camera_uid )
			camera = this._binded_camera;
		else
			camera = this._root.scene.findComponentByUId( this.camera_uid );
	}

	if(!camera)
	{
		if( this._binded_camera )
		{
			LEvent.unbindAll( this._binded_camera, this );
			this._binded_camera = null;
		}
		return;
	}

	if(camera && camera != this._binded_camera)
	{
		if(this._binded_camera)
			LEvent.unbindAll( this._binded_camera, this );
		LEvent.bind( camera, "enableFrameContext", this.enableCameraFBO, this );
		LEvent.bind( camera, "showFrameContext", this.showCameraFBO, this );
	}
	this._binded_camera = camera;
}

CameraFX.prototype.onAfterRender = function( e, render_settings )
{
	if(!this.enabled)
		return;
	//this.showFBO();
}

CameraFX.prototype.enableCameraFBO = function(e, render_settings )
{
	if(!this.enabled)
		return;

	var camera = this._binded_camera;
	var viewport = this._viewport = camera.getLocalViewport( null, this._viewport );
	this.frame.enable( render_settings, viewport );

	render_settings.ignore_viewports = true;
}

CameraFX.prototype.showCameraFBO = function(e, render_settings )
{
	if(!this.enabled)
		return;
	render_settings.ignore_viewports = false;
	this.showFBO();
}

CameraFX.prototype.showFBO = function()
{
	if(!this.enabled)
		return;

	this.frame.disable();

	LEvent.trigger( LS.Renderer, "beforeShowFrameContext", this.frame );

	if(this.shader_material)
	{
		var material = LS.ResourcesManager.getResource( this.shader_material );
		var rendered = false;
		if(material && material.constructor === LS.ShaderMaterial )
			rendered = material.applyToTexture( this.frame._color_texture );
		if(!rendered)
			this.frame._color_texture.toViewport(); //fallback in case the shader is missing
		return;
	}

	if( this._viewport )
	{
		gl.setViewport( this._viewport );
		this.applyFX();
		gl.setViewport( this.frame._fbo._old_viewport );
	}
	else
		this.applyFX();
}

CameraFX.prototype.applyFX = function()
{
	var color_texture = this.frame._color_texture;
	var depth_texture = this.frame._depth_texture;

	this.fx.apply_fxaa = this.use_antialiasing;
	this.fx.filter = this.frame.filter_texture;
	this.fx.applyFX( color_texture, null, { depth_texture: depth_texture } );
}

LS.registerComponent( CameraFX );


text:
include_recipe 'python::virtualenv'

account = 'websockets'

user_account account do
  create_group true
  ssh_keygen   false
end

git "/home/#{account}/metadisk-websockets" do
  repository 'https://github.com/storj/metadisk-websockets.git'
  action :sync

  user  account
  group account

  notifies :run, 'execute[metadisk-websockets-requirements]'
end

python_virtualenv "/home/#{account}/metadisk-websockets/.env" do
  owner account
  group account
end

execute 'metadisk-websockets-requirements' do
  command '.env/bin/pip install -r requirements.txt'

  cwd   "/home/#{account}/metadisk-websockets"
  user  account
  group account
end

template "/etc/init/metadisk-websockets.conf" do
  mode  0644
  owner 'root'
  group 'root'

  source "metadisk-websockets.upstart.erb"
  variables user: account

  notifies :run, 'execute[enable-metadisk-websockets]'
end

execute 'enable-metadisk-websockets' do
  command 'service metadisk-websockets start'
  action  :nothing

  user  'root'
  group 'root'
end

redpajama_set_name: RedPajamaGithub


text:
"""
An EBS implementation of the ``IBlockDeviceAPI``.
"""

from subprocess import check_output
import threading
import time
import logging
from uuid import UUID

from bitmath import Byte, GiB

from pyrsistent import PRecord, field, pset
from zope.interface import implementer
from boto import ec2
from boto import config
from boto.ec2.connection import EC2Connection
from boto.utils import get_instance_metadata
from boto.exception import EC2ResponseError
from twisted.python.filepath import FilePath

from eliot import Message

from .blockdevice import (
    IBlockDeviceAPI, BlockDeviceVolume, UnknownVolume, AlreadyAttachedVolume,
    UnattachedVolume,
)
from ._logging import (
    AWS_ACTION, BOTO_EC2RESPONSE_ERROR, NO_AVAILABLE_DEVICE,
    NO_NEW_DEVICE_IN_OS, WAITING_FOR_VOLUME_STATUS_CHANGE,
    BOTO_LOG_HEADER, IN_USE_DEVICES,
)

DATASET_ID_LABEL = u'flocker-dataset-id'
METADATA_VERSION_LABEL = u'flocker-metadata-version'
CLUSTER_ID_LABEL = u'flocker-cluster-id'
BOTO_NUM_RETRIES = u'20'
VOLUME_STATE_CHANGE_TIMEOUT = 300
MAX_ATTACH_RETRIES = 3

class EliotLogHandler(logging.Handler):
    _to_log = {"Method", "Path", "Params"}

    def emit(self, record):
        fields = vars(record)
        # Only log certain things.  The log is massively too verbose
        # otherwise.
        if fields.get("msg", ":").split(":")[0] in self._to_log:
            Message.new(
                message_type=BOTO_LOG_HEADER, **fields
            ).write()

def _enable_boto_logging():
    """
    Make boto log activity using Eliot.
    """
    logger = logging.getLogger("boto")
    logger.addHandler(EliotLogHandler())

    # It seems as though basically all boto log messages are at the same
    # level.  Either we can see all of them or we can see none of them.
    # We'll do some extra filtering in the handler.
    logger.setLevel(logging.DEBUG)

_enable_boto_logging()

class AttachedUnexpectedDevice(Exception):
    """
    A volume was attached to a device other than the one we expected.

    :ivar str _template: A native string giving the template into which to
        format attributes for the string representation.
    """
    _template = "AttachedUnexpectedDevice(requested={!r}, discovered={!r})"

    def __init__(self, requested, discovered):
        """
        :param FilePath requested: The requested device name.
        :param FilePath discovered: The device which was discovered on the
            system.
        """
        self.requested = requested
        self.discovered = discovered

    def __str__(self):
        return self._template.format(
            self.requested.path, self.discovered.path,
        )

    __repr__ = __str__

def _expected_device(requested_device):
    """
    Given a device we requested from AWS EBS, determine the OS device path that
    will actually be created.

    This maps EBS required ``/dev/sdX`` names to ``/dev/vbdX`` names that are
    used by currently supported platforms (Ubuntu 14.04 and CentOS 7).
    """
    prefix = b"/dev/sd"
    if requested_device.startswith(prefix):
        return FilePath(b"/dev").child(b"xvd" + requested_device[len(prefix):])
    raise ValueError(
        "Unsupported requested device {!r}".format(requested_device)
    )

def ec2_client(region, zone, access_key_id, secret_access_key):
    """
    Establish connection to EC2 client.

    :param str region: The name of the EC2 region to connect to.
    :param str zone: The zone for the EC2 region to connect to.
    :param str access_key_id: "aws_access_key_id" credential for EC2.
    :param str secret_access_key: "aws_secret_access_key" EC2 credential.

    :return: An ``_EC2`` giving information about EC2 client connection
        and EC2 instance zone.
    """
    # Set 2 retry knobs in Boto to BOTO_NUM_RETRIES:
    # 1. ``num_retries``:
    # Request automatic exponential backoff and retry
    # attempts by Boto if an EC2 API call fails with
    # ``RequestLimitExceeded`` due to system load.
    # 2. ``metadata_service_num_attempts``:
    # Request for retry attempts by Boto to
    # retrieve data from Metadata Service used to retrieve
    # credentials for IAM roles on EC2 instances.
    if not config.has_section('Boto'):
        config.add_section('Boto')
    config.set('Boto', 'num_retries', BOTO_NUM_RETRIES)
    config.set('Boto', 'metadata_service_num_attempts', BOTO_NUM_RETRIES)

    # Get Boto EC2 connection with ``EC2ResponseError`` logged by Eliot.
    connection = ec2.connect_to_region(region,
                                       aws_access_key_id=access_key_id,
                                       aws_secret_access_key=secret_access_key)
    return _EC2(zone=zone,
                connection=_LoggedBotoConnection(connection=connection))

def _boto_logged_method(method_name, original_name):
    """
    Run a boto.ec2.connection.EC2Connection method and
    log additional information about any exceptions that are raised.

    :param str method_name: The name of the method of the wrapped object to
        call.
    :param str original_name: The name of the attribute of self where the
        wrapped object can be found.

    :return: A function which will call the method of the wrapped object and do
        the extra exception logging.
    """
    def _run_with_logging(self, *args, **kwargs):
        """
        Run given boto.ec2.connection.EC2Connection method with exception
        logging for ``EC2ResponseError``.
        """
        original = getattr(self, original_name)
        method = getattr(original, method_name)

        # Trace IBlockDeviceAPI ``method`` as Eliot Action.
        # See https://clusterhq.atlassian.net/browse/FLOC-2054
        # for ensuring all method arguments are serializable.
        with AWS_ACTION(operation=[method_name, args, kwargs]):
            try:
                return method(*args, **kwargs)
            except EC2ResponseError as e:
                BOTO_EC2RESPONSE_ERROR(
                    aws_code=e.code,
                    aws_message=e.message,
                    aws_request_id=e.request_id,
                ).write()
                raise
    return _run_with_logging

def boto_logger(*args, **kwargs):
    """
    Decorator to log all callable boto.ec2.connection.EC2Connection
    methods.

    :return: A function that will decorate all methods of the given
        class with Boto exception logging.
    """
    def _class_decorator(cls):
        for attr in EC2Connection.__dict__:
            # Log wrap all callable methods except `__init__`.
            if attr != '__init__':
                attribute = getattr(EC2Connection, attr)
                if callable(attribute):
                    setattr(cls, attr,
                            _boto_logged_method(attr, *args, **kwargs))
        return cls
    return _class_decorator

@boto_logger("connection")
class _LoggedBotoConnection(PRecord):
    """
    Wrapper ``PRecord`` around ``boto.ec2.connection.EC2Connection``
    to facilitate logging of exceptions from Boto APIs.

    :ivar boto.ec2.connection.EC2Connection connection: Object
        representing connection to an EC2 instance with logged
        ``EC2ConnectionError``.
    """
    connection = field(mandatory=True)

class _EC2(PRecord):
    """
    :ivar str zone: The name of the zone for the connection.
    :ivar boto.ec2.connection.EC2Connection connection: Object
        representing connection to an EC2 instance.
    """
    zone = field(mandatory=True)
    connection = field(mandatory=True)

def _blockdevicevolume_from_ebs_volume(ebs_volume):
    """
    Helper function to convert Volume information from
    EBS format to Flocker block device format.

    :param boto.ec2.volume ebs_volume: Volume in EC2 format.

    :return: Input volume in BlockDeviceVolume format.
    """
    return BlockDeviceVolume(
        blockdevice_id=unicode(ebs_volume.id),
        size=int(GiB(ebs_volume.size).to_Byte().value),
        attached_to=ebs_volume.attach_data.instance_id,
        dataset_id=UUID(ebs_volume.tags[DATASET_ID_LABEL])
    )

def _wait_for_volume(volume,
                     start_status,
                     transient_status,
                     end_status):
    """
    Helper function to wait for a given volume to change state
    from ``start_status`` via ``transient_status`` to ``end_status``.

    :param boto.ec2.volume volume: Volume to check
        status for.
    :param unicode start_status: Volume status at starting point.
    :param unicode transient_status: Allowed transient state for
        volume to be in, on the way to ``end_status``.
    :param unicode end_status: Expected destination status for
        the input volume.

    :raises Exception: When input volume failed to reach
        expected destination status.
    """
    # It typically takes a few seconds for anything to happen, so start
    # out sleeping a little before doing initial check to reduce
    # unnecessary polling of the API:
    time.sleep(5.0)

    # Wait ``VOLUME_STATE_CHANGE_TIMEOUT`` seconds for
    # volume status to transition from
    # start_status -> transient_status -> end_status.
    start_time = time.time()
    while time.time() - start_time < VOLUME_STATE_CHANGE_TIMEOUT:
        try:
            volume.update()
        except EC2ResponseError as e:
            # If AWS cannot find the volume, raise ``UnknownVolume``.
            # (http://docs.aws.amazon.com/AWSEC2/latest/APIReference/errors-overview.html
            # for error details).
            if e.code == u'InvalidVolume.NotFound':
                raise UnknownVolume(volume.id)
        if volume.status == end_status:
            return
        elif volume.status not in [start_status, transient_status]:
            break
        time.sleep(1.0)

        WAITING_FOR_VOLUME_STATUS_CHANGE(volume_id=volume.id,
                                         status=volume.status,
                                         target_status=end_status,
                                         wait_time=(time.time() - start_time))

    # We either:
    # 1) Timed out waiting to reach ``end_status``, or,
    # 2) Reached an unexpected status (state change did not
    #    start, or failed).
    # Raise an ``Exception`` in both cases.
    raise Exception(
        'Volume state transition failed. '
        'Volume: {!r}, '
        'Start Status: {!r}, '
        'Transient Status: {!r}, '
        'Expected End Status: {!r}, '
        'Discovered End Status: {!r},'
        'Wait time: {!r},'
        'Time limit: {!r}.'.format(
            volume, start_status, transient_status, end_status,
            volume.status, time.time() - start_time,
            VOLUME_STATE_CHANGE_TIMEOUT
            )
        )

def _get_device_size(device):
    """
    Helper function to fetch the size of given block device.

    :param unicode device: Name of the block device to fetch size for.

    :returns: Size, in SI metric bytes, of device we are interested in.
    :rtype: int
    """
    device_name = b"/dev/" + device.encode("ascii")

    # Retrieve size of device as OS sees it using `lsblk`.
    # Requires util-linux-ng package on CentOS, and
    # util-linux on Ubuntu.
    # Required package is installed by default
    # on Ubuntu 14.04 and CentOS 7.
    command = [b"/bin/lsblk", b"--noheadings", b"--bytes",
               b"--output", b"SIZE", device_name]

    # Get the base device size, which is the first line in
    # `lsblk` output. Ignore partition sizes.
    # XXX: Handle error cases during `check_output()` run
    # (https://clusterhq.atlassian.net/browse/FLOC-1886).
    command_output = check_output(command).split(b'\n')[0]
    device_size = int(command_output.strip().decode("ascii"))

    return device_size

def _wait_for_new_device(base, size, time_limit=60):
    """
    Helper function to wait for up to 60s for new
    EBS block device (`/dev/sd*` or `/dev/xvd*`) to
    manifest in the OS.

    :param list base: List of baseline block devices
        that existed before execution of operation that expects
        to create a new block device.
    :param int size: Size of the block device we are expected
        to manifest in the OS.
    :param int time_limit: Time, in seconds, to wait for
        new device to manifest. Defaults to 60s.

    :returns: The path of the new block device file.
    :rtype: ``FilePath``
    """
    start_time = time.time()
    elapsed_time = time.time() - start_time
    while elapsed_time < time_limit:
        for device in list(set(FilePath(b"/sys/block").children()) -
                           set(base)):
            device_name = FilePath.basename(device)
            if (device_name.startswith((b"sd", b"xvd")) and
                    _get_device_size(device_name) == size):
                return FilePath(b"/dev").child(device_name)
        time.sleep(0.1)
        elapsed_time = time.time() - start_time

    # If we failed to find a new device of expected size,
    # log sizes of all new devices on this compute instance,
    # for debuggability.
    new_devices = list(set(FilePath(b"/sys/block").children()) - set(base))
    new_devices_size = [_get_device_size(device) for device in new_devices]
    NO_NEW_DEVICE_IN_OS(new_devices=new_devices,
                        new_devices_size=new_devices_size,
                        expected_size=size,
                        time_limit=time_limit).write()
    return None

def _is_cluster_volume(cluster_id, ebs_volume):
    """
    Helper function to check if given volume belongs to
    given cluster.

    :param UUID cluster_id: UUID of Flocker cluster to check for
        membership.
    :param boto.ec2.volume ebs_volume: EBS volume to check for
        input cluster membership.

    :return bool: True if input volume belongs to input
        Flocker cluster. False otherwise.
    """
    actual_cluster_id = ebs_volume.tags.get(CLUSTER_ID_LABEL)
    if actual_cluster_id is not None:
        actual_cluster_id = UUID(actual_cluster_id)
        if actual_cluster_id == cluster_id:
            return True
    return False

@implementer(IBlockDeviceAPI)
class EBSBlockDeviceAPI(object):
    """
    An EBS implementation of ``IBlockDeviceAPI`` which creates
    block devices in an EC2 cluster using Boto APIs.
    """
    def __init__(self, ec2_client, cluster_id):
        """
        Initialize EBS block device API instance.

        :param _EC2 ec2_client: A record of EC2 connection and zone.
        :param UUID cluster_id: UUID of cluster for this
            API instance.
        """
        self.connection = ec2_client.connection
        self.zone = ec2_client.zone
        self.cluster_id = cluster_id
        self.lock = threading.Lock()

    def allocation_unit(self):
        """
        Return a fixed allocation_unit for now; one which we observe
        to work on AWS.
        """
        return int(GiB(1).to_Byte().value)

    def compute_instance_id(self):
        """
        Look up the EC2 instance ID for this node.
        """
        return get_instance_metadata()['instance-id'].decode("ascii")

    def _get_ebs_volume(self, blockdevice_id):
        """
        Lookup EBS Volume information for a given blockdevice_id.

        :param unicode blockdevice_id: ID of a blockdevice that needs lookup.

        :returns: boto.ec2.volume.Volume for the input id.

        :raise UnknownVolume: If no volume with a matching identifier can be
             found.
        """
        try:
            all_volumes = self.connection.get_all_volumes(
                volume_ids=[blockdevice_id])
        except EC2ResponseError as e:
            # https://docs.aws.amazon.com/AWSEC2/latest/APIReference/errors-overview.html#CommonErrors
            if e.error_code == "InvalidVolume.NotFound":
                raise UnknownVolume(blockdevice_id)
            else:
                raise

        for volume in all_volumes:
            if volume.id == blockdevice_id:
                return volume
        raise UnknownVolume(blockdevice_id)

    def _next_device(self, instance_id, volumes, devices_in_use):
        """
        Get the next available EBS device name for a given EC2 instance.

        Algorithm:
        1. Get all ``Block devices`` currently in use by given instance:
            a) List all volumes visible to this instance.
            b) Gather device IDs of all devices attached to (a).
        2. Devices available for EBS volume usage are ``/dev/sd[f-p]``.
           Find the first device from this set that is currently not
           in use.
        XXX: Handle lack of free devices in ``/dev/sd[f-p]`` range
        (see https://clusterhq.atlassian.net/browse/FLOC-1887).

        :param unicode instance_id: EC2 instance ID.
        :param volumes: Collection of currently known
            ``BlockDeviceVolume`` instances.
        :param set devices_in_use: Unicode names of devices that are
            probably in use based on observed behavior.

        :returns unicode file_name: available device name for attaching
            EBS volume.
        :returns ``None`` if suitable EBS device names on this EC2
            instance are currently occupied.
        """
        devices = pset({v.attach_data.device for v in volumes
                       if v.attach_data.instance_id == instance_id})
        devices = devices | devices_in_use
        IN_USE_DEVICES(devices=devices).write()

        for suffix in b"fghijklmonp":
            file_name = u'/dev/sd' + suffix
            if file_name not in devices:
                return file_name

        # Could not find any suitable device that is available
        # for attachment. Log to Eliot before giving up.
        NO_AVAILABLE_DEVICE(devices=devices).write()
        return None

    def create_volume(self, dataset_id, size):
        """
        Create a volume on EBS. Store Flocker-specific
        {metadata version, cluster id, dataset id} for the volume
        as volume tag data.
        Open issues: https://clusterhq.atlassian.net/browse/FLOC-1792
        """
        requested_volume = self.connection.create_volume(
            size=int(Byte(size).to_GiB().value), zone=self.zone)

        # Stamp created volume with Flocker-specific tags.
        metadata = {
            METADATA_VERSION_LABEL: '1',
            CLUSTER_ID_LABEL: unicode(self.cluster_id),
            DATASET_ID_LABEL: unicode(dataset_id),
        }
        self.connection.create_tags([requested_volume.id],
                                    metadata)

        # Wait for created volume to reach 'available' state.
        _wait_for_volume(requested_volume,
                         start_status=u'',
                         transient_status=u'creating',
                         end_status=u'available')

        # Return created volume in BlockDeviceVolume format.
        return _blockdevicevolume_from_ebs_volume(requested_volume)

    def list_volumes(self):
        """
        Return all volumes that belong to this Flocker cluster.
        """
        volumes = []
        for ebs_volume in self.connection.get_all_volumes():
            if _is_cluster_volume(self.cluster_id, ebs_volume):
                volumes.append(
                    _blockdevicevolume_from_ebs_volume(ebs_volume)
                )
        return volumes

    def attach_volume(self, blockdevice_id, attach_to):
        """
        Attach an EBS volume to given compute instance.

        :param unicode blockdevice_id: EBS UUID for volume to be attached.
        :param unicode attach_to: Instance id of AWS Compute instance to
            attached the blockdevice to.

        :raises UnknownVolume: If there does not exist a BlockDeviceVolume
            corresponding to the input blockdevice_id.
        :raises AlreadyAttachedVolume: If the input volume is already attached
            to a device.
        :raises AttachedUnexpectedDevice: If the attach operation fails to
            associate the volume with the expected OS device file.  This
            indicates use on an unsupported OS, a misunderstanding of the EBS
            device assignment rules, or some other bug in this implementation.
        """
        ebs_volume = self._get_ebs_volume(blockdevice_id)
        volume = _blockdevicevolume_from_ebs_volume(ebs_volume)
        if (volume.attached_to is not None or
                ebs_volume.status != 'available'):
            raise AlreadyAttachedVolume(blockdevice_id)

        ignore_devices = pset([])
        attach_attempts = 0
        while True:
            with self.lock:
                # begin lock scope

                blockdevices = FilePath(b"/sys/block").children()
                volumes = self.connection.get_all_volumes()
                device = self._next_device(attach_to, volumes, ignore_devices)

                if device is None:
                    # XXX: Handle lack of free devices in ``/dev/sd[f-p]``.
                    # (https://clusterhq.atlassian.net/browse/FLOC-1887).
                    # No point in attempting an ``attach_volume``, return.
                    return

                try:
                    self.connection.attach_volume(blockdevice_id,
                                                  attach_to,
                                                  device)
                except EC2ResponseError as e:
                    # If attach failed that is often because of eventual
                    # consistency in AWS, so let's ignore this one if it
                    # fails:
                    if e.code == u'InvalidParameterValue':
                        attach_attempts += 1
                        if attach_attempts == MAX_ATTACH_RETRIES:
                            raise
                        ignore_devices = ignore_devices.add(device)
                    else:
                        raise
                else:
                    # Wait for new device to manifest in the OS. Since there
                    # is currently no standardized protocol across Linux guests
                    # in EC2 for mapping `device` to the name device driver
                    # picked (http://docs.aws.amazon.com/AWSEC2/latest/
                    # UserGuide/device_naming.html), wait for new block device
                    # to be available to the OS, and interpret it as ours.
                    # Wait under lock scope to reduce false positives.
                    device_path = _wait_for_new_device(
                        blockdevices, volume.size
                    )
                    # We do, however, expect the attached device name to follow
                    # a certain simple pattern.  Verify that now and signal an
                    # error immediately if the assumption is violated.  If we
                    # let it go by, a later call to ``get_device_path`` will
                    # quietly produce the wrong results.
                    #
                    # To make this explicit, we *expect* that the device will
                    # *always* be what we *expect* the device to be (sorry).
                    # This check is only here in case we're wrong to make the
                    # system fail in a less damaging way.
                    if _expected_device(device) != device_path:
                        # We also don't want anything to re-discover the volume
                        # in an attached state since that might also result in
                        # use of ``get_device_path`` (producing an incorrect
                        # result).  This is a best-effort.  It's possible the
                        # agent will crash after attaching the volume and
                        # before detaching it here, leaving the system in a bad
                        # state.  This is one reason we need a better solution
                        # in the long term.
                        self.detach_volume(blockdevice_id)
                        raise AttachedUnexpectedDevice(device, device_path)
                    break
                # end lock scope

        _wait_for_volume(ebs_volume,
                         start_status=u'available',
                         transient_status=u'attaching',
                         end_status=u'in-use')

        attached_volume = volume.set('attached_to', attach_to)
        return attached_volume

    def detach_volume(self, blockdevice_id):
        """
        Detach EBS volume identified by blockdevice_id.

        :param unicode blockdevice_id: EBS UUID for volume to be detached.

        :raises UnknownVolume: If there does not exist a BlockDeviceVolume
            corresponding to the input blockdevice_id.
        :raises UnattachedVolume: If the BlockDeviceVolume for the
            blockdevice_id is not currently 'in-use'.
        """
        ebs_volume = self._get_ebs_volume(blockdevice_id)
        volume = _blockdevicevolume_from_ebs_volume(ebs_volume)
        if (volume.attached_to is None or
                ebs_volume.status != 'in-use'):
            raise UnattachedVolume(blockdevice_id)

        self.connection.detach_volume(blockdevice_id)

        _wait_for_volume(ebs_volume,
                         start_status=u'in-use',
                         transient_status=u'detaching',
                         end_status=u'available')

    def destroy_volume(self, blockdevice_id):
        """
        Destroy EBS volume identified by blockdevice_id.

        :param String blockdevice_id: EBS UUID for volume to be destroyed.

        :raises UnknownVolume: If there does not exist a Flocker cluster
            volume identified by input blockdevice_id.
        :raises Exception: If we failed to destroy Flocker cluster volume
            corresponding to input blockdevice_id.
        """
        ebs_volume = self._get_ebs_volume(blockdevice_id)
        destroy_result = self.connection.delete_volume(blockdevice_id)
        if destroy_result:
            try:
                _wait_for_volume(ebs_volume,
                                 start_status=u'available',
                                 transient_status=u'deleting',
                                 end_status='')
            except UnknownVolume:
                return
        else:
            raise Exception(
                'Failed to delete volume: {!r}'.format(blockdevice_id)
            )

    def get_device_path(self, blockdevice_id):
        """
        Get device path for the EBS volume corresponding to the given
        block device.

        :param unicode blockdevice_id: EBS UUID for the volume to look up.

        :returns: A ``FilePath`` for the device.
        :raises UnknownVolume: If the supplied ``blockdevice_id`` does not
            exist.
        :raises UnattachedVolume: If the supplied ``blockdevice_id`` is
            not attached to a host.
        """
        ebs_volume = self._get_ebs_volume(blockdevice_id)
        volume = _blockdevicevolume_from_ebs_volume(ebs_volume)
        if volume.attached_to is None:
            raise UnattachedVolume(blockdevice_id)

        compute_instance_id = self.compute_instance_id()
        if volume.attached_to != compute_instance_id:
            # This is untested.  See FLOC-2453.
            raise Exception(
                "Volume is attached to {}, not to {}".format(
                    volume.attached_to, compute_instance_id
                )
            )

        return _expected_device(ebs_volume.attach_data.device)

def aws_from_configuration(region, zone, access_key_id, secret_access_key,
                           cluster_id):
    """
    Build an ``EBSBlockDeviceAPI`` instance using configuration and
    credentials.

    :param str region: The EC2 region slug.  Volumes will be manipulated in
        this region.
    :param str zone: The EC2 availability zone.  Volumes will be manipulated in
        this zone.
    :param str access_key_id: The EC2 API key identifier to use to make AWS API
        calls.
    :param str secret_access_key: The EC2 API key to use to make AWS API calls.
    :param UUID cluster_id: The unique identifier of the cluster with which to
        associate the resulting object.  It will only manipulate volumes
        belonging to this cluster.

    :return: A ``EBSBlockDeviceAPI`` instance using the given parameters.
    """
    return EBSBlockDeviceAPI(
        ec2_client=ec2_client(
            region=region,
            zone=zone,
            access_key_id=access_key_id,
            secret_access_key=secret_access_key,
        ),
        cluster_id=cluster_id,
    )


text:
package nl.avansc1.facturatie.controller;

import nl.avansc1.facturatie.model.administration.InsuranceCompany;
import nl.avansc1.facturatie.model.billing.Declaration;
import nl.avansc1.facturatie.model.billing.Invoice;
import nl.avansc1.facturatie.model.billing.PaymentCondition;
import nl.avansc1.facturatie.model.customers.Customer;
import nl.avansc1.facturatie.model.insurances.Policy;
import nl.avansc1.facturatie.repository.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by kevin on 11-10-2016.
 */
@Controller
@RequestMapping("/invoice")
public class InvoiceController {
    private final Logger logger = LoggerFactory.getLogger(DeclarationController.class);

    @Autowired
    private InvoiceDAO invoiceDAO;
    @Autowired
    private InsuranceCompanyDAO insuranceCompanyDAO;
    @Autowired
    private PolicyDAO policyDAO;
    @Autowired
    private DeclarationDAO declarationDAO;
    @Autowired
    private PaymentConditionDAO paymentConditionDAO;
    @Autowired
    private CustomerDAO customerDAO;

    /**
     * Returns page name for displaying invoices in a list
     *
     * @param theModel
     * @return Page name
     */
    @RequestMapping("")
    public String listInvoices(Model theModel) {
        //Get invoices from DAO
        Iterable<Invoice> invoiceList = invoiceDAO.findAll();

        //Add invoices to model
        theModel.addAttribute("invoices", invoiceList);
        theModel.addAttribute("paymentConditions", paymentConditionDAO.findAll());

        //Return page name
        return "invoice/index";
    }

    @RequestMapping(value = "/show/{csn}", method = RequestMethod.GET)
    public String showInvoiceByCsn(Model theModel, @PathVariable int csn) {
        //Get Customer by csn
        Customer customer = customerDAO.findByCsn(csn);

        //Get invoices from DAO
        Iterable<Invoice> invoiceList = invoiceDAO.findByCustomer(customer);

        Invoice invoice = new Invoice();
        invoice.setCustomer(customer);

        //Add invoices to model
        theModel.addAttribute("invoices", invoiceList);
        theModel.addAttribute("invoice", invoice);
        theModel.addAttribute("paymentConditions", paymentConditionDAO.findAll());
        theModel.addAttribute("customer", customer);

        //Return page name
        return "invoice/index";
    }

    /**
     * Deletes invoice by given id in the path variable
     * @param model
     * @param id Invoice id
     * @return Page name
     */
    @RequestMapping(value = "/delete/{id}" , method = RequestMethod.GET)
    public String deleteDeclaration(Model model, @PathVariable int id) {
        logger.debug("Invoice, id = " + id);

        //Delete invoice with Id
        Invoice invoice = invoiceDAO.findOne(id);
        invoiceDAO.delete(invoice);

        //Add successful message to the model
        model.addAttribute("success", "Invoice removed!");

        //Return list with invoices page
        return this.listInvoices(model);
    }

    /**
     * Set payment day and status of a invoice to paid
     * @param model
     * @param id Invoice id
     * @return Page name
     */
    @RequestMapping(value = "/pay/{id}", method = RequestMethod.GET)
    public String payDeclaration(Model model, @PathVariable int id) {
        //Find invoice with given id
        Invoice invoice = invoiceDAO.findOne(id);

        //Set the date payed to today and set the state to paid
        invoice.setDatePayed(new Date());
        invoice.setState(1);

        //Save invoice
        this.invoiceDAO.save(invoice);

        //Add successful message to the model
        model.addAttribute("success", "Invoice marked as paid!");

        // Open view
        return this.listInvoices(model);
    }

    /**
     * Changes the payment condition of a certain invoice
     * @param model
     * @param id Invoice id
     * @param paymentConditionId Payment condition id to change into
     * @return Page name
     */
    @RequestMapping(value = "/{id}/change-payment-condition/{paymentConditionId}", method = RequestMethod.GET)
    public String changePaymenyCondition(Model model, @PathVariable int id, @PathVariable int paymentConditionId) {
        //Find invoice with given id
        Invoice invoice = invoiceDAO.findOne(id);

        //Set the given payment condition
        invoice.setPaymentCondition(paymentConditionDAO.findOne(paymentConditionId));

        //Save invoice
        this.invoiceDAO.save(invoice);

        //Add successful message to the model
        model.addAttribute("success", "Payment Condition updated!");

        // Open view
        return this.listInvoices(model);
    }

    /**
     * Print a certain invoice based on the given id
     * @param model
     * @param id Invoice id
     * @return Page for printing the invoice
     */
    @RequestMapping(value = "/print/{id}", method = RequestMethod.GET)
    public String PrintInvoice(Model model, @PathVariable int id) {
        //Find all the needed info to print the invoice
        Invoice invoice = invoiceDAO.findOne(id);
        Customer customer = invoice.getCustomer();
        Policy policy = policyDAO.findByCustomer(customer);
        InsuranceCompany company = policy.getInsurance().getInsuranceCompany();
        List<Declaration> declarations = declarationDAO.findByCustomer(customer);

        //Add the general info to the model
        model.addAttribute("Invoice", invoice);
        model.addAttribute("Customer", customer);
        model.addAttribute("Company", company);
        model.addAttribute("Declarations", declarations);

        //Loop trough the declarations to get the subtotal
        double subTotal = 0;
        for (Declaration d : declarations) {
            subTotal += (d.getPrice() - d.getCompensated());
        }

        //Format for the decimal values
        DecimalFormat formatter = new DecimalFormat("€ #,##0.00");

        //Round up the vat amount
        double vatAmount = Math.round((subTotal * company.getVat().getPercentageAmount()) * 100.0) / 100.0;

        //Add the payment info to the model
        model.addAttribute("SubTotal", formatter.format(subTotal));
        model.addAttribute("VatAmount", formatter.format(vatAmount));
        model.addAttribute("Total", formatter.format((subTotal + vatAmount)));

        //Replace the temp fill in fields with the data
        String paymentCondition = invoice.getPaymentCondition().getTemplate();
        paymentCondition = paymentCondition.replace("%Amount%", formatter.format((subTotal + vatAmount)));
        paymentCondition = paymentCondition.replace("%period_in_days%", Integer.toString(invoice.getPaymentCondition().getPeriodInDays()));
        paymentCondition = paymentCondition.replace("%BankAccount%", company.getIban());
        paymentCondition = paymentCondition.replace("%Company_Name%", company.getCompanyname());
        paymentCondition = paymentCondition.replace("%Invoice_Ref%", Integer.toString(invoice.getId()));

        //Add the filled in condition to the model
        model.addAttribute("PaymentCondition", paymentCondition);

        //Return the view
        return "invoice/print";
    }

    /**
     * Generates a new invoice for a given customer
     * @param model
     */
    @PostMapping("/create")
    public String GenerateInvoice(Model model, @ModelAttribute Invoice invoice) {
        String url = "https://ivh5c1-api.herokuapp.com/import/" + invoice.getCustomer().getCsn();

        try {
            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();
            con.getInputStream();
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        //Find the customer given
        Customer customer = customerDAO.findByCsn(invoice.getCustomer().getCsn());

        //Find the open decelerations
        List<Declaration> decelerations = declarationDAO.findByCustomerInvoice(customer.getCsn());

        //Find decelerations count already on invoice
        int coveredDecelerations = declarationDAO.findByCustomerAndInvoiceNotNullOrderById(customer).size();

        //Find the policy for the customer
        Policy policy = policyDAO.findByCustomer(customer);

        if (policy != null) {

            //Find the insurance company of the customer
            InsuranceCompany company = policy.getInsurance().getInsuranceCompany();
            //Find the payment condition
            PaymentCondition paymentCondition = paymentConditionDAO.findOne(invoice.getPaymentCondition().getId());

            int needToCover = policy.getInsurance().getCoveredTreatments() - coveredDecelerations;

            float contributionToPay = (policy.getContribution() - policy.getContributionUsed());

            //Create an invoice if there are decelerations
            if (decelerations.size() > 0) {

                invoice = new Invoice();
                invoice.setCustomer(customer);
                invoice.setPaymentCondition(paymentCondition);
                invoice.setVat(company.getVat());
                invoice.setDateCreated(new Date());
                invoice.setState(1);
                invoiceDAO.save(invoice);

                for (Declaration d : decelerations) {
                    if (needToCover > 0) {
                        d.setCompensated(d.getPrice());
                        needToCover -= 1;
                    }
                    if (d.getCompensated() <= 0) {
                        contributionToPay = (policy.getContribution() - policy.getContributionUsed());
                        if (contributionToPay <= 0) {
                            d.setCompensated(d.getPrice());
                        } else {
                            if ((contributionToPay - d.getPrice()) < 0) {
                                d.setCompensated(d.getPrice() - contributionToPay);
                                policy.setContributionUsed(policy.getContributionUsed() + contributionToPay);
                            } else {
                                d.setCompensated(0);
                                policy.setContributionUsed(policy.getContributionUsed() + d.getPrice());
                            }
                            policyDAO.save(policy);
                        }
                    }
                    d.setInvoice(invoice);
                    declarationDAO.save(d);
                }
            } else {
                model.addAttribute("failure", "No declarations for this customer at this moment");
            }
        } else {
            model.addAttribute("failure", "No policy for this customer at this moment");
        }
        return listInvoices(model);
    }

    /**
     * Module name of page
     * @return returns the module name
     */
    @ModelAttribute("page")
    public String module() {
        return "invoices";
    }
}


text:
<?php

$loader = require __DIR__.'/../vendor/autoload.php';
$loader->add('PHPPromTests', __DIR__);


text:
'use strict';

var models = require('./index');

/**
 * @class
 * Initializes a new instance of the CatalogDictionary class.
 * @constructor
 * @member {object} [productDictionary] Dictionary of products
 *
 */
function CatalogDictionary(parameters) {
  if (parameters !== null && parameters !== undefined) {
    if (parameters.productDictionary) {
      this.productDictionary = {};
      for(var valueElement in parameters.productDictionary) {
        if (parameters.productDictionary[valueElement]) {
          this.productDictionary[valueElement] = new models['Product'](parameters.productDictionary[valueElement]);
        }
      }
    }
  }
}

/**
 * Validate the payload against the CatalogDictionary schema
 *
 * @param {JSON} payload
 *
 */
CatalogDictionary.prototype.serialize = function () {
  var payload = {};
  if (this['productDictionary'] && typeof this['productDictionary'] === 'object') {
    payload['productDictionary'] = {};
    for(var valueElement1 in this['productDictionary']) {
      if (this['productDictionary'][valueElement1]) {
        payload['productDictionary'][valueElement1] = this['productDictionary'][valueElement1].serialize();
      }
      else {
        payload['productDictionary'][valueElement1] = this['productDictionary'][valueElement1];
      }
    }
  }

  return payload;
};

/**
 * Deserialize the instance to CatalogDictionary schema
 *
 * @param {JSON} instance
 *
 */
CatalogDictionary.prototype.deserialize = function (instance) {
  if (instance) {
    if (instance['productDictionary']) {
      this['productDictionary'] = {};
      for(var valueElement2 in instance['productDictionary']) {
        if (instance['productDictionary'] !== null && instance['productDictionary'] !== undefined) {
          if (instance['productDictionary'][valueElement2]) {
            this['productDictionary'][valueElement2] = new models['Product']().deserialize(instance['productDictionary'][valueElement2]);
          }
        }
      }
    }
  }

  return this;
};

module.exports = CatalogDictionary;


text:
Widget.Collections.MyModel.fetch();

alert(Widget.Collections.MyModel.length);


text:
js.initbtn = function(obj){
	var o = $("[click]"),i,o1,cl;
	for(i=0; i<o.length; i++){
		o1	= $(o[i]);
		cl	= o1.attr('clickadd');
		if(cl!='true'){
			o1.click(function(){
				var cls = $(this).attr('click');
				if(typeof(cls)=='string'){
					cls=cls.split(',');
					obj[cls[0]](this, cls[1], cls[2]);
				}
				return false;
			});
		}
	}
	o.attr('clickadd','true');
}

js.initedit = function(id,can){
	var cans = js.apply({
		resizeType : 0,
		allowPreviewEmoticons : false,
		allowImageUpload : true,
		formatUploadUrl:false,
		uploadJson:'mode/kindeditor/kindeditor_upload.php',
		allowFileManager:true,
		items : ['fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold', 'italic', 'underline',
			'removeformat', '|', 'justifyleft', 'justifycenter', 'justifyright', 'insertorderedlist',
			'insertunorderedlist', '|','image', 'link','unlink','|','source','clearhtml','fullscreen'],
		blur:function(){

		}
	},can);

	var editorobj = KindEditor.create('#'+id+'', cans);
	return editorobj;
}

js.setwhere	= function(mid,call){
	if(!call)call='';
	var url =js.getajaxurl('@setwhere','where','flow',{modeid:mid,callback:call});
	js.tanbody('setwherewin','设置条件',500,330,{
		html:'

',
		bbar:'none'
	});
	winiframese.location.href=url;
}


text:
package uk.gov.gchq.gaffer.store.operation.handler.output;

import uk.gov.gchq.gaffer.commonutil.iterable.StreamFlatMapIterable;
import uk.gov.gchq.gaffer.data.element.id.EdgeId;
import uk.gov.gchq.gaffer.data.element.id.ElementId;
import uk.gov.gchq.gaffer.data.element.id.EntityId;
import uk.gov.gchq.gaffer.operation.OperationException;
import uk.gov.gchq.gaffer.operation.impl.output.ToVertices;
import uk.gov.gchq.gaffer.operation.impl.output.ToVertices.EdgeVertices;
import uk.gov.gchq.gaffer.operation.impl.output.ToVertices.UseMatchedVertex;
import uk.gov.gchq.gaffer.store.Context;
import uk.gov.gchq.gaffer.store.Store;
import uk.gov.gchq.gaffer.store.operation.handler.OutputOperationHandler;

import java.util.function.Function;
import java.util.stream.Stream;

/**
 * A {@code ToVerticesHandler} handles for {@link ToVertices} operations.
 * <p>
 * For {@link uk.gov.gchq.gaffer.data.element.Entity} objects, the vertex object
 * is used. For {@link uk.gov.gchq.gaffer.data.element.Edge}s the correct object
 * is selected based on the values of the {@link EdgeVertices} and {@link UseMatchedVertex}
 * values.
 * </p>
 */
public class ToVerticesHandler implements OutputOperationHandler<ToVertices, Iterable<? extends Object>> {

    @Override
    public Iterable<Object> doOperation(final ToVertices operation, final Context context, final Store store) throws OperationException {
        if (null == operation.getInput()) {
            return null;
        }

        return new StreamFlatMapIterable<>(operation.getInput(), elementIdsToVertices(operation));
    }

    private Function<ElementId, Stream<Object>> elementIdsToVertices(final ToVertices operation) {
        return e -> {
            final Stream<Object> vertices;

            if (e instanceof EdgeId) {
                final EdgeId edgeId = (EdgeId) e;
                if (EdgeVertices.NONE == operation.getEdgeVertices()) {
                    vertices = Stream.empty();
                } else if (null != edgeId.getMatchedVertex()) {
                    vertices = getMatchedEdgeVertices(operation, edgeId);
                } else if (null != operation.getEdgeVertices()) {
                    vertices = getEdgeVertices(operation.getEdgeVertices(), edgeId);
                } else if (UseMatchedVertex.EQUAL == operation.getUseMatchedVertex()) {
                    vertices = getEdgeVertices(EdgeVertices.SOURCE, edgeId);
                } else if (UseMatchedVertex.OPPOSITE == operation.getUseMatchedVertex()) {
                    vertices = getEdgeVertices(EdgeVertices.DESTINATION, edgeId);
                } else {
                    vertices = getEdgeVertices(operation.getEdgeVertices(), edgeId);
                }
            } else {
                vertices = Stream.of(((EntityId) e).getVertex());
            }
            return vertices;
        };
    }

    private Stream<Object> getMatchedEdgeVertices(final ToVertices operation, final EdgeId edgeId) {
        final Stream<Object> vertices;
        if (UseMatchedVertex.EQUAL == operation.getUseMatchedVertex()) {
            if (EdgeId.MatchedVertex.SOURCE == edgeId.getMatchedVertex()) {
                vertices = Stream.of(edgeId.getSource());
            } else {
                vertices = Stream.of(edgeId.getDestination());
            }
        } else if (UseMatchedVertex.OPPOSITE == operation.getUseMatchedVertex()) {
            if (EdgeId.MatchedVertex.SOURCE == edgeId.getMatchedVertex()) {
                vertices = Stream.of(edgeId.getDestination());
            } else {
                vertices = Stream.of(edgeId.getSource());
            }
        } else {
            vertices = getEdgeVertices(operation.getEdgeVertices(), edgeId);
        }
        return vertices;
    }

    private Stream<Object> getEdgeVertices(final EdgeVertices edgeVertices, final EdgeId edgeId) {
        final Stream<Object> vertices;
        if (null == edgeVertices) {
            vertices = Stream.empty();
        } else {
            switch (edgeVertices) {
                case BOTH:
                    vertices = Stream.of(edgeId.getSource(), edgeId.getDestination());
                    break;
                case SOURCE:
                    vertices = Stream.of(edgeId.getSource());
                    break;
                case DESTINATION:
                    vertices = Stream.of(edgeId.getDestination());
                    break;
                default:
                    vertices = Stream.empty();
                    break;
            }
        }

        return vertices;
    }
}


text:
"""
https://leetcode.com/explore/challenge/card/march-leetcoding-challenge-2021/588/week-1-march-1st-march-7th/3661/
"""

from typing import List

from kevin.utils.bst import TreeNode

class Solution:
    def average_of_levels(self, root: TreeNode) -> List[float]:
        # need to go level by level, so let's do a BFS?
        # add non-None children to the queue
        # pop from start for BFS ordering
        # also have the state encode the level of the given node
        # add that to the running average for each level
        # O(n) BFS runtime to get to each node
        # each average computation should be O(1) if we do things right
        # (could also just do it O(n), that's fine too at first)
        # additional memory complexity would be O(log n) if we just store
        #     current level amounts
        queue = []
        inital_state = (root, 0)  # node, level
        all_vals = [[root.val]]  # list of list of nodes
        queue.append(inital_state)

        while queue:
            current_node, level = queue.pop(0) # pop at 0 for BFS ordering
            current_val = current_node.val

            if len(all_vals) == level:
                # new level
                all_vals.append([current_val])
            else:
                # add to the existing level
                all_vals[level].append(current_val)

            # add non-None children at new levels
            if current_node.left:
                queue.append((current_node.left, level + 1))

            if current_node.right:
                queue.append((current_node.right, level + 1))

        return [sum(vals) / len(vals) for vals in all_vals]

# inspired by:
# https://leetcode.com/explore/challenge/card/march-leetcoding-challenge-2021/588/week-1-march-1st-march-7th/3661/discuss/1094399/Python-simple-bfs-explained
class SolutionOptimized:
    def average_of_levels(self, root: TreeNode) -> List[float]:
        queue = [root]
        result = []

        while queue:
            level = []

            for i in range(len(queue)):
                node = queue.pop(0)
                level.append(node.val)
                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)

            result.append(sum(level) / len(level))

        return result


text:
<?php

/**
 * Created by PhpStorm.
 * User: ibodnar
 * Date: 12.09.15
 * Time: 14:42.
 */
namespace AmaxLab\PhpSpeller;

/**
 * @author Igor Bodnar <ibodnar@amaxlab.ru>
 */
interface ParserInterface
{
    /**
     * @param string $path
     *
     * @return array|Word[]
     */
    public function parseFile($path);

    /**
     * @param \SplFileInfo $fileInfo
     *
     * @return bool
     */
    public function supports(\SplFileInfo $fileInfo);
}


text:
class TagGroupRelation < ActiveRecord::Base
  belongs_to :tag
  belongs_to :group
end


text:
define(['require'], function(require){
  return {templateUrl: require.toUrl('./partials/home.html')}
});


text:
<?php
/**
 * Created by PhpStorm.
 * User: blaze
 * Date: 07.12.2015
 * Time: 21:31
 */

namespace PalufBundle\Security\User;

use Doctrine\ORM\EntityManager;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;

class PalufUserProvider implements UserProviderInterface
{

    /**
     * @var EntityManager
     */
    private $entityManager;

    /**
     * PalufUserProvider constructor.
     * @param EntityManager $entityManager
     */
    public function __construct($entityManager)
    {
        $this->entityManager = $entityManager;
    }

    public function loadUserByUsername($username)
    {
        $user = $this
            ->entityManager
            ->getRepository('PalufBundle:Team')
            ->findOneBy(['email' => $username]);

        if ($user) {
            return new PalufUser($user);
        }

        $user = $this
            ->entityManager
            ->getRepository('PalufBundle:Admin')
            ->findOneBy(['email' => $username]);

        if ($user) {
            return new PalufUser($user);
        }

        throw new UsernameNotFoundException(
            sprintf('Username "%s" does not exist.', $username)
        );
    }

    public function refreshUser(UserInterface $user)
    {
        if (!$user instanceof PalufUser) {
            throw new UnsupportedUserException(
                sprintf('Instances of "%s" are not supported.', get_class($user))
            );
        }

        return $this->loadUserByUsername($user->getUsername());
    }

    public function supportsClass($class)
    {
        return $class === 'PalufBundle\Security\User\PalufUser';
    }

}


text:
The SmartThings Device SDK(for short STDK) is the core device library that allow device applications to securely connect to the SmartThings Cloud.
It has been integrated on TizenRT as a submodule.

## Prerequisites

- Mobile phone with SmartThings application installed.
- Wifi AP could connect internet.
- An Artik053 board or ESP32 Wrover kit board. (with necessary devices connected)
  * Artik053, input button use SW703 on board, RGB LED connect GPIO 53(R), 51(G), 52(B), and GND connect 3.3v
  * ESP32 Wrover, input button connect GPIO 5, RGB LED connect GPIO 18(R), 21(G), 19(B), and GND connect 3.3v

## How to build with STDK

### Update submodule
```shell
git submodule update --init "external/stdk/st-device-sdk-c"
git submodule update --init "external/libsodium/libsodium"
```

### Apply patch for stdk
```shell
cd external/stdk/st-device-sdk-c
git apply ../patch/0001-port-net-fix-ssl-issue-on-TizenRT.patch
```

### Register device and update configure info
refering https://github.com/SmartThingsCommunity/st-device-sdk-c-ref/blob/master/doc/getting_started.md

- Create device identity and update to \apps\examples\stdk_smart_lamp\device_info.json
- Registe device and update information to \apps\examples\stdk_smart_lamp\onboarding_config.json

### Select build config
There are build configs for STDK on different boards supported, choose one according to your testing board.
Reference example of the config is \apps\examples\stdk_smart_lamp
\artik053\STDK
\esp_wrover_kit\STDK

## Test

After build and install the test image on target board, you can easysetup and control the device like other SmartThings device.
- Reboot device.
- Smartthings APP: add device, scan, select STDKxx device.
- Press input button(SW703 for artik or GPIO 5 for esp32) when confirmation is request.
  If input button is unavailable, modify the "BUTTON" to "JUSTWORKS" in onboarding_config.json.
- Select proper WiFi AP on the APP.
- After onboarding is complete, you can control the device then.


text:
package restful.domain;

import lombok.Data;
import lombok.ToString;

import javax.persistence.*;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

@Entity
@Data
@ToString(exclude={"tagsList", "userProfile"})
public class Picture {

	@Id
	@GeneratedValue
	private Long id;

	@ManyToOne
	private UserProfile userProfile;

	@ManyToMany
	@JoinTable(name = "picture_tags",
		joinColumns = @JoinColumn(name = "picture_id"),
		inverseJoinColumns = @JoinColumn(name = "tag_id"))
	private Set<Tag> tagsList = new HashSet<>();

	@Column(nullable = false, length = 127)
	private String originalFileName;

	/* maximum 10Mb */
	@Column(nullable = false, length = 1073741824)
	private byte[] pictureFile;

	@Column(nullable = false, length = 63)
	private String pictureTitle;
	@Column(length = 255)
	private String pictureDescription;

	@Column(nullable = false)
	private int fileSize;

	@Temporal(TemporalType.TIMESTAMP)
	@Column(nullable = false)
	private Date created;
	@Temporal(TemporalType.TIMESTAMP)
	private Date modified;

	@Version
	private long version;

	public Picture(){

	}

	public Picture(String originalFileName, String pictureTitle, String pictureDescription,
				   byte[] pictureFile, int fileSize) {
		super();
		this.originalFileName = originalFileName;
		this.pictureTitle = pictureTitle;
		this.pictureDescription = pictureDescription;

		this.pictureFile = pictureFile;
		this.fileSize = fileSize;

		/* set created date time */
		this.created = new Date();
	}
}


text:
	<title>Deena Payne's panel show appearances</title>

	<link rel="stylesheet" media="all" href="../style.css" type="text/css"/>

Deena Payne's panel show appearances

Deena Payne (born 1954-08-29[ref]) has appeared in 1 episodes between 2010-2010.  Deena Payne on IMDB. Deena Payne on Wikipedia.

2010

2010-01-29 / Loose Women


text:
namespace Visitor.EmployeesDemo.Visitors
{
    using System;

    using Visitor.EmployeesDemo.Employees;

    public class VacationVisitor : IVisitor
    {
        public void Visit(Employee employee)
        {
            if (employee != null)
            {
                // Provide 3 extra vacation days
                // The number of vacation days may be given as a constructor parameter
                employee.VacationDays += 3;
                Console.WriteLine("{0} {1}'s new vacation days: {2}", employee.GetType().Name, employee.Name, employee.VacationDays);
            }
        }
    }
}