text:
#ifndef lint
static const char rcsid[] _U_ =
    "@(#) $Header: /tcpdump/master/libpcap/pcap-win32.c,v 1.25.2.7 2007/06/14 22:07:14 gianluca Exp $ (LBL)";
#endif

#include <pcap-int.h>
#include <Packet32.h>
#include <Ntddndis.h>
#ifdef HAVE_DAG_API
#include <dagnew.h>
#include <dagapi.h>
#endif /* HAVE_DAG_API */
#ifdef __MINGW32__
int* _errno();
#define errno (*_errno())
#endif /* __MINGW32__ */

static int pcap_setfilter_win32_npf(pcap_t *, struct bpf_program *);
static int pcap_setfilter_win32_dag(pcap_t *, struct bpf_program *);
static int pcap_getnonblock_win32(pcap_t *, char *);
static int pcap_setnonblock_win32(pcap_t *, int, char *);

#define	PcapBufSize 256000	/*dimension of the buffer in the pcap_t structure*/
#define	SIZE_BUF 1000000

/* Equivalent to ntohs(), but a lot faster under Windows */
#define SWAPS(_X) ((_X & 0xff) << 8) | (_X >> 8)

/*
 * Header that the WinPcap driver associates to the packets.
 * Once was in bpf.h
 */
struct bpf_hdr {
	struct timeval	bh_tstamp;	/* time stamp */
	bpf_u_int32	bh_caplen;	/* length of captured portion */
	bpf_u_int32	bh_datalen;	/* original length of packet */
	u_short		bh_hdrlen;	/* length of bpf header (this struct
					   plus alignment padding) */
};

/* Start winsock */
int
wsockinit()
{
	WORD wVersionRequested;
	WSADATA wsaData;
	int err;
	wVersionRequested = MAKEWORD( 1, 1);
	err = WSAStartup( wVersionRequested, &wsaData );
	if ( err != 0 )
	{
		return -1;
	}
	return 0;
}

static int
pcap_stats_win32(pcap_t *p, struct pcap_stat *ps)
{

	if(PacketGetStats(p->adapter, (struct bpf_stat*)ps) != TRUE){
		snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "PacketGetStats error: %s", pcap_win32strerror());
		return -1;
	}

	return 0;
}

static int
pcap_read_win32_npf(pcap_t *p, int cnt, pcap_handler callback, u_char *user)
{
	int cc;
	int n = 0;
	register u_char *bp, *ep;

	cc = p->cc;
	if (p->cc == 0) {
		/*
		 * Has "pcap_breakloop()" been called?
		 */
		if (p->break_loop) {
			/*
			 * Yes - clear the flag that indicates that it
			 * has, and return -2 to indicate that we were
			 * told to break out of the loop.
			 */
			p->break_loop = 0;
			return (-2);
		}

	    /* capture the packets */
		if(PacketReceivePacket(p->adapter,p->Packet,TRUE)==FALSE){
			snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "read error: PacketReceivePacket failed");
			return (-1);
		}

		cc = p->Packet->ulBytesReceived;

		bp = p->Packet->Buffer;
	}
	else
		bp = p->bp;

	/*
	 * Loop through each packet.
	 */
#define bhp ((struct bpf_hdr *)bp)
	ep = bp + cc;
	while (1) {
		register int caplen, hdrlen;

		/*
		 * Has "pcap_breakloop()" been called?
		 * If so, return immediately - if we haven't read any
		 * packets, clear the flag and return -2 to indicate
		 * that we were told to break out of the loop, otherwise
		 * leave the flag set, so that the *next* call will break
		 * out of the loop without having read any packets, and
		 * return the number of packets we've processed so far.
		 */
		if (p->break_loop) {
			if (n == 0) {
				p->break_loop = 0;
				return (-2);
			} else {
				p->bp = bp;
				p->cc = ep - bp;
				return (n);
			}
		}
		if (bp >= ep)
			break;

		caplen = bhp->bh_caplen;
		hdrlen = bhp->bh_hdrlen;

		/*
		 * XXX A bpf_hdr matches a pcap_pkthdr.
		 */
		(*callback)(user, (struct pcap_pkthdr*)bp, bp + hdrlen);
		bp += BPF_WORDALIGN(caplen + hdrlen);
		if (++n >= cnt && cnt > 0) {
			p->bp = bp;
			p->cc = ep - bp;
			return (n);
		}
	}
#undef bhp
	p->cc = 0;
	return (n);
}

#ifdef HAVE_DAG_API
static int
pcap_read_win32_dag(pcap_t *p, int cnt, pcap_handler callback, u_char *user)
{
	u_char *dp = NULL;
	int	packet_len = 0, caplen = 0;
	struct pcap_pkthdr	pcap_header;
	u_char *endofbuf;
	int n = 0;
	dag_record_t *header;
	unsigned erf_record_len;
	ULONGLONG ts;
	int cc;
	unsigned swt;
	unsigned dfp = p->adapter->DagFastProcess;

	cc = p->cc;
	if (cc == 0) /* Get new packets only if we have processed all the ones of the previous read */
	{
	    /* Get new packets from the network */
		if(PacketReceivePacket(p->adapter, p->Packet, TRUE)==FALSE){
			snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "read error: PacketReceivePacket failed");
			return (-1);
		}

		cc = p->Packet->ulBytesReceived;
		if(cc == 0)
			/* The timeout has expired but we no packets arrived */
			return 0;
		header = (dag_record_t*)p->adapter->DagBuffer;
	}
	else
		header = (dag_record_t*)p->bp;

	endofbuf = (char*)header + cc;

	/*
	 * Cycle through the packets
	 */
	do
	{
		erf_record_len = SWAPS(header->rlen);
		if((char*)header + erf_record_len > endofbuf)
			break;

		/* Increase the number of captured packets */
		p->md.stat.ps_recv++;

		/* Find the beginning of the packet */
		dp = ((u_char *)header) + dag_record_size;

		/* Determine actual packet len */
		switch(header->type)
		{
		case TYPE_ATM:
			packet_len = ATM_SNAPLEN;
			caplen = ATM_SNAPLEN;
			dp += 4;

			break;

		case TYPE_ETH:
			swt = SWAPS(header->wlen);
			packet_len = swt - (p->md.dag_fcs_bits);
			caplen = erf_record_len - dag_record_size - 2;
			if (caplen > packet_len)
			{
				caplen = packet_len;
			}
			dp += 2;

			break;

		case TYPE_HDLC_POS:
			swt = SWAPS(header->wlen);
			packet_len = swt - (p->md.dag_fcs_bits);
			caplen = erf_record_len - dag_record_size;
			if (caplen > packet_len)
			{
				caplen = packet_len;
			}

			break;
		}

		if(caplen > p->snapshot)
			caplen = p->snapshot;

		/*
		 * Has "pcap_breakloop()" been called?
		 * If so, return immediately - if we haven't read any
		 * packets, clear the flag and return -2 to indicate
		 * that we were told to break out of the loop, otherwise
		 * leave the flag set, so that the *next* call will break
		 * out of the loop without having read any packets, and
		 * return the number of packets we've processed so far.
		 */
		if (p->break_loop)
		{
			if (n == 0)
			{
				p->break_loop = 0;
				return (-2);
			}
			else
			{
				p->bp = (char*)header;
				p->cc = endofbuf - (char*)header;
				return (n);
			}
		}

		if(!dfp)
		{
			/* convert between timestamp formats */
			ts = header->ts;
			pcap_header.ts.tv_sec = (int)(ts >> 32);
			ts = (ts & 0xffffffffi64) * 1000000;
			ts += 0x80000000; /* rounding */
			pcap_header.ts.tv_usec = (int)(ts >> 32);
			if (pcap_header.ts.tv_usec >= 1000000) {
				pcap_header.ts.tv_usec -= 1000000;
				pcap_header.ts.tv_sec++;
			}
		}

		/* No underlaying filtering system. We need to filter on our own */
		if (p->fcode.bf_insns)
		{
			if (bpf_filter(p->fcode.bf_insns, dp, packet_len, caplen) == 0)
			{
				/* Move to next packet */
				header = (dag_record_t*)((char*)header + erf_record_len);
				continue;
			}
		}

		/* Fill the header for the user suppplied callback function */
		pcap_header.caplen = caplen;
		pcap_header.len = packet_len;

		/* Call the callback function */
		(*callback)(user, &pcap_header, dp);

		/* Move to next packet */
		header = (dag_record_t*)((char*)header + erf_record_len);

		/* Stop if the number of packets requested by user has been reached*/
		if (++n >= cnt && cnt > 0)
		{
			p->bp = (char*)header;
			p->cc = endofbuf - (char*)header;
			return (n);
		}
	}
	while((u_char*)header < endofbuf);

  return 1;
}
#endif /* HAVE_DAG_API */

/* Send a packet to the network */
static int
pcap_inject_win32(pcap_t *p, const void *buf, size_t size){
	LPPACKET PacketToSend;

	PacketToSend=PacketAllocatePacket();

	if (PacketToSend == NULL)
	{
		snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "send error: PacketAllocatePacket failed");
		return -1;
	}

	PacketInitPacket(PacketToSend,(PVOID)buf,size);
	if(PacketSendPacket(p->adapter,PacketToSend,TRUE) == FALSE){
		snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "send error: PacketSendPacket failed");
		PacketFreePacket(PacketToSend);
		return -1;
	}

	PacketFreePacket(PacketToSend);

	/*
	 * We assume it all got sent if "PacketSendPacket()" succeeded.
	 * "pcap_inject()" is expected to return the number of bytes
	 * sent.
	 */
	return size;
}

static void
pcap_close_win32(pcap_t *p)
{
	pcap_close_common(p);
	if (p->adapter != NULL) {
		PacketCloseAdapter(p->adapter);
		p->adapter = NULL;
	}
	if (p->Packet) {
		PacketFreePacket(p->Packet);
		p->Packet = NULL;
	}
}

