<commit_before>//based loosely on bostock's example and
//http://bl.ocks.org/d3noob/5141278

var nodes = data.nodes
var links = data.links
var count = 0
for (i in links) {
   if (count<links[i].value) count = links[i].value
}

var ele = document.getElementById("vis"),
    //width = ele.offsetWidth+1200
    //height = ele.offsetHeight+1200
    width = ele.clientWidth,
    height= ele.clientHeight;

var force = d3.layout.force()
    .charge([-250])
    .linkDistance([75])
    .size([width, height])
    .nodes(nodes)
    .links(links)
    .start();

var drag = force.drag();
drag.on("dragstart",dragstart);

var defaultColors = d3.scale.category20(); //10 or 20

var svg = d3.select("#vis").append("svg")
    .attr("width", "100%")
    .attr("height", "100%")
    .append("g")
	.call(d3.behavior.zoom().scaleExtent([0.5,5]).on("zoom",zoomHandler)).on("dblclick.zoom",null).on("mousedown.zoom",null);

var outer_box = svg.append("rect")
    .attr("width", "100%")
    .attr("height", "100%")
    .attr("x", 0)
    .attr("y", 0)
    .attr("id","outer_box")    //.attr("fill","none")
    	.attr("fill", "grey")
    	.attr("opacity", 0.1)
    .attr("pointer-events","all");

console.log(outer_box);

svg.append("svg:defs").selectAll("marker")
    .data(["end"])// Different path types defined here
    .enter().append("svg:marker")
    .attr("id", String)
    .attr("viewBox", "0 -5 10 10")
    .attr("refX", 15)
    .attr("refY", 0)
    .attr("markerUnits", "userSpaceOnUse")
    .style("fill", function (d) {
        return d.color || "black"
    })
    .style("opacity", function(d) {
        return d.opacity || 1
    })
    .attr("markerWidth", 10)
    .attr("markerHeight", 10)
    .attr("orient", "auto")
    .append("svg:path")
    .attr("d", "M0,-5L10,0L0,5");

var link = svg.append("svg:g").selectAll("path")
    .data(links)
    .enter().append("svg:path")
    .attr("class", "link")
    .attr("marker-end", "url(#end)")
    .style("stroke-width", function (d) {
        return d.width || "1.5"
    })
    .style("stroke", function (d) {
        return d.color || "black"
    })
    .style("opacity", function(d) {
        return d.opacity || 1
    })
    .style("stroke-dasharray", function(d) {
        return d.dasharray || ""
    })
    .style("fill", "none")

//scale values between 1 and 100 to a reasonable range
var scaleSize = d3.scale.linear()
    .domain([1,100])
    .range([80,4000]);

//outer node
var node = svg.selectAll(".node")
    .data(nodes)
    .enter().append("g")
    .on("mouseover", mouseover)
    .on("mouseout", mouseout)
    .on("dblclick", dblclick)
    .call(force.drag)

//inner nodes
node
    .append('path')
    .attr("class", "node")
    .attr("d", d3.svg.symbol()
        .type(function(d) { return d.shape || "circle"; })
        .size(function(d) {return scaleSize(d.size || 1); })
    )
    .style("fill", function(d, i) {
        return d.color || defaultColors(i);
    })
    .style("opacity", function(d) {
        return d.opacity || 1
    })

//inner nodes
node
    .append("text")
    .attr("x", 12)
    .attr("dy", ".35em")
    .style("color",'black')
    .style("display", "none")
    .text(function(d) {
        return d.name;
    });

// Function to add line breaks to node labels/names
var insertLineBreaks = function(d) {
	var el = d3.select(this);
	var words = d3.select(this).text().split('\n');
	el.text('');

	for (var i = 0; i < words.length; i++) {
	    var tspan = el.append('tspan').text(words[i]);
	    if (i > 0)
		tspan.attr('x',0).attr('dy','15');
	}
}

// Add line breaks to node labels
svg.selectAll('text').each(insertLineBreaks);

force.on("tick", function() {
    link
        .attr("d", function(d) {
            var dx = d.target.x - d.source.x,
                dy = d.target.y - d.source.y,
                dr = Math.sqrt(dx * dx + dy * dy);
            return "M" +
                d.source.x + "," +
                d.source.y + "A" +
                dr + "," + dr + " 0 0,1 " +
                d.target.x + "," +
                d.target.y;
        });

    node
        .attr("transform", function(d) {
            return "translate(" + d.x + "," + d.y + ")";
        });
})

function mouseover() {

    d3.select(this).select("text").transition()
        .duration(750)
        .style("display","block")
    d3.select(this).select("path").transition()
        .duration(750)
        .attr('d', function (d) {
            return d3.svg.symbol().type(d.shape||"circle")
                    .size(scaleSize(40))()
        })
}

function mouseout() {

    d3.select(this).select("text").transition()
        .duration(750)
        .style("display","none")
    d3.select(this).select("path").transition()
        .duration(750)
        .attr('d', function (d) {
            return d3.svg.symbol().type(d.shape||"circle")
                    .size(scaleSize(d.size||1))()
        })

}

// zoom function
function zoomHandler() {
    svg.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
    var w = svg.style("width");
    d3.select("#outer_box").attr("width",w)
    .attr("height",height);//outter_box.attr("width","100%");
}

// Handle doubleclick on node path (shape)
function dblclick(d) {
    //console.log(this, d);
    d3.select(this).classed("fixed", d.fixed = false);
    //d3.select(this).attr("d", d3.svg.symbol()
	//		.type(function(d) { return d.shape || "circle"; })
	//		.size(function(d) { return scaleSize(d.size * 2 || 2); })
	//);
}

// Handle dragstart on force.drag()
function dragstart(d) {
    //console.log(this, d);
    d3.select(this).classed("fixed", d.fixed = true);
    //d3.select(this).attr("d", d3.svg.symbol()
		//.type(function(d) { return d.shape || "circle"; })
		//.size(function(d) { return scaleSize(d.size || 1); })
	//);
}

<commit_msg>fixed a semicolon<commit_after>//based loosely on bostock's example and
//http://bl.ocks.org/d3noob/5141278

var nodes = data.nodes
var links = data.links
var count = 0
for (i in links) {
   if (count<links[i].value) count = links[i].value
}

var ele = document.getElementById("vis"),
    //width = ele.offsetWidth+1200
    //height = ele.offsetHeight+1200
    width = ele.clientWidth,
    height= ele.clientHeight;

var force = d3.layout.force()
    .charge([-250])
    .linkDistance([75])
    .size([width, height])
    .nodes(nodes)
    .links(links)
    .start();

var drag = force.drag();
drag.on("dragstart",dragstart);

var defaultColors = d3.scale.category20(); //10 or 20

var svg = d3.select("#vis").append("svg")
    .attr("width", "100%")
    .attr("height", "100%")
    .append("g")
	.call(d3.behavior.zoom().scaleExtent([0.5,5]).on("zoom",zoomHandler)).on("dblclick.zoom",null).on("mousedown.zoom",null);

var outer_box = svg.append("rect")
    .attr("width", "100%")
    .attr("height", "100%")
    .attr("x", 0)
    .attr("y", 0)
    .attr("id","outer_box")    //.attr("fill","none")
    	.attr("fill", "grey")
    	.attr("opacity", 0.1)
    .attr("pointer-events","all");

console.log(outer_box);

svg.append("svg:defs").selectAll("marker")
    .data(["end"])// Different path types defined here
    .enter().append("svg:marker")
    .attr("id", String)
    .attr("viewBox", "0 -5 10 10")
    .attr("refX", 15)
    .attr("refY", 0)
    .attr("markerUnits", "userSpaceOnUse")
    .style("fill", function (d) {
        return d.color || "black"
    })
    .style("opacity", function(d) {
        return d.opacity || 1
    })
    .attr("markerWidth", 10)
    .attr("markerHeight", 10)
    .attr("orient", "auto")
    .append("svg:path")
    .attr("d", "M0,-5L10,0L0,5");

var link = svg.append("svg:g").selectAll("path")
    .data(links)
    .enter().append("svg:path")
    .attr("class", "link")
    .attr("marker-end", "url(#end)")
    .style("stroke-width", function (d) {
        return d.width || "1.5"
    })
    .style("stroke", function (d) {
        return d.color || "black"
    })
    .style("opacity", function(d) {
        return d.opacity || 1
    })
    .style("stroke-dasharray", function(d) {
        return d.dasharray || ""
    })
    .style("fill", "none")

//scale values between 1 and 100 to a reasonable range
var scaleSize = d3.scale.linear()
    .domain([1,100])
    .range([80,4000]);

//outer node
var node = svg.selectAll(".node")
    .data(nodes)
    .enter().append("g")
    .on("mouseover", mouseover)
    .on("mouseout", mouseout)
    .on("dblclick", dblclick)
    .call(force.drag)

//inner nodes
node
    .append('path')
    .attr("class", "node")
    .attr("d", d3.svg.symbol()
        .type(function(d) { return d.shape || "circle"; })
        .size(function(d) {return scaleSize(d.size || 1); })
    )
    .style("fill", function(d, i) {
        return d.color || defaultColors(i);
    })
    .style("opacity", function(d) {
        return d.opacity || 1
    })

//inner nodes
node
    .append("text")
    .attr("x", 12)
    .attr("dy", ".35em")
    .style("color",'black')
    .style("display", "none")
    .text(function(d) {
        return d.name;
    });

// Function to add line breaks to node labels/names
var insertLineBreaks = function(d) {
	var el = d3.select(this);
	var words = d3.select(this).text().split('\n');
	el.text('');

	for (var i = 0; i < words.length; i++) {
	    var tspan = el.append('tspan').text(words[i]);
	    if (i > 0)
		tspan.attr('x',0).attr('dy','15');
	}
}

// Add line breaks to node labels
svg.selectAll('text').each(insertLineBreaks);

force.on("tick", function() {
    link
        .attr("d", function(d) {
            var dx = d.target.x - d.source.x,
                dy = d.target.y - d.source.y,
                dr = Math.sqrt(dx * dx + dy * dy);
            return "M" +
                d.source.x + "," +
                d.source.y + "A" +
                dr + "," + dr + " 0 0,1 " +
                d.target.x + "," +
                d.target.y;
        });

    node
        .attr("transform", function(d) {
            return "translate(" + d.x + "," + d.y + ")";
        });
})

