text:
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
                        unicode_literals, with_statement)

from abc import abstractproperty
from collections import MutableMapping, MutableSequence

import six

from pants.engine.exp.addressable import SubclassesOf, SuperclassesOf, addressable, addressable_list
from pants.engine.exp.objects import Serializable, SerializableFactory, Validatable, ValidationError
from pants.util.meta import AbstractClass

def _normalize_utf8_keys(kwargs):
  """When kwargs are passed literally in a source file, their keys are ascii: normalize."""
  if any(type(key) is six.binary_type for key in kwargs.keys()):
    # This is to preserve the original dict type for kwargs.
    dict_type = type(kwargs)
    return dict_type([(six.text_type(k), v) for k, v in kwargs.items()])
  return kwargs

class Struct(Serializable, SerializableFactory, Validatable):
  """A serializable object.

  A Struct is composed of basic python builtin types and other high-level Structs.
  Structs can carry a name in which case they become addressable and can be reused.
  """

  # Fields dealing with inheritance.
  _INHERITANCE_FIELDS = {'extends', 'merges'}
  # The type alias for an instance overwrites any inherited type_alias field.
  _TYPE_ALIAS_FIELD = 'type_alias'
  # The field that indicates whether a Struct is abstract (and should thus skip validation).
  _ABSTRACT_FIELD = 'abstract'
  # Fields that should not be inherited.
  _UNINHERITABLE_FIELDS = _INHERITANCE_FIELDS | {_TYPE_ALIAS_FIELD, _ABSTRACT_FIELD}
  # Fields that are only intended for consumption by the Struct baseclass.
  _INTERNAL_FIELDS = _INHERITANCE_FIELDS | {_ABSTRACT_FIELD}

  def __init__(self, abstract=False, extends=None, merges=None, type_alias=None, **kwargs):
    """Creates a new struct data blob.

    By default Structs are anonymous (un-named), concrete (not `abstract`), and they neither
    inherit nor merge another Struct.

    Inheritance is allowed via the `extends` and `merges` channels.  An object inherits all
    attributes from the object it extends, overwriting any attributes in common with the extended
    object with its own.  The relationship is an "overlay".  For the merges, the same rules apply
    for as for extends working left to right such that the rightmost merges attribute will overwrite
    any similar attribute from merges to its left where the main object does not itself define the
    attribute.  The primary difference is in handling of lists and dicts.  These are merged and not
    over-written; again working from left to right with the main object's collection serving as the
    seed when present.

    A Struct can be semantically abstract without setting `abstract=True`. The `abstract`
    value can serve as documentation, or, for subclasses that provide an implementation for
    `validate_concrete`, it allows skipping validation for abstract instances.

    :param bool abstract: `True` to mark this struct as abstract, in which case no
                          validation is performed (see `validate_concrete`); `False` by default.
    :param extends: The struct instance to inherit field values from.  Any shared fields are
                    over-written with this instances values.
    :type extends: An addressed or concrete struct instance that is a type compatible with
                   this struct or this structs superclasses.
    :param merges: The struct instances to merge this instance's field values with.  Merging
                   is like extension except for containers, which are extended instead of replaced;
                   ie: any `dict` values are updated with this instances items and any `list` values
                   are extended with this instances items.
    :type merges: An addressed or concrete struct instance that is a type compatible with
                  this struct or this structs superclasses.
    :param **kwargs: The struct parameters.
    """
    kwargs = _normalize_utf8_keys(kwargs)

    self._kwargs = kwargs

    self._kwargs['abstract'] = abstract
    self._kwargs[self._TYPE_ALIAS_FIELD] = type_alias

    self.extends = extends
    self.merges = merges

    # Allow for structs that are directly constructed in memory.  These can have an
    # address directly assigned (vs. inferred from name + source file location) and we only require
    # that if they do, their name - if also assigned, matches the address.
    if self.address:
      target_name, _, config_specifier = self.address.target_name.partition('@')
      if self.name and self.name != target_name:
        self.report_validation_error('Address and name do not match! address: {}, name: {}'
                                     .format(self.address, self.name))
      self._kwargs['name'] = target_name

  def kwargs(self):
    """Returns a dict of the kwargs for this Struct which were not interpreted by the baseclass.

    This excludes fields like `extends`, `merges`, and `abstract`, which are consumed by
    SerializableFactory.create and Validatable.validate.
    """
    return {k: v for k, v in self._kwargs.items() if k not in self._INTERNAL_FIELDS}

  @property
  def name(self):
    """Return the name of this object, if any.

    In general structs need not be named, in which case they are generally embedded
    objects; ie: attributes values of enclosing named structs.  Any top-level
    struct object, though, will carry a unique name (in the struct object's enclosing
    namespace) that can be used to address it.

    :rtype: string
    """
    return self._kwargs.get('name')

  @property
  def address(self):
    """Return the address of this object, if any.

    In general structs need not be identified by an address, in which case they are
    generally embedded objects; ie: attributes values of enclosing named structs.
    Any top-level struct, though, will be identifiable via a unique address.

    :rtype: :class:`pants.build_graph.address.Address`
    """
    return self._kwargs.get('address')

  @property
  def type_alias(self):
    """Return the type alias this target was constructed via.

    For a target read from a BUILD file, this will be target alias, like 'java_library'.
    For a target constructed in memory, this will be the simple class name, like 'JavaLibrary'.

    The end result is that the type alias should be the most natural way to refer to this target's
    type to the author of the target instance.

    :rtype: string
    """
    type_alias = self._kwargs.get(self._TYPE_ALIAS_FIELD, None)
    return type_alias if type_alias is not None else type(self).__name__

  @property
  def abstract(self):
    """Return `True` if this object has been marked as abstract.

    Abstract objects are not validated. See: `validate_concrete`.

    :rtype: bool
    """
    return self._kwargs.get('abstract', False)

  # It only makes sense to inherit a subset of our own fields (we should not inherit new fields!),
  # our superclasses logically provide fields within this constrained set.
  # NB: Since `Struct` is at base an ~unconstrained struct, a superclass does allow for
  # arbitrary and thus more fields to be defined than a subclass might logically support.  We
  # accept this hole in a trade for generally expected behavior when `Struct` is subclassed
  # in the style of constructors with named parameters representing the full complete set of
  # expected parameters leaving **kwargs only for use by 'the system'; ie for `type_alias` and
  # `address` plumbing for example.
  #
  # Of note is the fact that we pass a constraint type and not a concrete constraint value.  This
  # tells addressable to use `SuperclassesOf([Struct instance's type])`, which is what we
  # want.  Aka, for `StructSubclassA`, the constraint is
  # `SuperclassesOf(StructSubclassA)`.
  #
  @addressable(SuperclassesOf)
  def extends(self):
    """Return the object this object extends, if any.

    :rtype: :class:`Serializable`
    """

  @addressable_list(SuperclassesOf)
  def merges(self):
    """Return the objects this object merges in, if any.

    :rtype: list of :class:`Serializable`
    """

  def _asdict(self):
    return self._kwargs

  def _extract_inheritable_attributes(self, serializable):
    attributes = serializable._asdict().copy()

    # Allow for embedded objects inheriting from addressable objects - they should never inherit an
    # address and any top-level object inheriting will have its own address.
    attributes.pop('address', None)

    # We should never inherit special fields - these are for local book-keeping only.
    for field in self._UNINHERITABLE_FIELDS:
      attributes.pop(field, None)

    return attributes

  def create(self):
    if not (self.extends or self.merges):
      return self

    # Filter out the attributes that we will consume below for inheritance.
    attributes = {k: v for k, v in self._asdict().items()
                  if k not in self._INHERITANCE_FIELDS and v is not None}

    if self.extends:
      for k, v in self._extract_inheritable_attributes(self.extends).items():
        attributes.setdefault(k, v)

    if self.merges:
      def merge(attrs):
        for k, v in attrs.items():
          if isinstance(v, MutableMapping):
            mapping = attributes.get(k, {})
            mapping.update(v)
            attributes[k] = mapping
          elif isinstance(v, MutableSequence):
            sequence = attributes.get(k, [])
            sequence.extend(v)
            attributes[k] = sequence
          else:
            attributes.setdefault(k, v)

      for merged in self.merges:
        merge(self._extract_inheritable_attributes(merged))

    struct_type = type(self)
    return struct_type(**attributes)

  def validate(self):
    if not self.abstract:
      self.validate_concrete()

  def report_validation_error(self, message):
    """Raises a properly identified validation error.

    :param string message: An error message describing the validation error.
    :raises: :class:`pants.engine.exp.objects.ValidationError`
    """
    raise ValidationError(self.address, message)

  def validate_concrete(self):
    """Subclasses can override to implement validation logic.

    The object will be fully hydrated state and it's guaranteed the object will be concrete, aka.
    not `abstract`.  If an error is found in the struct's fields, a validation error should
    be raised by calling `report_validation_error`.

    :raises: :class:`pants.engine.exp.objects.ValidationError`
    """

  def __getattr__(self, item):
    if item in self._kwargs:
      return self._kwargs[item]
    raise AttributeError('{} does not have attribute {!r}'.format(self, item))

  def _key(self):
    if self.address:
      return self.address
    else:
      def hashable(value):
        if isinstance(value, dict):
          return tuple(sorted((k, hashable(v)) for k, v in value.items()))
        elif isinstance(value, list):
          return tuple(hashable(v) for v in value)
        else:
          return value
      return tuple(sorted((k, hashable(v)) for k, v in self._kwargs.items()
                          if k not in self._INHERITANCE_FIELDS))

  def __hash__(self):
    return hash(self._key())

  def __eq__(self, other):
    return isinstance(other, Struct) and self._key() == other._key()

  def __ne__(self, other):
    return not (self == other)

  def __repr__(self):
    classname = type(self).__name__
    if self.address:
      return '{classname}(address={address})'.format(classname=classname,
                                                     address=self.address.reference())
    else:
      return '{classname}({args})'.format(classname=classname,
                                          args=', '.join(sorted('{}={!r}'.format(k, v)
                                                                for k, v in self._kwargs.items()
                                                                if v)))

