text:
#include <linux/module.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/ioport.h>
#include <linux/errno.h>
#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/string.h>
#include <linux/poll.h>
#include <linux/init.h>
#include <linux/interrupt.h>

#include <asm/etraxgpio.h>
#include <asm/arch/svinto.h>
#include <asm/io.h>
#include <asm/system.h>
#include <asm/irq.h>
#include <asm/arch/io_interface_mux.h>

#define GPIO_MAJOR 120  /* experimental MAJOR number */

#define D(x)

#if 0
static int dp_cnt;
#define DP(x) do { dp_cnt++; if (dp_cnt % 1000 == 0) x; }while(0)
#else
#define DP(x)
#endif

static char gpio_name[] = "etrax gpio";

#if 0
static wait_queue_head_t *gpio_wq;
#endif

static int gpio_ioctl(struct inode *inode, struct file *file,
		      unsigned int cmd, unsigned long arg);
static ssize_t gpio_write(struct file * file, const char * buf, size_t count,
                          loff_t *off);
static int gpio_open(struct inode *inode, struct file *filp);
static int gpio_release(struct inode *inode, struct file *filp);
static unsigned int gpio_poll(struct file *filp, struct poll_table_struct *wait);

/* private data per open() of this driver */

struct gpio_private {
	struct gpio_private *next;
	/* These fields are for PA and PB only */
	volatile unsigned char *port, *shadow;
	volatile unsigned char *dir, *dir_shadow;
	unsigned char changeable_dir;
	unsigned char changeable_bits;
	unsigned char clk_mask;
	unsigned char data_mask;
	unsigned char write_msb;
	unsigned char pad1, pad2, pad3;
	/* These fields are generic */
	unsigned long highalarm, lowalarm;
	wait_queue_head_t alarm_wq;
	int minor;
};

/* linked list of alarms to check for */

static struct gpio_private *alarmlist = 0;

static int gpio_some_alarms = 0; /* Set if someone uses alarm */
static unsigned long gpio_pa_irq_enabled_mask = 0;

static DEFINE_SPINLOCK(gpio_lock); /* Protect directions etc */

/* Port A and B use 8 bit access, but Port G is 32 bit */
#define NUM_PORTS (GPIO_MINOR_B+1)

static volatile unsigned char *ports[NUM_PORTS] = {
	R_PORT_PA_DATA,
	R_PORT_PB_DATA,
};
static volatile unsigned char *shads[NUM_PORTS] = {
	&port_pa_data_shadow,
	&port_pb_data_shadow
};

/* What direction bits that are user changeable 1=changeable*/
#ifndef CONFIG_ETRAX_PA_CHANGEABLE_DIR
#define CONFIG_ETRAX_PA_CHANGEABLE_DIR 0x00
#endif
#ifndef CONFIG_ETRAX_PB_CHANGEABLE_DIR
#define CONFIG_ETRAX_PB_CHANGEABLE_DIR 0x00
#endif

#ifndef CONFIG_ETRAX_PA_CHANGEABLE_BITS
#define CONFIG_ETRAX_PA_CHANGEABLE_BITS 0xFF
#endif
#ifndef CONFIG_ETRAX_PB_CHANGEABLE_BITS
#define CONFIG_ETRAX_PB_CHANGEABLE_BITS 0xFF
#endif

static unsigned char changeable_dir[NUM_PORTS] = {
	CONFIG_ETRAX_PA_CHANGEABLE_DIR,
	CONFIG_ETRAX_PB_CHANGEABLE_DIR
};
static unsigned char changeable_bits[NUM_PORTS] = {
	CONFIG_ETRAX_PA_CHANGEABLE_BITS,
	CONFIG_ETRAX_PB_CHANGEABLE_BITS
};

static volatile unsigned char *dir[NUM_PORTS] = {
	R_PORT_PA_DIR,
	R_PORT_PB_DIR
};

static volatile unsigned char *dir_shadow[NUM_PORTS] = {
	&port_pa_dir_shadow,
	&port_pb_dir_shadow
};

/* All bits in port g that can change dir. */
static const unsigned long int changeable_dir_g_mask = 0x01FFFF01;

/* Port G is 32 bit, handle it special, some bits are both inputs
   and outputs at the same time, only some of the bits can change direction
   and some of them in groups of 8 bit. */
static unsigned long changeable_dir_g;
static unsigned long dir_g_in_bits;
static unsigned long dir_g_out_bits;
static unsigned long dir_g_shadow; /* 1=output */

#define USE_PORTS(priv) ((priv)->minor <= GPIO_MINOR_B)

static unsigned int
gpio_poll(struct file *file,
	  poll_table *wait)
{
	unsigned int mask = 0;
	struct gpio_private *priv = (struct gpio_private *)file->private_data;
	unsigned long data;
	spin_lock(&gpio_lock);
	poll_wait(file, &priv->alarm_wq, wait);
	if (priv->minor == GPIO_MINOR_A) {
		unsigned long flags;
		unsigned long tmp;
		data = *R_PORT_PA_DATA;
		/* PA has support for high level interrupt -
		 * lets activate for those low and with highalarm set
		 */
		tmp = ~data & priv->highalarm & 0xFF;
		tmp = (tmp << R_IRQ_MASK1_SET__pa0__BITNR);
		local_irq_save(flags);
		gpio_pa_irq_enabled_mask |= tmp;
		*R_IRQ_MASK1_SET = tmp;
		local_irq_restore(flags);

	} else if (priv->minor == GPIO_MINOR_B)
		data = *R_PORT_PB_DATA;
	else if (priv->minor == GPIO_MINOR_G)
		data = *R_PORT_G_DATA;
	else
		return 0;

	if ((data & priv->highalarm) ||
	    (~data & priv->lowalarm)) {
		mask = POLLIN|POLLRDNORM;
	}

	spin_unlock(&gpio_lock);

	DP(printk("gpio_poll ready: mask 0x%08X\n", mask));

	return mask;
}

int etrax_gpio_wake_up_check(void)
{
	struct gpio_private *priv = alarmlist;
	unsigned long data = 0;
        int ret = 0;
	spin_lock(&gpio_lock);
	while (priv) {
		if (USE_PORTS(priv)) {
			data = *priv->port;
		} else if (priv->minor == GPIO_MINOR_G) {
			data = *R_PORT_G_DATA;
		}
		if ((data & priv->highalarm) ||
		    (~data & priv->lowalarm)) {
			DP(printk("etrax_gpio_wake_up_check %i\n",priv->minor));
			wake_up_interruptible(&priv->alarm_wq);
                        ret = 1;
		}
		priv = priv->next;
	}
	spin_unlock(&gpio_lock);
        return ret;
}

static irqreturn_t
gpio_poll_timer_interrupt(int irq, void *dev_id, struct pt_regs *regs)
{
	if (gpio_some_alarms) {
		etrax_gpio_wake_up_check();
                return IRQ_HANDLED;
	}
        return IRQ_NONE;
}

static irqreturn_t
gpio_pa_interrupt(int irq, void *dev_id, struct pt_regs *regs)
{
	unsigned long tmp;
	spin_lock(&gpio_lock);
	/* Find what PA interrupts are active */
	tmp = (*R_IRQ_READ1);

	/* Find those that we have enabled */
	tmp &= gpio_pa_irq_enabled_mask;

	/* Clear them.. */
	*R_IRQ_MASK1_CLR = tmp;
	gpio_pa_irq_enabled_mask &= ~tmp;

	spin_unlock(&gpio_lock);

	if (gpio_some_alarms) {
		return IRQ_RETVAL(etrax_gpio_wake_up_check());
	}
        return IRQ_NONE;
}

