text:
// SPDX-License-Identifier: Apache-2.0

#define pr_fmt(fmt)    "FLASH: " fmt

#include <skiboot.h>
#include <cpu.h>
#include <lock.h>
#include <opal.h>
#include <opal-msg.h>
#include <platform.h>
#include <device.h>
#include <libflash/libflash.h>
#include <libflash/libffs.h>
#include <libflash/ipmi-hiomap.h>
#include <libflash/blocklevel.h>
#include <libflash/ecc.h>
#include <libstb/secureboot.h>
#include <libstb/trustedboot.h>
#include <libxz/xz.h>
#include <elf.h>
#include <timebase.h>

struct flash {
	struct list_node	list;
	bool			busy;
	bool			no_erase;
	struct blocklevel_device *bl;
	uint64_t		size;
	uint32_t		block_size;
	int			id;
};

static struct {
	enum resource_id	id;
	uint32_t		subid;
	char			name[PART_NAME_MAX+1];
} part_name_map[] = {
	{ RESOURCE_ID_KERNEL,	RESOURCE_SUBID_NONE,		"BOOTKERNEL" },
	{ RESOURCE_ID_INITRAMFS,RESOURCE_SUBID_NONE,		"ROOTFS" },
	{ RESOURCE_ID_CAPP,	RESOURCE_SUBID_SUPPORTED,	"CAPP" },
	{ RESOURCE_ID_IMA_CATALOG,  RESOURCE_SUBID_SUPPORTED,	"IMA_CATALOG" },
	{ RESOURCE_ID_VERSION,	RESOURCE_SUBID_NONE,		"VERSION" },
	{ RESOURCE_ID_KERNEL_FW,	RESOURCE_SUBID_NONE,		"BOOTKERNFW" },
};

static LIST_HEAD(flashes);
static struct flash *system_flash;

/* Using a single lock as we only have one flash at present. */
static struct lock flash_lock;

/* nvram-on-flash support */
static struct flash *nvram_flash;
static u32 nvram_offset, nvram_size;

/* secboot-on-flash support */
static struct flash *secboot_flash;
static u32 secboot_offset, secboot_size;

bool flash_reserve(void)
{
	bool rc = false;

	if (!try_lock(&flash_lock))
		return false;

	if (!system_flash->busy) {
		system_flash->busy = true;
		rc = true;
	}
	unlock(&flash_lock);

	return rc;
}

void flash_release(void)
{
	lock(&flash_lock);
	system_flash->busy = false;
	unlock(&flash_lock);
}

bool flash_unregister(void)
{
	struct blocklevel_device *bl = system_flash->bl;

	if (bl->exit)
		return bl->exit(bl);

	prlog(PR_NOTICE, "Unregister flash device is not supported\n");
	return true;
}

int flash_secboot_info(uint32_t *total_size)
{
	int rc;

	lock(&flash_lock);
	if (!secboot_flash) {
		rc = OPAL_HARDWARE;
	} else if (secboot_flash->busy) {
		rc = OPAL_BUSY;
	} else {
		*total_size = secboot_size;
		rc = OPAL_SUCCESS;
	}
	unlock(&flash_lock);

	return rc;
}

int flash_secboot_read(void *dst, uint32_t src, uint32_t len)
{
	int rc;

	if (!try_lock(&flash_lock))
		return OPAL_BUSY;

	if (!secboot_flash) {
		rc = OPAL_HARDWARE;
		goto out;
	}

	if (secboot_flash->busy) {
		rc = OPAL_BUSY;
		goto out;
	}

	if ((src + len) > secboot_size) {
		prerror("FLASH_SECBOOT: read out of bound (0x%x,0x%x)\n",
			src, len);
		rc = OPAL_PARAMETER;
		goto out;
	}

	secboot_flash->busy = true;
	unlock(&flash_lock);

	rc = blocklevel_read(secboot_flash->bl, secboot_offset + src, dst, len);

	lock(&flash_lock);
	secboot_flash->busy = false;
out:
	unlock(&flash_lock);
	return rc;
}

int flash_secboot_write(uint32_t dst, void *src, uint32_t len)
{
	int rc;

	if (!try_lock(&flash_lock))
		return OPAL_BUSY;

	if (secboot_flash->busy) {
		rc = OPAL_BUSY;
		goto out;
	}

	if ((dst + len) > secboot_size) {
		prerror("FLASH_SECBOOT: write out of bound (0x%x,0x%x)\n",
			dst, len);
		rc = OPAL_PARAMETER;
		goto out;
	}

	secboot_flash->busy = true;
	unlock(&flash_lock);

	rc = blocklevel_write(secboot_flash->bl, secboot_offset + dst, src, len);

	lock(&flash_lock);
	secboot_flash->busy = false;
out:
	unlock(&flash_lock);
	return rc;
}

static int flash_nvram_info(uint32_t *total_size)
{
	int rc;

	lock(&flash_lock);
	if (!nvram_flash) {
		rc = OPAL_HARDWARE;
	} else if (nvram_flash->busy) {
		rc = OPAL_BUSY;
	} else {
		*total_size = nvram_size;
		rc = OPAL_SUCCESS;
	}
	unlock(&flash_lock);

	return rc;
}

static int flash_nvram_start_read(void *dst, uint32_t src, uint32_t len)
{
	int rc;

	if (!try_lock(&flash_lock))
		return OPAL_BUSY;

	if (!nvram_flash) {
		rc = OPAL_HARDWARE;
		goto out;
	}

	if (nvram_flash->busy) {
		rc = OPAL_BUSY;
		goto out;
	}

	if ((src + len) > nvram_size) {
		prerror("NVRAM: read out of bound (0x%x,0x%x)\n",
			src, len);
		rc = OPAL_PARAMETER;
		goto out;
	}

	nvram_flash->busy = true;
	unlock(&flash_lock);

	rc = blocklevel_read(nvram_flash->bl, nvram_offset + src, dst, len);

	lock(&flash_lock);
	nvram_flash->busy = false;
out:
	unlock(&flash_lock);
	if (!rc)
		nvram_read_complete(true);
	return rc;
}

static int flash_nvram_write(uint32_t dst, void *src, uint32_t len)
{
	int rc;

	if (!try_lock(&flash_lock))
		return OPAL_BUSY;

	if (nvram_flash->busy) {
		rc = OPAL_BUSY;
		goto out;
	}

	/* TODO: When we have async jobs for PRD, turn this into one */

	if ((dst + len) > nvram_size) {
		prerror("NVRAM: write out of bound (0x%x,0x%x)\n",
			dst, len);
		rc = OPAL_PARAMETER;
		goto out;
	}

	nvram_flash->busy = true;
	unlock(&flash_lock);

	rc = blocklevel_write(nvram_flash->bl, nvram_offset + dst, src, len);

	lock(&flash_lock);
	nvram_flash->busy = false;
out:
	unlock(&flash_lock);
	return rc;
}

static int flash_secboot_probe(struct flash *flash, struct ffs_handle *ffs)
{
	uint32_t start, size, part;
	bool ecc;
	int rc;

	prlog(PR_DEBUG, "FLASH: probing for SECBOOT\n");

	rc = ffs_lookup_part(ffs, "SECBOOT", &part);
	if (rc) {
		prlog(PR_WARNING, "FLASH: no SECBOOT partition found\n");
		return OPAL_HARDWARE;
	}

	rc = ffs_part_info(ffs, part, NULL,
			   &start, &size, NULL, &ecc);
	if (rc) {
		/**
		 * @fwts-label SECBOOTNoPartition
		 * @fwts-advice OPAL could not find an SECBOOT partition
		 *     on the system flash. Check that the system flash
		 *     has a valid partition table, and that the firmware
		 *     build process has added a SECBOOT partition.
		 */
		prlog(PR_ERR, "FLASH: Can't parse ffs info for SECBOOT\n");
		return OPAL_HARDWARE;
	}

	secboot_flash = flash;
	secboot_offset = start;
	secboot_size = ecc ? ecc_buffer_size_minus_ecc(size) : size;

	return 0;
}

static int flash_nvram_probe(struct flash *flash, struct ffs_handle *ffs)
{
	uint32_t start, size, part;
	bool ecc;
	int rc;

	prlog(PR_INFO, "probing for NVRAM\n");

	rc = ffs_lookup_part(ffs, "NVRAM", &part);
	if (rc) {
		prlog(PR_WARNING, "no NVRAM partition found\n");
		return OPAL_HARDWARE;
	}

	rc = ffs_part_info(ffs, part, NULL,
			   &start, &size, NULL, &ecc);
	if (rc) {
		/**
		 * @fwts-label NVRAMNoPartition
		 * @fwts-advice OPAL could not find an NVRAM partition
		 *     on the system flash. Check that the system flash
		 *     has a valid partition table, and that the firmware
		 *     build process has added a NVRAM partition.
		 */
		prlog(PR_ERR, "Can't parse ffs info for NVRAM\n");
		return OPAL_HARDWARE;
	}

	nvram_flash = flash;
	nvram_offset = start;
	nvram_size = ecc ? ecc_buffer_size_minus_ecc(size) : size;

	platform.nvram_info = flash_nvram_info;
	platform.nvram_start_read = flash_nvram_start_read;
	platform.nvram_write = flash_nvram_write;

	return 0;
}

/* core flash support */

static struct dt_node *flash_add_dt_node(struct flash *flash, int id)
{
	int i;
	int rc;
	const char *name;
	bool ecc;
	struct ffs_handle *ffs;
	int ffs_part_num, ffs_part_start, ffs_part_size;
	struct dt_node *flash_node;
	struct dt_node *partition_container_node;
	struct dt_node *partition_node;

	flash_node = dt_new_addr(opal_node, "flash", id);
	dt_add_property_strings(flash_node, "compatible", "ibm,opal-flash");
	dt_add_property_cells(flash_node, "ibm,opal-id", id);
	dt_add_property_u64(flash_node, "reg", flash->size);
	dt_add_property_cells(flash_node, "ibm,flash-block-size",
			flash->block_size);
	if (flash->no_erase)
		dt_add_property(flash_node, "no-erase", NULL, 0);

	/* we fix to 32-bits */
	dt_add_property_cells(flash_node, "#address-cells", 1);
	dt_add_property_cells(flash_node, "#size-cells", 1);

	/* Add partition container node */
	partition_container_node = dt_new(flash_node, "partitions");
	dt_add_property_strings(partition_container_node, "compatible", "fixed-partitions");

	/* we fix to 32-bits */
	dt_add_property_cells(partition_container_node, "#address-cells", 1);
	dt_add_property_cells(partition_container_node, "#size-cells", 1);

	/* Add partitions */
	for (i = 0, name = NULL; i < ARRAY_SIZE(part_name_map); i++) {
		name = part_name_map[i].name;

		rc = ffs_init(0, flash->size, flash->bl, &ffs, 1);
		if (rc) {
			prerror("Can't open ffs handle\n");
			continue;
		}

		rc = ffs_lookup_part(ffs, name, &ffs_part_num);
		if (rc) {
			/* This is not an error per-se, some partitions
			 * are purposefully absent, don't spam the logs
			 */
		        prlog(PR_DEBUG, "No %s partition\n", name);
			continue;
		}
		rc = ffs_part_info(ffs, ffs_part_num, NULL,
				   &ffs_part_start, NULL, &ffs_part_size, &ecc);
		if (rc) {
			prerror("Failed to get %s partition info\n", name);
			continue;
		}

		partition_node = dt_new_addr(partition_container_node, "partition", ffs_part_start);
		dt_add_property_strings(partition_node, "label", name);
		dt_add_property_cells(partition_node, "reg", ffs_part_start, ffs_part_size);
		if (part_name_map[i].id != RESOURCE_ID_KERNEL_FW) {
			/* Mark all partitions other than the full PNOR and the boot kernel
			 * firmware as read only.  These two partitions are the only partitions
			 * that are properly erase block aligned at this time.
			 */
			dt_add_property(partition_node, "read-only", NULL, 0);
		}
	}

	partition_node = dt_new_addr(partition_container_node, "partition", 0);
	dt_add_property_strings(partition_node, "label", "PNOR");
	dt_add_property_cells(partition_node, "reg", 0, flash->size);

	return flash_node;
}

static void setup_system_flash(struct flash *flash, struct dt_node *node,
		const char *name, struct ffs_handle *ffs)
{
	char *path;

	if (!ffs)
		return;

	if (system_flash) {
		/**
		 * @fwts-label SystemFlashMultiple
		 * @fwts-advice OPAL Found multiple system flash.
		 *    Since we've already found a system flash we are
		 *    going to use that one but this ordering is not
		 *    guaranteed so may change in future.
		 */
		prlog(PR_WARNING, "Attempted to register multiple system "
		      "flash: %s\n", name);
		return;
	}

	prlog(PR_NOTICE, "Found system flash: %s id:%i\n",
	      name, flash->id);

	system_flash = flash;
	path = dt_get_path(node);
	dt_add_property_string(dt_chosen, "ibm,system-flash", path);
	free(path);

	prlog(PR_INFO, "registered system flash device %s\n", name);

	flash_nvram_probe(flash, ffs);
	flash_secboot_probe(flash, ffs);
}

