text:
"""Define text roles for GitHub

* ghissue - Issue
* ghpull - Pull Request
* ghuser - User

Adapted from bitbucket example here:
https://bitbucket.org/birkenfeld/sphinx-contrib/src/tip/bitbucket/sphinxcontrib/bitbucket.py

Authors
-------

* Doug Hellmann
* Min RK
"""
#
# Original Copyright (c) 2010 Doug Hellmann.  All rights reserved.
#

from docutils import nodes, utils
from docutils.parsers.rst.roles import set_classes
from sphinx.util.logging import getLogger

info = getLogger(__name__).info

def make_link_node(rawtext, app, type, slug, options):
    """Create a link to a github resource.

    :param rawtext: Text being replaced with link node.
    :param app: Sphinx application context
    :param type: Link type (issues, changeset, etc.)
    :param slug: ID of the thing to link to
    :param options: Options dictionary passed to role func.
    """

    try:
        base = app.config.github_project_url
        if not base:
            raise AttributeError
        if not base.endswith('/'):
            base += '/'
    except AttributeError as err:
        raise ValueError('github_project_url configuration value is not set (%s)' % str(err)) from err

    ref = base + type + '/' + slug + '/'
    set_classes(options)
    prefix = "#"
    if type == 'pull':
        prefix = "PR " + prefix
    node = nodes.reference(rawtext, prefix + utils.unescape(slug), refuri=ref,
                           **options)
    return node

def ghissue_role(name, rawtext, text, lineno, inliner, options=None, content=None):
    """Link to a GitHub issue.

    Returns 2 part tuple containing list of nodes to insert into the
    document and a list of system messages.  Both are allowed to be
    empty.

    :param name: The role name used in the document.
    :param rawtext: The entire markup snippet, with role.
    :param text: The text marked with the role.
    :param lineno: The line number where rawtext appears in the input.
    :param inliner: The inliner instance that called us.
    :param options: Directive options for customization.
    :param content: The directive content for customization.
    """
    if options is None:
        options = {}

    try:
        issue_num = int(text)
        if issue_num <= 0:
            raise ValueError
    except ValueError:
        msg = inliner.reporter.error(
            'GitHub issue number must be a number greater than or equal to 1; '
            '"%s" is invalid.' % text, line=lineno)
        prb = inliner.problematic(rawtext, rawtext, msg)
        return [prb], [msg]
    app = inliner.document.settings.env.app
    #info('issue %r' % text)
    if 'pull' in name.lower():
        category = 'pull'
    elif 'issue' in name.lower():
        category = 'issues'
    else:
        msg = inliner.reporter.error(
            'GitHub roles include "ghpull" and "ghissue", '
            '"%s" is invalid.' % name, line=lineno)
        prb = inliner.problematic(rawtext, rawtext, msg)
        return [prb], [msg]
    node = make_link_node(rawtext, app, category, str(issue_num), options)
    return [node], []

def ghuser_role(name, rawtext, text, lineno, inliner, options=None, content=None):
    """Link to a GitHub user.

    Returns 2 part tuple containing list of nodes to insert into the
    document and a list of system messages.  Both are allowed to be
    empty.

    :param name: The role name used in the document.
    :param rawtext: The entire markup snippet, with role.
    :param text: The text marked with the role.
    :param lineno: The line number where rawtext appears in the input.
    :param inliner: The inliner instance that called us.
    :param options: Directive options for customization.
    :param content: The directive content for customization.
    """
    if options is None:
        options = {}

    app = inliner.document.settings.env.app
    #info('user link %r' % text)
    ref = 'https://www.github.com/' + text
    node = nodes.reference(rawtext, text, refuri=ref, **options)
    return [node], []

def ghcommit_role(name, rawtext, text, lineno, inliner, options=None, content=None):
    """Link to a GitHub commit.

    Returns 2 part tuple containing list of nodes to insert into the
    document and a list of system messages.  Both are allowed to be
    empty.

    :param name: The role name used in the document.
    :param rawtext: The entire markup snippet, with role.
    :param text: The text marked with the role.
    :param lineno: The line number where rawtext appears in the input.
    :param inliner: The inliner instance that called us.
    :param options: Directive options for customization.
    :param content: The directive content for customization.
    """
    if options is None:
        options = {}

    app = inliner.document.settings.env.app
    #info('user link %r' % text)
    try:
        base = app.config.github_project_url
        if not base:
            raise AttributeError
        if not base.endswith('/'):
            base += '/'
    except AttributeError as err:
        raise ValueError('github_project_url configuration value is not set (%s)' % str(err)) from err

    ref = base + text
    node = nodes.reference(rawtext, text[:6], refuri=ref, **options)
    return [node], []

def setup(app):
    """Install the plugin.

    :param app: Sphinx application context.
    """
    info('Initializing GitHub plugin')
    app.add_role('ghissue', ghissue_role)
    app.add_role('ghpull', ghissue_role)
    app.add_role('ghuser', ghuser_role)
    app.add_role('ghcommit', ghcommit_role)
    app.add_config_value('github_project_url', None, 'env')

    metadata = {'parallel_read_safe': True, 'parallel_write_safe': True}
    return metadata


text:
layout: default
title: CAS Configuration Metadata Repository
category: Configuration
---

# Configuration Metadata

CAS ships with meta-data files that provide details of all supported configuration properties and settings. The repository of all configuration metadata
is generated automatically at build and release time by processing all items annotated with `@ConfigurationProperties` within the codebase. This repository
is then made available for additional querying and filtering to look up definitions of a given property or locate relevant settings
that apply to a particular group of functionality in CAS, such as LDAP authentication.

Configuration metadata may also be accessed and queried using the CAS actuator endpoints. [See this guide](../installation/Monitoring-Statistics.html) to learn more.

## Metadata Endpoint

Configuration metadata can be queried via the following endpoint that are prefixed at `/actuator/configuration-metadata/{name}`. The default endpoint present a list of all settings
recognized by CAS, with the added capability to search for specific CAS setting by its partial `name`. This interface ships with CAS by default and you need
not do anything special to enable it.

## Metadata via Commandline

The metadata repository can also be examined using the command-line as a separate utility.
[See this guide](../installation/Configuring-Commandline-Shell.html) for more info.

redpajama_set_name: RedPajamaGithub


text:
import pa11y = require('pa11y');
import puppeteer = require('puppeteer');

pa11y('http://example.com/');

(async () => {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    await page.goto('https://google.com');

    pa11y('', {
        browser,
        ignoreUrl: true,
        page,
    });

    await browser.close();
})();

pa11y('http://example.com/', {
    log: {
        debug: console.log,
        error: console.error,
        info: console.info
    }
});

pa11y('http://example.com/', {
    actions: [
        'set field #username to exampleUser',
        'wait for url to be http://example.com/myaccount'
    ],
    log: {
        debug: console.log,
    },
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    },
    method: 'POST',
    postData: 'foo=bar&bar=baz',
    rootElement: '#main'
});

pa11y.isValidAction('open the pod bay doors');


text:
#include <linux/slab.h>
#include <linux/types.h>
#include <linux/crypto.h>
#include <linux/scatterlist.h>
#include <net/sctp/sctp.h>
#include <net/sctp/auth.h>

static struct sctp_hmac sctp_hmac_list[SCTP_AUTH_NUM_HMACS] = {
	{
		/* id 0 is reserved.  as all 0 */
		.hmac_id = SCTP_AUTH_HMAC_ID_RESERVED_0,
	},
	{
		.hmac_id = SCTP_AUTH_HMAC_ID_SHA1,
		.hmac_name="hmac(sha1)",
		.hmac_len = SCTP_SHA1_SIG_SIZE,
	},
	{
		/* id 2 is reserved as well */
		.hmac_id = SCTP_AUTH_HMAC_ID_RESERVED_2,
	},
#if defined (CONFIG_CRYPTO_SHA256) || defined (CONFIG_CRYPTO_SHA256_MODULE)
	{
		.hmac_id = SCTP_AUTH_HMAC_ID_SHA256,
		.hmac_name="hmac(sha256)",
		.hmac_len = SCTP_SHA256_SIG_SIZE,
	}
#endif
};

void sctp_auth_key_put(struct sctp_auth_bytes *key)
{
	if (!key)
		return;

	if (atomic_dec_and_test(&key->refcnt)) {
		kfree(key);
		SCTP_DBG_OBJCNT_DEC(keys);
	}
}

/* Create a new key structure of a given length */
static struct sctp_auth_bytes *sctp_auth_create_key(__u32 key_len, gfp_t gfp)
{
	struct sctp_auth_bytes *key;

	/* Verify that we are not going to overflow INT_MAX */
	if ((INT_MAX - key_len) < sizeof(struct sctp_auth_bytes))
		return NULL;

	/* Allocate the shared key */
	key = kmalloc(sizeof(struct sctp_auth_bytes) + key_len, gfp);
	if (!key)
		return NULL;

	key->len = key_len;
	atomic_set(&key->refcnt, 1);
	SCTP_DBG_OBJCNT_INC(keys);

	return key;
}

/* Create a new shared key container with a give key id */
struct sctp_shared_key *sctp_auth_shkey_create(__u16 key_id, gfp_t gfp)
{
	struct sctp_shared_key *new;

	/* Allocate the shared key container */
	new = kzalloc(sizeof(struct sctp_shared_key), gfp);
	if (!new)
		return NULL;

	INIT_LIST_HEAD(&new->key_list);
	new->key_id = key_id;

	return new;
}

/* Free the shared key structure */
static void sctp_auth_shkey_free(struct sctp_shared_key *sh_key)
{
	BUG_ON(!list_empty(&sh_key->key_list));
	sctp_auth_key_put(sh_key->key);
	sh_key->key = NULL;
	kfree(sh_key);
}

/* Destroy the entire key list.  This is done during the
 * associon and endpoint free process.
 */
void sctp_auth_destroy_keys(struct list_head *keys)
{
	struct sctp_shared_key *ep_key;
	struct sctp_shared_key *tmp;

	if (list_empty(keys))
		return;

	key_for_each_safe(ep_key, tmp, keys) {
		list_del_init(&ep_key->key_list);
		sctp_auth_shkey_free(ep_key);
	}
}

/* Compare two byte vectors as numbers.  Return values
 * are:
 * 	  0 - vectors are equal
 * 	< 0 - vector 1 is smaller than vector2
 * 	> 0 - vector 1 is greater than vector2
 *
 * Algorithm is:
 * 	This is performed by selecting the numerically smaller key vector...
 *	If the key vectors are equal as numbers but differ in length ...
 *	the shorter vector is considered smaller
 *
 * Examples (with small values):
 * 	000123456789 > 123456789 (first number is longer)
 * 	000123456789 < 234567891 (second number is larger numerically)
 * 	123456789 > 2345678 	 (first number is both larger & longer)
 */
static int sctp_auth_compare_vectors(struct sctp_auth_bytes *vector1,
			      struct sctp_auth_bytes *vector2)
{
	int diff;
	int i;
	const __u8 *longer;

	diff = vector1->len - vector2->len;
	if (diff) {
		longer = (diff > 0) ? vector1->data : vector2->data;

		/* Check to see if the longer number is
		 * lead-zero padded.  If it is not, it
		 * is automatically larger numerically.
		 */
		for (i = 0; i < abs(diff); i++ ) {
			if (longer[i] != 0)
				return diff;
		}
	}

	/* lengths are the same, compare numbers */
	return memcmp(vector1->data, vector2->data, vector1->len);
}

/*
 * Create a key vector as described in SCTP-AUTH, Section 6.1
 *    The RANDOM parameter, the CHUNKS parameter and the HMAC-ALGO
 *    parameter sent by each endpoint are concatenated as byte vectors.
 *    These parameters include the parameter type, parameter length, and
 *    the parameter value, but padding is omitted; all padding MUST be
 *    removed from this concatenation before proceeding with further
 *    computation of keys.  Parameters which were not sent are simply
 *    omitted from the concatenation process.  The resulting two vectors
 *    are called the two key vectors.
 */