class StructWithDeps(Struct):
  """A subclass of Struct with dependencies."""

  def __init__(self, dependencies=None, **kwargs):
    """
    :param list dependencies: The direct dependencies of this struct.
    """
    # TODO: enforce the type of variants using the Addressable framework.
    super(StructWithDeps, self).__init__(**kwargs)
    self.dependencies = dependencies

  @addressable_list(SubclassesOf(Struct))
  def dependencies(self):
    """The direct dependencies of this target.

    :rtype: list
    """

class HasStructs(AbstractClass):
  """A mixin to mark an object as containing a collection of Structs in one of its fields."""

  @abstractproperty
  def collection_field(cls):
    """Returns the name of the field of this Class that contains a collection of Structs."""

class Variants(Struct):
  """A struct that holds default variant values.

  Variants are key-value pairs representing uniquely identifying parameters for a Node.

  Default variants are usually configured on a Target to be used whenever they are
  not specified by a caller.

  They can be imagined as a dict in terms of dupe handling, but for easier hashability they are
  stored internally as sorted nested tuples of key-value strings.
  """

  @staticmethod
  def merge(left, right):
    """Merges right over left, ensuring that the return value is a tuple of tuples, or None."""
    if not left:
      if right:
        return tuple(right)
      else:
        return None
    if not right:
      return tuple(left)
    # Merge by key, and then return sorted by key.
    merged = dict(left)
    for key, value in right:
      merged[key] = value
    return tuple(sorted(merged.items()))

  def __init__(self, default=None, **kwargs):
    """
    :param dict default: A dict of default variant values.
    """
    # TODO: enforce the type of variants using the Addressable framework.
    super(Variants, self).__init__(default=default, **kwargs)


