text:
package org.springframework.boot.actuate.autoconfigure.security.servlet;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.boot.actuate.autoconfigure.endpoint.web.WebEndpointProperties;
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.web.PathMappedEndpoints;
import org.springframework.boot.autoconfigure.security.servlet.RequestMatcherProvider;
import org.springframework.boot.autoconfigure.web.servlet.DispatcherServletPath;
import org.springframework.boot.security.servlet.ApplicationContextRequestMatcher;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.OrRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.context.WebApplicationContext;

/**
 * Factory that can be used to create a {@link RequestMatcher} for actuator endpoint
 * locations.
 *
 * @author Madhura Bhave
 * @author Phillip Webb
 * @since 2.0.0
 */
public final class EndpointRequest {

	private static final RequestMatcher EMPTY_MATCHER = (request) -> false;

	private EndpointRequest() {
	}

	/**
	 * Returns a matcher that includes all {@link Endpoint actuator endpoints}. It also
	 * includes the links endpoint which is present at the base path of the actuator
	 * endpoints. The {@link EndpointRequestMatcher#excluding(Class...) excluding} method
	 * can be used to further remove specific endpoints if required. For example:
	 *

	 * EndpointRequest.toAnyEndpoint().excluding(ShutdownEndpoint.class)
	 *

	 * @return the configured {@link RequestMatcher}
	 */
	public static EndpointRequestMatcher toAnyEndpoint() {
		return new EndpointRequestMatcher(true);
	}

	/**
	 * Returns a matcher that includes the specified {@link Endpoint actuator endpoints}.
	 * For example:

	 * EndpointRequest.to(ShutdownEndpoint.class, HealthEndpoint.class)
	 *

	 * @param endpoints the endpoints to include
	 * @return the configured {@link RequestMatcher}
	 */
	public static EndpointRequestMatcher to(Class<?>... endpoints) {
		return new EndpointRequestMatcher(endpoints, false);
	}

	/**
	 * Returns a matcher that includes the specified {@link Endpoint actuator endpoints}.
	 * For example:

	 * EndpointRequest.to("shutdown", "health")
	 *

	 * @param endpoints the endpoints to include
	 * @return the configured {@link RequestMatcher}
	 */
	public static EndpointRequestMatcher to(String... endpoints) {
		return new EndpointRequestMatcher(endpoints, false);
	}

	/**
	 * Returns a matcher that matches only on the links endpoint. It can be used when
	 * security configuration for the links endpoint is different from the other
	 * {@link Endpoint actuator endpoints}. The
	 * {@link EndpointRequestMatcher#excludingLinks() excludingLinks} method can be used
	 * in combination with this to remove the links endpoint from
	 * {@link EndpointRequest#toAnyEndpoint() toAnyEndpoint}. For example:
	 *

	 * EndpointRequest.toLinks()
	 *

	 * @return the configured {@link RequestMatcher}
	 */
	public static LinksRequestMatcher toLinks() {
		return new LinksRequestMatcher();
	}

	/**
	 * Base class for supported request matchers.
	 */
	private abstract static class AbstractRequestMatcher
			extends ApplicationContextRequestMatcher<WebApplicationContext> {

		private volatile RequestMatcher delegate;

		AbstractRequestMatcher() {
			super(WebApplicationContext.class);
		}

		@Override
		protected final void initialized(Supplier<WebApplicationContext> context) {
			this.delegate = createDelegate(context.get());
		}

		@Override
		protected final boolean matches(HttpServletRequest request,
				Supplier<WebApplicationContext> context) {
			return this.delegate.matches(request);
		}

		private RequestMatcher createDelegate(WebApplicationContext context) {
			try {
				String pathPrefix = getPathPrefix(context);
				return createDelegate(context, new RequestMatcherFactory(pathPrefix));
			}
			catch (NoSuchBeanDefinitionException ex) {
				return EMPTY_MATCHER;
			}
		}

		private String getPathPrefix(WebApplicationContext context) {
			try {
				return context.getBean(DispatcherServletPath.class).getPrefix();
			}
			catch (NoSuchBeanDefinitionException ex) {
				return "";
			}
		}

		protected abstract RequestMatcher createDelegate(WebApplicationContext context,
				RequestMatcherFactory requestMatcherFactory);

		protected List<RequestMatcher> getLinksMatchers(
				RequestMatcherFactory requestMatcherFactory,
				RequestMatcherProvider matcherProvider, String basePath) {
			List<RequestMatcher> linksMatchers = new ArrayList<>();
			linksMatchers.add(requestMatcherFactory.antPath(matcherProvider, basePath));
			linksMatchers
					.add(requestMatcherFactory.antPath(matcherProvider, basePath, "/"));
			return linksMatchers;
		}

		protected RequestMatcherProvider getRequestMatcherProvider(
				WebApplicationContext context) {
			try {
				return context.getBean(RequestMatcherProvider.class);
			}
			catch (NoSuchBeanDefinitionException ex) {
				return AntPathRequestMatcher::new;
			}
		}

	}

	/**
	 * The request matcher used to match against {@link Endpoint actuator endpoints}.
	 */
	public static final class EndpointRequestMatcher extends AbstractRequestMatcher {

		private final List<Object> includes;

		private final List<Object> excludes;

		private final boolean includeLinks;

		private EndpointRequestMatcher(boolean includeLinks) {
			this(Collections.emptyList(), Collections.emptyList(), includeLinks);
		}

		private EndpointRequestMatcher(Class<?>[] endpoints, boolean includeLinks) {
			this(Arrays.asList((Object[]) endpoints), Collections.emptyList(),
					includeLinks);
		}

		private EndpointRequestMatcher(String[] endpoints, boolean includeLinks) {
			this(Arrays.asList((Object[]) endpoints), Collections.emptyList(),
					includeLinks);
		}

		private EndpointRequestMatcher(List<Object> includes, List<Object> excludes,
				boolean includeLinks) {
			this.includes = includes;
			this.excludes = excludes;
			this.includeLinks = includeLinks;
		}

		public EndpointRequestMatcher excluding(Class<?>... endpoints) {
			List<Object> excludes = new ArrayList<>(this.excludes);
			excludes.addAll(Arrays.asList((Object[]) endpoints));
			return new EndpointRequestMatcher(this.includes, excludes, this.includeLinks);
		}

		public EndpointRequestMatcher excluding(String... endpoints) {
			List<Object> excludes = new ArrayList<>(this.excludes);
			excludes.addAll(Arrays.asList((Object[]) endpoints));
			return new EndpointRequestMatcher(this.includes, excludes, this.includeLinks);
		}

		public EndpointRequestMatcher excludingLinks() {
			return new EndpointRequestMatcher(this.includes, this.excludes, false);
		}

		@Override
		protected RequestMatcher createDelegate(WebApplicationContext context,
				RequestMatcherFactory requestMatcherFactory) {
			PathMappedEndpoints pathMappedEndpoints = context
					.getBean(PathMappedEndpoints.class);
			RequestMatcherProvider matcherProvider = getRequestMatcherProvider(context);
			Set<String> paths = new LinkedHashSet<>();
			if (this.includes.isEmpty()) {
				paths.addAll(pathMappedEndpoints.getAllPaths());
			}
			streamPaths(this.includes, pathMappedEndpoints).forEach(paths::add);
			streamPaths(this.excludes, pathMappedEndpoints).forEach(paths::remove);
			List<RequestMatcher> delegateMatchers = getDelegateMatchers(
					requestMatcherFactory, matcherProvider, paths);
			String basePath = pathMappedEndpoints.getBasePath();
			if (this.includeLinks && StringUtils.hasText(basePath)) {
				delegateMatchers.addAll(getLinksMatchers(requestMatcherFactory,
						matcherProvider, basePath));
			}
			return new OrRequestMatcher(delegateMatchers);
		}

		private Stream<String> streamPaths(List<Object> source,
				PathMappedEndpoints pathMappedEndpoints) {
			return source.stream().filter(Objects::nonNull).map(this::getEndpointId)
					.map(pathMappedEndpoints::getPath);
		}

		private String getEndpointId(Object source) {
			if (source instanceof String) {
				return (String) source;
			}
			if (source instanceof Class) {
				return getEndpointId((Class<?>) source);
			}
			throw new IllegalStateException("Unsupported source " + source);
		}

		private String getEndpointId(Class<?> source) {
			Endpoint annotation = AnnotatedElementUtils.getMergedAnnotation(source,
					Endpoint.class);
			Assert.state(annotation != null,
					() -> "Class " + source + " is not annotated with @Endpoint");
			return annotation.id();
		}

		private List<RequestMatcher> getDelegateMatchers(
				RequestMatcherFactory requestMatcherFactory,
				RequestMatcherProvider matcherProvider, Set<String> paths) {
			return paths.stream().map(
					(path) -> requestMatcherFactory.antPath(matcherProvider, path, "/**"))
					.collect(Collectors.toList());
		}

	}

	/**
	 * The request matcher used to match against the links endpoint.
	 */
	public static final class LinksRequestMatcher extends AbstractRequestMatcher {

		@Override
		protected RequestMatcher createDelegate(WebApplicationContext context,
				RequestMatcherFactory requestMatcherFactory) {
			WebEndpointProperties properties = context
					.getBean(WebEndpointProperties.class);
			String basePath = properties.getBasePath();
			if (StringUtils.hasText(basePath)) {
				return new OrRequestMatcher(getLinksMatchers(requestMatcherFactory,
						getRequestMatcherProvider(context), basePath));
			}
			return EMPTY_MATCHER;
		}

	}

	/**
	 * Factory used to create a {@link RequestMatcher}.
	 */
	private static class RequestMatcherFactory {

		private final String prefix;

		RequestMatcherFactory(String prefix) {
			this.prefix = prefix;
		}

		public RequestMatcher antPath(RequestMatcherProvider matcherProvider,
				String... parts) {
			String pattern = this.prefix;
			for (String part : parts) {
				pattern += part;
			}
			return matcherProvider.getRequestMatcher(pattern);
		}

	}

}


text:
using NUnit.Framework;
using ServiceStack.OrmLite.Tests;

namespace ServiceStack.OrmLite.PostgreSQL.Tests
{
    public class TypeWithByteArrayFieldTests : OrmLiteTestBase
    {
        [Test]
        public void CanInsertAndSelectByteArray()
        {
            var orig = new TypeWithByteArrayField { Id = 1, Content = new byte[] { 0, 17, 0, 17, 0, 7 } };

            using (var db = ConnectionString.OpenDbConnection())
            {
                db.CreateTable<TypeWithByteArrayField>(true);

                db.Save(orig);

                var target = db.GetById<TypeWithByteArrayField>(orig.Id);

                Assert.AreEqual(orig.Id, target.Id);
                Assert.AreEqual(orig.Content, target.Content);
            }
        }
    }

    class TypeWithByteArrayField
    {
        public int Id { get; set; }
        public byte[] Content { get; set; }
    }
}

redpajama_set_name: RedPajamaGithub


text:
PLEASE NOTE: This document applies to the HEAD of the source tree

If you are using a released version of Kubernetes, you should
refer to the docs that go with that version.