function mouseover() {

    d3.select(this).select("text").transition()
        .duration(750)
        .style("display","block")
    d3.select(this).select("path").transition()
        .duration(750)
        .attr('d', function (d) {
            return d3.svg.symbol().type(d.shape||"circle")
                    .size(scaleSize(40))()
        })
}

function mouseout() {

    d3.select(this).select("text").transition()
        .duration(750)
        .style("display","none")
    d3.select(this).select("path").transition()
        .duration(750)
        .attr('d', function (d) {
            return d3.svg.symbol().type(d.shape||"circle")
                    .size(scaleSize(d.size||1))()
        })

}

// zoom function
function zoomHandler() {
    svg.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
    //var w = svg.style("width");
    //d3.select("#outer_box").attr("width",w)
    //.attr("height",height);//outter_box.attr("width","100%");
}

// Handle doubleclick on node path (shape)
function dblclick(d) {
    //console.log(this, d);
    d3.select(this).classed("fixed", d.fixed = false);
    //d3.select(this).attr("d", d3.svg.symbol()
	//		.type(function(d) { return d.shape || "circle"; })
	//		.size(function(d) { return scaleSize(d.size * 2 || 2); })
	//);
}

// Handle dragstart on force.drag()
function dragstart(d) {
    //console.log(this, d);
    d3.select(this).classed("fixed", d.fixed = true);
    //d3.select(this).attr("d", d3.svg.symbol()
		//.type(function(d) { return d.shape || "circle"; })
		//.size(function(d) { return scaleSize(d.size || 1); })
	//);
}

<|endoftext|>


<commit_before>var graphs = []

function draw_graph(e, dataset) {
	var w = parseInt(d3.select(e).style('width'), 10);
	var h = 70;
	var padding = 22;

	var scaleY = d3.scale.linear()
		.domain([0, d3.max(dataset)])
		.range([0, h-padding]);

	var scaleX = d3.scale.linear()
		.domain([48, 0]).range([padding/2, w-(padding)]);

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

	var axis = d3.svg
		.axis()
		.scale(scaleX);

	var axisY = d3.svg
		.axis()
		.scale(d3.scale.linear().domain([0, d3.max(dataset)]).range([h, 0]))
		.ticks(3)
		.orient("left");

	var tip = d3.tip()
		.attr('class', 'd3-tip')
		.offset([-10,0])
		.html(function(d) { return d; });

	svg.call(tip);

	svg.append("g")
		.attr("class", "axis")
		.attr("transform", "translate(20," + (h-padding) + ")")
		.call(axis);

	svg.append("g")
		.attr("class", "axis")
		.attr("transform", "translate(31, -" + padding + ")")
		.call(axisY);

	svg.selectAll("rect")
		.data(dataset)
		.enter()
		.append("rect")
		.attr("x", function(d, i) {
			return w-scaleX(i);
		})
		.attr("y", h - padding - 2)
		.attr("width", w / dataset.length - 2)
		.attr("height", 0)
		.on('mouseover', tip.show)
		.on('mouseout', tip.hide);

	svg.selectAll("rect")
		.transition()
		.delay(function(d, i) {
			return (dataset.length - i) * 20;
		})
		.duration(500)
		.attr("y", function(d) { return (h - padding)-scaleY(d) - 2; })
		.attr("height", function(d) {
			return scaleY(d);
		});

}

function draw_graphs() {
	for (var i=0; i<graphs.length; i++) {
		draw_graph(graphs[i].e, graphs[i].dataset);
	}
}

d3.select(window).on('resize', draw_graphs);
<commit_msg>Change bar chart labels<commit_after>var graphs = []

function draw_graph(e, dataset) {
	var w = parseInt(d3.select(e).style('width'), 10);
	var h = 70;
	var padding = 22;

	var scaleY = d3.scale.linear()
		.domain([0, d3.max(dataset)])
		.range([0, h-padding]);

	var scaleX = d3.scale.linear()
		.domain([48, 0]).range([padding/2, w-(padding)]);

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

	var axis = d3.svg
		.axis()
		.tickFormat(function(d){ return d + "h ago"; })
		.scale(scaleX);

	var axisY = d3.svg
		.axis()
		.scale(d3.scale.linear().domain([0, d3.max(dataset)]).range([h, 0]))
		.ticks(3)
		.orient("left");

	var tip = d3.tip()
		.attr('class', 'd3-tip')
		.offset([-10,0])
		.html(function(d) { return d; });

	svg.call(tip);

	svg.append("g")
		.attr("class", "axis")
		.attr("transform", "translate(20," + (h-padding) + ")")
		.call(axis);

	svg.append("g")
		.attr("class", "axis")
		.attr("transform", "translate(31, -" + padding + ")")
		.call(axisY);

	svg.selectAll("rect")
		.data(dataset)
		.enter()
		.append("rect")
		.attr("x", function(d, i) {
			return w-scaleX(i);
		})
		.attr("y", h - padding - 2)
		.attr("width", w / dataset.length - 2)
		.attr("height", 0)
		.on('mouseover', tip.show)
		.on('mouseout', tip.hide);

	svg.selectAll("rect")
		.transition()
		.delay(function(d, i) {
			return (dataset.length - i) * 20;
		})
		.duration(500)
		.attr("y", function(d) { return (h - padding)-scaleY(d) - 2; })
		.attr("height", function(d) {
			return scaleY(d);
		});

}

function draw_graphs() {
	for (var i=0; i<graphs.length; i++) {
		draw_graph(graphs[i].e, graphs[i].dataset);
	}
}

d3.select(window).on('resize', draw_graphs);
<|endoftext|>


<commit_before>/*
Copyright (c) 2014, EDINA.
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this
   list of conditions and the following disclaimer in the documentation and/or
   other materials provided with the distribution.
3. All advertising materials mentioning features or use of this software must
   display the following acknowledgement: This product includes software
   developed by the EDINA.
4. Neither the name of the EDINA nor the names of its contributors may be used to
   endorse or promote products derived from this software without specific prior
   written permission.

THIS SOFTWARE IS PROVIDED BY EDINA ''AS IS'' AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
SHALL EDINA BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
DAMAGE.
*/

"use strict";

$(function() {
    if(window.location.href.substr(0, 4) === 'http'){
        onDeviceReady();
    }
    else{
        document.addEventListener("deviceready", onDeviceReady, false);
    }
});

function onDeviceReady(){
    // set up requirejs config
    require.config({
        paths: {
            "plugins": "../plugins",
            "templates": "../templates",
            "theme": "../theme",
            "proj4js": "ext/proj4js",
            "underscore": "ext/underscore",
            "text": "ext/requirejs-text",
            'QUnit': 'ext/qunit'
        },
        shim: {
            "proj4js":{
                exports: "Proj4js"
            },
            "underscore": {
                exports: "_"
            },
            'QUnit': {
                exports: 'QUnit',
                init: function() {
                    QUnit.config.autoload = false;
                    QUnit.config.autostart = false;
                }
            }
        }
    });

    require(['ui', 'map'], function(ui, map) {
        map.init();

        // called when all plugins are finished loading
        var pluginsComplete = function(){
            // when all plugins are finished loading finialise map
            map.postInit();

            // initialise home page first time
            ui.pageChange();
            ui.homePage();
        };

        // set up fieldtrip plugins
        $.getJSON('theme/project.json', function(f){
            var fieldtrip = f.plugins.fieldtrip;
            var noOfPlugins = Object.keys(fieldtrip).length;

            if(noOfPlugins > 0){
                var loaded = 0;
                $.each(fieldtrip, function(name){
                    require(["plugins/" + name + "/js/" + name], function(){
                        console.debug(name + " loaded");
                        ++loaded;

                        if(loaded === noOfPlugins){
                            pluginsComplete();
                        }
                    });
                });
            }
            else{
                pluginsComplete();
            }
        });

        $.getJSON('theme/menu-ids.json', function(ids){
            ui.toggleActiveInit(ids);
        });

        $(document).on('pageinit', 'div[data-role="page"]', function(event){
            // no use for this yet
        });
        $(document).on('pagebeforeshow', 'div[data-role="page"]', function(event){
            // no use for this yet
        });
        $(document).on('pageshow', 'div[data-role="page"]', function(event){
            ui.pageChange();
        });

        $(document).on('pageinit', '#map-page', function(){
            // map page is special case, need to setup up openlayers before onshow
            ui.mapPageInit();
        });

        var onShows = {
            'home-page': ui.homePage,
            'map-page': ui.mapPage,
            'capture-page': ui.capturePage,
            'annotate-page': ui.annotatePage,
            'annotate-preview-page': ui.annotatePreviewPage,
            'saved-records-page': ui.savedRecordsPage,
            'test-page': ui.testPage,
        };

        $.each(onShows, function(id, func){
            $(document).on('pageshow',
                           '#' + id,
                           $.proxy(func, ui));
        });
    });
};
<commit_msg>fix jshint errors<commit_after>/*
Copyright (c) 2014, EDINA.
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this
   list of conditions and the following disclaimer in the documentation and/or
   other materials provided with the distribution.
3. All advertising materials mentioning features or use of this software must
   display the following acknowledgement: This product includes software
   developed by the EDINA.
4. Neither the name of the EDINA nor the names of its contributors may be used to
   endorse or promote products derived from this software without specific prior
   written permission.

THIS SOFTWARE IS PROVIDED BY EDINA ''AS IS'' AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
SHALL EDINA BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
DAMAGE.
*/

"use strict";

$(function() {
    if(window.location.href.substr(0, 4) === 'http'){
        onDeviceReady();
    }
    else{
        document.addEventListener("deviceready", onDeviceReady, false);
    }
});

