text:
import logging
import simplejson as json

from django import forms
from django.core.serializers.json import DjangoJSONEncoder
from django.db import models
from django.utils.functional import curry
from django.utils.translation import ugettext_lazy as _

import plata

try:
    json.dumps([42], use_decimal=True)
except TypeError:
    raise Exception('simplejson>=2.1 with support for use_decimal required.')

#: Field offering all defined currencies
CurrencyField = curry(models.CharField, _('currency'), max_length=3, choices=zip(
    plata.settings.CURRENCIES, plata.settings.CURRENCIES))

class JSONFormField(forms.fields.CharField):
    def clean(self, value, *args, **kwargs):
        if value:
            try:
                # Run the value through JSON so we can normalize formatting and at least learn about malformed data:
                value = json.dumps(json.loads(value, use_decimal=True),
                    cls=DjangoJSONEncoder, use_decimal=True)
            except ValueError:
                raise forms.ValidationError("Invalid JSON data!")

        return super(JSONFormField, self).clean(value, *args, **kwargs)

class JSONField(models.TextField):
    """
    TextField which transparently serializes/unserializes JSON objects

    See:
    http://www.djangosnippets.org/snippets/1478/
    """

    # Used so to_python() is called
    __metaclass__ = models.SubfieldBase

    formfield = JSONFormField

    def to_python(self, value):
        """Convert our string value to JSON after we load it from the DB"""

        if isinstance(value, dict):
            return value
        elif isinstance(value, basestring):
            # Avoid asking the JSON decoder to handle empty values:
            if not value:
                return {}

            try:
                return json.loads(value, use_decimal=True)
            except ValueError:
                logging.getLogger("plata.fields").exception("Unable to deserialize store JSONField data: %s", value)
                return {}
        else:
            assert value is None
            return {}

    def get_prep_value(self, value):
        """Convert our JSON object to a string before we save"""
        return self._flatten_value(value)

    def value_to_string(self, obj):
        """Extract our value from the passed object and return it in string form"""

        if hasattr(obj, self.attname):
            value = getattr(obj, self.attname)
        else:
            assert isinstance(obj, dict)
            value = obj.get(self.attname, "")

        return self._flatten_value(value)

    def _flatten_value(self, value):
        """Return either a string, JSON-encoding dict()s as necessary"""
        if not value:
            return ""

        if isinstance(value, dict):
            value = json.dumps(value, cls=DjangoJSONEncoder, use_decimal=True)

        assert isinstance(value, basestring)

        return value

    def value_from_object(self, obj):
        return json.dumps(super(JSONField, self).value_from_object(obj),
            cls=DjangoJSONEncoder, use_decimal=True)

try:
    from south.modelsinspector import add_introspection_rules

    JSONField_introspection_rule = ( (JSONField,), [], {}, )

    add_introspection_rules(rules=[JSONField_introspection_rule], patterns=["^plata\.fields"])
except ImportError:
    pass


text:
/* $OpenBSD: eng_aesni.c,v 1.5 2014/06/12 15:49:29 deraadt Exp $ */
/*
 * Support for Intel AES-NI intruction set
 *   Author: Huang Ying <ying.huang@intel.com>
 *
 * Intel AES-NI is a new set of Single Instruction Multiple Data
 * (SIMD) instructions that are going to be introduced in the next
 * generation of Intel processor, as of 2009. These instructions
 * enable fast and secure data encryption and decryption, using the
 * Advanced Encryption Standard (AES), defined by FIPS Publication
 * number 197.  The architecture introduces six instructions that
 * offer full hardware support for AES. Four of them support high
 * performance data encryption and decryption, and the other two
 * instructions support the AES key expansion procedure.
 *
 * The white paper can be downloaded from:
 *   http://softwarecommunity.intel.com/isn/downloads/intelavx/AES-Instructions-Set_WP.pdf
 *
 * This file is based on engines/e_padlock.c
 */

/* ====================================================================
 * Copyright (c) 1999-2001 The OpenSSL Project.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. All advertising materials mentioning features or use of this
 *    software must display the following acknowledgment:
 *    "This product includes software developed by the OpenSSL Project
 *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
 *
 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
 *    endorse or promote products derived from this software without
 *    prior written permission. For written permission, please contact
 *    licensing@OpenSSL.org.
 *
 * 5. Products derived from this software may not be called "OpenSSL"
 *    nor may "OpenSSL" appear in their names without prior written
 *    permission of the OpenSSL Project.
 *
 * 6. Redistributions of any form whatsoever must retain the following
 *    acknowledgment:
 *    "This product includes software developed by the OpenSSL Project
 *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
 *
 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 * ====================================================================
 *
 * This product includes cryptographic software written by Eric Young
 * (eay@cryptsoft.com).  This product includes software written by Tim
 * Hudson (tjh@cryptsoft.com).
 *
 */

#include <openssl/opensslconf.h>

#if !defined(OPENSSL_NO_HW) && !defined(OPENSSL_NO_HW_AES_NI) && !defined(OPENSSL_NO_AES)

#include <stdio.h>
#include <assert.h>
#include "cryptlib.h"
#include <openssl/dso.h>
#include <openssl/engine.h>
#include <openssl/evp.h>
#include <openssl/aes.h>
#include <openssl/err.h>

/* AES-NI is available *ONLY* on some x86 CPUs.  Not only that it
   doesn't exist elsewhere, but it even can't be compiled on other
   platforms! */
#undef COMPILE_HW_AESNI
#if (defined(__x86_64) || defined(__x86_64__) || \
     defined(_M_AMD64) || defined(_M_X64) || \
     defined(OPENSSL_IA32_SSE2)) && !defined(OPENSSL_NO_ASM) && !defined(__i386__)
#define COMPILE_HW_AESNI
#endif
static ENGINE *ENGINE_aesni (void);

void ENGINE_load_aesni (void)
{
/* On non-x86 CPUs it just returns. */
#ifdef COMPILE_HW_AESNI
	ENGINE *toadd = ENGINE_aesni();
	if (!toadd)
		return;
	ENGINE_add (toadd);
	ENGINE_register_complete (toadd);
	ENGINE_free (toadd);
	ERR_clear_error ();
#endif
}

#ifdef COMPILE_HW_AESNI
int aesni_set_encrypt_key(const unsigned char *userKey, int bits,
    AES_KEY *key);
int aesni_set_decrypt_key(const unsigned char *userKey, int bits,
    AES_KEY *key);

void aesni_encrypt(const unsigned char *in, unsigned char *out,
    const AES_KEY *key);
void aesni_decrypt(const unsigned char *in, unsigned char *out,
    const AES_KEY *key);

void aesni_ecb_encrypt(const unsigned char *in, unsigned char *out,
    size_t length, const AES_KEY *key, int enc);
void aesni_cbc_encrypt(const unsigned char *in, unsigned char *out,
    size_t length, const AES_KEY *key, unsigned char *ivec, int enc);

/* Function for ENGINE detection and control */
static int aesni_init(ENGINE *e);

/* Cipher Stuff */
static int aesni_ciphers(ENGINE *e, const EVP_CIPHER **cipher,
    const int **nids, int nid);

#define AESNI_MIN_ALIGN	16
#define AESNI_ALIGN(x) \
	((void *)(((unsigned long)(x)+AESNI_MIN_ALIGN-1)&~(AESNI_MIN_ALIGN-1)))

/* Engine names */
static const char   aesni_id[] = "aesni",
    aesni_name[] = "Intel AES-NI engine",
    no_aesni_name[] = "Intel AES-NI engine (no-aesni)";

/* The input and output encrypted as though 128bit cfb mode is being
 * used.  The extra state information to record how much of the
 * 128bit block we have used is contained in *num;
 */
static void
aesni_cfb128_encrypt(const unsigned char *in, unsigned char *out,
    unsigned int len, const void *key, unsigned char ivec[16], int *num,
    int enc)
{
	unsigned int n;
	size_t l = 0;

	assert(in && out && key && ivec && num);

	n = *num;

	if (enc) {
#if !defined(OPENSSL_SMALL_FOOTPRINT)
			if (16%sizeof(size_t) == 0) do {	/* always true actually */
			while (n && len) {
				*(out++) = ivec[n] ^= *(in++);
				--len;
				n = (n + 1) % 16;
			}
			while (len >= 16) {
				aesni_encrypt(ivec, ivec, key);
				for (n = 0; n < 16; n += sizeof(size_t)) {
					*(size_t*)(out + n) =
					    *(size_t*)(ivec + n) ^= *(size_t*)(in + n);
				}
				len -= 16;
				out += 16;
				in += 16;
			}
			n = 0;
			if (len) {
				aesni_encrypt(ivec, ivec, key);
				while (len--) {
					out[n] = ivec[n] ^= in[n];
					++n;
				}
			}
			*num = n;
			return;
		} while (0);
		/* the rest would be commonly eliminated by x86* compiler */
#endif
		while (l < len) {
			if (n == 0) {
				aesni_encrypt(ivec, ivec, key);
			}
			out[l] = ivec[n] ^= in[l];
			++l;
			n = (n + 1) % 16;
		}
		*num = n;
	} else {
#if !defined(OPENSSL_SMALL_FOOTPRINT)
			if (16%sizeof(size_t) == 0) do {	/* always true actually */
			while (n && len) {
				unsigned char c;
				*(out++) = ivec[n] ^ (c = *(in++));
				ivec[n] = c;
				--len;
				n = (n + 1) % 16;
			}
			while (len >= 16) {
				aesni_encrypt(ivec, ivec, key);
				for (n = 0; n < 16; n += sizeof(size_t)) {
					size_t t = *(size_t*)(in + n);
					*(size_t*)(out + n) = *(size_t*)(ivec + n) ^ t;
					*(size_t*)(ivec + n) = t;
				}
				len -= 16;
				out += 16;
				in += 16;
			}
			n = 0;
			if (len) {
				aesni_encrypt(ivec, ivec, key);
				while (len--) {
					unsigned char c;
					out[n] = ivec[n] ^ (c = in[n]);
					ivec[n] = c;
					++n;
				}
			}
			*num = n;
			return;
		} while (0);
		/* the rest would be commonly eliminated by x86* compiler */
#endif
		while (l < len) {
			unsigned char c;
			if (n == 0) {
				aesni_encrypt(ivec, ivec, key);
			}
			out[l] = ivec[n] ^ (c = in[l]);
			ivec[n] = c;
			++l;
			n = (n + 1) % 16;
		}
		*num = n;
	}
}

/* The input and output encrypted as though 128bit ofb mode is being
 * used.  The extra state information to record how much of the
 * 128bit block we have used is contained in *num;
 */
static void
aesni_ofb128_encrypt(const unsigned char *in, unsigned char *out,
    unsigned int len, const void *key, unsigned char ivec[16], int *num)
{
	unsigned int n;
	size_t l = 0;

	assert(in && out && key && ivec && num);

	n = *num;

#if !defined(OPENSSL_SMALL_FOOTPRINT)
		if (16%sizeof(size_t) == 0) do { /* always true actually */
		while (n && len) {
			*(out++) = *(in++) ^ ivec[n];
			--len;
			n = (n + 1) % 16;
		}
		while (len >= 16) {
			aesni_encrypt(ivec, ivec, key);
			for (n = 0; n < 16; n += sizeof(size_t))
				*(size_t*)(out + n) =
				    *(size_t*)(in + n) ^ *(size_t*)(ivec + n);
			len -= 16;
			out += 16;
			in += 16;
		}
		n = 0;
		if (len) {
			aesni_encrypt(ivec, ivec, key);
			while (len--) {
				out[n] = in[n] ^ ivec[n];
				++n;
			}
		}
		*num = n;
		return;
	} while (0);
	/* the rest would be commonly eliminated by x86* compiler */
#endif
	while (l < len) {
		if (n == 0) {
			aesni_encrypt(ivec, ivec, key);
		}
		out[l] = in[l] ^ ivec[n];
		++l;
		n = (n + 1) % 16;
	}

	*num = n;
}
/* ===== Engine "management" functions ===== */

typedef unsigned long long IA32CAP;

