text:
package org.springframework.cloud.netflix.eureka;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import com.netflix.appinfo.HealthCheckHandler;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.appinfo.InstanceInfo.InstanceStatus;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.actuate.health.CompositeHealthContributor;
import org.springframework.boot.actuate.health.CompositeReactiveHealthContributor;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthContributor;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.boot.actuate.health.NamedContributor;
import org.springframework.boot.actuate.health.ReactiveHealthContributor;
import org.springframework.boot.actuate.health.ReactiveHealthIndicator;
import org.springframework.boot.actuate.health.Status;
import org.springframework.boot.actuate.health.StatusAggregator;
import org.springframework.cloud.client.discovery.health.DiscoveryCompositeHealthContributor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.Lifecycle;
import org.springframework.core.Ordered;
import org.springframework.util.Assert;

/**
 * A Eureka health checker, maps the application status into {@link InstanceStatus} that
 * will be propagated to Eureka registry.
 *
 * On each heartbeat Eureka performs the health check invoking registered
 * {@link HealthCheckHandler}. By default this implementation will perform aggregation of
 * all registered {@link HealthIndicator} through registered {@link StatusAggregator}.
 *
 * A {@code null} status is returned when the application context is closed (or in the
 * process of being closed). This prevents Eureka from updating the health status and only
 * consider the status present in the current InstanceInfo.
 *
 * @author Jakub Narloch
 * @author Spencer Gibb
 * @author Nowrin Anwar Joyita
 * @author Bertrand Renuart
 * @author Olga Maciaszek-Sharma
 * @see HealthCheckHandler
 * @see StatusAggregator
 */
public class EurekaHealthCheckHandler
		implements HealthCheckHandler, ApplicationContextAware, InitializingBean, Ordered, Lifecycle {

	private static final Map<Status, InstanceInfo.InstanceStatus> STATUS_MAPPING = new HashMap<>() {
		{
			put(Status.UNKNOWN, InstanceStatus.UNKNOWN);
			put(Status.OUT_OF_SERVICE, InstanceStatus.DOWN);
			put(Status.DOWN, InstanceStatus.DOWN);
			put(Status.UP, InstanceStatus.UP);
		}
	};

	private final StatusAggregator statusAggregator;

	private ApplicationContext applicationContext;

	private final Map<String, HealthContributor> healthContributors = new HashMap<>();

	/**
	 * {@code true} until the context is stopped.
	 */
	private boolean running = true;

	private final Map<String, ReactiveHealthContributor> reactiveHealthContributors = new HashMap<>();

	public EurekaHealthCheckHandler(StatusAggregator statusAggregator) {
		this.statusAggregator = statusAggregator;
		Assert.notNull(statusAggregator, "StatusAggregator must not be null");

	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext;
	}

	@Override
	public void afterPropertiesSet() {
		populateHealthContributors(applicationContext.getBeansOfType(HealthContributor.class));
		reactiveHealthContributors.putAll(applicationContext.getBeansOfType(ReactiveHealthContributor.class));
	}

	void populateHealthContributors(Map<String, HealthContributor> healthContributors) {
		for (Map.Entry<String, HealthContributor> entry : healthContributors.entrySet()) {
			// ignore EurekaHealthIndicator and flatten the rest of the composite
			// otherwise there is a never ending cycle of down. See gh-643
			if (entry.getValue() instanceof DiscoveryCompositeHealthContributor indicator) {
				indicator.getIndicators().forEach((name, discoveryHealthIndicator) -> {
					if (!(discoveryHealthIndicator instanceof EurekaHealthIndicator)) {
						this.healthContributors.put(name, (HealthIndicator) discoveryHealthIndicator::health);
					}
				});
			}
			else {
				this.healthContributors.put(entry.getKey(), entry.getValue());
			}
		}
	}

	@Override
	public InstanceStatus getStatus(InstanceStatus instanceStatus) {
		if (running) {
			return getHealthStatus();
		}
		else {
			// Return nothing if the context is not running, so the status held by the
			// InstanceInfo remains unchanged.
			// See gh-1571
			return null;
		}
	}

	protected InstanceStatus getHealthStatus() {
		Status status = getStatus(statusAggregator);
		return mapToInstanceStatus(status);
	}

	protected Status getStatus(StatusAggregator statusAggregator) {
		Set<Status> statusSet = new HashSet<>();
		for (HealthContributor contributor : healthContributors.values()) {
			processContributor(statusSet, contributor);
		}
		for (ReactiveHealthContributor contributor : reactiveHealthContributors.values()) {
			processContributor(statusSet, contributor);
		}
		return statusAggregator.getAggregateStatus(statusSet);
	}

	private void processContributor(Set<Status> statusSet, HealthContributor contributor) {
		if (contributor instanceof CompositeHealthContributor) {
			for (NamedContributor<HealthContributor> contrib : (CompositeHealthContributor) contributor) {
				processContributor(statusSet, contrib.getContributor());
			}
		}
		else if (contributor instanceof HealthIndicator) {
			statusSet.add(((HealthIndicator) contributor).health().getStatus());
		}
	}

	private void processContributor(Set<Status> statusSet, ReactiveHealthContributor contributor) {
		if (contributor instanceof CompositeReactiveHealthContributor) {
			for (NamedContributor<ReactiveHealthContributor> contrib : (CompositeReactiveHealthContributor) contributor) {
				processContributor(statusSet, contrib.getContributor());
			}
		}
		else if (contributor instanceof ReactiveHealthIndicator) {
			Health health = ((ReactiveHealthIndicator) contributor).health().block();
			if (health != null) {
				statusSet.add(health.getStatus());
			}
		}
	}

	protected InstanceStatus mapToInstanceStatus(Status status) {
		if (!STATUS_MAPPING.containsKey(status)) {
			return InstanceStatus.UNKNOWN;
		}
		return STATUS_MAPPING.get(status);
	}

	@Override
	public int getOrder() {
		// registered with a high order priority so the close() method is invoked early
		// and *BEFORE* EurekaAutoServiceRegistration
		// (must be in effect when the registration is closed and the eureka replication
		// triggered -> health check handler is
		// consulted at that moment)
		return Ordered.HIGHEST_PRECEDENCE;
	}

	@Override
	public void start() {
		running = true;
	}

	@Override
	public void stop() {
		running = false;
	}

	@Override
	public boolean isRunning() {
		return true;
	}

}


text:
var check = require('check-more-types');
var R = require('ramda');
var pkg = require('../package.json');
var info = pkg.name + ' - ' + pkg.description + '\n' +
  '  version: ' + pkg.version + '\n' +
  '  author: ' + JSON.stringify(pkg.author);

function isSmall(s) {
  return s < 100;
}

function isJustNumber(s) {
  return check.number(s) || (Number(s).toString() === s);
}

var isNumberOfCommits = R.allPredicates([isJustNumber, isSmall]);

function filterByCommitId(id, comparison) {
  return function (commits) {
    return commits.filter(function (c) {
      la(check.object(c), 'expected commit object', c);
      la(check.has(c, 'id'), 'commit object is missing id property', c);
      la(check.commitId(c.id), 'invalid commit id', c);
      return comparison(c.id, id);
    });
  };
}

function startsWith(start, s) {
  la(check.unemptyString(s), 'missing full string', arguments);
  la(check.unemptyString(start), 'missing start string', arguments);
  return s.indexOf(start) === 0;
}

function messageContains(word, commit) {
  la(check.object(commit) && check.unemptyString(commit.message),
    'invalid commit', commit);
  return commit.message.indexOf(word) !== -1;
}

function filterByMessage(word) {
  return function (commits) {
    var found = R.find(
      R.lPartial(messageContains, word),
      commits
    );
    return found ? [found] : [];
  };
}

function processOptions(options) {
  var R = require('ramda');
  var join = require('path').join;

  if (isNumberOfCommits(options.commits)) {
    options.commits = R.take(Number(options.commits));
  } else if (check.commitId(options.commits)) {
    options.commits = filterByCommitId(options.commits, R.eq);
  } else if (check.shortCommitId(options.commits)) {
    options.commits = filterByCommitId(options.commits,
      R.lPartial(startsWith, options.commits));
  } else if (check.unemptyString(options.commits)) {
    options.commits = filterByMessage(options.commits);
  }

  if (options.coverage && !check.absolute(options.coverage)) {
    options.coverage = join(options.repo, options.coverage);
  }

  if (!options.files) {
    options.files = R.alwaysTrue;
  } else {
    var filesFilter = new RegExp(options.files);
    options.files = function (filename) {
      return filesFilter.test(filename);
    };
  }

  return options;
}

function cliOptions() {
  var optimist = require('optimist');

  var program = optimist
    .option('version', {
      boolean: true,
      alias: 'v',
      description: 'show version and exit',
      default: false
    })
    .option('repo', {
      string: true,
      description: 'git repo path',
      default: '.'
    })
    .option('reset', {
      boolean: true,
      alias: 'r',
      description: 'erase previously collected coverage',
      default: false
    })
    .option('commits', {
      string: true,
      alias: 'c',
      description: 'commit filter, for example pick last two -c 2',
      default: 5
    })
    .option('update', {
      string: true,
      alias: 'u',
      description: 'path to JSON coverage file to update with'
    })
    .option('files', {
      string: true,
      alias: 'f',
      description: 'filter input files expression'
    })
    .option('open', {
      boolean: true,
      description: 'open all current HTML reports'
    })
    .usage(info)
    .argv;

  if (program.version) {
    console.log(info);
    process.exit(0);
  }

  if (program.help || program.h) {
    optimist.showHelp();
    process.exit(0);
  }

  return processOptions(program);
}

module.exports = cliOptions;

