text:
/*
 * INET		An implementation of the TCP/IP protocol suite for the LINUX
 *		operating system.  INET is implemented using the  BSD Socket
 *		interface as the means of communication with the user level.
 *
 *		The IP fragmentation functionality.
 *
 * Authors:	Fred N. van Kempen <waltje@uWalt.NL.Mugnet.ORG>
 *		Alan Cox <alan@lxorguk.ukuu.org.uk>
 *
 * Fixes:
 *		Alan Cox	:	Split from ip.c , see ip_input.c for history.
 *		David S. Miller :	Begin massive cleanup...
 *		Andi Kleen	:	Add sysctls.
 *		xxxx		:	Overlapfrag bug.
 *		Ultima          :       ip_expire() kernel panic.
 *		Bill Hawes	:	Frag accounting and evictor fixes.
 *		John McDonald	:	0 length frag bug.
 *		Alexey Kuznetsov:	SMP races, threading, cleanup.
 *		Patrick McHardy :	LRU queue of frag heads for evictor.
 */

#define pr_fmt(fmt) "IPv4: " fmt

#include <linux/compiler.h>
#include <linux/module.h>
#include <linux/types.h>
#include <linux/mm.h>
#include <linux/jiffies.h>
#include <linux/skbuff.h>
#include <linux/list.h>
#include <linux/ip.h>
#include <linux/icmp.h>
#include <linux/netdevice.h>
#include <linux/jhash.h>
#include <linux/random.h>
#include <linux/slab.h>
#include <net/route.h>
#include <net/dst.h>
#include <net/sock.h>
#include <net/ip.h>
#include <net/icmp.h>
#include <net/checksum.h>
#include <net/inetpeer.h>
#include <net/inet_frag.h>
#include <linux/tcp.h>
#include <linux/udp.h>
#include <linux/inet.h>
#include <linux/netfilter_ipv4.h>
#include <net/inet_ecn.h>

/* NOTE. Logic of IP defragmentation is parallel to corresponding IPv6
 * code now. If you change something here, _PLEASE_ update ipv6/reassembly.c
 * as well. Or notify me, at least. --ANK
 */

static int sysctl_ipfrag_max_dist __read_mostly = 64;

struct ipfrag_skb_cb
{
	struct inet_skb_parm	h;
	int			offset;
};

#define FRAG_CB(skb)	((struct ipfrag_skb_cb *)((skb)->cb))

/* Describe an entry in the "incomplete datagrams" queue. */
struct ipq {
	struct inet_frag_queue q;

	u32		user;
	__be32		saddr;
	__be32		daddr;
	__be16		id;
	u8		protocol;
	u8		ecn; /* RFC3168 support */
	int             iif;
	unsigned int    rid;
	struct inet_peer *peer;
};

static inline u8 ip4_frag_ecn(u8 tos)
{
	return 1 << (tos & INET_ECN_MASK);
}

static struct inet_frags ip4_frags;

int ip_frag_nqueues(struct net *net)
{
	return net->ipv4.frags.nqueues;
}

int ip_frag_mem(struct net *net)
{
	return sum_frag_mem_limit(&net->ipv4.frags);
}

static int ip_frag_reasm(struct ipq *qp, struct sk_buff *prev,
			 struct net_device *dev);

struct ip4_create_arg {
	struct iphdr *iph;
	u32 user;
};

static unsigned int ipqhashfn(__be16 id, __be32 saddr, __be32 daddr, u8 prot)
{
	net_get_random_once(&ip4_frags.rnd, sizeof(ip4_frags.rnd));
	return jhash_3words((__force u32)id << 16 | prot,
			    (__force u32)saddr, (__force u32)daddr,
			    ip4_frags.rnd) & (INETFRAGS_HASHSZ - 1);
}

static unsigned int ip4_hashfn(struct inet_frag_queue *q)
{
	struct ipq *ipq;

	ipq = container_of(q, struct ipq, q);
	return ipqhashfn(ipq->id, ipq->saddr, ipq->daddr, ipq->protocol);
}

static bool ip4_frag_match(struct inet_frag_queue *q, void *a)
{
	struct ipq *qp;
	struct ip4_create_arg *arg = a;

	qp = container_of(q, struct ipq, q);
	return	qp->id == arg->iph->id &&
		qp->saddr == arg->iph->saddr &&
		qp->daddr == arg->iph->daddr &&
		qp->protocol == arg->iph->protocol &&
		qp->user == arg->user;
}

static void ip4_frag_init(struct inet_frag_queue *q, void *a)
{
	struct ipq *qp = container_of(q, struct ipq, q);
	struct netns_ipv4 *ipv4 = container_of(q->net, struct netns_ipv4,
					       frags);
	struct net *net = container_of(ipv4, struct net, ipv4);

	struct ip4_create_arg *arg = a;

	qp->protocol = arg->iph->protocol;
	qp->id = arg->iph->id;
	qp->ecn = ip4_frag_ecn(arg->iph->tos);
	qp->saddr = arg->iph->saddr;
	qp->daddr = arg->iph->daddr;
	qp->user = arg->user;
	qp->peer = sysctl_ipfrag_max_dist ?
		inet_getpeer_v4(net->ipv4.peers, arg->iph->saddr, 1) : NULL;
}

static __inline__ void ip4_frag_free(struct inet_frag_queue *q)
{
	struct ipq *qp;

	qp = container_of(q, struct ipq, q);
	if (qp->peer)
		inet_putpeer(qp->peer);
}

/* Destruction primitives. */

static __inline__ void ipq_put(struct ipq *ipq)
{
	inet_frag_put(&ipq->q, &ip4_frags);
}

/* Kill ipq entry. It is not destroyed immediately,
 * because caller (and someone more) holds reference count.
 */
static void ipq_kill(struct ipq *ipq)
{
	inet_frag_kill(&ipq->q, &ip4_frags);
}

/* Memory limiting on fragments.  Evictor trashes the oldest
 * fragment queue until we are back under the threshold.
 */
static void ip_evictor(struct net *net)
{
	int evicted;

	evicted = inet_frag_evictor(&net->ipv4.frags, &ip4_frags, false);
	if (evicted)
		IP_ADD_STATS_BH(net, IPSTATS_MIB_REASMFAILS, evicted);
}

/*
 * Oops, a fragment queue timed out.  Kill it and send an ICMP reply.
 */
static void ip_expire(unsigned long arg)
{
	struct ipq *qp;
	struct net *net;

	qp = container_of((struct inet_frag_queue *) arg, struct ipq, q);
	net = container_of(qp->q.net, struct net, ipv4.frags);

	spin_lock(&qp->q.lock);

	if (qp->q.last_in & INET_FRAG_COMPLETE)
		goto out;

	ipq_kill(qp);

	IP_INC_STATS_BH(net, IPSTATS_MIB_REASMTIMEOUT);
	IP_INC_STATS_BH(net, IPSTATS_MIB_REASMFAILS);

	if ((qp->q.last_in & INET_FRAG_FIRST_IN) && qp->q.fragments != NULL) {
		struct sk_buff *head = qp->q.fragments;
		const struct iphdr *iph;
		int err;

		rcu_read_lock();
		head->dev = dev_get_by_index_rcu(net, qp->iif);
		if (!head->dev)
			goto out_rcu_unlock;

		/* skb has no dst, perform route lookup again */
		iph = ip_hdr(head);
		err = ip_route_input_noref(head, iph->daddr, iph->saddr,
					   iph->tos, head->dev);
		if (err)
			goto out_rcu_unlock;

		/*
		 * Only an end host needs to send an ICMP
		 * "Fragment Reassembly Timeout" message, per RFC792.
		 */
		if (qp->user == IP_DEFRAG_AF_PACKET ||
		    (qp->user == IP_DEFRAG_CONNTRACK_IN &&
		     skb_rtable(head)->rt_type != RTN_LOCAL))
			goto out_rcu_unlock;

		/* Send an ICMP "Fragment Reassembly Timeout" message. */
		icmp_send(head, ICMP_TIME_EXCEEDED, ICMP_EXC_FRAGTIME, 0);
out_rcu_unlock:
		rcu_read_unlock();
	}
out:
	spin_unlock(&qp->q.lock);
	ipq_put(qp);
}

/* Find the correct entry in the "incomplete datagrams" queue for
 * this IP datagram, and create new one, if nothing is found.
 */
static inline struct ipq *ip_find(struct net *net, struct iphdr *iph, u32 user)
{
	struct inet_frag_queue *q;
	struct ip4_create_arg arg;
	unsigned int hash;

	arg.iph = iph;
	arg.user = user;

	read_lock(&ip4_frags.lock);
	hash = ipqhashfn(iph->id, iph->saddr, iph->daddr, iph->protocol);

	q = inet_frag_find(&net->ipv4.frags, &ip4_frags, &arg, hash);
	if (IS_ERR_OR_NULL(q)) {
		inet_frag_maybe_warn_overflow(q, pr_fmt());
		return NULL;
	}
	return container_of(q, struct ipq, q);
}

/* Is the fragment too far ahead to be part of ipq? */
static inline int ip_frag_too_far(struct ipq *qp)
{
	struct inet_peer *peer = qp->peer;
	unsigned int max = sysctl_ipfrag_max_dist;
	unsigned int start, end;

	int rc;

	if (!peer || !max)
		return 0;

	start = qp->rid;
	end = atomic_inc_return(&peer->rid);
	qp->rid = end;

	rc = qp->q.fragments && (end - start) > max;

	if (rc) {
		struct net *net;

		net = container_of(qp->q.net, struct net, ipv4.frags);
		IP_INC_STATS_BH(net, IPSTATS_MIB_REASMFAILS);
	}

	return rc;
}

static int ip_frag_reinit(struct ipq *qp)
{
	struct sk_buff *fp;
	unsigned int sum_truesize = 0;

	if (!mod_timer(&qp->q.timer, jiffies + qp->q.net->timeout)) {
		atomic_inc(&qp->q.refcnt);
		return -ETIMEDOUT;
	}

	fp = qp->q.fragments;
	do {
		struct sk_buff *xp = fp->next;

		sum_truesize += fp->truesize;
		kfree_skb(fp);
		fp = xp;
	} while (fp);
	sub_frag_mem_limit(&qp->q, sum_truesize);

	qp->q.last_in = 0;
	qp->q.len = 0;
	qp->q.meat = 0;
	qp->q.fragments = NULL;
	qp->q.fragments_tail = NULL;
	qp->iif = 0;
	qp->ecn = 0;

	return 0;
}

