text:
import six

from heat.common import exception
from heat.common.i18n import _
from heat.engine import attributes
from heat.engine import constraints
from heat.engine import properties
from heat.engine import resource
from heat.engine.resources.openstack.neutron import neutron
from heat.engine import support

class HealthMonitor(neutron.NeutronResource):
    """
    A resource for managing health monitors for load balancers in Neutron.
    """

    PROPERTIES = (
        DELAY, TYPE, MAX_RETRIES, TIMEOUT, ADMIN_STATE_UP,
        HTTP_METHOD, EXPECTED_CODES, URL_PATH,
    ) = (
        'delay', 'type', 'max_retries', 'timeout', 'admin_state_up',
        'http_method', 'expected_codes', 'url_path',
    )

    ATTRIBUTES = (
        ADMIN_STATE_UP_ATTR, DELAY_ATTR, EXPECTED_CODES_ATTR, HTTP_METHOD_ATTR,
        MAX_RETRIES_ATTR, TIMEOUT_ATTR, TYPE_ATTR, URL_PATH_ATTR, TENANT_ID,
        SHOW,
    ) = (
        'admin_state_up', 'delay', 'expected_codes', 'http_method',
        'max_retries', 'timeout', 'type', 'url_path', 'tenant_id',
        'show',
    )

    properties_schema = {
        DELAY: properties.Schema(
            properties.Schema.INTEGER,
            _('The minimum time in seconds between regular connections of '
              'the member.'),
            required=True,
            update_allowed=True
        ),
        TYPE: properties.Schema(
            properties.Schema.STRING,
            _('One of predefined health monitor types.'),
            required=True,
            constraints=[
                constraints.AllowedValues(['PING', 'TCP', 'HTTP', 'HTTPS']),
            ]
        ),
        MAX_RETRIES: properties.Schema(
            properties.Schema.INTEGER,
            _('Number of permissible connection failures before changing the '
              'member status to INACTIVE.'),
            required=True,
            update_allowed=True
        ),
        TIMEOUT: properties.Schema(
            properties.Schema.INTEGER,
            _('Maximum number of seconds for a monitor to wait for a '
              'connection to be established before it times out.'),
            required=True,
            update_allowed=True
        ),
        ADMIN_STATE_UP: properties.Schema(
            properties.Schema.BOOLEAN,
            _('The administrative state of the health monitor.'),
            default=True,
            update_allowed=True
        ),
        HTTP_METHOD: properties.Schema(
            properties.Schema.STRING,
            _('The HTTP method used for requests by the monitor of type '
              'HTTP.'),
            update_allowed=True
        ),
        EXPECTED_CODES: properties.Schema(
            properties.Schema.STRING,
            _('The list of HTTP status codes expected in response from the '
              'member to declare it healthy.'),
            update_allowed=True
        ),
        URL_PATH: properties.Schema(
            properties.Schema.STRING,
            _('The HTTP path used in the HTTP request used by the monitor to '
              'test a member health.'),
            update_allowed=True
        ),
    }

    attributes_schema = {
        ADMIN_STATE_UP_ATTR: attributes.Schema(
            _('The administrative state of this health monitor.')
        ),
        DELAY_ATTR: attributes.Schema(
            _('The minimum time in seconds between regular connections '
              'of the member.')
        ),
        EXPECTED_CODES_ATTR: attributes.Schema(
            _('The list of HTTP status codes expected in response '
              'from the member to declare it healthy.')
        ),
        HTTP_METHOD_ATTR: attributes.Schema(
            _('The HTTP method used for requests by the monitor of type HTTP.')
        ),
        MAX_RETRIES_ATTR: attributes.Schema(
            _('Number of permissible connection failures before changing '
              'the member status to INACTIVE.')
        ),
        TIMEOUT_ATTR: attributes.Schema(
            _('Maximum number of seconds for a monitor to wait for a '
              'connection to be established before it times out.')
        ),
        TYPE_ATTR: attributes.Schema(
            _('One of predefined health monitor types.')
        ),
        URL_PATH_ATTR: attributes.Schema(
            _('The HTTP path used in the HTTP request used by the monitor '
              'to test a member health.')
        ),
        TENANT_ID: attributes.Schema(
            _('Tenant owning the health monitor.')
        ),
        SHOW: attributes.Schema(
            _('All attributes.')
        ),
    }

    def handle_create(self):
        properties = self.prepare_properties(
            self.properties,
            self.physical_resource_name())
        health_monitor = self.neutron().create_health_monitor(
            {'health_monitor': properties})['health_monitor']
        self.resource_id_set(health_monitor['id'])

    def _show_resource(self):
        return self.neutron().show_health_monitor(
            self.resource_id)['health_monitor']

    def handle_update(self, json_snippet, tmpl_diff, prop_diff):
        if prop_diff:
            self.neutron().update_health_monitor(
                self.resource_id, {'health_monitor': prop_diff})

    def handle_delete(self):
        try:
            self.neutron().delete_health_monitor(self.resource_id)
        except Exception as ex:
            self.client_plugin().ignore_not_found(ex)
        else:
            return True

