text:
r"""
I/O Registry (:mod:`skbio.io.registry`)
=======================================

.. currentmodule:: skbio.io.registry

Classes
-------

.. autosummary::
   :toctree: generated/

   IORegistry
   Format

Functions
---------

.. autosummary::
   :toctree: generated/

   create_format

Exceptions
----------

.. autosummary::
   :toctree: generated/

   DuplicateRegistrationError
   InvalidRegistrationError

Creating a new format for scikit-bio
------------------------------------
scikit-bio makes it simple to add new file formats to its I/O registry.
scikit-bio maintains a singleton of the :class:`IORegistry` class called
`io_registry`. This is where all scikit-bio file formats are registered. One
could also instantiate their own :class:`IORegistry`, but that is not the focus
of this tutorial.

The first step to creating a new format is to add a submodule in
`skbio/io/format/` named after the file format you are implementing.
For example, if the format you are implementing is called `myformat` then you
would create a file called `skbio/io/format/myformat.py`.

The next step is to import the :func:`create_format` factory from
:mod:`skbio.io`. This will allow you to create a new :class:`Format` object
that `io_registry` will know about.

Ideally you should name the result of :func:`create_format` as your file name.
For example:

.. code-block:: python

   from skbio.io import create_format

   myformat = create_format('myformat')

The `myformat` object is what we will use to register our new functionality.
At this point you should evaulate whether your format is binary or text.
If your format is binary, your :func:`create_format` call should look like
this:

.. code-block:: python

   myformat = create_format('myformat', encoding='binary')

Alternatively if your format is text and has a specific encoding or newline
handling you can also specify that:

.. code-block:: python

   myformat = create_format('myformat', encoding='ascii', newline='\n')

This will ensure that our registry will open files with a default encoding of
`'ascii'` for `'myformat'` and expect all newlines to be `'\n'` characters.

Having worked out these details, we are ready to register the actual
functionality of our format (e.g., sniffer, readers, and writers).

To create a sniffer simply decorate the following onto your sniffer function:

.. code-block:: python

   @myformat.sniffer()
   def _myformat_sniffer(fh):
       # do something with `fh` to determine the membership of the file

For futher details on sniffer functions see :func:`Format.sniffer`.

Creating a reader is very similar, but has one difference:

.. code-block:: python

   @myformat.reader(SomeSkbioClass)
   def _myformat_to_some_skbio_class(fh, kwarg1='default', extra=FileSentinel):
       # parse `fh` and return a SomeSkbioClass instance here
       # `extra` will also be an open filehandle if provided else None

Here we bound a function to a specific class. We also demonstrated using
our FileSentinel object to indicate to the registry that this reader can take
auxilary files that should be handled in the same way as the primary file.
For futher details on reader functions see :func:`Format.reader`.

Creating a writer is about the same:

.. code-block:: python

   @myformat.writer(SomeSkbioClass)
   def _some_skbio_class_to_myformat(obj, fh, kwarg1='whatever',
                                     extra=FileSentinel):
       # write the contents of `obj` into `fh` and whatever else into `extra`
       # do not return anything, it will be ignored

This is exactly the same as the `reader` above just in reverse, we also
receive the object we are writing as the first parameter instead of the file
(which is the second one). For further details on writer functions see
:func:`Format.writer`.

.. note:: When raising errors in readers and writers, the error should be a
   subclass of ``FileFormatError`` specific to your new format.

Once you are satisfied with the functionality, you will need to ensure that
`skbio/io/__init__.py` contains an import of your new submodule so the
decorators are executed. Add the function
``import_module('skbio.io.format.myformat')`` with your module name to the
existing list.

.. note:: Because scikit-bio handles all of the I/O boilerplate, you only need
   to unit-test the actual business logic of your `readers`, `writers`, and
   `sniffers`.

Reserved Keyword Arguments
--------------------------
The following keyword args may not be used when defining new `readers` or
`writers` as they already have special meaning to the registry system:

- `format`
- `into`
- `verify`
- `mode`
- `encoding`
- `errors`
- `newline`
- `compression`
- `compresslevel`

The following are not yet used but should be avoided as well:

- `auth`
- `user`
- `password`
- `buffering`
- `buffer_size`
- `closefd`
- `exclusive`
- `append`

"""

# ----------------------------------------------------------------------------
# Copyright (c) 2013--, scikit-bio development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
# ----------------------------------------------------------------------------

from __future__ import absolute_import, division, print_function

from warnings import warn
import types
import traceback
import itertools
import inspect
from functools import wraps

from future.builtins import zip

from ._exception import DuplicateRegistrationError, InvalidRegistrationError
from . import (UnrecognizedFormatError, ArgumentOverrideWarning,
               FormatIdentificationWarning)
from .util import _resolve_file, open_file, open_files, _d as _open_kwargs
from skbio.util._misc import make_sentinel, find_sentinels
from skbio.util._decorator import stable

FileSentinel = make_sentinel("FileSentinel")

