text:
#include <linux/init.h>
#include <linux/module.h>
#include <linux/delay.h>
#include <linux/device.h>
#include <linux/gpio.h>
#include <linux/io.h>
#include <linux/ioport.h>
#include <linux/irq.h>
#include <linux/errno.h>
#include <linux/interrupt.h>
#include <linux/platform_device.h>
#include <linux/spi/spi.h>
#include <linux/workqueue.h>

#include <asm/portmux.h>
#include <asm/bfin5xx_spi.h>
#include <asm/blackfin.h>
#include <asm/bfin_sport.h>
#include <asm/cacheflush.h>

#define DRV_NAME	"bfin-sport-spi"
#define DRV_DESC	"SPI bus via the Blackfin SPORT"

MODULE_AUTHOR("Cliff Cai");
MODULE_DESCRIPTION(DRV_DESC);
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:bfin-sport-spi");

enum bfin_sport_spi_state {
	START_STATE,
	RUNNING_STATE,
	DONE_STATE,
	ERROR_STATE,
};

struct bfin_sport_spi_master_data;

struct bfin_sport_transfer_ops {
	void (*write) (struct bfin_sport_spi_master_data *);
	void (*read) (struct bfin_sport_spi_master_data *);
	void (*duplex) (struct bfin_sport_spi_master_data *);
};

struct bfin_sport_spi_master_data {
	/* Driver model hookup */
	struct device *dev;

	/* SPI framework hookup */
	struct spi_master *master;

	/* Regs base of SPI controller */
	struct sport_register __iomem *regs;
	int err_irq;

	/* Pin request list */
	u16 *pin_req;

	/* Driver message queue */
	struct workqueue_struct *workqueue;
	struct work_struct pump_messages;
	spinlock_t lock;
	struct list_head queue;
	int busy;
	bool run;

	/* Message Transfer pump */
	struct tasklet_struct pump_transfers;

	/* Current message transfer state info */
	enum bfin_sport_spi_state state;
	struct spi_message *cur_msg;
	struct spi_transfer *cur_transfer;
	struct bfin_sport_spi_slave_data *cur_chip;
	union {
		void *tx;
		u8 *tx8;
		u16 *tx16;
	};
	void *tx_end;
	union {
		void *rx;
		u8 *rx8;
		u16 *rx16;
	};
	void *rx_end;

	int cs_change;
	struct bfin_sport_transfer_ops *ops;
};

struct bfin_sport_spi_slave_data {
	u16 ctl_reg;
	u16 baud;
	u16 cs_chg_udelay;	/* Some devices require > 255usec delay */
	u32 cs_gpio;
	u16 idle_tx_val;
	struct bfin_sport_transfer_ops *ops;
};

static void
bfin_sport_spi_enable(struct bfin_sport_spi_master_data *drv_data)
{
	bfin_write_or(&drv_data->regs->tcr1, TSPEN);
	bfin_write_or(&drv_data->regs->rcr1, TSPEN);
	SSYNC();
}

static void
bfin_sport_spi_disable(struct bfin_sport_spi_master_data *drv_data)
{
	bfin_write_and(&drv_data->regs->tcr1, ~TSPEN);
	bfin_write_and(&drv_data->regs->rcr1, ~TSPEN);
	SSYNC();
}

/* Caculate the SPI_BAUD register value based on input HZ */
static u16
bfin_sport_hz_to_spi_baud(u32 speed_hz)
{
	u_long clk, sclk = get_sclk();
	int div = (sclk / (2 * speed_hz)) - 1;

	if (div < 0)
		div = 0;

	clk = sclk / (2 * (div + 1));

	if (clk > speed_hz)
		div++;

	return div;
}

/* Chip select operation functions for cs_change flag */
static void
bfin_sport_spi_cs_active(struct bfin_sport_spi_slave_data *chip)
{
	gpio_direction_output(chip->cs_gpio, 0);
}

static void
bfin_sport_spi_cs_deactive(struct bfin_sport_spi_slave_data *chip)
{
	gpio_direction_output(chip->cs_gpio, 1);
	/* Move delay here for consistency */
	if (chip->cs_chg_udelay)
		udelay(chip->cs_chg_udelay);
}

static void
bfin_sport_spi_stat_poll_complete(struct bfin_sport_spi_master_data *drv_data)
{
	unsigned long timeout = jiffies + HZ;
	while (!(bfin_read(&drv_data->regs->stat) & RXNE)) {
		if (!time_before(jiffies, timeout))
			break;
	}
}

static void
bfin_sport_spi_u8_writer(struct bfin_sport_spi_master_data *drv_data)
{
	u16 dummy;

	while (drv_data->tx < drv_data->tx_end) {
		bfin_write(&drv_data->regs->tx16, *drv_data->tx8++);
		bfin_sport_spi_stat_poll_complete(drv_data);
		dummy = bfin_read(&drv_data->regs->rx16);
	}
}

static void
bfin_sport_spi_u8_reader(struct bfin_sport_spi_master_data *drv_data)
{
	u16 tx_val = drv_data->cur_chip->idle_tx_val;

	while (drv_data->rx < drv_data->rx_end) {
		bfin_write(&drv_data->regs->tx16, tx_val);
		bfin_sport_spi_stat_poll_complete(drv_data);
		*drv_data->rx8++ = bfin_read(&drv_data->regs->rx16);
	}
}

static void
bfin_sport_spi_u8_duplex(struct bfin_sport_spi_master_data *drv_data)
{
	while (drv_data->rx < drv_data->rx_end) {
		bfin_write(&drv_data->regs->tx16, *drv_data->tx8++);
		bfin_sport_spi_stat_poll_complete(drv_data);
		*drv_data->rx8++ = bfin_read(&drv_data->regs->rx16);
	}
}

static struct bfin_sport_transfer_ops bfin_sport_transfer_ops_u8 = {
	.write  = bfin_sport_spi_u8_writer,
	.read   = bfin_sport_spi_u8_reader,
	.duplex = bfin_sport_spi_u8_duplex,
};

static void
bfin_sport_spi_u16_writer(struct bfin_sport_spi_master_data *drv_data)
{
	u16 dummy;

	while (drv_data->tx < drv_data->tx_end) {
		bfin_write(&drv_data->regs->tx16, *drv_data->tx16++);
		bfin_sport_spi_stat_poll_complete(drv_data);
		dummy = bfin_read(&drv_data->regs->rx16);
	}
}

static void
bfin_sport_spi_u16_reader(struct bfin_sport_spi_master_data *drv_data)
{
	u16 tx_val = drv_data->cur_chip->idle_tx_val;

	while (drv_data->rx < drv_data->rx_end) {
		bfin_write(&drv_data->regs->tx16, tx_val);
		bfin_sport_spi_stat_poll_complete(drv_data);
		*drv_data->rx16++ = bfin_read(&drv_data->regs->rx16);
	}
}

static void
bfin_sport_spi_u16_duplex(struct bfin_sport_spi_master_data *drv_data)
{
	while (drv_data->rx < drv_data->rx_end) {
		bfin_write(&drv_data->regs->tx16, *drv_data->tx16++);
		bfin_sport_spi_stat_poll_complete(drv_data);
		*drv_data->rx16++ = bfin_read(&drv_data->regs->rx16);
	}
}

static struct bfin_sport_transfer_ops bfin_sport_transfer_ops_u16 = {
	.write  = bfin_sport_spi_u16_writer,
	.read   = bfin_sport_spi_u16_reader,
	.duplex = bfin_sport_spi_u16_duplex,
};

/* stop controller and re-config current chip */
static void
bfin_sport_spi_restore_state(struct bfin_sport_spi_master_data *drv_data)
{
	struct bfin_sport_spi_slave_data *chip = drv_data->cur_chip;
	unsigned int bits = (drv_data->ops == &bfin_sport_transfer_ops_u8 ? 7 : 15);

	bfin_sport_spi_disable(drv_data);
	dev_dbg(drv_data->dev, "restoring spi ctl state\n");

	bfin_write(&drv_data->regs->tcr1, chip->ctl_reg);
	bfin_write(&drv_data->regs->tcr2, bits);
	bfin_write(&drv_data->regs->tclkdiv, chip->baud);
	bfin_write(&drv_data->regs->tfsdiv, bits);
	SSYNC();

	bfin_write(&drv_data->regs->rcr1, chip->ctl_reg & ~(ITCLK | ITFS));
	bfin_write(&drv_data->regs->rcr2, bits);
	SSYNC();

	bfin_sport_spi_cs_active(chip);
}

/* test if there is more transfer to be done */
static enum bfin_sport_spi_state
bfin_sport_spi_next_transfer(struct bfin_sport_spi_master_data *drv_data)
{
	struct spi_message *msg = drv_data->cur_msg;
	struct spi_transfer *trans = drv_data->cur_transfer;

	/* Move to next transfer */
	if (trans->transfer_list.next != &msg->transfers) {
		drv_data->cur_transfer =
		    list_entry(trans->transfer_list.next,
			       struct spi_transfer, transfer_list);
		return RUNNING_STATE;
	}

	return DONE_STATE;
}

/*
 * caller already set message->status;
 * dma and pio irqs are blocked give finished message back
 */
static void
bfin_sport_spi_giveback(struct bfin_sport_spi_master_data *drv_data)
{
	struct bfin_sport_spi_slave_data *chip = drv_data->cur_chip;
	unsigned long flags;
	struct spi_message *msg;

	spin_lock_irqsave(&drv_data->lock, flags);
	msg = drv_data->cur_msg;
	drv_data->state = START_STATE;
	drv_data->cur_msg = NULL;
	drv_data->cur_transfer = NULL;
	drv_data->cur_chip = NULL;
	queue_work(drv_data->workqueue, &drv_data->pump_messages);
	spin_unlock_irqrestore(&drv_data->lock, flags);

	if (!drv_data->cs_change)
		bfin_sport_spi_cs_deactive(chip);

	if (msg->complete)
		msg->complete(msg->context);
}

static irqreturn_t
sport_err_handler(int irq, void *dev_id)
{
	struct bfin_sport_spi_master_data *drv_data = dev_id;
	u16 status;

	dev_dbg(drv_data->dev, "%s enter\n", __func__);
	status = bfin_read(&drv_data->regs->stat) & (TOVF | TUVF | ROVF | RUVF);

	if (status) {
		bfin_write(&drv_data->regs->stat, status);
		SSYNC();

		bfin_sport_spi_disable(drv_data);
		dev_err(drv_data->dev, "status error:%s%s%s%s\n",
			status & TOVF ? " TOVF" : "",
			status & TUVF ? " TUVF" : "",
			status & ROVF ? " ROVF" : "",
			status & RUVF ? " RUVF" : "");
	}

	return IRQ_HANDLED;
}

