<commit_before>/**
 * Created by Armin on 11.06.2017.
 */
var request = require('request');
var actionUrl = 'https://service.us.apiconnect.ibmcloud.com/gws/apigateway/api/c9f88de3acb5a4648e4f118769d019c8df8797d1777c4342f43260626b4c51bf/iwibotTest/router';
var params = {
    semester: 5,
    courseOfStudies: 'INFB',
    context: { // If this test is not successful, try to get a new context! (Log and paste it here!)
        conversation_id: '8b3c7145-70f7-496b-80eb-248311c25776',
        system:{
            dialog_stack:[{dialog_node: 'root'}],
            dialog_turn_counter: 1,
            dialog_request_counter: 1,
            _node_output_map:{
                node_2_1496758852004: [0]
            },
            branch_exited: true,
            branch_exited_reason: 'completed'
        }
    }
};

module.exports = {
    'Router Action Test (timetables)' : function (test) {
        test.expect(2);
        params.payload = 'timetable friday';
        request.post({
            headers: {'content-type': 'text/plain'},
            url: actionUrl,
            body: JSON.stringify(params)
        }, function (err, response, body) {
            console.log('Body: ' + body);
            console.log('Error: ' + err);
            console.log('Response: ' + JSON.stringify(response));
            body = JSON.parse(body);
            test.ok(typeof body.payload === 'string');
            test.ok(body.payload.indexOf('Error') === -1 && body.payload.indexOf('error') === -1);
            test.done();
        });
    },
    'Router Action Test (meal)' : function (test) {
        test.expect(2);
        params.payload = 'Food 1';
        request.post({
            headers: {'content-type': 'text/plain'},
            url: actionUrl,
            body: JSON.stringify(params)
        }, function (err, response, body) {
            console.log('Body: ' + body);
            console.log('Error: ' + err);
            console.log('Response: ' + JSON.stringify(response));
            body = JSON.parse(body);
            test.ok(typeof body.payload === 'string');
            test.ok(body.payload.indexOf('Error') === -1 && body.payload.indexOf('error') === -1);
            test.done();
        });
    },
    'Router Action Test (joke)' : function (test) {
        test.expect(1);
        params.payload = 'joke';
        request.post({
            headers: {'content-type': 'text/plain'},
            url: actionUrl,
            body: JSON.stringify(params)
        }, function (err, response, body) {
            console.log('Body: ' + body);
            console.log('Error: ' + err);
            console.log('Response: ' + JSON.stringify(response));
            body = JSON.parse(body);
            test.ok('payload' in body);
            test.done();
        });
    }
};<commit_msg>changed conversation id in router_test<commit_after>/**
 * Created by Armin on 11.06.2017.
 */
var request = require('request');
var actionUrl = 'https://service.us.apiconnect.ibmcloud.com/gws/apigateway/api/c9f88de3acb5a4648e4f118769d019c8df8797d1777c4342f43260626b4c51bf/iwibotTest/router';
var params = {
    semester: 5,
    courseOfStudies: 'INFB',
    context: { // If this test is not successful, try to get a new context! (Log and paste it here!)
        conversation_id: '69cf475b-b891-4889-923b-f3605060e1c2',
        system: {
            dialog_stack:[{dialog_node: 'root'}],
            dialog_turn_counter: 1,
            dialog_request_counter: 1,
            _node_output_map:{
                "Willkommen":[0]
            }
        }
    }
};

module.exports = {
    'Router Action Test (timetables)' : function (test) {
        test.expect(2);
        params.payload = 'timetable friday';
        request.post({
            headers: {'content-type': 'text/plain'},
            url: actionUrl,
            body: JSON.stringify(params)
        }, function (err, response, body) {
            console.log('Body: ' + body);
            console.log('Error: ' + err);
            console.log('Response: ' + JSON.stringify(response));
            body = JSON.parse(body);
            test.ok(typeof body.payload === 'string');
            test.ok(body.payload.indexOf('Error') === -1 && body.payload.indexOf('error') === -1);
            test.done();
        });
    },
    'Router Action Test (meal)' : function (test) {
        test.expect(2);
        params.payload = 'Food 1';
        request.post({
            headers: {'content-type': 'text/plain'},
            url: actionUrl,
            body: JSON.stringify(params)
        }, function (err, response, body) {
            console.log('Body: ' + body);
            console.log('Error: ' + err);
            console.log('Response: ' + JSON.stringify(response));
            body = JSON.parse(body);
            test.ok(typeof body.payload === 'string');
            test.ok(body.payload.indexOf('Error') === -1 && body.payload.indexOf('error') === -1);
            test.done();
        });
    },
    'Router Action Test (joke)' : function (test) {
        test.expect(1);
        params.payload = 'joke';
        request.post({
            headers: {'content-type': 'text/plain'},
            url: actionUrl,
            body: JSON.stringify(params)
        }, function (err, response, body) {
            console.log('Body: ' + body);
            console.log('Error: ' + err);
            console.log('Response: ' + JSON.stringify(response));
            body = JSON.parse(body);
            test.ok('payload' in body);
            test.done();
        });
    }
};<|endoftext|>


<commit_before>var Dog = Dog || {};

Dog.Main = (function() {
	// scene vars
	var scene, camera, renderer, orbitControls;

	// canvas capture vars
	var canvasImageData;
	var getCanvasImageData = false;
	var ONCE = 'once';

	// texture vars
	var textureBumpMapLoader, textureMapBump;

	// Should scene show helpers
	var USE_HELPERS = false;

	// Objects
	var hero;
	var sphere;
	var topVertIndexes = [];
	var animationSpeed = 2;
	var animOffset = 0;
	var maxUndulation = 80;
	var elements = [];
	var elementsContainer;

	function setup() {

		textureBumpMapLoader = new THREE.TextureLoader();

		// init scene
		scene = new THREE.Scene();

		// init camera
		camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 10000);
		camera.position.x = Dog.Utils.randomRange(-300, -500);
		camera.position.y = Dog.Utils.randomRange(300, 400);
		camera.position.z = Dog.Utils.randomRange(300, 500);

		// console.log('Main.js', camera.position);

		camera.lookAt(0, 0, 0)

		// init renderer
		renderer = new THREE.WebGLRenderer({
			antialias: true,
			alpha: true
		});
		renderer.setSize(window.innerWidth, window.innerHeight);
		renderer.autoClear = false;
		renderer.shadowMap.enabled = true;

		// console.dir(renderer.shadowMap);
		// renderer.shadowMapSoft = false;

		document.body.appendChild(renderer.domElement);

		// add controls
		orbitControls = new THREE.OrbitControls(camera, renderer.domElement);

		// add window resize handler
		window.addEventListener('resize', onWindowResize, false);

		// load images
		textureBumpMapLoader.load('./img/logo_dog.png', function(texture) {
			textureMapBump = texture;

			init();
		});

		if (USE_HELPERS) scene.add(new THREE.AxisHelper(500));
	}

	function init() {

		// add content
		addLighting();
		addFloor();
		addElements();

		// init keyboard listener
		initKeyboard();

		// render
		render();
	}

	function initKeyboard() {
		// listen for keystrokes
		document.body.addEventListener("keyup", function(event) {
			// console.info('event.keyCode', event.keyCode);

			switch (event.keyCode) {
				case 80: // p
					exportCanvasImageDataToPNG();
					break;
			}
		});
	}

	// gets image data
	function exportCanvasImageDataToPNG() {
		getCanvasImageData = true;
		render(ONCE);

		var win = window.open("", "Canvas Image");
		var canvas = renderer.domElement;
		var src = canvas.toDataURL("image/png");

		win.document.write("");
	}

	function onWindowResize() {
		// Update camera and renderer
		camera.aspect = window.innerWidth / window.innerHeight;
		camera.updateProjectionMatrix();

		renderer.setSize(window.innerWidth, window.innerHeight);
	}

	function addLighting() {

		// Add a light
		var spotLight1 = new THREE.DirectionalLight(0xffffff, 0.75);
		spotLight1.position.set(Dog.Utils.randomRange(300, 500), Dog.Utils.randomRange(300, 500), Dog.Utils.randomRange(300, 500));
		spotLight1.target.position.set(0, 0, 0);

		var shadowSize = 3000;

		spotLight1.castShadow = true;
		spotLight1.shadow.mapSize.width = shadowSize * 2;
		spotLight1.shadow.mapSize.height = shadowSize * 2;
		spotLight1.shadow.camera.near = 1;
		spotLight1.shadow.camera.far = 2000;
		spotLight1.shadow.camera.left = -shadowSize / 2;
		spotLight1.shadow.camera.right = shadowSize / 2;
		spotLight1.shadow.camera.top = shadowSize / 2;
		spotLight1.shadow.camera.bottom = -shadowSize / 2;
		spotLight1.shadow.camera.visible = true;

		scene.add(spotLight1);

		// helper
		if (USE_HELPERS) scene.add(new THREE.DirectionalLightHelper(spotLight1));

		// add another spotlight
		var spotLight2 = new THREE.DirectionalLight(0xffffff, 0.125);
		spotLight2.position.set(Dog.Utils.randomRange(-300, -500), Dog.Utils.randomRange(-300, -500), Dog.Utils.randomRange(-300, -500));
		spotLight2.target.position.set(0, 0, 0);

		scene.add(spotLight2);

		// helper
		if (USE_HELPERS) scene.add(new THREE.DirectionalLightHelper(spotLight2));

		// Add and additional AmbientLight
		scene.add(new THREE.AmbientLight(0x555555));
	}

	function addElements() {

		var width = 20;
		var gap = 20;
		var howManyInRow = 6;
		var howMany = Math.pow(howManyInRow, 3);
		var offSet = ((width * howManyInRow) + (gap * (howManyInRow - 1))) / 2;

		elementsContainer = new THREE.Object3D();
		scene.add(elementsContainer);

		var geometry = new THREE.BoxBufferGeometry(width, width, width);
		var material = new THREE.MeshPhongMaterial({
			color: 0x2194ce,
			shading: THREE.FlatShading,
			emissive: 0x000000,
			specular: 0x666666,
			shininess: 60,
			// side: THREE.DoubleSide,
			// transparent: true,
			// opacity: 0.9,
		});

		for (var i = 0; i < howMany; i++) {
			var element = new THREE.Mesh(geometry, material);
			element.position.x = (((i % howManyInRow) * (width + gap)) - offSet);
			element.position.y = (Math.floor(i / Math.pow(howManyInRow, 2)) * (width + gap)) - offSet;
			element.position.z = ((Math.floor(i / howManyInRow) % howManyInRow) * (width + gap)) - offSet;
			element.positionClone = element.position.clone();
			element.receiveShadow = true;
			element.castShadow = true;
			elementsContainer.add(element);
			elements.push(element);
		}
	}

	function addFloor() {
		var floorMaterial = new THREE.MeshPhongMaterial({
			color: 0xeeeeee,
			shading: THREE.FlatShading,
			emissive: 0x666666,
			specular: 0x111111,
			shininess: 30,
		});

		var floorGeometry = new THREE.PlaneBufferGeometry(10000, 10000);
		var floor = new THREE.Mesh(floorGeometry, floorMaterial);
		floor.receiveShadow = true;
		floor.rotation.x = -Math.PI / 2;
		floor.position.y = -170;
		scene.add(floor);
	}

	function animateElements() {
		for (var i = 0; i < elements.length; i++) {
			var element = elements[i];
			element.scale.x = element.scale.y = element.scale.z = element.scale.y + ((Math.sin(Dog.Utils.degToRad((element.positionClone.x) + animOffset))) / 100) + ((Math.sin(Dog.Utils.degToRad((element.positionClone.z) + animOffset))) / 100);
		}

		animOffset = (animOffset < 360) ? animOffset += animationSpeed : 0;
	}

	function render(howManyTimes) {
		/* If we are rendering for an exportCanvasImageDataToPNG then DO NOT requestAnimationFrame as can speed up animations that are called on render */

		if (howManyTimes !== ONCE) requestAnimationFrame(render);

		elementsContainer.rotation.y -= 0.01;
		animateElements();

		renderer.clear();
		renderer.render(scene, camera);
		orbitControls.update();

		if (getCanvasImageData === true) {
			canvasImageData = renderer.domElement.toDataURL();
			getCanvasImageData = false;
		}
	}

	return {
		init: function() {
			setup();
		}
	};
})();<commit_msg>Updated 08 - Scaling was bad implemented. Now fixed.<commit_after>var Dog = Dog || {};

