<commit_before>/**
 * @author mrdoob / http://mrdoob.com/
 */

var TG = {};

TG.Texture = function ( width, height ) {

	this.width = width;
	this.height = height;

	this.array = new Float32Array( width * height * 4 );
	this.arrayCopy = new Float32Array( width * height * 4 );

	return this;

};

TG.Texture.prototype = {

	constructor: TG.Texture,

	pass: function ( program, operation ) {

		if ( operation === undefined ) operation = '';

		var color = program.getColor();
		var source = program.getSource();

		this.arrayCopy.set( this.array );

		var string = [
			'var x = 0, y = 0;',
			'for ( var i = 0, il = dst.length; i < il; i += 4 ) {',
				'	' + source,
				color[ 0 ] !== 0 ? '	dst[ i + 0 ] ' + operation + '= color * ' + color[ 0 ] + ';' : '',
				color[ 1 ] !== 0 ? '	dst[ i + 1 ] ' + operation + '= color * ' + color[ 1 ] + ';' : '',
				color[ 2 ] !== 0 ? '	dst[ i + 2 ] ' + operation + '= color * ' + color[ 2 ] + ';' : '',
				'	if ( ++x === width ) { x = 0; y ++; }',
			'}'
		].join( '\n' );

		new Function( 'dst, src, width, height', string )( this.array, this.arrayCopy, this.width, this.height );

		return this;

	},

	add: function ( program ) {

		return this.pass( program, '+' );

	},

	sub: function ( program ) {

		return this.pass( program, '-' );

	},

	mul: function ( program ) {

		return this.pass( program, '*' );

	},

	div: function ( program ) {

		return this.pass( program, '/' );

	},

	toImageData: function ( context ) {

		var array = this.array;

		var imagedata = context.createImageData( this.width, this.height );
		var data = imagedata.data;

		for ( var i = 0, il = array.length; i < il; i += 4 ) {

			data[ i		 ] = array[ i		 ] * 255;
			data[ i + 1 ] = array[ i + 1 ] * 255;
			data[ i + 2 ] = array[ i + 2 ] * 255;
			data[ i + 3 ] = 255;

		}

		return imagedata;

	},

	toCanvas: function () {

		var canvas = document.createElement( 'canvas' );
		canvas.width = this.width;
		canvas.height = this.height;

		var context = canvas.getContext( '2d' );
		var imagedata = this.toImageData( context );

		context.putImageData( imagedata, 0, 0 );

		return canvas;

	}

};

TG.Program = function ( object ) {

	var color = [ 1, 1, 1 ];

	object.color = function ( r, g, b ) {
		color = [ r, g, b ];
		return this;
	};

	object.getColor = function () {
		return color;
	};

	return object;

};

TG.Number = function () {

	return new TG.Program( {
		getSource: function () {
			return 'var color = 1;';
		}
	} );

};

TG.SinX = function () {

	var frequency = 1;
	var offset = 0;

	return new TG.Program( {
		frequency: function ( value ) {
			frequency = value * Math.PI;
			return this;
		},
		offset: function ( value ) {
			offset = value;
			return this;
		},
		getSource: function () {
			return 'var color = Math.sin( ( x + ' + offset + ' ) * ' + frequency + ' );';
		}
	} );

};

TG.SinY = function () {

	var frequency = 1;
	var offset = 0;

	return new TG.Program( {
		frequency: function ( value ) {
			frequency = value * Math.PI;
			return this;
		},
		offset: function ( value ) {
			offset = value;
			return this;
		},
		getSource: function () {
			return 'var color = Math.sin( ( y + ' + offset + ' ) * ' + frequency + ' );';
		}
	} );

};

TG.OR = function () {

	return new TG.Program( {
		getSource: function () {
			return 'var color = ( x | y ) / width;';
		}
	} );

};

TG.XOR = function () {

	return new TG.Program( {
		getSource: function () {
			return 'var color = ( x ^ y ) / width;';
		}
	} );

};

TG.Noise = function () {

	return new TG.Program( {
		getSource: function () {
			return 'var color = Math.random();';
		}
	} );

};

TG.CheckerBoard = function () {

	var size = [ 32, 32 ];
	var offset = [ 0, 0 ];
	var rowShift = 0;

	return new TG.Program( {
		size: function ( x, y ) {
			size = [ x, y ];
			return this;
		},
		offset: function ( x, y ) {
			offset = [ x, y ];
			return this;
		},
		rowShift: function ( value ) {
			rowShift = value;
			return this;
		},
		getSource: function () {
			return 'var color = ( ( ( y + ' + offset[ 1 ] + ' ) / ' + size[ 1 ] + ' ) & 1 ) ^ ( ( ( x + ' + offset[ 0 ] + ' + parseInt( y / ' + size[ 1 ] + ' ) * ' + rowShift + ' ) / ' + size[ 0 ] + ' ) & 1 ) ? 0 : 1';
		}
	} );

};

TG.Rect = function () {

	var position = [ 0, 0 ];
	var size = [ 32, 32 ];

	return new TG.Program( {
		position: function ( x, y ) {
			position = [ x, y ];
			return this;
		},
		size: function ( x, y ) {
			size = [ x, y ];
			return this;
		},
		getSource: function () {
			return 'var color = ( x >= ' + position[ 0 ] + ' && x <= ' + ( position[ 0 ] + size[ 0 ] ) + ' && y <= ' + ( position[ 1 ] + size[ 1 ] ) + ' && y >= ' + position[ 1 ] + ' ) ? 1 : 0;';
		}
	} );

};

TG.Circle = function () {

	var position = [ 0, 0 ];
	var radius = 50;
	var delta = 1;

	return new TG.Program( {
		delta: function ( value ) {
			delta = value;
			return this;
		},
		position: function ( x, y ) {
			position = [ x, y ];
			return this;
		},
		radius: function ( value ) {
			radius = value;
			return this;
		},
		getSource: function () {
			return [
				'var dist = TG.Utils.distance( x, y, ' + position[ 0 ] + ',' + position[ 1 ] + ');',
				'var color = TG.Utils.smoothStep( ' + radius + ' - ' + delta + ', ' + radius + ', dist );',
			].join('\n');
		}
	} );

};

// Filters

TG.SineDistort = function () {

	var sines = [ 4, 4 ];
	var offset = [ 0, 0 ];
	var amplitude = [ 16, 16 ];

	return new TG.Program( {
		sines: function ( x, y ) {
			sines = [ x, y ];
			return this;
		},
		offset: function ( x, y ) {
			offset = [ x, y ];
			return this;
		},
		amplitude: function ( x, y ) {
			amplitude = [ x, y ];
			return this;
		},
		getSource: function () {
			return [
				'var sx = Math.sin(' + sines[ 0 ] / 100 + ' * y + ' + offset[ 0 ] + ') * ' + amplitude[ 0 ] + ' + x;',
				'var sy = Math.sin(' + sines[ 1 ] / 100 + ' * x + ' + offset[ 1 ] + ') * ' + amplitude[ 1 ] + ' + y;',
				'var color = TG.Utils.getPixelBilinear( src, sx, sy, 0, width, height );'
			].join( '\n' );
		}
	} );

};

TG.Twirl = function () {

	var strength = 0;
	var radius = 120;
	var position = [ 128, 128 ];

	return new TG.Program( {
		strength: function ( value ) {
			strength = value / 100.0;
			return this;
		},
		radius: function ( value ) {
			radius = value;
			return this;
		},
		position: function ( x, y ) {
			position = [ x, y ];
			return this;
		},
		getSource: function () {
			return [
				'var dist = TG.Utils.distance( x, y, ' + position[ 0 ] + ',' + position[ 1 ] + ');',

				// no distortion if outside of whirl radius.
				'if (dist < '+ radius +') {',
					'dist = Math.pow('+ radius +' - dist, 2) / ' + radius + ';',

					'var angle = 2.0 * Math.PI * (dist / (' + radius + ' / ' + strength + '));',
					'xpos = (((x - ' + position[ 0 ] + ') * Math.cos(angle)) - ((y - ' + position[ 0 ] + ') * Math.sin(angle)) + ' + position[ 0 ] + ' + 0.5);',
					'ypos = (((y - ' + position[ 1 ] + ') * Math.cos(angle)) + ((x - ' + position[ 1 ] + ') * Math.sin(angle)) + ' + position[ 1 ] + ' + 0.5);',
				'} else {',
					'xpos = x;',
					'ypos = y;',
				'}',

				'var color = TG.Utils.getPixelBilinear( src, xpos, ypos, 0, width, height );'

			].join( '\n' );
		}
	} );

};

TG.Transform = function () {

    var offset = [ 0, 0 ];
    var angle = 0;
    var zoom = 1;

    return new TG.Program( {

        offset: function ( x, y ) {

            offset = [ x, y ];
            return this;
        },
        angle: function ( value ) {

            angle = TG.Utils.deg2rad( value );
            return this;
        },
        zoom: function ( value ) {

            zoom = value;
            return this;
        },
        getSource: function () {
            return [

				'var x2 = x - width / 2;',
				'var y2 = y - height / 2;',

				's = x2 * (' + ( Math.cos( angle ) / zoom ) + ') + y2 * -(' + ( Math.sin( angle ) / zoom ) + ');',
				't = x2 * (' + ( Math.sin( angle ) / zoom ) + ') + y2 * (  ' + ( Math.cos( angle ) / zoom ) + ');',

				's += ' + offset[ 0 ] + ' + width /2;',
				't += ' + offset[ 1 ] + ' + height /2;',

	            'var color = TG.Utils.getPixelBilinear(src, s, t, 0, width, height);'

            ].join( '\n' );
        }
    } );

};

TG.Pixellate = function () {

	var pixelSize = [ 1, 1 ];

	return new TG.Program( {
		pixelSize: function ( width, height ) {

			if ( height === undefined ) height = width;
			pixelSize = [ width, height ];
			return this;
		},
		getSource: function () {
			return [

    			'var s = ' + pixelSize[ 0 ] + ' * Math.floor(x/' + pixelSize[ 0 ] + ');',
				'var t = ' + pixelSize[ 1 ] + ' * Math.floor(y/' + pixelSize[ 1 ] + ');',

				'var color = TG.Utils.getPixelNearest( src, s, t, 0, width, height );'

			].join( '\n' );
		}
	} );

};

TG.Utils = {

	smoothStep: function ( edge0, edge1, x ) {

		// Scale, bias and saturate x to 0..1 range
		x = TG.Utils.clamp( ( x - edge0 ) / ( edge1 - edge0 ), 0, 1 );

		// Evaluate polynomial
		return x * x * ( 3 - 2 * x );

	},

	distance: function( x0, y0, x1, y1 ) {

		var dx = x1 - x0, dy = y1 - y0;
		return Math.sqrt( dx * dx + dy * dy );

	},

	clamp: function( value, min, max ) {

		return Math.min( Math.max( value, min ), max );

	},

	getPixelNearest: function( pixels, x, y, offset, width, height ) {

        if ( y > height ) y -= height;
        if ( y < 0 ) y += height;
        if ( x > width ) x -= width;
        if ( x < 0 ) x += width;

		return pixels[ offset + Math.round( y ) * width * 4 + Math.round( x ) * 4 ];

	},

	getPixelBilinear: function( pixels, x, y, offset, width, height ) {

        if ( y > height ) y -= height;
        if ( y < 0 ) y += height;
        if ( x > width ) x -= width;
        if ( x < 0 ) x += width;

		var percentX = x - ( x ^ 0 );
		var percentX1 = 1.0 - percentX;
		var percentY = y - ( y ^ 0 );
		var fx4 = ( x ^ 0 ) * 4;
		var cx4 = fx4 + 4;
		var fy4 = ( y ^ 0 ) * 4;
		var cy4wo = ( fy4 + 4 ) * width + offset;
		var fy4wo = fy4 * width + offset;

		var top = pixels[ cy4wo + fx4 ] * percentX1 + pixels[ cy4wo + cx4 ] * percentX;
		var bottom = pixels[ fy4wo + fx4 ] * percentX1 + pixels[ fy4wo + cx4 ] * percentX;

		return top * percentY + bottom * ( 1.0 - percentY );

	},

	deg2rad: function ( deg ) {

		return deg * Math.PI / 180;

	}
};
<commit_msg>Added fipH & flipV<commit_after>/**
 * @author mrdoob / http://mrdoob.com/
 */

var TG = {};

TG.Texture = function ( width, height ) {

	this.width = width;
	this.height = height;

	this.array = new Float32Array( width * height * 4 );
	this.arrayCopy = new Float32Array( width * height * 4 );

	return this;

};

