text:
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt

#include <linux/kernel.h>
#include <linux/mman.h>
#include <linux/delay.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/kthread.h>
#include <linux/completion.h>
#include <linux/memory_hotplug.h>
#include <linux/memory.h>
#include <linux/notifier.h>
#include <linux/percpu_counter.h>

#include <linux/hyperv.h>

/*
 * We begin with definitions supporting the Dynamic Memory protocol
 * with the host.
 *
 * Begin protocol definitions.
 */

/*
 * Protocol versions. The low word is the minor version, the high word the major
 * version.
 *
 * History:
 * Initial version 1.0
 * Changed to 0.1 on 2009/03/25
 * Changes to 0.2 on 2009/05/14
 * Changes to 0.3 on 2009/12/03
 * Changed to 1.0 on 2011/04/05
 */

#define DYNMEM_MAKE_VERSION(Major, Minor) ((__u32)(((Major) << 16) | (Minor)))
#define DYNMEM_MAJOR_VERSION(Version) ((__u32)(Version) >> 16)
#define DYNMEM_MINOR_VERSION(Version) ((__u32)(Version) & 0xff)

enum {
	DYNMEM_PROTOCOL_VERSION_1 = DYNMEM_MAKE_VERSION(0, 3),
	DYNMEM_PROTOCOL_VERSION_2 = DYNMEM_MAKE_VERSION(1, 0),

	DYNMEM_PROTOCOL_VERSION_WIN7 = DYNMEM_PROTOCOL_VERSION_1,
	DYNMEM_PROTOCOL_VERSION_WIN8 = DYNMEM_PROTOCOL_VERSION_2,

	DYNMEM_PROTOCOL_VERSION_CURRENT = DYNMEM_PROTOCOL_VERSION_WIN8
};

/*
 * Message Types
 */

enum dm_message_type {
	/*
	 * Version 0.3
	 */
	DM_ERROR			= 0,
	DM_VERSION_REQUEST		= 1,
	DM_VERSION_RESPONSE		= 2,
	DM_CAPABILITIES_REPORT		= 3,
	DM_CAPABILITIES_RESPONSE	= 4,
	DM_STATUS_REPORT		= 5,
	DM_BALLOON_REQUEST		= 6,
	DM_BALLOON_RESPONSE		= 7,
	DM_UNBALLOON_REQUEST		= 8,
	DM_UNBALLOON_RESPONSE		= 9,
	DM_MEM_HOT_ADD_REQUEST		= 10,
	DM_MEM_HOT_ADD_RESPONSE		= 11,
	DM_VERSION_03_MAX		= 11,
	/*
	 * Version 1.0.
	 */
	DM_INFO_MESSAGE			= 12,
	DM_VERSION_1_MAX		= 12
};

/*
 * Structures defining the dynamic memory management
 * protocol.
 */

union dm_version {
	struct {
		__u16 minor_version;
		__u16 major_version;
	};
	__u32 version;
} __packed;

union dm_caps {
	struct {
		__u64 balloon:1;
		__u64 hot_add:1;
		/*
		 * To support guests that may have alignment
		 * limitations on hot-add, the guest can specify
		 * its alignment requirements; a value of n
		 * represents an alignment of 2^n in mega bytes.
		 */
		__u64 hot_add_alignment:4;
		__u64 reservedz:58;
	} cap_bits;
	__u64 caps;
} __packed;

union dm_mem_page_range {
	struct  {
		/*
		 * The PFN number of the first page in the range.
		 * 40 bits is the architectural limit of a PFN
		 * number for AMD64.
		 */
		__u64 start_page:40;
		/*
		 * The number of pages in the range.
		 */
		__u64 page_cnt:24;
	} finfo;
	__u64  page_range;
} __packed;

/*
 * The header for all dynamic memory messages:
 *
 * type: Type of the message.
 * size: Size of the message in bytes; including the header.
 * trans_id: The guest is responsible for manufacturing this ID.
 */

struct dm_header {
	__u16 type;
	__u16 size;
	__u32 trans_id;
} __packed;

/*
 * A generic message format for dynamic memory.
 * Specific message formats are defined later in the file.
 */

struct dm_message {
	struct dm_header hdr;
	__u8 data[]; /* enclosed message */
} __packed;

/*
 * Specific message types supporting the dynamic memory protocol.
 */

/*
 * Version negotiation message. Sent from the guest to the host.
 * The guest is free to try different versions until the host
 * accepts the version.
 *
 * dm_version: The protocol version requested.
 * is_last_attempt: If TRUE, this is the last version guest will request.
 * reservedz: Reserved field, set to zero.
 */

struct dm_version_request {
	struct dm_header hdr;
	union dm_version version;
	__u32 is_last_attempt:1;
	__u32 reservedz:31;
} __packed;

/*
 * Version response message; Host to Guest and indicates
 * if the host has accepted the version sent by the guest.
 *
 * is_accepted: If TRUE, host has accepted the version and the guest
 * should proceed to the next stage of the protocol. FALSE indicates that
 * guest should re-try with a different version.
 *
 * reservedz: Reserved field, set to zero.
 */

struct dm_version_response {
	struct dm_header hdr;
	__u64 is_accepted:1;
	__u64 reservedz:63;
} __packed;

/*
 * Message reporting capabilities. This is sent from the guest to the
 * host.
 */

struct dm_capabilities {
	struct dm_header hdr;
	union dm_caps caps;
	__u64 min_page_cnt;
	__u64 max_page_number;
} __packed;

/*
 * Response to the capabilities message. This is sent from the host to the
 * guest. This message notifies if the host has accepted the guest's
 * capabilities. If the host has not accepted, the guest must shutdown
 * the service.
 *
 * is_accepted: Indicates if the host has accepted guest's capabilities.
 * reservedz: Must be 0.
 */

struct dm_capabilities_resp_msg {
	struct dm_header hdr;
	__u64 is_accepted:1;
	__u64 reservedz:63;
} __packed;

/*
 * This message is used to report memory pressure from the guest.
 * This message is not part of any transaction and there is no
 * response to this message.
 *
 * num_avail: Available memory in pages.
 * num_committed: Committed memory in pages.
 * page_file_size: The accumulated size of all page files
 *		   in the system in pages.
 * zero_free: The nunber of zero and free pages.
 * page_file_writes: The writes to the page file in pages.
 * io_diff: An indicator of file cache efficiency or page file activity,
 *	    calculated as File Cache Page Fault Count - Page Read Count.
 *	    This value is in pages.
 *
 * Some of these metrics are Windows specific and fortunately
 * the algorithm on the host side that computes the guest memory
 * pressure only uses num_committed value.
 */

struct dm_status {
	struct dm_header hdr;
	__u64 num_avail;
	__u64 num_committed;
	__u64 page_file_size;
	__u64 zero_free;
	__u32 page_file_writes;
	__u32 io_diff;
} __packed;

/*
 * Message to ask the guest to allocate memory - balloon up message.
 * This message is sent from the host to the guest. The guest may not be
 * able to allocate as much memory as requested.
 *
 * num_pages: number of pages to allocate.
 */

struct dm_balloon {
	struct dm_header hdr;
	__u32 num_pages;
	__u32 reservedz;
} __packed;

/*
 * Balloon response message; this message is sent from the guest
 * to the host in response to the balloon message.
 *
 * reservedz: Reserved; must be set to zero.
 * more_pages: If FALSE, this is the last message of the transaction.
 * if TRUE there will atleast one more message from the guest.
 *
 * range_count: The number of ranges in the range array.
 *
 * range_array: An array of page ranges returned to the host.
 *
 */

struct dm_balloon_response {
	struct dm_header hdr;
	__u32 reservedz;
	__u32 more_pages:1;
	__u32 range_count:31;
	union dm_mem_page_range range_array[];
} __packed;

/*
 * Un-balloon message; this message is sent from the host
 * to the guest to give guest more memory.
 *
 * more_pages: If FALSE, this is the last message of the transaction.
 * if TRUE there will atleast one more message from the guest.
 *
 * reservedz: Reserved; must be set to zero.
 *
 * range_count: The number of ranges in the range array.
 *
 * range_array: An array of page ranges returned to the host.
 *
 */

struct dm_unballoon_request {
	struct dm_header hdr;
	__u32 more_pages:1;
	__u32 reservedz:31;
	__u32 range_count;
	union dm_mem_page_range range_array[];
} __packed;

/*
 * Un-balloon response message; this message is sent from the guest
 * to the host in response to an unballoon request.
 *
 */

struct dm_unballoon_response {
	struct dm_header hdr;
} __packed;

/*
 * Hot add request message. Message sent from the host to the guest.
 *
 * mem_range: Memory range to hot add.
 *
 * On Linux we currently don't support this since we cannot hot add
 * arbitrary granularity of memory.
 */

struct dm_hot_add {
	struct dm_header hdr;
	union dm_mem_page_range range;
} __packed;

/*
 * Hot add response message.
 * This message is sent by the guest to report the status of a hot add request.
 * If page_count is less than the requested page count, then the host should
 * assume all further hot add requests will fail, since this indicates that
 * the guest has hit an upper physical memory barrier.
 *
 * Hot adds may also fail due to low resources; in this case, the guest must
 * not complete this message until the hot add can succeed, and the host must
 * not send a new hot add request until the response is sent.
 * If VSC fails to hot add memory DYNMEM_NUMBER_OF_UNSUCCESSFUL_HOTADD_ATTEMPTS
 * times it fails the request.
 *
 *
 * page_count: number of pages that were successfully hot added.
 *
 * result: result of the operation 1: success, 0: failure.
 *
 */

struct dm_hot_add_response {
	struct dm_header hdr;
	__u32 page_count;
	__u32 result;
} __packed;

/*
 * Types of information sent from host to the guest.
 */

enum dm_info_type {
	INFO_TYPE_MAX_PAGE_CNT = 0,
	MAX_INFO_TYPE
};

/*
 * Header for the information message.
 */

struct dm_info_header {
	enum dm_info_type type;
	__u32 data_size;
} __packed;

/*
 * This message is sent from the host to the guest to pass
 * some relevant information (win8 addition).
 *
 * reserved: no used.
 * info_size: size of the information blob.
 * info: information blob.
 */

struct dm_info_msg {
	struct dm_header hdr;
	__u32 reserved;
	__u32 info_size;
	__u8  info[];
};

/*
 * End protocol definitions.
 */

/*
 * State to manage hot adding memory into the guest.
 * The range start_pfn : end_pfn specifies the range
 * that the host has asked us to hot add. The range
 * start_pfn : ha_end_pfn specifies the range that we have
 * currently hot added. We hot add in multiples of 128M
 * chunks; it is possible that we may not be able to bring
 * online all the pages in the region. The range
 * covered_start_pfn : covered_end_pfn defines the pages that can
 * be brough online.
 */

struct hv_hotadd_state {
	struct list_head list;
	unsigned long start_pfn;
	unsigned long covered_start_pfn;
	unsigned long covered_end_pfn;
	unsigned long ha_end_pfn;
	unsigned long end_pfn;
};

struct balloon_state {
	__u32 num_pages;
	struct work_struct wrk;
};

struct hot_add_wrk {
	union dm_mem_page_range ha_page_range;
	union dm_mem_page_range ha_region_range;
	struct work_struct wrk;
};

static bool hot_add = true;
static bool do_hot_add;
/*
 * Delay reporting memory pressure by
 * the specified number of seconds.
 */
static uint pressure_report_delay = 45;

module_param(hot_add, bool, (S_IRUGO | S_IWUSR));
MODULE_PARM_DESC(hot_add, "If set attempt memory hot_add");

module_param(pressure_report_delay, uint, (S_IRUGO | S_IWUSR));
MODULE_PARM_DESC(pressure_report_delay, "Delay in secs in reporting pressure");
static atomic_t trans_id = ATOMIC_INIT(0);

static int dm_ring_size = (5 * PAGE_SIZE);

/*
 * Driver specific state.
 */

enum hv_dm_state {
	DM_INITIALIZING = 0,
	DM_INITIALIZED,
	DM_BALLOON_UP,
	DM_BALLOON_DOWN,
	DM_HOT_ADD,
	DM_INIT_ERROR
};

static __u8 recv_buffer[PAGE_SIZE];
static __u8 *send_buffer;
#define PAGES_IN_2M	512
#define HA_CHUNK (32 * 1024)

struct hv_dynmem_device {
	struct hv_device *dev;
	enum hv_dm_state state;
	struct completion host_event;
	struct completion config_event;

	/*
	 * Number of pages we have currently ballooned out.
	 */
	unsigned int num_pages_ballooned;

	/*
	 * State to manage the ballooning (up) operation.
	 */
	struct balloon_state balloon_wrk;

	/*
	 * State to execute the "hot-add" operation.
	 */
	struct hot_add_wrk ha_wrk;

	/*
	 * This state tracks if the host has specified a hot-add
	 * region.
	 */
	bool host_specified_ha_region;