static void
bfin_sport_spi_pump_transfers(unsigned long data)
{
	struct bfin_sport_spi_master_data *drv_data = (void *)data;
	struct spi_message *message = NULL;
	struct spi_transfer *transfer = NULL;
	struct spi_transfer *previous = NULL;
	struct bfin_sport_spi_slave_data *chip = NULL;
	unsigned int bits_per_word;
	u32 tranf_success = 1;
	u32 transfer_speed;
	u8 full_duplex = 0;

	/* Get current state information */
	message = drv_data->cur_msg;
	transfer = drv_data->cur_transfer;
	chip = drv_data->cur_chip;

	if (transfer->speed_hz)
		transfer_speed = bfin_sport_hz_to_spi_baud(transfer->speed_hz);
	else
		transfer_speed = chip->baud;
	bfin_write(&drv_data->regs->tclkdiv, transfer_speed);
	SSYNC();

	/*
	 * if msg is error or done, report it back using complete() callback
	 */

	 /* Handle for abort */
	if (drv_data->state == ERROR_STATE) {
		dev_dbg(drv_data->dev, "transfer: we've hit an error\n");
		message->status = -EIO;
		bfin_sport_spi_giveback(drv_data);
		return;
	}

	/* Handle end of message */
	if (drv_data->state == DONE_STATE) {
		dev_dbg(drv_data->dev, "transfer: all done!\n");
		message->status = 0;
		bfin_sport_spi_giveback(drv_data);
		return;
	}

	/* Delay if requested at end of transfer */
	if (drv_data->state == RUNNING_STATE) {
		dev_dbg(drv_data->dev, "transfer: still running ...\n");
		previous = list_entry(transfer->transfer_list.prev,
				      struct spi_transfer, transfer_list);
		if (previous->delay_usecs)
			udelay(previous->delay_usecs);
	}

	if (transfer->len == 0) {
		/* Move to next transfer of this msg */
		drv_data->state = bfin_sport_spi_next_transfer(drv_data);
		/* Schedule next transfer tasklet */
		tasklet_schedule(&drv_data->pump_transfers);
	}

	if (transfer->tx_buf != NULL) {
		drv_data->tx = (void *)transfer->tx_buf;
		drv_data->tx_end = drv_data->tx + transfer->len;
		dev_dbg(drv_data->dev, "tx_buf is %p, tx_end is %p\n",
			transfer->tx_buf, drv_data->tx_end);
	} else
		drv_data->tx = NULL;

	if (transfer->rx_buf != NULL) {
		full_duplex = transfer->tx_buf != NULL;
		drv_data->rx = transfer->rx_buf;
		drv_data->rx_end = drv_data->rx + transfer->len;
		dev_dbg(drv_data->dev, "rx_buf is %p, rx_end is %p\n",
			transfer->rx_buf, drv_data->rx_end);
	} else
		drv_data->rx = NULL;

	drv_data->cs_change = transfer->cs_change;

	/* Bits per word setup */
	bits_per_word = transfer->bits_per_word ? : message->spi->bits_per_word;
	if (bits_per_word == 8)
		drv_data->ops = &bfin_sport_transfer_ops_u8;
	else
		drv_data->ops = &bfin_sport_transfer_ops_u16;

	drv_data->state = RUNNING_STATE;

	if (drv_data->cs_change)
		bfin_sport_spi_cs_active(chip);

	dev_dbg(drv_data->dev,
		"now pumping a transfer: width is %d, len is %d\n",
		bits_per_word, transfer->len);

	/* PIO mode write then read */
	dev_dbg(drv_data->dev, "doing IO transfer\n");

	bfin_sport_spi_enable(drv_data);
	if (full_duplex) {
		/* full duplex mode */
		BUG_ON((drv_data->tx_end - drv_data->tx) !=
		       (drv_data->rx_end - drv_data->rx));
		drv_data->ops->duplex(drv_data);

		if (drv_data->tx != drv_data->tx_end)
			tranf_success = 0;
	} else if (drv_data->tx != NULL) {
		/* write only half duplex */

		drv_data->ops->write(drv_data);

		if (drv_data->tx != drv_data->tx_end)
			tranf_success = 0;
	} else if (drv_data->rx != NULL) {
		/* read only half duplex */

		drv_data->ops->read(drv_data);
		if (drv_data->rx != drv_data->rx_end)
			tranf_success = 0;
	}
	bfin_sport_spi_disable(drv_data);

	if (!tranf_success) {
		dev_dbg(drv_data->dev, "IO write error!\n");
		drv_data->state = ERROR_STATE;
	} else {
		/* Update total byte transfered */
		message->actual_length += transfer->len;
		/* Move to next transfer of this msg */
		drv_data->state = bfin_sport_spi_next_transfer(drv_data);
		if (drv_data->cs_change)
			bfin_sport_spi_cs_deactive(chip);
	}

	/* Schedule next transfer tasklet */
	tasklet_schedule(&drv_data->pump_transfers);
}

/* pop a msg from queue and kick off real transfer */
static void
bfin_sport_spi_pump_messages(struct work_struct *work)
{
	struct bfin_sport_spi_master_data *drv_data;
	unsigned long flags;
	struct spi_message *next_msg;

	drv_data = container_of(work, struct bfin_sport_spi_master_data, pump_messages);

	/* Lock queue and check for queue work */
	spin_lock_irqsave(&drv_data->lock, flags);
	if (list_empty(&drv_data->queue) || !drv_data->run) {
		/* pumper kicked off but no work to do */
		drv_data->busy = 0;
		spin_unlock_irqrestore(&drv_data->lock, flags);
		return;
	}

	/* Make sure we are not already running a message */
	if (drv_data->cur_msg) {
		spin_unlock_irqrestore(&drv_data->lock, flags);
		return;
	}

	/* Extract head of queue */
	next_msg = list_entry(drv_data->queue.next,
		struct spi_message, queue);

	drv_data->cur_msg = next_msg;

	/* Setup the SSP using the per chip configuration */
	drv_data->cur_chip = spi_get_ctldata(drv_data->cur_msg->spi);

	list_del_init(&drv_data->cur_msg->queue);

	/* Initialize message state */
	drv_data->cur_msg->state = START_STATE;
	drv_data->cur_transfer = list_entry(drv_data->cur_msg->transfers.next,
					    struct spi_transfer, transfer_list);
	bfin_sport_spi_restore_state(drv_data);
	dev_dbg(drv_data->dev, "got a message to pump, "
		"state is set to: baud %d, cs_gpio %i, ctl 0x%x\n",
		drv_data->cur_chip->baud, drv_data->cur_chip->cs_gpio,
		drv_data->cur_chip->ctl_reg);

	dev_dbg(drv_data->dev,
		"the first transfer len is %d\n",
		drv_data->cur_transfer->len);

	/* Mark as busy and launch transfers */
	tasklet_schedule(&drv_data->pump_transfers);

	drv_data->busy = 1;
	spin_unlock_irqrestore(&drv_data->lock, flags);
}

/*
 * got a msg to transfer, queue it in drv_data->queue.
 * And kick off message pumper
 */
static int
bfin_sport_spi_transfer(struct spi_device *spi, struct spi_message *msg)
{
	struct bfin_sport_spi_master_data *drv_data = spi_master_get_devdata(spi->master);
	unsigned long flags;

	spin_lock_irqsave(&drv_data->lock, flags);

	if (!drv_data->run) {
		spin_unlock_irqrestore(&drv_data->lock, flags);
		return -ESHUTDOWN;
	}

	msg->actual_length = 0;
	msg->status = -EINPROGRESS;
	msg->state = START_STATE;

	dev_dbg(&spi->dev, "adding an msg in transfer()\n");
	list_add_tail(&msg->queue, &drv_data->queue);

	if (drv_data->run && !drv_data->busy)
		queue_work(drv_data->workqueue, &drv_data->pump_messages);

	spin_unlock_irqrestore(&drv_data->lock, flags);

	return 0;
}

/* Called every time common spi devices change state */
static int
bfin_sport_spi_setup(struct spi_device *spi)
{
	struct bfin_sport_spi_slave_data *chip, *first = NULL;
	int ret;

	/* Only alloc (or use chip_info) on first setup */
	chip = spi_get_ctldata(spi);
	if (chip == NULL) {
		struct bfin5xx_spi_chip *chip_info;

		chip = first = kzalloc(sizeof(*chip), GFP_KERNEL);
		if (!chip)
			return -ENOMEM;

		/* platform chip_info isn't required */
		chip_info = spi->controller_data;
		if (chip_info) {
			/*
			 * DITFS and TDTYPE are only thing we don't set, but
			 * they probably shouldn't be changed by people.
			 */
			if (chip_info->ctl_reg || chip_info->enable_dma) {
				ret = -EINVAL;
				dev_err(&spi->dev, "don't set ctl_reg/enable_dma fields");
				goto error;
			}
			chip->cs_chg_udelay = chip_info->cs_chg_udelay;
			chip->idle_tx_val = chip_info->idle_tx_val;
			spi->bits_per_word = chip_info->bits_per_word;
		}
	}

	if (spi->bits_per_word != 8 && spi->bits_per_word != 16) {
		ret = -EINVAL;
		goto error;
	}

	/* translate common spi framework into our register
	 * following configure contents are same for tx and rx.
	 */

	if (spi->mode & SPI_CPHA)
		chip->ctl_reg &= ~TCKFE;
	else
		chip->ctl_reg |= TCKFE;

	if (spi->mode & SPI_LSB_FIRST)
		chip->ctl_reg |= TLSBIT;
	else
		chip->ctl_reg &= ~TLSBIT;

	/* Sport in master mode */
	chip->ctl_reg |= ITCLK | ITFS | TFSR | LATFS | LTFS;

	chip->baud = bfin_sport_hz_to_spi_baud(spi->max_speed_hz);

	chip->cs_gpio = spi->chip_select;
	ret = gpio_request(chip->cs_gpio, spi->modalias);
	if (ret)
		goto error;

	dev_dbg(&spi->dev, "setup spi chip %s, width is %d\n",
			spi->modalias, spi->bits_per_word);
	dev_dbg(&spi->dev, "ctl_reg is 0x%x, GPIO is %i\n",
			chip->ctl_reg, spi->chip_select);

	spi_set_ctldata(spi, chip);

	bfin_sport_spi_cs_deactive(chip);

	return ret;

 error:
	kfree(first);
	return ret;
}

/*
 * callback for spi framework.
 * clean driver specific data
 */
static void
bfin_sport_spi_cleanup(struct spi_device *spi)
{
	struct bfin_sport_spi_slave_data *chip = spi_get_ctldata(spi);

	if (!chip)
		return;

	gpio_free(chip->cs_gpio);

	kfree(chip);
}

static int
bfin_sport_spi_init_queue(struct bfin_sport_spi_master_data *drv_data)
{
	INIT_LIST_HEAD(&drv_data->queue);
	spin_lock_init(&drv_data->lock);

	drv_data->run = false;
	drv_data->busy = 0;

	/* init transfer tasklet */
	tasklet_init(&drv_data->pump_transfers,
		     bfin_sport_spi_pump_transfers, (unsigned long)drv_data);

	/* init messages workqueue */
	INIT_WORK(&drv_data->pump_messages, bfin_sport_spi_pump_messages);
	drv_data->workqueue =
	    create_singlethread_workqueue(dev_name(drv_data->master->dev.parent));
	if (drv_data->workqueue == NULL)
		return -EBUSY;

	return 0;
}

static int
bfin_sport_spi_start_queue(struct bfin_sport_spi_master_data *drv_data)
{
	unsigned long flags;

	spin_lock_irqsave(&drv_data->lock, flags);

	if (drv_data->run || drv_data->busy) {
		spin_unlock_irqrestore(&drv_data->lock, flags);
		return -EBUSY;
	}

	drv_data->run = true;
	drv_data->cur_msg = NULL;
	drv_data->cur_transfer = NULL;
	drv_data->cur_chip = NULL;
	spin_unlock_irqrestore(&drv_data->lock, flags);

	queue_work(drv_data->workqueue, &drv_data->pump_messages);

	return 0;
}

static inline int
bfin_sport_spi_stop_queue(struct bfin_sport_spi_master_data *drv_data)
{
	unsigned long flags;
	unsigned limit = 500;
	int status = 0;

	spin_lock_irqsave(&drv_data->lock, flags);

	/*
	 * This is a bit lame, but is optimized for the common execution path.
	 * A wait_queue on the drv_data->busy could be used, but then the common
	 * execution path (pump_messages) would be required to call wake_up or
	 * friends on every SPI message. Do this instead
	 */
	drv_data->run = false;
	while (!list_empty(&drv_data->queue) && drv_data->busy && limit--) {
		spin_unlock_irqrestore(&drv_data->lock, flags);
		msleep(10);
		spin_lock_irqsave(&drv_data->lock, flags);
	}

	if (!list_empty(&drv_data->queue) || drv_data->busy)
		status = -EBUSY;

	spin_unlock_irqrestore(&drv_data->lock, flags);

	return status;
}

static inline int
bfin_sport_spi_destroy_queue(struct bfin_sport_spi_master_data *drv_data)
{
	int status;

	status = bfin_sport_spi_stop_queue(drv_data);
	if (status)
		return status;

	destroy_workqueue(drv_data->workqueue);

	return 0;
}

static int __devinit
bfin_sport_spi_probe(struct platform_device *pdev)
{
	struct device *dev = &pdev->dev;
	struct bfin5xx_spi_master *platform_info;
	struct spi_master *master;
	struct resource *res, *ires;
	struct bfin_sport_spi_master_data *drv_data;
	int status;

	platform_info = dev->platform_data;

	/* Allocate master with space for drv_data */
	master = spi_alloc_master(dev, sizeof(*master) + 16);
	if (!master) {
		dev_err(dev, "cannot alloc spi_master\n");
		return -ENOMEM;
	}

	drv_data = spi_master_get_devdata(master);
	drv_data->master = master;
	drv_data->dev = dev;
	drv_data->pin_req = platform_info->pin_req;

	master->mode_bits = SPI_CPOL | SPI_CPHA | SPI_LSB_FIRST;
	master->bus_num = pdev->id;
	master->num_chipselect = platform_info->num_chipselect;
	master->cleanup = bfin_sport_spi_cleanup;
	master->setup = bfin_sport_spi_setup;
	master->transfer = bfin_sport_spi_transfer;

	/* Find and map our resources */
	res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
	if (res == NULL) {
		dev_err(dev, "cannot get IORESOURCE_MEM\n");
		status = -ENOENT;
		goto out_error_get_res;
	}

	drv_data->regs = ioremap(res->start, resource_size(res));
	if (drv_data->regs == NULL) {
		dev_err(dev, "cannot map registers\n");
		status = -ENXIO;
		goto out_error_ioremap;
	}

	ires = platform_get_resource(pdev, IORESOURCE_IRQ, 0);
	if (!ires) {
		dev_err(dev, "cannot get IORESOURCE_IRQ\n");
		status = -ENODEV;
		goto out_error_get_ires;
	}
	drv_data->err_irq = ires->start;

	/* Initial and start queue */
	status = bfin_sport_spi_init_queue(drv_data);
	if (status) {
		dev_err(dev, "problem initializing queue\n");
		goto out_error_queue_alloc;
	}

	status = bfin_sport_spi_start_queue(drv_data);
	if (status) {
		dev_err(dev, "problem starting queue\n");
		goto out_error_queue_alloc;
	}

	status = request_irq(drv_data->err_irq, sport_err_handler,
		0, "sport_spi_err", drv_data);
	if (status) {
		dev_err(dev, "unable to request sport err irq\n");
		goto out_error_irq;
	}

	status = peripheral_request_list(drv_data->pin_req, DRV_NAME);
	if (status) {
		dev_err(dev, "requesting peripherals failed\n");
		goto out_error_peripheral;
	}

	/* Register with the SPI framework */
	platform_set_drvdata(pdev, drv_data);
	status = spi_register_master(master);
	if (status) {
		dev_err(dev, "problem registering spi master\n");
		goto out_error_master;
	}

	dev_info(dev, "%s, regs_base@%p\n", DRV_DESC, drv_data->regs);
	return 0;

 out_error_master:
	peripheral_free_list(drv_data->pin_req);
 out_error_peripheral:
	free_irq(drv_data->err_irq, drv_data);
 out_error_irq:
 out_error_queue_alloc:
	bfin_sport_spi_destroy_queue(drv_data);
 out_error_get_ires:
	iounmap(drv_data->regs);
 out_error_ioremap:
 out_error_get_res:
	spi_master_put(master);

	return status;
}

