text:
#include <errno.h>
#include <atomic.h>
#include <misc/byteorder.h>

#define BT_DBG_ENABLED IS_ENABLED(CONFIG_BLUETOOTH_DEBUG_GATT)
#include <bluetooth/log.h>
#include <net/buf.h>
#include <bluetooth/gatt.h>
#include <bluetooth/att.h>

#include "conn.h"
#include "conn_internal.h"
#include "gatt_internal.h"

#define NBLE_BUF_SIZE	384

/* TODO: Get this value during negotiation */
#define BLE_GATT_MTU_SIZE 23

#if CONFIG_BLUETOOTH_ATT_PREPARE_COUNT > 0
/* Pool for incoming ATT packets */
NET_BUF_POOL_DEFINE(prep_pool, CONFIG_BLUETOOTH_ATT_PREPARE_COUNT,
		    BLE_GATT_MTU_SIZE, sizeof(struct nble_gatts_write_evt),
		    NULL);

static K_FIFO_DEFINE(queue);
#endif

struct nble_gatt_service {
	const struct bt_gatt_attr *attrs;
	u16_t attr_count;
};

static struct nble_gatt_service svc_db[BLE_GATTS_MAX_SERVICES];
static u8_t svc_count;

static sys_slist_t subscriptions;

/**
 * Copy a UUID in a buffer using the smallest memory length
 * @param buf Pointer to the memory where the UUID shall be copied
 * @param uuid Pointer to the UUID to copy
 * @return The length required to store the UUID in the memory
 */
static u8_t bt_gatt_uuid_memcpy(u8_t *buf, const struct bt_uuid *uuid)
{
	u8_t *ptr = buf;

	/* Store the type of the UUID */
	*ptr = uuid->type;
	ptr++;

	/* Store the UUID data */
	if (uuid->type == BT_UUID_TYPE_16) {
		u16_t le16;

		le16 = sys_cpu_to_le16(BT_UUID_16(uuid)->val);
		memcpy(ptr, &le16, sizeof(le16));
		ptr += sizeof(le16);
	} else {
		memcpy(ptr, BT_UUID_128(uuid)->val, 16);
		ptr += 16;
	}

	return ptr - buf;
}

/* These attributes need the value to be read */
static struct bt_uuid *whitelist[] = {
	BT_UUID_GATT_PRIMARY,
	BT_UUID_GATT_SECONDARY,
	BT_UUID_GATT_INCLUDE,
	BT_UUID_GATT_CHRC,
	BT_UUID_GATT_CEP,
	BT_UUID_GATT_CUD,
	BT_UUID_GATT_CPF,
	BT_UUID_GAP_DEVICE_NAME,
	BT_UUID_GAP_APPEARANCE,
	BT_UUID_GAP_PPCP
};

static int attr_read(struct bt_gatt_attr *attr, u8_t *data, size_t len)
{
	u8_t i;
	int data_size;

	if (!data) {
		return -ENOMEM;
	}

	data_size = bt_gatt_uuid_memcpy(data, attr->uuid);

	for (i = 0; i < ARRAY_SIZE(whitelist); i++) {
		if (!bt_uuid_cmp(attr->uuid, whitelist[i])) {
			int read;

			read = attr->read(NULL, attr, data + data_size, len, 0);
			if (read < 0) {
				return read;
			}

			data_size += read;
			break;
		}
	}

	return data_size;
}

int bt_gatt_register(struct bt_gatt_attr *attrs, size_t count)
{
	struct nble_gatts_register_req param;
	size_t i;
	/* TODO: Replace the following with net_buf */
	u8_t attr_table[NBLE_BUF_SIZE];
	u8_t attr_table_size;

	if (!attrs || !count) {
		return -EINVAL;
	}
	BT_ASSERT(svc_count < BLE_GATTS_MAX_SERVICES);

	svc_db[svc_count].attrs = attrs;
	svc_db[svc_count].attr_count = count;
	svc_count++;
	param.attr_base = attrs;
	param.attr_count = count;
	param.attr_size = sizeof(struct bt_gatt_attr);

	attr_table_size = 0;

	for (i = 0; i < count; i++) {
		struct bt_gatt_attr *attr = &attrs[i];
		struct nble_gatts_attr *att;
		int err;

		if (attr_table_size + sizeof(*att) > sizeof(attr_table)) {
			return -ENOMEM;
		}

		att = (void *)&attr_table[attr_table_size];
		att->perm = attr->perm;

		attr_table_size += sizeof(*att);

		/* Read attribute data */
		err = attr_read(attr, att->data,
				sizeof(attr_table) - attr_table_size);
		if (err < 0) {
			BT_ERR("Failed to read attr: %d", err);
			return err;
		}

		att->data_size = err;

		/* Compute the new element size and align it on upper 4 bytes
		 * boundary.
		 */
		attr_table_size += (att->data_size + 3) & ~3;

		BT_DBG("table size = %u attr data_size = %u", attr_table_size,
		       att->data_size);
	}

	nble_gatts_register_req(&param, attr_table, attr_table_size);
	return 0;
}

void on_nble_gatts_register_rsp(const struct nble_gatts_register_rsp *rsp,
			       const struct nble_gatt_attr_handles *handles,
			       u8_t len)
{
	int i;
	struct bt_gatt_attr *head_svc_attr;

	BT_DBG("status %u", rsp->status);

	if (rsp->status != 0) {
		return;
	}

	head_svc_attr = rsp->attr_base;

	for (i = 0; i < rsp->attr_count; i++, head_svc_attr++) {
		head_svc_attr->handle = handles[i].handle;
	}
#if defined(CONFIG_BLUETOOTH_DEBUG_GATT)
	{
		int idx;

		for (idx = 0; idx < rsp->attr_count; idx++) {
			/* The following order of declaration is assumed for
			 * this to work (otherwise idx-2 will fail!):
			 * BT_GATT_CHARACTERISTIC -> ble core returns invalid
			 * handle.
			 * BT_GATT_DESCRIPTOR -> value handle of characteristic
			 * BT_GATT_CCC -> cccd handle is ignored as no storage
			 * but reference value is updated in CCC with value
			 * handle from descriptor.
			 */
			if (handles[idx].handle != 0) {
				char uuid[37];

				bt_uuid_to_str(rsp->attr_base[idx].uuid,
					       uuid, sizeof(uuid));
				BT_DBG("handle 0x%04x uuid %s",
				       handles[idx].handle, uuid);
			}
		}
	}
#endif
}

void bt_gatt_foreach_attr(u16_t start_handle, u16_t end_handle,
			  bt_gatt_attr_func_t func, void *user_data)
{
	int i;

	for (i = 0; i < svc_count; i++) {
		u16_t attr_count = svc_db[i].attr_count;
		const struct bt_gatt_attr *attr;
		int j;

		for (j = 0; j < attr_count; j++) {
			attr = &svc_db[i].attrs[j];

			/* Check if attribute handle is within range */
			if (attr->handle < start_handle ||
			    attr->handle > end_handle) {
				continue;
			}

			if (func(attr, user_data) == BT_GATT_ITER_STOP) {
				break;
			}
		}
	}
}

struct bt_gatt_attr *bt_gatt_attr_next(const struct bt_gatt_attr *attr)
{
	u16_t i;

	for (i = 0; i < svc_count; i++) {
		if (attr >= svc_db[i].attrs &&
		    attr < svc_db[i].attrs + svc_db[i].attr_count) {
			u8_t attr_i;

			attr_i = (attr - svc_db[i].attrs) + 1;

			/* Return next element of current service */
			if (attr_i < svc_db[i].attr_count) {
				return (struct bt_gatt_attr *)&attr[1];
			}

			/* Return next service as next attribute */
			if (i < (svc_count - 1)) {
				return (struct bt_gatt_attr *)svc_db[i+1].attrs;
			}
		}
	}

	return NULL;
}

ssize_t bt_gatt_attr_read(struct bt_conn *conn, const struct bt_gatt_attr *attr,
			  void *buf, u16_t buf_len, u16_t offset,
			  const void *value, u16_t value_len)
{
	u16_t len;

	BT_DBG("handle 0x%04x offset %u", attr->handle, offset);

	/* simply return the value length. used as max_value. */
	if (buf == NULL) {
		return value_len;
	}

	if (offset > value_len) {
		return BT_GATT_ERR(BT_ATT_ERR_INVALID_OFFSET);
	}

	len = min(buf_len, value_len - offset);

	memcpy(buf, value + offset, len);

	return len;
}

ssize_t bt_gatt_attr_read_service(struct bt_conn *conn,
				  const struct bt_gatt_attr *attr,
				  void *buf, u16_t len, u16_t offset)
{
	struct bt_uuid *uuid = attr->user_data;

	if (uuid->type == BT_UUID_TYPE_16) {
		u16_t uuid16 = sys_cpu_to_le16(BT_UUID_16(uuid)->val);

		return bt_gatt_attr_read(conn, attr, buf, len, offset,
					 &uuid16, 2);
	}

	return bt_gatt_attr_read(conn, attr, buf, len, offset,
				 BT_UUID_128(uuid)->val, 16);
}

ssize_t bt_gatt_attr_read_included(struct bt_conn *conn,
				   const struct bt_gatt_attr *attr,
				   void *buf, u16_t len, u16_t offset)
{
	/*
	 * bt_gatt_attr_read uses memcpy to copy the address of the attr
	 * to the buf, so pointer to pointer is needed here.
	 */
	struct bt_gatt_attr **incl = (struct bt_gatt_attr **)&attr->user_data;

	/* nble gatt register case reading user_data. */
	if (!conn) {
		return bt_gatt_attr_read(conn, attr, buf, len, offset, incl,
					 sizeof(*incl));
	}

	/* nble handles gattc reads internally */
	return -EINVAL;
}

struct gatt_chrc {
	u8_t properties;
	u16_t value_handle;
	union {
		u16_t uuid16;
		u8_t  uuid[16];
	};
} __packed;

ssize_t bt_gatt_attr_read_chrc(struct bt_conn *conn,
			       const struct bt_gatt_attr *attr, void *buf,
			       u16_t len, u16_t offset)
{
	struct bt_gatt_chrc *chrc = attr->user_data;
	struct gatt_chrc pdu;
	u8_t value_len;

	pdu.properties = chrc->properties;

	/* Handle cannot be read at this point */
	pdu.value_handle = 0x0000;

	value_len = sizeof(pdu.properties) + sizeof(pdu.value_handle);

	if (chrc->uuid->type == BT_UUID_TYPE_16) {
		pdu.uuid16 = sys_cpu_to_le16(BT_UUID_16(chrc->uuid)->val);
		value_len += 2;
	} else {
		memcpy(pdu.uuid, BT_UUID_128(chrc->uuid)->val, 16);
		value_len += 16;
	}

	return bt_gatt_attr_read(conn, attr, buf, len, offset, &pdu, value_len);
}

ssize_t bt_gatt_attr_read_ccc(struct bt_conn *conn,
			      const struct bt_gatt_attr *attr, void *buf,
			      u16_t len, u16_t offset)
{
	return BT_GATT_ERR(BT_ATT_ERR_NOT_SUPPORTED);
}

static void gatt_ccc_changed(const struct bt_gatt_attr *attr,
			     struct _bt_gatt_ccc *ccc)
{
	int i;
	u16_t value = 0x0000;

	for (i = 0; i < ccc->cfg_len; i++) {
		if (ccc->cfg[i].value > value) {
			value = ccc->cfg[i].value;
		}
	}

	BT_DBG("ccc %p value 0x%04x", ccc, value);

	if (value != ccc->value) {
		ccc->value = value;
		ccc->cfg_changed(attr, value);
	}
}

ssize_t bt_gatt_attr_write_ccc(struct bt_conn *conn,
			       const struct bt_gatt_attr *attr, const void *buf,
			       u16_t len, u16_t offset, u8_t flags)
{
	struct _bt_gatt_ccc *ccc = attr->user_data;
	const u16_t *data = buf;
	size_t i;

	if (offset > sizeof(*data)) {
		return BT_GATT_ERR(BT_ATT_ERR_INVALID_OFFSET);
	}

	if (offset + len > sizeof(*data)) {
		return BT_GATT_ERR(BT_ATT_ERR_INVALID_ATTRIBUTE_LEN);
	}

	for (i = 0; i < ccc->cfg_len; i++) {
		/* Check for existing configuration */
		if (!bt_addr_le_cmp(&ccc->cfg[i].peer, &conn->dst)) {
			break;
		}
	}

	if (i == ccc->cfg_len) {
		for (i = 0; i < ccc->cfg_len; i++) {
			/* Check for unused configuration */
			if (ccc->cfg[i].valid) {
				continue;
			}

			bt_addr_le_copy(&ccc->cfg[i].peer, &conn->dst);
			/* TODO: Only set valid if bonded */
			ccc->cfg[i].valid = true;
			break;
		}

		if (i == ccc->cfg_len) {
			BT_WARN("No space to store CCC cfg");
			return BT_GATT_ERR(BT_ATT_ERR_INSUFFICIENT_RESOURCES);
		}
	}

	ccc->cfg[i].value = sys_le16_to_cpu(*data);

	BT_DBG("handle 0x%04x value %u", attr->handle, ccc->cfg[i].value);

	/* Update cfg if don't match */
	if (ccc->cfg[i].value != ccc->value) {
		gatt_ccc_changed(attr, ccc);
	}

	return len;
}

ssize_t bt_gatt_attr_read_cep(struct bt_conn *conn,
			      const struct bt_gatt_attr *attr, void *buf,
			      u16_t len, u16_t offset)
{
	struct bt_gatt_cep *value = attr->user_data;
	u16_t props = sys_cpu_to_le16(value->properties);

	return bt_gatt_attr_read(conn, attr, buf, len, offset, &props,
				 sizeof(props));
}

