text:
/*	$NetBSD: raw_ip6.c,v 1.136 2014/08/09 05:33:01 rtr Exp $	*/
/*	$KAME: raw_ip6.c,v 1.82 2001/07/23 18:57:56 jinmei Exp $	*/

/*
 * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of the project nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

/*
 * Copyright (c) 1982, 1986, 1988, 1993
 *	The Regents of the University of California.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 *	@(#)raw_ip.c	8.2 (Berkeley) 1/4/94
 */

#include <sys/cdefs.h>
__KERNEL_RCSID(0, "$NetBSD: raw_ip6.c,v 1.136 2014/08/09 05:33:01 rtr Exp $");

#include "opt_ipsec.h"

#include <sys/param.h>
#include <sys/sysctl.h>
#include <sys/mbuf.h>
#include <sys/socket.h>
#include <sys/protosw.h>
#include <sys/socketvar.h>
#include <sys/systm.h>
#include <sys/proc.h>
#include <sys/kauth.h>
#include <sys/kmem.h>

#include <net/if.h>
#include <net/route.h>
#include <net/if_types.h>
#include <net/net_stats.h>

#include <netinet/in.h>
#include <netinet/in_var.h>
#include <netinet/ip6.h>
#include <netinet6/ip6_var.h>
#include <netinet6/ip6_private.h>
#include <netinet6/ip6_mroute.h>
#include <netinet/icmp6.h>
#include <netinet6/icmp6_private.h>
#include <netinet6/in6_pcb.h>
#include <netinet6/nd6.h>
#include <netinet6/ip6protosw.h>
#include <netinet6/scope6_var.h>
#include <netinet6/raw_ip6.h>

#ifdef IPSEC
#include <netipsec/ipsec.h>
#include <netipsec/ipsec_var.h>
#include <netipsec/ipsec_private.h>
#include <netipsec/ipsec6.h>
#endif

#include "faith.h"
#if defined(NFAITH) && 0 < NFAITH
#include <net/if_faith.h>
#endif

extern struct inpcbtable rawcbtable;
struct	inpcbtable raw6cbtable;
#define ifatoia6(ifa)	((struct in6_ifaddr *)(ifa))

/*
 * Raw interface to IP6 protocol.
 */

static percpu_t *rip6stat_percpu;

#define	RIP6_STATINC(x)		_NET_STATINC(rip6stat_percpu, x)

static void sysctl_net_inet6_raw6_setup(struct sysctllog **);

/*
 * Initialize raw connection block queue.
 */
void
rip6_init(void)
{

	sysctl_net_inet6_raw6_setup(NULL);
	in6_pcbinit(&raw6cbtable, 1, 1);

	rip6stat_percpu = percpu_alloc(sizeof(uint64_t) * RIP6_NSTATS);
}

/*
 * Setup generic address and protocol structures
 * for raw_input routine, then pass them along with
 * mbuf chain.
 */
int
rip6_input(struct mbuf **mp, int *offp, int proto)
{
	struct mbuf *m = *mp;
	struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
	struct inpcb_hdr *inph;
	struct in6pcb *in6p;
	struct in6pcb *last = NULL;
	struct sockaddr_in6 rip6src;
	struct mbuf *opts = NULL;

	RIP6_STATINC(RIP6_STAT_IPACKETS);

#if defined(NFAITH) && 0 < NFAITH
	if (faithprefix(&ip6->ip6_dst)) {
		/* send icmp6 host unreach? */
		m_freem(m);
		return IPPROTO_DONE;
	}
#endif

	/* Be proactive about malicious use of IPv4 mapped address */
	if (IN6_IS_ADDR_V4MAPPED(&ip6->ip6_src) ||
	    IN6_IS_ADDR_V4MAPPED(&ip6->ip6_dst)) {
		/* XXX stat */
		m_freem(m);
		return IPPROTO_DONE;
	}

	sockaddr_in6_init(&rip6src, &ip6->ip6_src, 0, 0, 0);
	if (sa6_recoverscope(&rip6src) != 0) {
		/* XXX: should be impossible. */
		m_freem(m);
		return IPPROTO_DONE;
	}

	TAILQ_FOREACH(inph, &raw6cbtable.inpt_queue, inph_queue) {
		in6p = (struct in6pcb *)inph;
		if (in6p->in6p_af != AF_INET6)
			continue;
		if (in6p->in6p_ip6.ip6_nxt &&
		    in6p->in6p_ip6.ip6_nxt != proto)
			continue;
		if (!IN6_IS_ADDR_UNSPECIFIED(&in6p->in6p_laddr) &&
		    !IN6_ARE_ADDR_EQUAL(&in6p->in6p_laddr, &ip6->ip6_dst))
			continue;
		if (!IN6_IS_ADDR_UNSPECIFIED(&in6p->in6p_faddr) &&
		    !IN6_ARE_ADDR_EQUAL(&in6p->in6p_faddr, &ip6->ip6_src))
			continue;
		if (in6p->in6p_cksum != -1) {
			RIP6_STATINC(RIP6_STAT_ISUM);
			if (in6_cksum(m, proto, *offp,
			    m->m_pkthdr.len - *offp)) {
				RIP6_STATINC(RIP6_STAT_BADSUM);
				continue;
			}
		}
		if (last) {
			struct	mbuf *n;

#ifdef IPSEC
			/*
			 * Check AH/ESP integrity
			 */
			if (ipsec_used && !ipsec6_in_reject(m, last))
#endif /* IPSEC */
			if ((n = m_copy(m, 0, (int)M_COPYALL)) != NULL) {
				if (last->in6p_flags & IN6P_CONTROLOPTS)
					ip6_savecontrol(last, &opts, ip6, n);
				/* strip intermediate headers */
				m_adj(n, *offp);
				if (sbappendaddr(&last->in6p_socket->so_rcv,
				    (struct sockaddr *)&rip6src, n, opts) == 0) {
					/* should notify about lost packet */
					m_freem(n);
					if (opts)
						m_freem(opts);
					RIP6_STATINC(RIP6_STAT_FULLSOCK);
				} else
					sorwakeup(last->in6p_socket);
				opts = NULL;
			}
		}
		last = in6p;
	}
#ifdef IPSEC
	if (ipsec_used && last && ipsec6_in_reject(m, last)) {
		m_freem(m);
		/*
		 * XXX ipsec6_in_reject update stat if there is an error
		 * so we just need to update stats by hand in the case of last is
		 * NULL
		 */
		if (!last)
			IPSEC6_STATINC(IPSEC_STAT_IN_POLVIO);
			IP6_STATDEC(IP6_STAT_DELIVERED);
			/* do not inject data into pcb */
		} else
#endif /* IPSEC */
	if (last) {
		if (last->in6p_flags & IN6P_CONTROLOPTS)
			ip6_savecontrol(last, &opts, ip6, m);
		/* strip intermediate headers */
		m_adj(m, *offp);
		if (sbappendaddr(&last->in6p_socket->so_rcv,
		    (struct sockaddr *)&rip6src, m, opts) == 0) {
			m_freem(m);
			if (opts)
				m_freem(opts);
			RIP6_STATINC(RIP6_STAT_FULLSOCK);
		} else
			sorwakeup(last->in6p_socket);
	} else {
		RIP6_STATINC(RIP6_STAT_NOSOCK);
		if (m->m_flags & M_MCAST)
			RIP6_STATINC(RIP6_STAT_NOSOCKMCAST);
		if (proto == IPPROTO_NONE)
			m_freem(m);
		else {
			u_int8_t *prvnxtp = ip6_get_prevhdr(m, *offp); /* XXX */
			in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_protounknown);
			icmp6_error(m, ICMP6_PARAM_PROB,
			    ICMP6_PARAMPROB_NEXTHEADER,
			    prvnxtp - mtod(m, u_int8_t *));
		}
		IP6_STATDEC(IP6_STAT_DELIVERED);
	}
	return IPPROTO_DONE;
}

void *
rip6_ctlinput(int cmd, const struct sockaddr *sa, void *d)
{
	struct ip6_hdr *ip6;
	struct ip6ctlparam *ip6cp = NULL;
	const struct sockaddr_in6 *sa6_src = NULL;
	void *cmdarg;
	void (*notify)(struct in6pcb *, int) = in6_rtchange;
	int nxt;

	if (sa->sa_family != AF_INET6 ||
	    sa->sa_len != sizeof(struct sockaddr_in6))
		return NULL;

	if ((unsigned)cmd >= PRC_NCMDS)
		return NULL;
	if (PRC_IS_REDIRECT(cmd))
		notify = in6_rtchange, d = NULL;
	else if (cmd == PRC_HOSTDEAD)
		d = NULL;
	else if (cmd == PRC_MSGSIZE)
		; /* special code is present, see below */
	else if (inet6ctlerrmap[cmd] == 0)
		return NULL;

	/* if the parameter is from icmp6, decode it. */
	if (d != NULL) {
		ip6cp = (struct ip6ctlparam *)d;
		ip6 = ip6cp->ip6c_ip6;
		cmdarg = ip6cp->ip6c_cmdarg;
		sa6_src = ip6cp->ip6c_src;
		nxt = ip6cp->ip6c_nxt;
	} else {
		ip6 = NULL;
		cmdarg = NULL;
		sa6_src = &sa6_any;
		nxt = -1;
	}

	if (ip6 && cmd == PRC_MSGSIZE) {
		const struct sockaddr_in6 *sa6 = (const struct sockaddr_in6 *)sa;
		int valid = 0;
		struct in6pcb *in6p;

		/*
		 * Check to see if we have a valid raw IPv6 socket
		 * corresponding to the address in the ICMPv6 message
		 * payload, and the protocol (ip6_nxt) meets the socket.
		 * XXX chase extension headers, or pass final nxt value
		 * from icmp6_notify_error()
		 */
		in6p = NULL;
		in6p = in6_pcblookup_connect(&raw6cbtable, &sa6->sin6_addr, 0,
					     (const struct in6_addr *)&sa6_src->sin6_addr, 0, 0, 0);
#if 0
		if (!in6p) {
			/*
			 * As the use of sendto(2) is fairly popular,
			 * we may want to allow non-connected pcb too.
			 * But it could be too weak against attacks...
			 * We should at least check if the local
			 * address (= s) is really ours.
			 */
			in6p = in6_pcblookup_bind(&raw6cbtable,
			    &sa6->sin6_addr, 0, 0);
		}
#endif

		if (in6p && in6p->in6p_ip6.ip6_nxt &&
		    in6p->in6p_ip6.ip6_nxt == nxt)
			valid++;

		/*
		 * Depending on the value of "valid" and routing table
		 * size (mtudisc_{hi,lo}wat), we will:
		 * - recalculate the new MTU and create the
		 *   corresponding routing entry, or
		 * - ignore the MTU change notification.
		 */
		icmp6_mtudisc_update((struct ip6ctlparam *)d, valid);

		/*
		 * regardless of if we called icmp6_mtudisc_update(),
		 * we need to call in6_pcbnotify(), to notify path MTU
		 * change to the userland (RFC3542), because some
		 * unconnected sockets may share the same destination
		 * and want to know the path MTU.
		 */
	}

	(void) in6_pcbnotify(&raw6cbtable, sa, 0,
	    (const struct sockaddr *)sa6_src, 0, cmd, cmdarg, notify);
	return NULL;
}

/*
 * Generate IPv6 header and pass packet to ip6_output.
 * Tack on options user may have setup with control call.
 */
int
rip6_output(struct mbuf *m, struct socket * const so,
    struct sockaddr_in6 * const dstsock, struct mbuf * const control)
{
	struct in6_addr *dst;
	struct ip6_hdr *ip6;
	struct in6pcb *in6p;
	u_int	plen = m->m_pkthdr.len;
	int error = 0;
	struct ip6_pktopts opt, *optp = NULL;
	struct ifnet *oifp = NULL;
	int type, code;		/* for ICMPv6 output statistics only */
	int scope_ambiguous = 0;
	struct in6_addr *in6a;

	in6p = sotoin6pcb(so);

	dst = &dstsock->sin6_addr;
	if (control) {
		if ((error = ip6_setpktopts(control, &opt,
		    in6p->in6p_outputopts,
		    kauth_cred_get(), so->so_proto->pr_protocol)) != 0) {
			goto bad;
		}
		optp = &opt;
	} else
		optp = in6p->in6p_outputopts;

	/*
	 * Check and convert scope zone ID into internal form.
	 * XXX: we may still need to determine the zone later.
	 */
	if (!(so->so_state & SS_ISCONNECTED)) {
		if (dstsock->sin6_scope_id == 0 && !ip6_use_defzone)
			scope_ambiguous = 1;
		if ((error = sa6_embedscope(dstsock, ip6_use_defzone)) != 0)
			goto bad;
	}