/* Prepare the ENGINE structure for registration */
static int
aesni_bind_helper(ENGINE *e)
{
	int engage;

	if (sizeof(OPENSSL_ia32cap_P) > 4) {
		engage = ((IA32CAP)OPENSSL_ia32cap_P >> 57) & 1;
	} else {
		IA32CAP OPENSSL_ia32_cpuid(void);
		engage = (OPENSSL_ia32_cpuid() >> 57) & 1;
	}

	/* Register everything or return with an error */
	if (!ENGINE_set_id(e, aesni_id) ||
	    !ENGINE_set_name(e, engage ? aesni_name : no_aesni_name) ||
	    !ENGINE_set_init_function(e, aesni_init) ||
	    (engage && !ENGINE_set_ciphers (e, aesni_ciphers)))
		return 0;

	/* Everything looks good */
	return 1;
}

/* Constructor */
static ENGINE *
ENGINE_aesni(void)
{
	ENGINE *eng = ENGINE_new();

	if (!eng) {
		return NULL;
	}

	if (!aesni_bind_helper(eng)) {
		ENGINE_free(eng);
		return NULL;
	}

	return eng;
}

/* Check availability of the engine */
static int
aesni_init(ENGINE *e)
{
	return 1;
}

#if defined(NID_aes_128_cfb128) && ! defined (NID_aes_128_cfb)
#define NID_aes_128_cfb	NID_aes_128_cfb128
#endif

#if defined(NID_aes_128_ofb128) && ! defined (NID_aes_128_ofb)
#define NID_aes_128_ofb	NID_aes_128_ofb128
#endif

#if defined(NID_aes_192_cfb128) && ! defined (NID_aes_192_cfb)
#define NID_aes_192_cfb	NID_aes_192_cfb128
#endif

#if defined(NID_aes_192_ofb128) && ! defined (NID_aes_192_ofb)
#define NID_aes_192_ofb	NID_aes_192_ofb128
#endif

#if defined(NID_aes_256_cfb128) && ! defined (NID_aes_256_cfb)
#define NID_aes_256_cfb	NID_aes_256_cfb128
#endif

#if defined(NID_aes_256_ofb128) && ! defined (NID_aes_256_ofb)
#define NID_aes_256_ofb	NID_aes_256_ofb128
#endif

/* List of supported ciphers. */
static int aesni_cipher_nids[] = {
	NID_aes_128_ecb,
	NID_aes_128_cbc,
	NID_aes_128_cfb,
	NID_aes_128_ofb,

	NID_aes_192_ecb,
	NID_aes_192_cbc,
	NID_aes_192_cfb,
	NID_aes_192_ofb,

	NID_aes_256_ecb,
	NID_aes_256_cbc,
	NID_aes_256_cfb,
	NID_aes_256_ofb,
};
static int aesni_cipher_nids_num =
    (sizeof(aesni_cipher_nids) / sizeof(aesni_cipher_nids[0]));

typedef struct {
	AES_KEY ks;
	unsigned int _pad1[3];
} AESNI_KEY;

static int
aesni_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *user_key,
    const unsigned char *iv, int enc)
{
	int ret;
	AES_KEY *key = AESNI_ALIGN(ctx->cipher_data);

	if ((ctx->cipher->flags & EVP_CIPH_MODE) == EVP_CIPH_CFB_MODE ||
	    (ctx->cipher->flags & EVP_CIPH_MODE) == EVP_CIPH_OFB_MODE ||
	    enc)
		ret = aesni_set_encrypt_key(user_key, ctx->key_len * 8, key);
	else
		ret = aesni_set_decrypt_key(user_key, ctx->key_len * 8, key);

	if (ret < 0) {
		EVPerr(EVP_F_AESNI_INIT_KEY, EVP_R_AES_KEY_SETUP_FAILED);
		return 0;
	}

	return 1;
}

static int
aesni_cipher_ecb(EVP_CIPHER_CTX *ctx, unsigned char *out,
    const unsigned char *in, size_t inl)
{
	AES_KEY *key = AESNI_ALIGN(ctx->cipher_data);

	aesni_ecb_encrypt(in, out, inl, key, ctx->encrypt);
	return 1;
}

static int
aesni_cipher_cbc(EVP_CIPHER_CTX *ctx, unsigned char *out,
    const unsigned char *in, size_t inl)
{
	AES_KEY *key = AESNI_ALIGN(ctx->cipher_data);

	aesni_cbc_encrypt(in, out, inl, key, ctx->iv, ctx->encrypt);
	return 1;
}

static int
aesni_cipher_cfb(EVP_CIPHER_CTX *ctx, unsigned char *out,
    const unsigned char *in, size_t inl)
{
	AES_KEY *key = AESNI_ALIGN(ctx->cipher_data);

	aesni_cfb128_encrypt(in, out, inl, key, ctx->iv, &ctx->num,
	    ctx->encrypt);
	return 1;
}

static int
aesni_cipher_ofb(EVP_CIPHER_CTX *ctx, unsigned char *out,
    const unsigned char *in, size_t inl)
{
	AES_KEY *key = AESNI_ALIGN(ctx->cipher_data);

	aesni_ofb128_encrypt(in, out, inl, key, ctx->iv, &ctx->num);
	return 1;
}

#define AES_BLOCK_SIZE		16

#define EVP_CIPHER_block_size_ECB	AES_BLOCK_SIZE
#define EVP_CIPHER_block_size_CBC	AES_BLOCK_SIZE
#define EVP_CIPHER_block_size_OFB	1
#define EVP_CIPHER_block_size_CFB	1

/* Declaring so many ciphers by hand would be a pain.
   Instead introduce a bit of preprocessor magic :-) */
#define	DECLARE_AES_EVP(ksize,lmode,umode)	\
static const EVP_CIPHER aesni_##ksize##_##lmode = {	\
	NID_aes_##ksize##_##lmode,			\
	EVP_CIPHER_block_size_##umode,			\
	ksize / 8,					\
	AES_BLOCK_SIZE,					\
	0 | EVP_CIPH_##umode##_MODE,			\
	aesni_init_key,				\
	aesni_cipher_##lmode,				\
	NULL,						\
	sizeof(AESNI_KEY),				\
	EVP_CIPHER_set_asn1_iv,				\
	EVP_CIPHER_get_asn1_iv,				\
	NULL,						\
	NULL						\
}

DECLARE_AES_EVP(128, ecb, ECB);
DECLARE_AES_EVP(128, cbc, CBC);
DECLARE_AES_EVP(128, cfb, CFB);
DECLARE_AES_EVP(128, ofb, OFB);

DECLARE_AES_EVP(192, ecb, ECB);
DECLARE_AES_EVP(192, cbc, CBC);
DECLARE_AES_EVP(192, cfb, CFB);
DECLARE_AES_EVP(192, ofb, OFB);

DECLARE_AES_EVP(256, ecb, ECB);
DECLARE_AES_EVP(256, cbc, CBC);
DECLARE_AES_EVP(256, cfb, CFB);
DECLARE_AES_EVP(256, ofb, OFB);

static int
aesni_ciphers(ENGINE *e, const EVP_CIPHER **cipher, const int **nids, int nid)
{
	/* No specific cipher => return a list of supported nids ... */
	if (!cipher) {
		*nids = aesni_cipher_nids;
		return aesni_cipher_nids_num;
	}

	/* ... or the requested "cipher" otherwise */
	switch (nid) {
	case NID_aes_128_ecb:
		*cipher = &aesni_128_ecb;
		break;
	case NID_aes_128_cbc:
		*cipher = &aesni_128_cbc;
		break;
	case NID_aes_128_cfb:
		*cipher = &aesni_128_cfb;
		break;
	case NID_aes_128_ofb:
		*cipher = &aesni_128_ofb;
		break;

	case NID_aes_192_ecb:
		*cipher = &aesni_192_ecb;
		break;
	case NID_aes_192_cbc:
		*cipher = &aesni_192_cbc;
		break;
	case NID_aes_192_cfb:
		*cipher = &aesni_192_cfb;
		break;
	case NID_aes_192_ofb:
		*cipher = &aesni_192_ofb;
		break;

	case NID_aes_256_ecb:
		*cipher = &aesni_256_ecb;
		break;
	case NID_aes_256_cbc:
		*cipher = &aesni_256_cbc;
		break;
	case NID_aes_256_cfb:
		*cipher = &aesni_256_cfb;
		break;
	case NID_aes_256_ofb:
		*cipher = &aesni_256_ofb;
		break;

	default:
		/* Sorry, we don't support this NID */
		*cipher = NULL;
		return 0;
	}
	return 1;
}

#endif /* COMPILE_HW_AESNI */
#endif /* !defined(OPENSSL_NO_HW) && !defined(OPENSSL_NO_HW_AESNI) && !defined(OPENSSL_NO_AES) */

redpajama_set_name: RedPajamaGithub


text:
package com.jxtelecom.pds.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

import javax.sql.DataSource;
import java.util.Properties;

/**
 * 定时任务配置
 *
 * @author guolf
 * @email guolingfa@gmail.com
 * @date 2017-05-09 23:38
 */
@Configuration
public class ScheduleConfig {

    @Bean
    public SchedulerFactoryBean schedulerFactoryBean(DataSource dataSource) {
        SchedulerFactoryBean factory = new SchedulerFactoryBean();
        factory.setDataSource(dataSource);

        //quartz参数
        Properties prop = new Properties();
        prop.put("org.quartz.scheduler.instanceName", "JxteleScheduler");
        prop.put("org.quartz.scheduler.instanceId", "AUTO");
        //线程池配置
        prop.put("org.quartz.threadPool.class", "org.quartz.simpl.SimpleThreadPool");
        prop.put("org.quartz.threadPool.threadCount", "20");
        prop.put("org.quartz.threadPool.threadPriority", "5");
        //JobStore配置
        prop.put("org.quartz.jobStore.class", "org.quartz.impl.jdbcjobstore.JobStoreTX");
        //集群配置
        prop.put("org.quartz.jobStore.isClustered", "true");
        prop.put("org.quartz.jobStore.clusterCheckinInterval", "15000");
        prop.put("org.quartz.jobStore.maxMisfiresToHandleAtATime", "1");

        prop.put("org.quartz.jobStore.misfireThreshold", "12000");
        prop.put("org.quartz.jobStore.tablePrefix", "QRTZ_");
        factory.setQuartzProperties(prop);

        factory.setSchedulerName("RenrenScheduler");
        //延时启动
        factory.setStartupDelay(30);
        factory.setApplicationContextSchedulerContextKey("applicationContextKey");
        //可选,QuartzScheduler 启动时更新己存在的Job,这样就不用每次修改targetObject后删除qrtz_job_details表对应记录了
        factory.setOverwriteExistingJobs(true);
        //设置自动启动,默认为true
        factory.setAutoStartup(true);

        return factory;
    }
}


text:
package com.xplus.commons.pattern.behavioral.iterator;

import java.util.List;

public class ProductList extends AbstractList<String> {

	public ProductList(List<String> objects) {
		super(objects);
	}

	@Override
	public Iterator<String> createIterator() {
		return new ProductIterator(this);
	}

}


text:
/**
 * @fileoverview Tests for util.js.
 */

goog.provide('firebaseui.auth.utilTest');

goog.require('firebaseui.auth.util');
goog.require('goog.dom');
goog.require('goog.dom.TagName');
goog.require('goog.testing.MockClock');
goog.require('goog.testing.PropertyReplacer');
goog.require('goog.testing.jsunit');
goog.require('goog.testing.recordFunction');

goog.setTestOnly('firebaseui.auth.utilTest');

var stubs = new goog.testing.PropertyReplacer();
var clock;
var BROWSER_URL = 'http://localhost';

function redirectCallback() {
  firebaseui.auth.util.goTo(BROWSER_URL);
}

function setUp() {
  clock = new goog.testing.MockClock();
  clock.install();
  stubs.set(firebaseui.auth.util, 'goTo', goog.testing.recordFunction());
}

function tearDown() {
  stubs.reset();
  clock.uninstall();
}

function testGetElement() {
  // Test that the element is correctly retrieved.
  var element = goog.dom.createDom(goog.dom.TagName.DIV);
  element.setAttribute('id', 'myElement');
  document.body.appendChild(element);
  assertEquals(element, firebaseui.auth.util.getElement('#myElement'));
  goog.dom.removeNode(element);

  // Test getElement default error description.
  try {
    firebaseui.auth.util.getElement('#notFound');
    fail('Should have thrown an error!');
  } catch (e) {
    assertEquals(e.message, 'Cannot find element.');
  }

  // Test getElement custom error description.
  try {
    firebaseui.auth.util.getElement('#notFound',
        'Element requested was not found!');
    fail('Should have thrown an error!');
  } catch (e) {
    assertEquals(e.message, 'Element requested was not found!');
  }
}