static ssize_t gpio_write(struct file * file, const char * buf, size_t count,
                          loff_t *off)
{
	struct gpio_private *priv = (struct gpio_private *)file->private_data;
	unsigned char data, clk_mask, data_mask, write_msb;
	unsigned long flags;

	spin_lock(&gpio_lock);

	ssize_t retval = count;
	if (priv->minor !=GPIO_MINOR_A && priv->minor != GPIO_MINOR_B) {
		return -EFAULT;
	}

	if (!access_ok(VERIFY_READ, buf, count)) {
		return -EFAULT;
	}
	clk_mask = priv->clk_mask;
	data_mask = priv->data_mask;
	/* It must have been configured using the IO_CFG_WRITE_MODE */
	/* Perhaps a better error code? */
	if (clk_mask == 0 || data_mask == 0) {
		return -EPERM;
	}
	write_msb = priv->write_msb;
	D(printk("gpio_write: %lu to data 0x%02X clk 0x%02X msb: %i\n",count, data_mask, clk_mask, write_msb));
	while (count--) {
		int i;
		data = *buf++;
		if (priv->write_msb) {
			for (i = 7; i >= 0;i--) {
				local_irq_save(flags);
				*priv->port = *priv->shadow &= ~clk_mask;
				if (data & 1<<i)
					*priv->port = *priv->shadow |= data_mask;
				else
					*priv->port = *priv->shadow &= ~data_mask;
			/* For FPGA: min 5.0ns (DCC) before CCLK high */
				*priv->port = *priv->shadow |= clk_mask;
				local_irq_restore(flags);
			}
		} else {
			for (i = 0; i <= 7;i++) {
				local_irq_save(flags);
				*priv->port = *priv->shadow &= ~clk_mask;
				if (data & 1<<i)
					*priv->port = *priv->shadow |= data_mask;
				else
					*priv->port = *priv->shadow &= ~data_mask;
			/* For FPGA: min 5.0ns (DCC) before CCLK high */
				*priv->port = *priv->shadow |= clk_mask;
				local_irq_restore(flags);
			}
		}
	}
	spin_unlock(&gpio_lock);
	return retval;
}

static int
gpio_open(struct inode *inode, struct file *filp)
{
	struct gpio_private *priv;
	int p = iminor(inode);

	if (p > GPIO_MINOR_LAST)
		return -EINVAL;

	priv = kmalloc(sizeof(struct gpio_private),
					      GFP_KERNEL);

	if (!priv)
		return -ENOMEM;

	priv->minor = p;

	/* initialize the io/alarm struct and link it into our alarmlist */

	priv->next = alarmlist;
	alarmlist = priv;
	if (USE_PORTS(priv)) { /* A and B */
		priv->port = ports[p];
		priv->shadow = shads[p];
		priv->dir = dir[p];
		priv->dir_shadow = dir_shadow[p];
		priv->changeable_dir = changeable_dir[p];
		priv->changeable_bits = changeable_bits[p];
	} else {
		priv->port = NULL;
		priv->shadow = NULL;
		priv->dir = NULL;
		priv->dir_shadow = NULL;
		priv->changeable_dir = 0;
		priv->changeable_bits = 0;
	}

	priv->highalarm = 0;
	priv->lowalarm = 0;
	priv->clk_mask = 0;
	priv->data_mask = 0;
	init_waitqueue_head(&priv->alarm_wq);

	filp->private_data = (void *)priv;

	return 0;
}

static int
gpio_release(struct inode *inode, struct file *filp)
{
	struct gpio_private *p;
	struct gpio_private *todel;

	spin_lock(&gpio_lock);

        p = alarmlist;
        todel = (struct gpio_private *)filp->private_data;

	/* unlink from alarmlist and free the private structure */

	if (p == todel) {
		alarmlist = todel->next;
	} else {
		while (p->next != todel)
			p = p->next;
		p->next = todel->next;
	}

	kfree(todel);
	/* Check if there are still any alarms set */
	p = alarmlist;
	while (p) {
		if (p->highalarm | p->lowalarm) {
			gpio_some_alarms = 1;
			return 0;
		}
		p = p->next;
	}
	gpio_some_alarms = 0;
	spin_unlock(&gpio_lock);
	return 0;
}

/* Main device API. ioctl's to read/set/clear bits, as well as to
 * set alarms to wait for using a subsequent select().
 */

unsigned long inline setget_input(struct gpio_private *priv, unsigned long arg)
{
	/* Set direction 0=unchanged 1=input,
	 * return mask with 1=input
	 */
	unsigned long flags;
	if (USE_PORTS(priv)) {
		local_irq_save(flags);
		*priv->dir = *priv->dir_shadow &=
		~((unsigned char)arg & priv->changeable_dir);
		local_irq_restore(flags);
		return ~(*priv->dir_shadow) & 0xFF; /* Only 8 bits */
	} else if (priv->minor == GPIO_MINOR_G) {
		/* We must fiddle with R_GEN_CONFIG to change dir */
		local_irq_save(flags);
		if (((arg & dir_g_in_bits) != arg) &&
		    (arg & changeable_dir_g)) {
			arg &= changeable_dir_g;
			/* Clear bits in genconfig to set to input */
			if (arg & (1<<0)) {
				genconfig_shadow &= ~IO_MASK(R_GEN_CONFIG,g0dir);
				dir_g_in_bits |= (1<<0);
				dir_g_out_bits &= ~(1<<0);
			}
			if ((arg & 0x0000FF00) == 0x0000FF00) {
				genconfig_shadow &= ~IO_MASK(R_GEN_CONFIG,g8_15dir);
				dir_g_in_bits |= 0x0000FF00;
				dir_g_out_bits &= ~0x0000FF00;
			}
			if ((arg & 0x00FF0000) == 0x00FF0000) {
				genconfig_shadow &= ~IO_MASK(R_GEN_CONFIG,g16_23dir);
				dir_g_in_bits |= 0x00FF0000;
				dir_g_out_bits &= ~0x00FF0000;
			}
			if (arg & (1<<24)) {
				genconfig_shadow &= ~IO_MASK(R_GEN_CONFIG,g24dir);
				dir_g_in_bits |= (1<<24);
				dir_g_out_bits &= ~(1<<24);
			}
			D(printk(KERN_INFO "gpio: SETINPUT on port G set "
				 "genconfig to 0x%08lX "
				 "in_bits: 0x%08lX "
				 "out_bits: 0x%08lX\n",
			         (unsigned long)genconfig_shadow,
			         dir_g_in_bits, dir_g_out_bits));
			*R_GEN_CONFIG = genconfig_shadow;
			/* Must be a >120 ns delay before writing this again */

		}
		local_irq_restore(flags);
		return dir_g_in_bits;
	}
	return 0;
} /* setget_input */

unsigned long inline setget_output(struct gpio_private *priv, unsigned long arg)
{
	unsigned long flags;
	if (USE_PORTS(priv)) {
		local_irq_save(flags);
		*priv->dir = *priv->dir_shadow |=
		  ((unsigned char)arg & priv->changeable_dir);
		local_irq_restore(flags);
		return *priv->dir_shadow;
	} else if (priv->minor == GPIO_MINOR_G) {
		/* We must fiddle with R_GEN_CONFIG to change dir */
		local_irq_save(flags);
		if (((arg & dir_g_out_bits) != arg) &&
		    (arg & changeable_dir_g)) {
			/* Set bits in genconfig to set to output */
			if (arg & (1<<0)) {
				genconfig_shadow |= IO_MASK(R_GEN_CONFIG,g0dir);
				dir_g_out_bits |= (1<<0);
				dir_g_in_bits &= ~(1<<0);
			}
			if ((arg & 0x0000FF00) == 0x0000FF00) {
				genconfig_shadow |= IO_MASK(R_GEN_CONFIG,g8_15dir);
				dir_g_out_bits |= 0x0000FF00;
				dir_g_in_bits &= ~0x0000FF00;
			}
			if ((arg & 0x00FF0000) == 0x00FF0000) {
				genconfig_shadow |= IO_MASK(R_GEN_CONFIG,g16_23dir);
				dir_g_out_bits |= 0x00FF0000;
				dir_g_in_bits &= ~0x00FF0000;
			}
			if (arg & (1<<24)) {
				genconfig_shadow |= IO_MASK(R_GEN_CONFIG,g24dir);
				dir_g_out_bits |= (1<<24);
				dir_g_in_bits &= ~(1<<24);
			}
			D(printk(KERN_INFO "gpio: SETOUTPUT on port G set "
				 "genconfig to 0x%08lX "
				 "in_bits: 0x%08lX "
				 "out_bits: 0x%08lX\n",
			         (unsigned long)genconfig_shadow,
			         dir_g_in_bits, dir_g_out_bits));
			*R_GEN_CONFIG = genconfig_shadow;
			/* Must be a >120 ns delay before writing this again */
		}
		local_irq_restore(flags);
		return dir_g_out_bits & 0x7FFFFFFF;
	}
	return 0;
} /* setget_output */