class IORegistry(object):
    """Create a registry of formats and implementations which map to classes.

    """

    @stable(as_of="0.4.0")
    def __init__(self):
        # This seperation of binary and text formats is useful because there
        # are many situations where we may have recieved a text-file. When this
        # happens, the binary data fundamentally does not exist. We could
        # assume encoding should be interpreted in reverse, however this misses
        # the bigger point: why would the user ever want text to be treated as
        # binary? They already went through the effort to hand us text.
        # Therefore, during format resolution, we should skip the binary
        # formats if they are irrelevant. (They are incompatible with such a
        # filehandle anyways.)
        self._binary_formats = {}
        self._text_formats = {}
        self._lookups = (self._binary_formats, self._text_formats)

    @stable(as_of="0.4.0")
    def create_format(self, *args, **kwargs):
        """A simple factory for creating new file formats.

        This will automatically register the format with this regsistry.

        All arguments are passed through to the Format constructor.

        Returns
        -------
        Format
            A new format that is registered with the registry.

        """
        format = Format(*args, **kwargs)
        self.add_format(format)
        return format

    @stable(as_of="0.4.0")
    def add_format(self, format_object):
        """Add a format to the registry.

        Parameters
        ----------
        format_object : Format
            The format to add to the registry.

        """
        # See comment in the constructor for an explanation for why this split
        # occurs.
        name = format_object.name
        if name in self._binary_formats or name in self._text_formats:
            raise DuplicateRegistrationError("A format already exists with"
                                             " that name: %s" % name)

        if format_object.is_binary_format:
            self._binary_formats[name] = format_object
        else:
            self._text_formats[name] = format_object

    @stable(as_of="0.4.0")
    def get_sniffer(self, format_name):
        """Locate the sniffer for a format.

        Parameters
        ----------
        format_name : str
            The name of the format to lookup.

        Returns
        -------
        function or None
            The sniffer associated with `format_name`

        """
        for lookup in self._lookups:
            if format_name in lookup:
                return lookup[format_name].sniffer_function
        return None

    @stable(as_of="0.4.0")
    def get_reader(self, format_name, cls):
        """Locate the reader for a format and class.

        Parameters
        ----------
        format_name : str
            The name of the format to lookup.
        cls : type or None
            The class which the reader will return an instance of. If `cls` is
            None, the reader will return a generator.
            Default is None.

        Returns
        -------
        function or None
            The reader associated with `format_name` and `cls`

        """
        return self._get_rw(format_name, cls, 'readers')

    @stable(as_of="0.4.0")
    def get_writer(self, format_name, cls):
        """Locate the writer for a format and class.

        Parameters
        ----------
        format_name : str
            The name of the format to lookup.
        cls : type or None
            The class which the writer will expect an instance of. If `cls` is
            None, the writer will expect a generator.
            Default is None.

        Returns
        -------
        function or None
            The writer associated with `format_name` and `cls`

        """
        return self._get_rw(format_name, cls, 'writers')

    def _get_rw(self, format_name, cls, lookup_name):
        for lookup in self._lookups:
            if format_name in lookup:
                format_lookup = getattr(lookup[format_name], lookup_name)
                if cls in format_lookup:
                    return format_lookup[cls]
        return None

    @stable(as_of="0.4.0")
    def list_read_formats(self, cls):
        """Return a list of available read formats for a given `cls` type.

        Parameters
        ----------
        cls : type
            The class which will be used to determine what read formats exist
            for an instance of `cls`.

        Returns
        -------
        list
            A list of available read formats for an instance of `cls`. List may
            be empty.

        """
        return list(self._iter_rw_formats(cls, 'readers'))

    @stable(as_of="0.4.0")
    def list_write_formats(self, cls):
        """Return a list of available write formats for a given `cls` type.

        Parameters
        ----------
        cls : type
            The class which will be used to determine what write formats exist
            for an instance of `cls`.

        Returns
        -------
        list
            A list of available write formats for an instance of `cls`. List
            may be empty.

        """
        return list(self._iter_rw_formats(cls, 'writers'))

    def _iter_rw_formats(self, cls, lookup_name):
        for lookup in self._lookups:
            for format in lookup.values():
                if cls in getattr(format, lookup_name):
                    yield format.name

    @stable(as_of="0.4.0")
    def sniff(self, file, **kwargs):
        """Detect the format of a given `file` and suggest kwargs for reading.

        Parameters
        ----------
        file : openable (filepath, URL, filehandle, etc.)
            The file to sniff. Something that is understood by `skbio.io.open`.
        kwargs : dict, optional
            Keyword arguments will be passed to `skbio.io.open`.

        Returns
        -------
        (str, dict)
            The name of the format of the file and any suggested kwargs for
            use with the corresponding reader.

        Raises
        ------
        UnrecognizedFormatError
            This occurs when the format is not 'claimed' by any registered
            sniffer or when the format is ambiguous and has been 'claimed' by
            more than one sniffer.

        """
        # By resolving the input here, we have the oppurtunity to reuse the
        # file (which is potentially ephemeral). Each sniffer will also resolve
        # the file, but that call will short-circuit and won't claim
        # responsibility for closing the file. This means that the file
        # should only close after leaving this context. This is also the reason
        # that we have to use SaneTextIOWrapper because each sniffer will
        # wrap the file to produce an appropriate default encoding for their
        # format (if unspecified). This results in the SaneTextIOWrapper being
        # garbage collected (using io.TextIOBase results in close being called
        # on our buffer by the deconstructor which we wanted to share with the
        # next sniffer)
        with _resolve_file(file, mode='r', **kwargs) as (fh, _,
                                                         is_binary_file):
            # tell may fail noisily if the user provided a TextIOBase or
            # BufferedReader which has already been iterated over (via next()).
            matches = []
            backup = fh.tell()
            if is_binary_file and kwargs.get('encoding', 'binary') == 'binary':
                matches = self._find_matches(fh, self._binary_formats,
                                             **kwargs)

            if kwargs.get('encoding', None) != 'binary':
                # We can always turn a binary file into a text file, but the
                # reverse doesn't make sense.
                matches += self._find_matches(fh, self._text_formats, **kwargs)
                fh.seek(backup)
            elif not is_binary_file:
                raise ValueError("Cannot decode text source (%r) as binary."
                                 % file)
            # else we are a binary_file and our encoding did not exclude binary
            # so we have already handled that condition

        if len(matches) > 1:
            raise UnrecognizedFormatError("File format for %r is ambiguous,"
                                          " may be one of: %r"
                                          % (file, [m for m, s in matches]))
        elif len(matches) == 0:
            raise UnrecognizedFormatError("Could not detect the format of %r"
                                          % file)

        return matches[0]

    def _find_matches(self, file, lookup, **kwargs):
        matches = []
        for format in lookup.values():
            if format.sniffer_function is not None:
                is_format, skwargs = format.sniffer_function(file, **kwargs)
                file.seek(0)
                if is_format:
                    matches.append((format.name, skwargs))
        return matches

    @stable(as_of="0.4.0")
    def read(self, file, format=None, into=None, verify=True, **kwargs):
        """Read `file` as `format` into an object.

        Parameters
        ----------
        file : openable (filepath, URL, filehandle, etc.)
            The file to read. Something that is understood by `skbio.io.open`.
        format : str, optional
            The format of the file if known. If None, the format will be
            inferred from the file.
        into : type or None, optional
            The object which will be returned. If None, a generator will be
            returned.
        verify : bool, optional
            When True, will double check the `format` if provided.
        kwargs : dict, optional
            Keyword arguments will be passed to their respective handlers
            (`skbio.io.open` and the reader for `format`)

        Returns
        -------
        object or generator
            An instance of `into` if `into` is not None else generator

        Raises
        ------
        ValueError
            Raised when `format` and `into` are both None.
        UnrecognizedFormatError
            Raised when a reader could not be found for a given `format` or the
            format could not be guessed.
        FormatIdentificationWarning
            Raised when `verify` is True and the sniffer of a `format` did
            not agree that `file` is a member of `format`
        ArgumentOverrideWarning
            Raised when `verify` is True and a user-supplied argument is
            overriding the suggestion provided by the sniffer of `format`.

        """
        # Context managers do not compose well with generators. We have to
        # duplicate the logic so that the file will stay open while yielding.
        # Otherwise the context exits as soon as the generator is returned
        # (making any iteration fail as the file is closed from its
        # perspective).
        if into is None:
            if format is None:
                raise ValueError("`into` and `format` cannot both be None")
            gen = self._read_gen(file, format, into, verify, kwargs)
            # This is done so that any errors occur immediately instead of
            # on the first call from __iter__
            # eta-reduction is possible, but we want to the type to be
            # GeneratorType
            return (x for x in itertools.chain([next(gen)], gen))
        else:
            return self._read_ret(file, format, into, verify, kwargs)

    def _read_ret(self, file, fmt, into, verify, kwargs):
        io_kwargs = self._find_io_kwargs(kwargs)
        with _resolve_file(file, **io_kwargs) as (file, _, _):
            reader, kwargs = self._init_reader(file, fmt, into, verify, kwargs,
                                               io_kwargs)
            return reader(file, **kwargs)

    def _read_gen(self, file, fmt, into, verify, kwargs):
        io_kwargs = self._find_io_kwargs(kwargs)
        # We needed to get the io_kwargs from kwargs for things like
        # _resolve_file and for verifying a format.
        # kwargs should still retain the contents of io_kwargs because the
        # actual reader will also need them.
        with _resolve_file(file, **io_kwargs) as (file, _, _):
            reader, kwargs = self._init_reader(file, fmt, into, verify, kwargs,
                                               io_kwargs)
            generator = reader(file, **kwargs)
            while True:
                yield next(generator)

    def _find_io_kwargs(self, kwargs):
        return {k: kwargs[k] for k in _open_kwargs if k in kwargs}

    def _init_reader(self, file, fmt, into, verify, kwargs, io_kwargs):
        skwargs = {}
        if fmt is None:
            fmt, skwargs = self.sniff(file, **io_kwargs)
        elif verify:
            sniffer = self.get_sniffer(fmt)
            if sniffer is not None:
                backup = file.tell()
                is_format, skwargs = sniffer(file, **io_kwargs)
                file.seek(backup)
                if not is_format:
                    warn("%r does not look like a %s file"
                         % (file, fmt), FormatIdentificationWarning)

        for key in skwargs:
            if key not in kwargs:
                kwargs[key] = skwargs[key]
            elif kwargs[key] != skwargs[key]:
                warn('Best guess was: %s=%r, continuing with user'
                     ' supplied: %r' % (key, skwargs[key],
                                        kwargs[key]),
                     ArgumentOverrideWarning)

        reader = self.get_reader(fmt, into)
        if reader is None:
            raise UnrecognizedFormatError(
                "Cannot read %r from %r, no %s reader found." %
                (fmt, file, into.__name__ if into else 'generator'))
        return reader, kwargs

    @stable(as_of="0.4.0")
    def write(self, obj, format, into, **kwargs):
        """Write `obj` as `format` into a file.

        Parameters
        ----------
        obj : object
            The object to write as `format`
        format : str
            The format to write `obj` as
        into : openable (filepath, URL, filehandle, etc.)
            What to write `obj` to. Something that is understood by
            `skbio.io.open`.
        kwargs : dict, optional
            Keyword arguments will be passed to their respective handlers
            (`skbio.io.open` and the writer for `format`)

        Returns
        -------
        openable (filepath, URL, filehandle, etc.)
            Will pass back the user argument for `into` as a convenience.

        Raises
        ------
        UnrecognizedFormatError
            Raised when a writer for writing `obj` as `format` could not be
            found.

        """
        # The simplest functionality here.
        cls = None
        if not isinstance(obj, types.GeneratorType):
            cls = obj.__class__
        writer = self.get_writer(format, cls)
        if writer is None:
            raise UnrecognizedFormatError(
                "Cannot write %r into %r, no %s writer found." %
                (format, into, obj.__class__.__name__))

        writer(obj, into, **kwargs)
        return into

    @stable(as_of="0.4.0")
    def monkey_patch(self):
        """Monkey-patch `read` and `write` methods onto registered classes.

        Will modify classes which have been registered to a reader or writer
        to have `read` and `write` methods which will contain documentation
        specifying useable formats for that class.

        The actual functionality will be a pass-through to `skbio.io.read`
        and `skbio.io.write` respectively.
        """
        reads = set()
        writes = set()
        for lookup in self._lookups:
            for format in lookup.values():
                reads |= format.monkey_patched_readers
                writes |= format.monkey_patched_writers

        for cls in reads:
            self._apply_read(cls)

        for cls in writes:
            self._apply_write(cls)

    def _apply_read(registry, cls):
        """Add read method if any formats have a reader for `cls`."""
        read_formats = registry.list_read_formats(cls)

        @classmethod
        def read(cls, file, format=None, **kwargs):
            return registry.read(file, into=cls, format=format, **kwargs)

        imports = registry._import_paths(read_formats)
        doc_list = registry._formats_for_docs(read_formats, imports)
        read.__func__.__doc__ = _read_docstring % {
            'name': cls.__name__,
            'list': doc_list,
            'see': '\n'.join(imports)
        }
        cls.read = read

    def _apply_write(registry, cls):
        """Add write method if any formats have a writer for `cls`."""
        write_formats = registry.list_write_formats(cls)
        if not hasattr(cls, 'default_write_format'):
            raise NotImplementedError(
                "Classes with registered writers must provide a "
                "`default_write_format`. Please add `default_write_format`"
                " to '%s'." % cls.__name__)

        def write(self, file, format=cls.default_write_format, **kwargs):
            return registry.write(self, into=file, format=format, **kwargs)

        imports = registry._import_paths(write_formats)
        doc_list = registry._formats_for_docs(write_formats, imports)
        write.__doc__ = _write_docstring % {
            'name': cls.__name__,
            'list': doc_list,
            'see': '\n'.join(imports),
            'default': cls.default_write_format
        }

        cls.write = write

    def _import_paths(self, formats):
        lines = []
        for fmt in formats:
            lines.append("skbio.io.format." + fmt)
        return lines

    def _formats_for_docs(self, formats, imports):
        lines = []
        for fmt, imp in zip(formats, imports):
            lines.append("- ``'%s'`` (:mod:`%s`)" % (fmt, imp))
        return '\n'.join(lines)

_read_docstring = """Create a new ``%(name)s`` instance from a file.

This is a convenience method for :func:`skbio.io.registry.read`. For
more information about the I/O system in scikit-bio, please see
:mod:`skbio.io`.

Supported file formats include:

%(list)s

Parameters
----------
file : openable (filepath, URL, filehandle, etc.)
    The location to read the given `format`. Something that is
    understood by :func:`skbio.io.util.open`. Filehandles are not
    automatically closed, it is the responsibility of the caller.
format : str, optional
    The format must be a format name with a reader for ``%(name)s``.
    If a `format` is not provided or is None, it will attempt to
    guess the format.
kwargs : dict, optional
    Keyword arguments passed to :func:`skbio.io.registry.read` and
    the file format reader for ``%(name)s``.

Returns
-------
%(name)s
    A new instance.

See Also
--------
write
skbio.io.registry.read
skbio.io.util.open
%(see)s

"""

_write_docstring = """Write an instance of ``%(name)s`` to a file.

This is a convenience method for :func:`skbio.io.registry.write`.
For more information about the I/O system in scikit-bio, please
see :mod:`skbio.io`.

Supported file formats include:

%(list)s

Parameters
----------
file : openable (filepath, URL, filehandle, etc.)
    The location to write the given `format` into.  Something
    that is understood by :func:`skbio.io.util.open`. Filehandles
    are not automatically closed, it is the responsibility of the
    caller.
format : str
    The format must be a registered format name with a writer for
    ``%(name)s``.
    Default is `'%(default)s'`.
kwargs : dict, optional
    Keyword arguments passed to :func:`skbio.io.registry.write`
    and the file format writer.

See Also
--------
read
skbio.io.registry.write
skbio.io.util.open
%(see)s

"""