function testIsHttpOrHttps() {
  // HTTP scheme.
  stubs.replace(
      firebaseui.auth.util,
      'getScheme',
      function() {
        return 'http:';
      });
  assertTrue(firebaseui.auth.util.isHttpOrHttps());
  // HTTPS scheme.
  stubs.replace(
      firebaseui.auth.util,
      'getScheme',
      function() {
        return 'https:';
      });
  assertTrue(firebaseui.auth.util.isHttpOrHttps());
  // FILE scheme.
  stubs.replace(
      firebaseui.auth.util,
      'getScheme',
      function() {
        return 'file:';
      });
  assertFalse(firebaseui.auth.util.isHttpOrHttps());
}


text:
// This class has been generated, DO NOT EDIT!

package org.tensorflow.op.io;

import java.util.Arrays;
import org.tensorflow.GraphOperation;
import org.tensorflow.Operand;
import org.tensorflow.Operation;
import org.tensorflow.OperationBuilder;
import org.tensorflow.Output;
import org.tensorflow.op.RawOp;
import org.tensorflow.op.RawOpInputs;
import org.tensorflow.op.Scope;
import org.tensorflow.op.annotation.Endpoint;
import org.tensorflow.op.annotation.OpInputsMetadata;
import org.tensorflow.op.annotation.OpMetadata;
import org.tensorflow.op.annotation.Operator;
import org.tensorflow.types.TString;
import org.tensorflow.types.family.TType;

/**
 * Returns the next record (key, value pair) produced by a Reader.
 * Will dequeue from the input queue if necessary (e.g. when the
 * Reader needs to start reading from a new file since it has finished
 * with the previous file).
 */
@OpMetadata(
    opType = ReaderRead.OP_NAME,
    inputsClass = ReaderRead.Inputs.class
)
@Operator(
    group = "io"
)
public final class ReaderRead extends RawOp {
  /**
   * The name of this op, as known by TensorFlow core engine
   */
  public static final String OP_NAME = "ReaderReadV2";

  private Output<TString> key;

  private Output<TString> value;

  public ReaderRead(Operation operation) {
    super(operation, OP_NAME);
    int outputIdx = 0;
    key = operation.output(outputIdx++);
    value = operation.output(outputIdx++);
  }

  /**
   * Factory method to create a class wrapping a new ReaderReadV2 operation.
   *
   * @param scope current scope
   * @param readerHandle Handle to a Reader.
   * @param queueHandle Handle to a Queue, with string work items.
   * @return a new instance of ReaderRead
   */
  @Endpoint(
      describeByClass = true
  )
  public static ReaderRead create(Scope scope, Operand<? extends TType> readerHandle,
      Operand<? extends TType> queueHandle) {
    OperationBuilder opBuilder = scope.opBuilder(OP_NAME, "ReaderRead");
    opBuilder.addInput(readerHandle.asOutput());
    opBuilder.addInput(queueHandle.asOutput());
    return new ReaderRead(opBuilder.build());
  }

  /**
   * Gets key.
   * A scalar.
   * @return key.
   */
  public Output<TString> key() {
    return key;
  }

  /**
   * Gets value.
   * A scalar.
   * @return value.
   */
  public Output<TString> value() {
    return value;
  }

  @OpInputsMetadata(
      outputsClass = ReaderRead.class
  )
  public static class Inputs extends RawOpInputs<ReaderRead> {
    /**
     * Handle to a Reader.
     */
    public final Operand<? extends TType> readerHandle;

    /**
     * Handle to a Queue, with string work items.
     */
    public final Operand<? extends TType> queueHandle;

    public Inputs(GraphOperation op) {
      super(new ReaderRead(op), op, Arrays.asList());
      int inputIndex = 0;
      readerHandle = (Operand<? extends TType>) op.input(inputIndex++);
      queueHandle = (Operand<? extends TType>) op.input(inputIndex++);
    }
  }
}


text:
<!DOCTYPE html>

  <title>GCode Tools</title>
  <link rel="stylesheet" href="styles.css">
  <link rel="stylesheet" href="codemirror.css">

<output></output>

  <button id="choose_file">Load Gcode</button>
  <button id="run_script">Run Script</button>
  <button id="save_gcode">Save Gcode</button>


