text:
#include <linux/module.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/of.h>
#include <linux/platform_device.h>
#include <linux/spi/spi.h>
#include <linux/spi/spi_bitbang.h>
#include <linux/spi/xilinx_spi.h>
#include <linux/io.h>

#define XILINX_SPI_NAME "xilinx_spi"

/* Register definitions as per "OPB Serial Peripheral Interface (SPI) (v1.00e)
 * Product Specification", DS464
 */
#define XSPI_CR_OFFSET		0x60	/* Control Register */

#define XSPI_CR_ENABLE		0x02
#define XSPI_CR_MASTER_MODE	0x04
#define XSPI_CR_CPOL		0x08
#define XSPI_CR_CPHA		0x10
#define XSPI_CR_MODE_MASK	(XSPI_CR_CPHA | XSPI_CR_CPOL)
#define XSPI_CR_TXFIFO_RESET	0x20
#define XSPI_CR_RXFIFO_RESET	0x40
#define XSPI_CR_MANUAL_SSELECT	0x80
#define XSPI_CR_TRANS_INHIBIT	0x100
#define XSPI_CR_LSB_FIRST	0x200

#define XSPI_SR_OFFSET		0x64	/* Status Register */

#define XSPI_SR_RX_EMPTY_MASK	0x01	/* Receive FIFO is empty */
#define XSPI_SR_RX_FULL_MASK	0x02	/* Receive FIFO is full */
#define XSPI_SR_TX_EMPTY_MASK	0x04	/* Transmit FIFO is empty */
#define XSPI_SR_TX_FULL_MASK	0x08	/* Transmit FIFO is full */
#define XSPI_SR_MODE_FAULT_MASK	0x10	/* Mode fault error */

#define XSPI_TXD_OFFSET		0x68	/* Data Transmit Register */
#define XSPI_RXD_OFFSET		0x6c	/* Data Receive Register */

#define XSPI_SSR_OFFSET		0x70	/* 32-bit Slave Select Register */

/* Register definitions as per "OPB IPIF (v3.01c) Product Specification", DS414
 * IPIF registers are 32 bit
 */
#define XIPIF_V123B_DGIER_OFFSET	0x1c	/* IPIF global int enable reg */
#define XIPIF_V123B_GINTR_ENABLE	0x80000000

#define XIPIF_V123B_IISR_OFFSET		0x20	/* IPIF interrupt status reg */
#define XIPIF_V123B_IIER_OFFSET		0x28	/* IPIF interrupt enable reg */

#define XSPI_INTR_MODE_FAULT		0x01	/* Mode fault error */
#define XSPI_INTR_SLAVE_MODE_FAULT	0x02	/* Selected as slave while
						 * disabled */
#define XSPI_INTR_TX_EMPTY		0x04	/* TxFIFO is empty */
#define XSPI_INTR_TX_UNDERRUN		0x08	/* TxFIFO was underrun */
#define XSPI_INTR_RX_FULL		0x10	/* RxFIFO is full */
#define XSPI_INTR_RX_OVERRUN		0x20	/* RxFIFO was overrun */
#define XSPI_INTR_TX_HALF_EMPTY		0x40	/* TxFIFO is half empty */

#define XIPIF_V123B_RESETR_OFFSET	0x40	/* IPIF reset register */
#define XIPIF_V123B_RESET_MASK		0x0a	/* the value to write */

struct xilinx_spi {
	/* bitbang has to be first */
	struct spi_bitbang bitbang;
	struct completion done;
	struct resource mem; /* phys mem */
	void __iomem	*regs;	/* virt. address of the control registers */

	u32		irq;

	u8 *rx_ptr;		/* pointer in the Tx buffer */
	const u8 *tx_ptr;	/* pointer in the Rx buffer */
	int remaining_bytes;	/* the number of bytes left to transfer */
	u8 bits_per_word;
	unsigned int (*read_fn) (void __iomem *);
	void (*write_fn) (u32, void __iomem *);
	void (*tx_fn) (struct xilinx_spi *);
	void (*rx_fn) (struct xilinx_spi *);
};

static void xspi_write32(u32 val, void __iomem *addr)
{
	iowrite32(val, addr);
}

static unsigned int xspi_read32(void __iomem *addr)
{
	return ioread32(addr);
}

static void xspi_write32_be(u32 val, void __iomem *addr)
{
	iowrite32be(val, addr);
}

static unsigned int xspi_read32_be(void __iomem *addr)
{
	return ioread32be(addr);
}

static void xspi_tx8(struct xilinx_spi *xspi)
{
	xspi->write_fn(*xspi->tx_ptr, xspi->regs + XSPI_TXD_OFFSET);
	xspi->tx_ptr++;
}

static void xspi_tx16(struct xilinx_spi *xspi)
{
	xspi->write_fn(*(u16 *)(xspi->tx_ptr), xspi->regs + XSPI_TXD_OFFSET);
	xspi->tx_ptr += 2;
}

static void xspi_tx32(struct xilinx_spi *xspi)
{
	xspi->write_fn(*(u32 *)(xspi->tx_ptr), xspi->regs + XSPI_TXD_OFFSET);
	xspi->tx_ptr += 4;
}

static void xspi_rx8(struct xilinx_spi *xspi)
{
	u32 data = xspi->read_fn(xspi->regs + XSPI_RXD_OFFSET);
	if (xspi->rx_ptr) {
		*xspi->rx_ptr = data & 0xff;
		xspi->rx_ptr++;
	}
}

static void xspi_rx16(struct xilinx_spi *xspi)
{
	u32 data = xspi->read_fn(xspi->regs + XSPI_RXD_OFFSET);
	if (xspi->rx_ptr) {
		*(u16 *)(xspi->rx_ptr) = data & 0xffff;
		xspi->rx_ptr += 2;
	}
}

static void xspi_rx32(struct xilinx_spi *xspi)
{
	u32 data = xspi->read_fn(xspi->regs + XSPI_RXD_OFFSET);
	if (xspi->rx_ptr) {
		*(u32 *)(xspi->rx_ptr) = data;
		xspi->rx_ptr += 4;
	}
}

static void xspi_init_hw(struct xilinx_spi *xspi)
{
	void __iomem *regs_base = xspi->regs;

	/* Reset the SPI device */
	xspi->write_fn(XIPIF_V123B_RESET_MASK,
		regs_base + XIPIF_V123B_RESETR_OFFSET);
	/* Disable all the interrupts just in case */
	xspi->write_fn(0, regs_base + XIPIF_V123B_IIER_OFFSET);
	/* Enable the global IPIF interrupt */
	xspi->write_fn(XIPIF_V123B_GINTR_ENABLE,
		regs_base + XIPIF_V123B_DGIER_OFFSET);
	/* Deselect the slave on the SPI bus */
	xspi->write_fn(0xffff, regs_base + XSPI_SSR_OFFSET);
	/* Disable the transmitter, enable Manual Slave Select Assertion,
	 * put SPI controller into master mode, and enable it */
	xspi->write_fn(XSPI_CR_TRANS_INHIBIT | XSPI_CR_MANUAL_SSELECT |
		XSPI_CR_MASTER_MODE | XSPI_CR_ENABLE | XSPI_CR_TXFIFO_RESET |
		XSPI_CR_RXFIFO_RESET, regs_base + XSPI_CR_OFFSET);
}

static void xilinx_spi_chipselect(struct spi_device *spi, int is_on)
{
	struct xilinx_spi *xspi = spi_master_get_devdata(spi->master);

	if (is_on == BITBANG_CS_INACTIVE) {
		/* Deselect the slave on the SPI bus */
		xspi->write_fn(0xffff, xspi->regs + XSPI_SSR_OFFSET);
	} else if (is_on == BITBANG_CS_ACTIVE) {
		/* Set the SPI clock phase and polarity */
		u16 cr = xspi->read_fn(xspi->regs + XSPI_CR_OFFSET)
			 & ~XSPI_CR_MODE_MASK;
		if (spi->mode & SPI_CPHA)
			cr |= XSPI_CR_CPHA;
		if (spi->mode & SPI_CPOL)
			cr |= XSPI_CR_CPOL;
		xspi->write_fn(cr, xspi->regs + XSPI_CR_OFFSET);

		/* We do not check spi->max_speed_hz here as the SPI clock
		 * frequency is not software programmable (the IP block design
		 * parameter)
		 */

		/* Activate the chip select */
		xspi->write_fn(~(0x0001 << spi->chip_select),
			xspi->regs + XSPI_SSR_OFFSET);
	}
}

/* spi_bitbang requires custom setup_transfer() to be defined if there is a
 * custom txrx_bufs(). We have nothing to setup here as the SPI IP block
 * supports 8 or 16 bits per word which cannot be changed in software.
 * SPI clock can't be changed in software either.
 * Check for correct bits per word. Chip select delay calculations could be
 * added here as soon as bitbang_work() can be made aware of the delay value.
 */
static int xilinx_spi_setup_transfer(struct spi_device *spi,
		struct spi_transfer *t)
{
	struct xilinx_spi *xspi = spi_master_get_devdata(spi->master);
	u8 bits_per_word;

	bits_per_word = (t && t->bits_per_word)
			 ? t->bits_per_word : spi->bits_per_word;
	if (bits_per_word != xspi->bits_per_word) {
		dev_err(&spi->dev, "%s, unsupported bits_per_word=%d\n",
			__func__, bits_per_word);
		return -EINVAL;
	}

	return 0;
}

static int xilinx_spi_setup(struct spi_device *spi)
{
	/* always return 0, we can not check the number of bits.
	 * There are cases when SPI setup is called before any driver is
	 * there, in that case the SPI core defaults to 8 bits, which we
	 * do not support in some cases. But if we return an error, the
	 * SPI device would not be registered and no driver can get hold of it
	 * When the driver is there, it will call SPI setup again with the
	 * correct number of bits per transfer.
	 * If a driver setups with the wrong bit number, it will fail when
	 * it tries to do a transfer
	 */
	return 0;
}

static void xilinx_spi_fill_tx_fifo(struct xilinx_spi *xspi)
{
	u8 sr;

	/* Fill the Tx FIFO with as many bytes as possible */
	sr = xspi->read_fn(xspi->regs + XSPI_SR_OFFSET);
	while ((sr & XSPI_SR_TX_FULL_MASK) == 0 && xspi->remaining_bytes > 0) {
		if (xspi->tx_ptr)
			xspi->tx_fn(xspi);
		else
			xspi->write_fn(0, xspi->regs + XSPI_TXD_OFFSET);
		xspi->remaining_bytes -= xspi->bits_per_word / 8;
		sr = xspi->read_fn(xspi->regs + XSPI_SR_OFFSET);
	}
}

static int xilinx_spi_txrx_bufs(struct spi_device *spi, struct spi_transfer *t)
{
	struct xilinx_spi *xspi = spi_master_get_devdata(spi->master);
	u32 ipif_ier;

	/* We get here with transmitter inhibited */

	xspi->tx_ptr = t->tx_buf;
	xspi->rx_ptr = t->rx_buf;
	xspi->remaining_bytes = t->len;
	INIT_COMPLETION(xspi->done);

	/* Enable the transmit empty interrupt, which we use to determine
	 * progress on the transmission.
	 */
	ipif_ier = xspi->read_fn(xspi->regs + XIPIF_V123B_IIER_OFFSET);
	xspi->write_fn(ipif_ier | XSPI_INTR_TX_EMPTY,
		xspi->regs + XIPIF_V123B_IIER_OFFSET);

	for (;;) {
		u16 cr;
		u8 sr;

		xilinx_spi_fill_tx_fifo(xspi);

		/* Start the transfer by not inhibiting the transmitter any
		 * longer
		 */
		cr = xspi->read_fn(xspi->regs + XSPI_CR_OFFSET) &
							~XSPI_CR_TRANS_INHIBIT;
		xspi->write_fn(cr, xspi->regs + XSPI_CR_OFFSET);

		wait_for_completion(&xspi->done);

		/* A transmit has just completed. Process received data and
		 * check for more data to transmit. Always inhibit the
		 * transmitter while the Isr refills the transmit register/FIFO,
		 * or make sure it is stopped if we're done.
		 */
		cr = xspi->read_fn(xspi->regs + XSPI_CR_OFFSET);
		xspi->write_fn(cr | XSPI_CR_TRANS_INHIBIT,
			       xspi->regs + XSPI_CR_OFFSET);

		/* Read out all the data from the Rx FIFO */
		sr = xspi->read_fn(xspi->regs + XSPI_SR_OFFSET);
		while ((sr & XSPI_SR_RX_EMPTY_MASK) == 0) {
			xspi->rx_fn(xspi);
			sr = xspi->read_fn(xspi->regs + XSPI_SR_OFFSET);
		}

		/* See if there is more data to send */
		if (xspi->remaining_bytes <= 0)
			break;
	}

	/* Disable the transmit empty interrupt */
	xspi->write_fn(ipif_ier, xspi->regs + XIPIF_V123B_IIER_OFFSET);

	return t->len - xspi->remaining_bytes;
}