class Format(object):
    """Defines a format on which readers/writers/sniffer can be registered.

    Parameters
    ----------
    name : str
        The name of this format.
    encoding : str, optional
        What the default encoding of this format is. If set to 'binary' then
        all registered handlers will receive an :class:`io.BufferedReader` or
        :class:`io.BufferedWriter` instead of an :class:`io.TextIOBase`. The
        user will also be unable to override the encoding in that case.
    newline : str, optional
        What the default newline handling of this format is. Default is to use
        universal newline handling.

    """
    @property
    @stable(as_of="0.4.0")
    def name(self):
        """The name of this format."""
        return self._name

    @property
    @stable(as_of="0.4.0")
    def is_binary_format(self):
        """Return True if this is a binary format."""
        return self._encoding == 'binary'

    @property
    @stable(as_of="0.4.0")
    def sniffer_function(self):
        """The sniffer function associated with this format."""
        return self._sniffer_function

    @property
    @stable(as_of="0.4.0")
    def readers(self):
        """Dictionary that maps classes to their writers for this format."""
        return self._readers

    @property
    @stable(as_of="0.4.0")
    def writers(self):
        """Dictionary that maps classes to their writers for this format."""
        return self._writers

    @property
    @stable(as_of="0.4.0")
    def monkey_patched_readers(self):
        """Set of classes bound to readers to monkey patch."""
        return self._monkey_patch['read']

    @property
    @stable(as_of="0.4.0")
    def monkey_patched_writers(self):
        """Set of classes bound to writers to monkey patch."""
        return self._monkey_patch['write']

    def __init__(self, name, encoding=None, newline=None):
        self._encoding = encoding
        self._newline = newline
        self._name = name

        self._sniffer_function = None
        self._readers = {}
        self._writers = {}
        self._monkey_patch = {'read': set(), 'write': set()}

    @stable(as_of="0.4.0")
    def sniffer(self, override=False):
        """Decorate a function to act as the sniffer for this format.

        The function should take one argument which will be an implementation
        of either :class:`io.TextIOBase` or :class:`io.BufferedReader`
        depending on if the format is text or binary, respectively.

        The sniffer will always receive a filehandle which is pointing to the
        beginning of the file. It must return a tuple of bool and a dict of
        suggested keyword arguments (if any) to pass to the reader.

        .. note:: Keyword arguments are not permitted in `sniffers`.
           `Sniffers` may not raise exceptions; if an exception is thrown by a
           `sniffer`, the user will be asked to report it on our `issue tracker
           <https://github.com/biocore/scikit-bio/issues/>`_.

        Parameters
        ----------
        override : bool, optional
            If True, the existing sniffer will be overriden.

        Raises
        ------
        DuplicateRegistrationError
            When `override` is False and a sniffer is already registered for
            this format.

        Examples
        --------
        >>> from skbio.io.registry import Format
        >>> # If developing a new format for skbio, use the create_format()
        >>> # factory instead of this constructor.
        >>> myformat = Format('myformat')
        >>> @myformat.sniffer()
        ... def myformat_sniffer(fh):
        ...     check = fh.read(8) == "myformat"
        ...     if check:
        ...         version = int(fh.read(1))
        ...         return True, {'version': version}
        ...     return False, {}
        ...
        >>> myformat_sniffer(["myformat2\\n", "some content\\n"])
        (True, {'version': 2})
        >>> myformat_sniffer(["something else\\n"])
        (False, {})

        """
        if not type(override) is bool:
            raise InvalidRegistrationError("`override` must be a bool not %r"
                                           % override)

        if not override and self._sniffer_function is not None:
            raise DuplicateRegistrationError("A sniffer is already registered"
                                             " to format: %s" % self._name)

        def decorator(sniffer):
            @wraps(sniffer)
            def wrapped_sniffer(file, encoding=self._encoding, errors='ignore',
                                newline=self._newline, **kwargs):
                self._validate_encoding(encoding)
                if encoding == 'binary':
                    # Errors is irrelevant so set to default to prevent raising
                    # a usage exception in open.
                    errors = _open_kwargs['errors']
                with open_file(file, mode='r', encoding=encoding,
                               newline=newline, errors=errors, **kwargs) as fh:
                    try:
                        # Some formats may have headers which indicate their
                        # format sniffers should be able to rely on the
                        # filehandle to point at the beginning of the file.
                        fh.seek(0)
                        return sniffer(fh)
                    except UnicodeDecodeError:
                        pass
                    except Exception:
                        warn("'%s' has encountered a problem.\nPlease"
                             " send the following to our issue tracker at\n"
                             "https://github.com/biocore/scikit-bio/issues\n\n"
                             "%s" % (sniffer.__name__, traceback.format_exc()),
                             FormatIdentificationWarning)

                    return False, {}

            self._sniffer_function = wrapped_sniffer
            return wrapped_sniffer
        return decorator

    @stable(as_of="0.4.0")
    def reader(self, cls, monkey_patch=True, override=False):
        """Decorate a function to act as the reader for a class in this format.

        The function should take an argument which will be an implementation
        of either :class:`io.TextIOBase` or :class:`io.BufferedReader`
        depending on if the format is text or binary, respectively. Any kwargs
        given by the user which are not handled by :func:`skbio.io.util.open`
        will be passed into the function. Any kwarg with a default of
        `FileSentinel` will transform user input for that parameter into a
        filehandle or `None` if not provided.

        Parameters
        ----------
        cls : type or None
            The class which the function will be registered to handle. If
            None, it is assumed that the function will produce a generator.
        monkey_patch : bool, optional
            Whether to allow an IORegistry to attach a `read` method to `cls`
            with this format listed as an option.
        override : bool, optional
            If True, any existing readers for `cls` in this format will be
            overriden.

        Raises
        ------
        DuplicateRegistrationError
            When `override` is False and a reader is already registered to
            `cls` for this format.

        Examples
        --------
        >>> from skbio.io.registry import Format, IORegistry
        >>> registry = IORegistry()
        >>> myformat = Format('myformat')
        >>> registry.add_format(myformat)
        >>> # If developing a new format for skbio, use the create_format()
        >>> # factory instead of the above.
        >>> class MyObject(object):
        ...     def __init__(self, content):
        ...         self.content = content
        ...
        >>> @myformat.reader(MyObject)
        ... def myformat_reader(fh):
        ...     return MyObject(fh.readlines()[1:])
        ...
        >>> registry.monkey_patch() # If developing skbio, this isn't needed
        >>> MyObject.read(["myformat2\\n", "some content here!\\n"],
        ...               format='myformat').content
        ['some content here!\\n']

        """
        self._check_registration(cls)

        def decorator(reader_function):
            file_params = find_sentinels(reader_function, FileSentinel)
            # This split has to occur for the same reason as in IORegistry.read
            if cls is not None:

                @wraps(reader_function)
                def wrapped_reader(file, encoding=self._encoding,
                                   newline=self._newline, **kwargs):
                    file_keys, files, io_kwargs = self._setup_locals(
                        file_params, file, encoding, newline, kwargs)
                    with open_files(files, mode='r', **io_kwargs) as fhs:
                        # The primary file is at the end of fh because append
                        # is cheaper than insert
                        kwargs.update(zip(file_keys, fhs[:-1]))
                        return reader_function(fhs[-1], **kwargs)
            else:

                @wraps(reader_function)
                def wrapped_reader(file, encoding=self._encoding,
                                   newline=self._newline, **kwargs):
                    file_keys, files, io_kwargs = self._setup_locals(
                        file_params, file, encoding, newline, kwargs)
                    with open_files(files, mode='r', **io_kwargs) as fhs:
                        kwargs.update(zip(file_keys, fhs[:-1]))
                        generator = reader_function(fhs[-1], **kwargs)
                        while True:
                            yield next(generator)

            self._add_reader(cls, wrapped_reader, monkey_patch, override)
            return wrapped_reader
        return decorator

    @stable(as_of="0.4.0")
    def writer(self, cls, monkey_patch=True, override=False):
        """Decorate a function to act as the writer for a class in this format.

        The function should take an instance of `cls` as its first argument
        and the second argument is a filehandle which will be an implementation
        of either :class:`io.TextIOBase` or :class:`io.BufferedWriter`
        depending on if the format is text or binary, respectively. Any kwargs
        given by the user which are not handled by :func:`skbio.io.util.open`
        will be passed into the function. Any kwarg with a default of
        `FileSentinel` will transform user input for that parameter into a
        filehandle or `None` if not provided.

        Parameters
        ----------
        cls : type or None
            The class which the function will be registered to handle. If
            None, it is assumed that the function will consume a generator.
        monkey_patch : bool, optional
            Whether to allow an IORegistry to attach a `write` method to `cls`
            with this format listed as an option.
        override : bool, optional
            If True, any existing writers for `cls` in this format will be
            overriden.

        Raises
        ------
        DuplicateRegistrationError
            When `override` is False and a writer is already registered to
            `cls` for this format.

        Examples
        --------
        >>> from skbio.io.registry import Format, IORegistry
        >>> registry = IORegistry()
        >>> myformat = Format('myformat')
        >>> registry.add_format(myformat)
        >>> # If developing a new format for skbio, use the create_format()
        >>> # factory instead of the above.
        >>> class MyObject(object):
        ...     default_write_format = 'myformat'
        ...     def __init__(self, content):
        ...         self.content = content
        ...
        >>> @myformat.writer(MyObject)
        ... def myformat_reader(obj, fh):
        ...     fh.write("myformat2\\n")
        ...     for c in obj.content:
        ...         fh.write(c)
        ...
        >>> registry.monkey_patch() # If developing skbio, this isn't needed
        >>> obj = MyObject(["some content here!\\n"])
        >>> obj.write([], format='myformat')
        ['myformat2\\n', 'some content here!\\n']

        """
        self._check_registration(cls)

        def decorator(writer_function):
            file_params = find_sentinels(writer_function, FileSentinel)

            @wraps(writer_function)
            def wrapped_writer(obj, file, encoding=self._encoding,
                               newline=self._newline, **kwargs):
                file_keys, files, io_kwargs = self._setup_locals(
                    file_params, file, encoding, newline, kwargs)
                with open_files(files, mode='w', **io_kwargs) as fhs:
                    kwargs.update(zip(file_keys, fhs[:-1]))
                    writer_function(obj, fhs[-1], **kwargs)

            self._add_writer(cls, wrapped_writer, monkey_patch, override)
            return wrapped_writer
        return decorator

    def _check_registration(self, cls):
        if cls is not None and not inspect.isclass(cls):
            raise InvalidRegistrationError("`cls` must be a class or None, not"
                                           " %r" % cls)

    def _setup_locals(self, file_params, file, encoding, newline, kwargs):
        self._validate_encoding(encoding)
        io_kwargs = self._pop_io_kwargs(kwargs, encoding, newline)
        file_keys, files = self._setup_file_args(kwargs, file_params)
        files.append(file)

        return file_keys, files, io_kwargs

    def _validate_encoding(self, encoding):
        if encoding != self._encoding:
            if self._encoding == 'binary':
                raise ValueError("Encoding must be 'binary' for %r"
                                 % self.name)
            if encoding == 'binary':
                raise ValueError("Encoding must not be 'binary' for %r"
                                 % self.name)

    def _pop_io_kwargs(self, kwargs, encoding, newline):
        io_kwargs = dict(encoding=encoding, newline=newline)
        for key in _open_kwargs:
            if key in kwargs:
                io_kwargs[key] = kwargs.pop(key)
        return io_kwargs

    def _setup_file_args(self, kwargs, file_params):
        file_keys = []
        files = []
        for param in file_params:
            arg = kwargs.get(param, None)
            if arg is not None:
                file_keys.append(param)
                files.append(arg)
            else:
                # set to None to mask FileSentinel when user neglected argument
                kwargs[param] = None

        return file_keys, files

    def _add_writer(self, cls, writer, monkey_patch, override):
        if cls in self._writers and not override:
            raise DuplicateRegistrationError("There is already a writer"
                                             " registered to %s in format: %s"
                                             % (cls, self._name))
        self._writers[cls] = writer
        if monkey_patch and cls is not None:
            self._monkey_patch['write'].add(cls)

    def _add_reader(self, cls, reader, monkey_patch, override):
        if cls in self._readers and not override:
            raise DuplicateRegistrationError("There is already a reader"
                                             " registered to %s in format: %s"
                                             % (cls, self._name))
        self._readers[cls] = reader
        if monkey_patch and cls is not None:
            self._monkey_patch['read'].add(cls)