text:
package io.amaze.bench.cluster.jms;

import com.google.common.testing.NullPointerTester;
import io.amaze.bench.api.ActorKey;
import io.amaze.bench.cluster.actor.ActorInputMessage;
import io.amaze.bench.cluster.actor.RuntimeActor;
import io.amaze.bench.shared.jms.JMSClient;
import io.amaze.bench.shared.jms.JMSException;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import javax.jms.MessageListener;

import static io.amaze.bench.runtime.actor.TestActor.DUMMY_ACTOR;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.*;

/**
 * Created on 3/27/16.
 */
@RunWith(MockitoJUnitRunner.class)
public final class JMSActorClusterClientTest {

    @Mock
    private JMSClient jmsClient;
    @Mock
    private RuntimeActor actor;

    private JMSActorClusterClient client;

    @Before
    public void before() {
        client = new JMSActorClusterClient(jmsClient, DUMMY_ACTOR);
    }

    @After
    public void after() {
        client.close();
    }

    @Test
    public void null_parameters_invalid() {
        NullPointerTester tester = new NullPointerTester();
        tester.setDefault(ActorInputMessage.class, ActorInputMessage.dumpMetrics());
        tester.setDefault(ActorKey.class, DUMMY_ACTOR);

        tester.testAllPublicConstructors(JMSActorClusterClient.class);
        tester.testAllPublicInstanceMethods(client);
    }

    @Test
    public void start_actor_listener() throws JMSException {
        when(actor.getKey()).thenReturn(DUMMY_ACTOR);

        client.startActorListener(actor);

        verify(jmsClient).addQueueListener(eq(DUMMY_ACTOR.getName()), any(MessageListener.class));
        verify(jmsClient).startListening();
        verifyNoMoreInteractions(jmsClient);
    }

    @Test(expected = RuntimeException.class)
    public void start_actor_listener_and_listening_throws() throws JMSException {
        when(actor.getKey()).thenReturn(DUMMY_ACTOR);
        doThrow(new JMSException(new IllegalArgumentException())).when(jmsClient).startListening();

        client.startActorListener(actor);
    }