function onDeviceReady(){
    // set up requirejs config
    require.config({
        paths: {
            "plugins": "../plugins",
            "templates": "../templates",
            "theme": "../theme",
            "proj4js": "ext/proj4js",
            "underscore": "ext/underscore",
            "text": "ext/requirejs-text",
            'QUnit': 'ext/qunit'
        },
        shim: {
            "proj4js":{
                exports: "Proj4js"
            },
            "underscore": {
                exports: "_"
            },
            'QUnit': {
                exports: 'QUnit',
                init: function() {
                    QUnit.config.autoload = false;
                    QUnit.config.autostart = false;
                }
            }
        }
    });

    require(['ui', 'map'], function(ui, map) {
        map.init();

        // called when all plugins are finished loading
        var pluginsComplete = function(){
            // when all plugins are finished loading finialise map
            map.postInit();

            // initialise home page first time
            ui.pageChange();
            ui.homePage();
        };

        // set up fieldtrip plugins
        $.getJSON('theme/project.json', function(f){
            var fieldtrip = f.plugins.fieldtrip;
            var noOfPlugins = Object.keys(fieldtrip).length;

            if(noOfPlugins > 0){
                var loaded = 0;
                $.each(fieldtrip, function(name){
                    require(["plugins/" + name + "/js/" + name], function(){
                        console.debug(name + " loaded");
                        ++loaded;

                        if(loaded === noOfPlugins){
                            pluginsComplete();
                        }
                    });
                });
            }
            else{
                pluginsComplete();
            }
        });

        $.getJSON('theme/menu-ids.json', function(ids){
            ui.toggleActiveInit(ids);
        });

        $(document).on('pageinit', 'div[data-role="page"]', function(event){
            // no use for this yet
        });
        $(document).on('pagebeforeshow', 'div[data-role="page"]', function(event){
            // no use for this yet
        });
        $(document).on('pageshow', 'div[data-role="page"]', function(event){
            ui.pageChange();
        });

        $(document).on('pageinit', '#map-page', function(){
            // map page is special case, need to setup up openlayers before onshow
            ui.mapPageInit();
        });

        var onShows = {
            'home-page': ui.homePage,
            'map-page': ui.mapPage,
            'capture-page': ui.capturePage,
            'annotate-page': ui.annotatePage,
            'annotate-preview-page': ui.annotatePreviewPage,
            'saved-records-page': ui.savedRecordsPage,
            'test-page': ui.testPage,
        };

        $.each(onShows, function(id, func){
            $(document).on('pageshow',
                           '#' + id,
                           $.proxy(func, ui));
        });
    });
};
<|endoftext|>


<commit_before>module.exports = function mountLoopBackExplorer(server) {
  var explorer;
  try {
    explorer = require('loopback-explorer');
  } catch(err) {
    // Print the message only when the app was started via `server.listen()`.
    // Do not print any message when the project is used as a component.
    server.once('started', function(baseUrl) {
      console.log(
        'Run `npm install loopback-explorer` to enable the LoopBack explorer'
      );
    });
    return;
  }

  var restApiRoot = server.get('restApiRoot');

  var explorerApp = explorer(server, { basePath: restApiRoot });
  server.use('/explorer', explorerApp);
  server.once('started', function() {
    var baseUrl = server.get('url').replace(/\/$/, '');
    // express 4.x (loopback 2.x) uses `mountpath`
    // express 3.x (loopback 1.x) uses `route`
    var explorerPath = explorerApp.mountpath || explorerApp.route;
    console.log('Browse your REST API at %s%s', baseUrl, explorerPath);
  });
};
<commit_msg>disable explorer with code<commit_after>module.exports = function mountLoopBackExplorer(server) {
  var explorer;
  try {
    explorer = require('loopback-explorer');
  } catch(err) {
    // Print the message only when the app was started via `server.listen()`.
    // Do not print any message when the project is used as a component.
    server.once('started', function(baseUrl) {
      console.log(
        'Run `npm install loopback-explorer` to enable the LoopBack explorer'
      );
    });
    return;
  }

  var restApiRoot = server.get('restApiRoot');

  var explorerApp = explorer(server, { basePath: restApiRoot });
  if (process.env.NODE_ENV !== 'production') {
    server.use('/explorer', explorerApp);
  }
  server.once('started', function() {
    var baseUrl = server.get('url').replace(/\/$/, '');
    // express 4.x (loopback 2.x) uses `mountpath`
    // express 3.x (loopback 1.x) uses `route`
    var explorerPath = explorerApp.mountpath || explorerApp.route;
    console.log('Browse your REST API at %s%s', baseUrl, explorerPath);
  });
};
<|endoftext|>


<commit_before>
describe('Function', function() {
    "use strict";
    describe('bind', function() {
        var actual, expected,
            testSubject;

        testSubject = {
            push: function(o) {
                this.a.push(o);
            }
        };

        function func() {
            Array.prototype.forEach.call(arguments, function(a) {
                this.push(a);
            }, this);
            return this;
        };

        beforeEach(function() {
            actual = [];
            testSubject.a = [];
        });

        it('binds properly without a context', function() {
            var context;
            testSubject.func = function() {
                context = this;
            }.bind();
            testSubject.func();
            expect(context).toBe(function() {return this}.call());
        });
        it('binds properly without a context, and still supplies bound arguments', function() {
            var a, context;
            testSubject.func = function() {
                a = Array.prototype.slice.call(arguments);
                context = this;
            }.bind(undefined, 1,2,3);
            testSubject.func(1,2,3);
            expect(a).toEqual([1,2,3,1,2,3]);
            expect(context).toBe(function() {return this}.call());
        });
        it('binds a context properly', function() {
            testSubject.func = func.bind(actual);
            testSubject.func(1,2,3);
            expect(actual).toEqual([1,2,3]);
            expect(testSubject.a).toEqual([]);
        });
        it('binds a context and supplies bound arguments', function() {
            testSubject.func = func.bind(actual, 1,2,3);
            testSubject.func(4,5,6);
            expect(actual).toEqual([1,2,3,4,5,6]);
            expect(testSubject.a).toEqual([]);
        });

        it('returns properly without binding a context', function() {
            testSubject.func = function() {
                return this;
            }.bind();
            var context = testSubject.func();
            expect(context).toBe(function() {return this}.call());
        });
        it('returns properly without binding a context, and still supplies bound arguments', function() {
            var context;
            testSubject.func = function() {
                context = this;
                return Array.prototype.slice.call(arguments);
            }.bind(undefined, 1,2,3);
            actual = testSubject.func(1,2,3);
            expect(context).toBe(function() {return this}.call());
            expect(actual).toEqual([1,2,3,1,2,3]);
        });
        it('returns properly while binding a context properly', function() {
            var ret;
            testSubject.func = func.bind(actual);
            ret = testSubject.func(1,2,3);
            expect(ret).toBe(actual);
            expect(ret).not.toBe(testSubject);
        });
        it('returns properly while binding a context and supplies bound arguments', function() {
            var ret;
            testSubject.func = func.bind(actual, 1,2,3);
            ret = testSubject.func(4,5,6);
            expect(ret).toBe(actual);
            expect(ret).not.toBe(testSubject);
        });
        it('passes the correct arguments as a constructor', function() {
            var ret, expected = { name: "Correct" };
            testSubject.func = function(arg) {
                return arg;
            }.bind({ name: "Incorrect" });
            ret = new testSubject.func(expected);
            expect(ret).toBe(expected);
        });
        it('returns the return value of the bound function when called as a constructor', function () {
            var oracle = [1, 2, 3];
            var subject = function () {
                return oracle;
            }.bind(null);
            var result = new subject;
            expect(result).toBe(oracle);
        });
        it('returns the correct value if constructor returns primitive', function() {
            var oracle = [1, 2, 3];
            var subject = function () {
                return oracle;
            }.bind(null);
            var result = new subject;
            expect(result).toBe(oracle);

            oracle = {};
            result = new subject;
            expect(result).toBe(oracle);

            oracle = function(){};
            result = new subject;
            expect(result).toBe(oracle);

            oracle = "asdf";
            result = new subject;
            expect(result).not.toBe(oracle);

            oracle = null;
            result = new subject;
            expect(result).not.toBe(oracle);

            oracle = true;
            result = new subject;
            expect(result).not.toBe(oracle);

            oracle = 1;
            result = new subject;
            expect(result).not.toBe(oracle);
        });
    });
});
<commit_msg>+ add <Function>.bind test when called as a constructor with check returned value is instance of bound method<commit_after>
describe('Function', function() {
    "use strict";
    describe('bind', function() {
        var actual, expected,
            testSubject;

        testSubject = {
            push: function(o) {
                this.a.push(o);
            }
        };

        function func() {
            Array.prototype.forEach.call(arguments, function(a) {
                this.push(a);
            }, this);
            return this;
        };

        beforeEach(function() {
            actual = [];
            testSubject.a = [];
        });

        it('binds properly without a context', function() {
            var context;
            testSubject.func = function() {
                context = this;
            }.bind();
            testSubject.func();
            expect(context).toBe(function() {return this}.call());
        });
        it('binds properly without a context, and still supplies bound arguments', function() {
            var a, context;
            testSubject.func = function() {
                a = Array.prototype.slice.call(arguments);
                context = this;
            }.bind(undefined, 1,2,3);
            testSubject.func(1,2,3);
            expect(a).toEqual([1,2,3,1,2,3]);
            expect(context).toBe(function() {return this}.call());
        });
        it('binds a context properly', function() {
            testSubject.func = func.bind(actual);
            testSubject.func(1,2,3);
            expect(actual).toEqual([1,2,3]);
            expect(testSubject.a).toEqual([]);
        });
        it('binds a context and supplies bound arguments', function() {
            testSubject.func = func.bind(actual, 1,2,3);
            testSubject.func(4,5,6);
            expect(actual).toEqual([1,2,3,4,5,6]);
            expect(testSubject.a).toEqual([]);
        });

        it('returns properly without binding a context', function() {
            testSubject.func = function() {
                return this;
            }.bind();
            var context = testSubject.func();
            expect(context).toBe(function() {return this}.call());
        });
        it('returns properly without binding a context, and still supplies bound arguments', function() {
            var context;
            testSubject.func = function() {
                context = this;
                return Array.prototype.slice.call(arguments);
            }.bind(undefined, 1,2,3);
            actual = testSubject.func(1,2,3);
            expect(context).toBe(function() {return this}.call());
            expect(actual).toEqual([1,2,3,1,2,3]);
        });
        it('returns properly while binding a context properly', function() {
            var ret;
            testSubject.func = func.bind(actual);
            ret = testSubject.func(1,2,3);
            expect(ret).toBe(actual);
            expect(ret).not.toBe(testSubject);
        });
        it('returns properly while binding a context and supplies bound arguments', function() {
            var ret;
            testSubject.func = func.bind(actual, 1,2,3);
            ret = testSubject.func(4,5,6);
            expect(ret).toBe(actual);
            expect(ret).not.toBe(testSubject);
        });
        it('passes the correct arguments as a constructor', function() {
            var ret, expected = { name: "Correct" };
            testSubject.func = function(arg) {
                return arg;
            }.bind({ name: "Incorrect" });
            ret = new testSubject.func(expected);
            expect(ret).toBe(expected);
        });
        it('returns the return value of the bound function when called as a constructor', function () {
            var oracle = [1, 2, 3];
            var subject = function () {
                return oracle;
            }.bind(null);
            var result = new subject;
            expect(result).toBe(oracle);
        });
        it('returns the correct value if constructor returns primitive', function() {
            var oracle = [1, 2, 3];
            var subject = function () {
                return oracle;
            }.bind(null);
            var result = new subject;
            expect(result).toBe(oracle);

            oracle = {};
            result = new subject;
            expect(result).toBe(oracle);

            oracle = function(){};
            result = new subject;
            expect(result).toBe(oracle);

            oracle = "asdf";
            result = new subject;
            expect(result).not.toBe(oracle);

            oracle = null;
            result = new subject;
            expect(result).not.toBe(oracle);

            oracle = true;
            result = new subject;
            expect(result).not.toBe(oracle);

            oracle = 1;
            result = new subject;
            expect(result).not.toBe(oracle);
        });
        it('returns the value that instance of original "class" when called as a constructor', function() {
            var classA = function(x) {
				this.name = x || "A";
			}
			var classB = classA.bind(null, "B");

            var result = new classB;
            expect(result instanceof classA).toBe(true);
			expect(result instanceof classB).toBe(true);
        });
    });
});
<|endoftext|>