pcap_t *
pcap_open_live(const char *device, int snaplen, int promisc, int to_ms,
    char *ebuf)
{
	register pcap_t *p;
	NetType type;

	/* Init WinSock */
	wsockinit();

	p = (pcap_t *)malloc(sizeof(*p));
	if (p == NULL)
	{
		snprintf(ebuf, PCAP_ERRBUF_SIZE, "malloc: %s", pcap_strerror(errno));
		return (NULL);
	}
	memset(p, 0, sizeof(*p));
	p->adapter=NULL;

	p->adapter = PacketOpenAdapter((char*)device);

	if (p->adapter == NULL)
	{
		free(p);
		/* Adapter detected but we are not able to open it. Return failure. */
		snprintf(ebuf, PCAP_ERRBUF_SIZE, "Error opening adapter: %s", pcap_win32strerror());
		return NULL;
	}

	/*get network type*/
	if(PacketGetNetType (p->adapter,&type) == FALSE)
	{
		snprintf(ebuf, PCAP_ERRBUF_SIZE, "Cannot determine the network type: %s", pcap_win32strerror());
		goto bad;
	}

	/*Set the linktype*/
	switch (type.LinkType)
	{
	case NdisMediumWan:
		p->linktype = DLT_EN10MB;
		break;

	case NdisMedium802_3:
		p->linktype = DLT_EN10MB;
		/*
		 * This is (presumably) a real Ethernet capture; give it a
		 * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
		 * that an application can let you choose it, in case you're
		 * capturing DOCSIS traffic that a Cisco Cable Modem
		 * Termination System is putting out onto an Ethernet (it
		 * doesn't put an Ethernet header onto the wire, it puts raw
		 * DOCSIS frames out on the wire inside the low-level
		 * Ethernet framing).
		 */
		p->dlt_list = (u_int *) malloc(sizeof(u_int) * 2);
		/*
		 * If that fails, just leave the list empty.
		 */
		if (p->dlt_list != NULL) {
			p->dlt_list[0] = DLT_EN10MB;
			p->dlt_list[1] = DLT_DOCSIS;
			p->dlt_count = 2;
		}
		break;

	case NdisMediumFddi:
		p->linktype = DLT_FDDI;
		break;

	case NdisMedium802_5:
		p->linktype = DLT_IEEE802;
		break;

	case NdisMediumArcnetRaw:
		p->linktype = DLT_ARCNET;
		break;

	case NdisMediumArcnet878_2:
		p->linktype = DLT_ARCNET;
		break;

	case NdisMediumAtm:
		p->linktype = DLT_ATM_RFC1483;
		break;

	case NdisMediumCHDLC:
		p->linktype = DLT_CHDLC;
		break;

	case NdisMediumPPPSerial:
		p->linktype = DLT_PPP_SERIAL;
		break;

	case NdisMediumNull:
		p->linktype = DLT_NULL;
		break;

	case NdisMediumBare80211:
		p->linktype = DLT_IEEE802_11;
		break;

	case NdisMediumRadio80211:
		p->linktype = DLT_IEEE802_11_RADIO;
		break;

	case NdisMediumPpi:
		p->linktype = DLT_PPI;
		break;

	default:
		p->linktype = DLT_EN10MB;			/*an unknown adapter is assumed to be ethernet*/
		break;
	}

	/* Set promiscuous mode */
	if (promisc)
	{

		if (PacketSetHwFilter(p->adapter,NDIS_PACKET_TYPE_PROMISCUOUS) == FALSE)
		{
			snprintf(ebuf, PCAP_ERRBUF_SIZE, "failed to set hardware filter to promiscuous mode");
			goto bad;
		}
	}
	else
	{
		if (PacketSetHwFilter(p->adapter,NDIS_PACKET_TYPE_ALL_LOCAL) == FALSE)
		{
			snprintf(ebuf, PCAP_ERRBUF_SIZE, "failed to set hardware filter to non-promiscuous mode");
			goto bad;
		}
	}

	/* Set the buffer size */
	p->bufsize = PcapBufSize;

	/* Store the timeout. Used by pcap_setnonblock() */
	p->timeout= to_ms;

	/* allocate Packet structure used during the capture */
	if((p->Packet = PacketAllocatePacket())==NULL)
	{
		snprintf(ebuf, PCAP_ERRBUF_SIZE, "failed to allocate the PACKET structure");
		goto bad;
	}

	if(!(p->adapter->Flags & INFO_FLAG_DAG_CARD))
	{
	/*
	 * Traditional Adapter
	 */

		p->buffer = (u_char *)malloc(PcapBufSize);
		if (p->buffer == NULL)
		{
			snprintf(ebuf, PCAP_ERRBUF_SIZE, "malloc: %s", pcap_strerror(errno));
			goto bad;
		}

		PacketInitPacket(p->Packet,(BYTE*)p->buffer,p->bufsize);

		p->snapshot = snaplen;

		/* allocate the standard buffer in the driver */
		if(PacketSetBuff( p->adapter, SIZE_BUF)==FALSE)
		{
			snprintf(ebuf, PCAP_ERRBUF_SIZE,"driver error: not enough memory to allocate the kernel buffer\n");
			goto bad;
		}

		/* tell the driver to copy the buffer only if it contains at least 16K */
		if(PacketSetMinToCopy(p->adapter,16000)==FALSE)
		{
			snprintf(ebuf, PCAP_ERRBUF_SIZE,"Error calling PacketSetMinToCopy: %s\n", pcap_win32strerror());
			goto bad;
		}
	}
	else
#ifdef HAVE_DAG_API
	{
	/*
	 * Dag Card
	 */
		LONG	status;
		HKEY	dagkey;
		DWORD	lptype;
		DWORD	lpcbdata;
		int		postype = 0;
		char	keyname[512];

		snprintf(keyname, sizeof(keyname), "%s\\CardParams\\%s",
			"SYSTEM\\CurrentControlSet\\Services\\DAG",
			strstr(_strlwr((char*)device), "dag"));
		do
		{
			status = RegOpenKeyEx(HKEY_LOCAL_MACHINE, keyname, 0, KEY_READ, &dagkey);
			if(status != ERROR_SUCCESS)
				break;

			status = RegQueryValueEx(dagkey,
				"PosType",
				NULL,
				&lptype,
				(char*)&postype,
				&lpcbdata);

			if(status != ERROR_SUCCESS)
			{
				postype = 0;
			}

			RegCloseKey(dagkey);
		}
		while(FALSE);

		p->snapshot = PacketSetSnapLen(p->adapter, snaplen);

		/* Set the length of the FCS associated to any packet. This value
		 * will be subtracted to the packet length */
		p->md.dag_fcs_bits = p->adapter->DagFcsLen;
	}
#else
	goto bad;
#endif /* HAVE_DAG_API */

	PacketSetReadTimeout(p->adapter, to_ms);

#ifdef HAVE_DAG_API
	if(p->adapter->Flags & INFO_FLAG_DAG_CARD)
	{
		/* install dag specific handlers for read and setfilter */
		p->read_op = pcap_read_win32_dag;
		p->setfilter_op = pcap_setfilter_win32_dag;
	}
	else
	{
#endif /* HAVE_DAG_API */
		/* install traditional npf handlers for read and setfilter */
		p->read_op = pcap_read_win32_npf;
		p->setfilter_op = pcap_setfilter_win32_npf;
#ifdef HAVE_DAG_API
	}
#endif /* HAVE_DAG_API */
	p->setdirection_op = NULL;	/* Not implemented. */
	    /* XXX - can this be implemented on some versions of Windows? */
	p->inject_op = pcap_inject_win32;
	p->set_datalink_op = NULL;	/* can't change data link type */
	p->getnonblock_op = pcap_getnonblock_win32;
	p->setnonblock_op = pcap_setnonblock_win32;
	p->stats_op = pcap_stats_win32;
	p->close_op = pcap_close_win32;

	return (p);
bad:
	if (p->adapter)
	    PacketCloseAdapter(p->adapter);
	if (p->buffer != NULL)
		free(p->buffer);
	if(p->Packet)
		PacketFreePacket(p->Packet);
	/*
	 * Get rid of any link-layer type list we allocated.
	 */
	if (p->dlt_list != NULL)
		free(p->dlt_list);
	free(p);
	return (NULL);
}

static int
pcap_setfilter_win32_npf(pcap_t *p, struct bpf_program *fp)
{
	if(PacketSetBpf(p->adapter,fp)==FALSE){
		/*
		 * Kernel filter not installed.
		 * XXX - fall back on userland filtering, as is done
		 * on other platforms?
		 */
		snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "Driver error: cannot set bpf filter: %s", pcap_win32strerror());
		return (-1);
	}

	/*
	 * Discard any previously-received packets, as they might have
	 * passed whatever filter was formerly in effect, but might
	 * not pass this filter (BIOCSETF discards packets buffered
	 * in the kernel, so you can lose packets in any case).
	 */
	p->cc = 0;
	return (0);
}

/*
 * We filter at user level, since the kernel driver does't process the packets
 */
static int
pcap_setfilter_win32_dag(pcap_t *p, struct bpf_program *fp) {

	if(!fp)
	{
		strncpy(p->errbuf, "setfilter: No filter specified", sizeof(p->errbuf));
		return -1;
	}

	/* Install a user level filter */
	if (install_bpf_program(p, fp) < 0)
	{
		snprintf(p->errbuf, sizeof(p->errbuf),
			"setfilter, unable to install the filter: %s", pcap_strerror(errno));
		return -1;
	}

	p->md.use_bpf = 0;

	return (0);
}

static int
pcap_getnonblock_win32(pcap_t *p, char *errbuf)
{
	/*
	 * XXX - if there were a PacketGetReadTimeout() call, we
	 * would use it, and return 1 if the timeout is -1
	 * and 0 otherwise.
	 */
	return (p->nonblock);
}

static int
pcap_setnonblock_win32(pcap_t *p, int nonblock, char *errbuf)
{
	int newtimeout;

	if (nonblock) {
		/*
		 * Set the read timeout to -1 for non-blocking mode.
		 */
		newtimeout = -1;
	} else {
		/*
		 * Restore the timeout set when the device was opened.
		 * (Note that this may be -1, in which case we're not
		 * really leaving non-blocking mode.)
		 */
		newtimeout = p->timeout;
	}
	if (!PacketSetReadTimeout(p->adapter, newtimeout)) {
		snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
		    "PacketSetReadTimeout: %s", pcap_win32strerror());
		return (-1);
	}
	p->nonblock = (newtimeout == -1);
	return (0);
}

/* Set the driver working mode */
int
pcap_setmode(pcap_t *p, int mode){

	if (p->adapter==NULL)
	{
		snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "impossible to set mode while reading from a file");
		return -1;
	}

	if(PacketSetMode(p->adapter,mode)==FALSE)
	{
		snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "driver error: working mode not recognized");
		return -1;
	}

	return 0;
}

/* Set the dimension of the kernel-level capture buffer */
int
pcap_setbuff(pcap_t *p, int dim)
{
	if (p->adapter==NULL)
	{
		snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "The kernel buffer size cannot be set while reading from a file");
		return -1;
	}

	if(PacketSetBuff(p->adapter,dim)==FALSE)
	{
		snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "driver error: not enough memory to allocate the kernel buffer");
		return -1;
	}
	return 0;
}

/*set the minimum amount of data that will release a read call*/
int
pcap_setmintocopy(pcap_t *p, int size)
{
	if (p->adapter==NULL)
	{
		snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "Impossible to set the mintocopy parameter on an offline capture");
		return -1;
	}

	if(PacketSetMinToCopy(p->adapter, size)==FALSE)
	{
		snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "driver error: unable to set the requested mintocopy size");
		return -1;
	}
	return 0;
}


text:
'use strict';

const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
const Schema = mongoose.Schema;

const StalkedId = new Schema({
    sid: String,
    subscribers: Array
});

module.exports = mongoose.model('StalkedId', StalkedId);

redpajama_set_name: RedPajamaGithub


text:
package com.twosigma.beakerx.chart.serializer;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.ser.DefaultSerializerProvider;
import com.twosigma.beakerx.chart.Color;
import com.twosigma.beakerx.chart.xychart.plotitem.Points;
import com.twosigma.beakerx.chart.xychart.plotitem.ShapeType;
import org.assertj.core.api.Assertions;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

import java.io.IOException;
import java.io.StringWriter;
import java.util.Arrays;

public class PointsSerializerTest {

  static ObjectMapper mapper;
  static PointsSerializer pointsSerializer;
  JsonGenerator jgen;
  StringWriter sw;
  Points points;

  @BeforeClass
  public static void initClassStubData() {
    mapper = new ObjectMapper();
    pointsSerializer = new PointsSerializer();
  }

  @Before
  public void initTestStubData() throws IOException {
    sw = new StringWriter();
    jgen = mapper.getJsonFactory().createJsonGenerator(sw);
    points = new Points();
    points.setX(Arrays.asList(1, 2, 3));
    points.setY(Arrays.asList(1, 2, 3));
  }

  @Test
  public void serializeSizePoints_resultJsonHasSize() throws IOException {
    //when
    points.setSize(new Integer(11));
    pointsSerializer.serialize(points, jgen, new DefaultSerializerProvider.Impl());
    jgen.flush();
    //then
    JsonNode actualObj = mapper.readTree(sw.toString());
    Assertions.assertThat(actualObj.has("size")).isTrue();
    Assertions.assertThat(actualObj.get("size").asInt()).isEqualTo(11);
  }

  @Test
  public void serializeSizesPoints_resultJsonHasSizes() throws IOException {
    //when
    points.setSize(Arrays.asList(11, 22, 33));
    pointsSerializer.serialize(points, jgen, new DefaultSerializerProvider.Impl());
    jgen.flush();
    //then
    JsonNode actualObj = mapper.readTree(sw.toString());
    Assertions.assertThat(actualObj.has("sizes")).isTrue();
    ArrayNode arrayNode = (ArrayNode) actualObj.get("sizes");
    Assertions.assertThat(arrayNode.get(1).asInt()).isEqualTo(22);
  }

  @Test
  public void serializeShapePoints_resultJsonHasShapeSquare() throws IOException {
    //when
    points.setShape(ShapeType.SQUARE);
    pointsSerializer.serialize(points, jgen, new DefaultSerializerProvider.Impl());
    jgen.flush();
    //then
    JsonNode actualObj = mapper.readTree(sw.toString());
    Assertions.assertThat(actualObj.has("shape")).isTrue();
    Assertions.assertThat(actualObj.get("shape").asText()).isEqualTo("rect");
  }

  @Test
  public void serializeShapePoints_resultJsonHasShape() throws IOException {
    //when
    points.setShape(ShapeType.CIRCLE);
    pointsSerializer.serialize(points, jgen, new DefaultSerializerProvider.Impl());
    jgen.flush();
    //then
    JsonNode actualObj = mapper.readTree(sw.toString());
    Assertions.assertThat(actualObj.has("shape")).isTrue();
    Assertions.assertThat(actualObj.get("shape").asText()).isEqualTo("circle");
  }

  @Test
  public void serializeShapesPoints_resultJsonHasShapes() throws IOException {
    //when
    points.setShape(Arrays.asList(ShapeType.CIRCLE, ShapeType.CROSS));
    pointsSerializer.serialize(points, jgen, new DefaultSerializerProvider.Impl());
    jgen.flush();
    //then
    JsonNode actualObj = mapper.readTree(sw.toString());
    Assertions.assertThat(actualObj.has("shaps")).isTrue();
    ArrayNode arrayNode = (ArrayNode) actualObj.get("shaps");
    Assertions.assertThat(arrayNode.get(1).asText()).isEqualTo("cross");
  }

  @Test
  public void serializeFillPoints_resultJsonHasFill() throws IOException {
    //when
    points.setFill(true);
    pointsSerializer.serialize(points, jgen, new DefaultSerializerProvider.Impl());
    jgen.flush();
    //then
    JsonNode actualObj = mapper.readTree(sw.toString());
    Assertions.assertThat(actualObj.has("fill")).isTrue();
    Assertions.assertThat(actualObj.get("fill").asBoolean()).isTrue();
  }

