text:
/*	$NetBSD: iso_pcb.c,v 1.25 2003/10/30 01:43:10 simonb Exp $	*/

/*-
 * Copyright (c) 1991, 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.
 *
 *	@(#)iso_pcb.c	8.3 (Berkeley) 7/19/94
 */

/***********************************************************
		Copyright IBM Corporation 1987

                      All Rights Reserved

Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted,
provided that the above copyright notice appear in all copies and that
both that copyright notice and this permission notice appear in
supporting documentation, and that the name of IBM not be
used in advertising or publicity pertaining to distribution of the
software without specific, written prior permission.

IBM DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
IBM BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
SOFTWARE.

******************************************************************/

/*
 * ARGO Project, Computer Sciences Dept., University of Wisconsin - Madison
 */
/*
 * Iso address family net-layer(s) pcb stuff. NEH 1/29/87
 */

#include <sys/cdefs.h>
__KERNEL_RCSID(0, "$NetBSD: iso_pcb.c,v 1.25 2003/10/30 01:43:10 simonb Exp $");

#include "opt_iso.h"

#ifdef ISO

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/mbuf.h>
#include <sys/socket.h>
#include <sys/socketvar.h>
#include <sys/errno.h>
#include <sys/proc.h>

#include <netiso/argo_debug.h>
#include <netiso/iso.h>
#include <netiso/clnp.h>
#include <netinet/in_systm.h>
#include <net/if.h>
#include <net/route.h>
#include <netiso/iso_pcb.h>
#include <netiso/iso_var.h>
#include <sys/protosw.h>

#ifdef TPCONS
#include <netccitt/x25.h>
#include <netccitt/pk.h>
#include <netccitt/pk_var.h>
#include <netccitt/pk_extern.h>
#endif

struct iso_addr zeroiso_addr = {
	0
};

#ifdef ARGO_DEBUG
unsigned char   argo_debug[128];
#endif

/*
 * FUNCTION:		iso_pcballoc
 *
 * PURPOSE:		creates an isopcb structure in an mbuf,
 *			with socket (so), and
 *			puts it in the queue with head (head)
 *
 * RETURNS:		0 if OK, ENOBUFS if can't alloc the necessary mbuf
 */
int
iso_pcballoc(so, v)
	struct socket  *so;
	void *v;
{
	struct isopcb  *head = v;
	struct isopcb *isop;

#ifdef ARGO_DEBUG
	if (argo_debug[D_ISO]) {
		printf("iso_pcballoc(so %p)\n", so);
	}
#endif
	MALLOC(isop, struct isopcb *, sizeof(*isop), M_PCB, M_NOWAIT);
	if (isop == NULL)
		return ENOBUFS;
	bzero(isop, sizeof(*isop));
	isop->isop_head = head;
	isop->isop_socket = so;
	insque(isop, head);
	if (so)
		so->so_pcb = isop;
	return 0;
}

/*
 * FUNCTION:		iso_pcbbind
 *
 * PURPOSE:		binds the address given in *(nam) to the socket
 *			specified by the isopcb in *(isop)
 *			If the given address is zero, it makes sure the
 *			address isn't already in use and if it's got a network
 *			portion, we look for an interface with that network
 *			address.  If the address given is zero, we allocate
 *			a port and stuff it in the (nam) structure.
 *
 * RETURNS:		errno E* or 0 if ok.
 *
 * SIDE EFFECTS:	increments head->isop_lport if it allocates a port #
 *
 * NOTES:
 */
int
iso_pcbbind(v, nam, p)
	void *v;
	struct mbuf *nam;
	struct proc *p;
{
	struct isopcb *isop = v;
	struct isopcb *head = isop->isop_head;
	struct sockaddr_iso *siso;
	struct iso_ifaddr *ia;
	union {
		char            data[2];
		u_short         s;
	} suf;

#ifdef ARGO_DEBUG
	if (argo_debug[D_ISO]) {
		printf("iso_pcbbind(isop %p, nam %p)\n", isop, nam);
	}
#endif
	suf.s = 0;
	if (iso_ifaddr.tqh_first == 0)	/* any interfaces attached? */
		return EADDRNOTAVAIL;
	if (isop->isop_laddr)	/* already bound */
		return EADDRINUSE;
	if (nam == (struct mbuf *) 0) {
		isop->isop_laddr = &isop->isop_sladdr;
		isop->isop_sladdr.siso_len = sizeof(struct sockaddr_iso);
		isop->isop_sladdr.siso_family = AF_ISO;
		isop->isop_sladdr.siso_tlen = 2;
		isop->isop_sladdr.siso_nlen = 0;
		isop->isop_sladdr.siso_slen = 0;
		isop->isop_sladdr.siso_plen = 0;
		goto noname;
	}
	siso = mtod(nam, struct sockaddr_iso *);
#ifdef ARGO_DEBUG
	if (argo_debug[D_ISO]) {
		printf("iso_pcbbind(name len 0x%x)\n", nam->m_len);
		printf("The address is %s\n", clnp_iso_addrp(&siso->siso_addr));
	}
#endif
	/*
	 * We would like sort of length check but since some OSI addrs
	 * do not have fixed length, we can't really do much.
	 * The ONLY thing we can say is that an osi addr has to have
	 * at LEAST an afi and one more byte and had better fit into
	 * a struct iso_addr.
	 * However, in fact the size of the whole thing is a struct
	 * sockaddr_iso, so probably this is what we should check for.
	 */
	if ((nam->m_len < 2) || (nam->m_len < siso->siso_len)) {
		return ENAMETOOLONG;
	}
	if (siso->siso_nlen) {
		/* non-zero net addr- better match one of our interfaces */
#ifdef ARGO_DEBUG
		if (argo_debug[D_ISO]) {
			printf("iso_pcbbind: bind to NOT zeroisoaddr\n");
		}
#endif
		for (ia = iso_ifaddr.tqh_first; ia != 0; ia = ia->ia_list.tqe_next)
			if (SAME_ISOIFADDR(siso, &ia->ia_addr))
				break;
		if (ia == 0)
			return EADDRNOTAVAIL;
	}
	if (siso->siso_len <= sizeof(isop->isop_sladdr)) {
		isop->isop_laddr = &isop->isop_sladdr;
	} else {
		if ((nam = m_copy(nam, 0, (int) M_COPYALL)) == 0)
			return ENOBUFS;
		isop->isop_mladdr = nam;
		isop->isop_laddr = mtod(nam, struct sockaddr_iso *);
	}
	bcopy((caddr_t) siso, (caddr_t) isop->isop_laddr, siso->siso_len);
	if (siso->siso_tlen == 0)
		goto noname;
	if ((isop->isop_socket->so_options & SO_REUSEADDR) == 0 &&
	    iso_pcblookup(head, 0, (caddr_t) 0, isop->isop_laddr))
		return EADDRINUSE;
	if (siso->siso_tlen <= 2) {
		bcopy(TSEL(siso), suf.data, sizeof(suf.data));
		suf.s = ntohs(suf.s);
		if (suf.s < ISO_PORT_RESERVED &&
		    (p == 0 || suser(p->p_ucred, &p->p_acflag)))
			return EACCES;
	} else {
		char  *cp;
noname:
		cp = TSEL(isop->isop_laddr);
		isop->isop_laddr->siso_tlen = 2;
#ifdef ARGO_DEBUG
		if (argo_debug[D_ISO]) {
			printf("iso_pcbbind noname\n");
		}
#endif
		do {
			if (head->isop_lport++ < ISO_PORT_RESERVED ||
			    head->isop_lport > ISO_PORT_USERRESERVED)
				head->isop_lport = ISO_PORT_RESERVED;
			suf.s = htons(head->isop_lport);
			cp[0] = suf.data[0];
			cp[1] = suf.data[1];
		} while (iso_pcblookup(head, 0, (caddr_t) 0, isop->isop_laddr));
	}
#ifdef ARGO_DEBUG
	if (argo_debug[D_ISO]) {
		printf("iso_pcbbind returns 0, suf 0x%x\n", suf.s);
	}
#endif
	return 0;
}
/*
 * FUNCTION:		iso_pcbconnect
 *
 * PURPOSE:		Make the isopcb (isop) look like it's connected.
 *			In other words, give it the peer address given in
 *			the mbuf * (nam).   Make sure such a combination
 *			of local, peer addresses doesn't already exist
 *			for this protocol.  Internet mentality prevails here,
 *			wherein a src,dst pair uniquely identifies a connection.
 * 			Both net address and port must be specified in argument
 *			(nam).
 * 			If we don't have a local address for this socket yet,
 *			we pick one by calling iso_pcbbind().
 *
 * RETURNS:		errno E* or 0 if ok.
 *
 * SIDE EFFECTS:	Looks up a route, which may cause one to be left
 *			in the isopcb.
 *
 * NOTES:
 */
int
iso_pcbconnect(v, nam)
	void *v;
	struct mbuf    *nam;
{
	struct isopcb *isop = v;
	struct sockaddr_iso *siso = mtod(nam, struct sockaddr_iso *);
	int             local_zero, error = 0;
	struct iso_ifaddr *ia;

#ifdef ARGO_DEBUG
	if (argo_debug[D_ISO]) {
		printf("iso_pcbconnect(isop %p sock %p nam %p",
		    isop, isop->isop_socket, nam);
		printf("nam->m_len 0x%x), addr:\n", nam->m_len);
		dump_isoaddr(siso);
	}
#endif
	if (nam->m_len < siso->siso_len)
		return EINVAL;
	if (siso->siso_family != AF_ISO)
		return EAFNOSUPPORT;
	if (siso->siso_nlen == 0) {
		if ((ia = iso_ifaddr.tqh_first) != NULL) {
			int             nlen = ia->ia_addr.siso_nlen;
			memmove(nlen + TSEL(siso), TSEL(siso),
			siso->siso_plen + siso->siso_tlen + siso->siso_slen);
			bcopy((caddr_t) & ia->ia_addr.siso_addr,
			      (caddr_t) & siso->siso_addr, nlen + 1);
			/* includes siso->siso_nlen = nlen; */
		} else
			return EADDRNOTAVAIL;
	}
	/*
	 * Local zero means either not bound, or bound to a TSEL, but no
	 * particular local interface.  So, if we want to send somebody
	 * we need to choose a return address.
	 */
	local_zero =
		((isop->isop_laddr == 0) || (isop->isop_laddr->siso_nlen == 0));
	if (local_zero) {
		int             flags;

#ifdef ARGO_DEBUG
		if (argo_debug[D_ISO]) {
			printf("iso_pcbconnect localzero 1\n");
		}
#endif
		/*
		 * If route is known or can be allocated now, our src addr is
		 * taken from the i/f, else punt.
		 */
		flags = isop->isop_socket->so_options & SO_DONTROUTE;
		error = clnp_route(&siso->siso_addr,
		    (struct route_iso *)&isop->isop_route, flags, NULL, &ia);
		if (error)
			return error;
#ifdef ARGO_DEBUG
		if (argo_debug[D_ISO]) {
			printf("iso_pcbconnect localzero 2, ro->ro_rt %p",
			       isop->isop_route.ro_rt);
			printf(" ia %p\n", ia);
		}
#endif
	}
#ifdef ARGO_DEBUG
	if (argo_debug[D_ISO]) {
		printf("in iso_pcbconnect before lookup isop %p isop->sock %p\n",
		       isop, isop->isop_socket);
	}
#endif
	if (local_zero) {
		int             nlen, tlen, totlen;
		caddr_t         oldtsel, newtsel;
		siso = isop->isop_laddr;
		if (siso == 0 || siso->siso_tlen == 0)
			(void) iso_pcbbind(isop, (struct mbuf *)0,
			    (struct proc *)0);
		/*
		 * Here we have problem of squezeing in a definite network address
		 * into an existing sockaddr_iso, which in fact may not have room
		 * for it.  This gets messy.
		 */
		siso = isop->isop_laddr;
		oldtsel = TSEL(siso);
		tlen = siso->siso_tlen;
		nlen = ia->ia_addr.siso_nlen;
		totlen = tlen + nlen + offsetof(struct sockaddr_iso, siso_data[0]);
		if ((siso == &isop->isop_sladdr) &&
		    (totlen > sizeof(isop->isop_sladdr))) {
			struct mbuf    *m = m_get(M_DONTWAIT, MT_SONAME);
			if (m == 0)
				return ENOBUFS;
			m->m_len = totlen;
			isop->isop_mladdr = m;
			isop->isop_laddr = siso = mtod(m, struct sockaddr_iso *);
		}
		siso->siso_nlen = ia->ia_addr.siso_nlen;
		newtsel = TSEL(siso);
		memmove(newtsel, oldtsel, tlen);
		bcopy(ia->ia_addr.siso_data, siso->siso_data, nlen);
		siso->siso_tlen = tlen;
		siso->siso_family = AF_ISO;
		siso->siso_len = totlen;
		siso = mtod(nam, struct sockaddr_iso *);
	}
#ifdef ARGO_DEBUG
	if (argo_debug[D_ISO]) {
		printf("in iso_pcbconnect before bcopy isop %p isop->sock %p\n",
		    isop, isop->isop_socket);
	}
#endif
	/*
	 * If we had to allocate space to a previous big foreign address,
	 * and for some reason we didn't free it, we reuse it knowing
	 * that is going to be big enough, as sockaddrs are delivered in
	 * 128 byte mbufs.
	 * If the foreign address is small enough, we use default space;
	 * otherwise, we grab an mbuf to copy into.
	 */
	if (isop->isop_faddr == 0 || isop->isop_faddr == &isop->isop_sfaddr) {
		if (siso->siso_len <= sizeof(isop->isop_sfaddr))
			isop->isop_faddr = &isop->isop_sfaddr;
		else {
			struct mbuf    *m = m_get(M_DONTWAIT, MT_SONAME);
			if (m == 0)
				return ENOBUFS;
			isop->isop_mfaddr = m;
			isop->isop_faddr = mtod(m, struct sockaddr_iso *);
		}
	}
	bcopy((caddr_t) siso, (caddr_t) isop->isop_faddr, siso->siso_len);
#ifdef ARGO_DEBUG
	if (argo_debug[D_ISO]) {
		printf("in iso_pcbconnect after bcopy isop %p isop->sock %p\n",
		    isop, isop->isop_socket);
		printf("iso_pcbconnect connected to addr:\n");
		dump_isoaddr(isop->isop_faddr);
		printf("iso_pcbconnect end: src addr:\n");
		dump_isoaddr(isop->isop_laddr);
	}
#endif
	return 0;
}

