text:
package zjava.collection.primitive;

import java.util.Arrays;

import zjava.system.Const;

/**
 * Resizable dynamic array of primitive boolean values.
 *
 *
The <tt>size</tt>, <tt>get</tt>, <tt>set</tt> operations run in
 * constant time. The <tt>add</tt> operation runs in amortized constant
 * time, that is, adding n elements requires O(n) time. Removal and
 * insertion of elements at arbitrary index runs in O(n1/2)
 * amortized time.
 *
 *
Basically, this class has the following advantages over regular array:
 *
Resizable implementation which requires only O(n1/2) of
 * additional memory.

 *
Faster insertions at random positions.

 *
Support for more than {@code Integer.MAX_VALUE} elements.

 *
Uses only 1 bit of memory per value

 *
 * @since Zjava 1.0
 *
 * @author Ivan Zaitsau
 *
 */
public class BooleanList implements Cloneable, java.io.Serializable {

	static private final long serialVersionUID = 201612271645L;

	/** Actual initial block size is 2INITIAL_BLOCK_ADDRESS_BITS */
	static private final int INITIAL_BLOCK_ADDRESS_BITS = 10;

	/** Number of blocks on BooleanList initialization.
	 *
 Note: Must be even number due to some simplifications and assumptions made in the code*/
	static private final int INITIAL_BLOCKS_COUNT = 2;

	/** This coefficient used to check if reduction of block size and amount of blocks is required.
	 *
 Note: Must be no less than 4. Needs to be no less than 8 for amortized performance estimations to hold */
	static private final int REDUCTION_COEFFICIENT = 12;

    /**
	 * Internal storage block.

	 * Maintains up to <tt>capacity</tt> boolean values.

	 * If there are more elements than <tt>capacity</tt> after <tt>add</tt> operation,
	 * last element is removed from the block and returned from <tt>add</tt> method.

	 *
	 *
Implementation may vary, but the following conditions must be met:
	 *
 Insertions and deletions at the beginning and the end of the block must complete in constant time
	 *
 Retrieval of element at arbitrary position must complete in constant time
	 *
 Any other operation must complete in O(n)
	 *
 Only Blocks of sizes 2, 4, 8, ... 230 need to be supported
	 *
	 * @author Ivan Zaitsau
	 */
	static final private class BinaryBlock implements Cloneable, java.io.Serializable {

		private static final long serialVersionUID = 201612271645L;

		private static final int ADDRESS_BITS_PER_WORD = Const.ADDRESS_BITS_PER_LONG;
		private static final int WORD_MASK = (1 << ADDRESS_BITS_PER_WORD) - 1;

		// - partial logical shift to left
		private static long pshl(final long value, final int fromIndex, final int toIndex) {
			final long rangeMask = (((1L << toIndex) << 1) - 1) - ((1L << fromIndex) - 1);
			return (value & ~rangeMask) | (((value & rangeMask) << 1) & rangeMask);
		}

		// - partial logical shift to right
		private static long pshr(final long value, final int fromIndex, final int toIndex) {
			final long rangeMask = (((1L << toIndex) << 1) - 1) - ((1L << fromIndex) - 1);
			return (value & ~rangeMask) | (((value & rangeMask) >>> 1) & rangeMask);
		}

		// - merges two blocks of equal capacities into block with doubled capacity
		static BinaryBlock merge(BinaryBlock block1, BinaryBlock block2) {
			if ((block1 == null || block1.size() == 0) && (block2 == null || block2.size() == 0))
				return null;

			assert (block1 == null | block2 == null) || (block1.values.length == block2.values.length);

			if (block1 == null || block1.size == 0) {
				block1 = block2;
				block2 = null;
			}
			BinaryBlock mergedBlock = new BinaryBlock(2 * block1.values.length);

			// - copy bits from block1
			final int blockMask = (block1.values.length - 1);
			int remainingBits = block1.size & WORD_MASK;
			int wordSplit = block1.offset & WORD_MASK;
			int fullWords = block1.size >>> ADDRESS_BITS_PER_WORD;
			int wordOffset = block1.offset >>> ADDRESS_BITS_PER_WORD;
			if (wordSplit == 0) {
				for (int wi = 0; wi < fullWords; wi++) {
					mergedBlock.values[wi] = block1.values[(wordOffset + wi) & blockMask];
				}
				if (remainingBits > 0) {
					mergedBlock.values[fullWords] = block1.values[(wordOffset + fullWords) & blockMask]
							& ((1L << remainingBits) - 1);
				}
			}
			else {
				for (int wi = 0; wi < fullWords; wi++) {
					mergedBlock.values[wi] = (block1.values[(wordOffset + wi) & blockMask] >>> wordSplit)
							| (block1.values[(wordOffset + wi + 1) & blockMask] << -wordSplit);
				}
				if (remainingBits > 0) {
					mergedBlock.values[fullWords] = ((block1.values[(wordOffset + fullWords) & blockMask] >>> wordSplit)
							| (block1.values[(wordOffset + fullWords + 1) & blockMask] << -wordSplit))
							& ((1L << remainingBits) - 1);
				}
			}
			mergedBlock.size += block1.size;

			if (block2 == null || block2.size == 0)
				return mergedBlock;

			// - copy bits from block2
			final int bitsToCompleteWord = (remainingBits > 0) ? (1 << ADDRESS_BITS_PER_WORD) - remainingBits : 0;
			// - finish uncompleted word first
			if (remainingBits > 0) {
				if (bitsToCompleteWord > block2.size) {

				}

			}

			final int mergedWords = fullWords;
			remainingBits = (block2.size - bitsToCompleteWord) & WORD_MASK;
			wordSplit = (block2.offset + bitsToCompleteWord) & WORD_MASK;
			fullWords = (block2.size - bitsToCompleteWord) >>> ADDRESS_BITS_PER_WORD;
			wordOffset = (block2.offset + bitsToCompleteWord) >>> ADDRESS_BITS_PER_WORD;

			if (wordSplit == 0) {
				for (int wi = 0; wi < fullWords; wi++) {
					mergedBlock.values[mergedWords + wi] = block2.values[(wordOffset + wi) & blockMask];
				}
				if (remainingBits > 0) {
					mergedBlock.values[mergedWords + fullWords] = block2.values[(wordOffset + fullWords) & blockMask]
							& ((1L << remainingBits) - 1);
				}
			}
			else {
				for (int wi = 0; wi < fullWords; wi++) {
					mergedBlock.values[mergedWords + wi] = (block2.values[(wordOffset + wi) & blockMask] >>> wordSplit)
							| (block2.values[(wordOffset + wi + 1) & blockMask] << -wordSplit);
				}
				if (remainingBits > 0) {
					mergedBlock.values[mergedWords + fullWords] = ((block2.values[(wordOffset + fullWords) & blockMask] >>> wordSplit)
							| (block2.values[(wordOffset + fullWords + 1) & blockMask] << -wordSplit))
							& ((1L << remainingBits) - 1);
				}
			}
			mergedBlock.size += block2.size;

			return mergedBlock;
		}

		// - splits block to two smaller blocks of capacity equal to half of given block
		static BinaryBlock[] split(BinaryBlock block) {
			if (block == null || block.size == 0)
				return new BinaryBlock[] {null, null};

			assert (block.values.length & 1) == 0;

			final int halfCapacity = (block.values.length / 2) << ADDRESS_BITS_PER_WORD;
			final int blockMask = (block.values.length - 1);
			final int wordSplit = block.offset & WORD_MASK;
			final int remainingBits = block.size & WORD_MASK;
			final int wordOffset = block.offset >>> ADDRESS_BITS_PER_WORD;
			final int fullWords = block.size >>> ADDRESS_BITS_PER_WORD;

			if (block.size <= halfCapacity) {
				BinaryBlock block1 = new BinaryBlock(halfCapacity);
				if (wordSplit == 0) {
					for (int wi = 0; wi < fullWords; wi++) {
						block1.values[wi] = block.values[(wordOffset + wi) & blockMask];
					}
					if (remainingBits > 0) {
						block1.values[fullWords] = block.values[(wordOffset + fullWords) & blockMask]
								& ((1L << remainingBits) - 1);
					}
				}
				else {
					for (int wi = 0; wi < fullWords; wi++) {
						block1.values[wi] = (block.values[(wordOffset + wi) & blockMask] >>> wordSplit)
								+ (block.values[(wordOffset + wi + 1) & blockMask] << -wordSplit);
					}
					if (remainingBits > 0) {
						block1.values[fullWords] = ((block.values[(wordOffset + fullWords) & blockMask] >>> wordSplit)
								+ (block.values[(wordOffset + fullWords + 1) & blockMask] << -wordSplit))
								& ((1L << remainingBits) - 1);
					}
				}
				block1.size = block.size;
				return new BinaryBlock[] {block1, null};
			}
			else {
				BinaryBlock block1 = new BinaryBlock(halfCapacity);
				if (wordSplit == 0) {
					for (int wi = 0; wi < block1.values.length; wi++) {
						block1.values[wi] = block.values[(wordOffset + wi) & blockMask];
					}
				}
				else {
					for (int wi = 0; wi < block1.values.length; wi++) {
						block1.values[wi] = (block.values[(wordOffset + wi) & blockMask] >>> wordSplit)
								+ (block.values[(wordOffset + wi + 1) & blockMask] << -wordSplit);
					}
				}
				block1.size = halfCapacity;

				BinaryBlock block2 = new BinaryBlock(halfCapacity);
				if (wordSplit == 0) {
					for (int wi = 0; wi < fullWords; wi++) {
						block2.values[wi - block1.values.length] = block.values[(wordOffset + wi) & blockMask];
					}
					if (remainingBits > 0) {
						block2.values[fullWords - block1.values.length] = block.values[(wordOffset + fullWords) & blockMask]
								& ((1L << remainingBits) - 1);
					}
				}
				else {
					for (int wi = 0; wi < fullWords; wi++) {
						block2.values[wi - block1.values.length] = (block.values[(wordOffset + wi) & blockMask] >>> wordSplit)
								+ (block.values[(wordOffset + wi + 1) & blockMask] << -wordSplit);
					}
					if (remainingBits > 0) {
						block2.values[fullWords - block1.values.length] = ((block.values[(wordOffset + fullWords) & blockMask] >>> wordSplit)
								+ (block.values[(wordOffset + fullWords + 1) & blockMask] << -wordSplit))
								& ((1L << remainingBits) - 1);
					}
				}
				block2.size = block.size - halfCapacity;
				return new BinaryBlock[] {block1, block2};
			}
		}

		private int offset;
		private int size;
		private long[] values;

		BinaryBlock(int capacity) {
			// - capacity must be power of 2, greater than 64 (i.e. must contain at least two "words")
			assert((capacity & (capacity-1)) == 0 && capacity > 1 << ADDRESS_BITS_PER_WORD);

			this.offset = 0;
			this.size = 0;
			this.values = new long[capacity >>> ADDRESS_BITS_PER_WORD];
		}

		int size() {
			return size;
		}

		// - returns maximum amount of values this BinaryBlock can hold
		private int capacity() {
			return values.length << ADDRESS_BITS_PER_WORD;
		}

		// - returns "physical" index for given "logical" position
		private int index(final int pos) {
			return (offset + pos) & (capacity() - 1);
		}

		private boolean getBit(final int index) {
			return (values[index >>> ADDRESS_BITS_PER_WORD] & (1L << (index & WORD_MASK))) != 0;
		}

		/*
		 * updates given bit at the specified index to given value
		 * returns the value previously at the specified index
		 */
		private boolean setBit(final int index, final boolean value) {
			final int wi = index >>> ADDRESS_BITS_PER_WORD;
			final long beforeUpdate = values[wi];
			if (value) {
				// - 1 bit
				values[wi] |= 1L << (index & WORD_MASK);
				return values[wi] == beforeUpdate;
			}
			else {
				// - 0 bit
				values[wi] &= ~(1L << (index & WORD_MASK));
				return values[wi] != beforeUpdate;
			}
		}