  @Test
  public void serializeFillsPoints_resultJsonHasFills() throws IOException {
    //when
    points.setFill(Arrays.asList(false, true, false));
    pointsSerializer.serialize(points, jgen, new DefaultSerializerProvider.Impl());
    jgen.flush();
    //then
    JsonNode actualObj = mapper.readTree(sw.toString());
    Assertions.assertThat(actualObj.has("fills")).isTrue();
    ArrayNode arrayNode = (ArrayNode) actualObj.get("fills");
    Assertions.assertThat(arrayNode.get(1).asBoolean()).isTrue();
  }

  @Test
  public void serializeColorPoints_resultJsonHasColor() throws IOException {
    //when
    points.setColor(Color.GREEN);
    pointsSerializer.serialize(points, jgen, new DefaultSerializerProvider.Impl());
    jgen.flush();
    //then
    JsonNode actualObj = mapper.readTree(sw.toString());
    Assertions.assertThat(actualObj.has("color")).isTrue();
    Assertions.assertThat(actualObj.get("color")).isNotEmpty();
  }

  @Test
  public void serializeColorsPoints_resultJsonHasColors() throws IOException {
    //when
    points.setColor(Arrays.asList(Color.GREEN, Color.BLUE));
    pointsSerializer.serialize(points, jgen, new DefaultSerializerProvider.Impl());
    jgen.flush();
    //then
    JsonNode actualObj = mapper.readTree(sw.toString());
    Assertions.assertThat(actualObj.has("colors")).isTrue();
    ArrayNode arrayNode = (ArrayNode) actualObj.get("colors");
    Assertions.assertThat(arrayNode.get(1)).isNotEmpty();
  }

  @Test
  public void serializeOutlineColorPoints_resultJsonHasOutlineColor() throws IOException {
    //when
    points.setOutlineColor(Color.GREEN);
    pointsSerializer.serialize(points, jgen, new DefaultSerializerProvider.Impl());
    jgen.flush();
    //then
    JsonNode actualObj = mapper.readTree(sw.toString());
    Assertions.assertThat(actualObj.has("outline_color")).isTrue();
    Assertions.assertThat(actualObj.get("outline_color").get("rgb").asInt())
        .isEqualTo(Color.GREEN.getRGB());
  }

  @Test
  public void serializeOutlineColorsPoints_resultJsonHasOutlineColors() throws IOException {
    //when
    points.setOutlineColor(Arrays.asList(Color.GREEN, Color.BLUE));
    pointsSerializer.serialize(points, jgen, new DefaultSerializerProvider.Impl());
    jgen.flush();
    //then
    JsonNode actualObj = mapper.readTree(sw.toString());
    Assertions.assertThat(actualObj.has("outline_colors")).isTrue();
    ArrayNode arrayNode = (ArrayNode) actualObj.get("outline_colors");
    Assertions.assertThat(arrayNode.get(1).get("rgb").asInt()).isEqualTo(Color.BLUE.getRGB());
  }
}


text:
package com.nishtahir;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Validator {
	public static Validator instance;
	private Pattern pattern;

	public static Validator getInstance() {
		if(instance == null){
			instance = new Validator();
		}

		return instance;
	}

	private Validator(){
		String myEmailPattern = "\\w+@\\w+\\.\\w+"; // !$##%*)(*$
		pattern = Pattern.compile(myEmailPattern);
	}

	public boolean validateEmail(String userInput) {
		Matcher matcher = pattern.matcher(userInput);
		return matcher.matches();
	}

}


text:
from flask import Flask
app = Flask(__name__)

import nostalgify.views


text:
namespace org { namespace alljoyn { namespace ControlPanel {

} } }

partial ref class TypeConversionHelpers
{
internal:
};


text:
<meta charset='utf-8'/>
<meta name="viewport" content="width=device-width, initial-scale=0.6">

		<title>ENUM - Syntax Pages - Plange</title>
		<link rel=StyleSheet href='../../css/general.css' type='text/css' />

		<?php require('../../header.php') ?>

makes a compound type with static members for each of the elements, and each of those elements inherit/implement those specified inheritance list

syntax

"enum" {IC} ["inheriting" {IC} INHERITANCE_LIST {IC}] ["implementing" {IC} INHERITANCE_LIST {IC}] "{" [$ENUM_ELEMENT {{IC} ";" {IC} $ENUM_ELEMENT}] "}"

		<?php require('../../footer.php') ?>


text:
import testtools

from tempest.common import waiters
from tempest import config
from tempest.scenario import manager
from tempest import test

CONF = config.CONF

class TestNetworkAdvancedServerOps(manager.NetworkScenarioTest):
    """Check VM connectivity after some advanced instance operations executed:

     * Stop/Start an instance
     * Reboot an instance
     * Rebuild an instance
     * Pause/Unpause an instance
     * Suspend/Resume an instance
     * Resize an instance
    """

    @classmethod
    def skip_checks(cls):
        super(TestNetworkAdvancedServerOps, cls).skip_checks()
        if not (CONF.network.project_networks_reachable
                or CONF.network.public_network_id):
            msg = ('Either project_networks_reachable must be "true", or '
                   'public_network_id must be defined.')
            raise cls.skipException(msg)

    @classmethod
    def setup_credentials(cls):
        # Create no network resources for these tests.
        cls.set_network_resources()
        super(TestNetworkAdvancedServerOps, cls).setup_credentials()

    def _setup_server(self, keypair):
        security_groups = []
        if test.is_extension_enabled('security-group', 'network'):
            security_group = self._create_security_group()
            security_groups = [{'name': security_group['name']}]
        network, subnet, router = self.create_networks()
        server = self.create_server(
            networks=[{'uuid': network['id']}],
            key_name=keypair['name'],
            security_groups=security_groups,
            wait_until='ACTIVE')
        return server

    def _setup_network(self, server, keypair):
        public_network_id = CONF.network.public_network_id
        floating_ip = self.create_floating_ip(server, public_network_id)
        # Verify that we can indeed connect to the server before we mess with
        # it's state
        self._wait_server_status_and_check_network_connectivity(
            server, keypair, floating_ip)

        return floating_ip

    def _check_network_connectivity(self, server, keypair, floating_ip,
                                    should_connect=True):
        username = CONF.validation.image_ssh_user
        private_key = keypair['private_key']
        self._check_tenant_network_connectivity(
            server, username, private_key,
            should_connect=should_connect,
            servers_for_debug=[server])
        floating_ip_addr = floating_ip['floating_ip_address']
        # Check FloatingIP status before checking the connectivity
        self.check_floating_ip_status(floating_ip, 'ACTIVE')
        self.check_public_network_connectivity(floating_ip_addr, username,
                                               private_key, should_connect,
                                               servers=[server])

    def _wait_server_status_and_check_network_connectivity(self, server,
                                                           keypair,
                                                           floating_ip):
        waiters.wait_for_server_status(self.servers_client, server['id'],
                                       'ACTIVE')
        self._check_network_connectivity(server, keypair, floating_ip)

    @test.idempotent_id('61f1aa9a-1573-410e-9054-afa557cab021')
    @test.services('compute', 'network')
    def test_server_connectivity_stop_start(self):
        keypair = self.create_keypair()
        server = self._setup_server(keypair)
        floating_ip = self._setup_network(server, keypair)
        self.servers_client.stop_server(server['id'])
        waiters.wait_for_server_status(self.servers_client, server['id'],
                                       'SHUTOFF')
        self._check_network_connectivity(server, keypair, floating_ip,
                                         should_connect=False)
        self.servers_client.start_server(server['id'])
        self._wait_server_status_and_check_network_connectivity(
            server, keypair, floating_ip)

    @test.idempotent_id('7b6860c2-afa3-4846-9522-adeb38dfbe08')
    @test.services('compute', 'network')
    def test_server_connectivity_reboot(self):
        keypair = self.create_keypair()
        server = self._setup_server(keypair)
        floating_ip = self._setup_network(server, keypair)
        self.servers_client.reboot_server(server['id'], type='SOFT')
        self._wait_server_status_and_check_network_connectivity(
            server, keypair, floating_ip)

    @test.idempotent_id('88a529c2-1daa-4c85-9aec-d541ba3eb699')
    @test.services('compute', 'network')
    def test_server_connectivity_rebuild(self):
        keypair = self.create_keypair()
        server = self._setup_server(keypair)
        floating_ip = self._setup_network(server, keypair)
        image_ref_alt = CONF.compute.image_ref_alt
        self.servers_client.rebuild_server(server['id'],
                                           image_ref=image_ref_alt)
        self._wait_server_status_and_check_network_connectivity(
            server, keypair, floating_ip)

    @test.idempotent_id('2b2642db-6568-4b35-b812-eceed3fa20ce')
    @testtools.skipUnless(CONF.compute_feature_enabled.pause,
                          'Pause is not available.')
    @test.services('compute', 'network')
    def test_server_connectivity_pause_unpause(self):
        keypair = self.create_keypair()
        server = self._setup_server(keypair)
        floating_ip = self._setup_network(server, keypair)
        self.servers_client.pause_server(server['id'])
        waiters.wait_for_server_status(self.servers_client, server['id'],
                                       'PAUSED')
        self._check_network_connectivity(server, keypair, floating_ip,
                                         should_connect=False)
        self.servers_client.unpause_server(server['id'])
        self._wait_server_status_and_check_network_connectivity(
            server, keypair, floating_ip)

    @test.idempotent_id('5cdf9499-541d-4923-804e-b9a60620a7f0')
    @testtools.skipUnless(CONF.compute_feature_enabled.suspend,
                          'Suspend is not available.')
    @test.services('compute', 'network')
    def test_server_connectivity_suspend_resume(self):
        keypair = self.create_keypair()
        server = self._setup_server(keypair)
        floating_ip = self._setup_network(server, keypair)
        self.servers_client.suspend_server(server['id'])
        waiters.wait_for_server_status(self.servers_client, server['id'],
                                       'SUSPENDED')
        self._check_network_connectivity(server, keypair, floating_ip,
                                         should_connect=False)
        self.servers_client.resume_server(server['id'])
        self._wait_server_status_and_check_network_connectivity(
            server, keypair, floating_ip)

    @test.idempotent_id('719eb59d-2f42-4b66-b8b1-bb1254473967')
    @testtools.skipUnless(CONF.compute_feature_enabled.resize,
                          'Resize is not available.')
    @test.services('compute', 'network')
    def test_server_connectivity_resize(self):
        resize_flavor = CONF.compute.flavor_ref_alt
        if resize_flavor == CONF.compute.flavor_ref:
            msg = "Skipping test - flavor_ref and flavor_ref_alt are identical"
            raise self.skipException(msg)
        keypair = self.create_keypair()
        server = self._setup_server(keypair)
        floating_ip = self._setup_network(server, keypair)
        self.servers_client.resize_server(server['id'],
                                          flavor_ref=resize_flavor)
        waiters.wait_for_server_status(self.servers_client, server['id'],
                                       'VERIFY_RESIZE')
        self.servers_client.confirm_resize_server(server['id'])
        self._wait_server_status_and_check_network_connectivity(
            server, keypair, floating_ip)


text:
"""Auto-generated file, do not edit by hand. GF metadata"""
from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata

PHONE_METADATA_GF = PhoneMetadata(id='GF', country_code=594, international_prefix='00',
    general_desc=PhoneNumberDesc(national_number_pattern='[56]\\d{8}', possible_length=(9,)),
    fixed_line=PhoneNumberDesc(national_number_pattern='594(?:10|2[012457-9]|3[0-57-9]|4[3-9]|5[7-9]|6[0-3]|9[014])\\d{4}', example_number='594101234', possible_length=(9,)),
    mobile=PhoneNumberDesc(national_number_pattern='694(?:[0249]\\d|1[2-9]|3[0-48])\\d{4}', example_number='694201234', possible_length=(9,)),
    national_prefix='0',
    national_prefix_for_parsing='0',
    number_format=[NumberFormat(pattern='(\\d{3})(\\d{2})(\\d{2})(\\d{2})', format='\\1 \\2 \\3 \\4', national_prefix_formatting_rule='0\\1')])


text:
package config

import "sync/atomic"

// Config struct
type Config struct {
	internalStore atomic.Value
}

// NewConfig new config save v into internal store
func NewConfig(v interface{}) *Config {
	c := new(Config)
	c.internalStore.Store(v)
	return c
}

// Get get config inter store value
func (c *Config) Get() interface{} {
	return c.internalStore.Load()
}

// Set the setter function
func (c *Config) Set(v interface{}) {
	c.internalStore.Store(v)
}


text:
// The MIT License
//
// Copyright (c) 2008 Big Nerd Ranch, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