/*
 * FUNCTION:		iso_pcbdisconnect()
 *
 * PURPOSE:		washes away the peer address info so the socket
 *			appears to be disconnected.
 *			If there's no file descriptor associated with the socket
 *			it detaches the pcb.
 *
 * RETURNS:		Nada.
 *
 * SIDE EFFECTS:	May detach the pcb.
 *
 * NOTES:
 */
void
iso_pcbdisconnect(v)
	void *v;
{
	struct isopcb  *isop = v;
	struct sockaddr_iso *siso;

#ifdef ARGO_DEBUG
	if (argo_debug[D_ISO]) {
		printf("iso_pcbdisconnect(isop %p)\n", isop);
	}
#endif
	/*
	 * Preserver binding infnormation if already bound.
	 */
	if ((siso = isop->isop_laddr) && siso->siso_nlen && siso->siso_tlen) {
		caddr_t         otsel = TSEL(siso);
		siso->siso_nlen = 0;
		memmove(TSEL(siso), otsel, siso->siso_tlen);
	}
	if (isop->isop_faddr && isop->isop_faddr != &isop->isop_sfaddr)
		m_freem(isop->isop_mfaddr);
	isop->isop_faddr = 0;
	if (isop->isop_socket->so_state & SS_NOFDREF)
		iso_pcbdetach(isop);
}

/*
 * FUNCTION:		iso_pcbdetach
 *
 * PURPOSE:		detach the pcb at *(isop) from it's socket and free
 *			the mbufs associated with the pcb..
 *			Dequeues (isop) from its head.
 *
 * RETURNS:		Nada.
 *
 * SIDE EFFECTS:
 *
 * NOTES:
 */
void
iso_pcbdetach(v)
	void *v;
{
	struct isopcb  *isop = v;
	struct socket  *so = isop->isop_socket;

#ifdef ARGO_DEBUG
	if (argo_debug[D_ISO]) {
		printf("iso_pcbdetach(isop %p socket %p so %p)\n",
		    isop, isop->isop_socket, so);
	}
#endif
#ifdef TPCONS
	if (isop->isop_chan) {
		struct pklcd *lcp = (struct pklcd *) isop->isop_chan;
		if (--isop->isop_refcnt > 0)
			return;
		if (lcp && lcp->lcd_state == DATA_TRANSFER) {
			lcp->lcd_upper = 0;
			lcp->lcd_upnext = 0;
			pk_disconnect(lcp);
		}
		isop->isop_chan = 0;
	}
#endif
	if (so) {		/* in the x.25 domain, we sometimes have no
				 * socket */
		so->so_pcb = 0;
		sofree(so);
	}
#ifdef ARGO_DEBUG
	if (argo_debug[D_ISO]) {
		printf("iso_pcbdetach 2 \n");
	}
#endif
	if (isop->isop_options)
		(void) m_free(isop->isop_options);
#ifdef ARGO_DEBUG
	if (argo_debug[D_ISO]) {
		printf("iso_pcbdetach 3 \n");
	}
#endif
	if (isop->isop_route.ro_rt)
		rtfree(isop->isop_route.ro_rt);
#ifdef ARGO_DEBUG
	if (argo_debug[D_ISO]) {
		printf("iso_pcbdetach 3.1\n");
	}
#endif
	if (isop->isop_clnpcache != NULL) {
		struct clnp_cache *clcp =
		mtod(isop->isop_clnpcache, struct clnp_cache *);
#ifdef ARGO_DEBUG
		if (argo_debug[D_ISO]) {
			printf("iso_pcbdetach 3.2: clcp %p freeing clc_hdr %p\n",
			    clcp, clcp->clc_hdr);
		}
#endif
		if (clcp->clc_hdr != NULL)
			m_free(clcp->clc_hdr);
#ifdef ARGO_DEBUG
		if (argo_debug[D_ISO]) {
			printf("iso_pcbdetach 3.3: freeing cache %p\n",
			    isop->isop_clnpcache);
		}
#endif
		m_free(isop->isop_clnpcache);
	}
#ifdef ARGO_DEBUG
	if (argo_debug[D_ISO]) {
		printf("iso_pcbdetach 4 \n");
	}
#endif
	remque(isop);
#ifdef ARGO_DEBUG
	if (argo_debug[D_ISO]) {
		printf("iso_pcbdetach 5 \n");
	}
#endif
	if (isop->isop_laddr && (isop->isop_laddr != &isop->isop_sladdr))
		m_freem(isop->isop_mladdr);
	free((caddr_t) isop, M_PCB);
}

/*
 * FUNCTION:		iso_pcbnotify
 *
 * PURPOSE:		notify all connections in this protocol's queue (head)
 *			that have peer address (dst) of the problem (errno)
 *			by calling (notify) on the connections' isopcbs.
 *
 * RETURNS:		Rien.
 *
 * SIDE EFFECTS:
 *
 * NOTES:		(notify) is called at splnet!
 */
void
iso_pcbnotify(head, siso, errno, notify)
	struct isopcb  *head;
	struct sockaddr_iso *siso;
	int             errno;
	void (*notify) __P((struct isopcb *));
{
	struct isopcb *isop;
	int             s = splnet();

#ifdef ARGO_DEBUG
	if (argo_debug[D_ISO]) {
		printf("iso_pcbnotify(head %p, notify %p) dst:\n",
			head, notify);
	}
#endif
	for (isop = head->isop_next; isop != head; isop = isop->isop_next) {
		if (isop->isop_socket == 0 || isop->isop_faddr == 0 ||
		    !SAME_ISOADDR(siso, isop->isop_faddr)) {
#ifdef ARGO_DEBUG
			if (argo_debug[D_ISO]) {
				printf("iso_pcbnotify: CONTINUE isop %p, sock %p\n",
				    isop, isop->isop_socket);
				printf("addrmatch cmp'd with (%p):\n",
					isop->isop_faddr);
				dump_isoaddr(isop->isop_faddr);
			}
#endif
			continue;
		}
		if (errno)
			isop->isop_socket->so_error = errno;
		if (notify)
			(*notify) (isop);
	}
	splx(s);
#ifdef ARGO_DEBUG
	if (argo_debug[D_ISO]) {
		printf("END OF iso_pcbnotify\n");
	}
#endif
}

/*
 * FUNCTION:		iso_pcblookup
 *
 * PURPOSE:		looks for a given combination of (faddr), (fport),
 *			(lport), (laddr) in the queue named by (head).
 *			Argument (flags) is ignored.
 *
 * RETURNS:		ptr to the isopcb if it finds a connection matching
 *			these arguments, o.w. returns zero.
 *
 * SIDE EFFECTS:
 *
 * NOTES:
 */
struct isopcb  *
iso_pcblookup(head, fportlen, fport, laddr)
	struct isopcb  *head;
	struct sockaddr_iso *laddr;
	caddr_t         fport;
	int             fportlen;
{
	struct isopcb *isop;
	caddr_t lp = TSEL(laddr);
	unsigned int    llen = laddr->siso_tlen;

#ifdef ARGO_DEBUG
	if (argo_debug[D_ISO]) {
		printf("iso_pcblookup(head %p laddr %p fport %p)\n",
		       head, laddr, fport);
	}
#endif
	for (isop = head->isop_next; isop != head; isop = isop->isop_next) {
		if (isop->isop_laddr == 0 || isop->isop_laddr == laddr)
			continue;
		if (isop->isop_laddr->siso_tlen != llen)
			continue;
		if (bcmp(lp, TSEL(isop->isop_laddr), llen))
			continue;
		if (fportlen && isop->isop_faddr &&
		    bcmp(fport, TSEL(isop->isop_faddr), (unsigned) fportlen))
			continue;
		/*
		 * PHASE2 addrmatch1 should be iso_addrmatch(a, b, mask)
		 * where mask is taken from isop->isop_laddrmask (new field)
		 * isop_lnetmask will also be available in isop if (laddr !=
		 * &zeroiso_addr && !iso_addrmatch1(laddr,
		 * &(isop->isop_laddr.siso_addr))) continue;
		 */
		if (laddr->siso_nlen && (!SAME_ISOADDR(laddr, isop->isop_laddr)))
			continue;
		return (isop);
	}
	return (struct isopcb *) 0;
}
#endif /* ISO */


text:
import os

def locking(func):
    """
    Locking to prevent dogpiling
    """
    def perform_locking(*args, **kwargs):
        lock_dir = os.path.join(os.path.dirname(__file__), '.lockdir')
        if not os.path.exists(lock_dir):
            try:
                os.mkdir(lock_dir)
                return func(*args, **kwargs)
            finally:
                os.rmdir(lock_dir)
        else:
            pass

    return perform_locking

redpajama_set_name: RedPajamaGithub


text:
using Plugin.XamJam.Screen;
using PropertyChanged;
using Xamarin.Forms;
using XamJam.Nav;

namespace XamJam.Demo.ViewModel
{
    [ImplementPropertyChanged]
    public class DemoScreenSizeViewModel
    {
        public Command BackCommand { get; }

        public double Width { get; set; }