io_registry = IORegistry()

@wraps(IORegistry.sniff)
def sniff(file, **kwargs):
    return io_registry.sniff(file, **kwargs)

@wraps(IORegistry.read)
def read(file, format=None, into=None, verify=True, **kwargs):
    return io_registry.read(file, format=format, into=into, verify=verify,
                            **kwargs)

@wraps(IORegistry.write)
def write(obj, format, into, **kwargs):
    return io_registry.write(obj, format, into, **kwargs)

@wraps(IORegistry.create_format)
def create_format(*args, **kwargs):
    return io_registry.create_format(*args, **kwargs)


text:
@interface JMQueue : NSObject

@property (readonly) NSUInteger count;

-(void) enqueueObject:(NSObject*)obj;
-(id) dequeueQbject;

@end

redpajama_set_name: RedPajamaGithub


text:
title: Investigative Process
published: true
cases:
sort_order: 1
---

The ICC [Office of the Prosecutor](https://www.icc-cpi.int/about/otp) (OTP) may turn a preliminary examination into a formal investigation called a situation (such as the situation in [Libya](){: .cc-active}) if the four phases of analysis in a preliminary examination are satisfied.

In an investigation, the OTP gathers as much information as possible to uncover the truth about the alleged crime as well as to determine who is most responsible. An investigation may include:

* Inspection where the alleged crime occurred;
* Collection of evidence like cellphone data, emails, radio intercepts, videos, photographs, minutes of meetings, military and police communications, speeches and forensic material such as exhumation reports;
* Interviewing witnesses and victims;
* Consultation with relevant experts and specialists;
* Analysis of financial transactions.

The OTP is legally required to take whatever steps are necessary to gather all evidence which is relevant to an alleged crime, including incriminating and exonerating evidence. Before trial starts, the Prosecutor must disclose a great deal of evidence to the Defense. This includes all the evidence the Prosecutor intends to rely upon at trial, and any evidence which tends to show the innocence of the accused or which affects the credibility of prosecution evidence.


text:
<?php

namespace DataSift\Storyplayer\ConfigLib;

use DataSift\Stone\ExceptionsLib\Exxx_Exception;

/**
 * Base exception thrown when the storyplayer.json file is somehow invalid
 *
 * @category  Libraries
 * @package   Storyplayer/ConfigLib
 * @author    Stuart Herbert <stuart.herbert@datasift.com>
 * @copyright 2011-present Mediasift Ltd www.datasift.com
 * @license   http://www.opensource.org/licenses/bsd-license.php  BSD License
 * @link      http://datasift.github.io/storyplayer
 */
class E4xx_StoryplayerConfigInvalid extends Exxx_Exception
{
}


text: Tools for running the LSST stack and visualizing the results.


text:
@implementation OneSquareBtn

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        self.titleLabel.textAlignment = NSTextAlignmentCenter;
        [self setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        self.titleLabel.font = [UIFont systemFontOfSize:15];
        [self setBackgroundImage:[UIImage imageNamed:@"mainCellBackground"] forState:UIControlStateNormal];
    }
    return self;
}

- (void)layoutSubviews
{
    [super layoutSubviews];

    self.imageView.y = self.height * 0.15;
    self.imageView.width = self.width * 0.5;
    self.imageView.height = self.imageView.width;
    self.imageView.centerX = self.width * 0.5;

    self.titleLabel.x = 0;
    self.titleLabel.y = CGRectGetMaxY(self.imageView.frame);
    self.titleLabel.width = self.width;
    self.titleLabel.height = self.height - self.titleLabel.y;
}

- (void)setSquare:(OneSquare *)square
{
    _square = square;

    [self setTitle:square.name forState:UIControlStateNormal];
    [self sd_setImageWithURL:[NSURL URLWithString:square.icon] forState:UIControlStateNormal];
}

@end


text:
/*
 *  This file is part of the WSF Staff project.
 *  Please, visit http://code.google.com/p/staff for more information.
 */

#include "IService.h"

namespace staff
{
  IService::IService()
  {
  }

  IService::~IService()
  {
  }

  void IService::OnCreate()
  {
  }

  void IService::OnDestroy()
  {
  }

  ServiceClient* IService::GetClient()
  {
    return NULL;
  }

  const std::string& IService::GetServiceName() const
  {
    return m_sServiceName;
  }

  const std::string& IService::GetSessionId() const
  {
    return m_sSessionId;
  }

  const std::string& IService::GetInstanceId() const
  {
    return m_sInstanceId;
  }

  void IService::Init(const std::string& sServiceName, const std::string& sSessionId, const std::string& sInstanceId)
  {
    m_sServiceName = sServiceName;
    m_sSessionId = sSessionId;
    m_sInstanceId = sInstanceId;
  }

}


text:
/* isxdigit( int )

   This file is part of the Public Domain C Library (PDCLib).
   Permission is granted to use, modify, and / or redistribute at will.
*/

#include <ctype.h>

#ifndef REGTEST
#include "_PDCLIB_locale.h"

int isxdigit( int c )
{
    return ( _PDCLIB_threadlocale()->_CType[c].flags & _PDCLIB_CTYPE_XDIGT );
}

#endif

#ifdef TEST
#include "_PDCLIB_test.h"

int main( void )
{
    TESTCASE( isxdigit( '0' ) );
    TESTCASE( isxdigit( '9' ) );
    TESTCASE( isxdigit( 'a' ) );
    TESTCASE( isxdigit( 'f' ) );
    TESTCASE( ! isxdigit( 'g' ) );
    TESTCASE( isxdigit( 'A' ) );
    TESTCASE( isxdigit( 'F' ) );
    TESTCASE( ! isxdigit( 'G' ) );
    TESTCASE( ! isxdigit( '@' ) );
    TESTCASE( ! isxdigit( ' ' ) );
    return TEST_RESULTS;
}

#endif


text:
#include <onyx/irq.h>
#include <onyx/net/netif.h>
#include <onyx/panic.h>
#include <onyx/percpu.h>
#include <onyx/softirq.h>
#include <onyx/timer.h>

PER_CPU_VAR(unsigned int pending_vectors);

bool softirq_may_handle()
{
    auto irqs_enabled = !irq_is_disabled();
    auto preemption_disabled = sched_is_preemption_disabled();

    return irqs_enabled && !preemption_disabled;
}

bool softirq_pending()
{
    return get_per_cpu(pending_vectors) != 0;
}

void softirq_handle()
{
    sched_disable_preempt();

    bool is_disabled = irq_is_disabled();

    irq_enable();

    auto pending = get_per_cpu(pending_vectors);

    if (pending & (1 << SOFTIRQ_VECTOR_TIMER))
    {
        timer_handle_events(platform_get_timer());
        pending &= ~(1 << SOFTIRQ_VECTOR_TIMER);
    }

#ifdef CONFIG_NET
    if (pending & (1 << SOFTIRQ_VECTOR_NETRX))
    {
        netif_do_rx();
        pending &= ~(1 << SOFTIRQ_VECTOR_NETRX);
    }
#endif

    write_per_cpu(pending_vectors, pending);

    if (is_disabled)
        irq_disable();

    sched_enable_preempt_no_softirq();
}

void softirq_try_handle()
{
    if (get_per_cpu(pending_vectors) && softirq_may_handle())
        softirq_handle();
}

void softirq_raise(enum softirq_vector vec)
{
    unsigned int mask = (1 << vec);

    auto flags = irq_save_and_disable();

    /* This is thread safe because you can't signal other CPUs's softirqs */
    auto pending = get_per_cpu(pending_vectors) | mask;

    write_per_cpu(pending_vectors, pending);

    irq_restore(flags);

    if (pending && softirq_may_handle())
        softirq_handle();
}


text:
TaskOperation = function(conf) {
	if (!conf) {
		conf = {
			formId: 'xform',
			toolbarId: 'xformToolbar'
		};
	}

	this.formId = conf.formId;
	this.toolbarId = conf.toolbarId;
};

TaskOperation.prototype.saveDraft = function() {
	$('#' + this.formId).attr('action', ROOT_URL + '/operation/process-operation-saveDraft.do');
	$('#' + this.formId).submit();
};

TaskOperation.prototype.startProcess = function() {
	$('#' + this.formId).attr('action', ROOT_URL + '/operation/process-operation-startProcess.do');
	$('#' + this.formId).submit();
};

TaskOperation.prototype.taskConf = function() {
	$('#' + this.formId).attr('action', ROOT_URL + '/operation/process-operation-taskConf.do');
	$('#' + this.formId).submit();
};

TaskOperation.prototype.confirmStartProcess = function() {
	$('#' + this.formId).attr('action', ROOT_URL + '/operation/process-operation-confirmStartProcess.do');
	$('#' + this.formId).submit();
};

TaskOperation.prototype.completeTask = function() {
	$('#' + this.formId).attr('action', ROOT_URL + '/operation/task-operation-completeTask.do');
	$('#' + this.formId).submit();
};

TaskOperation.prototype.rollbackPrevious = function() {
	$('#' + this.formId).attr('action', ROOT_URL + '/operation/task-operation-rollbackPrevious.do');
	$('#' + this.formId).submit();
};

TaskOperation.prototype.transfer = function() {
	$('#modal form').attr('action', ROOT_URL + '/operation/task-operation-transfer.do');
	$('#modal').modal();
};

TaskOperation.prototype.delegateTask = function() {
	$('#modal form').attr('action', ROOT_URL + '/operation/task-operation-delegateTask.do');
	$('#modal').modal();
};


text:
module ListWatched where

import qualified Github.Repos.Watching as Github
import Data.List (intercalate)
import Data.Maybe (fromMaybe)

main = do
  possibleRepos <- Github.reposWatchedBy "mike-burns"
  putStrLn $ either (("Error: "++) . show)
                    (intercalate "\n\n" . map formatRepo)
                    possibleRepos