#import "MyDocument.h"
#import "GRLGraphView.h"
#import "GRLEdge.h"
#import "GRLGraph.h"
#import "GRLNode.h"
#import "BNRStore.h"
// For timing
#import <mach/mach_time.h>

#define SIZE 300
/*
NSRect expandRectToIncludePoint(NSRect r, NSPoint p)
{
    NSRect result = r;
    if (p.x < r.origin.x) {
        result.origin.x = p.x;
        result.size.width += r.origin.x - p.x;
    } else if (p.x > r.origin.x + r.size.width) {
        result.size.width = p.x - r.origin.x;
    }

    if (p.y < r.origin.y) {
        result.origin.y = p.y;
        result.size.height += r.origin.y - p.y;
    } else if (p.y > r.origin.y + r.size.height) {
        result.size.height = p.y - r.origin.y;
    }
    return result;
}
*/
float distanceBetweenPoints(NSPoint a, NSPoint b)
{
    float dx = a.x - b.x;
    float dy = a.y - b.y;
    return sqrt(dx * dx + dy * dy);
}
@implementation MyDocument

- (id)init
{
    self = [super init];
    if (self) {
        [[self store] addClass:[GRLEdge class]];
        [[self store] addClass:[GRLNode class]];
        graph = [[GRLGraph alloc] init];
        NSLog(@"graph = %@", graph);
        [[self store] setDelegate:self];
    }
    return self;
}

- (void)dealloc
{
    [store dissolveAllRelationships];
    [graph release];
    [super dealloc];
}

- (NSString *)windowNibName
{
    // Override returning the nib file name of the document
    // If you need to use a subclass of NSWindowController or if your document supports multiple NSWindowControllers, you should remove this method and override -makeWindowControllers instead.
    return @"MyDocument";
}

- (void)windowControllerDidLoadNib:(NSWindowController *) aController
{
    [super windowControllerDidLoadNib:aController];
    [graphView setGraph:graph];
}

- (void)jiggle:(id)sender
{
    NSArray *nodes = [graph nodes];
    int count = [nodes count];
    if (count == 0) {
        return;
    }
    int i;
    for (i = 0 ; i < 3; i++) {
        float deltaX, deltaY;
        deltaX = (float)(random() % 50 - 25);
        deltaY = (float)(random() % 50 - 25);
        int nodeIndex = random() % count;
        GRLNode *n = [nodes objectAtIndex:nodeIndex];
        NSPoint p = [n point];
        p.x += deltaX;
        p.y += deltaY;
        [store willUpdateObject:n];
        [n setPoint:p];
    }
}

- (void)scramble:(id)sender
{
    // Create some nodes
    int i;
    for (i = 0; i < 50; i++) {
        NSPoint p;
        p.x = (float)(random() % SIZE - SIZE/2);
        p.y = (float)(random() % SIZE - SIZE/2);
        GRLNode *n = [[GRLNode alloc] init];
        [n setPoint:p];
        [[self store] insertObject:n];
        [n release];
    }

    NSArray *nodes = [graph nodes];
    int count = [nodes count];
    for (i = 0; i < 75; i++) {
        int aIndex = random() % count;
        int bIndex = random() % count;
        GRLNode *aNode = [nodes objectAtIndex:aIndex];
        GRLNode *bNode = [nodes objectAtIndex:bIndex];
        float distance = distanceBetweenPoints([aNode point], [bNode point]);
        if (distance > 150) {
            continue;
        }
        GRLEdge *e = [[GRLEdge alloc] init];
        [e setSourceNode:aNode];
        [e setDestinationNode:bNode];

        // This inserts it into the graph
        [[self store] insertObject:e];
        [e release];
    }
}

- (void)cull:(id)sender
{
    // Remove some nodes
    int i;
    for (i = 0 ; i < 2; i++) {
        NSArray *nodes = [graph nodes];
        int count = [nodes count];
        if (count == 0) {
            return;
        }
        int nodeIndex = random() % count;
        GRLNode *n = [nodes objectAtIndex:nodeIndex];

        // GRLNode's prepareForDelete will cascade delete
        // to delete attached edges
        [store deleteObject:n];
    }

}

- (void)readFromStore
{
    // Time the read
    mach_timebase_info_data_t info;
    uint64_t start, end, elapsed;
    start = mach_absolute_time();
    if (mach_timebase_info (&info) != KERN_SUCCESS) {
        printf ("mach_timebase_info failed\n");
    }

    NSMutableArray *nodes = [store allObjectsForClass:[GRLNode class]];
    NSMutableArray *edges = [store allObjectsForClass:[GRLEdge class]];

    end = mach_absolute_time();
    elapsed = end - start;

    uint64_t nanos;
    nanos = elapsed * info.numer / info.denom;
    uint64_t millis = nanos / 1000000;
    printf ("elapsed time to load %lu nodes, %lu edges was %llu milliseconds\n", [nodes count], [edges count], millis);

    [graph release];
    graph = [[GRLGraph alloc] init];
    [graph setNodes:nodes];
    [graph setEdges:edges];

    [graphView setGraph:graph];
}

- (void)store:(BNRStore *)st willInsertObject:(BNRStoredObject *)so
{
    // NSLog(@"Adding to graph %@", so);
    if ([so class] == [GRLEdge class]) {
        [graph addEdge:(GRLEdge *)so];
    } else {
        [graph addNode:(GRLNode *)so];
    }

    [graphView setNeedsDisplay:YES];

}
- (void)store:(BNRStore *)st willDeleteObject:(BNRStoredObject *)so
{
    // NSLog(@"Removing from graph %@", so);
    if ([so isKindOfClass:[GRLEdge class]]) {
        [graph removeEdge:(GRLEdge *)so];
    } else {
        [graph removeNode:(GRLNode *)so];
    }

    [graphView setNeedsDisplay:YES];

}
- (void)store:(BNRStore *)st willUpdateObject:(BNRStoredObject *)so
{
    //NSLog(@"MyDocument: willUpdate %@", so);
    [graphView setNeedsDisplay:YES];
}

- (void)store:(BNRStore *)st didChangeObject:(BNRStoredObject *)so;
{
    //NSLog(@"MyDocument: willUpdate %@", so);
    [graphView setNeedsDisplay:YES];
}

@end


text:
struct Circle { void draw() const { std::cout << "drawing circle..." << std::endl; } };
struct Square { void draw() const { std::cout << "drawing square..." << std::endl; } };
struct Triangle { void draw() const { std::cout << "drawing triangle..." << std::endl; } };

int main() {
	std::variant<Circle, Square, Triangle> shape;
	shape = Triangle{};
	auto callDraw = [](auto& sh) { sh.draw(); };
	std::visit(callDraw, shape);

	return 0;
}


text:
#include <config.h>
#include "ofproto-dpif-monitor.h"

#include <string.h>

#include "bfd.h"
#include "cfm.h"
#include "dp-packet.h"
#include "guarded-list.h"
#include "hash.h"
#include "heap.h"
#include "hmap.h"
#include "latch.h"
#include "ofpbuf.h"
#include "ofproto-dpif.h"
#include "ovs-lldp.h"
#include "ovs-thread.h"
#include "poll-loop.h"
#include "seq.h"
#include "timeval.h"
#include "util.h"
#include "openvswitch/vlog.h"

VLOG_DEFINE_THIS_MODULE(ofproto_dpif_monitor);

/* Converts the time in millisecond to heap priority. */
#define MSEC_TO_PRIO(TIME) (LLONG_MAX - (TIME))
/* Converts the heap priority to time in millisecond. */
#define PRIO_TO_MSEC(PRIO) (LLONG_MAX - (PRIO))

/* Monitored port.  It owns references to ofport, bfd, cfm, and lldp structs. */
struct mport {
    struct hmap_node hmap_node;       /* In monitor_hmap. */
    struct heap_node heap_node;       /* In monitor_heap. */
    const struct ofport_dpif *ofport; /* The corresponding ofport. */

    struct cfm *cfm;                  /* Reference to cfm. */
    struct bfd *bfd;                  /* Reference to bfd. */
    struct lldp *lldp;                /* Reference to lldp. */
    uint8_t hw_addr[OFP_ETH_ALEN];    /* Hardware address. */
};

/* Entry of the 'send_soon' list.  Contains the pointer to the
 * 'ofport_dpif'.  Note, the pointed object is not protected, so
 * users should always use the mport_find() to convert it to 'mport'. */
struct send_soon_entry {
    struct ovs_list list_node;        /* In send_soon. */
    const struct ofport_dpif *ofport;
};

/* hmap that contains "struct mport"s. */
static struct hmap monitor_hmap = HMAP_INITIALIZER(&monitor_hmap);

/* heap for ordering mport based on bfd/cfm wakeup time. */
static struct heap monitor_heap;

/* guarded-list for storing the mports that need to send bfd/cfm control
 * packet soon. */
static struct guarded_list send_soon = GUARDED_OVS_LIST_INITIALIZER(&send_soon);

/* The monitor thread id. */
static pthread_t monitor_tid;
/* True if the monitor thread is running. */
static bool monitor_running;

static struct latch monitor_exit_latch;
static struct ovs_mutex monitor_mutex = OVS_MUTEX_INITIALIZER;

static void *monitor_main(void *);
static void monitor_check_send_soon(struct dp_packet *);
static void monitor_run(void);
static void monitor_mport_run(struct mport *, struct dp_packet *);

static void mport_register(const struct ofport_dpif *, struct bfd *,
                           struct cfm *, struct lldp *, uint8_t[ETH_ADDR_LEN])
    OVS_REQUIRES(monitor_mutex);
static void mport_unregister(const struct ofport_dpif *)
    OVS_REQUIRES(monitor_mutex);
static void mport_update(struct mport *, struct bfd *, struct cfm *,
                         struct lldp *, uint8_t[ETH_ADDR_LEN])
    OVS_REQUIRES(monitor_mutex);
static struct mport *mport_find(const struct ofport_dpif *)
    OVS_REQUIRES(monitor_mutex);

/* Tries finding and returning the 'mport' from the monitor_hmap.
 * If there is no such 'mport', returns NULL. */
static struct mport *
mport_find(const struct ofport_dpif *ofport) OVS_REQUIRES(monitor_mutex)
{
    struct mport *node;

    HMAP_FOR_EACH_WITH_HASH (node, hmap_node, hash_pointer(ofport, 0),
                             &monitor_hmap) {
        if (node->ofport == ofport) {
            return node;
        }
    }
    return NULL;
}

/* Creates a new mport and inserts it into monitor_hmap and monitor_heap,
 * if it doesn't exist.  Otherwise, just updates its fields. */
static void
mport_register(const struct ofport_dpif *ofport, struct bfd *bfd,
               struct cfm *cfm, struct lldp *lldp, uint8_t *hw_addr)
    OVS_REQUIRES(monitor_mutex)
{
    struct mport *mport = mport_find(ofport);

    if (!mport) {
        mport = xzalloc(sizeof *mport);
        mport->ofport = ofport;
        hmap_insert(&monitor_hmap, &mport->hmap_node, hash_pointer(ofport, 0));
        heap_insert(&monitor_heap, &mport->heap_node, 0);
    }
    mport_update(mport, bfd, cfm, lldp, hw_addr);
}

/* Removes mport from monitor_hmap and monitor_heap and frees it. */
static void
mport_unregister(const struct ofport_dpif *ofport)
    OVS_REQUIRES(monitor_mutex)
{
    struct mport *mport = mport_find(ofport);

    if (mport) {
        mport_update(mport, NULL, NULL, NULL, NULL);
        hmap_remove(&monitor_hmap, &mport->hmap_node);
        heap_remove(&monitor_heap, &mport->heap_node);
        free(mport);
    }
}

/* Updates the fields of an existing mport struct. */
static void
mport_update(struct mport *mport, struct bfd *bfd, struct cfm *cfm,
             struct lldp *lldp, uint8_t hw_addr[ETH_ADDR_LEN])
    OVS_REQUIRES(monitor_mutex)
{
    ovs_assert(mport);

    if (mport->cfm != cfm) {
        cfm_unref(mport->cfm);
        mport->cfm = cfm_ref(cfm);
    }
    if (mport->bfd != bfd) {
        bfd_unref(mport->bfd);
        mport->bfd = bfd_ref(bfd);
    }
    if (mport->lldp != lldp) {
        lldp_unref(mport->lldp);
        mport->lldp = lldp_ref(lldp);
    }
    if (hw_addr && memcmp(mport->hw_addr, hw_addr, ETH_ADDR_LEN)) {
        memcpy(mport->hw_addr, hw_addr, ETH_ADDR_LEN);
    }
    /* If bfd/cfm/lldp is added or reconfigured, move the mport on top of the heap
     * so that the monitor thread can run the mport next time it wakes up. */
    if (mport->bfd || mport->cfm || mport->lldp) {
        heap_change(&monitor_heap, &mport->heap_node, LLONG_MAX);
    }
}