	/*
	 * State to synchronize hot-add.
	 */
	struct completion  ol_waitevent;
	bool ha_waiting;
	/*
	 * This thread handles hot-add
	 * requests from the host as well as notifying
	 * the host with regards to memory pressure in
	 * the guest.
	 */
	struct task_struct *thread;

	/*
	 * A list of hot-add regions.
	 */
	struct list_head ha_region_list;

	/*
	 * We start with the highest version we can support
	 * and downgrade based on the host; we save here the
	 * next version to try.
	 */
	__u32 next_version;
};

static struct hv_dynmem_device dm_device;

#ifdef CONFIG_MEMORY_HOTPLUG

static void hv_bring_pgs_online(unsigned long start_pfn, unsigned long size)
{
	int i;

	for (i = 0; i < size; i++) {
		struct page *pg;
		pg = pfn_to_page(start_pfn + i);
		__online_page_set_limits(pg);
		__online_page_increment_counters(pg);
		__online_page_free(pg);
	}
}

static void hv_mem_hot_add(unsigned long start, unsigned long size,
				unsigned long pfn_count,
				struct hv_hotadd_state *has)
{
	int ret = 0;
	int i, nid;
	unsigned long start_pfn;
	unsigned long processed_pfn;
	unsigned long total_pfn = pfn_count;

	for (i = 0; i < (size/HA_CHUNK); i++) {
		start_pfn = start + (i * HA_CHUNK);
		has->ha_end_pfn +=  HA_CHUNK;

		if (total_pfn > HA_CHUNK) {
			processed_pfn = HA_CHUNK;
			total_pfn -= HA_CHUNK;
		} else {
			processed_pfn = total_pfn;
			total_pfn = 0;
		}

		has->covered_end_pfn +=  processed_pfn;

		init_completion(&dm_device.ol_waitevent);
		dm_device.ha_waiting = true;

		nid = memory_add_physaddr_to_nid(PFN_PHYS(start_pfn));
		ret = add_memory(nid, PFN_PHYS((start_pfn)),
				(HA_CHUNK << PAGE_SHIFT));

		if (ret) {
			pr_info("hot_add memory failed error is %d\n", ret);
			if (ret == -EEXIST) {
				/*
				 * This error indicates that the error
				 * is not a transient failure. This is the
				 * case where the guest's physical address map
				 * precludes hot adding memory. Stop all further
				 * memory hot-add.
				 */
				do_hot_add = false;
			}
			has->ha_end_pfn -= HA_CHUNK;
			has->covered_end_pfn -=  processed_pfn;
			break;
		}

		/*
		 * Wait for the memory block to be onlined.
		 * Since the hot add has succeeded, it is ok to
		 * proceed even if the pages in the hot added region
		 * have not been "onlined" within the allowed time.
		 */
		wait_for_completion_timeout(&dm_device.ol_waitevent, 5*HZ);

	}

	return;
}

static void hv_online_page(struct page *pg)
{
	struct list_head *cur;
	struct hv_hotadd_state *has;
	unsigned long cur_start_pgp;
	unsigned long cur_end_pgp;

	if (dm_device.ha_waiting) {
		dm_device.ha_waiting = false;
		complete(&dm_device.ol_waitevent);
	}

	list_for_each(cur, &dm_device.ha_region_list) {
		has = list_entry(cur, struct hv_hotadd_state, list);
		cur_start_pgp = (unsigned long)
				pfn_to_page(has->covered_start_pfn);
		cur_end_pgp = (unsigned long)pfn_to_page(has->covered_end_pfn);

		if (((unsigned long)pg >= cur_start_pgp) &&
			((unsigned long)pg < cur_end_pgp)) {
			/*
			 * This frame is currently backed; online the
			 * page.
			 */
			__online_page_set_limits(pg);
			__online_page_increment_counters(pg);
			__online_page_free(pg);
			has->covered_start_pfn++;
		}
	}
}

static bool pfn_covered(unsigned long start_pfn, unsigned long pfn_cnt)
{
	struct list_head *cur;
	struct hv_hotadd_state *has;
	unsigned long residual, new_inc;

	if (list_empty(&dm_device.ha_region_list))
		return false;

	list_for_each(cur, &dm_device.ha_region_list) {
		has = list_entry(cur, struct hv_hotadd_state, list);

		/*
		 * If the pfn range we are dealing with is not in the current
		 * "hot add block", move on.
		 */
		if ((start_pfn >= has->end_pfn))
			continue;
		/*
		 * If the current hot add-request extends beyond
		 * our current limit; extend it.
		 */
		if ((start_pfn + pfn_cnt) > has->end_pfn) {
			residual = (start_pfn + pfn_cnt - has->end_pfn);
			/*
			 * Extend the region by multiples of HA_CHUNK.
			 */
			new_inc = (residual / HA_CHUNK) * HA_CHUNK;
			if (residual % HA_CHUNK)
				new_inc += HA_CHUNK;

			has->end_pfn += new_inc;
		}

		/*
		 * If the current start pfn is not where the covered_end
		 * is, update it.
		 */

		if (has->covered_end_pfn != start_pfn) {
			has->covered_end_pfn = start_pfn;
			has->covered_start_pfn = start_pfn;
		}
		return true;

	}

	return false;
}

static unsigned long handle_pg_range(unsigned long pg_start,
					unsigned long pg_count)
{
	unsigned long start_pfn = pg_start;
	unsigned long pfn_cnt = pg_count;
	unsigned long size;
	struct list_head *cur;
	struct hv_hotadd_state *has;
	unsigned long pgs_ol = 0;
	unsigned long old_covered_state;

	if (list_empty(&dm_device.ha_region_list))
		return 0;

	list_for_each(cur, &dm_device.ha_region_list) {
		has = list_entry(cur, struct hv_hotadd_state, list);

		/*
		 * If the pfn range we are dealing with is not in the current
		 * "hot add block", move on.
		 */
		if ((start_pfn >= has->end_pfn))
			continue;

		old_covered_state = has->covered_end_pfn;

		if (start_pfn < has->ha_end_pfn) {
			/*
			 * This is the case where we are backing pages
			 * in an already hot added region. Bring
			 * these pages online first.
			 */
			pgs_ol = has->ha_end_pfn - start_pfn;
			if (pgs_ol > pfn_cnt)
				pgs_ol = pfn_cnt;
			hv_bring_pgs_online(start_pfn, pgs_ol);
			has->covered_end_pfn +=  pgs_ol;
			has->covered_start_pfn +=  pgs_ol;
			pfn_cnt -= pgs_ol;
		}

		if ((has->ha_end_pfn < has->end_pfn) && (pfn_cnt > 0)) {
			/*
			 * We have some residual hot add range
			 * that needs to be hot added; hot add
			 * it now. Hot add a multiple of
			 * of HA_CHUNK that fully covers the pages
			 * we have.
			 */
			size = (has->end_pfn - has->ha_end_pfn);
			if (pfn_cnt <= size) {
				size = ((pfn_cnt / HA_CHUNK) * HA_CHUNK);
				if (pfn_cnt % HA_CHUNK)
					size += HA_CHUNK;
			} else {
				pfn_cnt = size;
			}
			hv_mem_hot_add(has->ha_end_pfn, size, pfn_cnt, has);
		}
		/*
		 * If we managed to online any pages that were given to us,
		 * we declare success.
		 */
		return has->covered_end_pfn - old_covered_state;

	}

	return 0;
}

static unsigned long process_hot_add(unsigned long pg_start,
					unsigned long pfn_cnt,
					unsigned long rg_start,
					unsigned long rg_size)
{
	struct hv_hotadd_state *ha_region = NULL;

	if (pfn_cnt == 0)
		return 0;

	if (!dm_device.host_specified_ha_region)
		if (pfn_covered(pg_start, pfn_cnt))
			goto do_pg_range;

	/*
	 * If the host has specified a hot-add range; deal with it first.
	 */

	if (rg_size != 0) {
		ha_region = kzalloc(sizeof(struct hv_hotadd_state), GFP_KERNEL);
		if (!ha_region)
			return 0;

		INIT_LIST_HEAD(&ha_region->list);

		list_add_tail(&ha_region->list, &dm_device.ha_region_list);
		ha_region->start_pfn = rg_start;
		ha_region->ha_end_pfn = rg_start;
		ha_region->covered_start_pfn = pg_start;
		ha_region->covered_end_pfn = pg_start;
		ha_region->end_pfn = rg_start + rg_size;
	}

do_pg_range:
	/*
	 * Process the page range specified; bringing them
	 * online if possible.
	 */
	return handle_pg_range(pg_start, pfn_cnt);
}

#endif

static void hot_add_req(struct work_struct *dummy)
{
	struct dm_hot_add_response resp;
#ifdef CONFIG_MEMORY_HOTPLUG
	unsigned long pg_start, pfn_cnt;
	unsigned long rg_start, rg_sz;
#endif
	struct hv_dynmem_device *dm = &dm_device;

	memset(&resp, 0, sizeof(struct dm_hot_add_response));
	resp.hdr.type = DM_MEM_HOT_ADD_RESPONSE;
	resp.hdr.size = sizeof(struct dm_hot_add_response);
	resp.hdr.trans_id = atomic_inc_return(&trans_id);

#ifdef CONFIG_MEMORY_HOTPLUG
	pg_start = dm->ha_wrk.ha_page_range.finfo.start_page;
	pfn_cnt = dm->ha_wrk.ha_page_range.finfo.page_cnt;

	rg_start = dm->ha_wrk.ha_region_range.finfo.start_page;
	rg_sz = dm->ha_wrk.ha_region_range.finfo.page_cnt;

	if ((rg_start == 0) && (!dm->host_specified_ha_region)) {
		unsigned long region_size;
		unsigned long region_start;

		/*
		 * The host has not specified the hot-add region.
		 * Based on the hot-add page range being specified,
		 * compute a hot-add region that can cover the pages
		 * that need to be hot-added while ensuring the alignment
		 * and size requirements of Linux as it relates to hot-add.
		 */
		region_start = pg_start;
		region_size = (pfn_cnt / HA_CHUNK) * HA_CHUNK;
		if (pfn_cnt % HA_CHUNK)
			region_size += HA_CHUNK;

		region_start = (pg_start / HA_CHUNK) * HA_CHUNK;

		rg_start = region_start;
		rg_sz = region_size;
	}

	if (do_hot_add)
		resp.page_count = process_hot_add(pg_start, pfn_cnt,
						rg_start, rg_sz);
#endif
	/*
	 * The result field of the response structure has the
	 * following semantics:
	 *
	 * 1. If all or some pages hot-added: Guest should return success.
	 *
	 * 2. If no pages could be hot-added:
	 *
	 * If the guest returns success, then the host
	 * will not attempt any further hot-add operations. This
	 * signifies a permanent failure.
	 *
	 * If the guest returns failure, then this failure will be
	 * treated as a transient failure and the host may retry the
	 * hot-add operation after some delay.
	 */
	if (resp.page_count > 0)
		resp.result = 1;
	else if (!do_hot_add)
		resp.result = 1;
	else
		resp.result = 0;

	if (!do_hot_add || (resp.page_count == 0))
		pr_info("Memory hot add failed\n");

	dm->state = DM_INITIALIZED;
	vmbus_sendpacket(dm->dev->channel, &resp,
			sizeof(struct dm_hot_add_response),
			(unsigned long)NULL,
			VM_PKT_DATA_INBAND, 0);
}

static void process_info(struct hv_dynmem_device *dm, struct dm_info_msg *msg)
{
	struct dm_info_header *info_hdr;

	info_hdr = (struct dm_info_header *)msg->info;

	switch (info_hdr->type) {
	case INFO_TYPE_MAX_PAGE_CNT:
		pr_info("Received INFO_TYPE_MAX_PAGE_CNT\n");
		pr_info("Data Size is %d\n", info_hdr->data_size);
		break;
	default:
		pr_info("Received Unknown type: %d\n", info_hdr->type);
	}
}

static unsigned long compute_balloon_floor(void)
{
	unsigned long min_pages;
#define MB2PAGES(mb) ((mb) << (20 - PAGE_SHIFT))
	/* Simple continuous piecewiese linear function:
	 *  max MiB -> min MiB  gradient
	 *       0         0
	 *      16        16
	 *      32        24
	 *     128        72    (1/2)
	 *     512       168    (1/4)
	 *    2048       360    (1/8)
	 *    8192       552    (1/32)
	 *   32768      1320
	 *  131072      4392
	 */
	if (totalram_pages < MB2PAGES(128))
		min_pages = MB2PAGES(8) + (totalram_pages >> 1);
	else if (totalram_pages < MB2PAGES(512))
		min_pages = MB2PAGES(40) + (totalram_pages >> 2);
	else if (totalram_pages < MB2PAGES(2048))
		min_pages = MB2PAGES(104) + (totalram_pages >> 3);
	else
		min_pages = MB2PAGES(296) + (totalram_pages >> 5);
#undef MB2PAGES
	return min_pages;
}