/* This driver supports single master mode only. Hence Tx FIFO Empty
 * is the only interrupt we care about.
 * Receive FIFO Overrun, Transmit FIFO Underrun, Mode Fault, and Slave Mode
 * Fault are not to happen.
 */
static irqreturn_t xilinx_spi_irq(int irq, void *dev_id)
{
	struct xilinx_spi *xspi = dev_id;
	u32 ipif_isr;

	/* Get the IPIF interrupts, and clear them immediately */
	ipif_isr = xspi->read_fn(xspi->regs + XIPIF_V123B_IISR_OFFSET);
	xspi->write_fn(ipif_isr, xspi->regs + XIPIF_V123B_IISR_OFFSET);

	if (ipif_isr & XSPI_INTR_TX_EMPTY) {	/* Transmission completed */
		complete(&xspi->done);
	}

	return IRQ_HANDLED;
}

static const struct of_device_id xilinx_spi_of_match[] = {
	{ .compatible = "xlnx,xps-spi-2.00.a", },
	{ .compatible = "xlnx,xps-spi-2.00.b", },
	{}
};
MODULE_DEVICE_TABLE(of, xilinx_spi_of_match);

struct spi_master *xilinx_spi_init(struct device *dev, struct resource *mem,
	u32 irq, s16 bus_num, int num_cs, int little_endian, int bits_per_word)
{
	struct spi_master *master;
	struct xilinx_spi *xspi;
	int ret;

	master = spi_alloc_master(dev, sizeof(struct xilinx_spi));
	if (!master)
		return NULL;

	/* the spi->mode bits understood by this driver: */
	master->mode_bits = SPI_CPOL | SPI_CPHA;

	xspi = spi_master_get_devdata(master);
	xspi->bitbang.master = spi_master_get(master);
	xspi->bitbang.chipselect = xilinx_spi_chipselect;
	xspi->bitbang.setup_transfer = xilinx_spi_setup_transfer;
	xspi->bitbang.txrx_bufs = xilinx_spi_txrx_bufs;
	xspi->bitbang.master->setup = xilinx_spi_setup;
	init_completion(&xspi->done);

	if (!request_mem_region(mem->start, resource_size(mem),
		XILINX_SPI_NAME))
		goto put_master;

	xspi->regs = ioremap(mem->start, resource_size(mem));
	if (xspi->regs == NULL) {
		dev_warn(dev, "ioremap failure\n");
		goto map_failed;
	}

	master->bus_num = bus_num;
	master->num_chipselect = num_cs;
	master->dev.of_node = dev->of_node;

	xspi->mem = *mem;
	xspi->irq = irq;
	if (little_endian) {
		xspi->read_fn = xspi_read32;
		xspi->write_fn = xspi_write32;
	} else {
		xspi->read_fn = xspi_read32_be;
		xspi->write_fn = xspi_write32_be;
	}
	xspi->bits_per_word = bits_per_word;
	if (xspi->bits_per_word == 8) {
		xspi->tx_fn = xspi_tx8;
		xspi->rx_fn = xspi_rx8;
	} else if (xspi->bits_per_word == 16) {
		xspi->tx_fn = xspi_tx16;
		xspi->rx_fn = xspi_rx16;
	} else if (xspi->bits_per_word == 32) {
		xspi->tx_fn = xspi_tx32;
		xspi->rx_fn = xspi_rx32;
	} else
		goto unmap_io;

	/* SPI controller initializations */
	xspi_init_hw(xspi);

	/* Register for SPI Interrupt */
	ret = request_irq(xspi->irq, xilinx_spi_irq, 0, XILINX_SPI_NAME, xspi);
	if (ret)
		goto unmap_io;

	ret = spi_bitbang_start(&xspi->bitbang);
	if (ret) {
		dev_err(dev, "spi_bitbang_start FAILED\n");
		goto free_irq;
	}

	dev_info(dev, "at 0x%08llX mapped to 0x%p, irq=%d\n",
		(unsigned long long)mem->start, xspi->regs, xspi->irq);
	return master;

free_irq:
	free_irq(xspi->irq, xspi);
unmap_io:
	iounmap(xspi->regs);
map_failed:
	release_mem_region(mem->start, resource_size(mem));
put_master:
	spi_master_put(master);
	return NULL;
}
EXPORT_SYMBOL(xilinx_spi_init);

void xilinx_spi_deinit(struct spi_master *master)
{
	struct xilinx_spi *xspi;

	xspi = spi_master_get_devdata(master);

	spi_bitbang_stop(&xspi->bitbang);
	free_irq(xspi->irq, xspi);
	iounmap(xspi->regs);

	release_mem_region(xspi->mem.start, resource_size(&xspi->mem));
	spi_master_put(xspi->bitbang.master);
}
EXPORT_SYMBOL(xilinx_spi_deinit);

static int xilinx_spi_probe(struct platform_device *dev)
{
	struct xspi_platform_data *pdata;
	struct resource *r;
	int irq, num_cs = 0, little_endian = 0, bits_per_word = 8;
	struct spi_master *master;
	u8 i;

	pdata = dev->dev.platform_data;
	if (pdata) {
		num_cs = pdata->num_chipselect;
		little_endian = pdata->little_endian;
		bits_per_word = pdata->bits_per_word;
	}

#ifdef CONFIG_OF
	if (dev->dev.of_node) {
		const __be32 *prop;
		int len;

		/* number of slave select bits is required */
		prop = of_get_property(dev->dev.of_node, "xlnx,num-ss-bits",
				       &len);
		if (prop && len >= sizeof(*prop))
			num_cs = __be32_to_cpup(prop);
	}
#endif

	if (!num_cs) {
		dev_err(&dev->dev, "Missing slave select configuration data\n");
		return -EINVAL;
	}

	r = platform_get_resource(dev, IORESOURCE_MEM, 0);
	if (!r)
		return -ENODEV;

	irq = platform_get_irq(dev, 0);
	if (irq < 0)
		return -ENXIO;

	master = xilinx_spi_init(&dev->dev, r, irq, dev->id, num_cs,
				 little_endian, bits_per_word);
	if (!master)
		return -ENODEV;

	if (pdata) {
		for (i = 0; i < pdata->num_devices; i++)
			spi_new_device(master, pdata->devices + i);
	}

	platform_set_drvdata(dev, master);
	return 0;
}

static int xilinx_spi_remove(struct platform_device *dev)
{
	xilinx_spi_deinit(platform_get_drvdata(dev));
	platform_set_drvdata(dev, 0);

	return 0;
}

/* work with hotplug and coldplug */
MODULE_ALIAS("platform:" XILINX_SPI_NAME);

static struct platform_driver xilinx_spi_driver = {
	.probe = xilinx_spi_probe,
	.remove = xilinx_spi_remove,
	.driver = {
		.name = XILINX_SPI_NAME,
		.owner = THIS_MODULE,
		.of_match_table = xilinx_spi_of_match,
	},
};
module_platform_driver(xilinx_spi_driver);

MODULE_AUTHOR("MontaVista Software, Inc. <source@mvista.com>");
MODULE_DESCRIPTION("Xilinx SPI driver");
MODULE_LICENSE("GPL");


text:
using Serilog.Sinks.MSSqlServer.Dependencies;
using Serilog.Sinks.MSSqlServer.Platform;
using Serilog.Sinks.MSSqlServer.Tests.TestUtils;
using Xunit;

namespace Serilog.Sinks.MSSqlServer.Tests.Dependencies
{
    [Trait(TestCategory.TraitName, TestCategory.Unit)]
    public class SinkDependenciesFactoryTests
    {
        private const string _connectionString = "Server=localhost;Database=LogTest;Integrated Security=SSPI;";
        private readonly MSSqlServerSinkOptions _sinkOptions;
        private readonly Serilog.Sinks.MSSqlServer.ColumnOptions _columnOptions;

        public SinkDependenciesFactoryTests()
        {
            _sinkOptions = new MSSqlServerSinkOptions { TableName = "LogEvents" };
            _columnOptions = new Serilog.Sinks.MSSqlServer.ColumnOptions();
        }

        [Fact]
        public void CreatesSinkDependenciesWithSqlTableCreator()
        {
            // Act
            var result = SinkDependenciesFactory.Create(_connectionString, _sinkOptions, null, _columnOptions, null);

            // Assert
            Assert.NotNull(result.SqlTableCreator);
            Assert.IsType<SqlTableCreator>(result.SqlTableCreator);
        }

        [Fact]
        public void CreatesSinkDependenciesWithDataTableCreator()
        {
            // Act
            var result = SinkDependenciesFactory.Create(_connectionString, _sinkOptions, null, _columnOptions, null);

            // Assert
            Assert.NotNull(result.DataTableCreator);
            Assert.IsType<DataTableCreator>(result.DataTableCreator);
        }

        [Fact]
        public void CreatesSinkDependenciesWithSqlBulkBatchWriter()
        {
            // Act
            var result = SinkDependenciesFactory.Create(_connectionString, _sinkOptions, null, _columnOptions, null);

            // Assert
            Assert.NotNull(result.SqlBulkBatchWriter);
            Assert.IsType<SqlBulkBatchWriter>(result.SqlBulkBatchWriter);
        }

        [Fact]
        public void CreatesSinkDependenciesWithSqlLogEventWriter()
        {
            // Act
            var result = SinkDependenciesFactory.Create(_connectionString, _sinkOptions, null, _columnOptions, null);

            // Assert
            Assert.NotNull(result.SqlLogEventWriter);
            Assert.IsType<SqlLogEventWriter>(result.SqlLogEventWriter);
        }

