text:
from __future__ import unicode_literals
from copy import deepcopy
from datetime import datetime, date
import logging

from lxml import etree
from lxml.builder import ElementMaker
import six

from eulxml.utils.compat import u
from eulxml.xpath import ast, parse, serialize

__all__ = [
    'StringField', 'StringListField',
    'IntegerField', 'IntegerListField',
    'NodeField', 'NodeListField',
    'ItemField', 'SimpleBooleanField',
    'DateTimeField', 'DateTimeListField',
    'DateField', 'DateListField',
    'SchemaField','FloatField','FloatListField',
]

logger = logging.getLogger(__name__)

class Field(object):
    """Base class for all xmlmap fields.

    Takes an optional ``required`` value to indicate that the field is required
    or not required in the XML.  By default, required is ``None``, which indicates
    that it is unknown whether the field is required or not.  The required value
    for an xmlmap field should not conflict with the schema or DTD for that xml,
    if there is one.
    """

    # track each time a Field instance is created, to retain order
    creation_counter = 0

    def __init__(self, xpath, manager, mapper, required=None, verbose_name=None,
                    help_text=None):
        # compile xpath in order to catch an invalid xpath at load time
        etree.XPath(xpath)
        # NOTE: not saving compiled xpath because namespaces must be
        # passed in at compile time when evaluating an etree.XPath on a node
        self.xpath = xpath
        self.manager = manager
        self.mapper = mapper
        self.required = required
        self.verbose_name = verbose_name
        self.help_text = help_text

        # pre-parse the xpath for setters, etc
        self.parsed_xpath = parse(xpath)

        # adjust creation counter, save local copy of current count
        self.creation_counter = Field.creation_counter
        Field.creation_counter += 1

    def get_for_node(self, node, context):
        return self.manager.get(self.xpath, node, context, self.mapper, self.parsed_xpath)

    def set_for_node(self, node, context, value):
        return self.manager.set(self.xpath, self.parsed_xpath, node, context, self.mapper, value)

    def delete_for_node(self, node, context):
        return self.manager.delete(self.xpath, self.parsed_xpath, node, context, self.mapper)

    def __repr__(self):
        """
        Displays the module, class and name of the field.
        """
        return '<%s.%s>' % (self.__class__.__module__, self.__class__.__name__)

# data mappers to translate between identified xml nodes and Python values

class Mapper(object):
    # generic mapper to_xml function
    def to_xml(self, value):
        if value is None:
            return value
        else:
            return u(value)

class StringMapper(Mapper):
    XPATH = etree.XPath('string()')
    def __init__(self, normalize=False):
        if normalize:
            self.XPATH = etree.XPath('normalize-space(string())')

    def to_python(self, node):
        if node is None:
            return None
        if isinstance(node, six.string_types):
            return node
        return self.XPATH(node)

class IntegerMapper(Mapper):
    XPATH = etree.XPath('number()')
    def to_python(self, node):
        if node is None:
            return None
        try:
            # xpath functions such as count return a float and must be converted to int
            if isinstance(node, six.string_types) or isinstance(node, float):
                return int(node)

            return int(self.XPATH(node))
        except ValueError:
            # anything that can't be converted to an Integer
            return None

class FloatMapper(Mapper):
    XPATH = etree.XPath('number()')
    def to_python(self, node):
        if node is None:
            return None
        try:
            if isinstance(node, six.string_types):
                return float(node)

            return float(self.XPATH(node))
        except ValueError:
            # anything that can't be converted to an Float
            return None

class SimpleBooleanMapper(Mapper):
    XPATH = etree.XPath('string()')
    def __init__(self, true, false):
        self.true = true
        self.false = false

    def to_python(self, node):
        # handle node not present in xml first
        if node is None:
            # if false is configured as None, then missing node is False
            if self.false is None:
                return False
            # otherwise, return None to signify boolean is unset
            else:
                return None

        if isinstance(node, six.string_types):
            value = node
        else:
            value = self.XPATH(node)
        if value == str(self.true):
            return True
        if self.false is not None and \
                value == str(self.false):
            return False
        # what happens if it is neither of these?
        raise Exception("Boolean field value '%s' is neither '%s' nor '%s'" % (value, self.true, self.false))

    def to_xml(self, value):
        if value:
            return str(self.true)
        elif self.false is not None:
            return str(self.false)
        else:
            return None

class DateTimeMapper(object):
    XPATH = etree.XPath('string()')

    def __init__(self, format=None, normalize=False):
        self.format = format
        if normalize:
            self.XPATH = etree.XPath('normalize-space(string())')

    def to_python(self, node):
        if node is None:
            return None
        if isinstance(node, six.string_types):
            rep = node
        else:
            rep = self.XPATH(node)
        if rep.endswith('Z'): # strip Z
            rep = rep[:-1]
        if rep[-6] in '+-': # strip tz
            rep = rep[:-6]

        if self.format is not None:
            dt = datetime.strptime(rep, self.format)
        else:
            try:
                dt = datetime.strptime(rep, '%Y-%m-%dT%H:%M:%S')
            except ValueError:
                # if initial format fails, attempt to parse with microseconds
                dt = datetime.strptime(rep, '%Y-%m-%dT%H:%M:%S.%f')
        return dt

    def to_xml(self, dt):
        val = None
        if self.format is not None:
            val = u(dt.strftime(self.format))
        else:
            val = u(dt.isoformat())
        return val

class DateMapper(DateTimeMapper):

    def __init__(self, format=None, normalize=False):
        if format is None:
            format = '%Y-%m-%d'
        super(DateMapper, self).__init__(format=format, normalize=normalize)

    def to_python(self, node):
        if node is None:
            return None
        if isinstance(node, six.string_types):
            rep = node
        elif hasattr(node, 'text'):
            rep = node.text

        dt = datetime.strptime(rep, self.format)
        return date(dt.year, dt.month, dt.day)

class NullMapper(object):
    def to_python(self, node):
        return node

class NodeMapper(object):
    def __init__(self, node_class):
        self.node_class = node_class

    def to_python(self, node):
        if node is None:
            return None
        return self.node_class(node)

    def to_xml(self, xmlobject):
        if xmlobject:
            return xmlobject.node

# internal xml utility functions for use by managers

def _find_terminal_step(xast):
    if isinstance(xast, ast.Step):
        return xast
    elif isinstance(xast, ast.BinaryExpression):
        if xast.op in ('/', '//'):
            return _find_terminal_step(xast.right)
    return None

def _find_xml_node(xpath, node, context):
    #In some cases the this will return a value not a node
    matches = node.xpath(xpath, **context)
    if matches and isinstance(matches, list):
        return matches[0]
    elif matches:
        return matches

def _create_xml_node(xast, node, context, insert_index=None):
    if isinstance(xast, ast.Step):
        if isinstance(xast.node_test, ast.NameTest):
            # check the predicates (if any) to verify they're constructable
            for pred in xast.predicates:
                if not _predicate_is_constructible(pred):
                    msg = ("Missing element for '%s', and node creation is " +
                           "supported only for simple child and attribute " +
                           "nodes with simple predicates.") % (serialize(xast),)
                    raise Exception(msg)

            # create the node itself
            if xast.axis in (None, 'child'):
                new_node = _create_child_node(node, context, xast, insert_index)
            elif xast.axis in ('@', 'attribute'):
                new_node = _create_attribute_node(node, context, xast)

            # and create any nodes necessary for the predicates
            for pred in xast.predicates:
                _construct_predicate(pred, new_node, context)

            return new_node

        # if this is a text() node, we don't need to create anything further
        # return the node that will be parent to text()
        elif _is_text_nodetest(xast):
            return node

    elif isinstance(xast, ast.BinaryExpression):
        if xast.op == '/':
            left_xpath = serialize(xast.left)
            left_node = _find_xml_node(left_xpath, node, context)
            if left_node is None:
                left_node = _create_xml_node(xast.left, node, context)
            return _create_xml_node(xast.right, left_node, context)

    # anything else, throw an exception:
    msg = ("Missing element for '%s', and node creation is supported " + \
           "only for simple child and attribute nodes.") % (serialize(xast),)
    raise Exception(msg)

def _create_child_node(node, context, step, insert_index=None):
    opts = {}
    ns_uri = None
    if 'namespaces' in context:
        opts['nsmap'] = context['namespaces']
        if step.node_test.prefix:
            ns_uri = context['namespaces'][step.node_test.prefix]
    E = ElementMaker(namespace=ns_uri, **opts)
    new_node = E(step.node_test.name)
    if insert_index is not None:
        node.insert(insert_index, new_node)
    else:
        node.append(new_node)
    return new_node

def _create_attribute_node(node, context, step):
    node_name, node_xpath, nsmap = _get_attribute_name(step, context)
    # create an empty attribute node
    node.set(node_name, '')
    # find via xpath so a 'smart' string can be returned and set normally
    result = node.xpath(node_xpath, namespaces=nsmap)
    return result[0]

def _predicate_is_constructible(pred):
    if isinstance(pred, ast.Step):
        # only child and attribute for now
        if pred.axis not in (None, 'child', '@', 'attribute'):
            return False
        # no node tests for now: only name tests
        if not isinstance(pred.node_test, ast.NameTest):
            return False
        # only constructible if its own predicates are
        if any((not _predicate_is_constructible(sub_pred)
                for sub_pred in pred.predicates)):
            return False
    elif isinstance(pred, ast.BinaryExpression):
        if pred.op == '/':
            # path expressions are constructible if each side is
            if not _predicate_is_constructible(pred.left):
                return False
            if not _predicate_is_constructible(pred.right):
                return False
        elif pred.op == '=':
            # = expressions are constructible for now only if the left side
            # is constructible and the right side is a literal or variable
            if not _predicate_is_constructible(pred.left):
                return False
            if not isinstance(pred.right,
                    (six.integer_types, six.string_types, ast.VariableReference)):
                return False

    # otherwise, i guess we're ok
    return True

def _construct_predicate(xast, node, context):
    if isinstance(xast, ast.Step):
        return _create_xml_node(xast, node, context)
    elif isinstance(xast, ast.BinaryExpression):
        if xast.op == '/':
            left_leaf = _construct_predicate(xast.left, node, context)
            right_node = _construct_predicate(xast.right, left_leaf, context)
            return right_node
        elif xast.op == '=':
            left_leaf = _construct_predicate(xast.left, node, context)
            step = _find_terminal_step(xast.left)
            if isinstance(xast.right, ast.VariableReference):
                name = xast.right.name
                ctxval = context.get(name, None)
                if ctxval is None:
                    ctxval = context[name[1]]
                xvalue = str(ctxval)
            else:
                xvalue = str(xast.right)
            _set_in_xml(left_leaf, xvalue, context, step)
            return left_leaf

def _set_in_xml(node, val, context, step):

    # node could be either an element or an attribute
    if isinstance(node, etree._Element): # if it's an element
        if isinstance(val, etree._Element):
            # remove node children and graft val children in.
            node.clear()
            node.text = val.text
            for child in val:
                node.append(child)
            for name, val in val.attrib.iteritems():
                node.set(name, val)
        else: # set node contents to string val
            if not list(node):      # no child elements
                node.text = val
            else:
                raise Exception("Cannot set string value - not a text node!")

    # by default, etree returns a "smart" string for attributes and text.
    # if it's not an element (above) then it is either a text node
    # or an attribute
    elif hasattr(node, 'getparent'):
        # if node test is text(), set the text of the parent node
        if _is_text_nodetest(step):
            node.getparent().text = val

        # otherwise, treat it as an attribute
        else:
            attribute, node_xpath, nsmap = _get_attribute_name(step, context)
            node.getparent().set(attribute, val)