class Pool(neutron.NeutronResource):
    """
    A resource for managing load balancer pools in Neutron.
    """

    PROPERTIES = (
        PROTOCOL, SUBNET_ID, SUBNET, LB_METHOD, NAME, DESCRIPTION,
        ADMIN_STATE_UP, VIP, MONITORS,
    ) = (
        'protocol', 'subnet_id', 'subnet', 'lb_method', 'name', 'description',
        'admin_state_up', 'vip', 'monitors',
    )

    _VIP_KEYS = (
        VIP_NAME, VIP_DESCRIPTION, VIP_SUBNET, VIP_ADDRESS,
        VIP_CONNECTION_LIMIT, VIP_PROTOCOL_PORT,
        VIP_SESSION_PERSISTENCE, VIP_ADMIN_STATE_UP,
    ) = (
        'name', 'description', 'subnet', 'address',
        'connection_limit', 'protocol_port',
        'session_persistence', 'admin_state_up',
    )

    _VIP_SESSION_PERSISTENCE_KEYS = (
        VIP_SESSION_PERSISTENCE_TYPE, VIP_SESSION_PERSISTENCE_COOKIE_NAME,
    ) = (
        'type', 'cookie_name',
    )

    ATTRIBUTES = (
        ADMIN_STATE_UP_ATTR, NAME_ATTR, PROTOCOL_ATTR, SUBNET_ID_ATTR,
        LB_METHOD_ATTR, DESCRIPTION_ATTR, TENANT_ID, VIP_ATTR,
    ) = (
        'admin_state_up', 'name', 'protocol', 'subnet_id',
        'lb_method', 'description', 'tenant_id', 'vip',
    )

    properties_schema = {
        PROTOCOL: properties.Schema(
            properties.Schema.STRING,
            _('Protocol for balancing.'),
            required=True,
            constraints=[
                constraints.AllowedValues(['TCP', 'HTTP', 'HTTPS']),
            ]
        ),
        SUBNET_ID: properties.Schema(
            properties.Schema.STRING,
            support_status=support.SupportStatus(
                status=support.DEPRECATED,
                message=_('Use property %s.') % SUBNET,
                version='2014.2'),
            constraints=[
                constraints.CustomConstraint('neutron.subnet')
            ]
        ),
        SUBNET: properties.Schema(
            properties.Schema.STRING,
            _('The subnet for the port on which the members '
              'of the pool will be connected.'),
            support_status=support.SupportStatus(version='2014.2'),
            constraints=[
                constraints.CustomConstraint('neutron.subnet')
            ]
        ),
        LB_METHOD: properties.Schema(
            properties.Schema.STRING,
            _('The algorithm used to distribute load between the members of '
              'the pool.'),
            required=True,
            constraints=[
                constraints.AllowedValues(['ROUND_ROBIN',
                                           'LEAST_CONNECTIONS', 'SOURCE_IP']),
            ],
            update_allowed=True
        ),
        NAME: properties.Schema(
            properties.Schema.STRING,
            _('Name of the pool.')
        ),
        DESCRIPTION: properties.Schema(
            properties.Schema.STRING,
            _('Description of the pool.'),
            update_allowed=True
        ),
        ADMIN_STATE_UP: properties.Schema(
            properties.Schema.BOOLEAN,
            _('The administrative state of this pool.'),
            default=True,
            update_allowed=True
        ),
        VIP: properties.Schema(
            properties.Schema.MAP,
            _('IP address and port of the pool.'),
            schema={
                VIP_NAME: properties.Schema(
                    properties.Schema.STRING,
                    _('Name of the vip.')
                ),
                VIP_DESCRIPTION: properties.Schema(
                    properties.Schema.STRING,
                    _('Description of the vip.')
                ),
                VIP_SUBNET: properties.Schema(
                    properties.Schema.STRING,
                    _('Subnet of the vip.'),
                    constraints=[
                        constraints.CustomConstraint('neutron.subnet')
                    ]
                ),
                VIP_ADDRESS: properties.Schema(
                    properties.Schema.STRING,
                    _('IP address of the vip.'),
                    constraints=[
                        constraints.CustomConstraint('ip_addr')
                    ]
                ),
                VIP_CONNECTION_LIMIT: properties.Schema(
                    properties.Schema.INTEGER,
                    _('The maximum number of connections per second '
                      'allowed for the vip.')
                ),
                VIP_PROTOCOL_PORT: properties.Schema(
                    properties.Schema.INTEGER,
                    _('TCP port on which to listen for client traffic '
                      'that is associated with the vip address.'),
                    required=True
                ),
                VIP_SESSION_PERSISTENCE: properties.Schema(
                    properties.Schema.MAP,
                    _('Configuration of session persistence.'),
                    schema={
                        VIP_SESSION_PERSISTENCE_TYPE: properties.Schema(
                            properties.Schema.STRING,
                            _('Method of implementation of session '
                              'persistence feature.'),
                            required=True,
                            constraints=[constraints.AllowedValues(
                                ['SOURCE_IP', 'HTTP_COOKIE', 'APP_COOKIE']
                            )]
                        ),
                        VIP_SESSION_PERSISTENCE_COOKIE_NAME: properties.Schema(
                            properties.Schema.STRING,
                            _('Name of the cookie, '
                              'required if type is APP_COOKIE.')
                        )
                    }
                ),
                VIP_ADMIN_STATE_UP: properties.Schema(
                    properties.Schema.BOOLEAN,
                    _('The administrative state of this vip.'),
                    default=True
                ),
            },
            required=True
        ),
        MONITORS: properties.Schema(
            properties.Schema.LIST,
            _('List of health monitors associated with the pool.'),
            default=[],
            update_allowed=True
        ),
    }

    attributes_schema = {
        ADMIN_STATE_UP_ATTR: attributes.Schema(
            _('The administrative state of this pool.')
        ),
        NAME_ATTR: attributes.Schema(
            _('Name of the pool.')
        ),
        PROTOCOL_ATTR: attributes.Schema(
            _('Protocol to balance.')
        ),
        SUBNET_ID_ATTR: attributes.Schema(
            _('The subnet for the port on which the members of the pool '
              'will be connected.')
        ),
        LB_METHOD_ATTR: attributes.Schema(
            _('The algorithm used to distribute load between the members '
              'of the pool.')
        ),
        DESCRIPTION_ATTR: attributes.Schema(
            _('Description of the pool.')
        ),
        TENANT_ID: attributes.Schema(
            _('Tenant owning the pool.')
        ),
        VIP_ATTR: attributes.Schema(
            _('Vip associated with the pool.')
        ),
    }

    def validate(self):
        res = super(Pool, self).validate()
        if res:
            return res
        self._validate_depr_property_required(
            self.properties, self.SUBNET, self.SUBNET_ID)
        session_p = self.properties[self.VIP].get(self.VIP_SESSION_PERSISTENCE)
        if session_p is None:
            # session persistence is not configured, skip validation
            return

        persistence_type = session_p[self.VIP_SESSION_PERSISTENCE_TYPE]
        if persistence_type == 'APP_COOKIE':
            if session_p.get(self.VIP_SESSION_PERSISTENCE_COOKIE_NAME):
                return

            msg = _('Property cookie_name is required, when '
                    'session_persistence type is set to APP_COOKIE.')
            raise exception.StackValidationFailed(message=msg)

    def handle_create(self):
        properties = self.prepare_properties(
            self.properties,
            self.physical_resource_name())
        self.client_plugin().resolve_subnet(
            properties, self.SUBNET, 'subnet_id')
        vip_properties = properties.pop(self.VIP)
        monitors = properties.pop(self.MONITORS)
        client = self.neutron()
        pool = client.create_pool({'pool': properties})['pool']
        self.resource_id_set(pool['id'])

        for monitor in monitors:
            client.associate_health_monitor(
                pool['id'], {'health_monitor': {'id': monitor}})

        vip_arguments = self.prepare_properties(
            vip_properties,
            '%s.vip' % (self.name,))

        session_p = vip_arguments.get(self.VIP_SESSION_PERSISTENCE)
        if session_p is not None:
            prepared_props = self.prepare_properties(session_p, None)
            vip_arguments['session_persistence'] = prepared_props

        vip_arguments['protocol'] = self.properties[self.PROTOCOL]

        if vip_arguments.get(self.VIP_SUBNET) is None:
            vip_arguments['subnet_id'] = properties[self.SUBNET_ID]
        else:
            vip_arguments['subnet_id'] = self.client_plugin().resolve_subnet(
                vip_arguments, self.VIP_SUBNET, 'subnet_id')

        vip_arguments['pool_id'] = pool['id']
        vip = client.create_vip({'vip': vip_arguments})['vip']

        self.metadata_set({'vip': vip['id']})

    def _show_resource(self):
        return self.neutron().show_pool(self.resource_id)['pool']

    def check_create_complete(self, data):
        attributes = self._show_resource()
        status = attributes['status']
        if status == 'PENDING_CREATE':
            return False
        elif status == 'ACTIVE':
            vip_attributes = self.neutron().show_vip(
                self.metadata_get()['vip'])['vip']
            vip_status = vip_attributes['status']
            if vip_status == 'PENDING_CREATE':
                return False
            if vip_status == 'ACTIVE':
                return True
            if vip_status == 'ERROR':
                raise resource.ResourceInError(
                    resource_status=vip_status,
                    status_reason=_('error in vip'))
            raise resource.ResourceUnknownStatus(
                resource_status=vip_status,
                result=_('Pool creation failed due to vip'))
        elif status == 'ERROR':
            raise resource.ResourceInError(
                resource_status=status,
                status_reason=_('error in pool'))
        else:
            raise resource.ResourceUnknownStatus(
                resource_status=status,
                result=_('Pool creation failed'))

    def handle_update(self, json_snippet, tmpl_diff, prop_diff):
        if prop_diff:
            client = self.neutron()
            if self.MONITORS in prop_diff:
                monitors = set(prop_diff.pop(self.MONITORS))
                old_monitors = set(self.properties[self.MONITORS])
                for monitor in old_monitors - monitors:
                    client.disassociate_health_monitor(self.resource_id,
                                                       monitor)
                for monitor in monitors - old_monitors:
                    client.associate_health_monitor(
                        self.resource_id, {'health_monitor': {'id': monitor}})

            if prop_diff:
                client.update_pool(self.resource_id, {'pool': prop_diff})

    def _resolve_attribute(self, name):
        if name == self.VIP_ATTR:
            return self.neutron().show_vip(self.metadata_get()['vip'])['vip']
        return super(Pool, self)._resolve_attribute(name)

    def handle_delete(self):

        class PoolDeleteProgress(object):
            def __init__(self, val=False):
                self.pool = {'delete_called': val,
                             'deleted': val}
                self.vip = {'delete_called': val,
                            'deleted': val}

        if not self.resource_id:
            progress = PoolDeleteProgress(True)
            return progress

        progress = PoolDeleteProgress()
        if not self.metadata_get():
            progress.vip['delete_called'] = True
            progress.vip['deleted'] = True
        return progress

    def _delete_vip(self):
        return self._not_found_in_call(
            self.neutron().delete_vip, self.metadata_get()['vip'])

    def _check_vip_deleted(self):
        return self._not_found_in_call(
            self.neutron().show_vip, self.metadata_get()['vip'])

    def _delete_pool(self):
        return self._not_found_in_call(
            self.neutron().delete_pool, self.resource_id)

    def check_delete_complete(self, prg):
        if not prg.vip['delete_called']:
            prg.vip['deleted'] = self._delete_vip()
            prg.vip['delete_called'] = True
            return False
        if not prg.vip['deleted']:
            prg.vip['deleted'] = self._check_vip_deleted()
            return False
        if not prg.pool['delete_called']:
            prg.pool['deleted'] = self._delete_pool()
            prg.pool['delete_called'] = True
            return prg.pool['deleted']
        if not prg.pool['deleted']:
            prg.pool['deleted'] = super(Pool, self).check_delete_complete(True)
            return prg.pool['deleted']
        return True

class PoolMember(neutron.NeutronResource):
    """
    A resource to handle load balancer members.
    """

    support_status = support.SupportStatus(version='2014.1')

    PROPERTIES = (
        POOL_ID, ADDRESS, PROTOCOL_PORT, WEIGHT, ADMIN_STATE_UP,
    ) = (
        'pool_id', 'address', 'protocol_port', 'weight', 'admin_state_up',
    )

    ATTRIBUTES = (
        ADMIN_STATE_UP_ATTR, TENANT_ID, WEIGHT_ATTR, ADDRESS_ATTR,
        POOL_ID_ATTR, PROTOCOL_PORT_ATTR, SHOW,
    ) = (
        'admin_state_up', 'tenant_id', 'weight', 'address',
        'pool_id', 'protocol_port', 'show',
    )

    properties_schema = {
        POOL_ID: properties.Schema(
            properties.Schema.STRING,
            _('The ID of the load balancing pool.'),
            required=True,
            update_allowed=True
        ),
        ADDRESS: properties.Schema(
            properties.Schema.STRING,
            _('IP address of the pool member on the pool network.'),
            required=True,
            constraints=[
                constraints.CustomConstraint('ip_addr')
            ]
        ),
        PROTOCOL_PORT: properties.Schema(
            properties.Schema.INTEGER,
            _('TCP port on which the pool member listens for requests or '
              'connections.'),
            required=True,
            constraints=[
                constraints.Range(0, 65535),
            ]
        ),
        WEIGHT: properties.Schema(
            properties.Schema.INTEGER,
            _('Weight of pool member in the pool (default to 1).'),
            constraints=[
                constraints.Range(0, 256),
            ],
            update_allowed=True
        ),
        ADMIN_STATE_UP: properties.Schema(
            properties.Schema.BOOLEAN,
            _('The administrative state of the pool member.'),
            default=True
        ),
    }

    attributes_schema = {
        ADMIN_STATE_UP_ATTR: attributes.Schema(
            _('The administrative state of this pool member.')
        ),
        TENANT_ID: attributes.Schema(
            _('Tenant owning the pool member.')
        ),
        WEIGHT_ATTR: attributes.Schema(
            _('Weight of the pool member in the pool.')
        ),
        ADDRESS_ATTR: attributes.Schema(
            _('IP address of the pool member.')
        ),
        POOL_ID_ATTR: attributes.Schema(
            _('The ID of the load balancing pool.')
        ),
        PROTOCOL_PORT_ATTR: attributes.Schema(
            _('TCP port on which the pool member listens for requests or '
              'connections.')
        ),
        SHOW: attributes.Schema(
            _('All attributes.')
        ),
    }

    def handle_create(self):
        pool = self.properties[self.POOL_ID]
        client = self.neutron()
        protocol_port = self.properties[self.PROTOCOL_PORT]
        address = self.properties[self.ADDRESS]
        admin_state_up = self.properties[self.ADMIN_STATE_UP]
        weight = self.properties[self.WEIGHT]

        params = {
            'pool_id': pool,
            'address': address,
            'protocol_port': protocol_port,
            'admin_state_up': admin_state_up
        }

        if weight is not None:
            params['weight'] = weight

        member = client.create_member({'member': params})['member']
        self.resource_id_set(member['id'])

    def _show_resource(self):
        return self.neutron().show_member(self.resource_id)['member']

    def handle_update(self, json_snippet, tmpl_diff, prop_diff):
        if prop_diff:
            self.neutron().update_member(
                self.resource_id, {'member': prop_diff})

    def handle_delete(self):
        client = self.neutron()
        try:
            client.delete_member(self.resource_id)
        except Exception as ex:
            self.client_plugin().ignore_not_found(ex)
        else:
            return True