	/*
	 * For an ICMPv6 packet, we should know its type and code
	 * to update statistics.
	 */
	if (so->so_proto->pr_protocol == IPPROTO_ICMPV6) {
		struct icmp6_hdr *icmp6;
		if (m->m_len < sizeof(struct icmp6_hdr) &&
		    (m = m_pullup(m, sizeof(struct icmp6_hdr))) == NULL) {
			error = ENOBUFS;
			goto bad;
		}
		icmp6 = mtod(m, struct icmp6_hdr *);
		type = icmp6->icmp6_type;
		code = icmp6->icmp6_code;
	} else {
		type = 0;
		code = 0;
	}

	M_PREPEND(m, sizeof(*ip6), M_DONTWAIT);
	if (!m) {
		error = ENOBUFS;
		goto bad;
	}
	ip6 = mtod(m, struct ip6_hdr *);

	/*
	 * Next header might not be ICMP6 but use its pseudo header anyway.
	 */
	ip6->ip6_dst = *dst;

	/*
	 * Source address selection.
	 */
	if ((in6a = in6_selectsrc(dstsock, optp, in6p->in6p_moptions,
	    &in6p->in6p_route, &in6p->in6p_laddr, &oifp,
	    &error)) == 0) {
		if (error == 0)
			error = EADDRNOTAVAIL;
		goto bad;
	}
	ip6->ip6_src = *in6a;

	if (oifp && scope_ambiguous) {
		/*
		 * Application should provide a proper zone ID or the use of
		 * default zone IDs should be enabled.  Unfortunately, some
		 * applications do not behave as it should, so we need a
		 * workaround.  Even if an appropriate ID is not determined
		 * (when it's required), if we can determine the outgoing
		 * interface. determine the zone ID based on the interface.
		 */
		error = in6_setscope(&dstsock->sin6_addr, oifp, NULL);
		if (error != 0)
			goto bad;
	}
	ip6->ip6_dst = dstsock->sin6_addr;

	/* fill in the rest of the IPv6 header fields */
	ip6->ip6_flow = in6p->in6p_flowinfo & IPV6_FLOWINFO_MASK;
	ip6->ip6_vfc  &= ~IPV6_VERSION_MASK;
	ip6->ip6_vfc  |= IPV6_VERSION;
	/* ip6_plen will be filled in ip6_output, so not fill it here. */
	ip6->ip6_nxt   = in6p->in6p_ip6.ip6_nxt;
	ip6->ip6_hlim = in6_selecthlim(in6p, oifp);

	if (so->so_proto->pr_protocol == IPPROTO_ICMPV6 ||
	    in6p->in6p_cksum != -1) {
		int off;
		u_int16_t sum;

		/* compute checksum */
		if (so->so_proto->pr_protocol == IPPROTO_ICMPV6)
			off = offsetof(struct icmp6_hdr, icmp6_cksum);
		else
			off = in6p->in6p_cksum;
		if (plen < off + 1) {
			error = EINVAL;
			goto bad;
		}
		off += sizeof(struct ip6_hdr);

		sum = 0;
		m = m_copyback_cow(m, off, sizeof(sum), (void *)&sum,
		    M_DONTWAIT);
		if (m == NULL) {
			error = ENOBUFS;
			goto bad;
		}
		sum = in6_cksum(m, ip6->ip6_nxt, sizeof(*ip6), plen);
		m = m_copyback_cow(m, off, sizeof(sum), (void *)&sum,
		    M_DONTWAIT);
		if (m == NULL) {
			error = ENOBUFS;
			goto bad;
		}
	}

	error = ip6_output(m, optp, &in6p->in6p_route, 0,
	    in6p->in6p_moptions, so, &oifp);
	if (so->so_proto->pr_protocol == IPPROTO_ICMPV6) {
		if (oifp)
			icmp6_ifoutstat_inc(oifp, type, code);
		ICMP6_STATINC(ICMP6_STAT_OUTHIST + type);
	} else
		RIP6_STATINC(RIP6_STAT_OPACKETS);

	goto freectl;

 bad:
	if (m)
		m_freem(m);

 freectl:
	if (control) {
		ip6_clearpktopts(&opt, -1);
		m_freem(control);
	}
	return error;
}

/*
 * Raw IPv6 socket option processing.
 */
int
rip6_ctloutput(int op, struct socket *so, struct sockopt *sopt)
{
	int error = 0;

	if (sopt->sopt_level == SOL_SOCKET && sopt->sopt_name == SO_NOHEADER) {
		int optval;

		/* need to fiddle w/ opt(IPPROTO_IPV6, IPV6_CHECKSUM)? */
		if (op == PRCO_GETOPT) {
			optval = 1;
			error = sockopt_set(sopt, &optval, sizeof(optval));
		} else if (op == PRCO_SETOPT) {
			error = sockopt_getint(sopt, &optval);
			if (error)
				goto out;
			if (optval == 0)
				error = EINVAL;
		}

		goto out;
	} else if (sopt->sopt_level != IPPROTO_IPV6)
		return ip6_ctloutput(op, so, sopt);

	switch (sopt->sopt_name) {
	case MRT6_INIT:
	case MRT6_DONE:
	case MRT6_ADD_MIF:
	case MRT6_DEL_MIF:
	case MRT6_ADD_MFC:
	case MRT6_DEL_MFC:
	case MRT6_PIM:
		if (op == PRCO_SETOPT)
			error = ip6_mrouter_set(so, sopt);
		else if (op == PRCO_GETOPT)
			error = ip6_mrouter_get(so, sopt);
		else
			error = EINVAL;
		break;
	case IPV6_CHECKSUM:
		return ip6_raw_ctloutput(op, so, sopt);
	default:
		return ip6_ctloutput(op, so, sopt);
	}
 out:
	return error;
}

extern	u_long rip6_sendspace;
extern	u_long rip6_recvspace;

int
rip6_attach(struct socket *so, int proto)
{
	struct in6pcb *in6p;
	int s, error;

	KASSERT(sotoin6pcb(so) == NULL);
	sosetlock(so);

	error = kauth_authorize_network(curlwp->l_cred,
	    KAUTH_NETWORK_SOCKET, KAUTH_REQ_NETWORK_SOCKET_RAWSOCK,
	    KAUTH_ARG(AF_INET6),
	    KAUTH_ARG(SOCK_RAW),
	    KAUTH_ARG(so->so_proto->pr_protocol));
	if (error) {
		return error;
	}
	s = splsoftnet();
	error = soreserve(so, rip6_sendspace, rip6_recvspace);
	if (error) {
		splx(s);
		return error;
	}
	if ((error = in6_pcballoc(so, &raw6cbtable)) != 0) {
		splx(s);
		return error;
	}
	splx(s);
	in6p = sotoin6pcb(so);
	in6p->in6p_ip6.ip6_nxt = proto;
	in6p->in6p_cksum = -1;

	in6p->in6p_icmp6filt = kmem_alloc(sizeof(struct icmp6_filter), KM_SLEEP);
	if (in6p->in6p_icmp6filt == NULL) {
		in6_pcbdetach(in6p);
		return ENOMEM;
	}
	ICMP6_FILTER_SETPASSALL(in6p->in6p_icmp6filt);
	KASSERT(solocked(so));
	return error;
}

static void
rip6_detach(struct socket *so)
{
	struct in6pcb *in6p = sotoin6pcb(so);

	KASSERT(solocked(so));
	KASSERT(in6p != NULL);

	if (so == ip6_mrouter) {
		ip6_mrouter_done();
	}
	/* xxx: RSVP */
	if (in6p->in6p_icmp6filt != NULL) {
		kmem_free(in6p->in6p_icmp6filt, sizeof(struct icmp6_filter));
		in6p->in6p_icmp6filt = NULL;
	}
	in6_pcbdetach(in6p);
}

static int
rip6_accept(struct socket *so, struct mbuf *nam)
{
	KASSERT(solocked(so));

	return EOPNOTSUPP;
}

static int
rip6_bind(struct socket *so, struct mbuf *nam, struct lwp *l)
{
	struct in6pcb *in6p = sotoin6pcb(so);
	struct sockaddr_in6 *addr;
	struct ifaddr *ia = NULL;
	int error = 0;

	KASSERT(solocked(so));
	KASSERT(in6p != NULL);
	KASSERT(nam != NULL);

	addr = mtod(nam, struct sockaddr_in6 *);
	if (nam->m_len != sizeof(*addr))
		return EINVAL;
	if (IFNET_EMPTY() || addr->sin6_family != AF_INET6)
		return EADDRNOTAVAIL;

	if ((error = sa6_embedscope(addr, ip6_use_defzone)) != 0)
		return error;

	/*
	 * we don't support mapped address here, it would confuse
	 * users so reject it
	 */
	if (IN6_IS_ADDR_V4MAPPED(&addr->sin6_addr))
		return EADDRNOTAVAIL;
	if (!IN6_IS_ADDR_UNSPECIFIED(&addr->sin6_addr) &&
	    (ia = ifa_ifwithaddr((struct sockaddr *)addr)) == 0)
		return EADDRNOTAVAIL;
	if (ia && ((struct in6_ifaddr *)ia)->ia6_flags &
	    (IN6_IFF_ANYCAST|IN6_IFF_NOTREADY|
	     IN6_IFF_DETACHED|IN6_IFF_DEPRECATED))
		return EADDRNOTAVAIL;
	in6p->in6p_laddr = addr->sin6_addr;
	return 0;
}

static int
rip6_listen(struct socket *so, struct lwp *l)
{
	KASSERT(solocked(so));

	return EOPNOTSUPP;
}

static int
rip6_connect(struct socket *so, struct mbuf *nam, struct lwp *l)
{
	struct in6pcb *in6p = sotoin6pcb(so);
	struct sockaddr_in6 *addr;
	struct in6_addr *in6a = NULL;
	struct ifnet *ifp = NULL;
	int scope_ambiguous = 0;
	int error = 0;

	KASSERT(solocked(so));
	KASSERT(in6p != NULL);
	KASSERT(nam != NULL);

	addr = mtod(nam, struct sockaddr_in6 *);

	if (nam->m_len != sizeof(*addr))
		return EINVAL;
	if (IFNET_EMPTY())
		return EADDRNOTAVAIL;
	if (addr->sin6_family != AF_INET6)
		return EAFNOSUPPORT;

	/*
	 * Application should provide a proper zone ID or the use of
	 * default zone IDs should be enabled.  Unfortunately, some
	 * applications do not behave as it should, so we need a
	 * workaround.  Even if an appropriate ID is not determined,
	 * we'll see if we can determine the outgoing interface.  If we
	 * can, determine the zone ID based on the interface below.
	 */
	if (addr->sin6_scope_id == 0 && !ip6_use_defzone)
		scope_ambiguous = 1;
	if ((error = sa6_embedscope(addr, ip6_use_defzone)) != 0)
		return error;

	/* Source address selection. XXX: need pcblookup? */
	in6a = in6_selectsrc(addr, in6p->in6p_outputopts,
	    in6p->in6p_moptions, &in6p->in6p_route,
	    &in6p->in6p_laddr, &ifp, &error);
	if (in6a == NULL) {
		if (error == 0)
			return EADDRNOTAVAIL;
		return error;
	}
	/* XXX: see above */
	if (ifp && scope_ambiguous &&
	    (error = in6_setscope(&addr->sin6_addr, ifp, NULL)) != 0) {
		return error;
	}
	in6p->in6p_laddr = *in6a;
	in6p->in6p_faddr = addr->sin6_addr;
	soisconnected(so);
	return error;
}

static int
rip6_connect2(struct socket *so, struct socket *so2)
{
	KASSERT(solocked(so));

	return EOPNOTSUPP;
}

static int
rip6_disconnect(struct socket *so)
{
	struct in6pcb *in6p = sotoin6pcb(so);

	KASSERT(solocked(so));
	KASSERT(in6p != NULL);

	if ((so->so_state & SS_ISCONNECTED) == 0)
		return ENOTCONN;

	in6p->in6p_faddr = in6addr_any;
	so->so_state &= ~SS_ISCONNECTED;	/* XXX */
	return 0;
}

static int
rip6_shutdown(struct socket *so)
{
	KASSERT(solocked(so));

	/*
	 * Mark the connection as being incapable of futther input.
	 */
	socantsendmore(so);
	return 0;
}

