text:
require 'rspec/core/rake_task'
require 'kitchen/rake_tasks'
require 'foodcritic'
require 'berkshelf'

module CookbookDevelopment
  class TestTasks < Rake::TaskLib
    attr_reader :project_dir

    def initialize
      @project_dir   = Dir.pwd
      yield(self) if block_given?
      define
    end

    def define
      kitchen_config = Kitchen::Config.new
      Kitchen.logger = Kitchen.default_file_logger

      namespace "kitchen" do
        kitchen_config.instances.each do |instance|
          desc "Run #{instance.name} test instance"
          task instance.name do
            destroy = (ENV['KITCHEN_DESTROY'] || 'passing').to_sym
            instance.test(destroy)
          end
        end

        desc "Run all test instances"
        task :all do
          destroy = ENV['KITCHEN_DESTROY'] || 'passing'
          concurrency = ENV['KITCHEN_CONCURRENCY'] || '1'
          require 'kitchen/cli'
          Kitchen::CLI.new([], {concurrency: concurrency.to_i, destroy: destroy}).test()
        end
      end

      desc 'Runs Foodcritic linting'
      FoodCritic::Rake::LintTask.new do |task|
        task.options = {
          :search_gems => true,
          :fail_tags => ['any'],
          :tags => ['~FC003', '~FC015', '~FC059', '~FC064', '~FC065', '~FC066', '~FC067', '~FC121','~FC123'],
          :exclude_paths => ['vendor/**/*'],
          :context => true
        }
      end

      desc 'Runs unit tests'
      RSpec::Core::RakeTask.new(:unit) do |task|
        task.pattern = FileList[File.join(project_dir, 'test', 'unit', '**/*_spec.rb')]
      end

      desc 'Runs integration tests'
      task :integration do
        Rake::Task['kitchen:all'].invoke
      end

      desc 'Run all tests and linting'
      task :test do
        Rake::Task['foodcritic'].invoke
        Rake::Task['unit'].invoke
        Rake::Task['integration'].invoke
      end

      task :unit_test_header do
        puts "-----> Running unit tests with chefspec".cyan
      end
      task :unit => :unit_test_header

      task :foodcritic_header do
        puts "-----> Linting with foodcritic".cyan
      end
      task :foodcritic => :foodcritic_header

      task :integration_header do
        puts "-----> Running integration tests with test-kitchen".cyan
      end
      task :integration => :integration_header
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Sisaf\SisafBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class EgresosType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('Tipo', 'choice', array(
                'choices'   => array('Fijo' => 'Fijo', 'Variable' => 'Variable'),
                'required'  => true,
                ))
            ->add('Fecha')
            ->add('Descripcion')
            ->add('Monto', 'integer', array('max_length'=>15))

        ;
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Sisaf\SisafBundle\Entity\Egresos'
        ));
    }

    public function getName()
    {
        return 'sisaf_sisafbundle_egresostype';
    }
}


text:
#include <linux/clk.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/dmaengine.h>
#include <linux/platform_device.h>
#include <linux/slab.h>

#include <mach/dma.h>

/* M2P registers */
#define M2P_CONTROL			0x0000
#define M2P_CONTROL_STALLINT		BIT(0)
#define M2P_CONTROL_NFBINT		BIT(1)
#define M2P_CONTROL_CH_ERROR_INT	BIT(3)
#define M2P_CONTROL_ENABLE		BIT(4)
#define M2P_CONTROL_ICE			BIT(6)

#define M2P_INTERRUPT			0x0004
#define M2P_INTERRUPT_STALL		BIT(0)
#define M2P_INTERRUPT_NFB		BIT(1)
#define M2P_INTERRUPT_ERROR		BIT(3)

#define M2P_PPALLOC			0x0008
#define M2P_STATUS			0x000c

#define M2P_MAXCNT0			0x0020
#define M2P_BASE0			0x0024
#define M2P_MAXCNT1			0x0030
#define M2P_BASE1			0x0034

#define M2P_STATE_IDLE			0
#define M2P_STATE_STALL			1
#define M2P_STATE_ON			2
#define M2P_STATE_NEXT			3

/* M2M registers */
#define M2M_CONTROL			0x0000
#define M2M_CONTROL_DONEINT		BIT(2)
#define M2M_CONTROL_ENABLE		BIT(3)
#define M2M_CONTROL_START		BIT(4)
#define M2M_CONTROL_DAH			BIT(11)
#define M2M_CONTROL_SAH			BIT(12)
#define M2M_CONTROL_PW_SHIFT		9
#define M2M_CONTROL_PW_8		(0 << M2M_CONTROL_PW_SHIFT)
#define M2M_CONTROL_PW_16		(1 << M2M_CONTROL_PW_SHIFT)
#define M2M_CONTROL_PW_32		(2 << M2M_CONTROL_PW_SHIFT)
#define M2M_CONTROL_PW_MASK		(3 << M2M_CONTROL_PW_SHIFT)
#define M2M_CONTROL_TM_SHIFT		13
#define M2M_CONTROL_TM_TX		(1 << M2M_CONTROL_TM_SHIFT)
#define M2M_CONTROL_TM_RX		(2 << M2M_CONTROL_TM_SHIFT)
#define M2M_CONTROL_RSS_SHIFT		22
#define M2M_CONTROL_RSS_SSPRX		(1 << M2M_CONTROL_RSS_SHIFT)
#define M2M_CONTROL_RSS_SSPTX		(2 << M2M_CONTROL_RSS_SHIFT)
#define M2M_CONTROL_RSS_IDE		(3 << M2M_CONTROL_RSS_SHIFT)
#define M2M_CONTROL_NO_HDSK		BIT(24)
#define M2M_CONTROL_PWSC_SHIFT		25

#define M2M_INTERRUPT			0x0004
#define M2M_INTERRUPT_DONEINT		BIT(1)

#define M2M_BCR0			0x0010
#define M2M_BCR1			0x0014
#define M2M_SAR_BASE0			0x0018
#define M2M_SAR_BASE1			0x001c
#define M2M_DAR_BASE0			0x002c
#define M2M_DAR_BASE1			0x0030

#define DMA_MAX_CHAN_BYTES		0xffff
#define DMA_MAX_CHAN_DESCRIPTORS	32

struct ep93xx_dma_engine;

/**
 * struct ep93xx_dma_desc - EP93xx specific transaction descriptor
 * @src_addr: source address of the transaction
 * @dst_addr: destination address of the transaction
 * @size: size of the transaction (in bytes)
 * @complete: this descriptor is completed
 * @txd: dmaengine API descriptor
 * @tx_list: list of linked descriptors
 * @node: link used for putting this into a channel queue
 */
struct ep93xx_dma_desc {
	u32				src_addr;
	u32				dst_addr;
	size_t				size;
	bool				complete;
	struct dma_async_tx_descriptor	txd;
	struct list_head		tx_list;
	struct list_head		node;
};

/**
 * struct ep93xx_dma_chan - an EP93xx DMA M2P/M2M channel
 * @chan: dmaengine API channel
 * @edma: pointer to to the engine device
 * @regs: memory mapped registers
 * @irq: interrupt number of the channel
 * @clk: clock used by this channel
 * @tasklet: channel specific tasklet used for callbacks
 * @lock: lock protecting the fields following
 * @flags: flags for the channel
 * @buffer: which buffer to use next (0/1)
 * @last_completed: last completed cookie value
 * @active: flattened chain of descriptors currently being processed
 * @queue: pending descriptors which are handled next
 * @free_list: list of free descriptors which can be used
 * @runtime_addr: physical address currently used as dest/src (M2M only). This
 *                is set via %DMA_SLAVE_CONFIG before slave operation is
 *                prepared
 * @runtime_ctrl: M2M runtime values for the control register.
 *
 * As EP93xx DMA controller doesn't support real chained DMA descriptors we
 * will have slightly different scheme here: @active points to a head of
 * flattened DMA descriptor chain.
 *
 * @queue holds pending transactions. These are linked through the first
 * descriptor in the chain. When a descriptor is moved to the @active queue,
 * the first and chained descriptors are flattened into a single list.
 *
 * @chan.private holds pointer to &struct ep93xx_dma_data which contains
 * necessary channel configuration information. For memcpy channels this must
 * be %NULL.
 */
struct ep93xx_dma_chan {
	struct dma_chan			chan;
	const struct ep93xx_dma_engine	*edma;
	void __iomem			*regs;
	int				irq;
	struct clk			*clk;
	struct tasklet_struct		tasklet;
	/* protects the fields following */
	spinlock_t			lock;
	unsigned long			flags;
/* Channel is configured for cyclic transfers */
#define EP93XX_DMA_IS_CYCLIC		0

	int				buffer;
	dma_cookie_t			last_completed;
	struct list_head		active;
	struct list_head		queue;
	struct list_head		free_list;
	u32				runtime_addr;
	u32				runtime_ctrl;
};

/**
 * struct ep93xx_dma_engine - the EP93xx DMA engine instance
 * @dma_dev: holds the dmaengine device
 * @m2m: is this an M2M or M2P device
 * @hw_setup: method which sets the channel up for operation
 * @hw_shutdown: shuts the channel down and flushes whatever is left
 * @hw_submit: pushes active descriptor(s) to the hardware
 * @hw_interrupt: handle the interrupt
 * @num_channels: number of channels for this instance
 * @channels: array of channels
 *
 * There is one instance of this struct for the M2P channels and one for the
 * M2M channels. hw_xxx() methods are used to perform operations which are
 * different on M2M and M2P channels. These methods are called with channel
 * lock held and interrupts disabled so they cannot sleep.
 */
struct ep93xx_dma_engine {
	struct dma_device	dma_dev;
	bool			m2m;
	int			(*hw_setup)(struct ep93xx_dma_chan *);
	void			(*hw_shutdown)(struct ep93xx_dma_chan *);
	void			(*hw_submit)(struct ep93xx_dma_chan *);
	int			(*hw_interrupt)(struct ep93xx_dma_chan *);
#define INTERRUPT_UNKNOWN	0
#define INTERRUPT_DONE		1
#define INTERRUPT_NEXT_BUFFER	2

	size_t			num_channels;
	struct ep93xx_dma_chan	channels[];
};

static inline struct device *chan2dev(struct ep93xx_dma_chan *edmac)
{
	return &edmac->chan.dev->device;
}

static struct ep93xx_dma_chan *to_ep93xx_dma_chan(struct dma_chan *chan)
{
	return container_of(chan, struct ep93xx_dma_chan, chan);
}

/**
 * ep93xx_dma_set_active - set new active descriptor chain
 * @edmac: channel
 * @desc: head of the new active descriptor chain
 *
 * Sets @desc to be the head of the new active descriptor chain. This is the
 * chain which is processed next. The active list must be empty before calling
 * this function.
 *
 * Called with @edmac->lock held and interrupts disabled.
 */
static void ep93xx_dma_set_active(struct ep93xx_dma_chan *edmac,
				  struct ep93xx_dma_desc *desc)
{
	BUG_ON(!list_empty(&edmac->active));

	list_add_tail(&desc->node, &edmac->active);

	/* Flatten the @desc->tx_list chain into @edmac->active list */
	while (!list_empty(&desc->tx_list)) {
		struct ep93xx_dma_desc *d = list_first_entry(&desc->tx_list,
			struct ep93xx_dma_desc, node);

		/*
		 * We copy the callback parameters from the first descriptor
		 * to all the chained descriptors. This way we can call the
		 * callback without having to find out the first descriptor in
		 * the chain. Useful for cyclic transfers.
		 */
		d->txd.callback = desc->txd.callback;
		d->txd.callback_param = desc->txd.callback_param;

		list_move_tail(&d->node, &edmac->active);
	}
}

/* Called with @edmac->lock held and interrupts disabled */
static struct ep93xx_dma_desc *
ep93xx_dma_get_active(struct ep93xx_dma_chan *edmac)
{
	return list_first_entry(&edmac->active, struct ep93xx_dma_desc, node);
}

/**
 * ep93xx_dma_advance_active - advances to the next active descriptor
 * @edmac: channel
 *
 * Function advances active descriptor to the next in the @edmac->active and
 * returns %true if we still have descriptors in the chain to process.
 * Otherwise returns %false.
 *
 * When the channel is in cyclic mode always returns %true.
 *
 * Called with @edmac->lock held and interrupts disabled.
 */
static bool ep93xx_dma_advance_active(struct ep93xx_dma_chan *edmac)
{
	list_rotate_left(&edmac->active);

	if (test_bit(EP93XX_DMA_IS_CYCLIC, &edmac->flags))
		return true;

	/*
	 * If txd.cookie is set it means that we are back in the first
	 * descriptor in the chain and hence done with it.
	 */
	return !ep93xx_dma_get_active(edmac)->txd.cookie;
}

/*
 * M2P DMA implementation
 */

static void m2p_set_control(struct ep93xx_dma_chan *edmac, u32 control)
{
	writel(control, edmac->regs + M2P_CONTROL);
	/*
	 * EP93xx User's Guide states that we must perform a dummy read after
	 * write to the control register.
	 */
	readl(edmac->regs + M2P_CONTROL);
}

static int m2p_hw_setup(struct ep93xx_dma_chan *edmac)
{
	struct ep93xx_dma_data *data = edmac->chan.private;
	u32 control;

	writel(data->port & 0xf, edmac->regs + M2P_PPALLOC);

	control = M2P_CONTROL_CH_ERROR_INT | M2P_CONTROL_ICE
		| M2P_CONTROL_ENABLE;
	m2p_set_control(edmac, control);

	return 0;
}