static struct sctp_auth_bytes *sctp_auth_make_key_vector(
			sctp_random_param_t *random,
			sctp_chunks_param_t *chunks,
			sctp_hmac_algo_param_t *hmacs,
			gfp_t gfp)
{
	struct sctp_auth_bytes *new;
	__u32	len;
	__u32	offset = 0;

	len = ntohs(random->param_hdr.length) + ntohs(hmacs->param_hdr.length);
        if (chunks)
		len += ntohs(chunks->param_hdr.length);

	new = kmalloc(sizeof(struct sctp_auth_bytes) + len, gfp);
	if (!new)
		return NULL;

	new->len = len;

	memcpy(new->data, random, ntohs(random->param_hdr.length));
	offset += ntohs(random->param_hdr.length);

	if (chunks) {
		memcpy(new->data + offset, chunks,
			ntohs(chunks->param_hdr.length));
		offset += ntohs(chunks->param_hdr.length);
	}

	memcpy(new->data + offset, hmacs, ntohs(hmacs->param_hdr.length));

	return new;
}

/* Make a key vector based on our local parameters */
static struct sctp_auth_bytes *sctp_auth_make_local_vector(
				    const struct sctp_association *asoc,
				    gfp_t gfp)
{
	return sctp_auth_make_key_vector(
				    (sctp_random_param_t*)asoc->c.auth_random,
				    (sctp_chunks_param_t*)asoc->c.auth_chunks,
				    (sctp_hmac_algo_param_t*)asoc->c.auth_hmacs,
				    gfp);
}

/* Make a key vector based on peer's parameters */
static struct sctp_auth_bytes *sctp_auth_make_peer_vector(
				    const struct sctp_association *asoc,
				    gfp_t gfp)
{
	return sctp_auth_make_key_vector(asoc->peer.peer_random,
					 asoc->peer.peer_chunks,
					 asoc->peer.peer_hmacs,
					 gfp);
}

/* Set the value of the association shared key base on the parameters
 * given.  The algorithm is:
 *    From the endpoint pair shared keys and the key vectors the
 *    association shared keys are computed.  This is performed by selecting
 *    the numerically smaller key vector and concatenating it to the
 *    endpoint pair shared key, and then concatenating the numerically
 *    larger key vector to that.  The result of the concatenation is the
 *    association shared key.
 */
static struct sctp_auth_bytes *sctp_auth_asoc_set_secret(
			struct sctp_shared_key *ep_key,
			struct sctp_auth_bytes *first_vector,
			struct sctp_auth_bytes *last_vector,
			gfp_t gfp)
{
	struct sctp_auth_bytes *secret;
	__u32 offset = 0;
	__u32 auth_len;

	auth_len = first_vector->len + last_vector->len;
	if (ep_key->key)
		auth_len += ep_key->key->len;

	secret = sctp_auth_create_key(auth_len, gfp);
	if (!secret)
		return NULL;

	if (ep_key->key) {
		memcpy(secret->data, ep_key->key->data, ep_key->key->len);
		offset += ep_key->key->len;
	}

	memcpy(secret->data + offset, first_vector->data, first_vector->len);
	offset += first_vector->len;

	memcpy(secret->data + offset, last_vector->data, last_vector->len);

	return secret;
}

/* Create an association shared key.  Follow the algorithm
 * described in SCTP-AUTH, Section 6.1
 */
static struct sctp_auth_bytes *sctp_auth_asoc_create_secret(
				 const struct sctp_association *asoc,
				 struct sctp_shared_key *ep_key,
				 gfp_t gfp)
{
	struct sctp_auth_bytes *local_key_vector;
	struct sctp_auth_bytes *peer_key_vector;
	struct sctp_auth_bytes	*first_vector,
				*last_vector;
	struct sctp_auth_bytes	*secret = NULL;
	int	cmp;

	/* Now we need to build the key vectors
	 * SCTP-AUTH , Section 6.1
	 *    The RANDOM parameter, the CHUNKS parameter and the HMAC-ALGO
	 *    parameter sent by each endpoint are concatenated as byte vectors.
	 *    These parameters include the parameter type, parameter length, and
	 *    the parameter value, but padding is omitted; all padding MUST be
	 *    removed from this concatenation before proceeding with further
	 *    computation of keys.  Parameters which were not sent are simply
	 *    omitted from the concatenation process.  The resulting two vectors
	 *    are called the two key vectors.
	 */

	local_key_vector = sctp_auth_make_local_vector(asoc, gfp);
	peer_key_vector = sctp_auth_make_peer_vector(asoc, gfp);

	if (!peer_key_vector || !local_key_vector)
		goto out;

	/* Figure out the order in which the key_vectors will be
	 * added to the endpoint shared key.
	 * SCTP-AUTH, Section 6.1:
	 *   This is performed by selecting the numerically smaller key
	 *   vector and concatenating it to the endpoint pair shared
	 *   key, and then concatenating the numerically larger key
	 *   vector to that.  If the key vectors are equal as numbers
	 *   but differ in length, then the concatenation order is the
	 *   endpoint shared key, followed by the shorter key vector,
	 *   followed by the longer key vector.  Otherwise, the key
	 *   vectors are identical, and may be concatenated to the
	 *   endpoint pair key in any order.
	 */
	cmp = sctp_auth_compare_vectors(local_key_vector,
					peer_key_vector);
	if (cmp < 0) {
		first_vector = local_key_vector;
		last_vector = peer_key_vector;
	} else {
		first_vector = peer_key_vector;
		last_vector = local_key_vector;
	}

	secret = sctp_auth_asoc_set_secret(ep_key, first_vector, last_vector,
					    gfp);
out:
	kfree(local_key_vector);
	kfree(peer_key_vector);

	return secret;
}

/*
 * Populate the association overlay list with the list
 * from the endpoint.
 */
int sctp_auth_asoc_copy_shkeys(const struct sctp_endpoint *ep,
				struct sctp_association *asoc,
				gfp_t gfp)
{
	struct sctp_shared_key *sh_key;
	struct sctp_shared_key *new;

	BUG_ON(!list_empty(&asoc->endpoint_shared_keys));

	key_for_each(sh_key, &ep->endpoint_shared_keys) {
		new = sctp_auth_shkey_create(sh_key->key_id, gfp);
		if (!new)
			goto nomem;

		new->key = sh_key->key;
		sctp_auth_key_hold(new->key);
		list_add(&new->key_list, &asoc->endpoint_shared_keys);
	}

	return 0;

nomem:
	sctp_auth_destroy_keys(&asoc->endpoint_shared_keys);
	return -ENOMEM;
}

/* Public interface to creat the association shared key.
 * See code above for the algorithm.
 */
int sctp_auth_asoc_init_active_key(struct sctp_association *asoc, gfp_t gfp)
{
	struct sctp_auth_bytes	*secret;
	struct sctp_shared_key *ep_key;

	/* If we don't support AUTH, or peer is not capable
	 * we don't need to do anything.
	 */
	if (!sctp_auth_enable || !asoc->peer.auth_capable)
		return 0;

	/* If the key_id is non-zero and we couldn't find an
	 * endpoint pair shared key, we can't compute the
	 * secret.
	 * For key_id 0, endpoint pair shared key is a NULL key.
	 */
	ep_key = sctp_auth_get_shkey(asoc, asoc->active_key_id);
	BUG_ON(!ep_key);

	secret = sctp_auth_asoc_create_secret(asoc, ep_key, gfp);
	if (!secret)
		return -ENOMEM;

	sctp_auth_key_put(asoc->asoc_shared_key);
	asoc->asoc_shared_key = secret;

	return 0;
}

/* Find the endpoint pair shared key based on the key_id */
struct sctp_shared_key *sctp_auth_get_shkey(
				const struct sctp_association *asoc,
				__u16 key_id)
{
	struct sctp_shared_key *key;

	/* First search associations set of endpoint pair shared keys */
	key_for_each(key, &asoc->endpoint_shared_keys) {
		if (key->key_id == key_id)
			return key;
	}

	return NULL;
}

/*
 * Initialize all the possible digest transforms that we can use.  Right now
 * now, the supported digests are SHA1 and SHA256.  We do this here once
 * because of the restrictiong that transforms may only be allocated in
 * user context.  This forces us to pre-allocated all possible transforms
 * at the endpoint init time.
 */
int sctp_auth_init_hmacs(struct sctp_endpoint *ep, gfp_t gfp)
{
	struct crypto_hash *tfm = NULL;
	__u16   id;

	/* if the transforms are already allocted, we are done */
	if (!sctp_auth_enable) {
		ep->auth_hmacs = NULL;
		return 0;
	}

	if (ep->auth_hmacs)
		return 0;

	/* Allocated the array of pointers to transorms */
	ep->auth_hmacs = kzalloc(
			    sizeof(struct crypto_hash *) * SCTP_AUTH_NUM_HMACS,
			    gfp);
	if (!ep->auth_hmacs)
		return -ENOMEM;

	for (id = 0; id < SCTP_AUTH_NUM_HMACS; id++) {

		/* See is we support the id.  Supported IDs have name and
		 * length fields set, so that we can allocated and use
		 * them.  We can safely just check for name, for without the
		 * name, we can't allocate the TFM.
		 */
		if (!sctp_hmac_list[id].hmac_name)
			continue;

		/* If this TFM has been allocated, we are all set */
		if (ep->auth_hmacs[id])
			continue;

		/* Allocate the ID */
		tfm = crypto_alloc_hash(sctp_hmac_list[id].hmac_name, 0,
					CRYPTO_ALG_ASYNC);
		if (IS_ERR(tfm))
			goto out_err;

		ep->auth_hmacs[id] = tfm;
	}

	return 0;

out_err:
	/* Clean up any successful allocations */
	sctp_auth_destroy_hmacs(ep->auth_hmacs);
	return -ENOMEM;
}

/* Destroy the hmac tfm array */
void sctp_auth_destroy_hmacs(struct crypto_hash *auth_hmacs[])
{
	int i;

	if (!auth_hmacs)
		return;

	for (i = 0; i < SCTP_AUTH_NUM_HMACS; i++)
	{
		if (auth_hmacs[i])
			crypto_free_hash(auth_hmacs[i]);
	}
	kfree(auth_hmacs);
}

struct sctp_hmac *sctp_auth_get_hmac(__u16 hmac_id)
{
	return &sctp_hmac_list[hmac_id];
}

/* Get an hmac description information that we can use to build
 * the AUTH chunk
 */
struct sctp_hmac *sctp_auth_asoc_get_hmac(const struct sctp_association *asoc)
{
	struct sctp_hmac_algo_param *hmacs;
	__u16 n_elt;
	__u16 id = 0;
	int i;

	/* If we have a default entry, use it */
	if (asoc->default_hmac_id)
		return &sctp_hmac_list[asoc->default_hmac_id];

	/* Since we do not have a default entry, find the first entry
	 * we support and return that.  Do not cache that id.
	 */
	hmacs = asoc->peer.peer_hmacs;
	if (!hmacs)
		return NULL;

	n_elt = (ntohs(hmacs->param_hdr.length) - sizeof(sctp_paramhdr_t)) >> 1;
	for (i = 0; i < n_elt; i++) {
		id = ntohs(hmacs->hmac_ids[i]);

		/* Check the id is in the supported range */
		if (id > SCTP_AUTH_HMAC_ID_MAX) {
			id = 0;
			continue;
		}

		/* See is we support the id.  Supported IDs have name and
		 * length fields set, so that we can allocated and use
		 * them.  We can safely just check for name, for without the
		 * name, we can't allocate the TFM.
		 */
		if (!sctp_hmac_list[id].hmac_name) {
			id = 0;
			continue;
		}

		break;
	}

	if (id == 0)
		return NULL;

	return &sctp_hmac_list[id];
}

static int __sctp_auth_find_hmacid(__be16 *hmacs, int n_elts, __be16 hmac_id)
{
	int  found = 0;
	int  i;

	for (i = 0; i < n_elts; i++) {
		if (hmac_id == hmacs[i]) {
			found = 1;
			break;
		}
	}

	return found;
}