/* The 'main' function for the monitor thread. */
static void *
monitor_main(void * args OVS_UNUSED)
{
    VLOG_INFO("monitor thread created");
    while (!latch_is_set(&monitor_exit_latch)) {
        monitor_run();
        latch_wait(&monitor_exit_latch);
        poll_block();
    }
    VLOG_INFO("monitor thread terminated");
    return NULL;
}

/* The monitor thread should wake up this often to ensure that newly added or
 * reconfigured monitoring ports are run in a timely manner. */
#define MONITOR_INTERVAL_MSEC 100

/* Checks the 'send_soon' list and the heap for mports that have timed
 * out bfd/cfm sessions. */
static void
monitor_run(void)
{
    uint32_t stub[512 / 4];
    long long int prio_now;
    struct dp_packet packet;

    dp_packet_use_stub(&packet, stub, sizeof stub);
    ovs_mutex_lock(&monitor_mutex);

    /* The monitor_check_send_soon() needs to be run twice.  The first
     * time is for preventing the same 'mport' from being processed twice
     * (i.e. once from heap, the other from the 'send_soon' array).
     * The second run is to cover the case when the control packet is sent
     * via patch port and the other end needs to send back immediately. */
    monitor_check_send_soon(&packet);

    prio_now = MSEC_TO_PRIO(time_msec());
    /* Peeks the top of heap and checks if we should run this mport. */
    while (!heap_is_empty(&monitor_heap)
           && heap_max(&monitor_heap)->priority >= prio_now) {
        struct mport *mport;

        mport = CONTAINER_OF(heap_max(&monitor_heap), struct mport, heap_node);
        monitor_mport_run(mport, &packet);
    }

    monitor_check_send_soon(&packet);

    /* Waits on the earliest next wakeup time. */
    if (!heap_is_empty(&monitor_heap)) {
        long long int next_timeout, next_mport_wakeup;

        next_timeout = time_msec() + MONITOR_INTERVAL_MSEC;
        next_mport_wakeup = PRIO_TO_MSEC(heap_max(&monitor_heap)->priority);
        poll_timer_wait_until(MIN(next_timeout, next_mport_wakeup));
    }
    ovs_mutex_unlock(&monitor_mutex);
    dp_packet_uninit(&packet);
}

/* Checks the 'send_soon' list for any mport that needs to send cfm/bfd
 * control packet immediately, and calls monitor_mport_run(). */
static void
monitor_check_send_soon(struct dp_packet *packet)
    OVS_REQUIRES(monitor_mutex)
{
    while (!guarded_list_is_empty(&send_soon)) {
        struct send_soon_entry *entry;
        struct mport *mport;

        entry = CONTAINER_OF(guarded_list_pop_front(&send_soon),
                             struct send_soon_entry, list_node);
        mport = mport_find(entry->ofport);
        if (mport) {
            monitor_mport_run(mport, packet);
        }
        free(entry);
    }
}

/* Checks the sending of control packet on 'mport'.  Sends the control
 * packet if needed.  Executes bfd and cfm periodic functions (run, wait)
 * on 'mport'.  And changes the location of 'mport' in heap based on next
 * timeout. */
static void
monitor_mport_run(struct mport *mport, struct dp_packet *packet)
    OVS_REQUIRES(monitor_mutex)
{
    long long int next_wake_time;
    long long int bfd_wake_time = LLONG_MAX;
    long long int cfm_wake_time = LLONG_MAX;
    long long int lldp_wake_time = LLONG_MAX;

    if (mport->cfm && cfm_should_send_ccm(mport->cfm)) {
        dp_packet_clear(packet);
        cfm_compose_ccm(mport->cfm, packet, mport->hw_addr);
        ofproto_dpif_send_packet(mport->ofport, packet);
    }
    if (mport->bfd && bfd_should_send_packet(mport->bfd)) {
        dp_packet_clear(packet);
        bfd_put_packet(mport->bfd, packet, mport->hw_addr);
        ofproto_dpif_send_packet(mport->ofport, packet);
    }
    if (mport->lldp && lldp_should_send_packet(mport->lldp)) {
        dp_packet_clear(packet);
        lldp_put_packet(mport->lldp, packet, mport->hw_addr);
        ofproto_dpif_send_packet(mport->ofport, packet);
    }

    if (mport->cfm) {
        cfm_run(mport->cfm);
        cfm_wake_time = cfm_wait(mport->cfm);
    }
    if (mport->bfd) {
        bfd_run(mport->bfd);
        bfd_wake_time = bfd_wait(mport->bfd);
    }
    if (mport->lldp) {
        lldp_wake_time = lldp_wait(mport->lldp);
    }
    /* Computes the next wakeup time for this mport. */
    next_wake_time = MIN(bfd_wake_time,
                         cfm_wake_time);
    next_wake_time = MIN(next_wake_time, lldp_wake_time);
    heap_change(&monitor_heap, &mport->heap_node,
                MSEC_TO_PRIO(next_wake_time));
}

/* Creates the mport in monitor module if either bfd or cfm
 * is configured.  Otherwise, deletes the mport.
 * Also checks whether the monitor thread should be started
 * or terminated. */
void
ofproto_dpif_monitor_port_update(const struct ofport_dpif *ofport,
                                 struct bfd *bfd, struct cfm *cfm,
                                 struct lldp *lldp,
                                 uint8_t hw_addr[ETH_ADDR_LEN])
{
    ovs_mutex_lock(&monitor_mutex);
    if (!cfm && !bfd && !lldp) {
        mport_unregister(ofport);
    } else {
        mport_register(ofport, bfd, cfm, lldp, hw_addr);
    }
    ovs_mutex_unlock(&monitor_mutex);

    /* If the monitor thread is not running and the hmap
     * is not empty, starts it.  If it is and the hmap is empty,
     * terminates it. */
    if (!monitor_running && !hmap_is_empty(&monitor_hmap))  {
        latch_init(&monitor_exit_latch);
        monitor_tid = ovs_thread_create("monitor", monitor_main, NULL);
        monitor_running = true;
    } else if (monitor_running && hmap_is_empty(&monitor_hmap))  {
        latch_set(&monitor_exit_latch);
        xpthread_join(monitor_tid, NULL);
        latch_destroy(&monitor_exit_latch);
        monitor_running = false;
    }
}

/* Registers the 'ofport' in the 'send_soon' list.  We cannot directly
 * insert the corresponding mport to the 'send_soon' list, since the
 * 'send_soon' list is not updated when the mport is removed.
 *
 * Reader of the 'send_soon' list is responsible for freeing the entry. */
void
ofproto_dpif_monitor_port_send_soon(const struct ofport_dpif *ofport)
{
    struct send_soon_entry *entry = xzalloc(sizeof *entry);
    entry->ofport = ofport;

    guarded_list_push_back(&send_soon, &entry->list_node, SIZE_MAX);
}


text:
package com.github.jasonmfehr.combiner.mojo;

import java.util.List;
import java.util.Map;

import org.apache.maven.plugins.annotations.Parameter;

import com.github.jasonmfehr.combiner.combiner.ResourceCombiner;
import com.github.jasonmfehr.combiner.input.InputSourceReader;
import com.github.jasonmfehr.combiner.output.OutputSourceWriter;
import com.github.jasonmfehr.combiner.transformer.ResourceTransformer;

/**
 * Specifies a single combination of all configuration required to run a full pipeline cycle.
 *
 * @author jasonmfehr
 * @since 1.0.0
 */
public class Combination {

	/**
	 * String that uniquely identifies this particular combination.  This
	 * parameter is optional and only used in log messages.  Specifying
	 * a value is recommended when using more than one combination as it
	 * will be much easier to identify which combination set has the problem.
	 */
	@Parameter
	private String id;

	/**
	 * List of resources that will be used as the inputs to the combiner.
	 */
	@Parameter(required=true)
	private InputResources inputResources;

	/**
	 * {@link InputSourceReader} class to use when reading the inputSources.  If no package is specified,
	 * defaults to {@code com.github.jasonmfehr.combiner.input}
	 */
	@Parameter(required=true, defaultValue="FileInputSourceReader")
	private String inputSourceReader;

	/**
	 * List of the {@link ResourceTransformer} classes that will be applied to each input source.
	 * If no package is specified, defaults to {@code com.github.jasonmfehr.combiner.transformer}.
	 * Since this is an optional parameter, if no transformers are specified, then
	 * no transformations will be applied.
	 */
	@Parameter
	private List<String> transformers;

	/**
	 * {@link ResourceCombiner} that will be used to combine all the input sources.
	 * If no package is specified, defaults to {@code com.github.jasonmfehr.combiner.combiner}
	 */
	@Parameter(required=true)
	private String combiner;

	/**
	 * {@link OutputSourceWriter} class to use to write out the combined contents.  If no package is specified,
	 * defaults to {@code com.github.jasonmfehr.combiner.output}
	 */
	@Parameter(required=true, defaultValue="FileOutputSourceWriter")
	private String outputSourceWriter;

	/**
	 * Location of the resource where the combined inputs will be written.
	 */
	@Parameter(required=true)
	private String outputDestination;

	/**
	 * The charset to use when reading and writing the resources.
	 */
	@Parameter(required=true, defaultValue="${project.build.sourceEncoding}")
	private String encoding;

	/**
	 * List of key-value pairs that are used to provide additional
	 * configuration to the combining pipeline.  There are no restrictions on
	 * what can be put here.  Each pipeline stage implementation chooses what
	 * settings it needs (if any).  Format is <key>value</key>
	 */
	@Parameter
	private Map<String, String> settings;

	public String getId() {
		return this.id;
	}
	public void setId(String id) {
		this.id = id;
	}

	public InputResources getInputSources() {
		return inputResources;
	}
	public void setInputSources(InputResources inputSources) {
		this.inputResources = inputSources;
	}

	public String getInputSourceReader() {
		return inputSourceReader;
	}
	public void setInputSourceReader(String inputSourceReader) {
		this.inputSourceReader = inputSourceReader;
	}

	public List<String> getTransformers() {
		return transformers;
	}
	public void setTransformers(List<String> transformers) {
		this.transformers = transformers;
	}

	public String getCombiner() {
		return combiner;
	}
	public void setCombiner(String combiner) {
		this.combiner = combiner;
	}

	public String getOutputSourceWriter() {
		return outputSourceWriter;
	}
	public void setOutputSourceWriter(String outputSourceWriter) {
		this.outputSourceWriter = outputSourceWriter;
	}

	public String getOutputDestination() {
		return outputDestination;
	}
	public void setOutputDestination(String outputDestination) {
		this.outputDestination = outputDestination;
	}

	public String getEncoding() {
		return encoding;
	}
	public void setEncoding(String encoding) {
		this.encoding = encoding;
	}

	public Map<String, String> getSettings() {
		return settings;
	}
	public void setSettings(Map<String, String> settings) {
		this.settings = settings;
	}

}


text:
'use strict';

angular.module('flippersApp')
    .controller('FooterCtrl', function($scope) {
        $scope.version = '1.0.0-alpha';
    });


text:
#include "config.h"
#include "core/html/HTMLCanvasElement.h"

#include "bindings/core/v8/ExceptionMessages.h"
#include "bindings/core/v8/ExceptionState.h"
#include "bindings/core/v8/ScriptController.h"
#include "core/HTMLNames.h"
#include "core/dom/Document.h"
#include "core/dom/ExceptionCode.h"
#include "core/frame/LocalFrame.h"
#include "core/frame/Settings.h"
#include "core/html/ImageData.h"
#include "core/html/canvas/Canvas2DContextAttributes.h"
#include "core/html/canvas/CanvasRenderingContext2D.h"
#include "core/html/canvas/WebGLContextAttributes.h"
#include "core/html/canvas/WebGLContextEvent.h"
#include "core/html/canvas/WebGLRenderingContext.h"
#include "core/rendering/RenderHTMLCanvas.h"
#include "platform/MIMETypeRegistry.h"
#include "platform/RuntimeEnabledFeatures.h"
#include "platform/graphics/Canvas2DImageBufferSurface.h"
#include "platform/graphics/GraphicsContextStateSaver.h"
#include "platform/graphics/ImageBuffer.h"
#include "platform/graphics/RecordingImageBufferSurface.h"
#include "platform/graphics/UnacceleratedImageBufferSurface.h"
#include "platform/graphics/gpu/WebGLImageBufferSurface.h"
#include "platform/transforms/AffineTransform.h"
#include "public/platform/Platform.h"
#include <math.h>
#include <v8.h>