static inline u32 m2p_channel_state(struct ep93xx_dma_chan *edmac)
{
	return (readl(edmac->regs + M2P_STATUS) >> 4) & 0x3;
}

static void m2p_hw_shutdown(struct ep93xx_dma_chan *edmac)
{
	u32 control;

	control = readl(edmac->regs + M2P_CONTROL);
	control &= ~(M2P_CONTROL_STALLINT | M2P_CONTROL_NFBINT);
	m2p_set_control(edmac, control);

	while (m2p_channel_state(edmac) >= M2P_STATE_ON)
		cpu_relax();

	m2p_set_control(edmac, 0);

	while (m2p_channel_state(edmac) == M2P_STATE_STALL)
		cpu_relax();
}

static void m2p_fill_desc(struct ep93xx_dma_chan *edmac)
{
	struct ep93xx_dma_desc *desc = ep93xx_dma_get_active(edmac);
	u32 bus_addr;

	if (ep93xx_dma_chan_direction(&edmac->chan) == DMA_TO_DEVICE)
		bus_addr = desc->src_addr;
	else
		bus_addr = desc->dst_addr;

	if (edmac->buffer == 0) {
		writel(desc->size, edmac->regs + M2P_MAXCNT0);
		writel(bus_addr, edmac->regs + M2P_BASE0);
	} else {
		writel(desc->size, edmac->regs + M2P_MAXCNT1);
		writel(bus_addr, edmac->regs + M2P_BASE1);
	}

	edmac->buffer ^= 1;
}

static void m2p_hw_submit(struct ep93xx_dma_chan *edmac)
{
	u32 control = readl(edmac->regs + M2P_CONTROL);

	m2p_fill_desc(edmac);
	control |= M2P_CONTROL_STALLINT;

	if (ep93xx_dma_advance_active(edmac)) {
		m2p_fill_desc(edmac);
		control |= M2P_CONTROL_NFBINT;
	}

	m2p_set_control(edmac, control);
}

static int m2p_hw_interrupt(struct ep93xx_dma_chan *edmac)
{
	u32 irq_status = readl(edmac->regs + M2P_INTERRUPT);
	u32 control;

	if (irq_status & M2P_INTERRUPT_ERROR) {
		struct ep93xx_dma_desc *desc = ep93xx_dma_get_active(edmac);

		/* Clear the error interrupt */
		writel(1, edmac->regs + M2P_INTERRUPT);

		/*
		 * It seems that there is no easy way of reporting errors back
		 * to client so we just report the error here and continue as
		 * usual.
		 *
		 * Revisit this when there is a mechanism to report back the
		 * errors.
		 */
		dev_err(chan2dev(edmac),
			"DMA transfer failed! Details:\n"
			"\tcookie	: %d\n"
			"\tsrc_addr	: 0x%08x\n"
			"\tdst_addr	: 0x%08x\n"
			"\tsize		: %zu\n",
			desc->txd.cookie, desc->src_addr, desc->dst_addr,
			desc->size);
	}

	switch (irq_status & (M2P_INTERRUPT_STALL | M2P_INTERRUPT_NFB)) {
	case M2P_INTERRUPT_STALL:
		/* Disable interrupts */
		control = readl(edmac->regs + M2P_CONTROL);
		control &= ~(M2P_CONTROL_STALLINT | M2P_CONTROL_NFBINT);
		m2p_set_control(edmac, control);

		return INTERRUPT_DONE;

	case M2P_INTERRUPT_NFB:
		if (ep93xx_dma_advance_active(edmac))
			m2p_fill_desc(edmac);

		return INTERRUPT_NEXT_BUFFER;
	}

	return INTERRUPT_UNKNOWN;
}

/*
 * M2M DMA implementation
 *
 * For the M2M transfers we don't use NFB at all. This is because it simply
 * doesn't work well with memcpy transfers. When you submit both buffers it is
 * extremely unlikely that you get an NFB interrupt, but it instead reports
 * DONE interrupt and both buffers are already transferred which means that we
 * weren't able to update the next buffer.
 *
 * So for now we "simulate" NFB by just submitting buffer after buffer
 * without double buffering.
 */

static int m2m_hw_setup(struct ep93xx_dma_chan *edmac)
{
	const struct ep93xx_dma_data *data = edmac->chan.private;
	u32 control = 0;

	if (!data) {
		/* This is memcpy channel, nothing to configure */
		writel(control, edmac->regs + M2M_CONTROL);
		return 0;
	}

	switch (data->port) {
	case EP93XX_DMA_SSP:
		/*
		 * This was found via experimenting - anything less than 5
		 * causes the channel to perform only a partial transfer which
		 * leads to problems since we don't get DONE interrupt then.
		 */
		control = (5 << M2M_CONTROL_PWSC_SHIFT);
		control |= M2M_CONTROL_NO_HDSK;

		if (data->direction == DMA_TO_DEVICE) {
			control |= M2M_CONTROL_DAH;
			control |= M2M_CONTROL_TM_TX;
			control |= M2M_CONTROL_RSS_SSPTX;
		} else {
			control |= M2M_CONTROL_SAH;
			control |= M2M_CONTROL_TM_RX;
			control |= M2M_CONTROL_RSS_SSPRX;
		}
		break;

	case EP93XX_DMA_IDE:
		/*
		 * This IDE part is totally untested. Values below are taken
		 * from the EP93xx Users's Guide and might not be correct.
		 */
		control |= M2M_CONTROL_NO_HDSK;
		control |= M2M_CONTROL_RSS_IDE;
		control |= M2M_CONTROL_PW_16;

		if (data->direction == DMA_TO_DEVICE) {
			/* Worst case from the UG */
			control = (3 << M2M_CONTROL_PWSC_SHIFT);
			control |= M2M_CONTROL_DAH;
			control |= M2M_CONTROL_TM_TX;
		} else {
			control = (2 << M2M_CONTROL_PWSC_SHIFT);
			control |= M2M_CONTROL_SAH;
			control |= M2M_CONTROL_TM_RX;
		}
		break;

	default:
		return -EINVAL;
	}

	writel(control, edmac->regs + M2M_CONTROL);
	return 0;
}

static void m2m_hw_shutdown(struct ep93xx_dma_chan *edmac)
{
	/* Just disable the channel */
	writel(0, edmac->regs + M2M_CONTROL);
}

static void m2m_fill_desc(struct ep93xx_dma_chan *edmac)
{
	struct ep93xx_dma_desc *desc = ep93xx_dma_get_active(edmac);

	if (edmac->buffer == 0) {
		writel(desc->src_addr, edmac->regs + M2M_SAR_BASE0);
		writel(desc->dst_addr, edmac->regs + M2M_DAR_BASE0);
		writel(desc->size, edmac->regs + M2M_BCR0);
	} else {
		writel(desc->src_addr, edmac->regs + M2M_SAR_BASE1);
		writel(desc->dst_addr, edmac->regs + M2M_DAR_BASE1);
		writel(desc->size, edmac->regs + M2M_BCR1);
	}

	edmac->buffer ^= 1;
}

static void m2m_hw_submit(struct ep93xx_dma_chan *edmac)
{
	struct ep93xx_dma_data *data = edmac->chan.private;
	u32 control = readl(edmac->regs + M2M_CONTROL);

	/*
	 * Since we allow clients to configure PW (peripheral width) we always
	 * clear PW bits here and then set them according what is given in
	 * the runtime configuration.
	 */
	control &= ~M2M_CONTROL_PW_MASK;
	control |= edmac->runtime_ctrl;

	m2m_fill_desc(edmac);
	control |= M2M_CONTROL_DONEINT;

	/*
	 * Now we can finally enable the channel. For M2M channel this must be
	 * done _after_ the BCRx registers are programmed.
	 */
	control |= M2M_CONTROL_ENABLE;
	writel(control, edmac->regs + M2M_CONTROL);

	if (!data) {
		/*
		 * For memcpy channels the software trigger must be asserted
		 * in order to start the memcpy operation.
		 */
		control |= M2M_CONTROL_START;
		writel(control, edmac->regs + M2M_CONTROL);
	}
}

static int m2m_hw_interrupt(struct ep93xx_dma_chan *edmac)
{
	u32 control;

	if (!(readl(edmac->regs + M2M_INTERRUPT) & M2M_INTERRUPT_DONEINT))
		return INTERRUPT_UNKNOWN;

	/* Clear the DONE bit */
	writel(0, edmac->regs + M2M_INTERRUPT);

	/* Disable interrupts and the channel */
	control = readl(edmac->regs + M2M_CONTROL);
	control &= ~(M2M_CONTROL_DONEINT | M2M_CONTROL_ENABLE);
	writel(control, edmac->regs + M2M_CONTROL);

	/*
	 * Since we only get DONE interrupt we have to find out ourselves
	 * whether there still is something to process. So we try to advance
	 * the chain an see whether it succeeds.
	 */
	if (ep93xx_dma_advance_active(edmac)) {
		edmac->edma->hw_submit(edmac);
		return INTERRUPT_NEXT_BUFFER;
	}

	return INTERRUPT_DONE;
}

/*
 * DMA engine API implementation
 */

static struct ep93xx_dma_desc *
ep93xx_dma_desc_get(struct ep93xx_dma_chan *edmac)
{
	struct ep93xx_dma_desc *desc, *_desc;
	struct ep93xx_dma_desc *ret = NULL;
	unsigned long flags;

	spin_lock_irqsave(&edmac->lock, flags);
	list_for_each_entry_safe(desc, _desc, &edmac->free_list, node) {
		if (async_tx_test_ack(&desc->txd)) {
			list_del_init(&desc->node);

			/* Re-initialize the descriptor */
			desc->src_addr = 0;
			desc->dst_addr = 0;
			desc->size = 0;
			desc->complete = false;
			desc->txd.cookie = 0;
			desc->txd.callback = NULL;
			desc->txd.callback_param = NULL;

			ret = desc;
			break;
		}
	}
	spin_unlock_irqrestore(&edmac->lock, flags);
	return ret;
}

static void ep93xx_dma_desc_put(struct ep93xx_dma_chan *edmac,
				struct ep93xx_dma_desc *desc)
{
	if (desc) {
		unsigned long flags;

		spin_lock_irqsave(&edmac->lock, flags);
		list_splice_init(&desc->tx_list, &edmac->free_list);
		list_add(&desc->node, &edmac->free_list);
		spin_unlock_irqrestore(&edmac->lock, flags);
	}
}

/**
 * ep93xx_dma_advance_work - start processing the next pending transaction
 * @edmac: channel
 *
 * If we have pending transactions queued and we are currently idling, this
 * function takes the next queued transaction from the @edmac->queue and
 * pushes it to the hardware for execution.
 */
static void ep93xx_dma_advance_work(struct ep93xx_dma_chan *edmac)
{
	struct ep93xx_dma_desc *new;
	unsigned long flags;

	spin_lock_irqsave(&edmac->lock, flags);
	if (!list_empty(&edmac->active) || list_empty(&edmac->queue)) {
		spin_unlock_irqrestore(&edmac->lock, flags);
		return;
	}

	/* Take the next descriptor from the pending queue */
	new = list_first_entry(&edmac->queue, struct ep93xx_dma_desc, node);
	list_del_init(&new->node);

	ep93xx_dma_set_active(edmac, new);

	/* Push it to the hardware */
	edmac->edma->hw_submit(edmac);
	spin_unlock_irqrestore(&edmac->lock, flags);
}

static void ep93xx_dma_unmap_buffers(struct ep93xx_dma_desc *desc)
{
	struct device *dev = desc->txd.chan->device->dev;

	if (!(desc->txd.flags & DMA_COMPL_SKIP_SRC_UNMAP)) {
		if (desc->txd.flags & DMA_COMPL_SRC_UNMAP_SINGLE)
			dma_unmap_single(dev, desc->src_addr, desc->size,
					 DMA_TO_DEVICE);
		else
			dma_unmap_page(dev, desc->src_addr, desc->size,
				       DMA_TO_DEVICE);
	}
	if (!(desc->txd.flags & DMA_COMPL_SKIP_DEST_UNMAP)) {
		if (desc->txd.flags & DMA_COMPL_DEST_UNMAP_SINGLE)
			dma_unmap_single(dev, desc->dst_addr, desc->size,
					 DMA_FROM_DEVICE);
		else
			dma_unmap_page(dev, desc->dst_addr, desc->size,
				       DMA_FROM_DEVICE);
	}
}

static void ep93xx_dma_tasklet(unsigned long data)
{
	struct ep93xx_dma_chan *edmac = (struct ep93xx_dma_chan *)data;
	struct ep93xx_dma_desc *desc, *d;
	dma_async_tx_callback callback;
	void *callback_param;
	LIST_HEAD(list);

	spin_lock_irq(&edmac->lock);
	desc = ep93xx_dma_get_active(edmac);
	if (desc->complete) {
		edmac->last_completed = desc->txd.cookie;
		list_splice_init(&edmac->active, &list);
	}
	spin_unlock_irq(&edmac->lock);

	/* Pick up the next descriptor from the queue */
	ep93xx_dma_advance_work(edmac);

	callback = desc->txd.callback;
	callback_param = desc->txd.callback_param;

	/* Now we can release all the chained descriptors */
	list_for_each_entry_safe(desc, d, &list, node) {
		/*
		 * For the memcpy channels the API requires us to unmap the
		 * buffers unless requested otherwise.
		 */
		if (!edmac->chan.private)
			ep93xx_dma_unmap_buffers(desc);

		ep93xx_dma_desc_put(edmac, desc);
	}

	if (callback)
		callback(callback_param);
}