		// - appends given value to the beginning of the block
		boolean addFirst(final boolean value) {
			offset = index(-1);
			if (size < capacity()) {
				setBit(offset, value);
				size++;
				return false;
			}
			return setBit(offset, value);
		}

		// - appends given value to the end of the block
		void addLast(final boolean value) {
			if (size == capacity())
				return;
			setBit(index(size), value);
			size++;
		}

		// - shifts values in direction of the beginning of the values array
		private void shiftToLeft(final int fromPosition, final int toPosition) {
			final int fromIndex = index(fromPosition);
			final int firstWordIndex = fromIndex >>> ADDRESS_BITS_PER_WORD;
			final int toIndex = index(toPosition);
			final int lastWordIndex = toIndex >>> ADDRESS_BITS_PER_WORD;
			if (firstWordIndex == lastWordIndex & fromIndex < toIndex) {
				// - requested shift lies within the first "word"
				values[firstWordIndex] = pshr(values[firstWordIndex], fromIndex & WORD_MASK, toIndex & WORD_MASK);
				return;
			}
			values[firstWordIndex] = pshr(values[firstWordIndex], fromIndex & WORD_MASK, WORD_MASK)
					+ (values[(firstWordIndex + 1) & (values.length - 1)] << WORD_MASK);
			for (int wi = (firstWordIndex + 1) & (values.length - 1); wi != lastWordIndex; ) {
				final int ni = (wi + 1) & (values.length - 1);
				values[wi] = (values[wi] >>> 1) + (values[ni] << WORD_MASK);
				wi = ni;
			}
			values[lastWordIndex] = pshr(values[lastWordIndex], 0, toIndex & WORD_MASK);
		}

		// - shifts values in direction of the end of the values array
		private void shiftToRight(final int fromPosition, final int toPosition) {
			final int fromIndex = index(fromPosition);
			final int firstWordIndex = fromIndex >>> ADDRESS_BITS_PER_WORD;
			final int toIndex = index(toPosition);
			final int lastWordIndex = toIndex >>> ADDRESS_BITS_PER_WORD;
			if (firstWordIndex == lastWordIndex & fromIndex < toIndex) {
				// - requested shift lies within the first "word"
				values[firstWordIndex] = pshl(values[firstWordIndex], fromIndex & WORD_MASK, toIndex & WORD_MASK);
				return;
			}
			values[lastWordIndex] = pshl(values[lastWordIndex], 0, toIndex & WORD_MASK)
					+ (values[(lastWordIndex - 1) & (values.length - 1)] >>> WORD_MASK);
			for (int wi = (lastWordIndex - 1) & (values.length - 1); wi != lastWordIndex; ) {
				final int ni = (wi - 1) & (values.length - 1);
				values[wi] = (values[wi] << 1) + (values[ni] >>> WORD_MASK);
				wi = ni;
			}
			values[firstWordIndex] = pshl(values[firstWordIndex], fromIndex & WORD_MASK, WORD_MASK);
		}

		// - inserts given value at given position
		boolean add(final int pos, final boolean value) {
			// - range check
			assert(pos >= 0 && pos <= size);

			final boolean last = (size == capacity()) ? getBit(index(-1)) : false;
			if (2*pos < size) {
				offset = index(-1);
				shiftToLeft(0, pos);
			}
			else {
				shiftToRight(pos, (size == capacity() ? size-1 : size));
			}
			setBit(index(pos), value);
			if (size < capacity()) size++;
			return last;
		}

		// - replaces element at given position with given value
		boolean set(final int pos, final boolean value) {
			// - range check
			assert(pos >= 0 && pos < size);

			return setBit(index(pos), value);
		}

		// - removes first element of the block
		boolean removeFirst() {
			// - range check
			assert(size > 0);

			boolean removed = getBit(offset);
			offset = index(1);
			size--;
			return removed;
		}

		// - removes element at given position
		boolean remove(final int pos) {
			// - range check
			assert(pos >= 0 && pos < size);

			boolean removed = getBit(index(pos));
			if (2*pos < size) {
				shiftToRight(0, pos);
				offset = index(1);
			}
			else {
				shiftToLeft(pos, size-1);
			}
			size--;
			return removed;
		}

		// - returns element at given position
		boolean get(final int pos) {
			// - range check
			assert(pos >= 0 && pos < size);

			return getBit(index(pos));
		}

		public Object clone() {
			try {
				BinaryBlock clone = (BinaryBlock) super.clone();
				clone.values = values.clone();
				return clone;
			} catch (CloneNotSupportedException e) {
	    		// - this should never be thrown since we are Cloneable
	    		throw new InternalError();
			}
		}
	}

	private long size;
	private int blockAddressBits;
	private BinaryBlock[] data;

    private String outOfBoundsMsg(long index) {
        return "Index: " + index + ", Size: " + size;
    }

	private void rangeCheck(final long index) {
		if (index < 0 || index >= size)
			throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
	}

	private void rangeCheckForAdd(final long index) {
		if (index < 0 || index > size)
			throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
	}

	/** Null-safe access to data block with initialization.*/
	private BinaryBlock data(final int index) {
		if (data[index] == null)
			data[index] = new BinaryBlock(1 << blockAddressBits);
		return data[index];
	}

	private void ensureCapacity(long requiredCapacity) {
		long capacity = (long) data.length << blockAddressBits;
		while (requiredCapacity > capacity) {
			// - double number of blocks and their size
			BinaryBlock[] newData = new BinaryBlock[2*data.length];
			int newBlockBitsize = blockAddressBits+1;
			for (int i = 1, j = 0; i < data.length; i += 2, j++) {
				newData[j] = BinaryBlock.merge(data[i-1], data[i]);
				if (newData[j] == null)
					break;
			}
			/* Redundant because data.length assumed to be even number
			 * *deleted code*
			*/
			assert (data.length & 1) == 0;

			data = newData;
			blockAddressBits = newBlockBitsize;
			capacity = (long) data.length << blockAddressBits;
		}
	}

	private void compact() {
		if (data.length <= INITIAL_BLOCKS_COUNT)
			return;
		if (size * REDUCTION_COEFFICIENT <= (long) data.length << blockAddressBits) {
			// - decrease number of blocks and their size by half
			BinaryBlock[] newData = new BinaryBlock[(data.length+1)/2];
			int newBlockBitsize = blockAddressBits-1;
			main:
			for (int i = 0; ; i++) {
				BinaryBlock[] splitBlock = BinaryBlock.split(data[i]);
				for (int j = 0; j <= 1; j++) {
					if (splitBlock[j] == null || splitBlock[j].size() == 0)
						break main;
					newData[i+i+j] = splitBlock[j];
				}
			}
			data = newData;
			blockAddressBits = newBlockBitsize;
		}
	}

	private void init() {
		init(0);
	}

	private void init(long initialCapacity) {
		size = 0;
		blockAddressBits = INITIAL_BLOCK_ADDRESS_BITS;
		int blocksCount = INITIAL_BLOCKS_COUNT;
		while ((long)blocksCount << blockAddressBits < initialCapacity) {
			blocksCount += blocksCount;
			blockAddressBits++;
		}
		data = new BinaryBlock[blocksCount];
	}

	/**
     * Constructs an empty list with an initial capacity of 32 elements.
     */
	public BooleanList() {
		init();
	}

	/**
     * Constructs an empty list with at least specified capacity.
     */
	public BooleanList(long initialCapacity) {
		init(initialCapacity);
	}

    /**
     * Returns the number of elements in this list.
     *
     * @return the number of elements in this list
     */
	public long size() {
		return size;
	}

    /**
     * Returns the element at the specified position in this list.
     *
     * @param  index index of the element to return
     * @return the element at the specified position in this list
     * @throws IndexOutOfBoundsException if the index is out of range
     *         (<tt>index < 0 || index >= size()</tt>)
     */
	public boolean get(long index) {
		rangeCheck(index);
		int blockIndex = (int) (index >>> blockAddressBits);
		int valueIndex = (int) (index & (-1L >>> -blockAddressBits));
		return data[blockIndex].get(valueIndex);
	}

    /**
     * Replaces the element at the specified position in this list with
     * the specified element.
     *
     * @param index index of the element to replace
     * @param value element to be stored at the specified position
     * @return the element previously at the specified position
     * @throws IndexOutOfBoundsException if the index is out of range
     *         (<tt>index < 0 || index >= size()</tt>)
     */
	public boolean set(long index, boolean value) {
		rangeCheck(index);
		int blockIndex = (int) (index >>> blockAddressBits);
		int valueIndex = (int) (index & (-1L >>> -blockAddressBits));
		return data[blockIndex].set(valueIndex, value);
	}

    /**
     * Appends the specified element to the end of this list.
     *
     * @param value element to be appended to this list
     */
	public void add(boolean value) {
		ensureCapacity(size + 1);
		int blockIndex = (int) (size >>> blockAddressBits);
		data(blockIndex).addLast(value);
		size++;
	}

    /**
     * Inserts the specified element at the specified position in this
     * list. Shifts the element currently at that position (if any) and
     * any subsequent elements to the right (adds one to their indices).
     *
     * @param index index at which the specified element is to be inserted
     * @param value element to be inserted
     * @throws IndexOutOfBoundsException if the index is out of range
     *         (<tt>index < 0 || index >= size()</tt>)
     */
	public void add(long index, boolean value) {
		rangeCheckForAdd(index);
		ensureCapacity(size + 1);
		int blockIndex = (int) (index >>> blockAddressBits);
		int valueIndex = (int) (index & (-1L >>> -blockAddressBits));
		int blockSize = 1 << blockAddressBits;
		if (data(blockIndex).size() < blockSize) {
			data[blockIndex].add(valueIndex, value);
		}
		else {
			value = data[blockIndex].add(valueIndex, value);
			while (data(++blockIndex).size() == blockSize) {
				value = data[blockIndex].addFirst(value);
			}
			data[blockIndex].addFirst(value);
		}
		size++;
	}

    /**
     * Removes the element at the specified position in this list.
     * Shifts any subsequent elements to the left (subtracts one from their
     * indices).
     *
     * @param index the index of the element to be removed
     * @return the element that was removed from the list
     * @throws IndexOutOfBoundsException if the index is out of range
     *         (<tt>index < 0 || index >= size()</tt>)
     */
	public boolean remove(long index) {
		rangeCheck(index);
		int blockIndex = (int) (index >>> blockAddressBits);
		int valueIndex = (int) (index & (-1L >>> -blockAddressBits));
		boolean removed = data[blockIndex].remove(valueIndex);
		while (++blockIndex < data.length && data[blockIndex] != null && data[blockIndex].size() > 0) {
			data[blockIndex-1].addLast(data[blockIndex].removeFirst());
		}
		size--;
		// - free unused blocks for GC and compact list if needed
		boolean blockFreed = false;
		while (++blockIndex < data.length && data[blockIndex] != null && data[blockIndex].size() == 0) {
			data[blockIndex] = null;
			blockFreed = true;
		}
		if (blockFreed)
			compact();
		return removed;
	}

	/**
	 * Removes all of the elements from this list. The list will be empty after this call returns.
	 */
	public void clear() {
		Arrays.fill(data, null);
		size = 0;
	}

