text:
package org.openkilda.helper;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;

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

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.openkilda.constants.HttpError;
import org.openkilda.constants.IAuthConstants;
import org.openkilda.exception.ExternalSystemException;
import org.openkilda.exception.RestCallFailedException;
import org.openkilda.exception.UnauthorizedException;
import org.openkilda.integration.exception.InvalidResponseException;
import org.openkilda.model.response.ErrorMessage;
import org.openkilda.service.AuthPropertyService;
import org.openkilda.utility.IoUtil;
import org.openkilda.utility.StringUtil;

/**
 * The Class RestClientManager.
 */
@Component
public class RestClientManager {

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

    @Autowired
    private AuthPropertyService authPropertyService;

    @Autowired
    private ObjectMapper mapper;

    /**
     * Invoke.
     *
     * @param apiUrl the api url
     * @param httpMethod the http method
     * @param payload the payload
     * @param contentType the content type
     * @param basicAuth the basic auth
     * @return the http response
     */
    public HttpResponse invoke(final String apiUrl, final HttpMethod httpMethod,
            final String payload, final String contentType, final String basicAuth) {
        LOGGER.info("[invoke] - Start");

        HttpResponse httpResponse = null;

        try {
            HttpClient client = HttpClients.createDefault();
            HttpUriRequest httpUriRequest = null;
            HttpEntityEnclosingRequestBase httpEntityEnclosingRequest = null;

            // Initializing Request
            if (HttpMethod.POST.equals(httpMethod)) {
                httpEntityEnclosingRequest = new HttpPost(apiUrl);
            } else if (HttpMethod.PUT.equals(httpMethod)) {
                httpEntityEnclosingRequest = new HttpPut(apiUrl);
            } else if (HttpMethod.DELETE.equals(httpMethod)) {
                httpUriRequest = new HttpDelete(apiUrl);
            } else {
                httpUriRequest = new HttpGet(apiUrl);
            }

            if (!HttpMethod.POST.equals(httpMethod) && !HttpMethod.PUT.equals(httpMethod)) {
                // Setting Required Headers
                if (!StringUtil.isNullOrEmpty(basicAuth)) {
                    LOGGER.debug("[invoke] Setting authorization in header as "
                            + IAuthConstants.Header.AUTHORIZATION);
                    httpUriRequest.setHeader(IAuthConstants.Header.AUTHORIZATION, basicAuth);
                }
            }

            if (HttpMethod.POST.equals(httpMethod) || HttpMethod.PUT.equals(httpMethod)) {
                LOGGER.info("[invoke] Executing POST/ PUT request : httpEntityEnclosingRequest : "
                        + httpEntityEnclosingRequest + " : payload : " + payload);
                // Setting POST/PUT related headers
                httpEntityEnclosingRequest.setHeader(HttpHeaders.CONTENT_TYPE, contentType);

                httpEntityEnclosingRequest.setHeader(IAuthConstants.Header.BASIC_AUTH, basicAuth);

                // Setting request payload
                httpEntityEnclosingRequest.setEntity(new StringEntity(payload));

                httpResponse = client.execute(httpEntityEnclosingRequest);
                LOGGER.debug("[invoke] Call executed successfully");
            } else if (HttpMethod.DELETE.equals(httpMethod) || HttpMethod.GET.equals(httpMethod)) {
                LOGGER.info("[invoke] Executing DELETE/ GET request : httpUriRequest : "
                        + httpUriRequest);
                httpResponse = client.execute(httpUriRequest);
                LOGGER.info("[invoke] Call executed successfully");
            }

        } catch (Exception e) {
            LOGGER.error("[invoke] Exception: ", e);
            throw new RestCallFailedException(e);
        }
        LOGGER.info("[invoke] - End");
        return httpResponse;
    }

    /**
     * Invoke.
     *
     * @param <T> the generic type
     * @param response the response
     * @param responseClass the response class
     * @return the http response
     */
    // @SuppressWarnings("rawtypes")
    // public HttpResponse invoke(final String correlationId, String apiUrl,
    // final HttpMethod httpMethod, final String payload, final String token,
    // final String contentType, final String basicAuth, final Map<String, String> queryParams) {
    // StringBuilder queryStringBuilder = new StringBuilder();
    // if (queryParams != null) {
    // for (String key : queryParams.keySet()) {
    //
    // if (!StringUtils.isNullOrEmpty(key)
    // && !StringUtils.isNullOrEmpty(queryParams.get(key))) {
    // if (queryStringBuilder.length() == 0 && !apiUrl.contains("?")) {
    // queryStringBuilder.append("?");
    // } else {
    // queryStringBuilder.append("&");
    // }
    // queryStringBuilder.append(key).append("=").append(queryParams.get(key));
    // }
    // }
    // }
    // return invoke(correlationId, apiUrl + queryStringBuilder.toString(), httpMethod, payload,
    // token, contentType, basicAuth, new HashMap());
    // }

    /**
     * Gets the response list.
     *
     * @param <T> the generic type
     * @param response the response
     * @param responseClass the response class
     * @return the response list
     */
    @SuppressWarnings("unchecked")
    public <T> List<T> getResponseList(final HttpResponse response, final Class<T> responseClass) {
        return getResponse(response, List.class, responseClass);
    }

    /**
     * Gets the response.
     *
     * @param <T> the generic type
     * @param response the response
     * @param responseClass the response class
     * @return the response
     */
    public <T> T getResponse(final HttpResponse response, final Class<T> responseClass) {
        return getResponse(response, responseClass, null);
    }

    /**
     * Gets the response.
     *
     * @param <T> the generic type
     * @param <E> the element type
     * @param response the response
     * @param responseClass the response class
     * @param dependentClass the dependent class
     * @return the response
     */
    private <T, E> T getResponse(final HttpResponse response, final Class<T> responseClass,
            final Class<E> dependentClass) {
        T obj = null;
        try {
            LOGGER.info("[getResponse]  : StatusCode " + response.getStatusLine().getStatusCode());

            if (response.getStatusLine().getStatusCode() != HttpStatus.NO_CONTENT.value()) {
                String responseEntity = IoUtil.toString(response.getEntity().getContent());

                LOGGER.info("[getResponse]  : response object " + responseEntity);
                if (!(HttpStatus.valueOf(response.getStatusLine().getStatusCode())
                        .is2xxSuccessful() && response.getEntity() != null)) {
                    String errorMessage = null;
                    try {
                        if (responseEntity.startsWith("[")) {
                            responseEntity = responseEntity.replaceFirst("]", "").trim();
                        }
                        if (responseEntity.endsWith("]")) {
                            responseEntity = responseEntity.replace("]", "").trim();
                        }

                        errorMessage =
                                mapper.readValue(responseEntity, ErrorMessage.class).getMessage();

                    } catch (Exception e) {
                        if (response.getStatusLine().getStatusCode() == HttpStatus.UNAUTHORIZED
                                .value()) {
                            throw new UnauthorizedException(HttpError.UNAUTHORIZED.getMessage());
                        }

                        LOGGER.error("[getResponse] Exception :", e);
                        errorMessage =
                                authPropertyService.getError(
                                        IAuthConstants.Code.RESPONSE_PARSING_FAIL_ERROR)
                                        .getMessage();
                        throw new RestCallFailedException(errorMessage);
                    }

                    LOGGER.error("[getResponse] Exception : " + responseEntity);
                    throw new ExternalSystemException(response.getStatusLine().getStatusCode(),
                            errorMessage);

                } else {
                    if (dependentClass == null) {
                        obj = mapper.readValue(responseEntity, responseClass);
                    } else {
                        obj =
                                mapper.readValue(responseEntity, TypeFactory.defaultInstance()
                                        .constructCollectionLikeType(responseClass, dependentClass));
                    }
                }
            }
        } catch (IOException e) {
            throw new RestCallFailedException(e.getMessage());
        }
        return obj;
    }

    /**
     * Checks if is valid response.
     *
     * @param response the response
     * @return true, if is valid response
     */
    public static boolean isValidResponse(final HttpResponse response) {
        LOGGER.debug("[isValidResponse] Response Code " + response.getStatusLine().getStatusCode());
        boolean isValid = response.getStatusLine().getStatusCode() >= HttpStatus.OK.value()
                && response.getStatusLine().getStatusCode() < HttpStatus.MULTIPLE_CHOICES.value()
                && response.getEntity() != null;
        if(isValid) {
            return true;
        } else {
            try {
                String content = IoUtil.toString(response.getEntity().getContent());
                throw new InvalidResponseException(response.getStatusLine().getStatusCode(),
                        content);
            } catch (IOException exception) {
                LOGGER.error("[getResponse] Exception :" + exception.getMessage(), exception);
                throw new InvalidResponseException();
            }
        }
    }
}


text:
python setup.py install --prefix=~/.local
pushd sample
rm -rf liquipy_changelog.xml
python sample.py
popd

redpajama_set_name: RedPajamaGithub


text:
/**
 *
 */
/**
 * @author MrMoneyChanger
 *
 */
package com.firstlight.ui.wallet;


text:
namespace extra {
	public struct Margin {

		public int left;
		public int top;
		public int right;
		public int bottom;

		public Margin(int left, int top, int right, int bottom) {
			this.left = left;
			this.top = top;
			this.right = right;
			this.bottom = bottom;
		}

		public Margin(int leftRight, int topBottom) {
			this.left = leftRight;
			this.top = topBottom;
			this.right = leftRight;
			this.bottom = topBottom;
		}

		public Margin(int val) {
			this.left = val;
			this.top = val;
			this.right = val;
			this.bottom = val;
		}
	}
}


text:
/*
 * I'm tired of doing "vsnprintf()" etc just to open a
 * file, so here's a "return static buffer with printf"
 * interface for paths.
 *
 * It's obviously not thread-safe. Sue me. But it's quite
 * useful for doing things like
 *
 *   f = open(mkpath("%s/%s.perf", base, name), O_RDONLY);
 *
 * which is what it's designed for.
 */
#include "cache.h"

static char bad_path[] = "/bad-path/";
/*
 * Two hacks:
 */

static const char *get_perf_dir(void)
{
	return ".";
}

size_t strlcpy(char *dest, const char *src, size_t size)
{
	size_t ret = strlen(src);

	if (size) {
		size_t len = (ret >= size) ? size - 1 : ret;
		memcpy(dest, src, len);
		dest[len] = '\0';
	}
	return ret;
}

static char *get_pathname(void)
{
	static char pathname_array[4][PATH_MAX];
	static int idx;

	return pathname_array[3 & ++idx];
}

static char *cleanup_path(char *path)
{
	/* Clean it up */
	if (!memcmp(path, "./", 2)) {
		path += 2;
		while (*path == '/')
			path++;
	}
	return path;
}

char *mksnpath(char *buf, size_t n, const char *fmt, ...)
{
	va_list args;
	unsigned len;

	va_start(args, fmt);
	len = vsnprintf(buf, n, fmt, args);
	va_end(args);
	if (len >= n) {
		strlcpy(buf, bad_path, n);
		return buf;
	}
	return cleanup_path(buf);
}