static int
rip6_abort(struct socket *so)
{
	KASSERT(solocked(so));

	soisdisconnected(so);
	rip6_detach(so);
	return 0;
}

static int
rip6_ioctl(struct socket *so, u_long cmd, void *nam, struct ifnet *ifp)
{
	return in6_control(so, cmd, nam, ifp);
}

static int
rip6_stat(struct socket *so, struct stat *ub)
{
	KASSERT(solocked(so));

	/* stat: don't bother with a blocksize */
	return 0;
}

static int
rip6_peeraddr(struct socket *so, struct mbuf *nam)
{
	KASSERT(solocked(so));
	KASSERT(sotoin6pcb(so) != NULL);
	KASSERT(nam != NULL);

	in6_setpeeraddr(sotoin6pcb(so), nam);
	return 0;
}

static int
rip6_sockaddr(struct socket *so, struct mbuf *nam)
{
	KASSERT(solocked(so));
	KASSERT(sotoin6pcb(so) != NULL);
	KASSERT(nam != NULL);

	in6_setsockaddr(sotoin6pcb(so), nam);
	return 0;
}

static int
rip6_rcvd(struct socket *so, int flags, struct lwp *l)
{
	KASSERT(solocked(so));

	return EOPNOTSUPP;
}

static int
rip6_recvoob(struct socket *so, struct mbuf *m, int flags)
{
	KASSERT(solocked(so));

	return EOPNOTSUPP;
}

static int
rip6_send(struct socket *so, struct mbuf *m, struct mbuf *nam,
    struct mbuf *control, struct lwp *l)
{
	struct in6pcb *in6p = sotoin6pcb(so);
	struct sockaddr_in6 tmp;
	struct sockaddr_in6 *dst;
	int error = 0;

	KASSERT(solocked(so));
	KASSERT(in6p != NULL);
	KASSERT(m != NULL);

	/*
	 * Ship a packet out. The appropriate raw output
	 * routine handles any messaging necessary.
	 */

	/* always copy sockaddr to avoid overwrites */
	if (so->so_state & SS_ISCONNECTED) {
		if (nam) {
			error = EISCONN;
			goto release;
		}
		/* XXX */
		sockaddr_in6_init(&tmp, &in6p->in6p_faddr, 0, 0, 0);
		dst = &tmp;
	} else {
		if (nam == NULL) {
			error = ENOTCONN;
			goto release;
		}
		if (nam->m_len != sizeof(tmp)) {
			error = EINVAL;
			goto release;
		}

		tmp = *mtod(nam, struct sockaddr_in6 *);
		dst = &tmp;

		if (dst->sin6_family != AF_INET6) {
			error = EAFNOSUPPORT;
			goto release;
		}
	}
	error = rip6_output(m, so, dst, control);
	m = NULL;

release:
	if (m)
		m_freem(m);

	return error;
}

static int
rip6_sendoob(struct socket *so, struct mbuf *m, struct mbuf *control)
{
	KASSERT(solocked(so));

	if (m)
	 	m_freem(m);

	return EOPNOTSUPP;
}

static int
rip6_purgeif(struct socket *so, struct ifnet *ifp)
{

	mutex_enter(softnet_lock);
	in6_pcbpurgeif0(&raw6cbtable, ifp);
	in6_purgeif(ifp);
	in6_pcbpurgeif(&raw6cbtable, ifp);
	mutex_exit(softnet_lock);

	return 0;
}

int
rip6_usrreq(struct socket *so, int req, struct mbuf *m,
	struct mbuf *nam, struct mbuf *control, struct lwp *l)
{

	KASSERT(req != PRU_ACCEPT);
	KASSERT(req != PRU_BIND);
	KASSERT(req != PRU_LISTEN);
	KASSERT(req != PRU_CONNECT);
	KASSERT(req != PRU_CONNECT2);
	KASSERT(req != PRU_DISCONNECT);
	KASSERT(req != PRU_SHUTDOWN);
	KASSERT(req != PRU_ABORT);
	KASSERT(req != PRU_CONTROL);
	KASSERT(req != PRU_SENSE);
	KASSERT(req != PRU_PEERADDR);
	KASSERT(req != PRU_SOCKADDR);
	KASSERT(req != PRU_RCVD);
	KASSERT(req != PRU_RCVOOB);
	KASSERT(req != PRU_SEND);
	KASSERT(req != PRU_PURGEIF);
	KASSERT(req != PRU_SENDOOB);

	panic("rip6_usrreq");

	return 0;
}

static int
sysctl_net_inet6_raw6_stats(SYSCTLFN_ARGS)
{

	return (NETSTAT_SYSCTL(rip6stat_percpu, RIP6_NSTATS));
}

static void
sysctl_net_inet6_raw6_setup(struct sysctllog **clog)
{

	sysctl_createv(clog, 0, NULL, NULL,
		       CTLFLAG_PERMANENT,
		       CTLTYPE_NODE, "inet6", NULL,
		       NULL, 0, NULL, 0,
		       CTL_NET, PF_INET6, CTL_EOL);
	sysctl_createv(clog, 0, NULL, NULL,
		       CTLFLAG_PERMANENT,
		       CTLTYPE_NODE, "raw6",
		       SYSCTL_DESCR("Raw IPv6 settings"),
		       NULL, 0, NULL, 0,
		       CTL_NET, PF_INET6, IPPROTO_RAW, CTL_EOL);

	sysctl_createv(clog, 0, NULL, NULL,
		       CTLFLAG_PERMANENT,
		       CTLTYPE_STRUCT, "pcblist",
		       SYSCTL_DESCR("Raw IPv6 control block list"),
		       sysctl_inpcblist, 0, &raw6cbtable, 0,
		       CTL_NET, PF_INET6, IPPROTO_RAW,
		       CTL_CREATE, CTL_EOL);
	sysctl_createv(clog, 0, NULL, NULL,
		       CTLFLAG_PERMANENT,
		       CTLTYPE_STRUCT, "stats",
		       SYSCTL_DESCR("Raw IPv6 statistics"),
		       sysctl_net_inet6_raw6_stats, 0, NULL, 0,
		       CTL_NET, PF_INET6, IPPROTO_RAW, RAW6CTL_STATS,
		       CTL_EOL);
}

PR_WRAP_USRREQS(rip6)
#define	rip6_attach		rip6_attach_wrapper
#define	rip6_detach		rip6_detach_wrapper
#define	rip6_accept		rip6_accept_wrapper
#define	rip6_bind		rip6_bind_wrapper
#define	rip6_listen		rip6_listen_wrapper
#define	rip6_connect		rip6_connect_wrapper
#define	rip6_connect2		rip6_connect2_wrapper
#define	rip6_disconnect		rip6_disconnect_wrapper
#define	rip6_shutdown		rip6_shutdown_wrapper
#define	rip6_abort		rip6_abort_wrapper
#define	rip6_ioctl		rip6_ioctl_wrapper
#define	rip6_stat		rip6_stat_wrapper
#define	rip6_peeraddr		rip6_peeraddr_wrapper
#define	rip6_sockaddr		rip6_sockaddr_wrapper
#define	rip6_rcvd		rip6_rcvd_wrapper
#define	rip6_recvoob		rip6_recvoob_wrapper
#define	rip6_send		rip6_send_wrapper
#define	rip6_sendoob		rip6_sendoob_wrapper
#define	rip6_purgeif		rip6_purgeif_wrapper
#define	rip6_usrreq		rip6_usrreq_wrapper

const struct pr_usrreqs rip6_usrreqs = {
	.pr_attach	= rip6_attach,
	.pr_detach	= rip6_detach,
	.pr_accept	= rip6_accept,
	.pr_bind	= rip6_bind,
	.pr_listen	= rip6_listen,
	.pr_connect	= rip6_connect,
	.pr_connect2	= rip6_connect2,
	.pr_disconnect	= rip6_disconnect,
	.pr_shutdown	= rip6_shutdown,
	.pr_abort	= rip6_abort,
	.pr_ioctl	= rip6_ioctl,
	.pr_stat	= rip6_stat,
	.pr_peeraddr	= rip6_peeraddr,
	.pr_sockaddr	= rip6_sockaddr,
	.pr_rcvd	= rip6_rcvd,
	.pr_recvoob	= rip6_recvoob,
	.pr_send	= rip6_send,
	.pr_sendoob	= rip6_sendoob,
	.pr_purgeif	= rip6_purgeif,
	.pr_generic	= rip6_usrreq,
};


text: In this section you can learn about solutions to common UI tasks.

redpajama_set_name: RedPajamaGithub


text:
fiddle-0024-BarChart
======

![Screenshot](screenshot.png)

### Title

Bar Chart

### Creation Date

03-27-16

### Location

Chicago, IL

### Description

D3 fiddle exploring how to create a bar chart with the following requirements:

*  x axis should use an ordinal scale and be labelled along the bottom
*  y axis should use a linear scale and rendered along left side of the chart
*  series bars should have a linear gradient
*  colors used in the gradient should be defined in a separate css file
*  the width and height of the chart should be based on the dimension of the window
*  the dimensions of the chart should refresh on window resize
*  the y axis should use a custom scale based on the values proximity to a fixed value (aka tolerance)

### Published Version Link