/*
 * Post our status as it relates memory pressure to the
 * host. Host expects the guests to post this status
 * periodically at 1 second intervals.
 *
 * The metrics specified in this protocol are very Windows
 * specific and so we cook up numbers here to convey our memory
 * pressure.
 */

static void post_status(struct hv_dynmem_device *dm)
{
	struct dm_status status;
	struct sysinfo val;

	if (pressure_report_delay > 0) {
		--pressure_report_delay;
		return;
	}
	si_meminfo(&val);
	memset(&status, 0, sizeof(struct dm_status));
	status.hdr.type = DM_STATUS_REPORT;
	status.hdr.size = sizeof(struct dm_status);
	status.hdr.trans_id = atomic_inc_return(&trans_id);

	/*
	 * The host expects the guest to report free memory.
	 * Further, the host expects the pressure information to
	 * include the ballooned out pages.
	 * For a given amount of memory that we are managing, we
	 * need to compute a floor below which we should not balloon.
	 * Compute this and add it to the pressure report.
	 */
	status.num_avail = val.freeram;
	status.num_committed = vm_memory_committed() +
				dm->num_pages_ballooned +
				compute_balloon_floor();

	/*
	 * If our transaction ID is no longer current, just don't
	 * send the status. This can happen if we were interrupted
	 * after we picked our transaction ID.
	 */
	if (status.hdr.trans_id != atomic_read(&trans_id))
		return;

	vmbus_sendpacket(dm->dev->channel, &status,
				sizeof(struct dm_status),
				(unsigned long)NULL,
				VM_PKT_DATA_INBAND, 0);

}

static void free_balloon_pages(struct hv_dynmem_device *dm,
			 union dm_mem_page_range *range_array)
{
	int num_pages = range_array->finfo.page_cnt;
	__u64 start_frame = range_array->finfo.start_page;
	struct page *pg;
	int i;

	for (i = 0; i < num_pages; i++) {
		pg = pfn_to_page(i + start_frame);
		__free_page(pg);
		dm->num_pages_ballooned--;
	}
}

static int  alloc_balloon_pages(struct hv_dynmem_device *dm, int num_pages,
			 struct dm_balloon_response *bl_resp, int alloc_unit,
			 bool *alloc_error)
{
	int i = 0;
	struct page *pg;

	if (num_pages < alloc_unit)
		return 0;

	for (i = 0; (i * alloc_unit) < num_pages; i++) {
		if (bl_resp->hdr.size + sizeof(union dm_mem_page_range) >
			PAGE_SIZE)
			return i * alloc_unit;

		/*
		 * We execute this code in a thread context. Furthermore,
		 * we don't want the kernel to try too hard.
		 */
		pg = alloc_pages(GFP_HIGHUSER | __GFP_NORETRY |
				__GFP_NOMEMALLOC | __GFP_NOWARN,
				get_order(alloc_unit << PAGE_SHIFT));

		if (!pg) {
			*alloc_error = true;
			return i * alloc_unit;
		}

		dm->num_pages_ballooned += alloc_unit;

		/*
		 * If we allocatted 2M pages; split them so we
		 * can free them in any order we get.
		 */

		if (alloc_unit != 1)
			split_page(pg, get_order(alloc_unit << PAGE_SHIFT));

		bl_resp->range_count++;
		bl_resp->range_array[i].finfo.start_page =
			page_to_pfn(pg);
		bl_resp->range_array[i].finfo.page_cnt = alloc_unit;
		bl_resp->hdr.size += sizeof(union dm_mem_page_range);

	}

	return num_pages;
}

static void balloon_up(struct work_struct *dummy)
{
	int num_pages = dm_device.balloon_wrk.num_pages;
	int num_ballooned = 0;
	struct dm_balloon_response *bl_resp;
	int alloc_unit;
	int ret;
	bool alloc_error = false;
	bool done = false;
	int i;

	/*
	 * We will attempt 2M allocations. However, if we fail to
	 * allocate 2M chunks, we will go back to 4k allocations.
	 */
	alloc_unit = 512;

	while (!done) {
		bl_resp = (struct dm_balloon_response *)send_buffer;
		memset(send_buffer, 0, PAGE_SIZE);
		bl_resp->hdr.type = DM_BALLOON_RESPONSE;
		bl_resp->hdr.trans_id = atomic_inc_return(&trans_id);
		bl_resp->hdr.size = sizeof(struct dm_balloon_response);
		bl_resp->more_pages = 1;

		num_pages -= num_ballooned;
		num_ballooned = alloc_balloon_pages(&dm_device, num_pages,
						bl_resp, alloc_unit,
						 &alloc_error);

		if ((alloc_error) && (alloc_unit != 1)) {
			alloc_unit = 1;
			continue;
		}

		if ((alloc_error) || (num_ballooned == num_pages)) {
			bl_resp->more_pages = 0;
			done = true;
			dm_device.state = DM_INITIALIZED;
		}

		/*
		 * We are pushing a lot of data through the channel;
		 * deal with transient failures caused because of the
		 * lack of space in the ring buffer.
		 */

		do {
			ret = vmbus_sendpacket(dm_device.dev->channel,
						bl_resp,
						bl_resp->hdr.size,
						(unsigned long)NULL,
						VM_PKT_DATA_INBAND, 0);

			if (ret == -EAGAIN)
				msleep(20);

		} while (ret == -EAGAIN);

		if (ret) {
			/*
			 * Free up the memory we allocatted.
			 */
			pr_info("Balloon response failed\n");

			for (i = 0; i < bl_resp->range_count; i++)
				free_balloon_pages(&dm_device,
						 &bl_resp->range_array[i]);

			done = true;
		}
	}

}

static void balloon_down(struct hv_dynmem_device *dm,
			struct dm_unballoon_request *req)
{
	union dm_mem_page_range *range_array = req->range_array;
	int range_count = req->range_count;
	struct dm_unballoon_response resp;
	int i;

	for (i = 0; i < range_count; i++)
		free_balloon_pages(dm, &range_array[i]);

	if (req->more_pages == 1)
		return;

	memset(&resp, 0, sizeof(struct dm_unballoon_response));
	resp.hdr.type = DM_UNBALLOON_RESPONSE;
	resp.hdr.trans_id = atomic_inc_return(&trans_id);
	resp.hdr.size = sizeof(struct dm_unballoon_response);

	vmbus_sendpacket(dm_device.dev->channel, &resp,
				sizeof(struct dm_unballoon_response),
				(unsigned long)NULL,
				VM_PKT_DATA_INBAND, 0);

	dm->state = DM_INITIALIZED;
}

static void balloon_onchannelcallback(void *context);

static int dm_thread_func(void *dm_dev)
{
	struct hv_dynmem_device *dm = dm_dev;
	int t;

	while (!kthread_should_stop()) {
		t = wait_for_completion_timeout(&dm_device.config_event, 1*HZ);
		/*
		 * The host expects us to post information on the memory
		 * pressure every second.
		 */

		if (t == 0)
			post_status(dm);

	}

	return 0;
}

static void version_resp(struct hv_dynmem_device *dm,
			struct dm_version_response *vresp)
{
	struct dm_version_request version_req;
	int ret;

	if (vresp->is_accepted) {
		/*
		 * We are done; wakeup the
		 * context waiting for version
		 * negotiation.
		 */
		complete(&dm->host_event);
		return;
	}
	/*
	 * If there are more versions to try, continue
	 * with negotiations; if not
	 * shutdown the service since we are not able
	 * to negotiate a suitable version number
	 * with the host.
	 */
	if (dm->next_version == 0)
		goto version_error;

	dm->next_version = 0;
	memset(&version_req, 0, sizeof(struct dm_version_request));
	version_req.hdr.type = DM_VERSION_REQUEST;
	version_req.hdr.size = sizeof(struct dm_version_request);
	version_req.hdr.trans_id = atomic_inc_return(&trans_id);
	version_req.version.version = DYNMEM_PROTOCOL_VERSION_WIN7;
	version_req.is_last_attempt = 1;

	ret = vmbus_sendpacket(dm->dev->channel, &version_req,
				sizeof(struct dm_version_request),
				(unsigned long)NULL,
				VM_PKT_DATA_INBAND, 0);

	if (ret)
		goto version_error;

	return;

version_error:
	dm->state = DM_INIT_ERROR;
	complete(&dm->host_event);
}

static void cap_resp(struct hv_dynmem_device *dm,
			struct dm_capabilities_resp_msg *cap_resp)
{
	if (!cap_resp->is_accepted) {
		pr_info("Capabilities not accepted by host\n");
		dm->state = DM_INIT_ERROR;
	}
	complete(&dm->host_event);
}

static void balloon_onchannelcallback(void *context)
{
	struct hv_device *dev = context;
	u32 recvlen;
	u64 requestid;
	struct dm_message *dm_msg;
	struct dm_header *dm_hdr;
	struct hv_dynmem_device *dm = hv_get_drvdata(dev);
	struct dm_balloon *bal_msg;
	struct dm_hot_add *ha_msg;
	union dm_mem_page_range *ha_pg_range;
	union dm_mem_page_range *ha_region;

	memset(recv_buffer, 0, sizeof(recv_buffer));
	vmbus_recvpacket(dev->channel, recv_buffer,
			 PAGE_SIZE, &recvlen, &requestid);

	if (recvlen > 0) {
		dm_msg = (struct dm_message *)recv_buffer;
		dm_hdr = &dm_msg->hdr;

		switch (dm_hdr->type) {
		case DM_VERSION_RESPONSE:
			version_resp(dm,
				 (struct dm_version_response *)dm_msg);
			break;

		case DM_CAPABILITIES_RESPONSE:
			cap_resp(dm,
				 (struct dm_capabilities_resp_msg *)dm_msg);
			break;

		case DM_BALLOON_REQUEST:
			if (dm->state == DM_BALLOON_UP)
				pr_warn("Currently ballooning\n");
			bal_msg = (struct dm_balloon *)recv_buffer;
			dm->state = DM_BALLOON_UP;
			dm_device.balloon_wrk.num_pages = bal_msg->num_pages;
			schedule_work(&dm_device.balloon_wrk.wrk);
			break;

		case DM_UNBALLOON_REQUEST:
			dm->state = DM_BALLOON_DOWN;
			balloon_down(dm,
				 (struct dm_unballoon_request *)recv_buffer);
			break;

		case DM_MEM_HOT_ADD_REQUEST:
			if (dm->state == DM_HOT_ADD)
				pr_warn("Currently hot-adding\n");
			dm->state = DM_HOT_ADD;
			ha_msg = (struct dm_hot_add *)recv_buffer;
			if (ha_msg->hdr.size == sizeof(struct dm_hot_add)) {
				/*
				 * This is a normal hot-add request specifying
				 * hot-add memory.
				 */
				ha_pg_range = &ha_msg->range;
				dm->ha_wrk.ha_page_range = *ha_pg_range;
				dm->ha_wrk.ha_region_range.page_range = 0;
			} else {
				/*
				 * Host is specifying that we first hot-add
				 * a region and then partially populate this
				 * region.
				 */
				dm->host_specified_ha_region = true;
				ha_pg_range = &ha_msg->range;
				ha_region = &ha_pg_range[1];
				dm->ha_wrk.ha_page_range = *ha_pg_range;
				dm->ha_wrk.ha_region_range = *ha_region;
			}
			schedule_work(&dm_device.ha_wrk.wrk);
			break;

		case DM_INFO_MESSAGE:
			process_info(dm, (struct dm_info_msg *)dm_msg);
			break;

		default:
			pr_err("Unhandled message: type: %d\n", dm_hdr->type);

		}
	}

}