TG.Texture.prototype = {

	constructor: TG.Texture,

	pass: function ( program, operation ) {

		if ( operation === undefined ) operation = '';

		var color = program.getColor();
		var source = program.getSource();

		this.arrayCopy.set( this.array );

		var string = [
			'var x = 0, y = 0;',
			'for ( var i = 0, il = dst.length; i < il; i += 4 ) {',
				'	' + source,
				color[ 0 ] !== 0 ? '	dst[ i + 0 ] ' + operation + '= color * ' + color[ 0 ] + ';' : '',
				color[ 1 ] !== 0 ? '	dst[ i + 1 ] ' + operation + '= color * ' + color[ 1 ] + ';' : '',
				color[ 2 ] !== 0 ? '	dst[ i + 2 ] ' + operation + '= color * ' + color[ 2 ] + ';' : '',
				'	if ( ++x === width ) { x = 0; y ++; }',
			'}'
		].join( '\n' );

		new Function( 'dst, src, width, height', string )( this.array, this.arrayCopy, this.width, this.height );

		return this;

	},

	add: function ( program ) {

		return this.pass( program, '+' );

	},

	sub: function ( program ) {

		return this.pass( program, '-' );

	},

	mul: function ( program ) {

		return this.pass( program, '*' );

	},

	div: function ( program ) {

		return this.pass( program, '/' );

	},

	toImageData: function ( context ) {

		var array = this.array;

		var imagedata = context.createImageData( this.width, this.height );
		var data = imagedata.data;

		for ( var i = 0, il = array.length; i < il; i += 4 ) {

			data[ i		 ] = array[ i		 ] * 255;
			data[ i + 1 ] = array[ i + 1 ] * 255;
			data[ i + 2 ] = array[ i + 2 ] * 255;
			data[ i + 3 ] = 255;

		}

		return imagedata;

	},

	toCanvas: function () {

		var canvas = document.createElement( 'canvas' );
		canvas.width = this.width;
		canvas.height = this.height;

		var context = canvas.getContext( '2d' );
		var imagedata = this.toImageData( context );

		context.putImageData( imagedata, 0, 0 );

		return canvas;

	}

};

TG.Program = function ( object ) {

	var color = [ 1, 1, 1 ];

	object.color = function ( r, g, b ) {
		color = [ r, g, b ];
		return this;
	};

	object.getColor = function () {
		return color;
	};

	return object;

};

TG.Number = function () {

	return new TG.Program( {
		getSource: function () {
			return 'var color = 1;';
		}
	} );

};

TG.SinX = function () {

	var frequency = 1;
	var offset = 0;

	return new TG.Program( {
		frequency: function ( value ) {
			frequency = value * Math.PI;
			return this;
		},
		offset: function ( value ) {
			offset = value;
			return this;
		},
		getSource: function () {
			return 'var color = Math.sin( ( x + ' + offset + ' ) * ' + frequency + ' );';
		}
	} );

};

TG.SinY = function () {

	var frequency = 1;
	var offset = 0;

	return new TG.Program( {
		frequency: function ( value ) {
			frequency = value * Math.PI;
			return this;
		},
		offset: function ( value ) {
			offset = value;
			return this;
		},
		getSource: function () {
			return 'var color = Math.sin( ( y + ' + offset + ' ) * ' + frequency + ' );';
		}
	} );

};

TG.OR = function () {

	return new TG.Program( {
		getSource: function () {
			return 'var color = ( x | y ) / width;';
		}
	} );

};

TG.XOR = function () {

	return new TG.Program( {
		getSource: function () {
			return 'var color = ( x ^ y ) / width;';
		}
	} );

};

TG.Noise = function () {

	return new TG.Program( {
		getSource: function () {
			return 'var color = Math.random();';
		}
	} );

};

TG.CheckerBoard = function () {

	var size = [ 32, 32 ];
	var offset = [ 0, 0 ];
	var rowShift = 0;

	return new TG.Program( {
		size: function ( x, y ) {
			size = [ x, y ];
			return this;
		},
		offset: function ( x, y ) {
			offset = [ x, y ];
			return this;
		},
		rowShift: function ( value ) {
			rowShift = value;
			return this;
		},
		getSource: function () {
			return 'var color = ( ( ( y + ' + offset[ 1 ] + ' ) / ' + size[ 1 ] + ' ) & 1 ) ^ ( ( ( x + ' + offset[ 0 ] + ' + parseInt( y / ' + size[ 1 ] + ' ) * ' + rowShift + ' ) / ' + size[ 0 ] + ' ) & 1 ) ? 0 : 1';
		}
	} );

};

TG.Rect = function () {

	var position = [ 0, 0 ];
	var size = [ 32, 32 ];

	return new TG.Program( {
		position: function ( x, y ) {
			position = [ x, y ];
			return this;
		},
		size: function ( x, y ) {
			size = [ x, y ];
			return this;
		},
		getSource: function () {
			return 'var color = ( x >= ' + position[ 0 ] + ' && x <= ' + ( position[ 0 ] + size[ 0 ] ) + ' && y <= ' + ( position[ 1 ] + size[ 1 ] ) + ' && y >= ' + position[ 1 ] + ' ) ? 1 : 0;';
		}
	} );

};

TG.Circle = function () {

	var position = [ 0, 0 ];
	var radius = 50;
	var delta = 1;

	return new TG.Program( {
		delta: function ( value ) {
			delta = value;
			return this;
		},
		position: function ( x, y ) {
			position = [ x, y ];
			return this;
		},
		radius: function ( value ) {
			radius = value;
			return this;
		},
		getSource: function () {
			return [
				'var dist = TG.Utils.distance( x, y, ' + position[ 0 ] + ',' + position[ 1 ] + ');',
				'var color = TG.Utils.smoothStep( ' + radius + ' - ' + delta + ', ' + radius + ', dist );',
			].join('\n');
		}
	} );

};

// Filters

TG.SineDistort = function () {

	var sines = [ 4, 4 ];
	var offset = [ 0, 0 ];
	var amplitude = [ 16, 16 ];

	return new TG.Program( {
		sines: function ( x, y ) {
			sines = [ x, y ];
			return this;
		},
		offset: function ( x, y ) {
			offset = [ x, y ];
			return this;
		},
		amplitude: function ( x, y ) {
			amplitude = [ x, y ];
			return this;
		},
		getSource: function () {
			return [
				'var sx = Math.sin(' + sines[ 0 ] / 100 + ' * y + ' + offset[ 0 ] + ') * ' + amplitude[ 0 ] + ' + x;',
				'var sy = Math.sin(' + sines[ 1 ] / 100 + ' * x + ' + offset[ 1 ] + ') * ' + amplitude[ 1 ] + ' + y;',
				'var color = TG.Utils.getPixelBilinear( src, sx, sy, 0, width, height );'
			].join( '\n' );
		}
	} );

};

TG.Twirl = function () {

	var strength = 0;
	var radius = 120;
	var position = [ 128, 128 ];

	return new TG.Program( {
		strength: function ( value ) {
			strength = value / 100.0;
			return this;
		},
		radius: function ( value ) {
			radius = value;
			return this;
		},
		position: function ( x, y ) {
			position = [ x, y ];
			return this;
		},
		getSource: function () {
			return [
				'var dist = TG.Utils.distance( x, y, ' + position[ 0 ] + ',' + position[ 1 ] + ');',

				// no distortion if outside of whirl radius.
				'if (dist < '+ radius +') {',
					'dist = Math.pow('+ radius +' - dist, 2) / ' + radius + ';',

					'var angle = 2.0 * Math.PI * (dist / (' + radius + ' / ' + strength + '));',
					'xpos = (((x - ' + position[ 0 ] + ') * Math.cos(angle)) - ((y - ' + position[ 0 ] + ') * Math.sin(angle)) + ' + position[ 0 ] + ' + 0.5);',
					'ypos = (((y - ' + position[ 1 ] + ') * Math.cos(angle)) + ((x - ' + position[ 1 ] + ') * Math.sin(angle)) + ' + position[ 1 ] + ' + 0.5);',
				'} else {',
					'xpos = x;',
					'ypos = y;',
				'}',

				'var color = TG.Utils.getPixelBilinear( src, xpos, ypos, 0, width, height );'

			].join( '\n' );
		}
	} );

};

TG.Transform = function () {

    var offset = [ 0, 0 ];
    var angle = 0;
    var zoom = 1;
    var flipH = false;
    var flipV = false;

    return new TG.Program( {

        offset: function ( x, y ) {

            offset = [ x, y ];
            return this;
        },
        angle: function ( value ) {

            angle = TG.Utils.deg2rad( value );
            return this;
        },
        zoom: function ( value ) {

            if ( value <= 0 ) value = 1;
            zoom = value;

            return this;
        },
        flipH: function ( value ) {

        	flipH = value;
        	return this;
        },
        flipV: function ( value ) {

        	flipV = value;
        	return this;

        },
        getSource: function () {
            return [

            	'var x2 = x - width / 2;',
				'var y2 = y - height / 2;',

				's = x2 * (' + ( Math.cos( angle ) / zoom ) + ') + y2 * -(' + ( Math.sin( angle ) / zoom ) + ');',
				't = x2 * (' + ( Math.sin( angle ) / zoom ) + ') + y2 * (  ' + ( Math.cos( angle ) / zoom ) + ');',

				's += ' + offset[ 0 ] + ' + width /2;',
				't += ' + offset[ 1 ] + ' + height /2;',
	            'var color = TG.Utils.getPixelBilinear(src, ' + ( flipH ? '-' : '') + 's, ' + ( flipV ? '-' : '') + 't, 0, width, height);'

            ].join( '\n' );
        }
    } );

};

TG.Pixellate = function () {

	var pixelSize = [ 1, 1 ];

	return new TG.Program( {
		pixelSize: function ( width, height ) {

			if ( height === undefined ) height = width;
			pixelSize = [ width, height ];
			return this;
		},
		getSource: function () {
			return [

    			'var s = ' + pixelSize[ 0 ] + ' * Math.floor(x/' + pixelSize[ 0 ] + ');',
				'var t = ' + pixelSize[ 1 ] + ' * Math.floor(y/' + pixelSize[ 1 ] + ');',

				'var color = TG.Utils.getPixelNearest( src, s, t, 0, width, height );'

			].join( '\n' );
		}
	} );

};

TG.Utils = {

	smoothStep: function ( edge0, edge1, x ) {

		// Scale, bias and saturate x to 0..1 range
		x = TG.Utils.clamp( ( x - edge0 ) / ( edge1 - edge0 ), 0, 1 );

		// Evaluate polynomial
		return x * x * ( 3 - 2 * x );

	},

	distance: function( x0, y0, x1, y1 ) {

		var dx = x1 - x0, dy = y1 - y0;
		return Math.sqrt( dx * dx + dy * dy );

	},

	clamp: function( value, min, max ) {

		return Math.min( Math.max( value, min ), max );

	},

	getPixelNearest: function( pixels, x, y, offset, width, height ) {

        if ( y > height ) y -= height;
        if ( y < 0 ) y += height;
        if ( x > width ) x -= width;
        if ( x < 0 ) x += width;

		return pixels[ offset + Math.round( y ) * width * 4 + Math.round( x ) * 4 ];

	},

	getPixelBilinear: function( pixels, x, y, offset, width, height ) {

        if ( y > height ) y -= height;
        if ( y < 0 ) y += height;
        if ( x > width ) x -= width;
        if ( x < 0 ) x += width;

		var percentX = x - ( x ^ 0 );
		var percentX1 = 1.0 - percentX;
		var percentY = y - ( y ^ 0 );
		var fx4 = ( x ^ 0 ) * 4;
		var cx4 = fx4 + 4;
		var fy4 = ( y ^ 0 ) * 4;
		var cy4wo = ( fy4 + 4 ) * width + offset;
		var fy4wo = fy4 * width + offset;

		var top = pixels[ cy4wo + fx4 ] * percentX1 + pixels[ cy4wo + cx4 ] * percentX;
		var bottom = pixels[ fy4wo + fx4 ] * percentX1 + pixels[ fy4wo + cx4 ] * percentX;

		return top * percentY + bottom * ( 1.0 - percentY );

	},

	deg2rad: function ( deg ) {

		return deg * Math.PI / 180;

	}
};
<|endoftext|>


<commit_before>var sinon = require("sinon"),
  tharp = require("../index.js");

  var protoProperties = [{
    name: "@@normalize"
  }];

  var instanceProperties = [{
    name: "chains"
  },{
    name: "@@render"
  },{
    name: "offset"
  },{
    name: "orientation"
  }];

  // Doesn't actually do anything. We just spy on it.
  var mockChain = {
    devices: {
      "@@normalize": function(keyFrames) {
        if(keyFrames) {
          return keyFrames;
        }
      },
      "@@render": function(keyFrames) {
        if(keyFrames) {
          return keyFrames;
        }
      }
    },
    solve: function() {
      var angles = [1,0,1];
      return angles;
    }
  };