def _remove_xml(xast, node, context, if_empty=False):
    '''Remove a node or attribute.  For multipart XPaths that are
    constructible by :mod:`eulxml.xmlmap`, the corresponding nodes
    will be removed if they are empty (other than predicates specified
    in the XPath).

    :param xast: parsed xpath (xpath abstract syntax tree) from
	:mod:`eulxml.xpath`
    :param node: lxml node relative to which xast should be removed
    :param context: any context required for the xpath (e.g.,
    	namespace definitions)
    :param if_empty: optional boolean; only remove a node if it is
	empty (no attributes and no child nodes); defaults to False

    :returns: True if something was deleted
    '''
    if isinstance(xast, ast.Step):
        if isinstance(xast.node_test, ast.NameTest):
            if xast.axis in (None, 'child'):
                return _remove_child_node(node, context, xast, if_empty=if_empty)
            elif xast.axis in ('@', 'attribute'):
                return _remove_attribute_node(node, context, xast)
        # special case for text()
        # since it can't be removed, at least clear out any value in the text node
        elif _is_text_nodetest(xast):
            node.text = ''
            return True

    # If the xpath is a multi-step path (e.g., foo[@id="a"]/bar[@id="b"]/baz),
    # remove the leaf node.  If the remaining portions of that path
    # could have been constructed when setting the node and are empty
    # (other than any predicates defined in the xpath), remove them as well.
    elif isinstance(xast, ast.BinaryExpression):
        if xast.op == '/':
            left_xpath = serialize(xast.left)
            left_node = _find_xml_node(left_xpath, node, context)
            if left_node is not None:
                # remove the last element in the xpath
                removed = _remove_xml(xast.right, left_node, context,
                                      if_empty=if_empty) # honor current if_empty flag

                # If the left portion of the xpath is something we
                # could have constructed, remove it if it is empty.
                if removed and _predicate_is_constructible(left_xpath):
                    _remove_xml(xast.left, node, context, if_empty=True)

                # report on whether the leaf node was removed or not,
                # regardless of what was done with left portion of the path
                return removed

    return False

def _remove_child_node(node, context, xast, if_empty=False):
    '''Remove a child node based on the specified xpath.

    :param node: lxml element relative to which the xpath will be
    	interpreted
    :param context: any context required for the xpath (e.g.,
    	namespace definitions)
    :param xast: parsed xpath (xpath abstract syntax tree) from
	:mod:`eulxml.xpath`
    :param if_empty: optional boolean; only remove a node if it is
	empty (no attributes and no child nodes); defaults to False

    :returns: True if a node was deleted
    '''
    xpath = serialize(xast)
    child = _find_xml_node(xpath, node, context)
    if child is not None:
        # if if_empty was specified and node has children or attributes
        # other than any predicates defined in the xpath, don't remove
        if if_empty is True and \
               not _empty_except_predicates(xast, child, context):
            return False
        node.remove(child)
        return True

def _remove_attribute_node(node, context, xast):
    node_name, node_xpath, nsmap = _get_attribute_name(xast, context)
    del node.attrib[node_name]
    return True

def _remove_predicates(xast, node, context):
    '''Remove any constructible predicates specified in the xpath
    relative to the specified node.

    :param xast: parsed xpath (xpath abstract syntax tree) from
	:mod:`eulxml.xpath`
    :param node: lxml element which predicates will be removed from
    :param context: any context required for the xpath (e.g.,
    	namespace definitions)

    :returns: updated a copy of the xast without the predicates that
	were successfully removed
    '''
    # work from a copy since it may be modified
    xast_c = deepcopy(xast)
    # check if predicates are constructable
    for pred in list(xast_c.predicates):
        # ignore predicates that we can't construct
        if not _predicate_is_constructible(pred):
            continue

        if isinstance(pred, ast.BinaryExpression):
            # TODO: support any other predicate operators?
            # predicate construction supports op /

            # If the xml still matches the constructed value, remove it.
            # e.g., @type='text' or level='leaf'
            if pred.op == '=' and \
                   node.xpath(serialize(pred), **context) is True:
                # predicate xpath returns True if node=value

                if isinstance(pred.left, ast.Step):
                    if pred.left.axis in ('@', 'attribute'):
                        if _remove_attribute_node(node, context, pred.left):
                            # remove from the xast
                            xast_c.predicates.remove(pred)
                    elif pred.left.axis in (None, 'child'):
                        if _remove_child_node(node, context, pred.left, if_empty=True):
                            xast_c.predicates.remove(pred)

                elif isinstance(pred.left, ast.BinaryExpression):
                    # e.g., level/@id='b' or level/deep='deeper'
                    # - value has already been checked by xpath above,
                    # so just remove the multipart path
                    _remove_xml(pred.left, node, context, if_empty=True)

    return xast_c

def _empty_except_predicates(xast, node, context):
    '''Check if a node is empty (no child nodes or attributes) except
    for any predicates defined in the specified xpath.

    :param xast: parsed xpath (xpath abstract syntax tree) from
	:mod:`eulxml.xpath`
    :param node: lxml element to check
    :param context: any context required for the xpath (e.g.,
    	namespace definitions)

    :returns: boolean indicating if the element is empty or not
    '''
    # copy the node, remove predicates, and check for any remaining
    # child nodes or attributes
    node_c = deepcopy(node)
    _remove_predicates(xast, node_c, context)
    return bool(len(node_c) == 0 and len(node_c.attrib) == 0)

def _get_attribute_name(step, context):
    # calculate attribute name, xpath, and nsmap based on node info and context namespaces
    if not step.node_test.prefix:
        nsmap = {}
        ns_uri = None
        node_name = step.node_test.name
        node_xpath = '@%s' % node_name
    else:
        # if node has a prefix, the namespace *should* be defined in context
        if 'namespaces' in context and step.node_test.prefix in context['namespaces']:
            ns_uri = context['namespaces'][step.node_test.prefix]
        else:
            ns_uri = None
            # we could throw an exception here if ns_uri wasn't found, but
            # for now assume the user knows what he's doing...

        node_xpath = '@%s:%s' % (step.node_test.prefix, step.node_test.name)
        node_name = '{%s}%s' % (ns_uri, step.node_test.name)
        nsmap = {step.node_test.prefix: ns_uri}

    return node_name, node_xpath, nsmap

def _is_text_nodetest(step):
    '''Fields selected with an xpath of text() need special handling; Check if
    a xpath step is a text() node test. '''
    try:
        return step.node_test.name == 'text'
    except:
        pass
    return False

# managers to map operations to either a single identified node or a
# list of them

class SingleNodeManager(object):

    def __init__(self, instantiate_on_get=False):
        # DEPRECATED: don't use instantiate_on_get. Use create_for_node() as
        # described in XmlObjectType.__new__ comments and used by NodeField.
        self.instantiate_on_get = instantiate_on_get

    def get(self, xpath, node, context, mapper, xast):
        match = _find_xml_node(xpath, node, context)
        if match is None and self.instantiate_on_get:
            return mapper.to_python(_create_xml_node(xast, node, context))
        # else, non-None match, or not instantiate
        return mapper.to_python(match)

    def set(self, xpath, xast, node, context, mapper, value):
        xvalue = mapper.to_xml(value)
        match = _find_xml_node(xpath, node, context)

        if xvalue is None:
            # match must be None. if it exists, delete it.
            if match is not None:
                removed = _remove_xml(xast, node, context)
                # if a node can't be removed, warn since it could have unexpected results
                if not removed:
                    logger.warn('''Could not remove xml for '%s' from %r''' % \
                                (serialize(xast), node))
        else:
            if match is None:
                match = _create_xml_node(xast, node, context)
            # terminal (rightmost) step informs how we update the xml
            step = _find_terminal_step(xast)
            _set_in_xml(match, xvalue, context, step)

    def create(self, xpath, xast, node, context):
        # most clients will want to use get() or set(), but occasially we
        # just want a basic node to match the xpath.
        match = _find_xml_node(xpath, node, context)
        if match is not None:
            return match
        return _create_xml_node(xast, node, context)

    def delete(self, xpath, xast, node, context, mapper):
        match = _find_xml_node(xpath, node, context)
        # match must be None. if it exists, delete it.
        if match is not None:
            _remove_xml(xast, node, context)

class NodeList(object):
    """Custom List-like object to handle ListFields like :class:`IntegerListField`,
    :class:`StringListField`, and :class:`NodeListField`, which allows for getting,
    setting, and deleting list members.  :class:`NodeList` should **not** be
    initialized directly, but instead should only be accessed as the return type
    from a ListField.

    Supports common list functions and operators, including the following: len();
    **in**; equal and not equal comparison to standard python Lists.  Items can
    be retrieved, set, and deleted by index, but slice indexing is not supported.
    Supports the methods that Python documentation indicates should be provided
    by Mutable sequences, with the exceptions of reverse and sort; in the
    particular case of :class:`NodeListField`, it is unclear how a list of
    :class:`~eulxml.xmlmap.XmlObject` should be sorted, or whether or not such
    a thing would be useful or meaningful for XML content.

    When a new element is appended to a :class:`~eulxml.xmlmap.fields.NodeList`,
    it will be added to the XML immediately after the last element in the list.
    In the case of an empty list, the new content will be appended at the end of
    the appropriate XML parent node.  For XML content where element order is important
    for schema validity, extra care may be required when constructing content.
    """
    def __init__(self, xpath, node, context, mapper, xast):
        self.xpath = xpath
        self.node = node
        self.context = context
        self.mapper = mapper
        self.xast = xast

    @property
    def matches(self):
        # current matches from the xml tree
        # NOTE: retrieving from the xml every time rather than caching
        # because the xml document could change, and we want the latest data
        return self.node.xpath(self.xpath, **self.context)

    def is_empty(self):
        '''Parallel to :meth:`eulxml.xmlmap.XmlObject.is_empty`.  A
        NodeList is considered to be empty if every element in the
        list is empty.'''
        return all(n.is_empty() for n in self)

    @property
    def data(self):
        # data in list form - basis for several other list-y functions
        return [ self.mapper.to_python(match) for match in self.matches ]

    def __str__(self):
        return str(self.data)

    def __repr__(self):
        return str(self.data)

    def __len__(self):
        return len(self.data)

    def __contains__(self, item):
        return item in self.data

    def __iter__(self):
        for item in self.matches:
            yield self.mapper.to_python(item)

    def __eq__(self, other):
        # FIXME: is any other comparison possible ?
        return self.data == other

    def __ne__(self, other):
        return self.data != other

    def _check_key_type(self, key):
        # check argument type for getitem, setitem, delitem
        if not isinstance(key, (slice, six.integer_types)):
            raise TypeError
        assert not isinstance(key, slice), "Slice indexing is not supported"

    def __getitem__(self, key):
        self._check_key_type(key)
        return self.mapper.to_python(self.matches[key])

    def __setitem__(self, key, value):
        self._check_key_type(key)
        if key == len(self.matches):
            # just after the end of the list - create a new node
            if len(self.matches):
                # if there are existing nodes, use last element in list
                # to determine where the new node should be created
                last_item = self.matches[-1]
                position = last_item.getparent().index(last_item)
                insert_index = position + 1
            else:
                insert_index = None
            match = _create_xml_node(self.xast, self.node, self.context, insert_index)
        elif key > len(self.matches):
            raise IndexError("Can't set at index %d - out of range" % key )
        else:
            match = self.matches[key]

        if isinstance(self.mapper, NodeMapper):
            # if this is a NodeListField, the value should be an xmlobject
            # replace the indexed node with the node specified
            # NOTE: lxml does not require dom-style import before append/replace
            match.getparent().replace(match, value.node)
        else:       # not a NodeListField - set single-node value in xml
            # terminal (rightmost) step informs how we update the xml
            step = _find_terminal_step(self.xast)
            _set_in_xml(match, self.mapper.to_xml(value), self.context, step)

    def __delitem__(self, key):
        self._check_key_type(key)
        if key >= len(self.matches):
            raise IndexError("Can't delete at index %d - out of range" % key )

        match = self.matches[key]
        match.getparent().remove(match)