    /**
     * Returns a copy of this <tt>BooleanList</tt> instance.
     *
     * @return a clone of this <tt>BooleanList</tt> instance
     */
	public Object clone() {
    	try {
			BooleanList clone = (BooleanList) super.clone();
			clone.data = new BinaryBlock[data.length];
    		for (int i = 0; i < data.length && data[i] != null; i++) {
    			clone.data[i] = (BinaryBlock) data[i].clone();
    		}
    		return clone;
		}
    	catch (CloneNotSupportedException e) {
    		// - should never be thrown since we are Cloneable
    		throw new InternalError();
		}
    }
}


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('feed', '0007_auto_20160418_0350'),
    ]

    operations = [
        migrations.CreateModel(
            name='CacheViews',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('network', models.CharField(max_length=50)),
                ('room', models.CharField(max_length=50)),
                ('cache', models.ForeignKey(to='feed.Cache')),
            ],
            options={
            },
            bases=(models.Model,),
        ),
        migrations.RemoveField(
            model_name='feedsubscription',
            name='last_read',
        ),
    ]

redpajama_set_name: RedPajamaGithub


text:
/*
 * Exception.cpp
 *
 *  Created on: 2015/10/12
 *      Author: tsubaki
 */

#include "Exception.h"

Exception::Exception() {

}

Exception::Exception(std::string message) {
	this->message = message;
}

Exception::Exception(std::string message, Throwable* cause) {
	this->message = message;
	this->cause = cause;
}
Exception::~Exception() {
}

std::string Exception::getClassName() {
	return "Exception";
}


text:
PWM Speaker driver for Android Things
=====================================

This driver supports speaker and piezo buzzer peripherals using the PWM protocol.

NOTE: these drivers are not production-ready. They are offered as sample
implementations of Android Things user space drivers for common peripherals
as part of the Developer Preview release. There is no guarantee
of correctness, completeness or robustness.

How to use the driver
---------------------

### Gradle dependency

To use the `pwmspeaker` driver, simply add the line below to your project's `build.gradle`,
where `<version>` matches the last version of the driver available on [jcenter][jcenter].

```
dependencies {
    compile 'com.google.android.things.contrib:driver-pwmspeaker:<version>'
}
```

### Sample usage

```java
import com.google.android.things.contrib.driver.pwmspeaker.Speaker;

// Access the speaker:

Speaker mSpeaker;

try {
    mSpeaker = new Speaker(pwmPinName);
} catch (IOException e) {
    // couldn't configure the speaker...
}

// Make it play:

try {
    mSpeaker.play(440 /* tone */);
} catch (IOException e) {
    // error setting speaker
}

// Stop a currently playing tone:

try {
    mSpeaker.stop();
} catch (IOException e) {
    // error stopping speaker
}

// Close the speaker when finished:

try {
    mSpeaker.close();
} catch (IOException e) {
    // error closing speaker
}
```

License
-------

Copyright 2016 Google Inc.

Licensed to the Apache Software Foundation (ASF) under one or more contributor
license agreements.  See the NOTICE file distributed with this work for
additional information regarding copyright ownership.  The ASF licenses this
file to you 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.

[jcenter]: https://bintray.com/google/androidthings/contrib-driver-pwmspeaker/_latestVersion


text:
class <%= class_name %> < ActiveRecord::Migration
  def self.up
    execute("ALTER TABLE <%=class_name.underscore%> ADD COLUMN geom geometry;")
    execute("CREATE INDEX idx_<%=class_name.underscore%>_geom ON <%=class_name.underscore%> USING GIST (geom);")
    execute("CLUSTER idx_<%=class_name.underscore%>_geom ON <%=class_name.underscore%>;")
    execute("VACUUM ANALYZE <%=class_name.underscore%>;")
  end

  def self.down
    execute("ALTER TABLE <%= class_name.underscore %> drop column geom;")
  end
end


text:
//---------------------------------------------------------------------
// <copyright file="OperationCacheTests.cs" company="Microsoft">
//      Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
// </copyright>
//---------------------------------------------------------------------

namespace AstoriaUnitTests.TDD.Tests.Server
{
    using System;
    using Microsoft.OData.Service;
    using Microsoft.OData.Service.Providers;
    using System.Linq;
    using FluentAssertions;
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    using Strings = Microsoft.OData.Service.Strings;

    [TestClass]
    public class OperationCacheTests
    {
        private readonly ResourceType entityType1;
        private readonly ResourceType entityType2;
        private readonly ServiceAction actionWithBindingParameter1;
        private readonly ServiceAction actionWithBindingParameter2;
        private readonly ServiceOperation serviceOperation;
        private readonly OperationWrapper serviceOperationWrapper;
        private readonly OperationWrapper actionWithBindingParameterWrapper1;
        private readonly OperationWrapper actionWithBindingParameterWrapper2;

        private OperationCache testSubject;

        public OperationCacheTests()
        {
            this.entityType1 = new ResourceType(typeof(object), ResourceTypeKind.EntityType, null, "My.Namespace", "Entity1", false);
            this.entityType2 = new ResourceType(typeof(object), ResourceTypeKind.EntityType, null, "My.Namespace", "Entity2", false);

            var intType = ResourceType.GetPrimitiveResourceType(typeof(int));
            this.actionWithBindingParameter1 = CreateAction("SameName", intType, this.entityType1);
            this.actionWithBindingParameter2 = CreateAction("SameName", intType, this.entityType2);
            this.serviceOperation = CreateServiceOperation("SameName", intType);

            this.actionWithBindingParameter1.SetReadOnly();
            this.actionWithBindingParameter2.SetReadOnly();
            this.serviceOperation.SetReadOnly();

            this.actionWithBindingParameterWrapper1 = new OperationWrapper(this.actionWithBindingParameter1);
            this.actionWithBindingParameterWrapper2 = new OperationWrapper(this.actionWithBindingParameter2);
            this.serviceOperationWrapper = new OperationWrapper(this.serviceOperation);
        }

        [TestInitialize]
        public void Init()
        {
            this.testSubject = new OperationCache();
            this.testSubject.Add(this.actionWithBindingParameterWrapper1);
            this.testSubject.Add(this.actionWithBindingParameterWrapper2);
            this.testSubject.Add(this.serviceOperationWrapper);
        }

        [TestMethod]
        public void OperationCacheLookupShouldReturnSameInstance()
        {
            OperationWrapper resultWrapper;
            this.testSubject.TryGetWrapper(this.actionWithBindingParameter1, out resultWrapper).Should().BeTrue();
            resultWrapper.Should().BeSameAs(this.actionWithBindingParameterWrapper1);
        }

        [TestMethod]
        public void OperationCacheLookupShouldWorkIfKeyIsAnotherInstance()
        {
            var equivalentAction = CreateAction(this.actionWithBindingParameter1.Name, ResourceType.GetPrimitiveResourceType(typeof(string)), this.entityType1);
            equivalentAction.SetReadOnly();
            OperationWrapper resultWrapper;
            this.testSubject.TryGetWrapper(equivalentAction, out resultWrapper).Should().BeTrue();
            resultWrapper.Should().BeSameAs(this.actionWithBindingParameterWrapper1);
        }

        [TestMethod]
        public void OperationCacheLookupShouldThrowIfActionIsNotReadOnly()
        {
            var equivalentAction = CreateAction(this.actionWithBindingParameter1.Name, ResourceType.GetPrimitiveResourceType(typeof(string)), this.entityType1);
            OperationWrapper resultWrapper;
            Action lookup = () => this.testSubject.TryGetWrapper(equivalentAction, out resultWrapper);
            lookup.ShouldThrow<DataServiceException>().WithMessage(Strings.DataServiceProviderWrapper_ServiceOperationNotReadonly(this.actionWithBindingParameter1.Name));
        }

        [TestMethod]
        public void OperationCacheLookupShouldWorkForServiceOperataion()
        {
            OperationWrapper resultWrapper;
            this.testSubject.TryGetWrapper(this.serviceOperation, out resultWrapper).Should().BeTrue();
            resultWrapper.Should().BeSameAs(this.serviceOperationWrapper);
        }

        [TestMethod]
        public void OperationCacheShouldBeCaseSensitive()
        {
            OperationWrapper resultWrapper;
            this.testSubject.TryGetWrapper(this.actionWithBindingParameter1.Name.ToUpperInvariant(), this.entityType1, out resultWrapper).Should().BeFalse();
        }

        [TestMethod]
        public void OperationCacheShouldReturnCorrectOverload()
        {
            this.actionWithBindingParameter1.Name.Should().Be(this.actionWithBindingParameter2.Name);

            OperationWrapper resultWrapper;
            this.testSubject.TryGetWrapper(this.actionWithBindingParameter1.Name, this.entityType1, out resultWrapper).Should().BeTrue();
            resultWrapper.Should().BeSameAs(this.actionWithBindingParameterWrapper1);

            this.testSubject.TryGetWrapper(this.actionWithBindingParameter1.Name, this.entityType2, out resultWrapper).Should().BeTrue();
            resultWrapper.Should().BeSameAs(this.actionWithBindingParameterWrapper2);
        }

        [TestMethod]
        public void OperationCacheContainsShouldBeTrueForEquivalentAction()
        {
            var equivalentAction = CreateAction(this.actionWithBindingParameter1.Name, ResourceType.GetPrimitiveResourceType(typeof(string)), this.entityType1);
            equivalentAction.SetReadOnly();
            this.testSubject.Contains(equivalentAction).Should().BeTrue();
        }

        [TestMethod]
        public void OperationCacheContainsShouldBeTrueForEquivalentServiceOperation()
        {
            var equivalentServiceOp = CreateServiceOperation(this.serviceOperation.Name, ResourceType.GetPrimitiveResourceType(typeof(string)));
            equivalentServiceOp.SetReadOnly();
            this.testSubject.Contains(equivalentServiceOp).Should().BeTrue();
        }

        [TestMethod]
        public void OperationCacheContainsShouldBeFalseForDifferentAction()
        {
            var differentAction = CreateAction(this.actionWithBindingParameter1.Name + "_Fake", ResourceType.GetPrimitiveResourceType(typeof(string)), this.entityType1);
            differentAction.SetReadOnly();
            this.testSubject.Contains(differentAction).Should().BeFalse();
        }

        [TestMethod]
        public void OperationCacheContainsShouldBeFalseForDifferentServiceOperation()
        {
            var differentServiceOperation = CreateServiceOperation(this.serviceOperation.Name + "_Fake", ResourceType.GetPrimitiveResourceType(typeof(string)));
            differentServiceOperation.SetReadOnly();
            this.testSubject.Contains(differentServiceOperation).Should().BeFalse();
        }

        [TestMethod]
        public void OperationCacheContainsShouldThrowIfActionIsNotReadOnly()
        {
            var equivalentAction = CreateAction(this.actionWithBindingParameter1.Name, ResourceType.GetPrimitiveResourceType(typeof(string)), this.entityType1);
            Action lookup = () => this.testSubject.Contains(equivalentAction);
            lookup.ShouldThrow<DataServiceException>().WithMessage(Strings.DataServiceProviderWrapper_ServiceOperationNotReadonly(this.actionWithBindingParameter1.Name));
        }

        private static ServiceOperation CreateServiceOperation(string operationName, ResourceType returnType)
        {
            return new ServiceOperation(operationName, ServiceOperationResultKind.DirectValue, returnType, null, "GET", null);
        }

        private static ServiceAction CreateAction(string operationName, ResourceType returnType, params ResourceType[] parameterTypes)
        {
            return new ServiceAction(operationName, returnType, OperationParameterBindingKind.Sometimes, parameterTypes.Select((t, i) => new ServiceActionParameter("Param" + i, t)), null);
        }
    }
}


text:
import { isEqual } from 'lodash';
import React from 'react';
import { FlatFixtureTreeItem } from 'react-cosmos-shared2/fixtureTree';
import { FixtureId } from 'react-cosmos-shared2/renderer';
import styled from 'styled-components';
import { IconButton32 } from '../../shared/buttons';
import { grey176, grey32, white10 } from '../../shared/colors';
import {
  MenuIcon,
  RotateCcwIcon,
  SlidersIcon,
  XCircleIcon,
} from '../../shared/icons';
import { FixtureActionSlot } from '../../shared/slots/FixtureActionSlot';
import { RendererActionSlot } from '../../shared/slots/RendererActionSlot';