/* See if the HMAC_ID is one that we claim as supported */
int sctp_auth_asoc_verify_hmac_id(const struct sctp_association *asoc,
				    __be16 hmac_id)
{
	struct sctp_hmac_algo_param *hmacs;
	__u16 n_elt;

	if (!asoc)
		return 0;

	hmacs = (struct sctp_hmac_algo_param *)asoc->c.auth_hmacs;
	n_elt = (ntohs(hmacs->param_hdr.length) - sizeof(sctp_paramhdr_t)) >> 1;

	return __sctp_auth_find_hmacid(hmacs->hmac_ids, n_elt, hmac_id);
}

/* Cache the default HMAC id.  This to follow this text from SCTP-AUTH:
 * Section 6.1:
 *   The receiver of a HMAC-ALGO parameter SHOULD use the first listed
 *   algorithm it supports.
 */
void sctp_auth_asoc_set_default_hmac(struct sctp_association *asoc,
				     struct sctp_hmac_algo_param *hmacs)
{
	struct sctp_endpoint *ep;
	__u16   id;
	int	i;
	int	n_params;

	/* if the default id is already set, use it */
	if (asoc->default_hmac_id)
		return;

	n_params = (ntohs(hmacs->param_hdr.length)
				- sizeof(sctp_paramhdr_t)) >> 1;
	ep = asoc->ep;
	for (i = 0; i < n_params; i++) {
		id = ntohs(hmacs->hmac_ids[i]);

		/* Check the id is in the supported range */
		if (id > SCTP_AUTH_HMAC_ID_MAX)
			continue;

		/* If this TFM has been allocated, use this id */
		if (ep->auth_hmacs[id]) {
			asoc->default_hmac_id = id;
			break;
		}
	}
}

/* Check to see if the given chunk is supposed to be authenticated */
static int __sctp_auth_cid(sctp_cid_t chunk, struct sctp_chunks_param *param)
{
	unsigned short len;
	int found = 0;
	int i;

	if (!param || param->param_hdr.length == 0)
		return 0;

	len = ntohs(param->param_hdr.length) - sizeof(sctp_paramhdr_t);

	/* SCTP-AUTH, Section 3.2
	 *    The chunk types for INIT, INIT-ACK, SHUTDOWN-COMPLETE and AUTH
	 *    chunks MUST NOT be listed in the CHUNKS parameter.  However, if
	 *    a CHUNKS parameter is received then the types for INIT, INIT-ACK,
	 *    SHUTDOWN-COMPLETE and AUTH chunks MUST be ignored.
	 */
	for (i = 0; !found && i < len; i++) {
		switch (param->chunks[i]) {
		    case SCTP_CID_INIT:
		    case SCTP_CID_INIT_ACK:
		    case SCTP_CID_SHUTDOWN_COMPLETE:
		    case SCTP_CID_AUTH:
			break;

		    default:
			if (param->chunks[i] == chunk)
			    found = 1;
			break;
		}
	}

	return found;
}

/* Check if peer requested that this chunk is authenticated */
int sctp_auth_send_cid(sctp_cid_t chunk, const struct sctp_association *asoc)
{
	if (!sctp_auth_enable || !asoc || !asoc->peer.auth_capable)
		return 0;

	return __sctp_auth_cid(chunk, asoc->peer.peer_chunks);
}

/* Check if we requested that peer authenticate this chunk. */
int sctp_auth_recv_cid(sctp_cid_t chunk, const struct sctp_association *asoc)
{
	if (!sctp_auth_enable || !asoc)
		return 0;

	return __sctp_auth_cid(chunk,
			      (struct sctp_chunks_param *)asoc->c.auth_chunks);
}

/* SCTP-AUTH: Section 6.2:
 *    The sender MUST calculate the MAC as described in RFC2104 [2] using
 *    the hash function H as described by the MAC Identifier and the shared
 *    association key K based on the endpoint pair shared key described by
 *    the shared key identifier.  The 'data' used for the computation of
 *    the AUTH-chunk is given by the AUTH chunk with its HMAC field set to
 *    zero (as shown in Figure 6) followed by all chunks that are placed
 *    after the AUTH chunk in the SCTP packet.
 */
void sctp_auth_calculate_hmac(const struct sctp_association *asoc,
			      struct sk_buff *skb,
			      struct sctp_auth_chunk *auth,
			      gfp_t gfp)
{
	struct scatterlist sg;
	struct hash_desc desc;
	struct sctp_auth_bytes *asoc_key;
	__u16 key_id, hmac_id;
	__u8 *digest;
	unsigned char *end;
	int free_key = 0;

	/* Extract the info we need:
	 * - hmac id
	 * - key id
	 */
	key_id = ntohs(auth->auth_hdr.shkey_id);
	hmac_id = ntohs(auth->auth_hdr.hmac_id);

	if (key_id == asoc->active_key_id)
		asoc_key = asoc->asoc_shared_key;
	else {
		struct sctp_shared_key *ep_key;

		ep_key = sctp_auth_get_shkey(asoc, key_id);
		if (!ep_key)
			return;

		asoc_key = sctp_auth_asoc_create_secret(asoc, ep_key, gfp);
		if (!asoc_key)
			return;

		free_key = 1;
	}

	/* set up scatter list */
	end = skb_tail_pointer(skb);
	sg_init_one(&sg, auth, end - (unsigned char *)auth);

	desc.tfm = asoc->ep->auth_hmacs[hmac_id];
	desc.flags = 0;

	digest = auth->auth_hdr.hmac;
	if (crypto_hash_setkey(desc.tfm, &asoc_key->data[0], asoc_key->len))
		goto free;

	crypto_hash_digest(&desc, &sg, sg.length, digest);

free:
	if (free_key)
		sctp_auth_key_put(asoc_key);
}

/* API Helpers */

/* Add a chunk to the endpoint authenticated chunk list */
int sctp_auth_ep_add_chunkid(struct sctp_endpoint *ep, __u8 chunk_id)
{
	struct sctp_chunks_param *p = ep->auth_chunk_list;
	__u16 nchunks;
	__u16 param_len;

	/* If this chunk is already specified, we are done */
	if (__sctp_auth_cid(chunk_id, p))
		return 0;

	/* Check if we can add this chunk to the array */
	param_len = ntohs(p->param_hdr.length);
	nchunks = param_len - sizeof(sctp_paramhdr_t);
	if (nchunks == SCTP_NUM_CHUNK_TYPES)
		return -EINVAL;

	p->chunks[nchunks] = chunk_id;
	p->param_hdr.length = htons(param_len + 1);
	return 0;
}

/* Add hmac identifires to the endpoint list of supported hmac ids */
int sctp_auth_ep_set_hmacs(struct sctp_endpoint *ep,
			   struct sctp_hmacalgo *hmacs)
{
	int has_sha1 = 0;
	__u16 id;
	int i;

	/* Scan the list looking for unsupported id.  Also make sure that
	 * SHA1 is specified.
	 */
	for (i = 0; i < hmacs->shmac_num_idents; i++) {
		id = hmacs->shmac_idents[i];

		if (id > SCTP_AUTH_HMAC_ID_MAX)
			return -EOPNOTSUPP;

		if (SCTP_AUTH_HMAC_ID_SHA1 == id)
			has_sha1 = 1;

		if (!sctp_hmac_list[id].hmac_name)
			return -EOPNOTSUPP;
	}

	if (!has_sha1)
		return -EINVAL;

	memcpy(ep->auth_hmacs_list->hmac_ids, &hmacs->shmac_idents[0],
		hmacs->shmac_num_idents * sizeof(__u16));
	ep->auth_hmacs_list->param_hdr.length = htons(sizeof(sctp_paramhdr_t) +
				hmacs->shmac_num_idents * sizeof(__u16));
	return 0;
}

/* Set a new shared key on either endpoint or association.  If the
 * the key with a same ID already exists, replace the key (remove the
 * old key and add a new one).
 */
int sctp_auth_set_key(struct sctp_endpoint *ep,
		      struct sctp_association *asoc,
		      struct sctp_authkey *auth_key)
{
	struct sctp_shared_key *cur_key = NULL;
	struct sctp_auth_bytes *key;
	struct list_head *sh_keys;
	int replace = 0;

	/* Try to find the given key id to see if
	 * we are doing a replace, or adding a new key
	 */
	if (asoc)
		sh_keys = &asoc->endpoint_shared_keys;
	else
		sh_keys = &ep->endpoint_shared_keys;

	key_for_each(cur_key, sh_keys) {
		if (cur_key->key_id == auth_key->sca_keynumber) {
			replace = 1;
			break;
		}
	}

	/* If we are not replacing a key id, we need to allocate
	 * a shared key.
	 */
	if (!replace) {
		cur_key = sctp_auth_shkey_create(auth_key->sca_keynumber,
						 GFP_KERNEL);
		if (!cur_key)
			return -ENOMEM;
	}

	/* Create a new key data based on the info passed in */
	key = sctp_auth_create_key(auth_key->sca_keylength, GFP_KERNEL);
	if (!key)
		goto nomem;

	memcpy(key->data, &auth_key->sca_key[0], auth_key->sca_keylength);

	/* If we are replacing, remove the old keys data from the
	 * key id.  If we are adding new key id, add it to the
	 * list.
	 */
	if (replace)
		sctp_auth_key_put(cur_key->key);
	else
		list_add(&cur_key->key_list, sh_keys);

	cur_key->key = key;
	sctp_auth_key_hold(key);

	return 0;
nomem:
	if (!replace)
		sctp_auth_shkey_free(cur_key);

	return -ENOMEM;
}

int sctp_auth_set_active_key(struct sctp_endpoint *ep,
			     struct sctp_association *asoc,
			     __u16  key_id)
{
	struct sctp_shared_key *key;
	struct list_head *sh_keys;
	int found = 0;

	/* The key identifier MUST correst to an existing key */
	if (asoc)
		sh_keys = &asoc->endpoint_shared_keys;
	else
		sh_keys = &ep->endpoint_shared_keys;

	key_for_each(key, sh_keys) {
		if (key->key_id == key_id) {
			found = 1;
			break;
		}
	}

	if (!found)
		return -EINVAL;

	if (asoc) {
		asoc->active_key_id = key_id;
		sctp_auth_asoc_init_active_key(asoc, GFP_KERNEL);
	} else
		ep->active_key_id = key_id;

	return 0;
}

int sctp_auth_del_key_id(struct sctp_endpoint *ep,
			 struct sctp_association *asoc,
			 __u16  key_id)
{
	struct sctp_shared_key *key;
	struct list_head *sh_keys;
	int found = 0;

	/* The key identifier MUST NOT be the current active key
	 * The key identifier MUST correst to an existing key
	 */
	if (asoc) {
		if (asoc->active_key_id == key_id)
			return -EINVAL;

		sh_keys = &asoc->endpoint_shared_keys;
	} else {
		if (ep->active_key_id == key_id)
			return -EINVAL;

		sh_keys = &ep->endpoint_shared_keys;
	}

	key_for_each(key, sh_keys) {
		if (key->key_id == key_id) {
			found = 1;
			break;
		}
	}

	if (!found)
		return -EINVAL;

	/* Delete the shared key */
	list_del_init(&key->key_list);
	sctp_auth_shkey_free(key);

	return 0;
}


text:
$moduleName = 'Lability';
$repoRoot = (Resolve-Path "$PSScriptRoot\..\..\..\..").Path;
Import-Module (Join-Path -Path $RepoRoot -ChildPath "$moduleName.psm1") -Force;

Describe 'Src\Private\Set-LabSetupCompleteCmd' {

    InModuleScope $moduleName {

        It 'Creates target file "SetupComplete.cmd"' {
            Set-LabSetupCompleteCmd -Path TestDrive:\;
            Test-Path -Path "TestDrive:\SetupComplete.cmd" | Should Be $true;
        }

        It 'Bypasses Powershell execution policy' {
            Set-LabSetupCompleteCmd -Path TestDrive:\;
            $setupCompleteCmd = Get-Content -Path "TestDrive:\SetupComplete.cmd";

            $setupCompleteCmd -match '-ExecutionPolicy Bypass' | Should Be $true;
        }

        It 'Runs non-interactively' {
            Set-LabSetupCompleteCmd -Path TestDrive:\;
            $setupCompleteCmd = Get-Content -Path "TestDrive:\SetupComplete.cmd";

            $setupCompleteCmd -match '-NonInteractive' | Should Be $true;
        }

        It 'Creates scheduled tasks for CoreCLR image' {
            ## Must execute before we mock Set-Content!
            Set-LabSetupCompleteCmd -Path TestDrive:\ -CoreCLR;
            $setupCompleteCmd = Get-Content -Path "TestDrive:\SetupComplete.cmd";
            @($setupCompleteCmd -match 'Schtasks').Count -gt 0 | Should Be $true;
        }

        It 'Uses ASCII encoding' {
            Mock Set-Content -ParameterFilter { $Encoding -eq 'ASCII' } -MockWith { }

            Set-LabSetupCompleteCmd -Path TestDrive:\;

            Assert-MockCalled Set-Content -ParameterFilter { $Encoding -eq 'ASCII' } -Scope It
        }

    } #end InModuleScope
} #end Describe


