text:
/** @file
 * @brief IPv6 Fragment related functions
 */

/*
 * Copyright (c) 2018 Intel Corporation
 *
 * SPDX-License-Identifier: Apache-2.0
 */

#include <zephyr/logging/log.h>
LOG_MODULE_DECLARE(net_ipv6, CONFIG_NET_IPV6_LOG_LEVEL);

#include <errno.h>
#include <zephyr/net/net_core.h>
#include <zephyr/net/net_pkt.h>
#include <zephyr/net/net_stats.h>
#include <zephyr/net/net_context.h>
#include <zephyr/net/net_mgmt.h>
#include <zephyr/random/rand32.h>
#include "net_private.h"
#include "connection.h"
#include "icmpv6.h"
#include "udp_internal.h"
#include "tcp_internal.h"
#include "ipv6.h"
#include "nbr.h"
#include "6lo.h"
#include "route.h"
#include "net_stats.h"

/* Timeout for various buffer allocations in this file. */
#define NET_BUF_TIMEOUT K_MSEC(50)

#if defined(CONFIG_NET_IPV6_FRAGMENT_TIMEOUT)
#define IPV6_REASSEMBLY_TIMEOUT K_SECONDS(CONFIG_NET_IPV6_FRAGMENT_TIMEOUT)
#else
#define IPV6_REASSEMBLY_TIMEOUT K_SECONDS(5)
#endif /* CONFIG_NET_IPV6_FRAGMENT_TIMEOUT */

#define FRAG_BUF_WAIT K_MSEC(10) /* how long to max wait for a buffer */

static void reassembly_timeout(struct k_work *work);
static bool reassembly_init_done;

static struct net_ipv6_reassembly
reassembly[CONFIG_NET_IPV6_FRAGMENT_MAX_COUNT];

int net_ipv6_find_last_ext_hdr(struct net_pkt *pkt, uint16_t *next_hdr_off,
			       uint16_t *last_hdr_off)
{
	NET_PKT_DATA_ACCESS_CONTIGUOUS_DEFINE(ipv6_access, struct net_ipv6_hdr);
	struct net_ipv6_hdr *hdr;
	uint8_t next_nexthdr;
	uint8_t nexthdr;

	if (!pkt || !pkt->frags || !next_hdr_off || !last_hdr_off) {
		return -EINVAL;
	}

	net_pkt_cursor_init(pkt);

	hdr = (struct net_ipv6_hdr *)net_pkt_get_data(pkt, &ipv6_access);
	if (!hdr) {
		return -ENOBUFS;
	}

	net_pkt_acknowledge_data(pkt, &ipv6_access);

	nexthdr = hdr->nexthdr;

	/* Initial values */
	*next_hdr_off = offsetof(struct net_ipv6_hdr, nexthdr);
	*last_hdr_off = sizeof(struct net_ipv6_hdr);

	while (!net_ipv6_is_nexthdr_upper_layer(nexthdr)) {
		if (net_pkt_read_u8(pkt, &next_nexthdr)) {
			goto fail;
		}

		switch (nexthdr) {
		case NET_IPV6_NEXTHDR_HBHO:
		case NET_IPV6_NEXTHDR_DESTO:
			{
				uint8_t val = 0U;
				uint16_t length;

				if (net_pkt_read_u8(pkt, &val)) {
					goto fail;
				}

				length = val * 8U + 8 - 2;

				if (net_pkt_skip(pkt, length)) {
					goto fail;
				}
			}
			break;
		case NET_IPV6_NEXTHDR_FRAG:
			if (net_pkt_skip(pkt, 7)) {
				goto fail;
			}

			break;
		case NET_IPV6_NEXTHDR_NONE:
			goto out;
		default:
			/* TODO: Add more IPv6 extension headers to check */
			goto fail;
		}

		*next_hdr_off = *last_hdr_off;
		*last_hdr_off = net_pkt_get_current_offset(pkt);

		nexthdr = next_nexthdr;
	}
out:
	return 0;
fail:
	return -EINVAL;
}

static struct net_ipv6_reassembly *reassembly_get(uint32_t id,
						  struct in6_addr *src,
						  struct in6_addr *dst)
{
	int i, avail = -1;

	for (i = 0; i < CONFIG_NET_IPV6_FRAGMENT_MAX_COUNT; i++) {
		if (k_work_delayable_remaining_get(&reassembly[i].timer) &&
		    reassembly[i].id == id &&
		    net_ipv6_addr_cmp(src, &reassembly[i].src) &&
		    net_ipv6_addr_cmp(dst, &reassembly[i].dst)) {
			return &reassembly[i];
		}

		if (k_work_delayable_remaining_get(&reassembly[i].timer)) {
			continue;
		}

		if (avail < 0) {
			avail = i;
		}
	}

	if (avail < 0) {
		return NULL;
	}

	k_work_reschedule(&reassembly[avail].timer, IPV6_REASSEMBLY_TIMEOUT);

	net_ipaddr_copy(&reassembly[avail].src, src);
	net_ipaddr_copy(&reassembly[avail].dst, dst);

	reassembly[avail].id = id;

	return &reassembly[avail];
}

static bool reassembly_cancel(uint32_t id,
			      struct in6_addr *src,
			      struct in6_addr *dst)
{
	int i, j;

	NET_DBG("Cancel 0x%x", id);

	for (i = 0; i < CONFIG_NET_IPV6_FRAGMENT_MAX_COUNT; i++) {
		int32_t remaining;

		if (reassembly[i].id != id ||
		    !net_ipv6_addr_cmp(src, &reassembly[i].src) ||
		    !net_ipv6_addr_cmp(dst, &reassembly[i].dst)) {
			continue;
		}

		remaining = k_ticks_to_ms_ceil32(
			k_work_delayable_remaining_get(&reassembly[i].timer));
		k_work_cancel_delayable(&reassembly[i].timer);

		NET_DBG("IPv6 reassembly id 0x%x remaining %d ms",
			reassembly[i].id, remaining);

		reassembly[i].id = 0U;

		for (j = 0; j < CONFIG_NET_IPV6_FRAGMENT_MAX_PKT; j++) {
			if (!reassembly[i].pkt[j]) {
				continue;
			}

			NET_DBG("[%d] IPv6 reassembly pkt %p %zd bytes data",
				j, reassembly[i].pkt[j],
				net_pkt_get_len(reassembly[i].pkt[j]));

			net_pkt_unref(reassembly[i].pkt[j]);
			reassembly[i].pkt[j] = NULL;
		}

		return true;
	}

	return false;
}

static void reassembly_info(char *str, struct net_ipv6_reassembly *reass)
{
	NET_DBG("%s id 0x%x src %s dst %s remain %d ms", str, reass->id,
		net_sprint_ipv6_addr(&reass->src),
		net_sprint_ipv6_addr(&reass->dst),
		k_ticks_to_ms_ceil32(
			k_work_delayable_remaining_get(&reass->timer)));
}

static void reassembly_timeout(struct k_work *work)
{
	struct net_ipv6_reassembly *reass =
		CONTAINER_OF(work, struct net_ipv6_reassembly, timer);

	reassembly_info("Reassembly cancelled", reass);

	/* Send a ICMPv6 Time Exceeded only if we received the first fragment (RFC 2460 Sec. 5) */
	if (reass->pkt[0] && net_pkt_ipv6_fragment_offset(reass->pkt[0]) == 0) {
		net_icmpv6_send_error(reass->pkt[0], NET_ICMPV6_TIME_EXCEEDED, 1, 0);
	}

	reassembly_cancel(reass->id, &reass->src, &reass->dst);
}

static void reassemble_packet(struct net_ipv6_reassembly *reass)
{
	NET_PKT_DATA_ACCESS_CONTIGUOUS_DEFINE(ipv6_access, struct net_ipv6_hdr);
	NET_PKT_DATA_ACCESS_DEFINE(frag_access, struct net_ipv6_frag_hdr);
	union {
		struct net_ipv6_hdr *hdr;
		struct net_ipv6_frag_hdr *frag_hdr;
	} ipv6;

	struct net_pkt *pkt;
	struct net_buf *last;
	uint8_t next_hdr;
	int i, len;

	k_work_cancel_delayable(&reass->timer);

	NET_ASSERT(reass->pkt[0]);

	last = net_buf_frag_last(reass->pkt[0]->buffer);

	/* We start from 2nd packet which is then appended to
	 * the first one.
	 */
	for (i = 1; i < CONFIG_NET_IPV6_FRAGMENT_MAX_PKT; i++) {
		int removed_len;

		pkt = reass->pkt[i];
		if (!pkt) {
			break;
		}

		net_pkt_cursor_init(pkt);

		/* Get rid of IPv6 and fragment header which are at
		 * the beginning of the fragment.
		 */
		removed_len = net_pkt_ipv6_fragment_start(pkt) +
			      sizeof(struct net_ipv6_frag_hdr);

		NET_DBG("Removing %d bytes from start of pkt %p",
			removed_len, pkt->buffer);

		if (net_pkt_pull(pkt, removed_len)) {
			NET_ERR("Failed to pull headers");
			reassembly_cancel(reass->id, &reass->src, &reass->dst);
			return;
		}

		/* Attach the data to previous pkt */
		last->frags = pkt->buffer;
		last = net_buf_frag_last(pkt->buffer);

		pkt->buffer = NULL;
		reass->pkt[i] = NULL;

		net_pkt_unref(pkt);
	}

	pkt = reass->pkt[0];
	reass->pkt[0] = NULL;

	/* Next we need to strip away the fragment header from the first packet
	 * and set the various pointers and values in packet.
	 */
	net_pkt_cursor_init(pkt);

	if (net_pkt_skip(pkt, net_pkt_ipv6_fragment_start(pkt))) {
		NET_ERR("Failed to move to fragment header");
		goto error;
	}

	ipv6.frag_hdr = (struct net_ipv6_frag_hdr *)net_pkt_get_data(
							pkt, &frag_access);
	if (!ipv6.frag_hdr) {
		NET_ERR("Failed to get fragment header");
		goto error;
	}

	next_hdr = ipv6.frag_hdr->nexthdr;

	if (net_pkt_pull(pkt, sizeof(struct net_ipv6_frag_hdr))) {
		NET_ERR("Failed to remove fragment header");
		goto error;
	}

	/* This one updates the previous header's nexthdr value */
	if (net_pkt_skip(pkt, net_pkt_ipv6_hdr_prev(pkt)) ||
	    net_pkt_write_u8(pkt, next_hdr)) {
		goto error;
	}

	net_pkt_cursor_init(pkt);

	ipv6.hdr = (struct net_ipv6_hdr *)net_pkt_get_data(pkt, &ipv6_access);
	if (!ipv6.hdr) {
		goto error;
	}

	/* Fix the total length of the IPv6 packet. */
	len = net_pkt_ipv6_ext_len(pkt);
	if (len > 0) {
		NET_DBG("Old pkt %p IPv6 ext len is %d bytes", pkt, len);
		net_pkt_set_ipv6_ext_len(pkt,
				len - sizeof(struct net_ipv6_frag_hdr));
	}

	len = net_pkt_get_len(pkt) - sizeof(struct net_ipv6_hdr);

	ipv6.hdr->len = htons(len);

	net_pkt_set_data(pkt, &ipv6_access);

	NET_DBG("New pkt %p IPv6 len is %d bytes", pkt,
		len + NET_IPV6H_LEN);

	/* We need to use the queue when feeding the packet back into the
	 * IP stack as we might run out of stack if we call processing_data()
	 * directly. As the packet does not contain link layer header, we
	 * MUST NOT pass it to L2 so there will be a special check for that
	 * in process_data() when handling the packet.
	 */
	if (net_recv_data(net_pkt_iface(pkt), pkt) >= 0) {
		return;
	}
error:
	net_pkt_unref(pkt);
}

