// SPDX-License-Identifier: GPL-2.0+
/*
 * STMicroelectronics TPM ST33ZP24 SPI UBOOT driver
 *
 * Copyright (C) 2016, STMicroelectronics - All Rights Reserved
 * Author(s): Christophe Ricard <christophe-h.ricard@st.com> for STMicroelectronics.
 *
 * Description: Device driver for ST33ZP24 SPI TPM TCG.
 *
 * This device driver implements the TPM interface as defined in
 * the TCG TPM Interface Spec version 1.21, revision 1.0 and the
 * STMicroelectronics Protocol Stack Specification version 1.2.0.
 */

#include <common.h>
#include <dm.h>
#include <fdtdec.h>
#include <log.h>
#include <spi.h>
#include <tpm-v1.h>
#include <errno.h>
#include <linux/delay.h>
#include <linux/types.h>
#include <asm/unaligned.h>
#include <linux/compat.h>

#include "tpm_tis.h"
#include "tpm_internal.h"

#define TPM_ACCESS			0x0
#define TPM_STS				0x18
#define TPM_DATA_FIFO			0x24

#define LOCALITY0			0

#define TPM_DATA_FIFO				0x24
#define TPM_INTF_CAPABILITY			0x14

#define TPM_DUMMY_BYTE				0x00
#define TPM_WRITE_DIRECTION			0x80

#define MAX_SPI_LATENCY				15
#define LOCALITY0				0

#define ST33ZP24_OK					0x5A
#define ST33ZP24_UNDEFINED_ERR				0x80
#define ST33ZP24_BADLOCALITY				0x81
#define ST33ZP24_TISREGISTER_UKNOWN			0x82
#define ST33ZP24_LOCALITY_NOT_ACTIVATED			0x83
#define ST33ZP24_HASH_END_BEFORE_HASH_START		0x84
#define ST33ZP24_BAD_COMMAND_ORDER			0x85
#define ST33ZP24_INCORECT_RECEIVED_LENGTH		0x86
#define ST33ZP24_TPM_FIFO_OVERFLOW			0x89
#define ST33ZP24_UNEXPECTED_READ_FIFO			0x8A
#define ST33ZP24_UNEXPECTED_WRITE_FIFO			0x8B
#define ST33ZP24_CMDRDY_SET_WHEN_PROCESSING_HASH_END	0x90
#define ST33ZP24_DUMMY_BYTES				0x00

/*
 * TPM command can be up to 2048 byte, A TPM response can be up to
 * 1024 byte.
 * Between command and response, there are latency byte (up to 15
 * usually on st33zp24 2 are enough).
 *
 * Overall when sending a command and expecting an answer we need if
 * worst case:
 * 2048 (for the TPM command) + 1024 (for the TPM answer).  We need
 * some latency byte before the answer is available (max 15).
 * We have 2048 + 1024 + 15.
 */
#define ST33ZP24_SPI_BUFFER_SIZE (TPM_BUFSIZE + (TPM_BUFSIZE / 2) +\
				  MAX_SPI_LATENCY)

struct st33zp24_spi_phy {
	int latency;

	u8 tx_buf[ST33ZP24_SPI_BUFFER_SIZE];
	u8 rx_buf[ST33ZP24_SPI_BUFFER_SIZE];
};

static int st33zp24_spi_status_to_errno(u8 code)
{
	switch (code) {
	case ST33ZP24_OK:
		return 0;
	case ST33ZP24_UNDEFINED_ERR:
	case ST33ZP24_BADLOCALITY:
	case ST33ZP24_TISREGISTER_UKNOWN:
	case ST33ZP24_LOCALITY_NOT_ACTIVATED:
	case ST33ZP24_HASH_END_BEFORE_HASH_START:
	case ST33ZP24_BAD_COMMAND_ORDER:
	case ST33ZP24_UNEXPECTED_READ_FIFO:
	case ST33ZP24_UNEXPECTED_WRITE_FIFO:
	case ST33ZP24_CMDRDY_SET_WHEN_PROCESSING_HASH_END:
		return -EPROTO;
	case ST33ZP24_INCORECT_RECEIVED_LENGTH:
	case ST33ZP24_TPM_FIFO_OVERFLOW:
		return -EMSGSIZE;
	case ST33ZP24_DUMMY_BYTES:
		return -ENOSYS;
	}
	return code;
}

/*
 * st33zp24_spi_send
 * Send byte to TPM register according to the ST33ZP24 SPI protocol.
 * @param: tpm, the chip description
 * @param: tpm_register, the tpm tis register where the data should be written
 * @param: tpm_data, the tpm_data to write inside the tpm_register
 * @param: tpm_size, The length of the data
 * @return: should be zero if success else a negative error code.
 */
static int st33zp24_spi_write(struct udevice *dev, u8 tpm_register,
			      const u8 *tpm_data, size_t tpm_size)
{
	int total_length = 0, ret;
	struct spi_slave *slave = dev_get_parent_priv(dev);
	struct st33zp24_spi_phy *phy = dev_get_platdata(dev);

	u8 *tx_buf = (u8 *)phy->tx_buf;
	u8 *rx_buf = phy->rx_buf;

	tx_buf[total_length++] = TPM_WRITE_DIRECTION | LOCALITY0;
	tx_buf[total_length++] = tpm_register;

	if (tpm_size > 0 && tpm_register == TPM_DATA_FIFO) {
		tx_buf[total_length++] = tpm_size >> 8;
		tx_buf[total_length++] = tpm_size;
	}
	memcpy(tx_buf + total_length, tpm_data, tpm_size);
	total_length += tpm_size;

	memset(tx_buf + total_length, TPM_DUMMY_BYTE, phy->latency);

	total_length += phy->latency;

	ret = spi_claim_bus(slave);
	if (ret < 0)
		return ret;

	ret = spi_xfer(slave, total_length * 8, tx_buf, rx_buf,
		       SPI_XFER_BEGIN | SPI_XFER_END);
	if (ret < 0)
		return ret;

	spi_release_bus(slave);

	if (ret == 0)
		ret = rx_buf[total_length - 1];

	return st33zp24_spi_status_to_errno(ret);
}

/*
 * spi_st33zp24_spi_read8_reg
 * Recv byte from the TIS register according to the ST33ZP24 SPI protocol.
 * @param: tpm, the chip description
 * @param: tpm_loc, the locality to read register from
 * @param: tpm_register, the tpm tis register where the data should be read
 * @param: tpm_data, the TPM response
 * @param: tpm_size, tpm TPM response size to read.
 * @return: should be zero if success else a negative error code.
 */
static u8 st33zp24_spi_read8_reg(struct udevice *dev, u8 tpm_register,
				 u8 *tpm_data, size_t tpm_size)
{
	int total_length = 0, ret;
	struct spi_slave *slave = dev_get_parent_priv(dev);
	struct st33zp24_spi_phy *phy = dev_get_platdata(dev);

	u8 *tx_buf = (u8 *)phy->tx_buf;
	u8 *rx_buf = phy->rx_buf;

	/* Pre-Header */
	tx_buf[total_length++] = LOCALITY0;
	tx_buf[total_length++] = tpm_register;

	memset(&tx_buf[total_length], TPM_DUMMY_BYTE,
	       phy->latency + tpm_size);
	total_length += phy->latency + tpm_size;

	ret = spi_claim_bus(slave);
	if (ret < 0)
		return 0;

	ret = spi_xfer(slave, total_length * 8, tx_buf, rx_buf,
		       SPI_XFER_BEGIN | SPI_XFER_END);
	if (ret < 0)
		return 0;

	spi_release_bus(slave);

	if (tpm_size > 0 && ret == 0) {
		ret = rx_buf[total_length - tpm_size - 1];
		memcpy(tpm_data, rx_buf + total_length - tpm_size, tpm_size);
	}
	return ret;
}

/*
 * st33zp24_spi_recv
 * Recv byte from the TIS register according to the ST33ZP24 SPI protocol.
 * @param: phy_id, the phy description
 * @param: tpm_register, the tpm tis register where the data should be read
 * @param: tpm_data, the TPM response
 * @param: tpm_size, tpm TPM response size to read.
 * @return: number of byte read successfully: should be one if success.
 */
static int st33zp24_spi_read(struct udevice *dev, u8 tpm_register,
			     u8 *tpm_data, size_t tpm_size)
{
	int ret;

	ret = st33zp24_spi_read8_reg(dev, tpm_register, tpm_data, tpm_size);
	if (!st33zp24_spi_status_to_errno(ret))
		return tpm_size;

	return ret;
}

static int st33zp24_spi_evaluate_latency(struct udevice *dev)
{
	int latency = 1, status = 0;
	u8 data = 0;
	struct st33zp24_spi_phy *phy = dev_get_platdata(dev);

	while (!status && latency < MAX_SPI_LATENCY) {
		phy->latency = latency;
		status = st33zp24_spi_read8_reg(dev, TPM_INTF_CAPABILITY,
						&data, 1);
		latency++;
	}
	if (status < 0)
		return status;
	if (latency == MAX_SPI_LATENCY)
		return -ENODEV;

	return latency - 1;
}

/*
 * st33zp24_spi_release_locality release the active locality
 * @param: chip, the tpm chip description.
 */
static void st33zp24_spi_release_locality(struct udevice *dev)
{
	u8 data = TPM_ACCESS_ACTIVE_LOCALITY;

	st33zp24_spi_write(dev, TPM_ACCESS, &data, 1);
}

/*
 * st33zp24_spi_check_locality if the locality is active
 * @param: chip, the tpm chip description
 * @return: the active locality or -EACCES.
 */
static int st33zp24_spi_check_locality(struct udevice *dev)
{
	u8 data;
	u8 status;
	struct tpm_chip *chip = dev_get_priv(dev);

	status = st33zp24_spi_read(dev, TPM_ACCESS, &data, 1);
	if (status && (data &
		(TPM_ACCESS_ACTIVE_LOCALITY | TPM_ACCESS_VALID)) ==
		(TPM_ACCESS_ACTIVE_LOCALITY | TPM_ACCESS_VALID))
		return chip->locality;

	return -EACCES;
}

/*
 * st33zp24_spi_request_locality request the TPM locality
 * @param: chip, the chip description
 * @return: the active locality or negative value.
 */
static int st33zp24_spi_request_locality(struct udevice *dev)
{
	unsigned long start, stop;
	long ret;
	u8 data;
	struct tpm_chip *chip = dev_get_priv(dev);

	if (st33zp24_spi_check_locality(dev) == chip->locality)
		return chip->locality;

	data = TPM_ACCESS_REQUEST_USE;
	ret = st33zp24_spi_write(dev, TPM_ACCESS, &data, 1);
	if (ret < 0)
		return ret;

	/* wait for locality activated */
	start = get_timer(0);
	stop = chip->timeout_a;
	do {
		if (st33zp24_spi_check_locality(dev) >= 0)
			return chip->locality;
		udelay(TPM_TIMEOUT_MS * 1000);
	} while	 (get_timer(start) < stop);

	return -EACCES;
}

/*
 * st33zp24_spi_status return the TPM_STS register
 * @param: chip, the tpm chip description
 * @return: the TPM_STS register value.
 */
static u8 st33zp24_spi_status(struct udevice *dev)
{
	u8 data;

	st33zp24_spi_read(dev, TPM_STS, &data, 1);
	return data;
}

/*
 * st33zp24_spi_get_burstcount return the burstcount address 0x19 0x1A
 * @param: chip, the chip description
 * return: the burstcount or -TPM_DRIVER_ERR in case of error.
 */
static int st33zp24_spi_get_burstcount(struct udevice *dev)
{
	struct tpm_chip *chip = dev_get_priv(dev);
	unsigned long start, stop;
	int burstcnt, status;
	u8 tpm_reg, temp;

	/* wait for burstcount */
	start = get_timer(0);
	stop = chip->timeout_d;
	do {
		tpm_reg = TPM_STS + 1;
		status = st33zp24_spi_read(dev, tpm_reg, &temp, 1);
		if (status < 0)
			return -EBUSY;

		tpm_reg = TPM_STS + 2;
		burstcnt = temp;
		status = st33zp24_spi_read(dev, tpm_reg, &temp, 1);
		if (status < 0)
			return -EBUSY;

		burstcnt |= temp << 8;
		if (burstcnt)
			return burstcnt;
		udelay(TIS_SHORT_TIMEOUT_MS * 1000);
	} while (get_timer(start) < stop);

	return -EBUSY;
}

/*
 * st33zp24_spi_cancel, cancel the current command execution or
 * set STS to COMMAND READY.
 * @param: chip, tpm_chip description.
 */
static void st33zp24_spi_cancel(struct udevice *dev)
{
	u8 data;

	data = TPM_STS_COMMAND_READY;
	st33zp24_spi_write(dev, TPM_STS, &data, 1);
}

/*
 * st33zp24_spi_wait_for_stat wait for a TPM_STS value
 * @param: chip, the tpm chip description
 * @param: mask, the value mask to wait
 * @param: timeout, the timeout
 * @param: status,
 * @return: the tpm status, 0 if success, -ETIME if timeout is reached.
 */