text:
package client.views;

import static client.internationalization.ButtonNames.NEW_GAME;
import static common.utils.LoggingHelper.info;

import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.ActionListener;
import java.awt.event.MouseListener;
import java.util.Random;

import javax.swing.Box;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuBar;
import javax.swing.JTextField;
import javax.swing.UIManager;

import org.apache.log4j.Logger;

import client.controllers.BoardFieldBtnController;
import client.internationalization.ButtonNames;
import client.internationalization.DescriptionText;
import client.internationalization.DialogText;
import client.utils.GraphicsFactory;
import client.views.component.GameBoardPanel;
import common.enums.GameMode;
import common.enums.GameResult;
import common.model.DiscoveredField;
import common.model.GameSummary;
import common.model.LostReason;
import common.network.ServerAddress;

/**
 * View for the Main component (view with the game board). Standard window.
 */
@SuppressWarnings("serial")
public class MainWindow extends WindowBase {
	private static Logger log = Logger.getLogger(MainWindow.class);
	private JButton newGameBtn;
	private JButton resetBtn;
	private JTextField serverAddressTxtFld;
	private JTextField playerNameTxtFld;
	private GamePanelBase gamePanel;
	private GameRoomDialog gameRoomDialog;
	private MessageDialog msgDialog;
	private boolean resetEnable = true;
	private JMenuBar menuBar;

	public MainWindow() {
		resetBtn = new JButton(ButtonNames.RESET);
		newGameBtn = new JButton(NEW_GAME);
	}

	public void initializeEntryScreen(){
		clearWindow();
		setTitle(DialogText.MAINWINDOW_TITLE);
		setIconImage(Toolkit.getDefaultToolkit().getImage(MainWindow.class.getResource("/resources/images/bomb.png")));
		drawEntryScreen();

		Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
		this.setLocation(dim.width/2-this.getSize().width/2, dim.height/2-this.getSize().height/2);

		Dimension d = this.getLayout().preferredLayoutSize(this);
		setSize(d);
		setResizable(false);

	}

	public void initializeGameBoard(GameMode mode, int progressMaxValue) {
		clearWindow();
		drawComponents();

		Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
		this.setLocation(dim.width/2-this.getSize().width/2, dim.height/2-this.getSize().height/2);
		drawGameBoard(mode, progressMaxValue);
	}

	private void clearWindow() {
		setJMenuBar(null);
		getContentPane().removeAll();
		getContentPane().repaint();
	}

	public void drawComponents() {
		setBounds(100, 100, 456, 356);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		getContentPane().setLayout(new GridLayout(0, 1, 0, 0));

		menuBar = new JMenuBar();
		setJMenuBar(menuBar);

		menuBar.add(resetBtn);
		resetBtn.setEnabled(resetEnable);
		getContentPane().setBounds(0, 0, 450, 301);
		this.setResizable(true);
	}

	private void drawEntryScreen() {
		//setBounds(100, 100, 463, 288);

		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		GridBagLayout gridBagLayout = new GridBagLayout();
		gridBagLayout.columnWidths = new int[] { 20, 1, 55, 86, 31, 41, 0, 20,
				0 };
		gridBagLayout.rowHeights = new int[] { 10, 80, 10, 29, 20, 20, 0 };
		gridBagLayout.columnWeights = new double[] { 0.0, 1.0, 0.0, 1.0, 0.0,
				0.0, 0.0, 0.0, Double.MIN_VALUE };
		gridBagLayout.rowWeights = new double[] { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
				Double.MIN_VALUE };
		getContentPane().setLayout(gridBagLayout);

		Component horizontalStrut = Box.createHorizontalStrut(20);
		GridBagConstraints gbc_horizontalStrut = new GridBagConstraints();
		gbc_horizontalStrut.gridwidth = 8;
		gbc_horizontalStrut.insets = new Insets(0, 0, 5, 0);
		gbc_horizontalStrut.gridx = 0;
		gbc_horizontalStrut.gridy = 0;
		getContentPane().add(horizontalStrut, gbc_horizontalStrut);

		ImageIcon logo = GraphicsFactory.getLogoIcon();
		JLabel lblMinesweeper = new JLabel(logo);
		lblMinesweeper.setSize(logo.getIconWidth(), logo.getIconHeight());

		GridBagConstraints gbc_lblMinesweeper = new GridBagConstraints();
		gbc_lblMinesweeper.insets = new Insets(0, 0, 5, 5);
		gbc_lblMinesweeper.gridwidth = 6;
		gbc_lblMinesweeper.fill = GridBagConstraints.BOTH;
		gbc_lblMinesweeper.insets = new Insets(0, 0, 5, 5);
		gbc_lblMinesweeper.gridx = 1;
		gbc_lblMinesweeper.gridy = 1;
		getContentPane().add(lblMinesweeper, gbc_lblMinesweeper);

		Component horizontalStrut_1 = Box.createHorizontalStrut(20);
		GridBagConstraints gbc_horizontalStrut_1 = new GridBagConstraints();
		gbc_horizontalStrut_1.gridwidth = 8;
		gbc_horizontalStrut_1.insets = new Insets(0, 0, 5, 0);
		gbc_horizontalStrut_1.gridx = 0;
		gbc_horizontalStrut_1.gridy = 2;
		getContentPane().add(horizontalStrut_1, gbc_horizontalStrut_1);

		JLabel lblServerAdress = new JLabel(DescriptionText.SERVER_ADDRESS);
		GridBagConstraints gbc_lblServerAdress = new GridBagConstraints();
		gbc_lblServerAdress.fill = GridBagConstraints.BOTH;
		gbc_lblServerAdress.insets = new Insets(0, 0, 5, 5);
		gbc_lblServerAdress.gridx = 2;
		gbc_lblServerAdress.gridy = 3;
		getContentPane().add(lblServerAdress, gbc_lblServerAdress);

		serverAddressTxtFld = new JTextField();
		serverAddressTxtFld.setText(ServerAddress.LOCALHOST.getValue());
		serverAddressTxtFld.setColumns(10);
		GridBagConstraints gbc_serverAddress = new GridBagConstraints();
		gbc_serverAddress.fill = GridBagConstraints.BOTH;
		gbc_serverAddress.insets = new Insets(0, 0, 5, 5);
		gbc_serverAddress.gridx = 3;
		gbc_serverAddress.gridy = 3;
		getContentPane().add(serverAddressTxtFld, gbc_serverAddress);

		newGameBtn.setBackground(UIManager.getColor("Button.background"));
		GridBagConstraints gbc_newGameBtn = new GridBagConstraints();
		gbc_newGameBtn.anchor = GridBagConstraints.WEST;
		gbc_newGameBtn.fill = GridBagConstraints.VERTICAL;
		gbc_newGameBtn.gridwidth = 2;
		gbc_newGameBtn.gridheight = 2;
		gbc_newGameBtn.insets = new Insets(0, 0, 5, 5);
		gbc_newGameBtn.gridx = 5;
		gbc_newGameBtn.gridy = 3;
		getContentPane().add(newGameBtn, gbc_newGameBtn);

		JLabel lblUserName = new JLabel(DescriptionText.USER_NAME);
		GridBagConstraints gbc_lblUserName = new GridBagConstraints();
		gbc_lblUserName.fill = GridBagConstraints.HORIZONTAL;
		gbc_lblUserName.insets = new Insets(0, 0, 5, 5);
		gbc_lblUserName.gridx = 2;
		gbc_lblUserName.gridy = 4;
		getContentPane().add(lblUserName, gbc_lblUserName);

		playerNameTxtFld = new JTextField();
		// generate random user name so that user don't need to write it all the
		// time
		playerNameTxtFld.setText("user"	+ String.valueOf(new Random().nextInt(100)));
		playerNameTxtFld.setColumns(10);
		GridBagConstraints gbc_userNick = new GridBagConstraints();
		gbc_userNick.fill = GridBagConstraints.HORIZONTAL;
		gbc_userNick.anchor = GridBagConstraints.NORTH;
		gbc_userNick.insets = new Insets(0, 0, 5, 5);
		gbc_userNick.gridx = 3;
		gbc_userNick.gridy = 4;
		getContentPane().add(playerNameTxtFld, gbc_userNick);

		Component horizontalStrut_2 = Box.createHorizontalStrut(20);
		GridBagConstraints gbc_horizontalStrut_2 = new GridBagConstraints();
		gbc_horizontalStrut_2.gridwidth = 8;
		gbc_horizontalStrut_2.gridx = 0;
		gbc_horizontalStrut_2.gridy = 5;
		getContentPane().add(horizontalStrut_2, gbc_horizontalStrut_2);

	}

	public void addNewGameBtnListener(ActionListener listener) {
		newGameBtn.addActionListener(listener);
	}

	public void addResetBtnListener(ActionListener listener) {
		resetBtn.addActionListener(listener);
	}

	public void addBombFieldBtnListener(MouseListener listener) {
		gamePanel.addBombFieldBtnListener(listener);
	}

	public String getServerAddress() {
		return serverAddressTxtFld.getText();
	}

	public String getPlayerName() {
		return playerNameTxtFld.getText();
	}

	public void addNewPlayerGameBoardPanel(GameBoardPanel gameBoardPanel) {
		gamePanel.addNewPlayerGameBoardPanel(gameBoardPanel);
		Dimension d = this.getLayout().preferredLayoutSize(this);
		setSize(d);
		setMinimumSize(d);
	}

	/**
	 * TODO PlayerHandler.opponentShot, commented until SHARED,PERKS will be
	 * developed
	 */
	// TODO MALY Check if it's obsolete
	public void setOpponentAsBomb(int pos) {
		// oponentBombField[pos - 1].setBackground(Color.RED);
	}

	/**
	 * TODO PlayerHandler.opponentShot, commented until SHARED,PERKS will be
	 * developed
	 */
	// TODO MALY Check if it's obsolete
	public void setOpponentAsEmpty(int pos) {
		// oponentBombField[pos - 1].setBackground(Color.GRAY);
	}

	public void setProgress(String userNick, int progressValue) {
		gamePanel.setProgress(userNick, progressValue);
	}

	public void resetFields() {
		gamePanel.resetFields();
	}

	public void setFieldFlagged(int position) {
		gamePanel.setFieldFlagged(position);
	}

	public void setField(DiscoveredField field) {
		gamePanel.setField(field);
	}

	private void drawGameBoard(GameMode mode, int progressMaxValue) {
		switch (mode) {
		case CLASSIC:
			gamePanel = new ClassicGamePanel(progressMaxValue);
			setTitle(DialogText.MAINWINDOW_CLASSIC_TITLE);
			break;
		case PERKS:
			gamePanel = new PerksGamePanel();
			setTitle(DialogText.MAINWINDOW_PERKS_TITLE);
			break;
		case SHARED:
			gamePanel = new SharedGamePanel();
			setTitle(DialogText.MAINWINDOW_SHARED_TITLE);
		}
		getContentPane().add(gamePanel);
	}

	public GameRoomDialog getGameRoomDialog() {
		return gameRoomDialog;
	}

	public void setGameRoomDialog(GameRoomDialog gameRoomDialog) {
		this.gameRoomDialog = gameRoomDialog;
	}

	public void addOpponentStatus(String playerName) {
		gamePanel.addOpponentStatus(playerName);
		pack();
	}

	public void setLifeLeft(int lifeLeft) {
		gamePanel.setLifeLeft(lifeLeft);

	}