static int num_flashes(void)
{
	struct flash *flash;
	int i = 0;

	list_for_each(&flashes, flash, list)
		i++;

	return i;
}

int flash_register(struct blocklevel_device *bl)
{
	uint64_t size;
	uint32_t block_size;
	struct ffs_handle *ffs;
	struct dt_node *node;
	struct flash *flash;
	const char *name;
	int rc;

	rc = blocklevel_get_info(bl, &name, &size, &block_size);
	if (rc)
		return rc;

	if (!name)
		name = "(unnamed)";

	prlog(PR_INFO, "registering flash device %s "
			"(size 0x%llx, blocksize 0x%x)\n",
			name, size, block_size);

	flash = malloc(sizeof(struct flash));
	if (!flash) {
		prlog(PR_ERR, "Error allocating flash structure\n");
		return OPAL_RESOURCE;
	}

	flash->busy = false;
	flash->bl = bl;
	flash->no_erase = !(bl->flags & WRITE_NEED_ERASE);
	flash->size = size;
	flash->block_size = block_size;
	flash->id = num_flashes();

	rc = ffs_init(0, flash->size, bl, &ffs, 1);
	if (rc) {
		/**
		 * @fwts-label NoFFS
		 * @fwts-advice System flash isn't formatted as expected.
		 * This could mean several OPAL utilities do not function
		 * as expected. e.g. gard, pflash.
		 */
		prlog(PR_WARNING, "No ffs info; "
				"using raw device only\n");
		ffs = NULL;
	}

	node = flash_add_dt_node(flash, flash->id);

	setup_system_flash(flash, node, name, ffs);

	if (ffs)
		ffs_close(ffs);

	lock(&flash_lock);
	list_add(&flashes, &flash->list);
	unlock(&flash_lock);

	return OPAL_SUCCESS;
}

enum flash_op {
	FLASH_OP_READ,
	FLASH_OP_WRITE,
	FLASH_OP_ERASE,
};

static int64_t opal_flash_op(enum flash_op op, uint64_t id, uint64_t offset,
		uint64_t buf, uint64_t size, uint64_t token)
{
	struct flash *flash = NULL;
	int rc;

	if (!try_lock(&flash_lock))
		return OPAL_BUSY;

	list_for_each(&flashes, flash, list)
		if (flash->id == id)
			break;

	if (flash->id != id) {
		/* Couldn't find the flash */
		rc = OPAL_PARAMETER;
		goto err;
	}

	if (flash->busy) {
		rc = OPAL_BUSY;
		goto err;
	}

	if (size >= flash->size || offset >= flash->size
			|| offset + size > flash->size) {
		rc = OPAL_PARAMETER;
		goto err;
	}

	/*
	 * These ops intentionally have no smarts (ecc correction or erase
	 * before write) to them.
	 * Skiboot is simply exposing the PNOR flash to the host.
	 * The host is expected to understand that this is a raw flash
	 * device and treat it as such.
	 */
	switch (op) {
	case FLASH_OP_READ:
		rc = blocklevel_raw_read(flash->bl, offset, (void *)buf, size);
		break;
	case FLASH_OP_WRITE:
		rc = blocklevel_raw_write(flash->bl, offset, (void *)buf, size);
		break;
	case FLASH_OP_ERASE:
		rc = blocklevel_erase(flash->bl, offset, size);
		break;
	default:
		assert(0);
	}

	if (rc) {
		rc = OPAL_HARDWARE;
		goto err;
	}

	unlock(&flash_lock);

	opal_queue_msg(OPAL_MSG_ASYNC_COMP, NULL, NULL,
			cpu_to_be64(token),
			cpu_to_be64(rc));

	return OPAL_ASYNC_COMPLETION;

err:
	unlock(&flash_lock);
	return rc;
}

static int64_t opal_flash_read(uint64_t id, uint64_t offset, uint64_t buf,
		uint64_t size, uint64_t token)
{
	if (!opal_addr_valid((void *)buf))
		return OPAL_PARAMETER;

	return opal_flash_op(FLASH_OP_READ, id, offset, buf, size, token);
}

static int64_t opal_flash_write(uint64_t id, uint64_t offset, uint64_t buf,
		uint64_t size, uint64_t token)
{
	if (!opal_addr_valid((void *)buf))
		return OPAL_PARAMETER;

	return opal_flash_op(FLASH_OP_WRITE, id, offset, buf, size, token);
}

static int64_t opal_flash_erase(uint64_t id, uint64_t offset, uint64_t size,
		uint64_t token)
{
	return opal_flash_op(FLASH_OP_ERASE, id, offset, 0L, size, token);
}

opal_call(OPAL_FLASH_READ, opal_flash_read, 5);
opal_call(OPAL_FLASH_WRITE, opal_flash_write, 5);
opal_call(OPAL_FLASH_ERASE, opal_flash_erase, 4);

/* flash resource API */
const char *flash_map_resource_name(enum resource_id id)
{
	int i;

	for (i = 0; i < ARRAY_SIZE(part_name_map); i++) {
		if (part_name_map[i].id == id)
			return part_name_map[i].name;
	}
	return NULL;
}

static size_t sizeof_elf_from_hdr(void *buf)
{
	struct elf_hdr *elf = (struct elf_hdr *)buf;
	size_t sz = 0;

	BUILD_ASSERT(SECURE_BOOT_HEADERS_SIZE > sizeof(struct elf_hdr));
	BUILD_ASSERT(SECURE_BOOT_HEADERS_SIZE > sizeof(struct elf64be_hdr));
	BUILD_ASSERT(SECURE_BOOT_HEADERS_SIZE > sizeof(struct elf32be_hdr));

	if (elf->ei_ident == ELF_IDENT) {
		if (elf->ei_class == ELF_CLASS_64) {
			if (elf->ei_data == ELF_DATA_LSB) {
				struct elf64le_hdr *kh = (struct elf64le_hdr *)buf;
				sz = le64_to_cpu(kh->e_shoff) +
					((uint32_t)le16_to_cpu(kh->e_shentsize) *
					 (uint32_t)le16_to_cpu(kh->e_shnum));
			} else {
				struct elf64be_hdr *kh = (struct elf64be_hdr *)buf;
				sz = be64_to_cpu(kh->e_shoff) +
					((uint32_t)be16_to_cpu(kh->e_shentsize) *
					 (uint32_t)be16_to_cpu(kh->e_shnum));
			}
		} else if (elf->ei_class == ELF_CLASS_32) {
			if (elf->ei_data == ELF_DATA_LSB) {
				struct elf32le_hdr *kh = (struct elf32le_hdr *)buf;
				sz = le32_to_cpu(kh->e_shoff) +
					(le16_to_cpu(kh->e_shentsize) *
					 le16_to_cpu(kh->e_shnum));
			} else {
				struct elf32be_hdr *kh = (struct elf32be_hdr *)buf;
				sz = be32_to_cpu(kh->e_shoff) +
					(be16_to_cpu(kh->e_shentsize) *
					 be16_to_cpu(kh->e_shnum));
			}
		}
	}

	return sz;
}

/*
 * load a resource from FLASH
 * buf and len shouldn't account for ECC even if partition is ECCed.
 *
 * The API here is a bit strange.
 * If resource has a STB container, buf will contain it
 * If loading subpartition with STB container, buff will *NOT* contain it
 * For trusted boot, the whole partition containing the subpart is measured.
 *
 * Additionally, the logic to work out how much to read from flash is insane.
 */
static int flash_load_resource(enum resource_id id, uint32_t subid,
			       void *buf, size_t *len)
{
	int i;
	int rc = OPAL_RESOURCE;
	struct ffs_handle *ffs;
	struct flash *flash;
	const char *name;
	bool status = false;
	bool ecc;
	bool part_signed = false;
	void *bufp = buf;
	size_t bufsz = *len;
	int ffs_part_num, ffs_part_start, ffs_part_size;
	int content_size = 0;
	int offset = 0;

	lock(&flash_lock);

	if (!system_flash) {
		/**
		 * @fwts-label SystemFlashNotFound
		 * @fwts-advice No system flash was found. Check for missing
		 * calls flash_register(...).
		 */
		prlog(PR_WARNING, "Can't load resource id:%i. "
		      "No system flash found\n", id);
		goto out_unlock;
	}

	flash = system_flash;

	if (flash->busy)
		goto out_unlock;

	for (i = 0, name = NULL; i < ARRAY_SIZE(part_name_map); i++) {
		if (part_name_map[i].id == id) {
			name = part_name_map[i].name;
			break;
		}
	}
	if (!name) {
		prerror("Couldn't find partition for id %d\n", id);
		goto out_unlock;
	}
	/*
	 * If partition doesn't have a subindex but the caller specifies one,
	 * we fail.  eg. kernel partition doesn't have a subindex
	 */
	if ((part_name_map[i].subid == RESOURCE_SUBID_NONE) &&
	    (subid != RESOURCE_SUBID_NONE)) {
		prerror("PLAT: Partition %s doesn't have subindex\n", name);
		goto out_unlock;
	}

	rc = ffs_init(0, flash->size, flash->bl, &ffs, 1);
	if (rc) {
		prerror("Can't open ffs handle: %d\n", rc);
		goto out_unlock;
	}

	rc = ffs_lookup_part(ffs, name, &ffs_part_num);
	if (rc) {
		/* This is not an error per-se, some partitions
		 * are purposefully absent, don't spam the logs
		 */
	        prlog(PR_DEBUG, "No %s partition\n", name);
		goto out_free_ffs;
	}
	rc = ffs_part_info(ffs, ffs_part_num, NULL,
			   &ffs_part_start, NULL, &ffs_part_size, &ecc);
	if (rc) {
		prerror("Failed to get %s partition info\n", name);
		goto out_free_ffs;
	}
	prlog(PR_DEBUG,"%s partition %s ECC\n",
	      name, ecc  ? "has" : "doesn't have");

	/*
	 * FIXME: Make the fact we don't support partitions smaller than 4K
	 *  	  more explicit.
	 */
	if (ffs_part_size < SECURE_BOOT_HEADERS_SIZE) {
		prerror("secboot headers bigger than "
			"partition size 0x%x\n", ffs_part_size);
		goto out_free_ffs;
	}

	rc = blocklevel_read(flash->bl, ffs_part_start, bufp,
			SECURE_BOOT_HEADERS_SIZE);
	if (rc) {
		prerror("failed to read the first 0x%x from "
			"%s partition, rc %d\n", SECURE_BOOT_HEADERS_SIZE,
			name, rc);
		goto out_free_ffs;
	}

	part_signed = stb_is_container(bufp, SECURE_BOOT_HEADERS_SIZE);

	prlog(PR_DEBUG, "%s partition %s signed\n", name,
	      part_signed ? "is" : "isn't");

	/*
	 * part_start/size are raw pointers into the partition.
	 *  ie. they will account for ECC if included.
	 */

	if (part_signed) {
		bufp += SECURE_BOOT_HEADERS_SIZE;
		bufsz -= SECURE_BOOT_HEADERS_SIZE;
		content_size = stb_sw_payload_size(buf, SECURE_BOOT_HEADERS_SIZE);
		*len = content_size + SECURE_BOOT_HEADERS_SIZE;

		if (content_size > bufsz) {
			prerror("content size > buffer size\n");
			rc = OPAL_PARAMETER;
			goto out_free_ffs;
		}

		if (*len > ffs_part_size) {
			prerror("FLASH: Cannot load %s. Content is larger than the partition\n",
					name);
			rc = OPAL_PARAMETER;
			goto out_free_ffs;
		}

		ffs_part_start += SECURE_BOOT_HEADERS_SIZE;

		rc = blocklevel_read(flash->bl, ffs_part_start, bufp,
					  content_size);
		if (rc) {
			prerror("failed to read content size %d"
				" %s partition, rc %d\n",
				content_size, name, rc);
			goto out_free_ffs;
		}

		if (subid == RESOURCE_SUBID_NONE)
			goto done_reading;

		rc = flash_subpart_info(bufp, content_size, ffs_part_size,
					NULL, subid, &offset, &content_size);
		if (rc) {
			prerror("Failed to parse subpart info for %s\n",
				name);
			goto out_free_ffs;
		}
		bufp += offset;
		goto done_reading;
	} else /* stb_signed */ {
		/*
		 * Back to the old way of doing things, no STB header.
		 */
		if (subid == RESOURCE_SUBID_NONE) {
			if (id == RESOURCE_ID_KERNEL ||
				id == RESOURCE_ID_INITRAMFS) {
				/*
				 * Because actualSize is a lie, we compute the
				 * size of the BOOTKERNEL based on what the ELF
				 * headers say. Otherwise we end up reading more
				 * than we should
				 */
				content_size = sizeof_elf_from_hdr(buf);
				if (!content_size) {
					prerror("Invalid ELF header part"
						" %s\n", name);
					rc = OPAL_RESOURCE;
					goto out_free_ffs;
				}
			} else {
				content_size = ffs_part_size;
			}
			if (content_size > bufsz) {
				prerror("%s content size %d > "
					" buffer size %lu\n", name,
					content_size, bufsz);
				rc = OPAL_PARAMETER;
				goto out_free_ffs;
			}
			prlog(PR_DEBUG, "computed %s size %u\n",
			      name, content_size);
			rc = blocklevel_read(flash->bl, ffs_part_start,
						  buf, content_size);
			if (rc) {
				prerror("failed to read content size %d"
					" %s partition, rc %d\n",
					content_size, name, rc);
				goto out_free_ffs;
			}
			*len = content_size;
			goto done_reading;
		}
		BUILD_ASSERT(FLASH_SUBPART_HEADER_SIZE <= SECURE_BOOT_HEADERS_SIZE);
		rc = flash_subpart_info(bufp, SECURE_BOOT_HEADERS_SIZE,
					ffs_part_size, &ffs_part_size, subid,
					&offset, &content_size);
		if (rc) {
			prerror("FAILED reading subpart info. rc=%d\n",
				rc);
			goto out_free_ffs;
		}

		*len = ffs_part_size;
		prlog(PR_DEBUG, "Computed %s partition size: %u "
		      "(subpart %u size %u offset %u)\n", name, ffs_part_size,
		      subid, content_size, offset);
		/*
		 * For a sub partition, we read the whole (computed)
		 * partition, and then measure that.
		 * Afterwards, we memmove() things back into place for
		 * the caller.
		 */
		rc = blocklevel_read(flash->bl, ffs_part_start,
					  buf, ffs_part_size);

		bufp += offset;
	}

done_reading:
	/*
	 * Verify and measure the retrieved PNOR partition as part of the
	 * secure boot and trusted boot requirements
	 */
	secureboot_verify(id, buf, *len);
	trustedboot_measure(id, buf, *len);

	/* Find subpartition */
	if (subid != RESOURCE_SUBID_NONE) {
		memmove(buf, bufp, content_size);
		*len = content_size;
	}

	status = true;

out_free_ffs:
	ffs_close(ffs);
out_unlock:
	unlock(&flash_lock);
	return status ? OPAL_SUCCESS : rc;
}