void net_ipv6_frag_foreach(net_ipv6_frag_cb_t cb, void *user_data)
{
	int i;

	for (i = 0; reassembly_init_done &&
		     i < CONFIG_NET_IPV6_FRAGMENT_MAX_COUNT; i++) {
		if (!k_work_delayable_remaining_get(&reassembly[i].timer)) {
			continue;
		}

		cb(&reassembly[i], user_data);
	}
}

/* Verify that we have all the fragments received and in correct order.
 * Return:
 * - a negative value if the fragments are erroneous and must be dropped
 * - zero if we are expecting more fragments
 * - a positive value if we can proceed with the reassembly
 */
static int fragments_are_ready(struct net_ipv6_reassembly *reass)
{
	unsigned int expected_offset = 0;
	bool more = true;
	int i;

	/* Fragments can arrive in any order, for example in reverse order:
	 *   1 -> Fragment3(M=0, offset=x2)
	 *   2 -> Fragment2(M=1, offset=x1)
	 *   3 -> Fragment1(M=1, offset=0)
	 * We have to test several requirements before proceeding with the reassembly:
	 * - We received the first fragment (Fragment Offset is 0)
	 * - All intermediate fragments are contiguous
	 * - The More bit of the last fragment is 0
	 */
	for (i = 0; i < CONFIG_NET_IPV6_FRAGMENT_MAX_PKT; i++) {
		struct net_pkt *pkt = reass->pkt[i];
		unsigned int offset;
		int payload_len;

		if (!pkt) {
			break;
		}

		offset = net_pkt_ipv6_fragment_offset(pkt);

		if (offset < expected_offset) {
			/* Overlapping or duplicated
			 * According to RFC8200 we can drop it
			 */
			return -EBADMSG;
		} else if (offset != expected_offset) {
			/* Not contiguous, let's wait for fragments */
			return 0;
		}

		payload_len = net_pkt_get_len(pkt) - net_pkt_ipv6_fragment_start(pkt);
		payload_len -= sizeof(struct net_ipv6_frag_hdr);
		if (payload_len < 0) {
			return -EBADMSG;
		}

		expected_offset += payload_len;
		more = net_pkt_ipv6_fragment_more(pkt);
	}

	if (more) {
		return 0;
	}

	return 1;
}

static int shift_packets(struct net_ipv6_reassembly *reass, int pos)
{
	int i;

	for (i = pos + 1; i < CONFIG_NET_IPV6_FRAGMENT_MAX_PKT; i++) {
		if (!reass->pkt[i]) {
			NET_DBG("Moving [%d] %p (offset 0x%x) to [%d]",
				pos, reass->pkt[pos],
				net_pkt_ipv6_fragment_offset(reass->pkt[pos]),
				pos + 1);

			/* pkt[i] is free, so shift everything between
			 * [pos] and [i - 1] by one element
			 */
			memmove(&reass->pkt[pos + 1], &reass->pkt[pos],
				sizeof(void *) * (i - pos));

			/* pkt[pos] is now free */
			reass->pkt[pos] = NULL;

			return 0;
		}
	}

	/* We do not have free space left in the array */
	return -ENOMEM;
}

enum net_verdict net_ipv6_handle_fragment_hdr(struct net_pkt *pkt,
					      struct net_ipv6_hdr *hdr,
					      uint8_t nexthdr)
{
	struct net_ipv6_reassembly *reass = NULL;
	uint16_t flag;
	bool found;
	uint8_t more;
	uint32_t id;
	int ret;
	int i;

	if (!reassembly_init_done) {
		/* Static initializing does not work here because of the array
		 * so we must do it at runtime.
		 */
		for (i = 0; i < CONFIG_NET_IPV6_FRAGMENT_MAX_COUNT; i++) {
			k_work_init_delayable(&reassembly[i].timer,
					      reassembly_timeout);
		}

		reassembly_init_done = true;
	}

	/* Each fragment has a fragment header, however since we already
	 * read the nexthdr part of it, we are not going to use
	 * net_pkt_get_data() and access the header directly: the cursor
	 * being 1 byte too far, let's just read the next relevant pieces.
	 */
	if (net_pkt_skip(pkt, 1) || /* reserved */
	    net_pkt_read_be16(pkt, &flag) ||
	    net_pkt_read_be32(pkt, &id)) {
		goto drop;
	}

	reass = reassembly_get(id, (struct in6_addr *)hdr->src,
			       (struct in6_addr *)hdr->dst);
	if (!reass) {
		NET_DBG("Cannot get reassembly slot, dropping pkt %p", pkt);
		goto drop;
	}

	more = flag & 0x01;
	net_pkt_set_ipv6_fragment_flags(pkt, flag);

	if (more && net_pkt_get_len(pkt) % 8) {
		/* Fragment length is not multiple of 8, discard
		 * the packet and send parameter problem error with the
		 * offset of the "Payload Length" field in the IPv6 header.
		 */
		net_icmpv6_send_error(pkt, NET_ICMPV6_PARAM_PROBLEM,
				      NET_ICMPV6_PARAM_PROB_HEADER, NET_IPV6H_LENGTH_OFFSET);
		goto drop;
	}

	/* The fragments might come in wrong order so place them
	 * in reassembly chain in correct order.
	 */
	for (i = 0, found = false; i < CONFIG_NET_IPV6_FRAGMENT_MAX_PKT; i++) {
		if (reass->pkt[i]) {
			if (net_pkt_ipv6_fragment_offset(reass->pkt[i]) <
			    net_pkt_ipv6_fragment_offset(pkt)) {
				continue;
			}

			/* Make room for this fragment. If there is no room,
			 * then it will discard the whole reassembly.
			 */
			if (shift_packets(reass, i)) {
				break;
			}
		}

		NET_DBG("Storing pkt %p to slot %d offset %d",
			pkt, i, net_pkt_ipv6_fragment_offset(pkt));
		reass->pkt[i] = pkt;
		found = true;

		break;
	}

	if (!found) {
		/* We could not add this fragment into our saved fragment
		 * list. We must discard the whole packet at this point.
		 */
		NET_DBG("No slots available for 0x%x", reass->id);
		net_pkt_unref(pkt);
		goto drop;
	}

	ret = fragments_are_ready(reass);
	if (ret < 0) {
		NET_DBG("Reassembled IPv6 verify failed, dropping id %u",
			reass->id);

		/* Let the caller release the already inserted pkt */
		if (i < CONFIG_NET_IPV6_FRAGMENT_MAX_PKT) {
			reass->pkt[i] = NULL;
		}

		net_pkt_unref(pkt);
		goto drop;
	} else if (ret == 0) {
		reassembly_info("Reassembly nth pkt", reass);

		NET_DBG("More fragments to be received");
		goto accept;
	}

	reassembly_info("Reassembly last pkt", reass);

	/* The last fragment received, reassemble the packet */
	reassemble_packet(reass);

accept:
	return NET_OK;

drop:
	if (reass) {
		if (reassembly_cancel(reass->id, &reass->src, &reass->dst)) {
			return NET_OK;
		}
	}

	return NET_DROP;
}

#define BUF_ALLOC_TIMEOUT K_MSEC(100)

static int send_ipv6_fragment(struct net_pkt *pkt,
			      uint16_t fit_len,
			      uint16_t frag_offset,
			      uint16_t next_hdr_off,
			      uint8_t next_hdr,
			      bool final)
{
	NET_PKT_DATA_ACCESS_DEFINE(frag_access, struct net_ipv6_frag_hdr);
	uint8_t frag_pkt_next_hdr = NET_IPV6_NEXTHDR_HBHO;
	int ret = -ENOBUFS;
	struct net_ipv6_frag_hdr *frag_hdr;
	struct net_pkt *frag_pkt;

	frag_pkt = net_pkt_alloc_with_buffer(net_pkt_iface(pkt), fit_len +
					     net_pkt_ipv6_ext_len(pkt) +
					     NET_IPV6_FRAGH_LEN,
					     AF_INET6, 0, BUF_ALLOC_TIMEOUT);
	if (!frag_pkt) {
		return -ENOMEM;
	}

	net_pkt_cursor_init(pkt);

	/* We copy original headers back to the fragment packet
	 * Note that we insert the right next header to point to fragment header
	 */
	if (net_pkt_copy(frag_pkt, pkt, next_hdr_off) ||
	    net_pkt_write_u8(frag_pkt, NET_IPV6_NEXTHDR_FRAG) ||
	    net_pkt_skip(pkt, 1) ||
	    net_pkt_copy(frag_pkt, pkt, net_pkt_ip_hdr_len(pkt) +
			 net_pkt_ipv6_ext_len(pkt) - next_hdr_off - 1)) {
		goto fail;
	}

	if (!net_pkt_ipv6_ext_len(pkt)) {
		frag_pkt_next_hdr = NET_IPV6_NEXTHDR_FRAG;
	}

	/* And we append the fragmentation header */
	frag_hdr = (struct net_ipv6_frag_hdr *)net_pkt_get_data(frag_pkt,
								&frag_access);
	if (!frag_hdr) {
		goto fail;
	}

	frag_hdr->nexthdr = next_hdr;
	frag_hdr->reserved = 0U;
	frag_hdr->id = net_pkt_ipv6_fragment_id(pkt);
	frag_hdr->offset = htons(((frag_offset / 8U) << 3) | !final);

	if (net_pkt_set_data(frag_pkt, &frag_access)) {
		goto fail;
	}

	net_pkt_set_ipv6_ext_len(frag_pkt,
				 net_pkt_ipv6_ext_len(pkt) +
				 sizeof(struct net_ipv6_frag_hdr));

	/* Finally we copy the payload part of this fragment from
	 * the original packet
	 */
	if (net_pkt_skip(pkt, frag_offset) ||
	    net_pkt_copy(frag_pkt, pkt, fit_len)) {
		goto fail;
	}

	net_pkt_cursor_init(frag_pkt);

	if (net_ipv6_finalize(frag_pkt, frag_pkt_next_hdr) < 0) {
		goto fail;
	}

	/* If everything has been ok so far, we can send the packet. */
	ret = net_send_data(frag_pkt);
	if (ret < 0) {
		goto fail;
	}

	/* Let this packet to be sent and hopefully it will release
	 * the memory that can be utilized for next sent IPv6 fragment.
	 */
	k_yield();

	return 0;

fail:
	NET_DBG("Cannot send fragment (%d)", ret);
	net_pkt_unref(frag_pkt);

	return ret;
}