formatRepo repo =
  (Github.repoName repo) ++ "\t" ++
    (fromMaybe "" $ Github.repoDescription repo) ++ "\n" ++
    (Github.repoHtmlUrl repo) ++ "\n" ++
    (Github.repoCloneUrl repo) ++ "\t" ++
    (formatDate $ Github.repoUpdatedAt repo) ++ "\n" ++
    formatLanguage (Github.repoLanguage repo) ++
    "watchers: " ++ (show $ Github.repoWatchers repo) ++ "\t" ++
    "forks: " ++ (show $ Github.repoForks repo)

formatDate = show . Github.fromGithubDate

formatLanguage (Just language) = "language: " ++ language ++ "\t"
formatLanguage Nothing = ""


text:
using System.ServiceModel.Syndication;
using System.Web.Mvc;
using System.Xml;

namespace Firehose.Web.Infrastructure
{
	public class RssFeedResult : ActionResult
	{
		private readonly SyndicationFeed _feed;

		public RssFeedResult(SyndicationFeed feed)
		{
			_feed = feed;
		}

		public override void ExecuteResult(ControllerContext context)
		{
			context.HttpContext.Response.ContentType = "application/rss+xml";

			var rssFormatter = new Rss20FeedFormatter(_feed);
			using (var writer = XmlWriter.Create(context.HttpContext.Response.Output))
			{
				rssFormatter.WriteTo(writer);
			}
		}
	}
}


text:
#include "third_party/blink/renderer/core/events/progress_event.h"

#include "third_party/blink/renderer/bindings/core/v8/v8_progress_event_init.h"
#include "third_party/blink/renderer/core/event_interface_names.h"

namespace blink {

ProgressEvent::ProgressEvent()
    : length_computable_(false), loaded_(0), total_(0) {}

ProgressEvent::ProgressEvent(const AtomicString& type,
                             const ProgressEventInit* initializer)
    : Event(type, initializer),
      length_computable_(initializer->lengthComputable()),
      loaded_(initializer->loaded()),
      total_(initializer->total()) {}

ProgressEvent::ProgressEvent(const AtomicString& type,
                             bool length_computable,
                             uint64_t loaded,
                             uint64_t total)
    : Event(type, Bubbles::kNo, Cancelable::kNo),
      length_computable_(length_computable),
      loaded_(loaded),
      total_(total) {}

const AtomicString& ProgressEvent::InterfaceName() const {
  return event_interface_names::kProgressEvent;
}

void ProgressEvent::Trace(Visitor* visitor) {
  Event::Trace(visitor);
}

}  // namespace blink


text:
package com.spectralogic.dsbrowser.gui.services;

import com.google.inject.*;
import com.google.inject.util.Modules;
import com.spectralogic.ds3client.Ds3Client;
import com.spectralogic.ds3client.Ds3ClientImpl;
import com.spectralogic.dsbrowser.gui.DeepStorageBrowserPresenter;
import com.spectralogic.dsbrowser.gui.GuiModule;
import com.spectralogic.dsbrowser.gui.components.interruptedjobwindow.ButtonCell;
import com.spectralogic.dsbrowser.gui.components.interruptedjobwindow.EndpointInfo;
import com.spectralogic.dsbrowser.gui.services.settings.SettingsStore;
import com.sun.javafx.application.PlatformImpl;
import org.junit.BeforeClass;
import org.junit.Test;

import static org.mockito.Mockito.*;
import static org.junit.Assert.fail;

public class FactoryTest {
    private static Injector injector;
    private static TestModlue testModlue;
    private static GuiModule guiModule;
    private final static EndpointInfo endpointInfo = mock(EndpointInfo.class);

    private static class TestModlue implements Module {
        public void configure(final Binder binder) {
        }

        @Provides
        public BuildInfoServiceImpl getBuildService() {
            return mock(BuildInfoServiceImpl.class);
        }

        @Provides
        public DeepStorageBrowserPresenter getDSP() {
            return mock(DeepStorageBrowserPresenter.class);
        }

        @Provides
        protected Ds3Client providesDs3Client() {
            return mock(Ds3ClientImpl.class);
        }

        @Singleton
        @Provides
        protected SettingsStore providesSettingsStore() {
            return SettingsStore.createDefaultSettingStore();
        }
    }

    /*
        install(new FactoryModuleBuilder().build(ButtonCell.ButtonCellFactory.class));
     */

    @BeforeClass
    public static void prep() {
        testModlue = new TestModlue();
        guiModule = new GuiModule();
        injector = Guice.createInjector(Modules.override(guiModule).with(testModlue));
    }

    @Test
    public void buildButtonCell() {
        PlatformImpl.startup(new Runnable() {
            @Override
            public void run() {

            }
        });
        final ButtonCell.ButtonCellFactory f = injector.getInstance(ButtonCell.ButtonCellFactory.class);
        ButtonCell bc = null;
        try {
            bc = f.createButtonCell(endpointInfo);
        } catch (final ProvisionException pe) {
            fail("Provision Exception was thrown");
        }
        assert bc != null;
    }

}


text:
using System;
using AutoFixture.Kernel;
using Xunit;

namespace AutoFixtureUnitTest.Kernel
{
    public class SeedIgnoringRelayTest
    {
        [Fact]
        public void SutIsSpecimenBuilder()
        {
            // Arrange
            // Act
            var sut = new SeedIgnoringRelay();
            // Assert
            Assert.IsAssignableFrom<ISpecimenBuilder>(sut);
        }

        [Fact]
        public void CreateWithNullRequestWillReturnNull()
        {
            // Arrange
            var sut = new SeedIgnoringRelay();
            // Act
            var dummyContainer = new DelegatingSpecimenContext();
            var result = sut.Create(null, dummyContainer);
            // Assert
            var expectedResult = new NoSpecimen();
            Assert.Equal(expectedResult, result);
        }

        [Fact]
        public void CreateWithNullContainerWillThrow()
        {
            // Arrange
            var sut = new SeedIgnoringRelay();
            var dummyRequest = new object();
            // Act & assert
            Assert.Throws<ArgumentNullException>(() =>
                sut.Create(dummyRequest, null));
        }

        [Fact]
        public void CreateFromSeedWhenContainerCannotSatisfyWrappedRequestWillReturnNull()
        {
            // Arrange
            var anonymousSeed = new SeededRequest(typeof(object), new object());
            var unableContainer = new DelegatingSpecimenContext { OnResolve = r => new NoSpecimen() };
            var sut = new SeedIgnoringRelay();
            // Act
            var result = sut.Create(anonymousSeed, unableContainer);
            // Assert
            var expectedResult = new NoSpecimen();
            Assert.Equal(expectedResult, result);
        }

        [Fact]
        public void CreateFromSeedWhenContainerCanSatisfyWrappedRequestWillReturnCorrectResult()
        {
            // Arrange
            var anonymousSeed = new SeededRequest(typeof(object), new object());

            var expectedResult = new object();
            var container = new DelegatingSpecimenContext { OnResolve = r => expectedResult };

            var sut = new SeedIgnoringRelay();
            // Act
            var result = sut.Create(anonymousSeed, container);
            // Assert
            Assert.Equal(expectedResult, result);
        }

        [Fact]
        public void CreateFromSeedWillCorrectlyInvokeContainer()
        {
            // Arrange
            var sut = new SeedIgnoringRelay();
            var seededRequest = new SeededRequest(typeof(int), 1);

            var mockVerified = false;
            var containerMock = new DelegatingSpecimenContext();
            containerMock.OnResolve = r =>
            {
                Assert.Equal(typeof(int), r);
                mockVerified = true;
                return null;
            };
            // Act
            sut.Create(seededRequest, containerMock);
            // Assert
            Assert.True(mockVerified, "Mock verification");
        }
    }
}


text:
package org.apereo.cas.web.view;

import org.apereo.cas.configuration.CasConfigurationProperties;

import lombok.val;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.autoconfigure.RefreshAutoConfiguration;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockServletContext;
import org.springframework.webflow.context.ExternalContextHolder;
import org.springframework.webflow.context.servlet.ServletExternalContext;
import org.thymeleaf.IEngineConfiguration;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map;

import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;

/**
 * This is {@link ThemeFileTemplateResolverTests}.
 *
 * @author Misagh Moayyed
 * @since 6.2.0
 */
@SpringBootTest(classes = {
    RefreshAutoConfiguration.class,
    ThymeleafAutoConfiguration.class
})
@EnableConfigurationProperties(CasConfigurationProperties.class)
@Tag("Web")
public class ThemeFileTemplateResolverTests {

    @Autowired
    private CasConfigurationProperties casProperties;

    @Test
    public void verifyOperationByRequestAttribute() throws Exception {
        val request = new MockHttpServletRequest();
        val paramName = casProperties.getTheme().getParamName();
        request.setAttribute(paramName, "test");
        val mock = new ServletExternalContext(new MockServletContext(), request, new MockHttpServletResponse());
        ExternalContextHolder.setExternalContext(mock);
        verifyThemeFile();
    }

    @Test
    public void verifyOperationBySessionAttribute() throws Exception {
        val request = new MockHttpServletRequest();
        val paramName = casProperties.getTheme().getParamName();
        request.getSession(true).setAttribute(paramName, "test");
        val mock = new ServletExternalContext(new MockServletContext(), request, new MockHttpServletResponse());
        ExternalContextHolder.setExternalContext(mock);
        verifyThemeFile();
    }

    @Test
    public void verifyOperationByDefaultValue() throws Exception {
        casProperties.getTheme().setDefaultThemeName("test");
        verifyThemeFile();
    }

    private void verifyThemeFile() throws IOException {
        val themeDir = new File(FileUtils.getTempDirectory(), "test");
        if (!themeDir.exists() && !themeDir.mkdir()) {
            fail("Unable to create directory " + themeDir);
        }
        val path = new File(themeDir, "casLoginView.html");
        FileUtils.write(path, "<html><html>", StandardCharsets.UTF_8);

        val resolver = new ThemeFileTemplateResolver(casProperties);
        resolver.setSuffix(".html");
        resolver.setCheckExistence(true);
        resolver.setPrefix(FileUtils.getTempDirectoryPath() + "/%s/");
        val view = resolver.resolveTemplate(mock(IEngineConfiguration.class), StringUtils.EMPTY, "casLoginView", Map.of());
        assertNotNull(view);
    }
}


text:
<?php

namespace Phpug\Acl;

class RoleManager
{
    /**
     * @var \OrgHeiglHybridAuth\UserTokenInterface $user
     */
    protected $user = null;

    /**
     * @var array $admins
     */
    protected $admins = array();

    /**
     * The default role
     *
     * @var string $defaultRole
     */
    protected $defaultRole = 'guest';

    /**
     * The role to be used for logged in users
     *
     * @var string $loggedInRole
     */
    protected $loggedInRole = 'member';

    /**
     * The role for admin-users
     *
     * @var string $adminRole
     */
    protected $adminRole = 'admin';