ssize_t bt_gatt_attr_read_cud(struct bt_conn *conn,
			      const struct bt_gatt_attr *attr, void *buf,
			      u16_t len, u16_t offset)
{
	char *value = attr->user_data;

	return bt_gatt_attr_read(conn, attr, buf, len, offset, value,
				 strlen(value));
}

ssize_t bt_gatt_attr_read_cpf(struct bt_conn *conn,
			      const struct bt_gatt_attr *attr, void *buf,
			      u16_t len, u16_t offset)
{
	struct bt_gatt_cpf *value = attr->user_data;

	return bt_gatt_attr_read(conn, attr, buf, len, offset, value,
				 sizeof(*value));
}

static int notify(struct bt_conn *conn, const struct bt_gatt_attr *attr,
		  const void *data, size_t len)
{
	struct nble_gatts_notify_req notif;

	BT_DBG("");

	k_sem_take(&conn->gatt_notif_sem, K_FOREVER);

	notif.params.conn_handle = conn->handle;
	notif.params.attr = attr;
	notif.params.offset = 0;
	notif.cback = NULL;

	nble_gatts_notify_req(&notif, (u8_t *)data, len);

	return 0;
}

void on_nble_gatts_notify_tx_evt(const struct nble_gatts_notify_tx_evt *evt)
{
	struct bt_conn *conn;

	if (evt->status) {
		BT_ERR("status %d", evt->status);
		/**
		 * Continue since we get non zero status shen we
		 * unsubscribe from notifications
		 */
	}

	BT_DBG("conn handle %u status %d attr %p", evt->conn_handle,
	       evt->status, evt->attr);

	conn = bt_conn_lookup_handle(evt->conn_handle);
	if (!conn) {
		BT_ERR("Unable to find conn, handle 0x%04x", evt->conn_handle);
		return;
	}

	k_sem_give(&conn->gatt_notif_sem);

	bt_conn_unref(conn);
}

static int indicate(struct bt_conn *conn,
		    struct bt_gatt_indicate_params *params)
{
	struct nble_gatts_indicate_req ind;

	BT_DBG("conn %p", conn);

	if (!params) {
		return -EINVAL;
	}

	ind.params.conn_handle = conn->handle;
	ind.params.attr = (void *)params->attr;
	ind.params.offset = 0;
	ind.cback = params->func;

	nble_gatts_indicate_req(&ind, (void *)params->data, params->len);

	return 0;
}

struct notify_data {
	u16_t type;
	const struct bt_gatt_attr *attr;
	const void *data;
	u16_t len;
	struct bt_gatt_indicate_params *params;
};

static u8_t notify_cb(const struct bt_gatt_attr *attr, void *user_data)
{
	struct notify_data *data = user_data;
	struct _bt_gatt_ccc *ccc;
	size_t i;

	if (bt_uuid_cmp(attr->uuid, BT_UUID_GATT_CCC)) {
		return BT_GATT_ITER_CONTINUE;
	}

	/* Check attribute user_data must be of type struct _bt_gatt_ccc */
	if (attr->write != bt_gatt_attr_write_ccc) {
		return BT_GATT_ITER_CONTINUE;
	}

	ccc = attr->user_data;

	/* Notify all peers configured */
	for (i = 0; i < ccc->cfg_len; i++) {
		struct bt_conn *conn;
		int err;

		if (!ccc->value || ccc->value != data->type)
			continue;

		conn = bt_conn_lookup_addr_le(&ccc->cfg[i].peer);
		if (!conn) {
			continue;
		}

		if (conn->state != BT_CONN_CONNECTED) {
			bt_conn_unref(conn);
			continue;
		}

		if (data->type == BT_GATT_CCC_INDICATE) {
			err = indicate(conn, data->params);
		} else {
			err = notify(conn, data->attr, data->data, data->len);
		}

		bt_conn_unref(conn);

		if (err < 0) {
			return BT_GATT_ITER_STOP;
		}
	}

	return BT_GATT_ITER_CONTINUE;
}

int bt_gatt_notify(struct bt_conn *conn, const struct bt_gatt_attr *attr,
		   const void *data, u16_t len)
{
	struct notify_data nfy;

	BT_DBG("conn %p", conn);

	if (!attr) {
		return -EINVAL;
	}

	if (conn) {
		return notify(conn, attr, data, len);
	}

	nfy.attr = attr;
	nfy.type = BT_GATT_CCC_NOTIFY;
	nfy.data = data;
	nfy.len = len;

	bt_gatt_foreach_attr(1, 0xffff, notify_cb, &nfy);

	return 0;
}

int bt_gatt_indicate(struct bt_conn *conn,
		     struct bt_gatt_indicate_params *params)
{
	struct notify_data nfy;

	BT_DBG("conn %p", conn);

	if (!params || !params->attr || !params->attr->handle) {
		return -EINVAL;
	}

	if (conn) {
		return indicate(conn, params);
	}

	nfy.type = BT_GATT_CCC_INDICATE;
	nfy.params = params;

	bt_gatt_foreach_attr(1, 0xffff, notify_cb, &nfy);

	return 0;
}

/* Response to bt_gatt_indicate() */
void on_nble_gatts_indicate_rsp(const struct nble_gatts_indicate_rsp *rsp)
{
	struct bt_conn *conn;

	if (rsp->status) {
		BT_ERR("Send indication failed, status %d", rsp->status);
		return;
	}

	conn = bt_conn_lookup_handle(rsp->conn_handle);
	if (!conn) {
		BT_ERR("Unable to find conn, handle 0x%04x", rsp->conn_handle);
		return;
	}

	if (rsp->cback) {
		rsp->cback(conn, rsp->attr, rsp->status);
	}

	bt_conn_unref(conn);
}

int bt_gatt_exchange_mtu(struct bt_conn *conn,
			 struct bt_gatt_exchange_params *params)
{
	return -ENOSYS;
}

int bt_gatt_discover(struct bt_conn *conn,
		     struct bt_gatt_discover_params *params)
{
	struct nble_gattc_discover_req discover_params;

	if (!conn || !params || !params->func || !params->start_handle ||
	    !params->end_handle || params->start_handle > params->end_handle) {
		return -EINVAL;
	}

	if (conn->state != BT_CONN_CONNECTED) {
		return -ENOTCONN;
	}

	if (conn->gatt_private) {
		return -EBUSY;
	}

	BT_DBG("conn %p start 0x%04x end 0x%04x uuid %s", conn,
	       params->start_handle, params->end_handle,
	       bt_uuid_str(params->uuid));

	memset(&discover_params, 0, sizeof(discover_params));

	switch (params->type) {
	case BT_GATT_DISCOVER_PRIMARY:
	case BT_GATT_DISCOVER_CHARACTERISTIC:
		if (params->uuid) {
			/* Always copy a full 128 bit UUID */
			memcpy(&discover_params.uuid, BT_UUID_128(params->uuid),
			       sizeof(discover_params.uuid));
			discover_params.flags = DISCOVER_FLAGS_UUID_PRESENT;
		}

		break;
	case BT_GATT_DISCOVER_INCLUDE:
	case BT_GATT_DISCOVER_DESCRIPTOR:
		break;
	default:
		BT_ERR("Unknown params type %u", params->type);
		return -EINVAL;
	}

	discover_params.conn_handle = conn->handle;
	discover_params.type = params->type;
	discover_params.handle_range.start_handle = params->start_handle;
	discover_params.handle_range.end_handle = params->end_handle;

	conn->gatt_private = params;

	nble_gattc_discover_req(&discover_params);

	return 0;
}

static u16_t parse_include(struct bt_conn *conn,
			      struct bt_gatt_discover_params *params,
			      const u8_t *data, u8_t len)
{
	u16_t end_handle = 0;
	int i;

	for (i = 0; len > 0; i++) {
		const struct nble_gattc_included *att = (void *)data;
		struct bt_gatt_attr *attr = NULL;
		struct bt_gatt_include gatt_include;

		gatt_include.start_handle = att->range.start_handle;
		gatt_include.end_handle = att->range.end_handle;
		end_handle = att->handle;

		BT_DBG("start 0x%04x end 0x%04x", att->range.start_handle,
		       att->range.end_handle);

		/*
		 * 4.5.1 If the service UUID is a 16-bit Bluetooth UUID
		 *  it is also returned in the response.
		 */
		switch (att->uuid.uuid.type) {
		case BT_UUID_TYPE_16:
			gatt_include.uuid = &att->uuid.uuid;
			break;
		case BT_UUID_TYPE_128:
			/* Data is not available at this point */
			break;
		}

		attr = (&(struct bt_gatt_attr) {
			.uuid = BT_UUID_GATT_INCLUDE,
			.user_data = &gatt_include, });
		attr->handle = att->handle;

		data += sizeof(*att);
		len -= sizeof(*att);

		if (params->func(conn, attr, params) == BT_GATT_ITER_STOP) {
			return 0;
		}
	}

	return end_handle;
}

static u16_t parse_service(struct bt_conn *conn,
			      struct bt_gatt_discover_params *params,
			      const u8_t *data, u8_t len)
{
	u16_t end_handle = 0;
	int i;

	for (i = 0; len > 0; i++) {
		const struct nble_gattc_primary *att = (void *)data;
		struct bt_gatt_service gatt_service;
		struct bt_gatt_attr *attr = NULL;

		gatt_service.end_handle = att->range.end_handle;
		gatt_service.uuid = params->uuid;
		end_handle = gatt_service.end_handle;

		attr = (&(struct bt_gatt_attr)
			BT_GATT_PRIMARY_SERVICE(&gatt_service));
		attr->handle = att->handle;

		data += sizeof(*att);
		len -= sizeof(*att);

		if (params->func(conn, attr, params) == BT_GATT_ITER_STOP) {
			return 0;
		}
	}

	return end_handle;
}

static u16_t parse_characteristic(struct bt_conn *conn,
				     struct bt_gatt_discover_params *params,
				     const u8_t *data, u8_t len)
{
	u16_t end_handle = 0;
	int i;

	for (i = 0; len > 0; i++) {
		const struct nble_gattc_characteristic *att = (void *)data;
		struct bt_gatt_attr *attr = NULL;

		attr = (&(struct bt_gatt_attr)
			BT_GATT_CHARACTERISTIC(&att->uuid.uuid, att->prop));
		attr->handle = att->handle;
		end_handle = att->handle;

		data += sizeof(*att);
		len -= sizeof(*att);

		/* Skip if UUID is set but doesn't match */
		if (params->uuid &&
		    bt_uuid_cmp(&att->uuid.uuid, params->uuid)) {
			continue;
		}

		if (params->func(conn, attr, params) == BT_GATT_ITER_STOP) {
			return 0;
		}
	}

	return end_handle;
}

static u16_t parse_descriptor(struct bt_conn *conn,
				 struct bt_gatt_discover_params *params,
				 const u8_t *data, u8_t len)
{
	u16_t end_handle = 0;
	int i;

	for (i = 0; len > 0; i++) {
		const struct nble_gattc_descriptor *att = (void *)data;
		struct bt_gatt_attr *attr = NULL;

		attr = (&(struct bt_gatt_attr)
			BT_GATT_DESCRIPTOR(&att->uuid.uuid, 0, NULL, NULL, NULL));
		attr->handle = att->handle;
		end_handle = att->handle;

		data += sizeof(*att);
		len -= sizeof(*att);

		if (params->func(conn, attr, params) == BT_GATT_ITER_STOP) {
			return 0;
		}
	}

	return end_handle;
}

static void *gatt_get_private(struct bt_conn *conn)
{
	void *private;

	private = conn->gatt_private;
	/* Reset so it can be reused */
	conn->gatt_private = NULL;

	return private;
}

void on_nble_gattc_discover_rsp(const struct nble_gattc_discover_rsp *rsp,
				const u8_t *data, u8_t data_len)
{
	u16_t end_handle = 0;
	struct bt_gatt_discover_params *params;
	struct bt_conn *conn;
	int status;

	conn = bt_conn_lookup_handle(rsp->conn_handle);
	if (!conn) {
		BT_ERR("Unable to find conn, handle 0x%04x", rsp->conn_handle);
		return;
	}

	/* This pointer would keep new params set in the function below */
	params = gatt_get_private(conn);

	/* Status maybe error or indicate end of discovery */
	if (rsp->status) {
		BT_DBG("status %d", rsp->status);
		goto done;
	}

	BT_DBG("conn %p conn handle 0x%04x status %d len %u", conn,
	       conn->handle, rsp->status, data_len);

	switch (rsp->type) {
	case BT_GATT_DISCOVER_INCLUDE:
		end_handle = parse_include(conn, params, data, data_len);
		break;
	case BT_GATT_DISCOVER_PRIMARY:
		end_handle = parse_service(conn, params, data, data_len);
		break;
	case BT_GATT_DISCOVER_CHARACTERISTIC:
		end_handle = parse_characteristic(conn, params, data, data_len);
		break;
	case BT_GATT_DISCOVER_DESCRIPTOR:
		end_handle = parse_descriptor(conn, params, data, data_len);
		break;
	default:
		BT_ERR("Wrong discover type %d", rsp->type);
		bt_conn_unref(conn);
		return;
	}

	if (!end_handle) {
		goto stop;
	}

	/* Stop if end_handle is over the range */
	if (end_handle >= params->end_handle) {
		BT_WARN("Handle goes over the range: 0x%04x >= 0x%04x",
			end_handle, params->end_handle);
		goto done;
	}

	/* Continue discovery from last found handle */
	params->start_handle = end_handle;
	if (params->start_handle < UINT16_MAX) {
		params->start_handle++;
	}

	status = bt_gatt_discover(conn, params);
	if (status) {
		BT_ERR("Unable to continue discovering, status %d", status);
		goto done;
	}

	bt_conn_unref(conn);
	return;

done:
	/* End of discovery */
	params->func(conn, NULL, params);

stop:
	bt_conn_unref(conn);
}