/* Add new segment to existing queue. */
static int ip_frag_queue(struct ipq *qp, struct sk_buff *skb)
{
	struct sk_buff *prev, *next;
	struct net_device *dev;
	int flags, offset;
	int ihl, end;
	int err = -ENOENT;
	u8 ecn;

	if (qp->q.last_in & INET_FRAG_COMPLETE)
		goto err;

	if (!(IPCB(skb)->flags & IPSKB_FRAG_COMPLETE) &&
	    unlikely(ip_frag_too_far(qp)) &&
	    unlikely(err = ip_frag_reinit(qp))) {
		ipq_kill(qp);
		goto err;
	}

	ecn = ip4_frag_ecn(ip_hdr(skb)->tos);
	offset = ntohs(ip_hdr(skb)->frag_off);
	flags = offset & ~IP_OFFSET;
	offset &= IP_OFFSET;
	offset <<= 3;		/* offset is in 8-byte chunks */
	ihl = ip_hdrlen(skb);

	/* Determine the position of this fragment. */
	end = offset + skb->len - ihl;
	err = -EINVAL;

	/* Is this the final fragment? */
	if ((flags & IP_MF) == 0) {
		/* If we already have some bits beyond end
		 * or have different end, the segment is corrupted.
		 */
		if (end < qp->q.len ||
		    ((qp->q.last_in & INET_FRAG_LAST_IN) && end != qp->q.len))
			goto err;
		qp->q.last_in |= INET_FRAG_LAST_IN;
		qp->q.len = end;
	} else {
		if (end&7) {
			end &= ~7;
			if (skb->ip_summed != CHECKSUM_UNNECESSARY)
				skb->ip_summed = CHECKSUM_NONE;
		}
		if (end > qp->q.len) {
			/* Some bits beyond end -> corruption. */
			if (qp->q.last_in & INET_FRAG_LAST_IN)
				goto err;
			qp->q.len = end;
		}
	}
	if (end == offset)
		goto err;

	err = -ENOMEM;
	if (pskb_pull(skb, ihl) == NULL)
		goto err;

	err = pskb_trim_rcsum(skb, end - offset);
	if (err)
		goto err;

	/* Find out which fragments are in front and at the back of us
	 * in the chain of fragments so far.  We must know where to put
	 * this fragment, right?
	 */
	prev = qp->q.fragments_tail;
	if (!prev || FRAG_CB(prev)->offset < offset) {
		next = NULL;
		goto found;
	}
	prev = NULL;
	for (next = qp->q.fragments; next != NULL; next = next->next) {
		if (FRAG_CB(next)->offset >= offset)
			break;	/* bingo! */
		prev = next;
	}

found:
	/* We found where to put this one.  Check for overlap with
	 * preceding fragment, and, if needed, align things so that
	 * any overlaps are eliminated.
	 */
	if (prev) {
		int i = (FRAG_CB(prev)->offset + prev->len) - offset;

		if (i > 0) {
			offset += i;
			err = -EINVAL;
			if (end <= offset)
				goto err;
			err = -ENOMEM;
			if (!pskb_pull(skb, i))
				goto err;
			if (skb->ip_summed != CHECKSUM_UNNECESSARY)
				skb->ip_summed = CHECKSUM_NONE;
		}
	}

	err = -ENOMEM;

	while (next && FRAG_CB(next)->offset < end) {
		int i = end - FRAG_CB(next)->offset; /* overlap is 'i' bytes */

		if (i < next->len) {
			/* Eat head of the next overlapped fragment
			 * and leave the loop. The next ones cannot overlap.
			 */
			if (!pskb_pull(next, i))
				goto err;
			FRAG_CB(next)->offset += i;
			qp->q.meat -= i;
			if (next->ip_summed != CHECKSUM_UNNECESSARY)
				next->ip_summed = CHECKSUM_NONE;
			break;
		} else {
			struct sk_buff *free_it = next;

			/* Old fragment is completely overridden with
			 * new one drop it.
			 */
			next = next->next;

			if (prev)
				prev->next = next;
			else
				qp->q.fragments = next;

			qp->q.meat -= free_it->len;
			sub_frag_mem_limit(&qp->q, free_it->truesize);
			kfree_skb(free_it);
		}
	}

	FRAG_CB(skb)->offset = offset;

	/* Insert this fragment in the chain of fragments. */
	skb->next = next;
	if (!next)
		qp->q.fragments_tail = skb;
	if (prev)
		prev->next = skb;
	else
		qp->q.fragments = skb;

	dev = skb->dev;
	if (dev) {
		qp->iif = dev->ifindex;
		skb->dev = NULL;
	}
	qp->q.stamp = skb->tstamp;
	qp->q.meat += skb->len;
	qp->ecn |= ecn;
	add_frag_mem_limit(&qp->q, skb->truesize);
	if (offset == 0)
		qp->q.last_in |= INET_FRAG_FIRST_IN;

	if (ip_hdr(skb)->frag_off & htons(IP_DF) &&
	    skb->len + ihl > qp->q.max_size)
		qp->q.max_size = skb->len + ihl;

	if (qp->q.last_in == (INET_FRAG_FIRST_IN | INET_FRAG_LAST_IN) &&
	    qp->q.meat == qp->q.len) {
		unsigned long orefdst = skb->_skb_refdst;

		skb->_skb_refdst = 0UL;
		err = ip_frag_reasm(qp, prev, dev);
		skb->_skb_refdst = orefdst;
		return err;
	}

	skb_dst_drop(skb);
	inet_frag_lru_move(&qp->q);
	return -EINPROGRESS;

err:
	kfree_skb(skb);
	return err;
}

/* Build a new IP datagram from all its fragments. */

static int ip_frag_reasm(struct ipq *qp, struct sk_buff *prev,
			 struct net_device *dev)
{
	struct net *net = container_of(qp->q.net, struct net, ipv4.frags);
	struct iphdr *iph;
	struct sk_buff *fp, *head = qp->q.fragments;
	int len;
	int ihlen;
	int err;
	int sum_truesize;
	u8 ecn;

	ipq_kill(qp);

	ecn = ip_frag_ecn_table[qp->ecn];
	if (unlikely(ecn == 0xff)) {
		err = -EINVAL;
		goto out_fail;
	}
	/* Make the one we just received the head. */
	if (prev) {
		head = prev->next;
		fp = skb_clone(head, GFP_ATOMIC);
		if (!fp)
			goto out_nomem;

		fp->next = head->next;
		if (!fp->next)
			qp->q.fragments_tail = fp;
		prev->next = fp;

		skb_morph(head, qp->q.fragments);
		head->next = qp->q.fragments->next;

		consume_skb(qp->q.fragments);
		qp->q.fragments = head;
	}

	WARN_ON(head == NULL);
	WARN_ON(FRAG_CB(head)->offset != 0);

	/* Allocate a new buffer for the datagram. */
	ihlen = ip_hdrlen(head);
	len = ihlen + qp->q.len;

	err = -E2BIG;
	if (len > 65535)
		goto out_oversize;

	/* Head of list must not be cloned. */
	if (skb_unclone(head, GFP_ATOMIC))
		goto out_nomem;

	/* If the first fragment is fragmented itself, we split
	 * it to two chunks: the first with data and paged part
	 * and the second, holding only fragments. */
	if (skb_has_frag_list(head)) {
		struct sk_buff *clone;
		int i, plen = 0;

		if ((clone = alloc_skb(0, GFP_ATOMIC)) == NULL)
			goto out_nomem;
		clone->next = head->next;
		head->next = clone;
		skb_shinfo(clone)->frag_list = skb_shinfo(head)->frag_list;
		skb_frag_list_init(head);
		for (i = 0; i < skb_shinfo(head)->nr_frags; i++)
			plen += skb_frag_size(&skb_shinfo(head)->frags[i]);
		clone->len = clone->data_len = head->data_len - plen;
		head->data_len -= clone->len;
		head->len -= clone->len;
		clone->csum = 0;
		clone->ip_summed = head->ip_summed;
		add_frag_mem_limit(&qp->q, clone->truesize);
	}

	skb_push(head, head->data - skb_network_header(head));

	sum_truesize = head->truesize;
	for (fp = head->next; fp;) {
		bool headstolen;
		int delta;
		struct sk_buff *next = fp->next;

		sum_truesize += fp->truesize;
		if (head->ip_summed != fp->ip_summed)
			head->ip_summed = CHECKSUM_NONE;
		else if (head->ip_summed == CHECKSUM_COMPLETE)
			head->csum = csum_add(head->csum, fp->csum);

		if (skb_try_coalesce(head, fp, &headstolen, &delta)) {
			kfree_skb_partial(fp, headstolen);
		} else {
			if (!skb_shinfo(head)->frag_list)
				skb_shinfo(head)->frag_list = fp;
			head->data_len += fp->len;
			head->len += fp->len;
			head->truesize += fp->truesize;
		}
		fp = next;
	}
	sub_frag_mem_limit(&qp->q, sum_truesize);

	head->next = NULL;
	head->dev = dev;
	head->tstamp = qp->q.stamp;
	IPCB(head)->frag_max_size = qp->q.max_size;

	iph = ip_hdr(head);
	/* max_size != 0 implies at least one fragment had IP_DF set */
	iph->frag_off = qp->q.max_size ? htons(IP_DF) : 0;
	iph->tot_len = htons(len);
	iph->tos |= ecn;
	IP_INC_STATS_BH(net, IPSTATS_MIB_REASMOKS);
	qp->q.fragments = NULL;
	qp->q.fragments_tail = NULL;
	return 0;

out_nomem:
	LIMIT_NETDEBUG(KERN_ERR pr_fmt("queue_glue: no memory for gluing queue %p\n"),
		       qp);
	err = -ENOMEM;
	goto out_fail;
out_oversize:
	net_info_ratelimited("Oversized IP packet from %pI4\n", &qp->saddr);
out_fail:
	IP_INC_STATS_BH(net, IPSTATS_MIB_REASMFAILS);
	return err;
}

/* Process an incoming IP datagram fragment. */
int ip_defrag(struct sk_buff *skb, u32 user)
{
	struct ipq *qp;
	struct net *net;

	net = skb->dev ? dev_net(skb->dev) : dev_net(skb_dst(skb)->dev);
	IP_INC_STATS_BH(net, IPSTATS_MIB_REASMREQDS);

	/* Start by cleaning up the memory. */
	ip_evictor(net);

	/* Lookup (or create) queue header */
	if ((qp = ip_find(net, ip_hdr(skb), user)) != NULL) {
		int ret;

		spin_lock(&qp->q.lock);

		ret = ip_frag_queue(qp, skb);

		spin_unlock(&qp->q.lock);
		ipq_put(qp);
		return ret;
	}

	IP_INC_STATS_BH(net, IPSTATS_MIB_REASMFAILS);
	kfree_skb(skb);
	return -ENOMEM;
}
EXPORT_SYMBOL(ip_defrag);

struct sk_buff *ip_check_defrag(struct sk_buff *skb, u32 user)
{
	struct iphdr iph;
	u32 len;

	if (skb->protocol != htons(ETH_P_IP))
		return skb;

	if (!skb_copy_bits(skb, 0, &iph, sizeof(iph)))
		return skb;

	if (iph.ihl < 5 || iph.version != 4)
		return skb;

	len = ntohs(iph.tot_len);
	if (skb->len < len || len < (iph.ihl * 4))
		return skb;

	if (ip_is_fragment(&iph)) {
		skb = skb_share_check(skb, GFP_ATOMIC);
		if (skb) {
			if (!pskb_may_pull(skb, iph.ihl*4))
				return skb;
			if (pskb_trim_rcsum(skb, len))
				return skb;
			memset(IPCB(skb), 0, sizeof(struct inet_skb_parm));
			if (ip_defrag(skb, user))
				return NULL;
			skb_clear_hash(skb);
		}
	}
	return skb;
}
EXPORT_SYMBOL(ip_check_defrag);

#ifdef CONFIG_SYSCTL
static int zero;

static struct ctl_table ip4_frags_ns_ctl_table[] = {
	{
		.procname	= "ipfrag_high_thresh",
		.data		= &init_net.ipv4.frags.high_thresh,
		.maxlen		= sizeof(int),
		.mode		= 0644,
		.proc_handler	= proc_dointvec
	},
	{
		.procname	= "ipfrag_low_thresh",
		.data		= &init_net.ipv4.frags.low_thresh,
		.maxlen		= sizeof(int),
		.mode		= 0644,
		.proc_handler	= proc_dointvec
	},
	{
		.procname	= "ipfrag_time",
		.data		= &init_net.ipv4.frags.timeout,
		.maxlen		= sizeof(int),
		.mode		= 0644,
		.proc_handler	= proc_dointvec_jiffies,
	},
	{ }
};

static struct ctl_table ip4_frags_ctl_table[] = {
	{
		.procname	= "ipfrag_secret_interval",
		.data		= &ip4_frags.secret_interval,
		.maxlen		= sizeof(int),
		.mode		= 0644,
		.proc_handler	= proc_dointvec_jiffies,
	},
	{
		.procname	= "ipfrag_max_dist",
		.data		= &sysctl_ipfrag_max_dist,
		.maxlen		= sizeof(int),
		.mode		= 0644,
		.proc_handler	= proc_dointvec_minmax,
		.extra1		= &zero
	},
	{ }
};

static int __net_init ip4_frags_ns_ctl_register(struct net *net)
{
	struct ctl_table *table;
	struct ctl_table_header *hdr;

	table = ip4_frags_ns_ctl_table;
	if (!net_eq(net, &init_net)) {
		table = kmemdup(table, sizeof(ip4_frags_ns_ctl_table), GFP_KERNEL);
		if (table == NULL)
			goto err_alloc;

		table[0].data = &net->ipv4.frags.high_thresh;
		table[1].data = &net->ipv4.frags.low_thresh;
		table[2].data = &net->ipv4.frags.timeout;

		/* Don't export sysctls to unprivileged users */
		if (net->user_ns != &init_user_ns)
			table[0].procname = NULL;
	}

	hdr = register_net_sysctl(net, "net/ipv4", table);
	if (hdr == NULL)
		goto err_reg;

	net->ipv4.frags_hdr = hdr;
	return 0;

err_reg:
	if (!net_eq(net, &init_net))
		kfree(table);
err_alloc:
	return -ENOMEM;
}