type Props = {
  fixtureItems: FlatFixtureTreeItem[];
  fixtureId: FixtureId;
  navOpen: boolean;
  panelOpen: boolean;
  fixtureActionOrder: string[];
  rendererActionOrder: string[];
  onOpenNav: () => unknown;
  onTogglePanel: () => unknown;
  onFixtureSelect: (fixtureId: FixtureId) => unknown;
  onClose: () => unknown;
};

export const RendererHeader = React.memo(function RendererHeader({
  fixtureItems,
  fixtureId,
  navOpen,
  panelOpen,
  fixtureActionOrder,
  rendererActionOrder,
  onOpenNav,
  onTogglePanel,
  onFixtureSelect,
  onClose,
}: Props) {
  const fixtureItem = findFixtureItemById(fixtureItems, fixtureId);
  const slotProps = React.useMemo(() => ({ fixtureId }), [fixtureId]);
  const onReload = React.useCallback(() => onFixtureSelect(fixtureId), [
    fixtureId,
    onFixtureSelect,
  ]);

  return (
    <Container>
      <Left>
        {!navOpen && (
          <>
            <IconButton32
              icon={<MenuIcon />}
              title="Show fixture list"
              selected={false}
              onClick={onOpenNav}
            />
            <ButtonSeparator />
          </>
        )}
        <IconButton32
          icon={<XCircleIcon />}
          title="Close fixture"
          onClick={onClose}
        />
        <IconButton32
          icon={<RotateCcwIcon />}
          title="Reload fixture"
          onClick={onReload}
        />
        <FixtureActionSlot
          slotProps={slotProps}
          plugOrder={fixtureActionOrder}
        />
      </Left>
      {fixtureItem && <FixtureName>{getFixtureName(fixtureItem)}</FixtureName>}
      <Right>
        <RendererActionSlot
          slotProps={slotProps}
          plugOrder={rendererActionOrder}
        />
        <IconButton32
          icon={<SlidersIcon />}
          title="Toggle control panel"
          selected={panelOpen}
          onClick={onTogglePanel}
        />
      </Right>
    </Container>
  );
});

function findFixtureItemById(
  fixtureItems: FlatFixtureTreeItem[],
  fixtureId: FixtureId
) {
  return fixtureItems.find(fixtureItem =>
    isEqual(fixtureItem.fixtureId, fixtureId)
  );
}

function getFixtureName({ name, fileName }: FlatFixtureTreeItem) {
  return name ? `${fileName} ${name}` : fileName;
}

const Container = styled.div`
  flex-shrink: 0;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  height: 40px;
  padding: 0 4px;
  border-bottom: 1px solid ${white10};
  background: ${grey32};
  white-space: nowrap;
  overflow-x: auto;
`;

const Actions = styled.div`
  > button {
    margin-left: 4px;

    :first-child {
      margin-left: 0;
    }
  }
`;

const Left = styled(Actions)`
  display: flex;
  flex-direction: row;
  align-items: center;
`;

const Right = styled(Actions)`
  display: flex;
  flex-direction: row;
  align-items: center;
`;

const ButtonSeparator = styled.div`
  flex-shrink: 0;
  background: ${white10};
  width: 1px;
  height: 40px;
  margin-left: 4px;
`;

const FixtureName = styled.div`
  margin: 0 32px;
  padding: 4px 0;
  color: ${grey176};
  line-height: 24px;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
`;


text:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var passportLocalMongoose = require('passport-local-mongoose');

var ToolRequest = new Schema({
  lenderId: String,
  _lender: {type: Number, ref: 'User'},
  requesterId: String,
  _requester: {type: Number, ref: 'User'},
  toolId: String,
  status: String,
  reqStat: String,
  _tool: {type:Number, ref: 'Tool'},
});

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


text:
@interface KEZTableLabelDataSource ()
@property (nonatomic, strong) NSArray *rowTitles;
@property (nonatomic, strong) NSArray *columnTitles;
@property (nonatomic, strong) NSArray *labelStrings;
@end

@implementation KEZTableLabelDataSource
- (instancetype) init {
  return [self initWithRowTitles:nil columnTitles:nil labelStrings:@[]];
}

- (instancetype) initWithRowTitles:(NSArray *)rowTitles columnTitles:(NSArray *)columnTitles labelStrings:(NSArray *)labelStrings {
  if (self = [super init]) {
    _rowTitles = rowTitles;
    _columnTitles = columnTitles;
    _labelStrings = labelStrings;
  }

  return self;
}

+ (instancetype) sampleDataSourceWithRows:(NSUInteger)rows columns:(NSUInteger)columns rowHeaders:(BOOL)rowHeaders columnHeaders:(BOOL)columnHeaders {
  static NSNumberFormatter *formatter;
  if (!formatter) {
    formatter = [[NSNumberFormatter alloc] init];
    formatter.numberStyle = NSNumberFormatterSpellOutStyle;
  }

  NSMutableArray *rowTitles = [NSMutableArray array];
  NSMutableArray *rowHeaderTitles = rowHeaders ? [NSMutableArray array] : nil;
  NSMutableArray *columnHeaderTitles = columnHeaders ? [NSMutableArray array] : nil;

  for (int i = 0; i != rows; i++) {
    NSMutableArray *row = [NSMutableArray array];
    if (rowHeaders)
      [rowHeaderTitles addObject:[NSString stringWithFormat:@"Row %i", i]];

    for (int j = 0; j != columns; j++) {
      if (columnHeaders)
        [columnHeaderTitles addObject:[NSString stringWithFormat:@"Column %i", j]];

      [row addObject:[formatter stringFromNumber:@(i * j)]];
    }
    [rowTitles addObject:row];
  }

  return [[self alloc] initWithRowTitles:[rowHeaderTitles copy] columnTitles:[columnHeaderTitles copy] labelStrings:[rowTitles copy]];
}

- (NSString *) labelAtIndexPath:(NSIndexPath *)indexPath {
  return self.labelStrings[indexPath.section][indexPath.row];
}

- (NSString *) columnHeaderTitleAtIndexPath:(NSIndexPath *)indexPath {
  return self.columnTitles[indexPath.row];
}

- (NSString *) rowHeaderTitleAtIndexPath:(NSIndexPath *)indexPath {
  return self.rowTitles[indexPath.section];
}

#pragma mark - UICollectionViewDataSource
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
  static NSString *CellIdentifier = @"LabelCell";
  KEZLabelCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
  cell.label.text = self.labelStrings[indexPath.section][indexPath.row];
  return cell;
}

- (UICollectionReusableView *) collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
  static NSString *CellIdentifier = @"LabelHeader";
  KEZLabeledHeaderView *view = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:CellIdentifier forIndexPath:indexPath];
  if ([kind isEqualToString:KEZCollectionViewTableLayoutSupplementaryViewColumnHeader])
    view.label.text = self.columnTitles[indexPath.row];
  else if ([kind isEqualToString:KEZCollectionViewTableLayoutSupplementaryViewRowHeader])
    view.label.text = self.rowTitles[indexPath.section];

  return view;
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
  return self.labelStrings.count;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
  return ((NSArray*)self.labelStrings[section]).count;
}
@end


text:
package org.pentaho.js.require;

import org.json.simple.parser.JSONParser;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;

/**
 * Created by bryan on 8/5/14.
 */
public class RequireJsConfigManager {
  public static final String PACKAGE_JSON_PATH = "META-INF/js/package.json";
  public static final String REQUIRE_JSON_PATH = "META-INF/js/require.json";
  public static final String EXTERNAL_RESOURCES_JSON_PATH = "META-INF/js/externalResources.json";
  public static final String STATIC_RESOURCES_JSON_PATH = "META-INF/js/staticResources.json";

  private final Map<Long, Map<String, Object>> configMap = new HashMap<>();
  private final Map<Long, RequireJsConfiguration> requireConfigMap = new HashMap<>();

  private final JSONParser parser = new JSONParser();
  private BundleContext bundleContext;

  private static ScheduledExecutorService executorService =
    Executors.newSingleThreadScheduledExecutor( new ThreadFactory() {
      @Override
      public Thread newThread( Runnable r ) {
        Thread thread = Executors.defaultThreadFactory().newThread( r );
        thread.setDaemon( true );
        thread.setName( "RequireJSConfigManager pool" );
        return thread;
      }
    } );

  private volatile Future<String> cache;
  private volatile long lastModified;

  private String contextRoot = "/";
  private RequireJsBundleListener bundleListener;

  public BundleContext getBundleContext() {
    return bundleContext;
  }

  public void setBundleContext( BundleContext bundleContext ) {
    this.bundleContext = bundleContext;
  }

  public boolean updateBundleContext( Bundle bundle ) {
    switch ( bundle.getState() ) {
      case Bundle.STOPPING:
      case Bundle.RESOLVED:
      case Bundle.UNINSTALLED:
      case Bundle.INSTALLED:
        return updateBundleContextStopped( bundle );
      case Bundle.ACTIVE:
        break;
      default:
        return true;
    }

    boolean shouldInvalidate = false;

    URL packageJsonUrl = bundle.getResource( PACKAGE_JSON_PATH );
    URL configFileUrl = bundle.getResource( REQUIRE_JSON_PATH );

    URL externalResourcesUrl = bundle.getResource( EXTERNAL_RESOURCES_JSON_PATH );
    URL staticResourcesUrl = bundle.getResource( STATIC_RESOURCES_JSON_PATH );

    if ( configFileUrl != null ) {
      Map<String, Object> requireJsonObject = loadJsonObject( configFileUrl );

      if ( requireJsonObject != null ) {
        putInConfigMap( bundle.getBundleId(), requireJsonObject );

        shouldInvalidate = true;
      }
    }

    if ( !shouldInvalidate && packageJsonUrl != null ) {
      shouldInvalidate = parsePackageInformation( bundle, packageJsonUrl );
    }

    if ( externalResourcesUrl != null ) {
      Map<String, Object> externalResourceJsonObject = loadJsonObject( externalResourcesUrl );
      Map<String, Object> staticResourceJsonObject = loadJsonObject( staticResourcesUrl );

      if ( externalResourceJsonObject != null ) {
        List<String> requireJsList = (List<String>) externalResourceJsonObject.get( "requirejs" );

        if ( requireJsList != null ) {
          if ( staticResourceJsonObject != null ) {
            List<String> translatedList = new ArrayList<>( requireJsList.size() );

            for ( String element : requireJsList ) {
              boolean found = false;
              for ( Object key : staticResourceJsonObject.keySet() ) {
                String strKey = key.toString();

                if ( element.startsWith( strKey ) ) {
                  String value = staticResourceJsonObject.get( key ).toString();
                  translatedList.add( value + element.substring( strKey.length() ) );
                  found = true;
                  break;
                }
              }

              if ( !found ) {
                translatedList.add( element );
              }
            }

            requireJsList = translatedList;
          }

          putInRequireConfigMap( bundle.getBundleId(), new RequireJsConfiguration( bundle, requireJsList ) );
          shouldInvalidate = true;
        }
      }
    }

    return shouldInvalidate;
  }