struct flash_load_resource_item {
	enum resource_id id;
	uint32_t subid;
	int result;
	void *buf;
	size_t *len;
	struct list_node link;
};

static LIST_HEAD(flash_load_resource_queue);
static LIST_HEAD(flash_loaded_resources);
static struct lock flash_load_resource_lock = LOCK_UNLOCKED;
static struct cpu_job *flash_load_job = NULL;

int flash_resource_loaded(enum resource_id id, uint32_t subid)
{
	struct flash_load_resource_item *resource = NULL;
	struct flash_load_resource_item *r;
	int rc = OPAL_BUSY;

	lock(&flash_load_resource_lock);
	list_for_each(&flash_loaded_resources, r, link) {
		if (r->id == id && r->subid == subid) {
			resource = r;
			break;
		}
	}

	if (resource) {
		rc = resource->result;
		list_del(&resource->link);
		free(resource);
	}

	if (list_empty(&flash_load_resource_queue) && flash_load_job) {
		cpu_wait_job(flash_load_job, true);
		flash_load_job = NULL;
	}

	unlock(&flash_load_resource_lock);

	return rc;
}

/*
 * Retry for 10 minutes in 5 second intervals: allow 5 minutes for a BMC reboot
 * (need the BMC if we're using HIOMAP flash access), then 2x for some margin.
 */
#define FLASH_LOAD_WAIT_MS	5000
#define FLASH_LOAD_RETRIES	(2 * 5 * (60 / (FLASH_LOAD_WAIT_MS / 1000)))

static void flash_load_resources(void *data __unused)
{
	struct flash_load_resource_item *r;
	int retries = FLASH_LOAD_RETRIES;
	int result = OPAL_RESOURCE;

	lock(&flash_load_resource_lock);
	do {
		if (list_empty(&flash_load_resource_queue)) {
			break;
		}
		r = list_top(&flash_load_resource_queue,
			     struct flash_load_resource_item, link);
		if (r->result != OPAL_EMPTY)
			prerror("flash_load_resources() list_top unexpected "
				" result %d\n", r->result);
		r->result = OPAL_BUSY;
		unlock(&flash_load_resource_lock);

		while (retries) {
			result = flash_load_resource(r->id, r->subid, r->buf,
						     r->len);
			if (result == OPAL_SUCCESS) {
				retries = FLASH_LOAD_RETRIES;
				break;
			}

			if (result != FLASH_ERR_AGAIN &&
					result != FLASH_ERR_DEVICE_GONE)
				break;

			time_wait_ms(FLASH_LOAD_WAIT_MS);

			retries--;

			prlog(PR_WARNING,
			      "Retrying load of %d:%d, %d attempts remain\n",
			      r->id, r->subid, retries);
		}

		lock(&flash_load_resource_lock);
		r = list_pop(&flash_load_resource_queue,
			     struct flash_load_resource_item, link);
		/* Will reuse the result from when we hit retries == 0 */
		r->result = result;
		list_add_tail(&flash_loaded_resources, &r->link);
	} while(true);
	unlock(&flash_load_resource_lock);
}

static void start_flash_load_resource_job(void)
{
	if (flash_load_job)
		cpu_wait_job(flash_load_job, true);

	flash_load_job = cpu_queue_job(NULL, "flash_load_resources",
				       flash_load_resources, NULL);

	cpu_process_local_jobs();
}

int flash_start_preload_resource(enum resource_id id, uint32_t subid,
				 void *buf, size_t *len)
{
	struct flash_load_resource_item *r;
	bool start_thread = false;

	r = malloc(sizeof(struct flash_load_resource_item));

	assert(r != NULL);
	r->id = id;
	r->subid = subid;
	r->buf = buf;
	r->len = len;
	r->result = OPAL_EMPTY;

	prlog(PR_DEBUG, "Queueing preload of %x/%x\n",
	      r->id, r->subid);

	lock(&flash_load_resource_lock);
	if (list_empty(&flash_load_resource_queue)) {
		start_thread = true;
	}
	list_add_tail(&flash_load_resource_queue, &r->link);
	unlock(&flash_load_resource_lock);

	if (start_thread)
		start_flash_load_resource_job();

	return OPAL_SUCCESS;
}

/*
 * The `libxz` decompression routines are blocking; the new decompression
 * routines, wrapper around `libxz` functions, provide support for asynchronous
 * decompression. There are two routines, which start the decompression, and one
 * which waits for the decompression to complete.
 *
 * The decompressed image will be present in the `dst` parameter of
 * `xz_decompress` structure.
 *
 * When the decompression is successful, the xz_decompress->status will be
 * `OPAL_SUCCESS` else OPAL_PARAMETER, see definition of xz_decompress structure
 * for details.
 */
static void xz_decompress(void *data)
{
	struct xz_decompress *xz = (struct xz_decompress *)data;
	struct xz_dec *s;
	struct xz_buf b;

	/* Initialize the xz library first */
	xz_crc32_init();
	s = xz_dec_init(XZ_SINGLE, 0);
	if (s == NULL) {
		prerror("initialization error for xz\n");
		xz->status = OPAL_NO_MEM;
		return;
	}

	xz->xz_error = XZ_DATA_ERROR;
	xz->status = OPAL_PARTIAL;

	b.in = xz->src;
	b.in_pos = 0;
	b.in_size = xz->src_size;
	b.out = xz->dst;
	b.out_pos = 0;
	b.out_size = xz->dst_size;

	/* Start decompressing */
	xz->xz_error = xz_dec_run(s, &b);
	if (xz->xz_error != XZ_STREAM_END) {
		prerror("failed to decompress subpartition\n");
		xz->status = OPAL_PARAMETER;
	} else
		xz->status = OPAL_SUCCESS;

	xz_dec_end(s);
}

/*
 * xz_start_decompress: start the decompression job and return.
 *
 * struct xz_decompress *xz, should be populated by the caller with
 *     - the starting address of the compressed binary
 *     - the address where the decompressed image should be placed
 *     - the sizes of the source and the destination
 *
 * xz->src: Source address (The compressed binary)
 * xz->src_size: Source size
 * xz->dst: Destination address (The memory area where the `src` will be
 *          decompressed)
 * xz->dst_size: Destination size
 *
 * The `status` value will be OPAL_PARTIAL till the job completes (successfully
 * or not)
 */
void xz_start_decompress(struct xz_decompress *xz)
{
	struct cpu_job *job;

	if (!xz)
		return;

	if (!xz->dst || !xz->dst_size || !xz->src || !xz->src_size) {
		xz->status = OPAL_PARAMETER;
		return;
	}

	job = cpu_queue_job(NULL, "xz_decompress", xz_decompress,
			    (void *) xz);
	if (!job) {
		xz->status = OPAL_NO_MEM;
		return;
	}

	xz->job = job;
}

/*
 * This function waits for the decompression job to complete. The `ret`
 * structure member in `xz_decompress` will have the status code.
 *
 * status == OPAL_SUCCESS on success, else the corresponding error code.
 */
void wait_xz_decompress(struct xz_decompress *xz)
{
	if (!xz)
		return;

	cpu_wait_job(xz->job, true);
}


text:
layout: lab
number: 12
title:  "Compose with a Dockerfile"
---

### Goals
Integrate a Dockerfile with docker-compose.yml.

## Modify docker-compose.yml

In our last lab, we modified the PHP docker image so that it would have the
pdo_mysql module installed. Now, we want to use that modified version in the
Docker Compose setup we've been working on for our web server.

Modify docker-compose.yml. We want to replace `image: php:7.1-apache` with
`build: ./`. This tells Docker Compose to build the Dockerfile in the same
directory. When you're done, your file should look like this:

**docker-compose.yml**

```yaml
version: '3'

services:

  web:
    build: ./
    depends_on:
      - db
    volumes:
      - ./:/var/www/html
    ports:
      - "80:80"

  db:
    image: mysql:5.6
    environment:
      - MYSQL_ROOT_PASSWORD=password
      - MYSQL_DATABASE=SCHOOL
      - MYSQL_USER=my_user
      - MYSQL_PASSWORD=password
    volumes:
      - ./docker-entrypoint-initdb.d:/docker-entrypoint-initdb.d
    ports:
      - "3306:3306"
```

### Test it Out!