static void __net_exit ip4_frags_ns_ctl_unregister(struct net *net)
{
	struct ctl_table *table;

	table = net->ipv4.frags_hdr->ctl_table_arg;
	unregister_net_sysctl_table(net->ipv4.frags_hdr);
	kfree(table);
}

static void ip4_frags_ctl_register(void)
{
	register_net_sysctl(&init_net, "net/ipv4", ip4_frags_ctl_table);
}
#else
static inline int ip4_frags_ns_ctl_register(struct net *net)
{
	return 0;
}

static inline void ip4_frags_ns_ctl_unregister(struct net *net)
{
}

static inline void ip4_frags_ctl_register(void)
{
}
#endif

static int __net_init ipv4_frags_init_net(struct net *net)
{
	/* Fragment cache limits.
	 *
	 * The fragment memory accounting code, (tries to) account for
	 * the real memory usage, by measuring both the size of frag
	 * queue struct (inet_frag_queue (ipv4:ipq/ipv6:frag_queue))
	 * and the SKB's truesize.
	 *
	 * A 64K fragment consumes 129736 bytes (44*2944)+200
	 * (1500 truesize == 2944, sizeof(struct ipq) == 200)
	 *
	 * We will commit 4MB at one time. Should we cross that limit
	 * we will prune down to 3MB, making room for approx 8 big 64K
	 * fragments 8x128k.
	 */
	net->ipv4.frags.high_thresh = 4 * 1024 * 1024;
	net->ipv4.frags.low_thresh  = 3 * 1024 * 1024;
	/*
	 * Important NOTE! Fragment queue must be destroyed before MSL expires.
	 * RFC791 is wrong proposing to prolongate timer each fragment arrival
	 * by TTL.
	 */
	net->ipv4.frags.timeout = IP_FRAG_TIME;

	inet_frags_init_net(&net->ipv4.frags);

	return ip4_frags_ns_ctl_register(net);
}

static void __net_exit ipv4_frags_exit_net(struct net *net)
{
	ip4_frags_ns_ctl_unregister(net);
	inet_frags_exit_net(&net->ipv4.frags, &ip4_frags);
}

static struct pernet_operations ip4_frags_ops = {
	.init = ipv4_frags_init_net,
	.exit = ipv4_frags_exit_net,
};

void __init ipfrag_init(void)
{
	ip4_frags_ctl_register();
	register_pernet_subsys(&ip4_frags_ops);
	ip4_frags.hashfn = ip4_hashfn;
	ip4_frags.constructor = ip4_frag_init;
	ip4_frags.destructor = ip4_frag_free;
	ip4_frags.skb_free = NULL;
	ip4_frags.qsize = sizeof(struct ipq);
	ip4_frags.match = ip4_frag_match;
	ip4_frags.frag_expire = ip_expire;
	ip4_frags.secret_interval = 10 * 60 * HZ;
	inet_frags_init(&ip4_frags);
}


text:
//
//  TSMessageView.m
//  Toursprung
//
//  Created by Felix Krause on 24.08.12.
//  Copyright (c) 2012 Toursprung. All rights reserved.
//

#import "TSMessageView.h"
#import "UIColor+MLColorAdditions.h"

#define TSMessageViewPadding 15.0

#define TSDesignFileName @"design.json"

static NSDictionary *notificationDesign;

@interface TSMessageView ()

@property (nonatomic, strong) NSString *title;
@property (nonatomic, strong) NSString *content;
@property (nonatomic, strong) UIViewController *viewController;

/** Internal properties needed to resize the view on device rotation properly */
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UILabel *contentLabel;
@property (nonatomic, strong) UIImageView *iconImageView;
@property (nonatomic, strong) UIView *borderView;
@property (nonatomic, strong) UIImageView *backgroundImageView;

@property (nonatomic, assign) CGFloat textSpaceLeft;

@property (copy) void (^callback)();

- (CGFloat)updateHeightOfMessageView;
- (void)layoutSubviews;

@end

@implementation TSMessageView

- (id)initWithTitle:(NSString *)title
        withContent:(NSString *)content
           withType:(TSMessageNotificationType)notificationType
       withDuration:(CGFloat)duration
   inViewController:(UIViewController *)viewController
       withCallback:(void (^)())callback
{
    if (!notificationDesign)
    {
        NSString *path = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:TSDesignFileName];
        notificationDesign = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:path]
                                                             options:kNilOptions
                                                               error:nil];
    }

    if ((self = [self init]))
    {
        _title = title;
        _content = content;
        _duration = duration;
        _viewController = viewController;
        self.callback = callback;

        CGFloat screenWidth = self.viewController.view.frame.size.width;
        NSDictionary *current;
        NSString *currentString;
        switch (notificationType)
        {
            case TSMessageNotificationTypeMessage:
            {
                currentString = @"message";
                break;
            }
            case TSMessageNotificationTypeError:
            {
                currentString = @"error";
                break;
            }
            case TSMessageNotificationTypeSuccess:
            {
                currentString = @"success";
                break;
            }
            case TSMessageNotificationTypeWarning:
            {
                currentString = @"warning";
                break;
            }

            default:
                break;
        }

        current = [notificationDesign valueForKey:currentString];

        self.alpha = 0.0;

        UIImage *image;
        if ([current valueForKey:@"imageName"])
        {
            image = [UIImage imageNamed:[current valueForKey:@"imageName"]];
        }

        // add background image here
        UIImage *backgroundImage = [[UIImage imageNamed:[current valueForKey:@"backgroundImageName"]] stretchableImageWithLeftCapWidth:0.0 topCapHeight:0.0];
        _backgroundImageView = [[UIImageView alloc] initWithImage:backgroundImage];
        self.backgroundImageView.autoresizingMask = (UIViewAutoresizingFlexibleWidth);
        [self addSubview:self.backgroundImageView];

        UIColor *fontColor = [UIColor colorWithHexString:[current valueForKey:@"textColor"]
                                                   alpha:1.0];

        self.textSpaceLeft = 2 * TSMessageViewPadding;
        if (image) self.textSpaceLeft += image.size.width + 2 * TSMessageViewPadding;

        // Set up title label
        _titleLabel = [[UILabel alloc] init];
        [self.titleLabel setText:title];
        [self.titleLabel setTextColor:fontColor];
        [self.titleLabel setBackgroundColor:[UIColor clearColor]];
        [self.titleLabel setFont:[UIFont boldSystemFontOfSize:[[current valueForKey:@"titleFontSize"] floatValue]]];
        [self.titleLabel setShadowColor:[UIColor colorWithHexString:[current valueForKey:@"shadowColor"] alpha:1.0]];
        [self.titleLabel setShadowOffset:CGSizeMake([[current valueForKey:@"shadowOffsetX"] floatValue],
                                                    [[current valueForKey:@"shadowOffsetY"] floatValue])];
        self.titleLabel.numberOfLines = 0;
        self.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
        [self addSubview:self.titleLabel];

        // Set up content label (if set)
        if ([content length])
        {
            _contentLabel = [[UILabel alloc] init];
            [self.contentLabel setText:content];
            [self.contentLabel setTextColor:fontColor];
            [self.contentLabel setBackgroundColor:[UIColor clearColor]];
            [self.contentLabel setFont:[UIFont systemFontOfSize:[[current valueForKey:@"contentFontSize"] floatValue]]];
            [self.contentLabel setShadowColor:self.titleLabel.shadowColor];
            [self.contentLabel setShadowOffset:self.titleLabel.shadowOffset];
            self.contentLabel.lineBreakMode = self.titleLabel.lineBreakMode;
            self.contentLabel.numberOfLines = 0;

            [self addSubview:self.contentLabel];
        }

        if (image)
        {
            _iconImageView = [[UIImageView alloc] initWithImage:image];
            self.iconImageView.frame = CGRectMake(TSMessageViewPadding * 2,
                                                  TSMessageViewPadding,
                                                  image.size.width,
                                                  image.size.height);
            [self addSubview:self.iconImageView];
        }

        // Add a border on the bottom
        _borderView = [[UIView alloc] initWithFrame:CGRectMake(0.0,
                                                               0.0, // will be set later
                                                               screenWidth,
                                                               [[current valueForKey:@"borderHeight"] floatValue])];
        self.borderView.backgroundColor = [UIColor colorWithHexString:[current valueForKey:@"borderColor"]
                                                           alpha:1.0];
        self.borderView.autoresizingMask = (UIViewAutoresizingFlexibleWidth);
        [self addSubview:self.borderView];

        CGFloat actualHeight = [self updateHeightOfMessageView]; // this call also takes care of positioning the labels
        self.frame = CGRectMake(0.0, -actualHeight, screenWidth, actualHeight);
        self.autoresizingMask = (UIViewAutoresizingFlexibleWidth);

        UISwipeGestureRecognizer *gestureRec = [[UISwipeGestureRecognizer alloc] initWithTarget:self
                                                                                action:@selector(fadeMeOut)];
        [gestureRec setDirection:UISwipeGestureRecognizerDirectionUp];
        [self addGestureRecognizer:gestureRec];

        UITapGestureRecognizer *tapRec = [[UITapGestureRecognizer alloc] initWithTarget:self
                                                                                action:@selector(fadeMeOut)];
        [self addGestureRecognizer:tapRec];
    }
    return self;
}

- (CGFloat)updateHeightOfMessageView
{
    CGFloat currentHeight;
    CGFloat screenWidth = self.viewController.view.frame.size.width;

    self.titleLabel.frame = CGRectMake(self.textSpaceLeft,
                                       TSMessageViewPadding,
                                       screenWidth - TSMessageViewPadding - self.textSpaceLeft,
                                       0.0);
    [self.titleLabel sizeToFit];

    if ([self.content length])
    {
        self.contentLabel.frame = CGRectMake(self.textSpaceLeft,
                                             self.titleLabel.frame.origin.y + self.titleLabel.frame.size.height + 5.0,
                                             screenWidth - TSMessageViewPadding - self.textSpaceLeft,
                                             0.0);
        [self.contentLabel sizeToFit];

        currentHeight = self.contentLabel.frame.origin.y + self.contentLabel.frame.size.height;
    }
    else
    {
        // only the title was set
        currentHeight = self.titleLabel.frame.origin.y + self.titleLabel.frame.size.height;
    }

    currentHeight += TSMessageViewPadding;

    if (self.iconImageView)
    {
        // Check if that makes the popup larger (height)
        if (self.iconImageView.frame.origin.y + self.iconImageView.frame.size.height + TSMessageViewPadding > currentHeight)
        {
            currentHeight = self.iconImageView.frame.origin.y + self.iconImageView.frame.size.height;
        }
        else
        {
            // z-align
            self.iconImageView.center = CGPointMake([self.iconImageView center].x,
                                                    round(currentHeight / 2.0));
        }
    }

    // Correct the border position
    CGRect borderFrame = self.borderView.frame;
    borderFrame.origin.y = currentHeight;
    self.borderView.frame = borderFrame;

    currentHeight += self.borderView.frame.size.height;

    self.frame = CGRectMake(0.0, self.frame.origin.y, self.frame.size.width, currentHeight);

    self.backgroundImageView.frame = CGRectMake(self.backgroundImageView.frame.origin.x,
                                                self.backgroundImageView.frame.origin.y,
                                                screenWidth,
                                                currentHeight);

    return currentHeight;
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    [self updateHeightOfMessageView];
}

- (void)fadeMeOut
{
    // user tapped on the message
    dispatch_async(dispatch_get_main_queue(), ^
    {
        if (self.callback)
        {
            self.callback();
        }

        [[TSMessage sharedMessage] performSelector:@selector(fadeOutNotification:)
                                        withObject:self];
    });
}

@end

redpajama_set_name: RedPajamaGithub


text:
def wait_until_interactive(self, timeout=None):
    """
    Wait until page object is interactive.

    :param int timeout: number of seconds to wait, if not provided
        PageObject.DEFAULT_WAIT_TIMEOUT is used
    """
    if timeout is None:
        timeout = self.DEFAULT_WAIT_TIMEOUT

    self.logger.info(('waiting until page object {} is interactive'
        ).format(self._log_id_short))
    self.logger.debug(('waiting until page object is interactive; {}'
        ).format(self._log_id_long))

    error_msg = ('page object still not interactive after {} seconds; {}'
        ).format(timeout, self._log_id_long)

    self.wait_until(self.is_interactive, func_kwargs=dict(log=False),
        timeout=timeout, error_msg=error_msg)

    self.logger.info(('finished waiting until page object {} is interactive'
        ).format(self._log_id_short))
    self.logger.info(('finished waiting until page object is interactive; {}'
        ).format(self._log_id_long))

    return self


