text:
DEFINE_string(open_browser, "", "URL");
DEFINE_string(spawn_process, "", "path");

int main(int argc, char **argv) {
  InitGoogle(argv[0], &argc, &argv, false);
  if (!FLAGS_open_browser.empty()) {
    if (!mozc::Process::OpenBrowser(FLAGS_open_browser)) {
      LOG(INFO) << "Failed to open: " << FLAGS_open_browser;
    }
  }
  if (!FLAGS_spawn_process.empty()) {
    if (!mozc::Process::SpawnProcess(FLAGS_spawn_process, "")) {
      LOG(INFO) << "Failed to spawn: " << FLAGS_spawn_process;
    }
  }
  return 0;
}


text:
make test

valgrind --quiet --leak-check=yes ./test

make clean

redpajama_set_name: RedPajamaGithub


text:
package org.apache.camel.processor;

import java.util.concurrent.RejectedExecutionException;

import org.apache.camel.ContextTestSupport;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;

import static org.apache.camel.component.mock.MockEndpoint.expectsMessageCount;

public class CircuitBreakerLoadBalancerTest extends ContextTestSupport {

    private static class MyCustomException extends RuntimeException {

        private static final long serialVersionUID = 1L;
    }

    private MockEndpoint result;

    @Override
    protected void setUp() throws Exception {
        super.setUp();
        result = getMockEndpoint("mock:result");
    }

    protected RouteBuilder createRouteBuilder() {
        return new RouteBuilder() {
            public void configure() {
                from("direct:start").loadBalance()
                    .circuitBreaker(2, 1000L, MyCustomException.class)
                        .to("mock:result");
                from("direct:start-async").loadBalance()
                .circuitBreaker(2, 1000L, MyCustomException.class)
                    .threads(1).to("mock:result");
            }
        };
    }

    public void testClosedCircuitPassesMessagesSync() throws Exception {
        String endpoint = "direct:start";
        closedCircuitPassesMessages(endpoint);
    }

    public void testClosedCircuitPassesMessagesAsync() throws Exception {
        String endpoint = "direct:start-async";
        closedCircuitPassesMessages(endpoint);
    }

    private void closedCircuitPassesMessages(String endpoint) throws InterruptedException, Exception {
        expectsMessageCount(3, result);
        sendMessage(endpoint, "message one");
        sendMessage(endpoint, "message two");
        sendMessage(endpoint, "message three");
        assertMockEndpointsSatisfied();
    }

    public void testFailedMessagesOpenCircuitToPreventMessageThreeSync() throws Exception {
        String endpoint = "direct:start";
        failedMessagesOpenCircuitToPreventMessageThree(endpoint);
    }

    public void testFailedMessagesOpenCircuitToPreventMessageThreeAsync() throws Exception {
        String endpoint = "direct:start-async";
        failedMessagesOpenCircuitToPreventMessageThree(endpoint);
    }

    private void failedMessagesOpenCircuitToPreventMessageThree(String endpoint) throws InterruptedException, Exception {
        expectsMessageCount(2, result);

        result.whenAnyExchangeReceived(new Processor() {
            @Override
            public void process(Exchange exchange) throws Exception {
                exchange.setException(new MyCustomException());
            }
        });

        Exchange exchangeOne = sendMessage(endpoint, "message one");
        Exchange exchangeTwo = sendMessage(endpoint, "message two");
        Exchange exchangeThree = sendMessage(endpoint, "message three");
        assertMockEndpointsSatisfied();

        assertTrue(exchangeOne.getException() instanceof MyCustomException);
        assertTrue(exchangeTwo.getException() instanceof MyCustomException);
        assertTrue(exchangeThree.getException() instanceof RejectedExecutionException);
    }

    public void testHalfOpenAfterTimeoutSync() throws Exception {
        String endpoint = "direct:start";
        halfOpenAfterTimeout(endpoint);
    }

    public void testHalfOpenAfterTimeoutAsync() throws Exception {
        String endpoint = "direct:start-async";
        halfOpenAfterTimeout(endpoint);
    }

    private void halfOpenAfterTimeout(String endpoint) throws InterruptedException, Exception {
        expectsMessageCount(2, result);

        result.whenAnyExchangeReceived(new Processor() {
            @Override
            public void process(Exchange exchange) throws Exception {
                exchange.setException(new MyCustomException());
            }
        });

        Exchange exchangeOne = sendMessage(endpoint, "message one");
        Exchange exchangeTwo = sendMessage(endpoint, "message two");
        Exchange exchangeThree = sendMessage(endpoint, "message three");
        Exchange exchangeFour = sendMessage(endpoint, "message four");
        assertMockEndpointsSatisfied();
        Thread.sleep(1000);
        result.reset();
        result.whenAnyExchangeReceived(new Processor() {
            @Override
            public void process(Exchange exchange) throws Exception {
                exchange.setException(new MyCustomException());
            }
        });
        expectsMessageCount(1, result);
        Exchange exchangeFive = sendMessage(endpoint, "message five");
        Exchange exchangeSix = sendMessage(endpoint, "message six");
        assertMockEndpointsSatisfied();

        assertTrue(exchangeOne.getException() instanceof MyCustomException);
        assertTrue(exchangeTwo.getException() instanceof MyCustomException);
        assertTrue(exchangeThree.getException() instanceof RejectedExecutionException);
        assertTrue(exchangeFour.getException() instanceof RejectedExecutionException);
        assertTrue(exchangeFive.getException() instanceof MyCustomException);
        assertTrue(exchangeSix.getException() instanceof RejectedExecutionException);
    }

    public void testHalfOpenToCloseTransitionSync() throws Exception {
        String endpoint = "direct:start";
        halfOpenToCloseTransition(endpoint);
    }

    public void testHalfOpenToCloseTransitionAsync() throws Exception {
        String endpoint = "direct:start-async";
        halfOpenToCloseTransition(endpoint);
    }

    private void halfOpenToCloseTransition(String endpoint) throws Exception {
        expectsMessageCount(2, result);

        result.whenAnyExchangeReceived(new Processor() {
            @Override
            public void process(Exchange exchange) throws Exception {
                exchange.setException(new MyCustomException());
            }
        });

        Exchange exchangeOne = sendMessage(endpoint, "message one");
        Exchange exchangeTwo = sendMessage(endpoint, "message two");
        Exchange exchangeThree = sendMessage(endpoint, "message three");
        assertMockEndpointsSatisfied();
        Thread.sleep(1000);
        result.reset();

        expectsMessageCount(2, result);
        Exchange exchangeFour = sendMessage(endpoint, "message four");
        Exchange exchangeFive = sendMessage(endpoint, "message five");
        assertMockEndpointsSatisfied();

        assertTrue(exchangeOne.getException() instanceof MyCustomException);
        assertTrue(exchangeTwo.getException() instanceof MyCustomException);
        assertTrue(exchangeThree.getException() instanceof RejectedExecutionException);
        assertTrue(exchangeFour.getException() == null);
        assertTrue(exchangeFive.getException() == null);

    }

    public void testHalfOpenCircuitClosesAfterTimeoutSync() throws Exception {
        String endpoint = "direct:start";
        halfOpenCircuitClosesAfterTimeout(endpoint);
    }

    public void testHalfOpenCircuitClosesAfterTimeoutAsync() throws Exception {
        String endpoint = "direct:start-async";
        halfOpenCircuitClosesAfterTimeout(endpoint);
    }

    private void halfOpenCircuitClosesAfterTimeout(String endpoint) throws InterruptedException, Exception {
        expectsMessageCount(2, result);
        result.whenAnyExchangeReceived(new Processor() {
            @Override
            public void process(Exchange exchange) throws Exception {
                exchange.setException(new MyCustomException());
            }
        });

        sendMessage(endpoint, "message one");
        sendMessage(endpoint, "message two");
        sendMessage(endpoint, "message three");
        assertMockEndpointsSatisfied();

        result.reset();
        expectsMessageCount(1, result);

        Thread.sleep(1000);
        sendMessage(endpoint, "message four");
        assertMockEndpointsSatisfied();
    }

    protected Exchange sendMessage(final String endpoint, final Object body) throws Exception {
        return template.send(endpoint, new Processor() {
            @Override
            public void process(Exchange exchange) throws Exception {
                exchange.getIn().setBody(body);
            }
        });
    }
}


text:
from .base import Engine
from .interfaces import Connectable
from .interfaces import Dialect
from .. import event
from .. import exc