static irqreturn_t ep93xx_dma_interrupt(int irq, void *dev_id)
{
	struct ep93xx_dma_chan *edmac = dev_id;
	irqreturn_t ret = IRQ_HANDLED;

	spin_lock(&edmac->lock);

	switch (edmac->edma->hw_interrupt(edmac)) {
	case INTERRUPT_DONE:
		ep93xx_dma_get_active(edmac)->complete = true;
		tasklet_schedule(&edmac->tasklet);
		break;

	case INTERRUPT_NEXT_BUFFER:
		if (test_bit(EP93XX_DMA_IS_CYCLIC, &edmac->flags))
			tasklet_schedule(&edmac->tasklet);
		break;

	default:
		dev_warn(chan2dev(edmac), "unknown interrupt!\n");
		ret = IRQ_NONE;
		break;
	}

	spin_unlock(&edmac->lock);
	return ret;
}

/**
 * ep93xx_dma_tx_submit - set the prepared descriptor(s) to be executed
 * @tx: descriptor to be executed
 *
 * Function will execute given descriptor on the hardware or if the hardware
 * is busy, queue the descriptor to be executed later on. Returns cookie which
 * can be used to poll the status of the descriptor.
 */
static dma_cookie_t ep93xx_dma_tx_submit(struct dma_async_tx_descriptor *tx)
{
	struct ep93xx_dma_chan *edmac = to_ep93xx_dma_chan(tx->chan);
	struct ep93xx_dma_desc *desc;
	dma_cookie_t cookie;
	unsigned long flags;

	spin_lock_irqsave(&edmac->lock, flags);

	cookie = edmac->chan.cookie;

	if (++cookie < 0)
		cookie = 1;

	desc = container_of(tx, struct ep93xx_dma_desc, txd);

	edmac->chan.cookie = cookie;
	desc->txd.cookie = cookie;

	/*
	 * If nothing is currently prosessed, we push this descriptor
	 * directly to the hardware. Otherwise we put the descriptor
	 * to the pending queue.
	 */
	if (list_empty(&edmac->active)) {
		ep93xx_dma_set_active(edmac, desc);
		edmac->edma->hw_submit(edmac);
	} else {
		list_add_tail(&desc->node, &edmac->queue);
	}

	spin_unlock_irqrestore(&edmac->lock, flags);
	return cookie;
}

/**
 * ep93xx_dma_alloc_chan_resources - allocate resources for the channel
 * @chan: channel to allocate resources
 *
 * Function allocates necessary resources for the given DMA channel and
 * returns number of allocated descriptors for the channel. Negative errno
 * is returned in case of failure.
 */
static int ep93xx_dma_alloc_chan_resources(struct dma_chan *chan)
{
	struct ep93xx_dma_chan *edmac = to_ep93xx_dma_chan(chan);
	struct ep93xx_dma_data *data = chan->private;
	const char *name = dma_chan_name(chan);
	int ret, i;

	/* Sanity check the channel parameters */
	if (!edmac->edma->m2m) {
		if (!data)
			return -EINVAL;
		if (data->port < EP93XX_DMA_I2S1 ||
		    data->port > EP93XX_DMA_IRDA)
			return -EINVAL;
		if (data->direction != ep93xx_dma_chan_direction(chan))
			return -EINVAL;
	} else {
		if (data) {
			switch (data->port) {
			case EP93XX_DMA_SSP:
			case EP93XX_DMA_IDE:
				if (data->direction != DMA_TO_DEVICE &&
				    data->direction != DMA_FROM_DEVICE)
					return -EINVAL;
				break;
			default:
				return -EINVAL;
			}
		}
	}

	if (data && data->name)
		name = data->name;

	ret = clk_enable(edmac->clk);
	if (ret)
		return ret;

	ret = request_irq(edmac->irq, ep93xx_dma_interrupt, 0, name, edmac);
	if (ret)
		goto fail_clk_disable;

	spin_lock_irq(&edmac->lock);
	edmac->last_completed = 1;
	edmac->chan.cookie = 1;
	ret = edmac->edma->hw_setup(edmac);
	spin_unlock_irq(&edmac->lock);

	if (ret)
		goto fail_free_irq;

	for (i = 0; i < DMA_MAX_CHAN_DESCRIPTORS; i++) {
		struct ep93xx_dma_desc *desc;

		desc = kzalloc(sizeof(*desc), GFP_KERNEL);
		if (!desc) {
			dev_warn(chan2dev(edmac), "not enough descriptors\n");
			break;
		}

		INIT_LIST_HEAD(&desc->tx_list);

		dma_async_tx_descriptor_init(&desc->txd, chan);
		desc->txd.flags = DMA_CTRL_ACK;
		desc->txd.tx_submit = ep93xx_dma_tx_submit;

		ep93xx_dma_desc_put(edmac, desc);
	}

	return i;

fail_free_irq:
	free_irq(edmac->irq, edmac);
fail_clk_disable:
	clk_disable(edmac->clk);

	return ret;
}

/**
 * ep93xx_dma_free_chan_resources - release resources for the channel
 * @chan: channel
 *
 * Function releases all the resources allocated for the given channel.
 * The channel must be idle when this is called.
 */
static void ep93xx_dma_free_chan_resources(struct dma_chan *chan)
{
	struct ep93xx_dma_chan *edmac = to_ep93xx_dma_chan(chan);
	struct ep93xx_dma_desc *desc, *d;
	unsigned long flags;
	LIST_HEAD(list);

	BUG_ON(!list_empty(&edmac->active));
	BUG_ON(!list_empty(&edmac->queue));

	spin_lock_irqsave(&edmac->lock, flags);
	edmac->edma->hw_shutdown(edmac);
	edmac->runtime_addr = 0;
	edmac->runtime_ctrl = 0;
	edmac->buffer = 0;
	list_splice_init(&edmac->free_list, &list);
	spin_unlock_irqrestore(&edmac->lock, flags);

	list_for_each_entry_safe(desc, d, &list, node)
		kfree(desc);

	clk_disable(edmac->clk);
	free_irq(edmac->irq, edmac);
}

/**
 * ep93xx_dma_prep_dma_memcpy - prepare a memcpy DMA operation
 * @chan: channel
 * @dest: destination bus address
 * @src: source bus address
 * @len: size of the transaction
 * @flags: flags for the descriptor
 *
 * Returns a valid DMA descriptor or %NULL in case of failure.
 */
static struct dma_async_tx_descriptor *
ep93xx_dma_prep_dma_memcpy(struct dma_chan *chan, dma_addr_t dest,
			   dma_addr_t src, size_t len, unsigned long flags)
{
	struct ep93xx_dma_chan *edmac = to_ep93xx_dma_chan(chan);
	struct ep93xx_dma_desc *desc, *first;
	size_t bytes, offset;

	first = NULL;
	for (offset = 0; offset < len; offset += bytes) {
		desc = ep93xx_dma_desc_get(edmac);
		if (!desc) {
			dev_warn(chan2dev(edmac), "couln't get descriptor\n");
			goto fail;
		}

		bytes = min_t(size_t, len - offset, DMA_MAX_CHAN_BYTES);

		desc->src_addr = src + offset;
		desc->dst_addr = dest + offset;
		desc->size = bytes;

		if (!first)
			first = desc;
		else
			list_add_tail(&desc->node, &first->tx_list);
	}

	first->txd.cookie = -EBUSY;
	first->txd.flags = flags;

	return &first->txd;
fail:
	ep93xx_dma_desc_put(edmac, first);
	return NULL;
}

/**
 * ep93xx_dma_prep_slave_sg - prepare a slave DMA operation
 * @chan: channel
 * @sgl: list of buffers to transfer
 * @sg_len: number of entries in @sgl
 * @dir: direction of tha DMA transfer
 * @flags: flags for the descriptor
 *
 * Returns a valid DMA descriptor or %NULL in case of failure.
 */
static struct dma_async_tx_descriptor *
ep93xx_dma_prep_slave_sg(struct dma_chan *chan, struct scatterlist *sgl,
			 unsigned int sg_len, enum dma_data_direction dir,
			 unsigned long flags)
{
	struct ep93xx_dma_chan *edmac = to_ep93xx_dma_chan(chan);
	struct ep93xx_dma_desc *desc, *first;
	struct scatterlist *sg;
	int i;

	if (!edmac->edma->m2m && dir != ep93xx_dma_chan_direction(chan)) {
		dev_warn(chan2dev(edmac),
			 "channel was configured with different direction\n");
		return NULL;
	}

	if (test_bit(EP93XX_DMA_IS_CYCLIC, &edmac->flags)) {
		dev_warn(chan2dev(edmac),
			 "channel is already used for cyclic transfers\n");
		return NULL;
	}

	first = NULL;
	for_each_sg(sgl, sg, sg_len, i) {
		size_t sg_len = sg_dma_len(sg);

		if (sg_len > DMA_MAX_CHAN_BYTES) {
			dev_warn(chan2dev(edmac), "too big transfer size %d\n",
				 sg_len);
			goto fail;
		}

		desc = ep93xx_dma_desc_get(edmac);
		if (!desc) {
			dev_warn(chan2dev(edmac), "couln't get descriptor\n");
			goto fail;
		}

		if (dir == DMA_TO_DEVICE) {
			desc->src_addr = sg_dma_address(sg);
			desc->dst_addr = edmac->runtime_addr;
		} else {
			desc->src_addr = edmac->runtime_addr;
			desc->dst_addr = sg_dma_address(sg);
		}
		desc->size = sg_len;

		if (!first)
			first = desc;
		else
			list_add_tail(&desc->node, &first->tx_list);
	}

	first->txd.cookie = -EBUSY;
	first->txd.flags = flags;

	return &first->txd;

fail:
	ep93xx_dma_desc_put(edmac, first);
	return NULL;
}

/**
 * ep93xx_dma_prep_dma_cyclic - prepare a cyclic DMA operation
 * @chan: channel
 * @dma_addr: DMA mapped address of the buffer
 * @buf_len: length of the buffer (in bytes)
 * @period_len: lenght of a single period
 * @dir: direction of the operation
 *
 * Prepares a descriptor for cyclic DMA operation. This means that once the
 * descriptor is submitted, we will be submitting in a @period_len sized
 * buffers and calling callback once the period has been elapsed. Transfer
 * terminates only when client calls dmaengine_terminate_all() for this
 * channel.
 *
 * Returns a valid DMA descriptor or %NULL in case of failure.
 */
static struct dma_async_tx_descriptor *
ep93xx_dma_prep_dma_cyclic(struct dma_chan *chan, dma_addr_t dma_addr,
			   size_t buf_len, size_t period_len,
			   enum dma_data_direction dir)
{
	struct ep93xx_dma_chan *edmac = to_ep93xx_dma_chan(chan);
	struct ep93xx_dma_desc *desc, *first;
	size_t offset = 0;

	if (!edmac->edma->m2m && dir != ep93xx_dma_chan_direction(chan)) {
		dev_warn(chan2dev(edmac),
			 "channel was configured with different direction\n");
		return NULL;
	}

	if (test_and_set_bit(EP93XX_DMA_IS_CYCLIC, &edmac->flags)) {
		dev_warn(chan2dev(edmac),
			 "channel is already used for cyclic transfers\n");
		return NULL;
	}

	if (period_len > DMA_MAX_CHAN_BYTES) {
		dev_warn(chan2dev(edmac), "too big period length %d\n",
			 period_len);
		return NULL;
	}

	/* Split the buffer into period size chunks */
	first = NULL;
	for (offset = 0; offset < buf_len; offset += period_len) {
		desc = ep93xx_dma_desc_get(edmac);
		if (!desc) {
			dev_warn(chan2dev(edmac), "couln't get descriptor\n");
			goto fail;
		}

		if (dir == DMA_TO_DEVICE) {
			desc->src_addr = dma_addr + offset;
			desc->dst_addr = edmac->runtime_addr;
		} else {
			desc->src_addr = edmac->runtime_addr;
			desc->dst_addr = dma_addr + offset;
		}

		desc->size = period_len;

		if (!first)
			first = desc;
		else
			list_add_tail(&desc->node, &first->tx_list);
	}

	first->txd.cookie = -EBUSY;

	return &first->txd;

fail:
	ep93xx_dma_desc_put(edmac, first);
	return NULL;
}

/**
 * ep93xx_dma_terminate_all - terminate all transactions
 * @edmac: channel
 *
 * Stops all DMA transactions. All descriptors are put back to the
 * @edmac->free_list and callbacks are _not_ called.
 */
static int ep93xx_dma_terminate_all(struct ep93xx_dma_chan *edmac)
{
	struct ep93xx_dma_desc *desc, *_d;
	unsigned long flags;
	LIST_HEAD(list);

	spin_lock_irqsave(&edmac->lock, flags);
	/* First we disable and flush the DMA channel */
	edmac->edma->hw_shutdown(edmac);
	clear_bit(EP93XX_DMA_IS_CYCLIC, &edmac->flags);
	list_splice_init(&edmac->active, &list);
	list_splice_init(&edmac->queue, &list);
	/*
	 * We then re-enable the channel. This way we can continue submitting
	 * the descriptors by just calling ->hw_submit() again.
	 */
	edmac->edma->hw_setup(edmac);
	spin_unlock_irqrestore(&edmac->lock, flags);

	list_for_each_entry_safe(desc, _d, &list, node)
		ep93xx_dma_desc_put(edmac, desc);

	return 0;
}

static int ep93xx_dma_slave_config(struct ep93xx_dma_chan *edmac,
				   struct dma_slave_config *config)
{
	enum dma_slave_buswidth width;
	unsigned long flags;
	u32 addr, ctrl;

	if (!edmac->edma->m2m)
		return -EINVAL;