static int balloon_probe(struct hv_device *dev,
			const struct hv_vmbus_device_id *dev_id)
{
	int ret, t;
	struct dm_version_request version_req;
	struct dm_capabilities cap_msg;

	do_hot_add = hot_add;

	/*
	 * First allocate a send buffer.
	 */

	send_buffer = kmalloc(PAGE_SIZE, GFP_KERNEL);
	if (!send_buffer)
		return -ENOMEM;

	ret = vmbus_open(dev->channel, dm_ring_size, dm_ring_size, NULL, 0,
			balloon_onchannelcallback, dev);

	if (ret)
		goto probe_error0;

	dm_device.dev = dev;
	dm_device.state = DM_INITIALIZING;
	dm_device.next_version = DYNMEM_PROTOCOL_VERSION_WIN7;
	init_completion(&dm_device.host_event);
	init_completion(&dm_device.config_event);
	INIT_LIST_HEAD(&dm_device.ha_region_list);
	INIT_WORK(&dm_device.balloon_wrk.wrk, balloon_up);
	INIT_WORK(&dm_device.ha_wrk.wrk, hot_add_req);
	dm_device.host_specified_ha_region = false;

	dm_device.thread =
		 kthread_run(dm_thread_func, &dm_device, "hv_balloon");
	if (IS_ERR(dm_device.thread)) {
		ret = PTR_ERR(dm_device.thread);
		goto probe_error1;
	}

#ifdef CONFIG_MEMORY_HOTPLUG
	set_online_page_callback(&hv_online_page);
#endif

	hv_set_drvdata(dev, &dm_device);
	/*
	 * Initiate the hand shake with the host and negotiate
	 * a version that the host can support. We start with the
	 * highest version number and go down if the host cannot
	 * support it.
	 */
	memset(&version_req, 0, sizeof(struct dm_version_request));
	version_req.hdr.type = DM_VERSION_REQUEST;
	version_req.hdr.size = sizeof(struct dm_version_request);
	version_req.hdr.trans_id = atomic_inc_return(&trans_id);
	version_req.version.version = DYNMEM_PROTOCOL_VERSION_WIN8;
	version_req.is_last_attempt = 0;

	ret = vmbus_sendpacket(dev->channel, &version_req,
				sizeof(struct dm_version_request),
				(unsigned long)NULL,
				VM_PKT_DATA_INBAND, 0);
	if (ret)
		goto probe_error2;

	t = wait_for_completion_timeout(&dm_device.host_event, 5*HZ);
	if (t == 0) {
		ret = -ETIMEDOUT;
		goto probe_error2;
	}

	/*
	 * If we could not negotiate a compatible version with the host
	 * fail the probe function.
	 */
	if (dm_device.state == DM_INIT_ERROR) {
		ret = -ETIMEDOUT;
		goto probe_error2;
	}
	/*
	 * Now submit our capabilities to the host.
	 */
	memset(&cap_msg, 0, sizeof(struct dm_capabilities));
	cap_msg.hdr.type = DM_CAPABILITIES_REPORT;
	cap_msg.hdr.size = sizeof(struct dm_capabilities);
	cap_msg.hdr.trans_id = atomic_inc_return(&trans_id);

	cap_msg.caps.cap_bits.balloon = 1;
	cap_msg.caps.cap_bits.hot_add = 1;

	/*
	 * Specify our alignment requirements as it relates
	 * memory hot-add. Specify 128MB alignment.
	 */
	cap_msg.caps.cap_bits.hot_add_alignment = 7;

	/*
	 * Currently the host does not use these
	 * values and we set them to what is done in the
	 * Windows driver.
	 */
	cap_msg.min_page_cnt = 0;
	cap_msg.max_page_number = -1;

	ret = vmbus_sendpacket(dev->channel, &cap_msg,
				sizeof(struct dm_capabilities),
				(unsigned long)NULL,
				VM_PKT_DATA_INBAND, 0);
	if (ret)
		goto probe_error2;

	t = wait_for_completion_timeout(&dm_device.host_event, 5*HZ);
	if (t == 0) {
		ret = -ETIMEDOUT;
		goto probe_error2;
	}

	/*
	 * If the host does not like our capabilities,
	 * fail the probe function.
	 */
	if (dm_device.state == DM_INIT_ERROR) {
		ret = -ETIMEDOUT;
		goto probe_error2;
	}

	dm_device.state = DM_INITIALIZED;

	return 0;

probe_error2:
#ifdef CONFIG_MEMORY_HOTPLUG
	restore_online_page_callback(&hv_online_page);
#endif
	kthread_stop(dm_device.thread);

probe_error1:
	vmbus_close(dev->channel);
probe_error0:
	kfree(send_buffer);
	return ret;
}

static int balloon_remove(struct hv_device *dev)
{
	struct hv_dynmem_device *dm = hv_get_drvdata(dev);
	struct list_head *cur, *tmp;
	struct hv_hotadd_state *has;

	if (dm->num_pages_ballooned != 0)
		pr_warn("Ballooned pages: %d\n", dm->num_pages_ballooned);

	cancel_work_sync(&dm->balloon_wrk.wrk);
	cancel_work_sync(&dm->ha_wrk.wrk);

	vmbus_close(dev->channel);
	kthread_stop(dm->thread);
	kfree(send_buffer);
#ifdef CONFIG_MEMORY_HOTPLUG
	restore_online_page_callback(&hv_online_page);
#endif
	list_for_each_safe(cur, tmp, &dm->ha_region_list) {
		has = list_entry(cur, struct hv_hotadd_state, list);
		list_del(&has->list);
		kfree(has);
	}

	return 0;
}

static const struct hv_vmbus_device_id id_table[] = {
	/* Dynamic Memory Class ID */
	/* 525074DC-8985-46e2-8057-A307DC18A502 */
	{ HV_DM_GUID, },
	{ },
};

MODULE_DEVICE_TABLE(vmbus, id_table);

static  struct hv_driver balloon_drv = {
	.name = "hv_balloon",
	.id_table = id_table,
	.probe =  balloon_probe,
	.remove =  balloon_remove,
};

static int __init init_balloon_drv(void)
{

	return vmbus_driver_register(&balloon_drv);
}

module_init(init_balloon_drv);

MODULE_DESCRIPTION("Hyper-V Balloon");
MODULE_VERSION(HV_DRV_VERSION);
MODULE_LICENSE("GPL");


text:
import {Component, Output, EventEmitter} from 'angular2/core';

@Component({
    selector: 'search-box',
    template: `
        <div>
            <input #input type="text" (input)="update.emit(input.value)">
        </div>
    `
})
export class SearchBox {
    @Output() update = new EventEmitter();