[codepen](http://codepen.io/bradyhouse/pen/GZvmjN)
[jsfiddle.net](https://jsfiddle.net/4bqc7s22/)

### Tags

d3: scale: ordinal, rangeRoundBands; axis: scale, orient


text:
/* jshint node: true */
'use strict';

module.exports = {
  name: 'ember-simple-auth',

  included: function(app) {
    this._super.included.apply(this, arguments);

    // see: https://github.com/ember-cli/ember-cli/issues/3718
    if (typeof app.import !== 'function' && app.app) {
      app = app.app;
    }

    app.import('vendor/ember-simple-auth/register-version.js');
  }
};


text:
package org.apache.druid.query.materializedview;

import com.fasterxml.jackson.annotation.JsonProperty;
import org.joda.time.Period;

public class MaterializedViewConfig
{
  @JsonProperty
  private Period pollDuration = new Period("PT1M");

  public Period getPollDuration()
  {
    return pollDuration;
  }

}


text:
using System;
using NUnit.Framework;

namespace MonoTests.System  {

	[TestFixture]
	public class UIntPtrTest : Assertion {

		[Test]
		[ExpectedException (typeof (OverflowException))]
		public void Test64on32 ()
		{
			if (UIntPtr.Size > 4)
				throw new OverflowException ("Test only applicable to 32bits machines");

			ulong addr = UInt32.MaxValue;
			UIntPtr p = new UIntPtr (addr + 1);
		}

		[Test]
		public void TestUlongOn32 ()
		{
			// int64 can be used (as a type) with a 32bits address
			ulong max32 = UInt32.MaxValue;
			UIntPtr p32max = new UIntPtr (max32);

			ulong min32 = UInt32.MinValue;
			UIntPtr p32min = new UIntPtr (min32);
		}

		[Test]
		public void Test64on64 ()
		{
			// for 64 bits machines
			if (UIntPtr.Size > 4) {
				UIntPtr pmax = new UIntPtr (UInt64.MaxValue);
				AssertEquals ("Max", UInt64.MaxValue, (ulong) pmax);

				UIntPtr pmin = new UIntPtr (UInt64.MinValue);
				AssertEquals ("Min", UInt64.MinValue, (ulong) pmin);
			}
		}
	}
}


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

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
org.yaml.snakeyaml.util (SnakeYAML 1.11 API)
</TITLE>

<META NAME="keywords" CONTENT="org.yaml.snakeyaml.util package">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

org.yaml.snakeyaml.util

Classes

ArrayStack

UriEncoder


text:
Ppt2txt
=======

PowerPoint Slide Deck Text Extractor
------------------------------------

For more information, please refer to

http://thebuildingcoder.typepad.com/blog/2012/10/powerpoint-slide-deck-text-extractor-ppt2txt.html


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
Flora, Jena 68: 43 (1885)

#### Original name
Lecanora pyracea f. submersa Nyl.

### Remarks
null


text:
package de.gishmo.module0812.domain.dto.shared.transport.response;

import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeName;

import de.gishmo.module0812.domain.dto.shared.model.Person;

@JsonTypeName("PersonUpdateResponse")
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXTERNAL_PROPERTY)
public class PersonUpdateResponse extends AbstractResponse {

	private Person person;

	public PersonUpdateResponse() {
		super();
	}

  public Person getPerson() {
    return person;
  }

  public void setPerson(Person person) {
    this.person = person;
  }

}


text:
package com.hardcopy.retrowatchle.contents;

public interface IFeedListener {
	public static final int MSG_FEED_UPDATED = 1;

	public void OnFeedCallback(int msgType, int arg0, int arg1, String arg2, String arg3, Object arg4);
}


text:
class LibraryClass2{
  LibraryClass1 libClass1;
}


text:
"""The ants module provides basic functions for interfacing with ants functions.

   Change directory to provide relative paths for doctests
   >>> import os
   >>> filepath = os.path.dirname( os.path.realpath( __file__ ) )
   >>> datadir = os.path.realpath(os.path.join(filepath, '../../testing/data'))
   >>> os.chdir(datadir)

"""

# Standard library imports
import os
from glob import glob

# Local imports
from ..base import (TraitedSpec, File, traits, OutputMultiPath)
from ...utils.filemanip import split_filename
from .base import ANTSCommand, ANTSCommandInputSpec

class BuildTemplateInputSpec(ANTSCommandInputSpec):
    dimension = traits.Enum(3, 2, argstr='-d %d', usedefault=True,
                             desc='image dimension (2 or 3)', position=1)
    out_prefix = traits.Str('antsTMPL_', argstr='-o %s', usedefault=True,
                             desc=('Prefix that is prepended to all output '
                                   'files (default = antsTMPL_)'))
    in_files = traits.List(File(exists=True), mandatory=True,
                             desc='list of images to generate template from',
                             argstr='%s', position=-1)
    parallelization = traits.Enum(0, 1, 2, argstr='-c %d', usedefault=True,
                             desc=('control for parallel processing (0 = '
                                   'serial, 1 = use PBS, 2 = use PEXEC, 3 = '
                                   'use Apple XGrid'))
    gradient_step_size = traits.Float(argstr='-g %f',
                                      desc=('smaller magnitude results in '
                                            'more cautious steps (default = '
                                            '.25)'))
    iteration_limit = traits.Int(4, argstr='-i %d', usedefault=True,
                                 desc='iterations of template construction')
    num_cores = traits.Int(argstr='-j %d', requires=['parallelization'],
                           desc=('Requires parallelization = 2 (PEXEC). '
                                 'Sets number of cpu cores to use'))
    max_iterations = traits.List(traits.Int, argstr='-m %s', sep='x',
                             desc=('maximum number of iterations (must be '
                                   'list of integers in the form [J,K,L...]: '
                                   'J = coarsest resolution iterations, K = '
                                   'middle resolution interations, L = fine '
                                   'resolution iterations'))
    bias_field_correction = traits.Bool(argstr='-n 1',
                             desc=('Applies bias field correction to moving '
                                   'image'))
    rigid_body_registration = traits.Bool(argstr='-r 1',
                             desc=('registers inputs before creating template '
                                   '(useful if no initial template available)'))
    similarity_metric = traits.Enum('PR', 'CC', 'MI', 'MSQ', argstr='-s %s',
             desc=('Type of similartiy metric used for registration '
                   '(CC = cross correlation, MI = mutual information, '
                   'PR = probability mapping, MSQ = mean square difference)'))
    transformation_model = traits.Enum('GR', 'EL', 'SY', 'S2', 'EX', 'DD',
                                       argstr='-t %s', usedefault=True,
             desc=('Type of transofmration model used for registration '
                   '(EL = elastic transformation model, SY = SyN with time, '
                   'arbitrary number of time points, S2 =  SyN with time '
                   'optimized for 2 time points, GR = greedy SyN, EX = '
                   'exponential, DD = diffeomorphic demons style exponential '
                   'mapping'))
    use_first_as_target = traits.Bool(desc=('uses first volume as target of '
                                            'all inputs. When not used, an '
                                            'unbiased average image is used '
                                            'to start.'))

class BuildTemplateOutputSpec(TraitedSpec):
    final_template_file = File(exists=True, desc='final ANTS template')
    template_files = OutputMultiPath(File(exists=True),
                           desc='Templates from different stages of iteration')
    subject_outfiles = OutputMultiPath(File(exists=True),
                        desc=('Outputs for each input image. Includes warp '
                              'field, inverse warp, Affine, original image '
                              '(repaired) and warped image (deformed)'))

class BuildTemplate(ANTSCommand):
    """Generate a optimal average template

    .. warning::

      This can take a VERY long time to complete

    Examples
    --------

    >>> from nipype.interfaces.ants import BuildTemplate
    >>> tmpl = BuildTemplate()
    >>> tmpl.inputs.in_files = ['T1.nii', 'structural.nii']
    >>> tmpl.inputs.max_iterations = [30, 90, 20]
    >>> tmpl.cmdline
    'buildtemplateparallel.sh -d 3 -i 4 -m 30x90x20 -o antsTMPL_ -c 0 -t GR T1.nii structural.nii'

    """

    _cmd = 'buildtemplateparallel.sh'
    input_spec = BuildTemplateInputSpec
    output_spec = BuildTemplateOutputSpec

    def _format_arg(self, opt, spec, val):
        if opt == 'num_cores':
            if self.inputs.parallelization == 2:
                return '-j ' + val
            else:
                return ''
        if opt == 'in_files':
            if self.inputs.use_first_as_target:
                start = '-z '
            else:
                start = ''
            return start + ' '.join([os.path.split(name)[1] for name in val])
        return super(BuildTemplate, self)._format_arg(opt, spec, val)

    def _list_outputs(self):
        outputs = self._outputs().get()
        outputs['template_files'] = []
        for i in range(len(glob(os.path.realpath('*iteration*')))):
            temp = os.path.realpath('%s_iteration_%d/%stemplate.nii.gz' %
                                    (self.inputs.transformation_model,
                                     i,
                                     self.inputs.out_prefix))
            os.rename(temp,
                      os.path.realpath('%s_iteration_%d/%stemplate_i%d.nii.gz' %
                                       (self.inputs.transformation_model,
                                        i,
                                        self.inputs.out_prefix,
                                        i)))
            file_ = ('%s_iteration_%d/%stemplate_i%d.nii.gz' %
                     (self.inputs.transformation_model,
                      i,
                      self.inputs.out_prefix,
                      i))

            outputs['template_files'].append(os.path.realpath(file_))
            outputs['final_template_file'] = \
                  os.path.realpath('%stemplate.nii.gz' %
                                   self.inputs.out_prefix)
        outputs['subject_outfiles'] = []
        for filename in self.inputs.in_files:
            _, base, _ = split_filename(filename)
            temp = glob(os.path.realpath('%s%s*' % (self.inputs.out_prefix,
                                                    base)))
            for file_ in temp:
                outputs['subject_outfiles'].append(file_)
        return outputs


text:
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Akeneo.Serialization;
using Newtonsoft.Json;

namespace Akeneo.Http
{
	public static class HttpClientExtensions
	{
		public static Task<HttpResponseMessage> PostJsonAsync<TContent>(this HttpClient client, string uri, TContent content, JsonSerializerSettings setting, CancellationToken ct = default (CancellationToken))
		{
			return client.PostAsync(uri, new JsonContent(content, setting), ct);
		}

		public static Task<HttpResponseMessage> PostJsonAsync<TContent>(this HttpClient client, string uri, TContent content,  CancellationToken ct = default(CancellationToken))
		{
			return client.PostJsonAsync(uri, content, AkeneoSerializerSettings.Create, ct);
		}

		public static Task<HttpResponseMessage> PatchAsJsonAsync<TContent>(this HttpClient client, string requestUri, TContent content, CancellationToken ct)
		{
			return client.PatchAsJsonAsync(requestUri, content, AkeneoSerializerSettings.Update, ct);
		}

		public static Task<HttpResponseMessage> PatchAsJsonAsync<TContent>(this HttpClient client, string requestUri, TContent content, JsonSerializerSettings setting, CancellationToken ct)
		{
			return client.PatchAsync(requestUri, new JsonContent(content, setting), ct);
		}

		public static Task<HttpResponseMessage> PatchAsJsonCollectionAsync<TContent>(this HttpClient client, string requestUri, IEnumerable<TContent> content, CancellationToken ct)
		{
			return client.PatchAsync(requestUri, new JsonCollectionContent<TContent>(content), ct);
		}

		public static Task<HttpResponseMessage> PatchAsync(this HttpClient client, string requestUri, HttpContent content, CancellationToken ct)
		{
			var request = new HttpRequestMessage(
				new HttpMethod("PATCH"),
				new Uri(requestUri, UriKind.Relative))
			{
				Content = content
			};
			return client.SendAsync(request, ct);
		}
	}
}


text:
package com.intellij.plugins.haxe.ide;

import javax.annotation.Nonnull;

import com.intellij.lang.BracePair;
import com.intellij.lang.PairedBraceMatcher;
import com.intellij.plugins.haxe.lang.lexer.HaxeTokenTypes;
import com.intellij.psi.PsiFile;
import com.intellij.psi.tree.IElementType;

import javax.annotation.Nullable;

/**
 * @author: Fedor.Korotkov
 */
public class HaxeBraceMatcher implements PairedBraceMatcher {

  private static final BracePair[] PAIRS = new BracePair[]{
    new BracePair(HaxeTokenTypes.PLCURLY, HaxeTokenTypes.PRCURLY, false),
    new BracePair(HaxeTokenTypes.PLBRACK, HaxeTokenTypes.PRBRACK, false),
    new BracePair(HaxeTokenTypes.PLPAREN, HaxeTokenTypes.PRPAREN, false)
  };

  @Override
  public BracePair[] getPairs() {
    return PAIRS;
  }

  @Override
  public boolean isPairedBracesAllowedBeforeType(@Nonnull IElementType lbraceType, @Nullable IElementType contextType) {
    return true;
  }

  @Override
  public int getCodeConstructStart(PsiFile file, int openingBraceOffset) {
    return openingBraceOffset;
  }
}


text:
pub use self::simple::Simple;

pub mod simple;

use crate::{Error, Settings};
use std::io::prelude::*;

pub trait Transport
{
    fn process_data(&mut self,
                    read: &mut dyn Read,
                    settings: &Settings)
        -> Result<(), Error>;

    fn receive_raw_packet(&mut self)
        -> Result<Option<Vec<u8>>, Error>;

    fn send_raw_packet(&mut self,
                       write: &mut dyn Write,
                       packet: &[u8],
                       settings: &Settings)
        -> Result<(), Error>;
}


text:
<!doctype html>

	<meta charset="utf-8"/>
	<title>SIML -- Try it out!</title>

Try out SIML

				Angular mode [?] <input id="doAngular" type="checkbox" checked />

				FORCE curlies? [for nesting] <input id="curly" type="checkbox" />

// SIML can do fancy-pants tabby HTML:

section

    header > h1 'Hi there!'

    p 'This is a demo of SIML'

    p 'Try typing something...'

    p > small

        '

        Tip: Tick "Force curlies?" if you

        wanna force SIML to parse without paying

        attention to indentation level.

        '

hr //-------------------------------------------

// SIML can do HTML that looks like CSS

form {

    fieldset {

        label {

            for: "your-name";

            text: "Enter something..."

        }

        input.something#your-name {

            placeholder: " something ";

        }

    }

}

hr //-------------------------------------------

// SIML can do one-liners with vowelless quick tags:

ftr>(strng{'SIML'} 'is on ' a[href='//git.io/siml']'Github')


text:
      Experiment: {{ experiment.name }}
      {% if experiment.version > 1 %}v{{ experiment.version }}{% endif %}

      {{ experiment.start_time.strftime('%Y-%m-%d') }}
      <form class="form-reset-experiment" action="{{ url_for('.reset_experiment', experiment=experiment.name) }}" method="post">
        <input type="submit" class="btn" value="Reset Data">
      </form>
      <form class="form-delete-experiment" action="{{ url_for('.delete_experiment', experiment=experiment.name) }}" method="post">
        <input type="submit" class="btn btn-danger" value="Delete">
      </form>

        Alternative Name
        Participants
        Non-finished
        Completed
        Conversion Rate
        Confidence
        Finish

        Totals
        {{ experiment.total_participants }}
        {{ experiment.total_participants - experiment.total_completed }}
        {{ experiment.total_completed }}
        N/A
        N/A
        N/A

      {% for alternative in experiment.alternatives %}

            {{ alternative.name }}
            {% if alternative.is_control %}
              control
            {% endif %}

          {{ alternative.participant_count }}
          {{ alternative.participant_count - alternative.completed_count }}
          {{ alternative.completed_count }}

            {{ alternative.conversion_rate|percentage }}
            {% if experiment.control.conversion_rate > 0 and not alternative.is_control %}
              {% if alternative.conversion_rate > experiment.control.conversion_rate %}

                  +{{ ((alternative.conversion_rate / experiment.control.conversion_rate) - 1)|percentage }}

              {% elif alternative.conversion_rate < experiment.control.conversion_rate %}

                  {{ ((alternative.conversion_rate / experiment.control.conversion_rate) - 1)|percentage }}

              {% endif %}
            {% endif %}

              {{ alternative.confidence_level }}

            {% if experiment.winner %}
              {% if experiment.winner.name == alternative.name %}
                Winner
              {% else %}
                Loser
              {% endif %}
            {% else %}
              <form class="form-set-winner" action="{{ url_for('.set_experiment_winner', experiment=experiment.name) }}" method="post">
                <input type="hidden" name="alternative" value="{{ alternative.name }}">
                <input type="submit" value="Use this" class="btn btn-success btn-mini">
              </form>
            {% endif %}

      {% endfor %}