    /**
     * Set the current user
     *
     * @param \OrgHeiglHybridAuth\UserTokenInterface $user
     *
     * @return RoleManager
     */
    public function setUserToken(\OrgHeiglHybridAuth\UserTokenInterface $user)
    {
        $this->user = $user;

        return $this;
    }

    /**
     * Set the default role
     *
     * @param string $defaultRole
     */
    public function setDefaultRole($defaultRole)
    {
        $this->defaultRole = $defaultRole;

        return $this;
    }

    /**
     * Set the role for logged in users
     *
     * @param string $role
     *
     * @return RoleManager
     */
    public function setLoggedInRole($role)
    {
        $this->loggedInRole = $role;

        return $this;
    }

    /**
     * Set the rolename for admin users
     *
     * @param string $role
     *
     * @return RoleManager
     */
    public function setAdminRole($role)
    {
        $this->adminRole = $role;

        return $this;
    }

    /**
     * Set the Admin-users
     * The given array has to contain the service-name as key and an array with
     * usernames for that service as value
     *
     * @param array $admins
     *
     * @return RoleManager
     */
    public function setAdmins(array $array)
    {
        $this->admins = $array;

        return $this;
    }

    /**
     * Get the role of the currently set user
     *
     * @return string
     */
    public function getRole()
    {
        if (! $this->user->isAuthenticated()) {
            return $this->defaultRole;
        }

        if (! array_key_Exists($this->user->getService(), $this->admins)) {
            return $this->loggedInRole;
        }

        if (! in_array($this->user->getName(), $this->admins[$this->user->getService()])) {
            return $this->loggedInRole;
        }

        return $this->adminRole;
    }

    /**
     * Magic method to return the role.
     *
     * @return string
     */
    public function __toString()
    {
        return $this->getRole();
    }
}


text:
<?php

// redirect direct page urls to anchors
if (!is_frontpage() and get_format() == "html") {
    $url = ModuleHelper::getBaseUrl("/?jumpto=" . get_slug());
    Request::redirect($url);
}


text:
package org.cyclops.integrateddynamics.api.network;

import org.cyclops.cyclopscore.datastructure.DimPos;

/**
 * A network element that exists at a certain position.
 * @author rubensworks
 */
public interface IPositionedNetworkElement extends INetworkElement {

    public DimPos getPosition();

}


text:
var path = require('path'),
    express = require('express'),
    routes = require(__dirname + '/app/routes.js'),
    app = express(),
    port = (process.env.PORT || 3000),
    WebSocketServer = require("ws").Server,

// Grab environment variables specified in Procfile or as Heroku config vars
    username = process.env.USERNAME,
    password = process.env.PASSWORD,
    env = process.env.NODE_ENV || 'development';

// Authenticate against the environment-provided credentials, if running
// the app in production (Heroku, effectively)
// if (env === 'production') {
//   if (!username || !password) {
//     console.log('Username or password is not set, exiting.');
//     process.exit(1);
//   }
//   app.use(express.basicAuth(username, password));
// }

// Application settings
app.engine('html', require(__dirname + '/lib/template-engine.js').__express);
app.set('view engine', 'html');
app.set('vendorViews', __dirname + '/govuk_modules/govuk_template/views/layouts');
app.set('views', __dirname + '/app/views');

// Middleware to serve static assets
app.use('/public', express.static(__dirname + '/public'));
app.use('/public', express.static(__dirname + '/govuk_modules/govuk_template/assets'));
app.use('/public', express.static(__dirname + '/govuk_modules/govuk_frontend_toolkit'));

app.use(express.favicon(path.join(__dirname, 'govuk_modules', 'govuk_template', 'assets', 'images','favicon.ico')));

// send assetPath to all views
app.use(function (req, res, next) {
  res.locals({'assetPath': '/public/'});
  next();
});

// routes (found in app/routes.js)

routes.bind(app);

// auto render any view that exists

app.get(/^\/([^.]+)$/, function (req, res) {

	var path = (req.params[0]);

	res.render(path, function(err, html) {
		if (err) {
			console.log(err);
			res.send(404);
		} else {
			res.end(html);
		}
	});

});

// start the app

var server = app.listen(port);

var wss = new WebSocketServer({ server: server });

    wss.on("connection", function(ws) {

      ws.on("message", function incoming(message) {
        console.log('received: %s', message);
        wss.clients.forEach(function each(client) {
          client.send(message);
        });
      });

      //var id = ws.send(JSON.stringify(new Date()), function() {  })

      console.log("websocket connection open")

      ws.on("close", function() {
        console.log("websocket connection close")
        //clearInterval(id)
      })
    });

console.log('');
console.log('Listening on port ' + port);
console.log('');


text:
<?php

class Google_Service_Apigee_GoogleCloudApigeeV1ListAppsResponse extends Google_Collection
{
  protected $collection_key = 'app';
  protected $appType = 'Google_Service_Apigee_GoogleCloudApigeeV1App';
  protected $appDataType = 'array';

  /**
   * @param Google_Service_Apigee_GoogleCloudApigeeV1App[]
   */
  public function setApp($app)
  {
    $this->app = $app;
  }
  /**
   * @return Google_Service_Apigee_GoogleCloudApigeeV1App[]
   */
  public function getApp()
  {
    return $this->app;
  }
}


text:
// Copyright (c) 2015 Google Inc. All rights reserved.
//
// 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.

import AxiomError from 'axiom/core/error';
import AxiomEvent from 'axiom/core/event';
import Ephemeral from 'axiom/core/ephemeral';
import Stdio from 'axiom/fs/stdio';
import NestedStdio from 'axiom/fs/nested_stdio';

import Arguments from 'axiom/fs/arguments';
import Path from 'axiom/fs/path';
import TTYState from 'axiom/fs/tty_state';

/** @typedef FileSystem$$module$axiom$fs$base$file_system */
var FileSystem;

/** @typedef FileSystemManager$$module$axiom$fs$base$file_system_manager */
var FileSystemManager;

/** @typedef OpenContext$$module$axiom$fs$base$open_context */
var OpenContext;

/** @typedef OpenMode$$module$axiom$fs$open_mode */
var OpenMode;

/** @typedef ReadableStream$$module$axiom$fs$stream$readable_stream */
var ReadableStream;

/** @typedef {{name: string, value: *}} */
var Signal;

/** @typedef WritableStream$$module$axiom$fs$stream$writable_stream */
var WritableStream;

/**
 * @constructor @extends {Ephemeral<*>}
 *
 * An Ephemeral that represents a running executable on a FileSystem.
 *
 * You should only create an ExecuteContext by calling an instance of
 * FileSystem..createExecuteContext(...).
 *
 * @param {!FileSystem} fileSystem The parent file system.
 * @param {!Stdio} stdio
 * @param {Path} path
 * @param {Arguments} args
 */
export var ExecuteContext = function(fileSystem, stdio, path, args) {
  Ephemeral.call(this);

  if (!args || !(args instanceof Arguments))
    throw new AxiomError.Missing('arguments');

  /**
   * @type {!FileSystem} Parent file system.
   */
  this.fileSystem = fileSystem;

  /**
   * @type {!FileSystemManager} Parent file system.
   */
  this.fileSystemManager = fileSystem.fileSystemManager;

  /**
   * @type {Path} The path we're supposed to execute.
   */
  this.path = path;

  /**
   * @type {Arguments} The argument to pass to the executable.
   */
  this.args = args;

  // If the parent file system is closed, we close too.
  this.dependsOn(this.fileSystem);

  /**
   * The ExecuteContext we're currently calling out to, if any.
   *
   * See setCallee().
   *
   * @type {ExecuteContext}
   */
  this.callee = null;

  /** @type {!Stdio} */
  this.stdio = stdio;
  /** @type {!ReadableStream} */
  this.stdin = stdio.stdin;
  /** @type {!WritableStream} */
  this.stdout = stdio.stdout;
  /** @type {!WritableStream} */
  this.stderr = stdio.stderr;
  /** @type {!ReadableStream} */
  this.signal = stdio.signal;
  /** @type {!ReadableStream} */
  this.ttyin = stdio.ttyin;
  /** @type {!WritableStream} */
  this.ttyout = stdio.ttyout;

  /** @type {!AxiomEvent} */
  this.onTTYRequest = new AxiomEvent();

  /**
   * The environtment variables for this execute context.
   * @private @type {Object<string, *>}
   */
  this.env_ = {};

  /**
   * The tty state for this execute context.
   * @private @type {!TTYState}
   */
  this.tty_ = new TTYState();
};

export default ExecuteContext;

ExecuteContext.prototype = Object.create(Ephemeral.prototype);

/**
 * @param {string} name
 * @param {*=} opt_defaultValue
 * @return {?}
 */
ExecuteContext.prototype.getArg = function (name, opt_defaultValue) {
  return this.args.getValue(name, opt_defaultValue);
};

/**
 * @return {string}
 */
ExecuteContext.prototype.getPwd = function() {
  return this.getEnv('$PWD',
                     this.fileSystemManager.defaultFileSystem.rootPath.spec);
};

/**
 * Initiate the execute.
 *
 * Returns a promise that completes when the execution is complete.
 *
 * @return {!Promise<*>}
 */
ExecuteContext.prototype.execute = function() {
  this.assertEphemeral('Wait');
  return this.ephemeralPromise;
};

/**
 * Set the given ExecuteContext as the callee for this instance.
 *
 * When calling another executable, incoming calls and outbound events are
 * wired up to the caller as appropriate.  This instance will not receive
 * the stdio-like events while a call is in progress.  The onSignal event,
 * however, is delivered to this instance even when a call is in progress.
 *
 * If the callee is closed, events are rerouted back to this instance and the
 * callee instance property is set to null.
 *
 * @param {ExecuteContext} executeContext
 * @return {void}
 */
ExecuteContext.prototype.setCallee = function(executeContext) {
  if (this.callee)
    throw new AxiomError.Runtime('Call in progress');

  this.callee = executeContext;
  var previousInterruptChar = this.tty_.getInterrupt();

  var nestedStdio = new NestedStdio(this.callee.stdio);
  this.callee.setStdio(nestedStdio);

  var onClose = function() {
    nestedStdio.close();
    this.callee.setStdio(nestedStdio.parentStdio);
    this.callee.onTTYRequest.removeListener(this.onTTYRequest.fire);
    this.callee = null;

    if (this.tty_.getInterrupt() != previousInterruptChar)
      this.requestTTY({interrupt: previousInterruptChar});
  }.bind(this);

  this.callee.onClose.listenOnce(onClose);
  this.callee.onTTYRequest.addListener(this.onTTYRequest.fire);
  this.callee.setEnvs(this.env_);
  this.callee.setTTY_(this.tty_);
};

/**
 * @param {!Stdio} stdio
 * @return {void}
 */