<commit_before>$(function() {
  var reservations;
  var resources;
  function renderGraph() {
    if(!(reservations && resources))
      return;

    // Sort the rooms alphabetically
    resources = resources.sort(function(a, b) {
      var keyA = a.name.toLowerCase(),
          keyB = b.name.toLowerCase();
      if(keyA < keyB) return -1;
      if(keyA > keyB) return 1;
      return 0;
    });

    // Set up the reservation list
    var start = 28800 ; // 8:00 AM
    var end = 72000; // 7:00 PM

    // Convert start / end times to seconds in the day
    reservations = reservations.map(function(r) {
      var from = new Date(r.from);
      var to = new Date(r.to);

      r.from = from.getSeconds() + (60 * from.getMinutes()) + (60 * 60 * from.getHours());
      r.to = to.getSeconds() + (60 * to.getMinutes()) + (60 * 60 * to.getHours());
      return r;
    });

    // Set scales
    var xscale = d3.scale.linear()
      .domain([start, end])
      .range([0, 100]);

    // Generate the x axis
    var hours = [];
    for(var x = start; x < end; x += 3600) {
      var hour = (Math.floor(x/3600) - 1) % 12 + 1;
      var minute = (x % 3600);
      hours.push(hour + ":" + ((minute < 10)?"0":"") + minute);
    }

    // Render the x axis.
    var xaxis = d3.select("#x-axis").selectAll("div")
      .data(hours)
      .enter()
      .append("div")
      .attr("class", function(d, i) {
        return "time " + ((i%2 == 0)?"even": "odd") + ((i == hours.length - 1)?" last":"");
      })
      .style("width", (99 / hours.length) + "%")
      .append("div")
      .text(function(d) {
        return d;
      })
      .attr("class", "time-label");

    // Set the height of the reservations
    console.log($(window).height());
    $("#reservations").height($(window).height() - 170 - 60); // 170 is header height, 60 is footer padding

    // Render the rooms.
    var timeline = d3.select("#reservations");

    // Create one row per entry
    var rows = timeline.selectAll("div")
      .data(resources)
      .enter()
      .append("div")
      .attr("class","row")
      .style("height", (100/resources.length)  + "%")

    // Add the label
    rows.append("div")
      .attr("class", "resource")
      .append("div")
      .attr("class", "resource-label")
      .text(function(d) {
        return d.name;
      })

    // Add the reservations
    rows.each(function(resource) {
      var row = d3.select(this);
      var filtered = reservations.filter(function(d) {
        return d.resource.id == resource.id && d.from < (end - 60 * 60);
      });
      row.append("div")
        .attr("class","timeline")
        .selectAll("div")
        .data(filtered)
        .enter()
        .append("div")
        .attr("class","reservation")
        .style("width", function(d) {
          return (xscale(Math.min(d.to, end - 60 * 60)) - xscale(d.from)) + "%";
        })
        .style("left", function(d) {
          return (xscale(d.from)) + "%";
        })
        .append("div")
        .attr("class","reservation-label")
        .text(function(d) {
          return d.title;
        });
    })
  }

  $.ajax('/reservations', {
    method: 'GET',
    dataType: 'json'
  })
  .done(function(data) {
    reservations = data;
    renderGraph();
  })

  $.ajax('/resources', {
    method: 'GET',
    dataType: 'json'
  })
  .done(function(data) {
    resources = data;
    renderGraph();
  })

})
<commit_msg>removed some styling<commit_after>$(function() {
  var reservations;
  var resources;
  function renderGraph() {
    if(!(reservations && resources))
      return;

    // Sort the rooms alphabetically
    resources = resources.sort(function(a, b) {
      var keyA = a.name.toLowerCase(),
          keyB = b.name.toLowerCase();
      if(keyA < keyB) return -1;
      if(keyA > keyB) return 1;
      return 0;
    });

    // Set up the reservation list
    var start = 28800 ; // 8:00 AM
    var end = 72000; // 7:00 PM

    // Convert start / end times to seconds in the day
    reservations = reservations.map(function(r) {
      var from = new Date(r.from);
      var to = new Date(r.to);

      r.from = from.getSeconds() + (60 * from.getMinutes()) + (60 * 60 * from.getHours());
      r.to = to.getSeconds() + (60 * to.getMinutes()) + (60 * 60 * to.getHours());
      return r;
    });

    // Set scales
    var xscale = d3.scale.linear()
      .domain([start, end])
      .range([0, 100]);

    // Generate the x axis
    var hours = [];
    for(var x = start; x < end; x += 3600) {
      var hour = (Math.floor(x/3600) - 1) % 12 + 1;
      var minute = (x % 3600);
      hours.push(hour + ":" + ((minute < 10)?"0":"") + minute);
    }

    // Render the x axis.
    var xaxis = d3.select("#x-axis").selectAll("div")
      .data(hours)
      .enter()
      .append("div")
      .attr("class", function(d, i) {
        return "time " + ((i%2 == 0)?"even": "odd") + ((i == hours.length - 1)?" last":"");
      })
      .style("width", (99 / hours.length) + "%")
      .append("div")
      .text(function(d) {
        return d;
      })
      .attr("class", "time-label");

    // Set the height of the reservations
    $("#reservations").height($(window).height() - 170 - 60); // 170 is header height, 60 is footer padding

    // Render the rooms.
    var timeline = d3.select("#reservations");

    // Create one row per entry
    var rows = timeline.selectAll("div")
      .data(resources)
      .enter()
      .append("div")
      .attr("class","row")
      .style("height", (100/resources.length)  + "%")

    // Add the label
    rows.append("div")
      .attr("class", "resource")
      .append("div")
      .attr("class", "resource-label")
      .text(function(d) {
        return d.name;
      })

    // Add the reservations
    rows.each(function(resource) {
      var row = d3.select(this);
      var filtered = reservations.filter(function(d) {
        return d.resource.id == resource.id && d.from < (end - 60 * 60);
      });
      row.append("div")
        .attr("class","timeline")
        .selectAll("div")
        .data(filtered)
        .enter()
        .append("div")
        .attr("class","reservation")
        .style("width", function(d) {
          return (xscale(Math.min(d.to, end - 60 * 60)) - xscale(d.from)) + "%";
        })
        .style("left", function(d) {
          return (xscale(d.from)) + "%";
        })
        .append("div")
        .attr("class","reservation-label")
        .text(function(d) {
          return d.title;
        });
    })
  }

  $.ajax('/reservations', {
    method: 'GET',
    dataType: 'json'
  })
  .done(function(data) {
    reservations = data;
    renderGraph();
  })

  $.ajax('/resources', {
    method: 'GET',
    dataType: 'json'
  })
  .done(function(data) {
    resources = data;
    renderGraph();
  })

})
<|endoftext|>


<commit_before>describe("Menu Navigation", function() {

    var testGM;

    beforeEach(function() {
        testGM = new GameManager();
        testGM.screenmanager.root = new MainMenuScreen("home");
        testGM.screenmanager.root.start();
    });

    it("should be able to navigate from home to user-login", function() {
        testGM.screenmanager.changePage("user-login");
        expect(testGM.screenmanager.topScreen.menuName).toEqual("user-login");
    });

    it("should navigate back a page correctly", function() {
        testGM.screenmanager.changePage("user-login");
        testGM.screenmanager.changePage("back");

        expect(testGM.screenmanager.topScreen.menuName).toEqual("home");
    });

    it("should be able to navigate from home screen to guest login", function(){
        testGM.screenmanager.changePage("guest-login");
        expect(testGM.screenmanager.topScreen.menuName).toEqual("guest-login");
    });

    it("should be able to navigate from home screen to teacher login", function(){
        testGM.screenmanager.changePage("teacher-login");
        expect(testGM.screenmanager.topScreen.menuName).toEqual("teacher-login");
    });

    it("should be able to navigate from home screen to creator login", function(){
        testGM.screenmanager.changePage("creator-login");
        expect(testGM.screenmanager.topScreen.menuName).toEqual("creator-login");
    });

});