static int gatt_read_multiple(struct bt_conn *conn,
			      struct bt_gatt_read_params *params)
{
	struct nble_gattc_read_multi_req req;

	req.conn_handle = conn->handle;
	req.user_data = params;

	nble_gattc_read_multi_req(&req, params->handles,
				     2 * params->handle_count);

	return 0;
}

int bt_gatt_read(struct bt_conn *conn, struct bt_gatt_read_params *params)
{
	struct nble_gattc_read_req req;

	if (!conn || !params || !params->handle_count || !params->func) {
		return -EINVAL;
	}

	if (conn->state != BT_CONN_CONNECTED) {
		return -ENOTCONN;
	}

	if (params->handle_count > 1) {
		return gatt_read_multiple(conn, params);
	}

	BT_DBG("conn %p params %p", conn, params);

	req.conn_handle = conn->handle;
	req.handle = params->single.handle;
	req.offset = params->single.offset;
	req.user_data = params;

	nble_gattc_read_req(&req);

	return 0;
}

void on_nble_gattc_read_rsp(const struct nble_gattc_read_rsp *rsp,
			    u8_t *data, u8_t len)
{
	struct bt_gatt_read_params *params = rsp->user_data;
	struct bt_conn *conn;

	conn = bt_conn_lookup_handle(rsp->conn_handle);
	if (!conn) {
		BT_ERR("Unable to find conn, handle 0x%04x", rsp->conn_handle);
		return;
	}

	BT_DBG("status %d conn %p params %p", rsp->status, conn, params);

	if (rsp->status) {
		params->func(conn, rsp->status, params, NULL, 0);
		goto done;
	}

	if (params->func(conn, 0, params, data, len) == BT_GATT_ITER_STOP) {
		goto done;
	}

	/*
	 * Core Spec 4.2, Vol. 3, Part G, 4.8.1
	 * If the Characteristic Value is greater than (ATT_MTU - 1) octets
	 * in length, the Read Long Characteristic Value procedure may be used
	 * if the rest of the Characteristic Value is required.
	 * The data contain only (ATT_MTU - 1) octets.
	 */
	if (len < (BLE_GATT_MTU_SIZE - 1)) {
		params->func(conn, 0, params, NULL, 0);
		goto done;
	}

	params->single.offset += len;

	/* Continue reading the attribute */
	if (bt_gatt_read(conn, params)) {
		params->func(conn, BT_ATT_ERR_UNLIKELY, params, NULL, 0);
	}

done:
	bt_conn_unref(conn);
}

void on_nble_gattc_read_multi_rsp(const struct nble_gattc_read_rsp *rsp,
				     u8_t *data, u8_t len)
{
	struct bt_gatt_read_params *params = rsp->user_data;
	struct bt_conn *conn;

	conn = bt_conn_lookup_handle(rsp->conn_handle);
	if (!conn) {
		BT_ERR("Unable to find conn, handle 0x%04x", rsp->conn_handle);
		return;
	}

	BT_DBG("conn %p params %p status 0x%02x", conn, params, rsp->status);

	if (rsp->status) {
		params->func(conn, rsp->status, params, NULL, 0);
		goto done;
	}

	params->func(conn, 0, params, data, len);

	/* mark read as complete since read multiple is single response */
	params->func(conn, 0, params, NULL, 0);

done:
	bt_conn_unref(conn);
}

int bt_gatt_write(struct bt_conn *conn, struct bt_gatt_write_params *params)
{
	struct nble_gattc_write_req req;

	if (!conn || !params || !params->handle || !params->func) {
		return -EINVAL;
	}

	if (conn->state != BT_CONN_CONNECTED) {
		return -ENOTCONN;
	}

	if (conn->gatt_private) {
		return -EBUSY;
	}

	BT_DBG("conn %p handle 0x%04x offset 0x%04x len %u data %p",
	       conn, params->handle, params->offset, params->length,
	       params->data);

	memset(&req, 0, sizeof(req));

	req.conn_handle = conn->handle;
	req.handle = params->handle;
	req.offset = params->offset;
	req.with_resp = 1;

	conn->gatt_private = params;

	nble_gattc_write_req(&req, params->data, params->length);

	return 0;
}

static void gatt_write_ccc_rsp(struct bt_conn *conn, u8_t err,
			       struct bt_gatt_write_params *params)
{
	BT_DBG("conn %p err %u", conn, err);

	/* TODO: Remove failed subscription */
}

void on_nble_gattc_write_rsp(const struct nble_gattc_write_rsp *rsp)
{
	struct bt_conn *conn;
	void *private;
	bt_gatt_write_func_t func;

	conn = bt_conn_lookup_handle(rsp->conn_handle);
	if (!conn) {
		BT_ERR("Unable to find conn, handle 0x%04x", rsp->conn_handle);
		return;
	}

	BT_DBG("conn %p status %d", conn, rsp->status);

	private = gatt_get_private(conn);
	if (private == gatt_write_ccc_rsp) {
		func = gatt_write_ccc_rsp;
	} else {
		func = ((struct bt_gatt_write_params *)private)->func;
	}

	if (func) {
		func(conn, rsp->status, private);
	}

	bt_conn_unref(conn);
}

int bt_gatt_write_without_response(struct bt_conn *conn, u16_t handle,
				   const void *data, u16_t length,
				   bool sign)
{
	struct nble_gattc_write_req req;

	if (!conn || !handle) {
		return -EINVAL;
	}

	if (conn->state != BT_CONN_CONNECTED) {
		return -ENOTCONN;
	}

	if (conn->gatt_private) {
		return -EBUSY;
	}

	BT_DBG("conn %p handle 0x%04x len %u data %p sign %d",
	       conn, handle, length, data, sign);

	/* TODO: Handle signing */

	memset(&req, 0, sizeof(req));

	req.conn_handle = conn->handle;
	req.handle = handle;
	req.offset = 0;
	req.with_resp = 0;

	nble_gattc_write_req(&req, data, length);

	return 0;
}

static void gatt_subscription_add(struct bt_conn *conn,
				  struct bt_gatt_subscribe_params *params)
{
	bt_addr_le_copy(&params->_peer, &conn->dst);

	/* Prepend subscription */
	sys_slist_prepend(&subscriptions, &params->node);
}

static void gatt_subscription_remove(struct bt_conn *conn, sys_snode_t *prev,
				     struct bt_gatt_subscribe_params *params)
{
	/* Remove subscription from the list*/
	sys_slist_remove(&subscriptions, prev, &params->node);

	params->notify(conn, params, NULL, 0);
}

static void remove_subscriptions(struct bt_conn *conn)
{
	sys_snode_t *node, *tmp, *prev = NULL;

	/* Lookup existing subscriptions */
	SYS_SLIST_FOR_EACH_NODE_SAFE(&subscriptions, node, tmp) {
		struct bt_gatt_subscribe_params *params;

		params = CONTAINER_OF(node, struct bt_gatt_subscribe_params,
				      node);

		if (bt_addr_le_cmp(&params->_peer, &conn->dst)) {
			prev = node;
			continue;
		}

		if (params->flags & BT_GATT_SUBSCRIBE_FLAG_VOLATILE) {
			/* Remove subscription */
			params->value = 0;
			gatt_subscription_remove(conn, prev, params);
		}
	}
}

static int gatt_write_ccc(struct bt_conn *conn,
			  struct bt_gatt_subscribe_params *params)
{
	struct nble_gattc_write_req req;

	memset(&req, 0, sizeof(req));

	req.conn_handle = conn->handle;
	req.handle = params->ccc_handle;
	req.offset = 0;
	req.with_resp = 1;

	conn->gatt_private = gatt_write_ccc_rsp;

	nble_gattc_write_req(&req, (void *)&params->value,
			     sizeof(params->value));

	return 0;
}

int bt_gatt_subscribe(struct bt_conn *conn,
		      struct bt_gatt_subscribe_params *params)
{
	sys_snode_t *node;
	bool has_subscription = false;

	if (!conn || !params || !params->notify ||
	    !params->value || !params->ccc_handle) {
		return -EINVAL;
	}

	if (conn->state != BT_CONN_CONNECTED) {
		return -ENOTCONN;
	}

	BT_DBG("conn %p value_handle 0x%04x ccc_handle 0x%04x value 0x%04x",
	       conn, params->value_handle, params->ccc_handle, params->value);

	/* Lookup existing subscriptions */
	SYS_SLIST_FOR_EACH_NODE(&subscriptions, node) {
		struct bt_gatt_subscribe_params *tmp;

		tmp = CONTAINER_OF(node, struct bt_gatt_subscribe_params,
				   node);

		/* Fail if entry already exists */
		if (tmp == params) {
			return -EALREADY;
		}

		/* Check if another subscription exists */
		if (!bt_addr_le_cmp(&tmp->_peer, &conn->dst) &&
		    tmp->value_handle == params->value_handle &&
		    tmp->value >= params->value) {
			has_subscription = true;
		}
	}

	/* Skip write if already subscribed */
	if (!has_subscription) {
		int err;

		err = gatt_write_ccc(conn, params);
		if (err) {
			return err;
		}
	}

	/*
	 * Add subscription before write complete as some implementation were
	 * reported to send notification before reply to CCC write.
	 */
	gatt_subscription_add(conn, params);

	return 0;
}

void on_nble_gattc_value_evt(const struct nble_gattc_value_evt *ev,
			     u8_t *data, u8_t length)
{
	sys_snode_t *node, *tmp, *prev = NULL;
	struct bt_conn *conn;

	conn = bt_conn_lookup_handle(ev->conn_handle);
	if (!conn) {
		BT_ERR("Unable to find conn, handle 0x%04x", ev->conn_handle);
		return;
	}

	BT_DBG("conn %p value handle 0x%04x status %d data len %u",
	       conn, ev->handle, ev->status, length);

	SYS_SLIST_FOR_EACH_NODE_SAFE(&subscriptions, node, tmp) {
		struct bt_gatt_subscribe_params *params;

		params = CONTAINER_OF(node, struct bt_gatt_subscribe_params,
				      node);

		if (ev->handle != params->value_handle) {
			prev = node;
			continue;
		}

		if (params->notify(conn, params, data, length) ==
		    BT_GATT_ITER_STOP) {
			bt_gatt_unsubscribe(conn, params);
		} else {
			prev = node;
		}
	}

	bt_conn_unref(conn);
}

int bt_gatt_unsubscribe(struct bt_conn *conn,
			struct bt_gatt_subscribe_params *params)
{
	sys_snode_t *node, *next, *prev = NULL;
	struct bt_gatt_subscribe_params *found = NULL;
	bool has_subscription = false;

	if (!conn || !params) {
		return -EINVAL;
	}

	if (conn->state != BT_CONN_CONNECTED) {
		return -ENOTCONN;
	}

	BT_DBG("conn %p value_handle 0x%04x ccc_handle 0x%04x value 0x%04x",
	       conn, params->value_handle, params->ccc_handle, params->value);

	/* Lookup existing subscriptions */
	SYS_SLIST_FOR_EACH_NODE_SAFE(&subscriptions, node, next) {
		struct bt_gatt_subscribe_params *tmp;

		tmp = CONTAINER_OF(node, struct bt_gatt_subscribe_params,
				   node);

		/* Remove subscription */
		if (params == tmp) {
			found = params;
			sys_slist_remove(&subscriptions, prev, node);
			continue;
		} else {
			prev = node;
		}

		/* Check if there still remains any other subscription */
		if (!bt_addr_le_cmp(&tmp->_peer, &conn->dst) &&
		    tmp->value_handle == params->value_handle) {
			has_subscription = true;
		}
	}

	if (!found) {
		return -EINVAL;
	}

	if (has_subscription) {
		return 0;
	}

	BT_DBG("Current subscription %p value_handle 0x%04x value 0x%04x",
	       found, found->value_handle, found->value);

	/* Remove subscription bit */
	params->value = found->value & ~params->value;

	return gatt_write_ccc(conn, params);
}

void bt_gatt_cancel(struct bt_conn *conn, void *params)
{
	BT_DBG("");
}

static s32_t prep_write_evt(const struct nble_gatts_write_evt *ev,
			      const u8_t *data, u8_t len)
{
#if CONFIG_BLUETOOTH_ATT_PREPARE_COUNT > 0
	const struct bt_gatt_attr *attr = ev->attr;
	struct bt_conn *conn = bt_conn_lookup_handle(ev->conn_handle);
	struct net_buf *buf;
	ssize_t ret;

	BT_DBG("handle 0x%04x flag %d len %u", ev->attr->handle, ev->flag, len);

	if (!(attr->perm & BT_GATT_PERM_PREPARE_WRITE)) {
		return BT_GATT_ERR(BT_ATT_ERR_WRITE_NOT_PERMITTED);
	}

	/* Write attribute value to check if device is authorired */
	ret = attr->write(conn, attr, data, len, ev->offset,
			  BT_GATT_WRITE_FLAG_PREPARE);
	if (ret != 0) {
		return ret;
	}

	buf = net_buf_alloc(&prep_pool, K_NO_WAIT);
	if (!buf) {
		BT_ERR("No more buffers for prepare write");
		return BT_GATT_ERR(BT_ATT_ERR_PREPARE_QUEUE_FULL);
	}

	/* Copy data into the outstanding queue */
	memcpy(net_buf_user_data(buf), ev, sizeof(*ev));
	net_buf_add_mem(buf, data, len);

	k_fifo_put(&queue, buf);

	return 0;
#else
	return BT_GATT_ERR(BT_ATT_ERR_NOT_SUPPORTED);
#endif
}

static s32_t write_evt(struct bt_conn *conn,
			 const struct bt_gatt_attr *attr,
			 u16_t offset, const u8_t *data, u8_t len)
{
	s32_t status;

	status = attr->write(conn, attr, data, len, offset, 0);
	if (status < 0) {
		return status;
	}

	/* Return an error if not all data has been written */
	if (status != len) {
		return BT_GATT_ERR(BT_ATT_ERR_UNLIKELY);
	}

	return status;
}