        public double Height { get; set; }

        public DemoScreenSizeViewModel(Navigator navigator)
        {
            BackCommand = navigator.BackAsyncCommand;
        }

        internal void Update()
        {
            var cWidth = CrossScreen.Current.Size.Width;
            var cHeight = CrossScreen.Current.Size.Height;
            if (Width != cWidth)
            {
                Width = cWidth;
            }
            if (Height != cHeight)
            {
                Height = cHeight;
            }
        }
    }
}


text:
UsersSearchView = Backbone.View.extend({
	events: {
		'submit': 'searchForUsers',
		'click #find_friends_button': 'navigate'
	},

	title: 'Find Friends | YumHacker',

	description: 'Search for friends to find restaurants and bars endorsed by people you trust. Get restaurant and bar photos, reviews, hours and more!',

	initialize: function () {
		this.render();

		App.eventAggregator.trigger('domchange:title', this.title);
        App.eventAggregator.trigger('domchange:description', this.description);

		this.collection = new UserSuggestionsCollection();

		this.user_search_suggestion_list_view = new UsersSearchSuggestionListView({
			el: '#find_user_results_container',
			collection: this.collection
		});
	},

	render: function () {
		this.$el.html(render('users/search'));
	},

	searchForUsers: function (e) {
		e.preventDefault();
		var query = e.target[0].value;
		this.collection.fetch({ reset: true, data: { query: query } });
	},

	navigate: function (e) {
		e.preventDefault();
		App.navigate(e.currentTarget.pathname, { trigger: true });
	}
});


text:
class ApplicationController < ActionController::Base
  def current_user
    {}
  end
end


text:
package main

import (
	"fmt"
	"io"
	"os"

	"github.com/spf13/cobra"

	"k8s.io/helm/pkg/helm/helmpath"
	"k8s.io/helm/pkg/repo"
)

type repoRemoveCmd struct {
	out  io.Writer
	name string
	home helmpath.Home
}

func newRepoRemoveCmd(out io.Writer) *cobra.Command {
	remove := &repoRemoveCmd{out: out}

	cmd := &cobra.Command{
		Use:     "remove [flags] [NAME]",
		Aliases: []string{"rm"},
		Short:   "remove a chart repository",
		RunE: func(cmd *cobra.Command, args []string) error {
			if err := checkArgsLength(len(args), "name of chart repository"); err != nil {
				return err
			}
			remove.name = args[0]
			remove.home = settings.Home

			return remove.run()
		},
	}

	return cmd
}

func (r *repoRemoveCmd) run() error {
	return removeRepoLine(r.out, r.name, r.home)
}

func removeRepoLine(out io.Writer, name string, home helmpath.Home) error {
	repoFile := home.RepositoryFile()
	r, err := repo.LoadRepositoriesFile(repoFile)
	if err != nil {
		return err
	}

	if !r.Remove(name) {
		return fmt.Errorf("no repo named %q found", name)
	}
	if err := r.WriteFile(repoFile, 0644); err != nil {
		return err
	}

	if err := removeRepoCache(name, home); err != nil {
		return err
	}

	fmt.Fprintf(out, "%q has been removed from your repositories\n", name)

	return nil
}

func removeRepoCache(name string, home helmpath.Home) error {
	if _, err := os.Stat(home.CacheIndex(name)); err == nil {
		err = os.Remove(home.CacheIndex(name))
		if err != nil {
			return err
		}
	}
	return nil
}


text:
package org.javamoney.moneta.spi.loader;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.javamoney.moneta.spi.LoaderService.LoaderListener;

class DefaultLoaderListener {

	private static final Logger LOG = Logger.getLogger(DefaultLoaderListener.class.getName());

	private final Map<String, List<LoaderListener>> listenersMap = new ConcurrentHashMap<>();

	 /**
     * Evaluate the {@link LoaderListener} instances, listening fo a dataId
     * given.
     *
     * @param dataId The dataId, not null
     * @return the according listeners
     */
    public List<LoaderListener> getListeners(String dataId) {
        if (dataId==null) {
            dataId = "";
        }
        List<LoaderListener> listeners = this.listenersMap.get(dataId);
        if (listeners==null) {
            synchronized (listenersMap) {
                listeners = this.listenersMap.get(dataId);
                if (listeners==null) {
                    listeners = Collections.synchronizedList(new ArrayList<LoaderListener>());
                    this.listenersMap.put(dataId, listeners);
                }
            }
        }
        return listeners;
    }

    /**
     * Trigger the listeners registered for the given dataId.
     *
     * @param dataId the data id, not null.
     * @param is     the InputStream, containing the latest data.
     */
    public void trigger(String dataId, InputStream is) {
        List<LoaderListener> listeners = getListeners("");
        //noinspection SynchronizationOnLocalVariableOrMethodParameter
        synchronized (listeners) {
            for (LoaderListener ll : listeners) {
                try {
                    ll.newDataLoaded(dataId, is);
                } catch (Exception e) {
                    LOG.log(Level.SEVERE, "Error calling LoadListener: " + ll, e);
                }
            }
        }
        if (!(dataId==null || dataId.isEmpty())) {
            listeners = getListeners(dataId);
            //noinspection SynchronizationOnLocalVariableOrMethodParameter
            synchronized (listeners) {
                for (LoaderListener ll : listeners) {
                    try {
                        ll.newDataLoaded(dataId, is);
                    } catch (Exception e) {
                        throw new IllegalArgumentException("Failed to load new data: " + ll, e);
                    }
                }
            }
        }
    }

    @Override
    public String toString() {
        String sb = DefaultLoaderListener.class.getName() + '{' +
                "listenersMap: " + listenersMap + '}';
        return sb;
    }
}


text:
/*
 * Created on Oct 25, 2004
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package net.reliableresponse.notification.broker.impl;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.Vector;

import net.reliableresponse.notification.broker.ActionBroker;
import net.reliableresponse.notification.broker.BrokerFactory;
import net.reliableresponse.notification.web.actions.Action;

/**
 * @author drig
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
public class PropertiesActionBroker implements ActionBroker {
	Properties properties;

	public PropertiesActionBroker() {
		properties = new Properties();
		try {
			properties.load(new FileInputStream(BrokerFactory.getConfigurationBroker().getStringValue("tomcat.location")+"/webapps/notification/conf/actions.properties"));
		} catch (FileNotFoundException e) {
			BrokerFactory.getLoggingBroker().logError(e);
		} catch (IOException e) {
			BrokerFactory.getLoggingBroker().logError(e);
		}
	}

	/* (non-Javadoc)
	 * @see net.reliableresponse.notification.broker.ActionBroker#getActionsForPage(java.lang.String)
	 */
	public Action[] getActionsForPage(String page) {
		Vector actions = new Vector();
		String classes = (String)properties.get(page);
		if (classes != null) {
			StringTokenizer tokenizer = new StringTokenizer(classes, ",");

			while (tokenizer.hasMoreElements()) {
				try {
					String className = (String) tokenizer.nextElement();
					BrokerFactory.getLoggingBroker().logDebug("action for "+page+" = "+className);
					Action action = (Action) Class.forName(className)
							.newInstance();
					actions.addElement(action);
				} catch (InstantiationException e) {
					BrokerFactory.getLoggingBroker().logError(e);
				} catch (IllegalAccessException e) {
					BrokerFactory.getLoggingBroker().logError(e);
				} catch (ClassNotFoundException e) {
					BrokerFactory.getLoggingBroker().logError(e);
				}
			}
		}

		return (Action[])actions.toArray(new Action[0]);
	}

}


text:
type: post
title:  Lowering the Space Object Footprint
categories: SBP
parent: data-access-patterns.html
weight: 900
---

|Author|XAP Version|Last Updated | Reference | Download |
|------|-----------|-------------|-----------|----------|
|Shay Hassidim| 7.1 | July 2009  |           |          |

# Overview
By default, when using the GigaSpaces Java API, the space stores space object fields as is. No data compaction, or compression is done while the object is transported across the network or when stored within the space.

{{% note %}}

- The Compressed Storage Type compressing non-primitive fields using the zip utilities. It is different than the compact serialization pattern.
- The Binary Storage Type store non-primitive fields within the space as it in its byte array form. It does not compress or reduce the footprint of the data as the compact pattern. It avoid the need to introduce nested space object data type to the space JVM and the need to de-serialize these at the space side. The Binary Storage Type may improve the performance when the space object store large collection.
- The C++ and .Net API objects data does go through some compaction when sent across the network.
{{% /note %}}

With the Compact Serialization pattern you may reduce the space object memory footprint when stored within the data grid. This allows you to store more space objects per memory unit. This pattern works very well when the space object includes large number of numerical values as it is storing these in more optimal data type.

The basic idea of the compact serialization pattern is simple: Total control on the format of the space object data while transported over the network and when stored within the space. This technique:

- Compacts the object payload data when transported over the network and when stored in memory.
- Avoids the de-serialization involved when space object written to the space from a remote client (for non primitive fields such as user defined classes or collection field)
- Avoids the de-serialization replicated to a backup space(s)
- Avoids the serialization involved when reading an object back from the space into the client process (at the space side).

# The Basic Flow
With the compact serialization pattern:

- Before you write the object you serialize all non indexed fields (payload data) into one byte array field using the GigaSpaces serialization API (pack).
- You serialize/de-serialize all indexed fields as usual (have the `writeExternal` , `readExternal` implementation to write and read these into the stream).
- After reading the object from the space you should de-serialize the byte array data (unpack).

{{% align center %}}
![bin_ser.jpg](/attachment_files/sbp/bin_ser.jpg)
{{% /align %}}

When the object is written to the space:

- The non-indexed fields are compacted and serialized into the same field (as a byte array).
- All the indexed fields + the byte array are serialized as usual via the `writeExternal` call.
- The object with arrives in the space, de-serialized, indexed fields stored as usual and the byte array field stored as is.

When the object is read from the space:

- The read template undergoes the same actions as when writing an object to the space
- The matching object is serialized and sent to the client.
- When the matching object arrives the client side is it de-serialized, and the byte array data is de-serialized and expand (in a lazy manner).

# The Implementation
Using the compact serialization pattern can reduce the object footprint when stored within the space in drastic manner. As much as you will have more fields as part of the space object serialized using the GigaSpaces Serialization API, the memory footprint overhead will be smaller compared to the default serialization mode.

The compact serialization pattern involves creation the following methods:

1. `pack` method - Packs the object data into one field. Serialize the non-Indexed fields into the byte array.
2. `unpack` method - Unpacks the object data into one field. De-serialize the non-Indexed fields from the byte array.
3. `writeExternal` method - Serialize the object data. Required for the `Externalizable` implementation. Serialize the indexed fields and the byte array.
4. `readExternal` method - De-serialize the object data. Required for the `Externalizable` implementation. De-serialize the indexed fields and the byte array.
5. `checkNulls` method - Handles null data for the indexed and byte array fields.
6. `getnulls` method - Handles null data for non indexed fields.

# BinaryOutputStream and BinaryInputStream
The `BinaryOutputStream` contains various method to serialize all java's primitive type, their Object wrappers and arrays forms in a compacted mode. `BinaryInputStream` is its counterpart for de serialization. Your `pack` and `unpack` methods will be using an instance of those classes.

# Example
With the [attached example](/attachment_files/sbp/BinaryCompaction.zip) we have a space class with 37 fields.

- 1 Integer data type field (indexed used for queries).
- 12 String fields
- 12 Long fields
- 12 Integer Fields.

{{% info %}}
With this example - The footprint overhead of the default serialization compared to a compact format is **250%**.
{{% /info %}}

To run this example copy the example package zip into \GigaSpaces Root\examples\, extract the zip file and follow the instructions at the readme file.

## The Original Space class
Our example involves a space class that will be modified to follow the compact serialization pattern.

