<commit_before>// Visual Studio Code uses these to hush warnings about
//   variable names it can't find declared.
/* global Stats */
/* global THREE */
var container = document.createElement('div');
document.body.appendChild(container);

var raycaster = new THREE.Raycaster();
raycaster.linePrecision = 0;

var mouse = new THREE.Vector2();
var INTERSECTED;
document.addEventListener('mousemove', onDocumentMouseMove, false);
function onDocumentMouseMove(event) {

	event.preventDefault();
	//this will update the mouse position as well as make the tooltipSprite follow the mouse
	tooltipSprite.position.x= event.clientX-(window.innerWidth/2);
	tooltipSprite.position.y= -event.clientY+(window.innerHeight/2)+20;
	mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
	mouse.y = - (event.clientY / window.innerHeight) * 2 + 1;

}

var colors = {
	axes: 0x5d5d5d,
	background: 0xeeeeee,
	black: 0x000000,
	pink: 0xff00ff,
	soft_white: 0x404040,
	terrain_frame: 0x009900,
	white: 0xffffff,
};

var scene = new THREE.Scene();

var camera = new THREE.PerspectiveCamera(
	45, // FOV
	window.innerWidth / window.innerHeight, // Aspect
	0.1, // Near
	1000); // Far
camera.position.set(20, 20, 20);
camera.lookAt(new THREE.Vector3(5, 5, 5));

var width = window.innerWidth;
var height = window.innerHeight;
//orthographic camera for displaying tooltips
cameraOrtho = new THREE.OrthographicCamera( - width / 2, width / 2, height / 2, - height / 2, 1, 1000 );
//The z position of the orthgraphic camera seems to need to be "above" where the sprites are drawn
//setting it to one here
cameraOrtho.position.z = 1;
cameraOrtho.position.x = 0;
cameraOrtho.position.y = 0;
sceneOrtho = new THREE.Scene();

var tooltipSprite = makeTextSprite("Hello, I'm a Tooltip", {fontsize: 18, size: 250}); //Create a basic tooltip display sprite TODO: Make tooltip display info about current drillhole
tooltipSprite.scale.set(250,250,1);
sceneOrtho.add(tooltipSprite);

// Resize the camera when the window is resized.
window.addEventListener('resize', function (event) {
	camera.aspect = window.innerWidth / window.innerHeight;
	camera.updateProjectionMatrix();
	renderer.setSize(window.innerWidth, window.innerHeight);
});

// Bring in basic controls for our view, like rotating, panning, and zooming.
var controls = new THREE.OrbitControls(camera);
controls.zoomSpeed = 3.0;
controls.minDistance = 1;
controls.maxDistance = 100;
controls.target = new THREE.Vector3(5, 5, 5);
controls.autoRotate = true;

var renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setClearColor(colors.background, 1);
renderer.sortObjects = false;
renderer.autoClear=false;
container.appendChild(renderer.domElement);

renderer.domElement.addEventListener('mousedown', function (event) {
	controls.autoRotate = false;
});

var stats = new Stats();
stats.domElement.style.position = 'absolute';
stats.domElement.style.right = '0px';
stats.domElement.style.bottom = '0px';
container.appendChild(stats.domElement);

// Generate a bunch of cylinders in random locations, within the box.
var cylinder_geometry = new THREE.CylinderGeometry(0.05, 0.05, 0.3, 10);
var cylinder_material = new THREE.MeshLambertMaterial({ color: colors.pink });

var cylinder = new THREE.Mesh(cylinder_geometry, cylinder_material);

// Always draw a cylinder at the center of the box, to make it
//   easy to look at a sample cylinder.
// This one is not counted in the cylinder_count.
cylinder.position.x = 5; // TODO: Hard coded to box's size.
cylinder.position.y = 5; // TODO: Hard coded to box's size.
cylinder.position.z = 5; // TODO: Hard coded to box's size.

var cylinders = [];

scene.add(cylinder);

// This number is totally arbitrary.
var cylinder_count = 100;
var cylinder_max = 10000;

// Generate more than we'll ever use, but only ever add the first
//   cylinder_count to the scene.
for (var i = 0; i < cylinder_max; i += 1) {
	// We create an individual material for each cylinder so that
	//   modifications to one - when the raytracer hits it - doesn't change
	//   the others.
	var cylinder_material = new THREE.MeshPhongMaterial({
		color: colors.pink,
		shading: THREE.NoShading,
	});
	var cylinder = new THREE.Mesh(cylinder_geometry, cylinder_material);

	// We multiply by 7 for y because we draw the terrain at 7.
	// Otherwise, we multiply by 10 because the property box has length 10.
	cylinder.position.x = 10 * Math.random(); // TODO: Hard coded to box's size.
	cylinder.position.y = 7 * Math.random(); // TODO: Hard coded to box's size.
	cylinder.position.z = 10 * Math.random(); // TODO: Hard coded to box's size.

	// Only so man should be rendered at a time.
	if (i >= cylinder_count) {
		cylinder.visible = false;
	}

	cylinders.push(cylinder);
	scene.add(cylinder);
}

var reticle = new THREE.Mesh(
	new THREE.SphereGeometry(0.05),
	new THREE.MeshLambertMaterial({ color: colors.black }));
reticle.position.x = controls.target.x;
reticle.position.y = controls.target.y;
reticle.position.z = controls.target.z;
scene.add(reticle);

// This creates a wireframe box to encompass the property, but without the diagonals.
var property_boundary = new THREE.Mesh(new THREE.BoxGeometry(10, 10, 10));
var box = new THREE.EdgesHelper(property_boundary, colors.axes);
box.applyMatrix(new THREE.Matrix4().makeTranslation(5, 5, 5));
scene.add(box);

// A spotlight gives us basic shading.
var spotlight = new THREE.SpotLight(colors.white);
// This position is pretty arbitrary. It looks nice here, so I put it here.
spotlight.position.set(-35, 80, -35);
scene.add(spotlight);

// And ambiant light ensures every face is lit, even if it's just a little.
scene.add(new THREE.AmbientLight(colors.soft_white));

// Add a terrain wireframe.
var gridSize = 31;
var elevation = new THREE.Geometry();

// Create points for a grid, with a random y offset.
for (var i = 0; i < gridSize; ++i) {
	for (var j = 0; j < gridSize; ++j) {
		elevation.vertices.push(new THREE.Vector3(i / 3, Math.random() / 3, j / 3));
	}
}

// Use those points to create faces for the terrain.
for (var i = 0; i < gridSize - 1; ++i) {
	for (var j = 0; j < gridSize - 1; ++j) {
		elevation.faces.push(
			new THREE.Face3(j + i * gridSize, j + 1 + i * gridSize, j + (i + 1) * gridSize),
			new THREE.Face3(j + (i + 1) * gridSize, j + 1 + i * gridSize, j + 1 + (i + 1) * gridSize)
			);
	}
}

var surface = new THREE.Mesh(elevation, new THREE.MeshBasicMaterial({
	color: colors.terrain_frame,
	wireframe: true,
}));
surface.position.set(0, 7, 0);
scene.add(surface);

// Add labels for each axis.
var axis_format = {
	fontsize: 18,
	size: 250
};

var spriteX = makeTextSprite("X", axis_format);
spriteX.position.set(11, 0, 0); // TODO: Hard coded to box's size.
scene.add(spriteX);

var spriteY = makeTextSprite("Y", axis_format);
spriteY.position.set(0, 11, 0); // TODO: Hard coded to box's size.
scene.add(spriteY);

var spriteZ = makeTextSprite("Z", axis_format);
spriteZ.position.set(0, 0, 11); // TODO: Hard coded to box's size.
scene.add(spriteZ);

// dat.gui.js lets us modify variables live, on the page.
var gui = new dat.GUI();
gui.add(this, 'cylinder_count')
	.name("Cylinders")
	.min(1)
	.max(cylinder_max)
	.step(100)
	.onFinishChange(function () {
		if (cylinder_count < 1) {
			cylinder_count = 1;
		}
		for (var i = 0; i < cylinders.length; i += 1) {
			if (i < cylinder_count) {
				cylinders[i].visible = true;
			} else {
				cylinders[i].visible = false;
			}
		}
});

function makeTextSprite(message, parameters) {
	if (parameters === undefined) parameters = {};
	var fontface = parameters.hasOwnProperty("fontface") ? parameters["fontface"] : "Arial";
	var fontsize = parameters.hasOwnProperty("fontsize") ? parameters["fontsize"] : 18;
	var size = parameters.hasOwnProperty("size") ? parameters["size"] : 100;
	var textColor = parameters.hasOwnProperty("textColor") ? parameters["textColor"] : { r: 0, g: 0, b: 0, a: 1.0 };

	var canvas = document.createElement('canvas');
	canvas.width = size;
	canvas.height = size;
	var context = canvas.getContext('2d');
	context.font = "Bold " + fontsize + "px " + fontface;

	context.textAlign = 'center';
	context.fillStyle = "rgba(" + textColor.r + ", " + textColor.g + ", " + textColor.b + ", 1.0)";
	context.fillText(message, size / 2, size / 2);

	var texture = new THREE.Texture(canvas);
	texture.needsUpdate = true;

	var spriteMaterial = new THREE.SpriteMaterial({ map: texture, transparent: true, useScreenCoordinates: false });
	var sprite = new THREE.Sprite(spriteMaterial);
	sprite.scale.set(0.5 * fontsize, 0.25 * fontsize, 0.75 * fontsize);

	return sprite;
}

function checkMouseIntercept(){
	raycaster.setFromCamera(mouse, camera);

	var intersects = raycaster.intersectObjects(cylinders);

	if (intersects.length > 0) {
		if (INTERSECTED != intersects[0].object) {
			if (INTERSECTED) {
				var material = INTERSECTED.material;
				if (material.emissive) {
					material.emissive.setHex(INTERSECTED.currentHex);
				} else {
					material.color.setHex(INTERSECTED.currentHex);
				}
			}
			INTERSECTED = intersects[0].object;
			//set sprite to be in front of the orthographic camera so it is visible
			tooltipSprite.position.z=0;
			material = INTERSECTED.material;
			if (material.emissive) {
				INTERSECTED.currentHex = INTERSECTED.material.emissive.getHex();
				material.emissive.setHex(0xff0000);
			}
			else {
				INTERSECTED.currentHex = material.color.getHex();
				material.color.setHex(0xff0000);
			}

		}

	} else {
		if (INTERSECTED) {
			material = INTERSECTED.material;

			if (material.emissive) {
				material.emissive.setHex(INTERSECTED.currentHex);
			} else {
				material.color.setHex(INTERSECTED.currentHex);
			}
		}
		//set sprite to be behind the ortographic camer so it is not visible
		tooltipSprite.position.z=5;
		INTERSECTED = null;
	}
}

function render() {
	requestAnimationFrame(render);
	controls.update();
	stats.update();

	camera.updateMatrixWorld();

	checkMouseIntercept();

	reticle.position.x = controls.target.x;
	reticle.position.y = controls.target.y;
	reticle.position.z = controls.target.z;

	renderer.clear();
	renderer.render( scene, camera );
	renderer.clearDepth();
	renderer.render( sceneOrtho, cameraOrtho );
}
render();
<commit_msg>Changed our camera so that the Z axis faces up. Also added a random rotation to each cylinder from [0, pi/2], which makes things look more interesting and posibly more realistic.<commit_after>// Visual Studio Code uses these to hush warnings about
//   variable names it can't find declared.
/* global Stats */
/* global THREE */
var container = document.createElement('div');
document.body.appendChild(container);

var raycaster = new THREE.Raycaster();
raycaster.linePrecision = 0;