static int st33zp24_spi_wait_for_stat(struct udevice *dev, u8 mask,
				  unsigned long timeout, int *status)
{
	unsigned long start, stop;

	/* Check current status */
	*status = st33zp24_spi_status(dev);
	if ((*status & mask) == mask)
		return 0;

	start = get_timer(0);
	stop = timeout;
	do {
		udelay(TPM_TIMEOUT_MS * 1000);
		*status = st33zp24_spi_status(dev);
		if ((*status & mask) == mask)
			return 0;
	} while (get_timer(start) < stop);

	return -ETIME;
}

/*
 * st33zp24_spi_recv_data receive data
 * @param: chip, the tpm chip description
 * @param: buf, the buffer where the data are received
 * @param: count, the number of data to receive
 * @return: the number of bytes read from TPM FIFO.
 */
static int st33zp24_spi_recv_data(struct udevice *dev, u8 *buf, size_t count)
{
	struct tpm_chip *chip = dev_get_priv(dev);
	int size = 0, burstcnt, len, ret, status;

	while (size < count &&
	       st33zp24_spi_wait_for_stat(dev, TPM_STS_DATA_AVAIL | TPM_STS_VALID,
				chip->timeout_c, &status) == 0) {
		burstcnt = st33zp24_spi_get_burstcount(dev);
		if (burstcnt < 0)
			return burstcnt;
		len = min_t(int, burstcnt, count - size);
		ret = st33zp24_spi_read(dev, TPM_DATA_FIFO, buf + size, len);
		if (ret < 0)
			return ret;

		size += len;
	}
	return size;
}

/*
 * st33zp24_spi_recv received TPM response through TPM phy.
 * @param: chip, tpm_chip description.
 * @param: buf,	the buffer to store data.
 * @param: count, the number of bytes that can received (sizeof buf).
 * @return: Returns zero in case of success else -EIO.
 */
static int st33zp24_spi_recv(struct udevice *dev, u8 *buf, size_t count)
{
	struct tpm_chip *chip = dev_get_priv(dev);
	int size;
	unsigned int expected;

	if (!chip)
		return -ENODEV;

	if (count < TPM_HEADER_SIZE) {
		size = -EIO;
		goto out;
	}

	size = st33zp24_spi_recv_data(dev, buf, TPM_HEADER_SIZE);
	if (size < TPM_HEADER_SIZE) {
		debug("TPM error, unable to read header\n");
		goto out;
	}

	expected = get_unaligned_be32(buf + 2);
	if (expected > count || expected < TPM_HEADER_SIZE) {
		size = -EIO;
		goto out;
	}

	size += st33zp24_spi_recv_data(dev, &buf[TPM_HEADER_SIZE],
				   expected - TPM_HEADER_SIZE);
	if (size < expected) {
		debug("TPM error, unable to read remaining bytes of result\n");
		size = -EIO;
		goto out;
	}

out:
	st33zp24_spi_cancel(dev);
	st33zp24_spi_release_locality(dev);

	return size;
}

/*
 * st33zp24_spi_send send TPM commands through TPM phy.
 * @param: chip, tpm_chip description.
 * @param: buf,	the buffer to send.
 * @param: len, the number of bytes to send.
 * @return: Returns zero in case of success else the negative error code.
 */
static int st33zp24_spi_send(struct udevice *dev, const u8 *buf, size_t len)
{
	struct tpm_chip *chip = dev_get_priv(dev);
	u32 i, size;
	int burstcnt, ret, status;
	u8 data, tpm_stat;

	if (!chip)
		return -ENODEV;
	if (len < TPM_HEADER_SIZE)
		return -EIO;

	ret = st33zp24_spi_request_locality(dev);
	if (ret < 0)
		return ret;

	tpm_stat = st33zp24_spi_status(dev);
	if ((tpm_stat & TPM_STS_COMMAND_READY) == 0) {
		st33zp24_spi_cancel(dev);
		if (st33zp24_spi_wait_for_stat(dev, TPM_STS_COMMAND_READY,
					       chip->timeout_b, &status) < 0) {
			ret = -ETIME;
			goto out_err;
		}
	}

	for (i = 0; i < len - 1;) {
		burstcnt = st33zp24_spi_get_burstcount(dev);
		if (burstcnt < 0)
			return burstcnt;

		size = min_t(int, len - i - 1, burstcnt);
		ret = st33zp24_spi_write(dev, TPM_DATA_FIFO, buf + i, size);
		if (ret < 0)
			goto out_err;

		i += size;
	}

	tpm_stat = st33zp24_spi_status(dev);
	if ((tpm_stat & TPM_STS_DATA_EXPECT) == 0) {
		ret = -EIO;
		goto out_err;
	}

	ret = st33zp24_spi_write(dev, TPM_DATA_FIFO, buf + len - 1, 1);
	if (ret < 0)
		goto out_err;

	tpm_stat = st33zp24_spi_status(dev);
	if ((tpm_stat & TPM_STS_DATA_EXPECT) != 0) {
		ret = -EIO;
		goto out_err;
	}

	data = TPM_STS_GO;
	ret = st33zp24_spi_write(dev, TPM_STS, &data, 1);
	if (ret < 0)
		goto out_err;

	return len;

out_err:
	st33zp24_spi_cancel(dev);
	st33zp24_spi_release_locality(dev);

	return ret;
}

static int st33zp24_spi_cleanup(struct udevice *dev)
{
	st33zp24_spi_cancel(dev);
	/*
	 * The TPM needs some time to clean up here,
	 * so we sleep rather than keeping the bus busy
	 */
	mdelay(2);
	st33zp24_spi_release_locality(dev);

	return 0;
}

static int st33zp24_spi_init(struct udevice *dev)
{
	struct tpm_chip *chip = dev_get_priv(dev);
	struct st33zp24_spi_phy *phy = dev_get_platdata(dev);

	chip->is_open = 1;

	/* Default timeouts - these could move to the device tree */
	chip->timeout_a = TIS_SHORT_TIMEOUT_MS;
	chip->timeout_b = TIS_LONG_TIMEOUT_MS;
	chip->timeout_c = TIS_SHORT_TIMEOUT_MS;
	chip->timeout_d = TIS_SHORT_TIMEOUT_MS;

	chip->locality = LOCALITY0;

	phy->latency = st33zp24_spi_evaluate_latency(dev);
	if (phy->latency <= 0)
		return -ENODEV;

	/*
	 * A timeout query to TPM can be placed here.
	 * Standard timeout values are used so far
	 */

	return 0;
}

static int st33zp24_spi_open(struct udevice *dev)
{
	struct tpm_chip *chip = dev_get_priv(dev);
	int rc;

	debug("%s: start\n", __func__);
	if (chip->is_open)
		return -EBUSY;

	rc = st33zp24_spi_init(dev);
	if (rc < 0)
		chip->is_open = 0;

	return rc;
}

static int st33zp24_spi_close(struct udevice *dev)
{
	struct tpm_chip *chip = dev_get_priv(dev);

	if (chip->is_open) {
		st33zp24_spi_release_locality(dev);
		chip->is_open = 0;
		chip->vend_dev = 0;
	}

	return 0;
}

static int st33zp24_spi_get_desc(struct udevice *dev, char *buf, int size)
{
	struct tpm_chip *chip = dev_get_priv(dev);

	if (size < 50)
		return -ENOSPC;

	return snprintf(buf, size, "1.2 TPM (%s, chip type %s device-id 0x%x)",
			chip->is_open ? "open" : "closed",
			dev->name,
			chip->vend_dev >> 16);
}

const struct tpm_ops st33zp24_spi_tpm_ops = {
	.open = st33zp24_spi_open,
	.close = st33zp24_spi_close,
	.recv = st33zp24_spi_recv,
	.send = st33zp24_spi_send,
	.cleanup = st33zp24_spi_cleanup,
	.get_desc = st33zp24_spi_get_desc,
};

static int st33zp24_spi_probe(struct udevice *dev)
{
	struct tpm_chip_priv *uc_priv = dev_get_uclass_priv(dev);

	uc_priv->duration_ms[TPM_SHORT] = TIS_SHORT_TIMEOUT_MS;
	uc_priv->duration_ms[TPM_MEDIUM] = TIS_LONG_TIMEOUT_MS;
	uc_priv->duration_ms[TPM_LONG] = TIS_LONG_TIMEOUT_MS;
	uc_priv->retry_time_ms = TPM_TIMEOUT_MS;

	debug("ST33ZP24 SPI TPM from STMicroelectronics found\n");

	return 0;
}

static int st33zp24_spi_remove(struct udevice *dev)
{
	st33zp24_spi_release_locality(dev);

	return 0;
}

static const struct udevice_id st33zp24_spi_ids[] = {
	{ .compatible = "st,st33zp24-spi" },
	{ }
};

U_BOOT_DRIVER(st33zp24_spi_spi) = {
	.name   = "st33zp24-spi",
	.id     = UCLASS_TPM,
	.of_match = of_match_ptr(st33zp24_spi_ids),
	.probe  = st33zp24_spi_probe,
	.remove = st33zp24_spi_remove,
	.ops = &st33zp24_spi_tpm_ops,
	.priv_auto_alloc_size = sizeof(struct tpm_chip),
	.platdata_auto_alloc_size = sizeof(struct st33zp24_spi_phy),
};

{'repo_name': 'u-boot/u-boot', 'stars': '1164', 'repo_language': 'C', 'file_name': 'Makefile', 'mime_type': 'text/plain', 'hash': 3336547921802389388, 'source_dataset': 'data'}


var baseSlice = require('../internal/baseSlice'),
    isIterateeCall = require('../internal/isIterateeCall');

/**
 * Creates a slice of `array` from `start` up to, but not including, `end`.
 *
 * **Note:** This method is used instead of `Array#slice` to support node
 * lists in IE < 9 and to ensure dense arrays are returned.
 *
 * @static
 * @memberOf _
 * @category Array
 * @param {Array} array The array to slice.
 * @param {number} [start=0] The start position.
 * @param {number} [end=array.length] The end position.
 * @returns {Array} Returns the slice of `array`.
 */
function slice(array, start, end) {
  var length = array ? array.length : 0;
  if (!length) {
    return [];
  }
  if (end && typeof end != 'number' && isIterateeCall(array, start, end)) {
    start = 0;
    end = length;
  }
  return baseSlice(array, start, end);
}

module.exports = slice;

{'repo_name': 'sudo-js/cash', 'stars': '130', 'repo_language': 'JavaScript', 'file_name': 'test.js', 'mime_type': 'text/plain', 'hash': -8296197283331417414, 'source_dataset': 'data'}


package org.mockserver.templates.engine.serializer;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.mockserver.log.model.LogEntry;
import org.mockserver.logging.MockServerLogger;
import org.mockserver.model.HttpRequest;
import org.mockserver.serialization.ObjectMapperFactory;
import org.mockserver.serialization.model.DTO;
import org.mockserver.serialization.model.HttpRequestDTO;
import org.mockserver.serialization.model.HttpResponseDTO;
import org.mockserver.validator.jsonschema.JsonSchemaHttpRequestValidator;
import org.mockserver.validator.jsonschema.JsonSchemaHttpResponseValidator;
import org.slf4j.event.Level;

import static org.apache.commons.lang3.StringUtils.isEmpty;
import static org.apache.commons.lang3.StringUtils.uncapitalize;
import static org.mockserver.validator.jsonschema.JsonSchemaHttpRequestValidator.jsonSchemaHttpRequestValidator;
import static org.mockserver.validator.jsonschema.JsonSchemaHttpResponseValidator.jsonSchemaHttpResponseValidator;

/**
 * @author jamesdbloom
 */
public class HttpTemplateOutputDeserializer {

    private static ObjectMapper objectMapper = ObjectMapperFactory.createObjectMapper();
    private final MockServerLogger mockServerLogger;
    private JsonSchemaHttpRequestValidator httpRequestValidator;
    private JsonSchemaHttpResponseValidator httpResponseValidator;

    public HttpTemplateOutputDeserializer(MockServerLogger mockServerLogger) {
        this.mockServerLogger = mockServerLogger;
        httpRequestValidator = jsonSchemaHttpRequestValidator(mockServerLogger);
        httpResponseValidator = jsonSchemaHttpResponseValidator(mockServerLogger);
    }