void on_nble_gatts_write_evt(const struct nble_gatts_write_evt *ev,
			     const u8_t *buf, u8_t buflen)
{
	const struct bt_gatt_attr *attr = ev->attr;
	struct bt_conn *conn = bt_conn_lookup_handle(ev->conn_handle);
	struct nble_gatts_write_reply_req reply_data;

	BT_DBG("attr handle 0x%04x flag %d len %u", attr->handle, ev->flag,
	       buflen);

	/* Check for write support and flush support in case of prepare */
	if (!attr->write) {
		reply_data.status = BT_GATT_ERR(BT_ATT_ERR_WRITE_NOT_PERMITTED);

		goto reply;
	}

	if (ev->flag & NBLE_GATT_WR_FLAG_PREP) {
		reply_data.status = prep_write_evt(ev, buf, buflen);
		goto reply;
	}

	reply_data.status = write_evt(conn, attr, ev->offset, buf, buflen);

reply:
	if (ev->flag & NBLE_GATT_WR_FLAG_REPLY) {
		reply_data.conn_handle = ev->conn_handle;
		reply_data.offset = ev->offset;

		nble_gatts_write_reply_req(&reply_data, buf, buflen);
	}

	if (conn) {
		bt_conn_unref(conn);
	}
}

void on_nble_gatts_write_exec_evt(const struct nble_gatts_write_exec_evt *evt)
{
	struct bt_conn *conn;
	struct net_buf *buf;
	struct nble_gatts_write_reply_req rsp = {
		.conn_handle = evt->conn_handle,
		.status = 0,
	};

	BT_DBG("handle 0x%04x flag %u", evt->conn_handle, evt->flag);

	conn = bt_conn_lookup_handle(evt->conn_handle);
	if (!conn) {
		BT_ERR("Unable to find conn, handle 0x%04x", evt->conn_handle);
		return;
	}

	while ((buf = k_fifo_get(&queue, K_NO_WAIT))) {
		struct nble_gatts_write_evt *ev = net_buf_user_data(buf);
		const struct bt_gatt_attr *attr = ev->attr;

		/* Skip buffer for other connections */
		if (ev->conn_handle != evt->conn_handle) {
			k_fifo_put(&queue, buf);
			continue;
		}

		/*
		 * Dispatch the callback in case of success (status >= 0).
		 * Ignore in case of error (status < 0).
		 */
		if (rsp.status >= 0 && evt->flag == 1) {
			rsp.status = write_evt(conn, attr, ev->offset,
					       buf->data, buf->len);
		}

		net_buf_unref(buf);
	}

	nble_gatts_write_reply_req(&rsp, NULL, 0);

	bt_conn_unref(conn);
}

void on_nble_gatts_read_evt(const struct nble_gatts_read_evt *ev)
{
	struct nble_gatts_read_reply_req reply_data;
	const struct bt_gatt_attr *attr;
	/* TODO: Replace the following with net_buf */
	u8_t data[BLE_GATT_MTU_SIZE] = { 0 };
	int len;

	attr = ev->attr;

	BT_DBG("attr %p offset %u", attr, ev->offset);

	memset(&reply_data, 0, sizeof(reply_data));

	if (attr->read) {
		struct bt_conn *conn = bt_conn_lookup_handle(ev->conn_handle);

		len = attr->read(conn, attr, data, sizeof(data), ev->offset);

		if (conn) {
			bt_conn_unref(conn);
		}
	} else {
		len = BT_GATT_ERR(BT_ATT_ERR_NOT_SUPPORTED);
	}

	if (len >= 0) {
		reply_data.status = 0;
		reply_data.offset = ev->offset;
	} else {
		reply_data.status = len;
		len = 0;
	}

	reply_data.conn_handle = ev->conn_handle;

	nble_gatts_read_reply_req(&reply_data, data, len);
}

void bt_gatt_init(void)
{
	BT_DBG("");
}

void bt_gatt_connected(struct bt_conn *conn)
{
	/* Allow to send first notification */
	k_sem_init(&conn->gatt_notif_sem, 1, UINT_MAX);
}

void bt_gatt_disconnected(struct bt_conn *conn)
{
	struct net_buf *buf;

	BT_DBG("conn %p", conn);

#if CONFIG_BLUETOOTH_ATT_PREPARE_COUNT > 0
	/* Discard queued buffers */
	while ((buf = k_fifo_get(&queue, K_NO_WAIT))) {
		net_buf_unref(buf);
	}
#endif

	conn->gatt_private = NULL;

	/* TODO: If bonded don't remove subscriptions */
	remove_subscriptions(conn);
}


text:
namespace ical {
namespace properties {

const std::string RelatedTo::NAME = "RELATED-TO";

void RelatedTo::print(std::ostream &out) const {
    out << NAME;
    for(auto &i : reltypeParam) i.print(out);
    out << ":" << core::ValueParser::encodeText(value) << "\r\n";
}

RelatedTo RelatedTo::parse(const core::WithPos<core::GenericProperty> &generic) {
    if(generic->getName().value() != NAME)
        throw ParserException(generic.pos() , "invalid name in " + NAME + " property");
    if(generic->getValue()->empty())
        throw ParserException(generic.pos() , "empty property");

    auto &value = generic->getValue();

    RelatedTo relto;
    relto.value = std::move(core::ValueParser::parseText(
                                value.pos(), value->begin(), value->end()));

    for(const auto &i : generic->getParameters()) {
        if(i->getName().value() == parameters::Reltype::NAME) {
            if(!relto.reltypeParam.empty())
                throw ParserException(i.pos() ,
                                      parameters::Reltype::NAME + " parameter can't occurr multiple times");
            relto.reltypeParam.push_back(parameters::Reltype::parse(i));

        } else {
            throw ParserException(i.pos() , "invalid parameter in " + NAME + " property");
        }
    }
    return relto;
}

} // namespace properties
} // namespace ical

redpajama_set_name: RedPajamaGithub


text:
layout: post
title: "Kocaeli Üniversitesi IT Fest Etkinliği Ekim 2017"
date: 2017-10-05 16:30
author: engin.polat
comments: true
category: [Etkinlik]
tags: [etkinliklerim, seminer, web, azure, angular, aspnetcore]
---
_04 Ekim 2017_ tarihinde _Kocaeli Üniversitesi Bilişim Teknolojileri Kulübü_ tarafından organize edilen **IT Fest 2017** etkinliği gerçekleştirildi.

Ben ve sevgili arkadaşım _Bora Kaşmer_ de **.Net Core ve Angular ile oluşturulan projenin Azure'da yayınlanması** konulu oturumda _canlı kodlama_ (**live-coding**) yaptık.

<img class="lazy img-responsive" data-src="/assets/uploads/2017/10/itfest2017.png" width="600" height="840" />

Katılan tüm arkadaşlara _teşekkür ederim_


text:
const authHeader = require('./auth-header');
const makeRequest = require('./make-request');

const isReservedHeading = (context, str) => {
  const reservedHeadings = [
    'after-user-code',
    'answers',
    'before-user-code',
    'description',
    'fcc-editable-region',
    'hints',
    'instructions',
    'question',
    'seed',
    'seed-contents',
    'solutions',
    'text',
    'video-solution'
  ];
  const captureGroupStr = `(${reservedHeadings.join('|')})`;
  const regex = new RegExp(`--${captureGroupStr}--`);
  return !!(context.match(/^Headline/) && str.match(regex));
};

const isCode = str => /^\/pre\/code|\/code$/.test(str);

const isTitle = str => str.endsWith('title');

const shouldHide = (text, context, challengeTitle, crowdinFilePath) => {
  if (crowdinFilePath.endsWith('.yml')) {
    return !isTitle(context);
  }
  if (isReservedHeading(context, text) || isCode(context)) {
    return true;
  }
  return text !== challengeTitle && context.includes('id=front-matter');
};

const getStrings = async ({ projectId, fileId }) => {
  let headers = { ...authHeader };
  let done = false;
  let offset = 0;
  let strings = [];
  while (!done) {
    let endPoint = `projects/${projectId}/strings?limit=500&offset=${offset}`;
    if (fileId) {
      endPoint += `&fileId=${fileId}`;
    }
    const response = await makeRequest({ method: 'get', endPoint, headers });
    if (response.data) {
      if (response.data.length) {
        strings = [...strings, ...response.data];
        offset += 500;
      } else {
        done = true;
        return strings;
      }
    } else {
      const { error, errors } = response;
      console.error(error ? error : errors);
    }
  }
  return null;
};

const updateString = async ({ projectId, stringId, propsToUpdate }) => {
  let headers = { ...authHeader };
  const endPoint = `projects/${projectId}/strings/${stringId}`;
  const body = propsToUpdate.map(({ path, value }) => ({
    op: 'replace',
    path,
    value
  }));
  await makeRequest({
    method: 'patch',
    endPoint,
    headers,
    body
  });
};

const changeHiddenStatus = async (projectId, stringId, newStatus) => {
  await updateString({
    projectId,
    stringId,
    propsToUpdate: [{ path: '/isHidden', value: newStatus }]
  });
};

const updateFileStrings = async ({ projectId, fileId, challengeTitle }) => {
  const fileStrings = await getStrings({
    projectId,
    fileId
  });

  for (let {
    data: { id: stringId, text, isHidden, context }
  } of fileStrings) {
    const hideString = shouldHide(text, context, challengeTitle);
    if (!isHidden && hideString) {
      changeHiddenStatus(projectId, stringId, true);
    } else if (isHidden && !hideString) {
      changeHiddenStatus(projectId, stringId, false);
    }
  }
};

const updateFileString = async ({
  projectId,
  string,
  challengeTitle,
  crowdinFilePath
}) => {
  const {
    data: { id: stringId, text, isHidden, context }
  } = string;
  const hideString = shouldHide(text, context, challengeTitle, crowdinFilePath);
  if (!isHidden && hideString) {
    await changeHiddenStatus(projectId, stringId, true);
    console.log(
      `${challengeTitle} - stringId: ${stringId} - changed isHidden to true`
    );
  } else if (isHidden && !hideString) {
    await changeHiddenStatus(projectId, stringId, false);
    console.log(
      `${challengeTitle} - stringId: ${stringId} - changed isHidden to false`
    );
  }
};

const getStringTranslations = async ({ projectId, stringId, languageId }) => {
  let headers = { ...authHeader };
  let done = false;
  let offset = 0;
  let translations = [];
  while (!done) {
    let endPoint = `projects/${projectId}/translations?stringId=${stringId}&languageId=${languageId}&limit=500&offset=${offset}`;
    const response = await makeRequest({ method: 'get', endPoint, headers });
    if (response.data) {
      if (response.data.length) {
        translations = [...translations, ...response.data];
        offset += 500;
      } else {
        done = true;
        return translations;
      }
    } else {
      const { error, errors } = response;
      console.error(
        error ? JSON.stringify(error, null, 2) : JSON.stringify(errors, null, 2)
      );
    }
  }
  return null;
};

const deleteTranslation = async (projectId, translationId) => {
  let headers = { ...authHeader };
  const endPoint = `projects/${projectId}/translations/${translationId}`;
  await makeRequest({
    method: 'delete',
    endPoint,
    headers
  });
  console.log(`Deleted translationId ${translationId} from Crowdin project`);
  return null;
};

const addTranslation = async (projectId, stringId, languageId, text) => {
  let headers = { ...authHeader };
  const endPoint = `projects/${projectId}/translations`;
  const body = {
    stringId,
    languageId,
    text
  };
  const response = await makeRequest({
    method: 'post',
    endPoint,
    headers,
    body
  });
  if (response.data) {
    return response.data;
  }
  return null;
};

const getLanguageTranslations = async ({ projectId, languageId }) => {
  let headers = { ...authHeader };
  let done = false;
  let offset = 0;
  let translations = [];
  while (!done) {
    let endPoint = `projects/${projectId}/languages/${languageId}/translations?limit=500&offset=${offset}`;
    const response = await makeRequest({ method: 'get', endPoint, headers });
    if (response.data) {
      if (response.data.length) {
        translations = [...translations, ...response.data];
        offset += 500;
      } else {
        done = true;
        return translations;
      }
    } else {
      const { error, errors } = response;
      console.error(
        error ? JSON.stringify(error, null, 2) : JSON.stringify(errors, null, 2)
      );
    }
  }
  return null;
};

const deleteLanguageTranslations = async (projectId, languageId, stringId) => {
  let headers = { ...authHeader };
  const endPoint = `projects/${projectId}/translations?languageId=${languageId}&stringId=${stringId}`;
  console.log(`deleting ${stringId}...`);
  await makeRequest({
    method: 'delete',
    endPoint,
    headers
  });
  return null;
};

module.exports = {
  getStrings,
  updateString,
  updateFileStrings,
  updateFileString,
  getStringTranslations,
  addTranslation,
  deleteTranslation,
  getLanguageTranslations,
  deleteLanguageTranslations,
  changeHiddenStatus
};


text:
define(function(require, exports, module) {

    var Widget = require('widget');

    var PlayerFactory = Widget.extend({
        attrs: {
        },

        events: {
        },

        setup: function() {
        },

        create: function(type, options){
            switch(type){
                case "local-video-player":
                    var LocalVideoPlayer = require('./local-video-player');
                    return new LocalVideoPlayer(options);
                    break;
                case "cloud-video-player":
                    var CloudVideoPlayer = require('./cloud-video-player');
                    return new CloudVideoPlayer(options);
                    break;
                case "balloon-cloud-video-player":
                    var BalloonVideoPlayer = require('./balloon-cloud-video-player');
                    return new BalloonVideoPlayer(options);
                    break;
                case "audio-player":
                    var AudioPlayer = require('./audio-player');
                    return new AudioPlayer(options);
                    break;
            }

        },

        destroy: function(){
        }
    });

    module.exports = PlayerFactory;

});