	public void setResetEnable(boolean enable) {
		info(log, "setResetEnabled");
		resetEnable = enable;

		if (resetBtn != null)
			resetBtn.setEnabled(resetEnable);
	}

	public void displayLostReason(LostReason reason) {
		System.out.println("Display lost reason in GameResultDialog");
		switch (reason.getReasonMsg()) {
			case NO_BOARDS_LEFT :
				msgDialog.displayLostReasonMsg(this, true,  GameResult.LOSE, reason.getPlayerNick(), "No boards left, you loose.", "No boards left");
				break;
			case NO_LIFES :
				msgDialog.displayLostReasonMsg(this, true, common.enums.GameResult.LOSE, reason.getPlayerNick(), "No lifes left, you loose.", "No lifes left");
				break;
			case NORMAL_MODE_LOST :
				msgDialog.displayLostReasonMsg(this, true, common.enums.GameResult.LOSE, reason.getPlayerNick(), "Auch! Thats a bomb! You loose.", "You found a bomb.");
				break;
			case PLAYER_LEFT_BEFORE_END :
				// gameResultDialog = new GameResultDialog(this, true,
				// GameResult.FAIL, reason.getPlayerNick(),
				// "No boards left, you loose and gain XXX points",
				// "No boards left");
				break;
			default :
				break;
		}
	}

	public void displayEndGameSummary(GameSummary gameSummary) {
		System.out.println("Display end game summary in GameResultDialog");
		msgDialog.displayLostReasonMsg(this, true, gameSummary.getGameResult(), "playerName", "message", "title");
	}

	public void setMessageDialog(MessageDialog msgDialog) {
		this.msgDialog = msgDialog;

	}

}


text:
export function fly() {
    return { part : 'feather'};
}

export class Bird {
    constructor() {
        this.name = 'Bird';
    }
}

export const obj = {};


text:
<?php

namespace App\Controller\Api;

use Symfony\Component\Routing\Annotation\Route;

/**
 * PrioridadesController
 *
 * @author Rogério Lino <rogeriolino@gmail.com>
 *
 * @Route("/api/prioridades")
 */
class PrioridadesController extends ApiCrudController
{
    use Actions\GetTrait,
        Actions\FindTrait,
        Actions\PostTrait,
        Actions\PutTrait,
        Actions\DeleteTrait;

    public function getEntityName()
    {
        return \Novosga\Entity\Prioridade::class;
    }
}


text:
"""An optimization pass that aligns gates to the right of the circuit."""

from cirq import circuits
from cirq.circuits.insert_strategy import InsertStrategy

class AlignRight:
    """Aligns gates to the right of the circuit."""

    def __call__(self, circuit: circuits.Circuit):
        self.optimize_circuit(circuit)

    def optimize_circuit(self, circuit: circuits.Circuit):
        backwards = list(circuit.all_operations())[::-1]
        circuit[:] = circuits.Circuit(backwards, strategy=InsertStrategy.EARLIEST)[::-1]


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CkanDotNet.Api.Helper;

namespace CkanDotNet.Api.Model
{
    public class Group
    {
        /// <summary>
        /// Gets the auto-generated unique identifier
        /// </summary>
        public string Id { get; set; }

        /// <summary>
        /// Gets the friendly unique identifier
        /// </summary>
        public string Name { get; set; }

        /// <summary>
        /// Gets the title for display
        /// </summary>
        public string Title { get; set; }

        /// <summary>
        /// Gets the description
        /// </summary>
        public string Description { get; set; }

        /// <summary>
        /// Gets the created date in ISO string format
        /// </summary>
        public string Created { get; set; }

        /// <summary>
        /// Gets the state of the group
        /// </summary>
        public string State { get; set; }

        /// <summary>
        /// Gets the id of the most recent revision
        /// </summary>
        public string RevisionId { get; set; }

        /// <summary>
        /// Gets the packages in the group
        /// </summary>
        public List<string> Packages { get; set; }

        /// <summary>
        /// Gets the created date of the group
        /// </summary>
        public DateTime CreatedAsDate
        {
            get
            {
                return DateHelper.Parse(Created);
            }
        }
    }
}


text:
package gov.nih.nci.cabig.caaers;

/**
 * @author Rhett Sutphin
 */
public class CaaersError extends Error {
    public CaaersError(String message) {
        super(message);
    }

    public CaaersError(String message, Throwable cause) {
        super(message, cause);
    }
}


text:
using AppBrix.Modules;
using System;

namespace AppBrix.Configuration;

/// <summary>
/// A configuration element holding the information about an application module.
/// </summary>
public sealed class ModuleConfigElement
{
    #region Construction
    /// <summary>
    /// Creates a new instance of <see cref="ModuleConfigElement"/>.
    /// </summary>
    public ModuleConfigElement()
    {
        this.Type = string.Empty;
    }

    /// <summary>
    /// Creates a new element for the selected module.
    /// </summary>
    /// <typeparam name="T">The type of the module.</typeparam>
    /// <returns>The module element.</returns>
    public static ModuleConfigElement Create<T>() where T : IModule => ModuleConfigElement.Create(typeof(T));

    /// <summary>
    /// Creates a new element for the selected module.
    /// </summary>
    /// <param name="type">The type of the module.</param>
    /// <returns>The module element.</returns>
    public static ModuleConfigElement Create(Type type)
    {
        if (type is null)
            throw new ArgumentNullException(nameof(type));
        if (!typeof(IModule).IsAssignableFrom(type))
            throw new ArgumentException($"Type {type} is not of type {nameof(IModule)}.");

        return new ModuleConfigElement
        {
            Type = type.GetAssemblyQualifiedName()
        };
    }
    #endregion

    #region Properties
    /// <summary>
    /// Gets or sets the type of the module.
    /// </summary>
    public string Type { get; set; }

    /// <summary>
    /// Gets or sets the module's current status.
    /// Changing this property requires application restart.
    /// </summary>
    public ModuleStatus Status { get; set; }