    public <T> T deserializer(HttpRequest request, String json, Class<? extends DTO<T>> dtoClass) {
        T result = null;
        try {
            String validationErrors = "";
            if (dtoClass.isAssignableFrom(HttpResponseDTO.class)) {
                validationErrors = httpResponseValidator.isValid(json);
            } else if (dtoClass.isAssignableFrom(HttpRequestDTO.class)) {
                validationErrors = httpRequestValidator.isValid(json);
            }
            if (isEmpty(validationErrors)) {
                result = objectMapper.readValue(json, dtoClass).buildObject();
            } else {
                mockServerLogger.logEvent(
                    new LogEntry()
                        .setLogLevel(Level.ERROR)
                        .setHttpRequest(request)
                        .setMessageFormat("validation failed:{}" + uncapitalize(dtoClass.getSimpleName()) + ":{}")
                        .setArguments(validationErrors, json)
                );
            }
        } catch (Exception e) {
            mockServerLogger.logEvent(
                new LogEntry()
                    .setLogLevel(Level.ERROR)
                    .setHttpRequest(request)
                    .setMessageFormat("exception transforming json:{}")
                    .setArguments(json)
                    .setThrowable(e)
            );
        }
        return result;
    }
}

{'repo_name': 'mock-server/mockserver', 'stars': '2724', 'repo_language': 'Java', 'file_name': 'AssertTest.java', 'mime_type': 'text/x-java', 'hash': 5507141074556621413, 'source_dataset': 'data'}


/*
 * Copyright (C) 2010 ZXing authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package jiguang.chat.utils.zxing.camera;

import android.graphics.Point;
import android.hardware.Camera;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

public class PreviewCallback implements Camera.PreviewCallback {

	static final String TAG = PreviewCallback.class.getSimpleName();

	final CameraConfigurationManager configManager;
	Handler previewHandler;
	int previewMessage;

	public PreviewCallback(CameraConfigurationManager configManager) {
		this.configManager = configManager;
	}

	public void setHandler(Handler previewHandler, int previewMessage) {
		this.previewHandler = previewHandler;
		this.previewMessage = previewMessage;
	}

	@Override
	public void onPreviewFrame(byte[] data, Camera camera) {
		Point cameraResolution = configManager.getCameraResolution();
		Handler thePreviewHandler = previewHandler;
		if (cameraResolution != null && thePreviewHandler != null) {
			Message message = thePreviewHandler.obtainMessage(previewMessage, cameraResolution.x, cameraResolution.y, data);
			message.sendToTarget();
			previewHandler = null;
		} else {
			Log.d(TAG, "Got preview callback, but no handler or resolution available");
		}
	}

}

{'repo_name': 'jpush/jchat-android', 'stars': '353', 'repo_language': 'Java', 'file_name': 'DefEmoticons.java', 'mime_type': 'text/x-java', 'hash': 1483080901742253031, 'source_dataset': 'data'}


alert('hi');
alert('hello');

if (something) {

}

function myFunction()
{
    alert('code here');

    alert('code here');

    // Hello.

    /*
        HI
    */

}

function myFunction2()
{
    alert('code here');

    alert('code here');

}

MyFunction = function()
{
    alert('code here');

    alert('code here');

};

// phpcs:set Squiz.WhiteSpace.SuperfluousWhitespace ignoreBlankLines true

function myFunction2()
{
    alert('code here');

    alert('code here');

}

// phpcs:set Squiz.WhiteSpace.SuperfluousWhitespace ignoreBlankLines false

{'repo_name': 'spotweb/spotweb', 'stars': '296', 'repo_language': 'PHP', 'file_name': 'jquery.mobile-1.4.5.js', 'mime_type': 'text/plain', 'hash': 4998139355320864504, 'source_dataset': 'data'}


/**
* Copyright 2012-2020, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Registry = require('../registry');

exports.getDelay = function(fullLayout) {
    if(!fullLayout._has) return 0;

    return (
        fullLayout._has('gl3d') ||
        fullLayout._has('gl2d') ||
        fullLayout._has('mapbox')
    ) ? 500 : 0;
};

exports.getRedrawFunc = function(gd) {
    return function() {
        var fullLayout = gd._fullLayout || {};
        var hasPolar = fullLayout._has && fullLayout._has('polar');
        var hasLegacyPolar = !hasPolar && gd.data && gd.data[0] && gd.data[0].r;

        if(!hasLegacyPolar) {
            Registry.getComponentMethod('colorbar', 'draw')(gd);
        }
    };
};

exports.encodeSVG = function(svg) {
    return 'data:image/svg+xml,' + encodeURIComponent(svg);
};

exports.encodeJSON = function(json) {
    return 'data:application/json,' + encodeURIComponent(json);
};

var DOM_URL = window.URL || window.webkitURL;

exports.createObjectURL = function(blob) {
    return DOM_URL.createObjectURL(blob);
};

exports.revokeObjectURL = function(url) {
    return DOM_URL.revokeObjectURL(url);
};

exports.createBlob = function(url, format) {
    if(format === 'svg') {
        return new window.Blob([url], {type: 'image/svg+xml;charset=utf-8'});
    } else if(format === 'full-json') {
        return new window.Blob([url], {type: 'application/json;charset=utf-8'});
    } else {
        var binary = fixBinary(window.atob(url));
        return new window.Blob([binary], {type: 'image/' + format});
    }
};

exports.octetStream = function(s) {
    document.location.href = 'data:application/octet-stream' + s;
};

// Taken from https://bl.ocks.org/nolanlawson/0eac306e4dac2114c752
function fixBinary(b) {
    var len = b.length;
    var buf = new ArrayBuffer(len);
    var arr = new Uint8Array(buf);
    for(var i = 0; i < len; i++) {
        arr[i] = b.charCodeAt(i);
    }
    return buf;
}

exports.IMAGE_URL_PREFIX = /^data:image\/\w+;base64,/;

exports.MSG_IE_BAD_FORMAT = 'Sorry IE does not support downloading from canvas. Try {format:\'svg\'} instead.';

{'repo_name': 'plotly/plotly.js', 'stars': '11975', 'repo_language': 'JavaScript', 'file_name': 'config.yml', 'mime_type': 'text/plain', 'hash': -3223705759374851036, 'source_dataset': 'data'}


/*
 * Copyright (C) 2001-2003 Peter J Jones (pjones@pmade.org)
 * All Rights Reserved
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 * 3. Neither the name of the Author nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS''
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
 * PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

/** @file
 * This file contains the implementation of the Netxx::Datagram class.
**/

// common header
#include "common.h"

// Netxx includes
#include "Netxx/Datagram.h"
#include "Netxx/Address.h"
#include "Netxx/Peer.h"
#include "Socket.h"
#include "SockAddr.h"
#include "RecvFrom.h"
#include "OSError.h"

// system includes
#if defined (WIN32)
# include <winsock2.h>
#else
# include <sys/types.h>
# include <sys/socket.h>
# include <sys/un.h>
# include <errno.h>
# include <stdio.h>
# include <unistd.h>
# include <sys/stat.h>
#endif

// standard includes
#include <string>
#include <memory>
#include <cstring>
#include <vector>
#include <cstdlib>

namespace {
    void call_connect(Netxx::Socket &socket, const Netxx::Peer &peer, std::vector<std::string> &files);
    void call_bind(Netxx::Socket &socket, std::vector<std::string> &files);
    void get_tmp_filename (std::string &tmp_name);
}

//####################################################################
struct Netxx::Datagram::pimpl {
    pimpl (const Timeout &timeout) : timeout_(timeout) {}
    pimpl (const Timeout &timeout, socket_type socketfd) : timeout_(timeout), socket_(socketfd) {}

    ~pimpl (void) {
#   ifndef WIN32
	if (!files_.empty()) {
	    socket_.close();

	    std::vector<std::string>::const_iterator i(files_.begin()), end(files_.end());
	    for (; i!=end; ++i) unlink(i->c_str());
	}
#   endif
    }

    Timeout timeout_;
    Socket socket_;
    ProbeInfo pi_;
    std::vector<std::string> files_;
};
//####################################################################
Netxx::Datagram::Datagram (const Address &connect_to, const Timeout &timeout) {
    if (!connect_to.size()) throw Exception("no addresses to call connect for");
    std::auto_ptr<pimpl> ap(pimpl_ = new pimpl(timeout));

    call_connect(pimpl_->socket_, *connect_to.begin(), pimpl_->files_);
    pimpl_->pi_.add_socket(pimpl_->socket_.get_socketfd());

    ap.release();
}
//####################################################################
Netxx::Datagram::Datagram (const char *peer_name, port_type default_port, const Timeout &timeout) {
    Address connect_to(peer_name, default_port);
    std::auto_ptr<pimpl> ap(pimpl_ = new pimpl(timeout));

    call_connect(pimpl_->socket_, *connect_to.begin(), pimpl_->files_);
    pimpl_->pi_.add_socket(pimpl_->socket_.get_socketfd());

    ap.release();
}
//####################################################################
Netxx::Datagram::Datagram (socket_type socketfd, const Timeout &timeout) {
    std::auto_ptr<pimpl> ap (pimpl_ = new pimpl(timeout, socketfd));

    pimpl_->pi_.add_socket(pimpl_->socket_.get_socketfd());

    ap.release();
}
//####################################################################
Netxx::Datagram::Datagram (const Timeout &timeout) {
    std::auto_ptr<pimpl> ap (pimpl_ = new pimpl(timeout));

    pimpl_->pi_.add_socket(pimpl_->socket_.get_socketfd());

    ap.release();
}
//####################################################################
Netxx::Datagram::~Datagram (void) {
    delete pimpl_;
}
//####################################################################
Netxx::signed_size_type Netxx::Datagram::send (const Peer &peer, const void *buffer, size_type length) {
#   if defined(WIN32)
	const char *buffer_ptr = static_cast<const char*>(buffer);
#   else
	const void *buffer_ptr = buffer;
#   endif

    const sockaddr *sa = reinterpret_cast<const sockaddr*>(peer.get_sa());
    size_type sa_size = peer.get_sa_size();
    bool correct_type = false;

    /*
     * make sure our socket is setup to handle this type of peer
     */
    if (peer.get_socketfd() != -1 && peer.get_socketfd() == pimpl_->socket_.get_socketfd()) {
	// we have to be ready!
	correct_type = true;
    } else if (pimpl_->socket_.get_socketfd() >= 0) {
	Socket::Type stype = pimpl_->socket_.get_type();

	switch (stype) {
#   ifndef WIN32
	    case Socket::LOCALDGRAM:
		correct_type = sa->sa_family == AF_LOCAL;
		break;
#   endif

	    case Socket::UDP:
		correct_type = sa->sa_family == AF_INET;
		break;

#   ifndef NETXX_NO_INET6
	    case Socket::UDP6:
		correct_type = sa->sa_family == AF_INET6;
		break;
#   endif

	    default:
		break;
	}
    }

    if (!correct_type) {
	Socket::Type stype;

	switch (sa->sa_family) {
	    case AF_INET:
		stype = Socket::UDP;
		break;

#   ifndef NETXX_NO_INET6
	    case AF_INET6:
		stype = Socket::UDP6;
		break;
#   endif

#   ifndef WIN32
	    case AF_LOCAL:
		stype = Socket::LOCALDGRAM;
		break;
#   endif
	    default:
		stype = Socket::UDP;
	}

	Socket tmp_socket(stype);
	pimpl_->socket_.swap(tmp_socket);
	call_bind(pimpl_->socket_, pimpl_->files_);
    }

    if (pimpl_->timeout_ && !pimpl_->socket_.writable(pimpl_->timeout_))
	return -1;

    signed_size_type rc;
    if ( (rc = sendto(pimpl_->socket_.get_socketfd(), buffer_ptr, length, 0, sa, sa_size)) < 0) {
	std::string error("sendto(2) failure: ");
	error += strerror(get_last_error());
	throw Exception(error);
    }

    return rc;
}
//####################################################################
Netxx::Datagram::receive_type Netxx::Datagram::receive (void *buffer, size_type length) {
    /*
     * if this is not a connected datagram, the socket might not be ready
     * yet. We can't receive a datagram because we don't know if it should
     * be a AF_INET, AF_INET6 or even a AF_LOCAL datagram.
     */
    if (pimpl_->socket_.get_socketfd() < 0)
	throw Exception("can't receive datagram unless one is sent first");

    if (pimpl_->timeout_ && !pimpl_->socket_.readable(pimpl_->timeout_))
	return std::make_pair(-1, Peer());

    return call_recvfrom(pimpl_->socket_, buffer, length);
}
//####################################################################
Netxx::signed_size_type Netxx::Datagram::write (const void *buffer, size_type length) {
    return pimpl_->socket_.write(buffer, length, pimpl_->timeout_);
}
//####################################################################
Netxx::signed_size_type Netxx::Datagram::read (void *buffer, size_type length) {
    return pimpl_->socket_.read(buffer, length, pimpl_->timeout_);
}
//####################################################################
void Netxx::Datagram::close (void) {
    pimpl_->socket_.close();
    pimpl_->pi_.clear();
}
//####################################################################
void Netxx::Datagram::release (void) {
    pimpl_->socket_.release();
}
//####################################################################
const Netxx::ProbeInfo* Netxx::Datagram::get_probe_info (void) const {
    return &(pimpl_->pi_);
}
//####################################################################

namespace {

