<commit_before>/**
 * Based on http://www.emagix.net/academic/mscs-project/item/camera-sync-with-css3-and-webgl-threejs
 * @author mrdoob / http://mrdoob.com/
 */

THREE.CSS3DObject = function ( element ) {

	THREE.Object3D.call( this );

	this.element = element;
	this.element.style.position = 'absolute';

	this.addEventListener( 'removed', function () {

		if ( this.element.parentNode !== null ) {

			this.element.parentNode.removeChild( this.element );

		}

	} );

};

THREE.CSS3DObject.prototype = Object.create( THREE.Object3D.prototype );
THREE.CSS3DObject.prototype.constructor = THREE.CSS3DObject;

THREE.CSS3DSprite = function ( element ) {

	THREE.CSS3DObject.call( this, element );

};

THREE.CSS3DSprite.prototype = Object.create( THREE.CSS3DObject.prototype );
THREE.CSS3DSprite.prototype.constructor = THREE.CSS3DSprite;

//

THREE.CSS3DRenderer = function () {

	console.log( 'THREE.CSS3DRenderer', THREE.REVISION );

	var _width, _height;
	var _widthHalf, _heightHalf;

	var matrix = new THREE.Matrix4();

	var cache = {
		camera: { fov: 0, style: '' },
		objects: {}
	};

	var domElement = document.createElement( 'div' );
	domElement.style.overflow = 'hidden';

	this.domElement = domElement;

	var cameraElement = document.createElement( 'div' );

	cameraElement.style.WebkitTransformStyle = 'preserve-3d';
	cameraElement.style.MozTransformStyle = 'preserve-3d';
	cameraElement.style.transformStyle = 'preserve-3d';

	domElement.appendChild( cameraElement );

	// Should we replace to feature detection?
	// https://github.com/Modernizr/Modernizr/blob/master/feature-detects/css/transformstylepreserve3d.js
	// So far, we use `document.documentMode` to detect IE
	var isFlatTransform = !! document.documentMode;

	this.setClearColor = function () {};

	this.getSize = function () {

		return {
			width: _width,
			height: _height
		};

	};

	this.setSize = function ( width, height ) {

		_width = width;
		_height = height;
		_widthHalf = _width / 2;
		_heightHalf = _height / 2;

		domElement.style.width = width + 'px';
		domElement.style.height = height + 'px';

		cameraElement.style.width = width + 'px';
		cameraElement.style.height = height + 'px';

	};

	function epsilon( value ) {

		return Math.abs( value ) < 1e-10 ? 0 : value;

	}

	function getCameraCSSMatrix( matrix ) {

		var elements = matrix.elements;

		return 'matrix3d(' +
			epsilon( elements[ 0 ] ) + ',' +
			epsilon( - elements[ 1 ] ) + ',' +
			epsilon( elements[ 2 ] ) + ',' +
			epsilon( elements[ 3 ] ) + ',' +
			epsilon( elements[ 4 ] ) + ',' +
			epsilon( - elements[ 5 ] ) + ',' +
			epsilon( elements[ 6 ] ) + ',' +
			epsilon( elements[ 7 ] ) + ',' +
			epsilon( elements[ 8 ] ) + ',' +
			epsilon( - elements[ 9 ] ) + ',' +
			epsilon( elements[ 10 ] ) + ',' +
			epsilon( elements[ 11 ] ) + ',' +
			epsilon( elements[ 12 ] ) + ',' +
			epsilon( - elements[ 13 ] ) + ',' +
			epsilon( elements[ 14 ] ) + ',' +
			epsilon( elements[ 15 ] ) +
		')';

	}

	function getObjectCSSMatrix( matrix, cameraCSSMatrix ) {

		var elements = matrix.elements;
		var matrix3d = 'matrix3d(' +
			epsilon( elements[ 0 ] ) + ',' +
			epsilon( elements[ 1 ] ) + ',' +
			epsilon( elements[ 2 ] ) + ',' +
			epsilon( elements[ 3 ] ) + ',' +
			epsilon( - elements[ 4 ] ) + ',' +
			epsilon( - elements[ 5 ] ) + ',' +
			epsilon( - elements[ 6 ] ) + ',' +
			epsilon( - elements[ 7 ] ) + ',' +
			epsilon( elements[ 8 ] ) + ',' +
			epsilon( elements[ 9 ] ) + ',' +
			epsilon( elements[ 10 ] ) + ',' +
			epsilon( elements[ 11 ] ) + ',' +
			epsilon( elements[ 12 ] ) + ',' +
			epsilon( elements[ 13 ] ) + ',' +
			epsilon( elements[ 14 ] ) + ',' +
			epsilon( elements[ 15 ] ) +
		')';

		if ( ! isFlatTransform ) {

			return 'translate(-50%,-50%)' + matrix3d;

		}

		return 'translate(-50%,-50%)' +
			'translate(' + _widthHalf + 'px,' + _heightHalf + 'px)' +
			cameraCSSMatrix +
			matrix3d;

	}

	function renderObject( object, camera, cameraCSSMatrix ) {

		if ( object instanceof THREE.CSS3DObject ) {

			var style;

			if ( object instanceof THREE.CSS3DSprite ) {

				// http://swiftcoder.wordpress.com/2008/11/25/constructing-a-billboard-matrix/

				matrix.copy( camera.matrixWorldInverse );
				matrix.transpose();
				matrix.copyPosition( object.matrixWorld );
				matrix.scale( object.scale );

				matrix.elements[ 3 ] = 0;
				matrix.elements[ 7 ] = 0;
				matrix.elements[ 11 ] = 0;
				matrix.elements[ 15 ] = 1;

				style = getObjectCSSMatrix( matrix, cameraCSSMatrix );

			} else {

				style = getObjectCSSMatrix( object.matrixWorld, cameraCSSMatrix );

			}

			var element = object.element;
			var cachedStyle = cache.objects[ object.id ] && cache.objects[ object.id ].style;

			if ( cachedStyle === undefined || cachedStyle !== style ) {

				element.style.WebkitTransform = style;
				element.style.MozTransform = style;
				element.style.transform = style;

				cache.objects[ object.id ] = { style: style };

				if ( isFlatTransform ) {

					cache.objects[ object.id ].distanceToCameraSquared = getDistanceToSquared( camera, object );

				}

			}

			if ( element.parentNode !== cameraElement ) {

				cameraElement.appendChild( element );

			}

		}

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

			renderObject( object.children[ i ], camera, cameraCSSMatrix );

		}

	}

	var getDistanceToSquared = function () {

		var a = new THREE.Vector3();
		var b = new THREE.Vector3();

		return function ( object1, object2 ) {

			a.x = object1.matrixWorld.elements[ 12 ];
			a.y = object1.matrixWorld.elements[ 13 ];
			a.z = object1.matrixWorld.elements[ 14 ];

			b.x = object2.matrixWorld.elements[ 12 ];
			b.y = object2.matrixWorld.elements[ 13 ];
			b.z = object2.matrixWorld.elements[ 14 ];

			return a.distanceToSquared( b );

		};

	}();

	function zOrder( scene ) {

		var order = Object.keys( cache.objects ).sort( function ( a, b ) {

			return cache.objects[ a ].distanceToCameraSquared - cache.objects[ b ].distanceToCameraSquared;

		} );
		var zMax = order.length;

		scene.traverse( function ( object ) {

			var index = order.indexOf( object.id + '' );

			if ( index !== - 1 ) {

				object.element.style.zIndex = zMax - index;

			}

		} );

	}

	this.render = function ( scene, camera ) {

		var fov = 0.5 / Math.tan( THREE.Math.degToRad( camera.getEffectiveFOV() * 0.5 ) ) * _height;

		if ( cache.camera.fov !== fov ) {

			domElement.style.WebkitPerspective = fov + 'px';
			domElement.style.MozPerspective = fov + 'px';
			domElement.style.perspective = fov + 'px';

			cache.camera.fov = fov;

		}

		scene.updateMatrixWorld();

		if ( camera.parent === null ) camera.updateMatrixWorld();

		camera.matrixWorldInverse.getInverse( camera.matrixWorld );

		var cameraCSSMatrix = 'translateZ(' + fov + 'px)' +
			getCameraCSSMatrix( camera.matrixWorldInverse );

		var style = cameraCSSMatrix +
			'translate(' + _widthHalf + 'px,' + _heightHalf + 'px)';

		if ( ! isFlatTransform && cache.camera.style !== style ) {

			cameraElement.style.WebkitTransform = style;
			cameraElement.style.MozTransform = style;
			cameraElement.style.transform = style;

			cache.camera.style = style;

		}

		renderObject( scene, camera, cameraCSSMatrix );

		if ( isFlatTransform ) {

			// IE10 and 11 does not support 'preserve-3d'.
			// Thus, z-order in 3D will not work.
			// We have to calc z-order manually and set CSS z-index for IE.
			// FYI: z-index can't handle object intersection
			zOrder( scene );

		}

	};

};
<commit_msg>use UserAgent to detect IE<commit_after>/**
 * Based on http://www.emagix.net/academic/mscs-project/item/camera-sync-with-css3-and-webgl-threejs
 * @author mrdoob / http://mrdoob.com/
 */

THREE.CSS3DObject = function ( element ) {

	THREE.Object3D.call( this );

	this.element = element;
	this.element.style.position = 'absolute';

	this.addEventListener( 'removed', function () {

		if ( this.element.parentNode !== null ) {

			this.element.parentNode.removeChild( this.element );

		}

	} );

};

THREE.CSS3DObject.prototype = Object.create( THREE.Object3D.prototype );
THREE.CSS3DObject.prototype.constructor = THREE.CSS3DObject;

THREE.CSS3DSprite = function ( element ) {

	THREE.CSS3DObject.call( this, element );

};

THREE.CSS3DSprite.prototype = Object.create( THREE.CSS3DObject.prototype );
THREE.CSS3DSprite.prototype.constructor = THREE.CSS3DSprite;

//