describe("User Management", function() {

    var testGM;

    beforeEach(function() {
        testGM = new GameManager();
        testGM.screenmanager.root = new MainMenuScreen("home");
        testGM.screenmanager.root.start();
    });

    it("should be able to add a new user", function() {
        var testUser = new User(5);
        testGM.addUser(testUser);

        expect(testGM.users.length).toEqual(1);
    });

    it("should initialize a user's id correctly", function() {
        var testUser = new User(42);
        testGM.addUser(testUser);

        expect(testGM.getUser(42).id).toEqual(42);
    });

    it("should be able to remove a user", function() {
        var testUser1 = new User(1);
        var testUser2 = new User(2);
        testGM.addUser(testUser1);
        testGM.addUser(testUser2);
        testGM.removeUser(1);

        expect(testGM.users.length).toEqual(1);
    });
});

describe("In Game Menu Management", function(){

    var testGM;

    beforeEach(function() {
        testGM = new GameManager();
        testGM.screenmanager.root = new MainMenuScreen("home");
        testGM.screenmanager.root.start();
    });

    it("should be able to start a single player game", function(){
        testGM.screenmanager.changePage("levels");
        expect(testGM.screenmanager.topScreen.menuName).toEqual("levels");
    });

    it("should be able to start a multiplayer player game", function(){
    testGM.screenmanager.changePage("levels");
    expect(testGM.screenmanager.topScreen.menuName).toEqual("levels");
    });

    it("should be able to go to settings", function(){
    testGM.screenmanager.changePage("settings");
    expect(testGM.screenmanager.topScreen.menuName).toEqual("settings");
    });

    it("should be able to logout", function(){
        testGM.screenmanager.changePage("logout");
        expect(testGM.screenmanager.topScreen.menuName).toEqual("logout");
    });
});<commit_msg>Change test name from management to navigation<commit_after>describe("Menu Navigation", function() {

    var testGM;

    beforeEach(function() {
        testGM = new GameManager();
        testGM.screenmanager.root = new MainMenuScreen("home");
        testGM.screenmanager.root.start();
    });

    it("should be able to navigate from home to user-login", function() {
        testGM.screenmanager.changePage("user-login");
        expect(testGM.screenmanager.topScreen.menuName).toEqual("user-login");
    });

    it("should navigate back a page correctly", function() {
        testGM.screenmanager.changePage("user-login");
        testGM.screenmanager.changePage("back");

        expect(testGM.screenmanager.topScreen.menuName).toEqual("home");
    });

    it("should be able to navigate from home screen to guest login", function(){
        testGM.screenmanager.changePage("guest-login");
        expect(testGM.screenmanager.topScreen.menuName).toEqual("guest-login");
    });

    it("should be able to navigate from home screen to teacher login", function(){
        testGM.screenmanager.changePage("teacher-login");
        expect(testGM.screenmanager.topScreen.menuName).toEqual("teacher-login");
    });

    it("should be able to navigate from home screen to creator login", function(){
        testGM.screenmanager.changePage("creator-login");
        expect(testGM.screenmanager.topScreen.menuName).toEqual("creator-login");
    });

});

describe("User Management", function() {

    var testGM;

    beforeEach(function() {
        testGM = new GameManager();
        testGM.screenmanager.root = new MainMenuScreen("home");
        testGM.screenmanager.root.start();
    });

    it("should be able to add a new user", function() {
        var testUser = new User(5);
        testGM.addUser(testUser);

        expect(testGM.users.length).toEqual(1);
    });

    it("should initialize a user's id correctly", function() {
        var testUser = new User(42);
        testGM.addUser(testUser);

        expect(testGM.getUser(42).id).toEqual(42);
    });

    it("should be able to remove a user", function() {
        var testUser1 = new User(1);
        var testUser2 = new User(2);
        testGM.addUser(testUser1);
        testGM.addUser(testUser2);
        testGM.removeUser(1);

        expect(testGM.users.length).toEqual(1);
    });
});

describe("In Game Menu Navigation", function(){

    var testGM;

    beforeEach(function() {
        testGM = new GameManager();
        testGM.screenmanager.root = new MainMenuScreen("home");
        testGM.screenmanager.root.start();
    });

    it("should be able to start a single player game", function(){
        testGM.screenmanager.changePage("levels");
        expect(testGM.screenmanager.topScreen.menuName).toEqual("levels");
    });

    it("should be able to start a multiplayer player game", function(){
    testGM.screenmanager.changePage("levels");
    expect(testGM.screenmanager.topScreen.menuName).toEqual("levels");
    });

    it("should be able to go to settings", function(){
    testGM.screenmanager.changePage("settings");
    expect(testGM.screenmanager.topScreen.menuName).toEqual("settings");
    });

    it("should be able to logout", function(){
        testGM.screenmanager.changePage("logout");
        expect(testGM.screenmanager.topScreen.menuName).toEqual("logout");
    });
});<|endoftext|>


<commit_before>/*
 *  @copyright Adam Benda, 2016
 */

/**
 * DataSet is one source of data that can be used
 * to tell quality(ies) of a given point.
 *
 * @class
 *
 * @returns {DataSet}
 */
var DataSet = function (client, opts) {
    /**
     * Name of table in the Postgres geo database
     * @param {String}
     */
    this.table = "unnamed";
    if (typeof (opts.table) === "string" && opts.table.length > 0) {
        this.table = opts.table;
    }

    this.name = "unnamed";
    if (typeof (opts.name) === "string" && opts.name.length > 0) {
        this.name = opts.name;
    }

    /**
     * Name of columns in the Postgres geo database
     * @param {string[]}
     */
    this.columns = ["unknown"];
    if (Array.isArray(opts.columns)) {
        this.columns = opts.columns;
    }

    /**
     * @type {pg.Client}
     */
    this.client = client;

    this.queryName = "getQual_" + this.table;

    var columnsS = this.columns.join();
    this.firstQuery = this.client.query(
            {"text": 'SELECT ' + columnsS + ' FROM ' + this.table + ' WHERE ST_Contains(geom, ST_Point($1::float,$2::float))',
                "values": [14.4297444, 50.0797425],
                "name": this.queryName
            });

};

/**
 * Gets unformated info about given point
 * @param {number[]} point - [x,y]
 * @param {function} callback - function to be called afterwards
 * @returns {undefined}
 */
DataSet.prototype.getProperty = function (point, callback) {
    //using prepared query
    var thisQuery = this.client.query({
        name: this.queryName,
        values: point
    }, callback);
};

module.exports = DataSet;<commit_msg>Server: possibility to round some dataset value(2)<commit_after>/*
 *  @copyright Adam Benda, 2016
 */

/**
 * DataSet is one source of data that can be used
 * to tell quality(ies) of a given point.
 *
 * @class
 *
 * @returns {DataSet}
 */
var DataSet = function (client, opts) {
    /**
     * Name of table in the Postgres geo database
     * @param {String}
     */
    this.table = "unnamed";
    if (typeof (opts.table) === "string" && opts.table.length > 0) {
        this.table = opts.table;
    }

    this.name = "unnamed";
    if (typeof (opts.name) === "string" && opts.name.length > 0) {
        this.name = opts.name;
    }

    /**
     * Name of columns in the Postgres geo database
     * @param {string[]}
     */
    this.columns = ["unknown"];
    if (Array.isArray(opts.columns)) {
        this.columns = opts.columns;
    }

    this.round = false;
    if (typeof (opts.round) === "boolean") {
        this.round = opts.round;
    }

    /**
     * @type {pg.Client}
     */
    this.client = client;

    this.queryName = "getQual_" + this.table;

    if (this.round) {
        for (var i = 0; i < this.columns.length; i++) {
            this.columns[i] = "round(" + this.columns[i] + ")";
        }
    }
    var columnsS = this.columns.join();
    this.firstQuery = this.client.query(
            {"text": 'SELECT ' + columnsS + ' FROM ' + this.table + ' WHERE ST_Contains(geom, ST_Point($1::float,$2::float))',
                "values": [14.4297444, 50.0797425],
                "name": this.queryName
            });

};

/**
 * Gets unformated info about given point
 * @param {number[]} point - [x,y]
 * @param {function} callback - function to be called afterwards
 * @returns {undefined}
 */
DataSet.prototype.getProperty = function (point, callback) {
    //using prepared query
    var thisQuery = this.client.query({
        name: this.queryName,
        values: point
    }, callback);
};

module.exports = DataSet;<|endoftext|>


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

// create reusable transporter object using SMTP transport
var transporter = nodemailer.createTransport({
    service: 'Gmail',
    auth: {
        user: process.env.USER_EMAIL,
        pass: process.env.USER_PWD
    }
});

exports.sendMail = function(receiverEmail, eventURL) {
  // setup e-mail data
  var mailOptions = {
      from: process.env.USER_EMAIL, // sender address
      to: receiverEmail,  // list of receivers
      subject: '✔ Event Confirmation', // Subject line
      text: 'You have successfully created an event! View it here: '+eventURL, // plaintext body
  };

  transporter.sendMail(mailOptions, function(error, info) {
      if(error) {
          return console.log(error);
      }
      console.log('Message sent: ' + info.response + '\n');
  });
}<commit_msg>[refactor] fix syntax errors<commit_after>var nodemailer = require('nodemailer');

// create reusable transporter object using SMTP transport
var transporter = nodemailer.createTransport({
    service: 'Gmail',
    auth: {
        user: process.env.USER_EMAIL,
        pass: process.env.USER_PWD
    }
});

exports.sendMail = function(receiverEmail, eventURL) {
  // setup e-mail data
  var mailOptions = {
      from: process.env.USER_EMAIL, // sender address
      to: receiverEmail,  // list of receivers
      subject: '✔ Event Confirmation', // Subject line
      text: 'You have successfully created an event! View it here: '+eventURL, // plaintext body
  };

  transporter.sendMail(mailOptions, function(error, info) {
      if(error) {
          return console.log(error);
      }
      console.log('Message sent: ' + info.response + '\n');
  });
};<|endoftext|>


<commit_before>var canvas;
var container;
var gl;

function setMinTime() {
    return $.ajax({type: 'GET', url: 'times.php?search=' + search, async: false});
}