class ConnectionEvents(event.Events):
    """Available events for :class:`.Connectable`, which includes
    :class:`.Connection` and :class:`.Engine`.

    The methods here define the name of an event as well as the names of
    members that are passed to listener functions.

    An event listener can be associated with any :class:`.Connectable`
    class or instance, such as an :class:`.Engine`, e.g.::

        from sqlalchemy import event, create_engine

        def before_cursor_execute(conn, cursor, statement, parameters, context,
                                                        executemany):
            log.info("Received statement: %s", statement)

        engine = create_engine('postgresql://scott:tiger@localhost/test')
        event.listen(engine, "before_cursor_execute", before_cursor_execute)

    or with a specific :class:`.Connection`::

        with engine.begin() as conn:
            @event.listens_for(conn, 'before_cursor_execute')
            def before_cursor_execute(conn, cursor, statement, parameters,
                                            context, executemany):
                log.info("Received statement: %s", statement)

    When the methods are called with a `statement` parameter, such as in
    :meth:`.after_cursor_execute` or :meth:`.before_cursor_execute`,
    the statement is the exact SQL string that was prepared for transmission
    to the DBAPI ``cursor`` in the connection's :class:`.Dialect`.

    The :meth:`.before_execute` and :meth:`.before_cursor_execute`
    events can also be established with the ``retval=True`` flag, which
    allows modification of the statement and parameters to be sent
    to the database.  The :meth:`.before_cursor_execute` event is
    particularly useful here to add ad-hoc string transformations, such
    as comments, to all executions::

        from sqlalchemy.engine import Engine
        from sqlalchemy import event

        @event.listens_for(Engine, "before_cursor_execute", retval=True)
        def comment_sql_calls(conn, cursor, statement, parameters,
                                            context, executemany):
            statement = statement + " -- some comment"
            return statement, parameters

    .. note:: :class:`.ConnectionEvents` can be established on any
       combination of :class:`.Engine`, :class:`.Connection`, as well
       as instances of each of those classes.  Events across all
       four scopes will fire off for a given instance of
       :class:`.Connection`.  However, for performance reasons, the
       :class:`.Connection` object determines at instantiation time
       whether or not its parent :class:`.Engine` has event listeners
       established.   Event listeners added to the :class:`.Engine`
       class or to an instance of :class:`.Engine` *after* the instantiation
       of a dependent :class:`.Connection` instance will usually
       *not* be available on that :class:`.Connection` instance.  The newly
       added listeners will instead take effect for :class:`.Connection`
       instances created subsequent to those event listeners being
       established on the parent :class:`.Engine` class or instance.

    :param retval=False: Applies to the :meth:`.before_execute` and
      :meth:`.before_cursor_execute` events only.  When True, the
      user-defined event function must have a return value, which
      is a tuple of parameters that replace the given statement
      and parameters.  See those methods for a description of
      specific return arguments.

    """

    _target_class_doc = "SomeEngine"
    _dispatch_target = Connectable

    @classmethod
    def _listen(cls, event_key, retval=False):
        target, identifier, fn = (
            event_key.dispatch_target,
            event_key.identifier,
            event_key._listen_fn,
        )

        target._has_events = True

        if not retval:
            if identifier == "before_execute":
                orig_fn = fn

                def wrap_before_execute(
                    conn, clauseelement, multiparams, params
                ):
                    orig_fn(conn, clauseelement, multiparams, params)
                    return clauseelement, multiparams, params

                fn = wrap_before_execute
            elif identifier == "before_cursor_execute":
                orig_fn = fn

                def wrap_before_cursor_execute(
                    conn, cursor, statement, parameters, context, executemany
                ):
                    orig_fn(
                        conn,
                        cursor,
                        statement,
                        parameters,
                        context,
                        executemany,
                    )
                    return statement, parameters

                fn = wrap_before_cursor_execute
        elif retval and identifier not in (
            "before_execute",
            "before_cursor_execute",
            "handle_error",
        ):
            raise exc.ArgumentError(
                "Only the 'before_execute', "
                "'before_cursor_execute' and 'handle_error' engine "
                "event listeners accept the 'retval=True' "
                "argument."
            )
        event_key.with_wrapper(fn).base_listen()

    def before_execute(self, conn, clauseelement, multiparams, params):
        """Intercept high level execute() events, receiving uncompiled
        SQL constructs and other objects prior to rendering into SQL.

        This event is good for debugging SQL compilation issues as well
        as early manipulation of the parameters being sent to the database,
        as the parameter lists will be in a consistent format here.

        This event can be optionally established with the ``retval=True``
        flag.  The ``clauseelement``, ``multiparams``, and ``params``
        arguments should be returned as a three-tuple in this case::

            @event.listens_for(Engine, "before_execute", retval=True)
            def before_execute(conn, clauseelement, multiparams, params):
                # do something with clauseelement, multiparams, params
                return clauseelement, multiparams, params

        :param conn: :class:`.Connection` object
        :param clauseelement: SQL expression construct, :class:`.Compiled`
         instance, or string statement passed to :meth:`.Connection.execute`.
        :param multiparams: Multiple parameter sets, a list of dictionaries.
        :param params: Single parameter set, a single dictionary.

        .. seealso::

            :meth:`.before_cursor_execute`

        """

    def after_execute(self, conn, clauseelement, multiparams, params, result):
        """Intercept high level execute() events after execute.

        :param conn: :class:`.Connection` object
        :param clauseelement: SQL expression construct, :class:`.Compiled`
         instance, or string statement passed to :meth:`.Connection.execute`.
        :param multiparams: Multiple parameter sets, a list of dictionaries.
        :param params: Single parameter set, a single dictionary.
        :param result: :class:`.ResultProxy` generated by the execution.

        """

    def before_cursor_execute(
        self, conn, cursor, statement, parameters, context, executemany
    ):
        """Intercept low-level cursor execute() events before execution,
        receiving the string SQL statement and DBAPI-specific parameter list to
        be invoked against a cursor.

        This event is a good choice for logging as well as late modifications
        to the SQL string.  It's less ideal for parameter modifications except
        for those which are specific to a target backend.

        This event can be optionally established with the ``retval=True``
        flag.  The ``statement`` and ``parameters`` arguments should be
        returned as a two-tuple in this case::

            @event.listens_for(Engine, "before_cursor_execute", retval=True)
            def before_cursor_execute(conn, cursor, statement,
                            parameters, context, executemany):
                # do something with statement, parameters
                return statement, parameters

        See the example at :class:`.ConnectionEvents`.

        :param conn: :class:`.Connection` object
        :param cursor: DBAPI cursor object
        :param statement: string SQL statement, as to be passed to the DBAPI
        :param parameters: Dictionary, tuple, or list of parameters being
         passed to the ``execute()`` or ``executemany()`` method of the
         DBAPI ``cursor``.  In some cases may be ``None``.
        :param context: :class:`.ExecutionContext` object in use.  May
         be ``None``.
        :param executemany: boolean, if ``True``, this is an ``executemany()``
         call, if ``False``, this is an ``execute()`` call.

        .. seealso::

            :meth:`.before_execute`

            :meth:`.after_cursor_execute`

        """

    def after_cursor_execute(
        self, conn, cursor, statement, parameters, context, executemany
    ):
        """Intercept low-level cursor execute() events after execution.

        :param conn: :class:`.Connection` object
        :param cursor: DBAPI cursor object.  Will have results pending
         if the statement was a SELECT, but these should not be consumed
         as they will be needed by the :class:`.ResultProxy`.
        :param statement: string SQL statement, as passed to the DBAPI
        :param parameters: Dictionary, tuple, or list of parameters being
         passed to the ``execute()`` or ``executemany()`` method of the
         DBAPI ``cursor``.  In some cases may be ``None``.
        :param context: :class:`.ExecutionContext` object in use.  May
         be ``None``.
        :param executemany: boolean, if ``True``, this is an ``executemany()``
         call, if ``False``, this is an ``execute()`` call.

        """

    def handle_error(self, exception_context):
        r"""Intercept all exceptions processed by the :class:`.Connection`.

        This includes all exceptions emitted by the DBAPI as well as
        within SQLAlchemy's statement invocation process, including
        encoding errors and other statement validation errors.  Other areas
        in which the event is invoked include transaction begin and end,
        result row fetching, cursor creation.

        Note that :meth:`.handle_error` may support new kinds of exceptions
        and new calling scenarios at *any time*.  Code which uses this
        event must expect new calling patterns to be present in minor
        releases.

        To support the wide variety of members that correspond to an exception,
        as well as to allow extensibility of the event without backwards
        incompatibility, the sole argument received is an instance of
        :class:`.ExceptionContext`.   This object contains data members
        representing detail about the exception.

        Use cases supported by this hook include:

        * read-only, low-level exception handling for logging and
          debugging purposes
        * exception re-writing
        * Establishing or disabling whether a connection or the owning
          connection pool is invalidated or expired in response to a
          specific exception.

        The hook is called while the cursor from the failed operation
        (if any) is still open and accessible.   Special cleanup operations
        can be called on this cursor; SQLAlchemy will attempt to close
        this cursor subsequent to this hook being invoked.  If the connection
        is in "autocommit" mode, the transaction also remains open within
        the scope of this hook; the rollback of the per-statement transaction
        also occurs after the hook is called.

        For the common case of detecting a "disconnect" situation which
        is not currently handled by the SQLAlchemy dialect, the
        :attr:`.ExceptionContext.is_disconnect` flag can be set to True which
        will cause the exception to be considered as a disconnect situation,
        which typically results in the connection pool being invalidated::

            @event.listens_for(Engine, "handle_error")
            def handle_exception(context):
                if isinstance(context.original_exception, pyodbc.Error):
                    for code in (
                        '08S01', '01002', '08003',
                        '08007', '08S02', '08001', 'HYT00', 'HY010'):

                        if code in str(context.original_exception):
                            context.is_disconnect = True

        A handler function has two options for replacing
        the SQLAlchemy-constructed exception into one that is user
        defined.   It can either raise this new exception directly, in
        which case all further event listeners are bypassed and the
        exception will be raised, after appropriate cleanup as taken
        place::

            @event.listens_for(Engine, "handle_error")
            def handle_exception(context):
                if isinstance(context.original_exception,
                    psycopg2.OperationalError) and \
                    "failed" in str(context.original_exception):
                    raise MySpecialException("failed operation")

        .. warning::  Because the :meth:`.ConnectionEvents.handle_error`
           event specifically provides for exceptions to be re-thrown as
           the ultimate exception raised by the failed statement,
           **stack traces will be misleading** if the user-defined event
           handler itself fails and throws an unexpected exception;
           the stack trace may not illustrate the actual code line that
           failed!  It is advised to code carefully here and use
           logging and/or inline debugging if unexpected exceptions are
           occurring.

        Alternatively, a "chained" style of event handling can be
        used, by configuring the handler with the ``retval=True``
        modifier and returning the new exception instance from the
        function.  In this case, event handling will continue onto the
        next handler.   The "chained" exception is available using
        :attr:`.ExceptionContext.chained_exception`::

            @event.listens_for(Engine, "handle_error", retval=True)
            def handle_exception(context):
                if context.chained_exception is not None and \
                    "special" in context.chained_exception.message:
                    return MySpecialException("failed",
                        cause=context.chained_exception)

        Handlers that return ``None`` may be used within the chain; when
        a handler returns ``None``, the previous exception instance,
        if any, is maintained as the current exception that is passed onto the
        next handler.

        When a custom exception is raised or returned, SQLAlchemy raises
        this new exception as-is, it is not wrapped by any SQLAlchemy
        object.  If the exception is not a subclass of
        :class:`sqlalchemy.exc.StatementError`,
        certain features may not be available; currently this includes
        the ORM's feature of adding a detail hint about "autoflush" to
        exceptions raised within the autoflush process.

        :param context: an :class:`.ExceptionContext` object.  See this
         class for details on all available members.

        .. versionadded:: 0.9.7 Added the
            :meth:`.ConnectionEvents.handle_error` hook.

        .. versionchanged:: 1.1 The :meth:`.handle_error` event will now
           receive all exceptions that inherit from ``BaseException``,
           including ``SystemExit`` and ``KeyboardInterrupt``.  The setting for
           :attr:`.ExceptionContext.is_disconnect` is ``True`` in this case and
           the default for
           :attr:`.ExceptionContext.invalidate_pool_on_disconnect` is
           ``False``.

        .. versionchanged:: 1.0.0 The :meth:`.handle_error` event is now
           invoked when an :class:`.Engine` fails during the initial
           call to :meth:`.Engine.connect`, as well as when a
           :class:`.Connection` object encounters an error during a
           reconnect operation.

        .. versionchanged:: 1.0.0 The :meth:`.handle_error` event is
           not fired off when a dialect makes use of the
           ``skip_user_error_events`` execution option.   This is used
           by dialects which intend to catch SQLAlchemy-specific exceptions
           within specific operations, such as when the MySQL dialect detects
           a table not present within the ``has_table()`` dialect method.
           Prior to 1.0.0, code which implements :meth:`.handle_error` needs
           to ensure that exceptions thrown in these scenarios are re-raised
           without modification.

        """

    def engine_connect(self, conn, branch):
        """Intercept the creation of a new :class:`.Connection`.

        This event is called typically as the direct result of calling
        the :meth:`.Engine.connect` method.

        It differs from the :meth:`.PoolEvents.connect` method, which
        refers to the actual connection to a database at the DBAPI level;
        a DBAPI connection may be pooled and reused for many operations.
        In contrast, this event refers only to the production of a higher level
        :class:`.Connection` wrapper around such a DBAPI connection.

        It also differs from the :meth:`.PoolEvents.checkout` event
        in that it is specific to the :class:`.Connection` object, not the
        DBAPI connection that :meth:`.PoolEvents.checkout` deals with, although
        this DBAPI connection is available here via the
        :attr:`.Connection.connection` attribute.  But note there can in fact
        be multiple :meth:`.PoolEvents.checkout` events within the lifespan
        of a single :class:`.Connection` object, if that :class:`.Connection`
        is invalidated and re-established.  There can also be multiple
        :class:`.Connection` objects generated for the same already-checked-out
        DBAPI connection, in the case that a "branch" of a :class:`.Connection`
        is produced.

        :param conn: :class:`.Connection` object.
        :param branch: if True, this is a "branch" of an existing
         :class:`.Connection`.  A branch is generated within the course
         of a statement execution to invoke supplemental statements, most
         typically to pre-execute a SELECT of a default value for the purposes
         of an INSERT statement.

        .. versionadded:: 0.9.0

        .. seealso::

            :ref:`pool_disconnects_pessimistic` - illustrates how to use
            :meth:`.ConnectionEvents.engine_connect`
            to transparently ensure pooled connections are connected to the
            database.

            :meth:`.PoolEvents.checkout` the lower-level pool checkout event
            for an individual DBAPI connection

            :meth:`.ConnectionEvents.set_connection_execution_options` - a copy
            of a :class:`.Connection` is also made when the
            :meth:`.Connection.execution_options` method is called.

        """

    def set_connection_execution_options(self, conn, opts):
        """Intercept when the :meth:`.Connection.execution_options`
        method is called.

        This method is called after the new :class:`.Connection` has been
        produced, with the newly updated execution options collection, but
        before the :class:`.Dialect` has acted upon any of those new options.

        Note that this method is not called when a new :class:`.Connection`
        is produced which is inheriting execution options from its parent
        :class:`.Engine`; to intercept this condition, use the
        :meth:`.ConnectionEvents.engine_connect` event.

        :param conn: The newly copied :class:`.Connection` object

        :param opts: dictionary of options that were passed to the
         :meth:`.Connection.execution_options` method.

        .. versionadded:: 0.9.0

        .. seealso::

            :meth:`.ConnectionEvents.set_engine_execution_options` - event
            which is called when :meth:`.Engine.execution_options` is called.

        """

    def set_engine_execution_options(self, engine, opts):
        """Intercept when the :meth:`.Engine.execution_options`
        method is called.

        The :meth:`.Engine.execution_options` method produces a shallow
        copy of the :class:`.Engine` which stores the new options.  That new
        :class:`.Engine` is passed here.   A particular application of this
        method is to add a :meth:`.ConnectionEvents.engine_connect` event
        handler to the given :class:`.Engine` which will perform some per-
        :class:`.Connection` task specific to these execution options.

        :param conn: The newly copied :class:`.Engine` object

        :param opts: dictionary of options that were passed to the
         :meth:`.Connection.execution_options` method.

        .. versionadded:: 0.9.0

        .. seealso::

            :meth:`.ConnectionEvents.set_connection_execution_options` - event
            which is called when :meth:`.Connection.execution_options` is
            called.

        """

    def engine_disposed(self, engine):
        """Intercept when the :meth:`.Engine.dispose` method is called.

        The :meth:`.Engine.dispose` method instructs the engine to
        "dispose" of it's connection pool (e.g. :class:`.Pool`), and
        replaces it with a new one.  Disposing of the old pool has the
        effect that existing checked-in connections are closed.  The new
        pool does not establish any new connections until it is first used.

        This event can be used to indicate that resources related to the
        :class:`.Engine` should also be cleaned up, keeping in mind that the
        :class:`.Engine` can still be used for new requests in which case
        it re-acquires connection resources.

        .. versionadded:: 1.0.5

        """

    def begin(self, conn):
        """Intercept begin() events.

        :param conn: :class:`.Connection` object

        """

    def rollback(self, conn):
        """Intercept rollback() events, as initiated by a
        :class:`.Transaction`.

        Note that the :class:`.Pool` also "auto-rolls back"
        a DBAPI connection upon checkin, if the ``reset_on_return``
        flag is set to its default value of ``'rollback'``.
        To intercept this
        rollback, use the :meth:`.PoolEvents.reset` hook.

        :param conn: :class:`.Connection` object

        .. seealso::

            :meth:`.PoolEvents.reset`

        """

    def commit(self, conn):
        """Intercept commit() events, as initiated by a
        :class:`.Transaction`.

        Note that the :class:`.Pool` may also "auto-commit"
        a DBAPI connection upon checkin, if the ``reset_on_return``
        flag is set to the value ``'commit'``.  To intercept this
        commit, use the :meth:`.PoolEvents.reset` hook.

        :param conn: :class:`.Connection` object
        """

    def savepoint(self, conn, name):
        """Intercept savepoint() events.

        :param conn: :class:`.Connection` object
        :param name: specified name used for the savepoint.

        """

    def rollback_savepoint(self, conn, name, context):
        """Intercept rollback_savepoint() events.

        :param conn: :class:`.Connection` object
        :param name: specified name used for the savepoint.
        :param context: :class:`.ExecutionContext` in use.  May be ``None``.

        """

    def release_savepoint(self, conn, name, context):
        """Intercept release_savepoint() events.

        :param conn: :class:`.Connection` object
        :param name: specified name used for the savepoint.
        :param context: :class:`.ExecutionContext` in use.  May be ``None``.

        """

    def begin_twophase(self, conn, xid):
        """Intercept begin_twophase() events.

        :param conn: :class:`.Connection` object
        :param xid: two-phase XID identifier

        """

    def prepare_twophase(self, conn, xid):
        """Intercept prepare_twophase() events.

        :param conn: :class:`.Connection` object
        :param xid: two-phase XID identifier
        """

    def rollback_twophase(self, conn, xid, is_prepared):
        """Intercept rollback_twophase() events.

        :param conn: :class:`.Connection` object
        :param xid: two-phase XID identifier
        :param is_prepared: boolean, indicates if
         :meth:`.TwoPhaseTransaction.prepare` was called.

        """

    def commit_twophase(self, conn, xid, is_prepared):
        """Intercept commit_twophase() events.

        :param conn: :class:`.Connection` object
        :param xid: two-phase XID identifier
        :param is_prepared: boolean, indicates if
         :meth:`.TwoPhaseTransaction.prepare` was called.

        """