namespace blink {

using namespace HTMLNames;

// These values come from the WhatWG spec.
static const int DefaultWidth = 300;
static const int DefaultHeight = 150;

// Firefox limits width/height to 32767 pixels, but slows down dramatically before it
// reaches that limit. We limit by area instead, giving us larger maximum dimensions,
// in exchange for a smaller maximum canvas size.
static const int MaxCanvasArea = 32768 * 8192; // Maximum canvas area in CSS pixels

//In Skia, we will also limit width/height to 32767.
static const int MaxSkiaDim = 32767; // Maximum width/height in CSS pixels.

DEFINE_EMPTY_DESTRUCTOR_WILL_BE_REMOVED(CanvasObserver);

inline HTMLCanvasElement::HTMLCanvasElement(Document& document)
    : HTMLElement(canvasTag, document)
    , DocumentVisibilityObserver(document)
    , m_size(DefaultWidth, DefaultHeight)
    , m_ignoreReset(false)
    , m_accelerationDisabled(false)
    , m_externallyAllocatedMemory(0)
    , m_originClean(true)
    , m_didFailToCreateImageBuffer(false)
    , m_didClearImageBuffer(false)
{
    ScriptWrappable::init(this);
}

DEFINE_NODE_FACTORY(HTMLCanvasElement)

HTMLCanvasElement::~HTMLCanvasElement()
{
    resetDirtyRect();
    v8::Isolate::GetCurrent()->AdjustAmountOfExternalAllocatedMemory(-m_externallyAllocatedMemory);
#if !ENABLE(OILPAN)
    HashSet<RawPtr<CanvasObserver> >::iterator end = m_observers.end();
    for (HashSet<RawPtr<CanvasObserver> >::iterator it = m_observers.begin(); it != end; ++it)
        (*it)->canvasDestroyed(this);
    // Ensure these go away before the ImageBuffer.
    m_contextStateSaver.clear();
    m_context.clear();
#endif
}

void HTMLCanvasElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
{
    if (name == widthAttr || name == heightAttr)
        reset();
    HTMLElement::parseAttribute(name, value);
}

RenderObject* HTMLCanvasElement::createRenderer(RenderStyle* style)
{
    LocalFrame* frame = document().frame();
    if (frame && frame->script().canExecuteScripts(NotAboutToExecuteScript))
        return new RenderHTMLCanvas(this);
    return HTMLElement::createRenderer(style);
}

Node::InsertionNotificationRequest HTMLCanvasElement::insertedInto(ContainerNode* node)
{
    setIsInCanvasSubtree(true);
    return HTMLElement::insertedInto(node);
}

void HTMLCanvasElement::addObserver(CanvasObserver* observer)
{
    m_observers.add(observer);
}

void HTMLCanvasElement::removeObserver(CanvasObserver* observer)
{
    m_observers.remove(observer);
}

void HTMLCanvasElement::setHeight(int value)
{
    setIntegralAttribute(heightAttr, value);
}

void HTMLCanvasElement::setWidth(int value)
{
    setIntegralAttribute(widthAttr, value);
}

CanvasRenderingContext* HTMLCanvasElement::getContext(const String& type, CanvasContextAttributes* attrs)
{
    // A Canvas can either be "2D" or "webgl" but never both. If you request a 2D canvas and the existing
    // context is already 2D, just return that. If the existing context is WebGL, then destroy it
    // before creating a new 2D context. Vice versa when requesting a WebGL canvas. Requesting a
    // context with any other type string will destroy any existing context.
    enum ContextType {
        Context2d,
        ContextWebkit3d,
        ContextExperimentalWebgl,
        ContextWebgl,
        // Only add new items to the end and keep the order of existing items.
        ContextTypeCount,
    };

    // FIXME - The code depends on the context not going away once created, to prevent JS from
    // seeing a dangling pointer. So for now we will disallow the context from being changed
    // once it is created.
    if (type == "2d") {
        if (m_context && !m_context->is2d())
            return 0;
        if (!m_context) {
            blink::Platform::current()->histogramEnumeration("Canvas.ContextType", Context2d, ContextTypeCount);
            m_context = CanvasRenderingContext2D::create(this, static_cast<Canvas2DContextAttributes*>(attrs), document().inQuirksMode());
            setNeedsCompositingUpdate();
        }
        return m_context.get();
    }

    // Accept the the provisional "experimental-webgl" or official "webgl" context ID.
    if (type == "webgl" || type == "experimental-webgl") {
        ContextType contextType = (type == "webgl") ? ContextWebgl : ContextExperimentalWebgl;
        if (!m_context) {
            blink::Platform::current()->histogramEnumeration("Canvas.ContextType", contextType, ContextTypeCount);
            m_context = WebGLRenderingContext::create(this, static_cast<WebGLContextAttributes*>(attrs));
            setNeedsCompositingUpdate();
            updateExternallyAllocatedMemory();
        } else if (!m_context->is3d()) {
            dispatchEvent(WebGLContextEvent::create(EventTypeNames::webglcontextcreationerror, false, true, "Canvas has an existing, non-WebGL context"));
            return 0;
        }
        return m_context.get();
    }

    return 0;
}

void HTMLCanvasElement::didDraw(const FloatRect& rect)
{
    if (rect.isEmpty())
        return;
    clearCopiedImage();
    if (m_dirtyRect.isEmpty())
        blink::Platform::current()->currentThread()->addTaskObserver(this);
    m_dirtyRect.unite(rect);
}

void HTMLCanvasElement::didFinalizeFrame()
{
    if (m_dirtyRect.isEmpty())
        return;

    // Propagate the m_dirtyRect accumulated so far to the compositor
    // before restarting with a blank dirty rect.
    FloatRect srcRect(0, 0, size().width(), size().height());
    m_dirtyRect.intersect(srcRect);
    if (RenderBox* ro = renderBox()) {
        FloatRect mappedDirtyRect = mapRect(m_dirtyRect, srcRect, ro->contentBoxRect());
        ro->invalidatePaintRectangle(enclosingIntRect(mappedDirtyRect));
    }
    notifyObserversCanvasChanged(m_dirtyRect);
    blink::Platform::current()->currentThread()->removeTaskObserver(this);
    m_dirtyRect = FloatRect();
}

void HTMLCanvasElement::resetDirtyRect()
{
    if (m_dirtyRect.isEmpty())
        return;
    blink::Platform::current()->currentThread()->removeTaskObserver(this);
    m_dirtyRect = FloatRect();
}

void HTMLCanvasElement::didProcessTask()
{
    // This method gets invoked if didDraw was called earlier in the current task.
    ASSERT(!m_dirtyRect.isEmpty());
    if (is3D()) {
        didFinalizeFrame();
    } else {
        ASSERT(hasImageBuffer());
        m_imageBuffer->finalizeFrame();
    }
    ASSERT(m_dirtyRect.isEmpty());
}

void HTMLCanvasElement::willProcessTask()
{
    ASSERT_NOT_REACHED();
}

void HTMLCanvasElement::notifyObserversCanvasChanged(const FloatRect& rect)
{
    WillBeHeapHashSet<RawPtrWillBeWeakMember<CanvasObserver> >::iterator end = m_observers.end();
    for (WillBeHeapHashSet<RawPtrWillBeWeakMember<CanvasObserver> >::iterator it = m_observers.begin(); it != end; ++it)
        (*it)->canvasChanged(this, rect);
}

void HTMLCanvasElement::reset()
{
    if (m_ignoreReset)
        return;

    resetDirtyRect();

    bool ok;
    bool hadImageBuffer = hasImageBuffer();

    int w = getAttribute(widthAttr).toInt(&ok);
    if (!ok || w < 0)
        w = DefaultWidth;

    int h = getAttribute(heightAttr).toInt(&ok);
    if (!ok || h < 0)
        h = DefaultHeight;

    if (m_contextStateSaver) {
        // Reset to the initial graphics context state.
        m_contextStateSaver->restore();
        m_contextStateSaver->save();
    }

    if (m_context && m_context->is2d())
        toCanvasRenderingContext2D(m_context.get())->reset();

    IntSize oldSize = size();
    IntSize newSize(w, h);

    // If the size of an existing buffer matches, we can just clear it instead of reallocating.
    // This optimization is only done for 2D canvases for now.
    if (hadImageBuffer && oldSize == newSize && m_context && m_context->is2d()) {
        if (!m_didClearImageBuffer)
            clearImageBuffer();
        return;
    }

    setSurfaceSize(newSize);

    if (m_context && m_context->is3d() && oldSize != size())
        toWebGLRenderingContext(m_context.get())->reshape(width(), height());

    if (RenderObject* renderer = this->renderer()) {
        if (renderer->isCanvas()) {
            if (oldSize != size()) {
                toRenderHTMLCanvas(renderer)->canvasSizeChanged();
                if (renderBox() && renderBox()->hasAcceleratedCompositing())
                    renderBox()->contentChanged(CanvasChanged);
            }
            if (hadImageBuffer)
                renderer->setShouldDoFullPaintInvalidation(true);
        }
    }

    WillBeHeapHashSet<RawPtrWillBeWeakMember<CanvasObserver> >::iterator end = m_observers.end();
    for (WillBeHeapHashSet<RawPtrWillBeWeakMember<CanvasObserver> >::iterator it = m_observers.begin(); it != end; ++it)
        (*it)->canvasResized(this);
}

bool HTMLCanvasElement::paintsIntoCanvasBuffer() const
{
    ASSERT(m_context);

    if (!m_context->isAccelerated())
        return true;

    if (renderBox() && renderBox()->hasAcceleratedCompositing())
        return false;

    return true;
}

void HTMLCanvasElement::paint(GraphicsContext* context, const LayoutRect& r)
{
    if (m_context) {
        if (!paintsIntoCanvasBuffer() && !document().printing())
            return;
        m_context->paintRenderingResultsToCanvas();
    }

    if (hasImageBuffer()) {
        ImageBuffer* imageBuffer = buffer();
        if (imageBuffer) {
            CompositeOperator compositeOperator = !m_context || m_context->hasAlpha() ? CompositeSourceOver : CompositeCopy;
            if (m_presentedImage)
                context->drawImage(m_presentedImage.get(), pixelSnappedIntRect(r), compositeOperator, DoNotRespectImageOrientation);
            else
                context->drawImageBuffer(imageBuffer, pixelSnappedIntRect(r), 0, compositeOperator);
        }
    } else {
        // When alpha is false, we should draw to opaque black.
        if (m_context && !m_context->hasAlpha())
            context->fillRect(FloatRect(r), Color(0, 0, 0));
    }

    if (is3D())
        toWebGLRenderingContext(m_context.get())->markLayerComposited();
}

bool HTMLCanvasElement::is3D() const
{
    return m_context && m_context->is3d();
}

void HTMLCanvasElement::makePresentationCopy()
{
    if (!m_presentedImage) {
        // The buffer contains the last presented data, so save a copy of it.
        m_presentedImage = buffer()->copyImage(CopyBackingStore, Unscaled);
        updateExternallyAllocatedMemory();
    }
}

void HTMLCanvasElement::clearPresentationCopy()
{
    m_presentedImage.clear();
    updateExternallyAllocatedMemory();
}

void HTMLCanvasElement::setSurfaceSize(const IntSize& size)
{
    m_size = size;
    m_didFailToCreateImageBuffer = false;
    discardImageBuffer();
    clearCopiedImage();
    if (m_context && m_context->is2d()) {
        CanvasRenderingContext2D* context2d = toCanvasRenderingContext2D(m_context.get());
        if (context2d->isContextLost()) {
            context2d->restoreContext();
        }
    }
}

String HTMLCanvasElement::toEncodingMimeType(const String& mimeType)
{
    String lowercaseMimeType = mimeType.lower();

    // FIXME: Make isSupportedImageMIMETypeForEncoding threadsafe (to allow this method to be used on a worker thread).
    if (mimeType.isNull() || !MIMETypeRegistry::isSupportedImageMIMETypeForEncoding(lowercaseMimeType))
        lowercaseMimeType = "image/png";

    return lowercaseMimeType;
}

const AtomicString HTMLCanvasElement::imageSourceURL() const
{
    return AtomicString(toDataURLInternal("image/png", 0, true));
}

String HTMLCanvasElement::toDataURLInternal(const String& mimeType, const double* quality, bool isSaving) const
{
    if (m_size.isEmpty() || !buffer())
        return String("data:,");

    String encodingMimeType = toEncodingMimeType(mimeType);

    // Try to get ImageData first, as that may avoid lossy conversions.
    RefPtrWillBeRawPtr<ImageData> imageData = getImageData();

    if (imageData)
        return ImageDataToDataURL(ImageDataBuffer(imageData->size(), imageData->data()), encodingMimeType, quality);

    if (m_context && m_context->is3d()) {
        toWebGLRenderingContext(m_context.get())->setSavingImage(isSaving);
        m_context->paintRenderingResultsToCanvas();
        toWebGLRenderingContext(m_context.get())->setSavingImage(false);
    }

    return buffer()->toDataURL(encodingMimeType, quality);
}

String HTMLCanvasElement::toDataURL(const String& mimeType, const double* quality, ExceptionState& exceptionState) const
{
    if (!m_originClean) {
        exceptionState.throwSecurityError("Tainted canvases may not be exported.");
        return String();
    }

    return toDataURLInternal(mimeType, quality);
}

PassRefPtrWillBeRawPtr<ImageData> HTMLCanvasElement::getImageData() const
{
    if (!m_context || !m_context->is3d())
        return nullptr;
    return toWebGLRenderingContext(m_context.get())->paintRenderingResultsToImageData();
}

SecurityOrigin* HTMLCanvasElement::securityOrigin() const
{
    return document().securityOrigin();
}

bool HTMLCanvasElement::shouldAccelerate(const IntSize& size) const
{
    if (m_context && !m_context->is2d())
        return false;

    if (m_accelerationDisabled)
        return false;

    Settings* settings = document().settings();
    if (!settings || !settings->accelerated2dCanvasEnabled())
        return false;

    // Do not use acceleration for small canvas.
    if (size.width() * size.height() < settings->minimumAccelerated2dCanvasSize())
        return false;

    if (!blink::Platform::current()->canAccelerate2dCanvas())
        return false;

    return true;
}

PassOwnPtr<ImageBufferSurface> HTMLCanvasElement::createImageBufferSurface(const IntSize& deviceSize, int* msaaSampleCount)
{
    OpacityMode opacityMode = !m_context || m_context->hasAlpha() ? NonOpaque : Opaque;

    *msaaSampleCount = 0;
    if (is3D())
        return adoptPtr(new WebGLImageBufferSurface(size(), opacityMode));

    if (RuntimeEnabledFeatures::displayList2dCanvasEnabled()) {
        OwnPtr<ImageBufferSurface> surface = adoptPtr(new RecordingImageBufferSurface(size(), opacityMode));
        if (surface->isValid())
            return surface.release();
    }

    if (shouldAccelerate(deviceSize)) {
        if (document().settings())
            *msaaSampleCount = document().settings()->accelerated2dCanvasMSAASampleCount();
        OwnPtr<ImageBufferSurface> surface = adoptPtr(new Canvas2DImageBufferSurface(size(), opacityMode, *msaaSampleCount));
        if (surface->isValid())
            return surface.release();
    }

    return adoptPtr(new UnacceleratedImageBufferSurface(size(), opacityMode));
}

void HTMLCanvasElement::createImageBuffer()
{
    createImageBufferInternal();
    if (m_didFailToCreateImageBuffer && m_context && m_context->is2d())
        toCanvasRenderingContext2D(m_context.get())->loseContext();
}

void HTMLCanvasElement::createImageBufferInternal()
{
    ASSERT(!m_imageBuffer);
    ASSERT(!m_contextStateSaver);

    m_didFailToCreateImageBuffer = true;
    m_didClearImageBuffer = true;

    IntSize deviceSize = size();
    if (deviceSize.width() * deviceSize.height() > MaxCanvasArea)
        return;

    if (deviceSize.width() > MaxSkiaDim || deviceSize.height() > MaxSkiaDim)
        return;

    if (!deviceSize.width() || !deviceSize.height())
        return;

    int msaaSampleCount;
    OwnPtr<ImageBufferSurface> surface = createImageBufferSurface(deviceSize, &msaaSampleCount);
    if (!surface->isValid())
        return;

    m_imageBuffer = ImageBuffer::create(surface.release());
    m_imageBuffer->setClient(this);

    m_didFailToCreateImageBuffer = false;

    updateExternallyAllocatedMemory();

    if (is3D()) {
        // Early out for WebGL canvases
        return;
    }

    m_imageBuffer->setClient(this);
    m_imageBuffer->context()->setShouldClampToSourceRect(false);
    m_imageBuffer->context()->disableAntialiasingOptimizationForHairlineImages();
    m_imageBuffer->context()->setImageInterpolationQuality(CanvasDefaultInterpolationQuality);
    // Enabling MSAA overrides a request to disable antialiasing. This is true regardless of whether the
    // rendering mode is accelerated or not. For consistency, we don't want to apply AA in accelerated
    // canvases but not in unaccelerated canvases.
    if (!msaaSampleCount && document().settings() && !document().settings()->antialiased2dCanvasEnabled())
        m_imageBuffer->context()->setShouldAntialias(false);
    // GraphicsContext's defaults don't always agree with the 2d canvas spec.
    // See CanvasRenderingContext2D::State::State() for more information.
    m_imageBuffer->context()->setMiterLimit(10);
    m_imageBuffer->context()->setStrokeThickness(1);
#if ENABLE(ASSERT)
    m_imageBuffer->context()->disableDestructionChecks(); // 2D canvas is allowed to leave context in an unfinalized state.
#endif
    m_contextStateSaver = adoptPtr(new GraphicsContextStateSaver(*m_imageBuffer->context()));

    if (m_context)
        setNeedsCompositingUpdate();
}

void HTMLCanvasElement::notifySurfaceInvalid()
{
    if (m_context && m_context->is2d()) {
        CanvasRenderingContext2D* context2d = toCanvasRenderingContext2D(m_context.get());
        context2d->loseContext();
    }
}

void HTMLCanvasElement::trace(Visitor* visitor)
{
#if ENABLE(OILPAN)
    visitor->trace(m_observers);
    visitor->trace(m_context);
#endif
    DocumentVisibilityObserver::trace(visitor);
    HTMLElement::trace(visitor);
}

void HTMLCanvasElement::updateExternallyAllocatedMemory() const
{
    int bufferCount = 0;
    if (m_imageBuffer)
        bufferCount++;
    if (is3D())
        bufferCount += 2;
    if (m_copiedImage)
        bufferCount++;
    if (m_presentedImage)
        bufferCount++;

    Checked<intptr_t, RecordOverflow> checkedExternallyAllocatedMemory = 4 * bufferCount;
    checkedExternallyAllocatedMemory *= width();
    checkedExternallyAllocatedMemory *= height();
    intptr_t externallyAllocatedMemory;
    if (checkedExternallyAllocatedMemory.safeGet(externallyAllocatedMemory) == CheckedState::DidOverflow)
        externallyAllocatedMemory = std::numeric_limits<intptr_t>::max();

    // Subtracting two intptr_t that are known to be positive will never underflow.
    v8::Isolate::GetCurrent()->AdjustAmountOfExternalAllocatedMemory(externallyAllocatedMemory - m_externallyAllocatedMemory);
    m_externallyAllocatedMemory = externallyAllocatedMemory;
}

GraphicsContext* HTMLCanvasElement::drawingContext() const
{
    return buffer() ? m_imageBuffer->context() : 0;
}

GraphicsContext* HTMLCanvasElement::existingDrawingContext() const
{
    if (!hasImageBuffer())
        return 0;

    return drawingContext();
}

ImageBuffer* HTMLCanvasElement::buffer() const
{
    if (!hasImageBuffer() && !m_didFailToCreateImageBuffer)
        const_cast<HTMLCanvasElement*>(this)->createImageBuffer();
    return m_imageBuffer.get();
}

void HTMLCanvasElement::ensureUnacceleratedImageBuffer()
{
    if ((hasImageBuffer() && !m_imageBuffer->isAccelerated()) || m_didFailToCreateImageBuffer)
        return;
    discardImageBuffer();
    OpacityMode opacityMode = !m_context || m_context->hasAlpha() ? NonOpaque : Opaque;
    m_imageBuffer = ImageBuffer::create(size(), opacityMode);
    m_didFailToCreateImageBuffer = !m_imageBuffer;
}

Image* HTMLCanvasElement::copiedImage() const
{
    if (!m_copiedImage && buffer()) {
        if (m_context && m_context->is3d()) {
            toWebGLRenderingContext(m_context.get())->setSavingImage(true);
            m_context->paintRenderingResultsToCanvas();
            toWebGLRenderingContext(m_context.get())->setSavingImage(false);
        }
        m_copiedImage = buffer()->copyImage(CopyBackingStore, Unscaled);
        updateExternallyAllocatedMemory();
    }
    return m_copiedImage.get();
}

void HTMLCanvasElement::clearImageBuffer()
{
    ASSERT(hasImageBuffer() && !m_didFailToCreateImageBuffer);
    ASSERT(!m_didClearImageBuffer);
    ASSERT(m_context);

    m_didClearImageBuffer = true;

    if (m_context->is2d()) {
        // No need to undo transforms/clip/etc. because we are called right
        // after the context is reset.
        toCanvasRenderingContext2D(m_context.get())->clearRect(0, 0, width(), height());
    }
}

void HTMLCanvasElement::discardImageBuffer()
{
    m_contextStateSaver.clear(); // uses context owned by m_imageBuffer
    m_imageBuffer.clear();
    resetDirtyRect();
    updateExternallyAllocatedMemory();
}

bool HTMLCanvasElement::hasValidImageBuffer() const
{
    return m_imageBuffer && m_imageBuffer->isSurfaceValid();
}

void HTMLCanvasElement::clearCopiedImage()
{
    if (m_copiedImage) {
        m_copiedImage.clear();
        updateExternallyAllocatedMemory();
    }
    m_didClearImageBuffer = false;
}

AffineTransform HTMLCanvasElement::baseTransform() const
{
    ASSERT(hasImageBuffer() && !m_didFailToCreateImageBuffer);
    return m_imageBuffer->baseTransform();
}

void HTMLCanvasElement::didChangeVisibilityState(PageVisibilityState visibility)
{
    if (hasImageBuffer()) {
        bool hidden = visibility != PageVisibilityStateVisible;
        if (hidden) {
            clearCopiedImage();
            if (is3D()) {
                discardImageBuffer();
            }
        }
        if (hasImageBuffer()) {
            m_imageBuffer->setIsHidden(hidden);
        }
    }
}

void HTMLCanvasElement::didMoveToNewDocument(Document& oldDocument)
{
    setObservedDocument(document());
    HTMLElement::didMoveToNewDocument(oldDocument);
}

PassRefPtr<Image> HTMLCanvasElement::getSourceImageForCanvas(SourceImageMode mode, SourceImageStatus* status) const
{
    if (!width() || !height()) {
        *status = ZeroSizeCanvasSourceImageStatus;
        return nullptr;
    }

    if (!buffer()) {
        *status = InvalidSourceImageStatus;
        return nullptr;
    }

    if (mode == CopySourceImageIfVolatile) {
        *status = NormalSourceImageStatus;
        return copiedImage();
    }

    if (m_context && m_context->is3d()) {
        m_context->paintRenderingResultsToCanvas();
        *status = ExternalSourceImageStatus;
    } else {
        *status = NormalSourceImageStatus;
    }
    return m_imageBuffer->copyImage(DontCopyBackingStore, Unscaled);
}

bool HTMLCanvasElement::wouldTaintOrigin(SecurityOrigin*) const
{
    return !originClean();
}

FloatSize HTMLCanvasElement::sourceSize() const
{
    return FloatSize(width(), height());
}

}