var mouse = new THREE.Vector2();
var INTERSECTED;
document.addEventListener('mousemove', onDocumentMouseMove, false);
function onDocumentMouseMove(event) {

	event.preventDefault();
	//this will update the mouse position as well as make the tooltipSprite follow the mouse
	tooltipSprite.position.x= event.clientX-(window.innerWidth/2);
	tooltipSprite.position.y= -event.clientY+(window.innerHeight/2)+20;
	mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
	mouse.y = - (event.clientY / window.innerHeight) * 2 + 1;

}

var colors = {
	axes: 0x5d5d5d,
	background: 0xeeeeee,
	black: 0x000000,
	pink: 0xff00ff,
	soft_white: 0x404040,
	terrain_frame: 0x009900,
	white: 0xffffff,
};

var scene = new THREE.Scene();

var camera = new THREE.PerspectiveCamera(
	45, // FOV
	window.innerWidth / window.innerHeight, // Aspect
	0.1, // Near
	1000); // Far
camera.up.set(0, 0, 1);
camera.position.set(20, 20, 20);
camera.lookAt(new THREE.Vector3(5, 5, 5));

var width = window.innerWidth;
var height = window.innerHeight;
//orthographic camera for displaying tooltips
cameraOrtho = new THREE.OrthographicCamera( - width / 2, width / 2, height / 2, - height / 2, 1, 1000 );
//The z position of the orthgraphic camera seems to need to be "above" where the sprites are drawn
//setting it to one here
cameraOrtho.position.z = 1;
cameraOrtho.position.x = 0;
cameraOrtho.position.y = 0;
sceneOrtho = new THREE.Scene();

var tooltipSprite = makeTextSprite("Hello, I'm a Tooltip", {fontsize: 18, size: 250}); //Create a basic tooltip display sprite TODO: Make tooltip display info about current drillhole
tooltipSprite.scale.set(250,250,1);
sceneOrtho.add(tooltipSprite);

// Resize the camera when the window is resized.
window.addEventListener('resize', function (event) {
	camera.aspect = window.innerWidth / window.innerHeight;
	camera.updateProjectionMatrix();
	renderer.setSize(window.innerWidth, window.innerHeight);
});

// Bring in basic controls for our view, like rotating, panning, and zooming.
var controls = new THREE.OrbitControls(camera);
controls.zoomSpeed = 3.0;
controls.minDistance = 1;
controls.maxDistance = 100;
controls.target = new THREE.Vector3(5, 5, 5);
controls.autoRotate = true;

var renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setClearColor(colors.background, 1);
renderer.sortObjects = false;
renderer.autoClear=false;
container.appendChild(renderer.domElement);

renderer.domElement.addEventListener('mousedown', function (event) {
	controls.autoRotate = false;
});

var stats = new Stats();
stats.domElement.style.position = 'absolute';
stats.domElement.style.right = '0px';
stats.domElement.style.bottom = '0px';
container.appendChild(stats.domElement);

// Generate a bunch of cylinders in random locations, within the box.
var cylinder_geometry = new THREE.CylinderGeometry(0.05, 0.05, 0.3, 10);
var cylinder_material = new THREE.MeshLambertMaterial({ color: colors.pink });

var cylinder = new THREE.Mesh(cylinder_geometry, cylinder_material);

// Always draw a cylinder at the center of the box, to make it
//   easy to look at a sample cylinder.
// This one is not counted in the cylinder_count.
cylinder.position.x = 5; // TODO: Hard coded to box's size.
cylinder.position.y = 5; // TODO: Hard coded to box's size.
cylinder.position.z = 5; // TODO: Hard coded to box's size.

cylinder.rotation.x = Math.PI / 2 * Math.random();
cylinder.rotation.y = Math.PI / 2 * Math.random();
cylinder.rotation.z = Math.PI / 2 * Math.random();

var cylinders = [];

scene.add(cylinder);

// This number is totally arbitrary.
var cylinder_count = 100;
var cylinder_max = 10000;

// Generate more than we'll ever use, but only ever add the first
//   cylinder_count to the scene.
for (var i = 0; i < cylinder_max; i += 1) {
	// We create an individual material for each cylinder so that
	//   modifications to one - when the raytracer hits it - doesn't change
	//   the others.
	var cylinder_material = new THREE.MeshPhongMaterial({
		color: colors.pink,
		shading: THREE.NoShading,
	});
	var cylinder = new THREE.Mesh(cylinder_geometry, cylinder_material);

	// Rotate it to align with the z axis.
	cylinder.rotation.x = Math.PI / 2 * Math.random();
	cylinder.rotation.y = Math.PI / 2 * Math.random();
	cylinder.rotation.z = Math.PI / 2 * Math.random();

	// We multiply by 7 for z because we draw the terrain at 7.
	// Otherwise, we multiply by 10 because the property box has length 10.
	cylinder.position.x = 10 * Math.random(); // TODO: Hard coded to box's size.
	cylinder.position.y = 10 * Math.random(); // TODO: Hard coded to box's size.
	cylinder.position.z = 7 * Math.random(); // TODO: Hard coded to box's size.

	// Only so man should be rendered at a time.
	if (i >= cylinder_count) {
		cylinder.visible = false;
	}

	cylinders.push(cylinder);
	scene.add(cylinder);
}

var reticle = new THREE.Mesh(
	new THREE.SphereGeometry(0.05),
	new THREE.MeshLambertMaterial({ color: colors.black }));
reticle.position.x = controls.target.x;
reticle.position.y = controls.target.y;
reticle.position.z = controls.target.z;
scene.add(reticle);

// This creates a wireframe box to encompass the property, but without the diagonals.
var property_boundary = new THREE.Mesh(new THREE.BoxGeometry(10, 10, 10));
var box = new THREE.EdgesHelper(property_boundary, colors.axes);
box.applyMatrix(new THREE.Matrix4().makeTranslation(5, 5, 5));
scene.add(box);

// A spotlight gives us basic shading.
var spotlight = new THREE.SpotLight(colors.white);
// This position is pretty arbitrary. It looks nice here, so I put it here.
spotlight.position.set(-35, -35, 80);
scene.add(spotlight);

// And ambiant light ensures every face is lit, even if it's just a little.
scene.add(new THREE.AmbientLight(colors.soft_white));

// Add a terrain wireframe.
var gridSize = 31;
var elevation = new THREE.Geometry();

// Create points for a grid, with a random y offset.
for (var i = 0; i < gridSize; ++i) {
	for (var j = 0; j < gridSize; ++j) {
		elevation.vertices.push(new THREE.Vector3(i / 3, j / 3, Math.random() / 3));
	}
}

// Use those points to create faces for the terrain.
for (var i = 0; i < gridSize - 1; ++i) {
	for (var j = 0; j < gridSize - 1; ++j) {
		elevation.faces.push(
			new THREE.Face3(j + i * gridSize, j + 1 + i * gridSize, j + (i + 1) * gridSize),
			new THREE.Face3(j + (i + 1) * gridSize, j + 1 + i * gridSize, j + 1 + (i + 1) * gridSize)
			);
	}
}

var surface = new THREE.Mesh(elevation, new THREE.MeshBasicMaterial({
	color: colors.terrain_frame,
	wireframe: true,
}));
surface.position.set(0, 0, 7);
scene.add(surface);

// Add labels for each axis.
var axis_format = {
	fontsize: 18,
	size: 250
};

var spriteX = makeTextSprite("X", axis_format);
spriteX.position.set(11, 0, 0); // TODO: Hard coded to box's size.
scene.add(spriteX);

var spriteY = makeTextSprite("Y", axis_format);
spriteY.position.set(0, 11, 0); // TODO: Hard coded to box's size.
scene.add(spriteY);

var spriteZ = makeTextSprite("Z", axis_format);
spriteZ.position.set(0, 0, 11); // TODO: Hard coded to box's size.
scene.add(spriteZ);

// dat.gui.js lets us modify variables live, on the page.
var gui = new dat.GUI();
gui.add(this, 'cylinder_count')
	.name("Cylinders")
	.min(1)
	.max(cylinder_max)
	.step(100)
	.onFinishChange(function () {
		if (cylinder_count < 1) {
			cylinder_count = 1;
		}
		for (var i = 0; i < cylinders.length; i += 1) {
			if (i < cylinder_count) {
				cylinders[i].visible = true;
			} else {
				cylinders[i].visible = false;
			}
		}
});

function makeTextSprite(message, parameters) {
	if (parameters === undefined) parameters = {};
	var fontface = parameters.hasOwnProperty("fontface") ? parameters["fontface"] : "Arial";
	var fontsize = parameters.hasOwnProperty("fontsize") ? parameters["fontsize"] : 18;
	var size = parameters.hasOwnProperty("size") ? parameters["size"] : 100;
	var textColor = parameters.hasOwnProperty("textColor") ? parameters["textColor"] : { r: 0, g: 0, b: 0, a: 1.0 };

	var canvas = document.createElement('canvas');
	canvas.width = size;
	canvas.height = size;
	var context = canvas.getContext('2d');
	context.font = "Bold " + fontsize + "px " + fontface;

	context.textAlign = 'center';
	context.fillStyle = "rgba(" + textColor.r + ", " + textColor.g + ", " + textColor.b + ", 1.0)";
	context.fillText(message, size / 2, size / 2);

	var texture = new THREE.Texture(canvas);
	texture.needsUpdate = true;

	var spriteMaterial = new THREE.SpriteMaterial({ map: texture, transparent: true, useScreenCoordinates: false });
	var sprite = new THREE.Sprite(spriteMaterial);
	sprite.scale.set(0.5 * fontsize, 0.25 * fontsize, 0.75 * fontsize);

	return sprite;
}

function checkMouseIntercept(){
	raycaster.setFromCamera(mouse, camera);

	var intersects = raycaster.intersectObjects(cylinders);

	if (intersects.length > 0) {
		if (INTERSECTED != intersects[0].object) {
			if (INTERSECTED) {
				var material = INTERSECTED.material;
				if (material.emissive) {
					material.emissive.setHex(INTERSECTED.currentHex);
				} else {
					material.color.setHex(INTERSECTED.currentHex);
				}
			}
			INTERSECTED = intersects[0].object;
			//set sprite to be in front of the orthographic camera so it is visible
			tooltipSprite.position.z=0;
			material = INTERSECTED.material;
			if (material.emissive) {
				INTERSECTED.currentHex = INTERSECTED.material.emissive.getHex();
				material.emissive.setHex(0xff0000);
			}
			else {
				INTERSECTED.currentHex = material.color.getHex();
				material.color.setHex(0xff0000);
			}

		}

	} else {
		if (INTERSECTED) {
			material = INTERSECTED.material;

			if (material.emissive) {
				material.emissive.setHex(INTERSECTED.currentHex);
			} else {
				material.color.setHex(INTERSECTED.currentHex);
			}
		}
		//set sprite to be behind the ortographic camer so it is not visible
		tooltipSprite.position.z=5;
		INTERSECTED = null;
	}
}

function render() {
	requestAnimationFrame(render);
	controls.update();
	stats.update();

	camera.updateMatrixWorld();

	checkMouseIntercept();

	reticle.position.x = controls.target.x;
	reticle.position.y = controls.target.y;
	reticle.position.z = controls.target.z;

	renderer.clear();
	renderer.render( scene, camera );
	renderer.clearDepth();
	renderer.render( sceneOrtho, cameraOrtho );
}
render();
<|endoftext|>