static int
gpio_leds_ioctl(unsigned int cmd, unsigned long arg);

static int
gpio_ioctl(struct inode *inode, struct file *file,
	   unsigned int cmd, unsigned long arg)
{
	unsigned long flags;
	unsigned long val;
        int ret = 0;

	struct gpio_private *priv = (struct gpio_private *)file->private_data;
	if (_IOC_TYPE(cmd) != ETRAXGPIO_IOCTYPE) {
		return -EINVAL;
	}

	spin_lock(&gpio_lock);

	switch (_IOC_NR(cmd)) {
	case IO_READBITS: /* Use IO_READ_INBITS and IO_READ_OUTBITS instead */
		// read the port
		if (USE_PORTS(priv)) {
			ret =  *priv->port;
		} else if (priv->minor == GPIO_MINOR_G) {
			ret =  (*R_PORT_G_DATA) & 0x7FFFFFFF;
		}
		break;
	case IO_SETBITS:
		local_irq_save(flags);
		// set changeable bits with a 1 in arg
		if (USE_PORTS(priv)) {
			*priv->port = *priv->shadow |=
			  ((unsigned char)arg & priv->changeable_bits);
		} else if (priv->minor == GPIO_MINOR_G) {
			*R_PORT_G_DATA = port_g_data_shadow |= (arg & dir_g_out_bits);
		}
		local_irq_restore(flags);
		break;
	case IO_CLRBITS:
		local_irq_save(flags);
		// clear changeable bits with a 1 in arg
		if (USE_PORTS(priv)) {
			*priv->port = *priv->shadow &=
			 ~((unsigned char)arg & priv->changeable_bits);
		} else if (priv->minor == GPIO_MINOR_G) {
			*R_PORT_G_DATA = port_g_data_shadow &= ~((unsigned long)arg & dir_g_out_bits);
		}
		local_irq_restore(flags);
		break;
	case IO_HIGHALARM:
		// set alarm when bits with 1 in arg go high
		priv->highalarm |= arg;
		gpio_some_alarms = 1;
		break;
	case IO_LOWALARM:
		// set alarm when bits with 1 in arg go low
		priv->lowalarm |= arg;
		gpio_some_alarms = 1;
		break;
	case IO_CLRALARM:
		// clear alarm for bits with 1 in arg
		priv->highalarm &= ~arg;
		priv->lowalarm  &= ~arg;
		{
			/* Must update gpio_some_alarms */
			struct gpio_private *p = alarmlist;
			int some_alarms;
			some_alarms = 0;
			while (p) {
				if (p->highalarm | p->lowalarm) {
					some_alarms = 1;
					break;
				}
				p = p->next;
			}
			gpio_some_alarms = some_alarms;
		}
		break;
	case IO_READDIR: /* Use IO_SETGET_INPUT/OUTPUT instead! */
		/* Read direction 0=input 1=output */
		if (USE_PORTS(priv)) {
			ret = *priv->dir_shadow;
		} else if (priv->minor == GPIO_MINOR_G) {
			/* Note: Some bits are both in and out,
			 * Those that are dual is set here as well.
			 */
			ret = (dir_g_shadow | dir_g_out_bits) & 0x7FFFFFFF;
		}
		break;
	case IO_SETINPUT: /* Use IO_SETGET_INPUT instead! */
		/* Set direction 0=unchanged 1=input,
		 * return mask with 1=input
		 */
		ret = setget_input(priv, arg) & 0x7FFFFFFF;
		break;
	case IO_SETOUTPUT: /* Use IO_SETGET_OUTPUT instead! */
		/* Set direction 0=unchanged 1=output,
		 * return mask with 1=output
		 */
		ret =  setget_output(priv, arg) & 0x7FFFFFFF;
		break;
	case IO_SHUTDOWN:
		SOFT_SHUTDOWN();
		break;
	case IO_GET_PWR_BT:
#if defined (CONFIG_ETRAX_SOFT_SHUTDOWN)
		ret = (*R_PORT_G_DATA & ( 1 << CONFIG_ETRAX_POWERBUTTON_BIT));
#else
		ret = 0;
#endif
		break;
	case IO_CFG_WRITE_MODE:
		priv->clk_mask = arg & 0xFF;
		priv->data_mask = (arg >> 8) & 0xFF;
		priv->write_msb = (arg >> 16) & 0x01;
		/* Check if we're allowed to change the bits and
		 * the direction is correct
		 */
		if (!((priv->clk_mask & priv->changeable_bits) &&
		      (priv->data_mask & priv->changeable_bits) &&
		      (priv->clk_mask & *priv->dir_shadow) &&
		      (priv->data_mask & *priv->dir_shadow)))
		{
			priv->clk_mask = 0;
			priv->data_mask = 0;
			ret = -EPERM;
		}
		break;
	case IO_READ_INBITS:
		/* *arg is result of reading the input pins */
		if (USE_PORTS(priv)) {
			val = *priv->port;
		} else if (priv->minor == GPIO_MINOR_G) {
			val = *R_PORT_G_DATA;
		}
		if (copy_to_user((unsigned long*)arg, &val, sizeof(val)))
			ret = -EFAULT;
		break;
	case IO_READ_OUTBITS:
		 /* *arg is result of reading the output shadow */
		if (USE_PORTS(priv)) {
			val = *priv->shadow;
		} else if (priv->minor == GPIO_MINOR_G) {
			val = port_g_data_shadow;
		}
		if (copy_to_user((unsigned long*)arg, &val, sizeof(val)))
			ret = -EFAULT;
		break;
	case IO_SETGET_INPUT:
		/* bits set in *arg is set to input,
		 * *arg updated with current input pins.
		 */
		if (copy_from_user(&val, (unsigned long*)arg, sizeof(val)))
		{
			ret = -EFAULT;
			break;
		}
		val = setget_input(priv, val);
		if (copy_to_user((unsigned long*)arg, &val, sizeof(val)))
			ret = -EFAULT;
		break;
	case IO_SETGET_OUTPUT:
		/* bits set in *arg is set to output,
		 * *arg updated with current output pins.
		 */
		if (copy_from_user(&val, (unsigned long*)arg, sizeof(val)))
		{
			ret = -EFAULT;
			break;
		}
		val = setget_output(priv, val);
		if (copy_to_user((unsigned long*)arg, &val, sizeof(val)))
			ret = -EFAULT;
		break;
	default:
		if (priv->minor == GPIO_MINOR_LEDS)
			ret = gpio_leds_ioctl(cmd, arg);
		else
			ret = -EINVAL;
	} /* switch */

	spin_unlock(&gpio_lock);
	return ret;
}

static int
gpio_leds_ioctl(unsigned int cmd, unsigned long arg)
{
	unsigned char green;
	unsigned char red;

	switch (_IOC_NR(cmd)) {
	case IO_LEDACTIVE_SET:
		green = ((unsigned char) arg) & 1;
		red   = (((unsigned char) arg) >> 1) & 1;
		LED_ACTIVE_SET_G(green);
		LED_ACTIVE_SET_R(red);
		break;

	case IO_LED_SETBIT:
		LED_BIT_SET(arg);
		break;

	case IO_LED_CLRBIT:
		LED_BIT_CLR(arg);
		break;

	default:
		return -EINVAL;
	} /* switch */

	return 0;
}