text:
export function inject(name?: string): any;
export function service(name?: string): any;
declare let Service: any;
export default Service;


text:
#import "BBAStatusResponseMapper.h"
#import "BBAAuthenticationService.h"
#import "BBAAPIErrors.h"
#import "BBAAuthenticationServiceConstants.h"
#import "BBAConnection.h"

@interface BBASuccessLibraryResponseMapperTests : XCTestCase{
    BBAStatusResponseMapper *mapper;
}
@end

@implementation BBASuccessLibraryResponseMapperTests

#pragma mark - SetUp/TearDown

- (void)setUp{
    mapper = [BBAStatusResponseMapper new];
    [super setUp];
}

- (void)tearDown{
    mapper = nil;
    [super tearDown];
}

#pragma mark - Tests

- (void) testInit{
    XCTAssertNotNil(mapper, @"shouldn't be nil here");
}

- (void) testSuccessCode{
    NSError *error;
    BOOL succes = [[mapper responseFromData:nil
                                   response:[self responseWithHTTPStatus:BBAHTTPSuccess]
                                      error:&error] boolValue];

    XCTAssertTrue(succes, @"should return @YES");
    XCTAssertNil(error, @"nothing should be written to the error address");
}

- (void) testForbiddenCode{
    NSError *error;
    BOOL succes = [[mapper responseFromData:nil
                                   response:[self responseWithHTTPStatus:BBAHTTPForbidden]
                                      error:&error] boolValue];

    XCTAssertFalse(succes, @"should return @NO");
    XCTAssertEqual(error.code, BBAAPIErrorForbidden, @"Forbidden code");
    XCTAssertEqualObjects(error.domain, BBAConnectionErrorDomain, @"connection domain");
}

- (void) testUnauthorizedCode{
    NSError *error;
    BOOL succes = [[mapper responseFromData:nil
                                   response:[self responseWithHTTPStatus:BBAHTTPUnauthorized]
                                      error:&error] boolValue];

    XCTAssertFalse(succes, @"should return @NO");
    XCTAssertEqual(error.code, BBAAPIErrorUnauthorised, @"unauthorized code");
    XCTAssertEqualObjects(error.domain, kBBAAuthServiceName, @"auth domain");
}

- (void) testNotFoundCode{
    NSError *error;
    BOOL succes = [[mapper responseFromData:nil
                                   response:[self responseWithHTTPStatus:BBAHTTPNotFound]
                                      error:&error] boolValue];

    XCTAssertFalse(succes, @"should return @NO");
    XCTAssertEqual(error.code, BBAAPIErrorNotFound, @"Not found code");
    XCTAssertEqualObjects(error.domain, BBAConnectionErrorDomain, @"connection domain");
}