<commit_before>(function () {
    'use strict';

    window.BirdWatch = window.BirdWatch || {};

    BirdWatch.WordCloud = function (w, h, maxEntries, addSearch, elem) {

        var me = {},
            fill = d3.scale.category20b(),
            words = [],
            max,
            scale = 1,
            complete = 0,
            tags,
            fontSize,
            cloud,
            svg,
            background,
            transitionDuration = 700,
            vis;

        function draw(data, bounds) {
            scale = bounds ? Math.min(
                w / Math.abs(bounds[1].x - w / 2),
                w / Math.abs(bounds[0].x - w / 2),
                h / Math.abs(bounds[1].y - h / 2),
                h / Math.abs(bounds[0].y - h / 2)) / 2 : 1;
            words = data;
            var text = vis.selectAll("text")
                .data(words, function(d) { return d.text.toLowerCase(); });
            text.transition()
                .duration(transitionDuration)
                .attr("transform", function(d) { return "translate(" + [d.x, d.y] + ")rotate(" + d.rotate + ")"; })
                .style("font-size", function(d) { return d.size + "px"; });
            text.enter().append("text")
                .attr("text-anchor", "middle")
                .attr("transform", function(d) { return "translate(" + [d.x, d.y] + ")rotate(" + d.rotate + ")"; })
                .style("font-size", function(d) { return d.size + "px"; })
                .on("click",function (d) {
                    var tag;
                    tag = d.text.replace('#', '');
                    addSearch(tag);
                })
                .style("opacity", 1e-6)
                .transition()
                .duration(transitionDuration)
                .style("opacity", 1);
            text.style("font-family", function(d) { return d.font; })
                .style("fill", function(d) { return fill(d.text.toLowerCase()); })
                .text(function(d) { return d.text; });
            var exitGroup = background.append("g")
                .attr("transform", vis.attr("transform"));
            var exitGroupNode = exitGroup.node();
            text.exit().each(function() { exitGroupNode.appendChild(this); });
            exitGroup.transition()
                .duration(transitionDuration)
                .style("opacity", 1e-6)
                .remove();
            vis.transition()
                .delay(100)
                .duration(transitionDuration)
                .attr("transform", "translate(" + [w >> 1, h >> 1] + ")scale(" + scale + ")");
        }

        me.init = function() {
            BirdWatch.lastCloudUpdate = (new Date().getTime()) - 12000;

            cloud = d3.layout.cloud()
                .timeInterval(1)
                .size([w, h])
                .fontSize(function(d) { return fontSize(+d.value); })
                .text(function(d) { return d.key; })
                .on("end", draw);

            svg = d3.select(elem).append("svg").attr("width", w).attr("height", h);

            background = svg.append("g");
            vis = svg.append("g").attr("transform", "translate(" + [w >> 1, h >> 1] + ")");
        };

        function generate() {
            cloud.font("Impact").spiral("archimedean");
            fontSize = d3.scale.log().range([10, 85]);

            if (tags.length) fontSize.domain([+tags[tags.length - 1].value || 1, +tags[0].value]);
            complete = 0;
            words = [];
            cloud.stop().words(tags.slice(0, max = Math.min(tags.length, maxEntries))).start();
        }

        me.redraw = function(dataSource) {
            tags = dataSource;

            if ((new Date().getTime() - BirdWatch.lastCloudUpdate) > 15000) {
                generate();
                BirdWatch.lastCloudUpdate = (new Date().getTime());
            }
        };

        me.init();

        return me;
    };
}());
<commit_msg>don't strip # from term when clicking word<commit_after>(function () {
    'use strict';

    window.BirdWatch = window.BirdWatch || {};

    BirdWatch.WordCloud = function (w, h, maxEntries, addSearch, elem) {

        var me = {},
            fill = d3.scale.category20b(),
            words = [],
            max,
            scale = 1,
            complete = 0,
            tags,
            fontSize,
            cloud,
            svg,
            background,
            transitionDuration = 700,
            vis;

        function draw(data, bounds) {
            scale = bounds ? Math.min(
                w / Math.abs(bounds[1].x - w / 2),
                w / Math.abs(bounds[0].x - w / 2),
                h / Math.abs(bounds[1].y - h / 2),
                h / Math.abs(bounds[0].y - h / 2)) / 2 : 1;
            words = data;
            var text = vis.selectAll("text")
                .data(words, function(d) { return d.text.toLowerCase(); });
            text.transition()
                .duration(transitionDuration)
                .attr("transform", function(d) { return "translate(" + [d.x, d.y] + ")rotate(" + d.rotate + ")"; })
                .style("font-size", function(d) { return d.size + "px"; });
            text.enter().append("text")
                .attr("text-anchor", "middle")
                .attr("transform", function(d) { return "translate(" + [d.x, d.y] + ")rotate(" + d.rotate + ")"; })
                .style("font-size", function(d) { return d.size + "px"; })
                .on("click",function (d) {
                    var tag;
                    tag = d.text;
                    addSearch(tag);
                })
                .style("opacity", 1e-6)
                .transition()
                .duration(transitionDuration)
                .style("opacity", 1);
            text.style("font-family", function(d) { return d.font; })
                .style("fill", function(d) { return fill(d.text.toLowerCase()); })
                .text(function(d) { return d.text; });
            var exitGroup = background.append("g")
                .attr("transform", vis.attr("transform"));
            var exitGroupNode = exitGroup.node();
            text.exit().each(function() { exitGroupNode.appendChild(this); });
            exitGroup.transition()
                .duration(transitionDuration)
                .style("opacity", 1e-6)
                .remove();
            vis.transition()
                .delay(100)
                .duration(transitionDuration)
                .attr("transform", "translate(" + [w >> 1, h >> 1] + ")scale(" + scale + ")");
        }

        me.init = function() {
            BirdWatch.lastCloudUpdate = (new Date().getTime()) - 12000;

            cloud = d3.layout.cloud()
                .timeInterval(1)
                .size([w, h])
                .fontSize(function(d) { return fontSize(+d.value); })
                .text(function(d) { return d.key; })
                .on("end", draw);

            svg = d3.select(elem).append("svg").attr("width", w).attr("height", h);

            background = svg.append("g");
            vis = svg.append("g").attr("transform", "translate(" + [w >> 1, h >> 1] + ")");
        };

        function generate() {
            cloud.font("Impact").spiral("archimedean");
            fontSize = d3.scale.log().range([10, 85]);

            if (tags.length) fontSize.domain([+tags[tags.length - 1].value || 1, +tags[0].value]);
            complete = 0;
            words = [];
            cloud.stop().words(tags.slice(0, max = Math.min(tags.length, maxEntries))).start();
        }

        me.redraw = function(dataSource) {
            tags = dataSource;

            if ((new Date().getTime() - BirdWatch.lastCloudUpdate) > 15000) {
                generate();
                BirdWatch.lastCloudUpdate = (new Date().getTime());
            }
        };

        me.init();

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


<commit_before>

function streamLogs(log) {
  var socket = io.connect(),
      logPath = ['stacks', log.stack, 'regions', log.region, 'deployments', log.deployment, 'log'].join('.'),
      endPath = ['stacks', log.stack, 'regions', log.region, 'deployments', log.deployment, 'end'].join('.');

  socket.on(logPath, function(entry) {
    var dest = $('pre.deployment_log'),
        scroll = Math.abs(dest[0].scrollTop - (dest[0].scrollHeight - dest[0].offsetHeight)) < 10,
        line, table;

    if (entry.lvl <= 3) {
      line = $('
' + entry.msg + '
');
    } else {
      line = $('
' + entry.msg + '
');
    }

    table = $('

' + Object.keys(entry.obj).map(function(key) {
      var val;

      if (key === 'err') {
        val = entry.obj[key].stack;
      } else {
        val = entry.obj[key];
      }

      return '
' + key + '	' + val + '
';
    }).join('') + '

');

    line.click(function() {
      table.slideToggle('fast', 'swing');
    });

    dest.append(line);
    dest.append(table);

    if (scroll) {
      dest[0].scrollTop = dest[0].scrollHeight;
    }
  });

  socket.on(endPath, function(success) {
    var last = $('pre.deployment_log p').last();

    if (success) {
      last.addClass('success');
    } else {
      last.addClass('error');
    }
  });

  socket.once('connect', function() {
    socket.emit('request log', log);
  });
}

function dreadNow() {
  $('#dread-now').modal({
    keyboard: true
  });

  $('#deploy-form').submit(function(event) {
    if ($('#wack').val() !== 'true') {
      event.preventDefault();
      $('#dread-now').modal('show');
    } else {
      return true;
    }
  });

  $('#fearless').click(function(event) {
    $('#dread-now').modal('hide');
    $('#wack').val('true');
    $('#deploy-form').submit();
  });

  $('#fearful').click(function(event) {
    $('#dread-now').modal('hide');
  });
}
<commit_msg>use modal backdrop<commit_after>

function streamLogs(log) {
  var socket = io.connect(),
      logPath = ['stacks', log.stack, 'regions', log.region, 'deployments', log.deployment, 'log'].join('.'),
      endPath = ['stacks', log.stack, 'regions', log.region, 'deployments', log.deployment, 'end'].join('.');

  socket.on(logPath, function(entry) {
    var dest = $('pre.deployment_log'),
        scroll = Math.abs(dest[0].scrollTop - (dest[0].scrollHeight - dest[0].offsetHeight)) < 10,
        line, table;

    if (entry.lvl <= 3) {
      line = $('
' + entry.msg + '
');
    } else {
      line = $('
' + entry.msg + '
');
    }

    table = $('

' + Object.keys(entry.obj).map(function(key) {
      var val;

      if (key === 'err') {
        val = entry.obj[key].stack;
      } else {
        val = entry.obj[key];
      }

      return '
' + key + '	' + val + '
';
    }).join('') + '

');

    line.click(function() {
      table.slideToggle('fast', 'swing');
    });

    dest.append(line);
    dest.append(table);

    if (scroll) {
      dest[0].scrollTop = dest[0].scrollHeight;
    }
  });

  socket.on(endPath, function(success) {
    var last = $('pre.deployment_log p').last();

    if (success) {
      last.addClass('success');
    } else {
      last.addClass('error');
    }
  });

  socket.once('connect', function() {
    socket.emit('request log', log);
  });
}

function dreadNow() {
  $('#dread-now').modal({
    keyboard: true,
    backdrop: 'static'
  });

  $('#deploy-form').submit(function(event) {
    if ($('#wack').val() !== 'true') {
      event.preventDefault();
      $('#dread-now').modal('show');
    } else {
      return true;
    }
  });

  $('#fearless').click(function(event) {
    $('#dread-now').modal('hide');
    $('#wack').val('true');
    $('#deploy-form').submit();
  });

  $('#fearful').click(function(event) {
    $('#dread-now').modal('hide');
  });
}
<|endoftext|>


<commit_before>'use strict';

goog.provide('Blockly.Python.storage');

goog.require('Blockly.Python');

Blockly.Python['storage_fileopen'] = function(block) {
  // For each loop.
  var variable0 = Blockly.Python.valueToCode(this, 'FILE', Blockly.Python.ORDER_ATOMIC);
  var fn = Blockly.Python.valueToCode(this, 'FILENAME', Blockly.Python.ORDER_ATOMIC);
  var mode = this.getFieldValue('MODE');
  var code = variable0 + ' = open(' + fn + ', \'' + mode +'\')\n';
  return code;
};

Blockly.Python.storage_file_write = function () {
    var data = Blockly.Python.valueToCode(this, 'data', Blockly.Python.ORDER_ATOMIC);
    var file = Blockly.Python.valueToCode(this, 'FILE', Blockly.Python.ORDER_ATOMIC);
    return file+".write(" + data + ")\n";
}

Blockly.Python.storage_get_contents_without_para = function () {
    var mode = this.getFieldValue('MODE');
    var file = Blockly.Python.valueToCode(this, 'FILE', Blockly.Python.ORDER_ATOMIC);
    var code = file+'.'+mode+'()';
    return [code, Blockly.Python.ORDER_ATOMIC];
};

Blockly.Python.storage_get_contents = function () {
    var mode = this.getFieldValue('MODE');
    var file = Blockly.Python.valueToCode(this, 'FILE', Blockly.Python.ORDER_ATOMIC);
    var size = Blockly.Python.valueToCode(this, 'SIZE', Blockly.Python.ORDER_ATOMIC);
    var code = file+'.'+mode+'(' + size + ')';
    return [code, Blockly.Python.ORDER_ATOMIC];
};

Blockly.Python.storage_get_a_line = function () {
    var file = Blockly.Python.valueToCode(this, 'FILE', Blockly.Python.ORDER_ATOMIC);
    var size = Blockly.Python.valueToCode(this, 'SIZE', Blockly.Python.ORDER_ATOMIC);
    var code = file+".readline(" + size + ')';
    return [code, Blockly.Python.ORDER_ATOMIC];
};

Blockly.Python.storage_can_write_ornot = function () {
    var file = Blockly.Python.valueToCode(this, 'FILE', Blockly.Python.ORDER_ATOMIC);
    var code = file+".writable()";
    return [code, Blockly.Python.ORDER_ATOMIC];
};

Blockly.Python.storage_get_filename = function () {
    var file = Blockly.Python.valueToCode(this, 'FILE', Blockly.Python.ORDER_ATOMIC);
    var code = file+".name()";
    return [code, Blockly.Python.ORDER_ATOMIC];
};

Blockly.Python.storage_close_file = function () {
    var file = Blockly.Python.valueToCode(this, 'FILE', Blockly.Python.ORDER_ATOMIC);
    var code = file+".close()\n";
    return code;
};

Blockly.Python.storage_list_all_files = function() {
  Blockly.Python.definitions_['import_os'] = 'import os';
  var code = 'os.listdir()';
  return [code, Blockly.Python.ORDER_ATOMIC];
}

Blockly.Python.storage_delete_file = function () {
    Blockly.Python.definitions_['import_os'] = 'import os';
    var mode = this.getFieldValue('MODE');
    var file = Blockly.Python.valueToCode(this, 'FILE', Blockly.Python.ORDER_ATOMIC);
    var code = "os."+mode+"("+file+")\n";
    return code;
};

Blockly.Python.storage_get_file_size = function () {
    Blockly.Python.definitions_['import_os'] = 'import os';
    var file = Blockly.Python.valueToCode(this, 'FILE', Blockly.Python.ORDER_ATOMIC);
    var code = "os.size("+file+")";
    return [code, Blockly.Python.ORDER_ATOMIC];
};

Blockly.Python.storage_file_tell = function () {
    var file = Blockly.Python.valueToCode(this, 'FILE', Blockly.Python.ORDER_ATOMIC);
    var code = file+".tell()";
    return [code, Blockly.Python.ORDER_ATOMIC];
};

Blockly.Python.storage_file_seek = function () {
    var mode = this.getFieldValue('MODE');
    var mode_num = 0;
    if (mode == 'start'){
      mode_num = 0;}
    else if(mode == 'current'){
      mode_num = 1;
    }
    else{
      mode_num = 2;
    }
    var file = Blockly.Python.valueToCode(this, 'FILE', Blockly.Python.ORDER_ATOMIC);
    var size = Blockly.Python.valueToCode(this, 'SIZE', Blockly.Python.ORDER_ATOMIC);
    var code = file+'.seek('+ size + ',' + mode_num + ')';
    return [code, Blockly.Python.ORDER_ATOMIC];
};

Blockly.Python.storage_change_dir = function () {
    Blockly.Python.definitions_['import_os'] = 'import os';
    var file = Blockly.Python.valueToCode(this, 'FILE', Blockly.Python.ORDER_ATOMIC);
    var code = "os.chdir("+file+")\n";
    return code;
};

Blockly.Python.storage_get_current_dir = function() {
  Blockly.Python.definitions_['import_os'] = 'import os';
  var code = 'os.getcwd()';
  return [code, Blockly.Python.ORDER_ATOMIC];
}

Blockly.Python.storage_make_dir = function () {
  Blockly.Python.definitions_['import_os'] = 'import os';
    var mode = this.getFieldValue('MODE');
    var path = Blockly.Python.valueToCode(this, 'PATH', Blockly.Python.ORDER_ATOMIC);
    var code = 'os.'+mode+'(' + path + ')';
    return [code, Blockly.Python.ORDER_ATOMIC];
};

Blockly.Python.storage_rename = function () {
    Blockly.Python.definitions_['import_os'] = 'import os';
    var file = Blockly.Python.valueToCode(this, 'FILE', Blockly.Python.ORDER_ATOMIC);
    var file1 = Blockly.Python.valueToCode(this, 'NEWFILE', Blockly.Python.ORDER_ATOMIC);
    var code = "os.rename("+file+","+file1+")\n";
    return code;
};

Blockly.Python.storage_is_file = function () {
    Blockly.Python.definitions_['import_os'] = 'import os';
    var file = Blockly.Python.valueToCode(this, 'FILE', Blockly.Python.ORDER_ATOMIC);
    var mode = this.getFieldValue('MODE');
    var code = "os."+ mode + "(" + file + ")";
    return [code, Blockly.Python.ORDER_ATOMIC];
};<commit_msg>Update storage.js<commit_after>'use strict';

goog.provide('Blockly.Python.storage');

goog.require('Blockly.Python');

Blockly.Python['storage_fileopen'] = function(block) {
  // For each loop.
  var variable0 = Blockly.Python.valueToCode(this, 'FILE', Blockly.Python.ORDER_ATOMIC);
  var fn = Blockly.Python.valueToCode(this, 'FILENAME', Blockly.Python.ORDER_ATOMIC);
  var mode = this.getFieldValue('MODE');
  var code = variable0 + ' = open(' + fn + ', \'' + mode +'\')\n';
  return code;
};

Blockly.Python.storage_file_write = function () {
    var data = Blockly.Python.valueToCode(this, 'data', Blockly.Python.ORDER_ATOMIC);
    var file = Blockly.Python.valueToCode(this, 'FILE', Blockly.Python.ORDER_ATOMIC);
    return file+".write(" + data + ")\n";
}

Blockly.Python.storage_get_contents_without_para = function () {
    var mode = this.getFieldValue('MODE');
    var file = Blockly.Python.valueToCode(this, 'FILE', Blockly.Python.ORDER_ATOMIC);
    var code = file+'.'+mode+'()';
    return [code, Blockly.Python.ORDER_ATOMIC];
};

Blockly.Python.storage_get_contents = function () {
    var mode = this.getFieldValue('MODE');
    var file = Blockly.Python.valueToCode(this, 'FILE', Blockly.Python.ORDER_ATOMIC);
    var size = Blockly.Python.valueToCode(this, 'SIZE', Blockly.Python.ORDER_ATOMIC);
    var code = file+'.'+mode+'(' + size + ')';
    return [code, Blockly.Python.ORDER_ATOMIC];
};

Blockly.Python.storage_get_a_line = function () {
    var file = Blockly.Python.valueToCode(this, 'FILE', Blockly.Python.ORDER_ATOMIC);
    var size = Blockly.Python.valueToCode(this, 'SIZE', Blockly.Python.ORDER_ATOMIC);
    var code = file+".readline(" + size + ')';
    return [code, Blockly.Python.ORDER_ATOMIC];
};

Blockly.Python.storage_can_write_ornot = function () {
    var file = Blockly.Python.valueToCode(this, 'FILE', Blockly.Python.ORDER_ATOMIC);
    var code = file+".writable()";
    return [code, Blockly.Python.ORDER_ATOMIC];
};

Blockly.Python.storage_get_filename = function () {
    var file = Blockly.Python.valueToCode(this, 'FILE', Blockly.Python.ORDER_ATOMIC);
    var code = file+".name()";
    return [code, Blockly.Python.ORDER_ATOMIC];
};

Blockly.Python.storage_close_file = function () {
    var file = Blockly.Python.valueToCode(this, 'FILE', Blockly.Python.ORDER_ATOMIC);
    var code = file+".close()\n";
    return code;
};

Blockly.Python.storage_list_all_files = function() {
  Blockly.Python.definitions_['import_os'] = 'import os';
  var code = 'os.listdir()';
  return [code, Blockly.Python.ORDER_ATOMIC];
}

Blockly.Python.storage_delete_file = function () {
    Blockly.Python.definitions_['import_os'] = 'import os';
    var mode = this.getFieldValue('MODE');
    var file = Blockly.Python.valueToCode(this, 'FILE', Blockly.Python.ORDER_ATOMIC);
    var code = "os."+mode+"("+file+")\n";
    return code;
};

Blockly.Python.storage_get_file_size = function () {
    Blockly.Python.definitions_['import_os'] = 'import os';
    var file = Blockly.Python.valueToCode(this, 'FILE', Blockly.Python.ORDER_ATOMIC);
    var code = "os.size("+file+")";
    return [code, Blockly.Python.ORDER_ATOMIC];
};

Blockly.Python.storage_file_tell = function () {
    var file = Blockly.Python.valueToCode(this, 'FILE', Blockly.Python.ORDER_ATOMIC);
    var code = file+".tell()";
    return [code, Blockly.Python.ORDER_ATOMIC];
};

Blockly.Python.storage_file_seek = function () {
    var mode = this.getFieldValue('MODE');
    var mode_num = 0;
    if (mode == 'start'){
      mode_num = 0;}
    else if(mode == 'current'){
      mode_num = 1;
    }
    else{
      mode_num = 2;
    }
    var file = Blockly.Python.valueToCode(this, 'FILE', Blockly.Python.ORDER_ATOMIC);
    var size = Blockly.Python.valueToCode(this, 'SIZE', Blockly.Python.ORDER_ATOMIC);
    var code = file+'.seek('+ size + ',' + mode_num + ')\n';
    return code;
};

Blockly.Python.storage_change_dir = function () {
    Blockly.Python.definitions_['import_os'] = 'import os';
    var file = Blockly.Python.valueToCode(this, 'FILE', Blockly.Python.ORDER_ATOMIC);
    var code = "os.chdir("+file+")\n";
    return code;
};

Blockly.Python.storage_get_current_dir = function() {
  Blockly.Python.definitions_['import_os'] = 'import os';
  var code = 'os.getcwd()';
  return [code, Blockly.Python.ORDER_ATOMIC];
}

Blockly.Python.storage_make_dir = function () {
  Blockly.Python.definitions_['import_os'] = 'import os';
    var mode = this.getFieldValue('MODE');
    var path = Blockly.Python.valueToCode(this, 'PATH', Blockly.Python.ORDER_ATOMIC);
    var code = 'os.'+mode+'(' + path + ')';
    return [code, Blockly.Python.ORDER_ATOMIC];
};

Blockly.Python.storage_rename = function () {
    Blockly.Python.definitions_['import_os'] = 'import os';
    var file = Blockly.Python.valueToCode(this, 'FILE', Blockly.Python.ORDER_ATOMIC);
    var file1 = Blockly.Python.valueToCode(this, 'NEWFILE', Blockly.Python.ORDER_ATOMIC);
    var code = "os.rename("+file+","+file1+")\n";
    return code;
};

Blockly.Python.storage_is_file = function () {
    Blockly.Python.definitions_['import_os'] = 'import os';
    var file = Blockly.Python.valueToCode(this, 'FILE', Blockly.Python.ORDER_ATOMIC);
    var mode = this.getFieldValue('MODE');
    var code = "os."+ mode + "(" + file + ")";
    return [code, Blockly.Python.ORDER_ATOMIC];
};<|endoftext|>


<commit_before>'use strict';

var isObject = require('es5-ext/object/is-object')
  , isString = require('es5-ext/string/is-string')
  , configMap
  , output
  , getRandomName
  , getRandomPrimitive
  , names = ["Adam", "Stephen", "Alice"]
  , primitives = ["a", "b", "c"]
  , result, called = 0, calledPrimitive = 0, dbKey;

getRandomName = function () {
	called++;
	if (called >= names.length) {
		called = 0;
	}
	return names[called];
};

getRandomPrimitive = function () {
	calledPrimitive++;
	if (calledPrimitive >= primitives.length) {
		calledPrimitive = 0;
	}
	return primitives[calledPrimitive];
};

module.exports = function (t, a) {
	configMap = {
		id: 'User#',
		value: [
			[
				{ sKey: 'firstName', get: getRandomName },
				{ sKey: 'lastName', value: 'Kowalski' }
			],
			[
				{ sKey: 'annualTurnover',  value: 500 }
			],
			[
				{ sKey: 'secretary/title', value: 'mr' },
				{ sKey: 'secretary/businessAddress/street', value: 'Czereśniowa' }
			],
			[
				{ sKey: 'petitioner', value: {
					id: 'Partner#',
					value: [
						[
							{ sKey: 'firstName', get: getRandomName },
							{ sKey: 'lastName', value: 'Smith' }
						]
					]
				} }
			],
			[
				{ sKey: 'partners', multiple: true, min: 2, value: { id: 'Person#', value: [
					[
						{ sKey: 'firstName', get: getRandomName },
						{ sKey: 'isTall', value: true }
					]
				] }
					}
			],
			[
				{ sKey: 'primitivesMultiple', multiple: true, value: [
					"first", "second", "third"
				] }
			],
			[
				{ sKey: 'primitivesMultipleWithGet', multiple: true, min: 2, get: getRandomPrimitive }
			]
		]
	};
	output = [
		{ id: null, value: '7User#', stamp: null },
		{ id: [0, '/firstName'],                   value: '3Stephen', stamp: 0 },
		{ id: [0, '/lastName'],                    value: '3Kowalski', stamp: 1 },
		{ id: [0, '/annualTurnover'],              value: '2500', stamp: 2 },
		{ id: [0, '/secretary/title'],             value: '3mr', stamp: 3 },
		{ id: [0, '/secretary/businessAddress/street'],
			value: '3Czereśniowa', stamp: 4 },
		{ id: null,                                value: '7Partner#', stamp: null },
		{ id: [6, '/firstName'],                   value: '3Alice', stamp: 6 },
		{ id: [6, '/lastName'],                    value: '3Smith', stamp: 7 },
		{ id: [6, '/petitioner'],                  value: [6], stamp: 8 },
		{ id: null,                                value: '7Person#', stamp: null },
		{ id: [10, '/firstName'],                  value: '3Adam', stamp: 10 },
		{ id: [10, '/isTall'],                     value: '11', stamp: 11 },
		{ id: [0, '/partners*', 9],                value: '11', stamp: 12 },
		{ id: null,                                value: '7Person#', stamp: null },
		{ id: [14, '/firstName'],                  value: '3Adam', stamp: 13 },
		{ id: [14, '/isTall'],                     value: '11', stamp: 14 },
		{ id: [0, '/partners*', 13],               value: '11', stamp: 15 },
		{ id: [0, '/primitivesMultiple*first'],    value: '3first', stamp: 16 },
		{ id: [0, '/primitivesMultiple*second'],   value: '3second', stamp: 17 },
		{ id: [0, '/primitivesMultiple*third'],    value: '3third', stamp: 18 },
		{ id: [0, '/primitivesMultipleWithGet*b'], value: '3b', stamp: 19 },
		{ id: [0, '/primitivesMultipleWithGet*c'], value: '3c', stamp: 20 },
		{ id: [0, '/primitivesMultipleWithGet*a'], value: '3a', stamp: 21 }
	];
	result = t(configMap, { count: 1, stamp: 1 });
	result.forEach(function (entry, index) {
		a(isObject(output[index]), true);
		if (!output[index]) {
			return;
		}
		if (Array.isArray(output[index].id)) {
			dbKey = output[index].id.reduce(function (prev, curr) {
				if (!isString(prev)) {
					prev = result[prev].id;
				}
				if (!isString(curr)) {
					curr = result[curr].id;
				}
				return prev + curr;
			});
			a(entry.id, dbKey);
		}
		if (Array.isArray(output[index].value)) {
			a(entry.value === result[output[index].value[0]].id);
		} else {
			a(entry.value === output[index].value);
		}
		if (output[index].stamp != null) {
			a.ok(entry.stamp > result[output[index].stamp].stamp);
		}
	});
};
<commit_msg>#173 fixed output config stamps<commit_after>'use strict';

var isObject = require('es5-ext/object/is-object')
  , isString = require('es5-ext/string/is-string')
  , configMap
  , output
  , getRandomName
  , getRandomPrimitive
  , names = ["Adam", "Stephen", "Alice"]
  , primitives = ["a", "b", "c"]
  , result, called = 0, calledPrimitive = 0, dbKey;

getRandomName = function () {
	called++;
	if (called >= names.length) {
		called = 0;
	}
	return names[called];
};

getRandomPrimitive = function () {
	calledPrimitive++;
	if (calledPrimitive >= primitives.length) {
		calledPrimitive = 0;
	}
	return primitives[calledPrimitive];
};

module.exports = function (t, a) {
	configMap = {
		id: 'User#',
		value: [
			[
				{ sKey: 'firstName', get: getRandomName },
				{ sKey: 'lastName', value: 'Kowalski' }
			],
			[
				{ sKey: 'annualTurnover',  value: 500 }
			],
			[
				{ sKey: 'secretary/title', value: 'mr' },
				{ sKey: 'secretary/businessAddress/street', value: 'Czereśniowa' }
			],
			[
				{ sKey: 'petitioner', value: {
					id: 'Partner#',
					value: [
						[
							{ sKey: 'firstName', get: getRandomName },
							{ sKey: 'lastName', value: 'Smith' }
						]
					]
				} }
			],
			[
				{ sKey: 'partners', multiple: true, min: 2, value: { id: 'Person#', value: [
					[
						{ sKey: 'firstName', get: getRandomName },
						{ sKey: 'isTall', value: true }
					]
				] }
					}
			],
			[
				{ sKey: 'primitivesMultiple', multiple: true, value: [
					"first", "second", "third"
				] }
			],
			[
				{ sKey: 'primitivesMultipleWithGet', multiple: true, min: 2, get: getRandomPrimitive }
			]
		]
	};
	output = [
		{ id: null, value: '7User#', stamp: null },
		{ id: [0, '/firstName'],                   value: '3Stephen', stamp: 0 },
		{ id: [0, '/lastName'],                    value: '3Kowalski', stamp: 1 },
		{ id: [0, '/annualTurnover'],              value: '2500', stamp: 2 },
		{ id: [0, '/secretary/title'],             value: '3mr', stamp: 3 },
		{ id: [0, '/secretary/businessAddress/street'],
			value: '3Czereśniowa', stamp: 4 },
		{ id: null,                                value: '7Partner#', stamp: null },
		{ id: [6, '/firstName'],                   value: '3Alice', stamp: 6 },
		{ id: [6, '/lastName'],                    value: '3Smith', stamp: 7 },
		{ id: [6, '/petitioner'],                  value: [6], stamp: 8 },
		{ id: null,                                value: '7Person#', stamp: null },
		{ id: [10, '/firstName'],                  value: '3Adam', stamp: 10 },
		{ id: [10, '/isTall'],                     value: '11', stamp: 11 },
		{ id: [0, '/partners*', 9],                value: '11', stamp: 12 },
		{ id: null,                                value: '7Person#', stamp: null },
		{ id: [14, '/firstName'],                  value: '3Adam', stamp: 14 },
		{ id: [14, '/isTall'],                     value: '11', stamp: 15 },
		{ id: [0, '/partners*', 13],               value: '11', stamp: 16 },
		{ id: [0, '/primitivesMultiple*first'],    value: '3first', stamp: 17 },
		{ id: [0, '/primitivesMultiple*second'],   value: '3second', stamp: 18 },
		{ id: [0, '/primitivesMultiple*third'],    value: '3third', stamp: 19 },
		{ id: [0, '/primitivesMultipleWithGet*b'], value: '3b', stamp: 20 },
		{ id: [0, '/primitivesMultipleWithGet*c'], value: '3c', stamp: 21 },
		{ id: [0, '/primitivesMultipleWithGet*a'], value: '3a', stamp: 22 }
	];
	result = t(configMap, { count: 1, stamp: 1 });
	result.forEach(function (entry, index) {
		a(isObject(output[index]), true);
		if (!output[index]) {
			return;
		}
		if (Array.isArray(output[index].id)) {
			dbKey = output[index].id.reduce(function (prev, curr) {
				if (!isString(prev)) {
					prev = result[prev].id;
				}
				if (!isString(curr)) {
					curr = result[curr].id;
				}
				return prev + curr;
			});
			a(entry.id, dbKey);
		}
		if (Array.isArray(output[index].value)) {
			a(entry.value === result[output[index].value[0]].id);
		} else {
			a(entry.value === output[index].value);
		}
		if (output[index].stamp != null) {
			a.ok(entry.stamp > result[output[index].stamp].stamp);
		}
	});
};
<|endoftext|>


<commit_before>'use strict';

// external deps
var ObjectId = require('mongodb').ObjectId;

// internal deps
require('mongodb-toolkit');
var BateeqModels = require('bateeq-models');
var map = BateeqModels.map;

var ArticleApproval = BateeqModels.article.ArticleApproval;
var ArticleBrand = BateeqModels.article.ArticleBrand;
var ArticleCategory = BateeqModels.article.ArticleCategory;
var ArticleColor = BateeqModels.article.ArticleColor;
var ArticleCostCalculationDetail = BateeqModels.article.ArticleCostCalculationDetail;
var ArticleCostCalculation = BateeqModels.article.ArticleCostCalculation;
var ArticleCounter = BateeqModels.article.ArticleCounter;
var ArticleMaterial = BateeqModels.article.ArticleMaterial;
var ArticleMotif = BateeqModels.article.ArticleMotif;
var ArticleOrigin = BateeqModels.article.ArticleOrigin;
var ArticleSeason = BateeqModels.article.ArticleSeason;
var ArticleSize = BateeqModels.article.ArticleSize;
var ArticleSubCounter = BateeqModels.article.ArticleSubCounter;
var ArticleTheme = BateeqModels.article.ArticleTheme;
var ArticleType = BateeqModels.article.ArticleType;
var ArticleVariant = BateeqModels.article.ArticleVariant;
var Article = BateeqModels.article.Article;

module.exports = class ArticleCounterManager {
    constructor(db, user) {
        this.db = db;
        this.user = user;
        this.articleCounterCollection = this.db.use(map.article.ArticleCounter);
    }

    read(paging) {
        var _paging = Object.assign({
            page: 1,
            size: 20,
            order: '_id',
            asc: true
        }, paging);

        return new Promise((resolve, reject) => {
            var deleted = {
                _deleted: false
            };
            var query = _paging.keyword ? {
                '$and': [deleted]
            } : deleted;

            if (_paging.keyword) {
                var regex = new RegExp(_paging.keyword, "i");
                var filterCode = {
                    'code': {
                        '$regex': regex
                    }
                };
                var filterName = {
                    'name': {
                        '$regex': regex
                    }
                };
                var $or = {
                    '$or': [filterCode, filterName]
                };

                query['$and'].push($or);
            }

            this.articleCounterCollection
                .where(query)
                .page(_paging.page, _paging.size)
                .orderBy(_paging.order, _paging.asc)
                .execute()
                .then(articleCounters => {
                    resolve(articleCounters);
                })
                .catch(e => {
                    reject(e);
                });
        });
    }

    getById(id) {
        return new Promise((resolve, reject) => {
            var query = {
                _id: new ObjectId(id),
                _deleted: false
            };
            this.getSingleByQuery(query)
                .then(articleCounter => {
                    resolve(articleCounter);
                })
                .catch(e => {
                    reject(e);
                });
        });
    }

    getSingleByQuery(query) {
        return new Promise((resolve, reject) => {
            this.articleCounterCollection
                .single(query)
                .then(articleCounter => {
                    resolve(articleCounter);
                })
                .catch(e => {
                    reject(e);
                });
        })
    }

    create(articleCounter) {
        return new Promise((resolve, reject) => {
            this._validate(articleCounter)
                .then(validArticleCounter => {

                    this.articleCounterCollection.insert(validArticleCounter)
                        .then(id => {
                            resolve(id);
                        })
                        .catch(e => {
                            reject(e);
                        })
                })
                .catch(e => {
                    reject(e);
                })
        });
    }

    update(articleCounter) {
        return new Promise((resolve, reject) => {
            this._validate(articleCounter)
                .then(validArticleCounter => {
                    this.articleCounterCollection.update(validArticleCounter)
                        .then(id => {
                            resolve(id);
                        })
                        .catch(e => {
                            reject(e);
                        })
                })
                .catch(e => {
                    reject(e);
                })
        });
    }

    delete(articleCounter) {
        return new Promise((resolve, reject) => {
            this._validate(articleCounter)
                .then(validArticleCounter => {
                    validArticleCounter._deleted = true;
                    this.articleCounterCollection.update(validArticleCounter)
                        .then(id => {
                            resolve(id);
                        })
                        .catch(e => {
                            reject(e);
                        })
                })
                .catch(e => {
                    reject(e);
                })
        });
    }

    _validate(articleCounter) {

        var errors = {};

        return new Promise((resolve, reject) => {
            var valid = new ArticleCounter(articleCounter);

            var getArticleCounter = this.articleCounterCollection.singleOrDefault({
                "$and": [{
                    _id: {
                        '$ne': valid._id
                    }
                }, {
                    code: valid.code
                }]
            });

            Promise.all([getArticleCounter])
                .then(results => {
                    var _articleCounter = results[0];

                    if (valid.code == '')
                        errors["code"] = "code is required";
                    else if (_articleCounter) {
                        errors["code"] = "code already exists";
                    }

                    if (valid.name == '')
                        errors["name"] = "name is required";

                    var itemErrors = [];
                    var itemHasError = false;
                    for (var item of valid.subCounters) {
                        var itemError = {};
                        for (var i = valid.subCounters.indexOf(item) + 1; i < valid.subCounters.length; i++) {
                            var otherItem = valid.subCounters[i];
                            if (item.code == otherItem.code) {
                                itemError["code"] = "code already exists on another sub-counter";
                                itemHasError = true;
                            }
                        }
                        itemErrors.push(itemError);
                    }

                    if (itemHasError)
                        errors.subCounters = itemErrors;

                    for (var prop in errors) {
                        var ValidationError = require('../../validation-error');
                        reject(new ValidationError('data does not pass validation', errors));
                    }

                    valid.stamp(this.user.username, 'manager');
                    resolve(valid);
                })
                .catch(e => {
                    reject(e);
                })
        });
    }
};<commit_msg>1.0.0 - update article-counter validation<commit_after>'use strict';

// external deps
var ObjectId = require('mongodb').ObjectId;

// internal deps
require('mongodb-toolkit');
var BateeqModels = require('bateeq-models');
var map = BateeqModels.map;

var ArticleApproval = BateeqModels.article.ArticleApproval;
var ArticleBrand = BateeqModels.article.ArticleBrand;
var ArticleCategory = BateeqModels.article.ArticleCategory;
var ArticleColor = BateeqModels.article.ArticleColor;
var ArticleCostCalculationDetail = BateeqModels.article.ArticleCostCalculationDetail;
var ArticleCostCalculation = BateeqModels.article.ArticleCostCalculation;
var ArticleCounter = BateeqModels.article.ArticleCounter;
var ArticleMaterial = BateeqModels.article.ArticleMaterial;
var ArticleMotif = BateeqModels.article.ArticleMotif;
var ArticleOrigin = BateeqModels.article.ArticleOrigin;
var ArticleSeason = BateeqModels.article.ArticleSeason;
var ArticleSize = BateeqModels.article.ArticleSize;
var ArticleSubCounter = BateeqModels.article.ArticleSubCounter;
var ArticleTheme = BateeqModels.article.ArticleTheme;
var ArticleType = BateeqModels.article.ArticleType;
var ArticleVariant = BateeqModels.article.ArticleVariant;
var Article = BateeqModels.article.Article;

module.exports = class ArticleCounterManager {
    constructor(db, user) {
        this.db = db;
        this.user = user;
        this.articleCounterCollection = this.db.use(map.article.ArticleCounter);
    }

    read(paging) {
        var _paging = Object.assign({
            page: 1,
            size: 20,
            order: '_id',
            asc: true
        }, paging);

        return new Promise((resolve, reject) => {
            var deleted = {
                _deleted: false
            };
            var query = _paging.keyword ? {
                '$and': [deleted]
            } : deleted;

            if (_paging.keyword) {
                var regex = new RegExp(_paging.keyword, "i");
                var filterCode = {
                    'code': {
                        '$regex': regex
                    }
                };
                var filterName = {
                    'name': {
                        '$regex': regex
                    }
                };
                var $or = {
                    '$or': [filterCode, filterName]
                };

                query['$and'].push($or);
            }

            this.articleCounterCollection
                .where(query)
                .page(_paging.page, _paging.size)
                .orderBy(_paging.order, _paging.asc)
                .execute()
                .then(articleCounters => {
                    resolve(articleCounters);
                })
                .catch(e => {
                    reject(e);
                });
        });
    }

    getById(id) {
        return new Promise((resolve, reject) => {
            var query = {
                _id: new ObjectId(id),
                _deleted: false
            };
            this.getSingleByQuery(query)
                .then(articleCounter => {
                    resolve(articleCounter);
                })
                .catch(e => {
                    reject(e);
                });
        });
    }

    getSingleByQuery(query) {
        return new Promise((resolve, reject) => {
            this.articleCounterCollection
                .single(query)
                .then(articleCounter => {
                    resolve(articleCounter);
                })
                .catch(e => {
                    reject(e);
                });
        })
    }

    create(articleCounter) {
        return new Promise((resolve, reject) => {
            this._validate(articleCounter)
                .then(validArticleCounter => {

                    this.articleCounterCollection.insert(validArticleCounter)
                        .then(id => {
                            resolve(id);
                        })
                        .catch(e => {
                            reject(e);
                        })
                })
                .catch(e => {
                    reject(e);
                })
        });
    }

    update(articleCounter) {
        return new Promise((resolve, reject) => {
            this._validate(articleCounter)
                .then(validArticleCounter => {
                    this.articleCounterCollection.update(validArticleCounter)
                        .then(id => {
                            resolve(id);
                        })
                        .catch(e => {
                            reject(e);
                        })
                })
                .catch(e => {
                    reject(e);
                })
        });
    }

    delete(articleCounter) {
        return new Promise((resolve, reject) => {
            this._validate(articleCounter)
                .then(validArticleCounter => {
                    validArticleCounter._deleted = true;
                    this.articleCounterCollection.update(validArticleCounter)
                        .then(id => {
                            resolve(id);
                        })
                        .catch(e => {
                            reject(e);
                        })
                })
                .catch(e => {
                    reject(e);
                })
        });
    }

    _validate(articleCounter) {

        var errors = {};

        return new Promise((resolve, reject) => {
            var valid = new ArticleCounter(articleCounter);

            var getArticleCounter = this.articleCounterCollection.singleOrDefault({
                "$and": [{
                    _id: {
                        '$ne': valid._id
                    }
                }, {
                    code: valid.code
                }]
            });

            Promise.all([getArticleCounter])
                .then(results => {
                    var _articleCounter = results[0];

                    if (!valid.code || valid.code == '')
                        errors["code"] = "code is required";
                    else if (_articleCounter) {
                        errors["code"] = "code already exists";
                    }

                    if (!valid.name || valid.name == '')
                        errors["name"] = "name is required";

                    var itemErrors = [];
                    var itemHasError = false;
                    for (var item of valid.subCounters) {
                        var itemError = {};
                        for (var i = valid.subCounters.indexOf(item) + 1; i < valid.subCounters.length; i++) {
                            var otherItem = valid.subCounters[i];
                            if (!item.code || valid.code == '') {
                                itemError["code"] = "code is required";
                            }
                            else if (item.code == otherItem.code) {
                                itemError["code"] = "code already exists on another sub-counter";
                            }

                            if (!item.name || valid.name == '') {
                                itemError["name"] = "name is required";
                            }
                        }
                        itemErrors.push(itemError);
                    }

                    for (var itemError of itemErrors) {
                        for (var prop in itemError) {
                            errors.subCounters = itemErrors;
                            break;
                        }
                        if (errors.subCounters)
                            break;
                    }

                    for (var prop in errors) {
                        var ValidationError = require('../../validation-error');
                        reject(new ValidationError('data does not pass validation', errors));
                    }

                    valid.stamp(this.user.username, 'manager');
                    resolve(valid);
                })
                .catch(e => {
                    reject(e);
                })
        });
    }
};<|endoftext|>


<commit_before>loggingSettings = {
	"logDirectory" : "logs",
	"strategy" : "console",
	"APP_NAME" : "ast_parser",
	"disable": false // TODO: take from environment variable
};
// loggingSettings.level = 'info';

var fs = require("fs"),
	babelParser = require("babylon"),
	logger = require('./helpers/logger')(loggingSettings),
	path = require("path"),
	appDir = path.dirname(require.main.filename);

var outFile = "out/ast.txt"; //default out file

if(process.env.AST_PARSER_OUT_FILE) {
	outFile = process.env.AST_PARSER_OUT_FILE.trim();
	if(ensureDirectories(outFile)) {
		fs.writeFileSync(outFile, "");
		logger.info("+created ast output file: " + path.join(appDir, outFile));
	}
}

function ensureDirectories(filePath) {
	var parentDir = path.dirname(filePath);
	if(fs.existsSync(parentDir)) {
		return true;
	}

	ensureDirectories(parentDir);
	fs.mkdirSync(parentDir);
	return true;
}

var readFile = function (currentFilePath) {
	return new Promise(function (resolve, reject) {

		fs.readFile(currentFilePath, function (err, data) {

			if(err) {
				logger.warn("+DIDN'T get content of file!");
				return reject(err);
			}

			logger.info("+got content of file!");
			return resolve(data.toString());
		});
	});
}

var astFromFileContent = function (data, err) {
	return new Promise(function (resolve, reject) {

		if(err) {
			logger.warn("+DIDN'T parse ast from file!");
			return reject(err);
		}

		logger.info("+parsing ast from file!");
		var ast = babelParser.parse(data);
		// var ast = babelParser.parse("var = 4"); //try if error handling works ok
		return resolve(ast);
	});
};

var writeToFile = function(data, err) {
	return new Promise (function (resolve, reject) {
	 	fs.writeFile(outFile, JSON.stringify(data, null, 4), function (writeFileError) {

			if(err) {
				logger.warn("Error from writeToFile: " + err);
				return reject(err);
			}
			if(writeFileError) {
				logger.warn("Error writing file: " + writeFileError);
				return reject(writeFileError);
			}

			logger.info("+wrote to file: " + outFile);
			return resolve(data);
		});
	});
}

// TODO: implement and require from another file
var visitorsPackage = {
	"decoratorVisitor": function decoratorVisitor() {},
	"extendVisitor": function extendVisitor() {},
	"classVisitor": function classVisitor() {}
}

var visitAst = function (data, err) {
	return new Promise (function (resolve, reject) {
		if(err) {
			logger.warn("+DIDN'T visit ast!");
			return reject(err);
		}

		logger.info("+visiting ast with given visitor library!");

		// TODO: return visitor result and write to file
		var visitResult = visitWith(data, visitorsPackage);
		return resolve(visitResult);
	});
}

var visitWith = function(ast, visitorsForEs5) {
	logger.info("+visiting happens here");
}

var exceptionHandler = function (reason) {
	logger.error("Error: Exception Handler Caught: " + reason);
}

readFile("app/test.js").then(astFromFileContent)
						.then(writeToFile) //fluent api for debugging purposes
						.then(visitAst)
						.catch(exceptionHandler)<commit_msg>added env var for disabling logging<commit_after>var disableLogger = false;
if(process.env.AST_PARSER_DISABLE_LOGGING.trim() === "true") {
	disableLogger = true;
}

loggingSettings = {
	"logDirectory" : "logs",
	"strategy" : "console",
	"APP_NAME" : "ast_parser",
	"disable": disableLogger
};
// loggingSettings.level = 'info';

var fs = require("fs"),
	babelParser = require("babylon"),
	logger = require('./helpers/logger')(loggingSettings),
	path = require("path"),
	appDir = path.dirname(require.main.filename);

var outFile = "out/ast.txt"; //default out file

if(process.env.AST_PARSER_OUT_FILE) {
	outFile = process.env.AST_PARSER_OUT_FILE.trim();
	if(ensureDirectories(outFile)) {
		fs.writeFileSync(outFile, "");
		logger.info("+created ast output file: " + path.join(appDir, outFile));
	}
}

function ensureDirectories(filePath) {
	var parentDir = path.dirname(filePath);
	if(fs.existsSync(parentDir)) {
		return true;
	}

	ensureDirectories(parentDir);
	fs.mkdirSync(parentDir);
	return true;
}

var readFile = function (currentFilePath) {
	return new Promise(function (resolve, reject) {

		fs.readFile(currentFilePath, function (err, data) {

			if(err) {
				logger.warn("+DIDN'T get content of file!");
				return reject(err);
			}

			logger.info("+got content of file!");
			return resolve(data.toString());
		});
	});
}

var astFromFileContent = function (data, err) {
	return new Promise(function (resolve, reject) {

		if(err) {
			logger.warn("+DIDN'T parse ast from file!");
			return reject(err);
		}

		logger.info("+parsing ast from file!");
		var ast = babelParser.parse(data);
		// var ast = babelParser.parse("var = 4"); //try if error handling works ok
		return resolve(ast);
	});
};

var writeToFile = function(data, err) {
	return new Promise (function (resolve, reject) {
	 	fs.writeFile(outFile, JSON.stringify(data, null, 4), function (writeFileError) {

			if(err) {
				logger.warn("Error from writeToFile: " + err);
				return reject(err);
			}
			if(writeFileError) {
				logger.warn("Error writing file: " + writeFileError);
				return reject(writeFileError);
			}

			logger.info("+wrote to file: " + outFile);
			return resolve(data);
		});
	});
}

// TODO: implement and require from another file
var visitorsPackage = {
	"decoratorVisitor": function decoratorVisitor() {},
	"extendVisitor": function extendVisitor() {},
	"classVisitor": function classVisitor() {}
}

var visitAst = function (data, err) {
	return new Promise (function (resolve, reject) {
		if(err) {
			logger.warn("+DIDN'T visit ast!");
			return reject(err);
		}

		logger.info("+visiting ast with given visitor library!");

		// TODO: return visitor result and write to file
		var visitResult = visitWith(data, visitorsPackage);
		return resolve(visitResult);
	});
}

var visitWith = function(ast, visitorsForEs5) {
	logger.info("+visiting happens here");
}

var exceptionHandler = function (reason) {
	logger.error("Error: Exception Handler Caught: " + reason);
}

readFile("app/test.js").then(astFromFileContent)
						.then(writeToFile) //fluent api for debugging purposes
						.then(visitAst)
						.catch(exceptionHandler)<|endoftext|>


<commit_before>var Promise = require('bluebird');
var cloudinary = require('cloudinary');

// TODO: Add support for private_cdn
// TODO: Add support for secure_distribution
// TODO: Add support for cname
// TODO: Add support for cdn_subdomain
// http://cloudinary.com/documentation/node_additional_topics#configuration_options

function store(config) {
  this.config = config || {};
  cloudinary.config(config);
}

store.prototype.save = function(image) {
  var secure = this.config.secure || false;

  return new Promise(function(resolve) {
    cloudinary.uploader.upload(image.path, function(result) {
      resolve(secure ? result.secure_url : result.url);
    });
  });
};

store.prototype.serve = function() {
  return function (req, res, next) {
    next();
  };
};

module.exports = store;
<commit_msg>Added new code of module<commit_after>var Promise = require('bluebird');
var cloudinary = require('cloudinary');
var util = require('util');

var baseStore = require('ghost-storage-base');

// TODO: Add support for private_cdn
// TODO: Add support for secure_distribution
// TODO: Add support for cname
// TODO: Add support for cdn_subdomain
// http://cloudinary.com/documentation/node_additional_topics#configuration_options

function CloudinaryStore(config) {
    baseStore.call(this);
    this.config = config || {};
    cloudinary.config(config);
}

util.inherits(CloudinaryStore, baseStore);

CloudinaryStore.prototype.save = function(image) {
  var secure = this.config.secure || false;

  return new Promise(function(resolve) {
    cloudinary.uploader.upload(image.path, function(result) {
      resolve(secure ? result.secure_url : result.url);
    });
  });
};

CloudinaryStore.prototype.delete = function(image) {

  return new Promise(function(resolve) {
    cloudinary.uploader.destroy('zombie', function(result) {
      resolve(result)
    });
  });
};

CloudinaryStore.prototype.exists = function(filename) {
  return new Promise(function(resolve) {
    if (cloudinary.image(filename, { })) {
        resolve(true);
    } else {
        resolve(false);
    }
  });

}

CloudinaryStore.prototype.serve = function() {
  return function (req, res, next) {
    next();
  };
};

module.exports = CloudinaryStore;
<|endoftext|>


<commit_before>//some common java script functions which are used throughout the web site.
//note, these are for use on BOTH the PUBLIC and PRIVATE page.
//created by rjp, 1/2004.

// To be run at startup to enable the css drop downs
// See http://www.alistapart.com/articles/dropdowns/
// Attaches :hover function to LI class for IE 5.01+,
// normally IE doesn't support :hover property
// for things over than  tags
sfHover = function() {
    if (document.getElementById("dropDown")) {
        var sfEls1 = document.getElementById("dropDown").getElementsByTagName("TD");
        var sfEls2 = document.getElementById("dropDown").getElementsByTagName("LI");
        for (var i=0; i<sfEls1.length; i++) {
            sfEls1[i].onmouseover=function() {
                this.className+=" sfhover";
            }
            sfEls1[i].onmouseout=function() {
                this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
            }
        }
        for (var i=0; i<sfEls2.length; i++) {
            sfEls2[i].onmouseover=function() {
                this.className+=" sfhover";
            }
            sfEls2[i].onmouseout=function() {
                this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
            }
        }
    }
}
if (window.attachEvent) window.attachEvent("onload", sfHover);

// This is a handy little function for seeing what properties an object has
function showProperties ( obj ) {
    var result = "";

    for ( var i in obj ) {
        result += "obj." + i + " = " + obj[i] + "
\n";
    }
    document.write ( result );
}

function checkBrowserVersion() {
	var match = /Microsoft/i;

	if (match.test(navigator.appName)) {
		document.write("
Warning: Internet Explorer is not standards compliant and you should not use it on this web site or elsewhere.
 Aside from cosmetic defects in page rendering, error checking routines may not work correctly and you may be randomly logged out of the site.

 Please download and use Safari or Firefox, or read the web browser tip sheet for information on other free browsers.
");
	}
}

//
// for validation of form input
//

// returns true if the input is in a proper format for a last name
function properLastName(input) {
	if ((!input) || input == "") { return false; }
	var match = /^[A-Za-z,-.\'][A-Za-z ,-.\']*$/;
	return match.test(input);
}

// returns true if the input is in a proper format for an initial
function properInitial(input) {
	if ((!input) || input == "") { return false; }
	var match1 = /^[A-Z][A-Za-z .]*$/;
	var match2 = /[.]/;
	return (match1.test(input) && match2.test(input));
}

// returns true if it's a proper year format which begins with a 1 or 2,
// ie, 1900 and something or 2000 something.
function properYear(input) {
	if ((!input) || input == "") { return false; }
	var match = /^[12]\d{3}$/;
	return match.test(input);
}

//
// by rjp, 2/2004, modified by PS
function guessTaxonRank(taxon) {
    var isSpecies = /^[A-Z][a-z]+[ ][a-z]+\n?$/;
    var isSubspecies = /^[A-Z][a-z]+[ ][a-z]+[ ][a-z]+\n?$/;
    var isHigher = /^[A-Z][a-z]+\n?$/;

    //alert ("taxon = '" + taxon + "'");
    if (isSubspecies.test(taxon)) {
        return "subspecies";
    } else if (isSpecies.test(taxon)) {
        return "species";
    } else if (isHigher.test(taxon)) {
        return "higher";
    } else {
        return "invalid";
    }
}

// Error is a JavaScript class for error reporting..
// To use it, first create a new instance of the object, for example
// var err = new Error();  // you can optionally pass an error message in the constructor
// Then, call the add() method each time you want to add an error to it.
// err.add("my error message");
// When finished, you can print the alert by calling the showAlert method,
// or you can directly grab the string.
// err.showAlert();  //displays the alert message with the entire error
// alert(err);  // same thing

// constructor, optionally pass it the first error message.
//
// by rjp, 2/2004
function Error(msg) {
	this.starting = "\tPlease fix the following errors:\n\n";
	this.message = "";
	this.internalcount = 0;

	if (msg) {
		this.message = "* " + msg;
	}

	this.ending = "\n\nRefer to the tip sheet for instructions.";
}

// adds an error with a bullet point to the list of error messages
Error.prototype.add = function(msg) {
	this.message += "\n* " + msg;
	this.internalcount += 1;
}

Error.prototype.count = function() {
	return this.internalcount;
}

// displays an alert message with the error
Error.prototype.showAlert = function() {
	alert(this);
}

// converts the error object to a string.
Error.prototype.toString = function() {
	return this.starting + this.message + this.ending;
}

// pass this method another Error object, and it will append the
// new object onto the end of itself.
Error.prototype.appendErrors = function(newError) {
	this.message += newError.message;
	this.internalcount += newError.internalcount;
}

// End of error class.

//show a popup window with the passed URL.
function tipsPopup (URL,width,height) {
    var width  = (width == null) ? 640 : width;
    var height = (height== null) ? 480 : height;
	window.open(URL, 'tips', 'toolbar=1,scrollbars=1,location=1,statusbar=0,menubar=0,resizable=1,width='+width+',height='+height);
}

//show a popup window with the passed URL.
function imagePopup (URL,width,height) {
    var width  = (width == null) ? 800 : width;
    var height = (height== null) ? 600 : height;
	window.open(URL, 'imageview', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width='+width+',height='+height);
}

// Show a popup with a map in it.  this is kept distinct from the other two popups because if we include
// the full url in the javascript, search engines will still spider it, which is bad since the map
// generation is ultra heavyweight
function mapPopup(collection_no) {
    var link = 'bridge'+'.pl'+
               '?action=displayMapOfCollection'+
               '&display_header=NO'+
               '&collection_no='+collection_no;
    window.open(link,'mapview','toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=800,height=600');
}

//if java script is turned on, then this will
//print a hidden input field so we can check from the perl
//code and see that it was turned on.
function javascriptOnCheck() {
	document.writeln("<INPUT type=\"hidden\" name=\"javascripton\" value=\"yes\"></INPUT>");
}

//meant to fill the years in a pull down menu from 1998 to the current year.
//
// by rjp, 2/2004
function fillYears() {
	var yearField = document.forms[0].year
	var date = new Date();

	var maxYear = date.getFullYear();
	var year;

	for (year = maxYear; year >= 1998; year--) {
		document.writeln("<OPTION>" + year + "</OPTION>");
	}
}

function fillMonths() {
	document.write("<option value=12>December</option>");
	document.write("<option value=11>November</option>");
	document.write("<option value=10>October</option>");
	document.write("<option value=9>September</option>");
	document.write("<option value=8>August</option>");
	document.write("<option value=7>July</option>");
	document.write("<option value=6>June</option>");
	document.write("<option value=5>May</option>");
	document.write("<option value=4>April</option>");
	document.write("<option value=3>March</option>");
	document.write("<option value=2>February</option>");
	document.write("<option value=1>January</option>");
}

function fillDays() {
	var i;
	for (i = 31; i > 0; i--) {
		document.writeln("<OPTION>" + i + "</OPTION>");
	}
}

// Email addresses pass through a simple javascript, which most automated scripts won't execute
// before being displayed
function descram(part2r,part1r) {
    var em = "";
    for (i = 0; i <= part2r.length; i++) {
      em = part2r.charAt(i) + em;
    }
    em = "@" + em;
    for (i = 0; i <= part1r.length; i++) {
      em = part1r.charAt(i) + em;
    }
    document.write(em);
}

//pass this function a checkbox.
function checkAll(checkbox,the_class){
    var state = checkbox.checked;
    var frm = document.forms[0];
    for(var i=0; i < frm.elements.length; i++){
        if(frm.elements[i].className == the_class) {
            frm.elements[i].checked = state;
        }
    }
}

// used in the PAST module to hide or show lines of text that pop up next
//  to data points in plots on mouse over; assumes that the named elements
//  are single lines of text stacked on top of each other
function showHide(what)	{
        var elems = document.getElementsByName(what);
        for (var i=0,a; a=elems[i]; i++)	{
                if ( a.style.visibility != "hidden" )	{
                        a.style.visibility = "hidden";
                        a.style.height = "0em";
                } else	{
                        a.style.visibility = "visible";
                        a.style.height = "1.25em";
                }
        }
}

<commit_msg>moved form checking code here, delete some old Poling functions<commit_after>//some common java script functions which are used throughout the web site.
//note, these are for use on BOTH the PUBLIC and PRIVATE page.
//created by rjp, 1/2004.

// To be run at startup to enable the css drop downs
// See http://www.alistapart.com/articles/dropdowns/
// Attaches :hover function to LI class for IE 5.01+,
// normally IE doesn't support :hover property
// for things over than  tags
sfHover = function() {
    if (document.getElementById("dropDown")) {
        var sfEls1 = document.getElementById("dropDown").getElementsByTagName("TD");
        var sfEls2 = document.getElementById("dropDown").getElementsByTagName("LI");
        for (var i=0; i<sfEls1.length; i++) {
            sfEls1[i].onmouseover=function() {
                this.className+=" sfhover";
            }
            sfEls1[i].onmouseout=function() {
                this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
            }
        }
        for (var i=0; i<sfEls2.length; i++) {
            sfEls2[i].onmouseover=function() {
                this.className+=" sfhover";
            }
            sfEls2[i].onmouseout=function() {
                this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
            }
        }
    }
}
if (window.attachEvent) window.attachEvent("onload", sfHover);

// This is a handy little function for seeing what properties an object has
function showProperties ( obj ) {
    var result = "";

    for ( var i in obj ) {
        result += "obj." + i + " = " + obj[i] + "
\n";
    }
    document.write ( result );
}

function checkBrowserVersion() {
    var match = /Microsoft/i;

    if (match.test(navigator.appName)) {
        document.write("
Warning: Internet Explorer is not standards compliant and you should not use it on this web site or elsewhere.
 Aside from cosmetic defects in page rendering, error checking routines may not work correctly and you may be randomly logged out of the site.

 Please download and use Safari or Firefox, or read the web browser tip sheet for information on other free browsers.
");
    }
}

//
// for validation of form input
//

// returns true if the input is in a proper format for a last name
function properLastName(input) {
    if ((!input) || input == "") { return false; }
    var match = /^[A-Za-z,-.\'][A-Za-z ,-.\']*$/;
    return match.test(input);
}

// returns true if the input is in a proper format for an initial
function properInitial(input) {
    if ((!input) || input == "") { return false; }
    var match1 = /^[A-Z][A-Za-z .]*$/;
    var match2 = /[.]/;
    return (match1.test(input) && match2.test(input));
}

// returns true if it's a proper year format which begins with a 1 or 2,
// ie, 1900 and something or 2000 something.
function properYear(input) {
    if ((!input) || input == "") { return false; }
    var match = /^[12]\d{3}$/;
    return match.test(input);
}

//
// by rjp, 2/2004, modified by PS
function guessTaxonRank(taxon) {
    var isSpecies = /^[A-Z][a-z]+[ ][a-z]+\n?$/;
    var isSubspecies = /^[A-Z][a-z]+[ ][a-z]+[ ][a-z]+\n?$/;
    var isHigher = /^[A-Z][a-z]+\n?$/;

    //alert ("taxon = '" + taxon + "'");
    if (isSubspecies.test(taxon)) {
        return "subspecies";
    } else if (isSpecies.test(taxon)) {
        return "species";
    } else if (isHigher.test(taxon)) {
        return "higher";
    } else {
        return "invalid";
    }
}

// Error is a JavaScript class for error reporting..
// To use it, first create a new instance of the object, for example
// var err = new Error();  // you can optionally pass an error message in the constructor
// Then, call the add() method each time you want to add an error to it.
// err.add("my error message");
// When finished, you can print the alert by calling the showAlert method,
// or you can directly grab the string.
// err.showAlert();  //displays the alert message with the entire error
// alert(err);  // same thing

// constructor, optionally pass it the first error message.
//
// by rjp, 2/2004
function Error(msg) {
    this.starting = "\tPlease fix the following errors:\n\n";
    this.message = "";
    this.internalcount = 0;

    if (msg) {
        this.message = "* " + msg;
    }

    this.ending = "\n\nRefer to the tip sheet for instructions.";
}

// adds an error with a bullet point to the list of error messages
Error.prototype.add = function(msg) {
    this.message += "\n* " + msg;
    this.internalcount += 1;
}

Error.prototype.count = function() {
    return this.internalcount;
}

// displays an alert message with the error
Error.prototype.showAlert = function() {
    alert(this);
}

// converts the error object to a string.
Error.prototype.toString = function() {
    return this.starting + this.message + this.ending;
}

// pass this method another Error object, and it will append the
// new object onto the end of itself.
Error.prototype.appendErrors = function(newError) {
    this.message += newError.message;
    this.internalcount += newError.internalcount;
}

// End of error class.

//show a popup window with the passed URL.
function tipsPopup (URL,width,height) {
    var width  = (width == null) ? 640 : width;
    var height = (height== null) ? 480 : height;
    window.open(URL, 'tips', 'toolbar=1,scrollbars=1,location=1,statusbar=0,menubar=0,resizable=1,width='+width+',height='+height);
}

//show a popup window with the passed URL.
function imagePopup (URL,width,height) {
    var width  = (width == null) ? 800 : width;
    var height = (height== null) ? 600 : height;
    window.open(URL, 'imageview', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width='+width+',height='+height);
}

// Show a popup with a map in it.  this is kept distinct from the other two popups because if we include
// the full url in the javascript, search engines will still spider it, which is bad since the map
// generation is ultra heavyweight
function mapPopup(collection_no) {
    var link = 'bridge'+'.pl'+
               '?action=displayMapOfCollection'+
               '&display_header=NO'+
               '&collection_no='+collection_no;
    window.open(link,'mapview','toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=800,height=600');
}

//if java script is turned on, then this will
//print a hidden input field so we can check from the perl
//code and see that it was turned on.
function javascriptOnCheck() {
    document.writeln("<INPUT type=\"hidden\" name=\"javascripton\" value=\"yes\"></INPUT>");
}

// Email addresses pass through a simple javascript, which most automated scripts won't execute
// before being displayed
function descram(part2r,part1r) {
    var em = "";
    for (i = 0; i <= part2r.length; i++) {
      em = part2r.charAt(i) + em;
    }
    em = "@" + em;
    for (i = 0; i <= part1r.length; i++) {
      em = part1r.charAt(i) + em;
    }
    document.write(em);
}

//pass this function a checkbox.
function checkAll(checkbox,the_class){
    var state = checkbox.checked;
    var frm = document.forms[0];
    for(var i=0; i < frm.elements.length; i++){
        if(frm.elements[i].className == the_class) {
            frm.elements[i].checked = state;
        }
    }
}

// used in the PAST module to hide or show lines of text that pop up next
//  to data points in plots on mouse over; assumes that the named elements
//  are single lines of text stacked on top of each other
function showHide(what)    {
    var elems = document.getElementsByName(what);
    for (var i=0,a; a=elems[i]; i++)    {
        if ( a.style.visibility != "hidden" )    {
            a.style.visibility = "hidden";
            a.style.height = "0em";
        } else    {
            a.style.visibility = "visible";
            a.style.height = "1.25em";
        }
    }
}

function checkAllEmpty(frm,fields) {
    var element_count = 0;
    var empty_count = 0;
    for(i=0;i<frm.elements.length;i++) {
        var elem = frm.elements[i];
        for(j=0;j<fields.length;j++) {
            if (elem.name == fields[j]) {
                element_count++;
                if (elem.options) {
                    if (elem.selectedIndex == 0) empty_count++;
                } else {
                    if (elem.value == '') empty_count++;
                }
            }
        }
    }
    if (element_count == empty_count) {
        return true;
    } else {
        return false;
    }
}

<|endoftext|>


<commit_before>function initSpec(title, tests) {
  describe(title, () => {
    beforeEach(() => {
      cy.server();
      cy.route("/query/*").as("analysis-service")
    });
    tests.forEach(test => {
      describe(test.title, () => {
        test.specs.forEach(spec => {
          if (spec.only) {
            it.only(spec.description, () => {
              spec.test(test.mock);
            });
          } else {
            it(spec.description, () => {
              spec.test(test.mock);
            });
          }
        });
      });
    });
  });
}

export default (title, tests) => initSpec(title, tests);
<commit_msg>Update spec f<commit_after>function initSpec(title, testConfig) {
  describe(title, () => {
    beforeEach(() => {
      cy.server();
      cy.route('/query/*').as('analysis-service');
    });
    testConfig.forEach((testGroup) => {
      describe(testGroup.title, () => {
        const {spec} = testGroup;
        testGroup.tests.forEach((test) => {
          if (spec.only) {
            it.only(test.description, () => {
              spec.test(test);
            });
          } else {
            it(test.description, () => {
              spec.test(test);
            });
          }
        });
      });
    });
  });
}

export default (title, tests) => initSpec(title, tests);
<|endoftext|>