text:
package com.db4o.internal.references;

import com.db4o.foundation.*;
import com.db4o.internal.*;

/**
 * @exclude
 */
public interface ReferenceSystem {

	public void addNewReference(ObjectReference ref);

	public void addExistingReference(ObjectReference ref);

	public void commit();

	public ObjectReference referenceForId(int id);

	public ObjectReference referenceForObject(Object obj);

	public void removeReference(ObjectReference ref);

	public void rollback();

	public void traverseReferences(Visitor4 visitor);

	public void discarded();

}


text:
import java.io.DataInputStream;
import java.net.URL;
import net.runelite.mapping.Export;
import net.runelite.mapping.Implements;
import net.runelite.mapping.ObfuscatedGetter;
import net.runelite.mapping.ObfuscatedName;
import net.runelite.mapping.ObfuscatedSignature;

@ObfuscatedName("ci")
@Implements("AttackOption")
public enum AttackOption implements Enumerated {
   @ObfuscatedName("o")
   @ObfuscatedSignature(
      signature = "Lci;"
   )
   @Export("AttackOption_dependsOnCombatLevels")
   AttackOption_dependsOnCombatLevels(0),
   @ObfuscatedName("k")
   @ObfuscatedSignature(
      signature = "Lci;"
   )
   @Export("AttackOption_alwaysRightClick")
   AttackOption_alwaysRightClick(1),
   @ObfuscatedName("t")
   @ObfuscatedSignature(
      signature = "Lci;"
   )
   @Export("AttackOption_leftClickWhereAvailable")
   AttackOption_leftClickWhereAvailable(2),
   @ObfuscatedName("d")
   @ObfuscatedSignature(
      signature = "Lci;"
   )
   @Export("AttackOption_hidden")
   AttackOption_hidden(3);

   @ObfuscatedName("u")
   static int[][] field1354;
   @ObfuscatedName("n")
   static int[] field1356;
   @ObfuscatedName("r")
   @ObfuscatedGetter(
      intValue = 1565234007
   )
   static int field1348;
   @ObfuscatedName("h")
   @ObfuscatedGetter(
      intValue = -244735519
   )
   @Export("id")
   final int id;

   AttackOption(int var3) {
      this.id = var3;
   }

   @ObfuscatedName("o")
   @ObfuscatedSignature(
      signature = "(I)I",
      garbageValue = "-369819377"
   )
   public int rsOrdinal() {
      return this.id;
   }

   @ObfuscatedName("o")
   @ObfuscatedSignature(
      signature = "(Ljava/lang/String;Ljava/lang/Throwable;I)V",
      garbageValue = "98048"
   )
   @Export("processClientError")
   public static void processClientError(String var0, Throwable var1) {
      if(var1 != null) {
         var1.printStackTrace();
      } else {
         try {
            String var2 = "";
            if(var1 != null) {
               var2 = JagexGame.method4521(var1);
            }

            if(var0 != null) {
               if(var1 != null) {
                  var2 = var2 + " | ";
               }

               var2 = var2 + var0;
            }

            System.out.println("Error: " + var2);
            var2 = var2.replace(':', '.');
            var2 = var2.replace('@', '_');
            var2 = var2.replace('&', '_');
            var2 = var2.replace('#', '_');
            if(RunException.field2198 == null) {
               return;
            }

            URL var3 = new URL(RunException.field2198.getCodeBase(), "clienterror.ws?c=" + RunException.revision + "&u=" + RunException.field2194 + "&v1=" + Signlink.javaVendor + "&v2=" + Signlink.javaVersion + "&e=" + var2);
            DataInputStream var4 = new DataInputStream(var3.openStream());
            var4.read();
            var4.close();
         } catch (Exception var5) {
            ;
         }

      }
   }

   @ObfuscatedName("hh")
   @ObfuscatedSignature(
      signature = "(III)V",
      garbageValue = "882108004"
   )
   static final void method1903(int var0, int var1) {
      if(Client.menuOptionCount >= 2 || Client.itemSelectionState != 0 || Client.spellSelected) {
         if(Client.field1017) {
            int var2 = Client.menuOptionCount - 1;
            String var4;
            if(Client.itemSelectionState == 1 && Client.menuOptionCount < 2) {
               var4 = "Use" + " " + Client.lastSelectedItemName + " " + "->";
            } else if(Client.spellSelected && Client.menuOptionCount < 2) {
               var4 = Client.field1092 + " " + Client.field1028 + " " + "->";
            } else {
               String var5;
               if(var2 < 0) {
                  var5 = "";
               } else if(Client.menuTargets[var2].length() > 0) {
                  var5 = Client.menuOptions[var2] + " " + Client.menuTargets[var2];
               } else {
                  var5 = Client.menuOptions[var2];
               }

               var4 = var5;
            }

            if(Client.menuOptionCount > 2) {
               var4 = var4 + class45.getColTags(16777215) + " " + '/' + " " + (Client.menuOptionCount - 2) + " more options";
            }

            MessageNode.fontBold12.drawRandomizedMouseoverText(var4, var0 + 4, var1 + 15, 16777215, 0, Client.gameCycle / 1000);
         }
      }
   }
}


text:
package jp.seraphr.fileupload.main

import org.eclipse.jetty.server.{ Handler, Server }
import org.eclipse.jetty.server.handler.{ DefaultHandler, HandlerList, ResourceHandler }
import org.eclipse.jetty.webapp.WebAppContext
import org.scalatra.servlet.ScalatraListener

/**
 */
object FileUploadServerMain extends App {
  val tPort = 8080

  val tServer = new Server(tPort)
  val tContext = new WebAppContext()
  tContext.setContextPath("/")
  tContext.setResourceBase("src/main/webapp")
  tContext.addEventListener(new ScalatraListener)
  tContext.setInitParameter(ScalatraListener.LifeCycleKey, classOf[ScalatraBootstrap].getName)

  val tResourceHandler = new ResourceHandler()
  tResourceHandler.setDirectoriesListed(true)
  tResourceHandler.setWelcomeFiles(Array("index.html"))
  //  tResourceHandler.setResourceBase("..")
  tResourceHandler.setResourceBase("../webapp/assets/")

  val tHandlers = new HandlerList()
  tHandlers.setHandlers(Array[Handler](tResourceHandler, tContext, new DefaultHandler()))
  tServer.setHandler(tHandlers)

  tServer.start()
  tServer.join()
}


text:
package ch.swissonid.design_lib_sample.adapters;

import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

import ch.swissonid.design_lib_sample.R;
import ch.swissonid.design_lib_sample.fragments.tabs.TabFragment;

public class PagerAdapter extends FragmentPagerAdapter {

    private Context mContext;

    public PagerAdapter(FragmentManager fm, Context context) {
        super(fm);
        mContext = context;
    }

    @Override
    public Fragment getItem(int position) {
        return TabFragment.newInstance(getOffset(position));
    }

    private int getOffset(int position){
        switch (position){
            case 0: return 0;
            case 1: return 5;
            case 2: return 10;
            case 3: return 15;
        }
        return 0;
    }

    @Override
    public int getCount() {
        return 4;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        String title = mContext.getString(R.string.not_title_set);
        switch (position) {
            case 0:
                title = mContext.getString(R.string.pop_title);
                break;
            case 1:
                title = mContext.getString(R.string.indie_title);
                break;
            case 2:
                title = mContext.getString(R.string.rock_title);
                break;
            case 3:
                title = mContext.getString(R.string.r8b_title);
                break;
        }
        return title;
    }

}


text:
include_recipe 'jenkins::master'

# Include the create recipe so we have something to delete
include_recipe 'jenkins_slave::create_ssh'

%w(ssh-builder ssh-executor ssh-smoke).each do |name|
  jenkins_ssh_slave name do
    action :delete
  end
end


text:
package main

import (
	"fmt"
	"encoding/json"

	"github.com/gocircuit/circuit/client"
	"github.com/gocircuit/circuit/client/docker"

	"github.com/gocircuit/circuit/github.com/codegangsta/cli"
)

// circuit peek /X1234/hola/charlie
func peek(x *cli.Context) {
	defer func() {
		if r := recover(); r != nil {
			fatalf("error, likely due to missing server or misspelled anchor: %v", r)
		}
	}()
	c := dial(x)
	args := x.Args()
	if len(args) != 1 {
		fatalf("peek needs one anchor argument")
	}
	w, _ := parseGlob(args[0])
	switch t := c.Walk(w).Get().(type) {
	case client.Server:
		buf, _ := json.MarshalIndent(t.Peek(), "", "\t")
		fmt.Println(string(buf))
	case client.Chan:
		buf, _ := json.MarshalIndent(t.Stat(), "", "\t")
		fmt.Println(string(buf))
	case client.Proc:
		buf, _ := json.MarshalIndent(t.Peek(), "", "\t")
		fmt.Println(string(buf))
	case client.Nameserver:
		buf, _ := json.MarshalIndent(t.Peek(), "", "\t")
		fmt.Println(string(buf))
	case docker.Container:
		stat, err := t.Peek()
		if err != nil {
			fatalf("%v", err)
		}
		buf, _ := json.MarshalIndent(stat, "", "\t")
		fmt.Println(string(buf))
	case client.Subscription:
		buf, _ := json.MarshalIndent(t.Peek(), "", "\t")
		fmt.Println(string(buf))
	case nil:
		buf, _ := json.MarshalIndent(nil, "", "\t")
		fmt.Println(string(buf))
	default:
		fatalf("unknown element")
	}
}

func scrb(x *cli.Context) {
	defer func() {
		if r := recover(); r != nil {
			fatalf("error, likely due to missing server or misspelled anchor: %v", r)
		}
	}()
	c := dial(x)
	args := x.Args()
	if len(args) != 1 {
		fatalf("scrub needs one anchor argument")
	}
	w, _ := parseGlob(args[0])
	c.Walk(w).Scrub()
}


text:
package providers

import "net/http"

// RequestParamsMock ...
type RequestParamsMock struct {
	Params map[string]string
}

// Get ...
func (r *RequestParamsMock) Get(req *http.Request) map[string]string {
	return r.Params
}


text:
var CollectionPrototypeGenerator = require("collection_prototype_generator");

// ----------------------------------------------------------------------------
var set_1 = [
    ["Budapest", "images/db_icons/1.png", "", "sites_collection"],
    ["Bánkút", "images/db_icons/2.png"]
];

var testData = [set_1];

// ----------------------------------------------------------------------------
module.exports = CollectionPrototypeGenerator({
    collectionTitleId: "places",
    viewControllerName: "simple_table_view",
    text_id: false,
    testData: testData,
    id: "places_table",
    refreshable: true
});


text:
namespace remoting {

class PepperPacketSocketFactory : public rtc::PacketSocketFactory {
 public:
  explicit PepperPacketSocketFactory(const pp::InstanceHandle& instance);
  ~PepperPacketSocketFactory() override;

  rtc::AsyncPacketSocket* CreateUdpSocket(
      const rtc::SocketAddress& local_address,
      uint16 min_port,
      uint16 max_port) override;
  rtc::AsyncPacketSocket* CreateServerTcpSocket(
      const rtc::SocketAddress& local_address,
      uint16 min_port,
      uint16 max_port,
      int opts) override;
  rtc::AsyncPacketSocket* CreateClientTcpSocket(
      const rtc::SocketAddress& local_address,
      const rtc::SocketAddress& remote_address,
      const rtc::ProxyInfo& proxy_info,
      const std::string& user_agent,
      int opts) override;
  rtc::AsyncResolverInterface* CreateAsyncResolver() override;

 private:
  const pp::InstanceHandle pp_instance_;

  DISALLOW_COPY_AND_ASSIGN(PepperPacketSocketFactory);
};

}  // namespace remoting

#endif  // REMOTING_CLIENT_PLUGIN_PEPPER_PACKET_SOCKET_FACTORY_H_


text:
#ifndef BIO_MATH_H_
#define BIO_MATH_H_

#include "bio/defs.h"
#include "bio/gsl.h"

#include <boost/io/ios_state.hpp>

#include <gsl/gsl_sf_gamma.h>
#include <gsl/gsl_sf_log.h>
#include <gsl/gsl_sf_exp.h>

#include <numeric>

BIO_NS_START

/** Calculates the log of n choose the observed counts.  */
template < typename ObsIt >
double
calc_ln_n_choose(
	ObsIt obs_begin,
	ObsIt obs_end)
{
	double result = 0.0;

	unsigned n = 0;
	while (obs_end != obs_begin)
	{
		result -= gsl_sf_lnfact(*obs_begin);
		n += *obs_begin;

		++obs_begin;
	}

	result += gsl_sf_lnfact(n);

	return result;
}

/** Calculates a factor involved in the likelihood of a multinomial distribution with a dirichlet prior. */
template < typename ObsIt, typename AlphaIt >
double
calc_ln_gamma_factor(
	ObsIt obs_begin,
	ObsIt obs_end,
	AlphaIt alpha_begin)
{
	double ln_pi_gamma_alpha_obs = 0.0; //work in logarithms
	double ln_pi_gamma_alpha = 0.0; //work in logarithms
	double sum_alpha = 0.0;
	double sum_obs = 0.0;
	while (obs_end != obs_begin)
	{
		sum_alpha += *alpha_begin;
		sum_obs += *obs_begin;
		ln_pi_gamma_alpha += gsl_sf_lngamma(*alpha_begin);
		ln_pi_gamma_alpha_obs += gsl_sf_lngamma(*alpha_begin + *obs_begin);

		++obs_begin;
		++alpha_begin;
	}

	double ln_result =
		gsl_sf_lngamma(sum_alpha)
		- ln_pi_gamma_alpha
		+ ln_pi_gamma_alpha_obs
		- gsl_sf_lngamma(sum_alpha + sum_obs);

	return ln_result;
}