THREE.CSS3DRenderer = function () {

	console.log( 'THREE.CSS3DRenderer', THREE.REVISION );

	var _width, _height;
	var _widthHalf, _heightHalf;

	var matrix = new THREE.Matrix4();

	var cache = {
		camera: { fov: 0, style: '' },
		objects: {}
	};

	var domElement = document.createElement( 'div' );
	domElement.style.overflow = 'hidden';

	this.domElement = domElement;

	var cameraElement = document.createElement( 'div' );

	cameraElement.style.WebkitTransformStyle = 'preserve-3d';
	cameraElement.style.MozTransformStyle = 'preserve-3d';
	cameraElement.style.transformStyle = 'preserve-3d';

	domElement.appendChild( cameraElement );

	var isIE = /Trident/i.test( navigator.userAgent )

	this.setClearColor = function () {};

	this.getSize = function () {

		return {
			width: _width,
			height: _height
		};

	};

	this.setSize = function ( width, height ) {

		_width = width;
		_height = height;
		_widthHalf = _width / 2;
		_heightHalf = _height / 2;

		domElement.style.width = width + 'px';
		domElement.style.height = height + 'px';

		cameraElement.style.width = width + 'px';
		cameraElement.style.height = height + 'px';

	};

	function epsilon( value ) {

		return Math.abs( value ) < 1e-10 ? 0 : value;

	}

	function getCameraCSSMatrix( matrix ) {

		var elements = matrix.elements;

		return 'matrix3d(' +
			epsilon( elements[ 0 ] ) + ',' +
			epsilon( - elements[ 1 ] ) + ',' +
			epsilon( elements[ 2 ] ) + ',' +
			epsilon( elements[ 3 ] ) + ',' +
			epsilon( elements[ 4 ] ) + ',' +
			epsilon( - elements[ 5 ] ) + ',' +
			epsilon( elements[ 6 ] ) + ',' +
			epsilon( elements[ 7 ] ) + ',' +
			epsilon( elements[ 8 ] ) + ',' +
			epsilon( - elements[ 9 ] ) + ',' +
			epsilon( elements[ 10 ] ) + ',' +
			epsilon( elements[ 11 ] ) + ',' +
			epsilon( elements[ 12 ] ) + ',' +
			epsilon( - elements[ 13 ] ) + ',' +
			epsilon( elements[ 14 ] ) + ',' +
			epsilon( elements[ 15 ] ) +
		')';

	}

	function getObjectCSSMatrix( matrix, cameraCSSMatrix ) {

		var elements = matrix.elements;
		var matrix3d = 'matrix3d(' +
			epsilon( elements[ 0 ] ) + ',' +
			epsilon( elements[ 1 ] ) + ',' +
			epsilon( elements[ 2 ] ) + ',' +
			epsilon( elements[ 3 ] ) + ',' +
			epsilon( - elements[ 4 ] ) + ',' +
			epsilon( - elements[ 5 ] ) + ',' +
			epsilon( - elements[ 6 ] ) + ',' +
			epsilon( - elements[ 7 ] ) + ',' +
			epsilon( elements[ 8 ] ) + ',' +
			epsilon( elements[ 9 ] ) + ',' +
			epsilon( elements[ 10 ] ) + ',' +
			epsilon( elements[ 11 ] ) + ',' +
			epsilon( elements[ 12 ] ) + ',' +
			epsilon( elements[ 13 ] ) + ',' +
			epsilon( elements[ 14 ] ) + ',' +
			epsilon( elements[ 15 ] ) +
		')';

		if ( isIE ) {

			return 'translate(-50%,-50%)' +
				'translate(' + _widthHalf + 'px,' + _heightHalf + 'px)' +
				cameraCSSMatrix +
				matrix3d;

		}

		return 'translate(-50%,-50%)' + matrix3d;

	}

	function renderObject( object, camera, cameraCSSMatrix ) {

		if ( object instanceof THREE.CSS3DObject ) {

			var style;

			if ( object instanceof THREE.CSS3DSprite ) {

				// http://swiftcoder.wordpress.com/2008/11/25/constructing-a-billboard-matrix/

				matrix.copy( camera.matrixWorldInverse );
				matrix.transpose();
				matrix.copyPosition( object.matrixWorld );
				matrix.scale( object.scale );

				matrix.elements[ 3 ] = 0;
				matrix.elements[ 7 ] = 0;
				matrix.elements[ 11 ] = 0;
				matrix.elements[ 15 ] = 1;

				style = getObjectCSSMatrix( matrix, cameraCSSMatrix );

			} else {

				style = getObjectCSSMatrix( object.matrixWorld, cameraCSSMatrix );

			}

			var element = object.element;
			var cachedStyle = cache.objects[ object.id ] && cache.objects[ object.id ].style;

			if ( cachedStyle === undefined || cachedStyle !== style ) {

				element.style.WebkitTransform = style;
				element.style.MozTransform = style;
				element.style.transform = style;

				cache.objects[ object.id ] = { style: style };

				if ( isIE ) {

					cache.objects[ object.id ].distanceToCameraSquared = getDistanceToSquared( camera, object );

				}

			}

			if ( element.parentNode !== cameraElement ) {

				cameraElement.appendChild( element );

			}

		}

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

			renderObject( object.children[ i ], camera, cameraCSSMatrix );

		}

	}

	var getDistanceToSquared = function () {

		var a = new THREE.Vector3();
		var b = new THREE.Vector3();

		return function ( object1, object2 ) {

			a.x = object1.matrixWorld.elements[ 12 ];
			a.y = object1.matrixWorld.elements[ 13 ];
			a.z = object1.matrixWorld.elements[ 14 ];

			b.x = object2.matrixWorld.elements[ 12 ];
			b.y = object2.matrixWorld.elements[ 13 ];
			b.z = object2.matrixWorld.elements[ 14 ];

			return a.distanceToSquared( b );

		};

	}();

	function zOrder( scene ) {

		var order = Object.keys( cache.objects ).sort( function ( a, b ) {

			return cache.objects[ a ].distanceToCameraSquared - cache.objects[ b ].distanceToCameraSquared;

		} );
		var zMax = order.length;

		scene.traverse( function ( object ) {

			var index = order.indexOf( object.id + '' );

			if ( index !== - 1 ) {

				object.element.style.zIndex = zMax - index;

			}

		} );

	}

	this.render = function ( scene, camera ) {

		var fov = 0.5 / Math.tan( THREE.Math.degToRad( camera.getEffectiveFOV() * 0.5 ) ) * _height;

		if ( cache.camera.fov !== fov ) {

			domElement.style.WebkitPerspective = fov + 'px';
			domElement.style.MozPerspective = fov + 'px';
			domElement.style.perspective = fov + 'px';

			cache.camera.fov = fov;

		}

		scene.updateMatrixWorld();

		if ( camera.parent === null ) camera.updateMatrixWorld();

		camera.matrixWorldInverse.getInverse( camera.matrixWorld );

		var cameraCSSMatrix = 'translateZ(' + fov + 'px)' +
			getCameraCSSMatrix( camera.matrixWorldInverse );

		var style = cameraCSSMatrix +
			'translate(' + _widthHalf + 'px,' + _heightHalf + 'px)';

		if ( cache.camera.style !== style && ! isIE ) {

			cameraElement.style.WebkitTransform = style;
			cameraElement.style.MozTransform = style;
			cameraElement.style.transform = style;

			cache.camera.style = style;

		}

		renderObject( scene, camera, cameraCSSMatrix );

		if ( isIE ) {

			// IE10 and 11 does not support 'preserve-3d'.
			// Thus, z-order in 3D will not work.
			// We have to calc z-order manually and set CSS z-index for IE.
			// FYI: z-index can't handle object intersection
			zOrder( scene );

		}

	};

};
<|endoftext|>


<commit_before>/**
 * Based on http://www.emagix.net/academic/mscs-project/item/camera-sync-with-css3-and-webgl-threejs
 * @author mrdoob / http://mrdoob.com/
 */

THREE.CSS3DObject = function ( element ) {

	THREE.Object3D.call( this );

	this.element = element;
	this.element.style.position = 'absolute';

	this.addEventListener( 'removed', function () {

		if ( this.element.parentNode !== null ) {

			this.element.parentNode.removeChild( this.element );

		}

	} );

};

THREE.CSS3DObject.prototype = Object.create( THREE.Object3D.prototype );
THREE.CSS3DObject.prototype.constructor = THREE.CSS3DObject;

THREE.CSS3DSprite = function ( element ) {

	THREE.CSS3DObject.call( this, element );

};

THREE.CSS3DSprite.prototype = Object.create( THREE.CSS3DObject.prototype );
THREE.CSS3DSprite.prototype.constructor = THREE.CSS3DSprite;

//

THREE.CSS3DRenderer = function () {

	console.log( 'THREE.CSS3DRenderer', THREE.REVISION );

	var _width, _height;
	var _widthHalf, _heightHalf;

	var matrix = new THREE.Matrix4();

	var cache = {
		camera: { fov: 0, style: '' },
		objects: {}
	};

	var domElement = document.createElement( 'div' );
	domElement.style.overflow = 'hidden';

	this.domElement = domElement;

	var cameraElement = document.createElement( 'div' );

	cameraElement.style.WebkitTransformStyle = 'preserve-3d';
	cameraElement.style.MozTransformStyle = 'preserve-3d';
	cameraElement.style.transformStyle = 'preserve-3d';

	domElement.appendChild( cameraElement );

	var isIE = /Trident/i.test( navigator.userAgent )

	this.setClearColor = function () {};

	this.getSize = function () {

		return {
			width: _width,
			height: _height
		};

	};

	this.setSize = function ( width, height ) {

		_width = width;
		_height = height;
		_widthHalf = _width / 2;
		_heightHalf = _height / 2;

		domElement.style.width = width + 'px';
		domElement.style.height = height + 'px';

		cameraElement.style.width = width + 'px';
		cameraElement.style.height = height + 'px';

	};

	function epsilon( value ) {

		return Math.abs( value ) < 1e-10 ? 0 : value;

	}

	function getCameraCSSMatrix( matrix ) {

		var elements = matrix.elements;

		return 'matrix3d(' +
			epsilon( elements[ 0 ] ) + ',' +
			epsilon( - elements[ 1 ] ) + ',' +
			epsilon( elements[ 2 ] ) + ',' +
			epsilon( elements[ 3 ] ) + ',' +
			epsilon( elements[ 4 ] ) + ',' +
			epsilon( - elements[ 5 ] ) + ',' +
			epsilon( elements[ 6 ] ) + ',' +
			epsilon( elements[ 7 ] ) + ',' +
			epsilon( elements[ 8 ] ) + ',' +
			epsilon( - elements[ 9 ] ) + ',' +
			epsilon( elements[ 10 ] ) + ',' +
			epsilon( elements[ 11 ] ) + ',' +
			epsilon( elements[ 12 ] ) + ',' +
			epsilon( - elements[ 13 ] ) + ',' +
			epsilon( elements[ 14 ] ) + ',' +
			epsilon( elements[ 15 ] ) +
		')';

	}

	function getObjectCSSMatrix( matrix, cameraCSSMatrix ) {

		var elements = matrix.elements;
		var matrix3d = 'matrix3d(' +
			epsilon( elements[ 0 ] ) + ',' +
			epsilon( elements[ 1 ] ) + ',' +
			epsilon( elements[ 2 ] ) + ',' +
			epsilon( elements[ 3 ] ) + ',' +
			epsilon( - elements[ 4 ] ) + ',' +
			epsilon( - elements[ 5 ] ) + ',' +
			epsilon( - elements[ 6 ] ) + ',' +
			epsilon( - elements[ 7 ] ) + ',' +
			epsilon( elements[ 8 ] ) + ',' +
			epsilon( elements[ 9 ] ) + ',' +
			epsilon( elements[ 10 ] ) + ',' +
			epsilon( elements[ 11 ] ) + ',' +
			epsilon( elements[ 12 ] ) + ',' +
			epsilon( elements[ 13 ] ) + ',' +
			epsilon( elements[ 14 ] ) + ',' +
			epsilon( elements[ 15 ] ) +
		')';

		if ( isIE ) {

			return 'translate(-50%,-50%)' +
				'translate(' + _widthHalf + 'px,' + _heightHalf + 'px)' +
				cameraCSSMatrix +
				matrix3d;

		}

		return 'translate(-50%,-50%)' + matrix3d;

	}

	function renderObject( object, camera, cameraCSSMatrix ) {

		if ( object instanceof THREE.CSS3DObject ) {

			var style;

			if ( object instanceof THREE.CSS3DSprite ) {

				// http://swiftcoder.wordpress.com/2008/11/25/constructing-a-billboard-matrix/

				matrix.copy( camera.matrixWorldInverse );
				matrix.transpose();
				matrix.copyPosition( object.matrixWorld );
				matrix.scale( object.scale );

				matrix.elements[ 3 ] = 0;
				matrix.elements[ 7 ] = 0;
				matrix.elements[ 11 ] = 0;
				matrix.elements[ 15 ] = 1;

				style = getObjectCSSMatrix( matrix, cameraCSSMatrix );

			} else {

				style = getObjectCSSMatrix( object.matrixWorld, cameraCSSMatrix );

			}

			var element = object.element;
			var cachedStyle = cache.objects[ object.id ] && cache.objects[ object.id ].style;

			if ( cachedStyle === undefined || cachedStyle !== style ) {

				element.style.WebkitTransform = style;
				element.style.MozTransform = style;
				element.style.transform = style;

				cache.objects[ object.id ] = { style: style };

				if ( isIE ) {

					cache.objects[ object.id ].distanceToCameraSquared = getDistanceToSquared( camera, object );

				}

			}

			if ( element.parentNode !== cameraElement ) {

				cameraElement.appendChild( element );

			}

		}

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

			renderObject( object.children[ i ], camera, cameraCSSMatrix );

		}

	}

	var getDistanceToSquared = function () {

		var a = new THREE.Vector3();
		var b = new THREE.Vector3();

		return function ( object1, object2 ) {

			a.x = object1.matrixWorld.elements[ 12 ];
			a.y = object1.matrixWorld.elements[ 13 ];
			a.z = object1.matrixWorld.elements[ 14 ];

			b.x = object2.matrixWorld.elements[ 12 ];
			b.y = object2.matrixWorld.elements[ 13 ];
			b.z = object2.matrixWorld.elements[ 14 ];

			return a.distanceToSquared( b );

		};

	}();

	function zOrder( scene ) {

		var order = Object.keys( cache.objects ).sort( function ( a, b ) {

			return cache.objects[ a ].distanceToCameraSquared - cache.objects[ b ].distanceToCameraSquared;

		} );
		var zMax = order.length;

		scene.traverse( function ( object ) {

			var index = order.indexOf( object.id + '' );

			if ( index !== - 1 ) {

				object.element.style.zIndex = zMax - index;

			}

		} );

	}

	this.render = function ( scene, camera ) {

		var fov = 0.5 / Math.tan( THREE.Math.degToRad( camera.getEffectiveFOV() * 0.5 ) ) * _height;

		if ( cache.camera.fov !== fov ) {

			domElement.style.WebkitPerspective = fov + 'px';
			domElement.style.MozPerspective = fov + 'px';
			domElement.style.perspective = fov + 'px';

			cache.camera.fov = fov;

		}

		scene.updateMatrixWorld();

		if ( camera.parent === null ) camera.updateMatrixWorld();

		camera.matrixWorldInverse.getInverse( camera.matrixWorld );

		var cameraCSSMatrix = 'translateZ(' + fov + 'px)' +
			getCameraCSSMatrix( camera.matrixWorldInverse );

		var style = cameraCSSMatrix +
			'translate(' + _widthHalf + 'px,' + _heightHalf + 'px)';

		if ( cache.camera.style !== style && ! isIE ) {

			cameraElement.style.WebkitTransform = style;
			cameraElement.style.MozTransform = style;
			cameraElement.style.transform = style;

			cache.camera.style = style;

		}

		renderObject( scene, camera, cameraCSSMatrix );

		if ( isIE ) {

			// IE10 and 11 does not support 'preserve-3d'.
			// Thus, z-order in 3D will not work.
			// We have to calc z-order manually and set CSS z-index for IE.
			// FYI: z-index can't handle object intersection
			zOrder( scene );

		}

	};

};
<commit_msg>readable translation mat4 to vec3<commit_after>/**
 * Based on http://www.emagix.net/academic/mscs-project/item/camera-sync-with-css3-and-webgl-threejs
 * @author mrdoob / http://mrdoob.com/
 */