text:
import React from 'react'

import Icon from '../Icon'
import * as helpers from '../../helpers'

export default class EditPlaylistModal extends React.Component{

	constructor(props){
		super(props)
		this.state = {
			submit_enabled: true,
			name: this.props.data.name,
			is_public: this.props.data.is_public
		}
	}

	setPlaylistName(name){
		var submit_enabled = false
		if( name && name != '' ) submit_enabled = true
		this.setState({
			name: name,
			submit_enabled: submit_enabled
		})
	}

	savePlaylist(e){
		e.preventDefault();
		this.props.uiActions.savePlaylist(this.props.data.uri, this.state.name, this.state.is_public)
		this.props.uiActions.closeModal()
		return false;
	}

	render(){
		return (

Edit playlist

				<form onSubmit={(e) => this.savePlaylist(e)}>

						<input
							type="text"
							placeholder="Playlist name"
							onChange={ e => this.setPlaylistName( e.target.value )}
							value={ this.state.name } />

							<input
								type="checkbox"
								name="playlist_private"
								checked={ this.state.is_public }
								onChange={ e => this.setState({ is_public: !this.state.is_public })} />
							Public

						<button type="submit" className="primary wide" disabled={!this.state.submit_enabled}>Save</button>

				</form>

		)
	}
}


text:
import { Component } from '@angular/core';
import { ConfigService } from './service/config.service';

@Component({
  selector: 'my-app',
  templateUrl: "app/template/app.html",
})
export class AppComponent  {
  gameName = '';

  public constructor(config: ConfigService){
    config.load().then(response => {
      this.gameName = config.get("title");
    });
  }

  ngAfterViewInit(){
    $(".preloader-wrapper").hide();
  }
}


text:
<?php
namespace Api\Station\Specification;

use \ComPHPPuebla\Doctrine\TableGateway\Specification\QueryBuilderSpecification;
use \Doctrine\DBAL\Query\QueryBuilder;

class GeolocationSpecification extends QueryBuilderSpecification
{
    /**
     * @see \ComPHPPuebla\Doctrine\TableGateway\Specification\QueryBuilderSpecification::match()
     */
    public function match(QueryBuilder $qb)
    {
        if ($this->has('latitude') && $this->has('longitude')) {

            $qb->addSelect(<<<SELECT
    (6371
    * (2 * ATAN(SQRT(SIN(((:latitude - s.latitude) * (PI()/180))/2) * SIN(((:latitude - s.latitude) * (PI()/180))/2)
    + COS(:latitude * (PI()/180)) * COS(s.latitude * (PI()/180))
    * SIN(((:longitude - s.longitude) * (PI()/180))/2) * SIN(((:longitude - s.longitude) * (PI()/180))/2)),
            SQRT(1-(sin(((:latitude - s.latitude) * (PI()/180))/2) * SIN(((:latitude - s.latitude) * (PI()/180))/2)
    + COS(:latitude * (PI()/180) * COS(s.latitude * (PI()/180)
    * SIN(((:longitude - s.longitude) * (PI()/180))/2) * SIN(((:longitude - s.longitude) * (PI()/180))/2))))))))
    AS distance
SELECT
            );
            $qb->orderBy('distance');
            $qb->setParameter('latitude', $this->get('latitude'));
            $qb->setParameter('longitude', $this->get('longitude'));
       }
    }
}


text:
package com.ftfl.icareapplication;

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

import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;

import com.ftfl.icareapplication.adapter.ActivityCustomAdapter;
import com.ftfl.icareapplication.database.ICareActivityDataSource;
import com.ftfl.icareapplication.utill.ICareActivityChart;