Now that we have a PHP container with the pdo_mysql module installed, we can
finally run our website. Run `docker-compose up` and visit
[http://localhost](http://localhost) in your browser. The web container is able
to query data from the db container and return it to the user!

redpajama_set_name: RedPajamaGithub


text:
package org.springframework.data.elasticsearch.core;

import java.util.LinkedList;

import org.elasticsearch.action.get.MultiGetResponse;

/**
 * @author Mohsin Husen
 */
public interface MultiGetResultMapper {

	<T> LinkedList<T> mapResults(MultiGetResponse responses, Class<T> clazz);
}


text:
package gui.util;

import java.io.File;
import java.io.FileFilter;
import java.util.Vector;

import util.StringUtil;

/**
 * Diese Klasse repraesentiert einen Dateifilter, mit dem alle Dateien unter
 * WorkSpacePath gefiltertet werden koennen, nur die Dateien mit den
 * erlaubten Endungen duerfen im Baum anzeigen.
 *
 * @author      Zhilei Ma
 * @version     1.0
 *
 */
public class ListFileFilter implements FileFilter {

	/* Use to store allowed extensions */
	private Vector<String> extensionVector = new Vector<String>();

    /**
     * Legt einen neuen Dateifilter und die erlaubte Endungen
     * wird nicht spezifiziert.
     *
     */
	public ListFileFilter() {
	}

    /**
     * Legt einen neuen Dateifilter und die erlaubte Endungen
     * wird gleichzeitig spezifiziert.
     *
     */
	public ListFileFilter(String fileExtension) {
		extensionVector.add(fileExtension);
	}

	/**
	 * ob die Datei eine erlaubte Endung besitzt
	 *
	 * @see java.io.FileFilter#accept(java.io.File)
	 */
	public boolean accept(File pathname) {
		if (pathname.isDirectory() && !(pathname.getName().startsWith("."))) {
			return true;
		}

		String extension = StringUtil.getExtension(pathname.getName());

		if (extension == null) {
			return false;
		}

		if (extensionVector.contains(extension.toLowerCase())) {
			return true;
		}

		return false;
	}

	/**
	 * Fuegt eine erlaubte Endung hinzu
	 */
	public void addExtension(String extension) {
		if (!extensionVector.contains(extension)) {
			extensionVector.add(extension);
		}
	}

}


text:
var pg = require('pg').native
var Native = require('../')

var warmup = function(fn, cb) {
  var count = 0;
  var max = 10;
  var run = function(err) {
    if(err) return cb(err);

    if(max >= count++) {
      return fn(run)
    }

    cb()
  }
  run();
}

var native = Native();
native.connectSync();

var queryText = 'SELECT generate_series(0, 1000)';
var client = new pg.Client();
client.connect(function() {
  var pure = function(cb) {
    client.query(queryText, function(err) {
      if(err) throw err;
      cb(err);
    });
  }
  var nativeQuery = function(cb) {
    native.query(queryText, function(err) {
      if(err) throw err;
      cb(err);
    });
  }

  var run = function() {
    var start = Date.now()
    warmup(pure, function() {
      console.log('pure done', Date.now() - start)
      start = Date.now()
      warmup(nativeQuery, function() {
        console.log('native done', Date.now() - start)
      })
    })
  }

  setInterval(function() {
    run()
  }, 500)

});


text:
.ui-tooltip {
	padding: 8px;
	position: absolute;
	z-index: 9999;
	max-width: 300px;
	-webkit-box-shadow: 0 0 5px #aaa;
	box-shadow: 0 0 5px #aaa;
}
/* Fades and background-images don't work well together in IE6, drop the image */
* html .ui-tooltip {
	background-image: none;
}
body .ui-tooltip { border-width: 2px; }


text:
import j0Assign from '../index.js';
import test from '../../tests.js';
test(j0Assign, ['Object', 'assign#j0']);


text:
<?xml version="1.0" ?>

<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">

    <parameters>
        <parameter key="simplethings_entityaudit.request.current_user_listener.class">SimpleThings\EntityAudit\Request\CurrentUserListener</parameter>
    </parameters>

    <services>
        <service id="simplethings_entityaudit.request.current_user_listener" class="%simplethings_entityaudit.request.current_user_listener.class%">
            <tag name="kernel.event_listener" event="kernel.request" method="handle" />
            <argument type="service" id="simplethings_entityaudit.config" />
            <argument type="service" id="security.context" on-invalid="NULL" />
        </service>
    </services>
</container>


text:
require "spec_helper"

describe Mongoid::Matchable::In do

  describe "#_matches\?" do

    context 'when the attribute is not nil' do

      let(:matcher) do
        described_class.new("first")
      end

      context "when the values include the attribute" do

        it "returns true" do
          expect(matcher._matches?("$in" => [/\Afir.*\z/, "second"])).to be true
        end
      end

      context "when the values don't include the attribute" do

        it "returns false" do
          expect(matcher._matches?("$in" => ["third"])).to be false
        end
      end
    end

    context 'when the attribute is nil' do

      let(:matcher) do
        described_class.new(nil)
      end

      context "when the values include the attribute" do

        it "returns true" do
          expect(matcher._matches?("$in" => [/\Afir.*\z/, nil])).to be true
        end
      end

      context "when the values don't include the attribute" do

        it "returns false" do
          expect(matcher._matches?("$in" => ["third"])).to be false
        end
      end
    end
  end
end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>PodamStringValue (podam 7.1.1-SNAPSHOT API)</title>
<meta name="date" content="2017-10-20">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Field |

Required |

Optional

Detail:

Field |

Element

uk.co.jemos.podam.common

Annotation Type PodamStringValue

@Documented
 @PodamAnnotation
 @Target(value={FIELD,PARAMETER})
 @Retention(value=RUNTIME)
public @interface PodamStringValue

Annotation used to customise string type attributes or constructor parameter.

 The strValue attribute takes precedence over length. If the
 former was specified the latter will be ignored.

Author:

mtedone

Optional Element Summary

Optional Elements

Modifier and Type
Optional Element and Description

String
comment

It allows clients to specify a comment on this annotation

int
length

The length of the String for the annotated attribute.

String
strValue

If specified, it allows clients to specify an exact value for the string

Element Detail

length

public abstract int length

The length of the String for the annotated attribute. It defaults to
 PodamConstants.STR_DEFAULT_LENGTH

Returns:

string length

Default:

10

strValue

public abstract String strValue

If specified, it allows clients to specify an exact value for the string

Returns:

string value

Default:

""

comment

public abstract String comment

It allows clients to specify a comment on this annotation

Returns:

comment value

Default:

""

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Jemos 2002 - 2014: All Rights Reserved. Podam runs under 						the MIT license

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Field |

Required |

Optional

Detail:

Field |

Element

Copyright © 2017. All rights reserved.


text:
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using Zenject;

namespace Alensia.Core.Physics
{
    public abstract class RayCastingGroundDetector<T> : GroundDetector, IFixedTickable
        where T : Collider
    {
        public override Collider Target => _target;

        [Inject] private T _target;

        protected virtual void DetectGround()
        {
            var hits = CastRay(CreateRay(), _target);
            var grounds = hits.Select(h => h.collider).Where(h => h != Target && IsGround(h));

            OnDetectGround(grounds);
        }

        protected abstract Vector3 CalculateOrigin(T target);

        protected virtual Ray CreateRay() => new Ray(CalculateOrigin(_target), Vector3.down);

        protected abstract IEnumerable<RaycastHit> CastRay(Ray ray, T target);

        public void FixedTick() => DetectGround();
    }
}


text:
namespace geometry {
namespace spatial {

SO3 form_coordinate_frame_from_zhat(const Unit3& zhat) {
  const SO3 z_from_zhat = rotation_to(zhat.vec(), jcc::Vec3::UnitZ());
  return z_from_zhat;
}

SO3 form_coordinate_frame_from_zhat_and_x(const Unit3& zhat, const jcc::Vec3& x_dir) {
  const Unit3 xhat = Unit3(x_dir - zhat.project(x_dir));
  const Unit3 yhat = zhat.unit_cross(xhat);

  Eigen::Matrix3d mat;
  mat.col(0) = xhat.vec();
  mat.col(1) = yhat.vec();
  mat.col(2) = zhat.vec();

  const Eigen::Quaterniond q_world_from_frame(mat);
  return SO3(q_world_from_frame);
}

}  // namespace spatial
}  // namespace geometry


text:
define("dojox/widget/_CalendarMonthYear", [
	"dojo/_base/declare",
	"./_CalendarMonthYearView"
], function(declare, _CalendarMonthYearView){
	return declare("dojox.widget._CalendarMonthYear", null, {
		// summary:
		//		Mixin class for adding a view listing all 12
		//		months of the year to the dojox/widget/_CalendarBase

		constructor: function(){
			// summary:
			//		Adds a dojox/widget/_CalendarMonthView view to the calendar widget.
			this._addView(_CalendarMonthYearView);
		}
	});
});


text:
package org.locationtech.spatial4j.shape.impl;

import org.locationtech.spatial4j.shape.Point;
import org.locationtech.spatial4j.shape.Rectangle;
import org.locationtech.spatial4j.shape.SpatialRelation;

import static org.locationtech.spatial4j.shape.SpatialRelation.*;

/**
 * INERNAL: A buffered line of infinite length.
 * Public for test access.
 */
public class InfBufLine {

  /** Error epsilon. */
  private static final double EPS = 10e-14;

  //TODO consider removing support for vertical line -- let caller
  // do something else.  BufferedLine could have a factory method
  // that returns a rectangle, for example.

  // line: y = slope * x + intercept

  private final double slope;//can be infinite for vertical line
  //if slope is infinite, this is x intercept, otherwise y intercept
  private final double intercept;

  private final double buf;

  private final double distDenomInv;//cached: 1 / Math.sqrt(slope * slope + 1)

  InfBufLine(double slope, Point point, double buf) {
    assert !Double.isNaN(slope);
    this.slope = slope;
    if (Double.isInfinite(slope)) {
      intercept = point.getX();
      distDenomInv = Double.NaN;
    } else {
      intercept = point.getY() - slope * point.getX();
      distDenomInv = 1 / Math.sqrt(slope * slope + 1);
    }
    this.buf = buf;
  }

  SpatialRelation relate(Rectangle r, Point prC, Point scratch) {
    assert r.getCenter().equals(prC);

    int cQuad = quadrant(prC);

    Point nearestP = scratch;
    cornerByQuadrant(r, oppositeQuad[cQuad], nearestP);
    boolean nearestContains = contains(nearestP);

    if (nearestContains) {
      Point farthestP = scratch;
      nearestP = null;//just to be safe (same scratch object)
      cornerByQuadrant(r, cQuad, farthestP);
      boolean farthestContains = contains(farthestP);
      if (farthestContains)
        return CONTAINS;
      return INTERSECTS;
    } else {// not nearestContains
      if (quadrant(nearestP) == cQuad)
        return DISJOINT;//out of buffer on same side as center
      return INTERSECTS;//nearest & farthest points straddle the line
    }
  }

  boolean contains(Point p) {
    return (distanceUnbuffered(p) <= buf + EPS);
  }

  /** INTERNAL AKA lineToPointDistance */
  public double distanceUnbuffered(Point c) {
    if (Double.isInfinite(slope))
      return Math.abs(c.getX() - intercept);
    // http://math.ucsd.edu/~wgarner/math4c/derivations/distance/distptline.htm
    double num = Math.abs(c.getY() - slope * c.getX() - intercept);
    return num * distDenomInv;
  }

//  /** Amount to add or subtract to intercept to indicate where the
//   * buffered line edges cross the y axis.
//   * @return
//   */
//  double interceptBuffOffset() {
//    if (Double.isInfinite(slope))
//      return slope;
//    if (buf == 0)
//      return 0;
//    double slopeDivBuf = slope / buf;
//    return Math.sqrt(buf*buf + slopeDivBuf*slopeDivBuf);
//  }

  /** INTERNAL: AKA lineToPointQuadrant */
  public int quadrant(Point c) {
    //check vertical line case 1st
    if (Double.isInfinite(slope)) {
      //when slope is infinite, intercept is x intercept instead of y
      return c.getX() > intercept ? 1 : 2; //4 : 3 would work too
    }
    //(below will work for slope==0 horizontal line too)
    //is c above or below the line
    double yAtCinLine = slope * c.getX() + intercept;
    boolean above = c.getY() >= yAtCinLine;
    if (slope > 0) {
      //if slope is a forward slash, then result is 2 | 4
      return above ? 2 : 4;
    } else {
      //if slope is a backward slash, then result is 1 | 3
      return above ? 1 : 3;
    }
  }

  //TODO ? Use an Enum for quadrant?

  /* quadrants 1-4: NE, NW, SW, SE. */
  private static final int[] oppositeQuad= {-1,3,4,1,2};

  public static void cornerByQuadrant(Rectangle r, int cornerQuad, Point out) {
    double x = (cornerQuad == 1 || cornerQuad == 4) ? r.getMaxX() : r.getMinX();
    double y = (cornerQuad == 1 || cornerQuad == 2) ? r.getMaxY() : r.getMinY();
    out.reset(x, y);
  }

  public double getSlope() {
    return slope;
  }

  public double getIntercept() {
    return intercept;
  }

  public double getBuf() {
    return buf;
  }

  /** 1 / Math.sqrt(slope * slope + 1) */
  public double getDistDenomInv() {
    return distDenomInv;
  }

  @Override
  public String toString() {
    return "InfBufLine{" +
        "buf=" + buf +
        ", intercept=" + intercept +
        ", slope=" + slope +
        '}';
  }
}


text:
package com.github.aselab.activerecord.samples

import com.github.aselab.activerecord._
import com.github.aselab.activerecord.dsl._
import java.util.UUID

// TODO: support user managed id and immutability
abstract class UUIDRecord extends ActiveRecordBase[UUID] {
  var id: UUID = UUIDRecord.initialValue
  def isPersisted: Boolean = id != UUIDRecord.initialValue

  override def beforeCreate() {
    id = UUID.randomUUID
  }
}

object UUIDRecord {
  val initialValue = new UUID(0, 0)
}

case class UUIDModel(var value: String) extends UUIDRecord

object UUIDModel extends ActiveRecordBaseCompanion[UUID, UUIDModel]

object PrimaryKeyTables extends ActiveRecordTables {
  val uuidModels = table[UUIDModel]
}

object PrimaryKeySpec extends ActiveRecordSpecification {
  override def schema = PrimaryKeyTables

  "primary key type" should {
    "uuid" >> {
      val m = UUIDModel("value").create
      m.value = "test"
      m.save must beTrue
      UUIDModel.where(_.value === m.value).toList mustEqual List(m)
    }
  }
}


text:
module ContentVector (ContentVector,
                      isContentVector,
                      StandardTableaux,
                      isStandardTableaux,
                      printStandardTableaux,
                      standardToContent,
                      contentToStandard,
                      isDecreasing,
                      transposePartition,
                      transformTableaux) where

import Data.List (transpose)
import Text.PrettyPrint
import Control.Monad (join)
import Data.List (sort, sortBy)
import GHC.Exts (sortWith, groupWith)

type ContentVector = [Int]

-- there is probably a better way to test validity of a content vector
isContentVector :: ContentVector -> Bool
isContentVector [] = True
isContentVector [n] = if n == 0 then True else False
isContentVector list =    isContentVector ns
                       && ((elem (n-1) ns) || (elem (n+1) ns))
                       && if (elem n ns) then (elem (n-1) interval) && (elem (n+1) interval) else True
    where n  = last list
          ns = init list
          interval = takeWhile (/= n) (reverse ns)

type StandardTableaux = [[Int]]

-- test whether a list is a chain with respect to a total order
isChain :: (Ord a) => (a -> a -> Bool) -> [a] -> Bool
isChain _ [] = True
isChain _ [x] = True
isChain f l@(x:xs) = and [f p q | (p,q) <- zip l xs]

isIncreasing         :: (Ord a) => [a] -> Bool
isStrictlyIncreasing :: (Ord a) => [a] -> Bool
isDecreasing         :: (Ord a) => [a] -> Bool
isStrictlyDecreasing :: (Ord a) => [a] -> Bool

isIncreasing = isChain (<=)
isStrictlyIncreasing = isChain (<)
isDecreasing = isChain (\x y -> not (x < y))
isStrictlyDecreasing = isChain (>)

isStandardTableaux :: StandardTableaux -> Bool
isStandardTableaux [] = True
isStandardTableaux t =    (isDecreasing $ length <$> t)
                       && (and $ isStrictlyIncreasing <$> t)
                       && (and $ isStrictlyIncreasing <$> (transpose t))
                       && sort (join t) == [1..(length $ join t)]

-- safe maximum
maximum' :: [Int] -> Int
maximum' l = case l of [] -> 0
                       l  -> maximum l

-- when printing tableaux, you sometimes need to pad the strings
pad :: [[String]] -> [[String]]
pad t = (fmap . fmap) p t
    where m = maximum' $ maximum' <$> (fmap . fmap) length t
          p :: String -> String
          p s = take m (s ++ (repeat ' '))

printStandardTableaux :: StandardTableaux -> Doc
printStandardTableaux t = vcat $ hsep <$> t'
    where t' = (fmap . fmap) text $ pad $ (fmap . fmap) show t

matrixZip :: [[a]] -> [[b]] -> [[(a,b)]]
matrixZip x y = (uncurry zip) <$> zip x y

contents :: [[Int]]
contents = [ (subtract j) <$> [0..] | j <- [0..] ]
    where subtract j x = x - j

standardToContent :: StandardTableaux -> ContentVector
standardToContent t = snd <$> (sortWith fst $ join $ matrixZip t contents)

-- there is probably a better way to convert content vectors to standard tableaux
contentToStandard :: ContentVector -> StandardTableaux
contentToStandard c = foldl addDiagonal [] $ f <$> sortWith fst <$> (groupWith snd $ zip [1..] c)
    where f :: [(a,Int)] -> ([a],Int)
          f l = (fst <$> l, snd $ head l)
          addDiagonal :: [[a]] -> ([a],Int) -> [[a]]
          addDiagonal m (x:xs,n)
              | n <= 0 = [x] : (  uncurry (++) <$> zip m ((fmap return xs) ++ (repeat []))  )
              | n > 0  = uncurry (++) <$> zip m ( (fmap return (x:xs)) ++ (repeat []) )

--transposing partitions
transposePartition :: [Int] -> [Int]
transposePartition p = length <$> (transpose $ take' <$> p)
    where take' n = take n (repeat ())

--transforming tableaux
transformTableaux :: Int -> StandardTableaux -> StandardTableaux
transformTableaux n t = if (b == a + 1) || (b == a - 1) then t else contentToStandard (as ++ [b,a] ++ bs)
    where c = standardToContent t
          (p,q) = splitAt n c
          a = last p
          as = init p
          b = head q
          bs = tail q


text:
<?php
    namespace Thin;

    class Apifb
    {
        private $entity;
        private $token;
        private $dbs = array();

        public function __construct($entity, $login, $password, $factory = 'Memorydb')
        {
            $this->dbs['entity']    = new $factory($entity);
            $this->dbs['user']      = new $factory('api_db_user');
            $this->dbs['right']     = new $factory('api_db_right');

            $user = $this->dbs['user']->where("login = $login")->where("password = " . sha1($password))->exec();
            if (count($user)) {

            }
        }
    }


text:
<!DOCTYPE html>

  <title>Citizenship Test | Tim Thoughts</title>

  <meta charset="UTF-8">
  <meta name="language" content="en">
  <meta name="description" content="">
  <meta name="keywords" content="">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">

  <meta name="twitter:card" content="summary" />
  <meta name="twitter:title" content="Citizenship Test" />
  <meta name="twitter:description" content=""
  />
  <meta name="twitter:site" content="@https://twitter.com/timothy_phan" />
  <meta name="twitter:creator" content="@https://twitter.com/timothy_phan" />

  <link rel="shortcut icon" type="image/png" href="/favicon.ico" />

    <link rel="stylesheet" href="/css/post.min.679ea46872c2b319c5ae942c601a7330924fd57451c89d621d6cb129c870c2a8.css" integrity="sha256-Z56kaHLCsxnFrpQsYBpzMJJP1XRRyJ1iHWyxKchwwqg="/>

    <link rel="stylesheet" href="/css/custom.min.e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855.css" integrity="sha256-47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU="/>

        bio

        blog

        home

Citizenship Test

            <time datetime="0001-01-01 00:00:00 +0000 UTC" class="post__date"
            >Jan 1 0001</time>

What do you mean, I failed the test?

I'm sorry President Trump, but this is the last attempt. You forgot what the 3rd Amendment was. AirBnB cannot give veterans a free pass, they sued, remember?

You can't revoke my citizenship again! I was elected President in a landslide! I even manned the wall when the Mexicans came back for Texas, you ungrateful son of a bitch.

I'm sorry, I'm just following orders. You'll have to report to the DMV within 3 weeks for your reclassification exam, just like the rest of us.

Don't I get immunity from this? The amendment was meant to apply only to children of illegal immigrants, not current citizens. I distinctively remembered telling Speaker Cruz to add that to the bill.

No, the Supreme Court decided to expand the program. Chief Justice Ginsberg is still pissed about your weekly comments about her retirement. I really think you're making it worse.

Never mind her, do you know what they'll have me do? I heard Walker had to attend city council meetings for a year. Maybe I can read the Art of the Deal to inner city school children like I did last year.

Sorry, they've informed me they've got something different planned for you this year. You're not going to like it…

(3 weeks later)

Hello my fellow Americans, or should I say, ex-Americans. Before I begin, I'd like to go on record saying that I had only intended to end the culture of entitlement of illegals in this country. Citizenship is something you must earn, being an American is more than being born here!

(Univision camera lights up)

Hace ocho décadas y siete años, nuestros padres hicieron nacer en este continente una nueva nación…

      Next Post
      hello world

© {2020}


text:
<?php

namespace DynamicTableTest;

use PHPUnit_Framework_TestCase;
use DynamicTable\Table;
use DynamicTable\Adapter\DoctrineMongoODMAdapter;
use DynamicTableTest\Document\Sample as SampleDocument;

class OdmQueryMock {
    protected $cursor;

    public function __construct($cursor) {
        $this->cursor = $cursor;
    }

    public function execute() {
        return $this->cursor;
    }
}

class DoctrineMongoODMAdapterTest extends PHPUnit_Framework_TestCase
{
    public function setUp()
    {
        parent::setUp();

        $this->dm = $this->getMockBuilder('Doctrine\ODM\MongoDB\DocumentManager')
                         ->disableOriginalConstructor()
                         ->setMethods([ 'createQueryBuilder', 'getDocumentCollection', 'getClassMetadata' ])
                         ->getMock();

        $this->dm->expects($this->any())
                 ->method('getClassMetadata')
                 ->will($this->returnCallback(function ($name) {
                    return new \Doctrine\ODM\MongoDB\Mapping\ClassMetadata($name);
                 }));

        $this->qb = $this->getMockBuilder('Doctrine\ODM\MongoDB\Query\Builder')
                         ->setConstructorArgs([ $this->dm, 'DynamicTableTest\Document\Sample' ])
                         ->setMethods([ 'expr', 'getQuery', 'sort' ])
                         ->getMock();

        $this->dm->expects($this->any())
                 ->method('createQueryBuilder')
                 ->will($this->returnValue($this->qb));

        $this->expr = $this->getMockBuilder('Doctrine\ODM\MongoDB\Query\Expr')
                           ->setConstructorArgs([ $this->dm ])
                           ->setMethods([ 'getQuery', 'equals', 'range', 'gte', 'lte', 'exists' ])
                           ->getMock();

        $this->qb->expects($this->any())
                 ->method('expr')
                 ->will($this->returnValue($this->expr));

        $this->cursor = $this->getMockBuilder('Doctrine\ODM\MongoDB\Cursor')
                             ->disableOriginalConstructor()
                             ->setMethods([ 'valid', 'count', 'current', 'getMongoCursor', 'skip', 'limit' ])
                             ->getMock();

        $this->mongoCursor = $this->getMockBuilder('MongoCursor')
                                  ->disableOriginalConstructor()
                                  ->getMock();

        $this->cursor->expects($this->any())
                     ->method('getMongoCursor')
                     ->will($this->returnValue($this->mongoCursor));

        $this->qb->expects($this->any())
                 ->method('getQuery')
                 ->will($this->returnValue(new OdmQueryMock($this->cursor)));

        $this->adapter = new DoctrineMongoODMAdapter();
        $this->adapter->setQueryBuilder($this->qb);

        $this->table = new Table();
        $this->table->setAdapter($this->adapter);
        $this->table->setColumns([
            'id' => [
                'title'         => 'ID',
                'field_name'    => 'id',
                'type'          => Table::TYPE_STRING,
                'filters'       => [ Table::FILTER_EQUAL, Table::FILTER_BETWEEN, Table::FILTER_NULL ],
                'sortable'      => true,
                'visible'       => false,
            ],
            'string' => [
                'title'         => 'String',
                'field_name'    => 'value_string',
                'type'          => Table::TYPE_STRING,
                'filters'       => [ Table::FILTER_EQUAL, Table::FILTER_LIKE, Table::FILTER_NULL ],
                'sortable'      => true,
                'visible'       => true,
            ],
            'integer' => [
                'title'         => 'Integer',
                'field_name'    => 'value_integer',
                'type'          => Table::TYPE_INTEGER,
                'filters'       => [ Table::FILTER_EQUAL, Table::FILTER_BETWEEN, Table::FILTER_NULL ],
                'sortable'      => true,
                'visible'       => true,
            ],
            'float' => [
                'title'         => 'Float',
                'field_name'    => 'value_float',
                'type'          => Table::TYPE_FLOAT,
                'filters'       => [ Table::FILTER_EQUAL, Table::FILTER_BETWEEN, Table::FILTER_NULL ],
                'sortable'      => true,
                'visible'       => true,
            ],
            'boolean' => [
                'title'         => 'Boolean',
                'field_name'    => 'value_boolean',
                'type'          => Table::TYPE_BOOLEAN,
                'filters'       => [ Table::FILTER_EQUAL, Table::FILTER_NULL ],
                'sortable'      => true,
                'visible'       => true,
            ],
            'datetime' => [
                'title'         => 'DateTime',
                'field_name'    => 'value_datetime',
                'type'          => Table::TYPE_DATETIME,
                'filters'       => [ Table::FILTER_EQUAL, Table::FILTER_BETWEEN, Table::FILTER_NULL ],
                'sortable'      => true,
                'visible'       => true,
            ],
        ]);
        $this->table->setMapper(function ($row) {
            $datetime = $row->getValueDatetime();
            if ($datetime !== null)
                $datetime = $datetime->getTimestamp();

            return [
                'id'        => $row->getId(),
                'string'    => $row->getValueString(),
                'integer'   => $row->getValueInteger(),
                'float'     => $row->getValueFloat(),
                'boolean'   => $row->getValueBoolean(),
                'datetime'  => $datetime,
            ];
        });
    }

    public function testCheck()
    {
        try {
            $this->adapter->check($this->table);
        } catch (\Exception $e) {
            $this->fail('check() failed on valid data');
        }
    }

    public function testSort()
    {
        $resultColumn = null;
        $resultDir = null;
        $this->qb->expects($this->any())
                 ->method('sort')
                 ->will($this->returnCallback(function ($column, $dir) use (&$resultColumn, &$resultDir) {
                    $resultColumn = $column;
                    $resultDir = $dir;
                }));

        $this->table->setSortColumn('id');
        $this->table->setSortDir(Table::DIR_ASC);

        $this->adapter->sort($this->table);

        $this->assertEquals('id', $resultColumn, "Incorrect sort column was set");
        $this->assertEquals(Table::DIR_ASC, $resultDir, "Incorrect sort direction was set");

        $this->table->setSortDir(Table::DIR_DESC);

        $this->adapter->sort($this->table);

        $this->assertEquals('id', $resultColumn, "Incorrect sort column was set");
        $this->assertEquals(Table::DIR_DESC, $resultDir, "Incorrect sort direction was set");
    }

    public function testFilter()
    {
        $this->table->setFilters([
            'string' => [
                Table::FILTER_EQUAL => 'foo',
                Table::FILTER_LIKE => 'bar',
                Table::FILTER_NULL => true
            ],
            'integer' => [
                Table::FILTER_EQUAL => "42",
                Table::FILTER_BETWEEN => [ "10", "20" ],
                Table::FILTER_NULL => true
            ],
            'boolean' => [
                Table::FILTER_EQUAL => false,
                Table::FILTER_NULL => true
            ],
            'datetime' => [
                Table::FILTER_EQUAL => 100000,
                Table::FILTER_BETWEEN => [ 1000000, 2000000 ],
                Table::FILTER_NULL => true
            ]
        ]);

        $this->adapter->filter($this->table);

        $reflection = new \ReflectionClass(get_class($this->adapter));
        $property = $reflection->getProperty('andOps');
        $property->setAccessible(true);
        $andOps = $property->getValue($this->adapter);

        $string = $andOps['value_string'];
        $this->assertEquals('equals', $string[0]['operator'], "Prepared andOps are invalid");
        $this->assertEquals('foo', $string[0]['value'], "Prepared andOps are invalid");
        $this->assertEquals('equals', $string[1]['operator'], "Prepared andOps are invalid");
        $this->assertEquals(true, $string[1]['value'] instanceof \MongoRegex, "Prepared andOps are invalid");
        $this->assertEquals('exists', $string[2]['operator'], "Prepared andOps are invalid");
        $this->assertEquals(false, $string[2]['value'], "Prepared andOps are invalid");

        $integer = $andOps['value_integer'];
        $this->assertEquals('equals', $integer[0]['operator'], "Prepared andOps are invalid");
        $this->assertEquals(42, $integer[0]['value'], "Prepared andOps are invalid");
        $this->assertEquals('range', $integer[1]['operator'], "Prepared andOps are invalid");
        $this->assertEquals(10, $integer[1]['value1'], "Prepared andOps are invalid");
        $this->assertEquals(20, $integer[1]['value2'], "Prepared andOps are invalid");
        $this->assertEquals('exists', $integer[2]['operator'], "Prepared andOps are invalid");
        $this->assertEquals(false, $integer[2]['value'], "Prepared andOps are invalid");

        $boolean = $andOps['value_boolean'];
        $this->assertEquals('equals', $boolean[0]['operator'], "Prepared andOps are invalid");
        $this->assertEquals(false, $boolean[0]['value'], "Prepared andOps are invalid");
        $this->assertEquals('exists', $boolean[1]['operator'], "Prepared andOps are invalid");
        $this->assertEquals(false, $boolean[1]['value'], "Prepared andOps are invalid");

        $datetime = $andOps['value_datetime'];
        $this->assertEquals('equals', $datetime[0]['operator'], "Prepared andOps are invalid");
        $this->assertEquals(true, $datetime[0]['value'] instanceof \MongoDate, "Prepared andOps are invalid");
        $this->assertEquals('range', $datetime[1]['operator'], "Prepared andOps are invalid");
        $this->assertEquals(true, $datetime[1]['value1'] instanceof \MongoDate, "Prepared andOps are invalid");
        $this->assertEquals(true, $datetime[1]['value2'] instanceof \MongoDate, "Prepared andOps are invalid");
        $this->assertEquals('exists', $datetime[2]['operator'], "Prepared andOps are invalid");
        $this->assertEquals(false, $datetime[2]['value'], "Prepared andOps are invalid");
    }

    public function testPaginate()
    {
        $fixture = [];
        for ($i = 0; $i < 10; $i++) {
            $doc = new SampleDocument();
            $doc->setValueInteger(rand(0, 100));
            $fixture[] = $doc;
        }

        $i = 0; $count = count($fixture);
        $this->cursor->expects($this->any())
                     ->method('valid')
                     ->will($this->returnCallback(function () use (&$i, $count) {
                        return $i < $count;
                     }));

        $this->cursor->expects($this->any())
                     ->method('count')
                     ->will($this->returnValue($count));

        $this->cursor->expects($this->any())
                     ->method('current')
                     ->will($this->returnCallback(function () use (&$i, $fixture) {
                        return $fixture[$i++];
                     }));

        $passedSkip = null;
        $this->cursor->expects($this->any())
                     ->method('skip')
                     ->will($this->returnCallback(function ($skip) use (&$passedSkip) {
                        $passedSkip = $skip;
                     }));

        $passedLimit = null;
        $this->cursor->expects($this->any())
                     ->method('limit')
                     ->will($this->returnCallback(function ($limit) use (&$passedLimit) {
                        $passedLimit = $limit;
                     }));

        $this->table->setPageSize(2);
        $this->table->setPageNumber(3);

        $data = $this->adapter->paginate($this->table);

        $this->assertEquals(5, $this->table->getTotalPages(), "There should be 5 pages");
        $this->assertEquals(2 * 2, $passedSkip, "Number of skipped docs is wrong");
        $this->assertEquals(2, $passedLimit, "Limit of return docs is wrong");

        for ($i = 0; $i < count($fixture); $i++)
            $this->assertEquals($fixture[$i]->getValueInteger(), $data[$i]['integer'], "Returned data is wrong");
    }
}


text:
package seedu.Tdoo.model.task;

import java.util.Comparator;

import seedu.Tdoo.commons.util.CollectionUtil;
import seedu.Tdoo.model.task.attributes.EndDate;
import seedu.Tdoo.model.task.attributes.Name;
import seedu.Tdoo.model.task.attributes.Priority;
import seedu.Tdoo.model.task.attributes.StartDate;

/**
 * Represents a task in the TodoList. Guarantees: details are present and not
 * null, field values are validated.
 */
public class Todo extends Task implements ReadOnlyTask, Comparable<Todo> {

	private StartDate startDate;
	private EndDate endDate;
	private Priority priority;

	/**
	 * Every field must be present and not null.
	 *
	 * @param date
	 */
	public Todo(Name name, StartDate startDate, EndDate endDate, Priority priority, String isDone) {
		assert !CollectionUtil.isAnyNull(name, startDate, endDate, priority);
		super.name = name;
		this.startDate = startDate;
		this.endDate = endDate;
		this.priority = priority;
		this.isDone = isDone;
	}

	/**
	 * Copy constructor.
	 */
	public Todo(Todo source) {
		this(source.getName(), source.getStartDate(), source.getEndDate(), source.getPriority(), source.getDone());
	}

	public StartDate getStartDate() {
		return startDate;
	}

	public EndDate getEndDate() {
		return endDate;
	}

	public Priority getPriority() {
		return priority;
	}

	public Todo(ReadOnlyTask source) {
		this((Todo) source);
	};

	@Override
	public boolean equals(Object other) {
		return other == this // short circuit if same object
				|| (other instanceof Todo // instanceof handles nulls
						&& super.name.equals(((Todo) other).getName()))
						&& this.startDate.equals(((Todo) other).getStartDate())
						&& this.endDate.equals(((Todo) other).getEndDate())
						&& this.priority.equals(((Todo) other).getPriority());
	}

	@Override
	public String toString() {
		final StringBuilder builder = new StringBuilder();
		builder.append(getName()).append("\nPriority: ").append(getPriority());
		return builder.toString();
	}

	public Todo getTodo() {
		// TODO Auto-generated method stub
		return null;
	}

	//@@author A0144061U
		@Override
		public int compareTo(Todo other) {
			Integer thisInt = new Integer(0);
			Integer otherInt = new Integer(0);
			switch (this.priority.toString()) {
			case "HIGH": thisInt = 1; break;
			case "MEDIUM": thisInt = 2; break;
			case "LOW": thisInt = 3; break;
			}
			switch (other.getPriority().toString()) {
			case "HIGH": otherInt = 1; break;
			case "MEDIUM": otherInt = 2; break;
			case "LOW": otherInt = 3; break;
			}
			return thisInt.compareTo(otherInt);
		}
}

class TodoComparator implements Comparator<Task> {
	@Override
	public int compare(Task first, Task second) {
		Todo f = (Todo) first;
		Todo s = (Todo) second;
		return f.compareTo(s);
	}
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Syll. fung. (Abellini) 3: 338 (1884)

#### Original name
Sphaeria spurca Wallr.

### Remarks
null


text:
#ifndef ZEPHIR_KERNEL_VARIABLES_H
#define ZEPHIR_KERNEL_VARIABLES_H

#include <php.h>
#include <Zend/zend.h>

void zephir_var_dump(zval *var);

void zephir_var_export(zval *var);
void zephir_var_export_ex(zval *return_value, zval *var);

void zephir_get_defined_vars(zval *return_value);

#endif


text:
$LOAD_PATH.unshift "#{File.dirname(__FILE__)}/../lib"
require 'test/unit'
require "ninja2k"


text:
package shinro;

/**
 * Data structure and methods to represent a row and column pair (a grid position)
 *

 * The structure is comprised of two integer values.
 * @author Joseph Eib
 * @since December, 2014
 */
public class GridPos {
	private int row, col;

	/**
	 * Creates a new GridPos object
	 *

	 * The row and column are initialized to zero
	 */
	public GridPos() {
		this.row = this.col = 0;
	}

	/**
	 * Created a new GridPos object with specified row and column values
	 * @param row  the desired row
	 * @param col  the desired column
	 */
	public GridPos(int row, int col) {
		this.row = row;
		this.col = col;
	}

	/**
	 * Gets the value of this GridPos's row
	 * @return this GridPos's row value
	 */
	public int getRow() {
		return row;
	}

	/**
	 * Sets the value of this GridPos's row
	 * @param row  the desired new row value
	 */
	public void setRow(int row) {
		this.row = row;
	}

	/**
	 * Gets the value of this GridPos's column
	 * @return this GridPos's column value
	 */
	public int getCol() {
		return col;
	}

	/**
	 * Sets the value of this GridPos's row
	 * @param col  the desired new column value
	 */
	public void setCol(int col) {
		this.col = col;
	}

	/* In the format "(row, col)"
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		return "(" + row + ", " + col + ")";
	}

	/* (non-Javadoc)
	 * @see java.lang.Object#hashCode()
	 */
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + col;
		result = prime * result + row;
		return result;
	}

	/* (non-Javadoc)
	 * @see java.lang.Object#equals(java.lang.Object)
	 */
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (!(obj instanceof GridPos))
			return false;
		GridPos other = (GridPos) obj;
		if (col != other.col)
			return false;
		if (row != other.row)
			return false;
		return true;
	}

}


text:
external help file: Microsoft.Azure.Commands.Network.dll-Help.xml
Module Name: AzureRM.Network
ms.assetid: 2C603E0E-A19F-4EA6-B918-945007BE22FF
online version:
schema: 2.0.0
---

# Get-AzureRmExpressRouteCircuitRouteTableSummary

## SYNOPSIS
Gets a route table summary of an ExpressRoute circuit.

## SYNTAX

```
Get-AzureRmExpressRouteCircuitRouteTableSummary -ResourceGroupName <String> -ExpressRouteCircuitName <String>
 [-PeeringType <String>] -DevicePath <DevicePathEnum> [<CommonParameters>]
```

## DESCRIPTION
The **Get-AzureRmExpressRouteCircuitRouteTableSummary** cmdlet retrieves a summary of BGP neighbor
information for a particular routing context. This information is useful to determine for how long
a routing context has been established and the number of route prefixes advertised by the peering
router.

## EXAMPLES

### Example 1: Display the route summary for the primary path
```
Get-AzureRmExpressRouteCircuitRouteTableSummary -ResourceGroupName $RG -ExpressRouteCircuitName $CircuitName -DevicePath 'Primary'
```

## PARAMETERS

### -DevicePath
The acceptable values for this parameter are: `Primary` or `Secondary`

```yaml
Type: DevicePathEnum
Parameter Sets: (All)
Aliases:
Accepted values: Primary, Secondary

Required: True
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -ExpressRouteCircuitName
The name of the ExpressRoute circuit being examined.

```yaml
Type: String
Parameter Sets: (All)
Aliases: Name, ResourceName

Required: True
Position: Named
Default value: None
Accept pipeline input: True (ByPropertyName)
Accept wildcard characters: False
```

### -PeeringType
The acceptable values for this parameter are: `AzurePrivatePeering`, `AzurePublicPeering`, and
`MicrosoftPeering`

```yaml
Type: String
Parameter Sets: (All)
Aliases:
Accepted values: AzurePrivatePeering, AzurePublicPeering, MicrosoftPeering

Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -ResourceGroupName
The name of the resource group containing the ExpressRoute circuit.

```yaml
Type: String
Parameter Sets: (All)
Aliases:

Required: True
Position: Named
Default value: None
Accept pipeline input: True (ByPropertyName)
Accept wildcard characters: False
```

### CommonParameters
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see about_CommonParameters (http://go.microsoft.com/fwlink/?LinkID=113216).

## INPUTS

## OUTPUTS

### Microsoft.Azure.Commands.Network.Models.PSExpressRouteCircuitRoutesTableSummary

## NOTES

## RELATED LINKS

[Get-AzureRmExpressRouteCircuitARPTable](Get-AzureRmExpressRouteCircuitARPTable.md)

[Get-AzureRmExpressRouteCircuitRouteTable](Get-AzureRmExpressRouteCircuitRouteTable.md)

[Get-AzureRmExpressRouteCircuitStats](Get-AzureRmExpressRouteCircuitStats.md)


text:
from selenium import webdriver
#from lxml import html

#existing tag: J-347-3553-E
URL = "https://3ds.pokemon-gl.com/user/%s/secretbase"

#tag: slovo, 3 broja, 4 broja, slovo

def get_picture_url(tr_elements):
	for tr_element in tr_elements:
		for th_element in tr_element.find_elements_by_xpath('.//th'):
			print th_element.text
		if tr_element.find_elements_by_xpath('.//th')[0].text == 'QR Code':
			return tr_element.find_elements_by_xpath('.//img')[0].get_attribute('src')

def get_tag(i, j, k, l):
	return '%s-%s-%s-%s' % (i, j, k, l)

def get_location(tr_elements):
	for tr_element in tr_elements:
		for th_element in tr_element.find_elements_by_xpath('.//th'):
			print th_element.text
		if tr_element.find_elements_by_xpath('.//th')[0].text == 'Location':
			return tr_element.find_elements_by_xpath('.//p')[0].text

def write_to_file(file, tag, location, url):
	if tag:
		if location:
			if url:
				file.write('%s,%s,%s\n' % (tag, location, url))

#from pyvirtualdisplay import Display
#display = Display(visible=0, size=(800, 600))
#display.start()

profile = webdriver.FirefoxProfile()
profile.native_events_enabled = False
driver = webdriver.Firefox(profile)
out_file = open("secret_bases.csv", "a")

for i in xrange(ord('A'), ord('Z')+1):
	for j in xrange (0, 1000):
		for k in xrange (0, 10000):
			for l in xrange(ord('A'), ord('Z')+1):
				tag = "%s-%03d-%04d-%s" % (chr(i), j, k, chr(l))
				url = URL % (tag)
				print "Working on url: %s" % (url)
				driver.get(url)
				tr_elements = driver.find_elements_by_xpath('//tr')

				location = get_location(tr_elements)
				picture_url = get_picture_url(tr_elements)
				write_to_file(out_file, tag, location, picture_url)

out_file.close()
driver.quit()
#display.stop()


text:
package com.tc.utils;

import java.util.Date;
import java.util.concurrent.TimeUnit;

public class StopWatch {

	private Date start;
	private Date end;
	private String label;

	public StopWatch(){
		this.start();
	}

	public StopWatch(String label){
		this.label = label;
		this.start();
	}

	public void start(){
		start = new Date();
	}

	public void end(){
		end = new Date();
	}

	public long elapsedSeconds(){
		return this.elapsedTime(TimeUnit.SECONDS);
	}

	public long elapsedMilli(){
		return this.elapsedTime(TimeUnit.MILLISECONDS);
	}

	public long elapsedMin(){
		return this.elapsedTime(TimeUnit.MINUTES);
	}

	public long elapsedTime(TimeUnit timeUnit){

		if(end==null) this.end();

		long elapsed = 0;

		if(TimeUnit.MILLISECONDS.equals(timeUnit)){
			elapsed =DateUtils.getTimeDiffMiliSec(start, end);

		}else if(TimeUnit.SECONDS.equals(timeUnit)){
			elapsed = DateUtils.getTimeDiffSec(start, end);

		}else if(TimeUnit.MINUTES.equals(timeUnit)){
			elapsed = DateUtils.getTimeDiffMin(start, end);
		}

		return elapsed;
	}

	public void print(TimeUnit timeUnit, long max){
		long time = this.elapsedTime(timeUnit);
		if(time >=max){
			System.out.println(this.label + " in " + this.elapsedTime(timeUnit) + " " + timeUnit.name());
		}
	}

}


text:
package org.webchecker.watcher;

import java.util.function.BiConsumer;

/**
 * Class represents a configuration of a listener. It contains only one parameter yet, but can be
 * easily extend. There is no rule of number of listeners to one config, but one listener have to have
 * exact one config.
 *
 * @author Matěj Kripner <kripnermatej@gmail.com>
 * @version 1.0
 * @see Listener
 */
public class ListenerConfig {

    /**
     * Min value of auto checking delay. Has to be positive.
     */
    public static final int MIN_AUTO_CHECKING = 25;

    /* Represents the preferred delay between two listening of the listener. If the value is 0,
       listening should not be automatic and auto checking is off. */
    private int autoChecking;

    // This function will be called when change of #autoChecking parameter occurs.
    private BiConsumer<Integer, Integer> onAutoCheckingChange;

    // Constructor that sets this config to the default state.
    private ListenerConfig() {
        setToDefault();
    }

    // Sets this config to the default state.
    private void setToDefault() {
        autoChecking = 0;
    }

    /**
     * Returns new config in the default state.
     *
     * @return new config in the default state
     */
    public static ListenerConfig getDefaults() {
        return new ListenerConfig();
    }

    /**
     * Turn auto checking on with the given delay.
     *

     * The given delay has to be valid. In fact, delay is valid when:
     * {@code
     * delay >= {@link #MIN_AUTO_CHECKING}
     * }
     *
     * @param delay the new value of delay between two listening of a listener
     * @return this
     * @throws IllegalArgumentException if validation of the given delay fails
     * @see #validateDelay(int)
     */
    public ListenerConfig autoCheckingOn(int delay) throws IllegalArgumentException {
        validateDelay(delay);
        autoChecking = delay;
        runOnAutoCheckingChange(0, delay);
        return this;
    }

    /**
     * Checks that the given delay is valid.
     *

     * In fact, delay is valid when:

     * {@code
     * delay >= {@link #MIN_AUTO_CHECKING}
     * }
     *
     * @param delay the value to check
     * @throws IllegalArgumentException if value of the given delay is not valid
     */
    private void validateDelay(int delay) throws IllegalArgumentException {
        if (delay < MIN_AUTO_CHECKING)
            throw new IllegalArgumentException("delay can not be less than " + MIN_AUTO_CHECKING + ", but was " + delay);
    }

    /**
     * Turn the auto checking off.
     *
     * @return this
     */
    public ListenerConfig autoCheckingOff() {
        int tmp = autoChecking;
        autoChecking = 0;
        runOnAutoCheckingChange(tmp, 0);
        return this;
    }

    /**
     * Is not {@code null}, run auto checking change function.
     *
     * @param oldValue old value of auto checking
     * @param newValue new value of auto checking
     */
    private void runOnAutoCheckingChange(int oldValue, int newValue) {
        if (onAutoCheckingChange != null) onAutoCheckingChange.accept(oldValue, newValue);
    }

    /**
     * Simply return value of auto checking attribute. If auto checking is off, return zero.
     *
     * @return value of auto checking attribute
     */
    public int getAutoChecking() {
        return autoChecking;
    }

    /**
     * Tests that auto checking is on.
     *
     * @return auto checking is on
     */
    public boolean isAutoCheckingOn() {
        return getAutoChecking() != 0;
    }

    /**
     * Simple sets the value of auto checking change function attribute to given value.
     *
     * @param onAutoCheckingChange new value of auto checking change function attribute
     */
    public void setOnAutoCheckingChange(BiConsumer<Integer, Integer> onAutoCheckingChange) {
        this.onAutoCheckingChange = onAutoCheckingChange;
    }
}


text:
package org.dcm4chex.archive.ejb.conf;

import java.util.ArrayList;
import java.util.Arrays;

import javax.xml.parsers.SAXParserFactory;

import org.dcm4che.dict.Tags;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

/**
 *
 * @author gunter.zeilinger@tiani.com
 * @version $Revision: 1066 $ $Date: 2004-03-23 07:26:15 +0800 (周二, 23 3月 2004) $
 * @since 28.12.2003
 */
public final class AttributeFilter {

    private int[] patientFilter;
    private int[] studyFilter;
    private int[] seriesFilter;
    private int[] instanceFilter;

    private class MyHandler extends DefaultHandler {
        private ArrayList list = new ArrayList();

        public void startElement(
            String uri,
            String localName,
            String qName,
            Attributes attributes)
            throws SAXException {
            if (qName.equals("attr")) {
                list.add(attributes.getValue("tag"));
            }
        }

        private int[] tags() {
            int[] array = new int[list.size()];
            for (int i = 0; i < array.length; i++) {
	            array[i] = Tags.valueOf((String) list.get(i));
            }
            Arrays.sort(array);
            list.clear();
            return array;
        }

        public void endElement(String uri, String localName, String qName)
                throws SAXException {
            if (qName.equals("patient")) {
                patientFilter = tags();
            } else if (qName.equals("study")) {
                studyFilter = tags();
            } else if (qName.equals("series")) {
                seriesFilter = tags();
            } else if (qName.equals("instance")) {
                instanceFilter = tags();
            }
        }
    }

    public AttributeFilter(String uri) throws ConfigurationException {
        try {
            SAXParserFactory.newInstance().newSAXParser().parse(
                uri,
                new MyHandler());
        } catch (Exception e) {
            throw new ConfigurationException(
                "Failed to load attribute filter from " + uri,
                e);
        }
    }

    /**
     * @return
     */
    public final int[] getPatientFilter() {
        return patientFilter;
    }

    /**
     * @return
     */
    public final int[] getStudyFilter() {
        return studyFilter;
    }

    /**
     * @return
     */
    public final int[] getSeriesFilter() {
        return seriesFilter;
    }

    /**
     * @return
     */
    public final int[] getInstanceFilter() {
        return instanceFilter;
    }

}


text:
package org.piraso.api;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Monitor preferences.
 */
public class Preferences {

    private Map<String, Boolean> booleanProperties;

    private Map<String, Integer> integerProperties;

    private List<String> urlPatterns;

    public Map<String, Boolean> getBooleanProperties() {
        return booleanProperties;
    }

    public void addProperty(String name, boolean value) {
        if(MapUtils.isEmpty(booleanProperties)) {
            booleanProperties = new HashMap<String, Boolean>();
        }

        booleanProperties.put(name, value);
    }

    public void addProperty(String name, int value) {
        if(MapUtils.isEmpty(integerProperties)) {
            integerProperties = new HashMap<String, Integer>();
        }

        integerProperties.put(name, value);
    }

    public void addUrlPattern(String pattern) {
        if(urlPatterns == null) {
            urlPatterns = new ArrayList<String>();
        }

        urlPatterns.add(pattern);
    }

    public void setBooleanProperties(Map<String, Boolean> booleanProperties) {
        this.booleanProperties = booleanProperties;
    }

    public Map<String, Integer> getIntegerProperties() {
        return integerProperties;
    }

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

    public List<String> getUrlPatterns() {
        return urlPatterns;
    }

    public void setUrlPatterns(List<String> urlPatterns) {
        this.urlPatterns = urlPatterns;
    }

    public boolean isUrlAcceptable(String url) {
        // if empty all url are acceptable
        if(CollectionUtils.isEmpty(urlPatterns)) {
            return true;
        }

        for(String pattern : urlPatterns) {
            if(url.matches(pattern)) {
                return true;
            }
        }

        return false;
    }

    public boolean isEnabled(String property) {
        return MapUtils.isNotEmpty(booleanProperties) && booleanProperties.containsKey(property) && booleanProperties.get(property);
    }

    public boolean isRegexEnabled(String name) {
        if(MapUtils.isEmpty(booleanProperties)) {
            return false;
        }

        for(Map.Entry<String, Boolean> value : booleanProperties.entrySet()) {
            if(name.matches(value.getKey())) {
                return value.getValue();
            }
        }

        return false;
    }

    public Integer getIntValue(String property) {
        if(MapUtils.isEmpty(integerProperties) || !integerProperties.containsKey(property)) {
            return null;
        }

        return integerProperties.get(property);
    }

    @Override
    public boolean equals(Object o) {
        return EqualsBuilder.reflectionEquals(this, o);
    }

    @Override
    public int hashCode() {
        return HashCodeBuilder.reflectionHashCode(this);
    }
}


text:
package org.craapi.drone.matlab;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;

import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;

import org.craapi.drone.BasicControlFactory;
import org.craapi.drone.ControlTower;
import org.craapi.drone.Drone;
import org.craapi.drone.DroneDescriptor;
import org.craapi.drone.E_DroneState;
import org.craapi.drone.ar2.ARDrone2;
import org.craapi.drone.ar2.ARDrone2WifiConnection;
import org.craapi.drone.ar2.Util;
import org.craapi.drone.behavior.ConnectBehavior;
import org.craapi.drone.behavior.DisconnectBehavior;
import org.craapi.drone.behavior.Kinematics;
import org.craapi.drone.behavior.KinematicsBehavior;
import org.craapi.drone.behavior.LandBehavior;
import org.craapi.drone.behavior.TakeoffBehavior;
import org.craapi.drone.sim.OfflineSimDrone;

/**
 * Simple ARDrone interface (intended for use in Matlab)
 *

 * The underlying code is pure Java with no dependencies. It is rough, but works
 * well enough (with the limited testing I have been able to do). After nearly
 * completing this interface, I stumbled upon the YADrone open source project.
 * If you are interested in using a Java interface with the drone, I highly
 * recommend the YADrone project over this one. This one was coded very quickly
 * and the design is...unfortunate in some regards.
 *

 * The drone code I threw together is not very well documented. If I have time,
 * I will clean it up and document it. The bulk of the interface to the ARDrone
 * 2.0 is in the {@link ARDrone2WifiConnection} class. It is a bit of a
 * monolithic beast that needs to be cleaned up. Again, I strongly recommend
 * using YADrone over my implementation.
 *

 * Basic usage:

 * TODO
 *
 * @author nate
 * @see YADrone at Github (link)
 */
public class MatlabDrone {

	protected AtomicBoolean started = new AtomicBoolean();
	protected AtomicBoolean airborne = new AtomicBoolean();
	protected ControlTower c2;
	protected Drone drone;
	protected KinematicsBehavior control;
	protected TakeoffBehavior takeoff;
	protected ExecutorService exec;
	protected boolean simulated = false;

	/**
	 * If the provided argument is 'true', the drone will run in simulation mode
	 * with debug logging enabled. This is intended for testing and debugging.
	 * This must be called prior to {@link #init()}.
	 *

	 * The drone defaults to non-simulation mode.
	 *
	 * @param simFlag
	 *            if "true", the drone interface will operate in a
	 *            simulation rather than on a real device.
	 */
	public void setSimulation(int simFlag) {
		this.simulated = simFlag == 1;
	}

	/**
	 * Initialize the drone components. This must be called prior to calling
	 * {@link #startDrone()}.
	 */
	public synchronized void init() {

		if (c2 != null) {
			return;
		}

		if (simulated) {
			Util.DEBUG_ENABLED = true;
			Util.INFO_ENABLED = true;
			Util.WARN_ENABLED = true;
		}

		// create necessary components
		drone = simulated ? new OfflineSimDrone() : new ARDrone2();
		c2 = new ControlTower(new BasicControlFactory());
		final DroneDescriptor descriptor = new DroneDescriptor("MATLAB", drone);
		c2.register(drone, descriptor);
	}

	/**
	 * Connects to the drone if not already started and sets up state behaviors.
	 *
	 */
	public synchronized void startDrone() {

		if (started.compareAndSet(false, true)) {

			exec = Executors.newCachedThreadPool();

			DroneDescriptor descriptor = new DroneDescriptor("MATLAB", drone);

			// register default behaviors (launch, hover, wait for termination)
			c2.addStateObserver(descriptor, new ConnectBehavior(exec),
					E_DroneState.OFFLINE);
			c2.addStateObserver(descriptor, new DisconnectBehavior(1, exec),
					E_DroneState.GROUNDED);
			c2.addStateObserver(descriptor, new LandBehavior(-1, exec),
					E_DroneState.UNKNOWN, E_DroneState.ERROR);

			// register a delayed takeoff behavior
			TakeoffBehavior takeoff = new TakeoffBehavior(0, exec);
			takeoff.setAutomatic(false); // wait for command
			this.takeoff = takeoff;
			c2.addStateObserver(descriptor, takeoff,
					E_DroneState.GROUNDED);

			// register the kinematics behavior
			KinematicsBehavior temp = new KinematicsBehavior(exec);
			temp.setMax(new Kinematics(0.5f, 0.5f, 0.3f, 0.3f, null, null));
			temp.setMin(new Kinematics(-0.5f, -0.5f, -0.3f, -0.3f, null, null));
			this.control = temp;
			c2.addStateObserver(descriptor, temp, E_DroneState.HOVER, E_DroneState.INFLIGHT);

			// liftoff...
			c2.start();
		}
	}

	/**
	 * Returns 1 if the drone is started and 0
	 * otherwise.
	 *
	 * @return 1 if the drone is started and 0
	 *         otherwise
	 */
	public int isRunning() {
		return started.get() ? 1 : 0;
	}

	/**
	 * Returns 1 if the drone is airborne and 0
	 * otherwise.
	 *
	 * @return 1 if the drone is airborne and 0
	 *         otherwise
	 */
	public int isAirborne() {
		return (started.get() && airborne.get()) ? 1 : 0;
	}

	/**
	 * Stops the drone, which includes landing if necessary. After this is
	 * called, {@link #init()} and {@link #startDrone()} must be called in order
	 * to get back to a functional state.
	 *

	 * If you forget to call this prior to exiting Matlab, you may have a
	 * runaway drone on your hands. Call this method directly from the Matlab
	 * command prompt if necessary.
	 */
	public synchronized void stopDrone() {

		if (started.compareAndSet(true, false)) {

			E_DroneState state = drone.getState();
			if (state != E_DroneState.GROUNDED
					&& state != E_DroneState.DISCONNECTING
					&& state != E_DroneState.OFFLINE) {
				drone.transition(null, E_DroneState.ERROR); // hack to cause a
															// landing
			}

			try {
				// give the drone 5 seconds to land
				Thread.sleep(5000);
			} catch (InterruptedException e) {
				// ignore
			}

			airborne.set(false);

			c2.stop();
			c2.removeAllObservers(drone);
			control = null;
			takeoff = null;
			exec.shutdownNow();
			exec = null;
		}
	}

	/**
	 * If called after {@link #startDrone()}, this causes the drone to take off
	 * and enter a hovering state. This must be called prior to calling
	 * {@link #setKinematics(String)}.
	 */
	public void takeoff() {
		// update behavior
		if (started.get() && airborne.compareAndSet(false, true)) {
			synchronized (this) {
				if (takeoff != null) {
					takeoff.approveTakeoff();
				}
			}
		}
	}

	/**
	 * Accepts a string that contains the desired kinematics. I left this as a
	 * string for maximum compatibility with Matlab and the possibility of
	 * adding more name/value pairs without changing the API.
	 *

	 * Accepts a comma-delimited string:

	 * e.g., yaw=%f,pitch=%f,roll=%f,alt=%f,combine=true,hover=true

	 *
	 *

	 * Possible values:

	 *

	 *
yaw - the horizontal plane rotation speed

	 *
pitch - the front-back angle/speed (negative is backwards
	 * motion)

	 *
roll - the side-to-side angle/speed (negative is leftward
	 * motion)

	 *
alt - the up-down speed (negative is downward motion)

	 *
combine - enables 'combined yaw mode' (no clue)

	 *
hover - enables 'hover mode' (other arguments are ignored;
	 * drone is stationary)

	 *

	 *

	 * NOTE: All speeds are percentages of the maximum (absolute) speed.
	 * For example, a value of 1.0 means "max speed in x direction". A value of
	 * 0.0 means "no speed in x direction". So, all values are expressed in
	 * range [-1.0,1.0].
	 *
	 * @param kinematics
	 */
	public void setKinematics(String kinematics) {

		if (!airborne.get() || !started.get()) {
			return;
		}

		final Kinematics kin = new Kinematics();

		if (kinematics == null) {
			kin.setHover(true);
		} else {
			kinematics = kinematics.trim();
			if (kinematics.isEmpty()) {
				kin.setHover(true);
			} else {
				final String[] tokens = kinematics.split(",");
				final Map<String, String> args = new HashMap<String, String>(
						tokens.length);
				for (String t : tokens) {
					String[] nvPair = t.split("=", 2);
					if (nvPair.length == 2) {
						args.put(nvPair[0].trim().toLowerCase(), nvPair[1]
								.trim().toLowerCase());
					}
				}

				kin.setHover(Boolean.parseBoolean(args.get("hover")));
				if (!kin.getHover()) {
					kin.setCombinedYaw(Boolean.parseBoolean(args.get("combine")));
					try {
						kin.setYaw(Float.parseFloat(args.get("yaw")));
					} catch (Exception e) {
						// ignore
					}
					try {
						kin.setPitch(Float.parseFloat(args.get("pitch")));
					} catch (Exception e) {
						// ignore
					}
					try {
						kin.setRoll(Float.parseFloat(args.get("roll")));
					} catch (Exception e) {
						// ignore
					}
					try {
						kin.setVertical(Float.parseFloat(args.get("alt")));
					} catch (Exception e) {
						// ignore
					}
				}
			}
		}

		// update behavior
		synchronized(this) {
			if (control != null) {
				control.adjustKinematics(kin);
			}
		}
	}

	public static void main(String[] args) {
		main(1,true);
	}

	public static void mainForMatlab(final int simFlag) {
		final Thread t = new Thread(new Runnable() {

			@Override
			public void run() {
				main(simFlag, false);
			}
		});
		t.start();
	}

	public static void main(int simFlag, boolean showControlDialog) {

		final MatlabDrone drone = new MatlabDrone();
		drone.setSimulation(1);
		drone.init();
		drone.startDrone();

		if (showControlDialog) {
			SwingUtilities.invokeLater(new Runnable() {

				@Override
				public void run() {
					JOptionPane.showConfirmDialog(null, "Shutdown drone?");
					drone.stopDrone();
				}
			});
		}

		// takeoff
		drone.takeoff();

		// set some kinematics...

		try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			// ignore
		}

		drone.setKinematics("hover=false,yaw=0.2");

		try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			// ignore
		}

		drone.setKinematics("hover=true");

		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			// ignore
		}

		drone.setKinematics("yaw=0.0,pitch=0.2");

		try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			// ignore
		}

		drone.setKinematics("hover=true");

		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			// ignore
		}

		drone.setKinematics("pitch=0.0,roll=0.2");

		try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			// ignore
		}

		drone.setKinematics("hover=true");

		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			// ignore
		}

		drone.setKinematics("alt=-0.1,yaw=-0.2,roll=0.0");

		try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			// ignore
		}

		drone.setKinematics("hover=true");

		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			// ignore
		}

		drone.stopDrone();
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  >
  <TextView
    android:id="@+id/selection"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    />
  <AutoCompleteTextView android:id="@+id/edit"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:completionThreshold="3"/>