    //####################################################################
    void call_connect (Netxx::Socket &socket, const Netxx::Peer &peer, std::vector<std::string> &files) {
	const sockaddr *sa = reinterpret_cast<const sockaddr*>(peer.get_sa());
	Netxx::size_type sa_size = peer.get_sa_size();
	Netxx::Socket::Type stype;

	switch (sa->sa_family) {
	    case AF_INET:
		stype = Netxx::Socket::UDP;
		break;

# ifndef NETXX_NO_INET6
	    case AF_INET6:
		stype = Netxx::Socket::UDP6;
		break;
# endif

# ifndef WIN32
	    case AF_LOCAL:
		stype = Netxx::Socket::LOCALDGRAM;
		break;
# endif

	    default:
		stype = Netxx::Socket::UDP;
	}

	Netxx::Socket tmp_socket(stype);
	socket.swap(tmp_socket);
	call_bind(socket, files);

	if (connect(socket.get_socketfd(), sa, sa_size) != 0) {
	    std::string error("connect(2) failed: ");
	    error += strerror(Netxx::get_last_error());
	    throw Netxx::Exception(error);
	}
    }
    //####################################################################
    void call_bind (Netxx::Socket &socket, std::vector<std::string> &files) {
#	ifndef WIN32
	    if (socket.get_type() == Netxx::Socket::LOCALDGRAM) {
		Netxx::SockAddr socket_addr(socket.get_type());
		sockaddr_un *saun = reinterpret_cast<sockaddr_un*>(socket_addr.get_sa());
		Netxx::size_type saun_size = socket_addr.get_sa_size();

		std::string tmp_name;
		get_tmp_filename(tmp_name);
		files.push_back(tmp_name);

		if (tmp_name.size() >= sizeof(saun->sun_path))
		    throw Netxx::Exception("temp name is too large for sockaddr_un");

		std::strcpy(saun->sun_path, tmp_name.c_str());

		if (bind(socket.get_socketfd(), reinterpret_cast<sockaddr*>(saun), saun_size) != 0) {
		    std::string error("bind(2) error: ");
		    error += strerror(Netxx::get_last_error());
		    throw Netxx::Exception(error);
		}

		/*
		 * This will make a local domain socket more like a real
		 * socket since anyone with local file system access can
		 * connect to it. This may be a bad thing in this case
		 * though. More to come.
		 */
		chmod(saun->sun_path, 0666);
	    }
#	endif
    }
    //####################################################################
    void get_tmp_filename (std::string &tmp_name) {
#	ifndef WIN32
	    char buffer[] = "/tmp/Netxx_Domain_Socket.XXXXXXXXXXXXXXXXX";
	    int fd;

	    if ( (fd = mkstemp(buffer)) < 0) {
		std::string error("can't create temporary file: ");
		error += strerror(Netxx::get_last_error());
		throw Netxx::Exception(error);
	    }

	    /*
	     * WARNING WARNING WARNING WARNING
	     *
	     * The following action could create a race condition.  It may
	     * not be that big of a deal in this case since when we call
	     * bind(2) and it will fail if the file in sun_path already
	     * exists.
	     *
	     * So, if we close and unlink the file, and then before we call
	     * bind(2) someone creates a file with the same name, bind
	     * should fail.
	     *
	     * It might just be better to use tmpnam(3) but then you have to
	     * see the linker warning about tmpnam might be used in an
	     * unsafe manner. I think what we have here should be good
	     * enough.
	     *
	     * WARNING WARNING WARNING WARNING
	     */
	    close(fd);
	    unlink(buffer);

	    tmp_name = buffer;
#	endif
    }
    //####################################################################

} // end anonymous namespace

{'repo_name': 'resiprocate/resiprocate', 'stars': '333', 'repo_language': 'C++', 'file_name': 'TestClient_14_0.vcxproj', 'mime_type': 'text/xml', 'hash': -5353154462925524285, 'source_dataset': 'data'}


<!--
 Copyright (c) 2016, the Dart project authors.  Please see the AUTHORS file
 for details. All rights reserved. Use of this source code is governed by a
 BSD-style license that can be found in the LICENSE file.
-->
<div *ngIf="!supportsMultiSelect && isSelected"
    class="selected-accent mixin">
</div>
&ngsp;
<template [ngIf]="supportsMultiSelect && !hideCheckbox">
  <material-checkbox *ngIf="!useCheckMarks"
      tabindex="-1"
      [checked]="isSelected"
      [disabled]="disabled">
  </material-checkbox>
  &ngsp;
  <span *ngIf="useCheckMarks" class="check-container">
    <glyph *ngIf="isSelected"
        baseline
        class="check"
        icon="check">
    </glyph>
  </span>
</template>
&ngsp;
<span *ngIf="valueHasLabel" class="label">{{valueLabel}}</span>
&ngsp;
<dynamic-component *ngIf="componentType != null || componentFactory != null"
    class="dynamic-item"
    (onLoad)="onLoadCustomComponent($event)"
    [componentType]="componentType"
    [componentFactory]="componentFactory"
    [value]="value">
</dynamic-component>
<ng-content></ng-content>

{'repo_name': 'dart-lang/angular_components', 'stars': '371', 'repo_language': 'Dart', 'file_name': 'gallery_section.dart.mustache', 'mime_type': 'text/x-c++', 'hash': -3299440934598056097, 'source_dataset': 'data'}


/*
Theme Name: Underscores.me
Layout: Sidebar-Sidebar-Content
*/

.site-content {
	float: right;
	margin: 0 0 0 -40%;
	width: 100%;
}
#content {
	margin: 0 0 0 40%;
}
#main .widget-area {
	float: left;
	overflow: hidden;
	width: 20%;
}
.site-footer {
	clear: both;
	width: 100%;
}

{'repo_name': 'Automattic/underscores.me', 'stars': '195', 'repo_language': 'PHP', 'file_name': 'underscoresme-generator.php', 'mime_type': 'text/x-php', 'hash': -3728013057909891829, 'source_dataset': 'data'}


require 'spec_helper'

describe Queue do
  include QueueTest

  let :thread_num do
    5
  end

  let :loop_num do
    50
  end

  let :now do
    Time.now.to_i
  end

  def thread_main
    thread_id = Thread.current.object_id

    loop_num.times do |i|
      queue.submit("#{thread_id}-#{i}", "type01", {}, :now=>now-10)
      task = queue.poll(:now=>now, :alive_time=>60)
      expect(task).not_to eq(nil)
      task.heartbeat!(:now=>now, :alive_time=>70)
      task.finish!(:now=>now, :retention_time=>80)
    end
  end

  it 'stress' do
    puts "stress test with threads=#{thread_num} * loop_num=#{loop_num} = #{thread_num * loop_num} tasks"

    # initialize queue here
    queue
    now

    start_at = Time.now
    (1..thread_num).map {
      Thread.new(&method(:thread_main))
    }.each {|thread|
      thread.join
    }
    finish_at = Time.now

    elapsed = finish_at - start_at
    task_num = thread_num * loop_num
    puts "#{elapsed} sec."
    puts "#{task_num / elapsed} req/sec."
    puts "#{elapsed / task_num} sec/req."
  end

end

{'repo_name': 'treasure-data/perfectqueue', 'stars': '119', 'repo_language': 'Ruby', 'file_name': 'child_process_monitor.rb', 'mime_type': 'text/x-ruby', 'hash': 8517721080971616866, 'source_dataset': 'data'}


// Project OldRod - A KoiVM devirtualisation utility.
// Copyright (C) 2019 Washi
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.

using AsmResolver.DotNet;
using OldRod.Core.Architecture;

namespace OldRod.Core.Disassembly.Annotations
{
    public class BoxAnnotation : TypeAnnotation
    {
        public BoxAnnotation(ITypeDefOrRef type, object value)
            : base(VMCalls.BOX, type)
        {
            Value = value;
        }

        public object Value
        {
            get;
        }

        public bool IsUnknownValue => Value == null;

        public override string ToString()
        {
            return $"BOX {Type} ({(IsUnknownValue ? "?" : Value)})";
        }

    }
}

{'repo_name': 'Washi1337/OldRod', 'stars': '132', 'repo_language': 'C#', 'file_name': 'index.md', 'mime_type': 'text/plain', 'hash': -3982952592070411579, 'source_dataset': 'data'}


# Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0

"""
Stubs for testing parameter_store.py
"""

get_parameter = {
    'Parameter': {
        'Name': 'string',
        'Type': 'String',
        'Value': 'some_parameter_value',
        'Version': 123,
        'Selector': 'string',
        'SourceResult': 'string',
        'LastModifiedDate': 1,
        'ARN': 'string'
    }
}

get_parameters_by_path = {
    'Parameters': [
        {
            'Name': 'string',
            'Type': 'String',
            'Value': 'string',
            'Version': 123,
            'Selector': 'string',
            'SourceResult': 'string',
            'LastModifiedDate': 1,
            'ARN': 'string'
        },
    ],
    'NextToken': 'string'
}

{'repo_name': 'awslabs/aws-deployment-framework', 'stars': '299', 'repo_language': 'Python', 'file_name': 'template.yml', 'mime_type': 'text/plain', 'hash': -4968084746173990785, 'source_dataset': 'data'}


//
// detail/handler_invoke_helpers.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2016 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//

#ifndef BOOST_ASIO_DETAIL_HANDLER_INVOKE_HELPERS_HPP
#define BOOST_ASIO_DETAIL_HANDLER_INVOKE_HELPERS_HPP

#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)

#include <boost/asio/detail/config.hpp>
#include <boost/asio/detail/addressof.hpp>
#include <boost/asio/handler_invoke_hook.hpp>

#include <boost/asio/detail/push_options.hpp>

// Calls to asio_handler_invoke must be made from a namespace that does not
// contain overloads of this function. The boost_asio_handler_invoke_helpers
// namespace is defined here for that purpose.
namespace boost_asio_handler_invoke_helpers {

template <typename Function, typename Context>
inline void invoke(Function& function, Context& context)
{
#if !defined(BOOST_ASIO_HAS_HANDLER_HOOKS)
  Function tmp(function);
  tmp();
#else
  using boost::asio::asio_handler_invoke;
  asio_handler_invoke(function, boost::asio::detail::addressof(context));
#endif
}

template <typename Function, typename Context>
inline void invoke(const Function& function, Context& context)
{
#if !defined(BOOST_ASIO_HAS_HANDLER_HOOKS)
  Function tmp(function);
  tmp();
#else
  using boost::asio::asio_handler_invoke;
  asio_handler_invoke(function, boost::asio::detail::addressof(context));
#endif
}

} // namespace boost_asio_handler_invoke_helpers

#include <boost/asio/detail/pop_options.hpp>

#endif // BOOST_ASIO_DETAIL_HANDLER_INVOKE_HELPERS_HPP

{'repo_name': 'steniowagner/bon-appetit-app', 'stars': '262', 'repo_language': 'JavaScript', 'file_name': 'settings.json', 'mime_type': 'text/plain', 'hash': 7953314702687068128, 'source_dataset': 'data'}


#region License
/*
 * EndPointListener.cs
 *
 * This code is derived from System.Net.EndPointListener.cs of Mono
 * (http://www.mono-project.com).
 *
 * The MIT License
 *
 * Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
 * Copyright (c) 2012-2014 sta.blockhead
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
#endregion

#region Authors
/*
 * Authors:
 * - Gonzalo Paniagua Javier <gonzalo@novell.com>
 */
#endregion

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Threading;

namespace WebSocketSharp.Net
{
  internal sealed class EndPointListener
  {
    #region Private Static Fields

    private static readonly string _defaultCertFolderPath =
      Environment.GetFolderPath (Environment.SpecialFolder.ApplicationData);

    #endregion

    #region Private Fields

    private List<ListenerPrefix>                       _all; // host = '+'
    private X509Certificate2                           _cert;
    private IPEndPoint                                 _endpoint;
    private Dictionary<ListenerPrefix, HttpListener>   _prefixes;
    private bool                                       _secure;
    private Socket                                     _socket;
    private List<ListenerPrefix>                       _unhandled; // host = '*'
    private Dictionary<HttpConnection, HttpConnection> _unregistered;

    #endregion

    #region Public Constructors