public class ICareDietChartListActivity extends Activity {
	ListView mActivityListView = null;
	ICareActivityChart mActivityChart = null;
	List<ICareActivityChart> mActivityList = new ArrayList<ICareActivityChart>();
	public ArrayList<ICareActivityChart> mActivitiesList = new ArrayList<ICareActivityChart>();
	ActivityCustomAdapter activityAdapter;
	ICareDietChartListActivity mActivityCustomAdapter = null;
	TextView mTvId = null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_icare_diet_chart_list);
		mActivityCustomAdapter = this;
		/******** Take some data in Arraylist ( CustomListViewValuesArr ) ***********/
		setActivityListData();
		Resources activityResource = getResources();
		mActivityListView = (ListView) findViewById(R.id.iCareCustomActivityList);

		activityAdapter = new ActivityCustomAdapter(mActivityCustomAdapter,
				mActivitiesList, activityResource);
		mActivityListView.setAdapter(activityAdapter);

		// OnCLickListiner For List Items
		mActivityListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent,
					android.view.View view, int position, long id) {

				mTvId = (TextView) view.findViewById(R.id.db_activity_id);
				String activityIdValue = mTvId.getText().toString(); // get id
																		// from
																		// text
				/*
				 * create an intent and send data
				 */
				Intent mPreviewIntent = new Intent(getApplicationContext(),
						ICareDietChartPreviewActivity.class);
				mPreviewIntent.putExtra("activityId", activityIdValue);
				startActivity(mPreviewIntent);
			}
		});
	}

	@Override
	public void onResume() {
		super.onResume();
		mActivitiesList.clear();// clear the object list
		setActivityListData(); // set updated object list
		activityAdapter.notifyDataSetChanged(); // if any change occour to the
												// adapter adapter will load
												// with new data.
	}

	public void setActivityListData() {
		ICareActivityDataSource activityData = new ICareActivityDataSource(this);
		mActivityList = activityData.iCareActivityList();
		for (int i = 0; i < mActivityList.size(); i++) {
			ICareActivityChart mActivity = mActivityList.get(i);
			mActivitiesList.add(mActivity);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.icare_diet_chart_list, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
}


text:
///////////////////////////////////////////////////////////////////////////
// Copyright © Esri. All Rights Reserved.
//
// 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.
///////////////////////////////////////////////////////////////////////////

define([
  "dojo/_base/declare",
  "dijit/form/ValidationTextBox",
  "./Coordinate"
], function (
  dojoDeclare,
  dijitValidationTextBox,
  Coord
) {
  var mo = dojoDeclare("test", dijitValidationTextBox, {
    required: true,

    inputCoordinate: null,

    invalidMessage: "Blah Blah Blah",

    validateOnInput: true,
    _validateOnInputSetter: function (value) {
        this.validateOnInput = (value === "true");
    },

    clear: function () {
      this.set("validateOnInput", true);
      this.set("value", "");
      this.inputCoordinate.coordinateEsriGeometry = null;
    },
    /**
     *
     **/
    constructor: function (args) {
        dojoDeclare.safeMixin(this, args);
        this.inherited(arguments);
        this.inputCoordinate = new Coord({nls: this.nls, appConfig: arguments[0].appConfig});
    },

    postMixinProperties: function () {
    },

    /**
     *
     **/
    validator: function (value) {

      if (!this.validateOnInput) {
        return true;
      }
      //if (this.get('value').length < 4) return false;

      this.inputCoordinate.set("inputString", value);

      //this.inputCoordinate.set('formatString', 'YN XE');

      this.set("invalidMessage", this.inputCoordinate.message);
      this.set("promptMessage", this.inputCoordinate.message);

      return true;
    }
  });

  return mo;
});


text:
<?php

namespace KZ\grid\interfaces;

/**
 * Interface Pager
 * @package KZ\interfaces
 */
interface Pager
{
	/**
	 * @param int $itemCount
	 */
	public function __construct($itemCount);

	/**
	 * @return int
	 */
	public function getItemCount();

	/**
	 * Set number of items per page.
	 *
	 * @param int $pageSize
	 * @return $this
	 */
	public function setPageSize($pageSize);

	/**
	 * Get number of items per page.
	 *
	 * @return int
	 */
	public function getPageSize();

	/**
	 * Return current page.
	 *
	 * @return int
	 */
	public function getCurrentPage();

	/**
	 * Set current page.
	 *
	 * @param int $page
	 * @return $this
	 */
	public function setCurrentPage($page);

	/**
	 * @return int - limit for SQL
	 */
	public function getLimit();

	/**
	 * @return int - limit for SQL
	 */
	public function getOffset();

	/**
	 * Return number of pages.
	 *
	 * @return int
	 */
	public	function getPageCount();

	/**
	 * @param int $range
	 * @return $this
	 */
	public function setPageRange($range);

	/**
	 * @return array
	 */
	public function getPagesInRange();
}


text:
package scala.pickling

import scala.language.experimental.macros

import scala.reflect.runtime.universe._
// TODO - Document this, specifically what pinHints means.
trait Hintable {
  /** Hints at the expected (byte) size of the entry we're about to write.. */
  def hintKnownSize(knownSize: Int): this.type
  /** Hints to the pickle format that we KNOW the type of this field, so it can elide any type hints from the final pickle.
    *  During unpickling, this informs the format that it shouldn't look for any type hints in the pickle, but instead
    *  use this tag as the unpickle tag key.
    */
  def hintElidedType(tag: FastTypeTag[_]): this.type

  /** Hints the object id of the next `beginEntry`/`endEntry` calls.
    * If this oid is -1, it implies that the next entry has not been registered in any sharing cache, and should
    * be pickled fully.   If the oid != -1, then the pickle format is free to elide the fields of the entry in
    * favor of pickling a [[scala.pickling.refs.Ref]].
    *
    * Hint: This is only used during pickling.
    */
  def hintOid(id: Int): this.type
  /** Locks the hints down to what we've specified, so if you drop into anotehr pickler it retains our information. */
  def pinHints(): this.type
  /** Unlocks the hints. */
  def unpinHints(): this.type
  /** Creates a new fresh set of hints, preserving what was hinted before. */
  def pushHints(): this.type
  /** Pops to the previously saved set of hints. */
  def popHints(): this.type
}

/**
 * A builder of pickled content.  This is a mutable API, intended to be called in certain specific ways.
 *
 * Here are a few static rules that all picklers must follow when using this interface.
 *
 * 1. There will be one endEntry() for every beginEntry() call.
 * 2. There will be one endCollection() for every beginCollection() call.
 * 3. Every beginCollection()/endCollection() pair will be inside a beginEntry()/endEntry() pair.
 * 4. Every putElement() call must happen within a beginCollection()/endCollection() block.
 * 5. Every putField() call must happen within a beginEntry()/endEntry() block.
 * 6. There is no guarantee that putElement() will be called within a beginCollectoin()/endCollection() pair.
 *    i.e. we can write empty collections.
 * 7. There is no guarantee that putField will be called within a beginEntry()/endEntry() pair.
 *    i.e. if we don't put any fields, this means the entry was for a "primitive" type, at least what
 *    The pickling library considers primitives.
 * 8. The order of putField calls in any pickler will be the exact same ordering when unpickling, if the format
 *    is compatible.
 *
 * Here is a list of all types the auto-generated Picklers considers "primitives" and must be directly supported by
 * any PBuilder:
 *
 *   - Nothing
 *   - Null
 *   - Unit
 *   - Byte
 *   - Char
 *   - String
 *   - Short
 *   - Int
 *   - Long
 *   - Float
 *   - Double
 *   - Ref  (for circular object graphs)
 *   - ArrayByte
 *   - ArrayShort
 *   - ArrayChar
 *   - ArrayInt
 *   - ArrayLong
 *   - ArrayBoolean
 *   - ArrayFloat
 *   - ArrayDouble
 */
trait PBuilder extends Hintable {
  /** Called to denote that an object is about to be serialized.
    * @param picklee
    *                The object to be serialized.  This may be a primtiive, in which case
    *                it can be immediately serialized (or you can wait unitl endEntry is called).
    * @param tag
    *                The tag to use when pickling this entry.   Tags must be serialized/restored, unless
    *                otherwise hinted that it can be elided.
    * @return
    *                A pbuilder instance a pickler can use to serialize the picklee, if it's a complex type.
    */
  def beginEntry(picklee: Any, tag: FastTypeTag[_]): PBuilder
  /**
   * Serialize a "field" in a complex structure/object being pickled.
   * @param name  The name of the field to serialize.
   * @param pickler  A callback which will be passed an appropriate pickler.
   *                 You should ensure this function will perform a beginEntry()/endEntry() block.
   * @return A builder for remaining items in the current complex structure being pickled.
   */
  def putField(name: String, pickler: PBuilder => Unit): PBuilder

  /**
   * Call this to denote that the given primitive, collection or structure being pickled is completed.
   */
  def endEntry(): Unit

  /**
   * Denotes that a collection of elements is about to be pickled.
   *
   * Note: This must be called after beginEntry()
   * @param length   The length of the collection being serialized.
   * @return  A pickler which can serialzie the collection.
   */
  def beginCollection(length: Int): PBuilder

  /**
   * Places the next element in the serialized collection.
   *
   * Note: This must be called after beginCollection().
   * @param pickler  A callback which is passed a pickler able to serialize the item in the collection.
   * @return  A pickler which can serialize the next element of the collection.
   */
  def putElement(pickler: PBuilder => Unit): PBuilder
  /** Denote that we are done serializing the collection. */
  def endCollection(): Unit
  /** Return the resulting pickle of this builder. */
  def result(): Pickle
}
// Abstract shim for Java.
abstract class AbtsractPBuilder extends PBuilder with PickleTools

/**
 * A reader of pickled content.  This is a mutable API, intended to be called in certain specific ways.
 *
 * Here are a few static rules that all picklers must follow when using this interface.
 *
 * 1. There will be one endEntry() for every beginEntry() call.
 * 2. There will be one endCollection() for every beginCollection() call.
 * 3. Every beginCollection()/endCollection() pair will be inside a beginEntry()/endEntry() pair.
 * 4. Every readLength() call will be immediately after a beginCollection() call.
 * 5. Every readElement() call must happen within a beginCollection()/endCollection() block, and after a readLength().
 * 6. Every readField() call must happen within a beginEntry()/endEntry() block.
 * 7. If readLength() returns 0, there will be no called to readElement().
 * 8. readField() will only be called where atObject would return true
 * 9. readPrimitive will only be called when atPrimitive would return true
 * 10. The order of readField calls in any pickler will be the exact same ordering when pickling,
 *
 * Here is a list of all types the auto-generated Picklers considers "primitives" and must be directly supported by
 * any PReader "readPrimitive" operation:
 *
 *   - Nothing
 *   - Null
 *   - Unit
 *   - Byte
 *   - Char
 *   - String
 *   - Short
 *   - Int
 *   - Long
 *   - Float
 *   - Double
 *   - Ref  (for circular object graphs)
 *   - ArrayByte
 *   - ArrayShort
 *   - ArrayChar
 *   - ArrayInt
 *   - ArrayLong
 *   - ArrayBoolean
 *   - ArrayFloat
 *   - ArrayDouble
 */
trait PReader extends Hintable {
  /** Start reading a pickled value.
   *  This will return any serialized type tag key string.   This string can be used
   *  to reconstitute a FastTypeTag w/ a mirror, but is intended for use as fast string-matching.
   */
  def beginEntry(): String
  /** returns true if the reader is currently looking at a pickled primitive. */
  def atPrimitive: Boolean
  /** Reads one of the supported primitive types from the pickler. */
  def readPrimitive(): Any
  /** returns true if the reader is currently looking at a pickled object/structure. */
  def atObject: Boolean
  /** Returns a reader which can read a field of
    * a complex structure in the pickle.
    * @param name  The name of the field
    * @return  A reader which can read the structure's field.
    */
  def readField(name: String): PReader
  /** Denotes that we're done reading an entry in the pickle. */
  def endEntry(): Unit
  /** Denotes we'd like to read the current entry as a collection.
    * Note: Must be called after a beginEntry* call.
    */
  def beginCollection(): PReader
  /** Reads the length of a serialized collection.
    * Must be called directly after beginCollection and before readElement.
    * @return  The length of a serialized collection.
    */
  def readLength(): Int
  /** Returns a new Reader that can be used to read the next element in a collection.  */
  def readElement(): PReader
  /** Denote that we are done reading a collection. */
  def endCollection(): Unit
}

// Abstract class for Java implementors of picklers.
abstract class AbstractPReader extends PReader with PickleTools

/**
 * Exception thrown when the pickling or unpickling process fails.
 * @param message error message
 * @param cause exception causing the pickling exception if any
 */
final case class PicklingException(message: String, cause: Option[Throwable] = None) extends RuntimeException(message, cause.orNull)

/**
 * Exception thrown when a stream ends unexpectedly during unpickling.
 */
final class EndOfStreamException extends RuntimeException("End of stream reached while unpickling")


text:
<?php

namespace userAgent\userAgent\Detector\OS;

class MacOSDarwin extends AbstractOSDetector {
    protected static $link = 'http://www.apple.com/macosx/';
    protected static $name = 'Mac OS Darwin';
    protected static $regEx = '/Darwin/i';

    public static function detectVersion($userAgentString)
    {
        return 'unknown';
    }
}


text:
const webpack = require('webpack');

/*
 * Webpack Plugins
 */
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const ManifestRevisionPlugin = require('manifest-revision-webpack-plugin');

// take debug mode from the environment
const debug = (process.env.NODE_ENV !== 'production');

// Development asset host (webpack dev server)
const publicHost = debug ? 'http://localhost:2992' : '';

const rootAssetPath = './assets/';

module.exports = {
  // configuration
  context: __dirname,
  entry: {
    main_js: './assets/js/main',
    main_css: [
      './node_modules/font-awesome/css/font-awesome.css',
      './node_modules/bootstrap/dist/css/bootstrap.css',
      './assets/css/style.css'
    ]
  },
  output: {
    path: __dirname + '/tour/static/build',
    publicPath: publicHost + '/static/build/',
    filename: '[name].[hash].js',
    chunkFilename: '[id].[hash].js'
  },
  resolve: {
    extensions: ['.js', '.jsx', '.css']
  },
  devtool: debug ? 'inline-sourcemap' : 'source-map',
  devServer: {
    headers: { 'Access-Control-Allow-Origin': '*' }
  },
  module: {
    loaders: [
      { test: /\.html$/, loader: 'raw-loader' },
      { test: /\.less$/, loader: ExtractTextPlugin.extract({fallback: 'style-loader', use: 'css-loader!less-loader' }) },
      { test: /\.css$/, loader: ExtractTextPlugin.extract({fallback: 'style-loader', use: 'css-loader' }) },
      { test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: 'url-loader?limit=10000&mimetype=application/font-woff' },
      { test: /\.(ttf|eot|svg|png|jpe?g|gif|ico)(\?.*)?$/i,
        loader: 'file-loader?context=' + rootAssetPath + '&name=[path][name].[hash].[ext]' },
      { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader', query: { presets: ['es2015'], cacheDirectory: true } },
    ]
  },
  plugins: [
    new ExtractTextPlugin('[name].[hash].css'),
    new webpack.ProvidePlugin({ $: 'jquery',
                                jQuery: 'jquery' }),
    new ManifestRevisionPlugin(__dirname + '/tour/webpack/manifest.json', {
      rootAssetPath,
      ignorePaths: ['/js', '/css']
    }),
  ].concat(debug ? [] : [
    // production webpack plugins go here
    new webpack.DefinePlugin({
      'process.env': {
        'NODE_ENV': JSON.stringify('production')
      }
    }),
  ])
};


text:
package ti.modules.titanium.xml;

import org.appcelerator.kroll.annotations.Kroll;
import org.appcelerator.titanium.TiContext;
import org.w3c.dom.Comment;

@Kroll.proxy
public class CommentProxy extends CharacterDataProxy {

	public CommentProxy(TiContext context, Comment comment)
	{
		super(context, comment);
	}
}


text:
CFileHandleCache::CFileHandleCache(void)
{
}

CFileHandleCache::~CFileHandleCache(void)
{
}

CFileHandleCache& CFileHandleCache::instance()
{
    static CFileHandleCache inst;
    return inst;
}

HANDLE CFileHandleCache::GetFileHandle(LPCTSTR szFilePath)
{
    CString strFilePath(szFilePath);
    strFilePath.MakeLower();
    void* pHandle = NULL;
    if(m_mapFileHandles.Lookup(strFilePath, pHandle))
    {
        return (HANDLE)pHandle;
    }
    else
    {
        HANDLE hFile = ::CreateFile(strFilePath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, NULL, NULL);
        if(hFile != INVALID_HANDLE_VALUE)
        {
            m_mapFileHandles.SetAt(strFilePath, (void*)hFile);
        }
        return hFile;
    }
}

void CFileHandleCache::Clear()
{
    CString strFilePath;
    void* pHandle = INVALID_HANDLE_VALUE;
    POSITION pos = m_mapFileHandles.GetStartPosition();
    while(pos != NULL)
    {
        m_mapFileHandles.GetNextAssoc(pos, strFilePath, pHandle);
        if(pHandle != INVALID_HANDLE_VALUE)
        {
            ::CloseHandle((HANDLE)pHandle);
        }
    }
    m_mapFileHandles.RemoveAll();
}


text:
package com.ebay.myriad.api.model;

public class FlexDownClusterResponse {
	public FlexDownClusterResponse() {
	}
}


text:
namespace $ {

	export class $mol_server extends $mol_object {

		@ $mol_mem
		express() {
			var express = $node['express']()

			this.expressHandlers().forEach( plugin => express.use( plugin ) )

			return express
		}

		@ $mol_mem
		http() {

			const server = $node.http.createServer( this.express() )

			$node['portastic'].find(
				{
					min : this.port() ,
					max : this.port() + 1000 ,
					retrieve : 1
				}
			).then(
				( ports : number[] ) => {
					server.listen( ports[ 0 ] )
					this.$.$mol_log3_done({
						place: `${ this }` ,
						message: `Started` ,
						location: `http://127.0.0.1:${ ports[0] }/`
					})
				}
			)

			return server

		}

		connections = new Set< InstanceType<$node['ws']> >()

		@ $mol_mem
		socket() {

			const socket = new $node.ws.Server({
				server : this.http() ,
				perMessageDeflate: {
					zlibDeflateOptions: {
						chunkSize: 1024,
						memLevel: 7,
						level: 3
					},
					zlibInflateOptions: {
						chunkSize: 10 * 1024
					},
				}
			})

			socket.on( 'connection' , line => {

				this.connections.add( line )

				line.on( 'message' , ( message: any, isBinary: boolean )=> {

					for( const other of this.connections ) {
						if( line === other ) continue
						other.send( message, { binary: isBinary } )
					}

				} )

			} )

			return socket

		}

		expressHandlers() : any[] {
			return [
				this.expressCors() ,
				this.expressCompressor() ,
				this.expressBodier() ,
				this.expressGenerator() ,
				this.expressIndex() ,
				this.expressFiler() ,
				this.expressDirector() ,
			]
		}

		expressCompressor() {
			return $node['compression']() as unknown
		}

		expressCors() {
			return $node.cors() as unknown
		}

		expressBodier() {
			return $node[ 'body-parser' ].json(
				{
					limit : this.bodyLimit()
				}
			)
		}

		expressFiler() {
			return $node.express.static(
				$node.path.resolve( this.rootPublic() ) ,{
					maxAge : this.cacheTime()
				}
			)
		}

		expressDirector() {
			return $node['serve-index']( this.rootPublic() , { icons : true } ) as unknown
		}

		expressIndex() {
			return (
				req : typeof $node.express.request ,
				res : typeof $node.express.response ,
				next : () => void
			) => next()
		}

		expressGenerator() {
			return ( req : any , res : any , next : () => void )=> next()
		}

		bodyLimit() {
			return '1mb'
		}

		cacheTime() {
			return 1000 * 60 * 60 * 24 * 365 * 1000
		}

		port() {
			return 80
		}

		rootPublic() {
			return '.'
		}

	}

}


text:
ITK v5 Migration Guide
======================

This guide documents the changes required to migrate a code base
which uses ITK v4 to use ITK v5. The migration guide for transition
from v3 to v4 can be found [here](https://itk.org/migrationv4/).

Legacy code removed
-------------------

All code which was marked as legacy in ITK 4.13 has been removed.
External code which previously required
`ITK_LEGACY_REMOVE` CMake option to be `OFF` in order to build will now fail
to compile. Before starting migration to v5 (as explained in this guide),
migration to v4 should be finished. Dependent code should build and pass tests
with `ITK_LEGACY_REMOVE` turned `ON` when compiling against
[ITK v4.13](https://github.com/InsightSoftwareConsortium/ITK/releases/tag/v4.13.1).

Code which was marked as `ITK_FUTURE_LEGACY_REMOVE` has been now
re-flagged as `ITK_LEGACY_REMOVE`. There have been some other
deprecations and API changes. The new behavior is activated by setting
`ITK_LEGACY_REMOVE` to `ON`. By default, compatibility with v4 is retained
(`ITK_LEGACY_REMOVE=OFF`).

The first step is to get the external code building against ITK compiled with
`ITKV4_COMPATIBILITY` set to `ON`. Once that is accomplished, turn this
option `OFF`. It is `OFF` by default.

Once external code builds successfully with the default configuration
(`ITKV4_COMPATIBILITY` and `ITK_LEGACY_REMOVE` both `OFF`),
`ITK_LEGACY_REMOVE` should be set to `ON`.  Possible additional build errors
and/or warnings should be addressed.  Once dependent code builds and passes
tests without legacy options, migration to v5 is complete.

Support for for pre-20160229 `VXL_VERSION_DATE_FULL` system installed
versions of VXL has been removed.  VXL now supports more common Semantic Versioning
conventions with the minimum supported version for ITKv5 being 2.0.2 (as of 2018-11-30).

C++11
-----

A major improvement in ITK 5 is to fully adopt C++11.
Prior to ITK 5, a limited subset of C++11 functionalities were available in ITK
through back-ports and macros. This functionality was enabled when ITK was built with the C++11 standard enabled.
ITK 5.0.0 deprecates or removes these macros (e.g. `ITK_NULLPTR`, `ITK_DELETED_FUNCTION`,
`ITK_NOEXCEPT`, `ITK_CONSTEXPR`) and directly uses C++11 keywords such as
[delete](https://github.com/InsightSoftwareConsortium/ITK/commit/02128abbd0bf790deadc86a28c62c4a25e23518b),
[constexpr](https://github.com/InsightSoftwareConsortium/ITK/commit/b8e41d0d1652a8f6ddb84328faef67b207e77430),
[nullptr](https://github.com/InsightSoftwareConsortium/ITK/commit/3c6372b80ac2900e2e197899989c4cd151f1695f),
[override](https://github.com/InsightSoftwareConsortium/ITK/commit/3ceacc0ad4ec699b094d96e23d33f9467c2a63c6),
[noexcept](https://github.com/InsightSoftwareConsortium/ITK/commit/af4f65519abb32b59cebb2d72f0186a96efe3b4e).
The keywords [auto](https://github.com/InsightSoftwareConsortium/ITK/commit/de713e7ac52f7815a35754de885795ff0a1c4981)
and  `using` [[1](https://github.com/InsightSoftwareConsortium/ITK/commit/66e5d6b3bcc28f1a85b702086b6cedc8cab6723b),
[2](https://github.com/InsightSoftwareConsortium/ITK/commit/f21c1d27025575167ea9194214aa5bf17a0a5495)]
as well as [range-based loops](https://github.com/InsightSoftwareConsortium/ITK/commit/48daed0751df99bcb5fd1077e78ceb1b47546ccc)
are also now used in ITK. As a consequence, due to limitations in C++11 support
Visual Studio 2013 (MSVC 12.0) and other older C++ complilers cannot be used to build ITK from 5.0 and forward.

Errors similar to `error: conversion from 'int' to 'typename InterpolatorType::Pointer'` are a result of further
type safty for dealing with pointers. Enhancements in nullptr behavior in ITKv5 provide more clear
type checking and respect the nullptr identifier.  The 'long 0' value
known as NULL causes an abiguity for overload compilations of the ITKv5 smartpointers. To be backwards compatible
with pre C++11 compilers use the `ITK_NULLPTR` designation, otherwise replace NULL and 0 initialization of
`itk::SmartPointer` with nullptr.

Availability of the C++11 standard allows use of many Standard Library
features. These were previously implemented as portable ITK classes.
The standard library classes are preferred over ITK's implementations.
The most notable examples of this are:
 * [atomic integers](https://itk.org/Doxygen/html/classitk_1_1AtomicInt.html) should be replaced by `std::atomic`.
 * [mutex locks](https://itk.org/Doxygen/html/classitk_1_1MutexLock.html)
and related classes should be replaced by the similarly named classes from
[<mutex>](https://en.cppreference.com/w/cpp/header/mutex) header.
 * itksys::hash_map should be replaced by [std::unordered_map](https://en.cppreference.com/w/cpp/container/unordered_map).

To modernize your code base, replace:
  * `SimpleFastMutexLock` with `std::mutex`, and `#include "itkSimpleFastMutexLock.h"`  with `#include <mutex>`.
  * `FastMutexLock` with `std::mutex`, and `#include "itkFastMutexLock.h"`  with `#include <mutex>`.
  * `MutexLock` with `std::mutex`, and `#include "itkMutexLock.h"`  with `#include <mutex>`.

Modern CMake requirement
------------------------

ITK now requires **CMake 3.10.2** for configuration. While only a few features
enabled by this modern version of CMake are being used for 5.0 release, a
modern version of CMake is a prerequisite for future more aggressive updates
to ITK's build system. This is planned for a later version.

Before making other changes suggested in this document,
your code should work with the latest version of CMake.

Updated style
-------------

Important changes in style have also been integrated in ITK to match
C++11 best practices. This includes replacing `typedef` calls with
the keyword `using`, the usage of the keyword `auto` when appropriate,
and moving the macro `ITK_DISALLOW_COPY_AND_ASSIGN` from the private
class section to the public class section. The ITK Software Guide has
been updated to match these changes.

Multithreading refactored
-------------------------

Since ITK 5.0 `itk::MultiThreader` has been split into a class hierarchy.
Instead of a single `itk::MultiThreader` class which could optionally delegate work
to an [itk::ThreadPool](https://itk.org/Insight/Doxygen/html/classitk_1_1ThreadPool.html),
there are now multiple backends to provide thread-based parallel processing.
Most of the time you will want to replace `itk::MultiThreader` by
[itk::MultiThreaderBase](https://itk.org/Insight/Doxygen/html/classitk_1_1MultiThreaderBase.html).

[PlatformMultiThreader](https://itk.org/Insight/Doxygen/html/itkPlatformMultiThreader_8h.html)
is essentially the old `itk::MultiThreader`, renamed. `itk::PoolMultiThreader` behaves like
the old `itk::MultiThreader` with `ITK_USE_THREADPOOL=ON`. There is an addition of
[TBBMultiThreader](https://itk.org/Insight/Doxygen/html/classitk_1_1TBBMultiThreader.html),
which uses Intel Thread Building Blocks library's thread-pool, with has load balancing features.
The option to build TBB support must be enabled during the CMake configuration step.
The default multi-threader can be set via environment variable
`ITK_GLOBAL_DEFAULT_THREADER` with possible case-insensitive values of
`Platform`, `Pool` and `TBB`, e.g. `ITK_GLOBAL_DEFAULT_THREADER=tbb`.

For filter multi-threading, a new signature has been introduced:
`void DynamicThreadedGenerateData( const OutputRegionType& threadRegion )`.
By default, this new signature is invoked instead of the classic
`void ThreadedGenerateData( const OutputRegionType& threadRegion, ThreadIdType threadId )`.
To temporarily obtain the old behavior (classic signature invoked by default),
set `ITKV4_COMPATIBILITY` to `ON` in ITK's CMake configuration.
To permanently have your filter use the classic threading model,
invoke `this->DynamicMultiThreadingOff();` in the filter constructor.
That is required if any of the following is true:
 * Your filter needs a constant number of threads (known in advance)
 * Your filter uses `threadId` parameter in `ThreadedGenerateData()`
 * Your filter uses a custom region splitting method

Additionally, replace `itk::MultiThreader` by `itk::PlatformMultiThreader`
if any of the following is true:
 * Your filter uses cross-thread synchronization e.g. `itk::Barrier`
 * Your filter uses `MultipleMethodExecute()`
 * Your filter uses `SpawnThread`/`TerminateThread`

It is strongly advised to not explicitly use `itk::PlatformMultiThreader`.
`SpawnThread`/`TerminateThread` and `MultipleMethodExecute` can be
replaced by C++11 `std::thread`. Code in the example below shows
how to remove dependence on barrier by using ParallelizeImageRegion.

- Pattern for Multiple Parallel Operations:
```cpp
ThreadedGenerateData()
{
  //code1 (parallel)
  myBarrier->Wait();
  if (threadId==0)
    {
    //code2 single-threaded
    }
  //code3 (parallel)
}
```

after refactoring to not use barrier:
```cpp
GenerateData() //Not Threaded
{
  this->AllocateOutputs();
  this->BeforeThreadedGenerateData();
  ParallelizeImageRegion(code1 as lambda)
  //code2 single-threaded
  ParallelizeImageRegion(code3 as lambda)
  this->AfterThreadedGenerateData();
}
```

-  ITK_THREAD_RETURN_TYPE is now in the itk:: namespace
```cpp
#if ITK_VERSION_MAJOR >= 5
  static itk::ITK_THREAD_RETURN_TYPE NetworkingThreaderCallback( void * );
#else
  static ITK_THREAD_RETURN_TYPE NetworkingThreaderCallback( void * );
#endif
```

- ITK_THREAD_RETURN_VALUE is named itk::ITK_THREAD_RETURN_DEFAULT_VALUE
```cpp
#if ITK_VERSION_MAJOR >= 5
  return itk::ITK_THREAD_RETURN_DEFAULT_VALUE;
#else
  return ITK_THREAD_RETURN_VALUE;
#endif
```

- ThreadInfoStruct is renamed to WorkUnitInfo
```cpp
#if ITK_VERSION_MAJOR >= 5
    (((itk::PlatformMultiThreader::WorkUnitInfo *)(arg))->UserData);
#else
    (((itk::MultiThreader::ThreadInfoStruct *)(arg))->UserData);
#endif
```

- Pattern for Parallel Counting:
Previously parallel counting was often storing per-thread counts in an `itk::Array`
and aggregating the result in a filter's `AfterThreadedGenerateData()`.
With C++11, you might want to instead use `std::atomic`.
An external module example that demonstrates this can be found in
[this commit](https://github.com/InsightSoftwareConsortium/ITKBoneMorphometry/pull/32/commits/a8014c186ac53837362a0cb9db46ae224b8e9584).

Before, using `itk::Array`:
```C++
// Members:
Array<SizeValueType> m_NumVoxelsInsideMask;
BeforeThreadedGenerateData()
{
  // Resize the thread temporaries
  m_NumVoxelsInsideMask.SetSize(this->GetNumberOfThreads());
  m_NumVoxelsInsideMask.Fill(0);
}

ThreadedGenerateData(const RegionType & outputRegionForThread,
                     ThreadIdType threadId)
{
  // Do algorithm per threadId
  // Store the results per thread at the end
  m_NumVoxelsInsideMask[threadId] = numVoxelsForThisRegion;
}

AfterThreadedGenerateData()
{
  // Retrieve and sum all the results per thread.
  ThreadIdType numberOfThreads = this->GetNumberOfThreads();
  SizeValueType numVoxelsInsideMask = 0;
  for (unsigned int i = 0; i < numberOfThreads; ++i )
    {
    numVoxelsInsideMask += m_NumVoxelsInsideMask[i];
    }
}

```
After, using `std::atomic`:
```C++
// Members:
std::atomic<SizeValueType> m_NumVoxelsInsideMask;
BeforeThreadedGenerateData()
{
  // Initialize atomics
  m_NumVoxelsInsideMask.store(0);
}

DynamicThreadedGenerateData(const RegionType & outputRegionForThread)
{
  // Do algorithm without handling threadId
  m_NumVoxelsInsideMask.fetch_add(numVoxelsForThisRegion, std::memory_order_relaxed);
}

AfterThreadedGenerateData()
{
  // Get the value from the atomic
  SizeValueType numVoxelsInsideMask = m_NumVoxelsInsideMask.load();
}
```

`Get/SetGlobalMaximumNumberOfThreads()`, and `GlobalDefaultNumberOfThreads()`
now reside in `itk::MultiThreaderBase`.  With a warning, they are still
available in `itk::PlatformMultiThreader`.
`GetGlobalDefaultNumberOfThreadsByPlatform()` has also been moved from
`itk::ThreadPool` to `itk::MultiThreaderBase`.  In image filters and other
descendents of `itk::ProcessObject`, method `SetNumberOfThreads` has been
renamed into `SetNumberOfWorkUnits`.  For `itk::MultiThreaderBase` and
descendents, `SetNumberOfThreads` has been split into
`SetMaximumNumberOfThreads` and `SetNumberOfWorkUnits`.  Load balancing is
possible when `NumberOfWorkUnits` is greater than the number of threads. The
common case of `innerFilter->SetNumberOfThreads(1);` should be replaced by
`innerFilter->SetNumberOfWorkUnits(1);`. Generally, in most places where
threads were being manipulated before, work units should be accessed or
changed now.

To transition to the new threading model, it is usually enough to rename
`ThreadedGenerateData` into `DynamicThreadedGenerateData`, remove the
`threadId` parameter, and remove progress reporting which uses `threadId`.
Progress is being reported by multi-threaders on behalf of filters which
use `DynamicThreadedGenerateData` signature.

If your class needs to also work with legacy code where
`ITKV4_COMPATIBILITY` is enabled, invoke
`this->DynamicMultiThreadingOn();` in the filter constructor. An example of
an external module that transitioned to the new threading model can be found in
[this commit](https://github.com/InsightSoftwareConsortium/ITKTextureFeatures/commit/f794baa7546f9bb8b7d89ae3a083c9a432d55df0).

The variables `ITK_MAX_THREADS` and `ITK_DEFAULT_THREAD_ID` are now in the `itk::` namespace.
Backwards compatibility is currently supported by exposing these to the global namespace
with
```C++
  using itk::ITK_MAX_THREADS;
  using itk::ITK_DEFAULT_THREAD_ID;
```

Class changes
-------------

[itk::FilterWatcher](../Modules/Core/TestKernel/include/itkFilterWatcher.h) was deleted.
It should be replaced by [itk::SimpleFilterWatcher](../Modules/Core/Common/include/itkSimpleFilterWatcher.h).

Since `itk::ProgressReporter` does not work well with the new threading model,
it should be replaced by `itk::ProgressTransformer`.
This only applies to classes which use `GenerateData()` method, and either
have multiple `ParallelizeRegion` calls or a long single-threaded section.
An example of how to add progress reporting can be found in
[this commit](https://github.com/InsightSoftwareConsortium/ITK/commit/dd0b0d128d6c0760cefd8a958107cb0e841b51b4).

Otsu filters now return the correct threshold (bin's maximum value instead of mid-point) with ITKv5.
The old behavior is kept when ITKV4_COMPATIBILITY is enabled by setting `ReturnBinMidpoint` to true by default.
It is recommended when migrating to ITKv5 to explicitly set the `ReturnBinMidpoint` value to false.
This change may effect computations which rely on the results of an Otsu threshold filter.

`HoughTransform2DCirclesImageFilter<TInputPixelType, TOutputPixelType, TRadiusPixelType>` no longer
has a default argument for its last template parameter. Instead, users of the filter should now
explicitly specify all three template arguments. Earlier versions of ITK assumed that the radius
pixel type should be the same as `TOutputPixelType`. However, it appears that for the radius pixel
type (`TRadiusPixelType`), a floating point type is often preferred, whereas for the accumulator
output pixel type (`TOutputPixelType`), an unsigned integer type is often more appropriate.

`GaussianDerivativeImageFunction::ImageDimension2` is renamed to `GaussianDerivativeImageFunction::ImageDimension`.
The nested `GaussianDerivativeImageFunction` types `GaussianDerivativeFunctionType` and
`GaussianDerivativeFunctionPointer` are renamed to `GaussianDerivativeSpatialFunctionType` and
`GaussianDerivativeSpatialFunctionPointer`, respectively.

With ITK 5.0, `itk::ProcessObject::VerifyPreconditions()`  and
`itk::ProcessObject::VerifyInputInformation` are now declared `const`,
so if you have overridden these virtual member function, make sure that you
also add `const`. If your application needs to compile with both ITKv4 and ITKv5,
you should use macro `ITKv5_CONST` instead of `const` keyword.
This macro is present in ITKv4 since commit
b40f74e07d74614c75be4aceac63b87e80e589d1 on 2018-11-14.

Python changes
--------------

Mesh-related class wrapping has been simplified, made more consistent, and
expanded, but previous template parameters may not be available.

Arguments to functions in `itkExtras` were cleaned up and now use snake case.

Update scripts
--------------

[Utilities/ITKv5Preparation](../Utilities/ITKv5Preparation/) directory contains
bash scripts which have been used to update ITK to version 5. These scripts
can assist with updating external code bases to ITK 5 content and style.


text:
package com.google.common.collect.testing;

/**
 * A sample enumerated type we use for testing.
 *
 * @author Kevin Bourrillion
 */
public enum AnEnum {
  A, B, C, D, E, F
}


text:
namespace FluentValidation.Validators.UnitTestExtension.ValidatorVerifiers
{
    using FluentAssertions;

    public class ExactLengthValidatorVerifier<T> : LengthValidatorVerifier<ExactLengthValidator<T>>
    {
        public ExactLengthValidatorVerifier(int length) : base(length, length)
        {
        }
    }
}


text:
using System.Collections.ObjectModel;

#nullable enable
namespace System.Management.Automation.Provider
{
    #region IPropertyCmdletProvider

    /// <summary>
    /// An interface that can be implemented by a Cmdlet provider to expose properties of an item.
    /// </summary>
    /// <remarks>
    /// An IPropertyCmdletProvider provider implements a set of methods that allows
    /// the use of a set of core commands against the data store that the provider
    /// gives access to. By implementing this interface users can take advantage
    /// the commands that expose the contents of an item.
    ///     get-itemproperty
    ///     set-itemproperty
    ///     etc.
    /// This interface should only be implemented on derived classes of
    /// <see cref="CmdletProvider"/>, <see cref="ItemCmdletProvider"/>,
    /// <see cref="ContainerCmdletProvider"/>, or <see cref="NavigationCmdletProvider"/>.
    ///
    /// A namespace provider should implemented this interface if items in the
    /// namespace have properties the provide wishes to expose.
    /// </remarks>
    public interface IPropertyCmdletProvider
    {
        /// <summary>
        /// Gets the properties of the item specified by the path.
        /// </summary>
        /// <param name="path">
        /// The path to the item to retrieve properties from.
        /// </param>
        /// <param name="providerSpecificPickList">
        /// A list of properties that should be retrieved. If this parameter is null
        /// or empty, all properties should be retrieved.
        /// </param>
        /// <returns>
        /// Nothing.  The property that was retrieved should be passed to the WritePropertyObject method.
        /// </returns>
        /// <remarks>
        /// Providers override this method to give the user the ability to add properties to provider objects
        /// using the get-itemproperty cmdlet.
        ///
        /// Providers that declare <see cref="System.Management.Automation.Provider.ProviderCapabilities"/>
        /// of ExpandWildcards, Filter, Include, or Exclude should ensure that the path passed meets those
        /// requirements by accessing the appropriate property from the base class.
        ///
        /// By default overrides of this method should not retrieve properties from objects that are generally hidden from
        /// the user unless the Force property is set to true. An error should be sent to the WriteError method if
        /// the path represents an item that is hidden from the user and Force is set to false.
        ///
        /// An <see cref="System.Management.Automation.PSObject"/> can be used as a property bag for the
        /// properties that need to be returned if the <paramref name="providerSpecificPickList"/> contains
        /// multiple properties to write.
        /// </remarks>
        void GetProperty(
            string path,
            Collection<string>? providerSpecificPickList);

        /// <summary>
        /// Gives the provider an opportunity to attach additional parameters to the
        /// get-itemproperty cmdlet.
        /// </summary>
        /// <param name="path">
        /// If the path was specified on the command line, this is the path
        /// to the item to get the dynamic parameters for.
        /// </param>
        /// <param name="providerSpecificPickList">
        /// A list of properties that should be retrieved. If this parameter is null
        /// or empty, all properties should be retrieved.
        /// </param>
        /// <returns>
        /// Overrides of this method should return an object that has properties and fields decorated with
        /// parsing attributes similar to a cmdlet class or a
        /// <see cref="System.Management.Automation.RuntimeDefinedParameterDictionary"/>.
        ///
        /// The default implementation returns null. (no additional parameters)
        /// </returns>
        object? GetPropertyDynamicParameters(
            string path,
            Collection<string>? providerSpecificPickList);

        /// <summary>
        /// Sets the specified properties of the item at the specified path.
        /// </summary>
        /// <param name="path">
        /// The path to the item to set the properties on.
        /// </param>
        /// <param name="propertyValue">
        /// A PSObject which contains a collection of the name, type, value
        /// of the properties to be set.
        /// </param>
        /// <returns>
        /// Nothing.  The property that was set should be passed to the WritePropertyObject method.
        /// </returns>
        /// <remarks>
        /// Providers override this method to give the user the ability to set the value of provider object properties
        /// using the set-itemproperty cmdlet.
        ///
        /// Providers that declare <see cref="System.Management.Automation.Provider.ProviderCapabilities"/>
        /// of ExpandWildcards, Filter, Include, or Exclude should ensure that the path passed meets those
        /// requirements by accessing the appropriate property from the base class.
        ///
        /// By default overrides of this method should not retrieve properties from objects that are generally hidden from
        /// the user unless the Force property is set to true. An error should be sent to the WriteError method if
        /// the path represents an item that is hidden from the user and Force is set to false.
        ///
        /// An <see cref="System.Management.Automation.PSObject"/> can be used as a property bag for the
        /// properties that need to be returned if the <paramref name="providerSpecificPickList"/> contains
        /// multiple properties to write.
        /// <paramref name="propertyValue"/> is a property bag containing the properties that should be set.
        /// See <see cref="System.Management.Automation.PSObject"/> for more information.
        /// </remarks>
        void SetProperty(
            string path,
            PSObject propertyValue);

        /// <summary>
        /// Gives the provider an opportunity to attach additional parameters to the
        /// get-itemproperty cmdlet.
        /// </summary>
        /// <param name="path">
        /// If the path was specified on the command line, this is the path
        /// to the item to get the dynamic parameters for.
        /// </param>
        /// <param name="propertyValue">
        /// A PSObject which contains a collection of the name, type, value
        /// of the properties to be set.
        /// </param>
        /// <returns>
        /// Overrides of this method should return an object that has properties and fields decorated with
        /// parsing attributes similar to a cmdlet class or a
        /// <see cref="System.Management.Automation.RuntimeDefinedParameterDictionary"/>.
        ///
        /// The default implementation returns null. (no additional parameters)
        /// </returns>
        object? SetPropertyDynamicParameters(
            string path,
            PSObject propertyValue);

        /// <summary>
        /// Clears a property of the item at the specified path.
        /// </summary>
        /// <param name="path">
        /// The path to the item on which to clear the property.
        /// </param>
        /// <param name="propertyToClear">
        /// The name of the property to clear.
        /// </param>
        /// <returns>
        /// Nothing.  The property that was cleared should be passed to the WritePropertyObject method.
        /// </returns>
        /// <remarks>
        /// Providers override this method to give the user the ability to clear the value of provider object properties
        /// using the clear-itemproperty cmdlet.
        ///
        /// Providers that declare <see cref="System.Management.Automation.Provider.ProviderCapabilities"/>
        /// of ExpandWildcards, Filter, Include, or Exclude should ensure that the path passed meets those
        /// requirements by accessing the appropriate property from the base class.
        ///
        /// By default overrides of this method should not clear properties from objects that are generally hidden from
        /// the user unless the Force property is set to true. An error should be sent to the WriteError method if
        /// the path represents an item that is hidden from the user and Force is set to false.
        ///
        /// An <see cref="System.Management.Automation.PSObject"/> can be used as a property bag for the
        /// properties that need to be returned if the <paramref name="providerSpecificPickList"/> contains
        /// multiple properties to write.
        /// </remarks>
        void ClearProperty(
            string path,
            Collection<string> propertyToClear);

        /// <summary>
        /// Gives the provider an opportunity to attach additional parameters to the
        /// clear-itemproperty cmdlet.
        /// </summary>
        /// <param name="path">
        /// If the path was specified on the command line, this is the path
        /// to the item to get the dynamic parameters for.
        /// </param>
        /// <param name="propertyToClear">
        /// The name of the property to clear.
        /// </param>
        /// <returns>
        /// Overrides of this method should return an object that has properties and fields decorated with
        /// parsing attributes similar to a cmdlet class or a
        /// <see cref="System.Management.Automation.RuntimeDefinedParameterDictionary"/>.
        ///
        /// The default implementation returns null. (no additional parameters)
        /// </returns>
        object? ClearPropertyDynamicParameters(
            string path,
            Collection<string> propertyToClear);
    }

    #endregion IPropertyCmdletProvider
}


text:
require 'waveapi/operation'

module Waveapi
  class Wavelet
    attr_reader :wave_id, :wavelet_id, :creator, :creation_time, :participants, :root_blip_id, :root_blip, :context
    attr_accessor :blips, :proxy_for_id, :robot

    def initialize(json, context)
      @context = context
      @blips = @context.blips
      @raw_json = json
      @wave_id = json['waveId']
      @wavelet_id = json['waveletId']
      @creator = json['creator']
      @creation_time = json['creationTime'] || 0
      @data_documents = {} # TODO
      @last_modified_time = json['lastModifiedTime']
      @participants = Participants.new(json['participants'], json['participantRoles'],
        @wave_id, @wavelet_id, @context)
      @title = json['title'] || ''
      #@tags =
      @root_blip_id = json['rootBlipId']
      @root_blip = @context.find_blip_by_id(@root_blip_id)
      @proxy_for_id = nil
    end

    def domain
      @wave_id.split('!').first
    end

    def title=(title)
      @context.add_operation(WaveletSetTitleOperation.new(@wave_id, title))
    end

    def reply(message=nil)
      operation = WaveletAppendBlipOperation.new(@wave_id, @context, message, @proxy_for_id)
      @context.add_operation(operation)
      operation.blip
    end

    def proxy_for(proxy_for_id)
      operation = WaveletAddParticipantOperation.new(@wave_id, @wavelet_id,
        @context.address_for_proxy(proxy_for_id))
      @context.add_operation(operation)
      ret = self.class.new(@raw_json, @context)
      ret.proxy_for_id = proxy_for_id
      ret
    end

    def submit_with(other_wavelet)
      @context.operation_bundle.each do |operation|
        other_wavelet.context.add_operation(operation)
      end
      @context = other_wavelet.context
    end

    def to_hashmap
      {
        "rootBlipId" => @root_blip_id,
        "creator" => @creator,
        "blips" => Hash[*@blips.to_a.map{|k, v| [k, v.to_hashmap]}.flatten], # TODO: refactor
        "title" => @title,
        "creationTime" => @creation_time,
        "dataDocuments" => @data_document,
        "waveletId" => @wavelet_id,
        "participants" => @participants.participants,
        "waveId" => @wave_id,
        "lastModifiedTime" => @last_modified_time
      }
    end

    def to_json
      to_hashmap.to_json
    end
  end
end


text:
import genusTypes         from '../../../../constants/genus_types';
import shortAnswer      from './short_answer';

describe('shortAnswer', () => {

  let item;

  beforeEach(() => {
    item = {
      id: '1234',
      genusTypeId: 'item-genus-type%3Aqti-order-interaction-object-manipulation%40ODL.MIT.EDU',
      bankId: 'myBank',
      displayName: {
        text: 'displayYourText',
      },
      answers: [{
        id: '1',
        feedback: { text: '
Howdy
' },
        genusTypeId: genusTypes.answer.rightAnswer,
        fileIds: {},
        choiceIds: []
      }, {
        id: '2',
        feedback: { text: '
hiya
' },
        genusTypeId: genusTypes.answer.wrongAnswer,
        fileIds: {}
      }],
      question: {
        maxStrings: '100',
        expectedLength: '11',
        expectedLines: '2',
        shuffle: 'This is true',
        id: 'questionId',
        fileIds: {},
        texts: {},
        text: {
          text: 'this is your text.text',
        }
      }
    };
  });

  it('should deserialize maxStrings and expectedLength', () => {
    const result = shortAnswer(item);
    expect(result.question.maxStrings).toBe('100');
    expect(result.question.expectedLength).toBe('11');
    expect(result.question.expectedLines).toBe('2');
  });
});


text:
<?php

namespace AppBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use AppBundle\Entity\Wydzial;
use AppBundle\Form\WydzialType;

/**
 * Wydzial controller.
 *
 * @Route("/admin/wydzial")
 */
class WydzialController extends Controller
{

    /**
     * Lists all Wydzial entities.
     *
     * @Route("/", name="admin_wydzial")
     * @Method("GET")
     * @Template()
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();

        $entities = $em->getRepository('AppBundle:Wydzial')->findAll();

        return array(
            'entities' => $entities,
        );
    }
    /**
     * Creates a new Wydzial entity.
     *
     * @Route("/", name="admin_wydzial_create")
     * @Method("POST")
     * @Template("AppBundle:Wydzial:new.html.twig")
     */
    public function createAction(Request $request)
    {
        $entity = new Wydzial();
        $form = $this->createCreateForm($entity);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('admin_wydzial_show', array('id' => $entity->getId())));
        }

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }

    /**
     * Creates a form to create a Wydzial entity.
     *
     * @param Wydzial $entity The entity
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createCreateForm(Wydzial $entity)
    {
        $form = $this->createForm(new WydzialType(), $entity, array(
            'action' => $this->generateUrl('admin_wydzial_create'),
            'method' => 'POST',
        ));

        $form->add('submit', 'submit', array('label' => 'Create'));

        return $form;
    }

    /**
     * Displays a form to create a new Wydzial entity.
     *
     * @Route("/new", name="admin_wydzial_new")
     * @Method("GET")
     * @Template()
     */
    public function newAction()
    {
        $entity = new Wydzial();
        $form   = $this->createCreateForm($entity);

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }

    /**
     * Finds and displays a Wydzial entity.
     *
     * @Route("/{id}", name="admin_wydzial_show")
     * @Method("GET")
     * @Template()
     */
    public function showAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('AppBundle:Wydzial')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Wydzial entity.');
        }

        $deleteForm = $this->createDeleteForm($id);

        return array(
            'entity'      => $entity,
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
     * Displays a form to edit an existing Wydzial entity.
     *
     * @Route("/{id}/edit", name="admin_wydzial_edit")
     * @Method("GET")
     * @Template()
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('AppBundle:Wydzial')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Wydzial entity.');
        }

        $editForm = $this->createEditForm($entity);
        $deleteForm = $this->createDeleteForm($id);

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
    * Creates a form to edit a Wydzial entity.
    *
    * @param Wydzial $entity The entity
    *
    * @return \Symfony\Component\Form\Form The form
    */
    private function createEditForm(Wydzial $entity)
    {
        $form = $this->createForm(new WydzialType(), $entity, array(
            'action' => $this->generateUrl('admin_wydzial_update', array('id' => $entity->getId())),
            'method' => 'PUT',
        ));

        $form->add('submit', 'submit', array('label' => 'Update'));

        return $form;
    }
    /**
     * Edits an existing Wydzial entity.
     *
     * @Route("/{id}", name="admin_wydzial_update")
     * @Method("PUT")
     * @Template("AppBundle:Wydzial:edit.html.twig")
     */
    public function updateAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('AppBundle:Wydzial')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Wydzial entity.');
        }

        $deleteForm = $this->createDeleteForm($id);
        $editForm = $this->createEditForm($entity);
        $editForm->handleRequest($request);

        if ($editForm->isValid()) {
            $em->flush();

            return $this->redirect($this->generateUrl('admin_wydzial_edit', array('id' => $id)));
        }

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }
    /**
     * Deletes a Wydzial entity.
     *
     * @Route("/{id}", name="admin_wydzial_delete")
     * @Method("DELETE")
     */
    public function deleteAction(Request $request, $id)
    {
        $form = $this->createDeleteForm($id);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $entity = $em->getRepository('AppBundle:Wydzial')->find($id);

            if (!$entity) {
                throw $this->createNotFoundException('Unable to find Wydzial entity.');
            }

            $em->remove($entity);
            $em->flush();
        }

        return $this->redirect($this->generateUrl('admin_wydzial'));
    }

    /**
     * Creates a form to delete a Wydzial entity by id.
     *
     * @param mixed $id The entity id
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm($id)
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl('admin_wydzial_delete', array('id' => $id)))
            ->setMethod('DELETE')
            ->add('submit', 'submit', array('label' => 'Delete'))
            ->getForm()
        ;
    }
}


text:
package org.roklib.urifragmentrouting.parameter.converter;

import org.roklib.urifragmentrouting.exception.ParameterValueConversionException;

/**
 * Parameter value converter that converts to String which means that it doesn't do anything with the input. The input
 * is simply returned unaltered from the conversion methods.
 * <p>
 * No new objects of this converter can be created, as there is a static singleton {@link #INSTANCE} of this converter
 * to be used by client code.
 */
public class StringParameterValueConverter implements ParameterValueConverter<String> {
    /**
     * Singleton instance of this converter to be used.
     */
    public final static StringParameterValueConverter INSTANCE = new StringParameterValueConverter();

    private StringParameterValueConverter() {
    }

    @Override
    public String convertToString(String value) {
        return value;
    }

    @Override
    public String convertToValue(String valueAsString) throws ParameterValueConversionException {
        return valueAsString;
    }
}


text:
CREATE TABLE `ctm_test_command_target` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `testCommandId` bigint(20) unsigned NOT NULL,
  `target` text NOT NULL,
  PRIMARY KEY (`id`),
  KEY `test_command_id` (`testCommandId`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1;


text:
@interface NSArrayMatrix ()
@property(nonatomic, assign) NSUInteger rows;
@property(nonatomic, assign) NSUInteger columns;
@property(nonatomic, strong) NSMutableArray *elements;
@end

@implementation NSArrayMatrix

- (instancetype)initWithRows:(NSUInteger)rows columns:(NSUInteger)columns {
    self = [super init];
    if (self) {
        self.rows = rows;
        self.columns = columns;
        self.elements = [NSMutableArray array];
    }
    return self;
}

- (void) fillWithOrderData {
    for (int i=0; i<self.rows*self.columns; i++) {
        [self.elements addObject:[NSNumber numberWithInt:i]];
    }
}

- (void)iterateOverElementsWithBlock:(void (^)(NSUInteger, NSUInteger))iterationBlock {
    for (NSUInteger col=0; col<self.columns; col++) {
        for (NSUInteger row=0; row<self.rows; row++) {
            iterationBlock(row, col);
        }
    }
}

#pragma mark - Random methods
- (void)randomize {
    NSUInteger count = [self.elements count];
    for (NSUInteger i = 0; i < count; ++i) {
        // Select a random element between i and end of array to swap with.
        NSInteger nElements = count - i;
        NSInteger n = (random() % nElements) + i;
        [self.elements exchangeObjectAtIndex:i withObjectAtIndex:n];
    }
}

- (void) sortRightScanning {
    NSMutableArray *sortedArray = [NSMutableArray array];

    //Get an array sort the elements by columns
    for (NSInteger index=0; index<[self.elements count]; index++) {
        NSInteger auxPos = ((index%self.columns) * self.rows) + index/self.columns;
        [sortedArray addObject:self.elements[auxPos]];
    }

    self.elements = sortedArray;
}

- (void) sortLeftScanning {
    [self sortRightScanning];
    self.elements = [NSMutableArray arrayWithArray:[[self.elements reverseObjectEnumerator] allObjects]];
}

@end


text:
from django.conf.urls import patterns, url

# All urls are subject to change once the course identification system is up.
urlpatterns = patterns('',
                       url(r'^documents/$', 'documents.views.documents'),
                       url(r'^documents/filter/(?P<course_id>\w+)/$', 'documents.views.documents'),
                       url(r'^upload/$', 'documents.views.upload'),
                       url(r'^renameDocument/$', 'documents.views.rename_document'),
                       url(r'^deleteDocument/$', 'documents.views.delete_document'),
                       url(r'^documents/(?P<file_id>\w+)/$', 'documents.views.download'),
                       )


text:
<android.support.design.widget.AppBarLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/appbar"
    android:layout_width="match_parent"

    android:layout_height="wrap_content"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

    <android.support.design.widget.CollapsingToolbarLayout
        android:id="@+id/collapsing_toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:contentScrim="?attr/colorPrimaryDark"
        app:expandedTitleMarginEnd="64dp"
        app:layout_scrollFlags="scroll|exitUntilCollapsed">

        <ImageView
            android:id="@+id/toolbar_image"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_margin="8dp" />

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:layout_collapseMode="pin"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

    </android.support.design.widget.CollapsingToolbarLayout>

</android.support.design.widget.AppBarLayout>