text:
MPL_TEST_CASE()
{
    typedef joint_view<
          range_c<int,0,10>
        , range_c<int,10,15>
        > numbers;

    typedef range_c<int,0,15> answer;

    MPL_ASSERT(( equal<numbers,answer> ));
    MPL_ASSERT_RELATION( size<numbers>::value, ==, 15 );
}

template< typename View > struct test_is_empty
{
    typedef typename begin<View>::type first_;
    typedef typename end<View>::type last_;

    MPL_ASSERT_RELATION( size<View>::value, ==, 0 );
    MPL_ASSERT(( is_same< first_,last_> ));

    MPL_ASSERT_INSTANTIATION( View );
    MPL_ASSERT_INSTANTIATION( first_ );
    MPL_ASSERT_INSTANTIATION( last_ );
};

MPL_TEST_CASE()
{
    test_is_empty< joint_view< list0<>,list0<> > >();
    test_is_empty< joint_view< list<>,list0<> > >();
    test_is_empty< joint_view< list<>,list<> > >();
    test_is_empty< joint_view< list<>, joint_view< list0<>,list0<> > > >();
}


text:
namespace stoke {

class SearchGadget : public Search {
public:
  SearchGadget(Transform* transform, std::default_random_engine::result_type seed) :
    Search(transform) {
    set_seed(seed);
    set_beta(beta_arg);
  }
};

} // namespace stoke

#endif


text:
package org.neo4j.ogm.domain.cineasts.annotated;

import java.util.HashSet;
import java.util.Set;
import java.util.UUID;

import org.neo4j.ogm.annotation.GeneratedValue;
import org.neo4j.ogm.annotation.Id;
import org.neo4j.ogm.annotation.NodeEntity;
import org.neo4j.ogm.annotation.Relationship;
import org.neo4j.ogm.annotation.typeconversion.Convert;
import org.neo4j.ogm.id.UuidStrategy;
import org.neo4j.ogm.typeconversion.UuidStringConverter;

/**
 * @author Vince Bickers
 * @author Luanne Misquitta
 * @author Mark Angrish
 */
@NodeEntity
public class Actor {

    @Id
    @GeneratedValue(strategy = UuidStrategy.class)
    @Convert(UuidStringConverter.class)
    private UUID uuid;

    private String name;

    private Set<Movie> filmography;

    @Relationship(type = "ACTS_IN", direction = Relationship.Direction.OUTGOING)
    private Set<Role> roles;

    private Set<Nomination> nominations = new HashSet<>();

    @Relationship(type = "KNOWS", direction = Relationship.Direction.OUTGOING)
    public Set<Knows> knows = new HashSet<>();

    Actor() {
        // default constructor for OGM
    }

    public Actor(String name) {
        this.name = name;
    }

    public Role playedIn(Movie movie, String roleName) {
        if (roles == null) {
            roles = new HashSet<>();
        }
        Role role = new Role(movie, this, roleName);
        roles.add(role);
        movie.getRoles().add(role);
        return role;
    }

    public Nomination nominatedFor(Movie movie, String nominationName, int year) {
        Nomination nomination = new Nomination(movie, this, nominationName, year);
        nominations.add(nomination);
        if (movie.getNominations() == null) {
            movie.setNominations(new HashSet<Nomination>());
        }
        movie.getNominations().add(nomination);
        return nomination;
    }

    public String getName() {
        return name;
    }

    public Set<Knows> getKnows() {
        return knows;
    }

    public Set<Nomination> getNominations() {
        return nominations;
    }

    public void setNominations(Set<Nomination> nominations) {
        this.nominations = nominations;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }

        Actor actor = (Actor) o;

        if (name == null || ((Actor) o).getName() == null) {
            return false;
        }

        return name.equals(actor.name);
    }

    @Override
    public int hashCode() {
        return name != null ? name.hashCode() : 0;
    }

    public Set<Role> getRoles() {
        return roles;
    }

    public void setRoles(Set<Role> roles) {
        this.roles = roles;
    }

    public UUID getUuid() {
        return uuid;
    }

    @Override
    public String toString() {
        return "Actor {" +
            "name='" + name + '\'' +
            '}';
    }
}


text:
require 'spec_helper'

describe MysqlPartition do
  it 'has a version number' do
    expect(MysqlPartition::VERSION).not_to be nil
  end
end


text:
package ro.isdc.wro.http.handler;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;

import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;

import ro.isdc.wro.config.Context;
import ro.isdc.wro.http.support.HttpHeader;
import ro.isdc.wro.http.support.UnauthorizedRequestException;
import ro.isdc.wro.manager.factory.BaseWroManagerFactory;
import ro.isdc.wro.model.group.processor.Injector;
import ro.isdc.wro.model.group.processor.InjectorBuilder;
import ro.isdc.wro.model.resource.locator.ClasspathUriLocator;
import ro.isdc.wro.model.resource.locator.UriLocator;
import ro.isdc.wro.model.resource.locator.factory.UriLocatorFactory;
import ro.isdc.wro.model.resource.support.ResourceAuthorizationManager;
import ro.isdc.wro.util.WroUtil;

/**
 * @author Ivar Conradi Østhus
 */
public class TestResourceProxyRequestHandler {
  @InjectMocks
  private ResourceProxyRequestHandler victim;
  @Mock
  private HttpServletRequest request;
  @Mock
  private HttpServletResponse response;
  @Mock
  private ServletContext servletContext;
  @Mock
  private FilterConfig filterConfig;
  @Mock
  private ResourceAuthorizationManager mockAuthorizationManager;
  @Mock
  private UriLocatorFactory mockUriLocatorFactory;
  @Mock
  private UriLocator mockUriLocator;

  private OutputStream outputStream;

  private ServletOutputStream servletOutputStream;

  private String packagePath;

  @BeforeClass
  public static void onBeforeClass() {
    assertEquals(0, Context.countActive());
  }

  @AfterClass
  public static void onAfterClass() {
    assertEquals(0, Context.countActive());
  }

  @Before
  public void setup()
      throws IOException {
    MockitoAnnotations.initMocks(this);
    victim = new ResourceProxyRequestHandler();

    Mockito.when(filterConfig.getServletContext()).thenReturn(servletContext);
    Context.set(Context.webContext(request, response, filterConfig));
    // a more elaborate way to build injector, used to instruct it use a different instance of authorizationManager
    final Injector injector = new InjectorBuilder(new BaseWroManagerFactory().setUriLocatorFactory(
        mockUriLocatorFactory).setResourceAuthorizationManager(mockAuthorizationManager)).build();
    injector.inject(victim);

    when(mockUriLocatorFactory.getInstance(anyString())).thenReturn(mockUriLocator);
    when(mockUriLocatorFactory.locate(anyString())).then(new Answer<InputStream>() {
      public InputStream answer(final InvocationOnMock invocation)
          throws Throwable {
        final String uri = (String) invocation.getArguments()[0];
        return mockUriLocator.locate(uri);
      }
    });
    when(mockUriLocator.locate(anyString())).thenReturn(WroUtil.EMPTY_STREAM);

    packagePath = WroUtil.toPackageAsFolder(this.getClass());

    // Setup response writer
    outputStream = new ByteArrayOutputStream();
    servletOutputStream = new ServletOutputStream() {
      @Override
      public void write(final int i)
          throws IOException {
        outputStream.write(i);
      }
    };
    when(response.getOutputStream()).thenReturn(servletOutputStream);
  }

  @After
  public void tearDown() {
    Context.unset();
  }

  @Test
  public void shouldAlwaysBeEnabled() {
    assertTrue(victim.isEnabled());
  }

  @Test
  public void shouldAcceptCallsTo_wroResources() {
    when(request.getRequestURI()).thenReturn("?wroAPI=wroResources&id=test.css");
    when(request.getParameter(ResourceProxyRequestHandler.PATH_API)).thenReturn(
        ResourceProxyRequestHandler.PATH_RESOURCES);
    when(request.getParameter(ResourceProxyRequestHandler.PARAM_RESOURCE_ID)).thenReturn("test.css");
    assertTrue(victim.accept(request));
  }

  @Test
  public void shouldNotAcceptCallsTo_OtherUris() {
    when(request.getRequestURI()).thenReturn("/wro/someOtherUri");
    assertFalse(victim.accept(request));
  }

  @Test
  public void shouldReturnClasspathResource()
      throws IOException {
    final String resourceUri = "classpath:" + packagePath + "/" + "test.css";
    when(mockAuthorizationManager.isAuthorized(resourceUri)).thenReturn(true);
    when(request.getParameter(ResourceProxyRequestHandler.PARAM_RESOURCE_ID)).thenReturn(resourceUri);
    when(mockUriLocator.locate(anyString())).thenReturn(new ClasspathUriLocator().locate(resourceUri));

    victim.handle(request, response);

    final String body = outputStream.toString();
    final String expectedBody = IOUtils.toString(getInputStream("test.css"));

    assertEquals(expectedBody, body);
  }

  @Test(expected = UnauthorizedRequestException.class)
  public void cannotProxyUnauthorizedResources()
      throws IOException {
    final String resourceUri = "classpath:" + packagePath + "/" + "test.css";
    when(mockAuthorizationManager.isAuthorized(resourceUri)).thenReturn(false);
    when(request.getParameter(ResourceProxyRequestHandler.PARAM_RESOURCE_ID)).thenReturn(resourceUri);
    when(mockUriLocator.locate(anyString())).thenReturn(new ClasspathUriLocator().locate(resourceUri));

    victim.handle(request, response);
  }

  @Test
  public void shouldReturnRelativeResource()
      throws IOException {
    final String resourceUri = "/" + packagePath + "/" + "test.css";
    when(mockAuthorizationManager.isAuthorized(resourceUri)).thenReturn(true);

    // Set up victim
    when(mockUriLocator.locate(resourceUri)).thenReturn(getInputStream("test.css"));
    when(request.getParameter(ResourceProxyRequestHandler.PARAM_RESOURCE_ID)).thenReturn(resourceUri);

    // Perform Action
    victim.handle(request, response);
    final String body = outputStream.toString();
    final String expectedBody = IOUtils.toString(getInputStream("test.css"));

    verify(mockUriLocator, times(1)).locate(resourceUri);
    assertEquals(expectedBody, body);
  }

  @Test
  public void shouldSetResponseLength()
      throws IOException {
    final String resourceUri = "classpath:" + packagePath + "/" + "test.css";
    when(mockAuthorizationManager.isAuthorized(resourceUri)).thenReturn(true);
    when(request.getParameter(ResourceProxyRequestHandler.PARAM_RESOURCE_ID)).thenReturn(resourceUri);
    when(mockUriLocator.locate(anyString())).thenReturn(new ClasspathUriLocator().locate(resourceUri));

    victim.handle(request, response);
    final int expectedLength = IOUtils.toString(getInputStream("test.css")).length();

    verify(response, times(1)).setContentLength(expectedLength);
  }

  @Test
  public void shouldSetCSSContentType()
      throws IOException {
    final String resourceUri = "classpath:" + packagePath + "/" + "test.css";
    when(mockAuthorizationManager.isAuthorized(resourceUri)).thenReturn(true);
    when(request.getParameter(ResourceProxyRequestHandler.PARAM_RESOURCE_ID)).thenReturn(resourceUri);

    victim.handle(request, response);

    verify(response, times(1)).setContentType("text/css; charset=UTF-8");
  }

  @Test
  public void shouldSetJSContentType()
      throws IOException {
    final String resourceUri = "classpath:" + packagePath + "/" + "test.js";
    when(mockAuthorizationManager.isAuthorized(resourceUri)).thenReturn(true);
    when(request.getParameter(ResourceProxyRequestHandler.PARAM_RESOURCE_ID)).thenReturn(resourceUri);

    victim.handle(request, response);

    verify(response, times(1)).setContentType("application/javascript; charset=UTF-8");
  }