    public EndPointListener (
      IPAddress address, int port, bool secure, string certFolderPath, X509Certificate2 defaultCert)
    {
      if (secure) {
        _secure = secure;
        _cert = getCertificate (port, certFolderPath, defaultCert);
        if (_cert == null)
          throw new ArgumentException ("No server certificate found.");
      }

      _endpoint = new IPEndPoint (address, port);
      _prefixes = new Dictionary<ListenerPrefix, HttpListener> ();
      _unregistered = new Dictionary<HttpConnection, HttpConnection> ();

      _socket = new Socket (address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
      _socket.Bind (_endpoint);
      _socket.Listen (500);

      var args = new SocketAsyncEventArgs ();
      args.UserToken = this;
      args.Completed += onAccept;
      _socket.AcceptAsync (args);
    }

    #endregion

    #region Public Properties

    public X509Certificate2 Certificate {
      get {
        return _cert;
      }
    }

    public bool IsSecure {
      get {
        return _secure;
      }
    }

    #endregion

    #region Private Methods

    private static void addSpecial (List<ListenerPrefix> prefixes, ListenerPrefix prefix)
    {
      if (prefixes == null)
        return;

      var path = prefix.Path;
      foreach (var pref in prefixes)
        if (pref.Path == path) // TODO: Code?
          throw new HttpListenerException (400, "Prefix already in use.");

      prefixes.Add (prefix);
    }

    private void checkIfRemove ()
    {
      if (_prefixes.Count > 0)
        return;

      if (_unhandled != null && _unhandled.Count > 0)
        return;

      if (_all != null && _all.Count > 0)
        return;

      EndPointManager.RemoveEndPoint (this, _endpoint);
    }

    private static RSACryptoServiceProvider createRSAFromFile (string filename)
    {
      byte [] pvk = null;
      using (var fs = File.Open (filename, FileMode.Open, FileAccess.Read, FileShare.Read)) {
        pvk = new byte [fs.Length];
        fs.Read (pvk, 0, pvk.Length);
      }

      var rsa = new RSACryptoServiceProvider ();
      rsa.ImportCspBlob (pvk);

      return rsa;
    }

    private static X509Certificate2 getCertificate (
      int port, string certFolderPath, X509Certificate2 defaultCert)
    {
      if (certFolderPath == null || certFolderPath.Length == 0)
        certFolderPath = _defaultCertFolderPath;

      try {
        var cer = Path.Combine (certFolderPath, String.Format ("{0}.cer", port));
        var key = Path.Combine (certFolderPath, String.Format ("{0}.key", port));
        if (File.Exists (cer) && File.Exists (key)) {
          var cert = new X509Certificate2 (cer);
          cert.PrivateKey = createRSAFromFile (key);

          return cert;
        }
      }
      catch {
      }

      return defaultCert;
    }

    private static HttpListener matchFromList (
      string host, string path, List<ListenerPrefix> list, out ListenerPrefix prefix)
    {
      prefix = null;
      if (list == null)
        return null;

      HttpListener bestMatch = null;
      var bestLength = -1;
      foreach (var pref in list) {
        var ppath = pref.Path;
        if (ppath.Length < bestLength)
          continue;

        if (path.StartsWith (ppath)) {
          bestLength = ppath.Length;
          bestMatch = pref.Listener;
          prefix = pref;
        }
      }

      return bestMatch;
    }

    private static void onAccept (object sender, EventArgs e)
    {
      var args = (SocketAsyncEventArgs) e;
      var listener = (EndPointListener) args.UserToken;
      Socket accepted = null;
      if (args.SocketError == SocketError.Success) {
        accepted = args.AcceptSocket;
        args.AcceptSocket = null;
      }

      try {
        listener._socket.AcceptAsync (args);
      }
      catch {
        if (accepted != null)
          accepted.Close ();

        return;
      }

      if (accepted == null)
        return;

      HttpConnection conn = null;
      try {
        conn = new HttpConnection (accepted, listener);
        lock (((ICollection) listener._unregistered).SyncRoot)
          listener._unregistered [conn] = conn;

        conn.BeginReadRequest ();
      }
      catch {
        if (conn != null) {
          conn.Close (true);
          return;
        }

        accepted.Close ();
      }
    }

    private static bool removeSpecial (List<ListenerPrefix> prefixes, ListenerPrefix prefix)
    {
      if (prefixes == null)
        return false;

      var path = prefix.Path;
      var count = prefixes.Count;
      for (int i = 0; i < count; i++) {
        if (prefixes [i].Path == path) {
          prefixes.RemoveAt (i);
          return true;
        }
      }

      return false;
    }

    private HttpListener searchListener (Uri uri, out ListenerPrefix prefix)
    {
      prefix = null;
      if (uri == null)
        return null;

      var host = uri.Host;
      var port = uri.Port;
      var path = HttpUtility.UrlDecode (uri.AbsolutePath);
      var pathSlash = path [path.Length - 1] == '/' ? path : path + "/";

      HttpListener bestMatch = null;
      var bestLength = -1;
      if (host != null && host.Length > 0) {
        foreach (var pref in _prefixes.Keys) {
          var ppath = pref.Path;
          if (ppath.Length < bestLength)
            continue;

          if (pref.Host != host || pref.Port != port)
            continue;

          if (path.StartsWith (ppath) || pathSlash.StartsWith (ppath)) {
            bestLength = ppath.Length;
            bestMatch = _prefixes [pref];
            prefix = pref;
          }
        }

        if (bestLength != -1)
          return bestMatch;
      }

      var list = _unhandled;
      bestMatch = matchFromList (host, path, list, out prefix);
      if (path != pathSlash && bestMatch == null)
        bestMatch = matchFromList (host, pathSlash, list, out prefix);

      if (bestMatch != null)
        return bestMatch;

      list = _all;
      bestMatch = matchFromList (host, path, list, out prefix);
      if (path != pathSlash && bestMatch == null)
        bestMatch = matchFromList (host, pathSlash, list, out prefix);

      if (bestMatch != null)
        return bestMatch;

      return null;
    }

    #endregion

    #region Internal Methods

    internal static bool CertificateExists (int port, string certFolderPath)
    {
      if (certFolderPath == null || certFolderPath.Length == 0)
        certFolderPath = _defaultCertFolderPath;

      var cer = Path.Combine (certFolderPath, String.Format ("{0}.cer", port));
      var key = Path.Combine (certFolderPath, String.Format ("{0}.key", port));

      return File.Exists (cer) && File.Exists (key);
    }

    internal void RemoveConnection (HttpConnection connection)
    {
      lock (((ICollection) _unregistered).SyncRoot)
        _unregistered.Remove (connection);
    }

    #endregion

    #region Public Methods

    public void AddPrefix (ListenerPrefix prefix, HttpListener listener)
    {
      List<ListenerPrefix> current, future;
      if (prefix.Host == "*") {
        do {
          current = _unhandled;
          future = current != null
                   ? new List<ListenerPrefix> (current)
                   : new List<ListenerPrefix> ();

          prefix.Listener = listener;
          addSpecial (future, prefix);
        }
        while (Interlocked.CompareExchange (ref _unhandled, future, current) != current);

        return;
      }

      if (prefix.Host == "+") {
        do {
          current = _all;
          future = current != null
                   ? new List<ListenerPrefix> (current)
                   : new List<ListenerPrefix> ();

          prefix.Listener = listener;
          addSpecial (future, prefix);
        }
        while (Interlocked.CompareExchange (ref _all, future, current) != current);

        return;
      }

      Dictionary<ListenerPrefix, HttpListener> prefs, prefs2;
      do {
        prefs = _prefixes;
        if (prefs.ContainsKey (prefix)) {
          var other = prefs [prefix];
          if (other != listener) // TODO: Code?
            throw new HttpListenerException (400, "There's another listener for " + prefix);

          return;
        }

        prefs2 = new Dictionary<ListenerPrefix, HttpListener> (prefs);
        prefs2 [prefix] = listener;
      }
      while (Interlocked.CompareExchange (ref _prefixes, prefs2, prefs) != prefs);
    }

    public bool BindContext (HttpListenerContext context)
    {
      ListenerPrefix prefix;
      var listener = searchListener (context.Request.Url, out prefix);
      if (listener == null)
        return false;

      context.Listener = listener;
      context.Connection.Prefix = prefix;

      return true;
    }

    public void Close ()
    {
      _socket.Close ();

      lock (((ICollection) _unregistered).SyncRoot) {
        var conns = new List<HttpConnection> (_unregistered.Keys);
        _unregistered.Clear ();
        foreach (var conn in conns)
          conn.Close (true);

        conns.Clear ();
      }
    }

    public void RemovePrefix (ListenerPrefix prefix, HttpListener listener)
    {
      List<ListenerPrefix> current, future;
      if (prefix.Host == "*") {
        do {
          current = _unhandled;
          future = current != null
                   ? new List<ListenerPrefix> (current)
                   : new List<ListenerPrefix> ();

          if (!removeSpecial (future, prefix))
            break; // Prefix not found.
        }
        while (Interlocked.CompareExchange (ref _unhandled, future, current) != current);

        checkIfRemove ();
        return;
      }

      if (prefix.Host == "+") {
        do {
          current = _all;
          future = current != null
                   ? new List<ListenerPrefix> (current)
                   : new List<ListenerPrefix> ();

          if (!removeSpecial (future, prefix))
            break; // Prefix not found.
        }
        while (Interlocked.CompareExchange (ref _all, future, current) != current);

        checkIfRemove ();
        return;
      }

      Dictionary<ListenerPrefix, HttpListener> prefs, prefs2;
      do {
        prefs = _prefixes;
        if (!prefs.ContainsKey (prefix))
          break;

        prefs2 = new Dictionary<ListenerPrefix, HttpListener> (prefs);
        prefs2.Remove (prefix);
      }
      while (Interlocked.CompareExchange (ref _prefixes, prefs2, prefs) != prefs);

      checkIfRemove ();
    }

    public void UnbindContext (HttpListenerContext context)
    {
      if (context == null || context.Listener == null)
        return;

      context.Listener.UnregisterContext (context);
    }

    #endregion
  }
}

{'repo_name': 'fpanettieri/unity-socket.io-DEPRECATED', 'stars': '222', 'repo_language': 'C#', 'file_name': 'SocketIOTest.unity.meta', 'mime_type': 'text/plain', 'hash': -6890318683764862494, 'source_dataset': 'data'}


// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// +build darwin freebsd linux

package ipv4

import (
	"net"
	"unsafe"

	"golang.org/x/net/internal/socket"
)

func (so *sockOpt) getIPMreqn(c *socket.Conn) (*net.Interface, error) {
	b := make([]byte, so.Len)
	if _, err := so.Get(c, b); err != nil {
		return nil, err
	}
	mreqn := (*ipMreqn)(unsafe.Pointer(&b[0]))
	if mreqn.Ifindex == 0 {
		return nil, nil
	}
	ifi, err := net.InterfaceByIndex(int(mreqn.Ifindex))
	if err != nil {
		return nil, err
	}
	return ifi, nil
}

func (so *sockOpt) setIPMreqn(c *socket.Conn, ifi *net.Interface, grp net.IP) error {
	var mreqn ipMreqn
	if ifi != nil {
		mreqn.Ifindex = int32(ifi.Index)
	}
	if grp != nil {
		mreqn.Multiaddr = [4]byte{grp[0], grp[1], grp[2], grp[3]}
	}
	b := (*[sizeofIPMreqn]byte)(unsafe.Pointer(&mreqn))[:sizeofIPMreqn]
	return so.Set(c, b)
}

{'repo_name': 'prometheus/prometheus', 'stars': '31950', 'repo_language': 'Go', 'file_name': 'default_cert.go', 'mime_type': 'text/plain', 'hash': -5190726775129989647, 'source_dataset': 'data'}


/*
 * Copyright (c) 2019, Arm Limited. All rights reserved.
 *
 * SPDX-License-Identifier: BSD-3-Clause
 *
 */

#include "psa/internal_trusted_storage.h"
#include "tfm_api.h"

#include "psa/client.h"
#include "psa_manifest/sid.h"

#define IOVEC_LEN(x) (sizeof(x)/sizeof(x[0]))

psa_status_t psa_its_set(psa_storage_uid_t uid,
                         size_t data_length,
                         const void *p_data,
                         psa_storage_create_flags_t create_flags)
{
    psa_status_t status;
    psa_handle_t handle;

    psa_invec in_vec[] = {
        { .base = &uid, .len = sizeof(uid) },
        { .base = p_data, .len = data_length },
        { .base = &create_flags, .len = sizeof(create_flags) }
    };

    handle = psa_connect(TFM_ITS_SET_SID, TFM_ITS_SET_VERSION);
    if (!PSA_HANDLE_IS_VALID(handle)) {
        return PSA_ERROR_GENERIC_ERROR;
    }

    status = psa_call(handle, PSA_IPC_CALL, in_vec, IOVEC_LEN(in_vec), NULL, 0);

    psa_close(handle);

    if (status == (psa_status_t)TFM_ERROR_INVALID_PARAMETER) {
        return PSA_ERROR_INVALID_ARGUMENT;
    }

    return status;
}

psa_status_t psa_its_get(psa_storage_uid_t uid,
                         size_t data_offset,
                         size_t data_size,
                         void *p_data,
                         size_t *p_data_length)
{
    psa_status_t status;
    psa_handle_t handle;

    psa_invec in_vec[] = {
        { .base = &uid, .len = sizeof(uid) },
        { .base = &data_offset, .len = sizeof(data_offset) }
    };

    psa_outvec out_vec[] = {
        { .base = p_data, .len = data_size }
    };

    if (p_data_length == NULL) {
        return PSA_ERROR_INVALID_ARGUMENT;
    }

    handle = psa_connect(TFM_ITS_GET_SID, TFM_ITS_GET_VERSION);
    if (!PSA_HANDLE_IS_VALID(handle)) {
        return PSA_ERROR_GENERIC_ERROR;
    }

    status = psa_call(handle, PSA_IPC_CALL, in_vec, IOVEC_LEN(in_vec), out_vec,
                      IOVEC_LEN(out_vec));

    psa_close(handle);

    if (status == (psa_status_t)TFM_ERROR_INVALID_PARAMETER) {
        return PSA_ERROR_INVALID_ARGUMENT;
    }

    *p_data_length = out_vec[0].len;

    return status;
}

psa_status_t psa_its_get_info(psa_storage_uid_t uid,
                              struct psa_storage_info_t *p_info)
{
    psa_status_t status;
    psa_handle_t handle;