const struct file_operations gpio_fops = {
	.owner       = THIS_MODULE,
	.poll        = gpio_poll,
	.ioctl       = gpio_ioctl,
	.write       = gpio_write,
	.open        = gpio_open,
	.release     = gpio_release,
};

void ioif_watcher(const unsigned int gpio_in_available,
		  const unsigned int gpio_out_available,
		  const unsigned char pa_available,
		  const unsigned char pb_available)
{
	unsigned long int flags;
	D(printk("gpio.c: ioif_watcher called\n"));
	D(printk("gpio.c: G in: 0x%08x G out: 0x%08x PA: 0x%02x PB: 0x%02x\n",
		 gpio_in_available, gpio_out_available, pa_available, pb_available));

	spin_lock_irqsave(&gpio_lock, flags);

	dir_g_in_bits = gpio_in_available;
	dir_g_out_bits = gpio_out_available;

	/* Initialise the dir_g_shadow etc. depending on genconfig */
	/* 0=input 1=output */
	if (genconfig_shadow & IO_STATE(R_GEN_CONFIG, g0dir, out))
		dir_g_shadow |= (1 << 0);
	if (genconfig_shadow & IO_STATE(R_GEN_CONFIG, g8_15dir, out))
		dir_g_shadow |= 0x0000FF00;
	if (genconfig_shadow & IO_STATE(R_GEN_CONFIG, g16_23dir, out))
		dir_g_shadow |= 0x00FF0000;
	if (genconfig_shadow & IO_STATE(R_GEN_CONFIG, g24dir, out))
		dir_g_shadow |= (1 << 24);

	changeable_dir_g = changeable_dir_g_mask;
	changeable_dir_g &= dir_g_out_bits;
	changeable_dir_g &= dir_g_in_bits;
	/* Correct the bits that can change direction */
	dir_g_out_bits &= ~changeable_dir_g;
	dir_g_out_bits |= dir_g_shadow;
	dir_g_in_bits &= ~changeable_dir_g;
	dir_g_in_bits |= (~dir_g_shadow & changeable_dir_g);

	spin_unlock_irqrestore(&gpio_lock, flags);

	printk(KERN_INFO "GPIO port G: in_bits: 0x%08lX out_bits: 0x%08lX val: %08lX\n",
	       dir_g_in_bits, dir_g_out_bits, (unsigned long)*R_PORT_G_DATA);
	printk(KERN_INFO "GPIO port G: dir: %08lX changeable: %08lX\n",
	       dir_g_shadow, changeable_dir_g);
}

/* main driver initialization routine, called from mem.c */

static __init int
gpio_init(void)
{
	int res;
#if defined (CONFIG_ETRAX_CSP0_LEDS)
	int i;
#endif
        printk("gpio init\n");

	/* do the formalities */

	res = register_chrdev(GPIO_MAJOR, gpio_name, &gpio_fops);
	if (res < 0) {
		printk(KERN_ERR "gpio: couldn't get a major number.\n");
		return res;
	}

	/* Clear all leds */
#if defined (CONFIG_ETRAX_CSP0_LEDS) ||  defined (CONFIG_ETRAX_PA_LEDS) || defined (CONFIG_ETRAX_PB_LEDS)
	LED_NETWORK_SET(0);
	LED_ACTIVE_SET(0);
	LED_DISK_READ(0);
	LED_DISK_WRITE(0);

#if defined (CONFIG_ETRAX_CSP0_LEDS)
	for (i = 0; i < 32; i++) {
		LED_BIT_SET(i);
	}
#endif

#endif
	/* The I/O interface allocation watcher will be called when
	 * registering it. */
	if (cris_io_interface_register_watcher(ioif_watcher)){
		printk(KERN_WARNING "gpio_init: Failed to install IO if allocator watcher\n");
	}

	printk(KERN_INFO "ETRAX 100LX GPIO driver v2.5, (c) 2001, 2002, 2003, 2004 Axis Communications AB\n");
	/* We call etrax_gpio_wake_up_check() from timer interrupt and
	 * from cpu_idle() in kernel/process.c
	 * The check in cpu_idle() reduces latency from ~15 ms to ~6 ms
	 * in some tests.
	 */
	if (request_irq(TIMER0_IRQ_NBR, gpio_poll_timer_interrupt,
			IRQF_SHARED | IRQF_DISABLED,"gpio poll", NULL)) {
		printk(KERN_CRIT "err: timer0 irq for gpio\n");
	}
	if (request_irq(PA_IRQ_NBR, gpio_pa_interrupt,
			IRQF_SHARED | IRQF_DISABLED,"gpio PA", NULL)) {
		printk(KERN_CRIT "err: PA irq for gpio\n");
	}

	return res;
}

/* this makes sure that gpio_init is called during kernel boot */

module_init(gpio_init);


text:
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="keywords" content="Sam Dutton, Razvan Caliman, CSS, HTML5" />
<meta name="description" content="Simplest possible example of CSS regions with empty elements as placeholders" />
<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1">
<meta http-equiv="X-UA-Compatible" content="chrome=1"/>
<title>CSS Regions</title>
<link rel="stylesheet" href="../css/main.css" />

simpl.info CSS Regions

If you don't see two blocks of text side-by-side, CSS regions are not supported.
Change the window size to see content flowing from one block to the other:

Displaying the complex layouts of a typical magazine, newspaper, or textbook on the web requires capabilities beyond those available in existing CSS modules. Dynamic magazine layout in particular requires flexibility in placement of boxes for content flows. This is the purpose of the CSS regions module.

The CSS regions module allows content to flow across multiple areas called regions. The regions are not necessarily contiguous in the document order. The CSS regions module provides an advanced content flow mechanism, which can be combined with positioning schemes as defined by other CSS modules such as the Multi-Column Module or the Grid Layout Module to position the regions where content flows.

View source on GitHub

redpajama_set_name: RedPajamaGithub


text:
				<?php echo form_open_multipart('items/do_edit', array('id' => 'fromedit'));?>

 Product Information

									 * Product Name

									<input type="text" name="item_name" placeholder="Product Name" value="<?php echo $result->item_name;?>" required>

									 * Category

									<select name="category">
										<?php foreach($category->result() as $cate){?>
										<option <?php if($cate->category_name == $result->category){echo 'selected="selected"';}?> value="<?php echo $cate->category_name;?>"><?php echo $cate->category_name;?></option>
										<?php }?>
									</select>

								   * Brand

									<select  name="brand">
										<?php foreach($brand->result() as $bran){?>
										<option <?php if($bran->brand_name == $result->brand){echo 'selected="selected"';}?> value="<?php echo $bran->brand_name;?>"><?php echo $bran->brand_name;?></option>
										<?php }?>
									</select>

									 * Price

									<input type="text" name="price" placeholder="Price" value="<?php echo $result->price;?>" required />

								   * Add to shop

									<select name="shop">
										<?php foreach($shop->result() as $shops){?>
										<option <?php if($shops->shop_name == $result->shop){echo 'selected="selected"';}?> value="<?php echo $shops->shop_name;?>"><?php echo $shops->shop_name;?></option>
										<?php }?>
									</select>

										<input type="hidden" value="0" name="best_seller"  />
										<input type="checkbox" name="best_seller" id="pro_popular" value="1" />
										  Best Seller

									Description

									<textarea rows="8" name="description" placeholder="Description"><?php echo $result->description;?></textarea>

							<?php echo form_hidden('item_id', $result->item_id);?>

									 * Product Photo

													<img src="<?php echo base_url('uploads/thumbnail/'.$result->img_one);?>">

												<input type="file" name="thumbnail1" id="product_main_img" onchange="readURL(this);" title="" />

													<img src="<?php echo base_url('uploads/thumbnail/'.$result->img_two);?>">

												<input type="file" multiple name="thumbnail2" id="product_img_1" rowNum="1" onchange="readURLmat(this);" title="" />

													<img src="<?php echo base_url('uploads/thumbnail/'.$result->img_three);?>">

												<input type="file" multiple name="thumbnail3" id="product_img_2" rowNum="2" onchange="readURLmat(this);" title="" />

													<img src="<?php echo base_url('uploads/thumbnail/'.$result->img_four);?>">

												<input type="file" multiple name="thumbnail4" id="product_img_3" rowNum="3" onchange="readURLmat(this);" title="" />

								<input type="submit" name="save" class="tiny button" value="Save">

				<?php echo form_close()?>


