text:
import { FETCH_WEATHER } from './actionTypes.js';
import moment from 'moment';

function weather(state = null, action) {
    switch (action.type) {
        case FETCH_WEATHER:
            return extractCurrentAndForecastWeather(action.payload);
        default:
            return state;
    }
}

function extractCurrentAndForecastWeather(data) {
    const w = {
        current: extractCurrentWeather(data),
        forecast: extractForecastWeather(data),
    };
    return w;
}

function extractCurrentWeather(data) {
    const current = data.currentWeather;
    const feelsLike = getFeelsLikeTemperature(current.main.temp, current.wind.speed);
    const direction = getWindDirection(current.wind.deg);

    return {
        temperature: Math.round(current.main.temp),
        icon: current.weather[0].main,
        condition: current.weather[0].description.toUpperCase(),
        feelsLike: Math.round(feelsLike),
        high: Math.round(current.main.temp_max),
        low: Math.round(current.main.temp_min),
        uvIndex: 0,
        wind: {
            direction: direction,
            speed: Math.round(current.wind.speed)
        }
    };
}

function getFeelsLikeTemperature(temperature, windSpeed) {
    // as described here: http://www.onlineconversion.com/windchill.htm
    return 35.74 + 0.6215 * temperature - 35.75 * Math.pow(windSpeed, 0.16) + 0.4275 * temperature * Math.pow(windSpeed, 0.16);
}

function getWindDirection(angle) {
    // as described here: http://climate.umn.edu/snow_fence/components/winddirectionanddegreeswithouttable3.htm
    if (angle >= 348.75 || angle <= 11.25) {
        return 'N';
    } else if (angle >= 11.25 || angle <= 33.75) {
        return 'NNE';
    } else if (angle >= 33.75 || angle <= 56.25) {
        return 'NE';
    } else if (angle >= 56.25 || angle <= 78.75) {
        return 'ENE';
    } else if (angle >= 78.75 || angle <= 101.25) {
        return 'E';
    } else if (angle >= 101.25 || angle <= 123.75) {
        return 'ESE';
    } else if (angle >= 123.75 || angle <= 146.25) {
        return 'SE';
    } else if (angle >= 146.25 || angle <= 168.75) {
        return 'SSE';
    } else if (angle >= 168.75 || angle <= 191.25) {
        return 'S';
    } else if (angle >= 191.25 || angle <= 213.75) {
        return 'SSW';
    } else if (angle >= 213.75 || angle <= 236.25) {
        return 'SW';
    } else if (angle >= 236.25 || angle <= 258.75) {
        return 'WSW';
    } else if (angle >= 258.75 || angle <= 281.25) {
        return 'W';
    } else if (angle >= 281.25 || angle <= 303.75) {
        return 'WNW';
    } else if (angle >= 303.75 || angle <= 326.25) {
        return 'NW';
    } else if (angle >= 326.25 || angle <= 348.75) {
        return 'NNW';
    }
}

function extractForecastWeather(data) {
    let forecastWeather = [];
    const NUMBER_OF_FORECAST = 4;
    for (let i = 0; i < NUMBER_OF_FORECAST; i++) {
        forecastWeather[i] = getForecast(data.forecastWeather.list, i + 1);
    }
    return forecastWeather;
}

function getForecast(list, shift) {
    const date = moment().add(shift, 'days').hour(12).minute(0).seconds(0).milliseconds(0);
    const raw = findForecast(list, date);
    return {
        id: shift,
        icon: raw.weather[0].icon,
        temperature: Math.round(raw.main.temp),
        humidity: Math.round(raw.main.humidity),
    };
}

function findForecast(list, date) {
    const formattedDate = date.format("YYYY-MM-DD hh:mm:ss");
    return list.find(item => item.dt_txt === formattedDate);
}

export { weather };


text:
from .property import *
from .exceptions import ReservedWordError
from .declarative import DeclarativeMeta, DeclarativeType
from .vertex import Vertex
from .edge import Edge
from .broker import get_broker
from .query import Query
from .batch import Batch
from .commands import CreateVertexCommand, CreateEdgeCommand
from ..utils import to_unicode

import pyorient
from collections import namedtuple

ServerVersion = namedtuple('orientdb_version', ['major', 'minor', 'build'])