Dog.Main = (function() {
	// scene vars
	var scene, camera, renderer, orbitControls;

	// canvas capture vars
	var canvasImageData;
	var getCanvasImageData = false;
	var ONCE = 'once';

	// texture vars
	var textureBumpMapLoader, textureMapBump;

	// Should scene show helpers
	var USE_HELPERS = false;

	// Objects
	var hero;
	var sphere;
	var topVertIndexes = [];
	var animationSpeed = 2;
	var animOffset = 0;
	var maxUndulation = 80;
	var elements = [];
	var elementsContainer;

	function setup() {

		textureBumpMapLoader = new THREE.TextureLoader();

		// init scene
		scene = new THREE.Scene();

		// init camera
		camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 10000);
		camera.position.x = Dog.Utils.randomRange(-300, -500);
		camera.position.y = Dog.Utils.randomRange(300, 400);
		camera.position.z = Dog.Utils.randomRange(300, 500);

		// console.log('Main.js', camera.position);

		camera.lookAt(0, 0, 0)

		// init renderer
		renderer = new THREE.WebGLRenderer({
			antialias: true,
			alpha: true
		});
		renderer.setSize(window.innerWidth, window.innerHeight);
		renderer.autoClear = false;
		renderer.shadowMap.enabled = true;

		// console.dir(renderer.shadowMap);
		// renderer.shadowMapSoft = false;

		document.body.appendChild(renderer.domElement);

		// add controls
		orbitControls = new THREE.OrbitControls(camera, renderer.domElement);

		// add window resize handler
		window.addEventListener('resize', onWindowResize, false);

		// load images
		textureBumpMapLoader.load('./img/logo_dog.png', function(texture) {
			textureMapBump = texture;

			init();
		});

		if (USE_HELPERS) scene.add(new THREE.AxisHelper(500));
	}

	function init() {

		// add content
		addLighting();
		addFloor();
		addElements();

		// init keyboard listener
		initKeyboard();

		// render
		render();
	}

	function initKeyboard() {
		// listen for keystrokes
		document.body.addEventListener("keyup", function(event) {
			// console.info('event.keyCode', event.keyCode);

			switch (event.keyCode) {
				case 80: // p
					exportCanvasImageDataToPNG();
					break;
			}
		});
	}

	// gets image data
	function exportCanvasImageDataToPNG() {
		getCanvasImageData = true;
		render(ONCE);

		var win = window.open("", "Canvas Image");
		var canvas = renderer.domElement;
		var src = canvas.toDataURL("image/png");

		win.document.write("");
	}

	function onWindowResize() {
		// Update camera and renderer
		camera.aspect = window.innerWidth / window.innerHeight;
		camera.updateProjectionMatrix();

		renderer.setSize(window.innerWidth, window.innerHeight);
	}

	function addLighting() {

		// Add a light
		var spotLight1 = new THREE.DirectionalLight(0xffffff, 0.75);
		spotLight1.position.set(Dog.Utils.randomRange(300, 500), Dog.Utils.randomRange(300, 500), Dog.Utils.randomRange(300, 500));
		spotLight1.target.position.set(0, 0, 0);

		var shadowSize = 3000;

		spotLight1.castShadow = true;
		spotLight1.shadow.mapSize.width = shadowSize * 2;
		spotLight1.shadow.mapSize.height = shadowSize * 2;
		spotLight1.shadow.camera.near = 1;
		spotLight1.shadow.camera.far = 2000;
		spotLight1.shadow.camera.left = -shadowSize / 2;
		spotLight1.shadow.camera.right = shadowSize / 2;
		spotLight1.shadow.camera.top = shadowSize / 2;
		spotLight1.shadow.camera.bottom = -shadowSize / 2;
		spotLight1.shadow.camera.visible = true;

		scene.add(spotLight1);

		// helper
		if (USE_HELPERS) scene.add(new THREE.DirectionalLightHelper(spotLight1));

		// add another spotlight
		var spotLight2 = new THREE.DirectionalLight(0xffffff, 0.125);
		spotLight2.position.set(Dog.Utils.randomRange(-300, -500), Dog.Utils.randomRange(-300, -500), Dog.Utils.randomRange(-300, -500));
		spotLight2.target.position.set(0, 0, 0);

		scene.add(spotLight2);

		// helper
		if (USE_HELPERS) scene.add(new THREE.DirectionalLightHelper(spotLight2));

		// Add and additional AmbientLight
		scene.add(new THREE.AmbientLight(0x555555));
	}

	function addElements() {

		var width = 20;
		var gap = 20;
		var howManyInRow = 6;
		var howMany = Math.pow(howManyInRow, 3);
		var offSet = ((width * howManyInRow) + (gap * (howManyInRow - 1))) / 2;

		elementsContainer = new THREE.Object3D();
		scene.add(elementsContainer);

		var geometry = new THREE.BoxBufferGeometry(width, width, width);
		var material = new THREE.MeshPhongMaterial({
			color: 0x2194ce,
			shading: THREE.FlatShading,
			emissive: 0x000000,
			specular: 0x666666,
			shininess: 60,
			// side: THREE.DoubleSide,
			// transparent: true,
			// opacity: 0.9,
		});

		for (var i = 0; i < howMany; i++) {
			var element = new THREE.Mesh(geometry, material);
			element.position.x = (((i % howManyInRow) * (width + gap)) - offSet);
			element.position.y = (Math.floor(i / Math.pow(howManyInRow, 2)) * (width + gap)) - offSet;
			element.position.z = ((Math.floor(i / howManyInRow) % howManyInRow) * (width + gap)) - offSet;
			element.positionClone = element.position.clone();
			element.scaleClone = element.scale.clone();
			element.receiveShadow = true;
			element.castShadow = true;
			elementsContainer.add(element);
			elements.push(element);
		}
	}

	function addFloor() {
		var floorMaterial = new THREE.MeshPhongMaterial({
			color: 0xeeeeee,
			shading: THREE.FlatShading,
			emissive: 0x666666,
			specular: 0x111111,
			shininess: 30,
		});

		var floorGeometry = new THREE.PlaneBufferGeometry(10000, 10000);
		var floor = new THREE.Mesh(floorGeometry, floorMaterial);
		floor.receiveShadow = true;
		floor.rotation.x = -Math.PI / 2;
		floor.position.y = -170;
		scene.add(floor);
	}

	function animateElements() {
		for (var i = 0; i < elements.length; i++) {
			var element = elements[i];
			element.scale.x = element.scale.y = element.scale.z = element.scaleClone.y + ((Math.sin(Dog.Utils.degToRad((element.positionClone.x) + animOffset))) / 1.5) + ((Math.sin(Dog.Utils.degToRad((element.positionClone.z) + animOffset))) / 1.5);
		}

		animOffset = (animOffset < 360) ? animOffset += animationSpeed : 0;
	}

	function render(howManyTimes) {
		/* If we are rendering for an exportCanvasImageDataToPNG then DO NOT requestAnimationFrame as can speed up animations that are called on render */

		if (howManyTimes !== ONCE) requestAnimationFrame(render);

		elementsContainer.rotation.y -= 0.01;
		animateElements();

		renderer.clear();
		renderer.render(scene, camera);
		orbitControls.update();

		if (getCanvasImageData === true) {
			canvasImageData = renderer.domElement.toDataURL();
			getCanvasImageData = false;
		}
	}

	return {
		init: function() {
			setup();
		}
	};
})();<|endoftext|>


<commit_before>/**
 * Manage examples
 */

(function() {

var examples = {};

var treeURL = 'https://api.github.com/repos/LeaVerou/prism/git/trees/gh-pages?recursive=1';
var treePromise = new Promise(function (resolve) {
	$u.xhr({
		url: treeURL,
		callback: function (xhr) {
			if (xhr.status < 400) {
				resolve(JSON.parse(xhr.responseText).tree);
			}
		}
	});
});

var languages = components.languages;

for (var id in languages) {
	if (id === 'meta') {
		continue;
	}

	(function (id) {
		var language = languages[id];
		var checked = false;

		if (language.option === 'default') {
			checked = true;
		}

		language.enabled = checked;
		language.path = languages.meta.path.replace(/\{id}/g, id) + '.js';
		language.examplesPath = languages.meta.examplesPath.replace(/\{id}/g, id) + '.html';

		fileExists(language.examplesPath).then(function (exists) {
			$u.element.create('label', {
				attributes: {
					'data-id': id,
					'title': !exists ? 'No examples are available for this language.' : ''
				},
				className: !exists ? 'unavailable' : '',
				contents: [
					{
						tag: 'input',
						properties: {
							type: 'checkbox',
							name: 'language',
							value: id,
							checked: checked && exists,
							disabled: !exists,
							onclick: function () {
								$$('input[name="' + this.name + '"]').forEach(function (input) {
									languages[input.value].enabled = input.checked;
								});

								update(id);
							}
						}
					},
					language.title
				],
				inside: '#languages'
			});
			examples[id] = $u.element.create('section', {
				'id': 'language-' + id,
				'className': 'language-' + id,
				inside: '#examples'
			});
			if (checked) {
				update(id);
			}
		});
	}(id));
}

function fileExists(filepath) {
	return treePromise.then(function (tree) {
		for (var i = 0, l = tree.length; i < l; i++) {
			if (tree[i].path === filepath) {
				return true;
			}
		}
		return false;
	});
}

function getFileContents(filepath) {
	return new Promise(function (resolve, reject) {
		$u.xhr({
			url: filepath,
			callback: function (xhr) {
				if (xhr.status < 400 && xhr.responseText) {
					resolve(xhr.responseText);
				} else {
					reject();
				}
			}
		});
	});
}

function update(id) {
	var language = languages[id];
	if (language.enabled) {
		if (!language.examplesPromise) {
			language.examplesPromise = getFileContents(language.examplesPath);
		}
		language.examplesPromise.then(function (contents) {
			examples[id].innerHTML = contents;

			loadLanguage(id).then(function () {
				var elements = examples[id].querySelectorAll('code[class*="language-"], [class*="language-"] code, code[class*="lang-"], [class*="lang-"] code');

				for (var i=0, element; element = elements[i++];) {
					Prism.highlightElement(element);
				}
			});
		});
	} else {
		examples[id].innerHTML = '';
	}
}

/**
 * Loads a language, including all dependencies
 *
 * @param {string} lang the language to load
 * @type {Promise} the promise which resolves as soon as everything is loaded
 */
function loadLanguage (lang)
{
	// at first we need to fetch all dependencies for the main language
	// Note: we need to do this, even if the main language already is loaded (just to be sure..)
	//
	// We load an array of all dependencies and call recursively this function on each entry
	//
	// dependencies is now an (possibly empty) array of loading-promises
	var dependencies = getDependenciesOfLanguage(lang).map(loadLanguage);

	// We create a promise, which will resolve, as soon as all dependencies are loaded.
	// They need to be fully loaded because the main language may extend them.
	return Promise.all(dependencies)
		.then(function () {

			// If the main language itself isn't already loaded, load it now
			// and return the newly created promise (we chain the promises).
			// If the language is already loaded, just do nothing - the next .then()
			// will immediately be called
			if (!Prism.languages[lang]) {
				return new Promise(function (resolve) {
					$u.script('components/prism-' + lang + '.js', resolve);
				});
			}
		});
}

/**
 * Returns all dependencies (as identifiers) of a specific language
 *
 * @param {string} lang
 * @returns {Array.<string>} the list of dependencies. Empty if the language has none.
 */
function getDependenciesOfLanguage (lang)
{
	if (!components.languages[lang] || !components.languages[lang].require)
	{
		return [];
	}

	return ($u.type(components.languages[lang].require) === "array")
		? components.languages[lang].require
		: [components.languages[lang].require];
}

}());<commit_msg>Fixed repository url in examples<commit_after>/**
 * Manage examples
 */

