text:
"""Class for dashd node under test"""

import decimal
import errno
import http.client
import json
import logging
import os
import subprocess
import time

from .authproxy import JSONRPCException
from .mininode import NodeConn
from .util import (
    assert_equal,
    get_rpc_proxy,
    rpc_url,
    wait_until,
    p2p_port,
)

BITCOIND_PROC_WAIT_TIMEOUT = 60

class TestNode():
    """A class for representing a dashd node under test.

    This class contains:

    - state about the node (whether it's running, etc)
    - a Python subprocess.Popen object representing the running process
    - an RPC connection to the node
    - one or more P2P connections to the node

    To make things easier for the test writer, any unrecognised messages will
    be dispatched to the RPC connection."""

    def __init__(self, i, dirname, extra_args, rpchost, timewait, binary, stderr, mocktime, coverage_dir):
        self.index = i
        self.datadir = os.path.join(dirname, "node" + str(i))
        self.rpchost = rpchost
        if timewait:
            self.rpc_timeout = timewait
        else:
            # Wait for up to 60 seconds for the RPC server to respond
            self.rpc_timeout = 60
        if binary is None:
            self.binary = os.getenv("BITCOIND", "dashd")
        else:
            self.binary = binary
        self.stderr = stderr
        self.coverage_dir = coverage_dir
        # Most callers will just need to add extra args to the standard list below. For those callers that need more flexibity, they can just set the args property directly.
        self.extra_args = extra_args
        self.args = [self.binary, "-datadir=" + self.datadir, "-server", "-keypool=1", "-discover=0", "-rest", "-logtimemicros", "-debug", "-debugexclude=libevent", "-debugexclude=leveldb", "-mocktime=" + str(mocktime), "-uacomment=testnode%d" % i]

        self.cli = TestNodeCLI(os.getenv("BITCOINCLI", "dash-cli"), self.datadir)

        # Don't try auto backups (they fail a lot when running tests)
        self.args.append("-createwalletbackups=0")

        self.running = False
        self.process = None
        self.rpc_connected = False
        self.rpc = None
        self.url = None
        self.log = logging.getLogger('TestFramework.node%d' % i)

        self.p2ps = []

    def __getattr__(self, name):
        """Dispatches any unrecognised messages to the RPC connection."""
        assert self.rpc_connected and self.rpc is not None, "Error: no RPC connection"
        return getattr(self.rpc, name)

    def start(self, extra_args=None, stderr=None):
        """Start the node."""
        if extra_args is None:
            extra_args = self.extra_args
        if stderr is None:
            stderr = self.stderr
        self.process = subprocess.Popen(self.args + extra_args, stderr=stderr)
        self.running = True
        self.log.debug("dashd started, waiting for RPC to come up")

    def wait_for_rpc_connection(self):
        """Sets up an RPC connection to the dashd process. Returns False if unable to connect."""
        # Poll at a rate of four times per second
        poll_per_s = 4
        for _ in range(poll_per_s * self.rpc_timeout):
            assert self.process.poll() is None, "dashd exited with status %i during initialization" % self.process.returncode
            try:
                self.rpc = get_rpc_proxy(rpc_url(self.datadir, self.index, self.rpchost), self.index, timeout=self.rpc_timeout, coveragedir=self.coverage_dir)
                self.rpc.getblockcount()
                # If the call to getblockcount() succeeds then the RPC connection is up
                self.rpc_connected = True
                self.url = self.rpc.url
                self.log.debug("RPC successfully started")
                return
            except IOError as e:
                if e.errno != errno.ECONNREFUSED:  # Port not yet open?
                    raise  # unknown IO error
            except JSONRPCException as e:  # Initialization phase
                # -28 RPC in warmup
                # -342 Service unavailable, RPC server started but is shutting down due to error
                if e.error['code'] != -28 and e.error['code'] != -342:
                    raise  # unknown JSON RPC exception
            except ValueError as e:  # cookie file not found and no rpcuser or rpcassword. dashd still starting
                if "No RPC credentials" not in str(e):
                    raise
            time.sleep(1.0 / poll_per_s)
        raise AssertionError("Unable to connect to dashd")

    def get_wallet_rpc(self, wallet_name):
        assert self.rpc_connected
        assert self.rpc
        wallet_path = "wallet/%s" % wallet_name
        return self.rpc / wallet_path

    def stop_node(self, wait=0):
        """Stop the node."""
        if not self.running:
            return
        self.log.debug("Stopping node")
        try:
            self.stop(wait=wait)
        except http.client.CannotSendRequest:
            self.log.exception("Unable to stop node.")
        del self.p2ps[:]

    def is_node_stopped(self):
        """Checks whether the node has stopped.

        Returns True if the node has stopped. False otherwise.
        This method is responsible for freeing resources (self.process)."""
        if not self.running:
            return True
        return_code = self.process.poll()
        if return_code is None:
            return False

        # process has stopped. Assert that it didn't return an error code.
        assert_equal(return_code, 0)
        self.running = False
        self.process = None
        self.rpc_connected = False
        self.rpc = None
        self.log.debug("Node stopped")
        return True

    def wait_until_stopped(self, timeout=BITCOIND_PROC_WAIT_TIMEOUT):
        wait_until(self.is_node_stopped, timeout=timeout)

    def node_encrypt_wallet(self, passphrase):
        """"Encrypts the wallet.

        This causes dashd to shutdown, so this method takes
        care of cleaning up resources."""
        self.encryptwallet(passphrase)
        self.wait_until_stopped()

    def add_p2p_connection(self, p2p_conn, **kwargs):
        """Add a p2p connection to the node.

        This method adds the p2p connection to the self.p2ps list and also
        returns the connection to the caller."""
        if 'dstport' not in kwargs:
            kwargs['dstport'] = p2p_port(self.index)
        if 'dstaddr' not in kwargs:
            kwargs['dstaddr'] = '127.0.0.1'
        self.p2ps.append(p2p_conn)
        kwargs.update({'rpc': self.rpc, 'callback': p2p_conn})
        p2p_conn.add_connection(NodeConn(**kwargs))

        return p2p_conn

    @property
    def p2p(self):
        """Return the first p2p connection

        Convenience property - most tests only use a single p2p connection to each
        node, so this saves having to write node.p2ps[0] many times."""
        assert self.p2ps, "No p2p connection"
        return self.p2ps[0]

    def disconnect_p2ps(self):
        """Close all p2p connections to the node."""
        for p in self.p2ps:
            # Connection could have already been closed by other end.
            if p.connection is not None:
                p.connection.disconnect_node()
        self.p2ps = []