/* stop hardware and remove the driver */
static int __devexit
bfin_sport_spi_remove(struct platform_device *pdev)
{
	struct bfin_sport_spi_master_data *drv_data = platform_get_drvdata(pdev);
	int status = 0;

	if (!drv_data)
		return 0;

	/* Remove the queue */
	status = bfin_sport_spi_destroy_queue(drv_data);
	if (status)
		return status;

	/* Disable the SSP at the peripheral and SOC level */
	bfin_sport_spi_disable(drv_data);

	/* Disconnect from the SPI framework */
	spi_unregister_master(drv_data->master);

	peripheral_free_list(drv_data->pin_req);

	/* Prevent double remove */
	platform_set_drvdata(pdev, NULL);

	return 0;
}

#ifdef CONFIG_PM
static int
bfin_sport_spi_suspend(struct platform_device *pdev, pm_message_t state)
{
	struct bfin_sport_spi_master_data *drv_data = platform_get_drvdata(pdev);
	int status;

	status = bfin_sport_spi_stop_queue(drv_data);
	if (status)
		return status;

	/* stop hardware */
	bfin_sport_spi_disable(drv_data);

	return status;
}

static int
bfin_sport_spi_resume(struct platform_device *pdev)
{
	struct bfin_sport_spi_master_data *drv_data = platform_get_drvdata(pdev);
	int status;

	/* Enable the SPI interface */
	bfin_sport_spi_enable(drv_data);

	/* Start the queue running */
	status = bfin_sport_spi_start_queue(drv_data);
	if (status)
		dev_err(drv_data->dev, "problem resuming queue\n");

	return status;
}
#else
# define bfin_sport_spi_suspend NULL
# define bfin_sport_spi_resume  NULL
#endif

static struct platform_driver bfin_sport_spi_driver = {
	.driver	= {
		.name = DRV_NAME,
		.owner = THIS_MODULE,
	},
	.probe   = bfin_sport_spi_probe,
	.remove  = __devexit_p(bfin_sport_spi_remove),
	.suspend = bfin_sport_spi_suspend,
	.resume  = bfin_sport_spi_resume,
};

static int __init bfin_sport_spi_init(void)
{
	return platform_driver_register(&bfin_sport_spi_driver);
}
module_init(bfin_sport_spi_init);

static void __exit bfin_sport_spi_exit(void)
{
	platform_driver_unregister(&bfin_sport_spi_driver);
}
module_exit(bfin_sport_spi_exit);


text:
<?xml version="1.0" encoding="utf-8"?>
<linker>
       <assembly fullname="mscorlib">
	       	<namespace fullname="System.Collections.Generic" preserve="all"/>
       </assembly>
</linker>

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" ?>
<!DOCTYPE FTCS SYSTEM "futuretense_cs.dtd">

<FTCS Version="1.1">
<!-- OpenMarket/Xcelerate/AssetType/Page/LoadSiteTreeNodes
-
- INPUT
-
- OUTPUT
-
-->

<CALLELEMENT NAME="OpenMarket/Gator/UIFramework/GetDefaultNodeBehavior" />

<!-- Load operation -->
<SETVAR NAME="loadexecuted" VALUE="false"/>

<!-- We arrive here if we are displaying the contents of the 'placed' or 'unplaced' node in the tree -->
<if COND="Variables.loadpages=Placed">
<then>
  <IF cond="Variables.showParents=true">
  <THEN>
	   <CALLELEMENT NAME="OpenMarket/Xcelerate/AssetType/Page/PlacedPageParents"/>
  </THEN>
  <ELSE>
	   <CALLELEMENT NAME="OpenMarket/Xcelerate/AssetType/Page/PlacedPageChildren"/>
  </ELSE>
  </IF>
</then>
</if>

<!--  Is it Unplaced Page Query  -->
<if COND="Variables.loadpages=Unplaced">
<then>
 <IF cond="Variables.showParents=true">
 <THEN>
	   <CALLELEMENT NAME="OpenMarket/Xcelerate/AssetType/Page/UnplacedPageParents"/>
 </THEN>
 <ELSE>
	   <CALLELEMENT NAME="OpenMarket/Xcelerate/AssetType/Page/UnplacedPageChildren"/>
 </ELSE>
 </IF>
</then>
</if>

<!--  Has the load site nodes request been executed -->
<if COND="Variables.loadexecuted=false">
<then>
 	<SETVAR NAME="assetid" VALUE="Variables.loadpages"/>

	<IF cond="Variables.showParents=true">
 	<THEN>
	   <CALLELEMENT NAME="OpenMarket/Xcelerate/AssetType/Page/PageParents"/>
 	</THEN>
 	<ELSE>
	   <CALLELEMENT NAME="OpenMarket/Xcelerate/AssetType/Page/PageChildren"/>
 	</ELSE>
 	</IF>
</then>
</if>

</FTCS>


text:
class ExternalGPS {
public:
    // Constructor / Destructor
    ExternalGPS(void);
    virtual ~ExternalGPS();
    int quadID;
    void set_values(int id, char myip[100], char serverip[100]);
    float g_x,g_y,g_z,g_qx,g_qy,g_qz,g_qw;

    int init(void);
    void loop(void);

private:

    char szMyIPAddress[128];
    char szServerIPAddress[128];
    int DataSocket;

    char  szData[20000];
    int addr_len;
    struct sockaddr_in TheirAddress;

    // Analyse the data
    void Unpack(char*,int);

};

#endif


text:
"""Selectors module.

This module allows high-level and efficient I/O multiplexing, built upon the
`select` module primitives.

The following code adapted from trollius.selectors.
"""

from abc import ABCMeta, abstractmethod
from collections import namedtuple, Mapping
from errno import EINTR
import math
import select
import sys

import six

def _wrap_error(exc, mapping, key):
    if key not in mapping:
        return
    new_err_cls = mapping[key]
    new_err = new_err_cls(*exc.args)

    # raise a new exception with the original traceback
    if hasattr(exc, '__traceback__'):
        traceback = exc.__traceback__
    else:
        traceback = sys.exc_info()[2]
    six.reraise(new_err_cls, new_err, traceback)

# generic events, that must be mapped to implementation-specific ones
EVENT_READ = (1 << 0)
EVENT_WRITE = (1 << 1)

def _fileobj_to_fd(fileobj):
    """Return a file descriptor from a file object.

    Parameters:
    fileobj -- file object or file descriptor

    Returns:
    corresponding file descriptor

    Raises:
    ValueError if the object is invalid
    """
    if isinstance(fileobj, six.integer_types):
        fd = fileobj
    else:
        try:
            fd = int(fileobj.fileno())
        except (AttributeError, TypeError, ValueError):
            raise ValueError("Invalid file object: "
                             "{0!r}".format(fileobj))
    if fd < 0:
        raise ValueError("Invalid file descriptor: {0}".format(fd))
    return fd

SelectorKey = namedtuple('SelectorKey', ['fileobj', 'fd', 'events', 'data'])
"""Object used to associate a file object to its backing file descriptor,
selected event mask and attached data."""

class _SelectorMapping(Mapping):
    """Mapping of file objects to selector keys."""

    def __init__(self, selector):
        self._selector = selector

    def __len__(self):
        return len(self._selector._fd_to_key)

    def __getitem__(self, fileobj):
        try:
            fd = self._selector._fileobj_lookup(fileobj)
            return self._selector._fd_to_key[fd]
        except KeyError:
            raise KeyError("{0!r} is not registered".format(fileobj))

    def __iter__(self):
        return iter(self._selector._fd_to_key)

class BaseSelector(six.with_metaclass(ABCMeta)):
    """Selector abstract base class.

    A selector supports registering file objects to be monitored for specific
    I/O events.

    A file object is a file descriptor or any object with a `fileno()` method.
    An arbitrary object can be attached to the file object, which can be used
    for example to store context information, a callback, etc.

    A selector can use various implementations (select(), poll(), epoll()...)
    depending on the platform. The default `Selector` class uses the most
    efficient implementation on the current platform.
    """

    @abstractmethod
    def register(self, fileobj, events, data=None):
        """Register a file object.

        Parameters:
        fileobj -- file object or file descriptor
        events  -- events to monitor (bitwise mask of EVENT_READ|EVENT_WRITE)
        data    -- attached data

        Returns:
        SelectorKey instance

        Raises:
        ValueError if events is invalid
        KeyError if fileobj is already registered
        OSError if fileobj is closed or otherwise is unacceptable to
                the underlying system call (if a system call is made)

        Note:
        OSError may or may not be raised
        """
        raise NotImplementedError

    @abstractmethod
    def unregister(self, fileobj):
        """Unregister a file object.

        Parameters:
        fileobj -- file object or file descriptor

        Returns:
        SelectorKey instance

        Raises:
        KeyError if fileobj is not registered

        Note:
        If fileobj is registered but has since been closed this does
        *not* raise OSError (even if the wrapped syscall does)
        """
        raise NotImplementedError

    def modify(self, fileobj, events, data=None):
        """Change a registered file object monitored events or attached data.

        Parameters:
        fileobj -- file object or file descriptor
        events  -- events to monitor (bitwise mask of EVENT_READ|EVENT_WRITE)
        data    -- attached data

        Returns:
        SelectorKey instance

        Raises:
        Anything that unregister() or register() raises
        """
        self.unregister(fileobj)
        return self.register(fileobj, events, data)

    @abstractmethod
    def select(self, timeout=None):
        """Perform the actual selection, until some monitored file objects are
        ready or a timeout expires.

        Parameters:
        timeout -- if timeout > 0, this specifies the maximum wait time, in
                   seconds
                   if timeout <= 0, the select() call won't block, and will
                   report the currently ready file objects
                   if timeout is None, select() will block until a monitored
                   file object becomes ready

        Returns:
        list of (key, events) for ready file objects
        `events` is a bitwise mask of EVENT_READ|EVENT_WRITE
        """
        raise NotImplementedError

    def close(self):
        """Close the selector.

        This must be called to make sure that any underlying resource is freed.
        """
        pass

    def get_key(self, fileobj):
        """Return the key associated to a registered file object.

        Returns:
        SelectorKey for this file object
        """
        mapping = self.get_map()
        if mapping is None:
            raise RuntimeError('Selector is closed')
        try:
            return mapping[fileobj]
        except KeyError:
            raise KeyError("{0!r} is not registered".format(fileobj))

    @abstractmethod
    def get_map(self):
        """Return a mapping of file objects to selector keys."""
        raise NotImplementedError

    def __enter__(self):
        return self

    def __exit__(self, *args):
        self.close()