class DialectEvents(event.Events):
    """event interface for execution-replacement functions.

    These events allow direct instrumentation and replacement
    of key dialect functions which interact with the DBAPI.

    .. note::

        :class:`.DialectEvents` hooks should be considered **semi-public**
        and experimental.
        These hooks are not for general use and are only for those situations
        where intricate re-statement of DBAPI mechanics must be injected onto
        an existing dialect.  For general-use statement-interception events,
        please use the :class:`.ConnectionEvents` interface.

    .. seealso::

        :meth:`.ConnectionEvents.before_cursor_execute`

        :meth:`.ConnectionEvents.before_execute`

        :meth:`.ConnectionEvents.after_cursor_execute`

        :meth:`.ConnectionEvents.after_execute`

    .. versionadded:: 0.9.4

    """

    _target_class_doc = "SomeEngine"
    _dispatch_target = Dialect

    @classmethod
    def _listen(cls, event_key, retval=False):
        target = event_key.dispatch_target

        target._has_events = True
        event_key.base_listen()

    @classmethod
    def _accept_with(cls, target):
        if isinstance(target, type):
            if issubclass(target, Engine):
                return Dialect
            elif issubclass(target, Dialect):
                return target
        elif isinstance(target, Engine):
            return target.dialect
        else:
            return target

    def do_connect(self, dialect, conn_rec, cargs, cparams):
        """Receive connection arguments before a connection is made.

        Return a DBAPI connection to halt further events from invoking;
        the returned connection will be used.

        Alternatively, the event can manipulate the cargs and/or cparams
        collections; cargs will always be a Python list that can be mutated
        in-place and cparams a Python dictionary.  Return None to
        allow control to pass to the next event handler and ultimately
        to allow the dialect to connect normally, given the updated
        arguments.

        .. versionadded:: 1.0.3

        """

    def do_executemany(self, cursor, statement, parameters, context):
        """Receive a cursor to have executemany() called.

        Return the value True to halt further events from invoking,
        and to indicate that the cursor execution has already taken
        place within the event handler.

        """

    def do_execute_no_params(self, cursor, statement, context):
        """Receive a cursor to have execute() with no parameters called.

        Return the value True to halt further events from invoking,
        and to indicate that the cursor execution has already taken
        place within the event handler.

        """

    def do_execute(self, cursor, statement, parameters, context):
        """Receive a cursor to have execute() called.

        Return the value True to halt further events from invoking,
        and to indicate that the cursor execution has already taken
        place within the event handler.

        """

    def do_setinputsizes(
        self, inputsizes, cursor, statement, parameters, context
    ):
        """Receive the setinputsizes dictionary for possible modification.

        This event is emitted in the case where the dialect makes use of the
        DBAPI ``cursor.setinputsizes()`` method which passes information about
        parameter binding for a particular statement.   The given
        ``inputsizes`` dictionary will contain :class:`.BindParameter` objects
        as keys, linked to DBAPI-specific type objects as values; for
        parameters that are not bound, they are added to the dictionary with
        ``None`` as the value, which means the parameter will not be included
        in the ultimate setinputsizes call.   The event may be used to inspect
        and/or log the datatypes that are being bound, as well as to modify the
        dictionary in place.  Parameters can be added, modified, or removed
        from this dictionary.   Callers will typically want to inspect the
        :attr:`.BindParameter.type` attribute of the given bind objects in
        order to make decisions about the DBAPI object.

        After the event, the ``inputsizes`` dictionary is converted into
        an appropriate datastructure to be passed to ``cursor.setinputsizes``;
        either a list for a positional bound parameter execution style,
        or a dictionary of string parameter keys to DBAPI type objects for
        a named bound parameter execution style.

        Most dialects **do not use** this method at all; the only built-in
        dialect which uses this hook is the cx_Oracle dialect.   The hook here
        is made available so as to allow customization of how datatypes are set
        up with the  cx_Oracle DBAPI.

        .. versionadded:: 1.2.9

        .. seealso::

            :ref:`cx_oracle_setinputsizes`

        """
        pass