redpajama_set_name: RedPajamaGithub


text:
require 'faraday'
module Google
  module Compute
    class ParameterValidation < ArgumentError; end
    class BadRequest < RuntimeError; end
    class MethodNotOverridden < RuntimeError; end
    class ClientUnitialized < RuntimeError; end
    class OperationTimeout < RuntimeError; end
    class HashConvert < RuntimeError; end
    class ResourceNotFound < RuntimeError; end
    class ConnectionFail < Faraday::Error::ConnectionFailed; end
  end
end


text:
import Vue from 'vue';
import Router from 'vue-router';
import NotFound from '@/components/404';
import Home from '@/pages/home/index';
import Search from '@/pages/search/index';
import Edit from '@/pages/edit/index';
import Bell from '@/pages/bell/index';
import Person from '@/pages/person/index';
import TopicDetail from '@/pages/home/topics-detail/index';

Vue.use(Router);

export default new Router({
  mode: 'history',
  routes: [
    {
      path: '/',
      name: 'Home',
      component: Home,
    },
    {
      path: '/search',
      name: 'Search',
      component: Search,
    },
    {
      path: '/edit',
      name: 'Edit',
      component: Edit,
    },
    {
      path: '/bell',
      name: 'Bell',
      component: Bell,
    },
    {
      path: '/person',
      name: 'Person',
      component: Person,
    },
    {
      path: '/topics-detail/:id',
      name: 'topics-detail',
      component: TopicDetail,
    },
    {
      path: '*',
      name: '404',
      component: NotFound,
    },
  ],
});


text:
A pairs matching game in OpenGL.

The game uses the old fixed-pipeline method for OpenGL rendering.