class LoadBalancer(resource.Resource):
    """
    A resource to link a neutron pool with servers.
    """

    PROPERTIES = (
        POOL_ID, PROTOCOL_PORT, MEMBERS,
    ) = (
        'pool_id', 'protocol_port', 'members',
    )

    properties_schema = {
        POOL_ID: properties.Schema(
            properties.Schema.STRING,
            _('The ID of the load balancing pool.'),
            required=True,
            update_allowed=True
        ),
        PROTOCOL_PORT: properties.Schema(
            properties.Schema.INTEGER,
            _('Port number on which the servers are running on the members.'),
            required=True,
            constraints=[
                constraints.Range(0, 65535),
            ]
        ),
        MEMBERS: properties.Schema(
            properties.Schema.LIST,
            _('The list of Nova server IDs load balanced.'),
            update_allowed=True
        ),
    }

    default_client_name = 'neutron'

    def handle_create(self):
        pool = self.properties[self.POOL_ID]
        client = self.neutron()
        protocol_port = self.properties[self.PROTOCOL_PORT]

        for member in self.properties[self.MEMBERS] or []:
            address = self.client_plugin('nova').server_to_ipaddress(member)
            lb_member = client.create_member({
                'member': {
                    'pool_id': pool,
                    'address': address,
                    'protocol_port': protocol_port}})['member']
            self.data_set(member, lb_member['id'])

    def handle_update(self, json_snippet, tmpl_diff, prop_diff):
        new_props = json_snippet.properties(self.properties_schema,
                                            self.context)

        # Valid use cases are:
        # - Membership controlled by members property in template
        # - Empty members property in template; membership controlled by
        #   "updates" triggered from autoscaling group.
        # Mixing the two will lead to undefined behaviour.
        if (self.MEMBERS in prop_diff and
                (self.properties[self.MEMBERS] is not None or
                 new_props[self.MEMBERS] is not None)):
            members = set(new_props[self.MEMBERS] or [])
            rd_members = self.data()
            old_members = set(six.iterkeys(rd_members))
            client = self.neutron()
            for member in old_members - members:
                member_id = rd_members[member]
                try:
                    client.delete_member(member_id)
                except Exception as ex:
                    self.client_plugin().ignore_not_found(ex)
                self.data_delete(member)
            pool = self.properties[self.POOL_ID]
            protocol_port = self.properties[self.PROTOCOL_PORT]
            for member in members - old_members:
                address = self.client_plugin('nova').server_to_ipaddress(
                    member)
                lb_member = client.create_member({
                    'member': {
                        'pool_id': pool,
                        'address': address,
                        'protocol_port': protocol_port}})['member']
                self.data_set(member, lb_member['id'])

    def handle_delete(self):
        client = self.neutron()
        # FIXME(pshchelo): this deletes members in a tight loop,
        # so is prone to OverLimit bug similar to LP 1265937
        for member, member_id in self.data().items():
            try:
                client.delete_member(member_id)
            except Exception as ex:
                self.client_plugin().ignore_not_found(ex)
            self.data_delete(member)

def resource_mapping():
    return {
        'OS::Neutron::HealthMonitor': HealthMonitor,
        'OS::Neutron::Pool': Pool,
        'OS::Neutron::PoolMember': PoolMember,
        'OS::Neutron::LoadBalancer': LoadBalancer,
    }


text:
<!doctype html>

<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, minimum-scale=1.0, initial-scale=1.0, user-scalable=yes">

    <script src="../../webcomponentsjs/webcomponents-lite.js"></script>
    <script src="../../web-component-tester/browser.js"></script>
  </head>
  <body>
    <script>
      // Load and run all tests (.html, .js):
      WCT.loadSuites([
        'paper-tree.test.html?dom=shady',
        'paper-tree.test.html?dom=shadow',
        'paper-tree-node.test.html?dom=shady',
        'paper-tree-node.test.html?dom=shadow'
      ]);
    </script>
  </body>
</html>

redpajama_set_name: RedPajamaGithub


text:
class Ve
  class Word

    attr_accessor :word, :lemma, :part_of_speech, :tokens, :extra, :info

    # TODO: More elegance
    def initialize(word, lemma, part_of_speech, tokens, extra = {}, info = {})
      @word = word.dup
      @lemma = lemma.dup
      @part_of_speech = part_of_speech
      @tokens = tokens

      # TODO: I don't like this, it's too unstructured
      @extra = extra
      @info = info
    end

    # TODO: the main part of a word, for example 重要 in 重要な
    def main_part
    end

    def base_form
      @lemma
    end

    def inflected?
      @word != @lemma
    end

    def as_json(verbose = true)
      hash = {
        :word => @word,
        :lemma => @lemma,
        :part_of_speech => @part_of_speech.name,
        :extra => @extra
      }

      if verbose
        hash.merge!({
          :_class => 'Word',
          :tokens => @tokens,
          :info => @info
        })
      end

      hash
    end

  end
end


text:
package de.diddiz.codegeneration.codetree;

import java.util.List;
import java.util.Set;
import de.diddiz.codegeneration.codetree.evaluation.EvaluationContext;
import de.diddiz.codegeneration.codetree.generator.Context;
import de.diddiz.codegeneration.codetree.generator.Generator;
import de.diddiz.codegeneration.exceptions.UndeclaredVariableException;

public class UnaryOperator extends Expression
{
	private final String op;
	private final Expression val;

	public UnaryOperator(String op, Expression val) {
		this.op = op;
		this.val = val;
	}

	@Override
	public boolean eval(EvaluationContext context) throws UndeclaredVariableException {
		switch (op) {
			case "!":
				return !val.eval(context);
			default:
				throw new AssertionError();
		}
	}

	@Override
	public Expression mutate(Set<CodeElement> mutated, Context context) {
		if (mutated.contains(this)) // Mutate this
			return Generator.generateExpression(context);
		// Mutate children
		return new UnaryOperator(op, val.mutate(mutated, context));
	}

	@Override
	public String toCode() {
		return "(" + op + " " + val.toCode() + ")";
	}

	@Override
	protected void gatherChildren(List<CodeElement> children) {
		children.add(val);
		val.gatherChildren(children);
	}

}


text:
				A customizable story about how Keystoke can help your business endeavors.

				Begin your journey

Welcome to Once Upon a Keystoke.

This web application was designed as a 'Choose Your Own Adventure' to help you understand more about Keystoke and when you could need their services.

				Customize your story to your personal interests and information.

				Only see information relevant to your path and information.

				Experience a single page angular app with MongoDB storage.

				Get your finished story emailed to you (Coming Soon!).

				Add have fun.


text:
package ca.flop.jpublish.components;

import com.anthonyeden.lib.config.Configuration;
import com.anthonyeden.lib.config.ConfigurationException;
import com.anthonyeden.lib.util.ClassUtilities;
import org.antlr.stringtemplate.StringTemplate;
import org.antlr.stringtemplate.StringTemplateGroup;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jpublish.JPublishContext;
import org.jpublish.component.AbstractComponent;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * StringTemplate component.
 *
 * @author Florin T.PATRASCU
 * @since $Revision$ (created: 2007.09.01)
 */
public class JPSTComponent extends AbstractComponent {
    private static final Log log = LogFactory.getLog(JPSTComponent.class);
    public static final String BLANK = " ";
    public static final String EMPTY_STRING = "";
    public static final String GROUP_NAME_TERMINATOR = ":";

    private static final String NAME = "JPStringTemplateComponent";
    private static final String DESCRIPTION =
            "This component offers StringTemplate rendering support to any JPublish applications.";

    private Map stringTemplateGroups;
    private int stringTemplateCacheRefreshInterval = 0;
    private static final String DEFAULT_GROUP_NAME = "default";
    private static final String DEFAULT_TEMPLATE_LEXER = "org.antlr.stringtemplate.language.DefaultTemplateLexer";

    /**
     * Load the component's configuration data.  Implementations should
     * override this method if they require configuration.  If an
     * implementation does override this method the implementation
     * should call super.loadConfiguration(configuration)
     * first.
     *
     * @param configuration The configuration data
     * @throws com.anthonyeden.lib.config.ConfigurationException
     *
     */
    public void loadConfiguration(Configuration configuration) throws ConfigurationException {
        String lexerClassName;
        Class lexer;
        StringTemplateGroup stg;
        int refreshInterval;

        super.loadConfiguration(configuration);

        log.info("loading the StringTemplate rendering support...");

        Configuration stGroupsConfiguration = configuration.getChild("stringtemplate-groups");

        if (stGroupsConfiguration == null) {

            throw new ConfigurationException("'stringtemplate-groups' definition is required");

        } else {

            List stGroups = stGroupsConfiguration.getChildren();
            stringTemplateGroups = new HashMap();

            for (int i = 0; i < stGroups.size(); i++) {
                Configuration stGroupConfiguration = (Configuration) stGroups.get(i);
                String stGroupName = stGroupConfiguration.getAttribute("name", DEFAULT_GROUP_NAME);
                String stGroupDir = stGroupConfiguration.getAttribute("absolute-root-dir", EMPTY_STRING);
                String stRelativeGroupDir = stGroupConfiguration.getAttribute("relative-root-dir");

                if (stRelativeGroupDir != null) {
                    stGroupDir = super.getSiteContext().getRoot().getAbsolutePath() +
                            stRelativeGroupDir;
                }

                if (stGroupConfiguration.getAttribute("lexer") == null) {
                    lexerClassName = DEFAULT_TEMPLATE_LEXER;
                } else {
                    lexerClassName = stGroupConfiguration.getAttribute("lexer", DEFAULT_TEMPLATE_LEXER);
                }

                try {
                    lexer = ClassUtilities.loadClass(lexerClassName);
                } catch (ClassNotFoundException e) {
                    throw new ConfigurationException("Stringtemplate Lexer class not found: " + lexerClassName);
                }

                if (stGroupDir != null) {
                    stg = new StringTemplateGroup(stGroupName, stGroupDir, lexer);
                } else {
                    stg = new StringTemplateGroup(stGroupName, lexer);
                }

                refreshInterval = Integer.parseInt(
                        stGroupConfiguration.getAttribute("refresh-interval", "0"));
                stg.setRefreshInterval(refreshInterval);

                stringTemplateGroups.put(stGroupName, stg);
                log.info("... group: " + stGroupName + ", dir: " + stGroupDir + ", cache: " + refreshInterval +
                        "sec.,  lexer: " + lexerClassName + ",defined.");
            }
        }
        log.info("StringTemplate component support available.");

    }

    /**
     * Render the component for the specified path and return the result.
     *
     * @param uriString the stgroup uri locator
     * @param context   The context
     * @return The rendered component
     * @throws Exception
     */
    public String render(String uriString, JPublishContext context) throws Exception {
        STGroup stGroup = new STGroup(uriString);
        StringTemplateGroup group = (StringTemplateGroup) stringTemplateGroups.get(stGroup.getGroupName());
        StringTemplate query = group.getInstanceOf(stGroup.getTemplatePath(), copyContext(context));
        return query.toString();
    }

    /**
     * textilize a given text containing Textile syntax
     *
     * @param text a string containing the Textile syntax
     * @return a textilized text
     * @throws Exception if any
     */
    public String renderText(String text, JPublishContext context) throws Exception {
        StringTemplate query = new StringTemplate(text);
        query.setAttributes(copyContext(context));
        return query.toString();
    }