class TestNodeCLI():
    """Interface to bitcoin-cli for an individual node"""

    def __init__(self, binary, datadir):
        self.args = []
        self.binary = binary
        self.datadir = datadir
        self.input = None

    def __call__(self, *args, input=None):
        # TestNodeCLI is callable with bitcoin-cli command-line args
        self.args = [str(arg) for arg in args]
        self.input = input
        return self

    def __getattr__(self, command):
        def dispatcher(*args, **kwargs):
            return self.send_cli(command, *args, **kwargs)
        return dispatcher

    def send_cli(self, command, *args, **kwargs):
        """Run bitcoin-cli command. Deserializes returned string as python object."""

        pos_args = [str(arg) for arg in args]
        named_args = [str(key) + "=" + str(value) for (key, value) in kwargs.items()]
        assert not (pos_args and named_args), "Cannot use positional arguments and named arguments in the same bitcoin-cli call"
        p_args = [self.binary, "-datadir=" + self.datadir] + self.args
        if named_args:
            p_args += ["-named"]
        p_args += [command] + pos_args + named_args
        process = subprocess.Popen(p_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
        cli_stdout, cli_stderr = process.communicate(input=self.input)
        returncode = process.poll()
        if returncode:
            # Ignore cli_stdout, raise with cli_stderr
            raise subprocess.CalledProcessError(returncode, self.binary, output=cli_stderr)
        return json.loads(cli_stdout, parse_float=decimal.Decimal)


text:
package com.b2international.commons.exceptions;

import static org.slf4j.LoggerFactory.getLogger;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.slf4j.Logger;

import com.b2international.commons.CompareUtils;
import com.b2international.commons.Pair;
import com.b2international.commons.ReflectionUtils;
import com.b2international.commons.StringUtils;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.base.Throwables;

/**
 * Utility class for exceptions.
 *
 */
public abstract class Exceptions {

	private static final Logger LOGGER = getLogger(Exceptions.class);

	/**Represents the '&#58' character as a string.*/
	private static final String COLON = ":";

	/**Represents the message field on a {@link Throwable}. See {@link Throwable#getMessage()};*/
	private static final String THROWABLE_DETAILED_MESSAGE = "detailMessage";

	/**Pattern for a fully qualified JAVA class name.*/
	private static final Pattern JAVA_FQCN_PATTERN = Pattern.compile("([a-z][a-z_0-9]*\\.)*[A-Z_]($[A-Z_]|[\\w_])*");
	/**Pattern for a valid stack trace element prefix.*/
	private static final Pattern STACK_TRACE_ELEMENT_PATTERN = Pattern.compile("\\s*at\\s+([\\w\\.$_]+)\\.([\\w$_]+)(\\(.*java)?:(\\d+)\\)");

	/**
	 * Tries to extract the expected cause from the commit exception and returns with it. May return with {@code null}
	 * if the expected exception cannot be extracted from the wrapper commit exception.
	 * @param t the throwable possible wrapping the original cause of a failure commit.
	 * @param classLoader class loader for resolving the excepted cause. May be {@code null}.
	 * @param expectedCauseType the expected case type.
	 * @return the wrapped cause or {@code null} if cannot be extracted.
	 */
	public static <T extends Throwable> T extractCause(final Throwable t, final ClassLoader classLoader, final Class<? extends T> expectedCauseType) {

		Preconditions.checkNotNull(t, "Exception argument cannot be null.");
		Preconditions.checkNotNull(expectedCauseType, "Expected cause type class argument cannot be null.");

		@SuppressWarnings("rawtypes") final Pair<Class, String> cause = extractCause0(t, classLoader, expectedCauseType);
		if (null != cause && expectedCauseType.isAssignableFrom(cause.getA())) {
			try {
				final T $ = expectedCauseType.newInstance();
				ReflectionUtils.setField(Throwable.class, $, THROWABLE_DETAILED_MESSAGE, Strings.nullToEmpty(cause.getB()));
				return $;
			} catch (final InstantiationException e1) {
				LOGGER.error("Cannot instantiate " + cause.getA().getSimpleName() + " instance as the cause of " + t + ".");
			} catch (final IllegalAccessException e1) {
				LOGGER.error("Cannot instantiate " + cause.getA().getSimpleName() + " instance as the cause of " + t + ".");
			}
		}

		return null;
	}

	/*tries to extract the original cause and its detailed message of commit attempt from the given commit exception. can be null, if extraction failed.*/
	@SuppressWarnings({ "rawtypes" })
	private static <T extends Throwable> Pair<Class, String> extractCause0(final Throwable t, final ClassLoader classLoader, final Class<T> expectedCauseType) {

		Preconditions.checkNotNull(t, "Throwable argument cannot be null.");
		final String message = Throwables.getStackTraceAsString(t);

		if (StringUtils.isEmpty(message)) {

			//return with the original exception
			return null;

		}

		final Matcher matcher = JAVA_FQCN_PATTERN.matcher(message);

		Class<?> clazz = null;
		String detailedMessage = null;

		while (matcher.find()) {

			final String fqcn = matcher.group(0);

			try {

				if (null != classLoader) {

					clazz = classLoader.loadClass(fqcn);

				}

				if (null == clazz) {

					clazz = Class.forName(fqcn);

				}

				if (expectedCauseType.isAssignableFrom(clazz)) {

					detailedMessage = extractCauseMessage(clazz, message);
					return Pair.<Class, String>of(clazz, detailedMessage);

				}

			} catch (final ClassNotFoundException cnfe) {

				//ignore

			}

		}

		return null == clazz ? null : Pair.of((Class) clazz, Strings.nullToEmpty(detailedMessage));

	}

	/*extracts the throwable message from the stack trace message. may return with an empty string is the extraction failed.*/
	private static String extractCauseMessage(final Class<?> clazz, final String message) {

		final String classNameRegexp = clazz.getName() + COLON;
		final String[] split = message.split(classNameRegexp, 2);

		if (CompareUtils.isEmpty(split)) {

			return Strings.nullToEmpty(null);

		} else {

			final String causePart = Strings.nullToEmpty(split[1 == split.length ? 0 : 1]);
			final Matcher matcher = STACK_TRACE_ELEMENT_PATTERN.matcher(causePart);
			return matcher.find()
					? Strings.nullToEmpty(causePart).length() > 0
						? causePart.substring(1, matcher.start()) : Strings.nullToEmpty(null)
						: Strings.nullToEmpty(null);

		}

	}

	private Exceptions() {
		//suppressed constructor
	}

}

redpajama_set_name: RedPajamaGithub


text:
#ifndef _SEQ_DECL_PLUGIN_H_
#define _SEQ_DECL_PLUGIN_H_

#include "ast.h"

enum seq_sort_kind {
    SEQ_SORT,
    RE_SORT
};

enum seq_op_kind {
    OP_SEQ_UNIT,
    OP_SEQ_EMPTY,
    OP_SEQ_CONCAT,
    OP_SEQ_CONS,
    OP_SEQ_REV_CONS,
    OP_SEQ_HEAD,
    OP_SEQ_TAIL,
    OP_SEQ_LAST,
    OP_SEQ_FIRST,
    OP_SEQ_PREFIX_OF,
    OP_SEQ_SUFFIX_OF,
    OP_SEQ_SUBSEQ_OF,
    OP_SEQ_EXTRACT,
    OP_SEQ_NTH,
    OP_SEQ_LENGTH,

    OP_RE_PLUS,
    OP_RE_STAR,
    OP_RE_OPTION,
    OP_RE_RANGE,
    OP_RE_CONCAT,
    OP_RE_UNION,
    OP_RE_INTERSECT,
    OP_RE_COMPLEMENT,
    OP_RE_DIFFERENCE,
    OP_RE_LOOP,
    OP_RE_EMPTY_SET,
    OP_RE_FULL_SET,
    OP_RE_EMPTY_SEQ,
    OP_RE_OF_SEQ,
    OP_RE_OF_PRED,
    OP_RE_MEMBER,

    LAST_SEQ_OP
};

class seq_decl_plugin : public decl_plugin {
    struct psig {
        symbol          m_name;
        unsigned        m_num_params;
        sort_ref_vector m_dom;
        sort_ref        m_range;
        psig(ast_manager& m, char const* name, unsigned n, unsigned dsz, sort* const* dom, sort* rng):
            m_name(name),
            m_num_params(n),
            m_dom(m),
            m_range(rng, m)
        {
            m_dom.append(dsz, dom);
        }
    };

    ptr_vector<psig> m_sigs;
    bool m_init;

    void match(psig& sig, unsigned dsz, sort* const* dom, sort* range, sort_ref& rng);

    bool match(ptr_vector<sort>& binding, sort* s, sort* sP);

    sort* apply_binding(ptr_vector<sort> const& binding, sort* s);

    bool is_sort_param(sort* s, unsigned& idx);

    void init();

public:
    seq_decl_plugin();

    virtual ~seq_decl_plugin() {}
    virtual void finalize();

    virtual decl_plugin * mk_fresh() { return alloc(seq_decl_plugin); }

    virtual sort * mk_sort(decl_kind k, unsigned num_parameters, parameter const * parameters);

    virtual func_decl * mk_func_decl(decl_kind k, unsigned num_parameters, parameter const * parameters,
                                     unsigned arity, sort * const * domain, sort * range);

    virtual void get_op_names(svector<builtin_name> & op_names, symbol const & logic);

    virtual void get_sort_names(svector<builtin_name> & sort_names, symbol const & logic);

    virtual bool is_value(app * e) const;

    virtual bool is_unique_value(app * e) const { return is_value(e); }

};

#endif /* _SEQ_DECL_PLUGIN_H_ */


text:
import unittest

if 0:
    # no released version of manuel actually works with :lineno:
    # settings yet
    class ManuelDocsCase(unittest.TestCase):
        def __new__(self, test):
            return getattr(self, test)()

        @classmethod
        def test_docs(cls):
            import os
            import pkg_resources
            import manuel.testing
            import manuel.codeblock
            import manuel.capture
            import manuel.ignore
            m = manuel.ignore.Manuel()
            m += manuel.codeblock.Manuel()
            m += manuel.capture.Manuel()
            docs = []

            egg_path = pkg_resources.get_distribution('pyramid').location
            path = os.path.join(egg_path, 'docs')
            for root, dirs, files in os.walk(path):
                for ignore in ('.svn', '.build', '.hg', '.git', 'CVS'):
                    if ignore in dirs:
                        dirs.remove(ignore)

                for filename in files:
                    if filename.endswith('.rst'):
                        docs.append(os.path.join(root, filename))

            print(path)
            return manuel.testing.TestSuite(m, *docs)


text:
def findMax(temperatures: List[Int]) = {
  var highTemperature = Integer.MIN_VALUE
  for (temperature <- temperatures) {
    highTemperature = Math.max(highTemperature, temperature)
  }
  highTemperature
}

println(findMax(List(23, 27, 17)))


text:
module Google
  module Image
    VERSION = "0.0.4"
  end
end


text:
<?xml version="1.0" ?>

<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">

    <parameters>
        <parameter key="cart.form.type.subscription.class">MobileCart\SubscriptionBundle\Form\SubscriptionType</parameter>
        <parameter key="cart.form.type.subscription_customer.class">MobileCart\SubscriptionBundle\Form\SubscriptionCustomerType</parameter>
        <parameter key="cart.form.type.subscription_customer.frontend.class">MobileCart\SubscriptionBundle\Form\SubscriptionCustomerFrontendType</parameter>
        <parameter key="cart.listener.subscription.checkout.form.class">MobileCart\SubscriptionBundle\EventListener\Checkout\CheckoutForm</parameter>
        <parameter key="cart.listener.subscription.cart.add.product.class">MobileCart\SubscriptionBundle\EventListener\Cart\AddProduct</parameter>
        <parameter key="cart.listener.subscription.login.class">MobileCart\SubscriptionBundle\EventListener\Security\Login</parameter>
        <parameter key="cart.repo.subscription">MobileCartSubscriptionBundle:Subscription</parameter>
        <parameter key="cart.repo.subscription_customer">MobileCartSubscriptionBundle:SubscriptionCustomer</parameter>
        <parameter key="cart.subscription.class">MobileCart\SubscriptionBundle\Service\SubscriptionService</parameter>
        <parameter key="cart.subscription.session.class">MobileCart\SubscriptionBundle\Service\SubscriptionSessionService</parameter>
        <parameter key="cart.subscription.order.submit.success.class">MobileCart\SubscriptionBundle\EventListener\Checkout\OrderSubmitSuccess</parameter>
        <parameter key="cart.subscription.enabled">1</parameter>
        <parameter key="cart.twig.subscription.frontend.class">MobileCart\SubscriptionBundle\Twig\Extension\FrontendExtension</parameter>
        <parameter key="cart.listener.subscription.search.class">MobileCart\SubscriptionBundle\EventListener\Subscription\SubscriptionSearch</parameter>
        <parameter key="cart.listener.subscription.list.class">MobileCart\SubscriptionBundle\EventListener\Subscription\SubscriptionList</parameter>
        <parameter key="cart.listener.subscription.edit.return.class">MobileCart\SubscriptionBundle\EventListener\Subscription\SubscriptionEditReturn</parameter>
        <parameter key="cart.listener.subscription.new.return.class">MobileCart\SubscriptionBundle\EventListener\Subscription\SubscriptionNewReturn</parameter>
        <parameter key="cart.listener.subscription.create.return.class">MobileCart\SubscriptionBundle\EventListener\Subscription\SubscriptionCreateReturn</parameter>
        <parameter key="cart.listener.subscription.update.return.class">MobileCart\SubscriptionBundle\EventListener\Subscription\SubscriptionUpdateReturn</parameter>
        <parameter key="cart.listener.subscription.update.class">MobileCart\SubscriptionBundle\EventListener\Subscription\SubscriptionUpdate</parameter>
        <parameter key="cart.listener.subscription.insert.class">MobileCart\SubscriptionBundle\EventListener\Subscription\SubscriptionInsert</parameter>
        <parameter key="cart.listener.subscription.delete.class">MobileCart\SubscriptionBundle\EventListener\Subscription\SubscriptionDelete</parameter>
        <parameter key="cart.listener.subscription.admin.form.class">MobileCart\SubscriptionBundle\EventListener\Subscription\SubscriptionAdminForm</parameter>
        <parameter key="cart.listener.subscription_customer.search.class">MobileCart\SubscriptionBundle\EventListener\SubscriptionCustomer\SubscriptionCustomerSearch</parameter>
        <parameter key="cart.listener.subscription_customer.list.class">MobileCart\SubscriptionBundle\EventListener\SubscriptionCustomer\SubscriptionCustomerList</parameter>
        <parameter key="cart.listener.subscription_customer.frontend.list.class">MobileCart\SubscriptionBundle\EventListener\SubscriptionCustomer\SubscriptionCustomerFrontendList</parameter>
        <parameter key="cart.listener.subscription_customer.edit.return.class">MobileCart\SubscriptionBundle\EventListener\SubscriptionCustomer\SubscriptionCustomerEditReturn</parameter>
        <parameter key="cart.listener.subscription_customer.new.return.class">MobileCart\SubscriptionBundle\EventListener\SubscriptionCustomer\SubscriptionCustomerNewReturn</parameter>
        <parameter key="cart.listener.subscription_customer.create.return.class">MobileCart\SubscriptionBundle\EventListener\SubscriptionCustomer\SubscriptionCustomerCreateReturn</parameter>
        <parameter key="cart.listener.subscription_customer.update.return.class">MobileCart\SubscriptionBundle\EventListener\SubscriptionCustomer\SubscriptionCustomerUpdateReturn</parameter>
        <parameter key="cart.listener.subscription_customer.add.return.class">MobileCart\SubscriptionBundle\EventListener\SubscriptionCustomer\SubscriptionCustomerAddReturn</parameter>
        <parameter key="cart.listener.subscription_customer.add.post.return.class">MobileCart\SubscriptionBundle\EventListener\SubscriptionCustomer\SubscriptionCustomerAddPostReturn</parameter>
        <parameter key="cart.listener.subscription_customer.add.class">MobileCart\SubscriptionBundle\EventListener\SubscriptionCustomer\SubscriptionCustomerAdd</parameter>
        <parameter key="cart.listener.subscription_customer.add.success.class">MobileCart\SubscriptionBundle\EventListener\SubscriptionCustomer\SubscriptionCustomerAddSuccess</parameter>
        <parameter key="cart.listener.subscription_customer.update.class">MobileCart\SubscriptionBundle\EventListener\SubscriptionCustomer\SubscriptionCustomerUpdate</parameter>
        <parameter key="cart.listener.subscription_customer.insert.class">MobileCart\SubscriptionBundle\EventListener\SubscriptionCustomer\SubscriptionCustomerInsert</parameter>
        <parameter key="cart.listener.subscription_customer.delete.class">MobileCart\SubscriptionBundle\EventListener\SubscriptionCustomer\SubscriptionCustomerDelete</parameter>
        <parameter key="cart.listener.subscription_customer.cancel.class">MobileCart\SubscriptionBundle\EventListener\SubscriptionCustomer\SubscriptionCustomerCancel</parameter>
        <parameter key="cart.listener.subscription_customer.admin.form.class">MobileCart\SubscriptionBundle\EventListener\SubscriptionCustomer\SubscriptionCustomerAdminForm</parameter>
        <parameter key="cart.listener.subscription_customer.frontend.form.class">MobileCart\SubscriptionBundle\EventListener\SubscriptionCustomer\SubscriptionCustomerFrontendForm</parameter>
        <!-- Admin Menu Event Listener -->
        <parameter key="cart.listener.subscription.admin.navigation.class">MobileCart\SubscriptionBundle\EventListener\Admin\AdminNavigation</parameter>
    </parameters>

    <services>

        <!-- Admin Menu -->
        <service id="cart.listener.subscription.admin.navigation" lazy="true" class="%cart.listener.subscription.admin.navigation.class%">
            <tag name="kernel.event_listener" event="menu.build.admin_dashboard" method="onAdminNavigation" priority="40" />
            <call method="setRouter">
                <argument type="service" id="router"/>
            </call>
        </service>

        <!-- Order Success -->
        <service id="cart.subscription.order.submit.success" lazy="true" class="%cart.subscription.order.submit.success.class%">
            <tag name="kernel.event_listener" event="order.submit.success" method="onOrderSubmitSuccess" priority="50" />
            <call method="setSubscriptionSessionService">
                <argument type="service" id="cart.subscription.session" />
            </call>
        </service>

        <!-- Subscription Session -->
        <service id="cart.subscription.session" lazy="true" class="%cart.subscription.session.class%">
            <call method="setCartService">
                <argument type="service" id="cart" />
            </call>
        </service>

        <!-- Twig Extension -->
        <service id="cart.twig.subscription.frontend" lazy="true" class="%cart.twig.subscription.frontend.class%">
            <tag name="twig.extension" /><call method="setSubscriptionSessionService">
                <argument type="service" id="cart.subscription.session" />
            </call>
        </service>

        <!-- Login Listener -->
        <service id="cart.listener.subscription.login" lazy="true" class="%cart.listener.subscription.login.class%">
            <tag name="kernel.event_listener" event="login.success" method="onLoginSuccess" priority="40" />
            <call method="setCartService">
                <argument type="service" id="cart" />
            </call>
        </service>

        <!-- Event Listener: Checkout Form, configure subscription payment options -->
        <!--
        <service id="cart.listener.subscription.checkout.form" lazy="true" class="%cart.listener.subscription.checkout.form.class%">
            <tag name="kernel.event_listener" event="checkout.form" method="onCheckoutForm" priority="55" />
            <call method="setCheckoutSessionService">
                <argument type="service" id="cart.checkout.session" />
            </call>
        </service>
        -->

        <!-- Event Listener: Add Product to Cart -->
        <service id="cart.listener.subscription.cart.add.product" lazy="true" class="%cart.listener.subscription.cart.add.product.class%">
            <tag name="kernel.event_listener" event="cart.add.product" method="onCartAddProduct" priority="40" />
            <tag name="kernel.event_listener" event="cart.add.discount" method="onCartAddProduct" priority="40" />
            <call method="setCartService">
                <argument type="service" id="cart" />
            </call>
        </service>

        <!-- Subscription Service -->
        <service id="cart.subscription" lazy="true" class="%cart.subscription.class%">
            <call method="setIsEnabled">
                <argument type="string">%cart.subscription.enabled%</argument>
            </call>
            <call method="setOrderService">
                <argument type="service" id="cart.order" />
            </call>
            <call method="setPaymentService">
                <argument type="service" id="cart.payment" />
            </call>
            <call method="setMailer">
                <argument type="service" id="mailer" />
            </call>
        </service>

        <!-- Subscription Event Listeners -->
        <service id="cart.listener.subscription.search" lazy="true" class="%cart.listener.subscription.search.class%">
            <tag name="kernel.event_listener" event="subscription.search" method="onSubscriptionSearch" priority="50" />
            <call method="setSearch">
                <argument type="service" id="cart.search.admin" />
                <argument type="string">subscription</argument>
            </call>
        </service>
        <service id="cart.listener.subscription.list" lazy="true" class="%cart.listener.subscription.list.class%">
            <tag name="kernel.event_listener" event="subscription.search" method="onSubscriptionList" priority="40" />
            <call method="setRouter">
                <argument type="service" id="router"/>
            </call>
            <call method="setThemeService">
                <argument type="service" id="cart.theme"/>
            </call>
        </service>
        <service id="cart.listener.subscription.edit.return" lazy="true" class="%cart.listener.subscription.edit.return.class%">
            <tag name="kernel.event_listener" event="subscription.edit.return" method="onSubscriptionEditReturn" priority="50" />
            <call method="setEntityService">
                <argument type="service" id="cart.entity" />
            </call>
            <call method="setThemeService">
                <argument type="service" id="cart.theme"/>
            </call>
        </service>
        <service id="cart.listener.subscription.new.return" lazy="true" class="%cart.listener.subscription.new.return.class%">
            <tag name="kernel.event_listener" event="subscription.new.return" method="onSubscriptionNewReturn" priority="50" />
            <call method="setEntityService">
                <argument type="service" id="cart.entity" />
            </call>
            <call method="setThemeService">
                <argument type="service" id="cart.theme"/>
            </call>
        </service>
        <service id="cart.listener.subscription.create.return" lazy="true" class="%cart.listener.subscription.create.return.class%">
            <tag name="kernel.event_listener" event="subscription.create.return" method="onSubscriptionCreateReturn" priority="50" />
            <call method="setRouter">
                <argument type="service" id="router" />
            </call>
        </service>
        <service id="cart.listener.subscription.update.return" lazy="true" class="%cart.listener.subscription.update.return.class%">
            <tag name="kernel.event_listener" event="subscription.update.return" method="onSubscriptionUpdateReturn" priority="50" />
            <call method="setRouter">
                <argument type="service" id="router" />
            </call>
        </service>
        <service id="cart.listener.subscription.update" lazy="true" class="%cart.listener.subscription.update.class%">
            <tag name="kernel.event_listener" event="subscription.update" method="onSubscriptionUpdate" priority="50" />
            <call method="setEntityService">
                <argument type="service" id="cart.entity" />
            </call>
        </service>
        <service id="cart.listener.subscription.insert" lazy="true" class="%cart.listener.subscription.insert.class%">
            <tag name="kernel.event_listener" event="subscription.insert" method="onSubscriptionInsert" priority="50" />
            <call method="setEntityService">
                <argument type="service" id="cart.entity" />
            </call>
        </service>
        <service id="cart.listener.subscription.delete" lazy="true" class="%cart.listener.subscription.delete.class%">
            <tag name="kernel.event_listener" event="subscription.delete" method="onSubscriptionDelete" priority="50" />
            <call method="setEntityService">
                <argument type="service" id="cart.entity" />
            </call>
        </service>
        <service id="cart.listener.subscription.admin.form" lazy="true" class="%cart.listener.subscription.admin.form.class%">
            <tag name="kernel.event_listener" event="subscription.admin.form" method="onSubscriptionAdminForm" priority="50" />
            <call method="setEntityService">
                <argument type="service" id="cart.entity" />
            </call>
            <call method="setFormFactory">
                <argument type="service" id="form.factory" />
            </call>
            <call method="setFormTypeClass">
                <argument type="string">%cart.form.type.subscription.class%</argument>
            </call>
            <call method="setThemeConfig">
                <argument type="service" id="cart.theme.config" />
            </call>
        </service>

        <!-- Subscription Customer Event Listeners -->
        <service id="cart.listener.subscription_customer.search" lazy="true" class="%cart.listener.subscription_customer.search.class%">
            <tag name="kernel.event_listener" event="subscription_customer.search" method="onSubscriptionCustomerSearch" priority="50" />
            <call method="setSearch">
                <argument type="service" id="cart.search.admin" />
                <argument type="string">subscription_customer</argument>
            </call>
        </service>
        <service id="cart.listener.subscription_customer.list" lazy="true" class="%cart.listener.subscription_customer.list.class%">
            <tag name="kernel.event_listener" event="subscription_customer.search" method="onSubscriptionCustomerList" priority="40" />
            <call method="setRouter">
                <argument type="service" id="router"/>
            </call>
            <call method="setThemeService">
                <argument type="service" id="cart.theme"/>
            </call>
        </service>
        <service id="cart.listener.subscription_customer.edit.return" lazy="true" class="%cart.listener.subscription_customer.edit.return.class%">
            <tag name="kernel.event_listener" event="subscription_customer.edit.return" method="onSubscriptionCustomerEditReturn" priority="50" />
            <call method="setEntityService">
                <argument type="service" id="cart.entity" />
            </call>
            <call method="setThemeService">
                <argument type="service" id="cart.theme"/>
            </call>
        </service>
        <service id="cart.listener.subscription_customer.new.return" lazy="true" class="%cart.listener.subscription_customer.new.return.class%">
            <tag name="kernel.event_listener" event="subscription_customer.new.return" method="onSubscriptionCustomerNewReturn" priority="50" />
            <call method="setEntityService">
                <argument type="service" id="cart.entity" />
            </call>
            <call method="setThemeService">
                <argument type="service" id="cart.theme"/>
            </call>
        </service>
        <service id="cart.listener.subscription_customer.create.return" lazy="true" class="%cart.listener.subscription_customer.create.return.class%">
            <tag name="kernel.event_listener" event="subscription_customer.create.return" method="onSubscriptionCustomerCreateReturn" priority="50" />
            <call method="setRouter">
                <argument type="service" id="router" />
            </call>
        </service>
        <service id="cart.listener.subscription_customer.update.return" lazy="true" class="%cart.listener.subscription_customer.update.return.class%">
            <tag name="kernel.event_listener" event="subscription_customer.update.return" method="onSubscriptionCustomerUpdateReturn" priority="50" />
            <call method="setRouter">
                <argument type="service" id="router" />
            </call>
        </service>
        <service id="cart.listener.subscription_customer.update" lazy="true" class="%cart.listener.subscription_customer.update.class%">
            <tag name="kernel.event_listener" event="subscription_customer.update" method="onSubscriptionCustomerUpdate" priority="50" />
            <call method="setEntityService">
                <argument type="service" id="cart.entity" />
            </call>
        </service>
        <service id="cart.listener.subscription_customer.insert" lazy="true" class="%cart.listener.subscription_customer.insert.class%">
            <tag name="kernel.event_listener" event="subscription_customer.insert" method="onSubscriptionCustomerInsert" priority="50" />
            <call method="setEntityService">
                <argument type="service" id="cart.entity" />
            </call>
        </service>
        <service id="cart.listener.subscription_customer.delete" lazy="true" class="%cart.listener.subscription_customer.delete.class%">
            <tag name="kernel.event_listener" event="subscription_customer.delete" method="onSubscriptionCustomerDelete" priority="50" />
            <call method="setEntityService">
                <argument type="service" id="cart.entity" />
            </call>
            <call method="setRouter">
                <argument type="service" id="router" />
            </call>
        </service>
        <service id="cart.listener.subscription_customer.cancel" lazy="true" class="%cart.listener.subscription_customer.cancel.class%">
            <tag name="kernel.event_listener" event="subscription_customer.cancel" method="onSubscriptionCustomerCancel" priority="50" />
            <call method="setSubscriptionService">
                <argument type="service" id="cart.subscription" />
            </call>
            <call method="setRouter">
                <argument type="service" id="router" />
            </call>
        </service>
        <service id="cart.listener.subscription_customer.admin.form" lazy="true" class="%cart.listener.subscription_customer.admin.form.class%">
            <tag name="kernel.event_listener" event="subscription_customer.admin.form" method="onSubscriptionCustomerAdminForm" priority="50" />
            <call method="setEntityService">
                <argument type="service" id="cart.entity" />
            </call>
            <call method="setFormFactory">
                <argument type="service" id="form.factory" />
            </call>
            <call method="setFormTypeClass">
                <argument type="string">%cart.form.type.subscription_customer.class%</argument>
            </call>
            <call method="setThemeConfig">
                <argument type="service" id="cart.theme.config" />
            </call>
        </service>
        <service id="cart.listener.subscription_customer.frontend.form" lazy="true" class="%cart.listener.subscription_customer.frontend.form.class%">
            <tag name="kernel.event_listener" event="subscription_customer.frontend.form" method="onSubscriptionCustomerFrontendForm" priority="50" />
            <call method="setEntityService">
                <argument type="service" id="cart.entity" />
            </call>
            <call method="setFormFactory">
                <argument type="service" id="form.factory" />
            </call>
            <call method="setFormTypeClass">
                <argument type="string">%cart.form.type.subscription_customer.frontend.class%</argument>
            </call>
            <call method="setThemeConfig">
                <argument type="service" id="cart.theme.config" />
            </call>
        </service>
        <service id="cart.listener.subscription_customer.add.return" lazy="true" class="%cart.listener.subscription_customer.add.return.class%">
            <tag name="kernel.event_listener" event="subscription_customer.add.return" method="onSubscriptionCustomerAddReturn" priority="50" />
            <call method="setEntityService">
                <argument type="service" id="cart.entity" />
            </call>
            <call method="setThemeService">
                <argument type="service" id="cart.theme"/>
            </call>
        </service>
        <service id="cart.listener.subscription_customer.add" lazy="true" class="%cart.listener.subscription_customer.add.class%">
            <tag name="kernel.event_listener" event="subscription_customer.add" method="onSubscriptionCustomerAdd" priority="50" />
            <call method="setMailer">
                <argument type="service" id="mailer" />
            </call>
            <call method="setRouter">
                <argument type="service" id="router" />
            </call>
            <call method="setThemeService">
                <argument type="service" id="cart.theme" />
            </call>
            <call method="setSecurityPasswordEncoder">
                <argument type="service" id="security.password_encoder" />
            </call>
            <call method="setEntityService">
                <argument type="service" id="cart.entity" />
            </call>
        </service>
        <service id="cart.listener.subscription_customer.add.post.return" lazy="true" class="%cart.listener.subscription_customer.add.post.return.class%">
            <tag name="kernel.event_listener" event="subscription_customer.add.post.return" method="onSubscriptionCustomerAddPostReturn" priority="50" />
            <call method="setRouter">
                <argument type="service" id="router" />
            </call>
        </service>
        <service id="cart.listener.subscription_customer.add.success" lazy="true" class="%cart.listener.subscription_customer.add.success.class%">
            <tag name="kernel.event_listener" event="subscription_customer.add.success" method="onSubscriptionCustomerAddSuccess" priority="50" />
            <call method="setThemeService">
                <argument type="service" id="cart.theme"/>
            </call>
        </service>
        <service id="cart.listener.subscription_customer.frontend.list" lazy="true" class="%cart.listener.subscription_customer.frontend.list.class%">
            <tag name="kernel.event_listener" event="subscription_customer.frontend.list" method="onSubscriptionCustomerFrontendList" priority="50" />
            <call method="setRouter">
                <argument type="service" id="router"/>
            </call>
            <call method="setThemeService">
                <argument type="service" id="cart.theme"/>
            </call>
            <call method="setEntityService">
                <argument type="service" id="cart.entity"/>
            </call>
        </service>
    </services>

</container>


text:
import cherrypy

from lib.model.user import User

__all__ = ['UserTool']

class UserTool(cherrypy.Tool):
    def __init__(self):
        """
        The user tool takes care of fetching the current
        logged in user to then associating it with
        the request.
        """
        cherrypy.Tool.__init__(self, 'before_handler',
                               self._fetch,
                               priority=20)

    def _setup(self):
        cherrypy.Tool._setup(self)
        cherrypy.request.hooks.attach('on_end_resource',
                                      self._cleanup,
                                      priority=80)

    def _fetch(self):
        if 'user_id' not in cherrypy.session:
            raise cherrypy.HTTPRedirect("/login")

        uid = cherrypy.session['user_id'].decode('utf-8')
        user = User.get_by_uid(cherrypy.request.db, uid)
        if not user:
            raise cherrypy.HTTPRedirect("/login/")

        cherrypy.request.user = user

    def _cleanup(self):
        cherrypy.request.user = None


text:
<?php

namespace Illuminate\Tests\Auth;

use Illuminate\Auth\DatabaseUserProvider;
use Illuminate\Auth\GenericUser;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Contracts\Hashing\Hasher;
use Illuminate\Database\Connection;
use Mockery as m;
use PHPUnit\Framework\TestCase;
use stdClass;

class AuthDatabaseUserProviderTest extends TestCase
{
    protected function tearDown(): void
    {
        m::close();
    }

    public function testRetrieveByIDReturnsUserWhenUserIsFound()
    {
        $conn = m::mock(Connection::class);
        $conn->shouldReceive('table')->once()->with('foo')->andReturn($conn);
        $conn->shouldReceive('find')->once()->with(1)->andReturn(['id' => 1, 'name' => 'Dayle']);
        $hasher = m::mock(Hasher::class);
        $provider = new DatabaseUserProvider($conn, $hasher, 'foo');
        $user = $provider->retrieveById(1);

        $this->assertInstanceOf(GenericUser::class, $user);
        $this->assertSame(1, $user->getAuthIdentifier());
        $this->assertSame('Dayle', $user->name);
    }

    public function testRetrieveByIDReturnsNullWhenUserIsNotFound()
    {
        $conn = m::mock(Connection::class);
        $conn->shouldReceive('table')->once()->with('foo')->andReturn($conn);
        $conn->shouldReceive('find')->once()->with(1)->andReturn(null);
        $hasher = m::mock(Hasher::class);
        $provider = new DatabaseUserProvider($conn, $hasher, 'foo');
        $user = $provider->retrieveById(1);

        $this->assertNull($user);
    }

    public function testRetrieveByTokenReturnsUser()
    {
        $mockUser = new stdClass;
        $mockUser->remember_token = 'a';

        $conn = m::mock(Connection::class);
        $conn->shouldReceive('table')->once()->with('foo')->andReturn($conn);
        $conn->shouldReceive('find')->once()->with(1)->andReturn($mockUser);
        $hasher = m::mock(Hasher::class);
        $provider = new DatabaseUserProvider($conn, $hasher, 'foo');
        $user = $provider->retrieveByToken(1, 'a');

        $this->assertEquals(new GenericUser((array) $mockUser), $user);
    }

    public function testRetrieveTokenWithBadIdentifierReturnsNull()
    {
        $conn = m::mock(Connection::class);
        $conn->shouldReceive('table')->once()->with('foo')->andReturn($conn);
        $conn->shouldReceive('find')->once()->with(1)->andReturn(null);
        $hasher = m::mock(Hasher::class);
        $provider = new DatabaseUserProvider($conn, $hasher, 'foo');
        $user = $provider->retrieveByToken(1, 'a');

        $this->assertNull($user);
    }

    public function testRetrieveByBadTokenReturnsNull()
    {
        $mockUser = new stdClass;
        $mockUser->remember_token = null;

        $conn = m::mock(Connection::class);
        $conn->shouldReceive('table')->once()->with('foo')->andReturn($conn);
        $conn->shouldReceive('find')->once()->with(1)->andReturn($mockUser);
        $hasher = m::mock(Hasher::class);
        $provider = new DatabaseUserProvider($conn, $hasher, 'foo');
        $user = $provider->retrieveByToken(1, 'a');

        $this->assertNull($user);
    }

    public function testRetrieveByCredentialsReturnsUserWhenUserIsFound()
    {
        $conn = m::mock(Connection::class);
        $conn->shouldReceive('table')->once()->with('foo')->andReturn($conn);
        $conn->shouldReceive('where')->once()->with('username', 'dayle');
        $conn->shouldReceive('whereIn')->once()->with('group', ['one', 'two']);
        $conn->shouldReceive('first')->once()->andReturn(['id' => 1, 'name' => 'taylor']);
        $hasher = m::mock(Hasher::class);
        $provider = new DatabaseUserProvider($conn, $hasher, 'foo');
        $user = $provider->retrieveByCredentials(['username' => 'dayle', 'password' => 'foo', 'group' => ['one', 'two']]);

        $this->assertInstanceOf(GenericUser::class, $user);
        $this->assertSame(1, $user->getAuthIdentifier());
        $this->assertSame('taylor', $user->name);
    }

    public function testRetrieveByCredentialsReturnsNullWhenUserIsFound()
    {
        $conn = m::mock(Connection::class);
        $conn->shouldReceive('table')->once()->with('foo')->andReturn($conn);
        $conn->shouldReceive('where')->once()->with('username', 'dayle');
        $conn->shouldReceive('first')->once()->andReturn(null);
        $hasher = m::mock(Hasher::class);
        $provider = new DatabaseUserProvider($conn, $hasher, 'foo');
        $user = $provider->retrieveByCredentials(['username' => 'dayle']);

        $this->assertNull($user);
    }

    public function testCredentialValidation()
    {
        $conn = m::mock(Connection::class);
        $hasher = m::mock(Hasher::class);
        $hasher->shouldReceive('check')->once()->with('plain', 'hash')->andReturn(true);
        $provider = new DatabaseUserProvider($conn, $hasher, 'foo');
        $user = m::mock(Authenticatable::class);
        $user->shouldReceive('getAuthPassword')->once()->andReturn('hash');
        $result = $provider->validateCredentials($user, ['password' => 'plain']);

        $this->assertTrue($result);
    }
}


text:
/**
 * ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
 * @version v5.0.6
 * @link http://www.ag-grid.com/
 * @license MIT
 */
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var context_1 = require("../context/context");
var HorizontalDragService = (function () {
    function HorizontalDragService() {
    }
    HorizontalDragService.prototype.addDragHandling = function (params) {
        params.eDraggableElement.addEventListener('mousedown', function (startEvent) {
            new DragInstance(params, startEvent);
        });
    };
    HorizontalDragService = __decorate([
        context_1.Bean('horizontalDragService'),
        __metadata('design:paramtypes', [])
    ], HorizontalDragService);
    return HorizontalDragService;
})();
exports.HorizontalDragService = HorizontalDragService;
var DragInstance = (function () {
    function DragInstance(params, startEvent) {
        this.mouseMove = this.onMouseMove.bind(this);
        this.mouseUp = this.onMouseUp.bind(this);
        this.mouseLeave = this.onMouseLeave.bind(this);
        this.lastDelta = 0;
        this.params = params;
        this.eDragParent = document.querySelector('body');
        this.dragStartX = startEvent.clientX;
        this.startEvent = startEvent;
        this.eDragParent.addEventListener('mousemove', this.mouseMove);
        this.eDragParent.addEventListener('mouseup', this.mouseUp);
        this.eDragParent.addEventListener('mouseleave', this.mouseLeave);
        this.draggingStarted = false;
        var startAfterPixelsExist = typeof params.startAfterPixels === 'number' && params.startAfterPixels > 0;
        if (!startAfterPixelsExist) {
            this.startDragging();
        }
    }
    DragInstance.prototype.startDragging = function () {
        this.draggingStarted = true;
        this.oldBodyCursor = this.params.eBody.style.cursor;
        this.oldParentCursor = this.eDragParent.style.cursor;
        this.oldMsUserSelect = this.eDragParent.style.msUserSelect;
        this.oldWebkitUserSelect = this.eDragParent.style.webkitUserSelect;
        // change the body cursor, so when drag moves out of the drag bar, the cursor is still 'resize' (or 'move'
        this.params.eBody.style.cursor = this.params.cursor;
        // same for outside the grid, we want to keep the resize (or move) cursor
        this.eDragParent.style.cursor = this.params.cursor;
        // we don't want text selection outside the grid (otherwise it looks weird as text highlights when we move)
        this.eDragParent.style.msUserSelect = 'none';
        this.eDragParent.style.webkitUserSelect = 'none';
        this.params.onDragStart(this.startEvent);
    };
    DragInstance.prototype.onMouseMove = function (moveEvent) {
        var newX = moveEvent.clientX;
        this.lastDelta = newX - this.dragStartX;
        if (!this.draggingStarted) {
            var dragExceededStartAfterPixels = Math.abs(this.lastDelta) >= this.params.startAfterPixels;
            if (dragExceededStartAfterPixels) {
                this.startDragging();
            }
        }
        if (this.draggingStarted) {
            this.params.onDragging(this.lastDelta, false);
        }
    };
    DragInstance.prototype.onMouseUp = function () {
        this.stopDragging();
    };
    DragInstance.prototype.onMouseLeave = function () {
        this.stopDragging();
    };
    DragInstance.prototype.stopDragging = function () {
        // reset cursor back to original cursor, if they were changed in the first place
        if (this.draggingStarted) {
            this.params.eBody.style.cursor = this.oldBodyCursor;
            this.eDragParent.style.cursor = this.oldParentCursor;
            this.eDragParent.style.msUserSelect = this.oldMsUserSelect;
            this.eDragParent.style.webkitUserSelect = this.oldWebkitUserSelect;
            this.params.onDragging(this.lastDelta, true);
        }
        // always remove the listeners, as these are always added
        this.eDragParent.removeEventListener('mousemove', this.mouseMove);
        this.eDragParent.removeEventListener('mouseup', this.mouseUp);
        this.eDragParent.removeEventListener('mouseleave', this.mouseLeave);
    };
    return DragInstance;
})();


text:
use strict;
use warnings;
package MongoDB::_Types;

# MongoDB type definitions

use version;
our $VERSION = 'v2.2.3';

use Type::Library
  -base,
  -declare => qw(
  ArrayOfHashRef
  AuthMechanism
  Boolish
  Booleanpm
  BSONCodec
  BSONDoc
  ClientSession
  CompressionType
  ZlibCompressionLevel
  ConnectType
  CursorType
  DBRefColl
  DBRefDB
  Document
  ErrorStr
  HashLike
  HeartbeatFreq
  HostAddress
  HostAddressList
  Intish
  IndexModel
  IndexModelList
  IxHash
  MaxStalenessNum
  MaybeHashRef
  MongoDBClient
  MongoDBCollection
  MongoDBDatabase
  BSONTimestamp
  NonEmptyStr
  NonNegNum
  Numish
  OID
  OrderedDoc
  PairArrayRef
  ReadPrefMode
  ReadConcern
  ReadPreference
  ServerDesc
  ServerType
  SingleChar
  SingleKeyHash
  Stringish
  TopologyType
  TransactionState
  WriteConcern
);

use Type::Utils -all;
use Types::Standard qw(
    Any
    Bool
    ArrayRef
    Dict
    HashRef
    Int
    Maybe
    Num
    Optional
    Overload
    Ref
    Str
    Undef
);

use Scalar::Util qw/reftype/;
use boolean 0.25;
use MongoDB::_Constants;
require Tie::IxHash;

#--------------------------------------------------------------------------#
# Type declarations (without inherited coercions)
#--------------------------------------------------------------------------#

declare Stringish, as Str|Overload['""'];

declare Numish, as Num|Overload['0+'];

# Types::Standard::Bool is overly restrictive, not allowing objects that
# overload boolification, and Overload['bool'] doesn't detect objects that
# overload via fallback, so we use this type for documentation purposes,
# but allow any actual type.
declare Boolish, as Any;

declare ArrayOfHashRef, as ArrayRef [HashRef];

enum AuthMechanism,
  [qw/NONE DEFAULT MONGODB-CR MONGODB-X509 GSSAPI PLAIN SCRAM-SHA-1 SCRAM-SHA-256/];

duck_type BSONCodec, [ qw/encode_one decode_one/ ];

class_type BSONDoc, { class => 'BSON::Doc' };

class_type ClientSession, { class => 'MongoDB::ClientSession' };

enum CompressionType, [qw/zlib zstd snappy/];

declare ZlibCompressionLevel, as Int,
  where { $_ >= -1 && $_ <= 9 },
  message { "zlib compression value must be value from -1 to 9" };

enum ConnectType, [qw/replicaSet direct none/];

enum CursorType, [qw/non_tailable tailable tailable_await/];

declare ErrorStr, as Stringish, where { defined($_) && length($_) }; # needs a true value

declare HashLike, as Ref, where { reftype($_) eq 'HASH' };

declare HeartbeatFreq, as Num,
  where { defined($_) && $_ >= 500 },
  message { "value must be at least 500" };

# XXX loose address validation for now.  Host part should really be hostname or
# IPv4/IPv6 literals
declare HostAddress, as Stringish,
  where { $_ =~ /^[^:]+:[0-9]+$/ and lc($_) eq $_ }, message {
    "Address '$_' either not lowercased or not formatted as 'hostname:port'"
  };

declare HostAddressList, as ArrayRef [HostAddress], message {
    "Address list <@$_> not all formatted as lowercased 'hostname:port' pairs"
};

declare Intish, as Numish, where { defined $_ and $_ == int($_) };

class_type IxHash, { class => 'Tie::IxHash' };

declare MaybeHashRef, as Maybe[ HashRef ];

class_type MongoDBClient, { class => 'MongoDB::MongoClient' };

class_type MongoDBCollection, { class => 'MongoDB::Collection' };

class_type MongoDBDatabase, { class => 'MongoDB::Database' };

class_type BSONTimestamp, { class => 'BSON::Timestamp' };

declare NonEmptyStr, as Stringish, where { defined $_ && length $_ };

declare NonNegNum, as Numish,
  where { defined($_) && $_ >= 0 },
  message { "value must be a non-negative number" };

declare MaxStalenessNum, as Numish,
  where { defined($_) && ( $_ > 0 || $_ == -1 ) },
  message { "value must be a positive number or -1" };

declare OID, as Str, where { /\A[0-9a-f]{24}\z/ }, message {
    "Value '$_' is not a valid OID"
};

declare PairArrayRef, as ArrayRef,
  where { @$_ % 2 == 0 };

enum ReadPrefMode,
  [qw/primary primaryPreferred secondary secondaryPreferred nearest/];

class_type ReadPreference, { class => 'MongoDB::ReadPreference' };

class_type ReadConcern, { class => 'MongoDB::ReadConcern' };

class_type ServerDesc, { class => 'MongoDB::_Server' };

enum ServerType,
  [
    qw/Standalone Mongos PossiblePrimary RSPrimary RSSecondary RSArbiter RSOther RSGhost Unknown/
  ];

declare SingleChar, as Str, where { length $_ eq 1 };

declare SingleKeyHash, as HashRef, where { 1 == scalar keys %$_ };

enum TopologyType,
  [qw/Single ReplicaSetNoPrimary ReplicaSetWithPrimary Sharded Direct Unknown/];

enum TransactionState,
  [ TXN_NONE, TXN_STARTING, TXN_IN_PROGRESS, TXN_COMMITTED, TXN_ABORTED ];

class_type WriteConcern, { class => 'MongoDB::WriteConcern' };

# after SingleKeyHash, PairArrayRef and IxHash
declare OrderedDoc, as BSONDoc|PairArrayRef|IxHash|SingleKeyHash;
declare Document, as HashRef|BSONDoc|PairArrayRef|IxHash|HashLike;

# after NonEmptyStr
declare DBRefColl, as NonEmptyStr;
declare DBRefDB, as NonEmptyStr|Undef;

# after OrderedDoc
declare IndexModel, as Dict [ keys => OrderedDoc, options => Optional [HashRef] ];
declare IndexModelList, as ArrayRef [IndexModel];

#--------------------------------------------------------------------------#
# Coercions
#--------------------------------------------------------------------------#

coerce ArrayOfHashRef, from HashRef, via { [$_] };

coerce BSONCodec, from HashRef,
  via { require BSON; BSON->new($_) };

coerce Boolish, from Any, via { !!$_ };

coerce DBRefColl, from MongoDBCollection, via { $_->name };

coerce DBRefDB, from MongoDBDatabase, via { $_->name };

coerce ErrorStr, from Str, via { $_ || "unspecified error" };

coerce ReadPrefMode, from Str, via { $_ = lc $_; s/_?preferred/Preferred/; $_ };

coerce IxHash, from HashRef, via { Tie::IxHash->new(%$_) };

coerce IxHash, from ArrayRef, via { Tie::IxHash->new(@$_) };

coerce IxHash, from HashLike, via { Tie::IxHash->new(%$_) };

coerce IxHash, from BSONDoc, via { Tie::IxHash->new(@$_) };

coerce OID, from Str, via { lc $_ };

coerce ReadPreference, from HashRef,
  via { require MongoDB::ReadPreference; MongoDB::ReadPreference->new($_) };

coerce ReadPreference, from Str,
  via { require MongoDB::ReadPreference; MongoDB::ReadPreference->new( mode => $_ ) };

coerce ReadPreference, from ArrayRef,
  via { require MongoDB::ReadPreference; MongoDB::ReadPreference->new( mode => $_->[0], tag_sets => $_->[1] ) };

coerce ReadConcern, from Str,
  via { require MongoDB::ReadConcern; MongoDB::ReadConcern->new( level => $_ ) };

coerce ReadConcern, from HashRef,
  via { require MongoDB::ReadConcern; MongoDB::ReadConcern->new($_) };

coerce WriteConcern, from HashRef,
  via { require MongoDB::WriteConcern; MongoDB::WriteConcern->new($_) };

1;


text:
class GiftsAddColumnAppPictureRelPath < ActiveRecord::Migration
  def change
    add_column :gifts, :app_picture_rel_path, :text
  end
end


text:
"use strict";

function ObserveBodyChange(mutations)
{
    $('#feedbackify').remove();
}

function DestroyEverything() {
  $('.headline-area').remove();
  $('.module.coffee-break').remove();
  $('.social-share').remove();
  $('.moon_phases').remove();
  $('.settings').remove();
  $('.signin:parent').remove();

  $('a[title="Nouvelles"]:parent').remove();
  $('a[title="Galeries"]:parent').remove();
  $('a[title="Télé"]:parent').remove();
  $('a[title="FAQ"]:parent').remove();
  $('h3:contains("Style de vie")').parent().remove();

  $('#leaderboard').remove();
  $('#sidebar').remove();
  $('#videos_brightcove-multiple-playlist-3-video-city-page').remove();
  $('#map-view').remove();
  $('#gallery').remove();
  $('#news-slider').remove();
  $('#main-footer').remove();
  $('#news').remove();
  $('#videos_brightcove-multiple-playlist-3-video-homepage').remove();

  $("body").each(function(){
    this.observer = new MutationObserver(ObserveBodyChange);
    var config = { attributes: false, childList: true, characterData: false, subtree: true};
    this.observer.observe(this, config);
  });
}

$(document).ready(DestroyEverything());


text:
<?php

/**
 * Redis Caching Class
 *
 * @package     Kotori
 * @subpackage  Cache
 * @author      Kokororin
 * @link        https://kotori.love
 */
namespace Kotori\Core\Cache;

use Kotori\Core\Container;
use Kotori\Exception\CacheException;
use RedisException;

class Redis
{
    /**
     * Default config
     *
     * @var array
     */
    protected $redisConf = [
        'host' => '127.0.0.1',
        'password' => null,
        'port' => 6379,
        'timeout' => 0,
        'database' => 0,
    ];

    /**
     * Redis connection
     *
     * @var Redis
     */
    protected $redis;

    /**
     * Class constructor
     *
     * Setup Redis
     *
     * Loads Redis config file if present. Will halt execution
     * if a Redis connection can't be established.
     *
     * @param   array $config
     *
     * @throws \Kotori\Exception\CacheException
     */
    public function __construct($config = [])
    {
        if (!$this->isSupported()) {
            throw new CacheException('Failed to create Redis object; extension not loaded?');
        }

        if (empty($config)) {
            $config = Container::get('config')->get('cache');
            $config = array_merge($this->redisConf, $config);
        }

        $this->redis = new \Redis();

        try {
            if (!$this->redis->connect($config['host'], ($config['host'][0] === '/' ? 0 : $config['port']), $config['timeout'])) {
                throw new CacheException('Redis connection failed. Check your configuration.');
            }

            if (isset($config['password']) && !$this->redis->auth($config['password'])) {
                throw new CacheException('Redis authentication failed.');
            }

            if (isset($config['database']) && $config['database'] > 0 && !$this->redis->select($config['database'])) {
                throw new CacheException('Redis select database failed.');
            }
        } catch (RedisException $e) {
            throw new CacheException('Redis connection refused (' . $e->getMessage() . ')');
        }
    }

    /**
     * Get cache
     *
     * @param   string  $key
     * @return  mixed
     */
    public function get($key)
    {
        $value = $this->redis->hMGet($key, ['type', 'value']);

        if (!isset($value['type'], $value['value']) || $value['value'] === false) {
            return false;
        }

        switch ($value['type']) {
            case 'array':
            case 'object':
                return unserialize($value['value']);
            case 'boolean':
            case 'integer':
            case 'double': // Yes, 'double' is returned and NOT 'float'
            case 'string':
            case 'NULL':
                return settype($value['value'], $value['type'])
                ? $value['value']
                : false;
            case 'resource':
            default:
                return false;
        }
    }

    /**
     * Save cache
     *
     * @param   string    $key
     * @param   mixed     $value
     * @param   int       $ttl
     * @return  boolean
     */
    public function set($key, $value, $ttl = 60)
    {
        $dataType = gettype($value);

        switch ($dataType) {
            case 'array':
            case 'object':
                $value = serialize($value);
                break;
            case 'boolean':
            case 'integer':
            case 'double': // Yes, 'double' is returned and NOT 'float'
            case 'string':
            case 'NULL':
                break;
            case 'resource':
            default:
                return false;
        }

        if (!$this->redis->hMSet($key, ['type' => $dataType, 'value' => $value])) {
            return false;
        } elseif ($ttl) {
            $this->redis->expireAt($key, time() + $ttl);
        }

        return true;
    }

    /**
     * Delete from cache
     *
     * @param   string  $key
     * @return  boolean
     */
    public function delete($key)
    {
        return ($this->redis->del($key) === 1);
    }

    /**
     * Clean cache
     *
     * @return  boolean
     */
    public function clear()
    {
        return $this->redis->flushDB();
    }

    /**
     * Check if Redis driver is supported
     *
     * @return  boolean
     */
    public function isSupported()
    {
        return extension_loaded('redis');
    }

    /**
     * Class destructor
     *
     * Closes the connection to Redis if present.
     */
    public function __destruct()
    {
        if ($this->redis) {
            $this->redis->close();
        }
    }
}


text:
/*
*  Components are elements that attach to Nodes or other objects to add functionality
*  Some important components are Transform, Light or Camera
*
*	*  ctor: must accept an optional parameter with the serialized data
*	*  onAddedToNode: triggered when added to node
*	*  onRemovedFromNode: triggered when removed from node
*	*  onAddedToScene: triggered when the node is added to the scene
*	*  onRemovedFromScene: triggered when the node is removed from the scene
*	*  serialize: returns a serialized version packed in an object
*	*  configure: recieves an object to unserialize and configure this instance
*	*  getResources: adds to the object the resources to load
*	*  _root contains the node where the component is added
*
*	*  use the LEvent system to hook events to the node or the scene
*	*  never share the same component instance between two nodes
*
*/

function Component(o)
{
	if(o)
		this.configure(o);
}

//default methods inserted in components that doesnt have a configure or serialize method
Component.prototype.configure = function(o)
{
	if(!o)
		return;
	if(o.uid)
	{
		//special case, uid must never be enumerable to avoid showing it in the editor
		if(this.uid === undefined && !Object.hasOwnProperty(this, "uid"))
			Object.defineProperty(this, "uid", { value: o.uid, enumerable: false, writable: true });
		else
			this.uid = o.uid;
	}
	LS.cloneObject(o, this);
}

Component.prototype.serialize = function()
{
	var o = LS.cloneObject(this);
	if(this.uid) //special case, not enumerable
		o.uid = this.uid;
	return o;
}

Component.prototype.createProperty = function( name, value, type )
{
	if(type)
		this.constructor[ "@" + name ] = { type: type };

	//basic type
	if(value.constructor === Number || value.constructor === String || value.constructor === Boolean)
	{
		this[ name ] = value;
		return;
	}

	//vector type
	if(value.constructor === Float32Array)
	{
		var private_name = "_" + name;
		value = new Float32Array( value ); //clone
		this[ private_name ] = value; //this could be removed...

		Object.defineProperty( this, name, {
			get: function() { return value; },
			set: function(v) { value.set( v ); },
			enumerable: true
		});
	}
}

Component.prototype.getLocator = function()
{
	if(!this._root)
		return "";
	return this._root.uid + "/" + this.uid;
}

LS.Component = Component;


text:
[![Build Status](https://travis-ci.org/danvk/expandable-image-grid.svg?branch=master)](https://travis-ci.org/danvk/expandable-image-grid.svg?branch=master)

expandable-image-grid
=====================

A grid of expandable images, similar to Google Image Search.

Features:
  1. Dynamic resizing of images to get a clean right margin.
  2. Animated inline expansion of images.
  3. Flexible content in the expanded view.

See demo.html to get a sense for how this works.

Based on [this article on codrops](http://tympanus.net/codrops/?p=14530) and [this project](https://github.com/codrops/ThumbnailGridExpandingPreview/blob/master/README.md).


text:
class Board(object):

    def __init__(self, spots=None):
        self.spots = spots or [1, 2, 3, 4, 5, 6, 7, 8, 9]

    def place_move(self, mark, spot):
        self.spots[spot - 1] = mark

    def is_spot_available(self, spot):
        return spot in self.available_spots()

    def available_spots(self):
        available_spots = []
        for idx, spot in enumerate(self.spots):
            if isinstance(spot, int):
                available_spots.append(idx + 1)
        return available_spots

    def horizontal_rows(self):
        horizontal_rows = []
        horizontal_rows.append(self.spots[0:3])
        horizontal_rows.append(self.spots[3:6])
        horizontal_rows.append(self.spots[6:9])
        return horizontal_rows

    def vertical_rows(self):
        vertical_rows = []
        vertical_rows.append([self.spots[i] for i in 0, 3, 6])
        vertical_rows.append([self.spots[i] for i in 1, 4, 7])
        vertical_rows.append([self.spots[i] for i in 2, 5, 8])
        return vertical_rows

    def diagonal_rows(self):
        diagonal_rows = []
        diagonal_rows.append([self.spots[i] for i in 0, 4, 8])
        diagonal_rows.append([self.spots[i] for i in 2, 4, 6])
        return diagonal_rows

    def get_all_rows(self):
        horizontal = self.horizontal_rows()
        vertical = self.vertical_rows()
        diagonal = self.diagonal_rows()
        return horizontal + vertical + diagonal


text:
const express = require('express');
const router = express();
const db = require('APP/db');
const ParentCompany = db.model('parentCompany');

module.exports = require('express')
	.Router()
	.get('/', (req, res, next) => {
		ParentCompany.findAll({})
			.then(companies => {
				res.json(companies);
			})
			.catch(next);
	});


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
CaaersSerializerUtilTest
</TITLE>

<META NAME="keywords" CONTENT="gov.nih.nci.cabig.caaers.utils.CaaersSerializerUtilTest class">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

gov.nih.nci.cabig.caaers.utils

Class CaaersSerializerUtilTest

java.lang.Object
  junit.framework.Assert
      junit.framework.TestCase
          gov.nih.nci.cabig.caaers.utils.CaaersSerializerUtilTest

All Implemented Interfaces:
junit.framework.Test

public class CaaersSerializerUtilTest
extends junit.framework.TestCase

Author:

Monish

Constructor Summary

CaaersSerializerUtilTest()

Method Summary

 void
testSerializeException()

Methods inherited from class junit.framework.TestCase

countTestCases, createResult, getName, run, run, runBare, runTest, setName, setUp, tearDown, toString

Methods inherited from class junit.framework.Assert

assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertFalse, assertFalse, assertNotNull, assertNotNull, assertNotSame, assertNotSame, assertNull, assertNull, assertSame, assertSame, assertTrue, assertTrue, fail, fail

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

CaaersSerializerUtilTest

public CaaersSerializerUtilTest()

Method Detail

testSerializeException

public void testSerializeException()

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
.. _secvar/edk2:

Skiboot edk2-compatible Secure Variable Backend
===============================================

Overview
--------

The edk2 secure variable backend for skiboot borrows from edk2 concepts
such as the three key hierarchy (PK, KEK, and db), and a similar
structure. In general, variable updates must be signed with a key
of a higher level. So, updates to the db must be signed with a key stored
in the KEK; updates to the KEK must be signed with the PK. Updates to the
PK must be signed with the previous PK (if any).

Variables are stored in the efi signature list format, and updates are a
signed variant that includes an authentication header.

If no PK is currently enrolled, the system is considered to be in "Setup
Mode". Any key can be enrolled without signature checks. However, once a
PK is enrolled, the system switches to "User Mode", and each update must
now be signed according to the hierarchy. Furthermore, when in "User
Mode", the backend initialized the ``os-secure-mode`` device tree flag,
signaling to the kernel that we are in secure mode.

Updates are processed sequentially, in the order that they were provided
in the update queue. If any update fails to validate, appears to be
malformed, or any other error occurs, NO updates will not be applied.
This includes updates that may have successfully applied prior to the
error. The system will continue in an error state, reporting the error
reason via the ``update-status`` device tree property.

P9 Special Case for the Platform Key
------------------------------------

Due to the powerful nature of the platform key and the lack of lockable
flash, the edk2 backend will store the PK in TPM NV rather than PNOR on
P9 systems. (TODO expand on this)

Update Status Return Codes
--------------------------

TODO, edk2 driver needs to actually return these properly first

Device Tree Bindings
--------------------

TODO


text:
<?php

defined('BASEPATH') OR exit('No direct script access allowed');

$lang['projects_create'] = 'Criar';
$lang['projects_edit'] = 'Editar';
$lang['projects_remove'] = 'Remover';


text:
package org.ovirt.engine.core.bll.gluster;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.spy;

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

import org.junit.Test;
import org.mockito.Mock;
import org.ovirt.engine.core.bll.BaseCommandTest;
import org.ovirt.engine.core.common.action.gluster.GlusterVolumeReplaceBrickActionParameters;
import org.ovirt.engine.core.common.businessentities.Cluster;
import org.ovirt.engine.core.common.businessentities.VDS;
import org.ovirt.engine.core.common.businessentities.VDSStatus;
import org.ovirt.engine.core.common.businessentities.VdsStatic;
import org.ovirt.engine.core.common.businessentities.gluster.AccessProtocol;
import org.ovirt.engine.core.common.businessentities.gluster.GlusterBrickEntity;
import org.ovirt.engine.core.common.businessentities.gluster.GlusterStatus;
import org.ovirt.engine.core.common.businessentities.gluster.GlusterTaskOperation;
import org.ovirt.engine.core.common.businessentities.gluster.GlusterVolumeEntity;
import org.ovirt.engine.core.common.businessentities.gluster.GlusterVolumeType;
import org.ovirt.engine.core.common.businessentities.gluster.TransportType;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.compat.Version;
import org.ovirt.engine.core.dao.VdsStaticDao;
import org.ovirt.engine.core.dao.gluster.GlusterVolumeDao;
import org.ovirt.engine.core.dao.network.InterfaceDao;
import org.ovirt.engine.core.dao.network.NetworkDao;

public class ReplaceGlusterVolumeBrickCommandTest extends BaseCommandTest {

    @Mock
    GlusterVolumeDao volumeDao;

    @Mock
    VdsStaticDao vdsStaticDao;

    @Mock
    NetworkDao networkDao;

    @Mock
    InterfaceDao interfaceDao;

    private static final String serverName = "myhost";
    private final Guid clusterId = new Guid("c0dd8ca3-95dd-44ad-a88a-440a6e3d8106");
    private final Guid serverId = new Guid("d7f10a21-bbf2-4ffd-aab6-4da0b3b2ccec");
    private final Guid volumeId1 = new Guid("8bc6f108-c0ef-43ab-ba20-ec41107220f5");
    private final Guid volumeId2 = new Guid("b2cb2f73-fab3-4a42-93f0-d5e4c069a43e");
    private final Guid volumeId3 = new Guid("000000000000-0000-0000-0000-00000003");
    private final Guid volumeId4 = new Guid("000000000000-0000-0000-0000-00000004");

    /**
     * The command under test.
     */
    private ReplaceGlusterVolumeBrickCommand cmd;

    private void prepareMocks(ReplaceGlusterVolumeBrickCommand command) {
        doReturn(volumeDao).when(command).getGlusterVolumeDao();
        doReturn(vdsStaticDao).when(command).getVdsStaticDao();
        doReturn(networkDao).when(command).getNetworkDao();
        doReturn(interfaceDao).when(command).getInterfaceDao();
        doReturn(getVds(VDSStatus.Up)).when(command).getUpServer();
        doReturn(getDistributedVolume(volumeId1)).when(volumeDao).getById(volumeId1);
        doReturn(getDistributedVolume(volumeId2)).when(volumeDao).getById(volumeId2);
        doReturn(getReplicatedVolume(volumeId3, 2)).when(volumeDao).getById(volumeId3);
        doReturn(getReplicatedVolume(volumeId4, 4)).when(volumeDao).getById(volumeId4);
        doReturn(null).when(volumeDao).getById(null);
        doReturn(getVdsStatic()).when(vdsStaticDao).get(serverId);
        doReturn(getCluster()).when(command).getCluster();
    }

    private Cluster getCluster() {
        Cluster cluster = new Cluster();
        cluster.setId(clusterId);
        cluster.setVirtService(false);
        cluster.setGlusterService(true);
        cluster.setCompatibilityVersion(Version.v3_1);
        return cluster;
    }

    private VDS getVds(VDSStatus status) {
        VDS vds = new VDS();
        vds.setId(Guid.newGuid());
        vds.setVdsName("gfs1");
        vds.setClusterId(clusterId);
        vds.setStatus(status);
        return vds;
    }

    private VdsStatic getVdsStatic() {
        VdsStatic vds = new VdsStatic();
        vds.setClusterId(clusterId);
        vds.setHostName(serverName);
        return vds;
    }

    private GlusterVolumeEntity getDistributedVolume(Guid volumeId) {
        GlusterVolumeEntity volume = getVolume(volumeId);
        volume.setStatus((volumeId == volumeId1) ? GlusterStatus.UP : GlusterStatus.DOWN);
        volume.setBricks(getBricks(volumeId, "distrib", 2));
        volume.setVolumeType(GlusterVolumeType.DISTRIBUTE);
        volume.setClusterId(clusterId);
        return volume;
    }

    private GlusterVolumeEntity getReplicatedVolume(Guid volumeId, int brickCount) {
        GlusterVolumeEntity volume = getVolume(volumeId);
        volume.setStatus(GlusterStatus.UP);
        volume.setBricks(getBricks(volumeId, "repl", brickCount));
        volume.setVolumeType(GlusterVolumeType.REPLICATE);
        volume.setReplicaCount(brickCount);
        volume.setClusterId(clusterId);
        return volume;
    }

    private GlusterVolumeEntity getVolume(Guid id) {
        GlusterVolumeEntity volumeEntity = new GlusterVolumeEntity();
        volumeEntity.setId(id);
        volumeEntity.setName("test-vol");
        volumeEntity.addAccessProtocol(AccessProtocol.GLUSTER);
        volumeEntity.addTransportType(TransportType.TCP);
        return volumeEntity;
    }

    private List<GlusterBrickEntity> getBricks(Guid volumeId, String dirPrefix, int n) {
        List<GlusterBrickEntity> bricks = new ArrayList<>();
        GlusterBrickEntity brick;
        for (Integer i = 0; i < n; i++) {
            brick = new GlusterBrickEntity();
            brick.setVolumeId(volumeId);
            brick.setServerId(serverId);
            brick.setServerName(serverName);
            brick.setBrickDirectory("/tmp/" + dirPrefix + i.toString());
            brick.setStatus(GlusterStatus.UP);
            bricks.add(brick);
        }
        return bricks;
    }

    private ReplaceGlusterVolumeBrickCommand createTestCommand1(Guid volumeId) {
        return new ReplaceGlusterVolumeBrickCommand(new GlusterVolumeReplaceBrickActionParameters(volumeId,
                GlusterTaskOperation.START,
                getBricks(volumeId, "distrib", 1).get(0),
                getBricks(volumeId, "new", 1).get(0), false));
    }

    private ReplaceGlusterVolumeBrickCommand createTestCommand2(Guid volumeId) {
        return new ReplaceGlusterVolumeBrickCommand(new GlusterVolumeReplaceBrickActionParameters(volumeId,
                GlusterTaskOperation.START,
                null,
                getBricks(volumeId, "", 1).get(0), false));
    }

    @Test
    public void validateSucceedsOnUpVolume() {
        cmd = spy(createTestCommand1(volumeId1));
        prepareMocks(cmd);
        assertTrue(cmd.validate());
    }

    @Test
    public void validateFailesOnDownVolume() {
        cmd = spy(createTestCommand1(volumeId2));
        prepareMocks(cmd);
        assertFalse(cmd.validate());
    }

    @Test
    public void validateFailsOnInvalidBrick() {
        cmd = spy(createTestCommand1(volumeId3));
        prepareMocks(cmd);
        assertFalse(cmd.validate());
    }

    @Test
    public void validateFailsOnNull() {
        cmd = spy(createTestCommand1(null));
        prepareMocks(cmd);
        assertFalse(cmd.validate());
    }

    @Test
    public void validateFailsOnNoBrick() {
        cmd = spy(createTestCommand2(volumeId4));
        prepareMocks(cmd);
        assertFalse(cmd.validate());
    }

}


text:
Date: Thu, 21 Nov 1996 20:48:56 GMT
Server: NCSA/1.4.2
Content-type: text/html
Last-modified: Thu, 07 Nov 1996 22:19:42 GMT
Content-length: 5172

<title>Jamie Callan, (callan@cs.umass.edu)</title>
<!WA0>

Jamie Callan

Assistant Director

Center for Intelligent Information Retrieval

<!WA1>
Department of Computer Science

Lederle Graduate Research Center

Box 34610

<!WA2>
University of Massachusetts

Amherst, MA  01003-4610, USA

LGRC A-235

Phone:  (413) 545-4878

Fax:  (413) 545-1249

Email:  callan@cs.umass.edu

Jamie Callan is a Research Assistant Professor.  His research includes
improved methods of representing and retrieving full-text documents,
high speed document filtering algorithms, and algorithms that learn a
person's information needs.  He also works actively with members of
the
<!WA3>Center for Intelligent Information
Retrieval
to define technology
transfer projects involving the
<!WA4>INQUERY
information retrieval and InRoute document filtering systems.

Recent Publications:

Callan, J.  (1996).
<!WA5>
"Document Filtering With Inference Networks."

In  Proceedings of the Nineteenth Annual International ACM SIGIR Conference
on Research and Development in Information Retrieval, Zurich, Switzerland.
(pp. 262-269).

Lewis, D.D., Schapire, R.E., Callan, J.P. and Papka, R. (1996).
<!WA6>
"Training algorithms for linear text classifiers."

In  Proceedings of the Nineteenth Annual International ACM SIGIR Conference
on Research and Development in Information Retrieval, Zurich, Switzerland.
(pp. 298-306).

Allan, J., Ballesteros, L., Callan, J.P., Croft, W.B., and Lu, Z.  (In press).
<!WA7>
"Recent experiments with INQUERY."
In Proceedings of the Fourth Text REtrieval Conference (TREC-4).
Gaithersburg, MD: National Institute of Standards and Technology, special
publication.

Callan, J.P., Lu, Z., and Croft, W.B.  (1995).
<!WA8>
"Searching Distributed Collections with Inference Networks."
In  Proceedings of the Eighteenth Annual International ACM SIGIR Conference
on Research and Development in Information Retrieval, Seattle, WA.
(pp. 21-28).

DeFazio, S., Daoud, A., Smith, L.A., Srinivasan, J., Croft, B., and Callan, J.
(1995).
"Integrating IR and RDBMS Using Cooperative Indexing."
In  Proceedings of the Eighteenth Annual International ACM SIGIR Conference
on Research and Development in Information Retrieval, Seattle, WA.
(pp. 84-92).

Callan, J.P., Croft, W.B., and Broglio, J. (1995).
<!WA9>
"TREC and TIPSTER Experiments With INQUERY."
Information Processing and Management, 31(3),
pp. 327-343.

Broglio, J., Callan, J.P., Croft, W.B., and Nachbar, D.W. (1995).
<!WA10>
"Document Retrieval and Routing Using the INQUERY System."
In Proceedings of the Third Text REtrieval Conference (TREC-3).
Gaithersburg, MD: National Institute of Standards and Technology, special
publication 500-225, pp. 29-38.

Brown, E.W., Callan, J.P., and Croft, W.B. (1994).
<!WA11>
"Fast incremental indexing for full-text information retrieval."
In  Proceedings of the 20th International Conference on Very Large
Databases (VLDB), Santiago, Chile, pp. 192-202.

 Callan, J.P.  (1994).
<!WA12>
"Passage-level evidence in document retrieval."
In  Proceedings of the Seventeenth Annual International ACM SIGIR
Conference on Research and Development in Information Retrieval,
Dublin, Ireland, pp. 302-310.

 Brown, E.W., Callan, J.P., Croft, W.B., and Moss, J.E.B.  (1994).
<!WA13>
"Supporting full-text information retrieval with a persistent
object-store."
In  Proceedings of the Fourth International Conference on Extending
Database Technology, Cambridge, England, pp. 365-378.

 Callan, J.P., and Croft, W.B.  (1993).
<!WA14>
"An evaluation of query processing strategies using the TIPSTER
collection."
In  Proceedings of the Sixteenth Annual International ACM SIGIR Conference
on Research and Development in Information Retrieval, (pp. 347-355).
Pittsburgh, PA: Association for Computing Machinery.

  Callan, J.P., Croft, W.B., and Harding, S.M. (1992).
<!WA15>
"The INQUERY retrieval system."
In  Proceedings of the Third International Conference on Database and
Expert Systems Applications, (pp. 78-83).  Valencia, Spain:
Springer-Verlag.

Last update was August 27, 1996.
<address>
<!WA16>callan@cs.umass.edu
</address>


text:
package namespaceidx

import (
	"testing"

	nsmodel "github.com/contiv/vpp/plugins/ksr/model/namespace"
	"github.com/ligato/cn-infra/logging/logrus"
	"github.com/onsi/gomega"
)

func TestNewConfigIndex(t *testing.T) {
	gomega.RegisterTestingT(t)

	idx := NewConfigIndex(logrus.DefaultLogger(), "title")
	gomega.Expect(idx).NotTo(gomega.BeNil())
}

func TestRegisterUnregister(t *testing.T) {
	gomega.RegisterTestingT(t)

	idx := NewConfigIndex(logrus.DefaultLogger(), "title")
	gomega.Expect(idx).NotTo(gomega.BeNil())

	const (
		namespaceIDone   = "default"
		namespaceIDtwo   = "pepsi"
		namespaceIDthree = "coke"
	)

	namespaceDataOne := &nsmodel.Namespace{
		Name: namespaceIDone,
		Label: []*nsmodel.Namespace_Label{
			{
				Key:   "project",
				Value: "ts1",
			},
			{
				Key:   "project",
				Value: "ts2",
			},
		},
	}
	namespaceDataTwo := &nsmodel.Namespace{
		Name: namespaceIDone,
		Label: []*nsmodel.Namespace_Label{
			{
				Key:   "project",
				Value: "ts1",
			},
		},
	}
	namespaceDataThree := &nsmodel.Namespace{
		Name: namespaceIDone,
		Label: []*nsmodel.Namespace_Label{
			{
				Key:   "project",
				Value: "ts2",
			},
		},
	}

	res := idx.ListAll()
	gomega.Expect(res).To(gomega.BeNil())

	idx.RegisterNamespace(namespaceIDone, namespaceDataOne)
	idx.RegisterNamespace(namespaceIDtwo, namespaceDataTwo)
	idx.RegisterNamespace(namespaceIDthree, namespaceDataThree)

	found, data := idx.LookupNamespace(namespaceIDone)
	gomega.Expect(found).To(gomega.BeTrue())
	gomega.Expect(data).To(gomega.BeIdenticalTo(namespaceDataOne))

	found, data = idx.LookupNamespace(namespaceIDtwo)
	gomega.Expect(found).To(gomega.BeTrue())
	gomega.Expect(data).To(gomega.BeIdenticalTo(namespaceDataTwo))

	found, data = idx.LookupNamespace(namespaceIDthree)
	gomega.Expect(found).To(gomega.BeTrue())
	gomega.Expect(data).To(gomega.BeIdenticalTo(namespaceDataThree))

	idx.UnRegisterNamespace(namespaceIDone)
	found, _ = idx.LookupNamespace(namespaceIDone)
	gomega.Expect(found).To(gomega.BeFalse())

	idx.UnRegisterNamespace(namespaceIDtwo)
	found, _ = idx.LookupNamespace(namespaceIDtwo)
	gomega.Expect(found).To(gomega.BeFalse())

	idx.UnRegisterNamespace(namespaceIDthree)
	found, _ = idx.LookupNamespace(namespaceIDthree)
	gomega.Expect(found).To(gomega.BeFalse())

	// unregistering of non-existing item does nothing
	idx.UnRegisterNamespace(namespaceIDthree)

}

func TestSecondaryIndexLookup(t *testing.T) {
	gomega.RegisterTestingT(t)

	idx := NewConfigIndex(logrus.DefaultLogger(), "title")
	gomega.Expect(idx).NotTo(gomega.BeNil())

	const (
		namespaceIDone   = "default"
		namespaceIDtwo   = "pepsi"
		namespaceIDthree = "coke"
		namespaceIDFour  = "nike"
	)

	const (
		label1 = "project/ts1"
		label2 = "project/ts2"
		key1   = "project"
		key2   = "random"
	)

	namespaceDataOne := &nsmodel.Namespace{
		Name: namespaceIDone,
		Label: []*nsmodel.Namespace_Label{
			{
				Key:   "project",
				Value: "ts1",
			},
			{
				Key:   "project",
				Value: "ts2",
			},
		},
	}
	namespaceDataTwo := &nsmodel.Namespace{
		Name: namespaceIDtwo,
		Label: []*nsmodel.Namespace_Label{
			{
				Key:   "project",
				Value: "ts1",
			},
		},
	}
	namespaceDataThree := &nsmodel.Namespace{
		Name: namespaceIDthree,
		Label: []*nsmodel.Namespace_Label{
			{
				Key:   "project",
				Value: "ts2",
			},
		},
	}
	namespaceDataFour := &nsmodel.Namespace{
		Name: namespaceIDFour,
		Label: []*nsmodel.Namespace_Label{
			{
				Key:   "random",
				Value: "ts5",
			},
		},
	}

	idx.RegisterNamespace(namespaceIDone, namespaceDataOne)
	idx.RegisterNamespace(namespaceIDtwo, namespaceDataTwo)
	idx.RegisterNamespace(namespaceIDthree, namespaceDataThree)
	idx.RegisterNamespace(namespaceIDFour, namespaceDataFour)

	all := idx.ListAll()
	gomega.Expect(all).To(gomega.ContainElement(namespaceIDone))
	gomega.Expect(all).To(gomega.ContainElement(namespaceIDtwo))
	gomega.Expect(all).To(gomega.ContainElement(namespaceIDthree))
	gomega.Expect(all).To(gomega.ContainElement(namespaceIDFour))

	lsMatch := idx.LookupNamespacesByLabelSelector(label1)
	gomega.Expect(lsMatch).To(gomega.ContainElement(namespaceIDone))
	gomega.Expect(lsMatch).To(gomega.ContainElement(namespaceIDtwo))

	lsMatch = idx.LookupNamespacesByLabelSelector(label2)
	gomega.Expect(lsMatch).To(gomega.ContainElement(namespaceIDone))
	gomega.Expect(lsMatch).To(gomega.ContainElement(namespaceIDthree))

	keyMatch := idx.LookupNamespacesByKey(key2)
	gomega.Expect(keyMatch).To(gomega.ContainElement(namespaceIDFour))

	keyMatch = idx.LookupNamespacesByKey(key1)
	gomega.Expect(all).To(gomega.ContainElement(namespaceIDone))
	gomega.Expect(all).To(gomega.ContainElement(namespaceIDtwo))
	gomega.Expect(all).To(gomega.ContainElement(namespaceIDthree))
}


text:
download a chart from a repository and (optionally) unpack it in local directory

### Synopsis

Retrieve a package from a package repository, and download it locally.

This is useful for fetching packages to inspect, modify, or repackage. It can
also be used to perform cryptographic verification of a chart without installing
the chart.

There are options for unpacking the chart after download. This will create a
directory for the chart and uncomparess into that directory.

If the --verify flag is specified, the requested chart MUST have a provenance
file, and MUST pass the verification process. Failure in any part of this will
result in an error, and the chart will not be saved locally.

```
helm fetch [flags] [chart URL | repo/chartname] [...]
```

### Options

```
      --ca-file string       verify certificates of HTTPS-enabled servers using this CA bundle
      --cert-file string     identify HTTPS client using this SSL certificate file
  -d, --destination string   location to write the chart. If this and tardir are specified, tardir is appended to this (default ".")
      --devel                use development versions, too. Equivalent to version '>0.0.0-a'. If --version is set, this is ignored.
      --key-file string      identify HTTPS client using this SSL key file
      --keyring string       keyring containing public keys (default "~/.gnupg/pubring.gpg")
      --prov                 fetch the provenance file, but don't perform verification
      --repo string          chart repository url where to locate the requested chart
      --untar                if set to true, will untar the chart after downloading it
      --untardir string      if untar is specified, this flag specifies the name of the directory into which the chart is expanded (default ".")
      --verify               verify the package against its signature
      --version string       specific version of a chart. Without this, the latest version is fetched
```

### Options inherited from parent commands

```
      --debug                     enable verbose output
      --home string               location of your Helm config. Overrides $HELM_HOME (default "$HOME/.helm")
      --host string               address of tiller. Overrides $HELM_HOST
      --kube-context string       name of the kubeconfig context to use
      --tiller-namespace string   namespace of tiller (default "kube-system")
```

### SEE ALSO
* [helm](helm.md)	 - The Helm package manager for Kubernetes.

###### Auto generated by spf13/cobra on 29-May-2017


text:
package org.camunda.bpm.engine.impl.cmd;

import org.camunda.bpm.engine.history.UserOperationLogEntry;
import org.camunda.bpm.engine.impl.interceptor.CommandContext;
import org.camunda.bpm.engine.impl.persistence.entity.PropertyChange;

/**
 * @author Danny Gräf
 */
public class DeleteUserIdentityLinkCmd extends DeleteIdentityLinkCmd {

  private static final long serialVersionUID = 1L;

  public DeleteUserIdentityLinkCmd(String taskId, String userId, String type) {
    super(taskId, userId, null, type);
  }

  @Override
  public Void execute(CommandContext commandContext) {
    super.execute(commandContext);

    PropertyChange propertyChange = new PropertyChange(type, null, userId);

    commandContext.getOperationLogManager()
        .logLinkOperation(UserOperationLogEntry.OPERATION_TYPE_DELETE_USER_LINK, task, propertyChange);

    return null;
  }
}


text:
from importlib import import_module

class VirgaException(Exception):
    """Custom exception for Virga."""

def get_provider_class(args: any) -> any:
    """
    Return an instance of the Provider based on the name in the configuration.

    :param args: Command line args
    :return: An instance of the Provider
    """
    try:
        provider_module = import_module('virga.providers.%s' % args.provider)
        return provider_module.Provider(args)
    except ModuleNotFoundError:
        raise VirgaException('Provider module not found')
    except AttributeError:
        raise VirgaException('Provider class not found')