    ngOnInit(){
        this.update.emit("");
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.control;

import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn;

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

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.model.Autor;

@RestController
@RequestMapping("/autor")
public class AutorController {
	private static List<Autor> autores = CriaAutores();

	public static List<Autor> CriaAutores(){
		List<Autor> autores = new ArrayList<Autor>();
		//SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");

		Autor a1 = new Autor(1, "Autor", "1", "Basileiro", "27/07/1945");
		Autor a2 = new Autor(2, "Autor", "2", "Basileiro", "27/07/1975");
		Autor a3 = new Autor(3, "Autor", "3", "Basileiro", "27/07/1980");
		Autor a4 = new Autor(4, "Autor", "4", "Basileiro", "27/07/1950");

		autores.add(a1);
		autores.add(a2);
		autores.add(a3);
		autores.add(a4);
		return autores;
	}
	@RequestMapping(method = RequestMethod.GET, value ="/{id}")
    public ResponseEntity<Autor> getAutorById(@PathVariable("id") int idAutor) {
		Autor ar = null;
		for(Autor a : autores){
			if (a.getIdAutor() == idAutor){
				if (!a.hasLinks()){
					a.add(linkTo(methodOn(AutorController.class).getAutorById(a.getIdAutor())).withSelfRel());
				}
				ar = a;
			}

		}
        return new ResponseEntity<Autor>(ar, HttpStatus.OK);
    }

}


text:
package quickbi_public

//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

import (
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)

// UpdateDataLevelPermissionStatus invokes the quickbi_public.UpdateDataLevelPermissionStatus API synchronously
func (client *Client) UpdateDataLevelPermissionStatus(request *UpdateDataLevelPermissionStatusRequest) (response *UpdateDataLevelPermissionStatusResponse, err error) {
	response = CreateUpdateDataLevelPermissionStatusResponse()
	err = client.DoAction(request, response)
	return
}

// UpdateDataLevelPermissionStatusWithChan invokes the quickbi_public.UpdateDataLevelPermissionStatus API asynchronously
func (client *Client) UpdateDataLevelPermissionStatusWithChan(request *UpdateDataLevelPermissionStatusRequest) (<-chan *UpdateDataLevelPermissionStatusResponse, <-chan error) {
	responseChan := make(chan *UpdateDataLevelPermissionStatusResponse, 1)
	errChan := make(chan error, 1)
	err := client.AddAsyncTask(func() {
		defer close(responseChan)
		defer close(errChan)
		response, err := client.UpdateDataLevelPermissionStatus(request)
		if err != nil {
			errChan <- err
		} else {
			responseChan <- response
		}
	})
	if err != nil {
		errChan <- err
		close(responseChan)
		close(errChan)
	}
	return responseChan, errChan
}

// UpdateDataLevelPermissionStatusWithCallback invokes the quickbi_public.UpdateDataLevelPermissionStatus API asynchronously
func (client *Client) UpdateDataLevelPermissionStatusWithCallback(request *UpdateDataLevelPermissionStatusRequest, callback func(response *UpdateDataLevelPermissionStatusResponse, err error)) <-chan int {
	result := make(chan int, 1)
	err := client.AddAsyncTask(func() {
		var response *UpdateDataLevelPermissionStatusResponse
		var err error
		defer close(result)
		response, err = client.UpdateDataLevelPermissionStatus(request)
		callback(response, err)
		result <- 1
	})
	if err != nil {
		defer close(result)
		callback(nil, err)
		result <- 0
	}
	return result
}

// UpdateDataLevelPermissionStatusRequest is the request struct for api UpdateDataLevelPermissionStatus
type UpdateDataLevelPermissionStatusRequest struct {
	*requests.RpcRequest
	IsOpen      requests.Integer `position:"Query" name:"IsOpen"`
	RuleType    string           `position:"Query" name:"RuleType"`
	AccessPoint string           `position:"Query" name:"AccessPoint"`
	SignType    string           `position:"Query" name:"SignType"`
	CubeId      string           `position:"Query" name:"CubeId"`
}

// UpdateDataLevelPermissionStatusResponse is the response struct for api UpdateDataLevelPermissionStatus
type UpdateDataLevelPermissionStatusResponse struct {
	*responses.BaseResponse
	RequestId string `json:"RequestId" xml:"RequestId"`
	Result    bool   `json:"Result" xml:"Result"`
	Success   bool   `json:"Success" xml:"Success"`
}

// CreateUpdateDataLevelPermissionStatusRequest creates a request to invoke UpdateDataLevelPermissionStatus API
func CreateUpdateDataLevelPermissionStatusRequest() (request *UpdateDataLevelPermissionStatusRequest) {
	request = &UpdateDataLevelPermissionStatusRequest{
		RpcRequest: &requests.RpcRequest{},
	}
	request.InitWithApiInfo("quickbi-public", "2022-01-01", "UpdateDataLevelPermissionStatus", "quickbi", "openAPI")
	request.Method = requests.POST
	return
}

// CreateUpdateDataLevelPermissionStatusResponse creates a response to parse from UpdateDataLevelPermissionStatus response
func CreateUpdateDataLevelPermissionStatusResponse() (response *UpdateDataLevelPermissionStatusResponse) {
	response = &UpdateDataLevelPermissionStatusResponse{
		BaseResponse: &responses.BaseResponse{},
	}
	return
}


text:
package com.monstarlab.servicedroid.activity;

import java.util.Calendar;
import java.util.Date;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.widget.ShareActionProvider;
import com.monstarlab.servicedroid.model.Models.Literature;
import com.monstarlab.servicedroid.model.Models.Placements;
import com.monstarlab.servicedroid.model.Models.ReturnVisits;
import com.monstarlab.servicedroid.model.Models.TimeEntries;
import com.monstarlab.servicedroid.service.BackupService;
import com.monstarlab.servicedroid.util.TimeUtil;
import com.monstarlab.servicedroid.R;

public class StatisticsActivity extends SherlockActivity {

	private static final String TAG = "StatisticsActivity";

	private static final int TIME_PERIOD_MONTH = 0;
	private static final int TIME_PERIOD_YEAR = 1;

	//private TimeUtil mTimeHelper;

	//private static String[] CallsProjection = new String[] { Calls._ID, Calls.BIBLE_STUDY };
	private static String[] BibleStudiesProjection = new String[] { ReturnVisits._ID, ReturnVisits.DATE, ReturnVisits.IS_BIBLE_STUDY, ReturnVisits.CALL_ID };
	private static String[] TimeProjection = new String[] { TimeEntries._ID, TimeEntries.DATE, TimeEntries.LENGTH };
	private static String[] RVProjection = new String[] { ReturnVisits._ID, ReturnVisits.DATE, ReturnVisits.CALL_ID };
	private static String[] PlacementsProjection = new String[] { Placements._ID, Placements.DATE, Placements.QUANTITY, Literature.WEIGHT };

	private TextView mTimePeriodDisplay;
	private TextView mHoursDisplay;
	private TextView mRvsDisplay;
	//private TextView mMagsDisplay;
	//private TextView mBrochuresDisplay;
	//private TextView mBooksDisplay;
	private TextView mBibleStudiesDisplay;
    //private TextView mTractsDisplay;
    private TextView mPlacementsDisplay;
	private TextView mVideosDisplay;

	private int mCurrentMonth = TimeUtil.getCurrentMonth();
	private int mCurrentYear = TimeUtil.getCurrentYear(); // 1 - 12
	private int mTimeSpan = TIME_PERIOD_MONTH;

	private static int SERVICE_YEAR_START = 9; // Month, September

	private static final int SWIPE_MIN_DISTANCE = 120;
    private static final int SWIPE_MAX_OFF_PATH = 250;
    private static final int SWIPE_THRESHOLD_VELOCITY = 200;

	private static final int DIALOG_ROUND_ID = 1;

    private GestureDetector mGestureDetector;

	private ShareActionProvider mShareProvider;

	private Button mExtraTimeBtn;

	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.stats);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        mTimePeriodDisplay = (TextView)findViewById(R.id.stats_timeperiod);

        mHoursDisplay = (TextView)findViewById(R.id.hours);
        mRvsDisplay = (TextView)findViewById(R.id.rvs);
        //mMagsDisplay = (TextView)findViewById(R.id.magazines);
        //mBrochuresDisplay = (TextView)findViewById(R.id.brochures);
        //mBooksDisplay = (TextView)findViewById(R.id.books);
        mBibleStudiesDisplay = (TextView)findViewById(R.id.bible_studies);
        //mTractsDisplay = (TextView) findViewById(R.id.tracts);
		mPlacementsDisplay = (TextView) findViewById(R.id.placements);
		mVideosDisplay = (TextView) findViewById(R.id.videos);

        // Gesture detection
	    mGestureDetector = new GestureDetector(new MyGestureDetector());

        mExtraTimeBtn = (Button)findViewById(R.id.round_or_carry);
        mExtraTimeBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				promptExtraTime();
			}

        });
    }

	@Override
	protected void onResume() {
		super.onResume();

		fillData();
		toggleHintView();
	}

	protected void fillData() {
		mTimePeriodDisplay.setText(getTimePeriodText());
		mHoursDisplay.setText(getHours());
		mRvsDisplay.setText(getRVs());
		mBibleStudiesDisplay.setText(getBibleStudies());
        mPlacementsDisplay.setText(getPlacements());
		mVideosDisplay.setText(getVideos());

		toggleExtraTimeButton();
		setShareIntent();
	}

	protected void toggleExtraTimeButton() {
		// Extra Time, and on Monthly view. No need when looking at Service Year
		if (getTimeSpan() == TIME_PERIOD_MONTH && hasExtraTime()) {
			mExtraTimeBtn.setVisibility(View.VISIBLE);
		} else {
			mExtraTimeBtn.setVisibility(View.INVISIBLE);
		}
	}

	protected String getTimePeriodText() {
		if(mTimeSpan == TIME_PERIOD_MONTH) {
			String[] months = getResources().getStringArray(R.array.months_array);
			return months[mCurrentMonth-1] + " " + mCurrentYear;
		} else {
			return getString(R.string.service_year) + " " + mCurrentYear;
		}
	}

	protected String getBibleStudies() {
		Cursor c = getContentResolver().query(ReturnVisits.BIBLE_STUDIES_CONTENT_URI, BibleStudiesProjection, ReturnVisits.IS_BIBLE_STUDY + "=1 and " + getTimePeriodWhere(ReturnVisits.DATE), getTimePeriodArgs(mCurrentYear, mCurrentMonth), null);
		String numOfRVs = "0";
		if(c != null) {
			c.moveToFirst();
			numOfRVs = "" + c.getCount();
			c.close();
			c = null;
		}

		return numOfRVs;
	}

	protected String getPlacements() {
		Cursor c = getContentResolver().query(Placements.NON_VIDEOS_CONTENT_URI, PlacementsProjection, getTimePeriodWhere(Placements.DATE), getTimePeriodArgs(mCurrentYear, mCurrentMonth), null);
		int sum = 0;
		if(c != null) {
			c.moveToFirst();
			int weightCol = c.getColumnIndex(Literature.WEIGHT);
			int qtyCol = c.getColumnIndex(Placements.QUANTITY);
			while(!c.isAfterLast()) {
				sum +=  c.getInt(qtyCol) * c.getInt(weightCol);
				c.moveToNext();
			}
			c.close();
			c = null;
		}
		return ""+sum;
	}

	protected String getVideos() {
		Cursor c = getContentResolver().query(Placements.VIDEOS_CONTENT_URI, PlacementsProjection, getTimePeriodWhere(Placements.DATE), getTimePeriodArgs(mCurrentYear, mCurrentMonth), null);
		int sum = 0;
		if(c != null) {
			c.moveToFirst();
			int qtyCol = c.getColumnIndex(Placements.QUANTITY);
			while(!c.isAfterLast()) {
				sum += c.getInt(qtyCol);
				c.moveToNext();
			}
			c.close();
			c = null;
		}
		return ""+sum;

	}

	protected int getHoursSum() {

		Cursor c = getContentResolver().query(TimeEntries.CONTENT_URI, TimeProjection, getTimePeriodWhere(ReturnVisits.DATE), getTimePeriodArgs(mCurrentYear, mCurrentMonth), null);
		int sum = 0;
		if(c != null) {
			c.moveToFirst();
			while(!c.isAfterLast()) {
				sum += c.getInt(2);
				c.moveToNext();
			}
			c.close();
			c = null;
		}
		return sum;
	}

	protected String getHours() {
		return TimeUtil.toTimeString(getHoursSum(), getResources());
	}

	protected String getRVs() {
		Cursor c = getContentResolver().query(ReturnVisits.CONTENT_URI, RVProjection, getTimePeriodWhere(ReturnVisits.DATE), getTimePeriodArgs(mCurrentYear, mCurrentMonth), null);
		String numOfRVs = "0";
		if(c != null) {
			c.moveToFirst();
			numOfRVs = "" + c.getCount();
			c.close();
			c = null;
		}

		return numOfRVs;
	}

	protected void moveTimePeriodBackward() {
		if(mTimeSpan == TIME_PERIOD_MONTH) {
			mCurrentMonth--;
			if(mCurrentMonth <= 0) {
				mCurrentMonth = 12;
				mCurrentYear--;
			}
		} else {
			mCurrentYear--;
		}
	}

	protected void moveTimePeriodForward() {
		if(mTimeSpan == TIME_PERIOD_MONTH) {
			mCurrentMonth++;
			if(mCurrentMonth > 12) {
				mCurrentMonth = 1;
				mCurrentYear++;
			}
		} else {
			mCurrentYear++;
		}
	}

	protected String getTimePeriodWhere(String dateField) {
		return "("+dateField + " between ? and ?)";
	}

	protected String[] getTimePeriodArgs(int year, int month) {
		if(mTimeSpan == TIME_PERIOD_YEAR) {
			month = SERVICE_YEAR_START; // service year is from Sept (9) - Aug (8)
			year = year - 1; //year is always in the future
		}

		Calendar cal = Calendar.getInstance();
		cal.set(year, month - 1, 1, 0, 0, 0);
		String[] args = new String[2];

		//beginning of month
		Date start = cal.getTime();
		args[0] = TimeUtil.getSQLTextFromDate(start);

		if(mTimeSpan == TIME_PERIOD_MONTH) {
			cal.add(Calendar.MONTH, 1);
		} else {
			cal.add(Calendar.YEAR, 1);
		}

		cal.add(Calendar.SECOND, -1);

		Date end = cal.getTime();

		//end of month
		args[1] = TimeUtil.getSQLTextFromTime(end);

		return args;
	}

	protected void setTimeSpan(int span) {
		mTimeSpan = span;

		//we need to make sure to move the Year around to show the correct service year
		if(span == TIME_PERIOD_YEAR) {
			if(mCurrentMonth >= SERVICE_YEAR_START) {
				mCurrentYear++;
			}
		} else {
			if(mCurrentMonth >= SERVICE_YEAR_START) {
				mCurrentYear--;
			}
		}

		//invalidateOptionsMenu();
		fillData();
	}

	protected int getTimeSpan() {
		return mTimeSpan;
	}

	protected void toggleTimeSpan() {
		if (getTimeSpan() == TIME_PERIOD_MONTH) {
			setTimeSpan(TIME_PERIOD_YEAR);
		} else if (getTimeSpan() == TIME_PERIOD_YEAR) {
			setTimeSpan(TIME_PERIOD_MONTH);
		}
	}

	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
		getSupportMenuInflater().inflate(R.menu.stats, menu);
		mShareProvider = (ShareActionProvider) menu.findItem(R.id.menu_send).getActionProvider();
		setShareIntent();
		return super.onCreateOptionsMenu(menu);
    }

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		switch(item.getItemId()) {

		case android.R.id.home:
			Intent i = new Intent(this, ServiceDroidActivity.class);
			i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(i);
			return true;

		case R.id.menu_time_period:
			toggleTimeSpan();
			break;

		case R.id.menu_backup:
			backupData();
			break;
		}

		return super.onOptionsItemSelected(item);
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		Dialog dialog;
	    switch(id) {
	    case DIALOG_ROUND_ID:
	    	dialog = makeRoundTimeDialog();
	        break;
	    default:
	        dialog = null;
	    }
	    return dialog;
	}

	protected Dialog makeRoundTimeDialog() {

		AlertDialog.Builder builder = new AlertDialog.Builder(this);

		builder.setTitle(getHours());
		builder.setMessage(getString(R.string.round_time_prompt))
	       .setCancelable(true)
	       .setPositiveButton(getString(R.string.round_time_prompt_round), new DialogInterface.OnClickListener() {
	           public void onClick(DialogInterface dialog, int id) {
	        	   roundUpTime();
	           }
	       })
	       .setNegativeButton(getString(R.string.round_time_prompt_carry), new DialogInterface.OnClickListener() {
	           public void onClick(DialogInterface dialog, int id) {
		           carryOverTime();
	           }
	       });
		return builder.create();
	}

	protected void roundUpTime() {
		//add another time entry of 60 - mins, on last day of month
		int minutes = TimeUtil.getMins(getHoursSum());
		Calendar cal = Calendar.getInstance();
		cal.set(mCurrentYear, mCurrentMonth, 1);
		cal.add(Calendar.DATE, -1);

		Date lastDayOfMonth = cal.getTime();

		ContentValues values = new ContentValues();
		values.put(TimeEntries.LENGTH, TimeUtil.toTimeInt(0, 60 - minutes));
		values.put(TimeEntries.DATE, TimeUtil.getSQLTextFromDate(lastDayOfMonth));

		getContentResolver().insert(TimeEntries.CONTENT_URI, values);
		fillData();
	}

	protected void carryOverTime() {
		//place time entry of `mins` in next month
		int minutes = TimeUtil.getMins(getHoursSum());
		Calendar cal = Calendar.getInstance();
		cal.set(mCurrentYear, mCurrentMonth - 1, 1, 0, 0, 0);
		cal.add(Calendar.MONTH, 1);

		Date nextMonth = cal.getTime();

		// Save the all extra minutes into the next month
		ContentValues values = new ContentValues();
		values.put(TimeEntries.LENGTH, TimeUtil.toTimeInt(0, minutes));
		values.put(TimeEntries.DATE, TimeUtil.getSQLTextFromDate(nextMonth));
		values.put(TimeEntries.NOTE, getString(R.string.carry_over));

		getContentResolver().insert(TimeEntries.CONTENT_URI, values);

		//somehow remove those mins from this month
		// Collect all time entries, and peel off minutes until we get to 0 extra mins, and save the Entries back
		int minutesLeft = minutes;
		Cursor cursor = getContentResolver().query(TimeEntries.CONTENT_URI, TimeProjection, getTimePeriodWhere(ReturnVisits.DATE), getTimePeriodArgs(mCurrentYear, mCurrentMonth), TimeEntries.LENGTH +" desc");
		if(cursor.getCount() > 0) {
			cursor.moveToFirst();
			int curTime = 0;
			while(!cursor.isAfterLast() && minutesLeft > 0) {
				curTime = cursor.getInt(2) / TimeUtil.MIN;
				if(curTime >= minutesLeft) {
					curTime -= minutesLeft;
					minutesLeft = 0;
				} else {
					minutesLeft -= curTime;
					curTime = 0;
				}

				//update the time entry if curTime > 0, else remove the entry
				Uri curUri = ContentUris.withAppendedId(TimeEntries.CONTENT_URI, cursor.getInt(0));
				if(curTime > 0) {
					ContentValues upValues = new ContentValues();
					upValues.put(TimeEntries.LENGTH, TimeUtil.toTimeInt(0, curTime));
					getContentResolver().update(curUri, upValues, null, null);
				} else {
					getContentResolver().delete(curUri, null, null);
				}

				cursor.moveToNext();
			}
		}
		cursor.close();
		cursor = null;

		fillData();
	}

	protected void promptExtraTime() {
        int seconds = getHoursSum();
        int minutes = TimeUtil.getMins(seconds);

        if (minutes >= 45) {
		    showDialog(DIALOG_ROUND_ID);
        } else {
            carryOverTime();
            Toast.makeText(this, R.string.auto_carried_over, Toast.LENGTH_LONG).show();;
        }
	}

	private void setShareIntent() {
		if (mShareProvider != null) {
			Intent i = new Intent(Intent.ACTION_SEND);
			i.setType("text/plain");
			i.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.service_time_for, mCurrentMonth + "/" + mCurrentYear));
			i.putExtra(Intent.EXTRA_TEXT, getStatsTextForTimePeriod());
			mShareProvider.setShareIntent(i);
		}
	}

	protected void backupData() {
		Intent i = new Intent(BackupService.ACTION_BACKUP_IMMEDIATELY, null, this, BackupService.class);
		startService(i);
	}

	protected boolean hasExtraTime() {
		int seconds = getHoursSum();
		int hours = TimeUtil.getHours(seconds);
		int minutes = TimeUtil.getMins(seconds);

		//make sure Hours greater than 1. don't want to bother someone if they're submitting under an hour
		//since the Society points out that infirm publishers can still report as small as 15 minutes.
		//asking them to round or carry over every time would be discouraging...
		if(hours > 0 && minutes > 0) {
			return true;
		}

		return false;
	}

	protected String getStatsTextForTimePeriod() {
		StringBuilder sb = new StringBuilder();

		sb.append(getString(R.string.service_time_for, getTimePeriodText() + "\n\n"));
		sb.append(getString(R.string.hours) + ": " + getHours() + "\n");
		sb.append(getString(R.string.videos) + ": " + getVideos() + "\n");
		sb.append(getString(R.string.placements) + ": " + getPlacements() + "\n");
		sb.append(getString(R.string.rvs) + ": " + getRVs() + "\n");
		sb.append(getString(R.string.bible_studies) + ": " + getBibleStudies() + "\n");

		return sb.toString();
	}

	protected void toggleHintView() {
		//show the email hint 2 days before then end of the month
		// and 5 days from the start

		int day = TimeUtil.getCurrentDay();
		Calendar c = Calendar.getInstance();
		c.add(Calendar.MONTH, 1);
		c.set(Calendar.DATE, 1);
		c.add(Calendar.DATE, -1);

		int lastDayOfMonth = c.get(Calendar.DATE);
		if (day <= 5 || day > lastDayOfMonth - 2) {
			View hintView = findViewById(R.id.hint);
			hintView.setVisibility(View.VISIBLE);
		}

	}

	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		super.dispatchTouchEvent(ev);
		mGestureDetector.onTouchEvent(ev);

		//older versions of Android won't let the GestureDetector
		//fire its onFling unless this event is always consumed
		return true;
	}

	class MyGestureDetector extends SimpleOnGestureListener {
	    @Override
	    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
	        try {
	            if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
	                return false;
	            // right to left swipe
	            if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
	            	//left
	            	moveTimePeriodForward();
	            	fillData();
	            }  else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
	                //right
	            	moveTimePeriodBackward();
	            	fillData();
	            } else {
	            	return false;
	            }
	        } catch (Exception e) {
	            // nothing
	        }
	        return false;
	    }

	}

}