        [Fact]
        public void DefaultsColumnOptionsIfNull()
        {
            // Act (should not throw)
            SinkDependenciesFactory.Create(_connectionString, _sinkOptions, null, null, null);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.sqoop.mapreduce.db;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.util.ReflectionUtils;
import org.apache.sqoop.mapreduce.sqlserver.SqlServerRecordReader;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.TaskAttemptContext;

import com.cloudera.sqoop.mapreduce.db.DBConfiguration;
import com.cloudera.sqoop.mapreduce.db.DBInputFormat;
import com.cloudera.sqoop.mapreduce.db.DataDrivenDBInputFormat;

import  org.apache.sqoop.lib.SqoopRecord;

/**
 * A RecordReader that reads records from a SQL table.
 * This record reader handles connection failures using the configured
 * connection failure handler
 */
public class SQLServerDBRecordReader<T extends SqoopRecord> extends
      SqlServerRecordReader<T> {

  private static final Log LOG =
      LogFactory.getLog(SQLServerDBRecordReader.class);

  // The SQL handler to be used for recovering failed read operations
  protected SQLFailureHandler failureHandler = null;

  // Recover failed reads for RETRY_MAX
  protected static final int RETRY_MAX = 3;

  // Name of the split column used to re-generate selectQueries after
  // connection failures
  private String splitColumn;
  private String lastRecordKey;

  public SQLServerDBRecordReader(DBInputFormat.DBInputSplit split,
      Class<T> inputClass, Configuration conf, Connection conn,
      DBConfiguration dbConfig, String cond, String [] fields, String table,
      String dbProduct) throws SQLException {
    super(split, inputClass, conf, conn, dbConfig, cond, fields, table);
  }

  @Override
  /** {@inheritDoc} */
  public T getCurrentValue() {
    T val = super.getCurrentValue();
    // Lookup the key of the last read record to use for recovering
    // As documented, the map may not be null, though it may be empty.
    Object lastRecordSplitCol = val.getFieldMap().get(splitColumn);
    lastRecordKey = (lastRecordSplitCol == null) ? null
        : lastRecordSplitCol.toString();
    return val;
  }

  /**
   * Load the SQLFailureHandler configured for use by the record reader.
   */
  public void initialize(InputSplit inputSplit, TaskAttemptContext context)
      throws IOException, InterruptedException {
    // Load the configured connection failure handler
    Configuration conf = getConf();
    if (conf == null) {
      LOG.error("Configuration cannot be NULL");
    }

    Class connHandlerClass;
    try {
      String className = conf.get(
        SQLServerDBInputFormat.IMPORT_FAILURE_HANDLER_CLASS);

      // Get the class-name set in configuration
      connHandlerClass = conf.getClassByName(className);
    } catch (ClassNotFoundException ex) {
      LOG.error("Failed to find class: "
        + SQLServerDBInputFormat.IMPORT_FAILURE_HANDLER_CLASS);
      throw new IOException(ex);
    }

    // Verify handler class is a subclass of SQLFailureHandler
    if (!SQLFailureHandler.class.isAssignableFrom(connHandlerClass)) {
      String error = "A subclass of " + SQLFailureHandler.class.getName()
        + " is expected. Actual class set is: " + connHandlerClass.getName();
      LOG.error(error);
      throw new IOException(error);
    }
    LOG.trace("Using connection handler class: " + connHandlerClass);

    // Load the configured connection failure handler
    failureHandler = ReflectionUtils.newInstance(
      (Class<? extends SQLFailureHandler>)connHandlerClass, conf);

    // Initialize the connection handler with using job configuration
    failureHandler.initialize(conf);

    // Get the split-by column
    splitColumn = getDBConf().getInputOrderBy();
    if (splitColumn == null || splitColumn.length() == 0) {
      throw new IOException("Split column must be set");
    }

    // Ensure the split-column is not escaped so that we can use it to search
    // in the record map
    int splitColLen = splitColumn.length();
    if (splitColLen > 2 && splitColumn.charAt(0) == '['
      && splitColumn.charAt(splitColLen-1) == ']') {
      splitColumn = splitColumn.substring(1, splitColLen - 1);
    }
  }

  @Override
  /**
   * Read the next key, value pair.
   * Try to recover failed connections using the configured connection failure
   * handler before retrying the failed operation
   */
  public boolean nextKeyValue() throws IOException {
    boolean valueReceived = false;
    int retryCount = RETRY_MAX;
    boolean doRetry = true;

    do {
      try {
        // Try to get the next key/value pairs
        valueReceived = super.nextKeyValue();
        doRetry = false;
      } catch (IOException ioEx) {
        LOG.warn("Trying to recover from DB read failure: ", ioEx);
        Throwable cause = ioEx.getCause();

        // Use configured connection handler to recover from the connection
        // failure and use the newly constructed connection.
        // If the failure cannot be recovered, an exception is thrown
        if (failureHandler.canHandleFailure(cause)) {
          // Recover from connection failure
          Connection conn = failureHandler.recover();

          // Configure the new connection before using it
          configureConnection(conn);
          setConnection(conn);

          --retryCount;
          doRetry = (retryCount >= 0);
        } else {
          // Cannot recovered using configured handler, re-throw
          throw new IOException("Cannection handler cannot recover failure: ",
              ioEx);
        }
      }
    } while (doRetry);

    // Rethrow the exception if all retry attempts are consumed
    if (retryCount < 0) {
      throw new IOException("Failed to read from database after "
        + RETRY_MAX + " retries.");
    }

    return valueReceived;
  }

  /**
   * Configure the provided Connection for record reads.
   */
  protected void configureConnection(Connection conn) throws IOException {
    try {
      conn.setAutoCommit(false);
      conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
    } catch (SQLException sqlEx) {
      LOG.error("Failed to configure SQL Connection");
      throw new IOException(sqlEx);
    }
  }

  /** Returns the query for selecting the records,
   * For handling connection recovery we always want to start from the last
   * record that was successfully read.
   */
  protected String getSelectQuery() {
    // Last seen record key is only expected to be unavailable if no reads
    // ever happened
    String selectQuery;
    if (lastRecordKey == null) {
      selectQuery = super.getSelectQuery();
    } else {
      // If last record key is available, construct the select query to start
      // from
      DataDrivenDBInputFormat.DataDrivenDBInputSplit dataSplit =
          (DataDrivenDBInputFormat.DataDrivenDBInputSplit) getSplit();
      StringBuilder lowerClause = new StringBuilder();
      lowerClause.append(getDBConf().getInputOrderBy());
      lowerClause.append(" > ");
      lowerClause.append(lastRecordKey.toString());

      // Get the select query with the lowerClause, and split upper clause
      selectQuery = getSelectQuery(lowerClause.toString(),
          dataSplit.getUpperClause());
    }

    return selectQuery;
  }
}


text:
local Shared = ...
local Msg, ErrMsg = Shared.Msg, Shared.ErrMsg
local MacroStep = Shared.MacroStep
local pack, loadmacro, utils = Shared.pack, Shared.loadmacro, Shared.utils
local MacroCallFar = Shared.MacroCallFar
local FarMacroCallToLua = Shared.FarMacroCallToLua
local GetLastParseError = Shared.GetLastParseError
Shared = nil

local F = far.Flags

-- enum MACROPLUGINRETURNTYPE
local MPRT_NORMALFINISH, MPRT_ERRORFINISH, MPRT_HASNOMACRO, MPRT_PLUGINCALL =
      F.MPRT_NORMALFINISH, F.MPRT_ERRORFINISH, F.MPRT_HASNOMACRO, F.MPRT_PLUGINCALL

-- enum FARMACROSTATE
local MACROSTATE_NOMACRO, MACROSTATE_EXECUTING, MACROSTATE_EXECUTING_COMMON =
      F.MACROSTATE_NOMACRO, F.MACROSTATE_EXECUTING, F.MACROSTATE_EXECUTING_COMMON

-- unsigned __int64 MACROFLAGS_MFLAGS
local MFLAGS_ENABLEOUTPUT, MFLAGS_NOSENDKEYSTOPLUGINS, MFLAGS_POSTFROMPLUGIN =
      0x1, 0x2, 0x10000000

local KEY_NONE = 0x30001
local MCODE_F_PLUGIN_CALL = 0x80C4F

local type, setmetatable = type, setmetatable
local bit = bit or bit64
local band, bor, bxor, lshift = bit.band, bit.bor, bit.bxor, bit.lshift
--------------------------------------------------------------------------------

local MCODE_F_KEYMACRO = 0x80C68
local Import = {
  RestoreMacroChar        = function()  return MacroCallFar(MCODE_F_KEYMACRO, 1) end,
  ScrBufLock              = function()  return MacroCallFar(MCODE_F_KEYMACRO, 2) end,
  ScrBufUnlock            = function()  return MacroCallFar(MCODE_F_KEYMACRO, 3) end,
  ScrBufResetLockCount    = function()  return MacroCallFar(MCODE_F_KEYMACRO, 4) end,
  ScrBufGetLockCount      = function()  return MacroCallFar(MCODE_F_KEYMACRO, 5) end,
  ScrBufSetLockCount      = function(v) return MacroCallFar(MCODE_F_KEYMACRO, 6, v) end,
  GetUseInternalClipboard = function()  return MacroCallFar(MCODE_F_KEYMACRO, 7) end,
  SetUseInternalClipboard = function(v) return MacroCallFar(MCODE_F_KEYMACRO, 8, v) end,
  KeyNameToKey            = function(v) return MacroCallFar(MCODE_F_KEYMACRO, 9, v) end,
  KeyToText               = function(v) return MacroCallFar(MCODE_F_KEYMACRO, 10, v) end,
}
--------------------------------------------------------------------------------

local NewMacroRecord do
  local MacroRecord = {
    m_id     = 0,   -- идентификатор загруженного макроса в плагине LuaMacro
    m_flags  = 0,   -- флаги макропоследовательности
    m_key    = -1,  -- назначенная клавиша
    m_textkey= nil, -- текстовое представление назначенной клавиши
    m_value  = nil, -- значение, хранимое исполняющимся макросом
    m_handle = nil, -- хэндл исполняющегося макроса
    m_area   = nil  -- макрообласть, из которой стартовал макрос
  }
  local meta = { __index=MacroRecord }

  function MacroRecord:GetFlags() return self.m_flags end
  function MacroRecord:SetFlags(f) self.m_flags=f end
  function MacroRecord:GetHandle() return self.m_handle end
  function MacroRecord:GetValue() return self.m_value end
  function MacroRecord:SetValue(val) self.m_value=val end
  function MacroRecord:GetStartArea() return self.m_area end

  function MacroRecord:SetHandle()
    local Id = self.m_id
    local chunk, params
    if Id.action then
      chunk, params = Id.action, Id.data
    elseif Id.code then
      chunk, params = loadmacro(Id.language, Id.code)
    elseif Id.HasFunction then
      chunk, params = Id[1], Id[2] -- macros started via MSSC_POST or from the command line
    else
      chunk, params = Id[1], function() return unpack(Id,2,Id.n) end -- macros started via mf.postmacro
    end
    if chunk then
      self.m_handle = { coro=coroutine.create(chunk), params=params, _store=nil }
      return true
    else
      return nil, params
    end
  end

  NewMacroRecord = function (MacroId, Flags, Key, TextKey)
    return setmetatable({m_id=MacroId, m_flags=Flags, m_key=Key, m_textkey=TextKey,
                         m_area=far.MacroGetArea() }, meta)
  end
end
--------------------------------------------------------------------------------

-- Специализированная очередь, оптимизированная для очередей макросов.
-- Оптимизация по скорости и памяти, имеет смысл при добавлении в цикле сотен тысяч элементов.
-- Данная оптимизация накладывает следующие ограничения (соблюдаемые в нашем случае):
--   Элементы должны быть таблицами.
--   Очередь добавляет в элементы поле _next.
--   Нельзя добавлять элемент в очередь, если он уже имеется в этой очереди.
local NewQueue do
  local queue = {}
  local meta = { __index=queue }
  function queue:add(v)
    if self.last ~= nil then
      self.last._next = v
      self.last = v
    else
      self.first, self.last = v, v
    end
  end
  function queue:addqueue(q)
    if q.last ~= nil then
      if self.last ~= nil then
        self.last._next = q.first
        self.last = q.last
      else
        self.first, self.last = q.first, q.last
      end
    end
  end
  function queue:remove()
    if self.first ~= nil then
      self.first = self.first._next
      if self.first==nil then self.last=nil end
    end
  end
  function queue:empty() return self.first==nil end
  NewQueue = function() return setmetatable({}, meta) end
end
--------------------------------------------------------------------------------

local NewMacroState do
  local MacroState = {
    IntKey = 0, -- "описание реально нажатой клавиши"
    HistoryDisableMask = 0,
    UseInternalClipboard = false,
    MacroQueue = nil
  }
  local meta = { __index=MacroState }
  function MacroState:GetCurMacro() return self.MacroQueue.first end
  function MacroState:RemoveCurMacro() self.MacroQueue:remove() end
  NewMacroState = function() return setmetatable({ MacroQueue=NewQueue() }, meta) end
end
--------------------------------------------------------------------------------

local NewStack do
  local stack = {}
  local meta = { __index=stack }
  function stack:top() return self[#self] end
  function stack:pop() local v=self[#self]; self[#self]=nil; return v; end
  function stack:push(v) self[#self+1]=v end
  function stack:empty() return self[1]==nil end
  NewStack = function() return setmetatable({}, meta) end
end
--------------------------------------------------------------------------------

local KeyMacro = {}
local CurState = NewMacroState()
local StateStack = NewStack()
local MacroIsRunning = 0
--------------------------------------------------------------------------------

local function GetCurMacro() return CurState:GetCurMacro() end
local function GetTopMacro() return StateStack[1] and StateStack:top():GetCurMacro() end
local function RemoveCurMacro() CurState:RemoveCurMacro() end

local function IsExecuting()
  local m = GetCurMacro()
  if m and m:GetHandle() then
    return band(m:GetFlags(),MFLAGS_NOSENDKEYSTOPLUGINS)~=0 and MACROSTATE_EXECUTING or MACROSTATE_EXECUTING_COMMON
  else
    return StateStack[1] and MACROSTATE_EXECUTING_COMMON or MACROSTATE_NOMACRO
  end
end

local function IsHistoryDisable (TypeHistory)
  local State = StateStack:top() or CurState
  return State:GetCurMacro() and band(State.HistoryDisableMask, lshift(1,TypeHistory))~=0 and 1 or 0
end

local function IsDisableOutput()
  local m = GetCurMacro()
  return m and band(m:GetFlags(),MFLAGS_ENABLEOUTPUT)==0 and 1 or 0
end

local function PushState (withClip)
  if withClip then
    CurState.UseInternalClipboard = Import.GetUseInternalClipboard()
  end
  StateStack:push(CurState)
  CurState = NewMacroState()
end

local function PopState (withClip)
  if StateStack[1] then
    StateStack:top().MacroQueue:addqueue(CurState.MacroQueue)
    CurState = StateStack:pop()
    if withClip then
      Import.SetUseInternalClipboard(CurState.UseInternalClipboard)
    end
  end
end

function KeyMacro.InitInternalVars (InitedRAM)
  if InitedRAM then
    CurState.MacroQueue = NewQueue()
  end
  CurState.HistoryDisableMask = 0
end

function KeyMacro.mmode (Action, Value)     -- N=MMode(Action[,Value])
  local TopMacro = GetTopMacro()
  if not TopMacro then return false end

  local result = 0
  local flags = TopMacro:GetFlags()
  if Action==1 then -- enable/disable output
    result = band(flags, MFLAGS_ENABLEOUTPUT)==1 and 0 or 1
    if (Value==0 or Value==1 or Value==2) and Value~=result then
      TopMacro:SetFlags(bxor(flags, MFLAGS_ENABLEOUTPUT))
      far.Text() -- M#2389: mmode(1,x): вывод на экран включается/отключается не вовремя
    end
  elseif Action==2 then -- get MacroRecord flags
    result = bor(lshift(flags,8), TopMacro:GetStartArea())
  end
  return result
end

local function ACall (macro, param)
  local EntryStackSize = #StateStack
  macro:SetValue(true)
  PushState(true)

  local lockCount = Import.ScrBufGetLockCount()
  Import.ScrBufSetLockCount(0)

  local Result = pack(param[1](unpack(param,2,param.n)))

  Import.ScrBufSetLockCount(lockCount)

  if #StateStack > EntryStackSize then
    PopState(true)
    macro:SetValue(Result)
  end
end

local function GetInputFromMacro()
  while true do
    while MacroIsRunning==0 and not GetCurMacro() do
      if StateStack[1] then
        PopState(true)
      else
        CurState = NewMacroState()
        return MPRT_HASNOMACRO
      end
    end

    local macro = GetCurMacro()
    if not macro then return end

    if not macro:GetHandle() then
      PushState(false)
      local ok, msg = macro:SetHandle()
      PopState(false)
      if not ok then
        RemoveCurMacro()
        Import.RestoreMacroChar()
        ErrMsg(msg)
        return
      end
    end

    Import.ScrBufResetLockCount()

    local OldCurState = CurState
    MacroIsRunning = MacroIsRunning + 1
    PushState(false)
    local value, handle = macro:GetValue(), macro:GetHandle()
    local r1,r2
    if type(value) == "userdata" then  -- Plugin.Call/SyncCall
      r1,r2 = MacroStep(handle, FarMacroCallToLua(value))
    elseif type(value) == "table" then -- mf.acall, eval
      r1,r2 = MacroStep(handle, unpack(value,1,value.n))
    elseif value ~= nil then           -- Plugin.Menu/Config/Command, ...
      r1,r2 = MacroStep(handle, value)
    else
      r1,r2 = MacroStep(handle)
    end
    PopState(false)
    macro:SetValue(nil)
    MacroIsRunning = MacroIsRunning - 1

    if band(macro:GetFlags(),MFLAGS_ENABLEOUTPUT) == 0 then
      Import.ScrBufLock()
    end

    if r1 == MPRT_NORMALFINISH or r1 == MPRT_ERRORFINISH then
      if macro.caller then
        macro.caller:SetValue(r1==MPRT_NORMALFINISH and r2)
      end
      if band(macro:GetFlags(),MFLAGS_ENABLEOUTPUT) == 0 then
        Import.ScrBufUnlock()
      end
      OldCurState:RemoveCurMacro()
      if not GetCurMacro() then
        Import.RestoreMacroChar()
      end
      for k = #macro,1,-1 do -- exit handlers
        local tbl = macro[k]
        tbl.func(unpack(tbl, 1, tbl.n))
      end
    elseif r1 == MPRT_PLUGINCALL then
      KeyMacro.CallPlugin(r2, true)
    elseif r1 == "acall" then
      ACall(macro, r2)
    elseif r1 == "eval" then
      local m = r2[1]
      PushState(true)
      KeyMacro.PostNewMacro(m, m.flags, r2[2], false).caller = macro
    else
      return r1,r2
    end
  end
end

-- (1) mf.eval        (2) keypress macro   (3) mf.postmacro
-- (4) command line   (5) macro browser    (6) autostarting macros
function KeyMacro.PostNewMacro (macroId, flags, textKey, postFromPlugin)
  flags = flags or 0
  if postFromPlugin then
    flags = bor(flags, MFLAGS_POSTFROMPLUGIN)
  end
  local aKey = textKey and Import.KeyNameToKey(textKey) or 0
  local macro = NewMacroRecord(macroId, flags, aKey, textKey)
  CurState.MacroQueue:add(macro)
  return macro
end

local function TryToPostMacro (Mode, TextKey, IntKey)
  local m = utils.GetMacro(Mode, TextKey, true, false)
  if m then
    if m.index then
      KeyMacro.PostNewMacro(m, m.flags, TextKey, false)
      CurState.HistoryDisableMask = 0
      CurState.IntKey = IntKey
    end
    return true
  end
end

function KeyMacro.DisableHistory (Mask)
  Mask = type(Mask)=="number" and math.floor(Mask)
  local t = StateStack:top()
  local oldHistoryDisable = t and t.HistoryDisableMask or 0
  if t and Mask then t.HistoryDisableMask = Mask end
  return oldHistoryDisable
end

local function GetLastPressedKey()
  for level=#StateStack,1,-1 do
    local state = StateStack[level]
    local m = state:GetCurMacro()
    if m and 0~=band(m:GetFlags(),MFLAGS_POSTFROMPLUGIN) then return m.m_key end
    if state.IntKey > 0 then return state.IntKey end
  end
  return 0
end

--Mode = 0 - возвращается код клавиши, Mode = 1 - возвращается наименование клавиши.
--Type = 0 - возвращает реально нажатое сочетание, которым вызывался макрос,
--  Type = 1 - возвращает клавишу, на которую назначен макрос.
function KeyMacro.akey (Mode, Type)
  local TopMacro = GetTopMacro()
  if TopMacro then
    local IsCodeOutput = (tonumber(Mode) or 0) == 0
    local IsPressedKey = (tonumber(Type) or 0) == 0
    if IsPressedKey then
      local key = GetLastPressedKey()
      return IsCodeOutput and key or (key>0 and Import.KeyToText(key)) or ""
    else
      return IsCodeOutput and TopMacro.m_key or TopMacro.m_textkey or Import.KeyToText(TopMacro.m_key)
    end
  end
  return false
end

function KeyMacro.TransformKey (key)
  local lkey = key:lower()
  if lkey == "selword" then
    return 1
  elseif lkey == "xlat" then
    return 2
  elseif lkey == "akey" then
    if StateStack:empty() then return nil end
    local k = GetLastPressedKey()
    return 3, k > 0 and k or 0
  else
    local iKey = Import.KeyNameToKey(key)
    return 3, iKey==-1 and KEY_NONE or iKey
  end
end

function KeyMacro.CallPlugin (Params, AsyncCall)
  local Result = false
  if type(Params[1]) == "string" then
    local EntryStackSize = #StateStack

    if AsyncCall then
      Result = true
      GetCurMacro():SetValue(true)
      PushState(true)
    end

    local lockCount = Import.ScrBufGetLockCount()
    Import.ScrBufSetLockCount(0)
    local ResultCallPlugin = MacroCallFar(MCODE_F_PLUGIN_CALL, AsyncCall, unpack(Params,1,Params.n))
    Import.ScrBufSetLockCount(lockCount)

    local isSynchroCall = true
    if AsyncCall then
      if #StateStack > EntryStackSize then -- эта проверка нужна, т.к. PopState() мог уже быть вызван.
        PopState(true)
      else
        isSynchroCall = false
      end
    end

    if isSynchroCall then
      Result = ResultCallPlugin
      if AsyncCall then
        GetCurMacro():SetValue(Result)
      end
    end
  end
  return Result
end

function KeyMacro.AddExitHandler (func, ...)
  if type(func) == "function" then
    local TopMacro = GetTopMacro()
    if TopMacro then
      TopMacro[#TopMacro+1] = { n=select("#", ...); func=func; ... }
      return ...
    end
  end
end

local OP_ISEXECUTING              = 1
local OP_ISDISABLEOUTPUT          = 2
local OP_HISTORYDISABLEMASK       = 3
local OP_ISHISTORYDISABLE         = 4
local OP_ISTOPMACROOUTPUTDISABLED = 5
local OP_ISPOSTMACROENABLED       = 6
local OP_POSTNEWMACRO             = 7 -- comes not from Far
local OP_SETMACROVALUE            = 8
local OP_GETINPUTFROMMACRO        = 9
local OP_TRYTOPOSTMACRO           = 10 -- comes not from Far
local OP_GETLASTERROR             = 11

function KeyMacro.Dispatch (opcode, ...)
  local p1 = (...)
  if opcode == OP_ISEXECUTING then
    return IsExecuting()
  elseif opcode == OP_GETINPUTFROMMACRO then
    if not utils.LoadingInProgress() then return GetInputFromMacro() end
  elseif opcode == OP_ISDISABLEOUTPUT then
    return IsDisableOutput()
  elseif opcode == OP_HISTORYDISABLEMASK then
    local OldMask = CurState.HistoryDisableMask
    if p1 then CurState.HistoryDisableMask = p1 end
    return OldMask
  elseif opcode == OP_ISHISTORYDISABLE then
    return IsHistoryDisable(p1)
  elseif opcode==OP_ISTOPMACROOUTPUTDISABLED then
    local mr = GetTopMacro()
    return mr and 0==band(mr:GetFlags(),MFLAGS_ENABLEOUTPUT) and 1 or 0
  elseif opcode == OP_ISPOSTMACROENABLED then
    return not (IsExecuting() and GetCurMacro()) and 1 or 0
  elseif opcode == OP_POSTNEWMACRO then -- from API MacroControl(MSSC_POST)
    local Lang,Code,Flags,AKey,onlyCheck = ...
    local f1,f2 = loadmacro(Lang,Code)
    if f1 then
      CurState.MacroQueue:add(NewMacroRecord({ f1,f2,HasFunction=true },Flags,AKey))
      return true
    elseif not onlyCheck then
      ErrMsg(f2, Msg.MMacroParseErrorTitle)
    end
  elseif opcode == OP_SETMACROVALUE then
    local m = GetCurMacro()
    if m then m:SetValue(p1) end
  elseif opcode == OP_TRYTOPOSTMACRO then
    return TryToPostMacro(...)
  elseif opcode == OP_GETLASTERROR then
    return GetLastParseError()
  end
end

return KeyMacro


text:
@implementation ADTokenCacheKey

@synthesize authority = _authority;
@synthesize resource = _resource;
@synthesize clientId = _clientId;

- (void)calculateHash
{
    _hash = [[NSString stringWithFormat:@"##%@##%@##%@##", _authority, _resource, _clientId]
             hash];
}

- (id)initWithAuthority:(NSString *)authority
               resource:(NSString *)resource
               clientId:(NSString *)clientId
{
    if (!(self = [super init]))
    {
        return nil;
    }

    _authority = authority;
    _resource = resource;
    _clientId = clientId;

    [self calculateHash];

    return self;
}

+ (id)keyWithAuthority:(NSString *)authority
              resource:(NSString *)resource
              clientId:(NSString *)clientId
                 error:(ADAuthenticationError * __autoreleasing *)error
{
    API_ENTRY;
    // Trim first for faster nil or empty checks. Also lowercase and trimming is
    // needed to ensure that the cache handles correctly same items with different
    // character case:
    authority = [ADHelpers canonicalizeAuthority:authority];
    resource = resource.adTrimmedString.lowercaseString;
    clientId = clientId.adTrimmedString.lowercaseString;
    RETURN_NIL_ON_NIL_ARGUMENT(authority);
    RETURN_NIL_ON_NIL_EMPTY_ARGUMENT(clientId);

    ADTokenCacheKey* key = [[ADTokenCacheKey alloc] initWithAuthority:authority resource:resource clientId:clientId];
    return key;
}

- (NSUInteger)hash
{
    return _hash;
}

- (BOOL)isEqual:(id)object
{
    if (!object)
    {
        return NO;
    }

    if (![object isKindOfClass:[ADTokenCacheKey class]])
    {
        return NO;
    }

    ADTokenCacheKey* key = object;

    //First check the fields which cannot be nil:
    if (![self.authority isEqualToString:key.authority] ||
        ![self.clientId isEqualToString:key.clientId])
    {
        return NO;
    }

    //Now handle the case of nil resource:
    if (!self.resource)
    {
        return !key.resource;//Both should be nil to be equal
    }
    else
    {
        return [self.resource isEqualToString:key.resource];
    }
}

- (void)encodeWithCoder:(NSCoder *)aCoder
{
    [aCoder encodeObject:self.authority forKey:@"authority"];
    [aCoder encodeObject:self.resource forKey:@"resource"];
    [aCoder encodeObject:self.clientId forKey:@"clientId"];
}

- (id)initWithCoder:(NSCoder *)aDecoder
{
    if (!(self = [super init]))
    {
        return nil;
    }

    _authority = [aDecoder decodeObjectOfClass:[NSString class] forKey:@"authority"];
    _resource = [aDecoder decodeObjectOfClass:[NSString class] forKey:@"resource"];
    _clientId = [aDecoder decodeObjectOfClass:[NSString class] forKey:@"clientId"];

    [self calculateHash];

    return self;
}

+ (BOOL)supportsSecureCoding
{
    return YES;
}

- (id)copyWithZone:(NSZone *) zone
{
    ADTokenCacheKey* key = [[ADTokenCacheKey allocWithZone:zone] init];

    key->_authority = [_authority copyWithZone:zone];
    key->_clientId = [_clientId copyWithZone:zone];
    key->_resource = [_resource copyWithZone:zone];

    [key calculateHash];

    return key;
}

@end


text:
architecture wdc65816-strict

define MEMORY_MAP = LOROM
define ROM_SIZE = 1

include "../../../src/common/assert.inc"
include "../../../src/common/memory.inc"
include "../../../src/common/tmp_words.inc"

createRamBlock(dp,     0x000000, 0x000100)
createRamBlock(shadow, 0x7e0100, 0x7e1f80)
createRamBlock(stack,  0x7e1f80, 0x7e1fff)

namespace test {
    // test requesting a tmp before it's marked

    allocateTmpWord(tmp0)
    allocateTmpWord(tmp1)

    lda.w   tmp0
    sta.w   tmp1
}

allocate(dataBlock, shadow, 0x200)

markTmpWord(dataBlock + 0x0e)
markTmpWord(dataBlock + 0x1e)
markTmpWord(dataBlock + 0x2e)
markTmpWord(dataBlock + 0x3e)
markTmpWord(dataBlock + 0x4e)

namespace test {
    // test requesting a tmp after it's marked

    allocateTmpWord(tmp2)
    allocateTmpWord(tmp3)

    lda.w   tmp2
    sta.w   tmp3
}

assert(test.tmp2 == dataBlock + 0x2e)
assert(test.tmp3 == dataBlock + 0x3e)

// vim: ft=bass-65816 ts=4 sw=4 et:


text:
package org.ovirt.engine.api.resource;

import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.PathParam;
import javax.ws.rs.Path;
import javax.ws.rs.POST;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;

import org.ovirt.engine.api.model.Snapshot;
import org.ovirt.engine.api.model.Snapshots;

@Produces({ApiMediaType.APPLICATION_XML, ApiMediaType.APPLICATION_JSON, ApiMediaType.APPLICATION_X_YAML})
public interface SnapshotsResource {

    @GET
    public Snapshots list();

    @POST
    @Consumes({ApiMediaType.APPLICATION_XML, ApiMediaType.APPLICATION_JSON, ApiMediaType.APPLICATION_X_YAML})
    public Response add(Snapshot snapshot);

    @DELETE
    @Path("{id}")
    public Response remove(@PathParam("id") String id);

    /**
     * Sub-resource locator method, returns individual SnapshotResource on
     * which the remainder of the URI is dispatched.
     *
     * @param id  the snapshot ID
     * @return    matching subresource if found
     */
    @Path("{id}")
    public SnapshotResource getSnapshotSubResource(@PathParam("id") String id);
}


text:
'use strict';
const mongoose = require('mongoose');
const Promise = require('../lib/promise');
mongoose.Promise = Promise;
process.env.APP_SECRET = 'Secretkey';
require('./test_server');
require('./league_test');
require('./user_test');
require('./league_user_test');
process.on('exit', (code) => {
  mongoose.connection.db.dropDatabase(() => console.log('db dropped ' + code));
});


text: ALTER TABLE person MODIFY id NUMBER(10);


text:
ObjectAnimation::ObjectAnimation(std::string name, SceneObject *object)
{
	this->name=name;
	this->object=object;
	object->_getTransformPtr()->setIdentity();
	this->addAnimationListener();
}

ObjectAnimation::ObjectAnimation(void)
{
	name="";
	object=0;
}

ObjectAnimation::ObjectAnimation(const ObjectAnimation &c)
{
	name=c.name;
	object=c.object;
}

ObjectAnimation::~ObjectAnimation(void)
{
}

std::string &ObjectAnimation::getName(void){
	return name;
}

void ObjectAnimation::removeAnimationListener(void){
	nau::event_::IListener *lst;
	lst = this;
	EVENTMANAGER->removeListener("OBJECT_FRACTION",lst);
}

void ObjectAnimation::addAnimationListener(void){
	nau::event_::IListener *lst;
	lst = this;
	EVENTMANAGER->addListener("OBJECT_FRACTION",lst);
}

SceneObject *ObjectAnimation::getObject(void){
	return object;
}

void ObjectAnimation::eventReceived(const std::string &sender,
	const std::string &eventType, const std::shared_ptr<IEventData> &evt){

	vec3 *f=(vec3 *)evt->getData();
	vec3 fc=*f;

	if(object!=0){
		object->_getTransformPtr()->translate (fc);
	}
	std::shared_ptr<IEventData> e = EventFactory::Create("Vec3");
	e->setData(&fc);
	EVENTMANAGER->notifyEvent("OBJECT_POSITION", &name[0], "", e);
}


text:
extern "C"
{
#endif

//#define VUI_DEBUG

#ifdef VUI_DEBUG

#include <stdio.h>
#include <stdlib.h>

//#define VUI_DEBUG_TEST
//#define VUI_DEBUG_VUI
//#define VUI_DEBUG_TR
//#define VUI_DEBUG_STATEMACHINE
//#define VUI_DEBUG_GC
//#define VUI_DEBUG_STACK
//#define VUI_DEBUG_STRING
//#define VUI_DEBUG_UTF8

extern void vui_debugf(const char* format, ...);  // user must declare this

#endif

#ifdef __cplusplus
}
#endif

#endif


text:
import tealight from 'tealight'

import defaults from '../defaults'

import clean from '../methods/clean'

import style from '../functions/style'
import { Sequence } from '../functions/sequence'
import initialize from '../functions/initialize'

import each from '../../utils/each'
import logger from '../../utils/logger'
import isMobile from '../../utils/is-mobile'
import deepAssign from '../../utils/deep-assign'
import nextUniqueId from '../../utils/next-unique-id'

export default function reveal(target, options = {}, syncing = false) {
	const containerBuffer = []
	let sequence
	let interval = options.interval || defaults.interval

	try {
		if (interval) {
			sequence = new Sequence(interval)
		}

		const nodes = tealight(target)
		if (!nodes.length) {
			throw new Error('Invalid reveal target.')
		}

		const elements = nodes.reduce((elementBuffer, elementNode) => {
			const element = {}
			const existingId = elementNode.getAttribute('data-sr-id')

			if (existingId) {
				deepAssign(element, this.store.elements[existingId])

				/**
				 * In order to prevent previously generated styles
				 * from throwing off the new styles, the style tag
				 * has to be reverted to its pre-reveal state.
				 */
				element.node.setAttribute('style', element.styles.inline.computed)
			} else {
				element.id = nextUniqueId()
				element.node = elementNode
				element.seen = false
				element.revealed = false
				element.visible = false
			}

			const config = deepAssign({}, element.config || this.defaults, options)

			if ((!config.mobile && isMobile()) || (!config.desktop && !isMobile())) {
				if (existingId) {
					clean.call(this, element)
				}
				return elementBuffer // skip elements that are disabled
			}

			const containerNode = tealight(config.container)[0]
			if (!containerNode) {
				throw new Error('Invalid container.')
			}
			if (!containerNode.contains(elementNode)) {
				return elementBuffer // skip elements found outside the container
			}

			let containerId
			{
				containerId = getContainerId(
					containerNode,
					containerBuffer,
					this.store.containers
				)
				if (containerId === null) {
					containerId = nextUniqueId()
					containerBuffer.push({ id: containerId, node: containerNode })
				}
			}

			element.config = config
			element.containerId = containerId
			element.styles = style(element)

			if (sequence) {
				element.sequence = {
					id: sequence.id,
					index: sequence.members.length
				}
				sequence.members.push(element.id)
			}

			elementBuffer.push(element)
			return elementBuffer
		}, [])

		/**
		 * Modifying the DOM via setAttribute needs to be handled
		 * separately from reading computed styles in the map above
		 * for the browser to batch DOM changes (limiting reflows)
		 */
		each(elements, element => {
			this.store.elements[element.id] = element
			element.node.setAttribute('data-sr-id', element.id)
		})
	} catch (e) {
		return logger.call(this, 'Reveal failed.', e.message)
	}

	/**
	 * Now that element set-up is complete...
	 * Let's commit any container and sequence data we have to the store.
	 */
	each(containerBuffer, container => {
		this.store.containers[container.id] = {
			id: container.id,
			node: container.node
		}
	})
	if (sequence) {
		this.store.sequences[sequence.id] = sequence
	}

	/**
	 * If reveal wasn't invoked by sync, we want to
	 * make sure to add this call to the history.
	 */
	if (syncing !== true) {
		this.store.history.push({ target, options })

		/**
		 * Push initialization to the event queue, giving
		 * multiple reveal calls time to be interpreted.
		 */
		if (this.initTimeout) {
			window.clearTimeout(this.initTimeout)
		}
		this.initTimeout = window.setTimeout(initialize.bind(this), 0)
	}
}

function getContainerId(node, ...collections) {
	let id = null
	each(collections, collection => {
		each(collection, container => {
			if (id === null && container.node === node) {
				id = container.id
			}
		})
	})
	return id
}


text:
'use strong';

const vinylProps = require('./');
const File = require('vinyl');
const test = require('tape');

test('vinyl-properties', t => {
  t.plan(3);

  t.equal(vinylProps.name, 'vinylProperties', 'should have a function name.');

  t.throws(
    () => vinylProps(123),
    /TypeError.*must be a string or an array\./,
    'should throw a type error when the argument is neither string nor array.'
  );

  t.throws(
    () => vinylProps(['a', ['b'], 123]),
    /TypeError.*must be a string\./,
    'should throw a type error when the array contains non-string items.'
  );
});

test('vinyl-properties with an array of properties', t => {
  t.plan(3);

  const stream = vinylProps(['path', 'contents'])
  .on('finish', function() {
    t.deepEqual(
      this.contents,
      [null, new Buffer('a')],
      'should get file properties.'
    );
    t.deepEqual(
      this.path,
      ['foo', undefined],
      'should push `null` if the file does not have the target property.'
    );
    t.deepEqual(
      this.files,
      [
        {
          path: 'foo',
          contents: null
        },
        {
          path: undefined,
          contents: new Buffer('a')
        }
      ],
      'should set `files` property.'
    );
  });

  stream.write(new File({path: 'foo'}));
  stream.write(new File({contents: new Buffer('a')}));

  stream.end();
});

test('vinyl-properties with a property string', t => {
  t.plan(1);

  vinylProps('path')
  .on('finish', function() {
    t.deepEqual(this.path, ['bar'], 'should get file properties.');
  })
  .end(new File({path: 'bar'}));
});


text:
const searchKeywordIndex = (str, keyword, indexArr = []) => {
  const lastIndexPos = indexArr.length === 0 ? 0 : indexArr[indexArr.length - 1] + 1
  const index = str.indexOf(keyword, lastIndexPos)
  if (index === -1 || !str || !keyword) {
    return indexArr
  } else {
    return searchKeywordIndex(str, keyword, indexArr.concat([index]))
  }
}

const searchBraceIndex = (str, indexArr = []) => {
  return (searchKeywordIndex(str, '<').concat(searchKeywordIndex(str, '>'))).sort((a, b) => a - b)
}

const isIndexInBrace = (content, bracePos, index) => {
  switch (bracePos.length) {
    case 0 :
      return false
    case 1 :
      return false
    default :
      return (
        content[bracePos[0]] === '<' &&
        content[bracePos[1]] === '>' &&
        index > bracePos[0] &&
        index < bracePos[1]
      ) || isIndexInBrace(content, bracePos.slice(2), index)
  }
}

const breakContent = (content, len, validIndexes, prevPos = 0, splits = []) => {
  switch (validIndexes.length) {
    case 0:
      // concat the rest of the content
      return splits.concat([
        content.slice(Math.min(prevPos, content.length))
      ])
    default:
      const contentIndex = validIndexes[0]
      // break down into two part
      const s = splits.concat([
        content.slice(prevPos, contentIndex),
        content.slice(contentIndex, contentIndex + len)
      ])
      return breakContent(content, len, validIndexes.slice(1), contentIndex + len, s)
  }
}

const mergeAndInjectHightLightContent = (splits, hlContent = '') => {
  switch (splits.length) {
    case 0 :
      return hlContent
    case 1 :
      return `${hlContent}${splits[0]}`
    default :
      const merged = `${hlContent}${splits[0]}<span class="search-highlight">${splits[1]}</span>`
      return mergeAndInjectHightLightContent(splits.slice(2), merged)
  }
}

const searchAndInjectHighlightBetweenKeyword = (content, keyword) => {
  // find all brace for identify the html tag
  const bracePos = searchBraceIndex(content)

  // search the keyword position
  const validIndexes = searchKeywordIndex(content.toLowerCase(), keyword.toLowerCase())
    .filter(index => !isIndexInBrace(content, bracePos, index)) // we do not want accidentally search the html tag

  return {
    matches: validIndexes.length,
    hlContent: mergeAndInjectHightLightContent(breakContent(content, keyword.length, validIndexes))
  }
}

export const searchMultipleKeyword = (keywordArr, contentToSearch, result = { matches: 0 }) => {
  switch (keywordArr.length) {
    case 0 :
      return result.hlContent ? result : { matches: 0, hlContent: contentToSearch }
    default :
      const title = angular.element('<div/>').html(result.hlContent || contentToSearch).html()
      const [keyword, ...tail] = keywordArr

      const { matches, hlContent } = searchAndInjectHighlightBetweenKeyword(title, keyword)

      result = {
        matches: result.matches + matches,
        hlContent
      }

      return searchMultipleKeyword(tail, contentToSearch, result)
  }
}


text:
export default {
    index : "/popup/index.html",
    home : "/popup/index.html/home",
    configs : "/popup/index.html/configs",
    sponsor : '/popup/index.html/sponsor'
}


text:
package org.apache.qpid.protonj2.engine.impl;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNotSame;
import static org.junit.jupiter.api.Assertions.assertTrue;

import org.apache.qpid.protonj2.buffer.ProtonBuffer;
import org.apache.qpid.protonj2.buffer.ProtonByteBufferAllocator;
import org.apache.qpid.protonj2.engine.DeliveryTagGenerator;
import org.apache.qpid.protonj2.types.DeliveryTag;
import org.junit.jupiter.api.Test;

public class ProtonSequentialTagGeneratorTest {

    @Test
    public void testCreateTagGenerator() {
        DeliveryTagGenerator generator = ProtonDeliveryTagGenerator.BUILTIN.SEQUENTIAL.createGenerator();
        assertTrue(generator instanceof ProtonSequentialTagGenerator);
        assertNotNull(generator.toString());
    }

    @Test
    public void testCreateTag() {
        ProtonSequentialTagGenerator generator = new ProtonSequentialTagGenerator();

        assertNotNull(generator.nextTag());
    }

    @Test
    public void testCopyTag() {
        ProtonSequentialTagGenerator generator = new ProtonSequentialTagGenerator();
        DeliveryTag next = generator.nextTag();
        DeliveryTag copy = next.copy();

        assertNotSame(next, copy);
        assertEquals(next, copy);
    }

    @Test
    public void testTagEquals() {
        ProtonSequentialTagGenerator generator = new ProtonSequentialTagGenerator();

        DeliveryTag tag1 = generator.nextTag();
        DeliveryTag tag2 = generator.nextTag();
        DeliveryTag tag3 = generator.nextTag();

        assertEquals(tag1, tag1);
        assertNotEquals(tag1, tag2);
        assertNotEquals(tag2, tag3);
        assertNotEquals(tag1, tag3);

        assertNotEquals(null, tag1);
        assertNotEquals(tag1, null);
        assertNotEquals("something", tag1);
        assertNotEquals(tag2, "something");
    }

    @Test
    public void testCreateTagsThatAreEqual() {
        ProtonSequentialTagGenerator generator = new ProtonSequentialTagGenerator();

        generator.setNextTagId(42);
        DeliveryTag tag1 = generator.nextTag();

        generator.setNextTagId(42);
        DeliveryTag tag2 = generator.nextTag();

        assertNotSame(tag1, tag2);
        assertEquals(tag1, tag2);

        assertEquals(tag1.hashCode(), tag2.hashCode());
    }

    @Test
    public void testCreateTagsThatWrapAroundLimit() {
        ProtonSequentialTagGenerator generator = new ProtonSequentialTagGenerator();

        // Test that on wrap the tags start beyond the cached values.
        generator.setNextTagId(0xFFFFFFFFFFFFFFFFl);

        DeliveryTag maxUnsignedLong = generator.nextTag();
        DeliveryTag nextTagAfterWrap = generator.nextTag();

        assertEquals(Long.BYTES, maxUnsignedLong.tagBytes().length);
        assertEquals(Byte.BYTES, nextTagAfterWrap.tagBytes().length);
    }

    @Test
    public void testCreateMatchingValuesFromWrittenBuffer() {
        ProtonSequentialTagGenerator generator = new ProtonSequentialTagGenerator();
        ProtonBuffer buffer = ProtonByteBufferAllocator.DEFAULT.allocate(64);

        generator.setNextTagId(-127);                // Long
        generator.nextTag().writeTo(buffer);
        generator.setNextTagId(127);                 // Byte
        generator.nextTag().writeTo(buffer);
        generator.setNextTagId(256);                 // Short
        generator.nextTag().writeTo(buffer);
        generator.setNextTagId(65536);               // Int
        generator.nextTag().writeTo(buffer);
        generator.setNextTagId(0x00000001FFFFFFFFl); // Long
        generator.nextTag().writeTo(buffer);

        assertEquals(23, buffer.getReadableBytes());

        assertEquals(-127, buffer.readLong());
        assertEquals(127, buffer.readByte());
        assertEquals(256, buffer.readShort());
        assertEquals(65536, buffer.readInt());
        assertEquals(0x00000001FFFFFFFFl, buffer.readLong());
    }

    @Test
    public void testTagSizeMatchesValueRange() {
        ProtonSequentialTagGenerator generator = new ProtonSequentialTagGenerator();

        generator.setNextTagId(-127);
        assertEquals(Long.BYTES, generator.nextTag().tagLength());
        assertEquals(Long.BYTES, generator.nextTag().tagBytes().length);
        assertEquals(Long.BYTES, generator.nextTag().tagBuffer().getReadableBytes());

        generator.setNextTagId(127);
        assertEquals(Byte.BYTES, generator.nextTag().tagLength());
        assertEquals(Byte.BYTES, generator.nextTag().tagBytes().length);
        assertEquals(Byte.BYTES, generator.nextTag().tagBuffer().getReadableBytes());

        generator.setNextTagId(256);
        assertEquals(Short.BYTES, generator.nextTag().tagLength());
        assertEquals(Short.BYTES, generator.nextTag().tagBytes().length);
        assertEquals(Short.BYTES, generator.nextTag().tagBuffer().getReadableBytes());

        generator.setNextTagId(65536);
        assertEquals(Integer.BYTES, generator.nextTag().tagLength());
        assertEquals(Integer.BYTES, generator.nextTag().tagBytes().length);
        assertEquals(Integer.BYTES, generator.nextTag().tagBuffer().getReadableBytes());

        generator.setNextTagId(0x00000001FFFFFFFFl);
        assertEquals(Long.BYTES, generator.nextTag().tagLength());
        assertEquals(Long.BYTES, generator.nextTag().tagBytes().length);
        assertEquals(Long.BYTES, generator.nextTag().tagBuffer().getReadableBytes());
    }
}


text:
package org.kie.workbench.common.dmn.client.commands.expressions.types.dtable;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.kie.workbench.common.dmn.api.definition.model.DecisionRule;
import org.kie.workbench.common.dmn.api.definition.model.DecisionTable;
import org.kie.workbench.common.dmn.api.definition.model.InputClause;
import org.kie.workbench.common.dmn.api.definition.model.LiteralExpression;
import org.kie.workbench.common.dmn.api.definition.model.OutputClause;
import org.kie.workbench.common.dmn.api.definition.model.RuleAnnotationClause;
import org.kie.workbench.common.dmn.api.definition.model.RuleAnnotationClauseText;
import org.kie.workbench.common.dmn.api.definition.model.UnaryTests;
import org.kie.workbench.common.dmn.client.editors.expressions.types.dtable.InputClauseColumn;
import org.kie.workbench.common.dmn.client.editors.expressions.types.dtable.OutputClauseColumn;
import org.kie.workbench.common.dmn.client.editors.expressions.types.dtable.RuleAnnotationClauseColumn;
import org.kie.workbench.common.dmn.client.widgets.grid.model.DMNGridData;
import org.kie.workbench.common.stunner.core.client.canvas.AbstractCanvasHandler;
import org.kie.workbench.common.stunner.core.client.command.CanvasCommandResultBuilder;
import org.kie.workbench.common.stunner.core.client.command.CanvasViolation;
import org.kie.workbench.common.stunner.core.command.Command;
import org.kie.workbench.common.stunner.core.graph.command.GraphCommandExecutionContext;
import org.kie.workbench.common.stunner.core.graph.command.GraphCommandResultBuilder;
import org.kie.workbench.common.stunner.core.rule.RuleViolation;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.uberfire.ext.wires.core.grids.client.model.GridColumn;
import org.uberfire.ext.wires.core.grids.client.widget.grid.columns.RowNumberColumn;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public class MoveColumnsCommandTest {

    @Mock
    private RowNumberColumn uiRowNumberColumn;

    @Mock
    private InputClauseColumn uiInputClauseColumnOne;

    @Mock
    private InputClauseColumn uiInputClauseColumnTwo;

    @Mock
    private InputClauseColumn uiInputClauseColumnThree;

    @Mock
    private OutputClauseColumn uiOutputClauseColumnOne;

    @Mock
    private OutputClauseColumn uiOutputClauseColumnTwo;

    @Mock
    private OutputClauseColumn uiOutputClauseColumnThree;

    @Mock
    private RuleAnnotationClauseColumn uiRuleAnnotationClauseColumnOne;

    @Mock
    private RuleAnnotationClauseColumn uiRuleAnnotationClauseColumnTwo;

    @Mock
    private RuleAnnotationClauseColumn uiRuleAnnotationClauseColumnThree;

    @Mock
    private AbstractCanvasHandler canvasHandler;

    @Mock
    private GraphCommandExecutionContext graphCommandExecutionContext;

    private DecisionTable dtable;

    @Mock
    private InputClause inputClauseOne;

    @Mock
    private InputClause inputClauseTwo;

    @Mock
    private InputClause inputClauseThree;

    @Mock
    private OutputClause outputClauseOne;

    @Mock
    private OutputClause outputClauseTwo;

    @Mock
    private OutputClause outputClauseThree;

    @Mock
    private RuleAnnotationClause annotationClauseOne;

    @Mock
    private RuleAnnotationClause annotationClauseTwo;

    @Mock
    private RuleAnnotationClause annotationClauseThree;

    private DMNGridData uiModel;

    private MoveColumnsCommand command;

    private Command<GraphCommandExecutionContext, RuleViolation> graphCommand;

    private Command<AbstractCanvasHandler, CanvasViolation> canvasCommand;

    @Mock
    private org.uberfire.mvp.Command canvasOperation;

    @Before
    public void setUp() {
        this.dtable = new DecisionTable();
        this.uiModel = new DMNGridData();

        dtable.getInput().add(inputClauseOne);
        dtable.getInput().add(inputClauseTwo);
        dtable.getInput().add(inputClauseThree);
        dtable.getOutput().add(outputClauseOne);
        dtable.getOutput().add(outputClauseTwo);
        dtable.getOutput().add(outputClauseThree);
        dtable.getAnnotations().add(annotationClauseOne);
        dtable.getAnnotations().add(annotationClauseTwo);
        dtable.getAnnotations().add(annotationClauseThree);

        dtable.getRule().add(new DecisionRule() {{
            getInputEntry().add(new UnaryTests());
            getInputEntry().add(new UnaryTests());
            getInputEntry().add(new UnaryTests());
            getOutputEntry().add(new LiteralExpression());
            getOutputEntry().add(new LiteralExpression());
            getOutputEntry().add(new LiteralExpression());
            getAnnotationEntry().add(new RuleAnnotationClauseText());
            getAnnotationEntry().add(new RuleAnnotationClauseText());
            getAnnotationEntry().add(new RuleAnnotationClauseText());
        }});

        uiModel.appendColumn(uiRowNumberColumn);
        uiModel.appendColumn(uiInputClauseColumnOne);
        uiModel.appendColumn(uiInputClauseColumnTwo);
        uiModel.appendColumn(uiInputClauseColumnThree);
        uiModel.appendColumn(uiOutputClauseColumnOne);
        uiModel.appendColumn(uiOutputClauseColumnTwo);
        uiModel.appendColumn(uiOutputClauseColumnThree);
        uiModel.appendColumn(uiRuleAnnotationClauseColumnOne);
        uiModel.appendColumn(uiRuleAnnotationClauseColumnTwo);
        uiModel.appendColumn(uiRuleAnnotationClauseColumnThree);

        doReturn(0).when(uiRowNumberColumn).getIndex();
        doReturn(1).when(uiInputClauseColumnOne).getIndex();
        doReturn(2).when(uiInputClauseColumnTwo).getIndex();
        doReturn(3).when(uiInputClauseColumnThree).getIndex();
        doReturn(4).when(uiOutputClauseColumnOne).getIndex();
        doReturn(5).when(uiOutputClauseColumnTwo).getIndex();
        doReturn(6).when(uiOutputClauseColumnThree).getIndex();
        doReturn(7).when(uiRuleAnnotationClauseColumnOne).getIndex();
        doReturn(8).when(uiRuleAnnotationClauseColumnTwo).getIndex();
        doReturn(9).when(uiRuleAnnotationClauseColumnThree).getIndex();
    }

    @Test
    public void testCommandAllow() {
        moveColumnsToPositionCommand(Collections.singletonList(uiInputClauseColumnThree), 1);

        assertEquals(GraphCommandResultBuilder.SUCCESS,
                     graphCommand.allow(graphCommandExecutionContext));

        assertEquals(CanvasCommandResultBuilder.SUCCESS,
                     canvasCommand.allow(canvasHandler));
    }

    @Test
    public void testMoveSingleInputColumnLeft() {
        moveColumnsToPositionCommand(Collections.singletonList(uiInputClauseColumnThree), 1);

        assertEquals(GraphCommandResultBuilder.SUCCESS,
                     graphCommand.execute(graphCommandExecutionContext));

        assertClauses(1, 2, 0, 0, 1, 2, 0, 1, 2);

        assertEquals(CanvasCommandResultBuilder.SUCCESS,
                     canvasCommand.execute(canvasHandler));

        assertColumns(2, 3, 1, 4, 5, 6, 7, 8, 9);
    }

    @Test
    public void testMoveMultipleInputColumnsLeft() {
        moveColumnsToPositionCommand(Arrays.asList(uiInputClauseColumnTwo, uiInputClauseColumnThree), 1);

        assertEquals(GraphCommandResultBuilder.SUCCESS,
                     graphCommand.execute(graphCommandExecutionContext));

        assertClauses(2, 0, 1, 0, 1, 2, 0, 1, 2);

        assertEquals(CanvasCommandResultBuilder.SUCCESS,
                     canvasCommand.execute(canvasHandler));

        assertColumns(3, 1, 2, 4, 5, 6, 7, 8, 9);
    }

    @Test
    public void testMoveSingleInputColumnRight() {
        moveColumnsToPositionCommand(Collections.singletonList(uiInputClauseColumnOne), 3);

        assertEquals(GraphCommandResultBuilder.SUCCESS,
                     graphCommand.execute(graphCommandExecutionContext));

        assertClauses(2, 0, 1, 0, 1, 2, 0, 1, 2);

        assertEquals(CanvasCommandResultBuilder.SUCCESS,
                     canvasCommand.execute(canvasHandler));

        assertColumns(3, 1, 2, 4, 5, 6, 7, 8, 9);
    }

    @Test
    public void testMoveMultipleInputColumnsRight() {
        moveColumnsToPositionCommand(Arrays.asList(uiInputClauseColumnOne, uiInputClauseColumnTwo), 3);

        assertEquals(GraphCommandResultBuilder.SUCCESS,
                     graphCommand.execute(graphCommandExecutionContext));

        assertClauses(1, 2, 0, 0, 1, 2, 0, 1, 2);

        assertEquals(CanvasCommandResultBuilder.SUCCESS,
                     canvasCommand.execute(canvasHandler));

        assertColumns(2, 3, 1, 4, 5, 6, 7, 8, 9);
    }

    @Test
    public void testMoveSingleOutputColumnLeft() {
        moveColumnsToPositionCommand(Collections.singletonList(uiOutputClauseColumnThree), 4);

        assertEquals(GraphCommandResultBuilder.SUCCESS,
                     graphCommand.execute(graphCommandExecutionContext));

        assertClauses(0, 1, 2, 1, 2, 0, 0, 1, 2);

        assertEquals(CanvasCommandResultBuilder.SUCCESS,
                     canvasCommand.execute(canvasHandler));

        assertColumns(1, 2, 3, 5, 6, 4, 7, 8, 9);
    }

    @Test
    public void testMoveMultipleOutputColumnsLeft() {
        moveColumnsToPositionCommand(Arrays.asList(uiOutputClauseColumnTwo, uiOutputClauseColumnThree), 4);

        assertEquals(GraphCommandResultBuilder.SUCCESS,
                     graphCommand.execute(graphCommandExecutionContext));

        assertClauses(0, 1, 2, 2, 0, 1, 0, 1, 2);

        assertEquals(CanvasCommandResultBuilder.SUCCESS,
                     canvasCommand.execute(canvasHandler));

        assertColumns(1, 2, 3, 6, 4, 5, 7, 8, 9);
    }

    @Test
    public void testMoveSingleOutputColumnRight() {
        moveColumnsToPositionCommand(Collections.singletonList(uiOutputClauseColumnOne), 6);

        assertEquals(GraphCommandResultBuilder.SUCCESS,
                     graphCommand.execute(graphCommandExecutionContext));

        assertClauses(0, 1, 2, 2, 0, 1, 0, 1, 2);

        assertEquals(CanvasCommandResultBuilder.SUCCESS,
                     canvasCommand.execute(canvasHandler));

        assertColumns(1, 2, 3, 6, 4, 5, 7, 8, 9);
    }

    @Test
    public void testMoveMultipleOutputColumnsRight() {
        moveColumnsToPositionCommand(Arrays.asList(uiOutputClauseColumnOne, uiOutputClauseColumnTwo), 6);

        assertEquals(GraphCommandResultBuilder.SUCCESS,
                     graphCommand.execute(graphCommandExecutionContext));

        assertClauses(0, 1, 2, 1, 2, 0, 0, 1, 2);

        assertEquals(CanvasCommandResultBuilder.SUCCESS,
                     canvasCommand.execute(canvasHandler));

        assertColumns(1, 2, 3, 5, 6, 4, 7, 8, 9);
    }

    @Test
    public void testMoveSingleAnnotationColumnWithDuplicatedTitle() {

        final DecisionTable decisionTable = new DecisionTable();
        final DMNGridData model = new DMNGridData();

        final RuleAnnotationClause clauseOne = new RuleAnnotationClause();
        final RuleAnnotationClause clauseTwo = new RuleAnnotationClause();
        final RuleAnnotationClause clauseThree = new RuleAnnotationClause();
        decisionTable.getAnnotations().add(clauseOne);
        decisionTable.getAnnotations().add(clauseTwo);
        decisionTable.getAnnotations().add(clauseThree);

        decisionTable.getRule().add(new DecisionRule() {{
            getAnnotationEntry().add(new RuleAnnotationClauseText());
            getAnnotationEntry().add(new RuleAnnotationClauseText());
            getAnnotationEntry().add(new RuleAnnotationClauseText());
        }});

        final RuleAnnotationClauseColumn columnOne = mock(RuleAnnotationClauseColumn.class);
        final RuleAnnotationClauseColumn columnTwo = mock(RuleAnnotationClauseColumn.class);
        final RuleAnnotationClauseColumn columnThree = mock(RuleAnnotationClauseColumn.class);
        model.appendColumn(uiRowNumberColumn);
        model.appendColumn(columnOne);
        model.appendColumn(columnTwo);
        model.appendColumn(columnThree);
        when(columnOne.getIndex()).thenReturn(1);
        when(columnOne.getIndex()).thenReturn(2);
        when(columnOne.getIndex()).thenReturn(3);

        command = new MoveColumnsCommand(decisionTable, model, 2, Arrays.asList(columnOne), canvasOperation);
        graphCommand = command.newGraphCommand(canvasHandler);
        canvasCommand = command.newCanvasCommand(canvasHandler);

        assertEquals(GraphCommandResultBuilder.SUCCESS,
                     graphCommand.execute(graphCommandExecutionContext));

        assertEquals(CanvasCommandResultBuilder.SUCCESS,
                     canvasCommand.execute(canvasHandler));
    }

    @Test
    public void testMoveSingleAnnotationColumnLeft() {
        moveColumnsToPositionCommand(Collections.singletonList(uiRuleAnnotationClauseColumnThree), 7);

        assertEquals(GraphCommandResultBuilder.SUCCESS,
                     graphCommand.execute(graphCommandExecutionContext));

        assertClauses(0, 1, 2, 0, 1, 2, 1, 2, 0);

        assertEquals(CanvasCommandResultBuilder.SUCCESS,
                     canvasCommand.execute(canvasHandler));

        assertColumns(1, 2, 3, 4, 5, 6, 8, 9, 7);
    }

    @Test
    public void testMoveMultipleAnnotationColumnsLeft() {
        moveColumnsToPositionCommand(Arrays.asList(uiRuleAnnotationClauseColumnTwo, uiRuleAnnotationClauseColumnThree), 7);

        assertEquals(GraphCommandResultBuilder.SUCCESS,
                     graphCommand.execute(graphCommandExecutionContext));

        assertClauses(0, 1, 2, 0, 1, 2, 2, 0, 1);

        assertEquals(CanvasCommandResultBuilder.SUCCESS,
                     canvasCommand.execute(canvasHandler));

        assertColumns(1, 2, 3, 4, 5, 6, 9, 7, 8);
    }

    @Test
    public void testMoveSingleAnnotationColumnRight() {
        moveColumnsToPositionCommand(Collections.singletonList(uiRuleAnnotationClauseColumnOne), 8);

        assertEquals(GraphCommandResultBuilder.SUCCESS,
                     graphCommand.execute(graphCommandExecutionContext));

        assertClauses(0, 1, 2, 0, 1, 2, 1, 0, 2);

        assertEquals(CanvasCommandResultBuilder.SUCCESS,
                     canvasCommand.execute(canvasHandler));

        assertColumns(1, 2, 3, 4, 5, 6, 8, 7, 9);
    }

    @Test
    public void testMoveMultipleAnnotationColumnsRight() {
        moveColumnsToPositionCommand(Arrays.asList(uiRuleAnnotationClauseColumnOne, uiRuleAnnotationClauseColumnTwo), 9);

        assertEquals(GraphCommandResultBuilder.SUCCESS,
                     graphCommand.execute(graphCommandExecutionContext));

        assertClauses(0, 1, 2, 0, 1, 2, 1, 2, 0);

        assertEquals(CanvasCommandResultBuilder.SUCCESS,
                     canvasCommand.execute(canvasHandler));

        assertColumns(1, 2, 3, 4, 5, 6, 8, 9, 7);
    }

    @Test(expected = IllegalArgumentException.class)
    public void testMoveSingleAnnotationToOutputs() {
        moveColumnsToPositionCommand(Collections.singletonList(uiRuleAnnotationClauseColumnOne), 4);

        graphCommand.execute(graphCommandExecutionContext);
    }

    @Test(expected = IllegalArgumentException.class)
    public void testMoveSingleAnnotationToInputs() {
        moveColumnsToPositionCommand(Collections.singletonList(uiRuleAnnotationClauseColumnTwo), 1);

        graphCommand.execute(graphCommandExecutionContext);
    }

    @Test(expected = IllegalArgumentException.class)
    public void testMoveSingleInputToOutputs() {
        moveColumnsToPositionCommand(Collections.singletonList(uiInputClauseColumnOne), 4);

        graphCommand.execute(graphCommandExecutionContext);
    }

    @Test(expected = IllegalArgumentException.class)
    public void testMoveSingleInputToAnnotations() {
        moveColumnsToPositionCommand(Collections.singletonList(uiInputClauseColumnOne), 7);

        graphCommand.execute(graphCommandExecutionContext);
    }

    @Test(expected = IllegalArgumentException.class)
    public void testMoveSingleOutputToInputs() {
        moveColumnsToPositionCommand(Collections.singletonList(uiOutputClauseColumnOne), 1);

        graphCommand.execute(graphCommandExecutionContext);
    }

    @Test(expected = IllegalArgumentException.class)
    public void testMoveSingleOutputToAnnotations() {
        moveColumnsToPositionCommand(Collections.singletonList(uiOutputClauseColumnOne), 7);

        graphCommand.execute(graphCommandExecutionContext);
    }

    @Test(expected = IllegalArgumentException.class)
    public void testMoveMixedToInputs() {
        moveColumnsToPositionCommand(Arrays.asList(uiInputClauseColumnOne, uiOutputClauseColumnOne), 3);

        graphCommand.execute(graphCommandExecutionContext);
    }

    @Test(expected = IllegalArgumentException.class)
    public void testMoveMixedToOutputs() {
        moveColumnsToPositionCommand(Arrays.asList(uiOutputClauseColumnOne, uiInputClauseColumnOne), 6);

        graphCommand.execute(graphCommandExecutionContext);
    }

    @Test(expected = IllegalArgumentException.class)
    public void testMoveMixedToAnnotations() {
        moveColumnsToPositionCommand(Arrays.asList(uiOutputClauseColumnOne, uiInputClauseColumnOne), 7);

        graphCommand.execute(graphCommandExecutionContext);
    }

    @Test
    public void testInputClauseComponentWidths() {
        moveColumnsToPositionCommand(Arrays.asList(uiInputClauseColumnTwo, uiInputClauseColumnThree), 1);

        assertComponentWidths(1, 2, 3);
    }

    @Test
    public void testOutputClauseComponentWidths() {
        moveColumnsToPositionCommand(Arrays.asList(uiOutputClauseColumnTwo, uiOutputClauseColumnThree), 4);

        assertComponentWidths(4, 5, 6);
    }

    @Test
    public void testAnnotationClauseComponentWidths() {
        moveColumnsToPositionCommand(Arrays.asList(uiRuleAnnotationClauseColumnTwo, uiRuleAnnotationClauseColumnThree), 7);

        assertComponentWidths(7, 8, 9);
    }

    private void assertComponentWidths(final int uiColumn1Index,
                                       final int uiColumn2Index,
                                       final int uiColumn3Index) {
        final List<Double> componentWidths = dtable.getComponentWidths();
        componentWidths.set(uiColumn1Index, 10.0);
        componentWidths.set(uiColumn2Index, 20.0);
        componentWidths.set(uiColumn3Index, 30.0);

        final Command<GraphCommandExecutionContext, RuleViolation> graphCommand = command.newGraphCommand(canvasHandler);

        //Execute
        assertEquals(GraphCommandResultBuilder.SUCCESS,
                     graphCommand.execute(graphCommandExecutionContext));

        assertEquals(dtable.getRequiredComponentWidthCount(),
                     dtable.getComponentWidths().size());

        assertEquals(20.0,
                     dtable.getComponentWidths().get(uiColumn1Index),
                     0.0);
        assertEquals(30.0,
                     dtable.getComponentWidths().get(uiColumn2Index),
                     0.0);
        assertEquals(10.0,
                     dtable.getComponentWidths().get(uiColumn3Index),
                     0.0);

        //Move UI columns as MoveColumnsCommand.undo() relies on the UiModel being updated
        command.newCanvasCommand(canvasHandler).execute(canvasHandler);

        //Undo
        assertEquals(GraphCommandResultBuilder.SUCCESS,
                     graphCommand.undo(graphCommandExecutionContext));

        assertEquals(dtable.getRequiredComponentWidthCount(),
                     dtable.getComponentWidths().size());
        assertEquals(10.0,
                     dtable.getComponentWidths().get(uiColumn1Index),
                     0.0);
        assertEquals(20.0,
                     dtable.getComponentWidths().get(uiColumn2Index),
                     0.0);
        assertEquals(30.0,
                     dtable.getComponentWidths().get(uiColumn3Index),
                     0.0);
    }

    private void assertClauses(final int... clausesIndexes) {
        assertEquals(inputClauseOne, dtable.getInput().get(clausesIndexes[0]));
        assertEquals(inputClauseTwo, dtable.getInput().get(clausesIndexes[1]));
        assertEquals(inputClauseThree, dtable.getInput().get(clausesIndexes[2]));
        assertEquals(outputClauseOne, dtable.getOutput().get(clausesIndexes[3]));
        assertEquals(outputClauseTwo, dtable.getOutput().get(clausesIndexes[4]));
        assertEquals(outputClauseThree, dtable.getOutput().get(clausesIndexes[5]));
        assertEquals(annotationClauseOne, dtable.getAnnotations().get(clausesIndexes[6]));
        assertEquals(annotationClauseTwo, dtable.getAnnotations().get(clausesIndexes[7]));
        assertEquals(annotationClauseThree, dtable.getAnnotations().get(clausesIndexes[8]));
    }

    private void assertColumns(final int... columnIndexes) {
        assertEquals(uiInputClauseColumnOne, uiModel.getColumns().get(columnIndexes[0]));
        assertEquals(uiInputClauseColumnTwo, uiModel.getColumns().get(columnIndexes[1]));
        assertEquals(uiInputClauseColumnThree, uiModel.getColumns().get(columnIndexes[2]));
        assertEquals(uiOutputClauseColumnOne, uiModel.getColumns().get(columnIndexes[3]));
        assertEquals(uiOutputClauseColumnTwo, uiModel.getColumns().get(columnIndexes[4]));
        assertEquals(uiOutputClauseColumnThree, uiModel.getColumns().get(columnIndexes[5]));
        assertEquals(uiRuleAnnotationClauseColumnOne, uiModel.getColumns().get(columnIndexes[6]));
        assertEquals(uiRuleAnnotationClauseColumnTwo, uiModel.getColumns().get(columnIndexes[7]));
        assertEquals(uiRuleAnnotationClauseColumnThree, uiModel.getColumns().get(columnIndexes[8]));
    }

    private void moveColumnsToPositionCommand(final List<GridColumn<?>> columns, final int position) {
        command = new MoveColumnsCommand(dtable, uiModel, position, columns, canvasOperation);

        graphCommand = command.newGraphCommand(canvasHandler);
        canvasCommand = command.newCanvasCommand(canvasHandler);
    }
}


text:
const _ = require('lodash'),
    validator = require('validator'),
    BaseMapGenerator = require('./base-generator');

class UserMapGenerator extends BaseMapGenerator {
    constructor(opts) {
        super();

        this.name = 'authors';
        _.extend(this, opts);
    }

    /**
     * @TODO:
     * We could influence this with priority or meta information
     */
    getPriorityForDatum() {
        return 0.6;
    }

    validateImageUrl(imageUrl) {
        return imageUrl && validator.isURL(imageUrl, {protocols: ['http', 'https'], require_protocol: true});
    }
}

module.exports = UserMapGenerator;