function setDataList() {
    $.ajax("dataList.php", {async: 'false'}).success(function(j) {
        var options = '<option value="default">Pick database...</option>';
        data = jQuery.parseJSON(j);
        for (var i = 0; i < data.length; i++) {
            options += '<option value="' + data[i] + '">' + data[i] + '</option>';
        }

        $("#language").html(options);
    });
}

//
//    function reload(){
//            var container = document.getElementById("container");
//            var content = container.innerHTML;
//            container.innerHTML= content;
//        }

function outputUpdate(speednum) {
    document.querySelector('#speednum').value = vol;
}

function initGlobe() {
    document.body.style.backgroundImage = 'none'; // remove loading
    container = document.getElementById('container');
    globe = new DAT.Globe(container);
    globe.addData([], {format: 'magnitude', animated: false});
    globe.createPoints();
    globe.animate();

    animate = function() {
        requestAnimationFrame(animate);
    };

    animate();
}

function setGlobeData() {
    setInterval(function() {
        interval = 5000;
        time = time + interval;
        dataResp = $.ajax({
            type: 'GET',
            url: 'data.php?offset=' + time + '&search=' + search + '&interval=' + interval,
            async: false
        });
        dataObj = dataResp.responseText;
        data = jQuery.parseJSON(dataObj);
        window.data = data;
        if (data.length > 0) {
            for (i = 0; i < data.length; i += 1) {
                globe.addData(data[i], {format: 'magnitude', animated: false});
            }
            globe.createPoints();
            globe.animate();
        }
    }, 2000);
}

//
//dataSource.bind("sync", function(e) {
//  $('container').data("container").dataSource.read();
//});
//
function addGlobeData(search, colour) {
    dataResp = $.ajax({
        type: 'GET',
        url: 'search.php?search=' + search + '&colour=' + colour,
        async: false
    });
    dataObj = dataResp.responseText;
    if (dataObj) {
        data = jQuery.parseJSON(dataObj);
        window.data = data;
        if (dataObj && data.length > 0) {
            globe.addData(data, {format: 'magnitude', animated: false});
            globe.createPoints();
            globe.animate();
        }
        else {
            alert("No Results");
        }
    } else {
        alert("Please wait 10 mins and try again");
    }
}<commit_msg>remove animate call<commit_after>var canvas;
var container;
var gl;

function setMinTime() {
    return $.ajax({type: 'GET', url: 'times.php?search=' + search, async: false});
}

function setDataList() {
    $.ajax("dataList.php", {async: 'false'}).success(function(j) {
        var options = '<option value="default">Pick database...</option>';
        data = jQuery.parseJSON(j);
        for (var i = 0; i < data.length; i++) {
            options += '<option value="' + data[i] + '">' + data[i] + '</option>';
        }

        $("#language").html(options);
    });
}

//
//    function reload(){
//            var container = document.getElementById("container");
//            var content = container.innerHTML;
//            container.innerHTML= content;
//        }

function outputUpdate(speednum) {
    document.querySelector('#speednum').value = vol;
}

function initGlobe() {
    document.body.style.backgroundImage = 'none'; // remove loading
    container = document.getElementById('container');
    globe = new DAT.Globe(container);
    globe.addData([], {format: 'magnitude', animated: false});
    globe.createPoints();
    globe.animate();

    animate = function() {
        requestAnimationFrame(animate);
    };

    animate();
}

function setGlobeData() {
    setInterval(function() {
        interval = 5000;
        time = time + interval;
        dataResp = $.ajax({
            type: 'GET',
            url: 'data.php?offset=' + time + '&search=' + search + '&interval=' + interval,
            async: false
        });
        dataObj = dataResp.responseText;
        data = jQuery.parseJSON(dataObj);
        window.data = data;
        if (data.length > 0) {
            for (i = 0; i < data.length; i += 1) {
                globe.addData(data[i], {format: 'magnitude', animated: false});
            }
            globe.createPoints();
        }
    }, 2000);
}

//
//dataSource.bind("sync", function(e) {
//  $('container').data("container").dataSource.read();
//});
//
function addGlobeData(search, colour) {
    dataResp = $.ajax({
        type: 'GET',
        url: 'search.php?search=' + search + '&colour=' + colour,
        async: false
    });
    dataObj = dataResp.responseText;
    if (dataObj) {
        data = jQuery.parseJSON(dataObj);
        window.data = data;
        if (dataObj && data.length > 0) {
            globe.addData(data, {format: 'magnitude', animated: false});
            globe.createPoints();
            globe.animate();
        }
        else {
            alert("No Results");
        }
    } else {
        alert("Please wait 10 mins and try again");
    }
}<|endoftext|>


<commit_before>
var auth 			= require('./auth'),
    search 			= require('../controllers/search'),
	users 			= require('../controllers/users'),
	datasets  		= require('../controllers/datasets'),
	commodities 	= require('../controllers/commodities'),
	concessions 	= require('../controllers/concessions'),
	companies 		= require('../controllers/companies'),
	projects 		= require('../controllers/projects'),
	contracts 		= require('../controllers/contracts'),
	companyGroups 	= require('../controllers/companyGroups'),
	countries 		= require('../controllers/countries'),
	sources 		= require('../controllers/sources'),
	sites 			= require('../controllers/sites');
	//etl         = require('../controllers/etl');
	// answers 	= require('../controllers/answers'),
	// questions 	= require('../controllers/questions'),
	// assessments = require('../controllers/assessments');
	// mongoose 	= require('mongoose');
	// User 		= mongoose.model('User');