exports["Robot"] = {
  setUp: function(done) {

    this.robot = new tharp.Robot({
      chains: [mockChain, mockChain]
    });

    this.normalizeSpy = sinon.spy(mockChain.devices, "@@normalize");
    this.chainSolveSpy = sinon.spy(mockChain, "solve");
    this.solveSpy = sinon.spy(this.robot, "@@render");

    done();
  },

  tearDown: function(done) {
    this.normalizeSpy.restore();
    this.chainSolveSpy.restore();
    this.solveSpy.restore();
    done();
  },

  shape: function(test) {
    test.expect(protoProperties.length + instanceProperties.length);

    protoProperties.forEach(function(method) {
      test.equal(typeof this.robot[method.name], "function");
    }, this);

    instanceProperties.forEach(function(property) {
      test.notEqual(typeof this.robot[property.name], "undefined");
    }, this);

    test.done();

  },

  normalize: function(test) {

    test.expect(1);

    this.robot["@@normalize"]([
      [0, 1, 2, 3],
      [0, 1, 2, 3]
    ]);

    test.equal(this.normalizeSpy.callCount, 2);
    test.done();
  },

  render: function(test) {

    test.expect(2);

    this.robot["@@render"]([
      [0, 1, 2, 3],
      [0, 1, 2, 3]
    ]);

    test.equal(this.solveSpy.callCount, 1);
    test.equal(this.chainSolveSpy.callCount, 2);
    test.done();
  }
};
<commit_msg>Add normalize method on chain<commit_after>var sinon = require("sinon"),
  tharp = require("../index.js");

  var protoProperties = [{
    name: "@@normalize"
  }];

  var instanceProperties = [{
    name: "chains"
  },{
    name: "@@render"
  },{
    name: "offset"
  },{
    name: "orientation"
  }];

  // Doesn't actually do anything. We just spy on it.
  var mockChain = {
    devices: {
      "@@normalize": function(keyFrames) {
        if(keyFrames) {
          return keyFrames;
        }
      },
      "@@render": function(keyFrames) {
        if(keyFrames) {
          return keyFrames;
        }
      }
    },
    "@@normalize": function(keyFrames) {
      if(keyFrames) {
        return keyFrames;
      }
    },
    solve: function() {
      var angles = [1,0,1];
      return angles;
    }
  };

exports["Robot"] = {
  setUp: function(done) {

    this.robot = new tharp.Robot({
      chains: [mockChain, mockChain]
    });

    this.normalizeSpy = sinon.spy(mockChain.devices, "@@normalize");
    this.chainSolveSpy = sinon.spy(mockChain, "solve");
    this.solveSpy = sinon.spy(this.robot, "@@render");

    done();
  },

  tearDown: function(done) {
    this.normalizeSpy.restore();
    this.chainSolveSpy.restore();
    this.solveSpy.restore();
    done();
  },

  shape: function(test) {
    test.expect(protoProperties.length + instanceProperties.length);

    protoProperties.forEach(function(method) {
      test.equal(typeof this.robot[method.name], "function");
    }, this);

    instanceProperties.forEach(function(property) {
      test.notEqual(typeof this.robot[property.name], "undefined");
    }, this);

    test.done();

  },

  normalize: function(test) {

    test.expect(1);

    this.robot["@@normalize"]([
      [0, 1, 2, 3],
      [0, 1, 2, 3]
    ]);

    test.equal(this.normalizeSpy.callCount, 2);
    test.done();
  },

  render: function(test) {

    test.expect(2);

    this.robot["@@render"]([
      [0, 1, 2, 3],
      [0, 1, 2, 3]
    ]);

    test.equal(this.solveSpy.callCount, 1);
    test.equal(this.chainSolveSpy.callCount, 2);
    test.done();
  }
};
<|endoftext|>


<commit_before>var error_event = new Event('error_event');
var passing_event = new Event('passing_event');
var getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia; // So we don't have to keep checking for vendor prefixes.

function DiagnosticsTest() {
  this.webcams = null; // Should hold an array of webcam names
  this.webcamError = false; // Should we care about how many webcam failures there are, or should we just stop at the first?
  this.microphones = null; // Should hold an array of microphone names
  this.microphoneError = false;
  this.errors = new Array(); // Should be an array of errors
  this.warnings = new Array(); // Should be an array of warnings
  this.passing = new Array(); // Should be an array of passing messages
}

DiagnosticsTest.prototype.testWebRTCReadiness = function() {
  if (!!getUserMedia) {
    this.passing.push("Using a WebRTC-enabled browser.");
    document.dispatchEvent(passing_event);
  } else {
    this.errors.push("Not using a WebRTC-enabled browser.");
    document.dispatchEvent(erorr_event);
  }
  return !!getUserMedia;
}

/*
   findWebcams and findMicrophones would be much better suited to using
   navigator.getMediaDevices() as soon as it is available and ready.
*/

DiagnosticsTest.prototype.findWebcams = function() {
  // Find all connected and accessible webcams and store them in this.webcams
  // If none are found, put a meaningful and human-readable error message in this.errors
}

DiagnosticsTest.prototype.findMicrophones = function() {
  // Find all connected and accessible microphones and store them in this.microphones
  // If none are found, but a meaningful and human-readable error message in this.errors
}

// This is all we have to play with for now.
DiagnosticsTest.prototype.getWebcam = function() {
  var constraints = { video: true };
  getUserMedia.call(navigator, constraints, function(stream) {
    // Success
    this.passing.push("Able to reach a webcam.");
    document.dispatchEvent(passing_event);
    this.testWebcam(stream);
  }, function() {
    // Failure
    this.errors.push("Unable to reach a webcam. Is there one plugged in? Is it enabled?");
    document.dispatchEvent(error_event);
  });
}

// This is all we have to play with for now.
DiagnosticsTest.prototype.getMicrophone = function() {
  var constraints = { audio: true };
  getUserMedia(constraints, function(stream) {
    // Success
    this.testMicrophone(stream);
  }, function() {
    // Failure
    this.errors.push("Unable to reach a microphone. Is there one plugged in? Is it enabled?");
    document.dispatchEvent(error_event);
  });
}

DiagnosticsTest.prototype.webcamCount = function() {
  return this.webcams.length;
}

DiagnosticsTest.prototype.webcamNames = function() {
  return Object.keys(this.webcams);
}

DiagnosticsTest.prototype.microphoneCount = function() {
  return this.microphones.length;
}

DiagnosticsTest.prototype.microphoneNames = function() {
  return Object.keys(this.microphones);
}

DiagnosticsTest.prototype.testWebcam = function(webcam, display_element, echo_element) {
  // Attempt to access the webcam. If not, store an error.
  this.accessWebcam(webcam);
  // Attempt to displaya the webcam feed locally. If not, store an error.
  this.displayWebcam(webcam, display_element);
  // Attempt to echo the webcam feed back to ourselves via WebRTC, and ask if the user can see it. If not, store an error.
  this.echoWebcam(webcam, echo_element);
}

DiagnosticsTest.prototype.testWebcams = function(display_element) {
  for (webcam in this.webcams) {
    this.testWebcam(webcam, display_element);
  }
}

DiagnosticsTest.prototype.testMicrophone = function(microphone) {
  // Access microphone
  // Display a feedback bar
  // Attempt to echo the microphone audio back to the user
  // Ask user if they can hear themselves
}

DiagnosticsTest.prototype.accessWebcam = function(webcam) {
  // Attempt to access webcam
  // If error, put meaningful and human-readable error message in this.errors
}

DiagnosticsTest.prototype.displayWebcam = function(webcam, display_element) {
  // Attempt to display the webcam feed localling in specified display_element
  // If error, put meaningful and human-readable error message in this.errors
}

DiagnosticsTest.prototype.echoWebcam = function(webcam, echo_element) {
  // Attempt to use WebRTC to echo back locally to ourselves
  // Ask if user can see the echoed back feed
  // If error, put meaningful and human-readable error message in this.errors
}

DiagnosticsTest.prototype.accessMicrophone = function(microphone) {
  // Attempt to access the microphone
  // If error, put meaningful and human-readable error message in this.errors
}

DiagnosticsTest.prototype.displayMicrophone = function(microphone, display_element) {
  // Attempt to get feedback on microphone and display it as an indicator bar
  // Store the microphone element in the microphone object
  this.microphones.microphone += { display: new MicrophoneFeedbackBar() }
  // If error, put meaningful and human-readable error message in this.errors
}

DiagnosticsTest.prototype.finishTest = function() {
  // Summarize results
  // Generate score
  // Send results back to Mojo Lingo so we can display them like how iswebrtcreadyyet.com does because that's SO COOL (and so are we!)
}

// Will return an HTML element with the message formatted for display properly.
// type wants a string of 'passing', 'error', or 'warning'
DiagnosticsTest.prototype.displayMessage = function(message, type) {
  var div_class = "passing " + type;
  var html = "

" + message + "

";
  return html;
}

// Will create a feedback display bar. You must insert it somewhere.
function MicrophoneFeedbackBar() {
  this.level = 0; // Will hold percentage of volume.
  this.noiseColor = '#149bdf';
  this.element = "

";
  return this.element;
}

MicrophoneFeedbackBar.prototype.changeLevel = function(percentage) {
  if (percentage < 100) {
    percentage = percentage * 100;
  }
  this.level = percentage;
  $(this.element).css({ width: this.level + "%" });
}

MicrophoneFeedbackBar.prototype.color = function(hex_color) {
  this.color = hex_color;
  $(this.element).css({ color: this.color });
}

<commit_msg>Mini local test running.<commit_after>var error_event = new Event('error_event');
var passing_event = new Event('passing_event');
var getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia; // So we don't have to keep checking for vendor prefixes.

function DiagnosticsTest() {
  this.webcams = null; // Should hold an array of webcam names
  this.webcamError = false; // Should we care about how many webcam failures there are, or should we just stop at the first?
  this.microphones = null; // Should hold an array of microphone names
  this.microphoneError = false;
  this.errors = new Array(); // Should be an array of errors
  this.warnings = new Array(); // Should be an array of warnings
  this.passing = new Array(); // Should be an array of passing messages
}

DiagnosticsTest.prototype.testWebRTCReadiness = function() {
  if (!!getUserMedia) {
    this.passing.push("Using a WebRTC-enabled browser.");
    document.dispatchEvent(passing_event);
  } else {
    this.errors.push("Not using a WebRTC-enabled browser.");
    document.dispatchEvent(erorr_event);
  }
  return !!getUserMedia;
}

/*
   findWebcams and findMicrophones would be much better suited to using
   navigator.getMediaDevices() as soon as it is available and ready.
*/

DiagnosticsTest.prototype.findWebcams = function() {
  // Find all connected and accessible webcams and store them in this.webcams
  // If none are found, put a meaningful and human-readable error message in this.errors
}

DiagnosticsTest.prototype.findMicrophones = function() {
  // Find all connected and accessible microphones and store them in this.microphones
  // If none are found, but a meaningful and human-readable error message in this.errors
}

// This is all we have to play with for now.
DiagnosticsTest.prototype.getWebcam = function() {
  var scope = this;
  var constraints = { video: true };
  getUserMedia.call(navigator, constraints, function(stream) {
      // Success
      scope.passing.push("Able to reach a webcam.");
      document.dispatchEvent(passing_event);
      scope.testWebcam(stream);
  }, function() {
    // Failure
    scope.errors.push("Unable to reach a webcam. Did you allow access? Is there one plugged in? Is it enabled?");
    document.dispatchEvent(error_event);
  });
}

// This is all we have to play with for now.
DiagnosticsTest.prototype.getMicrophone = function() {
  var scope = this;
  var constraints = { audio: true };
  getUserMedia.call(navigator, constraints, function(stream) {
    // Success
    scope.passing.push("Able to reach a microphone.");
    document.dispatchEvent(passing_event);
    // scope.testMicrophone(stream);
  }, function() {
    // Failure
    scope.errors.push("Unable to reach a microphone. Is there one plugged in? Is it enabled?");
    document.dispatchEvent(error_event);
  });
}

DiagnosticsTest.prototype.webcamCount = function() {
  return this.webcams.length;
}

DiagnosticsTest.prototype.webcamNames = function() {
  return Object.keys(this.webcams);
}

DiagnosticsTest.prototype.microphoneCount = function() {
  return this.microphones.length;
}

DiagnosticsTest.prototype.microphoneNames = function() {
  return Object.keys(this.microphones);
}

DiagnosticsTest.prototype.testWebcam = function(webcam, display_element, echo_element) {
  // Attempt to access the webcam. If not, store an error.
  this.accessWebcam(webcam);
  // Attempt to displaya the webcam feed locally. If not, store an error.
  this.displayWebcam(webcam, display_element);
  // Attempt to echo the webcam feed back to ourselves via WebRTC, and ask if the user can see it. If not, store an error.
  this.echoWebcam(webcam, echo_element);
}

DiagnosticsTest.prototype.testWebcams = function(display_element) {
  for (webcam in this.webcams) {
    this.testWebcam(webcam, display_element);
  }
}

DiagnosticsTest.prototype.testMicrophone = function(microphone) {
  // Access microphone
  // Display a feedback bar
  // Attempt to echo the microphone audio back to the user
  // Ask user if they can hear themselves
}

DiagnosticsTest.prototype.accessWebcam = function(webcam) {
  // Attempt to access webcam
  // If error, put meaningful and human-readable error message in this.errors
}

DiagnosticsTest.prototype.displayWebcam = function(webcam, display_element) {
  // Attempt to display the webcam feed localling in specified display_element
  // If error, put meaningful and human-readable error message in this.errors
}