text:
> Package and compress (archive) files into zip file

- package and compress multiple directories & files

`zip -r {{compressed.zip}} {{/path/to/dir1 /path/to/dir2 /path/to/file}}`


text:
package playingcards;

import java.util.ArrayList;

/**
 * Hand : an arbitrary collection of cards.
 * @author mafudge
 */
public class Hand {
    private ArrayList<Card> cards;  // the big pile of cards

    /**
     * Constructor - new hand
     */
    public Hand() {
        cards = new ArrayList<Card>();
    }

    /**
     * Removes a card from the hand at index
     * @param index the position of the card to remove
     * @return the card removed
     */
    public Card remove(int index) {
        // TODO: Implement this method
        return this.cards.remove(index);
    }

    /**
     * Add a card to your hand
     * @param c the card to add
     */
    public void add(Card c) {
        // TODO: Implement this method
        this.cards.add(c);
    }

        /**
     * Get a count of cards in the hand
     * @return the number of cards in the hand
     */
    public int cardCount() {
        return cards.size();
    }

    /**
     * Converts the hand of cards to a string for display.
     * @return the cards represented as a string
     */
    @Override
    public String toString() {
        String result = "";
        for (Card c : cards) {
           result += c.toString() + " ";
        }
        return result;
    }

    public int rankCount (int rank ) {
        // TODO: Implement this method
        int count=0;
        for (int i=0;i<this.cards.size();i++) {
            count += this.cards.get(i).rank()==rank ? 1:0;
        }
        return count;

    }

}