  @Test
  public void shouldSetPNGContentType()
      throws IOException {
    final String resourceUri = "classpath:" + packagePath + "/" + "test.png";
    when(mockAuthorizationManager.isAuthorized(resourceUri)).thenReturn(true);
    when(request.getParameter(ResourceProxyRequestHandler.PARAM_RESOURCE_ID)).thenReturn(resourceUri);

    victim.handle(request, response);

    verify(response, times(1)).setContentType("image/png");
  }

  @Test
  public void shouldSetCorrectResopnsCodeBasedOnResourceChangeState()
      throws IOException {
    final String resourceUri = "classpath:" + packagePath + "/" + "test.css";
    when(mockAuthorizationManager.isAuthorized(resourceUri)).thenReturn(true);
    when(request.getParameter(ResourceProxyRequestHandler.PARAM_RESOURCE_ID)).thenReturn(resourceUri);

    final long timeInFuture = new Date().getTime() + 10000;
    when(request.getDateHeader(HttpHeader.IF_MODIFIED_SINCE.toString())).thenReturn(timeInFuture);
    victim.handle(request, response);
    verify(response).setStatus(HttpServletResponse.SC_NOT_MODIFIED);

    final long longTimeAgo = 123L;
    when(request.getDateHeader(HttpHeader.IF_MODIFIED_SINCE.toString())).thenReturn(longTimeAgo);
    victim.handle(request, response);
    verify(response).setStatus(Mockito.eq(HttpServletResponse.SC_OK));
  }

  @Test
  public void shouldAssumeResourceChangedWhenModifiedSinceHeaderExtractionFails()
      throws Exception {
    final String resourceUri = "classpath:" + packagePath + "/" + "test.css";
    when(mockAuthorizationManager.isAuthorized(resourceUri)).thenReturn(true);
    when(request.getParameter(ResourceProxyRequestHandler.PARAM_RESOURCE_ID)).thenReturn(resourceUri);

    when(request.getDateHeader(HttpHeader.IF_MODIFIED_SINCE.toString())).thenThrow(
        new IllegalArgumentException("BOOM!"));
    victim.handle(request, response);
    verify(response).setStatus(HttpServletResponse.SC_OK);
  }

  private InputStream getInputStream(final String filename)
      throws IOException {
    return this.getClass().getClassLoader().getResourceAsStream(packagePath + "/" + filename);
  }

  @Test(expected = NullPointerException.class)
  public void cannotAcceptNullRequestUriToCreateProxyPath() {
    ResourceProxyRequestHandler.createProxyPath(null, "");
  }

  @Test
  public void shouldCreateProxyPath() {
    assertEquals("/wro/all.js?wroAPI=wroResources&id=id", ResourceProxyRequestHandler.createProxyPath("/wro/all.js", "id"));
    assertEquals("?wroAPI=wroResources&id=id", ResourceProxyRequestHandler.createProxyPath("", "id"));
  }

  @Test
  public void shouldDetectProxyUri() {
    assertTrue(ResourceProxyRequestHandler.isProxyUri("/path?wroAPI=wroResources&id=id"));
  }
}


text:
{% extends "nadb/base_nadb.html" %}
{% load markup %}
{% load comments %}

{% block title %}{{ object.title }}{% endblock %}

{% block extra_head %}
<link rel="stylesheet" href="{{ STATIC_URL }}css/code.css">
{% endblock %}

{% block content_title %}
    {{ object.title }}
{% endblock %}

{% block content %}

Posted by {{ object.author }} on {{ object.published|date:"F d, Y" }}

{{ object.body_html|safe }}

{% render_comment_list for object %}

{% render_comment_form for object %}

{% endblock %}


text:
import { run } from 'ember-metal';
import Engine from '../../system/engine';
import { moduleFor, AbstractTestCase as TestCase } from 'internal-test-helpers';

let MyEngine, myEngine, myEngineInstance;

moduleFor(
  'Engine initializers',
  class extends TestCase {
    teardown() {
      run(() => {
        if (myEngineInstance) {
          myEngineInstance.destroy();
        }

        if (myEngine) {
          myEngine.destroy();
        }
      });
    }

    ["@test initializers require proper 'name' and 'initialize' properties"]() {
      MyEngine = Engine.extend();

      expectAssertion(() => {
        run(() => {
          MyEngine.initializer({ name: 'initializer' });
        });
      });

      expectAssertion(() => {
        run(() => {
          MyEngine.initializer({ initialize() {} });
        });
      });
    }

    ['@test initializers are passed an Engine'](assert) {
      MyEngine = Engine.extend();

      MyEngine.initializer({
        name: 'initializer',
        initialize(engine) {
          assert.ok(engine instanceof Engine, 'initialize is passed an Engine');
        },
      });

      myEngine = MyEngine.create();
      myEngineInstance = myEngine.buildInstance();
    }

    ['@test initializers can be registered in a specified order'](assert) {
      let order = [];

      MyEngine = Engine.extend();
      MyEngine.initializer({
        name: 'fourth',
        after: 'third',
        initialize() {
          order.push('fourth');
        },
      });

      MyEngine.initializer({
        name: 'second',
        after: 'first',
        before: 'third',
        initialize() {
          order.push('second');
        },
      });

      MyEngine.initializer({
        name: 'fifth',
        after: 'fourth',
        before: 'sixth',
        initialize() {
          order.push('fifth');
        },
      });

      MyEngine.initializer({
        name: 'first',
        before: 'second',
        initialize() {
          order.push('first');
        },
      });

      MyEngine.initializer({
        name: 'third',
        initialize() {
          order.push('third');
        },
      });

      MyEngine.initializer({
        name: 'sixth',
        initialize() {
          order.push('sixth');
        },
      });

      myEngine = MyEngine.create();
      myEngineInstance = myEngine.buildInstance();

      assert.deepEqual(order, ['first', 'second', 'third', 'fourth', 'fifth', 'sixth']);
    }

    ['@test initializers can be registered in a specified order as an array'](assert) {
      let order = [];

      MyEngine = Engine.extend();

      MyEngine.initializer({
        name: 'third',
        initialize() {
          order.push('third');
        },
      });

      MyEngine.initializer({
        name: 'second',
        after: 'first',
        before: ['third', 'fourth'],
        initialize() {
          order.push('second');
        },
      });

      MyEngine.initializer({
        name: 'fourth',
        after: ['second', 'third'],
        initialize() {
          order.push('fourth');
        },
      });

      MyEngine.initializer({
        name: 'fifth',
        after: 'fourth',
        before: 'sixth',
        initialize() {
          order.push('fifth');
        },
      });

      MyEngine.initializer({
        name: 'first',
        before: ['second'],
        initialize() {
          order.push('first');
        },
      });

      MyEngine.initializer({
        name: 'sixth',
        initialize() {
          order.push('sixth');
        },
      });

      myEngine = MyEngine.create();
      myEngineInstance = myEngine.buildInstance();

      assert.deepEqual(order, ['first', 'second', 'third', 'fourth', 'fifth', 'sixth']);
    }

    ['@test initializers can have multiple dependencies'](assert) {
      let order = [];

      MyEngine = Engine.extend();

      let a = {
        name: 'a',
        before: 'b',
        initialize() {
          order.push('a');
        },
      };
      let b = {
        name: 'b',
        initialize() {
          order.push('b');
        },
      };
      let c = {
        name: 'c',
        after: 'b',
        initialize() {
          order.push('c');
        },
      };
      let afterB = {
        name: 'after b',
        after: 'b',
        initialize() {
          order.push('after b');
        },
      };
      let afterC = {
        name: 'after c',
        after: 'c',
        initialize() {
          order.push('after c');
        },
      };

      MyEngine.initializer(b);
      MyEngine.initializer(a);
      MyEngine.initializer(afterC);
      MyEngine.initializer(afterB);
      MyEngine.initializer(c);

      myEngine = MyEngine.create();
      myEngineInstance = myEngine.buildInstance();

      assert.ok(order.indexOf(a.name) < order.indexOf(b.name), 'a < b');
      assert.ok(order.indexOf(b.name) < order.indexOf(c.name), 'b < c');
      assert.ok(order.indexOf(b.name) < order.indexOf(afterB.name), 'b < afterB');
      assert.ok(order.indexOf(c.name) < order.indexOf(afterC.name), 'c < afterC');
    }

    ['@test initializers set on Engine subclasses are not shared between engines'](assert) {
      let firstInitializerRunCount = 0;
      let secondInitializerRunCount = 0;
      let FirstEngine = Engine.extend();

      FirstEngine.initializer({
        name: 'first',
        initialize() {
          firstInitializerRunCount++;
        },
      });

      let SecondEngine = Engine.extend();

      SecondEngine.initializer({
        name: 'second',
        initialize() {
          secondInitializerRunCount++;
        },
      });

      let firstEngine = FirstEngine.create();
      let firstEngineInstance = firstEngine.buildInstance();

      assert.equal(firstInitializerRunCount, 1, 'first initializer only was run');
      assert.equal(secondInitializerRunCount, 0, 'first initializer only was run');

      let secondEngine = SecondEngine.create();
      let secondEngineInstance = secondEngine.buildInstance();

      assert.equal(firstInitializerRunCount, 1, 'second initializer only was run');
      assert.equal(secondInitializerRunCount, 1, 'second initializer only was run');

      run(function() {
        firstEngineInstance.destroy();
        secondEngineInstance.destroy();

        firstEngine.destroy();
        secondEngine.destroy();
      });
    }

    ['@test initializers are concatenated'](assert) {
      let firstInitializerRunCount = 0;
      let secondInitializerRunCount = 0;
      let FirstEngine = Engine.extend();

      FirstEngine.initializer({
        name: 'first',
        initialize() {
          firstInitializerRunCount++;
        },
      });

      let SecondEngine = FirstEngine.extend();

      SecondEngine.initializer({
        name: 'second',
        initialize() {
          secondInitializerRunCount++;
        },
      });

      let firstEngine = FirstEngine.create();
      let firstEngineInstance = firstEngine.buildInstance();

      assert.equal(
        firstInitializerRunCount,
        1,
        'first initializer only was run when base class created'
      );
      assert.equal(
        secondInitializerRunCount,
        0,
        'second initializer was not run when first base class created'
      );
      firstInitializerRunCount = 0;

      let secondEngine = SecondEngine.create();
      let secondEngineInstance = secondEngine.buildInstance();

      assert.equal(firstInitializerRunCount, 1, 'first initializer was run when subclass created');
      assert.equal(
        secondInitializerRunCount,
        1,
        'second initializers was run when subclass created'
      );

      run(function() {
        firstEngineInstance.destroy();
        secondEngineInstance.destroy();

        firstEngine.destroy();
        secondEngine.destroy();
      });
    }

    ['@test initializers are per-engine'](assert) {
      assert.expect(2);

      let FirstEngine = Engine.extend();

      FirstEngine.initializer({
        name: 'abc',
        initialize() {},
      });

      expectAssertion(function() {
        FirstEngine.initializer({
          name: 'abc',
          initialize() {},
        });
      });

      let SecondEngine = Engine.extend();
      SecondEngine.instanceInitializer({
        name: 'abc',
        initialize() {},
      });

      assert.ok(true, 'Two engines can have initializers named the same.');
    }

    ['@test initializers are executed in their own context'](assert) {
      assert.expect(1);

      MyEngine = Engine.extend();

      MyEngine.initializer({
        name: 'coolInitializer',
        myProperty: 'cool',
        initialize() {
          assert.equal(this.myProperty, 'cool', 'should have access to its own context');
        },
      });

      myEngine = MyEngine.create();
      myEngineInstance = myEngine.buildInstance();
    }
  }
);


text:
Work in progress

# InteractiveVideoComponents
A collection of node modules that can be used on video projects, centred a round the idea of hypertranscript as a way into the content of the video.