class Graph(object):
    def __init__(self, config, user=None, cred=None, strict=False):
        """Connect to OrientDB graph database, creating the database if
        non-existent.

        :param config: Information on database to which to connect
        :param user: (Optional) Username by which to use database
        :param cred: (Optional) Credential for database username
        :param strict: (Optional, default False) Use strict property checking

        :note: user only meaningful when cred also provided.
        """

        self.client = pyorient.OrientDB(config.host, config.port)
        self.client.connect(config.user, config.cred)

        self.config = config

        if config.initial_drop:
            self._last_db = self._last_user = self._last_cred = None
            self.drop()

        db_name = config.db_name
        if db_name:
            self.open(db_name, config.storage, user, cred)

        self.registry = {}
        # Maps property dict from database to added class's property dict
        self.props_from_db = {}

        self.scripts = config.scripts or pyorient.Scripts()

        self.strict = strict

    def open(self, db_name, storage, user=None, cred=None):
        """Open a graph on currently-connected database.

        :param storage: Either 'plocal' or 'memory'
        """
        config = self.config
        config.set_database(db_name, storage)

        # NOTE Odd behaviour; if storage not passed to db_exists, db_create
        # ignores storage
        if not self.client.db_exists(db_name, storage):
            self.client.db_create(db_name
                                  , pyorient.DB_TYPE_GRAPH
                                  , storage)

        if not (user and cred):
            user = config.user
            cred = config.cred
        self._last_user = user
        self._last_cred = cred
        self._last_db = db_name

        cluster_map = self.client.db_open(db_name, user, cred)

        self.server_version = ServerVersion(
            self.client.version.major, self.client.version.minor, self.client.version.build)

        return cluster_map

    def drop(self, db_name=None, storage=None):
        """Drop entire database."""
        config = self.config
        self.client.connect(config.user, config.cred)
        try:
            dropped_db = db_name or config.db_name
            self.client.db_drop(db_name or config.db_name
                                   , storage or config.storage)
        except:
            return False
        finally:
            last_db = self._last_db
            if last_db and last_db is not dropped_db:
                # In case we aren't dropping the currently-configured database,
                # ensure we are still able to use it.
                self.client.db_open(last_db
                                    , self._last_user, self._last_cred)
        return True

    def include(self, registry):
        """Update Graph's registry, when database schema already exists.

        Faster than a full create_all() when it's not required.
        """
        for cls in registry.values():
            db_to_element = Graph.compute_all_properties(cls)
            self.props_from_db[cls] = Graph.create_props_mapping(db_to_element)
            self.init_broker_for_class(cls)
            self.registry[cls.registry_name] = cls

    def build_mapping(self, vertex, edge, auto_plural=False):
        """Use database schema to dynamically build mapping classes.

        Returns a registry suitable for passing to include()

        :param vertex: Base class for vertexes. Always pass new declarative_node.
        :param edge: Base class for edges. Always pass new declarative_relationship.
        :param auto_plural: If True, will automatically set registry_plural
        on classes. For convenience when include() should set brokers.
        """

        registry = {}

        schema = self.client.command(
            'SELECT FROM (SELECT expand(classes) FROM metadata:schema)'
            ' WHERE name NOT IN [\'ORole\', \'ORestricted\', \'OTriggered\','
            ' \'ORIDs\', \'OUser\', \'OIdentity\', \'OSchedule\', \'OFunction\']')

        def resolve_class(name, registries):
            for r in registries:
                if name in r:
                    return r[name]
            return None

        def extract_properties(property_schema, is_edge):
            props = {}
            for p in property_schema:
                linked_class = None
                if 'linkedClass' in p:
                    linked_class = resolve_class(p['linkedClass'], registries)

                prop_name = p['name']
                # Special-case in property, mainly on edges
                if is_edge:
                    if p['name'] == 'in':
                        prop_name = 'in_'
                    elif p['name'] == 'out':
                        prop_name = 'out_'

                props[prop_name] = Graph.property_from_schema(p, linked_class)
            return props

        # We need to topologically sort classes, since we cannot rely on any ordering
        # in the database. In particular defaultClusterId is set to -1 for all abstract
        # classes. Additionally, superclass(es) can be changed post-create, changing the
        # dependency ordering.
        schema = Graph.toposort_classes([c.oRecordData for c in schema])
        registries = [registry, self.registry]
        # We will keep properties of non-graph types here, just in case vertex/edge
        # types derive from them.
        non_graph_properties = {}

        for class_def in schema:
            class_name = class_def['name']
            props = {}
            # Resolve all of the base classes
            base_names = Graph.list_superclasses(class_def)
            bases = []
            for base_name in base_names:
                if base_name == 'V':
                    bases.append(vertex)
                elif base_name == 'E':
                    bases.append(edge)
                else:
                    base = resolve_class(base_name, registries)
                    if base:
                        bases.append(base)
                    else:
                        # Worst-case scenario -- the base is not a graph type
                        props.update(non_graph_properties.get(base_name, {}))

            is_edge = bases and bases[0].decl_type == DeclarativeType.Edge
            props.update(extract_properties(class_def['properties'], is_edge))

            props['class_fields'] = class_def.get('customFields', None) or {}
            props['abstract'] = class_def.get('abstract', False)

            if bases:
                # Create class for the graph type
                props['decl_type'] = bases[0].decl_type

                if is_edge:
                    props['label'] = class_name
                    props['registry_name'] = class_name
                else:
                    if auto_plural:
                        props['element_plural'] = class_name
                        props['registry_plural'] = class_name
                    props['element_type'] = class_name

                # Shouldn't always assume DeclarativeMeta metaclass when constructing the OGM class
                # inheritance is passed through bases
                registry[class_name] = type(bases[0])(class_name, tuple(bases), props)
            else:
                # Otherwise preserve the properties in case a graph type derives from it.
                non_graph_properties[class_name] = props

        return registry

    def clear_registry(self):
        """Clear the registry and associated brokers.

           Useful in preparation for reloading mapping classes from the database
        """
        # Start by removing broker classes from attrs (reverse of init_broker_for_class)
        for k, cls in self.registry.items():
            broker_name = getattr(cls, 'registry_plural', None)
            if (broker_name and not getattr(cls, 'no_graph_broker', False) and
                    hasattr(self, broker_name)):
                delattr(self, broker_name)

        self.registry = {}
        self.props_from_db = {}

    def create_class(self, cls):
        """Add vertex or edge class to database.

        :param cls: Subclass of type returned by declarative_node
            /declarative_relationship
        """

        cls_name = cls.registry_name

        bases = [base for base in cls.__bases__ if Graph.valid_element_base(base)]
        if not bases:
            raise TypeError(
                'Unexpected base class(es) in Graph.create_class'
                ' - try the declarative bases')

        extends = None
        if bases[0] is bases[0].decl_root:
            extends = ['V', 'E'][bases[0].decl_type]
        else:
            extends = ','.join([base.registry_name for base in bases])

        #if not self.client.command(
        #    'SELECT FROM ( SELECT expand( classes ) FROM metadata:schema ) WHERE name = "{}"'
        #        .format(cls_name)):
        try:
            self.client.command(
                'CREATE CLASS {0} EXTENDS {1}'.format(cls_name, extends))
        except pyorient.PyOrientSchemaException:
            # Class already exists
            pass

        props = sorted([(k,v) for k,v in cls.__dict__.items()
                        if isinstance(v, Property)]
                       , key=lambda p:p[1].instance_idx)
        for prop_name, prop_value in props:
            value_name = prop_value.name
            if value_name:
                prop_name = value_name

            Graph.guard_reserved_words(prop_name, cls)

            # Special case in_ and out_ properties for edges
            if cls.decl_type == DeclarativeType.Edge:
                if prop_name == 'in_':
                    prop_name = 'in'
                elif prop_name == 'out_':
                    prop_name = 'out'

            class_prop = '{0}.{1}'.format(cls_name, prop_name)

            linked_to = None
            if isinstance(prop_value, LinkedClassProperty) and prop_value.linked_to is not None:
                type_linked_to = prop_value.linked_to

                # For now, in case type_linked_to is a Property,
                # need to bypass __getattr__()
                if type_linked_to.__dict__.get('registry_name', None):
                    linked_to = type_linked_to.registry_name
                else:
                    link_bases = type_linked_to.__dict__.get('__bases__', None)
                    if link_bases and \
                            isinstance(prop_value, LinkedProperty) and \
                            link_bases[0] is Property:
                        linked_to = type_linked_to.__name__

            try:
                self.client.command(
                    'CREATE PROPERTY {0} {1} {2}'
                        .format(class_prop
                                , type(prop_value).__name__
                                , linked_to or ''))
            except pyorient.PyOrientCommandException:
                # Property already exists
                pass

            if prop_value.default is not None:
                if self.server_version >= (2,1,0):
                    self.client.command(
                        'ALTER PROPERTY {0} DEFAULT {1}'
                            .format(class_prop,
                                    PropertyEncoder.encode_value(prop_value.default)))

            self.client.command(
                    'ALTER PROPERTY {0} NOTNULL {1}'
                        .format(class_prop
                                , str(not prop_value.nullable).lower()))

            self.client.command(
                    'ALTER PROPERTY {} MANDATORY {}'
                        .format(class_prop
                                , str(prop_value.mandatory).lower()))

            self.client.command(
                    'ALTER PROPERTY {} READONLY {}'
                        .format(class_prop
                                , str(prop_value.readonly).lower()))

            # TODO Add support for composite indexes
            if prop_value.indexed:
                try:
                    self.client.command(
                        'CREATE INDEX {0} {1}'
                            .format(class_prop
                                    , 'UNIQUE' if prop_value.unique
                                      else 'NOTUNIQUE'))
                except pyorient.PyOrientIndexException:
                    # Index already exists
                    pass

        # We store all of the properties for the reverse mapping, not only
        # those that are defined directly on the class
        db_to_element = Graph.compute_all_properties(cls)
        self.props_from_db[cls] = Graph.create_props_mapping(db_to_element)
        self.init_broker_for_class(cls)
        self.registry[cls_name] = cls

    def drop_class(self, cls, ignore_instances=False):
        """
        Drop vertex or edge class from database.

        :param cls: Subclass of type returned by declarative_node
            /declarative_relationship
        :param ignore_instances: Don't throw if class has instances;
        *will* still throw if subclassed.
        """
        if ignore_instances:
            self.client.command(
                'DROP CLASS {} UNSAFE'.format(cls.registry_name))
        else:
            self.client.command(
                'DROP CLASS {}'.format(cls.registry_name))

    def create_all(self, registry):
        """Create classes in database for all classes in registry.

        :param registry: Ordered collection of classes to create, bases first.
        """
        for cls in registry.values():
            self.create_class(cls)

    def drop_all(self, registry):
        """Drop all registry classes from database.

        :param registry: Ordered collection of classes to drop, bases first.
        """
        # Drop subclasses first
        for cls in reversed(list(registry.values())):
            self.drop_class(cls, ignore_instances=True)

    def create_vertex(self, vertex_cls, **kwargs):
        result = self.client.command(
            to_unicode(self.create_vertex_command(vertex_cls, **kwargs)))[0]

        props = result.oRecordData
        return vertex_cls.from_graph(self, result._rid,
                                     self.props_from_db[vertex_cls](props))

    def create_vertex_command(self, vertex_cls, **kwargs):
        class_name = vertex_cls.registry_name

        if kwargs:
            db_props = Graph.props_to_db(vertex_cls, kwargs, self.strict)
            set_clause = u' SET {}'.format(
                u','.join(u'{}={}'.format(
                    PropertyEncoder.encode_name(k), PropertyEncoder.encode_value(v))
                    for k, v in db_props.items()))
        else:
            set_clause = u''

        return CreateVertexCommand(
            u'CREATE VERTEX {}{}'.format(class_name, set_clause))

    def create_edge(self, edge_cls, from_vertex, to_vertex, **kwargs):
        result = self.client.command(
            to_unicode(self.create_edge_command(edge_cls
                                     , from_vertex
                                     , to_vertex
                                     , **kwargs)))[0]

        return self.edge_from_record(result, edge_cls)

    def create_edge_command(self, edge_cls, from_vertex, to_vertex, **kwargs):
        class_name = edge_cls.registry_name

        if kwargs:
            db_props = Graph.props_to_db(edge_cls, kwargs, self.strict)
            set_clause = u' SET {}'.format(
                u','.join(u'{}={}'.format(
                    PropertyEncoder.encode_name(k), PropertyEncoder.encode_value(v))
                    for k, v in db_props.items()))
        else:
            set_clause = ''

        return CreateEdgeCommand(
            u'CREATE EDGE {} FROM {} TO {}{}'.format(
                class_name, from_vertex._id, to_vertex._id, set_clause))

    def get_vertex(self, vertex_id):
        record = self.client.command('SELECT FROM {}'.format(vertex_id))
        return self.vertex_from_record(record[0]) if record else None

    def get_edge(self, edge_id):
        record = self.client.command('SELECT FROM {}'.format(edge_id))
        return self.edge_from_record(record[0]) if record else None

    def get_element(self, elem_id):
        record = self.client.command('SELECT FROM {}'.format(elem_id))
        return self.element_from_record(record[0]) if record else None

    def save_element(self, element_class, props, elem_id):
        """:returns: True if successful, False otherwise"""
        if isinstance(element_class, str):
            name = element_class
            element_class = self.registry.get(element_class)
            if not element_class:
                raise KeyError(
                    'Class \'{}\' not registered with graph.'.format(name))

        if props:
            db_props = Graph.props_to_db(element_class, props, self.strict)
            set_clause = u' SET {}'.format(
                u','.join(u'{}={}'.format(
                    PropertyEncoder.encode_name(k), PropertyEncoder.encode_value(v))
                    for k, v in db_props.items()))
        else:
            set_clause = ''

        result = self.client.command(u'UPDATE {}{}'.format(elem_id, set_clause))
        return result and result[0] == b'1'

    def query(self, first_entity, *entities):
        return Query(self, (first_entity,) + entities)

    def batch(self, isolation_level=Batch.READ_COMMITTED):
        return Batch(self, isolation_level)

    def gremlin(self, script, args=None, namespace=None):
        script_body = self.scripts.script_body(script, args, namespace)
        if script_body:
            response = self.client.gremlin(script_body)
        else:
            response = self.client.gremlin(script)
        return self.elements_from_records(response)

    # Vertex-centric functions
    def outE(self, from_, *edge_classes):
        """Get outgoing edges from vertex or class.

        :param from_: Vertex id, class, or class name
        :param edge_classes: Filter by these edges
        """

        edge_classes_quoted = \
            ['"%s"' % s for s in self.coerce_class_names(edge_classes)]
        records = self.client.command('SELECT outE({0}) FROM {1}'
            .format(','.join(edge_classes_quoted),
                    self.coerce_class_names(from_)))
        return [self.get_edge(e) for e in records[0].oRecordData['outE']] \
            if records else []

    def inE(self, to, *edge_classes):
        """Get edges incoming to vertex or class.

        :param to: Vertex id, class, or class name
        :param edge_classes: Filter by these edges
        """
        edge_classes_quoted = \
            ['"%s"' % s for s in self.coerce_class_names(edge_classes)]
        records = self.client.command('SELECT inE({0}) FROM {1}'
            .format(','.join(edge_classes_quoted),
                    self.coerce_class_names(to)))
        return [self.get_edge(e) for e in records[0].oRecordData['inE']] \
            if records else []

    def bothE(self, from_to, *edge_classes):
        """Get outgoing/incoming edges from/to vertex or class.

        :param from_to: Vertex id, class, or class name
        :param edge_classes: Filter by these edges
        """

        edge_classes_quoted = \
            ['"%s"' % s for s in self.coerce_class_names(edge_classes)]
        records = self.client.command('SELECT bothE({0}) FROM {1}'
            .format(','.join(edge_classes_quoted),
                    self.coerce_class_names(from_to)))
        return [self.get_edge(e) for e in records[0].oRecordData['bothE']] \
            if records else []

    def out(self, from_, *edge_classes):
        """Get adjacent outgoing vertexes from vertex or class.

        :param from_: Vertex id, class, or class name
        :param edge_classes: Filter by these edges
        """

        edge_classes_quoted = \
            ['"%s"' % s for s in self.coerce_class_names(edge_classes)]
        records = self.client.command('SELECT out({0}) FROM {1}'
            .format(','.join(edge_classes_quoted),
                    self.coerce_class_names(from_)))
        return [self.get_vertex(v) for v in records[0].oRecordData['out']] \
            if records else []

    def in_(self, to, *edge_classes):
        """Get adjacent incoming vertexes to vertex or class.

        :param to: Vertex id, class, or class name
        :param edge_classes: Filter by these edges
        """

        edge_classes_quoted = \
            ['"%s"' % s for s in self.coerce_class_names(edge_classes)]
        records = self.client.command('SELECT in({0}) FROM {1}'
            .format(','.join(edge_classes_quoted),
                    self.coerce_class_names(to)))
        return [self.get_vertex(v) for v in records[0].oRecordData['in']] \
            if records else []

    def both(self, from_to, *edge_classes):
        """Get adjacent vertexes to vertex or class.

        :param from_to: Vertex id, class, or class name
        :param edge_classes: Filter by these edges
        """

        edge_classes_quoted = \
            ['"%s"' % s for s in self.coerce_class_names(edge_classes)]
        records = self.client.command('SELECT both({0}) FROM {1}'
            .format(','.join(edge_classes_quoted),
                    self.coerce_class_names(from_to)))
        return [self.get_vertex(v) for v in records[0].oRecordData['both']] \
            if records else []

    # The following mostly intended for internal use

    def vertex_from_record(self, record, vertex_cls = None):
        if not vertex_cls:
            vertex_cls = self.registry.get(record._class)

        props = record.oRecordData
        return vertex_cls.from_graph(self
             , record._rid
             , self.props_from_db[vertex_cls](props)) if vertex_cls \
            else Vertex.from_graph(self, record._rid, props)

    def vertexes_from_records(self, records):
        return [self.vertex_from_record(record) for record in records]

    def edge_from_record(self, record, edge_cls = None):
        props = record.oRecordData

        in_hash = None
        in_prop = props['in']
        # Currently it is possible to override 'in' and 'out' with custom
        # properties, which breaks inV()/outV()
        if type(in_prop) is pyorient.OrientRecordLink:
            in_hash = in_prop.get_hash()

        out_hash = None
        out_prop = props['out']
        if type(out_prop) is pyorient.OrientRecordLink:
            out_hash = out_prop.get_hash()

        if not edge_cls:
            edge_cls = self.registry.get(record._class)
        return edge_cls.from_graph(self, record._rid
           , in_hash, out_hash
           , self.props_from_db[edge_cls](props)) if edge_cls \
            else Edge.from_graph(self, record._rid, in_hash, out_hash, props)

    def edges_from_records(self, records):
        return [self.edge_from_record(record) for record in records]

    def element_from_record(self, record):
        if not isinstance(record, pyorient.OrientRecord):
            return record

        record_data = record.oRecordData
        try:
            if isinstance(record_data['in'], pyorient.OrientRecordLink) and \
                    isinstance(record_data['out'],
                               pyorient.OrientRecordLink):
                return self.edge_from_record(record)
            else:
                return self.vertex_from_record(record)
        except:
            return self.vertex_from_record(record)

    def elements_from_records(self, records):
        return [self.element_from_record(record) for record in records]

    def element_from_link(self, link):
        return self.get_element(link.get_hash())

    def elements_from_links(self, links):
        return [self.element_from_link(link) for link in links]

    PROPERTY_TYPES = {
        0:Boolean
        , 1:Integer
        , 2:Short
        , 3:Long
        , 4:Float
        , 5:Double
        , 6:DateTime
        , 7:String
        , 8:Binary
        , 9:Embedded
        , 10:EmbeddedList
        , 11:EmbeddedSet
        , 12:EmbeddedMap
        , 13:Link
        , 14:LinkList
        , 15:LinkSet
        , 16:LinkMap
        , 17:Byte
        , 19:Date
        , 21:Decimal
    }

    @classmethod
    def property_from_schema(cls, prop_def, linked_class=None):
        prop_type = cls.PROPERTY_TYPES.get(prop_def['type'], Property)

        property_params = {
            'nullable': not prop_def['notNull'],
            'default': prop_def.get('defaultValue', None),
            'indexed': False, # FIXME
            'unique': False, # FIXME
            'mandatory': prop_def['mandatory'],
            'readonly': prop_def['readonly']
        }

        if linked_class:
            property_params['linked_to'] = linked_class

        return prop_type(**property_params)

    @staticmethod
    def valid_element_base(cls):
        try:
            return cls.decl_root is not None and cls.decl_type is not None
        except AttributeError:
            return False

    @staticmethod
    def guard_reserved_words(word, cls):
        reserved_words = [[],['in', 'out']][cls.decl_type]
        if word in reserved_words:
            # Should the class also be dropped from the database?
            raise ReservedWordError(
                "'{0}' as a property name will render"
                " class '{1}' unusable.".format(word,
                                                cls.registry_name))

    @staticmethod
    def create_props_mapping(db_to_element):
        return lambda db_props: {
            db_to_element[k]:v for k,v in db_props.items()
                if k in db_to_element }

    @staticmethod
    def props_to_db(element_class, props, strict):
        db_props = {}
        for k, v in props.items():
            # sanitize the property name -- this line
            # will raise an error if the name is invalid
            PropertyEncoder.encode_name(k)

            if hasattr(element_class, k):
                prop = getattr(element_class, k)
                db_props[prop.name or k] = v
            elif strict:
                raise AttributeError('Class {} has no property {}'.format(
                    element_class, k))
            # if we are not in the strict mode, swallow missing properties
        return db_props

    @staticmethod
    def compute_all_properties(cls):
        """Compute all properties (including the inherited ones) for the class """
        all_properties = {}

        props = []
        # Get all of the properties of the class including inherited ones
        for m in dir(cls):
            p = getattr(cls, m)
            if isinstance(p, Property):
                props.append((m, p))

        props = sorted(props, key=lambda p:p[1].instance_idx)
        for prop_name, prop_value in props:
            value_name = prop_value.name
            if value_name:
                all_properties[value_name] = prop_name
                prop_name = value_name
            else:
                all_properties[prop_name] = prop_name

            Graph.guard_reserved_words(prop_name, cls)
        return all_properties

    @staticmethod
    def coerce_class_names(classes):
        """Get class name(s) for vertexes/edges.

        :param classes: String/class object or list of strings/class objects
        :returns: List if input is iterable, string otherwise
        """
        return [getattr(val, 'registry_name', val) for val in classes] \
            if hasattr(classes, '__iter__') and not isinstance(classes, str) \
            else getattr(classes, 'registry_name', classes)

    @staticmethod
    def coerce_class_names_to_quoted(classes):
        """Get the quoted class name(s) for vertexes/edges. Useful when passing them to some operators"""
        names = Graph.coerce_class_names(classes)
        return [repr(name) for name in names] if names else []

    def init_broker_for_class(self, cls):
        broker = get_broker(cls)
        if broker:
            broker.init(self, cls)
        else:
            broker = cls.Broker(self, cls)
            setattr(cls, 'objects', broker)

        # Graph will only be assigned the broker for this element class if a
        # 'registry_plural' is set.
        #
        # Otherwise, only the class itself will get a Broker.
        broker_name = getattr(cls, 'registry_plural', None)
        if broker_name and not getattr(cls, 'no_graph_broker', False):
            if hasattr(self, broker_name):
                raise RuntimeError(
                    'Attempt to use a broker name reserved by Graph. '
                    'Could use a different name, or set the \'no_graph_broker\''
                    ' attribute to True for this element class.')
            setattr(self, broker_name, broker)

    @staticmethod
    def toposort_classes(classes):
        """Sort class metadatas so that a superclass is always before the subclass"""
        def get_class_topolist(class_name, name_to_class, processed_classes, current_trace):
            """Return a topologically sorted list of this class's dependencies and class itself

            :param class_name: name of the class to process
            :param name_to_class: a map from class name to the descriptor
            :param processed_classes: a set of classes that have already been processed
            :param current_trace: list of classes traversed during the recursion.

            :returns: element of classes list sorted in topological order
            """
            # Check if this class has already been handled
            if class_name in processed_classes:
                return []

            if class_name in current_trace:
                raise AssertionError(
                    'Encountered self-reference in dependency chain of {}'.format(class_name))

            cls = name_to_class[class_name]
            # Collect the dependency classes
            # These are bases and classes from linked properties
            dependencies = Graph.list_superclasses(cls)
            # Recursively process linked edges
            properties = cls['properties'] if 'properties' in cls else []
            for prop in properties:
                if 'linkedClass' in prop:
                    dependencies.append(prop['linkedClass'])

            class_list = []
            # Recursively process superclasses
            current_trace.add(class_name)
            for dependency in dependencies:
                class_list.extend(get_class_topolist(
                    dependency, name_to_class, processed_classes, current_trace))
            current_trace.remove(class_name)
            # Do the bookkeeping
            class_list.append(name_to_class[class_name])
            processed_classes.add(class_name)

            return class_list

        # Map names to classes
        class_map = {c['name']: c for c in classes}
        seen_classes = set()

        toposorted = []
        for name in class_map.keys():
            toposorted.extend(get_class_topolist(name, class_map, seen_classes, set([])))
        return toposorted

    @staticmethod
    def list_superclasses(class_def):
        superclasses = class_def.get('superClasses', [])
        if superclasses:
            # Make sure to duplicate the list
            return list(superclasses)

        sup = class_def.get('superClass', None)
        if sup:
            return [sup]
        else:
            return []

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.ComponentModel.DataAnnotations;
using System.Runtime.Serialization;