	switch (config->direction) {
	case DMA_FROM_DEVICE:
		width = config->src_addr_width;
		addr = config->src_addr;
		break;

	case DMA_TO_DEVICE:
		width = config->dst_addr_width;
		addr = config->dst_addr;
		break;

	default:
		return -EINVAL;
	}

	switch (width) {
	case DMA_SLAVE_BUSWIDTH_1_BYTE:
		ctrl = 0;
		break;
	case DMA_SLAVE_BUSWIDTH_2_BYTES:
		ctrl = M2M_CONTROL_PW_16;
		break;
	case DMA_SLAVE_BUSWIDTH_4_BYTES:
		ctrl = M2M_CONTROL_PW_32;
		break;
	default:
		return -EINVAL;
	}

	spin_lock_irqsave(&edmac->lock, flags);
	edmac->runtime_addr = addr;
	edmac->runtime_ctrl = ctrl;
	spin_unlock_irqrestore(&edmac->lock, flags);

	return 0;
}

/**
 * ep93xx_dma_control - manipulate all pending operations on a channel
 * @chan: channel
 * @cmd: control command to perform
 * @arg: optional argument
 *
 * Controls the channel. Function returns %0 in case of success or negative
 * error in case of failure.
 */
static int ep93xx_dma_control(struct dma_chan *chan, enum dma_ctrl_cmd cmd,
			      unsigned long arg)
{
	struct ep93xx_dma_chan *edmac = to_ep93xx_dma_chan(chan);
	struct dma_slave_config *config;

	switch (cmd) {
	case DMA_TERMINATE_ALL:
		return ep93xx_dma_terminate_all(edmac);

	case DMA_SLAVE_CONFIG:
		config = (struct dma_slave_config *)arg;
		return ep93xx_dma_slave_config(edmac, config);

	default:
		break;
	}

	return -ENOSYS;
}

/**
 * ep93xx_dma_tx_status - check if a transaction is completed
 * @chan: channel
 * @cookie: transaction specific cookie
 * @state: state of the transaction is stored here if given
 *
 * This function can be used to query state of a given transaction.
 */
static enum dma_status ep93xx_dma_tx_status(struct dma_chan *chan,
					    dma_cookie_t cookie,
					    struct dma_tx_state *state)
{
	struct ep93xx_dma_chan *edmac = to_ep93xx_dma_chan(chan);
	dma_cookie_t last_used, last_completed;
	enum dma_status ret;
	unsigned long flags;

	spin_lock_irqsave(&edmac->lock, flags);
	last_used = chan->cookie;
	last_completed = edmac->last_completed;
	spin_unlock_irqrestore(&edmac->lock, flags);

	ret = dma_async_is_complete(cookie, last_completed, last_used);
	dma_set_tx_state(state, last_completed, last_used, 0);

	return ret;
}

/**
 * ep93xx_dma_issue_pending - push pending transactions to the hardware
 * @chan: channel
 *
 * When this function is called, all pending transactions are pushed to the
 * hardware and executed.
 */
static void ep93xx_dma_issue_pending(struct dma_chan *chan)
{
	ep93xx_dma_advance_work(to_ep93xx_dma_chan(chan));
}

static int __init ep93xx_dma_probe(struct platform_device *pdev)
{
	struct ep93xx_dma_platform_data *pdata = dev_get_platdata(&pdev->dev);
	struct ep93xx_dma_engine *edma;
	struct dma_device *dma_dev;
	size_t edma_size;
	int ret, i;

	edma_size = pdata->num_channels * sizeof(struct ep93xx_dma_chan);
	edma = kzalloc(sizeof(*edma) + edma_size, GFP_KERNEL);
	if (!edma)
		return -ENOMEM;

	dma_dev = &edma->dma_dev;
	edma->m2m = platform_get_device_id(pdev)->driver_data;
	edma->num_channels = pdata->num_channels;

	INIT_LIST_HEAD(&dma_dev->channels);
	for (i = 0; i < pdata->num_channels; i++) {
		const struct ep93xx_dma_chan_data *cdata = &pdata->channels[i];
		struct ep93xx_dma_chan *edmac = &edma->channels[i];

		edmac->chan.device = dma_dev;
		edmac->regs = cdata->base;
		edmac->irq = cdata->irq;
		edmac->edma = edma;

		edmac->clk = clk_get(NULL, cdata->name);
		if (IS_ERR(edmac->clk)) {
			dev_warn(&pdev->dev, "failed to get clock for %s\n",
				 cdata->name);
			continue;
		}

		spin_lock_init(&edmac->lock);
		INIT_LIST_HEAD(&edmac->active);
		INIT_LIST_HEAD(&edmac->queue);
		INIT_LIST_HEAD(&edmac->free_list);
		tasklet_init(&edmac->tasklet, ep93xx_dma_tasklet,
			     (unsigned long)edmac);

		list_add_tail(&edmac->chan.device_node,
			      &dma_dev->channels);
	}

	dma_cap_zero(dma_dev->cap_mask);
	dma_cap_set(DMA_SLAVE, dma_dev->cap_mask);
	dma_cap_set(DMA_CYCLIC, dma_dev->cap_mask);

	dma_dev->dev = &pdev->dev;
	dma_dev->device_alloc_chan_resources = ep93xx_dma_alloc_chan_resources;
	dma_dev->device_free_chan_resources = ep93xx_dma_free_chan_resources;
	dma_dev->device_prep_slave_sg = ep93xx_dma_prep_slave_sg;
	dma_dev->device_prep_dma_cyclic = ep93xx_dma_prep_dma_cyclic;
	dma_dev->device_control = ep93xx_dma_control;
	dma_dev->device_issue_pending = ep93xx_dma_issue_pending;
	dma_dev->device_tx_status = ep93xx_dma_tx_status;

	dma_set_max_seg_size(dma_dev->dev, DMA_MAX_CHAN_BYTES);

	if (edma->m2m) {
		dma_cap_set(DMA_MEMCPY, dma_dev->cap_mask);
		dma_dev->device_prep_dma_memcpy = ep93xx_dma_prep_dma_memcpy;

		edma->hw_setup = m2m_hw_setup;
		edma->hw_shutdown = m2m_hw_shutdown;
		edma->hw_submit = m2m_hw_submit;
		edma->hw_interrupt = m2m_hw_interrupt;
	} else {
		dma_cap_set(DMA_PRIVATE, dma_dev->cap_mask);

		edma->hw_setup = m2p_hw_setup;
		edma->hw_shutdown = m2p_hw_shutdown;
		edma->hw_submit = m2p_hw_submit;
		edma->hw_interrupt = m2p_hw_interrupt;
	}

	ret = dma_async_device_register(dma_dev);
	if (unlikely(ret)) {
		for (i = 0; i < edma->num_channels; i++) {
			struct ep93xx_dma_chan *edmac = &edma->channels[i];
			if (!IS_ERR_OR_NULL(edmac->clk))
				clk_put(edmac->clk);
		}
		kfree(edma);
	} else {
		dev_info(dma_dev->dev, "EP93xx M2%s DMA ready\n",
			 edma->m2m ? "M" : "P");
	}

	return ret;
}

static struct platform_device_id ep93xx_dma_driver_ids[] = {
	{ "ep93xx-dma-m2p", 0 },
	{ "ep93xx-dma-m2m", 1 },
	{ },
};

static struct platform_driver ep93xx_dma_driver = {
	.driver		= {
		.name	= "ep93xx-dma",
	},
	.id_table	= ep93xx_dma_driver_ids,
};

static int __init ep93xx_dma_module_init(void)
{
	return platform_driver_probe(&ep93xx_dma_driver, ep93xx_dma_probe);
}
subsys_initcall(ep93xx_dma_module_init);

MODULE_AUTHOR("Mika Westerberg <mika.westerberg@iki.fi>");
MODULE_DESCRIPTION("EP93xx DMA driver");
MODULE_LICENSE("GPL");


text:
(function() {
  var serverSiteUrl = "http://localhost:8080"
  console.log('URL: '+location.href); // URL
  console.log('Title: '+checkTitle()); // title
  console.log('jQuery Ver: '+checkJquery())
  function checkJquery() {
    try {
      return ($ && $.fn && $.fn.jquery) || 'No jQuery'
    } catch (e) {
      return 'No jQuery'
    }
  }
  function checkTitle() {
    try {
      return document.querySelector('title').innerText
    } catch (e) {
      return 'No Title'
    }
  }
  function loadAsset(elementType, url, srcOrHref, parentElement) {
    parentElement = parentElement || document.body
    var assetElement = document.createElement(elementType)
    if (srcOrHref === 'href') {
      assetElement.href = url
    } else {
      assetElement.src = url
    }
    parentElement.appendChild(assetElement);
    return assetElement
  }
  // var socketIoScript = document.createElement('script')
  // socketIoScript.src='https://cdn.socket.io/socket.io-1.4.5.js';
  // document.body.appendChild(socketIoScript);
  // var socketIoScript = loadAsset('script', 'https://cdn.socket.io/socket.io-1.4.5.js')

  var x = new XMLHttpRequest();
  x.onreadystatechange = function() {
    if(x.readyState == 4 && x.status == 200) {
      eval(x.responseText)
      // var socketIoScript = document.createElement('script')
      // socketIoScript.text = x.responseText
      // document.body.appendChild(socketIoScript)
      setTimeout(function () {
        socketLoaded()
      }, 3000);
      // document.body.appendChild(socketIoScript)
    }
  }
  x.open("GET", serverSiteUrl+"/socket", true);
  x.send()
  var socketLoaded = function() {
    console.log('Socket Loaded!');
    var ioDomain = prompt("Please Set IO Server's Domain", serverSiteUrl);
    if (ioDomain) {
      var socket = io(ioDomain);
      socket.on('siteInfo', function (time) {
        // var title = document.querySelector('title')
        var siteInfo = {
          url: location.href,
          title: checkTitle(),
          userAgent: window.navigator.userAgent,
          languages: window.navigator.languages||[window.navigator.language||window.navigator.userLanguage||window.navigator.browserLanguage],
          jquery: checkJquery(),
          delay: Date.now() - time // one-way delay
        }
        console.log(siteInfo)
        socket.emit('siteInfo', siteInfo)
      })
      socket.on('load', function (asset) {
        console.log(asset)
        var elementType = asset.type.match(/^style|css$/) ? 'link' : 'script'
        var insertedAssert
        try {
          if (elementType === 'link') {
            insertedAssert = loadAsset(elementType, asset.uri, 'href')
          } else {
            insertedAssert = loadAsset(elementType, asset.uri)
          }
          // console.log(insertedAssert)
          var result = {
            message: insertedAssert.outerHTML + ' Inserted!'
          }
          socket.emit('result', result)
        } catch (e) {
          console.log(e);
          socket.emit('error', e)
        }
      })
      socket.on('exec', function (data) {
        console.log(data)
        try {
          var returnedMessage = eval(data.command)
          var result = {
            returns: returnedMessage,
            message: 'Executed!',
            at: Date.now()
          }
          socket.emit('result', result)
        } catch (e) {
          socket.emit('error', e)
        }
      })
      socket.on('disconnect', function (data) {
        socket.disconnect()
      })
    }
  }
})()