text:
package eu.bcvsolutions.idm.ic.impl;

import eu.bcvsolutions.idm.ic.api.IcAttribute;
import eu.bcvsolutions.idm.ic.api.IcAttributeInfo;

/**
 * IcAttributeInfo is meta data responsible for describing an
 * {@link IcAttribute}.
 *
 * @author svandav
 *
 */
public class IcAttributeInfoImpl implements IcAttributeInfo {

	private String name;
	private String classType;
	private String nativeName;
	private boolean required;
	private boolean multivalued;
	private boolean createable;
	private boolean updateable;
	private boolean readable;
	private boolean returnedByDefault;

	/**
	 * The name of the attribute. This the attribute name as it is known by the
	 * framework. It may be derived from the native attribute name. Or it may be
	 * one of the special names such as __NAME__ or __PASSWORD__.
	 *
	 * @return the name of the attribute its describing.
	 */
	@Override
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	/**
	 * The basic type associated with this attribute. All primitives are
	 * supported.
	 *
	 * @return the native type if uses.
	 */
	@Override
	public String getClassType() {
		return classType;
	}

	public void setClassType(String classType) {
		this.classType = classType;
	}

	/**
	 * The native name of the attribute. This is the attribute name as it is
	 * known by the resource. It is especially useful for attributes with
	 * special names such as __NAME__ or __PASSWORD__. In this case the
	 * nativeName will contain the real name of the attribute. The nativeName
	 * may be null. In such a case it is assumed that the native name is the
	 * same as name.
	 *
	 * @return the native name of the attribute its describing.
	 */
	@Override
	public String getNativeName() {
		return nativeName;
	}

	public void setNativeName(String nativeName) {
		this.nativeName = nativeName;
	}

	/**
	 * Determines whether this attribute is required for creates.
	 *
	 * @return true if the attribute is required for an object else false.
	 */
	@Override
	public boolean isRequired() {
		return required;
	}

	public void setRequired(boolean required) {
		this.required = required;
	}

	/**
	 * Determines if this attribute can handle multiple values.
	 *
	 * There is a special case with byte[] since in most instances this denotes
	 * a single object.
	 *
	 * @return true if the attribute is multi-value otherwise false.
	 */
	@Override
	public boolean isMultivalued() {
		return multivalued;
	}

	public void setMultivalued(boolean multivalued) {
		this.multivalued = multivalued;
	}

	/**
	 * Determines if the attribute is writable on create.
	 *
	 * @return true if the attribute is writable on create else false.
	 */
	@Override
	public boolean isCreateable() {
		return createable;
	}

	public void setCreateable(boolean createable) {
		this.createable = createable;
	}

	/**
	 * Determines if the attribute is writable on update.
	 *
	 * @return true if the attribute is writable on update else false.
	 */
	@Override
	public boolean isUpdateable() {
		return updateable;
	}

	public void setUpdateable(boolean updateable) {
		this.updateable = updateable;
	}

	/**
	 * Determines if the attribute is readable.
	 *
	 * @return true if the attribute is readable else false.
	 */
	@Override
	public boolean isReadable() {
		return readable;
	}

	public void setReadable(boolean readable) {
		this.readable = readable;
	}

	/**
	 * Determines if the attribute is returned by default.
	 *
	 * Indicates if an attribute will be returned during search, sync or get
	 * operations inside a connector object by default. The default value is
	 * true.
	 *
	 * @return false if the attribute should not be returned by default.
	 */
	@Override
	public boolean isReturnedByDefault() {
		return returnedByDefault;
	}

	public void setReturnedByDefault(boolean returnedByDefault) {
		this.returnedByDefault = returnedByDefault;
	}

	@Override
	public String toString() {
		return "IcSchemaAttributeInfo [name=" + name + ", classType=" + classType + "]";
	}

}


text:
@implementation IFBKLaunchpadAccount

@dynamic type, hrefUrl;

- (void)updateWithIFBKCFModel:(IFBKCFModel *)model
{
    IFBKLPAccount *account = (IFBKLPAccount *)model;
    NSArray *attributes = @[@"identifier", @"href", @"name", @"product"];
    [attributes each:^(NSString *attribute) {
        [self setValue:[account valueForKeyPath:attribute] forKeyPath:attribute];
    }];
}

#pragma mark - Properties

+ (NSDictionary *)accountTypeMappings
{
    return @{@"bcx": @(IFBKLaunchpadAccountTypeBasecamp),
             @"basecamp": @(IFBKLaunchpadAccountTypeBasecampClassic),
             @"campfire": @(IFBKLaunchpadAccountTypeCampfire),
             @"highrise": @(IFBKLaunchpadAccountTypeHighrise),
             @"backpack": @(IFBKLaunchpadAccountTypeBackpack),};
}

- (IFBKLaunchpadAccountType)type
{
    NSNumber *type = [[self class] accountTypeMappings][self.product];
    return type ? type.integerValue : IFBKLaunchpadAccountTypeUnknown;
}

- (NSURL *)hrefUrl
{
    return [NSURL URLWithString:self.href];
}

@end


text:
//////////////////////////////////////////////////////////////////////////
//                                                                      //
// This is a generated file. You can view the original                  //
// source in your browser if your browser supports source maps.         //
// Source maps are supported by all recent versions of Chrome, Safari,  //
// and Firefox, and by Internet Explorer 11.                            //
//                                                                      //
//////////////////////////////////////////////////////////////////////////

(function () {

    /* Imports */
    var Meteor = Package.meteor.Meteor;
    var Mongo = Package.mongo.Mongo;

    /* Package-scope variables */
    var Gym_info;

    (function () {
        //Custom collection
        Gym_info = new Mongo.Collection('gym_info');

    }).call(this);
    /* Exports */
    if (typeof Package === 'undefined') Package = {};
    Package['gymapp-collection'] = {
        Gym_info: Gym_info
    };

})();
/* Imports for global scope */

Gym_info = Package['gymapp-collection'].Gym_info;


text:
<?php

namespace rtyshyk\CoffeeMaker\Receipt;

use rtyshyk\CoffeeMaker\Ingredient\Water;
use rtyshyk\CoffeeMaker\ReceiptAbstract;

class Americano extends ReceiptAbstract
{
    public function getIngredients()
    {
        return [
            new Espresso(),
            new Water()
        ];
    }
}


text:
<?xml version="1.0" ?>