DiagnosticsTest.prototype.echoWebcam = function(webcam, echo_element) {
  // Attempt to use WebRTC to echo back locally to ourselves
  // Ask if user can see the echoed back feed
  // If error, put meaningful and human-readable error message in this.errors
}

DiagnosticsTest.prototype.accessMicrophone = function(microphone) {
  // Attempt to access the microphone
  // If error, put meaningful and human-readable error message in this.errors
}

DiagnosticsTest.prototype.displayMicrophone = function(microphone, display_element) {
  // Attempt to get feedback on microphone and display it as an indicator bar
  // Store the microphone element in the microphone object
  this.microphones.microphone += { display: new MicrophoneFeedbackBar() }
  // If error, put meaningful and human-readable error message in this.errors
}

DiagnosticsTest.prototype.finishTest = function() {
  // Summarize results
  // Generate score
  // Send results back to Mojo Lingo so we can display them like how iswebrtcreadyyet.com does because that's SO COOL (and so are we!)
}

// Will return an HTML element with the message formatted for display properly.
// type wants a string of 'passing', 'error', or 'warning'
DiagnosticsTest.prototype.displayMessage = function(message, type) {
  var div_class = "passing " + type;
  var html = "

" + message + "

";
  return html;
}

// Will create a feedback display bar. You must insert it somewhere.
function MicrophoneFeedbackBar() {
  this.level = 0; // Will hold percentage of volume.
  this.noiseColor = '#149bdf';
  this.element = "

";
  return this.element;
}

MicrophoneFeedbackBar.prototype.changeLevel = function(percentage) {
  if (percentage < 100) {
    percentage = percentage * 100;
  }
  this.level = percentage;
  $(this.element).css({ width: this.level + "%" });
}

MicrophoneFeedbackBar.prototype.color = function(hex_color) {
  this.color = hex_color;
  $(this.element).css({ color: this.color });
}

<|endoftext|>


<commit_before>import React, { Component } from 'react'
import { reduxForm, Field } from 'redux-form'
import {
  Button,
  Emoji,
  TextField
} from 'components'

import slackInviteValidation from './slackInviteValidation'

class SlackInviteForm extends Component {
  buttonState() {
    const {
      submitting,
      invalid,
      status
    } = this.props

    if (invalid) {
      return "disabled"
    } else if (submitting) {
      return "loading"
    } else {
      return status
    }
  }

  buttonText(status) {
    switch (status) {
    case "error":
      return (<Emoji type="thinking_face" />)
    case "success":
      return (Check your email for an invitation to your Slack account! <Emoji type="fisted_hand_sign" />)
    default:
      return "Get Your Hack Club Slack Account"
    }
  }

  render() {
    const { handleSubmit, style, status } = this.props

    return (
      <form style={style} onSubmit={handleSubmit}>
        <Field name="email" label="Email" placeholder="fiona@hackworth.com" component={TextField} />
        <Field name="username" label="Username" placeholder="fiona" component={TextField}/>
        <Field name="full_name" label="Full name" placeholder="Fiona Hackworth" component={TextField}/>
        <Field name="password" label="Password" placeholder="Dinosaur" component={TextField} type="password"/>

        <Button type="form" state={this.buttonState()}>
          {this.buttonText(status)}
        </Button>
      </form>
    )
  }
}

export default reduxForm({
  form: 'slackInviteForm',
  validate: slackInviteValidation
})(SlackInviteForm)
<commit_msg>Slack sign up form has dinosaur-themed placeholders<commit_after>import React, { Component } from 'react'
import { reduxForm, Field } from 'redux-form'
import {
  Button,
  Emoji,
  TextField
} from 'components'

import slackInviteValidation from './slackInviteValidation'

class SlackInviteForm extends Component {
  buttonState() {
    const {
      submitting,
      invalid,
      status
    } = this.props

    if (invalid) {
      return "disabled"
    } else if (submitting) {
      return "loading"
    } else {
      return status
    }
  }

  buttonText(status) {
    switch (status) {
    case "error":
      return (<Emoji type="thinking_face" />)
    case "success":
      return (Check your email for an invitation to your Slack account! <Emoji type="fisted_hand_sign" />)
    default:
      return "Get Your Hack Club Slack Account"
    }
  }

  render() {
    const { handleSubmit, style, status } = this.props

    return (
      <form style={style} onSubmit={handleSubmit}>
        <Field name="email" label="Email" placeholder="orpheus@hackclub.com" component={TextField} />
        <Field name="username" label="Username" placeholder="proforpheus" component={TextField} />
        <Field name="full_name" label="Full name" placeholder="Prophet Orpheus" component={TextField} />
        <Field name="password" label="Password" placeholder="LastDinosaur" component={TextField} type="password"/>

        <Button type="form" state={this.buttonState()}>
          {this.buttonText(status)}
        </Button>
      </form>
    )
  }
}

export default reduxForm({
  form: 'slackInviteForm',
  validate: slackInviteValidation
})(SlackInviteForm)
<|endoftext|>


<commit_before>import graphql from 'babel-plugin-relay/macro'
import { createFragmentContainer } from 'react-relay'

import Dashboard from 'js/components/Dashboard/DashboardComponent'

export default createFragmentContainer(Dashboard, {
  app: graphql`
    fragment DashboardContainer_app on App {
      campaign {
        isLive
      }
      ...UserMenuContainer_app
      ...TreePlantingCampaignContainer_app
    }
  `,
  user: graphql`
    fragment DashboardContainer_user on User
      # @tree-planting-campaign
      @argumentDefinitions(
        startTime: { type: "String" }
        endTime: { type: "String" }
      ) {
      id
      experimentActions {
        referralNotification
        searchIntro
      }
      joined
      searches
      tabs
      ...WidgetsContainer_user
      ...UserBackgroundImageContainer_user
      ...UserMenuContainer_user
      ...LogTabContainer_user
      ...LogAccountCreationContainer_user
      ...NewUserTourContainer_user
      ...AssignExperimentGroupsContainer_user
      ...TreePlantingCampaignContainer_user
    }
  `,
})
<commit_msg>Fix recruits query timeframe<commit_after>import graphql from 'babel-plugin-relay/macro'
import { createFragmentContainer } from 'react-relay'

import Dashboard from 'js/components/Dashboard/DashboardComponent'

export default createFragmentContainer(Dashboard, {
  app: graphql`
    fragment DashboardContainer_app on App {
      campaign {
        isLive
      }
      ...UserMenuContainer_app
      ...TreePlantingCampaignContainer_app
    }
  `,
  user: graphql`
    fragment DashboardContainer_user on User
      # @tree-planting-campaign
      @argumentDefinitions(
        startTime: { type: "String" }
        endTime: { type: "String" }
      ) {
      id
      experimentActions {
        referralNotification
        searchIntro
      }
      joined
      searches
      tabs
      ...WidgetsContainer_user
      ...UserBackgroundImageContainer_user
      ...UserMenuContainer_user
      ...LogTabContainer_user
      ...LogAccountCreationContainer_user
      ...NewUserTourContainer_user
      ...AssignExperimentGroupsContainer_user
      ...TreePlantingCampaignContainer_user
        @arguments(startTime: $startTime, endTime: $endTime)
    }
  `,
})
<|endoftext|>


<commit_before>(function($) {

    var formDiv;

    $.fn.dropdownFiller = function() {
        formDiv = this;
        $('select').each(function(index, value) {
            if ($(this).is(':empty')) {
                var masterName = $(this).attr('data-master');
                if (masterName) {
                    formDiv.loadData($(this));
                }
            }
        });

        return this;
    };

    $.fn.loadData = function(selectBox) {

        $.ajax({
            url: '/zols/master/' + selectBox.attr('data-master'),
            success: function(result) {
                $.each(result, function() {
                    selectBox.append($("<option />").val(this.name).text(this.label));
                });
                if (selectBox.attr('value')) {
                    selectBox.val(selectBox.attr('value'));
                }
            }
        });

        // Load From Data Store
        if (selectBox.is(':empty')) {
            $.ajax({
                url: '/zols/master/all/' + selectBox.attr('data-master'),
                success: function(result) {
                    $.each(result[selectBox.attr('data-master')], function() {
                        selectBox.append($("<option />").val(this.name).text(this.name));
                    });
                    if (selectBox.attr('value')) {
                        selectBox.val(selectBox.attr('value'));
                    }
                },
                error: function(error) {

                }
            });
        }

    };

}(jQuery));<commit_msg>External Url Context Path Issue<commit_after>(function($) {

    var formDiv;

    $.fn.dropdownFiller = function() {
        formDiv = this;
        $('select').each(function(index, value) {
            if ($(this).is(':empty')) {
                var masterName = $(this).attr('data-master');
                if (masterName) {
                    formDiv.loadData($(this));
                }
            }
        });

        return this;
    };

    $.fn.loadData = function(selectBox) {
        var contextpath = document.URL.substring(document.URL.indexOf('/',document.URL.indexOf('//')+2));
        contextpath = contextpath.substring(0,contextpath.indexOf('/',2));
        $.ajax({
            url: contextpath + '/master/' + selectBox.attr('data-master'),
            success: function(result) {
                $.each(result, function() {
                    selectBox.append($("<option />").val(this.name).text(this.label));
                });
                if (selectBox.attr('value')) {
                    selectBox.val(selectBox.attr('value'));
                }
            }
        });

        // Load From Data Store
        if (selectBox.is(':empty')) {
            $.ajax({
                url: contextpath + 'master/all/' + selectBox.attr('data-master'),
                success: function(result) {
                    $.each(result[selectBox.attr('data-master')], function() {
                        selectBox.append($("<option />").val(this.name).text(this.name));
                    });
                    if (selectBox.attr('value')) {
                        selectBox.val(selectBox.attr('value'));
                    }
                },
                error: function(error) {

                }
            });
        }

    };

}(jQuery));<|endoftext|>


<commit_before>'use strict';

var Grid = require('./Grid');
var Aud = require('./Audio');

function VUSpec(scene, options) {
  if (!options) {
    options = {};
  }

  var i;
  var j;

  this.node = scene.addChild()
    .setOrigin(0.5, 0.5, 0.5)
    .setAlign(0.5, 0.5, 0.5)
    .setMountPoint(0.5, 0.5, 0.5)
    .setSizeMode(1, 1, 1);

  this.id = this.node.addComponent(this);
  this.width = options.width || 8;
  this.height = options.height || 8;
  this.boxSize = options.boxSize || 25;
  this.ceil = options.ceil || 0.6;
  this.decay = options.decay || 0.8;

  this.grid = new Grid(this.node, {
    height: this.height,
    width: this.width,
    boxSize: this.boxSize
  });

  this.audio = new Aud();

  this.alphas = [];
  this.prevAlphas = [];

  for (i = 0; i < this.width; i ++) {
    this.alphas.push([]);
    this.prevAlphas.push([]);
    for (j = 0; j < this.height; j++) {
      this.alphas[i].push(0);
      this.prevAlphas[i].push(0);
    }
  }

  var colors = [];

  for (i = 0; i < this.width; i ++) {
    colors.push([0, 0, 0]);
    colors[i][0] = (0 + (1 / this.height * i)) * 255;
    colors[i][1] = (1 - (1 / this.height * i)) * 255;
  }

  for (i = 0; i < this.width; i ++) {
    this.grid.setColumnColor(i, colors);
  }

  for (i = 0; i < this.width; i ++) {
    this.grid.setColumnAlpha(i, this.alphas[i]);
  }

  this.node.requestUpdate(this.id);

  return this;
}

VUSpec.prototype.setColumnAlpha = function (fftVal, bin) {
  var segment = this.ceil / this.height;

  for (var i = 0; i < this.height; i++) {
    fftVal -= segment;
    if (fftVal >= segment) {
      this.alphas[bin][i] = 1;
    }
    else if (fftVal >= 0) {
      this.alphas[bin][i] = fftVal / segment;
    }
    else {
      this.alphas[bin][i] = 0;
    }
    this.alphas[bin][i] = this.alphas[bin][i] + this.prevAlphas[bin][i];
    this.prevAlphas[bin][i] = this.alphas[bin][i] * this.decay;
  }
  this.alphas[bin].reverse();
};

VUSpec.prototype.onUpdate = function (time) {
  var i, j;
  var fft = this.audio.getFFT();
  var freqs = [];
  var value;
  for (i = 0; i < fft.length; i++) {
    value = fft[i];
    freqs.push(value / 256);
  }

  var blockSize = freqs.length / this.width;
  var blocks = [];

  for (i = 0; i < this.width; i++) {
    blocks.push([]);
    blocks[i] = 0;
    for (j = 0; j < blockSize; j++) {
      blocks[i] += freqs[j + i * blockSize];
    }
    blocks[i] /= blockSize;
  }

  blocks.reverse();

  for (i = 0; i < this.width; i++) {
    this.setColumnAlpha(blocks[i], i);
    this.grid.setColumnAlpha(i, this.alphas[i]);
  }

  this.node.requestUpdateOnNextTick(this.id);
};