ExecuteContext.prototype.setStdio = function(stdio) {
  this.stdio = stdio;
  this.stdin = stdio.stdin;
  this.stdout = stdio.stdout;
  this.stderr = stdio.stderr;
  this.signal = stdio.signal;
  this.ttyin = stdio.ttyin;
  this.ttyout = stdio.ttyout;
};

/**
 * Utility method to construct a new ExecuteContext, set it as the callee, and
 * execute it with the given path and arg.
 *
 * @param {!FileSystemManager} fileSystemManager
 * @param {!Path} path
 * @param {Object} arg
 * @return {!Promise<*>}
 */
ExecuteContext.prototype.call = function(fileSystemManager, path, arg) {
  return fileSystemManager.createExecuteContext(path, this.stdio, arg).then(
    function(cx) {
      this.setCallee(cx);
      return cx.execute();
    }.bind(this));
};

/**
 * Return a copy of the internal tty state.
 * @return {TTYState}
 */
ExecuteContext.prototype.getTTY = function() {
  return this.tty_.clone();
};

/**
 * Set the authoritative state of the tty.
 *
 * This should only be invoked in the direction of tty->executable.  Calls in
 * the reverse direction will only affect this instance and those derived (via
 * setCallee) from it, and will be overwritten the next time the authoritative
 * state changes.
 *
 * Executables should use requestTTY to request changes to the authoritative
 * state.
 *
 * @private
 * @param {TTYState|Object} tty
 * @return {void}
 */
ExecuteContext.prototype.setTTY_ = function(tty) {
  this.assertEphemeral('Wait', 'Ready');

  this.tty_.copyFrom(tty);

  if (this.callee)
    this.callee.setTTY_(tty);
};

/**
 * @private
 *
 * Return a by-value copy of the given value.
 *
 * @param {*} v
 * @return {*}
 */
ExecuteContext.prototype.copyValue_ = function(v) {
  if (v instanceof Object)
    return JSON.parse(JSON.stringify(v));

  return v;
};

/**
 * Request a change to the controlling tty.
 *
 * At the moment only the 'interrupt' property can be changed.
 *
 * @param {Object} tty An object containing a changeable property of the
 *   tty.
 * @return {void}
 */
ExecuteContext.prototype.requestTTY = function(tty) {
  this.assertEphemeral('Ready');

  if (typeof tty.interrupt == 'string')
    this.onTTYRequest.fire({interrupt: tty.interrupt});
};

/**
 * Get a copy of the current environment variables.
 *
 * @return {*}
 */
ExecuteContext.prototype.getEnvs = function() {
  return this.copyValue_(this.env_);
};

/**
 * Get the value of the given environment variable, or the provided
 * defaultValue if it is not set.
 *
 * @param {string} name
 * @param {*=} opt_defaultValue
 * return {*}
 */
ExecuteContext.prototype.getEnv = function(name, opt_defaultValue) {
  if (this.env_.hasOwnProperty(name))
    return this.copyValue_(this.env_[name]);

  return opt_defaultValue;
};

/**
 * Overwrite the current environment.
 *
 * @param {Object} env
 * @return {void}
 */
ExecuteContext.prototype.setEnvs = function(env) {
  this.assertEphemeral('Wait', 'Ready');
  for (var key in env) {
    this.setEnv(key, this.copyValue_(env[key]));
  }
};

/**
 * Set the given environment variable.
 *
 * @param {string} name
 * @param {*} value
 * @return {void}
 */
ExecuteContext.prototype.setEnv = function(name, value) {
  this.assertEphemeral('Wait', 'Ready');
  this.env_[name] = this.copyValue_(value);
};

/**
 * Remove the given environment variable.
 *
 * @param {string} name
 * @return {void}
 */
ExecuteContext.prototype.delEnv = function(name) {
  this.assertEphemeral('Wait', 'Ready');
  delete this.env_[name];
};

/**
 * Create a new execute context using the fs.FileSystem for this execute
 * context, bound to the lifetime of this context.
 *
 * @param {!Path} path
 * @param {Object} arg
 * @return {Promise<ExecuteContext>}
 */
ExecuteContext.prototype.createExecuteContext = function(path, arg) {
  return this.fileSystemManager.createExecuteContext(
      path, this.stdio, arg).then(
    function(cx) {
      cx.dependsOn(this);
      return cx;
    }.bind(this));
};

/**
 * Create a new open context using the fs.FileSystem for this execute
 * context, bound to the lifetime of this context.
 *
 * @param {Path} path
 * @param {OpenMode} mode
 * @return {Promise<OpenContext>}
 */
ExecuteContext.prototype.createOpenContext = function(path, mode) {
  return this.fileSystemManager.createOpenContext(path, mode).then(
    function(cx) {
      cx.dependsOn(this);
      return cx;
    }.bind(this));
};

/**
 * Dispatch a signal to this execution context and callee.
 *
 * @param {!Signal} signal
 * @return {void}
 */
ExecuteContext.prototype.dispatchSignal = function(signal) {
  if (signal.name === 'tty-change') {
    this.setTTY_(/** @type {Object} */(signal.value));
    return;
  }

  if (signal.name === 'interrupt') {
    // Interrupt goes to the deepest callee
    if (this.callee) {
      this.callee.dispatchSignal(signal);
      return;
    }

    this.closeError(new AxiomError.Interrupt());
    return;
  }
};


text:
    <md-card class="signin-card signin-basic">
        <form novalidate [formGroup]="form" (ngSubmit)="f.form.valid && register(form.value)" #f="ngForm" >
            <md-toolbar color="primary">Register</md-toolbar>
            <md-card-content>

                        <md-input-container style="width: 100%">
                            <input mdInput placeholder="First Name" formControlName="firstName"  name="firstName" required>
                        </md-input-container>

First Name is required

                        <md-input-container style="width: 100%">
                            <input mdInput placeholder="Last Name" formControlName="lastName"  name="lastName" required>
                        </md-input-container>

Last Name is required

                        <md-input-container style="width: 100%">
                            <input mdInput class="form-control" type="text" formControlName="username" placeholder="Username"  name="username" required >
                        </md-input-container>

Username is required

                        <md-input-container style="width: 100%">
                            <input mdInput class="form-control" type="text" formControlName="email" placeholder="Email"  name="email" required >
                        </md-input-container>

Email is required

                        <md-input-container style="width: 100%">
                            <input mdInput class="form-control" type="password" formControlName="password" placeholder="Password"  name="password" required >
                        </md-input-container>

Password is required

          </md-card-content>
          <md-card-actions align="center">
            <button md-raised-button color="primary"  type="submit" [disabled]="loading || !f.form.valid" >Register</button>
            Cancel
          </md-card-actions>

            {{errMessage}}

        </form>
    </md-card>


text:
package com.mjiayou.trecore.net;

import android.text.TextUtils;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.mjiayou.trecore.common.Configs;
import com.mjiayou.trecore.util.ConvertUtil;
import com.mjiayou.trecorelib.bean.TCResponse;
import com.mjiayou.trecorelib.helper.GsonHelper;
import com.mjiayou.trecorelib.util.LogUtil;

import java.io.UnsupportedEncodingException;
import java.util.Map;

public class GsonRequest<T extends TCResponse> extends Request<T> {

    private RequestEntity mRequestEntity;
    private final Class<T> mClazz;
    private final Listener<T> mResponseListener;
    private final Gson mGson;

    /**
     * 构造函数
     */
    public GsonRequest(RequestEntity requestEntity, ErrorListener errorListener, Class<T> clazz, Listener<T> responseListener) {
        super(requestEntity.getMethodCode(), requestEntity.getUrl(), errorListener);
        this.mRequestEntity = requestEntity;
        this.mClazz = clazz;
        this.mResponseListener = responseListener;
        this.mGson = GsonHelper.get();
    }

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        return mRequestEntity.getHeaders();
    }

    @Override
    public byte[] getBody() throws AuthFailureError {
        if (!TextUtils.isEmpty(mRequestEntity.getRequestBody())) {
            return mRequestEntity.getRequestBody().getBytes();
        }
        return super.getBody();
    }

    @Override
    protected Map<String, String> getParams() throws AuthFailureError {
        return mRequestEntity.getParams();
    }

    @Override
    protected Response<T> parseNetworkResponse(NetworkResponse response) {
        try {
            String responseString;
            String encoding = response.headers.get("Content-Encoding");
            if (!TextUtils.isEmpty(encoding) && encoding.equals("gzip")) {
                responseString = ConvertUtil.parseString(response.data);
            } else {
                responseString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
            }
            T result = mGson.fromJson(responseString, mClazz);
            String responseInfo = "request_info | " + "\n" +
                    "response_data_string -> " + responseString + "\n" +
                    "response_data_object -> " + mGson.toJson(result) + "\n";
            LogUtil.i(Configs.TAG_VOLLEY, responseInfo);
            return Response.success(result, HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return Response.error(new ParseError(e));
        } catch (JsonSyntaxException e) {
            e.printStackTrace();
            return Response.error(new ParseError(e));
        }
    }

    @Override
    protected void deliverResponse(T response) {
        mResponseListener.onResponse(response);
    }
}


text: - Fixed an issue with XDM.


text:
/* TESTING */
var assign = require("react/lib/Object.assign");
var jest = require("jest-cli");
var chalk = require("chalk");

module.exports = function (callback) {
  var onComplete = function (result) {
    if (result) {
    } else {
      console.log(chalk.bgRed("!!! Jest tests failed! You should fix them soon. !!!"));
    }
    callback();
  }
  jest.runCLI({}, __dirname + "/../..", onComplete);
};


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">
    <TextView
        android:text="searching book owners"
        android:textSize="24sp"
        android:background="@color/colorPrimary"
        android:textColor="@color/white"
        android:padding="10dp"
        android:gravity="center"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <ProgressBar
        android:id="@+id/loading"
        style="?android:attr/progressBarStyle"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:visibility="gone" />

    <ListView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />

</LinearLayout>


text:
package org.editorconfig.configmanagement;

import com.intellij.application.options.CodeStyle;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectLocator;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.encoding.FileEncodingProvider;
import com.intellij.util.ObjectUtils;
import com.intellij.util.containers.ContainerUtil;
import org.editorconfig.Utils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Map;

public class ConfigEncodingManager implements FileEncodingProvider {
  // Handles the following EditorConfig settings:
  public static final String charsetKey = "charset";

  public static final String UTF8_BOM_ENCODING = "utf-8-bom";
  public static final String UTF8_ENCODING     = "utf-8";

  // @formatter:off
  private static final Map<String, Charset> encodingMap =
      Map.of(
        "latin1",          StandardCharsets.ISO_8859_1,
        UTF8_ENCODING,     StandardCharsets.UTF_8,
        UTF8_BOM_ENCODING, StandardCharsets.UTF_8,
        "utf-16be",        StandardCharsets.UTF_16BE,
        "utf-16le",        StandardCharsets.UTF_16LE);
  // @formatter:on