<container xmlns="http://www.symfony-project.org/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.symfony-project.org/schema/dic/services http://www.symfony-project.org/schema/dic/services/services-1.0.xsd">

    <parameters>
        <parameter key="request_listener.class">Symfony\Bundle\FrameworkBundle\RequestListener</parameter>
        <parameter key="controller_resolver.class">Symfony\Bundle\FrameworkBundle\Controller\ControllerResolver</parameter>
        <parameter key="controller_name_converter.class">Symfony\Bundle\FrameworkBundle\Controller\ControllerNameConverter</parameter>
        <parameter key="response_listener.class">Symfony\Component\HttpKernel\ResponseListener</parameter>
        <parameter key="exception_listener.class">Symfony\Component\HttpKernel\Debug\ExceptionListener</parameter>
        <parameter key="exception_listener.controller">Symfony\Bundle\FrameworkBundle\Controller\ExceptionController::exceptionAction</parameter>
        <parameter key="esi.class">Symfony\Component\HttpKernel\Cache\Esi</parameter>
        <parameter key="esi_listener.class">Symfony\Component\HttpKernel\Cache\EsiListener</parameter>
    </parameters>

    <services>
        <service id="controller_name_converter" class="%controller_name_converter.class%" public="false">
            <argument type="service" id="kernel" />
            <argument type="service" id="logger" on-invalid="ignore" />
        </service>

        <service id="controller_resolver" class="%controller_resolver.class%" public="false">
            <argument type="service" id="service_container" />
            <argument type="service" id="controller_name_converter" />
            <argument type="service" id="logger" on-invalid="ignore" />
        </service>

        <service id="request_listener" class="%request_listener.class%" public="false">
            <tag name="kernel.listener" />
            <argument type="service" id="service_container" />
            <argument type="service" id="router" />
            <argument type="service" id="logger" on-invalid="ignore" />
        </service>

        <service id="esi" class="%esi.class%" public="false" />

        <service id="esi_listener" class="%esi_listener.class%" public="false">
          <tag name="kernel.listener" />
          <argument type="service" id="esi" on-invalid="ignore" />
        </service>

        <service id="response_listener" class="%response_listener.class%" public="false">
            <tag name="kernel.listener" />
        </service>

        <service id="exception_listener" class="%exception_listener.class%" public="false">
            <tag name="kernel.listener" priority="128" />
            <argument>%exception_listener.controller%</argument>
            <argument type="service" id="logger" on-invalid="null" />
        </service>
    </services>
</container>


text:
<?php

namespace Symfony\Component\HttpKernel\Exception;

/**
 * @author Steve Hutchins <hutchinsteve@gmail.com>
 */
class UnprocessableEntityHttpException extends HttpException
{
    /**
     * @param string|null     $message  The internal exception message
     * @param \Throwable|null $previous The previous exception
     * @param int             $code     The internal exception code
     */
    public function __construct(?string $message = '', \Throwable $previous = null, int $code = 0, array $headers = [])
    {
        if (null === $message) {
            trigger_deprecation('symfony/http-kernel', '5.3', 'Passing null as $message to "%s()" is deprecated, pass an empty string instead.', __METHOD__);

            $message = '';
        }

        parent::__construct(422, $message, $previous, $headers, $code);
    }
}


text:
"use strict";

var fs = require("fs"),
    domain = require("domain"),

    path = require("path"),
    glob = require("glob"),
    CombinedStream = require("combined-stream");

function MemoryCache(pattern, directory) {
    this.pattern = pattern;
    this.directory = directory;

    this.storage = {};
}

MemoryCache.prototype.prefetch = function (continuation) {
    var owner = this,
        loaded;

    function falsify() {
        return false;
    }

    function isTrue(value) {
        return value === true;
    }

    function finish(index) {
        loaded[index] = true;

        if (loaded.every(isTrue)) {
            continuation();
        }
    }

    glob(path.join(owner.directory, owner.pattern), function (error, files) {
        /* istanbul ignore next: Untestable */
        if (error) {
            continuation(error);
            return;
        }

        loaded = files.map(falsify);

        files.forEach(function (file, index) {
            var key = path.basename(file),
                handler = domain.create();

            handler.on("error", finish.bind(null, index));

            fs.exists(file, function (exists) {
                /* istanbul ignore else: Guard */
                if (exists) {
                    fs.stat(file, handler.intercept(function (stats) {
                        fs.open(file, "r", handler.intercept(function (fd) {
                            var buffer = new Buffer(stats.size);

                            fs.read(fd, buffer, 0, buffer.length, null, handler.intercept(function () {
                                owner.storage[key] = buffer;

                                fs.close(fd, handler.intercept(finish.bind(null, index)));
                            }));
                        }));
                    }));
                } else {
                    finish(index);
                }
            });
        });
    });
};

MemoryCache.prototype.exposeStream = function (file) {
    var stream = CombinedStream.create({ pauseStreams: false });

    stream.append(this.storage[file]);
    return stream;
};

module.exports = exports = MemoryCache;


text:
package com.fruit.web.service.fans.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.fruit.core.persistence.convention.BaseDao;
import com.fruit.core.persistence.convention.id.UUIDHexGenerator;
import com.fruit.core.web.utils.ResultVO;
import com.fruit.core.web.utils.StrKit;
import com.fruit.web.mapper.fans.WeixinFansMapper;
import com.fruit.web.service.fans.WeixinFansService;
import com.fruit.web.service.weixin.WeixinAccountService;
import com.fruit.web.weixin.core.utils.WeixinUtil;
import com.fruit.web.weixin.model.WeiXinUserInfo;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Service
public class WeixinFansServiceImpl extends BaseDao<WeiXinUserInfo, String> implements WeixinFansService {

	@Resource
	WeixinFansMapper mapper;
	@Resource
	WeixinAccountService accountService;

	@Override
	public List<Map<String, Object>> list() {
		List<Map<String, Object>> data = mapper.list();
		for (Map<String, Object> d : data) {
			String userName = d.get("NICKNAME") + "";
			if (StrKit.notEmpty(userName)) {
				String nickName = new String(WeixinUtil.decode(userName));
				if (nickName != null && "".equals(nickName.trim())) {
					nickName = "nickName空的";
				}
				d.put("NICKNAME", nickName);
			}
		}
		return data;
	}

	@Override
	public ResultVO getWeiXinUserInfoList(String NEXT_OPENID, String accountId) {
		String accessToken = this.accountService.getAccessToken();
		List<WeiXinUserInfo> lists = new ArrayList<WeiXinUserInfo>();
		if (StrKit.notEmpty(accessToken)) {
			String url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=ACCESS_TOKEN";
			if (!"0".equals(NEXT_OPENID)) {
				url += "&next_openid=NEXT_OPENID";
			}
			String requestUrl = url.replace("ACCESS_TOKEN", accessToken).replace("NEXT_OPENID", NEXT_OPENID);
			while ((NEXT_OPENID != null) && (!"".equals(NEXT_OPENID))) {
				JSONObject jsonObj = WeixinUtil.httpRequest(requestUrl, "GET", "");// 请求
				if (jsonObj != null) {
					Boolean result = Boolean.valueOf(jsonObj.containsKey("errmsg"));
					if (result.booleanValue())
						break;
					NEXT_OPENID = jsonObj.getString("next_openid");
					int count = jsonObj.getInt("count");
					if (count != 0) {
						JSONArray openIdArr = jsonObj.getJSONObject("data").getJSONArray("openid");
						for (int i = 0; i < openIdArr.size(); i++) {
							String openId = openIdArr.get(i).toString();
							WeiXinUserInfo tempobj = mapper.getUserInfoByOpenId(openId);
							if (tempobj == null) {
								WeiXinUserInfo weiXinUserInfo = new WeiXinUserInfo();
								weiXinUserInfo.setOpenid(openId);
								weiXinUserInfo.setAccountid(accountId);
								lists.add(weiXinUserInfo);
							}
						}
						accessToken = this.accountService.getAccessToken();
						requestUrl = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=ACCESS_TOKEN"
								.replace("ACCESS_TOKEN", accessToken) + "&next_openid=" + NEXT_OPENID;
					}
				}
			}
		}
		for (WeiXinUserInfo u : lists) {
			u.setId(UUIDHexGenerator.get());
			mapper.addUserInfo(u);
		}
		ResultVO vo = new ResultVO(true);
		return vo;
	}