module.exports = VUSpec;
<commit_msg>Add a bit of rotation<commit_after>'use strict';

var Grid = require('./Grid');
var Aud = require('./Audio');

function VUSpec(scene, options) {
  if (!options) {
    options = {};
  }

  var i;
  var j;

  this.node = scene.addChild()
    .setOrigin(0.5, 0.5, 0.5)
    .setAlign(0.5, 0.5, 0.5)
    .setMountPoint(0.5, 0.5, 0.5)
    .setSizeMode(1, 1, 1);

  this.id = this.node.addComponent(this);
  this.width = options.width || 8;
  this.height = options.height || 8;
  this.boxSize = options.boxSize || 25;
  this.ceil = options.ceil || 0.6;
  this.decay = options.decay || 0.8;

  this.grid = new Grid(this.node, {
    height: this.height,
    width: this.width,
    boxSize: this.boxSize
  });

  this.audio = new Aud();

  this.alphas = [];
  this.prevAlphas = [];

  for (i = 0; i < this.width; i ++) {
    this.alphas.push([]);
    this.prevAlphas.push([]);
    for (j = 0; j < this.height; j++) {
      this.alphas[i].push(0);
      this.prevAlphas[i].push(0);
    }
  }

  var colors = [];

  for (i = 0; i < this.width; i ++) {
    colors.push([0, 0, 0]);
    colors[i][0] = (0 + (1 / this.height * i)) * 255;
    colors[i][1] = (1 - (1 / this.height * i)) * 255;
  }

  for (i = 0; i < this.width; i ++) {
    this.grid.setColumnColor(i, colors);
  }

  for (i = 0; i < this.width; i ++) {
    this.grid.setColumnAlpha(i, this.alphas[i]);
  }

  this.node.requestUpdate(this.id);

  return this;
}

VUSpec.prototype.setColumnAlpha = function (fftVal, bin) {
  var segment = this.ceil / this.height;

  for (var i = 0; i < this.height; i++) {
    fftVal -= segment;
    if (fftVal >= segment) {
      this.alphas[bin][i] = 1;
    }
    else if (fftVal >= 0) {
      this.alphas[bin][i] = fftVal / segment;
    }
    else {
      this.alphas[bin][i] = 0;
    }
    this.alphas[bin][i] = this.alphas[bin][i] + this.prevAlphas[bin][i];
    this.prevAlphas[bin][i] = this.alphas[bin][i] * this.decay;
  }
  this.alphas[bin].reverse();
};

VUSpec.prototype.onUpdate = function (time) {
  var i, j;
  var fft = this.audio.getFFT();
  var freqs = [];
  var value;
  for (i = 0; i < fft.length; i++) {
    value = fft[i];
    freqs.push(value / 256);
  }

  var blockSize = freqs.length / this.width;
  var blocks = [];

  for (i = 0; i < this.width; i++) {
    blocks.push([]);
    blocks[i] = 0;
    for (j = 0; j < blockSize; j++) {
      blocks[i] += freqs[j + i * blockSize];
    }
    blocks[i] /= blockSize;
  }

  blocks.reverse();

  for (i = 0; i < this.width; i++) {
    this.setColumnAlpha(blocks[i], i);
    this.grid.setColumnAlpha(i, this.alphas[i]);
  }

  this.node.setRotation(
    Math.sin(time / 1500) * 0.2,
    Math.sin(time / 750) * 0.2,
    Math.sin(time / 3000) * 0.2
  );

  this.node.requestUpdateOnNextTick(this.id);
};

module.exports = VUSpec;
<|endoftext|>


<commit_before>// ==UserScript==
// @name Douban Article Formatter
// @namespace DAF
// @description 豆瓣文章格式化脚本，能够过滤段落中的手动缩进，自动调整段落间距。
// @include /^https?://movie.douban.com/review/*/
// @include /^https?://www.douban.com/note/*/
// @include /^https?://book.douban.com/review/*/
// @include /^https?://music.douban.com/review/*/
// @version 1.1.3
// @author tranch
// ==/UserScript==