  @Override
  public @Nullable Charset getEncoding(@NotNull VirtualFile virtualFile) {
    Project project = ProjectLocator.getInstance().guessProjectForFile(virtualFile);
    return
      project != null && isEnabledFor(project, virtualFile) ?
      EditorConfigEncodingCache.getInstance().getCachedEncoding(virtualFile) : null;
  }

  @Nullable
  public static String toString(@NotNull Charset charset, boolean useBom) {
    if (charset == StandardCharsets.UTF_8) {
      return useBom ? UTF8_BOM_ENCODING : UTF8_ENCODING;
    }
    return ObjectUtils.doIfNotNull(
      ContainerUtil.find(encodingMap.entrySet(), e -> e.getValue() == charset), entry -> entry.getKey());
  }

  @Nullable
  public static Charset toCharset(@NotNull String str) {
    return encodingMap.get(str);
  }

  static boolean isEnabledFor(@NotNull Project project, @NotNull VirtualFile virtualFile) {
    return Utils.isEnabled(CodeStyle.getSettings(project)) &&
           Utils.isApplicableTo(virtualFile) && !Utils.isEditorConfigFile(virtualFile);
  }
}


text:
AnimatedFlowLayout
==================

A demonstration of animated UICollectionViewFlowLayout bling


text:
package org.apache.jackrabbit.util;

import javax.jcr.Item;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.Property;
import javax.jcr.PropertyIterator;
import javax.jcr.RepositoryException;
import javax.jcr.util.TraversingItemVisitor;

import org.apache.jackrabbit.commons.ItemNameMatcher;
import org.apache.jackrabbit.commons.iterator.NodeIteratorAdapter;
import org.apache.jackrabbit.commons.iterator.PropertyIteratorAdapter;

import java.util.ArrayList;
import java.util.Collection;

/**
 * ChildrenCollectorFilter is a utility class
 * which can be used to 'collect' child items of a
 * node whose names match a certain pattern. It implements the
 * ItemVisitor interface.
 */
public class ChildrenCollectorFilter extends TraversingItemVisitor.Default {
    static final char WILDCARD_CHAR = '*';
    static final String OR = "|";

    private final Collection<Item> children;
    private final boolean collectNodes;
    private final boolean collectProperties;
    // namePattern and nameGlobs fields are used mutually exclusive
    private final String namePattern;
    private final String[] nameGlobs;

    /**
     * Constructs a ChildrenCollectorFilter
     *
     * @param namePattern       the pattern which should be applied to the names
     *                          of the children
     * @param children          where the matching children should be added
     * @param collectNodes      true, if child nodes should be collected; otherwise false
     * @param collectProperties true, if child properties should be collected; otherwise false
     * @param maxLevel          number of hierarchy levels to traverse
     *                          (e.g. 1 for direct children only, 2 for children and their children, and so on)
     */
    public ChildrenCollectorFilter(
            String namePattern, Collection<Item> children,
            boolean collectNodes, boolean collectProperties, int maxLevel) {
        super(false, maxLevel);
        this.namePattern = namePattern;
        nameGlobs = null;
        this.children = children;
        this.collectNodes = collectNodes;
        this.collectProperties = collectProperties;
    }

    /**
     * Constructs a ChildrenCollectorFilter
     *
     * @param nameGlobs         an array of globbing strings which should be
     *                          applied to the names of the children
     * @param children          where the matching children should be added
     * @param collectNodes      true, if child nodes should be collected; otherwise false
     * @param collectProperties true, if child properties should be collected; otherwise false
     * @param maxLevel          number of hierarchy levels to traverse
     *                          (e.g. 1 for direct children only, 2 for children and their children, and so on)
     */
    public ChildrenCollectorFilter(
            String[] nameGlobs, Collection<Item> children,
            boolean collectNodes, boolean collectProperties, int maxLevel) {
        super(false, maxLevel);
        this.nameGlobs = nameGlobs;
        namePattern = null;
        this.children = children;
        this.collectNodes = collectNodes;
        this.collectProperties = collectProperties;
    }

    public static NodeIterator collectChildNodes(
            Node node, String namePattern) throws RepositoryException {
        Collection<Item> nodes = new ArrayList<Item>();
        node.accept(new ChildrenCollectorFilter(
                namePattern, nodes, true, false, 1));
        return new NodeIteratorAdapter(nodes);
    }

    public static NodeIterator collectChildNodes(
            Node node, String[] nameGlobs) throws RepositoryException {
        Collection<Item> nodes = new ArrayList<Item>();
        node.accept(new ChildrenCollectorFilter(
                nameGlobs, nodes, true, false, 1));
        return new NodeIteratorAdapter(nodes);
    }

    public static PropertyIterator collectProperties(
            Node node, String namePattern) throws RepositoryException {
        Collection<Item> properties = new ArrayList<Item>();
        node.accept(new ChildrenCollectorFilter(
                namePattern, properties, false, true, 1));
        return new PropertyIteratorAdapter(properties);
    }

    public static PropertyIterator collectProperties(
            Node node, String[] nameGlobs) throws RepositoryException {
        Collection<Item> properties = new ArrayList<Item>();
        node.accept(new ChildrenCollectorFilter(
                nameGlobs, properties, false, true, 1));
        return new PropertyIteratorAdapter(properties);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void entering(Node node, int level)
            throws RepositoryException {
        if (level > 0 && collectNodes) {
            if (namePattern != null) {
                if (matches(node.getName(), namePattern)) {
                    children.add(node);
                }
            } else {
                if (matches(node.getName(), nameGlobs)) {
                    children.add(node);
                }
            }
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void entering(Property property, int level)
            throws RepositoryException {
        if (level > 0 && collectProperties) {
            if (namePattern != null) {
                if (matches(property.getName(), namePattern)) {
                    children.add(property);
                }
            } else {
                if (matches(property.getName(), nameGlobs)) {
                    children.add(property);
                }
            }
        }
    }

    /**
     * Same as {@link ItemNameMatcher#matches(String, String)}.
     *
     * @see javax.jcr.Node#getNodes(String)
     */
    public static boolean matches(String name, String pattern) {
        return ItemNameMatcher.matches(name, pattern);
    }

    /**
     * Same as {@link ItemNameMatcher#matches(String, String)}.
     *
     * @see javax.jcr.Node#getNodes(String)
     */
    public static boolean matches(String name, String[] nameGlobs) {
        return ItemNameMatcher.matches(name, nameGlobs);
    }
}


text:
package org.softwarewolf.gameserver.service;

import org.softwarewolf.gameserver.domain.User;
import org.softwarewolf.gameserver.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
public class CustomUserDetailsService implements UserDetailsService {
	@Autowired
	private UserRepository userRepo;

	@Override
	public UserDetails loadUserByUsername(String arg0)
			throws UsernameNotFoundException {

		User user = userRepo.findOneByUsername(arg0);

		return user;
	}

}


text:
===================================
Ubidots PHP API Client
===================================

The Ubidots PHP API Client makes calls to the `Ubidots Api <http://things.ubidots.com/api>`_.

Installation
------------

Install with Composer
---------------------
Ubidots for php is available for install with `Composer <https://github.com/composer/composer/>`_:

.. code-block:: json

    {
        "require": {
            "ubidots/ubidots": "dev-master"
        }
    }

Connecting to the API
----------------------

Before playing with the API you should connect to it using your private API key, which can be found `in your profile <http://app.ubidots.com/userdata/api/>`_.

If you don't have an account yet, you can `create one here <http://app.ubidots.com/accounts/signup/>`_.

Once you have your API key, you can connect to the API by creating an ApiClient instance. Let's assume your API key is: "7fj39fk3044045k89fbh34rsd9823jkfs8323". Then your code would look like this:

.. code-block:: php

	require 'vendor/autoload.php';

	$api = new Ubidots\ApiClient($apikey="7fj39fk3044045k89fbh34rsd9823jkfs8323");

Now you have an instance of ApiClient ("api") which can be used to connect to the Ubidots API.

Saving a new Value to a Variable
--------------------------------

Retrieve the variable you'd like the value to be saved to:

.. code-block:: php

    $my_variable = $api->get_variable('56799cf1231b28459f976417');

Given the instantiated variable, you can save a new value with the following line:

.. code-block:: php

    $new_value = $my_variable->save_value( json_encode(array('value'=>10)) );

You can also specify a timestamp (optional):

.. code-block:: php

    $new_value = $my_variable->save_value( array('value'=>10, 'timestamp'=>1376061804407) );

If no timestamp is specified, the API server will assign the current time to it. We think it's always better for you to specify the timestamp so the record reflects the exact time the value was captured, not the time it arrived to our servers.

Creating a Data Source
----------------------

As you might know by now, a data source represents a device that's generating time-series data.

This line creates a new data source:

.. code-block:: php

    $new_datasource = $api->create_datasource( array("name"=>"myNewDs", "tags"=>array("firstDs", "new"), "description"=>"any des") );

The 'name' key is required, but the 'tags' and 'description' keys are optional. This new data source can be used to track different variables, so let's create one.

Creating a Variable
--------------------

A variable is a time-series containing different values over time. Let's create one:

.. code-block:: php

    $my_variable = $new_datasource->create_variable( array("name"=>"myNewVar", "unit"=>"Nw") );

The 'name' and 'unit' keys are required.

Getting Values
--------------

To get the values of a variable, use the method get_values in an instance of the class Variable. This will return a values array.

If you only want the last N values call the method with the number of elements you want.

.. code-block:: php

    /*
     * Getting all the values from the server. Note that this could result in a
     * lot of requests, and potentially violate your requests per second limit.
     */
    $all_values = $new_variable->get_values();

    /* If you want just the last 100 values you can use: */
    $some_values = $new_variable->get_values(100);

Getting a group of Data Sources
--------------------------------

If you want to get all your data sources you can a method on the ApiClient instance directly. This method return a objects Datasource array.

.. code-block:: php

    /* Get all datasources */
    $all_datasources = $api->get_datasources();

    /* Get the last five created datasources */
    $some_datasources = $api->get_datasources(5);

Getting a specific Data Source
-------------------------------

Each data source is identified by an ID. A specific data source can be retrieved from the server using this ID.

For example, if a data source has the id 51c99cfdf91b28459f976414, it can be retrieved as follows:

.. code-block:: php

    $my_specific_datasource = $api->get_datasource('51c99cfdf91b28459f976414');

Getting a group of Variables from a Data source
------------------------------------------------

You can also retrieve some or all of the variables of a data source:

.. code-block:: php

    /* Get all variables */
    $all_variables =  $my_datasource->get_variables();

    /* Get last 10 variables */
    $some_variables =  $my_datasource->get_variables(10)

Getting a specific Variable
------------------------------

As with data sources, you can use your variable's ID to retrieve the details about it:

.. code-block:: php

    $my_specific_variable = $api->get_variable('56799cf1231b28459f976417');