  private boolean parsePackageInformation( Bundle bundle, URL resourceUrl ) {
    try {
      URLConnection urlConnection = resourceUrl.openConnection();
      RequireJsGenerator gen = RequireJsGenerator.parseJsonPackage( urlConnection.getInputStream() );

      if ( gen != null ) {
        RequireJsGenerator.ArtifactInfo artifactInfo =
          new RequireJsGenerator.ArtifactInfo( "osgi-bundles", bundle.getSymbolicName(),
            bundle.getVersion().toString() );
        final RequireJsGenerator.ModuleInfo moduleInfo = gen.getConvertedConfig( artifactInfo );
        Map<String, Object> requireJsonObject = moduleInfo.getRequireJs();

        putInConfigMap( bundle.getBundleId(), requireJsonObject );

        return true;
      }
    } catch ( Exception ignored ) {
      // ignored
    }

    return false;
  }

  private void putInConfigMap( long bundleId, Map<String, Object> config ) {
    configMap.put( bundleId, config );
  }

  private void putInRequireConfigMap( long bundleId, RequireJsConfiguration config ) {
    requireConfigMap.put( bundleId, config );
  }

  private Map<String, Object> loadJsonObject( URL url ) {
    if ( url == null ) {
      return null;
    }

    InputStream inputStream = null;
    InputStreamReader inputStreamReader = null;
    BufferedReader bufferedReader = null;

    try {
      URLConnection urlConnection = url.openConnection();
      inputStream = urlConnection.getInputStream();
      inputStreamReader = new InputStreamReader( urlConnection.getInputStream() );
      bufferedReader = new BufferedReader( inputStreamReader );

      return (Map<String, Object>) parser.parse( bufferedReader );
    } catch ( Exception ignored ) {
      // ignored
    } finally {
      try {
        if ( bufferedReader != null ) {
          bufferedReader.close();
        }
        if ( inputStreamReader != null ) {
          inputStreamReader.close();
        }
        if ( inputStream != null ) {
          inputStream.close();
        }
      } catch ( IOException ignored ) {
        // ignored
      }
    }

    return null;
  }

  public boolean updateBundleContextStopped( Bundle bundle ) {
    Map<String, Object> bundleConfig = configMap.remove( bundle.getBundleId() );
    RequireJsConfiguration requireJsConfiguration = requireConfigMap.remove( bundle.getBundleId() );

    return bundleConfig != null || requireJsConfiguration != null;
  }

  public void invalidateCache( boolean shouldInvalidate ) {
    if ( shouldInvalidate ) {
      lastModified = System.currentTimeMillis();

      if ( this.cache != null ) {
        this.cache.cancel( true );
      }

      this.cache = executorService.schedule( new RebuildCacheCallable( new HashMap<>( this.configMap ),
        new ArrayList<>( requireConfigMap.values() ) ), 250, TimeUnit.MILLISECONDS );
    }
  }

  public String getRequireJsConfig() {
    Future<String> cache = null;
    String result = null;
    int tries = 3;
    Exception lastException = null;
    while ( tries-- > 0 && ( result == null || cache != this.cache ) ) {
      cache = this.cache;
      try {
        result = cache.get();
      } catch ( InterruptedException e ) {
        // ignore
      } catch ( ExecutionException e ) {
        lastException = e;
        invalidateCache( true );
      }
    }
    if ( result == null ) {
      result = "{}; // Error computing RequireJS Config: ";
      if ( lastException != null ) {
        result += lastException.getCause().getMessage();
      } else {
        result += "unknown error";
      }
    }
    return result;
  }

  public long getLastModified() {
    return lastModified;
  }

  protected void setLastModified( long lastModified ) {
    this.lastModified = lastModified;
  }

  public void bundleChanged( Bundle bundle ) {
    boolean shouldRefresh = true;
    try {
      shouldRefresh = updateBundleContext( bundle );
    } catch ( Exception e ) {
      // Ignore TODO possibly log
    } finally {
      invalidateCache( shouldRefresh );
    }
  }

  public void init() throws Exception {
    bundleListener = new RequireJsBundleListener( this );
    bundleContext.addBundleListener( bundleListener );
    for ( Bundle bundle : bundleContext.getBundles() ) {
      updateBundleContext( bundle );
    }
    updateBundleContext( bundleContext.getBundle() );
    invalidateCache( true );
  }

  public void destroy() {
    if ( bundleListener != null ) {
      bundleContext.removeBundleListener( bundleListener );
    }
  }

  public String getContextRoot() {
    return this.contextRoot;
  }

  public void setContextRoot( String contextRoot ) {
    // ensure that the given string is properly bounded with slashes
    contextRoot = ( contextRoot.startsWith( "/" ) == false ) ? "/" + contextRoot : contextRoot;
    contextRoot = ( contextRoot.endsWith( "/" ) == false ) ? contextRoot + "/" : contextRoot;
    this.contextRoot = contextRoot;
  }
}


text:
namespace DummyAssembly
{
    public class Class1
    {
    }
}


text:
      {{appFirstName}}

        <fa name="outdent"></fa>

        {{loggedUser.userInfo.firstName | uppercase | limitTo:15}}{{loggedUser.userInfo.firstName.length > 15 ? '...' : ''}} <fa name="angle-down"></fa>

            <fa name="user"></fa>Profile

            <fa name="sign-out"></fa>Logout


text:
<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use App\Rules\HumanNameRule;
use App\Rules\UsernameRule;
use App\Rules\FacultyAddStudentDepartment;
use App\User;
use App\Rules\SlugRule;

class StudentRequest extends FormRequest
{
        /**
        * Determine if the user is authorized to make this request.
        *
        * @return bool
        */
        public function authorize()
        {
            return \Auth::user()->hasAnyPermission(['students update','students create']);
        }

        /**
        * Get the validation rules that apply to the request.
        *
        * @return array
        */
        public function rules()
        {
                $studentTable = (new User)->getTable();

                $username       = "unique:$studentTable,username";
                $email          = "unique:$studentTable,email";
                $password       = '|min:5|max:100|confirmed';

                if($this->method() == 'PUT')
                {
                        $id = User::whereSlug($this->route('student'))->firstOrFail()->id;
                        $username       .= ",$id";
                        $email          .= ",$id";
                        $password       = 'nullable' . $password;
                }
                else
                {
                        $password = 'required' . $password;
                }

                return [
                        'first_name'=> ['required',new HumanNameRule],
                        'last_name' => ['required',new HumanNameRule],
                        'username'  => ['required',new UsernameRule, $username],
                        'email'     => ['required', 'min:5', 'max:100', 'email', $email],
                        'password'  => $password,
                        'gender'    => 'required|in:male,female',

                        'address'   => 'required|min:5|max:200|string',
                        'contact'   => 'required|min:5|max:200|string',

                        'birthdate' => 'required|date',

                        'city'      =>'required|min:5|max:200|string',
                        'province'  =>'required|min:5|max:200|string',
                        'zip_code'  =>'required|min:4|max:200|string',

                        'department' => ['required',new SlugRule, new FacultyAddStudentDepartment],
                        'batch'      => ['required',new SlugRule],
                ];
        }
}


text:
@class AppDelegate;
typedef void(^AppDelegateRegisteredRemoteNotifications)(AppDelegate *appdelegate, NSData *deviceToken);
@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;
@property (copy, nonatomic) AppDelegateRegisteredRemoteNotifications registeredForRemoteNotificationsCallback;

@end


text:
package sqlancer.sqlite3.gen.ddl;

import sqlancer.IgnoreMeException;
import sqlancer.Randomly;
import sqlancer.common.query.ExpectedErrors;
import sqlancer.common.query.SQLQueryAdapter;
import sqlancer.sqlite3.SQLite3GlobalState;

public final class SQLite3DropTableGenerator {

    private SQLite3DropTableGenerator() {
    }

    public static SQLQueryAdapter dropTable(SQLite3GlobalState globalState) {
        if (globalState.getSchema().getTables(t -> !t.isView()).size() == 1) {
            throw new IgnoreMeException();
        }
        StringBuilder sb = new StringBuilder("DROP TABLE ");
        if (Randomly.getBoolean()) {
            sb.append("IF EXISTS ");
        }
        sb.append(globalState.getSchema().getRandomTableOrBailout(t -> !t.isView()).getName());
        return new SQLQueryAdapter(sb.toString(),
                ExpectedErrors.from("[SQLITE_ERROR] SQL error or missing database (foreign key mismatch",
                        "Abort due to constraint violation (FOREIGN KEY constraint failed)",
                        "SQL error or missing database"),
                true);

    }

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Biblthca Mycol. 90: 339 (1982)

#### Original name
Entoloma neglectum var. tetrasporum Winterhoff ex Arnolds

### Remarks
null


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:orientation="horizontal"

	android:focusable="false"

	android:layout_width="fill_parent"
	android:layout_height="wrap_content"

	android:background="@color/message_text_background"
	>

	<TextView android:id="@+id/text"
		android:layout_width="80dp"
		android:layout_height="wrap_content"

		android:layout_margin="5dp"
		android:gravity="center"

		android:textSize="12sp"
		android:textColor="@color/message_timestamp_foreground"

		android:text="12:10 PM"
		/>

</LinearLayout>


text:
You're an avid bird watcher that keeps track of how many birds have visited your garden in the last seven days.

You have five tasks, all dealing with the numbers of birds that visited your garden.

## 1. Check what the counts were last week

For comparison purposes, you always keep a copy of last week's counts nearby, which were: 0, 2, 5, 3, 7, 8 and 4. Implement the `BirdCount.last_week` method that returns last week's counts:

```ruby
BirdCount.last_week
# => [0, 2, 5, 3, 7, 8, 4]
```

## 2. Check how many birds visited yesterday

Implement the `BirdCount#yesterday` method to return how many birds visited your garden yesterday. The bird counts are ordered by day, with the first element being the count of the oldest day, and the last element being today's count.

```ruby
birds_per_day = [2, 5, 0, 7, 4, 1]
bird_count = new BirdCount(birds_per_day)
bird_count.yesterday
# => 4
```

## 3. Calculate the total number of visiting birds

Implement the `BirdCount#total` method to return the total number of birds that have visited your garden:

```ruby
birds_per_day = [2, 5, 0, 7, 4, 1]
bird_count = new BirdCount(birds_per_day)
bird_count.total
# => 19
```

## 4. Calculate the number of busy days

Some days are busier that others. A busy day is one where five or more birds have visited your garden.
Implement the `BirdCount#busy_days` method to return the number of busy days:

```ruby
birds_per_day = [2, 5, 0, 7, 4, 1]
bird_count = new BirdCount(birds_per_day)
bird_count.busy_days
# => 2
```

## 5. Check if there was a day with no visiting birds

Implement the `BirdCount#day_without_birds?` method that returns `true` if there was a day at which zero birds visited the garden; otherwise, return `false`:

```ruby
birds_per_day = [2, 5, 0, 7, 4, 1]
ird_count = new BirdCount(birds_per_day)
bird_count.day_without_birds?
# => true
```


text:
.. _virtualenv_python_generator:

virtualenv_python
=================

Created files
-------------

- activate_run_python.{sh|bat}
- deactivate_run_python.{sh|bat}

Usage
-----

Linux/macOS:

.. code-block:: bash

    > source activate_run_python.sh

Windows:

.. code-block:: bash

    > activate_run_python.bat

Variables declared
------------------

+--------------------+---------------------------------------------------------------------+
| ENVIRONMENT VAR    | DESCRIPTION                                                         |
+====================+=====================================================================+
| PATH               | With every ``bin`` folder of your requirements.                     |
+--------------------+---------------------------------------------------------------------+
| PYTHONPATH         | Union of ``PYTHONPATH`` of your requirements.                       |
+--------------------+---------------------------------------------------------------------+
| LD_LIBRARY_PATH    | ``lib`` folders of  your requirements.                              |
+--------------------+---------------------------------------------------------------------+
| DYLD_LIBRARY_PATH  | ``lib`` folders of  your requirements.                              |
+--------------------+---------------------------------------------------------------------+


text:
namespace FlyweightFiguresDemo
{
    using System;