int net_ipv6_send_fragmented_pkt(struct net_if *iface, struct net_pkt *pkt,
				 uint16_t pkt_len)
{
	uint16_t next_hdr_off;
	uint16_t last_hdr_off;
	uint16_t frag_offset;
	size_t length;
	uint8_t next_hdr;
	uint8_t last_hdr;
	int fit_len;
	int ret;

	net_pkt_set_ipv6_fragment_id(pkt, sys_rand32_get());

	ret = net_ipv6_find_last_ext_hdr(pkt, &next_hdr_off, &last_hdr_off);
	if (ret < 0) {
		return ret;
	}

	net_pkt_cursor_init(pkt);

	if (net_pkt_skip(pkt, next_hdr_off) ||
	    net_pkt_read_u8(pkt, &next_hdr) ||
	    net_pkt_skip(pkt, last_hdr_off) ||
	    net_pkt_read_u8(pkt, &last_hdr)) {
		return -ENOBUFS;
	}

	/* The Maximum payload can fit into each packet after IPv6 header,
	 * Extension headers and Fragmentation header.
	 */
	fit_len = NET_IPV6_MTU - NET_IPV6_FRAGH_LEN -
		(net_pkt_ip_hdr_len(pkt) + net_pkt_ipv6_ext_len(pkt));
	if (fit_len <= 0) {
		/* Must be invalid extension headers length */
		NET_DBG("No room for IPv6 payload MTU %d hdrs_len %d",
			NET_IPV6_MTU, NET_IPV6_FRAGH_LEN +
			net_pkt_ip_hdr_len(pkt) + net_pkt_ipv6_ext_len(pkt));
		return -EINVAL;
	}

	frag_offset = 0U;

	length = net_pkt_get_len(pkt) -
		(net_pkt_ip_hdr_len(pkt) + net_pkt_ipv6_ext_len(pkt));
	while (length) {
		bool final = false;

		if (fit_len >= length) {
			final = true;
			fit_len = length;
		}

		ret = send_ipv6_fragment(pkt, fit_len, frag_offset,
					 next_hdr_off, next_hdr, final);
		if (ret < 0) {
			return ret;
		}

		length -= fit_len;
		frag_offset += fit_len;
	}

	return 0;
}


text:
@interface CSCompositeComponent (State)

- (void)updateState:(id _Nullable (^_Nonnull)(id _Nullable))updateBlock asynchronously:(BOOL)asynchronously NS_REFINED_FOR_SWIFT;

@end

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace DeliciousBrains\WPMDB\Free;

use DeliciousBrains\WPMDB\Common\Plugin\Menu;
use DeliciousBrains\WPMDB\Container;
use DeliciousBrains\WPMDB\WPMigrateDB;

class WPMigrateDBFree extends WPMigrateDB {

	public function __construct( $pro = false ) {
		parent::__construct( false );
	}

	public function register() {
		parent::register();
		$container = Container::getInstance();

		//Menu
		$this->menu = $container->addClass( 'menu', new Menu(
				$container->get( 'properties' ),
				$container->get( 'plugin_manager_base' ),
				$container->get( 'assets' )
			)
		);

		$container->get( 'migration_manager' )->register();
		$container->get( 'plugin_manager' )->register();
		$container->get( 'menu' )->register();
		$container->get( 'free_template' )->register();

		$filesystem = $container->get( 'filesystem' );
		$filesystem->register();
	}
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Beih. Sydowia 2: 277 (1961)

#### Original name
Meliola bicornis var. calopogonii F. Stevens

### Remarks
null


text:
var expect = require("chai").expect;
var assert = require("chai").assert;

var Promise = require("bluebird");

var $config = require("../config/app.js");

var log4js = require("log4js");
log4js.configure($config.log);
var $logger = log4js.getLogger("app");

var userService = new (require("../service/sample-user-service"))();

var authenticationService = new (require("../lib/service/authentication-service.js"))(function () {
    return userService;
}, $config, $logger);

var httpClient = require($config.https.enable ? "https" : "http");

describe("cloudpify handler", function () {
    it("should start server successfully", function (done) {
        //start
        var cloudpifyHandler = new (require("../cloudpify.js"))();
        cloudpifyHandler.start("full")
                .then(function () {
                    return testServer();
                })
                .then(function (isStart) {
                    expect(isStart).to.equal(true);

                    //stop server
                    return cloudpifyHandler.stop();
                })
                .then(function () {
                    return testServer();
                })
                .then(function (isRunning) {
                    expect(isRunning).to.equal(false);
                    return cloudpifyHandler.start();//full
                })
                .then(function () {
                    return testServer();
                })
                .then(function (isStart) {
                    expect(isStart).to.equal(true);
                    //stop server
                    return cloudpifyHandler.stop();
                })
                .then(function () {
                    done();
                })
                .catch(done);
    });

    it("should start server in app and service mode", function (done) {
        //start service
        //start app
        //test
        //stop service
        //test
        //stop app
        var cloudpifyServiceHandler = new (require("../lib/handler.js"))();
        var cloudpifyAppHandler = new (require("../lib/handler.js"))();
        cloudpifyServiceHandler.start("service")
                .then(function () {
                    return cloudpifyAppHandler.start("app");
                })
                .then(function () {
                    return testServer();
                })
                .then(function (isStart) {
                    expect(isStart).to.equal(true);
                    return cloudpifyServiceHandler.stop();
                })
                .then(function () {
                    return testServer();
                })
                .then(function (isRunning) {
                    expect(isRunning).to.equal(true);
                    return cloudpifyAppHandler.stop();
                })
                .then(function () {
                    return testServer();
                })
                .then(function (isRunning) {
                    expect(isRunning).to.equal(false);
                    done();
                })
                .catch(done);
    });
});

function testServer() {

    return new Promise(function (resolve, reject) {
        authenticationService.generateToken(1)
                .then(function (token) {
                    var options = {
                        hostname: "localhost",
                        port: 5102,
                        path: "/post-stanza?token=" + token,
                        method: "POST",
                        headers: {
                            userId: 1,
                            'Content-Type': 'application/json'
                        }
                    };

                    if ($config.https.enable) {
                        options.rejectUnauthorized = false;
                        options.requestCert = true;
                    }

                    var request = httpClient.request(options, function (response) {
                        response.setEncoding("utf8");
                        var responseInString = "";
                        response.on("data", function (chunk) {
                            responseInString += chunk;
                        });
                        response.on("end", function () {
                            try {
                                console.log("Receive message from server: " + responseInString);
                                resolve(true);
                            } catch (e) {
                                reject(e);
                            }
                        });
                    });
                    request.on("error", function (error) {
                        resolve(false);
                    });
                    request.write(JSON.stringify({
                        id: 10,
                        action: "cloudchat:sample-controller:hello",
                        type: "iq",
                        body: {
                            deviceId: "android",
                            username: "Tho Q Luong"
                        }
                    }));
                    request.end();
                });
    });

}


text:
RSpec.describe Biz::Interval do
  let(:start_time) { week_minute(wday: 1, hour: 9) }
  let(:end_time)   { week_minute(wday: 1, hour: 17) }
  let(:time_zone)  { TZInfo::Timezone.get('America/Los_Angeles') }

  subject(:interval) {
    described_class.new(
      Biz::WeekTime.start(start_time),
      Biz::WeekTime.end(end_time),
      time_zone
    )
  }

  describe '.to_hours' do
    let(:intervals) {
      [
        described_class.new(
          Biz::WeekTime.start(week_minute(wday: 1, hour: 9)),
          Biz::WeekTime.end(week_minute(wday: 1, hour: 17)),
          time_zone
        ),
        described_class.new(
          Biz::WeekTime.start(week_minute(wday: 2, hour: 9)),
          Biz::WeekTime.end(week_minute(wday: 2, hour: 12)),
          time_zone
        ),
        described_class.new(
          Biz::WeekTime.start(week_minute(wday: 2, hour: 13)),
          Biz::WeekTime.end(week_minute(wday: 2, hour: 17)),
          time_zone
        ),
        described_class.new(
          Biz::WeekTime.start(week_minute(wday: 4, hour: 10)),
          Biz::WeekTime.end(week_minute(wday: 4, hour: 16)),
          time_zone
        ),
        described_class.new(
          Biz::WeekTime.start(week_minute(wday: 5, hour: 9)),
          Biz::WeekTime.end(week_minute(wday: 5, hour: 17)),
          time_zone
        )
      ]
    }

    it 'returns a configuration hash for the provided intervals' do
      expect(described_class.to_hours(intervals)).to eq(
        mon: {'09:00' => '17:00'},
        tue: {'09:00' => '12:00', '13:00' => '17:00'},
        thu: {'10:00' => '16:00'},
        fri: {'09:00' => '17:00'}
      )
    end
  end

  describe '#start_time' do
    it 'returns the start time' do
      expect(interval.start_time).to eq Biz::WeekTime.start(start_time)
    end
  end

  describe '#end_time' do
    it 'returns the end time' do
      expect(interval.end_time).to eq Biz::WeekTime.end(end_time)
    end
  end

  describe '#time_zone' do
    it 'returns the time zone' do
      expect(interval.time_zone).to eq time_zone
    end
  end

  describe '#wday_symbol' do
    let(:start_time) { week_minute(wday: 1, hour: 12) }
    let(:end_time)   { week_minute(wday: 2, hour: 12) }

    it 'returns the symbol for the day containing the start time' do
      expect(interval.wday_symbol).to eq :mon
    end
  end

  describe '#endpoints' do
    it 'returns the interval endpoints' do
      expect(interval.endpoints).to eq [
        Biz::WeekTime.start(start_time),
        Biz::WeekTime.end(end_time)
      ]
    end
  end

  describe '#empty?' do
    context 'when the start time is before the end time' do
      let(:start_time) { end_time.pred }