    psa_invec in_vec[] = {
        { .base = &uid, .len = sizeof(uid) }
    };

    psa_outvec out_vec[] = {
        { .base = p_info, .len = sizeof(*p_info) }
    };

    handle = psa_connect(TFM_ITS_GET_INFO_SID, TFM_ITS_GET_INFO_VERSION);
    if (!PSA_HANDLE_IS_VALID(handle)) {
        return PSA_ERROR_GENERIC_ERROR;
    }

    status = psa_call(handle, PSA_IPC_CALL, in_vec, IOVEC_LEN(in_vec), out_vec,
                      IOVEC_LEN(out_vec));

    psa_close(handle);

    if (status == (psa_status_t)TFM_ERROR_INVALID_PARAMETER) {
        return PSA_ERROR_INVALID_ARGUMENT;
    }

    return status;
}

psa_status_t psa_its_remove(psa_storage_uid_t uid)
{
    psa_status_t status;
    psa_handle_t handle;

    psa_invec in_vec[] = {
        { .base = &uid, .len = sizeof(uid) }
    };

    handle = psa_connect(TFM_ITS_REMOVE_SID, TFM_ITS_REMOVE_VERSION);
    if (!PSA_HANDLE_IS_VALID(handle)) {
        return PSA_ERROR_GENERIC_ERROR;
    }

    status = psa_call(handle, PSA_IPC_CALL, in_vec, IOVEC_LEN(in_vec), NULL, 0);

    psa_close(handle);

    return status;
}

{'repo_name': 'ARMmbed/mbed-os', 'stars': '3304', 'repo_language': 'C', 'file_name': 'system_stm32f7xx.c', 'mime_type': 'text/x-c', 'hash': 1080142837593010876, 'source_dataset': 'data'}


//=======================================================================
// Copyright 2001 Jeremy G. Siek, Andrew Lumsdaine, Lie-Quan Lee,
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#include <boost/config.hpp>
#include <string>
#include <iostream>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/property_iter_range.hpp>

int
main()
{
  using namespace boost;
  typedef adjacency_list < listS, vecS, directedS,
    property < vertex_name_t, std::string > >graph_t;
  graph_t g(3);

  const char *vertex_names[] = { "Kubrick", "Clark", "Hal" };
  int i = 0;
  graph_property_iter_range < graph_t, vertex_name_t >::iterator v, v_end;
  for (boost::tie(v, v_end) = get_property_iter_range(g, vertex_name);
       v != v_end; ++v, ++i)
    *v = vertex_names[i];

  boost::tie(v, v_end) = get_property_iter_range(g, vertex_name);
  std::copy(v, v_end, std::ostream_iterator < std::string > (std::cout, " "));
  std::cout << std::endl;
  return 0;
}

{'repo_name': 'vslavik/poedit', 'stars': '1009', 'repo_language': 'C++', 'file_name': 'eat.qbk', 'mime_type': 'text/plain', 'hash': 5853662850112147733, 'source_dataset': 'data'}


===========
Research
===========

Research class allows you to easily:
* experiment with models parameters combinations
* run multiple pipeline configurations (e.g. simultanious train and test workflow)
* add functions, customizing research process
* save and load results of experiments in a unified form

Basic usage
-----------
Let's compare `VGG7` and `VGG16` performance on `MNIST` dataset with
different layouts of convolutional blocks. For each combination of
layout and model class, we train model for 1000 iterations, repeat
that process 10 times and save accuracy and loss on train and accuracy on test.

Firstly, import classes from `batchflow` to create pipelines:

.. code-block:: python

    from batchflow import B, C, D, V, F, Config
    from batchflow.opensets import MNIST
    from batchflow.models.tf import VGG7, VGG16

    from batchflow.research import Research
    from batchflow.research import ResearchPipeline as RP
    from batchflow.research import ResearchIteration as RI

Define model config. All parameters that we want to vary we define
as ``C('parameter_name')``:

.. code-block:: python

model_config={
    'inputs/images/shape': B('image_shape'),
    'inputs/labels/classes': D('num_classes'),
    'inputs/labels/name': 'targets',
    'initial_block/inputs': 'images',
    'body/block/layout': C('layout')
}

Strictly saying, the whole ``model_config`` with different
``'body/block/layout'`` is a pipeline parameter but due
to a substitution rule of named expressions you can define
named expression inside of `dict` or `Config` that is used as action parameter
(See :doc:`Named expressions <../intro/named_expr>`).

Define a dataset and train a pipeline:

.. code-block:: python

    mnist = MNIST()

    train_ppl = (mnist.train.p
                 .init_variable('loss', default=[])
                 .init_model('dynamic', C('model'), 'conv', config=model_config)
                 .to_array()
                 .train_model('conv', images=B('images'), labels=B('labels'),
                              fetches='loss', save_to=V('loss', mode='w'))
                 .run_later(64, shuffle=True, n_epochs=None)
                )

Action parameters that we want to vary we define as ``C('parameter_name')``. Note
that to specify parameters of batch generating ``run_later`` action must be defined.

Create an instance of `Research` class and add train pipeline:

.. code-block:: python

    research = Research()
    research.add_pipeline(train_ppl, variables='loss', name='train')

Parameter ``name`` defines pipeline name inside ``research``. At each iteration
that pipeline will be executed with ``.next_batch()`` and all ``variables`` from the pipeline
will be saved so that variables must be added with ``mode='w'``.

All parameter combinations we define through the dict where a key is
a parameter name and value is a list of possible parameter values.
Create a grid of parameters and add to ``research``:

.. code-block:: python

    domain = Domain({'model_class': [VGG7, VGG16], 'layout': ['cna', 'can']})
    research.add_domain(domain, n_reps=10)

To create more complex domains that can be updated in the process of research
you can use ``Option`` class and ``update_method`` of ``Research``.

Each experiment with the same config will be repeated 10 times because of `n_reps` parameter.

You can get all variants of config by ``list(domain.iterator)``:

::

    [ConfigAlias({'layout': 'cna', 'repetition': '0', 'model': 'VGG7'}),
     ConfigAlias({'layout': 'cna', 'repetition': '0', 'model': 'VGG16'}),
     ConfigAlias({'layout': 'can', 'repetition': '0', 'model': 'VGG7'}),
     ConfigAlias({'layout': 'can', 'repetition': '0', 'model': 'VGG16'})]

Each element is a ConfigAlias. It's a Config dict of parameter values
and dict with aliases for parameter values.

In order to control test accuracy we create test pipeline and add it
to ``research``:

.. code-block:: python

    test_ppl = (mnist.test.p
                .init_variable('predictions')
                .init_variable('metrics')
                .import_model('conv', C('import_from'))
                .to_array()
                .predict_model('conv',
                               images=B('images'), labels=B('labels'),
                               fetches='predictions', save_to=V('predictions'))
                .gather_metrics('class', targets=B('labels'), predictions=V('predictions'),
                               fmt='logits', axis=-1, save_to=V('metrics'))
                .run_later(64, shuffle=True, n_epochs=1))

    research.add_pipeline(test_ppl, variables='metrics', name='test', run=True,
                          execute=100, import_model=RP('train'))

That pipeline will be executed with ``.run()`` each 100 iterations because
of parameters ``run=True``  and ``execute=100``. Pipeline variable ``metrics``
will be saved after each execution. In order to add a mean value of accuracy
on the whole test dataset, you can add ``get_metrics`` method into research:

.. code-block:: python

    research.get_metrics(pipeline='test', metrics_var='metrics', metrics_name='accuracy',
                         returns='accuracy', execute=100)

You also can add into pipeline your custom functions and specify ``args`` and ``kwargs`` through
`ResearchNamedExpression`-child classes.

Note that we use ``C('import_model')`` in ``import_model`` action
and add test pipeline with parameter ``import_model=RP('train')``.
All ``kwargs`` in ``add_pipeline`` will be substituted to pipeline
configs so we can use named expression ``RP('train')`` that will be
evaluated and transformed to actual pipeline object.

Method ``run`` starts computations:

.. code-block:: python

    research.run(n_iters=1000, name='my_research', bar=True)

All results will be saved as
``{research_name}/results/{config_alias}/{unitname}_{iteration}``
as pickled dict (by dill) where keys are variable names and values are lists
of corresponding values.

There is method ``load_results`` to create ``pandas.DataFrame`` with results
of the research.

Parallel runnings
-----------------

If you have a lot of GPU devices (say, 4) you can do research faster,
just define in ``run`` method ``workers=4``, ``devices = [0, 1, 2, 3]``
as a list of available devices and add ``device=C('device')`` into model
config. In that case you can run 4 jobs in parallel!

.. code-block:: python

    research.run(n_iters=1000, workers=4, devices=[0,1,2,3], name='my_research', bar=True)

In that case, two workers will execute tasks in different processes
on different GPU.

Another way of parallel running
--------------------------------

If you have heavy loading you can do it just one time for few pipelines
with models. In that case devide pipelines into root and branch:

.. code-block:: python

    mnist = MNIST()
    train_root = mnist.train.p.run_later(64, shuffle=True, n_epochs=None)

    train_ppl = (Pipeline()
                 .init_variable('loss', default=[])
                 .init_model('dynamic', C('model'), 'conv', config=model_config)
                 .to_array()
                 .train_model('conv', images=B('images'), labels=B('labels'),
                              fetches='loss', save_to=V('loss', mode='w'))
                 .run_later(64, shuffle=True, n_epochs=None)
                )

Then define research in the following way:

.. code-block:: python

    research = (Research()
        .add_pipeline(root=train_root, branch=train_branch, variables='loss', name='train')
        .add_pipeline(test_ppl, variables='metrics', name='test', run=True, execute=100, import_model=RP('train'))
        .add_domain(domain, n_reps=2)
        .get_metrics(pipeline='test', metrics_var='metrics', metrics_name='accuracy',
                     returns='accuracy', execute=100)
    )

And now you can define the number of branches in each worker:

.. code-block:: python

    research.run(n_iters=1000, workers=2, branches=2, devices=[0,1,2,3], name='my_research', bar=True)

Dumping of results and logging
--------------------------------

By default if unit has varaibles or returns then results
will be dumped at last iteration. But there is unit parameter dump
that allows to save result not only in the end. It defines as execute
parameter. For example, dump train results each 200 iterations.
Besides, each research has log file. In order to add information about
unit execution and dumping into log, define ``logging=True``.

.. code-block:: python

    research = (Research()
        .add_pipeline(root=train_root, branch=train_template,
                      variables='loss', name='train', dump=200)
        .add_pipeline(test_ppl,
                      variables='accuracy', name='test', run=True, execute=100, import_from=RP('train'), logging=True)
        .add_domain(domain, n_reps=2)
        .get_metrics(pipeline='test', metrics_var='metrics', metrics_name='accuracy',
                     returns='accuracy', execute=100)
    )

    research.run(n_iters=1000, workers=2, branches=2, devices=[0,1,2,3], name='my_research', bar=True)

First worker will execute two branches on GPU 0 and 1
and the second on the 2 and 3.

Functions on root
--------------------------------

All functions and pipelines if branches > 0 executed in parallel
threads so sometime it can be a problem. In order to allow run
function in main thread there exists parameter on_root. Function
that will be added with on_root=True will get iteration, experiments
and kwargs. experiments is a list of experiments that was defined above
(OrderedDict of ExecutableUnits). Simple example of usage:

.. code-block:: python

    def on_root(iteration):
        print("On root", iteration)

    research = (Research()
        .add_function(on_root, on_root=True, execute=10, iteration=RI(), logging=True)
        .add_pipeline(root=train_root, branch=train_template,
                      variables='loss', name='train', dump=200)
        .add_pipeline(test_ppl,
                      variables='accuracy', name='test', run=True, execute=100, import_from=RP('train'), logging=True)
        .add_domain(domain)
        .get_metrics(pipeline='test', metrics_var='metrics', metrics_name='accuracy',
                     returns='accuracy', execute=100)
    )

That function will be executed just one time on 10 iteration
and will be executed one time for all branches in task.

.. code-block:: python

    research.run(n_iters=100, workers=2, branches=2, devices=[0,1,2,3], name='my_research', bar=True)

Logfile:

::