class _BaseSelectorImpl(BaseSelector):
    """Base selector implementation."""

    def __init__(self):
        # this maps file descriptors to keys
        self._fd_to_key = {}
        # read-only mapping returned by get_map()
        self._map = _SelectorMapping(self)

    def _fileobj_lookup(self, fileobj):
        """Return a file descriptor from a file object.

        This wraps _fileobj_to_fd() to do an exhaustive search in case
        the object is invalid but we still have it in our map.  This
        is used by unregister() so we can unregister an object that
        was previously registered even if it is closed.  It is also
        used by _SelectorMapping.
        """
        try:
            return _fileobj_to_fd(fileobj)
        except ValueError:
            # Do an exhaustive search.
            for key in self._fd_to_key.values():
                if key.fileobj is fileobj:
                    return key.fd
            # Raise ValueError after all.
            raise

    def register(self, fileobj, events, data=None):
        if (not events) or (events & ~(EVENT_READ | EVENT_WRITE)):
            raise ValueError("Invalid events: {0!r}".format(events))

        key = SelectorKey(fileobj, self._fileobj_lookup(fileobj), events, data)

        if key.fd in self._fd_to_key:
            raise KeyError("{0!r} (FD {1}) is already registered"
                           .format(fileobj, key.fd))

        self._fd_to_key[key.fd] = key
        return key

    def unregister(self, fileobj):
        try:
            key = self._fd_to_key.pop(self._fileobj_lookup(fileobj))
        except KeyError:
            raise KeyError("{0!r} is not registered".format(fileobj))
        return key

    def modify(self, fileobj, events, data=None):
        # TODO: Subclasses can probably optimize this even further.
        try:
            key = self._fd_to_key[self._fileobj_lookup(fileobj)]
        except KeyError:
            raise KeyError("{0!r} is not registered".format(fileobj))
        if events != key.events:
            self.unregister(fileobj)
            key = self.register(fileobj, events, data)
        elif data != key.data:
            # Use a shortcut to update the data.
            key = key._replace(data=data)
            self._fd_to_key[key.fd] = key
        return key

    def close(self):
        self._fd_to_key.clear()
        self._map = None

    def get_map(self):
        return self._map

    def _key_from_fd(self, fd):
        """Return the key associated to a given file descriptor.

        Parameters:
        fd -- file descriptor

        Returns:
        corresponding key, or None if not found
        """
        try:
            return self._fd_to_key[fd]
        except KeyError:
            return None

class SelectSelector(_BaseSelectorImpl):
    """Select-based selector."""

    def __init__(self):
        super(SelectSelector, self).__init__()
        self._readers = set()
        self._writers = set()

    def register(self, fileobj, events, data=None):
        key = super(SelectSelector, self).register(fileobj, events, data)
        if events & EVENT_READ:
            self._readers.add(key.fd)
        if events & EVENT_WRITE:
            self._writers.add(key.fd)
        return key

    def unregister(self, fileobj):
        key = super(SelectSelector, self).unregister(fileobj)
        self._readers.discard(key.fd)
        self._writers.discard(key.fd)
        return key

    if sys.platform == 'win32':
        def _select(self, r, w, _, timeout=None):
            r, w, x = select.select(r, w, w, timeout)
            return r, w + x, []
    else:
        _select = select.select

    def select(self, timeout=None):
        timeout = None if timeout is None else max(timeout, 0)
        ready = []
        try:
            r, w, _ = self._select(self._readers, self._writers, [], timeout)
        except select.error as exc:
            if exc.args[0] == EINTR:
                return ready
            else:
                raise
        r = set(r)
        w = set(w)
        for fd in r | w:
            events = 0
            if fd in r:
                events |= EVENT_READ
            if fd in w:
                events |= EVENT_WRITE

            key = self._key_from_fd(fd)
            if key:
                ready.append((key, events & key.events))
        return ready

if hasattr(select, 'poll'):

    class PollSelector(_BaseSelectorImpl):
        """Poll-based selector."""

        def __init__(self):
            super(PollSelector, self).__init__()
            self._poll = select.poll()

        def register(self, fileobj, events, data=None):
            key = super(PollSelector, self).register(fileobj, events, data)
            poll_events = 0
            if events & EVENT_READ:
                poll_events |= select.POLLIN
            if events & EVENT_WRITE:
                poll_events |= select.POLLOUT
            self._poll.register(key.fd, poll_events)
            return key

        def unregister(self, fileobj):
            key = super(PollSelector, self).unregister(fileobj)
            self._poll.unregister(key.fd)
            return key

        def select(self, timeout=None):
            if timeout is None:
                timeout = None
            elif timeout <= 0:
                timeout = 0
            else:
                # poll() has a resolution of 1 millisecond, round away from
                # zero to wait *at least* timeout seconds.
                timeout = int(math.ceil(timeout * 1e3))
            ready = []
            try:
                fd_event_list = self._poll.poll(timeout)
            except select.error as exc:
                if exc.args[0] == EINTR:
                    return ready
                else:
                    raise
            for fd, event in fd_event_list:
                events = 0
                if event & ~select.POLLIN:
                    events |= EVENT_WRITE
                if event & ~select.POLLOUT:
                    events |= EVENT_READ

                key = self._key_from_fd(fd)
                if key:
                    ready.append((key, events & key.events))
            return ready

if hasattr(select, 'epoll'):

    class EpollSelector(_BaseSelectorImpl):
        """Epoll-based selector."""

        def __init__(self):
            super(EpollSelector, self).__init__()
            self._epoll = select.epoll()

        def fileno(self):
            return self._epoll.fileno()

        def register(self, fileobj, events, data=None):
            key = super(EpollSelector, self).register(fileobj, events, data)
            epoll_events = 0
            if events & EVENT_READ:
                epoll_events |= select.EPOLLIN
            if events & EVENT_WRITE:
                epoll_events |= select.EPOLLOUT
            self._epoll.register(key.fd, epoll_events)
            return key

        def unregister(self, fileobj):
            key = super(EpollSelector, self).unregister(fileobj)
            try:
                self._epoll.unregister(key.fd)
            except IOError:
                # This can happen if the FD was closed since it
                # was registered.
                pass
            return key

        def select(self, timeout=None):
            if timeout is None:
                timeout = -1
            elif timeout <= 0:
                timeout = 0
            else:
                # epoll_wait() has a resolution of 1 millisecond, round away
                # from zero to wait *at least* timeout seconds.
                timeout = math.ceil(timeout * 1e3) * 1e-3

            # epoll_wait() expects `maxevents` to be greater than zero;
            # we want to make sure that `select()` can be called when no
            # FD is registered.
            max_ev = max(len(self._fd_to_key), 1)

            ready = []
            try:
                fd_event_list = self._epoll.poll(timeout, max_ev)
            except IOError as exc:
                if exc.errno == EINTR:
                    return ready
                else:
                    raise
            for fd, event in fd_event_list:
                events = 0
                if event & ~select.EPOLLIN:
                    events |= EVENT_WRITE
                if event & ~select.EPOLLOUT:
                    events |= EVENT_READ

                key = self._key_from_fd(fd)
                if key:
                    ready.append((key, events & key.events))
            return ready

        def close(self):
            self._epoll.close()
            super(EpollSelector, self).close()

if hasattr(select, 'devpoll'):

    class DevpollSelector(_BaseSelectorImpl):
        """Solaris /dev/poll selector."""

        def __init__(self):
            super(DevpollSelector, self).__init__()
            self._devpoll = select.devpoll()

        def fileno(self):
            return self._devpoll.fileno()

        def register(self, fileobj, events, data=None):
            key = super(DevpollSelector, self).register(fileobj, events, data)
            poll_events = 0
            if events & EVENT_READ:
                poll_events |= select.POLLIN
            if events & EVENT_WRITE:
                poll_events |= select.POLLOUT
            self._devpoll.register(key.fd, poll_events)
            return key

        def unregister(self, fileobj):
            key = super(DevpollSelector, self).unregister(fileobj)
            self._devpoll.unregister(key.fd)
            return key

        def select(self, timeout=None):
            if timeout is None:
                timeout = None
            elif timeout <= 0:
                timeout = 0
            else:
                # devpoll() has a resolution of 1 millisecond, round away from
                # zero to wait *at least* timeout seconds.
                timeout = math.ceil(timeout * 1e3)
            ready = []
            try:
                fd_event_list = self._devpoll.poll(timeout)
            except OSError as exc:
                if exc.errno == EINTR:
                    return ready
                else:
                    raise
            for fd, event in fd_event_list:
                events = 0
                if event & ~select.POLLIN:
                    events |= EVENT_WRITE
                if event & ~select.POLLOUT:
                    events |= EVENT_READ

                key = self._key_from_fd(fd)
                if key:
                    ready.append((key, events & key.events))
            return ready

        def close(self):
            self._devpoll.close()
            super(DevpollSelector, self).close()

if hasattr(select, 'kqueue'):

    class KqueueSelector(_BaseSelectorImpl):
        """Kqueue-based selector."""

        def __init__(self):
            super(KqueueSelector, self).__init__()
            self._kqueue = select.kqueue()

        def fileno(self):
            return self._kqueue.fileno()

        def register(self, fileobj, events, data=None):
            key = super(KqueueSelector, self).register(fileobj, events, data)
            if events & EVENT_READ:
                kev = select.kevent(key.fd, select.KQ_FILTER_READ,
                                    select.KQ_EV_ADD)
                self._kqueue.control([kev], 0, 0)
            if events & EVENT_WRITE:
                kev = select.kevent(key.fd, select.KQ_FILTER_WRITE,
                                    select.KQ_EV_ADD)
                self._kqueue.control([kev], 0, 0)
            return key

        def unregister(self, fileobj):
            key = super(KqueueSelector, self).unregister(fileobj)
            if key.events & EVENT_READ:
                kev = select.kevent(key.fd, select.KQ_FILTER_READ,
                                    select.KQ_EV_DELETE)
                try:
                    self._kqueue.control([kev], 0, 0)
                except OSError:
                    # This can happen if the FD was closed since it
                    # was registered.
                    pass
            if key.events & EVENT_WRITE:
                kev = select.kevent(key.fd, select.KQ_FILTER_WRITE,
                                    select.KQ_EV_DELETE)
                try:
                    self._kqueue.control([kev], 0, 0)
                except OSError:
                    # See comment above.
                    pass
            return key

        def select(self, timeout=None):
            timeout = None if timeout is None else max(timeout, 0)
            max_ev = len(self._fd_to_key)
            ready = []
            try:
                kev_list = self._kqueue.control(None, max_ev, timeout)
            except OSError as exc:
                if exc.errno == EINTR:
                    return ready
                else:
                    raise
            for kev in kev_list:
                fd = kev.ident
                flag = kev.filter
                events = 0
                if flag == select.KQ_FILTER_READ:
                    events |= EVENT_READ
                if flag == select.KQ_FILTER_WRITE:
                    events |= EVENT_WRITE

                key = self._key_from_fd(fd)
                if key:
                    ready.append((key, events & key.events))
            return ready

        def close(self):
            self._kqueue.close()
            super(KqueueSelector, self).close()

# Choose the best implementation, roughly:
#    epoll|kqueue|devpoll > poll > select.
# select() also can't accept a FD > FD_SETSIZE (usually around 1024)
if 'KqueueSelector' in globals():
    DefaultSelector = KqueueSelector
elif 'EpollSelector' in globals():
    DefaultSelector = EpollSelector
elif 'DevpollSelector' in globals():
    DefaultSelector = DevpollSelector
elif 'PollSelector' in globals():
    DefaultSelector = PollSelector
else:
    DefaultSelector = SelectSelector