![Screenshot](https://raw.githubusercontent.com/rfoligno/game-pairs/master/screenshot.png)

##Controls

Use the mouse to click on boxes and find doubles! Find two of the same letter to make a pair!

--

This game was originally created as part of an assignment while attending Swansea Metropolitan University for my B.Sc. in game development.


text:
using System;
using System.Reflection;

using MethodDecorator.Fody.Interfaces;

namespace SimpleTest.PnP
{
    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class, AllowMultiple = true)]
    class InterceptorWithPriorityAttribute : Attribute, IAspectMatchingRule, IPartialDecoratorInit1
    {
        string _Param;

        public string AttributeTargetTypes { get; set; }
        public bool AttributeExclude { get; set; }
        public int AttributePriority { get; set; }
        public int AspectPriority { get; set; }

        public InterceptorWithPriorityAttribute(string iParam) { _Param = iParam; }

        public void Init(MethodBase iMethod)
        {
            TestRecords.Record(Method.Init, new object[] { _Param , AspectPriority, AttributePriority});
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace CraneAlert
{
    public class RemoteCtlDev
    {
        private string idLockDevice;

        public virtual string IdLockDevice
        {
            get { return idLockDevice; }
            set { idLockDevice = value; }
        }

        private string simCardNo;

        public virtual string SimCardNo
        {
            get { return simCardNo; }
            set { simCardNo = value; }
        }

        private string customNo;

        public virtual string CustomNo
        {
            get { return customNo; }
            set { customNo = value; }
        }

        private string idDevice;

        public virtual string IdDevice
        {
            get { return idDevice; }
            set { idDevice = value; }
        }

        private string status;

        public virtual string Status
        {
            get { return status; }
            set { status = value; }
        }

        private DateTime lastActionTime;

        public virtual DateTime LastActionTime
        {
            get { return lastActionTime; }
            set { lastActionTime = value; }
        }
        private string workArea;

        public virtual string WorkArea
        {
            get { return workArea; }
            set { workArea = value; }
        }

        private string lastCmdName;

        public virtual string LastCmdName
        {
            get { return lastCmdName; }
            set { lastCmdName = value; }
        }

        private string memo;

        public virtual string Memo
        {
            get { return memo; }
            set { memo = value; }
        }

        private string count;

        public virtual string Count
        {
            get { return count; }
            set { count = value; }
        }
        private string category;

        public virtual string Category
        {
            get { return category; }
            set { category = value; }
        }
    }
}


text:
from setuptools import setup, find_packages

setup(
    name='apikit',
    version='0.4',
    url='http://github.com/pudo/apikit',
    license='MIT',
    author='Friedrich Lindenberg',
    author_email='friedrich@pudo.org',
    description='A set of utility functions for RESTful Flask applications.',
    packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
    namespace_packages=[],
    include_package_data=True,
    zip_safe=False,
    platforms='any',
    install_requires=[
        'Flask', 'six'
    ],
    classifiers=[
        'Development Status :: 4 - Beta',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.6',
        'Environment :: Web Environment',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
        'Topic :: Software Development :: Libraries :: Python Modules'
    ]
)


text:
from django.utils.translation import ugettext_lazy as _
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth.models import User

from coordinators.models import Coordinator

class CoordinatorInline(admin.StackedInline):
    model = Coordinator
    can_delete = False
    verbose_name_plural = _('coordinator')

class UserAdmin(BaseUserAdmin):
    inlines = (CoordinatorInline, )

# Re-register UserAdmin
admin.site.unregister(User)
admin.site.register(User, UserAdmin)


text:
package com.cardpay.pccredit.intopieces.model;

import com.wicresoft.jrad.base.database.model.ModelParam;
import com.wicresoft.jrad.base.database.model.BusinessModel;

/**
 *
 * @author 贺珈
 *
 */
@ModelParam(table = "qz_appln_dcnr")
public class QzApplnDcnr extends BusinessModel {

	private static final long serialVersionUID = 1L;
	private String id;
	private String customerId;
	private String reportId;
	private String reportName;
	private String loadStatus;
	private String applicationId;
	private String hetongId;
	private String userName;
	private String cardId;
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getCustomerId() {
		return customerId;
	}
	public void setCustomerId(String customerId) {
		this.customerId = customerId;
	}
	public String getReportId() {
		return reportId;
	}
	public void setReportId(String reportId) {
		this.reportId = reportId;
	}
	public String getReportName() {
		return reportName;
	}
	public void setReportName(String reportName) {
		this.reportName = reportName;
	}
	public String getLoadStatus() {
		return loadStatus;
	}
	public void setLoadStatus(String loadStatus) {
		this.loadStatus = loadStatus;
	}
	public String getApplicationId() {
		return applicationId;
	}
	public void setApplicationId(String applicationId) {
		this.applicationId = applicationId;
	}
	public String getHetongId() {
		return hetongId;
	}
	public void setHetongId(String hetongId) {
		this.hetongId = hetongId;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getCardId() {
		return cardId;
	}
	public void setCardId(String cardId) {
		this.cardId = cardId;
	}

}


text:
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="20dp"
    android:height="20dp"
    android:viewportWidth="20"
    android:viewportHeight="20"
    android:tint="?attr/colorControlNormal">
  <path
      android:fillColor="@android:color/white"
      android:pathData="M6.188,10.625H13.812V9.375H6.188ZM3.062,16.938V3.062H16.938V16.938Z"/>
</vector>


text:
namespace QuartzCore.Dependency
{
    public enum LifeStyle
    {
        Singleton,
        Transient
    }
}


text:
<TITLE>Review for Time to Kill, A (1996)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Time to Kill, A (1996)

reviewed by
Michael Redman

                                A TIME TO KILL
                       A film review by Michael Redman
                        Copyright 1996 Michael Redman

*** (out of ****)

Strongly reminiscent of "To Kill A Mockingbird", this is an incongruent
combination of riveting performances, a controversial topic, compelling
tear-jerking, one dimensional characters and overly simplistic political
statements. The film is based on John Grisman's first novel, and feels
much like the rest of his books turned films ("The Firm", "Pelican
Brief", "The Client").

A young black girl is brutally raped, beaten and left for dead by two
southern rednecks. Arrested and lead through the courthouse, they are
gunned down by the girl's father, Carl Lee Hailey (Samuel L. Jackson)
who has learned they would probably be released in less than 10 years
because she is black and they are white.  The remainder of the
two-and-a-half hour film features his trial and the question of whether
a black man can get a fair trial in Mississippi with an all-white jury.
Hailey's white lawyer Jake Brigance is played by Matthew McConaughey,
Hollywood's latest instant star and the focus of the film. In a twist,
this particular golden boy's hype is justified and he is one of the high
points of the movie. Aided by his alcoholic mentor (Donald Sutherland),
sleazy buddy (Oliver Platt) and sexy plucky northern legal aide (Sandra
Bullock); Brigance sets out to find a way out of what looks like a
no-win situation.

The film addresses heavy questions concerning racism in a bizarre mix of
some very human situations and a few cartoonish scenes. Jackson gives a
great performance in his talks with McConaughey concerning his view of
black and white relations. Contrast this with the caricature of the
self-serving NAACP representatives and the cinematic short-cut of white
racism as evidenced by the KKK, both of which are peopled by cardboard
characters.

The acting and casting are also a mixed bag. Jackson and McConaughey are
notable in their roles. Bullock, a personal unfavorite, turns in one of
her better performances (faint praise indeed), but for a strong female
role, she is sure dressed as if she=B9s fulfilling the babe role. It=B9s
entertaining to see Donald Sutherland on one side and son Keifer on the
other, but they are both one-note characters. Sutherland The Younger is
a KKK member in yet another of his (surprise!) psycho roles.

Platt has a fascinating screen presence and could have contributed much
to the film, but is casted in a throwaway role. There are far too many
characters who clutter up the story and could have been dropped from the
movie without affecting the story at all.

The strong acting makes up for the film's flaws, but leaves you
wondering how it would have worked if the rest of the elements had
measured up.

[This appeared in "The Bloomington Voice", Bloomington, Indiana,
8/15/96. Michael Redman can be reached at mredman@bvoice.com]

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


text:
<!DOCTYPE html>
<html>

<head>
    <title>Redirecting to "Permissions"</title>
    <link rel="canonical" href="../ImplementationGuidePermissions.html" />
    <meta name="robots" content="noindex">
    <meta charset="utf-8" />
    <meta http-equiv="refresh" content="0; url=../ImplementationGuidePermissions.html" />
</head>

</html>


text:
package org.wso2.carbon.gateway.core.config.dsl.external.deployer;

import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CommonTokenStream;
import org.osgi.framework.BundleContext;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ReferenceCardinality;
import org.osgi.service.component.annotations.ReferencePolicy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wso2.carbon.deployment.engine.Artifact;
import org.wso2.carbon.deployment.engine.ArtifactType;
import org.wso2.carbon.deployment.engine.Deployer;
import org.wso2.carbon.deployment.engine.exception.CarbonDeploymentException;
import org.wso2.carbon.gateway.core.config.ConfigRegistry;
import org.wso2.carbon.gateway.core.config.GWConfigHolder;
import org.wso2.carbon.gateway.core.config.dsl.external.WUMLConfigurationBuilder;
import org.wso2.carbon.gateway.core.config.dsl.external.wuml.WUMLBaseListenerImpl;
import org.wso2.carbon.gateway.core.config.dsl.external.wuml.generated.WUMLLexer;
import org.wso2.carbon.gateway.core.config.dsl.external.wuml.generated.WUMLParser;
import org.wso2.carbon.gateway.core.inbound.ProviderRegistry;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * A class responsible for read the .iflow files and deploy them to the runtime Object model.
 */
@Component(
        name = "org.wso2.carbon.gateway.core.config.dsl.external.deployer.IFlowDeployer",
        immediate = true,
        service = Deployer.class
)
public class IFlowDeployer implements Deployer {

    private ArtifactType artifactType;

    private URL directoryLocation;

    private Map<String, GWConfigHolder> artifactMap = new HashMap<>();

    private static final Logger logger = LoggerFactory.getLogger(IFlowDeployer.class);

    public static final String EXTERNAL_DSL_CONFIGS_DIRECTORY = "integration-flows";

    @Activate
    protected void activate(BundleContext bundleContext) {
        //TODO: check whether this guarantee whether this deployer registered on
        //TODO: after all mandatory services are available
    }

    @Reference(
            name = "inbound-provider-registry-service",
            service = ProviderRegistry.class,
            cardinality = ReferenceCardinality.MANDATORY,
            policy = ReferencePolicy.DYNAMIC,
            unbind = "removeInboundProviderRegistry"
    )
    protected void addInboundProviderRegistry(ProviderRegistry registry) {
    }

    protected void removeInboundProviderRegistry(ProviderRegistry registry) {
    }

    @Reference(
            name = "outbound-provider-registry-service",
            service = org.wso2.carbon.gateway.core.outbound.ProviderRegistry.class,
            cardinality = ReferenceCardinality.MANDATORY,
            policy = ReferencePolicy.DYNAMIC,
            unbind = "removeOutboundProviderRegistry"
    )
    protected void addOutboundProviderRegistry(
            org.wso2.carbon.gateway.core.outbound.ProviderRegistry registry) {
    }

    protected void removeOutboundProviderRegistry(
            org.wso2.carbon.gateway.core.outbound.ProviderRegistry registry) {
    }

    @Reference(
            name = "mediator-provider-registry-service",
            service = org.wso2.carbon.gateway.core.flow.ProviderRegistry.class,
            cardinality = ReferenceCardinality.MANDATORY,
            policy = ReferencePolicy.DYNAMIC,
            unbind = "removeMediatorProviderRegistry"
    )
    protected void addMediatorProviderRegistry(
            org.wso2.carbon.gateway.core.flow.ProviderRegistry registry) {
    }

    protected void removeMediatorProviderRegistry(
            org.wso2.carbon.gateway.core.flow.ProviderRegistry registry) {
    }

    @Override
    public void init() {
        artifactType = new ArtifactType<String>("iflow");
        try {
            directoryLocation = new URL("file:" + EXTERNAL_DSL_CONFIGS_DIRECTORY);
        } catch (MalformedURLException e) {
            logger.error("Error while initializing directoryLocation" + directoryLocation.getPath(), e);
        }
    }

    @Override
    public Object deploy(Artifact artifact) throws CarbonDeploymentException {
        updateESBConfig(artifact);
        return artifact.getFile().getName();
    }

    @Override
    public void undeploy(Object o) throws CarbonDeploymentException {
        GWConfigHolder configHolder = artifactMap.remove((String) o);
        ConfigRegistry.getInstance().removeGWConfig(configHolder);
    }

    @Override
    public Object update(Artifact artifact) throws CarbonDeploymentException {
        updateESBConfig(artifact);
        return artifact.getFile().getName();
    }

    @Override
    public URL getLocation() {
        return directoryLocation;
    }

    @Override
    public ArtifactType getArtifactType() {
        return artifactType;
    }

    private void updateESBConfig(Artifact artifact) {

        InputStream inputStream = null;
        try {
            File file = artifact.getFile();
            inputStream = new FileInputStream(file);

            CharStream cs = new ANTLRInputStream(inputStream);

            // Passing the input to the lexer to create tokens
            WUMLLexer lexer = new WUMLLexer(cs);

            CommonTokenStream tokens = new CommonTokenStream(lexer);

            // Passing the tokens to the parser to create the parse trea.
            WUMLParser parser = new WUMLParser(tokens);

            // Adding the listener to facilitate walking through parse tree.
            WUMLBaseListenerImpl wumlBaseListener = new WUMLBaseListenerImpl();

            parser.addParseListener(wumlBaseListener);
            parser.script();

            WUMLConfigurationBuilder.IntegrationFlow integrationFlow = wumlBaseListener.getIntegrationFlow();
            GWConfigHolder configHolder = integrationFlow.getGWConfigHolder();
            if (configHolder != null) {
                artifactMap.put(file.getName(), configHolder);
                ConfigRegistry.getInstance().addGWConfig(configHolder);
            }

        } catch (IOException e) {
            logger.error("Error while creating Cheetah object model", e);
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    logger.error("Error while closing the input stream", e);
                }
            }
        }
    }

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;

namespace AlexaSkillsKit.Speechlet
{
    public class System
    {
        public Application Application { get; private set; }
        public User User { get; set; }
        public Device Device { get; set; }

        public static System FromJson(JObject json)
        {
            if (json != null)
            {
                return new System
                {
                    Application = Application.FromJson(json.Value<JObject>("application")),
                    User = User.FromJson(json.Value<JObject>("user")),
                    Device = Device.FromJson(json.Value<JObject>("device"))
                };
            }

            return null;
        }
    }
}


text:
 Curiosity as a value is important to me. When you emphasize the curious search for knowledge, growth, wisdom and adventure
as an end unto itself, you take pressure off yourself. Whether you're learning something new or striving towards some accomplishment,
a sense of unmitigated curiosity and wonder can be more important than the concrete task at hand. This applies to everything from
social situations, cultural exploration and intellectual stimulation.

A friend recently asked advice for musical growth. I told him not to get bogged down in the technicalities and the daunting immensity
of the task at hand. Stay curious, stick to the task at hand regardless of any concrete accomplishments, and growth will come on its own.

Affirming your values is an important tool for combatting stereotype threat and performance anxiety. If you affirm the values of
curiosity, growth, creativity, and adventure with an emphasis on personal development and challenge, you can take away the psychological
threat of underperforming. Focusing on your worth as a creative learner can take the bite out of a fear of failure. Know your worth
and don't worry about others' perceptions.


text:
// Generated on 2013-11-24 using generator-angular 0.6.0-rc.2
'use strict';

// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// use this if you want to recursively match all subfolders:
// 'test/spec/**/*.js'
module.exports = function(grunt) {

    // Load grunt tasks automatically
    require('load-grunt-tasks')(grunt);

    // Time how long tasks take. Can help when optimizing build times
    require('time-grunt')(grunt);

    // Define the configuration for all the tasks
    grunt.initConfig({

        // Project settings
        yeoman: {
            // configurable paths
            app: require('./bower.json').appPath || 'app',
            dist: 'dist'
        },

        // Make sure code styles are up to par and there are no obvious mistakes
        jshint: {
            options: {
                jshintrc: '.jshintrc',
                reporter: require('jshint-stylish')
            },
            all: ['<%= yeoman.app %>/scripts/{,*/}*.js'],
            test: {
                options: {
                    jshintrc: 'test/.jshintrc'
                },
                src: ['test/spec/{,*/}*.js']
            }
        },

        // Test settings
        karma: {
            unit: {
                configFile: 'karma.conf.js',
                singleRun: true
            }
        }
    });

    grunt.registerTask('test', ['jshint:all', 'karma']);

    grunt.registerTask('default', ['jshint:all', 'test']);
};


text:
#region

using System;
using System.Linq;

using IV_Play.Properties;

#endregion

namespace IV_Play
{
  internal partial class GameList
  {
    public void GoToLastGame()
    {
      try
      {
        int i = 0;
        if (FavoritesMode == FavoritesMode.Favorites)
        {
          Game game = _search.FindGameByName(Settings.Default.last_game, out i);
          if (game != null && game.IsFavorite)
            SelectedGame = game;
        }
        else
        {
          Game game = _search.FindGameByName(Settings.Default.last_game, out i);
          SelectedGame = game ?? Games.First().Value;
        }
      }
      catch (Exception)
      {
        SelectedGame = null;
      }
    }

    private void GoToPreviousCharacter()
    {
      Game game;

      game = GetNodeParent(SelectedGame ?? GetNodeAtRow(VerticalScroll.Value / RowHeight));

      if (game == null)
        return;

      char nextKey;
      char key = Char.ToLower(game.Description.ToCharArray()[0]);

      nextKey = key == 'a' ? '9' : Char.ToLower((char)(key - 1));

      bool favorite = game.IsFavorite;
      while (!GoToLetter(nextKey, favorite))
      {
        if (nextKey == key)
          return;

        if (nextKey == '(' - 1)
        {
          nextKey = 'z';
          favorite = CountFavorites > 0 ? !game.IsFavorite : game.IsFavorite;
        }
        else
          nextKey--;
      }
    }

    private void ScrollTo(int inRow)
    {
      try
      {
        int row = inRow;
        row = row * RowHeight;

        if (row > VerticalScroll.Value)
          row += ClientRectangle.Height % RowHeight;
        int topBounds = VerticalScroll.Value + ClientRectangle.Height;
        if (!(row > VerticalScroll.Value && row < VerticalScroll.Value + ClientRectangle.Height))
          if (row >= topBounds)
            VerticalScroll.Value += row - topBounds + RowHeight;
          else
            VerticalScroll.Value = row;
      }
      catch (Exception ex)
      {
        Logger.WriteToLog(ex);
      }
      _prevScrollValue = Math.Min(VerticalScroll.Value, VerticalScroll.Maximum);
    }

    private bool GoToLetter(char key, bool favorite)
    {
      bool found = false;
      key = Char.ToLower(key);

      if (Games.Count > 1)
      {
        foreach (Game game in Games.Values)
        {
          if (!string.IsNullOrEmpty(game.Description) && (game.IsParent || game.IsFavorite) &&
              Char.ToLower(game.Description.ToCharArray()[0]) == key && game.IsFavorite == favorite)
          {
            found = true;
            SelectedGame = game;
            break;
          }
        }
      }
      else
        return true;
      return found;
    }

    private void GoToNextLetter()
    {

      Game game;

      game = GetNodeParent(SelectedGame ?? GetNodeAtRow(VerticalScroll.Value / RowHeight));

      if (game == null)
        return;

      //Game game;
      //if (SelectedGame == null)
      //{
      //    game = GetNodeParent(GetNodeAtRow(VerticalScroll.Value/RowHeight));
      //    _selectedGame = game;
      //}
      //else
      //    game = GetNodeParent(SelectedGame);

      char nextKey;
      char key = Char.ToLower(game.Description.ToCharArray()[0]);

      nextKey = key == '9' ? 'a' : Char.ToLower((char)(key + 1));

      bool favorite = game.IsFavorite;
      while (!GoToLetter(nextKey, favorite))
      {
        if (nextKey == key)
          return;

        if (nextKey == 'z' + 1)
        {
          nextKey = '(';
          favorite = CountFavorites > 0 ? !game.IsFavorite : game.IsFavorite;
        }
        else
          nextKey++;
      }
    }

    private void NavigateBackward(int n)
    {
      int row = Math.Max(SelectedRow - n, 0);
      if (row != SelectedRow)
        SelectedGame = GetNodeAtRow(row);
    }

    private void NavigateForward(int n)
    {
      int row = Math.Min(SelectedRow + n, Games.Count - 1);
      if (row != SelectedRow)
        SelectedGame = GetNodeAtRow(row);
    }
  }
}


text:
package com.github.kabdelrahman.transtat.api

import akka.actor.ActorRef
import akka.http.scaladsl.server.{Route, RouteConcatenation}
import com.github.kabdelrahman.transtat.bootstrap.AppConfig._
import com.github.kabdelrahman.transtat.metrics.AppWideMetrics
import com.github.kabdelrahman.transtat.persistence.{CacheController, ResetTickWheel, Tick}
import com.github.kabdelrahman.transtat.service.stats.StatService
import com.github.kabdelrahman.transtat.service.transaction.TransactionService
import com.github.kabdelrahman.transtat.swagger.SwaggerDocumentationService

import scala.concurrent.duration._

trait Api extends RouteConcatenation {
  this: Core =>

  private implicit val _ = system.dispatcher

  implicit val metrics = AppWideMetrics

  implicit val cacheController: ActorRef = system.actorOf(CacheController())

  // TODO refactor the scheduling part to mock it in tests
  // non-cancellable scheduler for cache controlling (ticking every 1 second to refresh cache)
  system.scheduler.schedule(0.seconds, cacheTick, cacheController, Tick)
  system.scheduler.schedule(cacheTtl, cacheTtl, cacheController, ResetTickWheel)

  val routes: Route = {
    new TransactionService().route ~
      new StatService().route ~
      SwaggerDocumentationService.routes
  }
}


text:
var Tokenizer = require('./tokenizer');
var SimpleOptimizer = require('./optimizers/simple');
var AdvancedOptimizer = require('./optimizers/advanced');

function SelectorsOptimizer(options, context) {
  this.options = options || {};
  this.context = context || {};
}

SelectorsOptimizer.prototype.process = function (data, stringifier) {
  var tokens = new Tokenizer(this.context, this.options.advanced, this.options.sourceMap).toTokens(data);

  new SimpleOptimizer(this.options).optimize(tokens);
  if (this.options.advanced)
    new AdvancedOptimizer(this.options, this.context).optimize(tokens);

  return stringifier.toString(tokens);
};

module.exports = SelectorsOptimizer;


text:
package provider

import (
	"context"
	"io"
	"net/http"
	"os"

	"github.com/pkg/errors"
)

// Filesystem provides a way to load files from the filesystem.
type Filesystem struct {
	Dir http.Dir
}

// Provide provides a file via the virtual http.Dir filesystem.
func (fp *Filesystem) Provide(ctx context.Context, filename string) (io.ReadCloser, error) {
	// Try to open the image from the virtual filesystem.
	f, err := fp.Dir.Open(filename)
	if err != nil {
		if errors.As(err, &os.PathError{}) {
			return nil, ErrNotFound
		}

		return nil, errors.Wrap(err, "cannot get file from filesystem")
	}

	return f, nil
}


text:
<?php

namespace LpFactory\Bundle\CoreBundle;

use Doctrine\Bundle\DoctrineBundle\DependencyInjection\Compiler\DoctrineOrmMappingsPass;
use LpFactory\Bundle\CoreBundle\DependencyInjection\Compiler\BlockConfigurationPass;
use LpFactory\Bundle\CoreBundle\DependencyInjection\Compiler\BlockDataProviderPass;
use LpFactory\Bundle\CoreBundle\DependencyInjection\Compiler\UrlSatinizerPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Bundle\Bundle;

/**
 * Class LpFactoryCoreBundle
 *
 * @package LpFactory\Bundle\CoreBundle
 * @author jobou
 */
class LpFactoryCoreBundle extends Bundle
{
    /**
     * @{inheritdoc}
     *
     * @param ContainerBuilder $container
     */
    public function build(ContainerBuilder $container)
    {
        parent::build($container);

        $modelDir = realpath($this->getPath() . '/Resources/config/model');

        $mappings = array(
            $modelDir => 'LpFactory\Bundle\CoreBundle\Model',
        );

        $container->addCompilerPass(
            DoctrineOrmMappingsPass::createYamlMappingDriver(
                $mappings
            )
        );

        $container->addCompilerPass(new BlockDataProviderPass());
        $container->addCompilerPass(new BlockConfigurationPass());
    }
}


text:
import Sora from "sora-js-sdk";

let RTCPeerConnection = window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
let RTCSessionDescription = window.RTCSessionDescription || window.mozRTCSessionDescription;
navigator.getUserMedia = navigator.getUserMedia ||
                         navigator.webkitGetUserMedia ||
                         navigator.mozGetUserMedia ||
                         navigator.msGetUserMedia;

class Anzu {
  /**
   * @constructor
   * @param {string} rolse - ロール (upstram or downstream)
   * @param {?object} [params={anzuUrl: null, signalingUrl: null}] - URL 設定
   */
  constructor(role, params={ anzuUrl: null, signalingUrl: null }) {
    this.anzuUrl = params.anzuUrl === null ? "https://anzu.shiguredo.jp/api/" : params.anzuUrl;
    this.signalingUrl = params.signalingUrl === null ? "wss://anzu.shiguredo.jp/signaling" : params.signalingUrl;
    if (role !== "upstream" && role !== "downstream") {
      let error = new Error("Role " + role + " is not defined");
      throw error;
    }
    this.role = role;
    this._onError = function() {};
    this._onDisconnect = function() {};
  }
  /**
   * Anzu を開始する
   * @param {string} channelId - チャンネルID
   * @param {string} token - アクセストークン
   * @param {object} [constraints={video: true, audio: true}] - LocalMediaStream オブジェクトがサポートするメディアタイプ
   */
  start(channelId, token, constraints=null, codecType="VP8", multistream=false) {
    if (this.role === "upstream") {
      let c = constraints === null ? { video: true, audio: true } : constraints;
      return this._startUpstream(channelId, token, c, codecType, multistream);
    }
    else if (this.role === "downstream") {
      return this._startDownstream(channelId, token, codecType, multistream);
    }
  }
  /**
   * アップストリームを開始する
   * @private
   * @param {string} channelId - チャンネルID
   * @param {string} upstreamToken - アップストリームトークン
   * @param {object} constraints - LocalMediaStream オブジェクトがサポートするメディアタイプ
   * )
   */
  _startUpstream(channelId, upstreamToken, constraints, codecType, multistream) {
    let getUserMedia = (constraints) => {
      return new Promise((resolve, reject) => {
        if (navigator.getUserMedia) {
          navigator.getUserMedia(constraints, (stream) => {
            this.trace("Upstream getUserMedia constraints", constraints);
            this.stream = stream;
            resolve({ stream: stream });
          }, (err) => { reject(err); });
        } else {
          reject();
        }
      });
    };
    let createOffer = () => {
      this.sora = new Sora(this.signalingUrl).connection();
      this.sora.onError(this._onError);
      this.sora.onDisconnect(this._onDisconnect);
      return this.sora.connect({
        role: "upstream",
        channelId: channelId,
        accessToken: upstreamToken,
        codecType: codecType,
        multistream: multistream
      });
    };
    let createPeerConnection = (offer) => {
      this.trace("Upstream Offer sdp", offer.sdp);
      this.trace("Upstream Offer clientId", offer.client_id);
      this.trace("Upstream Offer config", offer.config);
      return new Promise((resolve, _reject) => {
        this.clientId = offer.client_id;
        this.pc = new RTCPeerConnection(offer.config);
        this.pc.addStream(this.stream);
        resolve(offer);
      });
    };
    let createAnswer = (offer) => {
      return new Promise((resolve, reject) => {
        this.pc.oniceconnectionstatechange = (event) => {
          this.trace("Upstream oniceconnectionstatechange", {
            iceConnectionState: this.pc.iceConnectionState,
            iceGatheringState: this.pc.iceGatheringState
          });
          switch (this.pc.iceConnectionState) {
            case "connected":
            case "completed":
              resolve({ clientId: this.clientId, stream: this.stream });
              break;
            case "failed":
              reject(event);
              break;
          }
        };
        this.pc.onicecandidate = (event) => {
          this.trace("Upstream onicecandidate", {
            candidate: event.candidate,
            iceConnectionState: this.pc.iceConnectionState,
            iceGatheringState: this.pc.iceGatheringState
          });
          if (event.candidate !== null) {
            this.sora.candidate(event.candidate);
          }
        };
        this.pc.setRemoteDescription(new RTCSessionDescription(offer), () => {
          this.pc.createAnswer((answer) => {
            this.trace("Upstream answer sdp", answer.sdp);
            this.pc.setLocalDescription(answer, () => {
              this.sora.answer(answer.sdp);
            }, (error) => { reject(error); });
          }, (error) => { reject(error); });
        }, (error) => { reject(error); });
      });
    };
    return getUserMedia(constraints)
      .then(createOffer)
      .then(createPeerConnection)
      .then(createAnswer)
      .catch(e => {
        this.disconnect();
        return Promise.reject(e);
      });
  }
  /**
   * ダウンストリームを開始する
   * @private
   * @param {string} channelId - チャンネルID
   * @param {string} downstreamToken - ダウンストリームトークン
   */
  _startDownstream(channelId, downstreamToken, codecType, multistream) {
    let createOffer = () => {
      this.sora = new Sora(this.signalingUrl).connection();
      this.sora.onError(this._onError);
      this.sora.onDisconnect(this._onDisconnect);
      return this.sora.connect({
        role: "downstream",
        channelId: channelId,
        accessToken: downstreamToken,
        codecType: codecType,
        multistream: multistream
      });
    };
    let createPeerConnection = (offer) => {
      this.trace("Downstream offer sdp", offer.sdp);
      this.trace("Downstream offer clientId", offer.client_id);
      this.trace("Downstream offer config", offer.config);
      return new Promise((resolve, _reject) => {
        this.clientId = offer.client_id;
        this.pc = new RTCPeerConnection(offer.config);
        resolve(offer);
      });
    };
    let createAnswer = (offer) => {
      // firefox と chrome のタイミング問題判定用 flag
      this.icecandidateConnected = false;
      this.addstreamCompleted = false;
      return new Promise((resolve, reject) => {
        this.pc.onaddstream = (event) => {
          this.addstreamCompleted = true;
          this.stream = event.stream;
          this.trace("Downstream onaddstream", event.stream.id);
          if (this.icecandidateConnected) {
            resolve({ clientId: this.clientId, stream: this.stream });
          }
        };
        this.pc.oniceconnectionstatechange = (event) => {
          this.trace("Downstream oniceconnectionstatechange", {
            iceConnectionState: this.pc.iceConnectionState,
            iceGatheringState: this.pc.iceGatheringState
          });
          switch (this.pc.iceConnectionState) {
            case "connected":
            case "completed":
              this.icecandidateConnected = true;
              if (this.addstreamCompleted) {
                resolve({ clientId: this.clientId, stream: this.stream });
              }
              break;
            case "failed":
              reject(event);
              break;
          }
        };
        this.pc.onicecandidate = (event) => {
          this.trace("Downstream onicecandidate", {
            candidate: event.candidate,
            iceConnectionState: this.pc.iceConnectionState,
            iceGatheringState: this.pc.iceGatheringState
          });
          if (event.candidate !== null) {
            this.sora.candidate(event.candidate);
          }
        };
        this.pc.setRemoteDescription(new RTCSessionDescription(offer), () => {
          this.pc.createAnswer((answer) => {
            this.trace("Downstream answer sdp", answer.sdp);
            this.pc.setLocalDescription(answer, () => {
              this.sora.answer(answer.sdp);
            }, (error) => { reject(error); });
          }, (error) => { reject(error); });
        }, (error) => { reject(error); });
      });
    };
    return createOffer()
      .then(createPeerConnection)
      .then(createAnswer)
      .catch(e => {
        this.disconnect();
        return Promise.reject(e);
      });
  }
  /**
   * コンソールログを出力する
   * @private
   * @param {string} text - タイトル
   * @param {string|object} value - 値
   */
  trace(text, value) {
    let now = "";
    if (window.performance) {
      now = (window.performance.now() / 1000).toFixed(3) + ": ";
    }

    if (typeof value === "object" && value !== null) {
      console.info(now + text + "\n" + JSON.stringify(value, null, 2)); // eslint-disable-line
    }
    else {
      console.info(now + text + "\n" + value); // eslint-disable-line
    }
  }
  /**
   * 切断する
   */
  disconnect() {
    if (this.stream) {
      this.stream.getTracks().forEach((t) => {
        t.stop();
      });
    }
    this.stream = null;
    if (this.sora) {
      this.sora.disconnect();
    }
    this.sora = null;
    if (this.pc && (this.pc.signalingState !== "closed")) {
      this.pc.oniceconnectionstatechange = null;
      this.pc.close();
    }
    this.pc = null;
  }
  /**
   * エラー時のコールバックを登録する
   * @param {function} コールバック
   */
  onError(f) {
    this._onError = f;
    if (this.sora) {
      this.sora.onError(f);
    }
  }
  /**
   * 切断時のコールバックを登録する
   * @param {function} コールバック
   */
  onDisconnect(f) {
    this._onDisconnect = f;
    if (this.sora) {
      this.sora.onDisconnect(f);
    }

  }
}

module.exports = Anzu;


text:
//
// UniqueIdSet.cs
//
// Author: Jeffrey Stedfast <jeff@xamarin.com>
//
// Copyright (c) 2013-2016 Xamarin Inc. (www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

using System;
using System.Text;
using System.Collections;
using System.Globalization;
using System.Collections.Generic;

using MailKit.Search;

namespace MailKit {
	/// <summary>
	/// A set of unique identifiers.
	/// </summary>
	/// <remarks>
	/// When dealing with a large number of unique identifiers, it may be more efficient to use a
	/// <see cref="UniqueIdSet"/> than a typical IList<<see cref="UniqueId"/>>.
	/// </remarks>
	public class UniqueIdSet : IList<UniqueId>
	{
		struct Range
		{
			public uint Start;
			public uint End;

			public Range (uint start, uint end)
			{
				Start = start;
				End = end;
			}

			public int Count {
				get { return (int) (Start <= End ? End - Start : Start - End) + 1; }
			}

			public bool Contains (uint uid)
			{
				if (Start <= End)
					return uid >= Start && uid <= End;

				return uid <= Start && uid >= End;
			}

			public int IndexOf (uint uid)
			{
				if (Start <= End) {
					if (uid < Start || uid > End)
						return -1;

					return (int) (uid - Start);
				}

				if (uid > Start || uid < End)
					return -1;

				return (int) (Start - uid);
			}

			public uint this [int index] {
				get {
					return Start <= End ? Start + (uint) index : Start - (uint) index;
				}
			}

			public IEnumerator<uint> GetEnumerator ()
			{
				if (Start <= End) {
					for (uint uid = Start; uid <= End; uid++)
						yield return uid;
				} else {
					for (uint uid = Start; uid >= End; uid--)
						yield return uid;
				}

				yield break;
			}

			public override string ToString ()
			{
				if (Start == End)
					return Start.ToString (CultureInfo.InvariantCulture);

				if (Start <= End && End == uint.MaxValue)
					return string.Format (CultureInfo.InvariantCulture, "{0}:*", Start);

				return string.Format (CultureInfo.InvariantCulture, "{0}:{1}", Start, End);
			}
		}

		readonly List<Range> ranges = new List<Range> ();
		long count;

		/// <summary>
		/// Initializes a new instance of the <see cref="MailKit.UniqueIdSet"/> class.
		/// </summary>
		/// <remarks>
		/// Creates a new unique identifier set.
		/// </remarks>
		/// <param name="validity">The uid validity.</param>
		/// <param name="order">The sorting order to use for the unique identifiers.</param>
		/// <exception cref="System.ArgumentOutOfRangeException">
		/// <paramref name="order"/> is invalid.
		/// </exception>
		public UniqueIdSet (uint validity, SortOrder order = SortOrder.None)
		{
			switch (order) {
			case SortOrder.Descending:
			case SortOrder.Ascending:
			case SortOrder.None:
				break;
			default:
				throw new ArgumentOutOfRangeException ("order");
			}

			Validity = validity;
			SortOrder = order;
		}

		/// <summary>
		/// Initializes a new instance of the <see cref="MailKit.UniqueIdSet"/> class.
		/// </summary>
		/// <remarks>
		/// Creates a new unique identifier set.
		/// </remarks>
		/// <param name="order">The sorting order to use for the unique identifiers.</param>
		/// <exception cref="System.ArgumentOutOfRangeException">
		/// <paramref name="order"/> is invalid.
		/// </exception>
		public UniqueIdSet (SortOrder order = SortOrder.None) : this (0, order)
		{
		}

		/// <summary>
		/// Initializes a new instance of the <see cref="MailKit.UniqueIdSet"/> class.
		/// </summary>
		/// <remarks>
		/// Creates a new unique identifier set.
		/// </remarks>
		/// <param name="sort"><c>true</c> if unique identifiers should be sorted; otherwise, <c>false</c>.</param>
		[Obsolete ("Use UniqueIdSet (SortOrder) instead.")]
		public UniqueIdSet (bool sort) : this (sort ? SortOrder.Ascending : SortOrder.None)
		{
		}

		/// <summary>
		/// Initializes a new instance of the <see cref="MailKit.UniqueIdSet"/> class.
		/// </summary>
		/// <remarks>
		/// Creates a new set of unique identifier set containing the specified uids.
		/// </remarks>
		/// <param name="uids">An initial set of unique ids.</param>
		/// <param name="order">The sorting order to use for the unique identifiers.</param>
		/// <exception cref="System.ArgumentOutOfRangeException">
		/// <paramref name="order"/> is invalid.
		/// </exception>
		public UniqueIdSet (IEnumerable<UniqueId> uids, SortOrder order = SortOrder.None) : this (order)
		{
			foreach (var uid in uids)
				Add (uid);
		}

		/// <summary>
		/// Initializes a new instance of the <see cref="MailKit.UniqueIdSet"/> class.
		/// </summary>
		/// <remarks>
		/// Creates a new set of unique identifier set containing the specified uids.
		/// </remarks>
		/// <param name="uids">An initial set of unique ids.</param>
		/// <param name="sort"><c>true</c> if unique identifiers should be sorted; otherwise, <c>false</c>.</param>
		[Obsolete ("Use UniqueIdSet (IEnumerable<UniqueId>, SortOrder) instead.")]
		public UniqueIdSet (IEnumerable<UniqueId> uids, bool sort) : this (sort)
		{
			foreach (var uid in uids)
				Add (uid);
		}

		/// <summary>
		/// Gets the sort order of the unique identifiers.
		/// </summary>
		/// <remarks>
		/// Gets the sort order of the unique identifiers.
		/// </remarks>
		/// <value>The sort order.</value>
		public SortOrder SortOrder {
			get; private set;
		}

		/// <summary>
		/// Gets the validity, if non-zero.
		/// </summary>
		/// <remarks>
		/// Gets the UidValidity of the containing folder.
		/// </remarks>
		/// <value>The UidValidity of the containing folder.</value>
		public uint Validity {
			get; private set;
		}

		#region ICollection implementation

		/// <summary>
		/// Get the number of unique ids in the set.
		/// </summary>
		/// <remarks>
		/// Gets the number of unique ids in the set.
		/// </remarks>
		/// <value>The count.</value>
		public int Count {
			get { return (int) Math.Min (count, int.MaxValue); }
		}

		/// <summary>
		/// Get whether or not the set is read only.
		/// </summary>
		/// <remarks>
		/// Gets whether or not the set is read-only.
		/// </remarks>
		/// <value><c>true</c> if the set is read only; otherwise, <c>false</c>.</value>
		public bool IsReadOnly {
			get { return false; }
		}

		int BinarySearch (uint uid)
		{
			int min = 0, max = ranges.Count;

			if (max == 0)
				return -1;

			do {
				int i = min + ((max - min) / 2);

				if (SortOrder == SortOrder.Ascending) {
					// sorted ascending: 1:3,5:7,9
					if (uid >= ranges[i].Start) {
						if (uid <= ranges[i].End)
							return i;

						min = i + 1;
					} else {
						max = i;
					}
				} else {
					// sorted descending: 9,7:5,3:1
					if (uid >= ranges[i].End) {
						if (uid <= ranges[i].Start)
							return i;

						max = i;
					} else {
						min = i + 1;
					}
				}
			} while (min < max);

			return -1;
		}

		int IndexOfRange (uint uid)
		{
			if (SortOrder != SortOrder.None)
				return BinarySearch (uid);

			for (int i = 0; i < ranges.Count; i++) {
				if (ranges[i].Contains (uid))
					return i;
			}

			return -1;
		}

		void BinaryInsertAscending (uint uid)
		{
			int min = 0, max = ranges.Count;
			int i;

			do {
				i = min + ((max - min) / 2);

				if (uid >= ranges[i].Start) {
					if (uid <= ranges[i].End)
						return;

					if (uid == ranges[i].End + 1) {
						if (i + 1 < ranges.Count && uid + 1 >= ranges[i + 1].Start) {
							// merge the 2 ranges together
							ranges[i] = new Range (ranges[i].Start, ranges[i + 1].End);
							ranges.RemoveAt (i + 1);
							count++;
							return;
						}

						ranges[i] = new Range (ranges[i].Start, uid);
						count++;
						return;
					}

					min = i + 1;
					i = min;
				} else {
					if (uid == ranges[i].Start - 1) {
						if (i > 0 && uid - 1 <= ranges[i - 1].End) {
							// merge the 2 ranges together
							ranges[i - 1] = new Range (ranges[i - 1].Start, ranges[i].End);
							ranges.RemoveAt (i);
							count++;
							return;
						}

						ranges[i] = new Range (uid, ranges[i].End);
						count++;
						return;
					}

					max = i;
				}
			} while (min < max);

			var range = new Range (uid, uid);

			if (i < ranges.Count)
				ranges.Insert (i, range);
			else
				ranges.Add (range);

			count++;
		}

		void BinaryInsertDescending (uint uid)
		{
			int min = 0, max = ranges.Count;
			int i;

			do {
				i = min + ((max - min) / 2);

				if (uid <= ranges[i].Start) {
					if (uid >= ranges[i].End)
						return;

					if (uid == ranges[i].End - 1) {
						if (i + 1 < ranges.Count && uid - 1 <= ranges[i + 1].Start) {
							// merge the 2 ranges together
							ranges[i] = new Range (ranges[i].Start, ranges[i + 1].End);
							ranges.RemoveAt (i + 1);
							count++;
							return;
						}

						ranges[i] = new Range (ranges[i].Start, uid);
						count++;
						return;
					}

					min = i + 1;
					i = min;
				} else {
					if (uid == ranges[i].Start + 1) {
						if (i > 0 && uid + 1 >= ranges[i - 1].End) {
							// merge the 2 ranges together
							ranges[i - 1] = new Range (ranges[i - 1].Start, ranges[i].End);
							ranges.RemoveAt (i);
							count++;
							return;
						}

						ranges[i] = new Range (uid, ranges[i].End);
						count++;
						return;
					}

					max = i;
				}
			} while (min < max);

			var range = new Range (uid, uid);

			if (i < ranges.Count)
				ranges.Insert (i, range);
			else
				ranges.Add (range);

			count++;
		}

		void Append (uint uid)
		{
			if (IndexOfRange (uid) != -1)
				return;

			count++;

			if (ranges.Count > 0) {
				int index = ranges.Count - 1;
				var range = ranges[index];

				if (range.Start == range.End) {
					if (uid == range.End + 1 || uid == range.End - 1) {
						ranges[index] = new Range (range.Start, uid);
						return;
					}
				} else if (range.Start < range.End) {
					if (uid == range.End + 1) {
						ranges[index] = new Range (range.Start, uid);
						return;
					}
				} else if (range.Start > range.End) {
					if (uid == range.End - 1) {
						ranges[index] = new Range (range.Start, uid);
						return;
					}
				}
			}

			ranges.Add (new Range (uid, uid));
		}

		/// <summary>
		/// Adds the unique identifier to the set.
		/// </summary>
		/// <remarks>
		/// Adds the unique identifier to the set.
		/// </remarks>
		/// <param name="uid">The unique identifier to add.</param>
		public void Add (UniqueId uid)
		{
			if (ranges.Count == 0) {
				ranges.Add (new Range (uid.Id, uid.Id));
				count++;
				return;
			}

			switch (SortOrder) {
			case SortOrder.Descending:
				BinaryInsertDescending (uid.Id);
				break;
			case SortOrder.Ascending:
				BinaryInsertAscending (uid.Id);
				break;
			default:
				Append (uid.Id);
				break;
			}
		}

		/// <summary>
		/// Adds all of the uids to the set.
		/// </summary>
		/// <remarks>
		/// Adds all of the uids to the set.
		/// </remarks>
		/// <param name="uids">The collection of uids.</param>
		public void AddRange (IEnumerable<UniqueId> uids)
		{
			if (uids == null)
				throw new ArgumentNullException ("uids");

			foreach (var uid in uids)
				Add (uid);
		}

		/// <summary>
		/// Clears the list.
		/// </summary>
		/// <remarks>
		/// Clears the list.
		/// </remarks>
		/// <exception cref="System.InvalidOperationException">
		/// The collection is readonly.
		/// </exception>
		public void Clear ()
		{
			ranges.Clear ();
			count = 0;
		}

		/// <summary>
		/// Checks if the set contains the specified unique id.
		/// </summary>
		/// <remarks>
		/// Determines whether or not the set contains the specified unique id.
		/// </remarks>
		/// <returns><value>true</value> if the specified unique identifier is in the set; otherwise <value>false</value>.</returns>
		/// <param name="uid">The unique id.</param>
		public bool Contains (UniqueId uid)
		{
			return IndexOfRange (uid.Id) != -1;
		}

		/// <summary>
		/// Copies all of the unique ids in the set to the specified array.
		/// </summary>
		/// <remarks>
		/// Copies all of the unique ids within the set into the array,
		/// starting at the specified array index.
		/// </remarks>
		/// <param name="array">The array to copy the unique ids to.</param>
		/// <param name="arrayIndex">The index into the array.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <paramref name="array"/> is <c>null</c>.
		/// </exception>
		/// <exception cref="System.ArgumentOutOfRangeException">
		/// <paramref name="arrayIndex"/> is out of set.
		/// </exception>
		public void CopyTo (UniqueId[] array, int arrayIndex)
		{
			if (array == null)
				throw new ArgumentNullException ("array");

			if (arrayIndex < 0 || arrayIndex > (array.Length - Count))
				throw new ArgumentOutOfRangeException ("arrayIndex");

			int index = arrayIndex;

			for (int i = 0; i < ranges.Count; i++) {
				foreach (var uid in ranges[i])
					array[index++] = new UniqueId (Validity, uid);
			}
		}

		void Remove (int index, uint uid)
		{
			var range = ranges[index];

			if (uid == range.Start) {
				// remove the first item in the range
				if (range.Start != range.End) {
					if (range.Start <= range.End)
						ranges[index] = new Range (uid + 1, range.End);
					else
						ranges[index] = new Range (uid - 1, range.End);
				} else {
					ranges.RemoveAt (index);
				}
			} else if (uid == range.End) {
				// remove the last item in the range
				if (range.Start <= range.End)
					ranges[index] = new Range (range.Start, uid - 1);
				else
					ranges[index] = new Range (range.Start, uid + 1);
			} else {
				// remove a uid from the middle of the range
				if (range.Start < range.End) {
					ranges.Insert (index, new Range (range.Start, uid - 1));
					ranges[index + 1] = new Range (uid + 1, range.End);
				} else {
					ranges.Insert (index, new Range (range.Start, uid + 1));
					ranges[index + 1] = new Range (uid - 1, range.End);
				}
			}

			count--;
		}

		/// <summary>
		/// Removes the unique identifier from the set.
		/// </summary>
		/// <remarks>
		/// Removes the unique identifier from the set.
		/// </remarks>
		/// <returns><value>true</value> if the unique identifier was removed; otherwise <value>false</value>.</returns>
		/// <param name="uid">The unique identifier to remove.</param>
		public bool Remove (UniqueId uid)
		{
			int index = IndexOfRange (uid.Id);

			if (index == -1)
				return false;

			Remove (index, uid.Id);

			return true;
		}

		#endregion

		#region IList implementation

		/// <summary>
		/// Gets the index of the specified unique id, if it exists.
		/// </summary>
		/// <remarks>
		/// Finds the index of the specified unique id, if it exists.
		/// </remarks>
		/// <returns>The index of the specified unique id; otherwise <value>-1</value>.</returns>
		/// <param name="uid">The unique id.</param>
		public int IndexOf (UniqueId uid)
		{
			int index = 0;

			for (int i = 0; i < ranges.Count; i++) {
				if (ranges[i].Contains (uid.Id))
					return index + ranges[i].IndexOf (uid.Id);

				index += ranges[i].Count;
			}

			return -1;
		}

		/// <summary>
		/// Inserts the specified unique identifier at the given index.
		/// </summary>
		/// <remarks>
		/// Inserts the unique identifier at the specified index in the set.
		/// </remarks>
		/// <param name="index">The index to insert the unique id.</param>
		/// <param name="uid">The unique id.</param>
		/// <exception cref="System.NotSupportedException">
		/// The list does not support inserting items.
		/// </exception>
		public void Insert (int index, UniqueId uid)
		{
			throw new NotSupportedException ();
		}

		/// <summary>
		/// Removes the unique identifier at the specified index.
		/// </summary>
		/// <remarks>
		/// Removes the unique identifier at the specified index.
		/// </remarks>
		/// <param name="index">The index.</param>
		/// <exception cref="System.ArgumentOutOfRangeException">
		/// <paramref name="index"/> is out of range.
		/// </exception>
		public void RemoveAt (int index)
		{
			if (index < 0 || index >= count)
				throw new ArgumentOutOfRangeException ("index");

			int offset = 0;

			for (int i = 0; i < ranges.Count; i++) {
				if (index >= offset + ranges[i].Count) {
					offset += ranges[i].Count;
					continue;
				}

				var uid = ranges[i][index - offset];
				Remove (i, uid);
				return;
			}
		}

		/// <summary>
		/// Gets or sets the unique identifier at the specified index.
		/// </summary>
		/// <remarks>
		/// Gets or sets the unique identifier at the specified index.
		/// </remarks>
		/// <value>The unique identifier at the specified index.</value>
		/// <param name="index">The index.</param>
		/// <exception cref="System.ArgumentOutOfRangeException">
		/// <paramref name="index"/> is out of range.
		/// </exception>
		/// <exception cref="System.NotSupportedException">
		/// The list does not support setting items.
		/// </exception>
		public UniqueId this [int index] {
			get {
				if (index < 0 || index >= count)
					throw new ArgumentOutOfRangeException ("index");

				int offset = 0;

				for (int i = 0; i < ranges.Count; i++) {
					if (index >= offset + ranges[i].Count) {
						offset += ranges[i].Count;
						continue;
					}

					uint uid = ranges[i][index - offset];

					return new UniqueId (Validity, uid);
				}

				throw new ArgumentOutOfRangeException ("index");
			}
			set {
				throw new NotSupportedException ();
			}
		}

		#endregion

		#region IEnumerable implementation

		/// <summary>
		/// Gets an enumerator for the set of unique ids.
		/// </summary>
		/// <remarks>
		/// Gets an enumerator for the set of unique ids.
		/// </remarks>
		/// <returns>The enumerator.</returns>
		public IEnumerator<UniqueId> GetEnumerator ()
		{
			for (int i = 0; i < ranges.Count; i++) {
				foreach (var uid in ranges[i])
					yield return new UniqueId (Validity, uid);
			}

			yield break;
		}

		#endregion

		#region IEnumerable implementation

		/// <summary>
		/// Gets an enumerator for the set of unique ids.
		/// </summary>
		/// <remarks>
		/// Gets an enumerator for the set of unique ids.
		/// </remarks>
		/// <returns>The enumerator.</returns>
		IEnumerator IEnumerable.GetEnumerator ()
		{
			return GetEnumerator ();
		}

		#endregion

		/// <summary>
		/// Returns a <see cref="System.String"/> that represents the current <see cref="UniqueIdSet"/>.
		/// </summary>
		/// <remarks>
		/// Returns a <see cref="System.String"/> that represents the current <see cref="UniqueIdSet"/>.
		/// </remarks>
		/// <returns>A <see cref="System.String"/> that represents the current <see cref="UniqueIdSet"/>.</returns>
		public override string ToString ()
		{
			var builder = new StringBuilder ();

			for (int i = 0; i < ranges.Count; i++) {
				if (i > 0)
					builder.Append (',');

				builder.Append (ranges[i]);
			}

			return builder.ToString ();
		}

		/// <summary>
		/// Format a generic list of unique identifiers as a string.
		/// </summary>
		/// <remarks>
		/// Formats a generic list of unique identifiers as a string.
		/// </remarks>
		/// <returns>The string representation of the collection of unique identifiers.</returns>
		/// <param name="uids">The unique identifiers.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <paramref name="uids"/> is <c>null</c>.
		/// </exception>
		/// <exception cref="System.ArgumentException">
		/// One or more of the unique identifiers is invalid (has a value of <c>0</c>).
		/// </exception>
		public static string ToString (IList<UniqueId> uids)
		{
			if (uids == null)
				throw new ArgumentNullException ("uids");

			if (uids.Count == 0)
				return string.Empty;

			var range = uids as UniqueIdRange;
			if (range != null)
				return range.ToString ();

			var set = uids as UniqueIdSet;
			if (set != null)
				return set.ToString ();

			var builder = new StringBuilder ();
			int index = 0;

			while (index < uids.Count) {
				if (uids[index].Id == 0)
					throw new ArgumentException ("One or more of the uids is invalid.", "uids");

				uint start = uids[index].Id;
				uint end = uids[index].Id;
				int i = index + 1;

				if (i < uids.Count) {
					if (uids[i].Id == end + 1) {
						end = uids[i++].Id;

						while (i < uids.Count && uids[i].Id == end + 1) {
							end++;
							i++;
						}
					} else if (uids[i].Id == end - 1) {
						end = uids[i++].Id;

						while (i < uids.Count && uids[i].Id == end - 1) {
							end--;
							i++;
						}
					}
				}

				if (builder.Length > 0)
					builder.Append (',');

				if (start != end)
					builder.AppendFormat ("{0}:{1}", start, end);
				else
					builder.Append (start.ToString ());

				index = i;
			}

			return builder.ToString ();
		}

		/// <summary>
		/// Attempt to parse the specified token as a set of unique identifiers.
		/// </summary>
		/// <remarks>
		/// Attempts to parse the specified token as a set of unique identifiers.
		/// </remarks>
		/// <returns><c>true</c> if the set of unique identifiers were successfully parsed; otherwise, <c>false</c>.</returns>
		/// <param name="token">The token containing the set of unique identifiers.</param>
		/// <param name="validity">The UIDVALIDITY value.</param>
		/// <param name="uids">The set of unique identifiers.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <paramref name="token"/> is <c>null</c>.
		/// </exception>
		public static bool TryParse (string token, uint validity, out UniqueIdSet uids)
		{
			if (token == null)
				throw new ArgumentNullException ("token");

			uids = new UniqueIdSet (validity);

			var order = SortOrder.None;
			bool sorted = true;
			uint start, end;
			uint prev = 0;
			int index = 0;

			do {
				if (!UniqueId.TryParse (token, ref index, out start))
					return false;

				if (index < token.Length && token[index] == ':') {
					index++;

					if (!UniqueId.TryParse (token, ref index, out end))
						return false;

					var range = new Range (start, end);
					uids.count += range.Count;
					uids.ranges.Add (range);

					if (sorted) {
						switch (order) {
						default: sorted = true; order = start <= end ? SortOrder.Ascending : SortOrder.Descending; break;
						case SortOrder.Descending: sorted = start >= end && start <= prev; break;
						case SortOrder.Ascending: sorted = start <= end && start >= prev; break;
						}
					}

					prev = end;
				} else {
					uids.ranges.Add (new Range (start, start));
					uids.count++;

					if (sorted && uids.ranges.Count > 1) {
						switch (order) {
						default: sorted = true; order = start >= prev ? SortOrder.Ascending : SortOrder.Descending; break;
						case SortOrder.Descending: sorted = start <= prev; break;
						case SortOrder.Ascending: sorted = start >= prev; break;
						}
					}

					prev = start;
				}

				if (index >= token.Length)
					break;

				if (token[index++] != ',')
					return false;
			} while (true);

			uids.SortOrder = sorted ? order : SortOrder.None;

			return true;
		}

		/// <summary>
		/// Attempt to parse the specified token as a set of unique identifiers.
		/// </summary>
		/// <remarks>
		/// Attempts to parse the specified token as a set of unique identifiers.
		/// </remarks>
		/// <returns><c>true</c> if the set of unique identifiers were successfully parsed; otherwise, <c>false</c>.</returns>
		/// <param name="token">The token containing the set of unique identifiers.</param>
		/// <param name="uids">The set of unique identifiers.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <paramref name="token"/> is <c>null</c>.
		/// </exception>
		public static bool TryParse (string token, out UniqueIdSet uids)
		{
			return TryParse (token, 0, out uids);
		}
	}
}


text:
package com.twitter.finagle.redis.protocol

import com.twitter.conversions.time._
import com.twitter.finagle.redis.ClientError
import com.twitter.finagle.redis.naggati.RedisRequestTest
import com.twitter.finagle.redis.tags.CodecTest
import com.twitter.finagle.redis.util.StringToBuf
import com.twitter.util.Time
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner

@RunWith(classOf[JUnitRunner])
final class KeyCodecSuite extends RedisRequestTest {

  test("Correctly encode DELETE for one key", CodecTest) {
    //assert(codec(wrap("DEL foo\r\n")) == List(Del(List(bufFoo))))
    codec(wrap("DEL foo\r\n"))
  }

  test("Correctly encode DELETE for two keys", CodecTest) {
    assert(codec(wrap("DEL foo bar\r\n")) == List(Del(List(bufFoo, bufBar))))
  }

  test("Throw a ClientError if DELETE is called with no key") {
    intercept[ClientError] {
      codec(wrap("DEL\r\n"))
    }
  }

  test("Throw a ClientError if DUMP is called with no key", CodecTest) {
    intercept[ClientError] {
      codec(wrap("DUMP\r\n"))
    }
  }

  test("Correctly encode DUMP for one key", CodecTest) {
    assert(codec(wrap("DUMP baz\r\n")) == List(Dump(bufBaz)))
  }

  test("Correctly encode EXISTS for one key", CodecTest) {
    assert(codec(wrap("EXISTS foo\r\n")) == List(Exists(bufFoo)))
  }

  test("Throw a ClientError if EXISTS is called with no key") {
    intercept[ClientError] {
      codec(wrap("EXISTS\r\n"))
    }
  }

  test("Correctly encode EXPIRE for one key in 100 seconds", CodecTest) {
    assert(codec(wrap("EXPIRE moo 100\r\n")) == List(Expire(bufMoo, 100)))
  }

  test("Correctly encode one key to never EXPIRE", CodecTest) {
    assert(codec(wrap("EXPIRE baz -1\r\n")) == List(Expire(bufBaz, -1)))
  }

  test("Correctly encode one key to EXPIREAT at future timestamp", CodecTest) {
    assert(codec(wrap("EXPIREAT moo 100\r\n")) ==
      List(ExpireAt(bufMoo, Time.fromMilliseconds(100*1000))))
  }

  test("Correctly encode one key to EXPIREAT a future interpolated timestamp", CodecTest) {
    val time = Time.now + 10.seconds
    unwrap(codec(wrap("EXPIREAT foo %d\r\n".format(time.inSeconds)))) {
      case ExpireAt(foo, timestamp) => {
        assert(timestamp.inSeconds == time.inSeconds)
      }
    }
  }

  test("Correctly encode a KEYS pattern", CodecTest) {
    assert(codec(wrap("KEYS h?llo\r\n")) == List(Keys(StringToBuf("h?llo"))))
  }

  test("Correctly encode MOVE for one key to another database", CodecTest) {
    assert(codec(wrap("MOVE boo moo \r\n")) == List(Move(bufBoo, bufMoo)))
  }

  test("Throw a ClientError if MOVE is called with no key or database", CodecTest) {
    intercept[ClientError] {
      codec(wrap("MOVE\r\n"))
    }
  }

  test("Throw a ClientError if MOVE is called with a key but no database", CodecTest) {
    intercept[ClientError] {
      codec(wrap("MOVE foo\r\n"))
    }
  }

  test("Correctly encode PERSIST for one key", CodecTest) {
    assert(codec(wrap("PERSIST foo\r\n")) == List(Persist(bufFoo)))
  }

  test("Throw a ClientError if Persist is called without a key", CodecTest) {
    intercept[ClientError] {
      codec(wrap("PERSIST\r\n"))
    }
  }

  test("Correctly encode PEXPIRE for one key in 100 seconds", CodecTest) {
    assert(codec(wrap("PEXPIRE foo 100000\r\n")) == List(PExpire(bufFoo, 100000L)))
  }

  test("Correctly encode one key to never PEXPIRE", CodecTest) {
    assert(codec(wrap("PEXPIRE baz -1\r\n")) == List(PExpire(bufBaz, -1L)))
  }

  test("Correctly encode one key to PEXPIREAT at a future timestamp", CodecTest) {
    assert(codec(wrap("PEXPIREAT boo 100000\r\n")) ==
      List(PExpireAt(bufBoo, Time.fromMilliseconds(100000))))
  }

  test("Correctly encode one key to PEXPIREAT at a future interpolated timestamp", CodecTest) {
    val time = Time.now + 10.seconds
    unwrap(codec(wrap("PEXPIREAT foo %d\r\n".format(time.inMilliseconds))))  {
      case PExpireAt(foo, timestamp) => {
        assert(timestamp.inMilliseconds == time.inMilliseconds)
      }
    }
  }

  test("Correctly encode a PTTL, time to live in milliseconds, for a key", CodecTest) {
    assert(codec(wrap("PTTL foo\r\n")) == List(PTtl(bufFoo)))
  }

  test("Throw a ClientError if RENAME is called with no arguments", CodecTest) {
    intercept[ClientError] {
      codec(wrap("RENAME\r\n"))
    }
  }

  test("Throw a ClientError if RENAME is called without a second argument", CodecTest) {
    intercept[ClientError] {
      codec(wrap("RENAME foo\r\n"))
    }
  }

  test("Correctly encode RENAME of one key to another", CodecTest) {
    assert(codec(wrap("RENAME foo bar\r\n")) == List(Rename(bufFoo, bufBar)))
  }

  test("Throw a ClientError if RENAMEX is called with no arguments", CodecTest) {
    intercept[ClientError] {
      codec(wrap("RENAMENX\r\n"))
    }
  }

  test("Throw a ClientError if RENAMEX is called without a second argument", CodecTest) {
    intercept[ClientError] {
      codec(wrap("RENAMENX foo\r\n"))
    }
  }

  test("Correctly encode RENAMEX of one key to another", CodecTest) {
    assert(codec(wrap("RENAMENX foo bar\r\n")) == List(RenameNx(bufFoo, bufBar)))
  }

  test("Correctly encode a request for a RANDOMKEY", CodecTest) {
    assert(codec(wrap("RANDOMKEY\r\n")) == List(Randomkey()))
  }

  test("Correctly encode a TTL, time to live in seconds, for a key", CodecTest) {
    assert(codec(wrap("TTL foo\r\n")) == List(Ttl(bufFoo)))
  }

  test("Throw a ClientError if TYPE is called with no key", CodecTest) {
    intercept[ClientError] {
      codec(wrap("TYPE\r\n"))
    }
  }

  test("Correctly encode a TYPE request for a provided key", CodecTest) {
    assert(codec(wrap("TYPE foo\r\n")) == List(Type(bufFoo)))
  }
}


text:
echo "[client]
host=mysql
user=\"root\"
password=\"$MYSQL_ROOT_PASSWORD\"

[mysql]
host=mysql
user=\"root\"
password=\"$MYSQL_ROOT_PASSWORD\"
database=\"$MYSQL_DATABASE\"
default-character-set=utf8
local-infile=1
show-warnings
auto-rehash
sigint-ignore
reconnect

[mysqldump]
host=mysql
user=\"root\"
password=\"$MYSQL_ROOT_PASSWORD\"

" | tee /root/.my.cnf > /home/.my.cnf