(function() {

var examples = {};

var treeURL = 'https://api.github.com/repos/PrismJS/prism/git/trees/gh-pages?recursive=1';
var treePromise = new Promise(function (resolve) {
	$u.xhr({
		url: treeURL,
		callback: function (xhr) {
			if (xhr.status < 400) {
				resolve(JSON.parse(xhr.responseText).tree);
			}
		}
	});
});

var languages = components.languages;

for (var id in languages) {
	if (id === 'meta') {
		continue;
	}

	(function (id) {
		var language = languages[id];
		var checked = false;

		if (language.option === 'default') {
			checked = true;
		}

		language.enabled = checked;
		language.path = languages.meta.path.replace(/\{id}/g, id) + '.js';
		language.examplesPath = languages.meta.examplesPath.replace(/\{id}/g, id) + '.html';

		fileExists(language.examplesPath).then(function (exists) {
			$u.element.create('label', {
				attributes: {
					'data-id': id,
					'title': !exists ? 'No examples are available for this language.' : ''
				},
				className: !exists ? 'unavailable' : '',
				contents: [
					{
						tag: 'input',
						properties: {
							type: 'checkbox',
							name: 'language',
							value: id,
							checked: checked && exists,
							disabled: !exists,
							onclick: function () {
								$$('input[name="' + this.name + '"]').forEach(function (input) {
									languages[input.value].enabled = input.checked;
								});

								update(id);
							}
						}
					},
					language.title
				],
				inside: '#languages'
			});
			examples[id] = $u.element.create('section', {
				'id': 'language-' + id,
				'className': 'language-' + id,
				inside: '#examples'
			});
			if (checked) {
				update(id);
			}
		});
	}(id));
}

function fileExists(filepath) {
	return treePromise.then(function (tree) {
		for (var i = 0, l = tree.length; i < l; i++) {
			if (tree[i].path === filepath) {
				return true;
			}
		}
		return false;
	});
}

function getFileContents(filepath) {
	return new Promise(function (resolve, reject) {
		$u.xhr({
			url: filepath,
			callback: function (xhr) {
				if (xhr.status < 400 && xhr.responseText) {
					resolve(xhr.responseText);
				} else {
					reject();
				}
			}
		});
	});
}

function update(id) {
	var language = languages[id];
	if (language.enabled) {
		if (!language.examplesPromise) {
			language.examplesPromise = getFileContents(language.examplesPath);
		}
		language.examplesPromise.then(function (contents) {
			examples[id].innerHTML = contents;

			loadLanguage(id).then(function () {
				var elements = examples[id].querySelectorAll('code[class*="language-"], [class*="language-"] code, code[class*="lang-"], [class*="lang-"] code');

				for (var i=0, element; element = elements[i++];) {
					Prism.highlightElement(element);
				}
			});
		});
	} else {
		examples[id].innerHTML = '';
	}
}

/**
 * Loads a language, including all dependencies
 *
 * @param {string} lang the language to load
 * @type {Promise} the promise which resolves as soon as everything is loaded
 */
function loadLanguage (lang)
{
	// at first we need to fetch all dependencies for the main language
	// Note: we need to do this, even if the main language already is loaded (just to be sure..)
	//
	// We load an array of all dependencies and call recursively this function on each entry
	//
	// dependencies is now an (possibly empty) array of loading-promises
	var dependencies = getDependenciesOfLanguage(lang).map(loadLanguage);

	// We create a promise, which will resolve, as soon as all dependencies are loaded.
	// They need to be fully loaded because the main language may extend them.
	return Promise.all(dependencies)
		.then(function () {

			// If the main language itself isn't already loaded, load it now
			// and return the newly created promise (we chain the promises).
			// If the language is already loaded, just do nothing - the next .then()
			// will immediately be called
			if (!Prism.languages[lang]) {
				return new Promise(function (resolve) {
					$u.script('components/prism-' + lang + '.js', resolve);
				});
			}
		});
}

/**
 * Returns all dependencies (as identifiers) of a specific language
 *
 * @param {string} lang
 * @returns {Array.<string>} the list of dependencies. Empty if the language has none.
 */
function getDependenciesOfLanguage (lang)
{
	if (!components.languages[lang] || !components.languages[lang].require)
	{
		return [];
	}

	return ($u.type(components.languages[lang].require) === "array")
		? components.languages[lang].require
		: [components.languages[lang].require];
}

}());
<|endoftext|>


<commit_before>var Theta = require(__dirname+'/../');
// var Theta = require('ricoh-theta');

var ptp = require('ptp');

var theta = new Theta();
theta.connect('192.168.1.1');

theta.on('connect', function(){
  console.log('connect!!');
  theta.getBatteryLevel(function(err, res){
    if(err) return console.error(err);
    console.log("BatteryLevel: "+res.dataPacket.toString());
    theta.disconnect();
  });
});
<commit_msg>fix sample<commit_after>var Theta = require(__dirname+'/../');
// var Theta = require('ricoh-theta');

var theta = new Theta();
theta.connect('192.168.1.1');

theta.on('connect', function(){
  console.log('connect!!');
  theta.getBatteryLevel(function(err, res){
    if(err) return console.error(err);
    console.log("BatteryLevel: "+res.dataPacket.toString());
    theta.disconnect();
  });
});
<|endoftext|>