static char *perf_vsnpath(char *buf, size_t n, const char *fmt, va_list args)
{
	const char *perf_dir = get_perf_dir();
	size_t len;

	len = strlen(perf_dir);
	if (n < len + 1)
		goto bad;
	memcpy(buf, perf_dir, len);
	if (len && !is_dir_sep(perf_dir[len-1]))
		buf[len++] = '/';
	len += vsnprintf(buf + len, n - len, fmt, args);
	if (len >= n)
		goto bad;
	return cleanup_path(buf);
bad:
	strlcpy(buf, bad_path, n);
	return buf;
}

char *perf_snpath(char *buf, size_t n, const char *fmt, ...)
{
	va_list args;
	va_start(args, fmt);
	(void)perf_vsnpath(buf, n, fmt, args);
	va_end(args);
	return buf;
}

char *perf_pathdup(const char *fmt, ...)
{
	char path[PATH_MAX];
	va_list args;
	va_start(args, fmt);
	(void)perf_vsnpath(path, sizeof(path), fmt, args);
	va_end(args);
	return xstrdup(path);
}

char *mkpath(const char *fmt, ...)
{
	va_list args;
	unsigned len;
	char *pathname = get_pathname();

	va_start(args, fmt);
	len = vsnprintf(pathname, PATH_MAX, fmt, args);
	va_end(args);
	if (len >= PATH_MAX)
		return bad_path;
	return cleanup_path(pathname);
}

char *perf_path(const char *fmt, ...)
{
	const char *perf_dir = get_perf_dir();
	char *pathname = get_pathname();
	va_list args;
	unsigned len;

	len = strlen(perf_dir);
	if (len > PATH_MAX-100)
		return bad_path;
	memcpy(pathname, perf_dir, len);
	if (len && perf_dir[len-1] != '/')
		pathname[len++] = '/';
	va_start(args, fmt);
	len += vsnprintf(pathname + len, PATH_MAX - len, fmt, args);
	va_end(args);
	if (len >= PATH_MAX)
		return bad_path;
	return cleanup_path(pathname);
}

/* perf_mkstemp() - create tmp file honoring TMPDIR variable */
int perf_mkstemp(char *path, size_t len, const char *template)
{
	const char *tmp;
	size_t n;

	tmp = getenv("TMPDIR");
	if (!tmp)
		tmp = "/tmp";
	n = snprintf(path, len, "%s/%s", tmp, template);
	if (len <= n) {
		errno = ENAMETOOLONG;
		return -1;
	}
	return mkstemp(path);
}

const char *make_relative_path(const char *abs_path, const char *base)
{
	static char buf[PATH_MAX + 1];
	int baselen;

	if (!base)
		return abs_path;

	baselen = strlen(base);
	if (prefixcmp(abs_path, base))
		return abs_path;
	if (abs_path[baselen] == '/')
		baselen++;
	else if (base[baselen - 1] != '/')
		return abs_path;

	strcpy(buf, abs_path + baselen);

	return buf;
}

/*
 * It is okay if dst == src, but they should not overlap otherwise.
 *
 * Performs the following normalizations on src, storing the result in dst:
 * - Ensures that components are separated by '/' (Windows only)
 * - Squashes sequences of '/'.
 * - Removes "." components.
 * - Removes ".." components, and the components the precede them.
 * Returns failure (non-zero) if a ".." component appears as first path
 * component anytime during the normalization. Otherwise, returns success (0).
 *
 * Note that this function is purely textual.  It does not follow symlinks,
 * verify the existence of the path, or make any system calls.
 */
int normalize_path_copy(char *dst, const char *src)
{
	char *dst0;

	if (has_dos_drive_prefix(src)) {
		*dst++ = *src++;
		*dst++ = *src++;
	}
	dst0 = dst;

	if (is_dir_sep(*src)) {
		*dst++ = '/';
		while (is_dir_sep(*src))
			src++;
	}

	for (;;) {
		char c = *src;

		/*
		 * A path component that begins with . could be
		 * special:
		 * (1) "." and ends   -- ignore and terminate.
		 * (2) "./"           -- ignore them, eat slash and continue.
		 * (3) ".." and ends  -- strip one and terminate.
		 * (4) "../"          -- strip one, eat slash and continue.
		 */
		if (c == '.') {
			if (!src[1]) {
				/* (1) */
				src++;
			} else if (is_dir_sep(src[1])) {
				/* (2) */
				src += 2;
				while (is_dir_sep(*src))
					src++;
				continue;
			} else if (src[1] == '.') {
				if (!src[2]) {
					/* (3) */
					src += 2;
					goto up_one;
				} else if (is_dir_sep(src[2])) {
					/* (4) */
					src += 3;
					while (is_dir_sep(*src))
						src++;
					goto up_one;
				}
			}
		}

		/* copy up to the next '/', and eat all '/' */
		while ((c = *src++) != '\0' && !is_dir_sep(c))
			*dst++ = c;
		if (is_dir_sep(c)) {
			*dst++ = '/';
			while (is_dir_sep(c))
				c = *src++;
			src--;
		} else if (!c)
			break;
		continue;

	up_one:
		/*
		 * dst0..dst is prefix portion, and dst[-1] is '/';
		 * go up one level.
		 */
		dst--;	/* go to trailing '/' */
		if (dst <= dst0)
			return -1;
		/* Windows: dst[-1] cannot be backslash anymore */
		while (dst0 < dst && dst[-1] != '/')
			dst--;
	}
	*dst = '\0';
	return 0;
}

/*
 * path = Canonical absolute path
 * prefix_list = Colon-separated list of absolute paths
 *
 * Determines, for each path in prefix_list, whether the "prefix" really
 * is an ancestor directory of path.  Returns the length of the longest
 * ancestor directory, excluding any trailing slashes, or -1 if no prefix
 * is an ancestor.  (Note that this means 0 is returned if prefix_list is
 * "/".) "/foo" is not considered an ancestor of "/foobar".  Directories
 * are not considered to be their own ancestors.  path must be in a
 * canonical form: empty components, or "." or ".." components are not
 * allowed.  prefix_list may be null, which is like "".
 */
int longest_ancestor_length(const char *path, const char *prefix_list)
{
	char buf[PATH_MAX+1];
	const char *ceil, *colon;
	int len, max_len = -1;

	if (prefix_list == NULL || !strcmp(path, "/"))
		return -1;

	for (colon = ceil = prefix_list; *colon; ceil = colon+1) {
		for (colon = ceil; *colon && *colon != PATH_SEP; colon++);
		len = colon - ceil;
		if (len == 0 || len > PATH_MAX || !is_absolute_path(ceil))
			continue;
		strlcpy(buf, ceil, len+1);
		if (normalize_path_copy(buf, buf) < 0)
			continue;
		len = strlen(buf);
		if (len > 0 && buf[len-1] == '/')
			buf[--len] = '\0';

		if (!strncmp(path, buf, len) &&
		    path[len] == '/' &&
		    len > max_len) {
			max_len = len;
		}
	}

	return max_len;
}

/* strip arbitrary amount of directory separators at end of path */
static inline int chomp_trailing_dir_sep(const char *path, int len)
{
	while (len && is_dir_sep(path[len - 1]))
		len--;
	return len;
}

/*
 * If path ends with suffix (complete path components), returns the
 * part before suffix (sans trailing directory separators).
 * Otherwise returns NULL.
 */
char *strip_path_suffix(const char *path, const char *suffix)
{
	int path_len = strlen(path), suffix_len = strlen(suffix);

	while (suffix_len) {
		if (!path_len)
			return NULL;

		if (is_dir_sep(path[path_len - 1])) {
			if (!is_dir_sep(suffix[suffix_len - 1]))
				return NULL;
			path_len = chomp_trailing_dir_sep(path, path_len);
			suffix_len = chomp_trailing_dir_sep(suffix, suffix_len);
		}
		else if (path[--path_len] != suffix[--suffix_len])
			return NULL;
	}

	if (path_len && !is_dir_sep(path[path_len - 1]))
		return NULL;
	return xstrndup(path, chomp_trailing_dir_sep(path, path_len));
}


text:
package org.objenesis.tck.features;

import java.io.Externalizable;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.io.Serializable;

import org.objenesis.Objenesis;

/**
 * {@code Externalizable} methods should not be called during instantiation.
 *
 * @author Henri Tremblay
 */
public class ReadExternalNotCalled extends AbstractFeature {

   public static class ReadExternalAndAll implements Serializable, Externalizable {
      @Override
      public void writeExternal(ObjectOutput out) {
         called.add("writeExternal");
      }

      @Override
      public void readExternal(ObjectInput in) {
         called.add("readExternal");
      }
   }

   @Override
   public boolean isCompliant(Objenesis objenesis) {
      objenesis.newInstance(ReadExternalAndAll.class);
      return called.isEmpty();
   }
}


text:
import os

from django.conf import settings
from django.core.validators import FileExtensionValidator
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver

def determine_upload_location(instance, filename):
    """
    Determine where files are going to be uploaded
    Args
      instance: Candidate user instance
      filename: filename of resumes being uploaded
    Return
      path of the resume
    """
    _, extension = os.path.splitext(filename)
    return os.path.join("resumes", instance.user.username + extension)

class Candidate(models.Model):
    LEVEL_CHOICES = (
        ("IN", "Intern"),
        ("NG", "New grad"),
        ("CL", "Career level"),
        ("SR", "Senior"),
        ("PR", "Principal"),
    )
    STATUS_CHOICES = (
        ("NEW", "New"),
        ("PHO", "Phone Screening"),
        ("ON", "Onsite Interview"),
        ("OF", "Offer"),
        ("CL", "Closed"),
        ("AC", "Accepted"),
    )

    user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    level = models.CharField(max_length=3, choices=LEVEL_CHOICES, blank=True, null=True)
    status = models.CharField(max_length=3, choices=STATUS_CHOICES, default="NEW")
    phone = models.CharField(max_length=50)
    referrer = models.CharField(max_length=100, blank=True, null=True)

    resume = models.FileField(blank=True,
                              null=True,
                              upload_to=determine_upload_location,
                              validators=[FileExtensionValidator(['pdf', 'txt', 'doc', 'docx'])])
    resume_url = models.URLField(blank=True, null=True)
    website = models.URLField(blank=True, null=True)

    def __str__(self):
        return self.name()

    def name(self):
        n = []
        if self.user.first_name: n.append( self.user.first_name )
        if self.user.last_name: n.append( self.user.last_name )
        return " ".join(n) if n else str(self.user)

@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_user_candidate(sender, instance, created, **kwargs):
    if created:
        Candidate.objects.create(user=instance)


text:
package gedi.riboseq.visu;