    /// <summary>
    /// A 'ConcreteFlyweight' class
    /// </summary>
    public class Traingle : IShape
    {
        public void Print()
        {
            Console.WriteLine("Drawing a {0} to the console", this.GetType().Name);
        }
    }
}


text:
#!/usr/bin/env python
import os, sys

try:
    from setuptools import setup
    requires = {'requires': ['dateutil', 'django']}
except ImportError:
    from distutils.core import setup
    requires = {'install_requires': ['dateutil', 'Django>=1.6']}

if sys.argv[-1] == 'publish':
    os.system('python setup.py sdist upload')
    sys.exit(0)

with open('README.rst', 'r') as f:
    long_description = f.read()

# Dynamically calculate the version based on swingtime.VERSION.
version=__import__('swingtime').get_version()

setup(
    name='django-swingtime',
    url='https://github.com/dakrauth/django-swingtime',
    author='David A Krauth',
    author_email='dakrauth@gmail.com',
    description='A Django calendaring application.',
    version=version,
    long_description=long_description,
    platforms=['any'],
    license='MIT License',
    classifiers=(
        'Environment :: Web Environment',
        'Framework :: Django',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.4',
    ),
    packages=['swingtime', 'swingtime.conf'],
    package_data={'swingtime': ['locale/*/*/*.*', 'fixtures/swingtime_test.json']},
    **requires
)


text:
package com.samsung.sec.dexter.core.util;

import java.util.HashMap;
import java.util.Map;

public class DexterWebResourceAdapter implements IDexterWebResource {

	@Override
	public String getText(String uri, String id, String pwd) {
		return "";
	}

	@Override
	public Map<String, Object> getMap(String uri, String id, String pwd) {
		return new HashMap<String, Object>(0);
	}

	@Override
	public String postText(String uri, String id, String pwd) {
		return "";
	}

	@Override
	public String postWithBody(String uri, String id, String pwd, Map<String, Object> body) {
		return "";
	}

	@Override
	public String deleteWithBody(String uri, String id, String pwd, Map<String, Object> body) {
		return "";
	}

	@Override
	public String putWithBody(String uri, String id, String pwd, Map<String, Object> body) {
		return "";
	}

	@Override
	public String getConnectionResult(String uri, String id, String pwd) {
		return "";
	}

	@Override
	public String postWithBodyforCLI(String uri, String id, String pwd, String bodyJson) {
		return "";
	}

	@Override
	public void setDexterServerConfig(DexterServerConfig serverConfig) {

	}

	@Override
	public String getServiceUrl(String serviceUrl) {
		return null;
	}

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

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

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