namespace EspaceClient.FrontOffice.Domaine
{
    public partial class Lien_Client_Personne_Acces_Illimite
    {

        [DataMember]
        public long ID { get; set; }

        [DataMember]
        public virtual Client Client { get; set; }

        [DataMember]
        public long ClientID { get; set; }

        [DataMember]
        public virtual Personne Personne { get; set; }

        [DataMember]
        public long PersonneID { get; set; }
    }
}


text:
'use strict';

const LIVE_DB = 1; // for development or production
const TEST_DB = 2; // for testing (so we cache data separately)
const REDIS_DB = process.env.NODE_ENV === 'test' ? TEST_DB : LIVE_DB;
const REDIS_URL = 'redis://localhost:6379';

const redis = process.env.NODE_ENV === 'test' ? require('fakeredis')
                                              : require('redis');

function create( redisOpts ) {

  redisOpts = redisOpts || {};
  redisOpts.db = redisOpts.db || process.env.REDIS_DATABASE || REDIS_DB;
  redisOpts.password = redisOpts.password || process.env.REDIS_PASSWORD;
  redisOpts.prefix = redisOpts.prefix || process.env.REDIS_PREFIX;
  redisOpts.url = redisOpts.url || process.env.REDIS_URL || REDIS_URL;

  return redis.createClient( redisOpts );
}