      it 'returns false' do
        expect(interval.empty?).to eq false
      end
    end

    context 'when the start time is equal to the end time' do
      let(:start_time) { end_time }

      it 'returns true' do
        expect(interval.empty?).to eq true
      end
    end

    context 'when the start time is after the end time' do
      let(:start_time) { end_time.succ }

      it 'returns true' do
        expect(interval.empty?).to eq true
      end
    end
  end

  describe '#contains?' do
    context 'when the time is before the interval' do
      let(:time) { in_zone('America/New_York') { Time.utc(2006, 1, 2, 11) } }

      it 'returns false' do
        expect(interval.contains?(time)).to eq false
      end
    end

    context 'when the time is at the beginning of the interval' do
      let(:time) { in_zone('America/New_York') { Time.utc(2006, 1, 2, 12) } }

      it 'returns true' do
        expect(interval.contains?(time)).to eq true
      end
    end

    context 'when the time is contained by the interval' do
      let(:time) { in_zone('America/New_York') { Time.utc(2006, 1, 2, 15) } }

      it 'returns true' do
        expect(interval.contains?(time)).to eq true
      end
    end

    context 'when the time is at the end of the interval' do
      let(:time) { in_zone('America/New_York') { Time.utc(2006, 1, 2, 20) } }

      it 'returns false' do
        expect(interval.contains?(time)).to eq false
      end
    end

    context 'when the time is after the interval' do
      let(:time) { in_zone('America/New_York') { Time.utc(2006, 1, 2, 21) } }

      it 'returns false' do
        expect(interval.contains?(time)).to eq false
      end
    end
  end

  describe '#to_time_segment' do
    let(:week) { Biz::Week.new(4) }

    it 'returns the appropriate time segment for the given week' do
      expect(interval.to_time_segment(week)).to eq(
        Biz::TimeSegment.new(
          in_zone('America/Los_Angeles') { Time.utc(2006, 1, 30, 9) },
          in_zone('America/Los_Angeles') { Time.utc(2006, 1, 30, 17) }
        )
      )
    end

    context 'when the interval covers an entire day' do
      let(:start_time) { Biz::DayOfWeek.all.first.start_minute }
      let(:end_time)   { Biz::DayOfWeek.all.first.end_minute }

      it 'returns the appropriate time segment' do
        expect(interval.to_time_segment(week)).to eq(
          Biz::TimeSegment.new(
            in_zone('America/Los_Angeles') { Time.utc(2006, 1, 29) },
            in_zone('America/Los_Angeles') { Time.utc(2006, 1, 30) }
          )
        )
      end
    end

    context 'when the interval covers an entire week' do
      let(:start_time) { week_minute(wday: 0, hour: 0) }
      let(:end_time)   { Biz::Time.week_minutes }

      it 'returns the appropriate time segment' do
        expect(interval.to_time_segment(week)).to eq(
          Biz::TimeSegment.new(
            in_zone('America/Los_Angeles') { Time.utc(2006, 1, 29) },
            in_zone('America/Los_Angeles') { Time.utc(2006, 2, 5) }
          )
        )
      end
    end
  end

  describe '#&' do
    let(:other) {
      described_class.new(
        Biz::WeekTime.start(other_start_time),
        Biz::WeekTime.end(other_end_time),
        time_zone
      )
    }

    context 'when the other interval occurs before the interval' do
      let(:other_start_time) { week_minute(wday: 0, hour: 9) }
      let(:other_end_time)   { week_minute(wday: 0, hour: 17) }

      it 'returns a zero-duration interval' do
        expect(interval & other).to eq(
          described_class.new(
            Biz::WeekTime.start(start_time),
            Biz::WeekTime.end(start_time),
            time_zone
          )
        )
      end
    end

    context 'when the other interval starts before the interval' do
      let(:other_start_time) { week_minute(wday: 1, hour: 8) }

      context 'and ends before the interval' do
        let(:other_end_time) { week_minute(wday: 1, hour: 12) }

        it 'returns the correct interval' do
          expect(interval & other).to eq(
            described_class.new(
              Biz::WeekTime.start(start_time),
              Biz::WeekTime.end(other_end_time),
              time_zone
            )
          )
        end
      end

      context 'and ends after the interval' do
        let(:other_end_time) { week_minute(wday: 1, hour: 18) }

        it 'returns the correct interval' do
          expect(interval & other).to eq(
            described_class.new(
              Biz::WeekTime.start(start_time),
              Biz::WeekTime.end(end_time),
              time_zone
            )
          )
        end
      end
    end

    context 'when the other interval starts after the interval' do
      let(:other_start_time) { week_minute(wday: 1, hour: 12) }

      context 'and ends before the interval' do
        let(:other_end_time) { week_minute(wday: 1, hour: 15) }

        it 'returns the correct interval' do
          expect(interval & other).to eq(
            described_class.new(
              Biz::WeekTime.start(other_start_time),
              Biz::WeekTime.end(other_end_time),
              time_zone
            )
          )
        end
      end

      context 'and ends after the interval' do
        let(:other_end_time) { week_minute(wday: 1, hour: 18) }

        it 'returns the correct interval' do
          expect(interval & other).to eq(
            described_class.new(
              Biz::WeekTime.start(other_start_time),
              Biz::WeekTime.end(end_time),
              time_zone
            )
          )
        end
      end
    end

    context 'when the other interval occurs after the interval' do
      let(:other_start_time) { week_minute(wday: 2, hour: 9) }
      let(:other_end_time)   { week_minute(wday: 2, hour: 17) }

      it 'returns a zero-duration interval' do
        expect(interval & other).to eq(
          described_class.new(
            Biz::WeekTime.start(other_start_time),
            Biz::WeekTime.end(other_start_time),
            time_zone
          )
        )
      end
    end
  end

  context 'when performing comparison' do
    context 'and the compared object has an earlier start time' do
      let(:other) {
        described_class.new(
          Biz::WeekTime.start(start_time - 1),
          Biz::WeekTime.end(end_time),
          time_zone
        )
      }

      it 'compares as expected' do
        expect(interval > other).to eq true
      end
    end

    context 'and the compared object has a later start time' do
      let(:other) {
        described_class.new(
          Biz::WeekTime.start(start_time + 1),
          Biz::WeekTime.end(end_time),
          time_zone
        )
      }

      it 'compares as expected' do
        expect(interval > other).to eq false
      end
    end

    context 'and the compared object has an earlier end time' do
      let(:other) {
        described_class.new(
          Biz::WeekTime.start(start_time),
          Biz::WeekTime.end(end_time - 1),
          time_zone
        )
      }

      it 'compares as expected' do
        expect(interval > other).to eq true
      end
    end

    context 'and the compared object has a different time zone' do
      let(:other) {
        described_class.new(
          Biz::WeekTime.start(start_time),
          Biz::WeekTime.end(end_time + 1),
          TZInfo::Timezone.get('America/Los_Angeles')
        )
      }

      it 'compares as expected' do
        expect(interval == other).to eq false
      end
    end

    context 'and the compared object has the same endpoints and time zone' do
      let(:other) {
        described_class.new(
          Biz::WeekTime.start(start_time),
          Biz::WeekTime.end(end_time),
          time_zone
        )
      }

      it 'compares as expected' do
        expect(interval == other).to eq true
      end
    end

    context 'and the compared object is not an interval' do
      let(:other) { 1 }

      it 'is not comparable' do
        expect { interval < other }.to raise_error ArgumentError
      end
    end
  end
end


text:
var Reflux           = require('reflux');
var _                = require('lodash');
var DashboardActions = require('./../actions/DashboardActions');
var ConfigStore      = require('./ConfigStore');

var _dashboards      = [];
var _currentIndex    = 0;
var _config          = null;
var _timer           = null;

var DashboardStore = Reflux.createStore({
    init() {
        this.listenTo(DashboardActions.setDashboards,     this.setDashboards);
        this.listenTo(DashboardActions.previousDashboard, this.previousDashboard);
        this.listenTo(DashboardActions.nextDashboard,     this.nextDashboard);
        this.listenTo(ConfigStore,                        this.setConfig);
    },

    setConfig(config) {
        _config = _.pick(config, 'rotationDuration');
        this.start();
    },

    start() {
        if (_config.rotationDuration && _dashboards.length > 0 && _timer === null) {
            _timer = setInterval(() => {
                this.nextDashboard();
            }, _config.rotationDuration);
        }
    },

    previousDashboard() {
        _currentIndex--;
        this.trigger(_currentIndex);
    },

    nextDashboard() {
        if (_currentIndex < _dashboards.length - 1) {
            _currentIndex++;
        } else {
            _currentIndex = 0;
        }

        this.trigger(_currentIndex);
    },

    setDashboards(dashboards) {
        _.forEach(dashboards, (dashboard, index) => {
            dashboard.index = index;
        });

        _dashboards   = dashboards;
        _currentIndex = 0;

        this.start();

        this.trigger(_currentIndex);
    },

    currentIndex() {
        return _currentIndex;
    }
});

module.exports = DashboardStore;


text:
using MO.Common.Geom;
using MO.Common.IO;
using MO.DX.Core.Common;
using MO.DX.Core.Model;
using MO.Content3d.Resource.Model.Mesh;

namespace MO.Content3d.Util.Light
{
   public class FDrLightGeometry : FDxGeometry
   {
      //============================================================
      public FDrLightGeometry() {
      }