    @Test
    public void close_closes_jms_client() throws JMSException {
        client.close();

        verify(jmsClient).close();
        verifyNoMoreInteractions(jmsClient);
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.wikidata.wdtk.dumpfiles.wmf;

import org.junit.Test;
import org.wikidata.wdtk.util.CompressionType;

import static org.junit.Assert.assertEquals;

public class WmfDumpFileTest {

	@Test
	public void getDumpFileCompressionType() {
		assertEquals(WmfDumpFile.getDumpFileCompressionType("foo.tar.gz"), CompressionType.GZIP);
		assertEquals(WmfDumpFile.getDumpFileCompressionType("bar.txt.bz2"), CompressionType.BZ2);
		assertEquals(WmfDumpFile.getDumpFileCompressionType("baz.txt"), CompressionType.NONE);
		assertEquals(WmfDumpFile.getDumpFileCompressionType("bat.txt"), CompressionType.NONE);
	}
}


text:
package com.buzbuz.mygame;

import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.Texture.TextureFilter;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.input.GestureDetector;
import com.buzbuz.mygame.maps.Map;

public class MyGame extends Game {

    private OrthographicCamera camera;

    private SpriteBatch worldBatch;
    private Texture worldTexture;
    private Sprite worldSprite;

    private SpriteBatch uiBatch;
    private Texture uiTexture;
    private Sprite uiSprite;

    private Map mMap;
    private boolean mIsMapPrinted;

    @Override
    public void create() {
        camera = new OrthographicCamera(1280, 720);

        worldBatch = new SpriteBatch();
        worldTexture = new Texture(Gdx.files.internal("sc_map.png"));
        worldTexture.setFilter(TextureFilter.Linear, TextureFilter.Linear);
        worldSprite = new Sprite(worldTexture);
        worldSprite.setOrigin(0,0);
        worldSprite.setPosition(-worldSprite.getWidth()/2,-worldSprite.getHeight()/2);

        uiBatch = new SpriteBatch();
        uiTexture = new Texture(Gdx.files.internal("link.png"));
        uiSprite = new Sprite(uiTexture);
        uiSprite.setOrigin(0,0);
        uiSprite.setPosition(0,0);

        mMap = new Map(100,100,20);
        mMap.generate();

        Gdx.input.setInputProcessor(new GestureDetector(new InputHandler(camera)));
    }

    @Override
    public void dispose() {
        worldBatch.dispose();
        worldTexture.dispose();

        uiBatch.dispose();
        uiTexture.dispose();
    }

    @Override
    public void render() {
        Gdx.gl.glClearColor(0, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        if(!mIsMapPrinted) {
            mIsMapPrinted = true;
            mMap.printMapInLog();
        }

        camera.update();

        worldBatch.setProjectionMatrix(camera.combined);
        worldBatch.begin();
        worldSprite.draw(worldBatch);
        worldBatch.end();

        uiBatch.begin();
        uiSprite.draw(uiBatch);
        uiBatch.end();
    }

    @Override
    public void resize(int width, int height) {
    }

    @Override
    public void pause() {
    }

    @Override
    public void resume() {
    }
}


text:
import os
from functools import partial
from subprocess import check_output, CalledProcessError, STDOUT

from sh import docker

from tests.st.utils.exceptions import CommandExecError
from tests.st.utils import utils
from tests.st.utils.utils import retry_until_success, get_ip
from workload import Workload
from network import DockerNetwork

CALICO_DRIVER_SOCK = "/run/docker/plugins/calico.sock"

class DockerHost(object):
    """
    A host container which will hold workload containers to be networked by
    Calico.
    """
    def __init__(self, name, start_calico=True, dind=True):
        self.name = name
        self.dind = dind
        self.workloads = set()

        # This variable is used to assert on destruction that this object was
        # cleaned up.  If not used as a context manager, users of this object
        self._cleaned = False

        if dind:
            # TODO use pydocker
            docker.rm("-f", self.name, _ok_code=[0, 1])
            docker.run("--privileged", "-v", os.getcwd()+":/code", "--name",
                       self.name,
                       "-e", "DOCKER_DAEMON_ARGS="
                       "--kv-store=consul:%s:8500" % utils.get_ip(),
                       "-tid", "calico/dind")
            self.ip = docker.inspect("--format", "{{ .NetworkSettings.IPAddress }}",
                                     self.name).stdout.rstrip()

            self.ip6 = docker.inspect("--format",
                                      "{{ .NetworkSettings."
                                      "GlobalIPv6Address }}",
                                      self.name).stdout.rstrip()

            # Make sure docker is up
            docker_ps = partial(self.execute, "docker ps")
            retry_until_success(docker_ps, ex_class=CalledProcessError,
                                retries=100)
            self.execute("docker load --input /code/calico_containers/calico-node.tar && "
                         "docker load --input /code/calico_containers/busybox.tar")
        else:
            self.ip = get_ip()

        if start_calico:
            self.start_calico_node()

    def execute(self, command):
        """
        Pass a command into a host container.

        Raises a CommandExecError() if the command returns a non-zero
        return code.

        :param command:  The command to execute.
        :return: The output from the command with leading and trailing
        whitespace removed.
        """
        etcd_auth = "ETCD_AUTHORITY=%s:2379" % get_ip()
        # Export the environment, in case the command has multiple parts, e.g.
        # use of | or ;
        command = "export %s; %s" % (etcd_auth, command)

        if self.dind:
            command = self.escape_bash_single_quotes(command)
            command = "docker exec -it %s bash -c '%s'" % (self.name,
                                                           command)
        try:
            output = check_output(command, shell=True, stderr=STDOUT)
        except CalledProcessError as e:
            # Wrap the original exception with one that gives a better error
            # message (including command output).
            raise CommandExecError(e)
        else:
            return output.strip()

    def calicoctl(self, command):
        """
        Convenience function for abstracting away calling the calicoctl
        command.

        Raises a CommandExecError() if the command returns a non-zero
        return code.

        :param command:  The calicoctl command line parms as a single string.
        :return: The output from the command with leading and trailing
        whitespace removed.
        """
        if os.environ.get("CALICOCTL"):
            calicoctl = os.environ["CALICOCTL"]
        else:
            if self.dind:
                calicoctl = "/code/dist/calicoctl"
            else:
                calicoctl = "dist/calicoctl"
        return self.execute(calicoctl + " " + command)

    def start_calico_node(self, as_num=None):
        """
        Start calico in a container inside a host by calling through to the
        calicoctl node command.

        :param as_num: The AS Number for this node.  A value of None uses the
        inherited default value.
        """
        args = ['node', '--ip=%s' % self.ip]
        try:
            if self.ip6:
                args.append('--ip6=%s' % self.ip6)
        except AttributeError:
            # No ip6 configured
            pass
        if as_num:
            args.append('--as=%s' % as_num)

        cmd = ' '.join(args)
        self.calicoctl(cmd)

    def assert_driver_up(self):
        """
        Check that Calico Docker Driver is up by checking the existence of
        the unix socket.
        """
        sock_exists = partial(self.execute,
                              "[ -e %s ]" % CALICO_DRIVER_SOCK)
        retry_until_success(sock_exists, ex_class=CalledProcessError)

    def remove_workloads(self):
        """
        Remove all containers running on this host.

        Useful for test shut down to ensure the host is cleaned up.
        :return: None
        """
        for workload in self.workloads:
            try:
                self.execute("docker rm -f %s" % workload.name)
            except CalledProcessError:
                # Make best effort attempt to clean containers. Don't fail the
                # test if a container can't be removed.
                pass

    def remove_images(self):
        """
        Remove all images running on this host.

        Useful for test shut down to ensure the host is cleaned up.
        :return: None
        """
        cmd = "docker rmi $(docker images -qa)"
        try:
            self.execute(cmd)
        except CalledProcessError:
            # Best effort only.
            pass

    def remove_containers(self):
        """
        Remove all containers running on this host.

        Useful for test shut down to ensure the host is cleaned up.
        :return: None
        """
        cmd = "docker rm -f $(docker ps -qa)"
        try:
            self.execute(cmd)
        except CalledProcessError:
            # Best effort only.
            pass

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        """
        Exit the context of this host.
        :return: None
        """
        self.cleanup()

    def cleanup(self):
        """
        Clean up this host, including removing any containers is created.  This
        is necessary especially for Docker-in-Docker so we don't leave dangling
        volumes.
        :return:
        """
        if self.dind:
            # For Docker-in-Docker, we need to remove all containers and
            # all images...
            self.remove_containers()
            self.remove_images()

            # ...and the outer container for DinD.
            docker.rm("-f", self.name, _ok_code=[0, 1])
        else:
            # For non Docker-in-Docker, we can only remove the containers we
            # created - so remove the workloads and the calico node.
            self.remove_workloads()
            docker.rm("-f", "calico-node", _ok_code=[0, 1])

        self._cleaned = True

    def __del__(self):
        """
        This destructor asserts this object was cleaned up before being GC'd.

        Why not just clean up?  This object is used in test scripts and we
        can't guarantee that GC will happen between test runs.  So, un-cleaned
        objects may result in confusing behaviour since this object manipulates
        Docker containers running on the system.
        :return:
        """
        assert self._cleaned

    def create_workload(self, name, image="busybox", network=None,
                        service=None):
        """
        Create a workload container inside this host container.
        """
        workload = Workload(self, name, image=image, network=network,
                            service=service)
        self.workloads.add(workload)
        return workload

    def create_network(self, name, driver="calico"):
        """
        Create a Docker network using this host.

        :param name: The name of the network.  This must be unique per cluster
        and it the user-facing identifier for the network.  (Calico itself will
        get a UUID for the network via the driver API and will not get the
        name).
        :param driver: The name of the network driver to use.  (The Calico
        driver is the default.)
        :return: A DockerNetwork object.
        """
        return DockerNetwork(self, name, driver=driver)

    @staticmethod
    def escape_bash_single_quotes(command):
        """
        Escape single quotes in bash string strings.

        Replace ' (single-quote) in the command with an escaped version.
        This needs to be done, since the command is passed to "docker
        exec" to execute and needs to be single quoted.
        Strictly speaking, it's impossible to escape single-quoted
        bash script, but there is a workaround - end the single quoted
         string, then concatenate a double quoted single quote,
        and finally re-open the string with a single quote. Because
        this is inside a single quoted python, string, the single
        quotes also need escaping.

        :param command: The string to escape.
        :return: The escaped string
        """
        return command.replace('\'', '\'"\'"\'')


text:
%w{version setup connection errors event user room plugins/base services/campfire services/irc storage/base storage/hash storage/yaml}.each do |file|
  require "ceiling_cat/#{file}"
end


text:
{% extends 'base.html' %}

{% block title %}dashboard{% endblock %}

{% block content %}

Your Personalized URL

            		<input id="next-slug" style="width: 75%; height: 2em; text-align: center"
            		       type="text" min="50" disabled
            		       class="login-field active"
            		       value="http://nextfeed.org/next?subscription={{ user.get_profile.next_slug }}" />

Copy to Clipboard

                You should to copy this URL and bookmark it.

                Whenever you hit this address, it will immediately redirect you
                to the oldest unread entry in your feeds.

                Click it again to the next entry, and so on.

                You'll get the hang of it once you give it a go!

Your Feeds

        <form class="simple-form">{% csrf_token %}

              <input type="text" placeholder="Paste RSS address here!" id="feed-url-input" ng-model="new_feed_url" />
              <button id="add-feed-btn" class="btn" value="Add Feed" ng-click="add_feed()" >Add Feed</button>

            {[{ form_result }]}
        </form>

                        <button class="btn btn-mini dropdown-toggle" data-toggle="dropdown">Actions </button>

Mark All Unread

Mark All Read

Unsubscribe

                {[{ subscription.unread_entries }]}  {[{ subscription.title }]}

{% endblock %}

{% block scripts %}

{% endblock %}


text:
using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Alexa.NET.Management.SlotType
{
    public class ValueSupplierConverter:JsonConverter<ValueSupplier>
    {
        public override bool CanWrite => false;

        public override void WriteJson(JsonWriter writer, ValueSupplier value, JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }

        public override ValueSupplier ReadJson(JsonReader reader, Type objectType, ValueSupplier existingValue, bool hasExistingValue,
            JsonSerializer serializer)
        {
            // Load JObject from stream

            var jObject = JObject.Load(reader);

            var target = Mappings(jObject["type"].Value<string>());

            serializer.Populate(jObject.CreateReader(), target);

            return target;
        }

        private ValueSupplier Mappings(string value)
        {
            return value switch
            {
                InlineValueSupplier.ValueSupplierType => (ValueSupplier)new InlineValueSupplier(),
                CatalogValueSupplier.ValueSupplierType => new CatalogValueSupplier(),
                _ => null
            };
        }
    }
}


text:
jest.mock(`gatsby-cli/lib/reporter`, () => {
  return {
    panicOnBuild: jest.fn(),
    warn: jest.fn(),
  }
})
jest.mock(`../../resolve-module-exports`)

const reporter = require(`gatsby-cli/lib/reporter`)
const {
  collatePluginAPIs,
  handleBadExports,
  handleMultipleReplaceRenderers,
  warnOnIncompatiblePeerDependency,
} = require(`../validate`)

describe(`collatePluginAPIs`, () => {
  const MOCK_RESULTS = {
    "/foo/gatsby-node": [`node-1`, `node-2`],
    "/foo/gatsby-browser": [`browser-1`, `browser-2`],
    "/foo/gatsby-ssr": [`ssr-1`, `ssr-2`],
    "/bar/gatsby-node": [`node-2`, `node-3`],
    "/bar/gatsby-browser": [`browser-2`, `browser-3`],
    "/bar/gatsby-ssr": [`ssr-2`, `ssr-3`],
    "/bad-apis/gatsby-node": [`bad-node-2`, `bad-node-3`],
    "/bad-apis/gatsby-browser": [`bad-browser-2`, `bad-browser-3`],
    "/bad-apis/gatsby-ssr": [`bad-ssr-2`, `bad-ssr-3`],
  }

  beforeEach(() => {
    const resolveModuleExports = require(`../../resolve-module-exports`)
    resolveModuleExports(MOCK_RESULTS)
  })

  it(`Identifies APIs used by a site's plugins`, async () => {
    const apis = {
      node: [`node-1`, `node-2`, `node-3`, `node-4`],
      browser: [`browser-1`, `browser-2`, `browser-3`, `browser-4`],
      ssr: [`ssr-1`, `ssr-2`, `ssr-3`, `ssr-4`],
    }
    const flattenedPlugins = [
      {
        resolve: `/foo`,
        id: `Plugin foo`,
        name: `foo-plugin`,
        version: `1.0.0`,
        pluginOptions: { plugins: [] },
      },
      {
        resolve: `/bar`,
        id: `Plugin default-site-plugin`,
        name: `default-site-plugin`,
        version: `ec21d02c31ab044d027a1d2fcaeb4a79`,
        pluginOptions: { plugins: [] },
      },
    ]

    let result = collatePluginAPIs({ apis, flattenedPlugins })
    expect(result).toMatchSnapshot()
  })

  it(`Identifies incorrect APIs used by a site's plugins`, async () => {
    const apis = {
      node: [`node-1`, `node-2`, `node-3`, `node-4`],
      browser: [`browser-1`, `browser-2`, `browser-3`, `browser-4`],
      ssr: [`ssr-1`, `ssr-2`, `ssr-3`, `ssr-4`],
    }
    const flattenedPlugins = [
      {
        resolve: `/foo`,
        id: `Plugin foo`,
        name: `foo-plugin`,
        version: `1.0.0`,
        pluginOptions: { plugins: [] },
      },
      {
        resolve: `/bad-apis`,
        id: `Plugin default-site-plugin`,
        name: `default-site-plugin`,
        version: `ec21d02c31ab044d027a1d2fcaeb4a79`,
        pluginOptions: { plugins: [] },
      },
    ]

    let result = collatePluginAPIs({ apis, flattenedPlugins })
    expect(result).toMatchSnapshot()
  })
})

describe(`handleBadExports`, () => {
  it(`Does nothing when there are no bad exports`, async () => {
    handleBadExports({
      apis: {
        node: [`these`, `can`, `be`],
        browser: [`anything`, `as there`],
        ssr: [`are no`, `bad errors`],
      },
      badExports: {
        node: [],
        browser: [],
        ssr: [],
      },
    })
  })

  it(`Calls reporter.panicOnBuild when bad exports are detected`, async () => {
    handleBadExports({
      apis: {
        node: [``],
        browser: [``],
        ssr: [`notFoo`, `bar`],
      },
      badExports: {
        node: [],
        browser: [],
        ssr: [
          {
            exportName: `foo`,
            pluginName: `default-site-plugin`,
          },
        ],
      },
    })

    expect(reporter.panicOnBuild.mock.calls.length).toBe(1)
  })
})

describe(`handleMultipleReplaceRenderers`, () => {
  it(`Does nothing when replaceRenderers is implemented once`, async () => {
    const flattenedPlugins = [
      {
        resolve: `___TEST___`,
        id: `Plugin foo`,
        name: `foo-plugin`,
        version: `1.0.0`,
        pluginOptions: { plugins: [] },
        nodeAPIs: [],
        browserAPIs: [],
        ssrAPIs: [`replaceRenderer`],
      },
      {
        resolve: `___TEST___`,
        id: `Plugin default-site-plugin`,
        name: `default-site-plugin`,
        version: `ec21d02c31ab044d027a1d2fcaeb4a79`,
        pluginOptions: { plugins: [] },
        nodeAPIs: [],
        browserAPIs: [],
        ssrAPIs: [],
      },
    ]

    const result = handleMultipleReplaceRenderers({
      flattenedPlugins,
    })

    expect(result).toMatchSnapshot()
  })

  it(`Sets skipSSR when replaceRenderers is implemented more than once`, async () => {
    const flattenedPlugins = [
      {
        resolve: `___TEST___`,
        id: `Plugin foo`,
        name: `foo-plugin`,
        version: `1.0.0`,
        pluginOptions: { plugins: [] },
        nodeAPIs: [],
        browserAPIs: [],
        ssrAPIs: [`replaceRenderer`],
      },
      {
        resolve: `___TEST___`,
        id: `Plugin default-site-plugin`,
        name: `default-site-plugin`,
        version: `ec21d02c31ab044d027a1d2fcaeb4a79`,
        pluginOptions: { plugins: [] },
        nodeAPIs: [],
        browserAPIs: [],
        ssrAPIs: [`replaceRenderer`],
      },
    ]

    const result = handleMultipleReplaceRenderers({
      flattenedPlugins,
    })

    expect(result).toMatchSnapshot()
  })
})

describe(`warnOnIncompatiblePeerDependency`, () => {
  beforeEach(() => {
    reporter.warn.mockClear()
  })

  it(`Does not warn when no peer dependency`, () => {
    warnOnIncompatiblePeerDependency(`dummy-package`, { peerDependencies: {} })

    expect(reporter.warn).not.toHaveBeenCalled()
  })

  it(`Warns on incompatible gatsby peer dependency`, async () => {
    warnOnIncompatiblePeerDependency(`dummy-package`, {
      peerDependencies: {
        gatsby: `<2.0.0`,
      },
    })

    expect(reporter.warn).toHaveBeenCalledWith(
      expect.stringContaining(`Plugin dummy-package is not compatible`)
    )
  })
})


text:
package org.apache.isis.core.metamodel.specloader.specimpl;

import org.apache.isis.core.metamodel.spec.ObjectSpecification;

/**
 * Interface indicating an a mixed-in association or action.
 */
public interface MixedInMember2 extends MixedInMember {

    ObjectSpecification getMixinType();

}


text:
import { Directive, Input, Output, EventEmitter} from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import {toBoolean} from '../util/util';

@Directive({
  selector: '[nglPick]',
})
export class NglPick {

  selected: any;
  values = new BehaviorSubject(null);
  isMultiple = false;

  @Input('nglPick') set setSelected(selected: string) {
    this.selected = selected;
    this.ngAfterContentInit();
  }

  @Input() nglPickActiveClass: string;

  @Output() nglPickChange = new EventEmitter();
  @Output() nglOptionDestroyed = new EventEmitter();

  @Input('nglPickMultiple') set setIsMultiple(isMultiple: any) {
    this.isMultiple = toBoolean(isMultiple);
  }

  ngAfterContentInit() {
    this.values.next(this.selected);
  }

  selectOption(value: any) {
    let next: any;
    if (this.isMultiple) {
      if (Array.isArray(this.selected)) {
        // Remove if already there or add to selection
        const index = this.selected.indexOf(value);
        next = index > -1
                ? [...this.selected.slice(0, index), ...this.selected.slice(index + 1)]
                : [...this.selected, value];
      } else {
        next = Object.assign({}, this.selected, {[value]: !this.selected[value]});
      }
    } else {
      next = value;
    }

    this.nglPickChange.emit(next);
  }

  optionRemoved(value: any) {
    if (this.isMultiple && !this.selected) return;

    let emit: boolean;

    if (this.isMultiple) {
      emit = Array.isArray(this.selected) ? this.selected.indexOf(value) > -1 : !!this.selected[value];
    } else {
      emit = this.selected === value;
    }

    if (emit) {
      setTimeout(() => this.nglOptionDestroyed.emit(value));
    }
  }
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;
using Plainion.Flames.Infrastructure;
using Plainion.Flames.Infrastructure.Model;
using Plainion.Flames.Infrastructure.Services;
using Plainion.Flames.Model;
using Plainion.Flames.Presentation;
using Plainion.Flames.Viewer.Model;
using Plainion.Prism.Events;
using Plainion.Progress;
using Plainion.Windows;
using Plainion.Windows.Diagnostics;
using Prism.Events;

namespace Plainion.Flames.Viewer.Services
{
    [Export]
    class LoaderSerivce : IProjectService
    {
        private Project myProject;
        private string myOpenTraceFilter;
        private string mySaveTraceFilter;
        private IPresentationCreationService myPresentationCreationService;

        [ImportingConstructor]
        public LoaderSerivce(IPresentationCreationService presentationService, IEventAggregator eventAggregator)
        {
            myPresentationCreationService = presentationService;

            eventAggregator.GetEvent<ApplicationShutdownEvent>().Subscribe( x =>
            {
                // enforce unload of project incl. ProjectChanging event
                Project = null;
            } );
        }

        IProject IProjectService.Project { get { return myProject; } }

        public Project Project
        {
            get { return myProject; }
            private set
            {
                if( myProject == value )
                {
                    return;
                }

                if( myProject != null )
                {
                    if( ProjectChanging != null )
                    {
                        ProjectChanging( this, EventArgs.Empty );
                    }

                    Unload( myProject );
                }

                myProject = value;

                if( ProjectChanged != null )
                {
                    ProjectChanged( this, EventArgs.Empty );
                }
            }
        }

        public event EventHandler ProjectChanging;

        public event EventHandler ProjectChanged;

        [ImportMany]
        public IEnumerable<ITraceReader> TraceReaders { get; private set; }

        [ImportMany]
        public IEnumerable<ITraceWriter> TraceWriters { get; private set; }

        public string OpenTraceFilter
        {
            get
            {
                if( myOpenTraceFilter == null )
                {
                    myOpenTraceFilter = "All files (*.*)|*.*|" + string.Join( "|", TraceReaders
                        .SelectMany( r => r.FileFilters )
                        .Select( f => string.Format( "{0}|*{1}", f.Description, f.Extension ) ) );
                }

                return myOpenTraceFilter;
            }
        }

        public string SaveTraceFilter
        {
            get
            {
                if( mySaveTraceFilter == null )
                {
                    mySaveTraceFilter = string.Join( "|", TraceWriters
                        .SelectMany( r => r.FileFilters )
                        .Select( f => string.Format( "{0}|*{1}", f.Description, f.Extension ) ) );
                }

                return mySaveTraceFilter;
            }
        }

        [ImportMany( typeof( IDocument ) )]
        public IEnumerable<ExportFactory<IDocument, IDocumentMetadata>> Documents { get; private set; }

        // TODO: what would be the contract if nothing could be loaded?
        public async Task LoadAsync( IEnumerable<string> traceFiles, IProgress<IProgressInfo> progress )
        {
            var project = new Project( traceFiles );

            var file = GetProjectFile( project );

            project.WasDeserialized = File.Exists( file );

            // unload old project and reset project specific settings
            Project = null;
            myPresentationCreationService.Settings.Reset();

            if( File.Exists( file ) )
            {
                using( var stream = new FileStream( file, FileMode.Open ) )
                {
                    using( var archive = new ZipArchive( stream, ZipArchiveMode.Read ) )
                    {
                        foreach( var entry in archive.Entries )
                        {
                            var factory = Documents.SingleOrDefault( doc => doc.Metadata.Name == entry.Name );
                            var document = factory.CreateExport();
                            document.Value.Deserialize( entry.Open() );
                            project.Items.Add( document.Value );
                        }
                    }
                }
            }

            await LoadTraceLogAsync( project, progress );
        }

        private async Task LoadTraceLogAsync( Project project, IProgress<IProgressInfo> progress )
        {
            // now all project items are loaded - publish the new project
            Project = project;

            var builder = new TraceModelBuilder();

            foreach( var item in project.Items )
            {
                builder.ReaderContextHints.Add( item );
            }

            foreach( var traceFile in project.TraceFiles )
            {
                var ext = Path.GetExtension( traceFile );
                var reader = TryGetTraceReaderByExtension( ext );
                Contract.Requires( reader != null, "No Reader found for file extension: " + ext );

                await reader.ReadAsync( traceFile, builder, progress );
            }

            // first copy back the project items
            project.Items.Clear();
            foreach( var hint in builder.ReaderContextHints )
            {
                project.Items.Add( hint );
            }

            // ... then set the tracelog - some view models react on that and expect the project items to be there again
            project.TraceLog = builder.Complete();
        }

        private ITraceReader TryGetTraceReaderByExtension( string ext )
        {
            return TraceReaders
                .SingleOrDefault( r => r.FileFilters
                    .Any( f => f.Extension.Equals( ext, StringComparison.OrdinalIgnoreCase ) ) );
        }

        public bool CanLoad( string f )
        {
            return TryGetTraceReaderByExtension( Path.GetExtension( f ) ) != null;
        }

        /// <summary>
        /// Saves certain aspects (provided by ITraceLog) of the project.
        /// </summary>
        public Task ExportAsync( ITraceLog traceLog, string filename, IProgress<IProgressInfo> progress )
        {
            Contract.RequiresNotNull( traceLog, "traceLog" );

            var writer = TraceWriters
                .Single( r => r.FileFilters
                    .Any( f => f.Extension.Equals( Path.GetExtension( filename ), StringComparison.OrdinalIgnoreCase ) ) );

            return Task.Run( () =>
                {
                    var task = writer.WriteAsync( traceLog, filename, progress );

                    task.Wait();
                } );
        }

        private void Unload( Project project )
        {
            if( project == null )
            {
                return;
            }

            var file = GetProjectFile( project );

            if( File.Exists( file ) )
            {
                File.Delete( file );
            }

            using( var stream = new FileStream( file, FileMode.OpenOrCreate ) )
            {
                using( var archive = new ZipArchive( stream, ZipArchiveMode.Create ) )
                {
                    foreach( var doc in Project.Items.OfType<IDocument>() )
                    {
                        var attr = ( DocumentAttribute )doc.GetType().GetCustomAttributes( typeof( DocumentAttribute ), false ).Single();
                        using( var entryStream = archive.CreateEntry( attr.Name, CompressionLevel.Fastest ).Open() )
                        {
                            doc.Serialize( entryStream );
                        }
                    }
                }
            }

            if( project.TraceLog != null )
            {
                project.TraceLog.Dispose();
                project.TraceLog = null;
            }

            // http://stackoverflow.com/questions/13026826/execute-command-after-view-is-loaded-wpf-mvvm
            // trigger GC after application does idle so that all Unload handlers could cleanup so that
            // we can free all memory no longer needed
            Application.Current.Dispatcher.BeginInvoke( DispatcherPriority.ApplicationIdle, new Action( () =>
            {
                GC.Collect();
            } ) );

        }

        private static string GetProjectFile( Project project )
        {
            var mainTraceFile = project.TraceFiles.First();
            return Path.Combine( Path.GetDirectoryName( mainTraceFile ), Path.GetFileNameWithoutExtension( mainTraceFile ) + ".pfp" );
        }

        // TODO: move to IPresentationCreationService?
        public Task CreatePresentationAsync( IProgress<IProgressInfo> progress )
        {
            Contract.Invariant( Project != null, "No project exists" );

            return Task.Run<FlameSetPresentation>( () =>
                {
                    progress.Report( new UndefinedProgress( "Creating presentation" ) );

                    return myPresentationCreationService.CreateFlameSetPresentation( Project.TraceLog );
                } )
                .RethrowExceptionsInUIThread()
                .ContinueWith( t =>
                {
                    Project.Presentation = t.Result;
                }, CancellationToken.None, TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.FromCurrentSynchronizationContext() )
                .RethrowExceptionsInUIThread();
        }

        public void UnloadAll()
        {
            // trigger unload of the current projec
            Project = null;

            WpfStatics.CollectStatisticsOnIdle();
        }
    }
}


text:
- Add more description in initializer

## 0.8.0 (2019-01-08)
- Provide a solution so you are no longer to restart rails server to apply any definition changes of experiments in development mode.

## 0.7.0 (2017-11-21)
- Set domain of cookie to :all to support cross-subdomain experiment.

## 0.6.2 (2017-09-01)
- [BF] Calling ab_test multiple times with different experiment name in one request may cause unwanted result if the definitions of experiments contain scope or rules.

## 0.6.1 (2017-08-31)
- Include EasyAb::RSpec with mailer type. Now you can use `#assign_variant!` in mailer spec

## 0.6.0 (2017-08-25)
- Add new API (`assign_variant!`)
- Rename spec helper #assign_variant to #assign_variant! and return instance of EasyAb::Grouping instead of true/false

## 0.5.1 (2017-08-25)
- Add new API (`easy_ab_test`) for internal use.

## 0.5.0 (2017-08-18)
- Add new API (`find_easy_ab_variant`) to retrieve specified user's variant

## 0.4.2 (2017-08-18)
- Specify URL parameter to assign variant works for all user instead of admin only in development environment now. In production and test, admin is still required for assigning variant by URL paramenter.

## 0.4.1 (2017-08-18)
- Provide helper to assign variant in rspec

## 0.4.0 (2017-08-16)
- You can specify user in `ab_test()` This useful when requests do not contain current_user. A well-known example is controllers which handle payment results by listening requests from 3rd party payment gateway.

## 0.3.0 (2017-08-16)
- Supports scope in config to define whether a user can join an experiment or not.

## 0.2.0 (2017-08-15)
- **API change**: If all rules failed, `ab_test` returns nil, instead of the first variant.

## 0.1.0
- Support winner

## 0.0.3
- Add new API `all_participated_experiments` to list current user's all participated experiments

## 0.0.1
- The first version :)