module.exports = { create };

// EOF


text:
hBPF: An Embedded Haskell DSL for BPF Assembly
----------------------------------------------

**hBPF** is a declarative DSL that is embedded in Haskell for forming and compiling BPF assembly.
Users write their filters in a high-level, typed functional syntax that then gets compiled under the hood into BPF assembly code.

The assembly code generated can then be passed into a BPF assembler, an example is [bpf_asm](https://github.com/torvalds/linux/blob/master/tools/net/bpf_asm.c) as provided under the tools/net directory in the Linux kernel.

This repository serves as the source code for the final project for Stanford's [CS 240H](http://www.scs.stanford.edu/16wi-cs240h/) taught by [David Mazières](http://www.scs.stanford.edu/~dm/) and [Bryan O'Sullivan](http://www.serpentine.com/blog/) in the Winter of 2016.

Work of Andrew Duffy (agd@cs.stanford.edu) and Matt Denton (mdenton@cs.stanford.edu)


text:
<?php
require_once __DIR__ . '/../common.php';
use Wcs\Upload\Uploader;
use Wcs\Http\PutPolicy;
use Wcs\Config;

function print_help() {
    echo "Usage: php file_upload_return.php [-h | --help] -b <bucketName> -f <fileKey> -l <localFile> \n";
}
$opts = "hb:f:l:";
$longopts = array (
    'h',
    'help'
);

$options = getopt($opts, $longopts);
if (isset($options['h']) || isset($options['help'])) {
    print_help();
    exit(0);
}

if (!isset($options['b']) || !isset($options['f']) || !isset($options['l'])) {
    print_help();
    exit(0);
}

$bucketName = $options['b'];
$fileKey = $options['f'];
$localFile = $options['l'];
$contentdetect = 'imagePorn';
$detectNotifyURL = '';
$detectNotifyRule = 'all';

print("bucket: \t$bucketName\n");
print("file: \t\t$fileKey\n");
print("localFile: \t$localFile\n");
print("contentdetect: \t$contentdetect\n");
print("\n");

$pp = new PutPolicy();
$pp->overwrite = Config::WCS_OVERWRITE;
if ($fileKey == null || $fileKey == '') {
    $pp->scope = $bucketName;
} else {
    $pp->scope = $bucketName . ':' . $fileKey;
}
$pp->deadline = '1483027200000';
$pp->contentDetect = $contentdetect;
if ($detectNotifyURL != null || $detectNotifyURL != '') {
    $pp->detectNotifyURL = $detectNotifyURL;
}
if ($detectNotifyRule != null || $detectNotifyRule != '') {
    $pp->detectNotifyRule = $detectNotifyRule;
}
$token = $pp->get_token();

$client = new Uploader($token);
print_r($client->upload_return($localFile));
print("\n");


text:
describe Rains::Form do
  include_context 'preloaded translations'

  before do
    module User
      class IsAdult < Rains::Assertion
        attribute :age

        def check
          return true if age.nil?

          age >= 18
        end
      end

      class IsNameValid < Rains::Assertion
        attribute :name

        def check
          (3..20).include?(name.size)
        end
      end

      class Form < Rains::Form
        attribute :name, String
        attribute :age, Integer, required: false

        assertions IsAdult, IsNameValid
      end
    end
  end

  after { Object.send(:remove_const, :User) }

  context '#validate' do
    it 'returns truthy state' do
      form = User::Form.new(name: 'john', age: 18)
      result = form.validate

      expect(result.valid?).to eq(true)
      expect(result.messages).to eq([])
    end

    it 'returns one falsy with custom translation' do
      form = User::Form.new(name: 'jane', age: 16)
      result = form.validate

      expect(result.valid?).to eq(false)
      expect(result.messages).to eq(['User is a child (age 16)'])
    end

    it 'skips age validating' do
      form = User::Form.new(name: 'jane')
      result = form.validate

      expect(result.valid?).to eq(true)
    end
  end
end


text:
package consuladapter

import "github.com/hashicorp/consul/api"

//go:generate counterfeiter -o fakes/fake_kv.go . KV

type KV interface {
	Get(key string, q *api.QueryOptions) (*api.KVPair, *api.QueryMeta, error)
	List(prefix string, q *api.QueryOptions) (api.KVPairs, *api.QueryMeta, error)
	Put(p *api.KVPair, q *api.WriteOptions) (*api.WriteMeta, error)
	Release(p *api.KVPair, q *api.WriteOptions) (bool, *api.WriteMeta, error)
	DeleteTree(prefix string, w *api.WriteOptions) (*api.WriteMeta, error)
}

type keyValue struct {
	keyValue *api.KV
}

func NewConsulKV(kv *api.KV) KV {
	return &keyValue{keyValue: kv}
}

func (kv *keyValue) Get(key string, q *api.QueryOptions) (*api.KVPair, *api.QueryMeta, error) {
	return kv.keyValue.Get(key, q)
}

func (kv *keyValue) List(prefix string, q *api.QueryOptions) (api.KVPairs, *api.QueryMeta, error) {
	return kv.keyValue.List(prefix, q)
}

func (kv *keyValue) Put(p *api.KVPair, q *api.WriteOptions) (*api.WriteMeta, error) {
	return kv.keyValue.Put(p, q)
}

func (kv *keyValue) Release(p *api.KVPair, q *api.WriteOptions) (bool, *api.WriteMeta, error) {
	return kv.keyValue.Release(p, q)
}

func (kv *keyValue) DeleteTree(prefix string, w *api.WriteOptions) (*api.WriteMeta, error) {
	return kv.keyValue.DeleteTree(prefix, w)
}


text:
package com.exikle.java;

import java.applet.Applet;
import java.awt.Event;
import java.awt.Graphics;
import java.awt.Image;

// Inherit the applet class from the class Applet
@SuppressWarnings("serial")
public class MazeFinal extends Applet implements Runnable {

	private Image dbImage;

	private Graphics dbg;

	// Now you should implement the following methods
	// init - method is called the first time you enter the HTML site with the applet
	public void init() {}

	// start - method is called every time you enter the HTML - site with the applet
	public void start() {
		// define a new thread
		Thread th = new Thread(this);
		// start this thread
		th.start();
	}

	// stop - method is called if you leave the site with the applet
	public void stop() {}

	// destroy method is called if you leave the page finally (e. g. closing browser)
	public void destroy() {}

	public void run() {
		Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
		while (true) {
			repaint();

			try {
				Thread.sleep(10);
			} catch (InterruptedException ex) {
			}
			Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
		}
	}

	public boolean mouseDrag(Event e, int x, int y) {
		return true;
	}

	public boolean keyDown(Event e, int key) {
		if (key == Event.UP) {
		}

		return true;
	}

	public void update(Graphics g) {
		if (dbImage == null) {
			dbImage = createImage(200, 200);
			dbg = dbImage.getGraphics();
		}
		dbg.setColor(getBackground());
		dbg.fillRect(0, 0, 200, 200);

		dbg.setColor(getForeground());
		paint(dbg);

		g.drawImage(dbImage, 0, 0, this);
	}

	public void paint(Graphics g) {

	}
}


text:
// ==UserScript==
// @name           Zimbra webclient improvement: cleanup subject field
// @namespace      http://thomas-rosenau.de
// @description    Clean subject field from non-RFC German prefixes like "Aw:", "WG:" when replying
// @include        INSERT.URL.HERE
// @version        2
// ==/UserScript==

(function (main) {
    if (window == window.top && !document.querySelector('.LoginScreen')) {
        // http://stackoverflow.com/a/5006952/27862
        var script = document.createElement('script');
        script.textContent = 'try{(' + main + ')();}catch(e){console.log(e);}';
        document.body.appendChild(script).parentNode.removeChild(script);
    }
})(function () {

    // Zimbra can handle this internally, just needs a little help with the German language
    var id = setInterval(function () {
        if (window.ZmMailMsg && ZmMailMsg.SUBJ_PREFIX_RE) {
            ZmMailMsg.SUBJ_PREFIX_RE = /^\s*(Re|Fwd?|AW|WG|Antwort|Re\[\d+\]):\s*/gi;
            clearInterval(id);
        }
    }, 100);

})();


text:
package tigertonic

import (
	"fmt"
	"github.com/rcrowley/go-metrics"
	"net/http"
	"time"
)

// Counter is an http.Handler that counts requests via go-metrics.
type Counter struct {
	metrics.Counter
	handler http.Handler
}

// Counted returns an http.Handler that passes requests to an underlying
// http.Handler and then counts the request via go-metrics.
func Counted(
	handler http.Handler,
	name string,
	registry metrics.Registry,
) *Counter {
	counter := &Counter{
		Counter: metrics.NewCounter(),
		handler: handler,
	}
	if nil == registry {
		registry = metrics.DefaultRegistry
	}
	if err := registry.Register(name, counter); nil != err {
		panic(err)
	}
	return counter
}

// ServeHTTP passes the request to the underlying http.Handler and then counts
// the request via go-metrics.
func (c *Counter) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	c.handler.ServeHTTP(w, r)
	c.Inc(1)
}

