<commit_before>function APS( server, events, options ){
	this.option = {
		'poll': 25000,
		debug: false,
		session: true,
		connectionArgs: {},
		server: server,
		transport: ["wb", "lp"],
		//transport: "lp",
		secure: false
	}
	this.identifier = "APS";
	this.version = '0.9b1';
	this.state = 0;
	this.events = {};
	this.chl = 0;
	this.user = {};
	this.pipes = {};
	this.channels = {};
	this.eQueue = {};

	//Add Events
	if(!!events)
		this.on(events);

	//Update options
	if(!!options){
		for(var opt in options){
			this.option[opt] = options[opt];
		}
	}

	//IE9 crap - log function fix
	if(navigator.appName == "Microsoft Internet Explorer"){
		if(typeof window.console == "undefined"){
			this.log = function(){};
		}else{
			this.log = function(){
				if(this.option.debug == false) return;

				var args =  Array.prototype.slice.call(arguments);
				args.unshift("["+this.identifier+"]");

				window.console.log(args.join().replace(",",""));
			}

		}
	}

	var cb = {
		'onmessage': this.onMessage.bind(this),
		'onerror': this.log.bind(this, "T_ERR")
	}

	this.connect = function(args){
		if(this.state == 1)
			return this.log("Already Connected!");

		var client = this;
		this.option.connectionArgs = args || this.option.connectionArgs;

		//Handle transport
		if(!!this.transport){
			if(this.transport.state == 0){
				this.transport.close();
				this.transport = new APS.transport(server, cb, this);
			}else{
				//Use current active transport

			}
		}else{
			this.transport = new APS.transport(server, cb, this);
		}

		//Handle sessions
		if(this.option.session == true){
			if(this.session.restore() == true){
				return this;
			}
		}

		//Fresh Connect
		if(this.trigger("connect") == false)
			return false;

		this.sendCmd('CONNECT', args);

		return this;
	}

	function getTransport() {
		if('XMLHttpRequest' in window) return XMLHttpRequest;
		if('ActiveXObject' in window) {
			var names = [
				"Msxml2.XMLHTTP.6.0",
				"Msxml2.XMLHTTP.3.0",
				"Msxml2.XMLHTTP",
				"Microsoft.XMLHTTP"
			];
			for(var i in names){
				try{ return ActiveXObject(names[i]); }
				catch(e){}
			}
		}
		return false;
	}

	var request;
	var transport = getTransport();

	this.request = function(addr, data, callback){
		request = new transport();
		request.onreadystatechange = function(){
			if(this.readyState == 4)
				callback(this.responseText);
		};
		request.open('POST', addr, true);
		request.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
		request.send(data);
	}

	this.session.client = this;
	return this;
}

APS.prototype.trigger = function(ev, args){
	ev = ev.toLowerCase();

	if(!(args instanceof Array)) args = [args];

	//GLobal
	if("client" in this){
		for(var i in this.client.events[ev]){
			if(this.client.events[ev].hasOwnProperty(i)){
				this.log("{{{ " + ev + " }}} on client ", this.client);
				if(this.client.events[ev][i].apply(this, args) === false)
					return false;
			}
		}
	}

	//Local
	for(var i in this.events[ev]){
		if(this.events[ev].hasOwnProperty(i)){
			if(!this.client){
				this.log("{{{ " + ev + " }}} on client ", this);
			}else{
				this.log("{{{ " + ev + " }}} ", this);
			}
			if(this.events[ev][i].apply(this, args) === false)
				return false;
		}
	}

	return true;
}

APS.prototype.on = function(ev, fn){
	var Events = [];

	if(typeof ev == 'string' && typeof fn == 'function'){
		Events[ev] = fn;
	}else if(typeof ev == "object"){
		Events = ev;
	}else{
		return this;
	}

	for(var e in Events){
		var fn = Events[e];
		if(!this.events[e])
			this.events[e] = [];
		this.events[e].push(fn);
	}

	return this;
}

APS.prototype.getPipe = function(user){
	if(typeof user == 'string'){
		return this.pipes[user];
	} else {
		return this.pipes[user.pubid];
	}
}

APS.prototype.send =function(pipe, $event, data, callback){
	this.sendCmd("Event", {
		event: $event,
		data: data
	}, pipe, callback);
}

APS.prototype.sendCmd = function(cmd, args, pipe, callback){
	var specialCmd = {CONNECT: 0, RESTORE:0};
	if(this.state == 1 || cmd in specialCmd){

		var tmp = {
			'cmd': cmd,
			'chl': this.chl
		}

		if(args) tmp.params = args;
		if(pipe) tmp.params.pipe = typeof pipe == 'string' ? pipe : pipe.pubid;
		if(this.session.id) tmp.sessid = this.session.id;

		this.log('<<<< ', cmd.toUpperCase() , " >>>> ", tmp);

		if(typeof callback != "function")	callback = function(){};

		var data = [];
		try {
			data = JSON.stringify([tmp]);
		}catch(e){
			this.log(e);
			this.log(data);
		}

		//Send command
		switch(cmd){
			case "Event":
				if(typeof this.transport.push == "function"){
					this.transport.push(data, callback);
					break;
				}
			default:
				this.transport.send(data, callback);

		}

		if(!(cmd in specialCmd)){
			this.poll();
		}
		this.chl++;
		this.session.saveChl();
	} else {
		this.on('ready', this.sendCmd.bind(this, cmd, args));
	}

	return this;
}

APS.prototype.poll = function(){
	if(this.transport.id == 0){
		clearTimeout(this.poller);
		this.poller = setTimeout((function(){ this.check() }).bind(this), this.option.poll);
	}
}

APS.prototype.check = function(force){
	//this.log("Chec")
	if(this.transport.id == 0 || !!force)
		this.sendCmd('CHECK');
}

APS.prototype.quit = function(){
	this.sendCmd('QUIT');
	this.transport.close();
	this.trigger("quit");
	//Clear session on 'quit'
	this.session.destroy();
	this.state = 0;
}

APS.prototype.sub = function(channel, Events, callback){
	//Handle the events
	if(typeof Events == "object"){
		if(typeof channel == "object"){
			for(var chan in channel){
				this.onChannel(channel[chan], Events);
			}
		}else{
			this.onChannel(channel, Events);
		}
	}

	//Handle callback
	if(typeof callback == "function"){
		if(typeof channel == "object"){
			for(var chan in channel){
				this.onChannel(channel[chan], "joined", callback);
			}
		}else{
			this.onChannel(channel, "joined", callback);
		}
	}

	//Join Channel
	if(this.state == 0){
		this.on("ready", this.sub.bind(this, channel));
		this.connect({user: this.user});

	}else if(typeof this.channels[channel] != "object"){
		this.sendCmd('JOIN', {'channels': channel});
	}

	return this;
}

APS.prototype.pub = function(channel, data, callback){
	var pipe = this.getChannel(channel);
	if(!pipe && channel.length == 32) pipe = this.getPipe(channel);

	if(pipe){
		var $event = typeof data == "string" ? "message" : "data";
		var args = {data: data};
		pipe.send($event, data, callback);
		//pipe.trigger("pub",args);
	}else{
		this.log("NO Channel " + channel);
	}
};

APS.prototype.getChannel = function(channel){
	channel = channel.toLowerCase();
	if(channel in this.channels){
		return this.channels[channel];
	}

	return false;
}

APS.prototype.onChannel = function(channel, Events, fn){
	channel = channel.toLowerCase();

	if(channel in this.channels){
		this.channels[channel].on(Events, fn);
		return true;
	}

	if(typeof Events == "object"){
		//add events to queue
		if(typeof this.eQueue[channel] != "object")
			this.eQueue[channel] = [];

		//this.eQueue[channel].push(Events);
		for(var $event in Events){
			var fn = Events[$event];

			this.eQueue[channel].push([$event, fn]);

			this.log("Adding ["+channel+"] event '"+$event+"' to queue");
		}
	}else{
		var xnew = Object();
		xnew[Events] = fn;
		this.onChannel(channel,xnew);
	}
}

APS.prototype.unSub = function(channel){
	if(channel == "") return;
	this.getChannel(channel).leave();
}

//Debug Function for Browsers console
if(navigator.appName != "Microsoft Internet Explorer"){
	APS.prototype.log = function(){
		if(!this.option.debug) return;

		var args =  Array.prototype.slice.call(arguments);
		args.unshift("["+this.identifier+"]");

		window.console.log.apply(console, args);
	};

}
<commit_msg>updated the original connect() method to use the right argument variable<commit_after>function APS( server, events, options ){
	this.option = {
		'poll': 25000,
		debug: false,
		session: true,
		connectionArgs: {},
		server: server,
		transport: ["wb", "lp"],
		//transport: "lp",
		secure: false
	}
	this.identifier = "APS";
	this.version = '0.9b1';
	this.state = 0;
	this.events = {};
	this.chl = 0;
	this.user = {};
	this.pipes = {};
	this.channels = {};
	this.eQueue = {};

	//Add Events
	if(!!events)
		this.on(events);

	//Update options
	if(!!options){
		for(var opt in options){
			this.option[opt] = options[opt];
		}
	}

	//IE9 crap - log function fix
	if(navigator.appName == "Microsoft Internet Explorer"){
		if(typeof window.console == "undefined"){
			this.log = function(){};
		}else{
			this.log = function(){
				if(this.option.debug == false) return;

				var args =  Array.prototype.slice.call(arguments);
				args.unshift("["+this.identifier+"]");

				window.console.log(args.join().replace(",",""));
			}

		}
	}

	var cb = {
		'onmessage': this.onMessage.bind(this),
		'onerror': this.log.bind(this, "T_ERR")
	}

	this.connect = function(args){
		if(this.state == 1)
			return this.log("Already Connected!");

		var client = this;
		this.option.connectionArgs = args || this.option.connectionArgs;

		//Handle transport
		if(!!this.transport){
			if(this.transport.state == 0){
				this.transport.close();
				this.transport = new APS.transport(server, cb, this);
			}else{
				//Use current active transport

			}
		}else{
			this.transport = new APS.transport(server, cb, this);
		}

		//Handle sessions
		if(this.option.session == true){
			if(this.session.restore() == true){
				return this;
			}
		}

		//Fresh Connect
		if(this.trigger("connect") == false)
			return false;

		this.sendCmd('CONNECT', this.option.connectionArgs);

		return this;
	}

	function getTransport() {
		if('XMLHttpRequest' in window) return XMLHttpRequest;
		if('ActiveXObject' in window) {
			var names = [
				"Msxml2.XMLHTTP.6.0",
				"Msxml2.XMLHTTP.3.0",
				"Msxml2.XMLHTTP",
				"Microsoft.XMLHTTP"
			];
			for(var i in names){
				try{ return ActiveXObject(names[i]); }
				catch(e){}
			}
		}
		return false;
	}

	var request;
	var transport = getTransport();

	this.request = function(addr, data, callback){
		request = new transport();
		request.onreadystatechange = function(){
			if(this.readyState == 4)
				callback(this.responseText);
		};
		request.open('POST', addr, true);
		request.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
		request.send(data);
	}

	this.session.client = this;
	return this;
}

APS.prototype.trigger = function(ev, args){
	ev = ev.toLowerCase();

	if(!(args instanceof Array)) args = [args];

	//GLobal
	if("client" in this){
		for(var i in this.client.events[ev]){
			if(this.client.events[ev].hasOwnProperty(i)){
				this.log("{{{ " + ev + " }}} on client ", this.client);
				if(this.client.events[ev][i].apply(this, args) === false)
					return false;
			}
		}
	}

	//Local
	for(var i in this.events[ev]){
		if(this.events[ev].hasOwnProperty(i)){
			if(!this.client){
				this.log("{{{ " + ev + " }}} on client ", this);
			}else{
				this.log("{{{ " + ev + " }}} ", this);
			}
			if(this.events[ev][i].apply(this, args) === false)
				return false;
		}
	}

	return true;
}

APS.prototype.on = function(ev, fn){
	var Events = [];

	if(typeof ev == 'string' && typeof fn == 'function'){
		Events[ev] = fn;
	}else if(typeof ev == "object"){
		Events = ev;
	}else{
		return this;
	}

	for(var e in Events){
		var fn = Events[e];
		if(!this.events[e])
			this.events[e] = [];
		this.events[e].push(fn);
	}

	return this;
}

APS.prototype.getPipe = function(user){
	if(typeof user == 'string'){
		return this.pipes[user];
	} else {
		return this.pipes[user.pubid];
	}
}

APS.prototype.send =function(pipe, $event, data, callback){
	this.sendCmd("Event", {
		event: $event,
		data: data
	}, pipe, callback);
}

APS.prototype.sendCmd = function(cmd, args, pipe, callback){
	var specialCmd = {CONNECT: 0, RESTORE:0};
	if(this.state == 1 || cmd in specialCmd){

		var tmp = {
			'cmd': cmd,
			'chl': this.chl
		}

		if(args) tmp.params = args;
		if(pipe) tmp.params.pipe = typeof pipe == 'string' ? pipe : pipe.pubid;
		if(this.session.id) tmp.sessid = this.session.id;

		this.log('<<<< ', cmd.toUpperCase() , " >>>> ", tmp);

		if(typeof callback != "function")	callback = function(){};

		var data = [];
		try {
			data = JSON.stringify([tmp]);
		}catch(e){
			this.log(e);
			this.log(data);
		}

		//Send command
		switch(cmd){
			case "Event":
				if(typeof this.transport.push == "function"){
					this.transport.push(data, callback);
					break;
				}
			default:
				this.transport.send(data, callback);

		}

		if(!(cmd in specialCmd)){
			this.poll();
		}
		this.chl++;
		this.session.saveChl();
	} else {
		this.on('ready', this.sendCmd.bind(this, cmd, args));
	}

	return this;
}

APS.prototype.poll = function(){
	if(this.transport.id == 0){
		clearTimeout(this.poller);
		this.poller = setTimeout((function(){ this.check() }).bind(this), this.option.poll);
	}
}

APS.prototype.check = function(force){
	//this.log("Chec")
	if(this.transport.id == 0 || !!force)
		this.sendCmd('CHECK');
}

APS.prototype.quit = function(){
	this.sendCmd('QUIT');
	this.transport.close();
	this.trigger("quit");
	//Clear session on 'quit'
	this.session.destroy();
	this.state = 0;
}

APS.prototype.sub = function(channel, Events, callback){
	//Handle the events
	if(typeof Events == "object"){
		if(typeof channel == "object"){
			for(var chan in channel){
				this.onChannel(channel[chan], Events);
			}
		}else{
			this.onChannel(channel, Events);
		}
	}

	//Handle callback
	if(typeof callback == "function"){
		if(typeof channel == "object"){
			for(var chan in channel){
				this.onChannel(channel[chan], "joined", callback);
			}
		}else{
			this.onChannel(channel, "joined", callback);
		}
	}

	//Join Channel
	if(this.state == 0){
		this.on("ready", this.sub.bind(this, channel));
		this.connect({user: this.user});

	}else if(typeof this.channels[channel] != "object"){
		this.sendCmd('JOIN', {'channels': channel});
	}

	return this;
}

APS.prototype.pub = function(channel, data, callback){
	var pipe = this.getChannel(channel);
	if(!pipe && channel.length == 32) pipe = this.getPipe(channel);

	if(pipe){
		var $event = typeof data == "string" ? "message" : "data";
		var args = {data: data};
		pipe.send($event, data, callback);
		//pipe.trigger("pub",args);
	}else{
		this.log("NO Channel " + channel);
	}
};

APS.prototype.getChannel = function(channel){
	channel = channel.toLowerCase();
	if(channel in this.channels){
		return this.channels[channel];
	}

	return false;
}

APS.prototype.onChannel = function(channel, Events, fn){
	channel = channel.toLowerCase();

	if(channel in this.channels){
		this.channels[channel].on(Events, fn);
		return true;
	}

	if(typeof Events == "object"){
		//add events to queue
		if(typeof this.eQueue[channel] != "object")
			this.eQueue[channel] = [];

		//this.eQueue[channel].push(Events);
		for(var $event in Events){
			var fn = Events[$event];

			this.eQueue[channel].push([$event, fn]);

			this.log("Adding ["+channel+"] event '"+$event+"' to queue");
		}
	}else{
		var xnew = Object();
		xnew[Events] = fn;
		this.onChannel(channel,xnew);
	}
}

APS.prototype.unSub = function(channel){
	if(channel == "") return;
	this.getChannel(channel).leave();
}

//Debug Function for Browsers console
if(navigator.appName != "Microsoft Internet Explorer"){
	APS.prototype.log = function(){
		if(!this.option.debug) return;

		var args =  Array.prototype.slice.call(arguments);
		args.unshift("["+this.identifier+"]");

		window.console.log.apply(console, args);
	};

}
<|endoftext|>


<commit_before>var w = window,
    d = document,
    e = d.documentElement,
    g = d.getElementById('chart'),
    width = g.clientWidth/1.1, //w.innerWidth || e.clientWidth || g.clientWidth,
    height = e.clientHeight/1.45;//w.innerHeight|| e.clientHeight|| g.clientHeight;

var margin = {top: 20, right: 20, bottom: 30, left: 140},
  width = width - margin.left - margin.right,
  height = height - margin.top - margin.bottom;

var color = d3.scale.category20();

var force = d3.layout.force()
    .charge(-120)
    .linkDistance(250)
    .friction(0.9)
    .size([width, height]);

var forceSvg = d3.select("div#chord_chart").append("svg")
    .attr("width", width)
    .attr("height", height);

var forceListSvg = d3.select('div#force_list').append('svg')
    .attr('width', 200)
    .attr('height', 2000)
    .append('g')
      .attr("transform", "translate(" + margin.right + "," + margin.top + ")");;

var node_drag = d3.behavior.drag()
    .on("dragstart", dragstart)
    .on("drag", dragmove)
    .on("dragend", dragend);
    function dragstart(d, i) {
        force.stop() // stops the force auto positioning before you start dragging
    }
    function dragmove(d, i) {
        d.px += d3.event.dx;
        d.py += d3.event.dy;
        d.x += d3.event.dx;
        d.y += d3.event.dy;
    }
    function dragend(d, i) {
        d.fixed = true; // of course set the node to fixed so the force doesn't include the node in its auto positioning stuff
        force.resume();
    }
    function releasenode(d) {
        d.fixed = false; // of course set the node to fixed so the force doesn't include the node in its auto positioning stuff
        //force.resume();
    };

var selectedList = [];

drawGraph(selectedList);

function drawGraph(selectedList){

  d3.csv("cooccurrenceMatrixData.csv", function(data){

    totallist = [];
      for (i=0; i<data.length; i++){
        if ($.inArray(data[i].word1, totallist) < 0){
          totallist.push(data[i].word1);
        }
        if ($.inArray(data[i].word2, totallist) < 0){
          totallist.push(data[i].word2);
        }
      }

    data1 = $.map(data, function(element){
          return ($.inArray(element.word1,selectedList)>-1?element:null);
        });
        data = $.map(data1, function(element){
          return ($.inArray(element.word2,selectedList)>-1?element:null);
        });

        graphDict = {};
        graphDict['nodes'] = [];
        graphDict['links'] = [];
        entrylist = [];
        for (i=0; i<data.length; i++){
          if ($.inArray(data[i].word1, entrylist) < 0){
            dict = {};
            dict['name'] = data[i].word1
            dict['group'] = 0
            graphDict['nodes'].push(dict)
            entrylist.push(data[i].word1);
          };
          if ($.inArray(data[i].word2, entrylist) < 0){
            dict = {};
            dict['name'] = data[i].word2
            dict['group'] = 0
            graphDict['nodes'].push(dict)
            entrylist.push(data[i].word2);
          };
          dict = {};
          dict['source'] = entrylist.indexOf(data[i].word1);
          dict['target'] = entrylist.indexOf(data[i].word2);
          dict['value'] = +data[i].size
          graphDict['links'].push(dict);
        };

    graph = graphDict;

    var term_label = forceListSvg.selectAll('.force_item')
            .data(totallist);

    term_label
            .enter()
          .append('text')
            .attr('class', 'force_item')
            .attr("x", 50)
            .attr("y", function(d,i){ return i + "em"; })
            .style("text-anchor", "middle")
            .style("font-size", "16px")
            .style("fill", "#53565A")
            .transition()
            .duration(750)
            //.style('fill', function(d){ return line_color(d.term); })
            .text(function(d){ return d; });

    term_label.on('click', function(d){
            if ($.inArray(d, selectedList) < 0){
              selectedList.push(d);
              drawGraph(selectedList);
              d3.select(this).style('fill', 'rgb(31, 119, 180)')
            }
            else {
              selectedList = selectedList.filter(function(e){ return e != d; });
              drawGraph(selectedList);
              d3.select(this).style('fill', 'rgb(83, 86, 90)')
            }
          });

      //data = prepData(selectedList);

        force
          .nodes(graph.nodes)
          .links(graph.links)
          .start();

        var graphMin = d3.min(graph.links, function(d){ return d.size; });
        var graphMax = d3.max(graph.links, function(d){ return d.size; });

        var fill = d3.scale.ordinal()
            .domain([graphMin, graphMax])
            .range(["#f7fcfd","#e5f5f9","#ccece6","#99d8c9","#66c2a4",
              "#41ae76","#238b45","#006d2c","#00441b"]);

        var div = d3.select('div#chord_chart').append('div')
                .attr('class', 'tooltip')
                .style('opacity', 0);

        var link = forceSvg.selectAll(".link")
            .data(graph.links);

        link
          .enter().append("line")
            .attr("class", "link")
            //.style('stroke-width', 1)
            //.style('stroke', function(d){ return fill(d.value); })
            .style('stroke', '#47996E')
            .style("stroke-width", function(d) { return Math.sqrt(d.value); });

        link.exit().remove();

        var node = forceSvg.selectAll(".node")
            .data(graph.nodes);

        node
          .enter().append("circle")
            .attr("class", "node")
            .attr("r", 10)
            //.style("fill", function(d) { return color(d.group); })
            .on('dblclick', releasenode)
            .on('click', connectedNodes)
            .call(node_drag);
            //.call(force.drag);

        node
            .on('mouseover', function(d,i,j){
                d3.select(this).transition().duration(600)
                  .attr('r', 15).style('opacity', 1);
                div.transition()
                  .duration(500)
                  .style('opacity', 1);
                div.html(d.name)
                  .style('left', '300px')
                  .style('top', '10px');
                  //.style('left', (d3.event.pageX) + 10 + "px")
                  //.style('top', (d3.event.pageY) + 2 + "px")
                  //.style('color', line_color(used_data[j].term));
            })
            .on('mouseout', function(d){
                d3.select(this).transition().duration(600)
                  .attr('r', 10).style('opacity', 1);
                div.transition()
                  .duration(500)
                  .style('opacity', 0);
            });
        node.append("title")
            .text(function(d) { return d.name; });

        node.exit().remove();

        force.on("tick", function() {
          link.attr("x1", function(d) { return d.source.x; })
              .attr("y1", function(d) { return d.source.y; })
              .attr("x2", function(d) { return d.target.x; })
              .attr("y2", function(d) { return d.target.y; });

          node.attr("cx", function(d) { return d.x; })
              .attr("cy", function(d) { return d.y; });
        });

        //Toggle stores whether the highlighting is on
        var toggle = 0;

        //Create an array logging what is connected to what
        var linkedByIndex = {};
        for (i = 0; i < graph.nodes.length; i++) {
            linkedByIndex[i + "," + i] = 1;
        };
        graph.links.forEach(function (d) {
            linkedByIndex[d.source.index + "," + d.target.index] = 1;
        });

        //This function looks up whether a pair are neighbours
        function neighboring(a, b) {
            return linkedByIndex[a.index + "," + b.index];
        }

        function connectedNodes() {

          if (toggle == 0) {
              //Reduce the opacity of all but the neighbouring nodes
              d = d3.select(this).node().__data__;
              node.style("opacity", function (o) {
                  return neighboring(d, o) | neighboring(o, d) ? 1 : 0.1;
              });

              link.style("opacity", function (o) {
                  return d.index==o.source.index | d.index==o.target.index ? 1 : 0.1;
              });

              //Reduce the op

              toggle = 1;
          } else {
              //Put them back to opacity=1
              node.style("opacity", 1);
              link.style("opacity", 1);
              toggle = 0;
          }
        }

  });

};

function prepData(data, list){

      data1 = $.map(data, function(element){
        return ($.inArray(element.word1,list)>-1?element:null);
      });
      data = $.map(data1, function(element){
        return ($.inArray(element.word2,list)>-1?element:null);
      });

      graphDict = {};
      graphDict['nodes'] = [];
      graphDict['links'] = [];
      entrylist = [];
      for (i=0; i<data.length; i++){
        if ($.inArray(data[i].word1, entrylist) < 0){
          dict = {};
          dict['name'] = data[i].word1
          dict['group'] = 0
          graphDict['nodes'].push(dict)
          entrylist.push(data[i].word1);
        };
        if ($.inArray(data[i].word2, entrylist) < 0){
          dict = {};
          dict['name'] = data[i].word2
          dict['group'] = 0
          graphDict['nodes'].push(dict)
          entrylist.push(data[i].word2);
        };
        dict = {};
        dict['source'] = entrylist.indexOf(data[i].word1);
        dict['target'] = entrylist.indexOf(data[i].word2);
        dict['value'] = +data[i].size
        graphDict['links'].push(dict);
      };
      //return graphDict;
    };

/*
d3.json("newsGraph.json", function(error, graph) {
  testGraph = JSON.parse(JSON.stringify(graph))

  selectedList = ['up','police','china','labor','union'];
  selectedData1 = $.map(testGraph.nodes, function(element){
      return ($.inArray(element.name,selectedList)>-1?element:null);
    });

  selectedData2 = $.map(testGraph.links, function(element){
      return ($.inArray(element['name1'],selectedList)>-1?element:null);
    });

  selectedData3 = $.map(selectedData2, function(element){
      return ($.inArray(element.name2,selectedList)>-1?element:null);
    });

  new_graph = {};
  new_graph['nodes'] = graph.nodes;
  new_graph['links'] = selectedData3;

  //drawGraph(graph, selectedData1, selectedData3);
  drawGraph(graph);

});
*/

<commit_msg>resize window<commit_after>var w = window,
    d = document,
    e = d.documentElement,
    g = d.getElementById('chart'),
    width = g.clientWidth/1.1, //w.innerWidth || e.clientWidth || g.clientWidth,
    height = e.clientHeight/1.45;//w.innerHeight|| e.clientHeight|| g.clientHeight;

var margin = {top: 20, right: 20, bottom: 30, left: 140},
  width = width - margin.left - margin.right,
  height = height - margin.top - margin.bottom;

var color = d3.scale.category20();

var force = d3.layout.force()
    .charge(-120)
    .linkDistance(250)
    .friction(0.9)
    .size([width, height]);

var forceSvg = d3.select("div#chord_chart").append("svg")
    .attr("width", width)
    .attr("height", height);

var forceListSvg = d3.select('div#force_list').append('svg')
    .attr('width', 200)
    .attr('height', 2000)
    .append('g')
      .attr("transform", "translate(" + margin.right + "," + margin.top + ")");;

var node_drag = d3.behavior.drag()
    .on("dragstart", dragstart)
    .on("drag", dragmove)
    .on("dragend", dragend);
    function dragstart(d, i) {
        force.stop() // stops the force auto positioning before you start dragging
    }
    function dragmove(d, i) {
        d.px += d3.event.dx;
        d.py += d3.event.dy;
        d.x += d3.event.dx;
        d.y += d3.event.dy;
    }
    function dragend(d, i) {
        d.fixed = true; // of course set the node to fixed so the force doesn't include the node in its auto positioning stuff
        force.resume();
    }
    function releasenode(d) {
        d.fixed = false; // of course set the node to fixed so the force doesn't include the node in its auto positioning stuff
        //force.resume();
    };

var selectedList = [];

drawGraph(selectedList);

function drawGraph(selectedList){

  d3.csv("cooccurrenceMatrixData.csv", function(data){

    totallist = [];
      for (i=0; i<data.length; i++){
        if ($.inArray(data[i].word1, totallist) < 0){
          totallist.push(data[i].word1);
        }
        if ($.inArray(data[i].word2, totallist) < 0){
          totallist.push(data[i].word2);
        }
      }

    data1 = $.map(data, function(element){
          return ($.inArray(element.word1,selectedList)>-1?element:null);
        });
        data = $.map(data1, function(element){
          return ($.inArray(element.word2,selectedList)>-1?element:null);
        });

        graphDict = {};
        graphDict['nodes'] = [];
        graphDict['links'] = [];
        entrylist = [];
        for (i=0; i<data.length; i++){
          if ($.inArray(data[i].word1, entrylist) < 0){
            dict = {};
            dict['name'] = data[i].word1
            dict['group'] = 0
            graphDict['nodes'].push(dict)
            entrylist.push(data[i].word1);
          };
          if ($.inArray(data[i].word2, entrylist) < 0){
            dict = {};
            dict['name'] = data[i].word2
            dict['group'] = 0
            graphDict['nodes'].push(dict)
            entrylist.push(data[i].word2);
          };
          dict = {};
          dict['source'] = entrylist.indexOf(data[i].word1);
          dict['target'] = entrylist.indexOf(data[i].word2);
          dict['value'] = +data[i].size
          graphDict['links'].push(dict);
        };

    graph = graphDict;

    var term_label = forceListSvg.selectAll('.force_item')
            .data(totallist);

    term_label
            .enter()
          .append('text')
            .attr('class', 'force_item')
            .attr("x", 50)
            .attr("y", function(d,i){ return i + "em"; })
            .style("text-anchor", "middle")
            .style("font-size", "16px")
            .style("fill", "#53565A")
            .transition()
            .duration(750)
            //.style('fill', function(d){ return line_color(d.term); })
            .text(function(d){ return d; });

    term_label.on('click', function(d){
            if ($.inArray(d, selectedList) < 0){
              selectedList.push(d);
              drawGraph(selectedList);
              d3.select(this).style('fill', 'rgb(31, 119, 180)')
            }
            else {
              selectedList = selectedList.filter(function(e){ return e != d; });
              drawGraph(selectedList);
              d3.select(this).style('fill', 'rgb(83, 86, 90)')
            }
          });

      //data = prepData(selectedList);

        force
          .nodes(graph.nodes)
          .links(graph.links)
          .start();

        var graphMin = d3.min(graph.links, function(d){ return d.size; });
        var graphMax = d3.max(graph.links, function(d){ return d.size; });

        var fill = d3.scale.ordinal()
            .domain([graphMin, graphMax])
            .range(["#f7fcfd","#e5f5f9","#ccece6","#99d8c9","#66c2a4",
              "#41ae76","#238b45","#006d2c","#00441b"]);

        var div = d3.select('div#chord_chart').append('div')
                .attr('class', 'tooltip')
                .style('opacity', 0);

        var link = forceSvg.selectAll(".link")
            .data(graph.links);

        link
          .enter().append("line")
            .attr("class", "link")
            //.style('stroke-width', 1)
            //.style('stroke', function(d){ return fill(d.value); })
            .style('stroke', '#47996E')
            .style("stroke-width", function(d) { return Math.sqrt(d.value); });

        link.exit().remove();

        var node = forceSvg.selectAll(".node")
            .data(graph.nodes);

        node
          .enter().append("circle")
            .attr("class", "node")
            .attr("r", 10)
            //.style("fill", function(d) { return color(d.group); })
            .on('dblclick', releasenode)
            .on('click', connectedNodes)
            .call(node_drag);
            //.call(force.drag);

        node
            .on('mouseover', function(d,i,j){
                d3.select(this).transition().duration(600)
                  .attr('r', 15).style('opacity', 1);
                div.transition()
                  .duration(500)
                  .style('opacity', 1);
                div.html(d.name)
                  .style('left', '50px')
                  .style('top', '10px');
                  //.style('left', (d3.event.pageX) + 10 + "px")
                  //.style('top', (d3.event.pageY) + 2 + "px")
                  //.style('color', line_color(used_data[j].term));
            })
            .on('mouseout', function(d){
                d3.select(this).transition().duration(600)
                  .attr('r', 10).style('opacity', 1);
                div.transition()
                  .duration(500)
                  .style('opacity', 0);
            });
        node.append("title")
            .text(function(d) { return d.name; });

        node.exit().remove();

        force.on("tick", function() {
          link.attr("x1", function(d) { return d.source.x; })
              .attr("y1", function(d) { return d.source.y; })
              .attr("x2", function(d) { return d.target.x; })
              .attr("y2", function(d) { return d.target.y; });

          node.attr("cx", function(d) { return d.x; })
              .attr("cy", function(d) { return d.y; });
        });

        //Toggle stores whether the highlighting is on
        var toggle = 0;

        //Create an array logging what is connected to what
        var linkedByIndex = {};
        for (i = 0; i < graph.nodes.length; i++) {
            linkedByIndex[i + "," + i] = 1;
        };
        graph.links.forEach(function (d) {
            linkedByIndex[d.source.index + "," + d.target.index] = 1;
        });

        //This function looks up whether a pair are neighbours
        function neighboring(a, b) {
            return linkedByIndex[a.index + "," + b.index];
        }

        function connectedNodes() {

          if (toggle == 0) {
              //Reduce the opacity of all but the neighbouring nodes
              d = d3.select(this).node().__data__;
              node.style("opacity", function (o) {
                  return neighboring(d, o) | neighboring(o, d) ? 1 : 0.1;
              });

              link.style("opacity", function (o) {
                  return d.index==o.source.index | d.index==o.target.index ? 1 : 0.1;
              });

              //Reduce the op

              toggle = 1;
          } else {
              //Put them back to opacity=1
              node.style("opacity", 1);
              link.style("opacity", 1);
              toggle = 0;
          }
        }

  });

};

function prepData(data, list){

      data1 = $.map(data, function(element){
        return ($.inArray(element.word1,list)>-1?element:null);
      });
      data = $.map(data1, function(element){
        return ($.inArray(element.word2,list)>-1?element:null);
      });

      graphDict = {};
      graphDict['nodes'] = [];
      graphDict['links'] = [];
      entrylist = [];
      for (i=0; i<data.length; i++){
        if ($.inArray(data[i].word1, entrylist) < 0){
          dict = {};
          dict['name'] = data[i].word1
          dict['group'] = 0
          graphDict['nodes'].push(dict)
          entrylist.push(data[i].word1);
        };
        if ($.inArray(data[i].word2, entrylist) < 0){
          dict = {};
          dict['name'] = data[i].word2
          dict['group'] = 0
          graphDict['nodes'].push(dict)
          entrylist.push(data[i].word2);
        };
        dict = {};
        dict['source'] = entrylist.indexOf(data[i].word1);
        dict['target'] = entrylist.indexOf(data[i].word2);
        dict['value'] = +data[i].size
        graphDict['links'].push(dict);
      };
      //return graphDict;
    };

/*
d3.json("newsGraph.json", function(error, graph) {
  testGraph = JSON.parse(JSON.stringify(graph))

  selectedList = ['up','police','china','labor','union'];
  selectedData1 = $.map(testGraph.nodes, function(element){
      return ($.inArray(element.name,selectedList)>-1?element:null);
    });

  selectedData2 = $.map(testGraph.links, function(element){
      return ($.inArray(element['name1'],selectedList)>-1?element:null);
    });

  selectedData3 = $.map(selectedData2, function(element){
      return ($.inArray(element.name2,selectedList)>-1?element:null);
    });

  new_graph = {};
  new_graph['nodes'] = graph.nodes;
  new_graph['links'] = selectedData3;

  //drawGraph(graph, selectedData1, selectedData3);
  drawGraph(graph);

});
*/

<|endoftext|>


<commit_before>var width = 960,
    height = 500;

var color = d3.scale.category20();

var force = d3.layout.force()
    .charge(-80)
    .linkDistance(200)
    .friction(0.9)
    .size([width, height]);

var forceSvg = d3.select("div#chord_chart").append("svg")
    .attr("width", width)
    .attr("height", height);

var node_drag = d3.behavior.drag()
    .on("dragstart", dragstart)
    .on("drag", dragmove)
    .on("dragend", dragend);
    function dragstart(d, i) {
        force.stop() // stops the force auto positioning before you start dragging
    }
    function dragmove(d, i) {
        d.px += d3.event.dx;
        d.py += d3.event.dy;
        d.x += d3.event.dx;
        d.y += d3.event.dy;
    }
    function dragend(d, i) {
        d.fixed = true; // of course set the node to fixed so the force doesn't include the node in its auto positioning stuff
        force.resume();

    }
    function releasenode(d) {
        d.fixed = false; // of course set the node to fixed so the force doesn't include the node in its auto positioning stuff
        //force.resume();
    };

d3.json("newsGraph.json", function(error, graph) {
  testGraph = JSON.parse(JSON.stringify(graph))

  selectedList = ['up','police','china','labor','union'];
  selectedData1 = $.map(testGraph.nodes, function(element){
      return ($.inArray(element.name,selectedList)>-1?element:null);
    });

  selectedData2 = $.map(testGraph.links, function(element){
      return ($.inArray(element['name1'],selectedList)>-1?element:null);
    });
  console.log(selectedData2);

  selectedData3 = $.map(selectedData2, function(element){
      return ($.inArray(element.name2,selectedList)>-1?element:null);
    });

  new_graph = {};
  new_graph['nodes'] = graph.nodes;
  new_graph['links'] = selectedData3;

  console.log(new_graph);
  drawGraph(graph, selectedData1, selectedData3);

  function drawGraph(graph, nodes, links){
    console.log(nodes);
    force
      .nodes(graph.nodes)
      .links(graph.links)
      .start();

    var graphMin = d3.min(graph.links, function(d){ return d.size; });
    var graphMax = d3.max(graph.links, function(d){ return d.size; });

    var fill = d3.scale.ordinal()
        .domain([graphMin, graphMax])
        .range(["#f7fcfd","#e5f5f9","#ccece6","#99d8c9","#66c2a4",
          "#41ae76","#238b45","#006d2c","#00441b"]);

    var div = d3.select('div#chord_chart').append('div')
            .attr('class', 'tooltip')
            .style('opacity', 0);

    var link = forceSvg.selectAll(".link")
        .data(graph.links)
      .enter().append("line")
        .attr("class", "link")
        .style('stroke-width', 1)
        .style('stroke', function(d){ return fill(d.value); });
        //.style("stroke-width", function(d) { return Math.sqrt(d.value); });

    var node = forceSvg.selectAll(".node")
        .data(graph.nodes)
      .enter().append("circle")
        .attr("class", "node")
        .attr("r", 5)
        .style("fill", function(d) { return color(d.group); })
        .on('dblclick', releasenode)
        .on('click', connectedNodes)
        .call(node_drag);
        //.call(force.drag);

    node
        .on('mouseover', function(d,i,j){
            d3.select(this).transition().duration(600)
              .attr('r', 8).style('opacity', 1);
            div.transition()
              .duration(500)
              .style('opacity', 1);
            div.html(d.name)
              .style('left', '300px')
              .style('top', '10px');
              //.style('left', (d3.event.pageX) + 10 + "px")
              //.style('top', (d3.event.pageY) + 2 + "px")
              //.style('color', line_color(used_data[j].term));
        })
        .on('mouseout', function(d){
            d3.select(this).transition().duration(600)
              .attr('r', 5).style('opacity', 1);
            div.transition()
              .duration(500)
              .style('opacity', 0);
        });

    node.append("title")
        .text(function(d) { return d.name; });

    force.on("tick", function() {
      link.attr("x1", function(d) { return d.source.x; })
          .attr("y1", function(d) { return d.source.y; })
          .attr("x2", function(d) { return d.target.x; })
          .attr("y2", function(d) { return d.target.y; });

      node.attr("cx", function(d) { return d.x; })
          .attr("cy", function(d) { return d.y; });
    });

    var k = 0;
    while ((force.alpha() > 1e-2) && (k < 150)) {
        force.tick(),
        k = k + 1;
    }

    //Toggle stores whether the highlighting is on
  var toggle = 0;

  //Create an array logging what is connected to what
  var linkedByIndex = {};
  for (i = 0; i < graph.nodes.length; i++) {
      linkedByIndex[i + "," + i] = 1;
  };
  graph.links.forEach(function (d) {
      linkedByIndex[d.source.index + "," + d.target.index] = 1;
  });

  //This function looks up whether a pair are neighbours
  function neighboring(a, b) {
      return linkedByIndex[a.index + "," + b.index];
  }

  function connectedNodes() {

    if (toggle == 0) {
        //Reduce the opacity of all but the neighbouring nodes
        d = d3.select(this).node().__data__;
        node.style("opacity", function (o) {
            return neighboring(d, o) | neighboring(o, d) ? 1 : 0.1;
        });

        link.style("opacity", function (o) {
            return d.index==o.source.index | d.index==o.target.index ? 1 : 0.1;
        });

        //Reduce the op

        toggle = 1;
    } else {
        //Put them back to opacity=1
        node.style("opacity", 1);
        link.style("opacity", 1);
        toggle = 0;
    }

}
  }

});

<commit_msg>update data<commit_after>var width = 960,
    height = 500;

var color = d3.scale.category20();

var force = d3.layout.force()
    .charge(-80)
    .linkDistance(200)
    .friction(0.9)
    .size([width, height]);

var forceSvg = d3.select("div#chord_chart").append("svg")
    .attr("width", width)
    .attr("height", height);

var node_drag = d3.behavior.drag()
    .on("dragstart", dragstart)
    .on("drag", dragmove)
    .on("dragend", dragend);
    function dragstart(d, i) {
        force.stop() // stops the force auto positioning before you start dragging
    }
    function dragmove(d, i) {
        d.px += d3.event.dx;
        d.py += d3.event.dy;
        d.x += d3.event.dx;
        d.y += d3.event.dy;
    }
    function dragend(d, i) {
        d.fixed = true; // of course set the node to fixed so the force doesn't include the node in its auto positioning stuff
        force.resume();
        for (var i = 0; i < 20; ++i) force.tick();
        force.stop();

    }
    function releasenode(d) {
        d.fixed = false; // of course set the node to fixed so the force doesn't include the node in its auto positioning stuff
        //force.resume();
    };

d3.json("newsGraph.json", function(error, graph) {
  testGraph = JSON.parse(JSON.stringify(graph))

  selectedList = ['up','police','china','labor','union'];
  selectedData1 = $.map(testGraph.nodes, function(element){
      return ($.inArray(element.name,selectedList)>-1?element:null);
    });

  selectedData2 = $.map(testGraph.links, function(element){
      return ($.inArray(element['name1'],selectedList)>-1?element:null);
    });

  selectedData3 = $.map(selectedData2, function(element){
      return ($.inArray(element.name2,selectedList)>-1?element:null);
    });

  new_graph = {};
  new_graph['nodes'] = graph.nodes;
  new_graph['links'] = selectedData3;

  console.log(new_graph);
  drawGraph(graph, selectedData1, selectedData3);

  function drawGraph(graph, nodes, links){
    force
      .nodes(graph.nodes)
      .links(graph.links)
      .start();

    var graphMin = d3.min(graph.links, function(d){ return d.size; });
    var graphMax = d3.max(graph.links, function(d){ return d.size; });

    var fill = d3.scale.ordinal()
        .domain([graphMin, graphMax])
        .range(["#f7fcfd","#e5f5f9","#ccece6","#99d8c9","#66c2a4",
          "#41ae76","#238b45","#006d2c","#00441b"]);

    var div = d3.select('div#chord_chart').append('div')
            .attr('class', 'tooltip')
            .style('opacity', 0);

    var link = forceSvg.selectAll(".link")
        .data(graph.links)
      .enter().append("line")
        .attr("class", "link")
        .style('stroke-width', 1)
        .style('stroke', function(d){ return fill(d.value); });
        //.style("stroke-width", function(d) { return Math.sqrt(d.value); });

    var node = forceSvg.selectAll(".node")
        .data(graph.nodes)
      .enter().append("circle")
        .attr("class", "node")
        .attr("r", 5)
        .style("fill", function(d) { return color(d.group); })
        .on('dblclick', releasenode)
        .on('click', connectedNodes)
        .call(node_drag);
        //.call(force.drag);

    node
        .on('mouseover', function(d,i,j){
            d3.select(this).transition().duration(600)
              .attr('r', 8).style('opacity', 1);
            div.transition()
              .duration(500)
              .style('opacity', 1);
            div.html(d.name)
              .style('left', '300px')
              .style('top', '10px');
              //.style('left', (d3.event.pageX) + 10 + "px")
              //.style('top', (d3.event.pageY) + 2 + "px")
              //.style('color', line_color(used_data[j].term));
        })
        .on('mouseout', function(d){
            d3.select(this).transition().duration(600)
              .attr('r', 5).style('opacity', 1);
            div.transition()
              .duration(500)
              .style('opacity', 0);
        });

    node.append("title")
        .text(function(d) { return d.name; });

    force.on("tick", function() {
      link.attr("x1", function(d) { return d.source.x; })
          .attr("y1", function(d) { return d.source.y; })
          .attr("x2", function(d) { return d.target.x; })
          .attr("y2", function(d) { return d.target.y; });

      node.attr("cx", function(d) { return d.x; })
          .attr("cy", function(d) { return d.y; });
    });

    var k = 0;
    while ((force.alpha() > 1e-2) && (k < 150)) {
        force.tick(),
        k = k + 1;
    }

    //Toggle stores whether the highlighting is on
  var toggle = 0;

  //Create an array logging what is connected to what
  var linkedByIndex = {};
  for (i = 0; i < graph.nodes.length; i++) {
      linkedByIndex[i + "," + i] = 1;
  };
  graph.links.forEach(function (d) {
      linkedByIndex[d.source.index + "," + d.target.index] = 1;
  });

  //This function looks up whether a pair are neighbours
  function neighboring(a, b) {
      return linkedByIndex[a.index + "," + b.index];
  }

  function connectedNodes() {

    if (toggle == 0) {
        //Reduce the opacity of all but the neighbouring nodes
        d = d3.select(this).node().__data__;
        node.style("opacity", function (o) {
            return neighboring(d, o) | neighboring(o, d) ? 1 : 0.1;
        });

        link.style("opacity", function (o) {
            return d.index==o.source.index | d.index==o.target.index ? 1 : 0.1;
        });

        //Reduce the op

        toggle = 1;
    } else {
        //Put them back to opacity=1
        node.style("opacity", 1);
        link.style("opacity", 1);
        toggle = 0;
    }

}
  }

});

<|endoftext|>


<commit_before>/*!
 * Start Bootstrap - Freelancer Bootstrap Theme (http://startbootstrap.com)
 * Code licensed under the Apache License v2.0.
 * For details, see http://www.apache.org/licenses/LICENSE-2.0.
 */

// jQuery for page scrolling feature - requires jQuery Easing plugin
$(function() {
    $('.page-scroll a').bind('click', function(event) {
        var $anchor = $(this);
        $('html, body').stop().animate({
            scrollTop: $($anchor.attr('href')).offset().top
        }, 900, 'easeInOutExpo');
        event.preventDefault();
    });
});

// Floating label headings for the contact form
$(function() {
    $("body").on("input propertychange", ".floating-label-form-group", function(e) {
        $(this).toggleClass("floating-label-form-group-with-value", !! $(e.target).val());
    }).on("focus", ".floating-label-form-group", function() {
        $(this).addClass("floating-label-form-group-with-focus");
    }).on("blur", ".floating-label-form-group", function() {
        $(this).removeClass("floating-label-form-group-with-focus");
    });
});

// fade in elements on scroll
$(function(){  // $(document).ready shorthand
  $('.monster').fadeIn('slow');
});
$(document).ready(function() {
    /* Every time the window is scrolled ... */
    $(window).scroll( function(){
        /* Check the location of each desired element */
        $('.hideme').each( function(i){
            var bottom_of_object = $(this).position().top + $(this).outerHeight();
            var bottom_of_window = $(window).scrollTop() + $(window).height();
            /* If the object is completely visible in the window, fade it it */
            if( bottom_of_window > bottom_of_object ){
                $(this).animate({'opacity':'1'},13);
            }
        });
    });
});

// changes dropdown in contact form based on package link clicked
var $select = $('#select');
$('a[href="#contact"]').click(function () {
    $select.val( $(this).data('select') );
});

// Highlight the top nav as scrolling occurs
$('body').scrollspy({
    target: '.navbar-fixed-top'
})

// Carousel
$('.carousel').carousel({
  pause: null
})

$(function () {
  $('[data-toggle="tooltip"]').tooltip()
})

// Closes the Responsive Menu on Menu Item Click
$('.navbar-collapse ul li a').click(function() {
    $('.navbar-toggle:visible').click();
});
<commit_msg>changed face in timing<commit_after>/*!
 * Start Bootstrap - Freelancer Bootstrap Theme (http://startbootstrap.com)
 * Code licensed under the Apache License v2.0.
 * For details, see http://www.apache.org/licenses/LICENSE-2.0.
 */

// jQuery for page scrolling feature - requires jQuery Easing plugin
$(function() {
    $('.page-scroll a').bind('click', function(event) {
        var $anchor = $(this);
        $('html, body').stop().animate({
            scrollTop: $($anchor.attr('href')).offset().top
        }, 900, 'easeInOutExpo');
        event.preventDefault();
    });
});

// Floating label headings for the contact form
$(function() {
    $("body").on("input propertychange", ".floating-label-form-group", function(e) {
        $(this).toggleClass("floating-label-form-group-with-value", !! $(e.target).val());
    }).on("focus", ".floating-label-form-group", function() {
        $(this).addClass("floating-label-form-group-with-focus");
    }).on("blur", ".floating-label-form-group", function() {
        $(this).removeClass("floating-label-form-group-with-focus");
    });
});

// fade in elements on scroll
$(function(){  // $(document).ready shorthand
  $('.monster').fadeIn('slow');
});
$(document).ready(function() {
    /* Every time the window is scrolled ... */
    $(window).scroll( function(){
        /* Check the location of each desired element */
        $('.hideme').each( function(i){
            var bottom_of_object = $(this).position().top + $(this).outerHeight();
            var bottom_of_window = $(window).scrollTop() + $(window).height();
            /* If the object is completely visible in the window, fade it it */
            if( bottom_of_window > bottom_of_object ){
                $(this).animate({'opacity':'1'},2);
            }
        });
    });
});

// changes dropdown in contact form based on package link clicked
var $select = $('#select');
$('a[href="#contact"]').click(function () {
    $select.val( $(this).data('select') );
});

// Highlight the top nav as scrolling occurs
$('body').scrollspy({
    target: '.navbar-fixed-top'
})

// Carousel
$('.carousel').carousel({
  pause: null
})

$(function () {
  $('[data-toggle="tooltip"]').tooltip()
})

// Closes the Responsive Menu on Menu Item Click
$('.navbar-collapse ul li a').click(function() {
    $('.navbar-toggle:visible').click();
});
<|endoftext|>


<commit_before>/*!
 * Start Bootstrap - Freelancer Bootstrap Theme (http://startbootstrap.com)
 * Code licensed under the Apache License v2.0.
 * For details, see http://www.apache.org/licenses/LICENSE-2.0.
 */

// jQuery for page scrolling feature - requires jQuery Easing plugin
$(function() {
    $('body').on('click', '.page-scroll a', function(event) {
        var $anchor = $(this);
        $('html, body').stop().animate({
            scrollTop: $($anchor.attr('href')).offset().top
        }, 1500, 'easeInOutExpo');
        event.preventDefault();
    });
});

// Floating label headings for the contact form
$(function() {
    $("body").on("input propertychange", ".floating-label-form-group", function(e) {
        $(this).toggleClass("floating-label-form-group-with-value", !! $(e.target).val());
    }).on("focus", ".floating-label-form-group", function() {
        $(this).addClass("floating-label-form-group-with-focus");
    }).on("blur", ".floating-label-form-group", function() {
        $(this).removeClass("floating-label-form-group-with-focus");
    });
});

// Highlight the top nav as scrolling occurs
$('body').scrollspy({
    target: '.navbar-fixed-top'
})

// Closes the Responsive Menu on Menu Item Click
$('.navbar-collapse ul li a').click(function() {
    $('.navbar-toggle:visible').click();
});

//Jiggy Journal

//dropdown menu

$(document).ready(function () {
    //Handles menu drop down
    $('.dropdown-menu').find('form').click(function (e) {
        e.stopPropagation();
    });
});

// interval is in milliseconds. 1000 = 1 second - so 1000 * 10 = 10 seconds
$('.carousel').carousel({
  interval: 1000 * 4
});

//Datepicker

$(document).ready(function(){
    $('.input-group.date input').datepicker({
        format: "mm/dd/yyyy",
        autoclose: true,
        todayHighlight: true,
        todayBtn: "linked",
        orientation: "bottom right"
    });
});

$(document).ready(function () {
    $('[data-toggle="tooltip"]').tooltip();
});

// Validates that the input string is a valid date formatted as "mm/dd/yyyy"
function isValidDate($el, dateString, callback)
{
    // First check for the pattern
    if(!/^\d{1,2}\/\d{1,2}\/\d{4}$/.test(dateString))
    {
        returnValue = false;
    }

    // Parse the date parts to integers
    var parts = dateString.split("/");
    var day = parseInt(parts[1], 10);
    var month = parseInt(parts[0], 10);
    var year = parseInt(parts[2], 10);

    // Check the ranges of month and year
    if(year < 1000 || year > 3000 || month == 0 || month > 12)
    {
        returnValue = false;
    }

    var monthLength = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];

    // Adjust for leap years
    if(year % 400 == 0 || (year % 100 != 0 && year % 4 == 0))
        monthLength[1] = 29;

    // Check the range of the day
    returnValue =  day > 0 && day <= monthLength[month - 1];

    callback({
      value: dateString,
      valid: returnValue,
      message: "Must be a valid date in mm/dd/yyyy format"
    });
};

//Image preview function
function readURL(input) {

    if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {
            $('#preview').attr('src', e.target.result);
        }

        reader.readAsDataURL(input.files[0]);
    }
}

$("#imageInput").change(function(){
    readURL(this);
});

//Selecting other in security question shows input box
function selectSecurityQuestion(){
    $('#otherQuestion').value = $('#question').value;
   /* if(this.options[this.selectedIndex].value == "Other")
    {
        this.form.ques.value = "";
        $('#otherQuestion').show();
    }
    else
    {
        $('#otherQuestion').hide();
    }*/
}<commit_msg>Register security update<commit_after>/*!
 * Start Bootstrap - Freelancer Bootstrap Theme (http://startbootstrap.com)
 * Code licensed under the Apache License v2.0.
 * For details, see http://www.apache.org/licenses/LICENSE-2.0.
 */

// jQuery for page scrolling feature - requires jQuery Easing plugin
$(function() {
    $('body').on('click', '.page-scroll a', function(event) {
        var $anchor = $(this);
        $('html, body').stop().animate({
            scrollTop: $($anchor.attr('href')).offset().top
        }, 1500, 'easeInOutExpo');
        event.preventDefault();
    });
});

// Floating label headings for the contact form
$(function() {
    $("body").on("input propertychange", ".floating-label-form-group", function(e) {
        $(this).toggleClass("floating-label-form-group-with-value", !! $(e.target).val());
    }).on("focus", ".floating-label-form-group", function() {
        $(this).addClass("floating-label-form-group-with-focus");
    }).on("blur", ".floating-label-form-group", function() {
        $(this).removeClass("floating-label-form-group-with-focus");
    });
});

// Highlight the top nav as scrolling occurs
$('body').scrollspy({
    target: '.navbar-fixed-top'
})

// Closes the Responsive Menu on Menu Item Click
$('.navbar-collapse ul li a').click(function() {
    $('.navbar-toggle:visible').click();
});

//Jiggy Journal

//dropdown menu

$(document).ready(function () {
    //Handles menu drop down
    $('.dropdown-menu').find('form').click(function (e) {
        e.stopPropagation();
    });
});

// interval is in milliseconds. 1000 = 1 second - so 1000 * 10 = 10 seconds
$('.carousel').carousel({
  interval: 1000 * 4
});

//Datepicker

$(document).ready(function(){
    $('.input-group.date input').datepicker({
        format: "mm/dd/yyyy",
        autoclose: true,
        todayHighlight: true,
        todayBtn: "linked",
        orientation: "bottom right"
    });
});

$(document).ready(function () {
    $('[data-toggle="tooltip"]').tooltip();
});

// Validates that the input string is a valid date formatted as "mm/dd/yyyy"
function isValidDate($el, dateString, callback)
{
    // First check for the pattern
    if(!/^\d{1,2}\/\d{1,2}\/\d{4}$/.test(dateString))
    {
        returnValue = false;
    }

    // Parse the date parts to integers
    var parts = dateString.split("/");
    var day = parseInt(parts[1], 10);
    var month = parseInt(parts[0], 10);
    var year = parseInt(parts[2], 10);

    // Check the ranges of month and year
    if(year < 1000 || year > 3000 || month == 0 || month > 12)
    {
        returnValue = false;
    }

    var monthLength = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];

    // Adjust for leap years
    if(year % 400 == 0 || (year % 100 != 0 && year % 4 == 0))
        monthLength[1] = 29;

    // Check the range of the day
    returnValue =  day > 0 && day <= monthLength[month - 1];

    callback({
      value: dateString,
      valid: returnValue,
      message: "Must be a valid date in mm/dd/yyyy format"
    });
};

//Image preview function
function readURL(input) {

    if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {
            $('#preview').attr('src', e.target.result);
        }

        reader.readAsDataURL(input.files[0]);
    }
}

$("#imageInput").change(function(){
    readURL(this);
});

//Selecting other in security question shows input box
function selectSecurityQuestion(){
    $('#otherQuestion').val($('#question').val());
    if($('#question').val() == "Other")
    {
        $('#otherQuestion').val("");
        $('#otherQuestion').show();
    }
    else
    {
        $('#otherQuestion').hide();
    }
}<|endoftext|>


<commit_before>// Copyright 2015, University of Colorado Boulder

/**
 * Runs the lint rules on the specified files.
 *
 * @author Sam Reid (PhET Interactive Simulations)
 */
/* eslint-env node */
'use strict';

// modules
var eslint = require( 'eslint' );
var assert = require( 'assert' );

// constants
var CLIEngine = eslint.CLIEngine;

/**
 * Gets the relative path for the given repo.
 * @param {string} repo
 * @returns {string}
 */
var GET_PATH = function( repo ) { return '../' + repo; };

/**
 * @param grunt - the grunt instance
 * @param {string} target - 'dir'|'all'|'everything'
 * @param {Object} buildConfig
 */
module.exports = function( grunt, target, buildConfig ) {

  assert && assert( target === 'dir' || target === 'all' || target === 'everything', 'Bad lint target: ' + target );
  var repositoryName = buildConfig.name;

  // --disable-eslint-cache disables the cache, useful for developing rules
  var cache = !grunt.option( 'disable-eslint-cache' );

  var cli = new CLIEngine( {

    // Rules are specified in the .eslintrc file
    configFile: '../chipper/eslint/.eslintrc',

    // Caching only checks changed files or when the list of rules is changed.  Changing the implementation of a
    // custom rule does not invalidate the cache.  Caches are declared in .eslintcache files in the directory where
    // grunt was run from.
    cache: cache,

    // Our custom rules live here
    rulePaths: [ '../chipper/eslint/rules' ],

    // Where to store the target-specific cache file
    cacheFile: '../chipper/eslint/cache/' + repositoryName + '-' + target + '.eslintcache',

    // Files to skip for linting
    ignorePattern: [
      '**/build',
      '**/node_modules',
      '../scenery/snapshots/**',
      '../sherpa/**',
      '../kite/js/parser/svgPath.js',
      '../phet-io-website/root/assets/js/ua-parser-0.7.12.min.js',
      '../phet-io-website/root/assets/js/jquery-1.12.3.min.js',
      '../phet-io-website/root/assets/highlight.js-9.1.0/highlight.pack.js',
      '../phet-io-website/root/assets/highlight.js-9.1.0/highlight.js',
      '../phet-io-website/root/assets/bootstrap-3.3.6-dist/js/npm.js',
      '../phet-io-website/root/assets/bootstrap-3.3.6-dist/js/bootstrap.min.js',
      '../phet-io-website/root/assets/bootstrap-3.3.6-dist/js/bootstrap.js',
      '../phet-io-website/root/assets/js/phet-io-ga.js'
    ]
  } );

  // Identify the repos to be linted
  var files = target === 'dir' ? [ repositoryName ] :
              target === 'all' ? buildConfig.phetLibs :
              grunt.file.read( '../chipper/data/active-repos' ).trim().split( /\r?\n/ );
  grunt.verbose.writeln( 'linting: ' + files );

  // Use the correct relative paths
  files = files.map( GET_PATH );

  // run the eslint step
  var report = cli.executeOnFiles( files );

  // pretty print results to console if any
  (report.warningCount || report.errorCount) && grunt.log.write( cli.getFormatter()( report.results ) );

  report.warningCount && grunt.fail.warn( report.warningCount + ' Lint Warnings' );
  report.errorCount && grunt.fail.fatal( report.errorCount + ' Lint Errors' );
};<commit_msg>Fixed path for kite linting, see https://github.com/phetsims/chipper/issues/565<commit_after>// Copyright 2015, University of Colorado Boulder

/**
 * Runs the lint rules on the specified files.
 *
 * @author Sam Reid (PhET Interactive Simulations)
 */
/* eslint-env node */
'use strict';

// modules
var eslint = require( 'eslint' );
var assert = require( 'assert' );

// constants
var CLIEngine = eslint.CLIEngine;

/**
 * Gets the relative path for the given repo.
 * @param {string} repo
 * @returns {string}
 */
var GET_PATH = function( repo ) { return '../' + repo; };

/**
 * @param grunt - the grunt instance
 * @param {string} target - 'dir'|'all'|'everything'
 * @param {Object} buildConfig
 */
module.exports = function( grunt, target, buildConfig ) {

  assert && assert( target === 'dir' || target === 'all' || target === 'everything', 'Bad lint target: ' + target );
  var repositoryName = buildConfig.name;

  // --disable-eslint-cache disables the cache, useful for developing rules
  var cache = !grunt.option( 'disable-eslint-cache' );

  var cli = new CLIEngine( {

    // Rules are specified in the .eslintrc file
    configFile: '../chipper/eslint/.eslintrc',

    // Caching only checks changed files or when the list of rules is changed.  Changing the implementation of a
    // custom rule does not invalidate the cache.  Caches are declared in .eslintcache files in the directory where
    // grunt was run from.
    cache: cache,

    // Our custom rules live here
    rulePaths: [ '../chipper/eslint/rules' ],

    // Where to store the target-specific cache file
    cacheFile: '../chipper/eslint/cache/' + repositoryName + '-' + target + '.eslintcache',

    // Files to skip for linting
    ignorePattern: [
      '**/build',
      '**/node_modules',
      '../scenery/snapshots/**',
      '../sherpa/**',
      '**/js/parser/svgPath.js',
      '../phet-io-website/root/assets/js/ua-parser-0.7.12.min.js',
      '../phet-io-website/root/assets/js/jquery-1.12.3.min.js',
      '../phet-io-website/root/assets/highlight.js-9.1.0/highlight.pack.js',
      '../phet-io-website/root/assets/highlight.js-9.1.0/highlight.js',
      '../phet-io-website/root/assets/bootstrap-3.3.6-dist/js/npm.js',
      '../phet-io-website/root/assets/bootstrap-3.3.6-dist/js/bootstrap.min.js',
      '../phet-io-website/root/assets/bootstrap-3.3.6-dist/js/bootstrap.js',
      '../phet-io-website/root/assets/js/phet-io-ga.js'
    ]
  } );

  // Identify the repos to be linted
  var files = target === 'dir' ? [ repositoryName ] :
              target === 'all' ? buildConfig.phetLibs :
              grunt.file.read( '../chipper/data/active-repos' ).trim().split( /\r?\n/ );
  grunt.verbose.writeln( 'linting: ' + files );

  // Use the correct relative paths
  files = files.map( GET_PATH );

  // run the eslint step
  var report = cli.executeOnFiles( files );

  // pretty print results to console if any
  (report.warningCount || report.errorCount) && grunt.log.write( cli.getFormatter()( report.results ) );

  report.warningCount && grunt.fail.warn( report.warningCount + ' Lint Warnings' );
  report.errorCount && grunt.fail.fatal( report.errorCount + ' Lint Errors' );
};<|endoftext|>


<commit_before>/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2016-2017 James Robinson
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

var hic = (function (hic) {

    var defaultPixelSize, defaultState;

    hic.createBrowser = function ($hic_container, config) {

        defaultPixelSize = 1;

        defaultState = new hic.State(1, 1, 0, 0, 0, defaultPixelSize, "NONE");

        var href = window.location.href,
            hicUrl = gup(href, "hicUrl"),
            stateString = gup(href, "state"),
            colorScale = gup(href, "colorScale");

        if (hicUrl) {
            config.url = decodeURIComponent(hicUrl);
        }
        if (stateString) {
            stateString = decodeURIComponent(stateString);
            config.state = hic.destringifyState(stateString);
            var tokens = stateString.split(",");
        }
        if(colorScale) {
            config.colorScale = parseFloat(colorScale);
        }

        return new hic.Browser($hic_container, config);
    };

    hic.Browser = function ($app_container, config) {

        var $root,
            $content_container;

        this.config = config;

        $root = $('
');
        $app_container.append($root);

        // navbar
        this.$navbar_container = $('
');
        $root.append(this.$navbar_container);

        // logo
        this.$navbar_container.append($('
'));

        $content_container = $('
');
        $root.append($content_container);

        this.$xAxis = xAxis();
        $content_container.append(this.$xAxis);
        this.xAxisRuler = new hic.Ruler(this, this.$xAxis.find('div'), 'x');

        this.$yAxis = yAxis();
        $content_container.append(this.$yAxis);
        this.yAxisRuler = new hic.Ruler(this, this.$yAxis.find('div'), 'y');

        // location box / goto
        this.locusGoto = new hic.LocusGoto(this);
        this.$navbar_container.append(this.locusGoto.$container);

        // colorscale widget
        this.colorscaleWidget = new hic.ColorScaleWidget(this);
        this.$navbar_container.append(this.colorscaleWidget.$container);

        // resolution widget
        this.normalizationSelector = new hic.NormalizationWidget(this);
        this.$navbar_container.append(this.normalizationSelector.$container);

        // resolution widget
        this.resolutionSelector = new hic.ResolutionSelector(this);
        this.$navbar_container.append(this.resolutionSelector.$container);

        this.contactMatrixView = new hic.ContactMatrixView(this);
        $content_container.append(this.contactMatrixView.$viewport_container);

        // this.sweepZoom = new hic.SweepZoom(this.contactMatrixView.$viewport);

        this.state = config.state ? config.state : defaultState.clone();

        if (config.colorScale && !isNaN(config.colorScale)) {
            this.contactMatrixView.colorScale.high = config.colorScale;
            this.contactMatrixView.computeColorScale = false;
        }

        if (config.url) {
            this.loadHicFile(config);
        }

        function xAxis() {
            var $x_axis,
                $e;

            $x_axis = $('
');
            $e = $('
');
            $x_axis.append($e);
            return $x_axis
        }

        function yAxis() {
            var $y_axis,
                $e;

            $y_axis = $('
');
            $e = $('
');
            $y_axis.append($e);
            return $y_axis

        }

        hic.GlobalEventBus.subscribe("LocusChange", this);
        hic.GlobalEventBus.subscribe("DragStopped", this);
        hic.GlobalEventBus.subscribe("DataLoad", this);
        hic.GlobalEventBus.subscribe("ColorScale", this);
    };

    hic.Browser.prototype.getColorScale = function () {
        var cs = this.contactMatrixView.colorScale;
        return cs;
    };

    hic.Browser.prototype.updateColorScale = function (high) {
        this.contactMatrixView.colorScale.high = high;
        this.contactMatrixView.imageTileCache = {};
        this.contactMatrixView.update();
        this.updateHref();
    };

    hic.Browser.prototype.loadHicFile = function (config) {

        var self = this;

        if (!config.url) {
            console.log("No .hic url specified");
            return;
        }

        if (config.url === this.url) {
            console.log(this.url + " already loaded");
            return;
        }

        self.url = config.url;

        this.hicReader = new hic.HiCReader(config);

        self.contactMatrixView.clearCaches();

        self.contactMatrixView.startSpinner();

        self.hicReader.loadDataset()

            .then(function (dataset) {

                self.contactMatrixView.stopSpinner();

                self.dataset = dataset;

                if (config.state) {
                    self.setState(config.state);
                }
                else {

                    // Don't be clever for now

                    // z = findDefaultZoom.call(
                    //     self,
                    //     self.bpResolutions,
                    //     defaultPixelSize,
                    //     self.chromosomes[defaultState.chr1].size);
                    //
                    // defaultState.zoom = z;

                    self.setState(defaultState.clone());
                    self.contactMatrixView.computeColorScale = true;
                }

                self.contactMatrixView.setDataset(dataset);

                hic.GlobalEventBus.post(hic.Event("DataLoad", dataset));

                if (config.colorScale) {
                    self.getColorScale().high = config.colorScale;
                }

            })
            .catch(function (error) {
                self.contactMatrixView.stopSpinner();
                console.log(error);
            });
    };

    function findDefaultZoom(bpResolutions, defaultPixelSize, chrLength) {

        var viewDimensions = this.contactMatrixView.getViewDimensions(),
            d = Math.max(viewDimensions.width, viewDimensions.height),
            nBins = d / defaultPixelSize,
            z;

        for (z = bpResolutions.length - 1; z >= 0; z--) {
            if (chrLength / bpResolutions[z] <= nBins) {
                return z;
            }
        }
        return 0;

    }

    hic.Browser.prototype.parseGotoInput = function (string) {

        var self = this,
            loci = string.split(' '),
            validLoci,
            bpp,
            xLocus,
            yLocus,
            maxExtent,
            targetResolution,
            newZoom,
            newPixelSize;

        if (loci.length !== 2) {
            console.log('ERROR. Must enter locus for x and y axes.');
        } else {

            xLocus = self.parseLocusString(loci[0]);
            yLocus = self.parseLocusString(loci[1]);

            if (xLocus === undefined || yLocus === undefined) {
                console.log('ERROR. Must enter valid loci for X and Y axes');
            }

            maxExtent = Math.max(locusExtent(xLocus), locusExtent(yLocus));
            targetResolution = maxExtent / (this.contactMatrixView.$viewport.width() / this.state.pixelSize);

            var bpResolutions = this.dataset.bpResolutions;
            newZoom = this.findMatchingZoomIndex(targetResolution, bpResolutions);
            newPixelSize = this.state.pixelSize;   // Adjusting this is complex

            this.setState(new hic.State(
                xLocus.chr,
                yLocus.chr,
                newZoom,
                xLocus.start / bpResolutions[this.state.zoom],
                yLocus.start / bpResolutions[this.state.zoom],
                newPixelSize
            ));

        }

        function locusExtent(obj) {
            return obj.end - obj.start;
        }

    };

    hic.Browser.prototype.findMatchingZoomIndex = function (targetResolution, resolutionArray) {
        var z;
        for (z = resolutionArray.length - 1; z > 0; z--) {
            if (resolutionArray[z] >= targetResolution) {
                return z;
            }
        }
        return 0;
    };

    hic.Browser.prototype.parseLocusString = function (locus) {

        var self = this,
            parts,
            chrName,
            extent,
            succeeded,
            chromosomeNames,
            locusObject = {},
            numeric;

        parts = locus.trim().split(':');

        chromosomeNames = _.map(self.dataset.chromosomes, function (chr) {
            return chr.name;
        });

        chrName = parts[0];

        if (!_.contains(chromosomeNames, chrName)) {
            return undefined;
        } else {
            locusObject.chr = _.indexOf(chromosomeNames, chrName);
        }

        if (parts.length === 1) {
            // Chromosome name only
            locusObject.start = 0;
            locusObject.end = this.dataset.chromosomes[locusObject.chr].size;
        } else {
            extent = parts[1].split("-");
            if (extent.length !== 2) {
                return undefined;
            }
            else {
                _.each(extent, function (value, index) {
                    var numeric = value.replace(/\,/g, '');
                    if (isNaN(numeric)) {
                        return undefined;
                    }
                    locusObject[0 === index ? 'start' : 'end'] = parseInt(numeric, 10);
                });
            }
        }
        return locusObject;
    };

    hic.Browser.prototype.setZoom = function (zoom) {

        if (zoom === this.state.zoom) return;

        this.contactMatrixView.clearCaches();
        this.contactMatrixView.computeColorScale = true;

        // Shift x,y to maintain center, if possible
        var bpResolutions = this.dataset.bpResolutions,
            viewDimensions = this.contactMatrixView.getViewDimensions(),
            n = viewDimensions.width / (2 * this.state.pixelSize),
            resRatio = bpResolutions[this.state.zoom] / bpResolutions[zoom];

        this.state.zoom = zoom;
        this.state.x = (this.state.x + n) * resRatio - n;
        this.state.y = (this.state.y + n) * resRatio - n;
        this.state.pixelSize = Math.max(defaultPixelSize, minPixelSize.call(this, this.state.chr1, this.state.chr2, zoom));

        this.clamp();

        hic.GlobalEventBus.post(hic.Event("LocusChange", this.state));
    };

    function minPixelSize(chr1, chr2, zoom) {
        var viewDimensions = this.contactMatrixView.getViewDimensions(),
            chr1Length = this.dataset.chromosomes[chr1].size,
            chr2Length = this.dataset.chromosomes[chr2].size,
            binSize = this.dataset.bpResolutions[zoom];
        return Math.max(viewDimensions.width * binSize / chr1Length, viewDimensions.width * binSize / chr2Length);
    }

    hic.Browser.prototype.update = function () {
        hic.GlobalEventBus.post(hic.Event("LocusChange", this.state));
    };

    /**
     * Set the matrix state.  Used ot restore state from a bookmark
     * @param state  browser state
     */
    hic.Browser.prototype.setState = function (state) {

        this.state = state;

        // Possibly adjust pixel size
        this.state.pixelSize = Math.max(state.pixelSize, minPixelSize.call(this, this.state.chr1, this.state.chr2, this.state.zoom));

        hic.GlobalEventBus.post(hic.Event("LocusChange", this.state));

    };

    hic.Browser.prototype.setNormalization = function (normalization) {

        this.state.normalization = normalization;

        hic.GlobalEventBus.post(hic.Event("NormalizationChange", this.state.normalization))

    }

    hic.Browser.prototype.shiftPixels = function (dx, dy) {

        this.state.x += dx;
        this.state.y += dy;
        this.clamp();

        var locusChangeEvent = hic.Event("LocusChange", this.state);
        locusChangeEvent.dragging = true;
        hic.GlobalEventBus.post(locusChangeEvent);
    };

    hic.Browser.prototype.goto = function (bpX, bpXMax, bpY, bpYMax) {

        var viewDimensions, targetResolution, newZoom, actualResolution, pixelSize, binX, binY, currentState, newState;

        viewDimensions = this.contactMatrixView.getViewDimensions();
        targetResolution = (bpXMax - bpX) / viewDimensions.width;
        newZoom = this.findMatchingZoomIndex(targetResolution, this.dataset.bpResolutions);
        actualResolution = this.dataset.bpResolutions[newZoom];
        pixelSize = actualResolution / targetResolution;
        binX = bpX / actualResolution;
        binY = bpY / actualResolution;
        currentState = this.state;
        newState = new hic.State(currentState.chr1, currentState.chr2, newZoom, binX, binY, pixelSize);

        this.state = newState;
        this.contactMatrixView.clearCaches();
        this.contactMatrixView.computeColorScale = true;

        hic.GlobalEventBus.post(hic.Event("LocusChange", this.state));

    }

    hic.Browser.prototype.clamp = function () {
        var viewDimensions = this.contactMatrixView.getViewDimensions(),
            chr1Length = this.dataset.chromosomes[this.state.chr1].size,
            chr2Length = this.dataset.chromosomes[this.state.chr2].size,
            binSize = this.dataset.bpResolutions[this.state.zoom],
            maxX = (chr1Length / binSize) - (viewDimensions.width / this.state.pixelSize),
            maxY = (chr2Length / binSize) - (viewDimensions.height / this.state.pixelSize);

        // Negative maxX, maxY indicates pixelSize is not enough to fill view.  In this case we clamp x, y to 0,0
        maxX = Math.max(0, maxX);
        maxY = Math.max(0, maxY);

        this.state.x = Math.min(Math.max(0, this.state.x), maxX);
        this.state.y = Math.min(Math.max(0, this.state.y), maxY);
    };

    hic.Browser.prototype.receiveEvent = function (event) {

        if (event.dragging) return;

        this.updateHref(event);
    };

    hic.Browser.prototype.updateHref = function (event) {
        var location = window.location,
            href = location.href;

        var href = window.location.href;

        if (event && event.type === "DataLoad") {
            href = replaceURIParameter("hicUrl", this.url, href);
        }

        href = replaceURIParameter("colorScale", "" + this.contactMatrixView.colorScale.high, href);

        window.history.replaceState("", "juicebox", href);
    };

    hic.Browser.prototype.resolution = function () {
        return this.dataset.bpResolutions[this.state.zoom];
    };

    function gup(href, name) {
        name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
        var regexS = "[\\?&]" + name + "=([^&#]*)";
        var regex = new RegExp(regexS);
        var results = regex.exec(href);
        if (results == null)
            return undefined;
        else
            return results[1];
    }

    function replaceURIParameter(key, newValue, href) {

        var oldValue = gup(href, key);
        if (oldValue) {
            href = href.replace(key + "=" + oldValue, key + "=" + encodeURIComponent(newValue));
        }
        else {
            var delim = href.includes("?") ? "&" : "?";
            href += delim + key + "=" + encodeURIComponent(newValue);
        }

        return href;

    }

    hic.State = function (chr1, chr2, zoom, x, y, pixelSize) {

        this.chr1 = chr1;
        this.chr2 = chr2;
        this.zoom = zoom;
        this.x = x;
        this.y = y;
        this.pixelSize = pixelSize;
    };

    return hic;

})
(hic || {});
<commit_msg>Bug fix -- normalization option forgotten after sweep-zoom<commit_after>/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2016-2017 James Robinson
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

var hic = (function (hic) {

    var defaultPixelSize, defaultState;

    hic.createBrowser = function ($hic_container, config) {

        defaultPixelSize = 1;

        defaultState = new hic.State(1, 1, 0, 0, 0, defaultPixelSize, "NONE");

        var href = window.location.href,
            hicUrl = gup(href, "hicUrl"),
            stateString = gup(href, "state"),
            colorScale = gup(href, "colorScale");

        if (hicUrl) {
            config.url = decodeURIComponent(hicUrl);
        }
        if (stateString) {
            stateString = decodeURIComponent(stateString);
            config.state = hic.destringifyState(stateString);
            var tokens = stateString.split(",");
        }
        if(colorScale) {
            config.colorScale = parseFloat(colorScale);
        }

        return new hic.Browser($hic_container, config);
    };

    hic.Browser = function ($app_container, config) {

        var $root,
            $content_container;

        this.config = config;

        $root = $('
');
        $app_container.append($root);

        // navbar
        this.$navbar_container = $('
');
        $root.append(this.$navbar_container);

        // logo
        this.$navbar_container.append($('
'));

        $content_container = $('
');
        $root.append($content_container);

        this.$xAxis = xAxis();
        $content_container.append(this.$xAxis);
        this.xAxisRuler = new hic.Ruler(this, this.$xAxis.find('div'), 'x');

        this.$yAxis = yAxis();
        $content_container.append(this.$yAxis);
        this.yAxisRuler = new hic.Ruler(this, this.$yAxis.find('div'), 'y');

        // location box / goto
        this.locusGoto = new hic.LocusGoto(this);
        this.$navbar_container.append(this.locusGoto.$container);

        // colorscale widget
        this.colorscaleWidget = new hic.ColorScaleWidget(this);
        this.$navbar_container.append(this.colorscaleWidget.$container);

        // resolution widget
        this.normalizationSelector = new hic.NormalizationWidget(this);
        this.$navbar_container.append(this.normalizationSelector.$container);

        // resolution widget
        this.resolutionSelector = new hic.ResolutionSelector(this);
        this.$navbar_container.append(this.resolutionSelector.$container);

        this.contactMatrixView = new hic.ContactMatrixView(this);
        $content_container.append(this.contactMatrixView.$viewport_container);

        // this.sweepZoom = new hic.SweepZoom(this.contactMatrixView.$viewport);

        this.state = config.state ? config.state : defaultState.clone();

        if (config.colorScale && !isNaN(config.colorScale)) {
            this.contactMatrixView.colorScale.high = config.colorScale;
            this.contactMatrixView.computeColorScale = false;
        }

        if (config.url) {
            this.loadHicFile(config);
        }

        function xAxis() {
            var $x_axis,
                $e;

            $x_axis = $('
');
            $e = $('
');
            $x_axis.append($e);
            return $x_axis
        }

        function yAxis() {
            var $y_axis,
                $e;

            $y_axis = $('
');
            $e = $('
');
            $y_axis.append($e);
            return $y_axis

        }

        hic.GlobalEventBus.subscribe("LocusChange", this);
        hic.GlobalEventBus.subscribe("DragStopped", this);
        hic.GlobalEventBus.subscribe("DataLoad", this);
        hic.GlobalEventBus.subscribe("ColorScale", this);
    };

    hic.Browser.prototype.getColorScale = function () {
        var cs = this.contactMatrixView.colorScale;
        return cs;
    };

    hic.Browser.prototype.updateColorScale = function (high) {
        this.contactMatrixView.colorScale.high = high;
        this.contactMatrixView.imageTileCache = {};
        this.contactMatrixView.update();
        this.updateHref();
    };

    hic.Browser.prototype.loadHicFile = function (config) {

        var self = this;

        if (!config.url) {
            console.log("No .hic url specified");
            return;
        }

        if (config.url === this.url) {
            console.log(this.url + " already loaded");
            return;
        }

        self.url = config.url;

        this.hicReader = new hic.HiCReader(config);

        self.contactMatrixView.clearCaches();

        self.contactMatrixView.startSpinner();

        self.hicReader.loadDataset()

            .then(function (dataset) {

                self.contactMatrixView.stopSpinner();

                self.dataset = dataset;

                if (config.state) {
                    self.setState(config.state);
                }
                else {

                    // Don't be clever for now

                    // z = findDefaultZoom.call(
                    //     self,
                    //     self.bpResolutions,
                    //     defaultPixelSize,
                    //     self.chromosomes[defaultState.chr1].size);
                    //
                    // defaultState.zoom = z;

                    self.setState(defaultState.clone());
                    self.contactMatrixView.computeColorScale = true;
                }

                self.contactMatrixView.setDataset(dataset);

                hic.GlobalEventBus.post(hic.Event("DataLoad", dataset));

                if (config.colorScale) {
                    self.getColorScale().high = config.colorScale;
                }

            })
            .catch(function (error) {
                self.contactMatrixView.stopSpinner();
                console.log(error);
            });
    };

    function findDefaultZoom(bpResolutions, defaultPixelSize, chrLength) {

        var viewDimensions = this.contactMatrixView.getViewDimensions(),
            d = Math.max(viewDimensions.width, viewDimensions.height),
            nBins = d / defaultPixelSize,
            z;

        for (z = bpResolutions.length - 1; z >= 0; z--) {
            if (chrLength / bpResolutions[z] <= nBins) {
                return z;
            }
        }
        return 0;

    }

    hic.Browser.prototype.parseGotoInput = function (string) {

        var self = this,
            loci = string.split(' '),
            validLoci,
            bpp,
            xLocus,
            yLocus,
            maxExtent,
            targetResolution,
            newZoom,
            newPixelSize;

        if (loci.length !== 2) {
            console.log('ERROR. Must enter locus for x and y axes.');
        } else {

            xLocus = self.parseLocusString(loci[0]);
            yLocus = self.parseLocusString(loci[1]);

            if (xLocus === undefined || yLocus === undefined) {
                console.log('ERROR. Must enter valid loci for X and Y axes');
            }

            maxExtent = Math.max(locusExtent(xLocus), locusExtent(yLocus));
            targetResolution = maxExtent / (this.contactMatrixView.$viewport.width() / this.state.pixelSize);

            var bpResolutions = this.dataset.bpResolutions;
            newZoom = this.findMatchingZoomIndex(targetResolution, bpResolutions);
            newPixelSize = this.state.pixelSize;   // Adjusting this is complex

            this.setState(new hic.State(
                xLocus.chr,
                yLocus.chr,
                newZoom,
                xLocus.start / bpResolutions[this.state.zoom],
                yLocus.start / bpResolutions[this.state.zoom],
                newPixelSize
            ));

        }

        function locusExtent(obj) {
            return obj.end - obj.start;
        }

    };

    hic.Browser.prototype.findMatchingZoomIndex = function (targetResolution, resolutionArray) {
        var z;
        for (z = resolutionArray.length - 1; z > 0; z--) {
            if (resolutionArray[z] >= targetResolution) {
                return z;
            }
        }
        return 0;
    };

    hic.Browser.prototype.parseLocusString = function (locus) {

        var self = this,
            parts,
            chrName,
            extent,
            succeeded,
            chromosomeNames,
            locusObject = {},
            numeric;

        parts = locus.trim().split(':');

        chromosomeNames = _.map(self.dataset.chromosomes, function (chr) {
            return chr.name;
        });

        chrName = parts[0];

        if (!_.contains(chromosomeNames, chrName)) {
            return undefined;
        } else {
            locusObject.chr = _.indexOf(chromosomeNames, chrName);
        }

        if (parts.length === 1) {
            // Chromosome name only
            locusObject.start = 0;
            locusObject.end = this.dataset.chromosomes[locusObject.chr].size;
        } else {
            extent = parts[1].split("-");
            if (extent.length !== 2) {
                return undefined;
            }
            else {
                _.each(extent, function (value, index) {
                    var numeric = value.replace(/\,/g, '');
                    if (isNaN(numeric)) {
                        return undefined;
                    }
                    locusObject[0 === index ? 'start' : 'end'] = parseInt(numeric, 10);
                });
            }
        }
        return locusObject;
    };

    hic.Browser.prototype.setZoom = function (zoom) {

        if (zoom === this.state.zoom) return;

        this.contactMatrixView.clearCaches();
        this.contactMatrixView.computeColorScale = true;

        // Shift x,y to maintain center, if possible
        var bpResolutions = this.dataset.bpResolutions,
            viewDimensions = this.contactMatrixView.getViewDimensions(),
            n = viewDimensions.width / (2 * this.state.pixelSize),
            resRatio = bpResolutions[this.state.zoom] / bpResolutions[zoom];

        this.state.zoom = zoom;
        this.state.x = (this.state.x + n) * resRatio - n;
        this.state.y = (this.state.y + n) * resRatio - n;
        this.state.pixelSize = Math.max(defaultPixelSize, minPixelSize.call(this, this.state.chr1, this.state.chr2, zoom));

        this.clamp();

        hic.GlobalEventBus.post(hic.Event("LocusChange", this.state));
    };

    function minPixelSize(chr1, chr2, zoom) {
        var viewDimensions = this.contactMatrixView.getViewDimensions(),
            chr1Length = this.dataset.chromosomes[chr1].size,
            chr2Length = this.dataset.chromosomes[chr2].size,
            binSize = this.dataset.bpResolutions[zoom];
        return Math.max(viewDimensions.width * binSize / chr1Length, viewDimensions.width * binSize / chr2Length);
    }

    hic.Browser.prototype.update = function () {
        hic.GlobalEventBus.post(hic.Event("LocusChange", this.state));
    };

    /**
     * Set the matrix state.  Used ot restore state from a bookmark
     * @param state  browser state
     */
    hic.Browser.prototype.setState = function (state) {

        this.state = state;

        // Possibly adjust pixel size
        this.state.pixelSize = Math.max(state.pixelSize, minPixelSize.call(this, this.state.chr1, this.state.chr2, this.state.zoom));

        hic.GlobalEventBus.post(hic.Event("LocusChange", this.state));

    };

    hic.Browser.prototype.setNormalization = function (normalization) {

        this.state.normalization = normalization;

        hic.GlobalEventBus.post(hic.Event("NormalizationChange", this.state.normalization))

    }

    hic.Browser.prototype.shiftPixels = function (dx, dy) {

        this.state.x += dx;
        this.state.y += dy;
        this.clamp();

        var locusChangeEvent = hic.Event("LocusChange", this.state);
        locusChangeEvent.dragging = true;
        hic.GlobalEventBus.post(locusChangeEvent);
    };

    hic.Browser.prototype.goto = function (bpX, bpXMax, bpY, bpYMax) {

        var viewDimensions, targetResolution, newZoom, actualResolution, pixelSize, binX, binY, currentState, newState;

        viewDimensions = this.contactMatrixView.getViewDimensions();
        targetResolution = (bpXMax - bpX) / viewDimensions.width;
        newZoom = this.findMatchingZoomIndex(targetResolution, this.dataset.bpResolutions);
        actualResolution = this.dataset.bpResolutions[newZoom];
        pixelSize = actualResolution / targetResolution;
        binX = bpX / actualResolution;
        binY = bpY / actualResolution;
        currentState = this.state;
        newState = new hic.State(currentState.chr1, currentState.chr2, newZoom, binX, binY, pixelSize, currentState.normalization);

        this.state = newState;
        this.contactMatrixView.clearCaches();
        this.contactMatrixView.computeColorScale = true;

        hic.GlobalEventBus.post(hic.Event("LocusChange", this.state));

    }

    hic.Browser.prototype.clamp = function () {
        var viewDimensions = this.contactMatrixView.getViewDimensions(),
            chr1Length = this.dataset.chromosomes[this.state.chr1].size,
            chr2Length = this.dataset.chromosomes[this.state.chr2].size,
            binSize = this.dataset.bpResolutions[this.state.zoom],
            maxX = (chr1Length / binSize) - (viewDimensions.width / this.state.pixelSize),
            maxY = (chr2Length / binSize) - (viewDimensions.height / this.state.pixelSize);

        // Negative maxX, maxY indicates pixelSize is not enough to fill view.  In this case we clamp x, y to 0,0
        maxX = Math.max(0, maxX);
        maxY = Math.max(0, maxY);

        this.state.x = Math.min(Math.max(0, this.state.x), maxX);
        this.state.y = Math.min(Math.max(0, this.state.y), maxY);
    };

    hic.Browser.prototype.receiveEvent = function (event) {

        if (event.dragging) return;

        this.updateHref(event);
    };

    hic.Browser.prototype.updateHref = function (event) {
        var location = window.location,
            href = location.href;

        var href = window.location.href;

        if (event && event.type === "DataLoad") {
            href = replaceURIParameter("hicUrl", this.url, href);
        }

        href = replaceURIParameter("colorScale", "" + this.contactMatrixView.colorScale.high, href);

        window.history.replaceState("", "juicebox", href);
    };

    hic.Browser.prototype.resolution = function () {
        return this.dataset.bpResolutions[this.state.zoom];
    };

    function gup(href, name) {
        name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
        var regexS = "[\\?&]" + name + "=([^&#]*)";
        var regex = new RegExp(regexS);
        var results = regex.exec(href);
        if (results == null)
            return undefined;
        else
            return results[1];
    }

    function replaceURIParameter(key, newValue, href) {

        var oldValue = gup(href, key);
        if (oldValue) {
            href = href.replace(key + "=" + oldValue, key + "=" + encodeURIComponent(newValue));
        }
        else {
            var delim = href.includes("?") ? "&" : "?";
            href += delim + key + "=" + encodeURIComponent(newValue);
        }

        return href;

    }

    hic.State = function (chr1, chr2, zoom, x, y, pixelSize) {

        this.chr1 = chr1;
        this.chr2 = chr2;
        this.zoom = zoom;
        this.x = x;
        this.y = y;
        this.pixelSize = pixelSize;
    };

    return hic;

})
(hic || {});
<|endoftext|>