text:
'use strict';

const fs = require('fs');
const KernelBase = require('../kernel-base');
const utils = require('../../core/utils');
const Texture = require('../../core/texture');
const fragShaderString = require('./shader-frag');
const vertShaderString = require('./shader-vert');
const kernelString = require('./kernel-string');
const canvases = [];
const maxTexSizes = {};
module.exports = class WebGLKernel extends KernelBase {

	/**
	 * @constructor WebGLKernel
	 *
	 * @desc Kernel Implementation for WebGL.
	 *
This builds the shaders and runs them on the GPU,
	 * the outputs the result back as float(enabled by default) and Texture.

	 *
	 * @extends KernelBase
	 *
	 * @prop {Object} textureCache - webGl Texture cache
	 * @prop {Object} threadDim - The thread dimensions, x, y and z
	 * @prop {Object} programUniformLocationCache - Location of program variables in memory
	 * @prop {Object} framebuffer - Webgl frameBuffer
	 * @prop {Object} buffer - WebGL buffer
	 * @prop {Object} program - The webGl Program
	 * @prop {Object} functionBuilder - Function Builder instance bound to this Kernel
	 * @prop {Boolean} outputToTexture - Set output type to Texture, instead of float
	 * @prop {String} endianness - Endian information like Little-endian, Big-endian.
	 * @prop {Array} paramTypes - Types of parameters sent to the Kernel
	 * @prop {number} argumentsLength - Number of parameters sent to the Kernel
	 * @prop {String} compiledFragShaderString - Compiled fragment shader string
	 * @prop {String} compiledVertShaderString - Compiled Vertical shader string
	 */
	constructor(fnString, settings) {
		super(fnString, settings);
		this.textureCache = {};
		this.threadDim = {};
		this.programUniformLocationCache = {};
		this.framebuffer = null;

		this.buffer = null;
		this.program = null;
		this.functionBuilder = settings.functionBuilder;
		this.outputToTexture = settings.outputToTexture;
		this.endianness = utils.systemEndianness();
		this.subKernelOutputTextures = null;
		this.subKernelOutputVariableNames = null;
		this.paramTypes = null;
		this.argumentsLength = 0;
		this.ext = null;
		this.compiledFragShaderString = null;
		this.compiledVertShaderString = null;
		this.extDrawBuffersMap = null;
		this.outputTexture = null;
		this.maxTexSize = null;
		if (!this._webGl) this._webGl = utils.initWebGl(this.getCanvas());
	}

	/**
	 * @memberOf WebGLKernel#
	 * @function
	 * @name validateOptions
	 *
	 * @desc Validate options related to Kernel, such as
	 * floatOutputs and Textures, texSize, output,
	 * graphical output.
	 *
	 */
	validateOptions() {
		const isReadPixel = utils.isFloatReadPixelsSupported();
		if (this.floatTextures === true && !utils.OES_texture_float) {
			throw 'Float textures are not supported on this browser';
		} else if (this.floatOutput === true && this.floatOutputForce !== true && !isReadPixel) {
			throw 'Float texture outputs are not supported on this browser';
		} else if (this.floatTextures === null && !isReadPixel && !this.graphical) {
			//NOTE: handle
			this.floatTextures = true;
			this.floatOutput = false;
		}

		if (!this.output || this.output.length === 0) {
			if (arguments.length !== 1) {
				throw 'Auto output only supported for kernels with only one input';
			}

			const argType = utils.getArgumentType(arguments[0]);
			if (argType === 'Array') {
				this.output = utils.getDimensions(argType);
			} else if (argType === 'Texture') {
				this.output = arguments[0].output;
			} else {
				throw 'Auto output not supported for input type: ' + argType;
			}
		}

		this.texSize = utils.dimToTexSize({
			floatTextures: this.floatTextures,
			floatOutput: this.floatOutput
		}, this.output, true);

		if (this.graphical) {
			if (this.output.length !== 2) {
				throw 'Output must have 2 dimensions on graphical mode';
			}

			if (this.floatOutput) {
				throw 'Cannot use graphical mode and float output at the same time';
			}

			this.texSize = utils.clone(this.output);
		} else if (this.floatOutput === undefined && utils.OES_texture_float) {
			this.floatOutput = true;
		}
	}

	updateMaxTexSize() {
		const texSize = this.texSize;
		const canvas = this._canvas;
		if (this.maxTexSize === null) {
			let canvasIndex = canvases.indexOf(canvas);
			if (canvasIndex === -1) {
				canvasIndex = canvases.length;
				canvases.push(canvas);
				maxTexSizes[canvasIndex] = [texSize[0], texSize[1]];
			}
			this.maxTexSize = maxTexSizes[canvasIndex];
		}
		if (this.maxTexSize[0] < texSize[0]) {
			this.maxTexSize[0] = texSize[0];
		}
		if (this.maxTexSize[1] < texSize[1]) {
			this.maxTexSize[1] = texSize[1];
		}
	}

	/**
	 * @memberOf WebGLKernel#
	 * @function
	 * @name build
	 *
	 * @desc Builds the Kernel, by compiling Fragment and Vertical Shaders,
	 * and instantiates the program.
	 *
	 */

	build() {
		this.validateOptions();
		this.setupParams(arguments);
		this.updateMaxTexSize();
		const texSize = this.texSize;
		const gl = this._webGl;
		const canvas = this._canvas;
		gl.enable(gl.SCISSOR_TEST);
		gl.viewport(0, 0, this.maxTexSize[0], this.maxTexSize[1]);
		canvas.width = this.maxTexSize[0];
		canvas.height = this.maxTexSize[1];
		const threadDim = this.threadDim = utils.clone(this.output);
		while (threadDim.length < 3) {
			threadDim.push(1);
		}

		if (this.functionBuilder) this._addKernels();

		const compiledVertShaderString = this._getVertShaderString(arguments);
		const vertShader = gl.createShader(gl.VERTEX_SHADER);
		gl.shaderSource(vertShader, compiledVertShaderString);
		gl.compileShader(vertShader);

		const compiledFragShaderString = this._getFragShaderString(arguments);
		const fragShader = gl.createShader(gl.FRAGMENT_SHADER);
		gl.shaderSource(fragShader, compiledFragShaderString);
		gl.compileShader(fragShader);

		if (!gl.getShaderParameter(vertShader, gl.COMPILE_STATUS)) {
			console.log(compiledVertShaderString);
			console.error('An error occurred compiling the shaders: ' + gl.getShaderInfoLog(vertShader));
			throw 'Error compiling vertex shader';
		}
		if (!gl.getShaderParameter(fragShader, gl.COMPILE_STATUS)) {
			console.log(compiledFragShaderString);
			console.error('An error occurred compiling the shaders: ' + gl.getShaderInfoLog(fragShader));
			throw 'Error compiling fragment shader';
		}

		if (this.debug) {
			console.log('Options:');
			console.dir(this);
			console.log('GLSL Shader Output:');
			console.log(compiledFragShaderString);
		}

		const program = this.program = gl.createProgram();
		gl.attachShader(program, vertShader);
		gl.attachShader(program, fragShader);
		gl.linkProgram(program);
		this.framebuffer = gl.createFramebuffer();
		this.framebuffer.width = texSize[0];
		this.framebuffer.height = texSize[1];

		const vertices = new Float32Array([-1, -1,
			1, -1, -1, 1,
			1, 1
		]);
		const texCoords = new Float32Array([
			0, 0,
			1, 0,
			0, 1,
			1, 1
		]);

		const texCoordOffset = vertices.byteLength;

		let buffer = this.buffer;
		if (!buffer) {
			buffer = this.buffer = gl.createBuffer();
			gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
			gl.bufferData(gl.ARRAY_BUFFER, vertices.byteLength + texCoords.byteLength, gl.STATIC_DRAW);
		} else {
			gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
		}

		gl.bufferSubData(gl.ARRAY_BUFFER, 0, vertices);
		gl.bufferSubData(gl.ARRAY_BUFFER, texCoordOffset, texCoords);

		const aPosLoc = gl.getAttribLocation(this.program, 'aPos');
		gl.enableVertexAttribArray(aPosLoc);
		gl.vertexAttribPointer(aPosLoc, 2, gl.FLOAT, gl.FALSE, 0, 0);
		const aTexCoordLoc = gl.getAttribLocation(this.program, 'aTexCoord');
		gl.enableVertexAttribArray(aTexCoordLoc);
		gl.vertexAttribPointer(aTexCoordLoc, 2, gl.FLOAT, gl.FALSE, 0, texCoordOffset);

		this.setupOutputTexture();

		if (this.subKernelOutputTextures !== null) {
			const extDrawBuffersMap = this.extDrawBuffersMap = [gl.COLOR_ATTACHMENT0];
			for (let i = 0; i < this.subKernelOutputTextures.length; i++) {
				const subKernelOutputTexture = this.subKernelOutputTextures[i];
				extDrawBuffersMap.push(gl.COLOR_ATTACHMENT0 + i + 1);
				gl.activeTexture(gl.TEXTURE0 + arguments.length + i);
				gl.bindTexture(gl.TEXTURE_2D, subKernelOutputTexture);
				gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
				gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
				gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
				gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
				if (this.floatOutput) {
					gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, texSize[0], texSize[1], 0, gl.RGBA, gl.FLOAT, null);
				} else {
					gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, texSize[0], texSize[1], 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
				}
			}
		}
	}

	/**
	 * @memberOf WebGLKernel#
	 * @function
	 * @name run
	 *
	 * @desc Run the kernel program, and send the output to renderOutput
	 *
	 *
 This method calls a helper method *renderOutput* to return the result.

	 *
	 * @returns {Object} Result The final output of the program, as float, and as Textures for reuse.
	 *
	 *
	 */
	run() {
		if (this.program === null) {
			this.build.apply(this, arguments);
		}
		const paramNames = this.paramNames;
		const paramTypes = this.paramTypes;
		const texSize = this.texSize;
		const gl = this._webGl;

		gl.useProgram(this.program);
		gl.scissor(0, 0, texSize[0], texSize[1]);

		if (!this.hardcodeConstants) {
			const uOutputDimLoc = this.getUniformLocation('uOutputDim');
			gl.uniform3fv(uOutputDimLoc, this.threadDim);
			const uTexSizeLoc = this.getUniformLocation('uTexSize');
			gl.uniform2fv(uTexSizeLoc, texSize);
		}

		const ratioLoc = this.getUniformLocation('ratio');
		gl.uniform2f(ratioLoc, texSize[0] / this.maxTexSize[0], texSize[1] / this.maxTexSize[1]);

		this.argumentsLength = 0;
		for (let texIndex = 0; texIndex < paramNames.length; texIndex++) {
			this._addArgument(arguments[texIndex], paramTypes[texIndex], paramNames[texIndex]);
		}

		if (this.graphical) {
			gl.bindRenderbuffer(gl.RENDERBUFFER, null);
			gl.bindFramebuffer(gl.FRAMEBUFFER, null);
			gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
			return;
		}

		gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer);
		//the call to this._addArgument may rewrite the outputTexture, keep this here
		const outputTexture = this.outputTexture;
		gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, outputTexture, 0);

		if (this.subKernelOutputTextures !== null) {
			for (let i = 0; i < this.subKernelOutputTextures.length; i++) {
				const subKernelOutputTexture = this.subKernelOutputTextures[i];
				gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i + 1, gl.TEXTURE_2D, subKernelOutputTexture, 0);
			}
			this.ext.drawBuffersWEBGL(this.extDrawBuffersMap);
		}

		gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);

		if (this.subKernelOutputTextures !== null) {
			if (this.subKernels !== null) {
				const output = [];
				output.result = this.renderOutput(outputTexture);
				for (let i = 0; i < this.subKernels.length; i++) {
					output.push(new Texture(this.subKernelOutputTextures[i], texSize, this.output, this._webGl));
				}
				return output;
			} else if (this.subKernelProperties !== null) {
				const output = {
					result: this.renderOutput(outputTexture)
				};
				let i = 0;
				for (let p in this.subKernelProperties) {
					if (!this.subKernelProperties.hasOwnProperty(p)) continue;
					output[p] = new Texture(this.subKernelOutputTextures[i], texSize, this.output, this._webGl);
					i++;
				}
				return output;
			}
		}

		return this.renderOutput(outputTexture);
	}

	/**
	 * @memberOf WebGLKernel#
	 * @function
	 * @name renderOutput
	 *
	 *
	 * @desc Helper function to return webGl function's output.
	 * Since the program runs on GPU, we need to get the
	 * output of the program back to CPU and then return them.
	 *
	 * *Note*: This should not be called directly.
	 *
	 * @param {Object} outputTexture - Output Texture returned by webGl program
	 *
	 * @returns {Object|Array} result
	 *
	 *
	 */
	renderOutput(outputTexture) {
		const texSize = this.texSize;
		const gl = this._webGl;
		const threadDim = this.threadDim;
		const output = this.output;
		if (this.outputToTexture) {
			return new Texture(outputTexture, texSize, output, this._webGl);
		} else {
			let result;
			if (this.floatOutput) {
				result = new Float32Array(texSize[0] * texSize[1] * 4);
				gl.readPixels(0, 0, texSize[0], texSize[1], gl.RGBA, gl.FLOAT, result);
			} else {
				const bytes = new Uint8Array(texSize[0] * texSize[1] * 4);
				gl.readPixels(0, 0, texSize[0], texSize[1], gl.RGBA, gl.UNSIGNED_BYTE, bytes);
				result = new Float32Array(bytes.buffer);
			}

			result = result.subarray(0, threadDim[0] * threadDim[1] * threadDim[2]);

			if (output.length === 1) {
				return result;
			} else if (output.length === 2) {
				return utils.splitArray(result, output[0]);
			} else if (output.length === 3) {
				const cube = utils.splitArray(result, output[0] * output[1]);
				return cube.map(function(x) {
					return utils.splitArray(x, output[0]);
				});
			}
		}
	}

	/**
	 * @memberOf WebGLKernel#
	 * @function
	 * @name getOutputTexture
	 *
	 * @desc This uses *getTextureCache* to get the Texture Cache of the Output
	 *
	 * @returns {Object} Ouptut Texture Cache
	 *
	 */
	getOutputTexture() {
		return this.getTextureCache('OUTPUT');
	}

	/**
	 * @memberOf WebGLKernel#
	 * @function
	 * @name detachOutputTexture
	 *
	 * @desc Detaches output texture
	 *
	 *
	 */
	detachOutputTexture() {
		this.detachTextureCache('OUTPUT');
	}

	/**
	 * @memberOf WebGLKernel#
	 * @function
	 * @name setupOutputTexture
	 *
	 * @desc Detaches a texture from cache if exists, and sets up output texture
	 */
	setupOutputTexture() {
		const gl = this._webGl;
		const texSize = this.texSize;
		this.detachOutputTexture();
		this.outputTexture = this.getOutputTexture();
		gl.activeTexture(gl.TEXTURE0 + this.paramNames.length);
		gl.bindTexture(gl.TEXTURE_2D, this.outputTexture);
		gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
		gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
		gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
		gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
		if (this.floatOutput) {
			gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, texSize[0], texSize[1], 0, gl.RGBA, gl.FLOAT, null);
		} else {
			gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, texSize[0], texSize[1], 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
		}
	}

	/**
	 * @memberOf WebGLKernel#
	 * @function
	 * @name getArgumentTexture
	 *
	 * @desc This uses *getTextureCache** to get the Texture Cache of the argument supplied
	 *
	 * @param {String} name - Name of the argument
	 *
	 * 	Texture cache for the supplied argument
	 *
	 */
	getArgumentTexture(name) {
		return this.getTextureCache(`ARGUMENT_${ name }`);
	}

	/**
	 * @memberOf WebGLKernel#
	 * @name getSubKernelTexture
	 * @function
	 *
	 * @desc This uses *getTextureCache* to get the Texture Cache of the sub-kernel
	 *
	 * @param {String} name - Name of the subKernel
	 *
	 * @returns {Object} Texture cache for the subKernel
	 *
	 */
	getSubKernelTexture(name) {
		return this.getTextureCache(`SUB_KERNEL_${ name }`);
	}

	/**
	 * @memberOf WebGLKernel#
	 * @name getTextureCache
	 * @function
	 *
	 * @desc Returns the Texture Cache of the supplied parameter (can be kernel, sub-kernel or argument)
	 *
	 * @param {String} name - Name of the subkernel, argument, or kernel.
	 *
	 * @returns {Object} Texture cache
	 *
	 */
	getTextureCache(name) {
		if (this.outputToTexture) {
			// Don't retain a handle on the output texture, we might need to render on the same texture later
			return this._webGl.createTexture();
		}
		if (this.textureCache.hasOwnProperty(name)) {
			return this.textureCache[name];
		}
		return this.textureCache[name] = this._webGl.createTexture();
	}

	/**
	 * @memberOf WebGLKernel#
	 * @name detachTextureCache
	 * @function
	 * @desc removes a texture from the kernel's cache
	 * @param {String} name - Name of texture
	 */
	detachTextureCache(name) {
		delete this.textureCache[name];
	}

	/**
	 * @memberOf WebGLKernel#
	 * @function
	 * @name setupParams
	 *
	 * @desc Setup the parameter types for the parameters
	 * supplied to the Kernel function
	 *
	 * @param {Array} args - The actual parameters sent to the Kernel
	 *
	 */
	setupParams(args) {
		const paramTypes = this.paramTypes = [];
		for (let i = 0; i < args.length; i++) {
			const param = args[i];
			const paramType = utils.getArgumentType(param);
			paramTypes.push(paramType);
		}
	}

	/**
	 * @memberOf WebGLKernel#
	 * @function
	 * @name getUniformLocation
	 *
	 * @desc Return WebGlUniformLocation for various variables
	 * related to webGl program, such as user-defiend variables,
	 * as well as, dimension sizes, etc.
	 *
	 */
	getUniformLocation(name) {
		let location = this.programUniformLocationCache[name];
		if (!location) {
			location = this._webGl.getUniformLocation(this.program, name);
			this.programUniformLocationCache[name] = location;
		}
		return location;
	}

	/**
	 * @memberOf WebGLKernel#
	 * @function
	 * @name _getFragShaderArtifactMap
	 *
	 * @desc Generate Shader artifacts for the kernel program.
	 * The final object contains HEADER, KERNEL, MAIN_RESULT, and others.
	 *
	 * @param {Array} args - The actual parameters sent to the Kernel
	 *
	 * @returns {Object} An object containing the Shader Artifacts(CONSTANTS, HEADER, KERNEL, etc.)
	 *
	 */
	_getFragShaderArtifactMap(args) {
		return {
			HEADER: this._getHeaderString(),
			LOOP_MAX: this._getLoopMaxString(),
			CONSTANTS: this._getConstantsString(),
			DECODE32_ENDIANNESS: this._getDecode32EndiannessString(),
			ENCODE32_ENDIANNESS: this._getEncode32EndiannessString(),
			GET_WRAPAROUND: this._getGetWraparoundString(),
			GET_TEXTURE_CHANNEL: this._getGetTextureChannelString(),
			GET_TEXTURE_INDEX: this._getGetTextureIndexString(),
			GET_RESULT: this._getGetResultString(),
			MAIN_PARAMS: this._getMainParamsString(args),
			MAIN_CONSTANTS: this._getMainConstantsString(),
			KERNEL: this._getKernelString(),
			MAIN_RESULT: this._getMainResultString()
		};
	}

	/**
	 * @memberOf WebGLKernel#
	 * @function
	 * @name _addArgument
	 *
	 * @desc Adds kernel parameters to the Argument Texture,
	 * binding it to the webGl instance, etc.
	 *
	 * @param {Array|Texture|Number} value - The actual argument supplied to the kernel
	 * @param {String} type - Type of the argument
	 * @param {String} name - Name of the argument
	 *
	 */
	_addArgument(value, type, name) {
		const gl = this._webGl;
		const argumentTexture = this.getArgumentTexture(name);
		if (value instanceof Texture) {
			type = 'Texture';
		}
		switch (type) {
			case 'Array':
				{
					const dim = utils.getDimensions(value, true);
					const size = utils.dimToTexSize({
						floatTextures: this.floatTextures,
						floatOutput: this.floatOutput
					}, dim);
					gl.activeTexture(gl.TEXTURE0 + this.argumentsLength);
					gl.bindTexture(gl.TEXTURE_2D, argumentTexture);
					gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
					gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
					gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
					gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);

					let length = size[0] * size[1];
					if (this.floatTextures) {
						length *= 4;
					}

					const valuesFlat = new Float32Array(length);
					utils.flattenTo(value, valuesFlat);

					let buffer;
					if (this.floatTextures) {
						buffer = new Float32Array(valuesFlat);
						gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, size[0], size[1], 0, gl.RGBA, gl.FLOAT, buffer);
					} else {
						buffer = new Uint8Array((new Float32Array(valuesFlat)).buffer);
						gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, size[0], size[1], 0, gl.RGBA, gl.UNSIGNED_BYTE, buffer);
					}

					const loc = this.getUniformLocation('user_' + name);
					const locSize = this.getUniformLocation('user_' + name + 'Size');
					const dimLoc = this.getUniformLocation('user_' + name + 'Dim');

					if (!this.hardcodeConstants) {
						gl.uniform3fv(dimLoc, dim);
						gl.uniform2fv(locSize, size);
					}
					gl.uniform1i(loc, this.argumentsLength);
					break;
				}
			case 'Number':
				{
					const loc = this.getUniformLocation('user_' + name);
					gl.uniform1f(loc, value);
					break;
				}
			case 'Texture':
				{
					const inputTexture = value;
					const dim = utils.getDimensions(inputTexture.output, true);
					const size = inputTexture.size;

					if (inputTexture.texture === this.outputTexture) {
						this.setupOutputTexture();
					}

					gl.activeTexture(gl.TEXTURE0 + this.argumentsLength);
					gl.bindTexture(gl.TEXTURE_2D, inputTexture.texture);

					const loc = this.getUniformLocation('user_' + name);
					const locSize = this.getUniformLocation('user_' + name + 'Size');
					const dimLoc = this.getUniformLocation('user_' + name + 'Dim');

					gl.uniform3fv(dimLoc, dim);
					gl.uniform2fv(locSize, size);
					gl.uniform1i(loc, this.argumentsLength);
					break;
				}
			default:
				throw 'Input type not supported (WebGL): ' + value;
		}
		this.argumentsLength++;
	}

	/**
	 * @memberOf WebGLKernel#
	 * @function
	 * @name _getHeaderString
	 *
	 * @desc Get the header string for the program.
	 * This returns an empty string if no sub-kernels are defined.
	 *
	 * @returns {String} result
	 *
	 */
	_getHeaderString() {
		return (
			this.subKernels !== null || this.subKernelProperties !== null ?
			//webgl2 '#version 300 es\n' :
			'#extension GL_EXT_draw_buffers : require\n' :
			''
		);
	}

	/**
	 * @memberOf WebGLKernel#
	 * @function
	 * @name _getLoopMaxString
	 *
	 * @desc Get the maximum loop size String.
	 *
	 * @returns {String} result
	 *
	 */
	_getLoopMaxString() {
		return (
			this.loopMaxIterations ?
			` ${ parseInt(this.loopMaxIterations) }.0;\n` :
			' 100.0;\n'
		);
	}

	/**
	 * @memberOf WebGLKernel#
	 * @function
	 * @name _getConstantsString
	 *
	 * @desc Generate transpiled glsl Strings for constant parameters sent to a kernel
	 *
	 * They can be defined by *hardcodeConstants*
	 *
	 * @returns {String} result
	 *
	 */
	_getConstantsString() {
		const result = [];
		const threadDim = this.threadDim;
		const texSize = this.texSize;
		if (this.hardcodeConstants) {
			result.push(
				`highp vec3 uOutputDim = vec3(${ threadDim[0] },${ threadDim[1] }, ${ threadDim[2] })`,
				`highp vec2 uTexSize = vec2(${ texSize[0] }, ${ texSize[1] })`
			);
		} else {
			result.push(
				'uniform highp vec3 uOutputDim',
				'uniform highp vec2 uTexSize'
			);
		}

		return this._linesToString(result);
	}

	/**
	 * @memberOf WebGLKernel#
	 * @function
	 * @name _getTextureCoordinate
	 *
	 * @desc Get texture coordinate string for the program
	 *
	 * @returns {String} result
	 *
	 */
	_getTextureCoordinate() {
		const names = this.subKernelOutputVariableNames;
		if (names === null || names.length < 1) {
			return 'varying highp vec2 vTexCoord;\n';
		} else {
			return 'out highp vec2 vTexCoord;\n';
		}
	}

	/**
	 * @memberOf WebGLKernel#
	 * @function
	 * @name _getDecode32EndiannessString
	 *
	 * @desc Get Decode32 endianness string for little-endian and big-endian
	 *
	 * @returns {String} result
	 *
	 */
	_getDecode32EndiannessString() {
		return (
			this.endianness === 'LE' ?
			'' :
			'  rgba.rgba = rgba.abgr;\n'
		);
	}

	/**
	 * @memberOf WebGLKernel#
	 * @function
	 * @name _getEncode32EndiannessString
	 *
	 * @desc Get Encode32 endianness string for little-endian and big-endian
	 *
	 * @returns {String} result
	 *
	 */
	_getEncode32EndiannessString() {
		return (
			this.endianness === 'LE' ?
			'' :
			'  rgba.rgba = rgba.abgr;\n'
		);
	}

	/**
	 * @function
	 * @memberOf WebGLKernel#
	 * @name _getGetWraparoundString
	 *
	 * @returns {String} wraparound string
	 */
	_getGetWraparoundString() {
		return (
			this.wraparound ?
			'  xyz = mod(xyz, texDim);\n' :
			''
		);
	}

	/**
	 * @memberOf WebGLKernel#
	 * @function
	 * @name _getGetTextureChannelString
	 *
	 */
	_getGetTextureChannelString() {
		if (!this.floatTextures) return '';

		return this._linesToString([
			'  int channel = int(integerMod(index, 4.0))',
			'  index = float(int(index) / 4)'
		]);
	}

	/**
	 * @memberOf WebGLKernel#
	 * @function
	 * @name _getGetTextureIndexString
	 *
	 * @desc Get generic texture index string, if floatTextures flag is true.
	 *
	 * @example
	 * '  index = float(int(index)/4);\n'
	 *
	 */
	_getGetTextureIndexString() {
		return (
			this.floatTextures ?
			'  index = float(int(index)/4);\n' :
			''
		);
	}

	/**
	 * @memberOf WebGLKernel#
	 * @function
	 * @name _getGetResultString
	 *
	 */
	_getGetResultString() {
		if (!this.floatTextures) return '  return decode32(texel);\n';
		return this._linesToString([
			'  if (channel == 0) return texel.r',
			'  if (channel == 1) return texel.g',
			'  if (channel == 2) return texel.b',
			'  if (channel == 3) return texel.a'
		]);
	}

	/**
	 * @memberOf WebGLKernel#
	 * @function
	 * @name _getMainParamsString
	 *
	 * @desc Generate transpiled glsl Strings for user-defined parameters sent to a kernel
	 *
	 * @param {Array} args - The actual parameters sent to the Kernel
	 *
	 * @returns {String} result
	 *
	 */
	_getMainParamsString(args) {
		const result = [];
		const paramTypes = this.paramTypes;
		const paramNames = this.paramNames;
		for (let i = 0; i < paramNames.length; i++) {
			const param = args[i];
			const paramName = paramNames[i];
			const paramType = paramTypes[i];
			if (this.hardcodeConstants) {
				if (paramType === 'Array' || paramType === 'Texture') {
					const paramDim = utils.getDimensions(param, true);
					const paramSize = utils.dimToTexSize({
						floatTextures: this.floatTextures,
						floatOutput: this.floatOutput
					}, paramDim);

					result.push(
						`uniform highp sampler2D user_${ paramName }`,
						`highp vec2 user_${ paramName }Size = vec2(${ paramSize[0] }.0, ${ paramSize[1] }.0)`,
						`highp vec3 user_${ paramName }Dim = vec3(${ paramDim[0] }.0, ${ paramDim[1]}.0, ${ paramDim[2] }.0)`
					);
				} else if (paramType === 'Number' && Number.isInteger(param)) {
					result.push(`highp float user_${ paramName } = ${ param }.0`);
				} else if (paramType === 'Number') {
					result.push(`highp float user_${ paramName } = ${ param }`);
				}
			} else {
				if (paramType === 'Array' || paramType === 'Texture') {
					result.push(
						`uniform highp sampler2D user_${ paramName }`,
						`uniform highp vec2 user_${ paramName }Size`,
						`uniform highp vec3 user_${ paramName }Dim`
					);
				} else if (paramType === 'Number') {
					result.push(`uniform highp float user_${ paramName }`);
				}
			}
		}
		return this._linesToString(result);
	}

	/**
	 * @memberOf WebGLKernel#
	 * @function
	 * @name _getMainConstantsString
	 *
	 */
	_getMainConstantsString() {
		const result = [];
		if (this.constants) {
			for (let name in this.constants) {
				if (!this.constants.hasOwnProperty(name)) continue;
				let value = parseFloat(this.constants[name]);

				if (Number.isInteger(value)) {
					result.push('const float constants_' + name + ' = ' + parseInt(value) + '.0');
				} else {
					result.push('const float constants_' + name + ' = ' + parseFloat(value));
				}
			}
		}
		return this._linesToString(result);
	}

	/**
	 * @memberOf WebGLKernel#
	 * @function
	 * @name _getKernelString
	 *
	 * @desc Get Kernel program string (in *glsl*) for a kernel.
	 *
	 * @returns {String} result
	 *
	 */
	_getKernelString() {
		const result = [];
		const names = this.subKernelOutputVariableNames;
		if (names !== null) {
			result.push('highp float kernelResult = 0.0');
			for (let i = 0; i < names.length; i++) {
				result.push(
					`highp float ${ names[i] } = 0.0`
				);
			}

			/* this is v2 prep
      result.push('highp float kernelResult = 0.0');
			result.push('layout(location = 0) out highp float fradData0 = 0.0');
			for (let i = 0; i < names.length; i++) {
				result.push(
          `highp float ${ names[i] } = 0.0`,
				  `layout(location = ${ i + 1 }) out highp float fragData${ i + 1 } = 0.0`
        );
			}*/
		} else {
			result.push('highp float kernelResult = 0.0');
		}

		return this._linesToString(result) + this.functionBuilder.getPrototypeString('kernel');
	}

	/**
	 *
	 * @memberOf WebGLKernel#
	 * @function
	 * @name _getMainResultString
	 *
	 * @desc Get main result string with checks for floatOutput, graphical, subKernelsOutputs, etc.
	 *
	 * @returns {String} result
	 *
	 */
	_getMainResultString() {
		const names = this.subKernelOutputVariableNames;
		const result = [];
		if (this.floatOutput) {
			result.push('  index *= 4.0');
		}

		if (this.graphical) {
			result.push(
				'  threadId = indexTo3D(index, uOutputDim)',
				'  kernel()',
				'  gl_FragColor = actualColor'
			);
		} else if (this.floatOutput) {
			result.push(
				'  threadId = indexTo3D(index, uOutputDim)',
				'  kernel()',
				'  gl_FragColor.r = kernelResult',
				'  index += 1.0',
				'  threadId = indexTo3D(index, uOutputDim)',
				'  kernel()',
				'  gl_FragColor.g = kernelResult',
				'  index += 1.0',
				'  threadId = indexTo3D(index, uOutputDim)',
				'  kernel()',
				'  gl_FragColor.b = kernelResult',
				'  index += 1.0',
				'  threadId = indexTo3D(index, uOutputDim)',
				'  kernel()',
				'  gl_FragColor.a = kernelResult'
			);
		} else if (names !== null) {
			result.push('  threadId = indexTo3D(index, uOutputDim)');
			result.push('  kernel()');
			result.push('  gl_FragData[0] = encode32(kernelResult)');
			for (let i = 0; i < names.length; i++) {
				result.push(`  gl_FragData[${ i + 1 }] = encode32(${ names[i] })`);
			}
			/* this is v2 prep
       * result.push('  kernel()');
			result.push('  fragData0 = encode32(kernelResult)');
			for (let i = 0; i < names.length; i++) {
				result.push(`  fragData${ i + 1 } = encode32(${ names[i] })`);
			}*/
		} else {
			result.push(
				'  threadId = indexTo3D(index, uOutputDim)',
				'  kernel()',
				'  gl_FragColor = encode32(kernelResult)'
			);
		}

		return this._linesToString(result);
	}

	/**
	 * @memberOf WebGLKernel#
	 * @function
	 * @name _linesToString
	 *
	 * @param {Array} lines - An Array of strings
	 *
	 * @returns {String} Single combined String, seperated by *\n*
	 *
	 */
	_linesToString(lines) {
		if (lines.length > 0) {
			return lines.join(';\n') + ';\n';
		} else {
			return '\n';
		}
	}

	/**
	 * @memberOf WebGLKernel#
	 * @function
	 * @name _replaceArtifacts
	 *
	 * @param {String} src - Shader string
	 * @param {Array} map - Variables/Constants associated with shader
	 *
	 */
	_replaceArtifacts(src, map) {
		return src.replace(/[ ]*__([A-Z]+[0-9]*([_]?[A-Z])*)__;\n/g, (match, artifact) => {
			if (map.hasOwnProperty(artifact)) {
				return map[artifact];
			}
			throw `unhandled artifact ${ artifact }`;
		});
	}

	/**
	 * @memberOf WebGLKernel#
	 * @function
	 * @name _addKernels
	 *
	 * @desc Adds all the sub-kernels supplied with this Kernel instance.
	 *
	 */
	_addKernels() {
		const builder = this.functionBuilder;
		const gl = this._webGl;

		builder.addFunctions(this.functions);
		builder.addNativeFunctions(this.nativeFunctions);

		builder.addKernel(this.fnString, {
			prototypeOnly: false,
			constants: this.constants,
			debug: this.debug,
			loopMaxIterations: this.loopMaxIterations
		}, this.paramNames, this.paramTypes);

		if (this.subKernels !== null) {
			const ext = this.ext = gl.getExtension('WEBGL_draw_buffers');
			if (!ext) throw new Error('could not instantiate draw buffers extension');
			this.subKernelOutputTextures = [];
			this.subKernelOutputVariableNames = [];
			for (let i = 0; i < this.subKernels.length; i++) {
				const subKernel = this.subKernels[i];
				builder.addSubKernel(subKernel, {
					prototypeOnly: false,
					constants: this.constants,
					debug: this.debug,
					loopMaxIterations: this.loopMaxIterations
				});
				this.subKernelOutputTextures.push(this.getSubKernelTexture(i));
				this.subKernelOutputVariableNames.push(subKernel.name + 'Result');
			}

		} else if (this.subKernelProperties !== null) {
			const ext = this.ext = gl.getExtension('WEBGL_draw_buffers');
			if (!ext) throw new Error('could not instantiate draw buffers extension');
			this.subKernelOutputTextures = [];
			this.subKernelOutputVariableNames = [];
			let i = 0;
			for (let p in this.subKernelProperties) {
				if (!this.subKernelProperties.hasOwnProperty(p)) continue;
				const subKernel = this.subKernelProperties[p];
				builder.addSubKernel(subKernel, {
					prototypeOnly: false,
					constants: this.constants,
					debug: this.debug,
					loopMaxIterations: this.loopMaxIterations
				});
				this.subKernelOutputTextures.push(this.getSubKernelTexture(p));
				this.subKernelOutputVariableNames.push(subKernel.name + 'Result');
				i++;
			}
		}
	}

	/**
	 * @memberOf WebGLKernel#
	 * @function
	 * @name _getFragShaderString
	 *
	 * @desc Get the fragment shader String.
	 * If the String hasn't been compiled yet,
	 * then this method compiles it as well
	 *
	 * @param {Array} args - The actual parameters sent to the Kernel
	 *
	 * @returns {String} Fragment Shader string
	 *
	 */
	_getFragShaderString(args) {
		if (this.compiledFragShaderString !== null) {
			return this.compiledFragShaderString;
		}
		return this.compiledFragShaderString = this._replaceArtifacts(fragShaderString, this._getFragShaderArtifactMap(args));
	}

	/**
	 * @memberOf WebGLKernel#
	 * @function
	 * @name _getVertShaderString
	 *
	 * @desc Get the vertical shader String
	 *
	 * @param {Array} args - The actual parameters sent to the Kernel
	 *
	 * @returns {String} Vertical Shader string
	 *
	 */
	_getVertShaderString(args) {
		if (this.compiledVertShaderString !== null) {
			return this.compiledVertShaderString;
		}
		//TODO: webgl2 compile like frag shader
		return this.compiledVertShaderString = vertShaderString;
	}

	/**
	 * @memberOf WebGLKernel#
	 * @function
	 * @name toString
	 *
	 * @desc Returns the *pre-compiled* Kernel as a JS Object String, that can be reused.
	 *
	 */
	toString() {
		return kernelString(this);
	}

	addFunction(fn) {
		this.functionBuilder.addFunction(null, fn);
	}

	addNativeFunction(name, source) {
		this.functionBuilder.addNativeFunction(name, source);
	}
};