    /**
     * convenient method to render a StringTemplate in the 'default'
     * StringTemplateGroup
     *
     * @param stringTemplatePath the path to a StringTemplate in the 'default' group name.
     * @return a StringTemplate rendered text
     * @throws Exception if any
     */
    public String renderPath(String stringTemplatePath, JPublishContext context) throws Exception {
        STGroup stGroup = new STGroup(stringTemplatePath);
        StringTemplateGroup group = (StringTemplateGroup) stringTemplateGroups.get(stGroup.getGroupName());
        StringTemplate query = group.getInstanceOf(stGroup.getTemplatePath(), copyContext(context));
        return query.toString();
    }

    public String getName() {
        return NAME;
    }

    public String getDescription() {
        return DESCRIPTION;
    }

    public boolean isCacheEnabled() {
        return stringTemplateCacheRefreshInterval > 0;
    }

    /**
     * get a copy of the context attributes map
     * todo: improve the JPublishContext and prepare it for putAll() [florin]
     *
     * @param context the JPublish context
     * @return a copy of the JPublish context attributes map
     */
    private Map copyContext(JPublishContext context) {
        Map map = new HashMap();
        Object[] ctxKeys = context.getKeys();
        for (int i = 0; i < ctxKeys.length; i++) {
            String key = (String) ctxKeys[i];
            map.put(key, context.get(key));
        }
        return map;
    }

    /**
     * parse the given URI and extract the stgroup name and path.
     * The accepted format is: group_name:template_path
     * If the ':' is missing we assume the 'default' string template name group
     * will be used.
     *

     * [2007.08.19] florin
     */
    protected class STGroup {
        private String groupName = EMPTY_STRING;
        private String templatePath = EMPTY_STRING;

        public STGroup(String uriString) {
            if (uriString != null && uriString.trim().length() > 0) {
                int groupNameTerminatorIndex = uriString.indexOf(GROUP_NAME_TERMINATOR);
                if (groupNameTerminatorIndex <= 0) {
                    groupName = DEFAULT_GROUP_NAME;
                    templatePath = uriString;
                } else {
                    groupName = uriString.substring(0, groupNameTerminatorIndex);
                    templatePath = uriString.substring(groupNameTerminatorIndex + 1);
                    if (log.isDebugEnabled()) {
                        log.debug("accessing StringTemplateGroup: " + groupName + ", template: " + templatePath + "[.st]");
                    }
                }
            } else {
                log.warn("invalid StringTemplate group_name:group_path definiton.");
            }
        }

        public String getGroupName() {
            return groupName;
        }

        public String getTemplatePath() {
            return templatePath;
        }

    }
}


text:
/*!
 * \file ethosn_device.h
 * \brief Arm(R) Ethos(TM)-N NPU device integration.
 */
#ifndef TVM_RUNTIME_CONTRIB_ETHOSN_ETHOSN_DEVICE_H_
#define TVM_RUNTIME_CONTRIB_ETHOSN_ETHOSN_DEVICE_H_

#include <tvm/runtime/registry.h>

#include <vector>

#include "../../../relay/backend/contrib/ethosn/ethosn_api_version.h"
#include "ethosn_runtime.h"

namespace tvm {
namespace runtime {
namespace ethosn {

namespace dl = ::ethosn::driver_library;

using tvm::runtime::TVMArgs;

#if _ETHOSN_API_VERSION_ <= 2102
bool Inference(TVMArgs args, sl::CompiledNetwork* npu, const std::vector<uint32_t>& input_order,
               const std::vector<uint32_t>& output_order);
#else
bool Inference(TVMArgs args, dl::Network* npu, const std::vector<uint32_t>& input_order,
               const std::vector<uint32_t>& output_order);
#endif

}  // namespace ethosn
}  // namespace runtime
}  // namespace tvm

#endif  // TVM_RUNTIME_CONTRIB_ETHOSN_ETHOSN_DEVICE_H_


text:
using namespace clang;
using namespace std;
#endif
#if USE_F2003
#include "F2003Parser/FParser.h"
#endif
#include "FrontTransforms/CantoToReprise.h"
#include "FrontTransforms/Resolver.h"

#include <fstream>

//	Namespaces using
using namespace OPS::Reprise;

//	Enter namespace
namespace OPS
{
namespace Frontend
{

Frontend::Frontend(void) : m_program(new ProgramUnit()), m_clangSettings(ClangParserSettings::defaultSettings())
{
}

Frontend::~Frontend(void)
{
	delete m_program;
}

Options& Frontend::options()
{
	return m_options;
}

clang::ClangParserSettings& Frontend::clangSettings()
{
	return m_clangSettings;
}

const CompileResult& Frontend::compileSingleFile(const std::string& fileName, SourceLanguage language)
{
	delete m_program;
	m_program = new ProgramUnit();
	m_souceList.clear();
	m_sourceBufferList.clear();
	m_results.clear();
	m_bufferResults.clear();
	addSourceFile(fileName, language);
	compile();
	return getResultByName(fileName);
}

void Frontend::addSourceFile(
	const std::string& fileName, SourceLanguage language)
{
	m_souceList.push_back(make_pair(fileName, language));
	m_results.insert(std::make_pair(fileName, CompileResult()));
}

void Frontend::addSourceBuffer(
	const std::string& memoryBuffer, SourceLanguage language)
{
	m_sourceBufferList.push_back(make_pair(memoryBuffer, language));
	m_bufferResults.push_back(CompileResult());
}

void Frontend::clearSources()
{
	m_souceList.clear();
	m_sourceBufferList.clear();
	m_results.clear();
	m_bufferResults.clear();
	delete m_program;
	m_program = new ProgramUnit;
}

bool Frontend::compile(void)
{
	bool success = true;

	for (TFilesList::const_iterator source = m_souceList.begin(); source != m_souceList.end(); ++source)
	{
		SourceLanguage lang = source->second == AutoLanguage
			? guessLanguage(source->first)
			: source->second;

		switch(lang)
		{
#if USE_CLANG
		case CLanguage:
			success &= compileC(source->first, m_results[source->first], false);
			break;
#endif
#if USE_F2003
		case FortranLanguage:
			success &= compileFortran(source->first);
			break;
#endif
		OPS_DEFAULT_CASE_LABEL
		}
	}

	TBufferCompileResults::iterator result = m_bufferResults.begin();
	for (
		TFilesList::const_iterator source = m_sourceBufferList.begin();
		source != m_sourceBufferList.end(); ++ source, ++ result)
	{
		SourceLanguage lang = source->second == AutoLanguage
			? CLanguage
			: source->second;

		switch(lang)
		{
#if USE_CLANG
		case CLanguage:
			success &= compileC(source->first, *result, true);
			break;
#endif
		OPS_DEFAULT_CASE_LABEL
		}
	}

	if (m_options.resolve)
	{
			resolve();
	}

	return success;
}

static const char* const FortranExtensions[] = {"f", "for", "f90", "f95", "f2k"};

SourceLanguage Frontend::guessLanguage(const std::string& fileName)
{
	size_t pos = fileName.rfind('.');
	std::string ext = pos != std::string::npos
		? Strings::tolower(fileName.substr(pos + 1))
		: "";

	for(size_t i = 0; i < sizeof(FortranExtensions)/sizeof(FortranExtensions[0]); ++i)
	{
		if (ext == FortranExtensions[i])
			return FortranLanguage;
	}

	// default - C language
	return CLanguage;
}

std::list<std::string> Frontend::getFilters()
{
	std::list<std::string> filters;

#if USE_CLANG
	filters.push_back("*.c");
#endif

#if USE_F2003
	for(size_t i = 0; i < sizeof(FortranExtensions)/sizeof(FortranExtensions[0]); ++i)
	{
		filters.push_back(std::string("*.") + FortranExtensions[i]);
	}
#endif
	return filters;
}

#if USE_CLANG
bool Frontend::compileC(
	const std::string& fileName, CompileResult& result, bool useMemoryInput)
{
	try
	{
		ReprisePtr<OPS::Reprise::TranslationUnit> unit;
		if (!useMemoryInput)
			result.m_fileName = fileName;

		clang::parseFile(
			fileName, unit, result.m_messages,
			useMemoryInput, m_clangSettings);

		if (unit.get() != 0)
		{
			applyCantoToReprise(*unit);
#ifdef _DEBUG
			OPS::Reprise::Editing::checkParentChildRelations(*unit);
#endif
			m_program->addTranslationUnit(unit);
			return true;
		}
		else
		{
//			m_results[fileName].errorCount = 1;
//			m_results[fileName].errorText = "Unknown reason.";
			return false;
		}
	}
	catch(std::exception& e)
	{
		m_results[fileName].m_messages.push_back(
			CompilerResultMessage(CompilerResultMessage::CRK_ERROR, e.what(), "", fileName,
			CompilerResultMessage::TLocation(0,0), ""));
		return false;
	}
}
#endif

#if USE_F2003
bool Frontend::compileFortran(const std::string& fileName)
{
	try
	{
		m_results[fileName].m_fileName = fileName;
		Fortran2003Parser::FortranParser parser(Fortran2003Parser::FortranParserSettings::createDefault());
		std::unique_ptr<TranslationUnit> unit(parser.parseFile(fileName));

		const OPS::Reprise::CompileResult& result = parser.getCompileResult();
		m_results[fileName].m_messages = result.m_messages;

		if (unit.get() != 0)
		{
			ReprisePtr<TranslationUnit> reprise_unit(unit.release());
			applyCantoToReprise(*reprise_unit);
			if (m_options.convertHirFArrays)
			{
				C2R::convertHirFArrays(*m_program);
			}
#ifdef _DEBUG
			OPS::Reprise::Editing::checkParentChildRelations(*reprise_unit);
#endif
			m_program->addTranslationUnit(reprise_unit);
//			C2R::convertHirFArrays(*m_program);
//			C2R::convertStrictToBasic(*m_program);
			return true;
		}
		return false;
	}
	catch(std::exception& e)
	{
		m_results[fileName].m_messages.push_back(CompilerResultMessage(CompilerResultMessage::CRK_FATAL, e.what(),
			"", fileName, std::make_pair(1, 1), ""));
		return false;
	}
}
#endif

void Frontend::applyCantoToReprise(TranslationUnit& unit)
{
	if (m_options.convertTypes)
	{
		C2R::convertTypes(unit);
	}
	if (m_options.convertVariablesInit)
	{
		C2R::convertVariablesInit(unit);
	}
	if (m_options.convertCommonExpressions || m_options.convertGeneralExpressions || m_options.convertOtherExpressions)
	{
		C2R::convertExpressions(unit, m_options.convertCommonExpressions, m_options.convertGeneralExpressions, m_options.convertOtherExpressions);
	}
	if (m_options.convertLiterals)
	{
		C2R::convertLiterals(unit);
	}
	if (m_options.convertBreakContinue)
	{
		C2R::convertBreakContinue(unit);
	}
}

void Frontend::resolve()
{
    OPS::Transforms::Resolver resolver;
    resolver.setProgram(*m_program);
    resolver.resolve();

    int errorCount = resolver.getErrorCount();

    for(int i = 0; i < errorCount; ++i)
    {
        TCompileResults::reference result = *m_results.begin();
        result.second.m_messages.push_back(
                    CompilerResultMessage(CompilerResultMessage::CRK_ERROR,
                                          resolver.getError(i),
                                          "", result.first, std::make_pair(1, 1), ""));
    }
}

int Frontend::getResultCount(void) const
{
	return static_cast <int> (
		m_souceList.size() + m_sourceBufferList.size());
}

const CompileResult& Frontend::getResult(const unsigned index) const
{
	if (int(index) >= getResultCount())
		throw FrontendError(
			Strings::format(
				"Unexpected getting compile result for index (%u).", index));

	if (index < m_souceList.size())
		return getResultByName(m_souceList[index].first);

	return m_bufferResults[index - m_souceList.size()];
}

const CompileResult& Frontend::getResultByName(const std::string& fileName) const
{
	TCompileResults::const_iterator result = m_results.find(fileName);
	if (result != m_results.end())
		return result->second;
	else
		throw FrontendError(Strings::format("Unexpected getting compile result for file '%s'.", fileName.c_str()));
}

ProgramUnit& Frontend::getProgramUnit(void)
{
	return *m_program;
}

ReprisePtr<ProgramUnit> Frontend::detachProgramUnit(void)
{
	ReprisePtr<ProgramUnit> program(m_program);
	m_program = 0;
	return program;
}

//	Exit namespace
}
}