text:
[![CircleCI](https://img.shields.io/circleci/project/github/objectpartners/rancher-service-updater.svg?maxAge=0)](https://circleci.com/gh/objectpartners/rancher-service-updater/tree/master)
[![GitHub Release](https://img.shields.io/github/release/objectpartners/rancher-service-updater.svg?maxAge=0)](https://github.com/objectpartners/rancher-service-updater/releases)
[![Apache License 2.0](https://img.shields.io/badge/license-Apache_License_2.0-blue.svg)](https://github.com/objectpartners/rancher-service-updater/blob/master/LICENSE)

An Inversion of Control (IOC) service used to notify Rancher of new container
images and execute updates to those services based on container labels.

## Configuring

* `AUTOUPDATE_ENABLE_LABEL` [`autoupdate.enable`] - Specifies the container label to query for automatic update enabling.
* `AUTOUPDATE_ENVIRONMENT_NAMES` [`[".*"]`] - An array  of regex patterns to match Rancher environment names against. Environment name must match a pattern for auto-updating to occur in that environment.
* `AUTOUPDATE_HTTP_PORT` [`8080`] - The port that the service updater listens on.
* `AUTOUPDATE_SLACK_WEBHOOK_URL` - The webhook URL to use for sending Slack notifications. If not specified, Slack messaging is disabled.
* `AUTOUPDATE_SLACK_BOT_NAME` - The bot name to send as for Slack messages.
* `CATTLE_ACCESS_KEY` - The API access key for Rancher.
* `CATTLE_SECRET_KEY` - The API secret key for Rancher.
* `CATTLE_URL` - The Rancher server URL.

## Enabling Auto-Updating for Rancher Environment

The Rancher Service Updater configures itself to only check certain environments for services to automatically update.
This is done in conjunction with the API restrictions based on the credentials passed to the container.
That is, if an environment specific key is used, then the updater will only ever try to update service within that environment.

If however, a global/user key is used, then the updater can update services in any environment that that key has access to.
By default the updater is configured to allow updating of services in any environment.
This is set via the `AUTOUDPATE_ENVIRONMENT_NAMES` environment variable which should contain a comma (`,`) separated list of regex patterns.
The default value is `.*`.

In conjunction with a global key, this property can be used to restrict the environments.
For example, assume a cluster with 3 environments: `dev`, `qa`, and `production`.
The updater is configured with a global key that has access to all 3 environments.
To restrict automatic updates to only the `dev` environment, set `AUTOUPDATE_ENVIRONMENT_NAMES=dev`.
To restrict automatic updates to both the `dev` and `qa` environments, set `AUTOUPDATE_ENVIRONMENT_NAMES=dev,qa`

## Enabling Auto-Updating for a Rancher Service

Configure a service to be automatically updated by adding a container label of `autoupdate.enabled=true`.
Alternatively, the label to check can be specified by setting the `AUTOUPDATE_ENABLE_LABEL` environment variable

### Determining if update is required

| Currently Deployed Version | Newly Published Version | Update? |
|:---------------------------|:------------------------|:--------|
| 1.0                        | 2.0                     | `true`  |
| 2.0                        | 1.3                     | `false` |
| 1.0                        | latest                  | `true`  |
| latest                     | latest                  | `true`  |
| latest                     | 1.0                     | `false` |

## Running Service Updater on Rancher

The Rancher Service Updater relies upon the standard environment variables for providing
connection information to create a Rancher client instance.

If running this application as a container on a Rancher cluster itself, you can
provide the following service labels to automatically provision the API
credentials to the application.

* `io.rancher.container.create_agent=true`
* `io.rancher.container.agent.role=environment`

_NOTE:_ When using this method, the provisioned API credentials are tied to the
Rancher environment in which the service is deployed. Thus, it will only have access
to update services within that same environment.

_NOTE:_ If it is intended to auto-update services in multiple Rancher environments,
then the API configuration **must** be provided via environment variables.

## Triggering an upgrade.

Send a post to `/upgrade` with the following JSON payload:

```
{
  "docker_image": "docker:",
  "confirm": true,
  "start_first": false,
  "timeout": 30
}
```

* `docker_image` - the image path that is now available. Optionally start with `docker:`
* `confirm` - if the service upgrade should be confirmed/finished if successful
* `start_first` - Optional. Default of `false`. If true, then sets new services to be started before terminated old services.
* `timeout` - Optional. Timeout in seconds. Default of 30. Timeout for waiting for service upgrade to complete if `confirm = true`.

## Security

This service provides not mechanism for authentication/authorization. It is the responsibility of the user to properly secure
this service such that unauthorized access is not available.


text:
package demoapp.dom.types.javalang.integers.persistence;

import javax.inject.Inject;

import org.springframework.stereotype.Service;

import demoapp.dom._infra.seed.SeedServiceAbstract;
import demoapp.dom._infra.values.ValueHolderRepository;

/* This file was GENERATED by the showcase generator (tooling). Do NOT edit! */
@Service
public class WrapperIntegerSeeding
extends SeedServiceAbstract {

    @Inject
    public WrapperIntegerSeeding(ValueHolderRepository<java.lang.Integer, ? extends WrapperIntegerEntity> entities) {
        super(entities);
    }

}


text:
class HomeController < ApplicationController
  def index
  end

  def private
  end

  def user_dashboard
  end

  def admin_dashboard
  end

  def join
  end

  def set
    session["devise.foo_bar"] = "something"
    head :ok
  end

  def unauthenticated
    render :text => "unauthenticated", :status => :unauthorized
  end
end


text:
package org.vertexium;

import java.util.Map;

public interface Traceable {
    void traceOn(String description);

    void traceOn(String description, Map<String, String> data);

    void traceOff();
}


text:
#import "_ASAsyncTransaction.h"

#import "ASAssert.h"

@interface ASDisplayNodeAsyncTransactionOperation : NSObject
- (id)initWithOperationCompletionBlock:(asyncdisplaykit_async_transaction_operation_completion_block_t)operationCompletionBlock;
@property (nonatomic, copy) asyncdisplaykit_async_transaction_operation_completion_block_t operationCompletionBlock;
@property (atomic, retain) id<NSObject> value; // set on bg queue by the operation block
@end

@implementation ASDisplayNodeAsyncTransactionOperation

- (id)initWithOperationCompletionBlock:(asyncdisplaykit_async_transaction_operation_completion_block_t)operationCompletionBlock
{
  if ((self = [super init])) {
    _operationCompletionBlock = [operationCompletionBlock copy];
  }
  return self;
}

- (void)dealloc
{
  ASDisplayNodeAssertNil(_operationCompletionBlock, @"Should have been called and released before -dealloc");
}

- (void)callAndReleaseCompletionBlock:(BOOL)canceled;
{
  if (_operationCompletionBlock) {
    _operationCompletionBlock(self.value, canceled);
    // Guarantee that _operationCompletionBlock is released on _callbackQueue:
    self.operationCompletionBlock = nil;
  }
}

@end

@implementation _ASAsyncTransaction
{
  dispatch_group_t _group;
  NSMutableArray *_operations;
}

#pragma mark -
#pragma mark Lifecycle

- (id)initWithCallbackQueue:(dispatch_queue_t)callbackQueue
            completionBlock:(void(^)(_ASAsyncTransaction *, BOOL))completionBlock
{
  if ((self = [self init])) {
    if (callbackQueue == NULL) {
      callbackQueue = dispatch_get_main_queue();
    }
    _callbackQueue = callbackQueue;
    _completionBlock = [completionBlock copy];

    _state = ASAsyncTransactionStateOpen;
  }
  return self;
}

- (void)dealloc
{
  // Uncommitted transactions break our guarantees about releasing completion blocks on callbackQueue.
  ASDisplayNodeAssert(_state != ASAsyncTransactionStateOpen, @"Uncommitted ASAsyncTransactions are not allowed");
}

#pragma mark -
#pragma mark Transaction Management

- (void)addAsyncOperationWithBlock:(asyncdisplaykit_async_transaction_async_operation_block_t)block
                             queue:(dispatch_queue_t)queue
                        completion:(asyncdisplaykit_async_transaction_operation_completion_block_t)completion
{
  ASDisplayNodeAssertMainThread();
  ASDisplayNodeAssert(_state == ASAsyncTransactionStateOpen, @"You can only add operations to open transactions");

  [self _ensureTransactionData];

  ASDisplayNodeAsyncTransactionOperation *operation = [[ASDisplayNodeAsyncTransactionOperation alloc] initWithOperationCompletionBlock:completion];
  [_operations addObject:operation];
  dispatch_group_async(_group, queue, ^{
    if (_state != ASAsyncTransactionStateCanceled) {
      dispatch_group_enter(_group);
      block(^(id<NSObject> value){
        operation.value = value;
        dispatch_group_leave(_group);
      });
    }
  });
}

- (void)addOperationWithBlock:(asyncdisplaykit_async_transaction_operation_block_t)block
                        queue:(dispatch_queue_t)queue
                   completion:(asyncdisplaykit_async_transaction_operation_completion_block_t)completion
{
  ASDisplayNodeAssertMainThread();
  ASDisplayNodeAssert(_state == ASAsyncTransactionStateOpen, @"You can only add operations to open transactions");

  [self _ensureTransactionData];

  ASDisplayNodeAsyncTransactionOperation *operation = [[ASDisplayNodeAsyncTransactionOperation alloc] initWithOperationCompletionBlock:completion];
  [_operations addObject:operation];
  dispatch_group_async(_group, queue, ^{
    if (_state != ASAsyncTransactionStateCanceled) {
      operation.value = block();
    }
  });
}

- (void)addCompletionBlock:(asyncdisplaykit_async_transaction_completion_block_t)completion
{
  __weak typeof(self) weakSelf = self;
  [self addOperationWithBlock:^(){return (id<NSObject>)nil;} queue:_callbackQueue completion:^(id<NSObject> value, BOOL canceled) {
    typeof(self) strongSelf = weakSelf;
    completion(strongSelf, canceled);
  }];
}

- (void)cancel
{
  ASDisplayNodeAssertMainThread();
  ASDisplayNodeAssert(_state != ASAsyncTransactionStateOpen, @"You can only cancel a committed or already-canceled transaction");
  _state = ASAsyncTransactionStateCanceled;
}

- (void)commit
{
  ASDisplayNodeAssertMainThread();
  ASDisplayNodeAssert(_state == ASAsyncTransactionStateOpen, @"You cannot double-commit a transaction");
  _state = ASAsyncTransactionStateCommitted;

  if ([_operations count] == 0) {
    // Fast path: if a transaction was opened, but no operations were added, execute completion block synchronously.
    if (_completionBlock) {
      _completionBlock(self, NO);
    }
  } else {
    ASDisplayNodeAssert(_group != NULL, @"If there are operations, dispatch group should have been created");
    dispatch_group_notify(_group, _callbackQueue, ^{
      BOOL isCanceled = (_state == ASAsyncTransactionStateCanceled);
      for (ASDisplayNodeAsyncTransactionOperation *operation in _operations) {
        [operation callAndReleaseCompletionBlock:isCanceled];
      }
      if (_completionBlock) {
        _completionBlock(self, isCanceled);
      }
    });
  }
}

#pragma mark -
#pragma mark Helper Methods

- (void)_ensureTransactionData
{
  // Lazily initialize _group and _operations to avoid overhead in the case where no operations are added to the transaction
  if (_group == NULL) {
    _group = dispatch_group_create();
  }
  if (_operations == nil) {
    _operations = [[NSMutableArray alloc] init];
  }
}

@end


text:
MAKEFILE_DIR := $(shell dirname $(realpath $(lastword $(MAKEFILE_LIST))))
LOG_DIR?=$(MAKEFILE_DIR)/logs

.PHONY: clean build test docs build-noconda

build:
	conda install -y pip
	conda install -y numpy
	conda install -y scipy
	conda install -c conda-forge jq=1.5
	pip install --upgrade --user awscli
	pip install -q azure-cli
	conda install -y -c bioconda azure-cli
	conda install -y -c ibmdecisionoptimization cplex
	conda install -y -c ibmdecisionoptimization docplex
	make build-noconda

build-noconda:
	pip install --editable $(MAKEFILE_DIR)/.;
	if [ ! -e $(LOG_DIR) ]; then \
		mkdir $(LOG_DIR); \
	fi;

clean:
	pip uninstall $(MAKEFILE_DIR)/.;
	rm -rf $(MAKEFILE_DIR)/*.egg-info;
	rm -rf $(MAKEFILE_DIR)/.eggs;
	rm -rf $(MAKEFILE_DIR)/.cache;
	rm -rf $(LOG_DIR);

test: build-noconda
	python setup.py test

docs:
	pip install mkdocs; \
	cd documentation;\
	mkdocs build --clean; \
	cd ..;
	@echo 'To view documentation, go to the documentation directory, run "mkdocs serve", and then open "http://127.0.0.1:8000" in a web browser.'


text:
package mtgox

import (
	"code.google.com/p/go.net/websocket"
	"encoding/json"
	"fmt"
	"github.com/blooberr/coin-exchange/libcoin"
  "time"
)

type ticker struct {
	High      high              `json:"high"`
	Low       low               `json:"low"`
	Avg       avg               `json:"avg"`
	Vwap      vwap              `json:"vwap"`
	Vol       vol               `json:"vol"`
	LastLocal map[string]string `json:"last_local"`
	LastOrig  map[string]string `json:"last_orig"`
	LastAll   map[string]string `json:"last_all"`
	Last      last              `json:"last"`
	Buy       map[string]string `json:"buy"`
	Sell      map[string]string `json:"sell"`
	Item      string            `json:"item"`
	Now       int64             `json:"now,string"` // timestamp in microseconds
}

type high struct {
	Value string `json:"value"`
}

type low struct {
	Value float64 `json:"value,string"`
}

type vwap struct {
	Value float64 `json:"value,string"`
}

type avg struct {
	Value float64 `json:"value,string"`
}

type vol struct {
	Value        float64 `json:"value,string"`
	ValueInt     int64   `json:"value_int,string"`
	Display      string  `json:"display"`
	DisplayShort string  `json:"display_short"`
	Currency     string  `json:"currency"`
}

type last struct {
	Value        float64 `json:"value,string"`
	ValueInt     int64   `json:"value_int,string"`
	Display      string  `json:"display"`
	DisplayShort string  `json:"display_short"`
	Currency     string  `json:"currency"`
}

type exchange struct {
	Channel     string `json:"channel"`
	ChannelName string `json:"channel_name"`
	Op          string `json:"op"`
	Origin      string `json:"origin"`
	Private     string `json:"private"`
	Ticker      ticker `json:"ticker"`
	Stamp       int64  `json:"stamp"`
}

func Loop() {
	origin := "http://localhost"
	ws, err := websocket.Dial("ws://websocket.mtgox.com:80/mtgox?Currency=USD", "", origin)
	libcoin.PanicError(err)

	cp := &libcoin.CoinPacket{}

	var resp = make([]byte, 4096)
	info := &exchange{}
	for {
		n, err := ws.Read(resp)
		libcoin.PanicError(err)

		// fmt.Printf("Received: %s\n", string(resp[0:n]))
		json.Unmarshal(resp[0:n], &info)

		if info.ChannelName == "ticker.BTCUSD" {
			//fmt.Printf("Received: %s \n", string(resp[0:n]))
			//fmt.Printf("%+v \n", info)
			//fmt.Printf("last: %f (%s) with volume: %f \n", info.Ticker.Last.Value, info.Ticker.Last.Currency, info.Ticker.Vol.Value)

			//fmt.Printf("timestamp: %d \n", info.Ticker.Now)
			cp.Exchange = "mtgox"
			cp.Last = info.Ticker.Last.Value
			cp.Currency = info.Ticker.Last.Currency
			cp.CurrentVolume = info.Ticker.Vol.Value
			b, _ := json.Marshal(cp)
			//fmt.Printf("cp: %+v \n", cp)

			fmt.Printf("[%s] [mtgox]: %s \n", time.Unix(info.Ticker.Now / 1000000, 0), b)
		}
	}
}


text:
require 'spec_helper'

describe 'redis::instance', :type => 'define' do
  let(:title) { 'redis-instance' }

  context "On Debian systems with no password parameter" do

    let :facts do
      {
        :osfamily  => 'Debian'
      }
    end # let

    let :params do
      {
        :redis_password => false
      }
    end # let

    it do
      should_not contain_file('redis_port_6379.conf').with_content(/^requirepass/)
    end # it
  end # context

  context "On Debian systems with password parameter" do

    let :facts do
      {
        :osfamily  => 'Debian'
      }
    end # let

    let :params do
      {
        :redis_port     => '6900',
        :redis_password => 'ThisIsAReallyBigSecret'
      }
    end # let

    it do
      should contain_file('redis_port_6900.conf').with_content(/^requirepass ThisIsAReallyBigSecret/)
      should contain_file('redis-init-6900').with_content(/^CLIEXEC="[\w\/]+redis-cli -h \$REDIS_BIND_ADDRESS -p \$REDIS_PORT -a ThisIsAReallyBigSecret/)
    end # it
  end # context

  context "With a non-default port parameter" do
    let :params do
      {
        :redis_port => '6900'
      }
    end # let

    it do
      should contain_file('redis_port_6900.conf').with_content(/^port 6900$/)
      should contain_file('redis_port_6900.conf').with_content(/^pidfile \/var\/run\/redis_6900\.pid$/)
      should contain_file('redis_port_6900.conf').with_content(/^logfile \/var\/log\/redis_6900\.log$/)
      should contain_file('redis_port_6900.conf').with_content(/^dir \/var\/lib\/redis\/6900$/)
      should contain_file('redis-init-6900').with_content(/^REDIS_PORT="6900"$/)
    end # it
  end # context

  context "With a non default bind address" do
    let :params do
      {
        :redis_port => '6900',
        :redis_bind_address => '10.1.2.3'
      }
    end # let

    it do
      should contain_file('redis_port_6900.conf').with_content(/^bind 10\.1\.2\.3$/)
      should contain_file('redis-init-6900').with_content(/^REDIS_BIND_ADDRESS="10.1.2.3"$/)
    end # it
  end # context
end # describe


text:
using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using VkNet.Utils;

namespace VkNet.Model;

/// <summary>
/// Время последнего посещения.
/// </summary>
[Serializable]
public class LastSeen
{
	/// <summary>
	/// Время последнего посещения в формате unixtime. .
	/// </summary>
	[JsonConverter(converterType: typeof(UnixDateTimeConverter))]
	public DateTime? Time { get; set; }

	/// <summary>
	/// Тип платформы, через которую был осуществлён последний вход. Подробнее cмотрите
	/// на странице Подключение к LongPoll
	/// серверу. .
	/// </summary>
	public string Platform { get; set; }

	/// <summary>
	/// Разобрать из json.
	/// </summary>
	/// <param name="response"> Ответ сервера. </param>
	/// <returns> </returns>
	public static LastSeen FromJson(VkResponse response)
	{
		var giftItem = new LastSeen
		{
			Time = response[key: "time"],
			Platform = response[key: "platform"]
		};

		return giftItem;
	}
}


text:
    {% if page.title != "Services" %}

Services

Help your team and product grow.

    {% endif %}

      {% if page.title == "Services" %}
        {% for item in site.data.services.service-items %}

<svg class="icon"><use xlink:href="#{{ item.svg }}" /></svg>{{ item.title }}

{{ item.content }}

              {{ item.action-text }}

        {% endfor %}
      {% endif %}

      {% if page.title != "Services" %}
        {% for item in site.data.services.service-items limit:3 %}

<svg class="icon"><use xlink:href="#{{ item.svg }}" /></svg>{{ item.title }}

{{ item.content }}

              {{ item.action-text }}

        {% endfor %}
      {% endif %}

    {% if page.title != "Services" %}

Hit up the services page if you don't see what you're looking for.

    {% endif %}


text:
package com.xxfff.core.model;

import java.io.Serializable;
import java.util.List;

/**
 * 实体数组
 * @author jeek
 *
 * @param <T>
 */
public class BaseEntityArray<T extends BaseEntity> implements Serializable {
	private static final long serialVersionUID = 1847593255532494015L;

	private List<T> entityArray;

	public List<T> getEntityArray() {
		return entityArray;
	}

	public void setEntityArray(List<T> entityArray) {
		this.entityArray = entityArray;
	}
}


text:
import { API_BASE_URL } from '../config'

const headers = {
  // 'Content-type': 'application/json',
	Accept: 'application/json',
	'Content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
}

const responseError = (res) => {
	const error = new Error(res.statusText)
	error.response = res
	throw error
}

const checkStatus = (res) => {
	if (res.status >= 200 && res.status < 300) {
		return res
	} else if (res.status === 403) {
		// TODO need to log user out here
		return responseError(res)
	}
	return responseError(res)
}

const parseJSON = (response) => {
	const contentType = response.headers.get('content-type')
	if (contentType && contentType.indexOf('application/json') !== -1) {
		return response.json()
	}
	throw new Error('API response is not valid json')
}

// const camelizeKeys = (res) => {
	// This will change all server responses from snake_case to camelCase
	// return Promise.resolve(humps.camelizeKeys(res))
// }

const baseRequest = (path, options) => {
	const url = `${API_BASE_URL}${path}`
	const reqOptions = {
		...options,
		headers,
	}
	return fetch(url, reqOptions)
		.then(checkStatus)
		.then(parseJSON)
		// .then(camelizeKeys)
}

export const deleteReq = (path, data) => {
	const options = {
		method: 'DELETE',
		body: data,
	}
	return baseRequest(path, options)
}

export const getReq = (path, qs) => {
	const options = {
		method: 'GET',
		qs,
	}
	return baseRequest(path, options)
}

export const postReq = (path, qs, body) => {
	const options = {
		method: 'POST',
		qs,
		body: JSON.stringify(body),
	}
	return baseRequest(path, options)
}

export const putReq = (path, qs, body) => {
	const options = {
		method: 'PUT',
		qs,
		body: JSON.stringify(body),
	}
	return baseRequest(path, options)
}


text:
require "google/cloud/dataform/v1beta1"

##
# Example demonstrating basic usage of
# Google::Cloud::Dataform::V1beta1::Dataform::Client#delete_repository
#
def delete_repository
  # Create a client object. The client can be reused for multiple calls.
  client = Google::Cloud::Dataform::V1beta1::Dataform::Client.new

  # Create a request. To set request fields, pass in keyword arguments.
  request = Google::Cloud::Dataform::V1beta1::DeleteRepositoryRequest.new

  # Call the delete_repository method.
  result = client.delete_repository request

  # The returned object is of type Google::Protobuf::Empty.
  p result
end
# [END dataform_v1beta1_generated_Dataform_DeleteRepository_sync]


text:
class Dialog : public QDialog
{
    Q_OBJECT

public:
    Dialog(QWidget *parent = 0);
    ~Dialog();

private:
    QPushButton *btn;
    QLineEdit *num1, *num2;
    QLabel *label;

    QTimer *time1;

private slots:
    void add();

    void on_time();
};

#endif // DIALOG_H


text:
package androidx.work.integration.testapp.db;

import androidx.annotation.NonNull;
import androidx.room.Entity;
import androidx.room.PrimaryKey;

/**
 * A POJO for a word and its count.
 */
@Entity
public class WordCount {

    @PrimaryKey
    @NonNull
    public String mWord;
    public int mCount;
}


text:
package cz.tul.executor;

import cz.tul.entities.Chain;
import cz.tul.entities.StateEnum;
import cz.tul.repositories.ChainDAO;
import cz.tul.repositories.PartDAO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Bc. Marek Jindrák on 12.10.2016.
 */
@Service
@EnableAsync
public class AsyncTaskExecutor {
    private static final Logger logger = LoggerFactory.getLogger(AsyncTaskExecutor.class);
    private final int maxTasks = 50;

    @Autowired
    PartDAO partDAO;

    @Autowired
    ThreadPoolTaskExecutor executor;

    @Autowired
    ChainDAO chainDAO;

    @Scheduled(fixedDelay = 1000)
    public void execute() {

        int activeTasks = executor.getActiveCount();

        if (activeTasks <= maxTasks) {
            List<Chain> chains = changeState(chainDAO.getLastActiveChains(maxTasks - activeTasks));
            logger.info("Coutnt of chain to processes: " + chains.size());
            if (chains.size() > 0) {
                logger.info("Count of task:" + chains.size());
                logger.info("Processing:" + chains.size());
                chainDAO.update(chains);
                for (Chain chain : chains) {

                    Task asyncTask = new Task(chain, chainDAO, partDAO);

                    executor.execute(asyncTask);
                }
            }
        }

    }

    private List<Chain> changeState(List<Chain> chains) {

        List<Chain> result = new ArrayList<>();
        if (chains.size() > 0) {
            for (Chain chain : chains) {
                chain.setState(StateEnum.PROCESSING.getState());
                result.add(chain);
            }
            chainDAO.update(result);
        }
        return result;
    }

}


text:
<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorAccent">@color/black</item>
        <item name="colorPrimary">@color/black</item>
        <item name="colorPrimaryDark">@color/black</item>
        <item name="colorControlNormal">@color/black</item>
        <item name="colorControlHighlight">@color/grey_500</item>
    </style>

</resources>


text:
#ifndef itkEuler3DTransform_h
#define itkEuler3DTransform_h

#include <iostream>
#include "itkRigid3DTransform.h"

namespace itk
{
/** \class Euler3DTransform
 *
 * \brief Euler3DTransform of a vector space (e.g. space coordinates)
 *
 * This transform applies a rotation and translation to the space given 3 euler
 * angles and a 3D translation. Rotation is about a user specified center.
 *
 * The parameters for this transform can be set either using individual Set
 * methods or in serialized form using SetParameters() and SetFixedParameters().
 *
 * The serialization of the optimizable parameters is an array of 6 elements.
 * The first 3 represents three euler angle of rotation respectively about
 * the X, Y and Z axis. The last 3 parameters defines the translation in each
 * dimension.
 *
 * The serialization of the fixed parameters is an array of 3 elements defining
 * the center of rotation.
 *
 * \ingroup ITKTransform
 */
template<typename TParametersValueType=double >
class ITK_TEMPLATE_EXPORT Euler3DTransform :
  public Rigid3DTransform<TParametersValueType>
{
public:
  /** Standard class typedefs. */
  typedef Euler3DTransform                       Self;
  typedef Rigid3DTransform<TParametersValueType> Superclass;
  typedef SmartPointer<Self>                     Pointer;
  typedef SmartPointer<const Self>               ConstPointer;

  /** New macro for creation of through a Smart Pointer. */
  itkNewMacro(Self);

  /** Run-time type information (and related methods). */
  itkTypeMacro(Euler3DTransform, Rigid3DTransform);

  /** Dimension of the space. */
  itkStaticConstMacro(SpaceDimension, unsigned int, 3);
  itkStaticConstMacro(InputSpaceDimension, unsigned int, 3);
  itkStaticConstMacro(OutputSpaceDimension, unsigned int, 3);
  itkStaticConstMacro(ParametersDimension, unsigned int, 6);

  typedef typename Superclass::ParametersType            ParametersType;
  typedef typename Superclass::ParametersValueType       ParametersValueType;
  typedef typename Superclass::FixedParametersType       FixedParametersType;
  typedef typename Superclass::FixedParametersValueType  FixedParametersValueType;
  typedef typename Superclass::JacobianType              JacobianType;
  typedef typename Superclass::ScalarType                ScalarType;
  typedef typename Superclass::InputVectorType           InputVectorType;
  typedef typename Superclass::OutputVectorType          OutputVectorType;
  typedef typename Superclass::InputCovariantVectorType  InputCovariantVectorType;
  typedef typename Superclass::OutputCovariantVectorType OutputCovariantVectorType;
  typedef typename Superclass::InputVnlVectorType        InputVnlVectorType;
  typedef typename Superclass::OutputVnlVectorType       OutputVnlVectorType;
  typedef typename Superclass::InputPointType            InputPointType;
  typedef typename Superclass::OutputPointType           OutputPointType;
  typedef typename Superclass::MatrixType                MatrixType;
  typedef typename Superclass::InverseMatrixType         InverseMatrixType;
  typedef typename Superclass::CenterType                CenterType;
  typedef typename Superclass::TranslationType           TranslationType;
  typedef typename Superclass::OffsetType                OffsetType;
  typedef typename Superclass::ScalarType                AngleType;

  /** Set/Get the transformation from a container of parameters
   * This is typically used by optimizers.  There are 6 parameters. The first
   * three represent the angles to rotate around the coordinate axis, and the
   * last three represents the offset. */
  void SetParameters(const ParametersType & parameters) ITK_OVERRIDE;

  const ParametersType & GetParameters(void) const ITK_OVERRIDE;

  const FixedParametersType & GetFixedParameters() const ITK_OVERRIDE;
  virtual void SetFixedParameters(const FixedParametersType & parameters) ITK_OVERRIDE;

  /** Set the rotational part of the transform. */
  void SetRotation(ScalarType angleX, ScalarType angleY, ScalarType angleZ);

  itkGetConstMacro(AngleX, ScalarType);
  itkGetConstMacro(AngleY, ScalarType);
  itkGetConstMacro(AngleZ, ScalarType);

  /** This method computes the Jacobian matrix of the transformation.
   * given point or vector, returning the transformed point or
   * vector. The rank of the Jacobian will also indicate if the
   * transform is invertible at this point. */
  virtual void ComputeJacobianWithRespectToParameters( const InputPointType  & p, JacobianType & jacobian) const ITK_OVERRIDE;

  /** The Euler angle representation of a rotation is not unique and
   * depends on the order of rotations. In general there are 12
   * options. This class supports two of them, ZXY and ZYX. The
   * default is ZXY. These functions set and get the value which
   * indicates whether the rotation is ZYX or ZXY.
   */
  virtual void SetComputeZYX (const bool flag);
  itkGetConstMacro(ComputeZYX, bool);

  virtual void SetIdentity(void) ITK_OVERRIDE;

protected:
  Euler3DTransform(const MatrixType & matrix, const OutputPointType & offset);
  Euler3DTransform(unsigned int paramsSpaceDims);
  Euler3DTransform();

  ~Euler3DTransform()
  {
  }

  void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE;

  /** Set values of angles directly without recomputing other parameters. */
  void SetVarRotation(ScalarType angleX, ScalarType angleY, ScalarType angleZ);

  /** Compute the components of the rotation matrix in the superclass. */
  void ComputeMatrix(void) ITK_OVERRIDE;

  void ComputeMatrixParameters(void) ITK_OVERRIDE;

private:
  ITK_DISALLOW_COPY_AND_ASSIGN(Euler3DTransform);

  ScalarType m_AngleX;
  ScalarType m_AngleY;
  ScalarType m_AngleZ;
  bool       m_ComputeZYX;
}; // class Euler3DTransform
}  // namespace itk

#ifndef ITK_MANUAL_INSTANTIATION
#include "itkEuler3DTransform.hxx"
#endif

#endif /* itkEuler3DTransform_h */


text:
(function (items) {

  var edition = new BookmarkEdition(items), ctx = edition.ctx;
  items = edition.items;

  items.editorPanel = items.editor.markdownEditor({
    preview: true,
    theme: "ace/theme/tomorrow_night",
    onPreview: function (content, callback) {
      callback(parseMarkdown(content));
    }
  });

  items.preview = $(".md-preview");
  items.btnVisualize = items.editorPanel.find(".btn-preview");

  edition.getEditorValue = function () {
    console.debug('m=getEditorValue');
    return this.items.editor.markdownEditor('content');
  };

  edition.setup();

  items.editorPanel.editor.setOption("showInvisibles", mg.settings.CODE_STYLE_SHOW_WHITESPACES === "true");
  let session = items.editorPanel.editor.getSession();
  session.setUseSoftTabs(mg.settings.CODE_STYLE_TAB_STYLE === "SPACES");
  session.setTabSize(mg.settings.CODE_STYLE_TAB_SIZE);
  items.editorPanel.focus(function () {
    items.editorPanel.editor.focus();
  });

})(new function () {
});


text:
import React, { Component } from 'react'
import immutable from 'immutable'
import { connect } from 'react-redux'
import autobind from 'autobind-decorator'
import { shouldComponentUpdate } from '../plugins/PureRender.js'
import { pushSnackbar } from '../actions/pageUI.js'
import { getInviteLink, refreshInviteLink } from '../actions/activeList.js'
import handleClipboard from '../util/clipboard.js'
import config from '../config/config'
import Invite from '../components/Invite.jsx'
import Modal from '../components/Modal.jsx'
import language from '../config/language.js'

import item from '../util/item.js'
import ActiveListWrap from './ActiveListWrap.js'
import ListItemWrap from './ListItemWrap.js'
import ListItem from '../components/ListItem.jsx'
import message from '../util/message.js'

window.handleClipboard = handleClipboard;

const InviteWarp = (WrappedComponent) => class extends Component{
    constructor(props){
        super(props);
        this.shouldComponentUpdate = shouldComponentUpdate.bind(this);
        this.state = {modalState: false, isLoading: true, room: immutable.fromJS({})};
    }
    connectLink(link){
        return config.inviteLink + link;
    }
    @autobind
    handleOpenModal(){
        this.setState({modalState: true});
    }
    @autobind
    handlecloseModal(){
        this.setState({modalState: false});
    }
    @autobind
    handleGetInviteLink(){
        getInviteLink({_id: this.props.user.get('curRoom')})
        .then((ret) => {
            ret.link = ret.inviteLink ? this.connectLink(ret.inviteLink) : '...';
            this.isMount && this.setState({room: immutable.fromJS(ret)});
        })
    }
    @autobind
    handleRefreshLink(){
        const curRoom = this.props.user.get('curRoom');
        const user = this.props.user.get('_id');
        refreshInviteLink({_id: curRoom, creater: user})
        .then((ret) => {
            pushSnackbar(language.refreshLink);
            let room = this.state.room.set('inviteLink',ret.inviteLink);
            room = room.set('link',this.connectLink(ret.inviteLink));
            this.isMount && this.setState({room: room});
        })
        .catch((err) => pushSnackbar(language.ERROR10013))
    }
    @autobind
    handleCopyLink(){
        handleClipboard.setClipboardValue(this.state.room.get('link'));
        const success = handleClipboard.clipboard();
        if(success) return pushSnackbar(language.copiedLink);
        return pushSnackbar(language.copyError);
    }

    componentDidMount(){
        this.isMount = true;
        this.handleGetInviteLink();
    }
    componentWillUnmount(){
        this.isMount = false;
    }
    render(){
        const newProps = {
            handleCopyLink: this.handleCopyLink,
            handleRefreshLink: this.handleRefreshLink,
            handleOpenModal: this.handleOpenModal,
        }
        const handleClick = message.redirectMessage(this.props.user.toJS(),this.state.room.get('link'),'text',this.handlecloseModal);
        const ActiveListItem = ListItemWrap(ListItem,item.getItemInfo,handleClick);
        const ActiveList = ActiveListWrap(ActiveListItem);
        return (
            <div>
                <WrappedComponent  {...this.state} {...newProps}/>
                <Modal
                    open = {this.state.modalState}
                    handleClose = {this.handlecloseModal}
                    title = {language.sendInviteLink}
                >
                    <ActiveList />
                </Modal>
            </div>
        );
    }
}

export default connect((state) =>({
    user: state.get('user'),
}
))(InviteWarp(Invite))


text:
<?php
/**
 * List View Template
 * The wrapper template for a list of events. This includes the Past Events and Upcoming Events views
 * as well as those same views filtered to a specific category.
 *
 * Override this template in your own theme by creating a file at [your-theme]/tribe-events/list.php
 *
 * @package TribeEventsCalendar
 * @since  2.1
 * @author Modern Tribe Inc.
 *
 */

if ( !defined('ABSPATH') ) { die('-1'); } ?>

<?php do_action( 'tribe_events_before_template' ); ?>

<?php tribe_get_template_part( 'list/content' ); ?>

<?php do_action( 'tribe_events_after_template' ) ?>


text:
import os
while True:
	os.system("python "+os.path.abspath(__file__)[:-20]+"/main.py")


text:
package com.google.javascript.jscomp;

import static com.google.javascript.jscomp.SyntacticScopeCreator.VAR_MULTIPLY_DECLARED_ERROR;

import com.google.common.collect.Maps;
import com.google.javascript.jscomp.GlobalNamespace.Name;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.Token;

import java.util.Map;

/**
 * @author nicksantos@google.com (Nick Santos)
 */
public class ProcessDefinesTest extends CompilerTestCase {

  public ProcessDefinesTest() {
    super("var externMethod;");

    // ProcessDefines emits warnings if the user tries to re-define a constant,
    // but the constant is not defined anywhere in the binary.
    allowSourcelessWarnings();
  }

  private Map<String, Node> overrides = Maps.newHashMap();
  private GlobalNamespace namespace;

  @Override
  public void setUp() throws Exception {
    super.setUp();
    overrides.clear();
  }

  @Override
  protected CompilerPass getProcessor(Compiler compiler) {
    return new ProcessDefinesWithInjectedNamespace(compiler);
  }

  @Override
  protected int getNumRepetitions() {
    // Only do one repetition, so that we can make sure the first pass keeps
    // GlobalNamespace up to date.
    return 1;
  }

  /**
   * Helper for tests that expects definitions to remain unchanged, such
   * that {@code definitions+js} is coverted to {@code definitions+expected}.
   */
  private void testWithPrefix(String definitions, String js, String expected) {
    test(definitions + js, definitions + expected);
  }

  public void testBasicDefine1() {
    test("/** @define {boolean} */ var DEF = true", "var DEF=true");
  }

  public void testBasicDefine2() {
    test("/** @define {string} */ var DEF = 'a'", "var DEF=\"a\"");
  }

  public void testBasicDefine3() {
    test("/** @define {number} */ var DEF = 0", "var DEF=0");
  }

  public void testDefineBadType() {
    test("/** @define {Object} */ var DEF = {}",
        null, ProcessDefines.INVALID_DEFINE_TYPE_ERROR);
  }

  public void testDefineWithBadValue1() {
    test("/** @define {boolean} */ var DEF = new Boolean(true);", null,
        ProcessDefines.INVALID_DEFINE_INIT_ERROR);
  }

  public void testDefineWithBadValue2() {
    test("/** @define {string} */ var DEF = 'x' + y;", null,
        ProcessDefines.INVALID_DEFINE_INIT_ERROR);
  }

  public void testDefineWithDependentValue() {
    test("/** @define {boolean} */ var BASE = false;\n" +
         "/** @define {boolean} */ var DEF = !BASE;",
         "var BASE=false;var DEF=!BASE");
    test("var a = {};\n" +
         "/** @define {boolean} */ a.BASE = false;\n" +
         "/** @define {boolean} */ a.DEF = !a.BASE;",
         "var a={};a.BASE=false;a.DEF=!a.BASE");
  }

  public void testDefineWithInvalidDependentValue() {
    test("var BASE = false;\n" +
         "/** @define {boolean} */ var DEF = !BASE;",
         null,
          ProcessDefines.INVALID_DEFINE_INIT_ERROR);
  }

  public void testOverriding1() {
    overrides.put("DEF_OVERRIDE_TO_TRUE", new Node(Token.TRUE));
    overrides.put("DEF_OVERRIDE_TO_FALSE", new Node(Token.FALSE));
    test(
        "/** @define {boolean} */ var DEF_OVERRIDE_TO_TRUE = false;" +
        "/** @define {boolean} */ var DEF_OVERRIDE_TO_FALSE = true",
        "var DEF_OVERRIDE_TO_TRUE=true;var DEF_OVERRIDE_TO_FALSE=false");
  }

  public void testOverriding2() {
    overrides.put("DEF_OVERRIDE_TO_TRUE", new Node(Token.TRUE));
    String normalConst = "var DEF_OVERRIDE_TO_FALSE=true;";
    testWithPrefix(
        normalConst,
        "/** @define {boolean} */ var DEF_OVERRIDE_TO_TRUE = false",
        "var DEF_OVERRIDE_TO_TRUE=true");
  }

  public void testOverriding3() {
    overrides.put("DEF_OVERRIDE_TO_TRUE", new Node(Token.TRUE));
    test(
        "/** @define {boolean} */ var DEF_OVERRIDE_TO_TRUE = true;",
        "var DEF_OVERRIDE_TO_TRUE=true");
  }

  public void testOverridingString0() {
    test(
        "/** @define {string} */ var DEF_OVERRIDE_STRING = 'x';",
        "var DEF_OVERRIDE_STRING=\"x\"");
  }

  public void testOverridingString1() {
    test(
        "/** @define {string} */ var DEF_OVERRIDE_STRING = 'x' + 'y';",
        "var DEF_OVERRIDE_STRING=\"x\" + \"y\"");
  }

  public void testOverridingString2() {
    overrides.put("DEF_OVERRIDE_STRING", Node.newString("foo"));
    test(
        "/** @define {string} */ var DEF_OVERRIDE_STRING = 'x';",
        "var DEF_OVERRIDE_STRING=\"foo\"");
  }

  public void testOverridingString3() {
    overrides.put("DEF_OVERRIDE_STRING", Node.newString("foo"));
    test(
        "/** @define {string} */ var DEF_OVERRIDE_STRING = 'x' + 'y';",
        "var DEF_OVERRIDE_STRING=\"foo\"");
  }

  public void testMisspelledOverride() {
    overrides.put("DEF_BAD_OVERIDE", new Node(Token.TRUE));
    test("/** @define {boolean} */ var DEF_BAD_OVERRIDE = true",
        "var DEF_BAD_OVERRIDE=true", null,
        ProcessDefines.UNKNOWN_DEFINE_WARNING);
  }

  public void testCompiledIsKnownDefine() {
    overrides.put("COMPILED", new Node(Token.TRUE));
    testSame("");
  }

  public void testSimpleReassign1() {
    test("/** @define {boolean} */ var DEF = false; DEF = true;",
        "var DEF=true;true");
  }

  public void testSimpleReassign2() {
    test("/** @define {number|boolean} */ var DEF=false;DEF=true;DEF=3",
        "var DEF=3;true;3");

    Name def = namespace.getNameIndex().get("DEF");
    assertEquals(0, def.refs.size());
    assertEquals(1, def.globalSets);
    assertNotNull(def.declaration);
  }

  public void testSimpleReassign3() {
    test("/** @define {boolean} */ var DEF = false;var x;x = DEF = true;",
        "var DEF=true;var x;x=true");
  }

  public void testDuplicateVar() {
    test("/** @define {boolean} */ var DEF = false; var DEF = true;",
         null, VAR_MULTIPLY_DECLARED_ERROR);
  }

  public void testAssignBeforeDeclaration1() {
    test("DEF=false;var b=false,/** @define {boolean} */DEF=true,c=false",
         null, ProcessDefines.INVALID_DEFINE_INIT_ERROR);
  }

  public void testAssignBeforeDeclaration2() {
    overrides.put("DEF_OVERRIDE_TO_TRUE", new Node(Token.TRUE));
    test(
        "DEF_OVERRIDE_TO_TRUE = 3;" +
        "/** @define {boolean|number} */ var DEF_OVERRIDE_TO_TRUE = false;",
        null, ProcessDefines.INVALID_DEFINE_INIT_ERROR);
  }

  public void testEmptyDeclaration() {
    test("/** @define {boolean} */ var DEF;",
         null, ProcessDefines.INVALID_DEFINE_INIT_ERROR);
  }

  public void testReassignAfterCall() {
    test("/** @define {boolean} */var DEF=true;externMethod();DEF=false",
        null, ProcessDefines.DEFINE_NOT_ASSIGNABLE_ERROR);
  }

  public void testReassignAfterRef() {
    test("/** @define {boolean} */var DEF=true;var x = DEF;DEF=false",
        null, ProcessDefines.DEFINE_NOT_ASSIGNABLE_ERROR);
  }

  public void testReassignWithExpr() {
    test("/** @define {boolean} */var DEF=true;var x;DEF=x=false",
        null, ProcessDefines.INVALID_DEFINE_INIT_ERROR);
  }

  public void testReassignAfterNonGlobalRef() {
    test(
        "/** @define {boolean} */var DEF=true;" +
        "var x=function(){var y=DEF}; DEF=false",
        "var DEF=false;var x=function(){var y=DEF};false");

    Name def = namespace.getNameIndex().get("DEF");
    assertEquals(1, def.refs.size());
    assertEquals(1, def.globalSets);
    assertNotNull(def.declaration);
  }

  public void testReassignAfterRefInConditional() {
    test(
        "/** @define {boolean} */var DEF=true;" +
        "if (false) {var x=DEF} DEF=false;",
        null, ProcessDefines.DEFINE_NOT_ASSIGNABLE_ERROR);
  }

  public void testAssignInNonGlobalScope() {
    test("/** @define {boolean} */var DEF=true;function foo() {DEF=false};",
        null, ProcessDefines.NON_GLOBAL_DEFINE_INIT_ERROR);
  }

  public void testDeclareInNonGlobalScope() {
    test("function foo() {/** @define {boolean} */var DEF=true;};",
        null, ProcessDefines.NON_GLOBAL_DEFINE_INIT_ERROR);
  }

  public void testDefineAssignmentInLoop() {
    test("/** @define {boolean} */var DEF=true;var x=0;while (x) {DEF=false;}",
        null, ProcessDefines.NON_GLOBAL_DEFINE_INIT_ERROR);
  }

  public void testWithNoDefines() {
    testSame("var DEF=true;var x={};x.foo={}");
  }

  public void testNamespacedDefine1() {
    test("var a = {}; /** @define {boolean} */ a.B = false; a.B = true;",
         "var a = {}; a.B = true; true;");

    Name aDotB = namespace.getNameIndex().get("a.B");
    assertEquals(0, aDotB.refs.size());
    assertEquals(1, aDotB.globalSets);
    assertNotNull(aDotB.declaration);
  }

  public void testNamespacedDefine2a() {
    overrides.put("a.B", new Node(Token.TRUE));
    test("var a = {}; /** @define {boolean} */ a.B = false;",
         "var a = {}; a.B = true;");
  }

  public void testNamespacedDefine2b() {
    // TODO(johnlenz): We should either reject the define as invalid
    // or replace its value.
    overrides.put("a.B", new Node(Token.TRUE));
    test("var a = { /** @define {boolean} */ B : false };",
         "var a = {B : false};",
         null, ProcessDefines.UNKNOWN_DEFINE_WARNING);
  }

  public void testNamespacedDefine2c() {
    // TODO(johnlenz): We should either reject the define as invalid
    // or replace its value.
    overrides.put("a.B", new Node(Token.TRUE));
    test("var a = { /** @define {boolean} */ get B() { return false } };",
      "var a = {get B() { return false } };",
      null, ProcessDefines.UNKNOWN_DEFINE_WARNING);
  }

  public void testNamespacedDefine3() {
    overrides.put("a.B", new Node(Token.TRUE));
    test("var a = {};", "var a = {};", null,
         ProcessDefines.UNKNOWN_DEFINE_WARNING);
  }

  public void testNamespacedDefine4() {
    overrides.put("a.B", new Node(Token.TRUE));
    test("var a = {}; /** @define {boolean} */ a.B = false;",
         "var a = {}; a.B = true;");
  }

  public void testOverrideAfterAlias() {
    test("var x; /** @define {boolean} */var DEF=true; x=DEF; DEF=false;",
         null, ProcessDefines.DEFINE_NOT_ASSIGNABLE_ERROR);
  }

  private class ProcessDefinesWithInjectedNamespace implements CompilerPass {
    private final Compiler compiler;

    public ProcessDefinesWithInjectedNamespace(Compiler compiler) {
      this.compiler = compiler;
    }

    public void process(Node externs, Node js) {
      namespace = new GlobalNamespace(compiler, js);
      new ProcessDefines(compiler, overrides)
          .injectNamespace(namespace)
          .process(externs, js);
    }
  }
}


text:
package allocator

import (
	"encoding/json"
	"fmt"
	"net"

	"github.com/containernetworking/cni/pkg/types"
)

// IPAMConfig represents the IP related network configuration.
type IPAMConfig struct {
	Name       string
	Type       string        `json:"type"`
	RangeStart net.IP        `json:"rangeStart"`
	RangeEnd   net.IP        `json:"rangeEnd"`
	Subnet     types.IPNet   `json:"subnet"`
	Gateway    net.IP        `json:"gateway"`
	Routes     []types.Route `json:"routes"`
	DataDir    string        `json:"dataDir"`
	ResolvConf string        `json:"resolvConf"`
	Args       *IPAMArgs     `json:"-"`
}

type IPAMArgs struct {
	types.CommonArgs
	IP net.IP `json:"ip,omitempty"`
}

type Net struct {
	Name       string      `json:"name"`
	CNIVersion string      `json:"cniVersion"`
	IPAM       *IPAMConfig `json:"ipam"`
}

// NewIPAMConfig creates a NetworkConfig from the given network name.
func LoadIPAMConfig(bytes []byte, args string) (*IPAMConfig, string, error) {
	n := Net{}
	if err := json.Unmarshal(bytes, &n); err != nil {
		return nil, "", err
	}

	if n.IPAM == nil {
		return nil, "", fmt.Errorf("IPAM config missing 'ipam' key")
	}

	if args != "" {
		n.IPAM.Args = &IPAMArgs{}
		err := types.LoadArgs(args, n.IPAM.Args)
		if err != nil {
			return nil, "", err
		}
	}

	// Copy net name into IPAM so not to drag Net struct around
	n.IPAM.Name = n.Name

	return n.IPAM, n.CNIVersion, nil
}

func convertRoutesToCurrent(routes []types.Route) []*types.Route {
	var currentRoutes []*types.Route
	for _, r := range routes {
		currentRoutes = append(currentRoutes, &types.Route{
			Dst: r.Dst,
			GW:  r.GW,
		})
	}
	return currentRoutes
}


text:
/**********************************************************************************************************************************************************************************************************
 *
 * @class - LevelGraphNodeType - Collection of all constant types of a LevelGraphNode which are currently supported by the application.
 *
 * @author - Arthur Kaul
 *
 *********************************************************************************************************************************************************************************************************/
export class LevelGraphNodeType {
  public static readonly NODETYPE = 'NODETYPE';
  public static readonly RELATIONSHIPTYPE = 'RELATIONSHIPTYPE';
  public static readonly NODETYPEFRAGMENT = 'NODETYPEFRAGMENT';
  public static readonly RELATIONSHIPTYPEFRAGMENT = 'RELATIONSHIPTYPEFRAGMENT';
}


text:
package org.jclouds.ec2.binders;

import javax.inject.Singleton;

import org.jclouds.aws.util.AWSUtils;
import org.jclouds.http.HttpRequest;
import org.jclouds.rest.Binder;

/**
 * Binds the Iterable to form parameters named with UserId.index
 */
@Singleton
public class BindUserIdsToIndexedFormParams implements Binder {
   @Override
   public <R extends HttpRequest> R bindToRequest(R request, Object input) {
      return AWSUtils.indexIterableToFormValuesWithPrefix(request, "UserId", input);
   }

}


text:
from __future__ import unicode_literals

from django.db import migrations, models
import employee.models.employee

class Migration(migrations.Migration):

    dependencies = [
        ('employee', '0006_employee_avatar'),
    ]

    operations = [
        migrations.AlterField(
            model_name='employee',
            name='avatar',
            field=models.FileField(blank=True, default='default.jpg', null=True, upload_to=employee.models.employee.avatar_location, verbose_name='User icon'),
        ),
    ]


text:
Samples

This page shows the samples associated with the current <%-TYPE%>

	 New Sample


text:
// Copyright (c) 2016 Couchbase, Inc.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
// except in compliance with the License. You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied. See the License for the specific language governing permissions
// and limitations under the License.
#include "skiplist.hh"
#include <vector>
#include <thread>
#include <iostream>

static unsigned int seed;

void insert(Skiplist *s, int n, bool is_rand) {
    for (int x=0; x < n; x++) {
        unsigned r;
        if (is_rand) {
            r = rand_r(&seed);
        } else {
            r = x;
        }
        int *v = (int *) skiplist_malloc(sizeof(int));
        *v = r;
        Item *itm = newItem(v, sizeof(int));
        Skiplist_Insert(s, itm);
    }
}

void lookup(Skiplist *s, int n) {
    Node *preds[MaxLevel], *succs[MaxLevel];
    for (int x=0; x < n; x++) {
        unsigned r = rand_r(&seed);
        int *v = (int *) skiplist_malloc(sizeof(int));
        *v = r % n;
        Item *itm = newItem(v, sizeof(int));
        Skiplist_findPath(s, itm, preds, succs);
        skiplist_free(itm);
    }
}

int main() {

    srand(time(NULL));
    int i = 100;
    Skiplist *s = newSkiplist();
    std::vector<std::thread> threads;

    insert(s, 10000000, false);

    time_t t0 = time(NULL);
    /*
    for (int x=0; x < 8; x++) {
        threads.push_back(std::thread(&insert,s, 1000000, true));
    }
    */
    for (int x=0; x < 8; x++) {
        threads.push_back(std::thread(&lookup,s, 1000000));
    }

    for (auto& th : threads) th.join();
    std::cout<<"took "<<(time(NULL)-t0)<<"s"<<std::endl;

    exit(0);
    int count = 0;
    Node *p = s->head;
    while (p) {
        if (p->itm->l == 4) {
            count++;
//            std::cout<<"itm "<<count<<" - "<<*((int *)(p->itm->data))<<std::endl;
        }

        NodeRef r = Node_getNext(p, 0);
        p = r.ptr;
    }

    std::cout<<count<<std::endl;
}


text:
#ifndef DJC_MATH_COMPILE_HPP
#define DJC_MATH_COMPILE_HPP

// std
#include <cstddef> // std::size_t

/* to force all operations to happen at compile time the function return
 must be assigned to a constexpr variable. if not bound to a constexpr variable prepare to incure massive runtime costs :)

example

auto constexpr test =  constexpr_power(2.0f , 10); // compile time
auto test =  constexpr_power(2.0f , 10); // runtime
*/

namespace djc::math {

//------------------------------------------------------------
template <typename T>
constexpr T constexpr_power(T const& x, std::size_t n);

//------------------------------------------------------------
template<typename T>
constexpr T constexpr_factoral(T x);

//------------------------------------------------------------
constexpr double
constexpr_sqrt(double x);

//------------------------------------------------------------
constexpr double
constexpr_sin();

//------------------------------------------------------------
constexpr double
constexpr_cos(); // @todo:

//------------------------------------------------------------
constexpr double
constexpr_tan(); // @todo:

}; // djc::math
#include "inline/compile_inl.hpp"
#endif // DJC_MATH_COMPILE_HPP


text:
sh comp.sh
sh exec.sh


text:
define(["require", "exports", "./notification.service", "./module", "./module-require"], function (require, exports, notification_service_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    function notificationServiceFactory(i) {
        return i.get("NotificationService");
    }
    exports.notificationServiceFactory = notificationServiceFactory;
    exports.notificationServiceProvider = {
        provide: notification_service_1.NotificationService,
        useFactory: notificationServiceFactory,
        deps: ["$injector"]
    };
});
//# sourceMappingURL=angular2.js.map


text:
#ifndef GRIDREGION_H
#define GRIDREGION_H

#include "gridcell.h"
#include "Tree/treenode.h"

class GridCell;

class GridRegion
{
public:
    /* Constructor */
    GridRegion(TreeNode* n) : associatedNode(n) {}

    /* Make new nodes */
    GridRegion* addChildRegion(TreeNode* n);

    /* Where the magic happens */
    void buildGrid();

    QList<GridRegion*> getChildren() { return children; }

    /* Print */
    QString toString();

private:
    /* Connections */
    GridRegion* parent;
    QList<GridRegion*> children;
    TreeNode* associatedNode;

    /* Array */
    int width;
    int height;
    GridCell*** array; // array[col][row]

    /* Copies my elements into the provided array */
    void transferCells(int sx, int sy, GridCell*** parentArray);

    /* Helper to handle array allocations:
     * Only call after setting width and height */
    void allocateSpace();

    /* Helper to fill the corners and borders of a cut
     * Only call after allocating space */
    void addBorders();

    /* Helper to fill in padding
     * Only call after allocating space and transfering all children*/
    void fillPadding();
};

#endif // GRIDREGION_H