- (void) testServerErrorCode{
    NSError *error;
    BOOL succes = [[mapper responseFromData:nil
                                   response:[self responseWithHTTPStatus:BBAHTTPServerError]
                                      error:&error] boolValue];

    XCTAssertFalse(succes, @"should return @NO");
    XCTAssertEqual(error.code, BBAAPIServerError, @"server error code");
    XCTAssertEqualObjects(error.domain, BBAConnectionErrorDomain, @"connection domain");
}

- (void) testUnexpectedCodeThrows{
    XCTAssertThrows([mapper responseFromData:nil
                                    response:[self responseWithHTTPStatus:123]
                                       error:nil], @"unexpected http code");
}

#pragma mark - Helpers

- (NSHTTPURLResponse *)responseWithHTTPStatus:(NSInteger)status{
    NSHTTPURLResponse *URLResponse = [[NSHTTPURLResponse alloc] initWithURL:nil
                                                                 statusCode:status
                                                                HTTPVersion:@"HTTP/1.1"
                                                               headerFields:nil];
    return URLResponse;
}

@end


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

<title>BackgroundAnimation.AbstractBackgroundAnimationBuilder</title>
<meta name="date" content="2018-11-26">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

de.mrapp.android.dialog.animation

Class BackgroundAnimation.AbstractBackgroundAnimationBuilder<AnimationType extends BackgroundAnimation,BuilderType extends BackgroundAnimation.AbstractBackgroundAnimationBuilder<AnimationType,?>>

java.lang.Object

de.mrapp.android.dialog.builder.AbstractBuilder<AnimationType,BuilderType>

de.mrapp.android.dialog.animation.DrawableAnimation.AbstractDrawableAnimationBuilder<AnimationType,BuilderType>

de.mrapp.android.dialog.animation.BackgroundAnimation.AbstractBackgroundAnimationBuilder<AnimationType,BuilderType>

Type Parameters:

AnimationType - The type of the animations, which are created by the builder

BuilderType - The type of the builder

Direct Known Subclasses:

CircleTransitionAnimation.Builder, CrossFadeTransitionAnimation.Builder

Enclosing class:

BackgroundAnimation

protected abstract static class BackgroundAnimation.AbstractBackgroundAnimationBuilder<AnimationType extends BackgroundAnimation,BuilderType extends BackgroundAnimation.AbstractBackgroundAnimationBuilder<AnimationType,?>>
extends DrawableAnimation.AbstractDrawableAnimationBuilder<AnimationType,BuilderType>

An abstract base class for all builders, which allow to create animations, which can be used
 to change backgrounds.

Constructor Summary

Constructors

Modifier
Constructor and Description

protected
AbstractBackgroundAnimationBuilder(android.content.Context context)

Creates a new builder, which allows to create animations, which can be used to change
 backgrounds.

Method Summary

Methods inherited from class de.mrapp.android.dialog.animation.DrawableAnimation.AbstractDrawableAnimationBuilder

setDuration, setListener

Methods inherited from class de.mrapp.android.dialog.builder.AbstractBuilder

create, getContext, getProduct, onCreateProduct, self, setContext

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

AbstractBackgroundAnimationBuilder

protected AbstractBackgroundAnimationBuilder(@NonNull
                                             android.content.Context context)

Creates a new builder, which allows to create animations, which can be used to change
 backgrounds.

Parameters:

context - The context, which should be used by the builder, as an instance of the class
         Context. The context may not be null

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
class Organization:
    pass

class Facility:
    pass

class Network:
    pass

class InternetExchange:
    pass

class InternetExchangeFacility:
    pass

class InternetExchangeLan:
    pass

class InternetExchangeLanPrefix:
    pass

class NetworkFacility:
    pass

class NetworkIXLan:
    pass

class NetworkContact:
    pass


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

import docking.ActionContext;
import docking.action.MenuData;
import ghidra.app.plugin.core.navigation.FindAppliedDataTypesService;
import ghidra.app.util.HelpTopics;
import ghidra.program.model.data.Composite;
import ghidra.program.model.data.DataTypeComponent;
import ghidra.util.*;

/**
 * An action to show references to the field in the currently selected editor row
 */
public class FindReferencesToField extends CompositeEditorTableAction {

	public final static String ACTION_NAME = "Find Uses of";
	private final static String GROUP_NAME = BASIC_ACTION_GROUP;
	private final static String DESCRIPTION = "Find uses of field in the selected row";
	private static String[] popupPath = new String[] { ACTION_NAME };

	public FindReferencesToField(CompositeEditorProvider provider) {
		super(provider, EDIT_ACTION_PREFIX + ACTION_NAME, GROUP_NAME, popupPath, null, null);
		setDescription(DESCRIPTION);
		adjustEnablement();
		setHelpLocation(new HelpLocation(HelpTopics.FIND_REFERENCES, "Data_Types"));
	}

	@Override
	public void actionPerformed(ActionContext context) {

		FindAppliedDataTypesService service = tool.getService(FindAppliedDataTypesService.class);
		if (service == null) {
			Msg.showError(this, null, "Missing Plugin",
				"The FindAppliedDataTypesService is not installed.\n" +
					"Please add the plugin implementing this service.");
			return;
		}

		String fieldName = getFieldName();
		Composite composite = model.getOriginalComposite();
		Swing.runLater(() -> service.findAndDisplayAppliedDataTypeAddresses(composite, fieldName));
	}

	private String getFieldName() {
		int[] rows = model.getSelectedComponentRows();
		if (rows.length == 0) {
			return null;
		}

		int row = rows[0];
		DataTypeComponent dtComponet = model.getComponent(row);
		String fieldName = dtComponet.getFieldName();
		return fieldName;
	}

	@Override
	public void adjustEnablement() {
		setEnabled(false);
		if (model.getSelectedComponentRows().length != 1) {
			return;
		}

		Composite composite = model.getOriginalComposite();
		if (composite == null) {
			return; // not sure if this can happen
		}

		String fieldName = getFieldName();
		if (fieldName == null) {
			return;
		}

		setEnabled(true);
		updateMenuName(fieldName);
	}

	private void updateMenuName(String name) {

		String menuName = ACTION_NAME + ' ' + name;
		MenuData data = getPopupMenuData().cloneData();
		data.setMenuPath(new String[] { menuName });
		setPopupMenuData(data);
	}

}


text:
module Fog
  module Compute
    class Cloudstack

      class Real
        # Lists all volumes.
        #
        # {CloudStack API Reference}[http://cloudstack.apache.org/docs/api/apidocs-4.3/root_admin/listVolumes.html]
        def list_volumes(options={})
          options.merge!(
            'command' => 'listVolumes'
          )
          request(options)
        end
      end

      class Mock
        def list_volumes(options={})
          volume_id = options.delete('id')
          if volume_id
            volumes = [self.data[:volumes][volume_id]]
          else
            volumes = self.data[:volumes].values
          end

          {
            'listvolumesresponse' => {
              'count' => volumes.size,
              'volume' => volumes
            }
          }
        end
      end
    end
  end
end


text:
<BroadcastMonitor>
  <updated>2015-08-03T09:28:17</updated>
  <stationName>Radio 6</stationName>
  <Current>
    <startTime></startTime>
    <itemId></itemId>
    <titleId></titleId>
    <itemCode></itemCode>
    <itemReference></itemReference>
    <titleName></titleName>
    <artistName></artistName>
    <albumName></albumName>
    <CategoryCode></CategoryCode>
    <CategoryName></CategoryName>
    <itemDuration></itemDuration>
    <MultiMedia1></MultiMedia1>
    <MultiMedia2></MultiMedia2>
    <MultiMedia3></MultiMedia3>
    <MultiMedia4></MultiMedia4>
  </Current>
  <Next>
    <startTime>2015-08-03T09:28:14</startTime>
    <itemId>1000080504:1242174</itemId>
    <titleId>216084158</titleId>
    <itemCode></itemCode>
    <itemReference></itemReference>
    <titleName>*** Lekker Lang Jazz</titleName>
    <artistName></artistName>
    <albumName></albumName>
    <CategoryCode>756</CategoryCode>
    <CategoryName>EERST JAAP</CategoryName>
    <itemDuration>3</itemDuration>
    <MultiMedia1></MultiMedia1>
    <MultiMedia2></MultiMedia2>
    <MultiMedia3></MultiMedia3>
    <MultiMedia4></MultiMedia4>
  </Next>
</BroadcastMonitor>


text:
package com.netflix.spinnaker.clouddriver.model;

import java.util.Set;

public class NoopSubnetProvider implements SubnetProvider<Subnet> {

  @Override
  public String getCloudProvider() {
    return null;
  }

  @Override
  public Set<Subnet> getAll() {
    return Set.of();
  }
}


text:
var fs = require("fs");
var path = require("path");
var argparse =  require( "argparse" );
var uglify = require("uglify-js");
var spawn = require('child_process').spawn;

function main(){
    "use strict";
    var parser = new argparse.ArgumentParser();
    parser.addArgument(['--include'], {"action":'append', 'required':true});
    parser.addArgument(['--externs'], {"action":'append', "defaultValue":['./externs/common.js']});
    parser.addArgument(['--minify'], {"action":'storeTrue', "defaultValue":false});
    parser.addArgument(['--output'], {"defaultValue":'../build/operaextensions.js'});

	var args = parser.parseArgs();

    var output = args.output;
    console.log(' * Building ' + output);

    console.dir(args);

    var buffer = [];
    for (var i = 0;i < args.include.length;i++){

        var files = JSON.parse(fs.readFileSync('./includes/' + args.include[i] + '.json', 'utf8'));
        for (var file = 0;file < files.length;file++){
            buffer.push(fs.readFileSync(files[file], 'utf8'));
        }
    }
    console.log(buffer.length);
    var temp = buffer.join("");

    if (!args.minify){
        fs.writeFileSync(output,temp,'utf8');
    } else {

        fs.writeFileSync(output,uglify(temp),'utf8');

//        An attempt to get the closure minifier working

//        var externs = ' --externs ' + args.externs.join();
//        console.log(externs);
//        var temppath = output + ".tmp";
//        fs.writeFileSync(temppath,temp,'utf8');
//        var java = spawn("java -jar ./compiler/compiler.jar --warning_level=VERBOSE --jscomp_off=globalThis " + externs + " --jscomp_off=checkTypes --language_in=ECMASCRIPT5_STRICT --js " + temppath + "  --js_output_file " + output);
//        java.stdout.on('data', function (data) {
//            console.log(data);
//        });
//        java.stderr.on('data', function (data) {
//          console.log('java stderr: ' + data);
//        });
//        java.on('exit', function (code) {
//            if (code !== 0) {
//                console.log('java process exited with code ' + code);
//            }
//        });

    }
}
main();


text:
#ifndef FSM_SUBGRAPH_H
#define FSM_SUBGRAPH_H

/*
 * Spans nodes added between fsm_subgraph_start() and
 * fsm_subgraph_end()
 *
 * Can be used by fsm_subgraph_duplicate() to make copies of the subgraph.
 *
 * The subgraph capture is only valid as long as no nodes are deleted after
 * fsm_subgraph_start() is called.
 */
struct fsm_subgraph {
	fsm_state_t start;
	fsm_state_t end;
};

void
fsm_subgraph_start(struct fsm *fsm, struct fsm_subgraph *subgraph);

void
fsm_subgraph_stop(struct fsm *fsm, struct fsm_subgraph *subgraph);

/*
 * Duplicate a captured sub-graph.
 *
 * If non-NULL, the state x in the origional subgraph is overwritten with its
 * equivalent state in the duplicated subgraph.
 * This provides a mechanism to keep track of a state of interest (for example
 * the endpoint of a segment).
 *
 * The start of the subgraph is output to *q.
 */
int
fsm_subgraph_duplicate(struct fsm *fsm,
	const struct fsm_subgraph *subgraph,
	fsm_state_t *x,
	fsm_state_t *q);

#endif


text:
package org.colorcoding.ibas.bobas.db.mssql;

import java.sql.Connection;
import java.sql.DriverManager;

import org.colorcoding.ibas.bobas.db.DbException;
import org.colorcoding.ibas.bobas.db.IBOAdapter;

public class DbAdapter extends org.colorcoding.ibas.bobas.db.DbAdapter {

	@Override
	public Connection createConnection(String server, String dbName, String userName, String userPwd,
			String applicationName) throws DbException {
		try {
			Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
			String dbURL = String.format("jdbc:sqlserver://%s;DatabaseName=%s;ApplicationName=%s", server, dbName,
					applicationName);
			return DriverManager.getConnection(dbURL, userName, userPwd);
		} catch (Exception e) {
			// 接数据库失败
			throw new DbException(e);
		}
	}

	@Override
	public IBOAdapter createBOAdapter() {
		return new BOAdapter();
	}

}