/** Calculates the log of the likelihood of seeing the observed counts under a dirichlet prior. */
template < typename ObsIt, typename AlphaIt >
double
calc_multinomial_ln_likelihood_dirichlet_prior(
	ObsIt obs_begin,
	ObsIt obs_end,
	AlphaIt alpha_begin)
{
	return calc_ln_gamma_factor(obs_begin, obs_end, alpha_begin) + calc_ln_n_choose(obs_begin, obs_end);
}

/** Calculates the log of the likelihood of seeing the observed counts under a uniform multinomial distribution. */
template < typename ObsIt >
double
calc_multinomial_ln_likelihood_uniform_dist(
	ObsIt obs_begin,
	ObsIt obs_end)
{
	const unsigned n = std::accumulate(obs_begin, obs_end, unsigned(0));
	if (0 == n)
	{
		return 0.0;
	}

	const double ln_n_choose = calc_ln_n_choose(obs_begin, obs_end);
	return ln_n_choose - n * gsl_sf_log(double(obs_end - obs_begin));
}

/** Calculates the log of the likelihood of seeing the observed counts under a multinomial distribution with given p's. */
template < typename ObsIt, typename PIt >
double
calc_multinomial_ln_likelihood(
	ObsIt obs_begin,
	ObsIt obs_end,
	PIt p_begin)
{
	const unsigned n = std::accumulate(obs_begin, obs_end, unsigned(0));
	if (0 == n)
	{
		return 0.0;
	}

	double result = calc_ln_n_choose(obs_begin, obs_end);
	while (obs_end != obs_begin)
	{
		result += *obs_begin * gsl_sf_log(*p_begin);

		++obs_begin;
		++p_begin;
	}

	return result;
}

/** Calculates the ratio of evidence in favour of a uniform distribution over one with a dirichlet prior
defined by the alphas. */
template < typename ObsIt, typename AlphaIt >
double
calc_ln_multinomial_uniform_evidence(
	ObsIt obs_begin,
	ObsIt obs_end,
	AlphaIt alpha_begin)
{
	const double ln_likelihood_uniform_dist = calc_multinomial_ln_likelihood_uniform_dist(obs_begin, obs_end);
	const double ln_likelihood_dirichlet_prior = calc_multinomial_ln_likelihood_dirichlet_prior(obs_begin, obs_end, alpha_begin);
	return ln_likelihood_uniform_dist - ln_likelihood_dirichlet_prior;
}

/** Calculates the ratio of evidence in favour of a particular multinomial distribution (defined by the p's)
over one with a dirichlet prior defined by the alpha's. */
template < typename ObsIt, typename AlphaIt, typename PIt >
double
calc_ln_multinomial_evidence(
	ObsIt obs_begin,
	ObsIt obs_end,
	AlphaIt alpha_begin,
	PIt p_begin)
{
	return
		calc_multinomial_ln_likelihood(obs_begin, obs_end, p_begin)
		- calc_multinomial_ln_likelihood_dirichlet_prior(obs_begin, obs_end, alpha_begin);
}

BIO_NS_END

#endif //BIO_MATH_H_


text:
A `birthdays.sql` file has been created and opened for you.
Click on it and type a _SELECT * FROM_ statement that gets only the rows that contain birthdays for 2016 plus sorting them by date order:

```
--- In your birthdays.sql file:

USE people;

SELECT * FROM basic_info
WHERE birthday > '2016'
ORDER BY birthday;
```

Source it:

```
mysql> source birthdays.sql
```
And you should see this:
```
+----+-------------------------------------+------------+-----------+-------------+
| id | email                               | birthday   | country   | city        |
+----+-------------------------------------+------------+-----------+-------------+
|  3 | tincidunt.tempus.risus@acurnaUt.com | 2016-03-05 | Comoros   | Enines      |
| 10 | non.cursus@duinec.edu               | 2016-04-17 | Guatemala | Ilbono      |
|  4 | sed.pede@nisi.com                   | 2016-07-17 | Kiribati  | Frankenthal |
|  6 | imperdiet.nec.leo@nec.ca            | 2016-07-22 | Hong Kong | Richmond    |
+----+-------------------------------------+------------+-----------+-------------+
4 rows in set (0.00 sec)
```

Get ready for a challenge in the next section.


text:
RUN_DIR=`pwd`

function help {
    echo "Choose one of the following: {build|run|deploy|clean}"
    exit 1
}

if [ $# -eq 0 ]
then
    help
fi

APP_NAME="demo_client"
PROJECT_HOME=$(pwd)
BUILD_DIR="build"
LIBS_PATH="libs"
KAA_LIB_PATH="$LIBS_PATH/kaa"
KAA_C_LIB_HEADER_PATH="$KAA_LIB_PATH/src"
KAA_CPP_LIB_HEADER_PATH="$KAA_LIB_PATH/kaa"
KAA_SDK_TAR="kaa-c*.tar.gz"

#Wifi settings
SSID="xxx"
PASSWORD="xxxxxxxxx"
#Firmware version
MAJOR_VERSION=1
MINOR_VERSION=0
DEMO_LED=0

function build_app {
    read -p "Enter WiFi SSID: " SSID
    read -p "Enter WiFi Password: " PASSWORD
    read -p "Enter firmware major version: " MAJOR_VERSION
    read -p "Enter firmware minor version: " MINOR_VERSION
    read -p "Enter firmware classifier: " CLASSIFIER_VERSION
    read -p "Enter flags of an active leds[ red=0x01 orange=0x02 green=0x04 ]: " DEMO_LED

    if [ -z $DEMO_LED ]
    then
        DEMO_LED=0
    fi

    cd $PROJECT_HOME &&
    mkdir -p "$PROJECT_HOME/$BUILD_DIR" &&
    cd $BUILD_DIR
    cmake -DKAA_PLATFORM=cc32xx -DCMAKE_TOOLCHAIN_FILE=../libs/kaa/toolchains/cc32xx.cmake -DBUILD_TESTING=OFF -DSSID=$SSID -DPWD=$PASSWORD -DMAJOR_VERSION=$MAJOR_VERSION -DMINOR_VERSION=$MINOR_VERSION $ENV_VAR -DCLASSIFIER_VERSION=$CLASSIFIER_VERSION -DDEMO_LED="$DEMO_LED" ..
    make
}

function clean {
    rm -rf "$KAA_LIB_PATH/$BUILD_DIR"
    rm -rf "$PROJECT_HOME/$BUILD_DIR"
}

function run {
    mkdir -p $PROJECT_HOME/../../fmw_bin
    cp $PROJECT_HOME/$BUILD_DIR/demo_client.bin $PROJECT_HOME/../../fmw_bin/demo_client_0x0$DEMO_LED.bin
}

#for cmd in $@
#do
cmd=$1

case "$cmd" in
    build)
        build_app
    ;;

    run)
        run
    ;;

    deploy)
        clean
        build_app
        run
        ;;

    clean)
        clean
    ;;

    *)
        help
    ;;
esac


text:
from distutils.version import LooseVersion
import warnings

_NUMEXPR_INSTALLED = False
_MIN_NUMEXPR_VERSION = "2.6.1"
_NUMEXPR_VERSION = None

try:
    import numexpr as ne
    ver = LooseVersion(ne.__version__)
    _NUMEXPR_INSTALLED = ver >= LooseVersion(_MIN_NUMEXPR_VERSION)
    _NUMEXPR_VERSION = ver

    if not _NUMEXPR_INSTALLED:
        warnings.warn(
            "The installed version of numexpr {ver} is not supported "
            "in pandas and will be not be used\nThe minimum supported "
            "version is {min_ver}\n".format(
                ver=ver, min_ver=_MIN_NUMEXPR_VERSION), UserWarning)

except ImportError:  # pragma: no cover
    pass

__all__ = ['_NUMEXPR_INSTALLED', '_NUMEXPR_VERSION']


text:
The attachments section allows you upload or reference files that support the message. e.g. transcripts,
        outlines, notes, slides, etc.
        <?php while ($mb->have_fields_and_multi('attachment')): ?>
        <?php $mb->the_group_open(); ?>

        <?php $mb->the_field('url'); ?>

            URL:

                Remove Attachment
                <input type="text" name="<?php $mb->the_name(); ?>" value="<?php $mb->the_value(); ?>"
                       class="regular-text"/>
                <input class="button media_button" type="button" value="Upload Attachment"
                       data-title="Choose Attachment" data-select="Select Attachment"/>

Enter the URL to an attachment, upload a file from your computer, or select a
                    file from the media library. e.g. http://www.example.com/homework.pdf

                <?php $mb->the_field('url-id'); ?>
                <input name="<?php $mb->the_name() ?>" type="hidden" value="<?php $mb->the_value() ?>"/>

        <?php $mb->the_field('title'); ?>

            <label for="<?php $mb->the_name(); ?>">Title:
            <input type="text" name="<?php $mb->the_name(); ?>" value="<?php $mb->the_value(); ?>"
                       class="regular-text"/>

(Optional) Enter the title of the attachment. e.g. Growth Group Homework

        <?php $mb->the_field('description'); ?>

            <label for="<?php $mb->the_name(); ?>">Description:
            <textarea name="<?php $mb->the_name(); ?>" rows="5"
                          class="large-text"><?php $mb->the_value(); ?></textarea>

(Optional) Enter a discription of the attachment content.

    <?php $mb->the_group_close(); ?>
    <?php endwhile; ?>

        Add Another Attachment


text:
Imports SistFoncreagro.Report
Public Class ReporteActividadesCaserio
    Inherits System.Web.UI.Page
    Dim IdProyecto As String
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        IdProyecto = Session("IdProyecto")
        Me.ReportViewer1.Report = New RepActividadesXCaserio
        Me.ReportViewer1.Report.ReportParameters(0).Value = IdProyecto
    End Sub

End Class


text:
<?xml version="1.0" encoding="UTF-8"?>
<CustomField xmlns="http://soap.sforce.com/2006/04/metadata">
    <fullName>Grading_Period_Sequence__c</fullName>
    <description>Indicates which Term this is. For example, enter "1" for the first quarter or semester, "2" for the second quarter or semester, etc.</description>
    <externalId>false</externalId>
    <inlineHelpText>Indicates which Term this is. For example, enter "1" for the first quarter or semester, "2" for the second quarter or semester, etc.</inlineHelpText>
    <label>Grading Period Sequence</label>
    <precision>18</precision>
    <required>false</required>
    <scale>0</scale>
    <trackTrending>false</trackTrending>
    <type>Number</type>
    <unique>false</unique>
</CustomField>


text:
import argparse
import os
import codecs
import logging
logger = logging.getLogger()

if __name__ == '__main__':
    logging.basicConfig( format = '%(asctime)s : %(levelname)s : %(message)s',
                         level = logging.INFO )

    parser = argparse.ArgumentParser()
    parser.add_argument( 'dir', type = str )
    parser.add_argument( '--run_id', type = int, default = 1 )
    parser.add_argument( '--model_cnt', type = int, default = 5 )
    args = parser.parse_args()

    logger.info( args )

    weight = 1. / args.model_cnt

    solution = {}
    for i in xrange( args.model_cnt ):
        filename = os.path.join( args.dir, '%d.tsv' % i )
        with codecs.open( filename, 'rb', 'utf8' ) as fp:
            for line in fp:
                tokens = line.strip().split(u'\t')
                key = (tokens[3], tokens[5], tokens[6])
                if key in solution:
                    solution[key]['score'] = weight + solution[key]['score']
                else:
                    solution[key] = { 'spelling' : tokens[2], 'score' : weight }
        logger.info( '%d.tsv processed' % i )
    logger.info( len(solution) )

    for i in xrange(args.model_cnt):
        threshold = weight * i
        cnt = 0
        output = os.path.join( args.dir, '%02d-of-%02d.tsv' % (i, args.model_cnt) )
        with codecs.open( output, 'wb', 'utf8' ) as fp:
            for key in solution:
                if solution[key]['score'] > threshold:
                    position, mention1, mention2 = key
                    out_str = u'\t'.join( [
                        u'YorkNRM%d' % args.run_id,
                        u'TEDL16_EVAL_%06d' % cnt,
                        solution[key]['spelling'],
                        position,
                        u'NIL000000',
                        mention1,
                        mention2,
                        u'%.1f' % solution[key]['score']
                    ] )
                    fp.write( out_str + u'\n' )
                    cnt += 1


text:
#ifndef PHOTO_LIST_DELETE_CONFIRM
#define PHOTO_LIST_DELETE_CONFIRM

#include "abstractdeleteconfirm.h"
class PhotoListDeleteConfirm : public AbstractDeleteConfirm {
    Q_OBJECT
public:
    void setFile(QString);

public slots:
    virtual void onRejected();
    virtual void onAccepted();

private:
    QString file;
};

#endif


text:
package net.chrigel.clusterbrake.transcode;

import java.util.LinkedList;
import java.util.List;
import net.chrigel.clusterbrake.media.VideoOptionPackage;

/**
 *
 */
public class SimpleOptionPackage
        implements VideoOptionPackage {

    private List<String> options = new LinkedList<>();

    @Override
    public List<String> getOptions() {
        return options;
    }

    @Override
    public void setOptions(List<String> options) {
        this.options = options;
    }

}


text:
layout: default
title: Protothon on March 24th, Stockholm, Sweden
author: Serge Lachapelle
date: 2012-02-21 02:50:00
---

With the help of our friends Peter, Joe, Clara and Johan from
[protothon.com][1], we are organizing a day long event on Saturday, March 24th
2012 in Stockholm Sweden. Prototype hacking with WebRTC.

While some of you may think it is very early to do such an event, we think the
timing is perfect:

  * Software designers should  get a kick out of being amongst the first
    playing with this technology, and influencing it's outcome.

  * We get hugely valuable feedback, the kind of hands-on feedback usually not
    present in API specification discussions.

We will have, on hand, people that have written and edited the WebRTC API,
people that have implemented it in Chrome / WebKit and signal processing
experts that make the magic happen underneath the APIs and browser
integrations.