When refactoring [quickQuote](http://times.github.io/quickQuote/) from ruby on rails to node, adding a live video stream as input and export to twitter video API,
decided to abstract core components in common between quickQuote and [autoEdit](http://pietropassarelli.com/autoEdit.html) into
 a collection of `InteractiveVideoComponents` in this repository, to make it easier to quickly get off the ground on similar video/transcription based projects.

Currently this is a work in progress.

The [wiki section](https://github.com/pietrop/InteractiveVideoComponents/wiki) of this project is up to date with the description and state of the development of the various components.

## Config file

Config file is in git ignore, but the following code create one for your project.

```js
var config = {};

config.twitter = {};
config.spokendata={};

config.spokendata.baseurl 		=	process.env.SPOKENDATA_BASEURL 		|| "";
config.spokendata.userid 		=	process.env.SPOKENDATA_USERID		|| ;
config.spokendata.apitoken 		=	process.env.SPOKENDATA_APITOKEN		|| "";

config.twitter.consumer_key 	=	process.env.TWITTER_CONSUMER_KEY 	|| "";
config.twitter.consumer_secret 	= 	process.env.TWITTER_CONSUMER_SECRET || "";
config.twitter.token 			=	process.env.TWITTER_TOKEN 			|| "";
config.twitter.token_secret		= 	process.env.TWITTER_SECRET 			|| "";

module.exports = config;
```

## Install dependencies

```bash
npm install
```

## video file

as the video file is 207.5 mb is not included in the git repo, and the `.gitignore` is set to exclude videos from the repo to stop it from upload. So here is a[link to video file](https://dl.dropboxusercontent.com/u/449999/debate_test.mp4).


text:
using Concise.Steps.TestFramework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

#if NETSTANDARD1_6
using Microsoft.Extensions.DependencyModel;
using Microsoft.Extensions.PlatformAbstractions;
#endif

namespace Concise.Steps.IoC
{
    internal class Bootstrapper
    {
        static Bootstrapper()
        {
            Bootstrapper.InitializeWithConciseContainer();
        }

        public static IContainer InitializeWithConciseContainer()
        {
            var container = new ConciseContainer();
            InitializeWithContainer(container);
            return container;
        }

        private static void InitializeWithContainer(IContainer container)
        {
            // Find and register the loaded ITestFrameworkAdapter by looking through assemblies that directly reference this one
            {
                string currentAssemblyFullName = typeof(Bootstrapper).GetTypeInfo().Assembly.FullName;

                // Libraries directly referencing this one
                IList<Assembly> assembliesReferencingThisAssembly = AppDomain.CurrentDomain.GetAssemblies()
                    .Where((Assembly x) =>
                        x.GetName().FullName != currentAssemblyFullName &&
                        x.GetReferencedAssemblies().Any((AssemblyName y) => y.FullName == currentAssemblyFullName))
                    .ToList();

                // All types in those libraries implementing ITestFrameworkAdapter
                IList<Type> typesImplementingInterface = assembliesReferencingThisAssembly
                    .SelectMany(assembly => assembly.GetTypes().Where(x => x.GetInterfaces().Contains(typeof(ITestFrameworkAdapter))))
                    .ToList();

                if (!typesImplementingInterface.Any())
                    throw new InvalidOperationException("Unable to find a registered test adapter.  Did you forget to add a NuGet reference to Concise.Steps.MSTest or Concise.Steps.NUnit?");

                if( typesImplementingInterface.Count > 1 )
                {
                    throw new InvalidOperationException(
                        $"Multiple registered test framework adapters located - please remove a referenced assembly so that only one adapter is present." +
                        $" ({string.Join(",", typesImplementingInterface.Select(x => x.FullName))})");
                }

                container.RegisterSingleton(typeof(ITestFrameworkAdapter), typesImplementingInterface.First());
            }

            Bootstrapper.Locator = container.Provider;
        }

        /// <summary>
        /// Internal property for service locator use
        /// </summary>
        internal static IServiceProvider Locator { get; private set; }
    }
}


text:
package org.elasticsearch.river.dummy;

import org.elasticsearch.common.inject.AbstractModule;
import org.elasticsearch.river.River;

/**
 *
 */
public class DummyRiverModule extends AbstractModule {

    @Override
    protected void configure() {
        bind(River.class).to(DummyRiver.class).asEagerSingleton();
    }
}


text:
const program = require('commander')
const chalk = require('chalk')

const error = chalk.bold.red
const logErr = (msg) => console.log(error(msg))

program
  .version(require('../package.json').version)
  .description('For better use of traffic-splitter create an isolated app. Take advantage of custom rules, handling events and adding middlewares.')
  .option('-c, --conf <file>', 'provide configuration file (.json or .js with module.exports = {...})')

program.on('/help', () => program.help())

program.parse(process.argv)

if (!program.conf) {
  logErr('Missing configuration file.')
  logErr('Use: traffic-splitter -c yourConfigurationFile.')
  program.help()
}

let config
try {
  config = require(process.cwd() + '/' + program.conf)
} catch (err) {
  logErr(err)
  process.exit(1)
}

const TrafficSplitter = require('..')

if (!TrafficSplitter.isConfigurationValid(config)) {
  logErr('Invalid configuration. Please check traffic-splitter documentation at http://trafficsplitter.io')
  process.exit(1)
}

try {
  const splitter = new TrafficSplitter(config)
  splitter.start()
} catch (err) {
  logErr(err)
  process.exit(1)
}


text:
import { Constructor } from './constructor';

/** @docs-private */
export interface HasPlaceholder {
  /** Whether the component is placeholder. */
  placeholder: string;
}

/** @docs-private */
export type HasPlaceholderCtor = Constructor<HasPlaceholder>;

/** Mixin to augment a directive with a `placeholder` property. */
export function mixinPlaceholder<T extends Constructor<{}>>(base: T): HasPlaceholderCtor & T {
  return class extends base {
    protected _placeholder: string;

    get placeholder(): string {
      return this._placeholder;
    }
    set placeholder(value: string) {
      this._placeholder = value;
    }

    constructor(...args: any[]) {
      super(...args);
    }
  };
}


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.42000
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace NavigationBot.Properties {
    using System;

    /// <summary>
    ///   A strongly-typed resource class, for looking up localized strings, etc.
    /// </summary>
    // This class was auto-generated by the StronglyTypedResourceBuilder
    // class via a tool like ResGen or Visual Studio.
    // To add or remove a member, edit your .ResX file then rerun ResGen
    // with the /str option, or rebuild your VS project.
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    internal class Resources {

        private static global::System.Resources.ResourceManager resourceMan;

        private static global::System.Globalization.CultureInfo resourceCulture;

        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        internal Resources() {
        }

        /// <summary>
        ///   Returns the cached ResourceManager instance used by this class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        internal static global::System.Resources.ResourceManager ResourceManager {
            get {
                if (object.ReferenceEquals(resourceMan, null)) {
                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("NavigationBot.Properties.Resources", typeof(Resources).Assembly);
                    resourceMan = temp;
                }
                return resourceMan;
            }
        }

        /// <summary>
        ///   Overrides the current thread's CurrentUICulture property for all
        ///   resource lookups using this strongly typed resource class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        internal static global::System.Globalization.CultureInfo Culture {
            get {
                return resourceCulture;
            }
            set {
                resourceCulture = value;
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Menu.
        /// </summary>
        internal static string NavigationMenu_Option {
            get {
                return ResourceManager.GetString("NavigationMenu_Option", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Topic 1.1.
        /// </summary>
        internal static string Topic1_1_Option {
            get {
                return ResourceManager.GetString("Topic1_1_Option", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Topic 1.2.
        /// </summary>
        internal static string Topic1_2_Option {
            get {
                return ResourceManager.GetString("Topic1_2_Option", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Topic 1.3.
        /// </summary>
        internal static string Topic1_3_Option {
            get {
                return ResourceManager.GetString("Topic1_3_Option", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Topic 1.
        /// </summary>
        internal static string Topic1_Option {
            get {
                return ResourceManager.GetString("Topic1_Option", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Topic 2.1.
        /// </summary>
        internal static string Topic2_1_Option {
            get {
                return ResourceManager.GetString("Topic2_1_Option", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Topic 2.2.
        /// </summary>
        internal static string Topic2_2_Option {
            get {
                return ResourceManager.GetString("Topic2_2_Option", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Topic 2.3.
        /// </summary>
        internal static string Topic2_3_Option {
            get {
                return ResourceManager.GetString("Topic2_3_Option", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Topic 2.
        /// </summary>
        internal static string Topic2_Option {
            get {
                return ResourceManager.GetString("Topic2_Option", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Topic 3.1.
        /// </summary>
        internal static string Topic3_1_Option {
            get {
                return ResourceManager.GetString("Topic3_1_Option", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Topic 3.2.
        /// </summary>
        internal static string Topic3_2_Option {
            get {
                return ResourceManager.GetString("Topic3_2_Option", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Topic 3.3.
        /// </summary>
        internal static string Topic3_3_Option {
            get {
                return ResourceManager.GetString("Topic3_3_Option", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Topic 3.
        /// </summary>
        internal static string Topic3_Option {
            get {
                return ResourceManager.GetString("Topic3_Option", resourceCulture);
            }
        }
    }
}


text:
package cloudstack

import (
	"fmt"
	"testing"

	"github.com/hashicorp/terraform/helper/resource"
	"github.com/hashicorp/terraform/terraform"
	"github.com/xanzy/go-cloudstack/cloudstack"
)

func TestAccCloudStackAffinityGroup_basic(t *testing.T) {
	var affinityGroup cloudstack.AffinityGroup

	resource.Test(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckCloudStackAffinityGroupDestroy,
		Steps: []resource.TestStep{
			resource.TestStep{
				Config: testAccCloudStackAffinityGroup,
				Check: resource.ComposeTestCheckFunc(
					testAccCheckCloudStackAffinityGroupExists("cloudstack_affinity_group.foo", &affinityGroup),
					testAccCheckCloudStackAffinityGroupAttributes(&affinityGroup),
				),
			},
		},
	})
}

func testAccCheckCloudStackAffinityGroupExists(
	n string, affinityGroup *cloudstack.AffinityGroup) resource.TestCheckFunc {
	return func(s *terraform.State) error {
		rs, ok := s.RootModule().Resources[n]
		if !ok {
			return fmt.Errorf("Not found: %s", n)
		}

		if rs.Primary.ID == "" {
			return fmt.Errorf("No affinity group ID is set")
		}

		cs := testAccProvider.Meta().(*cloudstack.CloudStackClient)
		ag, _, err := cs.AffinityGroup.GetAffinityGroupByID(rs.Primary.ID)

		if err != nil {
			return err
		}

		if ag.Id != rs.Primary.ID {
			return fmt.Errorf("Affinity group not found")
		}

		*affinityGroup = *ag

		return nil
	}
}

func testAccCheckCloudStackAffinityGroupAttributes(
	affinityGroup *cloudstack.AffinityGroup) resource.TestCheckFunc {
	return func(s *terraform.State) error {

		if affinityGroup.Name != "terraform-affinity-group" {
			return fmt.Errorf("Bad name: %s", affinityGroup.Name)
		}

		if affinityGroup.Description != "terraform-affinity-group" {
			return fmt.Errorf("Bad description: %s", affinityGroup.Description)
		}

		if affinityGroup.Type != "host anti-affinity" {
			return fmt.Errorf("Bad type: %s", affinityGroup.Type)
		}

		return nil
	}
}

func testAccCheckCloudStackAffinityGroupDestroy(s *terraform.State) error {
	cs := testAccProvider.Meta().(*cloudstack.CloudStackClient)

	for _, rs := range s.RootModule().Resources {
		if rs.Type != "cloudstack_affinity_group" {
			continue
		}

		if rs.Primary.ID == "" {
			return fmt.Errorf("No affinity group ID is set")
		}

		_, _, err := cs.AffinityGroup.GetAffinityGroupByID(rs.Primary.ID)
		if err == nil {
			return fmt.Errorf("Affinity group %s still exists", rs.Primary.ID)
		}
	}

	return nil
}

var testAccCloudStackAffinityGroup = fmt.Sprintf(`
resource "cloudstack_affinity_group" "foo" {
	name = "terraform-affinity-group"
	type = "host anti-affinity"
}`)


text:
FROM debian:wheezy
MAINTAINER Lopez Shackleford <lopez.shackleford@gmail.com>

ENV DEBIAN_FRONTEND noninteractive

# Keep upstart from complaining
RUN dpkg-divert --local --rename --add /sbin/initctl
RUN ln -sf /bin/true /sbin/initctl

# Install utils
RUN apt-get update && apt-get -y install wget curl

# ADD PHP 5.6 Repo
RUN \
  wget -O - http://www.dotdeb.org/dotdeb.gpg | apt-key add - && \
  echo "deb http://packages.dotdeb.org wheezy-php56 all" > /etc/apt/sources.list.d/dotdeb.list && \
  echo "\ndeb-src http://packages.dotdeb.org wheezy-php56 all" >> /etc/apt/sources.list.d/dotdeb.list

# Packages.
RUN apt-get update && apt-get -y --force-yes install \
  apache2 \
  apt-utils \
  git \
  libapache2-mod-php5 \
  mysql-client \
  openjdk-7-jre-headless \
  pv \
  pwgen \
  python-setuptools \
  sudo \
  supervisor \
  tidy \
  vim

# Install PHP
RUN apt-get update && apt-get install -y \
  php5-curl \
  php5-dbg \
  php5-gd \
  php5-mysql \
  php5-sqlite \
  php5-pgsql \
  php-pear \
  php5-xdebug

# Install Mailcatcher
RUN apt-get install -y \
  binutils \
  build-essential \
  bzip2 \
  cpp \
  dpkg-dev \
  fakeroot \
  g++ \
  libsqlite3-dev \
  make \
  ruby \
  ruby-dev \
  sqlite3

RUN gem install mailcatcher

RUN apt-get remove -y build-essential libsqlite3-dev ruby-dev && \
    apt-get autoclean && \
    rm -rf /var/lib/apt/lists

# whitelist = phar
RUN \
  mkdir -p /etc/php5/conf.d/ && \
  echo "suhosin.executor.include.whitelist = phar" >> /etc/php5/conf.d/suhosin.ini

# Composer.
RUN \
  curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin -d detect_unicode=0 && \
  ln -s /usr/local/bin/composer.phar /usr/local/bin/composer

# Enable a2enmod rewrite
RUN a2enmod rewrite php5 ssl

# Sudo.
RUN echo %sudo	ALL=NOPASSWD: ALL >> /etc/sudoers

# Scripts.
COPY ./conf/scripts/start.sh /start.sh

# Apache.
RUN rm -rf /var/www/*

# Apache / PHP.
COPY ./conf/apache2/vhost.conf /etc/apache2/sites-available/default
COPY ./conf/apache2/vhost-ssl.conf /etc/apache2/sites-available/default-ssl
COPY ./conf/php5/apache2.ini /etc/php5/apache2/php.ini
COPY ./conf/php5/cli.ini /etc/php5/cli/php.ini

# SSL cert - NOT for production!
COPY ./conf/apache2/localcerts/apache.key /etc/ssl/localcerts/apache.key
COPY ./conf/apache2/localcerts/apache.pem /etc/ssl/localcerts/apache.pem
RUN chmod 600 /etc/ssl/localcerts/apache*

# Enable ssl module and site
RUN a2ensite default-ssl && a2enmod ssl
RUN mkdir -p /var/run/apache2

# Supervisor
COPY ./conf/supervisor/supervisord.conf /etc/supervisor/conf.d/supervisord.conf

# Drupal.
COPY ./conf/drupal/settings.docker.php /etc/settings.docker.php

# Xdebug settings.
RUN \
  echo xdebug.remote_enable=1 >> /etc/php5/mods-available/xdebug.ini && \
  echo xdebug.remote_connect_back=1 >> /etc/php5/mods-available/xdebug.ini && \
  echo xdebug.remote_autostart=0 >> /etc/php5/mods-available/xdebug.ini && \
  echo xdebug.max_nesting_level=256 >> /etc/php5/mods-available/xdebug.ini && \
  echo xdebug.remote_log=/var/www/logs/xdebug.log >> /etc/php5/mods-available/xdebug.ini

EXPOSE 80 443 1080 1025

# Start  file
RUN chmod 755 /start.sh


text: DROP TABLE {$NAMESPACE}_repository.repository_vcspassword;


text:
Ti=Remarks by Tim Cook, CEO Apple

Note=Adding my section titles - unofficial

sec={0.sec}

{Hello.Sec}
{Crisis.Sec}
{Intrusion.sec}
{Remedy.Sec}
{Movement.Sec}
{AI.Sec}
{Walden.Sec}
{Thanks.Sec}

=[G/ICDPPC/40th-TimCook/Form/1.md]


text:
> [Documentation](../README.md) ▸ [API Reference](API.md) ▸ **RouteMap**

A RouteMap represents a bijection bewteen a URL route and a typed value.
It is used by [Router](Router.md), but can also be installed independently
to tie the browser's current hash (`document.location.href`) to a typed reactive
variable.

Routes are represented as `list<string>`.  When converting to and from URL hashes,
the framework automatically encodes the strings using `encodeUriComponent`
and `decodeUriComponent`.  All non-null values are therefore supported.

```fsharp
namespace WebSharper.UI.Next

type RouteMap<'T>
type RouteMap =
    static member Create : ('T -> list<string>) -> (list<string> -> 'T) -> RouteMap<'T>
    static member Install : RouteMap<'T> -> Var<'T>
```

# **RouteMap** `type RouteMap<'T>`

A bijection between an URL route and a value of the given type.

# RouteMap.**Install** : `RouteMap<'T> -> Var<'T>`

Installs a map to observe and modify the browser's current hash route (`document.location.hash`).
This should be called once per application, as the current URL is a shared resource.


text:
from __future__ import print_function
import time, sys, signal, atexit
from upm import pyupm_grovegprs as sensorObj

def main():
    # Instantiate a GroveGPRS Module on UART 0
    sensor = sensorObj.GroveGPRS(0)

    ## Exit handlers ##
    # This stops python from printing a stacktrace when you hit control-C
    def SIGINTHandler(signum, frame):
        raise SystemExit

    # This function lets you run code on exit
    def exitHandler():
        print("Exiting")
        sys.exit(0)

    # Register exit handlers
    atexit.register(exitHandler)
    signal.signal(signal.SIGINT, SIGINTHandler)

    # Set the baud rate, 19200 baud is the default.
    if (sensor.setBaudRate(19200)):
        print("Failed to set baud rate")
        sys.exit(0)

    usageStr = ("Usage:\n"
    "If an argument is supplied on the command line, that argument is\n"
    "sent to the module and the response is printed out.\n\n"
    "If no argument is used, then the manufacturer and the current\n"
    "saved profiles are queried and the results printed out.\n\n")
    print(usageStr)

    # simple helper function to send a command and wait for a response
    def sendCommand(sensor, cmd):
        # commands need to be terminated with a carriage return
        cmd += "\r";
        sensor.writeDataStr(cmd)

        # wait up to 1 second
        if (sensor.dataAvailable(1000)):
            print("Returned: ", end=' ')
            print(sensor.readDataStr(1024))
        else:
            print("Timed out waiting for response")

    if (len(sys.argv) > 1):
        print("Sending command line argument (" + sys.argv[1] + ")...")
        sendCommand(sensor, sys.argv[1])
    else:
        # query the module manufacturer
        print("Querying module manufacturer (AT+CGMI)...")
        sendCommand(sensor, "AT+CGMI");

        time.sleep(1);

        # query the saved profiles
        print("Querying the saved profiles (AT&V)...")
        sendCommand(sensor, "AT&V");

        # A comprehensive list is available from the datasheet at:
        # http://www.seeedstudio.com/wiki/images/7/72/AT_Commands_v1.11.pdf

if __name__ == '__main__':
    main()


text:
import shutil
from os.path import expanduser
home = expanduser("~")

def call_backup():
    shutil.move('backup/own.py', 'configs/own.py')
def move():
    shutil.move('configs/own.py', '%s/.mbwarband/rgl_config.txt' % (home))


text:
package com.github.twitch4j.common.events.channel;

import com.github.twitch4j.common.events.TwitchEvent;
import com.github.twitch4j.common.events.domain.EventChannel;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Value;

/**
 * This event gets called when a channel goes offline
 */
@Value
@Getter
@EqualsAndHashCode(callSuper = false)
@Deprecated
public class ChannelGoOfflineEvent extends TwitchEvent {

    /**
     * Channel
     */
    private final EventChannel channel;

    /**
     * Event Constructor
     *
     * @param channel        The channel that went offline
     */
    public ChannelGoOfflineEvent(EventChannel channel) {
        this.channel = channel;
    }
}


text:
Returns a taxonomy item
##Syntax
```powershell
Get-SPOTaxonomyItem -Term <String>
```

##Parameters
Parameter|Type|Required|Description
---------|----|--------|-----------
|Term|String|True|The path, delimited by | of the taxonomy item to retrieve, alike GROUPLABEL|TERMSETLABEL|TERMLABEL|


text:
@interface ICMVideoPlayerViewController : ICMAbstractViewController

- (void)playVideo:(NSString *)uri;

@end


text:
module.exports = {
    browserSync: {
        server: {
            // Serve up our build folder
            baseDir: './client'
        }
    },
    browserify: {
        // A separate bundle will be generated for each
        // bundle config in the list below
        bundleConfigs: [{
            entries: './lib/index.js',
            dest: './client',
            outputName: 'index.js',
            // list of externally available modules to exclude from the bundle
            external: []
        }]
    },
    lint: {
        src: "./lib/**/*.js"
    }
};


text:
<mvc:View
	height="100%"
	controllerName="sap.m.sample.MultiComboBoxSuggestionsAndValueState.controller.MultiComboBoxSuggestionsAndValueState"
	xmlns:l="sap.ui.layout"
	xmlns:core="sap.ui.core"
	xmlns:mvc="sap.ui.core.mvc"
	xmlns="sap.m">
	<Page showHeader="false">
		<l:VerticalLayout
			class="sapUiContentPadding"
			width="100%">
			<Label text="MultiComboBox with suggestions and success value state with a a long message:"/>
			<MultiComboBox class="sapUiSmallMarginBottom"
				maxWidth="500px"
				valueState="Success"
				valueStateText="Success message. Extra long text used as a success message. Extra long text used as a success message - 2. Extra long text used as a success message."
				items="{
					path: '/ProductCollection',
					sorter: { path: 'Name' }
				}">
				<core:Item key="{ProductId}" text="{Name}" />
			</MultiComboBox>
			<Label text="MultiComboBox with suggestions and information value state with a a long message:"/>
			<MultiComboBox class="sapUiSmallMarginBottom"
				maxWidth="500px"
				valueState="Information"
				valueStateText="Information message. Extra long text used as a information message. Extra long text used as a information message - 2. Extra long text used as a information message."
				items="{
					path: '/ProductCollection',
					sorter: { path: 'Name' }
				}">
				<core:Item key="{ProductId}" text="{Name}" />
			</MultiComboBox>
			<Label text="MultiComboBox with suggestions and an information value state with multiple links:"/>
			<MultiComboBox class="sapUiSmallMarginBottom"
				maxWidth="500px"
				valueState="Information"
				items="{
					path: '/ProductCollection',
					sorter: { path: 'Name' }
				}">
				<core:Item key="{ProductId}" text="{Name}" />
				<formattedValueStateText>
					<FormattedText htmlText="Value state with FormattedText used as an information message containing %%0 %%1." >
						<controls>
							<Link text="multiple" href="" press=".handleValueStateLinkPress" />
							<Link text="links" href="" press=".handleValueStateLinkPress" />

						</controls>
					</FormattedText>
				</formattedValueStateText>
			</MultiComboBox>
			<Label text="MultiComboBox with suggestions and warning value state with a a long message:"/>
			<MultiComboBox class="sapUiSmallMarginBottom"
				maxWidth="500px"
				valueState="Warning"
				valueStateText="Warning message. Extra long text used as a warning message. Extra long text used as a information message - 2. Extra long text used as a warning message."
				items="{
					path: '/ProductCollection',
					sorter: { path: 'Name' }
				}">
				<core:Item key="{ProductId}" text="{Name}" />
			</MultiComboBox>
			<Label text="MultiComboBox with suggestions and a warning value state with a link:"/>
			<MultiComboBox class="sapUiSmallMarginBottom"
				maxWidth="500px"
				valueState="Warning"
				valueStateText="Warning message. Extra long text used as a warning message."
				items="{
					path: '/ProductCollection',
					sorter: { path: 'Name' }
				}">
				<core:Item key="{ProductId}" text="{Name}" />
				<formattedValueStateText>
					<FormattedText htmlText="Value state with FormattedText used as a warning message containing a %%0." >
						<controls>
							<Link text="link" href="" press=".handleValueStateLinkPress" />
						</controls>
					</FormattedText>
				</formattedValueStateText>
			</MultiComboBox>
			<Label text="MultiComboBox with suggestions and an error value state with a a long message:"/>
			<MultiComboBox class="sapUiSmallMarginBottom"
				maxWidth="500px"
				valueState="Error"
				valueStateText="Error message. Extra long text used as a warning message. Extra long text used as an error message - 2. Extra long text used as an error message."
				items="{
					path: '/ProductCollection',
					sorter: { path: 'Name' }
				}">
				<core:Item key="{ProductId}" text="{Name}" />
			</MultiComboBox>
		</l:VerticalLayout>
	</Page>
</mvc:View>


text:
<project name="docker-ubuntu" default="build">
    <target name="build">
        <echo message="Building Docker Image" />
    </target>
</project>