text:
title:  "Quick guide to solving problems based on Bit Manipulation"
date:   2017-01-27 15:04:23
categories: [Programming]
tags: [Programming]
---

Below, I have compiled a 2- minute quick read for solving programming challenges based on Bit Manipulation.

* The bitwise XOR of numbers which occur even number of times will always be zero.

* To find the number of set bits in a number X, bitwise AND X and X -- 1. The number of times this operation is successful gives the number of set bits.

* To get the number of Most Significant Bits (MSB) common to two given numbers, apply bitwise XOR operation. The number of zeroes from the right gives the required result. To find this count of common bits, you can bitwise LEFT SHIFT the result of the XOR operation until the number becomes equal to zero.

* Left shift is equivalent to multiplying the bit pattern with 2^k. Right shift is equivalent to dividing the bit pattern with 2^k. (Here, k denotes the number of bits shifted left/ right.)

* To check if a number X is power of 2, calculate bitwise AND of X and X -- 1. If the result is zero, it indicates that the given number is a power of 2.

[Source code](https://github.com/Diksha-Rathi/Competitive-Programming/tree/master/Algorithms/Bit%20Manipulation) to my submissions of related problems from [HackerRank](https://www.hackerrank.com/domains/algorithms/bit-manipulation/) and [HackerEarth](https://www.hackerearth.com/practice/basic-programming/bit-manipulation/basics-of-bit-manipulation/practice-problems/).

redpajama_set_name: RedPajamaGithub


text:
import RPi.GPIO as GPIO
import MFRC522
import signal
#import hashlib  future function on using hashes.. must be man made

#set Variables
continue_reading = True
tag_a1 = 83
tag_b1 = 00
tag_master = 255

# ****** Functions
# Function to check the tag encoding after existance check
# It will ingest the whole raw sector of 16 bytes
def tag_encode_ok( raw ):
   result = ( raw[1] + raw[2] + raw[3] ) - raw[15] - raw[0]
   return result;

# Function to check the tag encoding after existance check
def tag_whois( id_nr ):
   if id_nr == tag_a1:
   	whois = "tag a1"
   elif id_nr == tag_b1:
   	whois = "tag b1"
   elif id_nr == tag_master:
	print "Masterkey.. open all doors?"
	whois = "master tag"
   else:
	whois = "UNKNOWN CARD.. INTRUDER ALERT??"
   return whois;

# ******* Onetime stuff
# Set up phase - Capture SIGINT for cleanup when the script is aborted
def end_read(signal,frame):
    global continue_reading
    print " .. aha.. Ctrl+C captured, ending read."
    continue_reading = False
    GPIO.cleanup()
# Hook the SIGINT
signal.signal(signal.SIGINT, end_read)

# ******* MAIN
# Start of main loop
print "House Guard Active - Present card to enter..."

# Create an object of the class MFRC522
MIFAREReader = MFRC522.MFRC522()

# This loop keeps checking for chips. If one is near it will get the UID and authenticate
while continue_reading:

    # Scan for cards
    (status,TagType) = MIFAREReader.MFRC522_Request(MIFAREReader.PICC_REQIDL)

    # If a card is found
    if status == MIFAREReader.MI_OK:
        print "Card detected"

    # Get the UID of the card
    (status,uid) = MIFAREReader.MFRC522_Anticoll()

    # If we have the UID, continue
    if status == MIFAREReader.MI_OK:

        # Print UID
        print "Card read UID: "+str(uid[0])+","+str(uid[1])+","+str(uid[2])+","+str(uid[3])

        # This is the default key for authentication
        key = [0xFF,0xFF,0xFF,0xFF,0xFF,0xFF]

        # Select the scanned tag
        MIFAREReader.MFRC522_SelectTag(uid)

        # Dump the data
        #MIFAREReader.MFRC522_DumpClassic1K(key, uid)

        # Authenticate for sector 8
        status = MIFAREReader.MFRC522_Auth(MIFAREReader.PICC_AUTHENT1A, 8, key, uid)

        # Check if authenticated
        if status == MIFAREReader.MI_OK:
            #MIFAREReader.MFRC522_Read(8)
	    (rawsector) = MIFAREReader.MFRC522_ReadSector(8)
            MIFAREReader.MFRC522_StopCrypto1()
	    print "Raw Sector "+str(rawsector)
	    sectorlength=len(rawsector)
	    for i in range(0,sectorlength):
		print rawsector[i]
	    print rawsector
        else:
            print "Authentication error"

        # ******* Check tag-id and encoding
	name = tag_whois( rawsector[0] )
	print name
	checkresult = tag_encode_ok( rawsector )
	print checkresult

	#perform state changes here for team A and team B
	#print on display and go into wait loop

        # wait card removed
        print "--- Remove Card ---"
        card_removed = False
        card_removed_counter = 5
        while not card_removed:
            (status,TagType) = MIFAREReader.MFRC522_Request(MIFAREReader.PICC_REQIDL)
            if status != MIFAREReader.MI_OK:
                card_removed_counter = card_removed_counter-1
                if card_removed_counter==0:
                    card_removed = True
            else:
                card_removed_counter = 5
        print "--- Card removed---"
        print "Place card again please..."


text:
import springies.Springies;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import javax.swing.JFrame;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;

/**
 * Creates window that can be moved, resized, and closed by the user.
 *
 * @author Robert C. Duvall
 */
public class Main
{
    // constants
    public static final Dimension SIZE = new Dimension(800, 600);
    public static final String TITLE = "Springies!";

    /**
     * main --- where the program starts
     *
     * @param args
     * @throws IOException
     * @throws SAXException
     * @throws ParserConfigurationException
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     * @throws InstantiationException
     * @throws NoSuchMethodException
     * @throws IllegalArgumentException
     * @throws SecurityException
     */
    public static void main (String args[]) throws ParserConfigurationException, SAXException, IOException, SecurityException, IllegalArgumentException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException
    {
        // view of user's content
        final Springies sp = new Springies();
        // container that will work with user's OS
        JFrame frame = new JFrame(TITLE);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        // add our user interface components
        frame.getContentPane().add(sp, BorderLayout.CENTER);

        // display them
        frame.pack();
        frame.setVisible(true);

    }

}


text:
/*

 Tests for the static functions used in `gpii.pouch.express`.

 */
/* eslint-env node */
"use strict";
var fluid =  require("infusion");
var jqUnit = require("node-jqunit");
var gpii   = fluid.registerNamespace("gpii");

require("../../../");

fluid.registerNamespace("gpii.tests.pouchdb.express");

gpii.tests.pouchdb.express.testDbDefExpansion = function (testDef) {
    jqUnit.test(testDef.name, function () {
        jqUnit.assertDeepEq("The output should be as expected...", testDef.expected, gpii.pouch.express.expandDbDef(testDef.input));
    });
};

fluid.defaults("gpii.tests.pouchdb.express", {
    gradeNames: ["fluid.component"],
    dbDefExpansionTests: {
        objectSinglePath: {
            name:     "An object with a single path should be expanded correctly...",
            input:    { data: "/tmp/foo"},
            expected: { data: ["/tmp/foo"]}
        },
        objectMultiplePaths: {
            name:     "An object with an array of paths should be expanded correctly...",
            input:    { data: ["/tmp/foo", "/tmp/bar"]},
            expected: { data: ["/tmp/foo", "/tmp/bar"]}
        },
        objectWithDataAndCustomOptions: {
            name:     "An object with data and custom options should be expanded correctly...",
            input:    { data: "/tmp/foo", custom: true},
            expected: { data: ["/tmp/foo"], custom: true}
        },
        objectWithOnlyCustomOptions: {
            name:     "An object with data and custom options should be expanded correctly...",
            input:    { custom: true },
            expected: { custom: true }
        },
        emptyObject: {
            name:     "An object with data and custom options should be expanded correctly...",
            input:    {},
            expected: {}
        },
        undefined: {
            name:     "An undefined value should be expanded correctly...",
            input:    undefined,
            expected: {}
        },
        null: {
            name:     "A null value should be expanded correctly...",
            input:    null,
            expected: {}
        },
        true: {
            name:     "A boolean `true` should be expanded correctly...",
            input:    true,
            expected: {}
        },
        false: {
            name:     "A boolean `false` should be expanded correctly...",
            input:    false,
            expected: {}
        }
    },
    listeners: {
        "onCreate.announceModule": {
            funcName: "jqUnit.module",
            args:     ["Testing static functions used in `gpii.pouch.express`..."]
        },
        "onCreate.runDbDefExpansionTests": {
            priority: "after:announceModule",
            funcName: "fluid.each",
            args:     ["{that}.options.dbDefExpansionTests", gpii.tests.pouchdb.express.testDbDefExpansion]
        }
    }
});

gpii.tests.pouchdb.express();


text:
namespace CampBg.Web.Infrastructure
{
    using System;
    using System.Globalization;
    using System.Web.Mvc;

    public class DecimalModelBinder : IModelBinder
    {
        public object BindModel(ControllerContext controllerContext,
            ModelBindingContext bindingContext)
        {
            object result = null;

            string modelName = bindingContext.ModelName;
            string attemptedValue =
                bindingContext.ValueProvider.GetValue(modelName).AttemptedValue;

            string wantedSeperator = NumberFormatInfo.CurrentInfo.NumberDecimalSeparator;
            string alternateSeperator = (wantedSeperator == "," ? "." : ",");

            if (attemptedValue.IndexOf(wantedSeperator) == -1
                && attemptedValue.IndexOf(alternateSeperator) != -1)
            {
                attemptedValue =
                    attemptedValue.Replace(alternateSeperator, wantedSeperator);
            }

            try
            {
                if (bindingContext.ModelMetadata.IsNullableValueType
                    && string.IsNullOrWhiteSpace(attemptedValue))
                {
                    return null;
                }

                result = decimal.Parse(attemptedValue, NumberStyles.Any);
            }
            catch (FormatException e)
            {
                bindingContext.ModelState.AddModelError(modelName, e);
            }

            return result;
        }
    }
}


text:
#ifndef CODEEDITORTEST
#define CODEEDITORTEST

#include <memory>

#include <QTest>

#include "../src/CodeEditor.hpp"

/**
 * @brief The CodeEditor Testing class
 * @author Veit Heller(s0539501) & Tobias Brosge(s0539501)
 *
 * Tests the CodeEditor class; functionality tested includes
 * object creation and writing to the text editor.
 */
class CodeEditorTest : public QObject{
Q_OBJECT
private slots:
    void initTestCase() {
        codeEditor = std::unique_ptr<CodeEditor>(new CodeEditor());
    }
    void objectCreationTest(){
        QVERIFY(codeEditor.get());
    }
    void writingTest(){
        QTest::keyClicks(codeEditor.get(), "I am an int and that is code;");
        QCOMPARE(codeEditor->toPlainText(), QStringLiteral("I am an int and that is code;"));
    }
    void LineHighlightingTest(){
        QVERIFY(codeEditor->lineHighlightingWidth() == 10);
    }
private:
    std::unique_ptr<CodeEditor> codeEditor;
};
#endif // CODEEDITORTEST


text:
#ifndef __LL_MAP_H__
#define __LL_MAP_H__ 1

int ll_remember_index(const struct sockaddr_nl *who,
		      struct nlmsghdr *n, void *arg);

void ll_init_map(struct rtnl_handle *rth);
unsigned ll_name_to_index(const char *name);
const char *ll_index_to_name(unsigned idx);
const char *ll_idx_n2a(unsigned idx, char *buf);
int ll_index_to_type(unsigned idx);
int ll_index_to_flags(unsigned idx);
unsigned namehash(const char *str);

#endif /* __LL_MAP_H__ */


text:
package org.apache.druid.server;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableList;
import com.google.inject.Guice;
import com.google.inject.Injector;
import org.apache.druid.guice.PropertiesModule;
import org.apache.druid.initialization.DruidModule;
import org.apache.druid.initialization.ServerInjectorBuilderTest;
import org.apache.druid.java.util.common.StringUtils;
import org.junit.Assert;
import org.junit.Test;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.stream.Collectors;

public class StatusResourceTest
{
  @Test
  public void testLoadedModules()
  {

    Collection<DruidModule> modules = ImmutableList.of(new ServerInjectorBuilderTest.TestDruidModule());
    List<StatusResource.ModuleVersion> statusResourceModuleList = new StatusResource.Status(modules).getModules();

    Assert.assertEquals("Status should have all modules loaded!", modules.size(), statusResourceModuleList.size());

    for (DruidModule module : modules) {
      String moduleName = module.getClass().getName();

      boolean contains = Boolean.FALSE;
      for (StatusResource.ModuleVersion version : statusResourceModuleList) {
        if (version.getName().equals(moduleName)) {
          contains = Boolean.TRUE;
          break;
        }
      }
      Assert.assertTrue("Status resource should contain module " + moduleName, contains);
    }
  }

  @Test
  public void testHiddenProperties() throws Exception
  {
    testHiddenPropertiesWithPropertyFileName("status.resource.test.runtime.properties");
  }

  @Test
  public void testHiddenPropertiesContain() throws Exception
  {
    testHiddenPropertiesWithPropertyFileName("status.resource.test.runtime.hpc.properties");
  }

  private void testHiddenPropertiesWithPropertyFileName(String fileName) throws Exception
  {
    Injector injector = Guice.createInjector(Collections.singletonList(new PropertiesModule(Collections.singletonList(
        fileName))));
    Map<String, String> returnedProperties = injector.getInstance(StatusResource.class).getProperties();
    Set<String> lowerCasePropertyNames = returnedProperties.keySet()
                                                           .stream()
                                                           .map(StringUtils::toLowerCase)
                                                           .collect(Collectors.toSet());

    Assert.assertTrue(
        "The list of unfiltered Properties is not > the list of filtered Properties?!?",
        injector.getInstance(Properties.class).stringPropertyNames().size() > returnedProperties.size()
    );

    Set<String> hiddenProperties = new ObjectMapper().readValue(
        returnedProperties.get("druid.server.hiddenProperties"),
        new TypeReference<Set<String>>() {});

    hiddenProperties.forEach(
        (property) -> {
          lowerCasePropertyNames.forEach(
              lowerCasePropertyName -> Assert.assertFalse(lowerCasePropertyName.contains(StringUtils.toLowerCase(
                  property)))
          );
        }
    );
  }

}


text:
package rx.internal.operators;

import rx.*;
import rx.Observable.OnSubscribe;
import rx.Scheduler.Worker;
import rx.functions.Action0;

/**
 * Subscribes Observers on the specified {@code Scheduler}.
 *

 *
 *
 * @param <T> the value type of the actual source
 */
public final class OperatorSubscribeOn<T> implements OnSubscribe<T> {

    final Scheduler scheduler;
    final Observable<T> source;

    public OperatorSubscribeOn(Observable<T> source, Scheduler scheduler) {
        this.scheduler = scheduler;
        this.source = source;
    }

    @Override
    public void call(final Subscriber<? super T> subscriber) {
        final Worker inner = scheduler.createWorker();
        subscriber.add(inner);

        inner.schedule(new Action0() {
            @Override
            public void call() {
                final Thread t = Thread.currentThread();

                Subscriber<T> s = new Subscriber<T>(subscriber) {
                    @Override
                    public void onNext(T t) {
                        subscriber.onNext(t);
                    }

                    @Override
                    public void onError(Throwable e) {
                        try {
                            subscriber.onError(e);
                        } finally {
                            inner.unsubscribe();
                        }
                    }

                    @Override
                    public void onCompleted() {
                        try {
                            subscriber.onCompleted();
                        } finally {
                            inner.unsubscribe();
                        }
                    }

                    @Override
                    public void setProducer(final Producer p) {
                        subscriber.setProducer(new Producer() {
                            @Override
                            public void request(final long n) {
                                if (t == Thread.currentThread()) {
                                    p.request(n);
                                } else {
                                    inner.schedule(new Action0() {
                                        @Override
                                        public void call() {
                                            p.request(n);
                                        }
                                    });
                                }
                            }
                        });
                    }
                };

                source.unsafeSubscribe(s);
            }
        });
    }
}


text:
package alluxio.client.file.options;

import alluxio.CommonTestUtils;

import org.junit.Assert;
import org.junit.Test;

/**
 * Tests for the {@link RenameOptions} class.
 */
public final class RenameOptionsTest {
  @Test
  public void defaults() {
    RenameOptions options = RenameOptions.defaults();

    Assert.assertNotNull(options);
  }

  @Test
  public void equalsTest() throws Exception {
    CommonTestUtils.testEquals(RenameOptions.class);
  }
}


text:
require "abstract_unit"
require "pathname"
require "file_update_checker_shared_tests"

class EventedFileUpdateCheckerTest < ActiveSupport::TestCase
  include FileUpdateCheckerSharedTests

  def setup
    skip if ENV["LISTEN"] == "0"
    require "listen"
    super
  end

  def new_checker(files = [], dirs = {}, &block)
    ActiveSupport::EventedFileUpdateChecker.new(files, dirs, &block).tap do |c|
      wait
    end
  end

  def teardown
    super
    Listen.stop
  end

  def wait
    sleep 1
  end

  def touch(files)
    super
    wait # wait for the events to fire
  end

  test "notifies forked processes" do
    jruby_skip "Forking not available on JRuby"

    FileUtils.touch(tmpfiles)

    checker = new_checker(tmpfiles) {}
    assert !checker.updated?

    # Pipes used for flow control across fork.
    boot_reader,  boot_writer  = IO.pipe
    touch_reader, touch_writer = IO.pipe

    pid = fork do
      assert checker.updated?

      # Clear previous check value.
      checker.execute
      assert !checker.updated?

      # Fork is booted, ready for file to be touched
      # notify parent process.
      boot_writer.write("booted")

      # Wait for parent process to signal that file
      # has been touched.
      IO.select([touch_reader])

      assert checker.updated?
    end

    assert pid

    # Wait for fork to be booted before touching files.
    IO.select([boot_reader])
    touch(tmpfiles)

    # Notify fork that files have been touched.
    touch_writer.write("touched")

    assert checker.updated?

    Process.wait(pid)
  end
end

class EventedFileUpdateCheckerPathHelperTest < ActiveSupport::TestCase
  def pn(path)
    Pathname.new(path)
  end

  setup do
    @ph = ActiveSupport::EventedFileUpdateChecker::PathHelper.new
  end

  test "#xpath returns the expanded path as a Pathname object" do
    assert_equal pn(__FILE__).expand_path, @ph.xpath(__FILE__)
  end

  test "#normalize_extension returns a bare extension as is" do
    assert_equal "rb", @ph.normalize_extension("rb")
  end

  test "#normalize_extension removes a leading dot" do
    assert_equal "rb", @ph.normalize_extension(".rb")
  end

  test "#normalize_extension supports symbols" do
    assert_equal "rb", @ph.normalize_extension(:rb)
  end

  test "#longest_common_subpath finds the longest common subpath, if there is one" do
    paths = %w(
      /foo/bar
      /foo/baz
      /foo/bar/baz/woo/zoo
    ).map { |path| pn(path) }

    assert_equal pn("/foo"), @ph.longest_common_subpath(paths)
  end

  test "#longest_common_subpath returns the root directory as an edge case" do
    paths = %w(
      /foo/bar
      /foo/baz
      /foo/bar/baz/woo/zoo
      /wadus
    ).map { |path| pn(path) }

    assert_equal pn("/"), @ph.longest_common_subpath(paths)
  end

  test "#longest_common_subpath returns nil for an empty collection" do
    assert_nil @ph.longest_common_subpath([])
  end

  test "#existing_parent returns the most specific existing ascendant" do
    wd = Pathname.getwd

    assert_equal wd, @ph.existing_parent(wd)
    assert_equal wd, @ph.existing_parent(wd.join("non-existing/directory"))
    assert_equal pn("/"), @ph.existing_parent(pn("/non-existing/directory"))
  end

  test "#filter_out_descendants returns the same collection if there are no descendants (empty)" do
    assert_equal [], @ph.filter_out_descendants([])
  end

  test "#filter_out_descendants returns the same collection if there are no descendants (one)" do
    assert_equal ["/foo"], @ph.filter_out_descendants(["/foo"])
  end

  test "#filter_out_descendants returns the same collection if there are no descendants (several)" do
    paths = %w(
      /Rails.root/app/controllers
      /Rails.root/app/models
      /Rails.root/app/helpers
    ).map { |path| pn(path) }

    assert_equal paths, @ph.filter_out_descendants(paths)
  end

  test "#filter_out_descendants filters out descendants preserving order" do
    paths = %w(
      /Rails.root/app/controllers
      /Rails.root/app/controllers/concerns
      /Rails.root/app/models
      /Rails.root/app/models/concerns
      /Rails.root/app/helpers
    ).map { |path| pn(path) }

    assert_equal paths.values_at(0, 2, 4), @ph.filter_out_descendants(paths)
  end

  test "#filter_out_descendants works on path units" do
    paths = %w(
      /foo/bar
      /foo/barrrr
    ).map { |path| pn(path) }

    assert_equal paths, @ph.filter_out_descendants(paths)
  end

  test "#filter_out_descendants deals correctly with the root directory" do
    paths = %w(
      /
      /foo
      /foo/bar
    ).map { |path| pn(path) }

    assert_equal paths.values_at(0), @ph.filter_out_descendants(paths)
  end

  test "#filter_out_descendants preserves duplicates" do
    paths = %w(
      /foo
      /foo/bar
      /foo
    ).map { |path| pn(path) }

    assert_equal paths.values_at(0, 2), @ph.filter_out_descendants(paths)
  end
end


text:
if [ -f /etc/bird.conf ]; then
    BIRD_CONF=/etc/bird.conf
else
    BIRD_CONF=/etc/bird/bird.conf
fi

BIRD_CONF_TEMPLATE=/usr/share/calico/bird/calico-bird.conf.template

# Require 3 arguments.
[ $# -eq 3 ] || cat <<EOF

Usage: $0 <my-ip-address> <rr-ip-address> <as-number>

where
  <my-ip-address> is the external IP address of the local machine
  <rr-ip-address> is the IP address of the route reflector that
      the local BIRD should peer with
  <as-number> is the BGP AS number that the route relector is using.

Please specify exactly these 3 required arguments.

EOF
[ $# -eq 3 ] || exit -1

# Name the arguments.
my_ip_address=$1
rr_ip_address=$2
as_number=$3

# Generate BIRD config file.
mkdir -p $(dirname $BIRD_CONF)
sed -e "
s/@MY_IP_ADDRESS@/$my_ip_address/;
s/@RR_IP_ADDRESS@/$rr_ip_address/;
s/@AS_NUMBER@/$as_number/;
" < $BIRD_CONF_TEMPLATE > $BIRD_CONF

echo BIRD configuration generated at $BIRD_CONF

service bird restart
echo BIRD restarted


text:
require "google/cloud/speech/v1p1beta1"

##
# Example demonstrating basic usage of
# Google::Cloud::Speech::V1p1beta1::Adaptation::Client#update_phrase_set
#
def update_phrase_set
  # Create a client object. The client can be reused for multiple calls.
  client = Google::Cloud::Speech::V1p1beta1::Adaptation::Client.new

  # Create a request. To set request fields, pass in keyword arguments.
  request = Google::Cloud::Speech::V1p1beta1::UpdatePhraseSetRequest.new

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

  # The returned object is of type Google::Cloud::Speech::V1p1beta1::PhraseSet.
  p result
end
# [END speech_v1p1beta1_generated_Adaptation_UpdatePhraseSet_sync]


text:
package org.bouncycastle.openpgp.operator;

import org.bouncycastle.openpgp.PGPException;

public interface PublicKeyDataDecryptorFactory
    extends PGPDataDecryptorFactory
{
    public byte[] recoverSessionData(int keyAlgorithm, byte[][] secKeyData)
            throws PGPException;
}


text:
import sqlalchemy as sa

meta = sa.MetaData()

comments = sa.Table(
    'comments_comments', meta,
    sa.Column('id', sa.Integer, primary_key=True),
    sa.Column('content', sa.String, nullable=False),
)

comments_tree = sa.Table(
    'comments_tree', meta,
    sa.Column('id', sa.Integer, primary_key=True),
    sa.Column('ancestor_id', sa.Integer, sa.ForeignKey(comments.c.id), nullable=False),
    sa.Column('nearest_ancestor_id', sa.Integer, sa.ForeignKey(comments.c.id), nullable=False),
    sa.Column('descendant_id', sa.Integer, sa.ForeignKey(comments.c.id), nullable=False),
    sa.Column('depth', sa.Integer, nullable=False),
)


text:
package logic;

public interface MoveListener {

	void makeMove(CellWrapped cell);

}


text:
require 'elasticsearch'
require 'yaml'

client = Elasticsearch::Client.new host: 'localhost:9200', log: true

puts client.indices.get_settings(index: 'livedoor-gourmet').to_yaml
puts client.indices.get_mapping(index: 'livedoor-gourmet').to_yaml


text:
<!--
  Copyright 2015 The AMP HTML Authors. All Rights Reserved.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS-IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the license.
-->
<!--
  Test Description:
  Tests what happens when the custom style made by the author
  of the document contains things that we disallow.
-->
<!doctype html>
<html ⚡>
<head>
  <meta charset="utf-8">
  <link rel="canonical" href="./regular-html-version.html">
  <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no,minimal-ui">
  <style amp-custom>
    /* These CSS Rules violate essential CSS validation */
    @import url("http://somewhere/on/the/internet.css");
    foo.i-amp-class {}
    foo.amp-class {}
    foo { b: red !important; }
    @viewport (mumble mumble) { }
    @media (whatever) { @notallowednested }

    /* some tests for url verification - images */
    foo { background-image: url('') }  /* allowed for now */
    foo { background-image: url('invalid://invalid.com/1.jpg') }
    foo { background-image: url('https://valid.com/1.jpg') }
    foo { background-image: url('http://valid.com/1.jpg') }
    foo { background-image: url('absolute://disallow.com/soon.jpg') }
    foo { background-image: url('://valid.jpg') }
    foo { background-image: url('valid.jpg') }

    /* some tests for url verification - fonts */
    @font-face { src: url(''); } /* allowed for now */
    @font-face { src: url('invalid://invalid.com/1.ttf') }
    @font-face { src: url('https://valid.com/1.ttf') }
    @font-face { src: url('http://valid.com/1.ttf') }
    @font-face { src: url('absolute://invalid.com/1.ttf') }
    @font-face { src: url('://valid.ttf') }
    @font-face { src: url('valid.ttf') }
  </style>
  <style amp-boilerplate>body{-webkit-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-moz-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-ms-animation:-amp-start 8s steps(1,end) 0s 1 normal both;animation:-amp-start 8s steps(1,end) 0s 1 normal both}@-webkit-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-moz-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-ms-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-o-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}</style><noscript><style amp-boilerplate>body{-webkit-animation:none;-moz-animation:none;-ms-animation:none;animation:none}</style></noscript>
  <script src="https://cdn.ampproject.org/v0.js" async></script>
</head>
<body>
</body>
</html>


text:
import logging
import time

from nose.tools import assert_true, assert_false, assert_equal, assert_raises
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse

from desktop.lib.django_test_util import make_logged_in_client
from desktop.models import Document

from liboozie.oozie_api_tests import OozieServerProvider
from oozie.models import Workflow, Node, Action, Start, Kill, End, Link

LOG = logging.getLogger(__name__)

class TestJobsubWithHadoop(OozieServerProvider):

  def setUp(self):
    OozieServerProvider.setup_class()
    self.cluster.fs.do_as_user('jobsub_test', self.cluster.fs.create_home_dir, '/user/jobsub_test')
    self.cluster.fs.do_as_superuser(self.cluster.fs.chmod, '/user/jobsub_test', 0777, True) # Hum?
    self.client = make_logged_in_client(username='jobsub_test')
    self.user = User.objects.get(username='jobsub_test')

    # Ensure access to MR folder.
    # Need to chmod because jobs are submitted as a
    # different user than what was previously used.
    for i in range(0,10):
      try:
        self.cluster.fs.do_as_superuser(self.cluster.fs.chmod, '/tmp', 0777, recursive=True)
        break
      except Exception, e:
        # chmod failure likely do to async processing of resource deletion.
        # If the directory has improper permissions, should fail later in the test case.
        LOG.warn("Received the following exception while change mode attempt %d of /tmp: %s" % (i, str(e)))
        time.sleep(1)

    self.design = self.create_design()

  def tearDown(self):
    Workflow.objects.all().delete()

  def create_design(self):
    response = self.client.post(reverse('jobsub.views.new_design',
      kwargs={'node_type': 'mapreduce'}),
      data={'name': 'sleep_job',
            'description': '',
            'node_type': 'mapreduce',
            'jar_path': '/user/hue/oozie/workspaces/lib/hadoop-examples.jar',
            'prepares': '[]',
            'files': '[]',
            'archives': '[]',
            'job_properties': '[{\"name\":\"mapred.reduce.tasks\",\"value\":\"1\"},{\"name\":\"mapred.mapper.class\",\"value\":\"org.apache.hadoop.examples.SleepJob\"},{\"name\":\"mapred.reducer.class\",\"value\":\"org.apache.hadoop.examples.SleepJob\"},{\"name\":\"mapred.mapoutput.key.class\",\"value\":\"org.apache.hadoop.io.IntWritable\"},{\"name\":\"mapred.mapoutput.value.class\",\"value\":\"org.apache.hadoop.io.NullWritable\"},{\"name\":\"mapred.output.format.class\",\"value\":\"org.apache.hadoop.mapred.lib.NullOutputFormat\"},{\"name\":\"mapred.input.format.class\",\"value\":\"org.apache.hadoop.examples.SleepJob$SleepInputFormat\"},{\"name\":\"mapred.partitioner.class\",\"value\":\"org.apache.hadoop.examples.SleepJob\"},{\"name\":\"mapred.speculative.execution\",\"value\":\"false\"},{\"name\":\"sleep.job.map.sleep.time\",\"value\":\"0\"},{\"name\":\"sleep.job.reduce.sleep.time\",\"value\":\"${REDUCER_SLEEP_TIME}\"}]'},
      HTTP_X_REQUESTED_WITH='XMLHttpRequest')
    assert_equal(response.status_code, 200)
    return Workflow.objects.all()[0]

  def test_new_design(self):
    # Ensure the following:
    #   - creator is owner.
    #   - workflow name and description are the same as action name and description.
    #   - workflow has one action.
    assert_false(self.design.managed)
    assert_equal(4, Action.objects.filter(workflow=self.design).count())
    assert_equal(1, Kill.objects.filter(workflow=self.design).count())
    assert_equal(1, Start.objects.filter(workflow=self.design).count())
    assert_equal(1, End.objects.filter(workflow=self.design).count())
    assert_equal(4, Node.objects.filter(workflow=self.design).count())
    assert_equal(3, Link.objects.filter(parent__workflow=self.design).count())

  def test_save_design(self):
    response = self.client.post(reverse('jobsub.views.save_design',
      kwargs={'design_id': self.design.id}),
      data={'name': 'mapreduce1',
            'description': '',
            'node_type': 'mapreduce',
            'jar_path': '/user/hue/oozie/workspaces/lib/hadoop-examples.jar',
            'prepares': '[]',
            'files': '[{"name": "test", "dummy": ""}]',
            'archives': '[]',
            'job_properties': '[{\"name\":\"mapred.reduce.tasks\",\"value\":\"1\"},{\"name\":\"mapred.mapper.class\",\"value\":\"org.apache.hadoop.examples.SleepJob\"},{\"name\":\"mapred.reducer.class\",\"value\":\"org.apache.hadoop.examples.SleepJob\"},{\"name\":\"mapred.mapoutput.key.class\",\"value\":\"org.apache.hadoop.io.IntWritable\"},{\"name\":\"mapred.mapoutput.value.class\",\"value\":\"org.apache.hadoop.io.NullWritable\"},{\"name\":\"mapred.output.format.class\",\"value\":\"org.apache.hadoop.mapred.lib.NullOutputFormat\"},{\"name\":\"mapred.input.format.class\",\"value\":\"org.apache.hadoop.examples.SleepJob$SleepInputFormat\"},{\"name\":\"mapred.partitioner.class\",\"value\":\"org.apache.hadoop.examples.SleepJob\"},{\"name\":\"mapred.speculative.execution\",\"value\":\"false\"},{\"name\":\"sleep.job.map.sleep.time\",\"value\":\"0\"},{\"name\":\"sleep.job.reduce.sleep.time\",\"value\":\"${REDUCER_SLEEP_TIME}\"}]'},
      HTTP_X_REQUESTED_WITH='XMLHttpRequest')
    assert_equal(response.status_code, 200)
    self.design = Workflow.objects.get(id=self.design.id)
    assert_equal(self.design.start.get_child('to').get_full_node().files, '[{"name": "test", "dummy": ""}]')

  def test_get_design(self):
    response = self.client.get(reverse('jobsub.views.get_design',
      kwargs={'design_id': self.design.id}),
      HTTP_X_REQUESTED_WITH='XMLHttpRequest')
    assert_equal(response.status_code, 200)

  def test_delete_design(self):
    # Trash
    n_available = Document.objects.available_docs(Workflow, self.user).count()
    n_trashed = Document.objects.trashed_docs(Workflow, self.user).count()

    response = self.client.post(reverse('jobsub.views.delete_design',
      kwargs={'design_id': self.design.id}),
      follow=True,
      HTTP_X_REQUESTED_WITH='XMLHttpRequest')

    assert_equal(response.status_code, 200)
    assert_equal(n_available - 1, Document.objects.available_docs(Workflow, self.user).count())
    assert_equal(n_trashed + 1, Document.objects.trashed_docs(Workflow, self.user).count())

    # Destroy
    response = self.client.post(reverse('jobsub.views.delete_design',
      kwargs={'design_id': self.design.id}) + '?skip_trash',
      follow=True,
      HTTP_X_REQUESTED_WITH='XMLHttpRequest')

    assert_equal(response.status_code, 200)
    assert_equal(n_available - 1, Document.objects.available_docs(Workflow, self.user).count())
    assert_equal(n_trashed, Document.objects.trashed_docs(Workflow, self.user).count())

  def test_clone_design(self):
    n_available = Document.objects.available_docs(Workflow, self.user).count()

    response = self.client.post(reverse('jobsub.views.clone_design',
      kwargs={'design_id': self.design.id}),
      follow=True,
      HTTP_X_REQUESTED_WITH='XMLHttpRequest')

    assert_equal(response.status_code, 200)
    assert_equal(n_available + 1, Document.objects.available_docs(Workflow, self.user).count())

  def test_restore_design(self):
    n_available = Document.objects.available_docs(Workflow, self.user).count()
    n_trashed = Document.objects.trashed_docs(Workflow, self.user).count()

    response = self.client.post(reverse('jobsub.views.delete_design',
      kwargs={'design_id': self.design.id}),
      follow=True,
      HTTP_X_REQUESTED_WITH='XMLHttpRequest')

    assert_equal(response.status_code, 200)
    assert_equal(n_available - 1, Document.objects.available_docs(Workflow, self.user).count())
    assert_equal(n_trashed + 1, Document.objects.trashed_docs(Workflow, self.user).count())

    response = self.client.post(reverse('jobsub.views.restore_design',
      kwargs={'design_id': self.design.id}),
      follow=True,
      HTTP_X_REQUESTED_WITH='XMLHttpRequest')

    assert_equal(response.status_code, 200)
    assert_equal(n_available, Document.objects.available_docs(Workflow, self.user).count())
    assert_equal(n_trashed, Document.objects.trashed_docs(Workflow, self.user).count())


text:
@interface NSTimer (pause)

-(void)pauseTimer;
-(void)resumeTimer;

@end


text:
export function routeConfig($stateProvider, $urlRouterProvider) {
    $urlRouterProvider.otherwise('/login');
    $stateProvider
        .state('login', {
            url: '/login',
            component: 'login',
            resolve: {
                user: function ($q, $state, airyUser) {
                    let deferred = $q.defer();
                    airyUser.userLoaded.then(function () {
                        if (airyUser.user.name) {
                            deferred.reject();
                            $state.go('client_list');
                        } else {
                            deferred.resolve();
                        }
                    });
                    return deferred.promise;
                },
            },
        })
        .state('client_list', {
            url: '/clients',
            component: 'clientList',
        })
        .state('client_detail', {
            url: '/clients/:clientId',
            component: 'clientDetail',
        })
        .state('client_timesheet', {
            url: '/clients/:clientId/timesheet',
            component: 'clientTimeSheet',
        })
        .state('client_report', {
            url: '/clients/:clientId/report',
            component: 'clientReport',
        })
        .state('project_detail', {
            url: '/clients/:clientId/projects/:projectId',
            component: 'projectDetail',
        });
}


text:
package com.google.bigquery.utils.zetasqlhelper;

import io.grpc.Channel;

/**
 * Client to establish connections with ZetaSQL Helper server.
 */
public class Client {

    private static ZetaSqlHelperLocalServiceGrpc.ZetaSqlHelperLocalServiceBlockingStub stub;
    // The port number can be modified using setPort method.
    private static int port = 50051;

    private Client() {
    }

    public static ZetaSqlHelperLocalServiceGrpc.ZetaSqlHelperLocalServiceBlockingStub getStub() {
        if (stub == null) {
            Channel channel = getChannel();
            stub = ZetaSqlHelperLocalServiceGrpc.newBlockingStub(channel);
        }
        return stub;
    }

    private static Channel getChannel() {
        return LocalServiceProvider.loadChannel(port);
    }

    public static int getPort() {
        return port;
    }

    /**
     * Set the port number to connect to the ZetaSQL Helper server. The default number is 50051.
     *
     * @param port user-defined port number
     */
    public static void setPort(int port) {
        Client.port = port;
    }
}


text:
package gov.nih.nci.cagrid.fqp.results.utils;

import gov.nih.nci.cagrid.cqlresultset.CQLQueryResults;
import gov.nih.nci.cagrid.data.utilities.CQLQueryResultsIterator;
import gov.nih.nci.cagrid.enumeration.stubs.response.EnumerationResponseContainer;
import gov.nih.nci.cagrid.fqp.processor.exceptions.FederatedQueryProcessingException;
import gov.nih.nci.cagrid.wsenum.utils.EnumConfigDiscoveryUtil;
import gov.nih.nci.cagrid.wsenum.utils.EnumIteratorFactory;
import gov.nih.nci.cagrid.wsenum.utils.EnumerateResponseFactory;
import gov.nih.nci.cagrid.wsenum.utils.IterImplType;

import java.io.IOException;
import java.io.StringReader;
import java.util.LinkedList;
import java.util.List;

import javax.xml.namespace.QName;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.soap.SOAPElement;

import org.apache.axis.message.MessageElement;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.globus.ws.enumeration.EnumIterator;
import org.globus.wsrf.utils.XmlUtils;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

/**
 * FQPEnumerationExecutionUtil
 * Sets up a WS-Enumeration retrieval of CQL query results.
 *
 * @author ervin
 */
public class FQPEnumerationExecutionUtil {

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

    private FQPEnumerationExecutionUtil() {
        // prevent instantiation
    }

    public static EnumerationResponseContainer setUpEnumeration(
        CQLQueryResults cqlResults) throws FederatedQueryProcessingException {

        // placeholder for result object QName
        QName resultTypeQname = null;

        // Aggregate results as a List of XML documents.
        // Using XML documents removes requirement that server be able
        // to deserialize every type of object it might potentially handle.
        LOG.debug("Creating XML documents from results");
        List<SOAPElement> aggregatedDocuments = new LinkedList<SOAPElement>();
        CQLQueryResultsIterator iterator = new CQLQueryResultsIterator(cqlResults, true);
        try {
            while (iterator.hasNext()) {
                String resultXml = (String) iterator.next();
                Document doc = XmlUtils.newDocument(new InputSource(new StringReader(resultXml)));
                MessageElement xmlAsElement = new MessageElement(doc.getDocumentElement());
                QName cqlElementQname = xmlAsElement.getQName();
                if (resultTypeQname == null) {
                    resultTypeQname = cqlElementQname;
                } else if (!resultTypeQname.equals(cqlElementQname)) {
                    throw new FederatedQueryProcessingException(
                        "Encountered a CQL query result of type " + cqlElementQname.toString() +
                        " but expected " + resultTypeQname.toString());
                }
                aggregatedDocuments.add(xmlAsElement);
            }
        } catch (IOException ex) {
            throw new FederatedQueryProcessingException(
                "Error reading XML query results: " + ex.getMessage(), ex);
        } catch (SAXException ex) {
            throw new FederatedQueryProcessingException(
                "Error parsing XML query results: " + ex.getMessage(), ex);
        } catch (ParserConfigurationException ex) {
            throw new FederatedQueryProcessingException(
                "Error parsing XML query results: " + ex.getMessage(), ex);
        }

        // create an EnumIterator instance
        LOG.debug("Creating EnumIterator instance");
        EnumIterator enumIter = null;
        try {
            IterImplType iterImplementation = EnumConfigDiscoveryUtil.getConfiguredIterImplType();
            enumIter = EnumIteratorFactory.createIterator(
                iterImplementation, aggregatedDocuments, resultTypeQname, null);
        } catch (Exception ex) {
            throw new FederatedQueryProcessingException("Error creating EnumIterator instance: " + ex.getMessage(), ex);
        }

        // create the response... this will properly initialize the Enumeration resource
        LOG.debug("Preparing enumeration resource and response");
        EnumerationResponseContainer responseContainer = null;
        try {
            responseContainer = EnumerateResponseFactory.createEnumerationResponse(enumIter);
        } catch (Exception ex) {
            throw new FederatedQueryProcessingException("Error creating Enumeration resource: " + ex.getMessage(), ex);
        }

        return responseContainer;
    }
}


text:
---
layout: post
title: 跟着android官网学android
tags: [android, sqlite]
categories: articles
comments: true
share: true
---

{% highlight html %}
由于新项目服务端方面没这么忙,老大也让我学起客户端来。这也就上了andorid官网学习起andoird来了
{% endhighlight %}

## 1.AndroidManifest.xml

跟着官网写的第一个app,其中提到了AndroidManifest.xml这个文件是描述这个app的特点还有定义各类组件。
该文件中其中一个最重要的元素是<uses-sdk android:minSdkVersion="9" android:targetSdkVersion="17" />.
其中要把targetSdkVersion设得越高越好

## 2.数据库存储sqlite

使用sqlite下面两个方法的时候,要在一个异步执行

Note: Because they can be long-running, be sure that you call getWritableDatabase() or getReadableDatabase() in a background thread, such as with AsyncTask or IntentService

{% highlight ruby %}
/**BaseColumns 接口
一般可以写个内部类实现这个接口,里面定义一些数据库的表名,列名。方便使用,防止在使用过程中拼写错误*/
public static abstract class FeedEntry implements BaseColumns{
        public static final String TABLE_NAME = "entry";
        public static final String COL_NAME_ENTRY_ID = "entry_id";
        public static final String COL_NAME_TITLE = "title";
        public static final String COL_NAME_SUBTITLE = "subtitle";
    }
{% endhighlight %}

## 3.android.content.Context

Context是android.app.Activity的父类


text:
[![Build Status](https://img.shields.io/travis/RobLoach/require-one/master.svg)](http://travis-ci.org/RobLoach/require-one "Check this project's build status on TravisCI")
[![NPM downloads](https://img.shields.io/npm/dm/require-one.svg)](https://npmjs.org/package/require-one "View this project on NPM")
[![Dependency Status](https://img.shields.io/david/RobLoach/require-one.svg)](https://david-dm.org/RobLoach/require-one)

> Load the first package found from the given array.

## Install

Method | Installation
------ | ------------
[npm](http://npmjs.com/package/jquery-once) | `npm install require-one --save`
[component](https://github.com/componentjs/component) | `component install robloach/require-one`
[Composer](https://packagist.org/packages/robloach/require-one) | `composer require require-one`
[Bower](http://bower.io/search/?q=require-one) | `bower install require-one`

## Usage

This works across [CommonJS](https://webpack.github.io/docs/commonjs.html)/[node](http://nodejs.org), [AMD](http://requirejs.org/docs/whyamd.html#amd) and with global variables for the browser.

### CommonJS

This is an example of loading either [jQuery](http://jquery.com), [Zepto](http://zeptojs.com), or [Cheerio](http://cheeriojs.github.io/cheerio) with a CommonJS module loader, like [Node.js](http://nodejs.org).

``` javascript
var $ = requireOne('jquery', 'zepto', 'cheerio');
// => jQuery, Zepto or Cheerio, depending on which one is available.
```

### AMD

This is an example of loading either [jQuery](http://jquery.com), [Zepto](http://zeptojs.com), or [Cheerio](http://cheeriojs.github.io/cheerio) with an AMD module loader, like [Require.js](http://requirejs.org).

``` javascript
require(['require-one'], function(requireOne) {

  // Retrieve the first package that is available.
  var $ = requireOne('jquery', 'zepto', 'cheerio');
  // => jQuery, Zepto or Cheerio, depending on which one is available.

  // ...
});
```

### Globals

This is an example of loading either [jQuery](http://jquery.com), [Zepto](http://zeptojs.com), or [Cheerio](http://cheeriojs.github.io/cheerio) without a module loader, i.e. with the browser's global variables.

``` html
<!DOCTYPE html>
<html>
  <head>
    <script type="text/javascript" src="path/to/require-one.js"></script>
    <script>
      var $ = requireOne('jquery', 'jQuery', 'zepto', 'Zepto', 'cheerio');
      // => jQuery, Zepto or Cheerio, depending on which one is available.
    </script>
  </head>
  <body>
    <h1>My Sample Project</h1>
  </body>
</html>
```

## License

[MIT](LICENSE.md)


text:
import React from 'react';

// importing components by family type
import FoundationFamily from './componentsFamilies/FoundationFamily';
import LayoutFamily from './componentsFamilies/LayoutFamily/LayoutFamily';
import InputFamily from './componentsFamilies/InputFamily';
import SelectionFamily from './componentsFamilies/SelectionFamily';
import ButtonFamily from './componentsFamilies/ButtonFamily';
import NavigationFamily from './componentsFamilies/NavigationFamily';
import TooltipFamily from './componentsFamilies/TooltipFamily';
import NotificationFamily from './componentsFamilies/NotificationFamily';
import ModalFamily from './componentsFamilies/ModalFamily';
import PickerFamily from './componentsFamilies/PickerFamily';
import OtherFamily from './componentsFamilies/OtherFamily';
import ContentWidgetsFamily from './componentsFamilies/ContentWidgetsFamily';
import InternalFamily from './componentsFamilies/InternalFamily';

import { Layout, Cell, Page } from 'wix-style-react';

class ComponentsCheatsheet extends React.Component {
  render() {
    const componentsFamiliesArr = [
      FoundationFamily,
      LayoutFamily,
      InputFamily,
      SelectionFamily,
      ButtonFamily,
      NavigationFamily,
      TooltipFamily,
      NotificationFamily,
      ModalFamily,
      PickerFamily,
      OtherFamily,
      ContentWidgetsFamily,
      InternalFamily,
    ];

    return (
      <Page>
        <Page.Header
          title="Components Cheatsheet"
          subtitle="Common components index"
        />
        <Page.Content>
          <Layout>
            {componentsFamiliesArr.map((Family, i) => (
              <Cell key={`family-Cell-${i}`}>
                <Family key={`family-${i}`} />
              </Cell>
            ))}
          </Layout>
        </Page.Content>
      </Page>
    );
  }
}
export default ComponentsCheatsheet;


text:
package com.xidian.flyhigher.magicweather.gson;

import com.google.gson.annotations.SerializedName;

public class Suggestion {

    @SerializedName("comf")
    public Comfort comfort;

    @SerializedName("cw")
    public CarWash carWash;

    @SerializedName("drsg")
    public CarWash drsg;

    @SerializedName("flu")
    public CarWash flu;

    @SerializedName("uv")
    public CarWash uv;

    public Sport sport;

    public class Uv {

        @SerializedName("txt")
        public String info;

    }

    public class Flu {

        @SerializedName("txt")
        public String info;

    }

    public class Drsg {

        @SerializedName("txt")
        public String info;

    }

    public class Comfort {

        @SerializedName("txt")
        public String info;

    }

    public class CarWash {

        @SerializedName("txt")
        public String info;

    }

    public class Sport {

        @SerializedName("txt")
        public String info;

    }

}


text:
/*
 *
 * This example shows how to implement a simple code lock. The code
 * lock waits for key presses from a numeric keyboard and if the
 * correct code is entered, the lock is unlocked. There is a maximum
 * time of one second between each key press, and after the correct
 * code has been entered, no more keys must be pressed for 0.5 seconds
 * before the lock is opened.
 *
 * This is an example that shows two things:
 * - how to implement a code lock key input mechanism, and
 * - how to implement a sequential timed routine.
 *
 * The program consists of two protothreads, one that implements the
 * code lock reader and one that implements simulated keyboard input.
 *
 *
 */

#ifdef _WIN32
#include <windows.h>
#else
#include <unistd.h>
#include <sys/time.h>
#endif
#include <stdio.h>

#include "pt.h"

/*---------------------------------------------------------------------------*/
/*
 * The following definitions are just for the simple timer library
 * used in this example. The actual implementation of the functions
 * can be found at the end of this file.
 */
struct timer { int start, interval; };
static int  timer_expired(struct timer *t);
static void timer_set(struct timer *t, int usecs);
/*---------------------------------------------------------------------------*/
/*
 * This example uses two timers: one for the code lock protothread and
 * one for the simulated key input protothread.
 */
static struct timer codelock_timer, input_timer;
/*---------------------------------------------------------------------------*/
/*
 * This is the code that has to be entered.
 */
static const char code[4] = {'1', '4', '2', '3'};
/*---------------------------------------------------------------------------*/
/*
 * This example has two protothread and therefor has two protothread
 * control structures of type struct pt. These are initialized with
 * PT_INIT() in the main() function below.
 */
static struct pt codelock_pt, input_pt;
/*---------------------------------------------------------------------------*/
/*
 * The following code implements a simple key input. Input is made
 * with the press_key() function, and the function key_pressed()
 * checks if a key has been pressed. The variable "key" holds the
 * latest key that was pressed. The variable "key_pressed_flag" is set
 * when a key is pressed and cleared when a key press is checked.
 */
static char key, key_pressed_flag;

static void
press_key(char k)
{
  printf("--- Key '%c' pressed\n", k);
  key = k;
  key_pressed_flag = 1;
}

static int
key_pressed(void)
{
  if(key_pressed_flag != 0) {
    key_pressed_flag = 0;
    return 1;
  }
  return 0;
}
/*---------------------------------------------------------------------------*/
/*
 * Declaration of the protothread function implementing the code lock
 * logic. The protothread function is declared using the PT_THREAD()
 * macro. The function is declared with the "static" keyword since it
 * is local to this file. The name of the function is codelock_thread
 * and it takes one argument, pt, of the type struct pt.
 *
 */
static
PT_THREAD(codelock_thread(struct pt *pt))
{
  /* This is a local variable that holds the number of keys that have
   * been pressed. Note that it is declared with the "static" keyword
   * to make sure that the variable is *not* allocated on the stack.
   */
  static int keys;

  /*
   * Declare the beginning of the protothread.
   */
  PT_BEGIN(pt);

  /*
   * We'll let the protothread loop until the protothread is
   * expliticly exited with PT_EXIT().
   */
  while(1) {

    /*
     * We'll be reading key presses until we get the right amount of
     * correct keys.
     */
    for(keys = 0; keys < sizeof(code); ++keys) {

      /*
       * If we haven't gotten any keypresses, we'll simply wait for one.
       */
      if(keys == 0) {

	/*
	 * The PT_WAIT_UNTIL() function will block until the condition
	 * key_pressed() is true.
	 */
	PT_WAIT_UNTIL(pt, key_pressed());
      } else {

	/*
	 * If the "key" variable was larger than zero, we have already
	 * gotten at least one correct key press. If so, we'll not
	 * only wait for the next key, but we'll also set a timer that
	 * expires in one second. This gives the person pressing the
	 * keys one second to press the next key in the code.
	 */
	timer_set(&codelock_timer, 1000);

	/*
	 * The following statement shows how complex blocking
	 * conditions can be easily expressed with protothreads and
	 * the PT_WAIT_UNTIL() function.
	 */
	PT_WAIT_UNTIL(pt, key_pressed() || timer_expired(&codelock_timer));

	/*
	 * If the timer expired, we should break out of the for() loop
	 * and start reading keys from the beginning of the while(1)
	 * loop instead.
	 */
	if(timer_expired(&codelock_timer)) {
	  printf("Code lock timer expired.\n");

	  /*
	   * Break out from the for() loop and start from the
	   * beginning of the while(1) loop.
	   */
	  break;
	}
      }

      /*
       * Check if the pressed key was correct.
       */
      if(key != code[keys]) {
	printf("Incorrect key '%c' found\n", key);
	/*
	 * Break out of the for() loop since the key was incorrect.
	 */
	break;
      } else {
	printf("Correct key '%c' found\n", key);
      }
    }

    /*
     * Check if we have gotten all keys.
     */
    if(keys == sizeof(code)) {
      printf("Correct code entered, waiting for 500 ms before unlocking.\n");

      /*
       * Ok, we got the correct code. But to make sure that the code
       * was not just a fluke of luck by an intruder, but the correct
       * code entered by a person that knows the correct code, we'll
       * wait for half a second before opening the lock. If another
       * key is pressed during this time, we'll assume that it was a
       * fluke of luck that the correct code was entered the first
       * time.
       */
      timer_set(&codelock_timer, 500);
      PT_WAIT_UNTIL(pt, key_pressed() || timer_expired(&codelock_timer));

      /*
       * If we continued from the PT_WAIT_UNTIL() statement without
       * the timer expired, we don't open the lock.
       */
      if(!timer_expired(&codelock_timer)) {
	printf("Key pressed during final wait, code lock locked again.\n");
      } else {

	/*
	 * If the timer expired, we'll open the lock and exit from the
	 * protothread.
	 */
	printf("Code lock unlocked.\n");
	PT_EXIT(pt);
      }
    }
  }

  /*
   * Finally, we'll mark the end of the protothread.
   */
  PT_END(pt);
}
/*---------------------------------------------------------------------------*/
/*
 * This is the second protothread in this example. It implements a
 * simulated user pressing the keys. This illustrates how a linear
 * sequence of timed instructions can be implemented with
 * protothreads.
 */
static
PT_THREAD(input_thread(struct pt *pt))
{
  PT_BEGIN(pt);

  printf("Waiting 1 second before entering first key.\n");

  timer_set(&input_timer, 1000);
  PT_WAIT_UNTIL(pt, timer_expired(&input_timer));

  press_key('1');

  timer_set(&input_timer, 100);
  PT_WAIT_UNTIL(pt, timer_expired(&input_timer));

  press_key('2');

  timer_set(&input_timer, 100);
  PT_WAIT_UNTIL(pt, timer_expired(&input_timer));

  press_key('3');

  timer_set(&input_timer, 2000);
  PT_WAIT_UNTIL(pt, timer_expired(&input_timer));

  press_key('1');

  timer_set(&input_timer, 200);
  PT_WAIT_UNTIL(pt, timer_expired(&input_timer));

  press_key('4');

  timer_set(&input_timer, 200);
  PT_WAIT_UNTIL(pt, timer_expired(&input_timer));

  press_key('2');

  timer_set(&input_timer, 2000);
  PT_WAIT_UNTIL(pt, timer_expired(&input_timer));

  press_key('3');

  timer_set(&input_timer, 200);
  PT_WAIT_UNTIL(pt, timer_expired(&input_timer));

  press_key('1');

  timer_set(&input_timer, 200);
  PT_WAIT_UNTIL(pt, timer_expired(&input_timer));

  press_key('4');

  timer_set(&input_timer, 200);
  PT_WAIT_UNTIL(pt, timer_expired(&input_timer));

  press_key('2');

  timer_set(&input_timer, 100);
  PT_WAIT_UNTIL(pt, timer_expired(&input_timer));

  press_key('3');

  timer_set(&input_timer, 100);
  PT_WAIT_UNTIL(pt, timer_expired(&input_timer));

  press_key('4');

  timer_set(&input_timer, 1500);
  PT_WAIT_UNTIL(pt, timer_expired(&input_timer));

  press_key('1');

  timer_set(&input_timer, 300);
  PT_WAIT_UNTIL(pt, timer_expired(&input_timer));

  press_key('4');

  timer_set(&input_timer, 400);
  PT_WAIT_UNTIL(pt, timer_expired(&input_timer));

  press_key('2');

  timer_set(&input_timer, 500);
  PT_WAIT_UNTIL(pt, timer_expired(&input_timer));

  press_key('3');

  timer_set(&input_timer, 2000);
  PT_WAIT_UNTIL(pt, timer_expired(&input_timer));

  PT_END(pt);
}
/*---------------------------------------------------------------------------*/
/*
 * This is the main function. It initializes the two protothread
 * control structures and schedules the two protothreads. The main
 * function returns when the protothread the runs the code lock exits.
 */
int
main(void)
{
  /*
   * Initialize the two protothread control structures.
   */
  PT_INIT(&input_pt);
  PT_INIT(&codelock_pt);

  /*
   * Schedule the two protothreads until the codelock_thread() exits.
   */
  while(PT_SCHEDULE(codelock_thread(&codelock_pt))) {
    PT_SCHEDULE(input_thread(&input_pt));

    /*
     * When running this example on a multitasking system, we must
     * give other processes a chance to run too and therefore we call
     * usleep() resp. Sleep() here. On a dedicated embedded system,
     * we usually do not need to do this.
     */
#ifdef _WIN32
    Sleep(0);
#else
    usleep(10);
#endif
  }

  return 0;
}
/*---------------------------------------------------------------------------*/
/*
 * Finally, the implementation of the simple timer library follows.
 */
#ifdef _WIN32

static int clock_time(void)
{ return (int)GetTickCount(); }

#else /* _WIN32 */

static int clock_time(void)
{
  struct timeval tv;
  struct timezone tz;
  gettimeofday(&tv, &tz);
  return tv.tv_sec * 1000 + tv.tv_usec / 1000;
}

#endif /* _WIN32 */

static int timer_expired(struct timer *t)
{ return (int)(clock_time() - t->start) >= (int)t->interval; }

static void timer_set(struct timer *t, int interval)
{ t->interval = interval; t->start = clock_time(); }
/*---------------------------------------------------------------------------*/


text:
function mappedX = gda(X, Y, no_dims, varargin)
%GDA Perform Generalized Discriminant Analysis
%
%	mappedX = gda(X, Y, no_dims)
%	mappedX = gda(X, Y, no_dims, kernel)
%	mappedX = gda(X, Y, no_dims, kernel, param1)
%	mappedX = gda(X, Y, no_dims, kernel, param1, param2)
%
% Perform Generalized Discriminant Analysis. GDA or Kernel LDA is the
% nonlinear generalization of LDA by means of the kernel trick. X is the
% data on which to perform GDA, Y are the corresponding labels.
% The value of kernel determines the used kernel. Possible values are 'linear',
% 'gauss', 'poly', 'subsets', or 'princ_angles' (default = 'gauss'). For
% more info on setting the parameters of the kernel function, type HELP
% GRAM.
% The function returns the locations of the embedded trainingdata in
% mappedX.
%
%

% This file is part of the Matlab Toolbox for Dimensionality Reduction.
% The toolbox can be obtained from http://homepage.tudelft.nl/19j49
% You are free to use, change, or redistribute this code in any way you
% want for non-commercial purposes. However, it is appreciated if you
% maintain the name of the original author.
%
% (C) Laurens van der Maaten, Delft University of Technology

    % Process inputs
    if ~exist('no_dims', 'var')
        no_dims = 2;
    end
    kernel = 'gauss';
    param1 = 1;
	param2 = 0;
    if length(varargin) > 0 & strcmp(class(varargin{1}), 'char'), kernel = varargin{1}; end
	if length(varargin) > 1 & strcmp(class(varargin{2}), 'double'), param1 = varargin{2}; end
	if length(varargin) > 2 & strcmp(class(varargin{3}), 'double'), param2 = varargin{3}; end

	% Make sure labels are nice
	[foo, bar, Y] = unique(Y, 'rows');

	% Get dimensions
	[n, dim] = size(X);
	nclass = max(Y);

	% Sort data according to labels
	[foo, ind] = sort(Y);
	Y = Y(ind);
	X = X(ind,:);

	% Compute kernel matrix
    disp('Computing kernel matrix...');
    K = gram(X, X, kernel, param1, param2);

    % Compute centering matrix
    ell = size(X, 1);
    D = sum(K) / ell;
    E = sum(D) / ell;
    J = ones(ell, 1) * D;
    K = K - J - J' + E * ones(ell, ell);

    % Perform eigenvector decomposition of kernel matrix (Kc = P * gamma * P')
    disp('Performing eigendecomposition of kernel matrix...');
    K(isnan(K)) = 0;
    K(isinf(K)) = 0;
    [P, gamma] = eig(K);

	if size(P, 2) < n
		error('Singularities in kernel matrix prevent solution.');
    end

	% Sort eigenvalues and vectors in descending order
	[gamma, ind] = sort(diag(gamma), 'descend');
	P = P(:,ind);

	% Remove eigenvectors with relatively small value
	minEigv = max(gamma) / 1e5;
	ind = find(gamma > minEigv);
	P = P(:,ind);
	gamma = gamma(ind);
	rankK = length(ind);

	% Recompute kernel matrix
    K = P * diag(gamma) * P';

	% Construct diagonal block matrix W
	W = [];
	for i=1:nclass
		num_data_class = length(find(Y == i));
		W = blkdiag(W, ones(num_data_class) / num_data_class);
	end

	% Determine target dimensionality of data
	old_no_dims = no_dims;
    no_dims = min([no_dims rankK nclass]);
    if old_no_dims > no_dims
        warning(['Target dimensionality reduced to ' num2str(no_dims) '.']);
    end

	% Perform eigendecomposition of matrix (P' * W * P)
	disp('Performing GDA eigenanalysis...');
    [Beta, lambda] = eig(P' * W * P);
	lambda = diag(lambda);

	% Sort eigenvalues and eigenvectors in descending order
	[lambda, ind] = sort(lambda, 'descend');
	Beta = Beta(:,ind(1:no_dims));

	% Compute final embedding mappedX
	mappedX = P * diag(1 ./ gamma) * Beta;

	% Normalize embedding
	for i=1:no_dims
		mappedX(:,i) = mappedX(:,i) / sqrt(mappedX(:,i)' * K * mappedX(:,i));
	end


text:
<?php namespace SleepingOwl\Admin\Interfaces;

interface ShowItemInterface
{

	/**
	 * Initialize form item
	 */
	public function initialize();

}