# according to python docs, Mutable sequences should provide the following methods:
# append, count, index, extend, insert, pop, remove, reverse and sort
# NOTE: not implementing sort/reverse at this time; not clear

    def count(self, x):
        "Return the number of times x appears in the list."
        return self.data.count(x)

    def append(self, x):
        "Add an item to the end of the list."
        self[len(self)] = x

    def index(self, x):
        """Return the index in the list of the first item whose value is x,
        or error if there is no such item."""
        return self.data.index(x)

    def remove(self, x):
        """Remove the first item from the list whose value is x,
        or error if there is no such item."""
        del(self[self.index(x)])

    def pop(self, i=None):
        """Remove the item at the given position in the list, and return it.
        If no index is specified, removes and returns the last item in the list."""
        if i is None:
            i = len(self) - 1
        val = self[i]
        del(self[i])
        return val

    def extend(self, list):
        """Extend the list by appending all the items in the given list."""
        for item in list:
            self.append(item)

    def insert(self, i, x):
        """Insert an item (x) at a given position (i)."""
        if i == len(self):  # end of list or empty list: append
            self.append(x)
        elif len(self.matches) > i:
            # create a new xml node at the requested position
            insert_index = self.matches[i].getparent().index(self.matches[i])
            _create_xml_node(self.xast, self.node, self.context, insert_index)
            # then use default set logic
            self[i] = x
        else:
            raise IndexError("Can't insert '%s' at index %d - list length is only %d" \
                            % (x, i, len(self)))

class NodeListManager(object):
    def get(self, xpath, node, context, mapper, xast):
        return NodeList(xpath, node, context, mapper, xast)

    def delete(self, xpath, xast, node, context, mapper):
        current_list = self.get(xpath, node, context, mapper, xast)
        [current_list.remove(x) for x in current_list]

    def set(self, xpath, xast, node, context, mapper, value):
        current_list = self.get(xpath, node, context, mapper, xast)
        # for each value in the new list, set the equivalent value
        # in the NodeList
        for i in range(len(value)):
            current_list[i] = value[i]

        # remove any extra values from end of the current list
        while len(current_list) > len(value):
            current_list.pop()

# finished field classes mixing a manager and a mapper

class StringField(Field):

    """Map an XPath expression to a single Python string. If the XPath
    expression evaluates to an empty NodeList, a StringField evaluates to
    `None`.

    Takes an optional parameter to indicate that the string contents should have
    whitespace normalized.  By default, does not normalize.

    Takes an optional list of choices to restrict possible values.

    Supports setting values for attributes, empty nodes, or text-only nodes.
    """

    def __init__(self, xpath, normalize=False, choices=None, *args, **kwargs):
        self.choices = choices
        # FIXME: handle at a higher level, common to all/more field types?
        #        does choice list need to be checked in the python ?
        super(StringField, self).__init__(xpath,
                manager = SingleNodeManager(),
                mapper = StringMapper(normalize=normalize), *args, **kwargs)

class StringListField(Field):

    """Map an XPath expression to a list of Python strings. If the XPath
    expression evaluates to an empty NodeList, a StringListField evaluates to
    an empty list.

    Takes an optional parameter to indicate that the string contents should have
    whitespace normalized.  By default, does not normalize.

    Takes an optional list of choices to restrict possible values.

    Actual return type is :class:`~eulxml.xmlmap.fields.NodeList`, which can be
    treated like a regular Python list, and includes set and delete functionality.
    """
    def __init__(self, xpath, normalize=False, choices=None, *args, **kwargs):
        self.choices = choices
        super(StringListField, self).__init__(xpath,
                manager = NodeListManager(),
                mapper = StringMapper(normalize=normalize), *args, **kwargs)

class FloatField(Field):

    """Map an XPath expression to a single Python float. If the XPath
    expression evaluates to an empty NodeList, an FloatField evaluates to
    `None`.

    Supports setting values for attributes, empty nodes, or text-only nodes.
    """

    def __init__(self, xpath, *args, **kwargs):
        super(FloatField, self).__init__(xpath,
                manager = SingleNodeManager(),
                mapper = FloatMapper(), *args, **kwargs)

class FloatListField(Field):

    """Map an XPath expression to a list of Python floats. If the XPath
    expression evaluates to an empty NodeList, an IntegerListField evaluates to
    an empty list.

    Actual return type is :class:`~eulxml.xmlmap.fields.NodeList`, which can be
    treated like a regular Python list, and includes set and delete functionality.
    """

    def __init__(self, xpath, *args, **kwargs):
        super(FloatListField, self).__init__(xpath,
                manager = NodeListManager(),
                mapper = FloatMapper(), *args, **kwargs)

class IntegerField(Field):

    """Map an XPath expression to a single Python integer. If the XPath
    expression evaluates to an empty NodeList, an IntegerField evaluates to
    `None`.

    Supports setting values for attributes, empty nodes, or text-only nodes.
    """

    def __init__(self, xpath, *args, **kwargs):
        super(IntegerField, self).__init__(xpath,
                manager = SingleNodeManager(),
                mapper = IntegerMapper(), *args, **kwargs)

class IntegerListField(Field):

    """Map an XPath expression to a list of Python integers. If the XPath
    expression evaluates to an empty NodeList, an IntegerListField evaluates to
    an empty list.

    Actual return type is :class:`~eulxml.xmlmap.fields.NodeList`, which can be
    treated like a regular Python list, and includes set and delete functionality.
    """

    def __init__(self, xpath, *args, **kwargs):
        super(IntegerListField, self).__init__(xpath,
                manager = NodeListManager(),
                mapper = IntegerMapper(), *args, **kwargs)

class SimpleBooleanField(Field):

    """Map an XPath expression to a Python boolean.  Constructor takes additional
    parameter of true, false values for comparison and setting in xml.  This only
    handles simple boolean that can be read and set via string comparison.

    Supports setting values for attributes, empty nodes, or text-only nodes.
    """

    def __init__(self, xpath, true, false, *args, **kwargs):
        super(SimpleBooleanField, self).__init__(xpath,
                manager = SingleNodeManager(),
                mapper = SimpleBooleanMapper(true, false), *args, **kwargs)

class DateTimeField(Field):
    """
    Map an XPath expression to a single Python
    :class:`datetime.datetime`. If the XPath expression evaluates to
    an empty :class:`NodeList`, a :class:`DateTimeField` evaluates to
    `None`.

    :param format: optional date-time format.  Used with
	:meth:`datetime.datetime.strptime` and
	:meth:`datetime.datetime.strftime` to convert between XML text
	and Python :class:`datetime.datetime` objects.  If no format
	is specified, XML dates are converted from full ISO date time
	format, with or without microseconds, and dates are written
	out to XML in ISO format via
	:meth:`datetime.datetime.isoformat`.

    :param normalize: optional parameter to indicate string contents
        should have whitespace normalized before converting to
        :class:`~datetime.datetime`.  By default, no normalization is
        done.

    For example, given the field definition::

      last_update = DateTimeField('last_update', format="%d-%m-%Y %H:%M:%S",
      	  normalize=True)

    and the XML::

      <last_update>
   	  21-04-2012 00:00:00
      </last_update>

    accessing the field would return::

      >>> myobj.last_update
      datetime.datetime(2012, 4, 21, 0, 0)

    """

    def __init__(self, xpath, format=None, normalize=False, *args, **kwargs):
        super(DateTimeField, self).__init__(xpath,
                manager = SingleNodeManager(),
                mapper = DateTimeMapper(format=format, normalize=normalize), *args, **kwargs)

class DateTimeListField(Field):
    """
    Map an XPath expression to a list of Python
    :class:`datetime.datetime` objects. If the XPath expression
    evaluates to an empty :class:`NodeList`, a
    :class:`DateTimeListField` evaluates to an empty list.  Date
    formatting is as described in :class:`DateTimeField`.

    Actual return type is :class:`~eulxml.xmlmap.fields.NodeList`, which can be
    treated like a regular Python list, and includes set and delete functionality.

    :param format: optional date-time format.  See
        :class:`DateTimeField` for more details.

    :param normalize: optional parameter to indicate string contents
        should have whitespace normalized before converting to
        :class:`~datetime.datetime`.  By default, no normalization is
        done.

    """

    def __init__(self, xpath, format=None, normalize=False, *args, **kwargs):
        super(DateTimeListField, self).__init__(xpath,
                manager = NodeListManager(),
                mapper = DateTimeMapper(format=format, normalize=normalize), *args, **kwargs)

class DateField(Field):
    '''
    Map an XPath expression to a single Python :class:`datetime.date`,
    roughly comparable to :class:`DateTimeField`.

    :param format: optional date-time format.  Used to convert between
        XML and Python :class:`datetime.date`; if no format, then
        the ISO format YYYY-MM-DD (%Y-%m-%d) will be used.
    :param normalize: optional parameter to indicate string contents
        should have whitespace normalized before converting to
        :class:`~datetime.date`.  By default, no normalization is
        done.
    '''

    def __init__(self, xpath, format=None, normalize=False, *args, **kwargs):
        super(DateField, self).__init__(xpath,
                manager = SingleNodeManager(),
                mapper = DateMapper(format=format, normalize=normalize), *args, **kwargs)

class DateListField(Field):
    '''
    Map an XPath expression to a list of Python
    :class:`datetime.date` objects. See :class:`DateField` and
    :class:`DateTimeListField` for more details.
    '''

    def __init__(self, xpath, format=None, normalize=False, *args, **kwargs):
        super(DateListField, self).__init__(xpath,
                manager = NodeListManager(),
                mapper = DateMapper(format=format, normalize=normalize), *args, **kwargs)

class NodeField(Field):

    """Map an XPath expression to a single
    :class:`~eulxml.xmlmap.XmlObject` subclass instance. If the XPath
    expression evaluates to an empty NodeList, a NodeField evaluates
    to `None`.

    Normally a ``NodeField``'s ``node_class`` is a class. As a special
    exception, it may be the string ``"self"``, in which case it recursively
    refers to objects of its containing :class:`~eulxml.xmlmap.XmlObject` class.

    If an :class:`~eulxml.xmlmap.XmlObject` contains a NodeField named
    ``foo``, then the object will automatically have a
    ``create_foo()`` method in addition to its ``foo`` property. Code
    can call this ``create_foo()`` method to create the child element
    if it doesn't exist; the method will have no effect if the element
    is already present.

    Deprecated ``instantiate_on_get`` flag: set to True if you need a
    non-existent node to be created when the NodeField is accessed. This
    feature is deprecated: Instead, create your node explicitly with
    ``create_foo()`` as described above.
    """

    def __init__(self, xpath, node_class, instantiate_on_get=False, *args, **kwargs):
        super(NodeField, self).__init__(xpath,
                manager = SingleNodeManager(instantiate_on_get=instantiate_on_get),
                mapper = NodeMapper(node_class), *args, **kwargs)

    def _get_node_class(self):
        return self.mapper.node_class
    def _set_node_class(self, val):
        self.mapper.node_class = val
    node_class = property(_get_node_class, _set_node_class)

    def create_for_node(self, node, context):
        return self.manager.create(self.xpath, self.parsed_xpath, node, context)