Our goal until then is to get the latest JSEP proposal implemented in Chrome,
make an abstraction JS library available (for simplicity) and get the
apprtc.appspot.com demo open sourced.

Hope you will sign up ... ([here])!

[1]: http://protothon.com/
[2]: http://www.protothon.com/


text:
// This file has been auto-generated by code_generator_v8.py. DO NOT MODIFY!

#include "config.h"
#include "V8Uint16Array.h"

#include "bindings/core/v8/ExceptionState.h"
#include "bindings/core/v8/V8ArrayBuffer.h"
#include "bindings/core/v8/V8DOMConfiguration.h"
#include "bindings/core/v8/V8ObjectConstructor.h"
#include "core/dom/ContextFeatures.h"
#include "core/dom/Document.h"
#include "platform/RuntimeEnabledFeatures.h"
#include "platform/TraceEvent.h"
#include "wtf/GetPtr.h"
#include "wtf/RefPtr.h"

namespace blink {

// Suppress warning: global constructors, because struct WrapperTypeInfo is trivial
// and does not depend on another global objects.
#if defined(COMPONENT_BUILD) && defined(WIN32) && COMPILER(CLANG)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wglobal-constructors"
#endif
const WrapperTypeInfo V8Uint16Array::wrapperTypeInfo = { gin::kEmbedderBlink, 0, V8Uint16Array::refObject, V8Uint16Array::derefObject, V8Uint16Array::trace, 0, 0, V8Uint16Array::preparePrototypeObject, V8Uint16Array::installConditionallyEnabledProperties, "Uint16Array", &V8ArrayBufferView::wrapperTypeInfo, WrapperTypeInfo::WrapperTypeObjectPrototype, WrapperTypeInfo::ObjectClassId, WrapperTypeInfo::NotInheritFromEventTarget, WrapperTypeInfo::Independent, WrapperTypeInfo::RefCountedObject };
#if defined(COMPONENT_BUILD) && defined(WIN32) && COMPILER(CLANG)
#pragma clang diagnostic pop
#endif

// This static member must be declared by DEFINE_WRAPPERTYPEINFO in DOMUint16Array.h.
// For details, see the comment of DEFINE_WRAPPERTYPEINFO in
// bindings/core/v8/ScriptWrappable.h.

bool V8Uint16Array::hasInstance(v8::Local<v8::Value> v8Value, v8::Isolate* isolate)
{
    return v8Value->IsUint16Array();
}

DOMUint16Array* V8Uint16Array::toImpl(v8::Local<v8::Object> object)
{
    ASSERT(object->IsUint16Array());
    ScriptWrappable* scriptWrappable = toScriptWrappable(object);
    if (scriptWrappable)
        return scriptWrappable->toImpl<DOMUint16Array>();

    v8::Local<v8::Uint16Array> v8View = object.As<v8::Uint16Array>();
    RefPtr<DOMUint16Array> typedArray = DOMUint16Array::create(V8ArrayBuffer::toImpl(v8View->Buffer()), v8View->ByteOffset(), v8View->Length());
    v8::Local<v8::Object> associatedWrapper = typedArray->associateWithWrapper(v8::Isolate::GetCurrent(), typedArray->wrapperTypeInfo(), object);
    ASSERT_UNUSED(associatedWrapper, associatedWrapper == object);

    return typedArray->toImpl<DOMUint16Array>();
}

DOMUint16Array* V8Uint16Array::toImplWithTypeCheck(v8::Isolate* isolate, v8::Local<v8::Value> value)
{
    return hasInstance(value, isolate) ? toImpl(v8::Local<v8::Object>::Cast(value)) : 0;
}

void V8Uint16Array::refObject(ScriptWrappable* scriptWrappable)
{
    scriptWrappable->toImpl<DOMUint16Array>()->ref();
}

void V8Uint16Array::derefObject(ScriptWrappable* scriptWrappable)
{
    scriptWrappable->toImpl<DOMUint16Array>()->deref();
}

} // namespace blink


text:
#include <linux/module.h>
#include <linux/init.h>
#include <linux/spinlock.h>
#include <linux/sched.h>
#include <linux/interrupt.h>
#include <linux/profile.h>
#include <linux/errno.h>
#include <linux/err.h>
#include <linux/mm.h>
#include <linux/cpu.h>
#include <linux/smp.h>
#include <linux/irq.h>
#include <linux/delay.h>
#include <linux/atomic.h>
#include <linux/percpu.h>
#include <linux/cpumask.h>
#include <linux/spinlock_types.h>
#include <linux/reboot.h>
#include <asm/processor.h>
#include <asm/setup.h>
#include <asm/mach_desc.h>

arch_spinlock_t smp_atomic_ops_lock = __ARCH_SPIN_LOCK_UNLOCKED;
arch_spinlock_t smp_bitops_lock = __ARCH_SPIN_LOCK_UNLOCKED;

struct plat_smp_ops  plat_smp_ops;

/* XXX: per cpu ? Only needed once in early seconday boot */
struct task_struct *secondary_idle_tsk;

/* Called from start_kernel */
void __init smp_prepare_boot_cpu(void)
{
}

/*
 * Initialise the CPU possible map early - this describes the CPUs
 * which may be present or become present in the system.
 */
void __init smp_init_cpus(void)
{
	unsigned int i;

	for (i = 0; i < NR_CPUS; i++)
		set_cpu_possible(i, true);
}

/* called from init ( ) =>  process 1 */
void __init smp_prepare_cpus(unsigned int max_cpus)
{
	int i;

	/*
	 * Initialise the present map, which describes the set of CPUs
	 * actually populated at the present time.
	 */
	for (i = 0; i < max_cpus; i++)
		set_cpu_present(i, true);
}

void __init smp_cpus_done(unsigned int max_cpus)
{

}

/*
 * After power-up, a non Master CPU needs to wait for Master to kick start it
 *
 * The default implementation halts
 *
 * This relies on platform specific support allowing Master to directly set
 * this CPU's PC (to be @first_lines_of_secondary() and kick start it.
 *
 * In lack of such h/w assist, platforms can override this function
 *   - make this function busy-spin on a token, eventually set by Master
 *     (from arc_platform_smp_wakeup_cpu())
 *   - Once token is available, jump to @first_lines_of_secondary
 *     (using inline asm).
 *
 * Alert: can NOT use stack here as it has not been determined/setup for CPU.
 *        If it turns out to be elaborate, it's better to code it in assembly
 *
 */
void __attribute__((weak)) arc_platform_smp_wait_to_boot(int cpu)
{
	/*
	 * As a hack for debugging - since debugger will single-step over the
	 * FLAG insn - wrap the halt itself it in a self loop
	 */
	__asm__ __volatile__(
	"1:		\n"
	"	flag 1	\n"
	"	b 1b	\n");
}

const char *arc_platform_smp_cpuinfo(void)
{
	return plat_smp_ops.info;
}

/*
 * The very first "C" code executed by secondary
 * Called from asm stub in head.S
 * "current"/R25 already setup by low level boot code
 */
void __cpuinit start_kernel_secondary(void)
{
	struct mm_struct *mm = &init_mm;
	unsigned int cpu = smp_processor_id();

	/* MMU, Caches, Vector Table, Interrupts etc */
	setup_processor();

	atomic_inc(&mm->mm_users);
	atomic_inc(&mm->mm_count);
	current->active_mm = mm;

	notify_cpu_starting(cpu);
	set_cpu_online(cpu, true);

	pr_info("## CPU%u LIVE ##: Executing Code...\n", cpu);

	if (machine_desc->init_smp)
		machine_desc->init_smp(smp_processor_id());

	arc_local_timer_setup(cpu);

	local_irq_enable();
	preempt_disable();
	cpu_startup_entry(CPUHP_ONLINE);
}

/*
 * Called from kernel_init( ) -> smp_init( ) - for each CPU
 *
 * At this point, Secondary Processor  is "HALT"ed:
 *  -It booted, but was halted in head.S
 *  -It was configured to halt-on-reset
 *  So need to wake it up.
 *
 * Essential requirements being where to run from (PC) and stack (SP)
*/
int __cpuinit __cpu_up(unsigned int cpu, struct task_struct *idle)
{
	unsigned long wait_till;

	secondary_idle_tsk = idle;

	pr_info("Idle Task [%d] %p", cpu, idle);
	pr_info("Trying to bring up CPU%u ...\n", cpu);

	if (plat_smp_ops.cpu_kick)
		plat_smp_ops.cpu_kick(cpu,
				(unsigned long)first_lines_of_secondary);

	/* wait for 1 sec after kicking the secondary */
	wait_till = jiffies + HZ;
	while (time_before(jiffies, wait_till)) {
		if (cpu_online(cpu))
			break;
	}

	if (!cpu_online(cpu)) {
		pr_info("Timeout: CPU%u FAILED to comeup !!!\n", cpu);
		return -1;
	}

	secondary_idle_tsk = NULL;

	return 0;
}

/*
 * not supported here
 */
int __init setup_profiling_timer(unsigned int multiplier)
{
	return -EINVAL;
}

/*****************************************************************************/
/*              Inter Processor Interrupt Handling                           */
/*****************************************************************************/

/*
 * structures for inter-processor calls
 * A Collection of single bit ipi messages
 *
 */

/*
 * TODO_rajesh investigate tlb message types.
 * IPI Timer not needed because each ARC has an individual Interrupting Timer
 */
enum ipi_msg_type {
	IPI_NOP = 0,
	IPI_RESCHEDULE = 1,
	IPI_CALL_FUNC,
	IPI_CALL_FUNC_SINGLE,
	IPI_CPU_STOP
};

struct ipi_data {
	unsigned long bits;
};

static DEFINE_PER_CPU(struct ipi_data, ipi_data);

static void ipi_send_msg(const struct cpumask *callmap, enum ipi_msg_type msg)
{
	unsigned long flags;
	unsigned int cpu;

	local_irq_save(flags);

	for_each_cpu(cpu, callmap) {
		struct ipi_data *ipi = &per_cpu(ipi_data, cpu);
		set_bit(msg, &ipi->bits);
	}

	/* Call the platform specific cross-CPU call function  */
	if (plat_smp_ops.ipi_send)
		plat_smp_ops.ipi_send((void *)callmap);

	local_irq_restore(flags);
}

void smp_send_reschedule(int cpu)
{
	ipi_send_msg(cpumask_of(cpu), IPI_RESCHEDULE);
}

void smp_send_stop(void)
{
	struct cpumask targets;
	cpumask_copy(&targets, cpu_online_mask);
	cpumask_clear_cpu(smp_processor_id(), &targets);
	ipi_send_msg(&targets, IPI_CPU_STOP);
}

void arch_send_call_function_single_ipi(int cpu)
{
	ipi_send_msg(cpumask_of(cpu), IPI_CALL_FUNC_SINGLE);
}

void arch_send_call_function_ipi_mask(const struct cpumask *mask)
{
	ipi_send_msg(mask, IPI_CALL_FUNC);
}

/*
 * ipi_cpu_stop - handle IPI from smp_send_stop()
 */
static void ipi_cpu_stop(unsigned int cpu)
{
	machine_halt();
}

static inline void __do_IPI(unsigned long *ops, struct ipi_data *ipi, int cpu)
{
	unsigned long msg = 0;

	do {
		msg = find_next_bit(ops, BITS_PER_LONG, msg+1);

		switch (msg) {
		case IPI_RESCHEDULE:
			scheduler_ipi();
			break;

		case IPI_CALL_FUNC:
			generic_smp_call_function_interrupt();
			break;

		case IPI_CALL_FUNC_SINGLE:
			generic_smp_call_function_single_interrupt();
			break;

		case IPI_CPU_STOP:
			ipi_cpu_stop(cpu);
			break;
		}
	} while (msg < BITS_PER_LONG);

}

/*
 * arch-common ISR to handle for inter-processor interrupts
 * Has hooks for platform specific IPI
 */
irqreturn_t do_IPI(int irq, void *dev_id)
{
	int cpu = smp_processor_id();
	struct ipi_data *ipi = &per_cpu(ipi_data, cpu);
	unsigned long ops;

	if (plat_smp_ops.ipi_clear)
		plat_smp_ops.ipi_clear(cpu, irq);

	/*
	 * XXX: is this loop really needed
	 * And do we need to move ipi_clean inside
	 */
	while ((ops = xchg(&ipi->bits, 0)) != 0)
		__do_IPI(&ops, ipi, cpu);

	return IRQ_HANDLED;
}

/*
 * API called by platform code to hookup arch-common ISR to their IPI IRQ
 */
static DEFINE_PER_CPU(int, ipi_dev);
int smp_ipi_irq_setup(int cpu, int irq)
{
	int *dev_id = &per_cpu(ipi_dev, smp_processor_id());
	return request_percpu_irq(irq, do_IPI, "IPI Interrupt", dev_id);
}


text:
using System;

namespace Bike2Ride.Data.Models.Contracts
{
    public interface IDataModel
    {
        Guid Id { get; }
    }
}


text:
<?php

namespace dokuwiki\Menu\Item;

/**
 * Class Edit
 *
 * Most complex item. Shows the edit button but mutates to show, draft and create based on
 * current state.
 */
class Edit extends AbstractItem {

    /** @inheritdoc */
    public function __construct() {
        global $ACT;
        global $INFO;
        global $REV;

        parent::__construct();

        if($ACT === 'show') {
            $this->method = 'post';
            if($INFO['writable']) {
                $this->accesskey = 'e';
                if(!empty($INFO['draft'])) {
                    $this->type = 'draft';
                    $this->params['do'] = 'draft';
                } else {
                    $this->params['rev'] = $REV;
                    if(!$INFO['exists']) {
                        $this->type = 'create';
                    }
                }
            } else {
                if(!actionOK("source")) throw new \RuntimeException("action disabled: source");
                $params['rev'] = $REV;
                $this->type = 'source';
                $this->accesskey = 'v';
            }
        } else {
            $this->params = array('do' => '');
            $this->type = 'show';
            $this->accesskey = 'v';
        }

        $this->setIcon();
    }