text:
package implementations;

import core.board.Game;
import core.board.IState;
import core.board.LogGame;
import core.color.Color;
import core.table.Table;
import score.GameScore;
import api.GameExtView;
import api.GoAPI;
import api.Parser;

import java.util.function.Function;
import java.util.function.Supplier;

/**
 * Created by maxus on 15.04.16.
 */
abstract class Core {

	public final Fields fields;
	private final Parser<Integer> parser;

	public Core(int size) {
		this.fields = new Fields(size);
		this.parser = new Parser<>(fields::getField, size);
	}

	public abstract Color<Integer> makeColor();
	public Table<Integer, Integer> makeTable() {
		return new Table<>(fields.fields, fields::getAdjacency, makeColor(), makeColor());
	}
	public Game<Integer, Integer> makeGame() {
		return new Game<>(makeTable());
	}
	public Game<Integer, Integer> makeLogGame(Function<IState<Integer, Integer>, String> statelogger, Supplier<Boolean> loggingstate) {
		return new LogGame<>(makeTable(), statelogger, loggingstate);
	}
	public GameExtView<Integer> makeGameView() {
		return new GameExtView<>(makeGame(), parser, GameScore::getScore);
	}
	public GoAPI<GameExtView<Integer>> makeGameApi() {
		return new GoAPI<>(this::makeGameView);
	}

}


text:
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.container.plugin.classanalysis.sampleclasses;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.ImagingOpException;
import java.awt.image.Kernel;

/**
 * Input for class analysis tests.
 * @author Tony Vaagenes
 */
public interface Interface1 extends Interface2 {
    Image methodSignatureTest(Kernel kernel, BufferedImage image);
    int ignoreBasicTypes(float f) throws ImagingOpException;
    int[] ignoreArrayOfBasicTypes(int[][] l);
}


text:
div.alphabet {
	position: relative;
	display: table;
	width: 100%;
	margin-bottom: 1em;
}

div.alphabet span {
	display: table-cell;
	color: #3174c7;
	cursor: pointer;
	text-align: center;
	width: 3.5%
}

div.alphabet span:hover {
	text-decoration: underline;
}

div.alphabet span.active {
	color: black;
}

div.alphabet span.empty {
	color: red;
}

div.alphabetInfo {
	display: block;
	position: absolute;
	background-color: #111;
	border-radius: 3px;
	color: white;
	top: 2em;
	height: 1.8em;
	padding-top: 0.4em;
	text-align: center;
	z-index: 1;
}


text:
/*
 * ETextLineEncoder.hh
 *
 *  Created on: 2016-5-24
 *      Author: cxxjava@163.com
 */

#ifndef ETEXTLINEENCODER_HH_
#define ETEXTLINEENCODER_HH_

#include "./EProtocolEncoderAdapter.hh"

namespace efc {
namespace eio {

class ETextLineEncoder: public EProtocolEncoderAdapter {
public:
	virtual ~ETextLineEncoder();
	ETextLineEncoder(const char* crlf);

	/**
	 * {@inheritDoc}
	 */
	virtual void encode(sp<EIoSession>& session, sp<EObject>& message, sp<EProtocolEncoderOutput>& out) THROWS(EException);

private:
	es_string_t* crlf;
};

} /* namespace eio */
} /* namespace efc */
#endif /* ETEXTLINEENCODER_HH_ */


text:
'use strict';

const rewire = require('rewire');
const C = require('../chai');

const Cluster = rewire('./taskDefinitionManager');

/*global describe, it, expect, beforeEach, afterEach */
describe('taskDefinitionManager', () => {
});