THREE.CSS3DObject = function ( element ) {

	THREE.Object3D.call( this );

	this.element = element;
	this.element.style.position = 'absolute';

	this.addEventListener( 'removed', function () {

		if ( this.element.parentNode !== null ) {

			this.element.parentNode.removeChild( this.element );

		}

	} );

};

THREE.CSS3DObject.prototype = Object.create( THREE.Object3D.prototype );
THREE.CSS3DObject.prototype.constructor = THREE.CSS3DObject;

THREE.CSS3DSprite = function ( element ) {

	THREE.CSS3DObject.call( this, element );

};

THREE.CSS3DSprite.prototype = Object.create( THREE.CSS3DObject.prototype );
THREE.CSS3DSprite.prototype.constructor = THREE.CSS3DSprite;

//

THREE.CSS3DRenderer = function () {

	console.log( 'THREE.CSS3DRenderer', THREE.REVISION );

	var _width, _height;
	var _widthHalf, _heightHalf;

	var matrix = new THREE.Matrix4();

	var cache = {
		camera: { fov: 0, style: '' },
		objects: {}
	};

	var domElement = document.createElement( 'div' );
	domElement.style.overflow = 'hidden';

	this.domElement = domElement;

	var cameraElement = document.createElement( 'div' );

	cameraElement.style.WebkitTransformStyle = 'preserve-3d';
	cameraElement.style.MozTransformStyle = 'preserve-3d';
	cameraElement.style.transformStyle = 'preserve-3d';

	domElement.appendChild( cameraElement );

	var isIE = /Trident/i.test( navigator.userAgent );

	this.setClearColor = function () {};

	this.getSize = function () {

		return {
			width: _width,
			height: _height
		};

	};

	this.setSize = function ( width, height ) {

		_width = width;
		_height = height;
		_widthHalf = _width / 2;
		_heightHalf = _height / 2;

		domElement.style.width = width + 'px';
		domElement.style.height = height + 'px';

		cameraElement.style.width = width + 'px';
		cameraElement.style.height = height + 'px';

	};

	function epsilon( value ) {

		return Math.abs( value ) < 1e-10 ? 0 : value;

	}

	function getCameraCSSMatrix( matrix ) {

		var elements = matrix.elements;

		return 'matrix3d(' +
			epsilon( elements[ 0 ] ) + ',' +
			epsilon( - elements[ 1 ] ) + ',' +
			epsilon( elements[ 2 ] ) + ',' +
			epsilon( elements[ 3 ] ) + ',' +
			epsilon( elements[ 4 ] ) + ',' +
			epsilon( - elements[ 5 ] ) + ',' +
			epsilon( elements[ 6 ] ) + ',' +
			epsilon( elements[ 7 ] ) + ',' +
			epsilon( elements[ 8 ] ) + ',' +
			epsilon( - elements[ 9 ] ) + ',' +
			epsilon( elements[ 10 ] ) + ',' +
			epsilon( elements[ 11 ] ) + ',' +
			epsilon( elements[ 12 ] ) + ',' +
			epsilon( - elements[ 13 ] ) + ',' +
			epsilon( elements[ 14 ] ) + ',' +
			epsilon( elements[ 15 ] ) +
		')';

	}

	function getObjectCSSMatrix( matrix, cameraCSSMatrix ) {

		var elements = matrix.elements;
		var matrix3d = 'matrix3d(' +
			epsilon( elements[ 0 ] ) + ',' +
			epsilon( elements[ 1 ] ) + ',' +
			epsilon( elements[ 2 ] ) + ',' +
			epsilon( elements[ 3 ] ) + ',' +
			epsilon( - elements[ 4 ] ) + ',' +
			epsilon( - elements[ 5 ] ) + ',' +
			epsilon( - elements[ 6 ] ) + ',' +
			epsilon( - elements[ 7 ] ) + ',' +
			epsilon( elements[ 8 ] ) + ',' +
			epsilon( elements[ 9 ] ) + ',' +
			epsilon( elements[ 10 ] ) + ',' +
			epsilon( elements[ 11 ] ) + ',' +
			epsilon( elements[ 12 ] ) + ',' +
			epsilon( elements[ 13 ] ) + ',' +
			epsilon( elements[ 14 ] ) + ',' +
			epsilon( elements[ 15 ] ) +
		')';

		if ( isIE ) {

			return 'translate(-50%,-50%)' +
				'translate(' + _widthHalf + 'px,' + _heightHalf + 'px)' +
				cameraCSSMatrix +
				matrix3d;

		}

		return 'translate(-50%,-50%)' + matrix3d;

	}

	function renderObject( object, camera, cameraCSSMatrix ) {

		if ( object instanceof THREE.CSS3DObject ) {

			var style;

			if ( object instanceof THREE.CSS3DSprite ) {

				// http://swiftcoder.wordpress.com/2008/11/25/constructing-a-billboard-matrix/

				matrix.copy( camera.matrixWorldInverse );
				matrix.transpose();
				matrix.copyPosition( object.matrixWorld );
				matrix.scale( object.scale );

				matrix.elements[ 3 ] = 0;
				matrix.elements[ 7 ] = 0;
				matrix.elements[ 11 ] = 0;
				matrix.elements[ 15 ] = 1;

				style = getObjectCSSMatrix( matrix, cameraCSSMatrix );

			} else {

				style = getObjectCSSMatrix( object.matrixWorld, cameraCSSMatrix );

			}

			var element = object.element;
			var cachedStyle = cache.objects[ object.id ] && cache.objects[ object.id ].style;

			if ( cachedStyle === undefined || cachedStyle !== style ) {

				element.style.WebkitTransform = style;
				element.style.MozTransform = style;
				element.style.transform = style;

				cache.objects[ object.id ] = { style: style };

				if ( isIE ) {

					cache.objects[ object.id ].distanceToCameraSquared = getDistanceToSquared( camera, object );

				}

			}

			if ( element.parentNode !== cameraElement ) {

				cameraElement.appendChild( element );

			}

		}

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

			renderObject( object.children[ i ], camera, cameraCSSMatrix );

		}

	}

	var getDistanceToSquared = function () {

		var a = new THREE.Vector3();
		var b = new THREE.Vector3();

		return function ( object1, object2 ) {

			a.setFromMatrixPosition( object1.matrixWorld );
			b.setFromMatrixPosition( object2.matrixWorld );

			return a.distanceToSquared( b );

		};

	}();

	function zOrder( scene ) {

		var order = Object.keys( cache.objects ).sort( function ( a, b ) {

			return cache.objects[ a ].distanceToCameraSquared - cache.objects[ b ].distanceToCameraSquared;

		} );
		var zMax = order.length;

		scene.traverse( function ( object ) {

			var index = order.indexOf( object.id + '' );

			if ( index !== - 1 ) {

				object.element.style.zIndex = zMax - index;

			}

		} );

	}

	this.render = function ( scene, camera ) {

		var fov = 0.5 / Math.tan( THREE.Math.degToRad( camera.getEffectiveFOV() * 0.5 ) ) * _height;

		if ( cache.camera.fov !== fov ) {

			domElement.style.WebkitPerspective = fov + 'px';
			domElement.style.MozPerspective = fov + 'px';
			domElement.style.perspective = fov + 'px';

			cache.camera.fov = fov;

		}

		scene.updateMatrixWorld();

		if ( camera.parent === null ) camera.updateMatrixWorld();

		camera.matrixWorldInverse.getInverse( camera.matrixWorld );

		var cameraCSSMatrix = 'translateZ(' + fov + 'px)' +
			getCameraCSSMatrix( camera.matrixWorldInverse );

		var style = cameraCSSMatrix +
			'translate(' + _widthHalf + 'px,' + _heightHalf + 'px)';

		if ( cache.camera.style !== style && ! isIE ) {

			cameraElement.style.WebkitTransform = style;
			cameraElement.style.MozTransform = style;
			cameraElement.style.transform = style;

			cache.camera.style = style;

		}

		renderObject( scene, camera, cameraCSSMatrix );

		if ( isIE ) {

			// IE10 and 11 does not support 'preserve-3d'.
			// Thus, z-order in 3D will not work.
			// We have to calc z-order manually and set CSS z-index for IE.
			// FYI: z-index can't handle object intersection
			zOrder( scene );

		}

	};

};
<|endoftext|>


<commit_before>/* global XMLHttpRequest, expect */

function loadBinaryResource (url, unicodeCleanUp) {
  const req = new XMLHttpRequest()
  req.open('GET', url, false)
   // XHR binary charset opt by Marcus Granado 2006 [http://mgran.blogspot.com]
  req.overrideMimeType('text\/plain; charset=x-user-defined');
  req.send(null)
  if (req.status !== 200) {
    throw new Error('Unable to load file')
  }
      var responseText = req.responseText;
    var responseTextLen = req.responseText.length;
    if (unicodeCleanUp === true) {
      var byteArray = [];
      let asciidDecoder = new TextDecoder('iso-8859-1');
      var i = 0;
      for (i = 0; i < req.responseText.length; i += 1) {
        byteArray.push(req.responseText.charCodeAt(i) & 0xff);
      }
      return asciidDecoder.decode(new Uint8Array(byteArray));
    }
  return req.responseText;
}

function sendReference (filename, data) {
  const req = new XMLHttpRequest()
  req.open('POST', `http://localhost:9090/${filename}`, true)
  req.onload = e => {
    console.log(e)
  }
  req.send(data)
}

const resetCreationDate = input =>
  input.replace(
    /\/CreationDate \(D:(.*?)\)/,
    '/CreationDate (D:19871210000000+00\'00\'\)'
  )

/**
 * Find a better way to set this
 * @type {Boolean}
 */
window.comparePdf = (actual, expectedFile, suite, unicodeCleanUp) => {
  let pdf;
  unicodeCleanUp = unicodeCleanUp || false;
  try {
    pdf = loadBinaryResource(`/base/tests/${suite}/reference/${expectedFile}`, unicodeCleanUp)
  } catch (error) {
    sendReference(`/tests/${suite}/reference/${expectedFile}`, resetCreationDate(actual))
    pdf = actual
  }
  const expected = resetCreationDate(pdf).trim()
  actual = resetCreationDate(actual.trim())

  expect(actual).toEqual(expected)
}
<commit_msg>Update compare.js<commit_after>/* global XMLHttpRequest, expect */