// CounterByStatus is an http.Handler that counts responses by their HTTP
// status code via go-metrics.
type CounterByStatus struct {
	counters map[int]metrics.Counter
	handler  http.Handler
}

// CountedByStatus returns an http.Handler that passes requests to an
// underlying http.Handler and then counts the response by its HTTP status code
// via go-metrics.
func CountedByStatus(
	handler http.Handler,
	name string,
	registry metrics.Registry,
) *CounterByStatus {
	if nil == registry {
		registry = metrics.DefaultRegistry
	}
	counters := map[int]metrics.Counter{
		100: metrics.NewCounter(),
		101: metrics.NewCounter(),
		200: metrics.NewCounter(),
		201: metrics.NewCounter(),
		202: metrics.NewCounter(),
		203: metrics.NewCounter(),
		204: metrics.NewCounter(),
		205: metrics.NewCounter(),
		206: metrics.NewCounter(),
		300: metrics.NewCounter(),
		301: metrics.NewCounter(),
		302: metrics.NewCounter(),
		303: metrics.NewCounter(),
		304: metrics.NewCounter(),
		305: metrics.NewCounter(),
		306: metrics.NewCounter(),
		307: metrics.NewCounter(),
		400: metrics.NewCounter(),
		401: metrics.NewCounter(),
		402: metrics.NewCounter(),
		403: metrics.NewCounter(),
		404: metrics.NewCounter(),
		405: metrics.NewCounter(),
		406: metrics.NewCounter(),
		407: metrics.NewCounter(),
		408: metrics.NewCounter(),
		409: metrics.NewCounter(),
		410: metrics.NewCounter(),
		411: metrics.NewCounter(),
		412: metrics.NewCounter(),
		413: metrics.NewCounter(),
		414: metrics.NewCounter(),
		415: metrics.NewCounter(),
		416: metrics.NewCounter(),
		417: metrics.NewCounter(),
		422: metrics.NewCounter(),
		500: metrics.NewCounter(),
		501: metrics.NewCounter(),
		502: metrics.NewCounter(),
		503: metrics.NewCounter(),
		504: metrics.NewCounter(),
		505: metrics.NewCounter(),
	}
	for code, counter := range counters {
		if err := registry.Register(
			fmt.Sprintf("%s-%d", name, code),
			counter,
		); nil != err {
			panic(err)
		}
	}
	return &CounterByStatus{
		counters: counters,
		handler:  handler,
	}
}

// ServeHTTP passes the request to the underlying http.Handler and then counts
// the response by its HTTP status code via go-metrics.
func (c *CounterByStatus) ServeHTTP(w0 http.ResponseWriter, r *http.Request) {
	w := NewTeeHeaderResponseWriter(w0)
	c.handler.ServeHTTP(w, r)
	c.counters[w.StatusCode].Inc(1)
}

// CounterByStatusXX is an http.Handler that counts responses by the first
// digit of their HTTP status code via go-metrics.
type CounterByStatusXX struct {
	counter1xx, counter2xx, counter3xx, counter4xx, counter5xx metrics.Counter
	handler                                                    http.Handler
}

// CountedByStatusXX returns an http.Handler that passes requests to an
// underlying http.Handler and then counts the response by the first digit of
// its HTTP status code via go-metrics.
func CountedByStatusXX(
	handler http.Handler,
	name string,
	registry metrics.Registry,
) *CounterByStatusXX {
	if nil == registry {
		registry = metrics.DefaultRegistry
	}
	c := &CounterByStatusXX{
		counter1xx: metrics.NewCounter(),
		counter2xx: metrics.NewCounter(),
		counter3xx: metrics.NewCounter(),
		counter4xx: metrics.NewCounter(),
		counter5xx: metrics.NewCounter(),
		handler:    handler,
	}
	if err := registry.Register(
		fmt.Sprintf("%s-1xx", name),
		c.counter1xx,
	); nil != err {
		panic(err)
	}
	if err := registry.Register(
		fmt.Sprintf("%s-2xx", name),
		c.counter2xx,
	); nil != err {
		panic(err)
	}
	if err := registry.Register(
		fmt.Sprintf("%s-3xx", name),
		c.counter3xx,
	); nil != err {
		panic(err)
	}
	if err := registry.Register(
		fmt.Sprintf("%s-4xx", name),
		c.counter4xx,
	); nil != err {
		panic(err)
	}
	if err := registry.Register(
		fmt.Sprintf("%s-5xx", name),
		c.counter5xx,
	); nil != err {
		panic(err)
	}
	return c
}

// ServeHTTP passes the request to the underlying http.Handler and then counts
// the response by its HTTP status code via go-metrics.
func (c *CounterByStatusXX) ServeHTTP(w0 http.ResponseWriter, r *http.Request) {
	w := NewTeeHeaderResponseWriter(w0)
	c.handler.ServeHTTP(w, r)
	if w.StatusCode < 200 {
		c.counter1xx.Inc(1)
	} else if w.StatusCode < 300 {
		c.counter2xx.Inc(1)
	} else if w.StatusCode < 400 {
		c.counter3xx.Inc(1)
	} else if w.StatusCode < 500 {
		c.counter4xx.Inc(1)
	} else {
		c.counter5xx.Inc(1)
	}
}

// Timer is an http.Handler that counts requests via go-metrics.
type Timer struct {
	metrics.Timer
	handler http.Handler
}

// Timed returns an http.Handler that starts a timer, passes requests to an
// underlying http.Handler, stops the timer, and updates the timer via
// go-metrics.
func Timed(handler http.Handler, name string, registry metrics.Registry) *Timer {
	timer := &Timer{
		Timer:   metrics.NewTimer(),
		handler: handler,
	}
	if nil == registry {
		registry = metrics.DefaultRegistry
	}
	if err := registry.Register(name, timer); nil != err {
		panic(err)
	}
	return timer
}

// ServeHTTP starts a timer, passes the request to the underlying http.Handler,
// stops the timer, and updates the timer via go-metrics.
func (t *Timer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	defer t.UpdateSince(time.Now())
	t.handler.ServeHTTP(w, r)
}


text:
package org.locationtech.geogig.cli.plumbing;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.locationtech.geogig.cli.AbstractCommand;
import org.locationtech.geogig.cli.Console;
import org.locationtech.geogig.cli.GeogigCLI;
import org.locationtech.geogig.cli.annotation.ReadOnly;
import org.locationtech.geogig.plumbing.diff.Patch;
import org.locationtech.geogig.plumbing.diff.PatchSerializer;
import org.locationtech.geogig.plumbing.diff.VerifyPatchOp;
import org.locationtech.geogig.plumbing.diff.VerifyPatchResults;

import com.beust.jcommander.Parameter;
import com.beust.jcommander.Parameters;
import com.google.common.io.Closeables;

/**
 * Verifies that a patch can be applied
 *
 */
@ReadOnly
@Parameters(commandNames = "verify-patch", commandDescription = "Verifies that a patch can be applied")
public class VerifyPatch extends AbstractCommand {

    /**
     * The path to the patch file
     */
    @Parameter(description = "<patch>")
    private List<String> patchFiles = new ArrayList<String>();

    @Parameter(names = { "--reverse" }, description = "Check if the patch can be applied in reverse")
    private boolean reverse;

    @Override
    public void runInternal(GeogigCLI cli) throws IOException {
        checkParameter(patchFiles.size() < 2, "Only one single patch file accepted");
        checkParameter(!patchFiles.isEmpty(), "No patch file specified");

        Console console = cli.getConsole();

        File patchFile = new File(patchFiles.get(0));
        checkParameter(patchFile.exists(), "Patch file cannot be found");
        FileInputStream stream;
        try {
            stream = new FileInputStream(patchFile);
        } catch (FileNotFoundException e1) {
            throw new IllegalStateException("Can't open patch file " + patchFile);
        }
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            Closeables.closeQuietly(reader);
            Closeables.closeQuietly(stream);
            throw new IllegalStateException("Error reading patch file " + patchFile, e);
        }
        Patch patch = PatchSerializer.read(reader);
        Closeables.closeQuietly(reader);
        Closeables.closeQuietly(stream);