      //============================================================
      public void LoadResource(FDrGeometry geometry) {
         // 创建数据
         int faceCount = geometry.FaceList.Count;
         FByteStream vertexs = new FByteStream(4 * 10 * 3 * faceCount);
         FByteStream faces = new FByteStream(3 * faceCount);
         for(int f = 0; f < faceCount; f++) {
            FDrFace face = geometry.FaceList[f];
            for (int n = 0; n < 3; n++) {
               // 输出顶点数据
               FDrVertex vertex = geometry.VertexList[face.VertexIndex[n]];
               FDrCoord coord = geometry.CoordList[face.CoordIndex[n]];
               float coordX = coord.Coord.X;
               float coordY = coord.Coord.Y + 1.0f;
               if (geometry.Channels.Count > 1) {
                  FDrChannelFace channelFace = geometry.Channels[2].Indexs[face.Index];
                  SFloatPoint3 channelPoint = channelFace.Points[n];
                  coordX = channelPoint.X;
                  coordY = channelPoint.Y;
               }
               FDrColor color = geometry.ColorList[face.ColorIndex[n]];
               vertexs.WriteFloat(vertex.Position.X);
               vertexs.WriteFloat(vertex.Position.Y);
               vertexs.WriteFloat(vertex.Position.Z);
               vertexs.WriteFloat(1.0f);
               vertexs.WriteFloat(coordX);
               vertexs.WriteFloat(coordY);
               vertexs.WriteFloat(color.Color.R);
               vertexs.WriteFloat(color.Color.G);
               vertexs.WriteFloat(color.Color.B);
               vertexs.WriteFloat(1.0f);
               // 输出索引数据
               faces.WriteInt32(3 * f + n);
            }
         }
         // 创建顶点流
         _vertexBuffer = new FDxVertexBuffer();
         _vertexBuffer.Device = _device;
         _vertexBuffer.UploadNormal(10, vertexs.Memory, 0, vertexs.Length);
         // 创建索引流
         _faceBuffer = new FDxFaceBuffer();
         _faceBuffer.Device = _device;
         _faceBuffer.Upload32(faces.Memory, 0, faces.Length);
      }
   }
}


text:
@interface WordTreeWindow : NSWindow {

}

@end


text:
package com.intellij.vcs.log.history;

import com.intellij.openapi.vcs.FilePath;
import com.intellij.openapi.vcs.RepositoryLocation;
import com.intellij.openapi.vcs.VcsException;
import com.intellij.openapi.vcs.changes.ByteBackedContentRevision;
import com.intellij.openapi.vcs.changes.ContentRevision;
import com.intellij.openapi.vcs.history.VcsFileRevisionEx;
import com.intellij.openapi.vcs.history.VcsRevisionNumber;
import com.intellij.vcs.log.VcsFullCommitDetails;
import com.intellij.vcs.log.VcsUser;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;

public class VcsLogFileRevision extends VcsFileRevisionEx {
  @NotNull private final ContentRevision myRevision;
  @NotNull private final FilePath myPath;
  @NotNull private final VcsUser myAuthor;
  @NotNull private final VcsUser myCommitter;
  private final long myAuthorTime;
  private final long myCommitTime;
  @NotNull private final String myFullMessage;

  @Nullable private byte[] myContent = null;

  public VcsLogFileRevision(@NotNull VcsFullCommitDetails details, @NotNull ContentRevision revision, @NotNull FilePath path) {
    myRevision = revision;
    myPath = path;

    myAuthor = details.getAuthor();
    myCommitter = details.getCommitter();
    myAuthorTime = details.getAuthorTime();
    myCommitTime = details.getCommitTime();
    myFullMessage = details.getFullMessage();
  }

  @Nullable
  @Override
  public String getAuthor() {
    return myAuthor.getName();
  }

  @Nullable
  @Override
  public String getAuthorEmail() {
    return myAuthor.getEmail();
  }

  @Nullable
  @Override
  public String getCommitterName() {
    return myCommitter.getName();
  }

  @Nullable
  @Override
  public String getCommitterEmail() {
    return myCommitter.getName();
  }

  @Nullable
  @Override
  public String getCommitMessage() {
    return myFullMessage;
  }

  @NotNull
  @Override
  public FilePath getPath() {
    return myPath;
  }

  @Nullable
  @Override
  public String getBranchName() {
    return null;
  }

  @Nullable
  @Override
  public RepositoryLocation getChangedRepositoryPath() {
    return null;
  }

  @Override
  public byte[] loadContent() throws IOException, VcsException {
    if (myContent == null) {
      if (myRevision instanceof ByteBackedContentRevision) {
        myContent = ((ByteBackedContentRevision)myRevision).getContentAsBytes();
      }
      else {
        String content = myRevision.getContent();
        if (content != null) {
          myContent = content.getBytes(myPath.getCharset().name());
        }
      }
    }

    return myContent;
  }

  @Nullable
  @Override
  public byte[] getContent() {
    return myContent;
  }

  @NotNull
  @Override
  public VcsRevisionNumber getRevisionNumber() {
    return myRevision.getRevisionNumber();
  }

  @Override
  public Date getRevisionDate() {
    Calendar cal = Calendar.getInstance();
    cal.setTimeInMillis(myCommitTime);
    return cal.getTime();
  }

  @Nullable
  @Override
  public Date getAuthorDate() {
    Calendar cal = Calendar.getInstance();
    cal.setTimeInMillis(myAuthorTime);
    return cal.getTime();
  }
}


text:
@class NSString;

@interface _XCNotificationExpectation : XCTestExpectation
{
    id _observedObject;
    NSString *_notificationName;
    CDUnknownBlockType _handler;
}

- (void)_observeExpectedNotification:(id)arg1;
- (void)cleanup;
- (void)dealloc;
@property(copy) CDUnknownBlockType handler; // @synthesize handler=_handler;
@property(copy) NSString *notificationName; // @synthesize notificationName=_notificationName;
@property(retain) id observedObject; // @synthesize observedObject=_observedObject;
- (void)startObserving;

@end


text:
package org.ovirt.engine.core.dal.dbbroker.auditloghandling;

import org.ovirt.engine.core.compat.*;
import org.ovirt.engine.core.common.*;
import org.ovirt.engine.core.dal.dbbroker.*;

/**
 * AlertDirector
 */
public final class AlertDirector {
    /**
     * Alerts the specified audit logable.
     *
     * @param auditLogable
     *            The audit logable.
     * @param logType
     *            Type of the log.
     */
    public static void Alert(AuditLogableBase auditLogable, AuditLogType logType) {
        AuditLogDirector.log(auditLogable, logType);
    }

    /**
     * Removes the alert.
     *
     * @param vdsId
     *            The VDS id.
     * @param type
     *            The type.
     */
    public static void RemoveVdsAlert(Guid vdsId, AuditLogType type) {
        DbFacade.getInstance().getAuditLogDAO().removeAllOfTypeForVds(vdsId, type.getValue());
    }