function loadBinaryResource (url, unicodeCleanUp) {
  const req = new XMLHttpRequest()
  req.open('GET', url, false)
   // XHR binary charset opt by Marcus Granado 2006 [http://mgran.blogspot.com]
  req.overrideMimeType('text\/plain; charset=x-user-defined');
  req.send(null)
  if (req.status !== 200) {
    throw new Error('Unable to load file')
  }
      var responseText = req.responseText;
    var responseTextLen = req.responseText.length;
    if (unicodeCleanUp === true) {
      var byteArray = [];
      //let asciidDecoder = new TextDecoder('iso-8859-1');
      var i = 0;
      for (i = 0; i < req.responseText.length; i += 1) {
        byteArray.push(req.responseText.charCodeAt(i) & 0xff);
      }
      return String.fromCharCode.apply(null, new Uint8Array(byteArray));
      //return asciidDecoder.decode(new Uint8Array(byteArray));
    }
  return req.responseText;
}

function sendReference (filename, data) {
  const req = new XMLHttpRequest()
  req.open('POST', `http://localhost:9090/${filename}`, true)
  req.onload = e => {
    console.log(e)
  }
  req.send(data)
}

const resetCreationDate = input =>
  input.replace(
    /\/CreationDate \(D:(.*?)\)/,
    '/CreationDate (D:19871210000000+00\'00\'\)'
  )

/**
 * Find a better way to set this
 * @type {Boolean}
 */
window.comparePdf = (actual, expectedFile, suite, unicodeCleanUp) => {
  let pdf;
  unicodeCleanUp = unicodeCleanUp || false;
  try {
    pdf = loadBinaryResource(`/base/tests/${suite}/reference/${expectedFile}`, unicodeCleanUp)
  } catch (error) {
    sendReference(`/tests/${suite}/reference/${expectedFile}`, resetCreationDate(actual))
    pdf = actual
  }
  const expected = resetCreationDate(pdf).trim()
  actual = resetCreationDate(actual.trim())

  expect(actual).toEqual(expected)
}
<|endoftext|>


<commit_before>'use strict';

var Client = require('node-rest-client').Client;
var querystring = require('querystring');
var urljoin = require('url-join');
var _initialised = false;
var _serviceUrlTemplate;
var _clientId;
var _clientSecret;

function initialise(options) {
    if (!options) {
        throw new Error(module.exports.errorMessage.noOptions);
    }
    if (typeof (options) !== "object") {
        throw new Error(module.exports.errorMessage.optionsNotAnObject);
    }
    if (!options.neuronBaseUrl) {
        throw new Error(module.exports.errorMessage.neuronBaseUrlMustBeSpecified);
    }
    if (typeof (options.neuronBaseUrl) !== "string") {
        throw new Error(module.exports.errorMessage.neuronBaseUrlMustBeAString);
    }
    if (options.neuronBaseUrl.trim() === "") {
        throw new Error(module.exports.errorMessage.neuronBaseUrlCannotBeBlank);
    }
    if (!options.clientId) {
        throw new Error(module.exports.errorMessage.noClientId);
    }
    if (typeof (options.clientId) !== "string") {
        throw new Error(module.exports.errorMessage.clientIdMustBeAString);
    }
    if (options.clientId.trim() === "") {
        throw new Error(module.exports.errorMessage.clientIdCannotBeBlank);
    }

    if (!options.clientSecret) {
        throw new Error(module.exports.errorMessage.noClientSecret);
    }
    if (typeof (options.clientSecret) !== "string") {
        throw new Error(module.exports.errorMessage.clientSecretMustBeAString);
    }
    if (options.clientSecret.trim() === "") {
        throw new Error(module.exports.errorMessage.clientSecretCannotBeBlank);
    }
    _initialised = true;
    _clientId = options.clientId;
    _clientSecret = options.clientSecret;
    _serviceUrlTemplate = urljoin(options.neuronBaseUrl, ':programName/oauth/token');
}

function getServiceUrlTemplate() {
    return _serviceUrlTemplate;
}

function getToken(inputs, callback) {
    if (!inputs) {
        return callback(new Error(module.exports.errorMessage.noInputs));
    }
    if (typeof (inputs) !== "object") {
        return callback(new Error(module.exports.errorMessage.inputsNotAnObject));
    }
    if (!callback) {
        throw new Error(module.exports.errorMessage.noCallback);
    }
    if (typeof (callback) !== "function") {
        throw new Error(module.exports.errorMessage.callbackNotAFunction);
    }
    if (!inputs.programName) {
        return callback(new Error(module.exports.errorMessage.programNameRequired));
    }
    if (typeof (inputs.programName) !== "string") {
        return callback(new Error(module.exports.errorMessage.programNameMustBeAString));
    }
    if (inputs.programName.trim() === "") {
        return callback(new Error(module.exports.errorMessage.programNameCannotBeBlank));
    }
    if (_initialised === false) {
        return callback(new Error(module.exports.errorMessage.notInitialised));
    }
    var programName = inputs.programName;
    var url = _serviceUrlTemplate.replace(':programName', programName);
    var body = {
        "client_id": _clientId,
        "client_secret": _clientSecret,
        "grant_type": "client_credentials",
        "scope": inputs.scope
    };
    var args = {
        data: querystring.stringify(body),
        headers: {
            "Content-Type": "application/x-www-form-urlencoded"
        }
    };
    var client = new Client();
    var req = client.post(url, args, function (data, response) {
        var tokenString;
        if (Buffer.isBuffer(data)) {
            tokenString = data.toString('utf8');
        } else if (typeof data === 'string') {
            tokenString = data;
        }
        if (response.statusCode !== 200) {
            return callback(new Error(tokenString));
        }
        var token = JSON.parse(tokenString);
        if (!token.access_token) {
            throw new Error(module.exports.errorMessage.noAccessToken);
        }
        return callback(null, token.access_token);
    });
    req.on('requestTimeout', function (req) {
        req.abort();
        return callback(new Error(module.exports.errorMessage.requestTimeout));
    });

    req.on('responseTimeout', function (res) {
        return callback(new Error(module.exports.errorMessage.responseTimeout));
    });

    req.on('error', function (err) {
        return callback(err);
    });

}

module.exports = {
    initialise: initialise,
    getToken: getToken,
    getServiceUrlTemplate: getServiceUrlTemplate,
    errorMessage: {
        noOptions: "initialise must be called with options",
        optionsNotAnObject: "options must be an object",
        neuronBaseUrlMustBeSpecified: "neuronBaseUrl must be set",
        neuronBaseUrlMustBeAString: "Neuron base url must be a string",
        neuronBaseUrlCannotBeBlank: "Neuron base url cannot be blank",
        noClientId: "clientId must be set",
        clientIdMustBeAString: "clientId must be a string",
        clientIdCannotBeBlank: "clientId cannot be blank",
        noClientSecret: "clientSecret must be specified",
        clientSecretMustBeAString: "clientSecret must be a string",
        clientSecretCannotBeBlank: "clientSecret cannot be blank",
        noInputs: "Input must be specified when getToken is called",
        inputsNotAnObject: "The first argument (inputs) on getToken must be an object",
        noCallback: "Callback must be specified when getToken is called",
        callbackNotAFunction: "callback must be a function",
        programNameRequired: "inputs.program name is required",
        programNameMustBeAString: "Program name must be a string",
        programNameCannotBeBlank: "Program name cannot be blank",
        notInitialised: "neuron-synapse has not yet been initialised",
        noAccessToken: "token object did not contain the property access_token",
        requestTimeout: 'request has expired',
        responseTimeout: 'response has expired'
    }
};
<commit_msg>updating code to store the token in the memory cache if it has an expires_in field and that is greater than 30 seconds.<commit_after>'use strict';

var Client = require('node-rest-client').Client;
var querystring = require('querystring');
var urljoin = require('url-join');
var _initialised = false;
var _serviceUrlTemplate;
var _clientId;
var _clientSecret;
var _programCache;
var _tokenSafetyIntervalInSeconds = 30;

function initialise(options) {
    if (!options) {
        throw new Error(module.exports.errorMessage.noOptions);
    }
    if (typeof (options) !== "object") {
        throw new Error(module.exports.errorMessage.optionsNotAnObject);
    }
    if (!options.neuronBaseUrl) {
        throw new Error(module.exports.errorMessage.neuronBaseUrlMustBeSpecified);
    }
    if (typeof (options.neuronBaseUrl) !== "string") {
        throw new Error(module.exports.errorMessage.neuronBaseUrlMustBeAString);
    }
    options.neuronBaseUrl = options.neuronBaseUrl.trim();
    if (options.neuronBaseUrl === "") {
        throw new Error(module.exports.errorMessage.neuronBaseUrlCannotBeBlank);
    }
    if (!options.clientId) {
        throw new Error(module.exports.errorMessage.noClientId);
    }
    if (typeof (options.clientId) !== "string") {
        throw new Error(module.exports.errorMessage.clientIdMustBeAString);
    }
    options.clientId = options.clientId.trim();
    if (options.clientId === "") {
        throw new Error(module.exports.errorMessage.clientIdCannotBeBlank);
    }

    if (!options.clientSecret) {
        throw new Error(module.exports.errorMessage.noClientSecret);
    }
    if (typeof (options.clientSecret) !== "string") {
        throw new Error(module.exports.errorMessage.clientSecretMustBeAString);
    }
    options.clientSecret = options.clientSecret.trim();
    if (options.clientSecret === "") {
        throw new Error(module.exports.errorMessage.clientSecretCannotBeBlank);
    }
    _initialised = true;
    _programCache = {};
    _clientId = options.clientId;
    _clientSecret = options.clientSecret;
    _serviceUrlTemplate = urljoin(options.neuronBaseUrl, ':programName/oauth/token');
}

function getServiceUrlTemplate() {
    return _serviceUrlTemplate;
}

function getToken(inputs, callback) {
    if (!inputs) {
        return callback(new Error(module.exports.errorMessage.noInputs));
    }
    if (typeof (inputs) !== "object") {
        return callback(new Error(module.exports.errorMessage.inputsNotAnObject));
    }
    if (!callback) {
        throw new Error(module.exports.errorMessage.noCallback);
    }
    if (typeof (callback) !== "function") {
        throw new Error(module.exports.errorMessage.callbackNotAFunction);
    }
    if (!inputs.programName) {
        return callback(new Error(module.exports.errorMessage.programNameRequired));
    }
    if (typeof (inputs.programName) !== "string") {
        return callback(new Error(module.exports.errorMessage.programNameMustBeAString));
    }
    inputs.programName = inputs.programName.trim();
    if (inputs.programName === "") {
        return callback(new Error(module.exports.errorMessage.programNameCannotBeBlank));
    }
    if (_initialised === false) {
        return callback(new Error(module.exports.errorMessage.notInitialised));
    }
    if (!inputs.scope) {
        inputs.scope = "";
    }
    var programName = inputs.programName;
    var url = _serviceUrlTemplate.replace(':programName', programName);
    var body = {
        "client_id": _clientId,
        "client_secret": _clientSecret,
        "grant_type": "client_credentials",
        "scope": inputs.scope
    };
    var args = {
        data: querystring.stringify(body),
        headers: {
            "Content-Type": "application/x-www-form-urlencoded"
        }
    };
    var client = new Client();
    var req = client.post(url, args, function (data, response) {
        var tokenString;
        if (Buffer.isBuffer(data)) {
            tokenString = data.toString('utf8');
        } else if (typeof data === 'string') {
            tokenString = data;
        }
        if (response.statusCode !== 200) {
            return callback(new Error(tokenString));
        }
        var token = JSON.parse(tokenString);
        if (!token.access_token) {
            throw new Error(module.exports.errorMessage.noAccessToken);
        }
        if (token.expires_in && token.expires_in > _tokenSafetyIntervalInSeconds) {
            cacheToken(token, programName, inputs.scope);
        }
        return callback(null, token.access_token);
    });
    req.on('requestTimeout', function (req) {
        req.abort();
        return callback(new Error(module.exports.errorMessage.requestTimeout));
    });

    req.on('responseTimeout', function () {
        return callback(new Error(module.exports.errorMessage.responseTimeout));
    });

    req.on('error', function (err) {
        return callback(err);
    });

}