text:
class GccAT6 < Formula
  desc "GNU compiler collection"
  homepage "https://gcc.gnu.org"
  url "https://ftp.gnu.org/gnu/gcc/gcc-6.4.0/gcc-6.4.0.tar.xz"
  mirror "https://ftpmirror.gnu.org/gcc/gcc-6.4.0/gcc-6.4.0.tar.xz"
  sha256 "850bf21eafdfe5cd5f6827148184c08c4a0852a37ccf36ce69855334d2c914d4"

  bottle do
    sha256 "d33494e55966361e4ceeebac90868e1376470a0cf892d7d560fb33cb8517d315" => :high_sierra
    sha256 "a8b246961500f3ffb8fc30da8bb7b261029fb6e8ba602c18797785bfd405c2c9" => :sierra
    sha256 "8942f79d833b4897820795607b25f5feaa49a0f0e160a9db25263d6876069313" => :el_capitan
    sha256 "5c3d71e364916409f8eafe3868d0d66209720c5303334bfcf44b7a712d23ce18" => :yosemite
  end

  # GCC's Go compiler is not currently supported on macOS.
  # See: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=46986
  option "with-java", "Build the gcj compiler"
  option "with-all-languages", "Enable all compilers and languages, except Ada"
  option "with-nls", "Build with native language support (localization)"
  option "with-jit", "Build the jit compiler"
  option "without-fortran", "Build without the gfortran compiler"

  depends_on "gmp"
  depends_on "libmpc"
  depends_on "mpfr"
  depends_on "isl"
  depends_on "ecj" if build.with?("java") || build.with?("all-languages")

  fails_with :gcc_4_0

  # GCC bootstraps itself, so it is OK to have an incompatible C++ stdlib
  cxxstdlib_check :skip

  # The bottles are built on systems with the CLT installed, and do not work
  # out of the box on Xcode-only systems due to an incorrect sysroot.
  pour_bottle? do
    reason "The bottle needs the Xcode CLT to be installed."
    satisfy { MacOS::CLT.installed? }
  end

  # Fix for libgccjit.so linkage on Darwin
  # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=64089
  # https://github.com/Homebrew/homebrew-core/issues/1872#issuecomment-225625332
  # https://github.com/Homebrew/homebrew-core/issues/1872#issuecomment-225626490
  patch do
    url "https://raw.githubusercontent.com/Homebrew/formula-patches/e9e0ee09389a54cc4c8fe1c24ebca3cd765ed0ba/gcc/6.1.0-jit.patch"
    sha256 "863957f90a934ee8f89707980473769cff47ca0663c3906992da6afb242fb220"
  end

  # Fix parallel build on APFS filesystem
  # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=81797
  if MacOS.version >= :high_sierra
    patch do
      url "https://raw.githubusercontent.com/Homebrew/formula-patches/df0465c02a/gcc/apfs.patch"
      sha256 "f7772a6ba73f44a6b378e4fe3548e0284f48ae2d02c701df1be93780c1607074"
    end
  end

  def install
    # GCC will suffer build errors if forced to use a particular linker.
    ENV.delete "LD"

    if build.with? "all-languages"
      # Everything but Ada, which requires a pre-existing GCC Ada compiler
      # (gnat) to bootstrap. GCC 4.6.0 adds go as a language option, but it is
      # currently only compilable on Linux.
      languages = %w[c c++ objc obj-c++ fortran java jit]
    else
      # C, C++, ObjC compilers are always built
      languages = %w[c c++ objc obj-c++]

      languages << "fortran" if build.with? "fortran"
      languages << "java" if build.with? "java"
      languages << "jit" if build.with? "jit"
    end

    version_suffix = version.to_s.slice(/\d/)

    # Even when suffixes are appended, the info pages conflict when
    # install-info is run so pretend we have an outdated makeinfo
    # to prevent their build.
    ENV["gcc_cv_prog_makeinfo_modern"] = "no"

    osmajor = `uname -r`.chomp
    arch = MacOS.prefer_64_bit? ? "x86_64" : "i686"

    args = [
      "--build=#{arch}-apple-darwin#{osmajor}",
      "--prefix=#{prefix}",
      "--libdir=#{lib}/gcc/#{version_suffix}",
      "--enable-languages=#{languages.join(",")}",
      # Make most executables versioned to avoid conflicts.
      "--program-suffix=-#{version_suffix}",
      "--with-gmp=#{Formula["gmp"].opt_prefix}",
      "--with-mpfr=#{Formula["mpfr"].opt_prefix}",
      "--with-mpc=#{Formula["libmpc"].opt_prefix}",
      "--with-isl=#{Formula["isl"].opt_prefix}",
      "--with-system-zlib",
      "--enable-stage1-checking",
      "--enable-checking=release",
      "--enable-lto",
      # Use 'bootstrap-debug' build configuration to force stripping of object
      # files prior to comparison during bootstrap (broken by Xcode 6.3).
      "--with-build-config=bootstrap-debug",
      "--disable-werror",
      "--with-pkgversion=Homebrew GCC #{pkg_version} #{build.used_options*" "}".strip,
      "--with-bugurl=https://github.com/Homebrew/homebrew-core/issues",
    ]

    # The pre-Mavericks toolchain requires the older DWARF-2 debugging data
    # format to avoid failure during the stage 3 comparison of object files.
    # See: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=45248
    args << "--with-dwarf2" if MacOS.version <= :mountain_lion

    args << "--disable-nls" if build.without? "nls"

    if build.with?("java") || build.with?("all-languages")
      args << "--with-ecj-jar=#{Formula["ecj"].opt_share}/java/ecj.jar"
    end

    if MacOS.prefer_64_bit?
      args << "--enable-multilib"
    else
      args << "--disable-multilib"
    end

    args << "--enable-host-shared" if build.with?("jit") || build.with?("all-languages")

    # Ensure correct install names when linking against libgcc_s;
    # see discussion in https://github.com/Homebrew/homebrew/pull/34303
    inreplace "libgcc/config/t-slibgcc-darwin", "@shlib_slibdir@", "#{HOMEBREW_PREFIX}/lib/gcc/#{version_suffix}"

    mkdir "build" do
      unless MacOS::CLT.installed?
        # For Xcode-only systems, we need to tell the sysroot path.
        # "native-system-headers" will be appended
        args << "--with-native-system-header-dir=/usr/include"
        args << "--with-sysroot=#{MacOS.sdk_path}"
      end

      system "../configure", *args
      system "make", "bootstrap"
      system "make", "install"
    end

    # Handle conflicts between GCC formulae and avoid interfering
    # with system compilers.
    # Rename man7.
    Dir.glob(man7/"*.7") { |file| add_suffix file, version_suffix }
    # Even when we disable building info pages some are still installed.
    info.rmtree
  end

  def add_suffix(file, suffix)
    dir = File.dirname(file)
    ext = File.extname(file)
    base = File.basename(file, ext)
    File.rename file, "#{dir}/#{base}-#{suffix}#{ext}"
  end

  test do
    (testpath/"hello-c.c").write <<-EOS.undent
      #include <stdio.h>
      int main()
      {
        puts("Hello, world!");
        return 0;
      }
    EOS
    system "#{bin}/gcc-6", "-o", "hello-c", "hello-c.c"
    assert_equal "Hello, world!\n", `./hello-c`

    (testpath/"hello-cc.cc").write <<-EOS.undent
      #include <iostream>
      int main()
      {
        std::cout << "Hello, world!" << std::endl;
        return 0;
      }
    EOS
    system "#{bin}/g++-6", "-o", "hello-cc", "hello-cc.cc"
    assert_equal "Hello, world!\n", `./hello-cc`

    if build.with?("fortran") || build.with?("all-languages")
      fixture = <<-EOS.undent
        integer,parameter::m=10000
        real::a(m), b(m)
        real::fact=0.5

        do concurrent (i=1:m)
          a(i) = a(i) + fact*b(i)
        end do
        print *, "done"
        end
      EOS
      (testpath/"in.f90").write(fixture)
      system "#{bin}/gfortran-6", "-o", "test", "in.f90"
      assert_equal "done", `./test`.strip
    end
  end
end


text:
#ifndef WEBRTC_COMMON_AUDIO_MOCKS_MOCK_SMOOTHING_FILTER_H_
#define WEBRTC_COMMON_AUDIO_MOCKS_MOCK_SMOOTHING_FILTER_H_

#include "webrtc/common_audio/smoothing_filter.h"
#include "webrtc/test/gmock.h"

namespace webrtc {

class MockSmoothingFilter : public SmoothingFilter {
 public:
  MOCK_METHOD1(AddSample, void(float));
  MOCK_METHOD0(GetAverage, rtc::Optional<float>());
  MOCK_METHOD1(SetTimeConstantMs, bool(int));
};

}  // namespace webrtc

#endif  // WEBRTC_COMMON_AUDIO_MOCKS_MOCK_SMOOTHING_FILTER_H_


text:
'use strict';

var flight;

function coerceToInt(number) {
    if (number === 'NA') {
        return null;
    }
    var int = parseInt(number);
    if (isNaN(int)) {
        return null;
    } else {
        return int;
    }
}

// http://www.epochconverter.com/
// http://momentjs.com

var beginningOf2001 = moment('2001-01-01');
var beginningOf2002 = moment('2002-01-01');
var months = [beginningOf2001];
var weeks = [beginningOf2001];
for (var i = 1; i <= 11; i++) {
    var nextMonth = beginningOf2001.clone().add(i, 'months');
    months.push(nextMonth);
}
const monthNames = months.map(month => month.format('MMMM'));

// https://developer.mozilla.org/en/docs/Web/HTML/Element/select
const timeRangeMonthDisplay = document.querySelector('#time-range-month');
monthNames.forEach((name, index) => {
    const option = document.createElement('option');
    option.setAttribute('value', index);
    option.appendChild(document.createTextNode(name));
   timeRangeMonthDisplay.appendChild(option);
});
timeRangeMonthDisplay.addEventListener('change', event => {
    const selectedMonth = event.target.value;
    if (selectedMonth != -1) {
        handleRangeChangeMonth(selectedMonth);
    }
});

for (var i = 1; i <= 51; i++) {
    var nextWeek = beginningOf2001.clone().add(i, 'weeks');
    if ( nextWeek.isAfter(beginningOf2002) ) {
        break;
    }
    weeks.push(nextWeek);
}
const weekNames = weeks.map(week => week.format('Wo'));
const timeRangeWeekDisplay = document.querySelector('#time-range-week');
weekNames.forEach((name, index) => {
    const option = document.createElement('option');
    option.setAttribute('value', index);
    option.appendChild(document.createTextNode(name));
    timeRangeWeekDisplay.appendChild(option);
});
timeRangeWeekDisplay.addEventListener('change', event => {
    const selectedWeek = event.target.value;
    if (selectedWeek != -1) {
        handleRangeChangeWeek(selectedWeek);
    }
});

var dayInMS = +moment.duration(1, 'day');
var weekInMS = +moment.duration(1, 'week');
var beginningOfSeptember = +months[8];
var beginningOfOctober = +months[9];

// var endOf2001 = 1009839600000;
// var allOf2001 = endOf2001 - beginningOf2001;
// var beginningOfFebruary = beginningOf2001 + 31 * dayInMS;
// var beginningOfMarch = beginningOfFebruary + 28 * dayInMS;
// var beginningOfApril = beginningOfMarch + 31 * dayInMS;
// var beginningOfMai = beginningOfApril + 30 * dayInMS;
// var beginningOfMonths = [beginningOf2001, beginningOfFebruary, beginningOfMarch, beginningOfApril];

var createQuery = function (fields, from, to) {
    // reduced data
    from = from || beginningOfSeptember + 1 * weekInMS;
    to = to || beginningOfSeptember + 2 * weekInMS;
    // from = from || beginningOfSeptember;
    // to = to || beginningOfOctober;

    // set index.max_result_window in elasticsearch.yml to 1000000 to allow for large result sets
    return {
        "size": 500000,
        "query": {
            "filtered": {
                "query": {
                    "query_string": {
                        "query": "Cancelled: false",
                        "analyze_wildcard": true
                    }
                },
                "filter": {
                    "bool": {
                        "must": [
                            {
                                "range": {
                                    "@timestamp": {
                                        "gte": from,
                                        "lte": to,
                                        "format": "epoch_millis"
                                    }
                                }
                            }
                        ],
                        "must_not": []
                    }
                }
            }
        },
        "aggs": {},
        "fields": fields
    };
}

function unwrap(hit, fields) {
    const unwrapped = {};
    fields.forEach((field) => {
        unwrapped[field] = hit.fields[field][0]
    });
    return unwrapped;
}

function handleRangeChangeMonth(monthIndex) {
    const month = months[monthIndex];
    document.querySelector('#time-range-name').innerHTML = monthNames[monthIndex];
    const from = +month;
    const to = +month.clone().add(1, 'month');
    load((cf) => render(cf, from, to, 31), from, to);
}

function handleRangeChangeWeek(weekIndex) {
    const week = weeks[weekIndex];
    document.querySelector('#time-range-name').innerHTML = `${weekNames[weekIndex]} week of`;
    const from = +week;
    const to = +week.clone().add(1, 'week');
    load((cf) => render(cf, from, to, 7), from, to);
}

function load(callback, from, to) {
    signalLoadingStart();

    const fields = ["Year", "Month", "DayofMonth", "Origin", "Dest", "UniqueCarrier"];

    const query = createQuery(fields, from, to);

    // be sure to enable CORS in elasticsearch
    // https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-http.html

    // fetch('http://localhost:9200/expo2009_airline/_search', {
    fetch('http://localhost:9200/expo2009_pandas/_search', {
        method: 'POST',
        //mode: 'no-cors', // we need cors, otherwise we get no response back
        body: JSON.stringify(query),
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        }
    }).then((response) => {
        return response.json();
    }).catch((ex) => {
            console.error('parsing failed', ex);
    }).then(data => handleData(data, fields, callback));

}

function handleData(data, fields, callback) {
    console.log('Loading done');
    console.log(new Date());
    //console.log(data);
    console.log(data.hits.total);
    console.log(data.hits.hits[0]);
    const flights = data.hits.hits.map((hit) => unwrap(hit, fields));
    //console.log(flights);
    console.log(flights[0]);

    d3.json("helper_data/airports_by_state.json", function (airportsArray) {
        // make airports a map using airport code as key
        var airports = {};
        airportsArray.forEach(function (airport) {
            airports[airport.airport] = airport;
        });

        // FCA missing in data set
        // https://en.wikipedia.org/wiki/Glacier_Park_International_Airport
        // https://en.wikipedia.org/wiki/List_of_U.S._state_abbreviations
        var fca = {
            airport: 'FCA',
            name: 'Glacier Park International Airport',
            state: 'MT'
        };
        airports[fca.airport] = fca;

        // MQT missing in data set
        // https://en.wikipedia.org/wiki/Sawyer_International_Airport
        var mqt = {
            airport: 'MQT',
            name: 'Sawyer International Airport',
            state: 'MI'
        };
        airports[mqt.airport] = mqt;

        console.log('Adding state information');
        // add state of origin and departure using airport code
        flights.forEach(function (flight) {
            if (airports[flight.Origin]) {
                flight.stateOrigin = airports[flight.Origin].state;
            } else {
                flight.stateOrigin = 'N/A';
                console.warn('Missing airport code', flight.Origin);
            }
            if (airports[flight.Dest]) {
                flight.stateDest = airports[flight.Dest].state;
            } else {
                flight.stateDest = 'N/A';
                console.warn('Missing airport code', flight.Dest);
            }
        });
        console.log('Done');
        console.log('Processed flight:');
        console.log(flights[0]);

        flight = crossfilter(flights);

        console.log('Conversion done');
        console.log(new Date());
        callback && callback(flight);
    });
}