    /**
     * Removes all alerts.
     *
     * @param vdsId
     *            The VDS id.
     * @param removeConfigAlerts
     *            if set to <c>true</c> [remove config alerts].
     */
    public static void RemoveAllVdsAlerts(Guid vdsId, boolean removeConfigAlerts) {
        DbFacade.getInstance().getAuditLogDAO().removeAllForVds(vdsId, removeConfigAlerts);
    }
}


text:
![General Assembly Logo](http://i.imgur.com/ke8USTq.png)

# Javascript Assignment Name

## Objectives

By the end of this, students should be able to:

- Objective 1
- Objective 2
- Objective 3

## Instructions

Include explict step-by-step instructions about the goals of the assignment, and how to run the code.

Make sure to wrap section of code in appropriate markdown like `ls -al`, and denote the language as below for longer sections:

```javascript
function(){
  var x = 2
  var y = 3
  return x + y
};

```

## Bonus (Optional Section)

If you're looking for extra challenge or practice once you've completed the above, try to...

## Notes

Gotcha's and extra information

## Additional Resources

List additional related resources such as videos, blog posts and official documentation.

- Item 1
- Item 2
- Item 3


text:
package compression

import (
	"github.com/nbio/st"
	"gopkg.in/h2non/gentleman.v2/context"
	"net/http"
	"testing"
)

func TestDisableCompression(t *testing.T) {
	ctx := context.New()
	fn := newHandler()
	Disable().Exec("request", ctx, fn.fn)
	st.Expect(t, fn.called, true)
	transport := ctx.Client.Transport.(*http.Transport)
	st.Expect(t, transport.DisableCompression, true)
}

type handler struct {
	fn     context.Handler
	called bool
}

func newHandler() *handler {
	h := &handler{}
	h.fn = context.NewHandler(func(c *context.Context) {
		h.called = true
	})
	return h
}


text:
import os
from urllib.parse import urlparse

class FileAPI():

    def __init__(self, root):
        self.root = root

    def to_abs(self, relative):
        p = os.path.abspath(os.path.join(self.root, "./" + relative))
        return p

    def to_rel(self, abspath):
        p = os.path.relpath(abspath, self.root)
        return p

    def prepare_dir(self, relative):
        d = os.path.dirname(relative)
        if d and not os.path.exists(self.to_abs(d)):
            import re
            folders = re.split(r"\\|/", d)
            p = self.root
            for f in folders:
                p += os.path.sep + f
                if not os.path.exists(p):
                    os.makedirs(p)

    def open_with_mkdir(self, relative):
        self.prepare_dir(relative)
        return open(self.to_abs(relative), "wb")

    def get_file_name(self, url):
        parsed = urlparse(url)
        name, ext = os.path.splitext(os.path.basename(parsed.path))
        if not ext:
            name, ext = os.path.splitext(os.path.basename(parsed.query.replace("=", "/")))
        ext = ext.lower()
        fname = name + ext
        return fname

    def join_relative(self, relative, path):
        p = os.path.join(relative, path)
        relp = os.path.join(os.path.relpath(p), "")  # append final / everytime
        return relp

    def is_image(self, fname):
        extensions = [".jpeg", ".jpg", ".png", ".gif"]
        if fname.lower().endswith(tuple(extensions)):
            return True
        else:
            return False

    def ls_images(self, relative):
        path = self.to_abs(relative)
        for root, dirs, files in os.walk(path):
            for f in files:
                if self.is_image(f):
                    reldir = os.path.relpath(root, self.root)
                    rel = os.path.join(reldir, f)
                    yield rel

    @classmethod
    def add_ext_name(cls, path, ext_name):
        name, ext = os.path.splitext(os.path.basename(path))
        added = os.path.join(os.path.dirname(path), name + ext_name + ext)
        return added

    def write_iter(self, path, mode, iterator):
        _m = "ab" if mode in ("a", "ab") else "wb"
        with open(path, mode=_m) as f:
            index = 0
            for ln in iterator:
                f.write(ln.encode("utf-8"))
                if index // 1000 == 0:
                    f.flush()
                index += 1


text:
extern void* memsetZero(void *dest, int n);

void *sys_calloc(int elements, int elementSize){
    int p = elements*elementSize;
    void *tmp;
    tmp=sys_malloc(p);
    if (tmp==0)
        return 0;

    memsetZero(tmp, p);
    return tmp;
}


text:
//-------------
// <copyright file="EpisodeIndexItemViewModel.cs" company="Uncas">
//     Copyright (c) Ole Lynge Sørensen. All rights reserved.
// </copyright>
//-------------

namespace Uncas.PodCastPlayer.ViewModel
{
    using System;

    /// <summary>
    /// Represents a view of an episode item.
    /// </summary>
    public class EpisodeIndexItemViewModel
    {
        #region Constructor

        /// <summary>
        /// Initializes a new instance of the <see cref="EpisodeIndexItemViewModel"/> class.
        /// </summary>
        /// <param name="date">The publish date.</param>
        /// <param name="id">The id of the episode.</param>
        /// <param name="title">The title of the episode.</param>
        /// <param name="pendingDownload">if set to <c>true</c> [pending download].</param>
        /// <param name="downloadCompleted">if set to <c>true</c> [download completed].</param>
        public EpisodeIndexItemViewModel(
            DateTime date,
            string id,
            string title,
            bool pendingDownload,
            bool downloadCompleted)
        {
            if (date != null)
            {
                this.Date = date.Date;
            }

            this.DownloadCompleted = downloadCompleted;
            this.Id = id;
            this.PendingDownload = pendingDownload;
            this.Title = title;
        }

        #endregion

        #region Public properties

        /// <summary>
        /// Gets the date.
        /// </summary>
        /// <value>The publish date.</value>
        public DateTime Date { get; private set; }

        /// <summary>
        /// Gets a value indicating whether [download completed].
        /// </summary>
        /// <value><c>true</c> if [download completed]; otherwise, <c>false</c>.</value>
        public bool DownloadCompleted { get; private set; }

        /// <summary>
        /// Gets the id.
        /// </summary>
        /// <value>The id of the episode.</value>
        public string Id { get; private set; }

        /// <summary>
        /// Gets a value indicating whether [pending download].
        /// </summary>
        /// <value><c>true</c> if [pending download]; otherwise, <c>false</c>.</value>
        public bool PendingDownload { get; private set; }

        /// <summary>
        /// Gets the title.
        /// </summary>
        /// <value>The title of the episode.</value>
        public string Title { get; private set; }

        #endregion
    }
}


text:
define(["jquery", "backbone", "models/Model", "text!templates/chat.html"],

    function($, Backbone, Model, template){
        console.log("Init View")
        var Chat = Backbone.View.extend({

            // The DOM Element associated with this view
            el: ".eventChat",

            // View constructor
            initialize: function() {
                _this = this
                $(window).on('resize', function(){ _this.render() });
                // Calls the view's render method
                this.render();

            },

            // View Event Handlers
            events: {

            },

            // Renders the view's template to the UI
            render: function() {

                var chatHeight = $(window).height() - 67
                // Setting the view's template property using the Underscore template method
                this.template = _.template(template, {'chatHeight': chatHeight});

                // Dynamically updates the UI with the view's template
                this.$el.html(this.template);

                // Maintains chainability
                this.$el.css('height', chatHeight)
                return this;

            }

        });

        // Returns the View class
        return Chat;

    }

);


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

class Conta extends CI_Controller {

    public function index($conta  = null){
        $usuario = $this->session->userdata('usuario_logado');
        if ($usuario == null){
            redirect('../index.php/usuario/logoff');
        }

        $this->load->model('usuario_model');
        $this->load->model('categoria_model');
        $this->load->model('conta_model');
        $this->load->model('movimentacao_model');

        $data = date('Y-m-d');
        $data = explode('-',$data);

        $mes = $data[1];

        if(isset($_POST['filterMes'])){
            $mes = $this->input->post('filterMes');
        }

        if($this->session->flashdata('mes')){
            $mes = $this->session->flashdata('mes');
        }

        $data[1] = intval($mes);

        $this->session->set_flashdata('exibir' ,0);

        $usuario = $this->usuario_model->pegaUsuarioById($usuario['cd_usuario']);
        $categorias['receitas'] = $this->categoria_model->pegaCategorias(1);
        $categorias['despesas'] = $this->categoria_model->pegaCategorias(2);
        $contas = $this->conta_model->pegaContasUsuario($usuario['cd_usuario']);
        $movimentacoes['conta'] = $this->movimentacao_model->pegaMovimentacoesContaPorData($data, $usuario['cd_usuario']);

        if(count($contas) > 0){
            $open = ($conta == null) ? $contas[0]['cd_conta'] : $conta;
        }else{
            $open = 0;
        }

        $parametros = array(
            'usuario' => $usuario,
            'contas' => $contas,
            'categorias' => $categorias,
            'mes' => $mes,
            'movimentacoes' => $movimentacoes,
            'open' => $open,
        );

        $this->load->main_template('conta/contas.php', $parametros);
    }

    public function novaConta(){
        $usuario = $this->session->userdata('usuario_logado');

        if(isset($_POST)){
            $conta = array(
                'nm_conta' => $this->input->post('nome'),
                'ds_cor' => $this->input->post('cor'),
                'tipo' => $this->input->post('tipo'),
                'banco' => $this->input->post('banco'),
                'cd_usuario' => $usuario['cd_usuario'],
                'status' => 1
            );
            $this->load->model('conta_model');
            $this->conta_model->salvaConta($conta);
        }

        redirect("conta/");
    }

    public function deletarConta($id_conta){
        $usuario = $this->session->userdata('usuario_logado');

        $this->load->model('conta_model');
        $conta = $this->conta_model->pegaConta($id_conta);

        if($usuario['cd_usuario'] == $conta['cd_usuario']){
            $conta['status'] = 0;
            $this->conta_model->deletaConta($id_conta, $conta);
            $this->session->set_flashdata("aviso", "
Deletado conta com sucesso
");
        }else{
            $this->session->set_flashdata("aviso", "
Erro ao deletar conta, Não Autorizado
");
        }

        redirect("conta/");

    }

    public function editarConta($id_conta){

        if(isset($_POST)){

            $this->load->model('conta_model');

            $contaAtual = $this->conta_model->pegaConta($id_conta);

            $conta = array(
                'nm_conta' => empty($this->input->post('nome')) ? $contaAtual['nm_conta'] : $this->input->post('nome') ,
                'ds_cor' => $this->input->post('cor'),
                'tipo' => $this->input->post('tipo'),
                'banco' => $this->input->post('banco')
            );

            $this->conta_model->editaConta($id_conta, $conta);
        }

        redirect("conta/");

    }

}


text:
package com.dorand.gpsc.ui;

import android.app.Activity;
import android.os.Bundle;

public class AboutActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_about);
	}

}


text:
require 'puppet'
require File.expand_path(File.join(File.dirname(__FILE__), '..', 'rabbitmqctl'))
Puppet::Type.type(:rabbitmq_exchange).provide(:rabbitmqadmin, :parent => Puppet::Provider::Rabbitmqctl) do

  if Puppet::PUPPETVERSION.to_f < 3
    commands :rabbitmqctl   => 'rabbitmqctl'
    commands :rabbitmqadmin => '/usr/local/bin/rabbitmqadmin'
  else
    has_command(:rabbitmqctl, 'rabbitmqctl') do
      environment :HOME => "/tmp"
    end
    has_command(:rabbitmqadmin, '/usr/local/bin/rabbitmqadmin') do
      environment :HOME => "/tmp"
    end
  end
  defaultfor :feature => :posix

  def should_vhost
    if @should_vhost
      @should_vhost
    else
      @should_vhost = resource[:name].split('@')[1]
    end
  end

  def self.all_vhosts
    vhosts = []
    self.run_with_retries {
      rabbitmqctl('-q', 'list_vhosts')
    }.split(/\n/).each do |vhost|
      vhosts.push(vhost)
    end
    vhosts
  end

  def self.all_exchanges(vhost)
    exchanges = []
    self.run_with_retries {
      rabbitmqctl('-q', 'list_exchanges', '-p', vhost, 'name', 'type')
    }.split(/\n/).each do |exchange|
      exchanges.push(exchange)
    end
    exchanges
  end

  def self.instances
    resources = []
    all_vhosts.each do |vhost|
        all_exchanges(vhost).each do |line|
            name, type = line.split()
            if type.nil?
                # if name is empty, it will wrongly get the type's value.
                # This way type will get the correct value
                type = name
                name = ''
            end
            exchange = {
              :type   => type,
              :ensure => :present,
              :name   => "%s@%s" % [name, vhost],
            }
            resources << new(exchange) if exchange[:type]
        end
    end
    resources
  end

  def self.prefetch(resources)
    packages = instances
    resources.keys.each do |name|
      if provider = packages.find{ |pkg| pkg.name == name }
        resources[name].provider = provider
      end
    end
  end

  def exists?
    @property_hash[:ensure] == :present
  end

  def create
    vhost_opt = should_vhost ? "--vhost=#{should_vhost}" : ''
    name = resource[:name].split('@')[0]
    rabbitmqadmin('declare', 'exchange', vhost_opt, "--user=#{resource[:user]}", "--password=#{resource[:password]}", "name=#{name}", "type=#{resource[:type]}", '-c', '/etc/rabbitmq/rabbitmqadmin.conf')
    @property_hash[:ensure] = :present
  end

  def destroy
    vhost_opt = should_vhost ? "--vhost=#{should_vhost}" : ''
    name = resource[:name].split('@')[0]
    rabbitmqadmin('delete', 'exchange', vhost_opt, "--user=#{resource[:user]}", "--password=#{resource[:password]}", "name=#{name}", '-c', '/etc/rabbitmq/rabbitmqadmin.conf')
    @property_hash[:ensure] = :absent
  end

end


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Panzeria canescens Bunge

### Remarks
null


text:
OPENEXR_IMF_INTERNAL_NAMESPACE_HEADER_ENTER

typedef std::vector<std::string> StringVector;
typedef TypedAttribute<OPENEXR_IMF_INTERNAL_NAMESPACE::StringVector> StringVectorAttribute;

template <>
IMF_EXPORT
const char *StringVectorAttribute::staticTypeName ();

template <>
IMF_EXPORT
void StringVectorAttribute::writeValueTo (OPENEXR_IMF_INTERNAL_NAMESPACE::OStream &,
                                          int) const;

template <>
IMF_EXPORT
void StringVectorAttribute::readValueFrom (OPENEXR_IMF_INTERNAL_NAMESPACE::IStream &,
                                           int, int);

OPENEXR_IMF_INTERNAL_NAMESPACE_HEADER_EXIT

#endif


text:
<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

    <session-factory>

        <!-- Database connection settings -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://127.0.0.1:3306/drogaria</property>
        <property name="connection.username">root</property>
        <property name="connection.password"></property>

        <!-- Pool de Conexões  -->
        <property name="connection.pool_size">1</property>

        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>

        <!-- Gerenciamento do Contexto das Sessões -->
        <property name="current_session_context_class">thread</property>

        <!-- Disable the second-level cache / Cache de Segundo Nível  -->
        <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>

        <!-- Echo all executed SQL to stdout / Mostra as SQLs Geradas -->
        <property name="show_sql">true</property>

        <!-- Drop and re-create the database schema on startup -->
        <property name="hbm2ddl.auto">validate</property>