function cacheToken(token, programName, scope) {
    setExpiryDateOnToken(token);
    var thisProgramCache = getEnsureProgramCacheExists(programName);
    var cacheKey = getCacheKey(scope);
    thisProgramCache[cacheKey] = token;
}

function getCacheKey(scope) {
    var inputScopeArray = scope.toLowerCase().split(' ');
    var validScopes = [];
    inputScopeArray.forEach(function (scope) {
        if (scope !== '') {
            validScopes.push(scope);
        }
    });
    if (validScopes.length === 0) {
        validScopes.push("none");
    }
    validScopes = validScopes.sort();
    var cacheKey = validScopes.join('');
    return cacheKey;
}

function getEnsureProgramCacheExists(programName) {
    var lowerCaseProgramName = programName.toLowerCase();
    if (!_programCache[lowerCaseProgramName]) {
        _programCache[lowerCaseProgramName] = {};
    }
    return _programCache[lowerCaseProgramName];
}

function setExpiryDateOnToken(token) {
    var secondsuntilTokenExpires = token.expires_in - _tokenSafetyIntervalInSeconds; //remove the tokenSafetyIntervalInSeconds to ensure that the token does not expire mid request
    var expiryDate = new Date();
    expiryDate.setSeconds(expiryDate.getSeconds() + secondsuntilTokenExpires);
    token.expiryDate = expiryDate;
}

module.exports = {
    initialise: initialise,
    getToken: getToken,
    getServiceUrlTemplate: getServiceUrlTemplate,
    errorMessage: {
        noOptions: "initialise must be called with options",
        optionsNotAnObject: "options must be an object",
        neuronBaseUrlMustBeSpecified: "neuronBaseUrl must be set",
        neuronBaseUrlMustBeAString: "Neuron base url must be a string",
        neuronBaseUrlCannotBeBlank: "Neuron base url cannot be blank",
        noClientId: "clientId must be set",
        clientIdMustBeAString: "clientId must be a string",
        clientIdCannotBeBlank: "clientId cannot be blank",
        noClientSecret: "clientSecret must be specified",
        clientSecretMustBeAString: "clientSecret must be a string",
        clientSecretCannotBeBlank: "clientSecret cannot be blank",
        noInputs: "Input must be specified when getToken is called",
        inputsNotAnObject: "The first argument (inputs) on getToken must be an object",
        noCallback: "Callback must be specified when getToken is called",
        callbackNotAFunction: "callback must be a function",
        programNameRequired: "inputs.program name is required",
        programNameMustBeAString: "Program name must be a string",
        programNameCannotBeBlank: "Program name cannot be blank",
        notInitialised: "neuron-synapse has not yet been initialised",
        noAccessToken: "token object did not contain the property access_token",
        requestTimeout: 'request has expired',
        responseTimeout: 'response has expired'
    }
};
<|endoftext|>


<commit_before><commit_msg>[skip ci]<commit_after><|endoftext|>


<commit_before>
// Your library here<commit_msg>removed leftover from template - tests are now written for jquery.editinplace.js<commit_after><|endoftext|>


<commit_before><commit_msg>addRandomKeyTask не переберал ключи, а падал на совпадениях.<commit_after><|endoftext|>


<commit_before>module.exports = function (sails) {

	/**
	 * Module dependencies.
	 */

	var		util			= require( '../../util' ),
			SocketServer	= require('socket.io'),
			RedisStore		= require('socket.io/lib/stores/redis'),
			Redis			= require('socket.io/node_modules/redis'),
			Socket			= {
				authorization	: require('./authorization')(sails),
				connection		: require('./connection')(sails)
			};

	/**
	 * configure()
	 * @param {Function} cb
	 *
	 * Prepare the nascent ws:// server (but don't listen for connections yet)
	 */

	return function configure (cb) {
		sails.log.verbose('Configuring socket (ws://) server...');

		var socketConfig = sails.config.sockets;

		// Socket.io server (WebSockets+polyfill to support Flash sockets, AJAX long polling, etc.)
		var io = sails.io = sails.ws =
		SocketServer.listen(sails.express.server, {
			logger: {
				info: function (){}
			}
		});

		// If logger option not set, use the default Sails logger config
		if (!socketConfig.logger) {
			var logLevels = {
				'silent': 0,
				'error': 1,
				'warn': 2,
				'debug': 4, // Socket.io flips these around (and it considers debug more `verbose` than `info`)
				'info': 3,	// Socket.io flips these around
				'verbose': 4	// Socket.io has no concept of `verbose`
			};
			io.set('log level', logLevels[sails.config.log.level] || logLevels['info']);
			io.set('logger', {
				error: sails.log.error,
				warn: sails.log.warn,
				info: sails.log.info,
				debug: sails.log.verbose // socket.io considers `debug` the most verbose config, so we'll use verbose to represent it
			});
		}

		// Process the Config File
		util.each(socketConfig, function(value, propertyName) {

			// Handle `Memory` adapter value
			if (propertyName === 'adapter' && value === 'memory') return;

			// Setup custom socket.io MQ (pubsub) store(s)
			if (propertyName === 'adapter' && value === 'redis') {
				var host = socketConfig.host || '127.0.0.1';
				var port = socketConfig.port || 6379;

				var pub = createRedisConnection(port, host);
				var sub = createRedisConnection(port, host);
				var client = createRedisConnection(port, host);

				var storeConfig = {
					redisPub: pub,
					redisSub: sub,
					redisClient: client
				};

				// Add a pointer to the redis, required with Auth
				if(socketConfig.pass) {
					storeConfig.redis = Redis;
				}

				io.set('store', new RedisStore(storeConfig));
				return;
			}

			// Configure logic to be run before allowing sockets to connect
			if (propertyName === 'authorization') {

				// Custom logic
				if (util.isFunction(value)) {
					io.set('authorization', value);
					return;
				}

				// `authorization: true` means go ahead and use the default behavior
				if (value === true) {
					io.set('authorization', Socket.authorization);
					return;
				}

				// Otherwise skip the authorization step
				io.set('authorization', false);

				return;
			}

			// If value is explicitly undefined, do nothing
			if (util.isUndefined(value)) return;

			// In the general case, pass the configuration straight down to socket.io
			io.set(propertyName, value);

		});

		// For later:
		// io.configure('development', function() {});
		// io.configure('production', function() {});

		// Link Socket.io requests to a controller/action
		// When a socket.io client connects, listen for the actions in the routing table
		// Authorization has already passed at this point!
		io.sockets.on('connection', Socket.connection);

		cb && cb();
	};

	/**
	 * Creates a new Redis Connection if specified.
	 *
	 * Can be used to connect to remote server with authentication if
	 * `pass` is declared in the socketConfig file.
	 */

	function createRedisConnection(port, host) {

		var socketConfig = sails.config.sockets;

		// Create a new client using the port, host and other options
		var client = Redis.createClient(port, host, socketConfig);

		// If a password is needed use client.auth to set it
		if(socketConfig.pass) {
			client.auth(socketConfig.pass, function(err) {
		        if (err) throw err;
		    });
		}

		// If a db is set select it on the client
		if (socketConfig.db) {
			client.select(socketConfig.db);
		}

		return client;
	}

};
<commit_msg>adding an onError event listener and on connect to know when reconnected<commit_after>module.exports = function (sails) {

	/**
	 * Module dependencies.
	 */

	var		util			= require( '../../util' ),
			SocketServer	= require('socket.io'),
			RedisStore		= require('socket.io/lib/stores/redis'),
			Redis			= require('socket.io/node_modules/redis'),
			Socket			= {
				authorization	: require('./authorization')(sails),
				connection		: require('./connection')(sails)
			};

	/**
	 * configure()
	 * @param {Function} cb
	 *
	 * Prepare the nascent ws:// server (but don't listen for connections yet)
	 */

	return function configure (cb) {
		sails.log.verbose('Configuring socket (ws://) server...');

		var socketConfig = sails.config.sockets;

		// Socket.io server (WebSockets+polyfill to support Flash sockets, AJAX long polling, etc.)
		var io = sails.io = sails.ws =
		SocketServer.listen(sails.express.server, {
			logger: {
				info: function (){}
			}
		});

		// If logger option not set, use the default Sails logger config
		if (!socketConfig.logger) {
			var logLevels = {
				'silent': 0,
				'error': 1,
				'warn': 2,
				'debug': 4, // Socket.io flips these around (and it considers debug more `verbose` than `info`)
				'info': 3,	// Socket.io flips these around
				'verbose': 4	// Socket.io has no concept of `verbose`
			};
			io.set('log level', logLevels[sails.config.log.level] || logLevels['info']);
			io.set('logger', {
				error: sails.log.error,
				warn: sails.log.warn,
				info: sails.log.info,
				debug: sails.log.verbose // socket.io considers `debug` the most verbose config, so we'll use verbose to represent it
			});
		}

		// Process the Config File
		util.each(socketConfig, function(value, propertyName) {

			// Handle `Memory` adapter value
			if (propertyName === 'adapter' && value === 'memory') return;

			// Setup custom socket.io MQ (pubsub) store(s)
			if (propertyName === 'adapter' && value === 'redis') {
				var host = socketConfig.host || '127.0.0.1';
				var port = socketConfig.port || 6379;

				var pub = createRedisConnection(port, host);
				var sub = createRedisConnection(port, host);
				var client = createRedisConnection(port, host);

				var storeConfig = {
					redisPub: pub,
					redisSub: sub,
					redisClient: client
				};

				// Add a pointer to the redis, required with Auth
				if(socketConfig.pass) {
					storeConfig.redis = Redis;
				}

				io.set('store', new RedisStore(storeConfig));
				return;
			}

			// Configure logic to be run before allowing sockets to connect
			if (propertyName === 'authorization') {

				// Custom logic
				if (util.isFunction(value)) {
					io.set('authorization', value);
					return;
				}

				// `authorization: true` means go ahead and use the default behavior
				if (value === true) {
					io.set('authorization', Socket.authorization);
					return;
				}

				// Otherwise skip the authorization step
				io.set('authorization', false);

				return;
			}

			// If value is explicitly undefined, do nothing
			if (util.isUndefined(value)) return;

			// In the general case, pass the configuration straight down to socket.io
			io.set(propertyName, value);

		});

		// For later:
		// io.configure('development', function() {});
		// io.configure('production', function() {});

		// Link Socket.io requests to a controller/action
		// When a socket.io client connects, listen for the actions in the routing table
		// Authorization has already passed at this point!
		io.sockets.on('connection', Socket.connection);

		cb && cb();
	};

	/**
	 * Creates a new Redis Connection if specified.
	 *
	 * Can be used to connect to remote server with authentication if
	 * `pass` is declared in the socketConfig file.
	 */

	function createRedisConnection(port, host) {

		var socketConfig = sails.config.sockets;

		// Create a new client using the port, host and other options
		var client = Redis.createClient(port, host, socketConfig);

		// If a password is needed use client.auth to set it
		if(socketConfig.pass) {
			client.auth(socketConfig.pass, function(err) {
		        if (err) throw err;
		    });
		}

		if (socketConfig.onError) {
			client.on('error', socketConfig.onError);
		}

		if (socketConfig.onReady) {
			var event = 'ready';
			if (socketConfig.no_ready_check) {
				event = 'connect';
			}
			client.on(event, socketConfig.onReady);
		}

		// If a db is set select it on the client
		if (socketConfig.db) {
			client.select(socketConfig.db);
		}

		return client;
	}

};
<|endoftext|>


<commit_before>function setCarouselSize() {
    var wWidth = $(window).width();
    var wHeight = $(window).height();

    if (wHeight > wWidth) {
        var containerHeight = wHeight * $('.img-cartoon').width() / wWidth;
    } else {
        $('#carousel-example-generic').height($(window).height()-$('#panel-title').height());
    }
}

$(function() {
    setCarouselSize();
});

$(window).resize(function(){
    setCarouselSize();
});<commit_msg>Add logic to handle vertical screens<commit_after>function setCarouselSize() {
    var wWidth = $(window).width();
    var wHeight = $(window).height();

    var originalImageHeight = 1080;
    var originalImageWidth = 1920;

    if (wHeight > wWidth) {
        var containerHeight = originalImageHeight * wWidth / originalImageWidth;
        $('#carousel-example-generic').height(containerHeight);
    } else {
        $('#carousel-example-generic').height($(window).height()-$('#panel-title').height());
    }
}