    /**
     * change the icon according to what type the edit button has
     */
    protected function setIcon() {
        $icons = array(
            'edit' => '01-edit_pencil.svg',
            'create' => '02-create_pencil.svg',
            'draft' => '03-draft_android-studio.svg',
            'show' => '04-show_file-document.svg',
            'source' => '05-source_file-xml.svg',
        );
        if(isset($icons[$this->type])) {
            $this->svg = DOKU_INC . 'lib/images/menu/' . $icons[$this->type];
        }
    }

}


text:
package rpcd

import (
	"github.com/Symantec/Dominator/lib/srpc"
	"github.com/Symantec/Dominator/proto/imageserver"
)

func (t *srpcType) MakeDirectory(conn *srpc.Conn,
	request imageserver.MakeDirectoryRequest,
	reply *imageserver.MakeDirectoryResponse) error {
	username := conn.Username()
	if err := t.checkMutability(); err != nil {
		return err
	}
	if username == "" {
		t.logger.Printf("MakeDirectory(%s)\n", request.DirectoryName)
	} else {
		t.logger.Printf("MakeDirectory(%s) by %s\n",
			request.DirectoryName, username)
	}
	return t.imageDataBase.MakeDirectory(request.DirectoryName, username)
}


text:
import CardView from './cardView';
import Header from './header';
import Icon from './icon';
import Searchbar from './searchbar';
import Touchable from './touchable';
import TabView from './tabView';

export { CardView, Header, Icon, Searchbar, TabView, Touchable };


text:
module EmailQueue
  class Job
    attr_reader :queue_item, :error_details
    def initialize(queue_item)
      @queue_item = queue_item
    end

    # the actual sending of email happens here
    # the smtp or other configuration can be changed from config/mail.rb file.
    #
    # the queue implementation is generic enough to support other types of jobs
    # except the schema and the below function
    def process
      mail = Mail.new
      mail.from = queue_item.from_email_address
      mail.to = queue_item.to_email_address
      mail.subject = queue_item.subject
      mail.body = queue_item.body
      begin
        mail.deliver!
      rescue => e
        @error_details = e.message
      end
    end
  end
end


text:
        <link
            href="../../../syntax_highlighter/styles/shCore.css" rel="stylesheet"
            type="text/css"
        />
        <link
            href="../../../syntax_highlighter/styles/shCoreEclipse.css"
            rel="stylesheet" type="text/css"
        />
        <link
            href="../../../syntax_highlighter/styles/shThemeWordpress.css"
            rel="stylesheet" type="text/css"
        />

<?php

// start session
session_start();

// define root
if (!defined('__ROOT__')) {
	define('__ROOT__', dirname(dirname(dirname(__FILE__))));
}

/**
 * Get main class of annotation tool.
 * All external libraries are referenced in this class.
 */
require_once(__ROOT__. '/core/class/core.class.php');

// init classes
$cmf	= new CMF();
$core = new Core();

if (isset($_GET['serializer']) && ($_GET['serializer'] != '')) {

	$allowed = false;
	foreach ($cmf->settings->available_serializers as $key => $val) {
		if ($_GET['serializer'] == $key) {
			$allowed = true;
		}
	}

	if ($allowed != true) {

		// serializer not allowed

	}

	else {

		$video_data= $core->video;

		$sel_serializer = $_GET['serializer'];

		$file_data = $cmf->generateAnnotationObject($_COOKIE['annotationlist'], $video_data, $cmf->settings->available_serializers[$sel_serializer]);

		header('Content-type: ' .$cmf->settings->serializers_header[$sel_serializer]. '; charset=utf-8');

		print $file_data;

	}

}

?>


text:
package hn.join.fieldwork.service;

import hn.join.fieldwork.domain.BaseDomain.VisibleStatus;
import hn.join.fieldwork.domain.Device;
import hn.join.fieldwork.domain.Device.DeviceStatus;
import hn.join.fieldwork.domain.DeviceJournal;
import hn.join.fieldwork.persistence.DeviceMapper;
import hn.join.fieldwork.persistence.SQLQueryResult;
import hn.join.fieldwork.utils.JsonUtil;
import hn.join.fieldwork.web.command.CreateDeviceCommand;
import hn.join.fieldwork.web.command.EditDeviceCommand;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.collect.Maps;

/**
 * 设备管理
 * @author aisino_lzw
 *
 */
@Service
public class DeviceService {

	@Autowired
	private DeviceMapper deviceMapper;

	/**
	 * 添加设备
	 * @param command 设备信息
	 */
	@Transactional(rollbackFor = Exception.class)
	public void newDevice(CreateDeviceCommand command) {
		Device device = fromCreateDeviceCommand(command);
		deviceMapper.insertDevice(device);
	}

	/**
	 * 更新设备信息
	 * @param command 设备信息
	 * @param operatorId 操作员id
	 */
	@Transactional(rollbackFor = Exception.class)
	public void editDevice(EditDeviceCommand command, Long operatorId) {
		Device beforeOne = deviceMapper.getById(Long.parseLong(command
				.getDeviceId()));
		Device device = fromEditDeviceCommand(command);
		DeviceJournal deviceJournal = new DeviceJournal();
		deviceJournal.setMemo(command.getMemo());
		deviceJournal.setPreviousState(generatePreviousDeviceState(beforeOne));
		deviceMapper.updateDevice(device);
		deviceMapper.insertDeviceJournal(Long.parseLong(command.getDeviceId()),
				deviceJournal, operatorId);

	}

	/**
	 * 条件查询指定设备
	 * @param areaCode 区域编号
	 * @param meid 设备识别码
	 * @param phoneNo 电话号码
	 * @param page 指定页
	 * @param rows 指定行数
	 * @return 设备列表
	 */
	public SQLQueryResult<Device> findBy(String areaCode, String meid,
			String phoneNo, Integer page, Integer rows) {
		SQLQueryResult<Device> queryResult = null;
		long _count = deviceMapper.countBy(areaCode, meid, phoneNo);
		if (_count != 0) {
			Integer offset = (page - 1) * rows;
			List<Device> _result = deviceMapper.findBy(areaCode, meid, phoneNo,
					offset, rows);
			queryResult = new SQLQueryResult<Device>(_count, _result);
		} else {
			queryResult = SQLQueryResult.EMPTY_RESULT;
		}
		return queryResult;
	}

	/**
	 * 条件查询指定设备
	 * @param areaCode 区域编号
	 * @param meid  设备识别码
	 * @param phoneNo 电话号码
	 * @param page 指定页
	 * @param rows 指定行数
	 * @return 设备列表
	 */
	public SQLQueryResult<Device> findByIdle(String areaCode, String meid,
			String phoneNo, Integer page, Integer rows) {
		SQLQueryResult<Device> queryResult = null;
		long _count = deviceMapper.countByIdle(areaCode, meid, phoneNo);
		if (_count != 0) {
			Integer offset = (page - 1) * rows;
			List<Device> _result = deviceMapper.findByIdle(areaCode, meid,
					phoneNo, offset, rows);
			queryResult = new SQLQueryResult<Device>(_count, _result);
		} else {
			queryResult = SQLQueryResult.EMPTY_RESULT;
		}
		return queryResult;
	}

	/**
	 * 删除设备
	 * @param deviceId 设备id
	 * @param memo 备注
	 * @param operatorId 操作员id
	 */
	@Transactional(rollbackFor = Exception.class)
	public void removeDevice(Long deviceId, String memo, Long operatorId) {
		Device beforeOne = deviceMapper.getById(deviceId);
		DeviceJournal deviceJournal = new DeviceJournal();
		deviceJournal.setMemo(memo);
		deviceJournal.setPreviousState(generatePreviousDeviceState(beforeOne));
		deviceMapper.deleteDevice(deviceId);
		deviceMapper.insertDeviceJournal(deviceId, deviceJournal, operatorId);
	}

	/**
	 * 根据设备识别码确定该设备是否存在
	 * @param 设备识别码
	 * @return
	 */
	public boolean checkMeidAvailable(String meid) {
		long _count = deviceMapper.countByMeid(meid);
		if (_count == 0) {
			return true;
		}
		return false;
	}

	/**
	 * 查询设备日志信息
	 * @param deviceId 设备id
	 * @return 设备信息
	 */
	public List<DeviceJournal> loadDeviceJournal(Long deviceId) {
		return deviceMapper.findJournalByDeviceId(deviceId);
	}

	/**
	 * 创建设备对象
	 * @param command 创建条件(新建)
	 * @return
	 */
	private Device fromCreateDeviceCommand(CreateDeviceCommand command) {
		Device device = new Device();
		device.setPhoneNo(command.getPhoneNo());
		device.setMeid(command.getMeid());
		if (!StringUtils.isEmpty(command.getCurrentAmount())) {
			device.setCurrentAmount(Float.valueOf(command.getCurrentAmount()));
		}
		device.setConsumeCategory(command.getConsumeCategory());
		device.setModel(command.getModel());
		device.setStatus(DeviceStatus.valueOf(command.getStatus()));
		device.setAreaCode(command.getAreaCode());
		device.setVisibleStatus(VisibleStatus.visible);
		return device;
	}

	/**
	 * 创建设备对象
	 * @param command 创建条件(修改)
	 * @return
	 */
	private Device fromEditDeviceCommand(EditDeviceCommand command) {
		Device device = fromCreateDeviceCommand(command);
		device.setId(Long.valueOf(command.getDeviceId()));
		return device;
	}

	/**
	 * 返回设备信息json数据
	 * @param device 设备
	 * @return
	 */
	private String generatePreviousDeviceState(Device device) {
		Map<String, Object> _map = Maps.newHashMap();
		_map.put("phoneNo", device.getPhoneNo());
		_map.put("meid", device.getMeid());
		_map.put("model", device.getModel());
		_map.put("currentAmount", device.getCurrentAmount());
		_map.put("consumeCategory", device.getConsumeCategory());
		_map.put("status", device.getStatus());
		_map.put("areaCode", device.getAreaCode());
		return JsonUtil.toJson(_map);
	}

	// private String

}


text:
"""Functions related to the SDL shared library version.
"""

__docformat__ = 'restructuredtext'
__version__ = '$Id: $'

from ctypes import *

from . import dll

class SDL_version(Structure):
    """Version structure.

    :Ivariables:
        `major` : int
            Major version number
        `minor` : int
            Minor version number
        `patch` : int
            Patch revision number

    """
    _fields_ = [('major', c_ubyte),
                ('minor', c_ubyte),
                ('patch', c_ubyte)]

    def __repr__(self):
        return '%d.%d.%d' % \
            (self.major, self.minor, self.patch)

    def is_since(self, required):
        if hasattr(required, 'major'):
            return self.major >= required.major and \
                self.minor >= required.minor and \
                self.patch >= required.patch
        else:
            return self.major >= required[0] and \
                self.minor >= required[1] and \
                self.patch >= required[2]

def SDL_VERSIONNUM(major, minor, patch):
    """Turn the version numbers into a numeric value.

    For example::

        >>> SDL_VERSIONNUM(1, 2, 3)
        1203

    :Parameters:
     - `major`: int
     - `minor`: int
     - `patch`: int

    :rtype: int
    """
    return x*1000 + y*100 + z

SDL_Linked_Version = dll.function(
    'SDL_Linked_Version',
    '''Get the version of the dynamically linked SDL library.

    :rtype: `SDL_version`
    ''',
    args=[],
    arg_types=[],
    return_type=POINTER(SDL_version),
    dereference_return=True,
    require_return=True)

def SDL_VERSION_ATLEAST(major, minor, patch):
    """Determine if the SDL library is at least the given version.

    :Parameters:
     - `major`: int
     - `minor`: int
     - `patch`: int

    :rtype: bool
    """
    v = SDL_Linked_Version()
    return SDL_VERSIONNUM(v.major, v.minor, v.patch) >= \
        SDL_VERSIONNUM(major, minor, patch)

# SDL_VERSION and SDL_COMPILEDVERSION not implemented as there is no
# sensible mapping to compiled version numbers.


text:
package com.phonedeck.gcm4j;

import java.util.concurrent.Executors;

import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.common.util.concurrent.SettableFuture;

public class DefaultGcm extends AbstractDefaultGcm {

    private final ListeningExecutorService executor;

    public DefaultGcm(GcmConfig gcmConfig) {
        super(gcmConfig);
        this.executor = gcmConfig.getExecutor() != null ? gcmConfig.getExecutor() : MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());
    }

    @Override
    protected ListenableFuture<GcmResponse> executeRequestFuture(final GcmRequest request) {
        final SettableFuture<GcmResponse> result = SettableFuture.create();
        executor.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    result.set(executeRequest(request));
                } catch (GcmException ex) {
                    result.setException(ex);
                }
                  catch (Exception ex) {
                    result.setException(new GcmException("An error occurred when submitting the messsage", ex));
                }
            }
        });
        return result;
    }

}


text:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
	"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
	"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="org.hibernate.test.cid">

<!--

  This mapping demonstrates

     (1) use of a derived property which performs a
         subselect against an associated table

     (2) use of <synchronize/> to ensure that auto-flush
         works correctly for an entity with a property
         derived from another table

-->

    <class name="Product">
    	<synchronize table="LineItem"/>

    	<id name="productId"
    		length="10">
    		<generator class="assigned"/>
    	</id>

    	<property name="description"
    		not-null="true"
    		length="200"/>
    	<property name="price" length="3" column="cost"/>
    	<property name="numberAvailable"/>

    	<property name="numberOrdered"
    		formula="( select sum(li.quantity) from LineItem li where li.productId = productId )"/>
	</class>

</hibernate-mapping>


text:
@interface MOBProjectionEPSG21896 : MOBProjection

@end