        <!-- Mapeamento das entidades -->
        <mapping class="com.aula.andre.drogaria.domain.Cidade" />
        <mapping class="com.aula.andre.drogaria.domain.Cliente" />
        <mapping class="com.aula.andre.drogaria.domain.Estado" />
        <mapping class="com.aula.andre.drogaria.domain.Funcionario" />
        <mapping class="com.aula.andre.drogaria.domain.Fabricante" />
        <mapping class="com.aula.andre.drogaria.domain.Pessoa" />
        <mapping class="com.aula.andre.drogaria.domain.Produto" />
        <mapping class="com.aula.andre.drogaria.domain.Usuario" />
        <mapping class="com.aula.andre.drogaria.domain.Venda" />
        <mapping class="com.aula.andre.drogaria.domain.ItemVenda" />

    </session-factory>

</hibernate-configuration>


text:
#include <ServerVisionCam.h>

ServerVisionCam::ServerVisionCam() :
    m_dvp(0),
    m_running(false_e),
    m_server(NULL),
    m_data(NULL),
    m_pCam(NULL),
    m_frameData(NULL),
    m_numDataBytes(0),
    m_numImageBytes(0),
    m_pImages(NULL),
    m_status(STATUS_SUCCESS),
    m_param(NULL),
//#if defined(__QNX__)
    m_display_enabled(true_e),
//#else
//    m_display_enabled(false_e),
//#endif
    m_display(NULL),
    m_allocWidth(0),
    m_allocHeight(0)
{
    event_init(&m_wait, false_e);
    memset(&m_img, 0, sizeof(VisionCamImages_t));
    m_dvp = DVP_KernelGraph_Init();
    m_pImages = (DVP_Image_t *)calloc(VCAM_NUM_BUFFERS, sizeof(DVP_Image_t));
}

ServerVisionCam::~ServerVisionCam()
{
    if (m_param) {
        free(m_param);
        m_param = NULL;
    }
    free(m_pImages);
    DVP_KernelGraph_Deinit(m_dvp);
    event_deinit(&m_wait);
}

void ServerVisionCam::FrameCallback(VisionCamFrame * cameraFrame)
{
    ServerVisionCam *pSVCam = reinterpret_cast<ServerVisionCam *>(cameraFrame->mCookie);
    uint32_t offset = 0;

    if (pSVCam->m_display_enabled && cameraFrame->mFrameSource == VCAM_PORT_PREVIEW)
    {
        DVP_Image_t *pImage = (DVP_Image_t *)cameraFrame->mFrameBuff;
        DVP_Display_Render(pSVCam->m_display, pImage);
    }

    // serialize the camera frame to a flat buffer
    offset += cameraFrame->serialize(pSVCam->m_frameData, pSVCam->m_numDataBytes);

    // send the buffer size
    socket_send(pSVCam->m_data, (uint8_t *)&offset, sizeof(offset));

    // send the frame
    socket_send(pSVCam->m_data, pSVCam->m_frameData, offset);

    pSVCam->m_pCam->returnFrame(cameraFrame);
}

void ServerVisionCam::FocusCallback(int state)
{
    state = state; // warnings
    DVP_PRINT(DVP_ZONE_ALWAYS, "Focus state %d\n", state);
}

bool_e ServerVisionCam::init(void *arg, rpc_socket_item_t *params, uint32_t numParams, rpc_socket_item_t *returns, uint32_t *numReturns)
{
    ServerVisionCam *pSVCam = (ServerVisionCam *)arg;
    VisionCam *pCam = pSVCam->m_pCam;
    params = params; // remove warning
    if (pCam && numParams == 0)
    {
        pSVCam->m_status = pCam->init(pSVCam);
        if (pSVCam->m_status == STATUS_SUCCESS)
        {
            socket_connect(pSVCam->m_data);
            pCam->enablePreviewCbk(FrameCallback);
            pCam->setFocusCallBack(FocusCallback);
        }
        returns[0].type = RPC_SOCKET_TYPE_INT32;
        returns[0].numElements = 1;
        returns[0].sizeElement = sizeof(status_e);
        returns[0].item = &pSVCam->m_status; // must be static or class variable!
        *numReturns = 1;
        return true_e;
    }
    else
        return false_e;
}

bool_e ServerVisionCam::deinit(void *arg, rpc_socket_item_t *params, uint32_t numParams, rpc_socket_item_t *returns, uint32_t *numReturns)
{
    ServerVisionCam *pSVCam = (ServerVisionCam *)arg;
    VisionCam *pCam = pSVCam->m_pCam;
    params = params; // remove warning
    if (pCam && numParams == 0)
    {
        pCam->setFocusCallBack(NULL);
        pSVCam->m_status = pCam->deinit();

        returns[0].type = RPC_SOCKET_TYPE_INT32;
        returns[0].numElements = 1;
        returns[0].sizeElement = sizeof(status_e);
        returns[0].item = &pSVCam->m_status; // must be static or class variable!
        *numReturns = 1;
        event_set(&pSVCam->m_wait); // signal that we're done...
        return true_e;
    }
    else
        return false_e;
}

bool_e ServerVisionCam::setParameter(void *arg, rpc_socket_item_t *params, uint32_t numParams, rpc_socket_item_t *returns, uint32_t *numReturns)
{
    ServerVisionCam *pSVCam = (ServerVisionCam *)arg;
    VisionCam *pCam = pSVCam->m_pCam;
    if (pCam && numParams == 2 &&
        params[0].numElements == 1 && params[0].sizeElement == sizeof(int32_t))
    {
        VisionCamParam_e paramId = *(VisionCamParam_e *)params[0].item;
        void *param = params[1].item;
        uint32_t size = params[1].numElements * params[1].sizeElement;
        pSVCam->m_status = pCam->setParameter(paramId, param, size);
        returns[0].type = RPC_SOCKET_TYPE_INT32;
        returns[0].numElements = 1;
        returns[0].sizeElement = sizeof(status_e);
        returns[0].item = &pSVCam->m_status; // must be static or class variable!
        *numReturns = 1;
        return true_e;
    }
    else
        return false_e;
}

bool_e ServerVisionCam::getParameter(void *arg, rpc_socket_item_t *params, uint32_t numParams, rpc_socket_item_t *returns, uint32_t *numReturns)
{
    ServerVisionCam *pSVCam = (ServerVisionCam *)arg;
    VisionCam *pCam = pSVCam->m_pCam;
    if (pCam && numParams == 2 &&
        params[0].numElements == 1 && params[0].sizeElement == sizeof(int32_t) &&
        params[1].numElements == 1 && params[0].sizeElement == sizeof(uint32_t))
    {
        VisionCamParam_e paramId = *(VisionCamParam_e *)params[0].item;
        uint32_t size = *(uint32_t *)params[1].item;

        if (pSVCam->m_param) {
            free(pSVCam->m_param);
            pSVCam->m_param = NULL;
        }
        if (pSVCam->m_param == NULL) {
            pSVCam->m_param = calloc(1, size);
        }

        pSVCam->m_status = pCam->getParameter(paramId, pSVCam->m_param, size);

        if (paramId == VCAM_PARAM_2DBUFFER_DIM)
        {
            VisionCamResType *res = (VisionCamResType *)pSVCam->m_param;

            pSVCam->m_allocWidth = res->mWidth;
            pSVCam->m_allocHeight = res->mHeight;
        }

        returns[0].type = RPC_SOCKET_TYPE_INT32;
        returns[0].numElements = 1;
        returns[0].sizeElement = sizeof(status_e);
        returns[0].item = &pSVCam->m_status; // must be static or class variable!
        returns[1].type = RPC_SOCKET_TYPE_INT8;
        returns[1].numElements = size;
        returns[1].sizeElement = sizeof(uint8_t);
        returns[1].item = pSVCam->m_param; // must be static or class variable!
        *numReturns = 2;
        return true_e;
    }
    else
        return false_e;
}

bool_e ServerVisionCam::sendCommand(void *arg, rpc_socket_item_t *params, uint32_t numParams, rpc_socket_item_t *returns, uint32_t *numReturns)
{
    ServerVisionCam *pSVCam = (ServerVisionCam *)arg;
    VisionCam *pCam = pSVCam->m_pCam;
    if (pCam && numParams == 2 &&
        params[0].numElements == 1 && params[0].sizeElement == sizeof(int32_t))
    {
        VisionCamCmd_e cmd = *(VisionCamCmd_e *)params[0].item;
        void *param = params[1].item;
        uint32_t size = params[1].numElements * params[1].sizeElement;

        pSVCam->m_status = pCam->sendCommand(cmd, param, size);

        returns[0].type = RPC_SOCKET_TYPE_INT32;
        returns[0].numElements = 1;
        returns[0].sizeElement = sizeof(status_e);
        returns[0].item = &pSVCam->m_status; // must be static or class variable!
        *numReturns = 1;

        return true_e;
    }
    else
        return false_e;
}

bool_e ServerVisionCam::useBuffers(void *arg, rpc_socket_item_t *params, uint32_t numParams, rpc_socket_item_t *returns, uint32_t *numReturns)
{
    ServerVisionCam *pSVCam = (ServerVisionCam *)arg;
    VisionCam *pCam = pSVCam->m_pCam;
    if (pCam && numParams == 1 &&
        params[0].numElements == 1 && params[0].sizeElement == sizeof(VisionCamImages_t))
    {
        pSVCam->m_img = *(VisionCamImages_t *)params[0].item;
        if (pSVCam->m_frameData != NULL)
        {
            free(pSVCam->m_frameData);
            pSVCam->m_numDataBytes = 0;
            pSVCam->m_numImageBytes = 0;
            pSVCam->m_frameData = NULL;
        }
        if (pSVCam->m_frameData == NULL)
        {
            // compute the image size
            DVP_PRINT(DVP_ZONE_ALWAYS, "ServerVisionCam: w:%u h:%u c:0x%08x #:%u\n", pSVCam->m_img.width, pSVCam->m_img.height, pSVCam->m_img.color, pSVCam->m_img.count);
            DVP_PRINT(DVP_ZONE_ALWAYS, "ServerVisionCam: Alloc: w:%u h:%u\n", pSVCam->m_allocWidth, pSVCam->m_allocHeight);
            DVP_Image_t image;
            VisionCamFrame cFrame;

            // create a dummy image
            DVP_Image_Init(&image, pSVCam->m_img.width, pSVCam->m_img.height, pSVCam->m_img.color);

            // clear out the frame and assign the image then ask how big it could possibly be
            cFrame.clear();
            cFrame.mFrameBuff = ℑ

            pSVCam->m_numDataBytes = cFrame.maxSerialLength();
            pSVCam->m_frameData = (uint8_t *)calloc(1, pSVCam->m_numDataBytes);
            DVP_PRINT(DVP_ZONE_CAM, "ServerVisionCam: Allocated %u bytes for m_frameData %p packet [%p-%p)\n", pSVCam->m_numDataBytes, pSVCam->m_frameData, pSVCam->m_frameData, &pSVCam->m_frameData[pSVCam->m_numDataBytes]);
        }
        if (pSVCam->m_display_enabled)
        {
            pSVCam->m_display = DVP_Display_Create(pSVCam->m_img.width,
                                                   pSVCam->m_img.height,
                                                   pSVCam->m_allocWidth,
                                                   pSVCam->m_allocHeight,
                                                   DVP_DISPLAY_WIDTH,
                                                   DVP_DISPLAY_HEIGHT,
                                                   pSVCam->m_allocWidth,
                                                   pSVCam->m_allocHeight,
                                                   0, 0,
                                                   pSVCam->m_img.color,
                                                   0, pSVCam->m_img.count);
        }
        for (uint32_t i = 0; i < pSVCam->m_img.count; i++)
        {
            DVP_Image_Init(&pSVCam->m_pImages[i], pSVCam->m_allocWidth, pSVCam->m_allocHeight, pSVCam->m_img.color);
            pSVCam->m_pImages[i].width = pSVCam->m_img.width;
            pSVCam->m_pImages[i].height = pSVCam->m_img.height;

            if (pSVCam->m_display_enabled && pSVCam->m_display)
            {
                DVP_Display_Alloc(pSVCam->m_display, &pSVCam->m_pImages[i]);
                DVP_Image_Alloc(pSVCam->m_dvp, &pSVCam->m_pImages[i], (DVP_MemType_e)pSVCam->m_pImages[i].memType);
            }
            else
            {
#if defined(DVP_USE_TILER)
                DVP_Image_Alloc(pSVCam->m_dvp, &pSVCam->m_pImages[i], DVP_MTYPE_MPUNONCACHED_2DTILED);
#else
                DVP_Image_Alloc(pSVCam->m_dvp, &pSVCam->m_pImages[i], DVP_MTYPE_DEFAULT);
#endif
            }
        }
        pSVCam->m_status = pCam->useBuffers(pSVCam->m_pImages, pSVCam->m_img.count, (VisionCamPort_e)pSVCam->m_img.port);
        returns[0].type = RPC_SOCKET_TYPE_INT32;
        returns[0].numElements = 1;
        returns[0].sizeElement = sizeof(status_e);
        returns[0].item = &pSVCam->m_status; // must be static or class variable!
        *numReturns = 1;
        return true_e;
    }
    else
        return false_e;
}

bool_e ServerVisionCam::releaseBuffers(void *arg, rpc_socket_item_t *params, uint32_t numParams, rpc_socket_item_t *returns, uint32_t *numReturns)
{
    ServerVisionCam *pSVCam = (ServerVisionCam *)arg;
    VisionCam *pCam = pSVCam->m_pCam;
    params = params; // remove warning
    if (pCam && numParams == 0)
    {
        pCam->disablePreviewCbk(FrameCallback);
        pSVCam->m_status = pCam->releaseBuffers();
        socket_disconnect(pSVCam->m_data);
        socket_deinit(pSVCam->m_data);
        pSVCam->m_data = NULL;
        for (uint32_t i = 0; i < pSVCam->m_img.count; i++)
        {
            if (pSVCam->m_display_enabled)
            {
                DVP_Display_Free(pSVCam->m_display, &pSVCam->m_pImages[i]);
            }
            else
            {
                DVP_Image_Free(pSVCam->m_dvp,&pSVCam->m_pImages[i]);
                DVP_Image_Deinit(&pSVCam->m_pImages[i]);
            }
        }
        if (pSVCam->m_display_enabled)
        {
            DVP_Display_Destroy(&pSVCam->m_display);
            pSVCam->m_display_enabled = false_e;
        }
        free(pSVCam->m_frameData);
        pSVCam->m_frameData = NULL;
        pSVCam->m_numDataBytes = 0;
        pSVCam->m_numImageBytes = 0;
        returns[0].type = RPC_SOCKET_TYPE_INT32;
        returns[0].numElements = 1;
        returns[0].sizeElement = sizeof(status_e);
        returns[0].item = &pSVCam->m_status; // must be static or class variable!
        *numReturns = 1;
        return true_e;
    }
    else
        return false_e;
}

bool_e ServerVisionCam::flushBuffers(void *arg, rpc_socket_item_t *params, uint32_t numParams, rpc_socket_item_t *returns, uint32_t *numReturns)
{
    ServerVisionCam *pSVCam = (ServerVisionCam *)arg;
    VisionCam *pCam = pSVCam->m_pCam;
    params = params; // remove warning
    if (pCam && numParams == 0)
    {
        pSVCam->m_status = pCam->flushBuffers();
        returns[0].type = RPC_SOCKET_TYPE_INT32;
        returns[0].numElements = 1;
        returns[0].sizeElement = sizeof(status_e);
        returns[0].item = &pSVCam->m_status; // must be static or class variable!
        *numReturns = 1;
        return true_e;
    }
    else
        return false_e;
}

ServerVisionCam *ServerVisionCam::instantiate(char *hostname, VisionCam_e camType)
{
    ServerVisionCam *pSVCam = new ServerVisionCam();
    // @see VisionCamFunction_e This must match that order of functions.
    rpc_server_function_f functions[] = {
        ServerVisionCam::init,
        ServerVisionCam::deinit,
        ServerVisionCam::setParameter,
        ServerVisionCam::getParameter,
        ServerVisionCam::sendCommand,
        ServerVisionCam::useBuffers,
        ServerVisionCam::releaseBuffers,
        ServerVisionCam::flushBuffers,
    };

    // instantiate the camera but don't initialize
    pSVCam->m_pCam = VisionCamFactory(camType);

    // initlialize the server components
    pSVCam->m_ipaddr = socket_hostname(hostname);
    pSVCam->m_server = rpc_socket_server_init(hostname, VCAM_SOCKET_CMD_PORT, pSVCam, functions, dimof(functions));
    pSVCam->m_data = socket_init(pSVCam->m_ipaddr, VCAM_SOCKET_DATA_PORT, SOCKET_TCP, true_e);

    // start the server
    rpc_socket_server_start(pSVCam->m_server);

    return pSVCam;
}

bool_e ServerVisionCam::WaitForCompletion()
{
    // WAIT until it's over
    event_wait(&m_wait, EVENT_FOREVER);

    // Close up
    socket_disconnect(m_data);
    socket_deinit(m_data);
    rpc_socket_server_stop(m_server);
    rpc_socket_server_deinit(m_server);

    return true_e;
}

void ServerVisionCam::SignalCompletion()
{
    event_set(&m_wait);
}


text:
from __future__ import unicode_literals
from ..diffusion import dtiaverage

def test_dtiaverage_inputs():
    input_map = dict(DTI_double=dict(argstr='--DTI_double ',
    ),
    args=dict(argstr='%s',
    ),
    environ=dict(nohash=True,
    usedefault=True,
    ),
    ignore_exception=dict(nohash=True,
    usedefault=True,
    ),
    inputs=dict(argstr='--inputs %s...',
    ),
    tensor_output=dict(argstr='--tensor_output %s',
    hash_files=False,
    ),
    terminal_output=dict(deprecated='1.0.0',
    nohash=True,
    ),
    verbose=dict(argstr='--verbose ',
    ),
    )
    inputs = dtiaverage.input_spec()