<commit_before>dbs_inputText = function(pId) {
	var wTime = +new Date();
	var wTimeout;
	var wSearching = false;
	var wBlur = false;

	//Validação inicial
	dbsfaces.inputText.validate(pId);

	$(pId + " input").focusin(function(e){
		wSearching = false;
		dbsfaces.ui.selectAll(this);
	});

	$(pId + "-data.-upper").keydown(function(e){
		dbsfaces.inputText.letterCase($(this), e,"upper");
	});

	$(pId + "-data.-lower").keydown(function(e){
		dbsfaces.inputText.letterCase($(this), e,"lower");
	});

	$(pId + "-data.-proper").keydown(function(e){
		dbsfaces.inputText.letterCase($(this), e,"proper");
	});

	$(pId + "-data.-upperfirst").keydown(function(e){
		dbsfaces.inputText.letterCase($(this), e,"upperfirst");
	});

	$(pId + " > .-container > .-input > .dbs_input-data").focus(function(e){
		$(pId + "-suggestion").addClass("dbs_input-data-FOCUS");
	});

	$(pId + " > .-container > .-input > .dbs_input-data").blur(function(e){
		$(pId + "-suggestion").removeClass("dbs_input-data-FOCUS");
		dbsfaces.ui.selectNone(this);
		wTime = +new Date();

		//Esconde a lista
		if ($(pId + "-list").length > 0){
			$(pId + "-list").css("opacity","0");
			setTimeout(function() {
				$(pId + "-list").hide();
		  	}, 300);
		}

		//Omite blur caso pesquisa esteja em execução
		//Irá disparar após recebimento da resposta
		if (wSearching){
			wBlur = true;
			e.preventDefault();
			e.stopPropagation();
			e.stopImmediatePropagation();
		}else{
			dbsfaces.inputText.validate(pId);
		}
	});

	/* copia a sugestão para o input ou navega pela lista de sugestões*/
	$(pId + " > .-container > .-input > .dbs_input-data").keydown(function(e){
		//Confirma sugestão com tab e seta para a direita
		if ((e.which == 13 || //ENTER
			 e.which == 39) && //RIGHT
			$(this).get(0).selectionEnd == $(this).val().length) { //Se o cursor estiver no final do texto digitado pelo usuário
			e.stopImmediatePropagation();
			dbsfaces.inputText.acceptSuggestion(pId);
			if (e.which == 13){
				return false;
			}
		//Navega na lista de sugestões
		}else if(e.which==40   //DOWN
			  || e.which==38){ //UP
			//Se existe suggestion, controla a exibição e a navegação
			if ($(pId + "-list").length > 0){
				e.preventDefault();
				e.stopPropagation();
				//Exibe suggestions no primeiro click
				if ($(pId + "-list").css("display") == "none"){
					$(pId + "-list").css("opacity","1").show();
				}else{
					//Navega na lista de sugestões
					dbsfaces.dataTable.moveToNextOrPreviousRow(pId + "-dataTable", e.which);
				}
			}
		//Se não for tab, shift ou setas para a direira ou esquerda
		}else{
			if (dbsfaces.inputText.isValidKey(e)){
				//Apaga sugestão, pois será efetuada uma nova pesquisa no keyup
				dbsfaces.inputText.clearSuggestion(pId);
			}
			//Limpa campo da posição do cursos até o fim
			if (e.which == 8){ //BACKSPACES
				dbsfaces.ui.selectEnd($(this));
			}
		}
	});

	$(pId + " > .-container > .-input > .dbs_input-data").on("paste", function(e){
		dbsfaces.inputText.requestSuggestion(pId, wTime, wTimeout);

	});

	//Faz a pesquisa ===================================================
	$(pId + " > .-container > .-input").keyup(function(e){
		if (dbsfaces.inputText.isValidKey(e)){
			dbsfaces.inputText.requestSuggestion(pId, wTime, wTimeout);
		}
	});

	$(pId + "-submit").on(dbsfaces.EVENT.ON_AJAX_BEGIN, function(e){
		wSearching = true;

		$(pId + " > .-container > .-input").append("

");
		$(pId + " > .-container > .-input > .-is_pesquisar").hide();
		e.stopPropagation();
	});

	//Recebe a resposta da requisição da sugestão
	$(pId + "-submit").on(dbsfaces.EVENT.ON_AJAX_SUCCESS, function(e){
		wSearching = false;

		//Dispara o blur caso tenha sido ignorado originalmente
		if (wBlur){
			dbsfaces.inputText.triggerBlur(pId);
		}

		$(pId + " > .-container > .-input > div.-loading").remove();
		$(pId + " > .-container > .-input > .-is_pesquisar").show();
		dbsfaces.inputText.fixLayout(pId);
		dbsfaces.inputText.showFirstSuggestion(pId);

		e.stopPropagation();
	});

	//Item selecionado da lista
	$(pId + " > .-container > .-input").on(dbsfaces.EVENT.ON_ROW_SELECTED, ".-list", function(e, pRow){
		dbsfaces.inputText.suggestionReceived(pId, pRow, true);
	});

	//Seta foco na lista
	$(pId + " > .-container > .-input").on("click", ".-list", function(e){
		$(pId + "-data").focus();

		$(this).css("opacity","0");
		setTimeout(function() {
			$(pId + "-list").hide();
	  	}, 300);
	});

	dbsfaces.inputText.fixLayout(pId);

}

dbsfaces.inputText = {

	requestSuggestion: function(pId, pTime, pTimeOut){
		dbsfaces.inputText.clearSuggestion(pId);
		//Não faze pesquisa se valor for vázio
		var xValue = $.trim($(pId + "-data").val());
		var xNullText = $(pId + "-suggestion-key").attr("nulltext");
		if (xValue==""
		 || xValue==xNullText){
			return;
		}
		/* delay para evitar chamadas ajax contantes */
		if (pTime == 0){
			pTime = +new Date();
		}else{
			xDelay = +new Date() - pTime;
			pTime = +new Date();
			if (xDelay < 350){
				window.clearTimeout(pTimeOut); //Cancela request anterior
			}
			//Aguarda um tempo para chamar a rotina de sugestão
			pTimeOut = window.setTimeout(function(){
				$(pId + "-submit").click();
			}, 350); //Time de delay para efetuar a chamada
		}
	},

	clearSuggestion: function(pId){
		$(pId + "-suggestion").val("");
		$(pId + "-suggestion-key").attr("key", "");
		//Verifica se houve mudança antes de disparar evento
		if ($(pId + "-suggestion-key").val() != ""){
			$(pId + "-suggestion-key").val("");
			dbsfaces.inputText.triggerChange(pId);
		};
		dbsfaces.inputText.validate(pId);
	},

	acceptSuggestion: function(pId){
		var xSuggestionValue = $.trim($(pId + "-suggestion").val());
		//Verifica se houve mudança antes de disparar evento
		if ($(pId + "-suggestion-key").val() != $(pId + "-suggestion-key").attr("key")){
			//Seta valor selecionado
			$(pId + "-suggestion-key").val($(pId + "-suggestion-key").attr("key"));
			$(pId + "-data").val(xSuggestionValue);
			dbsfaces.inputText.triggerChange(pId);
		};
		dbsfaces.inputText.validate(pId);
	},

	//Copia valor da lista para a sugestão
	suggestionReceived: function(pId, pRow, pFromRowSelected){
		//Se encontrou alguma sugestão
		if ($(pRow).length > 0){
			var xRowKey = $(pRow).find('td .-key');
			var xRowValue = $(pRow).children('td.-dv');
			var xSuggestionValue = $.trim($(xRowValue).text());
			var xSuggestionKey = $.trim($(xRowKey).text());
			var xValue = $.trim($(pId + "-data").val());
			//Se não foi seleção da linha a partir da lista de sugestões, verifica se inicio do texto recebido é iqual a texto digitado.
			//Se não for, ignora sugestão recebida
			if (!pFromRowSelected){
				var xSuggestionValueTrunc = xSuggestionValue.substr(0, xValue.length);
				//Apaga sugestão se inicio do texto recebido não for iqual ao digitado.
				if (xSuggestionValueTrunc!=xValue){
					dbsfaces.inputText.clearSuggestion(pId);
					return;
				}
			}
			$(pId + "-suggestion-key").attr("key", xSuggestionKey);
			$(pId + "-suggestion").val(xSuggestionValue);
			//Se texto digitado já for igual a sugestão ou
			//foi seleção a partir da lista de sugestões, aceita a sugestão automaticamente
			if (pFromRowSelected
			|| xValue == xSuggestionValue){
				dbsfaces.inputText.acceptSuggestion(pId);
			}
		//Se não encontrou alguma sugestão
		}else{
			dbsfaces.inputText.clearSuggestion(pId);
		}

	},

	showFirstSuggestion: function(pId){
		//Le primeiro item da lista
		var xRow = $(pId + "-dataTable tbody").find("tr:first");

		dbsfaces.inputText.suggestionReceived(pId, xRow, false);
	},

	validate: function(pId){
		var xSuggestionValue = $.trim($(pId + "-suggestion").val());
		var xValue = $.trim($(pId + "-data").val());
		var xNullText = $(pId + "-suggestion-key").attr("nulltext");
		if (xValue==""
		 || xValue==xNullText){
			$(pId + "-data").val(xNullText);
			dbsfaces.inputText.removeError(pId);
		}else if (xSuggestionValue==xValue){
			//Confirma a sugestão
			dbsfaces.inputText.removeError(pId);
		}else{
			//Campo com erro
			dbsfaces.inputText.addError(pId);
		}
	},

	triggerChange: function(pId){
		$(pId + "-data").trigger("change");
	},

	triggerBlur: function(pId){
		wBlur = false;
		$(pId + "-data").trigger("blur");
		dbsfaces.inputText.validate(pId);
	},

	//Não fará pesquisa se for uma das teclas abaixo
	isValidKey: function(e){
		if (e.which == 9 || //TAB
			e.which == 13 || //ENTER
			e.which == 16 || //SHIFT
			e.which == 37 || //LEFT
			e.which == 38 || //UP
			e.which == 39 || //RIGHT
			e.which == 40 || //DOWN
			e.ctrlKey ||
			e.altKey){
			return false;
		}else{
			return true;
		}
	},
	removeError: function(pId){
		$(pId + "-suggestion").removeClass("-error");
		$(pId + "-data").removeClass("-error");
	},

	addError: function(pId){
		$(pId + "-suggestion").addClass("-error");
		$(pId + "-data").addClass("-error");
	},

	fixLayout: function(pId){
		$(pId + "-dataTable tbody:first").attr('tabindex', '-1');
		$(pId + "-dataTable input:first.-foo").attr('tabindex', '-1');

		var xWidth = $(pId + "-data").outerWidth();
		$(pId + "-dataTable thead:first").css('min-width', xWidth);
		$(pId + "-dataTable tbody:first").css('min-width', xWidth);
	},

	letterCase: function(pInput, e, pLetterCase){
		if (e.metaKey){
			return; //Sai para não converte o caracter recebido quando foi tecla especial como um Ctrl-C
		}
		if(e.which >= 65 && e.which <=90){
			if (pLetterCase!="upper" &&
				pLetterCase!="lower" &&
				pLetterCase!="proper" &&
				pLetterCase!="upperfirst"){
				return;
			}

			if (typeof pInput.attr("maxlength") != "undefined"){
				if (pInput.val().length >= parseInt(pInput.attr("maxlength"))){
					return;
				}
			}

			var xS = pInput.get(0).selectionEnd - pInput.get(0).selectionStart;
			var xValue = pInput.val();
			var xSS = pInput.get(0).selectionStart + 1;
			var xMinusculo = 0; //Default é upper
			if (pLetterCase=="upper"){
				xMinusculo = 0;
			}else if (pLetterCase=="lower"){
				xMinusculo = 32; //Incremento para os códigos de caracteres minúsculos
			}else if (pLetterCase=="proper"){
				if (pInput.get(0).selectionStart!=0){
					var xCharBefore = xValue.substr(pInput.get(0).selectionStart-1, 1);
					if (xCharBefore != " " && //Se não for inicio da palavra
						xCharBefore != ""){
						xMinusculo = 32; //Converte para minusculo
					}
				}
			}else if (pLetterCase=="upperfirst"){
				if (pInput.get(0).selectionStart!=0){
					return; //Sai para não converte o caracter recebido
				}
			}
			e.preventDefault();
			//Agrupo o inicio + valor digitado + final da texto. Isto previne os casos que a substituição no meio do texto
			xValue = xValue.substring(0, pInput.get(0).selectionStart) + String.fromCharCode(e.which + xMinusculo) + xValue.substring(pInput.get(0).selectionEnd, 200);
			pInput.val(xValue);
			pInput.get(0).setSelectionRange(xSS, xSS);
		}
	}
}

<commit_msg>1)Validação de campo com nulltext 2)Correção no tipo upperfirst 3)Ignora maxlenght para input com suggestion<commit_after>dbs_inputText = function(pId) {
	var wTime = +new Date();
	var wTimeout;
	var wSearching = false;
	var wBlur = false;

	$(pId + " input").focusin(function(e){
		wSearching = false;
		dbsfaces.ui.selectAll(this);
	});

	$(pId + "-data.-upper").keydown(function(e){
		dbsfaces.inputText.letterCase(pId, $(this), e,"upper");
	});

	$(pId + "-data.-lower").keydown(function(e){
		dbsfaces.inputText.letterCase(pId, $(this), e,"lower");
	});

	$(pId + "-data.-proper").keydown(function(e){
		dbsfaces.inputText.letterCase(pId, $(this), e,"proper");
	});

	$(pId + "-data.-upperfirst").keydown(function(e){
		dbsfaces.inputText.letterCase(pId, $(this), e,"upperfirst");
	});

	$(pId + " > .-container > .-input > .dbs_input-data").focus(function(e){
		$(pId + "-suggestion").addClass("dbs_input-data-FOCUS");
	});

	$(pId + " > .-container > .-input > .dbs_input-data").blur(function(e){
		$(pId + "-suggestion").removeClass("dbs_input-data-FOCUS");
		dbsfaces.ui.selectNone(this);
		wTime = +new Date();

		//Esconde a lista
		if ($(pId + "-list").length > 0){
			$(pId + "-list").css("opacity","0");
			setTimeout(function() {
				$(pId + "-list").hide();
		  	}, 300);
		}

		//Omite blur caso pesquisa esteja em execução
		//Irá disparar após recebimento da resposta
		if (wSearching){
			wBlur = true;
			e.preventDefault();
			e.stopPropagation();
			e.stopImmediatePropagation();
		}else{
			dbsfaces.inputText.validateNullText(pId);
		}
	});

	/* copia a sugestão para o input ou navega pela lista de sugestões*/
	$(pId + " > .-container > .-input > .dbs_input-data").keydown(function(e){
		//Confirma sugestão com tab e seta para a direita
		if ((e.which == 13 || //ENTER
			 e.which == 39) && //RIGHT
			$(this).get(0).selectionEnd == $(this).val().length) { //Se o cursor estiver no final do texto digitado pelo usuário
			e.stopImmediatePropagation();
			dbsfaces.inputText.acceptSuggestion(pId);
			if (e.which == 13){
				return false;
			}
		//Navega na lista de sugestões
		}else if(e.which==40   //DOWN
			  || e.which==38){ //UP
			//Se existe suggestion, controla a exibição e a navegação
			if ($(pId + "-list").length > 0){
				e.preventDefault();
				e.stopPropagation();
				//Exibe suggestions no primeiro click
				if ($(pId + "-list").css("display") == "none"){
					$(pId + "-list").css("opacity","1").show();
				}else{
					//Navega na lista de sugestões
					dbsfaces.dataTable.moveToNextOrPreviousRow(pId + "-dataTable", e.which);
				}
			}
		//Se não for tab, shift ou setas para a direira ou esquerda
		}else{
			if (dbsfaces.inputText.isValidKey(e)){
				//Apaga sugestão, pois será efetuada uma nova pesquisa no keyup
				dbsfaces.inputText.clearSuggestion(pId);
			}
			//Limpa campo da posição do cursos até o fim
			if (e.which == 8){ //BACKSPACES
				dbsfaces.ui.selectEnd($(this));
			}
		}
	});

	//Faz a pesquisa ===================================================
	$(pId + " > .-container > .-input").keyup(function(e){
		if (dbsfaces.inputText.isValidKey(e)){
			dbsfaces.inputText.requestSuggestion(pId, wTime, wTimeout);
		}
	});

	$(pId + " > .-container > .-input > .dbs_input-data").on("paste", function(e){
		dbsfaces.inputText.requestSuggestion(pId, wTime, wTimeout);

	});

	$(pId + "-submit").on(dbsfaces.EVENT.ON_AJAX_BEGIN, function(e){
		wSearching = true;

		$(pId + " > .-container > .-input").append("

");
		$(pId + " > .-container > .-input > .-is_pesquisar").hide();
		e.stopPropagation();
	});

	//Recebe a resposta da requisição da sugestão
	$(pId + "-submit").on(dbsfaces.EVENT.ON_AJAX_SUCCESS, function(e){
		wSearching = false;

		//Dispara o blur caso tenha sido ignorado originalmente
		if (wBlur){
			dbsfaces.inputText.triggerBlur(pId);
		}

		$(pId + " > .-container > .-input > div.-loading").remove();
		$(pId + " > .-container > .-input > .-is_pesquisar").show();
		dbsfaces.inputText.fixLayout(pId);
		dbsfaces.inputText.showFirstSuggestion(pId);

		e.stopPropagation();
	});

	//Item selecionado da lista
	$(pId + " > .-container > .-input").on(dbsfaces.EVENT.ON_ROW_SELECTED, ".-list", function(e, pRow){
		dbsfaces.inputText.suggestionReceived(pId, pRow, true);
	});

	//Seta foco na lista
	$(pId + " > .-container > .-input").on("click", ".-list", function(e){
		$(pId + "-data").focus();

		$(this).css("opacity","0");
		setTimeout(function() {
			$(pId + "-list").hide();
	  	}, 300);
	});

	//Validação inicial
	dbsfaces.inputText.validateNullText(pId);

	dbsfaces.inputText.fixLayout(pId);

}

dbsfaces.inputText = {

	requestSuggestion: function(pId, pTime, pTimeOut){
		dbsfaces.inputText.clearSuggestion(pId);
		//Não faze pesquisa se valor for vázio
		var xValue = $.trim($(pId + "-data").val());
		var xNullText = $(pId + "-suggestion-key").attr("nulltext");
		if (xValue==""
		 || xValue==xNullText){
			return;
		}
		/* delay para evitar chamadas ajax contantes */
		if (pTime == 0){
			pTime = +new Date();
		}else{
			xDelay = +new Date() - pTime;
			pTime = +new Date();
			if (xDelay < 350){
				window.clearTimeout(pTimeOut); //Cancela request anterior
			}
			//Aguarda um tempo para chamar a rotina de sugestão
			pTimeOut = window.setTimeout(function(){
				$(pId + "-submit").click();
			}, 350); //Time de delay para efetuar a chamada
		}
	},

	clearSuggestion: function(pId){
		$(pId + "-suggestion").val("");
		$(pId + "-suggestion-key").attr("key", "");
		//Verifica se houve mudança antes de disparar evento
		if ($(pId + "-suggestion-key").val() != ""){
			$(pId + "-suggestion-key").val("");
			dbsfaces.inputText.triggerChange(pId);
		};
		dbsfaces.inputText.validate(pId);
	},

	acceptSuggestion: function(pId){
		var xSuggestionValue = $.trim($(pId + "-suggestion").val());
		//Verifica se houve mudança antes de disparar evento
		if ($(pId + "-suggestion-key").val() != $(pId + "-suggestion-key").attr("key")){
			//Seta valor selecionado
			$(pId + "-suggestion-key").val($(pId + "-suggestion-key").attr("key"));
			$(pId + "-data").val(xSuggestionValue);
			dbsfaces.inputText.triggerChange(pId);
		};
		dbsfaces.inputText.validate(pId);
	},

	//Copia valor da lista para a sugestão
	suggestionReceived: function(pId, pRow, pFromRowSelected){
		//Se encontrou alguma sugestão
		if ($(pRow).length > 0){
			var xRowKey = $(pRow).find('td .-key');
			var xRowValue = $(pRow).children('td.-dv');
			var xSuggestionValue = $.trim($(xRowValue).text());
			var xSuggestionKey = $.trim($(xRowKey).text());
			var xValue = $.trim($(pId + "-data").val());
			//Se não foi seleção da linha a partir da lista de sugestões, verifica se inicio do texto recebido é iqual a texto digitado.
			//Se não for, ignora sugestão recebida
			if (!pFromRowSelected){
				var xSuggestionValueTrunc = xSuggestionValue.substr(0, xValue.length);
				//Apaga sugestão se inicio do texto recebido não for iqual ao digitado.
				if (xSuggestionValueTrunc!=xValue){
					dbsfaces.inputText.clearSuggestion(pId);
					return;
				}
			}
			$(pId + "-suggestion-key").attr("key", xSuggestionKey);
			$(pId + "-suggestion").val(xSuggestionValue);
			//Se texto digitado já for igual a sugestão ou
			//foi seleção a partir da lista de sugestões, aceita a sugestão automaticamente
			if (pFromRowSelected
			|| xValue == xSuggestionValue){
				dbsfaces.inputText.acceptSuggestion(pId);
			}
		//Se não encontrou alguma sugestão
		}else{
			dbsfaces.inputText.clearSuggestion(pId);
		}

	},

	showFirstSuggestion: function(pId){
		//Le primeiro item da lista
		var xRow = $(pId + "-dataTable tbody").find("tr:first");

		dbsfaces.inputText.suggestionReceived(pId, xRow, false);
	},

	validate: function(pId){
		//Sai caso input não seja do tipo que controla suggestion
		if ($(pId + "-suggestion").length > 0){
			//Verifica conteúdo da seleção
			var xSuggestionValue = $.trim($(pId + "-suggestion").val());
			var xValue = $.trim($(pId + "-data").val());
			var xNullText = $(pId + "-suggestion-key").attr("nulltext");
			if (xValue==""
			 || xValue==xNullText){
				dbsfaces.inputText.removeError(pId);
			}else if (xSuggestionValue==xValue){
				//Confirma a sugestão
				dbsfaces.inputText.removeError(pId);
			}else{
				//Campo com erro
				dbsfaces.inputText.addError(pId);
			}
		}
	},

	validateNullText: function(pId){
		if ($(pId + "-suggestion").length > 0){
			var xValue = $.trim($(pId + "-data").val());
			var xNullText = $(pId + "-suggestion-key").attr("nulltext");
			if (xValue==""){
				$(pId + "-data").val(xNullText);
			}
		}
	},

	triggerChange: function(pId){
		$(pId + "-data").trigger("change");
	},

	triggerBlur: function(pId){
		wBlur = false;
		$(pId + "-data").trigger("blur");
		dbsfaces.inputText.validateNullText(pId);
	},

	//Não fará pesquisa se for uma das teclas abaixo
	isValidKey: function(e){
		if (e.which == 9 || //TAB
			e.which == 12 || //CLEAR
			e.which == 13 || //ENTER
			e.which == 16 || //SHIFT
			e.which == 17 || //CONTROL
			e.which == 18 || //OPTION
			e.which == 27 || //ESC
			e.which == 34 || //PGDOWN
			e.which == 35 || //END
			e.which == 36 || //HOME
			e.which == 36 || //HOME
			e.which == 37 || //LEFT
			e.which == 38 || //UP
			e.which == 39 || //RIGHT
			e.which == 40 || //DOWN
			e.which == 91 || //COMMAND
			e.which == 33 || //PGUP
			(e.which >= 112 && e.which <= 130) || //fn
			e.ctrlKey ||
			e.altKey){
			return false;
		}else{
			return true;
		}
	},
	removeError: function(pId){
		$(pId + "-suggestion").removeClass("-error");
		$(pId + "-data").removeClass("-error");
	},

	addError: function(pId){
		$(pId + "-suggestion").addClass("-error");
		$(pId + "-data").addClass("-error");
	},

	fixLayout: function(pId){
		$(pId + "-dataTable tbody:first").attr('tabindex', '-1');
		$(pId + "-dataTable input:first.-foo").attr('tabindex', '-1');

		var xWidth = $(pId + "-data").outerWidth();
		$(pId + "-dataTable thead:first").css('min-width', xWidth);
		$(pId + "-dataTable tbody:first").css('min-width', xWidth);
	},

	letterCase: function(pId, pInput, e, pLetterCase){
		if (e.metaKey){
			return; //Sai para não converte o caracter recebido quando foi tecla especial como um Ctrl-C
		}
		if(e.which >= 65 && e.which <=90){
			if (pLetterCase!="upper" &&
				pLetterCase!="lower" &&
				pLetterCase!="proper" &&
				pLetterCase!="upperfirst"){
				return;
			}
			//Só testa tamanho máximo se imput não for com suggestion
			if ($(pId + "-suggestion").length == 0){
				if (typeof pInput.attr("maxlength") != "undefined"){
					if (pInput.val().length >= parseInt(pInput.attr("maxlength"))){
						return;
					}
				}
			}

			var xS = pInput.get(0).selectionEnd - pInput.get(0).selectionStart;
			var xValue = pInput.val();
			var xSS = pInput.get(0).selectionStart + 1;
			var xMinusculo = 0; //Default é upper
			if (pLetterCase=="upper"){
				xMinusculo = 0;
			}else if (pLetterCase=="lower"){
				xMinusculo = 32; //Incremento para os códigos de caracteres minúsculos
			}else if (pLetterCase=="proper"){
				if (pInput.get(0).selectionStart!=0){
					var xCharBefore = xValue.substr(pInput.get(0).selectionStart-1, 1);
					if (xCharBefore != " " && //Se não for inicio da palavra
						xCharBefore != ""){
						xMinusculo = 32; //Converte para minusculo
					}
				}
			}else if (pLetterCase=="upperfirst"){
				if (pInput.get(0).selectionStart!=0
				 && pInput.get(0).selectionEnd!=0){
					return; //Sai para não converte o caracter recebido
				}
			}
			e.preventDefault();
			//Agrupo o inicio + valor digitado + final da texto. Isto previne os casos que a substituição no meio do texto
			xValue = xValue.substring(0, pInput.get(0).selectionStart) + String.fromCharCode(e.which + xMinusculo) + xValue.substring(pInput.get(0).selectionEnd, 200);
			pInput.val(xValue);
			pInput.get(0).setSelectionRange(xSS, xSS);
		}
	}
}

<|endoftext|>


<commit_before>require('./bootFOAMNode.js');

var env = foam.box.Context.create();

var dst = foam.box.SocketBox.create({
  address: 'localhost:7000',
}, env);

var msg = boxmail.Message.create({
  subject: 'random mail',
  body: 'hello world'
});

var dao = foam.dao.ClientDAO.create({
  delegate: foam.box.SubBox.create({
    name: 'INBOX',
    delegate: dst
  }, env)
}, env);

dao.select().then(function(m) {
  console.log("Read", m.a.length, 'mails');
  for ( var i = 0 ; i < m.a.length ; i++ ) {
    var mail = m.a[i];
    console.log('');
    console.log('');
    console.log('MSGID:', mail.id);
    console.log('Subject:', mail.subject);
    console.log(mail.body);
  }
  process.exit(0);
});
<commit_msg>src/apps/boxmail/getmail.js cleanup<commit_after>require('./bootFOAMNode.js');

var env = foam.box.Context.create();

var dst = foam.box.SocketBox.create({
  address: 'localhost:7000',
}, env);

var dao = foam.dao.ClientDAO.create({
  delegate: foam.box.SubBox.create({
    name: 'INBOX',
    delegate: dst
  }, env)
}, env);

dao.select().then(function(m) {
  console.log("Read", m.a.length, 'mails');
  for ( var i = 0 ; i < m.a.length ; i++ ) {
    var mail = m.a[i];
    console.log('');
    console.log('');
    console.log('MSGID:', mail.id);
    console.log('Subject:', mail.subject);
    console.log(mail.body);
  }
  process.exit(0);
});
<|endoftext|>


<commit_before>/**
 * Module dependencies
 */

var express = require('express');
var superagent = require('superagent');
var envs = require('envs');
var NeDB = require('nedb');

superagent.parse['application/hyper+json'] = superagent.parse['application/json'];

function createDB(name) {
  return new NeDB({
    filename: __dirname + '/' + name + '.db',
    autoload: true
  });
}

var db = {
  games: createDB('games'),
  state: createDB('state')
};

var EMITTER_URL = envs('EMITTER_URL');
function notify(url, fn) {
  fn = fn || function(){};
  if (!EMITTER_URL) return fn();
  superagent
    .post(EMITTER_URL)
    .send({url: url})
    .end(function(err, res) {
      fn(err);
    });
}

/**
 * Expose api
 */

var api = module.exports = express();

api.use(express.json());
api.use(express.urlencoded());

/**
 * Defines
 */

var API_URL = envs('API_URL');

api.use(function(req, res, next) {
  var auth = req.header('authorization');
  if (!auth) return next(new Error('Unauthorized'));

  req.base = req.base || '';
  req.base = req.base + '/api';
  var url = req.base + (req.url === '/' ? '' : req.url);
  var json = res.json;
  res.json = function(obj) {
    obj.href = url;
    json.call(res, obj);
  };

  // TODO cache
  request(API_URL, auth)
    .end(function(err, response) {
      if (err) return next(err);
      if (response.error) return next(response.error);

      // backwards compat hack
      if (!response.body.account) response.body.account = {
        href: response.body.users.href + '/current'
      };

      var users = response.body.users.href;
      request(response.body.account.href, auth)
        .end(function(err, response) {
          if (err) return next(err);
          if (!response.ok) return next(response.error);
          req.user = response.body;
          var href = req.user.href || users + '/' + req.user.id;
          req.user.id = req.user.href = encodeURIComponent(href);
          next();
        });
    });
});

api.get('/', function(req, res) {
  var body = {
    account: {
      href: req.base + '/users/' + req.user.id
    },
    games: {
      href: req.base + '/games'
    }
  };

  res.json(body);
});

api.get('/games', function(req, res, next) {
  db.games.find({}, function(err, games) {
    if (err) return next(err);
    res.json({
      data: games.map(function(game) {
        return {
          href: req.base + '/games/' + game._id
        };
      }),
      open: games.filter(function(game) {
        return game.status === 'waiting';
      }).map(function(game) {
        return {
          href: req.base + '/games/' + game._id
        };
      }),
      create: {
        method: 'POST',
        action: req.base + '/games',
        input: {
          name: {
            type: 'text'
          },
          width: {
            type: 'number',
            value: 9,
            min: 4
          },
          height: {
            type: 'number',
            value: 9,
            min: 4
          }
        }
      }
    });
  });
});

api.post('/games', function(req, res, next) {
  var game = req.body;
  if (!game.name) return next(new Error('request missing "name" parameter'));

  if (typeof game.width === 'string') game.width = parseInt(game.width, 10);
  if (typeof game.height === 'string') game.height = parseInt(game.height, 10);

  var data = {
    name: game.name,
    width: game.width || 9,
    height: game.height || 9,
    owner: req.user.href,
    players: [req.user.href],
    status: 'waiting'
  };

  db.games.insert(data, function(err, doc) {
    if (err) return next(err);
    var url = req.base + '/games/' + doc._id;
    notify(url);
    notify(req.base + '/games');
    res.redirect(303, url);
  });
});

api.param('game', function(req, res, next, id) {
  db.games.findOne({_id: id}, function(err, game) {
    if (err) return next(err);
    if (!game) return res.send(404);
    res.locals.game = game;
    next();
  });
});

api.get('/games/:game', function(req, res, next) {
  var game = res.locals.game;
  var body = {
    name: game.name,
    owner: {
      href: req.base + '/users/' + game.owner
    },
    players: game.players.map(function(player) {
      return {
        href: req.base + '/users/' + player
      };
    })
  };

  if (game.status === 'waiting' && !~game.players.indexOf(req.user.id)) {
    body.join = {
      method: 'POST',
      action: req.base + '/games/' + req.params.game,
      input: {
        _action: {
          type: 'hidden',
          value: 'join'
        }
      }
    };
  }

  if (game.status === 'waiting' && game.owner === req.user.id && game.players.length >= 2) {
    body.start = {
      method: 'POST',
      action: req.base + '/games/' + req.params.game,
      input: {
        _action: {
          type: 'hidden',
          value: 'start'
        }
      }
    };
  }

  if (game.status !== 'waiting') {
    body.state = {
      href: req.base + '/games/' + req.params.game + '/state'
    };
  }

  if (~game.players.indexOf(req.user.id)) {
    body.chat = {
      href: req.base + '/games/' + req.params.game + '/chat'
    };
  }

  res.json(body);
});

api.post('/games/:game', function(req, res, next) {
  var game = res.locals.game;

  if (game.status !== 'waiting') return next(new Error('game has already started'));

  var action = false;
  if (req.body._action === 'join' && !~game.players.indexOf(req.user.id)) {
    game.players.push(req.user.id);
    action = 'join';
  }

  if (req.body._action === 'start' && game.owner === req.user.id) {
    game.status = 'in-progress';
    action = 'start';
  }

  if (!action) return next(new Error('invalid action'));

  var url = req.base + '/games/' + req.params.game;
  db.games.update({_id: req.params.game}, game, function(err) {
    if (action === 'start') {
      var h = 0, v = 0;

      var edges = {};
      for (h = 0; h <= game.height; h++) {
        for (v = 0; v < game.width; v++) {
          edges[h + 'h' + v] = 0;
        }
      }
      for (h = 0; h < game.height; h++) {
        for (v = 0; v <= game.width; v++) {
          edges[h + 'v' + v] = 0;
        }
      }

      var board = {};
      for (h = 0; h < game.height; h++) {
        for (v = 0; v < game.width; v++) {
          board[h + '|' + v] = 0;
        }
      }

      var scores = {};
      game.players.forEach(function(id) {
        scores[id.replace(/\./g, '__DOT__')] = 0;
      });

      var state = {
        game: game._id,
        edges: edges,
        board: board,
        scores: scores,
        turn: game.players[0]
      };

      console.log(state);

      db.state.insert(state, function(err) {
        if (err) return next(err);
        notify(url);
        res.redirect(url);
      });
    } else {
      notify(url);
      res.redirect(url);
    }
  });
});

api.get('/games/:game/state', function(req, res, next) {
  db.state.findOne({game: req.params.game}, function(err, state) {
    if (err) return next(err);
    if (!state) return res.send(404);

    var game = res.locals.game;
    var canPlay = state.turn === req.user.id;

    var edges = [];
    Object.keys(state.edges).forEach(function(place) {
      var owner = state.edges[place];
      var vertical = !!~place.indexOf('v');
      var pos = vertical
        ? place.split('v')
        : place.split('h');

      var edge = {
        row: parseInt(pos[0]),
        col: parseInt(pos[1]),
        type: vertical ? 'v' : 'h'
      };

      if (owner) {
        edge.owner = {
          href: req.base + '/users/' + owner
        };
      }

      if (!owner && canPlay) {
        edge.occupy = {
          method: 'POST',
          action: req.base + '/games/' + req.params.game + '/state',
          input: {
            position: {
              type: 'hidden',
              value: place
            }
          }
        }
      }

      edges.push(edge);
    });

    var board = [];
    Object.keys(state.board).forEach(function(place) {
      var owner = state.edges[place];
      var pos = place.split('|');
      var b = {
        occupied: !!owner,
        row: parseInt(pos[0]),
        col: parseInt(pos[1])
      };

      if (owner) {
        b.owner = {
          href: req.base + '/users/' + owner
        };
      }

      board.push(b);
    });

    var scores = Object.keys(state.scores).map(function(player) {
      var score = state.scores[player];
      return {
        player: {
          href: req.base + '/users/' + player.replace(/__DOT__/g, '.')
        },
        score: score
      };
    });

    res.json({
      edges: edges,
      board: board,
      scores: scores,
      turn: state.turn
    });
  });
});

api.post('/games/:game/state', function(req, res, next) {
  var game = res.locals.game;
  var position = req.body.position
  if (!req.body || !position) return next(new Error('missing position parameter'));
  db.state.findOne({game: req.params.game}, function(err, state) {
    if (err) return next(err);
    if (!state) return res.send(404);
    if (state.turn !== req.user.id) return next(new Error('tried to play out of turn... nice try'));
    if (state.edges[position] !== 0) return next(new Error('invalid move'));

    state.edges[position] = req.user.id;

    // TODO fill in squares
    // TODO compute scores

    var i = game.players.indexOf(req.user.id) + 1;
    var turn = game.players[i];
    if (!turn) turn = game.players[0];

    db.state.update({_id: state._id}, {$set: {turn: turn, edges: state.edges}}, function(err) {
      var url = req.base + '/games/' + req.params.game + '/state';
      notify(url);
      res.redirect(url);
    });
  });
});

api.param('user', function(req, res, next, id) {
  if (id === req.user.id) {
    res.locals.user = req.user;
    next();
  }

  request(decodeURIComponent(id), req.header('authorization'))
    .end(function(err, response) {
      if (err) return next(err);
      if (!response.ok) return next(response.error);
      res.locals.user = response.body;
      res.locals.user.href = res.locals.user.id = id;
      next();
    });
});

api.get('/users/:user', function(req, res, next) {
  var user = res.locals.user;
  res.json({
    name: user.name,
    'first-name': user.first_name,
    'last-name': user.last_name,
    color: stringToColor(user.id)
  });
});

api.use(function(err, req, res, next) {
  console.error(err.stack || err.message || err);
  res.json({
    error: {
      message: err.message,
      stack: err.stack
    }
  });
});

function request(href, token) {
  return superagent
    .get(href)
    .set({accept: 'application/hyper+json', authorization: token})
    .buffer(true);
}

function stringToColor(str) {
  // str to hash
  for (var i = 0, hash = 0; i < str.length; hash = str.charCodeAt(i++) + ((hash << 5) - hash));
  // int/hash to hex
  for (var i = 0, color = "#"; i < 3; color += ("00" + ((hash >> i++ * 8) & 0xFF).toString(16)).slice(-2));

  return color;
}
<commit_msg>return the game dimensions<commit_after>/**
 * Module dependencies
 */

var express = require('express');
var superagent = require('superagent');
var envs = require('envs');
var NeDB = require('nedb');

superagent.parse['application/hyper+json'] = superagent.parse['application/json'];

function createDB(name) {
  return new NeDB({
    filename: __dirname + '/' + name + '.db',
    autoload: true
  });
}

var db = {
  games: createDB('games'),
  state: createDB('state'),
  users: createDB('users')
};

var EMITTER_URL = envs('EMITTER_URL');
function notify(url, fn) {
  fn = fn || function(){};
  if (!EMITTER_URL) return fn();
  superagent
    .post(EMITTER_URL)
    .send({url: url})
    .end(function(err, res) {
      fn(err);
    });
}

/**
 * Expose api
 */

var api = module.exports = express();

api.use(express.json());
api.use(express.urlencoded());

/**
 * Defines
 */

var API_URL = envs('API_URL');

api.use(function(req, res, next) {
  var auth = req.header('authorization');
  if (!auth) return next(new Error('Unauthorized'));

  req.base = req.base || '';
  req.base = req.base + '/api';
  var url = req.base + (req.url === '/' ? '' : req.url);
  var json = res.json;
  res.json = function(obj) {
    obj.href = url;
    json.call(res, obj);
  };

  // TODO cache
  request(API_URL, auth)
    .end(function(err, response) {
      if (err) return next(err);
      if (response.error) return next(response.error);

      // backwards compat hack
      if (!response.body.account) response.body.account = {
        href: response.body.users.href + '/current'
      };

      var users = response.body.users.href;
      request(response.body.account.href, auth)
        .end(function(err, response) {
          if (err) return next(err);
          if (!response.ok) return next(response.error);
          req.user = response.body;
          var href = req.user.href || users + '/' + req.user.id;
          req.user.id = req.user.href = encodeURIComponent(href);
          next();
        });
    });
});

api.get('/', function(req, res) {
  var body = {
    account: {
      href: req.base + '/users/' + req.user.id
    },
    games: {
      href: req.base + '/games'
    }
  };

  res.json(body);
});

api.get('/games', function(req, res, next) {
  db.games.find({}, function(err, games) {
    if (err) return next(err);
    res.json({
      data: games.map(function(game) {
        return {
          href: req.base + '/games/' + game._id
        };
      }),
      open: games.filter(function(game) {
        return game.status === 'waiting';
      }).map(function(game) {
        return {
          href: req.base + '/games/' + game._id
        };
      }),
      create: {
        method: 'POST',
        action: req.base + '/games',
        input: {
          name: {
            type: 'text'
          },
          width: {
            type: 'number',
            value: 9,
            min: 4
          },
          height: {
            type: 'number',
            value: 9,
            min: 4
          }
        }
      }
    });
  });
});

api.post('/games', function(req, res, next) {
  var game = req.body;
  if (!game.name) return next(new Error('request missing "name" parameter'));

  if (typeof game.width === 'string') game.width = parseInt(game.width, 10);
  if (typeof game.height === 'string') game.height = parseInt(game.height, 10);

  var data = {
    name: game.name,
    width: game.width || 9,
    height: game.height || 9,
    owner: req.user.href,
    players: [req.user.href],
    status: 'waiting'
  };

  db.games.insert(data, function(err, doc) {
    if (err) return next(err);
    var url = req.base + '/games/' + doc._id;
    notify(url);
    notify(req.base + '/games');
    res.redirect(303, url);
  });
});

api.param('game', function(req, res, next, id) {
  db.games.findOne({_id: id}, function(err, game) {
    if (err) return next(err);
    if (!game) return res.send(404);
    res.locals.game = game;
    next();
  });
});

api.get('/games/:game', function(req, res, next) {
  var game = res.locals.game;
  var body = {
    name: game.name,
    owner: {
      href: req.base + '/users/' + game.owner
    },
    players: game.players.map(function(player) {
      return {
        href: req.base + '/users/' + player
      };
    }),
    width: game.width,
    height: game.height
  };

  if (game.status === 'waiting' && !~game.players.indexOf(req.user.id)) {
    body.join = {
      method: 'POST',
      action: req.base + '/games/' + req.params.game,
      input: {
        _action: {
          type: 'hidden',
          value: 'join'
        }
      }
    };
  }

  if (game.status === 'waiting' && game.owner === req.user.id && game.players.length >= 2) {
    body.start = {
      method: 'POST',
      action: req.base + '/games/' + req.params.game,
      input: {
        _action: {
          type: 'hidden',
          value: 'start'
        }
      }
    };
  }

  if (game.status !== 'waiting') {
    body.state = {
      href: req.base + '/games/' + req.params.game + '/state'
    };
  }

  if (~game.players.indexOf(req.user.id)) {
    body.chat = {
      href: req.base + '/games/' + req.params.game + '/chat'
    };
  }

  res.json(body);
});

api.post('/games/:game', function(req, res, next) {
  var game = res.locals.game;

  if (game.status !== 'waiting') return next(new Error('game has already started'));

  var action = false;
  if (req.body._action === 'join' && !~game.players.indexOf(req.user.id)) {
    game.players.push(req.user.id);
    action = 'join';
  }

  if (req.body._action === 'start' && game.owner === req.user.id) {
    game.status = 'in-progress';
    action = 'start';
  }

  if (!action) return next(new Error('invalid action'));

  var url = req.base + '/games/' + req.params.game;
  db.games.update({_id: req.params.game}, game, function(err) {
    if (action === 'start') {
      var h = 0, v = 0;

      var edges = {};
      for (h = 0; h <= game.height; h++) {
        for (v = 0; v < game.width; v++) {
          edges[h + 'h' + v] = 0;
        }
      }
      for (h = 0; h < game.height; h++) {
        for (v = 0; v <= game.width; v++) {
          edges[h + 'v' + v] = 0;
        }
      }

      var board = {};
      for (h = 0; h < game.height; h++) {
        for (v = 0; v < game.width; v++) {
          board[h + '|' + v] = 0;
        }
      }

      var scores = {};
      game.players.forEach(function(id) {
        scores[id.replace(/\./g, '__DOT__')] = 0;
      });

      var state = {
        game: game._id,
        edges: edges,
        board: board,
        scores: scores,
        turn: game.players[0]
      };

      console.log(state);

      db.state.insert(state, function(err) {
        if (err) return next(err);
        notify(url);
        res.redirect(url);
      });
    } else {
      notify(url);
      res.redirect(url);
    }
  });
});

api.get('/games/:game/state', function(req, res, next) {
  db.state.findOne({game: req.params.game}, function(err, state) {
    if (err) return next(err);
    if (!state) return res.send(404);

    var game = res.locals.game;
    var canPlay = state.turn === req.user.id;

    var edges = [];
    Object.keys(state.edges).forEach(function(place) {
      var owner = state.edges[place];
      var vertical = !!~place.indexOf('v');
      var pos = vertical
        ? place.split('v')
        : place.split('h');

      var edge = {
        row: parseInt(pos[0]),
        col: parseInt(pos[1]),
        type: vertical ? 'v' : 'h'
      };

      if (owner) {
        edge.owner = {
          href: req.base + '/users/' + owner
        };
      }

      if (!owner && canPlay) {
        edge.occupy = {
          method: 'POST',
          action: req.base + '/games/' + req.params.game + '/state',
          input: {
            position: {
              type: 'hidden',
              value: place
            }
          }
        }
      }

      edges.push(edge);
    });

    var board = [];
    Object.keys(state.board).forEach(function(place) {
      var owner = state.edges[place];
      var pos = place.split('|');
      var b = {
        occupied: !!owner,
        row: parseInt(pos[0]),
        col: parseInt(pos[1])
      };

      if (owner) {
        b.owner = {
          href: req.base + '/users/' + owner
        };
      }

      board.push(b);
    });

    var scores = Object.keys(state.scores).map(function(player) {
      var score = state.scores[player];
      return {
        player: {
          href: req.base + '/users/' + player.replace(/__DOT__/g, '.')
        },
        score: score
      };
    });

    res.json({
      edges: edges,
      board: board,
      scores: scores,
      turn: state.turn
    });
  });
});

api.post('/games/:game/state', function(req, res, next) {
  var game = res.locals.game;
  var position = req.body.position
  if (!req.body || !position) return next(new Error('missing position parameter'));
  db.state.findOne({game: req.params.game}, function(err, state) {
    if (err) return next(err);
    if (!state) return res.send(404);
    if (state.turn !== req.user.id) return next(new Error('tried to play out of turn... nice try'));
    if (state.edges[position] !== 0) return next(new Error('invalid move'));

    state.edges[position] = req.user.id;

    // TODO fill in squares
    // TODO compute scores

    var i = game.players.indexOf(req.user.id) + 1;
    var turn = game.players[i];
    if (!turn) turn = game.players[0];

    db.state.update({_id: state._id}, {$set: {turn: turn, edges: state.edges}}, function(err) {
      var url = req.base + '/games/' + req.params.game + '/state';
      notify(url);
      res.redirect(url);
    });
  });
});

api.param('user', function(req, res, next, id) {
  if (id === req.user.id) {
    res.locals.user = req.user;
    next();
  }

  request(decodeURIComponent(id), req.header('authorization'))
    .end(function(err, response) {
      if (err) return next(err);
      if (!response.ok) return next(response.error);
      res.locals.user = response.body;
      res.locals.user.href = res.locals.user.id = id;
      next();
    });
});

api.get('/users/:user', function(req, res, next) {
  var user = res.locals.user;
  res.json({
    name: user.name,
    'first-name': user.first_name,
    'last-name': user.last_name,
    color: stringToColor(user.id)
  });
});

api.use(function(err, req, res, next) {
  console.error(err.stack || err.message || err);
  res.json({
    error: {
      message: err.message,
      stack: err.stack
    }
  });
});

function request(href, token) {
  return superagent
    .get(href)
    .set({accept: 'application/hyper+json', authorization: token})
    .buffer(true);
}

function stringToColor(str) {
  // str to hash
  for (var i = 0, hash = 0; i < str.length; hash = str.charCodeAt(i++) + ((hash << 5) - hash));
  // int/hash to hex
  for (var i = 0, color = "#"; i < 3; color += ("00" + ((hash >> i++ * 8) & 0xFF).toString(16)).slice(-2));

  return color;
}
<|endoftext|>


<commit_before>var _ = require('./../lib/lodash');
var helpers = require('./helpers');
var Fulltext = require('./fulltext');

/**
 * search by filters
 */
module.exports.search = function(items, input, configuration, fulltext) {

  input = input || {};

  var search_time = 0;
  // make search by query first
  if (fulltext) {

    var search_start_time = new Date().getTime();
    items = fulltext.search(input.query);
    search_time = new Date().getTime() - search_start_time;
  }

  /**
   * making a prefiltering after search and before faceting
   * after search because search is very fast
   * the goal is to make a library more customizable for developers
   */
  if (input.prefilter instanceof Function) {
    items = input.prefilter(items);
  }

  /**
   * responsible for filtering items by aggregation values (processed input)
   * not sure now about the reason but probably performance
   */
  var filtered_items = module.exports.items_by_aggregations(items, input.aggregations);

  var per_page = input.per_page || 12;
  var page = input.page || 1;

  /**
   * sorting items
   */
  var sorting_time = 0;
  if (input.sort) {
    var sorting_start_time = new Date().getTime();
    filtered_items = module.exports.sorted_items(filtered_items, input.sort, configuration.sortings);
    sorting_time = new Date().getTime() - sorting_start_time;
  }

  /**
   * calculating facets
   */
  var facets_start_time = new Date().getTime();
  var aggregations = module.exports.aggregations(items, input.aggregations);
  var facets_time = new Date().getTime() - facets_start_time;

  return {
    pagination: {
      per_page: per_page,
      page: page,
      total: filtered_items.length
    },
    timings: {
      facets: facets_time,
      search: search_time,
      sorting: sorting_time
    },
    data: {
      items: filtered_items.slice((page - 1) * per_page, page * per_page),
      aggregations: aggregations
    }
  };
}

/**
 * returns list of elements in aggregation
 * useful for autocomplete or list all aggregation options
 */
module.exports.aggregation = function(items, input, aggregations) {

  var per_page = input.per_page || 10;
  var page = input.page || 1;

  if (input.name && (!aggregations || !aggregations[input.name])) {
    throw new Error(`Please define aggregation "${input.name}" in config`);
  }

  var buckets = module.exports.buckets(items, input.name, aggregations[input.name], aggregations)

  if (input.query) {
    buckets = _.filter(buckets, val => {
      // responsible for query
      // counterpart to startsWith
      return val.key.toLowerCase().indexOf(input.query.toLowerCase()) === 0;
    });
  }

  return {
    pagination: {
      per_page: per_page,
      page: page,
      total: buckets.length
    },
    data: {
      buckets: buckets.slice((page - 1) * per_page, page * per_page),
    }
  }
}

/**
 * return items by sort
 */
module.exports.sorted_items = function(items, sort, sortings) {

  if (sortings[sort] && sortings[sort].field) {

    return _.orderBy(
      items,
      [sortings[sort].field],
      [sortings[sort].order || 'asc']
    );
  }

  return items;
}

/**
 * return items which pass filters (aggregations)
 */
module.exports.items_by_aggregations = function(items, aggregations) {

  return _.filter(items, (item) => {
    return module.exports.filterable_item(item, aggregations);
  });
}

/**
 * it returns list of aggregations with buckets
 * it calculates based on object filters like {tags: ['drama', '1980s']} against list of items
 * in realtime
 *
 * @TODO
 * consider caching aggregations results in startup time
 */
module.exports.aggregations = function(items, aggregations) {

  var position = 0;
  return _.mapValues((aggregations), (val, key) => {
    // key is a 'tags' and val is ['drama', '1980s']
    ++position;
    return {
      name: key,
      title: val.title || key.charAt(0).toUpperCase() + key.slice(1),
      position: position,
      buckets: module.exports.buckets(items, key, val, aggregations).slice(0, val.size || 10)
    }
  })
}

/**
 * checks if item is passing aggregations - if it's filtered or not
 * @TODO should accept filters (user input) as the parameter
 * and not user params merged with global config
 * should be is_filterable_item
 */
module.exports.filterable_item = function(item, aggregations) {

  var keys = _.keys(aggregations)

  for (var i = 0 ; i < keys.length ; ++i) {

    var key = keys[i]
    if (helpers.is_empty_agg(aggregations[key])) {
      if (helpers.check_empty_field(item[aggregations[key].field], aggregations[key].filters)) {
        continue;
      }
      return false;
    } else if (helpers.is_not_filters_agg(aggregations[key]) && !helpers.not_filters_field(item[key], aggregations[key].not_filters)) {
      return false;
    } else if (helpers.is_disjunctive_agg(aggregations[key]) && !helpers.disjunctive_field(item[key], aggregations[key].filters)) {
      return false;
    } else if (helpers.is_conjunctive_agg(aggregations[key]) && !helpers.conjunctive_field(item[key], aggregations[key].filters)) {
      return false;
    }
  }

  return true;
}

/*
 * returns array of item key values only if they are passing aggregations criteria
 */
module.exports.bucket_field = function(item, aggregations, key) {

  var keys = _.keys(aggregations);

  /**
   * responsible for narrowing facets with not_filter filter
   */
  for (var i = 0 ; i < keys.length ; ++i) {

    var it = keys[i]
    if (helpers.is_not_filters_agg(aggregations[it])) {

      if (!helpers.not_filters_field(item[it], aggregations[it].not_filters)) {
        return [];
      }
    }
  }

  for (var i = 0 ; i < keys.length ; ++i) {

    if (keys[i] === key) {
      continue;
    }

    var it = keys[i];

    if (helpers.is_empty_agg(aggregations[it])) {
      if (!helpers.check_empty_field(item[aggregations[it].field], aggregations[it].filters)) {
        return [];
      } else {
        continue;
      }
    } else if (helpers.is_disjunctive_agg(aggregations[it]) && !helpers.disjunctive_field(item[it], aggregations[it].filters)) {
      return [];
    } else if (helpers.is_conjunctive_agg(aggregations[it]) && !helpers.conjunctive_field(item[it], aggregations[it].filters)) {
      return [];
    }

  }

  if (helpers.is_empty_agg(aggregations[key])) {
    var temp = helpers.check_empty_field(item[aggregations[key].field], aggregations[key].filters)

    if (temp) {
      return temp;
    }
    return [];
  }

  if (helpers.is_disjunctive_agg(aggregations[key]) || helpers.includes(item[key], aggregations[key].filters)) {
    return item[key] ? _.flatten([item[key]]) : [];
  }

  return [];
}

/*
 * fields count for one item based on aggregation options
 * returns buckets objects
 */
module.exports.bucket = function(item, aggregations) {

  return _.mapValues((aggregations), (val, key) => {

    return module.exports.bucket_field(item, aggregations, key);
  });
}

/**
 * returns buckets list for items for specific key and aggregation configuration
 *
 * @TODO it should be more lower level and should not be dependent directly on user configuration
 * should be able to sort buckets alphabetically, by count and by asc or desc
 */
module.exports.buckets = function(items, field, agg, aggregations) {

  var buckets = _.transform(items, function(result, item) {

    item = module.exports.bucket(item, aggregations)
    var elements = item[field];

    if (
      agg.conjunction !== false && helpers.includes(elements, agg.filters)
    //|| agg.conjunction === false && helpers.includes_any(elements, agg.filters)
    || agg.conjunction === false
       ) {

      // go through elements in item field
      for (var i = 0 ; elements && i < elements.length ; ++i) {
        var key = elements[i];
        if (!result[key]) {
          result[key] = 1;
        } else {
          result[key] += 1;
        }
      }
    }

  }, {});

  // transform object of objects to array of objects
  buckets = _.map(buckets, (val, key) => {
    return {
      key: key,
      doc_count: val
    };
  })

  if (agg.sort === 'term') {
    buckets = _.orderBy(buckets, ['key'], [agg.order || 'asc']);
  } else {
    buckets = _.orderBy(buckets, ['doc_count', 'key'], [agg.order || 'desc', 'asc']);
  }

  return buckets;
}

/**
 * returns list of elements in aggregation
 * useful for autocomplete or list all aggregation options
 */
module.exports.similar = function(items, id, options) {

  var result = [];
  var per_page = options.per_page || 10;
  var minimum = options.minimum || 0;
  var page = options.page || 1;

  var item;

  for (var i = 0 ; i < items.length ; ++i) {
    if (items[i].id === id) {
      item = items[i];
      break;
    }
  }

  if (!options.field) {
    throw new Error(`Please define field in options`);
  }

  var field = options.field;
  var sorted_items = [];

  for (var i = 0 ; i < items.length ; ++i) {

    if (items[i].id !== id) {
      var intersection = _.intersection(item[field], items[i][field])

      if (intersection.length >= minimum) {
        sorted_items.push(items[i]);
        sorted_items[sorted_items.length - 1].intersection_length = intersection.length;
      }
    }
  }

  sorted_items = _.orderBy(
    sorted_items,
    ['intersection_length'],
    ['desc']
  );

  return {
    pagination: {
      per_page: per_page,
      page: page,
      total: sorted_items.length
    },
    data: {
      items: sorted_items.slice((page - 1) * per_page, page * per_page),
    }
  }
}
<commit_msg>fix similar items<commit_after>var _ = require('./../lib/lodash');
var helpers = require('./helpers');
var Fulltext = require('./fulltext');

/**
 * search by filters
 */
module.exports.search = function(items, input, configuration, fulltext) {

  input = input || {};

  var search_time = 0;
  // make search by query first
  if (fulltext) {

    var search_start_time = new Date().getTime();
    items = fulltext.search(input.query);
    search_time = new Date().getTime() - search_start_time;
  }

  /**
   * making a prefiltering after search and before faceting
   * after search because search is very fast
   * the goal is to make a library more customizable for developers
   */
  if (input.prefilter instanceof Function) {
    items = input.prefilter(items);
  }

  /**
   * responsible for filtering items by aggregation values (processed input)
   * not sure now about the reason but probably performance
   */
  var filtered_items = module.exports.items_by_aggregations(items, input.aggregations);

  var per_page = input.per_page || 12;
  var page = input.page || 1;

  /**
   * sorting items
   */
  var sorting_time = 0;
  if (input.sort) {
    var sorting_start_time = new Date().getTime();
    filtered_items = module.exports.sorted_items(filtered_items, input.sort, configuration.sortings);
    sorting_time = new Date().getTime() - sorting_start_time;
  }

  /**
   * calculating facets
   */
  var facets_start_time = new Date().getTime();
  var aggregations = module.exports.aggregations(items, input.aggregations);
  var facets_time = new Date().getTime() - facets_start_time;

  return {
    pagination: {
      per_page: per_page,
      page: page,
      total: filtered_items.length
    },
    timings: {
      facets: facets_time,
      search: search_time,
      sorting: sorting_time
    },
    data: {
      items: filtered_items.slice((page - 1) * per_page, page * per_page),
      aggregations: aggregations
    }
  };
}

/**
 * returns list of elements in aggregation
 * useful for autocomplete or list all aggregation options
 */
module.exports.aggregation = function(items, input, aggregations) {

  var per_page = input.per_page || 10;
  var page = input.page || 1;

  if (input.name && (!aggregations || !aggregations[input.name])) {
    throw new Error(`Please define aggregation "${input.name}" in config`);
  }

  var buckets = module.exports.buckets(items, input.name, aggregations[input.name], aggregations)

  if (input.query) {
    buckets = _.filter(buckets, val => {
      // responsible for query
      // counterpart to startsWith
      return val.key.toLowerCase().indexOf(input.query.toLowerCase()) === 0;
    });
  }

  return {
    pagination: {
      per_page: per_page,
      page: page,
      total: buckets.length
    },
    data: {
      buckets: buckets.slice((page - 1) * per_page, page * per_page),
    }
  }
}

/**
 * return items by sort
 */
module.exports.sorted_items = function(items, sort, sortings) {

  if (sortings[sort] && sortings[sort].field) {

    return _.orderBy(
      items,
      [sortings[sort].field],
      [sortings[sort].order || 'asc']
    );
  }

  return items;
}

/**
 * return items which pass filters (aggregations)
 */
module.exports.items_by_aggregations = function(items, aggregations) {

  return _.filter(items, (item) => {
    return module.exports.filterable_item(item, aggregations);
  });
}

/**
 * it returns list of aggregations with buckets
 * it calculates based on object filters like {tags: ['drama', '1980s']} against list of items
 * in realtime
 *
 * @TODO
 * consider caching aggregations results in startup time
 */
module.exports.aggregations = function(items, aggregations) {

  var position = 0;
  return _.mapValues((aggregations), (val, key) => {
    // key is a 'tags' and val is ['drama', '1980s']
    ++position;
    return {
      name: key,
      title: val.title || key.charAt(0).toUpperCase() + key.slice(1),
      position: position,
      buckets: module.exports.buckets(items, key, val, aggregations).slice(0, val.size || 10)
    }
  })
}

/**
 * checks if item is passing aggregations - if it's filtered or not
 * @TODO should accept filters (user input) as the parameter
 * and not user params merged with global config
 * should be is_filterable_item
 */
module.exports.filterable_item = function(item, aggregations) {

  var keys = _.keys(aggregations)

  for (var i = 0 ; i < keys.length ; ++i) {

    var key = keys[i]
    if (helpers.is_empty_agg(aggregations[key])) {
      if (helpers.check_empty_field(item[aggregations[key].field], aggregations[key].filters)) {
        continue;
      }
      return false;
    } else if (helpers.is_not_filters_agg(aggregations[key]) && !helpers.not_filters_field(item[key], aggregations[key].not_filters)) {
      return false;
    } else if (helpers.is_disjunctive_agg(aggregations[key]) && !helpers.disjunctive_field(item[key], aggregations[key].filters)) {
      return false;
    } else if (helpers.is_conjunctive_agg(aggregations[key]) && !helpers.conjunctive_field(item[key], aggregations[key].filters)) {
      return false;
    }
  }

  return true;
}

/*
 * returns array of item key values only if they are passing aggregations criteria
 */
module.exports.bucket_field = function(item, aggregations, key) {

  var keys = _.keys(aggregations);

  /**
   * responsible for narrowing facets with not_filter filter
   */
  for (var i = 0 ; i < keys.length ; ++i) {

    var it = keys[i]
    if (helpers.is_not_filters_agg(aggregations[it])) {

      if (!helpers.not_filters_field(item[it], aggregations[it].not_filters)) {
        return [];
      }
    }
  }

  for (var i = 0 ; i < keys.length ; ++i) {

    if (keys[i] === key) {
      continue;
    }

    var it = keys[i];

    if (helpers.is_empty_agg(aggregations[it])) {
      if (!helpers.check_empty_field(item[aggregations[it].field], aggregations[it].filters)) {
        return [];
      } else {
        continue;
      }
    } else if (helpers.is_disjunctive_agg(aggregations[it]) && !helpers.disjunctive_field(item[it], aggregations[it].filters)) {
      return [];
    } else if (helpers.is_conjunctive_agg(aggregations[it]) && !helpers.conjunctive_field(item[it], aggregations[it].filters)) {
      return [];
    }

  }

  if (helpers.is_empty_agg(aggregations[key])) {
    var temp = helpers.check_empty_field(item[aggregations[key].field], aggregations[key].filters)

    if (temp) {
      return temp;
    }
    return [];
  }

  if (helpers.is_disjunctive_agg(aggregations[key]) || helpers.includes(item[key], aggregations[key].filters)) {
    return item[key] ? _.flatten([item[key]]) : [];
  }

  return [];
}

/*
 * fields count for one item based on aggregation options
 * returns buckets objects
 */
module.exports.bucket = function(item, aggregations) {

  return _.mapValues((aggregations), (val, key) => {

    return module.exports.bucket_field(item, aggregations, key);
  });
}

/**
 * returns buckets list for items for specific key and aggregation configuration
 *
 * @TODO it should be more lower level and should not be dependent directly on user configuration
 * should be able to sort buckets alphabetically, by count and by asc or desc
 */
module.exports.buckets = function(items, field, agg, aggregations) {

  var buckets = _.transform(items, function(result, item) {

    item = module.exports.bucket(item, aggregations)
    var elements = item[field];

    if (
      agg.conjunction !== false && helpers.includes(elements, agg.filters)
    //|| agg.conjunction === false && helpers.includes_any(elements, agg.filters)
    || agg.conjunction === false
       ) {

      // go through elements in item field
      for (var i = 0 ; elements && i < elements.length ; ++i) {
        var key = elements[i];
        if (!result[key]) {
          result[key] = 1;
        } else {
          result[key] += 1;
        }
      }
    }

  }, {});

  // transform object of objects to array of objects
  buckets = _.map(buckets, (val, key) => {
    return {
      key: key,
      doc_count: val
    };
  })

  if (agg.sort === 'term') {
    buckets = _.orderBy(buckets, ['key'], [agg.order || 'asc']);
  } else {
    buckets = _.orderBy(buckets, ['doc_count', 'key'], [agg.order || 'desc', 'asc']);
  }

  return buckets;
}

/**
 * returns list of elements in aggregation
 * useful for autocomplete or list all aggregation options
 */
module.exports.similar = function(items, id, options) {

  var result = [];
  var per_page = options.per_page || 10;
  var minimum = options.minimum || 0;
  var page = options.page || 1;

  var item;

  for (var i = 0 ; i < items.length ; ++i) {
    if (items[i].id == id) {
      item = items[i];
      break;
    }
  }

  if (!options.field) {
    throw new Error(`Please define field in options`);
  }

  var field = options.field;
  var sorted_items = [];

  for (var i = 0 ; i < items.length ; ++i) {

    if (items[i].id !== id) {
      var intersection = _.intersection(item[field], items[i][field])

      if (intersection.length >= minimum) {
        sorted_items.push(items[i]);
        sorted_items[sorted_items.length - 1].intersection_length = intersection.length;
      }
    }
  }

  sorted_items = _.orderBy(
    sorted_items,
    ['intersection_length'],
    ['desc']
  );

  return {
    pagination: {
      per_page: per_page,
      page: page,
      total: sorted_items.length
    },
    data: {
      items: sorted_items.slice((page - 1) * per_page, page * per_page),
    }
  }
}
<|endoftext|>


<commit_before>document.onscroll = (function() {
  var prevy = 0,
      prevt = Date.now();
  var buffer = [];
  var threshold = 50;
  var maxwidth = 15;
  function onscroll() {
    var now = Date.now();
    var y = window.scrollY;
    if (buffer.length == 0 || now - prevt > threshold) {
      buffer.push({ ys: y, yp: y, dy: 0, ts: now, te: now })
    }
    var cur = buffer[buffer.length-1];
    cur.dy += Math.abs(cur.yp - y);
    cur.yp = y;
    cur.te = prevt = now;
    if (shouldrender())
      renderscroll();
  };

  var prevrendertime = null;
  function shouldrender() {
    if (prevrendertime == null) return true;
    var t = Date.now();
    var pt = prevrendertime;
    prevrendertime = t;
    return (t - pt > threshold) ;
  };

  function renderscroll() {
    var maxh = document.documentElement.clientHeight;
    svg.selectAll("*").remove();
    var g = svg.append("g");
    g.selectAll("rect")
      .data(buffer).enter()
      .append("rect")
      .attr("x", 0)
      .attr("y", function(d, i) { return i*3; })
      .attr("height", 2)
      .attr("x", function(d) { return Math.min(maxwidth, maxwidth * d.dy / maxh);})
      .attr("width", 2)
      .style("fill", window.color);
  };

  // setup master div
  var svg = d3.select("body").append("svg");
  svg.style("position", "fixed")
     .style("top", "1em")
     .style("left", "0px")
     .style("height", "100%")
     .style("width", "20px")
     .style("z-index", "100");
  return onscroll;
})();
<commit_msg>updated site<commit_after>document.onscroll = (function() {
  var prevy = 0,
      prevt = Date.now();
  var buffer = [];
  var threshold = 50;
  var maxwidth = 15;
  function onscroll() {
    var now = Date.now();
    var y = window.scrollY;
    if (buffer.length == 0 || now - prevt > threshold) {
      buffer.push({ ys: y, yp: y, dy: 0, ts: now, te: now })
    }
    var cur = buffer[buffer.length-1];
    cur.dy += Math.abs(cur.yp - y);
    cur.yp = y;
    cur.te = prevt = now;
    if (shouldrender())
      renderscroll();
  };

  var prevrendertime = null;
  function shouldrender() {
    if (prevrendertime == null) return true;
    var t = Date.now();
    var pt = prevrendertime;
    prevrendertime = t;
    return (t - pt > threshold) ;
  };

  function renderscroll() {
    var maxh = document.documentElement.clientHeight;
    svg.selectAll("*").remove();
    var g = svg.append("g");
    g.selectAll("rect")
      .data(buffer).enter()
      .append("rect")
      .attr("x", 0)
      .attr("y", function(d, i) { return i*3; })
      .attr("height", 2)
      .attr("x", function(d) { return Math.min(maxwidth, maxwidth * d.dy / maxh);})
      .attr("width", 2)
      .style("fill", window.color);
  };

  // setup master div
  var svg = d3.select("body").append("svg");
  svg.style("position", "fixed")
     .style("top", "1em")
     .style("left", "0px")
     .style("height", "100%")
     .style("width", "20px")
     .style("z-index", "100");
  return onscroll;

})();
<|endoftext|>


<commit_before><commit_msg>Revert "feat(project): expose metadata class"<commit_after><|endoftext|>