text:
import {OverlayModule} from '@angular/cdk/overlay';
import {PortalModule} from '@angular/cdk/portal';
import {CommonModule} from '@angular/common';
import {NgModule} from '@angular/core';
import {MatButtonModule} from '@angular/material-experimental/mdc-button';
import {MatCommonModule} from '@angular/material-experimental/mdc-core';

import {MatSimpleSnackBar} from './simple-snack-bar';
import {MatSnackBarContainer} from './snack-bar-container';
import {
  MatSnackBarAction,
  MatSnackBarActions,
  MatSnackBarLabel
} from './snack-bar-content';

@NgModule({
  imports: [
    OverlayModule,
    PortalModule,
    CommonModule,
    MatButtonModule,
    MatCommonModule,
  ],
  exports: [
    MatCommonModule,
    MatSnackBarContainer,
    MatSnackBarLabel,
    MatSnackBarActions,
    MatSnackBarAction,
  ],
  declarations: [
    MatSimpleSnackBar,
    MatSnackBarContainer,
    MatSnackBarLabel,
    MatSnackBarActions,
    MatSnackBarAction,
  ],
  entryComponents: [
    MatSimpleSnackBar,
    MatSnackBarContainer,
  ],
})
export class MatSnackBarModule {
}


text:
module ErrbitPivotalPlugin
  VERSION = '0.5.0'
end


text:
package org.apache.hyracks.storage.am.lsm.btree.perf;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.concurrent.ConcurrentSkipListSet;

import org.apache.hyracks.api.dataflow.value.ITypeTraits;
import org.apache.hyracks.api.exceptions.HyracksDataException;
import org.apache.hyracks.dataflow.common.data.accessors.ITupleReference;
import org.apache.hyracks.storage.am.common.datagen.DataGenThread;
import org.apache.hyracks.storage.am.common.datagen.TupleBatch;
import org.apache.hyracks.storage.am.common.ophelpers.MultiComparator;
import org.apache.hyracks.storage.am.common.tuples.TypeAwareTupleReference;
import org.apache.hyracks.storage.am.common.tuples.TypeAwareTupleWriter;
import org.apache.hyracks.storage.am.common.tuples.TypeAwareTupleWriterFactory;

public class InMemorySortRunner implements IExperimentRunner {
    public class TupleComparator implements Comparator<ITupleReference> {
        private final MultiComparator cmp;

        public TupleComparator(MultiComparator cmp) {
            this.cmp = cmp;
        }

        @Override
        public int compare(ITupleReference o1, ITupleReference o2) {
            try {
                return cmp.compare(o1, o2);
            } catch (HyracksDataException e) {
                throw new IllegalArgumentException(e);
            }
        }
    }

    private final TupleComparator tupleCmp;
    private final int numBatches;
    private final int batchSize;
    private final int tupleSize;
    private final ITypeTraits[] typeTraits;

    private final TypeAwareTupleWriterFactory tupleWriterFactory;
    private final TypeAwareTupleWriter tupleWriter;
    private final ArrayList<TypeAwareTupleReference> tuples;
    private final ByteBuffer tupleBuf;

    public InMemorySortRunner(int numBatches, int batchSize, int tupleSize, ITypeTraits[] typeTraits,
            MultiComparator cmp) {
        this.numBatches = numBatches;
        this.tupleSize = tupleSize;
        this.batchSize = batchSize;
        this.typeTraits = typeTraits;
        tupleCmp = new TupleComparator(cmp);
        tupleWriterFactory = new TypeAwareTupleWriterFactory(typeTraits);
        tupleWriter = (TypeAwareTupleWriter) tupleWriterFactory.createTupleWriter();
        int numTuples = numBatches * batchSize;
        tuples = new ArrayList<TypeAwareTupleReference>();
        tupleBuf = ByteBuffer.allocate(numTuples * tupleSize);
        for (int i = 0; i < numTuples; i++) {
            tuples.add((TypeAwareTupleReference) tupleWriter.createTupleReference());
        }
    }

    @Override
    public long runExperiment(DataGenThread dataGen, int numThreads) throws InterruptedException {
        // Wait until the tupleBatchQueue is completely full.
        while (dataGen.tupleBatchQueue.remainingCapacity() != 0) {
            Thread.sleep(10);
        }

        long start = System.currentTimeMillis();
        int tupleIndex = 0;
        for (int i = 0; i < numBatches; i++) {
            TupleBatch batch = dataGen.tupleBatchQueue.take();
            for (int j = 0; j < batch.size(); j++) {
                // Copy the tuple to the buffer and set the pre-created tuple ref.
                tupleWriter.writeTuple(batch.get(j), tupleBuf.array(), tupleIndex * tupleSize);
                tuples.get(tupleIndex).resetByTupleOffset(tupleBuf.array(), tupleIndex * tupleSize);
                tupleIndex++;
            }
        }
        // Perform the sort.
        Collections.sort(tuples, tupleCmp);
        long end = System.currentTimeMillis();
        long time = end - start;
        return time;
    }

    @Override
    public void init() throws Exception {
    }

    @Override
    public void deinit() throws Exception {
    }

    public void reset() throws Exception {
    }

    public class SkipListThread extends Thread {
        private final DataGenThread dataGen;
        private final ConcurrentSkipListSet<ITupleReference> skipList;
        private final int numBatches;
        public final TypeAwareTupleWriterFactory tupleWriterFactory;
        public final TypeAwareTupleWriter tupleWriter;
        public final TypeAwareTupleReference[] tuples;
        public final ByteBuffer tupleBuf;

        public SkipListThread(DataGenThread dataGen, ConcurrentSkipListSet<ITupleReference> skipList, int numBatches,
                int batchSize) {
            this.dataGen = dataGen;
            this.numBatches = numBatches;
            this.skipList = skipList;
            tupleWriterFactory = new TypeAwareTupleWriterFactory(typeTraits);
            tupleWriter = (TypeAwareTupleWriter) tupleWriterFactory.createTupleWriter();
            int numTuples = numBatches * batchSize;
            tuples = new TypeAwareTupleReference[numTuples];
            tupleBuf = ByteBuffer.allocate(numTuples * tupleSize);
            for (int i = 0; i < numTuples; i++) {
                tuples[i] = (TypeAwareTupleReference) tupleWriter.createTupleReference();
            }
        }

        @Override
        public void run() {
            int tupleIndex = 0;
            try {
                for (int i = 0; i < numBatches; i++) {
                    TupleBatch batch = dataGen.tupleBatchQueue.take();
                    for (int j = 0; j < batch.size(); j++) {
                        // Copy the tuple to the buffer and set the pre-created tuple ref.
                        tupleWriter.writeTuple(batch.get(j), tupleBuf.array(), tupleIndex * tupleSize);
                        tuples[tupleIndex].resetByTupleOffset(tupleBuf.array(), tupleIndex * tupleSize);
                        skipList.add(tuples[tupleIndex]);
                        tupleIndex++;
                    }
                }
            } catch (Exception e) {
                System.out.println(tupleIndex);
                e.printStackTrace();
            }
        }
    }
}


text:
package net.bytebuddy.description.type;

import org.junit.Test;

import static net.bytebuddy.matcher.ElementMatchers.none;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;

public class RecordComponentListEmptyTest {

    @Test
    public void testTokenListWithFilter() throws Exception {
        assertThat(new RecordComponentList.Empty<RecordComponentDescription>().asTokenList(none()).size(), is(0));
    }

    @Test
    public void testDeclaredList() throws Exception {
        assertThat(new RecordComponentList.Empty<RecordComponentDescription>().asDefined().size(), is(0));
    }
}


text:
package lombok.ast.ecj;

import org.eclipse.jdt.internal.compiler.ast.*;