    for key, metadata in list(input_map.items()):
        for metakey, value in list(metadata.items()):
            assert getattr(inputs.traits()[key], metakey) == value

def test_dtiaverage_outputs():
    output_map = dict(tensor_output=dict(),
    )
    outputs = dtiaverage.output_spec()

    for key, metadata in list(output_map.items()):
        for metakey, value in list(metadata.items()):
            assert getattr(outputs.traits()[key], metakey) == value


text:
const rpc           = require('axon-rpc')
const axon          = require('axon')
const rep           = axon.socket('rep');
const path          = require('path');
const Table         = require('cli-table');
const colors        = require('colors/safe');
const fs            = require('fs');

const { RPC_PORT }  = require('../common/constraints');
const conf          = require('../common/config');
const { fork }      = require('child_process');
const { spawn }     = require('child_process');

const BASE_DIR      = path.dirname(require.main.filename);

const server        = new rpc.Server(rep);
var modules = {};
var modulesJson = [];

server.expose({
  'server:start': function(port, fn) {
    let pid = fork(`${__dirname}/../core/pserver.js`, ['-p', port]).pid;

    conf.set('servers.pserver', {
      port: port,
      pid: pid
    });

    fn(null, 'done!');
  },

  'server:stop': function(fn) {
    let pid = conf.get(`servers.pserver.pid`);

    if (typeof pid == 'number') {
      spawn('kill', ['-9', pid]);
    }

    fn(null, 'done!');
  },

  'modules:list': function(fn) {
    var table = new Table({
      head: [colors.bold.cyan('Name'), colors.bold.cyan('Pid')],
      colWidths: [30, 10],
    });

    var rows = [];

    const modules = conf.get('modules');
    const modulesKeys = Object.keys(modules);

    for (var i = 0; i < modulesKeys.length; i++) {
      table.push([modulesKeys[i], modules[modulesKeys[i]].pid])
    }

    fn(null, table.toString());
  },

  'modules:list-json': function(fn) {
    const modules = conf.get('modules');

    fn(null, modules);
  },

  'module:start': function(module, server, name, fn) {
    const modulePath = path.join(process.cwd(), module);

    fs.readdir(modulePath, 'utf8', (err, data) => {
      data.forEach((fileName) => {
        if (fileName.indexOf('.pjs') > -1) {
          const pjsPath = path.join(modulePath, fileName);

          fs.readFile(pjsPath, 'utf8', (err, data) => {
            if (err) throw err;
            const conf = require('../common/config');
            const moduleData = JSON.parse(data);

            let moduleCount = conf.get('m_count') + 1;
            conf.set('m_count', moduleCount);

            // TODO name must be unique
            var pid = fork(`${__dirname}/../core/pmodule.js`, ['-m', pjsPath, '-s', server]).pid;

            conf.set(`modules.${moduleData.name}_${moduleCount}`, {
              name: moduleData.name,
              _v:   moduleData._v,
              path: modulePath,
              services: moduleData.services,
              pid:  pid
            });
          });
        }
      });
    });

    fn(null, 'done!');
  },

  'module:stop': function(name, fn) {
    let modulePid = conf.get(`modules.${name}.pid`);

    if (typeof modulePid == 'number') {
      spawn('kill', ['-9', modulePid]);
    }

    conf.delete(`modules.${name}`);

    fn(null, 'done!');
  }
});

rep.bind(RPC_PORT, () => {
});


text:
import React from 'react'
import TopNav from '../../src/components/core/TopNav'

class Notes extends React.Component {

  render () {
    return (

Notes

Notes, reflections, and highlights from my studies and the books I read

    )
  }
}

export default Notes;