class NodeListField(Field):

    """Map an XPath expression to a list of
    :class:`~eulxml.xmlmap.XmlObject` subclass instances. If the XPath
    expression evalues to an empty NodeList, a NodeListField evaluates
    to an empty list.

    Normally a ``NodeListField``'s ``node_class`` is a class. As a special
    exception, it may be the string ``"self"``, in which case it recursively
    refers to objects of its containing :class:`~eulxml.xmlmap.XmlObject` class.

    Actual return type is :class:`~eulxml.xmlmap.fields.NodeList`, which can be
    treated like a regular Python list, and includes set and delete functionality.
    """

    def __init__(self, xpath, node_class, *args, **kwargs):
        super(NodeListField, self).__init__(xpath,
                manager = NodeListManager(),
                mapper = NodeMapper(node_class), *args, **kwargs)

    def _get_node_class(self):
        return self.mapper.node_class
    def _set_node_class(self, val):
        self.mapper.node_class = val
    node_class = property(_get_node_class, _set_node_class)

class ItemField(Field):

    """Access the results of an XPath expression directly. An ItemField does no
    conversion on the result of evaluating the XPath expression."""

    def __init__(self, xpath, *args, **kwargs):
        super(ItemField, self).__init__(xpath,
                manager = SingleNodeManager(),
                mapper = NullMapper(), *args, **kwargs)

class SchemaField(Field):
    """Schema-based field.  At class definition time, a SchemaField will be
    **replaced** with the appropriate :class:`eulxml.xmlmap.fields.Field` type
    based on the schema type definition.

    Takes an xpath (which will be passed on to the real Field init) and a schema
    type definition name.  If the schema type has enumerated restricted values,
    those will be passed as choices to the Field.

    For example, to define a resource type based on the `MODS
    <http://www.loc.gov/standards/mods/>`_ schema,
    ``resourceTypeDefinition`` is a simple type with an enumeration of
    values, so you could add something like this::

        resource_type  = xmlmap.SchemaField("mods:typeOfResource", "resourceTypeDefinition")

    Currently only supports simple string-based schema types.
    """
    def __init__(self, xpath, schema_type, *args, **kwargs):
        self.xpath = xpath
        self.schema_type = schema_type

        super(SchemaField, self).__init__(xpath, manager=None, mapper=None,
                *args, **kwargs)
        # SchemaField does not use common Field init logic; handle creation counter
        #self.creation_counter = Field.creation_counter
        #Field.creation_counter += 1

    def get_field(self, schema):
        """Get the requested type definition from the schema and return the
        appropriate :class:`~eulxml.xmlmap.fields.Field`.

        :param schema: instance of :class:`eulxml.xmlmap.core.XsdSchema`
        :rtype: :class:`eulxml.xmlmap.fields.Field`
        """
        type = schema.get_type(self.schema_type)
        logger.debug('Found schema type %s; base type %s, restricted values %s' % \
                     (self.schema_type, type.base_type(), type.restricted_values))
        kwargs = {}
        if type.restricted_values:
            # field has a restriction with enumerated values - pass as choices to field
            # - empty value at beginning of list for unset value; for required fields,
            #   will force user to select a value, rather than first item being default
            choices = []
            choices.extend(type.restricted_values)
            # restricted values could include a blank
            # if it's there, remove it so we don't get two
            if '' in choices:
                choices.remove('')
            choices.insert(0, '')   # add blank choice at the beginning of the list
            kwargs['choices'] = choices

        # TODO: possibly also useful to look for pattern restrictions

        basetype = type.base_type()
        if basetype == 'string':
            newfield = StringField(self.xpath, required=self.required, **kwargs)
            # copy original creation counter to newly created field
            # to preserve declaration order
            newfield.creation_counter = self.creation_counter
            return newfield
        else:
            raise Exception("basetype %s is not yet supported by SchemaField" % basetype)


text:
/*
 * \brief
 * \author Sylvain Jaume, Francois Huguet
 */

# ifndef SO_VTK_IMAGEDIFFERENCE_H_
# define SO_VTK_IMAGEDIFFERENCE_H_

# include <Inventor/engines/SoSubEngine.h>

# include "xip/inventor/vtk/SoSFVtkAlgorithmOutput.h"
# include "xip/inventor/vtk/SoSFVtkObject.h"

# include "vtkImageDifference.h"

# include "Inventor/fields/SoSFInt32.h"

class SoVtkImageDifference : public SoEngine
{
	SO_ENGINE_HEADER( SoVtkImageDifference );

public:

	/// Constructor
	SoVtkImageDifference();

	/// Class Initialization
	static void initClass();

	// Inputs
	/// AllowShift
	SoSFInt32 AllowShift;
	/// Averaging
	SoSFInt32 Averaging;
	/// Threshold
	SoSFInt32 Threshold;
	/// NumberOfThreads
	SoSFInt32 NumberOfThreads;
	/// Image of type vtkDataObject
	SoSFVtkObject Image;
	/// Input connection
	SoSFVtkAlgorithmOutput InputConnection;

	// Outputs
	/// SoSFVtkObject of type vtkImageData
	SoEngineOutput Output;
	/// SoSFVtkAlgorithmOutput
	SoEngineOutput OutputPort;
	/// SoSFVtkObject of type vtkImageData
	SoEngineOutput oImage;

protected:

	/// Destructor
	~SoVtkImageDifference();

	/// Evaluate Function
	virtual void evaluate();

	/// inputChanged Function
	virtual void inputChanged(SoField *);

	/// reset Function
	virtual void reset();

	/// vtkImageData
	SoVtkObject *mOutput;

	/// vtkAlgorithm
	SoVtkAlgorithmOutput *mOutputPort;

	/// vtkImageData
	SoVtkObject *mImage;

private:

	vtkImageDifference* mObject;
	/// addCalled checks if the Add*() method has been called
	bool addCalled;
};

#endif // SO_VTK_IMAGEDIFFERENCE_H_

redpajama_set_name: RedPajamaGithub


text:
<!doctype html>
<html>
  <head>
    <title>Barkovsky lab8</title>

    <link rel="stylesheet" href="style.css">

    <script src="three.min.js" defer></script>
    <script src="dat.gui.min.js" defer></script>
    <script src="rendering.js" defer></script>
  </head>
  <body>
  </body>
</html>


text:
{% import 'admin/static.html' as admin_static with context%}
{% import 'admin/lib.html' as lib with context %}