public abstract class EcjTreeVisitor {
	public void visitEcjNode(ASTNode node) {
		if (node == null) return;
		Class<?> clazz = node.getClass();

		if (clazz == Wildcard.class) {
			visitWildcard((Wildcard) node);
			return;
		}
		if (clazz == WhileStatement.class) {
			visitWhileStatement((WhileStatement) node);
			return;
		}
		if (clazz == UnaryExpression.class) {
			visitUnaryExpression((UnaryExpression) node);
			return;
		}
		if (clazz == TypeParameter.class) {
			visitTypeParameter((TypeParameter) node);
			return;
		}
		if (clazz == TypeDeclaration.class) {
			visitTypeDeclaration((TypeDeclaration) node);
			return;
		}
		if (clazz == TryStatement.class) {
			visitTryStatement((TryStatement) node);
			return;
		}
		if (clazz == TrueLiteral.class) {
			visitTrueLiteral((TrueLiteral) node);
			return;
		}
		if (clazz == ThrowStatement.class) {
			visitThrowStatement((ThrowStatement) node);
			return;
		}
		if (clazz == ThisReference.class) {
			visitThisReference((ThisReference) node);
			return;
		}
		if (clazz == SynchronizedStatement.class) {
			visitSynchronizedStatement((SynchronizedStatement) node);
			return;
		}
		if (clazz == SwitchStatement.class) {
			visitSwitchStatement((SwitchStatement) node);
			return;
		}
		if (clazz == SuperReference.class) {
			visitSuperReference((SuperReference) node);
			return;
		}
		if (clazz == StringLiteral.class) {
			visitStringLiteral((StringLiteral) node);
			return;
		}
		if (clazz == SingleTypeReference.class) {
			visitSingleTypeReference((SingleTypeReference) node);
			return;
		}
		if (clazz == SingleNameReference.class) {
			visitSingleNameReference((SingleNameReference) node);
			return;
		}
		if (clazz == SingleMemberAnnotation.class) {
			visitSingleMemberAnnotation((SingleMemberAnnotation) node);
			return;
		}
		if (clazz == ReturnStatement.class) {
			visitReturnStatement((ReturnStatement) node);
			return;
		}
		if (clazz == QualifiedTypeReference.class) {
			visitQualifiedTypeReference((QualifiedTypeReference) node);
			return;
		}
		if (clazz == QualifiedThisReference.class) {
			visitQualifiedThisReference((QualifiedThisReference) node);
			return;
		}
		if (clazz == QualifiedSuperReference.class) {
			visitQualifiedSuperReference((QualifiedSuperReference) node);
			return;
		}
		if (clazz == QualifiedNameReference.class) {
			visitQualifiedNameReference((QualifiedNameReference) node);
			return;
		}
		if (clazz == QualifiedAllocationExpression.class) {
			visitQualifiedAllocationExpression((QualifiedAllocationExpression) node);
			return;
		}
		if (clazz == PrefixExpression.class) {
			visitPrefixExpression((PrefixExpression) node);
			return;
		}
		if (clazz == PostfixExpression.class) {
			visitPostfixExpression((PostfixExpression) node);
			return;
		}
		if (clazz == ParameterizedSingleTypeReference.class) {
			visitParameterizedSingleTypeReference((ParameterizedSingleTypeReference) node);
			return;
		}
		if (clazz == ParameterizedQualifiedTypeReference.class) {
			visitParameterizedQualifiedTypeReference((ParameterizedQualifiedTypeReference) node);
			return;
		}
		if (clazz == OR_OR_Expression.class) {
			visitOR_OR_Expression((OR_OR_Expression) node);
			return;
		}
		if (clazz == NullLiteral.class) {
			visitNullLiteral((NullLiteral) node);
			return;
		}
		if (clazz == NormalAnnotation.class) {
			visitNormalAnnotation((NormalAnnotation) node);
			return;
		}
		if (clazz == StringLiteralConcatenation.class) {
			visitStringLiteralConcatenation((StringLiteralConcatenation) node);
			return;
		}
		if (clazz == MethodDeclaration.class) {
			visitMethodDeclaration((MethodDeclaration) node);
			return;
		}
		if (clazz == MessageSend.class) {
			visitMessageSend((MessageSend) node);
			return;
		}
		if (clazz == MemberValuePair.class) {
			visitMemberValuePair((MemberValuePair) node);
			return;
		}
		if (clazz == MarkerAnnotation.class) {
			visitMarkerAnnotation((MarkerAnnotation) node);
			return;
		}
		if (clazz == LongLiteral.class) {
			visitLongLiteral((LongLiteral) node);
			return;
		}
		if (clazz == LocalDeclaration.class) {
			visitLocalDeclaration((LocalDeclaration) node);
			return;
		}
		if (clazz == LabeledStatement.class) {
			visitLabeledStatement((LabeledStatement) node);
			return;
		}
		if (clazz == IntLiteral.class) {
			visitIntLiteral((IntLiteral) node);
			return;
		}
		if (clazz == InstanceOfExpression.class) {
			visitInstanceOfExpression((InstanceOfExpression) node);
			return;
		}
		if (clazz == Initializer.class) {
			visitInitializer((Initializer) node);
			return;
		}
		if (clazz == ImportReference.class) {
			visitImportReference((ImportReference) node);
			return;
		}
		if (clazz == IfStatement.class) {
			visitIfStatement((IfStatement) node);
			return;
		}
		if (clazz == ForStatement.class) {
			visitForStatement((ForStatement) node);
			return;
		}
		if (clazz == ForeachStatement.class) {
			visitForeachStatement((ForeachStatement) node);
			return;
		}
		if (clazz == FloatLiteral.class) {
			visitFloatLiteral((FloatLiteral) node);
			return;
		}
		if (clazz == FieldReference.class) {
			visitFieldReference((FieldReference) node);
			return;
		}
		if (clazz == FieldDeclaration.class) {
			visitFieldDeclaration((FieldDeclaration) node);
			return;
		}
		if (clazz == FalseLiteral.class) {
			visitFalseLiteral((FalseLiteral) node);
			return;
		}
		if (clazz == ExtendedStringLiteral.class) {
			visitExtendedStringLiteral((ExtendedStringLiteral) node);
			return;
		}
		if (clazz == ExplicitConstructorCall.class) {
			visitExplicitConstructorCall((ExplicitConstructorCall) node);
			return;
		}
		if (clazz == EqualExpression.class) {
			visitEqualExpression((EqualExpression) node);
			return;
		}
		if (clazz == EmptyStatement.class) {
			visitEmptyStatement((EmptyStatement) node);
			return;
		}
		if (clazz == DoubleLiteral.class) {
			visitDoubleLiteral((DoubleLiteral) node);
			return;
		}
		if (clazz == DoStatement.class) {
			visitDoStatement((DoStatement) node);
			return;
		}
		if (clazz == ContinueStatement.class) {
			visitContinueStatement((ContinueStatement) node);
			return;
		}
		if (clazz == ConstructorDeclaration.class) {
			visitConstructorDeclaration((ConstructorDeclaration) node);
			return;
		}
		if (clazz == ConditionalExpression.class) {
			visitConditionalExpression((ConditionalExpression) node);
			return;
		}
		if (clazz == CompoundAssignment.class) {
			visitCompoundAssignment((CompoundAssignment) node);
			return;
		}
		if (clazz == CompilationUnitDeclaration.class) {
			visitCompilationUnitDeclaration((CompilationUnitDeclaration) node);
			return;
		}
		if (clazz == Clinit.class) {
			visitClinit((Clinit) node);
			return;
		}
		if (clazz == ClassLiteralAccess.class) {
			visitClassLiteralAccess((ClassLiteralAccess) node);
			return;
		}
		if (clazz == CharLiteral.class) {
			visitCharLiteral((CharLiteral) node);
			return;
		}
		if (clazz == CastExpression.class) {
			visitCastExpression((CastExpression) node);
			return;
		}
		if (clazz == CaseStatement.class) {
			visitCaseStatement((CaseStatement) node);
			return;
		}
		if (clazz == BreakStatement.class) {
			visitBreakStatement((BreakStatement) node);
			return;
		}
		if (clazz == Block.class) {
			visitBlock((Block) node);
			return;
		}
		if (clazz == BinaryExpression.class) {
			visitBinaryExpression((BinaryExpression) node);
			return;
		}
		if (clazz == Assignment.class) {
			visitAssignment((Assignment) node);
			return;
		}
		if (clazz == AssertStatement.class) {
			visitAssertStatement((AssertStatement) node);
			return;
		}
		if (clazz == ArrayTypeReference.class) {
			visitArrayTypeReference((ArrayTypeReference) node);
			return;
		}
		if (clazz == ArrayReference.class) {
			visitArrayReference((ArrayReference) node);
			return;
		}
		if (clazz == ArrayQualifiedTypeReference.class) {
			visitArrayQualifiedTypeReference((ArrayQualifiedTypeReference) node);
			return;
		}
		if (clazz == ArrayInitializer.class) {
			visitArrayInitializer((ArrayInitializer) node);
			return;
		}
		if (clazz == ArrayAllocationExpression.class) {
			visitArrayAllocationExpression((ArrayAllocationExpression) node);
			return;
		}
		if (clazz == Argument.class) {
			visitArgument((Argument) node);
			return;
		}
		if (clazz == AnnotationMethodDeclaration.class) {
			visitAnnotationMethodDeclaration((AnnotationMethodDeclaration) node);
			return;
		}
		if (clazz == AND_AND_Expression.class) {
			visitAND_AND_Expression((AND_AND_Expression) node);
			return;
		}
		if (clazz == AllocationExpression.class) {
			visitAllocationExpression((AllocationExpression) node);
			return;
		}
		if (clazz == CombinedBinaryExpression.class) {
			visitCombinedBinaryExpression((CombinedBinaryExpression) node);
			return;
		}
		if (clazz == IntLiteralMinValue.class) {
			visitIntLiteralMinValue((IntLiteralMinValue) node);
			return;
		}
		if (clazz == LongLiteralMinValue.class) {
			visitLongLiteralMinValue((LongLiteralMinValue) node);
			return;
		}
		if (clazz == Javadoc.class) {
			visitJavadoc((Javadoc) node);
			return;
		}
		if (clazz == UnionTypeReference.class) {
			visitUnionTypeReference((UnionTypeReference) node);
			return;
		}
		if (clazz == ReferenceExpression.class) {
			visitReferenceExpression((ReferenceExpression) node);
            return;
		}
        if (clazz == LambdaExpression.class) {
            visitLambdaExpression((LambdaExpression) node);
            return;
        }

		visitOther(node);
	}

	public void visitOther(ASTNode node) {
		throw new UnsupportedOperationException("Unknown ASTNode child: " + node.getClass().getSimpleName());
	}

	public void visitAny(ASTNode node) {
		throw new UnsupportedOperationException("visit" + node.getClass().getSimpleName() + " not implemented");
	}

	public void visitWildcard(Wildcard node) {
		visitAny(node);
	}

	public void visitWhileStatement(WhileStatement node) {
		visitAny(node);
	}

	public void visitUnaryExpression(UnaryExpression node) {
		visitAny(node);
	}

	public void visitTypeParameter(TypeParameter node) {
		visitAny(node);
	}

	public void visitTypeDeclaration(TypeDeclaration node) {
		visitAny(node);
	}

	public void visitTryStatement(TryStatement node) {
		visitAny(node);
	}

	public void visitTrueLiteral(TrueLiteral node) {
		visitAny(node);
	}

	public void visitThrowStatement(ThrowStatement node) {
		visitAny(node);
	}

	public void visitThisReference(ThisReference node) {
		visitAny(node);
	}

	public void visitSynchronizedStatement(SynchronizedStatement node) {
		visitAny(node);
	}

	public void visitSwitchStatement(SwitchStatement node) {
		visitAny(node);
	}

	public void visitSuperReference(SuperReference node) {
		visitAny(node);
	}

	public void visitStringLiteral(StringLiteral node) {
		visitAny(node);
	}

	public void visitSingleTypeReference(SingleTypeReference node) {
		visitAny(node);
	}

	public void visitSingleNameReference(SingleNameReference node) {
		visitAny(node);
	}

	public void visitSingleMemberAnnotation(SingleMemberAnnotation node) {
		visitAny(node);
	}

	public void visitReturnStatement(ReturnStatement node) {
		visitAny(node);
	}

	public void visitQualifiedTypeReference(QualifiedTypeReference node) {
		visitAny(node);
	}

	public void visitQualifiedThisReference(QualifiedThisReference node) {
		visitAny(node);
	}

	public void visitQualifiedSuperReference(QualifiedSuperReference node) {
		visitAny(node);
	}

	public void visitQualifiedNameReference(QualifiedNameReference node) {
		visitAny(node);
	}

	public void visitQualifiedAllocationExpression(QualifiedAllocationExpression node) {
		visitAny(node);
	}

	public void visitPrefixExpression(PrefixExpression node) {
		visitAny(node);
	}

	public void visitPostfixExpression(PostfixExpression node) {
		visitAny(node);
	}

	public void visitParameterizedSingleTypeReference(ParameterizedSingleTypeReference node) {
		visitAny(node);
	}

	public void visitParameterizedQualifiedTypeReference(ParameterizedQualifiedTypeReference node) {
		visitAny(node);
	}

	public void visitOR_OR_Expression(OR_OR_Expression node) {
		visitAny(node);
	}

	public void visitNullLiteral(NullLiteral node) {
		visitAny(node);
	}

	public void visitNormalAnnotation(NormalAnnotation node) {
		visitAny(node);
	}

	public void visitStringLiteralConcatenation(StringLiteralConcatenation node) {
		visitAny(node);
	}

	public void visitMethodDeclaration(MethodDeclaration node) {
		visitAny(node);
	}

	public void visitMessageSend(MessageSend node) {
		visitAny(node);
	}

	public void visitMemberValuePair(MemberValuePair node) {
		visitAny(node);
	}

	public void visitMarkerAnnotation(MarkerAnnotation node) {
		visitAny(node);
	}

	public void visitLongLiteral(LongLiteral node) {
		visitAny(node);
	}

	public void visitLocalDeclaration(LocalDeclaration node) {
		visitAny(node);
	}

	public void visitLabeledStatement(LabeledStatement node) {
		visitAny(node);
	}

	public void visitIntLiteral(IntLiteral node) {
		visitAny(node);
	}

	public void visitInstanceOfExpression(InstanceOfExpression node) {
		visitAny(node);
	}

	public void visitInitializer(Initializer node) {
		visitAny(node);
	}

	public void visitImportReference(ImportReference node) {
		visitAny(node);
	}

	public void visitIfStatement(IfStatement node) {
		visitAny(node);
	}

	public void visitForStatement(ForStatement node) {
		visitAny(node);
	}

	public void visitForeachStatement(ForeachStatement node) {
		visitAny(node);
	}

	public void visitFloatLiteral(FloatLiteral node) {
		visitAny(node);
	}

	public void visitFieldReference(FieldReference node) {
		visitAny(node);
	}

	public void visitFieldDeclaration(FieldDeclaration node) {
		visitAny(node);
	}

	public void visitFalseLiteral(FalseLiteral node) {
		visitAny(node);
	}

	public void visitExtendedStringLiteral(ExtendedStringLiteral node) {
		visitAny(node);
	}

	public void visitExplicitConstructorCall(ExplicitConstructorCall node) {
		visitAny(node);
	}

	public void visitEqualExpression(EqualExpression node) {
		visitAny(node);
	}

	public void visitEmptyStatement(EmptyStatement node) {
		visitAny(node);
	}

	public void visitDoubleLiteral(DoubleLiteral node) {
		visitAny(node);
	}

	public void visitDoStatement(DoStatement node) {
		visitAny(node);
	}

	public void visitContinueStatement(ContinueStatement node) {
		visitAny(node);
	}

	public void visitConstructorDeclaration(ConstructorDeclaration node) {
		visitAny(node);
	}

	public void visitConditionalExpression(ConditionalExpression node) {
		visitAny(node);
	}

	public void visitCompoundAssignment(CompoundAssignment node) {
		visitAny(node);
	}

	public void visitCompilationUnitDeclaration(CompilationUnitDeclaration node) {
		visitAny(node);
	}

	public void visitClinit(Clinit node) {
		visitAny(node);
	}

	public void visitClassLiteralAccess(ClassLiteralAccess node) {
		visitAny(node);
	}

	public void visitCharLiteral(CharLiteral node) {
		visitAny(node);
	}

	public void visitCastExpression(CastExpression node) {
		visitAny(node);
	}

	public void visitCaseStatement(CaseStatement node) {
		visitAny(node);
	}

	public void visitBreakStatement(BreakStatement node) {
		visitAny(node);
	}

	public void visitBlock(Block node) {
		visitAny(node);
	}

	public void visitBinaryExpression(BinaryExpression node) {
		visitAny(node);
	}

	public void visitAssignment(Assignment node) {
		visitAny(node);
	}

	public void visitAssertStatement(AssertStatement node) {
		visitAny(node);
	}

	public void visitArrayTypeReference(ArrayTypeReference node) {
		visitAny(node);
	}

	public void visitArrayReference(ArrayReference node) {
		visitAny(node);
	}

	public void visitArrayQualifiedTypeReference(ArrayQualifiedTypeReference node) {
		visitAny(node);
	}

	public void visitArrayInitializer(ArrayInitializer node) {
		visitAny(node);
	}

	public void visitArrayAllocationExpression(ArrayAllocationExpression node) {
		visitAny(node);
	}

	public void visitArgument(Argument node) {
		visitAny(node);
	}

	public void visitAnnotationMethodDeclaration(AnnotationMethodDeclaration node) {
		visitAny(node);
	}