    /// <summary>
    /// Gets or sets the module's installed version.
    /// This property is automatically updated when the module is intalled or upgraded.
    /// An install can be forced by removing the value.
    /// An upgrade can be forced by lowering the value to a previous version of the assembly.
    /// </summary>
    public Version? Version { get; set; }
    #endregion
}


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Model_Dashboard_Reporte extends CI_Model
{
    public function __construct()
    {
        parent::__construct();
    }

    function GetAprobadosEstudio()
    {
        $estudios = $this->db->query("select nombre_naturaleza_inv, count(nombre_pi)as Cantidadpip from PROYECTO_INVERSION right join NATURALEZA_INVERSION ON PROYECTO_INVERSION.id_naturaleza_inv=NATURALEZA_INVERSION.id_naturaleza_inv group by nombre_naturaleza_inv");//listar EVAL
        if ($estudios->num_rows()> 0) {
            return $estudios->result();
        } else {
            return false;
        }
    }

    function NaturalezaInversionMontos()
    {
        $estudios = $this->db->query("select nombre_naturaleza_inv, sum (costo_pi) as Monto from PROYECTO_INVERSION left join NATURALEZA_INVERSION ON PROYECTO_INVERSION.id_naturaleza_inv=NATURALEZA_INVERSION.id_naturaleza_inv group by nombre_naturaleza_inv");//listar EVAL
        if ($estudios->num_rows()> 0) {
            return $estudios->result();
        } else {
            return false;
        }
    }

    function CantidadPipFuenteFinancimiento()
    {
        $estudios = $this->db->query("select nombre_fuente_finan , count(nombre_pi)as Cantidadpip from PROYECTO_INVERSION RIGHT JOIN RUBRO_PI on PROYECTO_INVERSION.id_pi=RUBRO_PI.id_pi RIGHT JOIN RUBRO ON RUBRO_PI.id_rubro=RUBRO.id_rubro RIGHT JOIN FUENTE_FINANCIAMIENTO ON RUBRO.id_fuente_finan=FUENTE_FINANCIAMIENTO.id_fuente_finan GROUP BY  nombre_fuente_finan ");//listar EVAL
        if ($estudios->num_rows()> 0) {
            return $estudios->result();
        } else {
            return false;
        }
    }

    function MontoPipFuenteFinanciamiento()
    {
        $estudios = $this->db->query("select nombre_fuente_finan , sum(costo_pi)as Monto from PROYECTO_INVERSION RIGHT JOIN RUBRO_PI on PROYECTO_INVERSION.id_pi=RUBRO_PI.id_pi RIGHT JOIN RUBRO ON RUBRO_PI.id_rubro=RUBRO.id_rubro RIGHT JOIN FUENTE_FINANCIAMIENTO ON RUBRO.id_fuente_finan=FUENTE_FINANCIAMIENTO.id_fuente_finan GROUP BY  nombre_fuente_finan");//listar EVAL
        if ($estudios->num_rows()> 0) {
            return $estudios->result();
        } else {
            return false;
        }
    }

    function CantidadPipModalidad()
    {
        $estudios = $this->db->query("select nombre_modalidad_ejec,count(nombre_pi)as CantidadPip FROM MODALIDAD_EJECUCION left JOIN MODALIDAD_EJECUCION_PI ON MODALIDAD_EJECUCION.id_modalidad_ejec=MODALIDAD_EJECUCION_PI.id_modalidad_ejec left JOIN PROYECTO_INVERSION ON MODALIDAD_EJECUCION_PI.id_pi=PROYECTO_INVERSION.id_pi group by nombre_modalidad_ejec");//listar EVAL
        if ($estudios->num_rows()> 0) {
            return $estudios->result();
        } else {
            return false;
        }
    }

    function MontoPipModalidad()
    {
        $data = $this->db->query("select nombre_modalidad_ejec,sum(costo_pi)as Monto FROM MODALIDAD_EJECUCION left JOIN MODALIDAD_EJECUCION_PI ON MODALIDAD_EJECUCION.id_modalidad_ejec=MODALIDAD_EJECUCION_PI.id_modalidad_ejec left JOIN PROYECTO_INVERSION ON MODALIDAD_EJECUCION_PI.id_pi=PROYECTO_INVERSION.id_pi group by nombre_modalidad_ejec");//listar EVAL
        if ($data->num_rows()> 0) {
            return $data->result();
        } else {
            return false;
        }
    }

    function CantidadPipRubro()
    {
        $data = $this->db->query("select nombre_rubro ,count (nombre_pi)as Cantidadpip from RUBRO LEFT JOIN RUBRO_PI on RUBRO.id_rubro=RUBRO_PI.id_rubro LEFT JOIN PROYECTO_INVERSION on RUBRO_PI.id_pi=PROYECTO_INVERSION.id_pi group by nombre_rubro");//listar EVAL
        if ($data->num_rows()> 0) {
            return $data->result();
        } else {
            return false;
        }
    }

    function CantidadPipProvincia()
    {
        $data = $this->db->query("select UBIGEO.provincia ,count (nombre_pi)as Cantidadpip from PROYECTO_INVERSION INNER JOIN UBIGEO_PI on PROYECTO_INVERSION.id_pi=UBIGEO_PI.id_pi INNER JOIN UBIGEO on UBIGEO_PI.id_ubigeo=UBIGEO.id_ubigeo group by  UBIGEO.provincia");//listar EVAL
        if ($data->num_rows()> 0) {
            return $data->result();
        } else {
            return false;
        }
    }

    function FuncionNumeroPip()
    {
        $data=$this->db->query("select FUNCION.nombre_funcion ,count (nombre_pi)as CantidadPip, sum(costo_pi)as CostoPip from PROYECTO_INVERSION INNER JOIN GRUPO_FUNCIONAL ON PROYECTO_INVERSION.id_grupo_funcional=GRUPO_FUNCIONAL.id_grup_funcional INNER JOIN  DIVISION_FUNCIONAL on GRUPO_FUNCIONAL.id_div_funcional=DIVISION_FUNCIONAL.id_div_funcional INNER JOIN FUNCION on DIVISION_FUNCIONAL.id_funcion=FUNCION.id_funcion group by FUNCION.nombre_funcion");
        if ($data->num_rows()> 0)
        {
            return $data->result();
        }
        else
        {
            return false;
        }
    }
    function ReporteDevengadoPiaPimPorPip($CodigoUnico)
    {
       $data = $this->db->query("select * from PROYECTO_INVERSION LEFT join META_PRESUPUESTAL_PI on PROYECTO_INVERSION.id_pi=META_PRESUPUESTAL_PI.id_pi LEFT JOIN DEVENGADO_META ON
         META_PRESUPUESTAL_PI.id_meta_pi=DEVENGADO_META.id_meta_pi WHERE PROYECTO_INVERSION.codigo_unico_pi='".$CodigoUnico."' and year(anio_meta_pres)=year(GETDATE())");//listar EVAL
        if ($data->num_rows()> 0)
        {
            return $data->result()[0];
        }
        else
        {
            return false;
        }
    }

    function ReporteDevengadoPiaPimPorPipGraficos($CodigoUnico)
    {
       $data = $this->db->query("select codigo_unico_pi,SUM(costo_pi) as costo_pi,SUM(pia_meta_pres) as pia_meta_pres ,SUM(pim_acumulado) AS pim_acumulado,
        SUM(compromiso_acumulado) as compromiso_acumulado ,SUM(devengado_acumulado) as devengado_acumulado from
        PROYECTO_INVERSION inner join META_PRESUPUESTAL_PI on  PROYECTO_INVERSION.id_pi=META_PRESUPUESTAL_PI.id_pi
        where PROYECTO_INVERSION.codigo_unico_pi='".$CodigoUnico."' GROUP BY codigo_unico_pi");
        if ($data->num_rows()> 0)
        {
            return $data->result()[0];
        }
        else
        {
            return false;
        }
    }

}


text:
package consulo.hub.frontend.backend;

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;

import java.util.Collection;

/**
 * @author VISTALL
 * @since 04/09/2021
 */
public class BackendAuthenticationToken extends UsernamePasswordAuthenticationToken
{
	private final String myToken;

	public BackendAuthenticationToken(Object principal, String token, Collection<? extends GrantedAuthority> authorities)
	{
		super(principal, "N/A", authorities);
		myToken = token;
	}

	public String getToken()
	{
		return myToken;
	}
}


text:
'use strict';

(function (scope) {
    /**
     * Recognition input object for shape recognition
     *
     * @class ShapeRecognitionInput
     * @extends AbstractRecognitionInput
     * @constructor
     */
    function ShapeRecognitionInput() {
    }

    /**
     * Inheritance property
     */
    ShapeRecognitionInput.prototype = new scope.AbstractRecognitionInput();

    /**
     * Constructor property
     */
    ShapeRecognitionInput.prototype.constructor = ShapeRecognitionInput;

    /**
     * Get parameters
     *
     * @method getParameters
     * @returns {ShapeParameter}
     */
    ShapeRecognitionInput.prototype.getParameters = function () {
        return new ShapeParameter({
            rejectDetectionSensitivity: this.rejectDetectionSensitivity,
            doBeautification: this.doBeautification,
            userResources: this.userResources
        });
    };

    /**
     * Set parameters
     *
     * @method setParameters
     * @param {ShapeParameter} parameters
     */
    ShapeRecognitionInput.prototype.setParameters = function (parameters) {
        if (parameters) {
            this.rejectDetectionSensitivity = parameters.getRejectDetectionSensitivity();
            this.doBeautification = parameters.hasBeautification();
            this.userResources = parameters.getUserResources();
        }
    };

    /**
     * Get input components
     *
     * @method getComponents
     * @returns {AbstractComponent[]}
     */
    ShapeRecognitionInput.prototype.getComponents = function () {
        return this.components;
    };

    /**
     * Set input components
     *
     * @method setComponents
     * @param {AbstractComponent[]} components
     */
    ShapeRecognitionInput.prototype.setComponents = function (components) {
        this.components = components;
    };

    // Export
    scope.ShapeRecognitionInput = ShapeRecognitionInput;
})(MyScript);


text:
package org.arcticsoft.bluebearlive.core.handler;

import com.mrheadshot62.api.Packet;
import com.mrheadshot62.api.TypesAnswer;
import com.mrheadshot62.api.types.PermissionPacket;

/**
 * Created by novak on 05.01.2017.
 */
public class MainHandler {
    private Packet[] packets;
    private PermissionPacket permisson;

    public MainHandler(Packet[] packets) {
        this.packets = packets;
        for (Packet p : packets) {
            switch (p.getType()){
                case TypesAnswer.ONLYCODE:
                    new AnswerHandler().handlePacket(p);
                    break;
                case TypesAnswer.AUTH_USER_FROM_SERVER:
                    new AuthUserFromServerHandler().handlePacket(p);
                    break;
                case TypesAnswer.USERPACKET:
                    //TODO Большой Ди, ты знаешь что делать... Database.setUser(User u);Database.getUser();
                    new UserHandler().handlePacket(p);
                case TypesAnswer.REPORTPACKET:
                    new ReportHandler().handlePacket(p);
                    break;
                case TypesAnswer.AUTH_CHECK_SECRET_KEY:
                    new SecondAuthHandler().handlePacket(p);
                    break;
                default:
                    break;
            }
        }
    }

    private boolean checkSession(){
        return true;    //TODO Session
    }

}


text:
export sympa_url=
export admin_email=
export admin_pass=
export default_list=
export test_email_list=test_email_list.text


text:
<!-- multilang from README.md

NO MODIFIQUE ESTE ARCHIVO. FUE GENERADO AUTOMÁTICAMENTE POR multilang.js

-->
# best-promise
select the best promise available at certain moment or leave the choice to the end user

![extending](https://img.shields.io/badge/stability-extending-yellow.svg)
[![version](https://img.shields.io/npm/v/best-promise.svg)](https://npmjs.org/package/best-promise)
[![downloads](https://img.shields.io/npm/dm/best-promise.svg)](https://npmjs.org/package/best-promise)
[![Build Status](https://secure.travis-ci.org/emilioplatzer/best-promise.svg)](http://travis-ci.org/emilioplatzer/best-promise)

<!--multilang buttons-->

idioma: ![castellano](https://raw.githubusercontent.com/codenautas/multilang/master/img/lang-es.png)
también disponible en:
[![inglés](https://raw.githubusercontent.com/codenautas/multilang/master/img/lang-en.png)](README.md)

***Basado en [any-promise](npmjs.org/package/any-promise)***

Cuando se usa con Travis-CI ***best-promise*** seleccionará al azar una librería Promise.

En el resto de los casos funciona igual que [any-promise](npmjs.org/package/any-promise).

La lista de módulos Promise es:

  - [es6-promise](https://github.com/jakearchibald/es6-promise)
  - [promise](https://github.com/then/promise)
  - [native-promise-only](https://github.com/getify/native-promise-only)
  - [bluebird](https://github.com/petkaantonov/bluebird)
  - [rsvp](https://github.com/tildeio/rsvp.js)
  - [when](https://github.com/cujojs/when)
  - [q](https://github.com/kriskowal/q)

Si no hay ninguna librearía instalada ***any-promise*** intenta exportar el módulo global `Promise` (ya sea nativo o el polyfill).

Se puede especificar la librería elegida en cada momento usando la variable de ambiente `PROMISE_IMPL`
o también se puede usar la variable de ambiente `PROMISE_RANDOM` para que sortee aunque no esté en Travis-CI.

```javascript
var Promise = require('best-promise').Promise;

return Promise
  .all([xf, f, init, coll])
  .then(fn);

return new Promise(function(resolve, reject){
  try {
    resolve(item);
  } catch(e){
    reject(e);
  }
});

```

## mejoras

Una forma común de las promesas es empezar la primera función dentro de un then,
de ese modo si la expresión que arma los parámetros lanza un error
se captura dentro de la cadena de promesas

```js

var Promises = require('best-promise');
var fs = require('fs-promise');

Promises.start(function(){
    return fs.stat(path+path.sep+fileName);
}).then(function(stat){
    // ...
});

```


text:
<script>

window.onerror = function myErrorHandler(errorMsg, url, lineNumber) {

    showModal('That is not good...', errorMsg);
    loading.stop();

    return false;

}

function getFormValues(container) {

    var values = [];
    $(container).find('input, select, textarea').each(function() {

        var val = $(this).val();
        if($(this).attr('required') && val === '') {

            var message = 'Not all required fields are filled. Please check your input and try again.';
            showModal('Oops!', message);
            throw message;

        }

        if($(this).data('type').indexOf('formula') > -1 && val[0] !== '=') {
            values.push('');
        } else {
            values.push(val);
        }

    });

    return values;

}

function setContent(template, atts, element) {

    var target = atts.target || '#dynamic-content';

    runFunction('templatePart', [template, atts], function(content) {

        $(target).empty();
        $(target).append(content);

        $('.select2').select2({'theme': 'bootstrap'});
        $('.data-table').DataTable();

        if(atts.after) window[atts.after](element);

        if(target === '#dynamic-content') {
            google.script.url.getLocation(function(location) {
                google.script.history.push({'template': template, 'atts': atts},
                                           {'spreadsheetId': location.parameter.spreadsheetId,
                                            'template': template,
                                            'atts': JSON.stringify(atts)});
            });
        }

        window.scrollTo(0, 0);
        loading.stop();

    });

}

//Enable back button. A lot of improvement is possible here, to be explored
google.script.history.setChangeHandler(function (e) {

    loading.start();
    setContent(e.state.template, e.state.atts);

});

function removeTrigger(element) {

    $(element).removeClass('trigger-action');

}

function runFunction(func, args, success) {

    return google.script.run
    .withSuccessHandler(success)
    .withFailureHandler(function(error) {

        var title = 'Something went terribly wrong...';
        showModal(title, error.message);
        loading.stop();

    })[func].apply(this, args);

}

function showModal(title, message) {

    $('.modal-title').html(title);
    $('.modal-body').html(message);
    $('.modal').modal();

};

var loading = {

    start: function() {
        $('.progress').show();
        $('button, a').addClass('disabled');
    },

    stop: function() {
        $('button, a').removeClass('disabled');
        $('.progress').hide();
    }

}

</script>


text:
using System;

namespace Zirpl.AppEngine.Model.Membership
{
    public interface IResetLostPasswordRequest
    {
        String NewPassword { get; }
        Guid UserId { get; }
    }
}


text:
/*
 */

import React, { Component } from 'react'
import { applyMiddleware, compose, createStore } from 'redux'
import { Provider } from 'react-redux'
import logger from 'redux-logger'
import thunk from 'redux-thunk'
import { composeWithDevTools } from './redux-devtools-extension';

import App from './app'

// All redux reducers (rolled into one mega-reducer)
import rootReducer from '../reducers/index'

// Load middleware
let middleware = [
  thunk, // Allows action creators to return functions (not just plain objects)
];

// Init redux store (using the given reducer & middleware)

const composeEnhancers = composeWithDevTools({
  // Specify here name, actionsBlacklist, actionsCreators and other options
  rootReducer
});
const store = createStore(rootReducer, composeEnhancers(
  applyMiddleware(...middleware)
));

// Wrap App in Redux provider (makes Redux available to all sub-components)
export default class AppContainer extends Component {
  render() {
    return (
      <Provider store={store}>
        <App />
      </Provider>
    );
  }
}


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [("cases", "0016_case_contact")]

    operations = [
        migrations.AddField(model_name="outgoing", name="text", field=models.TextField(max_length=640, null=True))
    ]


text:
#include <click/config.h>
#include "portclassifier.hh"
#include <click/confparse.hh>
#include <click/error.hh>
#include <clicknet/tcp.h>

PortClassifier::PortClassifier()
{
}

PortClassifier::~PortClassifier()
{
}

int
PortClassifier::configure(const Vector<String> &conf, ErrorHandler *errh)
{
  String srcdst;
  if (cp_va_parse(conf, this, errh,
                  cpString, "srcdst", &srcdst,
		  cpUnsigned, "base", &_base,
                  cpUnsigned, "stepping", &_stepping,
		  cpEnd) < 0)
    return -1;

  if (srcdst == "SRC")
    _src = 1;
  else if (srcdst == "DST")
    _src = 0;
  else
    return -1;

  return 0;
}

void
PortClassifier::push(int, Packet *p)
{
  int port=0;
  unsigned int sport, dport;
  const click_tcp *tcph= p->tcp_header();
  sport = ntohs(tcph->th_sport);
  dport = ntohs(tcph->th_dport);

  if (_src)
    port = sport / _stepping - _base / _stepping;
  else
    port = dport / _stepping - _base / _stepping;

  if (port >= noutputs())
    port = noutputs()-1;

  //click_chatter("  sport: %d, dport: %d chose: %d", sport, dport, port);
  output(port).push(p);
  return;
}

EXPORT_ELEMENT(PortClassifier)
ELEMENT_MT_SAFE(PortClassifier)


text:
@implementation SPetsModel
+(NSDictionary<NSString *,id> *)modelContainerPropertyGenericClass{
    return @{@"values":[SPetsValuesModel class]};
}
+(NSDictionary<NSString *,id> *)modelCustomPropertyMapper{
    return @{@"values":@"data.values",@"has_more":@"data.has_more"};
}
@end

@implementation SPetsValuesModel
+(NSDictionary<NSString *,id> *)modelContainerPropertyGenericClass{
    return @{@"services":[NSString class],@"photos":[NSString class]};
}
+(NSDictionary<NSString *,id> *)modelCustomPropertyMapper{
    return @{@"other":@"shipping_types.other",@"selfType":@"shipping_types.self",@"areaID":@"area.id",@"areaName":@"area.name",@"pinyin":@"area.pinyin",@"area_id":@"contact.area_id",@"mobile":@"contact.mobile",@"contactName":@"contact.name",@"contactAddress":@"contact.address",@"ID":@"id"};
}
@end

@implementation SPetsValuesUserModel
+(NSDictionary<NSString *,id> *)modelCustomPropertyMapper{
    return @{@"userID":@"id",@"address":@"contact.address",@"mobile":@"contact.mobile",@"nsme":@"contact.name",};
}
@end

@implementation SPetsValuesCatModel

@end


text:
package jp.bglb.bonboru.flux.example.dto;

import java.util.List;
import java.util.Map;
import jp.bglb.bonboru.flux.processor.annotation.ObservableClass;
import jp.bglb.bonboru.flux.processor.annotation.ObservableField;
import jp.bglb.bonboru.flux.processor.type.CheckType;

@ObservableClass public class TestData {
  @ObservableField private String nonNullName;

  @ObservableField(checkType = CheckType.NULLABLE) private String name;

  @ObservableField(checkType = CheckType.PASS) private String passName;

  @ObservableField(checkType = CheckType.PASS, hasDefaultValue = true) private String defaultName;

  @ObservableField(checkType = CheckType.PASS) private List<String> messages;

  @ObservableField(checkType = CheckType.STRICT, hasDefaultValue = true)
  private Map<String, Integer> map;

  @ObservableField(checkType = CheckType.PASS) private int i;

  @ObservableField private long l;

  @ObservableField(checkType = CheckType.PASS) private float f;

  @ObservableField private double d;

  @ObservableField private boolean b;

  @ObservableField(checkType = CheckType.PASS) private short s;

  @ObservableField private byte bb;

  @ObservableField private char c;

  @ObservableField(checkType = CheckType.PASS) private int[] ia;

  @ObservableField(checkType = CheckType.STRICT) private long[] la;

  @ObservableField(checkType = CheckType.NULLABLE) private float[] fa;

  public String getNonNullName() {
    return nonNullName;
  }

  public void setNonNullName(String nonNullName) {
    this.nonNullName = nonNullName;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public String getPassName() {
    return passName;
  }

  public void setPassName(String passName) {
    this.passName = passName;
  }

  public String getDefaultName() {
    return defaultName;
  }

  public void setDefaultName(String defaultName) {
    this.defaultName = defaultName;
  }

  public List<String> getMessages() {
    return messages;
  }

  public void setMessages(List<String> messages) {
    this.messages = messages;
  }

  public Map<String, Integer> getMap() {
    return map;
  }

  public void setMap(Map<String, Integer> map) {
    this.map = map;
  }

  public int getI() {
    return i;
  }

  public void setI(int i) {
    this.i = i;
  }

  public long getL() {
    return l;
  }

  public void setL(long l) {
    this.l = l;
  }

  public float getF() {
    return f;
  }

  public void setF(float f) {
    this.f = f;
  }

  public double getD() {
    return d;
  }

  public void setD(double d) {
    this.d = d;
  }

  public boolean isB() {
    return b;
  }

  public void setB(boolean b) {
    this.b = b;
  }

  public short getS() {
    return s;
  }

  public void setS(short s) {
    this.s = s;
  }

  public byte getBb() {
    return bb;
  }

  public void setBb(byte bb) {
    this.bb = bb;
  }

  public char getC() {
    return c;
  }

  public void setC(char c) {
    this.c = c;
  }

  public int[] getIa() {
    return ia;
  }

  public void setIa(int[] ia) {
    this.ia = ia;
  }

  public long[] getLa() {
    return la;
  }

  public void setLa(long[] la) {
    this.la = la;
  }

  public float[] getFa() {
    return fa;
  }

  public void setFa(float[] fa) {
    this.fa = fa;
  }
}


text:
<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "hl_gethelp".
 *
 * @property integer $get_id
 * @property integer $user_id
 * @property integer $money
 * @property integer $match_time
 * @property integer $create_time
 * @property integer $status
 * @property string $type
 */
class Gethelp extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'hl_gethelp';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['user_id', 'money', 'match_time', 'create_time', 'status', 'type'], 'integer']
        ];
    }

      public function getUser()
    {
        return $this->hasOne(User::className(), ['user_id' => 'user_id']);
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'get_id' => 'Get ID',
            'user_id' => 'User ID',
            'money' => 'Money',
            'match_time' => 'Match Time',
            'create_time' => 'Create Time',
            'status' => 'Status',
            'type' => 'Type',
        ];
    }
}


text:
std::stringstream BElse::getLabel() {
    std::stringstream stream = m_parentScope->getLabel();
    stream << "_else_";
    return stream;
}


text:
I've stolen so many things from so many people, it's time to make my files
available to others.  This repo contains all the files needed to manage my vim
configuration.  Some files are ignored in my .gitignore file, but present on
my file system:

    .
    ├── .gitignore
    ├── .vim
    │   ├── .netrwhist
    │   ├── UltiSnips
    │   |   └── [...]
    │   ├── bundle
    │   |   └── [...]
    │   └── spell
    │       └── [...]
    ├── .vim-backup
    ├── .vim-swapfiles
    └── .vimrc

I'm [managing these files using stow][1].  If you wanted to do the same, don't
forget to ignore the readme when you deploy it:

    stow --ignore "tags|README.md|LICENSE.md" vim

Please also note that I'm using [vim-plug][2] to manage my plugins.  If you're
just cloning this repository, then you should install Vundle:

    curl -fLo ~/.vim/autoload/plug.vim --create-dirs \
        https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim

And you should install those plugins with something like this:

    vim +PlugInstall +qall

If you're new to vim, I strongly recommend [Drew Neil's Practical Vim][3] and
his screencasts over on [vimcasts.org][4].

[1]: http://brandon.invergo.net/news/2012-05-26-using-gnu-stow-to-manage-your-dotfiles.html
[2]: https://github.com/junegunn/vim-plug
[3]: https://pragprog.com/book/dnvim/practical-vim
[4]: http://vimcasts.org


text:
package org.skife.jdbi.v2.util;

import java.sql.ResultSet;
import java.sql.SQLException;

public class ByteArrayMapper extends TypedMapper<byte[]>
{

    public ByteArrayMapper()
    {
        super();
    }

    public ByteArrayMapper(int index)
    {
        super(index);
    }

    public ByteArrayMapper(String name)
    {
        super(name);
    }

    @Override
    protected byte[] extractByName(ResultSet r, String name) throws SQLException
    {
        return r.getBytes(name);
    }

    @Override
    protected byte[] extractByIndex(ResultSet r, int index) throws SQLException
    {
        return r.getBytes(index);
    }

    public static final ByteArrayMapper FIRST = new ByteArrayMapper();
}


text:
#include "shm.h"
#include "internal.h"
#include "util.h"
#include "wayland_buffer.h"

#include <errno.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <wayland-server.h>
#include <wld/pixman.h>
#include <wld/wld.h>

struct swc_shm swc_shm;

static struct
{
    struct wl_global * global;
} shm;

struct pool
{
    struct wl_resource * resource;
    void * data;
    uint32_t size;
    unsigned references;
};

struct pool_reference
{
    struct wld_destructor destructor;
    struct pool * pool;
};

static void unref_pool(struct pool * pool)
{
    if (--pool->references > 0)
        return;

    munmap(pool->data, pool->size);
    free(pool);
}

static void destroy_pool_resource(struct wl_resource * resource)
{
    struct pool * pool = wl_resource_get_user_data(resource);

    unref_pool(pool);
}

static void handle_buffer_destroy(struct wld_destructor * destructor)
{
    struct pool_reference * reference
        = wl_container_of(destructor, reference, destructor);

    unref_pool(reference->pool);
}

static inline uint32_t format_shm_to_wld(uint32_t format)
{
    switch (format)
    {
        case WL_SHM_FORMAT_ARGB8888:
            return WLD_FORMAT_ARGB8888;
        case WL_SHM_FORMAT_XRGB8888:
            return WLD_FORMAT_XRGB8888;
        default:
            return format;
    }
}

static void create_buffer(struct wl_client * client,
                          struct wl_resource * resource, uint32_t id,
                          int32_t offset, int32_t width, int32_t height,
                          int32_t stride, uint32_t format)
{
    struct pool * pool = wl_resource_get_user_data(resource);
    struct pool_reference * reference;
    struct wld_buffer * buffer;
    struct wl_resource * buffer_resource;
    union wld_object object;

    if (offset > pool->size || offset < 0)
    {
        wl_resource_post_error(resource, WL_SHM_ERROR_INVALID_STRIDE,
                               "offset is too big or negative");
        return;
    }

    object.ptr = (void *)((uintptr_t) pool->data + offset);
    buffer = wld_import_buffer(swc.shm->context, WLD_OBJECT_DATA, object,
                               width, height, format_shm_to_wld(format),
                               stride);

    if (!buffer)
        goto error0;

    buffer_resource = wayland_buffer_create_resource
        (client, wl_resource_get_version(resource), id, buffer);

    if (!buffer_resource)
        goto error1;

    if (!(reference = malloc(sizeof *reference)))
        goto error2;

    reference->pool = pool;
    reference->destructor.destroy = &handle_buffer_destroy;
    wld_buffer_add_destructor(buffer, &reference->destructor);
    ++pool->references;

    return;

  error2:
    wl_resource_destroy(buffer_resource);
  error1:
    wld_buffer_unreference(buffer);
  error0:
    wl_resource_post_no_memory(resource);
}

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

static void resize(struct wl_client * client, struct wl_resource * resource,
                   int32_t size)
{
    struct pool * pool = wl_resource_get_user_data(resource);
    void * data;

    data = mremap(pool->data, pool->size, size, MREMAP_MAYMOVE);

    if (data == MAP_FAILED)
    {
        wl_resource_post_error(resource, WL_SHM_ERROR_INVALID_FD,
                               "mremap failed: %s", strerror(errno));
        return;
    }

    pool->data = data;
    pool->size = size;
}

static struct wl_shm_pool_interface shm_pool_implementation = {
    .create_buffer = &create_buffer,
    .destroy = &destroy,
    .resize = &resize
};

static void create_pool(struct wl_client * client,
                        struct wl_resource * resource, uint32_t id,
                        int32_t fd, int32_t size)
{
    struct pool * pool;

    if (!(pool = malloc(sizeof *pool)))
    {
        wl_resource_post_no_memory(resource);
        return;
    }

    pool->resource = wl_resource_create(client, &wl_shm_pool_interface,
                                        wl_resource_get_version(resource), id);

    if (!pool->resource)
    {
        wl_resource_post_no_memory(resource);
        goto error0;
    }

    wl_resource_set_implementation(pool->resource, &shm_pool_implementation,
                                   pool, &destroy_pool_resource);
    pool->data = mmap(NULL, size, PROT_READ, MAP_SHARED, fd, 0);

    if (pool->data == MAP_FAILED)
    {
        wl_resource_post_error(resource, WL_SHM_ERROR_INVALID_FD,
                               "mmap failed: %s", strerror(errno));
        goto error1;
    }

    pool->size = size;
    pool->references = 1;

    return;

  error1:
    wl_resource_destroy(pool->resource);
  error0:
    free(pool);
}

static struct wl_shm_interface shm_implementation = {
    .create_pool = &create_pool
};

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

    if (version > 1)
        version = 1;

    resource = wl_resource_create(client, &wl_shm_interface, version, id);
    wl_resource_set_implementation(resource, &shm_implementation, NULL, NULL);

    wl_shm_send_format(resource, WL_SHM_FORMAT_XRGB8888);
    wl_shm_send_format(resource, WL_SHM_FORMAT_ARGB8888);
}

bool shm_initialize(void)
{
    if (!(swc.shm->context = wld_pixman_create_context()))
        goto error0;

    if (!(swc.shm->renderer = wld_create_renderer(swc.shm->context)))
        goto error1;

    shm.global = wl_global_create(swc.display, &wl_shm_interface, 1,
                                  NULL, &bind_shm);

    if (!shm.global)
        goto error2;

    return true;

  error2:
    wld_destroy_renderer(swc.shm->renderer);
  error1:
    wld_destroy_context(swc.shm->context);
  error0:
    return false;
}

void shm_finalize(void)
{
    wl_global_destroy(shm.global);
    wld_destroy_renderer(swc.shm->renderer);
    wld_destroy_context(swc.shm->context);
}


text:
namespace power_sampler {

class Sampler;
class Monitor;
struct DataColumnKey;

// The sampling controller takes care of colleting datums from all samplers
// on a sampling event.
class SamplingController {
 public:
  SamplingController();
  ~SamplingController();

  // Adds |sampler| to this controller if it has a unique name.
  // Returns true if |sampler| was added to the controller.
  bool AddSampler(std::unique_ptr<Sampler> sampler);

  // Adds |monitor| to this controller.
  // Each monitor is called after a sample is acquired to evaluate whether the
  // sampling session should end.
  void AddMonitor(std::unique_ptr<Monitor> monitor);

  // Call once after all samplers and monitors have been added.
  // Will notify monitors that a session is starting.
  void StartSession();

  // Returns true iff this controller has all the samples it wants.
  bool OnSamplingEvent();

  // Call once after the last call to OnSamplingEvent.
  // Will notify monitors that a session has ended.
  void EndSession();

  // TODO(siggi): We want to at least have a sampling event provider that
  //     ticks on IOPMPowerSource change notification, plus a simple timed
  //     source.
  // TODO(siggi): We want to output samples in CSV at least, maybe other
  //     formats? Outputting samples as they're collected seems the best
  //     strategy?

 private:
  using Samplers = std::vector<std::unique_ptr<Sampler>>;
  using Monitors = std::vector<std::unique_ptr<Monitor>>;

  Samplers samplers_;
  Monitors monitors_;

  base::flat_map<DataColumnKey, std::string> data_columns_units_;

  bool started_ = false;
};

}  // namespace power_sampler

#endif  // TOOLS_MAC_POWER_POWER_SAMPLER_SAMPLING_CONTROLLER_H_


text:
import sys
import string
import logging

from util import mapper_logfile
logging.basicConfig(filename=mapper_logfile, format='%(message)s',
                    level=logging.INFO, filemode='w')

def mapper():
    """
    In this exercise, for each turnstile unit, you will determine the date and time
    (in the span of this data set) at which the most people entered through the unit.

    The input to the mapper will be the final Subway-MTA dataset, the same as
    in the previous exercise. You can check out the csv and its structure below:
    https://www.dropbox.com/s/meyki2wl9xfa7yk/turnstile_data_master_with_weather.csv

    For each line, the mapper should return the UNIT, ENTRIESn_hourly, DATEn, and
    TIMEn columns, separated by tabs. For example:
    'R001\t100000.0\t2011-05-01\t01:00:00'

    Since you are printing the output of your program, printing a debug
    statement will interfere with the operation of the grader. Instead,
    use the logging module, which we've configured to log to a file printed
    when you click "Test Run". For example:
    logging.info("My debugging message")
    """

    for line in sys.stdin:
        # your code here

        data = line.strip().split(",")

        if data[1] == 'UNIT' or len(data) != 22:
            continue
        else:
            print "{0}\t{1}\t{2}\t{3}".format(data[1],data[6],data[2],data[3])

mapper()


text:
/***************************************************************************
 *  Enrico Fucile                                                                         *
 ***************************************************************************/
#include "grib_api_internal.h"
/*
   This is used by make_class.pl

   START_CLASS_DEF
   CLASS      = action
   IMPLEMENTS = dump;xref
   IMPLEMENTS = destroy;execute
   MEMBERS    = grib_sarray *sarray
   MEMBERS    = char *name
   END_CLASS_DEF

 */

/* START_CLASS_IMP */

/*

Don't edit anything between START_CLASS_IMP and END_CLASS_IMP
Instead edit values between START_CLASS_DEF and END_CLASS_DEF
or edit "action.class" and rerun ./make_class.pl

*/

static void init_class      (grib_action_class*);
static void dump            (grib_action* d, FILE*,int);
static void xref            (grib_action* d, FILE* f,const char* path);
static void destroy         (grib_context*,grib_action*);
static int execute(grib_action* a,grib_handle* h);

typedef struct grib_action_set_sarray {
    grib_action          act;
/* Members defined in set_sarray */
	grib_sarray *sarray;
	char *name;
} grib_action_set_sarray;

static grib_action_class _grib_action_class_set_sarray = {
    0,                              /* super                     */
    "action_class_set_sarray",                              /* name                      */
    sizeof(grib_action_set_sarray),            /* size                      */
    0,                                   /* inited */
    &init_class,                         /* init_class */
    0,                               /* init                      */
    &destroy,                            /* destroy */

    &dump,                               /* dump                      */
    &xref,                               /* xref                      */

    0,             /* create_accessor*/

    0,                            /* notify_change */
    0,                            /* reparse */
    &execute,                            /* execute */
};

grib_action_class* grib_action_class_set_sarray = &_grib_action_class_set_sarray;

static void init_class(grib_action_class* c)
{
}
/* END_CLASS_IMP */

grib_action* grib_action_create_set_sarray( grib_context* context,
        const char* name,
        grib_sarray* sarray)
{
    char buf[1024];

    grib_action_set_sarray* a ;
    grib_action_class* c   = grib_action_class_set_sarray;
    grib_action* act       = (grib_action*)grib_context_malloc_clear_persistent(context,c->size);
    act->op              = grib_context_strdup_persistent(context,"section");

    act->cclass       = c;
    a                 = (grib_action_set_sarray*)act;
    act->context      = context;

    a->sarray  = sarray;
    a->name        = grib_context_strdup_persistent(context,name);

    sprintf(buf,"set_sarray%p",(void*)sarray);

    act->name      = grib_context_strdup_persistent(context,buf);

    return act;
}

static int execute(grib_action* a, grib_handle *h)
{
    grib_action_set_sarray* self = (grib_action_set_sarray*) a;

    return grib_set_string_array(h, self->name, (const char**)self->sarray->v, self->sarray->n);
}

static void dump(grib_action* act, FILE* f, int lvl)
{
    int i =0;
    grib_action_set_sarray* self=(grib_action_set_sarray*)act;
    for (i=0;i<lvl;i++)
        grib_context_print(act->context,f,"     ");
    grib_context_print(act->context,f,self->name);
    printf("\n");
}

static void destroy(grib_context* context,grib_action* act)
{
    grib_action_set_sarray* a = (grib_action_set_sarray*) act;

    grib_context_free_persistent(context, a->name);
    grib_sarray_delete(context,a->sarray);
    grib_context_free_persistent(context, act->name);
    grib_context_free_persistent(context, act->op);
}

static void xref(grib_action* d, FILE* f,const char *path)
{
}


text:
package info.re4k.asfc.croudia;

import info.re4k.asfc.croudia.http.HttpResponseCode;

public class CroudiaException extends Exception{
	private static final long serialVersionUID = 1L;
	private String message = null;
	private int statusCode = -1;
	private String errorMessage = null;
	private String errorResponseMessage = null;

	public CroudiaException(String message){
		this.message = message;
	}

	public CroudiaException(String message,int statusCode){
		this.message = message;
		this.statusCode = statusCode;
		this.errorMessage = getErrorMessage(statusCode);
	}

	public CroudiaException(String message,int statusCode,String errorResponseMessage){
		this.message = message;
		this.statusCode = statusCode;
		this.errorMessage = getErrorMessage(statusCode);
		this.errorResponseMessage = errorResponseMessage;
	}

	@Override
	public String getMessage(){
		return message;
	}

	public int getStatusCode(){
		return statusCode;
	}

	public String getErrorMessage(){
		return errorMessage;
	}

	public String getErrorResponseMessage(){
		return errorResponseMessage;
	}

	// http://developer.croudia.com/docs/206_response
	public static String getErrorMessage(int statusCode){
		if(statusCode==HttpResponseCode.Http_Success){// これは呼び出されないはず
			return "http request ok";
		}else if(statusCode==HttpResponseCode.Http_Not_Modified){
			return "新しいデータがない";
		}else if(statusCode==HttpResponseCode.Http_Bad_Request){
			return "リクエストに不正がある or レートリミットに達している or OAuthのシグニチャに問題がある";
		}else if(statusCode==HttpResponseCode.Http_Unauthorized){
			return "認証情報に誤りがある";
		}else if(statusCode==HttpResponseCode.Http_Forbidden){
			return "リクエスト拒否された";
		}else if(statusCode==HttpResponseCode.Http_Not_Found){
			return "リソースが存在していない";
		}else if(statusCode==HttpResponseCode.Http_Server_Internal_Error){
			return "サーバー側で問題が発生した";
		}else if(statusCode==HttpResponseCode.Http_Bad_Gateway){
			return "サーバ側に障害がある or サーバーの更新中";
		}else if(statusCode==HttpResponseCode.Http_Service_Unavailable){
			return "サーバーが過負荷になっている";
		}
		return "不明なエラーコード";
	}
}


text:
package org.apache.flume.auth;

/**
 * Simple Pair class used to define a unique (principal, keyTab) combination.
 */
public class KerberosUser {

  private final String principal;
  private final String keyTab;

  public KerberosUser(String principal, String keyTab) {
    this.principal = principal;
    this.keyTab = keyTab;
  }

  public String getPrincipal() {
    return principal;
  }

  public String getKeyTab() {
    return keyTab;
  }

  @Override
  public boolean equals(Object obj) {
    if (obj == null) {
      return false;
    }
    if (getClass() != obj.getClass()) {
      return false;
    }
    final KerberosUser other = (KerberosUser) obj;
    if ((this.principal == null) ?
        (other.principal != null) :
        !this.principal.equals(other.principal)) {
      return false;
    }
    if ((this.keyTab == null) ? (other.keyTab != null) : !this.keyTab.equals(other.keyTab)) {
      return false;
    }
    return true;
  }

  @Override
  public int hashCode() {
    int hash = 7;
    hash = 41 * hash + (this.principal != null ? this.principal.hashCode() : 0);
    hash = 41 * hash + (this.keyTab != null ? this.keyTab.hashCode() : 0);
    return hash;
  }

  @Override
  public String toString() {
    return "{ principal: " + principal + ", keytab: " + keyTab + " }";
  }
}


text:
<?php

/**
 * Thrown if the request body received was invalid.
 *
 * @package Webdav
 * @version //autogen//
 */
class ezcWebdavInvalidRequestBodyException extends ezcWebdavBadRequestException
{
    /**
     * Initializes the exception with the given $method and $reason and sets
     * the exception message from it.
     *
     * @param mixed $method
     * @param mixed $reason
     * @return void
     */
    public function __construct( $method, $reason = null )
    {
        parent::__construct(
            "The HTTP request body received for HTTP method '$method' was invalid." . ( $reason !== null ? " Reason: $reason" : '' )
        );
    }
}

?>