text:
{% load i18n %}

{% if quantity == 1 %}
    {% blocktrans with title=product.get_title %}
    {{ title }} has been added to your basket.
    {% endblocktrans %}
{% else %}
    {% blocktrans with title=product.get_title quantity=quantity %}
    {{ quantity }} copies of {{ title }}
    have been added to your basket.
    {% endblocktrans %}
{% endif %}


text:
package com.github.chengpohi.builder

import com.github.chengpohi.model.FieldSelector

/**
 * secer
 * Created by chengpohi on 3/19/16.
 */
object FieldSelectorBuilder {
  val fieldSelector = FieldSelector("div", "div")
  val fieldSelectors = List(FieldSelector("div1", "div1"), FieldSelector("div2", "div2"))
}


text:
<?php

namespace cs;

Cache::instance()->clean();
$Config = Config::instance();
$Config->core['frontend_load_optimization'] = 1;
$Config->save();


text:
<?php

namespace Sylius\Component\Shipping\Calculator;

use Sylius\Component\Shipping\Model\ShippingSubjectInterface;

/**
 * @author Antonio Peric <antonio@locastic.com>
 */
class VolumeRateCalculator implements CalculatorInterface
{
    /**
     * {@inheritdoc}
     */
    public function calculate(ShippingSubjectInterface $subject, array $configuration)
    {
        return (int) round($configuration['amount'] * ($subject->getShippingVolume() / $configuration['division']));
    }

    /**
     * {@inheritdoc}
     */
    public function getType()
    {
        return 'volume_rate';
    }
}


text:
stylecow plugin bower-loader
============================