The original class includes:

- One Integer indexed field.
- 12 String type non indexed fields declared as space class fields
- 12 Long type non indexed fields declared as space class fields
- 12 Integer type non indexed fields declared as space class fields
- Getter and Setter methods for the above fields

The original class looks like this:

```java
@SpaceClass
public class SimpleEntry {

	public SimpleEntry() {
	}
	private Integer queryField;
	private Long _longFieldA1;

	....

	@SpaceRouting
	@SpaceIndex(type=SpaceIndexType.BASIC)
	public Integer getQueryField() {
		return queryField;
	}

	// getter and setter methods
	public void setQueryField(Integer field) {
		queryField = field;
	}

	public Long get_longFieldA1() {
		return _longFieldA1;
	}

	public void set_longFieldA1(Long fieldA1) {
		_longFieldA1 = fieldA1;
	}
```

## The BinaryFormatEntry class
The modified class that implements the compact serialization pattern includes:

- Using the `@SpaceClass(includeProperties=IncludeProperties.EXPLICIT)` decoration - this allows you to control which fields will be Space class fields explicitly.
- One Integer indexed field.
- One byte array field declared as a space class field.
- 12 String type non indexed fields. These are not space class fields.
- 12 Long type non indexed fields. These are not space class fields.
- 12 Integer type non indexed fields. These are not space class fields.
- Getter and setter methods for the above fields.
- `pack` and `unpack` method and few helper methods.
- `Externalizable` implementation - `writeExternal` and `readExternal` methods

The modified class looks like this:

```java
@SpaceClass(includeProperties=IncludeProperties.EXPLICIT)
public class BinaryFormatEntry implements Externalizable {

	public BinaryFormatEntry(){}

	private Integer    queryField;
	private byte[]     _binary;

	private Long       _longFieldA1;
	....

	@SpaceRouting
	@SpaceIndex(type=SpaceIndexType.BASIC)
		public Long getQueryField()
	{
	    return queryField;
	}

	public void setQueryField(Long _queryField)
	{
	    queryField = _queryField;
	}

	@SpaceProperty
	public byte[] getBinary() {
		return _binary;
	}

	public void setBinary(byte[] _binary) {
		this._binary = _binary;
	}

	public Long get_longFieldA1() {
		return _longFieldA1;
	}

	public void set_longFieldA1(Long fieldA1) {
		_longFieldA1 = fieldA1;
	}
	...

	public void pack(){...}
	public void unpack(){...}
	public void writeExternal(ObjectOutput out){...}
	public void readExternal(ObjectInput in) {...}
	private long getnulls(){...}
	private short checkNulls() {...}
}
```

## The pack method
The `pack` method serializes the object non indexed data. It is called explicitly before calling the space write operation. This method serialize the object data by placing the data into the byte array field. Null values fields indication stored within one field. The `BinaryOutputStream` utility class is used to write the compacted data into the byte array.

```java
public void pack() throws Exception
{
    BinaryOutputStream output = new BinaryOutputStream();
    long nulls = getNulls();
    output.writeLong(nulls);
    if (_longFieldA1 != null)
        output.writeLong(_longFieldA1);

    // ... etc. for all other compactable fields.

    _binary = output.toByteArray();
    output.close();
}
```

## The unpack method
This method de-serialize the object data by extracting the data from the byte array field and populating the fields with their corresponding values. `null` values fields are non-populated.  This method is called after calling the space read operation. The `BinaryOutputStream` utility class is used to read the compacted data and place it into the relevant field.

```java
public void unpack() throws Exception
{
    BinaryInputStream input = new BinaryInputStream(_binary);
    long nulls = input.readLong();
    int i = 0;

    if ((nulls & 1L << i) == 0)
        _longFieldA1 = input.readLong();
    i++;

    // ... etc. for all other compactable fields.

    input.close();
    _binary = null;
}
```

## The writeExternal method
The `writeExternal` method serializes the object data into the output stream.  The object data involves a field indicates which fields have `null` value, the indexed fields and a byte array field that includes all non indexed fields data (created by the `pack` method). The `writeExternal` assumes the `pack` method has been called explicitly prior the space write method call that initiated the `writeExternal` call.

```java
public void writeExternal(ObjectOutput out) throws IOException {
	short nulls = 0;
    int i=0;

    nulls = checkNulls();

    out.writeShort(nulls);
    if (queryField != null) {
        out.writeLong(queryField);
    }
    if (_binary != null) {
        out.write(_binary);
    }
}
```

## The readExternal method
The `readExternal` method essentially performs the opposite of the what the `writeExternal` method is doing. This methods populates the indexed fields data and the byte array field data. Later, the remaining fields will be populated once the `unpack` method will be called.

```java
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
	short nulls;
    int i=0;
    nulls = in.readShort();

    if( (nulls & 1L << i) == 0 )
      queryField = in.readLong();
    i++;
    if( (nulls & 1L << i) == 0 )
    {
         byte[] data = new byte[500];
         int len = in.read(data);
         _binary = new byte[len];
         System.arraycopy(data, 0, _binary, 0, len);
    }
}
```

## The checkNulls method
This method goes through the indexed fields and the byte array field and place into a `short` data type field an indication for the ones with null value using a bit map.

```java
private short checkNulls() {
    short nulls = 0;
    int i = 0;

    nulls = (short) ((queryField == null) ? nulls | 1 << i : nulls);
    i++;
    nulls = (short) ((_binary == null) ? nulls | 1 << i : nulls);
    i++;
    return nulls;
}
```

## The getnulls method
This method goes through all class non indexed fields (the ones that their data is stored within the byte array) and place into a `long` data type field indication for the ones with null value using a bit map.

```java
private long getnulls()
{
    long nulls = 0;
    int i=0;

    nulls = ((_longFieldA1 == null)  ? nulls | 1L << i : nulls ) ;
    i++;
    nulls = ((_longFieldB1 == null)  ? nulls | 1L << i : nulls ) ;
    i++;
    ...
    return nulls;
}
```

## The Factory method
The example using a factory method called `generateBinaryFormatEntry` to create the space object. Once it has been populated , its `pack` method is called.

```java
private BinaryFormatEntry generateBinaryFormatEntry(int id){
	BinaryFormatEntry bfe = new BinaryFormatEntry(id, value1 , value2 ?)
	bfe.pack();     //  the pack method is called implicitly as part of the factory method
	return bfe;
}
```

## Writing and Reading the Object from the space
The following code snipped illustrates how the compact serialized object is written into the space and read from the space:

```java
GigaSpace _gigaspace;
BinaryFormatEntry testBFE = generateBinaryFormatEntry(500);
_gigaspace.write(testBFE, Lease.FOREVER);
BinaryFormatEntry templateBFE = new BinaryFormatEntry();
templateBFE.setQueryField (new Long(500));
BinaryFormatEntry resBFE = (BinaryFormatEntry)_gigaspace.read(templateBFE, 0);
resBFE.unpack(); // this deserialize the binary data into the object fields
```