        VerifyPatchResults verify = cli.getGeogig().command(VerifyPatchOp.class).setPatch(patch)
                .setReverse(reverse).call();
        Patch toReject = verify.getToReject();
        Patch toApply = verify.getToApply();
        if (toReject.isEmpty()) {
            console.println("Patch can be applied.");
        } else {
            console.println("Error: Patch cannot be applied\n");
            console.println("Applicable entries:\n");
            console.println(toApply.toString());
            console.println("\nConflicting entries:\n");
            console.println(toReject.toString());
        }

    }

}


text:
var Alexa = require('alexa-sdk');
//var Data = require("./data");

const skillName = "Bedtime";

var handlers = {

    "BedtimeActivityIntent": function () {
        function getRandomInt(min, max) {
            return Math.floor(Math.random() * (max - min)) + min;
        }
        var speechOutput = "";
        if(this.event.request.intent.slots.Activity.value && this.event.request.intent.slots.Activity.value.toLowerCase() == "brush teeth") {
            speechOutput = "brush, brush, brush. <audio src='https://s3.amazonaws.com/niltoid/audio/brushteeth.mp3' />";
        } else if(this.event.request.intent.slots.Activity.value && this.event.request.intent.slots.Activity.value.toLowerCase() == "wear pajamas") {
            speechOutput = "wear pajamas time!";
        } else {
            speechOutput = "I don't have anything interesting to share regarding what you've asked."
        }
        this.emit(':tellWithCard', speechOutput, skillName, speechOutput);
    },

    "AboutIntent": function () {
        var speechOutput = "I don't know too much about the " + skillName + " skill.  ";
        this.emit(':tellWithCard', speechOutput, skillName, speechOutput);
    },

    "AMAZON.HelpIntent": function () {
        var speechOutput = "";
        speechOutput += "Here are some things you can say: ";
        speechOutput += "Tell me something interesting about Java. ";
        speechOutput += "Tell me about the skill developer. ";
        speechOutput += "You can also say stop if you're done. ";
        speechOutput += "So how can I help?";
        this.emit(':ask', speechOutput, speechOutput);
    },

    "AMAZON.StopIntent": function () {
        var speechOutput = "Goodbye";
        this.emit(':tell', speechOutput);
    },

    "AMAZON.CancelIntent": function () {
        var speechOutput = "Goodbye";
        this.emit(':tell', speechOutput);
    },

    "LaunchRequest": function () {
        var speechText = "";
        speechText += "Welcome to " + skillName + ", Nami and Miya and Mama and Baba.  ";
        speechText += "Its bedtime time, <audio src='https://s3.amazonaws.com/niltoid/audio/sound.mp3' />  Do you want to brush teeth, or wear pajamas first? ";
        var repromptText = "Do you want to brush teeth, or wear pajamas first? ";
        this.emit(':ask', speechText, repromptText);
    }

};

exports.handler = function (event, context) {
    var alexa = Alexa.handler(event, context);
    alexa.APP_ID = "bedtime";
    alexa.registerHandlers(handlers);
    alexa.execute();
};


text:
The identity map pattern is a database access design pattern used to improve performance by providing a context-specific, in-memory
cache to prevent duplicate retrieval of the same object data from the database.

```php
$blogEntry = new AnyModelObject();
$id        = 'some-unique-id-here';

$identityMap = new Pimf\Util\IdentityMap();

if (true === $identityMap->hasId($id)) {
  return $identityMap->getObject($id);
}
```

Setting objects/instances inti the identity map.

```php
$identityMap->set($id, $blogEntry);

if (true === $identityMap->hasObject($blogEntry)) {
  throw new RuntimeException('Object has an ID, cannot insert.');
}
```