import gedi.core.data.mapper.GenomicRegionDataMapper;
import gedi.core.data.mapper.GenomicRegionDataMapping;
import gedi.core.data.reads.AlignedReadsData;
import gedi.core.data.reads.ConditionMappedAlignedReadsData;
import gedi.core.data.reads.ContrastMapping;
import gedi.core.data.reads.ReadCountMode;
import gedi.core.reference.ReferenceSequence;
import gedi.core.reference.Strand;
import gedi.core.region.ArrayGenomicRegion;
import gedi.core.region.GenomicRegion;
import gedi.core.region.MutableReferenceGenomicRegion;
import gedi.core.region.ReferenceGenomicRegion;
import gedi.gui.genovis.pixelMapping.PixelBlockToValuesMap;
import gedi.gui.genovis.pixelMapping.PixelLocationMapping;
import gedi.gui.genovis.pixelMapping.PixelLocationMappingBlock;
import gedi.riboseq.cleavage.RiboModel;
import gedi.riboseq.cleavage.SimpleCodonModel;
import gedi.riboseq.inference.codon.Codon;
import gedi.riboseq.inference.codon.CodonInference;
import gedi.riboseq.utils.RiboUtils;
import gedi.util.ArrayUtils;
import gedi.util.StringUtils;
import gedi.util.datastructure.array.DoubleArray;
import gedi.util.datastructure.array.NumericArray;
import gedi.util.datastructure.array.NumericArray.NumericArrayType;
import gedi.util.datastructure.collections.doublecollections.DoubleArrayList;
import gedi.util.datastructure.collections.intcollections.IntArrayList;
import gedi.util.datastructure.tree.redblacktree.IntervalTree;
import gedi.util.functions.EI;
import gedi.util.math.optim.NNLS;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.function.Supplier;

import cern.colt.matrix.DoubleMatrix1D;
import cern.colt.matrix.DoubleMatrix2D;
import cern.colt.matrix.impl.DenseDoubleMatrix1D;
import cern.colt.matrix.impl.DenseDoubleMatrix2D;
import cern.colt.matrix.impl.SparseDoubleMatrix2D;
import cern.colt.matrix.linalg.CholeskyDecomposition;

@GenomicRegionDataMapping(fromType=PixelBlockToValuesMap.class,toType=PixelBlockToValuesMap.class)
public class ToFramesTransformer implements GenomicRegionDataMapper<PixelBlockToValuesMap,PixelBlockToValuesMap> {

	private Strand fixedStrand;

	public ToFramesTransformer(Strand strand) throws IOException {
		this.fixedStrand = strand;
	}

	public PixelBlockToValuesMap map(ReferenceSequence reference,
			GenomicRegion region, PixelLocationMapping pixelMapping,
			PixelBlockToValuesMap data) {

		if (data.size()==0) return new PixelBlockToValuesMap(pixelMapping, 0, NumericArrayType.Double);

		Strand strand = fixedStrand;
		if (strand==null && reference.getStrand()==Strand.Independent)
			throw new RuntimeException("Set fixed strand!");

		if (strand==null) strand = reference.getStrand();

		PixelBlockToValuesMap re = new PixelBlockToValuesMap(data.getBlocks(), 3, NumericArrayType.Double);

		for (int i=0; i<data.size(); i++) {
			PixelLocationMappingBlock b = data.getBlock(i);
			for (int f=0; f<3; f++) {
				double val = data.getValues(i).getDouble(f);
				if (val>0) {
					if (b.getBasePairs()==1) {
						for (int o=0; o<3 && i+o<re.size(); o++)
							re.getValues(i+o).setDouble(f, val);
					} else {
						int stop = re.getBlockIndex(reference, b.getStopBp()+2);
						for (int o=i; o<=stop; o++)
							re.getValues(o).setDouble(f, val);
					}
				}
			}
		}

		return re;

	}

}


text:
package space.dotcat.assistant.content;

import android.arch.persistence.room.ColumnInfo;
import android.arch.persistence.room.Entity;
import android.arch.persistence.room.Ignore;
import android.support.annotation.NonNull;

import java.util.List;

@Entity(tableName = "Binary_Sensors")
public class BinarySensor extends ValueSensor {

    @ColumnInfo(name = "thing_is_active")
    private Boolean mIsActive;

    @Ignore
    public BinarySensor() {
    }

    public BinarySensor(@NonNull String id, @NonNull List<String> capabilities, @NonNull List<String> commands,
                        @NonNull Boolean isAvailable, @NonNull Boolean isEnabled, @NonNull String placement,
                        @NonNull String type, @NonNull String friendlyName, @NonNull String value, @NonNull Boolean isActive) {
        super(id, capabilities, commands, isAvailable, isEnabled, placement, type, friendlyName, value);

        mIsActive = isActive;
    }

    public Boolean getIsActive() {
        return mIsActive;
    }

    public void setActive(Boolean active) {
        mIsActive = active;
    }
}


text:
.. NBA Advanced Statistics and Analytics documentation master file, created by
   sphinx-quickstart on Wed Dec  3 14:12:15 2014.
   You can adapt this file completely to your liking, but it should at least
   contain the root `toctree` directive.

Welcome to NBA Advanced Statistics and Analytics's documentation!
=================================================================

Contents:

.. toctree::
   :maxdepth: 2

   installation
   web_scraping

Indices and tables
==================

* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`


text:
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Client</title>


text:
package com.github.cxfplus.com.sun.xml.bind.v2.runtime.output;

import java.io.IOException;
import java.lang.reflect.Constructor;

import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;

import com.github.cxfplus.com.sun.xml.bind.v2.runtime.JAXBContextImpl;
import com.github.cxfplus.com.sun.xml.bind.v2.runtime.MarshallerImpl;
import com.github.cxfplus.com.sun.xml.bind.v2.runtime.XMLSerializer;
import com.github.cxfplus.com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl;

import org.xml.sax.SAXException;

/**
 * {@link XmlOutput} that writes to StAX {@link XMLStreamWriter}.
 * <p>
 * TODO:
 * Finding the optimized FI implementations is a bit hacky and not very
 * extensible. Can we use the service provider mechnism in general for
 * concrete implementations of XmlOutputAbstractImpl.
 *
 * @author Kohsuke Kawaguchi
 */
public class XMLStreamWriterOutput extends XmlOutputAbstractImpl {

    /**
     * Creates a new {@link XmlOutput} from a {@link XMLStreamWriter}.
     * This method recognizes an FI StAX writer.
     */
    public static XmlOutput create(XMLStreamWriter out, JAXBContextImpl context) {
        // try optimized path
        final Class writerClass = out.getClass();
        if (writerClass==FI_STAX_WRITER_CLASS) {
            try {
                return FI_OUTPUT_CTOR.newInstance(out, context);
            } catch (Exception e) {
            }
        }
        if (STAXEX_WRITER_CLASS!=null && STAXEX_WRITER_CLASS.isAssignableFrom(writerClass)) {
            try {
                return STAXEX_OUTPUT_CTOR.newInstance(out);
            } catch (Exception e) {
            }
        }

        // otherwise the normal writer.
        return new XMLStreamWriterOutput(out);
    }

    private final XMLStreamWriter out;

    protected final char[] buf = new char[256];

    protected XMLStreamWriterOutput(XMLStreamWriter out) {
        this.out = out;
    }

    // not called if we are generating fragments
    public void startDocument(XMLSerializer serializer, boolean fragment, int[] nsUriIndex2prefixIndex, NamespaceContextImpl nsContext) throws IOException, SAXException, XMLStreamException {
        super.startDocument(serializer, fragment,nsUriIndex2prefixIndex,nsContext);
        if(!fragment)
            out.writeStartDocument();
    }

    public void endDocument(boolean fragment) throws IOException, SAXException, XMLStreamException {
        if(!fragment) {
            out.writeEndDocument();
            out.flush();
        }
        super.endDocument(fragment);
    }

    public void beginStartTag(int prefix, String localName) throws IOException, XMLStreamException {
        out.writeStartElement(
            nsContext.getPrefix(prefix),
            localName,
            nsContext.getNamespaceURI(prefix));

        NamespaceContextImpl.Element nse = nsContext.getCurrent();
        if(nse.count()>0) {
            for( int i=nse.count()-1; i>=0; i-- ) {
                String uri = nse.getNsUri(i);
                if(uri.length()==0 && nse.getBase()==1)
                    continue;   // no point in definint xmlns='' on the root
                out.writeNamespace(nse.getPrefix(i),uri);
            }
        }
    }

    public void attribute(int prefix, String localName, String value) throws IOException, XMLStreamException {
        if(prefix==-1)
            out.writeAttribute(localName,value);
        else
            out.writeAttribute(
                    nsContext.getPrefix(prefix),
                    nsContext.getNamespaceURI(prefix),
                    localName, value);
    }

    public void endStartTag() throws IOException, SAXException {
        // noop
    }

    public void endTag(int prefix, String localName) throws IOException, SAXException, XMLStreamException {
        out.writeEndElement();
    }

    public void text(String value, boolean needsSeparatingWhitespace) throws IOException, SAXException, XMLStreamException {
        if(needsSeparatingWhitespace)
            out.writeCharacters(" ");
        out.writeCharacters(value);
    }

    public void text(Pcdata value, boolean needsSeparatingWhitespace) throws IOException, SAXException, XMLStreamException {
        if(needsSeparatingWhitespace)
            out.writeCharacters(" ");

        int len = value.length();
        if(len <buf.length) {
            value.writeTo(buf,0);
            out.writeCharacters(buf,0,len);
        } else {
            out.writeCharacters(value.toString());
        }
    }

    /**
     * Reference to FI's XMLStreamWriter class, if FI can be loaded.
     */
    private static final Class FI_STAX_WRITER_CLASS = initFIStAXWriterClass();
    private static final Constructor<? extends XmlOutput> FI_OUTPUT_CTOR = initFastInfosetOutputClass();

    private static Class initFIStAXWriterClass() {
        try {
            Class llfisw = Class.forName(
                    "org.jvnet.fastinfoset.stax.LowLevelFastInfosetStreamWriter", true, MarshallerImpl.class.getClassLoader());
            Class sds = MarshallerImpl.class.getClassLoader().
                    loadClass("com.sun.xml.fastinfoset.stax.StAXDocumentSerializer");
            // Check if StAXDocumentSerializer implements LowLevelFastInfosetStreamWriter
            if (llfisw.isAssignableFrom(sds))
                return sds;
            else
                return null;
        } catch (Throwable e) {
            return null;
        }
    }

    private static Constructor<? extends XmlOutput> initFastInfosetOutputClass() {
        try {
            if (FI_STAX_WRITER_CLASS == null)
                return null;

            Class c = Class.forName(
                    "com.sun.xml.bind.v2.runtime.output.FastInfosetStreamWriterOutput", true,
                    UnmarshallerImpl.class.getClassLoader());
            return c.getConstructor(FI_STAX_WRITER_CLASS, JAXBContextImpl.class);
        } catch (Throwable e) {
            return null;
        }
    }

    //
    // StAX-ex
    //
    private static final Class STAXEX_WRITER_CLASS = initStAXExWriterClass();
    private static final Constructor<? extends XmlOutput> STAXEX_OUTPUT_CTOR = initStAXExOutputClass();

    private static Class initStAXExWriterClass() {
        try {
            return Class.forName("org.jvnet.staxex.XMLStreamWriterEx",true,MarshallerImpl.class.getClassLoader());
        } catch (Throwable e) {
            return null;
        }
    }

    private static Constructor<? extends XmlOutput> initStAXExOutputClass() {
        try {
            Class c = Class.forName("com.sun.xml.bind.v2.runtime.output.StAXExStreamWriterOutput",true, UnmarshallerImpl.class.getClassLoader());
            return c.getConstructor(STAXEX_WRITER_CLASS);
        } catch (Throwable e) {
            return null;
        }
    }
}


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ElectricCurrent.cs" company="QuantityTypes">
//   Copyright (c) 2014 QuantityTypes contributors
// </copyright>
// <summary>
//   Implements operators related to electric current.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace QuantityTypes
{
    /// <summary>
    ///     Implements operators related to electric current.
    /// </summary>
    public partial struct ElectricCurrent
    {
        /// <summary>
        ///     Implements the operator *.
        /// </summary>
        /// <param name="x"> The x. </param>
        /// <param name="y"> The y. </param>
        /// <returns> The result of the operator. </returns>
        public static ElectricCharge operator *(ElectricCurrent x, Time y)
        {
            return new ElectricCharge(x.Value * y.Value);
        }

        /// <summary>
        ///     Implements the operator *.
        /// </summary>
        /// <param name="x"> The x. </param>
        /// <param name="y"> The y. </param>
        /// <returns> The result of the operator. </returns>
        public static Power operator *(ElectricCurrent x, ElectricVoltage y)
        {
            return new Power(x.Value * y.Value);
        }

        /// <summary>
        ///     Implements the operator *.
        /// </summary>
        /// <param name="x"> The x. </param>
        /// <param name="y"> The y. </param>
        /// <returns> The result of the operator. </returns>
        public static ElectricVoltage operator *(ElectricCurrent x, ElectricResistance y)
        {
            return new ElectricVoltage(x.Value * y.Value);
        }
    }
}


text:
<project name="touchtestmodule" default="dist">
	<description>
		Ant build script for Titanium Android module touchtestmodule
	</description>

	<property name="ti.module.root" location="${basedir}"/>
	<property file="build.properties" />

	<import file="${titanium.platform}/../module/android/build.xml"/>
</project>


text:
package org.drools.planner.core.localsearch.event;

import org.drools.planner.core.localsearch.scope.LocalSearchSolverPhaseScope;
import org.drools.planner.core.localsearch.scope.LocalSearchStepScope;
import org.drools.planner.core.solver.event.SolverLifecycleListener;

public interface LocalSearchSolverPhaseLifecycleListener extends SolverLifecycleListener {

    void phaseStarted(LocalSearchSolverPhaseScope localSearchSolverPhaseScope);

    void stepStarted(LocalSearchStepScope localSearchStepScope);

    void stepEnded(LocalSearchStepScope localSearchStepScope);

    void phaseEnded(LocalSearchSolverPhaseScope localSearchSolverPhaseScope);

}


text:
<?php

namespace Doctrine\Tests\Common\Proxy;

final class FinalClass
{
}


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

namespace TrelloMailer.Core.TemplateEngiens
{
    public class RazorTempate : ITemplateEngine
    {
        public string Render(string template, List<TrelloNet.Board> bords)
        {
            return string.Empty;
        }
    }
}


text:
/*
   ARPACK++ v1.2 2/20/2000
   c++ interface to ARPACK code.

   MODULE ceupp.h.
   Interface to ARPACK subroutines zneupd and cneupd.

   ARPACK Authors
      Richard Lehoucq
      Danny Sorensen
      Chao Yang
      Dept. of Computational & Applied Mathematics
      Rice University
      Houston, Texas
*/

#ifndef CEUPP_H
#define CEUPP_H

#include <cstddef>
#include <string>
#include "arch.h"
#include "arpackf.h"

inline void ceupp(bool rvec, char HowMny, arcomplex<double> d[],
                  arcomplex<double> Z[], ARint ldz, arcomplex<double> sigma,
                  arcomplex<double> workev[], char bmat, ARint n, const std::string& which,
                  ARint nev, double tol, arcomplex<double> resid[], ARint ncv,
                  arcomplex<double> V[], ARint ldv, ARint iparam[],
                  ARint ipntr[], arcomplex<double> workd[],
                  arcomplex<double> workl[], ARint lworkl, double rwork[],
                  ARint& info)

/*
  c++ version of ARPACK routine zneupd.
  This subroutine returns the converged approximations to eigenvalues
  of A*z = lambda*B*z and (optionally):

  (1) the corresponding approximate eigenvectors,
  (2) an orthonormal basis for the associated approximate
      invariant subspace,

  There is negligible additional cost to obtain eigenvectors. An
  orthonormal basis is always computed.  There is an additional storage cost
  of n*nev if both are requested (in this case a separate array Z must be
  supplied).
  The approximate eigenvalues and eigenvectors of  A*z = lambda*B*z
  are derived from approximate eigenvalues and eigenvectors of
  of the linear operator OP prescribed by the MODE selection in the
  call to caupp. caupp must be called before this routine is called.
  These approximate eigenvalues and vectors are commonly called Ritz
  values and Ritz vectors respectively.  They are referred to as such
  in the comments that follow.  The computed orthonormal basis for the
  invariant subspace corresponding to these Ritz values is referred to
  as a Schur basis.
  See documentation in the header of the subroutine caupp for
  definition of OP as well as other terms and the relation of computed
  Ritz values and Ritz vectors of OP with respect to the given problem
  A*z = lambda*B*z.  For a brief description, see definitions of
  iparam[7], MODE and which in the documentation of caupp.

  Parameters:

    rvec    (Input) Specifies whether a basis for the invariant subspace
            corresponding to the converged Ritz value approximations for
            the eigenproblem A*z = lambda*B*z is computed.
            rvec = false: Compute Ritz values only.
            rvec = true : Compute the Ritz vectors or Schur vectors.
                          See Remarks below.
    HowMny  (Input) Specifies the form of the basis for the invariant
            subspace corresponding to the converged Ritz values that
            is to be computed.
            = 'A': Compute nev Ritz vectors;
            = 'P': Compute nev Schur vectors;
    d       (Output) Array of dimension nev+1. D contains the  Ritz
            approximations to the eigenvalues lambda for A*z = lambda*B*z.
    Z       (Output) Array of dimension nev*n. If rvec = TRUE. and
            HowMny = 'A', then Z contains approximate eigenvectors (Ritz
            vectors) corresponding to the NCONV=iparam[5] Ritz values for
            eigensystem A*z = lambda*B*z.
            If rvec = .FALSE. or HowMny = 'P', then Z is not referenced.
            NOTE: If if rvec = .TRUE. and a Schur basis is not required,
                  the array Z may be set equal to first nev+1 columns of
                  the Arnoldi basis array V computed by caupp.  In this
                  case the Arnoldi basis will be destroyed and overwritten
                  with the eigenvector basis.
    ldz     (Input) Dimension of the vectors contained in Z. This
            parameter MUST be set to n.
    sigma   (Input) If iparam[7] = 3, sigma represents the shift. Not
            referenced if iparam[7] = 1 or 2.
    workv   (Workspace) Array of dimension 2*ncv.
    V       (Input/Output) Array of dimension n*ncv+1.
            Upon Input: V contains the ncv vectors of the Arnoldi basis
                        for OP as constructed by caupp.
            Upon Output: If rvec = TRUE the first NCONV=iparam[5] columns
                        contain approximate Schur vectors that span the
                        desired invariant subspace.
            NOTE: If the array Z has been set equal to first nev+1 columns
                  of the array V and rvec = TRUE. and HowMny = 'A', then
                  the Arnoldi basis held by V has been overwritten by the
                  desired Ritz vectors.  If a separate array Z has been
                  passed then the first NCONV=iparam[5] columns of V will
                  contain approximate Schur vectors that span the desired
                  invariant subspace.
    workl   (Input / Output) Array of length lworkl+1.
            workl[1:ncv*ncv+3*ncv] contains information obtained in
            caupp. They are not changed by ceupp.
            workl[ncv*ncv+3*ncv+1:3*ncv*ncv+4*ncv] holds the untransformed
            Ritz values, the untransformed error estimates of the Ritz
            values, the upper triangular matrix for H, and the associated
            matrix representation of the invariant subspace for H.
    ipntr   (Input / Output) Array of length 14. Pointer to mark the
            starting locations in the workl array for matrices/vectors
            used by caupp and ceupp.
            ipntr[9]:  pointer to the ncv RITZ values of the original
                       system.
            ipntr[11]: pointer to the ncv corresponding error estimates.
            ipntr[12]: pointer to the ncv by ncv upper triangular
                       Schur matrix for H.
            ipntr[13]: pointer to the ncv by ncv matrix of eigenvectors
                       of the upper Hessenberg matrix H. Only referenced
                       by ceupp if rvec = TRUE. See Remark 2 below.
    info    (Output) Error flag.
            =  0 : Normal exit.
            =  1 : The Schur form computed by LAPACK routine csheqr
                   could not be reordered by LAPACK routine ztrsen.
                   Re-enter subroutine ceupp with iparam[5] = ncv and
                   increase the size of the array D to have
                   dimension at least dimension ncv and allocate at least
                   ncv columns for Z. NOTE: Not necessary if Z and V share
                   the same space. Please notify the authors if this error
                   occurs.
            = -1 : n must be positive.
            = -2 : nev must be positive.
            = -3 : ncv must satisfy nev+1 <= ncv <= n.
            = -5 : which must be one of 'LM','SM','LR','SR','LI','SI'.
            = -6 : bmat must be one of 'I' or 'G'.
            = -7 : Length of private work workl array is not sufficient.
            = -8 : Error return from LAPACK eigenvalue calculation.
                   This should never happened.
            = -9 : Error return from calculation of eigenvectors.
                   Informational error from LAPACK routine ztrevc.
            = -10: iparam[7] must be 1, 2 or 3.
            = -11: iparam[7] = 1 and bmat = 'G' are incompatible.
            = -12: HowMny = 'S' not yet implemented.
            = -13: HowMny must be one of 'A' or 'P' if rvec = TRUE.
            = -14: caupp did not find any eigenvalues to sufficient
                   accuracy.

  NOTE:     The following arguments

            bmat, n, which, nev, tol, resid, ncv, V, ldv, iparam,
            ipntr, workd, workl, lworkl, rwork, info

            must be passed directly to ceupp following the last call
            to caupp.  These arguments MUST NOT BE MODIFIED between
            the the last call to caupp and the call to ceupp.

  Remarks
    1. Currently only HowMny = 'A' and 'P' are implemented.
    2. Schur vectors are an orthogonal representation for the basis of
       Ritz vectors. Thus, their numerical properties are often superior.
       Let X' denote the transpose of X. If rvec = .TRUE. then the
       relationship A * V[:,1:iparam[5]] = V[:,1:iparam[5]] * T, and
       V[:,1:iparam[5]]' * V[:,1:iparam[5]] = I are approximately satisfied.
       Here T is the leading submatrix of order iparam[5] of the real
       upper quasi-triangular matrix stored workl[ipntr[12]].
*/

{

  ARint              irvec;
  ARlogical*         iselect;
  arcomplex<double>* iZ;

  irvec   = (ARint) rvec;
  iselect = new ARlogical[ncv];
  iZ = (Z == NULL) ? &V[1] : Z;

  F77NAME(zneupd)(&irvec, &HowMny, iselect, d, iZ, &ldz, &sigma,
                  &workev[1], &bmat, &n, which.c_str(), &nev, &tol, resid,
                  &ncv, &V[1], &ldv, &iparam[1], &ipntr[1],
                  &workd[1], &workl[1], &lworkl, &rwork[1], &info);

  delete[] iselect;

} // ceupp (arcomplex<double>).

inline void ceupp(bool rvec, char HowMny, arcomplex<float> d[],
                  arcomplex<float> Z[], ARint ldz, arcomplex<float> sigma,
                  arcomplex<float> workev[], char bmat, ARint n, const std::string& which,
                  ARint nev, float tol, arcomplex<float> resid[], ARint ncv,
                  arcomplex<float> V[], ARint ldv, ARint iparam[],
                  ARint ipntr[], arcomplex<float> workd[],
                  arcomplex<float> workl[], ARint lworkl, float rwork[],
                  ARint& info)

/*
  c++ version of ARPACK routine cneupd. The only difference between
  cneupd and zneupd is that in the former function all vectors have
  single precision elements and in the latter all vectors have double
  precision elements.
*/

{

  ARint             irvec;
  ARlogical*        iselect;
  arcomplex<float>* iZ;

  irvec   = (ARint) rvec;
  iselect = new ARlogical[ncv];
  iZ = (Z == NULL) ? &V[1] : Z;

  F77NAME(cneupd)(&irvec, &HowMny, iselect, d, iZ, &ldz, &sigma,
                  &workev[1], &bmat, &n, which.c_str(), &nev, &tol, resid,
                  &ncv, &V[1], &ldv, &iparam[1], &ipntr[1],
                  &workd[1], &workl[1], &lworkl, &rwork[1], &info);

  delete[] iselect;

} // ceupp (arcomplex<float>).

#endif // CEUPP_H


text:
<?php

namespace Phine\Bundles\BuiltIn\Modules\Frontend;

use Phine\Bundles\Core\Logic\Module\FrontendForm;
use Phine\Bundles\BuiltIn\Modules\Backend\ChangePasswordForm;
use Phine\Framework\FormElements\Fields\Input;
use App\Phine\Database\Core\MemberChangeRequest;
use Phine\Framework\System\Date;
use Phine\Bundles\Core\Logic\DBEnums\ChangeRequestPurpose;
use App\Phine\Database\BuiltIn\ContentChangePassword;
use Phine\Bundles\BuiltIn\Logic\ChangeRequest\Confirmer;
use App\Phine\Database\Access;
use App\Phine\Database\Core\Member;
use Phine\Framework\Validation\DatabaseCount;
use Phine\Framework\System\Str;
use Phine\Framework\System\IO\Path;
use Phine\Bundles\Core\Logic\Util\PathUtil;
use Phine\Bundles\BuiltIn\Logic\HtmlTemplating\TemplateParser;
use Phine\Framework\System\Http\Response;
use Phine\Bundles\Core\Logic\Routing\FrontendRouter;
use PHPMailer\PHPMailer\PHPMailer;
class ChangePassword extends FrontendForm
{

    private $changePassword;

    protected function Init()
    {

        $this->changePassword = ContentChangePassword::Schema()->ByContent($this->Content());
        $this->AddNameField();
        $this->AddUniqueSubmit('ChangePasswordSubmit');
        return parent::Init();
    }

    private function AddNameField()
    {
        $name = 'Name';
        $this->AddField(Input::Text($name));
        $this->SetRequired($name);
        $this->AddValidator($name, $this->DBValidator());
    }

    private function DBValidator()
    {
        $sql = Access::SqlBuilder();
        $tblMember = Member::Schema()->Table();
        $where = $sql->Equals($tblMember->Field('Name'), $sql->Placeholder())
                ->Or_($sql->Equals($tblMember->Field('EMail'), $sql->Placeholder()));

        $what = $sql->SelectList($sql->FunctionCount(array($tblMember->Field('ID'))));
        $select = $sql->Select(false, $what, $tblMember, $where);
        $validator = DatabaseCount::UniqueExists($select);
        $validator->SetNumPlaceholders(2);
        return $validator;
    }

    protected function OnSuccess()
    {
        $changeRequest = new MemberChangeRequest();
        $member = Member::Schema()->ByEMail($this->Value('Name'));
        if (!$member) {
            $member = Member::Schema()->ByName($this->Value('Name'));
        }
        $changeRequest->SetMember($member);
        $changeRequest->SetMailSent(Date::Now());
        $changeRequest->SetPurpose((string) ChangeRequestPurpose::NewPassword());
        $changeRequest->SetNewValue('');
        $salt = Str::Start(md5(uniqid(microtime())), 16);
        $changeRequest->SetMailSalt($salt);
        $changeRequest->Save();
        $this->SendConfirmMail($changeRequest);
        if ($this->changePassword->GetNextUrl()){
            Response::Redirect(FrontendRouter::Url($this->changePassword->GetNextUrl()));
        }
    }

    private function SendConfirmMail(MemberChangeRequest $changeRequest)
    {
        $mailer = new PHPMailer(true);
        $mailer->From = $this->changePassword->GetMailFrom();
        $mailer->Subject = $this->changePassword->GetMailSubject();
        $mailer->addAddress($changeRequest->GetMember()->GetEMail());
        $mailer->msgHTML($this->GetConfirmMessage($changeRequest));
        $mailer->send();
    }

    private function GetConfirmMessage(MemberChangeRequest $changeRequest)
    {
        $replacements = array();
        $replacements['Text1'] = $this->changePassword->GetMailText1();
        $replacements['Text2'] = $this->changePassword->GetMailText2();
        $replacements['Title'] = Html($this->changePassword->GetMailSubject());
        $replacements['Styles'] = Html($this->changePassword->GetMailStyles());
        $confirmUrl = $this->changePassword->GetConfirmUrl();
        if ($confirmUrl) {
            $replacements['ConfirmUrl'] = Html(Confirmer::CalcUrl($changeRequest, $confirmUrl));
        }
        $template = Path::Combine(PathUtil::BundleFolder($this->MyBundle()), 'MailTemplates/Confirm.phtml');
        $parser = new TemplateParser($replacements);
        return $parser->Parse($template);
    }

    public function AllowChildren()
    {
        return false;
    }

    public function ContentForm()
    {
        return new ChangePasswordForm();
    }

    public function AllowCustomTemplates()
    {
        return true;
    }

}


text:
/* global it expect jest */

import authenticate from '../authenticate';

const stubBase = () => ({
  onAuth: cb => cb({ uid: 'xyz' }),
  auth: () => ({ signInAnonymously: cb => cb({ uid: 'xyz' }) })
});

it('creates a new visitor', () => {
  const base = stubBase();
  const promise = Promise.resolve({ uid: 'xyz' });

  base.onAuth = jest.fn(cb => cb(null));

  base.auth = jest.fn().mockReturnValue({
    signInAnonymously: () => promise
  });

  authenticate(base, ({ uid }) => {
    expect(uid).toEqual('xyz');
  });

  expect(base.onAuth).toHaveBeenCalled();
  expect(base.auth).toHaveBeenCalled();

  return promise.then(({ uid }) => expect(uid).toEqual('xyz'));
});

it('signs in an existing visitor', () => {
  const base = stubBase();

  base.onAuth = jest.fn(cb => cb({ uid: 'xyz' }));
  base.auth = jest.fn();

  authenticate(base, ({ uid }) => {
    expect(uid).toEqual('xyz');
  });

  expect(base.onAuth).toHaveBeenCalled();
  expect(base.auth).not.toHaveBeenCalled();
});


text:
namespace Tavis.OpenApi
{
    using SharpYaml.Serialization;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using Tavis.OpenApi.Model;

    /// <summary>
    /// Service class for converting strings or streams into OpenApiDocument instances
    /// </summary>
    public class OpenApiParser
    {
        public static ParsingContext Parse(string document)
        {
            var ms = new MemoryStream();
            var writer = new StreamWriter(ms);
            writer.Write(document);
            writer.Flush();
            ms.Position = 0;
            return Parse(ms);
        }

        public static ParsingContext Parse(Stream stream)
        {
            RootNode rootNode;
            var context = new ParsingContext();
            try
            {
                var yamlStream = new YamlStream();
                yamlStream.Load(new StreamReader(stream));

                var yamlDocument = yamlStream.Documents.First();
                rootNode = new RootNode(context, yamlDocument);

            }
            catch (SharpYaml.SyntaxErrorException ex)
            {
                context.ParseErrors.Add(new OpenApiError("", ex.Message));
                context.OpenApiDocument = new OpenApiDocument();  // Could leave this null?
                return context;
            }

            var inputVersion = GetVersion(rootNode);

            switch (inputVersion)
            {
                case "2.0":
                    context.SetReferenceService(new ReferenceService(rootNode)
                    {
                        loadReference = OpenApiV2Reader.LoadReference,
                        parseReference = p => OpenApiV2Reader.ParseReference(p)
                    });
                    context.OpenApiDocument = OpenApiV2Reader.LoadOpenApi(rootNode);
                    break;
               default:
                    context.SetReferenceService(new ReferenceService(rootNode)
                    {
                        loadReference = OpenApiV3Reader.LoadReference,
                        parseReference = p => new OpenApiReference(p)
                    });
                    context.OpenApiDocument = OpenApiV3Reader.LoadOpenApi(rootNode);
                    break;
            }
            return context;
        }

        private static string GetVersion(RootNode rootNode)
        {
            var versionNode = rootNode.Find(new JsonPointer("/openapi"));
            if (versionNode != null)
            {
                return versionNode.GetScalarValue();
            }

            versionNode = rootNode.Find(new JsonPointer("/swagger"));
            if (versionNode != null)
            {
                return versionNode.GetScalarValue();
            }
            return null;
        }

    }
}


text:
file_cache_path "/vagrant/chef-sylius/cache"
cookbook_path "/vagrant/chef-sylius/cookbooks"


text:
<!doctype html>

  <title>Paged List</title>
  <link rel="canonical" href="https://example.com/advanced/paged_list/">

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,minimum-scale=1,initial-scale=1">

  <amp-list class="paged-amp-list"
            layout="fixed-height"
            height="720"
            src="/advanced/paged_list/search"
            [src]="'/advanced/paged_list/search?page=' + pageNumber"
            binding="no"
            reset-on-refresh
            single-item>
            <template type="amp-mustache">

Page {{currentPage}} of {{pageCount}}

                {{#products}}

                  <amp-img layout="responsive" class="image" width="320" height="240" src="{{image}}"></amp-img>
                  {{title}}

{{copy}}

                {{/products}}

            </template>

              <button>Show more</button>

  </amp-list>

    <button class="prev"
            hidden
            [hidden]="pageNumber < 2"
            on="tap: AMP.setState({ pageNumber: pageNumber - 1 })">
      Previous
    </button>
    <button class="next"
            [hidden]="page ? pageNumber >= page.items.pageCount : false"
            on="tap: AMP.setState({ pageNumber: pageNumber ? pageNumber + 1 : 2 })">
      Next
    </button>

  <amp-state id="page"
             src="/advanced/paged_list/search"
             [src]="'/advanced/paged_list/search?page=' + pageNumber">
  </amp-state>


text:
require "spec_helper"

module BoardGameGeek
  module Result
    class ResultItem
      describe ItemAttribute do
        subject do
          ItemAttribute.new :@name => "image",
                            :value => "5",
                            :type => "primary",
                            :@children => ["some text value"]
        end

        its(:name) { is_expected.to eq("image") }
        its(:text_value) { is_expected.to eq("some text value") }
        its(:value) { is_expected.to eq("5") }
        its(:type) { is_expected.to eq("primary") }
      end
    end
  end
end


text:
[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(WebFormsExam.Web.App_Start.NinjectWeb), "Start")]

namespace WebFormsExam.Web.App_Start
{
    using Microsoft.Web.Infrastructure.DynamicModuleHelper;

    using Ninject.Web;

    public static class NinjectWeb
    {
        /// <summary>
        /// Starts the application
        /// </summary>
        public static void Start()
        {
            DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
        }
    }
}


text:
package org.hawkular.inventory.api.model;

import static org.assertj.core.api.Assertions.assertThat;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Optional;

import org.junit.Test;

/**
 * @author Joel Takvorian
 */
public class ResourceNodeTest {

    private static final ResourceType EAP = new ResourceType("EAP", new ArrayList<>(), new HashMap<>());
    private static final Metric METRIC1
            = new Metric("memory", "Memory", MetricUnit.BYTES, new HashMap<>());
    private static final Metric METRIC2
            = new Metric("gc", "GC", MetricUnit.NONE, new HashMap<>());

    private static final RawResource RAW = new RawResource("id", "name", "feedX", "EAP",
            null, Arrays.asList(METRIC1, METRIC2), new HashMap<>(), new HashMap<>());

    private static final RawResource CH1 = new RawResource("child-1", "name-1", "feedX", "t", "id",
            new ArrayList<>(), new HashMap<>(), new HashMap<>());
    private static final RawResource CH2 = new RawResource("child-2", "name-2", "feedX", "t", "id",
            new ArrayList<>(), new HashMap<>(), new HashMap<>());

    @Test
    public void shouldCreateFromRaw() {
        ResourceNode r = ResourceNode.fromRaw(RAW, id -> Optional.of(EAP), id -> {
            if (id.equals("id")) {
                return Arrays.asList(CH1, CH2);
            }
            return Collections.emptyList();
        });
        assertThat(r.getType().getId()).isEqualTo("EAP");
        assertThat(r.getMetrics()).extracting(Metric::getName).containsExactly("memory", "gc");
        assertThat(r.getChildren())
                .extracting(ResourceNode::getName)
                .containsExactly("name-1", "name-2");
    }
}


text:
// Main.cpp

#include "StdAfx.h"

#include "Common/MyInitGuid.h"

#include "Common/CommandLineParser.h"
#include "Common/StringConvert.h"

#include "Windows/DLL.h"
#include "Windows/Error.h"
#include "Windows/FileDir.h"
#include "Windows/FileName.h"
#include "Windows/NtCheck.h"
#include "Windows/ResourceString.h"

#include "../../ICoder.h"
#include "../../IPassword.h"
#include "../../Archive/IArchive.h"
#include "../../UI/Common/Extract.h"
#include "../../UI/Common/ExitCode.h"
#include "../../UI/Explorer/MyMessages.h"
#include "../../UI/GUI/ExtractGUI.h"
#include "../../UI/GUI/ExtractRes.h"

HINSTANCE g_hInstance;

#ifdef UNDER_CE
bool g_LVN_ITEMACTIVATE_Support = true;
#endif

static const wchar_t *kUnknownExceptionMessage = L"ERROR: Unknown Error!";

void ErrorMessageForHRESULT(HRESULT res)
{
  ShowErrorMessage(HResultToMessage(res));
}

int APIENTRY WinMain2()
{
  UString password;
  bool assumeYes = false;
  bool outputFolderDefined = false;
  UString outputFolder;
  UStringVector commandStrings;
  NCommandLineParser::SplitCommandLine(GetCommandLineW(), commandStrings);

  #ifndef UNDER_CE
  if (commandStrings.Size() > 0)
    commandStrings.Delete(0);
  #endif

  for (int i = 0; i < commandStrings.Size(); i++)
  {
    const UString &s = commandStrings[i];
    if (s.CompareNoCase(L"-y") == 0)
      assumeYes = true;
    else if (s.Left(2).CompareNoCase(L"-o") == 0)
    {
      outputFolder = s.Mid(2);
      NWindows::NFile::NName::NormalizeDirPathPrefix(outputFolder);
      outputFolderDefined = !outputFolder.IsEmpty();
    }
    else if (s.Left(2).CompareNoCase(L"-p") == 0)
    {
      password = s.Mid(2);
    }
  }

  UString path;
  NWindows::NDLL::MyGetModuleFileName(g_hInstance, path);

  UString fullPath;
  int fileNamePartStartIndex;
  if (!NWindows::NFile::NDirectory::MyGetFullPathName(path, fullPath, fileNamePartStartIndex))
  {
    ShowErrorMessage(L"Error 1329484");
    return 1;
  }

  CCodecs *codecs = new CCodecs;
  CMyComPtr<IUnknown> compressCodecsInfo = codecs;
  HRESULT result = codecs->Load();
  if (result != S_OK)
  {
    ErrorMessageForHRESULT(result);
    return 1;
  }

  // COpenCallbackGUI openCallback;

  // openCallback.PasswordIsDefined = !password.IsEmpty();
  // openCallback.Password = password;

  CExtractCallbackImp *ecs = new CExtractCallbackImp;
  CMyComPtr<IFolderArchiveExtractCallback> extractCallback = ecs;
  ecs->Init();

  #ifndef _NO_CRYPTO
  ecs->PasswordIsDefined = !password.IsEmpty();
  ecs->Password = password;
  #endif

  CExtractOptions eo;
  eo.OutputDir = outputFolderDefined ? outputFolder :
      fullPath.Left(fileNamePartStartIndex);
  eo.YesToAll = assumeYes;
  eo.OverwriteMode = assumeYes ?
      NExtract::NOverwriteMode::kWithoutPrompt :
      NExtract::NOverwriteMode::kAskBefore;
  eo.PathMode = NExtract::NPathMode::kFullPathnames;
  eo.TestMode = false;

  UStringVector v1, v2;
  v1.Add(fullPath);
  v2.Add(fullPath);
  NWildcard::CCensorNode wildcardCensor;
  wildcardCensor.AddItem(true, L"*", true, true, true);

  bool messageWasDisplayed = false;
  result = ExtractGUI(codecs, CIntVector(), v1, v2,
      wildcardCensor, eo, (assumeYes ? false: true), messageWasDisplayed, ecs);

  if (result == S_OK)
  {
    if (!ecs->IsOK())
      return NExitCode::kFatalError;
    return 0;
  }
  if (result == E_ABORT)
    return NExitCode::kUserBreak;
  if (!messageWasDisplayed)
  {
    if (result == S_FALSE)
      ShowErrorMessage(L"Error in archive");
    else
      ErrorMessageForHRESULT(result);
  }
  if (result == E_OUTOFMEMORY)
    return NExitCode::kMemoryError;
  return NExitCode::kFatalError;
}

#define NT_CHECK_FAIL_ACTION ShowErrorMessage(L"Unsupported Windows version"); return NExitCode::kFatalError;

int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE /* hPrevInstance */,
  #ifdef UNDER_CE
  LPWSTR
  #else
  LPSTR
  #endif
  /* lpCmdLine */, int /* nCmdShow */)
{
  g_hInstance = (HINSTANCE)hInstance;

  NT_CHECK

  try
  {
    return WinMain2();
  }
  catch(const CNewException &)
  {
    ErrorMessageForHRESULT(E_OUTOFMEMORY);
    return NExitCode::kMemoryError;
  }
  catch(...)
  {
    ShowErrorMessage(kUnknownExceptionMessage);
    return NExitCode::kFatalError;
  }
}


text:
package org.yarlithub.yschool.spreadSheetHandler;

/**
 * Created by jaykrish on 5/2/14.
 */
public interface Writer {
}


text:
<!doctype html>

	<title>jQuery UI Slider - Default functionality</title>
	<link type="text/css" href="../../themes/base/ui.all.css" rel="stylesheet" />

	<link type="text/css" href="../demos.css" rel="stylesheet" />

The basic slider is horizontal and has a single handle that can be moved with the mouse or by using the arrow keys.


text:
typedef Identified<
            Attributed<
                Labelled<
                    Positioned<
                        Styled<
                            UsecaseGraphNode > > > > > UsecaseNode;

typedef Identified<
            Labelled<
                Positioned<
                    Styled<
                        ActorGraphNode > > > > ActorNode;

typedef Identified<
            Attributed<
                Labelled<
                    Positioned<
                        Styled<
                            SubFlowGraphNode > > > > > SubFlowNode;

typedef Identified<
            Attributed<
                Labelled<
                    Positioned<
                        Styled<
                            AltFlowGraphNode > > > > > AltFlowNode;

typedef Identified<
            Attributed<
                Labelled<
                    Positioned<
                        Styled<
                            SecFlowGraphNode > > > > > SecFlowNode;

typedef Identified<
            Labelled<
                Positioned<
                    Styled<
                        SquareGraphNode > > > > SquareNode;

typedef Identified<
            Labelled<
                Positioned<
                    Styled<
                        RectangleGraphNode > > > > RectangleNode;

typedef Identified<
            Labelled<
                Positioned<
                    Styled<
                        CircleGraphNode > > > > CircleNode;

typedef Identified<
            Labelled<
                Positioned<
                    Styled<
                        TriangleGraphNode > > > > TriangleNode;

#endif // NODEDEFS_H


text:
                <?php
                  wp_nav_menu(array('menu' => 'Header Menu', 'menu_class' => 'nav nav-pills'));
                ?>

                <?php
                  get_template_part('templates/searchform');
                ?>

Social

Contact us

      <a class="navbar-brand hidden-xs" href="<?php echo home_url(); ?>/">
      <?php bloginfo('description'); ?>

     <button data-target=".nav-main" data-toggle="collapse" type="button" class="navbar-toggle">

    </button>
     <img class="hidden-xs pull-right strap img-responsive" src="<?php bloginfo('stylesheet_directory');?>/assets/img/strapline.gif" width="" height="" />

      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
        Toggle navigation

      </button>

      <?php
        if (has_nav_menu('primary_navigation')) :
          wp_nav_menu(array('theme_location' => 'primary_navigation', 'menu_class' => 'nav navbar-nav'));
        endif;
      ?>

            <a class="navbar-brand visible-xs" href="<?php echo home_url(); ?>/">
            <?php bloginfo('description'); ?>

                <img class="visible-xs mob-social" src="<?php bloginfo('stylesheet_directory');?>/assets/img/mobile-passion.gif" width="" height="" />

Linkedin

Facebook

Twitter

eMail

Feed

  <?php if (is_front_page()) : get_template_part('templates/page', 'hero'); endif; //VF hero placement?>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace TodoMvc
{
    // This class is used by the application to send Email and SMS when you turn on two-factor authentication in ASP.NET Identity.
    // For more details see this link http://go.microsoft.com/fwlink/?LinkID=532713
    public static class MessageServices
    {
        public static Task SendEmailAsync(string email, string subject, string message)
        {
            // Plug in your email service here to send an email.
            return Task.FromResult(0);
        }
        public static Task SendSmsAsync(string number, string message)
        {
            // Plug in your SMS service here to send a text message.
            return Task.FromResult(0);
        }
    }
}


text:
const path = require('path');

const match = '/*/integration.html';

async function handler(req, res) {
  const filePath = path.join(__dirname, '..', 'static', 'integration.html');
  res.sendFile(filePath);
}

module.exports = {
  handler,
  match,
};


text:
module IqRdf
  class Uri < Node

    attr_reader :namespace, :uri_postfix
    attr_reader :rdf_type

    def initialize(namespace, uri_postfix, rdf_type = nil, lang = nil)
      raise "rdf_type has to be an IqRdf::Uri" unless rdf_type.nil? || rdf_type.is_a?(IqRdf::Uri)
      @namespace = namespace
      @uri_postfix = uri_postfix
      @rdf_type = rdf_type
      super(lang)
    end

    def full_uri(parent_lang = nil)
      # URI::join etc won't work since uri_postfix has not to be a valid URI itself.
      "#{self.namespace.uri_prefix.to_s}#{self.uri_postfix.to_s}"
    end

    def to_s(parent_lang = nil)
      if namespace.token # There is a dummy_empty_namespace without token => postfix is a full uri!
        "#{namespace.turtle_token}:#{self.uri_postfix.to_s}"
      else
        "<#{self.uri_postfix.to_s}>"
      end
    end

    def is_subject?()
      if (nodes.size > 0) # walk through the nodes: a blank node is an object (but has nodes)
        nodes.each do |node|
          return true unless node.is_a?(BlankNode)
        end
      end
      return !rdf_type.nil?
    end

    def build_xml(xml, &block)
      if (is_subject?)
        attrs = {"rdf:about" => self.full_uri}
        attrs["xml:lang"] = self.lang if self.lang
        xml.rdf(:Description, attrs) do
          if self.rdf_type
            xml.rdf(:type, "rdf:resource" => self.rdf_type.full_uri)
          end
          self.nodes.each do |predicate|
            predicate.build_xml(xml)
          end
        end
      elsif block
        block.call("rdf:resource" => self.full_uri)
      end
    end

  end
end


text: export declare function rmdir(dir: string): Promise<void>;


text:
import type { CommonOffset, PlatformPointEvent } from "@akashic/pdi-types";
import * as pl from "@akashic/playlog";
import type { Camera } from "./Camera";
import type { PointSource } from "./entities/E";
import { EventPriority } from "./EventPriority";

/**
 * @ignore
 */
interface PointEventHolder {
	targetId?: number;
	local?: boolean;
	point: CommonOffset;
	start: CommonOffset;
	prev: CommonOffset;
	// TODO: タイムスタンプのようなものを入れて一定時間後にクリアする仕組みが必要かもしれない。
	//       pointUpをトリガに解放するので、pointUpを取り逃すとリークする(mapに溜まったままになってしまう)
}

export interface PointSourceResolver {
	findPointSource(point: CommonOffset, camera?: Camera): PointSource | undefined;
}

export interface PointEventResolverParameterObject {
	/**
	 * この `PointEventResolver` がエンティティの解決などに用いる `PointSourceResolver` 。
	 */
	sourceResolver: PointSourceResolver;

	/**
	 * プレイヤーID
	 */
	playerId: string;
}

/**
 * PlatformPointEventからg.Eventへの変換機構。
 *
 * ほぼ座標しか持たないPlatformPointEventに対して、g.Point(Down|Move|Up)Eventはその座標にあるエンティティや、
 * (g.Point(Move|Up)Eventの場合)g.PointDownEventからの座標の差分を持っている。
 * それらの足りない情報を管理・追加して、PlatformPointEventをg.Eventに変換するクラス。
 * Platform実装はpointDown()なしでpointMove()を呼び出してくることも考えられるため、
 * Down -> Move -> Up の流れを保証する機能も持つ。
 *
 * 本クラスのインスタンスをゲーム開発者が直接生成することはなく、ゲーム開発者が利用する必要もない。
 * @ignore
 */
export class PointEventResolver {
	_sourceResolver: PointSourceResolver;
	_playerId: string;

	// g.Eと関連した座標データ
	private _pointEventMap: { [key: number]: PointEventHolder } = {};

	constructor(param: PointEventResolverParameterObject) {
		this._sourceResolver = param.sourceResolver;
		this._playerId = param.playerId;
	}

	pointDown(e: PlatformPointEvent): pl.PointDownEvent {
		const source = this._sourceResolver.findPointSource(e.offset);
		// @ts-ignore
		const point = source.point ? source.point : e.offset;
		// @ts-ignore
		const targetId = source.target ? source.target.id : undefined;
		// @ts-ignore
		const local = source.local;

		this._pointEventMap[e.identifier] = {
			targetId,
			local,
			point,
			start: { x: e.offset.x, y: e.offset.y },
			prev: { x: e.offset.x, y: e.offset.y }
		};

		// NOTE: 優先度は機械的にJoinedをつけておく。Joinしていない限りPointDownEventなどはリジェクトされる。
		const ret: pl.PointDownEvent = [
			pl.EventCode.PointDown, // 0: イベントコード
			EventPriority.Joined, //   1: 優先度
			this._playerId, //         2: プレイヤーID
			e.identifier, //           3: ポインターID
			point.x, //                4: X座標
			point.y, //                5: Y座標
			targetId //                6?: エンティティID
		];
		if (source && source.local) ret.push(source.local); // 7?: ローカル
		return ret;
	}

	pointMove(e: PlatformPointEvent): pl.PointMoveEvent | null {
		const holder = this._pointEventMap[e.identifier];
		if (!holder) return null;
		const prev = { x: 0, y: 0 };
		const start = { x: 0, y: 0 };
		this._pointMoveAndUp(holder, e.offset, prev, start);
		const ret: pl.PointMoveEvent = [
			pl.EventCode.PointMove, // 0: イベントコード
			EventPriority.Joined, //   1: 優先度
			this._playerId, //         2: プレイヤーID
			e.identifier, //           3: ポインターID
			holder.point.x, //         4: X座標
			holder.point.y, //         5: Y座標
			start.x, //                6: ポイントダウンイベントからのX座標の差
			start.y, //                7: ポイントダウンイベントからのY座標の差
			prev.x, //                 8: 直前のポイントムーブイベントからのX座標の差
			prev.y, //                 9: 直前のポイントムーブイベントからのY座標の差
			holder.targetId //         10?: エンティティID
		];
		if (holder.local) ret.push(holder.local); // 11?: ローカル
		return ret;
	}

	pointUp(e: PlatformPointEvent): pl.PointUpEvent | null {
		const holder = this._pointEventMap[e.identifier];
		if (!holder) return null;
		const prev = { x: 0, y: 0 };
		const start = { x: 0, y: 0 };
		this._pointMoveAndUp(holder, e.offset, prev, start);
		delete this._pointEventMap[e.identifier];
		const ret: pl.PointUpEvent = [
			pl.EventCode.PointUp, // 0: イベントコード
			EventPriority.Joined, // 1: 優先度
			this._playerId, //       2: プレイヤーID
			e.identifier, //         3: ポインターID
			holder.point.x, //       4: X座標
			holder.point.y, //       5: Y座標
			start.x, //              6: ポイントダウンイベントからのX座標の差
			start.y, //              7: ポイントダウンイベントからのY座標の差
			prev.x, //               8: 直前のポイントムーブイベントからのX座標の差
			prev.y, //               9: 直前のポイントムーブイベントからのY座標の差
			holder.targetId //       10?: エンティティID
		];
		if (holder.local) ret.push(holder.local); // 11?: ローカル
		return ret;
	}

	private _pointMoveAndUp(holder: PointEventHolder, offset: CommonOffset, prevDelta: CommonOffset, startDelta: CommonOffset): void {
		startDelta.x = offset.x - holder.start.x;
		startDelta.y = offset.y - holder.start.y;
		prevDelta.x = offset.x - holder.prev.x;
		prevDelta.y = offset.y - holder.prev.y;

		holder.prev.x = offset.x;
		holder.prev.y = offset.y;
	}
}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Reflection;

namespace System.Runtime.Serialization
{
    internal class XmlObjectSerializerReadContextComplex : XmlObjectSerializerReadContext
    {
        private readonly bool _preserveObjectReferences;
        private readonly SerializationMode _mode;
        private readonly ISerializationSurrogateProvider _serializationSurrogateProvider;

        internal XmlObjectSerializerReadContextComplex(DataContractSerializer serializer, DataContract rootTypeDataContract, DataContractResolver dataContractResolver)
            : base(serializer, rootTypeDataContract, dataContractResolver)
        {
            _mode = SerializationMode.SharedContract;
            _preserveObjectReferences = serializer.PreserveObjectReferences;
            _serializationSurrogateProvider = serializer.SerializationSurrogateProvider;
        }

        internal XmlObjectSerializerReadContextComplex(XmlObjectSerializer serializer, int maxItemsInObjectGraph, StreamingContext streamingContext, bool ignoreExtensionDataObject)
            : base(serializer, maxItemsInObjectGraph, streamingContext, ignoreExtensionDataObject)
        {
        }

        internal override SerializationMode Mode
        {
            get { return _mode; }
        }

        internal override object InternalDeserialize(XmlReaderDelegator xmlReader, int declaredTypeID, RuntimeTypeHandle declaredTypeHandle, string name, string ns)
        {
            if (_mode == SerializationMode.SharedContract)
            {
                if (_serializationSurrogateProvider == null)
                    return base.InternalDeserialize(xmlReader, declaredTypeID, declaredTypeHandle, name, ns);
                else
                    return InternalDeserializeWithSurrogate(xmlReader, Type.GetTypeFromHandle(declaredTypeHandle), null /*surrogateDataContract*/, name, ns);
            }
            else
            {
                return InternalDeserializeInSharedTypeMode(xmlReader, declaredTypeID, Type.GetTypeFromHandle(declaredTypeHandle), name, ns);
            }
        }

        internal override object InternalDeserialize(XmlReaderDelegator xmlReader, Type declaredType, string name, string ns)
        {
            if (_mode == SerializationMode.SharedContract)
            {
                if (_serializationSurrogateProvider == null)
                    return base.InternalDeserialize(xmlReader, declaredType, name, ns);
                else
                    return InternalDeserializeWithSurrogate(xmlReader, declaredType, null /*surrogateDataContract*/, name, ns);
            }
            else
            {
                return InternalDeserializeInSharedTypeMode(xmlReader, -1, declaredType, name, ns);
            }
        }

        internal override object InternalDeserialize(XmlReaderDelegator xmlReader, Type declaredType, DataContract dataContract, string name, string ns)
        {
            if (_mode == SerializationMode.SharedContract)
            {
                if (_serializationSurrogateProvider == null)
                    return base.InternalDeserialize(xmlReader, declaredType, dataContract, name, ns);
                else
                    return InternalDeserializeWithSurrogate(xmlReader, declaredType, dataContract, name, ns);
            }
            else
            {
                return InternalDeserializeInSharedTypeMode(xmlReader, -1, declaredType, name, ns);
            }
        }

        private object InternalDeserializeInSharedTypeMode(XmlReaderDelegator xmlReader, int declaredTypeID, Type declaredType, string name, string ns)
        {
            object retObj = null;
            if (TryHandleNullOrRef(xmlReader, declaredType, name, ns, ref retObj))
                return retObj;

            DataContract dataContract;
            string assemblyName = attributes.ClrAssembly;
            string typeName = attributes.ClrType;
            if (assemblyName != null && typeName != null)
            {
                Assembly assembly;
                Type type;
                dataContract = ResolveDataContractInSharedTypeMode(assemblyName, typeName, out assembly, out type);
                if (dataContract == null)
                {
                    if (assembly == null)
                        throw XmlObjectSerializer.CreateSerializationException(SR.Format(SR.AssemblyNotFound, assemblyName));
                    if (type == null)
                        throw XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ClrTypeNotFound, assembly.FullName, typeName));
                }
                //Array covariance is not supported in XSD. If declared type is array, data is sent in format of base array
                if (declaredType != null && declaredType.IsArray)
                    dataContract = (declaredTypeID < 0) ? GetDataContract(declaredType) : GetDataContract(declaredTypeID, declaredType.TypeHandle);
            }
            else
            {
                if (assemblyName != null)
                    throw XmlObjectSerializer.CreateSerializationException(XmlObjectSerializer.TryAddLineInfo(xmlReader, SR.Format(SR.AttributeNotFound, Globals.SerializationNamespace, Globals.ClrTypeLocalName, xmlReader.NodeType, xmlReader.NamespaceURI, xmlReader.LocalName)));
                else if (typeName != null)
                    throw XmlObjectSerializer.CreateSerializationException(XmlObjectSerializer.TryAddLineInfo(xmlReader, SR.Format(SR.AttributeNotFound, Globals.SerializationNamespace, Globals.ClrAssemblyLocalName, xmlReader.NodeType, xmlReader.NamespaceURI, xmlReader.LocalName)));
                else if (declaredType == null)
                    throw XmlObjectSerializer.CreateSerializationException(XmlObjectSerializer.TryAddLineInfo(xmlReader, SR.Format(SR.AttributeNotFound, Globals.SerializationNamespace, Globals.ClrTypeLocalName, xmlReader.NodeType, xmlReader.NamespaceURI, xmlReader.LocalName)));
                dataContract = (declaredTypeID < 0) ? GetDataContract(declaredType) : GetDataContract(declaredTypeID, declaredType.TypeHandle);
            }
            return ReadDataContractValue(dataContract, xmlReader);
        }

        private object InternalDeserializeWithSurrogate(XmlReaderDelegator xmlReader, Type declaredType, DataContract surrogateDataContract, string name, string ns)
        {
            DataContract dataContract = surrogateDataContract ??
                GetDataContract(DataContractSurrogateCaller.GetDataContractType(_serializationSurrogateProvider, declaredType));
            if (this.IsGetOnlyCollection && dataContract.UnderlyingType != declaredType)
            {
                throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.SurrogatesWithGetOnlyCollectionsNotSupportedSerDeser, DataContract.GetClrTypeFullName(declaredType))));
            }
            ReadAttributes(xmlReader);
            string objectId = GetObjectId();
            object oldObj = InternalDeserialize(xmlReader, name, ns, declaredType, ref dataContract);
            object obj = DataContractSurrogateCaller.GetDeserializedObject(_serializationSurrogateProvider, oldObj, dataContract.UnderlyingType, declaredType);
            ReplaceDeserializedObject(objectId, oldObj, obj);

            return obj;
        }

        private Type ResolveDataContractTypeInSharedTypeMode(string assemblyName, string typeName, out Assembly assembly)
        {
            // The method is used only when _mode == SerializationMode.SharedType.
            // _mode is set to SerializationMode.SharedType only when the context is for NetDataContractSerializer.
            throw new PlatformNotSupportedException(SR.PlatformNotSupported_NetDataContractSerializer);
        }

        private DataContract ResolveDataContractInSharedTypeMode(string assemblyName, string typeName, out Assembly assembly, out Type type)
        {
            type = ResolveDataContractTypeInSharedTypeMode(assemblyName, typeName, out assembly);
            if (type != null)
            {
                return GetDataContract(type);
            }

            return null;
        }

        protected override DataContract ResolveDataContractFromTypeName()
        {
            if (_mode == SerializationMode.SharedContract)
            {
                return base.ResolveDataContractFromTypeName();
            }
            else
            {
                if (attributes.ClrAssembly != null && attributes.ClrType != null)
                {
                    Assembly assembly;
                    Type type;
                    return ResolveDataContractInSharedTypeMode(attributes.ClrAssembly, attributes.ClrType, out assembly, out type);
                }
            }
            return null;
        }

        internal override void CheckIfTypeSerializable(Type memberType, bool isMemberTypeSerializable)
        {
            if (_serializationSurrogateProvider != null)
            {
                while (memberType.IsArray)
                    memberType = memberType.GetElementType();
                memberType = DataContractSurrogateCaller.GetDataContractType(_serializationSurrogateProvider, memberType);
                if (!DataContract.IsTypeSerializable(memberType))
                    throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.TypeNotSerializable, memberType)));
                return;
            }

            base.CheckIfTypeSerializable(memberType, isMemberTypeSerializable);
        }

        internal override Type GetSurrogatedType(Type type)
        {
            if (_serializationSurrogateProvider == null)
            {
                return base.GetSurrogatedType(type);
            }
            else
            {
                type = DataContract.UnwrapNullableType(type);
                Type surrogateType = DataContractSerializer.GetSurrogatedType(_serializationSurrogateProvider, type);
                if (this.IsGetOnlyCollection && surrogateType != type)
                {
                    throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.SurrogatesWithGetOnlyCollectionsNotSupportedSerDeser,
                        DataContract.GetClrTypeFullName(type))));
                }
                else
                {
                    return surrogateType;
                }
            }
        }

#if USE_REFEMIT
        public override int GetArraySize()
#else
        internal override int GetArraySize()
#endif
        {
            return _preserveObjectReferences ? attributes.ArraySZSize : -1;
        }
    }
}


text:
<?php

namespace Magento\Framework\Session;

use Magento\Framework\App\DeploymentConfig;

/**
 * Magento session save handler
 */
class SaveHandler implements SaveHandlerInterface
{
    /**
     * Session handler
     *
     * @var \SessionHandler
     */
    protected $saveHandlerAdapter;

    /**
     * Constructor
     *
     * @param SaveHandlerFactory $saveHandlerFactory
     * @param DeploymentConfig $deploymentConfig
     * @param string $default
     */
    public function __construct(
        SaveHandlerFactory $saveHandlerFactory,
        DeploymentConfig $deploymentConfig,
        $default = self::DEFAULT_HANDLER
    ) {
        $saveMethod = $deploymentConfig->get(\Magento\Framework\Session\Config::PARAM_SESSION_SAVE_METHOD);
        try {
            $adapter = $saveHandlerFactory->create($saveMethod);
        } catch (SaveHandlerException $e) {
            $adapter = $saveHandlerFactory->create($default);
        }
        $this->saveHandlerAdapter = $adapter;
    }

    /**
     * Open Session - retrieve resources
     *
     * @param string $savePath
     * @param string $name
     * @return bool
     */
    public function open($savePath, $name)
    {
        return $this->saveHandlerAdapter->open($savePath, $name);
    }

    /**
     * Close Session - free resources
     *
     * @return bool
     */
    public function close()
    {
        return $this->saveHandlerAdapter->close();
    }

    /**
     * Read session data
     *
     * @param string $sessionId
     * @return string
     */
    public function read($sessionId)
    {
        return $this->saveHandlerAdapter->read($sessionId);
    }

    /**
     * Write Session - commit data to resource
     *
     * @param string $sessionId
     * @param string $data
     * @return bool
     */
    public function write($sessionId, $data)
    {
        return $this->saveHandlerAdapter->write($sessionId, $data);
    }

    /**
     * Destroy Session - remove data from resource for given session id
     *
     * @param string $sessionId
     * @return bool
     */
    public function destroy($sessionId)
    {
        return $this->saveHandlerAdapter->destroy($sessionId);
    }

    /**
     * Garbage Collection - remove old session data older
     * than $maxLifetime (in seconds)
     *
     * @param int $maxLifetime
     * @return bool
     */
    public function gc($maxLifetime)
    {
        return $this->saveHandlerAdapter->gc($maxLifetime);
    }
}


text:
  #### Example:
  - Created Foo
  - Fixed bar when xyz happened

## Checklist
  - [ ] Added tests
  - [ ] All existing and new tests pass
  - [ ] Updated README (if appropriate)
  - [ ] Code lints (Rubocop) successfully
  - [ ] Commits are according to our commit guidelines


text:
echo "Running tests from tests.server.dbmodule.objects.test_app"
nosetests --tests tests.server.dbmodule.objects.test_app

echo "Running tests from tests.server.dbmodule.objects.test_env"
nosetests --tests tests.server.dbmodule.objects.test_env

echo "Running functional tests"

has_server_started=`ps -eaf | grep -v grep | grep fmserver`

if [[ -z "${has_server_started}" ]]; then
    echo "CloudARK server not running. Please start the server and then run the tests."
    exit
fi

nosetests --tests tests.server.local.test_local:TestLocal.test_app_deploy_hello_world


text:
package org.apache.tapestry5.internal.services;

import java.util.List;

import org.apache.tapestry5.OptionModel;
import org.apache.tapestry5.SelectModel;
import org.apache.tapestry5.ValueEncoder;
import org.apache.tapestry5.internal.OptionModelImpl;
import org.apache.tapestry5.internal.SelectModelImpl;
import org.apache.tapestry5.ioc.internal.util.CollectionFactory;
import org.apache.tapestry5.ioc.services.ClassPropertyAdapter;
import org.apache.tapestry5.ioc.services.PropertyAccess;
import org.apache.tapestry5.ioc.services.PropertyAdapter;
import org.apache.tapestry5.services.SelectModelFactory;
import org.apache.tapestry5.services.ValueEncoderSource;

public class SelectModelFactoryImpl implements SelectModelFactory
{
    private final PropertyAccess propertyAccess;
    private final ValueEncoderSource valueEncoderSource;

    public SelectModelFactoryImpl(final PropertyAccess propertyAccess,
            final ValueEncoderSource valueEncoderSource)
    {
        super();
        this.propertyAccess = propertyAccess;
        this.valueEncoderSource = valueEncoderSource;
    }

    @SuppressWarnings("unchecked")
    public SelectModel create(final List<?> objects, final String labelProperty)
    {
        final List<OptionModel> options = CollectionFactory.newList();

        for (final Object object : objects)
        {
            final ClassPropertyAdapter classPropertyAdapter = this.propertyAccess
                    .getAdapter(object);

            final PropertyAdapter propertyAdapter = classPropertyAdapter.getPropertyAdapter(labelProperty);

            final ValueEncoder encoder = this.valueEncoderSource.getValueEncoder(propertyAdapter.getType());

            final Object label = propertyAdapter.get(object);

            options.add(new OptionModelImpl(encoder.toClient(label), object));

        }

        return new SelectModelImpl(null, options);
    }
}


text: Conversion utility that allows Jira issues to be migrated into the GitHub issue tracker.