(function() {
    function GM_wait() {
        if (typeof window.jQuery == 'undefined') {
            setTimeout(GM_wait, 100);
        } else {
            main(jQuery);
        }
    }

    function main($) {
        var article, article_container;
        switch (location.host.split('.')[0]) {
            case 'movie':
                article_container = $('div[property="v:description"]');
                break;
            case 'book':
            case 'music':
                article_container = $('span[property="v:description"]');
                break;
            case 'www':
                article_container = $('div#link-report.note');
                break;
            default:
                return;
        }
        article = article_container.html().replace(/( |\s|\n){2,}/g, '');
        article = '
' + article.replace(/(
(\s|( )*)+)+/g, '

') + '
';
        article_container.addClass('article_description').html(article);
        $('head').append($('


<commit_before>var assert = require('chai').assert;
var utils   = require('../utils');
var Test = require("mocha/lib/test");

var suiteAnat = describe('utils.type.isAnat', function(){
    before(function(done) {
        var goodFilenames = ["/sub-15/anat/sub-15_inplaneT2.nii.gz",
            "/sub-15/ses-12/anat/sub-15_ses-12_inplaneT2.nii.gz",
            "/sub-16/anat/sub-16_T1w.nii.gz",
            "/sub-16/anat/sub-16_T1w.json",
            "/sub-16/anat/sub-16_run-01_T1w.nii.gz",
            "/sub-16/anat/sub-16_acq-highres_T1w.nii.gz",
            "/sub-16/anat/sub-16_rec-mc_T1w.nii.gz"
        ];

        goodFilenames.forEach(function (path) {
            suiteAnat.addTest(new Test("isAnat('" + path + "') === true", function (isdone){
                assert.equal(utils.type.isAnat(path), true);
                isdone();
            }));
        });

        var badFilenames = [
            "/sub-1/anat/sub-15_inplaneT2.nii.gz",
            "/sub-15/ses-12/anat/sub-15_inplaneT2.nii.gz",
            "/sub-16/anat/sub-16_T1.nii.gz",
            "blaaa.nii.gz",
            "/sub-16/anat/sub-16_run-second_T1w.nii.gz",
            "/sub-16/anat/sub-16_run-01_rec-mc_T1w.nii.gz"
        ];

        badFilenames.forEach(function (path) {
            suiteAnat.addTest(new Test("isAnat('" + path + "') === false", function (isdone){
                assert.equal(utils.type.isAnat(path), false);
                isdone();
            }));
        });
        done();
    });

    // we need to have at least one non-dynamic test
    return it('dummy test', function() {
        require('assert').ok(true);
    });
});

var suiteFunc = describe('utils.type.isFunc', function(){
    before(function(done) {
        var goodFilenames = [
            "/sub-15/func/sub-15_task-0back_bold.nii.gz",
            "/sub-15/ses-12/func/sub-15_ses-12_task-0back_bold.nii.gz",
            "/sub-16/func/sub-16_task-0back_bold.json",
            "/sub-16/func/sub-16_task-0back_run-01_bold.nii.gz",
            "/sub-16/func/sub-16_task-0back_acq-highres_bold.nii.gz",
            "/sub-16/func/sub-16_task-0back_rec-mc_bold.nii.gz"
        ];

        goodFilenames.forEach(function (path) {
            suiteFunc.addTest(new Test("isFunc('" + path + "') === true", function (isdone){
                assert.equal(utils.type.isFunc(path), true);
                isdone();
            }));
        });

        var badFilenames = [
            "/sub-1/func/sub-15_inplaneT2.nii.gz",
            "/sub-15/ses-12/func/sub-15_inplaneT2.nii.gz",
            "/sub-16/func/sub-16_T1.nii.gz",
            "blaaa.nii.gz",
            "/sub-16/func/sub-16_run-second_T1w.nii.gz",
            "/sub-16/func/sub-16_task-0-back_rec-mc_bold.nii.gz",
            "/sub-16/func/sub-16_run-01_rec-mc_T1w.nii.gz"
        ];

        badFilenames.forEach(function (path) {
            suiteFunc.addTest(new Test("isFunc('" + path + "') === false", function (isdone){
                assert.equal(utils.type.isFunc(path), false);
                isdone();
            }));
        });
        done();
    });

    // we need to have at least one non-dynamic test
    return it('dummy test', function() {
        require('assert').ok(true);
    });
});

var suiteTop = describe('utils.type.isTopLevel', function(){
    before(function(done) {
        var goodFilenames = ["/README",
            "/CHANGES",
            "/dataset_description.json",
            "/ses-pre_task-rest_bold.json",
            "/dwi.bval",
            "/dwi.bvec"
        ];

        goodFilenames.forEach(function (path) {
            suiteTop.addTest(new Test("isTopLevel('" + path + "') === true", function (isdone){
                assert.equal(utils.type.isTopLevel(path), true);
                isdone();
            }));
        });

        var badFilenames = [
            "/readme.txt",
            "/changelog",
            "/dataset_description.yml",
            "/ses.json"
        ];

        badFilenames.forEach(function (path) {
            suiteTop.addTest(new Test("isTopLevel('" + path + "') === false", function (isdone){
                assert.equal(utils.type.isTopLevel(path), false);
                isdone();
            }));
        });
        done();
    });

    // we need to have at least one non-dynamic test
    return it('dummy test', function() {
        require('assert').ok(true);
    });
});

var suiteSession = describe('utils.type.isSessionLevel', function(){
    before(function(done) {
        var goodFilenames = [
            "/sub-12/sub-12_scans.tsv",
            "/sub-12/ses-pre/sub-12_ses-pre_scans.tsv"
        ];

        goodFilenames.forEach(function (path) {
            suiteSession.addTest(new Test("isSessionLevel('" + path + "') === true", function (isdone){
                assert.equal(utils.type.isSessionLevel(path), true);
                isdone();
            }));
        });

        var badFilenames = ["/sub-12/sub-12.tsv",
            "/sub-12/ses-pre/sub-12_ses-pre_scan.tsv"];

        badFilenames.forEach(function (path) {
            suiteSession.addTest(new Test("isSessionLevel('" + path + "') === false", function (isdone){
                assert.equal(utils.type.isSessionLevel(path), false);
                isdone();
            }));
        });
        done();
    });

    // we need to have at least one non-dynamic test
    return it('dummy test', function() {
        require('assert').ok(true);
    });
});

var suiteDWI = describe('utils.type.isDWI', function(){
    before(function(done) {
        var goodFilenames = [
            "/sub-12/dwi/sub-12_dwi.nii.gz",
            "/sub-12/ses-pre/dwi/sub-12_ses-pre_dwi.nii.gz",
            "/sub-12/ses-pre/dwi/sub-12_ses-pre_dwi.bvec",
            "/sub-12/ses-pre/dwi/sub-12_ses-pre_dwi.bval"
        ];

        goodFilenames.forEach(function (path) {
            suiteDWI.addTest(new Test("isDWI('" + path + "') === true", function (isdone){
                assert.equal(utils.type.isDWI(path), true);
                isdone();
            }));
        });

        var badFilenames = ["/sub-12/sub-12.tsv",
            "/sub-12/ses-pre/sub-12_ses-pre_scan.tsv",
            "/sub-12/ses-pre/dwi/sub-12_ses-pre_dwi.bvecs",
            "/sub-12/ses-pre/dwi/sub-12_ses-pre_dwi.bvals"];

        badFilenames.forEach(function (path) {
            suiteDWI.addTest(new Test("isDWI('" + path + "') === false", function (isdone){
                assert.equal(utils.type.isDWI(path), false);
                isdone();
            }));
        });
        done();
    });

    // we need to have at least one non-dynamic test
    return it('dummy test', function() {
        require('assert').ok(true);
    });
});<commit_msg>Added tests for associated data checks<commit_after>var assert = require('chai').assert;
var utils   = require('../utils');
var Test = require("mocha/lib/test");

var suiteAnat = describe('utils.type.isAnat', function(){
    before(function(done) {
        var goodFilenames = ["/sub-15/anat/sub-15_inplaneT2.nii.gz",
            "/sub-15/ses-12/anat/sub-15_ses-12_inplaneT2.nii.gz",
            "/sub-16/anat/sub-16_T1w.nii.gz",
            "/sub-16/anat/sub-16_T1w.json",
            "/sub-16/anat/sub-16_run-01_T1w.nii.gz",
            "/sub-16/anat/sub-16_acq-highres_T1w.nii.gz",
            "/sub-16/anat/sub-16_rec-mc_T1w.nii.gz"
        ];

        goodFilenames.forEach(function (path) {
            suiteAnat.addTest(new Test("isAnat('" + path + "') === true", function (isdone){
                assert.equal(utils.type.isAnat(path), true);
                isdone();
            }));
        });

        var badFilenames = [
            "/sub-1/anat/sub-15_inplaneT2.nii.gz",
            "/sub-15/ses-12/anat/sub-15_inplaneT2.nii.gz",
            "/sub-16/anat/sub-16_T1.nii.gz",
            "blaaa.nii.gz",
            "/sub-16/anat/sub-16_run-second_T1w.nii.gz",
            "/sub-16/anat/sub-16_run-01_rec-mc_T1w.nii.gz"
        ];

        badFilenames.forEach(function (path) {
            suiteAnat.addTest(new Test("isAnat('" + path + "') === false", function (isdone){
                assert.equal(utils.type.isAnat(path), false);
                isdone();
            }));
        });
        done();
    });

    // we need to have at least one non-dynamic test
    return it('dummy test', function() {
        require('assert').ok(true);
    });
});

var suiteFunc = describe('utils.type.isFunc', function(){
    before(function(done) {
        var goodFilenames = [
            "/sub-15/func/sub-15_task-0back_bold.nii.gz",
            "/sub-15/ses-12/func/sub-15_ses-12_task-0back_bold.nii.gz",
            "/sub-16/func/sub-16_task-0back_bold.json",
            "/sub-16/func/sub-16_task-0back_run-01_bold.nii.gz",
            "/sub-16/func/sub-16_task-0back_acq-highres_bold.nii.gz",
            "/sub-16/func/sub-16_task-0back_rec-mc_bold.nii.gz"
        ];

        goodFilenames.forEach(function (path) {
            suiteFunc.addTest(new Test("isFunc('" + path + "') === true", function (isdone){
                assert.equal(utils.type.isFunc(path), true);
                isdone();
            }));
        });

        var badFilenames = [
            "/sub-1/func/sub-15_inplaneT2.nii.gz",
            "/sub-15/ses-12/func/sub-15_inplaneT2.nii.gz",
            "/sub-16/func/sub-16_T1.nii.gz",
            "blaaa.nii.gz",
            "/sub-16/func/sub-16_run-second_T1w.nii.gz",
            "/sub-16/func/sub-16_task-0-back_rec-mc_bold.nii.gz",
            "/sub-16/func/sub-16_run-01_rec-mc_T1w.nii.gz"
        ];

        badFilenames.forEach(function (path) {
            suiteFunc.addTest(new Test("isFunc('" + path + "') === false", function (isdone){
                assert.equal(utils.type.isFunc(path), false);
                isdone();
            }));
        });
        done();
    });

    // we need to have at least one non-dynamic test
    return it('dummy test', function() {
        require('assert').ok(true);
    });
});

var suiteTop = describe('utils.type.isTopLevel', function(){
    before(function(done) {
        var goodFilenames = ["/README",
            "/CHANGES",
            "/dataset_description.json",
            "/ses-pre_task-rest_bold.json",
            "/dwi.bval",
            "/dwi.bvec"
        ];

        goodFilenames.forEach(function (path) {
            suiteTop.addTest(new Test("isTopLevel('" + path + "') === true", function (isdone){
                assert.equal(utils.type.isTopLevel(path), true);
                isdone();
            }));
        });

        var badFilenames = [
            "/readme.txt",
            "/changelog",
            "/dataset_description.yml",
            "/ses.json"
        ];

        badFilenames.forEach(function (path) {
            suiteTop.addTest(new Test("isTopLevel('" + path + "') === false", function (isdone){
                assert.equal(utils.type.isTopLevel(path), false);
                isdone();
            }));
        });
        done();
    });

    // we need to have at least one non-dynamic test
    return it('dummy test', function() {
        require('assert').ok(true);
    });
});

var suiteSession = describe('utils.type.isSessionLevel', function(){
    before(function(done) {
        var goodFilenames = [
            "/sub-12/sub-12_scans.tsv",
            "/sub-12/ses-pre/sub-12_ses-pre_scans.tsv"
        ];

        goodFilenames.forEach(function (path) {
            suiteSession.addTest(new Test("isSessionLevel('" + path + "') === true", function (isdone){
                assert.equal(utils.type.isSessionLevel(path), true);
                isdone();
            }));
        });

        var badFilenames = ["/sub-12/sub-12.tsv",
            "/sub-12/ses-pre/sub-12_ses-pre_scan.tsv"];

        badFilenames.forEach(function (path) {
            suiteSession.addTest(new Test("isSessionLevel('" + path + "') === false", function (isdone){
                assert.equal(utils.type.isSessionLevel(path), false);
                isdone();
            }));
        });
        done();
    });

    // we need to have at least one non-dynamic test
    return it('dummy test', function() {
        require('assert').ok(true);
    });
});

var suiteDWI = describe('utils.type.isDWI', function(){
    before(function(done) {
        var goodFilenames = [
            "/sub-12/dwi/sub-12_dwi.nii.gz",
            "/sub-12/ses-pre/dwi/sub-12_ses-pre_dwi.nii.gz",
            "/sub-12/ses-pre/dwi/sub-12_ses-pre_dwi.bvec",
            "/sub-12/ses-pre/dwi/sub-12_ses-pre_dwi.bval"
        ];

        goodFilenames.forEach(function (path) {
            suiteDWI.addTest(new Test("isDWI('" + path + "') === true", function (isdone){
                assert.equal(utils.type.isDWI(path), true);
                isdone();
            }));
        });

        var badFilenames = ["/sub-12/sub-12.tsv",
            "/sub-12/ses-pre/sub-12_ses-pre_scan.tsv",
            "/sub-12/ses-pre/dwi/sub-12_ses-pre_dwi.bvecs",
            "/sub-12/ses-pre/dwi/sub-12_ses-pre_dwi.bvals"];

        badFilenames.forEach(function (path) {
            suiteDWI.addTest(new Test("isDWI('" + path + "') === false", function (isdone){
                assert.equal(utils.type.isDWI(path), false);
                isdone();
            }));
        });
        done();
    });

    // we need to have at least one non-dynamic test
    return it('dummy test', function() {
        require('assert').ok(true);
    });
});

var suitedAssociated = describe('utils.type.isAssociatedData', function () {
    it('should return false for unknown root directories', function () {
        var badFilenames = [
            "/images/picture.jpeg",
            "/temporary/test.json"
        ];

        badFilenames.forEach(function (path) {
            assert.equal(utils.type.isAssociatedData(path), false);
        });
    });

    it('should return true for associated data directories and any files within', function () {
        var goodFilenames = [
            "/code/test-script.py",
            "/derivatives/sub-01_QA.pdf",
            "/sourcedata/sub-01_ses-01_bold.dcm",
            "/stimuli/text.pdf"
        ];

        goodFilenames.forEach(function (path) {
            assert(utils.type.isAssociatedData(path));
        });

    });
});<|endoftext|>


<commit_before>/**
 * @author Mugen87 / https://github.com/Mugen87
 * @author mrdoob / http://mrdoob.com/
 */

THREE.Lensflare = function () {

	THREE.Mesh.call( this, THREE.Lensflare.Geometry, new THREE.MeshBasicMaterial( { opacity: 0, transparent: true } ) );

	this.type = 'Lensflare';
	this.frustumCulled = false;
	this.renderOrder = Infinity;

	//

	var positionScreen = new THREE.Vector3();

	// textures

	var tempMap = new THREE.DataTexture( new Uint8Array( 16 * 16 * 3 ), 16, 16, THREE.RGBFormat );
	tempMap.minFilter = THREE.NearestFilter;
	tempMap.magFilter = THREE.NearestFilter;
	tempMap.wrapS = THREE.ClampToEdgeWrapping;
	tempMap.wrapT = THREE.ClampToEdgeWrapping;
	tempMap.needsUpdate = true;

	var occlusionMap = new THREE.DataTexture( new Uint8Array( 16 * 16 * 3 ), 16, 16, THREE.RGBFormat );
	occlusionMap.minFilter = THREE.NearestFilter;
	occlusionMap.magFilter = THREE.NearestFilter;
	occlusionMap.wrapS = THREE.ClampToEdgeWrapping;
	occlusionMap.wrapT = THREE.ClampToEdgeWrapping;
	occlusionMap.needsUpdate = true;

	// material

	var geometry = THREE.Lensflare.Geometry;

	var shader = THREE.Lensflare.Shader;

	var material1a = new THREE.RawShaderMaterial( {
		uniforms: {
			'scale': { value: null },
			'screenPosition': { value: null }
		},
		vertexShader: [

			'precision highp float;',

			'uniform vec3 screenPosition;',
			'uniform vec2 scale;',

			'attribute vec3 position;',

			'void main() {',

			'	gl_Position = vec4( position.xy * scale + screenPosition.xy, screenPosition.z, 1.0 );',

			'}'

		].join( '\n' ),
		fragmentShader: [

			'precision highp float;',

			'void main() {',

			'	gl_FragColor = vec4( 1.0, 0.0, 1.0, 1.0 );',

			'}'

		].join( '\n' ),
		depthTest: true,
		depthWrite: false,
		transparent: false
	} );

	var material1b = new THREE.RawShaderMaterial( {
		uniforms: {
			'map': { value: tempMap },
			'scale': { value: null },
			'screenPosition': { value: null }
		},
		vertexShader: [

			'precision highp float;',

			'uniform vec3 screenPosition;',
			'uniform vec2 scale;',

			'attribute vec3 position;',
			'attribute vec2 uv;',

			'varying vec2 vUV;',

			'void main() {',

			'	vUV = uv;',

			'	gl_Position = vec4( position.xy * scale + screenPosition.xy, screenPosition.z, 1.0 );',

			'}'

		].join( '\n' ),
		fragmentShader: [

			'precision highp float;',

			'uniform sampler2D map;',

			'varying vec2 vUV;',

			'void main() {',

			'	gl_FragColor = texture2D( map, vUV );',

			'}'

		].join( '\n' ),
		depthTest: false,
		depthWrite: false,
		transparent: false
	} );

	// the following object is used for occlusionMap generation

	var mesh1 = new THREE.Mesh( geometry, material1a );

	//

	this.elements = [];

	var shader = THREE.LensflareElement.Shader;

	var material2 = new THREE.RawShaderMaterial( {
		uniforms: {
			'map': { value: null },
			'occlusionMap': { value: occlusionMap },
			'color': { value: new THREE.Color( 0xffffff ) },
			'scale': { value: new THREE.Vector2() },
			'screenPosition': { value: new THREE.Vector3() }
		},
		vertexShader: shader.vertexShader,
		fragmentShader: shader.fragmentShader,
		blending: THREE.AdditiveBlending,
		transparent: true,
		depthWrite: false
	} );

	var mesh2 = new THREE.Mesh( geometry, material2 );

	this.addElement = function ( element ) {

		this.elements.push( element );

	};

	//

	var scale = new THREE.Vector2();
	var screenPositionPixels = new THREE.Vector2();
	var validArea = new THREE.Box2();
	var viewport = new THREE.Vector4();

	this.onBeforeRender = function ( renderer, scene, camera ) {

		viewport.copy( renderer.getCurrentViewport() );

		var invAspect = viewport.w / viewport.z;
		var halfViewportWidth = viewport.z / 2.0;
		var halfViewportHeight = viewport.w / 2.0;

		var size = 16 / viewport.w;
		scale.set( size * invAspect, size );

		validArea.min.set( viewport.x, viewport.y );
		validArea.max.set( viewport.x + ( viewport.z - 16 ), viewport.y + ( viewport.w - 16 ) );

		// calculate position in screen space

		positionScreen.setFromMatrixPosition( this.matrixWorld );

		positionScreen.applyMatrix4( camera.matrixWorldInverse );
		positionScreen.applyMatrix4( camera.projectionMatrix );

		// horizontal and vertical coordinate of the lower left corner of the pixels to copy

		screenPositionPixels.x = viewport.x + ( positionScreen.x * halfViewportWidth ) + halfViewportWidth - 8;
		screenPositionPixels.y = viewport.y + ( positionScreen.y * halfViewportHeight ) + halfViewportHeight - 8;

		// screen cull

		if ( validArea.containsPoint( screenPositionPixels ) ) {

			// save current RGB to temp texture

			renderer.copyFramebufferToTexture( screenPositionPixels, tempMap );

			// render pink quad

			var uniforms = material1a.uniforms;
			uniforms.scale.value = scale;
			uniforms.screenPosition.value = positionScreen;

			renderer.renderBufferDirect( camera, null, geometry, material1a, mesh1, null );

			// copy result to occlusionMap

			renderer.copyFramebufferToTexture( screenPositionPixels, occlusionMap );

			// restore graphics

			var uniforms = material1b.uniforms;
			uniforms.scale.value = scale;
			uniforms.screenPosition.value = positionScreen;

			renderer.renderBufferDirect( camera, null, geometry, material1b, mesh1, null );

			// render elements

			var vecX = - positionScreen.x * 2;
			var vecY = - positionScreen.y * 2;

			for ( var i = 0, l = this.elements.length; i < l; i ++ ) {

				var element = this.elements[ i ];

				var uniforms = material2.uniforms;

				uniforms.color.value.copy( element.color );
				uniforms.map.value = element.texture;
				uniforms.screenPosition.value.x = positionScreen.x + vecX * element.distance;
				uniforms.screenPosition.value.y = positionScreen.y + vecY * element.distance;

				var size = element.size / viewport.w;
				var invAspect = viewport.w / viewport.z;

				uniforms.scale.value.set( size * invAspect, size );

				material2.uniformsNeedUpdate = true;

				renderer.renderBufferDirect( camera, null, geometry, material2, mesh2, null );

			}

		}

	};

	this.dispose = function () {

		material1a.dispose();
		material1b.dispose();
		material2.dispose();

		tempMap.dispose();
		occlusionMap.dispose();

	};

};

THREE.Lensflare.prototype = Object.create( THREE.Mesh.prototype );
THREE.Lensflare.prototype.constructor = THREE.Lensflare;
THREE.Lensflare.prototype.isLensflare = true;

//

THREE.LensflareElement = function ( texture, size, distance, color ) {

	this.texture = texture;
	this.size = size || 1;
	this.distance = distance || 0;
	this.color = color || new THREE.Color( 0xffffff );

};

THREE.LensflareElement.Shader = {

	uniforms: {

		'map': { value: null },
		'occlusionMap': { value: null },
		'color': { value: null },
		'scale': { value: null },
		'screenPosition': { value: null }

	},

	vertexShader: [

		'precision highp float;',

		'uniform vec3 screenPosition;',
		'uniform vec2 scale;',

		'uniform sampler2D occlusionMap;',

		'attribute vec3 position;',
		'attribute vec2 uv;',

		'varying vec2 vUV;',
		'varying float vVisibility;',

		'void main() {',

		'	vUV = uv;',

		'	vec2 pos = position.xy;',

		'	vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );',
		'	visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );',
		'	visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );',
		'	visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );',
		'	visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );',
		'	visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );',
		'	visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );',
		'	visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );',
		'	visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );',

		'	vVisibility =        visibility.r / 9.0;',
		'	vVisibility *= 1.0 - visibility.g / 9.0;',
		'	vVisibility *=       visibility.b / 9.0;',

		'	gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );',

		'}'

	].join( '\n' ),

	fragmentShader: [

		'precision highp float;',

		'uniform sampler2D map;',
		'uniform vec3 color;',

		'varying vec2 vUV;',
		'varying float vVisibility;',

		'void main() {',

		'	vec4 texture = texture2D( map, vUV );',
		'	texture.a *= vVisibility;',
		'	gl_FragColor = texture;',
		'	gl_FragColor.rgb *= color;',

		'}'

	].join( '\n' )

};

THREE.Lensflare.Geometry = ( function () {

	var geometry = new THREE.BufferGeometry();

	var float32Array = new Float32Array( [
		- 1, - 1, 0, 0, 0,
		1, - 1, 0, 1, 0,
		1, 1, 0, 1, 1,
		- 1, 1, 0, 0, 1
	] );

	var interleavedBuffer = new THREE.InterleavedBuffer( float32Array, 5 );

	geometry.setIndex( [ 0, 1, 2,	0, 2, 3 ] );
	geometry.addAttribute( 'position', new THREE.InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
	geometry.addAttribute( 'uv', new THREE.InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );

	return geometry;

} )();
<commit_msg>Update Lensflare.js<commit_after>/**
 * @author Mugen87 / https://github.com/Mugen87
 * @author mrdoob / http://mrdoob.com/
 */

THREE.Lensflare = function () {

	THREE.Mesh.call( this, THREE.Lensflare.Geometry, new THREE.MeshBasicMaterial( { opacity: 0, transparent: true } ) );

	this.type = 'Lensflare';
	this.frustumCulled = false;
	this.renderOrder = Infinity;

	//

	var positionScreen = new THREE.Vector3();

	// textures

	var tempMap = new THREE.DataTexture( new Uint8Array( 16 * 16 * 3 ), 16, 16, THREE.RGBFormat );
	tempMap.minFilter = THREE.NearestFilter;
	tempMap.magFilter = THREE.NearestFilter;
	tempMap.wrapS = THREE.ClampToEdgeWrapping;
	tempMap.wrapT = THREE.ClampToEdgeWrapping;
	tempMap.needsUpdate = true;

	var occlusionMap = new THREE.DataTexture( new Uint8Array( 16 * 16 * 3 ), 16, 16, THREE.RGBFormat );
	occlusionMap.minFilter = THREE.NearestFilter;
	occlusionMap.magFilter = THREE.NearestFilter;
	occlusionMap.wrapS = THREE.ClampToEdgeWrapping;
	occlusionMap.wrapT = THREE.ClampToEdgeWrapping;
	occlusionMap.needsUpdate = true;

	// material

	var geometry = THREE.Lensflare.Geometry;

	var shader = THREE.Lensflare.Shader;

	var material1a = new THREE.RawShaderMaterial( {
		uniforms: {
			'scale': { value: null },
			'screenPosition': { value: null }
		},
		vertexShader: [

			'precision highp float;',

			'uniform vec3 screenPosition;',
			'uniform vec2 scale;',

			'attribute vec3 position;',

			'void main() {',

			'	gl_Position = vec4( position.xy * scale + screenPosition.xy, screenPosition.z, 1.0 );',

			'}'

		].join( '\n' ),
		fragmentShader: [

			'precision highp float;',

			'void main() {',

			'	gl_FragColor = vec4( 1.0, 0.0, 1.0, 1.0 );',

			'}'

		].join( '\n' ),
		depthTest: true,
		depthWrite: false,
		transparent: false
	} );

	var material1b = new THREE.RawShaderMaterial( {
		uniforms: {
			'map': { value: tempMap },
			'scale': { value: null },
			'screenPosition': { value: null }
		},
		vertexShader: [

			'precision highp float;',

			'uniform vec3 screenPosition;',
			'uniform vec2 scale;',

			'attribute vec3 position;',
			'attribute vec2 uv;',

			'varying vec2 vUV;',

			'void main() {',

			'	vUV = uv;',

			'	gl_Position = vec4( position.xy * scale + screenPosition.xy, screenPosition.z, 1.0 );',

			'}'

		].join( '\n' ),
		fragmentShader: [

			'precision highp float;',

			'uniform sampler2D map;',

			'varying vec2 vUV;',

			'void main() {',

			'	gl_FragColor = texture2D( map, vUV );',

			'}'

		].join( '\n' ),
		depthTest: false,
		depthWrite: false,
		transparent: false
	} );

	// the following object is used for occlusionMap generation

	var mesh1 = new THREE.Mesh( geometry, material1a );

	//

	elements = [];

	var shader = THREE.LensflareElement.Shader;

	var material2 = new THREE.RawShaderMaterial( {
		uniforms: {
			'map': { value: null },
			'occlusionMap': { value: occlusionMap },
			'color': { value: new THREE.Color( 0xffffff ) },
			'scale': { value: new THREE.Vector2() },
			'screenPosition': { value: new THREE.Vector3() }
		},
		vertexShader: shader.vertexShader,
		fragmentShader: shader.fragmentShader,
		blending: THREE.AdditiveBlending,
		transparent: true,
		depthWrite: false
	} );

	var mesh2 = new THREE.Mesh( geometry, material2 );

	this.addElement = function ( element ) {

		elements.push( element );

	};

	//

	var scale = new THREE.Vector2();
	var screenPositionPixels = new THREE.Vector2();
	var validArea = new THREE.Box2();
	var viewport = new THREE.Vector4();

	this.onBeforeRender = function ( renderer, scene, camera ) {

		viewport.copy( renderer.getCurrentViewport() );

		var invAspect = viewport.w / viewport.z;
		var halfViewportWidth = viewport.z / 2.0;
		var halfViewportHeight = viewport.w / 2.0;

		var size = 16 / viewport.w;
		scale.set( size * invAspect, size );

		validArea.min.set( viewport.x, viewport.y );
		validArea.max.set( viewport.x + ( viewport.z - 16 ), viewport.y + ( viewport.w - 16 ) );

		// calculate position in screen space

		positionScreen.setFromMatrixPosition( this.matrixWorld );

		positionScreen.applyMatrix4( camera.matrixWorldInverse );
		positionScreen.applyMatrix4( camera.projectionMatrix );

		// horizontal and vertical coordinate of the lower left corner of the pixels to copy

		screenPositionPixels.x = viewport.x + ( positionScreen.x * halfViewportWidth ) + halfViewportWidth - 8;
		screenPositionPixels.y = viewport.y + ( positionScreen.y * halfViewportHeight ) + halfViewportHeight - 8;

		// screen cull

		if ( validArea.containsPoint( screenPositionPixels ) ) {

			// save current RGB to temp texture

			renderer.copyFramebufferToTexture( screenPositionPixels, tempMap );

			// render pink quad

			var uniforms = material1a.uniforms;
			uniforms.scale.value = scale;
			uniforms.screenPosition.value = positionScreen;

			renderer.renderBufferDirect( camera, null, geometry, material1a, mesh1, null );

			// copy result to occlusionMap

			renderer.copyFramebufferToTexture( screenPositionPixels, occlusionMap );

			// restore graphics

			var uniforms = material1b.uniforms;
			uniforms.scale.value = scale;
			uniforms.screenPosition.value = positionScreen;

			renderer.renderBufferDirect( camera, null, geometry, material1b, mesh1, null );

			// render elements

			var vecX = - positionScreen.x * 2;
			var vecY = - positionScreen.y * 2;

			for ( var i = 0, l = elements.length; i < l; i ++ ) {

				var element = elements[ i ];

				var uniforms = material2.uniforms;

				uniforms.color.value.copy( element.color );
				uniforms.map.value = element.texture;
				uniforms.screenPosition.value.x = positionScreen.x + vecX * element.distance;
				uniforms.screenPosition.value.y = positionScreen.y + vecY * element.distance;

				var size = element.size / viewport.w;
				var invAspect = viewport.w / viewport.z;

				uniforms.scale.value.set( size * invAspect, size );

				material2.uniformsNeedUpdate = true;

				renderer.renderBufferDirect( camera, null, geometry, material2, mesh2, null );

			}

		}

	};

	this.dispose = function () {

		material1a.dispose();
		material1b.dispose();
		material2.dispose();

		tempMap.dispose();
		occlusionMap.dispose();

		for ( var i = 0, l = elements.length; i < l; i ++ ) {
			elements[i].texture.dispose();
		}

	};

};

THREE.Lensflare.prototype = Object.create( THREE.Mesh.prototype );
THREE.Lensflare.prototype.constructor = THREE.Lensflare;
THREE.Lensflare.prototype.isLensflare = true;

//

THREE.LensflareElement = function ( texture, size, distance, color ) {

	this.texture = texture;
	this.size = size || 1;
	this.distance = distance || 0;
	this.color = color || new THREE.Color( 0xffffff );

};

THREE.LensflareElement.Shader = {

	uniforms: {

		'map': { value: null },
		'occlusionMap': { value: null },
		'color': { value: null },
		'scale': { value: null },
		'screenPosition': { value: null }

	},

	vertexShader: [

		'precision highp float;',

		'uniform vec3 screenPosition;',
		'uniform vec2 scale;',

		'uniform sampler2D occlusionMap;',

		'attribute vec3 position;',
		'attribute vec2 uv;',

		'varying vec2 vUV;',
		'varying float vVisibility;',

		'void main() {',

		'	vUV = uv;',

		'	vec2 pos = position.xy;',

		'	vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );',
		'	visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );',
		'	visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );',
		'	visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );',
		'	visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );',
		'	visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );',
		'	visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );',
		'	visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );',
		'	visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );',

		'	vVisibility =        visibility.r / 9.0;',
		'	vVisibility *= 1.0 - visibility.g / 9.0;',
		'	vVisibility *=       visibility.b / 9.0;',

		'	gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );',

		'}'

	].join( '\n' ),

	fragmentShader: [

		'precision highp float;',

		'uniform sampler2D map;',
		'uniform vec3 color;',

		'varying vec2 vUV;',
		'varying float vVisibility;',

		'void main() {',

		'	vec4 texture = texture2D( map, vUV );',
		'	texture.a *= vVisibility;',
		'	gl_FragColor = texture;',
		'	gl_FragColor.rgb *= color;',

		'}'

	].join( '\n' )

};

THREE.Lensflare.Geometry = ( function () {

	var geometry = new THREE.BufferGeometry();

	var float32Array = new Float32Array( [
		- 1, - 1, 0, 0, 0,
		1, - 1, 0, 1, 0,
		1, 1, 0, 1, 1,
		- 1, 1, 0, 0, 1
	] );

	var interleavedBuffer = new THREE.InterleavedBuffer( float32Array, 5 );

	geometry.setIndex( [ 0, 1, 2,	0, 2, 3 ] );
	geometry.addAttribute( 'position', new THREE.InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
	geometry.addAttribute( 'uv', new THREE.InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );

	return geometry;

} )();
<|endoftext|>


<commit_before>/**
 * datatable.js
 * @author Vinit Kumar
 */

var myApp = angular.module('myApp', []);

myApp.service('datatableService', function($http){
	return {
		getData : function(size) {
			return $http({
				url: 'data/datatable.json',
				method: 'GET'
			});
		}
	}
});

myApp.controller('datatableController', function($scope, datatableService){
	$scope.rowList = {};
	$scope.colDef = [{'fname':'First Name'}, {'lname':'Last Name'}, {'project':'Project'}, {'designation':'Designation'}];

	datatableService.getData().then(function(response){
		$scope.rowList = response.data;
	});
});

myApp.directive('dTable', function($document, $filter) {
	return {
		restrict: 'E',
		transclude: true,
		scope: {
			colDef: '=',
			rowList: "=",
			sortable: "@"
		},
		link: function (scope, element, attrs) {
			scope.sortKey = [];

			// To sort the list
			scope.sortByKey = function(key){

				if(scope.sortKey[key] !== undefined){
					// If key exist, Reverse the existing order
					scope.sortKey[key] = !scope.sortKey[key];
				}else{
					// Remove existing key and add new key
					scope.sortKey = [];
					scope.sortKey[key] = false;
				}
				scope.reverse = scope.sortKey[key];
				scope.rowList = $filter('orderBy')(scope.rowList, key, scope.reverse);
			}

		},
		templateUrl: 'templates/datatable.html'
	}
});

<commit_msg>Update datatable.js<commit_after>/**
 * datatable.js
 * @author Vinit Kumar
 */

var myApp = angular.module('myApp', []);

myApp.service('datatableService', function($http){
	return {
		getData : function(size) {
			return $http({
				url: 'data/datatable.json',
				method: 'GET'
			});
		}
	}
});

myApp.controller('datatableController', function($scope, datatableService){
	$scope.rowList = {};
	$scope.colDef = [{'fname':'First Name'}, {'lname':'Last Name'}, {'project':'Project'}, {'designation':'Designation'}];

	datatableService.getData().then(function(response){
		$scope.rowList = response.data;
	});
});

myApp.directive('dTable', function($document, $filter) {
	return {
		restrict: 'E',
		transclude: true,
		scope: {
			colDef: '=',
			rowList: "=",
			sortable: "="
		},
		link: function (scope, element, attrs) {
			scope.sortKey = [];

			// To sort the list
			scope.sortByKey = function(key){

				if(scope.sortKey[key] !== undefined){
					// If key exist, Reverse the existing order
					scope.sortKey[key] = !scope.sortKey[key];
				}else{
					// Remove existing key and add new key
					scope.sortKey = [];
					scope.sortKey[key] = false;
				}
				scope.reverse = scope.sortKey[key];
				scope.rowList = $filter('orderBy')(scope.rowList, key, scope.reverse);
			}

		},
		templateUrl: 'templates/datatable.html'
	}
});

<|endoftext|>


<commit_before>var Zanimo = (function () {

    var VERSION = "0.0.0",
        kDelta = 20;

    var Z = function (domElt) {
        var d = Zanimo.async.defer();
        d.resolve(domElt);
        return d.promise;
    };

    Z.delay = function (ms) {
        var d = Zanimo.async.defer();
        setTimeout(function () { d.resolve(ms); }, ms);
        return d.promise;
    };

    Z.transition = function (domElt, attr, value, duration, timing) {
        var d = Zanimo.async.defer(),
            pos = -1,
            done = false;

        var cb = function (evt) {
            done = true;
            d.resolve(domElt);
            domElt.removeEventListener(
                Zanimo.utils.prefix.evt,
                cb,
                false
            );
        };

        domElt.addEventListener(Zanimo.utils.prefix.evt, cb, false);

        Zanimo.delay(duration + kDelta)
              .then(
                function () {
                    if (!done) {
                        d.resolve(Zanimo.async.reject("Transition error."));
                    }
              });

        pos = Zanimo.utils._add(domElt, Zanimo.utils._getAttr(attr));
        Zanimo.utils._setAt(domElt, "TransitionDuration", duration + "ms", pos);
        Zanimo.utils._setAt(domElt, "TransitionTimingFunction", timing || "linear", pos);

        domElt.style[Zanimo.utils._getAttrName(attr)] = value;
        return d.promise;
    };

    return Z;
})();
<commit_msg>integrating Z func def in first var definition...<commit_after>var Zanimo = (function () {

    var VERSION = "0.0.0",
        kDelta = 20,

        Z = function (domElt) {
            var d = Zanimo.async.defer();
            d.resolve(domElt);
            return d.promise;
        };

    Z.delay = function (ms) {
        var d = Zanimo.async.defer();
        setTimeout(function () { d.resolve(ms); }, ms);
        return d.promise;
    };

    Z.transition = function (domElt, attr, value, duration, timing) {
        var d = Zanimo.async.defer(),
            pos = -1,
            done = false;

        var cb = function (evt) {
            done = true;
            d.resolve(domElt);
            domElt.removeEventListener(
                Zanimo.utils.prefix.evt,
                cb,
                false
            );
        };

        domElt.addEventListener(Zanimo.utils.prefix.evt, cb, false);

        Zanimo.delay(duration + kDelta)
              .then( function () {
                  if (!done) {
                      d.resolve(Zanimo.async.reject("Transition error."));
                  }
              });

        pos = Zanimo.utils._add(domElt, Zanimo.utils._getAttr(attr));
        Zanimo.utils._setAt(domElt, "TransitionDuration", duration + "ms", pos);
        Zanimo.utils._setAt(domElt, "TransitionTimingFunction", timing || "linear", pos);

        domElt.style[Zanimo.utils._getAttrName(attr)] = value;
        return d.promise;
    };

    return Z;
})();
<|endoftext|>


<commit_before><commit_msg>Minor style fix in async-await example<commit_after><|endoftext|>


<commit_before>'use strict'
/*!
 * module dependencies
 */
const Contentstack = require('../../dist/node/contentstack.js');

/*
 * Example ContentstackDemo Class
 * */

class ContentstackDemo {
    constructor(config) {
        config = config || { 'api_key': 'blt123something', 'devlivery_token': 'blt123something', 'environment': 'development',  }
            // Initialize the Contentstackstack
            //console.log("datattatata", Contentstack.Region.EUROPE)

        this.Stack = Contentstack.Stack(config);
    }

    /**
     * getEntries
     * @description  : getEntries is used to get the entries of the specified entries
     * @params       : contentTypeUid {string} - Content-Type from which entries to be retrieved
     * @return       : Result {Promise}
     */
    getEntries(contentTypeUid) {
        contentTypeUid = contentTypeUid || 'source'
        return this.Stack.ContentType('test').Query().includeContentType().toJSON().find()
        //return this.Stack.getContentTypes(contentTypeUid)

    }

    /**
     * getEntries
     * @description  : getEntries is used to get the entries of the specified entries
     * @params       : contentTypeUid {string} - Content-Type from which entries to be retrieved
     * @return       : Result {Promise}
     */
    getLastActivities() {
        //contentTypeUid = contentTypeUid || 'source'
        return this.Stack.getLastActivities()
    }

    /**
     * getEntries
     * @description  : getEntries is used to get the entries of the specified entries
     * @params       : contentTypeUid {string} - Content-Type from which entries to be retrieved
     * @return       : Result {Promise}
     */
    getContentTypedemo() {
        contentTypeUid = contentTypeUid || 'source'
        return this.Stack.ContentType(contentTypeUid).fetch()
       // return this.Stack.ContentType('event_list').Entry('blt5d40c608567844d4').toJSON().fetch()
    }

    /**
     * getEntries
     * @description  : getEntries is used to get the entries of the specified entries
     * @params       : contentTypeUid {string} - Content-Type from which entries to be retrieved
     * @return       : Result {Promise}
     */
    getContentType(uid) {
        //contentTypeUid = contentTypeUid || 'source'
        // return this.Stack.getContentType(uid)
        // return this.Stack.ContentType(uid).Entry("blta07130f8b344b260").includeReferenceContentTypeUID().includeSchema().toJSON().fetch()
        //return this.Stack.getContentTypes({"include_global_field_schema": true})
    }

    /**
     * fetchEntry
     * @description  : fetchEntry is used to get the specified uid entry
     * @params       : contentTypeUid {string} - Content-Type from which entry to be fetched
     *                 entryUid       {string} - Specified entry to be fetched
     * @return       : Result {Promise}
     */
    getEntry(contentTypeUid, entryUid) {
            contentTypeUid = contentTypeUid || 'source'
            entryUid = entryUid || 'blt123something'
            return this.Stack.ContentType(contentTypeUid).Entry(entryUid).language('ja-jp').fetch()
        }

        /**
         * getAssets
         * @description  : getAssets is used to get the assets
         * @return       : Result {Promise}
         */
    getAssets() {
        return this.Stack.Assets().Query().toJSON().find()
    }

    /**
     * fetchAsset
     * @description  : fetchAsset is used to get the specified uid asset
     * @params       : assetUid       {string} - Specified Asset uid to be fetched
     * @return       : Result {Promise}
     */
    getAsset(assetUid) {
        assetUid = assetUid || 'blt123something'
        return this.Stack.Assets(assetUid).addParam('include_dimension', 'true').fetch()
    }

    /**
     * fetchAsset
     * @description  : fetchAsset is used to get the specified uid asset
     * @params       : assetUid       {string} - Specified Asset uid to be fetched
     * @return       : Result {Promise}
     */
    getSyncApi(params) {
        params = params || 'blt123something'
        return this.Stack.sync(params);
    }

}

module.exports = ContentstackDemo<commit_msg>Default time-out set<commit_after>'use strict'
/*!
 * module dependencies
 */
const Contentstack = require('../../dist/node/contentstack.js');

/*
 * Example ContentstackDemo Class
 * */

class ContentstackDemo {
    constructor(config) {
        config = config || { 'api_key': 'blt123something', 'delivery_token': 'blt123something', 'environment': 'development',  }
            // Initialize the Contentstackstack
            //console.log("datattatata", Contentstack.Region.EUROPE)

        this.Stack = Contentstack.Stack(config);
    }

    /**
     * getEntries
     * @description  : getEntries is used to get the entries of the specified entries
     * @params       : contentTypeUid {string} - Content-Type from which entries to be retrieved
     * @return       : Result {Promise}
     */
    getEntries(contentTypeUid) {
        contentTypeUid = contentTypeUid || 'source'
        return this.Stack.ContentType('test').Query().includeContentType().toJSON().find()
        //return this.Stack.getContentTypes(contentTypeUid)

    }

    /**
     * getEntries
     * @description  : getEntries is used to get the entries of the specified entries
     * @params       : contentTypeUid {string} - Content-Type from which entries to be retrieved
     * @return       : Result {Promise}
     */
    getLastActivities() {
        //contentTypeUid = contentTypeUid || 'source'
        return this.Stack.getLastActivities()
    }

    /**
     * getEntries
     * @description  : getEntries is used to get the entries of the specified entries
     * @params       : contentTypeUid {string} - Content-Type from which entries to be retrieved
     * @return       : Result {Promise}
     */
    getContentTypedemo() {
        contentTypeUid = contentTypeUid || 'source'
        return this.Stack.ContentType(contentTypeUid).fetch()
       // return this.Stack.ContentType('event_list').Entry('blt5d40c608567844d4').toJSON().fetch()
    }

    /**
     * getEntries
     * @description  : getEntries is used to get the entries of the specified entries
     * @params       : contentTypeUid {string} - Content-Type from which entries to be retrieved
     * @return       : Result {Promise}
     */
    getContentType(uid) {
        //contentTypeUid = contentTypeUid || 'source'
        // return this.Stack.getContentType(uid)
        // return this.Stack.ContentType(uid).Entry("blta07130f8b344b260").includeReferenceContentTypeUID().includeSchema().toJSON().fetch()
        //return this.Stack.getContentTypes({"include_global_field_schema": true})
    }

    /**
     * fetchEntry
     * @description  : fetchEntry is used to get the specified uid entry
     * @params       : contentTypeUid {string} - Content-Type from which entry to be fetched
     *                 entryUid       {string} - Specified entry to be fetched
     * @return       : Result {Promise}
     */
    getEntry(contentTypeUid, entryUid) {
            contentTypeUid = contentTypeUid || 'source'
            entryUid = entryUid || 'blt123something'
            return this.Stack.ContentType(contentTypeUid).Entry(entryUid).language('ja-jp').fetch()
        }

        /**
         * getAssets
         * @description  : getAssets is used to get the assets
         * @return       : Result {Promise}
         */
    getAssets() {
        return this.Stack.Assets().Query().toJSON().find()
    }

    /**
     * fetchAsset
     * @description  : fetchAsset is used to get the specified uid asset
     * @params       : assetUid       {string} - Specified Asset uid to be fetched
     * @return       : Result {Promise}
     */
    getAsset(assetUid) {
        assetUid = assetUid || 'blt123something'
        return this.Stack.Assets(assetUid).addParam('include_dimension', 'true').fetch()
    }

    /**
     * fetchAsset
     * @description  : fetchAsset is used to get the specified uid asset
     * @params       : assetUid       {string} - Specified Asset uid to be fetched
     * @return       : Result {Promise}
     */
    getSyncApi(params) {
        params = params || 'blt123something'
        return this.Stack.sync(params);
    }

}

module.exports = ContentstackDemo<|endoftext|>