$(function() {
    setCarouselSize();
});

$(window).resize(function(){
    setCarouselSize();
});<|endoftext|>


<commit_before>var log = require('../../utils/logging').log;

// current level is info
log( "info", "SHOULD be shown" );
log( "error", "SHOULD NOT be shown" );
log( "debug", "SHOULD NOT be shown" );

global.LOG_LEVEL = "debug";

log( "info", "SHOULD be shown" );
log( "error", "SHOULD be shown" );
log( "debug", "SHOULD be shown" );

global.LOG_LEVEL = "info";

log( "info", "SHOULD be shown" );
log( "error", "SHOULD be shown" );
log( "debug", "SHOULD NOT be shown" );

// invalid global level, nothing shown
global.LOG_LEVEL = "invalid";

log( "info", "SHOULD NOT be shown" );
log( "error", "SHOULD NOT be shown" );
log( "debug", "SHOULD NOT be shown" );

// invalid log level, nothing shown
global.LOG_LEVEL = "debug";

log( "invalid", "SHOULD NOT be shown" );
<commit_msg>Touched up test<commit_after>var log = require('../../utils/logging').log;

log("info", "If you see a SHOULD NOT be shown from this point on, thats BAD\n----------");
// but there's no way to actually test for it

// current level is info
log( "info", "SHOULD be shown" );
log( "error", "SHOULD NOT be shown" );
log( "debug", "SHOULD NOT be shown" );

global.LOG_LEVEL = "debug";

log( "info", "SHOULD be shown" );
log( "error", "SHOULD be shown" );
log( "debug", "SHOULD be shown" );

global.LOG_LEVEL = "info";

log( "info", "SHOULD be shown" );
log( "error", "SHOULD be shown" );
log( "debug", "SHOULD NOT be shown" );

// invalid global level, nothing shown
global.LOG_LEVEL = "invalid";

log( "info", "SHOULD NOT be shown" );
log( "error", "SHOULD NOT be shown" );
log( "debug", "SHOULD NOT be shown" );

// invalid log level, nothing shown
global.LOG_LEVEL = "debug";

log( "invalid", "SHOULD NOT be shown" );
<|endoftext|>


<commit_before>var fs = require('fs');
var request = require("request"),
    syncRequest = require("sync-request"),
    cheerio = require("cheerio"),
    sleep = require("sleep"),
    Levenshtein = require('levenshtein'),
    url = 'https://github.com/JJ/top-github-users-data/blob/master/formatted/top-alt-Spain.md';

var replaceAll = function(find, replace, str) {
    var find = find.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
    return str.replace(new RegExp(find, 'g'), replace);
};

var createDir = function(dir) {
    if (!fs.existsSync(dir)) {
        fs.mkdirSync(dir);
    }
};

var topgithub = function() {};

var position, username, commits, stars, language, city, avatar, $td;
var users = [], usr;

var features = [];
var cities = {};
var citiesObj = JSON.parse(fs.readFileSync('municipios.json'));
topgithub.prototype.request = function(url) {
    var self = this;
    request(url, function(error, response, body) {
        if (!error) {
            var $ = cheerio.load(body);

            var result = [];

            $('.container #readme table tr').filter(function(i, el) {
                $td = $(this).find('td').first();
                position = $td.text();
                username = $td.next().text();
                commits = $td.next().next().text();
                stars = $td.next().next().next().text();
                languages = $td.next().next().next().next().text();
                city = $td.next().next().next().next().next().text();
                avatar = $td.next().next().next().next().next().next().find('a').attr('href');

                user = {
                    'position': position,
                    'username': username,
                    'commits': commits,
                    'stars': stars,
                    'languages': languages,
                    'city': city,
                    'avatar': avatar
                };

                var coords = self.getLonLat(city);

                if (username) {
                    features.push({
                        'type': 'Feature',
                        'geometry' : {
                            'type': 'Point',
                            'coordinates': coords
                        },
                        'properties': user
                    });
                }
            });

            var es = {
                'featureCollection': {
                    'features': features
                }
            };

            var output = 'top_github_ES.geojson';

            fs.writeFileSync(output, JSON.stringify(es, null, 4));

            console.log('File successfully written! - Check your project directory for the ' + output + ' file');
        } else {
            console.log("We’ve encountered an error: " + error);
        }
    });
};

topgithub.prototype.getLonLat = function(city) {
    var cityParts = city.split(',');
    var c, coord, found = false;
    for (var i = 0; i < cityParts.length; i++) {
        if (found) {
            break;
        }

        c = cityParts[i].trim();

        if (!cities[c]) {
            for (var j = 0; j < citiesObj.length; j++) {
                if (new Levenshtein(citiesObj[j].municipio, c).distance <= 3) {
                    coord = [citiesObj[j].longitud, citiesObj[j].latitud];
                    cities[c] = coord;
                    found = true;
                    break;
                }
            }
        } else {
            coord = cities[c];
        }
    }
    return coord;
}

var ttt = new topgithub();
ttt.request(url);

exports = module.exports = topgithub;<commit_msg>Working<commit_after>var fs = require('fs');
var request = require("request"),
    syncRequest = require("sync-request"),
    cheerio = require("cheerio"),
    sleep = require("sleep"),
    Levenshtein = require('levenshtein'),
    url = 'https://github.com/JJ/top-github-users-data/blob/master/formatted/top-alt-Spain.md';

var replaceAll = function(find, replace, str) {
    var find = find.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
    return str.replace(new RegExp(find, 'g'), replace);
};

var createDir = function(dir) {
    if (!fs.existsSync(dir)) {
        fs.mkdirSync(dir);
    }
};

var topgithub = function() {};

var position, username, commits, stars, language, city, avatar, $td;
var users = [], usr;

var features = [];
var cities = {};
var citiesObj = JSON.parse(fs.readFileSync('municipios.json'));
topgithub.prototype.request = function(url) {
    var self = this;
    request(url, function(error, response, body) {
        if (!error) {
            var $ = cheerio.load(body);

            var result = [];

            $('.container #readme table tr').filter(function(i, el) {
                $td = $(this).find('td').first();
                position = $td.text();
                username = $td.next().text();
                commits = $td.next().next().text();
                stars = $td.next().next().next().text();
                languages = $td.next().next().next().next().text();
                city = $td.next().next().next().next().next().text();
                avatar = $td.next().next().next().next().next().next().find('a').attr('href');

                user = {
                    'position': position,
                    'username': username,
                    'commits': commits,
                    'stars': stars,
                    'languages': languages,
                    'city': city,
                    'avatar': avatar
                };

                var coords = self.getLonLat(city);

                if (username) {
                    features.push({
                        'type': 'Feature',
                        'geometry' : {
                            'type': 'Point',
                            'coordinates': coords
                        },
                        'properties': user
                    });
                }
            });

            var es = {
                'featureCollection': {
                    'features': features
                }
            };

            var output = 'top_github_ES.geojson';

            fs.writeFileSync(output, JSON.stringify(es, null, 4));

            console.log('File successfully written! - Check your project directory for the ' + output + ' file');
        } else {
            console.log("We’ve encountered an error: " + error);
        }
    });
};

topgithub.prototype.getLonLat = function(city) {
    var cityParts = city.split(',');
    var c, coord, found = false;
    for (var i = 0; i < cityParts.length; i++) {
        if (found) {
            break;
        }

        c = cityParts[i].trim().toLowerCase();

        if (!cities[c]) {
            for (var j = 0; j < citiesObj.length; j++) {
                if (new Levenshtein(citiesObj[j].municipio.toLowerCase(), c.toLowerCase()).distance <= 1) {
                    coord = [citiesObj[j].longitud, citiesObj[j].latitud];
                    cities[c] = coord;
                    found = true;
                    // console.log(citiesObj[j].municipio.toLowerCase() + ' - ' + c.toLowerCase());
                    break;
                }
            }
        } else {
            coord = cities[c];
        }
    }
    return coord;
}

var ttt = new topgithub();
ttt.request(url);

exports = module.exports = topgithub;<|endoftext|>


<commit_before>#!/usr/bin/env node
"use strict";

var Snoocore = require('snoocore');
var reddit = new Snoocore({ userAgent: 'myApp v0.0.0' });

// Example code for http://www.reddit.com/dev/api#GET_new
// [/r/*subreddit*]/new

// Brackets `[]` denote optional sections of the URL, we can
// Leave out [/r/subreddit] to get new posts site wide
var frontpagePromise = reddit('/hot').get();

// Or specify a subreddit with the url parameter *subreddit*
var netsecFrontpagePromise = reddit('/r/$subreddit/hot').get({
	$subreddit: 'netsec',
	limit: 10
});

frontpagePromise.done(function(results) {
	console.log('FRONTPAGE');
	console.log(results);
});

netsecFrontpagePromise.done(function(results) {
	console.log('NETSEC FRONTPAGE');
	console.log(results);
});<commit_msg>update example<commit_after>#!/usr/bin/env node
"use strict";

var Snoocore = require('../../Snoocore');
var reddit = new Snoocore({ userAgent: 'myApp v0.0.0' });

// Example code for http://www.reddit.com/dev/api#GET_new
// [/r/*subreddit*]/new

// Brackets `[]` denote optional sections of the URL, we can
// Leave out [/r/subreddit] to get new posts site wide
var frontpagePromise = reddit('/hot').get();

// Or specify a subreddit with the url parameter *subreddit*
var netsecFrontpagePromise = reddit('/r/$subreddit/hot').get({
	$subreddit: 'netsec',
	limit: 10
});

frontpagePromise.done(function(results) {
	console.log('FRONTPAGE');
	console.log(results);
});

netsecFrontpagePromise.done(function(results) {
	console.log('NETSEC FRONTPAGE');
	console.log(results);
});<|endoftext|>