# References
The [PackRat](http://www.openspaces.org/display/PRT/PackRat) project allows you to use the compact serialization pattern via simple annotations.


text:
USAGE=$'api_checker.bash [-n] <gazebo_source_dir>
  -n : Do not install latest Gazebo via apt-get (assumes that you have already installed the version that you want to compare against)'

# Stop on error
set -e

# Parse args
install_gazebo=1
if [[ $# -lt 1 ]]; then
  echo "$USAGE"
  exit 1
elif [[ $# -gt 1 ]]; then
  if [[ $1 == "-n" ]]; then
    install_gazebo=0
    srcdir=$2
    # Do we have gazebo or gazebo-current installed?
    gazebo_name="gazebo-current"
    if ! dpkg -l $gazebo_name > /dev/null || [[ `dpkg -L $gazebo_name | wc | awk {'print $1'}` -lt 2 ]]; then
      gazebo_name="gazebo"
      if ! dpkg -l $gazebo_name > /dev/null || [[ `dpkg -L $gazebo_name | wc | awk {'print $1'}` -lt 2 ]]; then
        echo "Couldn't find an existing installation of gazebo or gazebo-current, and you passed -n, telling me not to install gazebo-current."
        exit 1
      fi
    fi
    echo "Found installation of $gazebo_name."
  else
    echo "$USAGE"
    exit 1
  fi
else
  srcdir=$1
  gazebo_name="gazebo-current"
fi

# Convert to absolute path, in case the developer gave something like '..'
GAZEBO_SOURCE_DIR=$(readlink -f $srcdir)
GAZEBO_BRANCH=$(cd $GAZEBO_SOURCE_DIR && hg branch)

# Install Gazebo and some tools we'll need
sudo apt-get update
if [[ $install_gazebo -eq 1 ]]; then
  sudo apt-get install $gazebo_name
fi
sudo apt-get install exuberant-ctags git
# Also install things that are needed to build Gazebo.  We want to ensure
# that we end up with the same set of system packages, especially the optional
# ones, that are used in building the Gazebo .deb.  For now, I'm copying in the
# Build-Depends from precise/debian/control.  That's not ideal, but will
# probably work.
sudo apt-get install cmake \
     debhelper \
     doxygen \
     doxygen-latex \
     libfreeimage-dev \
     libprotoc-dev \
     libprotobuf-dev \
     protobuf-compiler \
     freeglut3-dev \
     libcurl4-openssl-dev \
     libtinyxml-dev \
     libtar-dev \
     libtbb-dev \
     libogre-dev \
     libxml2-dev \
     pkg-config \
     libqt4-dev \
     libltdl-dev \
     libboost-thread-dev \
     libboost-signals-dev \
     libboost-system-dev \
     libboost-filesystem-dev \
     libboost-program-options-dev \
     libboost-regex-dev \
     libboost-iostreams-dev \
     robot-player-dev \
     libcegui-mk2-dev \
     libavformat-dev \
     libavcodec-dev \
     libswscale-dev \
     sdformat

# Install abi-compliance-checker.git
TMPDIR=$(mktemp -d)
mkdir $TMPDIR/source $TMPDIR/build $TMPDIR/install $TMPDIR/config
cd $TMPDIR/source
git clone git://github.com/lvc/abi-compliance-checker.git
cd abi-compliance-checker
perl Makefile.pl -install --prefix=$TMPDIR/install

# Figure out which libraries we're going to compare and what version of Gazebo
# we're working with.
GAZEBO_LIBS=$(dpkg -L $gazebo_name | grep lib.*.so)
GAZEBO_LIBS_LOCAL=$(dpkg -L $gazebo_name | grep lib.*.so | sed -e "s:^/usr:$TMPDIR/install:g")
BIN_VERSION=$(dpkg -l $gazebo_name | tail -n 1 | awk '{ print  $3 }')
MAJOR_MINOR=$(echo $BIN_VERSION | cut -d . -f 1,2)

echo "We're going to compare your working copy in $srcdir with the system-installed version, which is $MAJOR_MINOR."

# Build and install Gazebo.  I'm doing this as a separate build to avoid
# unexpected interactions with the developer's own build space.  An
# optimization would be to allow reuse of an existing build space.
cd $TMPDIR/build
cmake -DENABLE_TESTS_COMPILATION:BOOL=False -DCMAKE_INSTALL_PREFIX=$TMPDIR/install $GAZEBO_SOURCE_DIR
# Assume that we can use all cores
MAKE_JOBS=$(grep -c ^processor /proc/cpuinfo)
make -j${MAKE_JOBS}
make install

# Generate the spec for our reference version of Gazebo.
cat > $TMPDIR/config/pkg.xml << CURRENT_DELIM
 <version>
     .deb pkg version: $BIN_VERSION
 </version>

 <headers>
   /usr/include/gazebo-$MAJOR_MINOR/gazebo
 </headers>

 <skip_headers>
   /usr/include/gazebo-$MAJOR_MINOR/gazebo/GIMPACT
   /usr/include/gazebo-$MAJOR_MINOR/gazebo/opcode
   /usr/include/gazebo-$MAJOR_MINOR/gazebo/test
 </skip_headers>

 <libs>
  $GAZEBO_LIBS
 </libs>
CURRENT_DELIM

# Generate the spec for our development version of Gazebo.
cat > $TMPDIR/config/devel.xml << DEVEL_DELIM
 <version>
     branch: $GAZEBO_BRANCH
 </version>

  <headers>
   $TMPDIR/install/include/gazebo-$MAJOR_MINOR/gazebo
 </headers>

 <skip_headers>
   $TMPDIR/install/include/gazebo-$MAJOR_MINOR/gazebo/GIMPACT
   $TMPDIR/install/include/gazebo-$MAJOR_MINOR/gazebo/opcode
   $TMPDIR/install/include/gazebo-$MAJOR_MINOR/gazebo/test
 </skip_headers>

 <libs>
  $GAZEBO_LIBS_LOCAL
 </libs>
DEVEL_DELIM

# Run the check
cd $TMPDIR/config
$TMPDIR/install/bin/abi-compliance-checker -lib gazebo -old pkg.xml -new devel.xml || true

echo "Your compatibility reports are in: "
echo "  $TMPDIR/config/compat_reports."
echo "When you're done, you might want to remove the working directory:"
echo "  $TMPDIR"


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
	<string name="app_name">Hologram</string>
</resources>


text:
import {info} from '../utils/console';
import {PullApproveGroupResult} from './group';

/** Create logs for each pullapprove group result. */
export function logGroup(group: PullApproveGroupResult, matched = true, printMessageFn = info) {
  const conditions = matched ? group.matchedConditions : group.unmatchedConditions;
  printMessageFn.group(`[${group.groupName}]`);
  if (conditions.length) {
    conditions.forEach(matcher => {
      const count = matcher.matchedFiles.size;
      printMessageFn(`${count} ${count === 1 ? 'match' : 'matches'} - ${matcher.expression}`);
    });
    printMessageFn.groupEnd();
  }
}

/** Logs a header within a text drawn box. */
export function logHeader(...params: string[]) {
  const totalWidth = 80;
  const fillWidth = totalWidth - 2;
  const headerText = params.join(' ').substr(0, fillWidth);
  const leftSpace = Math.ceil((fillWidth - headerText.length) / 2);
  const rightSpace = fillWidth - leftSpace - headerText.length;
  const fill = (count: number, content: string) => content.repeat(count);

  info(`┌${fill(fillWidth, '─')}┐`);
  info(`│${fill(leftSpace, ' ')}${headerText}${fill(rightSpace, ' ')}│`);
  info(`└${fill(fillWidth, '─')}┘`);
}


text:
#pragma once
#include <aws/ec2/EC2_EXPORTS.h>
#include <aws/ec2/EC2Request.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <utility>

namespace Aws
{
namespace EC2
{
namespace Model
{

  /**
   */
  class AWS_EC2_API AssignIpv6AddressesRequest : public EC2Request
  {
  public:
    AssignIpv6AddressesRequest();
    Aws::String SerializePayload() const override;

  protected:
    void DumpBodyToUrl(Aws::Http::URI& uri ) const override;

  public:
    /**
     *
The ID of the network interface.

     */
    inline const Aws::String& GetNetworkInterfaceId() const{ return m_networkInterfaceId; }

    /**
     *
The ID of the network interface.

     */
    inline void SetNetworkInterfaceId(const Aws::String& value) { m_networkInterfaceIdHasBeenSet = true; m_networkInterfaceId = value; }

    /**
     *
The ID of the network interface.

     */
    inline void SetNetworkInterfaceId(Aws::String&& value) { m_networkInterfaceIdHasBeenSet = true; m_networkInterfaceId = std::move(value); }

    /**
     *
The ID of the network interface.

     */
    inline void SetNetworkInterfaceId(const char* value) { m_networkInterfaceIdHasBeenSet = true; m_networkInterfaceId.assign(value); }

    /**
     *
The ID of the network interface.

     */
    inline AssignIpv6AddressesRequest& WithNetworkInterfaceId(const Aws::String& value) { SetNetworkInterfaceId(value); return *this;}

    /**
     *
The ID of the network interface.

     */
    inline AssignIpv6AddressesRequest& WithNetworkInterfaceId(Aws::String&& value) { SetNetworkInterfaceId(std::move(value)); return *this;}

    /**
     *
The ID of the network interface.

     */
    inline AssignIpv6AddressesRequest& WithNetworkInterfaceId(const char* value) { SetNetworkInterfaceId(value); return *this;}

    /**
     *
One or more specific IPv6 addresses to be assigned to the network interface.
     * You can't use this option if you're specifying a number of IPv6 addresses.

     */
    inline const Aws::Vector<Aws::String>& GetIpv6Addresses() const{ return m_ipv6Addresses; }

    /**
     *
One or more specific IPv6 addresses to be assigned to the network interface.
     * You can't use this option if you're specifying a number of IPv6 addresses.

     */
    inline void SetIpv6Addresses(const Aws::Vector<Aws::String>& value) { m_ipv6AddressesHasBeenSet = true; m_ipv6Addresses = value; }

    /**
     *
One or more specific IPv6 addresses to be assigned to the network interface.
     * You can't use this option if you're specifying a number of IPv6 addresses.

     */
    inline void SetIpv6Addresses(Aws::Vector<Aws::String>&& value) { m_ipv6AddressesHasBeenSet = true; m_ipv6Addresses = std::move(value); }

    /**
     *
One or more specific IPv6 addresses to be assigned to the network interface.
     * You can't use this option if you're specifying a number of IPv6 addresses.

     */
    inline AssignIpv6AddressesRequest& WithIpv6Addresses(const Aws::Vector<Aws::String>& value) { SetIpv6Addresses(value); return *this;}

    /**
     *
One or more specific IPv6 addresses to be assigned to the network interface.
     * You can't use this option if you're specifying a number of IPv6 addresses.

     */
    inline AssignIpv6AddressesRequest& WithIpv6Addresses(Aws::Vector<Aws::String>&& value) { SetIpv6Addresses(std::move(value)); return *this;}

    /**
     *
One or more specific IPv6 addresses to be assigned to the network interface.
     * You can't use this option if you're specifying a number of IPv6 addresses.

     */
    inline AssignIpv6AddressesRequest& AddIpv6Addresses(const Aws::String& value) { m_ipv6AddressesHasBeenSet = true; m_ipv6Addresses.push_back(value); return *this; }

    /**
     *
One or more specific IPv6 addresses to be assigned to the network interface.
     * You can't use this option if you're specifying a number of IPv6 addresses.

     */
    inline AssignIpv6AddressesRequest& AddIpv6Addresses(Aws::String&& value) { m_ipv6AddressesHasBeenSet = true; m_ipv6Addresses.push_back(std::move(value)); return *this; }

    /**
     *
One or more specific IPv6 addresses to be assigned to the network interface.
     * You can't use this option if you're specifying a number of IPv6 addresses.

     */
    inline AssignIpv6AddressesRequest& AddIpv6Addresses(const char* value) { m_ipv6AddressesHasBeenSet = true; m_ipv6Addresses.push_back(value); return *this; }

    /**
     *
The number of IPv6 addresses to assign to the network interface. Amazon EC2
     * automatically selects the IPv6 addresses from the subnet range. You can't use
     * this option if specifying specific IPv6 addresses.

     */
    inline int GetIpv6AddressCount() const{ return m_ipv6AddressCount; }

    /**
     *
The number of IPv6 addresses to assign to the network interface. Amazon EC2
     * automatically selects the IPv6 addresses from the subnet range. You can't use
     * this option if specifying specific IPv6 addresses.

     */
    inline void SetIpv6AddressCount(int value) { m_ipv6AddressCountHasBeenSet = true; m_ipv6AddressCount = value; }

    /**
     *
The number of IPv6 addresses to assign to the network interface. Amazon EC2
     * automatically selects the IPv6 addresses from the subnet range. You can't use
     * this option if specifying specific IPv6 addresses.

     */
    inline AssignIpv6AddressesRequest& WithIpv6AddressCount(int value) { SetIpv6AddressCount(value); return *this;}

  private:
    Aws::String m_networkInterfaceId;
    bool m_networkInterfaceIdHasBeenSet;
    Aws::Vector<Aws::String> m_ipv6Addresses;
    bool m_ipv6AddressesHasBeenSet;
    int m_ipv6AddressCount;
    bool m_ipv6AddressCountHasBeenSet;
  };

} // namespace Model
} // namespace EC2
} // namespace Aws


text:
import { RouterModule, Routes } from '@angular/router';
import { MembersComponent } from "./members/members.component";
import { MaintenanceComponent } from "./maintenance/maintenance.component";
import { LoginComponent } from "./login/login.component";
import { NametagsComponent } from './nametags/nametags.component';
import { ReportsComponent } from './reports/reports.component';
import { LocationStrategy } from "@angular/common";
import { AppComponent } from "./app.component";

// TODO: create some auth routes
export const AppRoutes: Routes = [
  { path: 'login', component: LoginComponent },
  { path: 'members', component: MembersComponent },
  { path: 'maintenance', component: MaintenanceComponent },
  { path: 'nametags', component: NametagsComponent },
  { path: 'reports', component: ReportsComponent}
];

export const routing = RouterModule.forRoot(
  AppRoutes
);


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:id="@+id/faqCardView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@android:color/transparent"
    card_view:cardElevation="5dp">

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="145dp"
        android:layout_gravity="fill">

        <com.usercare.views.FaqButton
            android:id="@+id/faqButton"
            android:layout_gravity="center"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:padding="5dp"
            android:minHeight="85dp"/>

    </FrameLayout>

</android.support.v7.widget.CardView>


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

#ifndef _CMP_BRINGIC_H_
#define _CMP_BRINGIC_H_

#include <vector>
#include <list>

#include "Interconnect.hpp"

namespace cmpex {

  namespace cmp {

    class Cluster;

    //======================================================================
    // This class represents a bidirectional ring interconnect for CMP.
    // The ring has a list of device components and possibly memory controllers
    // (not fully supported at the moment), plus an additional interface
    // component (NI). The interface component is present implicitly as the last
    // one in the list. The ring has two virtual channels to resolve deadlocks
    // (referred to as ports). Packets switch from VC0 to VC1 once they travel
    // from the NI component to the following one.
    // The routing algorithm is the shortest path. In case of equidistant
    // routing paths in both directions clockwise direction is chosen.
    //
    // Port indices (structure of traffic matrix and buffer arrays):
    // Every ring router has 3 physical (5 virtual) input ports:
    //   Index 0: component
    //   Index 1, 2: pass-through connection clockwise direction
    //   Index 3, 4: pass-through connection counterclockwise direction
    // Every ring router has 3 output ports:
    //   Index 0: component
    //   Index 1: pass-through clockwise
    //   Index 2: pass-through counterclockwise
    //======================================================================

    class BRingIc : public Interconnect {

      typedef std::vector<double> DoubleArray;

    public:

      // number of input ports in ring router: integer value for quick access
      static const UShort IPORT_NUM = 5;

      // number of output ports in ring router: integer value for quick access
      static const UShort OPORT_NUM = 3;

      // number of port pairs in router: integer value for quick access
      static const UShort PORT_PAIR_NUM = UShort(IPORT_NUM*OPORT_NUM);

      // ---------------------------- Methods ------------------------------

    public:

      // Constructors & destructor
      BRingIc (Cluster * c, UInt subnCnt);

      virtual ~BRingIc ();

      // Accessors
      // Total number of components, with iface and mcs
      inline int TotalCompCnt () const;

      // Number of device-related components
      inline int CompCnt () const;

      inline void CompCnt ( int c );

      inline int RouterDelay () const;

      inline void RouterDelay ( int d );

      inline int LinkDelay () const;

      inline void LinkDelay ( int d );

      // Implementation of the Interconnect interface

      // Returns hop-count distance from component with index 'srcIdx' to
      // another component with index 'dstIdx'.
      virtual int DistanceCompToComp (UShort srcIdx, UShort dstIdx);

      // Returns hop-count distance from component with index 'idx' to
      // the Iface component.
      virtual int DistanceCompToIface (UShort idx);

      // Returns latency from component with index 'srcIdx' to
      // another component with index 'dstIdx'.
      virtual double LatencyCompToComp (
          UShort srcIdx, UShort dstIdx, UShort pSize, bool dynamic, UShort subnIdx);

      // Returns latency from component with index 'idx' to the memory
      // controller 'mcIdx'.
      virtual double LatencyCompToMemCtrl (
          UShort idx, UShort mcIdx, UShort pSize, bool dynamic, UShort subnIdx);

      // Returns latency from component with index 'idx' to
      // the interface component.
      virtual double LatencyCompToIface (UShort idx, UShort pSize, bool dynamic, UShort subnIdx);

      // Returns latency from the interface component to
      // component with index 'idx'.
      virtual double LatencyIfaceToComp (UShort idx, UShort pSize, bool dynamic, UShort subnIdx);

      // Returns latency from memory controller with index 'mcIdx' to
      // component with index 'idx'.
      virtual double LatencyMemCtrlToComp (
          UShort mcIdx, UShort idx, UShort pSize, bool dynamic, UShort subnIdx);

      // Follow route between components (or a component and a memctrl)
      // and save the traffic rates into the matrix.
      virtual void MarkPathCompToComp (
          UShort srcIdx, UShort dstIdx, double traffic, UShort subnIdx);

      virtual void MarkPathCompToMemCtrl (
          UShort cIdx, UShort mcIdx, double traffic, UShort subnIdx);

      virtual void MarkPathMemCtrlToComp (
          UShort mcIdx, UShort cIdx, double traffic, UShort subnIdx);

      virtual void MarkPathCompToIface (UShort idx, double traffic, UShort subnIdx);

      virtual void MarkPathIfaceToComp (UShort idx, double traffic, UShort subnIdx);

      // Initialize traffic matrix and duffer delays.
      virtual void InitModel();

      // Run analytical modeling of the contention delays in input buffers.
      virtual int EstimateBufferDelays(bool fixNegDelays = false);

      // Access value of traffic matrix for 'iPort' -> 'oPort' of router 'rIdx'.
      inline double& Traffic (UShort subnIdx, UShort rIdx, UShort iPort, UShort oPort);

      // Access value of buffer delay for 'iPort' of router 'rIdx'.
      inline double& BufDelay (UShort subnIdx, UShort rIdx, UShort iPort);

      /* The following are the rudiments of the MATLAB model and should be eliminated. */

      virtual bool PortOnPathCompToComp(UShort srcIdx, UShort dstIdx, UShort rIdx, UShort pIdx) {
        return false;
      }

      virtual bool PortOnPathCompToMemCtrl(UShort srcIdx, UShort mc, UShort rIdx, UShort pIdx) {
        return false;
      }

      virtual bool PortOnPathMemCtrlToComp(UShort mc, UShort dstIdx, UShort rIdx, UShort pIdx) {
        return false;
      }

      virtual void DumpLatencyEqCompToComp(UShort srcIdx, UShort dstIdx,
                                           double prob, std::ostringstream& os) {}

      virtual void DumpLatencyEqCompToMemCtrl(UShort srcIdx, UShort mcIdx,
                                              double prob, std::ostringstream& os) {}

      virtual void DumpLatencyEqMemCtrlToComp(UShort mcIdx, UShort dstIdx,
                                              double prob, std::ostringstream& os) {}

      virtual bool PathCompToCompFollowsPorts(UShort srcIdx, UShort dstIdx,
                                              UShort r, UShort pi, UShort po) {}

      virtual bool PathCompToMemCtrlFollowsPorts(UShort srcIdx, UShort mcIdx,
                                                 UShort r, UShort pi, UShort po) {}

      virtual bool PathMemCtrlToCompFollowsPorts(UShort mcIdx, UShort dstIdx,
                                                 UShort r, UShort pi, UShort po) {}

      // Debug methods
      void Print () const;

    private:

      // Deprecated methods: prevent usage
      BRingIc ( const BRingIc& );

      BRingIc& operator = ( const BRingIc& );

      // -------------------------- Attributes -----------------------------

    private:

      int compCnt_; // number of components in ring

      int totalCompCnt_; // total number of components in ring, with iface and mcs

      int routerDelay_; // router delay (in cycles)

      int linkDelay_; // link delay (in cycles)

      // Matrix of traffic rates per IO-port pair per router per subnetwork.
      // To access the value of traffic from input port I to output port O
      // of router R in subnetwork S, use the the index
      // tm_[S*TotalCompCnt()*PORT_PAIR_NUM + R*PORT_PAIR_NUM + I*OPORT_NUM + O].
      DoubleArray tm_;

      // Matrix of buffer delays per I-port per router per subnetwork.
      // To access the delay value for input port I of router R in subnetwork S,
      // use the the index bufDelays_[S*TotalCompCnt()*IPORT_NUM + R*IPORT_NUM + I].
      DoubleArray bufDelays_;

    };

    //----------------------------------------------------------------------
    // Inline functions
    //----------------------------------------------------------------------

    int BRingIc::CompCnt () const {
      return compCnt_;
    }

    void BRingIc::CompCnt (int c) {
      compCnt_ = c;
      totalCompCnt_ = c+1; // add iface component
    }

    int BRingIc::TotalCompCnt () const {
      return totalCompCnt_;
    }

    int BRingIc::RouterDelay () const {
      return routerDelay_;
    }

    void BRingIc::RouterDelay (int d) {
      routerDelay_ = d;
    }

    int BRingIc::LinkDelay () const {
      return linkDelay_;
    }

    void BRingIc::LinkDelay (int d) {
      linkDelay_ = d;
    }

    double& BRingIc::Traffic (UShort subnIdx, UShort rIdx, UShort iPort, UShort oPort) {
      return tm_[subnIdx*TotalCompCnt()*PORT_PAIR_NUM + rIdx*PORT_PAIR_NUM + iPort*OPORT_NUM +oPort];
    }

    double& BRingIc::BufDelay (UShort subnIdx, UShort rIdx, UShort iPort) {
      return bufDelays_[subnIdx*TotalCompCnt()*IPORT_NUM + rIdx*IPORT_NUM + iPort];
    }

  } // namespace cmp

} // namespace cmpex

#endif // _CMP_BRINGIC_H_


text:
@implementation LDLTagButtonContainerView

- (id)initWithFrame:(NSRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code here.
    }
    return self;
}

- (void)drawRect:(NSRect)dirtyRect
{
	[super drawRect:dirtyRect];

    // Drawing code here.
}

-(BOOL)isFlipped {
  return YES;
}

@end


text:
var Collection = require('./ApplicationCollection');
describe('ApplicationCollection.js', function() {

	var sandbox;

	beforeEach(function() {
	    sandbox = sinon.sandbox.create();
	});

	afterEach(function() {
	    sandbox.restore();
	});

	it('should set the dataSource if provided in the options', function() {
		var dataSource = {};
	    var c = new Collection([], { dataSource: dataSource });
	    expect(c.dataSource).to.equal(dataSource);
	});

	it('should fetch from the server if the number of running applications has changed.', function() {
	    sandbox.stub(Collection.prototype, 'fetch');

	    var c = new Collection([
		    { id: 'app1', state: 'RUNNING' },
		    { id: 'app2', state: 'RUNNING' },
		    { id: 'app3', state: 'FAILED' }
	    ], { dataSource: {} });

	    c.setRunning([
		    { id: 'app1', state: 'RUNNING' },
		    { id: 'app2', state: 'FAILED' },
		    { id: 'app3', state: 'FAILED' }
	    ]);

	    expect(Collection.prototype.fetch).to.have.been.calledOnce;
	});

	describe('the fetch method', function() {

		var dataSource, c;

		beforeEach(function() {
		    dataSource = {};
	    	c = new Collection([], { dataSource: dataSource });
		});

	    it('should pass the option data.states=RUNNING by default', function() {
	   		sandbox.stub($, 'ajax', function(options) {
	   			expect(options).to.have.property('data');
	   			expect(options.data).to.eql({ states: 'RUNNING' });
	   		});
	   		c.fetch();
	    });

	    it('should add the option data.states=RUNNING to an existing options that gets passed', function() {
	    	sandbox.stub($, 'ajax', function(options) {
	   			expect(options).to.have.property('data');
	   			expect(options.data).to.eql({ states: 'RUNNING' });
	   			expect(options.async).to.equal(false);
	   		});
	   		c.fetch({
	   			async: false
	   		});
	    });

	    it('should not add the option data.states=RUNNING to an existing options that gets passed if data is already set', function() {
	    	sandbox.stub($, 'ajax', function(options) {
	   			expect(options).to.have.property('data');
	   			expect(options.data).to.eql({ param: 'value' });
	   		});
	   		c.fetch({
	   			data: {
	   				param: 'value'
	   			}
	   		});
	    });
	});

});


text:
package de.codepitbull.events;

import org.apache.wicket.ajax.AjaxRequestTarget;

/**
 * Copyright (C) 2012 by Jochen Mader (pflanzenmoerder@gmail.com)
 * ==============================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *

 * http://www.apache.org/licenses/LICENSE-2.0
 *

 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
public class ResetEvent {
	private final AjaxRequestTarget target;

	public ResetEvent(AjaxRequestTarget target) {
		this.target = target;
	}

	public AjaxRequestTarget getTarget() {
		return target;
	}
}


text:
<project>
	<modelVersion>4.0.0</modelVersion>
	<groupId>it.polimi</groupId>
	<artifactId>PowerMonitor</artifactId>
	<version>1.0</version>
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
	</properties>
	<dependencies>
<!-- 		<dependency>
		    <groupId>jdk.tools</groupId>
		    <artifactId>jdk.tools</artifactId>
		    <version>1.7.0_25</version>
		    <scope>system</scope>
		    <systemPath>${JAVA_HOME}/lib/tools.jar</systemPath>
		</dependency> -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.13.1</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.hamcrest</groupId>
			<artifactId>hamcrest-all</artifactId>
			<version>1.1</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.apache.hadoop</groupId>
			<artifactId>hadoop-common</artifactId>
			<version>3.2.3</version>
		</dependency>
		<dependency>
			<groupId>org.apache.hadoop</groupId>
			<artifactId>hadoop-common</artifactId>
			<version>3.2.3</version>
			<type>test-jar</type>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.apache.hadoop</groupId>
			<artifactId>hadoop-hdfs</artifactId>
			<version>2.2.0</version>
		</dependency>
		<dependency>
			<groupId>org.apache.hadoop</groupId>
			<artifactId>hadoop-hdfs</artifactId>
			<version>2.2.0</version>
			<type>test-jar</type>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.apache.hadoop</groupId>
			<artifactId>hadoop-mapreduce-client-app</artifactId>
			<version>2.2.0</version>
		</dependency>
		<dependency>
			<groupId>org.apache.hadoop</groupId>
			<artifactId>hadoop-mapreduce-client-common</artifactId>
			<version>2.2.0</version>
		</dependency>
		<dependency>
			<groupId>org.apache.hadoop</groupId>
			<artifactId>hadoop-mapreduce-client-core</artifactId>
			<version>2.2.0</version>
		</dependency>
		<dependency>
			<groupId>org.apache.hadoop</groupId>
			<artifactId>hadoop-mapreduce-client-hs</artifactId>
			<version>2.2.0</version>
		</dependency>
		<dependency>
			<groupId>org.apache.hadoop</groupId>
			<artifactId>hadoop-mapreduce-client-jobclient</artifactId>
			<version>2.2.0</version>
		</dependency>
		<dependency>
			<groupId>org.apache.hadoop</groupId>
			<artifactId>hadoop-mapreduce-client-jobclient</artifactId>
			<version>2.2.0</version>
			<type>test-jar</type>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.apache.hadoop</groupId>
			<artifactId>hadoop-yarn-common</artifactId>
			<version>2.2.0</version>
		</dependency>
		<dependency>
			<groupId>org.apache.hadoop</groupId>
			<artifactId>hadoop-yarn-server-tests</artifactId>
			<version>2.2.0</version>
			<type>test-jar</type>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.apache.mrunit</groupId>
			<artifactId>mrunit</artifactId>
			<version>0.8.1-incubating</version>
			<classifier>hadoop023</classifier>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>com.sun.jersey</groupId>
			<artifactId>jersey-core</artifactId>
			<version>1.8</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.apache.pig</groupId>
			<artifactId>pig</artifactId>
			<version>0.12.0</version>
		</dependency>
	</dependencies>
	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>2.3.2</version>
				<configuration>
					<source>1.6</source>
					<target>1.6</target>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-jar-plugin</artifactId>
				<version>2.4</version>
				<configuration>
					<outputDirectory>${basedir}</outputDirectory>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>


text:
description: Pulls service images.
keywords: fig, composition, compose, docker, orchestration, cli,  pull
title: docker-compose pull
notoc: true
---

```
Usage: pull [options] [SERVICE...]

Options:
    --ignore-pull-failures  Pull what it can and ignores images with pull failures.
    --parallel              Pull multiple images in parallel.
```

Pulls service images.


text:
/**古代战争 小地图
 * 作者:YYC
 * 日期:2014-05-12
 * 电子邮箱:395976266@qq.com
 * QQ: 395976266
 * 博客:http://www.cnblogs.com/chaogex/
 */
(function () {
    var SpriteColor = {
        SELECT: "#ffffff",   //白色
        RESOURCE: "#EE00EE",  //紫色
        PLAYER: "#00FF00",    //绿色
        ENEMY: "#CD0000",     //红色
        MOUTAIN: "#8B4726"    //灰色
    };

    var SmallMapEntityLayer = YYC.Class(SmallMapLayer, {
        Private: {
            __drawSprite: function () {
                var sprites = window.entityLayer.getChilds(),
                    fogLayer = window.fogLayer,
                    fillStyle = null,
                    self = this,
                    graphics = this.getGraphics();

                sprites.forEach(function (sprite) {
                    if ((sprite.isDead && sprite.isDead())
                        || !fogLayer.isVisible(sprite)
                        || sprite.isInstanceOf(PlantsSprite)
                        || (tool.isResourceSprite(sprite) && sprite.total <= 0)) {
                        return;
                    }

                    fillStyle = self.__getFillStyle(sprite);

                    if (tool.isGridSprite(sprite)) {
                        self.__drawGridSprite(sprite, fillStyle, graphics);
                    }
                    else {
                        self.__drawUnit(sprite, fillStyle, graphics);
                    }
                });
            },
            __getFillStyle: function (sprite) {
                var fillStyle = null;

                if (tool.isResourceSprite(sprite)) {
                    fillStyle = SpriteColor.RESOURCE;
                }
                else if (sprite.isInstanceOf(MoutainSprite)) {
                    fillStyle = SpriteColor.MOUTAIN;
                }
                else if (tool.isPlayerSprite(sprite)) {
                    if (this.__isSelected(sprite)) {
                        fillStyle = SpriteColor.SELECT;
                    }
                    else {
                        fillStyle = SpriteColor.PLAYER;
                    }
                }
                else if (tool.isEnemySprite(sprite)) {
                    fillStyle = SpriteColor.ENEMY;
                }

                return fillStyle;
            },
            __isSelected: function (sprite) {
                var result = false,
                    uid = sprite.getUid();

                window.mapLayer.getSelectItems().forEach(function (item) {
                    if (item.getUid() === uid) {
                        result = true;
                        return $break;
                    }
                });

                return result;
            },
            __drawGridSprite: function (sprite, fillStyle, graphics) {
                var diamondSize = 0,
                    singleDiamondSize = tool.getSmallDiamondSize(),
                    leftHalfAngle = window.mapLayer.getSmallMapLeftHalfAngle();

                if (tool.isLargeSprite(sprite)) {
                    diamondSize = singleDiamondSize * 3;
                }
                else if (tool.isMiddleSprite(sprite)) {
                    diamondSize = singleDiamondSize * 2;
                }
                else {
                    diamondSize = singleDiamondSize;
                }

                graphics.fillDiamondBox(fillStyle, tool.convertToSmallMapPix(sprite.gridX, sprite.gridY), leftHalfAngle, diamondSize);
            },
            __drawUnit: function (sprite, fillStyle, graphics) {
                var pixPos = tool.convertToSmallMapPix(sprite.gridX, sprite.gridY);

                //半径放大两倍,从而在小地图上显示得更明显
                graphics.fillCircle(fillStyle, pixPos[0], pixPos[1], sprite.smallMapRadius);
            }
        },
        Public: {
            draw: function (context) {
                this.__drawSprite();
                //在第一次主循环中先绘制出初始的画面,然后再降低调用频率,防止画面抖动
                this.setRunInterval(0.5);
            }
        }
    });

    window.SmallMapEntityLayer = SmallMapEntityLayer;
}());


text:
"""A handler and functions to check whether bisect is supported."""

import re

from dashboard.common import namespaced_stored_object

# A set of suites for which we can't do performance bisects.
_UNBISECTABLE_SUITES = [
    'arc-perf-test',
    'browser_tests',
    'content_browsertests',
    'sizes',
    'v8',
]

# The bisect bot map stored in datastore is expected to be
# a dict mapping master names to [perf bot, bisect bot] pairs.
# If a master name is not in the dict, bisect isn't supported.
BISECT_BOT_MAP_KEY = 'bisect_bot_map'

def IsValidTestForBisect(test_path):
  """Checks whether a test is valid for bisect."""
  if not test_path:
    return False
  path_parts = test_path.split('/')
  if len(path_parts) < 3:
    return False
  if not _MasterNameIsWhitelisted(path_parts[0]):
    return False
  if path_parts[2] in _UNBISECTABLE_SUITES:
    return False
  if test_path.endswith('/ref') or test_path.endswith('_ref'):
    return False
  return True

def _MasterNameIsWhitelisted(master_name):
  """Checks whether a master name is acceptable by checking a whitelist."""
  bisect_bot_map = namespaced_stored_object.Get(BISECT_BOT_MAP_KEY)
  if not bisect_bot_map:
    return True  # If there's no list available, all names are OK.
  whitelisted_masters = list(bisect_bot_map)
  return master_name in whitelisted_masters

def IsValidRevisionForBisect(revision):
  """Checks whether a revision looks like a valid revision for bisect."""
  return _IsGitHash(revision) or re.match(r'^[0-9]{5,7}$', str(revision))

def _IsGitHash(revision):
  """Checks whether the input looks like a SHA1 hash."""
  return re.match(r'[a-fA-F0-9]{40}$', str(revision))


text:
package org.apache.log4j.util;

import org.apache.oro.text.perl.Perl5Util;

public class AbsoluteDateAndTimeFilter implements Filter {
  Perl5Util util = new Perl5Util();

  public String filter(String in) {
    String pat = "/" + Filter.ABSOLUTE_DATE_AND_TIME_PAT + "/";

    if (util.match(pat, in)) {
      return util.substitute(
        "s/" + Filter.ABSOLUTE_DATE_AND_TIME_PAT + "//", in);
    } else {
      return in;
    }
  }
}


text:
from oslo_log import log as logging
from oslo_utils import excutils
from oslo_versionedobjects import base
from oslo_versionedobjects.base import VersionedObjectDictCompat as DictObjectMixin  # noqa
from oslo_versionedobjects import exception
from oslo_versionedobjects import fields as ovoo_fields

from designate import exceptions
from designate.objects import fields

LOG = logging.getLogger(__name__)

def _get_attrname(name):
    return "_obj_{}".format(name)

def get_dict_attr(klass, attr):
    for klass in [klass] + klass.mro():
        if attr in klass.__dict__:
            return klass.__dict__[attr]
    raise AttributeError

class DesignateObject(base.VersionedObject):
    OBJ_SERIAL_NAMESPACE = 'designate_object'
    OBJ_PROJECT_NAMESPACE = 'designate'

    STRING_KEYS = []

    def __init__(self, *args, **kwargs):
        for name in kwargs:
            if name not in self.fields:
                raise TypeError("__init__() got an unexpected keyword "
                                "argument '%(name)s'" % {'name': name})
        super(DesignateObject, self).__init__(self, *args, **kwargs)
        self._obj_original_values = dict()
        self.FIELDS = self.fields

    @classmethod
    def _make_obj_str(cls, data):
        msg = "<%s" % cls.obj_name()
        for key in cls.STRING_KEYS:
            msg += " %s:'%s'" % (key, data.get(key))
        msg += ">"
        return msg

    def __repr__(self):
        return self._make_obj_str(self.to_dict())

    def save(self, context):
        pass

    def _obj_check_relation(self, name):
        if name in self.fields:
            if hasattr(self.fields.get(name), 'objname'):
                if not self.obj_attr_is_set(name):
                    raise exceptions.RelationNotLoaded(
                        object=self, relation=name)

    def to_dict(self):
        """Convert the object to a simple dictionary."""
        data = {}

        if isinstance(self, ListObjectMixin):
            return {
                'objects': self.to_list()
            }
        for field in self.fields:
            if self.obj_attr_is_set(field):
                val = getattr(self, field)
                if isinstance(val, ListObjectMixin):
                    data[field] = val.to_list()
                elif isinstance(val, DesignateObject):
                    data[field] = val.to_dict()
                else:
                    data[field] = val

        return data

    def update(self, values):
        """Update a object's fields with the supplied key/value pairs"""
        for k, v in values.items():
            setattr(self, k, v)

    @classmethod
    def from_dict(cls, _dict):
        instance = cls()

        for field, value in _dict.items():
            if (field in instance.fields and
                    hasattr(instance.fields.get(field), 'objname')):
                relation_cls_name = instance.fields[field].objname
                # We're dealing with a relation, we'll want to create the
                # correct object type and recurse
                relation_cls = cls.obj_class_from_name(
                    relation_cls_name, '1.0')

                if isinstance(value, list):
                    setattr(instance, field, relation_cls.from_list(value))
                else:
                    setattr(instance, field, relation_cls.from_dict(value))

            else:
                setattr(instance, field, value)

        return instance

    @classmethod
    def from_list(cls, _list):
        raise NotImplementedError()

    def __setattr__(self, name, value):
        """Enforces all object attributes are private or well defined"""
        if not (name[0:5] == '_obj_' or
                name[0:7] == '_change' or
                name == '_context' or
                name in list(self.fields.keys()) or
                name == 'FIELDS' or
                name == 'VERSION' or
                name == 'fields'):
            raise AttributeError(
                "Designate object '%(type)s' has no"
                "attribute '%(name)s'" % {
                    'type': self.obj_name(),
                    'name': name,
                })
        super(DesignateObject, self).__setattr__(name, value)

    def __eq__(self, other):
        if self.__class__ != other.__class__:
            return False

        return self.obj_to_primitive() == other.obj_to_primitive()

    def __ne__(self, other):
        return not (self.__eq__(other))

    # TODO(daidv): all of bellow functions should
    # be removed when we completed migration.
    def nested_sort(self, key, value):
        """
        This function ensure that change fields list
        is sorted.
        :param key:
        :param value:
        :return:
        """
        if key == 'designate_object.changes':
            return sorted(value)
        if isinstance(value, list):
            _list = []
            for item in value:
                _list.append(self.nested_sort(None, item))
            return _list
        elif isinstance(value, dict):
            _dict = {}
            for k, v in value.items():
                _dict[k] = self.nested_sort(k, v)
            return _dict
        else:
            return value

    def to_primitive(self):
        return self.nested_sort(None, self.obj_to_primitive())

    @classmethod
    def from_primitive(cls, primitive, context=None):
        return cls.obj_from_primitive(primitive, context)

    @classmethod
    def obj_cls_from_name(cls, name):
        return cls.obj_class_from_name(name, '1.0')

    @classmethod
    def obj_get_schema(cls):
        return cls.to_json_schema()

    def obj_reset_changes(self, fields=None, recursive=False):
        """Reset the list of fields that have been changed.

        :param fields: List of fields to reset, or "all" if None.
        :param recursive: Call obj_reset_changes(recursive=True) on
                          any sub-objects within the list of fields
                          being reset.

        This is NOT "revert to previous values".

        Specifying fields on recursive resets will only be honored at the top
        level. Everything below the top will reset all.
        """
        if recursive:
            for field in self.obj_get_changes():

                # Ignore fields not in requested set (if applicable)
                if fields and field not in fields:
                    continue

                # Skip any fields that are unset
                if not self.obj_attr_is_set(field):
                    continue

                value = getattr(self, field)

                # Don't reset nulled fields
                if value is None:
                    continue

                # Reset straight Object and ListOfObjects fields
                if isinstance(self.fields[field], ovoo_fields.ObjectField):
                    value.obj_reset_changes(recursive=True)
                elif isinstance(self.fields[field],
                                ovoo_fields.ListOfObjectsField):
                    for thing in value:
                        thing.obj_reset_changes(recursive=True)

        if fields:
            self._changed_fields -= set(fields)
            for field in fields:
                self._obj_original_values.pop(field, None)
        else:
            self._changed_fields.clear()
            self._obj_original_values = dict()

    def obj_get_original_value(self, field):
        """Returns the original value of a field."""
        if field in list(self._obj_original_values.keys()):
            return self._obj_original_values[field]
        elif self.obj_attr_is_set(field):
            return getattr(self, field)
        else:
            raise KeyError(field)

    @property
    def obj_fields(self):
        return list(self.fields.keys()) + self.obj_extra_fields

    @property
    def obj_context(self):
        return self._context

    @property
    def is_valid(self):
        """Returns True if the Object is valid."""
        try:
            self.validate()
        except Exception:
            return False
        else:
            return True

    def validate(self):
        # NOTE(kiall, daidv): We make use of the Object registry here
        # in order to avoid an impossible circular import.
        ValidationErrorList = self.obj_cls_from_name('ValidationErrorList')
        ValidationError = self.obj_cls_from_name('ValidationError')
        self.fields = self.FIELDS
        for name in self.fields:
            field = self.fields[name]
            if self.obj_attr_is_set(name):
                value = getattr(self, name)  # Check relation
                if isinstance(value, ListObjectMixin):
                    for obj in value.objects:
                        obj.validate()
                elif isinstance(value, DesignateObject):
                    value.validate()
                else:
                    try:
                        field.coerce(self, name, value)  # Check value
                    except Exception:
                        raise exceptions.InvalidObject(
                            "{} is invalid".format(name))
            elif not field.nullable:
                # Check required is True ~ nullable is False
                errors = ValidationErrorList()
                e = ValidationError()
                e.path = ['records', 0]
                e.validator = 'required'
                e.validator_value = [name]
                e.message = "'%s' is a required property" % name
                errors.append(e)
                raise exceptions.InvalidObject(
                    "Provided object does not match "
                    "schema", errors=errors, object=self)

    def obj_attr_is_set(self, name):
        """
        Return True or False depending of if a particular attribute has had
        an attribute's value explicitly set.
        """
        return hasattr(self, _get_attrname(name))

class ListObjectMixin(base.ObjectListBase):
    LIST_ITEM_TYPE = DesignateObject

    @classmethod
    def _obj_from_primitive(cls, context, objver, primitive):
        instance = cls()
        instance.VERSION = objver
        instance._context = context

        for field, value in primitive['designate_object.data'].items():
            if field == 'objects':
                instance.objects = [
                    DesignateObject.obj_from_primitive(v) for v in value]
            elif isinstance(value, dict) and 'designate_object.name' in value:
                setattr(instance, field,
                        DesignateObject.obj_from_primitive(value))
            else:
                setattr(instance, field, value)

        instance._changed_fields = set(
            primitive.get('designate_object.changes', []))
        instance._obj_original_values = \
            primitive.get('designate_object.original_values', {})

        return instance

    @classmethod
    def from_list(cls, _list):
        instance = cls()

        for item in _list:
            instance.append(cls.LIST_ITEM_TYPE.from_dict(item))

        return instance

    def to_list(self):

        list_ = []

        for item in self.objects:
            if isinstance(item, ListObjectMixin):
                list_.append(item.to_list())
            elif isinstance(item, DesignateObject):
                list_.append(item.to_dict())
            else:
                list_.append(item)

        return list_

    def __repr__(self):
        return ("<%(type)s count:'%(count)s' object:'%(list_type)s'>" %
                {
                    'type': self.LIST_ITEM_TYPE.obj_name(),
                    'count': len(self),
                    'list_type': self.obj_name()
                })

    def __iter__(self):
        """List iterator interface"""
        return iter(self.objects)

    def __getitem__(self, index):
        """List index access"""
        if isinstance(index, slice):
            new_obj = self.__class__()
            new_obj.objects = self.objects[index]
            new_obj.obj_reset_changes()
            return new_obj
        return self.objects[index]

    def __setitem__(self, index, value):
        """Set list index value"""
        self.objects[index] = value

    def __contains__(self, value):
        """List membership test"""
        return value in self.objects

    def append(self, value):
        """Append a value to the list"""
        return self.objects.append(value)

    def extend(self, values):
        """Extend the list by appending all the items in the given list"""
        return self.objects.extend(values)

    def pop(self, index):
        """Pop a value from the list"""
        return self.objects.pop(index)

    def insert(self, index, value):
        """Insert a value into the list at the given index"""
        return self.objects.insert(index, value)

    def remove(self, value):
        """Remove a value from the list"""
        return self.objects.remove(value)

    def index(self, value):
        """List index of value"""
        return self.objects.index(value)

    def count(self, value):
        """List count of value occurrences"""
        return self.objects.count(value)

class AttributeListObjectMixin(ListObjectMixin):
    """
    Mixin class for "Attribute" objects.

    Attribute objects are ListObjects, who's memebers have a "key" and "value"
    property, which should be exposed on the list itself as list.<key>.
    """

    @classmethod
    def from_dict(cls, _dict):
        instances = cls.from_list([{'key': k, 'value': v} for k, v
                                   in _dict.items()])

        return cls.from_list(instances)

    def to_dict(self):
        data = {}

        for item in self.objects:
            data[item.key] = item.value

        return data

    def get(self, key, default=None):
        for obj in self.objects:
            if obj.key == key:
                return obj.value

        return default

class PersistentObjectMixin(object):
    """
    Mixin class for Persistent objects.

    This adds the fields that we use in common for all persistent objects.
    """
    fields = {
        'id': fields.UUIDFields(nullable=True),
        'created_at': fields.DateTimeField(nullable=True),
        'updated_at': fields.DateTimeField(nullable=True),
        'version': fields.IntegerFields(nullable=True)
    }

class SoftDeleteObjectMixin(object):
    """
    Mixin class for Soft-Deleted objects.

    This adds the fields that we use in common for all soft-deleted objects.
    """
    fields = {
        'deleted': fields.StringFields(nullable=True),
        'deleted_at': fields.DateTimeField(nullable=True),
    }

class PagedListObjectMixin(object):
    """
    Mixin class for List objects.

    This adds fields that would populate API metadata for collections.
    """
    fields = {
        'total_count': fields.IntegerFields(nullable=True)
    }

class DesignateRegistry(base.VersionedObjectRegistry):
    def registration_hook(self, cls, index):
        for name, field in cls.fields.items():
            attr = get_dict_attr(cls, name)

            def getter(self, name=name):
                attrname = _get_attrname(name)
                self._obj_check_relation(name)
                return getattr(self, attrname, None)

            def setter(self, value, name=name, field=field):
                attrname = _get_attrname(name)
                field_value = field.coerce(self, name, value)
                if field.read_only and hasattr(self, attrname):
                    # Note(yjiang5): _from_db_object() may iterate
                    # every field and write, no exception in such situation.
                    if getattr(self, attrname) != field_value:
                        raise exception.ReadOnlyFieldError(field=name)
                    else:
                        return

                self._changed_fields.add(name)
                # TODO(daidv): _obj_original_values shoud be removed
                # after OVO migration completed.
                if (self.obj_attr_is_set(name) and
                        value != getattr(self, name) and
                        name not in list(self._obj_original_values.keys())):  # noqa
                    self._obj_original_values[name] = getattr(self, name)
                try:
                    return setattr(self, attrname, field_value)
                except Exception:
                    with excutils.save_and_reraise_exception():
                        LOG.exception(
                            'Error setting %{obj_name}s.%{field_name}s',
                            {
                                "obj_name": self.obj_name(),
                                "field_name": name
                            })

            setattr(cls, name, property(getter, setter, attr.fdel))


text:
<?php

namespace Gremio\AbmBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Gremio\AbmBundle\Entity\Seccion
 *
 * @ORM\Table(name="seccion")
 * @ORM\Entity(repositoryClass="Gremio\AbmBundle\Entity\SeccionRepository")
 */
class Seccion
{
    /**
     * @var integer $id
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string $Descripcion
     *
     * @ORM\Column(name="Descripcion", type="string", length=50)
     */
    private $Descripcion;

    /**
     * @var string $Domicilio
     *
     * @ORM\Column(name="Domicilio", type="string", length=100)
     */
    private $Domicilio;

    /**
     * @var string $Telefono
     *
     * @ORM\Column(name="Telefono", type="string", length=12)
     */
    private $Telefono;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set Descripcion
     *
     * @param string $descripcion
     */
    public function setDescripcion($descripcion)
    {
        $this->Descripcion = $descripcion;
    }

    /**
     * Get Descripcion
     *
     * @return string
     */
    public function getDescripcion()
    {
        return $this->Descripcion;
    }

    /**
     * Set Domicilio
     *
     * @param string $domicilio
     */
    public function setDomicilio($domicilio)
    {
        $this->Domicilio = $domicilio;
    }

    /**
     * Get Domicilio
     *
     * @return string
     */
    public function getDomicilio()
    {
        return $this->Domicilio;
    }

    /**
     * Set Telefono
     *
     * @param string $telefono
     */
    public function setTelefono($telefono)
    {
        $this->Telefono = $telefono;
    }

    /**
     * Get Telefono
     *
     * @return string
     */
    public function getTelefono()
    {
        return $this->Telefono;
    }

    public function __toString()
    {
        return $this->getDescripcion();
    }

    /**
     * @ORM\ManyToOne(targetEntity="Localidad")
     * @Orm\JoinColumn(name="localidad_id", referencedColumnName="id")
     */

    protected $localidad;

    /**
     * Set localidad
     *
     * @param Gremio\AbmBundle\Entity\Localidad $localidad
     */
    public function setLocalidad(\Gremio\AbmBundle\Entity\Localidad $localidad)
    {
        $this->localidad = $localidad;
    }

    /**
     * Get localidad
     *
     * @return Gremio\AbmBundle\Entity\Localidad
     */
    public function getLocalidad()
    {
        return $this->localidad;
    }
}