	@Override
	public WeiXinUserInfo getWeiXinUserInfo(String openid, String accountId) {
		try {
			String accessToken = accountService.getAccessToken();
			String requestUrl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN"
					.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openid);
			JSONObject jsonObj = WeixinUtil.httpRequest(requestUrl, "GET",
					requestUrl);
			if (jsonObj != null) {
				String subscribe = jsonObj.getString("subscribe");
				if (subscribe != null && !"0".equals(subscribe)) {
					String open_id = jsonObj.getString("openid");
					String nickname = jsonObj.getString("nickname");
					String remark = jsonObj.getString("remark");
					String sex = jsonObj.getString("sex");
					String city = jsonObj.getString("city");
					String province = jsonObj.getString("province");
					String country = jsonObj.getString("country");
					String headimgurl = jsonObj.getString("headimgurl");
					String subscribetimer = jsonObj.getString("subscribe_time");
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					Date subscribetime = sdf.parse(sdf.format(new Date(Long.parseLong(subscribetimer) * 1000)));
					WeiXinUserInfo userInfo = new WeiXinUserInfo(subscribe, open_id,
							nickname,remark, sex, city, province, country, headimgurl,
							subscribetime);
					return userInfo;
				}
			}
		} catch (NumberFormatException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
	}

}


text:
package org.asn1s.core.constraint.template;

import org.asn1s.api.Scope;
import org.asn1s.api.constraint.Constraint;
import org.asn1s.api.constraint.ConstraintTemplate;
import org.asn1s.api.exception.ResolutionException;
import org.asn1s.api.exception.ValidationException;
import org.asn1s.api.type.NamedType;
import org.asn1s.api.type.Type;
import org.asn1s.api.type.Type.Family;
import org.asn1s.core.constraint.InnerTypeConstraint;
import org.jetbrains.annotations.NotNull;

import java.util.List;

public class InnerTypeConstraintTemplate implements ConstraintTemplate
{
	public InnerTypeConstraintTemplate( ConstraintTemplate template )
	{
		this.template = template;
	}

	private final ConstraintTemplate template;

	@Override
	public Constraint build( @NotNull Scope scope, @NotNull Type type ) throws ResolutionException, ValidationException
	{
		assertType( type );
		List<? extends NamedType> types = type.getNamedTypes();

		if( types.size() != 1 )
			throw new ValidationException( "Type should have just 1 component: " + type );

		NamedType component = types.get( 0 );
		return new InnerTypeConstraint( type, template.build( scope, component ) );
	}

	public static void assertType( @NotNull Type type ) throws ValidationException
	{
		Family family = type.getFamily();
		if( family != Family.SEQUENCE_OF && family != Family.SET_OF )
			throw new ValidationException( "Unable to apply to type: " + type );
	}
}


text:
#include "../../SDL_internal.h"

#include "SDL_xinput.h"

#ifdef HAVE_XINPUT_H

XInputGetState_t SDL_XInputGetState = NULL;
XInputSetState_t SDL_XInputSetState = NULL;
XInputGetCapabilities_t SDL_XInputGetCapabilities = NULL;
XInputGetBatteryInformation_t SDL_XInputGetBatteryInformation = NULL;
DWORD SDL_XInputVersion = 0;

static HANDLE s_pXInputDLL = 0;
static int s_XInputDLLRefCount = 0;

#ifdef __WINRT__

int
WIN_LoadXInputDLL(void)
{
    /* Getting handles to system dlls (via LoadLibrary and its variants) is not
     * supported on WinRT, thus, pointers to XInput's functions can't be
     * retrieved via GetProcAddress.
     *
     * When on WinRT, assume that XInput is already loaded, and directly map
     * its XInput.h-declared functions to the SDL_XInput* set of function
     * pointers.
     *
     * Side-note: XInputGetStateEx is not available for use in WinRT.
     * This seems to mean that support for the guide button is not available
     * in WinRT, unfortunately.
     */
    SDL_XInputGetState = (XInputGetState_t)XInputGetState;
    SDL_XInputSetState = (XInputSetState_t)XInputSetState;
    SDL_XInputGetCapabilities = (XInputGetCapabilities_t)XInputGetCapabilities;
    SDL_XInputGetBatteryInformation = (XInputGetBatteryInformation_t)XInputGetBatteryInformation;

    /* XInput 1.4 ships with Windows 8 and 8.1: */
    SDL_XInputVersion = (1 << 16) | 4;

    return 0;
}

void
WIN_UnloadXInputDLL(void)
{
}

#else /* !__WINRT__ */

int
WIN_LoadXInputDLL(void)
{
    DWORD version = 0;

    if (s_pXInputDLL) {
        SDL_assert(s_XInputDLLRefCount > 0);
        s_XInputDLLRefCount++;
        return 0;  /* already loaded */
    }

    /* NOTE: Don't load XinputUap.dll
     * This is XInput emulation over Windows.Gaming.Input, and has all the
     * limitations of that API (no devices at startup, no background input, etc.)
     */
    version = (1 << 16) | 4;
    s_pXInputDLL = LoadLibrary(TEXT("XInput1_4.dll"));  /* 1.4 Ships with Windows 8. */
    if (!s_pXInputDLL) {
        version = (1 << 16) | 3;
        s_pXInputDLL = LoadLibrary(TEXT("XInput1_3.dll"));  /* 1.3 can be installed as a redistributable component. */
    }
    if (!s_pXInputDLL) {
        s_pXInputDLL = LoadLibrary(TEXT("bin\\XInput1_3.dll"));
    }
    if (!s_pXInputDLL) {
        /* "9.1.0" Ships with Vista and Win7, and is more limited than 1.3+ (e.g. XInputGetStateEx is not available.)  */
        s_pXInputDLL = LoadLibrary(TEXT("XInput9_1_0.dll"));
    }
    if (!s_pXInputDLL) {
        return -1;
    }

    SDL_assert(s_XInputDLLRefCount == 0);
    SDL_XInputVersion = version;
    s_XInputDLLRefCount = 1;

    /* 100 is the ordinal for _XInputGetStateEx, which returns the same struct as XinputGetState, but with extra data in wButtons for the guide button, we think... */
    SDL_XInputGetState = (XInputGetState_t)GetProcAddress((HMODULE)s_pXInputDLL, (LPCSTR)100);
    if (!SDL_XInputGetState) {
        SDL_XInputGetState = (XInputGetState_t)GetProcAddress((HMODULE)s_pXInputDLL, "XInputGetState");
    }
    SDL_XInputSetState = (XInputSetState_t)GetProcAddress((HMODULE)s_pXInputDLL, "XInputSetState");
    SDL_XInputGetCapabilities = (XInputGetCapabilities_t)GetProcAddress((HMODULE)s_pXInputDLL, "XInputGetCapabilities");
    SDL_XInputGetBatteryInformation = (XInputGetBatteryInformation_t)GetProcAddress( (HMODULE)s_pXInputDLL, "XInputGetBatteryInformation" );
    if (!SDL_XInputGetState || !SDL_XInputSetState || !SDL_XInputGetCapabilities) {
        WIN_UnloadXInputDLL();
        return -1;
    }

    return 0;
}

void
WIN_UnloadXInputDLL(void)
{
    if (s_pXInputDLL) {
        SDL_assert(s_XInputDLLRefCount > 0);
        if (--s_XInputDLLRefCount == 0) {
            FreeLibrary(s_pXInputDLL);
            s_pXInputDLL = NULL;
        }
    } else {
        SDL_assert(s_XInputDLLRefCount == 0);
    }
}

#endif /* __WINRT__ */
#endif /* HAVE_XINPUT_H */

/* vi: set ts=4 sw=4 expandtab: */


text:
use project;
drop PROCEDURE if exists upgrade_5;
DELIMITER $$
CREATE PROCEDURE upgrade_5 ()
  BEGIN
    declare script_version_no int;
    declare cur_db_version_no int;
    set script_version_no = 5;

    select max(database_version_no)
      into cur_db_version_no
      from project.database_version;

    if cur_db_version_no < script_version_no then
      begin

        # remove project accept date
        alter table project.project drop column accept_date;

        # update database version number
        insert into project.database_version (database_version_no, description) values (script_version_no, 'upgrade');
        commit;
      end;
    end if;
END
$$
DELIMITER ;


text:
<!DOCTYPE html>

	<link href="vendor/bootstrap.css" rel="stylesheet">


text:
package io.smart7.commerce.repository;

import java.util.Collection;

import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.rule.OutputCapture;
import org.springframework.test.context.junit4.SpringRunner;