<commit_before>((function(){var a,b,c,d,e,f,g;jQuery.fn.render=function(a,c){var d;return d=this,b(d.get(),a,c),d},window.render=b=function(a,b,e){var h,i,j,k,l,m,n,o;typeof a.length!="number"&&(a=[a]),b instanceof Array||(b=[b]),e||(e={});for(l=0,n=a.length;l<n;l++){h=a[l],h.t||(h.t=h.cloneNode(!0));while(i=h.firstChild)h.removeChild(i);for(m=0,o=b.length;m<o;m++){j=b[m],k=h.t.cloneNode(!0),f(k,j),g(k,j),d(k,j,e),c(k,j,e);while(i=k.firstChild)h.appendChild(i)}}return a},f=function(a,b){var c;if(typeof b!="object")return c=a.querySelector(".listElement")||a.querySelector("*"),e(c,b)},g=function(b,c){var d,f,g,h;h=[];for(f in c)g=c[f],typeof g!="object"&&h.push(function(){var c,h,i,j;i=a(b,f),j=[];for(c=0,h=i.length;c<h;c++)d=i[c],j.push(e(d,g));return j}());return h},d=function(b,c,d){var f,g,h,i,j,k;k=[];for(h in d){g=d[h];if(typeof g!="function")continue;j=h.split("@"),h=j[0],f=j[1],k.push(function(){var d,j,k,l;k=a(b,h),l=[];for(d=0,j=k.length;d<j;d++)i=k[d],l.push(e(i,g.call(c,i),f));return l}())}return k},c=function(c,d,e){var f,g,h;h=[];for(f in d)g=d[f],typeof g=="object"&&h.push(b(a(c,f),g,e[f]));return h},e=function(a,b,c){var d,e,f,g,h;if(c)return a.setAttribute(c,b);h=function(){var b,c,e,f;e=a.childNodes,f=[];for(b=0,c=e.length;b<c;b++)d=e[b],d.nodeType===3&&f.push(d);return f}();for(f=0,g=h.length;f<g;f++)e=h[f],a.removeChild(e);return a.insertBefore(document.createTextNode(b),a.firstChild)},a=function(a,b){return a.querySelectorAll("#"+b+", "+b+", ."+b+", [data-bind='"+b+"']")}})).call(this);<commit_msg>Compile new version<commit_after>((function(){var a,b,c,d,e,f,g,h;jQuery.fn.render=function(a,b){return c(this.get(),a,b),this},window.render=c=function(b,c,f){var i,j,k,l,m,n,o,p,q,r,s,t,u,v,w;typeof b.length!="number"&&(b=[b]),c instanceof Array||(c=[c]),f||(f={});for(s=0,u=b.length;s<u;s++){i=b[s],i.t||(i.t={}),n=(p=i.t).parent||(p.parent=i),k=(q=i.t).instances||(q.instances=[]),(r=i.t).template||(r.template=function(){var a;a=[];while(l=i.firstChild)a.push(i.removeChild(l));return a}()),j=0;while(j<c.length){m=c[j],o=a(i,j),j+=1,g(o,m),h(o,m),e(o,m,f),d(o,m,f);while(l=o.firstChild)i.appendChild(l)}while(k.length>c.length){w=k.pop;for(t=0,v=w.length;t<v;t++)l=w[t],n.removeChild(l)}}return b},a=function(a,b){var c,d,e,f,g,h;e=document.createElement("div");if(b<a.t.instances.length){h=a.t.instances[b];for(f=0,g=h.length;f<g;f++)d=h[f],e.appendChild(d);return e}return c=function(){var b,c,f,g;f=a.t.template,g=[];for(b=0,c=f.length;b<c;b++)d=f[b],g.push(e.appendChild(d.cloneNode(!0)));return g}(),a.t.instances.push(c),e},g=function(a,b){var c;if(typeof b!="object")return c=a.querySelector(".listElement")||a.querySelector("*"),f(c,b)},h=function(a,c){var d,e,g,h;h=[];for(e in c)g=c[e],typeof g!="object"&&h.push(function(){var c,h,i,j;i=b(a,e),j=[];for(c=0,h=i.length;c<h;c++)d=i[c],j.push(f(d,g));return j}());return h},e=function(a,c,d){var e,g,h,i,j,k;k=[];for(h in d){g=d[h];if(typeof g!="function")continue;j=h.split("@"),h=j[0],e=j[1],k.push(function(){var d,j,k,l;k=b(a,h),l=[];for(d=0,j=k.length;d<j;d++)i=k[d],l.push(f(i,g.call(c,i),e));return l}())}return k},d=function(a,d,e){var f,g,h;h=[];for(f in d)g=d[f],typeof g=="object"&&h.push(c(b(a,f),g,e[f]));return h},f=function(a,b,c){var d,e,f,g,h,i;if(c)return a.setAttribute(c,b);if((a!=null?(h=a.t)!=null?h.text:void 0:void 0)!==b){i=function(){var b,c,e,f;e=a.childNodes,f=[];for(b=0,c=e.length;b<c;b++)d=e[b],d.nodeType===3&&f.push(d);return f}();for(f=0,g=i.length;f<g;f++)e=i[f],a.removeChild(e);return a.insertBefore(document.createTextNode(b),a.firstChild),a.t||(a.t={}),a.t.text=b}},b=function(a,b){return a.querySelectorAll("#"+b+", "+b+", ."+b+", [data-bind='"+b+"']")}})).call(this);<|endoftext|>


<commit_before>var _ = require("underscore");

var MAX_ALBUMS = 2
var MAX_PHOTOS_PER_ALBUM = 2

Parse.Cloud.define("newUser", function(request, response) {
	var thisUser = request.user;
	var locations = [];
	console.log("*****newUser photo count=" + request.params.roll.length);
	// find all the locations in the camera roll, count the photos at each location, find length of time at location
	// { id: unique_id, location: location_string, date: time_taken }
	var count = 0;
	_.each(request.params.roll, function(a) { reverseGeocode(a.location, function(geo) { a.reverseLocation = geo; if (++count >= request.params.roll.length) geoDone(); }) });
	function geoDone() {
		var albums = _.groupBy(request.params.roll, function(a) { return a.reverseLocation })
		albums = _.sortBy(albums, function(b) { -b.length });
		console.log("****************");
		if (albums.length > MAX_ALBUMS)
			albums.length = MAX_ALBUMS;
		_.each(albums, function(albumContents) {
			console.log("Album: " + albumContents[0].location + " " + albumContents.length + " photos");
			// sort by date earliest to latest
			albumContents = _.sortBy(album, function(a) { a.date });
			var Album = Parse.Object.extend("Album");
			var album = new Album();
			var worldACL = new Parse.ACL();
			worldACL.setPublicReadAccess(true);
			worldACL.setPublicWriteAccess(true);
			album.setACL(worldACL);
			console.log("******** saving album: " + makeAlbumTitle(albumContents));
			album.save({ type: "album", title: makeAlbumTitle(albumContents), comments: 0, likes: 0 } , {
				success: function(album) {
					if (albumContents.length > MAX_PHOTO_PER_ALBUM)
						albumContents.length = MAX_PHOTOS_PER_ALBUM;
					_.each(albumContents, function(post) {
						var Post = Parse.Object.extend("Post");
						var post = new Post();
						post.set("type", "post");
						post.set("views", 0);
						post.set("comments", 0);
						post.set("likes", 0);
						post.set("postedAt", post.date);
						post.set("persistentID", post.id);
						post.setACL(worldACL);
						reverseGeocode(albumContents[0].location, function(result) {
							console.log("******* Geolocation: " + result);
							post.set("location", result);
							post.save();
						});
					});
				},
				error: function(album, error) {
					console.error("************ newUser: error creating album: " + JSON.stringify(error));
				}
			});
		});
	}
	response.success("Success");
});

var geocoder = require('offline-geocoder')({ database: __dirname + "/data/geocode.db" });

function reverseGeocode(location, callback) {
	if (typeof(location.latitude) == "undefined" || typeof(location.longitude) == "undefined")
		callback("");
	else
		geocoder.reverse(location.latitude, location.longitude).then(function(result) { callback(result) });
}

function makeAlbumTitle(album) {
	// album is already sorted earliest to latest
	var timeStart = new Date(album[0].date);
	var timeEnd = new Date(album[album.length -1].date);
	var secDiff = hourDiff / 1000; //in s
	var minDiff = hourDiff / 60 / 1000; //in minutes
	var hDiff = hourDiff / 3600 / 1000; //in hours
	var day = timeStart.getDay();
	var month = timeStart.getMonth();
	var year = timeStart.getYear();
	var startHour = timeStart.getHours();
	var location = album[0].location;
	// holidays, thanksgiving, New Years, christmas July 4th etc, birthday
	var holidays = [
		{ name: "July 4th", start: "7/4", duration: 1 },
		{ name: "Christmas", start: "12/24", duration: 7 },
		{ name: "New Year", start: "12/31", duration: 2 },
	];
	var holiday = _.filter(holidays, function(h) {
		return day >= h.start && day < h.start + h.duration;
	});
	if (holiday.length > 0) {
		return holiday[0].name + " " + year;
	}
	// todo: variable holidays: Memorial Day, Easter, Labor Day, Thanksgiving
	if (starthour >= 6 && startHour + hDiff < 12)
		return "A morning in " + location;
	if (startHour >= 12 && startHour + hDiff < 18)
		return "An afternoon in " + location;
	if (startHour >= 18 && hDiff < 6)
		return "An evening in " + location;
	if (startHour >= 18 && hDiff < 12)
		return "A night in " + location;
	if (hDiff > 6 && hDiff < 24)
		return "A day in " + location;
	if (hDiff > 4*24 && hDiff < 10*24)
		return "A week in " + location;
	if (hdiff > 21*24 && hDiff < 42*24)
		return "A month in " + location;
	return location;
}

<commit_msg>Reverse geocoding<commit_after>var _ = require("underscore");

var MAX_ALBUMS = 2
var MAX_PHOTOS_PER_ALBUM = 2

Parse.Cloud.define("newUser", function(request, response) {
	var thisUser = request.user;
	var locations = [];
	console.log("*****newUser photo count=" + request.params.roll.length);
	// find all the locations in the camera roll, count the photos at each location, find length of time at location
	// { id: unique_id, location: location_string, date: time_taken }
	var count = 0;
	_.each(request.params.roll, function(a) { reverseGeocode(a.location, function(geo) { a.reverseLocation = geo; if (++count >= request.params.roll.length) geoDone(); }) });
	function geoDone() {
		var albums = _.groupBy(request.params.roll, function(a) { return a.reverseLocation })
		albums = _.sortBy(albums, function(b) { -b.length });
		console.log("****************");
		if (albums.length > MAX_ALBUMS)
			albums.length = MAX_ALBUMS;
		_.each(albums, function(albumContents) {
			console.log("Album: " + albumContents[0].location + " " + albumContents.length + " photos");
			// sort by date earliest to latest
			albumContents = _.sortBy(album, function(a) { a.date });
			var Album = Parse.Object.extend("Album");
			var album = new Album();
			var worldACL = new Parse.ACL();
			worldACL.setPublicReadAccess(true);
			worldACL.setPublicWriteAccess(true);
			album.setACL(worldACL);
			console.log("******** saving album: " + makeAlbumTitle(albumContents));
			album.save({ type: "album", title: makeAlbumTitle(albumContents), comments: 0, likes: 0 } , {
				success: function(album) {
					if (albumContents.length > MAX_PHOTO_PER_ALBUM)
						albumContents.length = MAX_PHOTOS_PER_ALBUM;
					_.each(albumContents, function(post) {
						var Post = Parse.Object.extend("Post");
						var post = new Post();
						post.set("type", "post");
						post.set("views", 0);
						post.set("comments", 0);
						post.set("likes", 0);
						post.set("postedAt", post.date);
						post.set("persistentID", post.id);
						post.setACL(worldACL);
						reverseGeocode(albumContents[0].location, function(result) {
							console.log("******* Geolocation: " + result);
							post.set("location", result);
							post.save();
						});
					});
				},
				error: function(album, error) {
					console.error("************ newUser: error creating album: " + JSON.stringify(error));
				}
			});
		});
	}
	response.success("Success");
});

var geocoder = require('offline-geocoder')({ database: __dirname + "/data/geocode.db" });