module.exports	= function(app) {

	app.get('/api/search', search.searchText);

	//CONTRACTS
	app.get('/api/contracts/:limit/:skip', contracts.getContracts);
	app.get('/api/contracts/:id', contracts.getContractByID);

	/////////////////////////
	///// CONCESSIONS CRUD ////////
	/////////////////////////
	app.get('/api/concessions/:limit/:skip', concessions.getConcessions);
	app.get('/api/concessions/:id', concessions.getConcessionByID);
	// POST
	app.post('/api/concessions',  concessions.createConcession);
	// PUT
	app.put('/api/concessions',  concessions.updateConcession);
	// DELETE
	app.delete('/api/concessions/:id', concessions.deleteConcession);

	/////////////////////////
	///// PROJECTS CRUD ////////
	/////////////////////////
	app.get('/api/projects/:limit/:skip', projects.getProjects);
	app.get('/api/projects/:id', projects.getProjectByID);
	app.get('/api/projects/', projects.getProjectsMap);
	// POST
	app.post('/api/projects',  projects.createProject);
	// PUT
	app.put('/api/projects',  projects.updateProject);
	// DELETE
	app.delete('/api/projects/:id', projects.deleteProject);

	/////////////////////////
	///// COMPANIES CRUD ////
	/////////////////////////
	//app.get('/api/companies/:limit/:skip', companies.getCompanies);
	app.get('/api/companies/:limit/:skip', companies.getCompanies);
	app.get('/api/companies/:id', companies.getCompanyByID);
	// POST
	app.post('/api/companies',  companies.createCompany);
	// PUT
	app.put('/api/companies',  companies.updateCompany);
	// DELETE
	app.delete('/api/companies/:id', companies.deleteCompany);

	/////////////////////////
	///// COMPANYGROUPS CRUD ////////
	/////////////////////////
	app.get('/api/companyGroups/:limit/:skip', companyGroups.getCompanyGroups);
	app.get('/api/companyGroups/:id', companyGroups.getCompanyGroupByID);
	// POST
	app.post('/api/companyGroups',  companyGroups.createCompanyGroup);
	// PUT
	app.put('/api/companyGroups',  companyGroups.updateCompanyGroup);
	// DELETE
	app.delete('/api/companyGroups/:id', companyGroups.deleteCompanyGroup);

	/////////////////////////
	///// COMMODITIES ////////
	/////////////////////////
	app.get('/api/commodities/:limit/:skip', commodities.getCommodities);
	app.get('/api/commodities/:id', commodities.getCommodityByID);
	// POST
	app.post('/api/commodities',  commodities.createCommodity);
	// PUT
	app.put('/api/commodities',  commodities.updateCommodity);
	// DELETE
	app.delete('/api/commodities/:id', commodities.deleteCommodity);

	/////////////////////////
	///// COUNTRIES CRUD ////////
	/////////////////////////
	app.get('/api/countries/:limit/:skip', countries.getCountries);
	app.get('/api/countries/:id', countries.getCountryByID);
	// POST
	app.post('/api/countries',  countries.createCountry);
	// PUT
	app.put('/api/countries',  countries.updateCountry);
	// DELETE
	app.delete('/api/countries/:id', countries.deleteCountry);

	/////////////////////////
	///// SOURCES CRUD ////////
	/////////////////////////
	app.get('/api/sources/:limit/:skip', sources.getSources);
	app.get('/api/sources/:id', sources.getSourceByID);

	// POST
	app.post('/api/sources',  sources.createSource);
	// PUT
	app.put('/api/sources',  sources.updateSource);
	// DELETE
	app.delete('/api/sources/:id', sources.deleteSource);

	//DATASETS - TODO: protect with admin
	app.get('/api/datasets', datasets.getDatasets);
	app.get('/api/datasets/:limit/:skip', datasets.getDatasets);
	app.get('/api/datasets/:id', datasets.getDatasetByID);

	//Reporting
	app.get('/admin/etl/datasets/:dataset_id/actions/:action_id/report',
		datasets.getActionReport,
		function(req, res) {
		    res.render('actionreport', {report: req.report});
	});

	//Reporting
	app.get('/admin/etl/datasets/:dataset_id/actions/:action_id/report',
		datasets.getActionReport,
		function(req, res) {
		    res.render('actionreport', {report: req.report});
	});

	//Reporting
	app.get('/admin/etl/datasets/:dataset_id/actions/:action_id/report',
		datasets.getActionReport,
		function(req, res) {
		    res.render('actionreport', {report: req.report});
	});

	//Reporting
	app.get('/admin/etl/datasets/:dataset_id/actions/:action_id/report',
		datasets.getActionReport,
		function(req, res) {
		    res.render('actionreport', {report: req.report});
	});

	//Reporting
	app.get('/admin/etl/datasets/:dataset_id/actions/:action_id/report',
		datasets.getActionReport,
		function(req, res) {
		    res.render('actionreport', {report: req.report});
	});

	//Reporting
	app.get('/admin/etl/datasets/:dataset_id/actions/:action_id/report',
		datasets.getActionReport,
		function(req, res) {
		    res.render('actionreport', {report: req.report});
	});

	//Create a dataset
	app.post('/api/datasets', auth.requiresApiLogin, /* auth.requiresRole('admin'),*/ datasets.createDataset);
	//Start an ETL step
	app.post('/api/datasets/:id/actions', /* auth.requiresApiLogin, auth.requiresRole('admin'), */ datasets.createAction);

	// POST
	app.post('/api/sources',  sources.createSource);
	// PUT
	app.put('/api/sources',  sources.updateSource);
	// DELETE
	app.delete('/api/sources/:id', sources.deleteSource);

	/////////////////////////////////////////////
	///// COMPANIES HOUSE DUMMY DATASETS ////////
	/////////////////////////////////////////////

	app.get('/api/testdata', datasets.getTestdata);

	/////////////////////////////////////////////
	///// COMPANIES HOUSE DUMMY DATASETS ////////
	/////////////////////////////////////////////

	app.get('/api/testdata', datasets.getTestdata);

	/////////////////////////
	///// SITES CRUD ////////
	/////////////////////////
	app.get('/api/sites/:limit/:skip/:field', sites.getSites);
	app.get('/api/sites/:id', sites.getSiteByID);
	app.get('/api/sites/map/:field', sites.getSitesMap);

	//DATASETS - TODO: protect with admin?
	app.get('/api/datasets', datasets.getDatasets);
	app.get('/api/datasets/:limit/:skip', datasets.getDatasets);
	app.get('/api/datasets/:id', datasets.getDatasetByID);

	//Reporting
	app.get('/admin/etl/datasets/:dataset_id/actions/:action_id/report',
		datasets.getActionReport,
		function(req, res) {
		    res.render('actionreport', {report: req.report});
	});

	//Create a dataset - todo protect with admin
	app.post('/api/datasets', /* auth.requiresApiLogin, auth.requiresRole('admin'), */ datasets.createDataset);
	//Start an ETL step
	app.post('/api/datasets/:id/actions', /* auth.requiresApiLogin, auth.requiresRole('admin'), */ datasets.createAction);

	// POST
	app.post('/api/sites',  sites.createSite);
	// PUT
	app.put('/api/sites',  sites.updateSite);
	// DELETE
	app.delete('/api/sites/:id', sites.deleteSite);

	/////////////////////////////////////////////
	///// COMPANIES HOUSE DUMMY DATASETS ////////
	/////////////////////////////////////////////

	app.get('/api/testdata', datasets.getTestdata);

	/////////////////////////////////////////////
	///// COMPANIES HOUSE DUMMY DATASETS ////////
	/////////////////////////////////////////////

	app.get('/api/testdata', datasets.getTestdata);

	/////////////////////////////////////////////
	///// COMPANIES HOUSE DUMMY DATASETS ////////
	/////////////////////////////////////////////

	app.get('/api/testdata', datasets.getTestdata);

	/////////////////////////
	///// USERS CRUD ////////
	/////////////////////////
	app.get('/api/users', auth.requiresRole('admin'), users.getUsers);
	app.get('/api/users/:id', auth.requiresRole('admin'), users.getUsersByID);
	app.get('/api/user-list/:id', auth.requiresRole('admin'), users.getUsersListByID);

	// POST
	app.post('/api/users', auth.requiresApiLogin, auth.requiresRole('admin'), users.createUser);

	// PUT
	app.put('/api/users', auth.requiresRole('admin'), users.updateUser);

	// DELETE
	app.delete('/api/users/:id', auth.requiresRole('admin'), users.deleteUser);
	////////////////////
	///// OTHER ////////
	////////////////////
	app.get('/partials/*', function(req, res) {
		res.render('../../public/app/' + req.params[0]);
	});

	app.post('/login', auth.authenticate);

	app.post('/logout', function(req, res) {
		req.logout();
		res.end();
	});

	app.all('/api/*', function(req, res) {
		res.sendStatus(404);
	});
	//app.get('*', function(req, res) {
	//	res.render('landing_page', {
	//		bootstrappedUser: req.user
	//	});
	//});
	app.get('*', function(req, res) {
		res.render('index', {
			bootstrappedUser: req.user
		});
	});
};<commit_msg>companies house dummy data route added for testing purposes<commit_after>
var auth 			= require('./auth'),
    search 			= require('../controllers/search'),
	users 			= require('../controllers/users'),
	datasets  		= require('../controllers/datasets'),
	commodities 	= require('../controllers/commodities'),
	concessions 	= require('../controllers/concessions'),
	companies 		= require('../controllers/companies'),
	projects 		= require('../controllers/projects'),
	contracts 		= require('../controllers/contracts'),
	companyGroups 	= require('../controllers/companyGroups'),
	countries 		= require('../controllers/countries'),
	sources 		= require('../controllers/sources'),
	sites 			= require('../controllers/sites');
	//etl         = require('../controllers/etl');
	// answers 	= require('../controllers/answers'),
	// questions 	= require('../controllers/questions'),
	// assessments = require('../controllers/assessments');
	// mongoose 	= require('mongoose');
	// User 		= mongoose.model('User');

module.exports	= function(app) {

	app.get('/api/search', search.searchText);

	//CONTRACTS
	app.get('/api/contracts/:limit/:skip', contracts.getContracts);
	app.get('/api/contracts/:id', contracts.getContractByID);

	/////////////////////////
	///// CONCESSIONS CRUD ////////
	/////////////////////////
	app.get('/api/concessions/:limit/:skip', concessions.getConcessions);
	app.get('/api/concessions/:id', concessions.getConcessionByID);
	// POST
	app.post('/api/concessions',  concessions.createConcession);
	// PUT
	app.put('/api/concessions',  concessions.updateConcession);
	// DELETE
	app.delete('/api/concessions/:id', concessions.deleteConcession);

	/////////////////////////
	///// PROJECTS CRUD ////////
	/////////////////////////
	app.get('/api/projects/:limit/:skip', projects.getProjects);
	app.get('/api/projects/:id', projects.getProjectByID);
	app.get('/api/projects/', projects.getProjectsMap);
	// POST
	app.post('/api/projects',  projects.createProject);
	// PUT
	app.put('/api/projects',  projects.updateProject);
	// DELETE
	app.delete('/api/projects/:id', projects.deleteProject);

	/////////////////////////
	///// COMPANIES CRUD ////
	/////////////////////////
	//app.get('/api/companies/:limit/:skip', companies.getCompanies);
	app.get('/api/companies/:limit/:skip', companies.getCompanies);
	app.get('/api/companies/:id', companies.getCompanyByID);
	// POST
	app.post('/api/companies',  companies.createCompany);
	// PUT
	app.put('/api/companies',  companies.updateCompany);
	// DELETE
	app.delete('/api/companies/:id', companies.deleteCompany);

	/////////////////////////
	///// COMPANYGROUPS CRUD ////////
	/////////////////////////
	app.get('/api/companyGroups/:limit/:skip', companyGroups.getCompanyGroups);
	app.get('/api/companyGroups/:id', companyGroups.getCompanyGroupByID);
	// POST
	app.post('/api/companyGroups',  companyGroups.createCompanyGroup);
	// PUT
	app.put('/api/companyGroups',  companyGroups.updateCompanyGroup);
	// DELETE
	app.delete('/api/companyGroups/:id', companyGroups.deleteCompanyGroup);

	/////////////////////////
	///// COMMODITIES ////////
	/////////////////////////
	app.get('/api/commodities/:limit/:skip', commodities.getCommodities);
	app.get('/api/commodities/:id', commodities.getCommodityByID);
	// POST
	app.post('/api/commodities',  commodities.createCommodity);
	// PUT
	app.put('/api/commodities',  commodities.updateCommodity);
	// DELETE
	app.delete('/api/commodities/:id', commodities.deleteCommodity);

	/////////////////////////
	///// COUNTRIES CRUD ////////
	/////////////////////////
	app.get('/api/countries/:limit/:skip', countries.getCountries);
	app.get('/api/countries/:id', countries.getCountryByID);
	// POST
	app.post('/api/countries',  countries.createCountry);
	// PUT
	app.put('/api/countries',  countries.updateCountry);
	// DELETE
	app.delete('/api/countries/:id', countries.deleteCountry);

	/////////////////////////
	///// SOURCES CRUD ////////
	/////////////////////////
	app.get('/api/sources/:limit/:skip', sources.getSources);
	app.get('/api/sources/:id', sources.getSourceByID);

	// POST
	app.post('/api/sources',  sources.createSource);
	// PUT
	app.put('/api/sources',  sources.updateSource);
	// DELETE
	app.delete('/api/sources/:id', sources.deleteSource);

	//DATASETS - TODO: protect with admin
	app.get('/api/datasets', datasets.getDatasets);
	app.get('/api/datasets/:limit/:skip', datasets.getDatasets);
	app.get('/api/datasets/:id', datasets.getDatasetByID);

	//Reporting
	app.get('/admin/etl/datasets/:dataset_id/actions/:action_id/report',
		datasets.getActionReport,
		function(req, res) {
		    res.render('actionreport', {report: req.report});
	});

	//Reporting
	app.get('/admin/etl/datasets/:dataset_id/actions/:action_id/report',
		datasets.getActionReport,
		function(req, res) {
		    res.render('actionreport', {report: req.report});
	});

	//Reporting
	app.get('/admin/etl/datasets/:dataset_id/actions/:action_id/report',
		datasets.getActionReport,
		function(req, res) {
		    res.render('actionreport', {report: req.report});
	});

	//Reporting
	app.get('/admin/etl/datasets/:dataset_id/actions/:action_id/report',
		datasets.getActionReport,
		function(req, res) {
		    res.render('actionreport', {report: req.report});
	});

	//Reporting
	app.get('/admin/etl/datasets/:dataset_id/actions/:action_id/report',
		datasets.getActionReport,
		function(req, res) {
		    res.render('actionreport', {report: req.report});
	});

	//Reporting
	app.get('/admin/etl/datasets/:dataset_id/actions/:action_id/report',
		datasets.getActionReport,
		function(req, res) {
		    res.render('actionreport', {report: req.report});
	});

	//Create a dataset
	app.post('/api/datasets', auth.requiresApiLogin, /* auth.requiresRole('admin'),*/ datasets.createDataset);
	//Start an ETL step
	app.post('/api/datasets/:id/actions', /* auth.requiresApiLogin, auth.requiresRole('admin'), */ datasets.createAction);

	// POST
	app.post('/api/sources',  sources.createSource);
	// PUT
	app.put('/api/sources',  sources.updateSource);
	// DELETE
	app.delete('/api/sources/:id', sources.deleteSource);

	/////////////////////////////////////////////
	///// COMPANIES HOUSE DUMMY DATASETS ////////
	/////////////////////////////////////////////

	app.get('/api/testdata', datasets.getTestdata);

	/////////////////////////////////////////////
	///// COMPANIES HOUSE DUMMY DATASETS ////////
	/////////////////////////////////////////////

	app.get('/api/testdata', datasets.getTestdata);

	/////////////////////////
	///// SITES CRUD ////////
	/////////////////////////
	app.get('/api/sites/:limit/:skip/:field', sites.getSites);
	app.get('/api/sites/:id', sites.getSiteByID);
	app.get('/api/sites/map/:field', sites.getSitesMap);

	//DATASETS - TODO: protect with admin?
	app.get('/api/datasets', datasets.getDatasets);
	app.get('/api/datasets/:limit/:skip', datasets.getDatasets);
	app.get('/api/datasets/:id', datasets.getDatasetByID);

	//Reporting
	app.get('/admin/etl/datasets/:dataset_id/actions/:action_id/report',
		datasets.getActionReport,
		function(req, res) {
		    res.render('actionreport', {report: req.report});
	});

	//Create a dataset - todo protect with admin
	app.post('/api/datasets', /* auth.requiresApiLogin, auth.requiresRole('admin'), */ datasets.createDataset);
	//Start an ETL step
	app.post('/api/datasets/:id/actions', /* auth.requiresApiLogin, auth.requiresRole('admin'), */ datasets.createAction);

	// POST
	app.post('/api/sites',  sites.createSite);
	// PUT
	app.put('/api/sites',  sites.updateSite);
	// DELETE
	app.delete('/api/sites/:id', sites.deleteSite);

	/////////////////////////////////////////////
	///// COMPANIES HOUSE DUMMY DATASETS ////////
	/////////////////////////////////////////////

	app.get('/api/testdata', datasets.getTestdata);

	/////////////////////////////////////////////
	///// COMPANIES HOUSE DUMMY DATASETS ////////
	/////////////////////////////////////////////

	app.get('/api/testdata', datasets.getTestdata);

	/////////////////////////////////////////////
	///// COMPANIES HOUSE DUMMY DATASETS ////////
	/////////////////////////////////////////////

	app.get('/api/testdata', datasets.getTestdata);

	/////////////////////////////////////////////
	///// COMPANIES HOUSE DUMMY DATASETS ////////
	/////////////////////////////////////////////

	app.get('/api/testdata', datasets.getTestdata);

	/////////////////////////
	///// USERS CRUD ////////
	/////////////////////////
	app.get('/api/users', auth.requiresRole('admin'), users.getUsers);
	app.get('/api/users/:id', auth.requiresRole('admin'), users.getUsersByID);
	app.get('/api/user-list/:id', auth.requiresRole('admin'), users.getUsersListByID);

	// POST
	app.post('/api/users', auth.requiresApiLogin, auth.requiresRole('admin'), users.createUser);

	// PUT
	app.put('/api/users', auth.requiresRole('admin'), users.updateUser);

	// DELETE
	app.delete('/api/users/:id', auth.requiresRole('admin'), users.deleteUser);
	////////////////////
	///// OTHER ////////
	////////////////////
	app.get('/partials/*', function(req, res) {
		res.render('../../public/app/' + req.params[0]);
	});

	app.post('/login', auth.authenticate);

	app.post('/logout', function(req, res) {
		req.logout();
		res.end();
	});

	app.all('/api/*', function(req, res) {
		res.sendStatus(404);
	});
	//app.get('*', function(req, res) {
	//	res.render('landing_page', {
	//		bootstrappedUser: req.user
	//	});
	//});
	app.get('*', function(req, res) {
		res.render('index', {
			bootstrappedUser: req.user
		});
	});
};<|endoftext|>