The latest release of this document can be found
[here](http://releases.k8s.io/release-1.1/examples/elasticsearch/production_cluster/README.md).

Documentation for other releases can be found at
[releases.k8s.io](http://releases.k8s.io).

--

# Elasticsearch for Kubernetes

Kubernetes makes it trivial for anyone to easily build and scale [Elasticsearch](http://www.elasticsearch.org/) clusters. Here, you'll find how to do so.
Current Elasticsearch version is `1.7.1`.

Before we start, one needs to know that Elasticsearch best-practices recommend to separate nodes in three roles:
* `Master` nodes - intended for clustering management only, no data, no HTTP API
* `Client` nodes - intended for client usage, no data, with HTTP API
* `Data` nodes - intended for storing and indexing your data, no HTTP API

This is enforced throughout this document.

 Current pod descriptors use an `emptyDir` for storing data in each data node container. This is meant to be for the sake of simplicity and [should be adapted according to your storage needs](../../../docs/design/persistent-storage.md).

## Docker image

This example uses [this pre-built image](https://github.com/pires/docker-elasticsearch-kubernetes) will not be supported. Feel free to fork to fit your own needs, but mind yourself that you will need to change Kubernetes descriptors accordingly.

## Deploy

```
kubectl create -f examples/elasticsearch/production_cluster/service-account.yaml
kubectl create -f examples/elasticsearch/production_cluster/es-discovery-svc.yaml
kubectl create -f examples/elasticsearch/production_cluster/es-svc.yaml
kubectl create -f examples/elasticsearch/production_cluster/es-master-rc.yaml
```

Wait until `es-master` is provisioned, and

```
kubectl create -f examples/elasticsearch/production_cluster/es-client-rc.yaml
```

Wait until `es-client` is provisioned, and

```
kubectl create -f examples/elasticsearch/production_cluster/es-data-rc.yaml
```

Wait until `es-data` is provisioned.

Now, I leave up to you how to validate the cluster, but a first step is to wait for containers to be in ```RUNNING``` state and check the Elasticsearch master logs:

```
$ kubectl get pods
NAME              READY     STATUS    RESTARTS   AGE
es-client-2ep9o   1/1       Running   0          2m
es-data-r9tgv     1/1       Running   0          1m
es-master-vxl6c   1/1       Running   0          6m
```

```
$ kubectl logs es-master-vxl6c
log4j:WARN No such property [maxBackupIndex] in org.apache.log4j.DailyRollingFileAppender.
log4j:WARN No such property [maxBackupIndex] in org.apache.log4j.DailyRollingFileAppender.
log4j:WARN No such property [maxBackupIndex] in org.apache.log4j.DailyRollingFileAppender.
[2015-08-21 10:58:51,324][INFO ][node                     ] [Arc] version[1.7.1], pid[8], build[b88f43f/2015-07-29T09:54:16Z]
[2015-08-21 10:58:51,328][INFO ][node                     ] [Arc] initializing ...
[2015-08-21 10:58:51,542][INFO ][plugins                  ] [Arc] loaded [cloud-kubernetes], sites []
[2015-08-21 10:58:51,624][INFO ][env                      ] [Arc] using [1] data paths, mounts [[/data (/dev/sda9)]], net usable_space [14.4gb], net total_space [15.5gb], types [ext4]
[2015-08-21 10:58:57,439][INFO ][node                     ] [Arc] initialized
[2015-08-21 10:58:57,439][INFO ][node                     ] [Arc] starting ...
[2015-08-21 10:58:57,782][INFO ][transport                ] [Arc] bound_address {inet[/0:0:0:0:0:0:0:0:9300]}, publish_address {inet[/10.244.15.2:9300]}
[2015-08-21 10:58:57,847][INFO ][discovery                ] [Arc] myesdb/-x16XFUzTCC8xYqWoeEOYQ
[2015-08-21 10:59:05,167][INFO ][cluster.service          ] [Arc] new_master [Arc][-x16XFUzTCC8xYqWoeEOYQ][es-master-vxl6c][inet[/10.244.15.2:9300]]{data=false, master=true}, reason: zen-disco-join (elected_as_master)
[2015-08-21 10:59:05,202][INFO ][node                     ] [Arc] started
[2015-08-21 10:59:05,238][INFO ][gateway                  ] [Arc] recovered [0] indices into cluster_state
[2015-08-21 11:02:28,797][INFO ][cluster.service          ] [Arc] added {[Gideon][4EfhWSqaTqikbK4tI7bODA][es-data-r9tgv][inet[/10.244.59.4:9300]]{master=false},}, reason: zen-disco-receive(join from node[[Gideon][4EfhWSqaTqikbK4tI7bODA][es-data-r9tgv][inet[/10.244.59.4:9300]]{master=false}])
[2015-08-21 11:03:16,822][INFO ][cluster.service          ] [Arc] added {[Venomm][tFYxwgqGSpOejHLG4umRqg][es-client-2ep9o][inet[/10.244.53.2:9300]]{data=false, master=false},}, reason: zen-disco-receive(join from node[[Venomm][tFYxwgqGSpOejHLG4umRqg][es-client-2ep9o][inet[/10.244.53.2:9300]]{data=false, master=false}])
```

As you can assert, the cluster is up and running. Easy, wasn't it?

## Scale

Scaling each type of node to handle your cluster is as easy as:

```
kubectl scale --replicas=3 rc es-master
kubectl scale --replicas=2 rc es-client
kubectl scale --replicas=2 rc es-data
```

Did it work?

```
$ kubectl get pods
NAME              READY     STATUS    RESTARTS   AGE
es-client-2ep9o   1/1       Running   0          4m
es-client-ye5s1   1/1       Running   0          50s
es-data-8az22     1/1       Running   0          47s
es-data-r9tgv     1/1       Running   0          3m
es-master-57h7k   1/1       Running   0          52s
es-master-kuwse   1/1       Running   0          52s
es-master-vxl6c   1/1       Running   0          8m
```

Let's take another look of the Elasticsearch master logs:

```
$ kubectl logs es-master-vxl6c
log4j:WARN No such property [maxBackupIndex] in org.apache.log4j.DailyRollingFileAppender.
log4j:WARN No such property [maxBackupIndex] in org.apache.log4j.DailyRollingFileAppender.
log4j:WARN No such property [maxBackupIndex] in org.apache.log4j.DailyRollingFileAppender.
[2015-08-21 10:58:51,324][INFO ][node                     ] [Arc] version[1.7.1], pid[8], build[b88f43f/2015-07-29T09:54:16Z]
[2015-08-21 10:58:51,328][INFO ][node                     ] [Arc] initializing ...
[2015-08-21 10:58:51,542][INFO ][plugins                  ] [Arc] loaded [cloud-kubernetes], sites []
[2015-08-21 10:58:51,624][INFO ][env                      ] [Arc] using [1] data paths, mounts [[/data (/dev/sda9)]], net usable_space [14.4gb], net total_space [15.5gb], types [ext4]
[2015-08-21 10:58:57,439][INFO ][node                     ] [Arc] initialized
[2015-08-21 10:58:57,439][INFO ][node                     ] [Arc] starting ...
[2015-08-21 10:58:57,782][INFO ][transport                ] [Arc] bound_address {inet[/0:0:0:0:0:0:0:0:9300]}, publish_address {inet[/10.244.15.2:9300]}
[2015-08-21 10:58:57,847][INFO ][discovery                ] [Arc] myesdb/-x16XFUzTCC8xYqWoeEOYQ
[2015-08-21 10:59:05,167][INFO ][cluster.service          ] [Arc] new_master [Arc][-x16XFUzTCC8xYqWoeEOYQ][es-master-vxl6c][inet[/10.244.15.2:9300]]{data=false, master=true}, reason: zen-disco-join (elected_as_master)
[2015-08-21 10:59:05,202][INFO ][node                     ] [Arc] started
[2015-08-21 10:59:05,238][INFO ][gateway                  ] [Arc] recovered [0] indices into cluster_state
[2015-08-21 11:02:28,797][INFO ][cluster.service          ] [Arc] added {[Gideon][4EfhWSqaTqikbK4tI7bODA][es-data-r9tgv][inet[/10.244.59.4:9300]]{master=false},}, reason: zen-disco-receive(join from node[[Gideon][4EfhWSqaTqikbK4tI7bODA][es-data-r9tgv][inet[/10.244.59.4:9300]]{master=false}])
[2015-08-21 11:03:16,822][INFO ][cluster.service          ] [Arc] added {[Venomm][tFYxwgqGSpOejHLG4umRqg][es-client-2ep9o][inet[/10.244.53.2:9300]]{data=false, master=false},}, reason: zen-disco-receive(join from node[[Venomm][tFYxwgqGSpOejHLG4umRqg][es-client-2ep9o][inet[/10.244.53.2:9300]]{data=false, master=false}])
[2015-08-21 11:04:40,781][INFO ][cluster.service          ] [Arc] added {[Erik Josten][QUJlahfLTi-MsxzM6_Da0g][es-master-kuwse][inet[/10.244.59.5:9300]]{data=false, master=true},}, reason: zen-disco-receive(join from node[[Erik Josten][QUJlahfLTi-MsxzM6_Da0g][es-master-kuwse][inet[/10.244.59.5:9300]]{data=false, master=true}])
[2015-08-21 11:04:41,076][INFO ][cluster.service          ] [Arc] added {[Power Princess][V4qnR-6jQOS5ovXQsPgo7g][es-master-57h7k][inet[/10.244.53.3:9300]]{data=false, master=true},}, reason: zen-disco-receive(join from node[[Power Princess][V4qnR-6jQOS5ovXQsPgo7g][es-master-57h7k][inet[/10.244.53.3:9300]]{data=false, master=true}])
[2015-08-21 11:04:53,966][INFO ][cluster.service          ] [Arc] added {[Cagliostro][Wpfx5fkBRiG2qCEWd8laaQ][es-client-ye5s1][inet[/10.244.15.3:9300]]{data=false, master=false},}, reason: zen-disco-receive(join from node[[Cagliostro][Wpfx5fkBRiG2qCEWd8laaQ][es-client-ye5s1][inet[/10.244.15.3:9300]]{data=false, master=false}])
[2015-08-21 11:04:56,803][INFO ][cluster.service          ] [Arc] added {[Thog][vkdEtX3ESfWmhXXf-Wi0_Q][es-data-8az22][inet[/10.244.15.4:9300]]{master=false},}, reason: zen-disco-receive(join from node[[Thog][vkdEtX3ESfWmhXXf-Wi0_Q][es-data-8az22][inet[/10.244.15.4:9300]]{master=false}])
```

## Access the service

*Don't forget* that services in Kubernetes are only acessible from containers in the cluster. For different behavior you should [configure the creation of an external load-balancer](http://kubernetes.io/v1.0/docs/user-guide/services.html#type-loadbalancer). While it's supported within this example service descriptor, its usage is out of scope of this document, for now.

```
$ kubectl get service elasticsearch
NAME            LABELS                                SELECTOR                              IP(S)          PORT(S)
elasticsearch   component=elasticsearch,role=client   component=elasticsearch,role=client   10.100.134.2   9200/TCP
```

From any host on your cluster (that's running `kube-proxy`), run:

```
curl http://10.100.134.2:9200
```

You should see something similar to the following:

```json
{
  "status" : 200,
  "name" : "Cagliostro",
  "cluster_name" : "myesdb",
  "version" : {
    "number" : "1.7.1",
    "build_hash" : "b88f43fc40b0bcd7f173a1f9ee2e97816de80b19",
    "build_timestamp" : "2015-07-29T09:54:16Z",
    "build_snapshot" : false,
    "lucene_version" : "4.10.4"
  },
  "tagline" : "You Know, for Search"
}
```

Or if you want to check cluster information:

```
curl http://10.100.134.2:9200/_cluster/health?pretty
```

You should see something similar to the following:

```json
{
  "cluster_name" : "myesdb",
  "status" : "green",
  "timed_out" : false,
  "number_of_nodes" : 7,
  "number_of_data_nodes" : 2,
  "active_primary_shards" : 0,
  "active_shards" : 0,
  "relocating_shards" : 0,
  "initializing_shards" : 0,
  "unassigned_shards" : 0,
  "delayed_unassigned_shards" : 0,
  "number_of_pending_tasks" : 0,
  "number_of_in_flight_fetch" : 0
}
```

[![Analytics](https://kubernetes-site.appspot.com/UA-36037335-10/GitHub/examples/elasticsearch/production_cluster/README.md?pixel)]()


text:
using Microsoft.Azure.Batch.Protocol;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using AsyncTask = System.Threading.Tasks.Task;

namespace Microsoft.Azure.Batch.Conventions.Files.UnitTests.Utilities
{
    public sealed class FakeBatchServiceClient : BatchServiceClient
    {
        public FakeBatchServiceClient(Func<HttpRequestMessage, HttpResponseMessage> impl)
            : base(new FakingHandler(impl))
        {
            this.BatchUrl = "https://a.b.c.d.e.f.g";
        }

        public FakeBatchServiceClient(object responseBody)
            : this(_ => FakeResponse(responseBody))
        {
        }

        public FakeBatchServiceClient()
            : this(_ => { throw new InvalidOperationException("FakeBatchServiceClient not configured with any responses"); })
        {
        }

        public static HttpResponseMessage FakeResponse(object responseBody)
        {
            return new HttpResponseMessage
            {
                StatusCode = HttpStatusCode.OK,
                Content = new StringContent(JsonConvert.SerializeObject(responseBody)),
            };
        }

        private class FakingHandler : DelegatingHandler
        {
            private readonly Func<HttpRequestMessage, HttpResponseMessage> _impl;

            public FakingHandler(Func<HttpRequestMessage, HttpResponseMessage> impl)
            {
                _impl = impl;
            }

            protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
            {
                return AsyncTask.FromResult(_impl(request));
            }
        }
    }
}


text:
import { Form, Formik, FormikErrors, FormikHelpers } from "formik";
import * as React from "react";

import { GetMessage } from "src/common/helpers";
import CheckboxField from "src/options/components/common/CheckboxField";
import HtmlPhrase from "src/options/components/common/HtmlPhrase";
import RadioButtonField from "src/options/components/common/RadioButtonField";
import TextField from "src/options/components/common/TextField";
import { IFormFillerOptionsForm, IFormFillerOptions } from "src/types";

const validate = (values: IFormFillerOptionsForm): FormikErrors<IFormFillerOptionsForm> => {
  const errors: FormikErrors<IFormFillerOptionsForm> = {};

  if (values.emailSettingsUsernameType === "list" && !values.emailSettingsUsernameList) {
    errors.emailSettingsUsernameList = GetMessage("generalSettings_validation_enterUsernames");
  }

  if (values.emailSettingsUsernameType === "regex" && !values.emailSettingsUsernameRegEx) {
    errors.emailSettingsUsernameRegEx = GetMessage("generalSettings_validation_enterRegEx");
  }

  if (values.emailSettingsHostnameType === "list" && !values.emailSettingsHostnameList) {
    errors.emailSettingsHostnameList = GetMessage("generalSettings_validation_enterHostname");
  }

  if (values.passwordSettingsMode === "defined" && !values.passwordSettingsPassword) {
    errors.passwordSettingsPassword = GetMessage("generalSettings_validation_enterPassword");
  }

  if (
    !values.fieldMatchId &&
    !values.fieldMatchName &&
    !values.fieldMatchLabel &&
    !values.fieldMatchClass &&
    !values.fieldMatchPlaceholder
  ) {
    errors.fieldMatchId = GetMessage("generalSettings_validation_enterAtLeastOneMatch");
  }

  if (!values.defaultMaxLength || values.defaultMaxLength.length === 0) {
    errors.defaultMaxLength = GetMessage("generalSettings_validation_invalidDefaultMaxLength");
  }

  if (values.defaultMaxLength && parseInt(values.defaultMaxLength, 10) < 1) {
    errors.defaultMaxLength = GetMessage("generalSettings_validation_invalidDefaultMaxLength");
  }

  return errors;
};

interface IOwnProps {
  options: IFormFillerOptions;
  showSavedMessage: boolean;
  onSave: (formValues: IFormFillerOptionsForm) => void;
}

class GeneralSettingsForm extends React.PureComponent<IOwnProps> {
  constructor(props: IOwnProps) {
    super(props);

    this.handleSubmit = this.handleSubmit.bind(this);
  }

  private handleSubmit(values: IFormFillerOptionsForm, actions: FormikHelpers<IFormFillerOptionsForm>): void {
    this.props.onSave(values);
    actions.setSubmitting(false);
  }

  public render(): JSX.Element {
    const initialValues: Partial<IFormFillerOptionsForm> = {};

    initialValues.agreeTermsFields = this.props.options.agreeTermsFields.join(", ");
    initialValues.confirmFields = this.props.options.confirmFields.join(", ");
    initialValues.defaultMaxLength = String(this.props.options.defaultMaxLength);
    initialValues.enableContextMenu = this.props.options.enableContextMenu;
    initialValues.ignoreFieldsWithContent = this.props.options.ignoreFieldsWithContent;
    initialValues.ignoreHiddenFields = this.props.options.ignoreHiddenFields;
    initialValues.ignoredFields = this.props.options.ignoredFields.join(", ");
    initialValues.triggerClickEvents = this.props.options.triggerClickEvents;
    initialValues.passwordSettingsMode = this.props.options.passwordSettings.mode;
    initialValues.passwordSettingsPassword = this.props.options.passwordSettings.password;
    initialValues.fieldMatchId = this.props.options.fieldMatchSettings.matchId;
    initialValues.fieldMatchName = this.props.options.fieldMatchSettings.matchName;
    initialValues.fieldMatchLabel = this.props.options.fieldMatchSettings.matchLabel;
    initialValues.fieldMatchClass = this.props.options.fieldMatchSettings.matchClass;
    initialValues.fieldMatchPlaceholder = this.props.options.fieldMatchSettings.matchPlaceholder;
    initialValues.emailSettingsHostnameType = this.props.options.emailSettings.hostname;
    initialValues.emailSettingsHostnameList = this.props.options.emailSettings.hostnameList.join(", ");
    initialValues.emailSettingsUsernameType = this.props.options.emailSettings.username;
    initialValues.emailSettingsUsernameList = this.props.options.emailSettings.usernameList.join(", ");
    initialValues.emailSettingsUsernameRegEx = this.props.options.emailSettings.usernameRegEx;

    return (
      <Formik
        initialValues={initialValues as IFormFillerOptionsForm}
        enableReinitialize
        validate={validate}
        onSubmit={this.handleSubmit}
      >
        {({ isSubmitting, isValid }) => (
          <Form>

{GetMessage("generalSettings_emailSettings")}

                {GetMessage("generalSettings_label_username")}

                <RadioButtonField
                  name="emailSettingsUsernameType"
                  value="username"
                  label={GetMessage("generalSettings_label_username_usernameLabel")}
                />
                <RadioButtonField
                  name="emailSettingsUsernameType"
                  value="name"
                  label={GetMessage("generalSettings_label_username_nameLabel")}
                />
                <RadioButtonField
                  name="emailSettingsUsernameType"
                  value="random"
                  label={GetMessage("generalSettings_label_username_randomLabel")}
                />
                <RadioButtonField
                  name="emailSettingsUsernameType"
                  value="list"
                  label={GetMessage("generalSettings_label_username_listLabel")}
                />
                <TextField name="emailSettingsUsernameList" placeholder={GetMessage("enterCsv")} />
                <RadioButtonField
                  name="emailSettingsUsernameType"
                  value="regex"
                  label={GetMessage("generalSettings_label_username_regExTextPlaceholder")}
                />
                <TextField name="emailSettingsUsernameRegEx" placeholder={GetMessage("enterCsv")} />

                {GetMessage("generalSettings_label_hostName")}

                <RadioButtonField
                  name="emailSettingsHostnameType"
                  value="random"
                  label={GetMessage("generalSettings_label_hostName_randomLabel")}
                />
                <RadioButtonField
                  name="emailSettingsHostnameType"
                  value="list"
                  label={GetMessage("generalSettings_label_hostName_listLabel")}
                />
                <TextField
                  name="emailSettingsHostnameList"
                  placeholder={GetMessage("enterCsv")}
                  helpText={GetMessage("generalSettings_label_hostName_listTextHelp")}
                />

{GetMessage("generalSettings_passwordSettings")}

                {GetMessage("generalSettings_password")}

                <RadioButtonField
                  name="passwordSettingsMode"
                  value="random"
                  label={GetMessage("generalSettings_password_randomLabel")}
                />
                <RadioButtonField
                  name="passwordSettingsMode"
                  value="defined"
                  label={GetMessage("generalSettings_password_useThisLabel")}
                />
                <TextField name="passwordSettingsPassword" />

{GetMessage("generalSettings_fieldOptions")}

                {GetMessage("generalSettings_ignoreFieldsMatch")}

                <TextField name="ignoredFields" placeholder={GetMessage("enterCsv")} />
                <CheckboxField
                  name="ignoreHiddenFields"
                  label={GetMessage("generalSettings_ignoreHiddenFieldsLabel")}
                />
                <CheckboxField
                  name="ignoreFieldsWithContent"
                  label={GetMessage("generalSettings_ignoreFieldsWithContentLabel")}
                />
                <HtmlPhrase
                  phrase={GetMessage("generalSettings_ignoreFieldsWithContentHelp")}
                  as="div"
                  className="form-text text-muted"
                />

            <TextField
              name="confirmFields"
              label={GetMessage("generalSettings_confirmationFieldsMatch")}
              placeholder={GetMessage("enterCsv")}
              helpText={GetMessage("generalSettings_confirmFieldsHelp")}
            />

            <TextField
              name="agreeTermsFields"
              label={GetMessage("generalSettings_agreeToTermsMatch")}
              placeholder={GetMessage("enterCsv")}
              helpText={GetMessage("generalSettings_agreeToTermsMatchHelp")}
            />

{GetMessage("generalSettings_matchFieldsUsing")}

                <CheckboxField name="fieldMatchId" label={GetMessage("generalSettings_matchFields_useId")} />
                <CheckboxField name="fieldMatchName" label={GetMessage("generalSettings_matchFields_useName")} />
                <CheckboxField name="fieldMatchLabel" label={GetMessage("generalSettings_matchFields_useLabel")} />
                <CheckboxField name="fieldMatchClass" label={GetMessage("generalSettings_matchFields_useClass")} />
                <CheckboxField
                  name="fieldMatchPlaceholder"
                  label={GetMessage("generalSettings_matchFields_usePlaceholder")}
                />

{GetMessage("generalSettings_matchFields_help")}

            <TextField
              name="defaultMaxLength"
              type="number"
              label={GetMessage("generalSettings_defaultMaxLength")}
              helpText={GetMessage("generalSettings_defaultMaxLength_help")}
            />

{GetMessage("generalSettings")}

            <CheckboxField
              name="triggerClickEvents"
              label={GetMessage("generalSettings_triggerEventsLabel")}
              title={GetMessage("generalSettings_triggerEvents")}
            />
            <CheckboxField
              name="enableContextMenu"
              label={GetMessage("generalSettings_contextMenuLabel")}
              title={GetMessage("generalSettings_contextMenu")}
            />

                <button type="submit" className="btn btn-primary" disabled={isSubmitting || !isValid}>
                  {GetMessage("saveSettings")}
                </button>
                {this.props.showSavedMessage && (
                  {GetMessage("generalSettings_settingsSaved")}
                )}

          </Form>
        )}
      </Formik>
    );
  }
}

export default GeneralSettingsForm;


text:
package com.eventhorizon.jarvis.entity;

import java.io.Serializable;

import javax.persistence.*;

import java.util.Date;

import lombok.Getter;
import lombok.Setter;

/**
 * The persistent class for the JobExecution database table.
 *
 */
@Entity(name = "JOB_Exection")
@NamedQuery(name="JOB_Exection.findAll", query="SELECT j FROM JOB_Exection j")
public class JobExecution extends AbstractEntity<Long> implements Serializable {

	/**
	 *
	 */
	private static final long serialVersionUID = -6048626075185367441L;

	@Getter @Setter
	@Temporal(TemporalType.TIMESTAMP)
	private Date endTime;

	@Getter @Setter
	@Temporal(TemporalType.TIMESTAMP)
	private Date execTime;

	@Lob
	@Getter @Setter
	private String output;

	//bi-directional many-to-one association to Job
	@Getter @Setter
	@ManyToOne(fetch=FetchType.LAZY)
	@JoinColumn(name="Id_JOB")
	private Job job;

}


text:
import _ from 'lodash';

//// store
export const getStorePristine = () => ({
	maxid: 0,
	containers: [{
		id: 99999999,
		name: 'Freezer',
		description: '',
		categories: []
	}],
	user: {
		id: 88888888,
		name: 'demo',
		email: 'demo@demo.com',
		container_id: 99999999
	}
});

let store = getStorePristine();

let storeBackup = getStorePristine();

//// uncommenting the following line will give you a pristine store on every load for debugging
// localStorage.removeItem('wimf');

export const resetStore = () => {
	// const storePristine = getStorePristine();
	store = getStorePristine();
}

export const getStore = () => ({...store});

////// Helpers
const getReturnItem = (item, category) => {
	const returnItem = {...item};
	returnItem.category = category.name;
	return returnItem;
};

export const getContainerById = (id) => {
	const container = store.containers.find(container => (
		parseInt(container.id, 10) === parseInt(id, 10)
	));
	if (container === undefined) {
		throw new Error(`container_id ${id} not found`);
	}
	store.user.container_id = id;
	return container;
}

export const getCategoryByName = (container, name) => {
	let category = _.find(container.categories, { name: name });
	if (category === undefined) {
		category = {
			id: store.maxid++,
			name: name,
			container_id: container.id,
			items: []
		};
		container.categories.push(category);
	}
	return category;
};

//// persistence methods
export const persistContainers = (resolve, reject, method, args=[], data={}) => {
	switch (method) {
		case 'get':
			//// container list for dropdown
			if (args.length === 0) {
				return {
					containers: store.containers.map(container => ({
						id: container.id,
						name: container.name,
						description: container.description })),
					selected: store.user.container_id
				};
			//// specific container with categories
			} else {
				const container_id = args[0];
				const container = store.containers.find(container => (
						parseInt(container.id, 10) === parseInt(container_id, 10)
					));
				if (container === undefined) {
					throw new Error(`Undefined container, ${args[0]}`);
				}
				const returnContainer = Object.assign({}, container);
				returnContainer.categories.forEach(category => {
					category.items.forEach(item => {
						item.category = category.name;
					});
				});
				store.user.container_id = container_id;
				return returnContainer;
			}
		case 'post':
			const container = {
				name: data.name,
				description: data.description,
				id: store.maxid++,
				categories: []
			};
			//// check for duplicates
			if (_.find(store.containers, { name: container.name })) {
				reject({ data: { error: `Add: Container "${container.name}" exists`}});
				return;
			}
			store.containers.push(container);
			// console.log(store);
			return container;
		case 'put':
			//// check for other container with new name
			let put_container = _.find(store.containers, { name: data.name });
			if (put_container && put_container.id !== data.id) {
				reject({ data: { update: `Add: Container "${put_container.name}" exists`}});
				return;
			}
			//// name changed
			if (!put_container) {
				put_container = _.find(store.containers, { id: data.id });
			}
			//// update container
			put_container = { ...put_container, ...data };
			//// update store
			store.containers = store.containers.map(container => {
				return (container.id === put_container.id) ? put_container : container;
			});
			return put_container;
		case 'delete':
			const id = args[0];
			store.containers = store.containers.filter(c => parseInt(c.id) !== parseInt(id));
			// console.log(store);
			return;
		default:
			console.error('bad method');
	}
};

export const persistCurrentUser = (resolve, reject, method, args, data) => {
	switch (method) {
		case 'get':
			return store.user;
		default:
			console.error('bad method');
			reject();
	}
};

export const persistItems = (resolve, reject, method, args, data) => {
	let category_name, item, container, category, container_id;
	//// put/post
	if (['put', 'post'].indexOf(method) > -1) {
		({ container_id, category: category_name, ...item } = data);
		//// find the container
		container = getContainerById(container_id);

		//// find the category
		category = getCategoryByName(container, category_name);
		//// set item's category id
		item.category_id = category.id;
	}
	//// update item state
	switch (method) {
		case 'post':
			//// add id to item
			item.id = store.maxid++;
			//// check for duplicates
			if (_.find(category.items, { name: item.name })) {
				store = {...storeBackup};
				reject({ data: { error: `Add: Item "${item.name}" exists in "${category.name}"`}});
				return;
			}
			category.items.push(item);
			return getReturnItem(item, category);
		case 'put':
			const existingItem = _.find(category.items, { id: item.id });
			//// check for duplicates
			if (_.find(category.items, item => item.id !== existingItem.id
					&& item.name === existingItem.name)) {
				store = {...storeBackup};
				reject({ data: { error: `Update: Item "${item.name}" exists in "${category.name}"`}});
				return;
			}
			for (let i = 0; i < category.items.length; i++) {
				if (category.items[i].id === item.id) {
					category.items[i] = item;
				}
			}
			return getReturnItem(item, category);
		case 'delete':
			const id = args[0];
			for (let i = 0; i < store.containers.length; i++) {
				let categories = store.containers[i].categories;
				for (let j = 0; j < categories.length; j++) {
					let category = categories[j];
					if (_.find(category.items, catitem => parseInt(catitem.id, 10) === parseInt(id, 10))) {
						category.items = _.filter(category.items, catitem => parseInt(catitem.id, 10) !== parseInt(id, 10));
						break;
					}
				}
			}
			return item;
		default:
			console.error('bad method');
	}
};

const localPersistedStore = (resolve, reject, method, url, data) => {
	const parts = url.slice(1).split('/').slice(1),
		type = parts[0],
		args = parts.slice(1);
	//// deserialize store
	if (localStorage.getItem('wimf')) {
		store = JSON.parse(localStorage.getItem('wimf'));
	}
	//// update store
	let retval = {};
	method = method.toLowerCase();

	switch (type) {
		case 'containers':
			retval = persistContainers(resolve, reject, method, args, data);
			break;
		case 'items':
			retval = persistItems(resolve, reject, method, args, data);
			break;
		case 'me':
			retval = persistCurrentUser(resolve, reject, method, args, data);
			break;
		default:
			console.error('Invalid type', parts);
	}
	////serializeStore
	console.log('deserializeStore', resolve, reject, method, type, store);
	localStorage.setItem('wimf', JSON.stringify(store));
	storeBackup = { ...store };
	resolve({
		data: retval
	});
};

export default localPersistedStore;


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.1" language="zh_CN">
<context>
    <name>CPluginManagerImp</name>
    <message>
        <location filename="../library/ctkPluginManager/pluginmanagerImp.cpp" line="126"/>
        <source>Failed to initialize the plug-in framework:</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../library/ctkPluginManager/pluginmanagerImp.cpp" line="139"/>
        <source>Begin loading plugins...</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../library/ctkPluginManager/pluginmanagerImp.cpp" line="143"/>
        <source>LOAD:</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../library/ctkPluginManager/pluginmanagerImp.cpp" line="175"/>
        <source>plugin </source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../library/ctkPluginManager/pluginmanagerImp.cpp" line="175"/>
        <source> has interface:</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../library/ctkPluginManager/pluginmanagerImp.cpp" line="216"/>
        <source>Resolve interface:</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../library/ctkPluginManager/pluginmanagerImp.cpp" line="216"/>
        <source>failure</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../library/ctkPluginManager/pluginmanagerImp.cpp" line="228"/>
        <source>plugin</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../library/ctkPluginManager/pluginmanagerImp.cpp" line="228"/>
        <source>has no Export-Interface in manifest_headers.cmake</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../library/ctkPluginManager/pluginmanagerImp.cpp" line="234"/>
        <source>init ctkPluginFramework exception, reason :</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../library/ctkPluginManager/pluginmanagerImp.cpp" line="307"/>
        <source>get Service:</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../library/ctkPluginManager/pluginmanagerImp.cpp" line="307"/>
        <source>from ctk pluginFramework exception, reason :</source>
        <translation type="unfinished"></translation>
    </message>
</context>
</TS>


text:
package ru.lizaalert.hotline.ui.test;

import android.app.ActionBar;
import android.support.v4.view.ViewPager;
import android.test.ActivityInstrumentationTestCase2;
import android.test.UiThreadTest;
import android.widget.EditText;

import ru.lizaalert.hotline.R;
import ru.lizaalert.hotline.ui.MainActivity;

public class MainActivityTest extends
        ActivityInstrumentationTestCase2<MainActivity> {

    MainActivity mActivity;
    ActionBar mActionBar;
    ViewPager mViewPager;

    public MainActivityTest() {
        super(MainActivity.class);
    }

    protected void setUp() throws Exception {
        super.setUp();

        setActivityInitialTouchMode(false);

        mActivity = getActivity();
        mActionBar = mActivity.getActionBar();

        mViewPager = (ViewPager) mActivity.findViewById(R.id.pager);
    }

    public void testPreconditions() {
        assertTrue(mActionBar != null);
        assertEquals(mActionBar.getTabCount(), 2);

        assertTrue(mViewPager != null);
    }

    protected void tearDown() throws Exception {
        super.tearDown();
    }

    private final static String TEST_PHONE_1 = "+78122128506";
    private final static String TEST_CITY_1 = "Москва";
    private final static String TEST_NAME_1 = "Иван Иванович";
    private final static String TEST_BIRTHDAY_1 = "1975";
    private final static String TEST_DESCR_1 = "Раз два";

    private final static String TEST_PHONE_2 = "+78122128507";
    private final static String TEST_CITY_2 = "Санкт-Петербург";
    private final static String TEST_NAME_2 = "Петр Петрович";
    private final static String TEST_BIRTHDAY_2 = "1976";
    private final static String TEST_DESCR_2 = "Три четыре";

    @UiThreadTest
    public void testStateDestroy() {
        mViewPager = (ViewPager) mActivity.findViewById(R.id.pager);
        mViewPager.setCurrentItem(0);

        EditText phone, city, name, birthday, descr;

        phone = (EditText)mActivity.findViewById(R.id.et_phone);
        city = (EditText)mActivity.findViewById(R.id.et_city);
        name = (EditText)mActivity.findViewById(R.id.et_name);
        birthday = (EditText)mActivity.findViewById(R.id.et_birthday);
        descr = (EditText)mActivity.findViewById(R.id.et_descr);

        assertTrue(phone != null);
        assertTrue(city != null);
        assertTrue(name != null);
        assertTrue(birthday != null);
        assertTrue(descr != null);

        phone.setText(TEST_PHONE_1);
        city.setText(TEST_CITY_1);
        name.setText(TEST_NAME_1);
        birthday.setText(TEST_BIRTHDAY_1);
        descr.setText(TEST_DESCR_1);

        mActivity.finish();

        mActivity = this.getActivity();

        phone = (EditText)mActivity.findViewById(R.id.et_phone);
        city = (EditText)mActivity.findViewById(R.id.et_city);
        name = (EditText)mActivity.findViewById(R.id.et_name);
        birthday = (EditText)mActivity.findViewById(R.id.et_birthday);
        descr = (EditText)mActivity.findViewById(R.id.et_descr);

        assertTrue(phone != null);
        assertTrue(city != null);
        assertTrue(name != null);
        assertTrue(birthday != null);
        assertTrue(descr != null);

        assertEquals(TEST_PHONE_1, phone.getText().toString());
        assertEquals(TEST_CITY_1, city.getText().toString());
        assertEquals(TEST_NAME_1, name.getText().toString());
        assertEquals(TEST_BIRTHDAY_1, birthday.getText().toString());
        assertEquals(TEST_DESCR_1, descr.getText().toString());

        phone.setText(TEST_PHONE_2);
        city.setText(TEST_CITY_2);
        name.setText(TEST_NAME_2);
        birthday.setText(TEST_BIRTHDAY_2);
        descr.setText(TEST_DESCR_2);

        mActivity.finish();

        mActivity = this.getActivity();

        phone = (EditText)mActivity.findViewById(R.id.et_phone);
        city = (EditText)mActivity.findViewById(R.id.et_city);
        name = (EditText)mActivity.findViewById(R.id.et_name);
        birthday = (EditText)mActivity.findViewById(R.id.et_birthday);
        descr = (EditText)mActivity.findViewById(R.id.et_descr);

        assertTrue(phone != null);
        assertTrue(city != null);
        assertTrue(name != null);
        assertTrue(birthday != null);
        assertTrue(descr != null);

        assertEquals(TEST_PHONE_2, phone.getText().toString());
        assertEquals(TEST_CITY_2, city.getText().toString());
        assertEquals(TEST_NAME_2, name.getText().toString());
        assertEquals(TEST_BIRTHDAY_2, birthday.getText().toString());
        assertEquals(TEST_DESCR_2, descr.getText().toString());
    }

    /*
    @UiThreadTest
    public void testOne() {
        Instrumentation instr = this.getInstrumentation();

        mViewPager.setCurrentItem(1);
        assertEquals(1, mViewPager.getCurrentItem());

        instr.callActivityOnPause(mActivity);

        mViewPager.setCurrentItem(0);

        instr.callActivityOnResume(mActivity);
        assertEquals(1, mViewPager.getCurrentItem());

    }
    */

}


text:
module Kamcaptcha
  module Validation
    def kamcaptcha_validates?
      return false unless defined?(params)
      return false unless params.respond_to?(:key?)
      return false unless params.key?(:kamcaptcha)

      token = instance_exec(&Kamcaptcha::Token.lookup)

      Kamcaptcha::Token.valid?(token, params[:kamcaptcha][:input])
    end
  end
end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Parmelia convoluta f. convoluta

### Remarks
null


text:
'use strict';

var db = require('../../../../db');

module.exports = require('eregistrations/notifications/revision-sent-back')(db.BusinessProcessDemo);


text:
package org.apache.accumulo.minicluster.impl;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileFilter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;

import org.apache.accumulo.cluster.AccumuloCluster;
import org.apache.accumulo.core.client.AccumuloException;
import org.apache.accumulo.core.client.AccumuloSecurityException;
import org.apache.accumulo.core.client.ClientConfiguration;
import org.apache.accumulo.core.client.Connector;
import org.apache.accumulo.core.client.Instance;
import org.apache.accumulo.core.client.ZooKeeperInstance;
import org.apache.accumulo.core.client.security.tokens.PasswordToken;
import org.apache.accumulo.core.conf.Property;
import org.apache.accumulo.core.master.thrift.MasterGoalState;
import org.apache.accumulo.core.util.Daemon;
import org.apache.accumulo.core.util.Pair;
import org.apache.accumulo.core.util.UtilWaitThread;
import org.apache.accumulo.gc.SimpleGarbageCollector;
import org.apache.accumulo.master.Master;
import org.apache.accumulo.master.state.SetGoalState;
import org.apache.accumulo.minicluster.ServerType;
import org.apache.accumulo.server.init.Initialize;
import org.apache.accumulo.server.util.PortUtils;
import org.apache.accumulo.server.util.time.SimpleTimer;
import org.apache.accumulo.start.Main;
import org.apache.accumulo.start.classloader.vfs.MiniDFSUtil;
import org.apache.accumulo.tserver.TabletServer;
import org.apache.commons.configuration.MapConfiguration;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.impl.VFSClassLoader;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.hdfs.DFSConfigKeys;
import org.apache.hadoop.hdfs.MiniDFSCluster;
import org.apache.zookeeper.server.ZooKeeperServerMain;

import com.google.common.base.Joiner;
import com.google.common.base.Predicate;
import com.google.common.collect.Maps;

/**
 * A utility class that will create Zookeeper and Accumulo processes that write all of their data to a single local directory. This class makes it easy to test
 * code against a real Accumulo instance. Its much more accurate for testing than {@link org.apache.accumulo.core.client.mock.MockAccumulo}, but much slower.
 *
 * @since 1.6.0
 */
public class MiniAccumuloClusterImpl implements AccumuloCluster {

  public static class LogWriter extends Daemon {
    private BufferedReader in;
    private BufferedWriter out;

    public LogWriter(InputStream stream, File logFile) throws IOException {
      this.in = new BufferedReader(new InputStreamReader(stream));
      out = new BufferedWriter(new FileWriter(logFile));

      SimpleTimer.getInstance(null).schedule(new Runnable() {
        @Override
        public void run() {
          try {
            flush();
          } catch (IOException e) {
            e.printStackTrace();
          }
        }
      }, 1000, 1000);
    }

    public synchronized void flush() throws IOException {
      if (out != null)
        out.flush();
    }

    @Override
    public void run() {
      String line;

      try {
        while ((line = in.readLine()) != null) {
          out.append(line);
          out.append("\n");
        }

        synchronized (this) {
          out.close();
          out = null;
          in.close();
        }

      } catch (IOException e) {}
    }
  }

  private static final long ZOOKEEPER_STARTUP_WAIT = 20 * 1000;

  private boolean initialized = false;
  private Process zooKeeperProcess = null;
  private Process masterProcess = null;
  private Process gcProcess = null;
  private List<Process> tabletServerProcesses = Collections.synchronizedList(new ArrayList<Process>());

  private Set<Pair<ServerType,Integer>> debugPorts = new HashSet<Pair<ServerType,Integer>>();

  private File zooCfgFile;
  private String dfsUri;

  public List<LogWriter> getLogWriters() {
    return logWriters;
  }

  private List<LogWriter> logWriters = new ArrayList<MiniAccumuloClusterImpl.LogWriter>();

  private MiniAccumuloConfigImpl config;
  private MiniDFSCluster miniDFS = null;
  private List<Process> cleanup = new ArrayList<Process>();

  public Process exec(Class<?> clazz, String... args) throws IOException {
    return exec(clazz, null, args);
  }

  public Process exec(Class<?> clazz, List<String> jvmArgs, String... args) throws IOException {
    ArrayList<String> jvmArgs2 = new ArrayList<String>(1 + (jvmArgs == null ? 0 : jvmArgs.size()));
    jvmArgs2.add("-Xmx" + config.getDefaultMemory());
    if (jvmArgs != null)
      jvmArgs2.addAll(jvmArgs);
    Process proc = _exec(clazz, jvmArgs2, args);
    cleanup.add(proc);
    return proc;
  }

  private boolean containsSiteFile(File f) {
    return f.isDirectory() && f.listFiles(new FileFilter() {

      @Override
      public boolean accept(File pathname) {
        return pathname.getName().endsWith("site.xml");
      }
    }).length > 0;
  }

  private void append(StringBuilder classpathBuilder, URL url) throws URISyntaxException {
    File file = new File(url.toURI());
    // do not include dirs containing hadoop or accumulo site files
    if (!containsSiteFile(file))
      classpathBuilder.append(File.pathSeparator).append(file.getAbsolutePath());
  }

  private String getClasspath() throws IOException {

    try {
      ArrayList<ClassLoader> classloaders = new ArrayList<ClassLoader>();

      ClassLoader cl = this.getClass().getClassLoader();

      while (cl != null) {
        classloaders.add(cl);
        cl = cl.getParent();
      }

      Collections.reverse(classloaders);

      StringBuilder classpathBuilder = new StringBuilder();
      classpathBuilder.append(config.getConfDir().getAbsolutePath());

      if (config.getClasspathItems() == null) {

        // assume 0 is the system classloader and skip it
        for (int i = 1; i < classloaders.size(); i++) {
          ClassLoader classLoader = classloaders.get(i);

          if (classLoader instanceof URLClassLoader) {

            for (URL u : ((URLClassLoader) classLoader).getURLs()) {
              append(classpathBuilder, u);
            }

          } else if (classLoader instanceof VFSClassLoader) {

            VFSClassLoader vcl = (VFSClassLoader) classLoader;
            for (FileObject f : vcl.getFileObjects()) {
              append(classpathBuilder, f.getURL());
            }
          } else {
            throw new IllegalArgumentException("Unknown classloader type : " + classLoader.getClass().getName());
          }
        }
      } else {
        for (String s : config.getClasspathItems())
          classpathBuilder.append(File.pathSeparator).append(s);
      }

      return classpathBuilder.toString();

    } catch (URISyntaxException e) {
      throw new IOException(e);
    }
  }

  private Process _exec(Class<?> clazz, List<String> extraJvmOpts, String... args) throws IOException {
    String javaHome = System.getProperty("java.home");
    String javaBin = javaHome + File.separator + "bin" + File.separator + "java";
    String classpath = getClasspath();

    String className = clazz.getName();

    ArrayList<String> argList = new ArrayList<String>();
    argList.addAll(Arrays.asList(javaBin, "-Dproc=" + clazz.getSimpleName(), "-cp", classpath));
    argList.addAll(extraJvmOpts);
    for (Entry<String,String> sysProp : config.getSystemProperties().entrySet()) {
      argList.add(String.format("-D%s=%s", sysProp.getKey(), sysProp.getValue()));
    }
    argList.addAll(Arrays.asList("-XX:+UseConcMarkSweepGC", "-XX:CMSInitiatingOccupancyFraction=75", "-Dapple.awt.UIElement=true", Main.class.getName(),
        className));
    argList.addAll(Arrays.asList(args));

    ProcessBuilder builder = new ProcessBuilder(argList);

    builder.environment().put("ACCUMULO_HOME", config.getDir().getAbsolutePath());
    builder.environment().put("ACCUMULO_LOG_DIR", config.getLogDir().getAbsolutePath());
    builder.environment().put("ACCUMULO_CLIENT_CONF_PATH", config.getClientConfFile().getAbsolutePath());
    String ldLibraryPath = Joiner.on(File.pathSeparator).join(config.getNativeLibPaths());
    builder.environment().put("LD_LIBRARY_PATH", ldLibraryPath);
    builder.environment().put("DYLD_LIBRARY_PATH", ldLibraryPath);

    // if we're running under accumulo.start, we forward these env vars
    String env = System.getenv("HADOOP_PREFIX");
    if (env != null)
      builder.environment().put("HADOOP_PREFIX", env);
    env = System.getenv("ZOOKEEPER_HOME");
    if (env != null)
      builder.environment().put("ZOOKEEPER_HOME", env);
    builder.environment().put("ACCUMULO_CONF_DIR", config.getConfDir().getAbsolutePath());
    // hadoop-2.2 puts error messages in the logs if this is not set
    builder.environment().put("HADOOP_HOME", config.getDir().getAbsolutePath());

    Process process = builder.start();

    LogWriter lw;
    lw = new LogWriter(process.getErrorStream(), new File(config.getLogDir(), clazz.getSimpleName() + "_" + process.hashCode() + ".err"));
    logWriters.add(lw);
    lw.start();
    lw = new LogWriter(process.getInputStream(), new File(config.getLogDir(), clazz.getSimpleName() + "_" + process.hashCode() + ".out"));
    logWriters.add(lw);
    lw.start();

    return process;
  }

  private Process _exec(Class<?> clazz, ServerType serverType, String... args) throws IOException {

    List<String> jvmOpts = new ArrayList<String>();
    jvmOpts.add("-Xmx" + config.getMemory(serverType));

    if (config.isJDWPEnabled()) {
      Integer port = PortUtils.getRandomFreePort();
      jvmOpts.addAll(buildRemoteDebugParams(port));
      debugPorts.add(new Pair<ServerType,Integer>(serverType, port));
    }
    return _exec(clazz, jvmOpts, args);
  }

  /**
   *
   * @param dir
   *          An empty or nonexistant temp directoy that Accumulo and Zookeeper can store data in. Creating the directory is left to the user. Java 7, Guava,
   *          and Junit provide methods for creating temporary directories.
   * @param rootPassword
   *          Initial root password for instance.
   */
  public MiniAccumuloClusterImpl(File dir, String rootPassword) throws IOException {
    this(new MiniAccumuloConfigImpl(dir, rootPassword));
  }

  /**
   * @param config
   *          initial configuration
   */
  @SuppressWarnings("deprecation")
  public MiniAccumuloClusterImpl(MiniAccumuloConfigImpl config) throws IOException {

    this.config = config.initialize();

    config.getConfDir().mkdirs();
    config.getAccumuloDir().mkdirs();
    config.getZooKeeperDir().mkdirs();
    config.getLogDir().mkdirs();
    config.getWalogDir().mkdirs();
    config.getLibDir().mkdirs();
    config.getLibExtDir().mkdirs();

    if (config.useMiniDFS()) {
      File nn = new File(config.getAccumuloDir(), "nn");
      nn.mkdirs();
      File dn = new File(config.getAccumuloDir(), "dn");
      dn.mkdirs();
      File dfs = new File(config.getAccumuloDir(), "dfs");
      dfs.mkdirs();
      Configuration conf = new Configuration();
      conf.set(DFSConfigKeys.DFS_NAMENODE_NAME_DIR_KEY, nn.getAbsolutePath());
      conf.set(DFSConfigKeys.DFS_DATANODE_DATA_DIR_KEY, dn.getAbsolutePath());
      conf.set(DFSConfigKeys.DFS_REPLICATION_KEY, "1");
      conf.set("dfs.support.append", "true");
      conf.set("dfs.datanode.synconclose", "true");
      conf.set("dfs.datanode.data.dir.perm", MiniDFSUtil.computeDatanodeDirectoryPermission());
      String oldTestBuildData = System.setProperty("test.build.data", dfs.getAbsolutePath());
      miniDFS = new MiniDFSCluster(conf, 1, true, null);
      if (oldTestBuildData == null)
        System.clearProperty("test.build.data");
      else
        System.setProperty("test.build.data", oldTestBuildData);
      miniDFS.waitClusterUp();
      InetSocketAddress dfsAddress = miniDFS.getNameNode().getNameNodeAddress();
      dfsUri = "hdfs://" + dfsAddress.getHostName() + ":" + dfsAddress.getPort();
      File coreFile = new File(config.getConfDir(), "core-site.xml");
      writeConfig(coreFile, Collections.singletonMap("fs.default.name", dfsUri).entrySet());
      File hdfsFile = new File(config.getConfDir(), "hdfs-site.xml");
      writeConfig(hdfsFile, conf);

      Map<String,String> siteConfig = config.getSiteConfig();
      siteConfig.put(Property.INSTANCE_DFS_URI.getKey(), dfsUri);
      siteConfig.put(Property.INSTANCE_DFS_DIR.getKey(), "/accumulo");
      config.setSiteConfig(siteConfig);
    } else {
      dfsUri = "file://";
    }

    File clientConfFile = config.getClientConfFile();
    // Write only the properties that correspond to ClientConfiguration properties
    writeConfigProperties(clientConfFile, Maps.filterEntries(config.getSiteConfig(), new Predicate<Entry<String,String>>() {
      @Override
      public boolean apply(Entry<String,String> v) {
        return ClientConfiguration.ClientProperty.getPropertyByKey(v.getKey()) != null;
      }
    }));

    File siteFile = new File(config.getConfDir(), "accumulo-site.xml");
    writeConfig(siteFile, config.getSiteConfig().entrySet());

    zooCfgFile = new File(config.getConfDir(), "zoo.cfg");
    FileWriter fileWriter = new FileWriter(zooCfgFile);

    // zookeeper uses Properties to read its config, so use that to write in order to properly escape things like Windows paths
    Properties zooCfg = new Properties();
    zooCfg.setProperty("tickTime", "2000");
    zooCfg.setProperty("initLimit", "10");
    zooCfg.setProperty("syncLimit", "5");
    zooCfg.setProperty("clientPort", config.getZooKeeperPort() + "");
    zooCfg.setProperty("maxClientCnxns", "1000");
    zooCfg.setProperty("dataDir", config.getZooKeeperDir().getAbsolutePath());
    zooCfg.store(fileWriter, null);

    fileWriter.close();
  }

  private void writeConfig(File file, Iterable<Map.Entry<String,String>> settings) throws IOException {
    FileWriter fileWriter = new FileWriter(file);
    fileWriter.append("<configuration>\n");

    for (Entry<String,String> entry : settings) {
      String value = entry.getValue().replace("&", "&").replace("<", "<").replace(">", ">");
      fileWriter.append("<property><name>" + entry.getKey() + "</name><value>" + value + "</value></property>\n");
    }
    fileWriter.append("</configuration>\n");
    fileWriter.close();
  }

  private void writeConfigProperties(File file, Map<String,String> settings) throws IOException {
    FileWriter fileWriter = new FileWriter(file);

    for (Entry<String,String> entry : settings.entrySet())
      fileWriter.append(entry.getKey() + "=" + entry.getValue() + "\n");
    fileWriter.close();
  }

  /**
   * Starts Accumulo and Zookeeper processes. Can only be called once.
   *
   * @throws IllegalStateException
   *           if already started
   */
  @Override
  public void start() throws IOException, InterruptedException {

    if (!initialized) {

      Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
          try {
            MiniAccumuloClusterImpl.this.stop();
          } catch (IOException e) {
            e.printStackTrace();
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
        }
      });
    }

    if (zooKeeperProcess == null) {
      zooKeeperProcess = _exec(ZooKeeperServerMain.class, ServerType.ZOOKEEPER, zooCfgFile.getAbsolutePath());
    }

    if (!initialized) {
      // sleep a little bit to let zookeeper come up before calling init, seems to work better
      long startTime = System.currentTimeMillis();
      while (true) {
        Socket s = null;
        try {
          s = new Socket("localhost", config.getZooKeeperPort());
          s.getOutputStream().write("ruok\n".getBytes());
          s.getOutputStream().flush();
          byte buffer[] = new byte[100];
          int n = s.getInputStream().read(buffer);
          if (n >= 4 && new String(buffer, 0, 4).equals("imok"))
            break;
        } catch (Exception e) {
          if (System.currentTimeMillis() - startTime >= ZOOKEEPER_STARTUP_WAIT) {
            throw new RuntimeException("Zookeeper did not start within " + (ZOOKEEPER_STARTUP_WAIT / 1000) + " seconds. Check the logs in "
                + config.getLogDir() + " for errors.  Last exception: " + e);
          }
          UtilWaitThread.sleep(250);
        } finally {
          if (s != null)
            s.close();
        }
      }
      Process initProcess = exec(Initialize.class, "--instance-name", config.getInstanceName(), "--password", config.getRootPassword());
      int ret = initProcess.waitFor();
      if (ret != 0) {
        throw new RuntimeException("Initialize process returned " + ret + ". Check the logs in " + config.getLogDir() + " for errors.");
      }
      initialized = true;
    }
    synchronized (tabletServerProcesses) {
      for (int i = tabletServerProcesses.size(); i < config.getNumTservers(); i++) {
        tabletServerProcesses.add(_exec(TabletServer.class, ServerType.TABLET_SERVER));
      }
    }
    int ret = 0;
    for (int i = 0; i < 5; i++) {
      ret = exec(Main.class, SetGoalState.class.getName(), MasterGoalState.NORMAL.toString()).waitFor();
      if (ret == 0)
        break;
      UtilWaitThread.sleep(1000);
    }
    if (ret != 0) {
      throw new RuntimeException("Could not set master goal state, process returned " + ret + ". Check the logs in " + config.getLogDir() + " for errors.");
    }
    if (masterProcess == null) {
      masterProcess = _exec(Master.class, ServerType.MASTER);
    }

    if (gcProcess == null) {
      gcProcess = _exec(SimpleGarbageCollector.class, ServerType.GARBAGE_COLLECTOR);
    }
  }

  private List<String> buildRemoteDebugParams(int port) {
    return Arrays.asList(new String[] {"-Xdebug", String.format("-Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=%d", port)});
  }

  /**
   * @return generated remote debug ports if in debug mode.
   * @since 1.6.0
   */
  public Set<Pair<ServerType,Integer>> getDebugPorts() {
    return debugPorts;
  }

  List<ProcessReference> references(Process... procs) {
    List<ProcessReference> result = new ArrayList<ProcessReference>();
    for (Process proc : procs) {
      result.add(new ProcessReference(proc));
    }
    return result;
  }

  public Map<ServerType,Collection<ProcessReference>> getProcesses() {
    Map<ServerType,Collection<ProcessReference>> result = new HashMap<ServerType,Collection<ProcessReference>>();
    result.put(ServerType.MASTER, references(masterProcess));
    result.put(ServerType.TABLET_SERVER, references(tabletServerProcesses.toArray(new Process[0])));
    result.put(ServerType.ZOOKEEPER, references(zooKeeperProcess));
    if (null != gcProcess) {
      result.put(ServerType.GARBAGE_COLLECTOR, references(gcProcess));
    }
    return result;
  }

  public void killProcess(ServerType type, ProcessReference proc) throws ProcessNotFoundException, InterruptedException {
    boolean found = false;
    switch (type) {
      case MASTER:
        if (proc.equals(masterProcess)) {
          masterProcess.destroy();
          masterProcess.waitFor();
          masterProcess = null;
          found = true;
        }
        break;
      case TABLET_SERVER:
        synchronized (tabletServerProcesses) {
          for (Process tserver : tabletServerProcesses) {
            if (proc.equals(tserver)) {
              tabletServerProcesses.remove(tserver);
              tserver.destroy();
              tserver.waitFor();
              found = true;
              break;
            }
          }
        }
        break;
      case ZOOKEEPER:
        if (proc.equals(zooKeeperProcess)) {
          zooKeeperProcess.destroy();
          zooKeeperProcess.waitFor();
          zooKeeperProcess = null;
          found = true;
        }
        break;
      case GARBAGE_COLLECTOR:
        if (proc.equals(gcProcess)) {
          gcProcess.destroy();
          gcProcess.waitFor();
          gcProcess = null;
          found = true;
        }
        break;
    }
    if (!found)
      throw new ProcessNotFoundException();
  }

  /**
   * @return Accumulo instance name
   */
  @Override
  public String getInstanceName() {
    return config.getInstanceName();
  }

  /**
   * @return zookeeper connection string
   */
  @Override
  public String getZooKeepers() {
    return config.getZooKeepers();
  }

  /**
   * Stops Accumulo and Zookeeper processes. If stop is not called, there is a shutdown hook that is setup to kill the processes. However its probably best to
   * call stop in a finally block as soon as possible.
   */
  @Override
  public void stop() throws IOException, InterruptedException {
    for (LogWriter lw : logWriters) {
      lw.flush();
    }

    if (gcProcess != null) {
      gcProcess.destroy();
      gcProcess.waitFor();
    }
    if (masterProcess != null) {
      masterProcess.destroy();
      masterProcess.waitFor();
    }
    if (tabletServerProcesses != null) {
      synchronized (tabletServerProcesses) {
        for (Process tserver : tabletServerProcesses) {
          tserver.destroy();
          tserver.waitFor();
        }
      }
    }
    if (zooKeeperProcess != null) {
      zooKeeperProcess.destroy();
      zooKeeperProcess.waitFor();
    }

    zooKeeperProcess = null;
    masterProcess = null;
    gcProcess = null;
    tabletServerProcesses.clear();
    if (config.useMiniDFS() && miniDFS != null)
      miniDFS.shutdown();
    for (Process p : cleanup) {
      p.destroy();
      p.waitFor();
    }
    miniDFS = null;
  }

  /**
   * @since 1.6.0
   */
  @Override
  public MiniAccumuloConfigImpl getConfig() {
    return config;
  }

  /**
   * Utility method to get a connector to the MAC.
   *
   * @since 1.6.0
   */
  @Override
  public Connector getConnector(String user, String passwd) throws AccumuloException, AccumuloSecurityException {
    Instance instance = new ZooKeeperInstance(getClientConfig());
    return instance.getConnector(user, new PasswordToken(passwd));
  }

  @Override
  public ClientConfiguration getClientConfig() {
    return new ClientConfiguration(Arrays.asList(new MapConfiguration(config.getSiteConfig()))).withInstance(this.getInstanceName()).withZkHosts(
        this.getZooKeepers());
  }

  public FileSystem getFileSystem() {
    try {
      return FileSystem.get(new URI(dfsUri), new Configuration());
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
}


text:
import a3c_main
import sys

class Defaults:

    #------------------------
    # Experiment Parameters
    #------------------------
    TRAINING = False  # testing by default
    EPOCHS = 100  # FIXME: not used
    MAX_STEPS = 160000000
    BATCH_SIZE = 32
    DETERMINISTIC = False  # use deterministic seed
    SAMPLE_ARGMAX = False  # False means use exploration
    NUM_REPS_EVAL = 10
    NUM_STEPS_EVAL = 10000
    # folder and prefix file
    # (the folder must exist before launching the code)
    RESULTS_FILE = "log/results"
    LEARNING_RATE = 0.0007
    GRADIENT_CLIPPING = None
    RENDER_FLAG = True  # only whilst evaluating the model

    #------------------------
    # GYM Parameters
    #------------------------
    GAME = 'Breakout-v0'

    #-----------------------
    # A3C Parameters
    #-----------------------
    NUM_THREADS = 16
    RESIZED_WIDTH = 84
    GAMMA_RATE = 0.99
    RESIZED_HEIGHT = 84
    AGENT_HISTORY_LENGTH = 4
    CHECKPOINT_INTERVAL = 50000
    A3C_LSTM = False
    LSTM_OUTPUT_UNITS = 256

if __name__ == "__main__":
    a3c_main.launch(sys.argv[1:], Defaults, __doc__)


text:
package org.typetopaste.install;

import static org.typetopaste.util.StringUtil.join;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;

import org.typetopaste.key.KeyUtil;
import org.typetopaste.util.IOUtil;
import org.typetopaste.util.TemplateEngine;

/**
 * Implementation of {@link ShortcutCreator} for MS Windows.<br/>
 *
 * Generates and runs VB script that creates desktop shortcut with predefined keyboard shortcut.
 *
 * @author alex
 */
public class WindowsShortcutCreator implements ShortcutCreator {
	private static final String ICON_RESOURCE = "keyboard.ico";

	private static final String ARGS = "typetopaste.args";
	private static final String ICON = "typetopaste.icon";
	private static final String SHORTCUT = "typetopaste.shortcut";

	private static final String SCRIPT_TIMPLATE = "CreateShortcutTemplate.vbs";
	private static final String SCRIPT_NAME = "CreateTypeToPasteShortcut.vbs";
	private static final String CSCRIPT = "cscript";

	private TemplateEngine templateEngine = new TemplateEngine();

	// http://stackoverflow.com/questions/17061482/jdk-7-reports-itself-as-a-jre-via-java-home-system-property

	@Override
	public void createShortcut(String jvmPath, String[] args, int[] shortcut) throws IOException {
		File tmpDir = new File(System.getProperty("java.io.tmpdir"));
		File icon = extractIcon(tmpDir);
		Properties props = new Properties(System.getProperties());
		props.setProperty(ARGS, join(" ", args));
		props.setProperty(ICON, icon.getAbsolutePath());
		props.setProperty(SHORTCUT, KeyUtil.toString(shortcut));

		String scriptTemplate = IOUtil.readAllAsString(getClass().getResourceAsStream('/' + SCRIPT_TIMPLATE));
		String scriptSrc = templateEngine.process(scriptTemplate, props);

		File script = new File(tmpDir, SCRIPT_NAME);

		try (OutputStream scriptOut = new FileOutputStream(script)) {
			IOUtil.copy(new ByteArrayInputStream(scriptSrc.getBytes()), scriptOut);
		}

		ProcessBuilder pb  = new ProcessBuilder();
		pb.command(CSCRIPT, script.getAbsolutePath());
		Process process = pb.start();
		try {
			process.waitFor();
		} catch (InterruptedException e) {
			throw new IOException(e);
		}
	}

	private File extractIcon(File toDir) throws IOException {
		File iconFile = new File(toDir, ICON_RESOURCE);
		try (OutputStream out = new FileOutputStream(iconFile)) {
			IOUtil.copy(getClass().getResourceAsStream("/" + ICON_RESOURCE), out);
		}
		return iconFile;
	}
}


text:
export const setCookie = (cookieName, cvalue, exdays) => {
  const d = new Date();
  d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
  const expires = `expires=${ d.toUTCString() }`;
  document.cookie = `${ cookieName }=${ cvalue };${ expires };path=/`;
};

export const getCookie = cookieName => {
  const name = `${ cookieName }=`;
  const decodedCookie = decodeURIComponent(document.cookie);
  const ca = decodedCookie.split(';');
  for (let i = 0; i < ca.length; i++) {
    let c = ca[i];
    while (c.charAt(0) == ' ') {
      c = c.substring(1);
    }
    if (c.indexOf(name) == 0) {
      return c.substring(name.length, c.length);
    }
  }
  return '';
};


text:
<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <artifactId>MJAVADOC-280-1</artifactId>
    <groupId>org.apache.maven.plugins.maven-javadoc-plugin.it</groupId>
    <version>1.0-SNAPSHOT</version>
  </parent>

  <artifactId>MJAVADOC-280-1-modB</artifactId>
  <name>MJAVADOC-280-1-modB</name>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-source-plugin</artifactId>
      </plugin>
    </plugins>
  </build>
</project>


text:
const char usage[]  = "\n\
StochHMM - Stochastic Hidden Markov Model Framework (version 0.36) Date: September 6, 2013\n\
\n\
Usage: StochHMM -model <model_file>  -seq <seq_file> [options]\n\
\n\
Command Line options:\n\
\t-help or -h		print usage statement\n\
\n\
Files: reqires a sequence file and a model file\n\
\t-model <model file>\t\timport model file\n\
\t-seq <sequence file>\t\t\timport sequence file in fasta format\n\
\n\
Non-stochastic Decoding:  Different algorithms available for decoding\n\
\t-viterbi\t\t\tperforms viterbi traceback\n\
\t-posterior\t\tCalculates posterior probabilities\n\
\t\t\tIf no output options are supplied, this will return the posterior scores\n\
\t\t\tfor all of the states.\n\n\
\t\t-threshold <score>: Return only the States with a GFF_DESC, if they are\n\
\t\t\tgreater than or equal to the threshold amount.\n\n\
\t-nbest <number of paths> \t\tperforms n-best viterbi algorithm\n\
\n\
Stochastic Decoding:\n\
\t-stochastic <Type of stochastic algorithm to use> -repetitions <number of tracebacks to sample>\n\
\t\tTypes:\n\
\t\tforward\t\t\tperforms stochastic traceback using forward algorithm\n\
\t\tviterbi\t\t\tperforms stochastic traceback using modified-viterbi algorithm\n\
\t\tposterior\t\t\tperforms stochastic traceback using posterior algorithm\n\
\n\
Output options:\n\
\t-gff\t\t\tprints path in GFF format\n\
\t-path\t\t\tprints state path according to state number\n\
\t-label\t\t\tprints state path as labels\n\
\t-hits\t\tprints hit table from stochastic sampling for each position and state\n\
\n\
Written by Paul Lott at University of California, Davis\n\
Please direct any questions, suggestions or bugs reports to Paul Lott at plott@ucdavis.edu\n\
\n\
";

#endif


text:
Create a Server
===
[![NPM version][npm-image]][npm-url] [![Build Status][travis-image]][travis-url] [![Coverage Status][codecov-image]][codecov-url] [![Dependencies][dependencies-image]][dependencies-url]

> Create an HTTP/S [server](https://github.com/kgryte/node-http-server) (or server [cluster](https://github.com/kgryte/node-server-cluster)).

## Installation

``` bash
$ npm install create-a-server
```

## Usage

``` javascript
var server = require( 'create-a-server' );
```

#### server( [ options,] logger[, requestListener ] )

Returns a `function` to create an HTTP/S [server](https://github.com/kgryte/node-http-server) (or server [cluster](https://github.com/kgryte/node-server-cluster)).

``` javascript

```

The `function` accepts the following `options`:

*	__port__: server port. Default: `0`, i.e., randomly assigned.
*	__address__: server address. Default: `0.0.0.0`.
*	__hostname__: server hostname.
*	__maxport__: max server port when [port hunting](https://github.com/kgryte/node-http-server#notes). Default: `maxport=port`.
*	__ssl__: `boolean` indicating whether to create an [HTTPS](https://github.com/kgryte/node-https-server) server. Default: `false`.
*	__key__: path to private key for TLS/SSL.
*	__cert__: path to public certificate for TLS/SSL.
*	__cluster__: `boolean` indicating whether to run a server in [cluster](https://github.com/kgryte/node-server-cluster) mode. Default: `false`.
*	__size__: cluster size. Default: `num_cpus`.

#### create( done )

Creates an HTTP/S [server](https://github.com/kgryte/node-http-server) (or server [cluster](https://github.com/kgryte/node-server-cluster)).

``` javascript
var cluster = require( 'cluster' );

function done( error, server ) {
	if ( error ) {
		throw error;
	}
	if ( cluster.isMaster ) {
		console.log( 'All workers are ready.' );
	} else {
		console.log( server.address() );
	}
}

create( done );
```

## Examples

``` javascript
var express = require( 'express' ),
	logger = require( './logger.js' ),
	next = require( './next.js' ),
	server = require( 'create-a-server' );

// Specify server options...
var opts = {
	'port': 7331,
	'cluster': true,
	'size': 2
};

// Create an express app:
var app = express();

// Create a function for creating a server cluster...
var createServer = server( opts, logger, app );

// Create a cluster:
createServer( next );
```

To run the example code from the top-level application directory,

``` bash
$ node ./examples/index.js
```

## Tests

### Unit

Unit tests use the [Mocha](http://mochajs.org/) test framework with [Chai](http://chaijs.com) assertions. To run the tests, execute the following command in the top-level application directory:

``` bash
$ make test
```

All new feature development should have corresponding unit tests to validate correct functionality.

### Test Coverage

This repository uses [Istanbul](https://github.com/gotwarlost/istanbul) as its code coverage tool. To generate a test coverage report, execute the following command in the top-level application directory:

``` bash
$ make test-cov
```

Istanbul creates a `./reports/coverage` directory. To access an HTML version of the report,

``` bash
$ make view-cov
```

---
## License

[MIT license](http://opensource.org/licenses/MIT).

## Copyright

Copyright © 2015. Athan Reines.

[npm-image]: http://img.shields.io/npm/v/create-a-server.svg
[npm-url]: https://npmjs.org/package/create-a-server

[travis-image]: http://img.shields.io/travis/kgryte/create-a-server/master.svg
[travis-url]: https://travis-ci.org/kgryte/create-a-server

[codecov-image]: https://img.shields.io/codecov/c/github/kgryte/create-a-server/master.svg
[codecov-url]: https://codecov.io/github/kgryte/create-a-server?branch=master

[dependencies-image]: http://img.shields.io/david/kgryte/create-a-server.svg
[dependencies-url]: https://david-dm.org/kgryte/create-a-server

[dev-dependencies-image]: http://img.shields.io/david/dev/kgryte/create-a-server.svg
[dev-dependencies-url]: https://david-dm.org/dev/kgryte/create-a-server

[github-issues-image]: http://img.shields.io/github/issues/kgryte/create-a-server.svg
[github-issues-url]: https://github.com/kgryte/create-a-server/issues


text:
import unittest

import numpy as np

import chainer
from chainer import testing
from chainer.dataset import tabular

class TestFromData(unittest.TestCase):

    def test_unary_args(self):
        dataset = tabular.from_data(np.arange(10))

        self.assertIsInstance(dataset, chainer.dataset.TabularDataset)
        self.assertEqual(len(dataset), 10)
        self.assertEqual(len(dataset.keys), 1)
        self.assertIsNone(dataset.mode)

        output = dataset.slice[[1, 3]].fetch()
        np.testing.assert_equal(output, [1, 3])
        self.assertIsInstance(output, np.ndarray)

    def test_unary_args_with_key(self):
        dataset = tabular.from_data(('a', np.arange(10)))

        self.assertIsInstance(dataset, chainer.dataset.TabularDataset)
        self.assertEqual(len(dataset), 10)
        self.assertEqual(dataset.keys, ('a',))
        self.assertIsNone(dataset.mode)

        output = dataset.slice[[1, 3]].fetch()
        np.testing.assert_equal(output, [1, 3])
        self.assertIsInstance(output, np.ndarray)

    def test_unary_kwargs(self):
        dataset = tabular.from_data(a=np.arange(10))

        self.assertIsInstance(dataset, chainer.dataset.TabularDataset)
        self.assertEqual(len(dataset), 10)
        self.assertEqual(dataset.keys, ('a',))
        self.assertIsNone(dataset.mode)

        output = dataset.slice[[1, 3]].fetch()
        np.testing.assert_equal(output, [1, 3])
        self.assertIsInstance(output, np.ndarray)

    def test_tuple(self):
        dataset = tabular.from_data(
            np.arange(10),
            ('b', [2, 7, 1, 8, 4, 5, 9, 0, 3, 6]))

        self.assertIsInstance(dataset, chainer.dataset.TabularDataset)
        self.assertEqual(len(dataset), 10)
        self.assertEqual(len(dataset.keys), 2)
        self.assertEqual(dataset.keys[1], 'b')
        self.assertEqual(dataset.mode, tuple)

        output = dataset.slice[[1, 3]].fetch()
        np.testing.assert_equal(output, ([1, 3], [7, 8]))
        self.assertIsInstance(output[0], np.ndarray)
        self.assertIsInstance(output[1], list)

    def test_tuple_unique(self):
        dataset_a = tabular.from_data(
            np.arange(10),
            [3, 1, 4, 5, 9, 2, 6, 8, 7, 0])
        dataset_b = tabular.from_data(
            [2, 7, 1, 8, 4, 5, 9, 0, 3, 6],
            -np.arange(10))
        self.assertFalse(set(dataset_a.keys) & set(dataset_b.keys))

    def test_dict(self):
        dataset = tabular.from_data(
            a=np.arange(10),
            b=[2, 7, 1, 8, 4, 5, 9, 0, 3, 6])

        self.assertIsInstance(dataset, chainer.dataset.TabularDataset)
        self.assertEqual(len(dataset), 10)
        self.assertEqual(set(dataset.keys), {'a', 'b'})
        self.assertEqual(dataset.mode, dict)

        output = dataset.slice[[1, 3]].fetch()
        np.testing.assert_equal(output, {'a': [1, 3], 'b': [7, 8]})
        self.assertIsInstance(output['a'], np.ndarray)
        self.assertIsInstance(output['b'], list)

testing.run_module(__name__, __file__)


text:
function _SoundManagerAdd(name, filename)
{
	Module.SoundManagerAdd(Pointer_stringify(name), Pointer_stringify(filename));
}

function _SoundManagerPlay(name)
{
    Module.SoundManagerPlay(Pointer_stringify(name));
}

function _SoundManagerPause(name)
{
    Module.SoundManagerPause(Pointer_stringify(name));
}

function _SoundManagerStop(name)
{
    Module.SoundManagerStop(Pointer_stringify(name));
}

function _SoundManagerLoop(name)
{
    Module.SoundManagerLoop(Pointer_stringify(name));
}

function _SoundManagerSetGain(name, gain)
{
    Module.SoundManagerSetGain(Pointer_stringify(name), gain);
}


text:
module Questionable
  class Answer < ApplicationRecord
    belongs_to :user
    belongs_to :option
    belongs_to :question, inverse_of: :answers

    def date_answer
      message.try(:to_date)
    rescue ArgumentError
    end

    def answer_summary
      if option && message
        "#{option.title} (#{message})"
      elsif message && question.date?
        date_answer
      elsif option
        option.title
      else
        message
      end
    end
  end
end


text:
<lift:surround with="default" at="content">
  <lift:TestController.test2 />
</lift:surround>


text:
<?php

 namespace Company\Model;
 use Zend\InputFilter\InputFilter;
 use Zend\InputFilter\InputFilterAwareInterface;
 use Zend\InputFilter\InputFilterInterface;

class Company implements InputFilterAwareInterface
 {

        public $id;
        public $public;
        public $added ;
        public $enterprise ;
        public $advertiser ;
        public $provider;
        public $street;
        public $number;
        public $bus ;
        public $city;
        public $postal ;
        public $country;
        public $btw;
        public $invoice;
        public $serviceprovider;
        protected $inputFilter;

     public function exchangeArray($data)
     {
         $this->id     = (!empty($data['id'])) ? $data['id'] : null;
         $this->public = (!empty($data['public'])) ? $data['public'] : null;
         $this->added = (!empty($data['added'])) ? $data['added'] : null;
         $this->entreprise     = (!empty($data['entreprise'])) ? $data['entreprise'] : null;
         $this->advertiser = (!empty($data['advertiser'])) ? $data['advertiser'] : null;
         $this->provider = (!empty($data['provider'])) ? $data['provider'] : null;
         $this->street     = (!empty($data['street'])) ? $data['street'] : null;
         $this->number = (!empty($data['number'])) ? $data['number'] : null;
         $this->bus = (!empty($data['bus'])) ? $data['bus'] : null;
         $this->city     = (!empty($data['city'])) ? $data['city'] : null;
         $this->postal = (!empty($data['postal'])) ? $data['postal'] : null;
         $this->country = (!empty($data['country'])) ? $data['country'] : null;
         $this->btw     = (!empty($data['btw'])) ? $data['btw'] : null;
         $this->invoice = (!empty($data['invoice'])) ? $data['invoice'] : null;
         $this->serviceprovider = (!empty($data['serviceprovider'])) ? $data['serviceprovider'] : null;
     }

    public function getArrayCopy()
    {
        return get_object_vars($this);
    }

    public function setInputFilter(InputFilterInterface $inputFilter)
    {
        throw new \Exception("Not used");
    }
 }
?>


text: Tests that origin whitelisting for https does not match http URLs.


text:
package org.springframework.boot.test.autoconfigure.jdbc;

import java.util.Collections;
import java.util.Set;

import org.springframework.boot.context.TypeExcludeFilter;
import org.springframework.boot.test.autoconfigure.filter.AnnotationCustomizableTypeExcludeFilter;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.core.annotation.AnnotatedElementUtils;

/**
 * {@link TypeExcludeFilter} for {@link JdbcTest @JdbcTest}.
 *
 * @author Stephane Nicoll
 */
class JdbcTypeExcludeFilter extends AnnotationCustomizableTypeExcludeFilter {

	private final JdbcTest annotation;

	JdbcTypeExcludeFilter(Class<?> testClass) {
		this.annotation = AnnotatedElementUtils.getMergedAnnotation(testClass,
				JdbcTest.class);
	}

	@Override
	protected boolean hasAnnotation() {
		return this.annotation != null;
	}

	@Override
	protected ComponentScan.Filter[] getFilters(FilterType type) {
		switch (type) {
		case INCLUDE:
			return this.annotation.includeFilters();
		case EXCLUDE:
			return this.annotation.excludeFilters();
		}
		throw new IllegalStateException("Unsupported type " + type);
	}

	@Override
	protected boolean isUseDefaultFilters() {
		return this.annotation.useDefaultFilters();
	}

	@Override
	protected Set<Class<?>> getDefaultIncludes() {
		return Collections.emptySet();
	}

	@Override
	protected Set<Class<?>> getComponentIncludes() {
		return Collections.emptySet();
	}

}


text:
package org.workcraft.plugins.circuit.commands;

import org.workcraft.plugins.circuit.VisualCircuit;
import org.workcraft.workspace.WorkspaceEntry;
import org.workcraft.workspace.WorkspaceUtils;

public class CircuitLayoutPlacementCommand extends CircuitLayoutCommand {

    @Override
    public String getDisplayName() {
        return "Circuit placement only";
    }

    @Override
    public boolean isApplicableTo(WorkspaceEntry we) {
        return WorkspaceUtils.isApplicable(we, VisualCircuit.class);
    }

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

}