function reverseGeocode(location, callback) {
	console.log("*********** " + JSON.stringify(location);
	if (typeof(location.latitude) == "undefined" || typeof(location.longitude) == "undefined")
		callback("");
	else
		geocoder.reverse(location.latitude, location.longitude).then(function(result) { callback(result) });
}

function makeAlbumTitle(album) {
	// album is already sorted earliest to latest
	var timeStart = new Date(album[0].date);
	var timeEnd = new Date(album[album.length -1].date);
	var secDiff = hourDiff / 1000; //in s
	var minDiff = hourDiff / 60 / 1000; //in minutes
	var hDiff = hourDiff / 3600 / 1000; //in hours
	var day = timeStart.getDay();
	var month = timeStart.getMonth();
	var year = timeStart.getYear();
	var startHour = timeStart.getHours();
	var location = album[0].location;
	// holidays, thanksgiving, New Years, christmas July 4th etc, birthday
	var holidays = [
		{ name: "July 4th", start: "7/4", duration: 1 },
		{ name: "Christmas", start: "12/24", duration: 7 },
		{ name: "New Year", start: "12/31", duration: 2 },
	];
	var holiday = _.filter(holidays, function(h) {
		return day >= h.start && day < h.start + h.duration;
	});
	if (holiday.length > 0) {
		return holiday[0].name + " " + year;
	}
	// todo: variable holidays: Memorial Day, Easter, Labor Day, Thanksgiving
	if (starthour >= 6 && startHour + hDiff < 12)
		return "A morning in " + location;
	if (startHour >= 12 && startHour + hDiff < 18)
		return "An afternoon in " + location;
	if (startHour >= 18 && hDiff < 6)
		return "An evening in " + location;
	if (startHour >= 18 && hDiff < 12)
		return "A night in " + location;
	if (hDiff > 6 && hDiff < 24)
		return "A day in " + location;
	if (hDiff > 4*24 && hDiff < 10*24)
		return "A week in " + location;
	if (hdiff > 21*24 && hDiff < 42*24)
		return "A month in " + location;
	return location;
}

<|endoftext|>


<commit_before>'use strict';

// const { Client } = require('pg');
//
// const client = new Client({
//   connectionString: process.env.DATABASE_URL
// });
// client.connect();
//
// client.query('SELECT NOW()', (err, res) => {
//   console.log(err, res);
//   client.end();
// });

const Sequelize = require('sequelize');

const sequelize = new Sequelize({ url: process.env.DATABASE_URL, dialect: 'postgres', logging: false });

sequelize
  .query(
    'CREATE TABLE people ( id bigserial primary key, first_name varchar(10) NOT NULL, last_name varchar(10) NOT NULL, created timestamp NOT NULL, updated timestamp NOT NULL );'
  )
  .then(() => {
    console.log('Table created!');
    process.exit(0);
  })
  .catch(error => {
    console.log('Problem creating table', error);
    process.exit(1);
  });

// sequelize
//   .authenticate()
//   .then(() => {
//     console.log('DB Connected');
//   })
//   .catch(error => {
//     console.log("Can't connect to database", error);
//     process.exit(1);
//   });

// sequelize
//   .query('DROP TABLE people;')
//   .then(() => {
//     console.log('Table dropped!');
//     sequelize
//       .query(
//         'CREATE TABLE people ( id bigserial primary key, first_name varchar(10) NOT NULL, last_name varchar(10) NOT NULL, created timestamp NOT NULL, updated timestamp NOT NULL );'
//       )
//       .then(() => {
//         console.log('Table created!');
//         process.exit(0);
//       })
//       .catch(error => {
//         console.log('Problem creating table', error);
//         process.exit(1);
//       });
//   })
//   .catch(error => {
//     console.log('Problem dropping table', error);
//     process.exit(1);
//   });
<commit_msg>debugging circle<commit_after>'use strict';

const { Client } = require('pg');

const client = new Client({
  connectionString: process.env.DATABASE_URL
});
client.connect();

client.query('SELECT NOW()', (err, res) => {
  console.log(err, res);
  client.end();
});

const Sequelize = require('sequelize');

const sequelize = new Sequelize({ url: process.env.DATABASE_URL, dialect: 'postgres', logging: false });

sequelize
  .query(
    'CREATE TABLE people ( id bigserial primary key, first_name varchar(10) NOT NULL, last_name varchar(10) NOT NULL, created timestamp NOT NULL, updated timestamp NOT NULL );'
  )
  .then(() => {
    console.log('Table created!');
    process.exit(0);
  })
  .catch(error => {
    console.log('Problem creating table', error);
    process.exit(1);
  });

// sequelize
//   .authenticate()
//   .then(() => {
//     console.log('DB Connected');
//   })
//   .catch(error => {
//     console.log("Can't connect to database", error);
//     process.exit(1);
//   });

// sequelize
//   .query('DROP TABLE people;')
//   .then(() => {
//     console.log('Table dropped!');
//     sequelize
//       .query(
//         'CREATE TABLE people ( id bigserial primary key, first_name varchar(10) NOT NULL, last_name varchar(10) NOT NULL, created timestamp NOT NULL, updated timestamp NOT NULL );'
//       )
//       .then(() => {
//         console.log('Table created!');
//         process.exit(0);
//       })
//       .catch(error => {
//         console.log('Problem creating table', error);
//         process.exit(1);
//       });
//   })
//   .catch(error => {
//     console.log('Problem dropping table', error);
//     process.exit(1);
//   });
<|endoftext|>


<commit_before>var winston = require('winston');

// Logger for data output
var logger = new (winston.Logger)({
  transports: [
    new (winston.transports.File)({
      filename: 'Data.log'
    })
  ]
});

var outboundAirportName = 'Manchester, United Kingdom (MAN) To Brisbane, Australia (BNE)';
var inboundAirportName = 'Brisbane, Australia (BNE) To Manchester, United Kingdom (MAN)';
var cost = '';
var searchCommands = {

  VerifySearchPage: function(client) {
    this.waitForElementVisible('@outboundFlightContainerDiv', 3000)
      .waitForElementVisible('@inboundsFlightContainerDiv', 3000)
      .assert.containsText('@outboundFlightAirportLocation', outboundAirportName)
      .assert.containsText('@inboundFlightAirportLocation', inboundAirportName)

    logger.info('START');
    logger.warn(client.globals.departureAirport);
    logger.warn(client.globals.destinationAirport);

    return this;
  },
  getTextData: function(client, div) {
    this.getText(div, function(result) {
      cost = result.value;
      var dateAndPrice = cost.split("\n");
      var PriceWithCurrency = dateAndPrice[1].split(" ");
      var price = PriceWithCurrency[1];
      logger.info(price);
    });
     },

  GetData: function(client) {

    var elementValue = this.getText('@outboundMenu');
    this.waitForElementVisible('@outboundMenu', 2000)

    this.getTextData(client, "@outboundMenuDaySelectorFirst");
    this.getTextData(client, "@outboundMenuDaySelectorSecond");
    this.getTextData(client, "@outboundMenuDaySelectorThird");
    this.getTextData(client, "@outboundMenuDaySelectorFourth");
    this.getTextData(client, "@outboundMenuDaySelectorFive");
    this.getTextData(client, "@outboundMenuDaySelectorSix");
    this.getTextData(client, "@outboundMenuDaySelectorSeventh");

    this.getTextData(client, "@inboundMenuDaySelectorFirst");
    this.getTextData(client, "@inboundMenuDaySelectorSecond");
    this.getTextData(client, "@inboundMenuDaySelectorThird");
    this.getTextData(client, "@inboundMenuDaySelectorFourth");
    this.getTextData(client, "@inboundMenuDaySelectorFive");
    this.getTextData(client, "@inboundMenuDaySelectorSix");
    this.getTextData(client, "@inboundMenuDaySelectorSeventh");

    return this;
  }
};

module.exports = {
  url: function() {
    return this.launchUrl;
  },
  commands: [searchCommands],
  elements: {
    outboundFlightContainerDiv: {selector: 'div[id=outbounds]'},
    inboundsFlightContainerDiv: {selector: 'div[id=inbounds]'},
    outboundFlightAirportLocation: {selector: '#outbounds .flight-info .xchnge-section-dl'},
    inboundFlightAirportLocation: {selector: '#inbounds .flight-info .xchnge-section-dl'},
    outboundMenu: {selector: '#outbounds-3-menu'},
    outboundMenuDaySelectorFirst: {selector: '#outbounds-3-menu .yuimenubaritem'},
    outboundMenuDaySelectorSecond: {selector: '#outbounds-3-menu .yuimenubaritem:nth-child(2)'},
    outboundMenuDaySelectorThird: {selector: '#outbounds-3-menu .yuimenubaritem:nth-child(3)'},
    outboundMenuDaySelectorFourth: {selector: '#outbounds-3-menu .yuimenubaritem:nth-child(4)'},
    outboundMenuDaySelectorFive: {selector: '#outbounds-3-menu .yuimenubaritem:nth-child(5)'},
    outboundMenuDaySelectorSix: {selector: '#outbounds-3-menu .yuimenubaritem:nth-child(6)'},
    outboundMenuDaySelectorSeventh: {selector: '#outbounds-3-menu .yuimenubaritem:last-of-type'},
    inboundMenuDaySelectorFirst: {selector: '#inbounds-3-menu .yuimenubaritem'},
    inboundMenuDaySelectorSecond: {selector: '#inbounds-3-menu .yuimenubaritem:nth-child(2)'},
    inboundMenuDaySelectorThird: {selector: '#inbounds-3-menu .yuimenubaritem:nth-child(3)'},
    inboundMenuDaySelectorFourth: {selector: '#inbounds-3-menu .yuimenubaritem:nth-child(4)'},
    inboundMenuDaySelectorFive: {selector: '#inbounds-3-menu .yuimenubaritem:nth-child(5)'},
    inboundMenuDaySelectorSix: {selector: '#inbounds-3-menu .yuimenubaritem:nth-child(6)'},
    inboundMenuDaySelectorSeventh: {selector: '#inbounds-3-menu .yuimenubaritem:last-of-type'}
  }
};
<commit_msg>removed client from getTextData function<commit_after>var winston = require('winston');

// Logger for data output
var logger = new (winston.Logger)({
  transports: [
    new (winston.transports.File)({
      filename: 'Data.log'
    })
  ]
});

var outboundAirportName = 'Manchester, United Kingdom (MAN) To Brisbane, Australia (BNE)';
var inboundAirportName = 'Brisbane, Australia (BNE) To Manchester, United Kingdom (MAN)';
var cost = '';
var searchCommands = {

  VerifySearchPage: function(client) {
    this.waitForElementVisible('@outboundFlightContainerDiv', 3000)
      .waitForElementVisible('@inboundsFlightContainerDiv', 3000)
      .assert.containsText('@outboundFlightAirportLocation', outboundAirportName)
      .assert.containsText('@inboundFlightAirportLocation', inboundAirportName)

    logger.info('START');
    logger.warn(client.globals.departureAirport);
    logger.warn(client.globals.destinationAirport);

    return this;
  },
  getTextData: function(div) {
    this.getText(div, function(result) {
      cost = result.value;
      var dateAndPrice = cost.split("\n");
      var PriceWithCurrency = dateAndPrice[1].split(" ");
      var price = PriceWithCurrency[1];
      logger.info(price);
    });
  },

  GetData: function(client) {

    var elementValue = this.getText('@outboundMenu');
    this.waitForElementVisible('@outboundMenu', 2000)

    this.getTextData("@outboundMenuDaySelectorFirst");
    this.getTextData("@outboundMenuDaySelectorSecond");
    this.getTextData("@outboundMenuDaySelectorThird");
    this.getTextData("@outboundMenuDaySelectorFourth");
    this.getTextData("@outboundMenuDaySelectorFive");
    this.getTextData("@outboundMenuDaySelectorSix");
    this.getTextData("@outboundMenuDaySelectorSeventh");

    this.getTextData("@inboundMenuDaySelectorFirst");
    this.getTextData("@inboundMenuDaySelectorSecond");
    this.getTextData("@inboundMenuDaySelectorThird");
    this.getTextData("@inboundMenuDaySelectorFourth");
    this.getTextData("@inboundMenuDaySelectorFive");
    this.getTextData("@inboundMenuDaySelectorSix");
    this.getTextData("@inboundMenuDaySelectorSeventh");

    return this;
  }
};

module.exports = {
  url: function() {
    return this.launchUrl;
  },
  commands: [searchCommands],
  elements: {
    outboundFlightContainerDiv: {selector: 'div[id=outbounds]'},
    inboundsFlightContainerDiv: {selector: 'div[id=inbounds]'},
    outboundFlightAirportLocation: {selector: '#outbounds .flight-info .xchnge-section-dl'},
    inboundFlightAirportLocation: {selector: '#inbounds .flight-info .xchnge-section-dl'},
    outboundMenu: {selector: '#outbounds-3-menu'},
    outboundMenuDaySelectorFirst: {selector: '#outbounds-3-menu .yuimenubaritem'},
    outboundMenuDaySelectorSecond: {selector: '#outbounds-3-menu .yuimenubaritem:nth-child(2)'},
    outboundMenuDaySelectorThird: {selector: '#outbounds-3-menu .yuimenubaritem:nth-child(3)'},
    outboundMenuDaySelectorFourth: {selector: '#outbounds-3-menu .yuimenubaritem:nth-child(4)'},
    outboundMenuDaySelectorFive: {selector: '#outbounds-3-menu .yuimenubaritem:nth-child(5)'},
    outboundMenuDaySelectorSix: {selector: '#outbounds-3-menu .yuimenubaritem:nth-child(6)'},
    outboundMenuDaySelectorSeventh: {selector: '#outbounds-3-menu .yuimenubaritem:last-of-type'},
    inboundMenuDaySelectorFirst: {selector: '#inbounds-3-menu .yuimenubaritem'},
    inboundMenuDaySelectorSecond: {selector: '#inbounds-3-menu .yuimenubaritem:nth-child(2)'},
    inboundMenuDaySelectorThird: {selector: '#inbounds-3-menu .yuimenubaritem:nth-child(3)'},
    inboundMenuDaySelectorFourth: {selector: '#inbounds-3-menu .yuimenubaritem:nth-child(4)'},
    inboundMenuDaySelectorFive: {selector: '#inbounds-3-menu .yuimenubaritem:nth-child(5)'},
    inboundMenuDaySelectorSix: {selector: '#inbounds-3-menu .yuimenubaritem:nth-child(6)'},
    inboundMenuDaySelectorSeventh: {selector: '#inbounds-3-menu .yuimenubaritem:last-of-type'}
  }
};
<|endoftext|>