	@Override
	public int getServerPort() {
		return 0;
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  android:id="@+id/root"
  android:layout_width="match_parent"
  android:layout_height="match_parent">

  <ProgressBar
    android:id="@+id/upcoming_events_progress"
    style="?android:attr/progressBarStyle"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:visibility="gone" />

  <android.support.v7.widget.RecyclerView
    android:id="@+id/upcoming_events_list"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:clipToPadding="false"
    android:paddingBottom="@dimen/fab_total_size"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:scrollbarStyle="outsideOverlay"
    android:scrollbars="vertical"
    tools:listitem="@layout/row_upcoming_events_bankholiday" />

  <TextView
    android:id="@+id/upcoming_events_emptyview"
    style="@style/NoContacts.Text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:gravity="center"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:text="@string/no_contacts_text"
    android:visibility="gone" />

</FrameLayout>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Acn.Rdm;
using Acn.ArtNet.IO;

namespace Acn.ArtNet.Packets
{
    public class ArtRdmSubPacket : ArtNetPacket
    {
        public ArtRdmSubPacket()
            : base(ArtNetOpCodes.RdmSub)
        {
            RdmVersion = 1;
        }

        public ArtRdmSubPacket(ArtNetReceiveData data)
            : base(data)
        {

        }

        #region Packet Properties

        public byte RdmVersion { get; set; }

        public UId DeviceId { get; set; }

        public RdmCommands Command { get; set; }

        public RdmParameters ParameterId { get; set; }

        public short SubDevice { get; set; }

        public short SubCount { get; set; }

        public byte[] RdmData { get; set; }

        #endregion

        public override void ReadData(ArtNetBinaryReader data)
        {
            RdmBinaryReader reader = new RdmBinaryReader(data.BaseStream);

            base.ReadData(data);

            RdmVersion = data.ReadByte();
            data.BaseStream.Seek(1, System.IO.SeekOrigin.Current);
            DeviceId = reader.ReadUId();
            data.BaseStream.Seek(1, System.IO.SeekOrigin.Current);
            Command = (RdmCommands) data.ReadByte();
            ParameterId = (RdmParameters) reader.ReadNetwork16();
            SubDevice = reader.ReadNetwork16();
            SubCount = reader.ReadNetwork16();
            data.BaseStream.Seek(4, System.IO.SeekOrigin.Current);
        }

        public override void WriteData(ArtNetBinaryWriter data)
        {
            RdmBinaryWriter writer = new RdmBinaryWriter(data.BaseStream);

            base.WriteData(data);

            writer.Write(RdmVersion);
            writer.Write(new byte[1]);
            writer.Write(DeviceId);
            writer.Write(new byte[1]);
            writer.Write((byte)Command);
            writer.WriteNetwork((short)ParameterId);
            writer.WriteNetwork(SubDevice);
            writer.WriteNetwork(SubCount);
            writer.Write(new byte[4]);
            writer.Write(RdmData);
        }

    }
}


text:
#ifndef KERNEL_INCLUDE_IO_PORT_HPP_
#define KERNEL_INCLUDE_IO_PORT_HPP_

/** @file
 * @brief Manage the IO communications
 */

#include <stdint.h>

#include <panic.hpp>

class IOPort {
public:
    /**
     * @brief Write a byte to a specific IO port
     * @param port The port address where to write to
     * @param byte The data to write
     */
    static void write_byte(uint16_t port, uint8_t byte);

    /**
     * @brief Read a byte from a specific IO port
     * @param port The port address where to read from
     * @return The data read
     */
    static uint8_t read_byte(uint16_t port);
};

#endif /* KERNEL_INCLUDE_IO_PORT_HPP_ */


text:
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;

namespace OpenNI
{
	public class EnumerationError
	{
		internal EnumerationError(IntPtr it)
		{
			this.it = it;
		}

		public ProductionNodeDescription Description
		{
			get
			{
				return SafeNativeMethods.xnEnumerationErrorsGetCurrentDescription(this.it);
			}
		}

		public string Error
		{
			get
			{
				int status = SafeNativeMethods.xnEnumerationErrorsGetCurrentError(this.it);
				return WrapperUtils.GetErrorMessage(status);
			}
		}

		private IntPtr it;
	}

	public class EnumerationErrors : ObjectWrapper, IEnumerable<EnumerationError>
	{
		internal EnumerationErrors(IntPtr pErrors) :
			base(pErrors)
		{
		}

		public EnumerationErrors() :
			this(Create())
		{
		}

		public bool IsEmpty()
		{
			IntPtr first = SafeNativeMethods.xnEnumerationErrorsGetFirst(this.InternalObject);
			return !SafeNativeMethods.xnEnumerationErrorsIteratorIsValid(first);
		}

		public override string ToString()
		{
			const int size = 2048;
			StringBuilder sb = new StringBuilder(size);
			int status = SafeNativeMethods.xnEnumerationErrorsToString(this.InternalObject, sb, size);
			WrapperUtils.ThrowOnError(status);
			return sb.ToString();
		}

		#region EnumerationErrosEnumerator class

		private class EnumerationErrosEnumerator : IEnumerator<EnumerationError>
		{
			public EnumerationErrosEnumerator(EnumerationErrors errors)
			{
				this.errors = errors;
				this.reset = true;
				this.it = IntPtr.Zero;
			}

			#region IEnumerator<EnumerationError> Members

			public EnumerationError Current
			{
				get { return new EnumerationError(this.it); }
			}

			#endregion

			#region IDisposable Members

			public void Dispose()
			{
			}

			#endregion

			#region IEnumerator Members

			object System.Collections.IEnumerator.Current
			{
				get { return ((IEnumerator<EnumerationError>)this).Current; }
			}

			public bool MoveNext()
			{
				if (this.reset)
				{
					this.it = SafeNativeMethods.xnEnumerationErrorsGetFirst(this.errors.InternalObject);
					this.reset = false;
				}
				else
				{
					this.it = SafeNativeMethods.xnEnumerationErrorsGetNext(this.it);
				}

				return SafeNativeMethods.xnEnumerationErrorsIteratorIsValid(this.it);
			}

			public void Reset()
			{
				this.reset = true;
			}

			#endregion

			private EnumerationErrors errors;
			private IntPtr it;
			private bool reset;
		}

		#endregion

		#region IEnumerable<EnumerationError> Members

		public IEnumerator<EnumerationError> GetEnumerator()
		{
			return new EnumerationErrosEnumerator(this);
		}

		#endregion

		#region IEnumerable Members

		System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
		{
			return ((IEnumerable<EnumerationError>)this).GetEnumerator();
		}

		#endregion

		protected override void FreeObject(IntPtr ptr, bool disposing)
		{
			SafeNativeMethods.xnEnumerationErrorsFree(ptr);
		}

		private static IntPtr Create()
		{
			IntPtr pErrors;
			int status = SafeNativeMethods.xnEnumerationErrorsAllocate(out pErrors);
			WrapperUtils.ThrowOnError(status);
			return pErrors;
		}
	}
}


text:
package org.spongepowered.common.service.permission;

import org.spongepowered.api.command.CommandSource;
import org.spongepowered.api.service.context.Context;
import org.spongepowered.api.service.permission.MemorySubjectData;
import org.spongepowered.api.service.permission.PermissionService;
import org.spongepowered.api.service.permission.Subject;
import org.spongepowered.api.service.permission.SubjectCollection;
import org.spongepowered.api.service.permission.SubjectReference;
import org.spongepowered.api.util.Tristate;
import org.spongepowered.common.service.permission.base.SpongeSubject;
import org.spongepowered.common.service.permission.base.SpongeSubjectCollection;

import java.util.Collection;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.function.Function;

import static com.google.common.base.Preconditions.checkNotNull;

public class DataFactoryCollection extends SpongeSubjectCollection {
    private final SpongePermissionService service;
    private final ConcurrentMap<String, SpongeSubject> subjects = new ConcurrentHashMap<>();
    private final Function<String, MemorySubjectData> dataFactory;
    final Function<String, CommandSource> commandSourceFunction;

    protected DataFactoryCollection(String identifier, SpongePermissionService service, Function<String, MemorySubjectData> dataFactory,
                                    Function<String, CommandSource> commandSourceFunction) {
        super(identifier, service);
        this.service = service;
        this.dataFactory = dataFactory;
        this.commandSourceFunction = commandSourceFunction;
    }

    @Override
    public SpongeSubject get(String identifier) {
        checkNotNull(identifier, "identifier");
        if (!this.subjects.containsKey(identifier)) {
            this.subjects.putIfAbsent(identifier, new DataFactorySubject(identifier, this.dataFactory.apply(identifier)));
        }
        return this.subjects.get(identifier);
    }

    @Override
    public boolean isRegistered(String identifier) {
        return this.subjects.containsKey(identifier);
    }

    @Override
    @SuppressWarnings("unchecked")
    public Collection<Subject> getLoadedSubjects() {
        return (Collection) this.subjects.values();
    }

    private class DataFactorySubject extends SpongeSubject {
        private final String identifier;
        private final MemorySubjectData data;

        protected DataFactorySubject(String identifier, MemorySubjectData data) {
            this.identifier = identifier;
            this.data = data;
        }

        @Override
        public String getIdentifier() {
            return this.identifier;
        }

        @Override
        public Optional<String> getFriendlyIdentifier() {
            return getCommandSource().map(CommandSource::getName);
        }

        @Override
        public Optional<CommandSource> getCommandSource() {
            return Optional.ofNullable(DataFactoryCollection.this.commandSourceFunction.apply(getIdentifier()));
        }

        @Override
        public SubjectCollection getContainingCollection() {
            return DataFactoryCollection.this;
        }

        @Override
        public PermissionService getService() {
            return DataFactoryCollection.this.service;
        }

        @Override
        public SubjectReference asSubjectReference() {
            return DataFactoryCollection.this.service.newSubjectReference(DataFactoryCollection.this.getIdentifier(), getIdentifier());
        }

        @Override
        public MemorySubjectData getSubjectData() {
            return this.data;
        }

        @Override
        public Tristate getPermissionValue(Set<Context> contexts, String permission) {
            Tristate ret = super.getPermissionValue(contexts, permission);

            if (ret == Tristate.UNDEFINED) {
                ret = getDataPermissionValue(DataFactoryCollection.this.getDefaults().getTransientSubjectData(), permission);
            }

            if (ret == Tristate.UNDEFINED) {
                ret = getDataPermissionValue(DataFactoryCollection.this.service.getDefaults().getTransientSubjectData(), permission);
            }
            return ret;
        }

        @Override
        public Optional<String> getOption(Set<Context> contexts, String option) {
            Optional<String> ret = super.getOption(contexts, option);
            if (!ret.isPresent()) {
                ret = getDataOptionValue(DataFactoryCollection.this.getDefaults().getSubjectData(), option);
            }
            if (!ret.isPresent()) {
                ret = getDataOptionValue(DataFactoryCollection.this.service.getDefaults().getSubjectData(), option);
            }
            return ret;
        }
    }
}


text:
{extend name="template/base" /}
{block name="nav"}{/block}
{block name="content"}

    <form action="{:\\think\\Request::instance()->baseUrl()}" method="post" id="form" style="padding-top: 50px">
        <input type="hidden" name="id" VALUE="{$Request.param.id}" />

                <button type="button" class="btn btn-primary radius" onclick="$('#checkAll').click()">  全选  </button>

                <button type="submit" class="btn btn-primary radius">  保存  </button>
                <button type="button" class="ml-20 btn btn-default radius" onclick="layer_close()">  取消  </button>

                        <input type="checkbox" id="checkAll">

                帐号
                姓名

            {volist name="list" id="vo"}

                        <input type="checkbox" name="user_id[]" value="{$vo.id}"/>

                {$vo.account}
                {$vo.realname}

            {/volist}

    </form>

{/block}
{block name="script"}

{/block}


text: Performing actions on notifications from Twitter


text:
package com.mapswithme.maps.bookmarks;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;

import com.mapswithme.maps.base.BaseToolbarActivity;
import com.mapswithme.maps.bookmarks.data.BookmarkManager;

public class BookmarksCatalogActivity extends BaseToolbarActivity
{
  public static final int REQ_CODE_CATALOG = 101;
  public static final String EXTRA_DOWNLOADED_CATEGORY = "extra_downloaded_category";

  public static void startForResult(@NonNull Fragment fragment, int requestCode)
  {
    fragment.startActivityForResult(makeLaunchIntent(fragment.getContext()), requestCode);
  }

  public static void startForResult(@NonNull Activity context, int requestCode)
  {
    context.startActivityForResult(makeLaunchIntent(context), requestCode);
  }

  @NonNull
  private static Intent makeLaunchIntent(@NonNull Context context)
  {
    Intent intent = new Intent(context, BookmarksCatalogActivity.class);
    intent.putExtra(BookmarksCatalogFragment.EXTRA_BOOKMARKS_CATALOG_URL,
                    BookmarkManager.INSTANCE.getCatalogFrontendUrl());
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    return intent;
  }

  @Override
  protected Class<? extends Fragment> getFragmentClass()
  {
    return BookmarksCatalogFragment.class;
  }

  @Override
  protected void onHomeOptionItemSelected()
  {
    finish();
  }
}


text:
using Gx.Common;
// <auto-generated>
//
//
// Generated by Enunciate.
// </auto-generated>
using System;
using System.Xml.Serialization;
using Newtonsoft.Json;
using System.Collections.Generic;

namespace Gx.Agent
{

    /// <remarks>
    ///  An online account for a web application.
    /// </remarks>
    ///
    ///  An online account for a web application.
    ///
    [Serializable]
    [XmlType(Namespace = "http://gedcomx.org/v1/", TypeName = "OnlineAccount")]
    public partial class OnlineAccount : Gx.Common.ExtensibleData
    {

        private string _accountName;
        private Gx.Common.ResourceReference _serviceHomepage;
        ///
        ///  The name associated the holder of this account with the account.
        ///
        [XmlElement(ElementName = "accountName", Namespace = "http://gedcomx.org/v1/")]
        [JsonProperty("accountName")]
        public string AccountName
        {
            get
            {
                return this._accountName;
            }
            set
            {
                this._accountName = value;
            }
        }
        ///
        ///  The homepage of the service that provides this account.
        ///
        [XmlElement(ElementName = "serviceHomepage", Namespace = "http://gedcomx.org/v1/")]
        [JsonProperty("serviceHomepage")]
        public Gx.Common.ResourceReference ServiceHomepage
        {
            get
            {
                return this._serviceHomepage;
            }
            set
            {
                this._serviceHomepage = value;
            }
        }

        /**
         * Build up this online account with a service homepage.
         *
         * @param serviceHomepage The service homepage.
         * @return this.
         */
        public OnlineAccount SetServiceHomepage(ResourceReference serviceHomepage)
        {
            this.ServiceHomepage = serviceHomepage;
            return this;
        }

        /**
         * Build up this online account with an account name.
         *
         * @param accountName The account name.
         */
        public OnlineAccount SetAccountName(String accountName)
        {
            this.AccountName = accountName;
            return this;
        }
    }
}


text:
<?php

namespace Zend\Mvc\Router\Http;

use Traversable;
use Zend\Mvc\Router\Exception;
use Zend\Stdlib\ArrayUtils;
use Zend\Stdlib\RequestInterface as Request;

/**
 * Hostname route.
 *
 * @package    Zend_Mvc_Router
 * @subpackage Http
 * @see        http://manuals.rubyonrails.com/read/chapter/65
 */
class Hostname implements RouteInterface
{
    /**
     * RouteInterface to match.
     *
     * @var array
     */
    protected $route;

    /**
     * Constraints for parameters.
     *
     * @var array
     */
    protected $constraints;

    /**
     * Default values.
     *
     * @var array
     */
    protected $defaults;

    /**
     * List of assembled parameters.
     *
     * @var array
     */
    protected $assembledParams = array();

    /**
     * Create a new hostname route.
     *
     * @param  string $route
     * @param  array  $constraints
     * @param  array  $defaults
     */
    public function __construct($route, array $constraints = array(), array $defaults = array())
    {
        $this->route       = explode('.', $route);
        $this->constraints = $constraints;
        $this->defaults    = $defaults;
    }

    /**
     * factory(): defined by RouteInterface interface.
     *
     * @see    Route::factory()
     * @param  array|\Traversable $options
     * @throws \Zend\Mvc\Router\Exception\InvalidArgumentException
     * @return Hostname
     */
    public static function factory($options = array())
    {
        if ($options instanceof Traversable) {
            $options = ArrayUtils::iteratorToArray($options);
        } elseif (!is_array($options)) {
            throw new Exception\InvalidArgumentException(__METHOD__ . ' expects an array or Traversable set of options');
        }

        if (!isset($options['route'])) {
            throw new Exception\InvalidArgumentException('Missing "route" in options array');
        }

        if (!isset($options['constraints'])) {
            $options['constraints'] = array();
        }

        if (!isset($options['defaults'])) {
            $options['defaults'] = array();
        }

        return new static($options['route'], $options['constraints'], $options['defaults']);
    }

    /**
     * match(): defined by RouteInterface interface.
     *
     * @see    Route::match()
     * @param  Request $request
     * @return RouteMatch
     */
    public function match(Request $request)
    {
        if (!method_exists($request, 'getUri')) {
            return null;
        }

        $uri      = $request->getUri();
        $hostname = explode('.', $uri->getHost());
        $params   = array();

        if (count($hostname) !== count($this->route)) {
            return null;
        }

        foreach ($this->route as $index => $routePart) {
            if (preg_match('(^:(?P<name>.+)$)', $routePart, $matches)) {
                if (isset($this->constraints[$matches['name']]) && !preg_match('(^' . $this->constraints[$matches['name']] . '$)', $hostname[$index])) {
                    return null;
                }

                $params[$matches['name']] = $hostname[$index];
            } elseif ($hostname[$index] !== $routePart) {
                return null;
            }
        }

        return new RouteMatch(array_merge($this->defaults, $params));
    }

    /**
     * assemble(): Defined by RouteInterface interface.
     *
     * @see    Route::assemble()
     * @param  array $params
     * @param  array $options
     * @return mixed
     * @throws Exception\InvalidArgumentException
     */
    public function assemble(array $params = array(), array $options = array())
    {
        $mergedParams          = array_merge($this->defaults, $params);
        $this->assembledParams = array();

        if (isset($options['uri'])) {
            $parts = array();

            foreach ($this->route as $routePart) {
                if (preg_match('(^:(?P<name>.+)$)', $routePart, $matches)) {
                    if (!isset($mergedParams[$matches['name']])) {
                        throw new Exception\InvalidArgumentException(sprintf('Missing parameter "%s"', $matches['name']));
                    }

                    $parts[] = $mergedParams[$matches['name']];

                    $this->assembledParams[] = $matches['name'];
                } else {
                    $parts[] = $routePart;
                }
            }

            $options['uri']->setHost(implode('.', $parts));
        }

        // A hostname does not contribute to the path, thus nothing is returned.
        return '';
    }

    /**
     * getAssembledParams(): defined by RouteInterface interface.
     *
     * @see    Route::getAssembledParams
     * @return array
     */
    public function getAssembledParams()
    {
        return $this->assembledParams;
    }
}


text:
#ifndef BADVPN_TUN2SOCKS_SOCKSUDPGWCLIENT_H
#define BADVPN_TUN2SOCKS_SOCKSUDPGWCLIENT_H

#include <misc/debug.h>
#include <base/DebugObject.h>
#include <system/BReactor.h>
#ifdef BADVPN_SOCKS_UDP_RELAY
#include <protocol/udpgw_proto.h>
#include <protocol/packetproto.h>
#include <system/BDatagram.h>
#include <flow/PacketBuffer.h>
#include <flow/SinglePacketBuffer.h>
#include <flow/BufferWriter.h>
#include <structure/BAVL.h>
#include <structure/LinkedList1.h>
#include <misc/offset.h>
#else
#include <udpgw_client/UdpGwClient.h>
#include <socksclient/BSocksClient.h>
#endif

typedef void (*SocksUdpGwClient_handler_received) (void *user, BAddr local_addr, BAddr remote_addr, const uint8_t *data, int data_len);

typedef struct {
    int udp_mtu;
    BAddr socks_server_addr;
    const struct BSocksClient_auth_info *auth_info;
    size_t num_auth_info;
    BAddr remote_udpgw_addr;
    BReactor *reactor;
    void *user;
    SocksUdpGwClient_handler_received handler_received;
#ifdef BADVPN_SOCKS_UDP_RELAY
    int udpgw_mtu;
    int num_connections;
    int max_connections;
    BAVL connections_tree;
    LinkedList1 connections_list;
#else
    UdpGwClient udpgw_client;
    BTimer reconnect_timer;
    int have_socks;
    BSocksClient socks_client;
    int socks_up;
#endif
    DebugObject d_obj;
} SocksUdpGwClient;

#ifdef BADVPN_SOCKS_UDP_RELAY
typedef struct {
    BAddr local_addr;
    BAddr remote_addr;
} SocksUdpGwClient_conaddr;

typedef struct {
    SocksUdpGwClient *client;
    SocksUdpGwClient_conaddr conaddr;
    BPending first_job;
    const uint8_t *first_data;
    int first_data_len;
    BDatagram udp_dgram;
    BufferWriter udp_send_writer;
    PacketBuffer udp_send_buffer;
    SinglePacketBuffer udp_recv_buffer;
    PacketPassInterface udp_recv_if;
    BAVLNode connections_tree_node;
    LinkedList1Node connections_list_node;
} SocksUdpGwClient_connection;
#endif

int SocksUdpGwClient_Init (SocksUdpGwClient *o, int udp_mtu, int max_connections, int send_buffer_size, btime_t keepalive_time,
                           BAddr socks_server_addr, const struct BSocksClient_auth_info *auth_info, size_t num_auth_info,
                           BAddr remote_udpgw_addr, btime_t reconnect_time, BReactor *reactor, void *user,
                           SocksUdpGwClient_handler_received handler_received) WARN_UNUSED;
void SocksUdpGwClient_Free (SocksUdpGwClient *o);
void SocksUdpGwClient_SubmitPacket (SocksUdpGwClient *o, BAddr local_addr, BAddr remote_addr, int is_dns, const uint8_t *data, int data_len);

#endif


text:
using System.IO;
using NUnit.Framework;
using SSDTDevPack.Rewriter;

namespace SSDTDevPack.Common.UnitTests
{
    static class Directories
    {
        public static string GetSampleSolution()
        {
            return @"..\..\..\SampleSolutions";
        }
    }

    [TestFixture]
    public class InequalityRewriterTests
    {
        [Test]
        public void RewritesBangEquals()
        {
            var script = @"select 1, (select top 1 a from b where 1!=2) from a where a ! /*sssssss**/  =   b";

            var rewriter = new InEqualityRewriter(script);
            var replacements = rewriter.GetReplacements(ScriptDom.ScriptDom.GetQuerySpecifications(script));
            Assert.AreEqual(2, replacements.Count);
        }

        //[Test] - NOT SURE WHERE GoodImport.sql is??
        //public void MultipleRewritesAreFound()
        //{
        //    var script = File.ReadAllText(Path.Combine(Directories.GetSampleSolution(), @"NestedProjects\Nested\ABC\DEF\GoodImport.sql"));
        //    var rewriter = new InEqualityRewriter(script);
        //    var replacements = rewriter.GetReplacements(ScriptDom.ScriptDom.GetQuerySpecifications(script));

        //    Assert.AreEqual(2, replacements.Count);

        //}
    }
}


text:
namespace Umbraco.Cms.Core.Persistence
{
    public enum TextColumnType
    {
        NVarchar,
        NText
    }
}


text:
import time

import eventlet
from mock import (MagicMock, Mock, patch)
import unittest2

from st2reactor.container.process_container import ProcessSensorContainer

import st2tests.config as tests_config
tests_config.parse_args()

class ProcessContainerTests(unittest2.TestCase):

    def test_no_sensors_dont_quit(self):
        process_container = ProcessSensorContainer(None, poll_interval=0.1)
        process_container_thread = eventlet.spawn(process_container.run)
        eventlet.sleep(0.5)
        self.assertEqual(process_container.running(), 0)
        self.assertEqual(process_container.stopped(), False)
        process_container.shutdown()
        process_container_thread.kill()

    @patch.object(time, 'time', MagicMock(return_value=1439441533))
    def test_dispatch_triggers_on_spawn_exit(self):
        mock_dispatcher = Mock()
        process_container = ProcessSensorContainer(None, poll_interval=0.1,
                                                   dispatcher=mock_dispatcher)
        sensor = {
            'class_name': 'pack.StupidSensor'
        }
        process = Mock()
        process_attrs = {'pid': 1234}
        process.configure_mock(**process_attrs)
        cmd = 'sensor_wrapper.py --class-name pack.StupidSensor'

        process_container._dispatch_trigger_for_sensor_spawn(sensor, process, cmd)
        mock_dispatcher.dispatch.assert_called_with(
            'core.st2.sensor.process_spawn',
            payload={
                'timestamp': 1439441533,
                'cmd': 'sensor_wrapper.py --class-name pack.StupidSensor',
                'pid': 1234,
                'id': 'pack.StupidSensor'})

        process_container._dispatch_trigger_for_sensor_exit(sensor, 1)
        mock_dispatcher.dispatch.assert_called_with(
            'core.st2.sensor.process_exit',
            payload={
                'id': 'pack.StupidSensor',
                'timestamp': 1439441533,
                'exit_code': 1
            })


text:
using System;
using System.Linq.Expressions;
using FluentNHibernate.Testing.Values;
using FluentNHibernate.Utils.Reflection;
using NHibernate;
using NUnit.Framework;
using Rhino.Mocks;

namespace FluentNHibernate.Testing.Testing.Values
{
    [TestFixture]
    public class When_a_reference_property_is_registered_on_the_persistence_specification : Specification
    {
        private ReferenceProperty<PropertyEntity, OtherEntity> sut;
        private PersistenceSpecification<PropertyEntity> specification;
        private OtherEntity referencedEntity;
        private ISession session;

        public override void establish_context()
        {
            var property = ReflectionHelper.GetAccessor((Expression<Func<ReferenceEntity, OtherEntity>>)(x => x.Reference));

            referencedEntity = new OtherEntity();

            session = MockRepository.GenerateStub<ISession>();
            session.Stub(x => x.BeginTransaction()).Return(MockRepository.GenerateStub<ITransaction>());
            specification = new PersistenceSpecification<PropertyEntity>(session);

            sut = new ReferenceProperty<PropertyEntity, OtherEntity>(property, referencedEntity);
        }

        public override void because()
        {
            sut.HasRegistered(specification);
        }

        [Test]
        public void should_save_the_referenced_entity()
        {
            session.AssertWasCalled(x => x.Save(referencedEntity));
        }
    }
}


text:
package cmd

type builderFunc func([]string) *Cmd
type builder struct {
	keyFile     string
	builderFunc builderFunc
}

var builders []builder

func init() {
	builders = []builder{
		{"Makefile", MakefileBuilder},
		{"./test.sh", TestSHBuilder},
		{".buffalo.dev.yml", BuffaloBuilder},
		{"**/*_test.go", GoBuilder},
	}
}


text:
const path = require('path');

// Packages
const mlog = require('mocha-logger');
const _ = require('lodash');
const sleep = require('thread-sleep');
const request = require('urllib-sync').request;

const options = {
  'log-level': 'silent',
  'no-port-scan': true,
  port: 8888
};

const httpHost = 'http://localhost:' + options.port;

try {
  // Check if the server is online
  request(httpHost);

  mlog.error('There is a server already running under the host \'' + httpHost + '\'');
  process.exit(500);
} catch (err) {
}

const startServer = (opts = {}, dirname) => {
  let htmlPages = null;

  const checkIfServerIsOnline = (retries = 0) => {
    try {
      // Check if the server is online
      request(httpHost + '/@server-status::check-if-server-is-already-up');

      return true;
    } catch (err) {
      if (retries >= 25) {
        mlog.error('Can\'t connect to ' + httpHost + '. Number of retries: ' + retries);
        process.exit(1);
      }

      sleep(50);
    }
    retries++;

    return checkIfServerIsOnline(retries);
  };

  opts = _.merge({}, options, opts);

  if (dirname === undefined) {
    dirname = path.join(__dirname, 'data');
  }

  htmlPages = require('../lib/api')(dirname, opts);

  if (checkIfServerIsOnline() === false) {
    checkIfServerIsOnline();
  }

  return {
    htmlPages,
    httpHost
  };
};

const parseResponse = (response, debug) => {
  if (debug !== true) {
    return false;
  }

  mlog.log('response', Object.keys(response));
  mlog.log('status', response.status);
  mlog.log('statusCode', response.statusCode);

  for (const _header in response.headers) {
    mlog.log('_header', _header, response.headers[_header]);
  }
};

module.exports = {
  startServer,
  parseResponse
};


text:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>Filibuster</title> <link rel="stylesheet" href="styles.css">
<link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro" rel="stylesheet">

Results for "books_section"

Index

Elderly

Paris

Parental

Food

New in print

Book

Sci-Fi

Healthy cooking

Interior

Valentine

Design

Interior

Math

AAA

Children books

Typography

Classics

Fantasy

Classics

Valentine


text:
define(
    ['./main',
        './login',
        './navbar',
        './sidebar',
        './content.controller',
        './add.content.controller',
        './contentTemplates',
        './contenttypes.controller',
        './add.contenttypes.controller',
        './files',
        './directories',
        './script',
        './settings',
        './block'
    ], function() {});


text:
<TITLE>Review for Six Days Seven Nights (1998)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Six Days Seven Nights (1998)

reviewed by
James Sanford

        On paper, at least, the idea must have looked like it couldn't miss:
Harrison Ford plays a grizzled pilot named Quinn hired to fly cosmopolitan
Robin (Anne Heche) to Tahiti, and when they crash, the two must fend off
myriad dangers on an uncharted island. Think of a "Romancing The Stone" and
"African Queen" with just a trace of the sexual politics of "Swept Away"
thrown in.

Now lower your expectations - drastically.

"Six Days, Seven Nights" is the sort of movie that looks lovely and comes
across nicely in clips, but ultimately proves to be neither erotic, exotic
or even exciting.

There's nothing glaringly awful here, just a lot of underachievement from
some people who can do - and have done - better. That said, "Six Days" is
painless enough to sit through if all you're looking for is two hours of
gorgeous tropical scenery and the odd bit of action.
Films like this rely heavily on star power, and Ford and Heche turn out to
be a far cry from Humphrey Bogart and Katharine Hepburn. In fact, they're
not even close to Michael Douglas and Kathleen Turner.

Part of the blame rests on their shoulders. Ford does not seem to be
terribly engaged by his shallow character, and Heche, though charming in her
laid-back moments, tends to mug and screech to get laughs. She also
continually plunges into the water in a variety of semi-transparent white
tops, to no great effect. Ford and Heche are working at opposite extremes,
and though they're on the screen together, it doesn't feel like they're in
the same movie much of the time.

Then again, writer Michael Browning hasn't given either actor much to work
with in terms of witty lines or romantic moments. Shortly after being
stranded, Quinn and Robin take turns getting into each other's pants, as he
removes a water snake from hers and she retrieves a flare gun from his.
Unfortunately, neither situation generates any sizzle or much in the way of
big laughs.

Neither do the antics of David Schwimmer and Jacqueline Obradors as Robin's
wormy fiance and Quinn's voluptuous fling-of-the-moment. Their subplot shows
signs of having been severely curtailed, probably an act of mercy.

Near the start, "Six Days" shows a welcome satiric streak, introducing Heche
as a put-upon assistant editor at a magazine called Dazzle, which features
stories with such enticing headlines as "Your derriere: Five ways to tame
the beast." But that soon evaporates as the movie spends its best jokes
early on, struggles vainly to establish Ford and Heche as a credible couple,
then elects late in the game to throw in machine-gun-toting pirates and
explosions as a kicker.

Director Ivan Reitman does what he can to establish a buoyant tone for the
film, and he's fairly successful. But in the final analysis,
"Six Days" is neither a true adventure nor a good comedy, neither sexy nor
suspenseful, neither fish nor fowl. One thing is certain, though: See it
tonight and you will have forgotten all about it by this time next week.
James Sanford

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews