<commit_before>
// Wait for user to finish typing
// callback: The callback function
// wait: The number of milliseconds to wait after the the last key press before firing the callback
// highlight: Highlights the element when it receives focus
// allowSubmit: Allows a non-multiline element to be submitted (enter key) regardless of captureLength
// captureLength: Minimum # of characters necessary to fire the callback

$(document).ready(function() {

	//stop loader.gif and overlay
	stop_loader();

	//enable typewatch
	$('#street').typeWatch({
		captureLength: 2,
		wait: 1750,
    		highlight: true,
		callback: function(value) {
			//alert("typing finished");
			street_to_geo(value);
		}
	});
});

function start_loader(){
	$('#loader').fadeIn('slow');
	$('#overlay').fadeIn('slow');
}

function stop_loader(){
	$('#loader').fadeOut('slow');
	$('#overlay').fadeOut('slow');

}

function street_to_geo(street){
      //encodes the street string into url friendly format
      var street_encoded = encodeURIComponent(street);
      var uri = "https://nominatim.openstreetmap.org/search/" + street_encoded + "?format=json";
      //alert(uri);
      //makes the the jquery call and gets json back
      $.getJSON(uri, function(data) {
        //make js obj containing lat and long
        var obj = {latitude: data[0].lat, longitude: data[0].lon};
        alert(obj.latitude + " " + obj.longitude);
        //return obj;
      });
}

function calc_distance(lat1, lon1, lat2, lon2) {
	var unit = "K";
	var radlat1 = Math.PI * lat1/180;
	var radlat2 = Math.PI * lat2/180;
	var theta = lon1-lon2;
	var radtheta = Math.PI * theta/180;
	var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
	dist = Math.acos(dist);
	dist = dist * 180/Math.PI;
	dist = dist * 60 * 1.1515;
	if (unit=="K") { dist = dist * 1.609344; }
	if (unit=="N") { dist = dist * 0.8684; }
	return dist;
}

function get_places(lat, long, category) {
	var url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json";
	var method = "POST";
	var postData = "";	// TODO get key
	postData += "location=" + lat + "," + long;
	postData += "radius=5000";	// 5km, could be changed or added as a configurable later
	postData += "type=" + category;

	// if it is not true, it'll block ALL execution waiting for server response.
	var shouldBeAsync = true;

	var request = new XMLHttpRequest();

	// This function attached to the XMLHttpRequest "onload" property specifies how the HTTP response will be handled.
	// request.onreadystatechange can also be used if this doesn't work
	request.onload = function () {
		// You can get all kinds of information about the HTTP response.
		var status = request.status; // HTTP response status, e.g., 200 for "200 OK"
		var data = request.responseText; // Returned data, e.g., an HTML document.

		var jsObj = null;

		if (status == 200) {
			jsObj = data.results;
			add_details(jsObj, lat, long);
			sort_json(jsObj, 'rating_over_distance', false);	// false because we want descending order
		}

		// TODO: call whatever needs to use the jsObj
	}

	request.open(method, url, shouldBeAsync);

	request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");

	// Actually sends the request to the server.
	request.send(postData);
}

function add_details(json_object, lat, long) {
	for ( x in json_object) {
		json_object[x].distance = calc_distance(lat, lon, json_object[x].geometry.location.lat, json_object[x].geometry.location.lng);
		json_object[x].rating_over_distance = json_object[x].rating/json_object[x].distance;
	}
}

function sort_json(json_object, key_to_sort_by, ascending) {
    function sortByKey(a, b) {
        var x = a[key_to_sort_by];
        var y = b[key_to_sort_by];
        if (ascending ==  true) {
        	return ((x < y) ? -1 : ((x > y) ? 1 : 0));
        } else {
        	return ((x > y) ? -1 : ((x < y) ? 1 : 0));
        }
    }

    json_object.sort(sortByKey);
}

//returns a Coordinate, could add some other functionality of what to do when geolocation is not supported
var pos;
function get_my_location(){
	var options = {
	  enableHighAccuracy: true
	};
	if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(function(position) {
        pos = {
          lat: position.coords.latitude,
          lng: position.coords.longitude
        };

	      //return pos;
		var location = pos.lat + " " + pos.lng;
		alert(location);
      },
      function(err){},
      options);
    }

}

function get_weather(lat, lon){

	//if the function does not work, maybe the get_json.php should be in root, or path should be js/get_json.php

    var api_url = "js/get_json.php?";
    var type = "type=weather"

	api_request = api_url;
    api_request += type;
    api_request += "&lat="
    api_request += lat;
    api_request += "&lon="
    api_request += lon;

    //document.write(api_request);

    $(function () {
        $.getJSON(
            api_request,
            function (data) {
                $("#reply").html(JSON.stringify(data));
                return(JSON.stringify(data.weather[0].main));
            });
    });

}
<commit_msg>Update main.js<commit_after>
// Wait for user to finish typing
// callback: The callback function
// wait: The number of milliseconds to wait after the the last key press before firing the callback
// highlight: Highlights the element when it receives focus
// allowSubmit: Allows a non-multiline element to be submitted (enter key) regardless of captureLength
// captureLength: Minimum # of characters necessary to fire the callback

$(document).ready(function() {

	//stop loader.gif and overlay
	stop_loader();

	//enable typewatch
	$('#street').typeWatch({
		captureLength: 2,
		wait: 1750,
    		highlight: true,
		callback: function(value) {
			//alert("typing finished");
			street_to_geo(value);
		}
	});
});

function start_loader(){
	$('#loader').fadeIn('slow');
	$('#overlay').fadeIn('slow');
}

function stop_loader(){
	$('#loader').fadeOut('slow');
	$('#overlay').fadeOut('slow');

}

function street_to_geo(street){
      //encodes the street string into url friendly format
      var street_encoded = encodeURIComponent(street);
      var uri = "https://nominatim.openstreetmap.org/search/" + street_encoded + "?format=json";
      //alert(uri);
      //makes the the jquery call and gets json back
      $.getJSON(uri, function(data) {
        //make js obj containing lat and long
        var obj = {latitude: data[0].lat, longitude: data[0].lon};
        alert(obj.latitude + " " + obj.longitude);
        //return obj;
      });
}

function calc_distance(lat1, lon1, lat2, lon2) {
	var unit = "K";
	var radlat1 = Math.PI * lat1/180;
	var radlat2 = Math.PI * lat2/180;
	var theta = lon1-lon2;
	var radtheta = Math.PI * theta/180;
	var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
	dist = Math.acos(dist);
	dist = dist * 180/Math.PI;
	dist = dist * 60 * 1.1515;
	if (unit=="K") { dist = dist * 1.609344; }
	if (unit=="N") { dist = dist * 0.8684; }
	return dist;
}

function get_places(lat, long, category) {
	var url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json";
	var method = "POST";
	var postData = "";	// TODO get key
	postData += "location=" + lat + "," + long;
	postData += "radius=5000";	// 5km, could be changed or added as a configurable later
	postData += "type=" + category;

	// if it is not true, it'll block ALL execution waiting for server response.
	var shouldBeAsync = true;

	var request = new XMLHttpRequest();

	// This function attached to the XMLHttpRequest "onload" property specifies how the HTTP response will be handled.
	// request.onreadystatechange can also be used if this doesn't work
	request.onload = function () {
		// You can get all kinds of information about the HTTP response.
		var status = request.status; // HTTP response status, e.g., 200 for "200 OK"
		var data = request.responseText; // Returned data, e.g., an HTML document.

		var jsObj = null;

		if (status == 200) {
			jsObj = data.results;
			add_details(jsObj, lat, long);
			sort_json(jsObj, 'rating_over_distance', false);	// false because we want descending order
		}

		// TODO: call whatever needs to use the jsObj
	}

	request.open(method, url, shouldBeAsync);

	request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");

	// Actually sends the request to the server.
	request.send(postData);
}

function add_details(json_object, lat, long) {
	for ( x in json_object) {
		json_object[x].distance = calc_distance(lat, lon, json_object[x].geometry.location.lat, json_object[x].geometry.location.lng);
		json_object[x].rating_over_distance = json_object[x].rating/json_object[x].distance;
	}
}

function sort_json(json_object, key_to_sort_by, ascending) {
    function sortByKey(a, b) {
        var x = a[key_to_sort_by];
        var y = b[key_to_sort_by];
        if (ascending ==  true) {
        	return ((x < y) ? -1 : ((x > y) ? 1 : 0));
        } else {
        	return ((x > y) ? -1 : ((x < y) ? 1 : 0));
        }
    }

    json_object.sort(sortByKey);
}

//returns a Coordinate, could add some other functionality of what to do when geolocation is not supported
var pos;
function get_my_location(){
	start_loader();
	var options = {
	  enableHighAccuracy: true
	};
	if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(function(position) {
        pos = {
          lat: position.coords.latitude,
          lng: position.coords.longitude
        };

	      //return pos;
		var location = pos.lat + " " + pos.lng;
	      	stop_loader();
		alert(location);
      },
      function(err){stop_loader();},
      options);
    }

}

function get_weather(lat, lon){

	//if the function does not work, maybe the get_json.php should be in root, or path should be js/get_json.php

    var api_url = "js/get_json.php?";
    var type = "type=weather"

	api_request = api_url;
    api_request += type;
    api_request += "&lat="
    api_request += lat;
    api_request += "&lon="
    api_request += lon;

    //document.write(api_request);

    $(function () {
        $.getJSON(
            api_request,
            function (data) {
                $("#reply").html(JSON.stringify(data));
                return(JSON.stringify(data.weather[0].main));
            });
    });

}
<|endoftext|>


<commit_before>function LWConsole() {
    var consoleDiv = document.getElementById("lwConsole");
    var consoleOutDOM = document.getElementById("consoleOut");
    var consoleInDOM = document.getElementById("consoleIn");
    var consoleOut = "";
    var motd = "Welcome to " + window.location.hostname + "\nType 'help' for help.\n";
    var commands = [
        {
            name: "help",
            description: "Shows a list of commands",
            visible: true,
            handler: helpCMD
        },
        {
            name: "motd",
            description: "Shows the message of the day",
            visible: true,
            handler: function () {
                return motd;
            }
        },
        {
            name: "echo",
            description: "Displays message on console - no pipes yet :-(",
            visible: true,
            handler: echoCMD
        },
        {
            name: "invert",
            description: "Invert website colors",
            visible: true,
            handler: function () {
                util.toggleInvert();
                return "Page inverted!";
            }
        },
        {
            name: "clear",
            description: "Clears the console",
            visible: true, //Visible in help page?
            handler: function () {
                consoleOut = "";
                consoleOutDOM.value = consoleOut;
            }
        },
        {
            name: "exit",
            description: "Exit console",
            visible: true,
            handler: function () {
                util.toggleConsole();
            }
        },
        {
            name: "kleinhase",
            description: "Secret message",
            visible: false,
            handler: function () {
                return "<3";
            }
        }
    ];

    //Get initial state depending on dom
    this.visible = window.getComputedStyle(consoleDiv).getPropertyValue("visibility") === "visible";

    //Attach key handler to enter key
    document.addEventListener("keydown", function (e) {
        if (consoleInDOM === document.activeElement && e.keyCode == 13) {
            var value = consoleInDOM.value;
            if (value === "") { //Do not trigger cmd when input is empty
                return;
            }
            sendCMD(value);
            consoleInDOM.value = ""; //Empty after cmd sent
        }
    });

    //Set initial content of textarea
    print(motd);

    //Methods ======================================

    this.show = function (state) {
        if (state) {
            consoleDiv.style.visibility = "visible";
            this.visible = true;
            //Set focus to console
            consoleInDOM.focus();
        }
        else {
            consoleDiv.style.visibility = "hidden";
            this.visible = false;
        }
    };

    this.isVisible = function () {
        return this.visible;
    };

    /**
     * Prints message to console and updates cursor position (scroll)
     * @param str message to print
     */
    function print(str) {
        if (str) {
            consoleOut += str + "\n"; //Append string to print and newline
            consoleOutDOM.value = consoleOut; //update textarea text
            consoleOutDOM.scrollTop = consoleOutDOM.scrollHeight; //scroll down in textarea for console-like behavior
        }
    }

    /**
     * Executes user cmd and updates output accordingly
     * @param cmd raw cmd by user
     */
    function sendCMD(cmd) {
        var splitCMD = cmd.split(" "); //split cmd by space (cmd name, args)
        print("> " + cmd); //Print cmd from user
        print(executeCMD(splitCMD)); //Print result of cmd-execution
    }

    function executeCMD(cmd) {
        for (var c in commands) {
            if (commands[c].name === cmd[0]) {
                cmd.shift(); //remove cmd name from array, only leaving args
                return commands[c].handler(cmd); //Execute handler with array of args
            }
        }
        return "Unknown command.";
    }

    // Command handlers

    function helpCMD() {
        var msg = "Available commands:";
        for (var c in commands) {
            if (commands[c].visible) {
                msg += "\n" + commands[c].name + ": " + commands[c].description;
            }
        }
        return msg;
    }

    function echoCMD(args) {
        var init = true;
        var str = "";

        for (var arg in args) {
            if (!init) {
                str += " ";
            }
            init = false;
            str += args[arg];
        }
        return str;
    }
}

function JSUtil() {
    var isInverted = false;
    var lwConsole = new LWConsole();

    function invert(state) {
        var invertStr;
        if (state) {
            invertStr = "100%";
        }
        else {
            invertStr = "0%";
        }
        document.getElementById("monitor").style.filter = "invert(" + invertStr + ")";
    }

    this.toggleInvert = function () {
        isInverted = !isInverted;
        invert(isInverted);
    };

    this.toggleConsole = function () {
        lwConsole.show(!lwConsole.isVisible());
    }
}
var util = new JSUtil();<commit_msg>ignore case in command name<commit_after>function LWConsole() {
    var consoleDiv = document.getElementById("lwConsole");
    var consoleOutDOM = document.getElementById("consoleOut");
    var consoleInDOM = document.getElementById("consoleIn");
    var consoleOut = "";
    var motd = "Welcome to " + window.location.hostname + "\nType 'help' for help.\n";
    var commands = [
        {
            name: "help",
            description: "Shows a list of commands",
            visible: true,
            handler: helpCMD
        },
        {
            name: "motd",
            description: "Shows the message of the day",
            visible: true,
            handler: function () {
                return motd;
            }
        },
        {
            name: "echo",
            description: "Displays message on console - no pipes yet :-(",
            visible: true,
            handler: echoCMD
        },
        {
            name: "invert",
            description: "Invert website colors",
            visible: true,
            handler: function () {
                util.toggleInvert();
                return "Page inverted!";
            }
        },
        {
            name: "clear",
            description: "Clears the console",
            visible: true, //Visible in help page?
            handler: function () {
                consoleOut = "";
                consoleOutDOM.value = consoleOut;
            }
        },
        {
            name: "exit",
            description: "Exit console",
            visible: true,
            handler: function () {
                util.toggleConsole();
            }
        },
        {
            name: "kleinhase",
            description: "Secret message",
            visible: false,
            handler: function () {
                return "<3";
            }
        }
    ];

    //Get initial state depending on dom
    this.visible = window.getComputedStyle(consoleDiv).getPropertyValue("visibility") === "visible";

    //Attach key handler to enter key
    document.addEventListener("keydown", function (e) {
        if (consoleInDOM === document.activeElement && e.keyCode == 13) {
            var value = consoleInDOM.value;
            if (value === "") { //Do not trigger cmd when input is empty
                return;
            }
            sendCMD(value);
            consoleInDOM.value = ""; //Empty after cmd sent
        }
    });

    //Set initial content of textarea
    print(motd);

    //Methods ======================================

    this.show = function (state) {
        if (state) {
            consoleDiv.style.visibility = "visible";
            this.visible = true;
            //Set focus to console
            consoleInDOM.focus();
        }
        else {
            consoleDiv.style.visibility = "hidden";
            this.visible = false;
        }
    };

    this.isVisible = function () {
        return this.visible;
    };

    /**
     * Prints message to console and updates cursor position (scroll)
     * @param str message to print
     */
    function print(str) {
        if (str) {
            consoleOut += str + "\n"; //Append string to print and newline
            consoleOutDOM.value = consoleOut; //update textarea text
            consoleOutDOM.scrollTop = consoleOutDOM.scrollHeight; //scroll down in textarea for console-like behavior
        }
    }

    /**
     * Executes user cmd and updates output accordingly
     * @param cmd raw cmd by user
     */
    function sendCMD(cmd) {
        var splitCMD = cmd.split(" "); //split cmd by space (cmd name, args)
        print("> " + cmd); //Print cmd from user
        print(executeCMD(splitCMD)); //Print result of cmd-execution
    }

    function executeCMD(cmd) {
        for (var c in commands) {
            if (commands[c].name === cmd[0].toLowerCase()) {
                cmd.shift(); //remove cmd name from array, only leaving args
                return commands[c].handler(cmd); //Execute handler with array of args
            }
        }
        return "Unknown command.";
    }

    // Command handlers

    function helpCMD() {
        var msg = "Available commands:";
        for (var c in commands) {
            if (commands[c].visible) {
                msg += "\n" + commands[c].name + ": " + commands[c].description;
            }
        }
        return msg;
    }

    function echoCMD(args) {
        var init = true;
        var str = "";

        for (var arg in args) {
            if (!init) {
                str += " ";
            }
            init = false;
            str += args[arg];
        }
        return str;
    }
}

function JSUtil() {
    var isInverted = false;
    var lwConsole = new LWConsole();

    function invert(state) {
        var invertStr;
        if (state) {
            invertStr = "100%";
        }
        else {
            invertStr = "0%";
        }
        document.getElementById("monitor").style.filter = "invert(" + invertStr + ")";
    }

    this.toggleInvert = function () {
        isInverted = !isInverted;
        invert(isInverted);
    };

    this.toggleConsole = function () {
        lwConsole.show(!lwConsole.isVisible());
    }
}
var util = new JSUtil();<|endoftext|>


<commit_before>
<commit_msg>Add target=_blank behavior<commit_after>;(function() {
    document.body.addEventListener && document.body.addEventListener('click',
        function(e) {
            if(e.target.tagName === 'A') {
                e.preventDefault();
                window.open(e.target.href);
            }
        }
    );
}());
<|endoftext|>


<commit_before>var _url = '', _selector = null, _width = 500, _height = 500, _gravity = -0.01, _damper = 0.1, _center = null, _data = null, _vis = null, _circles = null, _force = null, _fill_color = null, _radius_scale = null, _p_centers = [];

var _charge = function(d){ return -Math.pow(d.radius, 2.0) / 8; };

var _buoyancy = function(alpha) {
    return function(d) {
        var val = d.y * 0.05 * alpha * alpha * alpha * 100;
        d.y = (d.color === '#d84b2a') ? d.y + val : (d.color === '#7aa25c') ? d.y - val : d.y;
    };
};

var _move_towards_center = function(alpha){
    return function(d) {
        d.x = d.x + (_center.x - d.x) * (_damper + 0.02) * alpha;
        d.y = d.y + (_center.y - d.y) * (_damper + 0.02) * alpha;
    };
};

var _move_towards_process = function(alpha) {
    return function(d) {
        var target = _p_centers[d.process];
        d.x = d.x + (target.x - d.x) * (_damper + 0.02) * alpha * 1.1;
        d.y = d.y + (target.y - d.y) * (_damper + 0.02) * alpha * 1.1;
    };
};

var _display_group_all = function() {
    _force.gravity(_gravity)
        .charge(_charge)
        .friction(0.9)
        .on('tick', function(e) {
            _circles.each(_move_towards_center(e.alpha)).each(_buoyancy(e.alpha))
            .attr('cx', function(d) {
                return d.x;
            })
            .attr('cy', function(d) {
                return d.y;
            });
        })
        .start();
};

var _display_by_process = function(){
    _force.gravity(_gravity)
        .charge(_charge)
        .friction(0.9)
        .on('tick', function(e) {
            _circles
                .each(_move_towards_process(e.alpha))
                .attr('cx', function(d) { return d.x; })
                .attr('cy', function(d) { return d.y; });
        })
        .start();
};

var _create_vis = function(){
    _vis = d3.select(_selector).append('svg').attr('width', _width).attr('height', _height).attr('id', 'svg_vis');
    _circles = _vis.selectAll('circle').data(_data.nodes, function(d){ return d.id; });

    _circles.enter().append('circle')
        .attr('r', function(d){return d.radius;})
        .attr('fill', function(d){ return d.color; })
        .attr('id', function(d) { return 'bubble_' + d.id; })
        .on('mouseover', function(d, i) {
            console.log('mouseover');
        }).on('mouseout', function(d, i) {
            console.log('mouseout');
        })
        .on('click', function(d){console.log(d);});

    _center = { x:_width/2, y: _height/2 };
    _force = d3.layout.force().nodes(_data.nodes).size([_width, _height]);
    _display_group_all();
};

var _format_data = function(json){

    var max_abs_log2 = d3.max(json.nodes, function(d) {
        return Math.abs(d.Log2fold_change);
    });

    _radius_scale = d3.scale.log().domain([1, max_abs_log2 + 1 ]).range([0.5, 40]);

    json.nodes = _.map(json.nodes, function(d){
        var val = Math.abs(d.Log2fold_change) + 1;
        d.radius = _radius_scale(val);
        d.color = (d.Log2fold_change > 1.5) ? '#7aa25c' : (d.Log2fold_change < - 1.5) ? '#d84b2a' : (d.p_value < 0.05 && d.Log2fold_change > 0) ? '#7aa25c' : (d.p_value < 0.05 && d.Log2fold_change < 0) ? '#d84b2a' : '#beccae';
        return d;
    });

    _data = json;
    _calc_process_centers();
};

var _calc_process_centers = function(){

    var rows = 4, cols = 5;
    var wScale = d3.scale.linear().domain([0, rows]).range([250, _width]);
    var hScale = d3.scale.linear().domain([0, cols]).range([250, _height]);

    _p_centers = _.groupBy(_data.nodes, function(n){ return n.process; });
    _p_centers = _.each(_p_centers, function(val, key){
        var affected = _.filter(val, function(n){ return (n.color === '#d84b2a' || n.color === '#7aa25c'); }).length;
        _p_centers[key] = {genes:val, x:wScale(this.row), y:hScale(this.col), percentage: (affected * 100)/ val.length};

        if(this.row < rows -1){
            this.row ++;
        }else{
            this.col ++;
            this.row =0;
        }

    }, {col:0,row:0});

    console.log(_p_centers);
};

//Public members
var App = function(){};

App.url = function(_){
    if (!arguments.length)
        return _url;
    _url = _;
    return App;
};

App.selector = function(_){
    if (!arguments.length)
        return _selector;
    _selector = _;
    return App;
};

App.width = function(_){
    if (!arguments.length)
        return _width;
    _width = _;
    return App;
};

App.height = function(_){
    if (!arguments.length)
        return _height;
    _height = _;
    return App;
};

App.displayTowardProcess = function(){
    _display_by_process();
};

App.displayGroupAll = function(){
    _display_group_all();
};

App.init = function(){
    d3.json(_url, function(error, json) {
        if (error) return console.warn(error);
        _format_data(json);
        _create_vis();
    });
};

module.exports = App;<commit_msg>transition node radius<commit_after>var _url = '', _selector = null, _width = 500, _height = 500, _gravity = -0.01, _damper = 0.1, _center = null, _data = null, _vis = null, _circles = null, _force = null, _fill_color = null, _radius_scale = null, _p_centers = [];

var _charge = function(d){ return -Math.pow(d.radius, 2.0) / 8; };

var _buoyancy = function(alpha) {
    return function(d) {
        var val = d.y * 0.05 * alpha * alpha * alpha * 100;
        d.y = (d.color === '#d84b2a') ? d.y + val : (d.color === '#7aa25c') ? d.y - val : d.y;
    };
};

var _move_towards_center = function(alpha){
    return function(d) {
        d.x = d.x + (_center.x - d.x) * (_damper + 0.02) * alpha;
        d.y = d.y + (_center.y - d.y) * (_damper + 0.02) * alpha;
    };
};

var _move_towards_process = function(alpha) {
    return function(d) {
        var target = _p_centers[d.process];
        d.x = d.x + (target.x - d.x) * (_damper + 0.02) * alpha * 1.1;
        d.y = d.y + (target.y - d.y) * (_damper + 0.02) * alpha * 1.1;
    };
};

var _display_group_all = function() {
    _force.gravity(_gravity)
        .charge(_charge)
        .friction(0.9)
        .on('tick', function(e) {
            _circles.each(_move_towards_center(e.alpha)).each(_buoyancy(e.alpha))
            .attr('cx', function(d) {
                return d.x;
            })
            .attr('cy', function(d) {
                return d.y;
            });
        })
        .start();
};

var _display_by_process = function(){
    _force.gravity(_gravity)
        .charge(_charge)
        .friction(0.9)
        .on('tick', function(e) {
            _circles
                .each(_move_towards_process(e.alpha))
                .attr('cx', function(d) { return d.x; })
                .attr('cy', function(d) { return d.y; });
        })
        .start();
};

var _create_vis = function(){
    _vis = d3.select(_selector).append('svg').attr('width', _width).attr('height', _height).attr('id', 'svg_vis');
    _circles = _vis.selectAll('circle').data(_data.nodes, function(d){ return d.id; });

    _circles.enter().append('circle')
        .attr('r', 0)
        .attr('fill', function(d){ return d.color; })
        .attr('id', function(d) { return 'bubble_' + d.id; })
        .on('mouseover', function(d, i) {
            console.log('mouseover');
        }).on('mouseout', function(d, i) {
            console.log('mouseout');
        })
        .on('click', function(d){console.log(d);})
        .transition().duration(2000).attr("r", function(d) {
            return d.radius;
        });

    _center = { x:_width/2, y: _height/2 };
    _force = d3.layout.force().nodes(_data.nodes).size([_width, _height]);
    _display_group_all();
};

var _format_data = function(json){

    var max_abs_log2 = d3.max(json.nodes, function(d) {
        return Math.abs(d.Log2fold_change);
    });

    _radius_scale = d3.scale.log().domain([1, max_abs_log2 + 1 ]).range([0.5, 40]);

    json.nodes = _.map(json.nodes, function(d){
        var val = Math.abs(d.Log2fold_change) + 1;
        d.radius = _radius_scale(val);
        d.color = (d.Log2fold_change > 1.5) ? '#7aa25c' : (d.Log2fold_change < - 1.5) ? '#d84b2a' : (d.p_value < 0.05 && d.Log2fold_change > 0) ? '#7aa25c' : (d.p_value < 0.05 && d.Log2fold_change < 0) ? '#d84b2a' : '#beccae';
        return d;
    });

    _data = json;
    _calc_process_centers();
};

var _calc_process_centers = function(){

    var rows = 4, cols = 5;
    var wScale = d3.scale.linear().domain([0, rows]).range([250, _width]);
    var hScale = d3.scale.linear().domain([0, cols]).range([250, _height]);

    _p_centers = _.groupBy(_data.nodes, function(n){ return n.process; });
    _p_centers = _.each(_p_centers, function(val, key){
        var affected = _.filter(val, function(n){ return (n.color === '#d84b2a' || n.color === '#7aa25c'); }).length;
        _p_centers[key] = {genes:val, x:wScale(this.row), y:hScale(this.col), percentage: (affected * 100)/ val.length};

        if(this.row < rows -1){
            this.row ++;
        }else{
            this.col ++;
            this.row =0;
        }

    }, {col:0,row:0});

    console.log(_p_centers);
};

//Public members
var App = function(){};

App.url = function(_){
    if (!arguments.length)
        return _url;
    _url = _;
    return App;
};

App.selector = function(_){
    if (!arguments.length)
        return _selector;
    _selector = _;
    return App;
};

App.width = function(_){
    if (!arguments.length)
        return _width;
    _width = _;
    return App;
};

App.height = function(_){
    if (!arguments.length)
        return _height;
    _height = _;
    return App;
};

App.displayTowardProcess = function(){
    _display_by_process();
};

App.displayGroupAll = function(){
    _display_group_all();
};

App.init = function(){
    d3.json(_url, function(error, json) {
        if (error) return console.warn(error);
        _format_data(json);
        _create_vis();
    });
};

module.exports = App;<|endoftext|>


<commit_before>/* jshint browser: true, devel: true, indent: 2, curly: true, eqeqeq: true, futurehostile: true, latedef: true, undef: true, unused: true */
/* global $, jQuery, document, Site, Modernizr */

Site = {
  mobileThreshold: 601,
  init: function() {
    var _this = this;

    $(window).resize(function(){
      _this.onResize();
    });

    $(document).ready(function () {

    });

    if ($('body').hasClass('single-programacion')) {
      _this.Programacion.Single.init();
    }

    if ($('body').hasClass('blog') || $('body').hasClass('single-post')) {
      _this.Noticias.init();
    }

  },

  onResize: function() {
    var _this = this;

  },

  fixWidows: function() {
    // utility class mainly for use on headines to avoid widows [single words on a new line]
    $('.js-fix-widows').each(function(){
      var string = $(this).html();
      string = string.replace(/ ([^ ]*)$/,' $1');
      $(this).html(string);
    });
  },
};

Site.Programacion = {

  Single: {
    init: function() {
      var _this = this;

      $(document).ready(function () {
        _this.initGallery();
      });
    },

    initGallery: function() {
      var _this = this;

      _this.swiper = new Swiper('.swiper-container', {
        loop: true,
        nextButton: '.swiper-next',
        prevButton: '.swiper-prev',
        pagination: '#single-programacion-gallery-pagination',
        paginationType: 'custom',
        paginationCustomRender: function (swiper, current, total) {
          return '' + current + ' / ' + total + '';
        },
        onClick: function(swiper) {
          swiper.slideNext();
        },
      });
    },
  }

};

Site.Noticias = {
  init: function() {
    this.Galleries.init();
  },

  Galleries: {
    init: function() {
      $('.swiper-container').each(function() {
        var swiper = new Swiper($(this), {
          loop: true,
          onClick: function(swiper) {
            swiper.slideNext();
          },
        });
      });
    },
  }
}

Site.init();<commit_msg>add masonry init<commit_after>/* jshint browser: true, devel: true, indent: 2, curly: true, eqeqeq: true, futurehostile: true, latedef: true, undef: true, unused: true */
/* global $, jQuery, document, Site, Modernizr */

Site = {
  mobileThreshold: 601,
  init: function() {
    var _this = this;

    $(window).resize(function(){
      _this.onResize();
    });

    $(document).ready(function () {

    });

    if ($('body').hasClass('single-programacion')) {
      _this.Programacion.Single.init();
    }

    if ($('body').hasClass('blog') || $('body').hasClass('single-post')) {
      _this.Noticias.init();
    }

    if ($('body').hasClass('page-home') || $('body').hasClass('page-citas')) {
      _this.layoutMasonry();
    }

  },

  onResize: function() {
    var _this = this;

  },

  fixWidows: function() {
    // utility class mainly for use on headines to avoid widows [single words on a new line]
    $('.js-fix-widows').each(function(){
      var string = $(this).html();
      string = string.replace(/ ([^ ]*)$/,' $1');
      $(this).html(string);
    });
  },

  layoutMasonry: function() {
    if ($('.home-item').length) {
      var $masonry = $('#home-holder').masonry({
        itemSelector: '.home-item',
        //columnWidth: '.home-item',
      });

      $masonry.imagesLoaded().progress( function() {
        $masonry.masonry('layout');
      });
    }
  }
};

Site.Programacion = {

  Single: {
    init: function() {
      var _this = this;

      $(document).ready(function () {
        _this.initGallery();
      });
    },

    initGallery: function() {
      var _this = this;

      _this.swiper = new Swiper('.swiper-container', {
        loop: true,
        nextButton: '.swiper-next',
        prevButton: '.swiper-prev',
        pagination: '#single-programacion-gallery-pagination',
        paginationType: 'custom',
        paginationCustomRender: function (swiper, current, total) {
          return '' + current + ' / ' + total + '';
        },
        onClick: function(swiper) {
          swiper.slideNext();
        },
      });
    },
  }

};

Site.Noticias = {
  init: function() {
    this.Galleries.init();
  },

  Galleries: {
    init: function() {
      $('.swiper-container').each(function() {
        var swiper = new Swiper($(this), {
          loop: true,
          onClick: function(swiper) {
            swiper.slideNext();
          },
        });
      });
    },
  }
}

Site.init();<|endoftext|>


<commit_before>var width = 1100;
var height = 700;
var value = 0;
var context;
var balls = [
  {active:true,x:200,y:200,dx:.707,dy:.707,color:"#0000ff",radius:20,damage:0},
  {active:true,x:100,y:100,dx:-.707,dy:.707,color:"#ff0000",radius:10,damage:0},
  {active:true,x:300,y:300,dx:.707,dy:-.707,color:"#00ff00",radius:30,damage:0},
  {active:false,x:400,y:400,dx:-1,dy:-1,color:"#ffff00",radius:15,damage:0}
]
var enemies = [
  {x:50,y:50,health:100,active:true,color:"#000000",radius:30},
  {x:50,y:120,health:200,active:false,color:"#000000",radius:30},
  {x:50,y:200,health:100,active:true,color:"#000000",radius:30},
  {x:650,y:50,health:100,active:true,color:"#000000",radius:30},
  {x:650,y:200,health:100,active:true,color:"#000000",radius:30},
  {x:850,y:500,health:100,active:true,color:"#000000",radius:30},
  {x:850,y:600,health:100,active:true,color:"#000000",radius:30},
]
function addValue()
{
  value = value + 1;
  document.getElementById("value").innerHTML = value;
}
function init()
{
  context= myCanvas.getContext('2d');
  setInterval(draw,10);
}

function draw(){
  context.clearRect(0,0,width,height);
  for(var i = 0; i<enemies.length; i++){
    var enemyDraw = enemies[i];
    if(enemyDraw.active){
      context.beginPath();
      context.fillStyle=enemyDraw.color;
      context.arc(enemyDraw.x,enemyDraw.y,enemyDraw.radius,0,Math.PI*2,true);
      context.closePath();
      context.fill();
    }
  }
  for(var i = 0; i<balls.length; i++){
    var ball = balls[i]
    if(ball.active){
      context.beginPath();
      context.fillStyle=ball.color;
      context.arc(ball.x,ball.y,ball.radius,0,Math.PI*2,true);
      context.closePath();
      context.fill();
      for(var e = 0; e<enemies.length; e++){
        var enemy = enemies[e];
        if(enemy.active){
          if(Math.pow(ball.x-enemy.x,2)+Math.pow(ball.y-enemy.y,2)<=Math.pow(enemy.radius+ball.radius,2)){
            console.log("Collision");
            ball.dx = (ball.x - enemy.x)/Math.sqrt(Math.pow(ball.x-enemy.x,2)+Math.pow(ball.y-enemy.y,2));
            ball.dy = (ball.y - enemy.y)/Math.sqrt(Math.pow(ball.x-enemy.x,2)+Math.pow(ball.y-enemy.y,2));
          }
        }
      }
      if(ball.x<=ball.radius || ball.x>=(width-ball.radius)) ball.dx=-ball.dx;
      if(ball.y<=ball.radius || ball.y>=(height-ball.radius)) ball.dy=-ball.dy;
      ball.x+=ball.dx*4;
      ball.y+=ball.dy*4;
    }
  }
}
<commit_msg>Added ball damage<commit_after>var width = 1100;
var height = 700;
var value = 0;
var context;
var balls = [
  {active:true,x:200,y:200,dx:.707,dy:.707,color:"#0000ff",radius:20,damage:8},
  {active:true,x:100,y:100,dx:-.707,dy:.707,color:"#ff0000",radius:10,damage:20},
  {active:true,x:300,y:300,dx:.707,dy:-.707,color:"#00ff00",radius:30,damage:13},
  {active:false,x:400,y:400,dx:-1,dy:-1,color:"#ffff00",radius:15,damage:13}
]
var enemies = [
  {x:50,y:50,health:100,active:true,color:"#000000",radius:30},
  {x:50,y:120,health:100,active:false,color:"#000000",radius:30},
  {x:50,y:200,health:100,active:true,color:"#000000",radius:30},
  {x:650,y:50,health:200,active:true,color:"#000000",radius:30},
  {x:650,y:200,health:200,active:true,color:"#000000",radius:30},
  {x:850,y:500,health:300,active:true,color:"#000000",radius:30},
  {x:850,y:600,health:300,active:true,color:"#000000",radius:30},
]
function addValue()
{
  value = value + 1;
  document.getElementById("value").innerHTML = value;
}
function init()
{
  context= myCanvas.getContext('2d');
  setInterval(draw,10);
}

function draw(){
  context.clearRect(0,0,width,height);
  for(var i = 0; i<enemies.length; i++){
    var enemyDraw = enemies[i];
    if(enemyDraw.active){
      context.beginPath();
      context.fillStyle=enemyDraw.color;
      context.arc(enemyDraw.x,enemyDraw.y,enemyDraw.radius,0,Math.PI*2,true);
      context.closePath();
      context.fill();
    }
  }
  for(var i = 0; i<balls.length; i++){
    var ball = balls[i]
    if(ball.active){
      context.beginPath();
      context.fillStyle=ball.color;
      context.arc(ball.x,ball.y,ball.radius,0,Math.PI*2,true);
      context.closePath();
      context.fill();
      for(var e = 0; e<enemies.length; e++){
        var enemy = enemies[e];
        if(enemy.active){
          if(Math.pow(ball.x-enemy.x,2)+Math.pow(ball.y-enemy.y,2)<=Math.pow(enemy.radius+ball.radius,2)){
            if(enemy.health>ball.damage)
              {
                enemy.health -= ball.damage;
              }
            else
              {
                enemy.active = false;
              }
            ball.dx = (ball.x - enemy.x)/Math.sqrt(Math.pow(ball.x-enemy.x,2)+Math.pow(ball.y-enemy.y,2));
            ball.dy = (ball.y - enemy.y)/Math.sqrt(Math.pow(ball.x-enemy.x,2)+Math.pow(ball.y-enemy.y,2));
          }
        }
      }
      if(ball.x<=ball.radius || ball.x>=(width-ball.radius)) ball.dx=-ball.dx;
      if(ball.y<=ball.radius || ball.y>=(height-ball.radius)) ball.dy=-ball.dy;
      ball.x+=ball.dx*4;
      ball.y+=ball.dy*4;
    }
  }
}
<|endoftext|>


<commit_before>$(document).ready(function() {

	// Video Nav Functions
	$(".videoNav a").click(function(e) {
		e.preventDefault();
		video.src = $(this).attr('href');
		//video.muted = true;

		$(".videoNav a.active").removeClass("active");
		$(this).addClass("active");
	})

	// About area close/open scripts
	$(".about .aboutClose").click(function(e) {
		e.preventDefault();
		$(".about").slideUp();
	});

	$(".aboutOpen").click(function(e) {
		e.preventDefault();
		$(".about").slideDown();
	});

	// Video Controls Functions
	$(".playButton").click(function(e) {
		video.play();
		$(".pauseButton").removeClass('active');
		$(".playButton").addClass('active');
		e.preventDefault();
	});

	$(".pauseButton").click(function(e) {
		video.pause();
		$(".pauseButton").addClass('active');
		$(".playButton").removeClass('active');
		e.preventDefault();
	});

	$(".muteButton").click(function(e) {
		video.muted = video.muted == false;
		if(video.muted) {
			$(".muteButton i").removeClass('icon-volume-high');
			$(".muteButton i").addClass('icon-volume-off');
		} else {
			$(".muteButton i").addClass('icon-volume-high');
			$(".muteButton i").removeClass('icon-volume-off');
		}
		e.preventDefault();
	});

	init();
	animate();

});

window.app = {};

var camera, scene, renderer, stats;

var video, texture;

var fov = 36,
texture_placeholder,
isUserInteracting = false,

// GLOBALS FOR TRACKING MOUSE
onMouseDownMouseX = 0, onMouseDownMouseY = 0,
lon = 0, onMouseDownLon = 0,
lat = 45, onMouseDownLat = 0,
phi = 0, theta = 0;
var ldr;
var videoStarted = false;

function init() {

	var container, mesh;

	container = document.getElementById( 'container' );
	scene = new THREE.Scene();
	camera = new THREE.PerspectiveCamera( fov, window.innerWidth / window.innerHeight, .1, 1000 );

	video = document.createElement( 'video' );
	video.loop = "loop";
	video.muted = true;

	// Report video load complete
	video.addEventListener("ended", function(e) {
		$(".pct").text("100% loaded.");
		// DEBUG
		console.log("done");
	});

	// Progress Meter
	video.addEventListener("progress", function(e) {
		var percent = null;
		    if (video && video.buffered && video.buffered.length > 0 && video.buffered.end && video.duration) {
		        percent = video.buffered.end(0) / video.duration;
		    }
		    // Some browsers (e.g., FF3.6 and Safari 5) cannot calculate target.bufferered.end()
		    // to be anything other than 0. If the byte count is available we use this instead.
		    // Browsers that support the else if do not seem to have the bufferedBytes value and
		    // should skip to there. Tested in Safari 5, Webkit head, FF3.6, Chrome 6, IE 7/8.
		    else if (video && video.bytesTotal != undefined && video.bytesTotal > 0 && video.bufferedBytes != undefined) {
		        percent = video.bufferedBytes / video.bytesTotal;
		    }

		   	var cpct = Math.round(percent * 100);
		   	if(cpct == 100) {
		   		$(".percentLoaded").fadeOut();
		   	} else {
		   		$(".pct").text(cpct + "% loaded.");
		   	}

	});

	// Video Play Listener, fires after video loads
	video.addEventListener("canplaythrough", function(e) {
		video.play();
	});

	// DEBUG
	window.v = video;

	video.src = $(".videoNav li:first-child a").attr("href");

	renderer = new THREE.WebGLRenderer();
	renderer.setSize( window.innerWidth, window.innerHeight );
	container.appendChild( renderer.domElement );

	texture = new THREE.Texture( video );
	texture.minFilter = THREE.LinearFilter;
	texture.magFilter = THREE.LinearFilter;

	mesh = new THREE.Mesh( new THREE.SphereGeometry( 500, 80, 50 ), new THREE.MeshBasicMaterial( { map: texture } ) );
	mesh.scale.x = -1;
	scene.add( mesh );

	// displays current and past frames per second attained by scene
	stats = new Stats();
	stats.domElement.style.position = 'absolute';
	stats.domElement.style.bottom = '0px';
	stats.domElement.style.zIndex = 100;
	container.appendChild( stats.domElement );

	document.addEventListener( 'mousedown', onDocumentMouseDown, false );
	document.addEventListener( 'mousemove', onDocumentMouseMove, false );
	document.addEventListener( 'mouseup', onDocumentMouseUp, false );
	document.addEventListener( 'mousewheel', onDocumentMouseWheel, false );
	document.addEventListener( 'DOMMouseScroll', onDocumentMouseWheel, false);

}

function onDocumentMouseDown( event ) {

	event.preventDefault();

	isUserInteracting = true;

}

function onDocumentMouseMove( event ) {
	onPointerDownPointerX = event.clientX;
	onPointerDownPointerY = -event.clientY;

	onPointerDownLon = lon;
	onPointerDownLat = lat;
	if ( 1 ) {

		lon = ( event.clientX / window.innerWidth ) * 430 - 45
		lat = ( event.clientY / window.innerHeight ) * -180 + 90

	}
}

function onDocumentMouseUp( event ) {

	isUserInteracting = false;

}

function onDocumentMouseWheel( event ) {

	var wheelSpeed = -.01;

	// WebKit

	if ( event.wheelDeltaY ) {

		fov -= event.wheelDeltaY * wheelSpeed;

	// Opera / Explorer 9

	} else if ( event.wheelDelta ) {

		fov -= event.wheelDelta * wheelSpeed;

	// Firefox

	} else if ( event.detail ) {

		fov += event.detail * 1.0;

	}

	var fovMin = 3;
	var fovMax = 100;

	if(fov < fovMin) {
		fov = fovMin;
	} else if(fov > fovMax) {
		fov = fovMax;
	}

	camera.setLens(fov)
	//render();

}

function animate() {

	requestAnimationFrame( animate );

	// run this the first time we play the video TODO: FIX THIS SO IT DOESN'T RUN ON EVERY DAMN FRAME
	if(!videoStarted) {

		if($("#loading").length > 0) {

			ldr = $("#loading");
			ldr.data("isLoading", true);

		}

		if ( video.readyState === video.HAVE_ENOUGH_DATA ) {

			if(ldr.data("isLoading") == true) {
				ldr.fadeOut('fast');
				ldr.data("isLoading", false);
			}

			videoStarted = true;

		}
	} else {
		if(!video.paused) {
			texture.needsUpdate = true;
		}

	}

	render();

}

function render() {

	lat = Math.max( - 85, Math.min( 85, lat ) );
	phi = ( 90 - lat ) * Math.PI / 180;
	theta = lon * Math.PI / 180;

	var cx = 500 * Math.sin( phi ) * Math.cos( theta );
	var cy = 500 * Math.cos( phi );
	var cz = 500 * Math.sin( phi ) * Math.sin( theta );

	camera.lookAt(new THREE.Vector3(cx, cy, cz));

	// distortion
	camera.position.x = - cx;
	camera.position.y = - cy;
	camera.position.z = - cz;
	stats.update();
	renderer.render( scene, camera );

}<commit_msg>converted to luminance only<commit_after>$(document).ready(function() {

	// Video Nav Functions
	$(".videoNav a").click(function(e) {
		e.preventDefault();
		video.src = $(this).attr('href');
		//video.muted = true;

		$(".videoNav a.active").removeClass("active");
		$(this).addClass("active");
	})

	// About area close/open scripts
	$(".about .aboutClose").click(function(e) {
		e.preventDefault();
		$(".about").slideUp();
	});

	$(".aboutOpen").click(function(e) {
		e.preventDefault();
		$(".about").slideDown();
	});

	// Video Controls Functions
	$(".playButton").click(function(e) {
		video.play();
		$(".pauseButton").removeClass('active');
		$(".playButton").addClass('active');
		e.preventDefault();
	});

	$(".pauseButton").click(function(e) {
		video.pause();
		$(".pauseButton").addClass('active');
		$(".playButton").removeClass('active');
		e.preventDefault();
	});

	$(".muteButton").click(function(e) {
		video.muted = video.muted == false;
		if(video.muted) {
			$(".muteButton i").removeClass('icon-volume-high');
			$(".muteButton i").addClass('icon-volume-off');
		} else {
			$(".muteButton i").addClass('icon-volume-high');
			$(".muteButton i").removeClass('icon-volume-off');
		}
		e.preventDefault();
	});

	init();
	animate();

});

window.app = {};

var camera, scene, renderer, stats;

var video, texture;

var fov = 36,
texture_placeholder,
isUserInteracting = false,

// GLOBALS FOR TRACKING MOUSE
onMouseDownMouseX = 0, onMouseDownMouseY = 0,
lon = 0, onMouseDownLon = 0,
lat = 45, onMouseDownLat = 0,
phi = 0, theta = 0;
var ldr;
var videoStarted = false;

function init() {

	var container, mesh;

	container = document.getElementById( 'container' );
	scene = new THREE.Scene();
	camera = new THREE.PerspectiveCamera( fov, window.innerWidth / window.innerHeight, .1, 1000 );

	video = document.createElement( 'video' );
	video.loop = "loop";
	video.muted = true;

	// Report video load complete
	video.addEventListener("ended", function(e) {
		$(".pct").text("100% loaded.");
		// DEBUG
		console.log("done");
	});

	// Progress Meter
	video.addEventListener("progress", function(e) {
		var percent = null;
		    if (video && video.buffered && video.buffered.length > 0 && video.buffered.end && video.duration) {
		        percent = video.buffered.end(0) / video.duration;
		    }
		    // Some browsers (e.g., FF3.6 and Safari 5) cannot calculate target.bufferered.end()
		    // to be anything other than 0. If the byte count is available we use this instead.
		    // Browsers that support the else if do not seem to have the bufferedBytes value and
		    // should skip to there. Tested in Safari 5, Webkit head, FF3.6, Chrome 6, IE 7/8.
		    else if (video && video.bytesTotal != undefined && video.bytesTotal > 0 && video.bufferedBytes != undefined) {
		        percent = video.bufferedBytes / video.bytesTotal;
		    }

		   	var cpct = Math.round(percent * 100);
		   	if(cpct == 100) {
		   		$(".percentLoaded").fadeOut();
		   	} else {
		   		$(".pct").text(cpct + "% loaded.");
		   	}

	});

	// Video Play Listener, fires after video loads
	video.addEventListener("canplaythrough", function(e) {
		video.play();
	});

	// DEBUG
	window.v = video;

	video.src = $(".videoNav li:first-child a").attr("href");

	renderer = new THREE.WebGLRenderer();
	renderer.setSize( window.innerWidth, window.innerHeight );
	container.appendChild( renderer.domElement );

	texture = new THREE.Texture( video );
	texture.minFilter = THREE.LinearFilter;
	texture.magFilter = THREE.LinearFilter;
	//texture.anistropy = 4;
	texture.format = THREE.LuminanceFormat;

	mesh = new THREE.Mesh( new THREE.SphereGeometry( 500, 80, 50 ), new THREE.MeshBasicMaterial( { map: texture } ) );
	mesh.scale.x = -1;
	scene.add( mesh );

	// displays current and past frames per second attained by scene
	stats = new Stats();
	stats.domElement.style.position = 'absolute';
	stats.domElement.style.bottom = '0px';
	stats.domElement.style.zIndex = 100;
	container.appendChild( stats.domElement );

	document.addEventListener( 'mousedown', onDocumentMouseDown, false );
	document.addEventListener( 'mousemove', onDocumentMouseMove, false );
	document.addEventListener( 'mouseup', onDocumentMouseUp, false );
	document.addEventListener( 'mousewheel', onDocumentMouseWheel, false );
	document.addEventListener( 'DOMMouseScroll', onDocumentMouseWheel, false);

}

function onDocumentMouseDown( event ) {

	event.preventDefault();

	isUserInteracting = true;

}

function onDocumentMouseMove( event ) {
	onPointerDownPointerX = event.clientX;
	onPointerDownPointerY = -event.clientY;

	onPointerDownLon = lon;
	onPointerDownLat = lat;
	if ( 1 ) {

		lon = ( event.clientX / window.innerWidth ) * 430 - 45
		lat = ( event.clientY / window.innerHeight ) * -180 + 90

	}
}

function onDocumentMouseUp( event ) {

	isUserInteracting = false;

}

function onDocumentMouseWheel( event ) {

	var wheelSpeed = -.01;

	// WebKit

	if ( event.wheelDeltaY ) {

		fov -= event.wheelDeltaY * wheelSpeed;

	// Opera / Explorer 9

	} else if ( event.wheelDelta ) {

		fov -= event.wheelDelta * wheelSpeed;

	// Firefox

	} else if ( event.detail ) {

		fov += event.detail * 1.0;

	}

	var fovMin = 3;
	var fovMax = 100;

	if(fov < fovMin) {
		fov = fovMin;
	} else if(fov > fovMax) {
		fov = fovMax;
	}

	camera.setLens(fov)
	//render();

}

function animate() {

	requestAnimationFrame( animate );

	// run this the first time we play the video TODO: FIX THIS SO IT DOESN'T RUN ON EVERY DAMN FRAME
	if(!videoStarted) {

		if($("#loading").length > 0) {

			ldr = $("#loading");
			ldr.data("isLoading", true);

		}

		if ( video.readyState === video.HAVE_ENOUGH_DATA ) {

			if(ldr.data("isLoading") == true) {
				ldr.fadeOut('fast');
				ldr.data("isLoading", false);
			}

			videoStarted = true;

		}
	} else {
		if(!video.paused) {
			texture.needsUpdate = true;
		}

	}

	render();

}

function render() {

	lat = Math.max( - 85, Math.min( 85, lat ) );
	phi = ( 90 - lat ) * Math.PI / 180;
	theta = lon * Math.PI / 180;

	var cx = 500 * Math.sin( phi ) * Math.cos( theta );
	var cy = 500 * Math.cos( phi );
	var cz = 500 * Math.sin( phi ) * Math.sin( theta );

	camera.lookAt(new THREE.Vector3(cx, cy, cz));

	// distortion
	camera.position.x = - cx;
	camera.position.y = - cy;
	camera.position.z = - cz;
	stats.update();
	renderer.render( scene, camera );

}<|endoftext|>


<commit_before>/**
 * The root namespace for the ERMrest library.
 * @namespace ermrest
 */
var ermrest = (function () {

    /**
     * ERMrest Service Provider. This is a stub. An example implementation
     * of the ServiceProvider is the RestServiceProvider which implements the
     * ERMrest "REST" style protocol.
     *
     * @constructor
     * @this {ServiceProvider}
     * @memberof ermrest
     */
    ServiceProvider = function() {};

    /**
     * An ERMrest service endpoint. This is a stub. An example implementation
     * of the ServiceEndpoint is the RestServiceEndpoint which implements the
     * state of a connection to an ERMrest service.
     *
     * @constructor
     * @this {ServiceEndpoint}
     * @memberof ermrest
     */
    ServiceEndpoint = function() {};

    /**
     * Returns a {Catalog} instance located at this {ServiceEndpoint}. This
     * function returns immediately.
     *
     * @function
     * @this {ServiceEndpoint}
     * @param {String} name The name of the catalog.
     * @param {function} statusfn The status callback function.
     */
    ServiceEndpoint.prototype.catalog = function (name) {};

    /**
     * Creates an instance of Catalog.
     *
     * @memberof ermrest
     * @constructor
     * @this {Catalog}
     * @param {string} URL The URL of the catalog
     */
    Catalog = function(URL) {};

    /**
     * Creates the Catalog.
     *
     * @function
     * @this {Catalog}
     * @param {function} status A callback function
     */
    Catalog.prototype.create = function (status) {};
    Catalog.prototype.get = function (status) {};
    Catalog.prototype.destroy = function (status) {};

    /**
     * Returns the schemas interface for this Catalog.
     *
     * @this {Catalog}
     * @return {Object} schema interface
     */
    Catalog.prototype.schemas = function() {};

    /**
     * Returns the entity interface for this Catalog.
     *
     * @this {Catalog}
     * @return {Object} entity interface
     */
    Catalog.prototype.entity = function () {};

    /**
     * Creates an Entity instance.
     *
     * @memberof ermrest
     * @constructor
     * @this {Entity}
     */
    Entity = function () {};

    /**
     * Creates an Alias out of a Table for use within the context of an
     * instance of the Entity interface.
     *
     * @function
     * @this {Entity}
     * @param {Table} table The table to alias
     * @return {Alias} An alias based on the table
     */
    Entity.prototype.alias = function (table) {};

    /**
     * Extends the current ERM path by a Table or Alias. This method must
     * be called at least once before any operations may be performed.
     *
     * @function
     * @this {Entity}
     * @param {Table} table The table or table alias to extend the path
     * @return {Entity} This entity instance.
     */
    Entity.prototype.extend = function (table) {};

    /**
     * Apply a filter to the current ERM path.
     * @function
     * @this {Entity}
     */
    Entity.prototype.filter = function () {};

    /**
     * Creates and returns a Condition object for use in filters.
     * @function
     * @this {Entity}
     */
    Entity.prototype.condition = function () {};

    /**
     * @constructor
     * @this {Condition}
     */
    Entity.prototype.Condition = function () {};
    Entity.prototype.Condition.prototype.predicate = function () {};
    Entity.prototype.Condition.prototype.and = function () {};
    Entity.prototype.Condition.prototype.or = function () {};

    Entity.prototype.get = function () {};
    Entity.prototype.update = function () {};
    Entity.prototype.del = function () {};

    /**
     * Registered service providers.
     * @var providers The dictionary of known service providers.
     */
    providers_ = { };

    return { providers: providers_ };
})();
<commit_msg>test commit<commit_after>/**
 * The root namespace for the ERMrest library.
 * @namespace ermrest
 */
var ermrest = (function () {

    /**
     * ERMrest Service Provider. This is a stub. An example implementation
     * of the ServiceProvider is the RestServiceProvider which implements the
     * ERMrest "REST" style protocol.
     *
     * @constructor
     * @this {ServiceProvider}
     * @memberof ermrest
     */
    ServiceProvider = function() {};

    /**
     * An ERMrest service endpoint. This is a stub. An example implementation
     * of the ServiceEndpoint is the RestServiceEndpoint which implements the
     * state of a connection to an ERMrest service.
     *
     * @constructor
     * @this {ServiceEndpoint}
     * @memberof ermrest
     */
    ServiceEndpoint = function() {};

    /**
     * Returns a {Catalog} instance located at this {ServiceEndpoint}. This
     * function returns immediately.
     *
     * @function
     * @this {ServiceEndpoint}
     * @param {String} name The name of the catalog.
     * @param {function} statusfn The status callback function.
     */
    ServiceEndpoint.prototype.catalog = function (name) {};

    /**
     * Creates an instance of Catalog.
     *
     * @memberof ermrest
     * @constructor
     * @this {Catalog}
     * @param {string} URL The URL of the catalog
     */
    Catalog = function(URL) {};

    /**
     * Creates the Catalog.
     *
     * @function
     * @this {Catalog}
     * @param {function} status A callback function
     */
    Catalog.prototype.create = function (status) {};
    Catalog.prototype.get = function (status) {};
    Catalog.prototype.destroy = function (status) {};

    /**
     * Returns the schemas interface for this Catalog.
     *
     * @this {Catalog}
     * @return {Object} schema interface
     */
    Catalog.prototype.schemas = function() {};

    /**
     * Returns the entity interface for this Catalog.
     *
     * @this {Catalog}
     * @return {Object} entity interface
     */
    Catalog.prototype.entity = function () {};

    /**
     * Creates an Entity instance.
     *
     * @memberof ermrest
     * @constructor
     * @this {Entity}
     */
    Entity = function () {};

    /**
     * Creates an Alias out of a Table for use within the context of an
     * instance of the Entity interface.
     *
     * @function
     * @this {Entity}
     * @param {Table} table The table to alias
     * @return {Alias} An alias based on the table
     */
    Entity.prototype.alias = function (table) {};

    /**
     * Extends the current ERM path by a Table or Alias. This method must
     * be called at least once before any operations may be performed.
     *
     * @function
     * @this {Entity}
     * @param {Table} table The table or table alias to extend the path
     * @return {Entity} This entity instance.
     */
    Entity.prototype.extend = function (table) {};

    /**
     * Apply a filter to the current ERM path.
     * @function
     * @this {Entity}
     */
    Entity.prototype.filter = function () {};

    /**
     * Creates and returns a Condition object for use in filters.
     * @function
     * @this {Entity}
     */
    Entity.prototype.condition = function () {};

    /**
     * Creates a new instance of a Condition
     *
     * @constructor
     * @this {Condition}
     */
    Entity.prototype.Condition = function () {};
    Entity.prototype.Condition.prototype.predicate = function () {};
    Entity.prototype.Condition.prototype.and = function () {};
    Entity.prototype.Condition.prototype.or = function () {};

    Entity.prototype.get = function () {};
    Entity.prototype.update = function () {};
    Entity.prototype.del = function () {};

    /**
     * Registered service providers.
     * @var providers The dictionary of known service providers.
     */
    providers_ = { };

    return { providers: providers_ };
})();
<|endoftext|>


<commit_before>
// Wait for user to finish typing
// callback: The callback function
// wait: The number of milliseconds to wait after the the last key press before firing the callback
// highlight: Highlights the element when it receives focus
// allowSubmit: Allows a non-multiline element to be submitted (enter key) regardless of captureLength
// captureLength: Minimum # of characters necessary to fire the callback

$(document).ready(function() {

	//stop loader.gif and overlay
	stop_loader();

	//enable typewatch
	$('#street').typeWatch({
		captureLength: 2,
		wait: 1750,
    		highlight: true,
		callback: function(value) {
			//alert("typing finished");
			street_to_geo(value);
		}
	});
});

function start_loader(){
	$('#loader').fadeIn('slow');
	$('#overlay').fadeIn('slow');
}

function stop_loader(){
	$('#loader').fadeOut('slow');
	$('#overlay').fadeOut('slow');

}

function street_to_geo(street){
      start_loader();
      //encodes the street string into url friendly format
      var street_encoded = encodeURIComponent(street);
      var uri = "https://nominatim.openstreetmap.org/search/" + street_encoded + "?format=json";
      //alert(uri);
      //makes the the jquery call and gets json back
      $.getJSON(uri, function(data) {
        //make js obj containing lat and long
        var obj = {latitude: data[0].lat, longitude: data[0].lon};
	stop_loader();
        alert(obj.latitude + " " + obj.longitude);
        //return obj;
      });
}

function calc_distance(lat1, lon1, lat2, lon2) {
	var unit = "K";
	var radlat1 = Math.PI * lat1/180;
	var radlat2 = Math.PI * lat2/180;
	var theta = lon1-lon2;
	var radtheta = Math.PI * theta/180;
	var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
	dist = Math.acos(dist);
	dist = dist * 180/Math.PI;
	dist = dist * 60 * 1.1515;
	if (unit=="K") { dist = dist * 1.609344; }
	if (unit=="N") { dist = dist * 0.8684; }
	return dist;
}

function get_places(lat, long, category) {
	var url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json";
	var method = "POST";
	var postData = "";	// TODO get key
	postData += "location=" + lat + "," + long;
	postData += "radius=5000";	// 5km, could be changed or added as a configurable later
	postData += "type=" + category;

	// if it is not true, it'll block ALL execution waiting for server response.
	var shouldBeAsync = true;

	var request = new XMLHttpRequest();

	// This function attached to the XMLHttpRequest "onload" property specifies how the HTTP response will be handled.
	// request.onreadystatechange can also be used if this doesn't work
	request.onload = function () {
		// You can get all kinds of information about the HTTP response.
		var status = request.status; // HTTP response status, e.g., 200 for "200 OK"
		var data = request.responseText; // Returned data, e.g., an HTML document.

		var jsObj = null;

		if (status == 200) {
			jsObj = data.results;
			add_details(jsObj, lat, long);
			sort_json(jsObj, 'rating_over_distance', false);	// false because we want descending order
		}

		// TODO: call whatever needs to use the jsObj
	}

	request.open(method, url, shouldBeAsync);

	request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");

	// Actually sends the request to the server.
	request.send(postData);
}

function add_details(json_object, lat, long) {
	for ( x in json_object) {
		json_object[x].distance = calc_distance(lat, lon, json_object[x].geometry.location.lat, json_object[x].geometry.location.lng);
		json_object[x].rating_over_distance = json_object[x].rating/json_object[x].distance;
	}
}

function sort_json(json_object, key_to_sort_by, ascending) {
    function sortByKey(a, b) {
        var x = a[key_to_sort_by];
        var y = b[key_to_sort_by];
        if (ascending ==  true) {
        	return ((x < y) ? -1 : ((x > y) ? 1 : 0));
        } else {
        	return ((x > y) ? -1 : ((x < y) ? 1 : 0));
        }
    }

    json_object.sort(sortByKey);
}

//returns a Coordinate, could add some other functionality of what to do when geolocation is not supported
var pos;
function get_my_location(){
	start_loader();
	var options = {
	  enableHighAccuracy: true
	};
	if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(function(position) {
        pos = {
          lat: position.coords.latitude,
          lng: position.coords.longitude
        };

	      //return pos;
		var location = pos.lat + " " + pos.lng;
	      	stop_loader();
		alert(location);
      },
      function(err){
	      stop_loader(); alert("could not get device position");
      		},
      options);
    }

}

function get_weather(lat, lon){

	//if the function does not work, maybe the get_json.php should be in root, or path should be js/get_json.php

    var api_url = "js/get_json.php?";
    var type = "type=weather"

	api_request = api_url;
    api_request += type;
    api_request += "&lat="
    api_request += lat;
    api_request += "&lon="
    api_request += lon;

    //document.write(api_request);

    $(function () {
        $.getJSON(
            api_request,
            function (data) {
                $("#reply").html(JSON.stringify(data));
                return(JSON.stringify(data.weather[0].main));
            });
    });

}
<commit_msg>Update main.js<commit_after>
// Wait for user to finish typing
// callback: The callback function
// wait: The number of milliseconds to wait after the the last key press before firing the callback
// highlight: Highlights the element when it receives focus
// allowSubmit: Allows a non-multiline element to be submitted (enter key) regardless of captureLength
// captureLength: Minimum # of characters necessary to fire the callback

$(document).ready(function() {

	//stop loader.gif and overlay
	stop_loader();

	//enable typewatch
	$('#street').typeWatch({
		captureLength: 2,
		wait: 1750,
    		highlight: true,
		callback: function(value) {
			//alert("typing finished");
			street_to_geo(value);
		}
	});
});

function start_loader(){
	$('#loader').fadeIn('slow');
	$('#overlay').fadeIn('slow');
}

function stop_loader(){
	$('#loader').fadeOut('slow');
	$('#overlay').fadeOut('slow');

}

function street_to_geo(street){
      start_loader();
      //encodes the street string into url friendly format
      var street_encoded = encodeURIComponent(street);
      var uri = "https://nominatim.openstreetmap.org/search/" + street_encoded + "?format=json";
      //alert(uri);
      //makes the the jquery call and gets json back
      $.getJSON(uri, function(data) {
        //make js obj containing lat and long
        var obj = {latitude: data[0].lat, longitude: data[0].lon};
	stop_loader();
        alert(obj.latitude + " " + obj.longitude);
        //return obj;
      });
}

function calc_distance(lat1, lon1, lat2, lon2) {
	var unit = "K";
	var radlat1 = Math.PI * lat1/180;
	var radlat2 = Math.PI * lat2/180;
	var theta = lon1-lon2;
	var radtheta = Math.PI * theta/180;
	var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
	dist = Math.acos(dist);
	dist = dist * 180/Math.PI;
	dist = dist * 60 * 1.1515;
	if (unit=="K") { dist = dist * 1.609344; }
	if (unit=="N") { dist = dist * 0.8684; }
	return dist;
}

function get_places(lat, long, category) {
	var url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json";
	var method = "POST";
	var postData = "";	// TODO get key
	postData += "location=" + lat + "," + long;
	postData += "radius=5000";	// 5km, could be changed or added as a configurable later
	postData += "type=" + category;

	// if it is not true, it'll block ALL execution waiting for server response.
	var shouldBeAsync = true;

	var request = new XMLHttpRequest();

	// This function attached to the XMLHttpRequest "onload" property specifies how the HTTP response will be handled.
	// request.onreadystatechange can also be used if this doesn't work
	request.onload = function () {
		// You can get all kinds of information about the HTTP response.
		var status = request.status; // HTTP response status, e.g., 200 for "200 OK"
		var data = request.responseText; // Returned data, e.g., an HTML document.

		var jsObj = null;

		if (status == 200) {
			jsObj = data.results;
			add_details(jsObj, lat, long);
			sort_json(jsObj, 'rating_over_distance', false);	// false because we want descending order
		}

		// TODO: call whatever needs to use the jsObj
	}

	request.open(method, url, shouldBeAsync);

	request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");

	// Actually sends the request to the server.
	request.send(postData);
}

function add_details(json_object, lat, long) {
	for ( x in json_object) {
		json_object[x].distance = calc_distance(lat, lon, json_object[x].geometry.location.lat, json_object[x].geometry.location.lng);
		json_object[x].rating_over_distance = json_object[x].rating/json_object[x].distance;
	}
}

function sort_json(json_object, key_to_sort_by, ascending) {
    function sortByKey(a, b) {
        var x = a[key_to_sort_by];
        var y = b[key_to_sort_by];
        if (ascending ==  true) {
        	return ((x < y) ? -1 : ((x > y) ? 1 : 0));
        } else {
        	return ((x > y) ? -1 : ((x < y) ? 1 : 0));
        }
    }

    json_object.sort(sortByKey);
}

//returns a Coordinate, could add some other functionality of what to do when geolocation is not supported
var pos;
function get_my_location(){
	start_loader();
	var options = {
	  enableHighAccuracy: true
	};
	if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(function(position) {
        pos = {
          lat: position.coords.latitude,
          lng: position.coords.longitude
        };

	      //return pos;
		var location = pos.lat + " " + pos.lng;
	      	stop_loader();
		alert(location);
	        get_places(pos.lat,pos.lng,'bank');

      },
      function(err){
	      stop_loader(); alert("could not get device position");
      		},
      options);
    }

}

function get_weather(lat, lon){

	//if the function does not work, maybe the get_json.php should be in root, or path should be js/get_json.php

    var api_url = "js/get_json.php?";
    var type = "type=weather"

	api_request = api_url;
    api_request += type;
    api_request += "&lat="
    api_request += lat;
    api_request += "&lon="
    api_request += lon;

    //document.write(api_request);

    $(function () {
        $.getJSON(
            api_request,
            function (data) {
                $("#reply").html(JSON.stringify(data));
                return(JSON.stringify(data.weather[0].main));
            });
    });

}
<|endoftext|>


<commit_before>'use strict';

const electron = require('electron');
const app = electron.app;
const nodeURL = require('url');
const squirrelStartup = require('electron-squirrel-startup');
const AutoLaunch = require('auto-launch');
const urlParser = require('url');
const { getConfigField } = require('./config.js');
const { isMac, isDevEnv } = require('./utils/misc.js');
const protocolHandler = require('./protocolHandler');
const getCmdLineArg = require('./utils/getCmdLineArg.js')

// used to check if a url was opened when the app was already open
let isAppAlreadyOpen = false;

// exit early for squirrel installer
if (squirrelStartup) {
    return;
}

require('./mainApiMgr.js');

// monitor memory of main process
require('./memoryMonitor.js');

const windowMgr = require('./windowMgr.js');

// only allow a single instance of app.
const shouldQuit = app.makeSingleInstance((argv) => {
    // Someone tried to run a second instance, we should focus our window.
    let mainWin = windowMgr.getMainWindow();
    if (mainWin) {
        isAppAlreadyOpen = true;
        if (mainWin.isMinimized()) {
            mainWin.restore();
        }
        mainWin.focus();
    }
    processProtocolAction(argv);
});

// quit if another instance is already running
if (shouldQuit) {
    app.quit();
}

var symphonyAutoLauncher = new AutoLaunch({
    name: 'Symphony',
    path: process.execPath,
});

/**
 * This method will be called when Electron has finished
 * initialization and is ready to create browser windows.
 * Some APIs can only be used after this event occurs.
 */
app.on('ready', setupThenOpenMainWindow);

app.on('window-all-closed', function () {
    app.quit();
});

app.on('activate', function () {
    if (windowMgr.isMainWindow(null)) {
        setupThenOpenMainWindow();
    } else {
        windowMgr.showMainWindow();
    }
});

// adds 'symphony' as a protocol
// in the system. plist file in macOS
// and registry keys in windows
app.setAsDefaultProtocolClient('symphony');

// This event is emitted only on macOS
// at this moment, support for windows
// is in pipeline (https://github.com/electron/electron/pull/8052)
app.on('open-url', function (event, url) {
    handleProtocolAction(url);
});

function setupThenOpenMainWindow() {

    processProtocolAction(process.argv);

    isAppAlreadyOpen = true;

    // allows installer to launch app and set auto startup mode then
    // immediately quit.
    let hasInstallFlag = getCmdLineArg(process.argv, '--install', true);
    if (!isMac && hasInstallFlag) {
        getConfigField('launchOnStartup')
        .then(setStartup)
        .then(app.quit)
        .catch(app.quit);
        return;
    }

    getUrlAndCreateMainWindow();
}

function setStartup(lStartup){
    return symphonyAutoLauncher.isEnabled()
    .then(function(isEnabled){
        if (!isEnabled && lStartup) {
            return symphonyAutoLauncher.enable();
        }

        if (isEnabled && !lStartup) {
            return symphonyAutoLauncher.disable();
        }

        return true;
    });
}

function getUrlAndCreateMainWindow() {
    // for dev env allow passing url argument
    if (isDevEnv) {
        let url = getCmdLineArg(process.argv, '--url=')
        if (url) {
            windowMgr.createMainWindow(url.substr(6));
            return;
        }
    }

    getConfigField('url')
        .then(createWin).catch(function (err) {
            let title = 'Error loading configuration';
            electron.dialog.showErrorBox(title, title + ': ' + err);
        });
}

function createWin(urlFromConfig) {
    let protocol = '';
    // add https protocol if none found.
    let parsedUrl = nodeURL.parse(urlFromConfig);
    if (!parsedUrl.protocol) {
        protocol = 'https';
    }
    var url = nodeURL.format({
        protocol: protocol,
        slahes: true,
        pathname: parsedUrl.href
    });

    windowMgr.createMainWindow(url);
}

/**
 * processes protocol action for windows clients
 * @param argv {Array} an array of command line arguments
 */
function processProtocolAction(argv) {

    // In case of windows, we need to handle protocol handler
    // manually because electron doesn't emit
    // 'open-url' event on windows
    if (!(process.platform === 'win32')) {
        return;
    }

    let protocolUri = getCmdLineArg(argv, 'symphony://');

    if (protocolUri) {

        const parsedURL = urlParser.parse(protocolUri);

        if (!parsedURL.protocol || !parsedURL.slashes) {
            return;
        }

        handleProtocolAction(protocolUri);

    }
}

function handleProtocolAction(uri) {
    if (!isAppAlreadyOpen) {
        // app is opened by the protocol url, cache the protocol url to be used later
        protocolHandler.setProtocolUrl(uri);
    } else {
        // app is already open, so, just trigger the protocol action method
        protocolHandler.processProtocolAction(uri);
    }
}
<commit_msg>ignore single app instance for dev mode (#119)<commit_after>'use strict';

const electron = require('electron');
const app = electron.app;
const nodeURL = require('url');
const squirrelStartup = require('electron-squirrel-startup');
const AutoLaunch = require('auto-launch');
const urlParser = require('url');
const { getConfigField } = require('./config.js');
const { isMac, isDevEnv } = require('./utils/misc.js');
const protocolHandler = require('./protocolHandler');
const getCmdLineArg = require('./utils/getCmdLineArg.js')

// used to check if a url was opened when the app was already open
let isAppAlreadyOpen = false;

// exit early for squirrel installer
if (squirrelStartup) {
    return;
}

require('./mainApiMgr.js');

// monitor memory of main process
require('./memoryMonitor.js');

const windowMgr = require('./windowMgr.js');

// only allow a single instance of app.
const shouldQuit = app.makeSingleInstance((argv) => {
    // Someone tried to run a second instance, we should focus our window.
    let mainWin = windowMgr.getMainWindow();
    if (mainWin) {
        isAppAlreadyOpen = true;
        if (mainWin.isMinimized()) {
            mainWin.restore();
        }
        mainWin.focus();
    }
    processProtocolAction(argv);
});

// quit if another instance is already running, ignore for dev env
if (!isDevEnv && shouldQuit) {
    app.quit();
}

var symphonyAutoLauncher = new AutoLaunch({
    name: 'Symphony',
    path: process.execPath,
});

/**
 * This method will be called when Electron has finished
 * initialization and is ready to create browser windows.
 * Some APIs can only be used after this event occurs.
 */
app.on('ready', setupThenOpenMainWindow);

app.on('window-all-closed', function () {
    app.quit();
});

app.on('activate', function () {
    if (windowMgr.isMainWindow(null)) {
        setupThenOpenMainWindow();
    } else {
        windowMgr.showMainWindow();
    }
});

// adds 'symphony' as a protocol
// in the system. plist file in macOS
// and registry keys in windows
app.setAsDefaultProtocolClient('symphony');

// This event is emitted only on macOS
// at this moment, support for windows
// is in pipeline (https://github.com/electron/electron/pull/8052)
app.on('open-url', function (event, url) {
    handleProtocolAction(url);
});

function setupThenOpenMainWindow() {

    processProtocolAction(process.argv);

    isAppAlreadyOpen = true;

    // allows installer to launch app and set auto startup mode then
    // immediately quit.
    let hasInstallFlag = getCmdLineArg(process.argv, '--install', true);
    if (!isMac && hasInstallFlag) {
        getConfigField('launchOnStartup')
        .then(setStartup)
        .then(app.quit)
        .catch(app.quit);
        return;
    }

    getUrlAndCreateMainWindow();
}

function setStartup(lStartup){
    return symphonyAutoLauncher.isEnabled()
    .then(function(isEnabled){
        if (!isEnabled && lStartup) {
            return symphonyAutoLauncher.enable();
        }

        if (isEnabled && !lStartup) {
            return symphonyAutoLauncher.disable();
        }

        return true;
    });
}

function getUrlAndCreateMainWindow() {
    // for dev env allow passing url argument
    if (isDevEnv) {
        let url = getCmdLineArg(process.argv, '--url=')
        if (url) {
            windowMgr.createMainWindow(url.substr(6));
            return;
        }
    }

    getConfigField('url')
        .then(createWin).catch(function (err) {
            let title = 'Error loading configuration';
            electron.dialog.showErrorBox(title, title + ': ' + err);
        });
}

function createWin(urlFromConfig) {
    let protocol = '';
    // add https protocol if none found.
    let parsedUrl = nodeURL.parse(urlFromConfig);
    if (!parsedUrl.protocol) {
        protocol = 'https';
    }
    var url = nodeURL.format({
        protocol: protocol,
        slahes: true,
        pathname: parsedUrl.href
    });

    windowMgr.createMainWindow(url);
}

/**
 * processes protocol action for windows clients
 * @param argv {Array} an array of command line arguments
 */
function processProtocolAction(argv) {

    // In case of windows, we need to handle protocol handler
    // manually because electron doesn't emit
    // 'open-url' event on windows
    if (!(process.platform === 'win32')) {
        return;
    }

    let protocolUri = getCmdLineArg(argv, 'symphony://');

    if (protocolUri) {

        const parsedURL = urlParser.parse(protocolUri);

        if (!parsedURL.protocol || !parsedURL.slashes) {
            return;
        }

        handleProtocolAction(protocolUri);

    }
}

function handleProtocolAction(uri) {
    if (!isAppAlreadyOpen) {
        // app is opened by the protocol url, cache the protocol url to be used later
        protocolHandler.setProtocolUrl(uri);
    } else {
        // app is already open, so, just trigger the protocol action method
        protocolHandler.processProtocolAction(uri);
    }
}
<|endoftext|>