<commit_before>function router(app){

}

module.exports = router;<commit_msg>Adds cached response handling to router<commit_after>var metricsController = require('../controllers/metrics');
var MIN_QUERY_LENGTH = '0/sum/value=0'.length;
var cache = require('../cache');

/**
 * metric_id: Metric being observed
 * type: 'instances' || 'count' || 'sum' || 'average'
 * filter: Array of filters
 */
function router(app){
  app.get('/api/*', function(req, res){
    var queryString = req.params[0];
    cache.contains(queryString, function(doesExist){
      if (doesExist){
        res.statusCode = 200;
        return cache.get(queryString, function(value){
          res.send(value);
        });
      }

    });
  });
}

module.exports = router;<|endoftext|>


<commit_before>Meteor.publish("userInfo", function() {
	if(!this.userId) {
		return this.ready();
	}

	return Meteor.users.find(this.userId, {
		fields: {
			"admin": 1,
			"alive": 1,
			"target": 1,
			"assassinations": 1
		}
	});
});

Meteor.publish("userList", function() {
	if(!this.userId) {
		return this.ready();
	}

	return Meteor.users.find({}, {
		fields: {
			"profile.name": 1
		}
	});
});

Meteor.publish("posts", function() {
	return Posts.find();
});<commit_msg>Remove conditionals in publish methods<commit_after>Meteor.publish("userInfo", function() {
	return Meteor.users.find(this.userId, {
		fields: {
			"admin": 1,
			"alive": 1,
			"target": 1,
			"assassinations": 1
		}
	});
});

Meteor.publish("userList", function() {
	return Meteor.users.find({}, {
		fields: {
			"profile.name": 1
		}
	});
});

Meteor.publish("posts", function() {
	return Posts.find();
});<|endoftext|>


<commit_before>/******************************************************************************/
/*                                                                            */
/*  Poetic Generator Reloaded is a multiplayer and collaborative art          */
/*  experience.                                                               */
/*                                                                            */
/*  Copyright (C) 2011 - Gnuside                                              */
/*                                                                            */
/*  This program is free software: you can redistribute it and/or modify it   */
/*  under the terms of the GNU Affero General Public License as published by  */
/*  the Free Software Foundation, either version 3 of the License, or (at     */
/*  your option) any later version.                                           */
/*                                                                            */
/*  This program is distributed in the hope that it will be useful, but       */
/*  WITHOUT ANY WARRANTY; without even the implied warranty of                */
/*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero  */
/*  General Public License for more details.                                  */
/*                                                                            */
/*  You should have received a copy of the GNU Affero General Public License  */
/*  along with this program.  If not, see <http://www.gnu.org/licenses/>.     */
/*                                                                            */
/******************************************************************************/

// use phantomjs

var BASE_URL = "http://localhost:9393";

if (phantom.state.length === 0) {
	console.log("Setting up Phantom...");

	phantom.open( BASE_URL );

} else {

	if ( document.location.href == BASE_URL ) {
		// on base url
		// set username (bot + date)
		// set logout date
		// validate

		// on drawing page
		// pick a color
		// generate a random number of strokes in editor
		//   set a direction
		//   continue in that direction
	} else {
		console.log("  [oops] unknown page");
		phantom.exit();
	}

}
<commit_msg>bot: handle page changes.<commit_after>/******************************************************************************/
/*                                                                            */
/*  Poetic Generator Reloaded is a multiplayer and collaborative art          */
/*  experience.                                                               */
/*                                                                            */
/*  Copyright (C) 2011 - Gnuside                                              */
/*                                                                            */
/*  This program is free software: you can redistribute it and/or modify it   */
/*  under the terms of the GNU Affero General Public License as published by  */
/*  the Free Software Foundation, either version 3 of the License, or (at     */
/*  your option) any later version.                                           */
/*                                                                            */
/*  This program is distributed in the hope that it will be useful, but       */
/*  WITHOUT ANY WARRANTY; without even the implied warranty of                */
/*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero  */
/*  General Public License for more details.                                  */
/*                                                                            */
/*  You should have received a copy of the GNU Affero General Public License  */
/*  along with this program.  If not, see <http://www.gnu.org/licenses/>.     */
/*                                                                            */
/******************************************************************************/

// use phantomjs

var BASE_URL = "http://localhost:9393/";

phantom.click = function ( el ) {
	var evt = document.createEvent('MouseEvents');
	evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0,
			false, false, false, false, 0, null);
	el.dispatchEvent(evt);
}

if (phantom.state.length === 0) {
	console.log("Setting up Phantom...");
	var r = Math.floor( Math.random() * 256 ).toString(16);
	var g = Math.floor( Math.random() * 256 ).toString(16);
	var b = Math.floor( Math.random() * 256 ).toString(16);
	phantom.state = "#" + r + g + b;

	phantom.open( BASE_URL );

} else {
	console.log( "[color] " + phantom.state );
	console.log( "[url] " + document.location.href );

	if ( document.location.href == BASE_URL ) {
		// on base url
		// set username (bot + date)
		// set logout date
		// validate
		var username_elem = document.getElementById('username');
		var play_elem = document.getElementById('link_play');
		username_elem.value = "bot_" + phantom.state;

		phantom.click( play_elem );

	} else if ( document.location.href.match( /\/page\/draw$/ ) ) {
		// on drawing page
		// set color
		// generate a random number of strokes in editor
		//   set a direction
		//   continue in that direction
		var editor = document.getElementById('session-editor');
		// console.log( "  [canvas] width" + canvas_elem.width );
		// console.log( document.body.innerHTML );
		console.log( editor );

	} else {
		console.log("  [oops] unknown page");
		phantom.exit();
	}

}
<|endoftext|>