text:
{-# LANGUAGE NamedFieldPuns    #-}
{-# LANGUAGE NoImplicitPrelude #-}

module System.Etc.Internal.Resolver.Cli.Plain (PlainConfigSpec, resolvePlainCli, resolvePlainCliPure) where

import           RIO
import qualified RIO.HashMap as HashMap
import qualified RIO.Text    as Text

import qualified Data.Aeson          as JSON
import qualified Options.Applicative as Opt
import           System.Environment  (getArgs, getProgName)

import           System.Etc.Internal.Resolver.Cli.Common
import qualified System.Etc.Internal.Spec.Types          as Spec
import           System.Etc.Internal.Types

--------------------------------------------------------------------------------

type PlainConfigSpec =
  Spec.ConfigSpec ()

--------------------------------------------------------------------------------

entrySpecToConfigValueCli
  :: (MonadThrow m)
  => Spec.ConfigValueType
  -> Bool
  -> Spec.CliEntrySpec ()
  -> m (Opt.Parser (Maybe (Value JSON.Value)))
entrySpecToConfigValueCli cvType isSensitive entrySpec = case entrySpec of
  Spec.CmdEntry{} -> throwM CommandKeyOnPlainCli

  Spec.PlainEntry specSettings ->
    return (settingsToJsonCli cvType isSensitive specSettings)

configValueSpecToCli
  :: (MonadThrow m)
  => Text
  -> Spec.ConfigValueType
  -> Bool
  -> Spec.ConfigSources ()
  -> Opt.Parser ConfigValue
  -> m (Opt.Parser ConfigValue)
configValueSpecToCli specEntryKey cvType isSensitive sources acc =
  let updateAccConfigOptParser configValueParser accOptParser =
        (\configValue accSubConfig -> case accSubConfig of
            ConfigValue{} -> accSubConfig

            SubConfig subConfigMap ->
              subConfigMap & HashMap.alter (const $ Just configValue) specEntryKey & SubConfig
          )
          <$> configValueParser
          <*> accOptParser
  in  case Spec.cliEntry sources of
        Nothing        -> return acc

        Just entrySpec -> do
          jsonOptParser <- entrySpecToConfigValueCli cvType isSensitive entrySpec

          let configValueParser = jsonToConfigValue <$> jsonOptParser

          return $ updateAccConfigOptParser configValueParser acc

subConfigSpecToCli
  :: (MonadThrow m)
  => Text
  -> HashMap.HashMap Text (Spec.ConfigValue ())
  -> Opt.Parser ConfigValue
  -> m (Opt.Parser ConfigValue)
subConfigSpecToCli specEntryKey subConfigSpec acc =
  let updateAccConfigOptParser subConfigParser accOptParser =
        (\subConfig accSubConfig -> case accSubConfig of
            ConfigValue{} -> accSubConfig

            SubConfig subConfigMap ->
              subConfigMap & HashMap.alter (const $ Just subConfig) specEntryKey & SubConfig
          )
          <$> subConfigParser
          <*> accOptParser
  in  do
        configOptParser <- foldM specToConfigValueCli
                                 (pure $ SubConfig HashMap.empty)
                                 (HashMap.toList subConfigSpec)

        return $ updateAccConfigOptParser configOptParser acc

specToConfigValueCli
  :: (MonadThrow m)
  => Opt.Parser ConfigValue
  -> (Text, Spec.ConfigValue ())
  -> m (Opt.Parser ConfigValue)
specToConfigValueCli acc (specEntryKey, specConfigValue) = case specConfigValue of
  Spec.ConfigValue { Spec.configValueType, Spec.isSensitive, Spec.configSources } ->
    configValueSpecToCli specEntryKey configValueType isSensitive configSources acc

  Spec.SubConfig subConfigSpec -> subConfigSpecToCli specEntryKey subConfigSpec acc

configValueCliAccInit :: (MonadThrow m) => Spec.ConfigSpec () -> m (Opt.Parser ConfigValue)
configValueCliAccInit spec =
  let zeroParser   = pure $ SubConfig HashMap.empty

      commandsSpec = do
        programSpec <- Spec.specCliProgramSpec spec
        Spec.cliCommands programSpec
  in  case commandsSpec of
        Nothing -> return zeroParser

        Just _  -> throwM CommandKeyOnPlainCli

specToConfigCli :: (MonadThrow m) => Spec.ConfigSpec () -> m (Opt.Parser Config)
specToConfigCli spec = do
  acc    <- configValueCliAccInit spec
  parser <- foldM specToConfigValueCli acc (HashMap.toList $ Spec.specConfigValues spec)

  parser & (Config <$>) & return

{-|

Dynamically generate an OptParser CLI from the spec settings declared on the
@ConfigSpec@. This will process the OptParser from given input
rather than fetching it from the OS.

Once it generates the CLI and gathers the input, it will return the
configuration map with keys defined for the program on @ConfigSpec@.

-}
resolvePlainCliPure
  :: MonadThrow m
  => PlainConfigSpec -- ^ Plain ConfigSpec (no sub-commands)
  -> Text            -- ^ Name of the program running the CLI
  -> [Text]          -- ^ Arglist for the program
  -> m Config        -- ^ returns Configuration Map
resolvePlainCliPure configSpec progName args = do
  configParser <- specToConfigCli configSpec

  let
    programModFlags = case Spec.specCliProgramSpec configSpec of
      Just programSpec ->
        Opt.fullDesc
          `mappend` (programSpec & Spec.cliProgramDesc & Text.unpack & Opt.progDesc)
          `mappend` (programSpec & Spec.cliProgramHeader & Text.unpack & Opt.header)
      Nothing -> mempty

    programParser = Opt.info (Opt.helper <*> configParser) programModFlags

    programResult =
      args & map Text.unpack & Opt.execParserPure Opt.defaultPrefs programParser

  programResultToResolverResult progName programResult

{-|

Dynamically generate an OptParser CLI from the spec settings declared on the
@ConfigSpec@.

Once it generates the CLI and gathers the input, it will return the
configuration map with keys defined for the program on @ConfigSpec@.

-}
resolvePlainCli
  :: PlainConfigSpec  -- ^ Plain ConfigSpec (no sub-commands)
  -> IO Config        -- ^ returns Configuration Map
resolvePlainCli configSpec = do
  progName <- Text.pack <$> getProgName
  args     <- map Text.pack <$> getArgs

  handleCliResult $ resolvePlainCliPure configSpec progName args


text:
<?php
interface Resource { /* … */ }
interface Dispatcher { /* … */ }

abstract class DispatchableResource implements Resource,Dispatcher { /* … */ }

class TrafficCop extends DispatchableResource
{
  protected $resource = 'traffic cop';
}
$cop = new TrafficCop();
echo $cop->dispatch();
// 'Dispatched traffic cop'


text:
using Android.OS;
using Android.App;
using Android.Content.PM;

using EntryCustomReturn.Forms.Plugin.Android;

namespace SimpleSample.Droid
{
    [Activity(Label = "SimpleSample.Droid", Icon = "@drawable/icon", Theme = "@style/MyTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
    public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
    {
        protected override void OnCreate(Bundle savedInstanceState)
        {
            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource = Resource.Layout.Toolbar;

            base.OnCreate(savedInstanceState);

            global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
            CustomReturnEntryRenderer.Init();

            LoadApplication(new App());
        }
    }
}


text:
<bill session="110" type="h" number="7192" updated="2009-01-09T07:37:04-05:00">
	<status><introduced date="1222488000" datetime="2008-09-27"/></status>

	<introduced date="1222488000" datetime="2008-09-27"/>
	<titles>
		<title type="short" as="introduced">Preserving Patient Access to Primary Care Act</title>
		<title type="official" as="introduced">To amend the Public Health Service Act and the Social Security Act to increase the number of primary care physicians and to improve patient access to primary care services, and for other purposes.</title>
	</titles>
	<sponsor id="400647"/>
	<cosponsors>

	</cosponsors>
	<actions>
		<action date="1222488000" datetime="2008-09-27"><text>Referred to the Committee on Energy and Commerce, and in addition to the Committees on the Judiciary, Education and Labor, and Ways and Means, for a period to be subsequently determined by the Speaker, in each case for consideration of such provisions as fall within the jurisdiction of the committee concerned.</text></action>
		<action date="1222488000" datetime="2008-09-27"><text>Referred to House Energy and Commerce</text></action>
		<action date="1222488000" datetime="2008-09-27"><committee name="House Energy and Commerce"/><text>Referred to the Subcommittee on Health.</text></action>
		<action date="1222488000" datetime="2008-09-27"><text>Referred to House Judiciary</text></action>
		<action date="1222488000" datetime="2008-09-27"><text>Referred to House Education and Labor</text></action>
		<action date="1222488000" datetime="2008-09-27"><text>Referred to House Ways and Means</text></action>
	</actions>
	<committees>

	</committees>
	<relatedbills>

	</relatedbills>
	<subjects>

	</subjects>
	<amendments>

	</amendments>
	<summary>

	</summary>
</bill>


text:
package org.apache.beam.sdk.runners.inprocess;

import org.apache.beam.sdk.coders.CannotProvideCoderException;
import org.apache.beam.sdk.coders.Coder;
import org.apache.beam.sdk.coders.CoderException;
import org.apache.beam.sdk.io.BoundedSource;
import org.apache.beam.sdk.io.OffsetBasedSource;
import org.apache.beam.sdk.io.OffsetBasedSource.OffsetBasedReader;
import org.apache.beam.sdk.io.Read;
import org.apache.beam.sdk.options.PipelineOptions;
import org.apache.beam.sdk.transforms.Create;
import org.apache.beam.sdk.transforms.Create.Values;
import org.apache.beam.sdk.transforms.PTransform;
import org.apache.beam.sdk.util.CoderUtils;
import org.apache.beam.sdk.values.PCollection;
import org.apache.beam.sdk.values.PInput;
import org.apache.beam.sdk.values.POutput;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;

import java.io.IOException;
import java.util.List;
import java.util.NoSuchElementException;

import javax.annotation.Nullable;

/**
 * An in-process implementation of the {@link Values Create.Values} {@link PTransform}, implemented
 * using a {@link BoundedSource}.
 *
 * The coder is inferred via the {@link Values#getDefaultOutputCoder(PInput)} method on the original
 * transform.
 */
class InProcessCreate<T> extends ForwardingPTransform<PInput, PCollection<T>> {
  private final Create.Values<T> original;

  /**
   * A {@link PTransformOverrideFactory} for {@link InProcessCreate}.
   */
  public static class InProcessCreateOverrideFactory implements PTransformOverrideFactory {
    @Override
    public <InputT extends PInput, OutputT extends POutput> PTransform<InputT, OutputT> override(
        PTransform<InputT, OutputT> transform) {
      if (transform instanceof Create.Values) {
        @SuppressWarnings("unchecked")
        PTransform<InputT, OutputT> override =
            (PTransform<InputT, OutputT>) from((Create.Values<OutputT>) transform);
        return override;
      }
      return transform;
    }
  }

  public static <T> InProcessCreate<T> from(Create.Values<T> original) {
    return new InProcessCreate<>(original);
  }

  private InProcessCreate(Values<T> original) {
    this.original = original;
  }

  @Override
  public PCollection<T> apply(PInput input) {
    Coder<T> elementCoder;
    try {
      elementCoder = original.getDefaultOutputCoder(input);
    } catch (CannotProvideCoderException e) {
      throw new IllegalArgumentException(
          "Unable to infer a coder and no Coder was specified. "
          + "Please set a coder by invoking Create.withCoder() explicitly.",
          e);
    }
    InMemorySource<T> source;
    try {
      source = InMemorySource.fromIterable(original.getElements(), elementCoder);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
    PCollection<T> result = input.getPipeline().apply(Read.from(source));
    result.setCoder(elementCoder);
    return result;
  }

  @Override
  public PTransform<PInput, PCollection<T>> delegate() {
    return original;
  }

  @VisibleForTesting
  static class InMemorySource<T> extends OffsetBasedSource<T> {
    private final List<byte[]> allElementsBytes;
    private final long totalSize;
    private final Coder<T> coder;

    public static <T> InMemorySource<T> fromIterable(Iterable<T> elements, Coder<T> elemCoder)
        throws CoderException, IOException {
      ImmutableList.Builder<byte[]> allElementsBytes = ImmutableList.builder();
      long totalSize = 0L;
      for (T element : elements) {
        byte[] bytes = CoderUtils.encodeToByteArray(elemCoder, element);
        allElementsBytes.add(bytes);
        totalSize += bytes.length;
      }
      return new InMemorySource<>(allElementsBytes.build(), totalSize, elemCoder);
    }

    /**
     * Create a new source with the specified bytes. The new source owns the input element bytes,
     * which must not be modified after this constructor is called.
     */
    private InMemorySource(List<byte[]> elementBytes, long totalSize, Coder<T> coder) {
      super(0, elementBytes.size(), 1);
      this.allElementsBytes = ImmutableList.copyOf(elementBytes);
      this.totalSize = totalSize;
      this.coder = coder;
    }

    @Override
    public long getEstimatedSizeBytes(PipelineOptions options) throws Exception {
      return totalSize;
    }

    @Override
    public boolean producesSortedKeys(PipelineOptions options) throws Exception {
      return false;
    }

    @Override
    public BoundedSource.BoundedReader<T> createReader(PipelineOptions options) throws IOException {
      return new BytesReader<>(this);
    }

    @Override
    public void validate() {}

    @Override
    public Coder<T> getDefaultOutputCoder() {
      return coder;
    }

    @Override
    public long getMaxEndOffset(PipelineOptions options) throws Exception {
      return allElementsBytes.size();
    }

    @Override
    public OffsetBasedSource<T> createSourceForSubrange(long start, long end) {
      List<byte[]> primaryElems = allElementsBytes.subList((int) start, (int) end);
      long primarySizeEstimate =
          (long) (totalSize * primaryElems.size() / (double) allElementsBytes.size());
      return new InMemorySource<>(primaryElems, primarySizeEstimate, coder);
    }

    @Override
    public long getBytesPerOffset() {
      if (allElementsBytes.size() == 0) {
        return 0L;
      }
      return totalSize / allElementsBytes.size();
    }
  }

  private static class BytesReader<T> extends OffsetBasedReader<T> {
    private int index;
    /**
     * Use an optional to distinguish between null next element (as Optional.absent()) and no next
     * element (next is null).
     */
    @Nullable private Optional<T> next;

    public BytesReader(InMemorySource<T> source) {
      super(source);
      index = -1;
    }

    @Override
    @Nullable
    public T getCurrent() throws NoSuchElementException {
      if (next == null) {
        throw new NoSuchElementException();
      }
      return next.orNull();
    }

    @Override
    public void close() throws IOException {}

    @Override
    protected long getCurrentOffset() {
      return index;
    }

    @Override
    protected boolean startImpl() throws IOException {
      return advanceImpl();
    }

    @Override
    public synchronized InMemorySource<T> getCurrentSource() {
      return (InMemorySource<T>) super.getCurrentSource();
    }

    @Override
    protected boolean advanceImpl() throws IOException {
      InMemorySource<T> source = getCurrentSource();
      index++;
      if (index >= source.allElementsBytes.size()) {
        return false;
      }
      next =
          Optional.fromNullable(
              CoderUtils.decodeFromByteArray(
                  source.coder, source.allElementsBytes.get(index)));
      return true;
    }
  }
}


text:
package storage

import (
	"context"
	"encoding/base64"
	"errors"
	"fmt"
	"io"
	"sync"
	"unicode/utf8"

	"google.golang.org/api/googleapi"
	raw "google.golang.org/api/storage/v1"
)

// A Writer writes a Cloud Storage object.
type Writer struct {
	// ObjectAttrs are optional attributes to set on the object. Any attributes
	// must be initialized before the first Write call. Nil or zero-valued
	// attributes are ignored.
	ObjectAttrs

	// SendCRC specifies whether to transmit a CRC32C field. It should be set
	// to true in addition to setting the Writer's CRC32C field, because zero
	// is a valid CRC and normally a zero would not be transmitted.
	// If a CRC32C is sent, and the data written does not match the checksum,
	// the write will be rejected.
	SendCRC32C bool

	// ChunkSize controls the maximum number of bytes of the object that the
	// Writer will attempt to send to the server in a single request. Objects
	// smaller than the size will be sent in a single request, while larger
	// objects will be split over multiple requests. The size will be rounded up
	// to the nearest multiple of 256K. If zero, chunking will be disabled and
	// the object will be uploaded in a single request.
	//
	// ChunkSize will default to a reasonable value. If you perform many concurrent
	// writes of small objects, you may wish set ChunkSize to a value that matches
	// your objects' sizes to avoid consuming large amounts of memory.
	//
	// ChunkSize must be set before the first Write call.
	ChunkSize int

	// ProgressFunc can be used to monitor the progress of a large write.
	// operation. If ProgressFunc is not nil and writing requires multiple
	// calls to the underlying service (see
	// https://cloud.google.com/storage/docs/json_api/v1/how-tos/resumable-upload),
	// then ProgressFunc will be invoked after each call with the number of bytes of
	// content copied so far.
	//
	// ProgressFunc should return quickly without blocking.
	ProgressFunc func(int64)

	ctx context.Context
	o   *ObjectHandle

	opened bool
	pw     *io.PipeWriter

	donec chan struct{} // closed after err and obj are set.
	obj   *ObjectAttrs

	mu  sync.Mutex
	err error
}

func (w *Writer) open() error {
	attrs := w.ObjectAttrs
	// Check the developer didn't change the object Name (this is unfortunate, but
	// we don't want to store an object under the wrong name).
	if attrs.Name != w.o.object {
		return fmt.Errorf("storage: Writer.Name %q does not match object name %q", attrs.Name, w.o.object)
	}
	if !utf8.ValidString(attrs.Name) {
		return fmt.Errorf("storage: object name %q is not valid UTF-8", attrs.Name)
	}
	if attrs.KMSKeyName != "" && w.o.encryptionKey != nil {
		return errors.New("storage: cannot use KMSKeyName with a customer-supplied encryption key")
	}
	pr, pw := io.Pipe()
	w.pw = pw
	w.opened = true

	go w.monitorCancel()

	if w.ChunkSize < 0 {
		return errors.New("storage: Writer.ChunkSize must be non-negative")
	}
	mediaOpts := []googleapi.MediaOption{
		googleapi.ChunkSize(w.ChunkSize),
	}
	if c := attrs.ContentType; c != "" {
		mediaOpts = append(mediaOpts, googleapi.ContentType(c))
	}

	go func() {
		defer close(w.donec)

		rawObj := attrs.toRawObject(w.o.bucket)
		if w.SendCRC32C {
			rawObj.Crc32c = encodeUint32(attrs.CRC32C)
		}
		if w.MD5 != nil {
			rawObj.Md5Hash = base64.StdEncoding.EncodeToString(w.MD5)
		}
		if w.o.c.envHost != "" {
			w.o.c.raw.BasePath = fmt.Sprintf("%s://%s", w.o.c.scheme, w.o.c.envHost)
		}
		call := w.o.c.raw.Objects.Insert(w.o.bucket, rawObj).
			Media(pr, mediaOpts...).
			Projection("full").
			Context(w.ctx)

		if w.ProgressFunc != nil {
			call.ProgressUpdater(func(n, _ int64) { w.ProgressFunc(n) })
		}
		if attrs.KMSKeyName != "" {
			call.KmsKeyName(attrs.KMSKeyName)
		}
		if attrs.PredefinedACL != "" {
			call.PredefinedAcl(attrs.PredefinedACL)
		}
		if err := setEncryptionHeaders(call.Header(), w.o.encryptionKey, false); err != nil {
			w.mu.Lock()
			w.err = err
			w.mu.Unlock()
			pr.CloseWithError(err)
			return
		}
		var resp *raw.Object
		err := applyConds("NewWriter", w.o.gen, w.o.conds, call)
		if err == nil {
			if w.o.userProject != "" {
				call.UserProject(w.o.userProject)
			}
			setClientHeader(call.Header())
			// If the chunk size is zero, then no chunking is done on the Reader,
			// which means we cannot retry: the first call will read the data, and if
			// it fails, there is no way to re-read.
			if w.ChunkSize == 0 {
				resp, err = call.Do()
			} else {
				// We will only retry here if the initial POST, which obtains a URI for
				// the resumable upload, fails with a retryable error. The upload itself
				// has its own retry logic.
				err = runWithRetry(w.ctx, func() error {
					var err2 error
					resp, err2 = call.Do()
					return err2
				})
			}
		}
		if err != nil {
			w.mu.Lock()
			w.err = err
			w.mu.Unlock()
			pr.CloseWithError(err)
			return
		}
		w.obj = newObject(resp)
	}()
	return nil
}

// Write appends to w. It implements the io.Writer interface.
//
// Since writes happen asynchronously, Write may return a nil
// error even though the write failed (or will fail). Always
// use the error returned from Writer.Close to determine if
// the upload was successful.
func (w *Writer) Write(p []byte) (n int, err error) {
	w.mu.Lock()
	werr := w.err
	w.mu.Unlock()
	if werr != nil {
		return 0, werr
	}
	if !w.opened {
		if err := w.open(); err != nil {
			return 0, err
		}
	}
	n, err = w.pw.Write(p)
	if err != nil {
		w.mu.Lock()
		werr := w.err
		w.mu.Unlock()
		// Preserve existing functionality that when context is canceled, Write will return
		// context.Canceled instead of "io: read/write on closed pipe". This hides the
		// pipe implementation detail from users and makes Write seem as though it's an RPC.
		if werr == context.Canceled || werr == context.DeadlineExceeded {
			return n, werr
		}
	}
	return n, err
}

// Close completes the write operation and flushes any buffered data.
// If Close doesn't return an error, metadata about the written object
// can be retrieved by calling Attrs.
func (w *Writer) Close() error {
	if !w.opened {
		if err := w.open(); err != nil {
			return err
		}
	}

	// Closing either the read or write causes the entire pipe to close.
	if err := w.pw.Close(); err != nil {
		return err
	}

	<-w.donec
	w.mu.Lock()
	defer w.mu.Unlock()
	return w.err
}

// monitorCancel is intended to be used as a background goroutine. It monitors the
// the context, and when it observes that the context has been canceled, it manually
// closes things that do not take a context.
func (w *Writer) monitorCancel() {
	select {
	case <-w.ctx.Done():
		w.mu.Lock()
		werr := w.ctx.Err()
		w.err = werr
		w.mu.Unlock()

		// Closing either the read or write causes the entire pipe to close.
		w.CloseWithError(werr)
	case <-w.donec:
	}
}

// CloseWithError aborts the write operation with the provided error.
// CloseWithError always returns nil.
//
// Deprecated: cancel the context passed to NewWriter instead.
func (w *Writer) CloseWithError(err error) error {
	if !w.opened {
		return nil
	}
	return w.pw.CloseWithError(err)
}

// Attrs returns metadata about a successfully-written object.
// It's only valid to call it after Close returns nil.
func (w *Writer) Attrs() *ObjectAttrs {
	return w.obj
}


text:
class RemoteTable
  module Json
    def _each
      require 'json'

      data.each do |row|
        yield row
      end
    ensure
      local_copy.cleanup
    end

    private

    def json_string
      local_copy.encoded_io.read
    end

    def parsed_json
      ::JSON.parse(json_string)
    end

    def data
      root_node.nil? ? parsed_json : parsed_json[root_node]
    end
  end
end


text:
namespace google_breakpad {

class UntypedMDRVA;
template<typename MDType> class TypedMDRVA;

// The user of this class can Open() a file and add minidump streams, data, and
// strings using the definitions in minidump_format.h.  Since this class is
// expected to be used in a situation where the current process may be
// damaged, it will not allocate heap memory.
// Sample usage:
// MinidumpFileWriter writer;
// writer.Open("/tmp/minidump.dmp");
// TypedMDRVA<MDRawHeader> header(&writer_);
// header.Allocate();
// header->get()->signature = MD_HEADER_SIGNATURE;
//  :
// writer.Close();
//
// An alternative is to use SetFile and provide a file descriptor:
// MinidumpFileWriter writer;
// writer.SetFile(minidump_fd);
// TypedMDRVA<MDRawHeader> header(&writer_);
// header.Allocate();
// header->get()->signature = MD_HEADER_SIGNATURE;
//  :
// writer.Close();

class MinidumpFileWriter {
public:
  // Invalid MDRVA (Minidump Relative Virtual Address)
  // returned on failed allocation
  static const MDRVA kInvalidMDRVA;

  MinidumpFileWriter();
  ~MinidumpFileWriter();

  // Open |path| as the destination of the minidump data. If |path| already
  // exists, then Open() will fail.
  // Return true on success, or false on failure.
  bool Open(const char *path);

  // Sets the file descriptor |file| as the destination of the minidump data.
  // Can be used as an alternative to Open() when a file descriptor is
  // available.
  // Note that |fd| is not closed when the instance of MinidumpFileWriter is
  // destroyed.
  void SetFile(const int file);

  // Close the current file (that was either created when Open was called, or
  // specified with SetFile).
  // Return true on success, or false on failure.
  bool Close();

  // Copy the contents of |str| to a MDString and write it to the file.
  // |str| is expected to be either UTF-16 or UTF-32 depending on the size
  // of wchar_t.
  // Maximum |length| of characters to copy from |str|, or specify 0 to use the
  // entire NULL terminated string.  Copying will stop at the first NULL.
  // |location| the allocated location
  // Return true on success, or false on failure
  bool WriteString(const wchar_t *str, unsigned int length,
                   MDLocationDescriptor *location);

  // Same as above, except with |str| as a UTF-8 string
  bool WriteString(const char *str, unsigned int length,
                   MDLocationDescriptor *location);

  // Write |size| bytes starting at |src| into the current position.
  // Return true on success and set |output| to position, or false on failure
  bool WriteMemory(const void *src, size_t size, MDMemoryDescriptor *output);

  // Copies |size| bytes from |src| to |position|
  // Return true on success, or false on failure
  bool Copy(MDRVA position, const void *src, ssize_t size);

  // Return the current position for writing to the minidump
  inline MDRVA position() const { return position_; }

 private:
  friend class UntypedMDRVA;

  // Allocates an area of |size| bytes.
  // Returns the position of the allocation, or kInvalidMDRVA if it was
  // unable to allocate the bytes.
  MDRVA Allocate(size_t size);

  // The file descriptor for the output file.
  int file_;

  // Whether |file_| should be closed when the instance is destroyed.
  bool close_file_when_destroyed_;

  // Current position in buffer
  MDRVA position_;

  // Current allocated size
  size_t size_;

  // Copy |length| characters from |str| to |mdstring|.  These are distinct
  // because the underlying MDString is a UTF-16 based string.  The wchar_t
  // variant may need to create a MDString that has more characters than the
  // source |str|, whereas the UTF-8 variant may coalesce characters to form
  // a single UTF-16 character.
  bool CopyStringToMDString(const wchar_t *str, unsigned int length,
                            TypedMDRVA<MDString> *mdstring);
  bool CopyStringToMDString(const char *str, unsigned int length,
                            TypedMDRVA<MDString> *mdstring);

  // The common templated code for writing a string
  template <typename CharType>
  bool WriteStringCore(const CharType *str, unsigned int length,
                       MDLocationDescriptor *location);
};

// Represents an untyped allocated chunk
class UntypedMDRVA {
 public:
  explicit UntypedMDRVA(MinidumpFileWriter *writer)
      : writer_(writer),
        position_(writer->position()),
        size_(0) {}

  // Allocates |size| bytes.  Must not call more than once.
  // Return true on success, or false on failure
  bool Allocate(size_t size);

  // Returns the current position or kInvalidMDRVA if allocation failed
  inline MDRVA position() const { return position_; }

  // Number of bytes allocated
  inline size_t size() const { return size_; }

  // Return size and position
  inline MDLocationDescriptor location() const {
    MDLocationDescriptor location = { static_cast<uint32_t>(size_),
                                      position_ };
    return location;
  }

  // Copy |size| bytes starting at |src| into the minidump at |position|
  // Return true on success, or false on failure
  bool Copy(MDRVA position, const void *src, size_t size);

  // Copy |size| bytes from |src| to the current position
  inline bool Copy(const void *src, size_t size) {
    return Copy(position_, src, size);
  }

 protected:
  // Writer we associate with
  MinidumpFileWriter *writer_;

  // Position of the start of the data
  MDRVA position_;

  // Allocated size
  size_t size_;
};

// Represents a Minidump object chunk.  Additional memory can be allocated at
// the end of the object as a:
// - single allocation
// - Array of MDType objects
// - A MDType object followed by an array
template<typename MDType>
class TypedMDRVA : public UntypedMDRVA {
 public:
  // Constructs an unallocated MDRVA
  explicit TypedMDRVA(MinidumpFileWriter *writer)
      : UntypedMDRVA(writer),
        data_(),
        allocation_state_(UNALLOCATED) {}

  inline ~TypedMDRVA() {
    // Ensure that the data_ object is written out
    if (allocation_state_ != ARRAY)
      Flush();
  }

  // Address of object data_ of MDType.  This is not declared const as the
  // typical usage will be to access the underlying |data_| object as to
  // alter its contents.
  MDType *get() { return &data_; }

  // Allocates minidump_size<MDType>::size() bytes.
  // Must not call more than once.
  // Return true on success, or false on failure
  bool Allocate();

  // Allocates minidump_size<MDType>::size() + |additional| bytes.
  // Must not call more than once.
  // Return true on success, or false on failure
  bool Allocate(size_t additional);

  // Allocate an array of |count| elements of MDType.
  // Must not call more than once.
  // Return true on success, or false on failure
  bool AllocateArray(size_t count);

  // Allocate an array of |count| elements of |size| after object of MDType
  // Must not call more than once.
  // Return true on success, or false on failure
  bool AllocateObjectAndArray(size_t count, size_t size);

  // Copy |item| to |index|
  // Must have been allocated using AllocateArray().
  // Return true on success, or false on failure
  bool CopyIndex(unsigned int index, MDType *item);

  // Copy |size| bytes starting at |str| to |index|
  // Must have been allocated using AllocateObjectAndArray().
  // Return true on success, or false on failure
  bool CopyIndexAfterObject(unsigned int index, const void *src, size_t size);

  // Write data_
  bool Flush();

 private:
  enum AllocationState {
    UNALLOCATED = 0,
    SINGLE_OBJECT,
    ARRAY,
    SINGLE_OBJECT_WITH_ARRAY
  };

  MDType data_;
  AllocationState allocation_state_;
};

}  // namespace google_breakpad

#endif  // CLIENT_MINIDUMP_FILE_WRITER_H__


text:
<?php

defined('AJXP_EXEC') or die( 'Access not allowed');

class MultiAuthFrontend extends AbstractAuthFrontend {

    function tryToLogUser(&$httpVars, $isLast = false){
        return false;
    }

    protected function parseSpecificContributions(&$contribNode)
    {
        parent::parseSpecificContributions($contribNode);
        if($contribNode->nodeName != "actions") return ;

        $actionXpath=new DOMXPath($contribNode->ownerDocument);
        $loginCallbackNodeList = $actionXpath->query('//clientCallback', $contribNode);
        $callbackNode = $loginCallbackNodeList->item(0);
        $xmlContent = $callbackNode->firstChild->wholeText;

        $sources = array();
        if(!isSet($this->options) || !isSet($this->options["DRIVERS"]) || !is_array($this->options["DRIVERS"])) return;
        foreach ($this->options["DRIVERS"] as $driverDef) {
            $dName = $driverDef["NAME"];
            if (isSet($driverDef["LABEL"])) {
                $dLabel = $driverDef["LABEL"];
            } else {
                $dLabel = $driverDef["NAME"];
            }
            $sources[$dName] = $dLabel;
        }
        $xmlContent = str_replace("AJXP_MULTIAUTH_SOURCES", json_encode($sources), $xmlContent);
        $xmlContent = str_replace("AJXP_MULTIAUTH_MASTER", $this->options["MASTER_DRIVER"], $xmlContent);
        $xmlContent = str_replace("AJXP_USER_ID_SEPARATOR", $this->options["USER_ID_SEPARATOR"], $xmlContent);
        if($callbackNode) {
            $callbackNode->removeChild($callbackNode->firstChild);
            $callbackNode->appendChild($contribNode->ownerDocument->createCDATASection($xmlContent));
        }

    }

}


text:
package org.openksavi.sponge.springboot.remoteservice;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends SpongeRemoteWebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();

        // Enable in memory based authentication with a user named "admin".
        auth.inMemoryAuthentication().withUser("admin").password(encoder.encode("password")).roles("ADMIN2");
    }
}


text:
<?php

namespace backend\controllers;

use common\models\cf\PersonsRecord;
use Yii;
use common\models\cf\PersonsChildrenRecord;
use common\models\cf\PersonsChildrenSearch;
use yii\helpers\ArrayHelper;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * PersonChildrenController implements the CRUD actions for PersonsChildrenRecord model.
 */
class PersonChildrenController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return ArrayHelper::merge(parent::behaviors(),[
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ]);
    }

    /**
     * Lists all PersonsChildrenRecord models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new PersonsChildrenSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a children for one person
     * @param integer $personId
     * @return mixed
     */
    public function actionView($personId)
    {
        $model = PersonsRecord::findOne($personId);
        $searchModel = new PersonsChildrenSearch();
        $searchModel->PersonID = $personId;
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('view', [
            'model' => $model,
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Creates a new PersonsChildrenRecord model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new PersonsChildrenRecord();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'personId' => $model->PersonID]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing PersonsChildrenRecord model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->ID]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing PersonsChildrenRecord model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $model = $this->findModel($id);
        $model->delete();

        return $this->redirect(['view', 'personId' => $model->id]);
    }

    /**
     * Finds the PersonsChildrenRecord model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return PersonsChildrenRecord the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = PersonsChildrenRecord::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}


text:
import {
  cloneDeep,
  isArray,
  isBoolean,
  isDate,
  isFunction,
  isNumber,
  isObject,
  Resource,
} from '@qgrid/core';

export class DataManipulationState {
  constructor() {
    this.resource = new Resource();

    this.deleted = new Set();
    this.added = new Set();
    this.edited = new Map();

    this.rowFactory = etalonRow => {
      if (etalonRow) {
        return cloneDeep(etalonRow, value => {
          if (isArray(value)) {
            return [];
          }

          if (!isObject(value) ||
						isNumber(value) ||
						isDate(value) ||
						isBoolean(value) ||
						isFunction(value)) {
            return null;
          }
        });
      }
    };
  }
}


text:
package com.strider.datadefender.utils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.junit.Test;

import com.strider.datadefender.database.DatabaseAnonymizerException;
import com.strider.datadefender.database.metadata.MatchMetaData;
import com.strider.datadefender.requirement.Column;
import com.strider.datadefender.requirement.Key;
import com.strider.datadefender.requirement.Parameter;
import com.strider.datadefender.requirement.Requirement;
import com.strider.datadefender.requirement.Table;

import junit.framework.TestCase;

/**
 * Unit test to test requirement related utility methods
 *
 * @author Matthew Eaton
 */
public class RequirementUtilsTest extends TestCase {
    private static final String TEST_FILE_NAME = "target/test-classes/utest-req-write.xml";
    private static final String STRING_TYPE    = "String";
    private Requirement         requirement;

    // Setup load-related tests
    private void load() throws DatabaseAnonymizerException {
        load(getClass().getResource("/Requirement.xml").getFile());
    }

    private void load(final String fname) throws DatabaseAnonymizerException {
        requirement = RequirementUtils.load(fname);
        assertNotNull(requirement);
    }

    @SuppressWarnings("serial")
    @Test
    public void testCreate() {    // just test the important stuff for now (as we aren't sure if the defaults make sense)
        final List<MatchMetaData> list = new ArrayList<MatchMetaData>() {
            {
                add(new MatchMetaData(null, "t1", Arrays.asList("pk"), Arrays.asList("fk"), "col1", STRING_TYPE, 5));    // one pk, 1 column
                add(new MatchMetaData(null, "t2", Arrays.asList("pk1", "pk2"), Arrays.asList("fk"), "col1", STRING_TYPE, 5));    // two pk, two columns
                add(new MatchMetaData(null, "t2", Arrays.asList("pk1", "pk2"), Arrays.asList("fk"),"col2", STRING_TYPE, 5));
            }
        };
        final Requirement req = RequirementUtils.create(list);

        assertEquals("Autogenerated Template Client", req.getClient());
        assertEquals("1.0", req.getVersion());
        assertEquals(2, req.getTables().size());

        final Table t1 = req.getTables().get(0);

        assertEquals("t1", t1.getName());
        assertEquals("pk", t1.getPKey());
        assertEquals(1, t1.getColumns().size());

        final Column c1 = t1.getColumns().get(0);

        assertEquals("col1", c1.getName());
        assertEquals(STRING_TYPE, c1.getReturnType());

        // default function
        assertEquals("com.strider.datadefender.functions.CoreFunctions.randomStringFromFile", c1.getFunction());
        assertEquals(1, c1.getParameters().size());

        final Table t2 = req.getTables().get(1);

        assertEquals("t2", t2.getName());
        assertEquals(2, t2.getPrimaryKeys().size());
        assertEquals(2, t2.getColumns().size());
    }

    /**
     * Test getting parameters with name "file"
     * @author Matthew Eaton
     * @throws Exception
     */
    @Test
    public void testGetFileParameter() throws Exception {
        load();

        int columnNo = 0;

        for (final Column column : requirement.getTables().get(0).getColumns()) {
            if ("column1".equals(column.getName()) || "column2".equals(column.getName())) {
                final Parameter parameter = RequirementUtils.getFileParameter(column.getParameters());

                assertNotNull(parameter);
                assertEquals(RequirementUtils.PARAM_NAME_FILE, parameter.getName());
            } else {
                final Parameter parameter = RequirementUtils.getFileParameter(column.getParameters());

                assertNull(parameter);
            }

            assertEquals("column" + ++columnNo, column.getName());
        }
    }

    @Test
    public void testGetPrimitiveArrayParameterValue() throws Exception {
        load();

        List<Parameter> params = requirement.getTables().get(2).getColumns().get(2).getParameters();

        assertNotNull(params);

        Object ret = params.get(0).getTypeValue();

        assertNotNull(ret);

        final int[] arr = (int[]) ret;

        assertEquals(3, arr.length);
        assertEquals(1, arr[0]);
        assertEquals(10, arr[1]);
        assertEquals(-20, arr[2]);
        params = requirement.getTables().get(2).getColumns().get(2).getParameters();
        assertNotNull(params);
        ret = params.get(1).getTypeValue();
        assertNotNull(ret);

        final double[] dArr = (double[]) ret;

        assertEquals(3, dArr.length);
        assertEquals(1.2, dArr[0]);
        assertEquals(10.5, dArr[1]);
        assertEquals(-20.1, dArr[2]);
    }

    @Test
    public void testGetPrimitiveParameterValues() throws Exception {
        load();

        final List<Parameter> params = requirement.getTables().get(2).getColumns().get(0).getParameters();

        assertNotNull(params);
        assertEquals(true, (boolean) params.get(0).getTypeValue());
        assertEquals(Boolean.class, params.get(0).getTypeValue().getClass());
        assertEquals(1, (byte) params.get(1).getTypeValue());
        assertEquals(Byte.class, params.get(1).getTypeValue().getClass());
        assertEquals(2, (short) params.get(2).getTypeValue());
        assertEquals(Short.class, params.get(2).getTypeValue().getClass());
        assertEquals('s', (char) params.get(3).getTypeValue());
        assertEquals(Character.class, params.get(3).getTypeValue().getClass());
        assertEquals(-3, (int) params.get(4).getTypeValue());
        assertEquals(Integer.class, params.get(4).getTypeValue().getClass());
        assertEquals(4, (long) params.get(5).getTypeValue());
        assertEquals(Long.class, params.get(5).getTypeValue().getClass());
        assertEquals(0.25f, (float) params.get(6).getTypeValue());
        assertEquals(Float.class, params.get(6).getTypeValue().getClass());
        assertEquals(0.5, (double) params.get(7).getTypeValue());
        assertEquals(Double.class, params.get(7).getTypeValue().getClass());
    }

    @Test
    public void testGetStringArrayParameterValue() throws Exception {
        load();

        final List<Parameter> params = requirement.getTables().get(2).getColumns().get(1).getParameters();

        assertNotNull(params);

        final Object ret = params.get(0).getTypeValue();

        assertNotNull(ret);

        final String[] arr = (String[]) ret;

        assertEquals(3, arr.length);
        assertEquals("column1", arr[0]);
        assertEquals("column2", arr[1]);
        assertEquals("column3", arr[2]);
    }

    /**
     * Test loaded requirements from file
     * @throws Exception
     */
    @Test
    public void testLoad() throws Exception {
        load();
        assertEquals("Test Client", requirement.getClient());
        assertEquals("1.0", requirement.getVersion());
        assertEquals(3, requirement.getTables().size());
        assertEquals("test_table", requirement.getTables().get(0).getName());

        int columnNo = 0;

        for (final Column column : requirement.getTables().get(0).getColumns()) {
            assertEquals("column" + ++columnNo, column.getName());
        }

        final List<Key> pKeys = requirement.getTables().get(1).getPrimaryKeys();

        assertNotNull(pKeys);
        assertEquals(2, pKeys.size());
        assertEquals("id1", pKeys.get(0).getName());
        assertEquals("id2", pKeys.get(1).getName());
        assertEquals(5, columnNo);
    }

    // Doesn't tests a reading a writing a simple requirement
    @Test
    public void testSimpleWriteRead() throws Exception {

        // create
        final Requirement req = new Requirement();

        req.setClient("Unit test client.");
        req.setVersion("X.X");

        final Table table = new Table();

        table.setName("Table name");
        table.setPkey("pKey");

        final Column col = new Column();

        col.setName("cName");
        col.setFunction("some.function()");

        final Parameter param = new Parameter();

        param.setName("pName");
        param.setValue("pvalue/file.txt");
        param.setType(STRING_TYPE);
        col.setParameters(Arrays.asList(param));
        table.setColumns(Arrays.asList(col));
        req.setTables(Arrays.asList(table));

        // write
        RequirementUtils.write(req, TEST_FILE_NAME);

        // read and test
        load(TEST_FILE_NAME);
        assertEquals("Unit test client.", requirement.getClient());
        assertEquals("X.X", requirement.getVersion());
        assertEquals(1, requirement.getTables().size());

        final Table t1 = requirement.getTables().get(0);

        assertEquals("Table name", t1.getName());
        assertEquals("pKey", t1.getPKey());
        assertEquals(1, t1.getColumns().size());

        final Column c1 = t1.getColumns().get(0);

        assertEquals("cName", c1.getName());
        assertEquals("some.function()", c1.getFunction());
        assertEquals(1, c1.getParameters().size());

        final Parameter p1 = c1.getParameters().get(0);

        assertEquals("pName", p1.getName());
        assertEquals("pvalue/file.txt", p1.getValue());
        assertEquals(STRING_TYPE, p1.getType());
    }
}

//~ Formatted by Jindent --- http://www.jindent.com


text:
redisSub = module.exports;

var redis = require('redis')
  , cacheApi = require('./cache.api')
  , config = require('../../../../config/config.global.js')
  , logutils = require('../../utils/log.utils')
  , util = require('util')
  , global = require('../../common/global')
  , UUID = require('uuid-js')
  , messages = require('../../common/messages')
  , longPolling = require('./longPolling.api')
  , commonUtils = require('../../utils/common.utils')
  , discClient = require('../../common/discoveryclient.api')
  ;

if (!module.parent) {
    logutils.logger.warn(util.format(messages.warn.invalid_mod_call,
                                  module.filename));
  process.exit(1);
}
function createRedisClientAndSubscribeMsg (callback)
{
    commonUtils.createRedisClient(function(client) {
        redisSub.redisSubClient = client;
        addRedisSubMsgListener(redisSub.redisSubClient);
        subsToRedis(global.MSG_REDIRECT_TO_LOGOUT);
        subsToRedis(global.DISC_SERVER_SUB_CLINET);
        callback();
    });
}

commonUtils.createRedisClient(global.WEBUI_SESSION_REDIS_DB, function(client) {
    redisSub.redisPerClient = client;
});

/* Function: subsToRedis
    This function is used to subscribe to a apecific channel to redis
 */
function subsToRedis (channel)
{
  logutils.logger.info("Redis subs done for channel:" + channel);
  redisSub.redisSubClient.subscribe(channel);
}

/* Function: unsubsToRedis
    This function is used to unsubscribe a channel from redis
 */
function unsubsToRedis (channel)
{
  redisSub.redisSubClient.unsubscribe(channel);
}

/* Function: createChannelByHashURL
    This function is used to create a channel by hash and URL.
    Whenever a client wants to subscribe to a channel, this API needs to be
    used, using unique hash, hash may be any string
 */
function createChannelByHashURL (hash, url)
{
  var channel = 'q:' + hash + global.ZWQ_MSG_SEPERATOR + url;
  return channel;
}

/* Function: createChannelByReqData
    This function is used to create a channel from the reqData.
    This channel is used for subscribing to redis for a specific client.
    reqData must be taken by using cacheApi.createReqData() API
 */
function createChannelByReqData (reqData, hash)
{
  var reqJSON = JSON.parse(reqData);
  var channel = reqJSON.data.jobCreateReqTime + global.ZWQ_MSG_SEPERATOR
    + hash + global.ZWQ_MSG_SEPERATOR + reqJSON.data.url;
  logutils.logger.info("Creating listening channel as:" + channel);
  return channel;
}

/** @Function: createPubChannelKey
  *  This function is used to create publish channel key against which Job Server
  *  publishes data in Redis
  *  The publish key is UUID.
  * @public function
  */
function createPubChannelKey ()
{
    /* Version 4 */
    var pubKey = UUID.create();
    return pubKey.toString();
}

function processRedisSubMessage (channel, msg)
{
    switch (channel) {
    case global.MSG_REDIRECT_TO_LOGOUT:
        longPolling.redirectToLogoutByChannel(msg);
        break;

    case global.DISC_SERVER_SUB_CLINET:
        discClient.processDiscoveryServiceResponseMsg(msg);
        break;

    default:
        cacheApi.sendResponseByChannel(channel, msg);
        redisSub.unsubsToRedis(channel);
        break;
    }
}

/* Function: addRedisSubMsgListener
    This function is used to add listener for messages published by redis to
    this client
 */
function addRedisSubMsgListener (redisClient)
{
  redisClient.on('message', function(channel, msg) {
    if (global.DISC_SERVER_SUB_CLINET != channel) {
        /* As in system there will be a lot of disc-server-sub message, we are
         * not logging it
         */
        logutils.logger.debug("We got the channel:" + channel + " by process:" +
                              process.pid);
    }
    /* Based on the channel, now search the request/response context from
       redis and send response and check if we got timed out or not
     */
    /* Process MSG by channel */
    processRedisSubMessage(channel, msg);
  });
}

exports.createPubChannelKey = createPubChannelKey;
exports.subsToRedis = subsToRedis;
exports.unsubsToRedis = unsubsToRedis;
exports.createChannelByHashURL = createChannelByHashURL;
exports.createChannelByReqData = createChannelByReqData;
exports.createPubChannelKey = createPubChannelKey;
exports.createRedisClientAndSubscribeMsg = createRedisClientAndSubscribeMsg;