Please find more here: [github.com/gjerokrsteski/php-identity-map](https://github.com/gjerokrsteski/php-identity-map)


text:
import React, { Component } from 'react';

export default class Loader extends Component {
  render () {
    return (

    );
  }
}


text:
class Capybara::Selenium::Node < Capybara::Driver::Node
  def text
    # Selenium doesn't normalize Unicode whitespace.
    Capybara::Helpers.normalize_whitespace(native.text)
  end

  def [](name)
    native.attribute(name.to_s)
  rescue Selenium::WebDriver::Error::WebDriverError
    nil
  end

  def value
    if tag_name == "select" and self[:multiple] and not self[:multiple] == "false"
      native.find_elements(:xpath, ".//option").select { |n| n.selected? }.map { |n| n[:value] || n.text }
    else
      native[:value]
    end
  end

  def set(value)
    tag_name = self.tag_name
    type = self[:type]
    if (Array === value) && !self[:multiple]
      raise ArgumentError.new "Value cannot be an Array when 'multiple' attribute is not present. Not a #{value.class}"
    end
    if tag_name == 'input' and type == 'radio'
      click
    elsif tag_name == 'input' and type == 'checkbox'
      click if value ^ native.attribute('checked').to_s.eql?("true")
    elsif tag_name == 'input' and type == 'file'
      path_names = value.to_s.empty? ? [] : value
      native.send_keys(*path_names)
    elsif tag_name == 'textarea' or tag_name == 'input'
      native.send_keys(("\b" * native[:value].size) + value.to_s)
    end
  end

  def select_option
    native.click unless selected?
  end

  def unselect_option
    if select_node['multiple'] != 'multiple' and select_node['multiple'] != 'true'
      raise Capybara::UnselectNotAllowed, "Cannot unselect option from single select box."
    end
    native.click if selected?
  end

  def click
    native.click
  end

  def drag_to(element)
    driver.browser.action.drag_and_drop(native, element.native).perform
  end

  def tag_name
    native.tag_name.downcase
  end

  def visible?
    displayed = native.displayed?
    displayed and displayed != "false"
  end

  def selected?
    selected = native.selected?
    selected and selected != "false"
  end

  alias :checked? :selected?

  def find(locator)
    native.find_elements(:xpath, locator).map { |n| self.class.new(driver, n) }
  end

private

  # a reference to the select node if this is an option node
  def select_node
    find('./ancestor::select').first
  end
end


text:
Statistics.Model.Search.ViewTypeEnum = {

	BarChart: 0,

	PieChart: 1,

	ThematicMap: 2,

	PivotTable: 3,

	/**
	 * @public
	 * @function
	 * @param {Integer} analysis
	 */
	getAnalysisKey: function(analysis) {

		for(var p in this) {
			if(this[p] == analysis) return p;
		}

		return null;

	}

};


text:
class EmailAddress < ActiveRecord::Base
  has_many :received_messages, :class_name => 'EmailHistory', :foreign_key => 'to_email_id'
  has_many :sent_messages, :class_name => 'EmailHistory', :foreign_key => 'from_email_id'
  has_many :blocked_lists
  belongs_to :last_penalty, :class_name => 'EmailArchive', :foreign_key => 'penalized_message_id', :primary_key => 'message_id'
  before_create :set_allow_since, :set_unique
  def set_allow_since(t = Time.now)
    self.allow_from_since = t
    self.allow_to_since = t
  end
  def set_unique
    self.unique = Digest::SHA1.hexdigest(self.email)
  end
  def self.base_email(email)
    email.to_s.gsub(/\+[^@]+@/, '@').downcase
  end
end


text:
/**
  * Generate a world with a simple cellular automata.
  * This cellular automata is actually broken, since it
  * doesn't check the previous state of the current neighbor
  * cell but its current state.
  * Somehow, it still generates some cool structures so...
  */
"use strict";
var common = require('./common');
var tools = require('./tools');
var Tile = require('./tile');

function WorldGenerator(width, height) {
    this.width = width;
    this.height = height;
    do {
        console.log("Generating a world...");
        this.firstStage();

        for (var i = 0; i < common.GENERATIONS; i++) {
            this.step();
        }
    } while (! this.check());
}

WorldGenerator.prototype.generateRandomTile = function() {

    var tileNumber;

    if (tools.randInt(0, 100) < common.FILL_PROBABILITY) {
        tileNumber = common.TILES.WALL;
    }
    else {
        tileNumber = common.TILES.EMPTY;
    }

    return new Tile(tileNumber);
};

WorldGenerator.prototype.firstStage = function() {
    var tiles = [];
    for (var i = 0; i < this.height; i++) {
        tiles[i] = [];
        for (var j = 0; j < this.width; j++) {
            tiles[i][j] = this.generateRandomTile();
        }
    }

    for (var i = 0; i < this.height; i++) {
        tiles[i][0] = new Tile(common.TILES.WALL);
        tiles[i][this.width - 1] = new Tile(common.TILES.WALL);
    }

    for (var j = 0; j < this.width; j++) {
        tiles[0][j] = new Tile(common.TILES.WALL);
        tiles[this.height - 1][j] = new Tile(common.TILES.WALL);
    }

    this.tiles = tiles;
};

WorldGenerator.prototype.isWall = function(x, y) {
    return this.tiles[y][x].type == common.TILES.WALL;
}

WorldGenerator.prototype.getAdjacentWalls = function(x, y) {
    var startX = x - 1;
    var startY = y - 1;
    var endX = x + 1;
    var endY = y + 1;

    var walls = 0;

    for (var i = startY ; i <= endY; i++) {
        for (var j = startX; j <= endX; j++) {
            if (!(i == y && j == x)) {
                if (this.isWall(j,i)) {
                    walls++;
                }
            }
        }
    }

    return walls;
};

WorldGenerator.prototype.changeTileStateIfNeeded = function(x, y) {
    var adjacentWalls = this.getAdjacentWalls(x, y);
    if (this.tiles[y][x].type == common.TILES.WALL) {
        if (adjacentWalls < 2) {
            this.tileChanged++;
            this.tiles[y][x] = new Tile(common.TILES.EMPTY);
        }
    }
    else {
        if (adjacentWalls >= 5) {
            this.tileChanged++;
            this.tiles[y][x] = new Tile(common.TILES.WALL);
        }
    }
};

WorldGenerator.prototype.step = function() {
    this.tileChanged = 0;
    for (var i = 1; i < this.height - 1; i++) {
        for (var j = 1; j < this.width - 1; j++) {
            this.changeTileStateIfNeeded(j, i);
        }
    }
    console.log(this.tileChanged + " tiles changed during this generation");
};

WorldGenerator.prototype.check = function() {
    this.generateFloodTiles();
    this.generateFirstFloodTile();
    this.propagate();
    return this.isValidMap();
};

WorldGenerator.prototype.generateFloodTiles = function() {
    var tiles = [];
    for (var i = 0; i < this.height; i++) {
        tiles[i] = [];
        for (var j = 0; j < this.width; j++) {
            if (this.tiles[i][j].type == common.TILES.WALL) {
                tiles[i][j] = -1;
            }
            else {
                tiles[i][j] = 0;
            }
        }
    }
    this.floodTiles = tiles;

};

WorldGenerator.prototype.generateFirstFloodTile = function() {
    var x, y;
    do {
        x = tools.randInt(0, this.width);
        y = tools.randInt(0, this.height);
    } while (this.floodTiles[y][x] == -1);
    this.floodTiles[y][x] = 1;
};

WorldGenerator.prototype.propagate = function() {
    var tilesChanged;
    do {
        tilesChanged = 0;

        for (var i = 1; i < this.height - 1; i++) {
            for (var j = 1; j < this.width - 1; j++) {
                if (this.floodTiles[i][j] == 0) {
                    if (this.hasFloodNeighbor(j, i)) {
                        this.floodTiles[i][j] = 1;
                        tilesChanged++;
                    }
                }
            }
        }
    } while (tilesChanged != 0);
};
WorldGenerator.prototype.hasFloodNeighbor = function(x, y) {
    if (this.floodTiles[y][x - 1] == 1) {
        return true;
    }
    else if (this.floodTiles[y][x + 1] == 1) {
        return true;
    }
    else if (this.floodTiles[y - 1][x] == 1) {
        return true;
    }
    else if (this.floodTiles[y + 1][x] == 1) {
        return true;
    }
    return false;
};
WorldGenerator.prototype.isValidMap = function() {
    for (var i = 0; i < this.height; i++) {
        for (var j = 0; j < this.width; j++) {
            if (this.floodTiles[i][j] == 0) {
                return false;
            }
        }
    }
    return true;
};

exports.generate = function(width, height) {
    var generator = new WorldGenerator(width, height);
    return generator.tiles;
};


text:
package com.facebook.buck.distributed;

import com.facebook.buck.core.exceptions.HumanReadableException;
import com.facebook.buck.core.util.log.Logger;
import com.facebook.buck.distributed.thrift.BuildJobStateFileHashEntry;
import com.facebook.buck.distributed.thrift.BuildJobStateFileHashes;
import com.facebook.buck.distributed.thrift.PathWithUnixSeparators;
import com.facebook.buck.io.ArchiveMemberPath;
import com.facebook.buck.io.filesystem.ProjectFilesystem;
import com.facebook.buck.util.cache.FileHashCacheVerificationResult;
import com.facebook.buck.util.cache.ProjectFileHashCache;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import com.google.common.hash.HashCode;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.Stack;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * Note that this class may or may not return the real HashCode of a file/dir. The primary purpose
 * of this class is to trigger async materialization of files in a distributed build.
 */
class MaterializerDummyFileHashCache implements ProjectFileHashCache {

  private static final Logger LOG = Logger.get(MaterializerDummyFileHashCache.class);
  private static final long DEFAULT_PRELOAD_FILE_MATERIALIZATION_TIMEOUT_SECONDS = 300;

  private final ImmutableMap<Path, BuildJobStateFileHashEntry> remoteFileHashesByAbsPath;
  private final Set<Path> materializedPaths;
  private final FileContentsProvider provider;
  private final ProjectFilesystem projectFilesystem;
  private final ProjectFileHashCache delegate;
  private final Map<BuildJobStateFileHashEntry, ListenableFuture<?>>
      fileMaterializationFuturesByFileHashEntry;
  private final ListeningExecutorService executorService;

  public MaterializerDummyFileHashCache(
      ProjectFileHashCache delegate,
      BuildJobStateFileHashes remoteFileHashes,
      FileContentsProvider provider,
      ListeningExecutorService executorService) {
    this.delegate = delegate;
    this.remoteFileHashesByAbsPath =
        DistBuildFileHashes.indexEntriesByPath(delegate.getFilesystem(), remoteFileHashes);
    this.materializedPaths = Collections.newSetFromMap(new ConcurrentHashMap<Path, Boolean>());
    this.provider = provider;
    this.projectFilesystem = delegate.getFilesystem();
    this.fileMaterializationFuturesByFileHashEntry = new ConcurrentHashMap<>();
    this.executorService = executorService;
  }

  /**
   * This method creates all symlinks and touches all regular files so that any file existence
   * checks during action graph transformation go through (for instance,
   * PrebuiltCxxLibraryDescription::requireSharedLibrary). Note: THIS IS A HACK. And this needs to
   * be here until the misbehaving rules are fixed. TODO(alisdair): remove this once action graph
   * doesn't read from file system.
   */
  public void preloadAllFiles(boolean materializeAllFiles) throws IOException {
    for (Path absPath : remoteFileHashesByAbsPath.keySet()) {
      LOG.info("Preloading: [%s]", absPath.toString());
      BuildJobStateFileHashEntry fileHashEntry = remoteFileHashesByAbsPath.get(absPath);
      if (fileHashEntry == null || fileHashEntry.isPathIsAbsolute()) {
        continue;
      }

      if (fileHashEntry.isSetRootSymLink()) {
        Path rootSymlinkAbsPath =
            projectFilesystem.resolve(fileHashEntry.getRootSymLink().getPath());
        Optional<Path> rootSymlinkRelPath =
            projectFilesystem.getPathRelativeToProjectRoot(rootSymlinkAbsPath);
        if (!rootSymlinkRelPath.isPresent()) {
          // RecordingProjectFileHashCache stored an absolute path (which was also a sym link).
          throw new RuntimeException("Root symlink is not in project root: " + absPath);
        }

        materializeSymlink(
            projectFilesystem.getPathRelativeToProjectRoot(absPath).get(), fileHashEntry);
        continue;
      }

      if (fileHashEntry.isDirectory) {
        // Create directory
        // No need to materialize sub-dirs/files here, as there will be separate entries for those.
        projectFilesystem.mkdirs(absPath);
        continue;
      }

      if (materializeAllFiles
          || fileHashEntry.isSetMaterializeDuringPreloading()
              && fileHashEntry.isMaterializeDuringPreloading()) {
        Path relPath = projectFilesystem.getPathRelativeToProjectRoot(absPath).get();
        materializeFileAsync(relPath, fileHashEntry);
        continue;
      }

      // Touch file
      projectFilesystem.createParentDirs(absPath);
      projectFilesystem.touch(absPath);
    }

    try {
      getMaterializationFuturesAsList()
          .get(DEFAULT_PRELOAD_FILE_MATERIALIZATION_TIMEOUT_SECONDS, TimeUnit.SECONDS);
    } catch (ExecutionException e) {
      String msg =
          String.format(
              "Preload file materialization failed with exception: [%s].", e.getMessage());
      LOG.error(e, msg);
      throw new RuntimeException(msg);
    } catch (InterruptedException e) {
      Thread.currentThread().interrupt();
      String msg = "Preload file materialization was interrupted.";
      LOG.error(e, msg);
      throw new RuntimeException(msg);
    } catch (TimeoutException e) {
      printMissingFiles();
      String msg =
          String.format(
              "Preload materialization timed out after [%d] seconds.",
              DEFAULT_PRELOAD_FILE_MATERIALIZATION_TIMEOUT_SECONDS);
      LOG.error(e, msg);
      throw new RuntimeException(msg);
    }
  }

  private void printMissingFiles() {
    for (BuildJobStateFileHashEntry fileEntry :
        fileMaterializationFuturesByFileHashEntry.keySet()) {
      ListenableFuture<?> materializationFuture =
          Objects.requireNonNull(fileMaterializationFuturesByFileHashEntry.get(fileEntry));
      if (!materializationFuture.isDone()) {
        LOG.warn(
            String.format(
                "Materialization missing for: [%s] [sha1: %s]",
                fileEntry.getPath().getPath(), fileEntry.getSha1()));
      }
    }
  }

  private void materializeIfNeededAsync(Path relPath) throws IOException {
    Stack<Path> remainingPaths = new Stack<>();
    remainingPaths.add(relPath);

    while (!remainingPaths.isEmpty()) {
      relPath = remainingPaths.pop();
      if (materializedPaths.contains(relPath)) {
        LOG.verbose("Path already materialized: [%s].", relPath.toString());
        continue;
      }

      Path absPath = projectFilesystem.resolve(relPath).toAbsolutePath();
      BuildJobStateFileHashEntry fileHashEntry = remoteFileHashesByAbsPath.get(absPath);

      if (fileHashEntry == null || fileHashEntry.isPathIsAbsolute()) {
        LOG.info(
            "Insufficient information or no need for materializing path: [%s].",
            relPath.toString());
        recordMaterializedPath(relPath);
        continue;
      }

      if (fileHashEntry.isSetRootSymLink()) {
        materializeSymlink(relPath, fileHashEntry);
        continue;
      }

      if (fileHashEntry.isIsDirectory()) {
        materializeDirectory(relPath, fileHashEntry, remainingPaths);
        continue;
      }

      materializeFileAsync(relPath, fileHashEntry);
    }
  }

  private void postFileMaterializationHelper(
      boolean success, Path relPath, BuildJobStateFileHashEntry fileHashEntry) throws IOException {
    Path absPath = projectFilesystem.resolve(relPath);
    Preconditions.checkState(
        success,
        "Failed to materialize source file [%s] for FileHashEntry=[%s].",
        absPath,
        fileHashEntry);

    absPath.toFile().setExecutable(fileHashEntry.isExecutable);
    recordMaterializedPath(relPath);
  }

  private ListenableFuture<?> materializeFileAsync(
      Path relPath, BuildJobStateFileHashEntry fileHashEntry) throws IOException {
    // We need to maintain synchronization a per-file basis. Trying to materialize a file again
    // makes the file unavailable for a small window when we're writing it again.
    synchronized (fileHashEntry) {
      // Check if we've previously tried to materialize this file.
      if (fileMaterializationFuturesByFileHashEntry.containsKey(fileHashEntry)) {
        LOG.verbose("File already materialized: [%s].", relPath.toString());
        return fileMaterializationFuturesByFileHashEntry.get(fileHashEntry);
      }

      LOG.info("Materializing file: [%s]", relPath.toString());
      Path absPath = projectFilesystem.resolve(relPath);
      projectFilesystem.createParentDirs(absPath);
      projectFilesystem.touch(absPath);

      ListenableFuture<?> materializationFuture =
          Futures.transform(
              provider.materializeFileContentsAsync(fileHashEntry, absPath),
              (success) -> {
                try {
                  postFileMaterializationHelper(success, relPath, fileHashEntry);
                  return success;
                } catch (IOException e) {
                  throw new RuntimeException(
                      String.format(
                          "Failed to materialize source file [%s] for FileHashEntry=[%s].",
                          absPath, fileHashEntry),
                      e);
                }
              },
              executorService);

      ListenableFuture<?> prevValue =
          fileMaterializationFuturesByFileHashEntry.put(fileHashEntry, materializationFuture);

      Preconditions.checkState(prevValue == null, "must not override prev value");

      return materializationFuture;
    }
  }

  private void materializeDirectory(
      Path relPath, BuildJobStateFileHashEntry fileHashEntry, Stack<Path> remainingPaths)
      throws IOException {
    synchronized (fileHashEntry) {
      // Check if someone materialized the dir while we were waiting for synchronization.
      if (materializedPaths.contains(relPath)) {
        LOG.verbose(
            "Directory already materialized (may still be waiting for some files asynchronously): [%s].",
            relPath.toString());
        return;
      }

      projectFilesystem.mkdirs(relPath);
      remainingPaths.push(relPath);

      for (PathWithUnixSeparators unixPath : fileHashEntry.getChildren()) {
        Path absPathToChild = projectFilesystem.resolve(Paths.get(unixPath.getPath()));
        Path relPathToChild = projectFilesystem.getPathRelativeToProjectRoot(absPathToChild).get();
        if (!materializedPaths.contains(relPathToChild)) {
          remainingPaths.push(relPathToChild);
        }
      }

      if (remainingPaths.peek().equals(relPath)) {
        // This means all children were already materialized.
        LOG.info(
            "Materialized directory (may still be waiting for some files asynchronously): [%s].",
            relPath.toString());
        remainingPaths.pop();
        recordMaterializedPath(relPath);
      }
    }
  }

  private synchronized void materializeSymlink(
      Path relPath, BuildJobStateFileHashEntry fileHashEntry) throws IOException {
    synchronized (fileHashEntry) {
      Path targetAbsPath =
          projectFilesystem.resolve(fileHashEntry.getRootSymLinkTarget().getPath());

      // Check if someone materialized the symlink while we were waiting for synchronization.
      if (materializedPaths.contains(relPath)) {
        LOG.verbose(
            "Symlink already materialized: [%s] -> [%s].",
            relPath.toString(), targetAbsPath.toString());
        return;
      }

      Path rootSymlinkAbsPath = projectFilesystem.resolve(fileHashEntry.getRootSymLink().getPath());
      Path rootSymlinkRelPath =
          projectFilesystem.getPathRelativeToProjectRoot(rootSymlinkAbsPath).get();

      if (materializedPaths.contains(rootSymlinkRelPath)) {
        LOG.verbose(
            "Symlink already materialized: [%s] -> [%s].",
            relPath.toString(), targetAbsPath.toString());
        recordMaterializedPath(relPath);
        return;
      }

      LOG.info(
          "Materializing symlink [%s] -> [%s].",
          rootSymlinkAbsPath.toString(), targetAbsPath.toString());

      try {
        projectFilesystem.createParentDirs(rootSymlinkAbsPath);
        projectFilesystem.createSymLink(rootSymlinkAbsPath, targetAbsPath, true);
      } catch (IOException e) {
        LOG.error(e);
        throw new RuntimeException(e);
      }
      recordMaterializedPath(relPath);
      recordMaterializedPath(rootSymlinkRelPath);
    }
  }

  /**
   * Verification of FileHashes is important because we anyways use the remote file hashes to
   * compute the RuleKeys (see {@link DistBuildCachingEngineDelegate}). We don't want to upload
   * corrupt cache artifacts in case we end up materializing corrupt source files.
   */
  private void integrityCheck(Path relPath) throws IOException {
    Path absPath = projectFilesystem.resolve(relPath).toAbsolutePath();
    BuildJobStateFileHashEntry fileHashEntry = remoteFileHashesByAbsPath.get(absPath);
    if (fileHashEntry == null || !fileHashEntry.isSetSha1()) {
      return;
    }

    HashCode computedHash =
        Preconditions.checkNotNull(
            delegate.get(relPath),
            "File materialization failed. Delegate FileHashCache returned null HashCode for [%s].",
            relPath);
    if (!computedHash.toString().equals(fileHashEntry.getSha1())) {
      throw new HumanReadableException(
          "SHA1 of materialized file (at [%s]) does not match the SHA1 sent by buck client.\n"
              + "Computed SHA1: %s\n"
              + "Expected SHA1: %s",
          relPath, computedHash.toString(), fileHashEntry.getSha1());
    }
  }

  private void recordMaterializedPath(Path relPath) throws IOException {
    integrityCheck(relPath);
    materializedPaths.add(relPath);
  }

  public ListenableFuture<?> getMaterializationFuturesAsList() {
    return Futures.allAsList(fileMaterializationFuturesByFileHashEntry.values());
  }

  @Override
  public HashCode get(Path relPath) throws IOException {
    materializeIfNeededAsync(relPath);
    if (getMaterializationFuturesAsList().isDone()) {
      return delegate.get(relPath);
    } else {
      // Return a fake. This class is not meant for actually computing HashCodes.
      return HashCode.fromInt(0);
    }
  }

  @Override
  public long getSize(Path relPath) throws IOException {
    return delegate.getSize(relPath);
  }

  @Override
  public Optional<HashCode> getIfPresent(Path path) {
    throw new UnsupportedOperationException();
  }

  @Override
  public HashCode get(ArchiveMemberPath archiveMemberRelPath) throws IOException {
    materializeIfNeededAsync(archiveMemberRelPath.getArchivePath());
    if (getMaterializationFuturesAsList().isDone()) {
      return delegate.get(archiveMemberRelPath);
    } else {
      // Return a fake. This class is not meant for actually computing HashCodes.
      return HashCode.fromInt(0);
    }
  }

  @Override
  public ProjectFilesystem getFilesystem() {
    return projectFilesystem;
  }

  @Override
  public boolean willGet(Path relPath) {
    // DistBuildCellIndex makes sure only relative paths to the materializer's filesystem are
    // passed here so we can safely accept all paths here.
    return true;
  }

  @Override
  public boolean willGet(ArchiveMemberPath archiveMemberRelPath) {
    // DistBuildCellIndex makes sure only relative paths to the materializer's filesystem are
    // passed here so we can safely accept all paths here.
    return true;
  }

  @Override
  public void invalidate(Path relPath) {
    delegate.invalidate(relPath);
  }

  @Override
  public void invalidateAll() {
    delegate.invalidateAll();
  }

  @Override
  public void set(Path relPath, HashCode hashCode) throws IOException {
    delegate.set(relPath, hashCode);
  }

  @Override
  public FileHashCacheVerificationResult verify() throws IOException {
    return delegate.verify();
  }

  @Override
  public boolean isIgnored(Path path) {
    return delegate.isIgnored(path);
  }
}


text:
#if !defined(lint) && !defined(DOS)
static char rcsid[] = "$Id: creatdir.c 769 2007-10-24 00:15:40Z hubert@u.washington.edu $";
#endif

#include <system.h>
#include "../charconv/utf8.h"
#include "../charconv/filesys.h"
#include "creatdir.h"

#ifdef	S_IRWXU
#define	MAILDIR_MODE	S_IRWXU
#else
#define	MAILDIR_MODE	0700
#endif

/*----------------------------------------------------------------------
      Create the mail subdirectory.

  Args: dir -- Name of the directory to create

 Result: Directory is created.  Returns 0 on success, else -1 on error
	 and errno is valid.
  ----*/
int
create_mail_dir(char *dir)
{
    if(our_mkdir(dir, MAILDIR_MODE) < 0)
      return(-1);

#ifndef _WINDOWS
    our_chmod(dir, MAILDIR_MODE);

    /* Some systems need this, on others we don't care if it fails */
    our_chown(dir, getuid(), getgid());
#endif /* !_WINDOWS */

    return(0);
}


text:
<?xml version="1.0"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>org.rundeck</groupId>
  <artifactId>rundeck-project</artifactId>
  <packaging>pom</packaging>
  <version>2.6.1-SNAPSHOT</version>
  <name>RunDeck parent project</name>
  <url>http://rundeck.org</url>
  <modules>
    <module>rundeck-storage</module>
    <module>core</module>
    <module>plugins</module>
    <module>rundeckapp</module>
    <module>rundeck-launcher</module>
  </modules>
  <build>
    <pluginManagement>
      <plugins>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>2.3.2</version>
          <configuration>
            <source>1.7</source>
            <target>1.7</target>
          </configuration>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
</project>