</LinearLayout>


text:
describe('ArtSVG TEST', function() {

    describe('ArtSVG.prototype.getDrawerType', function() {

        it('should return "path"', function() {
            var container = document.createElement('div');
            var svg       = document.createElement('svg');

            container.appendChild(svg);

            var artSVG = new ArtSVG(container, svg, 800, 600, {});

            expect(artSVG.getDrawerType()).toEqual('path');
        });

    });

});


text:
package com.computing.cloud.exception;

import java.util.ArrayList;
import java.util.List;

import com.computing.cloud.validator.ValidationError;

@SuppressWarnings("serial")
public class ApiException extends RuntimeException {

	private int status;
	private List<ValidationError> errorsList = new ArrayList<ValidationError>();

	public ApiException(String message, int status) {
		super(message);
		this.status = status;
	}

	public ApiException(String message, int status, List<ValidationError> validationErrorsEntityList) {
		this(message, status);
		this.errorsList = validationErrorsEntityList;
	}

	public ApiException(String message, int status, Exception cause) {
		super(message, cause);
		this.status = status;
	}

	public int getStatus() {
		return status;
	}

	public List<ValidationError> getErrorsList() {
		return errorsList;
	}

	@Override
	public String getMessage() {
		return super.getMessage();
	}

}


text:
<?php

namespace Eu\Mydevlab\TumblrExportImport\Model\Entity\Deps;

/**
 * Class Dialogue
 *
 * @package Eu\Mydevlab\TumblrExportImport\Model\Entity\Deps
 * @author Sylvain Artois <sylvain.artois@gmail.com>
 */
class Dialogue
{
    /** @var string Name of the speaker */
    protected $name;

    /** @var string Label of the speaker */
    protected $label;

    /** @var string Text */
    protected $phrase;

    /**
     * @param string $name
     * @param string $label
     * @param string $phrase
     */
    public function __construct($name, $label, $phrase)
    {
        $this->label = $label;
        $this->name = $name;
        $this->phrase = $phrase;
    }

    /**
     * @param string $label
     */
    public function setLabel($label)
    {
        $this->label = $label;
    }

    /**
     * @return string
     */
    public function getLabel()
    {
        return $this->label;
    }

    /**
     * @param string $name
     */
    public function setName($name)
    {
        $this->name = $name;
    }

    /**
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * @param string $phrase
     */
    public function setPhrase($phrase)
    {
        $this->phrase = $phrase;
    }

    /**
     * @return string
     */
    public function getPhrase()
    {
        return $this->phrase;
    }
}