	public void visitAND_AND_Expression(AND_AND_Expression node) {
		visitAny(node);
	}

	public void visitAllocationExpression(AllocationExpression node) {
		visitAny(node);
	}

	public void visitCombinedBinaryExpression(CombinedBinaryExpression node) {
		visitAny(node);
	}

	public void visitIntLiteralMinValue(IntLiteralMinValue node) {
		visitAny(node);
	}

	public void visitLongLiteralMinValue(LongLiteralMinValue node) {
		visitAny(node);
	}

	public void visitJavadoc(Javadoc node) {
		visitAny(node);
	}

	public void visitUnionTypeReference(UnionTypeReference node) {
		visitAny(node);
	}

    public void visitReferenceExpression(ReferenceExpression node) {
        visitAny(node);
    }

	public void visitLambdaExpression(LambdaExpression node) {
		visitAny(node);
	}
}


text:
@implementation EFApiModel

@synthesize last_item;
@synthesize total_items;
@synthesize first_item;
@synthesize page_number;
@synthesize page_size;
@synthesize page_items;
@synthesize search_time;
@synthesize page_count;
@synthesize events;

#pragma mark NSObject

- (void)dealloc
{
    self.last_item = nil;
    self.total_items = nil;
    self.first_item = nil;
    self.page_number = nil;
    self.page_size = nil;
    self.page_items = nil;
    self.search_time = nil;
    self.page_count = nil;
    self.events = nil;
}

@end


text:
import EventEmitter from 'events';
import {AsyncExecService, Logger} from "cyclon.p2p-common";
import {SignallingServerService} from "./SignallingServerService";
import {SignallingSocket} from "./SignallingSocket";
import {AnswerMessage, IceCandidatesMessage, OfferMessage, SignallingService} from "./SignallingService";
import {SocketFactory} from "./SocketFactory";
import {SignallingServerSpec} from "./SignallingServerSpec";

const INTERVAL_BETWEEN_SERVER_CONNECTIVITY_CHECKS = 30 * 1000;

/**
 * Maintains connections to up to a specified number of signalling servers
 * via socket.io and emits signalling messages received on them
 *
 * @param signallingServerService
 * @param loggingService
 * @param socketFactory
 * @param asyncExecService
 * @param signallingServerSelector
 * @constructor
 */
export class RedundantSignallingSocket extends EventEmitter implements SignallingSocket  {

    private readonly connectedSockets: { [signallingApiBase: string]: SocketIOClient.Socket };
    private readonly connectedSpecs: { [signallingApiBase: string]: SignallingServerSpec };
    private connectivityIntervalId?: number;
    private unloadInProgress: boolean;
    private signallingService?: SignallingService;
    private rooms: string[];

    constructor(private readonly signallingServerService: SignallingServerService,
                private readonly socketFactory: SocketFactory,
                private readonly logger: Logger,
                private readonly asyncExecService: AsyncExecService,
                private readonly signallingServerSelector: any) {
        super();
        this.connectedSockets = {};
        this.connectedSpecs = {};
        this.unloadInProgress = false;
        this.rooms = [];

        // If we're in a window, watch for unloads so we can disable
        // attempting to reconnect (and losing affinity with our previous signalling servers)
        if (typeof (window) !== "undefined") {
            window.addEventListener("beforeunload", () => {
                this.unloadInProgress = true;
            });
        }

        // We should only ever have one answer, and one offer listener
        this.setMaxListeners(2);
    }

    /**
     * Connect to signalling servers
     */
    connect(localSignallingService: SignallingService, roomsToJoin: string[]) {
        this.signallingService = localSignallingService;
        this.rooms = roomsToJoin;
        this.connectAndMonitor();
    }

    /**
     * Schedule periodic server connectivity checks
     */
    private scheduleServerConnectivityChecks() {
        if (this.connectivityIntervalId === undefined) {
            this.connectivityIntervalId = this.asyncExecService.setInterval(() => {
                this.updateRegistrations();
                this.connectToServers();
            }, INTERVAL_BETWEEN_SERVER_CONNECTIVITY_CHECKS);
        }
        else {
            throw new Error("BUG ::: Attempt was made to start connectivity checks twice");
        }
    }

    /**
     * Update our registrations with the servers
     * we're connected to
     */
    private updateRegistrations(): void {
        for (const key in this.connectedSockets) {
            this.sendRegisterMessage(this.connectedSockets[key]);
        }
    }

    /**
     * Stop periodic connectivity checks
     */
    private stopConnectivityChecks(): void {
        if (this.connectivityIntervalId !== undefined) {
            this.asyncExecService.clearInterval(this.connectivityIntervalId);
            delete this.connectivityIntervalId;
        }
    }

    private connectAndMonitor(): void {
        this.connectToServers();
        this.scheduleServerConnectivityChecks();
    }

    /**
     * Get the list of server specs we're currently listening on
     *
     * @returns {Array}
     */
    getCurrentServerSpecs(): SignallingServerSpec[] {
        const specs = [];
        for (const spec in this.connectedSpecs) {
            specs.push(this.connectedSpecs[spec]);
        }
        return specs;
    }

    /**
     * Connect to servers if we're not connected to enough
     */
    private connectToServers(): void {
        const knownServers = this.signallingServerSelector.getServerSpecsInPriorityOrder();

        for (let i = 0; i < knownServers.length; i++) {
            const connectionsRemaining = this.signallingServerService.getPreferredNumberOfSockets() - Object.keys(this.connectedSockets).length;

            //
            // We have enough connections
            //
            if (connectionsRemaining === 0) {
                break;
            }

            //
            // Try to connect to a new server
            //
            const serverSpec = knownServers[i];
            if (!this.currentlyConnectedToServer(serverSpec)) {
                let socket;
                try {
                    socket = this.socketFactory.createSocket(serverSpec);
                    this.storeSocket(serverSpec, socket);
                    this.addListeners(socket, serverSpec);
                    this.logger.info(`Attempting to connect to signalling server (${serverSpec.signallingApiBase})`);
                }
                catch (error) {
                    this.logger.error(`Error connecting to socket ${serverSpec.signallingApiBase}`, error);
                }
            }
        }

        //
        // Store the new set of connected servers in session storage so we
        // can prefer them in the event of a reload
        //
        this.signallingServerSelector.setLastConnectedServers(this.getListOfCurrentSignallingApiBases());
    }

    /**
     * Are we currently connected to the specified server?
     *
     * @param serverSpec
     * @returns {boolean}
     */
    private currentlyConnectedToServer(serverSpec: SignallingServerSpec): boolean {
        return this.connectedSockets.hasOwnProperty(serverSpec.signallingApiBase);
    }

    /**
     * Return the list of signallingApiBase values for the current set
     * of signalling servers
     *
     * @returns {Array}
     */
    private getListOfCurrentSignallingApiBases(): string[] {
        return Object.keys(this.connectedSpecs);
    }

    /**
     * Delete a socket from the local store
     *
     * @param spec
     * @param socket
     */
    private storeSocket(spec: SignallingServerSpec, socket: SocketIOClient.Socket) {
        this.connectedSpecs[spec.signallingApiBase] = spec;
        this.connectedSockets[spec.signallingApiBase] = socket;
    }

    /**
     * Delete the socket from the local store
     *
     * @param apiBase
     */
    private deleteSocket(apiBase: string): void {
        delete this.connectedSpecs[apiBase];
        delete this.connectedSockets[apiBase];
        this.signallingServerSelector.flagDisconnection(apiBase);
    }

    /**
     * Add listeners for a socket
     *
     * @param socket
     * @param serverSpec
     */
    private addListeners(socket: SocketIOClient.Socket, serverSpec: SignallingServerSpec) {
        const apiBase = serverSpec.signallingApiBase;
        const disposeFunction = this.disposeOfSocket(apiBase);
        const registerFunction = this.register(socket);

        // Register if we connect
        socket.on("connect", registerFunction);

        // Dispose if we disconnect/fail to connect/error
        socket.io.on("connect_error", disposeFunction);
        socket.on("error", disposeFunction);
        socket.on("disconnect", disposeFunction);

        /**
         * Emit offers/answers when they're received
         */
        socket.on("answer", (answer: AnswerMessage) => {
            this.emitAnswer(answer);
        });
        socket.on("offer", (offer: OfferMessage) => {
            this.emitOffer(offer);
        });
        socket.on("candidates", (candidates: IceCandidatesMessage) => {
            this.emitCandidates(candidates);
        });
    }

    /**
     * Return a closure that will dispose of a socket
     *
     * @param apiBase
     * @returns {Function}
     */
    private disposeOfSocket(apiBase: string) {
        return (error: Error) => {
            this.logger.warn(`Got disconnected from signalling server (${apiBase})`, error);

            const socket = this.connectedSockets[apiBase];
            if (socket) {
                this.stopConnectivityChecks();
                socket.removeAllListeners();
                socket.io.removeAllListeners();
                try {
                    socket.disconnect();
                }
                catch (ignore) {
                }
                this.deleteSocket(apiBase);

                if (!this.unloadInProgress) {
                    this.connectAndMonitor();
                }
            }
            else {
                throw new Error("BUG ::: Disconnected from a socket we're not connected to?!");
            }
        };
    }

    /**
     * Tell the signalling server who we are
     *
     * @param socket
     * @returns {Function}
     */
    private register(socket: SocketIOClient.Socket) {
        return () => {
            this.sendRegisterMessage(socket);
            this.sendJoinRoomsMessage(socket);
        };
    }

    private sendRegisterMessage(socket: SocketIOClient.Socket) {
        socket.emit("register", (this.signallingService as SignallingService).createNewPointer());
    }

    private sendJoinRoomsMessage(socket: SocketIOClient.Socket) {
        socket.emit("join", this.rooms);
    }

    private emitAnswer(message: AnswerMessage) {
        this.emit("answer", message);
    }

    private emitOffer(message: OfferMessage) {
        this.emit("offer", message);
    }

    private emitCandidates(message: IceCandidatesMessage) {
        this.emit("candidates", message);
    }
}


text:
module Azure::CDN::Mgmt::V2020_09_01
  module Models
    #
    # Defines a managed rule group override setting.
    #
    class ManagedRuleOverride

      include MsRestAzure

      # @return [String] Identifier for the managed rule.
      attr_accessor :rule_id

      # @return [ManagedRuleEnabledState] Describes if the managed rule is in
      # enabled or disabled state. Defaults to Disabled if not specified.
      # Possible values include: 'Disabled', 'Enabled'
      attr_accessor :enabled_state

      # @return [ActionType] Describes the override action to be applied when
      # rule matches. Possible values include: 'Allow', 'Block', 'Log',
      # 'Redirect'
      attr_accessor :action

      #
      # Mapper for ManagedRuleOverride class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'ManagedRuleOverride',
          type: {
            name: 'Composite',
            class_name: 'ManagedRuleOverride',
            model_properties: {
              rule_id: {
                client_side_validation: true,
                required: true,
                serialized_name: 'ruleId',
                type: {
                  name: 'String'
                }
              },
              enabled_state: {
                client_side_validation: true,
                required: false,
                serialized_name: 'enabledState',
                type: {
                  name: 'String'
                }
              },
              action: {
                client_side_validation: true,
                required: false,
                serialized_name: 'action',
                type: {
                  name: 'String'
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
package org.projectfloodlight.openflow.protocol.oxm;

import org.projectfloodlight.openflow.protocol.*;
import org.projectfloodlight.openflow.protocol.action.*;
import org.projectfloodlight.openflow.protocol.actionid.*;
import org.projectfloodlight.openflow.protocol.bsntlv.*;
import org.projectfloodlight.openflow.protocol.errormsg.*;
import org.projectfloodlight.openflow.protocol.meterband.*;
import org.projectfloodlight.openflow.protocol.instruction.*;
import org.projectfloodlight.openflow.protocol.instructionid.*;
import org.projectfloodlight.openflow.protocol.match.*;
import org.projectfloodlight.openflow.protocol.oxm.*;
import org.projectfloodlight.openflow.protocol.queueprop.*;
import org.projectfloodlight.openflow.types.*;
import org.projectfloodlight.openflow.util.*;
import org.projectfloodlight.openflow.exceptions.*;
import org.jboss.netty.buffer.ChannelBuffer;

public interface OFOxmIcmpv6CodeMasked extends OFObject, OFOxm<U8> {
    long getTypeLen();
    U8 getValue();
    U8 getMask();
    MatchField<U8> getMatchField();
    boolean isMasked();
    OFOxm<U8> getCanonical();
    OFVersion getVersion();

    void writeTo(ChannelBuffer channelBuffer);

    Builder createBuilder();
    public interface Builder extends OFOxm.Builder<U8> {
        OFOxmIcmpv6CodeMasked build();
        long getTypeLen();
        U8 getValue();
        Builder setValue(U8 value);
        U8 getMask();
        Builder setMask(U8 mask);
        MatchField<U8> getMatchField();
        boolean isMasked();
        OFOxm<U8> getCanonical();
        OFVersion getVersion();
    }
}