text:
[![Build status](https://travis-ci.org/rdkit/rdkit.svg)](https://travis-ci.org/rdkit/rdkit)
[![Documentation Status](https://readthedocs.org/projects/rdkit/badge/?version=latest)](http://rdkit.readthedocs.org/en/latest/)

[RDKit](https://github.com/rdkit/rdkit) is a collection of cheminformatics and machine-learning software written in C++ and Python.

  * [BSD license](https://github.com/rdkit/rdkit/blob/master/license.txt) - a business friendly license for open source
  * Core data structures and algorithms in C++
  * [Python (2.x and 3.x) wrapper](http://www.rdkit.org/docs/GettingStartedInPython.html) generated using Boost.Python
  * Java and C# wrappers generated with SWIG
  * 2D and 3D molecular operations
  * [Descriptor](http://www.rdkit.org/docs/GettingStartedInPython.html#list-of-available-descriptors) and [Fingerprint](http://www.rdkit.org/docs/GettingStartedInPython.html#list-of-available-fingerprints) generation for machine learning
  * Molecular database [cartridge](http://www.rdkit.org/docs/Cartridge.html) for PostgreSQL supporting substructure and similarity searches as well as many descriptor calculators
  * Cheminformatics nodes for [KNIME](http://tech.knime.org/community/rdkit)
  * [Contrib](https://github.com/rdkit/rdkit/tree/master/Contrib) folder with useful community-contributed software harnessing the power of the RDKit

## Web presence

  * [RDKit web page](https://github.com/rdkit/rdkit)
  * [Blog](https://rdkit.blogspot.com)
  * [Documentation](http://www.rdkit.org/docs/index.html) also
    available at [ReadTheDocs](http://rdkit.readthedocs.org/en/latest/)

#### Code

  * [GitHub code](https://github.com/rdkit) and [bug tracker](https://github.com/rdkit/rdkit/issues)

#### Community

  * [Mailing list](https://sourceforge.net/p/rdkit/mailman/)
  * [Google +](https://plus.google.com/u/0/116996224395614252219)
  * [LinkedIn](https://www.linkedin.com/groups/RDKit-8192558/about)

#### Materials from user group meetings

  * [2012 UGM](http://www.rdkit.org/UGM/2012/)
  * [2013 UGM](https://github.com/rdkit/UGM_2013)
  * [2014 UGM](https://github.com/rdkit/UGM_2014)

## Documentation
Available on the [RDKit page](http://www.rdkit.org/docs/index.html)
and in the [Docs](https://github.com/rdkit/rdkit/tree/master/Docs) folder on GitHub

## Installation

Installation instructions are available in [Docs/Book/Install.md](https://github.com/rdkit/rdkit/blob/master/Docs/Book/Install.md).

#### Binary distributions, anaconda, homebrew

  * Windows binaries are available with each [release](https://github.com/rdkit/rdkit/releases).
  * [RPMs](https://copr.fedoraproject.org/coprs/giallu/rdkit/) for RedHat Enterprise Linux, Centos, and Fedora. Contributed by Gianluca Sforna.
  * [homebrew](https://github.com/rdkit/homebrew-rdkit) formula for building on the Mac. Contributed by Eddie Cao.
  * [recipes](https://github.com/rdkit/conda-rdkit) for building using the excellent conda package manager. Contributed by Riccardo Vianello.

## Projects using RDKit

  * [ChEMBL Beaker](https://github.com/mnowotka/chembl_beaker) - standalone web server wrapper for RDKit and OSRA
  * [myChEMBL](https://github.com/chembl/mychembl) ([blog post](http://chembl.blogspot.de/2013/10/chembl-virtual-machine-aka-mychembl.html), [paper](http://bioinformatics.oxfordjournals.org/content/early/2013/11/20/bioinformatics.btt666)) - A virtual machine implementation of open data and cheminformatics tools
  * [sdf_viewer.py](https://github.com/apahl/sdf_viewer) - an interactive SDF viewer
  * [sdf2ppt](https://github.com/dkuhn/sdf2ppt) - Reads an SDFile and displays molecules as image grid in powerpoint/openoffice presentation.
  * [MolGears](https://github.com/admed/molgears) - A cheminformatics tool for bioactive molecules
  * [PYPL](http://www.biochemfusion.com/downloads/#OracleUtilities) - Simple cartridge that lets you call Python scripts from Oracle PL/SQL.
  * [shape-it-rdkit](https://github.com/jandom/shape-it-rdkit) - Gaussian molecular overlap code shape-it (from silicos it) ported to RDKit backend
  * [WONKA](http://wonka.sgc.ox.ac.uk/WONKA/) - Tool for analysis and interrogation of protein-ligand crystal structures
  * [OOMMPPAA](http://oommppaa.sgc.ox.ac.uk/OOMMPPAA/) - Tool for directed synthesis and data analysis based on protein-ligand crystal structures

## License

Code released under the [BSD license](https://github.com/rdkit/rdkit/blob/master/license.txt).


text:
#ifndef HTTP_REQ_H
#define HTTP_REQ_H 1

#include <stdbool.h>
#include <sys/time.h>
#include <ubiqx/ubi_dLinkList.h>
#include "Ipv4Tcp.h"
#include "Rules.h"

#define ZERO_EOL 0
#define ONE_EOL 1
#define TWO_EOL 2

/**
* @ingroup HttpConn
* @defgroup HttpReq Http Request
* @{
*/

enum http_method { http_method_options, /* RFC 2616   sect 9.2 */
		http_method_get,         /* RFC 2616   sect 9.3 */
		http_method_head,
		http_method_post,
		http_method_put,
		http_method_delete,
		http_method_trace,
		http_method_connect,
		http_method_propfind,   /* RFC 4918 WebDav */
		http_method_proppatch,
		http_method_mkcol,
		http_method_copy,
		http_method_move,
		http_method_lock,
		http_method_unlock,
		http_method_report,   /* RFC 3253 version control. SVN over http uses this */
		http_method_version_control,
		http_method_checkout,
		http_method_checkin,
		http_method_uncheckout,
		http_method_mkworkspace,
};

enum msg_state { msg_state_new, ///newly allocated
		msg_state_partial,  /// more HTTP headers
		msg_state_read_content, /// read POST/PUT data or response data
		msg_state_complete,
		msg_state_last };

struct HttpConn;

#define HTTP_REQ_MAX_CATEGORY_IDS 5

/* Struct to model rfc 2616 messages to/from server and client*/
struct http_msg {
	enum msg_state state;
	uint64_t content_length;  /// from 'Content-Length:'
	uint64_t content_received;  /// content data received of the content length.
	char *buf_line; /// temporary buffer when one line of a header is in multiple packets
	unsigned int buf_line_len; /// length of buffer
	bool chunked; ///   Transfer-Encoding: chunked
	unsigned int chunk_len; /// length of current chunk
	unsigned int chunk_recieved; /// length of current chunk received
};

struct HttpReq {
	ubi_dlNode node;	/** ubiqx "internal" data */
	struct HttpConn *con; /// connection this request is a part of
	unsigned id;  // an auto increment ID for us to track.
	int resp_status_code; /// 200, 304, 404  etc. RFC2616  Section 6.1.1
	enum http_method method; /// GET, POST, etc
	char *host;
	char *path;
	char *url; /** combine host and path, without http://  so will be host/path */
	struct timeval start_time; /** time the request started */
	struct http_msg client_req_msg;  /// data coming from client HTTP Request
	struct http_msg server_resp_msg;  /// data coming from server HTTP response

	/// NOTE  consider putting virus, phishing, malware, category, etc
	/// into some kind of attributes list,
	/// and each filter object can set the attributes it wants.
//	enum Action verdict; /// reject, virus, Phishing, malware, etc
	struct Rule *rule_matched; /// rule that was matched
	int category_id[HTTP_REQ_MAX_CATEGORY_IDS];
	char *reject_reason; /* virus name, or other reason to reject */
	char *category_name;
	int file_scan_fd;
	char *file_scan_tmpfile;
	struct ContentFilter *cf; /* content filter object */
	/// Private data that a filter object may request, will allow different filter objects to share data.
	/// Or it allows a filter object to save its state between request states
	struct PrivData *priv_data;
};

typedef ubi_dlList HttpReq_list_t;
struct ContentFilter;

struct HttpReq * HttpReq_new(struct HttpConn*);

void HttpReq_del(struct HttpReq **req);
// void * HttpReq_newPrivateDataPtr(struct HttpReq *req, int key, void (*free_fn)(void *));
// void * HttpReq_getPrivateDataPtr(struct HttpReq *req, int key);
// int HttpReq_freePrivateDataPtr(struct HttpReq *req, int key);

int HttpReq_processHeaderLine(struct HttpReq *req, bool client_req,
		unsigned char **start_line, unsigned int *buf_len);

int HttpReq_consumeResponseContent(struct HttpReq *req, const unsigned char *data,
	unsigned int len);

void HttpReq_setRuleMatched(struct HttpReq *req, struct Rule *r);
void HttpReq_setRejectReason(struct HttpReq *req, const char *reason);
void HttpReq_setCatName(struct HttpReq *req, const char *name);

/** @}  */

#endif


text:
package springfox.documentation.schema;

import com.fasterxml.classmate.ResolvedType;
import com.google.common.base.Function;
import springfox.documentation.service.AllowableValues;

public class ModelProperty {
  private final String name;
  private final ResolvedType type;
  private final String qualifiedType;
  private final int position;
  private final Boolean required;
  private final boolean isHidden;
  private final Boolean readOnly;
  private final String description;
  private final AllowableValues allowableValues;
  private ModelRef modelRef;

  public ModelProperty(String name, ResolvedType type, String qualifiedType,
                       int position, Boolean required, Boolean isHidden, Boolean readOnly,
                       String description, AllowableValues allowableValues) {
    this.name = name;
    this.type = type;
    this.qualifiedType = qualifiedType;
    this.position = position;
    this.required = required;
    this.isHidden = isHidden;
    this.readOnly = readOnly;
    this.description = description;
    this.allowableValues = allowableValues;
  }

  public String getName() {
    return name;
  }

  public ResolvedType getType() {
    return type;
  }

  public String getQualifiedType() {
    return qualifiedType;
  }

  public int getPosition() {
    return position;
  }

  public Boolean isRequired() {
    return required;
  }

  public Boolean isReadOnly() {
    return readOnly;
  }

  public String getDescription() {
    return description;
  }

  public AllowableValues getAllowableValues() {
    return allowableValues;
  }

  public ModelRef getModelRef() {
    return modelRef;
  }

  public boolean isHidden() {
    return isHidden;
  }

  public ModelProperty updateModelRef(Function<? super ResolvedType, ModelRef> modelRefFactory) {
    modelRef = modelRefFactory.apply(type);
    return this;
  }
}


text:
from django.conf import settings as django_settings
from django.forms.widgets import Textarea
from django.utils.safestring import mark_safe
from django.utils.translation import get_language

from . import settings

try:
    from django.urls import reverse
except ImportError:
    # For old versions of django
    from django.core.urlresolvers import reverse

def get_trumbowyg_language():
    """
    Get and convert language from django to trumbowyg format

    Example:
        Django uses: pt-br and trumbowyg use pt_br
    """
    language = getattr(settings, 'TRUMBOWYG_LANGUAGE', django_settings.LANGUAGE_CODE)
    return language.replace('-', '_')

class TrumbowygWidget(Textarea):
    class Media:
        css = {
            'all': (
                'trumbowyg/ui/trumbowyg.css',
                'trumbowyg/admin.css',
            )
        }
        js = [
            '//ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js',
            'trumbowyg/trumbowyg.min.js',
            'trumbowyg/plugins/upload/trumbowyg.upload.js',
            'trumbowyg/langs/{0}.min.js'.format(get_trumbowyg_language())
        ]

    def render(self, name, value, attrs=None, renderer=None):
        output = super(TrumbowygWidget, self).render(name, value, attrs)
        script = u'''
            <script>
                $("#id_{name}").trumbowyg({{
                    lang: "{lang}",
                    semantic: {semantic},
                    resetCss: true,
                    autogrow: true,
                    removeformatPasted: true,
                    btnsDef: {{
                        image: {{
                            dropdown: ["upload", "insertImage", "base64", "noembed"],
                            ico: "insertImage"
                        }}
                    }},
                    btns: [
                        ["formatting"],
                        "btnGrp-semantic",
                        ["link"],
                        ["image"],
                        "btnGrp-justify",
                        "btnGrp-lists",
                        ["horizontalRule"],
                        ["removeformat"],
                        ["viewHTML"],
                        ["fullscreen"]
                    ],
                    plugins: {{
                        upload: {{
                            serverPath: "{path}",
                            fileFieldName: "image",
                            statusPropertyName: "message",
                            urlPropertyName: "file"
                        }}
                    }}
                }});
            </script>
        '''.format(
            name=name,
            lang=get_trumbowyg_language(),
            semantic=settings.SEMANTIC,
            path=reverse('trumbowyg_upload_image'),
        )
        output += mark_safe(script)
        return output


text:
from app import db

class ServerData(db.Model):
    __tablename__ = 'server_data'
    id = db.Column(db.Integer, primary_key=True)
    server_id = db.Column(db.String(50))
    qps = db.Column(db.Float)
    aps = db.Column(db.Float)
    timestamp = db.Column(db.Float)

    def __init__(self, server_id=None, qps=None, aps=None, timestamp=None):
        self.server_id = server_id
        self.qps = qps
        self.aps = aps
        self.timestamp = timestamp

    def __repr__(self):
        return "<ServerData, id: %r, server_id: %r, qps: %r, aps: %r, timestamp: %r>" % (
            self.id, self.server_id, self.qps, self.aps, self.timestamp)

class TopDomains(db.Model):
    __tablename__ = 'top_domains'
    id = db.Column(db.Integer, primary_key=True)
    domain = db.Column(db.String(100))
    count = db.Column(db.Integer)
    timestamp = db.Column(db.Float)

    def __init__(self, domain=None, count=None, timestamp=None):
        self.domain = domain
        self.count = count
        self.timestamp = timestamp

    def __repr__(self):
        return "<TopDomains, id: %r, domain: %r, count: %r, timestamp: %r>" % (
            self.id, self.domain, self.count, self.timestamp)

class DataByRecordType(db.Model):
    __tablename__ = 'data_by_record_type'
    id = db.Column(db.Integer, primary_key=True)
    record_type = db.Column(db.String(10))
    client_ip = db.Column(db.String(40))
    queries_count = db.Column(db.Integer)
    total_queries_percentage = db.Column(db.Float)
    type_queries_percentage = db.Column(db.Float)
    server_id = db.Column(db.String(50))
    timestamp = db.Column(db.Float)

    def __init__(self, record_type=None, client_ip=None, queries_count=None, total_queries_percentage=None,
                 type_queries_percentage=None, server_id=None, timestamp=None):
        self.record_type = record_type
        self.client_ip = client_ip
        self.queries_count = queries_count
        self.total_queries_percentage = total_queries_percentage
        self.type_queries_percentage = type_queries_percentage
        self.server_id = server_id
        self.timestamp = timestamp

    def __repr__(self):
        return "<DataByRecordType, id: %r, record_type: %r, client_ip: %r, queries_count: %r, " \
               "total_queries_percentage: %r, type_queries,percentage: %r, server_id: %r, timestamp: %r>" % (
                   self.id, self.record_type, self.client_ip, self.queries_count, self.total_queries_percentage,
                   self.type_queries_percentage, self.server_id, self.timestamp)


text:
cask 'syncplay' do
  version '1.6.1'
  sha256 '88dd53b6396d0b32aa82f4c8570bb42489541dff1a5f95e056a988966e4d9c89'

  # github.com/Syncplay/syncplay was verified as official when first introduced to the cask
  url "https://github.com/Syncplay/syncplay/releases/download/v#{version}/Syncplay_#{version}.dmg"
  appcast 'https://github.com/Syncplay/syncplay/releases.atom'
  name 'Syncplay'
  homepage 'https://syncplay.pl/'

  app 'Syncplay.app'

  zap trash: [
               '~/.syncplay',
               '~/Library/Saved Application State/pl.syncplay.Syncplay.savedState',
               '~/Library/Preferences/com.syncplay.MoreSettings.plist',
               '~/Library/Preferences/com.syncplay.Interface.plist',
               '~/Library/Preferences/com.syncplay.MainWindow.plist',
               '~/Library/Preferences/pl.syncplay.Syncplay.plist',
               '~/Library/Preferences/com.syncplay.PlayerList.plist',
             ]
end


text:
#include <cstddef>

#include "glimp/tracing/tracing.h"

#if defined(ENABLE_GLIMP_TRACING)

namespace glimp {

namespace {
TraceEventImpl* g_trace_event_implementation = NULL;
}  // namespace

ScopedTraceEvent::ScopedTraceEvent(const char* name) : name_(name) {
  if (g_trace_event_implementation) {
    g_trace_event_implementation->BeginTrace(name_);
  }
}

ScopedTraceEvent::~ScopedTraceEvent() {
  if (g_trace_event_implementation) {
    g_trace_event_implementation->EndTrace(name_);
  }
}

void SetTraceEventImplementation(TraceEventImpl* impl) {
  g_trace_event_implementation = impl;
}

}  // namespace glimp

#endif  // #if defined(ENABLE_GLIMP_TRACING)


text:
<?php

namespace Pingxx\Account\Api\Controller;

use Flarum\Core\Command\EditUser;
use Flarum\Http\Controller\ControllerInterface;
use Psr\Http\Message\ServerRequestInterface;
use Illuminate\Contracts\Bus\Dispatcher;

class PingxxActiveUserHandler implements ControllerInterface
{
    protected $bus;

    /**
     * @param Dispatcher $bus
     */
    public function __construct(Dispatcher $bus)
    {
        $this->bus = $bus;
    }
    /**
     * {@inheritdoc}
     */
    public function handle(ServerRequestInterface $request)
    {
        $id = array_get($request->getQueryParams(), 'id');
        echo $id;
        $actor = $request->getAttribute('actor');
        $data = array_get($request->getParsedBody(), 'data', []);

        return $this->bus->dispatch(
            new EditUser($id, $actor, $data)
        );

    }
}


text:
package com.google.android.exoplayer;

import java.nio.ByteBuffer;

/**
 * Holds sample data and corresponding metadata.
 */
public final class SampleHolder {

  /**
   * Disallows buffer replacement.
   */
  public static final int BUFFER_REPLACEMENT_MODE_DISABLED = 0;

  /**
   * Allows buffer replacement using {@link ByteBuffer#allocate(int)}.
   */
  public static final int BUFFER_REPLACEMENT_MODE_NORMAL = 1;

  /**
   * Allows buffer replacement using {@link ByteBuffer#allocateDirect(int)}.
   */
  public static final int BUFFER_REPLACEMENT_MODE_DIRECT = 2;

  public final CryptoInfo cryptoInfo;

  /**
   * A buffer holding the sample data.
   */
  public ByteBuffer data;

  /**
   * The size of the sample in bytes.
   */
  public int size;

  /**
   * Flags that accompany the sample. A combination of {@link C#SAMPLE_FLAG_SYNC},
   * {@link C#SAMPLE_FLAG_ENCRYPTED} and {@link C#SAMPLE_FLAG_DECODE_ONLY}.
   */
  public int flags;

  /**
   * The time at which the sample should be presented.
   */
  public long timeUs;

  private final int bufferReplacementMode;

  /**
   * @param bufferReplacementMode Determines the behavior of {@link #ensureSpaceForWrite(int)}. One
   *     of {@link #BUFFER_REPLACEMENT_MODE_DISABLED}, {@link #BUFFER_REPLACEMENT_MODE_NORMAL} and
   *     {@link #BUFFER_REPLACEMENT_MODE_DIRECT}.
   */
  public SampleHolder(int bufferReplacementMode) {
    this.cryptoInfo = new CryptoInfo();
    this.bufferReplacementMode = bufferReplacementMode;
  }

  /**
   * Ensures that {@link #data} is large enough to accommodate a write of a given length at its
   * current position.
   * <p>
   * If the capacity of {@link #data} is sufficient this method does nothing. If the capacity is
   * insufficient then an attempt is made to replace {@link #data} with a new {@link ByteBuffer}
   * whose capacity is sufficient. Data up to the current position is copied to the new buffer.
   *
   * @param length The length of the write that must be accommodated, in bytes.
   * @throws IllegalStateException If there is insufficient capacity to accommodate the write and
   *     the buffer replacement mode of the holder is {@link #BUFFER_REPLACEMENT_MODE_DISABLED}.
   */
  public void ensureSpaceForWrite(int length) throws IllegalStateException {
    if (data == null) {
      data = createReplacementBuffer(length);
      return;
    }
    // Check whether the current buffer is sufficient.
    int capacity = data.capacity();
    int position = data.position();
    int requiredCapacity = position + length;
    if (capacity >= requiredCapacity) {
      return;
    }
    // Instantiate a new buffer if possible.
    ByteBuffer newData = createReplacementBuffer(requiredCapacity);
    // Copy data up to the current position from the old buffer to the new one.
    if (position > 0) {
      data.position(0);
      data.limit(position);
      newData.put(data);
    }
    // Set the new buffer.
    data = newData;
  }

  /**
   * Returns whether {@link #flags} has {@link C#SAMPLE_FLAG_ENCRYPTED} set.
   */
  public boolean isEncrypted() {
    return (flags & C.SAMPLE_FLAG_ENCRYPTED) != 0;
  }

  /**
   * Returns whether {@link #flags} has {@link C#SAMPLE_FLAG_DECODE_ONLY} set.
   */
  public boolean isDecodeOnly() {
    return (flags & C.SAMPLE_FLAG_DECODE_ONLY) != 0;
  }

  /**
   * Returns whether {@link #flags} has {@link C#SAMPLE_FLAG_SYNC} set.
   */
  public boolean isSyncFrame() {
    return (flags & C.SAMPLE_FLAG_SYNC) != 0;
  }

  /**
   * Clears {@link #data}. Does nothing if {@link #data} is null.
   */
  public void clearData() {
    if (data != null) {
      data.clear();
    }
  }

  private ByteBuffer createReplacementBuffer(int requiredCapacity) {
    if (bufferReplacementMode == BUFFER_REPLACEMENT_MODE_NORMAL) {
      return ByteBuffer.allocate(requiredCapacity);
    } else if (bufferReplacementMode == BUFFER_REPLACEMENT_MODE_DIRECT) {
      return ByteBuffer.allocateDirect(requiredCapacity);
    } else {
      int currentCapacity = data == null ? 0 : data.capacity();
      throw new IllegalStateException("Buffer too small (" + currentCapacity + " < "
          + requiredCapacity + ")");
    }
  }

}


text:
module Opta
end


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

package be.stacktrace.activiti.rest.variable;

import java.lang.reflect.Field;
import java.util.List;

import org.activiti.rest.api.RestResponseFactory;
import org.activiti.rest.api.engine.variable.RestVariableConverter;

/**
 * @author Frederik Heremans
 */
public class CustomRestResponseFactory extends RestResponseFactory {

  @Override
  protected void initializeVariableConverters() {
    super.initializeVariableConverters();

    // Add custom converter for MyPojo variables
    getVariableConverters().add(new MyPojoVariableConverter());
  }

  @SuppressWarnings("unchecked")
  private List<RestVariableConverter> getVariableConverters() {
    try {
      // Workaround until the "variableConverters" field is set protected on RestResponseFactory or
      // the converters are exposed.
      Field f = RestResponseFactory.class.getDeclaredField("variableConverters");
      f.setAccessible(true);
      List<RestVariableConverter> variableConverters = ( List<RestVariableConverter> ) f.get(this);
      return variableConverters;

    } catch (SecurityException e) {
      throw new RuntimeException(e);
    } catch (NoSuchFieldException e) {
      throw new RuntimeException(e);
    } catch (IllegalArgumentException e) {
      throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
      throw new RuntimeException(e);
    }
  }
}


text:
package utils

import (
	"bytes"
	"errors"
	"github.com/heketi/heketi/tests"
	"strings"
	"testing"
)

func TestLogLevel(t *testing.T) {
	var testbuffer bytes.Buffer

	defer tests.Patch(&stdout, &testbuffer).Restore()

	l := NewLogger("[testing]", LEVEL_INFO)
	tests.Assert(t, LEVEL_INFO == l.level)
	tests.Assert(t, LEVEL_INFO == l.Level())

	l.SetLevel(LEVEL_CRITICAL)
	tests.Assert(t, LEVEL_CRITICAL == l.level)
	tests.Assert(t, LEVEL_CRITICAL == l.Level())

}

func TestLogInfo(t *testing.T) {
	var testbuffer bytes.Buffer

	defer tests.Patch(&stdout, &testbuffer).Restore()

	l := NewLogger("[testing]", LEVEL_INFO)

	l.Info("Hello %v", "World")
	tests.Assert(t, strings.Contains(testbuffer.String(), "[testing] INFO "), testbuffer.String())
	tests.Assert(t, strings.Contains(testbuffer.String(), "Hello World"), testbuffer.String())
	testbuffer.Reset()

	l.SetLevel(LEVEL_WARNING)
	l.Info("TEXT")
	tests.Assert(t, testbuffer.Len() == 0)
}

func TestLogDebug(t *testing.T) {
	var testbuffer bytes.Buffer

	defer tests.Patch(&stdout, &testbuffer).Restore()

	l := NewLogger("[testing]", LEVEL_DEBUG)

	l.Debug("Hello %v", "World")
	tests.Assert(t, strings.Contains(testbuffer.String(), "[testing] DEBUG "), testbuffer.String())
	tests.Assert(t, strings.Contains(testbuffer.String(), "Hello World"), testbuffer.String())
	tests.Assert(t, strings.Contains(testbuffer.String(), "log_test.go"), testbuffer.String())
	testbuffer.Reset()

	l.SetLevel(LEVEL_INFO)
	l.Debug("TEXT")
	tests.Assert(t, testbuffer.Len() == 0)
}

func TestLogWarning(t *testing.T) {
	var testbuffer bytes.Buffer

	defer tests.Patch(&stdout, &testbuffer).Restore()

	l := NewLogger("[testing]", LEVEL_DEBUG)

	l.Warning("Hello %v", "World")
	tests.Assert(t, strings.Contains(testbuffer.String(), "[testing] WARNING "), testbuffer.String())
	tests.Assert(t, strings.Contains(testbuffer.String(), "Hello World"), testbuffer.String())
	testbuffer.Reset()

	l.SetLevel(LEVEL_ERROR)
	l.Warning("TEXT")
	tests.Assert(t, testbuffer.Len() == 0)
}

func TestLogError(t *testing.T) {
	var testbuffer bytes.Buffer

	defer tests.Patch(&stderr, &testbuffer).Restore()

	l := NewLogger("[testing]", LEVEL_DEBUG)

	l.LogError("Hello %v", "World")
	tests.Assert(t, strings.Contains(testbuffer.String(), "[testing] ERROR "), testbuffer.String())
	tests.Assert(t, strings.Contains(testbuffer.String(), "Hello World"), testbuffer.String())
	tests.Assert(t, strings.Contains(testbuffer.String(), "log_test.go"), testbuffer.String())
	testbuffer.Reset()
	testbuffer.Reset()

	err := errors.New("BAD")
	l.Err(err)
	tests.Assert(t, strings.Contains(testbuffer.String(), "[testing] ERROR "), testbuffer.String())
	tests.Assert(t, strings.Contains(testbuffer.String(), "BAD"), testbuffer.String())
	tests.Assert(t, strings.Contains(testbuffer.String(), "log_test.go"), testbuffer.String())
	testbuffer.Reset()

	l.SetLevel(LEVEL_CRITICAL)
	l.LogError("TEXT")
	tests.Assert(t, testbuffer.Len() == 0)

}

func TestLogCritical(t *testing.T) {
	var testbuffer bytes.Buffer

	defer tests.Patch(&stderr, &testbuffer).Restore()

	l := NewLogger("[testing]", LEVEL_DEBUG)

	l.LogError("Hello %v", "World")
	tests.Assert(t, strings.Contains(testbuffer.String(), "[testing] ERROR "), testbuffer.String())
	tests.Assert(t, strings.Contains(testbuffer.String(), "Hello World"), testbuffer.String())
	tests.Assert(t, strings.Contains(testbuffer.String(), "log_test.go"), testbuffer.String())
	testbuffer.Reset()

	l.SetLevel(LEVEL_NOLOG)
	l.LogError("TEXT")
	tests.Assert(t, testbuffer.Len() == 0)

}


text:
var grunt = require('grunt');
var path = require('path');
var os = require('os');

Array.prototype.inArray = function (obj, wildcard) {

    if (typeof obj == 'object') {
        var a = obj.length;
        while (a --) {
            if (this.inArray(obj[ a ])) return true;
        }
        return false;
    }

    var i = this.length;
    while (i --) {
        if (this[ i ] === obj) {
            return true;
        }
        if (typeof wildcard !== 'undefined' && wildcard === true) {
            if (this[ i ].indexOf(obj) !== - 1) {
                return true;
            }
        }
    }
    return false;
};

/** @return: String */
String.prototype.ReplaceSpecialPaths = function (config) {
    return this
        .replace('$THEME_DIR', path.join(config.dist, config.theme))
        .replace('$DIST_DIR', config.dist)
        .replace('$ROOT_DIR', '')
        .replace(/^(\/)/,"");
};

module.exports = function (grunt) {

    var config = {
        vendor_css: [],
        concat: [],
        rename: [],
        browserify: [],
        copy: [],
        swig: {}
    };

    var theme = grunt.option('theme');
    var dist = grunt.option('dist') || 'dist/themes';
    var minify = grunt.option('min') !== false;

    global.debug = grunt.option('debug') === true;

    config.cpu = Math.max((os.cpus().length || 1), 2);

    grunt.config.init({
        pkg: grunt.file.readJSON('package.json'),
        banner: '/*!\n' +
        ' * <%= pkg.description %> <%= pkg.version %>\n' +
        ' * Author: <%= pkg.author%>\n' +
        ' * Licence: <%= pkg.license.url %>\n' +
        ' * Copyright <%= grunt.template.today("yyyy") %>\n' +
        ' */\n'
    });

    grunt.file.expand({}, path.join(process.cwd(), '.grunt', '*.json')).forEach(function (value) {
        var file = value.split('/').pop(),
            configKey = file.split('.').shift();
        config[configKey] = grunt.file.readJSON(path.join(process.cwd(), '.grunt', file));
    });

    try {
        config.skins = grunt.file.readJSON(path.join(process.cwd(), 'src', 'skins.json'));
    } catch (err) {
    }

    if (! theme && ! grunt.cli.tasks.inArray('parallel', true) && ! grunt.cli.tasks.inArray(Object.keys(config.parallel))) {
        grunt.fail.fatal('You must specify a theme by using the --theme [theme_name] option.');
    }

    if (typeof config.dist !== 'undefined' && typeof config.dist[ theme ] !== 'undefined') {
        dist = config.dist[ theme ];
    }

    grunt.registerTask('setCPU', function (limit) {
        var async = this.async();
        grunt.task.run(['setParallelCPU:' + limit, 'setConcurrentCPU:' + limit]);
        async();
    });

    config.theme = theme;
    config.dist = dist;
    config.minify = minify;

    return config;

}(grunt);


text:
package org.zstack.header.vm;

import org.springframework.http.HttpMethod;
import org.zstack.header.identity.Action;
import org.zstack.header.message.APIEvent;
import org.zstack.header.message.APIMessage;
import org.zstack.header.message.APIParam;
import org.zstack.header.network.l3.L3NetworkVO;
import org.zstack.header.notification.ApiNotification;
import org.zstack.header.rest.RestRequest;
import org.zstack.header.rest.RestResponse;

/**
 * Created by frank on 2/26/2016.
 */
@Action(category = VmInstanceConstant.ACTION_CATEGORY)
@RestRequest(
        path = "/vm-instances/{vmInstanceUuid}/actions",
        isAction = true,
        method = HttpMethod.PUT,
        responseClass = APISetVmStaticIpEvent.class
)
public class APISetVmStaticIpMsg extends APIMessage implements VmInstanceMessage {
    @APIParam(resourceType = VmInstanceVO.class, checkAccount = true, operationTarget = true)
    private String vmInstanceUuid;
    @APIParam(resourceType = L3NetworkVO.class)
    private String l3NetworkUuid;
    @APIParam
    private String ip;

    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    @Override
    public String getVmInstanceUuid() {
        return vmInstanceUuid;
    }

    public void setVmInstanceUuid(String vmInstanceUuid) {
        this.vmInstanceUuid = vmInstanceUuid;
    }

    public String getL3NetworkUuid() {
        return l3NetworkUuid;
    }

    public void setL3NetworkUuid(String l3NetworkUuid) {
        this.l3NetworkUuid = l3NetworkUuid;
    }

    public static APISetVmStaticIpMsg __example__() {
        APISetVmStaticIpMsg msg = new APISetVmStaticIpMsg();
        msg.vmInstanceUuid = uuid();
        msg.l3NetworkUuid = uuid();
        msg.ip = "192.168.10.10";
        return msg;
    }

    public ApiNotification __notification__() {
        APIMessage that = this;

        return new ApiNotification() {
            @Override
            public void after(APIEvent evt) {
                ntfy("Static ip: %s was set", ip).resource(vmInstanceUuid, VmInstanceVO.class.getSimpleName())
                        .messageAndEvent(that, evt).done();

                ntfy("Set").resource(l3NetworkUuid, L3NetworkVO.class.getSimpleName())
                        .messageAndEvent(that, evt).done();
            }
        };
    }

}


text:
package io.sarl.lang.ui.extralanguage.properties;

import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Widget;

/** Control wrapper that may be automatically considered in the option dialog.
 *
 * @author $Author: sgalland$
 * @version $FullVersion$
 * @mavengroupid $GroupId$
 * @mavenartifactid $ArtifactId$
 * @since 0.6
 */
public interface IExtraControlController {

	/** Get a preference value.
	 *
	 * @param key the preference key.
	 * @return the value.
	 */
	String getValue(String key);

	/** Notify the controller that a widget content changed.
	 *
	 * @param widget the changed widget.
	 */
	void controlChanged(Widget widget);

	/** Notify the controller that a preference has changed.
	 *
	 * @param preferenceKey the key of the preference.
	 * @param preferenceValue the new value for the preference entry.
	 */
	void controlChanged(String preferenceKey, String preferenceValue);

	/** Notify the controller that a text widget has changed.
	 *
	 * @param textControl the changed widget.
	 */
	void textChanged(Text textControl);

	/** Register the given preference key.
	 *
	 * @param key the key to be registered.
	 */
	void registerKey(String key);

}