text:
A talk for ELAConf 2017 built with reveal.js [![Build Status](https://travis-ci.org/hakimel/reveal.js.svg?branch=master)](https://travis-ci.org/hakimel/reveal.js)

[Slides.](https://alexelash.github.io/elaconf2017/)

## Abstract
Even though we spend the majority of our time working—or maybe because of it—identifying a work environment as detrimental to self-worth and a healthy work/life balance is difficult. Whether harassed by coworkers, demeaned by a demanding boss, or a part of a culture that conflates hard work with working 24/7, it can be difficult to make the distinction between the ups-and-downs that accompany working life and legitimately toxic surroundings. Not identifying this early enough can lead to burnout, a questionably short tenure on your resume, or lasting self-doubt.

I want to anonymously interview friends and people in the community, as well as use personal experience, to explore and share answers to the following questions that I have surrounding the issue:
- What was the turning point for you?
- Did you talk to anyone about your concerns, whether friends, coworkers, or a manager? How did that go?
- Did you attempt to directly address these issues? How were those attempts met?
- How did you get past the negative experience at future jobs?
- Were there (in retrospect) any early on red flags that you've identified since?

I hope that as a result of the talk, people in a toxic work environment can recognize their situation and develop the courage to leave on their terms. Ideally, recent grads or professionals with little work experience will additionally be armed with the ability to recognize and reject companies that issue warning signs before making the mistake of entering a toxic work environment.


text:
#include "config.h"

#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <cairo.h>
#include <math.h>
#include <assert.h>
#include <pixman.h>
#include <sys/epoll.h>
#include <sys/socket.h>
#include <unistd.h>

#include <EGL/egl.h>
#include <EGL/eglext.h>
#include <GLES2/gl2.h>
#include <GLES2/gl2ext.h>

#include <cairo-gl.h>

#include <wayland-client.h>
#define WL_HIDE_DEPRECATED
#include <wayland-server.h>

#include "shared/helpers.h"
#include "window.h"

#ifndef EGL_WL_create_wayland_buffer_from_image
#define EGL_WL_create_wayland_buffer_from_image 1

#ifdef EGL_EGLEXT_PROTOTYPES
EGLAPI struct wl_buffer * EGLAPIENTRY eglCreateWaylandBufferFromImageWL(EGLDisplay dpy, EGLImageKHR image);
#endif
typedef struct wl_buffer * (EGLAPIENTRYP PFNEGLCREATEWAYLANDBUFFERFROMIMAGEWL) (EGLDisplay dpy, EGLImageKHR image);

#endif

static int option_blit;

struct nested {
	struct display *display;
	struct window *window;
	struct widget *widget;
	struct wl_display *child_display;
	struct task child_task;

	EGLDisplay egl_display;
	struct program *texture_program;

	struct wl_list surface_list;

	const struct nested_renderer *renderer;
};

struct nested_region {
	struct wl_resource *resource;
	pixman_region32_t region;
};

struct nested_buffer_reference {
	struct nested_buffer *buffer;
	struct wl_listener destroy_listener;
};

struct nested_buffer {
	struct wl_resource *resource;
	struct wl_signal destroy_signal;
	struct wl_listener destroy_listener;
	uint32_t busy_count;

	/* A buffer in the parent compositor representing the same
	 * data. This is created on-demand when the subsurface
	 * renderer is used */
	struct wl_buffer *parent_buffer;
	/* This reference is used to mark when the parent buffer has
	 * been attached to the subsurface. It will be unrefenced when
	 * we receive a buffer release event. That way we won't inform
	 * the client that the buffer is free until the parent
	 * compositor is also finished with it */
	struct nested_buffer_reference parent_ref;
};

struct nested_surface {
	struct wl_resource *resource;
	struct nested *nested;
	EGLImageKHR *image;
	struct wl_list link;

	struct wl_list frame_callback_list;

	struct {
		/* wl_surface.attach */
		int newly_attached;
		struct nested_buffer *buffer;
		struct wl_listener buffer_destroy_listener;

		/* wl_surface.frame */
		struct wl_list frame_callback_list;

		/* wl_surface.damage */
		pixman_region32_t damage;
	} pending;

	void *renderer_data;
};

/* Data used for the blit renderer */
struct nested_blit_surface {
	struct nested_buffer_reference buffer_ref;
	GLuint texture;
	cairo_surface_t *cairo_surface;
};

/* Data used for the subsurface renderer */
struct nested_ss_surface {
	struct widget *widget;
	struct wl_surface *surface;
	struct wl_subsurface *subsurface;
	struct wl_callback *frame_callback;
};

struct nested_frame_callback {
	struct wl_resource *resource;
	struct wl_list link;
};

struct nested_renderer {
	void (* surface_init)(struct nested_surface *surface);
	void (* surface_fini)(struct nested_surface *surface);
	void (* render_clients)(struct nested *nested, cairo_t *cr);
	void (* surface_attach)(struct nested_surface *surface,
				struct nested_buffer *buffer);
};

static const struct weston_option nested_options[] = {
	{ WESTON_OPTION_BOOLEAN, "blit", 'b', &option_blit },
};

static const struct nested_renderer nested_blit_renderer;
static const struct nested_renderer nested_ss_renderer;

static PFNGLEGLIMAGETARGETTEXTURE2DOESPROC image_target_texture_2d;
static PFNEGLCREATEIMAGEKHRPROC create_image;
static PFNEGLDESTROYIMAGEKHRPROC destroy_image;
static PFNEGLBINDWAYLANDDISPLAYWL bind_display;
static PFNEGLUNBINDWAYLANDDISPLAYWL unbind_display;
static PFNEGLQUERYWAYLANDBUFFERWL query_buffer;
static PFNEGLCREATEWAYLANDBUFFERFROMIMAGEWL create_wayland_buffer_from_image;

static void
nested_buffer_destroy_handler(struct wl_listener *listener, void *data)
{
	struct nested_buffer *buffer =
		container_of(listener, struct nested_buffer, destroy_listener);

	wl_signal_emit(&buffer->destroy_signal, buffer);

	if (buffer->parent_buffer)
		wl_buffer_destroy(buffer->parent_buffer);

	free(buffer);
}

static struct nested_buffer *
nested_buffer_from_resource(struct wl_resource *resource)
{
	struct nested_buffer *buffer;
	struct wl_listener *listener;

	listener =
		wl_resource_get_destroy_listener(resource,
						 nested_buffer_destroy_handler);

	if (listener)
		return container_of(listener, struct nested_buffer,
				    destroy_listener);

	buffer = zalloc(sizeof *buffer);
	if (buffer == NULL)
		return NULL;

	buffer->resource = resource;
	wl_signal_init(&buffer->destroy_signal);
	buffer->destroy_listener.notify = nested_buffer_destroy_handler;
	wl_resource_add_destroy_listener(resource, &buffer->destroy_listener);

	return buffer;
}

static void
nested_buffer_reference_handle_destroy(struct wl_listener *listener,
				       void *data)
{
	struct nested_buffer_reference *ref =
		container_of(listener, struct nested_buffer_reference,
			     destroy_listener);

	assert((struct nested_buffer *)data == ref->buffer);
	ref->buffer = NULL;
}

static void
nested_buffer_reference(struct nested_buffer_reference *ref,
			struct nested_buffer *buffer)
{
	if (buffer == ref->buffer)
		return;

	if (ref->buffer) {
		ref->buffer->busy_count--;
		if (ref->buffer->busy_count == 0) {
			assert(wl_resource_get_client(ref->buffer->resource));
			wl_resource_queue_event(ref->buffer->resource,
						WL_BUFFER_RELEASE);
		}
		wl_list_remove(&ref->destroy_listener.link);
	}

	if (buffer) {
		buffer->busy_count++;
		wl_signal_add(&buffer->destroy_signal,
			      &ref->destroy_listener);

		ref->destroy_listener.notify =
			nested_buffer_reference_handle_destroy;
	}

	ref->buffer = buffer;
}

static void
flush_surface_frame_callback_list(struct nested_surface *surface,
				  uint32_t time)
{
	struct nested_frame_callback *nc, *next;

	wl_list_for_each_safe(nc, next, &surface->frame_callback_list, link) {
		wl_callback_send_done(nc->resource, time);
		wl_resource_destroy(nc->resource);
	}
	wl_list_init(&surface->frame_callback_list);

	/* FIXME: toytoolkit need a pre-block handler where we can
	 * call this. */
	wl_display_flush_clients(surface->nested->child_display);
}

static void
redraw_handler(struct widget *widget, void *data)
{
	struct nested *nested = data;
	cairo_surface_t *surface;
	cairo_t *cr;
	struct rectangle allocation;

	widget_get_allocation(nested->widget, &allocation);

	surface = window_get_surface(nested->window);

	cr = cairo_create(surface);
	cairo_set_operator(cr, CAIRO_OPERATOR_SOURCE);
	cairo_rectangle(cr,
			allocation.x,
			allocation.y,
			allocation.width,
			allocation.height);
	cairo_set_source_rgba(cr, 0, 0, 0, 0.8);
	cairo_fill(cr);

	nested->renderer->render_clients(nested, cr);

	cairo_destroy(cr);

	cairo_surface_destroy(surface);
}

static void
keyboard_focus_handler(struct window *window,
		       struct input *device, void *data)
{
	struct nested *nested = data;

	window_schedule_redraw(nested->window);
}

static void
handle_child_data(struct task *task, uint32_t events)
{
	struct nested *nested = container_of(task, struct nested, child_task);
	struct wl_event_loop *loop;

	loop = wl_display_get_event_loop(nested->child_display);

	wl_event_loop_dispatch(loop, -1);
	wl_display_flush_clients(nested->child_display);
}

struct nested_client {
	struct wl_client *client;
	pid_t pid;
};

static struct nested_client *
launch_client(struct nested *nested, const char *path)
{
	int sv[2];
	pid_t pid;
	struct nested_client *client;

	client = malloc(sizeof *client);
	if (client == NULL)
		return NULL;

	if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0, sv) < 0) {
		fprintf(stderr, "launch_client: "
			"socketpair failed while launching '%s': %m\n",
			path);
		free(client);
		return NULL;
	}

	pid = fork();
	if (pid == -1) {
		close(sv[0]);
		close(sv[1]);
		free(client);
		fprintf(stderr, "launch_client: "
			"fork failed while launching '%s': %m\n", path);
		return NULL;
	}

	if (pid == 0) {
		int clientfd;
		char s[32];

		/* SOCK_CLOEXEC closes both ends, so we dup the fd to
		 * get a non-CLOEXEC fd to pass through exec. */
		clientfd = dup(sv[1]);
		if (clientfd == -1) {
			fprintf(stderr, "compositor: dup failed: %m\n");
			exit(-1);
		}

		snprintf(s, sizeof s, "%d", clientfd);
		setenv("WAYLAND_SOCKET", s, 1);

		execl(path, path, NULL);

		fprintf(stderr, "compositor: executing '%s' failed: %m\n",
			path);
		exit(-1);
	}

	close(sv[1]);

	client->client = wl_client_create(nested->child_display, sv[0]);
	if (!client->client) {
		close(sv[0]);
		free(client);
		fprintf(stderr, "launch_client: "
			"wl_client_create failed while launching '%s'.\n",
			path);
		return NULL;
	}

	client->pid = pid;

	return client;
}

static void
destroy_surface(struct wl_resource *resource)
{
	struct nested_surface *surface = wl_resource_get_user_data(resource);
	struct nested *nested = surface->nested;
	struct nested_frame_callback *cb, *next;

	wl_list_for_each_safe(cb, next,
			      &surface->frame_callback_list, link)
		wl_resource_destroy(cb->resource);

	wl_list_for_each_safe(cb, next,
			      &surface->pending.frame_callback_list, link)
		wl_resource_destroy(cb->resource);

	pixman_region32_fini(&surface->pending.damage);

	nested->renderer->surface_fini(surface);

	wl_list_remove(&surface->link);

	free(surface);
}

static void
surface_destroy(struct wl_client *client, struct wl_resource *resource)
{
	wl_resource_destroy(resource);
}

static void
surface_attach(struct wl_client *client,
	       struct wl_resource *resource,
	       struct wl_resource *buffer_resource, int32_t sx, int32_t sy)
{
	struct nested_surface *surface = wl_resource_get_user_data(resource);
	struct nested *nested = surface->nested;
	struct nested_buffer *buffer = NULL;

	if (buffer_resource) {
		int format;

		if (!query_buffer(nested->egl_display, (void *) buffer_resource,
				  EGL_TEXTURE_FORMAT, &format)) {
			wl_resource_post_error(buffer_resource,
					       WL_DISPLAY_ERROR_INVALID_OBJECT,
					       "attaching non-egl wl_buffer");
			return;
		}

		switch (format) {
		case EGL_TEXTURE_RGB:
		case EGL_TEXTURE_RGBA:
			break;
		default:
			wl_resource_post_error(buffer_resource,
					       WL_DISPLAY_ERROR_INVALID_OBJECT,
					       "invalid format");
			return;
		}

		buffer = nested_buffer_from_resource(buffer_resource);
		if (buffer == NULL) {
			wl_client_post_no_memory(client);
			return;
		}
	}

	if (surface->pending.buffer)
		wl_list_remove(&surface->pending.buffer_destroy_listener.link);

	surface->pending.buffer = buffer;
	surface->pending.newly_attached = 1;
	if (buffer) {
		wl_signal_add(&buffer->destroy_signal,
			      &surface->pending.buffer_destroy_listener);
	}
}

static void
nested_surface_attach(struct nested_surface *surface,
		      struct nested_buffer *buffer)
{
	struct nested *nested = surface->nested;

	if (surface->image != EGL_NO_IMAGE_KHR)
		destroy_image(nested->egl_display, surface->image);

	surface->image = create_image(nested->egl_display, NULL,
				      EGL_WAYLAND_BUFFER_WL, buffer->resource,
				      NULL);
	if (surface->image == EGL_NO_IMAGE_KHR) {
		fprintf(stderr, "failed to create img\n");
		return;
	}

	nested->renderer->surface_attach(surface, buffer);
}

static void
surface_damage(struct wl_client *client,
	       struct wl_resource *resource,
	       int32_t x, int32_t y, int32_t width, int32_t height)
{
	struct nested_surface *surface = wl_resource_get_user_data(resource);

	pixman_region32_union_rect(&surface->pending.damage,
				   &surface->pending.damage,
				   x, y, width, height);
}

static void
destroy_frame_callback(struct wl_resource *resource)
{
	struct nested_frame_callback *callback = wl_resource_get_user_data(resource);

	wl_list_remove(&callback->link);
	free(callback);
}

static void
surface_frame(struct wl_client *client,
	      struct wl_resource *resource, uint32_t id)
{
	struct nested_frame_callback *callback;
	struct nested_surface *surface = wl_resource_get_user_data(resource);

	callback = malloc(sizeof *callback);
	if (callback == NULL) {
		wl_resource_post_no_memory(resource);
		return;
	}

	callback->resource = wl_resource_create(client,
						&wl_callback_interface, 1, id);
	wl_resource_set_implementation(callback->resource, NULL, callback,
				       destroy_frame_callback);

	wl_list_insert(surface->pending.frame_callback_list.prev,
		       &callback->link);
}

static void
surface_set_opaque_region(struct wl_client *client,
			  struct wl_resource *resource,
			  struct wl_resource *region_resource)
{
	fprintf(stderr, "surface_set_opaque_region\n");
}

static void
surface_set_input_region(struct wl_client *client,
			 struct wl_resource *resource,
			 struct wl_resource *region_resource)
{
	fprintf(stderr, "surface_set_input_region\n");
}

static void
surface_commit(struct wl_client *client, struct wl_resource *resource)
{
	struct nested_surface *surface = wl_resource_get_user_data(resource);
	struct nested *nested = surface->nested;

	/* wl_surface.attach */
	if (surface->pending.newly_attached)
		nested_surface_attach(surface, surface->pending.buffer);

	if (surface->pending.buffer) {
		wl_list_remove(&surface->pending.buffer_destroy_listener.link);
		surface->pending.buffer = NULL;
	}
	surface->pending.newly_attached = 0;

	/* wl_surface.damage */
	pixman_region32_clear(&surface->pending.damage);

	/* wl_surface.frame */
	wl_list_insert_list(&surface->frame_callback_list,
			    &surface->pending.frame_callback_list);
	wl_list_init(&surface->pending.frame_callback_list);

	/* FIXME: For the subsurface renderer we don't need to
	 * actually redraw the window. However we do want to cause a
	 * commit because the subsurface is synchronized. Ideally we
	 * would just queue the commit */
	window_schedule_redraw(nested->window);
}

static void
surface_set_buffer_transform(struct wl_client *client,
			     struct wl_resource *resource, int transform)
{
	fprintf(stderr, "surface_set_buffer_transform\n");
}

static const struct wl_surface_interface surface_interface = {
	surface_destroy,
	surface_attach,
	surface_damage,
	surface_frame,
	surface_set_opaque_region,
	surface_set_input_region,
	surface_commit,
	surface_set_buffer_transform
};

static void
surface_handle_pending_buffer_destroy(struct wl_listener *listener, void *data)
{
	struct nested_surface *surface =
		container_of(listener, struct nested_surface,
			     pending.buffer_destroy_listener);

	surface->pending.buffer = NULL;
}

static void
compositor_create_surface(struct wl_client *client,
			  struct wl_resource *resource, uint32_t id)
{
	struct nested *nested = wl_resource_get_user_data(resource);
	struct nested_surface *surface;

	surface = zalloc(sizeof *surface);
	if (surface == NULL) {
		wl_resource_post_no_memory(resource);
		return;
	}

	surface->nested = nested;

	wl_list_init(&surface->frame_callback_list);

	wl_list_init(&surface->pending.frame_callback_list);
	surface->pending.buffer_destroy_listener.notify =
		surface_handle_pending_buffer_destroy;
	pixman_region32_init(&surface->pending.damage);

	display_acquire_window_surface(nested->display,
				       nested->window, NULL);

	nested->renderer->surface_init(surface);

	display_release_window_surface(nested->display, nested->window);

	surface->resource =
		wl_resource_create(client, &wl_surface_interface, 1, id);

	wl_resource_set_implementation(surface->resource,
				       &surface_interface, surface,
				       destroy_surface);

	wl_list_insert(nested->surface_list.prev, &surface->link);
}

static void
destroy_region(struct wl_resource *resource)
{
	struct nested_region *region = wl_resource_get_user_data(resource);

	pixman_region32_fini(&region->region);
	free(region);
}

static void
region_destroy(struct wl_client *client, struct wl_resource *resource)
{
	wl_resource_destroy(resource);
}

static void
region_add(struct wl_client *client, struct wl_resource *resource,
	   int32_t x, int32_t y, int32_t width, int32_t height)
{
	struct nested_region *region = wl_resource_get_user_data(resource);

	pixman_region32_union_rect(&region->region, &region->region,
				   x, y, width, height);
}

static void
region_subtract(struct wl_client *client, struct wl_resource *resource,
		int32_t x, int32_t y, int32_t width, int32_t height)
{
	struct nested_region *region = wl_resource_get_user_data(resource);
	pixman_region32_t rect;

	pixman_region32_init_rect(&rect, x, y, width, height);
	pixman_region32_subtract(&region->region, &region->region, &rect);
	pixman_region32_fini(&rect);
}

static const struct wl_region_interface region_interface = {
	region_destroy,
	region_add,
	region_subtract
};

static void
compositor_create_region(struct wl_client *client,
			 struct wl_resource *resource, uint32_t id)
{
	struct nested_region *region;

	region = malloc(sizeof *region);
	if (region == NULL) {
		wl_resource_post_no_memory(resource);
		return;
	}

	pixman_region32_init(&region->region);

	region->resource =
		wl_resource_create(client, &wl_region_interface, 1, id);
	wl_resource_set_implementation(region->resource, &region_interface,
				       region, destroy_region);
}

static const struct wl_compositor_interface compositor_interface = {
	compositor_create_surface,
	compositor_create_region
};

static void
compositor_bind(struct wl_client *client,
		void *data, uint32_t version, uint32_t id)
{
	struct nested *nested = data;
	struct wl_resource *resource;

	resource = wl_resource_create(client, &wl_compositor_interface,
				      MIN(version, 3), id);
	wl_resource_set_implementation(resource, &compositor_interface,
				       nested, NULL);
}

static int
nested_init_compositor(struct nested *nested)
{
	const char *extensions;
	struct wl_event_loop *loop;
	int use_ss_renderer = 0;
	int fd, ret;

	wl_list_init(&nested->surface_list);
	nested->child_display = wl_display_create();
	loop = wl_display_get_event_loop(nested->child_display);
	fd = wl_event_loop_get_fd(loop);
	nested->child_task.run = handle_child_data;
	display_watch_fd(nested->display, fd,
			 EPOLLIN, &nested->child_task);

	if (!wl_global_create(nested->child_display,
			      &wl_compositor_interface, 1,
			      nested, compositor_bind))
		return -1;

	wl_display_init_shm(nested->child_display);

	nested->egl_display = display_get_egl_display(nested->display);
	extensions = eglQueryString(nested->egl_display, EGL_EXTENSIONS);
	if (strstr(extensions, "EGL_WL_bind_wayland_display") == NULL) {
		fprintf(stderr, "no EGL_WL_bind_wayland_display extension\n");
		return -1;
	}

	bind_display = (void *) eglGetProcAddress("eglBindWaylandDisplayWL");
	unbind_display = (void *) eglGetProcAddress("eglUnbindWaylandDisplayWL");
	create_image = (void *) eglGetProcAddress("eglCreateImageKHR");
	destroy_image = (void *) eglGetProcAddress("eglDestroyImageKHR");
	query_buffer = (void *) eglGetProcAddress("eglQueryWaylandBufferWL");
	image_target_texture_2d =
		(void *) eglGetProcAddress("glEGLImageTargetTexture2DOES");

	ret = bind_display(nested->egl_display, nested->child_display);
	if (!ret) {
		fprintf(stderr, "failed to bind wl_display\n");
		return -1;
	}

	if (display_has_subcompositor(nested->display)) {
		const char *func = "eglCreateWaylandBufferFromImageWL";
		const char *ext = "EGL_WL_create_wayland_buffer_from_image";

		if (strstr(extensions, ext)) {
			create_wayland_buffer_from_image =
				(void *) eglGetProcAddress(func);
			use_ss_renderer = 1;
		}
	}

	if (option_blit)
		use_ss_renderer = 0;

	if (use_ss_renderer) {
		printf("Using subsurfaces to render client surfaces\n");
		nested->renderer = &nested_ss_renderer;
	} else {
		printf("Using local compositing with blits to "
		       "render client surfaces\n");
		nested->renderer = &nested_blit_renderer;
	}

	return 0;
}

static struct nested *
nested_create(struct display *display)
{
	struct nested *nested;

	nested = zalloc(sizeof *nested);
	if (nested == NULL)
		return nested;

	nested->window = window_create(display);
	nested->widget = window_frame_create(nested->window, nested);
	window_set_title(nested->window, "Wayland Nested");
	nested->display = display;

	window_set_user_data(nested->window, nested);
	widget_set_redraw_handler(nested->widget, redraw_handler);
	window_set_keyboard_focus_handler(nested->window,
					  keyboard_focus_handler);

	nested_init_compositor(nested);

	widget_schedule_resize(nested->widget, 400, 400);

	return nested;
}

static void
nested_destroy(struct nested *nested)
{
	widget_destroy(nested->widget);
	window_destroy(nested->window);
	free(nested);
}

/*** blit renderer ***/

static void
blit_surface_init(struct nested_surface *surface)
{
	struct nested_blit_surface *blit_surface =
		xzalloc(sizeof *blit_surface);

	glGenTextures(1, &blit_surface->texture);
	glBindTexture(GL_TEXTURE_2D, blit_surface->texture);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

	surface->renderer_data = blit_surface;
}

static void
blit_surface_fini(struct nested_surface *surface)
{
	struct nested_blit_surface *blit_surface = surface->renderer_data;

	nested_buffer_reference(&blit_surface->buffer_ref, NULL);

	glDeleteTextures(1, &blit_surface->texture);

	free(blit_surface);
}

static void
blit_frame_callback(void *data, struct wl_callback *callback, uint32_t time)
{
	struct nested *nested = data;
	struct nested_surface *surface;

	wl_list_for_each(surface, &nested->surface_list, link)
		flush_surface_frame_callback_list(surface, time);

	if (callback)
		wl_callback_destroy(callback);
}

static const struct wl_callback_listener blit_frame_listener = {
	blit_frame_callback
};

static void
blit_render_clients(struct nested *nested,
		    cairo_t *cr)
{
	struct nested_surface *s;
	struct rectangle allocation;
	struct wl_callback *callback;

	widget_get_allocation(nested->widget, &allocation);

	wl_list_for_each(s, &nested->surface_list, link) {
		struct nested_blit_surface *blit_surface = s->renderer_data;

		display_acquire_window_surface(nested->display,
					       nested->window, NULL);

		glBindTexture(GL_TEXTURE_2D, blit_surface->texture);
		image_target_texture_2d(GL_TEXTURE_2D, s->image);

		display_release_window_surface(nested->display,
					       nested->window);

		cairo_set_operator(cr, CAIRO_OPERATOR_OVER);
		cairo_set_source_surface(cr, blit_surface->cairo_surface,
					 allocation.x + 10,
					 allocation.y + 10);
		cairo_rectangle(cr, allocation.x + 10,
				allocation.y + 10,
				allocation.width - 10,
				allocation.height - 10);

		cairo_fill(cr);
	}

	callback = wl_surface_frame(window_get_wl_surface(nested->window));
	wl_callback_add_listener(callback, &blit_frame_listener, nested);
}

static void
blit_surface_attach(struct nested_surface *surface,
		    struct nested_buffer *buffer)
{
	struct nested *nested = surface->nested;
	struct nested_blit_surface *blit_surface = surface->renderer_data;
	EGLint width, height;
	cairo_device_t *device;

	nested_buffer_reference(&blit_surface->buffer_ref, buffer);

	if (blit_surface->cairo_surface)
		cairo_surface_destroy(blit_surface->cairo_surface);

	query_buffer(nested->egl_display, (void *) buffer->resource,
		     EGL_WIDTH, &width);
	query_buffer(nested->egl_display, (void *) buffer->resource,
		     EGL_HEIGHT, &height);

	device = display_get_cairo_device(nested->display);
	blit_surface->cairo_surface =
		cairo_gl_surface_create_for_texture(device,
						    CAIRO_CONTENT_COLOR_ALPHA,
						    blit_surface->texture,
						    width, height);
}

static const struct nested_renderer
nested_blit_renderer = {
	.surface_init = blit_surface_init,
	.surface_fini = blit_surface_fini,
	.render_clients = blit_render_clients,
	.surface_attach = blit_surface_attach
};

/*** subsurface renderer ***/

static void
ss_surface_init(struct nested_surface *surface)
{
	struct nested *nested = surface->nested;
	struct wl_compositor *compositor =
		display_get_compositor(nested->display);
	struct nested_ss_surface *ss_surface =
		xzalloc(sizeof *ss_surface);
	struct rectangle allocation;
	struct wl_region *region;

	ss_surface->widget =
		window_add_subsurface(nested->window,
				      nested,
				      SUBSURFACE_SYNCHRONIZED);

	widget_set_use_cairo(ss_surface->widget, 0);

	ss_surface->surface = widget_get_wl_surface(ss_surface->widget);
	ss_surface->subsurface = widget_get_wl_subsurface(ss_surface->widget);

	/* The toy toolkit gets confused about the pointer position
	 * when it gets motion events for a subsurface so we'll just
	 * disable input on it */
	region = wl_compositor_create_region(compositor);
	wl_surface_set_input_region(ss_surface->surface, region);
	wl_region_destroy(region);

	widget_get_allocation(nested->widget, &allocation);
	wl_subsurface_set_position(ss_surface->subsurface,
				   allocation.x + 10,
				   allocation.y + 10);

	surface->renderer_data = ss_surface;
}

static void
ss_surface_fini(struct nested_surface *surface)
{
	struct nested_ss_surface *ss_surface = surface->renderer_data;

	widget_destroy(ss_surface->widget);

	if (ss_surface->frame_callback)
		wl_callback_destroy(ss_surface->frame_callback);

	free(ss_surface);
}

static void
ss_render_clients(struct nested *nested,
		  cairo_t *cr)
{
	/* The clients are composited by the parent compositor so we
	 * don't need to do anything here */
}

static void
ss_buffer_release(void *data, struct wl_buffer *wl_buffer)
{
	struct nested_buffer *buffer = data;

	nested_buffer_reference(&buffer->parent_ref, NULL);
}

static struct wl_buffer_listener ss_buffer_listener = {
   ss_buffer_release
};

static void
ss_frame_callback(void *data, struct wl_callback *callback, uint32_t time)
{
	struct nested_surface *surface = data;
	struct nested_ss_surface *ss_surface = surface->renderer_data;

	flush_surface_frame_callback_list(surface, time);

	if (callback)
		wl_callback_destroy(callback);

	ss_surface->frame_callback = NULL;
}

static const struct wl_callback_listener ss_frame_listener = {
	ss_frame_callback
};

static void
ss_surface_attach(struct nested_surface *surface,
		  struct nested_buffer *buffer)
{
	struct nested *nested = surface->nested;
	struct nested_ss_surface *ss_surface = surface->renderer_data;
	struct wl_buffer *parent_buffer;
	const pixman_box32_t *rects;
	int n_rects, i;

	if (buffer) {
		/* Create a representation of the buffer in the parent
		 * compositor if we haven't already */
		if (buffer->parent_buffer == NULL) {
			EGLDisplay *edpy = nested->egl_display;
			EGLImageKHR image = surface->image;

			buffer->parent_buffer =
				create_wayland_buffer_from_image(edpy, image);

			wl_buffer_add_listener(buffer->parent_buffer,
					       &ss_buffer_listener,
					       buffer);
		}

		parent_buffer = buffer->parent_buffer;

		/* We'll take a reference to the buffer while the parent
		 * compositor is using it so that we won't report the release
		 * event until the parent has also finished with it */
		nested_buffer_reference(&buffer->parent_ref, buffer);
	} else {
		parent_buffer = NULL;
	}

	wl_surface_attach(ss_surface->surface, parent_buffer, 0, 0);

	rects = pixman_region32_rectangles(&surface->pending.damage, &n_rects);

	for (i = 0; i < n_rects; i++) {
		const pixman_box32_t *rect = rects + i;
		wl_surface_damage(ss_surface->surface,
				  rect->x1,
				  rect->y1,
				  rect->x2 - rect->x1,
				  rect->y2 - rect->y1);
	}

	if (ss_surface->frame_callback)
		wl_callback_destroy(ss_surface->frame_callback);

	ss_surface->frame_callback = wl_surface_frame(ss_surface->surface);
	wl_callback_add_listener(ss_surface->frame_callback,
				 &ss_frame_listener,
				 surface);

	wl_surface_commit(ss_surface->surface);
}

static const struct nested_renderer
nested_ss_renderer = {
	.surface_init = ss_surface_init,
	.surface_fini = ss_surface_fini,
	.render_clients = ss_render_clients,
	.surface_attach = ss_surface_attach
};

int
main(int argc, char *argv[])
{
	struct display *display;
	struct nested *nested;

	if (parse_options(nested_options,
			  ARRAY_LENGTH(nested_options), &argc, argv) > 1) {
		printf("Usage: %s [OPTIONS]\n  --blit or -b\n", argv[0]);
		exit(1);
	}

	display = display_create(&argc, argv);
	if (display == NULL) {
		fprintf(stderr, "failed to create display: %m\n");
		return -1;
	}

	nested = nested_create(display);

	launch_client(nested, "weston-nested-client");

	display_run(display);

	nested_destroy(nested);
	display_destroy(display);

	return 0;
}


text:
package org.innovateuk.ifs.finance.totals.mapper;

import org.innovateuk.ifs.finance.resource.ApplicationFinanceResource;
import org.innovateuk.ifs.finance.resource.category.DefaultCostCategory;
import org.innovateuk.ifs.finance.resource.category.FinanceRowCostCategory;
import org.innovateuk.ifs.finance.resource.cost.FinanceRowType;
import org.innovateuk.ifs.finance.resource.cost.Materials;
import org.innovateuk.ifs.finance.resource.cost.OtherCost;
import org.innovateuk.ifs.finance.resource.totals.FinanceCostTotalResource;
import org.innovateuk.ifs.finance.resource.totals.FinanceType;
import org.innovateuk.ifs.util.MapFunctions;
import org.junit.Before;
import org.junit.Test;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import static org.assertj.core.api.Assertions.assertThat;
import static org.innovateuk.ifs.finance.builder.ApplicationFinanceResourceBuilder.newApplicationFinanceResource;
import static org.innovateuk.ifs.finance.builder.DefaultCostCategoryBuilder.newDefaultCostCategory;
import static org.innovateuk.ifs.finance.builder.FinanceCostTotalResourceBuilder.newFinanceCostTotalResource;
import static org.innovateuk.ifs.finance.builder.MaterialsCostBuilder.newMaterials;
import static org.innovateuk.ifs.finance.builder.OtherCostBuilder.newOtherCost;

public class FinanceCostTotalResourceMapperTest {

    private FinanceCostTotalResourceMapper financeCostTotalResourceMapper;

    @Before
    public void init() {
        financeCostTotalResourceMapper = new FinanceCostTotalResourceMapper();
    }

    @Test
    public void mapFromApplicationFinanceResourceList() {
        Long financeId = 1L;

        OtherCost otherCost = newOtherCost()
                .withCost(BigDecimal.valueOf(1000)).build();
        DefaultCostCategory otherCostCategory = newDefaultCostCategory().withCosts(Arrays.asList(otherCost)).build();
        otherCostCategory.calculateTotal();

        Materials materialCost = newMaterials()
                .withCost(BigDecimal.valueOf(500))
                .withQuantity(10).build();
        DefaultCostCategory materialCostCategory = newDefaultCostCategory().withCosts(Arrays.asList(materialCost)).build();
        materialCostCategory.calculateTotal();

        Map<FinanceRowType, FinanceRowCostCategory> costs = MapFunctions.asMap(
                FinanceRowType.OTHER_COSTS, otherCostCategory,
                FinanceRowType.MATERIALS, materialCostCategory
        );

        ApplicationFinanceResource applicationFinanceResource = newApplicationFinanceResource()
                .withId(financeId)
                .withFinanceOrganisationDetails(costs).build();

        List<FinanceCostTotalResource> actualResult =
                financeCostTotalResourceMapper.mapFromApplicationFinanceResourceToList(applicationFinanceResource);

        FinanceCostTotalResource expectedOtherCostTotalResource = newFinanceCostTotalResource()
                .withFinanceType(FinanceType.APPLICATION)
                .withFinanceRowType(FinanceRowType.OTHER_COSTS)
                .withTotal(new BigDecimal(1000))
                .withFinanceId(financeId).build();

        FinanceCostTotalResource expectedMaterialCostTotalResource = newFinanceCostTotalResource()
                .withFinanceType(FinanceType.APPLICATION)
                .withFinanceRowType(FinanceRowType.MATERIALS)
                .withTotal(new BigDecimal(5000))
                .withFinanceId(financeId).build();

        assertThat(actualResult)
                .usingFieldByFieldElementComparator()
                .contains(expectedOtherCostTotalResource, expectedMaterialCostTotalResource);

    }

    @Test
    public void mapFromApplicationFinanceResourceListToList() {
        Long financeId = 1L;

        OtherCost otherCost = newOtherCost()
                .withCost(BigDecimal.valueOf(1000)).build();
        DefaultCostCategory otherCostCategory = newDefaultCostCategory().withCosts(Arrays.asList(otherCost)).build();
        otherCostCategory.calculateTotal();

        Materials materialCost = newMaterials()
                .withCost(BigDecimal.valueOf(500))
                .withQuantity(10).build();
        DefaultCostCategory materialCostCategory = newDefaultCostCategory().withCosts(Arrays.asList(materialCost)).build();
        materialCostCategory.calculateTotal();

        Map<FinanceRowType, FinanceRowCostCategory> costs = MapFunctions.asMap(
                FinanceRowType.OTHER_COSTS, otherCostCategory,
                FinanceRowType.MATERIALS, materialCostCategory
        );

        List<ApplicationFinanceResource> applicationFinanceResources = newApplicationFinanceResource()
                .withId(financeId)
                .withFinanceOrganisationDetails(costs).build(2);

        List<FinanceCostTotalResource> actualResult =
                financeCostTotalResourceMapper.mapFromApplicationFinanceResourceListToList(applicationFinanceResources);

        FinanceCostTotalResource expectedOtherCostTotalResource = newFinanceCostTotalResource()
                .withFinanceType(FinanceType.APPLICATION)
                .withFinanceRowType(FinanceRowType.OTHER_COSTS)
                .withTotal(new BigDecimal(1000))
                .withFinanceId(financeId).build();

        FinanceCostTotalResource expectedMaterialCostTotalResource = newFinanceCostTotalResource()
                .withFinanceType(FinanceType.APPLICATION)
                .withFinanceRowType(FinanceRowType.MATERIALS)
                .withTotal(new BigDecimal(5000))
                .withFinanceId(financeId).build();

        assertThat(actualResult).usingFieldByFieldElementComparator().contains(expectedOtherCostTotalResource,
                expectedMaterialCostTotalResource,
                expectedOtherCostTotalResource,
                expectedMaterialCostTotalResource);
    }
}


text:
require 'rails_helper'

describe ApplicationHelper, type: :helper do
  describe '#application_name' do
    it 'renders' do
      expect(helper.application_name).to be_present
    end
  end

  describe '#pretty_date_from_now' do
    it 'renders never if date is nil' do
      expect(helper.pretty_date_from_now(nil, 'flarg')).to eql 'flarg'
    end

    it 'adds "ago" on the end if it is in the past' do
      now = Time.now
      expect(Time).to receive(:now).at_least(:once).and_return(now)
      expect(helper.pretty_date_from_now(now - 10)).to eql 'less than a minute ago'
    end

    it 'prefixes "in" if it is in the future' do
      now = Time.now
      expect(Time).to receive(:now).at_least(:once).and_return(now)
      expect(helper.pretty_date_from_now(now + 10)).to eql 'in less than a minute'
    end
  end
end


text:
> Grunt plugin to list jshint eval warning suppressions in code

## Getting Started
This plugin requires Grunt `~0.4.2`

If you haven't used [Grunt](http://gruntjs.com/) before, be sure to check out the [Getting Started](http://gruntjs.com/getting-started) guide, as it explains how to create a [Gruntfile](http://gruntjs.com/sample-gruntfile) as well as install and use Grunt plugins. Once you're familiar with that process, you may install this plugin with this command:

```shell
npm install grunt-evil-list --save-dev
```

Once the plugin has been installed, it may be enabled inside your Gruntfile with this line of JavaScript:

```js
grunt.loadNpmTasks('grunt-evil-list');
```

## The "evilList" task

### Overview
In your project's Gruntfile, add a section named `evilList` to the data object passed into `grunt.initConfig()`.

```js
grunt.initConfig({
  evilList: {
    options: {
    	markdown: true|false
    },
    your_target: {
      // Target-specific file lists and/or options go here.
    },
  },
})
```

### Options

#### options.markdown
Type: `Boolean`
Default value: `false`

A boolea value that determines if markdown or plain text format report must be generated.

#### Default Options
In this example, the default options are used to do something with whatever. So if the `testing` file has the content `Testing` and the `123` file had the content `1 2 3`, the generated result would be `Testing, 1 2 3.`

```js
grunt.initConfig({
  evilList: {
    options: {},
    files: {
      'dest/default_options': ['src/testing', 'src/123'],
    },
  },
})
```

#### Custom Options
In this example, custom options are used to do something else with whatever else. So if the `testing` file has the content `Testing` and the `123` file had the content `1 2 3`, the generated result in this case would be `Testing: 1 2 3 !!!`

```js
grunt.initConfig({
  evilList: {
    options: {
      separator: ': ',
      punctuation: ' !!!',
    },
    files: {
      'dest/default_options': ['src/testing', 'src/123'],
    },
  },
})
```

## Contributing

## Release History
_(Nothing yet)_


text:
Conquer.bar do
  every(5.seconds) { Time.now }
  separator
  every(8.seconds) { %w(Hello World).sample }
  separator
  scroll do
    block { `mpc -w current`.chomp }
  end
end


text:
<tool id="bedtools_annotatebed" name="bedtools AnnotateBed" version="@TOOL_VERSION@">
    <description>annotate coverage of features from multiple files</description>
    <macros>
        <import>macros.xml</import>
    </macros>
    <expand macro="requirements" />
    <expand macro="stdio" />
    <command><![CDATA[
bedtools annotate
-i '${inputA}'
#if $names.names_select == 'yes':
    -files
    #for $bed in $names.beds:
        '${bed.input}'
    #end for

    -names
    #for $bed in $names.beds:
        '${bed.inputName}'
    #end for
#else:
    -files
    #for $bed in $names.beds:
        '$bed'
    #end for
    -names
    #for $bed in $names.beds:
        '${bed.display_name}'
    #end for
#end if
$strand
$counts
$both
> '${output}'
    ]]></command>
    <inputs>
        <param name="inputA" argument="-i" type="data" format="@STD_BEDTOOLS_INPUTS@" label="@STD_BEDTOOLS_INPUT_LABEL@ file" />
        <conditional name="names">
            <param name="names_select" type="select" label="Specify names for each file">
                <option value="no" selected="true">No</option>
                <option value="yes">Yes</option>
            </param>
            <when value="yes">
                <repeat name="beds" title="Add BED files and names" >
                    <param name="input" type="data" format="@STD_BEDTOOLS_INPUTS@" label="@STD_BEDTOOLS_INPUT_LABEL@ file" />
                    <param name="inputName" type="text" label="Name of the file" />
                </repeat>
            </when>
            <when value="no">
                <param name="beds" type="data" format="@STD_BEDTOOLS_INPUTS@" multiple="true" label="@STD_BEDTOOLS_INPUT_LABEL@ files" />
            </when>
        </conditional>
        <expand macro="strand2" />
        <param argument="-counts" type="boolean" truevalue="-counts" falsevalue="" checked="false"
            label="Report the count of features followed by the % coverage for each annotation file"
            help="Default is to report solely the fraction of -i covered by each file" />
        <param argument="-both" type="boolean" truevalue="-both" falsevalue="" checked="false"
            label="Report the count of features followed by the % coverage for each annotation file"
            help="Default is to report solely the fraction of the input file covered by each file" />
    </inputs>
    <outputs>
        <data name="output" format="bed" />
    </outputs>
    <tests>
        <test>
            <param name="inputA" value="annotateBed1.bed" ftype="bed" />
            <param name="names_select" value="no" />
            <param name="beds" value="annotateBed2.bed,annotateBed3.bed,annotateBed4.bed" />
            <output name="output" file="annotateBed_result.bed" ftype="bed" />
        </test>
    </tests>
    <help><![CDATA[
**What it does**

bedtools annotate, well, annotates one @STD_BEDTOOLS_INPUT_LABEL@ file with the coverage and number of overlaps observed from multiple other @STD_BEDTOOLS_INPUT_LABEL@ files. In this way, it allows one to ask to what degree one feature coincides with multiple other feature types with a single command.

@REFERENCES@
    ]]></help>
    <expand macro="citations" />
</tool>


text:
package org.springframework.security.oauth2.jwt;

import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.URL;
import java.util.Map;
import java.util.Set;

import com.nimbusds.jose.jwk.source.RemoteJWKSet;
import com.nimbusds.jose.proc.SecurityContext;

import org.springframework.security.oauth2.core.OAuth2TokenValidator;
import org.springframework.security.oauth2.jose.jws.SignatureAlgorithm;
import org.springframework.util.Assert;

/**
 * Allows creating a {@link JwtDecoder} from an OpenID
 * Provider Configuration or
 * Authorization Server Metadata
 * Request based on provided issuer and method invoked.
 *
 * @author Josh Cummings
 * @author Rafiullah Hamedy
 * @since 5.1
 */
public final class JwtDecoders {

	private JwtDecoders() {
	}

	/**
	 * Creates a {@link JwtDecoder} using the provided Issuer
	 * by making an OpenID
	 * Provider Configuration Request and using the values in the OpenID
	 * Provider Configuration Response to initialize the {@link JwtDecoder}.
	 * @param oidcIssuerLocation the Issuer
	 * @return a {@link JwtDecoder} that was initialized by the OpenID Provider
	 * Configuration.
	 */
	public static JwtDecoder fromOidcIssuerLocation(String oidcIssuerLocation) {
		Assert.hasText(oidcIssuerLocation, "oidcIssuerLocation cannot be empty");
		Map<String, Object> configuration = JwtDecoderProviderConfigurationUtils
				.getConfigurationForOidcIssuerLocation(oidcIssuerLocation);
		return withProviderConfiguration(configuration, oidcIssuerLocation);
	}

	/**
	 * Creates a {@link JwtDecoder} using the provided Issuer
	 * by querying three different discovery endpoints serially, using the values in the
	 * first successful response to initialize. If an endpoint returns anything other than
	 * a 200 or a 4xx, the method will exit without attempting subsequent endpoints.
	 *
	 * The three endpoints are computed as follows, given that the {@code issuer} is
	 * composed of a {@code host} and a {@code path}:
	 *
	 *

	 *
{@code host/.well-known/openid-configuration/path}, as defined in
	 * RFC 8414's Compatibility
	 * Notes.

	 *
{@code issuer/.well-known/openid-configuration}, as defined in
	 * OpenID Provider Configuration.

	 *
{@code host/.well-known/oauth-authorization-server/path}, as defined in
	 * Authorization Server
	 * Metadata Request.

	 *

	 *
	 * Note that the second endpoint is the equivalent of calling
	 * {@link JwtDecoders#fromOidcIssuerLocation(String)}
	 * @param issuer the Issuer
	 * @return a {@link JwtDecoder} that was initialized by one of the described endpoints
	 */
	public static JwtDecoder fromIssuerLocation(String issuer) {
		Assert.hasText(issuer, "issuer cannot be empty");
		Map<String, Object> configuration = JwtDecoderProviderConfigurationUtils
				.getConfigurationForIssuerLocation(issuer);
		return withProviderConfiguration(configuration, issuer);
	}

	/**
	 * Validate provided issuer and build {@link JwtDecoder} from OpenID
	 * Provider Configuration Response and
	 * Authorization Server
	 * Metadata Response.
	 * @param configuration the configuration values
	 * @param issuer the Issuer
	 * @return {@link JwtDecoder}
	 */
	private static JwtDecoder withProviderConfiguration(Map<String, Object> configuration, String issuer) {
		JwtDecoderProviderConfigurationUtils.validateIssuer(configuration, issuer);
		OAuth2TokenValidator<Jwt> jwtValidator = JwtValidators.createDefaultWithIssuer(issuer);
		String jwkSetUri = configuration.get("jwks_uri").toString();
		RemoteJWKSet<SecurityContext> jwkSource = new RemoteJWKSet<>(url(jwkSetUri));
		Set<SignatureAlgorithm> signatureAlgorithms = JwtDecoderProviderConfigurationUtils
				.getSignatureAlgorithms(jwkSource);
		NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withJwkSetUri(jwkSetUri)
				.jwsAlgorithms((algs) -> algs.addAll(signatureAlgorithms)).build();
		jwtDecoder.setJwtValidator(jwtValidator);
		return jwtDecoder;
	}

	private static URL url(String url) {
		try {
			return new URL(url);
		}
		catch (IOException ex) {
			throw new UncheckedIOException(ex);
		}
	}

}


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

#import "FRProofer.h"
#import "FRTranslator.h"

@interface FRProofer ()
- (NSString *)mostUsedLanguageFromArray:(NSArray *)languagesArray;
@end

@implementation FRProofer

@synthesize translator;

- (void)setClientId:(NSString *)clientId clientSecret:(NSString *)clientSecret {
	if (!self.translator) {
		self.translator = [[FRTranslator alloc] init];
	}
	self.translator.clientId = clientId;
	self.translator.clientSecret = clientSecret;
}

- (BOOL)setupAccessToken {
	return [self.translator getAccessToken];
}

- (void)proofFileFromPath:(NSString *)fromPath toPath:(NSString *)toPath {
	NSError *error = nil;
	NSStringEncoding encoding;

	NSString *contents = [NSString stringWithContentsOfFile:fromPath
											   usedEncoding:&encoding
													  error:&error];

	NSArray *lines = [contents componentsSeparatedByCharactersInSet:
					  [NSCharacterSet characterSetWithCharactersInString:@"\r\n"]];;

	if (!self.translator.language) {
		[self determineTranslatorLanguageUsingLines:lines];
	}

	NSMutableArray *originalStrings = [[NSMutableArray alloc] init];
	NSMutableArray *translatedStrings = [[NSMutableArray alloc] init];

	for (NSString *line in lines) {
		NSUInteger location = [line rangeOfString:@"/*"].location;
		if (location == NSNotFound && [line length] != 0) {
			[originalStrings addObject:[self leftSideOfStringsLine:line]];
			[translatedStrings addObject:[self rightSideOfStringsLine:line]];
		}
	}
	NSArray *proofedStrings = [translator translateArray:translatedStrings];

	NSString *outputString = @"/* Translation = Original = Proofed */\n";
	for (NSUInteger i = 0; i < [originalStrings count]; i++) {
		outputString = [outputString stringByAppendingFormat:@"\"%@\" = \"%@\" = \"%@\"\n",
						[translatedStrings objectAtIndex:i], [originalStrings objectAtIndex:i],
						[proofedStrings objectAtIndex:i]];
	}

	[outputString writeToFile:toPath atomically:YES encoding:NSUTF8StringEncoding error:NULL];
}

- (void)determineTranslatorLanguageUsingLines:(NSArray *)lines {
	if (!self.translator) { self.translator = [[FRTranslator alloc] init]; }

	// each translation takes up three lines. check the language of the first 5 lines to determine which language to
	// translate from
	NSArray *firstLines;
	if ([lines count] > 15) {
		NSRange firstTenLinesRange = { .location = 0, .length = 15 };
		firstLines = [lines subarrayWithRange:firstTenLinesRange];
	}
	else {
		firstLines = lines;
	}

	NSMutableArray *detectedLanguages = [[NSMutableArray alloc] init];
	for (NSString *line in firstLines) {
		NSString *translatedStringInLine = [self rightSideOfStringsLine:line];
		if (![translatedStringInLine isEqualToString:@""]) {
			NSString *detectedLanguage = [self.translator detectLanguageOfString:translatedStringInLine];
			[detectedLanguages addObject:detectedLanguage];
		}
	}

	self.translator.language = [self mostUsedLanguageFromArray:detectedLanguages];
}

- (NSString *)mostUsedLanguageFromArray:(NSArray *)languagesArray {
	NSMutableDictionary *languagesDict = [[NSMutableDictionary alloc] init];
	for (NSString *language in languagesArray) {
		[self incrementOccurrenceCountOfLanguage:language InDict:languagesDict];
	}

	NSString *mostUsedLanguage = [self mostUsedLanguageInDictionary:languagesDict];
	return mostUsedLanguage;
}

- (void)incrementOccurrenceCountOfLanguage:(NSString *)language InDict:(NSMutableDictionary *)languagesDict {
	NSNumber *numInstancesOfLanguage = [languagesDict objectForKey:language];
	if (numInstancesOfLanguage) {
		int intValue = [numInstancesOfLanguage intValue];
		intValue++;
		numInstancesOfLanguage = [NSNumber numberWithInt:intValue];
		[languagesDict setObject:numInstancesOfLanguage forKey:language];
	}
	else {
		[languagesDict setValue:[NSNumber numberWithInt:1] forKey:language];
	}
}

- (NSString *)mostUsedLanguageInDictionary:(NSDictionary *)dictionary {
	NSEnumerator *langEnumerator = [dictionary keyEnumerator];
	NSString *mostUsedLang = @"";
	NSNumber *mostOccurrences = [NSNumber numberWithInt:0];

	NSString *lang;
	while (lang = [langEnumerator nextObject]) {
		NSNumber *occurrencesOfLang = [dictionary valueForKey:lang];
		if ([occurrencesOfLang compare:mostOccurrences] == NSOrderedDescending) {
			mostUsedLang = lang;
			mostOccurrences = occurrencesOfLang;
		}
	}
	return mostUsedLang;
}

- (NSString *)leftSideOfStringsLine:(NSString *)line {
	NSString *leftSide = @"";
	NSArray *components = [line componentsSeparatedByString:@"\" = \""];
	NSCharacterSet *trim = [NSCharacterSet characterSetWithCharactersInString:@"\";"];
	if ([components count] == 2) {
			leftSide = [[components objectAtIndex:0] stringByTrimmingCharactersInSet:trim];
	}
	return leftSide;
}

- (NSString *)rightSideOfStringsLine:(NSString *)line {
	NSString *rightSide = @"";
	NSArray *components = [line componentsSeparatedByString:@"\" = \""];
	if ([components count] == 2) {
		NSCharacterSet *trim = [NSCharacterSet characterSetWithCharactersInString:@"\";"];
		rightSide = [[components objectAtIndex:1] stringByTrimmingCharactersInSet:trim];
	}
	return rightSide;
}

@end


text:
<?php

	/**
	 * LOCALISATION MANAGER
	 * for Symphony CMS
	 *
	 * Nils Hörrmann, http://www.nilshoerrmann.de
	 * Based on the Translation Manager class written by Marcin Konicki, http://ahwayakchih.neoni.net
	 */

	class LocalisationManager {

		private $_Sort;

		function __construct() {
			if(isset($_GET['sort'])) $this->_Sort = true;
		}

		public function buildDictionary($context, $lang, $name) {
			if(!$lang) $lang = 'en';

			// Get current translations
			$current = $this->getTranslations($context, $lang);
			if(empty($current)) {
				$current = array(
					'about' => array(
						'name' => ($name ? $name : 'New translation'),
						'author' => array(
							'name' => Administration::instance()->Author->getFullName(),
							'email' => Administration::instance()->Author->get('email'),
							'website' => ''
						),
					),
					'dictionary' => array(),
					'transliterations' => array()
				);
			}

			// Prepare current translations
			if($this->_Sort == true) ksort($current['dictionary']);
			foreach($current['dictionary'] as $key => $value) {
				if($value === false) unset($current['dictionary'][$key]);
			}

			// Get needed strings currently used by Symphony
			$strings = $this->getStrings($context);

			// Get transliterations
			$straight = array();
			$regexp = array();
			if($context == 'symphony') {
				$transliterations = $this->getTransliterations($current['transliterations']);

				// Group straight transliterations by type
				$type = null;
				foreach($transliterations['straight'] as $key => $transliteration) {
					switch($type) {
						case 'lowercase':
							$straight['lowercase'][$key] = $transliteration;
							if($key == ''n') $type = 'symbolic';
							break;
						case 'symbolic':
							$straight['symbolic'][$key] = $transliteration;
							if($key == '»') $type = 'special';
							break;
						case 'special':
							$straight['special'][$key] = $transliteration;
							if($key == 'º') $type = 'other';
							break;
						case 'other':
							$straight['other'][$key] = $transliteration;
							break;
						default:
							$straight['uppercase'][$key] = $transliteration;
							if($key == 'Þ') $type = 'lowercase';
							break;
					}
				}

				// Regular expression based transliterations – no grouping needed so far
				$type = null;
				foreach($transliterations['regexp'] as $key => $transliteration) {
					switch($type) {
						case 'other':
							$regexp['other'][$key] = $transliteration;
							break;
						default:
							$regexp['ampersands'][$key] = $transliteration;
							if($key == '/&(?!&)/') $type = 'other';
							break;
					}
				}
			}

			// Exclude core strings for extensions
			else {
				$core = $this->getStrings('symphony');
				$intersection = array_intersect_key($strings, $core);
				$strings = array_diff_key($strings, $intersection);
			}

			// Key compare function
			function key_compare_func($key1, $key2) {
				$key1 = stripslashes($key1);
				$key2 = stripslashes($key2);

				if($key1 == $key2) {
					return 0;
				}
				else if($key1 > $key2) {
					return 1;
				}
				else {
					return -1;
				}
			}

			// Extract namespaces
			$namespaces = array();
			foreach($current['dictionary'] as $namespace => $translations) {
				if(is_array($translations)) {

					// Check for existence of strings
					$namespaces[$namespace]['strings'] = array_intersect_key($translations, $current['dictionary']);
					$namespaces[$namespace]['obsolete'] = array_diff_ukey($translations, $current['dictionary'], "key_compare_func");

					// Remove namespaces from list of plain strings
					unset($current['dictionary'][$namespace]);
				}
			}

			// Return new dictionary
			return array(
				'about' => array(
					'name' => $current['about']['name'],
					'author' => array(
						'name' => $current['about']['author']['name'],
						'email' => $current['about']['author']['email'],
						'website' => $current['about']['author']['website']
					),
					'release-date' => date('Y-m-d')
				),
				'dictionary' => array(
					'strings' => array_intersect_key($current['dictionary'], $strings),
					'obsolete' => array_diff_ukey($current['dictionary'], $strings, "key_compare_func"),
					'missing' => array_diff_ukey($strings, $current['dictionary'], "key_compare_func"),
					'namespaces' => $namespaces
				),
				'transliterations' => array(
					'straight' => $straight,
					'regexp' => $regexp
				)
			);
		}

		public function getStrings($context) {

			// Set context path
			if($context == 'symphony') {
				$path = DOCROOT . '/symphony';
			}
			else {
				$path = EXTENSIONS . '/' . $context;
			}

			// Parse files
			$strings = $this->getFiles($path, array());
			$folders = General::listDirStructure($path);
			foreach($folders as $folder) {
				$strings = $this->getFiles($folder, $strings);
			}
			if(empty($strings) && $context != 'symphony') return array();

			// Get navigation and date string
			if($context == 'symphony') {
				$strings = array_merge($strings, $this->__findNavigationStrings());
				$strings = array_merge($strings, $this->__getDateStrings());
			}

			// Remove duplicated
			$strings = array_unique($strings);

			// Sort array
			if($this->_Sort == true) natcasesort($strings);

			// Generate correct keys and values
			$strings = array_combine(
				$strings,
				array_fill(0, count($strings), NULL)
			);

			// Return strings
			return $strings;
		}

		public function getFiles($folder, $strings) {

			// Get files
			$files = General::listStructure(preg_replace('{/$}', '', $folder), array('php', 'tpl', 'js'), false, 'asc', false);
			if(empty($files['filelist'])) {
				return $strings;
			}

			// Find strings
			foreach($files['filelist'] as $file) {
				if(pathinfo($file, PATHINFO_EXTENSION) == 'js') {
					$strings = array_merge($strings, $this->__findJavaScriptStrings($file));
				}
				else {
					$strings = array_merge($strings, $this->__findStrings($file));
				}
			}
			return $strings;
		}

		public function getTranslations($context, $lang) {

			// Get file
			if($context == 'symphony') {
				$languages = Lang::Languages();
				$file = vsprintf('%s/lang_%s/lang/lang.%s.php', array(
					EXTENSIONS, $languages[$lang]['handle'], $lang
				));
			}
			else {
				$file = EXTENSIONS . '/' . $context . '/lang/lang.' . $lang . '.php';
			}

			// Get translations
			if(!file_exists($file)) return false;
			include($file);
			if(is_array($dictionary)) ksort($dictionary);

			// Return strings
			return array(
				'about' => (is_array($about) ? $about : array()),
				'dictionary' => (is_array($dictionary) ? $dictionary : array()),
				'transliterations' => (is_array($transliterations) ? $transliterations : array()),
			);
		}

		public function getTransliterations($current) {
			include(LANG . '/transliterations.php');

			// Return transliterations
			if(!$current['straight']) {
				return $transliterations;
			}
			else {
				return array_merge($transliterations, $current);
			}
		}

		private function __findStrings($path) {
			if(!file_exists($path)) return false;

			// Get source
			$source = file_get_contents($path);

			/**
			 * Find all calls to the translation function, e. g. __('Your content here'):
			 * The regular expression searches for "__('TEXT'" and makes sure that the last ' is not escaped with \
			 * as this is used for apostrophs inside some language strings, e. g. __('Symphony\'s backend').
			 * It respects any whitespace character between the opening parenthesis and single quote.
			 * The regular expression respect the usage of single and double quote.
			 */
			preg_match_all("/__\(\s*(\"|')(.*)(?<!\\\\)\\1/U", $source, $strings);
			return $strings[2];
		}

		private function __findNavigationStrings() {

			// Get source
			$doc = new DOMDocument();
			$xml = $doc->load(ASSETS . '/navigation.xml');

			// Find navigation elements
			$xpath = new DOMXPath($doc);
			$items = $xpath->query("//*[not(@visible='no')]");

			// Get strings
			$strings = array();
			foreach($items as $item) {
				$string = $item->getAttribute('name');
				if($string) $strings[] = $string;
			}
			return $strings;
		}

		private function __findJavaScriptStrings($path) {

			// Get source
			$source = file_get_contents($path);

			// Extract language object
			preg_match_all("/Symphony.Language.add\({(.*)}\);/sU", $source, $objects);

			// Get strings
			$strings = array();
			foreach($objects[1] as $object) {
				preg_match_all("/.*(\"|')(.*)(\"|'): ?false,?/sU", $object, $result);
				$strings = array_merge($strings, $result[2]);
			}
			return $strings;
		}

		private function __getDateStrings() {
			include(LANG . '/datetime.php');

			// Return date and time strings
			return $datetime_strings;
		}

	}


text:
package org.publo.filebrowser.utils;

import java.io.InputStream;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;

/**
 * Application resources factory.
 *
 * @author Antonio Cucchiara
 * @since 0.2
 */
public class ResourceFactory {

    /**
     * Build an {@code ImageView} node to display on JavaFX components.
     *
     * @param classPathLocation of the resource
     * @return a JavaFX ImageView
     */
    public static ImageView buildImageView(final String classPathLocation) {
        final InputStream resourceStream = fetchResource(classPathLocation);
        final Image resourceImage = new Image(resourceStream);
        return new ImageView(resourceImage);
    }

    /**
     * Get a ClassPath Resource's {@code InputStream}.
     *
     * @param classpathLocation
     * @return the resource InputStream
     */
    private static InputStream fetchResource(final String classpathLocation) {
        return ResourceFactory.class.getResourceAsStream(classpathLocation);
    }
}


text:
from tests.base_case import ChatBotTestCase
from chatterbot.logic import MathematicalEvaluation
from chatterbot.conversation import Statement

class MathematicalEvaluationTests(ChatBotTestCase):

    def setUp(self):
        super().setUp()
        self.adapter = MathematicalEvaluation(self.chatbot)

    def test_can_process(self):
        statement = Statement(text='What is 10 + 10 + 10?')
        self.assertTrue(self.adapter.can_process(statement))

    def test_can_not_process(self):
        statement = Statement(text='What is your favorite song?')
        self.assertFalse(self.adapter.can_process(statement))

    def test_addition_operator(self):
        statement = Statement(text='What is 100 + 54?')
        response = self.adapter.process(statement)
        self.assertEqual(response.text, '100 + 54 = 154')
        self.assertEqual(response.confidence, 1)

    def test_subtraction_operator(self):
        statement = Statement(text='What is 100 - 58?')
        response = self.adapter.process(statement)
        self.assertEqual(response.text, '100 - 58 = 42')
        self.assertEqual(response.confidence, 1)

    def test_multiplication_operator(self):
        statement = Statement(text='What is 100 * 20')
        response = self.adapter.process(statement)
        self.assertEqual(response.text, '100 * 20 = 2000')
        self.assertEqual(response.confidence, 1)

    def test_division_operator(self):
        statement = Statement(text='What is 100 / 20')
        response = self.adapter.process(statement)

        self.assertEqual(response.text, '100 / 20 = 5')
        self.assertEqual(response.confidence, 1)

    def test_exponent_operator(self):
        statement = Statement(text='What is 2 ^ 10')
        response = self.adapter.process(statement)
        self.assertEqual(response.text, '2 ^ 10 = 1024')
        self.assertEqual(response.confidence, 1)

    def test_parenthesized_multiplication_and_addition(self):
        statement = Statement(text='What is 100 + ( 1000 * 2 )?')
        response = self.adapter.process(statement)
        self.assertEqual(response.text, '100 + ( 1000 * 2 ) = 2100')
        self.assertEqual(response.confidence, 1)

    def test_parenthesized_with_words(self):
        statement = Statement(text='What is four plus 100 + ( 100 * 2 )?')
        response = self.adapter.process(statement)
        self.assertEqual(response.text, 'four plus 100 + ( 100 * 2 ) = 304')
        self.assertEqual(response.confidence, 1)

    def test_word_numbers_addition(self):
        statement = Statement(text='What is one hundred + four hundred?')
        response = self.adapter.process(statement)
        self.assertEqual(response.text, 'one hundred + four hundred = 500')
        self.assertEqual(response.confidence, 1)

    def test_word_division_operator(self):
        statement = Statement(text='What is 100 divided by 100?')
        response = self.adapter.process(statement)

        self.assertEqual(response.text, '100 divided by 100 = 1')
        self.assertEqual(response.confidence, 1)

    def test_large_word_division_operator(self):
        statement = Statement(text='What is one thousand two hundred four divided by one hundred?')
        response = self.adapter.process(statement)

        self.assertEqual(response.text, 'one thousand two hundred four divided by one hundred = 12.04')

        self.assertEqual(response.confidence, 1)

    def test_negative_multiplication(self):
        statement = Statement(text='What is -105 * 5')
        response = self.adapter.process(statement)
        self.assertEqual(response.text, '-105 * 5 = -525')
        self.assertEqual(response.confidence, 1)

    def test_negative_decimal_multiplication(self):
        statement = Statement(text='What is -100.5 * 20?')
        response = self.adapter.process(statement)
        self.assertEqual(response.text, '-100.5 * 20 = -2010.0')
        self.assertEqual(response.confidence, 1)

    def test_pi_constant(self):
        statement = Statement(text='What is pi plus one ?')
        response = self.adapter.process(statement)
        self.assertEqual(response.text, 'pi plus one = 4.141693')
        self.assertEqual(response.confidence, 1)

    def test_e_constant(self):
        statement = Statement(text='What is e plus one ?')
        response = self.adapter.process(statement)
        self.assertEqual(response.text, 'e plus one = 3.718281')
        self.assertEqual(response.confidence, 1)

    def test_log_function(self):
        statement = Statement(text='What is log 100 ?')
        response = self.adapter.process(statement)
        self.assertEqual(response.text, 'log 100 = 2.0')
        self.assertEqual(response.confidence, 1)

    def test_square_root_function(self):
        statement = Statement(text='What is the sqrt 144 ?')
        response = self.adapter.process(statement)
        self.assertEqual(response.text, 'sqrt 144 = 12.0')
        self.assertEqual(response.confidence, 1)


text:
package org.vizzini.ai.geneticalgorithm.geneticprogramming.problem.cartcentering;

import java.util.Set;

import org.vizzini.ai.geneticalgorithm.geneticprogramming.Context;
import org.vizzini.ai.geneticalgorithm.geneticprogramming.DefaultContext;

/**
 * Provides a context for the cart centering problem.
 */
final class CartContext implements Context
{
    /** Delegate. */
    private final Context delegate = new DefaultContext();

    /**
     * Construct this object.
     *
     * @param x0 Initial position.
     * @param v0 Initial velocity.
     */
    public CartContext(final double x0, final double v0)
    {
        putVariable("time", 0.0);
        putVariable("x", x0);
        putVariable("v", v0);
    }

    /**
     * @return time
     */
    public Double getTime()
    {
        return (Double)getVariable("time");
    }

    /**
     * @return v
     */
    public Double getV()
    {
        return (Double)getVariable("v");
    }

    @Override
    public Object getVariable(final String name)
    {
        return delegate.getVariable(name);
    }

    @Override
    public Set<String> getVariableNames()
    {
        return delegate.getVariableNames();
    }

    /**
     * @return x
     */
    public Double getX()
    {
        return (Double)getVariable("x");
    }

    @Override
    public Context putVariable(final String name, final Object value)
    {
        return delegate.putVariable(name, value);
    }

    /**
     * @param time Value to set.
     */
    public void setTime(final Double time)
    {
        putVariable("time", time);
    }

    /**
     * @param v Value to set.
     */
    public void setV(final Double v)
    {
        putVariable("v", v);
    }

    /**
     * @param x Value to set.
     */
    public void setX(final Double x)
    {
        putVariable("x", x);
    }
}


text: export { default } from 'ui-bootstrap/components/ui-navbar';