    INFO     [2018-05-15 14:18:32,496] Distributor [id:5176] is preparing workers
    INFO     [2018-05-15 14:18:32,497] Create queue of jobs
    INFO     [2018-05-15 14:18:32,511] Run 2 workers
    INFO     [2018-05-15 14:18:32,608] Start Worker 0 [id:26021] (devices: [0, 1])
    INFO     [2018-05-15 14:18:32,709] Start Worker 1 [id:26022] (devices: [2, 3])
    INFO     [2018-05-15 14:18:41,722] Worker 0 is creating process for Job 0
    INFO     [2018-05-15 14:18:49,254] Worker 1 is creating process for Job 1
    INFO     [2018-05-15 14:18:53,101] Job 0 was started in subprocess [id:26082] by Worker 0
    INFO     [2018-05-15 14:18:53,118] Job 0 has the following configs:
    {'layout': 'cna', 'model': 'VGG7'}
    {'layout': 'cna', 'model': 'VGG16'}
    INFO     [2018-05-15 14:18:59,267] Job 1 was started in subprocess [id:26130] by Worker 1
    INFO     [2018-05-15 14:18:59,281] Job 1 has the following configs:
    {'layout': 'can', 'model': 'VGG7'}
    {'layout': 'can', 'model': 'VGG16'}
    INFO     [2018-05-15 14:19:02,415] J 0 [26082] I 11: on root 'unit_0' [0]
    INFO     [2018-05-15 14:19:02,415] J 0 [26082] I 11: on root 'unit_0' [1]
    INFO     [2018-05-15 14:19:07,803] J 0 [26082] I 100: dump 'unit_0' [0]
    INFO     [2018-05-15 14:19:07,803] J 0 [26082] I 100: dump 'unit_0' [1]
    INFO     [2018-05-15 14:19:08,761] J 1 [26130] I 11: on root 'unit_0' [0]
    INFO     [2018-05-15 14:19:08,761] J 1 [26130] I 11: on root 'unit_0' [1]
    INFO     [2018-05-15 14:19:12,050] J 0 [26082] I 100: execute 'test' [0]
    INFO     [2018-05-15 14:19:12,051] J 0 [26082] I 100: execute 'test' [1]
    INFO     [2018-05-15 14:19:12,051] J 0 [26082] I 100: dump 'test' [0]
    INFO     [2018-05-15 14:19:12,051] J 0 [26082] I 100: dump 'test' [1]
    INFO     [2018-05-15 14:19:12,056] Job 0 [26082] was finished by Worker 0
    INFO     [2018-05-15 14:19:14,149] J 1 [26130] I 100: dump 'unit_0' [0]
    INFO     [2018-05-15 14:19:14,149] J 1 [26130] I 100: dump 'unit_0' [1]
    INFO     [2018-05-15 14:19:18,819] J 1 [26130] I 100: execute 'test' [0]
    INFO     [2018-05-15 14:19:18,819] J 1 [26130] I 100: execute 'test' [1]
    INFO     [2018-05-15 14:19:18,820] J 1 [26130] I 100: dump 'test' [0]
    INFO     [2018-05-15 14:19:18,820] J 1 [26130] I 100: dump 'test' [1]
    INFO     [2018-05-15 14:19:18,825] Job 1 [26130] was finished by Worker 1
    INFO     [2018-05-15 14:19:18,837] All workers have finished the work

API
---

See :doc:`Research API <../api/batchflow.research>`.

{'repo_name': 'analysiscenter/batchflow', 'stars': '144', 'repo_language': 'Python', 'file_name': 'batchflow.models.tf.models.rst', 'mime_type': 'text/plain', 'hash': 5548453105772474533, 'source_dataset': 'data'}


# SPDX-License-Identifier: GPL-2.0
#
# Makefile for ALSA
# Copyright (c) 2001 by Jaroslav Kysela <perex@perex.cz>
#

snd-emu10k1-objs := emu10k1.o emu10k1_main.o \
		    irq.o memory.o voice.o emumpu401.o emupcm.o io.o \
		    emumixer.o emufx.o timer.o p16v.o
snd-emu10k1-$(CONFIG_SND_PROC_FS) += emuproc.o
snd-emu10k1-synth-objs := emu10k1_synth.o emu10k1_callback.o emu10k1_patch.o
snd-emu10k1x-objs := emu10k1x.o

# Toplevel Module Dependency
obj-$(CONFIG_SND_EMU10K1) += snd-emu10k1.o
obj-$(CONFIG_SND_EMU10K1_SEQ) += snd-emu10k1-synth.o
obj-$(CONFIG_SND_EMU10K1X) += snd-emu10k1x.o

{'repo_name': 'google/kmsan', 'stars': '238', 'repo_language': 'C', 'file_name': 'pinctrl-uniphier-pro5.c', 'mime_type': 'text/x-c', 'hash': 8304487450128729381, 'source_dataset': 'data'}


FUNCTION_BLOCK CMD_MONITOR
 VAR_INPUT AUTO_CMD : BOOL ; (* Automated command *)
          AUTO_MODE : BOOL ; (* AUTO_CMD enable *)
            MAN_CMD : BOOL ; (* Manual Command *)
        MAN_CMD_CHK : BOOL ; (* Negated MAN_CMD to debounce *)
          T_CMD_MAX : TIME ; (* Max time from CMD to FDBK *)
               FDBK : BOOL ; (* Confirmation of CMD completion
                                by operative unit *)
                ACK : BOOL ; (* Acknowledge/cancel ALRM *)
 END_VAR
 VAR_OUTPUT CMD : BOOL ;   (* Command to operative unit *)
           ALRM : BOOL ;   (* T_CMD_MAX expired without FDBK *)
 END_VAR
 VAR CMD_TMR : TON ;    (* CMD-to-FDBK timer *)
     ALRM_FF : SR ;     (* Note over-riding S input: *)
 END_VAR                (* Command must be cancelled before
                              "ACK" can cancel alarm *)
 (* Function Block Body *)
LD	T_CMD_MAX
ST	CMD_TMR.PT	(* Store an input to the TON FB *)
LD	AUTO_CMD
AND	AUTO_MODE
OR(	MAN_CMD
ANDN	AUTO_MODE
ANDN	MAN_CMD_CHK
)
ST	CMD
IN	CMD_TMR	(* Invoke the TON FB *)
LD	CMD_TMR.Q
ANDN	FDBK
ST	ALRM_FF.S1	(* Store an input to the SR FB *)
LD	ACK
R	ALRM_FF	(* Invoke the SR FB *)
LD	ALRM_FF.Q1
ST    	ALRM

END_FUNCTION_BLOCK

{'repo_name': 'thiagoralves/OpenPLC_v3', 'stars': '204', 'repo_language': 'C++', 'file_name': 'readme.md', 'mime_type': 'text/plain', 'hash': 3073022428570487256, 'source_dataset': 'data'}


/*
 * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

package java.awt.event;

import java.util.EventListener;

/**
 * The listener interface for receiving component events.
 * The class that is interested in processing a component event
 * either implements this interface (and all the methods it
 * contains) or extends the abstract {@code ComponentAdapter} class
 * (overriding only the methods of interest).
 * The listener object created from that class is then registered with a
 * component using the component's {@code addComponentListener}
 * method. When the component's size, location, or visibility
 * changes, the relevant method in the listener object is invoked,
 * and the {@code ComponentEvent} is passed to it.
 *

 * Component events are provided for notification purposes ONLY;
 * The AWT will automatically handle component moves and resizes
 * internally so that GUI layout works properly regardless of
 * whether a program registers a {@code ComponentListener} or not.
 *
 * @see ComponentAdapter
 * @see ComponentEvent
 * @see Tutorial: Writing a Component Listener
 *
 * @author Carl Quinn
 * @since 1.1
 */
public interface ComponentListener extends EventListener {
    /**
     * Invoked when the component's size changes.
     * @param e the event to be processed
     */
    public void componentResized(ComponentEvent e);

    /**
     * Invoked when the component's position changes.
     * @param e the event to be processed
     */
    public void componentMoved(ComponentEvent e);

    /**
     * Invoked when the component has been made visible.
     * @param e the event to be processed
     */
    public void componentShown(ComponentEvent e);

    /**
     * Invoked when the component has been made invisible.
     * @param e the event to be processed
     */
    public void componentHidden(ComponentEvent e);
}

{'repo_name': 'YunaiV/openjdk', 'stars': '110', 'repo_language': 'Java', 'file_name': 'AccessibleIcon.java', 'mime_type': 'text/plain', 'hash': 112237902189598526, 'source_dataset': 'data'}


# jKey Beta 1.1

## Key shortcuts made simple

Visit [http://oscargodson.github.com/jKey/](http://oscargodson.github.com/jKey/) for a live demo

### Examples

#### Example 1 - Basic Usage

Below is the most basic usage. Press the a key to give you an alert. Code below:

    $(document).jkey('a',function(){
    	jkey.log('You pressed the a key.');
    });

##### Example 1A - Selecting An Element

jKey works with jQuery, so you can select any applicable element to set a key command to. Basically, any element that can be focused on such as an input or textarea can have a key command applied to it. Example:

    $('input').jkey('i',function(){
    	jkey.log('You pressed the i key inside of an input.');
    });

##### Example 1B - Comboing Anything!

Unlike OS key shortcuts, jKey allows you to combo just about any key supported by jKey. For example:

    $(document).jkey('y+u',function(){
    	jkey.log('You pressed y and u!');
    });

Please see the key support section below to see what's supported by jKey.

#### Example 2 - Key Combos

    $(document).jkey('alt+d',function(){
    	jkey.log('Congrats, you did a key combo: alt+d');
    });

##### Example 2A - Chaining Key Combos

With jKey you can intuitively connect more than just two keys for a combo. For example:

    $(document).jkey('alt+shift+s',function(){
    	jkey.log('Congrats, you did a key combo: alt+shift+s');
    });

#### Example 3 - Multiple Selections

You can also do multiple selections. You can select multiple keys just as you'd select multiple elements in CSS or jQuery. Useful for trying to catch user intent, e.g. doing w and up, so a user can move a character in a game forward with either key like many computer games.

    $(document).jkey('w, up',function(){
    	jkey.log('You pressed either w, or up!');
    });

#### Example 4 - Grabbing the Keys Pressed in the Callback

Sometimes when working with key shortcuts you want to have similar, but different, events fire when certain keys are pressed. For example, you want to have a sliding animation happen when the user presses up or down. The funcationality is basically the same, speed, animation, tween, AJAX event maybe, etc. However, you're a good developer and you want to keep things [DRY]( http://en.wikipedia.org/wiki/Don't_repeat_yourself). Thanks to jKey this is simple:

    $(document).jkey('left, right',function(key){
    	var direction;
    	if(key == 'left'){
    		direction = 'left';
    	}
    	else{
    		direction = 'right';
    	}
    	jkey.log(direction);
    });

####Example 5 - Allowing Bubbling of Events
There might be times when you don't want to prevent keys from bubbling such as the up or down keys. By default, jKey will prevent bubbling so that you don't manually have to as *most* of the time when using jKey you don't want it to bubble and make the page go haywire. However, when you do want it to it's just a simple boolean value you set like so:

	$('input').jkey('h',true,function(key){
	    jkey.log('Allowed to bubble h!');
    });

#### Key Support

*   a-z
*   0-9
*   f1-f12
*   left, down, up, right
*   esc/escape, insert, delete, home, end, pgup/pageup, pgdn/pagedown, fn/function(3)
*   ctrl/control, alt, shift, backspace/osxdelete(1), enter/return(2), super/windows, capslk/capslock, tab, space/spacebar
*   `, ~, -, _, =, +, [, {, ], }, \, |, ;, :, ', ", ,, <, ., &gt, /, ?

If we're missing something, let us know in the bug reporter on our [Github page](https://github.com/OscarGodson/jKey).

(1) - This is the Mac version of the backspace button. Calling either should work across OSs. Due to conflicts with normal western keyboards, we went with "osxdelete". We suggest just using the backspace.

(2) - This is the Mac version of the enter key. Calling either should work across OSs.

(3) - This will NOT work in Mac OS X. It does not send a key event to the browser. Silly Apple.

#### Important Notes!

##### IE Doesn't Like `$(window)`
This isn't jKey's fault. IE doesn't allow you to attach key events to the window. jKey will try to fix it for you if you do it by accident though. If you want to attach a key event to the document/window use $(document) instead.

##### Don't nest your key commands (for now)

What we mean by this is, as of now, jKey can handle key commands like: alt + a and alt + shift + a in the same document, but when you go to do the 2nd one that includes shift, it'll run the 1st event as well. This is *most likely* not what you want.

##### Special characters that have the share the same physical key, get the same key code

For example, you can call : OR ;, [ OR {, etc. They are the same key to jKey.

##### Function key will NOT work on Mac OS X

There is nothing jKey can do about this. OS X doesn't send a key code back to the browser. Sorry!

{'repo_name': 'OscarGodson/jKey', 'stars': '182', 'repo_language': 'JavaScript', 'file_name': 'index.html', 'mime_type': 'text/html', 'hash': 5868289008701913702, 'source_dataset': 'data'}


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

#ifndef __XEN_PUBLIC_TRACE_H__
#define __XEN_PUBLIC_TRACE_H__

#define TRACE_EXTRA_MAX    7
#define TRACE_EXTRA_SHIFT 28

/* Trace classes */
#define TRC_CLS_SHIFT 16
#define TRC_GEN      0x0001f000    /* General trace            */
#define TRC_SCHED    0x0002f000    /* Xen Scheduler trace      */
#define TRC_DOM0OP   0x0004f000    /* Xen DOM0 operation trace */
#define TRC_HVM      0x0008f000    /* Xen HVM trace            */
#define TRC_MEM      0x0010f000    /* Xen memory trace         */
#define TRC_PV       0x0020f000    /* Xen PV traces            */
#define TRC_SHADOW   0x0040f000    /* Xen shadow tracing       */
#define TRC_ALL      0x0ffff000
#define TRC_HD_TO_EVENT(x) ((x)&0x0fffffff)
#define TRC_HD_CYCLE_FLAG (1UL<<31)
#define TRC_HD_INCLUDES_CYCLE_COUNT(x) ( !!( (x) & TRC_HD_CYCLE_FLAG ) )
#define TRC_HD_EXTRA(x)    (((x)>>TRACE_EXTRA_SHIFT)&TRACE_EXTRA_MAX)

/* Trace subclasses */
#define TRC_SUBCLS_SHIFT 12

/* trace subclasses for SVM */
#define TRC_HVM_ENTRYEXIT 0x00081000   /* VMENTRY and #VMEXIT       */
#define TRC_HVM_HANDLER   0x00082000   /* various HVM handlers      */

#define TRC_SCHED_MIN       0x00021000   /* Just runstate changes */
#define TRC_SCHED_VERBOSE   0x00028000   /* More inclusive scheduling */

/* Trace events per class */
#define TRC_LOST_RECORDS        (TRC_GEN + 1)
#define TRC_TRACE_WRAP_BUFFER  (TRC_GEN + 2)
#define TRC_TRACE_CPU_CHANGE    (TRC_GEN + 3)

#define TRC_SCHED_RUNSTATE_CHANGE (TRC_SCHED_MIN + 1)
#define TRC_SCHED_DOM_ADD        (TRC_SCHED_VERBOSE +  1)
#define TRC_SCHED_DOM_REM        (TRC_SCHED_VERBOSE +  2)
#define TRC_SCHED_SLEEP          (TRC_SCHED_VERBOSE +  3)
#define TRC_SCHED_WAKE           (TRC_SCHED_VERBOSE +  4)
#define TRC_SCHED_YIELD          (TRC_SCHED_VERBOSE +  5)
#define TRC_SCHED_BLOCK          (TRC_SCHED_VERBOSE +  6)
#define TRC_SCHED_SHUTDOWN       (TRC_SCHED_VERBOSE +  7)
#define TRC_SCHED_CTL            (TRC_SCHED_VERBOSE +  8)
#define TRC_SCHED_ADJDOM         (TRC_SCHED_VERBOSE +  9)
#define TRC_SCHED_SWITCH         (TRC_SCHED_VERBOSE + 10)
#define TRC_SCHED_S_TIMER_FN     (TRC_SCHED_VERBOSE + 11)
#define TRC_SCHED_T_TIMER_FN     (TRC_SCHED_VERBOSE + 12)
#define TRC_SCHED_DOM_TIMER_FN   (TRC_SCHED_VERBOSE + 13)
#define TRC_SCHED_SWITCH_INFPREV (TRC_SCHED_VERBOSE + 14)
#define TRC_SCHED_SWITCH_INFNEXT (TRC_SCHED_VERBOSE + 15)

#define TRC_MEM_PAGE_GRANT_MAP      (TRC_MEM + 1)
#define TRC_MEM_PAGE_GRANT_UNMAP    (TRC_MEM + 2)
#define TRC_MEM_PAGE_GRANT_TRANSFER (TRC_MEM + 3)

#define TRC_PV_HYPERCALL             (TRC_PV +  1)
#define TRC_PV_TRAP                  (TRC_PV +  3)
#define TRC_PV_PAGE_FAULT            (TRC_PV +  4)
#define TRC_PV_FORCED_INVALID_OP     (TRC_PV +  5)
#define TRC_PV_EMULATE_PRIVOP        (TRC_PV +  6)
#define TRC_PV_EMULATE_4GB           (TRC_PV +  7)
#define TRC_PV_MATH_STATE_RESTORE    (TRC_PV +  8)
#define TRC_PV_PAGING_FIXUP          (TRC_PV +  9)
#define TRC_PV_GDT_LDT_MAPPING_FAULT (TRC_PV + 10)
#define TRC_PV_PTWR_EMULATION        (TRC_PV + 11)
#define TRC_PV_PTWR_EMULATION_PAE    (TRC_PV + 12)
  /* Indicates that addresses in trace record are 64 bits */
#define TRC_64_FLAG               (0x100)

#define TRC_SHADOW_NOT_SHADOW                 (TRC_SHADOW +  1)
#define TRC_SHADOW_FAST_PROPAGATE             (TRC_SHADOW +  2)
#define TRC_SHADOW_FAST_MMIO                  (TRC_SHADOW +  3)
#define TRC_SHADOW_FALSE_FAST_PATH            (TRC_SHADOW +  4)
#define TRC_SHADOW_MMIO                       (TRC_SHADOW +  5)
#define TRC_SHADOW_FIXUP                      (TRC_SHADOW +  6)
#define TRC_SHADOW_DOMF_DYING                 (TRC_SHADOW +  7)
#define TRC_SHADOW_EMULATE                    (TRC_SHADOW +  8)
#define TRC_SHADOW_EMULATE_UNSHADOW_USER      (TRC_SHADOW +  9)
#define TRC_SHADOW_EMULATE_UNSHADOW_EVTINJ    (TRC_SHADOW + 10)
#define TRC_SHADOW_EMULATE_UNSHADOW_UNHANDLED (TRC_SHADOW + 11)
#define TRC_SHADOW_WRMAP_BF                   (TRC_SHADOW + 12)
#define TRC_SHADOW_PREALLOC_UNPIN             (TRC_SHADOW + 13)
#define TRC_SHADOW_RESYNC_FULL                (TRC_SHADOW + 14)
#define TRC_SHADOW_RESYNC_ONLY                (TRC_SHADOW + 15)

/* trace events per subclass */
#define TRC_HVM_VMENTRY         (TRC_HVM_ENTRYEXIT + 0x01)
#define TRC_HVM_VMEXIT          (TRC_HVM_ENTRYEXIT + 0x02)
#define TRC_HVM_VMEXIT64        (TRC_HVM_ENTRYEXIT + TRC_64_FLAG + 0x02)
#define TRC_HVM_PF_XEN          (TRC_HVM_HANDLER + 0x01)
#define TRC_HVM_PF_XEN64        (TRC_HVM_HANDLER + TRC_64_FLAG + 0x01)
#define TRC_HVM_PF_INJECT       (TRC_HVM_HANDLER + 0x02)
#define TRC_HVM_PF_INJECT64     (TRC_HVM_HANDLER + TRC_64_FLAG + 0x02)
#define TRC_HVM_INJ_EXC         (TRC_HVM_HANDLER + 0x03)
#define TRC_HVM_INJ_VIRQ        (TRC_HVM_HANDLER + 0x04)
#define TRC_HVM_REINJ_VIRQ      (TRC_HVM_HANDLER + 0x05)
#define TRC_HVM_IO_READ         (TRC_HVM_HANDLER + 0x06)
#define TRC_HVM_IO_WRITE        (TRC_HVM_HANDLER + 0x07)
#define TRC_HVM_CR_READ         (TRC_HVM_HANDLER + 0x08)
#define TRC_HVM_CR_READ64       (TRC_HVM_HANDLER + TRC_64_FLAG + 0x08)
#define TRC_HVM_CR_WRITE        (TRC_HVM_HANDLER + 0x09)
#define TRC_HVM_CR_WRITE64      (TRC_HVM_HANDLER + TRC_64_FLAG + 0x09)
#define TRC_HVM_DR_READ         (TRC_HVM_HANDLER + 0x0A)
#define TRC_HVM_DR_WRITE        (TRC_HVM_HANDLER + 0x0B)
#define TRC_HVM_MSR_READ        (TRC_HVM_HANDLER + 0x0C)
#define TRC_HVM_MSR_WRITE       (TRC_HVM_HANDLER + 0x0D)
#define TRC_HVM_CPUID           (TRC_HVM_HANDLER + 0x0E)
#define TRC_HVM_INTR            (TRC_HVM_HANDLER + 0x0F)
#define TRC_HVM_NMI             (TRC_HVM_HANDLER + 0x10)
#define TRC_HVM_SMI             (TRC_HVM_HANDLER + 0x11)
#define TRC_HVM_VMMCALL         (TRC_HVM_HANDLER + 0x12)
#define TRC_HVM_HLT             (TRC_HVM_HANDLER + 0x13)
#define TRC_HVM_INVLPG          (TRC_HVM_HANDLER + 0x14)
#define TRC_HVM_INVLPG64        (TRC_HVM_HANDLER + TRC_64_FLAG + 0x14)
#define TRC_HVM_MCE             (TRC_HVM_HANDLER + 0x15)
#define TRC_HVM_IO_ASSIST       (TRC_HVM_HANDLER + 0x16)
#define TRC_HVM_MMIO_ASSIST     (TRC_HVM_HANDLER + 0x17)
#define TRC_HVM_CLTS            (TRC_HVM_HANDLER + 0x18)
#define TRC_HVM_LMSW            (TRC_HVM_HANDLER + 0x19)
#define TRC_HVM_LMSW64          (TRC_HVM_HANDLER + TRC_64_FLAG + 0x19)

/* This structure represents a single trace buffer record. */
struct t_rec {
    uint32_t event:28;
    uint32_t extra_u32:3;         /* # entries in trailing extra_u32[] array */
    uint32_t cycles_included:1;   /* u.cycles or u.no_cycles? */
    union {
        struct {
            uint32_t cycles_lo, cycles_hi; /* cycle counter timestamp */
            uint32_t extra_u32[7];         /* event data items */
        } cycles;
        struct {
            uint32_t extra_u32[7];         /* event data items */
        } nocycles;
    } u;
};

/*
 * This structure contains the metadata for a single trace buffer.  The head
 * field, indexes into an array of struct t_rec's.
 */
struct t_buf {
    /* Assume the data buffer size is X.  X is generally not a power of 2.
     * CONS and PROD are incremented modulo (2*X):
     *     0 <= cons < 2*X
     *     0 <= prod < 2*X
     * This is done because addition modulo X breaks at 2^32 when X is not a
     * power of 2:
     *     (((2^32 - 1) % X) + 1) % X != (2^32) % X
     */
    uint32_t cons;   /* Offset of next item to be consumed by control tools. */
    uint32_t prod;   /* Offset of next item to be produced by Xen.           */
    /*  Records follow immediately after the meta-data header.    */
};

#endif /* __XEN_PUBLIC_TRACE_H__ */

/*
 * Local variables:
 * mode: C
 * c-set-style: "BSD"
 * c-basic-offset: 4
 * tab-width: 4
 * indent-tabs-mode: nil
 * End:
 */

{'repo_name': 'cloudius-systems/osv', 'stars': '3086', 'repo_language': 'C', 'file_name': 'cold-label.cc', 'mime_type': 'text/plain', 'hash': -1914436006128976085, 'source_dataset': 'data'}


<?php foreach ($this->getTableMap()->getColumns() as $column): ?>

<?php echo sfInflector::humanize(sfInflector::underscore($column->getPhpName())) ?>:
[?= $<?php echo $this->getSingularName() ?>->get<?php echo $column->getPhpName() ?>() ?]

<?php endforeach; ?>

[?php echo link_to('edit', '<?php echo $this->getModuleName() ?>/edit?<?php echo $this->getPrimaryKeyUrlParams() ?>) ?]
 [?php echo link_to('list', '<?php echo $this->getModuleName() ?>/list') ?]

{'repo_name': 'kaltura/server', 'stars': '262', 'repo_language': 'PHP', 'file_name': 'AsperaNodeApi.php', 'mime_type': 'text/x-php', 'hash': 3566260154244574861, 'source_dataset': 'data'}


/*
 * Copyright 2012-2016 Sergey Ignatov
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.intellij.erlang.parser;

import org.intellij.erlang.ErlangParserDefinition;

public class ErlangReleaseFileParserTest extends ErlangParserTestBase {
  public ErlangReleaseFileParserTest() {
    super("parser", "rel", new ErlangParserDefinition());
  }

  public void testRelease() { doTest(false); }
}

{'repo_name': 'ignatov/intellij-erlang', 'stars': '658', 'repo_language': 'Java', 'file_name': 'erlang.bnf', 'mime_type': 'text/plain', 'hash': 2291491947386044895, 'source_dataset': 'data'}