{# store the jinja2 context for form_rules rendering logic #}
{% set render_ctx = h.resolve_ctx() %}

{% block body %}

    <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>
    {% block header_text %}
{{ _gettext('Create New Record') }}
{% endblock %}

    {# "save and add" button is removed from modal (it won't function properly) #}
    {% block create_form %}
      {{ lib.render_form(form, return_url, extra=None, form_opts=form_opts,
                         action=url_for('.create_view', url=return_url),
                         is_modal=True) }}
    {% endblock %}

{% endblock %}

{% block tail %}

{% endblock %}


text:
class Table < ApplicationRecord
  has_many :reservations
end


text:
module Digest
    ( digest
    , digestlazy
    ) where

import qualified Crypto.Hash.SHA1 as SHA1

import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as BL

digest :: B.ByteString -> B.ByteString
digest bs = SHA1.hash bs

digestlazy :: BL.ByteString -> B.ByteString
digestlazy bs = SHA1.hashlazy bs


text:
package com.facebook.buck.cxx;

import com.facebook.buck.rules.BuildRule;
import com.facebook.buck.rules.RuleKey;
import com.facebook.buck.rules.SourcePath;
import com.facebook.buck.rules.SourcePathResolver;
import com.facebook.buck.rules.Tool;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSortedSet;

import java.nio.file.Path;

public class HashedFileTool implements Tool {

  public static final Function<Path, HashedFileTool> FROM_PATH =
      new Function<Path, HashedFileTool>() {
        @Override
        public HashedFileTool apply(Path input) {
          return new HashedFileTool(input);
        }
      };

  private final Path path;

  public HashedFileTool(Path path) {
    this.path = path;
  }

  @Override
  public RuleKey.Builder appendToRuleKey(RuleKey.Builder builder) {
    return builder.setReflectively("path", path);
  }

  @Override
  public ImmutableCollection<BuildRule> getDeps(SourcePathResolver resolver) {
    return ImmutableSortedSet.of();
  }

  @Override
  public ImmutableCollection<SourcePath> getInputs() {
    return ImmutableSortedSet.of();
  }

  @Override
  public ImmutableList<String> getCommandPrefix(SourcePathResolver resolver) {
    return ImmutableList.of(path.toString());
  }

}


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

/* global angular */

// Module
var dashboardModule = angular.module('dashboard', []);

// Controller
dashboardModule.controller('MainController', ['$scope', function($scope) {
  $scope.title = 'Dashboard';
}]);


text:
<?php
/**
 * Tests for Footer class
 *
 * @package PhpMyAdmin-test
 */

/*
 * Include to test.
 */

require_once 'libraries/Footer.class.php';
require_once 'libraries/Response.class.php';
require_once 'libraries/js_escape.lib.php';
require_once 'libraries/core.lib.php';
require_once 'libraries/url_generating.lib.php';
require_once 'libraries/php-gettext/gettext.inc';
require_once 'libraries/Util.class.php';
require_once 'libraries/Config.class.php';
require_once 'libraries/Theme.class.php';
require_once 'libraries/Table.class.php';
require_once 'libraries/Error_Handler.class.php';
require_once 'libraries/vendor_config.php';
require_once 'libraries/relation.lib.php';

/**
 * Tests for Footer class
 *
 * @package PhpMyAdmin-test
 */
class PMA_Footer_Test extends PHPUnit_Framework_TestCase
{

    /**
     * @var array store private attributes of PMA_Footer
     */
    public $privates = array();

    /**
     * @access protected
     */
    protected $object;

    /**
     * Sets up the fixture, for example, opens a network connection.
     * This method is called before a test is executed.
     *
     * @access protected
     * @return void
     */
    protected function setUp()
    {
        $_SERVER['SCRIPT_NAME'] = 'index.php';
        $GLOBALS['PMA_PHP_SELF'] = 'index.php';
        $GLOBALS['db'] = '';
        $GLOBALS['table'] = '';
        $GLOBALS['text_dir'] = 'ltr';
        $GLOBALS['pmaThemeImage'] = 'image';
        $GLOBALS['PMA_Config'] = new PMA_Config();
        $GLOBALS['PMA_Config']->enableBc();
        $GLOBALS['collation_connection'] = 'utf8_general_ci';
        $GLOBALS['cfg']['Server']['verbose'] = 'verbose host';
        $GLOBALS['cfg']['DefaultTabDatabase'] = 'db_structure.php';
        $GLOBALS['server'] = '1';
        $_GET['reload_left_frame'] = '1';
        $GLOBALS['focus_querywindow'] = 'main_pane_left';
        $this->object = new PMA_Footer();
        unset($GLOBALS['error_message']);
        unset($GLOBALS['sql_query']);
        $GLOBALS['error_handler'] = new PMA_Error_Handler();
        unset($_POST);

        $_SESSION['PMA_Theme'] = PMA_Theme::load('./themes/pmahomme');
        $_SESSION['PMA_Theme'] = new PMA_Theme();
    }

    /**
     * Tears down the fixture, for example, closes a network connection.
     * This method is called after a test is executed.
     *
     * @access protected
     * @return void
     */
    protected function tearDown()
    {
        unset($this->object);
    }

    /**
     * Call private functions by setting visibility to public.
     *
     * @param string $name   method name
     * @param array  $params parameters for the invocation
     *
     * @return the output from the private method.
     */
    private function _callPrivateFunction($name, $params)
    {
        $class = new ReflectionClass('PMA_Footer');
        $method = $class->getMethod($name);
        $method->setAccessible(true);
        return $method->invokeArgs($this->object, $params);
    }

    /**
     * Test for getDebugMessage
     *
     * @return void
     *
     * @group medium
     */
    public function testGetDebugMessage()
    {

        $_SESSION['debug']['queries'] = array(
            'abc' => array(
                'count' => 1,
                'time' => 0.2,
                'query' => 'SELECT * FROM `pma_bookmark` WHERE 1',
            ),
            'def' => array(
                'count' => 1,
                'time' => 2.5,
                'query' => 'SELECT * FROM `db` WHERE 1',
            ),
        );

        $this->assertRegExp(
            '/
2 queries executed 2 times in 2.7 seconds'
            . '
/',
            $this->object->getDebugMessage()
        );
    }

    /**
     * Test for _getSelfLink
     *
     * @return void
     */
    public function testGetSelfLink()
    {

        $GLOBALS['cfg']['TabsMode'] = 'text';
        $GLOBALS['cfg']['ServerDefault'] = 1;

        $this->assertEquals(
            '
Open new phpMyAdmin window
',
            $this->_callPrivateFunction(
                '_getSelfLink',
                array(
                    $this->object->getSelfUrl()
                )
            )
        );
    }

    /**
     * Test for _getSelfLink
     *
     * @return void
     */
    public function testGetSelfLinkWithImage()
    {

        $GLOBALS['cfg']['TabsMode'] = 'icons';
        $GLOBALS['cfg']['ServerDefault'] = 1;
        $_SESSION['PMA_Theme'] = new PMA_Theme();
        $GLOBALS['pmaThemeImage'] = 'image';

        $this->assertEquals(
            '

',
            $this->_callPrivateFunction(
                '_getSelfLink',
                array(
                    $this->object->getSelfUrl()
                )
            )
        );
    }

    /**
     * Test for disable
     *
     * @return void
     */
    public function testDisable()
    {
        $footer = new PMA_Footer();
        $footer->disable();
        $this->assertEquals(
            '',
            $footer->getDisplay()
        );
    }

    /**
     * Test for footer when ajax enabled
     *
     * @return void
     */
    public function testAjax()
    {
        $footer = new PMA_Footer();
        $footer->setAjax(true);
        $this->assertEquals(
            '',
            $footer->getDisplay()
        );
    }

    /**
     * Test for footer get Scripts
     *
     * @return void
     */
    public function testGetScripts()
    {
        $footer = new PMA_Footer();
        $this->assertContains(
            '


text:
Docker From php:5.4-fpm

Added libraries:

 * iconv
 * json
 * mcrypt
 * mbstring
 * mysql
 * mysqli
 * pdo_mysql
 * pdo_sqlite
 * phar
 * curl
 * ftp
 * hash
 * session
 * simplexml
 * tokenizer
 * xml
 * xmlrpc
 * zip

# Docker compose usage

Add to your docker-compose.yml file following:

```
phpfpm:
  command: php-fpm --allow-to-run-as-root
  image: akalongman/dock-php:5.6-fpm
  volumes:
    - /path/to/fpm.conf:/usr/local/etc/php-fpm.conf
    - /path/to/php.ini:/usr/local/etc/php/php.ini
    - /path/to/prject:/var/www/html
  privileged: true
```

Create fpm.conf and php.ini file in the path you have specified in docker-compose.yml

Samples for fpm.conf and php.ini:

 * php.ini - [https://github.com/akalongman/dock-php/wiki/php.ini](https://github.com/akalongman/dock-php/wiki/php.ini)
 * fpm.conf - [https://github.com/akalongman/dock-php/wiki/fpm.conf](https://github.com/akalongman/dock-php/wiki/fpm.conf)

# Configuring nginx docker to work with phpfpm

Add following to your docker-compose.yml:

```
nginx:
  image: nginx:1.9.0
  volumes:
    - /path/to/nginx.conf:/etc/nginx/conf.d/default.conf
    - /path/to/prject:/var/www
  ports:
   - "80:80"
  links:
   - phpfpm
```

Create nginx.conf in the path specified in docker-compose.yml

example nginx.conf - [https://github.com/akalongman/dock-php/wiki/nginx.conf](https://github.com/akalongman/dock-php/wiki/nginx.conf)


text:
class CreateContributorRequests < ActiveRecord::Migration
  def change
    create_table :contributor_requests do |t|
      t.integer :organization_id, null: false
      t.integer :user_id, null: false

      t.timestamps
    end

    add_index :contributor_requests, [:organization_id, :user_id], unique: true
  end
end


text:
The following text is to be inserted after the Alternative Schema Object section.

### Alternative Schema Examples

Minimalist usage of alternative schema:

    schema:
        x-oas-draft-alternativeSchema:
          type: jsonSchema
          location: ./real-jsonschema.json

Combination of OAS schema and alternative:

    schema:
        type: object
        nullable: true
        x-oas-draft-alternativeSchema:
            type: jsonSchema
            location: ./real-jsonschema.json

Multiple different versions of alternative schema:

    schema:
        anyOf:
            - x-oas-draft-alternativeSchema:
                type: jsonSchema
                location: ./real-jsonschema-08.json
            - x-oas-draft-alternativeSchema:
                type: jsonSchema
                location: ./real-jsonschema-07.json

Combined alternative schemas:

    schema:
        allOf:
            - x-oas-draft-alternativeSchema:
                type: xmlSchema
                location: ./xmlSchema.xsd
            - x-oas-draft-alternativeSchema:
                type: schematron
                location: ./schema.sch

Mixed OAS schema and alternative schema:

    schema:
        type: array
        items:
            x-oas-draft-alternativeSchema:
                type: jsonSchema
                location: ./real-jsonschema.json


text:
title: Sorting
page_title: Sorting - WinForms DropDownList Control
description: WinForms DropDownList supports sorting of its pop-up items.
slug: winforms/dropdown-listcontrol-and-checkeddropdownlist/dropdownlist/sorting
tags: sorting
published: True
position: 10
previous_url: dropdown-and-listcontrol-dropdownlist-sorting
---

# Sorting

## SortStyle

__RadDropDownList__ supports sorting of its pop-up items. You can control how the items in the __RadDropDownList__ are sorted by specifying the __SortStyle__ property.

* __Ascending__: indicates ascending sorting.

* __Descending__: indicates descending sorting.

* __None__: indicates no sorting. Items appear in the order of inserting.

>caption Figure 1: SortStyle.Descending

![dropdown-and-listcontrol-dropdownlist-sorting 001](images/dropdown-and-listcontrol-dropdownlist-sorting001.png)

#### SortStyle

{{source=..\SamplesCS\DropDownListControl\DropDownList\DropDownListSorting.cs region=SortStyle}}
{{source=..\SamplesVB\DropDownListControl\DropDownList\DropDownListSorting.vb region=SortStyle}}

````C#

this.radDropDownList1.SortStyle = Telerik.WinControls.Enumerations.SortStyle.Descending;

````
````VB.NET
Me.RadDropDownList1.SortStyle = Telerik.WinControls.Enumerations.SortStyle.Descending

````

{{endregion}}

## Customizing sort order

When the __SortStyle__ property is set to *Ascending* or *Descending* you can manipulate how the items are ordered by specifying the __ItemsSortComparer__ property. You should create a class that implements the __IComparer<RadListDataItem>__ interface. The following example demonstrates how to order the items considering the RadListDataItem.__Value__ property instead of the RadListDataItem.__Text__ property:

>caption Figure 2: Custom sort order

![dropdown-and-listcontrol-dropdownlist-sorting 002](images/dropdown-and-listcontrol-dropdownlist-sorting002.png)

#### Custom comparer

{{source=..\SamplesCS\DropDownListControl\DropDownList\DropDownListSorting.cs region=CustomComparer}}
{{source=..\SamplesVB\DropDownListControl\DropDownList\DropDownListSorting.vb region=CustomComparer}}

````C#

public DropDownListSorting()
{
    InitializeComponent();

    for (int i = 0; i < 10; i++)
    {
        RadListDataItem item = new RadListDataItem();
        item.Value = 10 - i;
        item.Text = i + ".Item";
        this.radDropDownList1.Items.Add(item);
    }
    this.radDropDownList1.SortStyle = Telerik.WinControls.Enumerations.SortStyle.Ascending;
    this.radDropDownList1.ItemsSortComparer = new CustomComparer();
}

public class CustomComparer : IComparer<RadListDataItem>
{
    public int Compare(RadListDataItem x, RadListDataItem y)
    {
        int xId = 0;
        int yId = 0;
        if (int.TryParse(x.Value.ToString(), out xId) && int.TryParse(y.Value.ToString(), out yId))
        {
            return xId.CompareTo(yId);
        }
        return x.Value.ToString().CompareTo(y.Value.ToString());
    }
}

````
````VB.NET
Public Sub New()
    InitializeComponent()
    For i As Integer = 0 To 9
        Dim item As New RadListDataItem()
        item.Value = 10 - i
        item.Text = i & ".Item"
        Me.RadDropDownList1.Items.Add(item)
    Next
    Me.RadDropDownList1.SortStyle = Telerik.WinControls.Enumerations.SortStyle.Ascending
    Me.RadDropDownList1.ItemsSortComparer = New CustomComparer()
End Sub

Public Class CustomComparer
Implements IComparer(Of RadListDataItem)
    Public Function [Compare](x As RadListDataItem, y As RadListDataItem) As Integer Implements IComparer(Of RadListDataItem).[Compare]
        Dim xId As Integer = 0
        Dim yId As Integer = 0
        If Integer.TryParse(x.Value.ToString(), xId) AndAlso Integer.TryParse(y.Value.ToString(), yId) Then
            Return xId.CompareTo(yId)
        End If
        Return x.Value.ToString().CompareTo(y.Value.ToString())
    End Function
End Class

````

{{endregion}}


text:
import React from 'react';
import {createStore, applyMiddleware, compose} from 'redux';
import {combineReducers} from 'redux';
import {reducer as formReducer} from 'redux-form';
import {Provider} from 'react-redux';
import {storiesOf, action} from '@kadira/storybook';
import {deepOrange500} from 'material-ui/styles/colors';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import ADCertificatePayloadForm from '../ADCertificatePayloadForm';

const store = createStore(
  combineReducers({ form: formReducer }),
  {}
);

const muiTheme = getMuiTheme({
  palette: {
    accent1Color: deepOrange500
  }
});

storiesOf('ADCertificatePayloadForm', module)
  .add('default', () => {
    'use strict';
    return (<MuiThemeProvider muiTheme={muiTheme}>
      <Provider store={store}>

          <ADCertificatePayloadForm onSubmit={action('submit')} />

      </Provider>
    </MuiThemeProvider>);
  })
  .add('compatibility: Yosemite', () => {
    'use strict';
    return (<MuiThemeProvider muiTheme={muiTheme}>
      <Provider store={store}>

          <ADCertificatePayloadForm onSubmit={action('submit')} compatMacOS='10.10.0' />

      </Provider>
    </MuiThemeProvider>);
  });


text:
#ifndef VIEWCOLUMNSETCOLORS_H
#define VIEWCOLUMNSETCOLORS_H

#include "cellcolors.h"
#include "dwarftherapist.h"

class ViewColumnSetColors : public CellColors {
    Q_OBJECT
public:
    ViewColumnSetColors(QObject *parent=0);
    ViewColumnSetColors(QSettings &s, QObject *parent=0);
    ~ViewColumnSetColors();

    CellColors *get_default_colors();

public slots:
    void use_defaults();

private:
    CellColors *m_defaults;
};
#endif // VIEWCOLUMNSETCOLORS_H


text:
package org.efaps.esjp.data.jaxb.attributes;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;

import org.efaps.admin.program.esjp.EFapsApplication;
import org.efaps.admin.program.esjp.EFapsUUID;

/**
 * TODO comment!
 *
 * @author The eFaps Team
 *
 */
@EFapsUUID("b34f1961-3e5f-4199-9ea6-9cc6d5e10d93")
@EFapsApplication("eFapsApp-Data")
@XmlAccessorType(XmlAccessType.NONE)
public abstract class AbstractSimpleEFapsAttribute<T extends AbstractSimpleEFapsAttribute<T, S>, S>
    extends AbstractEFapsAttribute<T>
{
    /**
     * Name of the Attribute.
     */
    @XmlAttribute(required = true)
    public String value;

    public abstract S getValue();

    /**
     * Setter method for instance variable {@link #value}.
     *
     * @param _value value for instance variable {@link #value}
     */
    public T setValue(final S _value)
    {
        this.value = _value.toString();
        return getThis();
    }

    /**
     * Getter method for the instance variable {@link #value}.
     *
     * @return value of instance variable {@link #value}
     */
    protected String getValueInternal()
    {
        return this.value;
    }
}


text:
{{ctxProp}}

<form><input type="button" [(ngModel)]="ctxProp" name="first"/></form>
<my-comp *ngIf="ctxBool"></my-comp>


text:
package org.codehaus.groovy.runtime.m12n;

import groovy.lang.GroovyRuntimeException;
import org.codehaus.groovy.runtime.metaclass.MetaClassRegistryImpl;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.*;

import static org.codehaus.groovy.runtime.DefaultGroovyMethodsSupport.closeQuietly;

/**
 * A module extension scanner is responsible for searching classpath modules,
 * loading metadata from module descriptors, then perform custom tasks for each
 * module.
 *
 * This class was introduced as a fix for GROOVY-6008
 *
 * @author Cedric Champeau
 * @since 2.1.2
 */
public class ExtensionModuleScanner {
    public final static String MODULE_META_INF_FILE = "META-INF/services/org.codehaus.groovy.runtime.ExtensionModule";

    private final ExtensionModuleListener listener;
    private final ClassLoader classLoader;

    public ExtensionModuleScanner(final ExtensionModuleListener listener, final ClassLoader loader) {
        this.listener = listener;
        this.classLoader = loader;
    }

    public void scanClasspathModules() {
        try {
            Enumeration<URL> resources = classLoader.getResources(MODULE_META_INF_FILE);
            while (resources.hasMoreElements()) {
                URL url = resources.nextElement();
                scanExtensionModuleFromMetaInf(url);
            }
        } catch (IOException e) {
            // DO NOTHING
        }
    }

    private void scanExtensionModuleFromMetaInf(final URL metadata) {
        Properties properties = new Properties();
        InputStream inStream = null;
        try {
            inStream = metadata.openStream();
            properties.load(inStream);
        } catch (IOException e) {
            throw new GroovyRuntimeException("Unable to load module META-INF descriptor", e);
        } finally {
            closeQuietly(inStream);
        }
        scanExtensionModuleFromProperties(properties);
    }

    public void scanExtensionModuleFromProperties(final Properties properties) {
        StandardPropertiesModuleFactory factory = new StandardPropertiesModuleFactory();
        ExtensionModule module = factory.newModule(properties, classLoader);
        listener.onModule(module);
    }

    public static interface ExtensionModuleListener {
        void onModule(ExtensionModule module);
    }
}


text:
package com.google.cloud.texttospeech.v1beta1.it;

import static org.junit.Assert.assertTrue;

import com.google.cloud.texttospeech.v1beta1.AudioConfig;
import com.google.cloud.texttospeech.v1beta1.AudioEncoding;
import com.google.cloud.texttospeech.v1beta1.ListVoicesRequest;
import com.google.cloud.texttospeech.v1beta1.ListVoicesResponse;
import com.google.cloud.texttospeech.v1beta1.SsmlVoiceGender;
import com.google.cloud.texttospeech.v1beta1.SynthesisInput;
import com.google.cloud.texttospeech.v1beta1.SynthesizeSpeechResponse;
import com.google.cloud.texttospeech.v1beta1.TextToSpeechClient;
import com.google.cloud.texttospeech.v1beta1.Voice;
import com.google.cloud.texttospeech.v1beta1.VoiceSelectionParams;
import com.google.protobuf.ByteString;
import java.io.IOException;
import java.util.List;
import org.junit.Test;

public class ITSystemTest {

  @Test
  public void synthesizeSpeechTest() throws IOException {
    try (TextToSpeechClient textToSpeechClient = TextToSpeechClient.create()) {
      SynthesisInput input = SynthesisInput.newBuilder().setText("Hello, World!").build();

      VoiceSelectionParams voice =
          VoiceSelectionParams.newBuilder()
              .setLanguageCode("en-US")
              .setSsmlGender(SsmlVoiceGender.NEUTRAL)
              .build();

      AudioConfig audioConfig =
          AudioConfig.newBuilder().setAudioEncoding(AudioEncoding.MP3).build();

      SynthesizeSpeechResponse response =
          textToSpeechClient.synthesizeSpeech(input, voice, audioConfig);

      ByteString audioContents = response.getAudioContent();

      assertTrue(!audioContents.isEmpty());
    }
  }

  @Test
  public void listVoicesTest() throws IOException {
    try (TextToSpeechClient textToSpeechClient = TextToSpeechClient.create()) {
      ListVoicesRequest request = ListVoicesRequest.getDefaultInstance();

      ListVoicesResponse response = textToSpeechClient.listVoices(request);
      List<Voice> voices = response.getVoicesList();

      assertTrue(!voices.isEmpty());
    }
  }
}


text:
% Copyright ©2016 The Gonum Authors. All rights reserved.
% Use of this source code is governed by a BSD-style
% license that can be found in the LICENSE file.

function PrintGoSlice(a)
      fprintf('[]float64{')
      for i = 1:length(a)
            fprintf('%1.16e, ',a(i))
      end
      fprintf('}\n')
end


text:
package org.amv.highmobility.cryptotool.command;

import com.google.common.collect.ImmutableList;
import lombok.Builder;
import org.amv.highmobility.cryptotool.BinaryExecutor;
import org.amv.highmobility.cryptotool.Cryptotool;
import org.amv.highmobility.cryptotool.CryptotoolImpl;
import reactor.core.publisher.Flux;

import java.util.List;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Strings.isNullOrEmpty;
import static java.util.Objects.requireNonNull;
import static org.amv.highmobility.cryptotool.command.CommandHelper.parseValueWithPrefix;

@Builder(builderClassName = "Builder")
public class SignCommand implements Command<Cryptotool.Signature> {

    private final String message;
    private final String privateKey;

    public SignCommand(String message, String privateKey) {
        requireNonNull(message, "`message` must not be null");
        checkArgument(!isNullOrEmpty(privateKey), "`privateKey` must not be empty");

        this.message = message;
        this.privateKey = privateKey;
    }

    @Override
    public Flux<Cryptotool.Signature> execute(BinaryExecutor executor) {
        List<String> args = ImmutableList.<String>builder()
                .add("sign")
                .add(message)
                .add(privateKey)
                .build();

        String signPrefix = "SIGNATURE: ";
        return executor.execute(args)
                .map(processResult -> parseValueWithPrefix(signPrefix, processResult.getStdoutLines())
                        .orElseThrow(() -> new IllegalStateException("Cannot find signature on stdout",
                                processResult.getException().orElse(null))))
                .map(signature -> CryptotoolImpl.SignatureImpl.builder()
                        .signature(signature)
                        .build());
    }
}


text:
namespace NArchive {
namespace N7z {

const unsigned kSignatureSize = 6;
extern Byte kSignature[kSignatureSize];

// #define _7Z_VOL
// 7z-MultiVolume is not finished yet.
// It can work already, but I still do not like some
// things of that new multivolume format.
// So please keep it commented.

#ifdef _7Z_VOL
extern Byte kFinishSignature[kSignatureSize];
#endif

struct CArchiveVersion
{
  Byte Major;
  Byte Minor;
};

const Byte kMajorVersion = 0;

struct CStartHeader
{
  UInt64 NextHeaderOffset;
  UInt64 NextHeaderSize;
  UInt32 NextHeaderCRC;
};

const UInt32 kStartHeaderSize = 20;

#ifdef _7Z_VOL
struct CFinishHeader: public CStartHeader
{
  UInt64 ArchiveStartOffset;  // data offset from end if that struct
  UInt64 AdditionalStartBlockSize; // start  signature & start header size
};

const UInt32 kFinishHeaderSize = kStartHeaderSize + 16;
#endif

namespace NID
{
  enum EEnum
  {
    kEnd,

    kHeader,

    kArchiveProperties,

    kAdditionalStreamsInfo,
    kMainStreamsInfo,
    kFilesInfo,

    kPackInfo,
    kUnpackInfo,
    kSubStreamsInfo,

    kSize,
    kCRC,

    kFolder,

    kCodersUnpackSize,
    kNumUnpackStream,

    kEmptyStream,
    kEmptyFile,
    kAnti,

    kName,
    kCTime,
    kATime,
    kMTime,
    kWinAttrib,
    kComment,

    kEncodedHeader,

    kStartPos,
    kDummy

    // kNtSecure,
    // kParent,
    // kIsAux
  };
}

const UInt32 k_Copy = 0;
const UInt32 k_Delta = 3;

const UInt32 k_LZMA2 = 0x21;

const UInt32 k_SWAP2 = 0x20302;
const UInt32 k_SWAP4 = 0x20304;

const UInt32 k_LZMA  = 0x30101;
const UInt32 k_PPMD  = 0x30401;

const UInt32 k_Deflate = 0x40108;
const UInt32 k_BZip2   = 0x40202;

const UInt32 k_BCJ   = 0x3030103;
const UInt32 k_BCJ2  = 0x303011B;
const UInt32 k_PPC   = 0x3030205;
const UInt32 k_IA64  = 0x3030401;
const UInt32 k_ARM   = 0x3030501;
const UInt32 k_ARMT  = 0x3030701;
const UInt32 k_SPARC = 0x3030805;

const UInt32 k_AES   = 0x6F10701;

static inline bool IsFilterMethod(UInt64 m)
{
  if (m > (UInt64)0xFFFFFFFF)
    return false;
  switch ((UInt32)m)
  {
    case k_Delta:
    case k_BCJ:
    case k_BCJ2:
    case k_PPC:
    case k_IA64:
    case k_ARM:
    case k_ARMT:
    case k_SPARC:
    case k_SWAP2:
    case k_SWAP4:
      return true;
  }
  return false;
}

}}

#endif


text:
function isChrome() {
   return navigator.userAgent.toLowerCase().indexOf('chrome/') > -1
}

var fragmentShaderHeader = [''               // SHADER HEADER
,'   precision highp float;'
].join('\n');

function gl_start(canvas, vertexShader) {           // START WEBGL RUNNING IN A CANVAS
   gl_vertexShader = vertexShader;
   fragmentShader = textArea.fss[1];

   setTimeout(function() {
      try {
         canvas.gl = canvas.getContext('experimental-webgl');                 // Make sure WebGl is supported.
      } catch (e) { throw 'Sorry, your browser does not support WebGL.'; }

      canvas.setFragmentShader = function(fragmentShader) {
         this.setShaders(gl_vertexShader, fragmentShader);
      }

      canvas.setShaders = function(vertexShader, fragmentShader) {            // Add the vertex and fragment shaders:
         var gl = this.gl, program = gl.createProgram();                           // Create the WebGL program.
         var shaderError = '';
	 errorLineNumber = -1;

         function addshader(type, src) {                                           // Create and attach a WebGL shader.
            var shader = gl.createShader(type);
            gl.shaderSource(shader, src);
            gl.compileShader(shader);
            if (! gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
	       shaderError = gl.getShaderInfoLog(shader);
               console.log('Cannot compile shader:\n\n' + shaderError);
            }
            gl.attachShader(program, shader);
         };

         addshader(gl.VERTEX_SHADER  , vertexShader  );                            // Add the vertex and fragment shaders.
         addshader(gl.FRAGMENT_SHADER, fragmentShaderHeader + fragmentShader);

         gl.linkProgram(program);                                                  // Link the program and report any errors.
         if (! gl.getProgramParameter(program, gl.LINK_STATUS))
            console.log('Could not link the shader program!');

         else {
            gl.useProgram(program);

            gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer());                        // Create a square as a triangle strip
            gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(                          //    consisting of two triangles.
                          [ -1,1,0, 1,1,0, -1,-1,0, 1,-1,0 ]), gl.STATIC_DRAW);

            var aPos = gl.getAttribLocation(program, 'aPos');                         // Assign aPos attribute to each vertex.
            gl.enableVertexAttribArray(aPos);
            gl.vertexAttribPointer(aPos, 3, gl.FLOAT, false, 0, 0);

            gl.uTime = gl.getUniformLocation(program, 'uTime');                       // Remember address of uTime variable.
         }

	 textArea.style.color = shaderError.length == 0 ? 'white' : '#ffffa0';
	 if (shaderError.length == 0)
	    errorMessage.innerHTML = '';
         else {
	    var message = shaderError.substring(9, shaderError.length);
	    errorLineNumber = parseInt(message) - 2;
	    message = message.substring(message.indexOf(' '), message.length);
	    var nE = message.indexOf('ERROR');
	    if (nE > 0)
	       message = message.substring(0, nE);
	    errorMessage.innerHTML = ''
	                           + message.substring(0, Math.min(60, message.length))
				   + '';
	 }
         highlight.setHighlight(highlightPattern);
      }

      canvas.setShaders(vertexShader, fragmentShader);                        // Initialize everything,

      setInterval(function() {                                                // Start the animation loop.
         var gl = canvas.gl;
         if (gl.startTime === undefined)                                           // First time through,
            gl.startTime = Date.now();                                             //    record the start time.
         gl.uniform1f(gl.uTime, (Date.now() - gl.startTime)  / 1000);              // Set time for the shaders.
         gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);                                   // Render the square.
      }, 30);

   }, 100); // Wait 100 milliseconds after page has loaded before starting WebGL.
}

var errorLineNumber = -1;
var highlightPattern = '  ';
var index = 0;
function prevIndex() { setIndex(index - 3); }
function nextIndex() { setIndex(index + 3); }

function setIndex(i) {
   var fss = textArea.fss;
   index = Math.max(0, Math.min(fss.length - 3, i));
   highlightPattern = fss[index];
   textArea.setCode(fss[index + 1]);
   narrative.innerHTML = fss[index + 2];
   prevButton.style.background = index == 0 ? 'black' : accentColor(true);
   nextButton.style.background = index == fss.length - 3 ? 'black' : accentColor(true);
   canvas1.setShaders(gl_vertexShader, fss[index + 1], fss[index + 2]);
   for (i = 0 ; i < fss.length ; i += 3)
      window['indexButton' + i].style.background = accentColor(i == index);
}

function accentColor(isTrue) { return isTrue ? '#aaddff' : '#006080'; }

function addTextEditor(fss, callback) {                      // Add a text editor to the web page:
   highlightPattern = fss[0];
   var code         = fss[1];
   var narrative    = fss[2];

   function createIndexButtons() {
      var str = '';
      for (var i = 0 ; i < fss.length ; i += 3)
         str += '<button id=indexButton' + i + ' onclick="setIndex(' + i + ')" '
	        + 'style="color:black;background:' + accentColor(i==0) + ';border-style:none;outline-width:0">'
		+ '' + String.fromCharCode(65 + Math.floor(i / 3)) + ''
		+ '</button>  '
      return str;
   }

   document.body.innerHTML = [''

      ,''
      ,'
'
      ,'
'

      ,''

      ,    '
'

      ,    '
'
      ,    ''
      ,    '	'
      ,    ''
      ,        createIndexButtons()
      ,    '	'
      ,    '
'

      ,    '
'
      ,    ' 	'
      ,    '<text id=errorMessage> </text>	'
      ,    '
'

      ,    '
'
      ,    ''
      ,        '<text id=highlight style="font:13px"></text>'
      ,    '	'

      ,    ''
      ,        '
'

      ,        '
'
      ,        ''
      ,            '<button id=prevButton style="color:black;background:black;border-style:none;outline-width:0">'
      ,                '<big><big>←</big> PREV</big>'
      ,            '</button>'

      ,            ' '

      ,            '<button id=nextButton style="color:black;background:' + accentColor(true) + ';border-style:none;outline-width:0">'
      ,                '<big>NEXT <big>→</big></big>'
      ,            '</button>'
      ,        '	'
      ,        '
'

      ,        '
'
      ,        ''
      ,            '<textArea id=textArea '
      ,            'style="background:black;color:white;font:13px courier;outline-width:0;border-style:none;resize:none;overflow:scroll">'
      ,            '</textArea>'
      ,        '	'
      ,        '
'

      ,        '
'
      ,        ''
      ,            '
<big><text id=narrative>'
      ,                narrative
      ,            '</text>
'
      ,        '	'
      ,        '
'

      ,        '
'
      ,    '	'
      ,    '
'

      ,    '
'

      ,'	'

      ,''
      ,    document.body.innerHTML
      ,'	'

      ,'
'
      ,'
'
      ,''

   ].join('');

   prevButton.onclick = prevIndex;
   nextButton.onclick = nextIndex;
   highlight.style.color = accentColor(true);

   highlight.setHighlight = function(hlight) {
      while (hlight.length <= errorLineNumber)
         hlight += ' ';
      var str = '', i;
      for (i = 0 ; i < hlight.length ; i++)
         str += ( i == errorLineNumber ? '██' :
	          hlight.charCodeAt(i) > 32 ? '██' : '  ' ) + '\n';
      this.innerHTML = '

' + str + '
';
   }

   highlight.setHighlight(highlightPattern);

   textArea.setCode = function(code) {
      this.value = code;

      var i = 0, text = this.value.split('\n');                             // Set the correct number of rows and columns.
      this.rows = text.length;
      while (i < text.length)
         this.cols = Math.max(this.cols, text[i++].length);
   }

   textArea.fss = fss;
   textArea.setCode(code);
   textArea.onkeyup = callback;                                              // User-provided callback function on keystroke.
}


text:
using namespace indexer;
using namespace std;

namespace search
{
// CitiesBoundariesTable::Boundaries ---------------------------------------------------------------
bool CitiesBoundariesTable::Boundaries::HasPoint(m2::PointD const & p) const
{
  return any_of(m_boundaries.begin(), m_boundaries.end(),
                [&](CityBoundary const & b) { return b.HasPoint(p, m_eps); });
}

// CitiesBoundariesTable ---------------------------------------------------------------------------
bool CitiesBoundariesTable::Load()
{
  auto handle = FindWorld(m_dataSource);
  if (!handle.IsAlive())
  {
    LOG(LWARNING, ("Can't find World map file."));
    return false;
  }

  // Skip if table was already loaded from this file.
  if (handle.GetId() == m_mwmId)
    return true;

  MwmContext context(move(handle));
  base::Cancellable const cancellable;
  auto const localities = CategoriesCache(LocalitiesSource{}, cancellable).Get(context);

  auto const & cont = context.m_value.m_cont;

  if (!cont.IsExist(CITIES_BOUNDARIES_FILE_TAG))
  {
    LOG(LWARNING, ("No cities boundaries table in the world map."));
    return false;
  }

  vector<vector<CityBoundary>> all;
  double precision;

  try
  {
    auto reader = cont.GetReader(CITIES_BOUNDARIES_FILE_TAG);
    ReaderSource<ReaderPtr<ModelReader>> source(reader);
    CitiesBoundariesSerDes::Deserialize(source, all, precision);
  }
  catch (Reader::Exception const & e)
  {
    LOG(LERROR, ("Can't read cities boundaries table from the world map:", e.Msg()));
    return false;
  }

  ASSERT_EQUAL(all.size(), localities.PopCount(), ());
  if (all.size() != localities.PopCount())
  {
    LOG(LERROR,
        ("Wrong number of boundaries, expected:", localities.PopCount(), "actual:", all.size()));
    return false;
  }

  m_mwmId = context.GetId();
  m_table.clear();
  m_eps = precision;
  size_t boundary = 0;
  localities.ForEach([&](uint64_t fid) {
    ASSERT_LESS(boundary, all.size(), ());
    m_table[base::asserted_cast<uint32_t>(fid)] = move(all[boundary]);
    ++boundary;
  });
  ASSERT_EQUAL(boundary, all.size(), ());
  return true;
}

bool CitiesBoundariesTable::Get(FeatureID const & fid, Boundaries & bs) const
{
  if (fid.m_mwmId != m_mwmId)
    return false;
  return Get(fid.m_index, bs);
}

bool CitiesBoundariesTable::Get(uint32_t fid, Boundaries & bs) const
{
  auto const it = m_table.find(fid);
  if (it == m_table.end())
    return false;
  bs = Boundaries(it->second, m_eps);
  return true;
}

void GetCityBoundariesInRectForTesting(CitiesBoundariesTable const & table, m2::RectD const & rect,
                                       vector<uint32_t> & featureIds)
{
  featureIds.clear();
  for (auto const & kv : table.m_table)
  {
    for (auto const & cb : kv.second)
    {
      if (rect.IsIntersect(m2::RectD(cb.m_bbox.Min(), cb.m_bbox.Max())))
      {
        featureIds.push_back(kv.first);
        break;
      }
    }
  }
}
}  // namespace search


text: create context ctx_logger_appenders_g using &logger_user..logging accessed globally;


text:
class test_generate_key_image_helper : public single_tx_test_base
{
public:
  static const size_t loop_count = 500;

  bool test()
  {
    CryptoNote::KeyPair in_ephemeral;
    Crypto::KeyImage ki;
    return CryptoNote::generate_key_image_helper(m_bob.getAccountKeys(), m_tx_pub_key, 0, in_ephemeral, ki);
  }
};


text:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using Reverb.Data.Contracts;
using Reverb.Data.Models;
using System;

namespace Reverb.Services.UnitTests.SongModifyServiceTests
{
    [TestClass]
    public class Constructor_Should
    {
        [TestMethod]
        public void Thorw_WhenSongRepoIsNotSupplied()
        {
            // Arrange
            //var songRepo = new Mock<IEfContextWrapper<Song>>();
            var artistRepo = new Mock<IEfContextWrapper<Artist>>();
            var albumRepo = new Mock<IEfContextWrapper<Album>>();
            var genreRepo = new Mock<IEfContextWrapper<Genre>>();
            var context = new Mock<ISaveContext>();

            // Act & Assert
            Assert.ThrowsException<ArgumentNullException>(() => new SongModifyService(
                null,
                artistRepo.Object,
                albumRepo.Object,
                genreRepo.Object,
                context.Object));
        }

        [TestMethod]
        public void Thorw_WhenArtistRepoIsNotSupplied()
        {
            // Arrange
            var songRepo = new Mock<IEfContextWrapper<Song>>();
            //var artistRepo = new Mock<IEfContextWrapper<Artist>>();
            var albumRepo = new Mock<IEfContextWrapper<Album>>();
            var genreRepo = new Mock<IEfContextWrapper<Genre>>();
            var context = new Mock<ISaveContext>();

            // Act & Assert
            Assert.ThrowsException<ArgumentNullException>(() => new SongModifyService(
                songRepo.Object,
                null,
                albumRepo.Object,
                genreRepo.Object,
                context.Object));
        }

        [TestMethod]
        public void Thorw_WhenAlbumRepoIsNotSupplied()
        {
            // Arrange
            var songRepo = new Mock<IEfContextWrapper<Song>>();
            var artistRepo = new Mock<IEfContextWrapper<Artist>>();
            //var albumRepo = new Mock<IEfContextWrapper<Album>>();
            var genreRepo = new Mock<IEfContextWrapper<Genre>>();
            var context = new Mock<ISaveContext>();

            // Act & Assert
            Assert.ThrowsException<ArgumentNullException>(() => new SongModifyService(
                null,
                artistRepo.Object,
                null,
                genreRepo.Object,
                context.Object));
        }

        [TestMethod]
        public void Thorw_WhenGenreRepoIsNotSupplied()
        {
            // Arrange
            var songRepo = new Mock<IEfContextWrapper<Song>>();
            var artistRepo = new Mock<IEfContextWrapper<Artist>>();
            var albumRepo = new Mock<IEfContextWrapper<Album>>();
            //var genreRepo = new Mock<IEfContextWrapper<Genre>>();
            var context = new Mock<ISaveContext>();

            // Act & Assert
            Assert.ThrowsException<ArgumentNullException>(() => new SongModifyService(
                songRepo.Object,
                artistRepo.Object,
                albumRepo.Object,
                null,
                context.Object));
        }

        [TestMethod]
        public void Thorw_WhenContextIsNotSupplied()
        {
            // Arrange
            var songRepo = new Mock<IEfContextWrapper<Song>>();
            var artistRepo = new Mock<IEfContextWrapper<Artist>>();
            var albumRepo = new Mock<IEfContextWrapper<Album>>();
            var genreRepo = new Mock<IEfContextWrapper<Genre>>();
            //var context = new Mock<ISaveContext>();

            // Act & Assert
            Assert.ThrowsException<ArgumentNullException>(() => new SongModifyService(
                songRepo.Object,
                artistRepo.Object,
                albumRepo.Object,
                genreRepo.Object,
                null));
        }
    }
}


text:
package org.onetwo.common.spring.aop;

import org.aopalliance.intercept.MethodInvocation;
import org.springframework.aop.support.DelegatingIntroductionInterceptor;

/**
 * @author wayshall
 * <br/>
 */
@SuppressWarnings("serial")
public class FreezableImpl extends DelegatingIntroductionInterceptor implements Freezable {
    private boolean freeze;

    @Override
	public void freeze() {
    	this.freeze = true;
	}

	@Override
	public void unfreeze() {
		this.freeze = false;
	}

	@Override
	public boolean freezed() {
		return freeze;
	}

	public Object invoke(MethodInvocation invocation) throws Throwable {
        if (freezed() && invocation.getMethod().getName().indexOf("set") == 0)
        	throw new IllegalStateException("locked");
        return super.invoke(invocation);
   }

}


text:
package io.datakernel.di.annotation;

import io.datakernel.di.Injector;

import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

/**
 * A binding which is transient has no slot in object cache. That is - it works more like traditional DI's,
 * creating new instances upon each {@link Injector#getInstance getInstance} call.
 * <p>
 * Bindings cannot be both transient and {@link Eager eager} at the same time.
 */
@Target(METHOD)
@Retention(RUNTIME)
public @interface Transient {
}


text:
package life;

import life.db.DbClause;
import life.db.DbIterator;
import life.db.DbKey;
import life.db.DbUtils;
import life.db.EntityDbTable;
import life.util.Listener;
import life.util.Listeners;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public final class AssetTransfer {

    public static enum Event {
        ASSET_TRANSFER
    }

    private static final Listeners<AssetTransfer,Event> listeners = new Listeners<>();

    private static final DbKey.LongKeyFactory<AssetTransfer> transferDbKeyFactory = new DbKey.LongKeyFactory<AssetTransfer>("id") {

        @Override
        public DbKey newKey(AssetTransfer assetTransfer) {
            return assetTransfer.dbKey;
        }

    };

    private static final EntityDbTable<AssetTransfer> assetTransferTable = new EntityDbTable<AssetTransfer>("asset_transfer", transferDbKeyFactory) {

        @Override
        protected AssetTransfer load(Connection con, ResultSet rs) throws SQLException {
            return new AssetTransfer(rs);
        }

        @Override
        protected void save(Connection con, AssetTransfer assetTransfer) throws SQLException {
            assetTransfer.save(con);
        }

    };

    public static DbIterator<AssetTransfer> getAllTransfers(int from, int to) {
        return assetTransferTable.getAll(from, to);
    }

    public static int getCount() {
        return assetTransferTable.getCount();
    }

    public static boolean addListener(Listener<AssetTransfer> listener, Event eventType) {
        return listeners.addListener(listener, eventType);
    }

    public static boolean removeListener(Listener<AssetTransfer> listener, Event eventType) {
        return listeners.removeListener(listener, eventType);
    }

    public static DbIterator<AssetTransfer> getAssetTransfers(long assetId, int from, int to) {
        return assetTransferTable.getManyBy(new DbClause.LongClause("asset_id", assetId), from, to);
    }

    public static DbIterator<AssetTransfer> getAccountAssetTransfers(long accountId, int from, int to) {
        Connection con = null;
        try {
            con = Db.db.getConnection();
            PreparedStatement pstmt = con.prepareStatement("SELECT * FROM asset_transfer WHERE sender_id = ?"
                    + " UNION ALL SELECT * FROM asset_transfer WHERE recipient_id = ? AND sender_id <> ? ORDER BY height DESC"
                    + DbUtils.limitsClause(from, to));
            int i = 0;
            pstmt.setLong(++i, accountId);
            pstmt.setLong(++i, accountId);
            pstmt.setLong(++i, accountId);
            DbUtils.setLimits(++i, pstmt, from, to);
            return assetTransferTable.getManyBy(con, pstmt, false);
        } catch (SQLException e) {
            DbUtils.close(con);
            throw new RuntimeException(e.toString(), e);
        }
    }

    public static DbIterator<AssetTransfer> getAccountAssetTransfers(long accountId, long assetId, int from, int to) {
        Connection con = null;
        try {
            con = Db.db.getConnection();
            PreparedStatement pstmt = con.prepareStatement("SELECT * FROM asset_transfer WHERE sender_id = ? AND asset_id = ?"
                    + " UNION ALL SELECT * FROM asset_transfer WHERE recipient_id = ? AND sender_id <> ? AND asset_id = ? ORDER BY height DESC"
                    + DbUtils.limitsClause(from, to));
            int i = 0;
            pstmt.setLong(++i, accountId);
            pstmt.setLong(++i, assetId);
            pstmt.setLong(++i, accountId);
            pstmt.setLong(++i, accountId);
            pstmt.setLong(++i, assetId);
            DbUtils.setLimits(++i, pstmt, from, to);
            return assetTransferTable.getManyBy(con, pstmt, false);
        } catch (SQLException e) {
            DbUtils.close(con);
            throw new RuntimeException(e.toString(), e);
        }
    }

    public static int getTransferCount(long assetId) {
        return assetTransferTable.getCount(new DbClause.LongClause("asset_id", assetId));
    }

    static AssetTransfer addAssetTransfer(Transaction transaction, Attachment.ColoredCoinsAssetTransfer attachment) {
        AssetTransfer assetTransfer = new AssetTransfer(transaction, attachment);
        assetTransferTable.insert(assetTransfer);
        listeners.notify(assetTransfer, Event.ASSET_TRANSFER);
        return assetTransfer;
    }

    static void init() {}

    private final long id;
    private final DbKey dbKey;
    private final long assetId;
    private final int height;
    private final long senderId;
    private final long recipientId;
    private final long quantityQNT;
    private final int timestamp;

    private AssetTransfer(Transaction transaction, Attachment.ColoredCoinsAssetTransfer attachment) {
        this.id = transaction.getId();
        this.dbKey = transferDbKeyFactory.newKey(this.id);
        this.height = transaction.getHeight();
        this.assetId = attachment.getAssetId();
        this.senderId = transaction.getSenderId();
        this.recipientId = transaction.getRecipientId();
        this.quantityQNT = attachment.getQuantityQNT();
        this.timestamp = transaction.getBlockTimestamp();
    }

    private AssetTransfer(ResultSet rs) throws SQLException {
        this.id = rs.getLong("id");
        this.dbKey = transferDbKeyFactory.newKey(this.id);
        this.assetId = rs.getLong("asset_id");
        this.senderId = rs.getLong("sender_id");
        this.recipientId = rs.getLong("recipient_id");
        this.quantityQNT = rs.getLong("quantity");
        this.timestamp = rs.getInt("timestamp");
        this.height = rs.getInt("height");
    }

    private void save(Connection con) throws SQLException {
        try (PreparedStatement pstmt = con.prepareStatement("INSERT INTO asset_transfer (id, asset_id, "
                + "sender_id, recipient_id, quantity, timestamp, height) "
                + "VALUES (?, ?, ?, ?, ?, ?, ?)")) {
            int i = 0;
            pstmt.setLong(++i, this.getId());
            pstmt.setLong(++i, this.getAssetId());
            pstmt.setLong(++i, this.getSenderId());
            pstmt.setLong(++i, this.getRecipientId());
            pstmt.setLong(++i, this.getQuantityQNT());
            pstmt.setInt(++i, this.getTimestamp());
            pstmt.setInt(++i, this.getHeight());
            pstmt.executeUpdate();
        }
    }

    public long getId() {
        return id;
    }

    public long getAssetId() { return assetId; }

    public long getSenderId() {
        return senderId;
    }

    public long getRecipientId() {
        return recipientId;
    }

    public long getQuantityQNT() { return quantityQNT; }

    public int getTimestamp() {
        return timestamp;
    }

    public int getHeight() {
        return height;
    }

}


text:
import DS from 'ember-data';

export default DS.Model.extend({
  github: DS.attr(),
  projectname: DS.attr(),
  site: DS.attr(),
  contributors: DS.attr(),
  images: DS.attr(),
  comments: DS.hasMany('comment', {
    async: true
  }),
  ratings: DS.hasMany('rating', {
    async: true
  }),
  // contributors: DS.hasMany('contributor', {
  //   async: true
  // })

});