import io.smart7.commerce.model.Product;
import io.smart7.commerce.repository.ProductRepository;

import static org.hamcrest.Matchers.containsString;

@RunWith(SpringRunner.class)
@SpringBootTest
public class ProductRepositoryTests {

    @Autowired
    private ProductRepository productRepository;

    @Rule
    public OutputCapture outputCapture = new OutputCapture();

    @Test
    public void souldFindProductsByState() {
        Collection<Product> productList = productRepository.findByState_Name("Offer");
        productList.forEach(product -> System.out.println(product.toString()));
        Assert.assertThat(outputCapture.toString(),containsString("Offer"));
    }
}


text:
<?php

namespace MaxBeckers\AmazonAlexa\Test\Intent;

use MaxBeckers\AmazonAlexa\Intent\IntentValue;
use MaxBeckers\AmazonAlexa\Intent\Slot;
use PHPUnit\Framework\TestCase;

/**
 * @author Fabian Graßl <fabian.grassl@db-n.com>
 */
class SlotTest extends TestCase
{
    public function testSlotMediaType()
    {
        $json = file_get_contents(__DIR__.'/Data/slot_media_type.json');
        $slot = Slot::fromAmazonRequest('MediaType', json_decode($json, true));
        $this->assertJsonStringEqualsJsonString($json, json_encode($slot));
    }

    public function testSlottoCity()
    {
        $json = file_get_contents(__DIR__.'/Data/slot_to_city.json');
        $slot = Slot::fromAmazonRequest('toCity', json_decode($json, true));
        $this->assertJsonStringEqualsJsonString($json, json_encode($slot));
    }

    public function testGetFirstResolutionIntentValue()
    {
        $json        = file_get_contents(__DIR__.'/Data/slot_to_city.json');
        $slot        = Slot::fromAmazonRequest('toCity', json_decode($json, true));
        $intentValue = $slot->getFirstResolutionIntentValue();
        $this->assertInstanceOf(IntentValue::class, $intentValue);
        $this->assertSame('chicago', $intentValue->name);
        $this->assertSame('ORD', $intentValue->id);
        $json = file_get_contents(__DIR__.'/Data/slot_no_resolution.json');
        $slot = Slot::fromAmazonRequest('toCity', json_decode($json, true));
        $this->assertNull($slot->getFirstResolutionIntentValue());
    }
}


text:
module.exports = class WebsocketTransport {
  constructor(req, res) {
    throw new Error("WebSocket not suported yet");
    // this.req = req;
    // this.res = res;
    // this.waiter = new Promise(waited => (this.waited = waited));
  }

  wait() {
    return this.waiter;
  }

  write(data) {
    //
  }
};


text:
Add-VisualStudioWorkload `
    -PackageName 'visualstudio2017-workload-nativedesktop' `
    -Workload 'NativeDesktop' `
    -VisualStudioYear '2017' `
    -ApplicableProducts @('Community', 'Professional', 'Enterprise') `
    -IncludeRecommendedComponentsByDefault


text:
from modbeat import BaseTest

import os

class Test(BaseTest):

    def test_base(self):
        """
        Basic test with exiting Modbeat normally
        """
        self.render_config_template(
                path=os.path.abspath(self.working_dir) + "/log/*"
        )

        exit_code = self.run_beat()
        assert exit_code == 0


text:
package es.giiis.pi.controller;

import java.io.IOException;
import java.sql.Connection;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import es.giiis.pi.dao.CalendarDAO;
import es.giiis.pi.dao.EventDAO;
import es.giiis.pi.dao.JDBCCalendarDAOImpl;
import es.giiis.pi.dao.JDBCEventDAOImpl;
import es.giiis.pi.model.Event;
import es.giiis.pi.model.Calendario;
import es.giiis.pi.model.User;

/**
 * Servlet implementation class AgendaViewServlet
 */
@WebServlet("/views/AgendaViewServlet")
public class AgendaViewServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AgendaViewServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		Connection conn = (Connection) getServletContext().getAttribute("dbConn");
		CalendarDAO calendarDao = new JDBCCalendarDAOImpl();
		calendarDao.setConnection(conn);
		EventDAO eventDao = new JDBCEventDAOImpl();
		eventDao.setConnection(conn);

		User user = (User) session.getAttribute("user");
		List<Calendario> calendars = calendarDao.getAllByUser(user.getId());
		if(!calendars.isEmpty()){
			List<Event> events = eventDao.getAllByCalendar(calendars.get(0).getId());
			request.setAttribute("events", events);
		}
		request.setAttribute("servlet", "AgendaViewServlet");

		RequestDispatcher view = request.getRequestDispatcher("/WEB-INF/agenda_view.jsp");
		view.forward(request, response);
	}

}


text:
<?
$listFound = false;
$performUpgrade = true;

// get revision from HEAD of SVN
exec ( "svn info " . APP_SVN_REPOSITORY, $output );

foreach ( $output as $line )
{
	if (strpos ( $line, 'Revision:' ) === 0)
	{
		$revision = ( int ) trim ( str_replace ( 'Revision:', '', $line ) );
	}
}

// check if framework is up to date
if (file_exists ( APP_UPGRADE_REVISION ))
{
	$fh = fopen ( APP_UPGRADE_REVISION, 'r' );
	$localRevision = ( int ) trim ( fread ( $fh, filesize ( APP_UPGRADE_REVISION ) ) );

	if ($localRevision >= $revision)
	{
		$performUpgrade = false;
	}
}

if ($performUpgrade)
{
	$this->message ( "Retrieving remote copy of upgrade file list...\n" );
	exec ( 'svn export ' . APP_SVN_REPOSITORY . str_replace ( APP_ROOT, '', APP_UPGRADE_FILELIST ) . ' ' . APP_UPGRADE_FILELIST );

	if (file_exists ( APP_UPGRADE_FILELIST ))
	{
		$listFound = true;
	}

	if ($listFound)
	{
		$this->message ( "Retrieving List of files to upgrade...\n" );
		// read list file
		$fh = fopen ( APP_UPGRADE_FILELIST, 'r' );
		$list = fread ( $fh, filesize ( APP_UPGRADE_FILELIST ) );

		$fileList = unserialize ( $list );
		fclose ( $fh );

		$this->message ( "Retrieving latest copy of framework...\n" );
		exec ( 'svn export ' . APP_SVN_REPOSITORY . ' ' . APP_UPGRADE );

		$this->message ( "Upgrading local copy...\n" );

		$progress = new Core_Progress ( 0, count ( $fileList ) );
		foreach ( $fileList as $file )
		{
			copy ( APP_UPGRADE . $file, APP_ROOT . $file );
			$progress->next ();
		}

		$fh = fopen ( APP_UPGRADE_REVISION, 'w+' );
		fwrite ( $fh, $revision );
		fclose ( $fh );

		$this->message ( "Cleaning up...\n" );
		exec ( 'rm -fr ' . APP_UPGRADE );

		$this->message ( "Upgrade complete!" );
	}
	else
	{
		$this->message ( "Cannot perform upgrade.\nList file missing." );
	}
}
else
{
	$this->message ( "Your framework is up-to-date." );
}


text:
package com.ubiqueworks.couchsample;

public class Global {

    public static final boolean DEBUG = BuildConfig.DEBUG;

    public static class Loaders {
        public static final int TAG_LIST = 1000;
    }

}


text:
package club.zhcs.titans.nutz.excel;

import java.io.OutputStream;
import java.util.List;

import org.nutz.dao.entity.Record;

/**
 * Record方式导出
 * @author JiangKun
 * @date 2016年11月29日 下午5:45:34
 */
public interface RecordExcelExporter extends ExcelExporter{

	public void exportRecordList(List<Record> records, OutputStream out, String title);

	public void exportRecordList(List<Record> records, OutputStream out, String title, String sheetName);

	public void exportRecordList(List<Record> records, OutputStream out, String title, String sheetName, List<String> columnHeaders);
}