[![Build Status](https://travis-ci.org/stylecow/stylecow-plugin-bower-loader.svg)](https://travis-ci.org/stylecow/stylecow-plugin-bower-loader)

Stylecow plugin to resolve automatically the css paths of packages installed with [bower](http://bower.io/).

You write:

```css
@import "normalize-css";
```

And stylecow resolves the path and converts to:

```css
@import url("../bower_components/normalize-css/normalize.css");
```

You can combine this plugin with [import](https://github.com/stylecow/stylecow-plugin-import) to insert the css code instead resolve only the url.

More demos in [the tests folder](https://github.com/stylecow/stylecow-plugin-bower-loader/tree/master/tests/cases)


text:
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<title>JQuery test</title>


text:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/host_label"
        android:layout_height="wrap_content"
        android:layout_width="fill_parent"
        android:drawableLeft="@drawable/icon_host"
        android:drawablePadding="15sp"
        android:padding="15sp"
        android:gravity="center_vertical"/>


text:
/*globals define, module, require, document*/
(function (root, factory) {
    "use strict";
    if (typeof define === 'function' && define.amd) {
        define([], factory);
    } else if (typeof module !== 'undefined' && module.exports) {
        module.exports = factory();
    } else {
        root.JsonHuman = factory();
    }
}(this, function () {
    "use strict";

    var indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

    function makePrefixer(prefix) {
        return function (name) {
            return prefix + "-" + name;
        };
    }

    function isArray(obj) {
        return toString.call(obj) === '[object Array]';
    }

    function sn(tagName, className, data) {
        var result = document.createElement(tagName);

        result.className = className;
        result.appendChild(document.createTextNode("" + data));

        return result;
    }

    function scn(tagName, className, child) {
        var result = document.createElement(tagName),
            i, len;

        result.className = className;

        if (isArray(child)) {
            for (i = 0, len = child.length; i < len; i += 1) {
                result.appendChild(child[i]);
            }
        } else {
            result.appendChild(child);
        }

        return result;
    }

    function linkNode(child, href, target){
        var a = scn("a", HYPERLINK_CLASS_NAME, child);
        a.setAttribute('href', href);
        a.setAttribute('target', target);
        return a;
    }

    var toString = Object.prototype.toString,
        prefixer = makePrefixer("jh"),
        p = prefixer,
        ARRAY = 1,
        BOOL = 2,
        INT = 3,
        FLOAT = 4,
        STRING = 5,
        OBJECT = 6,
        FUNCTION = 7,
        UNK = 99,

        STRING_CLASS_NAME = p("type-string"),
        STRING_EMPTY_CLASS_NAME = p("type-string") + " " + p("empty"),

        BOOL_TRUE_CLASS_NAME = p("type-bool-true"),
        BOOL_FALSE_CLASS_NAME = p("type-bool-false"),
        BOOL_IMAGE = p("type-bool-image"),
        INT_CLASS_NAME = p("type-int") + " " + p("type-number"),
        FLOAT_CLASS_NAME = p("type-float") + " " + p("type-number"),

        OBJECT_CLASS_NAME = p("type-object"),
        OBJ_KEY_CLASS_NAME = p("key") + " " + p("object-key"),
        OBJ_VAL_CLASS_NAME = p("value") + " " + p("object-value"),
        OBJ_EMPTY_CLASS_NAME = p("type-object") + " " + p("empty"),

        FUNCTION_CLASS_NAME = p("type-function"),

        ARRAY_KEY_CLASS_NAME = p("key") + " " + p("array-key"),
        ARRAY_VAL_CLASS_NAME = p("value") + " " + p("array-value"),
        ARRAY_CLASS_NAME = p("type-array"),
        ARRAY_EMPTY_CLASS_NAME = p("type-array") + " " + p("empty"),

        HYPERLINK_CLASS_NAME = p('a'),

        UNKNOWN_CLASS_NAME = p("type-unk");

    function getType(obj) {
        var type = typeof obj;

        switch (type) {
            case "boolean":
                return BOOL;
            case "string":
                return STRING;
            case "number":
                return (obj % 1 === 0) ? INT : FLOAT;
            case "function":
                return FUNCTION;
            default:
                if (isArray(obj)) {
                    return ARRAY;
                } else if (obj === Object(obj)) {
                    return OBJECT;
                } else {
                    return UNK;
                }
        }
    }

    function _format(data, options, parentKey) {

        var result, container, key, keyNode, valNode, len, childs, tr, value,
            isEmpty = true,
            accum = [],
            type = getType(data);

        // Initialized & used only in case of objects & arrays
        var hyperlinksEnabled, aTarget, hyperlinkKeys ;

        switch (type) {
            case BOOL:
                var boolOpt = options.bool;
                container = document.createElement('div');

                if(boolOpt.showImage) {
                    var img = document.createElement('img');
                    img.setAttribute('class', BOOL_IMAGE);

                    img.setAttribute('src',
                        '' + (data ? boolOpt.img.true : boolOpt.img.false));

                    container.appendChild(img);
                }

                if(boolOpt.showText){
                    container.appendChild(data ?
                        sn("span", BOOL_TRUE_CLASS_NAME, boolOpt.text.true) :
                        sn("span", BOOL_FALSE_CLASS_NAME, boolOpt.text.false));
                }

                result = container;
                break;

            case STRING:
                if (data === "") {
                    result = sn("span", STRING_EMPTY_CLASS_NAME, "(Empty Text)");
                } else {
                    result = sn("span", STRING_CLASS_NAME, data);
                }
                break;
            case INT:
                result = sn("span", INT_CLASS_NAME, data);
                break;
            case FLOAT:
                result = sn("span", FLOAT_CLASS_NAME, data);
                break;
            case OBJECT:
                childs = [];

                aTarget =  options.hyperlinks.target;
                hyperlinkKeys = options.hyperlinks.keys;

                // Is Hyperlink Key
                hyperlinksEnabled =
                    options.hyperlinks.enable &&
                    hyperlinkKeys &&
                    hyperlinkKeys.length > 0;

                for (key in data) {
                    isEmpty = false;

                    value = data[key];

                    valNode = _format(value, options, key);
                    keyNode = sn("th", OBJ_KEY_CLASS_NAME, key);

                    if( hyperlinksEnabled &&
                        typeof(value) === 'string' &&
                        indexOf.call(hyperlinkKeys, key) >= 0){

                        valNode = scn("td", OBJ_VAL_CLASS_NAME, linkNode(valNode, value, aTarget));
                    } else {
                        valNode = scn("td", OBJ_VAL_CLASS_NAME, valNode);
                    }

                    tr = document.createElement("tr");
                    tr.appendChild(keyNode);
                    tr.appendChild(valNode);

                    childs.push(tr);
                }

                if (isEmpty) {
                    result = sn("span", OBJ_EMPTY_CLASS_NAME, "(Empty Object)");
                } else {
                    result = scn("table", OBJECT_CLASS_NAME, scn("tbody", '', childs));
                }
                break;
            case FUNCTION:
                result = sn("span", FUNCTION_CLASS_NAME, data);
                break;
            case ARRAY:
                if (data.length > 0) {
                    childs = [];
                    var showArrayIndices = options.showArrayIndex;

                    aTarget =  options.hyperlinks.target;
                    hyperlinkKeys = options.hyperlinks.keys;

                    // Hyperlink of arrays?
                    hyperlinksEnabled = parentKey && options.hyperlinks.enable &&
                        hyperlinkKeys &&
                        hyperlinkKeys.length > 0 &&
                        indexOf.call(hyperlinkKeys, parentKey) >= 0;

                    for (key = 0, len = data.length; key < len; key += 1) {

                        keyNode = sn("th", ARRAY_KEY_CLASS_NAME, key);
                        value = data[key];

                        if(hyperlinksEnabled && typeof(value) === "string") {
                            valNode = _format(value, options, key);
                            valNode = scn("td", ARRAY_VAL_CLASS_NAME, linkNode(valNode, value, aTarget));
                        } else {
                            valNode = scn("td", ARRAY_VAL_CLASS_NAME, _format(value, options, key));
                        }

                        tr = document.createElement("tr");

                        if(showArrayIndices) {
                            tr.appendChild(keyNode);
                        }
                        tr.appendChild(valNode);

                        childs.push(tr);
                    }

                    result = scn("table", ARRAY_CLASS_NAME, scn("tbody", '', childs));
                } else {
                    result = sn("span", ARRAY_EMPTY_CLASS_NAME, "(Empty List)");
                }
                break;
            default:
                result = sn("span", UNKNOWN_CLASS_NAME, data);
                break;
        }

        return result;
    }

    function format(data, options) {
        options = validateOptions(options || {});

        var result;

        result = _format(data, options);
        result.className = result.className + " " + prefixer("root");

        return result;
    }

    function validateOptions(options){
        options = validateArrayIndexOption(options);
        options = validateHyperlinkOptions(options);
        options = validateBoolOptions(options);

        // Add any more option validators here

        return options;
    }

    function validateArrayIndexOption(options) {
        if(options.showArrayIndex === undefined){
            options.showArrayIndex = true;
        } else {
            // Force to boolean just in case
            options.showArrayIndex = options.showArrayIndex ? true: false;
        }

        return options;
    }

    function validateHyperlinkOptions(options){
        var hyperlinks = {
            enable : false,
            keys : null,
            target : ''
        };

        if(options.hyperlinks && options.hyperlinks.enable) {
            hyperlinks.enable = true;

            hyperlinks.keys =  isArray(options.hyperlinks.keys) ? options.hyperlinks.keys : [];

            if(options.hyperlinks.target) {
                hyperlinks.target = '' + options.hyperlinks.target;
            } else {
                hyperlinks.target = '_blank';
            }
        }

        options.hyperlinks = hyperlinks;

        return options;
    }

    function validateBoolOptions(options){
        if(!options.bool){
            options.bool = {
                text:  {
                    true : "true",
                    false : "false"
                },
                img : {
                    true: "",
                    false: ""
                },
                showImage : false,
                showText : true
            };
        } else {
            var boolOptions = options.bool;

            // Show text if no option
            if(!boolOptions.showText && !boolOptions.showImage){
                boolOptions.showImage  =  false;
                boolOptions.showText  =  true;
            }

            if(boolOptions.showText){
                if(!boolOptions.text){
                    boolOptions.text = {
                        true : "true",
                        false : "false"
                    };
                } else {
                    var t = boolOptions.text.true, f = boolOptions.text.false;

                    if(getType(t) != STRING || t === ''){
                        boolOptions.text.true = 'true';
                    }

                    if(getType(f) != STRING || f === ''){
                        boolOptions.text.false = 'false';
                    }
                }
            }

            if(boolOptions.showImage){
                if(!boolOptions.img.true && !boolOptions.img.false){
                    boolOptions.showImage = false;
                }
            }
        }

        return options;
    }

    return {
        format: format
    };
}));


text: var escpos = require('../escpos');


text:
package org.apache.flink.api.connector.source.util.ratelimit;

import org.apache.flink.annotation.Experimental;

import javax.annotation.concurrent.NotThreadSafe;

import java.util.concurrent.CompletionStage;

/** The interface to rate limit execution of methods. */
@NotThreadSafe
@Experimental
public interface RateLimiter {

    /**
     * Returns a future that is completed once another event would not exceed the rate limit. For
     * correct functioning, the next invocation of this method should only happen after the
     * previously returned future has been completed.
     */
    CompletionStage<Void> acquire();

    /**
     * Notifies this {@code RateLimiter} that the checkpoint with the given {@code checkpointId}
     * completed and was committed. Makes it possible to implement rate limiters that control data
     * emission per checkpoint cycle.
     *
     * @param checkpointId The ID of the checkpoint that has been completed.
     */
    default void notifyCheckpointComplete(long checkpointId) {}
}


text:
"""
Usage:
    python monitor.py randopt_results/simple_example/
"""

import sys
import os
import time
import curses

import randopt as ro

USE_MPL = True
USE_CURSES = True

try:
    from terminaltables import AsciiTable, SingleTable
except:
    raise('run pip install terminaltables')

try:
    import matplotlib.pyplot as plt
except:
    print('matplotlib not found, live plotting disable.')
    USE_MPL = False

def table_statistics(counts, timings, minimums, maximums, name='Experiment'):
    minimum = "{0:.3f}".format(minimums[-1])
    maximum = "{0:.3f}".format(maximums[-1])
    timing = "{0:.2f}".format(timings[-1])
    data = [
        ['Results Count', 'Minimum Result', 'Maximum Result', 'Time Elapsed'],
        [counts[-1], minimum, maximum, timing],
    ]
    if USE_CURSES:
        table = AsciiTable(data, name)
    else:
        table = SingleTable(data, name)
#    table = SingleTable(data, name)
    table.inner_heading_row_border = True
    table.inner_row_border = True
    table.inner_column_border = True
    table.outer_border = False
    table.justify_columns = {0: 'center', 1: 'center', 2: 'center', 3: 'center'}
    return table.table

def plot_statistics(counts, timings, minimums, maximums, name='Experiment'):
    plt.ion()
    plt.clf()

    # Min subplot
    plt.subplot(211)
    plt.title('Experiment ' + name + ' Statistics')
    plt.plot(counts, minimums, label='Minimum')
    plt.legend()
    plt.ylabel('Result')

    # Min subplot
    plt.subplot(212)
    plt.plot(counts, maximums, label='Maximum')
    plt.legend()
    plt.xlabel('Number of experiments')
    plt.ylabel('Result')

    # This renders the figure
    plt.pause(0.05)

if __name__ == '__main__':
    exp_path = sys.argv[1]
    if exp_path[-1] == '/':
        exp_path = exp_path[:-1]
    exp_dir, exp_name = os.path.split(exp_path)
    exp = ro.Experiment(exp_name, directory=exp_dir)

    # init interactive display
    if USE_CURSES:
        screen = curses.initscr()
        curses.noecho()
        curses.cbreak()
        curses.curs_set(False)
        screen.keypad(True)

    start_time = time.time()
    timings = []
    minimums = []
    maximums = []
    counts = []
    try:
        while True:
            minimums.append(exp.minimum().result)
            maximums.append(exp.maximum().result)
            counts.append(exp.count())
            timings.append(time.time() - start_time)
            if USE_MPL:
                plot_statistics(counts, timings, minimums, maximums, exp_name)
            table = table_statistics(
                counts, timings, minimums, maximums, exp_name)
            if USE_CURSES:
                screen.addstr(0, 0, 'Experiment ' + exp_name + ' Statistics')
                for i, line in enumerate(table.split('\n')):
                        line = line.replace('-', u'\u2500')
                        line = line.replace('|', u'\u2502')
                        line = line.replace('+', u'\u253c')
                        screen.addstr(2 + i, 0, line)
                screen.refresh()
            else:
                print(table)
            if USE_MPL:
                plt.pause(5)
            else:
                time.sleep(5)
    finally:
        if USE_CURSES:
            curses.echo()
            curses.nocbreak()
            screen.keypad(True)
            curses.endwin()


text:
<?php namespace Anomaly\Streams\Platform\Model\Files;

use Anomaly\Streams\Platform\Entry\EntryModel;

class FilesBannerPromosiEntryModel extends EntryModel
{

    use \Illuminate\Database\Eloquent\SoftDeletes;

    protected $searchable = false;

    protected $table = 'files_banner_promosi';

    protected $titleName = '';

    protected $rules = [
];

    protected $fields = [
];

    protected $dates = ['created_at', 'updated_at', 'deleted_at'];

    protected $relationships = [];

    protected $translationForeignKey = 'entry_id';

    protected $translationModel = 'Anomaly\Streams\Platform\Model\Files\FilesBannerPromosiEntryTranslationsModel';

    protected $stream = [
'slug' => 'banner_promosi',
'namespace' => 'files',
'translatable' => '1',
'trashable' => '1',
'locked' => '',
'config' => 'a:0:{}',
'prefix' => 'files_',
'id' => '47',
'assignments' => [
],
'translations' => [
[
'id' => 47,
'stream_id' => 47,
'locale' => 'en',
'name' => 'Banner Promosi',
'description' => '',
],
],
];

}


text:
{% extends 'base.html' %}

{% load i18n %}
{% load bootstrap3 %}
{% load embed_video_tags %}

{% block head %}
{{ webform.media }}
{% endblock %}

{% block breadcrumb %}
{% with organizationcontractoraffiliation as affiliation %}

 Dashboard

 Public Contractors

 {{ self.request.user.organization }} Contractor Affiliations

 {{ affiliation.contractor.user.credit_name }}

{% endwith %}
{% endblock breadcrumb %}

{% block content %}

{% with organizationcontractoraffiliation as affiliation %}

Affiliation with {{ affiliation.contractor.user.credit_name }}

Editor Notes

    {{ affiliation.editor_notes }}

Strengths

    {{ affiliation.strengths }}

Conflicts

    {{ affiliation.conflicts }}

Rates

    {{ affiliation.rates }}

W9 on File

    {{ affiliation.w9_on_file }}

In Talent Pool

    {{ affiliation.talent_pool }}

Active Status

    {{ affiliation.status }}

{% endwith %}

{% endblock %}

{% block modals %}

{% endblock modals %}


text:
"""Multiple-producer-multiple-consumer signal-dispatching.

``dispatcher`` is the core of Louie, providing the primary API and the
core logic for the system.

Internal attributes:

- ``WEAKREF_TYPES``: Tuple of types/classes which represent weak
  references to receivers, and thus must be dereferenced on retrieval
  to retrieve the callable object

- ``connections``::

    { senderkey (id) : { signal : [receivers...] } }

- ``senders``: Used for cleaning up sender references on sender
  deletion::

    { senderkey (id) : weakref(sender) }

- ``senders_back``: Used for cleaning up receiver references on receiver
  deletion::

    { receiverkey (id) : [senderkey (id)...] }
"""

import os
import weakref

try:
    set
except NameError:
    from sets import Set as set, ImmutableSet as frozenset

from coherence.extern.louie import error
from coherence.extern.louie import robustapply
from coherence.extern.louie import saferef
from coherence.extern.louie.sender import Any, Anonymous
from coherence.extern.louie.signal import All

# Support for statistics.
if __debug__:
    connects = 0
    disconnects = 0
    sends = 0

    def print_stats():
        print ('\n'
               'Louie connects: %i\n'
               'Louie disconnects: %i\n'
               'Louie sends: %i\n'
               '\n') % (connects, disconnects, sends)

    if 'PYDISPATCH_STATS' in os.environ:
        import atexit
        atexit.register(print_stats)

WEAKREF_TYPES = (weakref.ReferenceType, saferef.BoundMethodWeakref)

connections = {}
senders = {}
senders_back = {}
plugins = []

def reset():
    """Reset the state of Louie.

    Useful during unit testing.  Should be avoided otherwise.
    """
    global connections, senders, senders_back, plugins
    connections = {}
    senders = {}
    senders_back = {}
    plugins = []

def connect(receiver, signal=All, sender=Any, weak=True):
    """Connect ``receiver`` to ``sender`` for ``signal``.

    - ``receiver``: A callable Python object which is to receive
      messages/signals/events.  Receivers must be hashable objects.

      If weak is ``True``, then receiver must be weak-referencable (more
      precisely ``saferef.safe_ref()`` must be able to create a
      reference to the receiver).

      Receivers are fairly flexible in their specification, as the
      machinery in the ``robustapply`` module takes care of most of the
      details regarding figuring out appropriate subsets of the sent
      arguments to apply to a given receiver.

      Note: If ``receiver`` is itself a weak reference (a callable), it
      will be de-referenced by the system's machinery, so *generally*
      weak references are not suitable as receivers, though some use
      might be found for the facility whereby a higher-level library
      passes in pre-weakrefed receiver references.

    - ``signal``: The signal to which the receiver should respond.

      If ``All``, receiver will receive all signals from the indicated
      sender (which might also be ``All``, but is not necessarily
      ``All``).

      Otherwise must be a hashable Python object other than ``None``
      (``DispatcherError`` raised on ``None``).

    - ``sender``: The sender to which the receiver should respond.

      If ``Any``, receiver will receive the indicated signals from any
      sender.

      If ``Anonymous``, receiver will only receive indicated signals
      from ``send``/``send_exact`` which do not specify a sender, or
      specify ``Anonymous`` explicitly as the sender.

      Otherwise can be any python object.

    - ``weak``: Whether to use weak references to the receiver.

      By default, the module will attempt to use weak references to
      the receiver objects.  If this parameter is ``False``, then strong
      references will be used.

    Returns ``None``, may raise ``DispatcherTypeError``.
    """
    if signal is None:
        raise error.DispatcherTypeError(
            'Signal cannot be None (receiver=%r sender=%r)'
            % (receiver, sender))
    if weak:
        receiver = saferef.safe_ref(receiver, on_delete=_remove_receiver)
    senderkey = id(sender)
    if connections.has_key(senderkey):
        signals = connections[senderkey]
    else:
        connections[senderkey] = signals = {}
    # Keep track of senders for cleanup.
    # Is Anonymous something we want to clean up?
    if sender not in (None, Anonymous, Any):
        def remove(object, senderkey=senderkey):
            _remove_sender(senderkey=senderkey)
        # Skip objects that can not be weakly referenced, which means
        # they won't be automatically cleaned up, but that's too bad.
        try:
            weak_sender = weakref.ref(sender, remove)
            senders[senderkey] = weak_sender
        except:
            pass
    receiver_id = id(receiver)
    # get current set, remove any current references to
    # this receiver in the set, including back-references
    if signals.has_key(signal):
        receivers = signals[signal]
        _remove_old_back_refs(senderkey, signal, receiver, receivers)
    else:
        receivers = signals[signal] = []
    try:
        current = senders_back.get(receiver_id)
        if current is None:
            senders_back[receiver_id] = current = []
        if senderkey not in current:
            current.append(senderkey)
    except:
        pass
    receivers.append(receiver)
    # Update stats.
    if __debug__:
        global connects
        connects += 1

def disconnect(receiver, signal=All, sender=Any, weak=True):
    """Disconnect ``receiver`` from ``sender`` for ``signal``.

    - ``receiver``: The registered receiver to disconnect.

    - ``signal``: The registered signal to disconnect.

    - ``sender``: The registered sender to disconnect.

    - ``weak``: The weakref state to disconnect.

    ``disconnect`` reverses the process of ``connect``, the semantics for
    the individual elements are logically equivalent to a tuple of
    ``(receiver, signal, sender, weak)`` used as a key to be deleted
    from the internal routing tables.  (The actual process is slightly
    more complex but the semantics are basically the same).

    Note: Using ``disconnect`` is not required to cleanup routing when
    an object is deleted; the framework will remove routes for deleted
    objects automatically.  It's only necessary to disconnect if you
    want to stop routing to a live object.

    Returns ``None``, may raise ``DispatcherTypeError`` or
    ``DispatcherKeyError``.
    """
    if signal is None:
        raise error.DispatcherTypeError(
            'Signal cannot be None (receiver=%r sender=%r)'
            % (receiver, sender))
    if weak:
        receiver = saferef.safe_ref(receiver)
    senderkey = id(sender)
    try:
        signals = connections[senderkey]
        receivers = signals[signal]
    except KeyError:
        raise error.DispatcherKeyError(
            'No receivers found for signal %r from sender %r'
            % (signal, sender)
            )
    try:
        # also removes from receivers
        _remove_old_back_refs(senderkey, signal, receiver, receivers)
    except ValueError:
        raise error.DispatcherKeyError(
            'No connection to receiver %s for signal %s from sender %s'
            % (receiver, signal, sender)
            )
    _cleanup_connections(senderkey, signal)
    # Update stats.
    if __debug__:
        global disconnects
        disconnects += 1

def get_receivers(sender=Any, signal=All):
    """Get list of receivers from global tables.

    This function allows you to retrieve the raw list of receivers
    from the connections table for the given sender and signal pair.

    Note: There is no guarantee that this is the actual list stored in
    the connections table, so the value should be treated as a simple
    iterable/truth value rather than, for instance a list to which you
    might append new records.

    Normally you would use ``live_receivers(get_receivers(...))`` to
    retrieve the actual receiver objects as an iterable object.
    """
    try:
        return connections[id(sender)][signal]
    except KeyError:
        return []

def live_receivers(receivers):
    """Filter sequence of receivers to get resolved, live receivers.

    This is a generator which will iterate over the passed sequence,
    checking for weak references and resolving them, then returning
    all live receivers.
    """
    for receiver in receivers:
        if isinstance(receiver, WEAKREF_TYPES):
            # Dereference the weak reference.
            receiver = receiver()
        if receiver is not None:
            # Check installed plugins to make sure this receiver is
            # live.
            live = True
            for plugin in plugins:
                if not plugin.is_live(receiver):
                    live = False
                    break
            if live:
                yield receiver

def get_all_receivers(sender=Any, signal=All):
    """Get list of all receivers from global tables.

    This gets all receivers which should receive the given signal from
    sender, each receiver should be produced only once by the
    resulting generator.
    """
    yielded = set()
    for receivers in (
        # Get receivers that receive *this* signal from *this* sender.
        get_receivers(sender, signal),
        # Add receivers that receive *all* signals from *this* sender.
        get_receivers(sender, All),
        # Add receivers that receive *this* signal from *any* sender.
        get_receivers(Any, signal),
        # Add receivers that receive *all* signals from *any* sender.
        get_receivers(Any, All),
        ):
        for receiver in receivers:
            if receiver: # filter out dead instance-method weakrefs
                try:
                    if not receiver in yielded:
                        yielded.add(receiver)
                        yield receiver
                except TypeError:
                    # dead weakrefs raise TypeError on hash...
                    pass

def send(signal=All, sender=Anonymous, *arguments, **named):
    """Send ``signal`` from ``sender`` to all connected receivers.

    - ``signal``: (Hashable) signal value; see ``connect`` for details.

    - ``sender``: The sender of the signal.

      If ``Any``, only receivers registered for ``Any`` will receive the
      message.

      If ``Anonymous``, only receivers registered to receive messages
      from ``Anonymous`` or ``Any`` will receive the message.

      Otherwise can be any Python object (normally one registered with
      a connect if you actually want something to occur).

    - ``arguments``: Positional arguments which will be passed to *all*
      receivers. Note that this may raise ``TypeError`` if the receivers
      do not allow the particular arguments.  Note also that arguments
      are applied before named arguments, so they should be used with
      care.

    - ``named``: Named arguments which will be filtered according to the
      parameters of the receivers to only provide those acceptable to
      the receiver.

    Return a list of tuple pairs ``[(receiver, response), ...]``

    If any receiver raises an error, the error propagates back through
    send, terminating the dispatch loop, so it is quite possible to
    not have all receivers called if a raises an error.
    """
    # Call each receiver with whatever arguments it can accept.
    # Return a list of tuple pairs [(receiver, response), ... ].
    responses = []
    for receiver in live_receivers(get_all_receivers(sender, signal)):
        # Wrap receiver using installed plugins.
        original = receiver
        for plugin in plugins:
            receiver = plugin.wrap_receiver(receiver)
        response = robustapply.robust_apply(
            receiver, original,
            signal=signal,
            sender=sender,
            *arguments,
            **named
            )
        responses.append((receiver, response))
    # Update stats.
    if __debug__:
        global sends
        sends += 1
    return responses

def send_minimal(signal=All, sender=Anonymous, *arguments, **named):
    """Like ``send``, but does not attach ``signal`` and ``sender``
    arguments to the call to the receiver."""
    # Call each receiver with whatever arguments it can accept.
    # Return a list of tuple pairs [(receiver, response), ... ].
    responses = []
    for receiver in live_receivers(get_all_receivers(sender, signal)):
        # Wrap receiver using installed plugins.
        original = receiver
        for plugin in plugins:
            receiver = plugin.wrap_receiver(receiver)
        response = robustapply.robust_apply(
            receiver, original,
            *arguments,
            **named
            )
        responses.append((receiver, response))
    # Update stats.
    if __debug__:
        global sends
        sends += 1
    return responses

def send_exact(signal=All, sender=Anonymous, *arguments, **named):
    """Send ``signal`` only to receivers registered for exact message.

    ``send_exact`` allows for avoiding ``Any``/``Anonymous`` registered
    handlers, sending only to those receivers explicitly registered
    for a particular signal on a particular sender.
    """
    responses = []
    for receiver in live_receivers(get_receivers(sender, signal)):
        # Wrap receiver using installed plugins.
        original = receiver
        for plugin in plugins:
            receiver = plugin.wrap_receiver(receiver)
        response = robustapply.robust_apply(
            receiver, original,
            signal=signal,
            sender=sender,
            *arguments,
            **named
            )
        responses.append((receiver, response))
    return responses

def send_robust(signal=All, sender=Anonymous, *arguments, **named):
    """Send ``signal`` from ``sender`` to all connected receivers catching
    errors

    - ``signal``: (Hashable) signal value, see connect for details

    - ``sender``: The sender of the signal.

      If ``Any``, only receivers registered for ``Any`` will receive the
      message.

      If ``Anonymous``, only receivers registered to receive messages
      from ``Anonymous`` or ``Any`` will receive the message.

      Otherwise can be any Python object (normally one registered with
      a connect if you actually want something to occur).

    - ``arguments``: Positional arguments which will be passed to *all*
      receivers. Note that this may raise ``TypeError`` if the receivers
      do not allow the particular arguments.  Note also that arguments
      are applied before named arguments, so they should be used with
      care.

    - ``named``: Named arguments which will be filtered according to the
      parameters of the receivers to only provide those acceptable to
      the receiver.

    Return a list of tuple pairs ``[(receiver, response), ... ]``

    If any receiver raises an error (specifically, any subclass of
    ``Exception``), the error instance is returned as the result for
    that receiver.
    """
    # Call each receiver with whatever arguments it can accept.
    # Return a list of tuple pairs [(receiver, response), ... ].
    responses = []
    for receiver in live_receivers(get_all_receivers(sender, signal)):
        original = receiver
        for plugin in plugins:
            receiver = plugin.wrap_receiver(receiver)
        try:
            response = robustapply.robust_apply(
                receiver, original,
                signal=signal,
                sender=sender,
                *arguments,
                **named
                )
        except Exception, err:
            responses.append((receiver, err))
        else:
            responses.append((receiver, response))
    return responses

def _remove_receiver(receiver):
    """Remove ``receiver`` from connections."""
    if not senders_back:
        # During module cleanup the mapping will be replaced with None.
        return False
    backKey = id(receiver)
    for senderkey in senders_back.get(backKey, ()):
        try:
            signals = connections[senderkey].keys()
        except KeyError:
            pass
        else:
            for signal in signals:
                try:
                    receivers = connections[senderkey][signal]
                except KeyError:
                    pass
                else:
                    try:
                        receivers.remove(receiver)
                    except Exception:
                        pass
                _cleanup_connections(senderkey, signal)
    try:
        del senders_back[backKey]
    except KeyError:
        pass

def _cleanup_connections(senderkey, signal):
    """Delete empty signals for ``senderkey``. Delete ``senderkey`` if
    empty."""
    try:
        receivers = connections[senderkey][signal]
    except:
        pass
    else:
        if not receivers:
            # No more connected receivers. Therefore, remove the signal.
            try:
                signals = connections[senderkey]
            except KeyError:
                pass
            else:
                del signals[signal]
                if not signals:
                    # No more signal connections. Therefore, remove the sender.
                    _remove_sender(senderkey)

def _remove_sender(senderkey):
    """Remove ``senderkey`` from connections."""
    _remove_back_refs(senderkey)
    try:
        del connections[senderkey]
    except KeyError:
        pass
    # Senderkey will only be in senders dictionary if sender
    # could be weakly referenced.
    try:
        del senders[senderkey]
    except:
        pass

def _remove_back_refs(senderkey):
    """Remove all back-references to this ``senderkey``."""
    try:
        signals = connections[senderkey]
    except KeyError:
        signals = None
    else:
        for signal, receivers in signals.iteritems():
            for receiver in receivers:
                _kill_back_ref(receiver, senderkey)

def _remove_old_back_refs(senderkey, signal, receiver, receivers):
    """Kill old ``senders_back`` references from ``receiver``.

    This guards against multiple registration of the same receiver for
    a given signal and sender leaking memory as old back reference
    records build up.

    Also removes old receiver instance from receivers.
    """
    try:
        index = receivers.index(receiver)
        # need to scan back references here and remove senderkey
    except ValueError:
        return False
    else:
        old_receiver = receivers[index]
        del receivers[index]
        found = 0
        signals = connections.get(signal)
        if signals is not None:
            for sig, recs in connections.get(signal, {}).iteritems():
                if sig != signal:
                    for rec in recs:
                        if rec is old_receiver:
                            found = 1
                            break
        if not found:
            _kill_back_ref(old_receiver, senderkey)
            return True
        return False

def _kill_back_ref(receiver, senderkey):
    """Do actual removal of back reference from ``receiver`` to
    ``senderkey``."""
    receiverkey = id(receiver)
    senders = senders_back.get(receiverkey, ())
    while senderkey in senders:
        try:
            senders.remove(senderkey)
        except:
            break
    if not senders:
        try:
            del senders_back[receiverkey]
        except KeyError:
            pass
    return True


text:
<?php //-->

namespace Cradle\Handlebars;

use Cradle\Helper\InstanceTrait;
use Cradle\Resolver\ResolverTrait;

/**
 * Welcome to Cradle\Handlebars!
 *
 * This definition wraps the Engine to match
 * the handlebars API as close as possible
 *
 * @vendor   Cradle
 * @package  Handlebars
 * @author   Christian Blanquera <cblanquera@openovate.com>
 * @standard PSR-2
 */
class HandlebarsHandler
{
    use ResolverTrait, InstanceTrait;

    /**
     * @const string FILE_PREFIX
     */
    const FILE_PREFIX = '__HANDLEBARS__';

    /**
     * @var string $prefix You can change the file prefix with setPrefix()
     */
    protected $prefix = self::FILE_PREFIX;

    /**
     * @var string|null $cache The cache path location
     */
    protected $cache = null;

    /**
     * @var string $bars
     */
    protected $bars = '{}';

    /**
     * @var array $callbacks A list of compiled template callbacks
     */
    protected static $callbacks = [];

    /**
     * Just load the default helpers
     */
    public function __construct()
    {
        $helpers = include __DIR__.'/helpers.php';

        foreach ($helpers as $name => $helper) {
            $this->registerHelper($name, $helper);
        }
    }

    /**
     * Returns a callback that binds the data with the template
     *
     * @param *string $template the template string
     *
     * @return function The template binding handler
     */
    public function compile($template)
    {
        $name = md5($template);

        if (isset(self::$callbacks[$name])) {
            return self::$callbacks[$name];
        }

        $file = $this->cache . '/' . $this->prefix . $name . '.php';

        if (is_dir($this->cache) && file_exists($file)) {
            $callback = include($file);
        } else {
            $code = $this->resolve(HandlebarsCompiler::class, $this, $template)
                ->compile();

            if (is_dir($this->cache)) {
                file_put_contents($file, $code);
            }

            //called like: function($data) {};
            $callback = @eval('?>'.$code);
            //$this->checkEval($code);
        }

        self::$callbacks[$name] = $callback;

        return $callback;
    }

    /**
     * Returns the bars template
     *
     * @return string
     */
    public function getBars()
    {
        return $this->bars;
    }

    /**
     * Returns the cache location
     *
     * @return string|null
     */
    public function getCache()
    {
        return $this->cache;
    }

    /**
     * Returns a specific helper
     *
     * @param *string $name The name of the helper
     *
     * @return function|null
     */
    public function getHelper($name)
    {
        return $this->resolveStatic(HandlebarsRuntime::class, 'getHelper', $name);
    }

    /**
     * Returns all the registered helpers
     *
     * @return array
     */
    public function getHelpers()
    {
        return $this->resolveStatic(HandlebarsRuntime::class, 'getHelpers');
    }

    /**
     * Returns a specific partial
     *
     * @param *string $name The name of the helper
     *
     * @return string|null
     */
    public function getPartial($name)
    {
        return $this->resolveStatic(HandlebarsRuntime::class, 'getPartial', $name);
    }

    /**
     * Returns all the registered partials
     *
     * @return array
     */
    public function getPartials()
    {
        return $this->resolveStatic(HandlebarsRuntime::class, 'getPartials');
    }

    /**
     * The famous register helper matching the Handlebars API
     *
     * @param *string   $name   The name of the helper
     * @param *callable $helper The helper handler
     *
     * @return HandlebarsHandler
     */
    public function registerHelper($name, $helper)
    {
        $this->resolveStatic(HandlebarsRuntime::class, 'registerHelper', $name, $helper);
        return $this;
    }

    /**
     * Delays registering partials to the engine
     * because there is no add partial method...
     *
     * @param *string $name    The name of the helper
     * @param *string $partial The helper handler
     *
     * @return HandlebarsHandler
     */
    public function registerPartial($name, $partial)
    {
        $this->resolveStatic(HandlebarsRuntime::class, 'registerPartial', $name, $partial);
        return $this;
    }

    /**
     * Resets the helpers and partials
     *
     * @return HandlebarsHandler
     */
    public function reset()
    {
         $this->resolveStatic(HandlebarsRuntime::class, 'flush');
         $this->__construct();
         return $this;
    }

    /**
     * Sets the handlebars characters
     *
     * @param string $bars
     *
     * @return HandlebarsCompiler
     */
    public function setBars($bars)
    {
        if (is_string($bars) && strlen($bars) > 1) {
            $this->bars = $bars;
        }

        return $this;
    }

    /**
     * Enables the cache option
     *
     * @param *string The cache path
     *
     * @return HandlebarsHandler
     */
    public function setCache($path)
    {
        $this->cache = $path;

        return $this;
    }

    /**
     * Sets the file name prefix
     *
     * @param *string $prefix
     *
     * @return HandlebarsHandler
     */
    public function setPrefix($prefix)
    {
        $this->prefix = $prefix;
        return $this;
    }

    /**
     * The opposite of registerHelper
     *
     * @param *string $name the helper name
     *
     * @return HandlebarsHandler
     */
    public function unregisterHelper($name)
    {
        $this->resolveStatic(HandlebarsRuntime::class, 'unregisterHelper', $name);
        return $this;
    }

    /**
     * The opposite of registerPartial
     *
     * @param *string $name the partial name
     *
     * @return HandlebarsHandler
     */
    public function unregisterPartial($name)
    {
        $this->resolveStatic(HandlebarsRuntime::class, 'unregisterPartial', $name);
        return $this;
    }

    /**
     * Returns a very nice error message
     *
     * @param *string $code
     *
     * @return HandlebarsHandler
     */
    protected function checkEval($code)
    {
        $error = error_get_last();

        if (isset($error['message'])
            && isset($error['line'])
            && $error['message'] === 'parse error'
        ) {
            $code = explode("\n", $code);
            $start = $error['line'] - 25;
            if ($start < 0) {
                $start = 0;
            }

            $code = array_splice($code, $start, 50);

            foreach ($code as $i => $line) {
                $code[$i] = (++$start) . ': ' . $line;
            }

            throw HandlebarsException::forCompileError($error, $code);
        }

        return $this;
    }
}